prompt.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import { consumeStringGen, type StringGen, type Stringifiable } from "@sv443-network/userutils";
  2. import { getOS, resourceAsString, setInnerHtml, t } from "../utils/index.js";
  3. import { BytmDialog } from "../components/BytmDialog.js";
  4. import { addSelectorListener } from "../observers.js";
  5. import "./prompt.css";
  6. //#region types
  7. type PromptStringGen = Stringifiable | ((type: PromptType) => Stringifiable | Promise<Stringifiable>);
  8. export type PromptDialogRenderProps = ConfirmRenderProps | AlertRenderProps | PromptRenderProps;
  9. export type PromptType = PromptDialogRenderProps["type"];
  10. type ConfirmRenderProps = BaseRenderProps & {
  11. type: "confirm";
  12. };
  13. type AlertRenderProps = BaseRenderProps & {
  14. type: "alert";
  15. };
  16. type PromptRenderProps = BaseRenderProps & {
  17. type: "prompt";
  18. defaultValue?: StringGen;
  19. };
  20. type BaseRenderProps = {
  21. message: PromptStringGen;
  22. confirmBtnText?: PromptStringGen;
  23. confirmBtnTooltip?: PromptStringGen;
  24. denyBtnText?: PromptStringGen;
  25. denyBtnTooltip?: PromptStringGen;
  26. };
  27. export type PromptDialogResolveVal = boolean | string | null;
  28. export type ShowPromptProps = Partial<PromptDialogRenderProps> & Required<Pick<PromptDialogRenderProps, "message">>;
  29. //#region PromptDialog
  30. let promptDialog: PromptDialog | null = null;
  31. class PromptDialog extends BytmDialog {
  32. constructor(props: PromptDialogRenderProps) {
  33. super({
  34. id: "prompt-dialog",
  35. width: 500,
  36. height: 400,
  37. destroyOnClose: true,
  38. closeBtnEnabled: true,
  39. closeOnBgClick: props.type !== "prompt",
  40. closeOnEscPress: true,
  41. small: true,
  42. renderHeader: () => this.renderHeader(props),
  43. renderBody: () => this.renderBody(props),
  44. renderFooter: () => this.renderFooter(props),
  45. });
  46. this.on("render", this.focusOnRender);
  47. }
  48. protected emitResolve(val: PromptDialogResolveVal) {
  49. this.events.emit("resolve", val);
  50. }
  51. protected async renderHeader({ type }: PromptDialogRenderProps) {
  52. const headerEl = document.createElement("div");
  53. headerEl.id = "bytm-prompt-dialog-header";
  54. setInnerHtml(headerEl, await resourceAsString(type === "alert" ? "icon-alert" : "icon-prompt"));
  55. return headerEl;
  56. }
  57. protected async renderBody({ type, message, ...rest }: PromptDialogRenderProps) {
  58. const contElem = document.createElement("div");
  59. contElem.classList.add(`bytm-prompt-type-${type}`);
  60. const upperContElem = document.createElement("div");
  61. upperContElem.id = "bytm-prompt-dialog-upper-cont";
  62. contElem.appendChild(upperContElem);
  63. const messageElem = document.createElement("p");
  64. messageElem.id = "bytm-prompt-dialog-message";
  65. messageElem.role = "alert";
  66. messageElem.ariaLive = "polite";
  67. messageElem.tabIndex = 0;
  68. messageElem.textContent = String(message);
  69. upperContElem.appendChild(messageElem);
  70. if(type === "prompt") {
  71. const inputElem = document.createElement("input");
  72. inputElem.id = "bytm-prompt-dialog-input";
  73. inputElem.type = "text";
  74. inputElem.autocomplete = "off";
  75. inputElem.spellcheck = false;
  76. inputElem.value = "defaultValue" in rest && rest.defaultValue
  77. ? await consumeStringGen(rest.defaultValue)
  78. : "";
  79. const inputEnterListener = (e: KeyboardEvent) => {
  80. if(e.key === "Enter") {
  81. inputElem.removeEventListener("keydown", inputEnterListener);
  82. this.emitResolve(inputElem?.value?.trim() ?? null);
  83. promptDialog?.close();
  84. }
  85. };
  86. inputElem.addEventListener("keydown", inputEnterListener);
  87. promptDialog?.once("close", () => inputElem.removeEventListener("keydown", inputEnterListener));
  88. upperContElem.appendChild(inputElem);
  89. }
  90. return contElem;
  91. }
  92. protected async renderFooter({ type, ...rest }: PromptDialogRenderProps) {
  93. const buttonsWrapper = document.createElement("div");
  94. buttonsWrapper.id = "bytm-prompt-dialog-button-wrapper";
  95. const buttonsCont = document.createElement("div");
  96. buttonsCont.id = "bytm-prompt-dialog-buttons-cont";
  97. let confirmBtn: HTMLButtonElement | undefined;
  98. if(type === "confirm" || type === "prompt") {
  99. confirmBtn = document.createElement("button");
  100. confirmBtn.id = "bytm-prompt-dialog-confirm";
  101. confirmBtn.classList.add("bytm-prompt-dialog-button");
  102. confirmBtn.textContent = await this.consumePromptStringGen(type, rest.confirmBtnText, t("prompt_confirm"));
  103. confirmBtn.ariaLabel = confirmBtn.title = await this.consumePromptStringGen(type, rest.confirmBtnTooltip, t("click_to_confirm_tooltip"));
  104. confirmBtn.tabIndex = 0;
  105. confirmBtn.addEventListener("click", () => {
  106. this.emitResolve(type === "confirm" ? true : (document.querySelector<HTMLInputElement>("#bytm-prompt-dialog-input"))?.value?.trim() ?? null);
  107. promptDialog?.close();
  108. }, { once: true });
  109. }
  110. const closeBtn = document.createElement("button");
  111. closeBtn.id = "bytm-prompt-dialog-close";
  112. closeBtn.classList.add("bytm-prompt-dialog-button");
  113. closeBtn.textContent = await this.consumePromptStringGen(type, rest.denyBtnText, t(type === "alert" ? "prompt_close" : "prompt_cancel"));
  114. closeBtn.ariaLabel = closeBtn.title = await this.consumePromptStringGen(type, rest.denyBtnTooltip, t(type === "alert" ? "click_to_close_tooltip" : "click_to_cancel_tooltip"));
  115. closeBtn.tabIndex = 0;
  116. closeBtn.addEventListener("click", () => {
  117. const resVals: Record<PromptType, boolean | null> = {
  118. alert: true,
  119. confirm: false,
  120. prompt: null,
  121. };
  122. this.emitResolve(resVals[type]);
  123. promptDialog?.close();
  124. }, { once: true });
  125. confirmBtn && getOS() !== "mac" && buttonsCont.appendChild(confirmBtn);
  126. buttonsCont.appendChild(closeBtn);
  127. confirmBtn && getOS() === "mac" && buttonsCont.appendChild(confirmBtn);
  128. buttonsWrapper.appendChild(buttonsCont);
  129. return buttonsWrapper;
  130. }
  131. /** Converts a {@linkcode stringGen} (stringifiable value or sync or async function that returns a stringifiable value) to a string - uses {@linkcode fallback} as a fallback */
  132. protected async consumePromptStringGen(curPromptType: PromptType, stringGen?: PromptStringGen, fallback?: Stringifiable): Promise<string> {
  133. if(typeof stringGen === "function")
  134. return await stringGen(curPromptType);
  135. return String(stringGen ?? fallback);
  136. }
  137. /** Called on render to focus on the confirm or cancel button or text input, depending on prompt type */
  138. protected focusOnRender() {
  139. const inputElem = document.querySelector<HTMLInputElement>("#bytm-prompt-dialog-input");
  140. if(inputElem)
  141. return inputElem.focus();
  142. let captureEnterKey = true;
  143. document.addEventListener("keydown", (e) => {
  144. if(e.key === "Enter" && captureEnterKey) {
  145. const confBtn = document.querySelector<HTMLButtonElement>("#bytm-prompt-dialog-confirm");
  146. const closeBtn = document.querySelector<HTMLButtonElement>("#bytm-prompt-dialog-close");
  147. if(confBtn || closeBtn) {
  148. confBtn?.click() ?? closeBtn?.click();
  149. captureEnterKey = false;
  150. }
  151. }
  152. }, { capture: true, once: true });
  153. }
  154. }
  155. //#region showPrompt fn
  156. /** Shows a `confirm()`-like prompt dialog with the specified message and resolves true if the user confirms it or false if they deny or cancel it */
  157. export function showPrompt(props: ConfirmRenderProps): Promise<boolean>;
  158. /** Shows an `alert()`-like prompt dialog with the specified message and always resolves true once the user dismisses it - for this type, only the close button will exist */
  159. export function showPrompt(props: AlertRenderProps): Promise<true>;
  160. /** Shows a `prompt()`-like dialog with the specified message and default value and resolves the entered value if the user confirms it or null if they cancel it */
  161. export function showPrompt(props: PromptRenderProps): Promise<string | null>;
  162. /** Custom dialog to emulate and enhance the behavior of the native `confirm()`, `alert()`, and `prompt()` functions */
  163. export function showPrompt({ type, ...rest }: PromptDialogRenderProps): Promise<PromptDialogResolveVal> {
  164. return new Promise<PromptDialogResolveVal>((resolve) => {
  165. if(BytmDialog.getOpenDialogs().includes("prompt-dialog"))
  166. promptDialog?.close();
  167. promptDialog = new PromptDialog({ type, ...rest });
  168. promptDialog.once("render" as "_", () => {
  169. addSelectorListener<HTMLButtonElement>("bytmDialogContainer", `#bytm-prompt-dialog-${type === "alert" ? "close" : "confirm"}`, {
  170. listener: (btn) => btn.focus(),
  171. });
  172. });
  173. // make config menu inert while prompt dialog is open
  174. promptDialog.once("open", () => document.querySelector("#bytm-cfg-menu")?.setAttribute("inert", "true"));
  175. promptDialog.once("close", () => document.querySelector("#bytm-cfg-menu")?.removeAttribute("inert"));
  176. let resolveVal: PromptDialogResolveVal | undefined;
  177. const tryResolve = () => resolve(typeof resolveVal !== "undefined" ? resolveVal : false);
  178. let closeUnsub: (() => void) | undefined; // eslint-disable-line prefer-const
  179. const resolveUnsub = promptDialog.on("resolve" as "_", (val: PromptDialogResolveVal) => {
  180. resolveUnsub();
  181. if(resolveVal !== undefined)
  182. return;
  183. resolveVal = val;
  184. tryResolve();
  185. closeUnsub?.();
  186. });
  187. closeUnsub = promptDialog.on("close", () => {
  188. closeUnsub!();
  189. if(resolveVal !== undefined)
  190. return;
  191. resolveVal = type === "alert";
  192. if(type === "prompt")
  193. resolveVal = null;
  194. tryResolve();
  195. resolveUnsub();
  196. });
  197. promptDialog.open();
  198. });
  199. }