minesweeper/src/main/js/UI.ts

88 lines
2.1 KiB
TypeScript
Raw Normal View History

import {blurActiveElement} from "./Common";
2020-08-04 21:41:10 +02:00
/**
* An overlay displayed in HTML.
*/
export class Overlay {
private readonly overlay: HTMLDivElement;
private readonly submitForm: HTMLFormElement | null;
private readonly cancelForm: HTMLFormElement | null;
2020-08-04 21:41:10 +02:00
/**
* Constructs a new overlay.
*
* @param overlay the overlay element to show and hide
* @param submitForm the form that invokes `onSubmit` and closes the overlay when submitted
* @param cancelForm the form that closes the overlay when submitted
* @param onSubmit the callback to invoke when the form is submit
*/
constructor(
overlay: HTMLDivElement,
submitForm: HTMLFormElement | null,
cancelForm: HTMLFormElement | null,
onSubmit: (() => void) | null = null
2020-08-04 21:41:10 +02:00
) {
this.overlay = overlay;
overlay.addEventListener(
"mousedown",
event => {
if (event.target === overlay)
this.hide();
}
);
2020-08-09 14:28:25 +02:00
document.addEventListener(
2020-08-04 21:41:10 +02:00
"keydown",
event => {
2020-08-09 14:28:25 +02:00
if (event.key === "Escape" && this.isVisible())
2020-08-04 21:41:10 +02:00
this.hide();
}
);
this.submitForm = submitForm;
2020-08-08 02:41:21 +02:00
submitForm?.addEventListener(
2020-08-04 21:41:10 +02:00
"submit",
event => {
event.preventDefault();
this.hide();
2020-08-08 02:41:21 +02:00
onSubmit?.();
2020-08-04 21:41:10 +02:00
}
);
this.cancelForm = cancelForm;
2020-08-08 02:41:21 +02:00
cancelForm?.addEventListener(
2020-08-04 21:41:10 +02:00
"submit",
event => {
event.preventDefault();
this.hide();
}
);
}
/**
* Shows the overlay.
*/
show(): void {
2021-04-28 13:51:53 +02:00
this.overlay.classList.remove("hidden");
2020-08-04 21:41:10 +02:00
}
/**
* Hides the overlay.
*/
hide(): void {
2021-04-28 13:51:53 +02:00
this.overlay.classList.add("hidden");
blurActiveElement();
2020-08-04 21:41:10 +02:00
}
2020-08-09 14:28:25 +02:00
/**
* Returns `true` if and only if this overlay is currently visible.
*/
isVisible(): boolean {
2021-04-28 13:51:53 +02:00
return this.overlay.classList.contains("hidden");
2020-08-09 14:28:25 +02:00
}
2020-08-04 21:41:10 +02:00
}