searx.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  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, callback) {
  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. element.parentNode.insertBefore(newNode, referenceNode);
  135. };
  136. searx.insertAfter = function(newNode, referenceNode) {
  137. referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
  138. };
  139. searx.on('.close', 'click', function(e) {
  140. var el = e.target || e.srcElement;
  141. this.parentNode.classList.add('invisible');
  142. });
  143. return searx;
  144. })(window, document);
  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: pageButtonClick(0),
  225. des: 'go to previous page',
  226. cat: 'Results'
  227. },
  228. 78: {
  229. key: 'n',
  230. fun: pageButtonClick(1),
  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 (vimKeys.hasOwnProperty(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(num) {
  351. return function() {
  352. var buttons = $('div#pagination button[type="submit"]');
  353. if (buttons.length !== 2) {
  354. console.log('page navigation with this theme is not supported');
  355. return;
  356. }
  357. if (num >= 0 && num < buttons.length) {
  358. buttons[num].click();
  359. } else {
  360. console.log('pageButtonClick(): invalid argument');
  361. }
  362. };
  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. var body = document.getElementsByTagName('body')[0];
  468. body.appendChild(helpPanel);
  469. } else {
  470. // togggle hidden
  471. helpPanel.classList.toggle('invisible');
  472. return;
  473. }
  474. }
  475. });
  476. ;/**
  477. * searx is free software: you can redistribute it and/or modify
  478. * it under the terms of the GNU Affero General Public License as published by
  479. * the Free Software Foundation, either version 3 of the License, or
  480. * (at your option) any later version.
  481. *
  482. * searx is distributed in the hope that it will be useful,
  483. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  484. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  485. * GNU Affero General Public License for more details.
  486. *
  487. * You should have received a copy of the GNU Affero General Public License
  488. * along with searx. If not, see < http://www.gnu.org/licenses/ >.
  489. *
  490. * (C) 2014 by Thomas Pointhuber, <thomas.pointhuber@gmx.at>
  491. * (C) 2017 by Alexandre Flament, <alex@al-f.net>
  492. */
  493. (function (w, d, searx) {
  494. 'use strict';
  495. searx.ready(function () {
  496. searx.on('.searx_init_map', 'click', function(event) {
  497. // no more request
  498. this.classList.remove("searx_init_map");
  499. //
  500. var leaflet_target = this.dataset.leafletTarget;
  501. var map_lon = parseFloat(this.dataset.mapLon);
  502. var map_lat = parseFloat(this.dataset.mapLat);
  503. var map_zoom = parseFloat(this.dataset.mapZoom);
  504. var map_boundingbox = JSON.parse(this.dataset.mapBoundingbox);
  505. var map_geojson = JSON.parse(this.dataset.mapGeojson);
  506. searx.loadStyle('css/leaflet.css');
  507. searx.loadScript('js/leaflet.js', function() {
  508. var map_bounds = null;
  509. if(map_boundingbox) {
  510. var southWest = L.latLng(map_boundingbox[0], map_boundingbox[2]);
  511. var northEast = L.latLng(map_boundingbox[1], map_boundingbox[3]);
  512. map_bounds = L.latLngBounds(southWest, northEast);
  513. }
  514. // init map
  515. var map = L.map(leaflet_target);
  516. // create the tile layer with correct attribution
  517. var osmMapnikUrl='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
  518. var osmMapnikAttrib='Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors';
  519. var osmMapnik = new L.TileLayer(osmMapnikUrl, {minZoom: 1, maxZoom: 19, attribution: osmMapnikAttrib});
  520. var osmWikimediaUrl='https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png';
  521. var osmWikimediaAttrib = 'Wikimedia maps beta | Maps data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors';
  522. var osmWikimedia = new L.TileLayer(osmWikimediaUrl, {minZoom: 1, maxZoom: 19, attribution: osmWikimediaAttrib});
  523. // init map view
  524. if(map_bounds) {
  525. // TODO hack: https://github.com/Leaflet/Leaflet/issues/2021
  526. // Still useful ?
  527. setTimeout(function () {
  528. map.fitBounds(map_bounds, {
  529. maxZoom:17
  530. });
  531. }, 0);
  532. } else if (map_lon && map_lat) {
  533. if(map_zoom) {
  534. map.setView(new L.latLng(map_lat, map_lon),map_zoom);
  535. } else {
  536. map.setView(new L.latLng(map_lat, map_lon),8);
  537. }
  538. }
  539. map.addLayer(osmMapnik);
  540. var baseLayers = {
  541. "OSM Mapnik": osmMapnik/*,
  542. "OSM Wikimedia": osmWikimedia*/
  543. };
  544. L.control.layers(baseLayers).addTo(map);
  545. if(map_geojson) {
  546. L.geoJson(map_geojson).addTo(map);
  547. } /*else if(map_bounds) {
  548. L.rectangle(map_bounds, {color: "#ff7800", weight: 3, fill:false}).addTo(map);
  549. }*/
  550. });
  551. // this event occour only once per element
  552. event.preventDefault();
  553. });
  554. });
  555. })(window, document, window.searx);
  556. ;/**
  557. * searx is free software: you can redistribute it and/or modify
  558. * it under the terms of the GNU Affero General Public License as published by
  559. * the Free Software Foundation, either version 3 of the License, or
  560. * (at your option) any later version.
  561. *
  562. * searx is distributed in the hope that it will be useful,
  563. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  564. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  565. * GNU Affero General Public License for more details.
  566. *
  567. * You should have received a copy of the GNU Affero General Public License
  568. * along with searx. If not, see < http://www.gnu.org/licenses/ >.
  569. *
  570. * (C) 2017 by Alexandre Flament, <alex@al-f.net>
  571. */
  572. (function(w, d, searx) {
  573. 'use strict';
  574. searx.ready(function() {
  575. searx.image_thumbnail_layout = new searx.ImageLayout('#urls', '#urls .result-images', 'img.image_thumbnail', 10, 200);
  576. searx.image_thumbnail_layout.watch();
  577. searx.on('.btn-collapse', 'click', function(event) {
  578. var btnLabelCollapsed = this.getAttribute('data-btn-text-collapsed');
  579. var btnLabelNotCollapsed = this.getAttribute('data-btn-text-not-collapsed');
  580. var target = this.getAttribute('data-target');
  581. var targetElement = d.querySelector(target);
  582. var html = this.innerHTML;
  583. if (this.classList.contains('collapsed')) {
  584. html = html.replace(btnLabelCollapsed, btnLabelNotCollapsed);
  585. } else {
  586. html = html.replace(btnLabelNotCollapsed, btnLabelCollapsed);
  587. }
  588. this.innerHTML = html;
  589. this.classList.toggle('collapsed');
  590. targetElement.classList.toggle('invisible');
  591. });
  592. searx.on('.media-loader', 'click', function(event) {
  593. var target = this.getAttribute('data-target');
  594. var iframe_load = d.querySelector(target + ' > iframe');
  595. var srctest = iframe_load.getAttribute('src');
  596. if (srctest === null || srctest === undefined || srctest === false) {
  597. iframe_load.setAttribute('src', iframe_load.getAttribute('data-src'));
  598. }
  599. });
  600. w.addEventListener('scroll', function() {
  601. var e = d.getElementById('backToTop'),
  602. scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  603. if (e !== null) {
  604. if (scrollTop >= 200) {
  605. e.style.opacity = 1;
  606. } else {
  607. e.style.opacity = 0;
  608. }
  609. }
  610. });
  611. });
  612. })(window, document, window.searx);
  613. ;/**
  614. * searx is free software: you can redistribute it and/or modify
  615. * it under the terms of the GNU Affero General Public License as published by
  616. * the Free Software Foundation, either version 3 of the License, or
  617. * (at your option) any later version.
  618. *
  619. * searx is distributed in the hope that it will be useful,
  620. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  621. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  622. * GNU Affero General Public License for more details.
  623. *
  624. * You should have received a copy of the GNU Affero General Public License
  625. * along with searx. If not, see < http://www.gnu.org/licenses/ >.
  626. *
  627. * (C) 2017 by Alexandre Flament, <alex@al-f.net>
  628. */
  629. (function(w, d, searx) {
  630. 'use strict';
  631. var firstFocus = true, qinput_id = "q", qinput;
  632. function placeCursorAtEnd(element) {
  633. if (element.setSelectionRange) {
  634. var len = element.value.length;
  635. element.setSelectionRange(len, len);
  636. }
  637. }
  638. function submitIfQuery() {
  639. if (qinput.value.length > 0) {
  640. var search = document.getElementById('search');
  641. setTimeout(search.submit.bind(search), 0);
  642. }
  643. }
  644. function createClearButton(qinput) {
  645. var cs = document.getElementById('clear_search');
  646. var updateClearButton = function() {
  647. if (qinput.value.length === 0) {
  648. cs.classList.add("empty");
  649. } else {
  650. cs.classList.remove("empty");
  651. }
  652. };
  653. // update status, event listener
  654. updateClearButton();
  655. cs.addEventListener('click', function() {
  656. qinput.value='';
  657. qinput.focus();
  658. updateClearButton();
  659. });
  660. qinput.addEventListener('keyup', updateClearButton, false);
  661. }
  662. searx.ready(function() {
  663. qinput = d.getElementById(qinput_id);
  664. function placeCursorAtEndOnce(e) {
  665. if (firstFocus) {
  666. placeCursorAtEnd(qinput);
  667. firstFocus = false;
  668. } else {
  669. // e.preventDefault();
  670. }
  671. }
  672. if (qinput !== null) {
  673. // clear button
  674. createClearButton(qinput);
  675. // autocompleter
  676. if (searx.autocompleter) {
  677. searx.autocomplete = AutoComplete.call(w, {
  678. Url: "./autocompleter",
  679. EmptyMessage: searx.translations.no_item_found,
  680. HttpMethod: searx.method,
  681. HttpHeaders: {
  682. "Content-type": "application/x-www-form-urlencoded",
  683. "X-Requested-With": "XMLHttpRequest"
  684. },
  685. MinChars: 4,
  686. Delay: 300,
  687. }, "#" + qinput_id);
  688. // hack, see : https://github.com/autocompletejs/autocomplete.js/issues/37
  689. w.addEventListener('resize', function() {
  690. var event = new CustomEvent("position");
  691. qinput.dispatchEvent(event);
  692. });
  693. }
  694. qinput.addEventListener('focus', placeCursorAtEndOnce, false);
  695. qinput.focus();
  696. }
  697. // vanilla js version of search_on_category_select.js
  698. if (qinput !== null && searx.search_on_category_select) {
  699. d.querySelector('.help').className='invisible';
  700. searx.on('#categories input', 'change', function(e) {
  701. var i, categories = d.querySelectorAll('#categories input[type="checkbox"]');
  702. for(i=0; i<categories.length; i++) {
  703. if (categories[i] !== this && categories[i].checked) {
  704. categories[i].click();
  705. }
  706. }
  707. if (! this.checked) {
  708. this.click();
  709. }
  710. submitIfQuery();
  711. return false;
  712. });
  713. searx.on(d.getElementById('time_range'), 'change', submitIfQuery);
  714. searx.on(d.getElementById('language'), 'change', submitIfQuery);
  715. }
  716. });
  717. })(window, document, window.searx);
  718. ;/**
  719. *
  720. * Google Image Layout v0.0.1
  721. * Description, by Anh Trinh.
  722. * Heavily modified for searx
  723. * https://ptgamr.github.io/2014-09-12-google-image-layout/
  724. * https://ptgamr.github.io/google-image-layout/src/google-image-layout.js
  725. *
  726. * @license Free to use under the MIT License.
  727. *
  728. */
  729. (function (w, d) {
  730. function ImageLayout(container_selector, results_selector, img_selector, margin, maxHeight) {
  731. this.container_selector = container_selector;
  732. this.results_selector = results_selector;
  733. this.img_selector = img_selector;
  734. this.margin = margin;
  735. this.maxHeight = maxHeight;
  736. this.isAlignDone = true;
  737. }
  738. /**
  739. * Get the height that make all images fit the container
  740. *
  741. * width = w1 + w2 + w3 + ... = r1*h + r2*h + r3*h + ...
  742. *
  743. * @param {[type]} images the images to be calculated
  744. * @param {[type]} width the container witdth
  745. * @param {[type]} margin the margin between each image
  746. *
  747. * @return {[type]} the height
  748. */
  749. ImageLayout.prototype._getHeigth = function (images, width) {
  750. var i, img;
  751. var r = 0;
  752. for (i = 0; i < images.length; i++) {
  753. img = images[i];
  754. if ((img.naturalWidth > 0) && (img.naturalHeight > 0)) {
  755. r += img.naturalWidth / img.naturalHeight;
  756. } else {
  757. // assume that not loaded images are square
  758. r += 1;
  759. }
  760. }
  761. return (width - images.length * this.margin) / r; //have to round down because Firefox will automatically roundup value with number of decimals > 3
  762. };
  763. ImageLayout.prototype._setSize = function (images, height) {
  764. var i, img, imgWidth;
  765. var imagesLength = images.length, resultNode;
  766. for (i = 0; i < imagesLength; i++) {
  767. img = images[i];
  768. if ((img.naturalWidth > 0) && (img.naturalHeight > 0)) {
  769. imgWidth = height * img.naturalWidth / img.naturalHeight;
  770. } else {
  771. // not loaded image : make it square as _getHeigth said it
  772. imgWidth = height;
  773. }
  774. img.style.width = imgWidth + 'px';
  775. img.style.height = height + 'px';
  776. img.style.marginLeft = '3px';
  777. img.style.marginTop = '3px';
  778. img.style.marginRight = this.margin - 7 + 'px'; // -4 is the negative margin of the inline element
  779. img.style.marginBottom = this.margin - 7 + 'px';
  780. resultNode = img.parentNode.parentNode;
  781. if (!resultNode.classList.contains('js')) {
  782. resultNode.classList.add('js');
  783. }
  784. }
  785. };
  786. ImageLayout.prototype._alignImgs = function (imgGroup) {
  787. var isSearching, slice, i, h;
  788. var containerElement = d.querySelector(this.container_selector);
  789. var containerCompStyles = window.getComputedStyle(containerElement);
  790. var containerPaddingLeft = parseInt(containerCompStyles.getPropertyValue('padding-left'), 10);
  791. var containerPaddingRight = parseInt(containerCompStyles.getPropertyValue('padding-right'), 10);
  792. var containerWidth = containerElement.clientWidth - containerPaddingLeft - containerPaddingRight;
  793. while (imgGroup.length > 0) {
  794. isSearching = true;
  795. for (i = 1; i <= imgGroup.length && isSearching; i++) {
  796. slice = imgGroup.slice(0, i);
  797. h = this._getHeigth(slice, containerWidth);
  798. if (h < this.maxHeight) {
  799. this._setSize(slice, h);
  800. // continue with the remaining images
  801. imgGroup = imgGroup.slice(i);
  802. isSearching = false;
  803. }
  804. }
  805. if (isSearching) {
  806. this._setSize(slice, Math.min(this.maxHeight, h));
  807. break;
  808. }
  809. }
  810. };
  811. ImageLayout.prototype.align = function () {
  812. var i;
  813. var results_selectorNode = d.querySelectorAll(this.results_selector);
  814. var results_length = results_selectorNode.length;
  815. var previous = null;
  816. var current = null;
  817. var imgGroup = [];
  818. for (i = 0; i < results_length; i++) {
  819. current = results_selectorNode[i];
  820. if (current.previousElementSibling !== previous && imgGroup.length > 0) {
  821. // the current image is not connected to previous one
  822. // so the current image is the start of a new group of images.
  823. // so call _alignImgs to align the current group
  824. this._alignImgs(imgGroup);
  825. // and start a new empty group of images
  826. imgGroup = [];
  827. }
  828. // add the current image to the group (only the img tag)
  829. imgGroup.push(current.querySelector(this.img_selector));
  830. // update the previous variable
  831. previous = current;
  832. }
  833. // align the remaining images
  834. if (imgGroup.length > 0) {
  835. this._alignImgs(imgGroup);
  836. }
  837. };
  838. ImageLayout.prototype.watch = function () {
  839. var i, img;
  840. var obj = this;
  841. var results_nodes = d.querySelectorAll(this.results_selector);
  842. var results_length = results_nodes.length;
  843. function throttleAlign() {
  844. if (obj.isAlignDone) {
  845. obj.isAlignDone = false;
  846. setTimeout(function () {
  847. obj.align();
  848. obj.isAlignDone = true;
  849. }, 100);
  850. }
  851. }
  852. w.addEventListener('pageshow', throttleAlign);
  853. w.addEventListener('load', throttleAlign);
  854. w.addEventListener('resize', throttleAlign);
  855. for (i = 0; i < results_length; i++) {
  856. img = results_nodes[i].querySelector(this.img_selector);
  857. if (img !== null && img !== undefined) {
  858. img.addEventListener('load', throttleAlign);
  859. img.addEventListener('error', throttleAlign);
  860. }
  861. }
  862. };
  863. w.searx.ImageLayout = ImageLayout;
  864. }(window, document));
  865. ;(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){
  866. /*
  867. * @license MIT
  868. *
  869. * Autocomplete.js v2.7.1
  870. * Developed by Baptiste Donaux
  871. * http://autocomplete-js.com
  872. *
  873. * (c) 2017, Baptiste Donaux
  874. */
  875. "use strict";
  876. var ConditionOperator;
  877. (function (ConditionOperator) {
  878. ConditionOperator[ConditionOperator["AND"] = 0] = "AND";
  879. ConditionOperator[ConditionOperator["OR"] = 1] = "OR";
  880. })(ConditionOperator || (ConditionOperator = {}));
  881. var EventType;
  882. (function (EventType) {
  883. EventType[EventType["KEYDOWN"] = 0] = "KEYDOWN";
  884. EventType[EventType["KEYUP"] = 1] = "KEYUP";
  885. })(EventType || (EventType = {}));
  886. /**
  887. * Core
  888. *
  889. * @class
  890. * @author Baptiste Donaux <baptiste.donaux@gmail.com> @baptistedonaux
  891. */
  892. var AutoComplete = /** @class */ (function () {
  893. // Constructor
  894. function AutoComplete(params, selector) {
  895. if (params === void 0) { params = {}; }
  896. if (selector === void 0) { selector = "[data-autocomplete]"; }
  897. if (Array.isArray(selector)) {
  898. selector.forEach(function (s) {
  899. new AutoComplete(params, s);
  900. });
  901. }
  902. else if (typeof selector == "string") {
  903. var elements = document.querySelectorAll(selector);
  904. Array.prototype.forEach.call(elements, function (input) {
  905. new AutoComplete(params, input);
  906. });
  907. }
  908. else {
  909. var specificParams = AutoComplete.merge(AutoComplete.defaults, params, {
  910. DOMResults: document.createElement("div")
  911. });
  912. AutoComplete.prototype.create(specificParams, selector);
  913. return specificParams;
  914. }
  915. }
  916. AutoComplete.prototype.create = function (params, element) {
  917. params.Input = element;
  918. if (params.Input.nodeName.match(/^INPUT$/i) && (params.Input.hasAttribute("type") === false || params.Input.getAttribute("type").match(/^TEXT|SEARCH$/i))) {
  919. params.Input.setAttribute("autocomplete", "off");
  920. params._Position(params);
  921. params.Input.parentNode.appendChild(params.DOMResults);
  922. params.$Listeners = {
  923. blur: params._Blur.bind(params),
  924. destroy: AutoComplete.prototype.destroy.bind(null, params),
  925. focus: params._Focus.bind(params),
  926. keyup: AutoComplete.prototype.event.bind(null, params, EventType.KEYUP),
  927. keydown: AutoComplete.prototype.event.bind(null, params, EventType.KEYDOWN),
  928. position: params._Position.bind(params)
  929. };
  930. for (var event in params.$Listeners) {
  931. params.Input.addEventListener(event, params.$Listeners[event]);
  932. }
  933. }
  934. };
  935. AutoComplete.prototype.getEventsByType = function (params, type) {
  936. var mappings = {};
  937. for (var key in params.KeyboardMappings) {
  938. var event = EventType.KEYUP;
  939. if (params.KeyboardMappings[key].Event !== undefined) {
  940. event = params.KeyboardMappings[key].Event;
  941. }
  942. if (event == type) {
  943. mappings[key] = params.KeyboardMappings[key];
  944. }
  945. }
  946. return mappings;
  947. };
  948. AutoComplete.prototype.event = function (params, type, event) {
  949. var eventIdentifier = function (condition) {
  950. if ((match === true && mapping.Operator == ConditionOperator.AND) || (match === false && mapping.Operator == ConditionOperator.OR)) {
  951. condition = AutoComplete.merge({
  952. Not: false
  953. }, condition);
  954. if (condition.hasOwnProperty("Is")) {
  955. if (condition.Is == event.keyCode) {
  956. match = !condition.Not;
  957. }
  958. else {
  959. match = condition.Not;
  960. }
  961. }
  962. else if (condition.hasOwnProperty("From") && condition.hasOwnProperty("To")) {
  963. if (event.keyCode >= condition.From && event.keyCode <= condition.To) {
  964. match = !condition.Not;
  965. }
  966. else {
  967. match = condition.Not;
  968. }
  969. }
  970. }
  971. };
  972. for (var name in AutoComplete.prototype.getEventsByType(params, type)) {
  973. var mapping = AutoComplete.merge({
  974. Operator: ConditionOperator.AND
  975. }, params.KeyboardMappings[name]), match = ConditionOperator.AND == mapping.Operator;
  976. mapping.Conditions.forEach(eventIdentifier);
  977. if (match === true) {
  978. mapping.Callback.call(params, event);
  979. }
  980. }
  981. };
  982. AutoComplete.prototype.makeRequest = function (params, callback, callbackErr) {
  983. var propertyHttpHeaders = Object.getOwnPropertyNames(params.HttpHeaders), request = new XMLHttpRequest(), method = params._HttpMethod(), url = params._Url(), queryParams = params._Pre(), queryParamsStringify = encodeURIComponent(params._QueryArg()) + "=" + encodeURIComponent(queryParams);
  984. if (method.match(/^GET$/i)) {
  985. if (url.indexOf("?") !== -1) {
  986. url += "&" + queryParamsStringify;
  987. }
  988. else {
  989. url += "?" + queryParamsStringify;
  990. }
  991. }
  992. request.open(method, url, true);
  993. for (var i = propertyHttpHeaders.length - 1; i >= 0; i--) {
  994. request.setRequestHeader(propertyHttpHeaders[i], params.HttpHeaders[propertyHttpHeaders[i]]);
  995. }
  996. request.onreadystatechange = function () {
  997. if (request.readyState == 4 && request.status == 200) {
  998. params.$Cache[queryParams] = request.response;
  999. callback(request.response);
  1000. }
  1001. else if (request.status >= 400) {
  1002. callbackErr();
  1003. }
  1004. };
  1005. return request;
  1006. };
  1007. AutoComplete.prototype.ajax = function (params, request, timeout) {
  1008. if (timeout === void 0) { timeout = true; }
  1009. if (params.$AjaxTimer) {
  1010. window.clearTimeout(params.$AjaxTimer);
  1011. }
  1012. if (timeout === true) {
  1013. params.$AjaxTimer = window.setTimeout(AutoComplete.prototype.ajax.bind(null, params, request, false), params.Delay);
  1014. }
  1015. else {
  1016. if (params.Request) {
  1017. params.Request.abort();
  1018. }
  1019. params.Request = request;
  1020. params.Request.send(params._QueryArg() + "=" + params._Pre());
  1021. }
  1022. };
  1023. AutoComplete.prototype.cache = function (params, callback, callbackErr) {
  1024. var response = params._Cache(params._Pre());
  1025. if (response === undefined) {
  1026. var request = AutoComplete.prototype.makeRequest(params, callback, callbackErr);
  1027. AutoComplete.prototype.ajax(params, request);
  1028. }
  1029. else {
  1030. callback(response);
  1031. }
  1032. };
  1033. AutoComplete.prototype.destroy = function (params) {
  1034. for (var event in params.$Listeners) {
  1035. params.Input.removeEventListener(event, params.$Listeners[event]);
  1036. }
  1037. params.DOMResults.parentNode.removeChild(params.DOMResults);
  1038. };
  1039. AutoComplete.merge = function () {
  1040. var merge = {}, tmp;
  1041. for (var i = 0; i < arguments.length; i++) {
  1042. for (tmp in arguments[i]) {
  1043. merge[tmp] = arguments[i][tmp];
  1044. }
  1045. }
  1046. return merge;
  1047. };
  1048. AutoComplete.defaults = {
  1049. Delay: 150,
  1050. EmptyMessage: "No result here",
  1051. Highlight: {
  1052. getRegex: function (value) {
  1053. return new RegExp(value, "ig");
  1054. },
  1055. transform: function (value) {
  1056. return "<strong>" + value + "</strong>";
  1057. }
  1058. },
  1059. HttpHeaders: {
  1060. "Content-type": "application/x-www-form-urlencoded"
  1061. },
  1062. Limit: 0,
  1063. MinChars: 0,
  1064. HttpMethod: "GET",
  1065. QueryArg: "q",
  1066. Url: null,
  1067. KeyboardMappings: {
  1068. "Enter": {
  1069. Conditions: [{
  1070. Is: 13,
  1071. Not: false
  1072. }],
  1073. Callback: function (event) {
  1074. if (this.DOMResults.getAttribute("class").indexOf("open") != -1) {
  1075. var liActive = this.DOMResults.querySelector("li.active");
  1076. if (liActive !== null) {
  1077. event.preventDefault();
  1078. this._Select(liActive);
  1079. this.DOMResults.setAttribute("class", "autocomplete");
  1080. }
  1081. }
  1082. },
  1083. Operator: ConditionOperator.AND,
  1084. Event: EventType.KEYDOWN
  1085. },
  1086. "KeyUpAndDown_down": {
  1087. Conditions: [{
  1088. Is: 38,
  1089. Not: false
  1090. },
  1091. {
  1092. Is: 40,
  1093. Not: false
  1094. }],
  1095. Callback: function (event) {
  1096. event.preventDefault();
  1097. },
  1098. Operator: ConditionOperator.OR,
  1099. Event: EventType.KEYDOWN
  1100. },
  1101. "KeyUpAndDown_up": {
  1102. Conditions: [{
  1103. Is: 38,
  1104. Not: false
  1105. },
  1106. {
  1107. Is: 40,
  1108. Not: false
  1109. }],
  1110. Callback: function (event) {
  1111. event.preventDefault();
  1112. 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");
  1113. if (active) {
  1114. var currentIndex = Array.prototype.indexOf.call(active.parentNode.children, active), position = currentIndex + (event.keyCode - 39), lisCount = this.DOMResults.getElementsByTagName("li").length;
  1115. if (position < 0) {
  1116. position = lisCount - 1;
  1117. }
  1118. else if (position >= lisCount) {
  1119. position = 0;
  1120. }
  1121. active.classList.remove("active");
  1122. active.parentElement.children.item(position).classList.add("active");
  1123. }
  1124. else if (last && event.keyCode == 38) {
  1125. last.classList.add("active");
  1126. }
  1127. else if (first) {
  1128. first.classList.add("active");
  1129. }
  1130. },
  1131. Operator: ConditionOperator.OR,
  1132. Event: EventType.KEYUP
  1133. },
  1134. "AlphaNum": {
  1135. Conditions: [{
  1136. Is: 13,
  1137. Not: true
  1138. }, {
  1139. From: 35,
  1140. To: 40,
  1141. Not: true
  1142. }],
  1143. Callback: function () {
  1144. var oldValue = this.Input.getAttribute("data-autocomplete-old-value"), currentValue = this._Pre();
  1145. if (currentValue !== "" && currentValue.length >= this._MinChars()) {
  1146. if (!oldValue || currentValue != oldValue) {
  1147. this.DOMResults.setAttribute("class", "autocomplete open");
  1148. }
  1149. AutoComplete.prototype.cache(this, function (response) {
  1150. this._Render(this._Post(response));
  1151. this._Open();
  1152. }.bind(this), this._Error);
  1153. }
  1154. else {
  1155. this._Close();
  1156. }
  1157. },
  1158. Operator: ConditionOperator.AND,
  1159. Event: EventType.KEYUP
  1160. }
  1161. },
  1162. DOMResults: null,
  1163. Request: null,
  1164. Input: null,
  1165. /**
  1166. * Return the message when no result returns
  1167. */
  1168. _EmptyMessage: function () {
  1169. var emptyMessage = "";
  1170. if (this.Input.hasAttribute("data-autocomplete-empty-message")) {
  1171. emptyMessage = this.Input.getAttribute("data-autocomplete-empty-message");
  1172. }
  1173. else if (this.EmptyMessage !== false) {
  1174. emptyMessage = this.EmptyMessage;
  1175. }
  1176. else {
  1177. emptyMessage = "";
  1178. }
  1179. return emptyMessage;
  1180. },
  1181. /**
  1182. * Returns the maximum number of results
  1183. */
  1184. _Limit: function () {
  1185. var limit = this.Input.getAttribute("data-autocomplete-limit");
  1186. if (isNaN(limit) || limit === null) {
  1187. return this.Limit;
  1188. }
  1189. return parseInt(limit, 10);
  1190. },
  1191. /**
  1192. * Returns the minimum number of characters entered before firing ajax
  1193. */
  1194. _MinChars: function () {
  1195. var minchars = this.Input.getAttribute("data-autocomplete-minchars");
  1196. if (isNaN(minchars) || minchars === null) {
  1197. return this.MinChars;
  1198. }
  1199. return parseInt(minchars, 10);
  1200. },
  1201. /**
  1202. * Apply transformation on labels response
  1203. */
  1204. _Highlight: function (label) {
  1205. return label.replace(this.Highlight.getRegex(this._Pre()), this.Highlight.transform);
  1206. },
  1207. /**
  1208. * Returns the HHTP method to use
  1209. */
  1210. _HttpMethod: function () {
  1211. if (this.Input.hasAttribute("data-autocomplete-method")) {
  1212. return this.Input.getAttribute("data-autocomplete-method");
  1213. }
  1214. return this.HttpMethod;
  1215. },
  1216. /**
  1217. * Returns the query param to use
  1218. */
  1219. _QueryArg: function () {
  1220. if (this.Input.hasAttribute("data-autocomplete-param-name")) {
  1221. return this.Input.getAttribute("data-autocomplete-param-name");
  1222. }
  1223. return this.QueryArg;
  1224. },
  1225. /**
  1226. * Returns the URL to use for AJAX request
  1227. */
  1228. _Url: function () {
  1229. if (this.Input.hasAttribute("data-autocomplete")) {
  1230. return this.Input.getAttribute("data-autocomplete");
  1231. }
  1232. return this.Url;
  1233. },
  1234. /**
  1235. * Manage the close
  1236. */
  1237. _Blur: function (now) {
  1238. if (now === void 0) { now = false; }
  1239. if (now) {
  1240. this._Close();
  1241. }
  1242. else {
  1243. var params = this;
  1244. setTimeout(function () {
  1245. params._Blur(true);
  1246. }, 150);
  1247. }
  1248. },
  1249. /**
  1250. * Manage the cache
  1251. */
  1252. _Cache: function (value) {
  1253. return this.$Cache[value];
  1254. },
  1255. /**
  1256. * Manage the open
  1257. */
  1258. _Focus: function () {
  1259. var oldValue = this.Input.getAttribute("data-autocomplete-old-value");
  1260. if ((!oldValue || this.Input.value != oldValue) && this._MinChars() <= this.Input.value.length) {
  1261. this.DOMResults.setAttribute("class", "autocomplete open");
  1262. }
  1263. },
  1264. /**
  1265. * Bind all results item if one result is opened
  1266. */
  1267. _Open: function () {
  1268. var params = this;
  1269. Array.prototype.forEach.call(this.DOMResults.getElementsByTagName("li"), function (li) {
  1270. if (li.getAttribute("class") != "locked") {
  1271. li.onclick = function () {
  1272. params._Select(li);
  1273. };
  1274. }
  1275. });
  1276. },
  1277. _Close: function () {
  1278. this.DOMResults.setAttribute("class", "autocomplete");
  1279. },
  1280. /**
  1281. * Position the results HTML element
  1282. */
  1283. _Position: function () {
  1284. this.DOMResults.setAttribute("class", "autocomplete");
  1285. this.DOMResults.setAttribute("style", "top:" + (this.Input.offsetTop + this.Input.offsetHeight) + "px;left:" + this.Input.offsetLeft + "px;width:" + this.Input.clientWidth + "px;");
  1286. },
  1287. /**
  1288. * Execute the render of results DOM element
  1289. */
  1290. _Render: function (response) {
  1291. var ul;
  1292. if (typeof response == "string") {
  1293. ul = this._RenderRaw(response);
  1294. }
  1295. else {
  1296. ul = this._RenderResponseItems(response);
  1297. }
  1298. if (this.DOMResults.hasChildNodes()) {
  1299. this.DOMResults.removeChild(this.DOMResults.childNodes[0]);
  1300. }
  1301. this.DOMResults.appendChild(ul);
  1302. },
  1303. /**
  1304. * ResponseItems[] rendering
  1305. */
  1306. _RenderResponseItems: function (response) {
  1307. var ul = document.createElement("ul"), li = document.createElement("li"), limit = this._Limit();
  1308. // Order
  1309. if (limit < 0) {
  1310. response = response.reverse();
  1311. }
  1312. else if (limit === 0) {
  1313. limit = response.length;
  1314. }
  1315. for (var item = 0; item < Math.min(Math.abs(limit), response.length); item++) {
  1316. li.innerHTML = response[item].Label;
  1317. li.setAttribute("data-autocomplete-value", response[item].Value);
  1318. ul.appendChild(li);
  1319. li = document.createElement("li");
  1320. }
  1321. return ul;
  1322. },
  1323. /**
  1324. * string response rendering (RAW HTML)
  1325. */
  1326. _RenderRaw: function (response) {
  1327. var ul = document.createElement("ul"), li = document.createElement("li");
  1328. if (response.length > 0) {
  1329. this.DOMResults.innerHTML = response;
  1330. }
  1331. else {
  1332. var emptyMessage = this._EmptyMessage();
  1333. if (emptyMessage !== "") {
  1334. li.innerHTML = emptyMessage;
  1335. li.setAttribute("class", "locked");
  1336. ul.appendChild(li);
  1337. }
  1338. }
  1339. return ul;
  1340. },
  1341. /**
  1342. * Deal with request response
  1343. */
  1344. _Post: function (response) {
  1345. try {
  1346. var returnResponse = [];
  1347. //JSON return
  1348. var json = JSON.parse(response);
  1349. if (Object.keys(json).length === 0) {
  1350. return "";
  1351. }
  1352. if (Array.isArray(json)) {
  1353. for (var i = 0; i < Object.keys(json).length; i++) {
  1354. returnResponse[returnResponse.length] = { "Value": json[i], "Label": this._Highlight(json[i]) };
  1355. }
  1356. }
  1357. else {
  1358. for (var value in json) {
  1359. returnResponse.push({
  1360. "Value": value,
  1361. "Label": this._Highlight(json[value])
  1362. });
  1363. }
  1364. }
  1365. return returnResponse;
  1366. }
  1367. catch (event) {
  1368. //HTML return
  1369. return response;
  1370. }
  1371. },
  1372. /**
  1373. * Return the autocomplete value to send (before request)
  1374. */
  1375. _Pre: function () {
  1376. return this.Input.value;
  1377. },
  1378. /**
  1379. * Choice one result item
  1380. */
  1381. _Select: function (item) {
  1382. if (item.hasAttribute("data-autocomplete-value")) {
  1383. this.Input.value = item.getAttribute("data-autocomplete-value");
  1384. }
  1385. else {
  1386. this.Input.value = item.innerHTML;
  1387. }
  1388. this.Input.setAttribute("data-autocomplete-old-value", this.Input.value);
  1389. },
  1390. /**
  1391. * Handle HTTP error on the request
  1392. */
  1393. _Error: function () {
  1394. },
  1395. $AjaxTimer: null,
  1396. $Cache: {},
  1397. $Listeners: {}
  1398. };
  1399. return AutoComplete;
  1400. }());
  1401. module.exports = AutoComplete;
  1402. },{}]},{},[1])(1)
  1403. });