diff --git a/packages/lab/src/NavigationStack/NavigationStack.test.tsx b/packages/lab/src/NavigationStack/NavigationStack.test.tsx index eae6a99239ee8..b000ff97c2e6d 100644 --- a/packages/lab/src/NavigationStack/NavigationStack.test.tsx +++ b/packages/lab/src/NavigationStack/NavigationStack.test.tsx @@ -14,7 +14,7 @@ */ import {describe, expect, it} from 'vitest'; -import {useState, type ReactNode} from 'react'; +import {Activity, useEffect, useState, type ReactNode} from 'react'; import {act, fireEvent, render, screen, waitFor} from '@testing-library/react'; import {List, ListItem} from '@astryxdesign/core/List'; import { @@ -148,6 +148,118 @@ describe('NavigationStack', () => { expect(screenCard('Settings')).not.toHaveAttribute('inert'); }); + describe('after the platform animated a history traversal', () => { + // An app that keeps its path in the history: a traversal (Safari's edge + // swipe, an iOS Home Screen app's back gesture) sets the path it reaches. + function HistoryHarness() { + const [path, setPath] = useState(['General']); + useEffect(() => { + const onPopState = (event: PopStateEvent) => + setPath((event.state as {path: string[]}).path); + window.addEventListener('popstate', onPopState); + return () => window.removeEventListener('popstate', onPopState); + }, []); + return ( + + + + } + path={path} + onPathChange={setPath} + getKey={entry => entry} + renderScreen={entry => ( + + + + )} + /> + ); + } + + const traverse = (path: string[], hasUAVisualTransition: boolean) => { + const event = new PopStateEvent('popstate', {state: {path}}); + Object.defineProperty(event, 'hasUAVisualTransition', { + value: hasUAVisualTransition, + }); + act(() => { + window.dispatchEvent(event); + }); + }; + + it('applies a platform-animated back at once: the popped screen leaves with no slide', () => { + render(); + traverse([], true); + expect(screen.queryByText('General content')).toBeNull(); + expect(screenCard('Settings')).not.toHaveAttribute('inert'); + }); + + it('still slides a back the platform did not animate', () => { + render(); + traverse([], false); + expect(screen.getByText('General content')).toBeInTheDocument(); + expect(screenCard('General')).toHaveAttribute('inert'); + }); + + it('applies a platform-animated forward at once: the pushed screen is on top with no slide', () => { + render(); + traverse([], true); + traverse(['General'], true); + expect(screenCard('General')).toHaveAttribute('data-navigation-top'); + expect(document.activeElement).toBe( + screen.getByRole('heading', {name: 'General'}), + ); + }); + + it('still slides the next push when a platform-animated traversal hides the stack before the mark clears', () => { + let showStack: () => void = () => {}; + function HiddenHarness() { + const [isVisible, setIsVisible] = useState(true); + const [path, setPath] = useState([]); + showStack = () => setIsVisible(true); + useEffect(() => { + // The traversal goes to a route that hides the stack, without + // changing the stack's own path. + const onPopState = () => setIsVisible(false); + window.addEventListener('popstate', onPopState); + return () => window.removeEventListener('popstate', onPopState); + }, []); + return ( + + + + + } + path={path} + onPathChange={setPath} + getKey={entry => entry} + renderScreen={entry => ( + + + + )} + /> + + ); + } + render(); + traverse([], true); + act(() => showStack()); + + fireEvent.click(screen.getByRole('button', {name: 'General'})); + + // A slid push moves focus to the new title once it settles, not at once. + expect(document.activeElement).not.toBe( + screen.getByRole('heading', {name: 'General'}), + ); + }); + }); + it('moves focus to the new title after a push, and back to the pushing control after the pop', async () => { render(); const general = screen.getByRole('button', {name: 'General'}); diff --git a/packages/lab/src/NavigationStack/NavigationStack.tsx b/packages/lab/src/NavigationStack/NavigationStack.tsx index ca03fb6881e4f..0a82326925244 100644 --- a/packages/lab/src/NavigationStack/NavigationStack.tsx +++ b/packages/lab/src/NavigationStack/NavigationStack.tsx @@ -814,13 +814,75 @@ function isDispatchingInput( return event instanceof view.Event && INPUT_EVENT_TYPES.has(event.type); } +/** + * Whether the browser has just animated a history traversal itself, such as + * Safari's edge swipe. The browser says so with `hasUAVisualTransition` on + * the Navigation API's `navigate` event and on `popstate`. The mark lasts two + * frames, long enough for the app to commit the path change the traversal + * causes. `take` reads the mark and clears it, so it applies to one + * transition only. `attach` listens on an element's window and returns the + * removal. + */ +function usePlatformAnimatedTraversal(): { + attach: (element: Element) => () => void; + take: () => boolean; +} { + const markRef = useRef(false); + return useMemo( + () => ({ + attach: (element: Element) => { + const view = element.ownerDocument.defaultView; + if (view == null) { + return () => {}; + } + let frame = 0; + const mark = (event: Event) => { + if (Reflect.get(event, 'hasUAVisualTransition') !== true) { + return; + } + markRef.current = true; + view.cancelAnimationFrame(frame); + frame = view.requestAnimationFrame(() => { + frame = view.requestAnimationFrame(() => { + markRef.current = false; + }); + }); + }; + // Capture runs first at the window, before an app's own popstate + // listener commits the path change. + view.addEventListener('popstate', mark, {capture: true}); + const historyNavigation: unknown = Reflect.get(view, 'navigation'); + const navigationTarget = + historyNavigation instanceof view.EventTarget + ? historyNavigation + : null; + navigationTarget?.addEventListener('navigate', mark); + return () => { + view.cancelAnimationFrame(frame); + // The frame that clears the mark does not run, so clear it here. + markRef.current = false; + view.removeEventListener('popstate', mark, {capture: true}); + navigationTarget?.removeEventListener('navigate', mark); + }; + }, + take: () => { + const isMarked = markRef.current; + markRef.current = false; + return isMarked; + }, + }), + [], + ); +} + /** * 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. + * whenever the path gains or loses its top entry, except after a history + * traversal the browser has animated itself. * * 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 @@ -881,6 +943,7 @@ export function NavigationStack({ const t = useTranslator(); const containerRef = useRef(null); const cardsRef = useRef(null); + const platformTraversal = usePlatformAnimatedTraversal(); const [registry] = useState(() => new Map()); // The last input decides whether a moved focus shows its ring. const {ref: trackModality, readModality} = useInteractionModalityTracking(); @@ -888,12 +951,15 @@ export function NavigationStack({ (element: HTMLDivElement | null) => { containerRef.current = element; const release = trackModality(element); + const detachTraversal = + element == null ? null : platformTraversal.attach(element); return () => { release?.(); + detachTraversal?.(); containerRef.current = null; }; }, - [trackModality], + [trackModality, platformTraversal], ); // 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. @@ -1470,6 +1536,29 @@ export function NavigationStack({ const release = releaseRef.current; releaseRef.current = null; pendingFocusRef.current = null; + // The platform already animated this traversal: the stack applies it at + // once, so the screen does not move twice. + if (release == null && platformTraversal.take()) { + runningRef.current = {id, done: true}; + 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) { + settle(under, 'covered'); + } + settle(top, 'top'); + focusAfter('push', top); + } + backControl.animator.set({opacity: 1}); + backChevron.animator.set({opacity: 1}); + return; + } const at = performance.now(); let promise: Promise; if (transition.kind === 'push') { @@ -1553,6 +1642,7 @@ export function NavigationStack({ view.transition.id, animateProgress, focusAfter, + platformTraversal, layersOf, readClearBars, setProgress,