aboutsummaryrefslogtreecommitdiff
path: root/static/widgets/search/index.js
blob: 324141b85ec63bac2c6a14baa7845b0dc3399af5 (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
import * as sfw from 'sfw';
const { Div, Input, Button } = sfw.element.native;

import icons from '../../icons/index.js';

const css = await sfw.css(import.meta.url, './index.css');

export default class Search extends sfw.element.Container {
	#container
	#search

	constructor() {
		super({ css });

		this.onsubmit = () => {}
		this.onhide = () => {}

		this.onclick = (e) => e.stopPropagation();
		this.hide = () => {
			this.#container.classList.remove('visible');
			document.removeEventListener('click', this.hide);
			this.onhide();
		};

		this.body.append(
			this.#container = Div.new({
				id: 'container',
				children: [
					Div.new({ innerText: 'Search', id: 'title' }),
					Div.new({
						id: 'search-box',
						children: [
							this.#search = Input.new({
								type: 'search',
								onsearch: () => this.submit(),
								onkeydown: (event) => {
									if (event.key === 'Enter') {
										this.submit();
									}
								}
							}),
							Button.new({
								children: [ icons.search ],
								onclick: () => this.submit(),
							}),
						]
					})
				]
			})
		);
	}

	submit() {
		this.onsubmit(this.#search.value);
		this.#search.blur();
		this.hide();
	}

	toggle() {
		this.#container.classList.toggle('visible');

		if (this.#container.classList.contains('visible')) {
			this.#search.focus()
			document.addEventListener('click', this.hide)
		}
	}
}