@gemboss/ui 0.50.0 → 0.52.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,183 @@
1
+ "use client";
2
+ // COLOR PICKER (24/10/2026, Chris: the colour picker should be standard and look right; "ưu tiên ui ux dễ dùng"). The panel a
3
+ // colour field's swatch opens (ColorControl → Popover). Before it the swatch opened the OPERATING SYSTEM's picker: a different
4
+ // window on every machine, no opacity, none of the theme's colours. Learnt from GemPages (an in-app square, hue and opacity, an
5
+ // eyedropper, recent colours) and NOT copied where it is worse (its square is hidden on desktop until a second click, and works
6
+ // with a mouse only; it offers no theme colours):
7
+ // · the square (saturation × brightness) works with the pointer AND the keys: ← → saturation, ↑ ↓ brightness, Shift for 10;
8
+ // · hue and opacity are native ranges (keys, screen readers, a finger: free), opacity over a checkerboard in the colour;
9
+ // · the hex box takes a colour as typed (3 or 6 digits, with or without #); the eyedropper picks one from the screen where
10
+ // the browser has `EyeDropper` (Chrome, Edge);
11
+ // · the theme's colours (they write `var(--gem-color-<role>)`: the page keeps following the theme), the recent ones, and None;
12
+ // · a pick keeps the value's transparency and its way of writing (`pickSwatch`, as the native swatch did); while a drag lasts
13
+ // it writes at most every 80 ms and once when it ends, so the canvas follows without a write per pixel.
14
+ // Its own part (`editor-color.css`).
15
+ import "../editor.css"; // the colour chips (.gemboss-ei-sw) are the editor's
16
+ import "../editor-color.css";
17
+ import React, { useEffect, useRef, useState } from "react";
18
+ import { Icon } from "../icons";
19
+ import { hexOf, opacityOf, parseColor, pickSwatch, withOpacity, type Rgba } from "./swatch";
20
+ import type { ColorChoice } from "./controls";
21
+
22
+ export interface ColorPickerProps {
23
+ /** The field's value now (what the theme chips and None compare with). */
24
+ value: string;
25
+ /** The colour picks start from: the value, or the colour a theme chip it holds paints. Empty opens on white. */
26
+ base?: string;
27
+ /** Called with each new value (throttled while a drag lasts, then once at its end). */
28
+ onChange: (value: string) => void;
29
+ /** The field's name, for the controls' names ("Background hue"). */
30
+ label: string;
31
+ choices?: readonly ColorChoice[];
32
+ /** A "None" chip that empties the field (Not set). */
33
+ allowNone?: boolean;
34
+ }
35
+
36
+ type Hsv = { h: number; s: number; v: number };
37
+ const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));
38
+
39
+ function hsvOf({ r, g, b }: Rgba, keepHue = 0): Hsv {
40
+ const R = r / 255, G = g / 255, B = b / 255, max = Math.max(R, G, B), min = Math.min(R, G, B), d = max - min;
41
+ let h = keepHue;
42
+ if (d) h = max === R ? ((G - B) / d) % 6 : max === G ? (B - R) / d + 2 : (R - G) / d + 4;
43
+ if (d) h = (h * 60 + 360) % 360;
44
+ return { h, s: max ? (d / max) * 100 : 0, v: max * 100 };
45
+ }
46
+ function rgbOf({ h, s, v }: Hsv) {
47
+ const S = s / 100, V = v / 100, c = V * S, x = c * (1 - Math.abs(((h / 60) % 2) - 1)), m = V - c;
48
+ const [r, g, b] = h < 60 ? [c, x, 0] : h < 120 ? [x, c, 0] : h < 180 ? [0, c, x] : h < 240 ? [0, x, c] : h < 300 ? [x, 0, c] : [c, 0, x];
49
+ return { r: (r + m) * 255, g: (g + m) * 255, b: (b + m) * 255 };
50
+ }
51
+
52
+ export function ColorPicker({ value, base, onChange, label, choices, allowNone = true }: ColorPickerProps) {
53
+ const from = base ?? value;
54
+ const parsed = parseColor(from);
55
+ const rgba: Rgba = parsed ?? { r: 255, g: 255, b: 255, a: 1 };
56
+ // The hue is kept here: a grey or a black has none, and dragging to one must not throw the square back to red.
57
+ const [hsv, setHsv] = useState<Hsv>(() => hsvOf(rgba));
58
+ // A value from outside (a chip, the text box, Undo) moves the square; our own echo does not, nor anything while a drag lasts
59
+ // (a throttled write comes back older than the pointer, and the square would jump back to it).
60
+ const emitted = useRef<string | null>(null);
61
+ const dragging = useRef(false);
62
+ useEffect(() => {
63
+ if (dragging.current || from === emitted.current) return;
64
+ setHsv((now) => hsvOf(rgba, now.h));
65
+ }, [from]); // eslint-disable-line react-hooks/exhaustive-deps
66
+
67
+ // Writes: a key or a click at once; a drag at most every 80 ms, and always its last one.
68
+ const last = useRef(0);
69
+ const trailing = useRef<ReturnType<typeof setTimeout> | null>(null);
70
+ const send = (next: string) => { emitted.current = next; last.current = Date.now(); onChange(next); };
71
+ const emit = (next: string, final = !dragging.current) => {
72
+ if (trailing.current) { clearTimeout(trailing.current); trailing.current = null; }
73
+ const now = Date.now();
74
+ if (final || now - last.current >= 80) { send(next); return; }
75
+ trailing.current = setTimeout(() => { trailing.current = null; send(next); }, 80 - (now - last.current));
76
+ };
77
+ useEffect(() => () => { if (trailing.current) clearTimeout(trailing.current); }, []);
78
+ const write = (h: Hsv, final?: boolean) => { setHsv(h); emit(pickSwatch(from, hexOf(rgbOf(h))), final); };
79
+ // A bar pressed and let go without moving writes nothing: a plain click rewrote a theme token as its hex, and hsl / oklch / #f00
80
+ // as rgb (review of #5296). `moved` says the bar's value changed during this press.
81
+ const moved = useRef(false);
82
+ const dragStart = () => { dragging.current = true; moved.current = false; };
83
+ const dragEnd = () => { dragging.current = false; };
84
+ // The opacity bar's value while it is held: a controlled range only moves when a (throttled) write lands, so between writes React
85
+ // put it back, and the release read that old value and wrote it over the one the pointer left (review of #5296).
86
+ const [alphaHeld, setAlphaHeld] = useState<number | null>(null);
87
+
88
+ // The square: pointer, then keys.
89
+ const area = useRef<HTMLDivElement>(null);
90
+ const fromPointer = (e: React.PointerEvent, final?: boolean) => {
91
+ const r = area.current!.getBoundingClientRect();
92
+ write({ h: hsv.h, s: clamp(((e.clientX - r.left) / r.width) * 100, 0, 100), v: clamp(100 - ((e.clientY - r.top) / r.height) * 100, 0, 100) }, final);
93
+ };
94
+ const areaKey = (e: React.KeyboardEvent) => {
95
+ const step = e.shiftKey ? 10 : 1;
96
+ const d = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] }[e.key];
97
+ if (!d) return;
98
+ e.preventDefault();
99
+ write({ h: hsv.h, s: clamp(hsv.s + d[0]!, 0, 100), v: clamp(hsv.v + d[1]!, 0, 100) }, true);
100
+ };
101
+
102
+ const alpha = opacityOf(from);
103
+ const pure = `hsl(${Math.round(hsv.h)} 100% 50%)`;
104
+ const now = hexOf(rgbOf(hsv));
105
+ const [hexDraft, setHexDraft] = useState<string | null>(null);
106
+ const commitHex = (raw: string) => {
107
+ setHexDraft(null);
108
+ const t = raw.trim().replace(/^#?/, "#");
109
+ if (!/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(t)) return;
110
+ const next = pickSwatch(from, t);
111
+ const c = parseColor(next);
112
+ if (c) setHsv((h) => hsvOf(c, h.h));
113
+ emit(next, true);
114
+ };
115
+ const canDrop = typeof window !== "undefined" && "EyeDropper" in window;
116
+ const dropper = async () => {
117
+ try {
118
+ const picked = await new (window as unknown as { EyeDropper: new () => { open: () => Promise<{ sRGBHex: string }> } }).EyeDropper().open();
119
+ const next = pickSwatch(from, picked.sRGBHex);
120
+ const c = parseColor(next);
121
+ if (c) setHsv((h) => hsvOf(c, h.h));
122
+ emit(next, true);
123
+ } catch { /* closed with Escape: nothing picked */ }
124
+ };
125
+ const theme = (choices ?? []).filter((c) => c.group !== "recent");
126
+ const recent = (choices ?? []).filter((c) => c.group === "recent");
127
+ const chips = (list: readonly ColorChoice[], name: string) => list.length ? (
128
+ <div className="gemboss-ei-cp-group">
129
+ <span className="gemboss-ei-cp-label">{name}</span>
130
+ <div className="gemboss-ei-cp-chips" role="group" aria-label={`${label}: ${name.toLowerCase()}`}>
131
+ {list.map((c) => {
132
+ const on = c.value === value.trim();
133
+ return <button key={c.value} type="button" className={`gemboss-ei-sw${on ? " on" : ""}`} title={c.label} aria-label={c.label} aria-pressed={on}
134
+ style={{ background: c.swatch }} onClick={() => { emitted.current = null; onChange(c.value); }} />;
135
+ })}
136
+ </div>
137
+ </div>
138
+ ) : null;
139
+
140
+ return (
141
+ <div className="gemboss-ei-cp" style={{ "--cp-hue": pure, "--cp-now": now } as React.CSSProperties}>
142
+ <div ref={area} className="gemboss-ei-cp-area" role="slider" tabIndex={0} data-autofocus=""
143
+ aria-label={`${label}: saturation and brightness`} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(hsv.s)}
144
+ aria-valuetext={`Saturation ${Math.round(hsv.s)}%, brightness ${Math.round(hsv.v)}%`}
145
+ onPointerDown={(e) => { e.currentTarget.setPointerCapture(e.pointerId); e.currentTarget.focus(); dragStart(); fromPointer(e); }}
146
+ onPointerMove={(e) => { if (e.currentTarget.hasPointerCapture(e.pointerId)) fromPointer(e); }}
147
+ onPointerUp={(e) => { if (e.currentTarget.hasPointerCapture(e.pointerId)) { dragEnd(); fromPointer(e, true); } }}
148
+ onPointerCancel={dragEnd}
149
+ onKeyDown={areaKey}>
150
+ <span className="gemboss-ei-cp-thumb" style={{ left: `${hsv.s}%`, top: `${100 - hsv.v}%` }} />
151
+ </div>
152
+ <input type="range" className="gemboss-ei-cp-hue" min={0} max={359} step={1} value={Math.round(hsv.h)} aria-label={`${label} hue`}
153
+ onPointerDown={dragStart} onChange={(e) => { moved.current = true; write({ ...hsv, h: Number(e.target.value) }); }}
154
+ onPointerUp={() => { dragEnd(); if (moved.current) emit(pickSwatch(from, now), true); }} onPointerCancel={dragEnd} />
155
+ <input type="range" className="gemboss-ei-cp-alpha" min={0} max={100} step={1} value={alphaHeld ?? alpha ?? 100} aria-label={`${label} opacity`}
156
+ disabled={alpha === null} onPointerDown={dragStart}
157
+ onChange={(e) => { const n = Number(e.target.value); moved.current = true; if (dragging.current) setAlphaHeld(n); emit(withOpacity(from, n)); }}
158
+ onPointerUp={() => { dragEnd(); const n = alphaHeld; setAlphaHeld(null); if (moved.current && n !== null) emit(withOpacity(from, n), true); }}
159
+ onPointerCancel={() => { dragEnd(); setAlphaHeld(null); }} />
160
+ <div className="gemboss-ei-cp-row">
161
+ <span className="gemboss-ei-cp-now" aria-hidden />
162
+ <input className="gemboss-field gemboss-ei-cp-hex" aria-label={`${label} hex`} spellCheck={false} autoComplete="off"
163
+ value={hexDraft ?? (parsed ? now.toUpperCase() : "")} placeholder="#FFFFFF"
164
+ // Only what was typed is written: a blur with nothing typed since (the popover handing the focus back) writes nothing.
165
+ onChange={(e) => setHexDraft(e.target.value)} onBlur={() => { if (hexDraft !== null) commitHex(hexDraft); }}
166
+ onKeyDown={(e) => { if (e.key === "Enter" && !e.nativeEvent.isComposing && hexDraft !== null) { e.preventDefault(); commitHex(hexDraft); } }} />
167
+ <span className="gemboss-ei-cp-pct" aria-hidden>{alpha === null ? "" : `${alpha}%`}</span>
168
+ {canDrop ? (
169
+ <button type="button" className="gemboss-ei-cp-drop" aria-label="Pick a color from the screen" title="Pick a color from the screen" onClick={dropper}>
170
+ <Icon name="eyedropper" size={16} />
171
+ </button>
172
+ ) : null}
173
+ </div>
174
+ {chips(theme, "Theme")}
175
+ {chips(recent, "Recent")}
176
+ {allowNone ? (
177
+ <button type="button" className="gemboss-ei-cp-none" aria-pressed={!value.trim()} onClick={() => { emitted.current = null; onChange(""); }}>
178
+ <span className="gemboss-ei-cp-none-sw" aria-hidden />None
179
+ </button>
180
+ ) : null}
181
+ </div>
182
+ );
183
+ }
@@ -11,10 +11,13 @@
11
11
  // · the edge box hands each keystroke to the caller (`onChange(side, raw)`) and says when to commit (`onCommit`, on
12
12
  // blur): the caller decides what an empty edge means, and the admin has three answers to that on purpose.
13
13
  import "../editor.css"; // its own stylesheet travels with it (0.23.0): a surface that never renders it never loads it
14
+ import "../editor-color.css"; // the swatch button (ColorControl); the picker's own rules are in it too
14
15
  import { useEffect, useId, useRef, useState } from "react";
15
16
  import type React from "react";
16
17
  import { cssUrl } from "./css-url";
17
- import { opacityOf, pickSwatch, swatchState, swatchWhy, withOpacity } from "./swatch";
18
+ import { ColorPicker } from "./color-picker";
19
+ import { Popover } from "./popover";
20
+ import { opacityOf, parseColor, swatchState, swatchWhy, withOpacity } from "./swatch";
18
21
  import { Segmented } from "../segmented";
19
22
 
20
23
  const blurOnEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
@@ -156,32 +159,49 @@ export interface ColorControlProps {
156
159
  /** Colours offered as chips while the field is in use (the focus inside it): the theme's colours by role, each with the colour
157
160
  * the page draws for it, then the ones used lately. A click writes `value`. None: no chips (the theme inspector, no page). */
158
161
  choices?: readonly ColorChoice[];
162
+ /** The picker's None, which empties the field (default true). False where an empty value is not one (a gradient's stop). */
163
+ allowNone?: boolean;
164
+ /** An id the text box is also described by (a field's "not saved" line), beside the swatch's own reason. */
165
+ describedBy?: string;
166
+ /** The text box as it is typed, each keystroke, before its commit (blur / Enter). A host that keeps unsaved edits (a claims
167
+ * queue, a flush when the panel switches) holds the typing with it: kept only here, a value landing from elsewhere replaced
168
+ * the half-typed one unseen, and a switch that unmounts the box without a blur dropped it (review of #5323). */
169
+ onDraft?: (text: string) => void;
159
170
  }
160
171
 
161
- /** One chip: what it writes (`var(--gem-color-accent)`, `#3366ff`), what it is called, and the colour it paints. */
162
- export interface ColorChoice { value: string; label: string; swatch: string }
172
+ /** One chip: what it writes (`var(--gem-color-accent)`, `#3366ff`), what it is called, and the colour it paints. `group`: where the
173
+ * picker shows it ("Theme" or "Recent"); unset is a theme colour. */
174
+ export interface ColorChoice { value: string; label: string; swatch: string; group?: "theme" | "recent" }
163
175
 
164
176
  /**
165
- * `.gemboss-ei-color`: a native swatch beside a text box, and the colour's opacity in percent. The swatch shows any one colour
166
- * (`swatchState`: hex, rgb, hsl, oklch) and a pick keeps the value's transparency and way of writing (`pickSwatch`); it is
167
- * DISABLED (with the reason under it) for what is not one colour, a token or a gradient: `<input type="color">` would show
168
- * black for it and overwrite it with black on the first touch. The opacity box shows for a colour only (A4, 21/10/2026: 17% of
169
- * the colours on real pages carry an alpha, which no control could change).
177
+ * `.gemboss-ei-color`: a swatch beside a text box, and the colour's opacity in percent. The swatch shows any one colour
178
+ * (`swatchState`: hex, rgb, hsl, oklch) over a checkerboard, and opens the kit's colour picker beside the settings column
179
+ * (`Popover` + `ColorPicker`, 24/10/2026: it opened the operating system's picker, a different window on every machine with no
180
+ * opacity and no theme colours); a pick keeps the value's transparency and way of writing (`pickSwatch`). It is DISABLED (with
181
+ * the reason under it) for what is not one colour, a token or a gradient: a pick would overwrite it. The opacity box shows for
182
+ * a colour only (A4, 21/10/2026: 17% of the colours on real pages carry an alpha, which no control could change).
170
183
  */
171
- export function ColorControl({ id, value, onChange, disabled, label, placeholder, choices }: ColorControlProps) {
184
+ export function ColorControl({ id, value, onChange, disabled, label, placeholder, choices, allowNone = true, describedBy, onDraft }: ColorControlProps) {
172
185
  const [draft, setDraft] = useState(value);
173
186
  useEffect(() => { setDraft(value); }, [value]);
174
- // THE THEME'S COLOURS, CLICKED (A4b, 21/10/2026; Chris: "bấm trước gõ sau"): while the field is in use its chips show under it,
175
- // and go when the focus leaves it, so a panel of colour fields is no longer for them. A theme colour the field holds shows on
176
- // the swatch as the colour the page draws for it, and a pick there writes that colour as your own.
177
- const [inUse, setInUse] = useState(false);
187
+ // THE THEME'S COLOURS, CLICKED (A4b, 21/10/2026; Chris: "bấm trước gõ sau"): in the picker the swatch opens, under Theme and
188
+ // Recent, two clicks as before. Not any more as chips under the row while it had the focus (24/10/2026): they went when the focus
189
+ // left, so a press on the row below moved up under the pointer and its click was lost (review of #5296, measured: 38px). A theme
190
+ // colour the field holds shows on the swatch as the colour the page draws for it, and a pick there writes that colour as your own.
178
191
  const chosen = choices?.find((c) => c.value === draft.trim()) ?? null;
179
192
  const shown = chosen ? swatchState(chosen.swatch) : null;
180
193
  // NOT SET IS NOT BLACK (control standard §13b U7, Chris 20/10/2026): an empty colour drew the swatch black beside "Not set", so a
181
194
  // seller read a colour nobody chose. Empty, the swatch is white with the slash a colour picker draws for "none" (editor.css
182
195
  // `[data-empty]`), and opens on white.
183
196
  const empty = !draft.trim();
184
- const { swatch, usable } = shown?.usable ? shown : swatchState(draft, "#ffffff");
197
+ const { usable } = shown?.usable ? shown : swatchState(draft);
198
+ // What the swatch paints: the colour with its opacity (the checkerboard shows through). Nothing for what it cannot show (a
199
+ // gradient, an unknown token): the native swatch painted those black, a colour nobody chose (SwatchState's rule).
200
+ const parsed = usable ? parseColor(chosen ? chosen.swatch : draft) : null;
201
+ const paint = parsed ? `rgba(${Math.round(parsed.r)}, ${Math.round(parsed.g)}, ${Math.round(parsed.b)}, ${parsed.a})` : null;
202
+ const rowRef = useRef<HTMLDivElement>(null);
203
+ const swatchRef = useRef<HTMLButtonElement>(null);
204
+ const [picking, setPicking] = useState(false);
185
205
  // Why the swatch is off, said under it, read with it (a tooltip alone reached neither a finger nor the keys). The COMMITTED
186
206
  // value's reason, and kept while the panel saves (it disables every field): taken from the draft or dropped while saving, the
187
207
  // line came and went on every write and while a hex was typed (review of #4636). A draft that is a whole hex has none.
@@ -198,14 +218,22 @@ export function ColorControl({ id, value, onChange, disabled, label, placeholder
198
218
  if (next !== draft) { setDraft(next); onChange(next); }
199
219
  };
200
220
  return (
201
- <div className="gemboss-ei-color" onFocus={() => setInUse(true)}
202
- onBlur={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setInUse(false); }}>
203
- <input type="color" className="gemboss-ei-swatch" aria-label={`${label} swatch`} value={swatch} data-empty={empty ? "" : undefined}
204
- disabled={disabled || !usable}
221
+ <div ref={rowRef} className="gemboss-ei-color">
222
+ <button ref={swatchRef} type="button" className="gemboss-ei-swatch" aria-label={`${label} swatch`} aria-haspopup="dialog" aria-expanded={picking}
223
+ data-empty={empty ? "" : undefined} disabled={disabled || !usable}
205
224
  title={usable ? undefined : swatchWhy(draft) ?? undefined} aria-describedby={why ? whyId : undefined}
206
- onChange={(e) => { const next = pickSwatch(chosen ? chosen.swatch : draft, e.target.value); setDraft(next); onChange(next); }} />
207
- <input id={id} className="gemboss-field gemboss-ei-inp" placeholder={placeholder ?? "Not set"} value={draft} disabled={disabled}
208
- onChange={(e) => setDraft(e.target.value)} onBlur={() => onChange(draft)} onKeyDown={blurOnEnter} />
225
+ onClick={() => setPicking((p) => !p)}>
226
+ <span className="gemboss-ei-swatch-fill" style={paint ? { "--sw": paint } as React.CSSProperties : undefined} />
227
+ </button>
228
+ {/* Open from the swatch's click until it is closed: not shut by a save in flight (the panels disable every field while one
229
+ runs, which closed it on each pick and opened it again with the focus: review of #5296), nor by the text box holding a
230
+ half-typed colour (it closed at "#" and opened at "#123", taking the focus and the rest of the typing). */}
231
+ <Popover open={picking} anchor={rowRef.current} returnTo={swatchRef.current} title={label} onClose={() => setPicking(false)}>
232
+ <ColorPicker value={draft} base={chosen ? chosen.swatch : draft} label={label} choices={choices} allowNone={allowNone}
233
+ onChange={(next) => { setDraft(next); onChange(next); }} />
234
+ </Popover>
235
+ <input id={id} className="gemboss-field gemboss-ei-inp" placeholder={placeholder ?? "Not set"} value={draft} disabled={disabled} aria-describedby={describedBy}
236
+ onChange={(e) => { setDraft(e.target.value); onDraft?.(e.target.value); }} onBlur={() => onChange(draft)} onKeyDown={blurOnEnter} />
209
237
  {/* A fixed narrow box beside the wide one (the row's own rule makes every .gemboss-ei-inp flex: 1): inline, not a new rule. */}
210
238
  {opacity !== null ? (
211
239
  // `data-alpha`: the hook editor-plain.js finds it by (the same box on a page without React).
@@ -213,18 +241,6 @@ export function ColorControl({ id, value, onChange, disabled, label, placeholder
213
241
  value={alphaDraft ?? `${opacity}%`} disabled={disabled}
214
242
  onChange={(e) => setAlphaDraft(e.target.value)} onBlur={(e) => commitAlpha(e.target.value)} onKeyDown={blurOnEnter} />
215
243
  ) : null}
216
- {inUse && choices?.length ? (
217
- // The kit's colour chips (.gemboss-ei-swatches / .gemboss-ei-sw, the theme inspector's Background row), on a line of their own.
218
- <div className="gemboss-ei-swatches" role="group" aria-label={`${label} colors`} style={{ flexBasis: "100%", flexWrap: "wrap" }}>
219
- {choices.map((c) => {
220
- const on = c.value === draft.trim();
221
- return (
222
- <button key={c.value} type="button" className={`gemboss-ei-sw${on ? " on" : ""}`} title={c.label} aria-label={c.label} aria-pressed={on}
223
- style={{ background: c.swatch }} disabled={disabled} onClick={() => { setDraft(c.value); onChange(c.value); }} />
224
- );
225
- })}
226
- </div>
227
- ) : null}
228
244
  {why ? <p id={whyId} className="gemboss-ei-color-why">{why}</p> : null}
229
245
  </div>
230
246
  );
@@ -53,4 +53,12 @@ export { SortableLayerList, type SortableLayerListProps, useRowDrag, dropIndex }
53
53
  export { RepeaterList, useKeyedRows, type RepeaterListProps, type KeyedRows } from "./repeater";
54
54
  // 16/10/2026: a closed choice of shapes (an image's ratio, a layout) as picture tiles; its own CSS part, editor-tiles.css.
55
55
  export { ChoiceTiles, type ChoiceTile, type ChoiceTilesProps } from "./tiles";
56
+ // 24/10/2026: a setting's small panel beside the settings column (top layer; a sheet at phone width); its own CSS part.
57
+ export { Popover, type PopoverProps } from "./popover";
58
+ // 24/10/2026: the colour picker ColorControl's swatch opens (square, hue, opacity, hex, eyedropper, theme/recent/None).
59
+ export { ColorPicker, type ColorPickerProps } from "./color-picker";
60
+ // 24/10/2026: the body of every "choose one" popup (search, rows, states); its own CSS part, editor-picker.css.
61
+ export { PickerList, type PickerItem, type PickerListProps, type PickerTone } from "./picker";
62
+ // 24/10/2026: the same search and states for things chosen by their picture (the shop's images, an icon library); its own CSS part.
63
+ export { PickerGrid, type PickerTile, type PickerGridProps } from "./picker-grid";
56
64
  export { LayerTree, type LayerTreeProps, type LayerTreeRow } from "./tree";
@@ -0,0 +1,186 @@
1
+ "use client";
2
+ // PICKER GRID (24/10/2026, picker standard slice 3): PickerList's search box, highlight and states for things chosen by their
3
+ // PICTURE (the shop's images, an icon library): tiles in as many columns as fit; a click selects, a double click or Enter uses at
4
+ // once where the caller has a "use" (the image picker's Use image); a tile being uploaded or that failed shows, cannot be chosen,
5
+ // and is said aloud from outside the grid (an option's children are presentational: an alert inside one is not announced).
6
+ // Keys, the WAI-ARIA grid combobox's: ↑ ↓ move by a row, to the tile in the next row nearest the column (the last row may be
7
+ // short; a row of tiles in flight is passed); in the search box ← → Home End are the caret's until ↑ or ↓ has stepped into the
8
+ // grid, and the grid's from then until the next keystroke typed (review of slice 3: with the box always keeping ← →, a keyboard
9
+ // reached only the highlighted tile's column). Without a box the grid has the focus and every key is the grid's.
10
+ // Its own part (`editor-picker-grid.css`); the shared pieces are editor-picker.css's.
11
+ import "../editor-picker.css";
12
+ import "../editor-picker-grid.css";
13
+ import React, { useEffect, useId, useRef, useState } from "react";
14
+ import { Icon } from "../icons";
15
+ import { PickNothing, PickSearch, typesFirst, usePickHighlight, type PickerSearch } from "./picker";
16
+
17
+ export interface PickerTile {
18
+ /** What `onSelect` / `onActivate` get, and what `selected` is compared with. */
19
+ key: string;
20
+ title: string;
21
+ /** A second line under the name (where the image came from). */
22
+ subtitle?: string;
23
+ /** The tile's tooltip, its title when left out: the image picker's file address, which tells two files of one name apart. */
24
+ tooltip?: string;
25
+ /** A photo: a URL, or null for one that could have a picture and has none (a grey square keeps its place). */
26
+ image?: string | null;
27
+ /** A drawn picture instead (an icon's SVG), centred in the tile. */
28
+ picture?: React.ReactNode;
29
+ /** The photo whole inside its square (a logo, a cut-out) instead of filling it; `checker`: on a checkerboard (a cut-out). */
30
+ fit?: "cover" | "contain";
31
+ checker?: boolean;
32
+ /** A tile not yet a choice: being uploaded (`busy`), or one that failed (`error`, said in red). Shown, not choosable. */
33
+ status?: { busy?: boolean; error?: string };
34
+ }
35
+
36
+ export interface PickerGridProps {
37
+ /** The grid's accessible name ("Your images", "Icons"). */
38
+ label: string;
39
+ tiles: readonly PickerTile[];
40
+ /** The tile now chosen: a check, `aria-selected`, and the one highlighted first. */
41
+ selected?: string | null;
42
+ /** A click, Space: the tile chosen (the image picker's selection; an icon library's pick). */
43
+ onSelect: (key: string) => void;
44
+ /** A double click, Enter: the tile used at once (the image picker's Use image). Without it they select. */
45
+ onActivate?: (key: string) => void;
46
+ search?: PickerSearch;
47
+ state?: "ready" | "loading" | "reloading" | "error";
48
+ error?: { message: string; onRetry?: () => void };
49
+ empty?: { title: string; body?: string; action?: React.ReactNode };
50
+ more?: { onClick: () => void; busy?: boolean; label?: string };
51
+ /** `photo`: square pictures, 120px wide at least, a name and a line (the default). `icon`: a 26px drawing over its name (two
52
+ * lines at most), 88px wide at least. */
53
+ size?: "photo" | "icon";
54
+ /** Skeleton tiles while loading (default 8). */
55
+ loadingTiles?: number;
56
+ }
57
+
58
+ export function PickerGrid({ label, tiles, selected = null, onSelect, onActivate, search, state = "ready", error, empty, more, size = "photo", loadingTiles = 8 }: PickerGridProps) {
59
+ const base = useId();
60
+ const boxRef = useRef<HTMLInputElement>(null);
61
+ const gridRef = useRef<HTMLUListElement>(null);
62
+ const phase = state === "reloading" && tiles.length === 0 ? "loading" : state;
63
+ const shown = phase === "ready" || phase === "reloading" ? tiles : [];
64
+ const live = phase === "ready";
65
+ const choosable = (t: PickerTile | undefined) => !!t && !t.status;
66
+ const query = search?.value ?? "";
67
+ const tileId = (i: number) => `${base}-t${i}`;
68
+ const { active, highlight } = usePickHighlight(shown, choosable, selected, query, tileId);
69
+ // In the box: ↑ or ↓ has stepped into the grid, so ← → Home End move the highlight; a keystroke typed gives them back to the caret.
70
+ const [stepping, setStepping] = useState(false);
71
+ useEffect(() => { setStepping(false); }, [query]);
72
+
73
+ // Columns as laid out now (as many as fit): the tiles on the first row.
74
+ const columns = () => {
75
+ const els = gridRef.current ? [...gridRef.current.querySelectorAll<HTMLElement>("[role=option]")] : [];
76
+ const top = els[0]?.offsetTop;
77
+ const n = els.findIndex((e) => e.offsetTop !== top);
78
+ return Math.max(1, n < 0 ? els.length : n);
79
+ };
80
+ const move = (step: "up" | "down" | "left" | "right" | "first" | "last") => {
81
+ const can = shown.flatMap((t, i) => (choosable(t) ? [i] : []));
82
+ if (!can.length) return;
83
+ const to = (i: number | undefined) => { if (i !== undefined) highlight(shown[i]!.key, "keys"); };
84
+ if (step === "first" || active < 0) return to(can[0]);
85
+ if (step === "last") return to(can[can.length - 1]);
86
+ if (step === "right") return to(can.find((i) => i > active));
87
+ if (step === "left") return to([...can].reverse().find((i) => i < active));
88
+ // A row up or down: the next row holding a choice, its tile nearest this column (a short last row, a row of uploads).
89
+ const cols = columns(), col = active % cols, dir = step === "down" ? 1 : -1;
90
+ for (let row = Math.floor(active / cols) + dir; row >= 0 && row * cols < shown.length; row += dir) {
91
+ const inRow = can.filter((i) => Math.floor(i / cols) === row);
92
+ if (inRow.length) return to(inRow.reduce((a, b) => (Math.abs((b % cols) - col) < Math.abs((a % cols) - col) ? b : a)));
93
+ }
94
+ };
95
+ const choose = (t: PickerTile | undefined, use: boolean) => {
96
+ if (!live || !choosable(t)) return;
97
+ if (use && onActivate) onActivate(t!.key); else onSelect(t!.key);
98
+ };
99
+ const clear = () => { search?.onChange(""); boxRef.current?.focus(); };
100
+ // As PickerList: `search.autoFocus`, the box takes the focus once, as the grid appears.
101
+ useEffect(() => { if (typesFirst(search)) boxRef.current?.focus(); }, []); // eslint-disable-line react-hooks/exhaustive-deps
102
+ const keyDown = (e: React.KeyboardEvent, fromBox: boolean) => {
103
+ if (e.nativeEvent.isComposing || e.keyCode === 229) return;
104
+ // A keystroke typed gives ← → back to the caret now, in this event: the effect on the query lands a render later, and the
105
+ // next key can come first.
106
+ if (fromBox && (e.key.length === 1 || e.key === "Backspace" || e.key === "Delete")) { if (stepping) setStepping(false); return; }
107
+ const grid = !fromBox || stepping;
108
+ const go = (step: Parameters<typeof move>[0]) => { e.preventDefault(); move(step); };
109
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") { if (fromBox) setStepping(true); go(e.key === "ArrowDown" ? "down" : "up"); }
110
+ else if (grid && e.key === "ArrowRight") go("right");
111
+ else if (grid && e.key === "ArrowLeft") go("left");
112
+ else if (grid && e.key === "Home") go("first");
113
+ else if (grid && e.key === "End") go("last");
114
+ else if (e.key === "Enter") { if (shown.length) e.preventDefault(); choose(shown[active], true); }
115
+ else if (!fromBox && e.key === " ") { e.preventDefault(); choose(shown[active], false); }
116
+ else if (fromBox && e.key === "Escape" && query) { e.preventDefault(); e.stopPropagation(); clear(); }
117
+ };
118
+ // The uploads in flight, said aloud from outside the grid (below).
119
+ const sending = tiles.filter((t) => t.status?.busy).map((t) => t.title);
120
+
121
+ const listId = `${base}-grid`;
122
+ const hasTiles = shown.length > 0;
123
+ const activeId = live && active >= 0 && shown[active] ? tileId(active) : undefined;
124
+
125
+ return (
126
+ <div className="gemboss-ei-pick">
127
+ {search ? <PickSearch search={search} boxRef={boxRef} listId={listId} hasList={hasTiles} activeId={activeId} onKeyDown={(e) => keyDown(e, true)} onClear={clear} /> : null}
128
+ {phase === "loading" || phase === "error" || !hasTiles ? (
129
+ <PickNothing phase={phase === "loading" ? "loading" : phase === "error" ? "error" : "empty"} error={error} empty={empty} query={query} onClear={clear}
130
+ skeleton={
131
+ <div className={`gemboss-ei-pickgrid${size === "icon" ? " is-icon" : ""}`} role="status" aria-label="Loading">
132
+ {Array.from({ length: loadingTiles }, (_, i) => (
133
+ <div key={i} className="gemboss-ei-pickgrid-skeleton" aria-hidden>
134
+ <span className="gemboss-ei-pickgrid-pic ui-skeleton__line" />
135
+ <span className="ui-skeleton__line" />
136
+ </div>
137
+ ))}
138
+ </div>
139
+ } />
140
+ ) : (
141
+ <>
142
+ <ul ref={gridRef} id={listId} className={`gemboss-ei-pickgrid${size === "icon" ? " is-icon" : ""}${live ? "" : " is-reloading"}`} role="listbox" aria-label={label}
143
+ aria-busy={live ? undefined : true} tabIndex={search ? -1 : 0} aria-activedescendant={search ? undefined : activeId}
144
+ onKeyDown={search ? undefined : (e) => keyDown(e, false)}>
145
+ {shown.map((t, i) => {
146
+ const chosen = t.key === selected;
147
+ const off = !live || !!t.status;
148
+ return (
149
+ <li key={t.key} id={tileId(i)} role="option" aria-selected={chosen} aria-disabled={off ? true : undefined} title={t.tooltip ?? t.title}
150
+ className={`gemboss-ei-pickgrid-tile${i === active ? " is-active" : ""}${t.status?.busy ? " is-busy" : ""}${t.status?.error ? " is-error" : ""}`} data-key={t.key}
151
+ onMouseDown={(e) => { if (search) e.preventDefault(); /* the search box keeps the focus */ }}
152
+ onMouseMove={() => { if (choosable(t) && i !== active) highlight(t.key, "pointer"); }}
153
+ onClick={() => choose(t, false)} onDoubleClick={() => choose(t, true)}>
154
+ {t.picture ? <span className="gemboss-ei-pickgrid-pic is-drawn" aria-hidden>{t.picture}</span>
155
+ : t.image ? <img className={`gemboss-ei-pickgrid-pic${t.fit === "contain" ? " is-whole" : ""}${t.checker ? " is-checker" : ""}`} src={t.image} alt="" loading="lazy" />
156
+ : <span className="gemboss-ei-pickgrid-pic" aria-hidden>{t.status?.error ? "!" : null}</span>}
157
+ <span className="gemboss-ei-pickgrid-name">{t.title}</span>
158
+ {t.status?.error || t.status?.busy || t.subtitle ? (
159
+ <span className="gemboss-ei-pickgrid-sub">
160
+ {t.status?.error ?? (t.status?.busy ? "Uploading…" : t.subtitle)}
161
+ </span>
162
+ ) : null}
163
+ {chosen ? <Icon name="check" size={16} className="gemboss-ei-pickgrid-check" /> : null}
164
+ </li>
165
+ );
166
+ })}
167
+ </ul>
168
+ </>
169
+ )}
170
+ {/* Said aloud from outside the grid (an option's children are presentational) and kept across its states: each failure once,
171
+ a log ADDS (one alert string with every failure read the first again with the second: review of #5325); the uploads in
172
+ flight as one line. */}
173
+ <div className="ui-sr-only" role="log" aria-live="assertive">
174
+ {tiles.filter((t) => t.status?.error).map((t) => <p key={t.key}>{`${t.title}: ${t.status!.error}`}</p>)}
175
+ </div>
176
+ <p className="ui-sr-only" role="status">{sending.length ? `Uploading ${sending.join(", ")}…` : ""}</p>
177
+ {/* After the grid, or after "no results" / an empty grid: the next page may hold what this one did not (the first page of a
178
+ store's Shopify files, all held already or none matching, kept Load more out of reach: review of #5325). */}
179
+ {more && (phase === "ready" || phase === "reloading") ? (
180
+ <div className="gemboss-ei-pick-more">
181
+ <button type="button" className="ui-btn" disabled={more.busy} onClick={more.onClick}>{more.busy ? "Loading…" : (more.label ?? "Show more")}</button>
182
+ </div>
183
+ ) : null}
184
+ </div>
185
+ );
186
+ }