1
0

Dialog.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. /**
  2. * @module lib/Dialog
  3. * This module contains the Dialog class, which allows you to quickly and easily create modal dialogs - [see the documentation for more info](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#dialog)
  4. */
  5. import { NanoEmitter } from "./NanoEmitter.js";
  6. import { addGlobalStyle } from "./dom.js";
  7. export const defaultDialogCss: string = `\
  8. .uu-no-select {
  9. user-select: none;
  10. }
  11. .uu-dialog-bg {
  12. --uu-dialog-bg: #333333;
  13. --uu-dialog-bg-highlight: #252525;
  14. --uu-scroll-indicator-bg: rgba(10, 10, 10, 0.7);
  15. --uu-dialog-separator-color: #797979;
  16. --uu-dialog-border-radius: 10px;
  17. }
  18. .uu-dialog-bg {
  19. display: block;
  20. position: fixed;
  21. width: 100%;
  22. height: 100%;
  23. top: 0;
  24. left: 0;
  25. z-index: 5;
  26. background-color: rgba(0, 0, 0, 0.6);
  27. }
  28. .uu-dialog {
  29. --uu-calc-dialog-height: calc(min(100vh - 40px, var(--uu-dialog-height-max)));
  30. position: absolute;
  31. display: flex;
  32. flex-direction: column;
  33. width: calc(min(100% - 60px, var(--uu-dialog-width-max)));
  34. border-radius: var(--uu-dialog-border-radius);
  35. height: auto;
  36. max-height: var(--uu-calc-dialog-height);
  37. left: 50%;
  38. top: 50%;
  39. transform: translate(-50%, -50%);
  40. z-index: 6;
  41. color: #fff;
  42. background-color: var(--uu-dialog-bg);
  43. }
  44. .uu-dialog.align-top {
  45. top: 0;
  46. transform: translate(-50%, 40px);
  47. }
  48. .uu-dialog.align-bottom {
  49. top: 100%;
  50. transform: translate(-50%, -100%);
  51. }
  52. .uu-dialog-body {
  53. font-size: 1.5rem;
  54. padding: 20px;
  55. }
  56. .uu-dialog-body.small {
  57. padding: 15px;
  58. }
  59. #uu-dialog-opts {
  60. display: flex;
  61. flex-direction: column;
  62. position: relative;
  63. padding: 30px 0px;
  64. overflow-y: auto;
  65. }
  66. .uu-dialog-header {
  67. display: flex;
  68. justify-content: space-between;
  69. align-items: center;
  70. margin-bottom: 6px;
  71. padding: 15px 20px 15px 20px;
  72. background-color: var(--uu-dialog-bg);
  73. border: 2px solid var(--uu-dialog-separator-color);
  74. border-style: none none solid none !important;
  75. border-radius: var(--uu-dialog-border-radius) var(--uu-dialog-border-radius) 0px 0px;
  76. }
  77. .uu-dialog-header.small {
  78. padding: 10px 15px;
  79. border-style: none none solid none !important;
  80. }
  81. .uu-dialog-header-pad {
  82. content: " ";
  83. min-height: 32px;
  84. }
  85. .uu-dialog-header-pad.small {
  86. min-height: 24px;
  87. }
  88. .uu-dialog-titlecont {
  89. display: flex;
  90. align-items: center;
  91. }
  92. .uu-dialog-titlecont-no-title {
  93. display: flex;
  94. justify-content: flex-end;
  95. align-items: center;
  96. }
  97. .uu-dialog-title {
  98. position: relative;
  99. display: inline-block;
  100. font-size: 22px;
  101. }
  102. .uu-dialog-close {
  103. cursor: pointer;
  104. }
  105. .uu-dialog-header-img,
  106. .uu-dialog-close
  107. {
  108. width: 32px;
  109. height: 32px;
  110. }
  111. .uu-dialog-header-img.small,
  112. .uu-dialog-close.small
  113. {
  114. width: 24px;
  115. height: 24px;
  116. }
  117. .uu-dialog-footer {
  118. font-size: 17px;
  119. text-decoration: underline;
  120. }
  121. .uu-dialog-footer.hidden {
  122. display: none;
  123. }
  124. .uu-dialog-footer-cont {
  125. margin-top: 6px;
  126. padding: 15px 20px;
  127. background: var(--uu-dialog-bg);
  128. background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, var(--uu-dialog-bg) 30%, var(--uu-dialog-bg) 100%);
  129. border: 2px solid var(--uu-dialog-separator-color);
  130. border-style: solid none none none !important;
  131. border-radius: 0px 0px var(--uu-dialog-border-radius) var(--uu-dialog-border-radius);
  132. }
  133. .uu-dialog-footer-buttons-cont button:not(:last-of-type) {
  134. margin-right: 15px;
  135. }`;
  136. /** ID of the last opened (top-most) dialog */
  137. export let currentDialogId: string | null = null;
  138. /** IDs of all currently open dialogs, top-most first */
  139. export const openDialogs: string[] = [];
  140. export const defaultStrings = {
  141. closeDialogTooltip: "Click to close the dialog",
  142. };
  143. /** Options passed to the Dialog constructor */
  144. export interface DialogOptions {
  145. /** ID that gets added to child element IDs - has to be unique and conform to HTML ID naming rules! */
  146. id: string;
  147. /** Target and max width of the dialog in pixels */
  148. width: number;
  149. /** Target and max height of the dialog in pixels */
  150. height: number;
  151. /** Whether the dialog should close when the background is clicked - defaults to true */
  152. closeOnBgClick?: boolean;
  153. /** Whether the dialog should close when the escape key is pressed - defaults to true */
  154. closeOnEscPress?: boolean;
  155. /** Whether the dialog should be destroyed when it's closed - defaults to false */
  156. destroyOnClose?: boolean;
  157. /** Whether the dialog should be unmounted when it's closed - defaults to true - superseded by destroyOnClose */
  158. unmountOnClose?: boolean;
  159. /** Whether all listeners should be removed when the dialog is destroyed - defaults to true */
  160. removeListenersOnDestroy?: boolean;
  161. /** Whether the dialog should have a smaller overall appearance - defaults to false */
  162. small?: boolean;
  163. /** Where to align or anchor the dialog vertically - defaults to "center" */
  164. verticalAlign?: "top" | "center" | "bottom";
  165. /** Strings used in the dialog (used for translations) - defaults to the default English strings */
  166. strings?: Partial<typeof defaultStrings>;
  167. /** CSS to apply to the dialog - defaults to the {@linkcode defaultDialogCss} */
  168. dialogCss?: string;
  169. /** Called to render the body of the dialog */
  170. renderBody: () => HTMLElement | Promise<HTMLElement>;
  171. /** Called to render the header of the dialog - leave undefined for a blank header */
  172. renderHeader?: () => HTMLElement | Promise<HTMLElement>;
  173. /** Called to render the footer of the dialog - leave undefined for no footer */
  174. renderFooter?: () => HTMLElement | Promise<HTMLElement>;
  175. /** Called to render the close button of the dialog - leave undefined for no close button */
  176. renderCloseBtn?: () => HTMLElement | Promise<HTMLElement>;
  177. }
  178. /** Creates and manages a modal dialog element */
  179. export class Dialog extends NanoEmitter<{
  180. /** Emitted just **after** the dialog is closed */
  181. close: () => void;
  182. /** Emitted just **after** the dialog is opened */
  183. open: () => void;
  184. /** Emitted just **after** the dialog contents are rendered */
  185. render: () => void;
  186. /** Emitted just **after** the dialog contents are cleared */
  187. clear: () => void;
  188. /** Emitted just **after** the dialog is destroyed and **before** all listeners are removed */
  189. destroy: () => void;
  190. }> {
  191. /** Options passed to the dialog in the constructor */
  192. public readonly options: DialogOptions;
  193. /** ID that gets added to child element IDs - has to be unique and conform to HTML ID naming rules! */
  194. public readonly id: string;
  195. /** Strings used in the dialog (used for translations) */
  196. public strings: typeof defaultStrings;
  197. protected dialogOpen = false;
  198. protected dialogMounted = false;
  199. constructor(options: DialogOptions) {
  200. super();
  201. const { strings, ...opts } = options;
  202. this.strings = {
  203. ...defaultStrings,
  204. ...(strings ?? {}),
  205. };
  206. this.options = {
  207. closeOnBgClick: true,
  208. closeOnEscPress: true,
  209. destroyOnClose: false,
  210. unmountOnClose: true,
  211. removeListenersOnDestroy: true,
  212. small: false,
  213. verticalAlign: "center",
  214. ...opts,
  215. };
  216. this.id = opts.id;
  217. }
  218. //#region public
  219. /** Call after DOMContentLoaded to pre-render the dialog and invisibly mount it in the DOM */
  220. public async mount(): Promise<HTMLElement | void> {
  221. if(this.dialogMounted)
  222. return;
  223. this.dialogMounted = true;
  224. if(!document.querySelector("style.uu-dialog-css"))
  225. addGlobalStyle(this.options.dialogCss ?? defaultDialogCss).classList.add("uu-dialog-css");
  226. const bgElem = document.createElement("div");
  227. bgElem.id = `uu-${this.id}-dialog-bg`;
  228. bgElem.classList.add("uu-dialog-bg");
  229. if(this.options.closeOnBgClick)
  230. bgElem.ariaLabel = bgElem.title = this.getString("closeDialogTooltip");
  231. bgElem.style.setProperty("--uu-dialog-width-max", `${this.options.width}px`);
  232. bgElem.style.setProperty("--uu-dialog-height-max", `${this.options.height}px`);
  233. bgElem.style.visibility = "hidden";
  234. bgElem.style.display = "none";
  235. bgElem.inert = true;
  236. bgElem.appendChild(await this.getDialogContent());
  237. document.body.appendChild(bgElem);
  238. this.attachListeners(bgElem);
  239. this.events.emit("render");
  240. return bgElem;
  241. }
  242. /** Closes the dialog and clears all its contents (unmounts elements from the DOM) in preparation for a new rendering call */
  243. public unmount(): void {
  244. this.close();
  245. this.dialogMounted = false;
  246. const clearSelectors = [
  247. `#uu-${this.id}-dialog-bg`,
  248. `#uu-style-dialog-${this.id}`,
  249. ];
  250. for(const sel of clearSelectors)
  251. document.querySelector(sel)?.remove();
  252. this.events.emit("clear");
  253. }
  254. /** Clears the DOM of the dialog and then renders it again */
  255. public async remount(): Promise<void> {
  256. this.unmount();
  257. await this.mount();
  258. }
  259. /**
  260. * Opens the dialog - also mounts it if it hasn't been mounted yet
  261. * Prevents default action and immediate propagation of the passed event
  262. */
  263. public async open(e?: MouseEvent | KeyboardEvent): Promise<HTMLElement | void> {
  264. e?.preventDefault();
  265. e?.stopImmediatePropagation();
  266. if(this.isOpen())
  267. return;
  268. this.dialogOpen = true;
  269. if(openDialogs.includes(this.id))
  270. throw new Error(`A dialog with the same ID of '${this.id}' already exists and is open!`);
  271. if(!this.isMounted())
  272. await this.mount();
  273. const dialogBg = document.querySelector<HTMLElement>(`#uu-${this.id}-dialog-bg`);
  274. if(!dialogBg)
  275. return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
  276. dialogBg.style.visibility = "visible";
  277. dialogBg.style.display = "block";
  278. dialogBg.inert = false;
  279. currentDialogId = this.id;
  280. openDialogs.unshift(this.id);
  281. // make sure all other dialogs are inert
  282. for(const dialogId of openDialogs)
  283. if(dialogId !== this.id)
  284. document.querySelector(`#uu-${dialogId}-dialog-bg`)?.setAttribute("inert", "true");
  285. // make sure body is inert and scroll is locked
  286. document.body.classList.remove("uu-no-select");
  287. document.body.setAttribute("inert", "true");
  288. this.events.emit("open");
  289. return dialogBg;
  290. }
  291. /** Closes the dialog - prevents default action and immediate propagation of the passed event */
  292. public close(e?: MouseEvent | KeyboardEvent): void {
  293. e?.preventDefault();
  294. e?.stopImmediatePropagation();
  295. if(!this.isOpen())
  296. return;
  297. this.dialogOpen = false;
  298. const dialogBg = document.querySelector<HTMLElement>(`#uu-${this.id}-dialog-bg`);
  299. if(!dialogBg)
  300. return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
  301. dialogBg.style.visibility = "hidden";
  302. dialogBg.style.display = "none";
  303. dialogBg.inert = true;
  304. openDialogs.splice(openDialogs.indexOf(this.id), 1);
  305. currentDialogId = openDialogs[0] ?? null;
  306. // make sure the new top-most dialog is not inert
  307. if(currentDialogId)
  308. document.querySelector(`#uu-${currentDialogId}-dialog-bg`)?.removeAttribute("inert");
  309. // remove the scroll lock and inert attribute on the body if no dialogs are open
  310. if(openDialogs.length === 0) {
  311. document.body.classList.add("uu-no-select");
  312. document.body.removeAttribute("inert");
  313. }
  314. this.events.emit("close");
  315. if(this.options.destroyOnClose)
  316. this.destroy();
  317. // don't destroy *and* unmount at the same time
  318. else if(this.options.unmountOnClose)
  319. this.unmount();
  320. }
  321. /** Returns true if the dialog is currently open */
  322. public isOpen(): boolean {
  323. return this.dialogOpen;
  324. }
  325. /** Returns true if the dialog is currently mounted */
  326. public isMounted(): boolean {
  327. return this.dialogMounted;
  328. }
  329. /** Clears the DOM of the dialog and removes all event listeners */
  330. public destroy(): void {
  331. this.unmount();
  332. this.events.emit("destroy");
  333. this.options.removeListenersOnDestroy && this.unsubscribeAll();
  334. }
  335. //#region static
  336. /** Returns the ID of the top-most dialog (the dialog that has been opened last) */
  337. public static getCurrentDialogId(): string | null {
  338. return currentDialogId;
  339. }
  340. /** Returns the IDs of all currently open dialogs, top-most first */
  341. public static getOpenDialogs(): string[] {
  342. return openDialogs;
  343. }
  344. //#region protected
  345. protected getString(key: keyof typeof defaultStrings): string {
  346. return this.strings[key] ?? defaultStrings[key];
  347. }
  348. /** Called once to attach all generic event listeners */
  349. protected attachListeners(bgElem: HTMLElement): void {
  350. if(this.options.closeOnBgClick) {
  351. bgElem.addEventListener("click", (e) => {
  352. if(this.isOpen() && (e.target as HTMLElement)?.id === `uu-${this.id}-dialog-bg`)
  353. this.close(e);
  354. });
  355. }
  356. if(this.options.closeOnEscPress) {
  357. document.body.addEventListener("keydown", (e) => {
  358. if(e.key === "Escape" && this.isOpen() && Dialog.getCurrentDialogId() === this.id)
  359. this.close(e);
  360. });
  361. }
  362. }
  363. //#region protected
  364. /**
  365. * Adds generic, accessible interaction listeners to the passed element.
  366. * All listeners have the default behavior prevented and stop propagation (for keyboard events only as long as the captured key is valid).
  367. * @param listenerOptions Provide a {@linkcode listenerOptions} object to configure the listeners
  368. */
  369. protected onInteraction<
  370. TElem extends HTMLElement
  371. > (
  372. elem: TElem,
  373. listener: (evt: MouseEvent | KeyboardEvent) => void,
  374. listenerOptions?: AddEventListenerOptions & {
  375. preventDefault?: boolean;
  376. stopPropagation?: boolean;
  377. },
  378. ): void {
  379. const { preventDefault = true, stopPropagation = true, ...listenerOpts } = listenerOptions ?? {};
  380. const interactionKeys = ["Enter", " ", "Space"];
  381. const proxListener = (e: MouseEvent | KeyboardEvent): void => {
  382. if(e instanceof KeyboardEvent) {
  383. if(interactionKeys.includes(e.key)) {
  384. preventDefault && e.preventDefault();
  385. stopPropagation && e.stopPropagation();
  386. }
  387. else return;
  388. }
  389. else if(e instanceof MouseEvent) {
  390. preventDefault && e.preventDefault();
  391. stopPropagation && e.stopPropagation();
  392. }
  393. // clean up the other listener that isn't automatically removed if `once` is set
  394. listenerOpts?.once && e.type === "keydown" && elem.removeEventListener("click", proxListener, listenerOpts);
  395. listenerOpts?.once && e.type === "click" && elem.removeEventListener("keydown", proxListener, listenerOpts);
  396. listener(e);
  397. };
  398. elem.addEventListener("click", proxListener, listenerOpts);
  399. elem.addEventListener("keydown", proxListener, listenerOpts);
  400. }
  401. /** Returns the dialog content element and all its children */
  402. protected async getDialogContent(): Promise<HTMLElement> {
  403. const header = this.options.renderHeader?.();
  404. const footer = this.options.renderFooter?.();
  405. const dialogWrapperEl = document.createElement("div");
  406. dialogWrapperEl.id = `uu-${this.id}-dialog`;
  407. dialogWrapperEl.classList.add("uu-dialog");
  408. dialogWrapperEl.ariaLabel = dialogWrapperEl.title = "";
  409. dialogWrapperEl.role = "dialog";
  410. dialogWrapperEl.setAttribute("aria-labelledby", `uu-${this.id}-dialog-title`);
  411. dialogWrapperEl.setAttribute("aria-describedby", `uu-${this.id}-dialog-body`);
  412. if(this.options.verticalAlign !== "center")
  413. dialogWrapperEl.classList.add(`align-${this.options.verticalAlign}`);
  414. //#region header
  415. const headerWrapperEl = document.createElement("div");
  416. headerWrapperEl.classList.add("uu-dialog-header");
  417. this.options.small && headerWrapperEl.classList.add("small");
  418. if(header) {
  419. const headerTitleWrapperEl = document.createElement("div");
  420. headerTitleWrapperEl.id = `uu-${this.id}-dialog-title`;
  421. headerTitleWrapperEl.classList.add("uu-dialog-title-wrapper");
  422. headerTitleWrapperEl.role = "heading";
  423. headerTitleWrapperEl.ariaLevel = "1";
  424. headerTitleWrapperEl.appendChild(header instanceof Promise ? await header : header);
  425. headerWrapperEl.appendChild(headerTitleWrapperEl);
  426. }
  427. else {
  428. // insert element to pad the header height
  429. const padEl = document.createElement("div");
  430. padEl.classList.add("uu-dialog-header-pad", this.options.small ? "small" : "");
  431. headerWrapperEl.appendChild(padEl);
  432. }
  433. if(this.options.renderCloseBtn) {
  434. const closeBtnEl = await this.options.renderCloseBtn();
  435. closeBtnEl.classList.add("uu-dialog-close");
  436. this.options.small && closeBtnEl.classList.add("small");
  437. closeBtnEl.tabIndex = 0;
  438. if(closeBtnEl.hasAttribute("alt"))
  439. closeBtnEl.setAttribute("alt", this.getString("closeDialogTooltip"));
  440. closeBtnEl.title = closeBtnEl.ariaLabel = this.getString("closeDialogTooltip");
  441. this.onInteraction(closeBtnEl, () => this.close());
  442. headerWrapperEl.appendChild(closeBtnEl);
  443. }
  444. dialogWrapperEl.appendChild(headerWrapperEl);
  445. //#region body
  446. const dialogBodyElem = document.createElement("div");
  447. dialogBodyElem.id = `uu-${this.id}-dialog-body`;
  448. dialogBodyElem.classList.add("uu-dialog-body");
  449. this.options.small && dialogBodyElem.classList.add("small");
  450. const body = this.options.renderBody();
  451. dialogBodyElem.appendChild(body instanceof Promise ? await body : body);
  452. dialogWrapperEl.appendChild(dialogBodyElem);
  453. //#region footer
  454. if(footer) {
  455. const footerWrapper = document.createElement("div");
  456. footerWrapper.classList.add("uu-dialog-footer-cont");
  457. dialogWrapperEl.appendChild(footerWrapper);
  458. footerWrapper.appendChild(footer instanceof Promise ? await footer : footer);
  459. }
  460. return dialogWrapperEl;
  461. }
  462. }