Skip to content
Closed
95 changes: 80 additions & 15 deletions packages/lab/src/NavigationStack/NavigationStack.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,54 @@ function writingDirection(element: HTMLElement | null): 'ltr' | 'rtl' {
return isRtlElement(element) ? 'rtl' : 'ltr';
}

/** When a transition's animations start, as the animator's call options. */
type TransitionClock = {at?: number; start?: 'next-frame'};

/**
* The clock of a transition. A finger's release keeps its release time, so
* the spring continues from the frame the finger left. A transition from rest
* leaves its start to the animator. The browser's commit then dates it. So a
* heavy commit or a later listener's block delays the motion. It never skips
* ahead. In an input event's own task (a tap on a row, a key), the motion
* starts at the first frame after that task.
*/
function transitionClock(
releasedAt: number | undefined,
isInputTask: boolean,
): TransitionClock {
if (releasedAt != null) {
return {at: releasedAt};
}
return isInputTask ? {start: 'next-frame'} : {};
}

/** The pointer, key and touch events a person's press dispatches. */
const INPUT_EVENT_TYPES: ReadonlySet<string> = new Set([
'click',
'pointerdown',
'pointerup',
'mousedown',
'mouseup',
'touchstart',
'touchend',
'keydown',
'keyup',
]);

/**
* The page is dispatching an input event (a pointer, a key, a touch) now.
* The fallback for a push the app starts outside the stack's own handlers.
*/
function isDispatchingInput(
view: (Window & typeof globalThis) | null | undefined,
): boolean {
if (view == null) {
return false;
}
const event: unknown = Reflect.get(view, 'event');
return event instanceof view.Event && INPUT_EVENT_TYPES.has(event.type);
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
}

/**
* A push/pop navigator: UINavigationController's transitions, back button
* and back swipes, on the compositor.
Expand Down Expand Up @@ -964,9 +1012,12 @@ export function NavigationStack<T>({
// ---------------------------------------------------------------------------

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);
// The clock the last transition's screens run on (their start), so the
// back chevron keeps time with them.
const startedRef = useRef<TransitionClock>({});
// A click or key press in the stack is being handled in this task
// (rememberActivation).
const inputTaskRef = useRef(false);
// 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>(
Expand Down Expand Up @@ -1102,6 +1153,8 @@ export function NavigationStack<T>({
/**
* 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).
* `releasedAt` is a finger's release time; without it the springs start on
* the animator's clock (transitionClock).
*/
const animateProgress = useCallback(
(
Expand All @@ -1112,14 +1165,18 @@ export function NavigationStack<T>({
dp: number | undefined,
release: boolean,
underBar: 'rest' | 'ride',
startAt?: number,
releasedAt?: 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 clock = transitionClock(
releasedAt,
inputTaskRef.current ||
isDispatchingInput(containerRef.current?.ownerDocument.defaultView),
);
const topLayers = layersOf(top);
const underLayers = layersOf(under);
const handles = [];
Expand All @@ -1132,13 +1189,13 @@ export function NavigationStack<T>({
{x: values.topX},
{spring, velocity: velocity ? {x: velocity.topX} : undefined},
{
at,
...clock,
touchRelease: release,
crossfadeAs: to === 0 ? 'entrance' : 'exit',
},
),
);
startedRef.current = at;
startedRef.current = clock;
}
// The bars move with their cards (each screen's bar is part of it in
// UIKit): the incoming one covers the outgoing title.
Expand All @@ -1147,7 +1204,7 @@ export function NavigationStack<T>({
topLayers.bar.animate(
{x: values.topX},
{spring, velocity: velocity ? {x: velocity.topX} : undefined},
{at, touchRelease: release},
{...clock, touchRelease: release},
),
);
}
Expand All @@ -1156,7 +1213,7 @@ export function NavigationStack<T>({
underLayers.bar.animate(
{x: values.underX},
{spring, velocity: velocity ? {x: velocity.underX} : undefined},
{at, touchRelease: release},
{...clock, touchRelease: release},
),
);
}
Expand All @@ -1166,7 +1223,7 @@ export function NavigationStack<T>({
{x: values.underX},
{spring, velocity: velocity ? {x: velocity.underX} : undefined},
{
at,
...clock,
touchRelease: release,
crossfadeAs: to === 1 ? 'entrance' : 'exit',
},
Expand Down Expand Up @@ -1206,15 +1263,15 @@ export function NavigationStack<T>({
spring,
velocity: clipVelocity == null ? undefined : {x: clipVelocity},
},
{at, touchRelease: release},
{...clock, touchRelease: release},
),
underLayers.barClipContent.animate(
{x: -clipTo},
{
spring,
velocity: clipVelocity == null ? undefined : {x: -clipVelocity},
},
{at, touchRelease: release},
{...clock, touchRelease: release},
),
);
}
Expand All @@ -1240,7 +1297,7 @@ export function NavigationStack<T>({
spring,
velocity: velocity ? {opacity: velocity.dim} : undefined,
},
{at, touchRelease: release},
{...clock, touchRelease: release},
),
);
}
Expand Down Expand Up @@ -1295,7 +1352,7 @@ export function NavigationStack<T>({
velocity: t => (t < delayS ? 0 : fade.velocity(t - delayS)),
},
},
{at: startedRef.current, touchRelease: release},
{...startedRef.current, touchRelease: release},
);
},
[view.models, backControl.animator, backChevron.animator],
Expand Down Expand Up @@ -1460,7 +1517,6 @@ export function NavigationStack<T>({
wasRunning ? undefined : programmaticVelocity('pop'),
false,
'ride',
at,
);
fadeBack('pop', under);
}
Expand Down Expand Up @@ -1569,6 +1625,15 @@ export function NavigationStack<T>({
// 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) => {
// A transition this click or key starts runs in its task: React commits
// it before the task ends, and the next task clears the mark. A click
// from script commits after window.event is restored. The mark still
// sees that task.
inputTaskRef.current = true;
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
const view = containerRef.current?.ownerDocument.defaultView;
view?.setTimeout(() => {
inputTaskRef.current = false;
}, 0);
const {target} = event;
if (isElement(target)) {
// The scroller is focusable while it overflows, but it is not a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1150,6 +1150,68 @@ function blockDuringPush(page: Page, ms: number) {
});
}

test('a push whose commit blocks the main thread starts from its first frame', async ({
page,
}) => {
// A heavy screen blocks the main thread in the task that pushes it (here
// for 300 ms, right after the stack mounts it). The push starts when that
// task ends, so its first frames show it near where it starts. Dated
// before the block, it would show almost all of its travel at once. The
// check reads the time since the block with the position, because an
// engine's first frames after a long task can take far longer than 16 ms.
const {driver, width} = await openStack(page, 'settings');
await page.evaluate(() => {
const observer = new MutationObserver(() => {
if (
document.querySelector('[data-navigation-screen="screen-General"]') ==
null
) {
return;
}
observer.disconnect();
const until = performance.now() + 300;
while (performance.now() < until) {
// Hold the main thread, as a heavy commit does.
}
(window as Window & {blockEnd?: number}).blockEnd = performance.now();
});
observer.observe(document.body, {childList: true, subtree: true});
});
await driver.tap(await rowCenter(page, 'General'));
// The second frame after the block, and how long after the block it ran.
const {x, sinceBlock} = await page.evaluate(
() =>
new Promise<{x: number; sinceBlock: number}>(resolve => {
requestAnimationFrame(() =>
requestAnimationFrame(() => {
const pushed = document.querySelector(
'[data-navigation-screen="screen-General"]',
);
const value =
pushed == null ? 'none' : getComputedStyle(pushed).translate;
const blockEnd =
(window as Window & {blockEnd?: number}).blockEnd ?? 0;
Comment on lines +1192 to +1193

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking (Miss): if the MutationObserver never sees screen-General (a renamed screen key, say), blockEnd falls back to 0. sinceBlock is then the page's whole age, and 0.5 * leftAt(sinceBlock) is about 10⁻¹⁷, so any card not exactly at rest passes and the test no longer checks a start after a block. Return the raw value and fail when the block did not run:

const blockEnd = (window as Window & {blockEnd?: number}).blockEnd;
resolve({x, blockEnd, sinceBlock: performance.now() - (blockEnd ?? 0)});
// after page.evaluate:
expect(blockEnd).toBeDefined();

resolve({
x: value === 'none' ? 0 : parseFloat(value),
sinceBlock: performance.now() - blockEnd,
});
}),
);
}),
);
// The push spring from the trailing edge (OMEGA, starting at
// PUSH_VELOCITY): about 70 % of the width is still to travel after 33 ms.
// The share left `ms` into the push:
const leftAt = (ms: number) => {
const s = ms / 1000;
return (1 + (OMEGA - PUSH_VELOCITY) * s) * Math.exp(-OMEGA * s);
};
// Started at the block's end, at least half of what the spring leaves at
// that time is still to travel. Dated before the 300 ms block, almost none
// would be.
expect(Math.abs(x) / width).toBeGreaterThan(0.5 * leftAt(sinceBlock));
});

test('a push keeps advancing every frame while the main thread is blocked', async ({
page,
browserName,
Expand Down
Loading