@gemboss/ui 0.63.0 → 0.65.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.
@@ -0,0 +1,453 @@
1
+ "use client";
2
+ // ONE CONTROL PER KIND OF SETTING, FOR EVERY APP (08/11/2026; Chris: "các control phải có bộ control và kiểu có sự tái sử dụng dùng chung
3
+ // shared component… đừng mỗi cho mỗi kiểu"). The schema-driven form every editor's settings are drawn with: `FieldControl` draws one field
4
+ // by its kind, `FieldRows` a group's fields with the label on one side for the run, `FieldRenderer` a schema as a flat run of titled groups
5
+ // (a selected thing's panel draws it in the settings frame instead: field-frame.tsx). Moved from the admin (components/shell/FieldRenderer.tsx)
6
+ // with the markup, the class names and the commit rules it had there, so the admin's editors draw and behave exactly as before.
7
+ //
8
+ // THE KIT'S KINDS (field-spec.ts) are drawn here, on the kit's parts: text, textarea and number boxes (a draft, committed on blur or Enter),
9
+ // a range, a select, chips (a list where they do not fit the row), On / Off, a colour (with the host's chips: ColorChoicesContext), an
10
+ // image and a list of rows. AN APP'S KINDS are its own (`kinds`, by prop or FieldKindsProvider): each with its rules (the control it is
11
+ // drawn with, for the label's side and a list's order) and its drawing, which gets the field's resolved id, its label as drawn and
12
+ // `base()` (the kit's own control for that kind, for an app that draws a kit kind its way only sometimes). A kind no one draws is a visible
13
+ // "no control" line, never a text box that seems to work. A choice's `glyph` is drawn as the app's picture by that name (`glyphs`).
14
+ import "../editor.css"; // its own stylesheet travels with it: a surface that never renders a form never loads it
15
+ import { createContext, useContext, useState, type ChangeEvent, type CSSProperties, type FocusEventHandler, type KeyboardEvent, type ReactNode } from "react";
16
+ import { ColorChoicesContext } from "./color-choices";
17
+ import { ChipButton, ColorControl, ImageControl, RangeControl, Seg, UnitField } from "./controls";
18
+ import {
19
+ chipsFitBeside, firstSideFirst, isKitFieldKind, kindIn, knobValue, labelize,
20
+ type AnyFieldSpec, type AppFieldSpec, type FieldKindRules, type FieldKindRuleSet, type FieldSchema, type FieldSpec,
21
+ } from "./field-spec";
22
+ import { labelSide, type FieldControlKind } from "./label-side";
23
+ import { useOnNewValue } from "./new-value";
24
+ import { Field, InspectorGroup } from "./panel";
25
+
26
+ // ── An app's kinds ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────
27
+
28
+ /** What an app's drawing of a kind gets: FieldControl's props, the control's id, the label as words and as drawn, and the kit's own
29
+ * control for the field (`base`: null for a kind the kit does not draw). */
30
+ export type FieldKindProps<F extends AppFieldSpec = AppFieldSpec> = Omit<FieldControlProps, "field" | "kinds" | "glyphs"> & {
31
+ field: F;
32
+ /** The control's id: `inputId`, else `fr-<field id>`. */
33
+ id: string;
34
+ /** The field's label as words: its `label`, else its id labelized. */
35
+ label: string;
36
+ /** The label as drawn: none when `labelHidden`, with `mark` after it. */
37
+ named: ReactNode;
38
+ /** The label for a screen reader where it is not drawn (`labelHidden`). */
39
+ ariaLabel?: string;
40
+ /** The kit's own control for this field; null for a kind the kit does not draw. */
41
+ base: () => ReactNode;
42
+ };
43
+
44
+ /** A kind an app draws: its rules (field-spec.ts) and its drawing, rendered as a component (it may hold state). */
45
+ export interface FieldKind<F extends AppFieldSpec = AppFieldSpec> extends FieldKindRules<F> {
46
+ render(props: FieldKindProps<F>): ReactNode;
47
+ }
48
+ /** An app's kinds, by kind. One for a kit kind takes its place. */
49
+ export type FieldKinds = Readonly<Record<string, FieldKind | undefined>>;
50
+ /** The picture an app draws a choice's `glyph` with, by name (drawn when the chips are, not before). Nothing for a name it does not draw:
51
+ * the choice's words are drawn instead. */
52
+ export type FieldGlyphs = (name: string) => ReactNode | undefined;
53
+
54
+ const FieldKindsContext = createContext<{ kinds?: FieldKinds; glyphs?: FieldGlyphs }>({});
55
+ /** The kinds and glyphs a form draws with: its own props, else the nearest FieldKindsProvider's. */
56
+ export function useFieldKinds(kinds?: FieldKinds, glyphs?: FieldGlyphs): { kinds?: FieldKinds; glyphs?: FieldGlyphs } {
57
+ const set = useContext(FieldKindsContext);
58
+ return { kinds: kinds ?? set.kinds, glyphs: glyphs ?? set.glyphs };
59
+ }
60
+ /** An app's kinds and glyphs for every form under it. A form's own `kinds` / `glyphs` props take their place. */
61
+ export function FieldKindsProvider({ kinds, glyphs, children }: { kinds?: FieldKinds; glyphs?: FieldGlyphs; children?: ReactNode }) {
62
+ return <FieldKindsContext.Provider value={{ kinds, glyphs }}>{children}</FieldKindsContext.Provider>;
63
+ }
64
+
65
+ // ── The label's side ───────────────────────────────────────────────────────────────────────────────────────────────────────────────
66
+
67
+ /**
68
+ * The control a field is drawn with, by the names of the label-side table (LABEL_SIDE): chips that do not fit the row's control column are
69
+ * a list (chipsFitBeside). A kind an app registered says its own (`rules`, one for a kit kind first); a kind no one draws is its "no
70
+ * control" line, across the field like a long text.
71
+ */
72
+ export function controlOf(field: AnyFieldSpec, value?: unknown, rules?: FieldKindRuleSet): FieldControlKind {
73
+ const rule = kindIn(rules, field.kind);
74
+ if (rule) return typeof rule.control === "function" ? rule.control(field, value) : rule.control;
75
+ if (!isKitFieldKind(field.kind)) return "textarea";
76
+ const f = field as FieldSpec;
77
+ switch (f.kind) {
78
+ case "toggle": return "toggle";
79
+ case "select": return "select";
80
+ case "segmented": return chipsFitBeside(f) ? "chips" : "select";
81
+ case "color": return "color";
82
+ case "range": return "range";
83
+ case "number": return "number";
84
+ case "text": return "text";
85
+ case "textarea": return "textarea";
86
+ case "image": return "image";
87
+ case "repeater": return "list";
88
+ }
89
+ }
90
+
91
+ /** Whether a field's label sits BESIDE its control (a `.gemboss-ei-fld--row`), as FieldControl draws it: one decision for the drawing and
92
+ * for a list's order (firstSideFirst). */
93
+ export function labelBeside(field: AnyFieldSpec, value?: unknown, rules?: FieldKindRuleSet): boolean {
94
+ return labelSide(controlOf(field, value, rules)) === "beside";
95
+ }
96
+
97
+ // ── FieldControl ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────
98
+
99
+ export type FieldControlProps = {
100
+ field: AnyFieldSpec; value: unknown; onChange: (v: unknown) => void; disabled?: boolean;
101
+ /** No label drawn: the control is named by it for a screen reader (its `aria-label`) where its place already says what it is (a list's
102
+ * row titled with it, a results page's period beside its heading, a search box). Honoured by text, textarea, number, select, toggle
103
+ * and segmented; the other kinds draw their label. With no label there is no ?, so a hint is drawn in sight under the control. */
104
+ labelHidden?: boolean;
105
+ /** The value was refused (an id no record has): `aria-invalid` on the text box, its border the error's. Its words are the host's, a line
106
+ * the box points at (`describedBy`). Honoured by text and number. */
107
+ invalid?: boolean;
108
+ /** The control's id, when the host mounts this field more than once (a hidden canvas layer of the same panel: one id each). Else
109
+ * `fr-<field id>`. */
110
+ inputId?: string;
111
+ /** Drawn after the label (a field whose save did not land), and the id of the line that says why, for the control's description.
112
+ * Honoured by text, textarea, number, select, toggle, segmented and a plain colour (and by an app's kinds as they choose). */
113
+ mark?: ReactNode; describedBy?: string;
114
+ /** A control right after the label, beside it (not in it): a dot on a value set for the screen being edited (Control UI C30). */
115
+ labelMark?: ReactNode;
116
+ /** A colour's typed text as it is typed (`onDraft`), for a host that claims each key. Off by default: a host that previews each draft
117
+ * would paint a half-typed colour (`#ff0` on the way to `#ff0000`). */
118
+ colorDrafts?: boolean;
119
+ /** The shop an app's kinds read (the admin's link picker searches its products and collections). The kit's kinds do not. */
120
+ shopId?: string;
121
+ /** Open a media library for an image field. When absent, images are paste-URL + clear only. */
122
+ onPickImage?: (id: string, current: string) => void;
123
+ /** Each step of a value not yet committed (a key typed in a text or number box), for a host that shows it at once. Every other control
124
+ * commits each change through `onChange` already. */
125
+ onDraft?: (v: unknown) => void;
126
+ /** A host's refusal before a numeric control normalizes its raw draft on blur; no wrapper is added. */
127
+ onBlurCapture?: FocusEventHandler<HTMLDivElement>;
128
+ /** The app's kinds (FieldKindsProvider by default). */
129
+ kinds?: FieldKinds;
130
+ /** The app's glyphs (FieldKindsProvider by default). */
131
+ glyphs?: FieldGlyphs;
132
+ };
133
+
134
+ type Drawn = FieldControlProps & { id: string; lbl: string; named: ReactNode; ariaLabel?: string };
135
+
136
+ /**
137
+ * ONE control: the field's kind drawn with its label on its control's side. An app's kind is its drawing; a kit kind the kit's own; any
138
+ * other kind a visible "no control" line.
139
+ */
140
+ export function FieldControl(props: FieldControlProps) {
141
+ const { kinds, glyphs } = useFieldKinds(props.kinds, props.glyphs);
142
+ const { field, inputId, labelHidden = false, mark } = props;
143
+ const lbl = field.label ?? labelize(field.id);
144
+ const id = inputId ?? `fr-${field.id}`;
145
+ const named: ReactNode = labelHidden ? undefined : mark ? <>{lbl}{mark}</> : lbl;
146
+ const ariaLabel = labelHidden ? lbl : undefined;
147
+ const drawn: Drawn = { ...props, kinds, glyphs, id, lbl, named, ariaLabel };
148
+ const own = kindIn(kinds, field.kind);
149
+ if (own) {
150
+ const Render = own.render;
151
+ const { kinds: _kinds, glyphs: _glyphs, ...rest } = props;
152
+ return <Render {...rest} id={id} label={lbl} named={named} ariaLabel={ariaLabel} base={() => (isKitFieldKind(field.kind) ? kitControl(drawn) : null)} />;
153
+ }
154
+ return kitControl(drawn);
155
+ }
156
+
157
+ function kitControl(p: Drawn): ReactNode {
158
+ const { value, onChange, disabled, onPickImage, onDraft, onBlurCapture, inputId, mark, labelMark, describedBy, shopId, colorDrafts = false, labelHidden = false, invalid = false, kinds, glyphs, id, lbl, named, ariaLabel } = p;
159
+ if (!isKitFieldKind(p.field.kind)) return <UnknownKind field={p.field} named={named} />;
160
+ const field = p.field as FieldSpec;
161
+ switch (field.kind) {
162
+ case "toggle": {
163
+ const on = value === true || value === "true";
164
+ return (
165
+ // The seam's `info` for a checkbox is `hint`. It fills the control column like every segmented row (control standard §13b: one
166
+ // width rule).
167
+ <Field label={named} className="togrow" hint={field.hint} control="toggle" mark={labelMark}>
168
+ <Seg<"on" | "off"> label={lbl} value={on ? "on" : "off"} disabled={disabled} onChange={(v) => onChange(v === "on")}
169
+ options={[{ value: "on", label: field.onLabel ?? "On" }, { value: "off", label: field.offLabel ?? "Off" }]} />
170
+ </Field>
171
+ );
172
+ }
173
+ case "select": {
174
+ // A stored value the list does not offer (a rating of 4.8 an agent or a clone wrote, a value an older seam had) is shown as itself.
175
+ // Else the browser shows the first option, and picking it wrote nothing, as it already looked picked.
176
+ const cur = String(value ?? "");
177
+ const stray = (typeof value === "string" || typeof value === "number") && cur !== "" && !field.options.some((o) => o.value === cur);
178
+ return (
179
+ <Field label={named} htmlFor={id} hint={field.hint} control="select" mark={labelMark}>
180
+ <select id={id} className="gemboss-field gemboss-ei-inp" value={cur} disabled={disabled} aria-describedby={describedBy} aria-label={ariaLabel}
181
+ onChange={(e) => { const v = e.target.value; onChange(field.numeric && v !== "" && Number.isFinite(Number(v)) ? Number(v) : v); }}>
182
+ {stray ? <option value={cur}>{cur}</option> : null}
183
+ {/* Nothing stored: said, not the first option shown as if chosen. Picking an option then writes it. A clearable list keeps it
184
+ as a choice. */}
185
+ {(cur === "" || field.clearable) && !field.options.some((o) => o.value === "") ? <option value="" disabled={!field.clearable}>Not set</option> : null}
186
+ {field.options.map((o) => <option key={o.value} value={o.value}>{o.label ?? labelize(o.value)}</option>)}
187
+ </select>
188
+ </Field>
189
+ );
190
+ }
191
+ case "segmented": {
192
+ // A glyph the app draws is a picture; one it does not is the choice's words, and words must fit the row like any (chipsFitBeside).
193
+ const pictures = field.options.map((o) => (o.glyph ? glyphs?.(o.glyph) ?? null : null));
194
+ if (!chipsFitBeside({ options: field.options.map((o, i) => (pictures[i] == null ? { ...o, glyph: undefined } : o)) })) {
195
+ // An option reads as its full name in a list (a sample's "AA · UPPERCASE", a glyph's "Left"): a list has no picture to carry it.
196
+ // A stored value the chips would have shown as itself (any value, as text) is the list's own stray option.
197
+ const list: FieldSpec = { kind: "select", id: field.id, label: field.label, hint: field.hint,
198
+ options: field.options.map(({ glyph: _glyph, name, ...o }) => ({ ...o, label: name ?? o.label })) };
199
+ return <FieldControl field={list} value={typeof value === "boolean" ? String(value) : value} onChange={onChange} disabled={disabled} inputId={inputId}
200
+ mark={mark} labelMark={labelMark} describedBy={describedBy} shopId={shopId} labelHidden={labelHidden} kinds={kinds} glyphs={glyphs} />;
201
+ }
202
+ // As the list it replaces reads it: a stored 3 is the option "3". And the button already pressed changes nothing, as a list never
203
+ // fires for the option already shown.
204
+ const cur = value === undefined || value === null || value === "" ? undefined : String(value);
205
+ // A stored value the chips do not offer lights none of them, so it is said under them, as the list shows one as itself.
206
+ const stray = cur !== undefined && !field.options.some((o) => o.value === cur);
207
+ // A choice that is "nothing set" (a shadow's None, valued ""): lit while nothing is stored, and pressing it then writes nothing.
208
+ const shown = cur ?? (field.options.some((o) => o.value === "") ? "" : undefined);
209
+ return (
210
+ // Here the chips fit the row's control column (3/5 of the field, chipsFitBeside): more, or longer labels, are a list.
211
+ <Field label={named} hint={field.hint} control="chips" mark={labelMark}>
212
+ <Seg label={lbl} value={shown} disabled={disabled} onChange={(v) => { if (v !== shown) onChange(v); else if (field.clearable) onChange(""); }}
213
+ options={field.options.map((o, i) => (o.glyph
214
+ ? { value: o.value, label: pictures[i] ?? o.label ?? labelize(o.value), name: o.label ?? labelize(o.value) }
215
+ : { value: o.value, label: o.label ?? labelize(o.value), ...(o.name ? { name: o.name } : {}) }))} />
216
+ {stray ? <p className="gemboss-ei-hint" data-stray-value={cur}>Set to “{labelize(cur)}”, which is not one of these.</p> : null}
217
+ </Field>
218
+ );
219
+ }
220
+ case "color":
221
+ return <ColorField id={id} label={lbl} value={typeof value === "string" ? value : ""} disabled={disabled} hint={field.hint} placeholder={field.placeholder} onCommit={onChange}
222
+ onDraft={colorDrafts ? onDraft : undefined} mark={mark} labelMark={labelMark} describedBy={describedBy} />;
223
+ case "image":
224
+ return <ImageField id={id} label={lbl} value={typeof value === "string" ? value : ""} disabled={disabled}
225
+ onCommit={onChange} onPickImage={onPickImage ? (cur) => onPickImage(field.id, cur) : undefined} />;
226
+ case "range":
227
+ return <RangeField id={id} label={lbl} field={field} value={value} disabled={disabled} onCommit={onChange} onBlurCapture={onBlurCapture} labelMark={labelMark} />;
228
+ case "repeater":
229
+ return <RepeaterField label={lbl} field={field} value={Array.isArray(value) ? (value as Array<Record<string, unknown>>) : []} disabled={disabled} onChange={onChange} />;
230
+ case "textarea":
231
+ case "number":
232
+ case "text":
233
+ return <TextField id={id} label={named} field={field} value={value} disabled={disabled} onCommit={onChange} onDraft={onDraft} onBlurCapture={onBlurCapture} describedBy={describedBy} labelMark={labelMark} ariaLabel={ariaLabel} invalid={invalid} />;
234
+ default:
235
+ // A kit kind with no drawing here yet: said in sight, as any kind no one draws.
236
+ return <UnknownKind field={p.field} named={named} />;
237
+ }
238
+ }
239
+
240
+ /** A kind no one draws here (an app's kind not registered in this form): said in sight, so a setting never goes missing in silence. */
241
+ function UnknownKind({ field, named }: { field: AnyFieldSpec; named: ReactNode }) {
242
+ return (
243
+ <Field label={named} control="textarea">
244
+ <p className="gemboss-ei-hint" role="note" data-unknown-kind={field.kind}>No control draws “{field.kind}” settings here.</p>
245
+ </Field>
246
+ );
247
+ }
248
+
249
+ function RepeaterField({ label, field, value, disabled, onChange }: {
250
+ label: string;
251
+ field: Extract<FieldSpec, { kind: "repeater" }>;
252
+ value: Array<Record<string, unknown>>;
253
+ disabled?: boolean;
254
+ onChange: (v: unknown) => void;
255
+ }) {
256
+ const update = (i: number, key: string, v: string) => onChange(value.map((r, ri) => (ri === i ? { ...r, [key]: v } : r)));
257
+ const add = () => onChange([...value, Object.fromEntries(field.item.map((f) => [f.key, ""]))]);
258
+ const remove = (i: number) => onChange(value.filter((_, ri) => ri !== i));
259
+ const rowStyle: CSSProperties = { display: "flex", gap: 6, alignItems: "flex-start", marginBottom: 6 };
260
+ const fieldsStyle: CSSProperties = { display: "grid", gap: 4, flex: 1 };
261
+ return (
262
+ <Field label={label} hint={field.hint} control="list">
263
+ {value.map((row, i) => (
264
+ <div style={rowStyle} key={i}>
265
+ <div style={fieldsStyle}>
266
+ {field.item.map((it) => (
267
+ it.long
268
+ ? <textarea key={it.key} className="gemboss-field gemboss-ei-inp" rows={2} placeholder={it.label ?? labelize(it.key)} disabled={disabled}
269
+ value={String(row[it.key] ?? "")} onChange={(e) => update(i, it.key, e.target.value)} />
270
+ : <input key={it.key} className="gemboss-field gemboss-ei-inp" placeholder={it.label ?? labelize(it.key)} disabled={disabled}
271
+ value={String(row[it.key] ?? "")} onChange={(e) => update(i, it.key, e.target.value)} />
272
+ ))}
273
+ </div>
274
+ <button type="button" className="gemboss-control gemboss-control--icon gemboss-ei-inp"
275
+ disabled={disabled} aria-label="Remove row" onClick={() => remove(i)}>×</button>
276
+ </div>
277
+ ))}
278
+ <button type="button" className="gemboss-control gemboss-ei-inp" disabled={disabled} onClick={add}>+ {field.addLabel ?? "Add"}</button>
279
+ </Field>
280
+ );
281
+ }
282
+
283
+ /** Text / number / textarea: draft locally, commit on blur or Enter (never per keystroke, so a live preview isn't hammered while typing).
284
+ * Numbers persist as numbers, else "" (reverts to default). */
285
+ function TextField({ id, label, field, value, disabled, onCommit, onDraft, onBlurCapture, describedBy, labelMark, ariaLabel, invalid = false }: {
286
+ id: string; label: ReactNode; field: Extract<FieldSpec, { kind: "text" | "number" | "textarea" }>; ariaLabel?: string; invalid?: boolean;
287
+ value: unknown; disabled?: boolean; onCommit: (v: unknown) => void; onDraft?: (v: unknown) => void;
288
+ onBlurCapture?: FocusEventHandler<HTMLDivElement>; describedBy?: string; labelMark?: ReactNode;
289
+ }) {
290
+ const norm = (v: unknown) => (v === undefined || v === null ? "" : String(v));
291
+ const [draft, setDraft] = useState(norm(value));
292
+ // A value from outside (Take latest, an Undo, the chat's write) replaces the draft while this renders, not in an effect a render later.
293
+ useOnNewValue(() => setDraft(norm(value)), [value]);
294
+ const isNum = field.kind === "number";
295
+ // Bounds a setting declares (a 10..90 % scroll depth) are shown AND held: a value outside them is clamped on commit, so what the panel
296
+ // keeps is what the storefront uses.
297
+ const lo = isNum ? field.min : undefined;
298
+ const hi = isNum ? field.max : undefined;
299
+ // An unset bound is no bound: with `hi ?? n` the typed value was its own ceiling, so under a floor alone (min 1) a 0 stayed 0.
300
+ const clamp = (n: number) => Math.min(hi ?? Infinity, Math.max(lo ?? -Infinity, n));
301
+ const commit = () => {
302
+ const next = isNum ? (draft !== "" && Number.isFinite(Number(draft)) ? clamp(Number(draft)) : "") : draft;
303
+ // A clamped number can equal the stored value, so the host correctly skips that write.
304
+ // Normalize the local draft too: without a new prop value, its effect cannot replace an invalid draft.
305
+ if (isNum) setDraft(norm(next));
306
+ onCommit(next);
307
+ };
308
+ // Each key typed, as the value it would commit: a number only once it reads as one (clamped as the commit clamps it).
309
+ const typed = (raw: string) => {
310
+ setDraft(raw);
311
+ if (!onDraft) return;
312
+ if (!isNum) { onDraft(raw); return; }
313
+ if (raw.trim() !== "" && Number.isFinite(Number(raw))) onDraft(clamp(Number(raw)));
314
+ };
315
+ // A lone bound says itself too: the commit raises a 0 to a floor of 1, and that needs its reason on screen as much as a pair does.
316
+ const boundUnit = isNum && field.suffix ? ` ${field.suffix}` : "";
317
+ const bounds = !isNum ? "" : lo !== undefined && hi !== undefined ? `Between ${lo} and ${hi}${boundUnit}.` : lo !== undefined ? `At least ${lo}${boundUnit}.` : hi !== undefined ? `At most ${hi}${boundUnit}.` : "";
318
+ // A length the box holds to is counted where it can be seen, for the same reason: the box stops taking keys at it.
319
+ const maxLength = !isNum && "maxLength" in field ? field.maxLength : undefined;
320
+ const count = maxLength !== undefined ? `${draft.length}/${maxLength}` : "";
321
+ return (
322
+ // The limits stay in sight under the box (not behind the ?): the commit clamps to them, and a 200 that turns into 90 needs its reason on
323
+ // screen. The setting's own help is behind the ?.
324
+ <Field label={label} htmlFor={id} hint={"hint" in field ? field.hint : undefined} control={controlOf(field)} onBlurCapture={onBlurCapture} mark={labelMark}>
325
+ {field.kind === "textarea" ? (
326
+ <textarea id={id} className={`gemboss-field gemboss-ei-inp${field.code ? " gemboss-mono" : ""}`} rows={field.rows ?? 2} placeholder={field.placeholder}
327
+ value={draft} disabled={disabled} maxLength={maxLength} spellCheck={field.code ? false : undefined}
328
+ aria-describedby={describedBy} aria-label={ariaLabel} onChange={(e) => typed(e.target.value)} onBlur={commit} />
329
+ ) : (() => {
330
+ const unit = "suffix" in field && field.suffix ? field.suffix : "";
331
+ const prefix = field.kind === "text" ? field.prefix : undefined;
332
+ const on = {
333
+ onChange: (e: ChangeEvent<HTMLInputElement>) => typed(e.target.value), onBlur: commit, "aria-describedby": describedBy, "aria-label": ariaLabel,
334
+ "aria-invalid": invalid || undefined,
335
+ // Enter commits by leaving the box; a search commits as it is typed and keeps the focus.
336
+ onKeyDown: (e: KeyboardEvent<HTMLInputElement>) => { if (e.key === "Enter" && !(field.kind === "text" && field.inputType === "search")) { e.preventDefault(); (e.target as HTMLInputElement).blur(); } },
337
+ };
338
+ const inputMode = isNum ? ("numeric" as const) : undefined;
339
+ const placeholder = field.kind === "text" || field.kind === "number" ? field.placeholder : undefined;
340
+ // The unit INSIDE its box (UnitField, Polaris TextField's `suffix`): beside it, the box ended short of every other control's right
341
+ // edge (control standard §13b).
342
+ return unit || prefix
343
+ ? <UnitField className="gemboss-ei-inp" unit={unit} prefix={prefix} id={id} inputMode={inputMode} placeholder={placeholder} value={draft} maxLength={maxLength} disabled={disabled} {...on} />
344
+ : <input id={id} className="gemboss-field gemboss-ei-inp" type={field.kind === "text" ? field.inputType : undefined} inputMode={inputMode} placeholder={placeholder} value={draft} maxLength={maxLength} disabled={disabled} {...on} />;
345
+ })()}
346
+ {bounds || count ? <p className="gemboss-ei-hint">{bounds || count}</p> : null}
347
+ </Field>
348
+ );
349
+ }
350
+
351
+ function RangeField({ id, label, field, value, disabled, onCommit, onBlurCapture, labelMark }: {
352
+ id: string; label: string; field: Extract<FieldSpec, { kind: "range" }>;
353
+ value: unknown; disabled?: boolean; onCommit: (v: unknown) => void;
354
+ onBlurCapture?: FocusEventHandler<HTMLDivElement>; labelMark?: ReactNode;
355
+ }) {
356
+ const n = typeof value === "number" ? value : Number(value);
357
+ const cur = Number.isFinite(n) ? n : field.min;
358
+ return (
359
+ <Field label={label} htmlFor={id} labelValue={<>{cur}{field.suffix ?? ""}</>} control="range" onBlurCapture={onBlurCapture} mark={labelMark}>
360
+ <RangeControl id={id} min={field.min} max={field.max} step={field.step} value={cur} disabled={disabled} onChange={onCommit} />
361
+ </Field>
362
+ );
363
+ }
364
+
365
+ function ColorField({ id, label, value, disabled, hint, placeholder, onCommit, onDraft, mark, describedBy, labelMark }: {
366
+ id: string; label: string; value: string; disabled?: boolean; hint?: string; placeholder?: string; onCommit: (v: unknown) => void;
367
+ onDraft?: (v: string) => void; mark?: ReactNode; describedBy?: string; labelMark?: ReactNode;
368
+ }) {
369
+ // ColorControl asks `swatchState` whether the swatch can show the value (a Shopify `color_scheme` setting holds an id like "scheme-1").
370
+ // The host's colours as chips (ColorChoicesContext: the admin's theme colours and the store's recent ones). Only a colour the seller
371
+ // changed to is remembered: leaving the box commits what it already held, which is no choice.
372
+ const offered = useContext(ColorChoicesContext);
373
+ return (
374
+ <Field label={mark ? <>{label}{mark}</> : label} htmlFor={id} hint={hint} control="color" mark={labelMark}>
375
+ <ColorControl id={id} label={label} value={value} disabled={disabled} placeholder={placeholder} describedBy={describedBy} onDraft={onDraft} choices={offered?.choices}
376
+ onChange={(v) => { onCommit(v); if (v !== value) offered?.remember(v); }} />
377
+ </Field>
378
+ );
379
+ }
380
+
381
+ function ImageField({ id, label, value, disabled, onCommit, onPickImage }: {
382
+ id: string; label: string; value: string; disabled?: boolean;
383
+ onCommit: (v: unknown) => void; onPickImage?: (current: string) => void;
384
+ }) {
385
+ return (
386
+ <Field label={label} htmlFor={id} control="image">
387
+ <ImageControl id={id} value={value} disabled={disabled} onChange={onCommit}
388
+ actions={onPickImage ? <ChipButton disabled={disabled} onClick={() => onPickImage(value)}>Library</ChipButton> : null} />
389
+ </Field>
390
+ );
391
+ }
392
+
393
+ // ── FieldRows · FieldRenderer ──────────────────────────────────────────────────────────────────────────────────────────────────────
394
+
395
+ /** What every schema form takes: the fields' values, the writes, and the fields that are off on their own. */
396
+ export type FieldRowsProps = {
397
+ values: Record<string, unknown>;
398
+ onChange: (id: string, value: unknown) => void;
399
+ disabled?: boolean;
400
+ /** Fields that are off on their own (a colour the store's brand HQ locks), and the id of the line saying why, which each of them points
401
+ * at (aria-describedby). */
402
+ off?: ReadonlySet<string>;
403
+ offWhy?: string;
404
+ /** Open a media library for an image field. When absent, images are paste-URL + clear only. */
405
+ onPickImage?: (id: string, current: string) => void;
406
+ /** Each value typed in a text or number box before it is committed (a host that marks the knob as being edited). */
407
+ onDraft?: (id: string, value: unknown) => void;
408
+ /** The controls' ids, `<idPrefix><field id>`, for a host whose form is mounted more than once. Else `fr-<field id>`. */
409
+ idPrefix?: string;
410
+ /** The app's kinds and glyphs (FieldKindsProvider by default). */
411
+ kinds?: FieldKinds;
412
+ glyphs?: FieldGlyphs;
413
+ };
414
+
415
+ /** One group's fields, each its control, with the label on one side for the run (firstSideFirst). What a schema form draws inside a group,
416
+ * whichever frame holds the group (FieldRenderer's static groups, FieldFrame's settings frame). A kind over several stored settings
417
+ * (`spread`) reads them and writes back only the ones it changed, and is locked when any of them is. */
418
+ export function FieldRows({ fields, values, onChange, disabled, off, offWhy, onPickImage, onDraft, idPrefix, kinds: kindsProp, glyphs: glyphsProp }: FieldRowsProps & { fields: readonly AnyFieldSpec[] }) {
419
+ const { kinds, glyphs } = useFieldKinds(kindsProp, glyphsProp);
420
+ const inputId = (f: AnyFieldSpec) => (idPrefix ? `${idPrefix}${f.id}` : undefined);
421
+ const spreadOf = (f: AnyFieldSpec) => kindIn(kinds, f.kind)?.spread;
422
+ return (
423
+ <>
424
+ {firstSideFirst(fields, (f) => labelBeside(f, values[f.id], kinds)).map((f) => {
425
+ const spread = spreadOf(f);
426
+ if (spread) {
427
+ // Several settings, one control: only the settings a change touched are written. Locked when any of them is.
428
+ const locked = !!off && [f.id, ...spread.ids(f)].some((id) => off.has(id));
429
+ return <FieldControl key={f.id} field={f} inputId={inputId(f)} disabled={disabled || locked} describedBy={locked ? offWhy : undefined}
430
+ value={knobValue(f, values, kinds)} kinds={kinds} glyphs={glyphs}
431
+ onChange={(v) => { for (const [id, next] of spread.write(f, v, values)) onChange(id, next); }} />;
432
+ }
433
+ return <FieldControl key={f.id} field={f} inputId={inputId(f)} value={values[f.id]} disabled={disabled || off?.has(f.id)}
434
+ describedBy={off?.has(f.id) ? offWhy : undefined} kinds={kinds} glyphs={glyphs}
435
+ onChange={(v) => onChange(f.id, v)} onPickImage={onPickImage} onDraft={onDraft ? (v) => onDraft(f.id, v) : undefined} />;
436
+ })}
437
+ </>
438
+ );
439
+ }
440
+
441
+ /** A schema as a flat run of titled groups: a form's settings (Global styles, a bundle's look). A selected thing's settings panel draws its
442
+ * schema in the settings frame instead (FieldFrame). */
443
+ export function FieldRenderer({ schema, ...rows }: FieldRowsProps & { schema: FieldSchema }) {
444
+ return (
445
+ <div className="gemboss-ei-body">
446
+ {schema.map((group, gi) => (
447
+ <InspectorGroup collapsible={false} key={group.title ?? `g${gi}`} title={group.title} hint={group.hint}>
448
+ <FieldRows fields={group.fields} {...rows} />
449
+ </InspectorGroup>
450
+ ))}
451
+ </div>
452
+ );
453
+ }
@@ -0,0 +1,182 @@
1
+ "use client";
2
+ // A SCHEMA FORM IN THE SETTINGS FRAME (one settings frame slice 1, 06/11/2026; Chris: three settings frames, "sao không chuẩn hoá"; moved from
3
+ // the admin's components/shell/FieldFrame.tsx, 08/11/2026). The element panel's frame is the standard (InspectorFrame): a search, the index
4
+ // Look · Layout · Visibility · Code, group titles, and a group that holds nothing as a + line, a chip in Look. A schema is drawn here, each
5
+ // field where the element panel puts the same setting (field-spec.ts frameGroups). The controls are FieldRows' and every field keeps its
6
+ // stored key and its write: + shows a group and writes nothing, − writes each of its fields cleared (field-spec.ts knobClearWrites).
7
+ //
8
+ // A SEARCH IS SHOWN IN PLACE: what the words do not find is hidden, nothing is drawn again. A host's own parts (a section's words, its
9
+ // options, who it is for) may read their fields from a server; drawn again, they read again and their controls are chosen again (a long
10
+ // heading turned into a text area). A part is found by its fields' labels as drawn (what the seller reads), set or not.
11
+ import "../editor.css"; // the frame's groups and the rows' fields are editor.css's
12
+ import "../editor-inspector-frame.css"; // the frame (InspectorFrame brings it too); a search reads its open heads by their class
13
+ import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode } from "react";
14
+ import { InspectorChips } from "./chips";
15
+ import { FieldRows, useFieldKinds, type FieldGlyphs, type FieldKinds, type FieldRowsProps } from "./field-control";
16
+ import {
17
+ foundGroups, frameGroups, groupClearable, groupHolds, groupState, knobClearWrites, knobHolds, knobValue, settingMatches,
18
+ type FieldSchema, type FrameCluster, type FrameGroup, type FramePlaces,
19
+ } from "./field-spec";
20
+ import { InspectorFrame, InspectorFrameGroup, InspectorFramePart, InspectorSearch } from "./inspector-frame";
21
+
22
+ /** A part of the panel that is not a schema group (a section's words, its own options, the product it sells, who it is for): drawn first
23
+ * in its cluster, as an element's own groups are. `words`: its name, which a search finds it by besides its fields' labels. */
24
+ export type FramePart = { key: string; words: string; node: ReactNode };
25
+
26
+ /** What a part's fields are named by, as drawn: a search reads these, not the keys a section happens to hold. */
27
+ const LABELS = "label, .gemboss-ei-lbl, .gemboss-ei-openhead, [role=heading], legend";
28
+ // A layout effect in the browser; on a server render (a gate's static markup) there is no search to read.
29
+ const useBrowserLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
30
+
31
+ /**
32
+ * THE PARTS A SEARCH FINDS: by their name or by a field's label as drawn (what the seller reads, set or not), read again while it is open
33
+ * (a part's fields arrive when its read answers). `partRef(key)` goes on each part's element (InspectorFramePart `partRef`). Shared by
34
+ * FieldFrame and a host's own frame (the admin's element panel draws a section built from elements' parts on its root).
35
+ */
36
+ export function usePartHits(parts: readonly FramePart[], q: string): { hits: ReadonlySet<string>; partRef: (key: string) => (el: HTMLDivElement | null) => void } {
37
+ const partEls = useRef(new Map<string, HTMLDivElement>());
38
+ const [hits, setHits] = useState<ReadonlySet<string>>(() => new Set());
39
+ const partKeys = parts.map((p) => `${p.key}\u0000${p.words}`).join("\u0001");
40
+ useBrowserLayoutEffect(() => {
41
+ if (!q) return undefined;
42
+ const read = () => {
43
+ const next = new Set<string>();
44
+ for (const p of parts) {
45
+ const el = partEls.current.get(p.key);
46
+ const labels = el ? [...el.querySelectorAll(LABELS)].map((n) => n.textContent ?? "") : [];
47
+ if ([p.words, ...labels].some((t) => settingMatches(q, t))) next.add(p.key);
48
+ }
49
+ setHits((h) => (h.size === next.size && [...next].every((k) => h.has(k)) ? h : next));
50
+ };
51
+ read();
52
+ const watch = new MutationObserver(read);
53
+ for (const el of partEls.current.values()) watch.observe(el, { childList: true, subtree: true, characterData: true });
54
+ return () => watch.disconnect();
55
+ // `parts` by their keys and words: a new array each render is the same parts.
56
+ }, [q, partKeys]);
57
+ const partRef = (key: string) => (el: HTMLDivElement | null) => { if (el) partEls.current.set(key, el); else partEls.current.delete(key); };
58
+ return { hits, partRef };
59
+ }
60
+
61
+ export type FieldFrameProps = FieldRowsProps & {
62
+ schema: FieldSchema;
63
+ /** Several fields at once, as ONE write: a group's − clears each of its rows. Each host writes them together (one save, one preview from
64
+ * the end state, busy until it answers); one by one, a host composing each write from the same state lost all but the last. A row's own
65
+ * change is `onChange`. */
66
+ onChangeMany: (entries: ReadonlyArray<readonly [string, unknown]>) => void;
67
+ /** Above the first cluster: what governs what is under it (a write held or not saved, the knobs a section's own settings set now). Drawn
68
+ * while searching too. */
69
+ lead?: ReactNode;
70
+ /** The host's own parts, first in Look. */
71
+ own?: readonly FramePart[];
72
+ /** Who sees it besides its screens (an audience), first in Visibility. */
73
+ who?: readonly FramePart[];
74
+ /** Parts first in Layout (a theme part's spacing with its screen switch, a theme section's arrangement), and in Code (custom CSS). */
75
+ place?: readonly FramePart[];
76
+ code?: readonly FramePart[];
77
+ /** The values the screen edited sets itself, where `values` shows what it inherits too (Tablet / Mobile). A group is added, and its −
78
+ * clears, by these; one that only inherits shows its rows and says where they come from, with no − (it would write an empty value over
79
+ * nothing and change nothing). Absent: `values`. */
80
+ heldHere?: Record<string, unknown>;
81
+ /** Where an inherited value comes from ("Desktop"). */
82
+ inheritedFrom?: string;
83
+ /** Which fields are placed by id, and where (field-spec.ts `STYLE_FRAME_PLACES` by default). */
84
+ places?: FramePlaces;
85
+ };
86
+
87
+ export function FieldFrame({ schema, lead, own = [], who = [], place: placeParts = [], code: codeParts = [], heldHere, inheritedFrom, onChangeMany, places, ...rows }: FieldFrameProps) {
88
+ const { values, disabled } = rows;
89
+ // The app's kinds, by prop or FieldKindsProvider: a kind over several settings holds and clears by its own rule.
90
+ const { kinds } = useFieldKinds(rows.kinds, rows.glyphs);
91
+ const here = heldHere ?? values;
92
+ const groups = useMemo(() => frameGroups(schema, "", places), [schema, places]);
93
+ const [query, setQuery] = useState("");
94
+ const q = query.trim();
95
+ // The + groups shown with nothing in them (+ writes nothing here), until their − or until the panel closes.
96
+ const [shown, setShown] = useState<ReadonlySet<string>>(() => new Set());
97
+ // Where the focus goes after + or − (the button pressed is gone): the group's −, or its + line again. Kept for a moment: after − the
98
+ // group is a + line once the host's write lands (it may be async), not in the render the press makes.
99
+ const focusNext = useRef<{ root: Element; sel: string; until: number } | null>(null);
100
+ useEffect(() => {
101
+ const f = focusNext.current;
102
+ if (!f) return;
103
+ const at = f.root.querySelector<HTMLElement>(f.sel);
104
+ if (at) { focusNext.current = null; at.focus(); } else if (Date.now() > f.until) focusNext.current = null;
105
+ });
106
+ const parts = [...own, ...placeParts, ...who, ...codeParts];
107
+ const { hits, partRef } = usePartHits(parts, q);
108
+ const found = useMemo(() => (q ? new Map(foundGroups(groups, q).map((g) => [g.key, g])) : null), [groups, q]);
109
+ const rowsOf = (g: FrameGroup) => (
110
+ <>
111
+ <FieldRows fields={g.fields} {...rows} />
112
+ {g.hint ? <p className="gemboss-ei-hint">{g.hint}</p> : null}
113
+ </>
114
+ );
115
+ const add = (g: FrameGroup) => (e: MouseEvent<HTMLButtonElement>) => {
116
+ const root = e.currentTarget.closest("[data-settings-frame]");
117
+ focusNext.current = root ? { root, sel: `[data-remove-group="${g.key}"]`, until: Date.now() + 3000 } : null;
118
+ setShown((s) => new Set(s).add(g.key));
119
+ };
120
+ const remove = (g: FrameGroup) => (e: MouseEvent<HTMLButtonElement>) => {
121
+ const root = e.currentTarget.closest("[data-settings-frame]");
122
+ focusNext.current = root ? { root, sel: `[data-add-group="${g.key}"] button`, until: Date.now() + 3000 } : null;
123
+ const cleared = g.fields.filter((f) => knobHolds(f, knobValue(f, here, kinds), kinds)).flatMap((f) => knobClearWrites(f, here, kinds));
124
+ if (cleared.length) onChangeMany(cleared);
125
+ setShown((s) => { const next = new Set(s); next.delete(g.key); return next; });
126
+ };
127
+ const draw = (g: FrameGroup, chip = false) => {
128
+ if (found) {
129
+ // Searching: a group the words find is open with the fields they find, every other one not drawn.
130
+ const hit = found.get(g.key);
131
+ return hit ? <InspectorFrameGroup key={g.key} groupKey={g.key} state="open" title={g.title}>{rowsOf(hit)}</InspectorFrameGroup> : null;
132
+ }
133
+ // One component in the three states, so a group that is added stays the same element where it was (the focus kept in it).
134
+ const holdsHere = groupHolds(g, here, kinds);
135
+ const inherits = !holdsHere && groupHolds(g, values, kinds);
136
+ const state = inherits && g.way === "add" ? "added" : groupState(g, here, shown, kinds);
137
+ // A − where it takes something off on this screen (never a text the seller wrote: groupClearable), or where + showed it with nothing.
138
+ const removable = holdsHere ? groupClearable(g) : !inherits && shown.has(g.key);
139
+ return (
140
+ <InspectorFrameGroup key={g.key} groupKey={g.key} state={state} title={g.title} disabled={disabled} chip={chip && state === "add"} onAdd={add(g)}
141
+ note={inherits && inheritedFrom ? `from ${inheritedFrom}` : undefined}
142
+ remove={removable ? { label: `Remove ${g.title.toLowerCase()}`, onRemove: remove(g) } : null}>
143
+ {state === "add" ? null : rowsOf(g)}
144
+ </InspectorFrameGroup>
145
+ );
146
+ };
147
+ const part = (p: FramePart) => (
148
+ <InspectorFramePart key={p.key} partKey={p.key} hidden={!!q && !hits.has(p.key)}
149
+ partRef={partRef(p.key)}>{p.node}</InspectorFramePart>
150
+ );
151
+ const of = (c: FrameCluster) => groups.filter((g) => g.cluster === c);
152
+ const look = of("look");
153
+ // The look's shared groups are one run where a + line is a chip (InspectorChips, Control UI C32 slice 3).
154
+ const firstShared = look.findIndex((g) => !g.own);
155
+ const ownLook = firstShared < 0 ? look : look.slice(0, firstShared);
156
+ const sharedLook = firstShared < 0 ? [] : look.slice(firstShared);
157
+ const place = of("place");
158
+ const when = of("when");
159
+ const code = of("code");
160
+ const nothing = !!q && !hits.size && !(found?.size);
161
+ return (
162
+ <InspectorFrame search={<InspectorSearch value={query} onChange={setQuery} name="section-setting-search" />} searching={!!q}
163
+ lead={<>{lead}{nothing ? <p className="gemboss-ei-hint" data-find-none="">No setting matches “{q}”.</p> : null}</>}
164
+ clusters={[
165
+ { id: "look", on: own.length + look.length > 0, content: <>{own.map(part)}{ownLook.map((g) => draw(g))}
166
+ {sharedLook.length ? <InspectorChips attrs={{ "data-look-chips": "" }}>{sharedLook.map((g) => draw(g, true))}</InspectorChips> : null}</> },
167
+ { id: "place", on: placeParts.length + place.length > 0, content: <>{placeParts.map(part)}{place.map((g) => draw(g))}</> },
168
+ { id: "when", on: who.length + when.length > 0, content: <>{who.map(part)}{when.map((g) => draw(g))}</> },
169
+ { id: "code", on: codeParts.length + code.length > 0, content: <>{codeParts.map(part)}{code.map((g) => draw(g))}</> },
170
+ ]} />
171
+ );
172
+ }
173
+
174
+ const NO_SCHEMA: FieldSchema = [];
175
+ const NO_VALUES: Record<string, unknown> = {};
176
+ const noop = () => {};
177
+ /** A panel of parts only, in the frame (a plugin's settings, the store's header and footer): the frame, its search and its index around
178
+ * groups a host draws itself with the kit's controls, no schema of its own. */
179
+ export function PartsFrame({ lead, own, place, who, code, kinds, glyphs }: { lead?: ReactNode; own?: readonly FramePart[]; place?: readonly FramePart[]; who?: readonly FramePart[]; code?: readonly FramePart[]; kinds?: FieldKinds; glyphs?: FieldGlyphs }) {
180
+ return <FieldFrame schema={NO_SCHEMA} values={NO_VALUES} onChange={noop} onChangeMany={noop} lead={lead} own={own} place={place} who={who} code={code} kinds={kinds} glyphs={glyphs} />;
181
+ }
182
+