searx.js 48 KB

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