@behavioral-agentic-design-system/core 0.8.3 → 0.9.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.
package/src/app/shell.tsx CHANGED
@@ -29,6 +29,7 @@ import { brand } from "@/brand.config";
29
29
  import { CustomizeTab } from "@behavioral-agentic-design-system/core/components/customize-tab";
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
+ import { DocsTab } from "@behavioral-agentic-design-system/core/components/docs-tab";
32
33
  import { BrandMark } from "@behavioral-agentic-design-system/core/components/brand-mark";
33
34
  import { OnboardingWizard } from "@behavioral-agentic-design-system/core/components/onboarding-wizard";
34
35
 
@@ -170,7 +171,8 @@ export type ShellProps = {
170
171
  * they need custom surfaces alongside the built-ins.
171
172
  */
172
173
  export const DEFAULT_TABS: ShellTab[] = [
173
- { value: "home", label: "Home", render: ({ goToTab }) => <HomeTab onBrowseComponents={() => goToTab("components")} /> },
174
+ { value: "home", label: "Home", render: ({ goToTab }) => <HomeTab onBrowseDocs={() => goToTab("docs")} onBrowseComponents={() => goToTab("components")} /> },
175
+ { value: "docs", label: "Docs", render: () => <DocsTab /> },
174
176
  { value: "components", label: "Components", render: ({ dark }) => <IframePreview dark={dark} src="/preview/components" /> },
175
177
  { value: "cards", label: "Cards", render: ({ dark }) => <IframePreview dark={dark} src="/preview/cards" /> },
176
178
  { value: "dashboard", label: "Dashboard", hidden: "md", render: ({ dark }) => <IframePreview dark={dark} src="/preview/dashboard" minWidth="1400px" /> },
@@ -227,33 +229,77 @@ export function Shell({ tabs, defaultTab }: ShellProps) {
227
229
  }, [activeTab]);
228
230
 
229
231
  // Tab changes flow through this so the choice is persisted for reload
230
- // restoration. The restore effect below reads it back on mount. Persisting
231
- // only on real changes (not on mount) means there's no race with the restore
232
- // read — sessionStorage is never clobbered with the default before it's read.
232
+ // restoration AND pushed onto the browser history stack. Persisting to
233
+ // sessionStorage only on real changes (not on mount) avoids racing the
234
+ // restore read. The pushState entry is what makes the browser Back button
235
+ // step through visited tabs instead of leaving the app entirely.
233
236
  const selectTab = useCallback((value: string) => {
234
237
  setActiveTab(value);
235
238
  try {
236
239
  window.sessionStorage.setItem(ACTIVE_TAB_KEY, value);
237
240
  } catch {}
241
+ try {
242
+ const url = new URL(window.location.href);
243
+ url.searchParams.set("tab", value);
244
+ window.history.pushState({ shellTab: value }, "", url);
245
+ } catch {}
238
246
  }, []);
239
247
 
240
- // Restore the pre-reload tab once on mount. Only restores a tab that still
241
- // exists in this shell's tab set, so a fork that drops a tab between sessions
242
- // falls back to the default instead of a blank panel.
248
+ // Restore the active tab once on mount, preferring an explicit ?tab= in the
249
+ // URL (a Back-nav landing or a shared deep link) over the persisted session
250
+ // tab. Only restores a tab that still exists in this shell's set, so a fork
251
+ // that drops a tab falls back to the default instead of a blank panel. Also
252
+ // seeds the current history entry with the resolved tab so a later Back to
253
+ // it carries state.
243
254
  useEffect(() => {
244
- let stored: string | null = null;
255
+ let target: string | null = null;
245
256
  try {
246
- stored = window.sessionStorage.getItem(ACTIVE_TAB_KEY);
257
+ target = new URL(window.location.href).searchParams.get("tab");
247
258
  } catch {}
248
- const target = stored;
249
- if (target && target !== initialTab && tabs.some((t) => t.value === target)) {
250
- setActiveTab(target);
251
- setSeen((prev) => (prev.has(target) ? prev : new Set(prev).add(target)));
259
+ if (!target || !tabs.some((t) => t.value === target)) {
260
+ try {
261
+ const stored = window.sessionStorage.getItem(ACTIVE_TAB_KEY);
262
+ if (stored && tabs.some((t) => t.value === stored)) target = stored;
263
+ } catch {}
264
+ }
265
+ const resolved = target && tabs.some((t) => t.value === target) ? target : initialTab;
266
+ if (resolved !== initialTab) {
267
+ setActiveTab(resolved);
268
+ setSeen((prev) => (prev.has(resolved) ? prev : new Set(prev).add(resolved)));
252
269
  }
253
- // Mount-only: restore the persisted tab a single time.
270
+ try {
271
+ const url = new URL(window.location.href);
272
+ if (resolved !== initialTab) url.searchParams.set("tab", resolved);
273
+ window.history.replaceState({ shellTab: resolved }, "", url);
274
+ } catch {}
275
+ // Mount-only: restore the tab a single time.
254
276
  // eslint-disable-next-line react-hooks/exhaustive-deps
255
277
  }, []);
256
278
 
279
+ // Browser Back / Forward: resolve the target tab from the history state (or
280
+ // the URL as a fallback) and apply it directly — no pushState, so we don't
281
+ // fight the browser's own back/forward stack. This is what keeps Back inside
282
+ // the app: each tab switch left a history entry, and popstate walks them.
283
+ useEffect(() => {
284
+ const onPop = (e: PopStateEvent) => {
285
+ const state = e.state as { shellTab?: unknown } | null;
286
+ let target = state && typeof state.shellTab === "string" ? state.shellTab : null;
287
+ if (!target) {
288
+ try {
289
+ target = new URL(window.location.href).searchParams.get("tab");
290
+ } catch {}
291
+ }
292
+ const resolved = target && tabs.some((t) => t.value === target) ? target : initialTab;
293
+ setActiveTab(resolved);
294
+ setSeen((prev) => (prev.has(resolved) ? prev : new Set(prev).add(resolved)));
295
+ try {
296
+ window.sessionStorage.setItem(ACTIVE_TAB_KEY, resolved);
297
+ } catch {}
298
+ };
299
+ window.addEventListener("popstate", onPop);
300
+ return () => window.removeEventListener("popstate", onPop);
301
+ }, [tabs, initialTab]);
302
+
257
303
  // Background preload: after the active tab has fully painted and idled,
258
304
  // mount every other tab so they load silently while the user is reading
259
305
  // the home tab. By the time someone clicks any other tab, its iframe is
@@ -424,7 +470,7 @@ export function Shell({ tabs, defaultTab }: ShellProps) {
424
470
  style={{ "--tabs-fade-duration": "260ms" } as React.CSSProperties}
425
471
  className="flex-1 flex flex-col overflow-hidden"
426
472
  >
427
- <div className="mt-2 mb-1 flex w-full items-center px-4 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
473
+ <div className="mt-2 mb-1 flex w-full items-center px-4 overflow-x-auto scrollbar-none">
428
474
  <TabsList className="bg-background text-muted-foreground inline-flex w-max shrink-0 items-center justify-center rounded-full px-0">
429
475
  {tabs.map((tab) => (
430
476
  <TabsTrigger
@@ -42,7 +42,7 @@ export function BrandMark({
42
42
  <span
43
43
  role="img"
44
44
  aria-label={label}
45
- className={cn("inline-flex items-center justify-center [&>svg]:h-full [&>svg]:w-full", toneClass, className)}
45
+ className={cn("inline-flex items-center justify-center [&>svg]:h-full [&>svg]:w-full [&>svg]:max-h-[200px]", toneClass, className)}
46
46
  style={{ width: size, height: size }}
47
47
  // SVG is sanitized server-side in /api/brand-mark before it lands in
48
48
  // brand-mark.json — script tags, on* handlers, and dangerous URL
@@ -0,0 +1,497 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
+ import {
5
+ BookOpen,
6
+ ChevronRight,
7
+ FileText,
8
+ Loader2,
9
+ Search,
10
+ ExternalLink,
11
+ } from "lucide-react";
12
+ import { Input } from "@behavioral-agentic-design-system/core/components/ui/input";
13
+ import { Button } from "@behavioral-agentic-design-system/core/components/ui/button";
14
+ import { Badge } from "@behavioral-agentic-design-system/core/components/ui/badge";
15
+ import { Dialog, DialogContent } from "@behavioral-agentic-design-system/core/components/ui/dialog";
16
+ import { MarkdownPreview } from "@behavioral-agentic-design-system/core/components/markdown-preview";
17
+ import { DOCS_INDEX, DOCS_TOTAL, type DocEntry, type DocGroup } from "@behavioral-agentic-design-system/core/data/docs-index";
18
+
19
+ // Persist last-viewed doc across reloads so the tab restores cleanly.
20
+ const ACTIVE_DOC_KEY = "bads:docs:active-path";
21
+
22
+ function findEntryByPath(path: string): DocEntry | undefined {
23
+ for (const group of DOCS_INDEX) {
24
+ const hit = group.entries.find((e) => e.path === path);
25
+ if (hit) return hit;
26
+ }
27
+ return undefined;
28
+ }
29
+
30
+ function flatEntries(): DocEntry[] {
31
+ return DOCS_INDEX.flatMap((g) => g.entries);
32
+ }
33
+
34
+ // Tiny fuzzy match: every search-token (split on whitespace) must appear
35
+ // somewhere in the haystack, case-insensitive. Good enough for ~60 docs;
36
+ // don't over-engineer until volume warrants it.
37
+ function matches(haystack: string, query: string): boolean {
38
+ if (!query.trim()) return true;
39
+ const h = haystack.toLowerCase();
40
+ return query
41
+ .toLowerCase()
42
+ .split(/\s+/)
43
+ .filter(Boolean)
44
+ .every((t) => h.includes(t));
45
+ }
46
+
47
+ export function DocsTab() {
48
+ const defaultEntry = DOCS_INDEX[0]?.entries[0];
49
+ const [activePath, setActivePath] = useState<string>(defaultEntry?.path ?? "");
50
+ const [content, setContent] = useState<string>("");
51
+ const [loading, setLoading] = useState<boolean>(false);
52
+ const [error, setError] = useState<string | null>(null);
53
+ const [paletteOpen, setPaletteOpen] = useState<boolean>(false);
54
+ const [paletteQuery, setPaletteQuery] = useState<string>("");
55
+ const [paletteIndex, setPaletteIndex] = useState<number>(0);
56
+ const paletteInputRef = useRef<HTMLInputElement | null>(null);
57
+
58
+ // Restore active doc on mount.
59
+ useEffect(() => {
60
+ try {
61
+ const stored = window.sessionStorage.getItem(ACTIVE_DOC_KEY);
62
+ if (stored && findEntryByPath(stored)) {
63
+ setActivePath(stored);
64
+ }
65
+ } catch {
66
+ // sessionStorage may be unavailable in private windows — skip restore.
67
+ }
68
+ }, []);
69
+
70
+ // Live navigation from the Home tab. The shell preloads (mounts) DocsTab
71
+ // before the user clicks any Home doc link, so the mount-once restore above
72
+ // can't catch a later click — it would stay stuck on the default (README).
73
+ // HomeTab dispatches this event so we switch the active doc live.
74
+ useEffect(() => {
75
+ const onNavigate = (e: Event) => {
76
+ const path = (e as CustomEvent<string>).detail;
77
+ if (path && findEntryByPath(path)) setActivePath(path);
78
+ };
79
+ window.addEventListener("bads:docs:navigate", onNavigate);
80
+ return () => window.removeEventListener("bads:docs:navigate", onNavigate);
81
+ }, []);
82
+
83
+ // Persist on change.
84
+ useEffect(() => {
85
+ if (!activePath) return;
86
+ try {
87
+ window.sessionStorage.setItem(ACTIVE_DOC_KEY, activePath);
88
+ } catch {}
89
+ }, [activePath]);
90
+
91
+ // Fetch the active doc's content.
92
+ useEffect(() => {
93
+ if (!activePath) return;
94
+ let cancelled = false;
95
+ setLoading(true);
96
+ setError(null);
97
+ fetch(`/api/layers/file?path=${encodeURIComponent(activePath)}`)
98
+ .then((res) => res.json())
99
+ .then((data: { content?: string; error?: string }) => {
100
+ if (cancelled) return;
101
+ if (data.error) {
102
+ setError(data.error);
103
+ setContent("");
104
+ } else {
105
+ setContent(data.content ?? "");
106
+ }
107
+ })
108
+ .catch((e) => {
109
+ if (cancelled) return;
110
+ setError(e instanceof Error ? e.message : "load failed");
111
+ })
112
+ .finally(() => {
113
+ if (!cancelled) setLoading(false);
114
+ });
115
+ return () => {
116
+ cancelled = true;
117
+ };
118
+ }, [activePath]);
119
+
120
+ // Global ⌘K / Ctrl-K opens the search palette.
121
+ useEffect(() => {
122
+ const onKey = (e: KeyboardEvent) => {
123
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
124
+ e.preventDefault();
125
+ setPaletteOpen((v) => !v);
126
+ }
127
+ };
128
+ window.addEventListener("keydown", onKey);
129
+ return () => window.removeEventListener("keydown", onKey);
130
+ }, []);
131
+
132
+ // When the palette opens, focus the input and reset state.
133
+ useEffect(() => {
134
+ if (paletteOpen) {
135
+ setPaletteQuery("");
136
+ setPaletteIndex(0);
137
+ // Defer focus so the dialog has mounted its input.
138
+ const id = window.setTimeout(() => paletteInputRef.current?.focus(), 20);
139
+ return () => window.clearTimeout(id);
140
+ }
141
+ }, [paletteOpen]);
142
+
143
+ const filteredFlat = useMemo(() => {
144
+ const q = paletteQuery.trim();
145
+ return flatEntries().filter((e) => matches(`${e.title} ${e.path} ${e.summary ?? ""}`, q));
146
+ }, [paletteQuery]);
147
+
148
+ // Sidebar items use the same matcher so sidebar + palette share behavior.
149
+ const sidebarGroups = useMemo<DocGroup[]>(() => {
150
+ const q = paletteQuery.trim();
151
+ if (!q) return DOCS_INDEX;
152
+ return DOCS_INDEX.map((g): DocGroup => ({
153
+ ...g,
154
+ entries: g.entries.filter((e) => matches(`${e.title} ${e.path} ${e.summary ?? ""}`, q)),
155
+ })).filter((g) => g.entries.length > 0);
156
+ }, [paletteQuery]);
157
+
158
+ const selectPath = useCallback((path: string) => {
159
+ setActivePath(path);
160
+ setPaletteOpen(false);
161
+ }, []);
162
+
163
+ // Intercept doc-to-doc links rendered inside markdown (e.g. `CAPABILITIES.md`,
164
+ // `prompts/setup.md`). Normalize the repo-relative href to an index path and,
165
+ // if it's a known doc, navigate in-app. Unknown targets (non-doc files like
166
+ // scripts/JSON) are swallowed rather than dead-ending on the private repo or a
167
+ // 404 — the click just does nothing on the public showcase.
168
+ const handleDocLink = useCallback(
169
+ (href: string) => {
170
+ const path = href.replace(/^\.?\//, "").split(/[#?]/)[0];
171
+ if (findEntryByPath(path)) selectPath(path);
172
+ },
173
+ [selectPath],
174
+ );
175
+
176
+ const activeEntry = findEntryByPath(activePath);
177
+
178
+ // Palette keyboard handling: arrow keys move selection, Enter selects.
179
+ const onPaletteKey = (e: React.KeyboardEvent<HTMLInputElement>) => {
180
+ if (e.key === "ArrowDown") {
181
+ e.preventDefault();
182
+ setPaletteIndex((i) => Math.min(i + 1, Math.max(0, filteredFlat.length - 1)));
183
+ } else if (e.key === "ArrowUp") {
184
+ e.preventDefault();
185
+ setPaletteIndex((i) => Math.max(0, i - 1));
186
+ } else if (e.key === "Enter") {
187
+ const hit = filteredFlat[paletteIndex];
188
+ if (hit) selectPath(hit.path);
189
+ } else if (e.key === "Escape") {
190
+ setPaletteOpen(false);
191
+ }
192
+ };
193
+
194
+ return (
195
+ <div data-slot="docs-tab" className="size-full flex gap-0">
196
+ {/* Sidebar — collapsible groups, doc rows, search affordance. */}
197
+ <aside
198
+ data-slot="docs-sidebar"
199
+ className="hidden w-72 shrink-0 flex-col border-r border-border bg-card md:flex"
200
+ aria-label="Documentation index"
201
+ >
202
+ <div className="flex shrink-0 items-center justify-between gap-2 border-b border-border px-4 py-3">
203
+ <div className="flex items-center gap-2">
204
+ <BookOpen className="size-4 text-primary" strokeWidth={1.5} />
205
+ <span className="text-sm font-semibold">Docs</span>
206
+ <Badge variant="secondary" className="ml-1">
207
+ {DOCS_TOTAL}
208
+ </Badge>
209
+ </div>
210
+ <Button
211
+ variant="ghost"
212
+ size="sm"
213
+ className="h-8 gap-1 px-2 text-xs"
214
+ onClick={() => setPaletteOpen(true)}
215
+ aria-label="Open docs search"
216
+ >
217
+ <Search className="size-3.5" strokeWidth={1.5} />
218
+ <span className="font-mono">⌘K</span>
219
+ </Button>
220
+ </div>
221
+ <div className="shrink-0 border-b border-border px-4 py-3">
222
+ <Input
223
+ type="search"
224
+ value={paletteQuery}
225
+ onChange={(e) => setPaletteQuery(e.target.value)}
226
+ placeholder="Filter docs…"
227
+ aria-label="Filter docs in sidebar"
228
+ className="h-9 text-sm"
229
+ />
230
+ </div>
231
+ <nav className="min-h-0 flex-1 overflow-y-auto px-2 py-3" aria-label="Documentation groups">
232
+ {sidebarGroups.length === 0 ? (
233
+ <p className="px-2 py-4 text-xs text-muted-foreground">
234
+ No docs match this filter.
235
+ </p>
236
+ ) : (
237
+ sidebarGroups.map((group) => (
238
+ <SidebarGroup
239
+ key={group.id}
240
+ group={group}
241
+ activePath={activePath}
242
+ onSelect={selectPath}
243
+ />
244
+ ))
245
+ )}
246
+ </nav>
247
+ </aside>
248
+
249
+ {/* Reading pane (and mobile top-bar with Browse) */}
250
+ <main
251
+ data-slot="docs-reading-pane"
252
+ className="flex min-w-0 flex-1 flex-col bg-background"
253
+ aria-label="Documentation reader"
254
+ >
255
+ {/* Mobile-only top bar with the Browse affordance. */}
256
+ <div className="flex shrink-0 items-center gap-2 border-b border-border bg-card px-4 py-3 md:hidden">
257
+ <BookOpen className="size-4 text-primary" strokeWidth={1.5} />
258
+ <span className="text-sm font-semibold">Docs</span>
259
+ <Badge variant="secondary" className="ml-1">
260
+ {DOCS_TOTAL}
261
+ </Badge>
262
+ <Button
263
+ variant="outline"
264
+ size="sm"
265
+ className="ml-auto h-9 gap-2 px-3"
266
+ onClick={() => setPaletteOpen(true)}
267
+ aria-label="Open docs search"
268
+ >
269
+ <Search className="size-3.5" strokeWidth={1.5} />
270
+ <span className="text-sm">Browse</span>
271
+ </Button>
272
+ </div>
273
+
274
+ <ReadingHeader activeEntry={activeEntry} activePath={activePath} />
275
+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-8 lg:px-10">
276
+ {loading ? (
277
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
278
+ <Loader2 className="size-4 animate-spin" strokeWidth={1.5} />
279
+ Loading {activeEntry?.title ?? activePath}…
280
+ </div>
281
+ ) : error ? (
282
+ <div className="rounded-md border border-destructive/50 bg-destructive/5 p-4 text-sm text-destructive">
283
+ Couldn&apos;t load <code className="font-mono text-xs">{activePath}</code>: {error}
284
+ </div>
285
+ ) : content ? (
286
+ <MarkdownPreview source={content} maxWidth="max-w-3xl" onDocLink={handleDocLink} />
287
+ ) : (
288
+ <p className="text-sm text-muted-foreground">No content.</p>
289
+ )}
290
+ </div>
291
+ </main>
292
+
293
+ {/* Command palette */}
294
+ <Dialog open={paletteOpen} onOpenChange={setPaletteOpen}>
295
+ <DialogContent className="max-w-2xl gap-0 p-0">
296
+ <div className="border-b border-border px-4 py-3">
297
+ <div className="flex items-center gap-2">
298
+ <Search className="size-4 text-muted-foreground" strokeWidth={1.5} />
299
+ <Input
300
+ ref={paletteInputRef}
301
+ type="search"
302
+ value={paletteQuery}
303
+ onChange={(e) => {
304
+ setPaletteQuery(e.target.value);
305
+ setPaletteIndex(0);
306
+ }}
307
+ onKeyDown={onPaletteKey}
308
+ placeholder={`Search ${DOCS_TOTAL} docs…`}
309
+ aria-label="Search documentation"
310
+ className="h-9 border-0 px-0 text-sm shadow-none focus-visible:ring-0"
311
+ />
312
+ <span className="font-mono text-xs text-muted-foreground">
313
+ {filteredFlat.length}
314
+ </span>
315
+ </div>
316
+ </div>
317
+ <div className="max-h-[60vh] overflow-y-auto">
318
+ {filteredFlat.length === 0 ? (
319
+ <p className="px-4 py-6 text-sm text-muted-foreground">
320
+ No docs match &ldquo;{paletteQuery}&rdquo;.
321
+ </p>
322
+ ) : (
323
+ <ul className="py-2">
324
+ {filteredFlat.map((entry, idx) => (
325
+ <li key={entry.path}>
326
+ <button
327
+ type="button"
328
+ onClick={() => selectPath(entry.path)}
329
+ onMouseEnter={() => setPaletteIndex(idx)}
330
+ data-active={idx === paletteIndex}
331
+ className="group flex w-full items-start gap-3 overflow-hidden px-4 py-2 text-left transition-colors hover:bg-accent/50 data-[active=true]:bg-accent"
332
+ style={{
333
+ transitionDuration: "var(--duration-fast)",
334
+ transitionTimingFunction: "var(--ease-out)",
335
+ }}
336
+ >
337
+ <FileText
338
+ className="mt-0.5 size-4 shrink-0 text-muted-foreground"
339
+ strokeWidth={1.5}
340
+ />
341
+ <span className="flex min-w-0 flex-1 flex-col">
342
+ <span className="truncate text-sm font-medium" title={entry.title}>
343
+ {entry.title}
344
+ </span>
345
+ <span
346
+ className="truncate font-mono text-xs text-muted-foreground"
347
+ title={entry.path}
348
+ >
349
+ {entry.path}
350
+ </span>
351
+ {entry.summary ? (
352
+ <span className="mt-1 truncate text-xs text-muted-foreground">
353
+ {entry.summary}
354
+ </span>
355
+ ) : null}
356
+ </span>
357
+ </button>
358
+ </li>
359
+ ))}
360
+ </ul>
361
+ )}
362
+ </div>
363
+ <div className="flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground">
364
+ <span className="flex items-center gap-3">
365
+ <span>
366
+ <kbd className="rounded border bg-background px-1.5 py-0.5 font-mono">↑↓</kbd>{" "}
367
+ navigate
368
+ </span>
369
+ <span>
370
+ <kbd className="rounded border bg-background px-1.5 py-0.5 font-mono">↵</kbd>{" "}
371
+ open
372
+ </span>
373
+ <span>
374
+ <kbd className="rounded border bg-background px-1.5 py-0.5 font-mono">esc</kbd>{" "}
375
+ close
376
+ </span>
377
+ </span>
378
+ <span className="font-mono">⌘K toggles</span>
379
+ </div>
380
+ </DialogContent>
381
+ </Dialog>
382
+ </div>
383
+ );
384
+ }
385
+
386
+ function SidebarGroup({
387
+ group,
388
+ activePath,
389
+ onSelect,
390
+ }: {
391
+ group: DocGroup;
392
+ activePath: string;
393
+ onSelect: (path: string) => void;
394
+ }) {
395
+ const containsActive = group.entries.some((e) => e.path === activePath);
396
+ const [open, setOpen] = useState<boolean>(containsActive);
397
+ useEffect(() => {
398
+ if (containsActive) setOpen(true);
399
+ }, [containsActive]);
400
+
401
+ return (
402
+ <div className="mb-1">
403
+ <button
404
+ type="button"
405
+ onClick={() => setOpen((v) => !v)}
406
+ className="flex w-full items-center justify-between gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-semibold uppercase tracking-wide text-muted-foreground transition-colors hover:bg-accent/50"
407
+ style={{
408
+ transitionDuration: "var(--duration-fast)",
409
+ transitionTimingFunction: "var(--ease-out)",
410
+ }}
411
+ aria-expanded={open}
412
+ aria-controls={`docs-group-${group.id}`}
413
+ >
414
+ <span className="truncate" title={group.label}>
415
+ {group.label}
416
+ </span>
417
+ <ChevronRight
418
+ className="size-3.5 shrink-0 transition-transform"
419
+ strokeWidth={1.5}
420
+ style={{
421
+ transform: open ? "rotate(90deg)" : "rotate(0deg)",
422
+ transitionDuration: "var(--duration-base)",
423
+ transitionTimingFunction: "var(--ease-spring)",
424
+ }}
425
+ />
426
+ </button>
427
+ {open ? (
428
+ <ul id={`docs-group-${group.id}`} className="mt-0.5 mb-2">
429
+ {group.entries.map((entry) => {
430
+ const active = entry.path === activePath;
431
+ return (
432
+ <li key={entry.path}>
433
+ <button
434
+ type="button"
435
+ onClick={() => onSelect(entry.path)}
436
+ data-active={active}
437
+ aria-current={active ? "page" : undefined}
438
+ className="flex w-full items-center gap-2 overflow-hidden rounded-sm px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent/50 data-[active=true]:bg-accent data-[active=true]:font-medium"
439
+ style={{
440
+ transitionDuration: "var(--duration-fast)",
441
+ transitionTimingFunction: "var(--ease-out)",
442
+ }}
443
+ >
444
+ <span className="block min-w-0 flex-1 truncate" title={entry.title}>
445
+ {entry.title}
446
+ </span>
447
+ </button>
448
+ </li>
449
+ );
450
+ })}
451
+ </ul>
452
+ ) : null}
453
+ </div>
454
+ );
455
+ }
456
+
457
+ function ReadingHeader({
458
+ activeEntry,
459
+ activePath,
460
+ }: {
461
+ activeEntry: DocEntry | undefined;
462
+ activePath: string;
463
+ }) {
464
+ // Only link out to the source on GitHub when a PUBLIC repo base is configured
465
+ // (NEXT_PUBLIC_DOCS_REPO_URL, e.g. https://github.com/org/repo). The default
466
+ // is unset, so the showcase never renders a link to a private repo that
467
+ // visitors can't open. Forks with a public repo opt in via the env var.
468
+ const repoBase = process.env.NEXT_PUBLIC_DOCS_REPO_URL;
469
+ const githubUrl =
470
+ repoBase && activePath ? `${repoBase.replace(/\/$/, "")}/blob/main/${activePath}` : null;
471
+ return (
472
+ <header className="flex shrink-0 items-start justify-between gap-4 border-b border-border bg-card px-6 py-4 lg:px-10">
473
+ <div className="min-w-0 flex-1">
474
+ <h1 className="truncate text-xl font-semibold tracking-tight" title={activeEntry?.title ?? activePath}>
475
+ {activeEntry?.title ?? activePath}
476
+ </h1>
477
+ <p
478
+ className="mt-0.5 truncate font-mono text-xs text-muted-foreground"
479
+ title={activePath}
480
+ >
481
+ {activePath}
482
+ </p>
483
+ {activeEntry?.summary ? (
484
+ <p className="mt-2 max-w-2xl text-sm text-muted-foreground">{activeEntry.summary}</p>
485
+ ) : null}
486
+ </div>
487
+ {githubUrl ? (
488
+ <Button asChild variant="ghost" size="sm" className="shrink-0">
489
+ <a href={githubUrl} target="_blank" rel="noreferrer" className="gap-1.5">
490
+ <span className="text-sm">View on GitHub</span>
491
+ <ExternalLink className="size-3.5" strokeWidth={1.5} />
492
+ </a>
493
+ </Button>
494
+ ) : null}
495
+ </header>
496
+ );
497
+ }