Skip to content

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

TypeScript

feat(lab): NavigationStack, push/pop navigation that moves like UINavigationController (#9697)

Christopher Chedeau4e4cf84d2e79
diff --git a/.changeset/cli-discover-navigation-stack.md b/.changeset/cli-discover-navigation-stack.md
new file mode 100644
index 0000000000..fb8a16f4bc
--- /dev/null
+++ b/.changeset/cli-discover-navigation-stack.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[experimental] `astryx discover` lists the experimental NavigationStack and NavigationScreen components from `@astryxdesign/lab`.
+
+@vjeux
diff --git a/apps/storybook/stories/NavigationStack.stories.tsx b/apps/storybook/stories/NavigationStack.stories.tsx
new file mode 100644
index 0000000000..370ea1230c
--- /dev/null
+++ b/apps/storybook/stories/NavigationStack.stories.tsx
@@ -0,0 +1,310 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ NavigationScreen,
+ NavigationStack,
+ useNavigationStack,
+} from '@astryxdesign/lab';
+import {Button} from '@astryxdesign/core/Button';
+import {List, ListItem} from '@astryxdesign/core/List';
+import {Icon} from '@astryxdesign/core/Icon';
+import {rtlStyles} from '@astryxdesign/core/utils';
+
+// =============================================================================
+// Meta
+// =============================================================================
+
+const meta: Meta<typeof NavigationStack> = {
+ title: 'Lab/NavigationStack',
+ component: NavigationStack,
+ parameters: {
+ layout: 'fullscreen',
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof NavigationStack>;
+
+// =============================================================================
+// Settings — the drill-down UIKit's own captures were taken on
+// =============================================================================
+
+const SECTIONS: Record<string, string[]> = {
+ Settings: ['General', 'Accessibility', 'Privacy & Security', 'Display'],
+ General: ['About', 'Software Update', 'Storage', 'Language & Region'],
+ Accessibility: ['Motion', 'Display & Text Size', 'Touch', 'Spoken Content'],
+ 'Privacy & Security': ['Location Services', 'Tracking', 'Camera', 'Photos'],
+ Display: ['Brightness', 'Text Size', 'Night Shift'],
+};
+
+function Rows({title}: {title: string}) {
+ const nav = useNavigationStack<string>();
+ const rows = SECTIONS[title] ?? [];
+ return (
+ <List>
+ {rows.map(row => (
+ <ListItem
+ key={row}
+ label={row}
+ endContent={
+ <Icon
+ icon="chevronRight"
+ color="secondary"
+ xstyle={rtlStyles.mirror}
+ />
+ }
+ onClick={() => nav.push(row)}
+ />
+ ))}
+ {rows.length === 0 ? (
+ <ListItem label={`${title} has nothing deeper.`} />
+ ) : null}
+ {rows.length === 0 ? (
+ <ListItem label="Done" onClick={() => nav.popToRoot()} />
+ ) : null}
+ </List>
+ );
+}
+
+function SettingsStack() {
+ const [path, setPath] = useState<string[]>([]);
+ return (
+ <div style={{height: '100vh'}}>
+ <NavigationStack
+ label="Settings"
+ root={
+ <NavigationScreen title="Settings">
+ <Rows title="Settings" />
+ </NavigationScreen>
+ }
+ path={path}
+ onPathChange={setPath}
+ getKey={entry => entry}
+ renderScreen={entry => (
+ <NavigationScreen title={entry}>
+ <Rows title={entry} />
+ </NavigationScreen>
+ )}
+ data-testid="navigation-stack"
+ />
+ </div>
+ );
+}
+
+export const Settings: Story = {
+ render: () => <SettingsStack />,
+};
+
+/** The root screen's bar holds an Edit button at its end (`endContent`). */
+function EndContentStack() {
+ const [path, setPath] = useState<string[]>([]);
+ return (
+ <div style={{height: '100vh'}}>
+ <NavigationStack
+ label="Settings"
+ root={
+ <NavigationScreen
+ title="Settings"
+ endContent={<Button label="Edit" variant="ghost" size="sm" />}>
+ <Rows title="Settings" />
+ </NavigationScreen>
+ }
+ path={path}
+ onPathChange={setPath}
+ getKey={entry => entry}
+ renderScreen={entry => (
+ <NavigationScreen title={entry}>
+ <Rows title={entry} />
+ </NavigationScreen>
+ )}
+ data-testid="navigation-stack"
+ />
+ </div>
+ );
+}
+
+export const EndContent: Story = {
+ name: 'End content',
+ render: () => <EndContentStack />,
+};
+
+/**
+ * Opens two levels deep, so the back swipe has somewhere to go; Done on the
+ * top screen pops back to the root in one transition.
+ */
+function DeepStack() {
+ const [path, setPath] = useState<string[]>(['General', 'About']);
+ return (
+ <div style={{height: '100vh'}}>
+ <NavigationStack
+ label="Settings"
+ root={
+ <NavigationScreen title="Settings">
+ <Rows title="Settings" />
+ </NavigationScreen>
+ }
+ path={path}
+ onPathChange={setPath}
+ getKey={entry => entry}
+ renderScreen={entry => (
+ <NavigationScreen title={entry}>
+ <Rows title={entry} />
+ </NavigationScreen>
+ )}
+ data-testid="navigation-stack"
+ />
+ </div>
+ );
+}
+
+export const Pushed: Story = {
+ name: 'Pushed two levels',
+ render: () => <DeepStack />,
+};
+
+// =============================================================================
+// Edge cases the stack must handle
+// =============================================================================
+
+/**
+ * A pushed screen with a horizontal strip: a sideways drag on the strip
+ * scrolls it while it can still scroll that way; elsewhere it pops.
+ */
+function CarouselStack() {
+ const [path, setPath] = useState<string[]>(['General']);
+ return (
+ <div style={{height: '100vh'}}>
+ <NavigationStack
+ label="Settings"
+ root={
+ <NavigationScreen title="Settings">
+ <Rows title="Settings" />
+ </NavigationScreen>
+ }
+ path={path}
+ onPathChange={setPath}
+ getKey={entry => entry}
+ renderScreen={entry => (
+ <NavigationScreen title={entry}>
+ <div
+ data-testid="carousel"
+ style={{
+ display: 'flex',
+ gap: 12,
+ padding: 16,
+ overflowX: 'auto',
+ }}>
+ {SECTIONS.Settings.concat(SECTIONS.General).map(label => (
+ <div
+ key={label}
+ style={{
+ flex: '0 0 140px',
+ height: 96,
+ borderRadius: 12,
+ border: '1px solid currentColor',
+ padding: 8,
+ }}>
+ {label}
+ </div>
+ ))}
+ </div>
+ <Rows title={entry} />
+ </NavigationScreen>
+ )}
+ data-testid="navigation-stack"
+ />
+ </div>
+ );
+}
+
+export const Carousel: Story = {
+ name: 'Pushed screen with a carousel',
+ render: () => <CarouselStack />,
+};
+
+/**
+ * An app that declines pops (it keeps its path, as one guarding unsaved
+ * edits would): a released back swipe springs back.
+ */
+function DeclinesPopsStack() {
+ const [path, setPath] = useState<string[]>(['General']);
+ return (
+ <div style={{height: '100vh'}}>
+ <NavigationStack
+ label="Settings"
+ root={
+ <NavigationScreen title="Settings">
+ <Rows title="Settings" />
+ </NavigationScreen>
+ }
+ path={path}
+ onPathChange={next => {
+ if (next.length >= path.length) {
+ setPath(next);
+ }
+ }}
+ getKey={entry => entry}
+ renderScreen={entry => (
+ <NavigationScreen title={entry}>
+ <Rows title={entry} />
+ </NavigationScreen>
+ )}
+ data-testid="navigation-stack"
+ />
+ </div>
+ );
+}
+
+export const DeclinesPops: Story = {
+ name: 'Declines pops',
+ render: () => <DeclinesPopsStack />,
+};
+
+/** The root with a large title (as in Settings): it scrolls with the rows and hands over to the bar. */
+function LargeTitleStack() {
+ const [path, setPath] = useState<string[]>([]);
+ return (
+ <div style={{height: '100vh'}}>
+ <NavigationStack
+ label="Settings"
+ root={
+ <NavigationScreen title="Settings" titleDisplayMode="large">
+ <Rows title="Settings" />
+ <List>
+ {Array.from({length: 24}, (_, i) => (
+ <ListItem key={i} label={`Setting ${i + 1}`} />
+ ))}
+ </List>
+ </NavigationScreen>
+ }
+ path={path}
+ onPathChange={setPath}
+ getKey={entry => entry}
+ renderScreen={entry =>
+ entry === 'Display' ? (
+ <NavigationScreen title={entry} titleDisplayMode="large">
+ <Rows title={entry} />
+ <List>
+ {Array.from({length: 24}, (_, i) => (
+ <ListItem key={i} label={`Display option ${i + 1}`} />
+ ))}
+ </List>
+ </NavigationScreen>
+ ) : (
+ <NavigationScreen title={entry}>
+ <Rows title={entry} />
+ </NavigationScreen>
+ )
+ }
+ data-testid="navigation-stack"
+ />
+ </div>
+ );
+}
+
+export const LargeTitle: Story = {
+ name: 'Large title',
+ render: () => <LargeTitleStack />,
+};
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index cc6a254eda..6fdc13555e 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -622,6 +622,16 @@
"path": "components/lab/log-stream",
"aliases": []
},
+ {
+ "name": "component-lab-navigation-screen",
+ "path": "components/lab/navigation-screen",
+ "aliases": []
+ },
+ {
+ "name": "component-lab-navigation-stack",
+ "path": "components/lab/navigation-stack",
+ "aliases": []
+ },
{
"name": "component-lab-radial-chart",
"path": "components/lab/radial-chart",
diff --git a/packages/cli/assets/discover/official-packages.json b/packages/cli/assets/discover/official-packages.json
index 5999288565..c409650e1d 100644
--- a/packages/cli/assets/discover/official-packages.json
+++ b/packages/cli/assets/discover/official-packages.json
@@ -144,6 +144,14 @@
"kind": "component",
"name": "LogStream"
},
+ {
+ "kind": "component",
+ "name": "NavigationScreen"
+ },
+ {
+ "kind": "component",
+ "name": "NavigationStack"
+ },
{
"kind": "component",
"name": "RadialChart"
diff --git a/packages/lab/src/NavigationStack/NavigationStack.doc.mjs b/packages/lab/src/NavigationStack/NavigationStack.doc.mjs
new file mode 100644
index 0000000000..834b13855b
--- /dev/null
+++ b/packages/lab/src/NavigationStack/NavigationStack.doc.mjs
@@ -0,0 +1,139 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+
+export const docs = {
+ name: 'NavigationStack',
+ displayName: 'Navigation Stack',
+ category: 'Navigation',
+ keywords: [
+ 'navigationstack',
+ 'navigation stack',
+ 'stack navigator',
+ 'drill down',
+ 'push',
+ 'pop',
+ 'back swipe',
+ 'navigation controller',
+ 'master detail',
+ 'mobile navigation',
+ ],
+ description:
+ 'Drill-down navigation for phone layouts: each screen pushes the next on top, and Back, the back swipe from the screen edge or from anywhere in the content returns to the previous one. Pushes, pops and the back swipe move like iOS: the new screen slides in from the trailing edge over the old one, which slides a third as far under a light dimming, and a released swipe finishes or springs back depending on how far and how fast it went. A push never waits for its animation: the new screen is usable as soon as it starts sliding in. With Reduce Motion the screens cross-fade instead. Experimental: lands in lab first.',
+ components: [
+ {
+ name: 'NavigationStack',
+ displayName: 'Navigation Stack',
+ description:
+ "The navigator. You own the path: pass the entries pushed on the root screen and update them in onPathChange. The stack renders the root screen and one screen per entry, the top one last, keeps covered screens and their scroll positions alive, and makes them inert. The bar shows the top screen's title, its end content and a round Back button with a chevron, named by the screen it returns to. A push moves focus to the new screen's title; a pop returns it to the control that pushed the screen.",
+ props: [
+ {
+ name: 'root',
+ type: 'ReactElement<NavigationScreenProps>',
+ description:
+ 'The root screen, a NavigationScreen. It has no Back button.',
+ required: true,
+ },
+ {
+ name: 'path',
+ type: 'ReadonlyArray<T>',
+ description:
+ 'The entries pushed on the root, bottom first. Adding one at the end pushes its screen; removing the last pops it; removing several pops straight back to the new top.',
+ required: true,
+ },
+ {
+ name: 'onPathChange',
+ type: '(path: T[]) => void',
+ description:
+ 'Called with the new path when a screen pushes or pops (useNavigationStack), Back is pressed, or a back swipe is released past the point of no return.',
+ required: true,
+ },
+ {
+ name: 'renderScreen',
+ type: '(entry: T, index: number) => ReactElement<NavigationScreenProps>',
+ description: 'Renders the screen for an entry: a NavigationScreen.',
+ required: true,
+ },
+ {
+ name: 'getKey',
+ type: '(entry: T, index: number) => string | number',
+ description:
+ "A stable key per entry, so a screen keeps its state while others are pushed on it. Defaults to the entry's position.",
+ },
+ {
+ name: 'isInteractivePopEnabled',
+ type: 'boolean',
+ description:
+ "Whether the back swipe pops: a sideways drag anywhere in the content, under any pointer (a finger, a pen or a mouse drag), and in a web app opened from the home screen also a finger's swipe from the leading screen edge. In a browser tab that edge stays the browser's own back swipe, and on Android the system back owns both screen edges.",
+ default: 'true',
+ },
+ {
+ name: 'label',
+ type: 'string',
+ description: 'Accessible name of the navigator region.',
+ },
+ ],
+ },
+ {
+ name: 'NavigationScreen',
+ displayName: 'Navigation Screen',
+ description:
+ "One screen of a NavigationStack: its title, the title Back shows on the screen pushed after it, its end content and its content. Returned by NavigationStack's root and renderScreen; it renders nothing on its own.",
+ props: [
+ {
+ name: 'title',
+ type: 'string',
+ description:
+ 'Shown in the bar while the screen is on top, and read first when it arrives.',
+ required: true,
+ },
+ {
+ name: 'backTitle',
+ type: 'string',
+ description:
+ 'What Back reads on the screen pushed on top of this one. Defaults to title.',
+ },
+ {
+ name: 'titleDisplayMode',
+ type: "'large' | 'inline'",
+ description:
+ "How the title shows. 'large' puts it above the content in a large bold type, scrolling with the content; once it has scrolled under the bar, the bar shows the title instead. Use it for a top-level screen, as iOS does.",
+ default: "'inline'",
+ },
+ {
+ name: 'endContent',
+ type: 'ReactNode',
+ description:
+ 'Content at the end of the bar while the screen is on top.',
+ },
+ {
+ name: 'children',
+ type: 'ReactNode',
+ description:
+ "The screen's content. It scrolls on its own and keeps its scroll position while covered.",
+ },
+ ],
+ },
+ ],
+ usage: {
+ description:
+ 'Use NavigationStack for hierarchical drill-down on phones: lists of settings, folders, a list and its detail. Call push from a row with useNavigationStack inside a screen.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ "Keep the path in the app's state (or the URL) and give entries stable keys, so screens keep their state as the stack changes.",
+ },
+ {
+ guidance: true,
+ description:
+ "Push from the control the person activated (a row's onClick): focus returns to it when the screen is popped.",
+ },
+ {
+ guidance: false,
+ description:
+ "Don't use it for top-level sections that people switch between; those are tabs or a sidebar, which keep each section's own stack.",
+ },
+ ],
+ },
+};
diff --git a/packages/lab/src/NavigationStack/NavigationStack.test.tsx b/packages/lab/src/NavigationStack/NavigationStack.test.tsx
new file mode 100644
index 0000000000..b5865f7811
--- /dev/null
+++ b/packages/lab/src/NavigationStack/NavigationStack.test.tsx
@@ -0,0 +1,322 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file NavigationStack.test.tsx
+ * @input Uses vitest, @testing-library/react, NavigationStack,
+ * NavigationScreen and useNavigationStack
+ * @output jsdom coverage of the stack's state: which screens render, the
+ * bar's title and back button, and inert covered screens. It also covers a
+ * popped screen leaving once its slide-out ends, focus after a push and
+ * after a pop, and the hook's guard.
+ * @position Testing. Real engines prove the motion itself in
+ * __tests__/NavigationStack.interaction.browser.spec.ts (jsdom has no Web
+ * Animations: the animator writes end values and settles on timers)
+ */
+
+import {describe, expect, it} from 'vitest';
+import {useState, type ReactNode} from 'react';
+import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';
+import {List, ListItem} from '@astryxdesign/core/List';
+import {
+ NavigationScreen,
+ NavigationStack,
+ useNavigationStack,
+} from './NavigationStack';
+
+function Root() {
+ const nav = useNavigationStack<string>();
+ return (
+ <>
+ <button type="button" onClick={() => nav.push('General')}>
+ General
+ </button>
+ <button type="button" onClick={() => nav.push('Privacy')}>
+ Privacy
+ </button>
+ </>
+ );
+}
+
+function Detail({entry}: {entry: string}) {
+ const nav = useNavigationStack<string>();
+ return (
+ <>
+ <p>{entry} content</p>
+ <button type="button" onClick={() => nav.push(`${entry} › About`)}>
+ About
+ </button>
+ <button type="button" onClick={() => nav.popToRoot()}>
+ Done
+ </button>
+ <span data-testid="depth">{nav.depth}</span>
+ </>
+ );
+}
+
+function Harness({
+ initial = [],
+ backTitle,
+ rootTitle = 'Settings',
+ rootEndContent,
+}: {
+ initial?: string[];
+ backTitle?: string;
+ rootTitle?: string;
+ rootEndContent?: ReactNode;
+}) {
+ const [path, setPath] = useState<string[]>(initial);
+ return (
+ <NavigationStack
+ label="Settings"
+ root={
+ <NavigationScreen
+ title={rootTitle}
+ backTitle={backTitle}
+ endContent={rootEndContent}>
+ <Root />
+ </NavigationScreen>
+ }
+ path={path}
+ onPathChange={setPath}
+ getKey={entry => entry}
+ renderScreen={entry => (
+ <NavigationScreen title={entry}>
+ <Detail entry={entry} />
+ </NavigationScreen>
+ )}
+ />
+ );
+}
+
+/** A screen's card, by title (the root is "Settings"). */
+const screenCard = (title: string) =>
+ document.querySelector<HTMLElement>(
+ `[data-navigation-screen="${title === 'Settings' ? 'root' : `screen-${title}`}"]`,
+ );
+
+/** The bar's back button (other buttons may share its name). */
+const backButton = (name: string) =>
+ screen
+ .getAllByRole('button', {name})
+ .find(button => button.hasAttribute('data-navigation-back'));
+
+describe('NavigationStack', () => {
+ it('renders the root screen with its title and no back button', () => {
+ render(<Harness />);
+ expect(screen.getByRole('region', {name: 'Settings'})).toBeInTheDocument();
+ expect(screen.getByRole('heading', {name: 'Settings'})).toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: /back|settings/i})).toBeNull();
+ expect(screen.getByRole('button', {name: 'General'})).toBeInTheDocument();
+ });
+
+ it('pushes a screen: its title shows, Back reads the previous title, the root is covered', async () => {
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', {name: 'General'}));
+
+ expect(screen.getByText('General content')).toBeInTheDocument();
+ const back = screen.getByRole('button', {name: 'Settings'});
+ expect(back).toHaveAttribute('data-navigation-back');
+ // The covered root screen takes no input, and assistive technology skips
+ // it.
+ expect(screenCard('Settings')).toHaveAttribute('inert');
+ expect(screenCard('General')).not.toHaveAttribute('inert');
+ expect(screen.getByTestId('depth')).toHaveTextContent('1');
+ });
+
+ it('pops with the back button; the popped screen leaves once its slide-out ends', async () => {
+ render(<Harness initial={['General']} />);
+ fireEvent.click(screen.getByRole('button', {name: 'Settings'}));
+
+ // Still rendered, and inert, while it slides out...
+ expect(screen.getByText('General content')).toBeInTheDocument();
+ expect(screenCard('General')).toHaveAttribute('inert');
+ // ...and gone once it has.
+ await waitFor(
+ () => expect(screen.queryByText('General content')).toBeNull(),
+ {timeout: 3000},
+ );
+ expect(screenCard('Settings')).not.toHaveAttribute('inert');
+ });
+
+ it('moves focus to the new title after a push, and back to the pushing control after the pop', async () => {
+ render(<Harness />);
+ const general = screen.getByRole('button', {name: 'General'});
+ general.focus();
+ fireEvent.click(general);
+
+ await waitFor(
+ () =>
+ expect(document.activeElement).toBe(
+ screen.getByRole('heading', {name: 'General'}),
+ ),
+ {timeout: 3000},
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Settings'}));
+ await waitFor(() => expect(general).toHaveFocus(), {timeout: 3000});
+ });
+
+ it('labels Back with the previous screen’s backTitle when it has one', () => {
+ render(<Harness initial={['General']} backTitle="All settings" />);
+ expect(screen.getByRole('button', {name: 'All settings'})).toHaveAttribute(
+ 'data-navigation-back',
+ );
+ });
+
+ it('names Back with the catalog’s “Back” when the previous screen’s title is empty', () => {
+ render(<Harness initial={['General']} rootTitle="" />);
+ expect(backButton('Back')).toBeDefined();
+ });
+
+ it('pops several screens back to the root at once', async () => {
+ render(<Harness initial={['General', 'General › About']} />);
+ expect(backButton('General')).toBeDefined();
+ act(() => {
+ fireEvent.click(screen.getAllByRole('button', {name: 'Done'}).at(-1)!);
+ });
+ await waitFor(
+ () => expect(screen.queryByText('General › About content')).toBeNull(),
+ {timeout: 3000},
+ );
+ expect(screen.queryByText('General content')).toBeNull();
+ expect(screen.getByRole('button', {name: 'Privacy'})).toBeInTheDocument();
+ });
+
+ describe('a large title', () => {
+ function LargeHarness() {
+ const [path, setPath] = useState<string[]>([]);
+ return (
+ <NavigationStack
+ label="Settings"
+ root={
+ <NavigationScreen title="Settings" titleDisplayMode="large">
+ <Root />
+ </NavigationScreen>
+ }
+ path={path}
+ onPathChange={setPath}
+ getKey={entry => entry}
+ renderScreen={entry => (
+ <NavigationScreen title={entry} titleDisplayMode="large">
+ <Detail entry={entry} />
+ </NavigationScreen>
+ )}
+ />
+ );
+ }
+
+ it('shows the title above the content and hides the bar title from assistive technology', () => {
+ render(<LargeHarness />);
+ const large = screen.getByRole('heading', {level: 1, name: 'Settings'});
+ // First in the screen's scrolling content.
+ expect(screenCard('Settings')?.firstElementChild?.firstElementChild).toBe(
+ large,
+ );
+ // The bar's copy of the title is hidden while the large one shows.
+ expect(screen.getAllByRole('heading', {name: 'Settings'})).toHaveLength(
+ 1,
+ );
+ });
+
+ it('moves focus to the pushed screen’s large title', async () => {
+ render(<LargeHarness />);
+ const general = screen.getByRole('button', {name: 'General'});
+ general.focus();
+ fireEvent.click(general);
+ await waitFor(
+ () =>
+ expect(document.activeElement).toBe(
+ screen.getByRole('heading', {level: 1, name: 'General'}),
+ ),
+ {timeout: 3000},
+ );
+ });
+ });
+
+ it('shows a screen’s end content in its bar, out of reach once a screen covers it', async () => {
+ render(<Harness rootEndContent={<button type="button">Edit</button>} />);
+ const edit = screen.getByRole('button', {name: 'Edit'});
+ const bar = edit.closest('[data-navigation-bar]');
+ expect(bar).toHaveAttribute('data-navigation-bar', 'root');
+ expect(bar).not.toHaveAttribute('inert');
+
+ fireEvent.click(screen.getByRole('button', {name: 'General'}));
+ await screen.findByRole('heading', {name: 'General', level: 2});
+ expect(bar).toHaveAttribute('inert');
+ });
+
+ it('keeps covered screens beyond the one underneath out of rendering', () => {
+ render(<Harness initial={['General', 'General › About']} />);
+ // Root, General (under the top) and About (top) are mounted; the root,
+ // two below the top, keeps its state but is not rendered.
+ expect(screenCard('Settings')?.className).toMatch(/cardHidden/);
+ expect(screenCard('General')?.className).not.toMatch(/cardHidden/);
+ });
+
+ it('returns focus to a row’s end control that pushed', async () => {
+ function EndControlRoot() {
+ const nav = useNavigationStack<string>();
+ return (
+ <List>
+ <ListItem
+ label="General"
+ onClick={() => nav.push('General')}
+ endContent={
+ <button
+ type="button"
+ onClick={event => {
+ event.stopPropagation();
+ nav.push('General info');
+ }}>
+ Info
+ </button>
+ }
+ />
+ </List>
+ );
+ }
+ function EndControlHarness() {
+ const [path, setPath] = useState<string[]>([]);
+ return (
+ <NavigationStack
+ label="Settings"
+ root={
+ <NavigationScreen title="Settings">
+ <EndControlRoot />
+ </NavigationScreen>
+ }
+ path={path}
+ onPathChange={setPath}
+ getKey={entry => entry}
+ renderScreen={entry => (
+ <NavigationScreen title={entry}>
+ <p>{entry} content</p>
+ </NavigationScreen>
+ )}
+ />
+ );
+ }
+ render(<EndControlHarness />);
+ const info = screen.getByRole('button', {name: 'Info'});
+ info.focus();
+ fireEvent.click(info);
+ await screen.findByRole('heading', {name: 'General info', level: 2});
+
+ fireEvent.click(backButton('Settings') as HTMLElement);
+ await waitFor(
+ () => expect(screen.queryByText('General info content')).toBeNull(),
+ {timeout: 3000},
+ );
+ await waitFor(() =>
+ expect(screen.getByRole('button', {name: 'Info'})).toHaveFocus(),
+ );
+ });
+
+ it('throws when useNavigationStack is used outside a stack', () => {
+ function Orphan() {
+ useNavigationStack();
+ return null;
+ }
+ expect(() => render(<Orphan />)).toThrow(/inside a NavigationStack/);
+ });
+});
diff --git a/packages/lab/src/NavigationStack/NavigationStack.tsx b/packages/lab/src/NavigationStack/NavigationStack.tsx
new file mode 100644
index 0000000000..f4deb3c734
--- /dev/null
+++ b/packages/lab/src/NavigationStack/NavigationStack.tsx
@@ -0,0 +1,1485 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file NavigationStack.tsx
+ * @input React and StyleX. Core's compositor animator and UIKit tables come
+ * from Core's internal touch entry and navigationMotion.ts. The math is in
+ * navigationTransition.ts, and the back swipes in NavigationStackTouch.ts.
+ * Each screen scrolls through Core's useScrollableArea.
+ * @output Exports NavigationStack, a push/pop navigator with UIKit's
+ * transitions and back gestures. NavigationScreen is one screen: its bar
+ * title, back title, end content and content. useNavigationStack pushes,
+ * pops and pops to the root from inside a screen.
+ * @position Lab component (packages/lab/src/NavigationStack). It is the
+ * phone presentation of drill-down navigation, UINavigationController's
+ * counterpart.
+ *
+ * SYNC: When modified, update NavigationStack.doc.mjs,
+ * NavigationStack.test.tsx and
+ * __tests__/NavigationStack.interaction.browser.spec.ts.
+ */
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactElement,
+ type ReactNode,
+ type SyntheticEvent,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ focusForLastInput,
+ isFocusLost,
+ isRtlElement,
+ resolveMotion,
+ solveSpring,
+ toSpring,
+ useInteractionModalityTracking,
+ type MotionEngine,
+ type SpringDescription,
+} from '@astryxdesign/core/internal/touch';
+import {useTranslator} from '@astryxdesign/core/i18n';
+import {useScrollableArea} from '@astryxdesign/core/hooks';
+import {focusOutlineStyles} from '@astryxdesign/core/utils';
+import {Icon} from '@astryxdesign/core/Icon';
+import {
+ colorVars,
+ focusVars,
+ fontWeightVars,
+ spacingVars,
+ textSizeVars,
+ typeScaleVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+import {
+ layerVelocities,
+ layersAt,
+ progressFromScreen,
+ programmaticVelocity,
+} from './navigationTransition';
+import {useBackSwipes, type BackSwipeStack} from './NavigationStackTouch';
+import {navigation, springs} from './navigationMotion';
+import {useMotionEngine} from '../internal/useMotionEngine';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface NavigationScreenProps {
+ /** The screen's title, shown in the bar and read first on arrival. */
+ title: string;
+ /**
+ * What the back button reads on the screen pushed on top of this one.
+ * Defaults to this screen's `title`.
+ */
+ backTitle?: string;
+ /** Content at the end of the bar while this screen is on top. */
+ endContent?: ReactNode;
+ /**
+ * How the title shows: in the bar (`inline`), or `large` above the
+ * content. A large title scrolls with the content, as iOS's large titles
+ * do. It hands over to the bar's title once it has scrolled under the bar.
+ * @default 'inline'
+ */
+ titleDisplayMode?: 'large' | 'inline';
+ /** The screen's content; it scrolls on its own. */
+ children?: ReactNode;
+}
+
+export interface NavigationStackProps<T> {
+ /** The root screen: a NavigationScreen. */
+ root: ReactElement<NavigationScreenProps>;
+ /** The entries pushed on the root, bottom first. Controlled. */
+ path: ReadonlyArray<T>;
+ /** Called with the new path when a push, pop or back swipe changes it. */
+ onPathChange: (path: T[]) => void;
+ /** Renders an entry's screen: a NavigationScreen. */
+ renderScreen: (
+ entry: T,
+ index: number,
+ ) => ReactElement<NavigationScreenProps>;
+ /**
+ * A stable key per entry, so a screen keeps its state while it moves down
+ * the stack. Defaults to the entry's position.
+ */
+ getKey?: (entry: T, index: number) => string | number;
+ /** Whether the back swipe pops. @default true */
+ isInteractivePopEnabled?: boolean;
+ /** Accessible name of the navigator region. */
+ label?: string;
+ 'data-testid'?: string;
+}
+
+export interface NavigationStackApi<T = unknown> {
+ /**
+ * Pushes an entry. The control that started it (the click or key press
+ * being handled, or `options.source`) gets focus back when its screen pops.
+ */
+ push: (entry: T, options?: {source?: Element | null}) => void;
+ /** Pops the top screen; nothing at the root. */
+ pop: () => void;
+ /** Pops back to the root. */
+ popToRoot: () => void;
+ /** How many screens are pushed on the root. */
+ depth: number;
+}
+
+// =============================================================================
+// Context
+// =============================================================================
+
+const NavigationStackContext = createContext<NavigationStackApi | null>(null);
+
+/** The enclosing NavigationStack's push / pop / popToRoot. */
+export function useNavigationStack<T = unknown>(): NavigationStackApi<T> {
+ const api = useContext(NavigationStackContext);
+ if (api == null) {
+ throw new Error('useNavigationStack must be used inside a NavigationStack');
+ }
+ return api as NavigationStackApi<T>;
+}
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+const BAR_HEIGHT = 44;
+
+const styles = stylex.create({
+ stack: {
+ position: 'relative',
+ width: '100%',
+ height: '100%',
+ overflow: 'hidden',
+ backgroundColor: colorVars['--color-background-body'],
+ },
+ // The bar overlays the screens, which scroll under it, as UIKit's content
+ // extends under its bar.
+ bar: {
+ position: 'absolute',
+ top: 0,
+ insetInline: 0,
+ isolation: 'isolate',
+ height: BAR_HEIGHT,
+ zIndex: 1,
+ },
+ // The bar's own background and hairline, under every screen's bar layer
+ // (each paints its own opaque background over it).
+ barBackground: {
+ position: 'absolute',
+ inset: 0,
+ zIndex: -2,
+ backgroundColor: colorVars['--color-background-surface'],
+ borderBottomWidth: 1,
+ borderBottomStyle: 'solid',
+ borderBottomColor: colorVars['--color-border'],
+ },
+ // Each screen's bar moves with its screen, as UIKit's per-screen bar copy
+ // does. It has an opaque background of its own (barLayerBackground), so
+ // the incoming one covers the outgoing title.
+ barLayer: {
+ position: 'absolute',
+ inset: 0,
+ display: 'grid',
+ gridTemplateColumns: '1fr auto 1fr',
+ alignItems: 'center',
+ paddingInline: spacingVars['--spacing-4'],
+ // Below the back button: WebKit does not promote the static siblings a
+ // moving layer crosses, so the moving one goes underneath.
+ zIndex: -1,
+ },
+ // A layer's opaque background, above the bar's hairline.
+ barLayerBackground: {
+ position: 'absolute',
+ insetInline: 0,
+ top: 0,
+ bottom: 1,
+ zIndex: -1,
+ backgroundColor: colorVars['--color-background-surface'],
+ },
+ // The one back button: it stays put while the bars move under it.
+ backControl: {
+ position: 'absolute',
+ insetInlineStart: spacingVars['--spacing-4'],
+ top: 0,
+ bottom: 0,
+ display: 'flex',
+ alignItems: 'center',
+ },
+ barLayerCovered: {
+ pointerEvents: 'none',
+ },
+ barStart: {
+ display: 'flex',
+ justifyContent: 'flex-start',
+ minWidth: 0,
+ },
+ barTitle: {
+ margin: 0,
+ minWidth: 0,
+ fontSize: textSizeVars['--font-size-lg'],
+ fontWeight: fontWeightVars['--font-weight-semibold'],
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ },
+ largeTitle: {
+ margin: 0,
+ paddingInline: spacingVars['--spacing-4'],
+ paddingTop: spacingVars['--spacing-1'],
+ paddingBottom: spacingVars['--spacing-2'],
+ fontSize: textSizeVars['--font-size-4xl'],
+ fontWeight: fontWeightVars['--font-weight-bold'],
+ lineHeight: typeScaleVars['--text-display-2-leading'],
+ // The scroller clips the sides: the ring draws inside the title.
+ outlineOffset: {
+ default: 0,
+ ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,
+ },
+ },
+ barEnd: {
+ display: 'flex',
+ justifyContent: 'flex-end',
+ minWidth: 0,
+ },
+ // iOS 26: a 44 pt circle holding only the chevron; the previous title
+ // is its accessible name, not a label.
+ back: {
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 44,
+ height: 44,
+ padding: 0,
+ borderRadius: '50%',
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: colorVars['--color-border'],
+ backgroundColor: colorVars['--color-background-surface'],
+ color: colorVars['--color-text-accent'],
+ cursor: {
+ default: 'pointer',
+ ':is(:disabled,[aria-disabled="true"])': 'default',
+ },
+ },
+ backIcon: {
+ transform: {
+ default: null,
+ ':is([dir="rtl"] *)': 'scaleX(-1)',
+ },
+ },
+ cards: {
+ position: 'absolute',
+ inset: 0,
+ },
+ card: {
+ position: 'absolute',
+ inset: 0,
+ overflow: 'hidden',
+ backgroundColor: colorVars['--color-background-body'],
+ },
+ scroller: {
+ position: 'absolute',
+ inset: 0,
+ boxSizing: 'border-box',
+ paddingTop: BAR_HEIGHT,
+ scrollPaddingTop: BAR_HEIGHT,
+ // The screen scrolls vertically; a sideways drag is the back swipe's. A
+ // horizontal scroller inside the content is its own scroll container
+ // and keeps its native sideways scrolling.
+ touchAction: 'pan-y pinch-zoom',
+ // The card clips anything outside the scroller: the ring draws inside it.
+ outlineOffset: {
+ default: 0,
+ ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,
+ },
+ },
+ cardHidden: {
+ contentVisibility: 'hidden',
+ },
+ dim: {
+ position: 'absolute',
+ inset: 0,
+ opacity: 0,
+ pointerEvents: 'none',
+ },
+ // A bar's dimming ends above the bar's hairline, as its background does:
+ // the covered bar would otherwise darken the hairline under it.
+ barDim: {
+ bottom: 1,
+ },
+});
+
+// The dimming's black is the UIKit table's alpha, a runtime value StyleX
+// cannot read at compile time.
+const dynamicStyles = stylex.create({
+ dimColor: (alpha: number) => ({
+ // eslint-disable-next-line @astryx/no-raw-color -- UIKit's parallax dimming is black at the table's measured alpha in every appearance; it is not a theme colour
+ backgroundColor: `rgba(0, 0, 0, ${alpha})`,
+ }),
+});
+
+// =============================================================================
+// Layers
+// =============================================================================
+
+/**
+ * One screen's animated layers: its card and the dimming over it, and its
+ * bar with the same dimming. The bar moves with the card, title and end
+ * content included.
+ */
+interface ScreenLayers {
+ card: MotionEngine;
+ dim: MotionEngine;
+ bar: MotionEngine;
+ barDim: MotionEngine;
+ titleElement: HTMLElement | null;
+ /** The large title above the content, for `titleDisplayMode="large"`. */
+ largeTitleElement: HTMLElement | null;
+ /** The bar title's text, hidden while the large title shows. */
+ titleText: MotionEngine;
+}
+
+type Registry = Map<string, Partial<ScreenLayers>>;
+
+interface ScreenModel {
+ key: string;
+ element: ReactElement<NavigationScreenProps>;
+ /** The control that pushed this screen; focus returns to it on the pop. */
+ source: Element | null;
+}
+
+function CardLayer({
+ model,
+ registry,
+ isTop,
+ isCovered,
+ isHidden,
+ onLargeTitleCollapse,
+}: {
+ model: ScreenModel;
+ registry: Registry;
+ isTop: boolean;
+ isCovered: boolean;
+ isHidden: boolean;
+ onLargeTitleCollapse: (key: string, isCollapsed: boolean) => void;
+}) {
+ const props = model.element.props;
+ const isLarge = props.titleDisplayMode === 'large';
+ // The large title has collapsed once it has scrolled entirely under the
+ // bar: the bar's own title takes over. The title reads the card's scroll
+ // position from the moment it attaches. A card hidden two levels down
+ // scrolls no more and keeps its last value. A title that detaches drops its
+ // collapse. One that attaches reads the scroll position again.
+ const largeTitleCallback = useCallback(
+ (title: HTMLHeadingElement | null) => {
+ const entry = registry.get(model.key) ?? {};
+ entry.largeTitleElement = title;
+ registry.set(model.key, entry);
+ const scroller = title?.parentElement ?? null;
+ if (title == null || scroller == null) {
+ return undefined;
+ }
+ // The screen scrolls under the bar: the title has gone once its bottom
+ // passes the bar's. A title with no layout has not scrolled away.
+ const read = () =>
+ onLargeTitleCollapse(
+ model.key,
+ title.offsetHeight > 0 &&
+ scroller.scrollTop >=
+ title.offsetTop + title.offsetHeight - BAR_HEIGHT,
+ );
+ read();
+ scroller.addEventListener('scroll', read, {passive: true});
+ // React runs this in place of a null call when the title detaches.
+ return () => {
+ scroller.removeEventListener('scroll', read);
+ onLargeTitleCollapse(model.key, false);
+ const current = registry.get(model.key);
+ if (current?.largeTitleElement === title) {
+ current.largeTitleElement = null;
+ }
+ };
+ },
+ [registry, model.key, onLargeTitleCollapse],
+ );
+ const card = useMotionEngine();
+ const dim = useMotionEngine();
+ // A forward Tab into the scroller moves on to its first plain link or
+ // button.
+ const {getViewportProps, getContentProps} = useScrollableArea({
+ axis: 'block',
+ overscroll: 'contain',
+ keyboardAccess: {owner: 'contentOrViewport', label: props.title},
+ });
+ // The screen's animators register as its card attaches. The callback is
+ // stable: a new one each render would detach and reattach the animator,
+ // and restart a running transition.
+ const cardRef = useCallback(
+ (element: HTMLDivElement | null) => {
+ card.ref(element);
+ const entry = registry.get(model.key) ?? {};
+ entry.card = card.animator;
+ entry.dim = dim.animator;
+ registry.set(model.key, entry);
+ },
+ [card, registry, model.key, dim.animator],
+ );
+ return (
+ <div
+ ref={cardRef}
+ data-navigation-screen={model.key}
+ data-navigation-top={isTop || undefined}
+ inert={isCovered || undefined}
+ {...stylex.props(styles.card, isHidden && styles.cardHidden)}>
+ <div
+ {...getViewportProps<HTMLDivElement>({
+ xstyle: [focusOutlineStyles.focusVisible, styles.scroller],
+ })}>
+ {isLarge ? (
+ <h1
+ ref={largeTitleCallback}
+ tabIndex={-1}
+ {...stylex.props(
+ focusOutlineStyles.focusVisible,
+ styles.largeTitle,
+ )}>
+ {props.title}
+ </h1>
+ ) : null}
+ <div {...getContentProps<HTMLDivElement>({})}>{props.children}</div>
+ </div>
+ <div
+ ref={dim.ref}
+ aria-hidden
+ {...stylex.props(
+ styles.dim,
+ dynamicStyles.dimColor(navigation.dimmingAlpha),
+ )}
+ />
+ </div>
+ );
+}
+
+function BarLayer({
+ model,
+ registry,
+ isCovered,
+ isLargeTitleShown,
+}: {
+ model: ScreenModel;
+ registry: Registry;
+ isCovered: boolean;
+ isLargeTitleShown: boolean;
+}) {
+ const bar = useMotionEngine();
+ const barDim = useMotionEngine();
+ // The bar's animators register with it as it attaches. Stable, as the
+ // card's: a new callback would detach and reattach the animator.
+ const barRef = useCallback(
+ (element: HTMLDivElement | null) => {
+ bar.ref(element);
+ const entry = registry.get(model.key) ?? {};
+ entry.bar = bar.animator;
+ entry.barDim = barDim.animator;
+ registry.set(model.key, entry);
+ },
+ [bar, registry, model.key, barDim.animator],
+ );
+ const titleText = useMotionEngine();
+ const wasShownRef = useRef<boolean | null>(null);
+ // The bar's title hides while the screen's large title shows, and fades in
+ // once the large title has scrolled under the bar. This drives the title's
+ // compositor animator, the system it syncs.
+ useLayoutEffect(() => {
+ const target = {
+ opacity: isLargeTitleShown ? 0 : 1,
+ y: isLargeTitleShown ? navigation.inlineTitleRise : 0,
+ };
+ if (wasShownRef.current == null) {
+ // First layout: the title is in place at once.
+ titleText.animator.set(target);
+ } else if (wasShownRef.current !== isLargeTitleShown) {
+ titleText.animator.animate(target, {
+ spring: springs.navigationBarElements,
+ });
+ }
+ wasShownRef.current = isLargeTitleShown;
+ }, [titleText.animator, isLargeTitleShown]);
+ // The title is one element (its heading role): the stack focuses it, and
+ // the animator rises and fades it. Both register as the title attaches.
+ const titleRefs = useCallback(
+ (element: HTMLHeadingElement | null) => {
+ const entry = registry.get(model.key) ?? {};
+ entry.titleElement = element;
+ entry.titleText = titleText.animator;
+ registry.set(model.key, entry);
+ titleText.ref(element);
+ },
+ [registry, model.key, titleText],
+ );
+ const props = model.element.props;
+ return (
+ <div
+ ref={barRef}
+ data-navigation-bar={model.key}
+ inert={isCovered || undefined}
+ {...stylex.props(styles.barLayer, isCovered && styles.barLayerCovered)}>
+ <div aria-hidden {...stylex.props(styles.barLayerBackground)} />
+ <div {...stylex.props(styles.barStart)} />
+ <h2
+ ref={titleRefs}
+ tabIndex={-1}
+ aria-hidden={isLargeTitleShown || undefined}
+ {...stylex.props(styles.barTitle, focusOutlineStyles.focusVisible)}>
+ {props.title}
+ </h2>
+ <div {...stylex.props(styles.barEnd)}>{props.endContent}</div>
+ <div
+ ref={barDim.ref}
+ aria-hidden
+ {...stylex.props(
+ styles.dim,
+ styles.barDim,
+ dynamicStyles.dimColor(navigation.dimmingAlpha),
+ )}
+ />
+ </div>
+ );
+}
+
+/**
+ * The back button: one for the stack, over the moving bars. Its glass
+ * platter shows from a push's first frame; its chevron fades in and out on
+ * its own clock (the stack drives both).
+ */
+function BackControl({
+ label,
+ onBack,
+ isInert,
+ control,
+ chevron,
+}: {
+ label: string;
+ onBack: () => void;
+ isInert: boolean;
+ control: (element: HTMLElement | null) => void;
+ chevron: (element: HTMLElement | null) => void;
+}) {
+ // The motion engine takes an HTML element, and the icon's ref reaches its
+ // inner SVG. So the animator binds the icon's wrapper, the button's first
+ // child.
+ const buttonRef = useCallback(
+ (button: HTMLButtonElement | null) => {
+ const icon = button?.firstElementChild;
+ chevron(isHTMLElement(icon) ? icon : null);
+ },
+ [chevron],
+ );
+ return (
+ <div
+ ref={control}
+ inert={isInert || undefined}
+ {...stylex.props(styles.backControl)}>
+ <button
+ ref={buttonRef}
+ type="button"
+ onClick={onBack}
+ aria-label={label}
+ data-navigation-back
+ {...stylex.props(styles.back)}>
+ <Icon icon="chevronLeft" color="inherit" xstyle={styles.backIcon} />
+ </button>
+ </div>
+ );
+}
+
+// =============================================================================
+// Screen
+// =============================================================================
+
+/**
+ * One screen of a NavigationStack. Its props describe the screen (title,
+ * back title, end content, content); the stack lays it out.
+ */
+export function NavigationScreen(_props: NavigationScreenProps): ReactNode {
+ // Rendered by NavigationStack, which reads these props; on its own it is
+ // nothing.
+ return null;
+}
+NavigationScreen.displayName = 'NavigationScreen';
+
+// =============================================================================
+// Stack
+// =============================================================================
+
+interface Transition {
+ id: number;
+ kind: 'push' | 'pop' | 'none';
+ /** The screen on top when the transition ends (push) or leaving (pop). */
+ top: string;
+ /** The screen under it. */
+ under: string | null;
+}
+
+/**
+ * Whether a value is an element, by its node type. `instanceof` reads the
+ * constructors of the window running this module. A stack rendered into
+ * another window (an iframe, a picture-in-picture window) does not use them.
+ */
+function isElement(value: unknown): value is Element {
+ return (
+ typeof value === 'object' &&
+ value != null &&
+ (value as Partial<Node>).nodeType === 1
+ );
+}
+
+function isHTMLElement(value: unknown): value is HTMLElement {
+ return (
+ isElement(value) && value.namespaceURI === 'http://www.w3.org/1999/xhtml'
+ );
+}
+
+/** What a press on a control's label or icon gives focus back to. */
+const FOCUSABLE_CONTROL =
+ 'button, a[href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
+
+/** The stack's writing direction, as core reads it. */
+function writingDirection(element: HTMLElement | null): 'ltr' | 'rtl' {
+ return isRtlElement(element) ? 'rtl' : 'ltr';
+}
+
+/**
+ * A push/pop navigator: UINavigationController's transitions, back button
+ * and back swipes, on the compositor.
+ *
+ * The app owns the path (`path` + `onPathChange`). The stack renders the
+ * root screen and one screen per entry, top last. It animates the change
+ * whenever the path gains or loses its top entry.
+ *
+ * Motion is UIKit's, measured on iOS 26.2 (motion/uikit/navigation.ts). A
+ * push is a critically damped spring (response 0.3 s) that starts at 8.773
+ * widths per second. The card underneath moves at 0.3 of the top card's
+ * speed, under a 10 % black dimming. Each screen's bar moves with it.
+ * Every layer runs on the compositor (core's animator), so a busy main thread
+ * does not stall a push or a pop. The recognizer tracks the back swipe 1:1,
+ * from the leading screen edge or, as on iOS 26, from anywhere in the
+ * content. The compositor plays its release. The swipe finishes when
+ * progress plus 0.35 s of velocity passes half the width. It finishes on a
+ * spring (0.3 s, ζ 0.85) that starts at the finger's speed. Nothing waits
+ * for a push. A pop during a push turns it around from where it is, and a
+ * finger can grab the moving card.
+ *
+ * The bar is iOS 26's (measured). Each screen has its own opaque bar that
+ * moves with its screen. So a pushed title slides in with its screen and
+ * covers the one it replaces, which rides the parallax underneath. Under a
+ * finger the revealed bar holds still. Back is one 44 pt circle over the
+ * bars. It holds only the chevron and takes its name from the screen it
+ * returns to. On a push from the root, its platter is there from the first
+ * frame, and the chevron fades in a beat later. On a pop to the root, the
+ * chevron fades out at once and the platter leaves with the screen. A back
+ * swipe leaves it alone until the pop finishes.
+ *
+ * In a browser tab the screen's leading edge is the browser's own back
+ * swipe, which iOS Safari keeps. So the stack's edge swipe runs only in a
+ * home-screen web app (`navigator.standalone`). The content swipe ignores
+ * touches that start in that edge band.
+ *
+ * Reduced Motion is the animator's. Under a finger the incoming screen fades
+ * in where it lands, and the outgoing one fades out in 200 ms. Nothing
+ * travels and nothing dims. Under a mouse the change is immediate. A finger's
+ * back swipe still tracks it, and what its release starts fades on any
+ * pointer.
+ *
+ * Accessibility: covered screens are `inert`. A push moves focus to the new
+ * screen's title; a pop returns it to the control that pushed the screen.
+ * The back button is a real button named by the screen it returns to.
+ */
+export function NavigationStack<T>({
+ root,
+ path,
+ onPathChange,
+ renderScreen,
+ getKey,
+ isInteractivePopEnabled = true,
+ label,
+ 'data-testid': testId,
+}: NavigationStackProps<T>) {
+ const t = useTranslator();
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const cardsRef = useRef<HTMLDivElement>(null);
+ const [registry] = useState<Registry>(() => new Map());
+ // The last input decides whether a moved focus shows its ring.
+ const {ref: trackModality, readModality} = useInteractionModalityTracking();
+ const containerCallback = useCallback(
+ (element: HTMLDivElement | null) => {
+ containerRef.current = element;
+ const release = trackModality(element);
+ return () => {
+ release?.();
+ containerRef.current = null;
+ };
+ },
+ [trackModality],
+ );
+ // Screens whose large title has scrolled under the bar. The ref holds the
+ // same set for the handlers and effects below; only the handler changes it.
+ const [collapsedTitles, setCollapsedTitles] = useState<ReadonlySet<string>>(
+ () => new Set(),
+ );
+ const collapsedRef = useRef(collapsedTitles);
+ const onLargeTitleCollapse = useCallback(
+ (key: string, isCollapsed: boolean) => {
+ const current = collapsedRef.current;
+ if (current.has(key) === isCollapsed) {
+ return;
+ }
+ const next = new Set(current);
+ if (isCollapsed) {
+ next.add(key);
+ } else {
+ next.delete(key);
+ }
+ collapsedRef.current = next;
+ setCollapsedTitles(next);
+ },
+ [],
+ );
+
+ // The screens on the path, root first.
+ const models = useMemo<ScreenModel[]>(() => {
+ const list: ScreenModel[] = [{key: 'root', element: root, source: null}];
+ path.forEach((entry, index) => {
+ list.push({
+ key: `screen-${getKey ? getKey(entry, index) : index}`,
+ element: renderScreen(entry, index),
+ source: null,
+ });
+ });
+ return list;
+ }, [root, path, renderScreen, getKey]);
+ const keys = models.map(model => model.key).join('\u0000');
+
+ // Sources of pushes, by screen key (focus returns there on the pop).
+ const sourcesRef = useRef(new Map<string, Element | null>());
+ // The last control activated inside the stack: what a push it starts came
+ // from.
+ const lastActivationRef = useRef<{target: Element; at: number} | null>(null);
+ // A pending push source handed to push(): applied to the new top.
+ const pendingSourceRef = useRef<Element | null | undefined>(undefined);
+ // An interactive release in flight: the pop it commits continues from the
+ // finger's velocity instead of starting a programmatic pop.
+ const releaseRef = useRef<{velocity: number} | null>(null);
+
+ // Derived during render, so a popped screen is still rendered (leaving) in
+ // the very commit that drops it from the path.
+ const [view, setView] = useState<{
+ keys: string;
+ models: ScreenModel[];
+ leaving: ScreenModel | null;
+ transition: Transition;
+ }>(() => ({
+ keys,
+ models,
+ leaving: null,
+ transition: {
+ id: 0,
+ kind: 'none',
+ top: models.at(-1)?.key ?? 'root',
+ under: null,
+ },
+ }));
+
+ if (view.keys !== keys) {
+ const before = view.models;
+ const isPrefix = (shorter: ScreenModel[], longer: ScreenModel[]) =>
+ shorter.every((model, i) => longer[i]?.key === model.key);
+ let transition: Transition;
+ let leaving: ScreenModel | null = null;
+ if (models.length === before.length + 1 && isPrefix(before, models)) {
+ transition = {
+ id: view.transition.id + 1,
+ kind: 'push',
+ top: models[models.length - 1].key,
+ under: before[before.length - 1]?.key ?? null,
+ };
+ } else if (models.length < before.length && isPrefix(models, before)) {
+ leaving = before[before.length - 1];
+ transition = {
+ id: view.transition.id + 1,
+ kind: 'pop',
+ top: leaving.key,
+ under: models[models.length - 1].key,
+ };
+ } else {
+ transition = {
+ id: view.transition.id + 1,
+ kind: 'none',
+ top: models[models.length - 1].key,
+ under: null,
+ };
+ }
+ setView({keys, models, leaving, transition});
+ } else if (view.models !== models) {
+ // Same screens, new elements (the app re-rendered): keep them current.
+ setView({...view, models});
+ }
+
+ const depth = models.length - 1;
+ const rendered = view.leaving ? [...view.models, view.leaving] : view.models;
+ const topKey = view.leaving
+ ? view.leaving.key
+ : (view.models.at(-1)?.key ?? 'root');
+ // While a pop runs, the screen it reveals; otherwise the one under the top
+ // (a finished pop's `transition.under` is the new top itself).
+ const underKey =
+ view.leaving != null
+ ? view.transition.under
+ : (view.models.at(-2)?.key ?? null);
+
+ // ---------------------------------------------------------------------------
+ // Transition driver
+ // ---------------------------------------------------------------------------
+
+ const runningRef = useRef<{id: number; done: boolean} | null>(null);
+ // The clock the last transition's screens run on (their start time), so
+ // the back chevron keeps time with them.
+ const startedRef = useRef(0);
+ // A pop's focus return, waiting for the commit that drops the leaving
+ // screen (until then every screen is `inert` and cannot take focus).
+ const pendingFocusRef = useRef<{popped: string; revealed: string} | null>(
+ null,
+ );
+ const progressRef = useRef(0);
+ // The back button's platter and chevron (one for the stack).
+ const backControl = useMotionEngine();
+ const backChevron = useMotionEngine();
+
+ const layersOf = useCallback(
+ (key: string | null) => (key == null ? null : (registry.get(key) ?? null)),
+ [registry],
+ );
+
+ /**
+ * Writes the layers for progress p (a finger's frame, or a transition's
+ * first one; no animation). The top bar moves with its card. Under a
+ * finger the revealed bar holds still where it rests, as UIKit's does.
+ * `underBar: 'ride'` puts it at its card's parallax instead, where a
+ * programmatic pop starts it.
+ */
+ const setProgress = useCallback(
+ (
+ p: number,
+ top: string,
+ under: string | null,
+ underBar: 'rest' | 'ride' = 'rest',
+ ) => {
+ const width = cardsRef.current?.clientWidth ?? 0;
+ const direction = writingDirection(containerRef.current);
+ const values = layersAt(p, width, direction);
+ const topLayers = layersOf(top);
+ const underLayers = layersOf(under);
+ topLayers?.card?.set({x: values.topX});
+ topLayers?.bar?.set({x: values.topX});
+ underLayers?.card?.set({x: values.underX});
+ underLayers?.bar?.set({x: underBar === 'ride' ? values.underX : 0});
+ underLayers?.dim?.set({opacity: values.dim});
+ underLayers?.barDim?.set({opacity: values.dim});
+ progressRef.current = p;
+ },
+ [layersOf],
+ );
+
+ /**
+ * Springs the layers to progress `to`. `dp` is the progress velocity to
+ * start from (omit it to keep the velocity the layers have on screen).
+ */
+ const animateProgress = useCallback(
+ (
+ to: 0 | 1,
+ top: string,
+ under: string | null,
+ spring: SpringDescription,
+ dp: number | undefined,
+ release: boolean,
+ underBar: 'rest' | 'ride',
+ startAt?: number,
+ ): Promise<boolean> => {
+ const width = cardsRef.current?.clientWidth ?? 0;
+ const direction = writingDirection(containerRef.current);
+ const values = layersAt(to, width, direction);
+ const velocity =
+ dp == null ? null : layerVelocities(dp, width, direction);
+ const at = startAt ?? performance.now();
+ const topLayers = layersOf(top);
+ const underLayers = layersOf(under);
+ const handles = [];
+ // Reduced Motion is the animator's; `crossfadeAs` says which card
+ // enters (fades in where it lands) and which leaves (fades out in
+ // place). A finger's release fades on any pointer (`touchRelease`).
+ if (topLayers?.card) {
+ handles.push(
+ topLayers.card.animate(
+ {x: values.topX},
+ {spring, velocity: velocity ? {x: velocity.topX} : undefined},
+ {
+ at,
+ touchRelease: release,
+ crossfadeAs: to === 0 ? 'entrance' : 'exit',
+ },
+ ),
+ );
+ startedRef.current = at;
+ }
+ // The bars move with their cards (each screen's bar is part of it in
+ // UIKit): the incoming one covers the outgoing title.
+ if (topLayers?.bar) {
+ handles.push(
+ topLayers.bar.animate(
+ {x: values.topX},
+ {spring, velocity: velocity ? {x: velocity.topX} : undefined},
+ {at, touchRelease: release},
+ ),
+ );
+ }
+ if (underLayers?.bar && underBar === 'ride') {
+ handles.push(
+ underLayers.bar.animate(
+ {x: values.underX},
+ {spring, velocity: velocity ? {x: velocity.underX} : undefined},
+ {at, touchRelease: release},
+ ),
+ );
+ }
+ if (underLayers?.card) {
+ handles.push(
+ underLayers.card.animate(
+ {x: values.underX},
+ {spring, velocity: velocity ? {x: velocity.underX} : undefined},
+ {
+ at,
+ touchRelease: release,
+ crossfadeAs: to === 1 ? 'entrance' : 'exit',
+ },
+ ),
+ );
+ }
+ for (const dim of [underLayers?.dim, underLayers?.barDim]) {
+ if (dim == null) {
+ continue;
+ }
+ if (dim.reducedMotion({touchRelease: release}) !== 'off') {
+ // A Reduced Motion fade has no dimming: the shade belongs to the
+ // slide.
+ dim.set({opacity: 0});
+ } else {
+ handles.push(
+ dim.animate(
+ {opacity: values.dim},
+ {
+ spring,
+ velocity: velocity ? {opacity: velocity.dim} : undefined,
+ },
+ {at, touchRelease: release},
+ ),
+ );
+ }
+ }
+ progressRef.current = to;
+ return Promise.all(handles.map(async handle => handle.finished)).then(
+ results => results.every(Boolean),
+ );
+ },
+ [layersOf],
+ );
+
+ /**
+ * The back button on a push from the root or a pop to it, as UIKit's. On
+ * the push the platter is there from the first frame, and the chevron
+ * fades in a beat later. On the pop the chevron fades out at once, and the
+ * platter leaves with the screen. Both fades are the back-button spring;
+ * the push's delay is the navigation table's, as measured.
+ */
+ const fadeBack = useCallback(
+ (kind: 'push' | 'pop', under: string | null, release = false) => {
+ const isRoot = under != null && view.models[0]?.key === under;
+ const element = containerRef.current;
+ const spring = springs.navigationBackButton;
+ if (!isRoot) {
+ return;
+ }
+ const delay =
+ kind === 'pop'
+ ? 0
+ : resolveMotion(element, navigation, 'backChevronPushDelayMs');
+ if (kind === 'push') {
+ backControl.animator.set({opacity: 1});
+ backChevron.animator.set({opacity: 0});
+ }
+ // On the screens' clock, and starting with them. The delay is part of
+ // the curve, so the whole fade is one compositor animation. A busy main
+ // thread cannot hold it back. In WebKit a start in the future would
+ // wait for the main thread.
+ const from = kind === 'push' ? 0 : 1;
+ const to = kind === 'push' ? 1 : 0;
+ const fade = solveSpring(toSpring(resolveMotion(element, spring)), {
+ from,
+ to,
+ });
+ const delayS = delay / 1000;
+ backChevron.animator.play(
+ {
+ opacity: {
+ duration: delayS + fade.settleTime(0.001),
+ at: t => (t < delayS ? from : fade.value(t - delayS)),
+ velocity: t => (t < delayS ? 0 : fade.velocity(t - delayS)),
+ },
+ },
+ {at: startedRef.current, touchRelease: release},
+ );
+ },
+ [view.models, backControl.animator, backChevron.animator],
+ );
+
+ /** Puts a screen's layers at rest: on top, covered, or off. */
+ const settle = useCallback(
+ (key: string, role: 'top' | 'covered') => {
+ const layers = layersOf(key);
+ const width = cardsRef.current?.clientWidth ?? 0;
+ const direction = writingDirection(containerRef.current);
+ const values = layersAt(0, width, direction);
+ if (role === 'top') {
+ layers?.card?.set({x: 0, opacity: 1});
+ layers?.dim?.set({opacity: 0});
+ layers?.bar?.set({x: 0});
+ layers?.barDim?.set({opacity: 0});
+ } else {
+ // Covered: parked at the parallax, under the top screen and its bar.
+ layers?.card?.set({x: values.underX, opacity: 1});
+ layers?.dim?.set({opacity: 1});
+ layers?.bar?.set({x: values.underX});
+ layers?.barDim?.set({opacity: 1});
+ }
+ },
+ [layersOf],
+ );
+
+ const focusAfter = useCallback(
+ (kind: 'push' | 'pop', key: string, revealed?: string) => {
+ const container = containerRef.current;
+ // Only move focus when it was in the stack or nowhere: never take it
+ // from elsewhere on the page.
+ if (container == null || !isFocusLost(container)) {
+ return;
+ }
+ // The moved focus shows its ring by the last input, as Core's overlays
+ // do. After a key it shows; after a tap it does not.
+ const modality = readModality();
+ const focus = (element: HTMLElement) =>
+ focusForLastInput(element, {preventScroll: true}, modality);
+ if (kind === 'pop') {
+ const source = sourcesRef.current.get(key);
+ sourcesRef.current.delete(key);
+ if (isHTMLElement(source) && source.isConnected) {
+ focus(source);
+ // A control that can no longer take focus falls through to the
+ // title.
+ if (source.ownerDocument.activeElement === source) {
+ return;
+ }
+ }
+ }
+ // Else the screen now on top (the one pushed, or the one revealed): its
+ // visible title, the large title while it shows, else the bar's.
+ const target = revealed ?? key;
+ const layers = layersOf(target);
+ const large = layers?.largeTitleElement;
+ const title =
+ large != null && large.isConnected && !collapsedRef.current.has(target)
+ ? large
+ : layers?.titleElement;
+ if (title != null) {
+ focus(title);
+ }
+ },
+ [layersOf, readModality],
+ );
+
+ // The committed view, and the back fade that follows it, for the effect
+ // below. They sync at each commit, so only a new transition restarts it.
+ const transitionInputsRef = useRef({view, fadeBack});
+ useLayoutEffect(() => {
+ transitionInputsRef.current = {view, fadeBack};
+ });
+ // Runs the transition the last path change asked for. It drives the
+ // screens' and bars' compositor animators, the system it syncs.
+ useLayoutEffect(() => {
+ const {view, fadeBack} = transitionInputsRef.current;
+ const transition = view.transition;
+ if (transition.kind === 'none') {
+ // Settle every screen where it rests.
+ view.models.forEach((model, index) => {
+ settle(model.key, index === view.models.length - 1 ? 'top' : 'covered');
+ });
+ backControl.animator.set({opacity: 1});
+ backChevron.animator.set({opacity: 1});
+ return;
+ }
+ const {top, under} = transition;
+ const id = transition.id;
+ const previous = runningRef.current;
+ const wasRunning = previous != null && !previous.done;
+ runningRef.current = {id, done: false};
+ const release = releaseRef.current;
+ releaseRef.current = null;
+ pendingFocusRef.current = null;
+ const at = performance.now();
+ let promise: Promise<boolean>;
+ if (transition.kind === 'push') {
+ if (!wasRunning) {
+ setProgress(1, top, under);
+ } else {
+ // The covered screen continues from where it is; the new one (just
+ // mounted, at rest) starts off screen as any push does.
+ const values = layersAt(
+ 1,
+ cardsRef.current?.clientWidth ?? 0,
+ writingDirection(containerRef.current),
+ );
+ layersOf(top)?.card?.set({x: values.topX});
+ layersOf(top)?.bar?.set({x: values.topX});
+ }
+ promise = animateProgress(
+ 0,
+ top,
+ under,
+ springs.navigationPush,
+ wasRunning ? undefined : programmaticVelocity('push'),
+ false,
+ 'ride',
+ );
+ fadeBack('push', under);
+ } else if (release != null) {
+ promise = animateProgress(
+ 1,
+ top,
+ under,
+ springs.navigationInteractivePopFinish,
+ release.velocity,
+ true,
+ 'rest',
+ at,
+ );
+ fadeBack('pop', under, true);
+ } else {
+ if (!wasRunning) {
+ setProgress(0, top, under, 'ride');
+ }
+ promise = animateProgress(
+ 1,
+ top,
+ under,
+ springs.navigationPop,
+ wasRunning ? undefined : programmaticVelocity('pop'),
+ false,
+ 'ride',
+ at,
+ );
+ fadeBack('pop', under);
+ }
+ void promise.then(finished => {
+ if (runningRef.current?.id !== id) {
+ return;
+ }
+ runningRef.current = {id, done: true};
+ if (!finished) {
+ return;
+ }
+ if (transition.kind === 'pop') {
+ setView(current =>
+ current.transition.id === id ? {...current, leaving: null} : current,
+ );
+ if (under != null) {
+ settle(under, 'top');
+ pendingFocusRef.current = {popped: top, revealed: under};
+ }
+ } else {
+ if (under != null) {
+ // The covered screen keeps its place under the top one.
+ layersOf(under)?.card?.set({opacity: 1});
+ }
+ focusAfter('push', top);
+ }
+ });
+ // Only a new transition restarts this; the stack drives the layers
+ // imperatively.
+ }, [
+ view.transition.id,
+ animateProgress,
+ focusAfter,
+ layersOf,
+ setProgress,
+ settle,
+ backControl.animator,
+ backChevron.animator,
+ ]);
+
+ // The pop's focus return, after the commit that dropped the leaving screen
+ // (the DOM's focus, the system this effect drives).
+ useLayoutEffect(() => {
+ const pending = pendingFocusRef.current;
+ if (view.leaving == null && pending != null) {
+ pendingFocusRef.current = null;
+ focusAfter('pop', pending.popped, pending.revealed);
+ }
+ }, [view.leaving, focusAfter]);
+
+ // ---------------------------------------------------------------------------
+ // API
+ // ---------------------------------------------------------------------------
+
+ // The committed path and callback, synced at each commit. `push` and `pop`
+ // build the next path from what the screen shows, never from a render
+ // React discards.
+ const pathRef = useRef(path);
+ const onPathChangeRef = useRef(onPathChange);
+ useLayoutEffect(() => {
+ pathRef.current = path;
+ onPathChangeRef.current = onPathChange;
+ });
+
+ const api = useMemo<NavigationStackApi<T>>(
+ () => ({
+ push: (entry, options) => {
+ const last = lastActivationRef.current;
+ const source =
+ options?.source !== undefined
+ ? options.source
+ : last != null && performance.now() - last.at < 1000
+ ? last.target
+ : null;
+ pendingSourceRef.current = source;
+ onPathChangeRef.current([...pathRef.current, entry]);
+ },
+ pop: () => {
+ if (pathRef.current.length > 0) {
+ onPathChangeRef.current(pathRef.current.slice(0, -1));
+ }
+ },
+ popToRoot: () => {
+ if (pathRef.current.length > 0) {
+ onPathChangeRef.current([]);
+ }
+ },
+ depth,
+ }),
+ [depth],
+ );
+
+ // Record the source of a push on the screen it pushed.
+ useLayoutEffect(() => {
+ if (view.transition.kind !== 'push') {
+ return;
+ }
+ if (pendingSourceRef.current !== undefined) {
+ sourcesRef.current.set(view.transition.top, pendingSourceRef.current);
+ pendingSourceRef.current = undefined;
+ }
+ }, [view.transition]);
+
+ // The control a push starts from: the last click or key press in the stack,
+ // from the container's own capture handlers. A press on a control's label or
+ // icon remembers the control itself.
+ const rememberActivation = useCallback((event: SyntheticEvent) => {
+ const {target} = event;
+ if (isElement(target)) {
+ // The scroller is focusable while it overflows, but it is not a
+ // control. After a push from its plain content, the pop focuses the
+ // title.
+ const control = target.closest(FOCUSABLE_CONTROL);
+ const isScreenScroller =
+ control?.parentElement?.hasAttribute('data-navigation-screen') === true;
+ lastActivationRef.current = {
+ target: control != null && !isScreenScroller ? control : target,
+ at: performance.now(),
+ };
+ }
+ }, []);
+
+ // ---------------------------------------------------------------------------
+ // Back swipes
+ // ---------------------------------------------------------------------------
+
+ const canPop = depth > 0 && view.leaving == null;
+ // What the touch layer (NavigationStackTouch.ts) moves: the swipes read
+ // and drive the stack through this, each frame's values from the latest
+ // render.
+ const swipeStackRef = useRef<BackSwipeStack | null>(null);
+ const swipeStack: BackSwipeStack = {
+ width: () => cardsRef.current?.clientWidth ?? 0,
+ direction: () => writingDirection(containerRef.current),
+ screens: () => {
+ const top = view.models.at(-1)?.key;
+ const under = view.models.at(-2)?.key;
+ return top == null || under == null ? null : {top, under};
+ },
+ grab: (top, under) => {
+ // Grab whatever is moving: the top card's presentation value is the
+ // progress to continue from.
+ const width = cardsRef.current?.clientWidth ?? 0;
+ const x = layersOf(top)?.card?.get('x') ?? 0;
+ const direction = writingDirection(containerRef.current);
+ for (const key of [top, under]) {
+ const layers = layersOf(key);
+ layers?.card?.stop();
+ layers?.dim?.stop();
+ layers?.bar?.stop();
+ layers?.barDim?.stop();
+ }
+ runningRef.current = null;
+ return progressFromScreen(x, width, direction);
+ },
+ setProgress: (p, top, under) => {
+ setProgress(p, top, under);
+ },
+ progress: () => progressRef.current,
+ release: (top, under, finish, velocity) => {
+ const springBack = (v: number) => {
+ const id = (runningRef.current?.id ?? 0) + 0.5;
+ runningRef.current = {id, done: false};
+ const at = performance.now();
+ void animateProgress(
+ 0,
+ top,
+ under,
+ // Released past its start (rubber-banded), UIKit's return.
+ progressRef.current < 0
+ ? springs.navigationInteractivePopReturn
+ : springs.navigationInteractivePopFinish,
+ v,
+ true,
+ 'rest',
+ at,
+ ).then(finished => {
+ if (runningRef.current?.id === id) {
+ runningRef.current = {id, done: true};
+ }
+ if (finished) {
+ settle(top, 'top');
+ settle(under, 'covered');
+ }
+ });
+ };
+ if (!finish) {
+ springBack(velocity);
+ return;
+ }
+ // Commit the pop; the transition it triggers continues from here at
+ // the finger's speed.
+ const release = {velocity};
+ const before = pathRef.current;
+ releaseRef.current = release;
+ onPathChangeRef.current(before.slice(0, -1));
+ // An app that keeps its path (guarding unsaved edits, say) gets no
+ // pop. By the next frame the release is still waiting, so the cards
+ // spring back where they came from.
+ const win = containerRef.current?.ownerDocument.defaultView;
+ win?.requestAnimationFrame(() => {
+ if (releaseRef.current === release && pathRef.current === before) {
+ releaseRef.current = null;
+ springBack(0);
+ }
+ });
+ },
+ };
+ useLayoutEffect(() => {
+ swipeStackRef.current = swipeStack;
+ });
+ useBackSwipes(containerRef, cardsRef, swipeStackRef, {
+ isEnabled: canPop && isInteractivePopEnabled,
+ });
+
+ // ---------------------------------------------------------------------------
+ // Render
+ // ---------------------------------------------------------------------------
+
+ const backLabelFor = (index: number) => {
+ if (index === 0) {
+ return null;
+ }
+ const previous = rendered[index - 1]?.element.props;
+ // An empty title names nothing: the catalog's "Back" covers that too.
+ return (
+ previous?.backTitle ||
+ previous?.title ||
+ t('@astryx.navigationStack.back')
+ );
+ };
+ // The top screen's back target; while a pop to the root runs, the leaving
+ // screen's (its button fades out with it).
+ const topBackLabel = backLabelFor(
+ rendered.findIndex(model => model.key === topKey),
+ );
+
+ return (
+ <NavigationStackContext.Provider value={api as NavigationStackApi}>
+ <div
+ ref={containerCallback}
+ role="region"
+ aria-label={label}
+ data-testid={testId}
+ onClickCapture={rememberActivation}
+ onKeyDownCapture={rememberActivation}
+ {...stylex.props(styles.stack)}>
+ <div {...stylex.props(styles.bar)}>
+ <div aria-hidden {...stylex.props(styles.barBackground)} />
+ {rendered.map(model =>
+ model.key === topKey || model.key === underKey ? (
+ <BarLayer
+ key={model.key}
+ model={model}
+ registry={registry}
+ isCovered={model.key !== topKey || view.leaving != null}
+ isLargeTitleShown={
+ model.element.props.titleDisplayMode === 'large' &&
+ !collapsedTitles.has(model.key)
+ }
+ />
+ ) : null,
+ )}
+ {topBackLabel != null ? (
+ <BackControl
+ label={topBackLabel}
+ onBack={api.pop}
+ isInert={view.leaving != null}
+ control={backControl.ref}
+ chevron={backChevron.ref}
+ />
+ ) : null}
+ </div>
+ <div ref={cardsRef} {...stylex.props(styles.cards)}>
+ {rendered.map(model => (
+ <CardLayer
+ key={model.key}
+ model={model}
+ registry={registry}
+ isTop={model.key === topKey && view.leaving == null}
+ isCovered={model.key !== topKey || view.leaving != null}
+ isHidden={model.key !== topKey && model.key !== underKey}
+ onLargeTitleCollapse={onLargeTitleCollapse}
+ />
+ ))}
+ </div>
+ </div>
+ </NavigationStackContext.Provider>
+ );
+}
+
+NavigationStack.displayName = 'NavigationStack';
diff --git a/packages/lab/src/NavigationStack/NavigationStackTouch.ts b/packages/lab/src/NavigationStack/NavigationStackTouch.ts
new file mode 100644
index 0000000000..e45c164b99
--- /dev/null
+++ b/packages/lab/src/NavigationStack/NavigationStackTouch.ts
@@ -0,0 +1,228 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file NavigationStackTouch.ts
+ * @input Core's gesture recognizers and UIKit gesture table, from its
+ * internal touch entry, and navigationMotion.ts and navigationTransition.ts
+ * for the swipe's values and release math
+ * @output useBackSwipes: UIKit's two back swipes, from the leading screen
+ * edge and from anywhere in the content (iOS 26), driving a stack through
+ * BackSwipeStack
+ * @position NavigationStack's back swipes, imported in one place
+ * (NavigationStack.tsx).
+ */
+
+import {useCallback, useRef, useSyncExternalStore, type RefObject} from 'react';
+import {
+ PanGestureRecognizer,
+ ScreenEdgePanGestureRecognizer,
+ UIKIT_GESTURES,
+ useGestureRecognizer,
+} from '@astryxdesign/core/internal/touch';
+import {navigation} from './navigationMotion';
+import {
+ popVelocity,
+ progressFromTravel,
+ shouldFinishPop,
+} from './navigationTransition';
+
+/** What a back swipe reads from the stack and drives in it. */
+export interface BackSwipeStack {
+ /** The cards' width in CSS px. */
+ width(): number;
+ /** The stack's writing direction. */
+ direction(): 'ltr' | 'rtl';
+ /** The screens a pop moves between, or null when there is nothing to pop. */
+ screens(): {top: string; under: string} | null;
+ /** Stops whatever moves and returns the progress to continue from. */
+ grab(top: string, under: string): number;
+ /** Puts both screens at a progress (0: the top at rest, 1: popped). */
+ setProgress(progress: number, top: string, under: string): void;
+ /** The progress the screens are at now. */
+ progress(): number;
+ /**
+ * The finger lifted (or the swipe was cancelled): commit the pop, or
+ * spring back, at the release velocity in widths per second.
+ */
+ release(top: string, under: string, finish: boolean, velocity: number): void;
+}
+
+/** Whether the page runs as a home-screen web app never changes while it runs. */
+const subscribeToNothing = () => () => {};
+
+/**
+ * The content swipe claims a sideways drag at the pan's own threshold, while
+ * the browser can still be told no. The browser stops asking once its own
+ * slop has passed. The content swipe moves nothing until UIKit's 27 px: the
+ * travel in between is a dead zone.
+ */
+const CONTENT_CLAIM_PX = UIKIT_GESTURES.pan.hysteresis.value;
+const CONTENT_DEAD_ZONE_PX = Math.max(
+ 0,
+ navigation.contentPopHysteresis - CONTENT_CLAIM_PX,
+);
+
+/** A web app opened from the home screen, where no browser back swipe exists. */
+function isStandaloneWebApp(): boolean {
+ return (
+ typeof navigator !== 'undefined' &&
+ (navigator as Navigator & {standalone?: boolean}).standalone === true
+ );
+}
+
+/**
+ * Whether a touch starting at client x is in the leading screen-edge band of
+ * a viewport `viewportWidth` wide.
+ */
+function startsInEdgeBand(
+ x: number,
+ direction: 'ltr' | 'rtl',
+ viewportWidth: number,
+): boolean {
+ const band = UIKIT_GESTURES.screenEdgePan.edgeRegion.value;
+ return direction === 'rtl' ? x >= viewportWidth - band : x <= band;
+}
+
+/**
+ * The stack's back swipes: the edge swipe on `containerRef` and the content
+ * swipe on `cardsRef`. Both drive the stack `stackRef` holds (read at each
+ * touch event, so it always sees the latest render). They run while
+ * `isEnabled` (the stack can pop and allows interactive pops).
+ */
+export function useBackSwipes(
+ containerRef: RefObject<HTMLElement | null>,
+ cardsRef: RefObject<HTMLElement | null>,
+ stackRef: RefObject<BackSwipeStack | null>,
+ {isEnabled}: {isEnabled: boolean},
+): void {
+ const swipeRef = useRef<{
+ start: number;
+ top: string;
+ under: string;
+ /** The finger has passed the content swipe's dead zone. */
+ isPastDeadZone: boolean;
+ } | null>(null);
+
+ const onSwipe = useCallback(
+ (recognizer: PanGestureRecognizer, deadZone: number) => {
+ const stack = stackRef.current;
+ const screens = stack?.screens();
+ if (stack == null || screens == null) {
+ return;
+ }
+ const width = stack.width();
+ const direction = stack.direction();
+ switch (recognizer.state) {
+ case 'began': {
+ const start = stack.grab(screens.top, screens.under);
+ swipeRef.current = {start, ...screens, isPastDeadZone: deadZone <= 0};
+ stack.setProgress(start, screens.top, screens.under);
+ break;
+ }
+ case 'changed': {
+ const swipe = swipeRef.current;
+ if (swipe == null) {
+ return;
+ }
+ const along =
+ (direction === 'rtl' ? -1 : 1) * recognizer.translation().x;
+ if (along >= deadZone) {
+ swipe.isPastDeadZone = true;
+ }
+ // In the dead zone the screen holds still. Once past it, back past
+ // where it started, the screen follows with resistance
+ // (progressFromTravel).
+ const travel = swipe.isPastDeadZone ? along - deadZone : 0;
+ stack.setProgress(
+ progressFromTravel(
+ swipe.start,
+ (direction === 'rtl' ? -1 : 1) * travel,
+ width,
+ direction,
+ ),
+ swipe.top,
+ swipe.under,
+ );
+ break;
+ }
+ case 'ended':
+ case 'cancelled': {
+ const swipe = swipeRef.current;
+ swipeRef.current = null;
+ if (swipe == null) {
+ return;
+ }
+ const p = stack.progress();
+ // The pan's own release velocity: Core's tracker reads 0 once the
+ // finger has rested before the lift.
+ const v =
+ recognizer.state === 'ended'
+ ? popVelocity(recognizer.velocity().x, width, direction)
+ : 0;
+ stack.release(
+ swipe.top,
+ swipe.under,
+ recognizer.state === 'ended' && shouldFinishPop(p, v),
+ v,
+ );
+ break;
+ }
+ default:
+ break;
+ }
+ },
+ [stackRef],
+ );
+
+ // Server render and first paint assume a browser tab, where the leading
+ // edge is the browser's own back swipe.
+ const browserOwnsEdge = useSyncExternalStore(
+ subscribeToNothing,
+ () => !isStandaloneWebApp(),
+ () => true,
+ );
+ const edge = useGestureRecognizer(
+ containerRef,
+ () =>
+ new ScreenEdgePanGestureRecognizer({
+ edges: ['leading'],
+ // Published, so app code can relate to it (gestureNamed).
+ name: 'NavigationStack.backSwipe',
+ }),
+ recognizer => onSwipe(recognizer, 0),
+ {isEnabled: isEnabled && !browserOwnsEdge},
+ );
+ // iOS 26's back swipe from anywhere in the content. It waits for the edge
+ // swipe to fail, which a touch outside the edge band does at once.
+ useGestureRecognizer(
+ cardsRef,
+ () => {
+ const recognizer = new PanGestureRecognizer({
+ name: 'NavigationStack.contentBackSwipe',
+ direction: 'right',
+ hysteresis: CONTENT_CLAIM_PX,
+ maximumNumberOfTouches: 1,
+ // A horizontal scroller under the finger that can still scroll
+ // that way keeps the drag (UIKit's scroll views do).
+ scrollEdge: true,
+ shouldReceiveTouch: (_recognizer, touch) => {
+ const direction = stackRef.current?.direction() ?? 'ltr';
+ // It pops toward the trailing edge, read at each touch: the
+ // writing direction can change while the stack is mounted.
+ recognizer.direction = direction === 'rtl' ? 'left' : 'right';
+ const view = containerRef.current?.ownerDocument.defaultView;
+ return !(
+ touch.pointerType === 'touch' &&
+ !isStandaloneWebApp() &&
+ startsInEdgeBand(touch.startX, direction, view?.innerWidth ?? 0)
+ );
+ },
+ });
+ return recognizer.requireToFail(edge);
+ },
+ recognizer => onSwipe(recognizer, CONTENT_DEAD_ZONE_PX),
+ {isEnabled},
+ );
+}
diff --git a/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts b/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts
new file mode 100644
index 0000000000..285ac4017a
--- /dev/null
+++ b/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts
@@ -0,0 +1,1957 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file NavigationStack.interaction.browser.spec.ts
+ * @input The built "Lab/NavigationStack" stories on the harness's phone, real
+ * touch input (Chromium CDP / WebKit's input command) and the interaction
+ * harness
+ * @output Proofs that NavigationStack moves like UINavigationController on
+ * iOS 26.2. A push follows UIKit's push spring (critically damped, 0.3 s,
+ * starting at 8.773 widths/s) to within half a pixel. The card underneath
+ * moves at 0.3 of its speed. The back swipe tracks the finger 1:1 from the
+ * leading edge and from the content. It finishes or springs back by UIKit's
+ * release rule, and a flick finishes from near the edge. A push keeps
+ * advancing every frame through a blocked main thread and does no Layout
+ * or Paint. Reduce Motion cross-fades. The spec also writes storyboards of
+ * a push and of a released swipe.
+ * @position Interaction proof for lab NavigationStack (NavigationStack.tsx,
+ * navigationTransition.ts); shape copied from the harness exemplar,
+ * BottomSheetDetent.interaction.browser.spec.ts
+ */
+
+import {
+ expect,
+ test,
+ type Browser,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ animationStoryboard,
+ blockMainThread,
+ busyWindowProof,
+ castStoryboard,
+ CONTROL_RGB,
+ countBetween,
+ drag,
+ flick,
+ holdAnimations,
+ markElement,
+ openStory,
+ releaseAnimations,
+ sampleCurve,
+ sampleRects,
+ startBusyControl,
+ startScreencast,
+ touchDriver,
+ touchStoryboard,
+ traceRendering,
+ trackMarker,
+ waitForAnimation,
+ waitForRest,
+ withStorybook,
+ writeEvidence,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+/** UIKit's push spring on iOS 26.2: critically damped, response 0.3 s. */
+const OMEGA = (2 * Math.PI) / 0.3;
+/** Its starting speed, widths per second. */
+const PUSH_VELOCITY = 8.773;
+
+interface Stack {
+ driver: TouchDriver;
+ stack: Locator;
+ width: number;
+ left: number;
+ /** The bar title of the screen on top. */
+ topTitle: () => Promise<string | null>;
+}
+
+/**
+ * A page under a real mouse: no touch and no mobile viewport, so script and
+ * CSS both read a fine pointer. (The phone project's own page stays coarse
+ * for CSS whatever script is told.) Close its context when done.
+ */
+async function newFinePage(browser: Browser) {
+ const context = await browser.newContext({
+ hasTouch: false,
+ isMobile: false,
+ viewport: {width: 402, height: 714},
+ });
+ return {context, page: await context.newPage()};
+}
+
+/**
+ * Opens a story. `standalone` makes the page a home-screen web app
+ * (`navigator.standalone`), where no browser back swipe owns the screen
+ * edge, so the stack's own edge swipe runs. `pointer: 'mouse'` needs a page
+ * from `newFinePage`, and fails before any check if the page reads coarse.
+ */
+async function openStack(
+ page: Page,
+ story: 'settings' | 'pushed' | 'carousel' | 'declines-pops' | 'large-title',
+ {
+ standalone = false,
+ pointer = 'touch',
+ }: {standalone?: boolean; pointer?: 'touch' | 'mouse'} = {},
+) {
+ // One touch model: touch behaviour keys on a coarse primary pointer, on
+ // every engine. Under a finger, script reads coarse whatever the engine
+ // emulates (the input is the emulated finger); under a mouse the page
+ // itself is fine (newFinePage).
+ if (pointer === 'touch') {
+ await page.addInitScript(() => {
+ const matchMedia = window.matchMedia.bind(window);
+ window.matchMedia = (query: string) =>
+ query.replace(/\s/g, '') === '(pointer:coarse)'
+ ? matchMedia('(min-width: 0px)')
+ : matchMedia(query);
+ });
+ }
+ if (standalone) {
+ await page.addInitScript(() => {
+ Object.defineProperty(Navigator.prototype, 'standalone', {
+ configurable: true,
+ get: () => true,
+ });
+ });
+ }
+ await openStory(page, storybook(), `lab-navigationstack--${story}`);
+ if (pointer === 'mouse') {
+ expect(
+ await page.evaluate(
+ () =>
+ matchMedia('(pointer: fine)').matches &&
+ !matchMedia('(pointer: coarse)').matches,
+ ),
+ 'a page under a mouse reads a fine pointer (newFinePage)',
+ ).toBe(true);
+ }
+ const driver = await touchDriver(page);
+ const stack = page.getByTestId('navigation-stack');
+ await expect(stack).toBeVisible();
+ const box = await stack.boundingBox();
+ if (box == null) {
+ throw new Error('no stack');
+ }
+ return {
+ driver,
+ stack,
+ width: box.width,
+ left: box.x,
+ topTitle: async () =>
+ page.evaluate(() => {
+ const top = document.querySelector('[data-navigation-top]');
+ const key = top?.getAttribute('data-navigation-screen');
+ const bars = [...document.querySelectorAll('h2')];
+ // The top screen's bar title is the one not inert.
+ const live = bars.find(h => h.closest('[inert]') == null);
+ return key == null ? null : (live?.textContent ?? null);
+ }),
+ } satisfies Stack;
+}
+
+/** A card's presented translateX, px (the animator drives `translate`). */
+const translateX = async (card: Locator) =>
+ card.evaluate(element => {
+ const value = getComputedStyle(element).translate;
+ return value === 'none' ? 0 : parseFloat(value);
+ });
+
+const card = (page: Page, key: string) =>
+ page.locator(`[data-navigation-screen="${key}"]`);
+
+/** One frame of `traceBars`: each screen's card and bar x, the back button. */
+interface BarFrame {
+ t: number;
+ cards: Record<string, number>;
+ bars: Record<string, number>;
+ /** Effective opacity (own times every ancestor's) of the back button. */
+ back: {platter: number; chevron: number} | null;
+ /** Whether an animation drives a card or a bar in this frame. */
+ animating: boolean;
+}
+
+/**
+ * Starts sampling, every frame, each card's and bar's x relative to the
+ * stack and the back button's effective opacities. The returned function
+ * stops and returns them. A layer's x is its computed `translate`: the cards
+ * and bars sit at the stack's leading edge, checked when the trace starts. So
+ * a frame reads no layout. Under load, in a frame that comes a few
+ * milliseconds late, WebKit evaluates two layers that animate on one clock
+ * about a millisecond apart. This holds for boxes and translates alike.
+ * `animating` says which frames an animation drives.
+ */
+async function traceBars(page: Page): Promise<() => Promise<BarFrame[]>> {
+ await page.evaluate(() => {
+ const w = window as unknown as {__bars: unknown[]; __barsStop: boolean};
+ w.__bars = [];
+ w.__barsStop = false;
+ const stack = document.querySelector('[data-testid="navigation-stack"]');
+ const effective = (element: Element) => {
+ let opacity = 1;
+ for (
+ let node: Element | null = element;
+ node != null && node !== document.documentElement;
+ node = node.parentElement
+ ) {
+ opacity *= Number(getComputedStyle(node).opacity);
+ }
+ return opacity;
+ };
+ const translateX = (element: Element) => {
+ const value = getComputedStyle(element).translate;
+ return value === 'none' ? 0 : parseFloat(value);
+ };
+ const read = (selector: string, attribute: string) => {
+ const out: Record<string, number> = {};
+ for (const element of document.querySelectorAll<HTMLElement>(selector)) {
+ const key = element.getAttribute(attribute);
+ if (key != null) {
+ out[key] = translateX(element);
+ }
+ }
+ return out;
+ };
+ // A layer at rest sits at the stack's edge: its box is its translate.
+ const left = stack?.getBoundingClientRect().left ?? 0;
+ for (const element of document.querySelectorAll(
+ '[data-navigation-screen], [data-navigation-bar]',
+ )) {
+ if (element.getAnimations().length > 0) {
+ continue;
+ }
+ const offset =
+ element.getBoundingClientRect().left - left - translateX(element);
+ if (Math.abs(offset) > 0.5) {
+ throw new Error(`a layer sits ${offset} px from the stack's edge`);
+ }
+ }
+ const t0 = performance.now();
+ const tick = () => {
+ const button = document.querySelector('[data-navigation-back]');
+ const chevron = button?.firstElementChild ?? null;
+ w.__bars.push({
+ t: performance.now() - t0,
+ cards: read('[data-navigation-screen]', 'data-navigation-screen'),
+ bars: read('[data-navigation-bar]', 'data-navigation-bar'),
+ back:
+ button == null || chevron == null
+ ? null
+ : {platter: effective(button), chevron: effective(chevron)},
+ animating: [
+ ...document.querySelectorAll(
+ '[data-navigation-screen], [data-navigation-bar]',
+ ),
+ ].some(element =>
+ element.getAnimations().some(a => a.playState === 'running'),
+ ),
+ });
+ if (!w.__barsStop) {
+ requestAnimationFrame(tick);
+ }
+ };
+ requestAnimationFrame(tick);
+ });
+ return async () =>
+ page.evaluate(() => {
+ const w = window as unknown as {__bars: unknown[]; __barsStop: boolean};
+ w.__barsStop = true;
+ return w.__bars;
+ }) as Promise<BarFrame[]>;
+}
+
+/** The first frame at which `key`'s card has left where it started. */
+const firstMove = (frames: BarFrame[], key: string) => {
+ const start = frames.find(f => f.cards[key] != null)?.cards[key];
+ return frames.find(
+ f => f.cards[key] != null && Math.abs(f.cards[key] - (start ?? 0)) > 0.5,
+ );
+};
+
+/**
+ * The time (ms) at which the screens' push or pop spring (critically damped,
+ * 0.3 s, starting at navigation.pushVelocity widths/s) reaches `progress`.
+ * This is the screens' own clock, read from where a card is. So a check keyed
+ * to it holds however late an engine shows the first frame.
+ */
+const screensClock = (progress: number) => {
+ const omega = (2 * Math.PI) / 0.3;
+ const at = (s: number) =>
+ 1 - (1 + (omega - 8.773) * s) * Math.exp(-omega * s);
+ let lo = 0;
+ let hi = 2;
+ for (let i = 0; i < 50; i++) {
+ const mid = (lo + hi) / 2;
+ if (at(mid) < progress) {
+ lo = mid;
+ } else {
+ hi = mid;
+ }
+ }
+ return ((lo + hi) / 2) * 1000;
+};
+
+/** Critically damped from rest: progress of a spring of `response` s. */
+const crit = (response: number, ms: number) => {
+ if (ms <= 0) {
+ return 0;
+ }
+ const u = ((2 * Math.PI) / response) * (ms / 1000);
+ return 1 - (1 + u) * Math.exp(-u);
+};
+
+const rowCenter = async (page: Page, name: string) => {
+ const box = await page.getByRole('button', {name}).first().boundingBox();
+ if (box == null) {
+ throw new Error(`no row ${name}`);
+ }
+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};
+};
+
+test('a push follows UIKit’s push spring, the card underneath at 0.3 of its speed', async ({
+ page,
+}, testInfo) => {
+ const {driver, width} = await openStack(page, 'settings');
+ await driver.tap(await rowCenter(page, 'General'));
+ const top = card(page, 'screen-General');
+ const under = card(page, 'root');
+ await waitForAnimation(top);
+ await holdAnimations(page);
+
+ const times = Array.from({length: 31}, (_, i) => i * 16.667);
+ const samples: {t: number; top: number; under: number; analytic: number}[] =
+ [];
+ for (const t of times) {
+ await page.evaluate(ms => {
+ const held =
+ (window as unknown as {__harnessHeld?: Animation[]}).__harnessHeld ??
+ [];
+ for (const animation of held) {
+ const end = Number(
+ animation.effect?.getComputedTiming().endTime ?? Infinity,
+ );
+ animation.currentTime = Math.min(ms, end - 0.5);
+ }
+ }, t);
+ const s = t / 1000;
+ // x(t) = (x0 + (v0 + ω·x0)·t)·e^(−ωt), from x0 = W at v0 = −8.773 W/s.
+ const analytic =
+ (width + (-PUSH_VELOCITY * width + OMEGA * width) * s) *
+ Math.exp(-OMEGA * s);
+ samples.push({
+ t: +t.toFixed(1),
+ top: await translateX(top),
+ under: await translateX(under),
+ analytic,
+ });
+ }
+ await releaseAnimations(page, {finish: true});
+ await writeEvidence(
+ 'curves/navigationstack-push',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {width, samples},
+ null,
+ 1,
+ ),
+ },
+ testInfo,
+ );
+
+ for (const sample of samples) {
+ expect(
+ Math.abs(sample.top - sample.analytic),
+ JSON.stringify(sample),
+ ).toBeLessThan(0.5);
+ // The card underneath: x = −0.3 W · (1 − p), p = top / W.
+ expect(sample.under).toBeCloseTo(
+ -0.3 * width * (1 - sample.top / width),
+ 0,
+ );
+ }
+ // It starts fast (UIKit's starting velocity, not from rest) and lands.
+ expect(samples[1].top).toBeLessThan(width * 0.92);
+ expect(samples.at(-1)?.top ?? Infinity).toBeLessThan(0.5);
+});
+
+test('a push’s bar: the new bar slides in with its screen, the covered one rides its parallax, the chevron fades in a beat later', async ({
+ page,
+}) => {
+ const {driver, width} = await openStack(page, 'settings');
+ const stop = await traceBars(page);
+ await driver.tap(await rowCenter(page, 'General'));
+ await page.waitForTimeout(900);
+ const frames = await stop();
+ const start = firstMove(frames, 'screen-General');
+ expect(start).toBeDefined();
+ const during = frames.filter(
+ f => f.t >= (start?.t ?? 0) && f.cards['screen-General'] > 0.5,
+ );
+ expect(during.length).toBeGreaterThan(5);
+ for (const f of during) {
+ // UIKit's bar copy is part of its screen: it moves with the card (one
+ // clock and spring). It stays within 1 % of the width, as engines sample
+ // rects.
+ expect(
+ Math.abs(f.bars['screen-General'] - f.cards['screen-General']),
+ JSON.stringify(f),
+ ).toBeLessThan(width * 0.01);
+ expect(
+ Math.abs(f.bars.root - f.cards.root),
+ JSON.stringify(f),
+ ).toBeLessThan(width * 0.01);
+ // The glass platter is there from the first frame.
+ expect(f.back?.platter ?? 0, JSON.stringify(f)).toBeGreaterThan(0.99);
+ }
+ // The chevron (springs.navigationBackButton 0.4 s) starts 60 ms after the
+ // screens start moving (navigation.backChevronPushDelayMs), on their
+ // clock: read it from where the pushed card is.
+ for (const f of during) {
+ const ms = screensClock(1 - f.cards['screen-General'] / width);
+ const expected = crit(0.4, ms - 60);
+ expect(
+ Math.abs((f.back?.chevron ?? 0) - expected),
+ JSON.stringify({ms: Math.round(ms), ...f.back, expected}),
+ ).toBeLessThan(0.1);
+ }
+});
+
+test('the back swipe from the leading edge tracks the finger and pops past half', async ({
+ page,
+}) => {
+ const {driver, width, left, topTitle} = await openStack(page, 'pushed', {
+ standalone: true,
+ });
+ expect(await topTitle()).toBe('About');
+ const top = card(page, 'screen-About');
+ const y = 400;
+ const travel: {finger: number; card: number}[] = [];
+ const script = drag(
+ {x: left + 4, y},
+ {x: left + width * 0.65, y},
+ {durationMs: 600, restMs: 150},
+ );
+ await driver.play(script, {
+ onEvent: async step => {
+ const finger = step.fingers[0]?.x;
+ if (finger != null) {
+ travel.push({finger: finger - (left + 4), card: await translateX(top)});
+ }
+ },
+ });
+ await waitForRest(card(page, 'screen-General'));
+ await expect.poll(topTitle).toBe('General');
+ await expect(top).toHaveCount(0);
+
+ // The edge pan is attached to the whole stack, an element reaching beyond
+ // the edge band. So an in-band touch decides at the shared 10 px claim
+ // distance. Once it has begun, the card is the finger's travel past that
+ // point: 1:1.
+ const tracking = travel.filter(t => t.card > 1 && t.finger < width * 0.6);
+ expect(tracking.length).toBeGreaterThan(5);
+ for (const t of tracking) {
+ expect(Math.abs(t.card - (t.finger - 10))).toBeLessThan(2);
+ }
+});
+
+test('a slow back swipe released short of half springs back', async ({
+ page,
+}) => {
+ const {driver, width, left, topTitle} = await openStack(page, 'pushed', {
+ standalone: true,
+ });
+ const top = card(page, 'screen-About');
+ // A slow approach: little velocity at the lift, so p + 0.35·v stays short.
+ await driver.play(
+ drag(
+ {x: left + 4, y: 400},
+ {x: left + width * 0.32, y: 400},
+ {
+ durationMs: 2000,
+ hz: 60,
+ },
+ ),
+ );
+ await waitForRest(top);
+ expect(await topTitle()).toBe('About');
+ expect(Math.abs(await translateX(top))).toBeLessThan(0.5);
+});
+
+test('moving back before the lift cancels the pop', async ({page}) => {
+ const {driver, width, left, topTitle} = await openStack(page, 'pushed', {
+ standalone: true,
+ });
+ const top = card(page, 'screen-About');
+ const out = [
+ ...drag(
+ {x: left + 4, y: 400},
+ {x: left + width * 0.45, y: 400},
+ {
+ durationMs: 450,
+ },
+ ),
+ ];
+ // Continue the same finger back 40 px before lifting.
+ const lift = out.pop();
+ const last = out[out.length - 1];
+ const x0 = last.fingers[0].x;
+ for (let i = 1; i <= 8; i++) {
+ out.push({t: last.t + i * 16.7, fingers: [{id: 0, x: x0 - i * 5, y: 400}]});
+ }
+ out.push({t: (lift?.t ?? last.t) + 8 * 16.7 + 4, fingers: []});
+ await driver.play(out);
+ await waitForRest(top);
+ expect(await topTitle()).toBe('About');
+});
+
+/**
+ * The pan's release velocity, px/s, by Core's rule, from the moves the page
+ * received (their own timestamps). It is 0.2 times the newest interval's
+ * velocity plus 0.8 times the previous one's. It is 0 when the finger was
+ * still for longer than 40 ms before the lift.
+ */
+function releaseVelocity(
+ moves: readonly {t: number; x: number}[],
+ upAt: number,
+): number {
+ const moved = moves.filter(
+ (move, i) =>
+ i === 0 || (move.x !== moves[i - 1].x && move.t > moves[i - 1].t),
+ );
+ const last = moved[moved.length - 1];
+ if (moved.length < 2 || upAt - last.t > 40) {
+ return 0;
+ }
+ const interval = (i: number) =>
+ (moved[i].x - moved[i - 1].x) / ((moved[i].t - moved[i - 1].t) / 1000);
+ const n = moved.length - 1;
+ return n === 1 ? interval(1) : 0.2 * interval(n) + 0.8 * interval(n - 1);
+}
+
+test('brought back past its start, the screen follows with resistance, then springs back as UIKit’s does', async ({
+ page,
+}) => {
+ // UIKit lab, iOS 26.2 simulator: past its start the screen follows the
+ // finger at 0.71 of its travel. A release there returns it on a damped
+ // spring (ω 16.5 rad/s, ζ 0.81) from the finger's velocity, never past
+ // rest. A real-time touch driver delivers moves when it can, so the
+ // velocity is judged against the moves the page received.
+ const {driver, width, left} = await openStack(page, 'pushed', {
+ standalone: true,
+ });
+ const top = card(page, 'screen-About');
+ const start = {x: left + 4, y: 400};
+ const far = left + width * 0.4;
+ // In the page: each touch move as the page received it, and where the
+ // screen stood after the stack handled it (at the window, bubbling).
+ await page.evaluate(() => {
+ const w = window as unknown as {
+ __moves: {t: number; x: number}[];
+ __pairs: {finger: number; x: number}[];
+ __upAt: number | null;
+ };
+ w.__moves = [];
+ w.__pairs = [];
+ w.__upAt = null;
+ const element = document.querySelector<HTMLElement>(
+ '[data-navigation-screen="screen-About"]',
+ );
+ const read = () => {
+ const x = parseFloat(
+ element == null ? '' : getComputedStyle(element).translate,
+ );
+ return Number.isFinite(x) ? x : 0;
+ };
+ for (const type of ['pointerdown', 'pointermove'] as const) {
+ addEventListener(
+ type,
+ event => {
+ if (event.pointerType === 'touch') {
+ w.__moves.push({t: event.timeStamp, x: event.clientX});
+ }
+ },
+ {capture: true},
+ );
+ }
+ addEventListener(
+ 'pointerup',
+ event => {
+ if (event.pointerType === 'touch') {
+ w.__upAt = event.timeStamp;
+ }
+ },
+ {capture: true},
+ );
+ addEventListener('touchmove', event => {
+ const touch = event.touches[0];
+ if (touch != null) {
+ w.__pairs.push({finger: touch.clientX, x: read()});
+ }
+ });
+ });
+ const reset = () =>
+ page.evaluate(() => {
+ const w = window as unknown as {
+ __moves: unknown[];
+ __pairs: unknown[];
+ __upAt: number | null;
+ };
+ w.__moves = [];
+ w.__pairs = [];
+ w.__upAt = null;
+ });
+ const recorded = () =>
+ page.evaluate(() => {
+ const w = window as unknown as {
+ __moves: {t: number; x: number}[];
+ __pairs: {finger: number; x: number}[];
+ __upAt: number | null;
+ };
+ return {moves: w.__moves, pairs: w.__pairs, upAt: w.__upAt};
+ });
+ // The drag out, without its lift.
+ const out = (to: number, durationMs: number) => {
+ const frames = [...drag(start, {x: to, y: 400}, {durationMs})];
+ frames.pop();
+ return frames;
+ };
+
+ // Where the screen's start is in finger coordinates: the swipe begins
+ // after its threshold, so the screen sits that far behind the finger.
+ // A slow swipe to a quarter, held still, then lifted (it springs back).
+ const near = left + width * 0.25;
+ const hold = out(near, 900);
+ const held = hold[hold.length - 1];
+ for (let i = 1; i <= 8; i++) {
+ hold.push({t: held.t + i * 16.7, fingers: [{id: 0, x: near, y: 400}]});
+ }
+ hold.push({t: held.t + 8 * 16.7 + 4, fingers: []});
+ await driver.play(hold);
+ await waitForRest(top);
+ const calibration = await recorded();
+ expect(calibration.pairs.length, 'moves reached the stack').toBeGreaterThan(
+ 0,
+ );
+ const offset =
+ near - Math.max(...calibration.pairs.map(pair => pair.x)) - start.x;
+ const origin = start.x + offset;
+
+ // The measured path: back past the start at ~310 px/s, lifted 10.7 px of
+ // finger after the screen crossed it.
+ await reset();
+ const frames = out(far, 450);
+ const last = frames[frames.length - 1];
+ const from = last.fingers[0].x;
+ const liftX = origin - 10.7;
+ const steps = Math.ceil((from - liftX) / 5.2);
+ for (let i = 1; i <= steps; i++) {
+ frames.push({
+ t: last.t + i * 16.7,
+ fingers: [{id: 0, x: Math.max(liftX, from - i * 5.2), y: 400}],
+ });
+ }
+ frames.push({t: last.t + steps * 16.7 + 4, fingers: []});
+ await driver.play(frames);
+ // The return, held where it runs and read every 2 ms from its start.
+ const heldAnimations = await holdAnimations(page, top);
+ const returnIndex = await top.evaluate(element =>
+ (
+ (window as unknown as {__harnessHeld?: Animation[]}).__harnessHeld ?? []
+ ).findIndex(animation => {
+ const effect = animation.effect as KeyframeEffect | null;
+ return (
+ effect?.target === element &&
+ effect.pseudoElement == null &&
+ effect
+ .getKeyframes()
+ .some(frame => 'translate' in frame || 'transform' in frame)
+ );
+ }),
+ );
+ const returned = heldAnimations.find(item => item.index === returnIndex);
+ expect(returned, 'the release starts the return').toBeDefined();
+ const times = Array.from(
+ {length: 201},
+ (_, i) => (returned?.offsetMs ?? 0) + i * 2,
+ );
+ const xs = (await sampleCurve(top, times)).map(
+ sample => sample.transform.translateX,
+ );
+ await releaseAnimations(page);
+ const {moves, pairs, upAt} = await recorded();
+
+ // Past its start, the screen followed the finger at 0.71 of its travel.
+ const past = pairs
+ .map(pair => ({d: pair.finger - origin, x: pair.x}))
+ .filter(pair => pair.d < -2);
+ const slope =
+ past.reduce((sum, pair) => sum + pair.d * pair.x, 0) /
+ past.reduce((sum, pair) => sum + pair.d * pair.d, 0);
+ // UIKit's damped spring from where the screen stood at the lift, with the
+ // velocity fitted to the curve (it enters linearly).
+ const omega = (2 * Math.PI) / 0.381;
+ const zeta = 0.81;
+ const damped = omega * Math.sqrt(1 - zeta * zeta);
+ const x0 = xs[0];
+ const at = (i: number) => {
+ const t = (i * 2) / 1000;
+ const decay = Math.exp(-zeta * omega * t);
+ return {
+ rest:
+ decay *
+ (x0 * Math.cos(damped * t) +
+ ((zeta * omega * x0) / damped) * Math.sin(damped * t)),
+ perVelocity: (decay * Math.sin(damped * t)) / damped,
+ };
+ };
+ const v0 =
+ xs.reduce((sum, x, i) => sum + (x - at(i).rest) * at(i).perVelocity, 0) /
+ xs.reduce((sum, _, i) => sum + at(i).perVelocity ** 2, 0);
+ const off = Math.max(
+ ...xs.map((x, i) => Math.abs(x - (at(i).rest + v0 * at(i).perVelocity))),
+ );
+ const expected = releaseVelocity(moves, upAt ?? Infinity);
+ const detail = JSON.stringify({
+ offset,
+ past,
+ slope,
+ x0,
+ v0,
+ expected,
+ off,
+ moves: moves.slice(-6).map(move => [Math.round(move.t), move.x]),
+ upAt,
+ xs: xs.filter((_, i) => i % 10 === 0).map(x => Math.round(x * 10) / 10),
+ });
+ // Present: moves past the start, a lift, and a return from behind rest.
+ expect(past.length, detail).toBeGreaterThanOrEqual(2);
+ expect(upAt, detail).not.toBeNull();
+ expect(x0, detail).toBeLessThan(-2);
+ expect(slope, detail).toBeGreaterThan(0.71 - 0.08);
+ expect(slope, detail).toBeLessThan(0.71 + 0.08);
+ // The return is UIKit's spring to within half a pixel, from the velocity
+ // the received moves give by Core's rule.
+ expect(off, detail).toBeLessThan(0.5);
+ expect(v0 / expected, detail).toBeGreaterThan(0.85);
+ expect(v0 / expected, detail).toBeLessThan(1.15);
+ // Never past rest, and at rest once it ends.
+ expect(Math.max(...xs), detail).toBeLessThan(0.5);
+ await waitForRest(top);
+ expect(Math.abs(await translateX(top))).toBeLessThan(0.5);
+});
+
+test('a fast swipe that rests before the lift springs back: a still finger never flicks', async ({
+ page,
+}) => {
+ // The pan's release velocity reads 0 once the finger has rested, so the
+ // release decides by its travel alone, short of half.
+ const {driver, width, left, topTitle} = await openStack(page, 'pushed', {
+ standalone: true,
+ });
+ const top = card(page, 'screen-About');
+ await driver.play(
+ drag(
+ {x: left + 4, y: 400},
+ {x: left + width * 0.42, y: 400},
+ {
+ durationMs: 400,
+ restMs: 300,
+ },
+ ),
+ );
+ await waitForRest(top);
+ expect(await topTitle()).toBe('About');
+ expect(Math.abs(await translateX(top))).toBeLessThan(0.5);
+});
+
+test('a flick from near the edge finishes the pop', async ({page}) => {
+ const {driver, left, topTitle} = await openStack(page, 'pushed', {
+ standalone: true,
+ });
+ // ~60 px of travel at ~1200 px/s: p + 0.35·v is well past half.
+ await driver.play(flick({x: left + 6, y: 400}, {velocity: {x: 1200, y: 0}}));
+ await waitForRest(card(page, 'screen-General'));
+ await expect.poll(topTitle).toBe('General');
+});
+
+test('in a browser tab the leading screen edge stays the browser’s', async ({
+ page,
+}) => {
+ // Not a home-screen app: a swipe from the edge band is the browser's back
+ // swipe, so the stack neither tracks nor pops.
+ const {driver, width, left, topTitle} = await openStack(page, 'pushed');
+ const top = card(page, 'screen-About');
+ let moved = 0;
+ await driver.play(
+ drag(
+ {x: left + 4, y: 400},
+ {x: left + width * 0.7, y: 400},
+ {
+ durationMs: 400,
+ restMs: 120,
+ },
+ ),
+ {
+ onEvent: async () => {
+ moved = Math.max(moved, Math.abs(await translateX(top)));
+ },
+ },
+ );
+ await page.waitForTimeout(300);
+ expect(moved).toBe(0);
+ expect(await topTitle()).toBe('About');
+});
+
+test('a sideways drag in the content pops (iOS 26’s full-width back swipe)', async ({
+ page,
+}) => {
+ const {driver, width, left, topTitle} = await openStack(page, 'pushed');
+ await driver.play(
+ drag(
+ {x: left + width * 0.3, y: 500},
+ {x: left + width * 0.98, y: 500},
+ {
+ durationMs: 500,
+ restMs: 150,
+ },
+ ),
+ );
+ await waitForRest(card(page, 'screen-General'));
+ await expect.poll(topTitle).toBe('General');
+});
+
+test('a push keeps advancing every frame while the main thread is blocked', async ({
+ page,
+ browserName,
+}, testInfo) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'screencast frame evidence is Chromium-only in Playwright (WebKit: the iOS simulator)',
+ );
+ const {driver} = await openStack(page, 'settings');
+ const top = card(page, 'screen-General');
+ // The compositor's own pace on this machine, from the same screencast.
+ await startBusyControl(page);
+ const cast = await startScreencast(page);
+ await driver.tap(await rowCenter(page, 'General'));
+ // Below the bar, which overlays the screens.
+ await markElement(top, {inset: 60});
+ const [push] = await waitForAnimation(top, {minProgressMs: 16});
+ // The page blocks itself from inside the push, once it has run a frame. A
+ // block from the test's own round trip can start before the marker paints.
+ const block = await blockMainThread(page, 600, {
+ during: top,
+ minProgressMs: 16,
+ });
+ await page.waitForTimeout(150);
+ const castFrames = await cast.stop();
+ const tracked = await trackMarker(page, castFrames);
+ const control = await trackMarker(page, castFrames, {rgb: CONTROL_RGB});
+ const proof = busyWindowProof(
+ tracked,
+ {from: block.from, to: Math.min(block.to, push.to)},
+ // The screencast resolves whole CSS pixels at both ends of the spring's
+ // sub-pixel tail. The last frame can round one pixel away from a tail
+ // frame that is still within a pixel of rest. So "settled" is 2 px.
+ {axis: 'x', settledWithin: 2, control},
+ );
+ await writeEvidence(
+ 'busy-main-thread/navigationstack-push',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {block, push, proof},
+ null,
+ 1,
+ ),
+ },
+ testInfo,
+ );
+ const film = await castStoryboard(page, castFrames, {
+ name: 'navigationstack-push-busy-main-thread',
+ zero: block.from,
+ from: block.from - 40,
+ to: Math.min(block.to, push.to) + 40,
+ columns: 8,
+ cellScale: 0.35,
+ data: t => ({x: tracked.find(f => f.t === t)?.box?.x ?? -1}),
+ });
+ await film.write(testInfo, {block, push});
+ // The harness verdict judges each frame the control moved on (a stall,
+ // the frames that moved, a window with nothing to judge). The test asserts
+ // no absolute frame interval or count here.
+ expect(proof.verdict.failures, proof.summary).toEqual([]);
+});
+
+test('the incoming bar covers the old title while the main thread is blocked', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'screencast frame evidence is Chromium-only in Playwright (WebKit: the iOS simulator)',
+ );
+ const {driver} = await openStack(page, 'settings');
+ // A marker at the trailing end of the root's title: the pushed screen's
+ // opaque bar slides over it on the compositor.
+ await page.locator('[data-navigation-bar="root"] h2').evaluate(title => {
+ const element = title as HTMLElement;
+ element.style.position = 'relative';
+ const chip = document.createElement('div');
+ chip.setAttribute('aria-hidden', 'true');
+ chip.style.cssText =
+ 'position:absolute;top:4px;right:0;width:10px;height:10px;background:rgb(255,0,255);pointer-events:none;';
+ element.append(chip);
+ });
+ const cast = await startScreencast(page);
+ await driver.tap(await rowCenter(page, 'General'));
+ // The page blocks itself from inside the push, once it has run a frame. A
+ // block after a further round trip can land after the bar has already
+ // covered the title.
+ const block = await blockMainThread(page, 900, {
+ during: page.getByTestId('navigation-stack'),
+ minProgressMs: 16,
+ });
+ await page.waitForTimeout(150);
+ const frames = await cast.stop();
+ const tracked = await trackMarker(page, frames);
+ const trace = JSON.stringify(
+ tracked.map(f => [Math.round(f.t - block.from), f.box?.x ?? null]),
+ );
+ const during = tracked.filter(f => f.t > block.from && f.t < block.to - 20);
+ // Seen while blocked, then covered before the block ends.
+ expect(
+ during.some(f => f.box != null),
+ trace,
+ ).toBe(true);
+ expect(during.at(-1)?.box ?? null, trace).toBeNull();
+});
+
+test('under a mouse a drag across the content pops, as a finger’s does', async ({
+ browser,
+}) => {
+ // Gestures attach for every pointer: a mouse drag across the content is
+ // the content swipe, tracked and released as a finger's. The edge swipe
+ // stays a finger's (the screen-edge pan's default).
+ const {context, page} = await newFinePage(browser);
+ try {
+ const {left, width} = await openStack(page, 'pushed', {
+ standalone: true,
+ pointer: 'mouse',
+ });
+ const top = card(page, 'screen-About');
+ await page.mouse.move(left + width * 0.3, 400);
+ await page.mouse.down();
+ await page.mouse.move(left + width * 0.95, 400, {steps: 30});
+ await page.mouse.up();
+ await expect(top).toHaveCount(0);
+ } finally {
+ await context.close();
+ }
+});
+
+test('a finger swipes back on an engine that is not iOS WebKit (one touch model)', async ({
+ page,
+}) => {
+ const {driver, left, width} = await openStack(page, 'pushed');
+ // Neither Playwright engine implements -webkit-touch-callout (iOS WebKit
+ // only): the swipe does not depend on it.
+ expect(
+ await page.evaluate(() => CSS.supports('-webkit-touch-callout', 'none')),
+ ).toBe(false);
+ await driver.play(
+ drag(
+ {x: left + width * 0.3, y: 420},
+ {x: left + width * 0.9, y: 420},
+ {durationMs: 300},
+ ),
+ );
+ await expect(card(page, 'screen-About')).toHaveCount(0);
+});
+
+test.describe('the bars ride with their screens, as UIKit’s', () => {
+ test('a programmatic pop rides the revealed bar in from its parallax and the leaving one out', async ({
+ page,
+ }) => {
+ const {driver, width} = await openStack(page, 'settings');
+ await driver.tap(await rowCenter(page, 'General'));
+ await waitForRest(card(page, 'screen-General'));
+ const stop = await traceBars(page);
+ await page.locator('[data-navigation-back]').click();
+ await page.waitForTimeout(900);
+ const frames = await stop();
+ const moving = frames.filter(
+ f =>
+ f.cards['screen-General'] != null &&
+ f.cards['screen-General'] > 0.5 &&
+ f.cards.root < -0.5,
+ );
+ expect(moving.length).toBeGreaterThan(5);
+ for (const f of moving) {
+ expect(
+ Math.abs(f.bars['screen-General'] - f.cards['screen-General']),
+ JSON.stringify(f),
+ ).toBeLessThan(width * 0.01);
+ expect(
+ Math.abs(f.bars.root - f.cards.root),
+ JSON.stringify(f),
+ ).toBeLessThan(width * 0.01);
+ // The chevron fades out at once on the 0.4 s spring, on the screens'
+ // clock; the platter stays until the screen has left.
+ const ms = screensClock(f.cards['screen-General'] / width);
+ expect(f.back?.platter ?? 0, JSON.stringify(f)).toBeGreaterThan(0.99);
+ expect(
+ Math.abs((f.back?.chevron ?? 0) - (1 - crit(0.4, ms))),
+ JSON.stringify({ms: Math.round(ms), ...f.back}),
+ ).toBeLessThan(0.1);
+ }
+ expect(frames.at(-1)?.back ?? null).toBeNull();
+ });
+
+ test('a back swipe holds the revealed bar still while the top one follows the finger', async ({
+ page,
+ }) => {
+ const {driver, width, left} = await openStack(page, 'pushed');
+ const stop = await traceBars(page);
+ await driver.play(
+ drag(
+ {x: left + width * 0.3, y: 420},
+ {x: left + width * 0.7, y: 420},
+ {durationMs: 1000, restMs: 300},
+ ),
+ );
+ await page.waitForTimeout(1200);
+ const frames = await stop();
+ const swiping = frames.filter(f => (f.cards['screen-About'] ?? 0) > 0.5);
+ expect(swiping.filter(f => !f.animating).length).toBeGreaterThan(10);
+ for (const f of swiping) {
+ // Within a pixel while the finger drives both layers. Through the
+ // release's spring back, the other bar proofs' 1 % of the width. In a
+ // late frame WebKit evaluates two layers on one clock about a
+ // millisecond apart.
+ expect(
+ Math.abs(f.bars['screen-About'] - f.cards['screen-About']),
+ JSON.stringify(f),
+ ).toBeLessThan(f.animating ? width * 0.01 : 1);
+ // UIKit's revealed title stays centred while its screen slides in.
+ expect(
+ Math.abs(f.bars['screen-General']),
+ JSON.stringify(f),
+ ).toBeLessThan(0.5);
+ // The back button does not follow a finger: full opacity throughout.
+ expect(f.back?.chevron ?? 0, JSON.stringify(f)).toBeGreaterThan(0.99);
+ }
+ });
+
+ test('each bar is opaque and stacks over the one it covers', async ({
+ page,
+ }) => {
+ const {driver} = await openStack(page, 'settings');
+ await driver.tap(await rowCenter(page, 'General'));
+ await waitForRest(card(page, 'screen-General'));
+ const bars = await page.evaluate(() =>
+ [...document.querySelectorAll('[data-navigation-bar]')].map(bar => ({
+ key: bar.getAttribute('data-navigation-bar'),
+ // Each layer paints its opaque background on its first child.
+ background: getComputedStyle(bar.firstElementChild ?? bar)
+ .backgroundColor,
+ })),
+ );
+ expect(bars.map(bar => bar.key)).toEqual(['root', 'screen-General']);
+ for (const bar of bars) {
+ // An rgb() colour has no alpha; rgba(…, 0) would let the title show.
+ expect(bar.background, JSON.stringify(bar)).toMatch(/^rgb\(/);
+ }
+ });
+
+ test('the covered bar’s dimming ends above the bar’s hairline', async ({
+ page,
+ }) => {
+ const {driver} = await openStack(page, 'settings');
+ await driver.tap(await rowCenter(page, 'General'));
+ await waitForRest(card(page, 'screen-General'));
+ // Each layer's dimming is its last child; the hairline is the bar's
+ // bottom pixel, which the layers' backgrounds leave uncovered.
+ const layers = await page.evaluate(() =>
+ [...document.querySelectorAll('[data-navigation-bar]')].map(bar => ({
+ key: bar.getAttribute('data-navigation-bar'),
+ bottom: bar.getBoundingClientRect().bottom,
+ dimBottom: bar.lastElementChild?.getBoundingClientRect().bottom ?? NaN,
+ })),
+ );
+ expect(layers.map(layer => layer.key)).toEqual(['root', 'screen-General']);
+ for (const layer of layers) {
+ expect(layer.dimBottom, JSON.stringify(layer)).toBeLessThanOrEqual(
+ layer.bottom - 1 + 0.01,
+ );
+ }
+ });
+});
+
+test.describe('edge cases', () => {
+ test('a keyboard Back returns focus to the row that pushed', async ({
+ browser,
+ }) => {
+ const {context, page} = await newFinePage(browser);
+ try {
+ await openStack(page, 'settings', {pointer: 'mouse'});
+ const general = page.getByRole('button', {name: 'General'}).first();
+ await general.focus();
+ await page.keyboard.press('Enter');
+ await waitForRest(card(page, 'screen-General'));
+ await page.locator('[data-navigation-back]').focus();
+ await page.keyboard.press('Enter');
+ await expect(card(page, 'screen-General')).toHaveCount(0);
+ await waitForRest(card(page, 'root'));
+ // Focus is on the General row itself, not left on the page body.
+ await expect
+ .poll(async () =>
+ page.evaluate(() => {
+ const active = document.activeElement;
+ return active == null || active === document.body
+ ? 'body'
+ : (active
+ .closest('li, button, [role="button"]')
+ ?.textContent?.trim() ?? active.tagName);
+ }),
+ )
+ .toBe('General');
+ } finally {
+ await context.close();
+ }
+ });
+
+ test('a click on a row’s text returns focus to the row after Back', async ({
+ browser,
+ }) => {
+ const {context, page} = await newFinePage(browser);
+ try {
+ await openStack(page, 'settings', {pointer: 'mouse'});
+ // The press lands on the row's label, inside its button.
+ await page
+ .getByRole('button', {name: 'General'})
+ .first()
+ .getByText('General', {exact: true})
+ .click();
+ await waitForRest(card(page, 'screen-General'));
+ await page.locator('[data-navigation-back]').click();
+ await expect(card(page, 'screen-General')).toHaveCount(0);
+ await waitForRest(card(page, 'root'));
+ await expect
+ .poll(async () =>
+ page.evaluate(() => {
+ const active = document.activeElement;
+ return active == null || active === document.body
+ ? 'body'
+ : (active
+ .closest('li, button, [role="button"]')
+ ?.textContent?.trim() ?? active.tagName);
+ }),
+ )
+ .toBe('General');
+ } finally {
+ await context.close();
+ }
+ });
+
+ test('inside the content swipe’s dead zone the screen holds still', async ({
+ page,
+ }) => {
+ const {driver, width, left} = await openStack(page, 'pushed');
+ const top = card(page, 'screen-About');
+ const from = {x: left + width * 0.3, y: 500};
+ // Past the pan's claim, short of the 27 px the content swipe moves at.
+ const frames = [
+ ...drag(from, {x: from.x + 20, y: from.y}, {durationMs: 300}),
+ ];
+ const lift = frames.pop();
+ const held = frames[frames.length - 1];
+ for (let i = 1; i <= 4; i++) {
+ frames.push({
+ t: held.t + i * 16.7,
+ fingers: [{id: 0, x: from.x + 20, y: from.y}],
+ });
+ }
+ // The lift comes after the hold; from there the screen rests again.
+ if (lift != null) {
+ frames.push({...lift, t: held.t + 5 * 16.7});
+ }
+ const xs: number[] = [];
+ await driver.play(frames, {
+ onEvent: async () => {
+ xs.push(await translateX(top));
+ },
+ });
+ await waitForRest(top);
+ expect(xs.length, JSON.stringify(xs)).toBeGreaterThan(5);
+ // Never against the finger: a screen pulled back would read below 0.
+ expect(Math.min(...xs), JSON.stringify(xs)).toBeGreaterThan(-0.5);
+ });
+
+ test('after the writing direction changes, the content swipe pops the new way', async ({
+ page,
+ }) => {
+ const {driver, width, left, topTitle} = await openStack(page, 'pushed');
+ // The stack turns right-to-left while mounted.
+ const stack = page.getByTestId('navigation-stack');
+ await stack.evaluate(element => element.setAttribute('dir', 'rtl'));
+ expect(
+ await stack.evaluate(element => getComputedStyle(element).direction),
+ ).toBe('rtl');
+ await driver.play(
+ drag(
+ {x: left + width * 0.7, y: 500},
+ {x: left + width * 0.02, y: 500},
+ {durationMs: 500, restMs: 150},
+ ),
+ );
+ await waitForRest(card(page, 'screen-General'));
+ await expect.poll(topTitle).toBe('General');
+ });
+
+ test('in a browser tab a mouse drag from the leading edge band still pops', async ({
+ browser,
+ }) => {
+ // Only a finger's swipe from the band is the browser's back swipe.
+ const {context, page} = await newFinePage(browser);
+ try {
+ const {left, width} = await openStack(page, 'pushed', {
+ pointer: 'mouse',
+ });
+ const top = card(page, 'screen-About');
+ await page.mouse.move(left + 4, 400);
+ await page.mouse.down();
+ await page.mouse.move(left + width * 0.95, 400, {steps: 30});
+ await page.mouse.up();
+ await expect(top).toHaveCount(0);
+ } finally {
+ await context.close();
+ }
+ });
+
+ test('after a keyboard push the focused title shows the focus indicator', async ({
+ browser,
+ }) => {
+ const {context, page} = await newFinePage(browser);
+ try {
+ await openStack(page, 'settings', {pointer: 'mouse'});
+ await page.getByRole('button', {name: 'General'}).first().focus();
+ await page.keyboard.press('Enter');
+ await waitForRest(card(page, 'screen-General'));
+ const title = page.locator('[data-navigation-bar="screen-General"] h2');
+ await expect(title).toBeFocused();
+ const ring = await title.evaluate(element => {
+ const style = getComputedStyle(element);
+ return {
+ visible: element.matches(':focus-visible'),
+ outline: style.outlineStyle,
+ width: parseFloat(style.outlineWidth),
+ shadow: style.boxShadow,
+ };
+ });
+ expect(ring.visible).toBe(true);
+ // An outline or a ring shadow: something shows where focus is.
+ expect(
+ (ring.outline !== 'none' && ring.width > 0) || ring.shadow !== 'none',
+ JSON.stringify(ring),
+ ).toBe(true);
+ } finally {
+ await context.close();
+ }
+ });
+
+ test('after a tap push the focused title shows no focus ring', async ({
+ page,
+ }) => {
+ const {driver} = await openStack(page, 'settings');
+ await driver.tap(await rowCenter(page, 'General'));
+ await waitForRest(card(page, 'screen-General'));
+ const title = page.locator('[data-navigation-bar="screen-General"] h2');
+ await expect(title).toBeFocused();
+ // Programmatic focus after pointer input keeps the pointer's modality:
+ // no ring.
+ expect(
+ await title.evaluate(element => element.matches(':focus-visible')),
+ ).toBe(false);
+ });
+
+ test('after a pop the screen underneath keeps its content and its bar', async ({
+ page,
+ }) => {
+ const {driver} = await openStack(page, 'pushed');
+ await page.locator('[data-navigation-back]').click();
+ await waitForRest(card(page, 'screen-General'));
+ await expect(card(page, 'screen-About')).toHaveCount(0);
+ // General is on top; the root lies under it, ready for a back swipe.
+ const root = await card(page, 'root').evaluate(
+ element => getComputedStyle(element).contentVisibility,
+ );
+ expect(root).not.toBe('hidden');
+ await expect(page.locator('[data-navigation-bar="root"]')).toHaveCount(1);
+ void driver;
+ });
+
+ test('a push during a running push slides the new screen in', async ({
+ page,
+ }) => {
+ const {driver, width} = await openStack(page, 'settings');
+ await driver.tap(await rowCenter(page, 'General'));
+ await page.waitForTimeout(80);
+ const stop = await traceBars(page);
+ const about = await page
+ .locator('[data-navigation-screen="screen-General"]')
+ .getByRole('button', {name: 'About'})
+ .boundingBox();
+ if (about == null) {
+ throw new Error('no About row');
+ }
+ await driver.tap({
+ x: about.x + about.width / 2,
+ y: about.y + about.height / 2,
+ });
+ await page.waitForTimeout(700);
+ const frames = await stop();
+ const first = frames.find(f => f.cards['screen-About'] != null);
+ // A lone push starts the card off screen: so does one that interrupts.
+ expect(
+ first?.cards['screen-About'] ?? 0,
+ JSON.stringify(first),
+ ).toBeGreaterThan(width * 0.5);
+ });
+
+ test('a sideways drag on a strip that can still scroll scrolls it instead of popping', async ({
+ page,
+ browserName,
+ }) => {
+ const {driver} = await openStack(page, 'carousel');
+ const strip = page.getByTestId('carousel');
+ await strip.evaluate(element => {
+ element.scrollLeft = 300;
+ });
+ const box = await strip.boundingBox();
+ if (box == null) {
+ throw new Error('no strip');
+ }
+ await driver.play(
+ drag(
+ {x: box.x + 40, y: box.y + box.height / 2},
+ {x: box.x + 200, y: box.y + box.height / 2},
+ {durationMs: 400, restMs: 100},
+ ),
+ );
+ await page.waitForTimeout(800);
+ // Desktop WebKit does not scroll for an emulated touch drag; Chromium
+ // does, so there the strip's own scroll shows too.
+ if (browserName === 'chromium') {
+ expect(await strip.evaluate(element => element.scrollLeft)).toBeLessThan(
+ 250,
+ );
+ }
+ await expect(card(page, 'screen-General')).toHaveCount(1);
+ expect(await translateX(card(page, 'screen-General'))).toBe(0);
+ });
+
+ test('a released swipe the app declines springs back', async ({page}) => {
+ const {driver, width, left} = await openStack(page, 'declines-pops');
+ await driver.play(
+ drag(
+ {x: left + width * 0.2, y: 420},
+ {x: left + width * 0.8, y: 420},
+ {durationMs: 300},
+ ),
+ );
+ await page.waitForTimeout(900);
+ await expect(card(page, 'screen-General')).toHaveCount(1);
+ expect(
+ Math.abs(await translateX(card(page, 'screen-General'))),
+ ).toBeLessThan(0.5);
+ });
+
+ test('a screen contains overscroll only while it overflows', async ({
+ page,
+ }) => {
+ await openStack(page, 'settings');
+ // The screen's scroller (under the overlaid bar) is the card's child.
+ const contain = async () =>
+ card(page, 'root').evaluate(
+ element =>
+ getComputedStyle(element.firstElementChild ?? element)
+ .overscrollBehaviorY,
+ );
+ // Four rows in a full-height stack: nothing to scroll, so a scroll
+ // chains to the page as usual.
+ expect(await contain()).toBe('auto');
+ await page.setViewportSize({width: 400, height: 200});
+ await expect.poll(contain).toBe('contain');
+ });
+});
+
+test('a push does no Layout or Paint per frame', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');
+ await openStack(page, 'settings');
+ const top = card(page, 'screen-General');
+ // A programmatic click: a finger's press would add the row's own press
+ // fade, which is not the push.
+ const row = page.getByRole('button', {name: 'General'}).first();
+ // The story's own first motion leaves its layers promoted for the
+ // animator's linger (half a second after it ends). Demoting one is a style
+ // pass and a Layout of its own. The root bar title's landed about 400 ms
+ // into a push started at once, at the window's edge. Start the push once
+ // none is left.
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => document.querySelectorAll('[style*="will-change"]').length,
+ ),
+ )
+ .toBe(0);
+ let push = {from: 0, to: 0};
+ const trace = await traceRendering(page, async () => {
+ // The page notes the push's own readiness. `started` is the frame after
+ // every animation of the push runs on the compositor. The one-off work
+ // that creates their layers comes before it. `landing` is the last frame
+ // before the first of them ends. A loaded machine moves both.
+ await page.evaluate(() => {
+ const stack = document.querySelector('[data-testid="navigation-stack"]');
+ const epoch = (t: number) => performance.timeOrigin + t;
+ (
+ window as unknown as {
+ pushMotion?: Promise<{started: number; landing: number}>;
+ }
+ ).pushMotion = new Promise(resolve => {
+ const waitForStart = () => {
+ const running = (stack?.getAnimations({subtree: true}) ?? []).filter(
+ animation => animation.playState === 'running',
+ );
+ if (running.length === 0) {
+ requestAnimationFrame(waitForStart);
+ return;
+ }
+ void Promise.all(running.map(animation => animation.ready)).then(() =>
+ requestAnimationFrame(first => {
+ const started = epoch(first);
+ let landing = started;
+ let ended = false;
+ void Promise.race(
+ running.map(animation =>
+ animation.finished.catch(() => undefined),
+ ),
+ ).then(() => {
+ ended = true;
+ });
+ const step = (now: number) => {
+ if (ended) {
+ resolve({started, landing});
+ return;
+ }
+ landing = epoch(now);
+ requestAnimationFrame(step);
+ };
+ requestAnimationFrame(step);
+ }),
+ );
+ };
+ requestAnimationFrame(waitForStart);
+ });
+ });
+ await row.evaluate(element => (element as HTMLElement).click());
+ [push] = await waitForAnimation(top);
+ await waitForRest(top);
+ });
+ const motion = await page.evaluate(
+ () =>
+ (
+ window as unknown as {
+ pushMotion: Promise<{started: number; landing: number}>;
+ }
+ ).pushMotion,
+ );
+ // The motion itself, from its running frames to its landing (focus moves
+ // to the new title after it, and may paint).
+ const from = Math.max(push.from + 80, motion.started);
+ const to = motion.landing;
+ const during = countBetween(trace, from, to);
+ const when = trace.events
+ .filter(e => e.name === 'Layout' || e.name === 'Paint')
+ .map(e => `${e.name}@${Math.round(e.t - push.from)}`);
+ const detail = JSON.stringify({push, motion, during, when});
+ // Present: a window of frames the page rendered.
+ expect(to - from, detail).toBeGreaterThanOrEqual(100);
+ expect(during.PrePaint ?? 0, detail).toBeGreaterThan(0);
+ expect(during.Layout ?? 0, detail).toBe(0);
+ expect(during.Paint ?? 0, detail).toBe(0);
+});
+
+test.describe('with Reduce Motion', () => {
+ test('a push never dims the covered screen', async ({page}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const {driver} = await openStack(page, 'settings');
+ const dimmed = await page.evaluate(() => {
+ const w = window as unknown as {__dim: number[]; __dimStop: boolean};
+ w.__dim = [];
+ w.__dimStop = false;
+ const dim = document.querySelector(
+ '[data-navigation-screen="root"]',
+ )?.lastElementChild;
+ const tick = () => {
+ if (dim != null) {
+ w.__dim.push(Number(getComputedStyle(dim).opacity));
+ }
+ if (!w.__dimStop) {
+ requestAnimationFrame(tick);
+ }
+ };
+ requestAnimationFrame(tick);
+ return dim != null;
+ });
+ expect(dimmed).toBe(true);
+ await driver.tap(await rowCenter(page, 'General'));
+ await page.waitForTimeout(800);
+ const samples = await page.evaluate(() => {
+ const w = window as unknown as {__dim: number[]; __dimStop: boolean};
+ w.__dimStop = true;
+ return w.__dim;
+ });
+ expect(samples.length).toBeGreaterThan(10);
+ // UIKit's cross-fade has no dimming: the 10 % shade belongs to the slide.
+ expect(Math.max(...samples), JSON.stringify(samples)).toBeLessThan(0.01);
+ });
+
+ test('under a mouse a push completes at once', async ({browser}) => {
+ const {context, page} = await newFinePage(browser);
+ try {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ await openStack(page, 'settings', {pointer: 'mouse'});
+ await page.getByRole('button', {name: 'General'}).first().click();
+ const top = card(page, 'screen-General');
+ await expect(top).toHaveCount(1);
+ // A fine pointer changes at once.
+ const first = await top.evaluate(
+ element =>
+ new Promise<{x: string; opacity: number}>(resolve =>
+ requestAnimationFrame(() =>
+ resolve({
+ x: getComputedStyle(element).translate,
+ opacity: Number(getComputedStyle(element).opacity),
+ }),
+ ),
+ ),
+ );
+ expect(first.x === 'none' || parseFloat(first.x) === 0).toBe(true);
+ expect(first.opacity).toBe(1);
+ } finally {
+ await context.close();
+ }
+ });
+
+ test('a push cross-fades in place instead of sliding', async ({page}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const {driver} = await openStack(page, 'settings');
+ await driver.tap(await rowCenter(page, 'General'));
+ const top = card(page, 'screen-General');
+ await waitForAnimation(top);
+ const midway = await top.evaluate(element => ({
+ x: getComputedStyle(element).translate,
+ opacity: Number(getComputedStyle(element).opacity),
+ }));
+ await waitForRest(top);
+ // No travel: the incoming screen is already where it lands, fading in.
+ expect(midway.x === 'none' || parseFloat(midway.x) === 0).toBe(true);
+ expect(midway.opacity).toBeLessThan(1);
+ expect(await translateX(top)).toBe(0);
+ });
+});
+
+test('a large title scrolls under the bar, which then shows the title; scrolling back hides it again', async ({
+ page,
+}) => {
+ await openStack(page, 'large-title');
+ const rootCard = card(page, 'root');
+ const barText = page.locator('[data-navigation-bar="root"] h2');
+ await expect(
+ page.getByRole('heading', {level: 1, name: 'Settings'}),
+ ).toBeVisible();
+ // The title's offset inside its bar, which the rise moves.
+ const read = async () =>
+ barText.evaluate(element => ({
+ opacity: Number(getComputedStyle(element).opacity),
+ top:
+ element.getBoundingClientRect().top -
+ (element.parentElement as HTMLElement).getBoundingClientRect().top,
+ }));
+ const hidden = await read();
+ expect(hidden.opacity).toBe(0);
+
+ // Scrolled under the bar (the scroll itself is the browser's): the bar's
+ // title rises into place as it fades in.
+ await rootCard.evaluate(element =>
+ (element.firstElementChild as HTMLElement).scrollTo({top: 300}),
+ );
+ await expect
+ .poll(async () => (await read()).opacity, {timeout: 3000})
+ .toBe(1);
+ // It rose 15 px into place (navigation.inlineTitleRise).
+ expect(hidden.top - (await read()).top).toBeCloseTo(15, 0);
+ await expect(barText).not.toHaveAttribute('aria-hidden');
+
+ await rootCard.evaluate(element =>
+ (element.firstElementChild as HTMLElement).scrollTo({top: 0}),
+ );
+ await expect
+ .poll(async () => (await read()).opacity, {timeout: 3000})
+ .toBe(0);
+ await expect(barText).toHaveAttribute('aria-hidden', 'true');
+});
+
+test('a pushed large title rides in with its screen', async ({page}) => {
+ const {driver} = await openStack(page, 'large-title');
+ await driver.tap(await rowCenter(page, 'General'));
+ const top = card(page, 'screen-General');
+ await waitForAnimation(top);
+ await waitForRest(top);
+ // The pushed screen here is inline; the root's large title stays with the
+ // root card, under it and to the left.
+ const rootTitle = page.getByRole('heading', {level: 1, name: 'Settings'});
+ const box = await rootTitle.boundingBox();
+ const rootBox = await card(page, 'root').boundingBox();
+ expect(box && rootBox && Math.abs(box.x - rootBox.x)).toBeLessThan(2);
+});
+
+/**
+ * Mean luminance (0–255) of a CSS-px box in each screencast frame, decoded
+ * in a scratch page (like trackMarker).
+ */
+async function boxLuminance(
+ page: Page,
+ frames: Awaited<
+ ReturnType<Awaited<ReturnType<typeof startScreencast>>['stop']>
+ >,
+ box: {x: number; y: number; width: number; height: number},
+): Promise<{t: number; luminance: number}[]> {
+ const scratch = await page.context().newPage();
+ try {
+ const out: {t: number; luminance: number}[] = [];
+ for (let i = 0; i < frames.length; i += 12) {
+ const batch = frames.slice(i, i + 12);
+ const values = await scratch.evaluate(
+ async ({items, rect}) => {
+ const results: number[] = [];
+ for (const item of items) {
+ const blob = await (
+ await fetch(`data:image/${item.format};base64,${item.data}`)
+ ).blob();
+ const bitmap = await createImageBitmap(blob);
+ const scale = bitmap.width / item.viewportWidth;
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext('2d');
+ if (context == null) {
+ throw new Error('no 2d context');
+ }
+ context.drawImage(bitmap, 0, 0);
+ const {data} = context.getImageData(
+ Math.round(rect.x * scale),
+ Math.round(rect.y * scale),
+ Math.max(1, Math.round(rect.width * scale)),
+ Math.max(1, Math.round(rect.height * scale)),
+ );
+ let sum = 0;
+ for (let o = 0; o < data.length; o += 4) {
+ sum +=
+ 0.2126 * data[o] + 0.7152 * data[o + 1] + 0.0722 * data[o + 2];
+ }
+ results.push(sum / (data.length / 4));
+ }
+ return results;
+ },
+ {items: batch, rect: box},
+ );
+ batch.forEach((frame, k) => out.push({t: frame.t, luminance: values[k]}));
+ }
+ return out;
+ } finally {
+ await scratch.close();
+ }
+}
+
+test('a back swipe carries the large titles: each rides its own screen', async ({
+ page,
+}) => {
+ const {driver, width, left} = await openStack(page, 'large-title');
+ await driver.tap(await rowCenter(page, 'General'));
+ const top = card(page, 'screen-General');
+ await waitForAnimation(top);
+ await waitForRest(top);
+ await expect(
+ page.getByRole('heading', {level: 1, name: 'Settings'}),
+ ).toBeVisible();
+ // All four boxes from one task in the page: separate reads let the swipe
+ // move a card between a title's read and its card's.
+ const read = () =>
+ page.evaluate(stackWidth => {
+ const x = (selector: string) =>
+ document.querySelector(selector)?.getBoundingClientRect().x ?? NaN;
+ const topCardX = x('[data-navigation-screen="screen-General"]');
+ return {
+ root:
+ x('[data-navigation-screen="root"] h1') -
+ x('[data-navigation-screen="root"]'),
+ top: x('[data-navigation-bar="screen-General"] h2') - topCardX,
+ p: (Number.isFinite(topCardX) ? topCardX : 0) / stackWidth,
+ };
+ }, width);
+ const rest = await read();
+ const samples: Awaited<ReturnType<typeof read>>[] = [];
+ // A slow sideways drag in the content (iOS 26's back swipe), released
+ // short of half so it springs back.
+ await driver.play(
+ drag(
+ {x: left + 80, y: 420},
+ {x: left + 80 + width * 0.3, y: 420},
+ {durationMs: 1500, hz: 60},
+ ),
+ {
+ onEvent: async () => {
+ samples.push(await read());
+ },
+ },
+ );
+ const moving = samples.filter(sample => sample.p > 0.05);
+ expect(moving.length).toBeGreaterThan(5);
+ for (const sample of moving) {
+ const at = JSON.stringify({sample, rest});
+ // The root's large title rides the root card (its parallax), the pushed
+ // screen's title rides the top card.
+ expect(Math.abs(sample.root - rest.root), at).toBeLessThan(1.5);
+ expect(Math.abs(sample.top - rest.top), at).toBeLessThan(1.5);
+ }
+ await waitForRest(top);
+});
+
+test('under Reduce Motion the bar title cross-fades in place, without the rise', async ({
+ page,
+}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ await openStack(page, 'large-title');
+ const barText = page.locator('[data-navigation-bar="root"] h2');
+ await card(page, 'root').evaluate(element =>
+ (element.firstElementChild as HTMLElement).scrollTo({top: 300}),
+ );
+ const samples = await sampleRects(barText, 900);
+ await expect
+ .poll(async () =>
+ barText.evaluate(e => Number(getComputedStyle(e).opacity)),
+ )
+ .toBe(1);
+ // Where the shown title rests (hidden, it sits 15 px lower for the rise).
+ const rest = await barText.boundingBox();
+ const fading = samples.filter(
+ sample => sample.opacity > 0.05 && sample.opacity < 0.95,
+ );
+ // A fade, not a jump…
+ expect(fading.length, JSON.stringify(samples)).toBeGreaterThan(2);
+ // …in place: every visible frame is already at the resting position.
+ for (const sample of samples.filter(item => item.opacity > 0.05)) {
+ expect(
+ Math.abs((sample.box?.y ?? NaN) - (rest?.y ?? NaN)),
+ JSON.stringify(samples),
+ ).toBeLessThan(0.5);
+ }
+});
+
+/** The bar title's opacity, every frame for `ms`. */
+async function sampleTitleOpacity(page: Page, bar: string, ms: number) {
+ return page.evaluate(
+ ({bar, ms}) =>
+ new Promise<number[]>(resolve => {
+ const samples: number[] = [];
+ const start = performance.now();
+ const tick = () => {
+ const title = document.querySelector(
+ `[data-navigation-bar="${bar}"] h2`,
+ );
+ samples.push(
+ title == null ? NaN : Number(getComputedStyle(title).opacity),
+ );
+ if (performance.now() - start < ms) {
+ requestAnimationFrame(tick);
+ } else {
+ resolve(samples);
+ }
+ };
+ requestAnimationFrame(tick);
+ }),
+ {bar, ms},
+ );
+}
+
+test('popping back to a large title two levels down shows it without the bar title', async ({
+ page,
+}) => {
+ const {driver} = await openStack(page, 'large-title');
+ await driver.tap(await rowCenter(page, 'General'));
+ await waitForRest(card(page, 'screen-General'));
+ await driver.tap(await rowCenter(page, 'About'));
+ await waitForRest(card(page, 'screen-About'));
+ // The root is two levels down now (not rendered); Done returns to it.
+ await driver.tap(await rowCenter(page, 'Done'));
+ const samples = await sampleTitleOpacity(page, 'root', 500);
+ // Its large title never scrolled: the bar's title stays hidden throughout.
+ expect(Math.max(...samples), JSON.stringify(samples)).toBeLessThan(0.05);
+});
+
+test('a large-title screen pushed again starts with its large title, not the bar’s', async ({
+ page,
+}) => {
+ const {driver} = await openStack(page, 'large-title');
+ await driver.tap(await rowCenter(page, 'Display'));
+ await waitForRest(card(page, 'screen-Display'));
+ await card(page, 'screen-Display').evaluate(element =>
+ (element.firstElementChild as HTMLElement).scrollTo({top: 300}),
+ );
+ await expect
+ .poll(() =>
+ page
+ .locator('[data-navigation-bar="screen-Display"] h2')
+ .evaluate(e => Number(getComputedStyle(e).opacity)),
+ )
+ .toBe(1);
+ await page.locator('[data-navigation-back]').last().click();
+ await expect(card(page, 'screen-Display')).toHaveCount(0);
+
+ // Mounted again, the card starts at the top with its large title showing.
+ await driver.tap(await rowCenter(page, 'Display'));
+ const samples = await sampleTitleOpacity(page, 'screen-Display', 400);
+ expect(Math.max(...samples), JSON.stringify(samples)).toBeLessThan(0.05);
+});
+
+test('the bar title’s handover keeps running while the main thread is blocked', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'screencast frame evidence is Chromium-only in Playwright (WebKit: the iOS simulator)',
+ );
+ await openStack(page, 'large-title');
+ const barText = page.locator('[data-navigation-bar="root"] h2');
+ const box = await barText.boundingBox();
+ expect(box).not.toBeNull();
+ await startBusyControl(page);
+ const cast = await startScreencast(page);
+ await card(page, 'root').evaluate(element =>
+ (element.firstElementChild as HTMLElement).scrollTo({top: 300}),
+ );
+ const [fade] = await waitForAnimation(barText, {minProgressMs: 16});
+ const block = await blockMainThread(page, 600, {
+ during: barText,
+ minProgressMs: 16,
+ });
+ await page.waitForTimeout(150);
+ const frames = await cast.stop();
+ // The title's rest place only: it fades in there throughout. A box that
+ // also covers the 15 px it rises from sees the text leave one part as it
+ // enters the other. So its mean can stand still while the title moves.
+ const region = {
+ x: box?.x ?? 0,
+ y: box?.y ?? 0,
+ width: box?.width ?? 0,
+ height: box?.height ?? 0,
+ };
+ const series = await boxLuminance(page, frames, region);
+ const control = await trackMarker(page, frames, {rgb: CONTROL_RGB});
+ const controlX = new Map(control.map(f => [f.t, f.box?.x ?? null]));
+ // The check judges the frames the compositor presented while blocked,
+ // those the control moved on. The title keeps changing (fading in) on each
+ // of them until it is nearly at rest.
+ const end = Math.min(block.to, fade.from + 350);
+ const judged = series.flatMap((item, i) => {
+ const before = series[i - 1];
+ const x = controlX.get(item.t) ?? null;
+ const previousX = before == null ? null : (controlX.get(before.t) ?? null);
+ return before != null &&
+ item.t >= block.from &&
+ item.t <= end &&
+ x != null &&
+ previousX != null &&
+ x !== previousX
+ ? [{t: item.t, step: Math.abs(item.luminance - before.luminance)}]
+ : [];
+ });
+ const detail = JSON.stringify({block, fade, judged});
+ expect(judged.length, detail).toBeGreaterThan(5);
+ const changed = judged.filter(item => item.step > 0.05).length;
+ expect(changed, detail).toBeGreaterThanOrEqual(judged.length - 2);
+});
+
+test('storyboard: a push', {tag: '@storyboard'}, async ({page}, testInfo) => {
+ const {driver, width} = await openStack(page, 'settings');
+ await driver.tap(await rowCenter(page, 'General'));
+ const top = card(page, 'screen-General');
+ await waitForAnimation(top);
+ const viewport = page.viewportSize() ?? {width: 402, height: 714};
+ const {storyboard} = await animationStoryboard(page, {
+ name: 'navigationstack-push',
+ clip: {x: 0, y: 0, width: viewport.width, height: viewport.height},
+ // The spring is at rest by ~0.45 s; the animator holds end states after.
+ times: Array.from({length: 28}, (_, i) => i * 16.667),
+ measure: async () => ({
+ top: await translateX(top),
+ under: await translateX(card(page, 'root')),
+ }),
+ columns: 8,
+ cellScale: 0.35,
+ });
+ await releaseAnimations(page, {finish: true});
+ await storyboard.write(testInfo);
+ const frames = storyboard.frames.map(
+ f => f.data as {top: number; under: number},
+ );
+ expect(frames[0].top).toBeCloseTo(width, 0);
+ expect(
+ frames.every((f, i) => i === 0 || f.top <= frames[i - 1].top + 0.5),
+ JSON.stringify(frames.map(f => Math.round(f.top))),
+ ).toBe(true);
+ expect(frames.at(-1)?.top ?? Infinity).toBeLessThan(1);
+});
+
+test(
+ 'storyboard: a back swipe released past half',
+ {tag: '@storyboard'},
+ async ({page}, testInfo) => {
+ const {driver, width, left, topTitle} = await openStack(page, 'pushed', {
+ standalone: true,
+ });
+ const top = card(page, 'screen-About');
+ const viewport = page.viewportSize() ?? {width: 402, height: 714};
+ const storyboard = await touchStoryboard(
+ page,
+ driver,
+ drag(
+ {x: left + 4, y: 400},
+ {x: left + width * 0.65, y: 400},
+ {
+ durationMs: 300,
+ hz: 30,
+ restMs: 120,
+ },
+ ),
+ {
+ name: 'navigationstack-edge-pop',
+ clip: {x: 0, y: 0, width: viewport.width, height: viewport.height},
+ measure: async () => ({top: await translateX(top)}),
+ columns: 6,
+ cellScale: 0.4,
+ },
+ );
+ await storyboard.write(testInfo);
+ await expect.poll(topTitle).toBe('General');
+ const frames = storyboard.frames.map(f => f.data as {top: number});
+ expect(Math.max(...frames.map(f => f.top))).toBeGreaterThan(width * 0.5);
+ },
+);
diff --git a/packages/lab/src/NavigationStack/index.ts b/packages/lab/src/NavigationStack/index.ts
new file mode 100644
index 0000000000..93507162d3
--- /dev/null
+++ b/packages/lab/src/NavigationStack/index.ts
@@ -0,0 +1,22 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file index.ts
+ * @input Imports from NavigationStack.tsx
+ * @output Re-exports NavigationStack, NavigationScreen, useNavigationStack
+ * and their types
+ * @position Barrel export; consumed by packages/lab/src/index.ts
+ */
+
+export {
+ NavigationScreen,
+ NavigationStack,
+ useNavigationStack,
+} from './NavigationStack';
+export type {
+ NavigationScreenProps,
+ NavigationStackApi,
+ NavigationStackProps,
+} from './NavigationStack';
diff --git a/packages/lab/src/NavigationStack/navigationMotion.ts b/packages/lab/src/NavigationStack/navigationMotion.ts
new file mode 100644
index 0000000000..725bc9e4ee
--- /dev/null
+++ b/packages/lab/src/NavigationStack/navigationMotion.ts
@@ -0,0 +1,105 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file navigationMotion.ts
+ * @input Core's UIKit navigation table and its four navigation springs, from
+ * Core's internal touch entry
+ * @output `navigation` and `springs`: Core's navigation values with the ones
+ * only NavigationStack reads, each with its measurement
+ * @position NavigationStack's motion table. Core's tables keep the values
+ * Core's own components read.
+ */
+
+import {
+ NAVIGATION_BAR_ELEMENTS_SPRING,
+ NAVIGATION_INTERACTIVE_POP_FINISH_SPRING,
+ NAVIGATION_POP_SPRING,
+ NAVIGATION_PUSH_SPRING,
+ navigation as coreNavigation,
+} from '@astryxdesign/core/internal/touch';
+
+export const navigation = {
+ ...coreNavigation,
+ /**
+ * Past its start (a finger brought back beyond where the screen is fully
+ * in place), the interactive pop's top screen resists with UIKit's rubber
+ * band. The band is (1 − 1 ÷ (x·c ÷ d + 1))·d, with this coefficient c and
+ * d the stack's width. The screen follows at c of the finger at its start.
+ * A release there returns on `springs.navigationInteractivePopReturn`. Over
+ * the measured 10.7 pt the band is within 0.2 pt of a straight line.
+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro, a back
+ * swipe scrubbed to ~50 % and brought back past its start at ~310 pt/s,
+ * lifted 10.7 pt of finger after the view crossed its start: fitted
+ * jointly with `springs.navigationInteractivePopReturn` to the view's x
+ * at the lift (−6.89 pt) and after it, Oct 24 2026
+ */
+ interactivePopRubberBand: 0.71,
+ /**
+ * Travel, in px, before the full-width content swipe (iOS 26's back swipe
+ * from anywhere in the content) begins.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, UINavigationController.contentSwipe began after 27–30 pt
+ * of travel for drags at or under 600 pt/s, Oct 23 2026
+ * At 1000 pt/s it began on the first move event (~8 pt), so above some
+ * speed between 600 and 1000 pt/s it begins sooner.
+ */
+ contentPopHysteresis: 27,
+ /**
+ * On a push from the root, the back button's glass platter is there from
+ * the first frame. Its chevron starts fading in (on
+ * `springs.navigationBackButton`) this many ms after the screens start
+ * moving. On a pop to the root the chevron fades out at once on the same
+ * spring and the platter leaves with the screen.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, inline root ↔ inline detail, per 60 Hz frame: the
+ * slide's start fitted with the push spring (rms 0.0015 of the travel);
+ * the chevron image's effective opacity (0.027, 0.27, 0.53, 0.72, 0.84,
+ * 0.91, 0.97 …) fits the 0.4 s spring from 60.8 ms after it within
+ * 0.010; on the pop it starts within a frame of the slide (0.973, 0.825,
+ * 0.642, 0.474 … at 34 ms steps), Oct 24 2026
+ */
+ backChevronPushDelayMs: 60,
+ /**
+ * How far, in px, the bar's title moves on `springs.navigationBarElements`.
+ * It rises as it fades in once a large title has scrolled under the bar.
+ * It sinks as it fades out when the large title comes back.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, real HID drags of a large-title table: the inline title
+ * label's frame y 88.67 → 73.67 on a UIView spring (springDuration 0.6,
+ * bounce 0) fired ~5 pt after the bar collapsed, Oct 24 2026
+ */
+ inlineTitleRise: 15,
+} as const;
+
+export const springs = {
+ navigationPush: NAVIGATION_PUSH_SPRING,
+ navigationPop: NAVIGATION_POP_SPRING,
+ navigationInteractivePopFinish: NAVIGATION_INTERACTIVE_POP_FINISH_SPRING,
+ navigationBarElements: NAVIGATION_BAR_ELEMENTS_SPRING,
+ /**
+ * Interactive pop released past its start (the screen rubber-banded by
+ * `navigation.interactivePopRubberBand`): it returns to rest from the
+ * finger's velocity, overshooting further first.
+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro, the
+ * cancelled scrub's per-frame view x (−6.89 pt at the lift at
+ * −310 pt/s, −14.21 pt 50 ms later, |x| < 0.5 pt from ~0.23 s, no
+ * overshoot past rest). Damped spring
+ * x(t) = e^(−ζωt)(x0 cos ω_d t + (v0 + ζωx0)/ω_d sin ω_d t), v0 the
+ * finger's velocity, x0 from `navigation.interactivePopRubberBand`,
+ * fitted jointly: ω = 16.5 rad/s, ζ = 0.81, with the at-lift value
+ * within 0.8 pt, the peak within 0.6 pt (−13.7 pt at 47 ms), at most
+ * 0.2 pt past rest and |x| < 0.5 pt by 0.27 s; worst frame 1.8 pt,
+ * mid-return, Oct 24 2026
+ */
+ navigationInteractivePopReturn: {response: 0.381, dampingRatio: 0.81},
+ /**
+ * The back button's chevron fading in on a push and out on a pop. An
+ * interactive swipe leaves it at full opacity; it fades once the pop
+ * finishes.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, the chevron's effective opacity per frame; a
+ * critically damped spring of response 0.4 s from rest fits all twelve
+ * 33 ms samples within 0.021, Oct 23 2026
+ */
+ navigationBackButton: {response: 0.4, dampingRatio: 1},
+} as const;
diff --git a/packages/lab/src/NavigationStack/navigationTransition.test.ts b/packages/lab/src/NavigationStack/navigationTransition.test.ts
new file mode 100644
index 0000000000..6bca1a950a
--- /dev/null
+++ b/packages/lab/src/NavigationStack/navigationTransition.test.ts
@@ -0,0 +1,158 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file navigationTransition.test.ts
+ * @input Uses vitest and navigationTransition.ts
+ * @output Unit coverage of NavigationStack's transition math: the layers at
+ * a progress, their velocities, and the release rule against UIKit's
+ * measured releases. It also covers progress from a finger's travel and the
+ * progress a caught screen resumes from.
+ * @position Testing; guards the numbers the component hands the animator
+ */
+
+import {rubberBand} from '@astryxdesign/core/internal/touch';
+import {describe, expect, it} from 'vitest';
+import {navigation} from './navigationMotion';
+import {
+ layersAt,
+ layerVelocities,
+ popVelocity,
+ programmaticVelocity,
+ progressFromScreen,
+ progressFromTravel,
+ shouldFinishPop,
+} from './navigationTransition';
+
+const W = 402;
+
+describe('layersAt', () => {
+ it('covers the screen with the top card at p = 0 (a push has landed)', () => {
+ expect(layersAt(0, W)).toEqual({
+ topX: 0,
+ underX: navigation.parallax * W,
+ dim: 1,
+ });
+ });
+
+ it('has the card under it back at p = 1 (a pop has landed)', () => {
+ const at = layersAt(1, W);
+ expect(at.topX).toBe(W);
+ expect(at.underX).toBeCloseTo(0, 10);
+ expect(at.dim).toBe(0);
+ });
+
+ it('moves the card underneath at 0.3 of the top card’s speed (parallax)', () => {
+ const a = layersAt(0.2, W);
+ const b = layersAt(0.6, W);
+ expect((b.underX - a.underX) / (b.topX - a.topX)).toBeCloseTo(0.3, 10);
+ });
+
+ it('mirrors every x under RTL', () => {
+ const ltr = layersAt(0.4, W);
+ const rtl = layersAt(0.4, W, 'rtl');
+ expect(rtl.topX).toBe(-ltr.topX);
+ expect(rtl.underX).toBe(-ltr.underX);
+ expect(rtl.dim).toBe(ltr.dim);
+ });
+});
+
+describe('layerVelocities', () => {
+ it('is the derivative of layersAt, so one spring keeps the layers together', () => {
+ const dp = 3.2;
+ const h = 1e-6;
+ const a = layersAt(0.5, W);
+ const b = layersAt(0.5 + dp * h, W);
+ const v = layerVelocities(dp, W);
+ expect(v.topX).toBeCloseTo((b.topX - a.topX) / h, 3);
+ expect(v.underX).toBeCloseTo((b.underX - a.underX) / h, 3);
+ expect(v.dim).toBeCloseTo((b.dim - a.dim) / h, 3);
+ });
+});
+
+describe('programmaticVelocity', () => {
+ it('starts the push and the pop at 8.773 widths per second, not from rest', () => {
+ expect(programmaticVelocity('push')).toBe(-navigation.pushVelocity);
+ expect(programmaticVelocity('pop')).toBe(navigation.pushVelocity);
+ // 3527 pt/s on the 402 pt card UIKit was measured on.
+ expect(navigation.pushVelocity * W).toBeCloseTo(3527, -1);
+ });
+});
+
+describe('shouldFinishPop', () => {
+ it.each([
+ // UIKit's own boundary cases (iOS 26.2 decision hook, 61 releases).
+ [0.475, 0, false], // a still finger short of half cancels
+ [0.05, 2.0, true], // a flick of ~2 widths/s from the edge finishes
+ [0.05, 1.28, false], // ~490 pt/s from the edge cancels
+ [0.6, 0, true],
+ [0.6, -0.5, false], // dragged back toward the edge
+ [0.9, -0.5, false], // moving back cancels, however far it went
+ [0.3, 0.6, true],
+ ])('p %f, v %f widths/s → finish %s', (p, v, finish) => {
+ expect(shouldFinishPop(p, v)).toBe(finish);
+ });
+});
+
+describe('progressFromTravel', () => {
+ it('tracks the finger 1:1 as a share of the width', () => {
+ expect(progressFromTravel(0, W / 4, W)).toBeCloseTo(0.25, 10);
+ });
+
+ it('continues from the progress a grabbed transition had', () => {
+ expect(progressFromTravel(0.4, W / 10, W)).toBeCloseTo(0.5, 10);
+ });
+
+ it('never passes the far edge', () => {
+ expect(progressFromTravel(0.9, W, W)).toBe(1);
+ });
+
+ it('back past the start, resists with UIKit’s rubber band', () => {
+ const c = navigation.interactivePopRubberBand;
+ expect(progressFromTravel(0, -50, W)).toBeCloseTo(
+ rubberBand(-50, W, c) / W,
+ 10,
+ );
+ expect(progressFromTravel(0.05, -W * 0.1, W)).toBeCloseTo(
+ rubberBand(-W * 0.05, W, c) / W,
+ 10,
+ );
+ // At the start it follows at the coefficient's share of the finger.
+ expect(progressFromTravel(0, -0.01, W) * W).toBeCloseTo(-0.01 * c, 5);
+ });
+
+ it('reads leftward travel as a pop under RTL', () => {
+ expect(progressFromTravel(0, -W / 2, W, 'rtl')).toBeCloseTo(0.5, 10);
+ });
+});
+
+describe('progressFromScreen', () => {
+ it.each([
+ [80, 'ltr'],
+ [-12, 'ltr'],
+ [-80, 'rtl'],
+ [12, 'rtl'],
+ ] as const)(
+ 'a screen caught at x %f (%s) resumes where it shows',
+ (x, direction) => {
+ const p = progressFromScreen(x, W, direction);
+ const sign = direction === 'rtl' ? -1 : 1;
+ expect(progressFromTravel(p, 0, W, direction) * W * sign).toBeCloseTo(
+ x,
+ 8,
+ );
+ },
+ );
+
+ it('keeps the side of the start: caught past it, it stays past it', () => {
+ expect(progressFromScreen(-12, W)).toBeLessThan(0);
+ expect(progressFromScreen(12, W, 'rtl')).toBeLessThan(0);
+ });
+});
+
+describe('popVelocity', () => {
+ it('converts px/s to widths per second toward the pop', () => {
+ expect(popVelocity(804, W)).toBeCloseTo(2, 10);
+ expect(popVelocity(-804, W, 'rtl')).toBeCloseTo(2, 10);
+ expect(popVelocity(100, 0)).toBe(0);
+ });
+});
diff --git a/packages/lab/src/NavigationStack/navigationTransition.ts b/packages/lab/src/NavigationStack/navigationTransition.ts
new file mode 100644
index 0000000000..2cc1ad30c0
--- /dev/null
+++ b/packages/lab/src/NavigationStack/navigationTransition.ts
@@ -0,0 +1,175 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file navigationTransition.ts
+ * @input The navigation table (navigationMotion.ts) and Core's rubber band
+ * (its internal touch entry)
+ * @output Pure math for NavigationStack's push/pop transition: the layers'
+ * values at a progress (`layersAt`) and their velocities for a progress
+ * velocity (`layerVelocities`). It also gives the interactive pop's release
+ * rule (`shouldFinishPop`), progress from a finger's travel
+ * (`progressFromTravel`) and the progress a caught screen resumes from
+ * (`progressFromScreen`).
+ * @position Lab NavigationStack internals; no DOM, no React. The component
+ * hands these numbers to the compositor animator.
+ *
+ * One number describes a transition: progress `p`, the share of the width
+ * the top card has uncovered. `p = 0`: the top card covers the screen (a
+ * push has landed). `p = 1`: it has left and the card under it is back (a
+ * pop has landed). A push runs p 1 → 0 and a pop runs p 0 → 1. An
+ * interactive pop scrubs p with the finger (UIKit: `percentComplete` =
+ * translation / width).
+ *
+ * The layers, as UIKit moves them on iOS 26.2 (measured):
+ * - top card: x = p · W;
+ * - card under it: x = parallax · W · (1 − p), so from −0.3 W to 0;
+ * - dimming over the card under it: opacity 1 − p (black at 10 %);
+ * - bars: each moves with its screen's card. Under a finger, the revealed
+ * bar holds still.
+ *
+ * Every layer is linear in p, so one spring run on all of them with
+ * velocities scaled the same way keeps them on one trajectory.
+ *
+ * SYNC: When modified, update navigationTransition.test.ts.
+ */
+
+import {rubberBand, rubberBandInverse} from '@astryxdesign/core/internal/touch';
+
+import {navigation} from './navigationMotion';
+
+export interface TransitionLayers {
+ /** The top card's translateX, px. */
+ readonly topX: number;
+ /** The covered card's translateX, px. */
+ readonly underX: number;
+ /** The dimming's opacity over the covered card, 0–1. */
+ readonly dim: number;
+}
+
+const clamp01 = (value: number) => Math.min(1, Math.max(0, value));
+
+/**
+ * The layers at progress `p` for a container `width` px wide. `direction`
+ * is the writing direction: under RTL cards enter from the left, so every x
+ * flips.
+ */
+export function layersAt(
+ p: number,
+ width: number,
+ direction: 'ltr' | 'rtl' = 'ltr',
+): TransitionLayers {
+ const sign = direction === 'rtl' ? -1 : 1;
+ return {
+ topX: sign * p * width,
+ underX: sign * navigation.parallax * width * (1 - p),
+ dim: clamp01(1 - p),
+ };
+}
+
+/**
+ * The layers' velocities (px/s and 1/s) when progress moves at `dp` per
+ * second. They use the same scaling as `layersAt`, so a spring started with
+ * these keeps every layer on the progress curve.
+ */
+export function layerVelocities(
+ dp: number,
+ width: number,
+ direction: 'ltr' | 'rtl' = 'ltr',
+): TransitionLayers {
+ const sign = direction === 'rtl' ? -1 : 1;
+ return {
+ topX: sign * dp * width,
+ underX: -sign * navigation.parallax * width * dp,
+ dim: -dp,
+ };
+}
+
+/**
+ * Progress of the push and pop springs' starting velocity: they do not start
+ * from rest (8.773 widths per second on iOS 26.2). Negative for a push
+ * (p heads to 0), positive for a pop.
+ */
+export function programmaticVelocity(kind: 'push' | 'pop'): number {
+ return kind === 'push' ? -navigation.pushVelocity : navigation.pushVelocity;
+}
+
+/**
+ * Progress from a finger's horizontal travel since the pop began, px, added
+ * to the progress the cards had when it began. A pop grabbed mid-flight
+ * continues from where it is. At most 1. Below 0 (the finger brought back
+ * past where the screen is fully in place) it resists with UIKit's rubber
+ * band. The release springs it back.
+ */
+export function progressFromTravel(
+ startProgress: number,
+ travelX: number,
+ width: number,
+ direction: 'ltr' | 'rtl' = 'ltr',
+): number {
+ if (width <= 0) {
+ return clamp01(startProgress);
+ }
+ const sign = direction === 'rtl' ? -1 : 1;
+ const p = startProgress + (sign * travelX) / width;
+ // Past the start the screen resists as UIKit's does; never past the far
+ // edge.
+ return p < 0
+ ? rubberBand(p * width, width, navigation.interactivePopRubberBand) / width
+ : Math.min(1, p);
+}
+
+/**
+ * The progress a finger resumes from when it catches the top screen at
+ * translateX `x`, px. It is the progress `progressFromTravel` shows there, so
+ * the screen does not jump. Past the start it undoes the rubber band.
+ */
+export function progressFromScreen(
+ x: number,
+ width: number,
+ direction: 'ltr' | 'rtl' = 'ltr',
+): number {
+ if (width <= 0) {
+ return 0;
+ }
+ const shown = (direction === 'rtl' ? -x : x) / width;
+ return shown < 0
+ ? rubberBandInverse(
+ shown * width,
+ width,
+ navigation.interactivePopRubberBand,
+ ) / width
+ : Math.min(1, shown);
+}
+
+/**
+ * The interactive pop's release rule (iOS 26.2, 58 of 61 releases). The pop
+ * finishes when progress plus 0.35 s of the release velocity, in widths per
+ * second, passes half the width. Otherwise it cancels. A still finger at
+ * 0.475 cancels; at 0.05 a flick needs about 2 widths per second. A release
+ * moving back toward the start cancels, whatever the travel so far.
+ */
+export function shouldFinishPop(
+ progress: number,
+ velocityWidthsPerSecond: number,
+): boolean {
+ if (velocityWidthsPerSecond < 0) {
+ return false;
+ }
+ return (
+ progress +
+ navigation.interactivePopFinishProjection * velocityWidthsPerSecond >
+ navigation.interactivePopFinishThreshold
+ );
+}
+
+/** A finger's horizontal velocity, px/s, in widths per second toward a pop. */
+export function popVelocity(
+ velocityX: number,
+ width: number,
+ direction: 'ltr' | 'rtl' = 'ltr',
+): number {
+ if (width <= 0) {
+ return 0;
+ }
+ return ((direction === 'rtl' ? -1 : 1) * velocityX) / width;
+}
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index 201a394c14..27dc575c75 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -328,6 +328,17 @@ export {
type DiffViewerSide,
} from './DiffViewer';
+// NavigationStack: push/pop drill-down navigation with UIKit's transitions
+// and back swipes.
+export {
+ NavigationScreen,
+ NavigationStack,
+ useNavigationStack,
+ type NavigationScreenProps,
+ type NavigationStackApi,
+ type NavigationStackProps,
+} from './NavigationStack';
+
// RichTextEditor (RFC meta/astryx#3899) moved out of @astryxdesign/lab into
// its own package, @astryxdesign/richtext. Import it from there:
// import {RichTextEditor, RichTextView} from '@astryxdesign/richtext';