@nswds/ui 5.2.0 → 5.3.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.
@@ -0,0 +1,186 @@
1
+ import * as class_variance_authority_types from 'class-variance-authority/types';
2
+ import { VariantProps } from 'class-variance-authority';
3
+ import * as React from 'react';
4
+ import { LinkProps } from './link.js';
5
+
6
+ /**
7
+ * The bar itself: a horizontal scroll container with the rule the tabs sit on.
8
+ *
9
+ * The rule is on the LIST, not on the `<nav>`. The nav is the scroll container,
10
+ * so a rule there spans only the visible width and stops dead at the right edge
11
+ * while the tabs keep going — the bar looks broken exactly when it overflows,
12
+ * which is the case that matters. `min-w-max` on the list makes it as wide as
13
+ * its tabs, so the rule runs the full scrollable width instead.
14
+ *
15
+ * The scrollbar is suppressed on the nav, the element that actually scrolls: a
16
+ * visible bar would sit on top of the tabs. The clipped final tab is what
17
+ * signals there is more to the right. Scrolling itself is untouched, so pointer
18
+ * drag, shift-wheel and keyboard all still reach the overflow — the same
19
+ * treatment `OnThisPage` gives its horizontal bar.
20
+ */
21
+ declare const tabNavListVariants: (props?: ({
22
+ border?: boolean | null | undefined;
23
+ } & class_variance_authority_types.ClassProp) | undefined) => string;
24
+ /**
25
+ * One tab.
26
+ *
27
+ * `-mb-px` pulls the 2px marker down over the list's 1px rule so the two merge
28
+ * into a single edge, rather than the marker floating a hairline above it.
29
+ *
30
+ * Idle and current ink live in separate branches rather than in the base
31
+ * string. Both are single-class selectors, so with both on the element at once
32
+ * the winner comes down to Tailwind's internal sort order — the same reason
33
+ * `OnThisPage` splits them.
34
+ *
35
+ * The current tab changes colour AND draws the marker rule, so the state is
36
+ * never signalled by colour alone (WCAG 2.2, 1.4.1). The rule is always drawn,
37
+ * `transparent` when idle, so becoming current never changes the tab's size and
38
+ * the bar cannot reflow under the pointer.
39
+ *
40
+ * Floored at 44px on coarse pointers, the promise DESIGN.md makes and
41
+ * `Button`/`PushMenu` hold. `p-4` over a 24px line box already clears it on
42
+ * most type scales; the floor makes that independent of the consumer's scale.
43
+ */
44
+ declare const tabNavLinkVariants: (props?: ({
45
+ current?: boolean | null | undefined;
46
+ } & class_variance_authority_types.ClassProp) | undefined) => string;
47
+ type TabNavProps = React.ComponentPropsWithoutRef<'nav'> & VariantProps<typeof tabNavListVariants> & {
48
+ /**
49
+ * The current page's href. The `TabNavLink` whose `href` matches it exactly
50
+ * gets `aria-current='page'` and the marker rule.
51
+ *
52
+ * Matching is EXACT, deliberately. Prefix matching (`pathname.startsWith`)
53
+ * is the obvious shortcut and it is wrong in two directions: `/colour`
54
+ * matches `/colour-blind-safe`, and every parent in a nested set matches at
55
+ * once, so several tabs claim the page. Matching rules beyond equality are
56
+ * the caller's to define — set `current` on the link directly and the bar
57
+ * will not second-guess it.
58
+ *
59
+ * Frameworkless replacement for `usePathname()` — pass your router's
60
+ * pathname in, as with `SideNav`.
61
+ */
62
+ currentHref?: string;
63
+ ref?: React.Ref<HTMLElement>;
64
+ };
65
+ /**
66
+ * Flat horizontal navigation between the pages of one section — the bar that
67
+ * sits under the site header and lists a section's peer pages.
68
+ *
69
+ * **Where it sits among the other navigation components**, none of which it
70
+ * overlaps:
71
+ *
72
+ * | Component | Moves you |
73
+ * | ------------ | ------------------------------------------------ |
74
+ * | `MainNav` | between sites/sections, mega menu |
75
+ * | `SideNav` | between pages, as a tree |
76
+ * | `TabNav` | between the pages of one section, as a flat bar |
77
+ * | `StepNav` | through a multi-page journey |
78
+ * | `OnThisPage` | within the page you are on |
79
+ *
80
+ * The closest neighbours are `SideNav` and `OnThisPage`. `SideNav` does the
81
+ * same job — peer-page navigation — but as a vertical tree with arbitrary
82
+ * nesting; this is the flat horizontal form, for a section whose pages have no
83
+ * hierarchy worth drawing. `OnThisPage` looks nearly identical and is not
84
+ * related: its entries are anchors into the current page, which is why it marks
85
+ * `aria-current='location'` where this marks `'page'`.
86
+ *
87
+ * **These are not ARIA tabs, and must never become them.** The name describes
88
+ * the visual idiom, which is what a designer reaching for this will search for.
89
+ * The semantics are a `<nav>` landmark over a list of links: each one navigates
90
+ * to a different URL, so a reader gets a page load, not a panel swap. Adding
91
+ * `role='tablist'`/`role='tab'` would promise `aria-controls` panels that do
92
+ * not exist and hand the arrow keys a selection model the browser cannot honour
93
+ * across a navigation. `OnThisPage` documents the mirror-image decision about
94
+ * `aria-current`; this is the same care applied to `role`.
95
+ *
96
+ * **No Base UI primitive is involved, and none is missing.** The house rule is
97
+ * never to hand-roll ARIA, focus or keyboard behaviour — but these are plain
98
+ * anchors, which have all three natively, and a link list needs no roving
99
+ * tabindex. Nothing is hand-rolled here because there is nothing to hand-roll.
100
+ *
101
+ * Accessibility contract:
102
+ *
103
+ * - The landmark is named (`aria-label`, default "Subsection navigation") so it
104
+ * is distinguishable from the page's other navigation landmarks (WCAG 2.2,
105
+ * 1.3.1). Name it after the section it navigates — "Colour", "Get started" —
106
+ * whenever you know it; the default only guarantees the landmark is not
107
+ * anonymous.
108
+ * - The current page is marked `aria-current='page'`.
109
+ * - `role='list'` is explicit on the `<ul>`: `list-style: none` strips list
110
+ * semantics in Safari/VoiceOver, the same reason `SideNav`, `StepIndicator`
111
+ * and `OnThisPage` set it.
112
+ * - The current state carries colour AND a marker rule, never colour alone
113
+ * (1.4.1), and the rule occupies its space when idle so nothing reflows.
114
+ * - Focus is always visible via the house outline pattern (2.4.13).
115
+ *
116
+ * Departures from the nswds-app `TabNavigation` source, all deliberate:
117
+ *
118
+ * - **The current tab comes from `currentHref`, not from internal state.** The
119
+ * source tracked the last-clicked tab in a `useState`, which is a click
120
+ * highlighter, not page navigation: on a fresh page load nothing is marked,
121
+ * and after a real navigation the state is gone. Marking the current page is
122
+ * the entire job of this component, so it reads the router's pathname the way
123
+ * `SideNav` does.
124
+ * - **Tabs are identified by `href`, not by a `tabId`.** The source defaulted
125
+ * every link's id to the literal string `'unique-id'`, so any two links
126
+ * without an explicit id shared one identity. Keying off the destination
127
+ * removes the id from the API entirely.
128
+ * - **No hover-pill animation, and no `motion` dependency.** The source
129
+ * animated a floating background between tabs via `motion/react`. The hover
130
+ * state here is a colour derivation per DESIGN.md's Derived State Rule; a
131
+ * design system taking on an animation runtime to decorate one hover is a
132
+ * cost every consumer pays.
133
+ * - Radix `NavigationMenu` → plain semantics. The source used it purely as
134
+ * markup scaffolding, and its `onSelect` is what made the active tab
135
+ * click-driven in the first place.
136
+ * - Links render through `Link`, so frameworks inject their own anchor via
137
+ * `LinkProvider` (`next/link` et al) — as in `SideNav`.
138
+ *
139
+ * @example
140
+ * ```tsx
141
+ * <TabNav currentHref={pathname} aria-label='Colour'>
142
+ * <TabNavLink href='/colour/brand'>Brand palette</TabNavLink>
143
+ * <TabNavLink href='/colour/semantic'>Semantic palette</TabNavLink>
144
+ * </TabNav>
145
+ * ```
146
+ */
147
+ declare function TabNav({ className, children, currentHref, border, 'aria-label': ariaLabel, ref, ...props }: TabNavProps): React.JSX.Element;
148
+ /**
149
+ * `as` is omitted deliberately, not by oversight.
150
+ *
151
+ * `Link` strips `href` from any non-anchor intrinsic element, so `as='button'`
152
+ * typechecked and rendered `<button href=null aria-current='page'>` — a control
153
+ * that cannot navigate, announcing itself as the current *page*. That is a
154
+ * name/role/value mismatch (WCAG 2.2, 4.1.2), not merely a dead link, and it
155
+ * contradicts the nav-over-links contract this component documents.
156
+ *
157
+ * Nothing is lost. A bar whose tabs render as different element types is
158
+ * incoherent by construction, and framework links still arrive the documented
159
+ * way — wrap the bar in `<LinkProvider component={NextLink}>`. `SideNav` sets
160
+ * the same precedent: it renders `Link` internally and never forwards `as`.
161
+ */
162
+ type TabNavLinkProps = Omit<LinkProps, 'variant' | 'as'> & {
163
+ /**
164
+ * Force the current state, overriding the bar's `currentHref` comparison.
165
+ *
166
+ * The escape hatch for any matching rule other than equality — prefix
167
+ * matching for a nested route, ignoring a query string, treating an index
168
+ * page as current for its children. Compute it from your router and set it
169
+ * here; `TabNav` does not guess.
170
+ *
171
+ * Also the only way to mark the current tab when `href` is a url object,
172
+ * which cannot be compared to a pathname string.
173
+ */
174
+ current?: boolean;
175
+ };
176
+ /**
177
+ * One tab: a link to a peer page, marked `aria-current='page'` when it is the
178
+ * one being read.
179
+ *
180
+ * Renders its own `<li>`, so `TabNav`'s children are tabs rather than list
181
+ * items — the compound shape `Header`/`HeaderBrand` and `Footer`/`FooterNav`
182
+ * already use.
183
+ */
184
+ declare function TabNavLink({ className, children, current, href, ...props }: TabNavLinkProps): React.JSX.Element;
185
+
186
+ export { TabNav, TabNavLink, type TabNavLinkProps, type TabNavProps, tabNavLinkVariants, tabNavListVariants };
@@ -0,0 +1,100 @@
1
+ "use client"
2
+ import { jsx } from 'react/jsx-runtime';
3
+ import { cva } from 'class-variance-authority';
4
+ import * as React from 'react';
5
+ import { cn } from '../lib/utils.js';
6
+ import { Link } from '../components/link.js';
7
+
8
+ const TabNavContext = React.createContext(null);
9
+ const tabNavListVariants = cva("flex min-w-max items-center", {
10
+ variants: {
11
+ /**
12
+ * The rule the tabs sit on. Off for a bar inside a `Card` or panel that
13
+ * already draws its own edge, where a second rule reads as a double border.
14
+ */
15
+ border: {
16
+ true: "border-b border-border",
17
+ false: ""
18
+ }
19
+ },
20
+ defaultVariants: {
21
+ border: true
22
+ }
23
+ });
24
+ const tabNavLinkVariants = cva(
25
+ [
26
+ "flex shrink-0 items-center border-b-2 p-4 font-bold whitespace-nowrap",
27
+ "-mb-px",
28
+ "[@media(pointer:coarse)]:min-h-11",
29
+ "motion-safe:transition-colors",
30
+ "hover:bg-primary/10 hover:text-primary",
31
+ "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
32
+ ],
33
+ {
34
+ variants: {
35
+ current: {
36
+ true: "border-primary text-primary",
37
+ false: "border-transparent text-foreground"
38
+ }
39
+ },
40
+ defaultVariants: {
41
+ current: false
42
+ }
43
+ }
44
+ );
45
+ function TabNav({
46
+ className,
47
+ children,
48
+ currentHref,
49
+ border,
50
+ "aria-label": ariaLabel = "Subsection navigation",
51
+ ref,
52
+ ...props
53
+ }) {
54
+ const context = React.useMemo(() => ({ currentHref }), [currentHref]);
55
+ return /* @__PURE__ */ jsx(
56
+ "nav",
57
+ {
58
+ ...props,
59
+ ref,
60
+ "data-slot": "tab-nav",
61
+ "aria-label": ariaLabel,
62
+ className: cn(
63
+ "text-base",
64
+ "[scrollbar-width:none] overflow-x-auto [&::-webkit-scrollbar]:hidden",
65
+ className
66
+ ),
67
+ children: /* @__PURE__ */ jsx("ul", { role: "list", "data-slot": "tab-nav-list", className: cn(tabNavListVariants({ border })), children: /* @__PURE__ */ jsx(TabNavContext.Provider, { value: context, children }) })
68
+ }
69
+ );
70
+ }
71
+ function warnIfOrphaned(hasContext) {
72
+ if (process.env.NODE_ENV === "production" || hasContext) {
73
+ return;
74
+ }
75
+ console.warn(
76
+ "[nswds/ui] TabNavLink rendered outside a TabNav \u2014 it cannot read currentHref, so the current tab is never derived automatically (only an explicit `current` still applies), and its <li> sits outside any list. Wrap the links in <TabNav>."
77
+ );
78
+ }
79
+ function TabNavLink({ className, children, current, href, ...props }) {
80
+ const context = React.useContext(TabNavContext);
81
+ warnIfOrphaned(context !== null);
82
+ const isCurrent = current ?? (context?.currentHref !== void 0 && typeof href === "string" && href === context.currentHref);
83
+ return /* @__PURE__ */ jsx("li", { "data-slot": "tab-nav-item", className: "flex", children: /* @__PURE__ */ jsx(
84
+ Link,
85
+ {
86
+ ...props,
87
+ variant: "unstyled",
88
+ "data-slot": "tab-nav-link",
89
+ "data-active": isCurrent ? "" : void 0,
90
+ href,
91
+ "aria-current": isCurrent ? "page" : void 0,
92
+ className: cn(tabNavLinkVariants({ current: isCurrent }), className),
93
+ children
94
+ }
95
+ ) });
96
+ }
97
+
98
+ export { TabNav, TabNavLink, tabNavLinkVariants, tabNavListVariants };
99
+ //# sourceMappingURL=tab-nav.js.map
100
+ //# sourceMappingURL=tab-nav.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/components/tab-nav.tsx"],"names":[],"mappings":";;;;;;AAiBA,MAAM,a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av.js","sourcesContent":["'use client'\n\nimport { cva, type VariantProps } from 'class-variance-authority'\nimport * as React from 'react'\n\nimport { cn } from '../lib/utils.js'\n\nimport { Link, type LinkProps } from '../components/link.js'\n\n/**\n * Carries the bar's `currentHref` down to the links without threading it\n * through every call site.\n *\n * `null` means a link is rendering outside a `TabNav` — a real mistake, since\n * nothing would ever be marked current. `warnIfOrphaned` names it in\n * development.\n */\nconst TabNavContext = React.createContext<{ currentHref: string | undefined } | null>(null)\n\n/**\n * The bar itself: a horizontal scroll container with the rule the tabs sit on.\n *\n * The rule is on the LIST, not on the `<nav>`. The nav is the scroll container,\n * so a rule there spans only the visible width and stops dead at the right edge\n * while the tabs keep going — the bar looks broken exactly when it overflows,\n * which is the case that matters. `min-w-max` on the list makes it as wide as\n * its tabs, so the rule runs the full scrollable width instead.\n *\n * The scrollbar is suppressed on the nav, the element that actually scrolls: a\n * visible bar would sit on top of the tabs. The clipped final tab is what\n * signals there is more to the right. Scrolling itself is untouched, so pointer\n * drag, shift-wheel and keyboard all still reach the overflow — the same\n * treatment `OnThisPage` gives its horizontal bar.\n */\nconst tabNavListVariants = cva('flex min-w-max items-center', {\n variants: {\n /**\n * The rule the tabs sit on. Off for a bar inside a `Card` or panel that\n * already draws its own edge, where a second rule reads as a double border.\n */\n border: {\n true: 'border-b border-border',\n false: '',\n },\n },\n defaultVariants: {\n border: true,\n },\n})\n\n/**\n * One tab.\n *\n * `-mb-px` pulls the 2px marker down over the list's 1px rule so the two merge\n * into a single edge, rather than the marker floating a hairline above it.\n *\n * Idle and current ink live in separate branches rather than in the base\n * string. Both are single-class selectors, so with both on the element at once\n * the winner comes down to Tailwind's internal sort order — the same reason\n * `OnThisPage` splits them.\n *\n * The current tab changes colour AND draws the marker rule, so the state is\n * never signalled by colour alone (WCAG 2.2, 1.4.1). The rule is always drawn,\n * `transparent` when idle, so becoming current never changes the tab's size and\n * the bar cannot reflow under the pointer.\n *\n * Floored at 44px on coarse pointers, the promise DESIGN.md makes and\n * `Button`/`PushMenu` hold. `p-4` over a 24px line box already clears it on\n * most type scales; the floor makes that independent of the consumer's scale.\n */\nconst tabNavLinkVariants = cva(\n [\n 'flex shrink-0 items-center border-b-2 p-4 font-bold whitespace-nowrap',\n '-mb-px',\n '[@media(pointer:coarse)]:min-h-11',\n 'motion-safe:transition-colors',\n 'hover:bg-primary/10 hover:text-primary',\n 'focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring',\n ],\n {\n variants: {\n current: {\n true: 'border-primary text-primary',\n false: 'border-transparent text-foreground',\n },\n },\n defaultVariants: {\n current: false,\n },\n },\n)\n\ntype TabNavProps = React.ComponentPropsWithoutRef<'nav'> &\n VariantProps<typeof tabNavListVariants> & {\n /**\n * The current page's href. The `TabNavLink` whose `href` matches it exactly\n * gets `aria-current='page'` and the marker rule.\n *\n * Matching is EXACT, deliberately. Prefix matching (`pathname.startsWith`)\n * is the obvious shortcut and it is wrong in two directions: `/colour`\n * matches `/colour-blind-safe`, and every parent in a nested set matches at\n * once, so several tabs claim the page. Matching rules beyond equality are\n * the caller's to define — set `current` on the link directly and the bar\n * will not second-guess it.\n *\n * Frameworkless replacement for `usePathname()` — pass your router's\n * pathname in, as with `SideNav`.\n */\n currentHref?: string\n ref?: React.Ref<HTMLElement>\n }\n\n/**\n * Flat horizontal navigation between the pages of one section — the bar that\n * sits under the site header and lists a section's peer pages.\n *\n * **Where it sits among the other navigation components**, none of which it\n * overlaps:\n *\n * | Component | Moves you |\n * | ------------ | ------------------------------------------------ |\n * | `MainNav` | between sites/sections, mega menu |\n * | `SideNav` | between pages, as a tree |\n * | `TabNav` | between the pages of one section, as a flat bar |\n * | `StepNav` | through a multi-page journey |\n * | `OnThisPage` | within the page you are on |\n *\n * The closest neighbours are `SideNav` and `OnThisPage`. `SideNav` does the\n * same job — peer-page navigation — but as a vertical tree with arbitrary\n * nesting; this is the flat horizontal form, for a section whose pages have no\n * hierarchy worth drawing. `OnThisPage` looks nearly identical and is not\n * related: its entries are anchors into the current page, which is why it marks\n * `aria-current='location'` where this marks `'page'`.\n *\n * **These are not ARIA tabs, and must never become them.** The name describes\n * the visual idiom, which is what a designer reaching for this will search for.\n * The semantics are a `<nav>` landmark over a list of links: each one navigates\n * to a different URL, so a reader gets a page load, not a panel swap. Adding\n * `role='tablist'`/`role='tab'` would promise `aria-controls` panels that do\n * not exist and hand the arrow keys a selection model the browser cannot honour\n * across a navigation. `OnThisPage` documents the mirror-image decision about\n * `aria-current`; this is the same care applied to `role`.\n *\n * **No Base UI primitive is involved, and none is missing.** The house rule is\n * never to hand-roll ARIA, focus or keyboard behaviour — but these are plain\n * anchors, which have all three natively, and a link list needs no roving\n * tabindex. Nothing is hand-rolled here because there is nothing to hand-roll.\n *\n * Accessibility contract:\n *\n * - The landmark is named (`aria-label`, default \"Subsection navigation\") so it\n * is distinguishable from the page's other navigation landmarks (WCAG 2.2,\n * 1.3.1). Name it after the section it navigates — \"Colour\", \"Get started\" —\n * whenever you know it; the default only guarantees the landmark is not\n * anonymous.\n * - The current page is marked `aria-current='page'`.\n * - `role='list'` is explicit on the `<ul>`: `list-style: none` strips list\n * semantics in Safari/VoiceOver, the same reason `SideNav`, `StepIndicator`\n * and `OnThisPage` set it.\n * - The current state carries colour AND a marker rule, never colour alone\n * (1.4.1), and the rule occupies its space when idle so nothing reflows.\n * - Focus is always visible via the house outline pattern (2.4.13).\n *\n * Departures from the nswds-app `TabNavigation` source, all deliberate:\n *\n * - **The current tab comes from `currentHref`, not from internal state.** The\n * source tracked the last-clicked tab in a `useState`, which is a click\n * highlighter, not page navigation: on a fresh page load nothing is marked,\n * and after a real navigation the state is gone. Marking the current page is\n * the entire job of this component, so it reads the router's pathname the way\n * `SideNav` does.\n * - **Tabs are identified by `href`, not by a `tabId`.** The source defaulted\n * every link's id to the literal string `'unique-id'`, so any two links\n * without an explicit id shared one identity. Keying off the destination\n * removes the id from the API entirely.\n * - **No hover-pill animation, and no `motion` dependency.** The source\n * animated a floating background between tabs via `motion/react`. The hover\n * state here is a colour derivation per DESIGN.md's Derived State Rule; a\n * design system taking on an animation runtime to decorate one hover is a\n * cost every consumer pays.\n * - Radix `NavigationMenu` → plain semantics. The source used it purely as\n * markup scaffolding, and its `onSelect` is what made the active tab\n * click-driven in the first place.\n * - Links render through `Link`, so frameworks inject their own anchor via\n * `LinkProvider` (`next/link` et al) — as in `SideNav`.\n *\n * @example\n * ```tsx\n * <TabNav currentHref={pathname} aria-label='Colour'>\n * <TabNavLink href='/colour/brand'>Brand palette</TabNavLink>\n * <TabNavLink href='/colour/semantic'>Semantic palette</TabNavLink>\n * </TabNav>\n * ```\n */\nfunction TabNav({\n className,\n children,\n currentHref,\n border,\n 'aria-label': ariaLabel = 'Subsection navigation',\n ref,\n ...props\n}: TabNavProps) {\n // Memoised so every tab does not re-render whenever the consuming page does\n // for an unrelated reason; `currentHref` is the only thing that should move.\n const context = React.useMemo(() => ({ currentHref }), [currentHref])\n\n return (\n <nav\n {...props}\n ref={ref}\n data-slot='tab-nav'\n aria-label={ariaLabel}\n className={cn(\n 'text-base',\n '[scrollbar-width:none] overflow-x-auto [&::-webkit-scrollbar]:hidden',\n className,\n )}\n >\n <ul role='list' data-slot='tab-nav-list' className={cn(tabNavListVariants({ border }))}>\n <TabNavContext.Provider value={context}>{children}</TabNavContext.Provider>\n </ul>\n </nav>\n )\n}\n\n/**\n * `as` is omitted deliberately, not by oversight.\n *\n * `Link` strips `href` from any non-anchor intrinsic element, so `as='button'`\n * typechecked and rendered `<button href=null aria-current='page'>` — a control\n * that cannot navigate, announcing itself as the current *page*. That is a\n * name/role/value mismatch (WCAG 2.2, 4.1.2), not merely a dead link, and it\n * contradicts the nav-over-links contract this component documents.\n *\n * Nothing is lost. A bar whose tabs render as different element types is\n * incoherent by construction, and framework links still arrive the documented\n * way — wrap the bar in `<LinkProvider component={NextLink}>`. `SideNav` sets\n * the same precedent: it renders `Link` internally and never forwards `as`.\n */\ntype TabNavLinkProps = Omit<LinkProps, 'variant' | 'as'> & {\n /**\n * Force the current state, overriding the bar's `currentHref` comparison.\n *\n * The escape hatch for any matching rule other than equality — prefix\n * matching for a nested route, ignoring a query string, treating an index\n * page as current for its children. Compute it from your router and set it\n * here; `TabNav` does not guess.\n *\n * Also the only way to mark the current tab when `href` is a url object,\n * which cannot be compared to a pathname string.\n */\n current?: boolean\n}\n\n/**\n * Dev-only guard, mirroring the misshapen-item check in `SideNav`: a link\n * outside a `TabNav` gets no context and renders an `<li>` with no list around\n * it. No-op in production.\n *\n * The message is careful about what is actually lost. An orphan can still be\n * marked by passing `current` directly — `current ?? …` short-circuits before\n * the context is read — so claiming no tab will be marked would be false\n * exactly when a caller has reached for that escape hatch. What an orphan\n * cannot do is derive the current tab from `currentHref`.\n */\nfunction warnIfOrphaned(hasContext: boolean) {\n if (process.env.NODE_ENV === 'production' || hasContext) {\n return\n }\n console.warn(\n '[nswds/ui] TabNavLink rendered outside a TabNav — it cannot read currentHref, so the current tab is never derived automatically (only an explicit `current` still applies), and its <li> sits outside any list. Wrap the links in <TabNav>.',\n )\n}\n\n/**\n * One tab: a link to a peer page, marked `aria-current='page'` when it is the\n * one being read.\n *\n * Renders its own `<li>`, so `TabNav`'s children are tabs rather than list\n * items — the compound shape `Header`/`HeaderBrand` and `Footer`/`FooterNav`\n * already use.\n */\nfunction TabNavLink({ className, children, current, href, ...props }: TabNavLinkProps) {\n const context = React.useContext(TabNavContext)\n\n warnIfOrphaned(context !== null)\n\n // Exact match only, and only for string hrefs — see `TabNav`'s `currentHref`\n // for why prefix matching is not offered, and `current` for url objects.\n const isCurrent =\n current ??\n (context?.currentHref !== undefined && typeof href === 'string' && href === context.currentHref)\n\n return (\n <li data-slot='tab-nav-item' className='flex'>\n {/* variant='unstyled' — the bar supplies the complete tab treatment, and\n Link's underline/colour variants would fight it. Rendering through\n Link still picks up the framework link component from LinkProvider. */}\n {/* `{...props}` spreads FIRST so the computed state below always wins. A\n consumer passing their own `aria-current` would otherwise silently\n beat the `current` prop, leaving two sources of truth for one state. */}\n <Link\n {...props}\n variant='unstyled'\n data-slot='tab-nav-link'\n data-active={isCurrent ? '' : undefined}\n href={href}\n aria-current={isCurrent ? 'page' : undefined}\n className={cn(tabNavLinkVariants({ current: isCurrent }), className)}\n >\n {children}\n </Link>\n </li>\n )\n}\n\nexport { TabNav, TabNavLink, tabNavLinkVariants, tabNavListVariants }\nexport type { TabNavLinkProps, TabNavProps }\n"]}
package/dist/index.d.ts CHANGED
@@ -35,6 +35,7 @@ export { Slider, SliderControl, SliderIndicator, SliderLabel, SliderProps, Slide
35
35
  export { Toaster } from './components/sonner.js';
36
36
  export { Spinner, SpinnerProps } from './components/spinner.js';
37
37
  export { Step, StepIndicator, StepIndicatorProps, StepNav, StepNavProps, StepNavSection, StepStatus, stepStatusStyles } from './components/step-indicator.js';
38
+ export { TabNav, TabNavLink, TabNavLinkProps, TabNavProps, tabNavLinkVariants, tabNavListVariants } from './components/tab-nav.js';
38
39
  export { ThemeSwitcher, ThemeSwitcherProps, ThemeSwitcherTheme } from './components/theme-switcher.js';
39
40
  export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './components/tooltip.js';
40
41
  export { UseChromeHeightOptions, UseChromeHeightResult, useChromeHeight } from './hooks/use-chrome-height.js';
package/dist/index.js CHANGED
@@ -35,6 +35,7 @@ export * from './components/slider.js';
35
35
  export * from './components/sonner.js';
36
36
  export * from './components/spinner.js';
37
37
  export * from './components/step-indicator.js';
38
+ export * from './components/tab-nav.js';
38
39
  export * from './components/theme-switcher.js';
39
40
  export * from './components/tooltip.js';
40
41
  export * from './hooks/use-chrome-height.js';