summaryrefslogtreecommitdiff
path: root/assets/script.js
blob: 95b8393d946f5dded1774fb37e306e5166898c5e (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
52
53
54
55
56
const searchInput = document.getElementById('search');
const suggestionsDiv = document.getElementById('suggestions');

async function enableAutocomplete() {
	const res = await fetch('/laws.json');
	const laws = await res.json();
	// TODO: strip accents before searching

	searchInput.addEventListener('input', (e) => {
		if (searchInput.value == '') {
			suggestionsDiv.innerHTML = '';
			return;
		}

		const titleRegex = new RegExp(searchInput.value, 'i');
		const abbrRegex = new RegExp('^' + searchInput.value, 'i');
		const suggestions = [];

		laws.map(l => {
			const titleMatch = titleRegex.exec(l.title);
			const abbrMatch = abbrRegex.exec(l.abbr);

			return {
				law: l,
				titleScore: titleMatch ? titleMatch.index : Number.MAX_VALUE,
				abbrScore: abbrMatch ? abbrMatch.index: Number.MAX_VALUE,
			}
		})
		.filter(l => l.titleScore < Number.MAX_VALUE || l.abbrScore < Number.MAX_VALUE)
		.sort((a,b) => {
			let abbrDiff = a.abbrScore - b.abbrScore;
			if (a.law.abbr && b.law.abbr && abbrDiff == 0 && a.abbrScore != Number.MAX_VALUE) {
				abbrDiff = a.law.abbr.length - b.law.abbr.length;
			}
			return abbrDiff || a.titleScore - b.titleScore;
		})
		.slice(0, 30)
		.forEach(x => {
			const l = x.law;
			const a = document.createElement('a');
			if (l.redir)
				a.href = '/' + l.redir;
			else
				a.href = l.url;
			a.textContent = l.title;
			const li = document.createElement('li');
			li.appendChild(a);
			suggestions.push(li);
		});

		suggestionsDiv.replaceChildren(...suggestions);
	});
}

if ('json' in searchInput.dataset)
	enableAutocomplete();