@behavioral-agentic-design-system/core 0.40.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 (148) hide show
  1. package/README.md +2 -0
  2. package/package.json +41 -9
  3. package/scripts/a11y-lint.cjs +66 -3
  4. package/scripts/check-spec.mjs +73 -0
  5. package/scripts/deal-directions.mjs +186 -0
  6. package/scripts/health-report.mjs +23 -3
  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/lint-slop.mjs +25 -1
  18. package/scripts/on-system-score.mjs +95 -0
  19. package/scripts/slop-rules.mjs +1 -1
  20. package/scripts/source-images.mjs +180 -0
  21. package/scripts/ux-tells.mjs +78 -0
  22. package/scripts/wcag-audit.cjs +72 -5
  23. package/src/api/brand-colors.ts +3 -0
  24. package/src/api/brand-fonts.ts +3 -0
  25. package/src/api/brand-mark.ts +6 -1
  26. package/src/api/dev-write-guard.ts +53 -0
  27. package/src/api/layers/file.ts +7 -4
  28. package/src/api/onboarding-extract.ts +85 -30
  29. package/src/api/onboarding.ts +3 -0
  30. package/src/api/save-tokens.ts +3 -0
  31. package/src/app/layout.tsx +6 -0
  32. package/src/app/opengraph-image.tsx +5 -0
  33. package/src/app/preview/canvas/page.tsx +12 -0
  34. package/src/app/preview/components/page.tsx +2003 -2
  35. package/src/app/preview/studio/blank-screen.tsx +143 -0
  36. package/src/app/preview/studio/page.tsx +7 -0
  37. package/src/app/shell.tsx +168 -49
  38. package/src/components/Foundations/Motion.stories.tsx +1 -0
  39. package/src/components/canvas/canvas.tsx +458 -0
  40. package/src/components/canvas/layout.ts +72 -0
  41. package/src/components/canvas/parse-canvas.ts +32 -0
  42. package/src/components/canvas/sample.ts +90 -0
  43. package/src/components/canvas/spec-frame.tsx +43 -0
  44. package/src/components/canvas/types.ts +33 -0
  45. package/src/components/customize/design-controls.tsx +16 -1
  46. package/src/components/docs-tab.tsx +7 -7
  47. package/src/components/home-recent.tsx +73 -0
  48. package/src/components/home-tab.tsx +13 -13
  49. package/src/components/layers-tab.tsx +2 -2
  50. package/src/components/markdown-preview.tsx +60 -12
  51. package/src/components/studio/control-panel.tsx +299 -0
  52. package/src/components/studio/control-row.tsx +77 -0
  53. package/src/components/studio/preview-frame.tsx +165 -0
  54. package/src/components/studio/preview-pane.tsx +247 -0
  55. package/src/components/studio/studio.tsx +158 -0
  56. package/src/components/studio/types.ts +218 -0
  57. package/src/components/studio/use-studio-tweaks.ts +128 -0
  58. package/src/components/studio/use-studio-view-state.ts +72 -0
  59. package/src/components/ui/anchor.tsx +37 -3
  60. package/src/components/ui/attachment.tsx +211 -0
  61. package/src/components/ui/autocomplete.tsx +1 -1
  62. package/src/components/ui/chart.tsx +3 -0
  63. package/src/components/ui/code.tsx +1 -1
  64. package/src/components/ui/color-picker.tsx +21 -5
  65. package/src/components/ui/data-table.tsx +64 -3
  66. package/src/components/ui/date-field.tsx +1 -1
  67. package/src/components/ui/editable.tsx +1 -0
  68. package/src/components/ui/faceted-filter.tsx +187 -0
  69. package/src/components/ui/gauge-chart.tsx +252 -0
  70. package/src/components/ui/heatmap.tsx +256 -0
  71. package/src/components/ui/index.ts +9 -0
  72. package/src/components/ui/infinite-scroll.tsx +103 -0
  73. package/src/components/ui/inline-edit.tsx +175 -0
  74. package/src/components/ui/json-input.tsx +351 -0
  75. package/src/components/ui/month-picker.tsx +1 -1
  76. package/src/components/ui/navigation-progress.tsx +281 -0
  77. package/src/components/ui/number-input.tsx +27 -7
  78. package/src/components/ui/otp-input.tsx +208 -0
  79. package/src/components/ui/password-input.tsx +2 -1
  80. package/src/components/ui/password-strength-input.tsx +288 -0
  81. package/src/components/ui/phone-input.tsx +274 -0
  82. package/src/components/ui/pill.tsx +140 -0
  83. package/src/components/ui/popover.tsx +27 -4
  84. package/src/components/ui/scroll-progress.tsx +100 -0
  85. package/src/components/ui/search-input.tsx +1 -1
  86. package/src/components/ui/snackbar.tsx +393 -0
  87. package/src/components/ui/sortable-list.tsx +342 -0
  88. package/src/components/ui/squircle.tsx +1 -1
  89. package/src/components/ui/table.tsx +1 -1
  90. package/src/components/ui/tags-input.tsx +1 -1
  91. package/src/components/ui/timer.tsx +1 -0
  92. package/src/components/ui/tour.tsx +1 -3
  93. package/src/components/ui/transfer-list.tsx +13 -26
  94. package/src/components/ui/week-picker.tsx +1 -1
  95. package/src/components/ui/year-picker.tsx +1 -1
  96. package/src/data/component-added.json +958 -0
  97. package/src/data/docs-index.ts +36 -0
  98. package/src/hooks/use-global-mono-font.ts +1 -0
  99. package/src/hooks/use-global-primary-color.ts +1 -0
  100. package/src/hooks/use-global-sans-font.ts +1 -0
  101. package/src/hooks/use-global-serif-font.ts +1 -0
  102. package/src/hooks/use-global-type-scale.ts +17 -2
  103. package/src/hooks/use-mobile.ts +2 -0
  104. package/src/hooks/use-sync-type-scale.ts +7 -11
  105. package/src/lib/clamp.ts +2 -0
  106. package/src/lib/spec-parse.ts +4 -0
  107. package/src/lib/svg-sanitize.ts +19 -9
  108. package/src/stories/Anchor.stories.tsx +54 -0
  109. package/src/stories/Attachment.stories.tsx +189 -0
  110. package/src/stories/Autocomplete.stories.tsx +2 -0
  111. package/src/stories/Canvas.stories.tsx +45 -0
  112. package/src/stories/Chart.stories.tsx +4 -0
  113. package/src/stories/Code.stories.tsx +1 -0
  114. package/src/stories/ColorPicker.stories.tsx +41 -0
  115. package/src/stories/DataTable.stories.tsx +30 -0
  116. package/src/stories/DateField.stories.tsx +21 -0
  117. package/src/stories/Editable.stories.tsx +2 -0
  118. package/src/stories/FacetedFilter.stories.tsx +197 -0
  119. package/src/stories/GaugeChart.stories.tsx +169 -0
  120. package/src/stories/Heatmap.stories.tsx +172 -0
  121. package/src/stories/InfiniteScroll.stories.tsx +225 -0
  122. package/src/stories/InlineEdit.stories.tsx +106 -0
  123. package/src/stories/JsonInput.stories.tsx +212 -0
  124. package/src/stories/MarkdownPreview.stories.tsx +53 -0
  125. package/src/stories/MonthPicker.stories.tsx +21 -0
  126. package/src/stories/NavigationProgress.stories.tsx +159 -0
  127. package/src/stories/NumberInput.stories.tsx +26 -0
  128. package/src/stories/OtpInput.stories.tsx +110 -0
  129. package/src/stories/PasswordInput.stories.tsx +4 -0
  130. package/src/stories/PasswordStrengthInput.stories.tsx +211 -0
  131. package/src/stories/PhoneInput.stories.tsx +127 -0
  132. package/src/stories/Pill.stories.tsx +201 -0
  133. package/src/stories/Popover.stories.tsx +29 -1
  134. package/src/stories/Portal.stories.tsx +3 -1
  135. package/src/stories/ScrollProgress.stories.tsx +117 -0
  136. package/src/stories/SearchInput.stories.tsx +2 -0
  137. package/src/stories/Snackbar.stories.tsx +315 -0
  138. package/src/stories/SortableList.stories.tsx +263 -0
  139. package/src/stories/Squircle.stories.tsx +1 -0
  140. package/src/stories/Table.stories.tsx +1 -0
  141. package/src/stories/TagsInput.stories.tsx +2 -0
  142. package/src/stories/Timer.stories.tsx +26 -0
  143. package/src/stories/Tour.stories.tsx +1 -0
  144. package/src/stories/TransferList.stories.tsx +4 -0
  145. package/src/stories/WeekPicker.stories.tsx +21 -0
  146. package/src/stories/YearPicker.stories.tsx +21 -0
  147. package/src/stories/story-groups.json +33 -16
  148. package/src/tokens.json +82 -54
@@ -0,0 +1,299 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import { PanelLeftClose } from "lucide-react";
5
+ import { Button } from "@behavioral-agentic-design-system/core/components/ui/button";
6
+ import { ScrollArea } from "@behavioral-agentic-design-system/core/components/ui/scroll-area";
7
+ import {
8
+ SegmentedControl,
9
+ SegmentedControlItem,
10
+ } from "@behavioral-agentic-design-system/core/components/ui/segmented-control";
11
+ import { Slider } from "@behavioral-agentic-design-system/core/components/ui/slider";
12
+ import { NativeSelect } from "@behavioral-agentic-design-system/core/components/ui/native-select";
13
+ import { Badge } from "@behavioral-agentic-design-system/core/components/ui/badge";
14
+ import { ColorPicker } from "@behavioral-agentic-design-system/core/components/ui/color-picker";
15
+ import {
16
+ Tooltip,
17
+ TooltipContent,
18
+ TooltipProvider,
19
+ TooltipTrigger,
20
+ } from "@behavioral-agentic-design-system/core/components/ui/tooltip";
21
+ import { Kbd } from "@behavioral-agentic-design-system/core/components/ui/kbd";
22
+ import { ColorPalette } from "@behavioral-agentic-design-system/core/components/customize-tab";
23
+ import { SANS_FONT_OPTIONS } from "@behavioral-agentic-design-system/core/hooks/use-global-sans-font";
24
+ import { RATIO_PRESETS } from "@behavioral-agentic-design-system/core/hooks/use-global-type-scale";
25
+ import {
26
+ NUMERIC_TWEAKS,
27
+ maxRatioForBase,
28
+ minBaseForRatio,
29
+ type StudioPanelMode,
30
+ type StudioTweakKey,
31
+ } from "./types";
32
+ import { useStudioTweaks } from "./use-studio-tweaks";
33
+ import { ControlRow } from "./control-row";
34
+
35
+ type NumericKey = Exclude<StudioTweakKey, "primaryColor" | "sansFont">;
36
+
37
+ const RADIUS_MARKS = [0, 0.25, 0.625, 1, 2];
38
+
39
+ /** Strip float noise, then fix to `digits` places. */
40
+ function fmt(n: number, digits: number): string {
41
+ return Number(n.toFixed(digits)).toString();
42
+ }
43
+
44
+ function ratioReadout(ratio: number): string {
45
+ const preset = RATIO_PRESETS.find((p) => Math.abs(p.value - ratio) <= 0.002);
46
+ const base = ratio.toFixed(3);
47
+ return preset ? `${base} ${preset.label}` : base;
48
+ }
49
+
50
+ function readoutFor(key: NumericKey, v: number): string {
51
+ switch (key) {
52
+ case "radius":
53
+ case "spacing":
54
+ return `${v.toFixed(3)} rem`;
55
+ case "letterSpacing":
56
+ return `${fmt(v, 3)} em`;
57
+ case "shadowOpacity":
58
+ return `${fmt(v * 100, 0)}%`;
59
+ case "typeBase":
60
+ return `${fmt(v, 1)} px`;
61
+ case "typeRatio":
62
+ return ratioReadout(v);
63
+ }
64
+ }
65
+
66
+ function GroupHeading({ children }: { children: React.ReactNode }) {
67
+ return <h3 className="text-sm font-semibold text-foreground">{children}</h3>;
68
+ }
69
+
70
+ export function ControlPanel({
71
+ mode,
72
+ onModeChange,
73
+ onCollapse,
74
+ }: {
75
+ mode: StudioPanelMode;
76
+ onModeChange: (mode: StudioPanelMode) => void;
77
+ /** Omit on mobile, where the outer Controls/Preview switch already does this. */
78
+ onCollapse?: () => void;
79
+ }) {
80
+ const { tweaks, set, reset, resetAll, isDefault, primaryOptions, addCustomColor } =
81
+ useStudioTweaks();
82
+
83
+ const ids = React.useId();
84
+ const fontId = `${ids}-font`;
85
+
86
+ /* Brand color: the picker speaks hex, the hook speaks option keys. */
87
+ const optionEntries = Object.entries(primaryOptions);
88
+ const swatches = optionEntries.map(([, o]) => o.primary);
89
+ const selected = primaryOptions[tweaks.primaryColor];
90
+ const colorValue = selected?.primary ?? swatches[0] ?? "#000000";
91
+
92
+ const handleColor = (hex: string) => {
93
+ const hit = optionEntries.find(([, o]) => o.primary.toLowerCase() === hex.toLowerCase());
94
+ if (hit) set("primaryColor", hit[0]);
95
+ else addCustomColor(hex);
96
+ };
97
+
98
+ /* Type floor: text-xs is base / ratio^2 and must stay at or above 14px. */
99
+ const baseMin = Math.min(
100
+ NUMERIC_TWEAKS.typeBase.max,
101
+ minBaseForRatio(tweaks.typeRatio),
102
+ );
103
+ const ratioMax = Math.max(
104
+ NUMERIC_TWEAKS.typeRatio.min,
105
+ maxRatioForBase(tweaks.typeBase),
106
+ );
107
+ const floorActive =
108
+ baseMin > NUMERIC_TWEAKS.typeBase.min || ratioMax < NUMERIC_TWEAKS.typeRatio.max;
109
+
110
+ const ratioMarks = RATIO_PRESETS.filter(
111
+ (p) => p.value >= NUMERIC_TWEAKS.typeRatio.min && p.value <= ratioMax,
112
+ ).map((p) => p.value);
113
+
114
+ const numeric = (
115
+ key: NumericKey,
116
+ opts?: { min?: number; max?: number; marks?: React.ComponentProps<typeof Slider>["marks"] },
117
+ ) => {
118
+ const meta = NUMERIC_TWEAKS[key];
119
+ const min = opts?.min ?? meta.min;
120
+ const max = opts?.max ?? meta.max;
121
+ const value = Math.min(max, Math.max(min, tweaks[key]));
122
+ return (
123
+ <ControlRow
124
+ key={key}
125
+ label={meta.label}
126
+ readout={readoutFor(key, tweaks[key])}
127
+ isDefault={isDefault(key)}
128
+ onReset={() => reset(key)}
129
+ >
130
+ <Slider
131
+ aria-label={meta.label}
132
+ value={[value]}
133
+ min={min}
134
+ max={max}
135
+ step={meta.step}
136
+ marks={opts?.marks}
137
+ onValueChange={([n]) => set(key, n)}
138
+ />
139
+ </ControlRow>
140
+ );
141
+ };
142
+
143
+ const grade = selected?.grade;
144
+ const gradeVariant =
145
+ grade === "AAA" ? "success" : grade === "AA" || grade === "AA Large" ? "warning" : "destructive";
146
+
147
+ return (
148
+ <TooltipProvider>
149
+ <div
150
+ data-slot="studio-control-panel"
151
+ className="flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-background"
152
+ >
153
+ <header className="flex min-w-0 flex-col gap-3 p-4">
154
+ <div className={onCollapse ? "flex min-w-0 items-center justify-between gap-2" : "sr-only"}>
155
+ <h2 className="min-w-0 truncate text-sm font-semibold text-foreground">Controls</h2>
156
+ {onCollapse ? (
157
+ <Tooltip>
158
+ <TooltipTrigger asChild>
159
+ <Button
160
+ type="button"
161
+ variant="ghost"
162
+ size="icon-xl"
163
+ aria-label="Collapse controls"
164
+ aria-keyshortcuts="Control+\ Meta+\"
165
+ onClick={onCollapse}
166
+ className="-my-2 shrink-0"
167
+ >
168
+ <PanelLeftClose strokeWidth={1.5} aria-hidden="true" />
169
+ </Button>
170
+ </TooltipTrigger>
171
+ <TooltipContent side="bottom">
172
+ <span className="flex items-center gap-2">
173
+ Collapse controls
174
+ <Kbd>{"⌘"}</Kbd>
175
+ <Kbd>\</Kbd>
176
+ </span>
177
+ </TooltipContent>
178
+ </Tooltip>
179
+ ) : null}
180
+ </div>
181
+ <SegmentedControl
182
+ label="Control panel mode"
183
+ value={mode}
184
+ onValueChange={(v) => onModeChange(v as StudioPanelMode)}
185
+ >
186
+ <SegmentedControlItem value="tweak">Tweak</SegmentedControlItem>
187
+ <SegmentedControlItem value="tokens">All tokens</SegmentedControlItem>
188
+ </SegmentedControl>
189
+ </header>
190
+
191
+ <ScrollArea role="region" aria-label="Studio controls" className="min-h-0 flex-1">
192
+ <div hidden={mode !== "tweak"} className="flex min-w-0 flex-col gap-6 p-4">
193
+ <p className="text-xs text-muted-foreground">
194
+ Changes apply to every preview tab and stay in this browser. Save them from All
195
+ tokens.
196
+ </p>
197
+
198
+ <section aria-labelledby={`${ids}-color`} className="flex min-w-0 flex-col gap-5">
199
+ <GroupHeading>
200
+ <span id={`${ids}-color`}>Color</span>
201
+ </GroupHeading>
202
+ <ControlRow
203
+ label="Brand color"
204
+ readout={selected?.label}
205
+ isDefault={isDefault("primaryColor")}
206
+ onReset={() => reset("primaryColor")}
207
+ >
208
+ <div className="flex min-w-0 flex-col gap-3">
209
+ <ColorPicker
210
+ aria-label="Brand color"
211
+ value={colorValue}
212
+ swatches={swatches}
213
+ wheel
214
+ onValueChange={handleColor}
215
+ />
216
+ {selected && (
217
+ <div className="flex min-w-0 flex-col gap-2">
218
+ <Badge variant={gradeVariant} size="default" className="w-fit">
219
+ {selected.grade} {selected.contrast}:1
220
+ </Badge>
221
+ {selected.grade !== "AAA" && (
222
+ <p className="text-xs text-muted-foreground">
223
+ This color misses the 7:1 AAA contrast floor against its foreground. You
224
+ can still apply it.
225
+ </p>
226
+ )}
227
+ </div>
228
+ )}
229
+ </div>
230
+ </ControlRow>
231
+ </section>
232
+
233
+ <section aria-labelledby={`${ids}-type`} className="flex min-w-0 flex-col gap-5">
234
+ <GroupHeading>
235
+ <span id={`${ids}-type`}>Type</span>
236
+ </GroupHeading>
237
+ <ControlRow
238
+ label="Sans font"
239
+ htmlFor={fontId}
240
+ isDefault={isDefault("sansFont")}
241
+ onReset={() => reset("sansFont")}
242
+ >
243
+ <NativeSelect
244
+ id={fontId}
245
+ size="xl"
246
+ value={tweaks.sansFont}
247
+ onChange={(e) => set("sansFont", e.target.value)}
248
+ >
249
+ {Object.entries(SANS_FONT_OPTIONS).map(([key, opt]) => (
250
+ <option key={key} value={key}>
251
+ {opt.label}
252
+ </option>
253
+ ))}
254
+ </NativeSelect>
255
+ </ControlRow>
256
+ {numeric("typeBase", { min: baseMin })}
257
+ {numeric("typeRatio", { max: ratioMax, marks: ratioMarks })}
258
+ {numeric("letterSpacing")}
259
+ {floorActive && (
260
+ <p className="text-xs text-muted-foreground">
261
+ Smallest text stays at 14px. That limits this range.
262
+ </p>
263
+ )}
264
+ </section>
265
+
266
+ <section aria-labelledby={`${ids}-shape`} className="flex min-w-0 flex-col gap-5">
267
+ <GroupHeading>
268
+ <span id={`${ids}-shape`}>Shape</span>
269
+ </GroupHeading>
270
+ {numeric("radius", { marks: RADIUS_MARKS })}
271
+ {numeric("shadowOpacity")}
272
+ </section>
273
+
274
+ <section aria-labelledby={`${ids}-space`} className="flex min-w-0 flex-col gap-5">
275
+ <GroupHeading>
276
+ <span id={`${ids}-space`}>Space</span>
277
+ </GroupHeading>
278
+ {numeric("spacing")}
279
+ </section>
280
+
281
+ <Button
282
+ type="button"
283
+ variant="outline"
284
+ size="xl"
285
+ className="w-full"
286
+ onClick={resetAll}
287
+ >
288
+ Reset all tweaks
289
+ </Button>
290
+ </div>
291
+
292
+ <div hidden={mode !== "tokens"} className="min-w-0 p-4">
293
+ <ColorPalette />
294
+ </div>
295
+ </ScrollArea>
296
+ </div>
297
+ </TooltipProvider>
298
+ );
299
+ }
@@ -0,0 +1,77 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import { RotateCcw } from "lucide-react";
5
+ import { Button } from "@behavioral-agentic-design-system/core/components/ui/button";
6
+ import { Label } from "@behavioral-agentic-design-system/core/components/ui/label";
7
+
8
+ const FOCUSABLE =
9
+ "[role='slider'], select, input, [role='radio'][aria-checked='true'], [role='radio'], button";
10
+
11
+ /**
12
+ * One tweakable value: label left, readout right, control beneath, and a reset
13
+ * button that only exists while the value differs from its default. Clicking
14
+ * reset restores the default and returns focus to the row's control, because the
15
+ * reset button unmounts and focus would otherwise fall to the document body.
16
+ */
17
+ export function ControlRow({
18
+ label,
19
+ readout,
20
+ isDefault,
21
+ onReset,
22
+ children,
23
+ htmlFor,
24
+ }: {
25
+ label: string;
26
+ readout?: React.ReactNode;
27
+ isDefault: boolean;
28
+ onReset: () => void;
29
+ children: React.ReactNode;
30
+ htmlFor?: string;
31
+ }) {
32
+ const controlRef = React.useRef<HTMLDivElement>(null);
33
+
34
+ const handleReset = () => {
35
+ onReset();
36
+ // Wait a frame so the control re-renders with the default before focusing.
37
+ requestAnimationFrame(() => {
38
+ controlRef.current?.querySelector<HTMLElement>(FOCUSABLE)?.focus();
39
+ });
40
+ };
41
+
42
+ return (
43
+ <div className="flex min-w-0 flex-col gap-3">
44
+ <div className="flex min-w-0 items-center justify-between gap-2">
45
+ {htmlFor ? (
46
+ <Label htmlFor={htmlFor} className="min-w-0 truncate text-sm font-medium">
47
+ {label}
48
+ </Label>
49
+ ) : (
50
+ <span className="min-w-0 truncate text-sm font-medium text-foreground">
51
+ {label}
52
+ </span>
53
+ )}
54
+ <div className="flex shrink-0 items-center gap-1">
55
+ {readout != null && (
56
+ <span className="text-xs tabular-nums text-muted-foreground">{readout}</span>
57
+ )}
58
+ {!isDefault && (
59
+ <Button
60
+ type="button"
61
+ variant="ghost"
62
+ size="icon-xl"
63
+ aria-label={`Reset ${label}`}
64
+ onClick={handleReset}
65
+ className="-my-3"
66
+ >
67
+ <RotateCcw strokeWidth={1.5} aria-hidden="true" />
68
+ </Button>
69
+ )}
70
+ </div>
71
+ </div>
72
+ <div ref={controlRef} className="min-w-0">
73
+ {children}
74
+ </div>
75
+ </div>
76
+ );
77
+ }
@@ -0,0 +1,165 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
4
+ import { Spinner } from "../ui/spinner";
5
+ import { cn } from "../../lib/utils";
6
+
7
+ /** What a frame reports about itself, for the pane's readout. */
8
+ export interface PreviewFrameMeasure {
9
+ /** CSS width of the iframe's viewport. */
10
+ width: number;
11
+ /** CSS height of the iframe's viewport. */
12
+ height: number;
13
+ /** 1 means no zoom. Below 1 the frame is scaled down to fit. */
14
+ scale: number;
15
+ }
16
+
17
+ function withDark(src: string, dark: boolean): string {
18
+ if (!dark) return src;
19
+ return `${src}${src.includes("?") ? "&" : "?"}dark=1`;
20
+ }
21
+
22
+ function applyDark(iframe: HTMLIFrameElement | null, dark: boolean) {
23
+ try {
24
+ iframe?.contentDocument?.documentElement.classList.toggle("dark", dark);
25
+ } catch {
26
+ // Cross-origin or detached frame. Nothing to sync.
27
+ }
28
+ }
29
+
30
+ export function PreviewFrame({
31
+ src,
32
+ forcedDark,
33
+ appDark,
34
+ width,
35
+ title,
36
+ caption,
37
+ onMeasure,
38
+ }: {
39
+ /** From STUDIO_SUBJECTS. */
40
+ src: string;
41
+ /** null = follow the app (the shell syncs it). true/false = this frame owns its theme. */
42
+ forcedDark: boolean | null;
43
+ /** Current app theme. Builds the initial ?dark=1 when forcedDark is null, and is applied
44
+ * immediately whenever forcedDark changes from true/false back to null. */
45
+ appDark: boolean;
46
+ /** null = fill. */
47
+ width: number | null;
48
+ title: string;
49
+ /** "Light" / "Dark" in Both mode. */
50
+ caption?: string;
51
+ /** Optional. Reports the frame's rendered size so the pane can show a readout. */
52
+ onMeasure?: (m: PreviewFrameMeasure) => void;
53
+ }) {
54
+ const iframeRef = useRef<HTMLIFrameElement>(null);
55
+ const slotRef = useRef<HTMLDivElement>(null);
56
+
57
+ // Theme the frame should be in right now. Read through a ref inside the load handler
58
+ // and the src-change path so neither depends on a value that flips mid-wipe.
59
+ const effectiveDark = forcedDark ?? appDark;
60
+ const effectiveDarkRef = useRef(effectiveDark);
61
+ effectiveDarkRef.current = effectiveDark;
62
+ const appDarkRef = useRef(appDark);
63
+ appDarkRef.current = appDark;
64
+
65
+ // The iframe's src attribute changes only when the subject changes. A theme flip must
66
+ // never reload the frame (same reasoning as IframePreview in shell.tsx).
67
+ const [frame, setFrame] = useState(() => ({ base: src, url: withDark(src, effectiveDark) }));
68
+ const [loaded, setLoaded] = useState(false);
69
+ if (frame.base !== src) {
70
+ setFrame({ base: src, url: withDark(src, effectiveDark) });
71
+ setLoaded(false);
72
+ }
73
+
74
+ // forcedDark transitions. Only applies appDark on the way back to null, via a ref, so an
75
+ // app theme flip in Match mode is left to the shell's view-transition sync.
76
+ const prevForcedRef = useRef<boolean | null>(forcedDark);
77
+ useEffect(() => {
78
+ const prev = prevForcedRef.current;
79
+ prevForcedRef.current = forcedDark;
80
+ if (forcedDark !== null) {
81
+ applyDark(iframeRef.current, forcedDark);
82
+ } else if (prev !== null) {
83
+ applyDark(iframeRef.current, appDarkRef.current);
84
+ }
85
+ }, [forcedDark]);
86
+
87
+ // Stage measurement.
88
+ const [slot, setSlot] = useState<{ w: number; h: number }>({ w: 0, h: 0 });
89
+ useLayoutEffect(() => {
90
+ const el = slotRef.current;
91
+ if (!el) return;
92
+ const read = () => setSlot({ w: el.clientWidth, h: el.clientHeight });
93
+ read();
94
+ const ro = new ResizeObserver(read);
95
+ ro.observe(el);
96
+ return () => ro.disconnect();
97
+ }, []);
98
+
99
+ const scale = width !== null && slot.w > 0 ? Math.min(1, slot.w / width) : 1;
100
+ const frameW = width !== null ? width : slot.w;
101
+ const frameH = scale > 0 && slot.h > 0 ? Math.round(slot.h / scale) : slot.h;
102
+
103
+ useEffect(() => {
104
+ if (!onMeasure || slot.w === 0 || slot.h === 0) return;
105
+ onMeasure({ width: Math.round(frameW), height: frameH, scale });
106
+ }, [onMeasure, slot.w, slot.h, frameW, frameH, scale]);
107
+
108
+ const readout = slot.w > 0 && slot.h > 0
109
+ ? `${Math.round(frameW)} × ${frameH}${scale < 1 ? ` · ${Math.round(scale * 100)}%` : ""}`
110
+ : "";
111
+
112
+ const handleLoad = useCallback(() => {
113
+ applyDark(iframeRef.current, effectiveDarkRef.current);
114
+ setLoaded(true);
115
+ }, []);
116
+
117
+ const fixed = width !== null;
118
+ const wrapperStyle = fixed ? { width: Math.round(width * scale) } : undefined;
119
+
120
+ return (
121
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col gap-2">
122
+ {caption ? (
123
+ <p className="flex items-baseline justify-between gap-2 text-xs">
124
+ <span className="font-medium text-foreground">{caption}</span>
125
+ <span className="tabular-nums text-muted-foreground">{readout}</span>
126
+ </p>
127
+ ) : null}
128
+ <div ref={slotRef} className="relative flex min-h-0 min-w-0 flex-1 justify-center">
129
+ <div
130
+ data-slot="studio-preview-frame"
131
+ data-theme-independent={forcedDark !== null ? "true" : undefined}
132
+ className={cn(
133
+ "relative h-full overflow-hidden rounded-lg bg-background shadow-sm",
134
+ fixed ? "shrink-0" : "w-full",
135
+ )}
136
+ style={wrapperStyle}
137
+ >
138
+ {!loaded ? (
139
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-2">
140
+ <Spinner size="sm" variant="muted" label="Loading preview" />
141
+ <p className="text-xs text-muted-foreground">Loading preview</p>
142
+ </div>
143
+ ) : null}
144
+ <iframe
145
+ ref={iframeRef}
146
+ src={frame.url}
147
+ title={title}
148
+ onLoad={handleLoad}
149
+ data-theme-independent={forcedDark !== null ? "true" : undefined}
150
+ className="absolute left-0 top-0 block border-0 transition-opacity"
151
+ style={{
152
+ width: fixed ? width : "100%",
153
+ height: fixed ? frameH : "100%",
154
+ transform: fixed && scale < 1 ? `scale(${scale})` : undefined,
155
+ transformOrigin: "top left",
156
+ opacity: loaded ? 1 : 0,
157
+ transitionDuration: "var(--duration-base)",
158
+ transitionTimingFunction: "var(--ease-out)",
159
+ }}
160
+ />
161
+ </div>
162
+ </div>
163
+ </div>
164
+ );
165
+ }