@behavioral-agentic-design-system/core 0.7.0 → 0.8.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.
package/src/app/shell.tsx CHANGED
@@ -4,7 +4,7 @@ import { useState, useEffect, useRef, useCallback, createContext, useContext, us
4
4
  import { Tabs, TabsContent, TabsList, TabsPanels, TabsTrigger } from "@behavioral-agentic-design-system/core/components/ui/tabs";
5
5
  import { Badge } from "@behavioral-agentic-design-system/core/components/ui/badge";
6
6
  import { Button } from "@behavioral-agentic-design-system/core/components/ui/button";
7
- import { Sun, Moon, BookOpen } from "lucide-react";
7
+ import { Sun, Moon, BookOpen, X } from "lucide-react";
8
8
 
9
9
  /**
10
10
  * Inline GitHub mark. Lucide dropped brand icons (Github / Twitter / etc.) in
@@ -30,6 +30,11 @@ import { CustomizeTab } from "@behavioral-agentic-design-system/core/components/
30
30
  import { LayersTab } from "@behavioral-agentic-design-system/core/components/layers-tab";
31
31
  import { HomeTab } from "@behavioral-agentic-design-system/core/components/home-tab";
32
32
  import { BrandMark } from "@behavioral-agentic-design-system/core/components/brand-mark";
33
+ import { OnboardingWizard } from "@behavioral-agentic-design-system/core/components/onboarding-wizard";
34
+
35
+ const ONBOARDING_DISMISSED_KEY = "bads:onboarding-wizard:dismissed";
36
+
37
+ const SETUP_PROMPT = `You are setting up a fresh BADS fork. Use the in-app onboarding brief that the user just completed as your source of truth. Do not re-ask questions that are already answered. Ask only for missing or contradictory details, then run the canonical setup steps in order: rename, source discovery, brand context, voice, microcopy, ethics, tokens, components, patterns, and Chromatic baseline.`;
33
38
 
34
39
  /**
35
40
  * Iframe-hosted preview surface. Listens for the parent's dark-mode state and
@@ -133,6 +138,14 @@ export type ShellTab = {
133
138
  value: string;
134
139
  label: string;
135
140
  hidden?: "md";
141
+ /**
142
+ * Skip the preload-all warm-up AND only mount this tab while it's active
143
+ * (unmount on leave). Use for tabs whose content is too heavy to sit in the
144
+ * DOM permanently — e.g. the Icons tab renders ~1,700 SVGs whose theme
145
+ * repaint, when kept mounted, stutters the dark/light view-transition on
146
+ * every toggle. Trade-off: a brief reload when you revisit the tab.
147
+ */
148
+ noPreload?: boolean;
136
149
  render: (ctx: ShellTabContext) => React.ReactNode;
137
150
  };
138
151
 
@@ -153,8 +166,8 @@ export const DEFAULT_TABS: ShellTab[] = [
153
166
  { value: "cards", label: "Cards", render: ({ dark }) => <IframePreview dark={dark} src="/preview/cards" /> },
154
167
  { value: "dashboard", label: "Dashboard", hidden: "md", render: ({ dark }) => <IframePreview dark={dark} src="/preview/dashboard" minWidth="1400px" /> },
155
168
  { value: "layers", label: "Layers", render: () => <LayersTab /> },
169
+ { value: "icons", label: "Icons", noPreload: true, render: ({ dark }) => <IframePreview dark={dark} src="/preview/icons" /> },
156
170
  { value: "colors", label: "Customize", render: () => <CustomizeTab /> },
157
- { value: "icons", label: "Icons", render: ({ dark }) => <IframePreview dark={dark} src="/preview/icons" /> },
158
171
  ];
159
172
 
160
173
  /**
@@ -171,6 +184,26 @@ export function Shell({ tabs, defaultTab }: ShellProps) {
171
184
  const initialTab = defaultTab ?? tabs[0]?.value ?? "home";
172
185
  const [activeTab, setActiveTab] = useState(initialTab);
173
186
  const [dark, setDark] = useState(false);
187
+ // Fresh-fork onboarding: only render when brand still says "BADS" (the rename
188
+ // hasn't run yet) AND the user hasn't dismissed the wizard this session.
189
+ // Renamed forks never see this — they've already gone through onboarding.
190
+ const isFreshFork = brand.name === "BADS";
191
+ const [onboardingDismissed, setOnboardingDismissed] = useState(true);
192
+ useEffect(() => {
193
+ if (!isFreshFork) return;
194
+ try {
195
+ setOnboardingDismissed(window.localStorage.getItem(ONBOARDING_DISMISSED_KEY) === "1");
196
+ } catch {
197
+ setOnboardingDismissed(false);
198
+ }
199
+ }, [isFreshFork]);
200
+ const dismissOnboarding = () => {
201
+ try {
202
+ window.localStorage.setItem(ONBOARDING_DISMISSED_KEY, "1");
203
+ } catch {}
204
+ setOnboardingDismissed(true);
205
+ };
206
+ const showOnboarding = isFreshFork && !onboardingDismissed;
174
207
  // Sticky-mount: once a tab has been viewed, keep it mounted forever so the
175
208
  // iframe (or React tree) doesn't cold-load on every switch. TabsPanels
176
209
  // cross-fades between mounted siblings, so subsequent switches are instant
@@ -191,7 +224,12 @@ export function Shell({ tabs, defaultTab }: ShellProps) {
191
224
  const preloadAll = () => {
192
225
  setSeen((prev) => {
193
226
  const next = new Set(prev);
194
- tabs.forEach((t) => next.add(t.value));
227
+ // noPreload tabs (e.g. Icons) are intentionally left out — they mount
228
+ // only while active so their heavy content doesn't sit in the DOM
229
+ // repainting on every theme toggle.
230
+ tabs.forEach((t) => {
231
+ if (!t.noPreload) next.add(t.value);
232
+ });
195
233
  return next;
196
234
  });
197
235
  };
@@ -215,25 +253,22 @@ export function Shell({ tabs, defaultTab }: ShellProps) {
215
253
  const prefersReduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
216
254
  const supports = typeof document !== "undefined" && "startViewTransition" in document;
217
255
 
218
- // Sync iframes in the currently-active tab right now so the visible
219
- // surface matches the new theme at the same instant the parent does —
220
- // otherwise the iframe lags behind React's useEffect and the view
221
- // transition captures stale content. Off-screen iframes (other tabs that
222
- // were preloaded into the DOM) catch up via the per-IframePreview
223
- // useEffect when React commits the new `dark` prop. Skipping the
224
- // synchronous sync for those iframes matters when one of them holds
225
- // expensive content (the Icons tab renders ~1,700 SVGs whose
226
- // currentColor strokes all recompute on `.dark` toggle) — paying for
227
- // that recompute every toggle, even when not visible, dominated the
228
- // perceived toggle latency.
256
+ // Sync EVERY mounted iframe's theme right now, synchronously, inside the
257
+ // transition callback — so all the repaint work happens UP FRONT, before
258
+ // the iris wipe animates, and nothing repaints mid-animation to steal
259
+ // frames. (Deferring off-screen iframes to the per-IframePreview useEffect
260
+ // is what made the wipe stutter: that repaint landed while the 0.4s
261
+ // animation was running.) This is safe now that the one expensive surface,
262
+ // the Icons tab, is lazy-mounted (noPreload — not in the DOM unless active)
263
+ // and its grid renders incrementally, so there's no ~1,700-SVG iframe to
264
+ // pay for here. Matches the smooth behavior of client forks without an
265
+ // Icons tab.
229
266
  const syncIframes = () => {
230
- document
231
- .querySelectorAll<HTMLIFrameElement>('[data-state="active"] iframe')
232
- .forEach((f) => {
233
- try {
234
- f.contentDocument?.documentElement.classList.toggle("dark", next);
235
- } catch {}
236
- });
267
+ document.querySelectorAll<HTMLIFrameElement>("iframe").forEach((f) => {
268
+ try {
269
+ f.contentDocument?.documentElement.classList.toggle("dark", next);
270
+ } catch {}
271
+ });
237
272
  };
238
273
  const syncHost = () => {
239
274
  root.classList.toggle("dark", next);
@@ -342,17 +377,44 @@ export function Shell({ tabs, defaultTab }: ShellProps) {
342
377
  <section className="relative flex-1 min-h-0 w-full overflow-hidden">
343
378
  <div className="absolute inset-x-4 top-1 bottom-4 isolate overflow-hidden rounded-lg">
344
379
  <TabsPanels>
345
- {tabs.map((tab) =>
346
- seen.has(tab.value) ? (
380
+ {tabs.map((tab) => {
381
+ // noPreload tabs mount only while active (and unmount on leave);
382
+ // everything else mounts once seen and stays for instant
383
+ // cross-fades. See ShellTab.noPreload.
384
+ const mounted = tab.noPreload ? activeTab === tab.value : seen.has(tab.value);
385
+ return mounted ? (
347
386
  <TabsContent key={tab.value} value={tab.value} forceMount>
348
387
  {tab.render(ctx)}
349
388
  </TabsContent>
350
- ) : null,
351
- )}
389
+ ) : null;
390
+ })}
352
391
  </TabsPanels>
353
392
  </div>
354
393
  </section>
355
394
  </Tabs>
395
+
396
+ {showOnboarding ? (
397
+ <div
398
+ role="dialog"
399
+ aria-modal="true"
400
+ aria-label="Onboarding"
401
+ className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-background/80 p-4 backdrop-blur-sm md:p-8"
402
+ >
403
+ <div className="relative w-full max-w-5xl">
404
+ <Button
405
+ type="button"
406
+ variant="ghost"
407
+ size="icon"
408
+ onClick={dismissOnboarding}
409
+ className="absolute -top-2 -right-2 z-10 size-9 rounded-full bg-background shadow-md ring-1 ring-border hover:bg-muted"
410
+ aria-label="Dismiss onboarding for now"
411
+ >
412
+ <X className="h-4 w-4" strokeWidth={1.5} />
413
+ </Button>
414
+ <OnboardingWizard setupPrompt={SETUP_PROMPT} defaultProductName={brand.name} />
415
+ </div>
416
+ </div>
417
+ ) : null}
356
418
  </div>
357
419
  </ShellNavContext.Provider>
358
420
  );
@@ -2,7 +2,16 @@ import type { Meta, StoryObj } from "@storybook/react";
2
2
 
3
3
  const meta: Meta = {
4
4
  title: "Foundations/Colors",
5
- parameters: { layout: "fullscreen" },
5
+ parameters: {
6
+ layout: "fullscreen",
7
+ // This is a palette reference: every swatch paints a raw token as a
8
+ // *background* with its name laid over it. Some tokens (chart fills, the
9
+ // focus ring) are never text-bearing surfaces in product, so the label-on-
10
+ // swatch pair legitimately falls under AA here. Disable only color-contrast
11
+ // for this doc story — every other axe rule still runs, and real text/bg
12
+ // pairs stay enforced by `pnpm wcag:audit` (AAA) and the rest of CI.
13
+ a11y: { config: { rules: [{ id: "color-contrast", enabled: false }] } },
14
+ },
6
15
  };
7
16
  export default meta;
8
17
  type Story = StoryObj<typeof meta>;
@@ -158,6 +158,9 @@ function ColorSwatch({
158
158
  </button>
159
159
  )}
160
160
  {showAdd && (
161
+ // allow-text-xs-cta — sub-flow Back link, paired with the
162
+ // text-xs labels around it in the color-add panel header.
163
+ // Reads as a breadcrumb/cancel, not a flow CTA.
161
164
  <button
162
165
  type="button"
163
166
  onClick={resetAddState}
@@ -185,7 +185,7 @@ const SHIPPED_LAYERS = [
185
185
  details: [
186
186
  "Makes every component discoverable and learnable — designers and engineers self-serve instead of asking questions",
187
187
  "Storybook coverage for every component (Default + all variants)",
188
- "Preview app with Home, Components, Cards, Dashboard, Layers, Customize, and Icons tabs",
188
+ "Preview app with Home, Components, Cards, Dashboard, Layers, Icons, and Customize tabs",
189
189
  "Chromatic visual regression wired to CI",
190
190
  "CAPABILITIES.md as the single discoverable index of every feature BADS ships",
191
191
  "Per-brand exemplars/ folder — pinned 'what good looks like' screenshots with annotations",
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
 
3
3
  import { useEffect, useState } from "react";
4
- import { Loader2, FileText, GitCommit, ChevronRight, Check, AlertCircle } from "lucide-react";
4
+ import { Loader2, FileText, GitCommit, ChevronRight, Check, AlertCircle, Palette } from "lucide-react";
5
5
  import ReactMarkdown, { type Components } from "react-markdown";
6
6
  import remarkGfm from "remark-gfm";
7
7
  import { Button } from "@behavioral-agentic-design-system/core/components/ui/button";
@@ -126,6 +126,97 @@ function prettyJsonOrRaw(content: string): string {
126
126
  }
127
127
  }
128
128
 
129
+ // Synthetic sidebar entry under Layer 4. It isn't a real file on disk —
130
+ // the semantic tokens live inside tokens.json's `theme` block — so it gets a
131
+ // sentinel path the component special-cases instead of routing through the
132
+ // file-content fetch. Keeps single-source-of-truth: the view reads the same
133
+ // tokens.json everything else builds from, never a duplicated export.
134
+ const SEMANTIC_VIEW = "semantic-tokens://resolved";
135
+
136
+ type SemanticToken = {
137
+ name: string;
138
+ light: string;
139
+ dark: string;
140
+ description?: string;
141
+ };
142
+
143
+ function TokenSwatch({ value }: { value: string }) {
144
+ return (
145
+ <span
146
+ className="inline-block size-4 shrink-0 rounded border border-border align-middle"
147
+ style={{ backgroundColor: value }}
148
+ aria-hidden
149
+ />
150
+ );
151
+ }
152
+
153
+ // Read-only resolved view of the semantic layer: every named role components
154
+ // consume (--background, --primary, …) with its light + dark value. Sourced
155
+ // live from tokens.json → theme, so it can't drift from what ships.
156
+ function SemanticTokensView({ tokens }: { tokens: SemanticToken[] | null }) {
157
+ if (tokens === null) {
158
+ return (
159
+ <div className="flex-1 flex items-center justify-center text-muted-foreground">
160
+ <Loader2 className="h-4 w-4 animate-spin" strokeWidth={1.5} />
161
+ </div>
162
+ );
163
+ }
164
+ if (tokens.length === 0) {
165
+ return (
166
+ <div className="flex-1 flex items-center justify-center text-muted-foreground">
167
+ <p className="text-sm">No semantic tokens found in tokens.json → theme.</p>
168
+ </div>
169
+ );
170
+ }
171
+ return (
172
+ <div className="flex-1 overflow-auto px-6 py-6">
173
+ <p className="mb-4 max-w-2xl text-sm text-muted-foreground">
174
+ The resolved semantic tokens — the named roles components consume,
175
+ mapped to their light and dark values. Sourced from{" "}
176
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">tokens.json</code> →{" "}
177
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">theme</code>. Read-only here;
178
+ edit values in tokens.json and run{" "}
179
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">pnpm build:tokens</code>.
180
+ </p>
181
+ <div className="overflow-hidden rounded-md border">
182
+ <table className="w-full border-collapse text-xs">
183
+ <thead className="border-b bg-muted/40 text-left">
184
+ <tr>
185
+ <th className="px-3 py-2 font-medium">Token</th>
186
+ <th className="px-3 py-2 font-medium">Light</th>
187
+ <th className="px-3 py-2 font-medium">Dark</th>
188
+ </tr>
189
+ </thead>
190
+ <tbody>
191
+ {tokens.map((t) => (
192
+ <tr key={t.name} className="border-b align-top last:border-0">
193
+ <td className="px-3 py-2">
194
+ <span className="font-mono text-foreground">--{t.name}</span>
195
+ {t.description && (
196
+ <span className="mt-0.5 block text-muted-foreground">{t.description}</span>
197
+ )}
198
+ </td>
199
+ <td className="px-3 py-2">
200
+ <span className="flex items-center gap-2">
201
+ <TokenSwatch value={t.light} />
202
+ <span className="font-mono text-foreground/80">{t.light}</span>
203
+ </span>
204
+ </td>
205
+ <td className="px-3 py-2">
206
+ <span className="flex items-center gap-2">
207
+ <TokenSwatch value={t.dark} />
208
+ <span className="font-mono text-foreground/80">{t.dark}</span>
209
+ </span>
210
+ </td>
211
+ </tr>
212
+ ))}
213
+ </tbody>
214
+ </table>
215
+ </div>
216
+ </div>
217
+ );
218
+ }
219
+
129
220
  export function LayersTab() {
130
221
  const [layers, setLayers] = useState<LayerEntry[]>([]);
131
222
  const [openLayers, setOpenLayers] = useState<Set<string>>(new Set());
@@ -137,6 +228,9 @@ export function LayersTab() {
137
228
  const [status, setStatus] = useState<SaveStatus>("idle");
138
229
  const [statusMessage, setStatusMessage] = useState<string>("");
139
230
  const [viewMode, setViewMode] = useState<ViewMode>("preview");
231
+ // null = loading; [] = loaded-but-empty. Only used by the synthetic
232
+ // semantic-tokens view.
233
+ const [semanticTokens, setSemanticTokens] = useState<SemanticToken[] | null>(null);
140
234
 
141
235
  // Load tree
142
236
  useEffect(() => {
@@ -156,6 +250,35 @@ export function LayersTab() {
156
250
  if (!activePath) return;
157
251
  setStatus("idle");
158
252
  setStatusMessage("");
253
+
254
+ // Synthetic semantic-tokens view: read tokens.json (the only non-layer
255
+ // path the file route allows) and pull the theme.light / theme.dark
256
+ // maps into a name → {light, dark} table. Always read-only.
257
+ if (activePath === SEMANTIC_VIEW) {
258
+ setFileType("read-only");
259
+ setSemanticTokens(null);
260
+ fetch(`/api/layers/file?path=${encodeURIComponent("packages/core/src/tokens.json")}`)
261
+ .then((r) => r.json())
262
+ .then((data) => {
263
+ try {
264
+ const parsed = JSON.parse(data.content ?? "{}");
265
+ const light = parsed?.theme?.light ?? {};
266
+ const dark = parsed?.theme?.dark ?? {};
267
+ const tokens: SemanticToken[] = Object.keys(light).map((name) => ({
268
+ name,
269
+ light: light[name]?.$value ?? "",
270
+ dark: dark[name]?.$value ?? "",
271
+ description: light[name]?.$description,
272
+ }));
273
+ setSemanticTokens(tokens);
274
+ } catch {
275
+ setSemanticTokens([]);
276
+ }
277
+ })
278
+ .catch(() => setSemanticTokens([]));
279
+ return;
280
+ }
281
+
159
282
  setFileType(getFileType(activePath));
160
283
  fetch(`/api/layers/file?path=${encodeURIComponent(activePath)}`)
161
284
  .then((r) => r.json())
@@ -234,8 +357,27 @@ export function LayersTab() {
234
357
  {open && (
235
358
  <div className="ml-5 border-l border-border">
236
359
  {layer.files.map((file) => {
237
- const fileName = file.split("/").pop() ?? file;
238
- const subPath = file.slice(layer.slug.length + 1);
360
+ // Show the path relative to the layer root rather than
361
+ // only the basename. Without this, every layer with a
362
+ // sub-discipline (e.g. `research/`) shows two
363
+ // "README.md" entries that look identical in the
364
+ // sidebar — clicking either is a coin flip. The
365
+ // sub-folder prefix renders muted so the filename
366
+ // stays visually dominant.
367
+ //
368
+ // Derive the name from the real path basename. Most
369
+ // files live under the layer's slug dir, but a few are
370
+ // mounted in from elsewhere (e.g. tokens.json lives at
371
+ // packages/core/src/tokens.json), so slicing by slug
372
+ // length would chew the start off the name
373
+ // ("…/tokens.json" → "json"). Only show a folder prefix
374
+ // for files genuinely nested inside the layer dir.
375
+ const withinLayer = file.startsWith(`${layer.slug}/`);
376
+ const subPath = withinLayer ? file.slice(layer.slug.length + 1) : file;
377
+ const lastSlash = subPath.lastIndexOf("/");
378
+ const folderPrefix =
379
+ withinLayer && lastSlash >= 0 ? subPath.slice(0, lastSlash + 1) : "";
380
+ const fileName = file.slice(file.lastIndexOf("/") + 1);
239
381
  const isActive = activePath === file;
240
382
  return (
241
383
  <button
@@ -250,11 +392,30 @@ export function LayersTab() {
250
392
  >
251
393
  <FileText className="h-3 w-3 shrink-0" />
252
394
  <span className="truncate" title={subPath}>
253
- {fileName}
395
+ {folderPrefix && (
396
+ <span className="text-muted-foreground/60">{folderPrefix}</span>
397
+ )}
398
+ <span>{fileName}</span>
254
399
  </span>
255
400
  </button>
256
401
  );
257
402
  })}
403
+ {layer.slug === "layer-4-semantic-tokens" && (
404
+ <button
405
+ type="button"
406
+ onClick={() => setActivePath(SEMANTIC_VIEW)}
407
+ className={`w-full flex items-center gap-2 pl-3 pr-2 py-1.5 text-xs rounded text-left ${
408
+ activePath === SEMANTIC_VIEW
409
+ ? "bg-primary/10 text-foreground"
410
+ : "text-muted-foreground hover:text-foreground hover:bg-accent/40"
411
+ }`}
412
+ >
413
+ <Palette className="h-3 w-3 shrink-0" strokeWidth={1.5} />
414
+ <span className="truncate" title="Resolved semantic tokens">
415
+ Semantic tokens
416
+ </span>
417
+ </button>
418
+ )}
258
419
  </div>
259
420
  )}
260
421
  </div>
@@ -277,9 +438,11 @@ export function LayersTab() {
277
438
  <>
278
439
  <header className="border-b px-6 py-3 flex items-center justify-between gap-4 shrink-0">
279
440
  <div className="min-w-0">
280
- <p className="text-xs text-muted-foreground font-mono truncate">{activePath}</p>
441
+ <p className="text-xs text-muted-foreground font-mono truncate">
442
+ {activePath === SEMANTIC_VIEW ? "packages/core/src/tokens.json → theme" : activePath}
443
+ </p>
281
444
  <h2 className="text-base font-semibold truncate">
282
- {activePath.split("/").pop()}
445
+ {activePath === SEMANTIC_VIEW ? "Semantic tokens" : activePath.split("/").pop()}
283
446
  </h2>
284
447
  </div>
285
448
  <div className="flex items-center gap-3 shrink-0">
@@ -323,7 +486,9 @@ export function LayersTab() {
323
486
  </div>
324
487
  </header>
325
488
 
326
- {fileType === "read-only" ? (
489
+ {activePath === SEMANTIC_VIEW ? (
490
+ <SemanticTokensView tokens={semanticTokens} />
491
+ ) : fileType === "read-only" ? (
327
492
  <div className="flex-1 rounded-none border-0 font-mono text-sm leading-relaxed overflow-auto bg-muted/30 p-6">
328
493
  <pre className="whitespace-pre-wrap break-words text-foreground/80">
329
494
  {prettyJsonOrRaw(content)}