aboutsummaryrefslogtreecommitdiff
path: root/components/dialog.js
blob: 28eff1d40e1e89402c108b3b4856ba4b6b88e121 (plain) (blame)
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
import { html, Component, createRef } from "../lib/index.js";

export default class Dialog extends Component {
	body = createRef();

	constructor(props) {
		super(props);

		this.handleCloseClick = this.handleCloseClick.bind(this);
		this.handleBackdropClick = this.handleBackdropClick.bind(this);
		this.handleKeyDown = this.handleKeyDown.bind(this);
	}

	dismiss() {
		this.props.onDismiss();
	}

	handleCloseClick(event) {
		event.preventDefault();
		this.dismiss();
	}

	handleBackdropClick(event) {
		if (event.target.className == "dialog") {
			this.dismiss();
		}
	}

	handleKeyDown(event) {
		if (event.key == "Escape") {
			this.dismiss();
		}
	}

	componentDidMount() {
		window.addEventListener("keydown", this.handleKeyDown);

		let autofocus = this.body.current.querySelector("input[autofocus]");
		if (autofocus) {
			autofocus.focus();
		}
	}

	componentWillUnmount() {
		window.removeEventListener("keydown", this.handleKeyDown);
	}

	render() {
		return html`
			<div class="dialog" onClick=${this.handleBackdropClick}>
				<div class="dialog-body" ref=${this.body}>
					<div class="dialog-header">
						<h2>${this.props.title}</h2>
						<button class="dialog-close" onClick=${this.handleCloseClick}>×</button>
					</div>
					${this.props.children}
				</div>
			</div>
		`;
	}
}