aboutsummaryrefslogtreecommitdiff
path: root/assets_src/js/lib/search.js
blob: 85559ef29f633a9fcd2001aaf179291278e73fd9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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<b>$2</b>$3")
			.replace(
				new RegExp('{ (.*?) }', 'gi'),
				'$1');
		this.strokeTimeout = null;
	}
}