searxng.js 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  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('time_range'), 'change', submitIfQuery);
  770. searxng.on(d.getElementById('language'), 'change', submitIfQuery);
  771. }
  772. });
  773. })(window, document, window.searxng);
  774. ;/**
  775. *
  776. * Google Image Layout v0.0.1
  777. * Description, by Anh Trinh.
  778. * Heavily modified for searx
  779. * https://ptgamr.github.io/2014-09-12-google-image-layout/
  780. * https://ptgamr.github.io/google-image-layout/src/google-image-layout.js
  781. *
  782. * @license Free to use under the MIT License.
  783. *
  784. */
  785. (function (w, d) {
  786. function ImageLayout(container_selector, results_selector, img_selector, verticalMargin, horizontalMargin, maxHeight) {
  787. this.container_selector = container_selector;
  788. this.results_selector = results_selector;
  789. this.img_selector = img_selector;
  790. this.verticalMargin = verticalMargin;
  791. this.horizontalMargin = horizontalMargin;
  792. this.maxHeight = maxHeight;
  793. this.isAlignDone = true;
  794. }
  795. /**
  796. * Get the height that make all images fit the container
  797. *
  798. * width = w1 + w2 + w3 + ... = r1*h + r2*h + r3*h + ...
  799. *
  800. * @param {[type]} images the images to be calculated
  801. * @param {[type]} width the container witdth
  802. * @param {[type]} margin the margin between each image
  803. *
  804. * @return {[type]} the height
  805. */
  806. ImageLayout.prototype._getHeigth = function (images, width) {
  807. var i, img;
  808. var r = 0;
  809. for (i = 0; i < images.length; i++) {
  810. img = images[i];
  811. if ((img.naturalWidth > 0) && (img.naturalHeight > 0)) {
  812. r += img.naturalWidth / img.naturalHeight;
  813. } else {
  814. // assume that not loaded images are square
  815. r += 1;
  816. }
  817. }
  818. return (width - images.length * this.verticalMargin) / r; //have to round down because Firefox will automatically roundup value with number of decimals > 3
  819. };
  820. ImageLayout.prototype._setSize = function (images, height) {
  821. var i, img, imgWidth;
  822. var imagesLength = images.length, resultNode;
  823. for (i = 0; i < imagesLength; i++) {
  824. img = images[i];
  825. if ((img.naturalWidth > 0) && (img.naturalHeight > 0)) {
  826. imgWidth = height * img.naturalWidth / img.naturalHeight;
  827. } else {
  828. // not loaded image : make it square as _getHeigth said it
  829. imgWidth = height;
  830. }
  831. img.style.width = imgWidth + 'px';
  832. img.style.height = height + 'px';
  833. img.style.marginLeft = this.horizontalMargin + 'px';
  834. img.style.marginTop = this.horizontalMargin + 'px';
  835. img.style.marginRight = this.verticalMargin - 7 + 'px'; // -4 is the negative margin of the inline element
  836. img.style.marginBottom = this.verticalMargin - 7 + 'px';
  837. resultNode = img.parentNode.parentNode;
  838. if (!resultNode.classList.contains('js')) {
  839. resultNode.classList.add('js');
  840. }
  841. }
  842. };
  843. ImageLayout.prototype._alignImgs = function (imgGroup) {
  844. var isSearching, slice, i, h;
  845. var containerElement = d.querySelector(this.container_selector);
  846. var containerCompStyles = window.getComputedStyle(containerElement);
  847. var containerPaddingLeft = parseInt(containerCompStyles.getPropertyValue('padding-left'), 10);
  848. var containerPaddingRight = parseInt(containerCompStyles.getPropertyValue('padding-right'), 10);
  849. var containerWidth = containerElement.clientWidth - containerPaddingLeft - containerPaddingRight;
  850. while (imgGroup.length > 0) {
  851. isSearching = true;
  852. for (i = 1; i <= imgGroup.length && isSearching; i++) {
  853. slice = imgGroup.slice(0, i);
  854. h = this._getHeigth(slice, containerWidth);
  855. if (h < this.maxHeight) {
  856. this._setSize(slice, h);
  857. // continue with the remaining images
  858. imgGroup = imgGroup.slice(i);
  859. isSearching = false;
  860. }
  861. }
  862. if (isSearching) {
  863. this._setSize(slice, Math.min(this.maxHeight, h));
  864. break;
  865. }
  866. }
  867. };
  868. ImageLayout.prototype.align = function () {
  869. var i;
  870. var results_selectorNode = d.querySelectorAll(this.results_selector);
  871. var results_length = results_selectorNode.length;
  872. var previous = null;
  873. var current = null;
  874. var imgGroup = [];
  875. for (i = 0; i < results_length; i++) {
  876. current = results_selectorNode[i];
  877. if (current.previousElementSibling !== previous && imgGroup.length > 0) {
  878. // the current image is not connected to previous one
  879. // so the current image is the start of a new group of images.
  880. // so call _alignImgs to align the current group
  881. this._alignImgs(imgGroup);
  882. // and start a new empty group of images
  883. imgGroup = [];
  884. }
  885. // add the current image to the group (only the img tag)
  886. imgGroup.push(current.querySelector(this.img_selector));
  887. // update the previous variable
  888. previous = current;
  889. }
  890. // align the remaining images
  891. if (imgGroup.length > 0) {
  892. this._alignImgs(imgGroup);
  893. }
  894. };
  895. ImageLayout.prototype.watch = function () {
  896. var i, img;
  897. var obj = this;
  898. var results_nodes = d.querySelectorAll(this.results_selector);
  899. var results_length = results_nodes.length;
  900. function throttleAlign() {
  901. if (obj.isAlignDone) {
  902. obj.isAlignDone = false;
  903. setTimeout(function () {
  904. obj.align();
  905. obj.isAlignDone = true;
  906. }, 100);
  907. }
  908. }
  909. w.addEventListener('pageshow', throttleAlign);
  910. w.addEventListener('load', throttleAlign);
  911. w.addEventListener('resize', throttleAlign);
  912. for (i = 0; i < results_length; i++) {
  913. img = results_nodes[i].querySelector(this.img_selector);
  914. if (img !== null && img !== undefined) {
  915. img.addEventListener('load', throttleAlign);
  916. img.addEventListener('error', throttleAlign);
  917. }
  918. }
  919. };
  920. w.searxng.ImageLayout = ImageLayout;
  921. }(window, document));
  922. ;(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){
  923. /*
  924. * @license MIT
  925. *
  926. * Autocomplete.js v2.7.1
  927. * Developed by Baptiste Donaux
  928. * http://autocomplete-js.com
  929. *
  930. * (c) 2017, Baptiste Donaux
  931. */
  932. "use strict";
  933. var ConditionOperator;
  934. (function (ConditionOperator) {
  935. ConditionOperator[ConditionOperator["AND"] = 0] = "AND";
  936. ConditionOperator[ConditionOperator["OR"] = 1] = "OR";
  937. })(ConditionOperator || (ConditionOperator = {}));
  938. var EventType;
  939. (function (EventType) {
  940. EventType[EventType["KEYDOWN"] = 0] = "KEYDOWN";
  941. EventType[EventType["KEYUP"] = 1] = "KEYUP";
  942. })(EventType || (EventType = {}));
  943. /**
  944. * Core
  945. *
  946. * @class
  947. * @author Baptiste Donaux <baptiste.donaux@gmail.com> @baptistedonaux
  948. */
  949. var AutoComplete = /** @class */ (function () {
  950. // Constructor
  951. function AutoComplete(params, selector) {
  952. if (params === void 0) { params = {}; }
  953. if (selector === void 0) { selector = "[data-autocomplete]"; }
  954. if (Array.isArray(selector)) {
  955. selector.forEach(function (s) {
  956. new AutoComplete(params, s);
  957. });
  958. }
  959. else if (typeof selector == "string") {
  960. var elements = document.querySelectorAll(selector);
  961. Array.prototype.forEach.call(elements, function (input) {
  962. new AutoComplete(params, input);
  963. });
  964. }
  965. else {
  966. var specificParams = AutoComplete.merge(AutoComplete.defaults, params, {
  967. DOMResults: document.createElement("div")
  968. });
  969. AutoComplete.prototype.create(specificParams, selector);
  970. return specificParams;
  971. }
  972. }
  973. AutoComplete.prototype.create = function (params, element) {
  974. params.Input = element;
  975. if (params.Input.nodeName.match(/^INPUT$/i) && (params.Input.hasAttribute("type") === false || params.Input.getAttribute("type").match(/^TEXT|SEARCH$/i))) {
  976. params.Input.setAttribute("autocomplete", "off");
  977. params._Position(params);
  978. params.Input.parentNode.appendChild(params.DOMResults);
  979. params.$Listeners = {
  980. blur: params._Blur.bind(params),
  981. destroy: AutoComplete.prototype.destroy.bind(null, params),
  982. focus: params._Focus.bind(params),
  983. keyup: AutoComplete.prototype.event.bind(null, params, EventType.KEYUP),
  984. keydown: AutoComplete.prototype.event.bind(null, params, EventType.KEYDOWN),
  985. position: params._Position.bind(params)
  986. };
  987. for (var event in params.$Listeners) {
  988. params.Input.addEventListener(event, params.$Listeners[event]);
  989. }
  990. }
  991. };
  992. AutoComplete.prototype.getEventsByType = function (params, type) {
  993. var mappings = {};
  994. for (var key in params.KeyboardMappings) {
  995. var event = EventType.KEYUP;
  996. if (params.KeyboardMappings[key].Event !== undefined) {
  997. event = params.KeyboardMappings[key].Event;
  998. }
  999. if (event == type) {
  1000. mappings[key] = params.KeyboardMappings[key];
  1001. }
  1002. }
  1003. return mappings;
  1004. };
  1005. AutoComplete.prototype.event = function (params, type, event) {
  1006. var eventIdentifier = function (condition) {
  1007. if ((match === true && mapping.Operator == ConditionOperator.AND) || (match === false && mapping.Operator == ConditionOperator.OR)) {
  1008. condition = AutoComplete.merge({
  1009. Not: false
  1010. }, condition);
  1011. if (condition.hasOwnProperty("Is")) {
  1012. if (condition.Is == event.keyCode) {
  1013. match = !condition.Not;
  1014. }
  1015. else {
  1016. match = condition.Not;
  1017. }
  1018. }
  1019. else if (condition.hasOwnProperty("From") && condition.hasOwnProperty("To")) {
  1020. if (event.keyCode >= condition.From && event.keyCode <= condition.To) {
  1021. match = !condition.Not;
  1022. }
  1023. else {
  1024. match = condition.Not;
  1025. }
  1026. }
  1027. }
  1028. };
  1029. for (var name in AutoComplete.prototype.getEventsByType(params, type)) {
  1030. var mapping = AutoComplete.merge({
  1031. Operator: ConditionOperator.AND
  1032. }, params.KeyboardMappings[name]), match = ConditionOperator.AND == mapping.Operator;
  1033. mapping.Conditions.forEach(eventIdentifier);
  1034. if (match === true) {
  1035. mapping.Callback.call(params, event);
  1036. }
  1037. }
  1038. };
  1039. AutoComplete.prototype.makeRequest = function (params, callback, callbackErr) {
  1040. var propertyHttpHeaders = Object.getOwnPropertyNames(params.HttpHeaders), request = new XMLHttpRequest(), method = params._HttpMethod(), url = params._Url(), queryParams = params._Pre(), queryParamsStringify = encodeURIComponent(params._QueryArg()) + "=" + encodeURIComponent(queryParams);
  1041. if (method.match(/^GET$/i)) {
  1042. if (url.indexOf("?") !== -1) {
  1043. url += "&" + queryParamsStringify;
  1044. }
  1045. else {
  1046. url += "?" + queryParamsStringify;
  1047. }
  1048. }
  1049. request.open(method, url, true);
  1050. for (var i = propertyHttpHeaders.length - 1; i >= 0; i--) {
  1051. request.setRequestHeader(propertyHttpHeaders[i], params.HttpHeaders[propertyHttpHeaders[i]]);
  1052. }
  1053. request.onreadystatechange = function () {
  1054. if (request.readyState == 4 && request.status == 200) {
  1055. params.$Cache[queryParams] = request.response;
  1056. callback(request.response);
  1057. }
  1058. else if (request.status >= 400) {
  1059. callbackErr();
  1060. }
  1061. };
  1062. return request;
  1063. };
  1064. AutoComplete.prototype.ajax = function (params, request, timeout) {
  1065. if (timeout === void 0) { timeout = true; }
  1066. if (params.$AjaxTimer) {
  1067. window.clearTimeout(params.$AjaxTimer);
  1068. }
  1069. if (timeout === true) {
  1070. params.$AjaxTimer = window.setTimeout(AutoComplete.prototype.ajax.bind(null, params, request, false), params.Delay);
  1071. }
  1072. else {
  1073. if (params.Request) {
  1074. params.Request.abort();
  1075. }
  1076. params.Request = request;
  1077. params.Request.send(params._QueryArg() + "=" + params._Pre());
  1078. }
  1079. };
  1080. AutoComplete.prototype.cache = function (params, callback, callbackErr) {
  1081. var response = params._Cache(params._Pre());
  1082. if (response === undefined) {
  1083. var request = AutoComplete.prototype.makeRequest(params, callback, callbackErr);
  1084. AutoComplete.prototype.ajax(params, request);
  1085. }
  1086. else {
  1087. callback(response);
  1088. }
  1089. };
  1090. AutoComplete.prototype.destroy = function (params) {
  1091. for (var event in params.$Listeners) {
  1092. params.Input.removeEventListener(event, params.$Listeners[event]);
  1093. }
  1094. params.DOMResults.parentNode.removeChild(params.DOMResults);
  1095. };
  1096. AutoComplete.merge = function () {
  1097. var merge = {}, tmp;
  1098. for (var i = 0; i < arguments.length; i++) {
  1099. for (tmp in arguments[i]) {
  1100. merge[tmp] = arguments[i][tmp];
  1101. }
  1102. }
  1103. return merge;
  1104. };
  1105. AutoComplete.defaults = {
  1106. Delay: 150,
  1107. EmptyMessage: "No result here",
  1108. Highlight: {
  1109. getRegex: function (value) {
  1110. return new RegExp(value, "ig");
  1111. },
  1112. transform: function (value) {
  1113. return "<strong>" + value + "</strong>";
  1114. }
  1115. },
  1116. HttpHeaders: {
  1117. "Content-type": "application/x-www-form-urlencoded"
  1118. },
  1119. Limit: 0,
  1120. MinChars: 0,
  1121. HttpMethod: "GET",
  1122. QueryArg: "q",
  1123. Url: null,
  1124. KeyboardMappings: {
  1125. "Enter": {
  1126. Conditions: [{
  1127. Is: 13,
  1128. Not: false
  1129. }],
  1130. Callback: function (event) {
  1131. if (this.DOMResults.getAttribute("class").indexOf("open") != -1) {
  1132. var liActive = this.DOMResults.querySelector("li.active");
  1133. if (liActive !== null) {
  1134. event.preventDefault();
  1135. this._Select(liActive);
  1136. this.DOMResults.setAttribute("class", "autocomplete");
  1137. }
  1138. }
  1139. },
  1140. Operator: ConditionOperator.AND,
  1141. Event: EventType.KEYDOWN
  1142. },
  1143. "KeyUpAndDown_down": {
  1144. Conditions: [{
  1145. Is: 38,
  1146. Not: false
  1147. },
  1148. {
  1149. Is: 40,
  1150. Not: false
  1151. }],
  1152. Callback: function (event) {
  1153. event.preventDefault();
  1154. },
  1155. Operator: ConditionOperator.OR,
  1156. Event: EventType.KEYDOWN
  1157. },
  1158. "KeyUpAndDown_up": {
  1159. Conditions: [{
  1160. Is: 38,
  1161. Not: false
  1162. },
  1163. {
  1164. Is: 40,
  1165. Not: false
  1166. }],
  1167. Callback: function (event) {
  1168. event.preventDefault();
  1169. 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");
  1170. if (active) {
  1171. var currentIndex = Array.prototype.indexOf.call(active.parentNode.children, active), position = currentIndex + (event.keyCode - 39), lisCount = this.DOMResults.getElementsByTagName("li").length;
  1172. if (position < 0) {
  1173. position = lisCount - 1;
  1174. }
  1175. else if (position >= lisCount) {
  1176. position = 0;
  1177. }
  1178. active.classList.remove("active");
  1179. active.parentElement.children.item(position).classList.add("active");
  1180. }
  1181. else if (last && event.keyCode == 38) {
  1182. last.classList.add("active");
  1183. }
  1184. else if (first) {
  1185. first.classList.add("active");
  1186. }
  1187. },
  1188. Operator: ConditionOperator.OR,
  1189. Event: EventType.KEYUP
  1190. },
  1191. "AlphaNum": {
  1192. Conditions: [{
  1193. Is: 13,
  1194. Not: true
  1195. }, {
  1196. From: 35,
  1197. To: 40,
  1198. Not: true
  1199. }],
  1200. Callback: function () {
  1201. var oldValue = this.Input.getAttribute("data-autocomplete-old-value"), currentValue = this._Pre();
  1202. if (currentValue !== "" && currentValue.length >= this._MinChars()) {
  1203. if (!oldValue || currentValue != oldValue) {
  1204. this.DOMResults.setAttribute("class", "autocomplete open");
  1205. }
  1206. AutoComplete.prototype.cache(this, function (response) {
  1207. this._Render(this._Post(response));
  1208. this._Open();
  1209. }.bind(this), this._Error);
  1210. }
  1211. else {
  1212. this._Close();
  1213. }
  1214. },
  1215. Operator: ConditionOperator.AND,
  1216. Event: EventType.KEYUP
  1217. }
  1218. },
  1219. DOMResults: null,
  1220. Request: null,
  1221. Input: null,
  1222. /**
  1223. * Return the message when no result returns
  1224. */
  1225. _EmptyMessage: function () {
  1226. var emptyMessage = "";
  1227. if (this.Input.hasAttribute("data-autocomplete-empty-message")) {
  1228. emptyMessage = this.Input.getAttribute("data-autocomplete-empty-message");
  1229. }
  1230. else if (this.EmptyMessage !== false) {
  1231. emptyMessage = this.EmptyMessage;
  1232. }
  1233. else {
  1234. emptyMessage = "";
  1235. }
  1236. return emptyMessage;
  1237. },
  1238. /**
  1239. * Returns the maximum number of results
  1240. */
  1241. _Limit: function () {
  1242. var limit = this.Input.getAttribute("data-autocomplete-limit");
  1243. if (isNaN(limit) || limit === null) {
  1244. return this.Limit;
  1245. }
  1246. return parseInt(limit, 10);
  1247. },
  1248. /**
  1249. * Returns the minimum number of characters entered before firing ajax
  1250. */
  1251. _MinChars: function () {
  1252. var minchars = this.Input.getAttribute("data-autocomplete-minchars");
  1253. if (isNaN(minchars) || minchars === null) {
  1254. return this.MinChars;
  1255. }
  1256. return parseInt(minchars, 10);
  1257. },
  1258. /**
  1259. * Apply transformation on labels response
  1260. */
  1261. _Highlight: function (label) {
  1262. return label.replace(this.Highlight.getRegex(this._Pre()), this.Highlight.transform);
  1263. },
  1264. /**
  1265. * Returns the HHTP method to use
  1266. */
  1267. _HttpMethod: function () {
  1268. if (this.Input.hasAttribute("data-autocomplete-method")) {
  1269. return this.Input.getAttribute("data-autocomplete-method");
  1270. }
  1271. return this.HttpMethod;
  1272. },
  1273. /**
  1274. * Returns the query param to use
  1275. */
  1276. _QueryArg: function () {
  1277. if (this.Input.hasAttribute("data-autocomplete-param-name")) {
  1278. return this.Input.getAttribute("data-autocomplete-param-name");
  1279. }
  1280. return this.QueryArg;
  1281. },
  1282. /**
  1283. * Returns the URL to use for AJAX request
  1284. */
  1285. _Url: function () {
  1286. if (this.Input.hasAttribute("data-autocomplete")) {
  1287. return this.Input.getAttribute("data-autocomplete");
  1288. }
  1289. return this.Url;
  1290. },
  1291. /**
  1292. * Manage the close
  1293. */
  1294. _Blur: function (now) {
  1295. if (now === void 0) { now = false; }
  1296. if (now) {
  1297. this._Close();
  1298. }
  1299. else {
  1300. var params = this;
  1301. setTimeout(function () {
  1302. params._Blur(true);
  1303. }, 150);
  1304. }
  1305. },
  1306. /**
  1307. * Manage the cache
  1308. */
  1309. _Cache: function (value) {
  1310. return this.$Cache[value];
  1311. },
  1312. /**
  1313. * Manage the open
  1314. */
  1315. _Focus: function () {
  1316. var oldValue = this.Input.getAttribute("data-autocomplete-old-value");
  1317. if ((!oldValue || this.Input.value != oldValue) && this._MinChars() <= this.Input.value.length) {
  1318. this.DOMResults.setAttribute("class", "autocomplete open");
  1319. }
  1320. },
  1321. /**
  1322. * Bind all results item if one result is opened
  1323. */
  1324. _Open: function () {
  1325. var params = this;
  1326. Array.prototype.forEach.call(this.DOMResults.getElementsByTagName("li"), function (li) {
  1327. if (li.getAttribute("class") != "locked") {
  1328. li.onclick = function () {
  1329. params._Select(li);
  1330. };
  1331. }
  1332. });
  1333. },
  1334. _Close: function () {
  1335. this.DOMResults.setAttribute("class", "autocomplete");
  1336. },
  1337. /**
  1338. * Position the results HTML element
  1339. */
  1340. _Position: function () {
  1341. this.DOMResults.setAttribute("class", "autocomplete");
  1342. this.DOMResults.setAttribute("style", "top:" + (this.Input.offsetTop + this.Input.offsetHeight) + "px;left:" + this.Input.offsetLeft + "px;width:" + this.Input.clientWidth + "px;");
  1343. },
  1344. /**
  1345. * Execute the render of results DOM element
  1346. */
  1347. _Render: function (response) {
  1348. var ul;
  1349. if (typeof response == "string") {
  1350. ul = this._RenderRaw(response);
  1351. }
  1352. else {
  1353. ul = this._RenderResponseItems(response);
  1354. }
  1355. if (this.DOMResults.hasChildNodes()) {
  1356. this.DOMResults.removeChild(this.DOMResults.childNodes[0]);
  1357. }
  1358. this.DOMResults.appendChild(ul);
  1359. },
  1360. /**
  1361. * ResponseItems[] rendering
  1362. */
  1363. _RenderResponseItems: function (response) {
  1364. var ul = document.createElement("ul"), li = document.createElement("li"), limit = this._Limit();
  1365. // Order
  1366. if (limit < 0) {
  1367. response = response.reverse();
  1368. }
  1369. else if (limit === 0) {
  1370. limit = response.length;
  1371. }
  1372. for (var item = 0; item < Math.min(Math.abs(limit), response.length); item++) {
  1373. li.innerHTML = response[item].Label;
  1374. li.setAttribute("data-autocomplete-value", response[item].Value);
  1375. ul.appendChild(li);
  1376. li = document.createElement("li");
  1377. }
  1378. return ul;
  1379. },
  1380. /**
  1381. * string response rendering (RAW HTML)
  1382. */
  1383. _RenderRaw: function (response) {
  1384. var ul = document.createElement("ul"), li = document.createElement("li");
  1385. if (response.length > 0) {
  1386. this.DOMResults.innerHTML = response;
  1387. }
  1388. else {
  1389. var emptyMessage = this._EmptyMessage();
  1390. if (emptyMessage !== "") {
  1391. li.innerHTML = emptyMessage;
  1392. li.setAttribute("class", "locked");
  1393. ul.appendChild(li);
  1394. }
  1395. }
  1396. return ul;
  1397. },
  1398. /**
  1399. * Deal with request response
  1400. */
  1401. _Post: function (response) {
  1402. try {
  1403. var returnResponse = [];
  1404. //JSON return
  1405. var json = JSON.parse(response);
  1406. if (Object.keys(json).length === 0) {
  1407. return "";
  1408. }
  1409. if (Array.isArray(json)) {
  1410. for (var i = 0; i < Object.keys(json).length; i++) {
  1411. returnResponse[returnResponse.length] = { "Value": json[i], "Label": this._Highlight(json[i]) };
  1412. }
  1413. }
  1414. else {
  1415. for (var value in json) {
  1416. returnResponse.push({
  1417. "Value": value,
  1418. "Label": this._Highlight(json[value])
  1419. });
  1420. }
  1421. }
  1422. return returnResponse;
  1423. }
  1424. catch (event) {
  1425. //HTML return
  1426. return response;
  1427. }
  1428. },
  1429. /**
  1430. * Return the autocomplete value to send (before request)
  1431. */
  1432. _Pre: function () {
  1433. return this.Input.value;
  1434. },
  1435. /**
  1436. * Choice one result item
  1437. */
  1438. _Select: function (item) {
  1439. if (item.hasAttribute("data-autocomplete-value")) {
  1440. this.Input.value = item.getAttribute("data-autocomplete-value");
  1441. }
  1442. else {
  1443. this.Input.value = item.innerHTML;
  1444. }
  1445. this.Input.setAttribute("data-autocomplete-old-value", this.Input.value);
  1446. },
  1447. /**
  1448. * Handle HTTP error on the request
  1449. */
  1450. _Error: function () {
  1451. },
  1452. $AjaxTimer: null,
  1453. $Cache: {},
  1454. $Listeners: {}
  1455. };
  1456. return AutoComplete;
  1457. }());
  1458. module.exports = AutoComplete;
  1459. },{}]},{},[1])(1)
  1460. });