import * as dom from './dom'; import * as ajax from './ajax'; export class InstantSearch { constructor(element, resultsElem) { this.resultClicked = () => {}; this.element = element; this.resultsElem = resultsElem; this.strokeTimeout = null; element.addEventListener('keydown', e => { if (this.strokeTimeout) { clearTimeout(this.strokeTimeout); } this.strokeTimeout = setTimeout(() => this.doSearch(), 150); }, false); resultsElem.addEventListener('click', e => { let li = dom.closest(e.target, el => el.tagName.match(/li/i)); if (!li) { return true; } this.resultsElem.innerHTML = ''; this.resultClicked(li.getAttribute('data-id')); }, true); } async doSearch() { let value = this.element.value; if (value.length < 2) { this.strokeTimeout = null; this.resultsElem.innerHTML = ""; return; } let response = null; try { response = await ajax.get(`/search/gril_instant/${value}`); } catch (e) { this.resultsElem.innerHTML = ''; return; } this.resultsElem.innerHTML = response .replace( new RegExp('{ (.*?)(' + value + ')(.*?) }', 'gi'), "$1$2$3") .replace( new RegExp('{ (.*?) }', 'gi'), '$1'); this.strokeTimeout = null; } }