@1agh/maude 1.8.1 → 1.9.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 (73) hide show
  1. package/apps/studio/acp/bridge.ts +14 -2
  2. package/apps/studio/acp/probe.ts +51 -1
  3. package/apps/studio/api.ts +19 -4
  4. package/apps/studio/bin/_curl-local.mjs +7 -0
  5. package/apps/studio/bin/annotate.mjs +16 -7
  6. package/apps/studio/bin/read-annotations.mjs +62 -4
  7. package/apps/studio/client/app.jsx +428 -15977
  8. package/apps/studio/client/dialogs/asset-picker.jsx +331 -0
  9. package/apps/studio/client/dialogs/command-palette.jsx +112 -0
  10. package/apps/studio/client/dialogs/export-dialog.jsx +782 -0
  11. package/apps/studio/client/dialogs/help-modal.jsx +324 -0
  12. package/apps/studio/client/dialogs/shortcuts-overlay.jsx +144 -0
  13. package/apps/studio/client/hooks/use-canvas-bridge.jsx +2150 -0
  14. package/apps/studio/client/hooks/use-git-actions.jsx +236 -0
  15. package/apps/studio/client/hooks/use-keyboard-shortcuts.jsx +297 -0
  16. package/apps/studio/client/hooks/use-palette-and-panels.jsx +474 -0
  17. package/apps/studio/client/hooks/use-photo-and-timeline.jsx +901 -0
  18. package/apps/studio/client/hooks/use-project-data.jsx +90 -0
  19. package/apps/studio/client/hooks/use-shell-core.jsx +1212 -0
  20. package/apps/studio/client/hooks/use-tabs.jsx +723 -0
  21. package/apps/studio/client/hooks/use-web-socket.jsx +13 -0
  22. package/apps/studio/client/inspector/artboard-knobs.jsx +456 -0
  23. package/apps/studio/client/inspector/color-picker.jsx +196 -0
  24. package/apps/studio/client/inspector/color.js +92 -0
  25. package/apps/studio/client/inspector/css-knobs.jsx +1720 -0
  26. package/apps/studio/client/inspector/css-vocab.jsx +131 -0
  27. package/apps/studio/client/inspector/ds-tokens.js +90 -0
  28. package/apps/studio/client/inspector/grid-tracks-editor.jsx +97 -0
  29. package/apps/studio/client/inspector/inspect-computed.jsx +68 -0
  30. package/apps/studio/client/inspector/inspector-panel.jsx +769 -0
  31. package/apps/studio/client/inspector/layers.jsx +322 -0
  32. package/apps/studio/client/inspector/selection.js +65 -0
  33. package/apps/studio/client/inspector/token-popover.jsx +301 -0
  34. package/apps/studio/client/menus/menubar.jsx +856 -0
  35. package/apps/studio/client/selection-scope.js +40 -0
  36. package/apps/studio/client/shell/banners.jsx +272 -0
  37. package/apps/studio/client/shell/collapsed-rail.jsx +23 -0
  38. package/apps/studio/client/shell/comments-panel.jsx +177 -0
  39. package/apps/studio/client/shell/constants.js +60 -0
  40. package/apps/studio/client/shell/dock.jsx +131 -0
  41. package/apps/studio/client/shell/icons.jsx +370 -0
  42. package/apps/studio/client/shell/status-bar.jsx +215 -0
  43. package/apps/studio/client/shell/util.js +332 -0
  44. package/apps/studio/client/shell/viewport.jsx +254 -0
  45. package/apps/studio/client/system/system-view.jsx +255 -0
  46. package/apps/studio/client/tree/tree.jsx +1243 -0
  47. package/apps/studio/comments-overlay.tsx +6 -4
  48. package/apps/studio/config.schema.json +5 -0
  49. package/apps/studio/context.ts +13 -0
  50. package/apps/studio/dist/client.bundle.js +1337 -1337
  51. package/apps/studio/dist/comment-mount.js +2 -2
  52. package/apps/studio/exporters/_browser-bundles.ts +21 -2
  53. package/apps/studio/exporters/jobs.ts +75 -15
  54. package/apps/studio/exporters/scope.ts +15 -12
  55. package/apps/studio/format.ts +296 -0
  56. package/apps/studio/http.ts +217 -23
  57. package/apps/studio/server.ts +141 -30
  58. package/apps/studio/sync/accepted-link.ts +6 -0
  59. package/apps/studio/sync/agent.ts +9 -1
  60. package/apps/studio/sync/cold-start-apply.ts +29 -4
  61. package/apps/studio/sync/cold-start.ts +78 -0
  62. package/apps/studio/sync/file-plane.ts +61 -1
  63. package/apps/studio/sync/format-sync.ts +160 -0
  64. package/apps/studio/sync/index.ts +134 -10
  65. package/apps/studio/sync/journal-client.ts +25 -5
  66. package/apps/studio/sync/migrate-seed.ts +8 -1
  67. package/apps/studio/sync/status.ts +2 -0
  68. package/apps/studio/sync/transaction-client.ts +130 -13
  69. package/apps/studio/ui-prefs.ts +95 -10
  70. package/apps/studio/whats-new.json +9 -0
  71. package/apps/studio/ws.ts +19 -4
  72. package/cli/bin/claude-design-server.mjs +0 -0
  73. package/package.json +10 -8
@@ -0,0 +1,322 @@
1
+ // inspector/layers.jsx — moved verbatim out of client/app.jsx (Maude v2 plan V2-0.2, move-only split).
2
+
3
+ import { useState } from 'react';
4
+ import { StIcon } from '../shell/icons.jsx';
5
+
6
+ // ---------- Inspector panel (display-only) ----------
7
+ //
8
+ // T6 (Plan C) — right-dock Inspect / Layers / CSS tabs per `.design/ui/Studio.tsx`
9
+ // InspectorPanel. DISPLAY-ONLY: reads the live `selected` payload from the
10
+ // inspector bridge (`bounds`, `tag`, `classes`, `dom_path`, `html`). The
11
+ // mockup's live-CSS-knob WRITEBACK is Phase 12 (needs a canvas-origin write
12
+ // bridge, DDR-054) — the CSS tab shows markup read-only + keeps that callout, so
13
+ // it never implies functionality it lacks (the exact reason DDR-096 deferred it).
14
+ // ---------- Layers tree row (Phase 12 Task 4) ----------
15
+ // Phase 12.3 (W3.1) — map a LayerNode `type` (classified in canvas-shell) to a
16
+ // type-distinct icon, matching the Studio.tsx layers design.
17
+ export const LAYER_TYPE_ICON = {
18
+ button: 'button',
19
+ heading: 'type',
20
+ text: 'type',
21
+ input: 'input',
22
+ form: 'input',
23
+ image: 'image',
24
+ link: 'link',
25
+ list: 'list',
26
+ nav: 'layers',
27
+ box: 'box',
28
+ // feature-4 T7 — synthetic group row (unstamped wrapper with stamped kids).
29
+ group: 'folder',
30
+ };
31
+
32
+ // Optimistic layers-tree reorder — move the node with `draggedId` relative to
33
+ // `refId` (before / after a sibling, or inside-end as a last child). Pure: clones
34
+ // the node array and returns a new one, so React re-renders. Ids are distinct
35
+ // here (repeated/list nodes can't be dragged), so first-match-by-id is safe.
36
+ // Returns the input unchanged if either node isn't found (the HMR rebuild will
37
+ // reconcile).
38
+ export function moveLayerNode(nodes, draggedId, refId, position) {
39
+ if (!Array.isArray(nodes) || draggedId === refId) return nodes;
40
+ const clone = JSON.parse(JSON.stringify(nodes));
41
+ let dragged = null;
42
+ const remove = (arr) => {
43
+ for (let i = 0; i < arr.length; i++) {
44
+ if (arr[i].id === draggedId) {
45
+ dragged = arr[i];
46
+ arr.splice(i, 1);
47
+ return true;
48
+ }
49
+ if (arr[i].children && remove(arr[i].children)) return true;
50
+ }
51
+ return false;
52
+ };
53
+ remove(clone);
54
+ if (!dragged) return nodes;
55
+ const insert = (arr) => {
56
+ for (let i = 0; i < arr.length; i++) {
57
+ if (arr[i].id === refId) {
58
+ if (position === 'inside-start' || position === 'inside-end') {
59
+ arr[i].children = arr[i].children || [];
60
+ if (position === 'inside-start') arr[i].children.unshift(dragged);
61
+ else arr[i].children.push(dragged);
62
+ } else {
63
+ arr.splice(position === 'before' ? i : i + 1, 0, dragged);
64
+ }
65
+ return true;
66
+ }
67
+ if (arr[i].children && insert(arr[i].children)) return true;
68
+ }
69
+ return false;
70
+ };
71
+ return insert(clone) ? clone : nodes;
72
+ }
73
+
74
+ // Void / self-closing tags can't hold children → not a nest target. Everything
75
+ // else (div, section, span, …) can be nested into (matches "drop into any div").
76
+ export const LAYER_VOID_TAGS = new Set([
77
+ 'img', 'input', 'br', 'hr', 'area', 'base', 'col', 'embed', 'link', 'meta',
78
+ 'param', 'source', 'track', 'wbr',
79
+ ]);
80
+
81
+ export function LayerRow({
82
+ node,
83
+ depth,
84
+ selectedId,
85
+ selectedIndex,
86
+ collapsed,
87
+ hiddenOverride,
88
+ onToggle,
89
+ onSelect,
90
+ onHover,
91
+ onToggleVisibility,
92
+ onReorder,
93
+ onRowPointerDown,
94
+ dragState,
95
+ // feature-4 T7a/b/c — component map (purple ◇/◆), locked keys + toggle,
96
+ // dblclick rename (writes data-dc-element via edit-attr).
97
+ componentMap,
98
+ lockedKeys,
99
+ onToggleLock,
100
+ onRename,
101
+ }) {
102
+ const key = `${node.id}:${node.index}`;
103
+ const hasKids = node.children && node.children.length > 0;
104
+ const isCollapsed = collapsed.has(key);
105
+ // feature-4 T7 — a synthetic group row (unstamped wrapper) is a pure
106
+ // structural stand-in: NOT selectable (no data-cd-id to address in source),
107
+ // NOT draggable, NO eye toggle. Clicking it just expands/collapses.
108
+ const isSynthetic = !!node.synthetic;
109
+ // feature-4 T7a — purple instance rows: this element renders through an
110
+ // instantiated component. `root` = the component's own frame root (◆).
111
+ const inst = !isSynthetic && componentMap ? componentMap[node.id] : null;
112
+ // feature-4 T7b — locked layers can't be selected/dragged on the canvas.
113
+ const isLocked = !isSynthetic && !!lockedKeys?.has(key);
114
+ // feature-4 T7c — inline rename (dblclick the label).
115
+ const [renaming, setRenaming] = useState(false);
116
+ const [renameDraft, setRenameDraft] = useState('');
117
+ // Match the specific INSTANCE (id + occurrence index), not every element that
118
+ // shares this source id — otherwise a `.map`ed element highlights all its
119
+ // clones at once. Fall back to id-only when the selection carries no index.
120
+ const isSel =
121
+ !isSynthetic &&
122
+ node.id === selectedId &&
123
+ (selectedIndex == null || node.index === selectedIndex);
124
+ const isHidden = hiddenOverride?.has(key) ? hiddenOverride.get(key) : !!node.hidden;
125
+ // A shared data-cd-id (reused component instance) IS reorderable now — the
126
+ // server maps the occurrence index to the parent <Component> usage — so these
127
+ // are no longer greyed/blocked. A `.map()`ed single-usage element still can't
128
+ // split; that move is refused server-side and reverts. A LOCKED row never
129
+ // drags (feature-4 T7b).
130
+ const canDrag = !!onReorder && !isSynthetic && !isLocked;
131
+ const commitRename = () => {
132
+ setRenaming(false);
133
+ const v = renameDraft
134
+ .trim()
135
+ .toLowerCase()
136
+ .replace(/\s+/g, '-')
137
+ .replace(/[^a-z0-9-]/g, '');
138
+ if (!v || v === (node.dcElement ?? '')) return;
139
+ onRename?.(node, v);
140
+ };
141
+ // Phase 12.1 — the row being dragged FLOATS with the cursor (same model as the
142
+ // in-canvas drag): a transform follows the pointer, its layout box stays
143
+ // reserved (empty slot at the origin), and pointer-events:none lets the row
144
+ // under the pointer be hit-tested. A blue divider (rendered by the tree) marks
145
+ // where it drops — indented to show the depth it will nest at (Figma-style).
146
+ const isDragging = dragState?.key === key;
147
+ const dragStyle = isDragging
148
+ ? {
149
+ transform: `translate(${dragState.dx}px, ${dragState.dy}px)`,
150
+ opacity: 0.9,
151
+ zIndex: 20,
152
+ position: 'relative',
153
+ pointerEvents: 'none',
154
+ cursor: 'grabbing',
155
+ boxShadow: '0 6px 18px rgba(0, 0, 0, 0.28)',
156
+ }
157
+ : null;
158
+ return (
159
+ <>
160
+ <div
161
+ className={
162
+ 'st-layer st-layer--row' +
163
+ (isSel ? ' is-sel' : '') +
164
+ (isHidden ? ' is-hidden' : '') +
165
+ (isSynthetic ? ' is-group' : '') +
166
+ (inst ? ' is-instance' : '') +
167
+ (isLocked ? ' is-locked' : '')
168
+ }
169
+ style={{ paddingLeft: 6 + depth * 14, ...dragStyle }}
170
+ role="treeitem"
171
+ aria-selected={isSynthetic ? undefined : isSel}
172
+ aria-expanded={hasKids ? !isCollapsed : undefined}
173
+ aria-grabbed={canDrag ? isDragging : undefined}
174
+ tabIndex={0}
175
+ title={
176
+ isSynthetic
177
+ ? `${node.tag} · group (unstamped wrapper)`
178
+ : `${node.tag} · ${node.type}${onRename ? ' · F2 to rename' : ''}`
179
+ }
180
+ data-layer-key={key}
181
+ onClick={() => (isSynthetic ? hasKids && onToggle(key) : onSelect(node))}
182
+ onMouseEnter={() => !isSynthetic && onHover(node)}
183
+ onMouseLeave={() => onHover(null)}
184
+ onPointerDown={canDrag ? (e) => onRowPointerDown(e, node, key) : undefined}
185
+ onKeyDown={(e) => {
186
+ // Enter/Space select (or, for a synthetic group, toggle); ↑/↓ (+
187
+ // modifiers) are handled at the tree container (selection-driven —
188
+ // survives the HMR re-render).
189
+ if (e.key === 'Enter' || e.key === ' ') {
190
+ e.preventDefault();
191
+ if (isSynthetic) hasKids && onToggle(key);
192
+ else onSelect(node);
193
+ } else if (e.key === 'F2' && onRename && !isSynthetic) {
194
+ // a11y fix (review fan-out, 2026-07-21) — dblclick was the ONLY
195
+ // entry point into rename, a keyboard-only user had no way to
196
+ // reach it at all (WCAG 2.1.1). F2 is the conventional rename key
197
+ // (Explorer/Finder/most tree UIs); mirrors the dblclick handler's
198
+ // own pre-fill.
199
+ e.preventDefault();
200
+ setRenameDraft(node.dcElement || node.label || '');
201
+ setRenaming(true);
202
+ }
203
+ }}
204
+ >
205
+ {hasKids ? (
206
+ <button
207
+ type="button"
208
+ className="st-layer-caret"
209
+ aria-label={isCollapsed ? 'Expand' : 'Collapse'}
210
+ onClick={(e) => {
211
+ e.stopPropagation();
212
+ onToggle(key);
213
+ }}
214
+ >
215
+ {isCollapsed ? '▸' : '▾'}
216
+ </button>
217
+ ) : (
218
+ <span className="st-layer-caret" aria-hidden="true" />
219
+ )}
220
+ {inst ? (
221
+ // feature-4 T7a — Figma vocabulary: ◆ the component's own frame root,
222
+ // ◇ an inner member of an instance. Purple via .is-instance CSS.
223
+ <span className="st-layer-inst-glyph" aria-hidden="true">
224
+ {inst.root ? '◆' : '◇'}
225
+ </span>
226
+ ) : (
227
+ <StIcon name={LAYER_TYPE_ICON[node.type] || 'box'} size={12} className="st-layer-ticon" />
228
+ )}
229
+ {renaming ? (
230
+ <input
231
+ className="st-layer-rename"
232
+ value={renameDraft}
233
+ autoFocus
234
+ aria-label={`Rename ${node.label}`}
235
+ onFocus={(e) => e.target.select()}
236
+ onChange={(e) => setRenameDraft(e.target.value)}
237
+ onClick={(e) => e.stopPropagation()}
238
+ onPointerDown={(e) => e.stopPropagation()}
239
+ onBlur={commitRename}
240
+ onKeyDown={(e) => {
241
+ e.stopPropagation();
242
+ if (e.key === 'Enter') commitRename();
243
+ else if (e.key === 'Escape') setRenaming(false);
244
+ }}
245
+ />
246
+ ) : (
247
+ <span
248
+ className="st-layer-label"
249
+ onDoubleClick={
250
+ onRename && !isSynthetic
251
+ ? (e) => {
252
+ // feature-4 T7c — dblclick rename. Pre-fill from the raw
253
+ // data-dc-element (kebab) when set, else the display label.
254
+ e.stopPropagation();
255
+ setRenameDraft(node.dcElement || node.label || '');
256
+ setRenaming(true);
257
+ }
258
+ : undefined
259
+ }
260
+ >
261
+ {node.label}
262
+ </span>
263
+ )}
264
+ <span className="st-layer-type">{inst ? inst.component : node.type}</span>
265
+ {onToggleLock && !isSynthetic ? (
266
+ <button
267
+ type="button"
268
+ className="st-layer-lock"
269
+ aria-label={isLocked ? `Unlock ${node.label}` : `Lock ${node.label}`}
270
+ aria-pressed={isLocked}
271
+ title={isLocked ? 'Unlock' : 'Lock'}
272
+ onClick={(e) => {
273
+ e.stopPropagation();
274
+ onToggleLock(key);
275
+ }}
276
+ >
277
+ <StIcon name={isLocked ? 'lock' : 'unlock'} size={12} />
278
+ </button>
279
+ ) : null}
280
+ {onToggleVisibility && !isSynthetic ? (
281
+ <button
282
+ type="button"
283
+ className="st-layer-eye"
284
+ aria-label={isHidden ? `Show ${node.label}` : `Hide ${node.label}`}
285
+ aria-pressed={isHidden}
286
+ title={isHidden ? 'Show' : 'Hide'}
287
+ onClick={(e) => {
288
+ e.stopPropagation();
289
+ onToggleVisibility(node);
290
+ }}
291
+ >
292
+ <StIcon name={isHidden ? 'eye-off' : 'eye'} size={13} />
293
+ </button>
294
+ ) : null}
295
+ </div>
296
+ {hasKids && !isCollapsed
297
+ ? node.children.map((c, ci) => (
298
+ <LayerRow
299
+ key={`${c.id}:${c.index}`}
300
+ node={c}
301
+ depth={depth + 1}
302
+ selectedId={selectedId}
303
+ selectedIndex={selectedIndex}
304
+ collapsed={collapsed}
305
+ hiddenOverride={hiddenOverride}
306
+ onToggle={onToggle}
307
+ onSelect={onSelect}
308
+ onHover={onHover}
309
+ onToggleVisibility={onToggleVisibility}
310
+ onReorder={onReorder}
311
+ onRowPointerDown={onRowPointerDown}
312
+ dragState={dragState}
313
+ componentMap={componentMap}
314
+ lockedKeys={lockedKeys}
315
+ onToggleLock={onToggleLock}
316
+ onRename={onRename}
317
+ />
318
+ ))
319
+ : null}
320
+ </>
321
+ );
322
+ }
@@ -0,0 +1,65 @@
1
+ // inspector/selection.js — moved verbatim out of client/app.jsx (Maude v2 plan V2-0.2, move-only split).
2
+
3
+ // Phase 12.2/12.3 — the WS `selected` echo is the server's projection
4
+ // (SelectedElement) and LACKS the client-only DOM fields the CSS knobs pre-fill
5
+ // from (`authored` / `computed` inline style + `customStyles` / `attrs` — all
6
+ // captured in the iframe, never round-tripped through the server). When the echo
7
+ // is for the SAME element we already hold locally, preserve those fields instead
8
+ // of clobbering them to empty (else the server round-trip wipes the custom-CSS /
9
+ // custom-attr rows + computed readout right after selection).
10
+ // feature-photo-editor — `photoKind`/`photoAsset` (dom-selection.ts) are the SAME
11
+ // class of client-only DOM-derived field and belong in this list for the same
12
+ // reason: without it, every server-pushed `selected`/`snapshot` restore (a canvas
13
+ // switch, a reconnect, the persisted `_active.json` on boot — none of which carry
14
+ // these fields) silently drops the Inspector's Photo tab until the next fresh
15
+ // click re-derives it live — the "tab is there, then it's gone" flicker.
16
+ export function mergeSelClientFields(incoming, prev) {
17
+ if (!incoming || Array.isArray(incoming) || Array.isArray(prev) || !prev) return incoming;
18
+ // Dogfood follow-up (print artboards) — a whole-ARTBOARD selection has NO
19
+ // data-cd-id (the frame chrome carries only data-dc-screen), so the id
20
+ // identity check below never matched it and every server echo returned
21
+ // `incoming` bare — wiping `attrs` (which carries data-dc-kind/-print for
22
+ // the ArtboardKnobs panel) seconds after each fresh click. The panel then
23
+ // silently fell back to kind='digital' + screen presets even though the
24
+ // artboard was print. Match an id-less pair by the artboard-shaped
25
+ // SELECTOR + file — NOT by artboardId: the server projection
26
+ // (inspect.ts `enrich()`) doesn't round-trip `artboardId` at all, so an
27
+ // artboardId comparison always sees undefined on the echo side and never
28
+ // matches (the second-round bug on this exact spot). The selector IS the
29
+ // identity here — `[data-dc-screen="<id>"]` — and enrich() preserves it.
30
+ if (!incoming.id && !prev.id) {
31
+ const isArtboardSel = (s) =>
32
+ typeof s.selector === 'string' && s.selector.startsWith('[data-dc-screen=');
33
+ if (
34
+ isArtboardSel(incoming) &&
35
+ isArtboardSel(prev) &&
36
+ incoming.selector === prev.selector &&
37
+ incoming.file === prev.file
38
+ ) {
39
+ return {
40
+ ...incoming,
41
+ authored: incoming.authored ?? prev.authored,
42
+ computed: incoming.computed ?? prev.computed,
43
+ customStyles: incoming.customStyles ?? prev.customStyles,
44
+ attrs: incoming.attrs ?? prev.attrs,
45
+ // enrich() drops artboardId/worldW/worldH from the echo entirely —
46
+ // restore them from the local snapshot so ArtboardKnobs keeps its
47
+ // exact W/H and the resize/kind writers keep their target id.
48
+ artboardId: incoming.artboardId ?? prev.artboardId,
49
+ worldW: incoming.worldW ?? prev.worldW,
50
+ worldH: incoming.worldH ?? prev.worldH,
51
+ };
52
+ }
53
+ return incoming;
54
+ }
55
+ if (!incoming.id || incoming.id !== prev.id) return incoming;
56
+ return {
57
+ ...incoming,
58
+ authored: incoming.authored ?? prev.authored,
59
+ computed: incoming.computed ?? prev.computed,
60
+ customStyles: incoming.customStyles ?? prev.customStyles,
61
+ attrs: incoming.attrs ?? prev.attrs,
62
+ photoKind: incoming.photoKind ?? prev.photoKind,
63
+ photoAsset: incoming.photoAsset ?? prev.photoAsset,
64
+ };
65
+ }
@@ -0,0 +1,301 @@
1
+ // inspector/token-popover.jsx — moved verbatim out of client/app.jsx (Maude v2 plan V2-0.2, move-only split).
2
+
3
+ import { useEffect, useRef, useState } from 'react';
4
+ import { StIcon } from '../shell/icons.jsx';
5
+ import { createPortal } from 'react-dom';
6
+ import { ColorPicker } from './color-picker.jsx';
7
+ import { cssColorToHex } from './color.js';
8
+
9
+ // Phase 12.3 (W2.1) — token picker as a Figma-style popover instead of a native
10
+ // <select>. `kind='color'` renders a swatch grid (resolved DS color values);
11
+ // `kind='value'` a variable list (pretty name + resolved value, à la Figma's
12
+ // variable picker). Picking commits `var(--token)`. Portals to <body> +
13
+ // fixed-positions from the trigger rect so the panel's overflow never clips it.
14
+ export function TokenPopover({ kind, groups, current, onPick, label, swatchBg, seedHex, activeDs, swatchClassName }) {
15
+ const [open, setOpen] = useState(false);
16
+ const [pos, setPos] = useState(null);
17
+ // Phase 12.3 (#4) — colour popover gets two tabs: a normal colour input
18
+ // (Custom) + the DS variables swatch list (Variables). Token-able non-colour
19
+ // popovers stay single-mode.
20
+ const [mode, setMode] = useState('custom');
21
+ const [query, setQuery] = useState('');
22
+ const btnRef = useRef(null);
23
+ const popRef = useRef(null);
24
+ const bound = typeof current === 'string' && /var\(\s*--/.test(current);
25
+ const isOn = (n) => current === `var(${n})`;
26
+ const pretty = (n) => n.replace(/^--/, '').replace(/-/g, ' ');
27
+ const gs = groups || [];
28
+ const total = gs.reduce((s, g) => s + (g.names?.length || 0), 0);
29
+ const showDsHeaders = gs.length > 1; // group by DS only when there's >1
30
+ // Search filter over the token name + resolved value, per group.
31
+ const q = query.trim().toLowerCase();
32
+ const filteredGs = !q
33
+ ? gs
34
+ : gs
35
+ .map((g) => ({
36
+ ...g,
37
+ names: (g.names || []).filter(
38
+ (n) =>
39
+ pretty(n).toLowerCase().includes(q) ||
40
+ n.toLowerCase().includes(q) ||
41
+ (g.vals?.[n] || '').toLowerCase().includes(q)
42
+ ),
43
+ }))
44
+ .filter((g) => g.names.length);
45
+
46
+ useEffect(() => {
47
+ if (!open) {
48
+ setQuery('');
49
+ return undefined;
50
+ }
51
+ const place = () => {
52
+ const r = btnRef.current?.getBoundingClientRect();
53
+ if (!r) return;
54
+ const W = 224;
55
+ const MAXH = 300;
56
+ let left = Math.min(r.right - W, window.innerWidth - W - 8);
57
+ if (left < 8) left = 8;
58
+ const below = window.innerHeight - r.bottom;
59
+ const top = below > MAXH + 8 ? r.bottom + 4 : Math.max(8, r.top - MAXH - 4);
60
+ setPos({ left, top, width: W, maxHeight: MAXH });
61
+ };
62
+ place();
63
+ const onDoc = (e) => {
64
+ if (popRef.current?.contains(e.target) || btnRef.current?.contains(e.target)) return;
65
+ setOpen(false);
66
+ };
67
+ const onKey = (e) => {
68
+ if (e.key === 'Escape') setOpen(false);
69
+ };
70
+ // Task 6 (feature-inspector-controls-redesign) — RE-ANCHOR on scroll/resize
71
+ // instead of dismissing. `place()` computes viewport-relative coordinates
72
+ // from `getBoundingClientRect()`, but this fixed-positioned popover's actual
73
+ // containing block is whichever ANCESTOR (if any) has a transform/filter/
74
+ // will-change — e.g. the right panel's mount-in `st-panel-in` transform —
75
+ // not necessarily the viewport. Re-running place() keeps it glued to the
76
+ // trigger through any layout change instead of vanishing on the first
77
+ // scroll (the old dismiss-on-scroll workaround for the same root cause).
78
+ const onScroll = (e) => {
79
+ if (popRef.current?.contains(e.target)) return;
80
+ place();
81
+ };
82
+ document.addEventListener('pointerdown', onDoc, true);
83
+ document.addEventListener('keydown', onKey);
84
+ window.addEventListener('resize', place);
85
+ document.addEventListener('scroll', onScroll, true);
86
+ return () => {
87
+ document.removeEventListener('pointerdown', onDoc, true);
88
+ document.removeEventListener('keydown', onKey);
89
+ window.removeEventListener('resize', place);
90
+ document.removeEventListener('scroll', onScroll, true);
91
+ };
92
+ }, [open]);
93
+
94
+ // Transform-ancestor compensation — regardless of WHICH ancestor ends up
95
+ // establishing this fixed popover's containing block, measure where it
96
+ // actually landed vs where `place()` intended (viewport-relative) and cancel
97
+ // out the delta. This is correct independent of the cause, so it doesn't
98
+ // require hunting down every transform/filter/will-change that could ever
99
+ // apply between `document.body` (the portal target) and this element.
100
+ // Converges in at most one correction: once the delta is compensated, the
101
+ // measured rect matches the intended position and the effect is a no-op.
102
+ useEffect(() => {
103
+ if (!open || !pos || !popRef.current) return;
104
+ const r = popRef.current.getBoundingClientRect();
105
+ const dx = pos.left - r.left;
106
+ const dy = pos.top - r.top;
107
+ if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) {
108
+ setPos((p) => (p ? { ...p, left: p.left + dx, top: p.top + dy } : p));
109
+ }
110
+ }, [open, pos]);
111
+
112
+ // Pick a token. #3 — apply CORRECTLY across design systems: a token from the
113
+ // canvas's OWN active DS commits `var(--token)` (round-trips + resolves right);
114
+ // a token from ANOTHER DS commits its RESOLVED value (literal), because
115
+ // `var(--token)` would resolve against the canvas's DS scope and paint the WRONG
116
+ // colour. So what you click is always what's applied ("natvrdo").
117
+ // SECURITY (ethical-hacker A3) — a cross-DS token value is committed as a
118
+ // LITERAL, and its source is a (possibly hub-pushed, untrusted) tokens CSS.
119
+ // A colour-shaped value can still smuggle a fetch primitive (e.g.
120
+ // `rgb(1 2 3) url(//x)` passes the colour sniff). Refuse to write a literal
121
+ // carrying url()/image-set()/expression()/@import — fall back to var(), which
122
+ // resolves against the CANVAS's own DS (never the attacker's value).
123
+ const UNSAFE_TOKEN_VALUE = /url\(|image-set\(|cross-fade\(|element\(|expression\(|@import|javascript:/i;
124
+ const pickFrom = (ds, n, resolved) => {
125
+ if (activeDs && ds && ds !== activeDs && resolved && !UNSAFE_TOKEN_VALUE.test(resolved)) {
126
+ onPick(resolved);
127
+ } else {
128
+ onPick(`var(${n})`);
129
+ }
130
+ setOpen(false);
131
+ };
132
+ // Custom colour / hex applies LIVE without closing, so the user can keep
133
+ // tweaking; the popover dismisses on outside-click / Esc like everything else.
134
+ const applyRaw = (v) => {
135
+ const val = (v || '').trim();
136
+ if (val) onPick(val);
137
+ };
138
+ // A search field over the token list (name + value). Auto-focuses so the user
139
+ // can type straight away.
140
+ const searchBar = (
141
+ <div className="st-cp-pop-search">
142
+ <StIcon name="search" size={12} />
143
+ <input
144
+ value={query}
145
+ onChange={(e) => setQuery(e.target.value)}
146
+ placeholder="Search variables"
147
+ aria-label="search variables"
148
+ // biome-ignore lint/a11y/noAutofocus: focusing the search on open is the intent.
149
+ autoFocus
150
+ />
151
+ </div>
152
+ );
153
+ // #2 — colour Variables as a scannable LIST (swatch · name · value), per DS.
154
+ const swatchList = (grps) =>
155
+ grps.map((g) => (
156
+ <div className="st-cp-pop-group" key={g.ds}>
157
+ {showDsHeaders ? <div className="st-cp-pop-ds">{g.ds}</div> : null}
158
+ <div className="st-cp-pop-list">
159
+ {g.names.map((n) => (
160
+ <button
161
+ key={`${g.ds}:${n}`}
162
+ type="button"
163
+ className={`st-cp-pop-row st-cp-pop-crow${isOn(n) ? ' is-on' : ''}`}
164
+ onClick={() => pickFrom(g.ds, n, g.vals?.[n])}
165
+ >
166
+ <span
167
+ className="st-cp-pop-cswatch"
168
+ style={{ background: g.vals?.[n] || 'transparent' }}
169
+ aria-hidden="true"
170
+ />
171
+ <span className="st-cp-pop-name">{pretty(n)}</span>
172
+ <span className="st-cp-pop-val">{g.vals?.[n] || ''}</span>
173
+ </button>
174
+ ))}
175
+ </div>
176
+ </div>
177
+ ));
178
+ // The value-token list (non-colour), per DS.
179
+ const valueList = (grps) =>
180
+ grps.map((g) => (
181
+ <div className="st-cp-pop-group" key={g.ds}>
182
+ {showDsHeaders ? <div className="st-cp-pop-ds">{g.ds}</div> : null}
183
+ <div className="st-cp-pop-list">
184
+ {g.names.map((n) => (
185
+ <button
186
+ key={`${g.ds}:${n}`}
187
+ type="button"
188
+ className={`st-cp-pop-row${isOn(n) ? ' is-on' : ''}`}
189
+ onClick={() => pickFrom(g.ds, n, g.vals?.[n])}
190
+ >
191
+ <span className="st-cp-pop-name">{pretty(n)}</span>
192
+ <span className="st-cp-pop-val">{g.vals?.[n] || ''}</span>
193
+ </button>
194
+ ))}
195
+ </div>
196
+ </div>
197
+ ));
198
+ const noMatch = <div className="st-cp-pop-empty">No match</div>;
199
+
200
+ return (
201
+ <>
202
+ {swatchBg !== undefined ? (
203
+ // Colour rows: the swatch IS the trigger — one popover, no separate native
204
+ // OS picker + ◇ (the "two popovers" the user flagged). Shows the current
205
+ // colour; bound-to-token gets the accent ring.
206
+ <button
207
+ type="button"
208
+ ref={btnRef}
209
+ className={`${swatchClassName || 'st-cp-swatch st-cp-swatch--mini st-cp-swatch--trigger'}${bound && !swatchClassName ? ' is-bound' : ''}`}
210
+ aria-haspopup="dialog"
211
+ aria-expanded={open}
212
+ aria-label={label || 'pick a colour'}
213
+ title={current || 'pick a colour'}
214
+ onClick={() => setOpen((v) => !v)}
215
+ >
216
+ <span style={{ position: 'absolute', inset: 0, background: swatchBg || 'transparent' }} />
217
+ </button>
218
+ ) : (
219
+ <button
220
+ type="button"
221
+ ref={btnRef}
222
+ className={`st-cp-tokbtn${bound ? ' is-bound' : ''}`}
223
+ aria-haspopup="dialog"
224
+ aria-expanded={open}
225
+ aria-label={label || 'pick a design token'}
226
+ title="design tokens"
227
+ onClick={() => setOpen((v) => !v)}
228
+ >
229
+ <span className="st-cp-tokbtn-glyph" aria-hidden="true" />
230
+ </button>
231
+ )}
232
+ {open && pos
233
+ ? createPortal(
234
+ <div
235
+ ref={popRef}
236
+ // Portalled to <body> (outside the App's `.maude` div), so it must
237
+ // re-establish the maude token scope itself — otherwise var(--bg-*)
238
+ // resolves to the legacy :root project palette (the cream popover bug).
239
+ className="maude st-cp-pop"
240
+ data-theme={
241
+ (typeof document !== 'undefined' &&
242
+ document.documentElement.getAttribute('data-theme')) ||
243
+ 'dark'
244
+ }
245
+ role="dialog"
246
+ aria-label={label || 'design tokens'}
247
+ style={{
248
+ left: pos.left,
249
+ top: pos.top,
250
+ width: pos.width,
251
+ maxHeight: pos.maxHeight,
252
+ }}
253
+ >
254
+ {kind === 'color' ? (
255
+ <>
256
+ <div className="st-cp-poptabs" role="tablist">
257
+ <button
258
+ type="button"
259
+ role="tab"
260
+ aria-selected={mode === 'custom'}
261
+ className={`st-cp-poptab${mode === 'custom' ? ' is-active' : ''}`}
262
+ onClick={() => setMode('custom')}
263
+ >
264
+ Custom
265
+ </button>
266
+ <button
267
+ type="button"
268
+ role="tab"
269
+ aria-selected={mode === 'vars'}
270
+ className={`st-cp-poptab${mode === 'vars' ? ' is-active' : ''}`}
271
+ onClick={() => setMode('vars')}
272
+ >
273
+ Variables
274
+ </button>
275
+ </div>
276
+ {mode === 'custom' ? (
277
+ <ColorPicker seed={seedHex || cssColorToHex(current) || '#000000'} onApply={applyRaw} />
278
+ ) : !total ? (
279
+ <div className="st-cp-pop-empty">No color tokens</div>
280
+ ) : (
281
+ <>
282
+ {searchBar}
283
+ {filteredGs.length ? swatchList(filteredGs) : noMatch}
284
+ </>
285
+ )}
286
+ </>
287
+ ) : !total ? (
288
+ <div className="st-cp-pop-empty">No tokens for this property</div>
289
+ ) : (
290
+ <>
291
+ {searchBar}
292
+ {filteredGs.length ? valueList(filteredGs) : noMatch}
293
+ </>
294
+ )}
295
+ </div>,
296
+ document.body
297
+ )
298
+ : null}
299
+ </>
300
+ );
301
+ }