@glasshome/ui 1.9.0 → 1.10.1

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.
Files changed (122) hide show
  1. package/README.md +2 -13
  2. package/SPEC.md +4 -4
  3. package/dist/lib/badge-tone.d.ts +0 -2
  4. package/dist/solid/badge.d.ts +1 -1
  5. package/dist/solid/card.d.ts +4 -2
  6. package/dist/solid/icon.d.ts +14 -0
  7. package/dist/solid/index.js +1645 -1632
  8. package/dist/solid/spinner.d.ts +1 -1
  9. package/package.json +9 -12
  10. package/scripts/check-pack.ts +32 -0
  11. package/src/index.ts +111 -0
  12. package/src/lib/badge-tone.ts +0 -4
  13. package/src/lib/carousel-classes.ts +2 -3
  14. package/src/solid/accordion.tsx +60 -0
  15. package/src/solid/alert-dialog.tsx +148 -0
  16. package/src/solid/alert.tsx +118 -0
  17. package/src/solid/area-picker.tsx +225 -0
  18. package/src/solid/aspect-ratio.tsx +21 -0
  19. package/src/solid/avatar.tsx +41 -0
  20. package/src/solid/badge.tsx +74 -0
  21. package/src/solid/bottom-sheet/arbitration.ts +40 -0
  22. package/src/solid/bottom-sheet/bottom-sheet.tsx +457 -0
  23. package/src/solid/bottom-sheet/constants.ts +8 -0
  24. package/src/solid/bottom-sheet/drag-controller.ts +221 -0
  25. package/src/solid/bottom-sheet/focus-trap.ts +56 -0
  26. package/src/solid/bottom-sheet/index.ts +14 -0
  27. package/src/solid/bottom-sheet/keyboard.ts +35 -0
  28. package/src/solid/bottom-sheet/scroll-lock.ts +64 -0
  29. package/src/solid/bottom-sheet/state-machine.ts +40 -0
  30. package/src/solid/bottom-sheet/velocity.ts +42 -0
  31. package/src/solid/breadcrumb.tsx +105 -0
  32. package/src/solid/button-group.tsx +66 -0
  33. package/src/solid/button.tsx +20 -0
  34. package/src/solid/card.tsx +101 -0
  35. package/src/solid/carousel.tsx +302 -0
  36. package/src/solid/charts.tsx +338 -0
  37. package/src/solid/checkbox.tsx +70 -0
  38. package/src/solid/collapsible.tsx +38 -0
  39. package/src/solid/color-slider.tsx +98 -0
  40. package/src/solid/color-wheel.tsx +77 -0
  41. package/src/solid/context-menu.tsx +109 -0
  42. package/src/solid/copy-button.tsx +46 -0
  43. package/src/solid/count-pill.tsx +24 -0
  44. package/src/solid/data-table.tsx +248 -0
  45. package/src/solid/dialog-parts.tsx +242 -0
  46. package/src/solid/dialog.tsx +121 -0
  47. package/src/solid/dock.tsx +186 -0
  48. package/src/solid/dropdown-menu.tsx +130 -0
  49. package/src/solid/empty.tsx +99 -0
  50. package/src/solid/entity-data.ts +78 -0
  51. package/src/solid/entity-selector.tsx +697 -0
  52. package/src/solid/field.tsx +253 -0
  53. package/src/solid/form.tsx +231 -0
  54. package/src/solid/hero-action.tsx +117 -0
  55. package/src/solid/hover-card.tsx +26 -0
  56. package/src/solid/icon-picker.tsx +432 -0
  57. package/src/solid/icon.tsx +20 -0
  58. package/src/solid/image-picker.tsx +380 -0
  59. package/src/solid/index.ts +417 -0
  60. package/src/solid/input-group.tsx +170 -0
  61. package/src/solid/input-otp.tsx +175 -0
  62. package/src/solid/input.tsx +12 -0
  63. package/src/solid/item.tsx +179 -0
  64. package/src/solid/kbd.tsx +30 -0
  65. package/src/solid/label.tsx +19 -0
  66. package/src/solid/list-reorder.ts +148 -0
  67. package/src/solid/logo.tsx +79 -0
  68. package/src/solid/media-copy.ts +37 -0
  69. package/src/solid/media-store.ts +110 -0
  70. package/src/solid/media-tile.tsx +100 -0
  71. package/src/solid/menu-parts.tsx +248 -0
  72. package/src/solid/number-field.tsx +72 -0
  73. package/src/solid/option-card.tsx +218 -0
  74. package/src/solid/ornament.tsx +53 -0
  75. package/src/solid/overlay.tsx +16 -0
  76. package/src/solid/page-header.tsx +102 -0
  77. package/src/solid/pagination.tsx +111 -0
  78. package/src/solid/password-input.tsx +69 -0
  79. package/src/solid/picker-row.tsx +102 -0
  80. package/src/solid/picker-search.tsx +78 -0
  81. package/src/solid/popover.tsx +103 -0
  82. package/src/solid/progress.tsx +31 -0
  83. package/src/solid/radio-group.tsx +60 -0
  84. package/src/solid/resizable.tsx +149 -0
  85. package/src/solid/responsive-dialog.tsx +180 -0
  86. package/src/solid/schema-form.tsx +830 -0
  87. package/src/solid/scope-indicator.tsx +13 -0
  88. package/src/solid/scroll-area.tsx +27 -0
  89. package/src/solid/section-card.tsx +358 -0
  90. package/src/solid/select.tsx +139 -0
  91. package/src/solid/separator.tsx +35 -0
  92. package/src/solid/settings-row.tsx +159 -0
  93. package/src/solid/sheet.tsx +157 -0
  94. package/src/solid/skeleton.tsx +15 -0
  95. package/src/solid/slider.tsx +148 -0
  96. package/src/solid/sliding-indicator.tsx +294 -0
  97. package/src/solid/sonner.tsx +219 -0
  98. package/src/solid/spinner.tsx +20 -0
  99. package/src/solid/step-indicator.tsx +30 -0
  100. package/src/solid/switch.tsx +62 -0
  101. package/src/solid/table.tsx +98 -0
  102. package/src/solid/tabs.tsx +86 -0
  103. package/src/solid/textarea.tsx +16 -0
  104. package/src/solid/toggle-group.tsx +102 -0
  105. package/src/solid/toggle.tsx +57 -0
  106. package/src/solid/tooltip.tsx +38 -0
  107. package/src/solid/widget-card.tsx +117 -0
  108. package/src/solid/widget-identity.tsx +135 -0
  109. package/src/solid/widget-trust-badge.tsx +37 -0
  110. package/src/tokens/hex.ts +50 -0
  111. package/src/tokens/index.ts +8 -0
  112. package/src/tokens/presets.ts +192 -0
  113. package/src/tokens/theme-colors.ts +147 -0
  114. package/dist/lib/carousel-init.d.ts +0 -9
  115. package/src/astro/Alert.astro +0 -63
  116. package/src/astro/Badge.astro +0 -18
  117. package/src/astro/Button.astro +0 -47
  118. package/src/astro/Card.astro +0 -48
  119. package/src/astro/Carousel.astro +0 -82
  120. package/src/astro/Logo.astro +0 -73
  121. package/src/astro/TierBadge.astro +0 -33
  122. package/src/lib/carousel-init.ts +0 -87
@@ -0,0 +1,830 @@
1
+ import type { JSONSchema7 } from "json-schema";
2
+ import { createMemo, createSignal, For, Index, Match, Show, Switch as SwitchFlow } from "solid-js";
3
+ import { FIELD_CHROME } from "../lib/input-classes.js";
4
+ import { SETTLE_MOTION } from "../lib/motion-classes.js";
5
+ import { cn } from "../lib/utils.js";
6
+ import { Alert } from "./alert.js";
7
+ import { AreaPicker } from "./area-picker.js";
8
+ import { Badge } from "./badge.js";
9
+ import { Button } from "./button.js";
10
+ import { Card } from "./card.js";
11
+ import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./collapsible.js";
12
+ import { EntitySelector } from "./entity-selector.js";
13
+ import { Field, FieldDescription, FieldLabel, FieldLegend, FieldSet } from "./field.js";
14
+ import { Icon } from "./icon.js";
15
+ import { IconPicker, type IconPickerProps } from "./icon-picker.js";
16
+ import { ImagePicker } from "./image-picker.js";
17
+ import { Input } from "./input.js";
18
+ import { createListReorder } from "./list-reorder.js";
19
+ import { useMediaStore } from "./media-store.js";
20
+ import { NumberField } from "./number-field.js";
21
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./select.js";
22
+ import { Switch } from "./switch.js";
23
+
24
+ export interface ExtendedJSONSchema extends JSONSchema7 {
25
+ /* Nested schemas carry the same extensions, so a whole tree types as one. */
26
+ properties?: { [key: string]: ExtendedJSONSchema | boolean };
27
+ items?: ExtendedJSONSchema | (ExtendedJSONSchema | boolean)[] | boolean;
28
+ /** Explicit control choice from the SDK's field.* helpers. */
29
+ formType?: string;
30
+ domain?: string;
31
+ singleSelect?: boolean;
32
+ deviceClass?: string;
33
+ /** formType "variants": the property that selects the active branch. */
34
+ discriminator?: string;
35
+ /** formType "variants": kind → display name for the discriminator Select. */
36
+ labels?: Record<string, string>;
37
+ /** formType "list": add-button caption. */
38
+ addLabel?: string;
39
+ /** formType "list": item field whose value captions the collapsed row. */
40
+ labelField?: string;
41
+ }
42
+
43
+ /**
44
+ * formType values with a dedicated renderer branch. Any other formType renders
45
+ * a read-only "needs a newer dashboard" notice instead of a broken control
46
+ * (widgets auto-update independently of the host, so an old host WILL meet
47
+ * schemas with formTypes it predates). Kept in lockstep with the SDK's field
48
+ * helpers by dash's formType parity test.
49
+ */
50
+ export const SCHEMA_FORM_FORM_TYPES = [
51
+ "icon-picker",
52
+ "image-picker",
53
+ "area-picker",
54
+ "list",
55
+ "variants",
56
+ ] as const;
57
+
58
+ const warnedLegacyAreaKeys = new Set<string>();
59
+
60
+ /**
61
+ * @deprecated Removed in the next major. Before the SDK had `field.area()`,
62
+ * an area picker was inferred from the property name alone, so a field had to
63
+ * be called `areaId` to get one and any other name silently rendered a text
64
+ * input. Declare `field.area()` instead — it works under any name.
65
+ */
66
+ function isLegacyAreaKey(key: string, prop: ExtendedJSONSchema): boolean {
67
+ const lower = key.toLowerCase();
68
+ if (prop.type !== "string" || (lower !== "areaid" && lower !== "area_id")) return false;
69
+ const isDev = typeof process !== "undefined" && process.env?.NODE_ENV !== "production";
70
+ if (isDev && !warnedLegacyAreaKeys.has(key)) {
71
+ warnedLegacyAreaKeys.add(key);
72
+ console.warn(
73
+ `[SchemaForm] "${key}" renders an area picker because of its name. That fallback is removed in the next major; declare it with field.area() instead. https://glasshome.app/docs/widget-sdk/config`,
74
+ );
75
+ }
76
+ return true;
77
+ }
78
+
79
+ function isKnownFormType(prop: ExtendedJSONSchema): boolean {
80
+ return (
81
+ prop.formType === undefined ||
82
+ (SCHEMA_FORM_FORM_TYPES as readonly string[]).includes(prop.formType)
83
+ );
84
+ }
85
+
86
+ function schemaOf(definition: unknown): ExtendedJSONSchema {
87
+ return typeof definition === "object" && definition !== null
88
+ ? (definition as ExtendedJSONSchema)
89
+ : {};
90
+ }
91
+
92
+ function itemsOf(prop: ExtendedJSONSchema): ExtendedJSONSchema {
93
+ return Array.isArray(prop.items) ? {} : schemaOf(prop.items);
94
+ }
95
+
96
+ function propertiesOf(prop: ExtendedJSONSchema): Array<[string, ExtendedJSONSchema]> {
97
+ return Object.entries(prop.properties ?? {}).map(([key, sub]) => [key, schemaOf(sub)]);
98
+ }
99
+
100
+ function isEntityArray(prop: ExtendedJSONSchema): boolean {
101
+ return prop.type === "array" && itemsOf(prop).type === "string" && prop.domain !== undefined;
102
+ }
103
+
104
+ function isStringArray(prop: ExtendedJSONSchema): boolean {
105
+ return prop.type === "array" && itemsOf(prop).type === "string";
106
+ }
107
+
108
+ function isObjectGroup(prop: ExtendedJSONSchema): boolean {
109
+ return prop.type === "object" && prop.properties !== undefined && prop.formType === undefined;
110
+ }
111
+
112
+ function recordOf(value: unknown): Record<string, unknown> {
113
+ return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : {};
114
+ }
115
+
116
+ /** Property defaults declared on the wire (`default`), plus `const` seeds
117
+ * (a variant branch's discriminator literal serializes as `const`). */
118
+ function propertyDefaults(branch: ExtendedJSONSchema): Record<string, unknown> {
119
+ const out: Record<string, unknown> = {};
120
+ for (const [key, sub] of propertiesOf(branch)) {
121
+ if (sub.const !== undefined) out[key] = structuredClone(sub.const);
122
+ else if (sub.default !== undefined) out[key] = structuredClone(sub.default);
123
+ }
124
+ return out;
125
+ }
126
+
127
+ /**
128
+ * New-item defaults from the wire schema: the serialized `default` when the
129
+ * SDK provided one (field.variants always does), else property defaults; for
130
+ * a variants item without a default, the first branch seeded by its
131
+ * discriminator const.
132
+ */
133
+ export function extractItemDefaults(schema: ExtendedJSONSchema): Record<string, unknown> {
134
+ if (schema.default !== undefined) return recordOf(structuredClone(schema.default));
135
+ const branches = variantBranches(schema);
136
+ const first = branches[0];
137
+ if (first) return propertyDefaults(first);
138
+ return propertyDefaults(schema);
139
+ }
140
+
141
+ function variantBranches(schema: ExtendedJSONSchema): ExtendedJSONSchema[] {
142
+ const raw = schema.oneOf ?? schema.anyOf ?? [];
143
+ return raw.map(schemaOf).filter((b) => b.properties !== undefined);
144
+ }
145
+
146
+ function branchKind(branch: ExtendedJSONSchema, discriminator: string): string {
147
+ const disc = schemaOf(branch.properties?.[discriminator]);
148
+ return typeof disc.const === "string" ? disc.const : "";
149
+ }
150
+
151
+ /**
152
+ * Switching kind keeps current values for keys the new branch also declares
153
+ * (matched by name) and drops the rest; missing keys take the branch defaults.
154
+ */
155
+ export function switchVariantValue(
156
+ branch: ExtendedJSONSchema,
157
+ discriminator: string,
158
+ kind: string,
159
+ current: Record<string, unknown>,
160
+ ): Record<string, unknown> {
161
+ const next = propertyDefaults(branch);
162
+ for (const [key] of propertiesOf(branch)) {
163
+ if (key === discriminator) continue;
164
+ if (key in current && current[key] !== undefined) next[key] = current[key];
165
+ }
166
+ next[discriminator] = kind;
167
+ return next;
168
+ }
169
+
170
+ interface SchemaFormProps {
171
+ schema: JSONSchema7;
172
+ data: Record<string, unknown>;
173
+ onChange: (data: Record<string, unknown>) => void;
174
+ errors?: string[];
175
+ /** Passed through to IconPicker for formType: "icon-picker" fields. */
176
+ searchIcons?: IconPickerProps["searchIcons"];
177
+ class?: string;
178
+ }
179
+
180
+ export function SchemaForm(props: SchemaFormProps) {
181
+ const properties = () => {
182
+ const schema = props.schema;
183
+ if (schema.type !== "object" || !schema.properties) return [];
184
+ return propertiesOf(schema as ExtendedJSONSchema);
185
+ };
186
+
187
+ // Controlled: props.data is the single source of truth, so parent-driven
188
+ // revert/reset/widget-switch reaches the visible form (audit finding #33).
189
+ const updateField = (key: string, value: unknown) => {
190
+ props.onChange({ ...props.data, [key]: value });
191
+ };
192
+
193
+ return (
194
+ <div class={cn("flex w-full min-w-0 flex-col gap-6", props.class)} data-slot="schema-form">
195
+ <For each={properties()}>
196
+ {([key, prop]) => (
197
+ <LabeledField
198
+ id={key}
199
+ name={key}
200
+ prop={prop}
201
+ value={props.data[key]}
202
+ onChange={(value) => updateField(key, value)}
203
+ searchIcons={props.searchIcons}
204
+ />
205
+ )}
206
+ </For>
207
+
208
+ <Show when={props.errors && props.errors.length > 0}>
209
+ <Alert tone="destructive" title="Validation errors">
210
+ <ul class="flex list-inside list-disc flex-col gap-1">
211
+ <For each={props.errors}>{(err) => <li>{err}</li>}</For>
212
+ </ul>
213
+ </Alert>
214
+ </Show>
215
+ </div>
216
+ );
217
+ }
218
+
219
+ interface FieldProps {
220
+ /** Unique control id (dot-path for nested fields). */
221
+ id: string;
222
+ /** Property key: label fallback and the legacy areaId heuristic. */
223
+ name: string;
224
+ prop: ExtendedJSONSchema;
225
+ value: unknown;
226
+ onChange: (value: unknown) => void;
227
+ searchIcons?: IconPickerProps["searchIcons"];
228
+ /** Id of the FieldLabel naming this control, for the kinds that render no
229
+ * element carrying `id`. */
230
+ labelledBy?: string;
231
+ /**
232
+ * This field is the root of a list item: the item Card is already its
233
+ * container and its header row already captions it, so a group renders its
234
+ * properties bare. Never forwarded down, so a group nested below the item
235
+ * root keeps the box that delimits it.
236
+ */
237
+ bare?: boolean;
238
+ }
239
+
240
+ /* The dispatch, as data: first match wins, and the same answer decides how the
241
+ * label reaches the control. Order is the contract (a legacy areaId key is a
242
+ * string like any other, so it has to be asked about before `enum`/`type`). */
243
+ type ControlKind =
244
+ | "unknown"
245
+ | "list"
246
+ | "variants"
247
+ | "entities"
248
+ | "icon"
249
+ | "image"
250
+ | "area"
251
+ | "enum"
252
+ | "boolean"
253
+ | "number"
254
+ | "strings"
255
+ | "group"
256
+ | "text";
257
+
258
+ const CONTROL_KINDS: ReadonlyArray<
259
+ readonly [ControlKind, (prop: ExtendedJSONSchema, name: string) => boolean]
260
+ > = [
261
+ ["unknown", (prop) => !isKnownFormType(prop)],
262
+ ["list", (prop) => prop.formType === "list"],
263
+ ["variants", (prop) => prop.formType === "variants"],
264
+ ["entities", (prop) => isEntityArray(prop)],
265
+ ["icon", (prop) => prop.formType === "icon-picker"],
266
+ ["image", (prop) => prop.formType === "image-picker"],
267
+ ["area", (prop, name) => prop.formType === "area-picker" || isLegacyAreaKey(name, prop)],
268
+ ["enum", (prop) => prop.enum !== undefined],
269
+ ["boolean", (prop) => prop.type === "boolean"],
270
+ ["number", (prop) => prop.type === "number" || prop.type === "integer"],
271
+ ["strings", (prop) => isStringArray(prop)],
272
+ ["group", (prop) => isObjectGroup(prop)],
273
+ ];
274
+
275
+ function controlKind(prop: ExtendedJSONSchema, name: string): ControlKind {
276
+ return CONTROL_KINDS.find(([, matches]) => matches(prop, name))?.[0] ?? "text";
277
+ }
278
+
279
+ /* `for` only where the control really renders an element carrying the field id;
280
+ * a picker trigger or a composite group is named by aria-labelledby instead, so
281
+ * no label points at nothing. `none`: nothing focusable to name. */
282
+ const LABEL_TARGET: Record<ControlKind, "for" | "labelledby" | "none"> = {
283
+ text: "for",
284
+ image: "for",
285
+ number: "for",
286
+ entities: "labelledby",
287
+ icon: "labelledby",
288
+ area: "labelledby",
289
+ enum: "labelledby",
290
+ boolean: "labelledby",
291
+ list: "labelledby",
292
+ variants: "labelledby",
293
+ strings: "labelledby",
294
+ unknown: "none",
295
+ group: "none",
296
+ };
297
+
298
+ /* A control's own hint sits below the control; a group carries its legend and
299
+ * explanation above its rows, so the group branch renders its own caption. */
300
+ function LabeledField(props: FieldProps) {
301
+ const kind = () => controlKind(props.prop, props.name);
302
+ const labelId = () => `${props.id}-label`;
303
+ const target = () => LABEL_TARGET[kind()];
304
+ return (
305
+ <Show when={kind() !== "group"} fallback={<FieldControl {...props} />}>
306
+ <Field>
307
+ <FieldLabel id={labelId()} for={target() === "for" ? props.id : undefined}>
308
+ {props.prop.title || props.name}
309
+ </FieldLabel>
310
+ <FieldControl {...props} labelledBy={target() === "labelledby" ? labelId() : undefined} />
311
+ <Show when={props.prop.description}>
312
+ {(description) => <FieldDescription>{description()}</FieldDescription>}
313
+ </Show>
314
+ </Field>
315
+ </Show>
316
+ );
317
+ }
318
+
319
+ /** The one recursive dispatch: every nesting level renders through here. */
320
+ function FieldControl(props: FieldProps) {
321
+ const current = () => props.value ?? props.prop.default;
322
+ const kind = () => controlKind(props.prop, props.name);
323
+ return (
324
+ <SwitchFlow
325
+ fallback={
326
+ <Input
327
+ id={props.id}
328
+ type="text"
329
+ value={String(current() ?? "")}
330
+ onInput={(e) => props.onChange(e.currentTarget.value)}
331
+ />
332
+ }
333
+ >
334
+ <Match when={kind() === "unknown"}>
335
+ <Alert tone="info" data-slot="schema-form-unknown">
336
+ This setting needs a newer dashboard version to be edited here.
337
+ </Alert>
338
+ </Match>
339
+ <Match when={kind() === "list"}>
340
+ <ListControl {...props} />
341
+ </Match>
342
+ <Match when={kind() === "variants"}>
343
+ <VariantsControl {...props} />
344
+ </Match>
345
+ <Match when={kind() === "entities"}>
346
+ <EntitySelector
347
+ aria-labelledby={props.labelledBy}
348
+ entityIds={(current() as string[]) ?? []}
349
+ onEntityIdsChange={(ids) => props.onChange(ids)}
350
+ domain={props.prop.domain ?? ""}
351
+ deviceClass={props.prop.deviceClass}
352
+ multiple={props.prop.singleSelect !== true}
353
+ />
354
+ </Match>
355
+ <Match when={kind() === "icon"}>
356
+ <IconPicker
357
+ aria-labelledby={props.labelledBy}
358
+ value={String(current() ?? "")}
359
+ onChange={(val) => props.onChange(val)}
360
+ searchIcons={props.searchIcons}
361
+ />
362
+ </Match>
363
+ <Match when={kind() === "image"}>
364
+ <ImagePicker
365
+ id={props.id}
366
+ value={String(current() ?? "")}
367
+ onChange={(val) => props.onChange(val)}
368
+ />
369
+ </Match>
370
+ <Match when={kind() === "area"}>
371
+ <AreaPicker
372
+ aria-labelledby={props.labelledBy}
373
+ value={String(current() ?? "")}
374
+ onChange={(val) => props.onChange(val)}
375
+ />
376
+ </Match>
377
+ <Match when={kind() === "enum"}>
378
+ <Select
379
+ value={String(current() ?? "")}
380
+ onChange={(val) => {
381
+ if (val != null) props.onChange(val);
382
+ }}
383
+ options={(props.prop.enum ?? []).map(String)}
384
+ itemComponent={(itemProps) => (
385
+ <SelectItem item={itemProps.item}>{String(itemProps.item.rawValue)}</SelectItem>
386
+ )}
387
+ >
388
+ <SelectTrigger class="w-full" aria-labelledby={props.labelledBy}>
389
+ <SelectValue<string>>{(state) => state.selectedOption()}</SelectValue>
390
+ </SelectTrigger>
391
+ <SelectContent />
392
+ </Select>
393
+ </Match>
394
+ <Match when={kind() === "boolean"}>
395
+ <div class="flex items-center gap-3">
396
+ <Switch
397
+ aria-labelledby={props.labelledBy}
398
+ checked={Boolean(current() ?? false)}
399
+ onChange={(checked) => props.onChange(checked)}
400
+ />
401
+ <span class="text-sm">{current() ? "Enabled" : "Disabled"}</span>
402
+ </div>
403
+ </Match>
404
+ <Match when={kind() === "number"}>
405
+ <NumberField
406
+ id={props.id}
407
+ value={Number(current() ?? 0)}
408
+ min={props.prop.minimum}
409
+ max={props.prop.maximum}
410
+ step={props.prop.type === "integer" ? 1 : "any"}
411
+ onInput={(e) => props.onChange(Number(e.currentTarget.value))}
412
+ />
413
+ </Match>
414
+ <Match when={kind() === "strings"}>
415
+ <StringListField
416
+ labelledBy={props.labelledBy}
417
+ value={(current() as string[]) ?? []}
418
+ onChange={(val) => props.onChange(val)}
419
+ />
420
+ </Match>
421
+ <Match when={kind() === "group"}>
422
+ <FieldSet
423
+ class={cn(props.bare !== true && "rounded-lg border border-border p-3")}
424
+ data-slot="schema-form-object"
425
+ >
426
+ <Show when={props.bare !== true}>
427
+ <FieldLegend variant="label">{props.prop.title || props.name}</FieldLegend>
428
+ </Show>
429
+ <Show when={props.prop.description}>
430
+ {(description) => <FieldDescription>{description()}</FieldDescription>}
431
+ </Show>
432
+ <For each={propertiesOf(props.prop)}>
433
+ {([subKey, subProp]) => (
434
+ <LabeledField
435
+ id={`${props.id}.${subKey}`}
436
+ name={subKey}
437
+ prop={subProp}
438
+ value={recordOf(current())[subKey]}
439
+ onChange={(value) => props.onChange({ ...recordOf(current()), [subKey]: value })}
440
+ searchIcons={props.searchIcons}
441
+ />
442
+ )}
443
+ </For>
444
+ </FieldSet>
445
+ </Match>
446
+ </SwitchFlow>
447
+ );
448
+ }
449
+
450
+ /* The drop slot the drag preview opens is the list's own gap, so both faces of
451
+ * it come from here. */
452
+ const LIST_GAP = { class: "gap-2", px: 8 } as const;
453
+
454
+ function ListControl(props: FieldProps) {
455
+ const itemSchema = () => itemsOf(props.prop);
456
+ const mediaStore = useMediaStore();
457
+ const [brokenThumbs, setBrokenThumbs] = createSignal<ReadonlySet<string>>(new Set());
458
+
459
+ // One image field is unambiguously the row's picture. Two would need the
460
+ // author to say which, so both zero and two keep the plain text row.
461
+ const imageKey = createMemo(() => {
462
+ const image = propertiesOf(itemSchema()).filter(([, sub]) => sub.formType === "image-picker");
463
+ return image.length === 1 ? image[0]?.[0] : undefined;
464
+ });
465
+
466
+ const thumbUrl = (item: unknown) => {
467
+ const key = imageKey();
468
+ const store = mediaStore;
469
+ if (key === undefined || !store) return undefined;
470
+ const id = recordOf(item)[key];
471
+ if (typeof id !== "string" || id === "") return undefined;
472
+ // A 32px row chip: the thumb variant, never the original.
473
+ return store.url(id, "thumb");
474
+ };
475
+
476
+ const liveThumbUrl = (item: unknown) => {
477
+ const url = thumbUrl(item);
478
+ return url !== undefined && !brokenThumbs().has(url) ? url : undefined;
479
+ };
480
+ const items = () => {
481
+ const value = props.value ?? props.prop.default;
482
+ return Array.isArray(value) ? (value as unknown[]) : [];
483
+ };
484
+ const minItems = () => props.prop.minItems ?? 0;
485
+ const atMax = () => props.prop.maxItems !== undefined && items().length >= props.prop.maxItems;
486
+ const [openIndex, setOpenIndex] = createSignal(-1);
487
+
488
+ const kindLabel = (item: unknown) => {
489
+ const schema = itemSchema();
490
+ if (schema.formType !== "variants" || schema.discriminator === undefined) return undefined;
491
+ const kind = recordOf(item)[schema.discriminator];
492
+ if (typeof kind !== "string") return undefined;
493
+ return schema.labels?.[kind] ?? kind;
494
+ };
495
+
496
+ // The kind badge carries the variant label, so the caption never repeats it:
497
+ // labelField value, else "Item N".
498
+ const caption = (item: unknown, index: number) => {
499
+ const record = recordOf(item);
500
+ const labelField = props.prop.labelField;
501
+ if (labelField !== undefined) {
502
+ const value = record[labelField];
503
+ if (typeof value === "string" && value.trim() !== "") return value;
504
+ if (typeof value === "number") return String(value);
505
+ }
506
+ return `Item ${index + 1}`;
507
+ };
508
+
509
+ const replaceAt = (index: number, value: unknown) => {
510
+ props.onChange(items().map((item, i) => (i === index ? value : item)));
511
+ };
512
+ const removeAt = (index: number) => {
513
+ props.onChange(items().filter((_, i) => i !== index));
514
+ if (openIndex() === index) setOpenIndex(-1);
515
+ else if (openIndex() > index) setOpenIndex(openIndex() - 1);
516
+ };
517
+ const reorder = (from: number, to: number) => {
518
+ if (to === from || to < 0 || to >= items().length) return;
519
+ const next = [...items()];
520
+ const [moved] = next.splice(from, 1);
521
+ next.splice(to, 0, moved);
522
+ props.onChange(next);
523
+ const open = openIndex();
524
+ if (open === from) setOpenIndex(to);
525
+ else if (open !== -1) {
526
+ if (from < open && to >= open) setOpenIndex(open - 1);
527
+ else if (from > open && to <= open) setOpenIndex(open + 1);
528
+ }
529
+ };
530
+
531
+ const listDrag = createListReorder({
532
+ count: () => items().length,
533
+ gapPx: LIST_GAP.px,
534
+ onReorder: reorder,
535
+ onDragStart: (index) => {
536
+ if (openIndex() === index) setOpenIndex(-1);
537
+ },
538
+ });
539
+ const add = () => {
540
+ const next = [...items(), extractItemDefaults(itemSchema())];
541
+ props.onChange(next);
542
+ setOpenIndex(next.length - 1);
543
+ };
544
+
545
+ return (
546
+ <fieldset
547
+ aria-labelledby={props.labelledBy}
548
+ class={cn("flex w-full min-w-0 flex-col", LIST_GAP.class)}
549
+ data-slot="schema-form-list"
550
+ >
551
+ <Index each={items()}>
552
+ {(item, index) => (
553
+ <Card
554
+ ref={(el: HTMLElement) => listDrag.setRowEl(index, el)}
555
+ class={cn(
556
+ "w-full min-w-0 overflow-hidden transition-transform duration-(--duration-state)",
557
+ listDrag.draggingIndex() === index && "relative shadow-lg",
558
+ )}
559
+ style={listDrag.rowStyle(index)}
560
+ data-slot="schema-form-list-item"
561
+ >
562
+ <Collapsible
563
+ open={openIndex() === index}
564
+ onOpenChange={(open) => {
565
+ if (listDrag.isToggleSuppressed()) return;
566
+ setOpenIndex(open ? index : -1);
567
+ }}
568
+ >
569
+ <div
570
+ data-slot="schema-form-list-row"
571
+ class={cn(
572
+ "relative flex min-h-11 select-none items-center gap-1.5 py-1 pr-1.5 pl-2",
573
+ "transition-colors duration-(--duration-micro) hover:bg-muted/40",
574
+ )}
575
+ onPointerDown={(e: PointerEvent) => {
576
+ const btn = (e.target as HTMLElement).closest("button");
577
+ if (btn && btn.dataset.slot !== "collapsible-trigger") return;
578
+ listDrag.startDrag(index, e, false);
579
+ }}
580
+ >
581
+ {/* Invisible layer over the whole bar: clicking anywhere toggles;
582
+ the action buttons sit above it and win their own clicks. */}
583
+ <CollapsibleTrigger
584
+ class="absolute inset-0 rounded-[inherit] py-0 outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50"
585
+ aria-label={caption(item(), index)}
586
+ />
587
+ <Icon
588
+ icon="lucide:chevron-right"
589
+ width={16}
590
+ height={16}
591
+ class={cn(
592
+ "pointer-events-none relative shrink-0 text-muted-foreground transition-transform duration-(--duration-state)",
593
+ openIndex() === index && "rotate-90",
594
+ )}
595
+ aria-hidden="true"
596
+ />
597
+ <Show when={imageKey() !== undefined && mediaStore !== undefined}>
598
+ <span
599
+ class={cn(
600
+ FIELD_CHROME,
601
+ "pointer-events-none relative flex size-8 shrink-0 items-center justify-center overflow-hidden rounded-md text-muted-foreground",
602
+ )}
603
+ data-slot="schema-form-list-item-thumb"
604
+ >
605
+ <Show
606
+ when={liveThumbUrl(item())}
607
+ fallback={
608
+ <Icon
609
+ icon={
610
+ thumbUrl(item()) === undefined ? "lucide:image" : "lucide:image-off"
611
+ }
612
+ width={16}
613
+ height={16}
614
+ aria-hidden="true"
615
+ />
616
+ }
617
+ >
618
+ {(url) => (
619
+ <img
620
+ src={url()}
621
+ alt=""
622
+ decoding="async"
623
+ class="absolute inset-0 h-full w-full object-cover"
624
+ onError={() => setBrokenThumbs((broken) => new Set(broken).add(url()))}
625
+ />
626
+ )}
627
+ </Show>
628
+ </span>
629
+ </Show>
630
+ <span class="pointer-events-none relative min-w-0 flex-1 truncate text-left text-sm">
631
+ {caption(item(), index)}
632
+ </span>
633
+ <Show when={kindLabel(item())}>
634
+ {(label) => (
635
+ <Badge class="pointer-events-none relative shrink-0">{label()}</Badge>
636
+ )}
637
+ </Show>
638
+ <Button
639
+ variant="ghost"
640
+ size="icon"
641
+ class="relative cursor-grab touch-none active:cursor-grabbing"
642
+ aria-label={`Reorder ${caption(item(), index)}`}
643
+ onPointerDown={(e: PointerEvent) => listDrag.startDrag(index, e, true)}
644
+ onKeyDown={(e: KeyboardEvent) => {
645
+ if (e.key === "ArrowUp") {
646
+ e.preventDefault();
647
+ reorder(index, index - 1);
648
+ } else if (e.key === "ArrowDown") {
649
+ e.preventDefault();
650
+ reorder(index, index + 1);
651
+ }
652
+ }}
653
+ >
654
+ <Icon icon="lucide:grip-vertical" width={16} height={16} aria-hidden="true" />
655
+ </Button>
656
+ <Button
657
+ variant="ghost"
658
+ size="icon"
659
+ class="relative"
660
+ aria-label={`Remove ${caption(item(), index)}`}
661
+ disabled={items().length <= minItems()}
662
+ onClick={() => removeAt(index)}
663
+ >
664
+ <Icon icon="lucide:x" width={16} height={16} aria-hidden="true" />
665
+ </Button>
666
+ </div>
667
+ <CollapsibleContent>
668
+ <div class="border-border border-t p-3">
669
+ <LabeledField
670
+ id={`${props.id}.${index}`}
671
+ name={props.name}
672
+ prop={itemSchema()}
673
+ value={item()}
674
+ onChange={(value) => replaceAt(index, value)}
675
+ searchIcons={props.searchIcons}
676
+ bare
677
+ />
678
+ </div>
679
+ </CollapsibleContent>
680
+ </Collapsible>
681
+ </Card>
682
+ )}
683
+ </Index>
684
+ <Show when={items().length < minItems()}>
685
+ <p class="text-muted-foreground text-sm">
686
+ Add at least {minItems()} {minItems() === 1 ? "item" : "items"}.
687
+ </p>
688
+ </Show>
689
+ <Button
690
+ variant="outline"
691
+ class="w-full"
692
+ disabled={atMax()}
693
+ onClick={add}
694
+ data-slot="schema-form-list-add"
695
+ >
696
+ <Icon icon="lucide:plus" width={16} height={16} aria-hidden="true" />
697
+ {props.prop.addLabel ?? "Add item"}
698
+ </Button>
699
+ </fieldset>
700
+ );
701
+ }
702
+
703
+ function VariantsControl(props: FieldProps) {
704
+ const branches = () => variantBranches(props.prop);
705
+ const discriminator = () => props.prop.discriminator ?? "";
706
+ const kinds = () => branches().map((b) => branchKind(b, discriminator()));
707
+ const value = () => recordOf(props.value ?? props.prop.default);
708
+ // Memos with default === equality: typing in a field changes value() but not
709
+ // the kind string, so the branch tuples keep their identity and the field
710
+ // subtree is NOT remounted (a remount would drop focus on every keystroke).
711
+ const currentKind = createMemo(() => {
712
+ const kind = value()[discriminator()];
713
+ if (typeof kind === "string" && kinds().includes(kind)) return kind;
714
+ return kinds()[0] ?? "";
715
+ });
716
+ const currentBranch = createMemo(() =>
717
+ branches().find((b) => branchKind(b, discriminator()) === currentKind()),
718
+ );
719
+ const labelFor = (kind: string) => props.prop.labels?.[kind] ?? kind;
720
+
721
+ const switchKind = (kind: string) => {
722
+ if (kind === currentKind()) return;
723
+ const branch = branches().find((b) => branchKind(b, discriminator()) === kind);
724
+ if (!branch) return;
725
+ props.onChange(switchVariantValue(branch, discriminator(), kind, value()));
726
+ };
727
+
728
+ const branchFields = createMemo(() => {
729
+ const branch = currentBranch();
730
+ if (!branch) return [];
731
+ return propertiesOf(branch).filter(([key]) => key !== discriminator());
732
+ });
733
+
734
+ return (
735
+ <fieldset
736
+ aria-labelledby={props.labelledBy}
737
+ class="flex w-full min-w-0 flex-col gap-3"
738
+ data-slot="schema-form-variants"
739
+ >
740
+ <Select
741
+ value={currentKind()}
742
+ onChange={(val) => {
743
+ if (val != null) switchKind(val);
744
+ }}
745
+ options={kinds()}
746
+ itemComponent={(itemProps) => (
747
+ <SelectItem item={itemProps.item}>{labelFor(String(itemProps.item.rawValue))}</SelectItem>
748
+ )}
749
+ >
750
+ <SelectTrigger class="w-full" aria-label={props.prop.title}>
751
+ <SelectValue<string>>{(state) => labelFor(state.selectedOption())}</SelectValue>
752
+ </SelectTrigger>
753
+ <SelectContent />
754
+ </Select>
755
+ <Show when={currentKind()} keyed>
756
+ {(_kind) => (
757
+ <div class={cn(SETTLE_MOTION, "flex flex-col gap-3")}>
758
+ <For each={branchFields()}>
759
+ {([subKey, subProp]) => (
760
+ <LabeledField
761
+ id={`${props.id}.${subKey}`}
762
+ name={subKey}
763
+ prop={subProp}
764
+ value={value()[subKey]}
765
+ onChange={(fieldValue) => props.onChange({ ...value(), [subKey]: fieldValue })}
766
+ searchIcons={props.searchIcons}
767
+ />
768
+ )}
769
+ </For>
770
+ </div>
771
+ )}
772
+ </Show>
773
+ </fieldset>
774
+ );
775
+ }
776
+
777
+ function StringListField(props: {
778
+ value: string[];
779
+ onChange: (value: string[]) => void;
780
+ labelledBy?: string;
781
+ }) {
782
+ const [input, setInput] = createSignal("");
783
+
784
+ const addItem = (item: string) => {
785
+ const trimmed = item.trim();
786
+ if (!trimmed || props.value.includes(trimmed)) return;
787
+ props.onChange([...props.value, trimmed]);
788
+ setInput("");
789
+ };
790
+
791
+ return (
792
+ <fieldset
793
+ aria-labelledby={props.labelledBy}
794
+ class="flex min-w-0 flex-col gap-2"
795
+ data-slot="schema-form-string-list"
796
+ >
797
+ <Show when={props.value.length > 0}>
798
+ <div class="flex flex-wrap gap-1.5">
799
+ <For each={props.value}>
800
+ {(item) => (
801
+ <Badge>
802
+ {item}
803
+ <button
804
+ type="button"
805
+ aria-label={`Remove ${item}`}
806
+ onClick={() => props.onChange(props.value.filter((v) => v !== item))}
807
+ class="cursor-pointer rounded-sm hover:text-destructive"
808
+ >
809
+ <Icon icon="lucide:x" width={12} height={12} aria-hidden="true" />
810
+ </button>
811
+ </Badge>
812
+ )}
813
+ </For>
814
+ </div>
815
+ </Show>
816
+ <Input
817
+ type="text"
818
+ placeholder="Type and press Enter to add"
819
+ value={input()}
820
+ onInput={(e) => setInput(e.currentTarget.value)}
821
+ onKeyDown={(e) => {
822
+ if (e.key === "Enter") {
823
+ e.preventDefault();
824
+ addItem(input());
825
+ }
826
+ }}
827
+ />
828
+ </fieldset>
829
+ );
830
+ }