An open source design system that's fully customizable and agent ready
TypeScript
feat(SideNav): keep nested items full width and indent their content (#7594)
Kenton Quatman27c8c55f273b
diff --git a/.changeset/sidenav-nested-full-width.md b/.changeset/sidenav-nested-full-width.mdnew file mode 100644index 0000000000..d5965dcce8--- /dev/null+++ b/.changeset/sidenav-nested-full-width.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] `SideNavItem`: nested items now span the full width of the nav list, like top-level items, so their hover and selected fill lines up with the rows above them. Before, a nested item started 24px in from the list edge. The indent now sits inside the row, one `--spacing-6` step per nesting level, so icons and labels stay exactly where they were. The indent area is now part of the nested row, so it shows hover feedback and clicking it activates the item. Content placed directly inside a `SideNavItem` that is not itself a `SideNavItem` is no longer inset by the children group. There is no supported way to keep the old inset look.++@kentonquatmandiff --git a/packages/core/src/SideNav/SideNav.test.tsx b/packages/core/src/SideNav/SideNav.test.tsxindex d1fd579655..5e11d58ad3 100644--- a/packages/core/src/SideNav/SideNav.test.tsx+++ b/packages/core/src/SideNav/SideNav.test.tsx@@ -828,6 +828,169 @@ describe('SideNavItem', () => {expect(screen.getByText('Security')).toBeInTheDocument();});+ it('keeps nested rows full width and indents their content inside the row', () => {+ render(+ <SideNavItem label="Settings">+ <SideNavItem label="General" href="/settings/general">+ <SideNavItem label="Advanced" href="/settings/general/advanced" />+ </SideNavItem>+ </SideNavItem>,+ );++ // The children group adds no inset of its own, so a nested row's hover+ // and selected fill spans the nav list like a top-level row's.+ const groups = screen.getAllByRole('group', {hidden: true});+ for (const group of groups) {+ expect(declaredOn(group, 'padding-inline-start')).toEqual([]);+ expect(+ declaredOn(group.firstElementChild!, 'padding-inline-start'),+ ).toEqual([]);+ }++ // The indent lives inside each row instead, one step per nesting level.+ // An ordinary row is the link itself: its own padding plus the steps.+ const top = screen.getByRole('button', {name: 'Settings'});+ const general = screen.getByRole('link', {name: 'General'});+ const advanced = screen.getByRole('link', {name: 'Advanced'});+ expect(indentOf(top)).toBeNull();+ expect(indentOf(advanced)).toBe(+ 'calc(var(--spacing-2) + 2 * var(--spacing-6))',+ );++ // A split row (own href plus children) keeps the wrapper's base padding+ // and puts the steps on the link, so the whole indent is clickable+ // instead of dead space that still shows hover and press feedback.+ expect(indentOf(general.parentElement!)).toBeNull();+ expect(indentOf(general)).toBe('calc(1 * var(--spacing-6))');+ });++ it('clips the children group only while it is collapsed', async () => {+ // Nested rows sit flush with the group, so a permanent clip would cut off+ // their focus ring. The group clips for the collapse animation only.+ const user = userEvent.setup();+ render(+ <SideNavItem label="Settings" collapsible>+ <SideNavItem label="General" href="/settings/general" />+ </SideNavItem>,+ );+ const group = () => screen.getByRole('group', {hidden: true});+ expect(declaredOn(group(), 'overflow')).toEqual(['visible']);+ expect(declaredOn(group().firstElementChild!, 'overflow')).toEqual([]);++ await user.click(screen.getByRole('button', {name: 'Settings'}));+ expect(declaredOn(group(), 'overflow')).toEqual(['hidden']);+ });++ it('puts the indent on the primary link of a nested actions row', () => {+ render(+ <SideNavItem label="Projects">+ <SideNavItem+ label="Alpha"+ href="/projects/alpha"+ actions={+ <button type="button" aria-label="Alpha actions">+ More+ </button>+ }+ />+ </SideNavItem>,+ );+ const alpha = screen.getByRole('link', {name: 'Alpha'});+ expect(indentOf(alpha.parentElement!)).toBeNull();+ expect(indentOf(alpha)).toBe('calc(1 * var(--spacing-6))');+ });++ it("composes a caller's style with the indent on a nested row", () => {+ render(+ <SideNavItem label="Settings">+ <SideNavItem+ label="General"+ href="/settings/general"+ style={{color: 'rebeccapurple'}}+ />+ <SideNavItem+ label="Security"+ href="/settings/security"+ style={{color: 'rebeccapurple'}}>+ <SideNavItem label="Keys" href="/settings/security/keys" />+ </SideNavItem>+ </SideNavItem>,+ );+ // Ordinary row: the link is the row.+ const general = screen.getByRole('link', {name: 'General'});+ expect(general.style.color).toBe('rebeccapurple');+ expect(indentOf(general)).toBe(+ 'calc(var(--spacing-2) + 1 * var(--spacing-6))',+ );+ // Split row: the caller's style still lands on the primary link.+ const security = screen.getByRole('link', {name: 'Security'});+ expect(security.style.color).toBe('rebeccapurple');+ expect(indentOf(security)).toBe('calc(1 * var(--spacing-6))');+ });++ it("lets a caller's inline-start padding replace the indent", () => {+ // The caller's `style` composes after the indent: a caller-set+ // inline-start padding is an inline declaration, so it wins over the+ // indent's class rule on the element that carries the indent, on both+ // the ordinary and the split row path.+ render(+ <SideNavItem label="Settings">+ <SideNavItem+ label="General"+ href="/settings/general"+ style={{paddingInlineStart: '20px'}}+ />+ <SideNavItem+ label="Security"+ href="/settings/security"+ style={{paddingInlineStart: '20px'}}>+ <SideNavItem label="Keys" href="/settings/security/keys" />+ </SideNavItem>+ </SideNavItem>,+ );+ const general = screen.getByRole('link', {name: 'General'});+ expect(general.style.paddingInlineStart).toBe('20px');+ const security = screen.getByRole('link', {name: 'Security'});+ expect(security.style.paddingInlineStart).toBe('20px');+ // A row whose caller sets no padding keeps its indent.+ expect(indentOf(screen.getByRole('link', {name: 'Keys'}))).toBe(+ 'calc(var(--spacing-2) + 2 * var(--spacing-6))',+ );+ });++ it('indents a small nested row from the small row padding', () => {+ render(+ <SideNavItem label="Settings">+ <SideNavItem label="General" href="/settings/general" size="sm" />+ </SideNavItem>,+ );+ expect(indentOf(screen.getByRole('link', {name: 'General'}))).toBe(+ 'calc(var(--spacing-1) + 1 * var(--spacing-6))',+ );+ });++ it('does not indent the first level of a collapsed rail flyout', async () => {+ const user = userEvent.setup();+ renderCollapsed(+ <SideNavItem label="Settings" icon={StubIcon}>+ <SideNavItem label="General" href="/settings/general">+ <SideNavItem label="Advanced" href="/settings/general/advanced" />+ </SideNavItem>+ </SideNavItem>,+ );+ await user.click(screen.getByRole('button', {name: 'Settings'}));++ // jsdom leaves the native popover `display: none`, hence `hidden: true`.+ // The flyout lists the parent's children as its own top level.+ const general = screen.getByRole('link', {name: 'General', hidden: true});+ const advanced = screen.getByRole('link', {name: 'Advanced', hidden: true});+ expect(indentOf(general)).toBeNull();+ expect(indentOf(general.parentElement!)).toBeNull();+ expect(indentOf(advanced)).toBe(+ 'calc(var(--spacing-2) + 1 * var(--spacing-6))',+ );+ });+it('passes data-testid', () => {render(<SideNavItem label="Dashboard" data-testid="nav-item" />);expect(screen.getByTestId('nav-item')).toBeInTheDocument();@@ -2457,6 +2620,22 @@ function declaredOn(el: Element, prop: string): string[] {.filter(value => value != null);}+/**+ * The nesting indent a row carries, or null for none. The indent is a+ * runtime StyleX value, so it rides the row's inline style as a custom+ * property; read the value rather than the generated property name.+ */+function indentOf(el: HTMLElement): string | null {+ const {style} = el;+ for (let i = 0; i < style.length; i++) {+ const value = style.getPropertyValue(style[i]).trim();+ if (value.includes('var(--spacing-6)')) {+ return value;+ }+ }+ return null;+}+/*** The selectors that actually paint the shared ring on `el`, read out of the* live stylesheet with StyleX's `:not(#\#)` specificity padding stripped sodiff --git a/packages/core/src/SideNav/SideNavItem.doc.mjs b/packages/core/src/SideNav/SideNavItem.doc.mjsindex eb1fd9650b..8a3c210024 100644--- a/packages/core/src/SideNav/SideNavItem.doc.mjs+++ b/packages/core/src/SideNav/SideNavItem.doc.mjs@@ -90,7 +90,7 @@ export const docs = {{name: 'children',type: 'ReactNode',- description: 'Sub-items for nesting.',+ description: 'Sub-items for nesting. Nested items span the full width of the nav list, like top-level items; their content is indented one step per nesting level.',slotElements: [{__element: 'SideNavItem',@@ -213,7 +213,7 @@ export const docsDense = {'Passive right-side content only (badges, counts). Interactive controls go in actions.',actions:'Row-level secondary controls (icon buttons, menus) rendered as siblings of the primary element, after the expand/collapse toggle and before nested children in DOM/focus order. Inherit the row control size via SizeContext (explicit size wins). Hidden when rail collapsed. Passive content goes in endContent; interactive content goes here.',- children: 'Sub-items for nesting.',+ children: 'Sub-items for nesting. Nested rows stay full width; content indents one step per level.',collapsible: 'Enables collapse for items w/ children. true=uncontrolled, object=controlled mode.',size: "Row size variant: 'sm' | 'md' | 'lg'.",},diff --git a/packages/core/src/SideNav/SideNavItem.tsx b/packages/core/src/SideNav/SideNavItem.tsxindex de841443b5..e0cd86d695 100644--- a/packages/core/src/SideNav/SideNavItem.tsx+++ b/packages/core/src/SideNav/SideNavItem.tsx@@ -17,6 +17,11 @@* `TopNavMenu` use). Hover is a progressive enhancement over the popover's* click behavior and is inert on coarse pointers.*+ * Nested rows span the full width of the nav list, like top-level rows, so+ * their hover and selected fill lines up with the rows above them. The+ * nesting indent sits inside the row as extra inline-start padding, one step+ * per level, tracked through a private depth context.+ ** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/SideNav/SideNav.doc.mjs* - /packages/core/src/SideNav/SideNav.test.tsx@@ -26,6 +31,8 @@*/import {+ createContext,+ use,useCallback,useId,useMemo,@@ -108,26 +115,45 @@ const styles = stylex.create({gap: spacingVars['--spacing-1'],pointerEvents: 'auto',},- children: {- paddingInlineStart: spacingVars['--spacing-6'],- },+ // The group clips its rows only for the 0fr collapse animation. Nested rows+ // sit flush with the group, so a permanent clip would cut off their focus+ // ring, which paints outside the row. The expanded group therefore stops+ // clipping once it has finished opening: `overflow` is discrete, so it rides+ // the same transition with `allow-discrete` and a delay equal to the open+ // duration, holding `hidden` until the rows' height has settled. Collapsing+ // flips back to `hidden` at once (no delay on the collapsed state), so+ // nothing spills while the group closes.+ //+ // Reduced fallback: a browser without `transition-behavior: allow-discrete`+ // (the tier below current Baseline) cannot delay the switch, so the group+ // stops clipping as soon as it starts opening and the opening rows briefly+ // overlap the row below. The group still opens and the ring still shows.childrenCollapsible: {display: 'grid',gridTemplateRows: '1fr',- transitionProperty: 'grid-template-rows',+ overflow: 'visible',+ transitionProperty: 'grid-template-rows, overflow',+ transitionBehavior: 'allow-discrete',transitionDuration: {- default: durationVars['--duration-medium'],- '@media (prefers-reduced-motion: reduce)': '0s',+ default: `${durationVars['--duration-medium']}, 0s`,+ '@media (prefers-reduced-motion: reduce)': '0s, 0s',+ },+ transitionDelay: {+ default: `0s, ${durationVars['--duration-medium']}`,+ '@media (prefers-reduced-motion: reduce)': '0s, 0s',},transitionTimingFunction: easeVars['--ease-standard'],},childrenCollapsed: {gridTemplateRows: '0fr',+ overflow: 'hidden',+ transitionDelay: '0s, 0s',},+ // No inline padding: nested rows fill the full width of the nav list, and+ // each row carries its own indent (`indentStyles` below). `minHeight: 0`+ // lets the 0fr track shrink this item to nothing; the group clips it.childrenInner: {- overflow: 'hidden',minHeight: 0,- paddingInlineStart: spacingVars['--spacing-6'],},expandChevron: {display: 'inline-flex',@@ -232,6 +258,35 @@ const styles = stylex.create({},});+// Nesting indent, drawn inside the row: one `--spacing-6` step per nesting+// level. The row itself stays full width, so its hover and selected fill+// matches a top-level row's.+// - `sm` / `md` — the ordinary row, where the row element is the link or+// button: its own inline-start padding plus the steps.+// SYNC: the base padding matches navItemStyles.sm / .md / .lg.+// - `primary` — the row-wrapper path: the wrapper keeps its base padding and+// the steps go on the primary link or button, so the whole indent is part+// of the click target rather than dead space that still shows feedback.+const indentStyles = stylex.create({+ sm: (depth: number) => ({+ paddingInlineStart: `calc(${spacingVars['--spacing-1']} + ${depth} * ${spacingVars['--spacing-6']})`,+ }),+ md: (depth: number) => ({+ paddingInlineStart: `calc(${spacingVars['--spacing-2']} + ${depth} * ${spacingVars['--spacing-6']})`,+ }),+ primary: (depth: number) => ({+ paddingInlineStart: `calc(${depth} * ${spacingVars['--spacing-6']})`,+ }),+});++/**+ * How many SideNavItems deep the current item sits: 0 at the top level,+ * 1 inside one parent, and so on. A collapsed rail's flyout resets it to 0,+ * since the flyout lists a parent's children as its own top level.+ */+const SideNavItemDepthContext = createContext(0);+SideNavItemDepthContext.displayName = 'SideNavItemDepthContext';+/*** Cascaded to the `actions` slot through `SizeContext` so a consumer's row* controls come out the same height as the built-in expand/collapse toggle,@@ -363,7 +418,9 @@ export interface SideNavItemProps extends BaseProps<HTMLElement> {*/actions?: ReactNode;/**- * Sub-items for nesting.+ * Sub-items for nesting. Nested items span the full width of the nav+ * list, like top-level items; their content is indented one step per+ * nesting level.*/children?: ReactNode;/**@@ -455,6 +512,7 @@ export function SideNavItem({const id = useId();const hasChildren = !!children;const itemRef = useRef<HTMLDivElement>(null);+ const depth = use(SideNavItemDepthContext);// Popover for collapsed items with childrenconst popover = usePopover({@@ -608,7 +666,9 @@ export function SideNavItem({onClick={() => popover.hide()}><div {...stylex.props(styles.popoverHeader)}>{label}</div><SideNavCollapseContext value={EXPANDED_COLLAPSE_STATE}>- {children}+ <SideNavItemDepthContext value={0}>+ {children}+ </SideNavItemDepthContext></SideNavCollapseContext></div>,{placement: 'end', alignment: 'start', xstyle: styles.popoverGap},@@ -686,6 +746,14 @@ export function SideNavItem({isSelected && navItemStyles.selected,isDisabled && navItemStyles.disabled,] as const;+ const rowIndent =+ depth > 0 && indentStyles[size === 'sm' ? 'sm' : 'md'](depth);+ const primaryIndent = depth > 0 && indentStyles.primary(depth);++ // The indent is a runtime value, so it reaches the element as an inline+ // style. These props are spread after `rest`, so fold the caller's `style`+ // back in (caller wins) rather than letting the indent replace it.+ const callerStyle = {style: rest.style};// Three shapes of the same row appearance:// - `rowProps` — split-action path (toggle, no actions): presentational@@ -702,7 +770,10 @@ export function SideNavItem({const focusableRowProps = {...mergeProps(itemThemeProps,- focusOutlineProps.focusVisible(...itemStyleArgs),+ mergeProps(+ focusOutlineProps.focusVisible(...itemStyleArgs, rowIndent),+ callerStyle,+ ),),...pressable,};@@ -748,11 +819,17 @@ export function SideNavItem({onClick={handleClick}{...rest}{...rowPrimaryAriaProps}- {...(hasActions- ? // The wrapper rings for this element; suppressing here is what- // keeps the UA's own ring from painting inside that one.- focusOutlineProps.suppressed(styles.splitAction)- : focusOutlineProps.focusVisible(styles.splitAction))}>+ {...mergeProps(+ hasActions+ ? // The wrapper rings for this element; suppressing here is what+ // keeps the UA's own ring from painting inside that one.+ focusOutlineProps.suppressed(styles.splitAction, primaryIndent)+ : focusOutlineProps.focusVisible(+ styles.splitAction,+ primaryIndent,+ ),+ callerStyle,+ )}>{itemContent}</NavItemElement>{hasIndependentToggle && (@@ -831,7 +908,9 @@ export function SideNavItem({<span id={`${id}-label`} hidden>{label}</span>- {children}+ <SideNavItemDepthContext value={depth + 1}>+ {children}+ </SideNavItemDepthContext></div></div>)}