1import { createSignal, type JSX, onMount, Show } from "solid-js";
2import { render } from "solid-js/web";
3import { reason } from "../api.ts";
4
5type Content = JSX.Element | (() => JSX.Element);
6const build = (content: Content) => (typeof content === "function" ? content() : content);
7
8interface DialogOptions {
9 title: string;
10 /**
11 * The consequence, read out with the title. Pass a function when it reads signals or uses control flow, so it's
12 * built inside the dialog rather than in the click handler, which has no owner.
13 */
14 description?: Content;
15 /** Form fields and options under the description (and text field), built inside the dialog like `description`. */
16 body?: Content;
17 /** Names the action, like "restart"; never "ok". */
18 confirmLabel: string;
19 destructive?: boolean;
20 canConfirm?: () => boolean;
21 /** Takes focus once the dialog closes, instead of the element that opened it. */
22 returnFocus?: HTMLElement;
23 onClose?: () => void;
24 /**
25 * Gets the body's named fields. The dialog stays open with a spinner until this settles; a rejection shakes it
26 * and shows the reason.
27 */
28 onConfirm: (form: FormData) => unknown;
29}
30
31interface TextDialogOptions extends Omit<DialogOptions, "onConfirm"> {
32 /** Visible label for the field. */
33 label: string;
34 placeholder?: string;
35 initialValue?: string;
36 /** Gates the confirm button; defaults to non-empty. */
37 validateInput?: (value: string) => boolean;
38 onConfirm: (value: string, form: FormData) => unknown;
39}
40
41const SHAKE = [0, -8, 8, -8, 8, -8, 8, 0].map((x) => ({ transform: `translateX(${x}px)` }));
42const reduced = matchMedia("(prefers-reduced-motion: reduce)");
43let dialogs = 0;
44
45export const showConfirmDialog = (options: DialogOptions) => open(options);
46
47/** Like showConfirmDialog with a text field; Enter submits once `validateInput` passes. */
48export const showTextDialog = (options: TextDialogOptions) =>
49 open({ ...options, onConfirm: (form) => options.onConfirm(String(form.get("value")), form) }, options);
50
51function open(options: DialogOptions, field?: TextDialogOptions) {
52 const host = document.body.appendChild(document.createElement("div"));
53 const id = `dialog-${++dialogs}`;
54 const dispose = render(() => {
55 const [value, setValue] = createSignal(field?.initialValue ?? "");
56 const [pending, setPending] = createSignal(false);
57 const [error, setError] = createSignal("");
58 const valid = () => (!field || (field.validateInput ?? Boolean)(value())) && (options.canConfirm?.() ?? true);
59 let dialog!: HTMLDialogElement;
60 let pressedOutside = false;
61
62 const close = () => {
63 if (pending()) return;
64 dialog.classList.add("closing");
65 setTimeout(() => dialog.close(), reduced.matches ? 0 : 140);
66 };
67
68 const submit = async (event: SubmitEvent) => {
69 event.preventDefault();
70 if (pending() || !valid()) return;
71 const form = new FormData(event.currentTarget as HTMLFormElement);
72 setPending(true);
73 setError("");
74 try {
75 await options.onConfirm(form);
76 setPending(false);
77 close();
78 } catch (failure) {
79 setPending(false);
80 setError(reason(failure));
81 if (!reduced.matches) dialog.animate(SHAKE, { duration: 380, easing: "cubic-bezier(0.36, 0.07, 0.19, 0.97)" });
82 }
83 };
84
85 onMount(() => dialog.showModal());
86 const body = build(options.body);
87
88 return (
89 <dialog ref={dialog} class="dialog" aria-labelledby={`${id}-title`}
90 aria-describedby={options.description ? `${id}-description` : undefined}
91 onCancel={(event) => {
92 event.preventDefault();
93 close();
94 }}
95 onClose={() => {
96 dispose();
97 host.remove();
98 options.returnFocus?.focus();
99 options.onClose?.();
100 }}
101 onPointerDown={(event) => (pressedOutside = event.target === dialog)}
102 onClick={(event) => pressedOutside && event.target === dialog && close()}>
103 <form onSubmit={submit}>
104 <h2 id={`${id}-title`}>{options.title}</h2>
105 <Show when={options.description}>
106 <div id={`${id}-description`} class="description">{build(options.description)}</div>
107 </Show>
108 <Show when={field}>
109 {(field) => (
110 <label class="field">
111 {field().label}
112 <input name="value" class="search" value={value()} placeholder={field().placeholder} autofocus
113 readOnly={pending()} autocomplete="off" spellcheck={false}
114 onInput={(event) => setValue(event.currentTarget.value)} />
115 </label>
116 )}
117 </Show>
118 <Show when={options.body}><fieldset disabled={pending()}>{body}</fieldset></Show>
119 <Show when={error()}><p class="error" role="alert">{error()}</p></Show>
120 <div class="actions">
121 <button type="button" class="button" disabled={pending()} onClick={close}>back<kbd aria-hidden="true">esc</kbd></button>
122 {/* aria-disabled rather than disabled while pending, so focus stays put for a retry. */}
123 <button type="submit" class="button primary" classList={{ danger: options.destructive }}
124 autofocus={!field} disabled={!valid()} aria-disabled={pending()} aria-busy={pending()}>
125 {options.confirmLabel}<kbd aria-hidden="true">enter</kbd>
126 </button>
127 </div>
128 </form>
129 </dialog>
130 );
131 }, host);
132}