Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 113 additions & 1 deletion packages/lab/src/NavigationStack/NavigationStack.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<string[]>(['General']);
useEffect(() => {
const onPopState = (event: PopStateEvent) =>
setPath((event.state as {path: string[]}).path);
window.addEventListener('popstate', onPopState);
return () => window.removeEventListener('popstate', onPopState);
}, []);
return (
<NavigationStack
label="Settings"
root={
<NavigationScreen title="Settings">
<Root />
</NavigationScreen>
}
path={path}
onPathChange={setPath}
getKey={entry => entry}
renderScreen={entry => (
<NavigationScreen title={entry}>
<Detail entry={entry} />
</NavigationScreen>
)}
/>
);
}

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(<HistoryHarness />);
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(<HistoryHarness />);
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(<HistoryHarness />);
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<string[]>([]);
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 (
<Activity mode={isVisible ? 'visible' : 'hidden'}>
<NavigationStack
label="Settings"
root={
<NavigationScreen title="Settings">
<Root />
</NavigationScreen>
}
path={path}
onPathChange={setPath}
getKey={entry => entry}
renderScreen={entry => (
<NavigationScreen title={entry}>
<Detail entry={entry} />
</NavigationScreen>
)}
/>
</Activity>
);
}
render(<HiddenHarness />);
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(<Harness />);
const general = screen.getByRole('button', {name: 'General'});
Expand Down
94 changes: 92 additions & 2 deletions packages/lab/src/NavigationStack/NavigationStack.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
};
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
},
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
Expand Down Expand Up @@ -881,19 +943,23 @@ export function NavigationStack<T>({
const t = useTranslator();
const containerRef = useRef<HTMLDivElement | null>(null);
const cardsRef = useRef<HTMLDivElement>(null);
const platformTraversal = usePlatformAnimatedTraversal();
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);
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.
Expand Down Expand Up @@ -1470,6 +1536,29 @@ export function NavigationStack<T>({
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()) {
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
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<boolean>;
if (transition.kind === 'push') {
Expand Down Expand Up @@ -1553,6 +1642,7 @@ export function NavigationStack<T>({
view.transition.id,
animateProgress,
focusAfter,
platformTraversal,
layersOf,
readClearBars,
setProgress,
Expand Down