searxng.js 20 KB

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