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. *
  173. * Google Image Layout v0.0.1
  174. * Description, by Anh Trinh.
  175. * Heavily modified for searx
  176. * https://ptgamr.github.io/2014-09-12-google-image-layout/
  177. * https://ptgamr.github.io/google-image-layout/src/google-image-layout.js
  178. *
  179. * @license Free to use under the MIT License.
  180. *
  181. * @example <caption>Example usage of searxng.ImageLayout class.</caption>
  182. * searxng.image_thumbnail_layout = new searxng.ImageLayout(
  183. * '#urls', // container_selector
  184. * '#urls .result-images', // results_selector
  185. * 'img.image_thumbnail', // img_selector
  186. * 14, // verticalMargin
  187. * 6, // horizontalMargin
  188. * 200 // maxHeight
  189. * );
  190. * searxng.image_thumbnail_layout.watch();
  191. */
  192. (function (w, d) {
  193. function ImageLayout (container_selector, results_selector, img_selector, verticalMargin, horizontalMargin, maxHeight) {
  194. this.container_selector = container_selector;
  195. this.results_selector = results_selector;
  196. this.img_selector = img_selector;
  197. this.verticalMargin = verticalMargin;
  198. this.horizontalMargin = horizontalMargin;
  199. this.maxHeight = maxHeight;
  200. this.trottleCallToAlign = null;
  201. this.alignAfterThrotteling = false;
  202. }
  203. /**
  204. * Get the height that make all images fit the container
  205. *
  206. * width = w1 + w2 + w3 + ... = r1*h + r2*h + r3*h + ...
  207. *
  208. * @param {[type]} images the images to be calculated
  209. * @param {[type]} width the container witdth
  210. * @param {[type]} margin the margin between each image
  211. *
  212. * @return {[type]} the height
  213. */
  214. ImageLayout.prototype._getHeigth = function (images, width) {
  215. var i, img;
  216. var r = 0;
  217. for (i = 0; i < images.length; i++) {
  218. img = images[i];
  219. if ((img.naturalWidth > 0) && (img.naturalHeight > 0)) {
  220. r += img.naturalWidth / img.naturalHeight;
  221. } else {
  222. // assume that not loaded images are square
  223. r += 1;
  224. }
  225. }
  226. return (width - images.length * this.verticalMargin) / r; // have to round down because Firefox will automatically roundup value with number of decimals > 3
  227. };
  228. ImageLayout.prototype._setSize = function (images, height) {
  229. var i, img, imgWidth;
  230. var imagesLength = images.length, resultNode;
  231. for (i = 0; i < imagesLength; i++) {
  232. img = images[i];
  233. if ((img.naturalWidth > 0) && (img.naturalHeight > 0)) {
  234. imgWidth = height * img.naturalWidth / img.naturalHeight;
  235. } else {
  236. // not loaded image : make it square as _getHeigth said it
  237. imgWidth = height;
  238. }
  239. img.setAttribute('width', Math.round(imgWidth));
  240. img.setAttribute('height', Math.round(height));
  241. img.style.marginLeft = Math.round(this.horizontalMargin) + 'px';
  242. img.style.marginTop = Math.round(this.horizontalMargin) + 'px';
  243. img.style.marginRight = Math.round(this.verticalMargin - 7) + 'px'; // -4 is the negative margin of the inline element
  244. img.style.marginBottom = Math.round(this.verticalMargin - 7) + 'px';
  245. resultNode = img.parentNode.parentNode;
  246. if (!resultNode.classList.contains('js')) {
  247. resultNode.classList.add('js');
  248. }
  249. }
  250. };
  251. ImageLayout.prototype._alignImgs = function (imgGroup) {
  252. var isSearching, slice, i, h;
  253. var containerElement = d.querySelector(this.container_selector);
  254. var containerCompStyles = window.getComputedStyle(containerElement);
  255. var containerPaddingLeft = parseInt(containerCompStyles.getPropertyValue('padding-left'), 10);
  256. var containerPaddingRight = parseInt(containerCompStyles.getPropertyValue('padding-right'), 10);
  257. var containerWidth = containerElement.clientWidth - containerPaddingLeft - containerPaddingRight;
  258. while (imgGroup.length > 0) {
  259. isSearching = true;
  260. for (i = 1; i <= imgGroup.length && isSearching; i++) {
  261. slice = imgGroup.slice(0, i);
  262. h = this._getHeigth(slice, containerWidth);
  263. if (h < this.maxHeight) {
  264. this._setSize(slice, h);
  265. // continue with the remaining images
  266. imgGroup = imgGroup.slice(i);
  267. isSearching = false;
  268. }
  269. }
  270. if (isSearching) {
  271. this._setSize(slice, Math.min(this.maxHeight, h));
  272. break;
  273. }
  274. }
  275. };
  276. ImageLayout.prototype.throttleAlign = function () {
  277. var obj = this;
  278. if (obj.trottleCallToAlign) {
  279. obj.alignAfterThrotteling = true;
  280. } else {
  281. obj.alignAfterThrotteling = false;
  282. obj.align();
  283. obj.trottleCallToAlign = setTimeout(function () {
  284. if (obj.alignAfterThrotteling) {
  285. obj.align();
  286. }
  287. obj.alignAfterThrotteling = false;
  288. obj.trottleCallToAlign = null;
  289. }, 20);
  290. }
  291. };
  292. ImageLayout.prototype.align = function () {
  293. var i;
  294. var results_selectorNode = d.querySelectorAll(this.results_selector);
  295. var results_length = results_selectorNode.length;
  296. var previous = null;
  297. var current = null;
  298. var imgGroup = [];
  299. for (i = 0; i < results_length; i++) {
  300. current = results_selectorNode[i];
  301. if (current.previousElementSibling !== previous && imgGroup.length > 0) {
  302. // the current image is not connected to previous one
  303. // so the current image is the start of a new group of images.
  304. // so call _alignImgs to align the current group
  305. this._alignImgs(imgGroup);
  306. // and start a new empty group of images
  307. imgGroup = [];
  308. }
  309. // add the current image to the group (only the img tag)
  310. imgGroup.push(current.querySelector(this.img_selector));
  311. // update the previous variable
  312. previous = current;
  313. }
  314. // align the remaining images
  315. if (imgGroup.length > 0) {
  316. this._alignImgs(imgGroup);
  317. }
  318. };
  319. ImageLayout.prototype._monitorImages = function () {
  320. var i, img;
  321. var objthrottleAlign = this.throttleAlign.bind(this);
  322. var results_nodes = d.querySelectorAll(this.results_selector);
  323. var results_length = results_nodes.length;
  324. function img_load_error (event) {
  325. // console.log("ERROR can't load: " + event.originalTarget.src);
  326. event.originalTarget.src = w.searxng.static_path + w.searxng.theme.img_load_error;
  327. }
  328. for (i = 0; i < results_length; i++) {
  329. img = results_nodes[i].querySelector(this.img_selector);
  330. if (img !== null && img !== undefined && !img.classList.contains('aligned')) {
  331. img.addEventListener('load', objthrottleAlign);
  332. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror
  333. img.addEventListener('error', objthrottleAlign);
  334. img.addEventListener('timeout', objthrottleAlign);
  335. if (w.searxng.theme.img_load_error) {
  336. img.addEventListener('error', img_load_error, {once: true});
  337. }
  338. img.classList.add('aligned');
  339. }
  340. }
  341. };
  342. ImageLayout.prototype.watch = function () {
  343. var objthrottleAlign = this.throttleAlign.bind(this);
  344. // https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event
  345. w.addEventListener('pageshow', objthrottleAlign);
  346. // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/load_event
  347. w.addEventListener('load', objthrottleAlign);
  348. // https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event
  349. w.addEventListener('resize', objthrottleAlign);
  350. this._monitorImages();
  351. var obj = this;
  352. let observer = new MutationObserver(entries => {
  353. let newElement = false;
  354. for (let i = 0; i < entries.length; i++) {
  355. if (entries[i].addedNodes.length > 0 && entries[i].addedNodes[0].classList.contains('result')) {
  356. newElement = true;
  357. break;
  358. }
  359. }
  360. if (newElement) {
  361. obj._monitorImages();
  362. }
  363. });
  364. observer.observe(d.querySelector(this.container_selector), {
  365. childList: true,
  366. subtree: true,
  367. attributes: false,
  368. characterData: false,
  369. });
  370. };
  371. w.searxng.ImageLayout = ImageLayout;
  372. }(window, document));
  373. ;/**
  374. * @license
  375. * (C) Copyright Contributors to the SearXNG project.
  376. * (C) Copyright Contributors to the searx project (2014 - 2021).
  377. * SPDX-License-Identifier: AGPL-3.0-or-later
  378. */
  379. $(document).ready(function() {
  380. function hasScrollbar() {
  381. var root = document.compatMode=='BackCompat'? document.body : document.documentElement;
  382. return root.scrollHeight>root.clientHeight;
  383. }
  384. function loadNextPage() {
  385. var formData = $('#pagination form:last').serialize();
  386. if (formData) {
  387. $('#pagination').html('<div class="loading-spinner"></div>');
  388. $.ajax({
  389. type: "POST",
  390. url: $('#search_form').prop('action'),
  391. data: formData,
  392. dataType: 'html',
  393. success: function(data) {
  394. var body = $(data);
  395. $('#pagination').remove();
  396. $('#main_results').append('<hr/>');
  397. $('#main_results').append(body.find('.result'));
  398. $('#main_results').append(body.find('#pagination'));
  399. if(!hasScrollbar()) {
  400. loadNextPage();
  401. }
  402. }
  403. });
  404. }
  405. }
  406. if (searxng.infinite_scroll) {
  407. var win = $(window);
  408. $("html").addClass('infinite_scroll');
  409. if(!hasScrollbar()) {
  410. loadNextPage();
  411. }
  412. win.on('scroll', function() {
  413. if ($(document).height() - win.height() - win.scrollTop() < 150) {
  414. loadNextPage();
  415. }
  416. });
  417. }
  418. });
  419. ;/**
  420. * @license
  421. * (C) Copyright Contributors to the SearXNG project.
  422. * (C) Copyright Contributors to the searx project (2014 - 2021).
  423. * SPDX-License-Identifier: AGPL-3.0-or-later
  424. */
  425. window.addEventListener('load', function() {
  426. // Hide infobox toggle if shrunk size already fits all content.
  427. $('.infobox').each(function() {
  428. var infobox_body = $(this).find('.infobox_body');
  429. var total_height = infobox_body.prop('scrollHeight') + infobox_body.find('img.infobox_part').height();
  430. var max_height = infobox_body.css('max-height').replace('px', '');
  431. if (total_height <= max_height) {
  432. $(this).find('.infobox_toggle').hide();
  433. }
  434. });
  435. });
  436. ;/**
  437. * @license
  438. * (C) Copyright Contributors to the SearXNG project.
  439. * (C) Copyright Contributors to the searx project (2014 - 2021).
  440. * (C) 2014 by Thomas Pointhuber, <thomas.pointhuber@gmx.at>
  441. * SPDX-License-Identifier: AGPL-3.0-or-later
  442. */
  443. $(document).ready(function(){
  444. $(".searxng_init_map").on( "click", function( event ) {
  445. var leaflet_target = $(this).data('leaflet-target');
  446. var map_lon = $(this).data('map-lon');
  447. var map_lat = $(this).data('map-lat');
  448. var map_zoom = $(this).data('map-zoom');
  449. var map_boundingbox = $(this).data('map-boundingbox');
  450. var map_geojson = $(this).data('map-geojson');
  451. if(map_boundingbox) {
  452. southWest = L.latLng(map_boundingbox[0], map_boundingbox[2]);
  453. northEast = L.latLng(map_boundingbox[1], map_boundingbox[3]);
  454. map_bounds = L.latLngBounds(southWest, northEast);
  455. }
  456. // change default imagePath
  457. L.Icon.Default.imagePath = "./static/themes/oscar/css/images/";
  458. // init map
  459. var map = L.map(leaflet_target);
  460. // create the tile layer with correct attribution
  461. var osmMapnikUrl='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
  462. var osmMapnikAttrib='Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors';
  463. var osmMapnik = new L.TileLayer(osmMapnikUrl, {minZoom: 1, maxZoom: 19, attribution: osmMapnikAttrib});
  464. var osmWikimediaUrl='https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png';
  465. var osmWikimediaAttrib = 'Wikimedia maps beta | Maps data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors';
  466. var osmWikimedia = new L.TileLayer(osmWikimediaUrl, {minZoom: 1, maxZoom: 19, attribution: osmWikimediaAttrib});
  467. // init map view
  468. setTimeout(function() {
  469. if(map_bounds) {
  470. map.fitBounds(map_bounds, {
  471. maxZoom:17
  472. });
  473. } else if (map_lon && map_lat) {
  474. if(map_zoom)
  475. map.setView(new L.LatLng(map_lat, map_lon),map_zoom);
  476. else
  477. map.setView(new L.LatLng(map_lat, map_lon),8);
  478. }
  479. }, 0);
  480. map.addLayer(osmMapnik);
  481. var baseLayers = {
  482. "OSM Mapnik": osmMapnik/*,
  483. "OSM Wikimedia": osmWikimedia*/
  484. };
  485. L.control.layers(baseLayers).addTo(map);
  486. if(map_geojson)
  487. L.geoJson(map_geojson).addTo(map);
  488. /*else if(map_bounds)
  489. L.rectangle(map_bounds, {color: "#ff7800", weight: 3, fill:false}).addTo(map);*/
  490. // this event occour only once per element
  491. $( this ).off( event );
  492. });
  493. });
  494. ;/**
  495. * @license
  496. * (C) Copyright Contributors to the SearXNG project.
  497. * (C) Copyright Contributors to the searx project (2014 - 2021).
  498. * SPDX-License-Identifier: AGPL-3.0-or-later
  499. */
  500. $(document).ready(function(){
  501. let engine_descriptions = null;
  502. function load_engine_descriptions() {
  503. if (engine_descriptions == null) {
  504. $.ajax("engine_descriptions.json", dataType="json").done(function(data) {
  505. engine_descriptions = data;
  506. for (const [engine_name, description] of Object.entries(data)) {
  507. let elements = $('[data-engine-name="' + engine_name + '"] .description');
  508. for(const element of elements) {
  509. let source = ' (<i>' + searxng.translations.Source + ':&nbsp;' + description[1] + '</i>)';
  510. element.innerHTML = description[0] + source;
  511. }
  512. }
  513. });
  514. }
  515. }
  516. if (document.querySelector('body[class="preferences_endpoint"]')) {
  517. $('[data-engine-name]').hover(function() {
  518. load_engine_descriptions();
  519. });
  520. }
  521. });
  522. ;/**
  523. * @license
  524. * (C) Copyright Contributors to the SearXNG project.
  525. * (C) Copyright Contributors to the searx project (2014 - 2021).
  526. * SPDX-License-Identifier: AGPL-3.0-or-later
  527. */
  528. $(document).ready(function(){
  529. $("#allow-all-engines").click(function() {
  530. $(".onoffswitch-checkbox").each(function() { this.checked = false;});
  531. });
  532. $("#disable-all-engines").click(function() {
  533. $(".onoffswitch-checkbox").each(function() { this.checked = true;});
  534. });
  535. });