searxng.js 53 KB

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