An open source design system that's fully customizable and agent ready
TypeScript
fix(SideNav): the collapse copy paints at the rail's own level, with no z-index escalation (#10145)
Cindy Zhanga0fcc977c4cb
diff --git a/.changeset/sidenav-collapse-copy-stacking.md b/.changeset/sidenav-collapse-copy-stacking.mdnew file mode 100644index 0000000000..98e15b7721--- /dev/null+++ b/.changeset/sidenav-collapse-copy-stacking.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] SideNav: during a collapse, the copy of the expanded rail now paints at the rail's own level, just below the rail, instead of at `z-index: 1` with the rail raised to `2`. Page content stacks against the leaving rail as it does against the nav: a positioned sibling with no `z-index` no longer sits under the copy, and content positioned above the nav also covers the copy. The motion's timing and curve are unchanged, and Reduce Motion stays instant.++@cixzhangdiff --git a/docs/specs/components/SideNav/SideNav.spec.md b/docs/specs/components/SideNav/SideNav.spec.mdindex c8407a2469..9882b7366f 100644--- a/docs/specs/components/SideNav/SideNav.spec.md+++ b/docs/specs/components/SideNav/SideNav.spec.md@@ -114,15 +114,15 @@ Consumer migration instructions belong in consumer docs and release notes.## Behavioral and layout contract-| ID | Invariant | Basis | Draft review state |-| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |-| FR1 | SideNav renders its navigation children in a scrollable list, which may be grouped by SideNavSection. A SideNavItem with children renders them, after its own row, in a group labelled by the parent's label; unless `collapsible` is `false`, the group expands and collapses and is hidden from assistive technology and inert while collapsed. | Current source, docs, and tests | Current behavior |-| FR2 | In a collapsed rail, a SideNavItem without an icon is not rendered; a leaf item renders icon-only, named by a non-blank caller `aria-label` or else its label; an item with children renders an icon-only trigger that opens a flyout listing its children as the flyout's top level. | Current source, docs, and tests | Current behavior |-| FR3 | In an expanded rail, in a flyout, and in the mobile navigation drawer, every SideNavItem row MUST span the full inline size of its list at any depth. A row at depth `n` MUST start its content `n` × `--spacing-6` beyond the row's own inline-start padding for its size, inside the row; the nested group MUST add no inset. A flyout's top level is depth 0. | `component:SideNav/DEC-1` | Settled intent; implementation may be staged |-| FR4 | The indent area MUST be part of the row's target: a click there, including a modified or middle click on a link row, does what the same click on the row's primary element does. When the row also carries an independent expand toggle or `actions`, the indent belongs to the primary link or button, and the toggle and actions keep their own activation at the row's trailing edge. | `component:SideNav/DEC-1`; `family:navigation-destinations` | Settled intent; implementation may be staged |-| FR5 | An expanded nested group MUST NOT clip its rows once it has finished opening, so a nested row's focus ring paints in full. The group MAY clip while collapsed and while it opens or closes. | `component:SideNav/DEC-1` | Settled intent; implementation may be staged |-| FR6 | Collapsing or expanding the rail plays one motion on one clock, `spec:AST-105` FR4's one shared motion, the theme's curve tokens, never a spring: layout snaps to the final rail width at once, with no width animation, and the rail reveals or covers its labels by a clip, its edge riding the main content's glide and its labels and collapsed icons fading on the same clock (`spec:AST-105` FR9's inline two-state form; the clip and the ride are the shared edge reveal's, and SideNav's own code keeps only the fades; the rail lends no pane to its resize controller, so a collapse plays once; implementation gap: the clip and the ride still run in SideNav's own rail motion code, not in the shared edge reveal): a collapse ends in the real collapsed state, icons only, and an expand ends in the real expanded state, with its labels. On a collapse or an expand the rail's old state is one transient copy, inert and hidden from assistive technology, removed when the motion ends. The main content moves on the same clock, as `component:AppShell` FR17 states. A change made before the rail first paints lands at once, unless the rail's own toggle made it, so the initial state never animates. Under reduced motion the rail follows `design:reduced-motion` DR2 under a coarse primary pointer and DR3 otherwise. Collapsing or expanding keeps the nav and its items mounted, a `resizable` rail included, so item state such as an open nested group, and focus, persist (AR3 governs focus on what the collapsed rail does not render). | `component:SideNav/DEC-2`; `component:AppShell` FR17; `spec:AST-105` FR8, FR9 | Verified by `SideNavRailMotion.test.tsx` and `SideNavRailMotion.interaction.browser.spec.ts`; the `reducedMotion: 'always'` theme case pending |-| FR7 | `resizable` also takes useResizable's output, beside `true` and its config object (owner decision, 2026-11-04); the region's `autoSaveId` then saves the width. When `resizable` is the hook's output and `collapsible` sets its own collapsed state, the region wins: the rail follows the region's `isCollapsed`, the toggle calls its `collapse` and `expand`, and SideNav warns in development, as `resizable`'s keys already override `collapsible`'s. When `resizable` is the hook's output, the region's own `collapsible` option also decides whether the rail collapses; a collapsible prop that disagrees is ignored, with the same warning. | `component:Resizable` FR9 | Verified by `resizableSlot.test.tsx` |+| ID | Invariant | Basis | Draft review state |+| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1 | SideNav renders its navigation children in a scrollable list, which may be grouped by SideNavSection. A SideNavItem with children renders them, after its own row, in a group labelled by the parent's label; unless `collapsible` is `false`, the group expands and collapses and is hidden from assistive technology and inert while collapsed. | Current source, docs, and tests | Current behavior |+| FR2 | In a collapsed rail, a SideNavItem without an icon is not rendered; a leaf item renders icon-only, named by a non-blank caller `aria-label` or else its label; an item with children renders an icon-only trigger that opens a flyout listing its children as the flyout's top level. | Current source, docs, and tests | Current behavior |+| FR3 | In an expanded rail, in a flyout, and in the mobile navigation drawer, every SideNavItem row MUST span the full inline size of its list at any depth. A row at depth `n` MUST start its content `n` × `--spacing-6` beyond the row's own inline-start padding for its size, inside the row; the nested group MUST add no inset. A flyout's top level is depth 0. | `component:SideNav/DEC-1` | Settled intent; implementation may be staged |+| FR4 | The indent area MUST be part of the row's target: a click there, including a modified or middle click on a link row, does what the same click on the row's primary element does. When the row also carries an independent expand toggle or `actions`, the indent belongs to the primary link or button, and the toggle and actions keep their own activation at the row's trailing edge. | `component:SideNav/DEC-1`; `family:navigation-destinations` | Settled intent; implementation may be staged |+| FR5 | An expanded nested group MUST NOT clip its rows once it has finished opening, so a nested row's focus ring paints in full. The group MAY clip while collapsed and while it opens or closes. | `component:SideNav/DEC-1` | Settled intent; implementation may be staged |+| FR6 | Collapsing or expanding the rail plays one motion on one clock, `spec:AST-105` FR4's one shared motion, the theme's curve tokens, never a spring: layout snaps to the final rail width at once, with no width animation, and the rail reveals or covers its labels by a clip, its edge riding the main content's glide and its labels and collapsed icons fading on the same clock (`spec:AST-105` FR9's inline two-state form; the clip and the ride are the shared edge reveal's, and SideNav's own code keeps only the fades; the rail lends no pane to its resize controller, so a collapse plays once; implementation gap: the clip and the ride still run in SideNav's own rail motion code, not in the shared edge reveal): a collapse ends in the real collapsed state, icons only, and an expand ends in the real expanded state, with its labels. On a collapse or an expand the rail's old state is one transient copy, inert and hidden from assistive technology, removed when the motion ends. On a collapse, the transient copy paints at the rail's own level, just below the rail and with no `z-index` of its own (`spec:AST-027` FR1, FR6); page content positioned above the nav also covers the leaving copy. The main content moves on the same clock, as `component:AppShell` FR17 states. A change made before the rail first paints lands at once, unless the rail's own toggle made it, so the initial state never animates. Under reduced motion the rail follows `design:reduced-motion` DR2 under a coarse primary pointer and DR3 otherwise. Collapsing or expanding keeps the nav and its items mounted, a `resizable` rail included, so item state such as an open nested group, and focus, persist (AR3 governs focus on what the collapsed rail does not render). | `component:SideNav/DEC-2`; `component:AppShell` FR17; `spec:AST-105` FR8, FR9 | Verified by `SideNavRailMotion.test.tsx` and `SideNavRailMotion.interaction.browser.spec.ts`; the `reducedMotion: 'always'` theme case pending |+| FR7 | `resizable` also takes useResizable's output, beside `true` and its config object (owner decision, 2026-11-04); the region's `autoSaveId` then saves the width. When `resizable` is the hook's output and `collapsible` sets its own collapsed state, the region wins: the rail follows the region's `isCollapsed`, the toggle calls its `collapse` and `expand`, and SideNav warns in development, as `resizable`'s keys already override `collapsible`'s. When `resizable` is the hook's output, the region's own `collapsible` option also decides whether the rail collapses; a collapsible prop that disagrees is ignored, with the same warning. | `component:Resizable` FR9 | Verified by `resizableSlot.test.tsx` |### Allowed variationdiff --git a/packages/core/src/SideNav/SideNavRailMotion.test.tsx b/packages/core/src/SideNav/SideNavRailMotion.test.tsxindex 01c47edb1d..735f705889 100644--- a/packages/core/src/SideNav/SideNavRailMotion.test.tsx+++ b/packages/core/src/SideNav/SideNavRailMotion.test.tsx@@ -415,8 +415,12 @@ describe('SideNav rail motion (component:SideNav FR6, component:AppShell FR17)',element => element.querySelector('nav') != null,);expect(railCopies).toHaveLength(1);- const panel = document.querySelector<HTMLElement>('.astryx-layout-panel');- expect(panel?.style.zIndex).toBe('2');+ // The real panel: its copy, placed just before it, carries the same class.+ const panel = document.querySelector<HTMLElement>(+ '.astryx-layout-panel:not([inert])',+ );+ expect(panel?.style.zIndex).toBe('');+ expect(railCopies[0].nextElementSibling).toBe(panel);// Its icons start at the opacity the collapsed rail showed, mostly seen.const icons = recorded.find(entry => entry.element === panel && 'opacity' in entry.keyframes[0],diff --git a/packages/core/src/SideNav/__tests__/SideNavCollapseStacking.a11y.chromium.spec.ts b/packages/core/src/SideNav/__tests__/SideNavCollapseStacking.a11y.chromium.spec.tsnew file mode 100644index 0000000000..9121461101--- /dev/null+++ b/packages/core/src/SideNav/__tests__/SideNavCollapseStacking.a11y.chromium.spec.ts@@ -0,0 +1,157 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope ^(packages/core/src/(SideNav|motion)/|apps/storybook/stories/SideNav\.stories)++/**+ * @file SideNavCollapseStacking.a11y.chromium.spec.ts+ * @input The built collapsible SideNav story, set beside a content column with+ * a positioned header that has no z-index, real Chromium, and its Web+ * Animations clock+ * @output Frame evidence that the collapse's copy of the expanded rail paints at+ * the rail's own level (a later positioned sibling covers it, as it would+ * the rail), that the motion's frames are unchanged, and that Reduce Motion+ * stays instant+ * @position Real-engine proof for component:SideNav FR6; jsdom cannot paint+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const STORY = 'core-sidenav--collapsible-sidebar';+const HEADER = {r: 255, g: 0, b: 255};++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++async function mount(page: Page) {+ await page.setViewportSize({width: 900, height: 600});+ await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);+ await expect(page.locator('nav').first()).toBeVisible();+ // A standalone frame, as an app builds it: the nav beside a content column+ // whose positioned header has no z-index, with no stacking context between.+ await page.evaluate(() => {+ const nav = document.querySelector('nav')!;+ const frame = nav.parentElement!;+ Object.assign(frame.style, {+ display: 'flex',+ width: '100vw',+ height: '100vh',+ overflow: 'hidden',+ });+ const main = document.createElement('main');+ Object.assign(main.style, {+ position: 'relative',+ flex: '1',+ minHeight: '0',+ overflow: 'auto',+ });+ const header = document.createElement('header');+ header.dataset.testid = 'sticky-header';+ Object.assign(header.style, {+ position: 'relative',+ height: '56px',+ background: 'rgb(255, 0, 255)',+ });+ const filler = document.createElement('div');+ filler.style.height = '1200px';+ main.append(header, filler);+ frame.append(main);+ });+ await expect(page.getByTestId('sticky-header')).toBeVisible();+}++/** Collapse, then hold every running animation at `progress` of its length. */+async function collapseAndHold(page: Page, progress: number) {+ await page.getByRole('button', {name: /collapse/i}).click();+ const timings = await page.evaluate(at => {+ return document.getAnimations().map(animation => {+ const timing = animation.effect!.getComputedTiming();+ animation.pause();+ animation.currentTime = Number(timing.duration) * at;+ return {+ duration: Number(timing.duration),+ easing: (animation.effect as KeyframeEffect).getTiming().easing,+ frames: (animation.effect as KeyframeEffect).getKeyframes().length,+ };+ });+ }, progress);+ return {timings};+}++/** The painted color at one viewport point, read from a real screenshot. */+async function pixel(page: Page, x: number, y: number) {+ const shot = await page.screenshot({clip: {x, y, width: 1, height: 1}});+ return page.evaluate(async base64 => {+ const blob = await (await fetch(`data:image/png;base64,${base64}`)).blob();+ const bitmap = await createImageBitmap(blob);+ const canvas = new OffscreenCanvas(1, 1);+ const context = canvas.getContext('2d')!;+ context.drawImage(bitmap, 0, 0);+ const [r, g, b] = context.getImageData(0, 0, 1, 1).data;+ return {r, g, b};+ }, shot.toString('base64'));+}++test("the leaving copy paints at the rail's level: a later positioned sibling covers it, as it would the rail", async ({+ page,+}) => {+ await mount(page);+ // Early in the collapse the copy still covers most of the expanded rail.+ const {timings} = await collapseAndHold(page, 0.15);+ expect(timings.length).toBeGreaterThan(0);+ // The real rail: the copy, placed just before it, is inert.+ const collapsed = await page+ .locator('nav:not([inert]):not([inert] nav)')+ .boundingBox();+ // Just past the collapsed rail, inside the header's band.+ const x = Math.round(collapsed!.x + collapsed!.width + 10);+ await page.screenshot({+ path: test.info().outputPath('collapse-frame.png'),+ clip: {x: 0, y: 0, width: 420, height: 140},+ });+ expect(await pixel(page, x, 28)).toEqual(HEADER);+ // No z-index escalation on the rail or its copy.+ const zIndexes = await page.evaluate(() =>+ [...document.querySelectorAll('nav')].map(nav => nav.style.zIndex),+ );+ expect(zIndexes.every(z => z === '')).toBe(true);+});++test('the collapse keeps its frames and timing, and Reduce Motion stays instant', async ({+ page,+}) => {+ await mount(page);+ const {timings} = await collapseAndHold(page, 0);+ // The receipt of every animation the collapse runs: its length, curve and+ // frame count. The rail's parts share one clock, as on main.+ expect(timings.length).toBeGreaterThan(0);+ const rail = timings.filter(timing => timing.easing === 'linear');+ expect(rail.length).toBeGreaterThan(0);+ for (const timing of rail) {+ expect(timing.duration).toBe(rail[0].duration);+ expect(timing.frames).toBe(rail[0].frames);+ }+ const receipt = timings+ .map(+ ({duration, easing, frames}) =>+ `${duration.toFixed(1)}|${easing}|${frames}`,+ )+ .sort();+ // eslint-disable-next-line no-console -- the receipt is this run's artifact+ console.log(`collapse timings ${JSON.stringify(receipt)}`);++ await page.emulateMedia({reducedMotion: 'reduce'});+ await mount(page);+ await page.getByRole('button', {name: /collapse/i}).click();+ expect(await page.evaluate(() => document.getAnimations().length)).toBe(0);+});diff --git a/packages/core/src/SideNav/__tests__/SideNavRailMotion.interaction.browser.spec.ts b/packages/core/src/SideNav/__tests__/SideNavRailMotion.interaction.browser.spec.tsindex 48c81fb742..3b61feb2ad 100644--- a/packages/core/src/SideNav/__tests__/SideNavRailMotion.interaction.browser.spec.ts+++ b/packages/core/src/SideNav/__tests__/SideNavRailMotion.interaction.browser.spec.ts@@ -788,10 +788,14 @@ test.describe('component:SideNav FR6 and component:AppShell FR17 under a mouse',const reverse = async (blockMs: number) =>page.evaluate(async blockMs => {const toggle = () =>- [...document.querySelectorAll('button')].find(button =>- /^(Collapse|Expand) sidebar$/.test(- button.getAttribute('aria-label') ?? button.textContent ?? '',- ),+ // The leaving copy is inert and sits before the real rail, so its+ // cloned toggle comes first in document order.+ [...document.querySelectorAll('button')].find(+ button =>+ button.closest('[inert]') == null &&+ /^(Collapse|Expand) sidebar$/.test(+ button.getAttribute('aria-label') ?? button.textContent ?? '',+ ),) as HTMLElement;const frame = async () =>new Promise<void>(resolve => {diff --git a/packages/core/src/motion/animatedLayout.edge.test.ts b/packages/core/src/motion/animatedLayout.edge.test.tsindex d90f307cc0..dbeb69644f 100644--- a/packages/core/src/motion/animatedLayout.edge.test.ts+++ b/packages/core/src/motion/animatedLayout.edge.test.ts@@ -454,9 +454,11 @@ describe('the two-state edge reveal (spec:AST-105 FR9)', () => {// Every frame of the copy follows the column's glide.const glide = lastOn(column) as Played;expect(clip.keyframes).toHaveLength(glide.keyframes.length);- // The panel, raised above its copy while it conceals, shows the caller's- // own frames, and drops the raise once the reveal ends.- expect(side.style.zIndex).toBe('2');+ // The copy paints at the panel's own level: just before it, with no+ // z-index, and the panel takes none either.+ expect(copy.nextElementSibling).toBe(side);+ expect(copy.style.zIndex).toBe('');+ expect(side.style.zIndex).toBe('');expect(icons).toHaveBeenCalled();clip.finish?.();expect(side.style.zIndex).toBe('');diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.tsindex 903f8a3f75..faa4d7a75f 100644--- a/packages/core/src/motion/animatedLayout.ts+++ b/packages/core/src/motion/animatedLayout.ts@@ -2228,8 +2228,17 @@ export interface LayoutSwapMotion {readonly copy: (p: number, ride: LayoutRide) => Keyframe;/** Its text's opacity, on its own curve, when that differs from the copy's. */readonly copyText?: (p: number) => number;- /** The copy paints above its neighbours, in the background it shows. */+ /**+ * The copy paints in the background it shows, above its neighbours: at+ * `z-index: 1` as the host's last child, or at `copyBefore`'s level.+ */readonly isOpaque?: boolean;+ /**+ * Place the copy just before this child of the host, at that child's+ * level in the paint order, with no `z-index` of its own. Without it the+ * opaque copy is the host's last child at `z-index: 1`.+ */+ readonly copyBefore?: Element;/*** An element the glide moves, such as the column the old content sat in.* Every part plays over its glide, frame by frame, and is told how far it@@ -2305,9 +2314,11 @@ export function playLayoutSwap(// Captured now: the parts riding a glide play a microtask later, on the// start of the change they are part of.const change = changeStartIn(swap.area, copy.ownerDocument);- placeOver(copy, how.host, swap.rect);+ placeOver(copy, how.host, swap.rect, how.copyBefore ?? null);if (how.isOpaque === true) {- copy.style.zIndex = '1';+ if (how.copyBefore == null) {+ copy.style.zIndex = '1';+ }copy.style.backgroundColor = paintedBackground(copy);}const animations: Animation[] = [];@@ -2684,21 +2695,20 @@ export function playLayoutEdge(while (raised != null && raised.parentElement !== host) {raised = raised.parentElement;}- const restore =- raised == null- ? null- : {position: raised.style.position, zIndex: raised.style.zIndex};- if (raised != null) {- if (getComputedStyle(raised).position === 'static') {- raised.style.position = 'relative';- }- raised.style.zIndex = '2';+ const restore = raised == null ? null : {position: raised.style.position};+ // The copy paints at the element's own level: just before it in the+ // host, with no z-index, so page content stacks against the pair as it+ // does against the element alone. The element, positioned, paints above+ // the copy by tree order.+ if (raised != null && getComputedStyle(raised).position === 'static') {+ raised.style.position = 'relative';}const end = playLayoutSwap({...swap, rect: at},{host,isOpaque: true,+ copyBefore: raised ?? undefined,copy: (p, ride) => ({clipPath: clip(extentOfBox(before) - extentAt(p, ride)),opacity: copyOpacity(p),@@ -2708,7 +2718,6 @@ export function playLayoutEdge(onEnd: () => {if (raised != null && restore != null) {raised.style.position = restore.position;- raised.style.zIndex = restore.zIndex;}},incoming: own.incoming ?? [],diff --git a/packages/core/src/motion/transientCopy.ts b/packages/core/src/motion/transientCopy.tsindex b060208bd6..f99fb39d3b 100644--- a/packages/core/src/motion/transientCopy.ts+++ b/packages/core/src/motion/transientCopy.ts@@ -237,15 +237,16 @@ export function paintedBackground(element: Element): string {}/**- * Lay `element` over `rect` (viewport coordinates), absolutely, as the last- * child of `host`, wherever its containing block is: no ancestor's position- * changes. A copy's scrolled descendants then restore their offsets, and the+ * Lay `element` over `rect` (viewport coordinates), absolutely, as a child of+ * `host` (before `beforeNode`, else last), wherever its containing block is:+ * no ancestor's position changes. A copy's scrolled descendants then restore their offsets, and the* CSS animations and transitions its element ran carry on in it.*/export function placeOver(element: HTMLElement,host: Element,rect: DOMRect,+ beforeNode: Node | null = null,): void {Object.assign(element.style, {position: 'absolute',@@ -256,7 +257,7 @@ export function placeOver(width: `${rect.width}px`,height: `${rect.height}px`,});- host.appendChild(element);+ host.insertBefore(element, beforeNode);// What it inherited where it was, where the host passes something else.const hostStyle = getComputedStyle(host);for (const [name, value] of inheritedValues.get(element) ?? []) {