searxng.js 48 KB

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