basalt-ui 2.13.0 → 2.13.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.
@@ -7,6 +7,8 @@ import {
7
7
  useCallback,
8
8
  useContext,
9
9
  useDeferredValue,
10
+ useEffect,
11
+ useId,
10
12
  useMemo,
11
13
  useRef,
12
14
  useState
@@ -38,28 +40,43 @@ const NO_REGION = {
38
40
  const AsideContext = createContext(NO_REGION);
39
41
  function AsideProvider({ children }) {
40
42
  const [target, setTarget] = useState(null);
41
- const [claims, setClaims] = useState(0);
42
- const [folded, setFolded] = useState(false);
43
+ const [{ ids, folds }, setClaims] = useState({ ids: [], folds: {} });
43
44
  const [closeSignal, setCloseSignal] = useState(0);
44
- const claim = useCallback(() => {
45
- setClaims((n) => n + 1);
46
- return () => {
47
- setClaims((n) => n - 1);
48
- setFolded(false);
49
- };
45
+ const claim = useCallback((id) => {
46
+ setClaims((s) => ({ ...s, ids: [...s.ids, id] }));
47
+ return () => setClaims((s) => ({
48
+ ids: s.ids.filter((x) => x !== id),
49
+ folds: Object.fromEntries(Object.entries(s.folds).filter(([k]) => k !== id))
50
+ }));
51
+ }, []);
52
+ const publishFolded = useCallback((id, folded2) => {
53
+ setClaims(
54
+ (s) => !s.ids.includes(id) || s.folds[id] === folded2 ? s : { ...s, folds: { ...s.folds, [id]: folded2 } }
55
+ );
50
56
  }, []);
51
57
  const requestClose = useCallback(() => setCloseSignal((n) => n + 1), []);
52
- const value = {
53
- target,
54
- setTarget,
55
- inShell: true,
56
- claimed: claims > 0,
57
- folded,
58
- claim,
59
- publishFolded: setFolded,
60
- closeSignal,
61
- requestClose
62
- };
58
+ useEffect(() => {
59
+ if (process.env.NODE_ENV === "production" || ids.length < 2) return;
60
+ console.warn(
61
+ "[basalt] more than one PageAside is mounted at once; the newest claimant owns the region. Render one per page."
62
+ );
63
+ }, [ids.length]);
64
+ const owner = ids.at(-1);
65
+ const folded = owner !== void 0 && folds[owner] === true;
66
+ const value = useMemo(
67
+ () => ({
68
+ target,
69
+ setTarget,
70
+ inShell: true,
71
+ claimed: owner !== void 0,
72
+ folded,
73
+ claim,
74
+ publishFolded,
75
+ closeSignal,
76
+ requestClose
77
+ }),
78
+ [target, owner, folded, claim, publishFolded, closeSignal, requestClose]
79
+ );
63
80
  return /* @__PURE__ */ jsx(AsideContext.Provider, { value, children });
64
81
  }
65
82
  function useAsideRegion() {
@@ -132,6 +149,7 @@ function PageAside(props) {
132
149
  const { title, persistKey, defaultFolded, children, className, style, classNames } = props;
133
150
  const { target, inShell, claim, publishFolded, closeSignal } = useContext(AsideContext);
134
151
  const docks = useContext(AsideDocksContext);
152
+ const id = useId();
135
153
  const { host: panelHost, claim: claimPanel, target: panelTarget } = useAsidePanelSlot();
136
154
  const isCompact = useSizeClass() === "compact";
137
155
  const [folded, storeFolded] = usePersistedOrLocal({
@@ -153,12 +171,12 @@ function PageAside(props) {
153
171
  }, []);
154
172
  useIsomorphicLayoutEffect(() => {
155
173
  if (!portalled) return;
156
- return claim();
157
- }, [portalled, claim]);
174
+ return claim(id);
175
+ }, [portalled, claim, id]);
158
176
  useIsomorphicLayoutEffect(() => {
159
177
  if (!portalled) return;
160
- publishFolded(folded);
161
- }, [portalled, folded, publishFolded]);
178
+ publishFolded(id, folded);
179
+ }, [portalled, folded, publishFolded, id]);
162
180
  const closeSignalBaseline = useRef(closeSignal);
163
181
  useIsomorphicLayoutEffect(() => {
164
182
  if (!portalled || closeSignal === closeSignalBaseline.current) return;
@@ -8,7 +8,7 @@ export declare const PAGE_BAR_HEIGHT_VAR = "--basalt-page-bar-h";
8
8
  * What a `PageAside` publishes when it projects itself into row 2 below `sm`
9
9
  * (`docs/ASIDE-SPEC.md` §0 "Desktop and mobile are one declaration"). Metadata only — the aside's
10
10
  * CHILDREN never travel through this context: they are portalled into the sheet's own node
11
- * ({@link PageBarSlots.panelTarget}), because a `ReactNode` in state would be a fresh object on
11
+ * ({@link AsidePanelSlot.panelTarget}), because a `ReactNode` in state would be a fresh object on
12
12
  * every parent render and the claim effect would loop.
13
13
  */
14
14
  export type AsidePanelClaim = {
@@ -1 +1 @@
1
- {"version":3,"file":"page-bar.d.ts","sourceRoot":"","sources":["../../src/shell/page-bar.tsx"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AAGtC,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAWnE,OAAO,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AAClF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAK9D,mEAAmE;AACnE,eAAO,MAAM,mBAAmB,wBAAwB,CAAA;AAExD;;;;;;GAMG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,gFAAgF;IAChF,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,gGAAgG;IAChG,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAA;CACzB,CAAA;AAuDD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,EAC9B,aAAa,EACb,QAAQ,GACT,EAAE;IACD,aAAa,EAAE,SAAS,YAAY,EAAE,CAAA;IACtC,QAAQ,EAAE,SAAS,CAAA;CACpB,GAAG,SAAS,CAsDZ;AAED,iFAAiF;AACjF,wBAAgB,aAAa,CAAC,EAAE,SAAS,EAAE,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,+BAGlE;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,SAAS,EAAE,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,+BAGtE;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,IAAI,OAAO,CAE3C;AAED,yFAAyF;AACzF,wBAAgB,mBAAmB,IAAI,OAAO,CAE7C;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,iB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,SAAS,CAAA;IAChB,OAAO,CAAC,EAAE,cAAc,CAAA;IACxB,qGAAqG;IACrG,IAAI,CAAC,EAAE,IAAI,CAAC,eAAe,EAAE,OAAO,CAAC,CAAA;IACrC,6CAA6C;IAC7C,OAAO,CAAC,EAAE,SAAS,CAAA;IACnB,sDAAsD;IACtD,UAAU,CAAC,EAAE,SAAS,EAAE,CAAA;IACxB,sBAAsB;IACtB,IAAI,CAAC,EAAE,SAAS,CAAA;CACjB,CAAA;AA6EH;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,OAAO,CAAC,EACtB,KAAK,EACL,IAAI,EACJ,OAAO,EACP,IAAI,EACJ,OAAO,EACP,UAAU,EACV,IAAI,EACJ,SAAS,EACT,KAAK,EACL,UAAU,GACX,EAAE,YAAY,GAAG,SAAS,CAmM1B"}
@@ -1,5 +1,5 @@
1
1
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
- import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
2
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
3
3
  import { createPortal } from "react-dom";
4
4
  import { cx } from "../common/props.js";
5
5
  import { CtlSlot } from "../theme/index.js";
@@ -16,18 +16,15 @@ import { useIsomorphicLayoutEffect } from "../common/isomorphic-layout-effect.js
16
16
  import classes from "./page-bar.module.css";
17
17
  import asideClasses from "./page-aside.module.css";
18
18
  const PAGE_BAR_HEIGHT_VAR = "--basalt-page-bar-h";
19
- const NO_SLOTS = {
19
+ const NO_TARGETS = {
20
20
  target: null,
21
21
  setTarget: () => {
22
22
  },
23
23
  bandTarget: null,
24
24
  setBandTarget: () => {
25
- },
26
- inShell: false,
27
- mobileMoreActions: [],
28
- kebabClaims: 0,
29
- claimKebab: () => () => {
30
- },
25
+ }
26
+ };
27
+ const NO_PANEL_SLOT = {
31
28
  panelHost: false,
32
29
  claimPanelHost: () => () => {
33
30
  },
@@ -38,7 +35,10 @@ const NO_SLOTS = {
38
35
  setPanelTarget: () => {
39
36
  }
40
37
  };
41
- const PageBarContext = createContext(NO_SLOTS);
38
+ const PortalTargetsContext = createContext(NO_TARGETS);
39
+ const AsidePanelContext = createContext(NO_PANEL_SLOT);
40
+ const InShellContext = createContext(false);
41
+ const KebabClaimedContext = createContext(false);
42
42
  function PageBarProvider({
43
43
  globalActions,
44
44
  children
@@ -63,41 +63,45 @@ function PageBarProvider({
63
63
  setPanel((current) => current === next ? null : current);
64
64
  };
65
65
  }, []);
66
- const mobileMoreActions = globalActions.filter((action, index) => (action.mobile ?? (index < 2 ? "bar" : "more")) === "more").map(globalActionAsBarAction);
67
- const value = {
68
- target,
69
- setTarget,
70
- bandTarget,
71
- setBandTarget,
72
- inShell: true,
73
- mobileMoreActions,
74
- kebabClaims,
75
- claimKebab,
76
- panelHost: panelHostClaims > 0,
77
- claimPanelHost,
78
- panel,
79
- claimPanel,
80
- panelTarget,
81
- setPanelTarget
82
- };
83
- return /* @__PURE__ */ jsx(PageBarContext.Provider, { value, children: /* @__PURE__ */ jsx(BarExtrasProvider, { value: { mobileMoreActions, claimKebab }, children }) });
66
+ const mobileMoreActions = useMemo(
67
+ () => globalActions.filter((action, index) => (action.mobile ?? (index < 2 ? "bar" : "more")) === "more").map(globalActionAsBarAction),
68
+ [globalActions]
69
+ );
70
+ const targets = useMemo(
71
+ () => ({ target, setTarget, bandTarget, setBandTarget }),
72
+ [target, bandTarget]
73
+ );
74
+ const panelSlot = useMemo(
75
+ () => ({
76
+ panelHost: panelHostClaims > 0,
77
+ claimPanelHost,
78
+ panel,
79
+ claimPanel,
80
+ panelTarget,
81
+ setPanelTarget
82
+ }),
83
+ [panelHostClaims, claimPanelHost, panel, claimPanel, panelTarget]
84
+ );
85
+ const extras = useMemo(() => ({ mobileMoreActions, claimKebab }), [mobileMoreActions, claimKebab]);
86
+ return /* @__PURE__ */ jsx(InShellContext.Provider, { value: true, children: /* @__PURE__ */ jsx(PortalTargetsContext.Provider, { value: targets, children: /* @__PURE__ */ jsx(KebabClaimedContext.Provider, { value: kebabClaims > 0, children: /* @__PURE__ */ jsx(AsidePanelContext.Provider, { value: panelSlot, children: /* @__PURE__ */ jsx(BarExtrasProvider, { value: extras, children }) }) }) }) });
84
87
  }
85
88
  function PageBarOutlet({ className }) {
86
- const { setTarget } = useContext(PageBarContext);
89
+ const { setTarget } = useContext(PortalTargetsContext);
87
90
  return /* @__PURE__ */ jsx("div", { ref: setTarget, className });
88
91
  }
89
92
  function PageBarBandOutlet({ className }) {
90
- const { setBandTarget } = useContext(PageBarContext);
93
+ const { setBandTarget } = useContext(PortalTargetsContext);
91
94
  return /* @__PURE__ */ jsx("div", { ref: setBandTarget, className });
92
95
  }
93
96
  function useInPageBarShell() {
94
- return useContext(PageBarContext).inShell;
97
+ return useContext(InShellContext);
95
98
  }
96
99
  function usePageKebabClaimed() {
97
- return useContext(PageBarContext).kebabClaims > 0;
100
+ return useContext(KebabClaimedContext);
98
101
  }
99
102
  function useAsidePanelSlot() {
100
- const { panelHost, claimPanel, panelTarget, inShell } = useContext(PageBarContext);
103
+ const { panelHost, claimPanel, panelTarget } = useContext(AsidePanelContext);
104
+ const inShell = useContext(InShellContext);
101
105
  const [settled, setSettled] = useState(false);
102
106
  useIsomorphicLayoutEffect(() => {
103
107
  setSettled(true);
@@ -158,7 +162,9 @@ function PageBar({
158
162
  style,
159
163
  classNames
160
164
  }) {
161
- const { target, bandTarget, inShell, panel, claimPanelHost, setPanelTarget } = useContext(PageBarContext);
165
+ const { target, bandTarget } = useContext(PortalTargetsContext);
166
+ const { panel, claimPanelHost, setPanelTarget } = useContext(AsidePanelContext);
167
+ const inShell = useContext(InShellContext);
162
168
  const [panelOpened, setPanelOpened] = useState(false);
163
169
  const seenPanel = useRef(panel);
164
170
  useEffect(() => {
package/llms.txt CHANGED
@@ -1,4 +1,4 @@
1
- # basalt-ui v2.13.0
1
+ # basalt-ui v2.13.1
2
2
  # Opinionated framework for Mantine-based React apps — theme, app shell, TanStack Charts, toolchain presets
3
3
  #
4
4
  # Entry points: use the exact import specifier below; do not guess.
@@ -13,7 +13,7 @@
13
13
  # A subpath's `Install:` line is its required peers; `OptionalPeers:` are import()-only, install on use.
14
14
 
15
15
  Package: basalt-ui
16
- Version: 2.13.0
16
+ Version: 2.13.1
17
17
 
18
18
  ## basalt-ui
19
19
  Import: import { ... } from 'basalt-ui'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basalt-ui",
3
- "version": "2.13.0",
3
+ "version": "2.13.1",
4
4
  "description": "Opinionated framework for Mantine-based React apps — theme, app shell, TanStack Charts, toolchain presets",
5
5
  "keywords": [
6
6
  "charts",
@@ -121,6 +121,11 @@ export type NavItemId<G> = Extract<keyof NavIndex<G>, string>
121
121
  export type NavGroupId<G> = G extends ReadonlyArray<{ id: infer I }> ? I : never
122
122
  export type NavTabId<G> = NavItemId<G> | NavGroupId<G>
123
123
 
124
+ /**
125
+ * The resolved definition `defineNav` returns. Call `defineNav` at module scope: the shell caches
126
+ * each destination's anchor per config object, so one built inside a component remounts the links
127
+ * on every render.
128
+ */
124
129
  export type NavConfig<
125
130
  G extends ReadonlyArray<AnyNavGroup>,
126
131
  T extends ReadonlyArray<NavTabId<G>>,
@@ -9,10 +9,16 @@
9
9
  * No JSX — anchors are built with `createElement`, so `./router-tanstack` stays a headless,
10
10
  * no-JSX `.ts` module per its own barrel contract.
11
11
  */
12
- import { createElement, forwardRef, useMemo } from 'react'
12
+ import { createElement, forwardRef, useMemo, useState } from 'react'
13
13
  import type { AnchorHTMLAttributes, ElementType, ReactNode } from 'react'
14
14
  import { Link, useMatchRoute, useRouterState } from '@tanstack/react-router'
15
- import type { MobileNavConfig, NavAnchor, SidebarItem, SidebarSection } from '../shell/nav-types'
15
+ import type {
16
+ ActiveCrumb,
17
+ MobileNavConfig,
18
+ NavAnchor,
19
+ SidebarItem,
20
+ SidebarSection,
21
+ } from '../shell/nav-types'
16
22
  import { flattenNav } from './nav-stash'
17
23
  import type { AnyNavGroup, AnyNavItem, NavConfig, NavItemId, NavTabId } from './nav'
18
24
 
@@ -23,7 +29,7 @@ export type UseNavOptions<G extends ReadonlyArray<AnyNavGroup>> = {
23
29
  * Anything else becomes `item.badge` (desktop only).
24
30
  */
25
31
  badges?: Partial<Record<NavItemId<G>, number | ReactNode>>
26
- /** Override active detection entirely. */
32
+ /** Override active detection entirely. Keep it stable (module scope or memoized). */
27
33
  isActive?: (item: AnyNavItem & { id: NavItemId<G> }) => boolean
28
34
  getScrollElement?: () => HTMLElement | null
29
35
  }
@@ -35,15 +41,10 @@ type OverriddenAnchorProps = AnchorHTMLAttributes<HTMLAnchorElement> & {
35
41
  }
36
42
 
37
43
  /**
38
- * The host `Link` renders as when `isActive` overrides the router. A `Link` computes its own
39
- * `isActive` and spreads `aria-current="page"` + `data-status="active"` as the LAST props it
40
- * applies (`@tanstack/react-router` 1.170.x `dist/esm/link.js`, `applyLinkState`), so under an
41
- * override a router-matched loser would still claim the page. `Link` renders `props._asChild` as
42
- * its host element in place of `'a'` (same file, `Link`: `const host = props._asChild || "a"`) —
43
- * an underscore-prefixed, undocumented seam, so `MAINTAINING.md` names it for re-verification on
44
- * every router bump. This host drops the router's two attributes and re-applies only basalt's own
45
- * verdict, which the anchor smuggles through `data-basalt-current`; `data-status` is re-stamped
46
- * for it so both paths expose the same hooks on the winner.
44
+ * The host `Link` renders as when `isActive` overrides the router (via the undocumented
45
+ * `props._asChild` seam, re-verified per router bump in `MAINTAINING.md`). It drops the router's
46
+ * `aria-current` / `data-status` and re-applies only basalt's verdict, passed as
47
+ * `data-basalt-current`, so a router-matched loser cannot claim the page.
47
48
  */
48
49
  const OverriddenAnchor = forwardRef<HTMLAnchorElement, OverriddenAnchorProps>((props, ref) => {
49
50
  const {
@@ -62,7 +63,88 @@ const OverriddenAnchor = forwardRef<HTMLAnchorElement, OverriddenAnchorProps>((p
62
63
  OverriddenAnchor.displayName = 'OverriddenAnchor'
63
64
 
64
65
  /** What this resolver turns a definition into: `ShellFrame`'s sidebar sections and mobile-bar tuning. */
65
- export type ResolvedNav = { sections: SidebarSection[]; mobileNav: MobileNavConfig }
66
+ export type ResolvedNav = {
67
+ sections: SidebarSection[]
68
+ mobileNav: MobileNavConfig
69
+ /** The breadcrumb for the one active destination; `undefined` when nothing matches. */
70
+ activeCrumb: ActiveCrumb | undefined
71
+ }
72
+
73
+ /**
74
+ * One anchor per destination for the life of its `config`: a fresh function per resolve is a new
75
+ * component TYPE and remounts every nav `<a>` on each navigation. Nothing per-render is closed over;
76
+ * active state arrives as the `aria-current` prop. Keyed by override mode because `isActive` swaps
77
+ * the host element (`OverriddenAnchor`).
78
+ */
79
+ const anchorCache = new WeakMap<object, Map<boolean, Map<string, NavAnchor>>>()
80
+
81
+ function anchorFor(config: object, item: AnyNavItem, overridden: boolean): NavAnchor {
82
+ let byMode = anchorCache.get(config)
83
+ if (!byMode) anchorCache.set(config, (byMode = new Map()))
84
+ let byId = byMode.get(overridden)
85
+ if (!byId) byMode.set(overridden, (byId = new Map()))
86
+ const cached = byId.get(item.id)
87
+ if (cached) return cached
88
+ // `exact: true` makes `resolveState` the only authority on active: a `Link` spreads its own
89
+ // `aria-current` LAST and cannot be overridden from outside, so a prefix-matching parent would
90
+ // otherwise claim the page beside its child. `Link as ElementType` is the one cast in the chain.
91
+ const Anchor: NavAnchor = (props) =>
92
+ createElement(Link as ElementType, {
93
+ ...item.link,
94
+ activeOptions: { exact: true, includeSearch: true },
95
+ ...(overridden && {
96
+ _asChild: OverriddenAnchor,
97
+ 'data-basalt-current': props['aria-current'],
98
+ }),
99
+ ...props,
100
+ })
101
+ byId.set(item.id, Anchor)
102
+ return Anchor
103
+ }
104
+
105
+ const NO_BADGES: Readonly<Record<string, unknown>> = {}
106
+
107
+ /** Shallow equality over own keys; `undefined` and `{}` are the same (no badges). */
108
+ function shallowEqual(
109
+ a: Readonly<Record<string, unknown>> = NO_BADGES,
110
+ b: Readonly<Record<string, unknown>> = NO_BADGES,
111
+ ): boolean {
112
+ if (a === b) return true
113
+ const keys = Object.keys(a)
114
+ return (
115
+ keys.length === Object.keys(b).length &&
116
+ keys.every((k) => Object.hasOwn(b, k) && Object.is(a[k], b[k]))
117
+ )
118
+ }
119
+
120
+ /** The breadcrumb for `winnerId`: its group, and its immediate parent when nested. */
121
+ function crumbOf(
122
+ config: { groups: ReadonlyArray<AnyNavGroup> },
123
+ winnerId: string | undefined,
124
+ overridden: boolean,
125
+ ): ActiveCrumb | undefined {
126
+ const find = (
127
+ items: ReadonlyArray<AnyNavItem>,
128
+ section: string,
129
+ parent?: AnyNavItem,
130
+ ): ActiveCrumb | undefined => {
131
+ for (const item of items) {
132
+ if (item.id === winnerId) {
133
+ const parentCrumb = parent && {
134
+ parent: parent.label,
135
+ parentAnchor: anchorFor(config, parent, overridden),
136
+ }
137
+ return { section, page: item.label, ...parentCrumb }
138
+ }
139
+ const nested = item.children && find(item.children, section, item)
140
+ if (nested) return nested
141
+ }
142
+ }
143
+ for (const group of config.groups) {
144
+ const found = find(group.items, group.label)
145
+ if (found) return found
146
+ }
147
+ }
66
148
 
67
149
  /**
68
150
  * Resolve a nav definition against the live router into `BasaltShell`'s internal `ShellFrame`
@@ -79,17 +161,18 @@ export function useNav<
79
161
  // The change signal: one string that moves on every navigation, including search-param-only ones.
80
162
  const href = useRouterState({ select: (s) => s.location.href })
81
163
 
82
- const badges = opts?.badges
164
+ // Keep the previous badges object while every value is unchanged, so an inline literal never
165
+ // rebuilds the sections below. Adjusting state during render is React's sanctioned form of this.
166
+ const [badges, setBadges] = useState(opts?.badges)
167
+ if (!shallowEqual(badges, opts?.badges)) setBadges(opts?.badges)
83
168
  const isActiveOverride = opts?.isActive
84
169
 
85
- const sections = useMemo<SidebarSection[]>(() => {
170
+ const resolved = useMemo<Pick<ResolvedNav, 'sections' | 'activeCrumb'>>(() => {
86
171
  const badgeOf = (id: string): number | ReactNode =>
87
- (badges as Record<string, number | ReactNode> | undefined)?.[id]
172
+ (badges as Readonly<Record<string, number | ReactNode>> | undefined)?.[id]
88
173
 
89
- // Per-item match, exactly as before: the override wins when supplied, otherwise a router
90
- // prefix match (`'/'` stays exact). What changed is that this boolean no longer BECOMES
91
- // `active` on its own — it only says "on the path", and the pass below picks ONE winner
92
- // across the whole definition so a parent and its child can no longer both read `active`.
174
+ // "On the path" only: the override wins, else a router prefix match (`'/'` stays exact). The
175
+ // pass below picks the ONE `active` winner.
93
176
  const matchOf = (item: AnyNavItem): boolean =>
94
177
  isActiveOverride?.(item as AnyNavItem & { id: NavItemId<G> }) ??
95
178
  Boolean(
@@ -100,13 +183,8 @@ export function useNav<
100
183
  }),
101
184
  )
102
185
 
103
- // One pass over the WHOLE flattened definition (`flattenNav` — depth-first, parent then
104
- // children, the same order every other reader of a nav config walks it) rather than a
105
- // per-item independent check, which is what let a parent prefix-match stay lit alongside an
106
- // exact-matching child. The most SPECIFIC match (most non-empty `/`-segments in `link.to`)
107
- // wins; a tie (the playground's `reports`/`components` shape, both pointing at `/components`)
108
- // keeps the FIRST item in definition order, since only a strictly later, strictly longer match
109
- // ever replaces the current winner below.
186
+ // One pass over the flattened definition: the most SPECIFIC match (most `/`-segments in
187
+ // `link.to`) wins, and a tie keeps the FIRST item in definition order.
110
188
  const allItems = flattenNav(config)
111
189
  const specificity = (to: string): number => to.split('/').filter(Boolean).length
112
190
  const matchedById = new Map<string, boolean>()
@@ -124,11 +202,8 @@ export function useNav<
124
202
  }
125
203
  }
126
204
 
127
- // `active` is true for the winner only. `ancestor` is true for a matched item that sits
128
- // strictly on the winner's PATH (`winnerTo` starts with `item.link.to + '/'`) — a same-length
129
- // tie loser matches nothing here (its own `to` cannot be a strict prefix of an equally long
130
- // `winnerTo`), so it reads as neither active nor an ancestor, which is the point: two
131
- // destinations sharing one route are siblings, not a hierarchy.
205
+ // `active` is the winner only; `ancestor` is a matched item strictly on the winner's path. Two
206
+ // destinations sharing one route are siblings, so a tie loser is neither.
132
207
  const resolveState = (item: AnyNavItem): { active: boolean; ancestor: boolean } => {
133
208
  if (item.id === winnerId) return { active: true, ancestor: false }
134
209
  const matched = matchedById.get(item.id) ?? false
@@ -136,45 +211,12 @@ export function useNav<
136
211
  return { active: false, ancestor }
137
212
  }
138
213
 
139
- const toSidebarItem = (item: AnyNavItem): SidebarItem => {
140
- // One anchor per destination. Basalt renders every pixel of chrome around it (desktop row,
141
- // 56px slot, 44px sheet row) and only hosts this component, so `preload`, middle-click and
142
- // back/forward all keep working. `Link as ElementType` is the single cast in the whole
143
- // chain: the widened `AnyNavLink['search']` is `unknown`, which `LinkComponentProps` rejects.
144
- // The consumer gets zero casts, which is the point.
145
- //
146
- // `activeOptions: { exact: true, includeSearch: true }` is what makes `resolveState` above
147
- // the ONLY authority on active, and it is not a preference — a `Link` computes its own
148
- // `isActive` (default `activeOptions.exact: false`, i.e. prefix) and spreads
149
- // `{ 'data-status': 'active', 'aria-current': 'page' }` LAST, after `activeProps` and after
150
- // every caller prop (`@tanstack/react-router/dist/esm/link.js` — `...isActive &&
151
- // STATIC_ACTIVE_PROPS` is the final entry of the returned object). So `aria-current` cannot
152
- // be overridden from outside; the only lever is `isActive` itself. Left at its default, the
153
- // router re-derived the exact fuzzy match this resolver exists to replace, and at
154
- // `/dashboard/sessions` BOTH the parent and the child anchor carried `aria-current="page"`
155
- // even with basalt's own model marking one of them an ancestor — verified in Chrome, and the
156
- // reason the first attempt at this fix measured as no fix at all. `includeSearch` already
157
- // defaults to `true` upstream; naming it here is belt-and-braces so a future default change
158
- // cannot silently reopen the gap.
159
- //
160
- // Exact here does NOT narrow basalt's own law. `resolveState` still matches fuzzily and still
161
- // lights an item whose exact route is never visited; that item is simply named by the
162
- // `aria-current` `app-sidebar.tsx` stamps itself, which survives because the router's spread
163
- // is conditional on ITS `isActive` being true. The CSS side no longer treats `aria-current`
164
- // as a style hook either (`theme/nav-link.module.css`, `shell/app-sidebar.module.css`), so
165
- // `use-nav`'s single `data-active` winner is the one visual authority even if the router's
166
- // own `isActive` ever disagreed.
167
- const Anchor: NavAnchor = (props) =>
168
- createElement(Link as ElementType, {
169
- ...item.link,
170
- activeOptions: { exact: true, includeSearch: true },
171
- ...(isActiveOverride !== undefined && {
172
- _asChild: OverriddenAnchor,
173
- 'data-basalt-current': props['aria-current'],
174
- }),
175
- ...props,
176
- })
214
+ const overridden = isActiveOverride !== undefined
177
215
 
216
+ const toSidebarItem = (item: AnyNavItem): SidebarItem => {
217
+ // One anchor per destination, hosted by basalt's own chrome (desktop row, 56px slot, 44px
218
+ // sheet row), so `preload`, middle-click and back/forward all keep working.
219
+ const Anchor = anchorFor(config, item, overridden)
178
220
  const badge = badgeOf(item.id)
179
221
  const children = item.children?.map(toSidebarItem)
180
222
  const { active, ancestor } = resolveState(item)
@@ -184,10 +226,7 @@ export function useNav<
184
226
  label: item.label,
185
227
  icon: item.icon,
186
228
  Anchor,
187
- // Exactly one destination in the WHOLE definition reads `active` (`resolveState` above).
188
- // Rolling that up into a mobile SLOT (any descendant active → the slot reads active) is
189
- // still `projectMobileNav`'s job, which reads `children` for that. `ancestor` is the
190
- // desktop-only middle state: a matched item that sits on the winner's path but isn't it.
229
+ // Exactly one destination reads `active`; `projectMobileNav` rolls it up into mobile slots.
191
230
  active,
192
231
  ...(ancestor && { ancestor }),
193
232
  ...(item.short !== undefined && { short: item.short }),
@@ -202,7 +241,7 @@ export function useNav<
202
241
  }
203
242
  }
204
243
 
205
- return config.groups.map((group) => ({
244
+ const sections = config.groups.map((group) => ({
206
245
  label: group.label,
207
246
  items: group.items.map(toSidebarItem),
208
247
  ...(group.icon !== undefined && { icon: group.icon }),
@@ -210,6 +249,7 @@ export function useNav<
210
249
  ...(group.defaultCollapsed !== undefined && { defaultCollapsed: group.defaultCollapsed }),
211
250
  ...(group.mobile !== undefined && { mobile: group.mobile }),
212
251
  }))
252
+ return { sections, activeCrumb: crumbOf(config, winnerId, overridden) }
213
253
  // `href` is deliberately an unread dep, and the reason the memo is correct: `matchRoute` has a
214
254
  // STABLE identity (`useCallback(fn, [router])`), so nothing else in this list moves on a
215
255
  // navigation — while the `matchRoute` calls above read router state that just changed. `href`
@@ -239,5 +279,5 @@ export function useNav<
239
279
  }
240
280
  }, [config, mobile, getScrollElement])
241
281
 
242
- return { sections, mobileNav }
282
+ return { ...resolved, mobileNav }
243
283
  }
@@ -41,8 +41,6 @@ export type AppBreadcrumbsProps = BasaltProps & {
41
41
  * client-side. basalt still owns every pixel of the crumb — the anchor only hosts the label.
42
42
  */
43
43
  parentAnchor?: NavAnchor | undefined
44
- /** Parent item href — the no-router fallback; ignored when `parentAnchor` is present. */
45
- parentHref?: string | undefined
46
44
  page?: string
47
45
  }
48
46
 
@@ -50,7 +48,6 @@ export function AppBreadcrumbs({
50
48
  section,
51
49
  parent,
52
50
  parentAnchor,
53
- parentHref,
54
51
  page,
55
52
  className,
56
53
  style,
@@ -89,15 +86,7 @@ export function AppBreadcrumbs({
89
86
  <Text style={separatorStyle}>/</Text>
90
87
  </>
91
88
  )}
92
- {parent && !parentAnchor && parentHref && (
93
- <>
94
- <Anchor style={crumbStyle} underline="never" href={parentHref} truncate>
95
- {parent}
96
- </Anchor>
97
- <Text style={separatorStyle}>/</Text>
98
- </>
99
- )}
100
- {parent && !parentAnchor && !parentHref && (
89
+ {parent && !parentAnchor && (
101
90
  <>
102
91
  <Text style={crumbStyle} truncate>
103
92
  {parent}