searx.js 50 KB

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