minesweeper/src/main/js/UI.ts

84 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-08-04 21:41:10 +02:00
/**
* An overlay displayed in HTML.
*/
export class Overlay {
private readonly overlay: HTMLDivElement;
2020-08-08 02:41:21 +02:00
private readonly submitForm: HTMLFormElement | undefined;
private readonly cancelForm: HTMLFormElement | undefined;
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,
2020-08-08 02:41:21 +02:00
submitForm: HTMLFormElement | undefined,
cancelForm: HTMLFormElement | undefined,
onSubmit: (() => void) | undefined = undefined
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 {
this.overlay.style.visibility = "unset";
}
/**
* Hides the overlay.
*/
hide(): void {
this.overlay.style.visibility = "hidden";
}
2020-08-09 14:28:25 +02:00
/**
* Returns `true` if and only if this overlay is currently visible.
*/
isVisible(): boolean {
return this.overlay.style.visibility !== "hidden";
}
2020-08-04 21:41:10 +02:00
}