searx.js 49 KB

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