@edenapp/solid-kit 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,42 @@
1
+ # @edenapp/solid-kit
2
+
3
+ High-level SolidJS UI utilities for Eden renderer apps.
4
+
5
+ ## Dialogs
6
+
7
+ `@edenapp/solid-kit/dialogs` provides local, in-renderer dialogs with a tiny promise API.
8
+
9
+ ```ts
10
+ import { createDialogs, DialogHost } from "@edenapp/solid-kit/dialogs";
11
+
12
+ const dialogs = createDialogs();
13
+
14
+ // In app root JSX:
15
+ // <DialogHost dialogs={dialogs} />
16
+
17
+ const confirmed = await dialogs.confirm({
18
+ title: "Delete",
19
+ message: "Delete this file?",
20
+ tone: "danger",
21
+ });
22
+ ```
23
+
24
+ Declarative forms are available so app code stays classless/markup-light.
25
+
26
+ ```ts
27
+ import { createDialogs, field } from "@edenapp/solid-kit/dialogs";
28
+
29
+ const dialogs = createDialogs();
30
+
31
+ const result = await dialogs.form({
32
+ title: "New Contact",
33
+ confirmLabel: "Save",
34
+ fields: [
35
+ field.text("firstName", "First Name", { required: true, autofocus: true }),
36
+ field.text("lastName", "Last Name", { required: true }),
37
+ field.email("email", "Email"),
38
+ ] as const,
39
+ });
40
+
41
+ // result -> { firstName: string; lastName: string; email: string } | null
42
+ ```
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@edenapp/solid-kit",
3
+ "version": "0.6.0",
4
+ "description": "High-level SolidJS UI primitives for Eden apps",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.ts",
11
+ "import": "./src/index.ts",
12
+ "default": "./src/index.ts"
13
+ },
14
+ "./dialogs": {
15
+ "types": "./src/dialogs.ts",
16
+ "import": "./src/dialogs.ts",
17
+ "default": "./src/dialogs.ts"
18
+ }
19
+ },
20
+ "files": [
21
+ "src"
22
+ ],
23
+ "scripts": {
24
+ "build": "tsc --noEmit",
25
+ "clean": "rm -rf dist"
26
+ },
27
+ "peerDependencies": {
28
+ "solid-js": "^1.9.0"
29
+ },
30
+ "devDependencies": {
31
+ "typescript": "^5.3.0"
32
+ },
33
+ "keywords": [
34
+ "eden",
35
+ "solid",
36
+ "dialog",
37
+ "renderer"
38
+ ],
39
+ "author": "Dariusz Majnert",
40
+ "license": "MIT",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/b0czek/eden.git",
44
+ "directory": "packages/solid-kit"
45
+ }
46
+ }
@@ -0,0 +1,176 @@
1
+ import type { Accessor, Component, Setter } from "solid-js";
2
+ import { createEffect, onCleanup } from "solid-js";
3
+ import { getDialogRuntime } from "./runtimeRegistry.js";
4
+ import type { DialogRequest } from "./runtimeTypes.js";
5
+ import type {
6
+ CustomDialogRenderContext,
7
+ DialogController,
8
+ DialogSize,
9
+ } from "./types.js";
10
+
11
+ /** Props for the dialogs host component. */
12
+ export interface DialogHostProps {
13
+ /** Controller returned by `createDialogs()`. */
14
+ dialogs: DialogController;
15
+ }
16
+
17
+ const sizeClass = (size: DialogSize) => {
18
+ if (size === "sm") return "eden-modal-sm";
19
+ if (size === "lg") return "eden-modal-lg";
20
+ return "";
21
+ };
22
+
23
+ /** Renders local dialog overlays for a dialogs controller instance. */
24
+ export const DialogHost: Component<DialogHostProps> = (props) => {
25
+ const dialogs = getDialogRuntime(props.dialogs);
26
+ if (!dialogs) {
27
+ console.error(
28
+ "DialogHost received an unsupported controller. Pass the value returned by createDialogs().",
29
+ );
30
+ return null;
31
+ }
32
+
33
+ let primaryActionRef: HTMLButtonElement | undefined;
34
+ let initialFocusRef: HTMLElement | undefined;
35
+ let modalRef: HTMLDivElement | undefined;
36
+
37
+ const createRenderContext = (
38
+ dialog: DialogRequest,
39
+ ): CustomDialogRenderContext<unknown, unknown> => {
40
+ return {
41
+ value: dialog.value as Accessor<unknown>,
42
+ setValue: dialog.setValue as Setter<unknown>,
43
+ canSubmit: dialog.canSubmit,
44
+ setCanSubmit: dialog.setCanSubmit,
45
+ submit: (result) => dialogs.submit(result),
46
+ cancel: dialogs.cancel,
47
+ setPrimaryActionRef: (el) => {
48
+ primaryActionRef = el;
49
+ },
50
+ setInitialFocusRef: (el) => {
51
+ initialFocusRef = el;
52
+ },
53
+ };
54
+ };
55
+
56
+ createEffect(() => {
57
+ const current = dialogs.active();
58
+ if (!current) return;
59
+
60
+ modalRef = undefined;
61
+ primaryActionRef = undefined;
62
+ initialFocusRef = undefined;
63
+
64
+ const previousActive = document.activeElement as HTMLElement | null;
65
+
66
+ queueMicrotask(() => {
67
+ const focusTarget = initialFocusRef ?? primaryActionRef;
68
+ focusTarget?.focus?.();
69
+
70
+ if (
71
+ current.selectInitialFocusText &&
72
+ focusTarget &&
73
+ "select" in focusTarget &&
74
+ typeof focusTarget.select === "function"
75
+ ) {
76
+ focusTarget.select();
77
+ }
78
+ });
79
+
80
+ onCleanup(() => {
81
+ previousActive?.focus?.();
82
+ });
83
+ });
84
+
85
+ createEffect(() => {
86
+ const current = dialogs.active();
87
+ if (!current) return;
88
+
89
+ const handleKeyDown = (e: KeyboardEvent) => {
90
+ e.stopPropagation();
91
+
92
+ if (e.key === "Escape" && current.dismissOnEscape) {
93
+ e.preventDefault();
94
+ dialogs.cancel();
95
+ return;
96
+ }
97
+
98
+ if (e.key === "Enter" && current.onEnter === "submit") {
99
+ const target = e.target as HTMLElement | null;
100
+ if (target?.tagName === "TEXTAREA") {
101
+ return;
102
+ }
103
+
104
+ e.preventDefault();
105
+ dialogs.submit();
106
+ }
107
+ };
108
+
109
+ const handleMouseDown = (e: MouseEvent) => {
110
+ if (!current.dismissOnBackdrop) return;
111
+
112
+ const target = e.target as Node | null;
113
+ if (!target || !modalRef) return;
114
+
115
+ if (!modalRef.contains(target)) {
116
+ dialogs.cancel();
117
+ }
118
+ };
119
+
120
+ document.addEventListener("mousedown", handleMouseDown, true);
121
+ document.addEventListener("keydown", handleKeyDown, true);
122
+ onCleanup(() => {
123
+ document.removeEventListener("mousedown", handleMouseDown, true);
124
+ document.removeEventListener("keydown", handleKeyDown, true);
125
+ modalRef = undefined;
126
+ });
127
+ });
128
+
129
+ return (
130
+ <>
131
+ {dialogs.active() && (
132
+ <div class="eden-modal-overlay">
133
+ {(() => {
134
+ const dialog = dialogs.active();
135
+ if (!dialog) {
136
+ return null;
137
+ }
138
+
139
+ const renderContext = createRenderContext(dialog);
140
+
141
+ return (
142
+ <div
143
+ ref={modalRef}
144
+ class={`eden-modal ${sizeClass(dialog.size)}`}
145
+ role="dialog"
146
+ aria-modal="true"
147
+ >
148
+ <div class="eden-modal-header">
149
+ <h3 class="eden-modal-title">{dialog.title}</h3>
150
+ <button
151
+ type="button"
152
+ class="eden-modal-close"
153
+ onClick={() => dialogs.cancel()}
154
+ >
155
+ ×
156
+ </button>
157
+ </div>
158
+
159
+ <div class="eden-modal-body">
160
+ {dialog.message != null && <div>{dialog.message}</div>}
161
+ {dialog.render?.(renderContext)}
162
+ </div>
163
+
164
+ {dialog.footer && (
165
+ <div class="eden-modal-footer">
166
+ {dialog.footer(renderContext)}
167
+ </div>
168
+ )}
169
+ </div>
170
+ );
171
+ })()}
172
+ </div>
173
+ )}
174
+ </>
175
+ );
176
+ };
@@ -0,0 +1,482 @@
1
+ import { createSignal, For, type JSX } from "solid-js";
2
+ import { registerDialogRuntime } from "./runtimeRegistry.js";
3
+ import type { DialogRequest, DialogRuntimeController } from "./runtimeTypes.js";
4
+ import type {
5
+ AlertDialogOptions,
6
+ ConfirmDialogOptions,
7
+ DialogController,
8
+ DialogFormField,
9
+ DialogFormValues,
10
+ DialogTone,
11
+ FormDialogOptions,
12
+ PromptDialogOptions,
13
+ } from "./types.js";
14
+
15
+ type FormValueRecord = Record<string, string | boolean>;
16
+
17
+ const hasOwn = <K extends string>(value: unknown, key: K): boolean => {
18
+ return (
19
+ typeof value === "object" && value !== null && Object.hasOwn(value, key)
20
+ );
21
+ };
22
+
23
+ const confirmButtonClass = (tone: DialogTone) => {
24
+ return tone === "danger"
25
+ ? "eden-btn eden-btn-danger"
26
+ : "eden-btn eden-btn-primary";
27
+ };
28
+
29
+ const getDefaultFormFieldValue = (field: DialogFormField): string | boolean => {
30
+ if (field.kind === "checkbox") {
31
+ return field.initialValue ?? false;
32
+ }
33
+
34
+ return field.initialValue ?? "";
35
+ };
36
+
37
+ const createInitialFormValues = (fields: readonly DialogFormField[]) => {
38
+ const values: FormValueRecord = {};
39
+
40
+ for (const field of fields) {
41
+ values[field.key] = getDefaultFormFieldValue(field);
42
+ }
43
+
44
+ return values;
45
+ };
46
+
47
+ const isRequiredFieldFilled = (
48
+ field: DialogFormField,
49
+ value: string | boolean | undefined,
50
+ ): boolean => {
51
+ if (!field.required) return true;
52
+
53
+ if (field.kind === "checkbox") {
54
+ return value === true;
55
+ }
56
+
57
+ return typeof value === "string" && value.trim().length > 0;
58
+ };
59
+
60
+ const isFormSubmittable = (
61
+ fields: readonly DialogFormField[],
62
+ values: FormValueRecord,
63
+ ): boolean => {
64
+ return fields.every((field) =>
65
+ isRequiredFieldFilled(field, values[field.key]),
66
+ );
67
+ };
68
+
69
+ const getInitialFocusFieldKey = (
70
+ fields: readonly DialogFormField[],
71
+ ): string | null => {
72
+ const explicit = fields.find((field) => field.autofocus);
73
+ if (explicit) {
74
+ return explicit.key;
75
+ }
76
+
77
+ const firstInteractive = fields.find((field) => field.kind !== "checkbox");
78
+ return firstInteractive?.key ?? null;
79
+ };
80
+
81
+ /**
82
+ * Creates a dialogs controller instance for a renderer tree.
83
+ * Mount `<DialogHost dialogs={dialogs} />` once in that tree to render dialogs.
84
+ */
85
+ export const createDialogs = (): DialogController => {
86
+ const [active, setActive] = createSignal<DialogRequest | null>(null);
87
+ const queue: DialogRequest[] = [];
88
+ let requestId = 0;
89
+
90
+ const pump = () => {
91
+ if (active()) return;
92
+
93
+ const next = queue.shift();
94
+ if (!next) return;
95
+
96
+ setActive(next);
97
+ };
98
+
99
+ const enqueue = (request: DialogRequest) => {
100
+ queue.push(request);
101
+ pump();
102
+ };
103
+
104
+ const closeAndContinue = () => {
105
+ setActive(null);
106
+ queueMicrotask(pump);
107
+ };
108
+
109
+ const custom: DialogController["custom"] = (options) => {
110
+ return new Promise((resolve) => {
111
+ const [value, setValue] = createSignal(options.initialValue as unknown);
112
+ const [canSubmit, setCanSubmit] = createSignal(
113
+ options.initialCanSubmit ?? true,
114
+ );
115
+
116
+ const hasDefaultSubmitResult = hasOwn(options, "defaultSubmitResult");
117
+ const hasCancelResult = hasOwn(options, "cancelResult");
118
+
119
+ enqueue({
120
+ id: ++requestId,
121
+ title: options.title,
122
+ message: options.message,
123
+ size: options.size ?? "sm",
124
+ dismissOnBackdrop: options.dismissOnBackdrop ?? true,
125
+ dismissOnEscape: options.dismissOnEscape ?? true,
126
+ onEnter: options.onEnter ?? "submit",
127
+ selectInitialFocusText: options.selectInitialFocusText ?? false,
128
+ value,
129
+ setValue,
130
+ canSubmit,
131
+ setCanSubmit,
132
+ render: options.render as DialogRequest["render"],
133
+ footer: options.footer as DialogRequest["footer"],
134
+ hasDefaultSubmitResult,
135
+ defaultSubmitResult: hasDefaultSubmitResult
136
+ ? (options as { defaultSubmitResult: unknown }).defaultSubmitResult
137
+ : undefined,
138
+ hasCancelResult,
139
+ cancelResult: hasCancelResult
140
+ ? (options as { cancelResult: unknown }).cancelResult
141
+ : undefined,
142
+ onSubmitAttempt:
143
+ options.onSubmitAttempt as DialogRequest["onSubmitAttempt"],
144
+ resolve: resolve as (result: unknown) => void,
145
+ });
146
+ });
147
+ };
148
+
149
+ const submit: DialogRuntimeController["submit"] = async (...args) => {
150
+ const current = active();
151
+ if (!current || !current.canSubmit()) return;
152
+
153
+ const hasExplicitResult = args.length > 0;
154
+ const result = args[0];
155
+ let resolvedResult = hasExplicitResult
156
+ ? result
157
+ : current.hasDefaultSubmitResult
158
+ ? current.defaultSubmitResult
159
+ : current.value();
160
+
161
+ if (current.onSubmitAttempt) {
162
+ try {
163
+ const submitResult = await current.onSubmitAttempt(resolvedResult);
164
+ if (!submitResult.allowClose) {
165
+ return;
166
+ }
167
+
168
+ if (hasOwn(submitResult, "result")) {
169
+ resolvedResult = submitResult.result;
170
+ }
171
+ } catch (error) {
172
+ console.error("Dialog submit handler failed:", error);
173
+ return;
174
+ }
175
+ }
176
+
177
+ current.resolve(resolvedResult);
178
+ closeAndContinue();
179
+ };
180
+
181
+ const cancel: DialogController["cancel"] = () => {
182
+ const current = active();
183
+ if (!current) return;
184
+
185
+ const resolvedResult = current.hasCancelResult
186
+ ? current.cancelResult
187
+ : null;
188
+ current.resolve(resolvedResult);
189
+ closeAndContinue();
190
+ };
191
+
192
+ const alert = async (options: AlertDialogOptions): Promise<void> => {
193
+ await custom<void, void>({
194
+ title: options.title,
195
+ message: options.message,
196
+ size: options.size,
197
+ dismissOnBackdrop: options.dismissOnBackdrop,
198
+ dismissOnEscape: options.dismissOnEscape,
199
+ onEnter: options.onEnter,
200
+ initialValue: undefined,
201
+ cancelResult: undefined,
202
+ footer: (ctx) => (
203
+ <button
204
+ type="button"
205
+ ref={ctx.setPrimaryActionRef}
206
+ class="eden-btn eden-btn-primary"
207
+ onClick={() => ctx.submit()}
208
+ >
209
+ {options.okLabel ?? "OK"}
210
+ </button>
211
+ ),
212
+ });
213
+ };
214
+
215
+ const confirm = (options: ConfirmDialogOptions): Promise<boolean> => {
216
+ const tone = options.tone ?? "default";
217
+
218
+ return custom<void, boolean>({
219
+ title: options.title,
220
+ message: options.message,
221
+ size: options.size,
222
+ dismissOnBackdrop: options.dismissOnBackdrop,
223
+ dismissOnEscape: options.dismissOnEscape,
224
+ onEnter: options.onEnter,
225
+ initialValue: undefined,
226
+ defaultSubmitResult: true,
227
+ cancelResult: false,
228
+ footer: (ctx) => (
229
+ <>
230
+ <button type="button" class="eden-btn" onClick={() => ctx.cancel()}>
231
+ {options.cancelLabel ?? "Cancel"}
232
+ </button>
233
+ <button
234
+ type="button"
235
+ ref={ctx.setPrimaryActionRef}
236
+ class={confirmButtonClass(tone)}
237
+ onClick={() => ctx.submit(true)}
238
+ >
239
+ {options.confirmLabel ?? "OK"}
240
+ </button>
241
+ </>
242
+ ),
243
+ });
244
+ };
245
+
246
+ const prompt = (options: PromptDialogOptions): Promise<string | null> => {
247
+ const tone = options.tone ?? "default";
248
+ const promptInputId = `eden-dialog-prompt-${requestId + 1}`;
249
+
250
+ return custom<string, string | null>({
251
+ title: options.title,
252
+ message: options.message,
253
+ size: options.size,
254
+ dismissOnBackdrop: options.dismissOnBackdrop,
255
+ dismissOnEscape: options.dismissOnEscape,
256
+ onEnter: options.onEnter,
257
+ selectInitialFocusText: true,
258
+ initialValue: options.initialValue ?? "",
259
+ cancelResult: null,
260
+ render: (ctx) => (
261
+ <div class="eden-form-group">
262
+ {options.label && (
263
+ <label class="eden-form-label" for={promptInputId}>
264
+ {options.label}
265
+ </label>
266
+ )}
267
+ <input
268
+ id={promptInputId}
269
+ ref={ctx.setInitialFocusRef}
270
+ type="text"
271
+ class="eden-input"
272
+ placeholder={options.placeholder}
273
+ value={ctx.value()}
274
+ onInput={(e) => ctx.setValue(e.currentTarget.value)}
275
+ />
276
+ {options.hint && <p class="eden-form-help">{options.hint}</p>}
277
+ </div>
278
+ ),
279
+ footer: (ctx) => (
280
+ <>
281
+ <button type="button" class="eden-btn" onClick={() => ctx.cancel()}>
282
+ {options.cancelLabel ?? "Cancel"}
283
+ </button>
284
+ <button
285
+ type="button"
286
+ ref={ctx.setPrimaryActionRef}
287
+ class={confirmButtonClass(tone)}
288
+ onClick={() => ctx.submit()}
289
+ >
290
+ {options.confirmLabel ?? "OK"}
291
+ </button>
292
+ </>
293
+ ),
294
+ });
295
+ };
296
+
297
+ const form = <TFields extends readonly DialogFormField[]>(
298
+ options: FormDialogOptions<TFields>,
299
+ ): Promise<DialogFormValues<TFields> | null> => {
300
+ const tone = options.tone ?? "default";
301
+ const focusFieldKey = getInitialFocusFieldKey(options.fields);
302
+ const formIdPrefix = `eden-dialog-form-${requestId + 1}`;
303
+ const [submitError, setSubmitError] = createSignal<
304
+ JSX.Element | string | null
305
+ >(null);
306
+ const initialValues = createInitialFormValues(
307
+ options.fields,
308
+ ) as DialogFormValues<TFields>;
309
+
310
+ return custom<DialogFormValues<TFields>, DialogFormValues<TFields> | null>({
311
+ title: options.title,
312
+ message: options.message,
313
+ size: options.size,
314
+ dismissOnBackdrop: options.dismissOnBackdrop,
315
+ dismissOnEscape: options.dismissOnEscape,
316
+ onEnter: options.onEnter,
317
+ initialValue: initialValues,
318
+ initialCanSubmit: isFormSubmittable(
319
+ options.fields,
320
+ initialValues as FormValueRecord,
321
+ ),
322
+ cancelResult: null,
323
+ render: (ctx) => (
324
+ <div class="eden-flex-col eden-gap-md">
325
+ <For each={options.fields}>
326
+ {(field) => {
327
+ const fieldValue = () => {
328
+ const values = ctx.value() as FormValueRecord;
329
+ return values[field.key];
330
+ };
331
+
332
+ const setFieldValue = (nextValue: string | boolean) => {
333
+ const currentValues = ctx.value() as FormValueRecord;
334
+ const nextValues = {
335
+ ...currentValues,
336
+ [field.key]: nextValue,
337
+ } as FormValueRecord;
338
+
339
+ setSubmitError(null);
340
+ ctx.setValue(() => nextValues as DialogFormValues<TFields>);
341
+ ctx.setCanSubmit(isFormSubmittable(options.fields, nextValues));
342
+ };
343
+
344
+ const isFocusField =
345
+ focusFieldKey != null && focusFieldKey === field.key;
346
+ const fieldId = `${formIdPrefix}-${field.key}`;
347
+
348
+ if (field.kind === "checkbox") {
349
+ return (
350
+ <div class="eden-form-group">
351
+ <label class="eden-checkbox-option">
352
+ <input
353
+ ref={isFocusField ? ctx.setInitialFocusRef : undefined}
354
+ type="checkbox"
355
+ class="eden-checkbox"
356
+ checked={fieldValue() === true}
357
+ disabled={field.disabled}
358
+ onChange={(e) => setFieldValue(e.currentTarget.checked)}
359
+ />
360
+ <span class="eden-checkbox-option-label">
361
+ {field.label}
362
+ </span>
363
+ </label>
364
+ {field.hint && <p class="eden-form-help">{field.hint}</p>}
365
+ </div>
366
+ );
367
+ }
368
+
369
+ if (field.kind === "textarea") {
370
+ return (
371
+ <div class="eden-form-group">
372
+ <label class="eden-form-label" for={fieldId}>
373
+ {field.label}
374
+ </label>
375
+ <textarea
376
+ id={fieldId}
377
+ ref={isFocusField ? ctx.setInitialFocusRef : undefined}
378
+ class="eden-textarea"
379
+ placeholder={field.placeholder}
380
+ value={String(fieldValue() ?? "")}
381
+ disabled={field.disabled}
382
+ rows={3}
383
+ onInput={(e) => setFieldValue(e.currentTarget.value)}
384
+ />
385
+ {field.hint && <p class="eden-form-help">{field.hint}</p>}
386
+ </div>
387
+ );
388
+ }
389
+
390
+ return (
391
+ <div class="eden-form-group">
392
+ <label class="eden-form-label" for={fieldId}>
393
+ {field.label}
394
+ </label>
395
+ <input
396
+ id={fieldId}
397
+ ref={isFocusField ? ctx.setInitialFocusRef : undefined}
398
+ type={field.kind}
399
+ class="eden-input"
400
+ placeholder={field.placeholder}
401
+ value={String(fieldValue() ?? "")}
402
+ disabled={field.disabled}
403
+ onInput={(e) => setFieldValue(e.currentTarget.value)}
404
+ />
405
+ {field.hint && <p class="eden-form-help">{field.hint}</p>}
406
+ </div>
407
+ );
408
+ }}
409
+ </For>
410
+ {submitError() && (
411
+ <div
412
+ class="eden-text-xs"
413
+ style={{ color: "var(--eden-color-danger)" }}
414
+ >
415
+ {submitError()}
416
+ </div>
417
+ )}
418
+ </div>
419
+ ),
420
+ onSubmitAttempt: async (result) => {
421
+ const values = result as DialogFormValues<TFields>;
422
+
423
+ const validationError = options.validate?.(values) ?? null;
424
+ if (validationError) {
425
+ setSubmitError(validationError);
426
+ return { allowClose: false };
427
+ }
428
+
429
+ if (options.onSubmit) {
430
+ const submitResult = await options.onSubmit(values);
431
+ if (submitResult) {
432
+ setSubmitError(submitResult);
433
+ return { allowClose: false };
434
+ }
435
+ }
436
+
437
+ return {
438
+ allowClose: true,
439
+ result: values,
440
+ };
441
+ },
442
+ footer: (ctx) => (
443
+ <>
444
+ <button type="button" class="eden-btn" onClick={() => ctx.cancel()}>
445
+ {options.cancelLabel ?? "Cancel"}
446
+ </button>
447
+ <button
448
+ type="button"
449
+ ref={ctx.setPrimaryActionRef}
450
+ class={confirmButtonClass(tone)}
451
+ disabled={!ctx.canSubmit()}
452
+ onClick={() => ctx.submit()}
453
+ >
454
+ {options.confirmLabel ?? "OK"}
455
+ </button>
456
+ </>
457
+ ),
458
+ });
459
+ };
460
+
461
+ const controller: DialogRuntimeController = {
462
+ active,
463
+ submit,
464
+ cancel,
465
+ custom,
466
+ alert,
467
+ confirm,
468
+ prompt,
469
+ form,
470
+ };
471
+ registerDialogRuntime(controller, controller);
472
+
473
+ return controller;
474
+ };
475
+
476
+ export type {
477
+ CustomDialogOptions,
478
+ CustomDialogRenderContext,
479
+ DialogFormField,
480
+ DialogFormValues,
481
+ FormDialogOptions,
482
+ } from "./types.js";
@@ -0,0 +1,110 @@
1
+ import type { DialogFormCheckboxField, DialogFormTextField } from "./types.js";
2
+
3
+ interface BaseFieldOptions {
4
+ required?: boolean;
5
+ disabled?: boolean;
6
+ autofocus?: boolean;
7
+ hint?: string;
8
+ }
9
+
10
+ interface TextFieldOptions extends BaseFieldOptions {
11
+ placeholder?: string;
12
+ initialValue?: string;
13
+ }
14
+
15
+ interface CheckboxFieldOptions extends BaseFieldOptions {
16
+ initialValue?: boolean;
17
+ }
18
+
19
+ /** Creates a single-line text field config for `dialogs.form`. */
20
+ const text = <TKey extends string>(
21
+ key: TKey,
22
+ label: string,
23
+ options: TextFieldOptions = {},
24
+ ): DialogFormTextField<TKey> => ({
25
+ kind: "text",
26
+ key,
27
+ label,
28
+ placeholder: options.placeholder,
29
+ initialValue: options.initialValue,
30
+ required: options.required,
31
+ disabled: options.disabled,
32
+ autofocus: options.autofocus,
33
+ hint: options.hint,
34
+ });
35
+
36
+ /** Creates an email field config for `dialogs.form`. */
37
+ const email = <TKey extends string>(
38
+ key: TKey,
39
+ label: string,
40
+ options: TextFieldOptions = {},
41
+ ): DialogFormTextField<TKey> => ({
42
+ kind: "email",
43
+ key,
44
+ label,
45
+ placeholder: options.placeholder,
46
+ initialValue: options.initialValue,
47
+ required: options.required,
48
+ disabled: options.disabled,
49
+ autofocus: options.autofocus,
50
+ hint: options.hint,
51
+ });
52
+
53
+ /** Creates a password field config for `dialogs.form`. */
54
+ const password = <TKey extends string>(
55
+ key: TKey,
56
+ label: string,
57
+ options: TextFieldOptions = {},
58
+ ): DialogFormTextField<TKey> => ({
59
+ kind: "password",
60
+ key,
61
+ label,
62
+ placeholder: options.placeholder,
63
+ initialValue: options.initialValue,
64
+ required: options.required,
65
+ disabled: options.disabled,
66
+ autofocus: options.autofocus,
67
+ hint: options.hint,
68
+ });
69
+
70
+ /** Creates a multiline textarea field config for `dialogs.form`. */
71
+ const textarea = <TKey extends string>(
72
+ key: TKey,
73
+ label: string,
74
+ options: TextFieldOptions = {},
75
+ ): DialogFormTextField<TKey> => ({
76
+ kind: "textarea",
77
+ key,
78
+ label,
79
+ placeholder: options.placeholder,
80
+ initialValue: options.initialValue,
81
+ required: options.required,
82
+ disabled: options.disabled,
83
+ autofocus: options.autofocus,
84
+ hint: options.hint,
85
+ });
86
+
87
+ /** Creates a checkbox field config for `dialogs.form`. */
88
+ const checkbox = <TKey extends string>(
89
+ key: TKey,
90
+ label: string,
91
+ options: CheckboxFieldOptions = {},
92
+ ): DialogFormCheckboxField<TKey> => ({
93
+ kind: "checkbox",
94
+ key,
95
+ label,
96
+ initialValue: options.initialValue,
97
+ required: options.required,
98
+ disabled: options.disabled,
99
+ autofocus: options.autofocus,
100
+ hint: options.hint,
101
+ });
102
+
103
+ /** Declarative form field builders used with `dialogs.form({ fields: [...] })`. */
104
+ export const field = {
105
+ text,
106
+ email,
107
+ password,
108
+ textarea,
109
+ checkbox,
110
+ };
@@ -0,0 +1,4 @@
1
+ export * from "./types.js";
2
+ export * from "./fields.js";
3
+ export * from "./createDialogs.js";
4
+ export * from "./DialogHost.js";
@@ -0,0 +1,18 @@
1
+ import type { DialogRuntimeController } from "./runtimeTypes.js";
2
+ import type { DialogController } from "./types.js";
3
+
4
+ const runtimeByController = new WeakMap<
5
+ DialogController,
6
+ DialogRuntimeController
7
+ >();
8
+
9
+ export const registerDialogRuntime = (
10
+ controller: DialogController,
11
+ runtime: DialogRuntimeController,
12
+ ) => {
13
+ runtimeByController.set(controller, runtime);
14
+ };
15
+
16
+ export const getDialogRuntime = (controller: DialogController) => {
17
+ return runtimeByController.get(controller);
18
+ };
@@ -0,0 +1,60 @@
1
+ import type { Accessor, JSX, Setter } from "solid-js";
2
+ import type {
3
+ CustomDialogRenderContext,
4
+ DialogController,
5
+ DialogEnterBehavior,
6
+ DialogSize,
7
+ DialogSubmitResult,
8
+ } from "./types.js";
9
+
10
+ interface DialogRequestMeta {
11
+ id: number;
12
+ title: string;
13
+ message?: JSX.Element | string;
14
+ size: DialogSize;
15
+ }
16
+
17
+ interface DialogRequestBehavior {
18
+ dismissOnBackdrop: boolean;
19
+ dismissOnEscape: boolean;
20
+ onEnter: DialogEnterBehavior;
21
+ selectInitialFocusText: boolean;
22
+ }
23
+
24
+ interface DialogRequestState<TValue> {
25
+ value: Accessor<TValue>;
26
+ setValue: Setter<TValue>;
27
+ canSubmit: Accessor<boolean>;
28
+ setCanSubmit: Setter<boolean>;
29
+ }
30
+
31
+ interface DialogRequestRender<TValue, TResult> {
32
+ render?: (ctx: CustomDialogRenderContext<TValue, TResult>) => JSX.Element;
33
+ footer?: (ctx: CustomDialogRenderContext<TValue, TResult>) => JSX.Element;
34
+ onSubmitAttempt?: (
35
+ result: TResult,
36
+ ) => Promise<DialogSubmitResult<TResult>> | DialogSubmitResult<TResult>;
37
+ }
38
+
39
+ interface DialogRequestResolution<TResult> {
40
+ hasDefaultSubmitResult: boolean;
41
+ defaultSubmitResult?: TResult;
42
+ hasCancelResult: boolean;
43
+ cancelResult?: TResult;
44
+ resolve: (result: TResult) => void;
45
+ }
46
+
47
+ // Internal runtime request shape used by `createDialogs` and `DialogHost`.
48
+ export type DialogRequest<
49
+ TValue = unknown,
50
+ TResult = unknown,
51
+ > = DialogRequestMeta &
52
+ DialogRequestBehavior &
53
+ DialogRequestState<TValue> &
54
+ DialogRequestRender<TValue, TResult> &
55
+ DialogRequestResolution<TResult>;
56
+
57
+ export interface DialogRuntimeController extends DialogController {
58
+ active: Accessor<DialogRequest | null>;
59
+ submit: (result?: unknown) => Promise<void>;
60
+ }
@@ -0,0 +1,211 @@
1
+ import type { Accessor, JSX, Setter } from "solid-js";
2
+
3
+ /** Dialog width preset used by the built-in modal container. */
4
+ export type DialogSize = "sm" | "md" | "lg";
5
+
6
+ /** Visual tone for primary/confirm actions. */
7
+ export type DialogTone = "default" | "danger";
8
+
9
+ /** Behavior of the Enter key when a dialog is focused. */
10
+ export type DialogEnterBehavior = "submit" | "ignore";
11
+
12
+ /** Supported field kinds for declarative `dialogs.form`. */
13
+ export type DialogFormFieldKind =
14
+ | "text"
15
+ | "email"
16
+ | "password"
17
+ | "textarea"
18
+ | "checkbox";
19
+
20
+ interface DialogBaseOptions {
21
+ /** Header title shown in the dialog. */
22
+ title: string;
23
+ /** Optional message/content rendered above custom body content. */
24
+ message?: JSX.Element | string;
25
+ /** Optional width preset. Defaults to `"sm"`. */
26
+ size?: DialogSize;
27
+ /** Close when clicking the backdrop. Defaults to `true`. */
28
+ dismissOnBackdrop?: boolean;
29
+ /** Close on Escape key. Defaults to `true`. */
30
+ dismissOnEscape?: boolean;
31
+ /** Enter key behavior. Defaults to `"submit"`. */
32
+ onEnter?: DialogEnterBehavior;
33
+ /** Select text after initial focus is applied (inputs/textareas). */
34
+ selectInitialFocusText?: boolean;
35
+ }
36
+
37
+ /** Runtime context passed to `custom.render` and `custom.footer`. */
38
+ export interface CustomDialogRenderContext<TValue, TResult = TValue | null> {
39
+ /** Current dialog value signal accessor. */
40
+ value: Accessor<TValue>;
41
+ /** Value signal setter. */
42
+ setValue: Setter<TValue>;
43
+ /** Whether submit action should be enabled. */
44
+ canSubmit: Accessor<boolean>;
45
+ /** Enable/disable submit action. */
46
+ setCanSubmit: Setter<boolean>;
47
+ /** Resolve dialog as confirmed (optionally with custom result). */
48
+ submit: (result?: TResult) => void;
49
+ /** Resolve dialog as cancelled. */
50
+ cancel: () => void;
51
+ /** Assign primary action button ref for default focus fallback. */
52
+ setPrimaryActionRef: (el: HTMLButtonElement | undefined) => void;
53
+ /** Assign initial focus target for this dialog. */
54
+ setInitialFocusRef: (el: HTMLElement | undefined) => void;
55
+ }
56
+
57
+ /** Advanced low-level dialog options used by `dialogs.custom`. */
58
+ export interface CustomDialogOptions<TValue, TResult = TValue | null>
59
+ extends DialogBaseOptions {
60
+ /** Initial value backing this dialog instance. */
61
+ initialValue: TValue;
62
+ /** Initial submit availability. Defaults to `true`. */
63
+ initialCanSubmit?: boolean;
64
+ /** Custom body renderer. */
65
+ render?: (ctx: CustomDialogRenderContext<TValue, TResult>) => JSX.Element;
66
+ /** Custom footer renderer. */
67
+ footer?: (ctx: CustomDialogRenderContext<TValue, TResult>) => JSX.Element;
68
+ /** Default result used when `submit()` is called without an argument. */
69
+ defaultSubmitResult?: TResult;
70
+ /** Result returned when cancelled. Defaults to `null` if not set. */
71
+ cancelResult?: TResult;
72
+ /** Async submit gate to prevent close and optionally override result. */
73
+ onSubmitAttempt?: (
74
+ result: TResult,
75
+ ) => Promise<DialogSubmitResult<TResult>> | DialogSubmitResult<TResult>;
76
+ }
77
+
78
+ /** Options for `dialogs.alert`. */
79
+ export interface AlertDialogOptions extends DialogBaseOptions {
80
+ /** Label for the single confirmation button. */
81
+ okLabel?: string;
82
+ }
83
+
84
+ /** Options for `dialogs.confirm`. */
85
+ export interface ConfirmDialogOptions extends DialogBaseOptions {
86
+ /** Label for the confirm button. */
87
+ confirmLabel?: string;
88
+ /** Label for the cancel button. */
89
+ cancelLabel?: string;
90
+ /** Visual tone for the confirm button. */
91
+ tone?: DialogTone;
92
+ }
93
+
94
+ /** Options for `dialogs.prompt`. */
95
+ export interface PromptDialogOptions extends DialogBaseOptions {
96
+ /** Optional field label shown above the input. */
97
+ label?: string;
98
+ /** Input placeholder. */
99
+ placeholder?: string;
100
+ /** Optional helper text shown below the input. */
101
+ hint?: JSX.Element | string;
102
+ /** Initial input value. */
103
+ initialValue?: string;
104
+ /** Label for the confirm button. */
105
+ confirmLabel?: string;
106
+ /** Label for the cancel button. */
107
+ cancelLabel?: string;
108
+ /** Visual tone for the confirm button. */
109
+ tone?: DialogTone;
110
+ }
111
+
112
+ interface DialogFormFieldBase<TKey extends string = string> {
113
+ /** Field key used in returned values object. */
114
+ key: TKey;
115
+ kind: DialogFormFieldKind;
116
+ /** Visible field label. */
117
+ label: string;
118
+ /** Optional helper text shown below the field. */
119
+ hint?: JSX.Element | string;
120
+ /** Whether this field must be filled before submit. */
121
+ required?: boolean;
122
+ /** Whether this field is disabled. */
123
+ disabled?: boolean;
124
+ /** Prefer this field for initial focus. */
125
+ autofocus?: boolean;
126
+ }
127
+
128
+ /** Declarative text-like field configuration. */
129
+ export interface DialogFormTextField<TKey extends string = string>
130
+ extends DialogFormFieldBase<TKey> {
131
+ kind: "text" | "email" | "password" | "textarea";
132
+ /** Placeholder for text-like controls. */
133
+ placeholder?: string;
134
+ /** Initial string value. */
135
+ initialValue?: string;
136
+ }
137
+
138
+ /** Declarative checkbox field configuration. */
139
+ export interface DialogFormCheckboxField<TKey extends string = string>
140
+ extends DialogFormFieldBase<TKey> {
141
+ kind: "checkbox";
142
+ /** Initial checked state. */
143
+ initialValue?: boolean;
144
+ }
145
+
146
+ /** Union of all supported declarative form field configurations. */
147
+ export type DialogFormField<TKey extends string = string> =
148
+ | DialogFormTextField<TKey>
149
+ | DialogFormCheckboxField<TKey>;
150
+
151
+ /** Value type produced by a given form field declaration. */
152
+ export type DialogFormValue<TField extends DialogFormField = DialogFormField> =
153
+ TField extends DialogFormCheckboxField ? boolean : string;
154
+
155
+ /** Strongly-typed values object returned by `dialogs.form`. */
156
+ export type DialogFormValues<TFields extends readonly DialogFormField[]> = {
157
+ [TField in TFields[number] as TField["key"]]: DialogFormValue<TField>;
158
+ };
159
+
160
+ /** Options for `dialogs.form`. */
161
+ export interface FormDialogOptions<TFields extends readonly DialogFormField[]>
162
+ extends DialogBaseOptions {
163
+ /** Declarative list of fields rendered in order. */
164
+ fields: TFields;
165
+ /** Label for the confirm/submit button. */
166
+ confirmLabel?: string;
167
+ /** Label for the cancel button. */
168
+ cancelLabel?: string;
169
+ /** Visual tone for the confirm button. */
170
+ tone?: DialogTone;
171
+ /** Sync validation hook. Return text/JSX to block submit and show error. */
172
+ validate?: (values: DialogFormValues<TFields>) => JSX.Element | string | null;
173
+ /** Async submit hook. Return text/JSX to keep dialog open and show error. */
174
+ onSubmit?: (
175
+ values: DialogFormValues<TFields>,
176
+ ) =>
177
+ | Promise<JSX.Element | string | null | undefined>
178
+ | JSX.Element
179
+ | string
180
+ | null
181
+ | undefined;
182
+ }
183
+
184
+ /** Result contract for `custom.onSubmitAttempt`. */
185
+ export interface DialogSubmitResult<TResult = unknown> {
186
+ /** Whether the dialog should close after submit attempt. */
187
+ allowClose: boolean;
188
+ /** Optional result override returned when closing is allowed. */
189
+ result?: TResult;
190
+ }
191
+
192
+ /** Public dialogs controller returned by `createDialogs()`. */
193
+ export interface DialogController {
194
+ /** Closes the currently active dialog, if any. */
195
+ cancel: () => void;
196
+
197
+ /** Advanced low-level API for custom dialog layout/behavior. */
198
+ custom: <TValue, TResult = TValue | null>(
199
+ options: CustomDialogOptions<TValue, TResult>,
200
+ ) => Promise<TResult>;
201
+ /** Shows an informational dialog with a single action. */
202
+ alert: (options: AlertDialogOptions) => Promise<void>;
203
+ /** Shows a confirm/cancel dialog and resolves to user choice. */
204
+ confirm: (options: ConfirmDialogOptions) => Promise<boolean>;
205
+ /** Shows a single text-input dialog and resolves to value or `null`. */
206
+ prompt: (options: PromptDialogOptions) => Promise<string | null>;
207
+ /** Shows a declarative form dialog and resolves to values or `null`. */
208
+ form: <TFields extends readonly DialogFormField[]>(
209
+ options: FormDialogOptions<TFields>,
210
+ ) => Promise<DialogFormValues<TFields> | null>;
211
+ }
package/src/dialogs.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./dialogs/index.js";
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./dialogs.js";