Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(core): SideNav's rail collapses by snap, clip and cross-fade; AppShell's content moves on its clock (#8723)

Cindy Zhangb8c5e4aee6a9
diff --git a/.changeset/sidenav-rail-motion.md b/.changeset/sidenav-rail-motion.md
new file mode 100644
index 0000000000..2819db30cd
--- /dev/null
+++ b/.changeset/sidenav-rail-motion.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] SideNav's rail no longer snaps when it collapses or expands. Layout snaps to the new width at once, the rail covers or reveals its labels with a clip and ends in its real collapsed state, and inside AppShell the content slides with it, its old line wrapping fading out over the new one, all on one motion (`springs.settle`). Under Reduce Motion it cross-fades with a finger and changes at once otherwise. Nothing animates a width, and no new props.
+
+@cixzhang
diff --git a/apps/storybook/stories/AppShell.stories.tsx b/apps/storybook/stories/AppShell.stories.tsx
index 82a16a6c68..a23e6fa117 100644
--- a/apps/storybook/stories/AppShell.stories.tsx
+++ b/apps/storybook/stories/AppShell.stories.tsx
@@ -133,9 +133,13 @@ function AppTopNav({
* The TopNav already displays the app name, so the SideNav omits its header
* to avoid doubling the identity.
*/
-function SideNavWithoutHeader() {
+function SideNavWithoutHeader({
+ collapsible,
+}: {
+ collapsible?: React.ComponentProps<typeof SideNav>['collapsible'];
+}) {
return (
- <SideNav>
+ <SideNav collapsible={collapsible}>
<SideNavSection title="Main" isHeaderHidden>
<SideNavItem
label="Dashboard"
@@ -544,6 +548,7 @@ export const AutoHeightWithFields: Story = {
*/
export const ControlledCollapse: Story = {
render: function ControlledCollapseStory() {
+ const [isCollapsed, setIsCollapsed] = useState(false);
return (
<AppShell
contentPadding={6}
@@ -553,21 +558,237 @@ export const ControlledCollapse: Story = {
heading={<TopNavHeading heading="Acme App" />}
endContent={
<Button
- label="Toggle sidebar"
+ label={isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'}
variant="ghost"
icon={<Bars3Icon style={{width: 16, height: 16}} />}
isIconOnly
+ onClick={() => setIsCollapsed(collapsed => !collapsed)}
/>
}
/>
}
- sideNav={<SideNavWithoutHeader />}>
+ sideNav={
+ <SideNavWithoutHeader
+ collapsible={{
+ isCollapsed,
+ onCollapsedChange: setIsCollapsed,
+ hasButton: false,
+ }}
+ />
+ }>
<MockContent />
</AppShell>
);
},
};
+/** Placeholder page text only: long lines that rewrap as the rail moves. */
+function PlaceholderPageText() {
+ return (
+ <div {...stylex.props(styles.longContent)}>
+ <Text type="large">Quarterly planning</Text>
+ <Text type="body">
+ Twelve projects are active this quarter and three are archived. Each
+ card shows its owner, its last update and its next milestone, so a long
+ description wraps to the width of the page.
+ </Text>
+ <Text type="body">
+ Collapse the side navigation and the page gets wider: these sentences
+ rewrap. The old wrapping fades out while the new one fades in, as both
+ slide with the rail on one motion. Expand it again and they slide back.
+ </Text>
+ <Text type="body">
+ Nothing animates a width: the layout takes its final size at once, the
+ rail covers or reveals its labels with a clip, and it ends in the real
+ collapsed state, icons only.
+ </Text>
+ </div>
+ );
+}
+
+/**
+ * The rail-collapse stories' code as an app writes it, for the docs' code
+ * panel (Storybook's own source would show the story object around it).
+ * SYNC: When modified, update the render of RailCollapseMotion and
+ * RailCollapseMotionPhone, which run exactly this.
+ */
+const RAIL_COLLAPSE_CODE = `function App() {
+ const [isCollapsed, setIsCollapsed] = useState(false);
+ return (
+ <AppShell
+ contentPadding={6}
+ mobileNav={{breakpoint: 'none'}}
+ sideNav={
+ <SideNav collapsible={{isCollapsed, onCollapsedChange: setIsCollapsed}}>
+ <SideNavSection title="Main" isHeaderHidden>
+ <SideNavItem
+ label="Dashboard"
+ icon={HomeIcon}
+ selectedIcon={HomeIconSolid}
+ isSelected
+ href="#"
+ />
+ <SideNavItem
+ label="Analytics"
+ icon={ChartBarIcon}
+ selectedIcon={ChartBarIconSolid}
+ href="#"
+ />
+ <SideNavItem
+ label="Projects"
+ icon={FolderIcon}
+ selectedIcon={FolderIconSolid}
+ href="#"
+ endContent={<Badge label={12} />}
+ />
+ </SideNavSection>
+ <SideNavSection title="Organization">
+ <SideNavItem
+ label="Team"
+ icon={UserGroupIcon}
+ selectedIcon={UserGroupIconSolid}
+ href="#"
+ />
+ <SideNavItem
+ label="Settings"
+ icon={Cog6ToothIcon}
+ selectedIcon={Cog6ToothIconSolid}
+ href="#"
+ />
+ </SideNavSection>
+ </SideNav>
+ }>
+ <PlaceholderPageText />
+ </AppShell>
+ );
+}`;
+
+/**
+ * The side nav's collapse motion (`component:SideNav` FR6,
+ * `component:AppShell` FR17): an AppShell with a collapsible SideNav whose
+ * collapsed state the app holds. Press the collapse button at the bottom of
+ * the rail: the layout snaps, the rail covers or reveals its labels with a
+ * clip, and the page's old and new wrapping cross-fade as they slide on one
+ * motion. Reduce Motion cross-fades with a finger and changes at once with a
+ * mouse.
+ */
+export const RailCollapseMotion: Story = {
+ name: 'Rail collapse motion',
+ parameters: {docs: {source: {code: RAIL_COLLAPSE_CODE, language: 'tsx'}}},
+ render: function RailCollapseMotionStory() {
+ const [isCollapsed, setIsCollapsed] = useState(false);
+ return (
+ <AppShell
+ contentPadding={6}
+ mobileNav={{breakpoint: 'none'}}
+ sideNav={
+ <SideNav
+ collapsible={{isCollapsed, onCollapsedChange: setIsCollapsed}}>
+ <SideNavSection title="Main" isHeaderHidden>
+ <SideNavItem
+ label="Dashboard"
+ icon={HomeIcon}
+ selectedIcon={HomeIconSolid}
+ isSelected
+ href="#"
+ />
+ <SideNavItem
+ label="Analytics"
+ icon={ChartBarIcon}
+ selectedIcon={ChartBarIconSolid}
+ href="#"
+ />
+ <SideNavItem
+ label="Projects"
+ icon={FolderIcon}
+ selectedIcon={FolderIconSolid}
+ href="#"
+ endContent={<Badge label={12} />}
+ />
+ </SideNavSection>
+ <SideNavSection title="Organization">
+ <SideNavItem
+ label="Team"
+ icon={UserGroupIcon}
+ selectedIcon={UserGroupIconSolid}
+ href="#"
+ />
+ <SideNavItem
+ label="Settings"
+ icon={Cog6ToothIcon}
+ selectedIcon={Cog6ToothIconSolid}
+ href="#"
+ />
+ </SideNavSection>
+ </SideNav>
+ }>
+ <PlaceholderPageText />
+ </AppShell>
+ );
+ },
+};
+
+/**
+ * The same motion on a phone: `mobileNav={{breakpoint: 'none'}}` keeps the
+ * rail inline at 390 px instead of the mobile drawer.
+ */
+export const RailCollapseMotionPhone: Story = {
+ name: 'Rail collapse motion (phone)',
+ globals: {viewport: {value: 'mobile1', isRotated: false}},
+ parameters: {docs: {source: {code: RAIL_COLLAPSE_CODE, language: 'tsx'}}},
+ render: function RailCollapseMotionPhoneStory() {
+ const [isCollapsed, setIsCollapsed] = useState(false);
+ return (
+ <AppShell
+ contentPadding={6}
+ mobileNav={{breakpoint: 'none'}}
+ sideNav={
+ <SideNav
+ collapsible={{isCollapsed, onCollapsedChange: setIsCollapsed}}>
+ <SideNavSection title="Main" isHeaderHidden>
+ <SideNavItem
+ label="Dashboard"
+ icon={HomeIcon}
+ selectedIcon={HomeIconSolid}
+ isSelected
+ href="#"
+ />
+ <SideNavItem
+ label="Analytics"
+ icon={ChartBarIcon}
+ selectedIcon={ChartBarIconSolid}
+ href="#"
+ />
+ <SideNavItem
+ label="Projects"
+ icon={FolderIcon}
+ selectedIcon={FolderIconSolid}
+ href="#"
+ endContent={<Badge label={12} />}
+ />
+ </SideNavSection>
+ <SideNavSection title="Organization">
+ <SideNavItem
+ label="Team"
+ icon={UserGroupIcon}
+ selectedIcon={UserGroupIconSolid}
+ href="#"
+ />
+ <SideNavItem
+ label="Settings"
+ icon={Cog6ToothIcon}
+ selectedIcon={Cog6ToothIconSolid}
+ href="#"
+ />
+ </SideNavSection>
+ </SideNav>
+ }>
+ <PlaceholderPageText />
+ </AppShell>
+ );
+ },
+};
+
/**
* No navigation at all — just content. Useful for full-bleed pages,
* auth screens, or embedded views.
diff --git a/packages/core/src/AppShell/AppShell.tsx b/packages/core/src/AppShell/AppShell.tsx
index 04fbb2808a..592d399bd9 100644
--- a/packages/core/src/AppShell/AppShell.tsx
+++ b/packages/core/src/AppShell/AppShell.tsx
@@ -45,6 +45,18 @@ import {LayoutContent} from '../Layout/LayoutContent';
import {MobileNavToggle} from '../MobileNav/MobileNavToggle';
import {MAX_CLOSE_DELAY_MS as MOBILE_NAV_MAX_CLOSE_DELAY_MS} from '../MobileNav/MobileNav';
import {SideNavRenderContext} from '../SideNav/SideNavRenderContext';
+import {SideNavShellContext, type SideNavShell} from '../SideNav/railMotion';
+import {useAnimatedLayout} from '../hooks/useAnimatedLayout';
+import {
+ holdLayoutSwap,
+ landLayoutGlide,
+ layoutMotionFor,
+ playLayoutFrames,
+ playLayoutSwap,
+ reportLayoutChange,
+ type LayoutChange,
+ type LayoutSwap,
+} from '../motion/animatedLayout';
import {TopNavRenderContext} from '../TopNav/TopNavRenderContext';
import {TopNavMobileContentContext} from '../TopNav/TopNavMobileContentContext';
import {AppShellMobileContext} from './AppShellMobileContext';
@@ -472,6 +484,19 @@ const styles = stylex.create({
* </AppShell>
* ```
*/
+
+/**
+ * The column beside the rail that holds `main`: its ancestor whose parent
+ * also holds the rail. The glide moves it; the rail's edge rides it.
+ */
+function columnOf(main: HTMLElement, rail: HTMLElement | null): HTMLElement {
+ let column = main;
+ while (column.parentElement != null && !column.parentElement.contains(rail)) {
+ column = column.parentElement;
+ }
+ return column;
+}
+
export function AppShell({
variant = 'elevated',
banner,
@@ -749,6 +774,147 @@ export function AppShell({
) : undefined;
// =========================================================================
+ // While the inline side nav collapses or expands, the content area holds
+ // its own animated layout handle (`component:AppShell` FR17): the column
+ // beside the rail glides from its old place, and the content swaps its old
+ // wrap for its new one in place (`spec:AST-105` FR8), on the rail's clock
+ // (`component:SideNav` FR6).
+ const railRef = useRef<HTMLDivElement>(null);
+ const mainRef = useRef<HTMLDivElement>(null);
+ const backdropRef = useRef<HTMLDivElement>(null);
+ const contentLayout = useAnimatedLayout({containerRef: shellRef});
+ const pendingContentRef = useRef<{
+ /** The column's glide, reported only for a spring motion. */
+ change: LayoutChange | null;
+ swap: LayoutSwap | null;
+ before: DOMRect;
+ /** The opacities the held and the entering wrap start from. */
+ held: number;
+ entering: number;
+ } | null>(null);
+ // The running swap: when it started and its wraps' starting opacities, so a
+ // change made during it starts its cross-fade from what the content shows.
+ const lastSwapRef = useRef<{
+ startedAt: number;
+ held: number;
+ entering: number;
+ } | null>(null);
+ const sideNavShell = useMemo<SideNavShell>(
+ () => ({
+ animatedLayout: contentLayout,
+ rail: () => railRef.current,
+ column: () =>
+ mainRef.current == null
+ ? null
+ : columnOf(mainRef.current, railRef.current),
+ landContent() {
+ if (mainRef.current != null) {
+ landLayoutGlide(columnOf(mainRef.current, railRef.current));
+ }
+ },
+ beforeRailChange() {
+ const main = mainRef.current;
+ if (main == null) {
+ return;
+ }
+ const motion = layoutMotionFor(main);
+ // Only a spring glides the column; under Reduce Motion the two wraps
+ // cross-fade over a steady surface (`design:reduced-motion` DR2).
+ let change: LayoutChange | null = null;
+ if (motion.kind === 'spring') {
+ change = reportLayoutChange(contentLayout, railRef);
+ change.measureBefore();
+ }
+ // At rest the copy (the wrap shown now) starts opaque and the entering
+ // wrap unseen; mid-swap the wrap in the DOM is the entering one and
+ // the copy's wrap is the one entering next, each at what it shows.
+ let held = 1;
+ let entering = 0;
+ const last = lastSwapRef.current;
+ if (last != null && motion.kind === 'spring') {
+ const elapsed =
+ Number(main.ownerDocument.timeline?.currentTime ?? 0) -
+ last.startedAt;
+ if (elapsed < motion.progress.durationMs) {
+ const p = 1 - motion.progress.remaining(elapsed);
+ held = last.entering + (1 - last.entering) * p;
+ entering = last.held * (1 - p);
+ }
+ }
+ lastSwapRef.current = null;
+ pendingContentRef.current = {
+ change,
+ swap: holdLayoutSwap(contentLayout, main, {isVisiblePart: true}),
+ before: main.getBoundingClientRect(),
+ held,
+ entering,
+ };
+ },
+ afterRailChange() {
+ const pending = pendingContentRef.current;
+ pendingContentRef.current = null;
+ const main = mainRef.current;
+ if (pending == null || main == null) {
+ return () => {};
+ }
+ pending.change?.animate();
+ // The column beside the rail, which the glide moves: the copy sits
+ // beside it, in its parent, and rides its glide.
+ const column = columnOf(main, railRef.current);
+ const after = main.getBoundingClientRect();
+ const isRtl = getComputedStyle(main).direction === 'rtl';
+ const travel = isRtl
+ ? pending.before.right - after.right
+ : pending.before.left - after.left;
+ // An expand slides the narrower column in from its old start, which
+ // opens a gap at its trailing edge: the content surface (the elevated
+ // backdrop, or the main element) reaches over it as it closes,
+ // whether or not the old wrap is held.
+ const cover: {element: Element; frames: (p: number) => Keyframe}[] = [];
+ const surface = backdropRef.current ?? main;
+ const color = getComputedStyle(surface).backgroundColor;
+ const isPainted = !/^rgba\(.*,\s*0\)$|^transparent$/.test(color);
+ const glides = layoutMotionFor(main).kind === 'spring';
+ if ((isRtl ? travel > 0 : travel < 0) && glides && isPainted) {
+ cover.push({
+ element: surface,
+ frames: p => ({
+ boxShadow: `${-travel * (1 - p)}px 0px 0px 0px ${color}`,
+ }),
+ });
+ }
+ if (pending.swap == null || column.parentElement == null) {
+ return playLayoutFrames(contentLayout, cover);
+ }
+ // Under Reduce Motion nothing glides: the old wrap's copy paints the
+ // surface it sat on, so that surface fades out with it where it was
+ // (`design:reduced-motion` DR2) instead of leaving a bare strip.
+ if (!glides && isPainted) {
+ pending.swap.copy.style.backgroundColor = color;
+ }
+ const {held, entering} = pending;
+ lastSwapRef.current = {
+ startedAt: Number(main.ownerDocument.timeline?.currentTime ?? 0),
+ held,
+ entering,
+ };
+ return playLayoutSwap(pending.swap, {
+ host: column.parentElement,
+ copy: p => ({opacity: held * (1 - p)}),
+ rideWith: {element: column, travel: {x: travel, y: 0}},
+ incoming: [
+ ...Array.from(main.children, element => ({
+ element,
+ frames: (p: number) => ({opacity: entering + (1 - entering) * p}),
+ })),
+ ...cover,
+ ],
+ });
+ },
+ }),
+ [contentLayout],
+ );
+
// Build sideNav content
//
// In auto mode, the sideNav panel is not internally scrollable (the page
@@ -758,6 +924,7 @@ export function AppShell({
// =========================================================================
const sideNavPanel = showSideNavInline ? (
<LayoutPanel
+ ref={railRef}
padding={0}
hasDivider={navHasDividers}
isScrollable={isFill}
@@ -767,7 +934,7 @@ export function AppShell({
isAuto && stickyBgStyle,
isAuto && styles.panelAutoFill,
]}>
- {sideNav}
+ <SideNavShellContext value={sideNavShell}>{sideNav}</SideNavShellContext>
</LayoutPanel>
) : undefined;
@@ -785,6 +952,7 @@ export function AppShell({
const mainInner = (
<LayoutContent
+ ref={mainRef}
padding={contentPadding ?? 0}
role="main"
id={MAIN_CONTENT_ID}
@@ -807,7 +975,7 @@ export function AppShell({
: styles.contentWrapper,
)}>
{shouldElevateWithCorner && (
- <div {...stylex.props(styles.elevatedBackdrop)} />
+ <div ref={backdropRef} {...stylex.props(styles.elevatedBackdrop)} />
)}
{mainInner}
</div>
diff --git a/packages/core/src/SideNav/SideNav.tsx b/packages/core/src/SideNav/SideNav.tsx
index 8a0dd84998..8057b051f9 100644
--- a/packages/core/src/SideNav/SideNav.tsx
+++ b/packages/core/src/SideNav/SideNav.tsx
@@ -23,9 +23,12 @@
*/
import {
+ use,
useCallback,
useId,
useImperativeHandle,
+ useLayoutEffect,
+ useMemo,
useRef,
type ReactNode,
} from 'react';
@@ -52,6 +55,15 @@ import {useDevWarning} from '../hooks/useDevWarning';
import {useTranslator} from '../i18n';
import {useMergedRefs} from '../hooks/useMergedRefs';
+import {LayoutChangeSnapshot} from '../motion/LayoutChangeSnapshot';
+import {
+ createRailLayout,
+ playRail,
+ snapshotRail,
+ SideNavShellContext,
+ type RailMotion,
+ type RailSnapshot,
+} from './railMotion';
// =============================================================================
// Constants
// =============================================================================
@@ -474,6 +486,70 @@ export function SideNav({
const collapsed = resizableHook.isCollapsed;
+ // Every collapse or expand, whatever caused it, plays the rail's motion
+ // (`component:SideNav` FR6): measured in the commit before the DOM changes,
+ // played after it before paint. Inside AppShell the content area moves with
+ // it through AppShell's own handle (`component:AppShell` FR17); outside,
+ // SideNav holds its own over its parent.
+ const shell = use(SideNavShellContext);
+ const ownLayout = useMemo(() => createRailLayout(() => navRef.current), []);
+ const railSnapshotRef = useRef<RailSnapshot | null>(null);
+ const motionRef = useRef<{rail: RailMotion; endContent: () => void} | null>(
+ null,
+ );
+ const measureRail = useCallback(
+ (wasCollapsed: boolean) => {
+ // A change during a running motion starts from what the rail shows.
+ const running = motionRef.current;
+ const shown = running?.rail.shown() ?? null;
+ running?.rail.end();
+ running?.endContent();
+ motionRef.current = null;
+ railSnapshotRef.current = snapshotRail(
+ shell?.rail() ?? navRef.current,
+ shell?.animatedLayout ?? ownLayout,
+ shown,
+ wasCollapsed,
+ );
+ // A collapse covers the old rail with its copy; when the rail cannot
+ // be copied, the page lands at once with it, on one clock, a running
+ // glide included.
+ const snapshot = railSnapshotRef.current;
+ if (snapshot != null && snapshot.swap == null && !wasCollapsed) {
+ shell?.landContent();
+ return;
+ }
+ shell?.beforeRailChange();
+ },
+ [shell, ownLayout],
+ );
+ useLayoutEffect(() => {
+ const snapshot = railSnapshotRef.current;
+ railSnapshotRef.current = null;
+ if (snapshot == null) {
+ return;
+ }
+ // The content moves first: its glide starts before the rail rides it.
+ const endContent = shell?.afterRailChange() ?? (() => {});
+ motionRef.current = {
+ rail: playRail(
+ snapshot,
+ shell?.rail() ?? navRef.current,
+ shell?.animatedLayout ?? ownLayout,
+ shell?.column() ?? null,
+ ),
+ endContent,
+ };
+ }, [collapsed, shell, ownLayout]);
+ // An unmount mid-motion removes the copy at once.
+ useLayoutEffect(
+ () => () => {
+ motionRef.current?.rail.end();
+ motionRef.current?.endContent();
+ },
+ [],
+ );
+
const toggle = useCallback(() => {
const next = !collapsed;
@@ -673,7 +749,7 @@ export function SideNav({
// Overlay drag handle inside the nav when resizable.
// Uses ResizeHandle in overlay mode so the handle sits inside
// the panel's overflow: clip bounds.
- const content = showResizeHandle ? (
+ const rail = showResizeHandle ? (
<div {...stylex.props(styles.resizableContainer)}>
{navElement}
<ResizeHandle
@@ -691,6 +767,14 @@ export function SideNav({
) : (
navElement
);
+ // The snapshot stays mounted outside the resize wrapper, which comes and
+ // goes with the collapse it measures.
+ const content = (
+ <>
+ <LayoutChangeSnapshot value={collapsed} onBeforeChange={measureRail} />
+ {rail}
+ </>
+ );
if (isCollapsible) {
return (
diff --git a/packages/core/src/SideNav/SideNavRailMotion.test.tsx b/packages/core/src/SideNav/SideNavRailMotion.test.tsx
new file mode 100644
index 0000000000..1d3d868079
--- /dev/null
+++ b/packages/core/src/SideNav/SideNavRailMotion.test.tsx
@@ -0,0 +1,620 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+
+import {AppShell} from '../AppShell';
+import {SideNav} from './SideNav';
+import {SideNavItem} from './SideNavItem';
+
+/**
+ * The rail's collapse motion (`component:SideNav` FR6, `component:AppShell`
+ * FR17): layout snaps, the rail reveals or covers by a clip, and the content's
+ * old and new wrap slide and fade on one clock. jsdom has no layout or Web
+ * Animations, so the rail's width comes from whether its labels render and
+ * every animation is recorded.
+ */
+
+const SHELL_WIDTH = 1024;
+const EXPANDED = 260;
+const COLLAPSED = 48;
+
+interface Recorded {
+ element: Element;
+ keyframes: Keyframe[];
+ options: KeyframeAnimationOptions;
+ animation: {finish: () => void; cancel: () => void; startTime: number | null};
+}
+
+let recorded: Recorded[] = [];
+/** Where the rail's inline-start edge sits for a width (a centered rail moves). */
+let railLeft = (_width: number) => 0;
+/** Where a running glide shows the column, past its layout place. */
+let columnShift = 0;
+let media: Record<string, boolean> = {};
+
+/** The real rail (not a copy): collapsed rows carry their label as a name. */
+function realNav(): Element | undefined {
+ return Array.from(document.querySelectorAll('nav')).find(
+ nav => nav.closest('[inert]') == null,
+ );
+}
+
+function railWidth(): number {
+ return realNav()?.querySelector('button[aria-label="Projects"]') != null
+ ? COLLAPSED
+ : EXPANDED;
+}
+
+/** Moves the timeline past any motion, as time passing would. */
+function settle() {
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ value: {currentTime: 1000 + 5000},
+ });
+}
+
+function rect(left: number, width: number): DOMRect {
+ return DOMRect.fromRect({x: left, y: 0, width, height: 600});
+}
+
+beforeEach(() => {
+ recorded = [];
+ railLeft = () => 0;
+ columnShift = 0;
+ media = {};
+ vi.stubGlobal('matchMedia', (query: string) => ({
+ matches: media[query] ?? false,
+ media: query,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ }));
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ value: {currentTime: 1000},
+ });
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(
+ function (this: HTMLElement) {
+ const width = railWidth();
+ if (this.closest('[inert]') != null) {
+ return rect(0, 0);
+ }
+ if (this.classList.contains('astryx-app-shell')) {
+ return rect(0, SHELL_WIDTH);
+ }
+ const nav = realNav();
+ if (this === nav) {
+ return rect(railLeft(width), width);
+ }
+ if (nav != null && this.contains(nav)) {
+ return rect(0, width);
+ }
+ // The main element and the column around it, beside the rail.
+ if (
+ this.querySelector('[role="main"]') != null ||
+ this.getAttribute('role') === 'main'
+ ) {
+ return rect(width + columnShift, SHELL_WIDTH - width);
+ }
+ return rect(0, 0);
+ },
+ );
+ (HTMLElement.prototype as unknown as {animate: unknown}).animate = function (
+ this: Element,
+ keyframes: Keyframe[],
+ options: KeyframeAnimationOptions,
+ ) {
+ const listeners: (() => void)[] = [];
+ const animation = {
+ startTime: null as number | null,
+ finished: {then: () => undefined},
+ onfinish: null as null | (() => void),
+ addEventListener: (_type: string, listener: () => void) => {
+ listeners.push(listener);
+ },
+ finish() {
+ listeners.forEach(listener => listener());
+ animation.onfinish?.();
+ },
+ cancel() {},
+ };
+ recorded.push({element: this, keyframes, options, animation});
+ return animation;
+ };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete (HTMLElement.prototype as unknown as {animate?: unknown}).animate;
+});
+
+function Shell({
+ inShell = true,
+ hasNav = true,
+ isResizable = false,
+ height = 'fill',
+ hasCanvas = false,
+}: {
+ inShell?: boolean;
+ hasNav?: boolean;
+ isResizable?: boolean;
+ height?: 'fill' | 'auto';
+ hasCanvas?: boolean;
+}) {
+ const nav = (
+ <SideNav collapsible resizable={isResizable}>
+ <SideNavItem label="Home" icon={<svg aria-hidden="true" />} />
+ <SideNavItem label="Projects" icon={<svg aria-hidden="true" />} />
+ {hasCanvas && (
+ <SideNavItem label="Chart" icon={<canvas width={4} height={4} />} />
+ )}
+ </SideNav>
+ );
+ return inShell ? (
+ <AppShell
+ height={height}
+ mobileNav={{breakpoint: 'none'}}
+ sideNav={hasNav ? nav : undefined}>
+ <h1>Projects page</h1>
+ <p>The page beside the rail.</p>
+ <label>
+ <input type="radio" name="plan" value="pro" defaultChecked /> Pro
+ </label>
+ </AppShell>
+ ) : (
+ nav
+ );
+}
+
+/** Collapse or expand, then let the glide's microtask run. */
+async function toggle() {
+ const button = screen.getByRole('button', {name: /collapse|expand/i});
+ await act(async () => {
+ fireEvent.click(button);
+ });
+}
+
+function animated(property: string): Recorded[] {
+ return recorded.filter(entry =>
+ entry.keyframes.some(frame => property in frame),
+ );
+}
+
+function copies(): Element[] {
+ return Array.from(document.querySelectorAll('[aria-hidden="true"][inert]'));
+}
+
+describe('SideNav rail motion (component:SideNav FR6, component:AppShell FR17)', () => {
+ it('collapses by covering the old rail with a clip while the content slides, never animating a width', async () => {
+ render(<Shell />);
+ await toggle();
+
+ expect(railWidth()).toBe(COLLAPSED);
+ expect(animated('width')).toEqual([]);
+ // The old rail's copy is covered by a clip from its full width to the
+ // collapsed one.
+ const [clip] = animated('clipPath');
+ expect(clip.keyframes[0].clipPath).toMatch(
+ /inset\(0(px)? 0(px)? 0(px)? 0(px)?\)/,
+ );
+ expect(clip.keyframes.at(-1)?.clipPath).toContain(
+ `${EXPANDED - COLLAPSED}px`,
+ );
+ // The content column starts where it was and slides to its new place.
+ const main = screen.getByRole('main');
+ const [slide] = animated('translate').filter(
+ entry => entry.element !== main && entry.element.contains(main),
+ );
+ expect(slide.keyframes[0].translate).toBe(`${EXPANDED - COLLAPSED}px 0px`);
+ expect(slide.keyframes.at(-1)?.translate).toBe('0px 0px');
+ // Every part plays on one clock.
+ const starts = new Set(recorded.map(entry => entry.animation.startTime));
+ expect(starts).toEqual(new Set([1000]));
+ const durations = new Set(recorded.map(entry => entry.options.duration));
+ expect(durations.size).toBe(1);
+ });
+
+ it('cross-fades the content: the old wrap fades out over the new one, which fades in', async () => {
+ render(<Shell />);
+ await toggle();
+ const main = screen.getByRole('main');
+ const copy = copies().find(element =>
+ element.textContent?.includes('The page beside the rail.'),
+ );
+ // Beside the content, which clips, not inside it: no line is cut.
+ expect(main.contains(copy ?? null)).toBe(false);
+ const fadeOut = recorded.find(entry => entry.element === copy);
+ expect(fadeOut?.keyframes[0]).toMatchObject({
+ opacity: 1,
+ translate: '0px 0px',
+ });
+ // It moves with the column: from where it was by the column's travel.
+ expect(fadeOut?.keyframes.at(-1)).toMatchObject({
+ opacity: 0,
+ translate: `${COLLAPSED - EXPANDED}px 0px`,
+ });
+ const heading = screen.getByRole('heading', {name: 'Projects page'});
+ const fadeIn = recorded.find(entry => entry.element === heading);
+ expect(fadeIn?.keyframes[0].opacity).toBe(0);
+ expect(fadeIn?.keyframes.at(-1)?.opacity).toBe(1);
+ });
+
+ it('expands by revealing the real rail with a clip under the old rail, applied before the first frame paints', async () => {
+ render(<Shell />);
+ await toggle();
+ act(() => {
+ recorded.forEach(entry => entry.animation.finish());
+ });
+ settle();
+ recorded = [];
+ await toggle();
+
+ expect(railWidth()).toBe(EXPANDED);
+ // The real rail is clipped open from the old width.
+ const reveal = animated('clipPath').find(
+ entry => !entry.element.hasAttribute('inert'),
+ );
+ expect(reveal).toBeDefined();
+ // The old, collapsed rail is held over it at first and fades, so the first
+ // frame is the frame before the click.
+ const old = recorded.find(
+ entry =>
+ entry.element.hasAttribute('inert') &&
+ entry.element.querySelector('button[aria-label="Projects"]') != null,
+ );
+ expect(old?.keyframes[0].opacity).toBe(1);
+ expect(old?.keyframes.at(-1)?.opacity).toBe(0);
+ expect(reveal?.keyframes[0].clipPath).toContain(
+ `${EXPANDED - COLLAPSED}px`,
+ );
+ expect(reveal?.keyframes.at(-1)?.clipPath).toMatch(
+ /inset\(0(px)? 0(px)? 0(px)? 0(px)?\)/,
+ );
+ const main = screen.getByRole('main');
+ const [slide] = animated('translate').filter(
+ entry => entry.element !== main && entry.element.contains(main),
+ );
+ expect(slide.keyframes[0].translate).toBe(`${COLLAPSED - EXPANDED}px 0px`);
+ });
+
+ it('starts a change made mid-motion from the width the rail shows', async () => {
+ render(<Shell />);
+ await toggle();
+ // 150 ms into the collapse the clip shows part of the old rail: the
+ // column's glide shows it 102 px past its place, so the rail shows 150.
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ value: {currentTime: 1150},
+ });
+ columnShift = 102;
+ recorded = [];
+ await toggle();
+ const reveal = animated('clipPath').find(
+ entry => !entry.element.hasAttribute('inert'),
+ );
+ const start = Number(
+ /inset\(0px ([\d.]+)px/.exec(String(reveal?.keyframes[0].clipPath))?.[1],
+ );
+ // It reveals from the shown width, not from the collapsed one.
+ expect(start).toBe(EXPANDED - 150);
+ });
+
+ it('continues what the rail and the page show when a change reverses a running one', async () => {
+ render(<Shell />);
+ await toggle();
+ // 40 ms into the collapse: the old labels still show, fading.
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ value: {currentTime: 1040},
+ });
+ recorded = [];
+ await toggle();
+ const opacityOf = (entry: Recorded | undefined) =>
+ Number(entry?.keyframes[0].opacity);
+ // The real labels start where the old ones were, not from nothing.
+ const label = recorded.find(
+ entry =>
+ !entry.element.closest('[inert]') &&
+ entry.element.textContent === 'Projects' &&
+ 'opacity' in entry.keyframes[0],
+ );
+ expect(opacityOf(label)).toBeGreaterThan(0.2);
+ // The collapsed rail had not shown yet, so its held copy starts unseen.
+ const collapsedCopy = recorded.find(
+ entry =>
+ entry.element.hasAttribute('inert') &&
+ entry.element.querySelector('button[aria-label="Projects"]') != null,
+ );
+ expect(opacityOf(collapsedCopy)).toBeLessThan(0.2);
+ // The page: the wrap held now showed partly, the entering wrap the rest.
+ const heading = recorded.find(
+ entry => entry.element.textContent === 'Projects page',
+ );
+ expect(opacityOf(heading)).toBeGreaterThan(0);
+ });
+
+ it('draws a collapse that reverses an expand with one rail copy, the real collapsed rail raised above it', async () => {
+ render(<Shell />);
+ await toggle();
+ settle();
+ await toggle();
+ // 40 ms into the expand, collapse again.
+ const at = (document.timeline as {currentTime: number}).currentTime;
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ value: {currentTime: at + 40},
+ });
+ recorded = [];
+ await toggle();
+ const railCopies = copies().filter(
+ element => element.querySelector('nav') != null,
+ );
+ expect(railCopies).toHaveLength(1);
+ const panel = document.querySelector<HTMLElement>('.astryx-layout-panel');
+ expect(panel?.style.zIndex).toBe('2');
+ // 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],
+ );
+ expect(Number(icons?.keyframes[0].opacity)).toBeGreaterThan(0.5);
+ act(() => {
+ recorded.forEach(entry => entry.animation.finish());
+ });
+ expect(panel?.style.zIndex).toBe('');
+ });
+
+ it('continues the page through a third press within the motion', async () => {
+ render(<Shell />);
+ await toggle();
+ for (const at of [1040, 1080]) {
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ value: {currentTime: at},
+ });
+ recorded = [];
+ await toggle();
+ }
+ // The wrap entering now had been fading out: it starts low, not high.
+ const heading = recorded.find(
+ entry => entry.element.textContent === 'Projects page',
+ );
+ expect(Number(heading?.keyframes[0].opacity)).toBeLessThan(0.5);
+ });
+
+ it('lays the old rail in the row beside the content, past an auto-height side wrapper that clips', async () => {
+ render(<Shell height="auto" />);
+ await toggle();
+ const railCopy = copies().find(
+ element => element.querySelector('nav') != null,
+ );
+ // In the row that holds the rail and the content, not in the sticky side
+ // wrapper, whose clip is already the collapsed width.
+ expect(railCopy?.parentElement?.contains(screen.getByRole('main'))).toBe(
+ true,
+ );
+ });
+
+ it('lands a collapse and the page at once when the old rail cannot be copied', async () => {
+ const getContext = vi
+ .spyOn(HTMLCanvasElement.prototype, 'getContext')
+ .mockImplementation(
+ () =>
+ ({
+ drawImage: vi.fn(),
+ getImageData: () => ({data: new Uint8ClampedArray(16 * 4)}),
+ }) as unknown as CanvasRenderingContext2D,
+ );
+ render(<Shell hasCanvas />);
+ await toggle();
+ getContext.mockRestore();
+ expect(railWidth()).toBe(COLLAPSED);
+ // No rail copy, so no page motion either: both land on one clock.
+ expect(copies()).toHaveLength(0);
+ expect(animated('translate')).toHaveLength(0);
+ });
+
+ it('lands the running page glide too when a no-copy collapse interrupts an expand', async () => {
+ const getContext = vi
+ .spyOn(HTMLCanvasElement.prototype, 'getContext')
+ .mockImplementation(
+ () =>
+ ({
+ drawImage: vi.fn(),
+ getImageData: () => ({data: new Uint8ClampedArray(16 * 4)}),
+ }) as unknown as CanvasRenderingContext2D,
+ );
+ render(<Shell hasCanvas />);
+ await toggle();
+ settle();
+ recorded = [];
+ await toggle();
+ // The expand's glide on the column beside the rail.
+ const main = screen.getByRole('main');
+ const glide = animated('translate').find(
+ entry => entry.element !== main && entry.element.contains(main),
+ );
+ expect(glide).toBeDefined();
+ const cancel = vi.spyOn(glide!.animation, 'cancel');
+ // 40 ms in, collapse again: the rail cannot be copied.
+ const at = (document.timeline as {currentTime: number}).currentTime;
+ Object.defineProperty(document, 'timeline', {
+ configurable: true,
+ value: {currentTime: at + 40},
+ });
+ recorded = [];
+ await toggle();
+ getContext.mockRestore();
+ expect(cancel).toHaveBeenCalled();
+ expect(animated('translate')).toHaveLength(0);
+ });
+
+ it('clips an expand open on the motion when the old rail cannot be copied', async () => {
+ // A canvas that reads back blank: the rail is not copied.
+ const getContext = vi
+ .spyOn(HTMLCanvasElement.prototype, 'getContext')
+ .mockImplementation(
+ () =>
+ ({
+ drawImage: vi.fn(),
+ getImageData: () => ({data: new Uint8ClampedArray(16 * 4)}),
+ }) as unknown as CanvasRenderingContext2D,
+ );
+ render(<Shell hasCanvas />);
+ await toggle();
+ settle();
+ recorded = [];
+ await toggle();
+ getContext.mockRestore();
+ expect(
+ copies().filter(element => element.querySelector('nav')),
+ ).toHaveLength(0);
+ const reveal = animated('clipPath').find(
+ entry => !entry.element.hasAttribute('inert'),
+ );
+ expect(reveal?.keyframes[0].clipPath).toContain(
+ `${EXPANDED - COLLAPSED}px`,
+ );
+ expect(reveal?.keyframes.at(-1)?.clipPath).toMatch(
+ /inset\(0(px)? 0(px)? 0(px)? 0(px)?\)/,
+ );
+ });
+
+ it('leaves the real collapsed rail and no copies once the motion ends', async () => {
+ render(<Shell />);
+ await toggle();
+ expect(copies().length).toBeGreaterThan(0);
+ act(() => {
+ recorded.forEach(entry => entry.animation.finish());
+ });
+ expect(copies()).toEqual([]);
+ expect(railWidth()).toBe(COLLAPSED);
+ });
+
+ it('changes at once under Reduce Motion with a fine pointer (design:reduced-motion DR3)', async () => {
+ media['(prefers-reduced-motion: reduce)'] = true;
+ render(<Shell />);
+ await toggle();
+ expect(recorded).toEqual([]);
+ expect(copies()).toEqual([]);
+ });
+
+ it('only cross-fades under Reduce Motion with a coarse pointer (design:reduced-motion DR2)', async () => {
+ media['(prefers-reduced-motion: reduce)'] = true;
+ media['(pointer: coarse)'] = true;
+ render(<Shell />);
+ await toggle();
+ expect(recorded.length).toBeGreaterThan(0);
+ // The surface stays put: nothing that holds the page animates.
+ const main = screen.getByRole('main');
+ expect(recorded.filter(entry => entry.element.contains(main))).toEqual([]);
+ for (const entry of recorded) {
+ for (const frame of entry.keyframes) {
+ expect(Object.keys(frame).filter(key => key !== 'offset')).toEqual([
+ 'opacity',
+ ]);
+ }
+ }
+ });
+
+ it('under DR2, an expand fades the old surface out with the old wrap', async () => {
+ media['(prefers-reduced-motion: reduce)'] = true;
+ media['(pointer: coarse)'] = true;
+ render(<Shell />);
+ const main = screen.getByRole('main');
+ main.style.backgroundColor = 'rgb(255, 255, 255)';
+ await toggle();
+ act(() => {
+ recorded.forEach(entry => entry.animation.finish());
+ });
+ settle();
+ recorded = [];
+ await toggle();
+ // The old wrap's copy paints the surface it sat on, from opaque at the
+ // first frame, so the strip the narrower page leaves fades with it.
+ const copy = copies().find(
+ element => element.querySelector('h1') != null,
+ ) as HTMLElement | undefined;
+ expect(copy?.style.backgroundColor).toBe('rgb(255, 255, 255)');
+ const fade = recorded.find(entry => entry.element === copy);
+ expect(fade?.keyframes[0].opacity).toBe(1);
+ });
+
+ it('outside AppShell, moves only the rail', async () => {
+ render(<Shell inShell={false} />);
+ await toggle();
+ expect(animated('clipPath').length).toBeGreaterThan(0);
+ expect(animated('translate')).toEqual([]);
+ });
+
+ it('leaves the page form state alone: a checked radio stays checked', async () => {
+ render(<Shell />);
+ const pro = screen.getByRole('radio', {name: 'Pro'});
+ expect(pro).toBeChecked();
+ await toggle();
+ // The copied radio joins no group, so it cannot uncheck the live one.
+ const [copied] = copies().flatMap(copy =>
+ Array.from(copy.querySelectorAll('input[type="radio"]')),
+ );
+ expect(copied).toBeDefined();
+ expect(copied).not.toHaveAttribute('name');
+ expect(pro).toBeChecked();
+ act(() => {
+ recorded.forEach(entry => entry.animation.finish());
+ });
+ expect(pro).toBeChecked();
+ });
+
+ it('plays for a resizable rail too, whose resize wrapper comes and goes with the collapse', async () => {
+ render(<Shell isResizable />);
+ await toggle();
+ expect(railWidth()).toBe(COLLAPSED);
+ expect(animated('clipPath').length).toBeGreaterThan(0);
+ });
+
+ it('plays for a resizable rail outside AppShell, whose nav remounts with the collapse', async () => {
+ render(<Shell inShell={false} isResizable />);
+ await toggle();
+ expect(railWidth()).toBe(COLLAPSED);
+ const clip = animated('clipPath').find(entry =>
+ entry.element.hasAttribute('inert'),
+ );
+ expect(clip).toBeDefined();
+ expect(clip?.element.isConnected).toBe(true);
+ });
+
+ it('removes its copies and restores the row when the rail unmounts mid-motion', async () => {
+ const {rerender} = render(<Shell />);
+ await toggle();
+ expect(copies().length).toBeGreaterThan(0);
+ rerender(<Shell hasNav={false} />);
+ expect(copies()).toEqual([]);
+ const clipped = Array.from(
+ document.querySelectorAll<HTMLElement>('*'),
+ ).filter(element => element.style.overflow === 'clip');
+ expect(clipped).toEqual([]);
+ });
+
+ it("keeps the old rail's copy on the real rail's edge wherever SideNav sits", async () => {
+ // A rail centered in its parent moves when it narrows.
+ railLeft = width => (SHELL_WIDTH - width) / 2;
+ render(<Shell inShell={false} />);
+ await toggle();
+ const copy = copies().find(element => element.matches('nav'));
+ expect(copy).toBeDefined();
+ expect((copy as HTMLElement).style.left).toBe(
+ `${(SHELL_WIDTH - COLLAPSED) / 2}px`,
+ );
+ expect((copy as HTMLElement).style.width).toBe(`${EXPANDED}px`);
+ });
+
+ it('changes at once without Web Animations', async () => {
+ delete (HTMLElement.prototype as unknown as {animate?: unknown}).animate;
+ render(<Shell />);
+ await toggle();
+ expect(railWidth()).toBe(COLLAPSED);
+ expect(copies()).toEqual([]);
+ });
+});
diff --git a/packages/core/src/SideNav/railMotion.ts b/packages/core/src/SideNav/railMotion.ts
new file mode 100644
index 0000000000..564916ab7f
--- /dev/null
+++ b/packages/core/src/SideNav/railMotion.ts
@@ -0,0 +1,315 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file railMotion.ts
+ * @input The rail's outer element, the animated-layout module's handle,
+ * motion and in-place swap (motion/animatedLayout.ts)
+ * @output Exports `SideNavShellContext` (what AppShell lends its SideNav),
+ * `createRailLayout`, `snapshotRail` and `playRail`: the rail's collapse
+ * motion
+ * @position Internal to SideNav (`component:SideNav` FR6, DEC-2); AppShell's
+ * content area moves through the context (`component:AppShell` FR17)
+ *
+ * Collapsing or expanding the rail plays one motion on one clock, the
+ * `springs.settle` role the animated-layout module reads (`spec:AST-105`
+ * FR4):
+ * - Layout snaps to the final rail width at once; nothing animates a width.
+ * - A collapse covers the old rail by a clip: the module's in-place swap
+ * (`spec:AST-105` FR8) holds the old, expanded rail as one transient copy
+ * and the clip closes it to the new width. The copy's text fades over the
+ * first 40%; the real collapsed rail, raised above the copy, fades in over
+ * the last 30%, so the real rail, icons only, is all that remains.
+ * - An expand reveals the real rail by a clip from the old width, its text
+ * fading in over the last 60% so no label shows at the collapsed width,
+ * under the old, collapsed rail held by the same swap, which fades over the
+ * first 60%: the first frame is the frame before the click.
+ * - In AppShell the rail's edge rides the content column's glide, frame by
+ * frame, so the two never part, also when a change interrupts a running
+ * one; the copy is laid in the row that holds both.
+ * - A change made during a running motion starts from what the rail shows:
+ * its width, its labels' opacity and its collapsed icons' opacity, so the
+ * rail stays continuous.
+ * - Every starting clip applies in the commit's layout effect, before the
+ * first frame paints.
+ * - Under Reduce Motion it follows `design:reduced-motion`: opacity only
+ * under a coarse primary pointer (DR2), an immediate change otherwise
+ * (DR3). Without Web Animations, the change lands at once.
+ *
+ * SYNC: When modified, update SideNav.tsx, AppShell.tsx and
+ * SideNavRailMotion.test.tsx.
+ */
+
+import {createContext} from 'react';
+import {
+ createAnimatedLayout,
+ holdLayoutSwap,
+ layoutMotionFor,
+ playLayoutFrames,
+ playLayoutSwap,
+ type AnimatedLayout,
+ type LayoutSwap,
+} from '../motion/animatedLayout';
+
+/** What AppShell lends its SideNav; outside AppShell, nothing. */
+export interface SideNavShell {
+ /** AppShell's own handle, whose area holds the rail and the content. */
+ readonly animatedLayout: AnimatedLayout;
+ /** The rail's outer element, which paints its background. */
+ rail(): HTMLElement | null;
+ /** The content column beside the rail, which glides. */
+ column(): HTMLElement | null;
+ /** In the commit, before the DOM changes: the content measures itself. */
+ beforeRailChange(): void;
+ /** After it, before paint: the content moves; returns what ends it. */
+ afterRailChange(): () => void;
+ /** The content lands where it is laid out, ending any running glide. */
+ landContent(): void;
+}
+
+export const SideNavShellContext = createContext<SideNavShell | null>(null);
+SideNavShellContext.displayName = 'SideNavShellContext';
+
+/** A SideNav outside AppShell holds its own handle over its parent. */
+export function createRailLayout(
+ rail: () => HTMLElement | null,
+): AnimatedLayout {
+ return createAnimatedLayout(() => rail()?.parentElement ?? null);
+}
+
+/** What a rail shows: at rest, or partway through a motion. */
+export interface RailShown {
+ readonly width: number;
+ /** The labels' opacity. */
+ readonly labels: number;
+ /** The collapsed rail's opacity (its icons). */
+ readonly collapsed: number;
+}
+
+export interface RailSnapshot {
+ readonly rail: HTMLElement;
+ readonly railRect: DOMRect;
+ /** What the rail shows when the change lands. */
+ readonly shown: RailShown;
+ /** The old rail, held by the swap. */
+ readonly swap: LayoutSwap | null;
+}
+
+/** A playing rail motion. */
+export interface RailMotion {
+ /** Ends it at once (a new change, an unmount). */
+ end(): void;
+ /** What the rail shows now, or null once it has settled. */
+ shown(): RailShown | null;
+}
+
+/**
+ * Before the change commits: the old rail, where it was, and what it shows,
+ * from a running motion or at rest.
+ */
+export function snapshotRail(
+ rail: HTMLElement | null,
+ handle: AnimatedLayout,
+ running: RailShown | null,
+ isCollapsed: boolean,
+): RailSnapshot | null {
+ if (rail == null || typeof rail.animate !== 'function') {
+ return null;
+ }
+ const railRect = rail.getBoundingClientRect();
+ return {
+ rail,
+ railRect,
+ shown: running ?? {
+ width: railRect.width,
+ labels: isCollapsed ? 0 : 1,
+ collapsed: isCollapsed ? 1 : 0,
+ },
+ swap: holdLayoutSwap(handle, rail),
+ };
+}
+
+const clamp = (value: number) => Math.min(1, Math.max(0, value));
+
+/** The rail's own text: elements that hold a run of text directly. */
+function textElements(rail: HTMLElement): Element[] {
+ return Array.from(rail.querySelectorAll('*')).filter(element =>
+ Array.from(element.childNodes).some(
+ node => node.nodeType === 3 && node.textContent?.trim(),
+ ),
+ );
+}
+
+/** `element`'s ancestor (or itself) that sits directly in `host`. */
+function childOf(host: Element, element: HTMLElement): HTMLElement | null {
+ let node: HTMLElement | null = element;
+ while (node != null && node.parentElement !== host) {
+ node = node.parentElement;
+ }
+ return node;
+}
+
+const AT_REST: RailMotion = {end: () => {}, shown: () => null};
+
+/**
+ * After the change commits, before paint: play the rail's motion from the
+ * snapshot, on the module's motion. With a `column` (in AppShell), the rail's
+ * edge rides its glide.
+ */
+export function playRail(
+ snapshot: RailSnapshot,
+ current: HTMLElement | null,
+ handle: AnimatedLayout,
+ column: HTMLElement | null = null,
+): RailMotion {
+ const {railRect, swap, shown: from} = snapshot;
+ // The rail as it is now: a resizable rail's nav remounts when its resize
+ // wrapper comes and goes with the collapse.
+ const rail = current?.isConnected === true ? current : snapshot.rail;
+ if (!rail.isConnected) {
+ return AT_REST;
+ }
+ const motion = layoutMotionFor(rail);
+ const next = rail.getBoundingClientRect();
+ if (motion.kind === 'instant' || Math.abs(next.width - from.width) < 0.5) {
+ return AT_REST;
+ }
+ const isCollapse = next.width < from.width;
+ // The labels and the collapsed icons over the motion's progress, from what
+ // the rail showed.
+ const labelsAt = (p: number) =>
+ isCollapse
+ ? from.labels * (1 - clamp(p / 0.4))
+ : from.labels + (1 - from.labels) * clamp((p - 0.4) / 0.6);
+ const collapsedAt = (p: number) =>
+ isCollapse
+ ? from.collapsed + (1 - from.collapsed) * clamp((p - 0.7) / 0.3)
+ : from.collapsed * (1 - clamp(p / 0.6));
+ const rtl = getComputedStyle(rail).direction === 'rtl';
+ const sign = rtl ? -1 : 1;
+ const inset = (px: number) =>
+ rtl ? `inset(0px 0px 0px ${px}px)` : `inset(0px ${px}px 0px 0px)`;
+ // The row that holds the rail and the column, or the rail's parent.
+ const host =
+ column?.parentElement != null && column.parentElement.contains(rail)
+ ? column.parentElement
+ : rail.parentElement;
+ // Riding needs the swap: its frames carry the column's travel. Without one
+ // (old content that cannot be copied) the clip follows the motion's curve.
+ const rides = host != null && column?.parentElement === host && swap != null;
+ // The width the rail shows over the motion: on the column's glide (its
+ // travel so far added to where it started), or on the motion's curve.
+ const widthAt = (p: number, ride: {x: number}) =>
+ rides
+ ? from.width + sign * ride.x
+ : from.width + (next.width - from.width) * p;
+ const now = () => Number(rail.ownerDocument.timeline?.currentTime ?? 0);
+ const startedAt = now();
+ const durationMs =
+ motion.kind === 'spring' ? motion.progress.durationMs : motion.durationMs;
+ const shown = (): RailShown | null => {
+ const elapsed = now() - startedAt;
+ if (elapsed >= durationMs) {
+ return null;
+ }
+ const p =
+ motion.kind === 'spring' ? 1 - motion.progress.remaining(elapsed) : 0;
+ let width = from.width + (next.width - from.width) * p;
+ if (rides && column != null) {
+ // The rail's edge is the column's: read it where it shows.
+ const edge = column.getBoundingClientRect();
+ const own = rail.getBoundingClientRect();
+ width = rtl ? own.right - edge.right : edge.left - own.left;
+ }
+ return {width, labels: labelsAt(p), collapsed: collapsedAt(p)};
+ };
+ const rideWith =
+ rides && column != null
+ ? {
+ element: column,
+ travel: {x: sign * (from.width - next.width), y: 0},
+ isCopyMoved: false,
+ }
+ : undefined;
+ // The copy keeps the rail's inline-start edge where the rail is now, so it
+ // meets the real rail wherever SideNav sits (a centered rail moves).
+ const at = DOMRect.fromRect({
+ x: rtl ? next.right - railRect.width : next.left,
+ y: next.top,
+ width: railRect.width,
+ height: railRect.height,
+ });
+
+ if (isCollapse) {
+ // A collapse covers the old rail, held by the swap, from the width it
+ // shows down to the new one; the real, collapsed rail fades in above it.
+ if (swap == null || host == null) {
+ return AT_REST;
+ }
+ const raised = childOf(host, rail);
+ 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 end = playLayoutSwap(
+ {...swap, rect: at},
+ {
+ host,
+ isOpaque: true,
+ copy: (p, ride) => ({
+ clipPath: inset(railRect.width - widthAt(p, ride)),
+ opacity: 1 - clamp((p - 0.7) / 0.3),
+ }),
+ copyText: labelsAt,
+ rideWith,
+ onEnd: () => {
+ if (raised != null && restore != null) {
+ raised.style.position = restore.position;
+ raised.style.zIndex = restore.zIndex;
+ }
+ },
+ incoming: [{element: rail, frames: p => ({opacity: collapsedAt(p)})}],
+ },
+ );
+ return {end, shown};
+ }
+
+ // An expand reveals the real rail from the width it showed, its text fading
+ // in late, under the old, collapsed rail fading early.
+ const incoming = [
+ {
+ element: rail,
+ frames: (p: number, ride: {x: number}) => ({
+ clipPath: inset(next.width - widthAt(p, ride)),
+ }),
+ },
+ ...textElements(rail).map(element => ({
+ element,
+ frames: (p: number) => ({opacity: labelsAt(p)}),
+ })),
+ ];
+ const end =
+ swap != null && host != null
+ ? playLayoutSwap(
+ {...swap, rect: at},
+ {
+ host,
+ isOpaque: true,
+ copy: p => ({opacity: collapsedAt(p)}),
+ rideWith,
+ incoming,
+ },
+ )
+ : playLayoutFrames(handle, incoming);
+ return {end, shown};
+}
diff --git a/packages/core/src/motion/animatedLayout.boundary.test.ts b/packages/core/src/motion/animatedLayout.boundary.test.ts
index 5b83c22e48..3728652256 100644
--- a/packages/core/src/motion/animatedLayout.boundary.test.ts
+++ b/packages/core/src/motion/animatedLayout.boundary.test.ts
@@ -144,7 +144,9 @@ describe('architecture:react-component-runtime INV12 source boundary', () => {
.map(path => relative(coreSrc, path))
.sort();
expect(users).toEqual([
+ 'AppShell/AppShell.tsx',
'Collapsible/Collapsible.tsx',
+ 'SideNav/railMotion.ts',
'TreeList/TreeList.tsx',
'hooks/useAnimatedLayout.ts',
]);
diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.ts
index 1bbe067a69..f7b5543f30 100644
--- a/packages/core/src/motion/animatedLayout.ts
+++ b/packages/core/src/motion/animatedLayout.ts
@@ -1750,7 +1750,23 @@ export function applyLayoutChangeTransition(
);
}
-/** @internal For tests: the motion a change in `area` plays. */
+/**
+ * Lands `element`'s running glide at once: it takes its layout place, and a
+ * later change starts from there (a change its caller lands rather than
+ * animates, such as a rail that snaps).
+ */
+export function landLayoutGlide(element: Element): void {
+ const glide = glides.get(element);
+ if (glide != null) {
+ glides.delete(element);
+ glide.animation.cancel();
+ }
+}
+
+/**
+ * @internal The motion a change in `area` plays, for tests and for SideNav's
+ * rail motion, which plays on the same clock (`component:SideNav` FR6).
+ */
export function layoutMotionFor(area: Element): LayoutMotion {
return layoutMotion(area);
}