searxng.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. /**
  2. * @license
  3. * (C) Copyright Contributors to the SearXNG project.
  4. * (C) Copyright Contributors to the searx project (2014 - 2021).
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. window.searxng = (function(d) {
  8. 'use strict';
  9. //
  10. d.getElementsByTagName("html")[0].className = "js";
  11. // add data- properties
  12. var script = d.currentScript || (function() {
  13. var scripts = d.getElementsByTagName('script');
  14. return scripts[scripts.length - 1];
  15. })();
  16. return {
  17. autocompleter: script.getAttribute('data-autocompleter') === 'true',
  18. method: script.getAttribute('data-method'),
  19. translations: JSON.parse(script.getAttribute('data-translations'))
  20. };
  21. })(document);
  22. ;/**
  23. * @license
  24. * (C) Copyright Contributors to the SearXNG project.
  25. * (C) Copyright Contributors to the searx project (2014 - 2021).
  26. * (C) 2014 by Thomas Pointhuber, <thomas.pointhuber@gmx.at>
  27. * SPDX-License-Identifier: AGPL-3.0-or-later
  28. */
  29. $(document).ready(function(){
  30. var original_search_value = '';
  31. if(searxng.autocompleter) {
  32. var searchResults = new Bloodhound({
  33. datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  34. queryTokenizer: Bloodhound.tokenizers.whitespace,
  35. remote: {
  36. url: './autocompleter?q=%QUERY',
  37. wildcard: '%QUERY'
  38. }
  39. });
  40. searchResults.initialize();
  41. $("#q").on('keydown', function(e) {
  42. if(e.which == 13) {
  43. original_search_value = $('#q').val();
  44. }
  45. });
  46. $('#q').typeahead({
  47. name: 'search-results',
  48. highlight: false,
  49. hint: true,
  50. displayKey: function(result) {
  51. return result;
  52. },
  53. classNames: {
  54. input: 'tt-input',
  55. hint: 'tt-hint',
  56. menu: 'tt-dropdown-menu',
  57. dataset: 'tt-dataset-search-results',
  58. },
  59. }, {
  60. name: 'autocomplete',
  61. source: searchResults,
  62. });
  63. $('#q').bind('typeahead:select', function(ev, suggestion) {
  64. if(original_search_value) {
  65. $('#q').val(original_search_value);
  66. }
  67. $("#search_form").submit();
  68. });
  69. }
  70. });
  71. ;/**
  72. * @license
  73. * (C) Copyright Contributors to the SearXNG project.
  74. * (C) Copyright Contributors to the searx project (2014 - 2021).
  75. * (C) 2014 by Thomas Pointhuber, <thomas.pointhuber@gmx.at>
  76. * SPDX-License-Identifier: AGPL-3.0-or-later
  77. */
  78. $(document).ready(function(){
  79. /**
  80. * focus element if class="autofocus" and id="q"
  81. */
  82. $('#q.autofocus').focus();
  83. /**
  84. * Empty search bar when click on reset button
  85. */
  86. $("#clear_search").click(function () {
  87. document.getElementById("q").value = "";
  88. });
  89. /**
  90. * select full content on click if class="select-all-on-click"
  91. */
  92. $(".select-all-on-click").click(function () {
  93. $(this).select();
  94. });
  95. /**
  96. * change text during btn-collapse click if possible
  97. */
  98. $('.btn-collapse').click(function() {
  99. var btnTextCollapsed = $(this).data('btn-text-collapsed');
  100. var btnTextNotCollapsed = $(this).data('btn-text-not-collapsed');
  101. if(btnTextCollapsed !== '' && btnTextNotCollapsed !== '') {
  102. if($(this).hasClass('collapsed')) {
  103. new_html = $(this).html().replace(btnTextCollapsed, btnTextNotCollapsed);
  104. } else {
  105. new_html = $(this).html().replace(btnTextNotCollapsed, btnTextCollapsed);
  106. }
  107. $(this).html(new_html);
  108. }
  109. });
  110. /**
  111. * change text during btn-toggle click if possible
  112. */
  113. $('.btn-toggle .btn').click(function() {
  114. var btnClass = 'btn-' + $(this).data('btn-class');
  115. var btnLabelDefault = $(this).data('btn-label-default');
  116. var btnLabelToggled = $(this).data('btn-label-toggled');
  117. if(btnLabelToggled !== '') {
  118. if($(this).hasClass('btn-default')) {
  119. new_html = $(this).html().replace(btnLabelDefault, btnLabelToggled);
  120. } else {
  121. new_html = $(this).html().replace(btnLabelToggled, btnLabelDefault);
  122. }
  123. $(this).html(new_html);
  124. }
  125. $(this).toggleClass(btnClass);
  126. $(this).toggleClass('btn-default');
  127. });
  128. /**
  129. * change text during btn-toggle click if possible
  130. */
  131. $('.media-loader').click(function() {
  132. var target = $(this).data('target');
  133. var iframe_load = $(target + ' > iframe');
  134. var srctest = iframe_load.attr('src');
  135. if(srctest === undefined || srctest === false){
  136. iframe_load.attr('src', iframe_load.data('src'));
  137. }
  138. });
  139. /**
  140. * Select or deselect every categories on double clic
  141. */
  142. $(".btn-sm").dblclick(function() {
  143. var btnClass = 'btn-' + $(this).data('btn-class'); // primary
  144. if($(this).hasClass('btn-default')) {
  145. $(".btn-sm > input").attr('checked', 'checked');
  146. $(".btn-sm > input").prop("checked", true);
  147. $(".btn-sm").addClass(btnClass);
  148. $(".btn-sm").addClass('active');
  149. $(".btn-sm").removeClass('btn-default');
  150. } else {
  151. $(".btn-sm > input").attr('checked', '');
  152. $(".btn-sm > input").removeAttr('checked');
  153. $(".btn-sm > input").checked = false;
  154. $(".btn-sm").removeClass(btnClass);
  155. $(".btn-sm").removeClass('active');
  156. $(".btn-sm").addClass('btn-default');
  157. }
  158. });
  159. $(".nav-tabs").click(function(a) {
  160. var tabs = $(a.target).parents("ul");
  161. tabs.children().attr("aria-selected", "false");
  162. $(a.target).parent().attr("aria-selected", "true");
  163. });
  164. /**
  165. * Layout images according to their sizes
  166. */
  167. searxng.image_thumbnail_layout = new searxng.ImageLayout('#main_results', '#main_results .result-images', 'img.img-thumbnail', 15, 3, 200);
  168. searxng.image_thumbnail_layout.watch();
  169. });
  170. ;/**
  171. * @license
  172. * (C) Copyright Contributors to the SearXNG project.
  173. * (C) Copyright Contributors to the searx project (2014 - 2021).
  174. * SPDX-License-Identifier: AGPL-3.0-or-later
  175. */
  176. window.addEventListener('load', function() {
  177. // Hide infobox toggle if shrunk size already fits all content.
  178. $('.infobox').each(function() {
  179. var infobox_body = $(this).find('.infobox_body');
  180. var total_height = infobox_body.prop('scrollHeight') + infobox_body.find('img.infobox_part').height();
  181. var max_height = infobox_body.css('max-height').replace('px', '');
  182. if (total_height <= max_height) {
  183. $(this).find('.infobox_toggle').hide();
  184. }
  185. });
  186. });
  187. ;/**
  188. * @license
  189. * (C) Copyright Contributors to the SearXNG project.
  190. * (C) Copyright Contributors to the searx project (2014 - 2021).
  191. * (C) 2014 by Thomas Pointhuber, <thomas.pointhuber@gmx.at>
  192. * SPDX-License-Identifier: AGPL-3.0-or-later
  193. */
  194. $(document).ready(function(){
  195. $(".searxng_init_map").on( "click", function( event ) {
  196. var leaflet_target = $(this).data('leaflet-target');
  197. var map_lon = $(this).data('map-lon');
  198. var map_lat = $(this).data('map-lat');
  199. var map_zoom = $(this).data('map-zoom');
  200. var map_boundingbox = $(this).data('map-boundingbox');
  201. var map_geojson = $(this).data('map-geojson');
  202. if(map_boundingbox) {
  203. southWest = L.latLng(map_boundingbox[0], map_boundingbox[2]);
  204. northEast = L.latLng(map_boundingbox[1], map_boundingbox[3]);
  205. map_bounds = L.latLngBounds(southWest, northEast);
  206. }
  207. // change default imagePath
  208. L.Icon.Default.imagePath = "./static/themes/oscar/css/images/";
  209. // init map
  210. var map = L.map(leaflet_target);
  211. // create the tile layer with correct attribution
  212. var osmMapnikUrl='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
  213. var osmMapnikAttrib='Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors';
  214. var osmMapnik = new L.TileLayer(osmMapnikUrl, {minZoom: 1, maxZoom: 19, attribution: osmMapnikAttrib});
  215. var osmWikimediaUrl='https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png';
  216. var osmWikimediaAttrib = 'Wikimedia maps beta | Maps data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors';
  217. var osmWikimedia = new L.TileLayer(osmWikimediaUrl, {minZoom: 1, maxZoom: 19, attribution: osmWikimediaAttrib});
  218. // init map view
  219. setTimeout(function() {
  220. if(map_bounds) {
  221. map.fitBounds(map_bounds, {
  222. maxZoom:17
  223. });
  224. } else if (map_lon && map_lat) {
  225. if(map_zoom)
  226. map.setView(new L.LatLng(map_lat, map_lon),map_zoom);
  227. else
  228. map.setView(new L.LatLng(map_lat, map_lon),8);
  229. }
  230. }, 0);
  231. map.addLayer(osmMapnik);
  232. var baseLayers = {
  233. "OSM Mapnik": osmMapnik/*,
  234. "OSM Wikimedia": osmWikimedia*/
  235. };
  236. L.control.layers(baseLayers).addTo(map);
  237. if(map_geojson)
  238. L.geoJson(map_geojson).addTo(map);
  239. /*else if(map_bounds)
  240. L.rectangle(map_bounds, {color: "#ff7800", weight: 3, fill:false}).addTo(map);*/
  241. // this event occour only once per element
  242. $( this ).off( event );
  243. });
  244. });
  245. ;/**
  246. * @license
  247. * (C) Copyright Contributors to the SearXNG project.
  248. * (C) Copyright Contributors to the searx project (2014 - 2021).
  249. * SPDX-License-Identifier: AGPL-3.0-or-later
  250. */
  251. $(document).ready(function(){
  252. let engine_descriptions = null;
  253. function load_engine_descriptions() {
  254. if (engine_descriptions == null) {
  255. $.ajax("engine_descriptions.json", dataType="json").done(function(data) {
  256. engine_descriptions = data;
  257. for (const [engine_name, description] of Object.entries(data)) {
  258. let elements = $('[data-engine-name="' + engine_name + '"] .description');
  259. for(const element of elements) {
  260. let source = ' (<i>' + searxng.translations.Source + ':&nbsp;' + description[1] + '</i>)';
  261. element.innerHTML = description[0] + source;
  262. }
  263. }
  264. });
  265. }
  266. }
  267. if (document.querySelector('body[class="preferences_endpoint"]')) {
  268. $('[data-engine-name]').hover(function() {
  269. load_engine_descriptions();
  270. });
  271. }
  272. });
  273. ;/**
  274. * @license
  275. * (C) Copyright Contributors to the SearXNG project.
  276. * (C) Copyright Contributors to the searx project (2014 - 2021).
  277. * SPDX-License-Identifier: AGPL-3.0-or-later
  278. */
  279. $(document).ready(function(){
  280. $("#allow-all-engines").click(function() {
  281. $(".onoffswitch-checkbox").each(function() { this.checked = false;});
  282. });
  283. $("#disable-all-engines").click(function() {
  284. $(".onoffswitch-checkbox").each(function() { this.checked = true;});
  285. });
  286. });
  287. ;/**
  288. *
  289. * Google Image Layout v0.0.1
  290. * Description, by Anh Trinh.
  291. * Heavily modified for searx
  292. * https://ptgamr.github.io/2014-09-12-google-image-layout/
  293. * https://ptgamr.github.io/google-image-layout/src/google-image-layout.js
  294. *
  295. * @license Free to use under the MIT License.
  296. *
  297. * @example <caption>Example usage of searxng.ImageLayout class.</caption>
  298. * searxng.image_thumbnail_layout = new searxng.ImageLayout(
  299. * '#urls', // container_selector
  300. * '#urls .result-images', // results_selector
  301. * 'img.image_thumbnail', // img_selector
  302. * 14, // verticalMargin
  303. * 6, // horizontalMargin
  304. * 200 // maxHeight
  305. * );
  306. * searxng.image_thumbnail_layout.watch();
  307. */
  308. (function (w, d) {
  309. function ImageLayout(container_selector, results_selector, img_selector, verticalMargin, horizontalMargin, maxHeight) {
  310. this.container_selector = container_selector;
  311. this.results_selector = results_selector;
  312. this.img_selector = img_selector;
  313. this.verticalMargin = verticalMargin;
  314. this.horizontalMargin = horizontalMargin;
  315. this.maxHeight = maxHeight;
  316. this.isAlignDone = true;
  317. }
  318. /**
  319. * Get the height that make all images fit the container
  320. *
  321. * width = w1 + w2 + w3 + ... = r1*h + r2*h + r3*h + ...
  322. *
  323. * @param {[type]} images the images to be calculated
  324. * @param {[type]} width the container witdth
  325. * @param {[type]} margin the margin between each image
  326. *
  327. * @return {[type]} the height
  328. */
  329. ImageLayout.prototype._getHeigth = function (images, width) {
  330. var i, img;
  331. var r = 0;
  332. for (i = 0; i < images.length; i++) {
  333. img = images[i];
  334. if ((img.naturalWidth > 0) && (img.naturalHeight > 0)) {
  335. r += img.naturalWidth / img.naturalHeight;
  336. } else {
  337. // assume that not loaded images are square
  338. r += 1;
  339. }
  340. }
  341. return (width - images.length * this.verticalMargin) / r; //have to round down because Firefox will automatically roundup value with number of decimals > 3
  342. };
  343. ImageLayout.prototype._setSize = function (images, height) {
  344. var i, img, imgWidth;
  345. var imagesLength = images.length, resultNode;
  346. for (i = 0; i < imagesLength; i++) {
  347. img = images[i];
  348. if ((img.naturalWidth > 0) && (img.naturalHeight > 0)) {
  349. imgWidth = height * img.naturalWidth / img.naturalHeight;
  350. } else {
  351. // not loaded image : make it square as _getHeigth said it
  352. imgWidth = height;
  353. }
  354. img.style.width = imgWidth + 'px';
  355. img.style.height = height + 'px';
  356. img.style.marginLeft = this.horizontalMargin + 'px';
  357. img.style.marginTop = this.horizontalMargin + 'px';
  358. img.style.marginRight = this.verticalMargin - 7 + 'px'; // -4 is the negative margin of the inline element
  359. img.style.marginBottom = this.verticalMargin - 7 + 'px';
  360. resultNode = img.parentNode.parentNode;
  361. if (!resultNode.classList.contains('js')) {
  362. resultNode.classList.add('js');
  363. }
  364. }
  365. };
  366. ImageLayout.prototype._alignImgs = function (imgGroup) {
  367. var isSearching, slice, i, h;
  368. var containerElement = d.querySelector(this.container_selector);
  369. var containerCompStyles = window.getComputedStyle(containerElement);
  370. var containerPaddingLeft = parseInt(containerCompStyles.getPropertyValue('padding-left'), 10);
  371. var containerPaddingRight = parseInt(containerCompStyles.getPropertyValue('padding-right'), 10);
  372. var containerWidth = containerElement.clientWidth - containerPaddingLeft - containerPaddingRight;
  373. while (imgGroup.length > 0) {
  374. isSearching = true;
  375. for (i = 1; i <= imgGroup.length && isSearching; i++) {
  376. slice = imgGroup.slice(0, i);
  377. h = this._getHeigth(slice, containerWidth);
  378. if (h < this.maxHeight) {
  379. this._setSize(slice, h);
  380. // continue with the remaining images
  381. imgGroup = imgGroup.slice(i);
  382. isSearching = false;
  383. }
  384. }
  385. if (isSearching) {
  386. this._setSize(slice, Math.min(this.maxHeight, h));
  387. break;
  388. }
  389. }
  390. };
  391. ImageLayout.prototype.align = function () {
  392. var i;
  393. var results_selectorNode = d.querySelectorAll(this.results_selector);
  394. var results_length = results_selectorNode.length;
  395. var previous = null;
  396. var current = null;
  397. var imgGroup = [];
  398. for (i = 0; i < results_length; i++) {
  399. current = results_selectorNode[i];
  400. if (current.previousElementSibling !== previous && imgGroup.length > 0) {
  401. // the current image is not connected to previous one
  402. // so the current image is the start of a new group of images.
  403. // so call _alignImgs to align the current group
  404. this._alignImgs(imgGroup);
  405. // and start a new empty group of images
  406. imgGroup = [];
  407. }
  408. // add the current image to the group (only the img tag)
  409. imgGroup.push(current.querySelector(this.img_selector));
  410. // update the previous variable
  411. previous = current;
  412. }
  413. // align the remaining images
  414. if (imgGroup.length > 0) {
  415. this._alignImgs(imgGroup);
  416. }
  417. };
  418. ImageLayout.prototype.watch = function () {
  419. var i, img;
  420. var obj = this;
  421. var results_nodes = d.querySelectorAll(this.results_selector);
  422. var results_length = results_nodes.length;
  423. function img_load_error(event) {
  424. // console.log("ERROR can't load: " + event.originalTarget.src);
  425. event.originalTarget.src = w.searxng.static_path + w.searxng.theme.img_load_error;
  426. }
  427. function throttleAlign() {
  428. if (obj.isAlignDone) {
  429. obj.isAlignDone = false;
  430. setTimeout(function () {
  431. obj.align();
  432. obj.isAlignDone = true;
  433. }, 100);
  434. }
  435. }
  436. // https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event
  437. w.addEventListener('pageshow', throttleAlign);
  438. // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/load_event
  439. w.addEventListener('load', throttleAlign);
  440. // https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event
  441. w.addEventListener('resize', throttleAlign);
  442. for (i = 0; i < results_length; i++) {
  443. img = results_nodes[i].querySelector(this.img_selector);
  444. if (img !== null && img !== undefined) {
  445. img.addEventListener('load', throttleAlign);
  446. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror
  447. img.addEventListener('error', throttleAlign);
  448. if (w.searxng.theme.img_load_error) {
  449. img.addEventListener('error', img_load_error, {once: true});
  450. }
  451. }
  452. }
  453. };
  454. w.searxng.ImageLayout = ImageLayout;
  455. }(window, document));