logo

searx

My custom branche(s) on searx, a meta-search engine git clone https://hacktivis.me/git/searx.git

searx.js (51610B)


  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. (function(w, d, searx) {
  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. searx = 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.staticPath + 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.staticPath + 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, window.searx);
  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. ;/**
  681. *
  682. * Google Image Layout v0.0.1
  683. * Description, by Anh Trinh.
  684. * Heavily modified for searx
  685. * http://trinhtrunganh.com
  686. *
  687. * @license Free to use under the MIT License.
  688. *
  689. */
  690. (function(w, d) {
  691. 'use strict';
  692. function ImageLayout(container_selector, results_selector, img_selector, maxHeight) {
  693. this.container_selector = container_selector;
  694. this.results_selector = results_selector;
  695. this.img_selector = img_selector;
  696. this.margin = 10;
  697. this.maxHeight = maxHeight;
  698. this._alignAllDone = true;
  699. }
  700. /**
  701. * Get the height that make all images fit the container
  702. *
  703. * width = w1 + w2 + w3 + ... = r1*h + r2*h + r3*h + ...
  704. *
  705. * @param {[type]} images the images to be calculated
  706. * @param {[type]} width the container witdth
  707. * @param {[type]} margin the margin between each image
  708. *
  709. * @return {[type]} the height
  710. */
  711. ImageLayout.prototype._getHeigth = function(images, width) {
  712. var r = 0,
  713. img;
  714. width -= images.length * this.margin;
  715. for (var i = 0; i < images.length; i++) {
  716. img = images[i];
  717. if ((img.naturalWidth > 0) && (img.naturalHeight > 0)) {
  718. r += img.naturalWidth / img.naturalHeight;
  719. } else {
  720. // assume that not loaded images are square
  721. r += 1;
  722. }
  723. }
  724. return width / r; //have to round down because Firefox will automatically roundup value with number of decimals > 3
  725. };
  726. ImageLayout.prototype._setSize = function(images, height) {
  727. var img, imgWidth, imagesLength = images.length;
  728. for (var i = 0; i < imagesLength; i++) {
  729. img = images[i];
  730. if ((img.naturalWidth > 0) && (img.naturalHeight > 0)) {
  731. imgWidth = height * img.naturalWidth / img.naturalHeight;
  732. } else {
  733. // not loaded image : make it square as _getHeigth said it
  734. imgWidth = height;
  735. }
  736. img.style.width = imgWidth + 'px';
  737. img.style.height = height + 'px';
  738. img.style.marginLeft = '3px';
  739. img.style.marginTop = '3px';
  740. img.style.marginRight = this.margin - 7 + 'px'; // -4 is the negative margin of the inline element
  741. img.style.marginBottom = this.margin - 7 + 'px';
  742. }
  743. };
  744. ImageLayout.prototype._alignImgs = function(imgGroup) {
  745. var slice, h,
  746. containerWidth = d.querySelector(this.container_selector).clientWidth;
  747. w: while (imgGroup.length > 0) {
  748. for (var i = 1; i <= imgGroup.length; i++) {
  749. slice = imgGroup.slice(0, i);
  750. h = this._getHeigth(slice, containerWidth);
  751. if (h < this.maxHeight) {
  752. this._setSize(slice, h);
  753. imgGroup = imgGroup.slice(i);
  754. continue w;
  755. }
  756. }
  757. this._setSize(slice, Math.min(this.maxHeight, h));
  758. break;
  759. }
  760. };
  761. ImageLayout.prototype.align = function(results_selector) {
  762. var results_selectorNode = d.querySelectorAll(this.results_selector),
  763. results_length = results_selectorNode.length,
  764. previous = null,
  765. current = null,
  766. imgGroup = [];
  767. for (var i = 0; i < results_length; i++) {
  768. current = results_selectorNode[i];
  769. if (current.previousElementSibling !== previous && imgGroup.length > 0) {
  770. // the current image is not conected to previous one
  771. // so the current image is the start of a new group of images.
  772. // so call _alignImgs to align the current group
  773. this._alignImgs(imgGroup);
  774. // and start a new empty group of images
  775. imgGroup = [];
  776. }
  777. // add the current image to the group (only the img tag)
  778. imgGroup.push(current.querySelector(this.img_selector));
  779. // update the previous variable
  780. previous = current;
  781. }
  782. // align the remaining images
  783. if (imgGroup.length > 0) {
  784. this._alignImgs(imgGroup);
  785. }
  786. };
  787. ImageLayout.prototype.watch = function() {
  788. var i, img, imgGroup, imgNodeLength,
  789. obj = this,
  790. results_nodes = d.querySelectorAll(this.results_selector),
  791. results_length = results_nodes.length;
  792. function align(e) {
  793. obj.align();
  794. }
  795. function throttleAlign(e) {
  796. if (obj._alignAllDone) {
  797. obj._alignAllDone = false;
  798. setTimeout(function() {
  799. obj.align();
  800. obj._alignAllDone = true;
  801. }, 100);
  802. }
  803. }
  804. w.addEventListener('resize', throttleAlign);
  805. w.addEventListener('pageshow', align);
  806. for (i = 0; i < results_length; i++) {
  807. img = results_nodes[i].querySelector(this.img_selector);
  808. if (typeof img !== 'undefined') {
  809. img.addEventListener('load', throttleAlign);
  810. img.addEventListener('error', throttleAlign);
  811. }
  812. }
  813. };
  814. w.searx.ImageLayout = ImageLayout;
  815. })(window, document);
  816. ;searx.ready(function() {
  817. searx.on('.result', 'click', function() {
  818. highlightResult(this)(true);
  819. });
  820. searx.on('.result a', 'focus', function(e) {
  821. var el = e.target;
  822. while (el !== undefined) {
  823. if (el.classList.contains('result')) {
  824. if (el.getAttribute("data-vim-selected") === null) {
  825. highlightResult(el)(true);
  826. }
  827. break;
  828. }
  829. el = el.parentNode;
  830. }
  831. }, true);
  832. var vimKeys = {
  833. 27: {
  834. key: 'Escape',
  835. fun: removeFocus,
  836. des: 'remove focus from the focused input',
  837. cat: 'Control'
  838. },
  839. 73: {
  840. key: 'i',
  841. fun: searchInputFocus,
  842. des: 'focus on the search input',
  843. cat: 'Control'
  844. },
  845. 66: {
  846. key: 'b',
  847. fun: scrollPage(-window.innerHeight),
  848. des: 'scroll one page up',
  849. cat: 'Navigation'
  850. },
  851. 70: {
  852. key: 'f',
  853. fun: scrollPage(window.innerHeight),
  854. des: 'scroll one page down',
  855. cat: 'Navigation'
  856. },
  857. 85: {
  858. key: 'u',
  859. fun: scrollPage(-window.innerHeight / 2),
  860. des: 'scroll half a page up',
  861. cat: 'Navigation'
  862. },
  863. 68: {
  864. key: 'd',
  865. fun: scrollPage(window.innerHeight / 2),
  866. des: 'scroll half a page down',
  867. cat: 'Navigation'
  868. },
  869. 71: {
  870. key: 'g',
  871. fun: scrollPageTo(-document.body.scrollHeight, 'top'),
  872. des: 'scroll to the top of the page',
  873. cat: 'Navigation'
  874. },
  875. 86: {
  876. key: 'v',
  877. fun: scrollPageTo(document.body.scrollHeight, 'bottom'),
  878. des: 'scroll to the bottom of the page',
  879. cat: 'Navigation'
  880. },
  881. 75: {
  882. key: 'k',
  883. fun: highlightResult('up'),
  884. des: 'select previous search result',
  885. cat: 'Results'
  886. },
  887. 74: {
  888. key: 'j',
  889. fun: highlightResult('down'),
  890. des: 'select next search result',
  891. cat: 'Results'
  892. },
  893. 80: {
  894. key: 'p',
  895. fun: pageButtonClick(0),
  896. des: 'go to previous page',
  897. cat: 'Results'
  898. },
  899. 78: {
  900. key: 'n',
  901. fun: pageButtonClick(1),
  902. des: 'go to next page',
  903. cat: 'Results'
  904. },
  905. 79: {
  906. key: 'o',
  907. fun: openResult(false),
  908. des: 'open search result',
  909. cat: 'Results'
  910. },
  911. 84: {
  912. key: 't',
  913. fun: openResult(true),
  914. des: 'open the result in a new tab',
  915. cat: 'Results'
  916. },
  917. 82: {
  918. key: 'r',
  919. fun: reloadPage,
  920. des: 'reload page from the server',
  921. cat: 'Control'
  922. },
  923. 72: {
  924. key: 'h',
  925. fun: toggleHelp,
  926. des: 'toggle help window',
  927. cat: 'Other'
  928. }
  929. };
  930. searx.on(document, "keydown", function(e) {
  931. // check for modifiers so we don't break browser's hotkeys
  932. if (vimKeys.hasOwnProperty(e.keyCode) && !e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey) {
  933. var tagName = e.target.tagName.toLowerCase();
  934. if (e.keyCode === 27) {
  935. if (tagName === 'input' || tagName === 'select' || tagName === 'textarea') {
  936. vimKeys[e.keyCode].fun();
  937. }
  938. } else {
  939. if (e.target === document.body || tagName === 'a' || tagName === 'button') {
  940. e.preventDefault();
  941. vimKeys[e.keyCode].fun();
  942. }
  943. }
  944. }
  945. });
  946. function highlightResult(which) {
  947. return function(noScroll) {
  948. var current = document.querySelector('.result[data-vim-selected]'),
  949. effectiveWhich = which;
  950. if (current === null) {
  951. // no selection : choose the first one
  952. current = document.querySelector('.result');
  953. if (current === null) {
  954. // no first one : there are no results
  955. return;
  956. }
  957. // replace up/down actions by selecting first one
  958. if (which === "down" || which === "up") {
  959. effectiveWhich = current;
  960. }
  961. }
  962. var next, results = document.querySelectorAll('.result');
  963. if (typeof effectiveWhich !== 'string') {
  964. next = effectiveWhich;
  965. } else {
  966. switch (effectiveWhich) {
  967. case 'visible':
  968. var top = document.documentElement.scrollTop || document.body.scrollTop;
  969. var bot = top + document.documentElement.clientHeight;
  970. for (var i = 0; i < results.length; i++) {
  971. next = results[i];
  972. var etop = next.offsetTop;
  973. var ebot = etop + next.clientHeight;
  974. if ((ebot <= bot) && (etop > top)) {
  975. break;
  976. }
  977. }
  978. break;
  979. case 'down':
  980. next = current.nextElementSibling;
  981. if (next === null) {
  982. next = results[0];
  983. }
  984. break;
  985. case 'up':
  986. next = current.previousElementSibling;
  987. if (next === null) {
  988. next = results[results.length - 1];
  989. }
  990. break;
  991. case 'bottom':
  992. next = results[results.length - 1];
  993. break;
  994. case 'top':
  995. /* falls through */
  996. default:
  997. next = results[0];
  998. }
  999. }
  1000. if (next) {
  1001. current.removeAttribute('data-vim-selected');
  1002. next.setAttribute('data-vim-selected', 'true');
  1003. var link = next.querySelector('h3 a') || next.querySelector('a');
  1004. if (link !== null) {
  1005. link.focus();
  1006. }
  1007. if (!noScroll) {
  1008. scrollPageToSelected();
  1009. }
  1010. }
  1011. };
  1012. }
  1013. function reloadPage() {
  1014. document.location.reload(true);
  1015. }
  1016. function removeFocus() {
  1017. if (document.activeElement) {
  1018. document.activeElement.blur();
  1019. }
  1020. }
  1021. function pageButtonClick(num) {
  1022. return function() {
  1023. var buttons = $('div#pagination button[type="submit"]');
  1024. if (buttons.length !== 2) {
  1025. console.log('page navigation with this theme is not supported');
  1026. return;
  1027. }
  1028. if (num >= 0 && num < buttons.length) {
  1029. buttons[num].click();
  1030. } else {
  1031. console.log('pageButtonClick(): invalid argument');
  1032. }
  1033. };
  1034. }
  1035. function scrollPageToSelected() {
  1036. var sel = document.querySelector('.result[data-vim-selected]');
  1037. if (sel === null) {
  1038. return;
  1039. }
  1040. var wtop = document.documentElement.scrollTop || document.body.scrollTop,
  1041. wheight = document.documentElement.clientHeight,
  1042. etop = sel.offsetTop,
  1043. ebot = etop + sel.clientHeight,
  1044. offset = 120;
  1045. // first element ?
  1046. if ((sel.previousElementSibling === null) && (ebot < wheight)) {
  1047. // set to the top of page if the first element
  1048. // is fully included in the viewport
  1049. window.scroll(window.scrollX, 0);
  1050. return;
  1051. }
  1052. if (wtop > (etop - offset)) {
  1053. window.scroll(window.scrollX, etop - offset);
  1054. } else {
  1055. var wbot = wtop + wheight;
  1056. if (wbot < (ebot + offset)) {
  1057. window.scroll(window.scrollX, ebot - wheight + offset);
  1058. }
  1059. }
  1060. }
  1061. function scrollPage(amount) {
  1062. return function() {
  1063. window.scrollBy(0, amount);
  1064. highlightResult('visible')();
  1065. };
  1066. }
  1067. function scrollPageTo(position, nav) {
  1068. return function() {
  1069. window.scrollTo(0, position);
  1070. highlightResult(nav)();
  1071. };
  1072. }
  1073. function searchInputFocus() {
  1074. window.scrollTo(0, 0);
  1075. document.querySelector('#q').focus();
  1076. }
  1077. function openResult(newTab) {
  1078. return function() {
  1079. var link = document.querySelector('.result[data-vim-selected] h3 a');
  1080. if (link !== null) {
  1081. var url = link.getAttribute('href');
  1082. if (newTab) {
  1083. window.open(url);
  1084. } else {
  1085. window.location.href = url;
  1086. }
  1087. }
  1088. };
  1089. }
  1090. function initHelpContent(divElement) {
  1091. var categories = {};
  1092. for (var k in vimKeys) {
  1093. var key = vimKeys[k];
  1094. categories[key.cat] = categories[key.cat] || [];
  1095. categories[key.cat].push(key);
  1096. }
  1097. var sorted = Object.keys(categories).sort(function(a, b) {
  1098. return categories[b].length - categories[a].length;
  1099. });
  1100. if (sorted.length === 0) {
  1101. return;
  1102. }
  1103. var html = '<a href="#" class="close" aria-label="close" title="close">×</a>';
  1104. html += '<h3>How to navigate searx with Vim-like hotkeys</h3>';
  1105. html += '<table>';
  1106. for (var i = 0; i < sorted.length; i++) {
  1107. var cat = categories[sorted[i]];
  1108. var lastCategory = i === (sorted.length - 1);
  1109. var first = i % 2 === 0;
  1110. if (first) {
  1111. html += '<tr>';
  1112. }
  1113. html += '<td>';
  1114. html += '<h4>' + cat[0].cat + '</h4>';
  1115. html += '<ul class="list-unstyled">';
  1116. for (var cj in cat) {
  1117. html += '<li><kbd>' + cat[cj].key + '</kbd> ' + cat[cj].des + '</li>';
  1118. }
  1119. html += '</ul>';
  1120. html += '</td>'; // col-sm-*
  1121. if (!first || lastCategory) {
  1122. html += '</tr>'; // row
  1123. }
  1124. }
  1125. html += '</table>';
  1126. divElement.innerHTML = html;
  1127. }
  1128. function toggleHelp() {
  1129. var helpPanel = document.querySelector('#vim-hotkeys-help');
  1130. console.log(helpPanel);
  1131. if (helpPanel === undefined || helpPanel === null) {
  1132. // first call
  1133. helpPanel = document.createElement('div');
  1134. helpPanel.id = 'vim-hotkeys-help';
  1135. helpPanel.className='dialog-modal';
  1136. helpPanel.style='width: 40%';
  1137. initHelpContent(helpPanel);
  1138. var body = document.getElementsByTagName('body')[0];
  1139. body.appendChild(helpPanel);
  1140. } else {
  1141. // togggle hidden
  1142. helpPanel.classList.toggle('invisible');
  1143. return;
  1144. }
  1145. }
  1146. });
  1147. ;/**
  1148. * searx is free software: you can redistribute it and/or modify
  1149. * it under the terms of the GNU Affero General Public License as published by
  1150. * the Free Software Foundation, either version 3 of the License, or
  1151. * (at your option) any later version.
  1152. *
  1153. * searx is distributed in the hope that it will be useful,
  1154. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  1155. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1156. * GNU Affero General Public License for more details.
  1157. *
  1158. * You should have received a copy of the GNU Affero General Public License
  1159. * along with searx. If not, see < http://www.gnu.org/licenses/ >.
  1160. *
  1161. * (C) 2014 by Thomas Pointhuber, <thomas.pointhuber@gmx.at>
  1162. * (C) 2017 by Alexandre Flament, <alex@al-f.net>
  1163. */
  1164. (function (w, d, searx) {
  1165. 'use strict';
  1166. searx.ready(function () {
  1167. searx.on('.searx_overpass_request', 'click', function(event) {
  1168. // no more request
  1169. this.classList.remove("searx_overpass_request");
  1170. //
  1171. var overpass_url = "https://overpass-api.de/api/interpreter?data=";
  1172. var query_start = overpass_url + "[out:json][timeout:25];(";
  1173. var query_end = ");out meta;";
  1174. var osm_id = this.dataset.osmId;
  1175. var osm_type = this.dataset.osmType;
  1176. var result_table = d.querySelector("#" + this.dataset.resultTable);
  1177. var result_table_loadicon = d.querySelector("#" + this.dataset.resultTableLoadicon);
  1178. // tags which can be ignored
  1179. var osm_ignore_tags = [ "addr:city", "addr:country", "addr:housenumber", "addr:postcode", "addr:street" ];
  1180. if(osm_id && osm_type && result_table) {
  1181. var query = null;
  1182. switch(osm_type) {
  1183. case 'node':
  1184. query = query_start + "node(" + osm_id + ");" + query_end;
  1185. break;
  1186. case 'way':
  1187. query = query_start + "way(" + osm_id + ");" + query_end;
  1188. break;
  1189. case 'relation':
  1190. query = query_start + "relation(" + osm_id + ");" + query_end;
  1191. break;
  1192. default:
  1193. break;
  1194. }
  1195. if(query) {
  1196. // console.log(query);
  1197. searx.http( 'GET', query ).then(function(html, contentType) {
  1198. html = JSON.parse(html);
  1199. if(html && html.elements && html.elements[0]) {
  1200. var element = html.elements[0];
  1201. var newHtml = "";
  1202. for (var row in element.tags) {
  1203. if(element.tags.name === null || osm_ignore_tags.indexOf(row) == -1) {
  1204. newHtml += "<tr><td>" + row + "</td><td>";
  1205. switch(row) {
  1206. case "phone":
  1207. case "fax":
  1208. newHtml += "<a href=\"tel:" + element.tags[row].replace(/ /g,'') + "\">" + element.tags[row] + "</a>";
  1209. break;
  1210. case "email":
  1211. newHtml += "<a href=\"mailto:" + element.tags[row] + "\">" + element.tags[row] + "</a>";
  1212. break;
  1213. case "website":
  1214. case "url":
  1215. newHtml += "<a href=\"" + element.tags[row] + "\">" + element.tags[row] + "</a>";
  1216. break;
  1217. case "wikidata":
  1218. newHtml += "<a href=\"https://www.wikidata.org/wiki/" + element.tags[row] + "\">" + element.tags[row] + "</a>";
  1219. break;
  1220. case "wikipedia":
  1221. if(element.tags[row].indexOf(":") != -1) {
  1222. newHtml += "<a href=\"https://" + element.tags[row].substring(0,element.tags[row].indexOf(":")) + ".wikipedia.org/wiki/" + element.tags[row].substring(element.tags[row].indexOf(":")+1) + "\">" + element.tags[row] + "</a>";
  1223. break;
  1224. }
  1225. /* jshint ignore:start */
  1226. default:
  1227. /* jshint ignore:end */
  1228. newHtml += element.tags[row];
  1229. break;
  1230. }
  1231. newHtml += "</td></tr>";
  1232. }
  1233. }
  1234. result_table_loadicon.parentNode.removeChild(result_table_loadicon);
  1235. result_table.classList.remove('invisible');
  1236. result_table.querySelector("tbody").innerHTML = newHtml;
  1237. }
  1238. })
  1239. .catch(function() {
  1240. result_table_loadicon.classList.remove('invisible');
  1241. result_table_loadicon.innerHTML = "could not load data!";
  1242. });
  1243. }
  1244. }
  1245. // this event occour only once per element
  1246. event.preventDefault();
  1247. });
  1248. searx.on('.searx_init_map', 'click', function(event) {
  1249. // no more request
  1250. this.classList.remove("searx_init_map");
  1251. //
  1252. var leaflet_target = this.dataset.leafletTarget;
  1253. var map_lon = parseFloat(this.dataset.mapLon);
  1254. var map_lat = parseFloat(this.dataset.mapLat);
  1255. var map_zoom = parseFloat(this.dataset.mapZoom);
  1256. var map_boundingbox = JSON.parse(this.dataset.mapBoundingbox);
  1257. var map_geojson = JSON.parse(this.dataset.mapGeojson);
  1258. searx.loadStyle('leaflet/leaflet.css');
  1259. searx.loadScript('leaflet/leaflet.js', function() {
  1260. var map_bounds = null;
  1261. if(map_boundingbox) {
  1262. var southWest = L.latLng(map_boundingbox[0], map_boundingbox[2]);
  1263. var northEast = L.latLng(map_boundingbox[1], map_boundingbox[3]);
  1264. map_bounds = L.latLngBounds(southWest, northEast);
  1265. }
  1266. // init map
  1267. var map = L.map(leaflet_target);
  1268. // create the tile layer with correct attribution
  1269. var osmMapnikUrl='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
  1270. var osmMapnikAttrib='Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors';
  1271. var osmMapnik = new L.TileLayer(osmMapnikUrl, {minZoom: 1, maxZoom: 19, attribution: osmMapnikAttrib});
  1272. var osmWikimediaUrl='https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png';
  1273. var osmWikimediaAttrib = 'Wikimedia maps beta | Maps data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors';
  1274. var osmWikimedia = new L.TileLayer(osmWikimediaUrl, {minZoom: 1, maxZoom: 19, attribution: osmWikimediaAttrib});
  1275. // init map view
  1276. if(map_bounds) {
  1277. // TODO hack: https://github.com/Leaflet/Leaflet/issues/2021
  1278. // Still useful ?
  1279. setTimeout(function () {
  1280. map.fitBounds(map_bounds, {
  1281. maxZoom:17
  1282. });
  1283. }, 0);
  1284. } else if (map_lon && map_lat) {
  1285. if(map_zoom) {
  1286. map.setView(new L.latLng(map_lat, map_lon),map_zoom);
  1287. } else {
  1288. map.setView(new L.latLng(map_lat, map_lon),8);
  1289. }
  1290. }
  1291. map.addLayer(osmMapnik);
  1292. var baseLayers = {
  1293. "OSM Mapnik": osmMapnik/*,
  1294. "OSM Wikimedia": osmWikimedia*/
  1295. };
  1296. L.control.layers(baseLayers).addTo(map);
  1297. if(map_geojson) {
  1298. L.geoJson(map_geojson).addTo(map);
  1299. } /*else if(map_bounds) {
  1300. L.rectangle(map_bounds, {color: "#ff7800", weight: 3, fill:false}).addTo(map);
  1301. }*/
  1302. });
  1303. // this event occour only once per element
  1304. event.preventDefault();
  1305. });
  1306. });
  1307. })(window, document, window.searx);
  1308. ;/**
  1309. * searx is free software: you can redistribute it and/or modify
  1310. * it under the terms of the GNU Affero General Public License as published by
  1311. * the Free Software Foundation, either version 3 of the License, or
  1312. * (at your option) any later version.
  1313. *
  1314. * searx is distributed in the hope that it will be useful,
  1315. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  1316. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1317. * GNU Affero General Public License for more details.
  1318. *
  1319. * You should have received a copy of the GNU Affero General Public License
  1320. * along with searx. If not, see < http://www.gnu.org/licenses/ >.
  1321. *
  1322. * (C) 2017 by Alexandre Flament, <alex@al-f.net>
  1323. */
  1324. (function(w, d, searx) {
  1325. 'use strict';
  1326. searx.ready(function() {
  1327. searx.image_thumbnail_layout = new searx.ImageLayout('#urls', '#urls .result-images', 'img.image_thumbnail', 200);
  1328. searx.image_thumbnail_layout.watch();
  1329. searx.on('.btn-collapse', 'click', function(event) {
  1330. var btnLabelCollapsed = this.getAttribute('data-btn-text-collapsed');
  1331. var btnLabelNotCollapsed = this.getAttribute('data-btn-text-not-collapsed');
  1332. var target = this.getAttribute('data-target');
  1333. var targetElement = d.querySelector(target);
  1334. var html = this.innerHTML;
  1335. if (this.classList.contains('collapsed')) {
  1336. html = html.replace(btnLabelCollapsed, btnLabelNotCollapsed);
  1337. } else {
  1338. html = html.replace(btnLabelNotCollapsed, btnLabelCollapsed);
  1339. }
  1340. this.innerHTML = html;
  1341. this.classList.toggle('collapsed');
  1342. targetElement.classList.toggle('invisible');
  1343. });
  1344. searx.on('.media-loader', 'click', function(event) {
  1345. var target = this.getAttribute('data-target');
  1346. var iframe_load = d.querySelector(target + ' > iframe');
  1347. var srctest = iframe_load.getAttribute('src');
  1348. if (srctest === null || srctest === undefined || srctest === false) {
  1349. iframe_load.setAttribute('src', iframe_load.getAttribute('data-src'));
  1350. }
  1351. });
  1352. w.addEventListener('scroll', function() {
  1353. var e = d.getElementById('backToTop'),
  1354. scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  1355. if (e !== null) {
  1356. if (scrollTop >= 200) {
  1357. e.style.opacity = 1;
  1358. } else {
  1359. e.style.opacity = 0;
  1360. }
  1361. }
  1362. });
  1363. });
  1364. })(window, document, window.searx);
  1365. ;/**
  1366. * searx is free software: you can redistribute it and/or modify
  1367. * it under the terms of the GNU Affero General Public License as published by
  1368. * the Free Software Foundation, either version 3 of the License, or
  1369. * (at your option) any later version.
  1370. *
  1371. * searx is distributed in the hope that it will be useful,
  1372. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  1373. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1374. * GNU Affero General Public License for more details.
  1375. *
  1376. * You should have received a copy of the GNU Affero General Public License
  1377. * along with searx. If not, see < http://www.gnu.org/licenses/ >.
  1378. *
  1379. * (C) 2017 by Alexandre Flament, <alex@al-f.net>
  1380. */
  1381. (function(w, d, searx) {
  1382. 'use strict';
  1383. var firstFocus = true, qinput_id = "q", qinput;
  1384. function placeCursorAtEnd(element) {
  1385. if (element.setSelectionRange) {
  1386. var len = element.value.length;
  1387. element.setSelectionRange(len, len);
  1388. }
  1389. }
  1390. function submitIfQuery() {
  1391. if (qinput.value.length > 0) {
  1392. var search = document.getElementById('search');
  1393. setTimeout(search.submit.bind(search), 0);
  1394. }
  1395. }
  1396. function createClearButton(qinput) {
  1397. var cs = document.getElementById('clear_search');
  1398. var updateClearButton = function() {
  1399. if (qinput.value.length === 0) {
  1400. cs.classList.add("empty");
  1401. } else {
  1402. cs.classList.remove("empty");
  1403. }
  1404. };
  1405. // update status, event listener
  1406. updateClearButton();
  1407. cs.addEventListener('click', function() {
  1408. qinput.value='';
  1409. qinput.focus();
  1410. updateClearButton();
  1411. });
  1412. qinput.addEventListener('keyup', updateClearButton, false);
  1413. }
  1414. searx.ready(function() {
  1415. qinput = d.getElementById(qinput_id);
  1416. function placeCursorAtEndOnce(e) {
  1417. if (firstFocus) {
  1418. placeCursorAtEnd(qinput);
  1419. firstFocus = false;
  1420. } else {
  1421. // e.preventDefault();
  1422. }
  1423. }
  1424. if (qinput !== null) {
  1425. // clear button
  1426. createClearButton(qinput);
  1427. // autocompleter
  1428. if (searx.autocompleter) {
  1429. searx.autocomplete = AutoComplete.call(w, {
  1430. Url: "./autocompleter",
  1431. EmptyMessage: searx.noItemFound,
  1432. HttpMethod: searx.method,
  1433. MinChars: 4,
  1434. Delay: 300,
  1435. }, "#" + qinput_id);
  1436. // hack, see : https://github.com/autocompletejs/autocomplete.js/issues/37
  1437. w.addEventListener('resize', function() {
  1438. var event = new CustomEvent("position");
  1439. qinput.dispatchEvent(event);
  1440. });
  1441. }
  1442. qinput.addEventListener('focus', placeCursorAtEndOnce, false);
  1443. qinput.focus();
  1444. }
  1445. // vanilla js version of search_on_category_select.js
  1446. if (qinput !== null && searx.search_on_category_select) {
  1447. d.querySelector('.help').className='invisible';
  1448. searx.on('#categories input', 'change', function(e) {
  1449. var i, categories = d.querySelectorAll('#categories input[type="checkbox"]');
  1450. for(i=0; i<categories.length; i++) {
  1451. if (categories[i] !== this && categories[i].checked) {
  1452. categories[i].click();
  1453. }
  1454. }
  1455. if (! this.checked) {
  1456. this.click();
  1457. }
  1458. submitIfQuery();
  1459. return false;
  1460. });
  1461. searx.on(d.getElementById('time_range'), 'change', submitIfQuery);
  1462. searx.on(d.getElementById('language'), 'change', submitIfQuery);
  1463. }
  1464. });
  1465. })(window, document, window.searx);