Dialog.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. import { NanoEmitter } from "./NanoEmitter.js";
  2. import { addGlobalStyle } from "./dom.js";
  3. export const defaultDialogCss = `\
  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;
  189. /** ID that gets added to child element IDs - has to be unique and conform to HTML ID naming rules! */
  190. public readonly id;
  191. /** Strings used in the dialog (used for translations) */
  192. public strings;
  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. smallHeader: false,
  209. verticalAlign: "center",
  210. dialogCss: defaultDialogCss,
  211. ...opts,
  212. };
  213. this.id = opts.id;
  214. }
  215. //#region public
  216. /** Call after DOMContentLoaded to pre-render the dialog and invisibly mount it in the DOM */
  217. public async mount() {
  218. if(this.dialogMounted)
  219. return;
  220. this.dialogMounted = true;
  221. if(!document.querySelector("style.uu-dialog-css"))
  222. addGlobalStyle(this.options.dialogCss).classList.add("uu-dialog-css");
  223. const bgElem = document.createElement("div");
  224. bgElem.id = `uu-${this.id}-dialog-bg`;
  225. bgElem.classList.add("uu-dialog-bg");
  226. if(this.options.closeOnBgClick)
  227. bgElem.ariaLabel = bgElem.title = this.getString("closeDialogTooltip");
  228. bgElem.style.setProperty("--uu-dialog-width-max", `${this.options.width}px`);
  229. bgElem.style.setProperty("--uu-dialog-height-max", `${this.options.height}px`);
  230. bgElem.style.visibility = "hidden";
  231. bgElem.style.display = "none";
  232. bgElem.inert = true;
  233. bgElem.appendChild(await this.getDialogContent());
  234. document.body.appendChild(bgElem);
  235. this.attachListeners(bgElem);
  236. this.events.emit("render");
  237. return bgElem;
  238. }
  239. /** Closes the dialog and clears all its contents (unmounts elements from the DOM) in preparation for a new rendering call */
  240. public unmount() {
  241. this.close();
  242. this.dialogMounted = false;
  243. const clearSelectors = [
  244. `#uu-${this.id}-dialog-bg`,
  245. `#uu-style-dialog-${this.id}`,
  246. ];
  247. for(const sel of clearSelectors)
  248. document.querySelector(sel)?.remove();
  249. this.events.emit("clear");
  250. }
  251. /** Clears the DOM of the dialog and then renders it again */
  252. public async remount() {
  253. this.unmount();
  254. await this.mount();
  255. }
  256. /**
  257. * Opens the dialog - also mounts it if it hasn't been mounted yet
  258. * Prevents default action and immediate propagation of the passed event
  259. */
  260. public async open(e?: MouseEvent | KeyboardEvent) {
  261. e?.preventDefault();
  262. e?.stopImmediatePropagation();
  263. if(this.isOpen())
  264. return;
  265. this.dialogOpen = true;
  266. if(openDialogs.includes(this.id))
  267. throw new Error(`A dialog with the same ID of '${this.id}' already exists and is open!`);
  268. if(!this.isMounted())
  269. await this.mount();
  270. const dialogBg = document.querySelector<HTMLElement>(`#uu-${this.id}-dialog-bg`);
  271. if(!dialogBg)
  272. return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
  273. dialogBg.style.visibility = "visible";
  274. dialogBg.style.display = "block";
  275. dialogBg.inert = false;
  276. currentDialogId = this.id;
  277. openDialogs.unshift(this.id);
  278. // make sure all other dialogs are inert
  279. for(const dialogId of openDialogs)
  280. if(dialogId !== this.id)
  281. document.querySelector(`#uu-${dialogId}-dialog-bg`)?.setAttribute("inert", "true");
  282. // make sure body is inert and scroll is locked
  283. document.body.classList.remove("uu-no-select");
  284. document.body.setAttribute("inert", "true");
  285. this.events.emit("open");
  286. return dialogBg;
  287. }
  288. /** Closes the dialog - prevents default action and immediate propagation of the passed event */
  289. public close(e?: MouseEvent | KeyboardEvent) {
  290. e?.preventDefault();
  291. e?.stopImmediatePropagation();
  292. if(!this.isOpen())
  293. return;
  294. this.dialogOpen = false;
  295. const dialogBg = document.querySelector<HTMLElement>(`#uu-${this.id}-dialog-bg`);
  296. if(!dialogBg)
  297. return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
  298. dialogBg.style.visibility = "hidden";
  299. dialogBg.style.display = "none";
  300. dialogBg.inert = true;
  301. openDialogs.splice(openDialogs.indexOf(this.id), 1);
  302. currentDialogId = openDialogs[0] ?? null;
  303. // make sure the new top-most dialog is not inert
  304. if(currentDialogId)
  305. document.querySelector(`#uu-${currentDialogId}-dialog-bg`)?.removeAttribute("inert");
  306. // remove the scroll lock and inert attribute on the body if no dialogs are open
  307. if(openDialogs.length === 0) {
  308. document.body.classList.add("uu-no-select");
  309. document.body.removeAttribute("inert");
  310. }
  311. this.events.emit("close");
  312. if(this.options.destroyOnClose)
  313. this.destroy();
  314. // don't destroy *and* unmount at the same time
  315. else if(this.options.unmountOnClose)
  316. this.unmount();
  317. }
  318. /** Returns true if the dialog is currently open */
  319. public isOpen() {
  320. return this.dialogOpen;
  321. }
  322. /** Returns true if the dialog is currently mounted */
  323. public isMounted() {
  324. return this.dialogMounted;
  325. }
  326. /** Clears the DOM of the dialog and removes all event listeners */
  327. public destroy() {
  328. this.unmount();
  329. this.events.emit("destroy");
  330. this.options.removeListenersOnDestroy && this.unsubscribeAll();
  331. }
  332. //#region static
  333. /** Returns the ID of the top-most dialog (the dialog that has been opened last) */
  334. public static getCurrentDialogId() {
  335. return currentDialogId;
  336. }
  337. /** Returns the IDs of all currently open dialogs, top-most first */
  338. public static getOpenDialogs() {
  339. return openDialogs;
  340. }
  341. //#region protected
  342. protected getString(key: keyof typeof defaultStrings) {
  343. return this.strings[key] ?? defaultStrings[key];
  344. }
  345. /** Called once to attach all generic event listeners */
  346. protected attachListeners(bgElem: HTMLElement) {
  347. if(this.options.closeOnBgClick) {
  348. bgElem.addEventListener("click", (e) => {
  349. if(this.isOpen() && (e.target as HTMLElement)?.id === `uu-${this.id}-dialog-bg`)
  350. this.close(e);
  351. });
  352. }
  353. if(this.options.closeOnEscPress) {
  354. document.body.addEventListener("keydown", (e) => {
  355. if(e.key === "Escape" && this.isOpen() && Dialog.getCurrentDialogId() === this.id)
  356. this.close(e);
  357. });
  358. }
  359. }
  360. //#region protected
  361. /**
  362. * Adds generic, accessible interaction listeners to the passed element.
  363. * All listeners have the default behavior prevented and stop propagation (for keyboard events only as long as the captured key is valid).
  364. * @param listenerOptions Provide a {@linkcode listenerOptions} object to configure the listeners
  365. */
  366. protected onInteraction<
  367. TElem extends HTMLElement
  368. > (
  369. elem: TElem,
  370. listener: (evt: MouseEvent | KeyboardEvent) => void,
  371. listenerOptions?: AddEventListenerOptions & {
  372. preventDefault?: boolean;
  373. stopPropagation?: boolean;
  374. },
  375. ) {
  376. const { preventDefault = true, stopPropagation = true, ...listenerOpts } = listenerOptions ?? {};
  377. const interactionKeys = ["Enter", " ", "Space"];
  378. const proxListener = (e: MouseEvent | KeyboardEvent) => {
  379. if(e instanceof KeyboardEvent) {
  380. if(interactionKeys.includes(e.key)) {
  381. preventDefault && e.preventDefault();
  382. stopPropagation && e.stopPropagation();
  383. }
  384. else return;
  385. }
  386. else if(e instanceof MouseEvent) {
  387. preventDefault && e.preventDefault();
  388. stopPropagation && e.stopPropagation();
  389. }
  390. // clean up the other listener that isn't automatically removed if `once` is set
  391. listenerOpts?.once && e.type === "keydown" && elem.removeEventListener("click", proxListener, listenerOpts);
  392. listenerOpts?.once && e.type === "click" && elem.removeEventListener("keydown", proxListener, listenerOpts);
  393. listener(e);
  394. };
  395. elem.addEventListener("click", proxListener, listenerOpts);
  396. elem.addEventListener("keydown", proxListener, listenerOpts);
  397. }
  398. /** Returns the dialog content element and all its children */
  399. protected async getDialogContent() {
  400. const header = this.options.renderHeader?.();
  401. const footer = this.options.renderFooter?.();
  402. const dialogWrapperEl = document.createElement("div");
  403. dialogWrapperEl.id = `uu-${this.id}-dialog`;
  404. dialogWrapperEl.classList.add("uu-dialog");
  405. dialogWrapperEl.ariaLabel = dialogWrapperEl.title = "";
  406. dialogWrapperEl.role = "dialog";
  407. dialogWrapperEl.setAttribute("aria-labelledby", `uu-${this.id}-dialog-title`);
  408. dialogWrapperEl.setAttribute("aria-describedby", `uu-${this.id}-dialog-body`);
  409. if(this.options.verticalAlign !== "center")
  410. dialogWrapperEl.classList.add(`align-${this.options.verticalAlign}`);
  411. //#region header
  412. const headerWrapperEl = document.createElement("div");
  413. headerWrapperEl.classList.add("uu-dialog-header");
  414. this.options.small && headerWrapperEl.classList.add("small");
  415. if(header) {
  416. const headerTitleWrapperEl = document.createElement("div");
  417. headerTitleWrapperEl.id = `uu-${this.id}-dialog-title`;
  418. headerTitleWrapperEl.classList.add("uu-dialog-title-wrapper");
  419. headerTitleWrapperEl.role = "heading";
  420. headerTitleWrapperEl.ariaLevel = "1";
  421. headerTitleWrapperEl.appendChild(header instanceof Promise ? await header : header);
  422. headerWrapperEl.appendChild(headerTitleWrapperEl);
  423. }
  424. else {
  425. // insert element to pad the header height
  426. const padEl = document.createElement("div");
  427. padEl.classList.add("uu-dialog-header-pad", this.options.small ? "small" : "");
  428. headerWrapperEl.appendChild(padEl);
  429. }
  430. if(this.options.renderCloseBtn) {
  431. const closeBtnEl = await this.options.renderCloseBtn();
  432. closeBtnEl.classList.add("uu-dialog-close");
  433. this.options.small && closeBtnEl.classList.add("small");
  434. closeBtnEl.tabIndex = 0;
  435. if(closeBtnEl.hasAttribute("alt"))
  436. closeBtnEl.setAttribute("alt", this.getString("closeDialogTooltip"));
  437. closeBtnEl.title = closeBtnEl.ariaLabel = this.getString("closeDialogTooltip");
  438. this.onInteraction(closeBtnEl, () => this.close());
  439. headerWrapperEl.appendChild(closeBtnEl);
  440. }
  441. dialogWrapperEl.appendChild(headerWrapperEl);
  442. //#region body
  443. const dialogBodyElem = document.createElement("div");
  444. dialogBodyElem.id = `uu-${this.id}-dialog-body`;
  445. dialogBodyElem.classList.add("uu-dialog-body");
  446. this.options.small && dialogBodyElem.classList.add("small");
  447. const body = this.options.renderBody();
  448. dialogBodyElem.appendChild(body instanceof Promise ? await body : body);
  449. dialogWrapperEl.appendChild(dialogBodyElem);
  450. //#region footer
  451. if(footer) {
  452. const footerWrapper = document.createElement("div");
  453. footerWrapper.classList.add("uu-dialog-footer-cont");
  454. dialogWrapperEl.appendChild(footerWrapper);
  455. footerWrapper.appendChild(footer instanceof Promise ? await footer : footer);
  456. }
  457. return dialogWrapperEl;
  458. }
  459. }