@behavioral-agentic-design-system/core 0.42.0 → 0.45.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.
Files changed (104) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +25 -9
  3. package/scripts/a11y-lint.cjs +25 -1
  4. package/scripts/check-spec.mjs +73 -0
  5. package/scripts/deal-directions.mjs +186 -0
  6. package/scripts/health-report.mjs +20 -14
  7. package/scripts/lib/counted-lint.mjs +100 -0
  8. package/scripts/lib/marketing-library.mjs +129 -0
  9. package/scripts/lib/on-system.mjs +249 -0
  10. package/scripts/lib/random.mjs +22 -0
  11. package/scripts/lib/spec-parse.d.mts +25 -0
  12. package/scripts/lib/spec-parse.mjs +188 -0
  13. package/scripts/lib/tells.mjs +128 -0
  14. package/scripts/lint-css-vars.mjs +175 -0
  15. package/scripts/lint-html-nesting.mjs +116 -0
  16. package/scripts/lint-live-ctas.mjs +138 -0
  17. package/scripts/on-system-score.mjs +95 -0
  18. package/scripts/slop-rules.mjs +1 -1
  19. package/scripts/source-images.mjs +180 -0
  20. package/scripts/ux-tells.mjs +78 -0
  21. package/src/api/brand-colors.ts +3 -0
  22. package/src/api/brand-fonts.ts +3 -0
  23. package/src/api/brand-mark.ts +6 -1
  24. package/src/api/dev-write-guard.ts +53 -0
  25. package/src/api/layers/file.ts +7 -4
  26. package/src/api/onboarding-extract.ts +85 -30
  27. package/src/api/onboarding.ts +3 -0
  28. package/src/api/save-tokens.ts +3 -0
  29. package/src/app/layout.tsx +6 -0
  30. package/src/app/preview/canvas/page.tsx +12 -0
  31. package/src/app/preview/components/page.tsx +734 -0
  32. package/src/app/preview/studio/blank-screen.tsx +143 -0
  33. package/src/app/preview/studio/page.tsx +7 -0
  34. package/src/app/shell.tsx +160 -44
  35. package/src/components/canvas/canvas.tsx +458 -0
  36. package/src/components/canvas/layout.ts +72 -0
  37. package/src/components/canvas/parse-canvas.ts +32 -0
  38. package/src/components/canvas/sample.ts +90 -0
  39. package/src/components/canvas/spec-frame.tsx +43 -0
  40. package/src/components/canvas/types.ts +33 -0
  41. package/src/components/docs-tab.tsx +7 -7
  42. package/src/components/home-recent.tsx +73 -0
  43. package/src/components/home-tab.tsx +13 -13
  44. package/src/components/layers-tab.tsx +2 -2
  45. package/src/components/markdown-preview.tsx +60 -12
  46. package/src/components/studio/control-panel.tsx +299 -0
  47. package/src/components/studio/control-row.tsx +77 -0
  48. package/src/components/studio/preview-frame.tsx +165 -0
  49. package/src/components/studio/preview-pane.tsx +247 -0
  50. package/src/components/studio/studio.tsx +133 -128
  51. package/src/components/studio/types.ts +218 -0
  52. package/src/components/studio/use-studio-tweaks.ts +128 -0
  53. package/src/components/studio/use-studio-view-state.ts +72 -0
  54. package/src/components/ui/autocomplete.tsx +1 -1
  55. package/src/components/ui/color-picker.tsx +20 -4
  56. package/src/components/ui/data-table.tsx +64 -3
  57. package/src/components/ui/date-field.tsx +1 -1
  58. package/src/components/ui/editable.tsx +1 -0
  59. package/src/components/ui/faceted-filter.tsx +187 -0
  60. package/src/components/ui/gauge-chart.tsx +18 -4
  61. package/src/components/ui/inline-edit.tsx +175 -0
  62. package/src/components/ui/month-picker.tsx +1 -1
  63. package/src/components/ui/number-input.tsx +28 -5
  64. package/src/components/ui/otp-input.tsx +208 -0
  65. package/src/components/ui/phone-input.tsx +274 -0
  66. package/src/components/ui/search-input.tsx +1 -1
  67. package/src/components/ui/tags-input.tsx +1 -1
  68. package/src/components/ui/timer.tsx +1 -0
  69. package/src/components/ui/transfer-list.tsx +13 -26
  70. package/src/components/ui/week-picker.tsx +1 -1
  71. package/src/components/ui/year-picker.tsx +1 -1
  72. package/src/data/component-added.json +958 -0
  73. package/src/data/docs-index.ts +13 -1
  74. package/src/hooks/use-global-mono-font.ts +1 -0
  75. package/src/hooks/use-global-primary-color.ts +1 -0
  76. package/src/hooks/use-global-sans-font.ts +1 -0
  77. package/src/hooks/use-global-serif-font.ts +1 -0
  78. package/src/hooks/use-global-type-scale.ts +17 -2
  79. package/src/hooks/use-mobile.ts +2 -0
  80. package/src/hooks/use-sync-type-scale.ts +7 -11
  81. package/src/lib/spec-parse.ts +4 -0
  82. package/src/lib/svg-sanitize.ts +19 -9
  83. package/src/stories/Autocomplete.stories.tsx +2 -0
  84. package/src/stories/Canvas.stories.tsx +45 -0
  85. package/src/stories/ColorPicker.stories.tsx +40 -0
  86. package/src/stories/DataTable.stories.tsx +30 -0
  87. package/src/stories/DateField.stories.tsx +21 -0
  88. package/src/stories/Editable.stories.tsx +2 -0
  89. package/src/stories/FacetedFilter.stories.tsx +197 -0
  90. package/src/stories/GaugeChart.stories.tsx +9 -3
  91. package/src/stories/InlineEdit.stories.tsx +106 -0
  92. package/src/stories/MarkdownPreview.stories.tsx +53 -0
  93. package/src/stories/MonthPicker.stories.tsx +21 -0
  94. package/src/stories/NumberInput.stories.tsx +25 -0
  95. package/src/stories/OtpInput.stories.tsx +110 -0
  96. package/src/stories/PhoneInput.stories.tsx +127 -0
  97. package/src/stories/SearchInput.stories.tsx +2 -0
  98. package/src/stories/TagsInput.stories.tsx +2 -0
  99. package/src/stories/Timer.stories.tsx +26 -0
  100. package/src/stories/TransferList.stories.tsx +4 -0
  101. package/src/stories/WeekPicker.stories.tsx +21 -0
  102. package/src/stories/YearPicker.stories.tsx +21 -0
  103. package/src/stories/story-groups.json +22 -16
  104. package/src/tokens.json +82 -54
@@ -0,0 +1,458 @@
1
+ "use client";
2
+
3
+ import "@xyflow/react/dist/base.css";
4
+ import {
5
+ createContext,
6
+ useCallback,
7
+ useContext,
8
+ useEffect,
9
+ useMemo,
10
+ useRef,
11
+ useState,
12
+ } from "react";
13
+ import {
14
+ Background,
15
+ getViewportForBounds,
16
+ Panel,
17
+ ReactFlow,
18
+ ReactFlowProvider,
19
+ useReactFlow,
20
+ useStore,
21
+ type Node,
22
+ type NodeProps,
23
+ } from "@xyflow/react";
24
+ import { ExternalLink, Maximize, Minus, Plus } from "lucide-react";
25
+ import { Button } from "../ui/button";
26
+ import { Card } from "../ui/card";
27
+ import { cn } from "../../lib/utils";
28
+ import { parseFrontMatter } from "../../lib/spec-parse";
29
+ import { MAX_ZOOM, MIN_ZOOM, placeFrames, type PlacedFrame, type Rect } from "./layout";
30
+ import { OUTLINE_ZOOM, SpecFrame } from "./spec-frame";
31
+ import type { CanvasDoc } from "./types";
32
+
33
+ const PAN_STEP = 80;
34
+ const ICON = { strokeWidth: 1.5 } as const;
35
+ const FIT_PADDING = "6%";
36
+
37
+ export interface CanvasProps {
38
+ doc: CanvasDoc;
39
+ /** Markdown sources for doc frames, keyed by the frame's `src`. */
40
+ docs?: Record<string, string>;
41
+ /** Maps a view name to the URL its live frame loads. Default: `/${view}`. */
42
+ resolveView?: (view: string) => string;
43
+ /** Where the full-width Spec reading view lives. Shows a pop-out link when set. */
44
+ specHref?: string;
45
+ /** View name to focus on first paint. */
46
+ initialFrame?: string;
47
+ className?: string;
48
+ }
49
+
50
+ // What the frame nodes need from the canvas. React Flow renders nodes from a stable
51
+ // `nodeTypes` map, so per-canvas values travel through context instead of props.
52
+ interface CanvasContextValue {
53
+ docs: Record<string, string>;
54
+ resolveView: (view: string) => string;
55
+ hasDoc: boolean;
56
+ /** The live frame the reader is interacting with. Others let the wheel pass to the canvas. */
57
+ activeId: string | null;
58
+ /** True while the canvas is moving, so a frame under the pointer cannot steal the drag. */
59
+ moving: boolean;
60
+ activate: (id: string) => void;
61
+ showFrame: (view: string) => void;
62
+ showSpecFor: (view: string) => void;
63
+ }
64
+ const CanvasContext = createContext<CanvasContextValue | null>(null);
65
+ const useCanvas = () => {
66
+ const ctx = useContext(CanvasContext);
67
+ if (!ctx) throw new Error("Canvas frame rendered outside <Canvas>.");
68
+ return ctx;
69
+ };
70
+
71
+ type FrameNode = Node<{ pf: PlacedFrame }, "frame">;
72
+ type TitleNode = Node<{ title: string }, "title">;
73
+
74
+ function FrameNodeView({ data }: NodeProps<FrameNode>) {
75
+ const { pf } = data;
76
+ const f = pf.frame;
77
+ const ctx = useCanvas();
78
+ const source = f.kind === "doc" ? ctx.docs[f.src] : undefined;
79
+ const meta = f.kind === "doc" && source ? parseFrontMatter(source).data : null;
80
+ const active = ctx.activeId === pf.id;
81
+ const bodyRef = useRef<HTMLDivElement>(null);
82
+ // A boolean selector re-renders this node only when zoom crosses the threshold.
83
+ const outline = useStore((s) => s.transform[2] < OUTLINE_ZOOM);
84
+
85
+ // Over a doc whose text overflows, the wheel scrolls the document: React Flow skips any
86
+ // element carrying `nowheel`. A doc short enough to fit leaves the wheel to the canvas,
87
+ // so it never traps a panning gesture. Watch the body and its content, since zooming
88
+ // into outline mode changes the content height.
89
+ const [overflowing, setOverflowing] = useState(false);
90
+ useEffect(() => {
91
+ const el = bodyRef.current;
92
+ if (!el) return;
93
+ const measure = () => setOverflowing(el.scrollHeight > el.clientHeight + 1);
94
+ measure();
95
+ const ro = new ResizeObserver(measure);
96
+ ro.observe(el);
97
+ if (el.firstElementChild) ro.observe(el.firstElementChild);
98
+ return () => ro.disconnect();
99
+ }, [source, outline]);
100
+
101
+ return (
102
+ <Card
103
+ role="group"
104
+ data-canvas-frame={pf.id}
105
+ aria-label={pf.name}
106
+ tabIndex={-1}
107
+ className={cn(
108
+ "h-full w-full gap-0 overflow-hidden outline-none focus-visible:ring-[3px] focus-visible:ring-ring",
109
+ active && "ring-2 ring-ring",
110
+ )}
111
+ >
112
+ <header className="flex h-14 shrink-0 items-center gap-3 border-b bg-muted/40 px-4">
113
+ <h2 className="min-w-0 truncate text-sm font-medium" title={pf.name}>{pf.name}</h2>
114
+ <span className="shrink-0 text-xs text-muted-foreground">
115
+ {f.kind === "live"
116
+ ? active
117
+ ? "Interactive. Esc to exit."
118
+ : `${f.width ?? 1280} × ${f.height ?? 800}`
119
+ : meta?.updated
120
+ ? `Updated ${meta.updated}`
121
+ : null}
122
+ </span>
123
+ {f.kind === "live" && ctx.hasDoc ? (
124
+ <Button variant="ghost" className="nodrag nopan ml-auto min-h-11" onClick={() => ctx.showSpecFor(f.view)}>
125
+ Spec
126
+ </Button>
127
+ ) : null}
128
+ </header>
129
+ {f.kind === "live" ? (
130
+ <div className="relative min-h-0 flex-1">
131
+ <iframe
132
+ title={`View: ${f.view}`}
133
+ src={ctx.resolveView(f.view)}
134
+ loading="lazy"
135
+ className="h-full w-full border-0 bg-background"
136
+ style={{ pointerEvents: active && !ctx.moving ? "auto" : "none" }}
137
+ />
138
+ {/* An idle frame passes the wheel and drag to the canvas. A click makes it live. */}
139
+ {!active ? (
140
+ <div
141
+ className="absolute inset-0 cursor-pointer"
142
+ onClick={() => ctx.activate(pf.id)}
143
+ aria-hidden="true"
144
+ />
145
+ ) : null}
146
+ </div>
147
+ ) : (
148
+ <div
149
+ ref={bodyRef}
150
+ role="region"
151
+ aria-label={`${pf.name} contents`}
152
+ tabIndex={0}
153
+ className={cn(
154
+ "nodrag nopan min-h-0 flex-1 cursor-auto select-text overflow-y-auto p-6 focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-ring",
155
+ overflowing && "nowheel",
156
+ )}
157
+ >
158
+ {source !== undefined ? (
159
+ <SpecFrame source={source} outline={outline} onFrameLink={ctx.showFrame} />
160
+ ) : (
161
+ <p className="text-sm text-muted-foreground">No document named {f.src}.</p>
162
+ )}
163
+ </div>
164
+ )}
165
+ </Card>
166
+ );
167
+ }
168
+
169
+ function TitleNodeView({ data }: NodeProps<TitleNode>) {
170
+ return <h2 className="whitespace-nowrap text-base font-medium text-muted-foreground">{data.title}</h2>;
171
+ }
172
+
173
+ // Defined once, outside any component, so React Flow does not remount every node.
174
+ const nodeTypes = { frame: FrameNodeView, title: TitleNodeView };
175
+
176
+ const toBounds = (r: Rect) => ({ x: r.x, y: r.y, width: r.w, height: r.h });
177
+
178
+ function CanvasInner({ doc, docs = {}, resolveView = (v) => `/${v}`, specHref, initialFrame, className }: CanvasProps) {
179
+ const rf = useReactFlow();
180
+ const wrapRef = useRef<HTMLDivElement>(null);
181
+ const [announce, setAnnounce] = useState("");
182
+ const [activeId, setActiveId] = useState<string | null>(null);
183
+ const [moving, setMoving] = useState(false);
184
+ const zoomPct = useStore((s) => Math.round(s.transform[2] * 100));
185
+
186
+ const placed = useMemo(() => placeFrames(doc), [doc]);
187
+ const docFrame = placed.frames.find((f) => f.frame.kind === "doc");
188
+
189
+ const nodes = useMemo<(FrameNode | TitleNode)[]>(
190
+ () => [
191
+ ...placed.sections.map((s, i): TitleNode => ({
192
+ id: `title-${i}`,
193
+ type: "title",
194
+ position: { x: s.rect.x, y: 8 },
195
+ data: { title: s.title },
196
+ draggable: false,
197
+ selectable: false,
198
+ focusable: false,
199
+ style: { pointerEvents: "none" },
200
+ })),
201
+ ...placed.frames.map((pf): FrameNode => ({
202
+ id: pf.id,
203
+ type: "frame",
204
+ position: { x: pf.rect.x, y: pf.rect.y },
205
+ data: { pf },
206
+ width: pf.rect.w,
207
+ height: pf.rect.h,
208
+ draggable: false,
209
+ focusable: false,
210
+ })),
211
+ ],
212
+ [placed],
213
+ );
214
+
215
+ // A reader who prefers reduced motion gets a jump, not a glide.
216
+ const duration = useCallback(
217
+ () => (window.matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : 300),
218
+ [],
219
+ );
220
+
221
+ // React Flow's fitBounds has no zoom ceiling below the canvas maximum, so a small frame
222
+ // would be blown up past 100 percent. Work out the viewport with a ceiling of 1.
223
+ const fitTo = useCallback(
224
+ (rect: Rect, ms: number) => {
225
+ const el = wrapRef.current;
226
+ if (!el) return;
227
+ const vp = getViewportForBounds(toBounds(rect), el.clientWidth, el.clientHeight, MIN_ZOOM, 1, FIT_PADDING);
228
+ void rf.setViewport(vp, { duration: ms });
229
+ },
230
+ [rf],
231
+ );
232
+
233
+ const focusFrame = useCallback(
234
+ (pf: PlacedFrame) => {
235
+ fitTo(pf.rect, duration());
236
+ requestAnimationFrame(() =>
237
+ wrapRef.current?.querySelector<HTMLElement>(`[data-canvas-frame="${pf.id}"]`)?.focus({ preventScroll: true }),
238
+ );
239
+ setAnnounce(`Frame ${pf.name}`);
240
+ },
241
+ [duration, fitTo],
242
+ );
243
+
244
+ const showFrame = useCallback(
245
+ (view: string) => {
246
+ const pf = placed.frames.find((f) => f.frame.kind === "live" && f.frame.view === view);
247
+ if (pf) focusFrame(pf);
248
+ else setAnnounce(`No frame named ${view}`);
249
+ },
250
+ [focusFrame, placed.frames],
251
+ );
252
+
253
+ const showSpecFor = useCallback(
254
+ (view: string) => {
255
+ if (!docFrame) return;
256
+ focusFrame(docFrame);
257
+ requestAnimationFrame(() => {
258
+ wrapRef.current
259
+ ?.querySelector<HTMLElement>(`[data-canvas-frame="${docFrame.id}"] a[href="frame:${view}"]`)
260
+ ?.scrollIntoView({ block: "center" });
261
+ });
262
+ },
263
+ [docFrame, focusFrame],
264
+ );
265
+
266
+ const fitAll = useCallback(
267
+ () => fitTo(placed.bounds, duration()),
268
+ [duration, fitTo, placed.bounds],
269
+ );
270
+
271
+ // First paint: the named frame; else the first two frames (usually the spec and the
272
+ // entry view), which opens at a zoom where the spec text is readable and scrollable;
273
+ // else everything.
274
+ const onInit = useCallback(() => {
275
+ const target = initialFrame
276
+ ? placed.frames.find((f) => f.frame.kind === "live" && f.frame.view === initialFrame)
277
+ : undefined;
278
+ const [a, b] = placed.frames;
279
+ let rect: Rect = placed.bounds;
280
+ if (target) rect = target.rect;
281
+ else if (a && b) {
282
+ const x = Math.min(a.rect.x, b.rect.x);
283
+ const y = Math.min(a.rect.y, b.rect.y);
284
+ rect = {
285
+ x,
286
+ y,
287
+ w: Math.max(a.rect.x + a.rect.w, b.rect.x + b.rect.w) - x,
288
+ h: Math.max(a.rect.y + a.rect.h, b.rect.y + b.rect.h) - y,
289
+ };
290
+ }
291
+ fitTo(rect, 0);
292
+ }, [fitTo, initialFrame, placed]);
293
+
294
+ // Live frames are iframes with their own document. Mirror the host's dark class into
295
+ // each one, on load and whenever the host flips theme, so a frame never shows the
296
+ // opposite theme to the spec beside it.
297
+ const syncTheme = useCallback(() => {
298
+ const dark = document.documentElement.classList.contains("dark");
299
+ wrapRef.current?.querySelectorAll("iframe").forEach((f) => {
300
+ try {
301
+ f.contentDocument?.documentElement.classList.toggle("dark", dark);
302
+ } catch {
303
+ // Cross-origin frame. Nothing to sync.
304
+ }
305
+ });
306
+ }, []);
307
+ useEffect(() => {
308
+ syncTheme();
309
+ const mo = new MutationObserver(syncTheme);
310
+ mo.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
311
+ const wrap = wrapRef.current;
312
+ // iframe `load` does not bubble, so listen in the capture phase.
313
+ wrap?.addEventListener("load", syncTheme, true);
314
+ return () => {
315
+ mo.disconnect();
316
+ wrap?.removeEventListener("load", syncTheme, true);
317
+ };
318
+ }, [syncTheme]);
319
+
320
+ const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
321
+ if (e.key === "Escape" && activeId) {
322
+ setActiveId(null);
323
+ return;
324
+ }
325
+ if (e.target !== e.currentTarget) return;
326
+ const pan = (dx: number, dy: number) => {
327
+ e.preventDefault();
328
+ const v = rf.getViewport();
329
+ void rf.setViewport({ x: v.x + dx, y: v.y + dy, zoom: v.zoom }, { duration: 0 });
330
+ };
331
+ const step = (dir: 1 | -1) => {
332
+ e.preventDefault();
333
+ const active = document.activeElement?.closest<HTMLElement>("[data-canvas-frame]")?.dataset.canvasFrame;
334
+ const at = placed.frames.findIndex((f) => f.id === active);
335
+ const next = placed.frames[(at + dir + placed.frames.length) % placed.frames.length];
336
+ if (next) focusFrame(next);
337
+ };
338
+ switch (e.key) {
339
+ case "ArrowLeft": return pan(PAN_STEP, 0);
340
+ case "ArrowRight": return pan(-PAN_STEP, 0);
341
+ case "ArrowUp": return pan(0, PAN_STEP);
342
+ case "ArrowDown": return pan(0, -PAN_STEP);
343
+ case "+":
344
+ case "=": e.preventDefault(); return void rf.zoomIn({ duration: 0 });
345
+ case "-": e.preventDefault(); return void rf.zoomOut({ duration: 0 });
346
+ case "0": e.preventDefault(); return fitAll();
347
+ case "]": return step(1);
348
+ case "[": return step(-1);
349
+ }
350
+ };
351
+
352
+ const ctx = useMemo<CanvasContextValue>(
353
+ () => ({ docs, resolveView, hasDoc: Boolean(docFrame), activeId, moving, activate: setActiveId, showFrame, showSpecFor }),
354
+ // `docs` and `resolveView` are usually inline in the parent. Keying on the spec text
355
+ // and the frame state keeps a parent re-render from rebuilding every node.
356
+ // eslint-disable-next-line react-hooks/exhaustive-deps
357
+ [docs["spec.md"], Object.keys(docs).join(), docFrame, activeId, moving, showFrame, showSpecFor],
358
+ );
359
+
360
+ return (
361
+ <CanvasContext.Provider value={ctx}>
362
+ <div
363
+ ref={wrapRef}
364
+ role="region"
365
+ aria-label="Canvas"
366
+ aria-keyshortcuts="ArrowLeft ArrowRight ArrowUp ArrowDown + - 0 [ ]"
367
+ tabIndex={0}
368
+ onKeyDown={onKeyDown}
369
+ data-slot="canvas"
370
+ className={cn(
371
+ "relative h-full min-h-[480px] w-full overflow-hidden rounded-lg border bg-muted/40 outline-none focus-visible:ring-[3px] focus-visible:ring-ring",
372
+ className,
373
+ )}
374
+ >
375
+ <ReactFlow
376
+ nodes={nodes}
377
+ edges={[]}
378
+ nodeTypes={nodeTypes}
379
+ onInit={onInit}
380
+ minZoom={MIN_ZOOM}
381
+ maxZoom={MAX_ZOOM}
382
+ // The wheel pans; holding Ctrl or Command zooms, and so does a trackpad pinch.
383
+ panOnScroll
384
+ zoomOnScroll={false}
385
+ zoomOnPinch
386
+ zoomOnDoubleClick={false}
387
+ zoomActivationKeyCode={["Meta", "Control"]}
388
+ panOnDrag={[0, 1]}
389
+ nodesDraggable={false}
390
+ nodesConnectable={false}
391
+ nodesFocusable={false}
392
+ edgesFocusable={false}
393
+ // React Flow gives a node no pointer events unless it can be selected or dragged, so
394
+ // frames stay selectable (clicks and the wheel reach them) but selection does nothing:
395
+ // no delete key, no multi-select, and no `onNodesChange` is wired.
396
+ deleteKeyCode={null}
397
+ selectionKeyCode={null}
398
+ multiSelectionKeyCode={null}
399
+ disableKeyboardA11y
400
+ onMoveStart={() => setMoving(true)}
401
+ onMoveEnd={() => setMoving(false)}
402
+ onPaneClick={() => setActiveId(null)}
403
+ proOptions={{ hideAttribution: true }}
404
+ >
405
+ <Background gap={24} size={1.5} color="var(--border)" />
406
+ <Panel position="top-left" className="!m-3 max-w-[calc(100%-1.5rem)]">
407
+ <div
408
+ data-canvas-toolbar
409
+ className="flex flex-wrap items-center gap-1 rounded-lg border bg-background/95 p-1 shadow-sm"
410
+ >
411
+ <Button variant="ghost" size="icon-xl" aria-label="Zoom out" onClick={() => void rf.zoomOut({ duration: duration() })}>
412
+ <Minus {...ICON} />
413
+ </Button>
414
+ <span className="min-w-14 text-center text-sm tabular-nums">{zoomPct}%</span>
415
+ <Button variant="ghost" size="icon-xl" aria-label="Zoom in" onClick={() => void rf.zoomIn({ duration: duration() })}>
416
+ <Plus {...ICON} />
417
+ </Button>
418
+ <Button variant="ghost" size="icon-xl" aria-label="Fit everything" onClick={fitAll}>
419
+ <Maximize {...ICON} />
420
+ </Button>
421
+ {specHref ? (
422
+ <Button variant="ghost" asChild className="min-h-11">
423
+ <a href={specHref}>
424
+ Open spec
425
+ <ExternalLink {...ICON} />
426
+ </a>
427
+ </Button>
428
+ ) : null}
429
+ <nav aria-label="Frames" className="flex flex-wrap items-center gap-1 border-l pl-1">
430
+ {placed.frames.map((pf) => (
431
+ <Button key={pf.id} variant="ghost" className="min-h-11 max-w-48" onClick={() => focusFrame(pf)}>
432
+ <span className="truncate">{pf.name}</span>
433
+ </Button>
434
+ ))}
435
+ </nav>
436
+ </div>
437
+ </Panel>
438
+ </ReactFlow>
439
+ <p className="sr-only" role="status">{announce}</p>
440
+ </div>
441
+ </CanvasContext.Provider>
442
+ );
443
+ }
444
+
445
+ /**
446
+ * An infinite canvas of frames, built on React Flow for pan, zoom, and fit. Live frames
447
+ * are iframes of real views; doc frames render markdown, usually the prototype's spec.
448
+ * The wheel pans, Ctrl or Command with the wheel (or a pinch) zooms, and dragging empty
449
+ * canvas pans. Over a doc whose text overflows the wheel scrolls the document. A live
450
+ * frame ignores the wheel until you click it; Esc hands the pointer back to the canvas.
451
+ */
452
+ export function Canvas(props: CanvasProps) {
453
+ return (
454
+ <ReactFlowProvider>
455
+ <CanvasInner {...props} />
456
+ </ReactFlowProvider>
457
+ );
458
+ }
@@ -0,0 +1,72 @@
1
+ import type { CanvasDoc, CanvasFrame } from "./types";
2
+
3
+ /** Space between frames in a section, in world pixels. */
4
+ export const FRAME_GAP = 48;
5
+ /** Space between sections. */
6
+ export const SECTION_GAP = 120;
7
+ /** Height of the section title row above its frames. */
8
+ export const TITLE_ROW = 48;
9
+ /** Height of a frame's title bar. The frame body sits below it. */
10
+ export const BAR_HEIGHT = 56;
11
+ export const MIN_ZOOM = 0.1;
12
+ export const MAX_ZOOM = 2;
13
+
14
+ export interface Rect {
15
+ x: number;
16
+ y: number;
17
+ w: number;
18
+ h: number;
19
+ }
20
+
21
+ export interface PlacedFrame {
22
+ /** Stable id: "<section>:<index>". */
23
+ id: string;
24
+ frame: CanvasFrame;
25
+ /** Display name: the view name, or the doc's file name. */
26
+ name: string;
27
+ rect: Rect;
28
+ sectionTitle: string;
29
+ }
30
+
31
+ export interface Placed {
32
+ frames: PlacedFrame[];
33
+ sections: { title: string; rect: Rect }[];
34
+ bounds: Rect;
35
+ }
36
+
37
+ export function frameSize(f: CanvasFrame): { w: number; h: number } {
38
+ const w = f.width ?? (f.kind === "doc" ? 640 : 1280);
39
+ const body = f.height ?? (f.kind === "doc" ? 900 : 800);
40
+ return { w, h: body + BAR_HEIGHT };
41
+ }
42
+
43
+ /**
44
+ * Lay sections out left to right. Frames in a section sit side by side under the
45
+ * section title. Every frame, a doc included, lives in the world and moves with it.
46
+ */
47
+ export function placeFrames(doc: CanvasDoc): Placed {
48
+ const frames: PlacedFrame[] = [];
49
+ const sections: Placed["sections"] = [];
50
+ let cursor = 0;
51
+ doc.sections.forEach((section, si) => {
52
+ let x = cursor;
53
+ let height = 0;
54
+ section.frames.forEach((frame, fi) => {
55
+ const id = `${si}:${fi}`;
56
+ const { w, h } = frameSize(frame);
57
+ const name = frame.kind === "live" ? frame.view : frame.src;
58
+ frames.push({ id, frame, name, rect: { x, y: TITLE_ROW, w, h }, sectionTitle: section.title });
59
+ x += w + FRAME_GAP;
60
+ height = Math.max(height, h);
61
+ });
62
+ const width = x - FRAME_GAP - cursor;
63
+ sections.push({ title: section.title, rect: { x: cursor, y: 0, w: width, h: TITLE_ROW + height } });
64
+ cursor = x - FRAME_GAP + SECTION_GAP;
65
+ });
66
+ const all = sections.map((s) => s.rect);
67
+ const x0 = Math.min(...all.map((r) => r.x), 0);
68
+ const y0 = Math.min(...all.map((r) => r.y), 0);
69
+ const x1 = Math.max(...all.map((r) => r.x + r.w), 0);
70
+ const y1 = Math.max(...all.map((r) => r.y + r.h), 0);
71
+ return { frames, sections, bounds: { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } };
72
+ }
@@ -0,0 +1,32 @@
1
+ import type { CanvasDoc, CanvasFrame, CanvasSection } from "./types";
2
+
3
+ function asFrame(raw: unknown): CanvasFrame | null {
4
+ if (typeof raw !== "object" || raw === null) return null;
5
+ const r = raw as Record<string, unknown>;
6
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined);
7
+ if (r.kind === "live" && typeof r.view === "string" && r.view) {
8
+ return { kind: "live", view: r.view, width: num(r.width), height: num(r.height) };
9
+ }
10
+ if (r.kind === "doc" && typeof r.src === "string" && r.src) {
11
+ return { kind: "doc", src: r.src, width: num(r.width), height: num(r.height) };
12
+ }
13
+ return null;
14
+ }
15
+
16
+ /**
17
+ * Read canvas JSON of unknown shape. Frames that do not parse are dropped, and so is
18
+ * any section left with no frames, so an agent never has to clean up empty sections.
19
+ */
20
+ export function parseCanvas(input: unknown): CanvasDoc {
21
+ const rawSections = typeof input === "object" && input !== null ? (input as { sections?: unknown }).sections : undefined;
22
+ const sections: CanvasSection[] = [];
23
+ if (!Array.isArray(rawSections)) return { sections };
24
+ for (const s of rawSections) {
25
+ if (typeof s !== "object" || s === null) continue;
26
+ const title = typeof (s as { title?: unknown }).title === "string" ? (s as { title: string }).title : "";
27
+ const rawFrames = (s as { frames?: unknown }).frames;
28
+ const frames = Array.isArray(rawFrames) ? rawFrames.map(asFrame).filter((f): f is CanvasFrame => f !== null) : [];
29
+ if (frames.length > 0) sections.push({ title, frames });
30
+ }
31
+ return { sections };
32
+ }
@@ -0,0 +1,90 @@
1
+ import type { CanvasDoc } from "./types";
2
+
3
+ /**
4
+ * A real spec for a real prototype: the BADS showcase, reviewed as two views. Used by
5
+ * the Canvas story and the /preview/canvas route. Kept free of backticks so it can
6
+ * sit in a template literal, and kept clean so `analyzeSpec` reports no problems.
7
+ */
8
+ export const SAMPLE_SPEC = `---
9
+ prototype: showcase-overview
10
+ path: B
11
+ updated: 2026-10-15
12
+ ---
13
+
14
+ # Showcase overview, two directions
15
+
16
+ ## Audience and problem
17
+
18
+ A client designer deciding whether BADS fits their product in one sitting. Today they open the component list first and cannot tell what the assembled system looks like.
19
+
20
+ ## What it does
21
+
22
+ - Shows the same system as a grid of vignettes and as a working dashboard.
23
+ - Lets the reviewer compare both at once, in light and dark.
24
+ - Links every claim in this spec to the view that proves it.
25
+
26
+ ## Element inventory
27
+
28
+ | Element | Source | Built | Notes | View |
29
+ |---|---|---|---|---|
30
+ | Card grid of vignettes | direction sketch 1 | yes | Charts, stats, calendar, share dialog. | cards |
31
+ | Dashboard with filters | direction sketch 2 | yes | Table, chart, and a filter drawer. | dashboard |
32
+ | Theme toggle in the corner | direction sketch 2 | yes | Same control as the app shell. | dashboard |
33
+ | Per-component usage notes | direction sketch 1 | deferred | Approved by Matthew on 2026-10-14. Lives in the Docs tab instead. | |
34
+ | Animated hero | direction sketch 2 | dropped | Approved by Matthew on 2026-10-14. Motion budget went to the charts. | |
35
+
36
+ ## States
37
+
38
+ | State | Covered | Where |
39
+ |---|---|---|
40
+ | Default | yes | cards, dashboard |
41
+ | Empty table | yes | dashboard |
42
+ | Loading | no | Needs a decision, see open questions. |
43
+
44
+ ## Decisions
45
+
46
+ - 2026-10-14 Kept both directions on the canvas. The cards read faster; the dashboard proves the system holds up under real density.
47
+ - 2026-10-14 Dropped the animated hero. A hero would repeat the AI landing page sequence the anti-defaults warn about.
48
+
49
+ ## Open questions
50
+
51
+ - Matthew: Should the dashboard ship a loading state before the first client review?
52
+ - Kelsey: Does the share dialog vignette need real event copy for the aura launch?
53
+
54
+ ## Out of scope
55
+
56
+ Pricing, onboarding, and anything behind a login.
57
+
58
+ ## Handoff
59
+
60
+ ### Build from
61
+
62
+ The card vignettes under the examples folder and the dashboard composition.
63
+
64
+ ### Do not miss
65
+
66
+ The deferred usage notes. They belong in the Docs tab, not in these views.
67
+
68
+ ### More context
69
+
70
+ The decisions above, newest first.
71
+
72
+ ### Ignore
73
+
74
+ The sample numbers in the charts.
75
+ `;
76
+
77
+ export const SAMPLE_CANVAS: CanvasDoc = {
78
+ sections: [
79
+ { title: "Spec", frames: [{ kind: "doc", src: "spec.md", width: 640, height: 900 }] },
80
+ {
81
+ title: "Entry",
82
+ frames: [
83
+ { kind: "live", view: "cards", width: 1100, height: 800 },
84
+ { kind: "live", view: "dashboard", width: 1100, height: 800 },
85
+ ],
86
+ },
87
+ ],
88
+ };
89
+
90
+ export const sampleResolveView = (view: string) => `/preview/${view}`;
@@ -0,0 +1,43 @@
1
+ "use client";
2
+
3
+ import { useMemo } from "react";
4
+ import { MarkdownPreview } from "../markdown-preview";
5
+ import { cn } from "../../lib/utils";
6
+ import { linkInventoryViews, parseFrontMatter } from "../../lib/spec-parse";
7
+
8
+ /** Below this canvas zoom a Spec frame shows headings only. */
9
+ export const OUTLINE_ZOOM = 0.4;
10
+
11
+ /**
12
+ * The body of a doc frame: a spec.md rendered with the BADS markdown styles.
13
+ * Front matter is stripped (the frame's title bar shows it), and names in the
14
+ * inventory's View column become links that call `onFrameLink`.
15
+ */
16
+ export function SpecFrame({
17
+ source,
18
+ outline = false,
19
+ onFrameLink,
20
+ className,
21
+ }: {
22
+ source: string;
23
+ /** Show headings only. The canvas turns this on when zoomed out past OUTLINE_ZOOM. */
24
+ outline?: boolean;
25
+ onFrameLink?: (view: string) => void;
26
+ className?: string;
27
+ }) {
28
+ const body = useMemo(() => linkInventoryViews(parseFrontMatter(source).body), [source]);
29
+ return (
30
+ <div
31
+ data-slot="spec-frame"
32
+ data-detail={outline ? "outline" : "full"}
33
+ className={cn(
34
+ // In outline mode everything that is not a heading is hidden, so a zoomed-out
35
+ // canvas reads as a table of contents instead of a wall of tiny text.
36
+ outline && "[&_[data-slot=markdown-preview]>*:not(h1,h2,h3)]:hidden",
37
+ className,
38
+ )}
39
+ >
40
+ <MarkdownPreview source={body} maxWidth="max-w-none" onFrameLink={onFrameLink} />
41
+ </div>
42
+ );
43
+ }