Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions apps/sandbox/scripts/next-export-routes.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"/pages/example-cards/",
"/pages/example/",
"/pages/gothic-palette/",
"/pages/history-back-probe/",
"/pages/layout-dsl/",
"/pages/list-reorder-cases/",
"/pages/markdown-perf/",
Expand Down
175 changes: 175 additions & 0 deletions apps/sandbox/src/app/(raw)/pages/history-back-probe/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

'use client';

/**
* @file page.tsx
* @input A finger on a phone: the buttons that push two history entries and
* go back, and the platform's own back gesture (Safari's edge swipe, an
* iOS Home Screen app's edge swipe)
* @output A bare page that logs, on screen, each popstate and Navigation API
* navigate event with its hasUAVisualTransition, and the display mode the
* page runs in. Below the log, a NavigationStack pushes one history entry
* per push and pops when the history goes back, so the platform's back
* swipe has history to run on
* @position A raw page, with no sandbox chrome, for checking on a real phone
* whether the platform animated a history back (NavigationStack skips its
* own pop animation after one)
*/

import {useEffect, useState} from 'react';
import {Button} from '@astryxdesign/core/Button';
import {HStack, VStack} from '@astryxdesign/core/Layout';
import {List, ListItem} from '@astryxdesign/core/List';
import {
NavigationScreen,
NavigationStack,
useNavigationStack,
} from '@astryxdesign/lab';
import {Heading, Text} from '@astryxdesign/core/Text';

interface LogEntry {
time: string;
event: string;
detail: string;
}

/** The Navigation API's navigate event fields this page reads. */
interface NavigateEventLike extends Event {
navigationType?: string;
hasUAVisualTransition?: boolean;
destination?: {url: string};
}

function now(): string {
return new Date().toISOString().slice(11, 23);
}

const ROWS = ['General', 'About', 'Storage'];

function Rows() {
const nav = useNavigationStack<string>();
return (
<List>
{ROWS.map(row => (
<ListItem key={row} label={row} onClick={() => nav.push(row)} />
))}
</List>
);
}

/**
* A NavigationStack whose every push adds a history entry, and whose path
* follows the history back and forward.
*/
function HistoryStack() {
const [path, setPath] = useState<string[]>([]);
useEffect(() => {
const onPopState = (event: PopStateEvent) => {
const state = event.state as {path?: string[]} | null;
setPath(state?.path ?? []);
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
};
window.addEventListener('popstate', onPopState);
return () => window.removeEventListener('popstate', onPopState);
}, []);
return (
<div style={{height: 420}}>
<NavigationStack
label="Probe"
root={
<NavigationScreen title="Probe">
<Rows />
</NavigationScreen>
}
path={path}
onPathChange={(next: string[]) => {
if (next.length > path.length) {
history.pushState({path: next}, '', `?depth=${next.length}`);
setPath(next);
} else {
history.go(next.length - path.length);
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
}
}}
getKey={(entry: string) => entry}
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
renderScreen={(entry: string) => (
<NavigationScreen title={entry}>
<Rows />
</NavigationScreen>
)}
data-testid="navigation-stack"
/>
</div>
);
}

export default function HistoryBackProbePage() {
const [log, setLog] = useState<LogEntry[]>([]);
const [mode, setMode] = useState('');

useEffect(() => {
const add = (event: string, detail: string) =>
setLog(current =>
[{time: now(), event, detail}, ...current].slice(0, 40),
);
const standalone =
(navigator as Navigator & {standalone?: boolean}).standalone === true;
setMode(
`standalone=${standalone} display-mode:standalone=${matchMedia('(display-mode: standalone)').matches} ` +
`navigation=${'navigation' in window} ${navigator.userAgent}`,
);
const onPopState = (event: PopStateEvent) =>
add(
'popstate',
`hasUAVisualTransition=${String((event as PopStateEvent & {hasUAVisualTransition?: boolean}).hasUAVisualTransition)} ` +
`state=${JSON.stringify(event.state)} url=${location.search || '/'}`,
);
window.addEventListener('popstate', onPopState);
const navigation = (window as Window & {navigation?: EventTarget})
.navigation;
const onNavigate = (event: Event) => {
const navigate = event as NavigateEventLike;
add(
'navigate',
`type=${navigate.navigationType} hasUAVisualTransition=${String(navigate.hasUAVisualTransition)} ` +
`to=${navigate.destination?.url.split('?')[1] ?? '/'}`,
);
};
navigation?.addEventListener('navigate', onNavigate);
return () => {
window.removeEventListener('popstate', onPopState);
navigation?.removeEventListener('navigate', onNavigate);
};
}, []);

const pushTwo = () => {
history.pushState({step: 1}, '', '?step=1');
history.pushState({step: 2}, '', '?step=2');
setLog(current => [
{time: now(), event: 'pushState', detail: 'step=1, step=2'},
...current,
]);
};

return (
<VStack gap={3} padding={4}>
<Heading level={1}>History back probe</Heading>
<Text color="secondary" data-testid="probe-mode">
{mode}
</Text>
<HStack gap={2}>
<Button label="Push two entries" onClick={pushTwo} />
<Button label="history.back()" onClick={() => history.back()} />
</HStack>
<List data-testid="probe-log">
{log.map((entry, index) => (
<ListItem
key={`${entry.time}-${index}`}
label={`${entry.event} ${entry.time}`}
description={entry.detail}
/>
))}
</List>
<HistoryStack />
</VStack>
);
}
68 changes: 67 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 {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 @@ -138,6 +138,72 @@ 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('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
82 changes: 82 additions & 0 deletions packages/lab/src/NavigationStack/NavigationStack.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@ import {
createContext,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type ReactElement,
type ReactNode,
type RefObject,
type SyntheticEvent,
} from 'react';
import * as stylex from '@stylexjs/stylex';
Expand Down Expand Up @@ -763,6 +765,61 @@ function writingDirection(element: HTMLElement | null): 'ltr' | 'rtl' {
return isRtlElement(element) ? 'rtl' : 'ltr';
}

/**
* Whether the platform has just animated a history traversal itself: Safari's
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
* edge swipe back or forward, or the back gesture of an iOS Home Screen app.
* 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.
*/
function usePlatformAnimatedTraversal(
containerRef: RefObject<HTMLElement | null>,
): {take: () => boolean} {
const markRef = useRef(false);
useEffect(() => {
const view = containerRef.current?.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 navigation: unknown = Reflect.get(view, 'navigation');
const navigationTarget =
navigation instanceof view.EventTarget ? navigation : null;
navigationTarget?.addEventListener('navigate', mark);
return () => {
view.cancelAnimationFrame(frame);
view.removeEventListener('popstate', mark, {capture: true});
navigationTarget?.removeEventListener('navigate', mark);
};
}, [containerRef]);
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
return useMemo(
() => ({
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.
Expand Down Expand Up @@ -829,6 +886,7 @@ export function NavigationStack<T>({
const t = useTranslator();
const containerRef = useRef<HTMLDivElement | null>(null);
const cardsRef = useRef<HTMLDivElement>(null);
const platformTraversal = usePlatformAnimatedTraversal(containerRef);
const [registry] = useState<Registry>(() => new Map());
// The last input decides whether a moved focus shows its ring.
const {ref: trackModality, readModality} = useInteractionModalityTracking();
Expand Down Expand Up @@ -1399,6 +1457,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 @@ -1483,6 +1564,7 @@ export function NavigationStack<T>({
view.transition.id,
animateProgress,
focusAfter,
platformTraversal,
layersOf,
readClearBars,
setProgress,
Expand Down