searxng.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  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(w, d) {
  8. 'use strict';
  9. // not invented here tookit with bugs fixed elsewhere
  10. // purposes : be just good enough and as small as possible
  11. // from https://plainjs.com/javascript/events/live-binding-event-handlers-14/
  12. if (w.Element) {
  13. (function(ElementPrototype) {
  14. ElementPrototype.matches = ElementPrototype.matches ||
  15. ElementPrototype.matchesSelector ||
  16. ElementPrototype.webkitMatchesSelector ||
  17. ElementPrototype.msMatchesSelector ||
  18. function(selector) {
  19. var node = this, nodes = (node.parentNode || node.document).querySelectorAll(selector), i = -1;
  20. while (nodes[++i] && nodes[i] != node);
  21. return !!nodes[i];
  22. };
  23. })(Element.prototype);
  24. }
  25. function callbackSafe(callback, el, e) {
  26. try {
  27. callback.call(el, e);
  28. } catch (exception) {
  29. console.log(exception);
  30. }
  31. }
  32. var searxng = window.searxng || {};
  33. searxng.on = function(obj, eventType, callback, useCapture) {
  34. useCapture = useCapture || false;
  35. if (typeof obj !== 'string') {
  36. // obj HTMLElement, HTMLDocument
  37. obj.addEventListener(eventType, callback, useCapture);
  38. } else {
  39. // obj is a selector
  40. d.addEventListener(eventType, function(e) {
  41. var el = e.target || e.srcElement, found = false;
  42. while (el && el.matches && el !== d && !(found = el.matches(obj))) el = el.parentElement;
  43. if (found) callbackSafe(callback, el, e);
  44. }, useCapture);
  45. }
  46. };
  47. searxng.ready = function(callback) {
  48. if (document.readyState != 'loading') {
  49. callback.call(w);
  50. } else {
  51. w.addEventListener('DOMContentLoaded', callback.bind(w));
  52. }
  53. };
  54. searxng.http = function(method, url) {
  55. var req = new XMLHttpRequest(),
  56. resolve = function() {},
  57. reject = function() {},
  58. promise = {
  59. then: function(callback) { resolve = callback; return promise; },
  60. catch: function(callback) { reject = callback; return promise; }
  61. };
  62. try {
  63. req.open(method, url, true);
  64. // On load
  65. req.onload = function() {
  66. if (req.status == 200) {
  67. resolve(req.response, req.responseType);
  68. } else {
  69. reject(Error(req.statusText));
  70. }
  71. };
  72. // Handle network errors
  73. req.onerror = function() {
  74. reject(Error("Network Error"));
  75. };
  76. req.onabort = function() {
  77. reject(Error("Transaction is aborted"));
  78. };
  79. // Make the request
  80. req.send();
  81. } catch (ex) {
  82. reject(ex);
  83. }
  84. return promise;
  85. };
  86. searxng.loadStyle = function(src) {
  87. var path = searxng.static_path + src,
  88. id = "style_" + src.replace('.', '_'),
  89. s = d.getElementById(id);
  90. if (s === null) {
  91. s = d.createElement('link');
  92. s.setAttribute('id', id);
  93. s.setAttribute('rel', 'stylesheet');
  94. s.setAttribute('type', 'text/css');
  95. s.setAttribute('href', path);
  96. d.body.appendChild(s);
  97. }
  98. };
  99. searxng.loadScript = function(src, callback) {
  100. var path = searxng.static_path + src,
  101. id = "script_" + src.replace('.', '_'),
  102. s = d.getElementById(id);
  103. if (s === null) {
  104. s = d.createElement('script');
  105. s.setAttribute('id', id);
  106. s.setAttribute('src', path);
  107. s.onload = callback;
  108. s.onerror = function() {
  109. s.setAttribute('error', '1');
  110. };
  111. d.body.appendChild(s);
  112. } else if (!s.hasAttribute('error')) {
  113. try {
  114. callback.apply(s, []);
  115. } catch (exception) {
  116. console.log(exception);
  117. }
  118. } else {
  119. console.log("callback not executed : script '" + path + "' not loaded.");
  120. }
  121. };
  122. searxng.insertBefore = function (newNode, referenceNode) {
  123. referenceNode.parentNode.insertBefore(newNode, referenceNode);
  124. };
  125. searxng.insertAfter = function(newNode, referenceNode) {
  126. referenceNode.parentNode.insertAfter(newNode, referenceNode.nextSibling);
  127. };
  128. searxng.on('.close', 'click', function() {
  129. this.parentNode.classList.add('invisible');
  130. });
  131. return searxng;
  132. })(window, document);
  133. ;/* SPDX-License-Identifier: AGPL-3.0-or-later */
  134. /*global searxng*/
  135. searxng.ready(function() {
  136. searxng.on('.result', 'click', function() {
  137. highlightResult(this)(true);
  138. });
  139. searxng.on('.result a', 'focus', function(e) {
  140. var el = e.target;
  141. while (el !== undefined) {
  142. if (el.classList.contains('result')) {
  143. if (el.getAttribute("data-vim-selected") === null) {
  144. highlightResult(el)(true);
  145. }
  146. break;
  147. }
  148. el = el.parentNode;
  149. }
  150. }, true);
  151. var vimKeys = {
  152. 27: {
  153. key: 'Escape',
  154. fun: removeFocus,
  155. des: 'remove focus from the focused input',
  156. cat: 'Control'
  157. },
  158. 73: {
  159. key: 'i',
  160. fun: searchInputFocus,
  161. des: 'focus on the search input',
  162. cat: 'Control'
  163. },
  164. 66: {
  165. key: 'b',
  166. fun: scrollPage(-window.innerHeight),
  167. des: 'scroll one page up',
  168. cat: 'Navigation'
  169. },
  170. 70: {
  171. key: 'f',
  172. fun: scrollPage(window.innerHeight),
  173. des: 'scroll one page down',
  174. cat: 'Navigation'
  175. },
  176. 85: {
  177. key: 'u',
  178. fun: scrollPage(-window.innerHeight / 2),
  179. des: 'scroll half a page up',
  180. cat: 'Navigation'
  181. },
  182. 68: {
  183. key: 'd',
  184. fun: scrollPage(window.innerHeight / 2),
  185. des: 'scroll half a page down',
  186. cat: 'Navigation'
  187. },
  188. 71: {
  189. key: 'g',
  190. fun: scrollPageTo(-document.body.scrollHeight, 'top'),
  191. des: 'scroll to the top of the page',
  192. cat: 'Navigation'
  193. },
  194. 86: {
  195. key: 'v',
  196. fun: scrollPageTo(document.body.scrollHeight, 'bottom'),
  197. des: 'scroll to the bottom of the page',
  198. cat: 'Navigation'
  199. },
  200. 75: {
  201. key: 'k',
  202. fun: highlightResult('up'),
  203. des: 'select previous search result',
  204. cat: 'Results'
  205. },
  206. 74: {
  207. key: 'j',
  208. fun: highlightResult('down'),
  209. des: 'select next search result',
  210. cat: 'Results'
  211. },
  212. 80: {
  213. key: 'p',
  214. fun: GoToPreviousPage(),
  215. des: 'go to previous page',
  216. cat: 'Results'
  217. },
  218. 78: {
  219. key: 'n',
  220. fun: GoToNextPage(),
  221. des: 'go to next page',
  222. cat: 'Results'
  223. },
  224. 79: {
  225. key: 'o',
  226. fun: openResult(false),
  227. des: 'open search result',
  228. cat: 'Results'
  229. },
  230. 84: {
  231. key: 't',
  232. fun: openResult(true),
  233. des: 'open the result in a new tab',
  234. cat: 'Results'
  235. },
  236. 82: {
  237. key: 'r',
  238. fun: reloadPage,
  239. des: 'reload page from the server',
  240. cat: 'Control'
  241. },
  242. 72: {
  243. key: 'h',
  244. fun: toggleHelp,
  245. des: 'toggle help window',
  246. cat: 'Other'
  247. }
  248. };
  249. searxng.on(document, "keydown", function(e) {
  250. // check for modifiers so we don't break browser's hotkeys
  251. if (Object.prototype.hasOwnProperty.call(vimKeys, e.keyCode) && !e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey) {
  252. var tagName = e.target.tagName.toLowerCase();
  253. if (e.keyCode === 27) {
  254. vimKeys[e.keyCode].fun(e);
  255. } else {
  256. if (e.target === document.body || tagName === 'a' || tagName === 'button') {
  257. e.preventDefault();
  258. vimKeys[e.keyCode].fun();
  259. }
  260. }
  261. }
  262. });
  263. function highlightResult(which) {
  264. return function(noScroll) {
  265. var current = document.querySelector('.result[data-vim-selected]'),
  266. effectiveWhich = which;
  267. if (current === null) {
  268. // no selection : choose the first one
  269. current = document.querySelector('.result');
  270. if (current === null) {
  271. // no first one : there are no results
  272. return;
  273. }
  274. // replace up/down actions by selecting first one
  275. if (which === "down" || which === "up") {
  276. effectiveWhich = current;
  277. }
  278. }
  279. var next, results = document.querySelectorAll('.result');
  280. if (typeof effectiveWhich !== 'string') {
  281. next = effectiveWhich;
  282. } else {
  283. switch (effectiveWhich) {
  284. case 'visible':
  285. var top = document.documentElement.scrollTop || document.body.scrollTop;
  286. var bot = top + document.documentElement.clientHeight;
  287. for (var i = 0; i < results.length; i++) {
  288. next = results[i];
  289. var etop = next.offsetTop;
  290. var ebot = etop + next.clientHeight;
  291. if ((ebot <= bot) && (etop > top)) {
  292. break;
  293. }
  294. }
  295. break;
  296. case 'down':
  297. next = current.nextElementSibling;
  298. if (next === null) {
  299. next = results[0];
  300. }
  301. break;
  302. case 'up':
  303. next = current.previousElementSibling;
  304. if (next === null) {
  305. next = results[results.length - 1];
  306. }
  307. break;
  308. case 'bottom':
  309. next = results[results.length - 1];
  310. break;
  311. case 'top':
  312. /* falls through */
  313. default:
  314. next = results[0];
  315. }
  316. }
  317. if (next) {
  318. current.removeAttribute('data-vim-selected');
  319. next.setAttribute('data-vim-selected', 'true');
  320. var link = next.querySelector('h3 a') || next.querySelector('a');
  321. if (link !== null) {
  322. link.focus();
  323. }
  324. if (!noScroll) {
  325. scrollPageToSelected();
  326. }
  327. }
  328. };
  329. }
  330. function reloadPage() {
  331. document.location.reload(true);
  332. }
  333. function removeFocus(e) {
  334. const tagName = e.target.tagName.toLowerCase();
  335. if (document.activeElement && (tagName === 'input' || tagName === 'select' || tagName === 'textarea')) {
  336. document.activeElement.blur();
  337. } else {
  338. searxng.closeDetail();
  339. }
  340. }
  341. function pageButtonClick(css_selector) {
  342. return function() {
  343. var button = document.querySelector(css_selector);
  344. if (button) {
  345. button.click();
  346. }
  347. };
  348. }
  349. function GoToNextPage() {
  350. return pageButtonClick('nav#pagination .next_page button[type="submit"]');
  351. }
  352. function GoToPreviousPage() {
  353. return pageButtonClick('nav#pagination .previous_page button[type="submit"]');
  354. }
  355. function scrollPageToSelected() {
  356. var sel = document.querySelector('.result[data-vim-selected]');
  357. if (sel === null) {
  358. return;
  359. }
  360. var wtop = document.documentElement.scrollTop || document.body.scrollTop,
  361. wheight = document.documentElement.clientHeight,
  362. etop = sel.offsetTop,
  363. ebot = etop + sel.clientHeight,
  364. offset = 120;
  365. // first element ?
  366. if ((sel.previousElementSibling === null) && (ebot < wheight)) {
  367. // set to the top of page if the first element
  368. // is fully included in the viewport
  369. window.scroll(window.scrollX, 0);
  370. return;
  371. }
  372. if (wtop > (etop - offset)) {
  373. window.scroll(window.scrollX, etop - offset);
  374. } else {
  375. var wbot = wtop + wheight;
  376. if (wbot < (ebot + offset)) {
  377. window.scroll(window.scrollX, ebot - wheight + offset);
  378. }
  379. }
  380. }
  381. function scrollPage(amount) {
  382. return function() {
  383. window.scrollBy(0, amount);
  384. highlightResult('visible')();
  385. };
  386. }
  387. function scrollPageTo(position, nav) {
  388. return function() {
  389. window.scrollTo(0, position);
  390. highlightResult(nav)();
  391. };
  392. }
  393. function searchInputFocus() {
  394. window.scrollTo(0, 0);
  395. document.querySelector('#q').focus();
  396. }
  397. function openResult(newTab) {
  398. return function() {
  399. var link = document.querySelector('.result[data-vim-selected] h3 a');
  400. if (link === null) {
  401. link = document.querySelector('.result[data-vim-selected] > a');
  402. }
  403. if (link !== null) {
  404. var url = link.getAttribute('href');
  405. if (newTab) {
  406. window.open(url);
  407. } else {
  408. window.location.href = url;
  409. }
  410. }
  411. };
  412. }
  413. function initHelpContent(divElement) {
  414. var categories = {};
  415. for (var k in vimKeys) {
  416. var key = vimKeys[k];
  417. categories[key.cat] = categories[key.cat] || [];
  418. categories[key.cat].push(key);
  419. }
  420. var sorted = Object.keys(categories).sort(function(a, b) {
  421. return categories[b].length - categories[a].length;
  422. });
  423. if (sorted.length === 0) {
  424. return;
  425. }
  426. var html = '<a href="#" class="close" aria-label="close" title="close">×</a>';
  427. html += '<h3>How to navigate searx with Vim-like hotkeys</h3>';
  428. html += '<table>';
  429. for (var i = 0; i < sorted.length; i++) {
  430. var cat = categories[sorted[i]];
  431. var lastCategory = i === (sorted.length - 1);
  432. var first = i % 2 === 0;
  433. if (first) {
  434. html += '<tr>';
  435. }
  436. html += '<td>';
  437. html += '<h4>' + cat[0].cat + '</h4>';
  438. html += '<ul class="list-unstyled">';
  439. for (var cj in cat) {
  440. html += '<li><kbd>' + cat[cj].key + '</kbd> ' + cat[cj].des + '</li>';
  441. }
  442. html += '</ul>';
  443. html += '</td>'; // col-sm-*
  444. if (!first || lastCategory) {
  445. html += '</tr>'; // row
  446. }
  447. }
  448. html += '</table>';
  449. divElement.innerHTML = html;
  450. }
  451. function toggleHelp() {
  452. var helpPanel = document.querySelector('#vim-hotkeys-help');
  453. console.log(helpPanel);
  454. if (helpPanel === undefined || helpPanel === null) {
  455. // first call
  456. helpPanel = document.createElement('div');
  457. helpPanel.id = 'vim-hotkeys-help';
  458. helpPanel.className='dialog-modal';
  459. helpPanel.style='width: 40%';
  460. initHelpContent(helpPanel);
  461. initHelpContent(helpPanel);
  462. initHelpContent(helpPanel);
  463. var body = document.getElementsByTagName('body')[0];
  464. body.appendChild(helpPanel);
  465. } else {
  466. // togggle hidden
  467. helpPanel.classList.toggle('invisible');
  468. return;
  469. }
  470. }
  471. searxng.scrollPageToSelected = scrollPageToSelected;
  472. searxng.selectNext = highlightResult('down');
  473. searxng.selectPrevious = highlightResult('up');
  474. });
  475. ;/* SPDX-License-Identifier: AGPL-3.0-or-later */
  476. /* global L */
  477. (function (w, d, searxng) {
  478. 'use strict';
  479. searxng.ready(function () {
  480. searxng.on('.searxng_init_map', 'click', function(event) {
  481. // no more request
  482. this.classList.remove("searxng_init_map");
  483. //
  484. var leaflet_target = this.dataset.leafletTarget;
  485. var map_lon = parseFloat(this.dataset.mapLon);
  486. var map_lat = parseFloat(this.dataset.mapLat);
  487. var map_zoom = parseFloat(this.dataset.mapZoom);
  488. var map_boundingbox = JSON.parse(this.dataset.mapBoundingbox);
  489. var map_geojson = JSON.parse(this.dataset.mapGeojson);
  490. searxng.loadStyle('css/leaflet.css');
  491. searxng.loadScript('js/leaflet.js', function() {
  492. var map_bounds = null;
  493. if(map_boundingbox) {
  494. var southWest = L.latLng(map_boundingbox[0], map_boundingbox[2]);
  495. var northEast = L.latLng(map_boundingbox[1], map_boundingbox[3]);
  496. map_bounds = L.latLngBounds(southWest, northEast);
  497. }
  498. // init map
  499. var map = L.map(leaflet_target);
  500. // create the tile layer with correct attribution
  501. var osmMapnikUrl='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
  502. var osmMapnikAttrib='Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors';
  503. var osmMapnik = new L.TileLayer(osmMapnikUrl, {minZoom: 1, maxZoom: 19, attribution: osmMapnikAttrib});
  504. var osmWikimediaUrl='https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png';
  505. var osmWikimediaAttrib = 'Wikimedia maps | Maps data © <a href="https://openstreetmap.org">OpenStreetMap contributors</a>';
  506. var osmWikimedia = new L.TileLayer(osmWikimediaUrl, {minZoom: 1, maxZoom: 19, attribution: osmWikimediaAttrib});
  507. // init map view
  508. if(map_bounds) {
  509. // TODO hack: https://github.com/Leaflet/Leaflet/issues/2021
  510. // Still useful ?
  511. setTimeout(function () {
  512. map.fitBounds(map_bounds, {
  513. maxZoom:17
  514. });
  515. }, 0);
  516. } else if (map_lon && map_lat) {
  517. if(map_zoom) {
  518. map.setView(new L.latLng(map_lat, map_lon),map_zoom);
  519. } else {
  520. map.setView(new L.latLng(map_lat, map_lon),8);
  521. }
  522. }
  523. map.addLayer(osmMapnik);
  524. var baseLayers = {
  525. "OSM Mapnik": osmMapnik,
  526. "OSM Wikimedia": osmWikimedia,
  527. };
  528. L.control.layers(baseLayers).addTo(map);
  529. if(map_geojson) {
  530. L.geoJson(map_geojson).addTo(map);
  531. } /*else if(map_bounds) {
  532. L.rectangle(map_bounds, {color: "#ff7800", weight: 3, fill:false}).addTo(map);
  533. }*/
  534. });
  535. // this event occour only once per element
  536. event.preventDefault();
  537. });
  538. });
  539. })(window, document, window.searxng);
  540. ;/* SPDX-License-Identifier: AGPL-3.0-or-later */
  541. (function (w, d, searxng) {
  542. 'use strict';
  543. searxng.ready(function() {
  544. let engine_descriptions = null;
  545. function load_engine_descriptions() {
  546. if (engine_descriptions == null) {
  547. searxng.http("GET", "engine_descriptions.json").then(function(content) {
  548. engine_descriptions = JSON.parse(content);
  549. for (const [engine_name, description] of Object.entries(engine_descriptions)) {
  550. let elements = d.querySelectorAll('[data-engine-name="' + engine_name + '"] .engine-description');
  551. for(const element of elements) {
  552. let source = ' (<i>' + searxng.translations['Source'] + ':&nbsp;' + description[1] + '</i>)';
  553. element.innerHTML = description[0] + source;
  554. }
  555. }
  556. });
  557. }
  558. }
  559. if (d.querySelector('body[class="preferences_endpoint"]')) {
  560. for(const el of d.querySelectorAll('[data-engine-name]')) {
  561. searxng.on(el, 'mouseenter', load_engine_descriptions);
  562. }
  563. }
  564. });
  565. })(window, document, window.searxng);
  566. ;/* SPDX-License-Identifier: AGPL-3.0-or-later */
  567. (function(w, d, searxng) {
  568. 'use strict';
  569. searxng.ready(function() {
  570. searxng.image_thumbnail_layout = new searxng.ImageLayout('#urls', '#urls .result-images', 'img.image_thumbnail', 14, 6, 200);
  571. searxng.image_thumbnail_layout.watch();
  572. searxng.on('.btn-collapse', 'click', function() {
  573. var btnLabelCollapsed = this.getAttribute('data-btn-text-collapsed');
  574. var btnLabelNotCollapsed = this.getAttribute('data-btn-text-not-collapsed');
  575. var target = this.getAttribute('data-target');
  576. var targetElement = d.querySelector(target);
  577. var html = this.innerHTML;
  578. if (this.classList.contains('collapsed')) {
  579. html = html.replace(btnLabelCollapsed, btnLabelNotCollapsed);
  580. } else {
  581. html = html.replace(btnLabelNotCollapsed, btnLabelCollapsed);
  582. }
  583. this.innerHTML = html;
  584. this.classList.toggle('collapsed');
  585. targetElement.classList.toggle('invisible');
  586. });
  587. searxng.on('.media-loader', 'click', function() {
  588. var target = this.getAttribute('data-target');
  589. var iframe_load = d.querySelector(target + ' > iframe');
  590. var srctest = iframe_load.getAttribute('src');
  591. if (srctest === null || srctest === undefined || srctest === false) {
  592. iframe_load.setAttribute('src', iframe_load.getAttribute('data-src'));
  593. }
  594. });
  595. function selectImage(e) {
  596. /*eslint no-unused-vars: 0*/
  597. let t = e.target;
  598. while (t && t.nodeName != 'ARTICLE') {
  599. t = t.parentNode;
  600. }
  601. if (t) {
  602. // load full size image in background
  603. const imgElement = t.querySelector('.result-images-source img');
  604. const thumbnailElement = t.querySelector('.image_thumbnail');
  605. const detailElement = t.querySelector('.detail');
  606. if (imgElement) {
  607. const imgSrc = imgElement.getAttribute('data-src');
  608. if (imgSrc) {
  609. const loader = d.createElement('div');
  610. const imgLoader = new Image();
  611. loader.classList.add('loader');
  612. detailElement.appendChild(loader);
  613. imgLoader.onload = e => {
  614. imgElement.src = imgSrc;
  615. loader.remove();
  616. };
  617. imgLoader.onerror = e => {
  618. loader.remove();
  619. };
  620. imgLoader.src = imgSrc;
  621. imgElement.src = thumbnailElement.src;
  622. imgElement.removeAttribute('data-src');
  623. }
  624. }
  625. }
  626. d.getElementById('results').classList.add('image-detail-open');
  627. searxng.image_thumbnail_layout.align();
  628. searxng.scrollPageToSelected();
  629. }
  630. searxng.closeDetail = function(e) {
  631. d.getElementById('results').classList.remove('image-detail-open');
  632. searxng.image_thumbnail_layout.align();
  633. searxng.scrollPageToSelected();
  634. }
  635. searxng.on('.result-images', 'click', e => {
  636. e.preventDefault();
  637. selectImage(e);
  638. });
  639. searxng.on('.result-images a', 'focus', selectImage, true);
  640. searxng.on('.result-detail-close', 'click', e => {
  641. e.preventDefault();
  642. searxng.closeDetail();
  643. });
  644. searxng.on('.result-detail-previous', 'click', e => searxng.selectPrevious(false));
  645. searxng.on('.result-detail-next', 'click', e => searxng.selectNext(false));
  646. w.addEventListener('scroll', function() {
  647. var e = d.getElementById('backToTop'),
  648. scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
  649. results = d.getElementById('results');
  650. if (e !== null) {
  651. if (scrollTop >= 100) {
  652. results.classList.add('scrolling');
  653. } else {
  654. results.classList.remove('scrolling');
  655. }
  656. }
  657. }, true);
  658. });
  659. })(window, document, window.searxng);
  660. ;/* SPDX-License-Identifier: AGPL-3.0-or-later */
  661. /* global AutoComplete */
  662. (function(w, d, searxng) {
  663. 'use strict';
  664. var firstFocus = true, qinput_id = "q", qinput;
  665. function placeCursorAtEnd(element) {
  666. if (element.setSelectionRange) {
  667. var len = element.value.length;
  668. element.setSelectionRange(len, len);
  669. }
  670. }
  671. function submitIfQuery() {
  672. if (qinput.value.length > 0) {
  673. var search = document.getElementById('search');
  674. setTimeout(search.submit.bind(search), 0);
  675. }
  676. }
  677. function createClearButton(qinput) {
  678. var cs = document.getElementById('clear_search');
  679. var updateClearButton = function() {
  680. if (qinput.value.length === 0) {
  681. cs.classList.add("empty");
  682. } else {
  683. cs.classList.remove("empty");
  684. }
  685. };
  686. // update status, event listener
  687. updateClearButton();
  688. cs.addEventListener('click', function() {
  689. qinput.value='';
  690. qinput.focus();
  691. updateClearButton();
  692. });
  693. qinput.addEventListener('keyup', updateClearButton, false);
  694. }
  695. searxng.ready(function() {
  696. qinput = d.getElementById(qinput_id);
  697. function placeCursorAtEndOnce() {
  698. if (firstFocus) {
  699. placeCursorAtEnd(qinput);
  700. firstFocus = false;
  701. } else {
  702. // e.preventDefault();
  703. }
  704. }
  705. if (qinput !== null) {
  706. // clear button
  707. createClearButton(qinput);
  708. // autocompleter
  709. if (searxng.autocompleter) {
  710. searxng.autocomplete = AutoComplete.call(w, {
  711. Url: "./autocompleter",
  712. EmptyMessage: searxng.translations.no_item_found,
  713. HttpMethod: searxng.method,
  714. HttpHeaders: {
  715. "Content-type": "application/x-www-form-urlencoded",
  716. "X-Requested-With": "XMLHttpRequest"
  717. },
  718. MinChars: 4,
  719. Delay: 300,
  720. }, "#" + qinput_id);
  721. // hack, see : https://github.com/autocompletejs/autocomplete.js/issues/37
  722. w.addEventListener('resize', function() {
  723. var event = new CustomEvent("position");
  724. qinput.dispatchEvent(event);
  725. });
  726. }
  727. qinput.addEventListener('focus', placeCursorAtEndOnce, false);
  728. qinput.focus();
  729. }
  730. // vanilla js version of search_on_category_select.js
  731. if (qinput !== null && d.querySelector('.help') != null && searxng.search_on_category_select) {
  732. d.querySelector('.help').className='invisible';
  733. searxng.on('#categories input', 'change', function() {
  734. var i, categories = d.querySelectorAll('#categories input[type="checkbox"]');
  735. for(i=0; i<categories.length; i++) {
  736. if (categories[i] !== this && categories[i].checked) {
  737. categories[i].click();
  738. }
  739. }
  740. if (! this.checked) {
  741. this.click();
  742. }
  743. submitIfQuery();
  744. return false;
  745. });
  746. searxng.on(d.getElementById('time_range'), 'change', submitIfQuery);
  747. searxng.on(d.getElementById('language'), 'change', submitIfQuery);
  748. }
  749. });
  750. })(window, document, window.searxng);
  751. ;/**
  752. *
  753. * Google Image Layout v0.0.1
  754. * Description, by Anh Trinh.
  755. * Heavily modified for searx
  756. * https://ptgamr.github.io/2014-09-12-google-image-layout/
  757. * https://ptgamr.github.io/google-image-layout/src/google-image-layout.js
  758. *
  759. * @license Free to use under the MIT License.
  760. *
  761. */
  762. (function (w, d) {
  763. function ImageLayout(container_selector, results_selector, img_selector, verticalMargin, horizontalMargin, maxHeight) {
  764. this.container_selector = container_selector;
  765. this.results_selector = results_selector;
  766. this.img_selector = img_selector;
  767. this.verticalMargin = verticalMargin;
  768. this.horizontalMargin = horizontalMargin;
  769. this.maxHeight = maxHeight;
  770. this.isAlignDone = true;
  771. }
  772. /**
  773. * Get the height that make all images fit the container
  774. *
  775. * width = w1 + w2 + w3 + ... = r1*h + r2*h + r3*h + ...
  776. *
  777. * @param {[type]} images the images to be calculated
  778. * @param {[type]} width the container witdth
  779. * @param {[type]} margin the margin between each image
  780. *
  781. * @return {[type]} the height
  782. */
  783. ImageLayout.prototype._getHeigth = function (images, width) {
  784. var i, img;
  785. var r = 0;
  786. for (i = 0; i < images.length; i++) {
  787. img = images[i];
  788. if ((img.naturalWidth > 0) && (img.naturalHeight > 0)) {
  789. r += img.naturalWidth / img.naturalHeight;
  790. } else {
  791. // assume that not loaded images are square
  792. r += 1;
  793. }
  794. }
  795. return (width - images.length * this.verticalMargin) / r; //have to round down because Firefox will automatically roundup value with number of decimals > 3
  796. };
  797. ImageLayout.prototype._setSize = function (images, height) {
  798. var i, img, imgWidth;
  799. var imagesLength = images.length, resultNode;
  800. for (i = 0; i < imagesLength; i++) {
  801. img = images[i];
  802. if ((img.naturalWidth > 0) && (img.naturalHeight > 0)) {
  803. imgWidth = height * img.naturalWidth / img.naturalHeight;
  804. } else {
  805. // not loaded image : make it square as _getHeigth said it
  806. imgWidth = height;
  807. }
  808. img.style.width = imgWidth + 'px';
  809. img.style.height = height + 'px';
  810. img.style.marginLeft = this.horizontalMargin + 'px';
  811. img.style.marginTop = this.horizontalMargin + 'px';
  812. img.style.marginRight = this.verticalMargin - 7 + 'px'; // -4 is the negative margin of the inline element
  813. img.style.marginBottom = this.verticalMargin - 7 + 'px';
  814. resultNode = img.parentNode.parentNode;
  815. if (!resultNode.classList.contains('js')) {
  816. resultNode.classList.add('js');
  817. }
  818. }
  819. };
  820. ImageLayout.prototype._alignImgs = function (imgGroup) {
  821. var isSearching, slice, i, h;
  822. var containerElement = d.querySelector(this.container_selector);
  823. var containerCompStyles = window.getComputedStyle(containerElement);
  824. var containerPaddingLeft = parseInt(containerCompStyles.getPropertyValue('padding-left'), 10);
  825. var containerPaddingRight = parseInt(containerCompStyles.getPropertyValue('padding-right'), 10);
  826. var containerWidth = containerElement.clientWidth - containerPaddingLeft - containerPaddingRight;
  827. while (imgGroup.length > 0) {
  828. isSearching = true;
  829. for (i = 1; i <= imgGroup.length && isSearching; i++) {
  830. slice = imgGroup.slice(0, i);
  831. h = this._getHeigth(slice, containerWidth);
  832. if (h < this.maxHeight) {
  833. this._setSize(slice, h);
  834. // continue with the remaining images
  835. imgGroup = imgGroup.slice(i);
  836. isSearching = false;
  837. }
  838. }
  839. if (isSearching) {
  840. this._setSize(slice, Math.min(this.maxHeight, h));
  841. break;
  842. }
  843. }
  844. };
  845. ImageLayout.prototype.align = function () {
  846. var i;
  847. var results_selectorNode = d.querySelectorAll(this.results_selector);
  848. var results_length = results_selectorNode.length;
  849. var previous = null;
  850. var current = null;
  851. var imgGroup = [];
  852. for (i = 0; i < results_length; i++) {
  853. current = results_selectorNode[i];
  854. if (current.previousElementSibling !== previous && imgGroup.length > 0) {
  855. // the current image is not connected to previous one
  856. // so the current image is the start of a new group of images.
  857. // so call _alignImgs to align the current group
  858. this._alignImgs(imgGroup);
  859. // and start a new empty group of images
  860. imgGroup = [];
  861. }
  862. // add the current image to the group (only the img tag)
  863. imgGroup.push(current.querySelector(this.img_selector));
  864. // update the previous variable
  865. previous = current;
  866. }
  867. // align the remaining images
  868. if (imgGroup.length > 0) {
  869. this._alignImgs(imgGroup);
  870. }
  871. };
  872. ImageLayout.prototype.watch = function () {
  873. var i, img;
  874. var obj = this;
  875. var results_nodes = d.querySelectorAll(this.results_selector);
  876. var results_length = results_nodes.length;
  877. function throttleAlign() {
  878. if (obj.isAlignDone) {
  879. obj.isAlignDone = false;
  880. setTimeout(function () {
  881. obj.align();
  882. obj.isAlignDone = true;
  883. }, 100);
  884. }
  885. }
  886. w.addEventListener('pageshow', throttleAlign);
  887. w.addEventListener('load', throttleAlign);
  888. w.addEventListener('resize', throttleAlign);
  889. for (i = 0; i < results_length; i++) {
  890. img = results_nodes[i].querySelector(this.img_selector);
  891. if (img !== null && img !== undefined) {
  892. img.addEventListener('load', throttleAlign);
  893. img.addEventListener('error', throttleAlign);
  894. }
  895. }
  896. };
  897. w.searxng.ImageLayout = ImageLayout;
  898. }(window, document));
  899. ;(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.AutoComplete = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  900. /*
  901. * @license MIT
  902. *
  903. * Autocomplete.js v2.7.1
  904. * Developed by Baptiste Donaux
  905. * http://autocomplete-js.com
  906. *
  907. * (c) 2017, Baptiste Donaux
  908. */
  909. "use strict";
  910. var ConditionOperator;
  911. (function (ConditionOperator) {
  912. ConditionOperator[ConditionOperator["AND"] = 0] = "AND";
  913. ConditionOperator[ConditionOperator["OR"] = 1] = "OR";
  914. })(ConditionOperator || (ConditionOperator = {}));
  915. var EventType;
  916. (function (EventType) {
  917. EventType[EventType["KEYDOWN"] = 0] = "KEYDOWN";
  918. EventType[EventType["KEYUP"] = 1] = "KEYUP";
  919. })(EventType || (EventType = {}));
  920. /**
  921. * Core
  922. *
  923. * @class
  924. * @author Baptiste Donaux <baptiste.donaux@gmail.com> @baptistedonaux
  925. */
  926. var AutoComplete = /** @class */ (function () {
  927. // Constructor
  928. function AutoComplete(params, selector) {
  929. if (params === void 0) { params = {}; }
  930. if (selector === void 0) { selector = "[data-autocomplete]"; }
  931. if (Array.isArray(selector)) {
  932. selector.forEach(function (s) {
  933. new AutoComplete(params, s);
  934. });
  935. }
  936. else if (typeof selector == "string") {
  937. var elements = document.querySelectorAll(selector);
  938. Array.prototype.forEach.call(elements, function (input) {
  939. new AutoComplete(params, input);
  940. });
  941. }
  942. else {
  943. var specificParams = AutoComplete.merge(AutoComplete.defaults, params, {
  944. DOMResults: document.createElement("div")
  945. });
  946. AutoComplete.prototype.create(specificParams, selector);
  947. return specificParams;
  948. }
  949. }
  950. AutoComplete.prototype.create = function (params, element) {
  951. params.Input = element;
  952. if (params.Input.nodeName.match(/^INPUT$/i) && (params.Input.hasAttribute("type") === false || params.Input.getAttribute("type").match(/^TEXT|SEARCH$/i))) {
  953. params.Input.setAttribute("autocomplete", "off");
  954. params._Position(params);
  955. params.Input.parentNode.appendChild(params.DOMResults);
  956. params.$Listeners = {
  957. blur: params._Blur.bind(params),
  958. destroy: AutoComplete.prototype.destroy.bind(null, params),
  959. focus: params._Focus.bind(params),
  960. keyup: AutoComplete.prototype.event.bind(null, params, EventType.KEYUP),
  961. keydown: AutoComplete.prototype.event.bind(null, params, EventType.KEYDOWN),
  962. position: params._Position.bind(params)
  963. };
  964. for (var event in params.$Listeners) {
  965. params.Input.addEventListener(event, params.$Listeners[event]);
  966. }
  967. }
  968. };
  969. AutoComplete.prototype.getEventsByType = function (params, type) {
  970. var mappings = {};
  971. for (var key in params.KeyboardMappings) {
  972. var event = EventType.KEYUP;
  973. if (params.KeyboardMappings[key].Event !== undefined) {
  974. event = params.KeyboardMappings[key].Event;
  975. }
  976. if (event == type) {
  977. mappings[key] = params.KeyboardMappings[key];
  978. }
  979. }
  980. return mappings;
  981. };
  982. AutoComplete.prototype.event = function (params, type, event) {
  983. var eventIdentifier = function (condition) {
  984. if ((match === true && mapping.Operator == ConditionOperator.AND) || (match === false && mapping.Operator == ConditionOperator.OR)) {
  985. condition = AutoComplete.merge({
  986. Not: false
  987. }, condition);
  988. if (condition.hasOwnProperty("Is")) {
  989. if (condition.Is == event.keyCode) {
  990. match = !condition.Not;
  991. }
  992. else {
  993. match = condition.Not;
  994. }
  995. }
  996. else if (condition.hasOwnProperty("From") && condition.hasOwnProperty("To")) {
  997. if (event.keyCode >= condition.From && event.keyCode <= condition.To) {
  998. match = !condition.Not;
  999. }
  1000. else {
  1001. match = condition.Not;
  1002. }
  1003. }
  1004. }
  1005. };
  1006. for (var name in AutoComplete.prototype.getEventsByType(params, type)) {
  1007. var mapping = AutoComplete.merge({
  1008. Operator: ConditionOperator.AND
  1009. }, params.KeyboardMappings[name]), match = ConditionOperator.AND == mapping.Operator;
  1010. mapping.Conditions.forEach(eventIdentifier);
  1011. if (match === true) {
  1012. mapping.Callback.call(params, event);
  1013. }
  1014. }
  1015. };
  1016. AutoComplete.prototype.makeRequest = function (params, callback, callbackErr) {
  1017. var propertyHttpHeaders = Object.getOwnPropertyNames(params.HttpHeaders), request = new XMLHttpRequest(), method = params._HttpMethod(), url = params._Url(), queryParams = params._Pre(), queryParamsStringify = encodeURIComponent(params._QueryArg()) + "=" + encodeURIComponent(queryParams);
  1018. if (method.match(/^GET$/i)) {
  1019. if (url.indexOf("?") !== -1) {
  1020. url += "&" + queryParamsStringify;
  1021. }
  1022. else {
  1023. url += "?" + queryParamsStringify;
  1024. }
  1025. }
  1026. request.open(method, url, true);
  1027. for (var i = propertyHttpHeaders.length - 1; i >= 0; i--) {
  1028. request.setRequestHeader(propertyHttpHeaders[i], params.HttpHeaders[propertyHttpHeaders[i]]);
  1029. }
  1030. request.onreadystatechange = function () {
  1031. if (request.readyState == 4 && request.status == 200) {
  1032. params.$Cache[queryParams] = request.response;
  1033. callback(request.response);
  1034. }
  1035. else if (request.status >= 400) {
  1036. callbackErr();
  1037. }
  1038. };
  1039. return request;
  1040. };
  1041. AutoComplete.prototype.ajax = function (params, request, timeout) {
  1042. if (timeout === void 0) { timeout = true; }
  1043. if (params.$AjaxTimer) {
  1044. window.clearTimeout(params.$AjaxTimer);
  1045. }
  1046. if (timeout === true) {
  1047. params.$AjaxTimer = window.setTimeout(AutoComplete.prototype.ajax.bind(null, params, request, false), params.Delay);
  1048. }
  1049. else {
  1050. if (params.Request) {
  1051. params.Request.abort();
  1052. }
  1053. params.Request = request;
  1054. params.Request.send(params._QueryArg() + "=" + params._Pre());
  1055. }
  1056. };
  1057. AutoComplete.prototype.cache = function (params, callback, callbackErr) {
  1058. var response = params._Cache(params._Pre());
  1059. if (response === undefined) {
  1060. var request = AutoComplete.prototype.makeRequest(params, callback, callbackErr);
  1061. AutoComplete.prototype.ajax(params, request);
  1062. }
  1063. else {
  1064. callback(response);
  1065. }
  1066. };
  1067. AutoComplete.prototype.destroy = function (params) {
  1068. for (var event in params.$Listeners) {
  1069. params.Input.removeEventListener(event, params.$Listeners[event]);
  1070. }
  1071. params.DOMResults.parentNode.removeChild(params.DOMResults);
  1072. };
  1073. AutoComplete.merge = function () {
  1074. var merge = {}, tmp;
  1075. for (var i = 0; i < arguments.length; i++) {
  1076. for (tmp in arguments[i]) {
  1077. merge[tmp] = arguments[i][tmp];
  1078. }
  1079. }
  1080. return merge;
  1081. };
  1082. AutoComplete.defaults = {
  1083. Delay: 150,
  1084. EmptyMessage: "No result here",
  1085. Highlight: {
  1086. getRegex: function (value) {
  1087. return new RegExp(value, "ig");
  1088. },
  1089. transform: function (value) {
  1090. return "<strong>" + value + "</strong>";
  1091. }
  1092. },
  1093. HttpHeaders: {
  1094. "Content-type": "application/x-www-form-urlencoded"
  1095. },
  1096. Limit: 0,
  1097. MinChars: 0,
  1098. HttpMethod: "GET",
  1099. QueryArg: "q",
  1100. Url: null,
  1101. KeyboardMappings: {
  1102. "Enter": {
  1103. Conditions: [{
  1104. Is: 13,
  1105. Not: false
  1106. }],
  1107. Callback: function (event) {
  1108. if (this.DOMResults.getAttribute("class").indexOf("open") != -1) {
  1109. var liActive = this.DOMResults.querySelector("li.active");
  1110. if (liActive !== null) {
  1111. event.preventDefault();
  1112. this._Select(liActive);
  1113. this.DOMResults.setAttribute("class", "autocomplete");
  1114. }
  1115. }
  1116. },
  1117. Operator: ConditionOperator.AND,
  1118. Event: EventType.KEYDOWN
  1119. },
  1120. "KeyUpAndDown_down": {
  1121. Conditions: [{
  1122. Is: 38,
  1123. Not: false
  1124. },
  1125. {
  1126. Is: 40,
  1127. Not: false
  1128. }],
  1129. Callback: function (event) {
  1130. event.preventDefault();
  1131. },
  1132. Operator: ConditionOperator.OR,
  1133. Event: EventType.KEYDOWN
  1134. },
  1135. "KeyUpAndDown_up": {
  1136. Conditions: [{
  1137. Is: 38,
  1138. Not: false
  1139. },
  1140. {
  1141. Is: 40,
  1142. Not: false
  1143. }],
  1144. Callback: function (event) {
  1145. event.preventDefault();
  1146. var first = this.DOMResults.querySelector("li:first-child:not(.locked)"), last = this.DOMResults.querySelector("li:last-child:not(.locked)"), active = this.DOMResults.querySelector("li.active");
  1147. if (active) {
  1148. var currentIndex = Array.prototype.indexOf.call(active.parentNode.children, active), position = currentIndex + (event.keyCode - 39), lisCount = this.DOMResults.getElementsByTagName("li").length;
  1149. if (position < 0) {
  1150. position = lisCount - 1;
  1151. }
  1152. else if (position >= lisCount) {
  1153. position = 0;
  1154. }
  1155. active.classList.remove("active");
  1156. active.parentElement.children.item(position).classList.add("active");
  1157. }
  1158. else if (last && event.keyCode == 38) {
  1159. last.classList.add("active");
  1160. }
  1161. else if (first) {
  1162. first.classList.add("active");
  1163. }
  1164. },
  1165. Operator: ConditionOperator.OR,
  1166. Event: EventType.KEYUP
  1167. },
  1168. "AlphaNum": {
  1169. Conditions: [{
  1170. Is: 13,
  1171. Not: true
  1172. }, {
  1173. From: 35,
  1174. To: 40,
  1175. Not: true
  1176. }],
  1177. Callback: function () {
  1178. var oldValue = this.Input.getAttribute("data-autocomplete-old-value"), currentValue = this._Pre();
  1179. if (currentValue !== "" && currentValue.length >= this._MinChars()) {
  1180. if (!oldValue || currentValue != oldValue) {
  1181. this.DOMResults.setAttribute("class", "autocomplete open");
  1182. }
  1183. AutoComplete.prototype.cache(this, function (response) {
  1184. this._Render(this._Post(response));
  1185. this._Open();
  1186. }.bind(this), this._Error);
  1187. }
  1188. else {
  1189. this._Close();
  1190. }
  1191. },
  1192. Operator: ConditionOperator.AND,
  1193. Event: EventType.KEYUP
  1194. }
  1195. },
  1196. DOMResults: null,
  1197. Request: null,
  1198. Input: null,
  1199. /**
  1200. * Return the message when no result returns
  1201. */
  1202. _EmptyMessage: function () {
  1203. var emptyMessage = "";
  1204. if (this.Input.hasAttribute("data-autocomplete-empty-message")) {
  1205. emptyMessage = this.Input.getAttribute("data-autocomplete-empty-message");
  1206. }
  1207. else if (this.EmptyMessage !== false) {
  1208. emptyMessage = this.EmptyMessage;
  1209. }
  1210. else {
  1211. emptyMessage = "";
  1212. }
  1213. return emptyMessage;
  1214. },
  1215. /**
  1216. * Returns the maximum number of results
  1217. */
  1218. _Limit: function () {
  1219. var limit = this.Input.getAttribute("data-autocomplete-limit");
  1220. if (isNaN(limit) || limit === null) {
  1221. return this.Limit;
  1222. }
  1223. return parseInt(limit, 10);
  1224. },
  1225. /**
  1226. * Returns the minimum number of characters entered before firing ajax
  1227. */
  1228. _MinChars: function () {
  1229. var minchars = this.Input.getAttribute("data-autocomplete-minchars");
  1230. if (isNaN(minchars) || minchars === null) {
  1231. return this.MinChars;
  1232. }
  1233. return parseInt(minchars, 10);
  1234. },
  1235. /**
  1236. * Apply transformation on labels response
  1237. */
  1238. _Highlight: function (label) {
  1239. return label.replace(this.Highlight.getRegex(this._Pre()), this.Highlight.transform);
  1240. },
  1241. /**
  1242. * Returns the HHTP method to use
  1243. */
  1244. _HttpMethod: function () {
  1245. if (this.Input.hasAttribute("data-autocomplete-method")) {
  1246. return this.Input.getAttribute("data-autocomplete-method");
  1247. }
  1248. return this.HttpMethod;
  1249. },
  1250. /**
  1251. * Returns the query param to use
  1252. */
  1253. _QueryArg: function () {
  1254. if (this.Input.hasAttribute("data-autocomplete-param-name")) {
  1255. return this.Input.getAttribute("data-autocomplete-param-name");
  1256. }
  1257. return this.QueryArg;
  1258. },
  1259. /**
  1260. * Returns the URL to use for AJAX request
  1261. */
  1262. _Url: function () {
  1263. if (this.Input.hasAttribute("data-autocomplete")) {
  1264. return this.Input.getAttribute("data-autocomplete");
  1265. }
  1266. return this.Url;
  1267. },
  1268. /**
  1269. * Manage the close
  1270. */
  1271. _Blur: function (now) {
  1272. if (now === void 0) { now = false; }
  1273. if (now) {
  1274. this._Close();
  1275. }
  1276. else {
  1277. var params = this;
  1278. setTimeout(function () {
  1279. params._Blur(true);
  1280. }, 150);
  1281. }
  1282. },
  1283. /**
  1284. * Manage the cache
  1285. */
  1286. _Cache: function (value) {
  1287. return this.$Cache[value];
  1288. },
  1289. /**
  1290. * Manage the open
  1291. */
  1292. _Focus: function () {
  1293. var oldValue = this.Input.getAttribute("data-autocomplete-old-value");
  1294. if ((!oldValue || this.Input.value != oldValue) && this._MinChars() <= this.Input.value.length) {
  1295. this.DOMResults.setAttribute("class", "autocomplete open");
  1296. }
  1297. },
  1298. /**
  1299. * Bind all results item if one result is opened
  1300. */
  1301. _Open: function () {
  1302. var params = this;
  1303. Array.prototype.forEach.call(this.DOMResults.getElementsByTagName("li"), function (li) {
  1304. if (li.getAttribute("class") != "locked") {
  1305. li.onclick = function () {
  1306. params._Select(li);
  1307. };
  1308. }
  1309. });
  1310. },
  1311. _Close: function () {
  1312. this.DOMResults.setAttribute("class", "autocomplete");
  1313. },
  1314. /**
  1315. * Position the results HTML element
  1316. */
  1317. _Position: function () {
  1318. this.DOMResults.setAttribute("class", "autocomplete");
  1319. this.DOMResults.setAttribute("style", "top:" + (this.Input.offsetTop + this.Input.offsetHeight) + "px;left:" + this.Input.offsetLeft + "px;width:" + this.Input.clientWidth + "px;");
  1320. },
  1321. /**
  1322. * Execute the render of results DOM element
  1323. */
  1324. _Render: function (response) {
  1325. var ul;
  1326. if (typeof response == "string") {
  1327. ul = this._RenderRaw(response);
  1328. }
  1329. else {
  1330. ul = this._RenderResponseItems(response);
  1331. }
  1332. if (this.DOMResults.hasChildNodes()) {
  1333. this.DOMResults.removeChild(this.DOMResults.childNodes[0]);
  1334. }
  1335. this.DOMResults.appendChild(ul);
  1336. },
  1337. /**
  1338. * ResponseItems[] rendering
  1339. */
  1340. _RenderResponseItems: function (response) {
  1341. var ul = document.createElement("ul"), li = document.createElement("li"), limit = this._Limit();
  1342. // Order
  1343. if (limit < 0) {
  1344. response = response.reverse();
  1345. }
  1346. else if (limit === 0) {
  1347. limit = response.length;
  1348. }
  1349. for (var item = 0; item < Math.min(Math.abs(limit), response.length); item++) {
  1350. li.innerHTML = response[item].Label;
  1351. li.setAttribute("data-autocomplete-value", response[item].Value);
  1352. ul.appendChild(li);
  1353. li = document.createElement("li");
  1354. }
  1355. return ul;
  1356. },
  1357. /**
  1358. * string response rendering (RAW HTML)
  1359. */
  1360. _RenderRaw: function (response) {
  1361. var ul = document.createElement("ul"), li = document.createElement("li");
  1362. if (response.length > 0) {
  1363. this.DOMResults.innerHTML = response;
  1364. }
  1365. else {
  1366. var emptyMessage = this._EmptyMessage();
  1367. if (emptyMessage !== "") {
  1368. li.innerHTML = emptyMessage;
  1369. li.setAttribute("class", "locked");
  1370. ul.appendChild(li);
  1371. }
  1372. }
  1373. return ul;
  1374. },
  1375. /**
  1376. * Deal with request response
  1377. */
  1378. _Post: function (response) {
  1379. try {
  1380. var returnResponse = [];
  1381. //JSON return
  1382. var json = JSON.parse(response);
  1383. if (Object.keys(json).length === 0) {
  1384. return "";
  1385. }
  1386. if (Array.isArray(json)) {
  1387. for (var i = 0; i < Object.keys(json).length; i++) {
  1388. returnResponse[returnResponse.length] = { "Value": json[i], "Label": this._Highlight(json[i]) };
  1389. }
  1390. }
  1391. else {
  1392. for (var value in json) {
  1393. returnResponse.push({
  1394. "Value": value,
  1395. "Label": this._Highlight(json[value])
  1396. });
  1397. }
  1398. }
  1399. return returnResponse;
  1400. }
  1401. catch (event) {
  1402. //HTML return
  1403. return response;
  1404. }
  1405. },
  1406. /**
  1407. * Return the autocomplete value to send (before request)
  1408. */
  1409. _Pre: function () {
  1410. return this.Input.value;
  1411. },
  1412. /**
  1413. * Choice one result item
  1414. */
  1415. _Select: function (item) {
  1416. if (item.hasAttribute("data-autocomplete-value")) {
  1417. this.Input.value = item.getAttribute("data-autocomplete-value");
  1418. }
  1419. else {
  1420. this.Input.value = item.innerHTML;
  1421. }
  1422. this.Input.setAttribute("data-autocomplete-old-value", this.Input.value);
  1423. },
  1424. /**
  1425. * Handle HTTP error on the request
  1426. */
  1427. _Error: function () {
  1428. },
  1429. $AjaxTimer: null,
  1430. $Cache: {},
  1431. $Listeners: {}
  1432. };
  1433. return AutoComplete;
  1434. }());
  1435. module.exports = AutoComplete;
  1436. },{}]},{},[1])(1)
  1437. });