summaryrefslogtreecommitdiff
path: root/html/javascript/package-search.js
blob: 78df7f2f24cc5dc2546256dafc9466190b561424 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see
 * <https://www.gnu.org/licenses/>. */

"use strict";

function parse_pattern(pattern) { // ala `apropos-parse-pattern'
	const words = pattern.split(/\s+/);
	const parts = words.map(s => `(${s.replace(/([^a-zA-Z0-9])/g, "\\$1")})`);
	return new RegExp(`((${parts.join("|")}).*)+`, "i");
}

window.addEventListener("load", function (event) {
	const table = document.getElementById("packages");

	const search = document.createElement("input");
	search.setAttribute("placeholder", "Search packages...");
	search.setAttribute("type", "search");

	let tid = false;			// timeout ID
	search.addEventListener("input", function(event) {
		if (tid) clearTimeout(tid);

		tid = setTimeout(function (query) {
			const pattern = parse_pattern(query);
			for (let i = 1; i < table.rows.length; i++) {
				const row = table.rows.item(i);

				const name = row.childNodes.item(0);
				name.classList.remove("alt");

				const desc = row.childNodes.item(2);
				desc.classList.remove("alt");

				if (query) {
					const name_matches = name.innerText.match(pattern);
					const desc_matches = desc.innerText.match(pattern);
					if (name_matches || desc_matches) {
						row.classList.remove("invisible");
						if (name_matches) { name.classList.add("alt"); }
						if (desc_matches) { desc.classList.add("alt"); }
					} else {
						row.classList.add("invisible");
					}
				} else {
					row.classList.remove("invisible");
				}
			}

			tid = false;
		}, 100, event.target.value.trim());
	});

	const main = document.querySelector("main");
	main.prepend(search);
});

// Local Variables:
// indent-tabs-mode: t
// js-indent-level: 4
// tab-width: 4
// End: