searxng.js 51 KB

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