@nswds/ui 4.3.0 → 4.4.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.
@@ -0,0 +1,357 @@
1
+ "use client"
2
+ import { jsxs, jsx } from 'react/jsx-runtime';
3
+ import React from 'react';
4
+ import { cn } from '../lib/utils.js';
5
+ import { Button } from '../components/button.js';
6
+ import { Link } from '../components/link.js';
7
+ import { IconChevronRight } from '../icons/chevron-right.js';
8
+ import { IconClose } from '../icons/close.js';
9
+ import { IconWest } from '../icons/west.js';
10
+
11
+ const PUSH_MENU_DURATION_MS = 300;
12
+ function buildLevelId(path) {
13
+ return `level-${path.length > 0 ? path.join("--") : "root"}`;
14
+ }
15
+ function generatePushMenuBreadcrumb(levels, maxLength = 50) {
16
+ const first = levels[0];
17
+ if (levels.length <= 1) {
18
+ return first?.title ?? "Menu";
19
+ }
20
+ const full = levels.map((level) => level.title).join(" \u203A ");
21
+ if (full.length <= maxLength) {
22
+ return full;
23
+ }
24
+ const last = levels.at(-1);
25
+ const secondLast = levels.at(-2);
26
+ if (levels.length > 3 && first && last && secondLast) {
27
+ return `${first.title} \u203A \u2026 \u203A ${secondLast.title} \u203A ${last.title}`;
28
+ }
29
+ return `${full.slice(0, maxLength - 1)}\u2026`;
30
+ }
31
+ function warnIfNavigationMalformed(navigation) {
32
+ if (process.env.NODE_ENV === "production") {
33
+ return;
34
+ }
35
+ if (!Array.isArray(navigation) || navigation.length === 0) {
36
+ console.warn("[nswds/ui] PushMenu received no navigation items \u2014 the menu renders empty.");
37
+ return;
38
+ }
39
+ const seen = /* @__PURE__ */ new Set();
40
+ const visit = (items) => {
41
+ for (const item of items) {
42
+ if (!item?.id || !item.title) {
43
+ console.warn("[nswds/ui] PushMenu navigation item is missing an `id` or `title`:", item);
44
+ continue;
45
+ }
46
+ if (seen.has(item.id)) {
47
+ console.warn(
48
+ `[nswds/ui] PushMenu navigation contains duplicate id "${item.id}" \u2014 level ids and focus restoration track items by id, so ids must be unique across the whole tree.`
49
+ );
50
+ }
51
+ seen.add(item.id);
52
+ if (!item.href && !item.links?.length) {
53
+ console.warn(
54
+ `[nswds/ui] PushMenu item "${item.id}" has neither an href nor children \u2014 it renders as a button that only fires onItemClick.`
55
+ );
56
+ }
57
+ if (item.links?.length) {
58
+ visit(item.links);
59
+ }
60
+ }
61
+ };
62
+ visit(navigation);
63
+ }
64
+ const itemBaseClassName = [
65
+ // min-h-11 guarantees the 44px minimum target size (WCAG 2.2, 2.5.8 Target
66
+ // Size) even for single-line rows with compact padding overrides.
67
+ "relative flex min-h-11 w-full cursor-pointer items-center justify-between gap-x-6 border-l p-4 text-left text-base",
68
+ "transition-colors motion-reduce:transition-none",
69
+ "hover:border-primary-800 hover:bg-primary-800/10 dark:hover:border-primary-200 dark:hover:bg-primary-200/10",
70
+ // Inset outline (negative offset): the levels scroll inside an
71
+ // overflow-hidden root, so an outward offset would be clipped on the first
72
+ // and last rows (WCAG 2.2, 2.4.13 Focus Appearance).
73
+ "focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-primary-800 dark:focus-visible:outline-primary-200"
74
+ ].join(" ");
75
+ const itemActiveClassName = "border-primary-800 bg-primary-800/10 font-semibold text-primary-800 dark:border-primary-200 dark:bg-primary-200/10 dark:text-primary-200";
76
+ const itemInactiveClassName = "border-transparent text-popover-foreground";
77
+ function PushMenu({
78
+ navigation,
79
+ currentHref,
80
+ title = "Menu",
81
+ onItemClick,
82
+ onNavigate,
83
+ onClose,
84
+ showBreadcrumbs = true,
85
+ durationMs = PUSH_MENU_DURATION_MS,
86
+ backLabel = "Back",
87
+ closeLabel = "Close menu",
88
+ headingLevel = 2,
89
+ className,
90
+ style,
91
+ "aria-label": ariaLabel,
92
+ ref,
93
+ ...props
94
+ }) {
95
+ const [navigationHistory, setNavigationHistory] = React.useState(() => [
96
+ { items: navigation, title, depth: 1, id: buildLevelId([]) }
97
+ ]);
98
+ const [animationState, setAnimationState] = React.useState("idle");
99
+ const [isAnimationStarted, setIsAnimationStarted] = React.useState(false);
100
+ const containerRef = React.useRef(null);
101
+ const timeoutRef = React.useRef(null);
102
+ const pendingFocusRef = React.useRef(null);
103
+ warnIfNavigationMalformed(navigation);
104
+ React.useEffect(() => {
105
+ return () => {
106
+ if (timeoutRef.current !== null) {
107
+ window.clearTimeout(timeoutRef.current);
108
+ }
109
+ };
110
+ }, []);
111
+ React.useLayoutEffect(() => {
112
+ const pending = pendingFocusRef.current;
113
+ if (!pending) {
114
+ return;
115
+ }
116
+ pendingFocusRef.current = null;
117
+ const level = containerRef.current?.querySelector(
118
+ `[data-level-id="${CSS.escape(pending.levelId)}"]`
119
+ );
120
+ if (!level) {
121
+ return;
122
+ }
123
+ const target = pending.itemId ? level.querySelector(`[data-item-id="${CSS.escape(pending.itemId)}"]`) : level.querySelector('[data-slot="push-menu-back-button"]') ?? level.querySelector(
124
+ '[data-slot="push-menu-item"], [data-slot="push-menu-link"]'
125
+ );
126
+ target?.focus({ preventScroll: true });
127
+ }, [navigationHistory, animationState]);
128
+ const breadcrumb = React.useMemo(
129
+ // During a back slide the trail already excludes the departing level —
130
+ // the breadcrumb tracks the level the user is arriving at (see
131
+ // activeIndex below), same as the live region.
132
+ () => generatePushMenuBreadcrumb(
133
+ animationState === "sliding-backward" ? navigationHistory.slice(0, -1) : navigationHistory
134
+ ),
135
+ [navigationHistory, animationState]
136
+ );
137
+ function navigateToSubmenu(item) {
138
+ if (!item.links?.length || animationState !== "idle") {
139
+ return;
140
+ }
141
+ const levelPath = [
142
+ ...navigationHistory.flatMap((level) => level.parentItem ? [level.parentItem.id] : []),
143
+ item.id
144
+ ];
145
+ const currentDepth = navigationHistory.at(-1)?.depth ?? 1;
146
+ const newLevel = {
147
+ items: item.links,
148
+ title: item.title,
149
+ parentItem: item,
150
+ depth: currentDepth + 1,
151
+ id: buildLevelId(levelPath)
152
+ };
153
+ const newHistory = [...navigationHistory, newLevel];
154
+ pendingFocusRef.current = { levelId: newLevel.id };
155
+ setNavigationHistory(newHistory);
156
+ setAnimationState("sliding-forward");
157
+ setIsAnimationStarted(false);
158
+ requestAnimationFrame(() => {
159
+ containerRef.current?.getBoundingClientRect();
160
+ setIsAnimationStarted(true);
161
+ });
162
+ timeoutRef.current = window.setTimeout(() => {
163
+ setAnimationState("idle");
164
+ setIsAnimationStarted(false);
165
+ onNavigate?.(newLevel, newHistory);
166
+ }, durationMs);
167
+ }
168
+ function navigateBack() {
169
+ if (navigationHistory.length <= 1 || animationState !== "idle") {
170
+ return;
171
+ }
172
+ const popped = navigationHistory.at(-1);
173
+ const revealed = navigationHistory.at(-2);
174
+ if (!revealed) {
175
+ return;
176
+ }
177
+ pendingFocusRef.current = { levelId: revealed.id, itemId: popped?.parentItem?.id };
178
+ setAnimationState("sliding-backward");
179
+ timeoutRef.current = window.setTimeout(() => {
180
+ const newHistory = navigationHistory.slice(0, -1);
181
+ setNavigationHistory(newHistory);
182
+ setAnimationState("idle");
183
+ onNavigate?.(revealed, newHistory);
184
+ }, durationMs);
185
+ }
186
+ const currentLevel = navigationHistory.at(-1);
187
+ if (!currentLevel) {
188
+ return null;
189
+ }
190
+ const isAnimating = animationState !== "idle";
191
+ const activeIndex = animationState === "sliding-backward" ? navigationHistory.length - 2 : navigationHistory.length - 1;
192
+ const activeLevel = navigationHistory[activeIndex] ?? currentLevel;
193
+ const HeadingTag = `h${headingLevel}`;
194
+ return /* @__PURE__ */ jsxs(
195
+ "nav",
196
+ {
197
+ "data-slot": "push-menu",
198
+ "aria-label": ariaLabel ?? title,
199
+ "data-animating": isAnimating || void 0,
200
+ ...props,
201
+ className: cn(
202
+ "relative isolate h-full overflow-hidden bg-popover text-popover-foreground",
203
+ className
204
+ ),
205
+ style: { ...style, "--push-menu-duration": `${durationMs}ms` },
206
+ ref: (node) => {
207
+ containerRef.current = node;
208
+ if (typeof ref === "function") {
209
+ ref(node);
210
+ } else if (ref) {
211
+ ref.current = node;
212
+ }
213
+ },
214
+ children: [
215
+ /* @__PURE__ */ jsx("div", { "data-slot": "push-menu-live-region", "aria-live": "polite", className: "sr-only", children: activeLevel.depth > 1 ? `${activeLevel.title}, level ${activeLevel.depth}` : activeLevel.title }),
216
+ navigationHistory.map((level, index) => {
217
+ const isTopLevel = index === navigationHistory.length - 1;
218
+ const isActiveLevel = index === activeIndex;
219
+ const shouldShowBackButton = level.depth > 1;
220
+ let translateX = 0;
221
+ if (animationState === "sliding-forward") {
222
+ translateX = isTopLevel ? isAnimationStarted ? 0 : 100 : 0;
223
+ } else if (animationState === "sliding-backward") {
224
+ translateX = isTopLevel ? 100 : 0;
225
+ }
226
+ const isSliding = isTopLevel && (animationState === "sliding-backward" || animationState === "sliding-forward" && isAnimationStarted);
227
+ return /* @__PURE__ */ jsxs(
228
+ "div",
229
+ {
230
+ "data-slot": "push-menu-level",
231
+ "data-level-id": level.id,
232
+ "data-current": isActiveLevel || void 0,
233
+ inert: !isActiveLevel,
234
+ className: cn(
235
+ "absolute inset-0 flex h-full w-full flex-col bg-popover will-change-transform",
236
+ isSliding ? "transition-transform duration-(--push-menu-duration) ease-out motion-reduce:transition-none" : "transition-none"
237
+ ),
238
+ style: { transform: `translateX(${translateX}%)`, zIndex: index + 1 },
239
+ children: [
240
+ /* @__PURE__ */ jsxs(
241
+ "div",
242
+ {
243
+ "data-slot": "push-menu-header",
244
+ className: "flex min-h-11 items-center gap-1 border-b border-border px-2 py-2",
245
+ children: [
246
+ shouldShowBackButton && /* @__PURE__ */ jsx(
247
+ Button,
248
+ {
249
+ "data-slot": "push-menu-back-button",
250
+ variant: "ghost",
251
+ color: "primary",
252
+ size: "sm",
253
+ leadingVisual: IconWest,
254
+ onClick: navigateBack,
255
+ className: cn(isAnimating && "pointer-events-none"),
256
+ children: backLabel
257
+ }
258
+ ),
259
+ /* @__PURE__ */ jsx(
260
+ HeadingTag,
261
+ {
262
+ "data-slot": "push-menu-title",
263
+ className: "min-w-0 flex-1 truncate px-2 text-base font-semibold",
264
+ children: level.title
265
+ }
266
+ ),
267
+ onClose && /* @__PURE__ */ jsx(
268
+ Button,
269
+ {
270
+ "data-slot": "push-menu-close-button",
271
+ variant: "ghost",
272
+ color: "grey",
273
+ size: "icon",
274
+ "aria-label": closeLabel,
275
+ leadingVisual: IconClose,
276
+ onClick: onClose
277
+ }
278
+ )
279
+ ]
280
+ }
281
+ ),
282
+ showBreadcrumbs && isActiveLevel && level.depth > 1 && // aria-hidden: the trail repeats what the heading and live
283
+ // region already announce, and "›" separators read poorly in AT.
284
+ /* @__PURE__ */ jsx(
285
+ "p",
286
+ {
287
+ "data-slot": "push-menu-breadcrumb",
288
+ "aria-hidden": "true",
289
+ className: "truncate border-b border-border px-4 py-2 text-xs text-muted-foreground",
290
+ children: breadcrumb
291
+ }
292
+ ),
293
+ /* @__PURE__ */ jsx("div", { "data-slot": "push-menu-items", className: "flex-1 overflow-y-auto", children: /* @__PURE__ */ jsx("ul", { role: "list", className: "m-0 list-none divide-y divide-border p-0", children: level.items.map((item) => {
294
+ const hasChildren = Boolean(item.links?.length);
295
+ const isActive = item.href != null && item.href === currentHref;
296
+ return /* @__PURE__ */ jsx("li", { children: hasChildren ? /* @__PURE__ */ jsxs(
297
+ "button",
298
+ {
299
+ type: "button",
300
+ "data-slot": "push-menu-item",
301
+ "data-item-id": item.id,
302
+ onClick: () => navigateToSubmenu(item),
303
+ className: cn(
304
+ itemBaseClassName,
305
+ isActive ? itemActiveClassName : itemInactiveClassName,
306
+ isAnimating && "pointer-events-none"
307
+ ),
308
+ children: [
309
+ /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate", children: item.title }),
310
+ /* @__PURE__ */ jsx(IconChevronRight, { "aria-hidden": "true", className: "size-5 shrink-0" })
311
+ ]
312
+ }
313
+ ) : item.href ? /* @__PURE__ */ jsx(
314
+ Link,
315
+ {
316
+ variant: "unstyled",
317
+ "data-slot": "push-menu-link",
318
+ "data-item-id": item.id,
319
+ href: item.href,
320
+ "aria-current": isActive ? "page" : void 0,
321
+ onClick: () => onItemClick?.(item),
322
+ className: cn(
323
+ itemBaseClassName,
324
+ isActive ? itemActiveClassName : itemInactiveClassName,
325
+ isAnimating && "pointer-events-none"
326
+ ),
327
+ children: /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate", children: item.title })
328
+ }
329
+ ) : /* @__PURE__ */ jsx(
330
+ "button",
331
+ {
332
+ type: "button",
333
+ "data-slot": "push-menu-item",
334
+ "data-item-id": item.id,
335
+ onClick: () => onItemClick?.(item),
336
+ className: cn(
337
+ itemBaseClassName,
338
+ itemInactiveClassName,
339
+ isAnimating && "pointer-events-none"
340
+ ),
341
+ children: /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate", children: item.title })
342
+ }
343
+ ) }, item.id);
344
+ }) }) })
345
+ ]
346
+ },
347
+ level.id
348
+ );
349
+ })
350
+ ]
351
+ }
352
+ );
353
+ }
354
+
355
+ export { PUSH_MENU_DURATION_MS, PushMenu, generatePushMenuBreadcrumb };
356
+ //# sourceMappingURL=push-menu.js.map
357
+ //# sourceMappingURL=push-menu.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/components/push-menu.tsx"],"names":[],"mappings":";;;;;;;;;AA0BA,MAAM,qBAAA,GAAwB;AA2B9B,SAAS,aAAa,IAAA,EAAwB;AAC5C,EAAA,OAAO,CAAA,MAAA,EAAS,KAAK,MAAA,GAAS,CAAA,GAAI,KAAK,IAAA,CAAK,IAAI,IAAI,MAAM,CAAA,CAAA;AAC5D;AASA,SAAS,0BAAA,CAA2B,MAAA,EAA6B,SAAA,GAAY,EAAA,EAAY;AACvF,EAAA,MAAM,KAAA,GAAQ,OAAO,CAAC,CAAA;AACtB,EAAA,IAAI,MAAA,CAAO,UAAU,CAAA,EAAG;AACtB,IAAA,OAAO,OAAO,KAAA,IAAS,MAAA;AAAA,EACzB;AAEA,EAAA,MAAM,IAAA,GAAO,OAAO,GAAA,CAAI,CAAC,UAAU,KAAA,CAAM,KAAK,CAAA,CAAE,IAAA,CAAK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AA,sBACV,gBAAc,IAAA,CAAK,EAAA;AAAA,sBACnB,MAAM,IAAA,CAAK,IAAA;AAAA,sBACX,cAAA,EAAc,WAAW,MAAA,GAAS,MAAA;AAAA,sBAClC,OAAA,EAAS,MAAM,WAAA,GAAc,IAAI,CAAA;AAAA,sBACjC,SAAA,EAAW,EAAA;AAAA,wBACT,iBAAA;AAAA,wBACA,WAAW,mBAAA,GAAsB,qBAAA;AAAA,wBACjC,WAAA,IAAe;AAAA,uBACjB;AAAA,sBAEA,QAAA,kBAAA,GAAA,CAAC,MAAA,EAAA,EAAK,SAAA,EAAU,yBAAA,EAA2B,eAAK,KAAA,EAAM;AAAA;AAAA,mBACxD,mBAEA,GAAA;AAAA,oBAAC,QAAA;AAAA,oBAAA;AAAA,sBACC,IAAA,EAAK,QAAA;AAAA,sBACL,WAAA,EAAU,gBAAA;AAAA,sBACV,gBAAc,IAAA,CAAK,EAAA;AAAA,sBACnB,OAAA,EAAS,MAAM,WAAA,GAAc,IAAI,CAAA;AAAA,sBACjC,SAAA,EAAW,EAAA;AAAA,wBACT,iBAAA;AAAA,wBACA,qBAAA;AAAA,wBACA,WAAA,IAAe;AAAA,uBACjB;AAAA,sBAEA,QAAA,kBAAA,GAAA,CAAC,MAAA,EAAA,EAAK,SAAA,EAAU,yBAAA,EAA2B,eAAK,KAAA,EAAM;AAAA;AAAA,mBACxD,EAAA,EA7CK,KAAK,EA+Cd,CAAA;AAAA,gBAEJ,CAAC,GACH,CAAA,EACF;AAAA;AAAA,aAAA;AAAA,YA7HK,KAAA,CAAM;AAAA,WA8Hb;AAAA,QAEJ,CAAC;AAAA;AAAA;AAAA,GACH;AAEJ","file":"push-menu.js","sourcesContent":["'use client'\n\nimport React from 'react'\n\nimport { cn } from '../lib/utils.js'\n\nimport { Button } from '../components/button.js'\nimport { Link } from '../components/link.js'\nimport { IconChevronRight } from '../icons/chevron-right.js'\nimport { IconClose } from '../icons/close.js'\nimport { IconWest } from '../icons/west.js'\n\n/**\n * Default slide duration for level transitions, in milliseconds — the default\n * of the `durationMs` prop.\n *\n * COUPLING: `durationMs` drives BOTH the `--push-menu-duration` custom\n * property (set inline on the root, read by the CSS transition) and the state\n * machine's `setTimeout`s (which settle the animation state, pop levels, and\n * schedule focus restoration). Do not override the custom property directly —\n * that changes only the visual duration while the state machine still settles\n * on `durationMs`, desyncing the two; pass `durationMs` instead. Under\n * `prefers-reduced-motion` the slide is skipped (`motion-reduce:\n * transition-none`) but the state machine still waits the full duration; the\n * menu is simply \"settled early\" for those users, never broken.\n */\nconst PUSH_MENU_DURATION_MS = 300\n\n/** A node in the menu tree. Items with `links` drill in; items with `href` navigate. */\ntype PushMenuItem = {\n /** Unique across the whole tree — level ids and focus restoration track items by id. */\n id: string\n /** Visible label. */\n title: string\n /** Navigation target for leaf items. Ignored for drilling when `links` is non-empty. */\n href?: string\n /** Child items. A non-empty array makes this item a drill-in button, not a link. */\n links?: PushMenuItem[]\n}\n\n/** One entry in the level stack — the root level plus one per drill-in. */\ntype PushMenuLevel = {\n id: string\n title: string\n /** 1 for the root level, incrementing per drill-in. */\n depth: number\n items: PushMenuItem[]\n /** The item whose activation opened this level. Absent on the root level. */\n parentItem?: PushMenuItem\n}\n\ntype PushMenuAnimationState = 'idle' | 'sliding-forward' | 'sliding-backward'\n\nfunction buildLevelId(path: string[]): string {\n return `level-${path.length > 0 ? path.join('--') : 'root'}`\n}\n\n/**\n * Collapses a trail of level titles into a single \"A › B › C\" string, keeping\n * the ends and eliding the middle once it outgrows `maxLength`. Exported so an\n * app can render the same trail outside the menu (e.g. in a sheet header).\n * Prefixed with \"PushMenu\" to avoid colliding with a future breadcrumb\n * component in the package barrel.\n */\nfunction generatePushMenuBreadcrumb(levels: { title: string }[], maxLength = 50): string {\n const first = levels[0]\n if (levels.length <= 1) {\n return first?.title ?? 'Menu'\n }\n\n const full = levels.map((level) => level.title).join(' › ')\n if (full.length <= maxLength) {\n return full\n }\n\n const last = levels.at(-1)\n const secondLast = levels.at(-2)\n if (levels.length > 3 && first && last && secondLast) {\n return `${first.title} › … › ${secondLast.title} › ${last.title}`\n }\n\n return `${full.slice(0, maxLength - 1)}…`\n}\n\n/**\n * Dev-only guard, mirroring `warnIfIconButtonUnlabelled` in button.tsx. It\n * replaces the nswds-app source's rendered \"Navigation Error\" fallback panel:\n * malformed navigation data is a programming error, not a runtime state a user\n * should ever see, so the design system surfaces it to the developer console\n * and renders what it can instead of shipping error chrome. No-op in\n * production.\n */\nfunction warnIfNavigationMalformed(navigation: PushMenuItem[]) {\n if (process.env.NODE_ENV === 'production') {\n return\n }\n if (!Array.isArray(navigation) || navigation.length === 0) {\n console.warn('[nswds/ui] PushMenu received no navigation items — the menu renders empty.')\n return\n }\n const seen = new Set<string>()\n const visit = (items: PushMenuItem[]) => {\n for (const item of items) {\n if (!item?.id || !item.title) {\n console.warn('[nswds/ui] PushMenu navigation item is missing an `id` or `title`:', item)\n continue\n }\n if (seen.has(item.id)) {\n console.warn(\n `[nswds/ui] PushMenu navigation contains duplicate id \"${item.id}\" — level ids and focus restoration track items by id, so ids must be unique across the whole tree.`,\n )\n }\n seen.add(item.id)\n if (!item.href && !item.links?.length) {\n console.warn(\n `[nswds/ui] PushMenu item \"${item.id}\" has neither an href nor children — it renders as a button that only fires onItemClick.`,\n )\n }\n if (item.links?.length) {\n visit(item.links)\n }\n }\n }\n visit(navigation)\n}\n\n// One treatment for every row — drill-in buttons and leaf links alike — so the\n// two read as a single list. Tokenized from the nswds-app source's\n// border-l + primary-800 active pattern, with dark-mode equivalents the app\n// lacked (its grey-800-on-white text disappeared in dark mode).\nconst itemBaseClassName = [\n // min-h-11 guarantees the 44px minimum target size (WCAG 2.2, 2.5.8 Target\n // Size) even for single-line rows with compact padding overrides.\n 'relative flex min-h-11 w-full cursor-pointer items-center justify-between gap-x-6 border-l p-4 text-left text-base',\n 'transition-colors motion-reduce:transition-none',\n 'hover:border-primary-800 hover:bg-primary-800/10 dark:hover:border-primary-200 dark:hover:bg-primary-200/10',\n // Inset outline (negative offset): the levels scroll inside an\n // overflow-hidden root, so an outward offset would be clipped on the first\n // and last rows (WCAG 2.2, 2.4.13 Focus Appearance).\n 'focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-primary-800 dark:focus-visible:outline-primary-200',\n].join(' ')\n\nconst itemActiveClassName =\n 'border-primary-800 bg-primary-800/10 font-semibold text-primary-800 dark:border-primary-200 dark:bg-primary-200/10 dark:text-primary-200'\n\nconst itemInactiveClassName = 'border-transparent text-popover-foreground'\n\ntype PushMenuProps = Omit<React.ComponentPropsWithoutRef<'nav'>, 'children' | 'title'> & {\n /** The menu tree. Item ids must be unique across the whole tree. */\n navigation: PushMenuItem[]\n /**\n * The app's current pathname. Leaf links whose `href` matches get\n * `aria-current=\"page\"` and the active treatment. Replaces the nswds-app\n * source's `usePathname()` — the design system is framework-free, so the\n * router value is passed in rather than read from next/navigation.\n */\n currentHref?: string\n /** Root level title, shown in the header row. Also the default `aria-label`. */\n title?: string\n /** Fired when a leaf item (link or child-less button) is activated. */\n onItemClick?: (item: PushMenuItem) => void\n /** Fired after a forward/back slide settles on a level. */\n onNavigate?: (level: PushMenuLevel, history: PushMenuLevel[]) => void\n /**\n * Renders a close button in the header row when provided. Unlike the\n * nswds-app source — which only offered close on sub-levels, leaving the\n * root level uncloseable — the button renders on every level.\n */\n onClose?: () => void\n /** Show the \"A › B › C\" trail under the header on sub-levels. Defaults to `true`. */\n showBreadcrumbs?: boolean\n /**\n * Slide duration in milliseconds, defaulting to `PUSH_MENU_DURATION_MS`\n * (300). Drives both the `--push-menu-duration` custom property and the\n * state machine's timeouts — tune the slide here, never by overriding the\n * custom property (see the coupling note on the constant).\n */\n durationMs?: number\n /** Label for the Back button on sub-levels. Defaults to `'Back'`. */\n backLabel?: string\n /** Accessible label for the close button. Defaults to `'Close menu'`. */\n closeLabel?: string\n /**\n * Heading level for the per-level title, following `FooterNavColumn`'s\n * precedent (the nswds-app source used a `Heading` component this package\n * does not ship). Defaults to `2`; `1` is excluded because a menu panel\n * title is never the page's own title.\n */\n headingLevel?: 2 | 3 | 4 | 5 | 6\n ref?: React.Ref<HTMLElement>\n}\n\n/**\n * Multi-level slide-in-place drill-down menu (\"push menu\") for mobile\n * navigation, ported from nswds-app's `MultiLevelPushMenu`. Items with\n * children render as buttons that slide a new level in from the right; leaf\n * items render as links through `Link`, so apps can inject their framework\n * link component via `LinkProvider`. Fill height from its container — compose\n * it inside `SheetContent side=\"left\"` for the classic mobile drawer.\n *\n * Accessibility contract (all improvements over the nswds-app source, which\n * got several of these wrong):\n *\n * - The root is a `nav` landmark named by `title` (override with `aria-label`).\n * - Non-current levels carry the `inert` attribute, so a hidden level's links\n * are neither tabbable nor exposed to assistive tech. The app left every\n * mounted level in the tab order, letting keyboard users tab into invisible\n * history levels (WCAG 2.2, 2.4.3 Focus Order).\n * - Focus moves with the level change (2.4.3): drilling forward focuses the\n * new level's Back button; going back focuses the item that opened the\n * level just left, tracked by item id and restored after the slide settles.\n * Without this, `inert` on the old level would silently drop focus to\n * `<body>`. The Back button is the only route back (the breadcrumb is\n * decorative), so it always renders on sub-levels — hiding it would make\n * drill-down one-way.\n * - A single visually-hidden `aria-live=\"polite\"` region at the root announces\n * the current level's title, suffixed with the level number below the root.\n * A live attribute on the per-level headings would not work: each level's\n * heading is freshly mounted, and newly-mounted live regions are not\n * reliably announced.\n * - Level lists are `<ul role=\"list\">` — `list-style: none` strips list\n * semantics in some screen reader/browser pairings (notably VoiceOver), and\n * the explicit role restores them.\n * - Every row is at least 44px tall (2.5.8 Target Size); Back/close buttons\n * inherit `Button`'s 44px touch target.\n * - During the slide, rows get `pointer-events-none` and the state machine\n * ignores re-entrant navigation, but nothing is ever `disabled` — disabling\n * the focused Back button mid-animation would eject keyboard focus.\n * - Slides are CSS transforms with `motion-reduce:transition-none`, replacing\n * the app's inline transition strings (which ignored reduced motion).\n *\n * Departures from the nswds-app source, beyond the above:\n *\n * - The footer/stats block (Level N, item counts, progress dots, lucide\n * icons) is cut, along with its `showStats`/`showFooter` props: it was demo\n * chrome for the sandbox, not part of a navigation component's job. The\n * breadcrumb trail it hosted moves under the header row.\n * - The rendered \"Navigation Error\" fallback for malformed data is replaced\n * by a dev-only console warning (`warnIfNavigationMalformed`), mirroring\n * button.tsx's `warnIfIconButtonUnlabelled`.\n * - The breadcrumb trail is `aria-hidden`: it repeats what the heading and\n * live region already announce, and \"›\" separators read poorly in AT.\n *\n * The level stack is seeded from `navigation`/`title` on mount; pass a `key`\n * to remount (and reset to the root level) if either changes at runtime.\n */\nfunction PushMenu({\n navigation,\n currentHref,\n title = 'Menu',\n onItemClick,\n onNavigate,\n onClose,\n showBreadcrumbs = true,\n durationMs = PUSH_MENU_DURATION_MS,\n backLabel = 'Back',\n closeLabel = 'Close menu',\n headingLevel = 2,\n className,\n style,\n 'aria-label': ariaLabel,\n ref,\n ...props\n}: PushMenuProps) {\n const [navigationHistory, setNavigationHistory] = React.useState<PushMenuLevel[]>(() => [\n { items: navigation, title, depth: 1, id: buildLevelId([]) },\n ])\n const [animationState, setAnimationState] = React.useState<PushMenuAnimationState>('idle')\n const [isAnimationStarted, setIsAnimationStarted] = React.useState(false)\n\n const containerRef = React.useRef<HTMLElement | null>(null)\n const timeoutRef = React.useRef<number | null>(null)\n // Focus target applied by the effect below, after React commits the level\n // change — the target element must exist and must no longer be inert.\n const pendingFocusRef = React.useRef<{ levelId: string; itemId?: string } | null>(null)\n\n warnIfNavigationMalformed(navigation)\n\n React.useEffect(() => {\n return () => {\n if (timeoutRef.current !== null) {\n window.clearTimeout(timeoutRef.current)\n }\n }\n }, [])\n\n // Layout effect, not a passive one: the same commit that queues a focus\n // move can also flip the previously-focused element inert (drilling turns\n // the old level inert; going back turns the departing level inert), and the\n // browser blurs an element the moment it becomes inert. Applying the new\n // focus before paint means AT never observes the intermediate\n // focus-on-body state, and a containing dialog's focus guards (Base UI\n // Sheet) see focus already inside the popup when their async handlers run.\n React.useLayoutEffect(() => {\n const pending = pendingFocusRef.current\n if (!pending) {\n return\n }\n pendingFocusRef.current = null\n const level = containerRef.current?.querySelector<HTMLElement>(\n `[data-level-id=\"${CSS.escape(pending.levelId)}\"]`,\n )\n if (!level) {\n return\n }\n const target = pending.itemId\n ? level.querySelector<HTMLElement>(`[data-item-id=\"${CSS.escape(pending.itemId)}\"]`)\n : (level.querySelector<HTMLElement>('[data-slot=\"push-menu-back-button\"]') ??\n level.querySelector<HTMLElement>(\n '[data-slot=\"push-menu-item\"], [data-slot=\"push-menu-link\"]',\n ))\n // preventScroll: a level mid-slide sits at translateX(100%) inside an\n // overflow-hidden root; letting focus scroll it into view would desync the\n // container's scroll position from the transform.\n target?.focus({ preventScroll: true })\n // animationState is a dependency because back-navigation queues its focus\n // move on the slide START (an animationState commit), not on the level\n // pop — see navigateBack.\n }, [navigationHistory, animationState])\n\n const breadcrumb = React.useMemo(\n // During a back slide the trail already excludes the departing level —\n // the breadcrumb tracks the level the user is arriving at (see\n // activeIndex below), same as the live region.\n () =>\n generatePushMenuBreadcrumb(\n animationState === 'sliding-backward' ? navigationHistory.slice(0, -1) : navigationHistory,\n ),\n [navigationHistory, animationState],\n )\n\n function navigateToSubmenu(item: PushMenuItem) {\n if (!item.links?.length || animationState !== 'idle') {\n return\n }\n const levelPath = [\n ...navigationHistory.flatMap((level) => (level.parentItem ? [level.parentItem.id] : [])),\n item.id,\n ]\n const currentDepth = navigationHistory.at(-1)?.depth ?? 1\n const newLevel: PushMenuLevel = {\n items: item.links,\n title: item.title,\n parentItem: item,\n depth: currentDepth + 1,\n id: buildLevelId(levelPath),\n }\n const newHistory = [...navigationHistory, newLevel]\n\n // Focus moves as soon as the new level commits (see the effect above):\n // waiting for the slide to finish would leave focus on the old level,\n // which turns inert in the same commit and would eject focus to <body>.\n pendingFocusRef.current = { levelId: newLevel.id }\n setNavigationHistory(newHistory)\n setAnimationState('sliding-forward')\n setIsAnimationStarted(false)\n\n // Two-step start: the new level mounts at translateX(100%) with no\n // transition, then flips to 0 with the transition on. The layout read in\n // between is LOAD-BEARING: without it, nothing forces the browser to\n // compute styles for the mounted-at-100% frame, and when both states land\n // in one style recalc there is no transition — the panel snaps into\n // place instead of sliding (an intermittent, timing-dependent jump).\n // Reading layout inside the rAF forces that recalc deterministically.\n requestAnimationFrame(() => {\n containerRef.current?.getBoundingClientRect()\n setIsAnimationStarted(true)\n })\n\n timeoutRef.current = window.setTimeout(() => {\n setAnimationState('idle')\n setIsAnimationStarted(false)\n onNavigate?.(newLevel, newHistory)\n }, durationMs)\n }\n\n function navigateBack() {\n if (navigationHistory.length <= 1 || animationState !== 'idle') {\n return\n }\n const popped = navigationHistory.at(-1)\n const revealed = navigationHistory.at(-2)\n if (!revealed) {\n return\n }\n\n // Focus moves at slide START, symmetric with drilling forward: the\n // 'sliding-backward' commit un-inerts the revealed level (see the\n // activeIndex logic below) and the effect above focuses the item that\n // opened the departing level. Restoring focus at the POP instead — while\n // focus still sat on the departing level's Back button — meant the\n // focused node was removed from a live dialog, and Base UI's focus\n // containment would re-grab focus to the dialog popup a frame after our\n // restoration, silently overriding it (observed inside Sheet).\n pendingFocusRef.current = { levelId: revealed.id, itemId: popped?.parentItem?.id }\n setAnimationState('sliding-backward')\n\n timeoutRef.current = window.setTimeout(() => {\n const newHistory = navigationHistory.slice(0, -1)\n setNavigationHistory(newHistory)\n setAnimationState('idle')\n onNavigate?.(revealed, newHistory)\n }, durationMs)\n }\n\n const currentLevel = navigationHistory.at(-1)\n if (!currentLevel) {\n return null\n }\n\n const isAnimating = animationState !== 'idle'\n // The level the user is arriving AT — the stack top, except during a back\n // slide, where the user's intent has already committed to the level being\n // revealed underneath. data-current, inert, the live region and the\n // breadcrumb all follow this index so focus can land on the revealed level\n // at slide start and AT hears the destination, not the departing level.\n const activeIndex =\n animationState === 'sliding-backward'\n ? navigationHistory.length - 2\n : navigationHistory.length - 1\n const activeLevel = navigationHistory[activeIndex] ?? currentLevel\n const HeadingTag = `h${headingLevel}` as const\n\n return (\n <nav\n data-slot='push-menu'\n aria-label={ariaLabel ?? title}\n // Present while a slide is running (matches header's present-or-absent\n // data-scrolled convention). Consumers can style the transition off it;\n // tests use it to wait for the state machine to go idle — clicks during\n // a slide are dropped by design, and pointer-events-none does not stop\n // a programmatic .click().\n data-animating={isAnimating || undefined}\n {...props}\n className={cn(\n 'relative isolate h-full overflow-hidden bg-popover text-popover-foreground',\n className,\n )}\n // The slide duration custom property is set from durationMs so the CSS\n // transition and the setTimeout state machine can never disagree — see\n // the coupling note on PUSH_MENU_DURATION_MS.\n style={{ ...style, '--push-menu-duration': `${durationMs}ms` } as React.CSSProperties}\n ref={(node) => {\n containerRef.current = node\n if (typeof ref === 'function') {\n ref(node)\n } else if (ref) {\n ;(ref as React.RefObject<HTMLElement | null>).current = node\n }\n }}\n >\n {/* Persistent live region: announces level changes to AT without\n stealing focus from the managed focus moves. The level number is\n appended below the root because live regions only re-announce when\n their content actually changes — navigating between identically-\n titled levels would otherwise announce nothing. Consecutive levels\n always differ in depth, so consecutive announcements always differ. */}\n <div data-slot='push-menu-live-region' aria-live='polite' className='sr-only'>\n {activeLevel.depth > 1\n ? `${activeLevel.title}, level ${activeLevel.depth}`\n : activeLevel.title}\n </div>\n\n {navigationHistory.map((level, index) => {\n // The stack top is the level that MOVES (slides in forward, slides\n // out backward); the active level is the one the user is arriving at\n // — they differ only during a back slide.\n const isTopLevel = index === navigationHistory.length - 1\n const isActiveLevel = index === activeIndex\n // Always shown below the root: the Back button is the ONLY route back\n // (the breadcrumb is aria-hidden and there is no keyboard binding or\n // imperative API), so making it optional would strand users.\n const shouldShowBackButton = level.depth > 1\n\n let translateX = 0\n if (animationState === 'sliding-forward') {\n translateX = isTopLevel ? (isAnimationStarted ? 0 : 100) : 0\n } else if (animationState === 'sliding-backward') {\n translateX = isTopLevel ? 100 : 0\n }\n\n // Only the moving (top) level transitions; forward slides wait for\n // the second frame so the mount position is applied untransitioned.\n const isSliding =\n isTopLevel &&\n (animationState === 'sliding-backward' ||\n (animationState === 'sliding-forward' && isAnimationStarted))\n\n return (\n <div\n key={level.id}\n data-slot='push-menu-level'\n data-level-id={level.id}\n data-current={isActiveLevel || undefined}\n // Non-active levels must be invisible to keyboard and AT, not\n // just to the eye. Keying this on the ACTIVE level (not the stack\n // top) un-inerts the revealed level at back-slide start, so focus\n // can move there immediately — and the focused Back button is\n // never removed from a live dialog while still focused.\n inert={!isActiveLevel}\n className={cn(\n 'absolute inset-0 flex h-full w-full flex-col bg-popover will-change-transform',\n isSliding\n ? 'transition-transform duration-(--push-menu-duration) ease-out motion-reduce:transition-none'\n : 'transition-none',\n )}\n style={{ transform: `translateX(${translateX}%)`, zIndex: index + 1 }}\n >\n <div\n data-slot='push-menu-header'\n className='flex min-h-11 items-center gap-1 border-b border-border px-2 py-2'\n >\n {shouldShowBackButton && (\n <Button\n data-slot='push-menu-back-button'\n variant='ghost'\n color='primary'\n size='sm'\n leadingVisual={IconWest}\n onClick={navigateBack}\n className={cn(isAnimating && 'pointer-events-none')}\n >\n {backLabel}\n </Button>\n )}\n <HeadingTag\n data-slot='push-menu-title'\n className='min-w-0 flex-1 truncate px-2 text-base font-semibold'\n >\n {level.title}\n </HeadingTag>\n {onClose && (\n <Button\n data-slot='push-menu-close-button'\n variant='ghost'\n color='grey'\n size='icon'\n aria-label={closeLabel}\n leadingVisual={IconClose}\n onClick={onClose}\n />\n )}\n </div>\n\n {showBreadcrumbs && isActiveLevel && level.depth > 1 && (\n // aria-hidden: the trail repeats what the heading and live\n // region already announce, and \"›\" separators read poorly in AT.\n <p\n data-slot='push-menu-breadcrumb'\n aria-hidden='true'\n className='truncate border-b border-border px-4 py-2 text-xs text-muted-foreground'\n >\n {breadcrumb}\n </p>\n )}\n\n <div data-slot='push-menu-items' className='flex-1 overflow-y-auto'>\n {/* role='list' restores list semantics stripped by list-none. */}\n <ul role='list' className='m-0 list-none divide-y divide-border p-0'>\n {level.items.map((item) => {\n const hasChildren = Boolean(item.links?.length)\n const isActive = item.href != null && item.href === currentHref\n\n return (\n <li key={item.id}>\n {hasChildren ? (\n <button\n type='button'\n data-slot='push-menu-item'\n data-item-id={item.id}\n onClick={() => navigateToSubmenu(item)}\n className={cn(\n itemBaseClassName,\n isActive ? itemActiveClassName : itemInactiveClassName,\n isAnimating && 'pointer-events-none',\n )}\n >\n <span className='min-w-0 flex-1 truncate'>{item.title}</span>\n <IconChevronRight aria-hidden='true' className='size-5 shrink-0' />\n </button>\n ) : item.href ? (\n <Link\n variant='unstyled'\n data-slot='push-menu-link'\n data-item-id={item.id}\n href={item.href}\n aria-current={isActive ? 'page' : undefined}\n onClick={() => onItemClick?.(item)}\n className={cn(\n itemBaseClassName,\n isActive ? itemActiveClassName : itemInactiveClassName,\n isAnimating && 'pointer-events-none',\n )}\n >\n <span className='min-w-0 flex-1 truncate'>{item.title}</span>\n </Link>\n ) : (\n <button\n type='button'\n data-slot='push-menu-item'\n data-item-id={item.id}\n onClick={() => onItemClick?.(item)}\n className={cn(\n itemBaseClassName,\n itemInactiveClassName,\n isAnimating && 'pointer-events-none',\n )}\n >\n <span className='min-w-0 flex-1 truncate'>{item.title}</span>\n </button>\n )}\n </li>\n )\n })}\n </ul>\n </div>\n </div>\n )\n })}\n </nav>\n )\n}\n\nexport { generatePushMenuBreadcrumb, PUSH_MENU_DURATION_MS, PushMenu }\nexport type { PushMenuItem, PushMenuLevel, PushMenuProps }\n"]}
@@ -0,0 +1,116 @@
1
+ import * as class_variance_authority_types from 'class-variance-authority/types';
2
+ import { VariantProps } from 'class-variance-authority';
3
+ import React__default from 'react';
4
+
5
+ /**
6
+ * One entry in a `SideNav` tree.
7
+ *
8
+ * - `href` and no `links` — a leaf link.
9
+ * - `links` — a branch. At the top level it renders as a section heading over an
10
+ * always-visible list; at any deeper level it renders as a collapsible
11
+ * trigger. A branch's own `href` is IGNORED (the row is a disclosure button,
12
+ * not a link) — a dev-only warning flags it, mirroring the nswds-app
13
+ * `SidebarNavigation` behaviour where branch rows only toggled.
14
+ * - Neither — a dead entry; rendered as inert text and flagged with a dev-only
15
+ * warning rather than a decoy `<a>` with no destination.
16
+ */
17
+ type SideNavItem = {
18
+ /** Visible text for the link, section heading, or branch trigger. */
19
+ title: string;
20
+ href?: string;
21
+ links?: SideNavItem[];
22
+ };
23
+ /**
24
+ * Row treatment shared by leaf links and branch triggers — the nswds-app
25
+ * left-rail language: each row carries its own left border sitting exactly on
26
+ * the list's rail (the `-ml-px` on the `<li>`), so hover and the current-page
27
+ * state recolour the rail segment beside the row.
28
+ *
29
+ * Departures from the source, both deliberate:
30
+ * - The idle border is `border-transparent` rather than the bare `border-l`
31
+ * default: idle rows show the rail through their transparent border, so the
32
+ * idle rail colour is defined once (on the list) instead of twice.
33
+ * - The current row adds `dark:text-white`. The source left dark active text
34
+ * to fall through to the idle `dark:text-grey-400`, which on the
35
+ * `dark:bg-white/20` highlight is both low-contrast and cascade-order
36
+ * dependent; bold white ink clears WCAG 2.2 AA (1.4.3) on that overlay.
37
+ *
38
+ * The hover font-weight change (`hover:font-semibold`) is source parity; it
39
+ * reflows the row's own text only, never the rail.
40
+ *
41
+ * Focus uses the house visible-focus pattern (outline-current, offset 2), so
42
+ * the indicator always contrasts with whatever text colour the row currently
43
+ * has (WCAG 2.2, 2.4.13 Focus Appearance).
44
+ */
45
+ declare const sideNavRowVariants: (props?: ({
46
+ current?: boolean | null | undefined;
47
+ } & class_variance_authority_types.ClassProp) | undefined) => string;
48
+ type SideNavProps = Omit<React__default.ComponentPropsWithoutRef<'nav'>, 'children'> & {
49
+ /**
50
+ * The navigation tree. A top-level item with `links` renders as a section
51
+ * heading over an always-visible rail; one without renders as a plain rail
52
+ * link — mirroring nswds-app `Navigation`'s section shape. Deeper items with
53
+ * `links` render as collapsible branches (nswds-app `SidebarNavigation`).
54
+ */
55
+ sections: SideNavItem[];
56
+ /**
57
+ * The current page's href. The matching leaf gets `aria-current='page'` and
58
+ * the active rail treatment, and every branch on the path to it starts
59
+ * expanded — at MOUNT only. Branches are `defaultOpen`, not controlled: a
60
+ * later `currentHref` change (SPA navigation) re-highlights the leaf but
61
+ * never re-expands a branch the reader has folded, so the highlight can
62
+ * land inside a collapsed branch. Branch expansion is seeded from
63
+ * `currentHref` on mount; pass a `key` (e.g. `key={currentHref}`) to
64
+ * remount and re-open the path on navigation — the same contract as
65
+ * PushMenu's level stack. Frameworkless replacement for the source's
66
+ * `usePathname()` — pass your router's pathname in.
67
+ */
68
+ currentHref?: string;
69
+ /**
70
+ * Fired from every leaf link (never from branch triggers). The mobile-drawer
71
+ * close hook, as in the source's `onLinkClick`.
72
+ */
73
+ onNavigate?: React__default.MouseEventHandler<HTMLAnchorElement>;
74
+ /**
75
+ * Heading level for section titles. Defaults to `2` — correct when the nav
76
+ * sits at the top level of the document outline. Step it down when the page
77
+ * nests the nav under another heading (WCAG 1.3.1). `1` is excluded: a
78
+ * section-nav heading is never the page's own title. Same contract as
79
+ * `FooterNavColumn`.
80
+ */
81
+ headingLevel?: 2 | 3 | 4 | 5 | 6;
82
+ ref?: React__default.Ref<HTMLElement>;
83
+ };
84
+ /**
85
+ * Left-rail section navigation — the consolidation of nswds-app's flat
86
+ * `Navigation` and recursive `SidebarNavigation` into one tree-shaped
87
+ * component. Renders a `<nav>` landmark of headed sections whose links may
88
+ * nest to any depth; nested branches collapse.
89
+ *
90
+ * Accessibility contract:
91
+ * - The landmark is named (`aria-label`, default "Section navigation") so it is
92
+ * distinguishable from the page's other navigation landmarks (WCAG 1.3.1).
93
+ * - Disclosure semantics — `aria-expanded`, `aria-controls`, Enter/Space
94
+ * activation — come entirely from Base UI's Collapsible; nothing hand-rolled.
95
+ * - The current page is marked with `aria-current='page'`, and every branch on
96
+ * the path to it starts expanded ON MOUNT, so the highlighted location is
97
+ * visible on arrival (ported `isLinkOrDescendantActive`). Expansion is
98
+ * `defaultOpen`, so it does not re-run when `currentHref` changes — see the
99
+ * `currentHref` prop for the `key={currentHref}` remount workaround.
100
+ * - Focus is always visible via the house `outline-current` pattern (2.4.13).
101
+ *
102
+ * Departures from the nswds-app source (see also `sideNavRowVariants` and
103
+ * `SideNavItem`):
104
+ * - `usePathname()` → the `currentHref` prop; links render through `Link`, so
105
+ * frameworks inject their own anchor via `LinkProvider`.
106
+ * - The Radix-based Collapsible → the Base UI primitive (this repo's
107
+ * `collapsible.tsx`), whose open state is `data-panel-open` on the trigger
108
+ * rather than Radix's `data-state='open'`.
109
+ * - The source rendered a stray empty `<ul>` after link-less sections and sent
110
+ * `href='#'` placeholders through the tree; both are dropped.
111
+ */
112
+ declare function SideNav({ className, sections, currentHref, onNavigate, headingLevel, 'aria-label': ariaLabel, ref, ...props }: SideNavProps): React__default.JSX.Element;
113
+
114
+ type SideNavRowVariantProps = VariantProps<typeof sideNavRowVariants>;
115
+
116
+ export { SideNav, type SideNavItem, type SideNavProps, type SideNavRowVariantProps, sideNavRowVariants };