1
0

Dialog.ts 17 KB

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