From bd5fcfdbee5a89ca832821d0bbe79041bf487660 Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Thu, 5 Nov 2026 15:05:03 -0800 Subject: [PATCH 1/6] feat(core): useFingerScroll tells its caller when a finger's scroll ends MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `useFingerScroll(scroller, {onEnd})` calls `onEnd` once each time a finger's scroll on the scroller ends — its scrollend after the lift, the lift after a scrollend under a resting finger, the quiet fallback, or the pointer turning fine — after the reader already says false. Unmounting never calls it. The internal touch entry re-exports the hook for Lab's ChatVirtualizer, which will drop its own touch listeners for it. --- .changeset/finger-scroll-end.md | 7 + docs/architecture/react-component-runtime.md | 4 +- packages/core/src/gestures/README.md | 5 +- .../__tests__/useFingerScroll.test.tsx | 138 +++++++++++++++++- packages/core/src/gestures/fingerScroll.ts | 52 ++++++- packages/core/src/gestures/useFingerScroll.ts | 29 +++- packages/core/src/internal/touch.test.ts | 7 + packages/core/src/internal/touch.ts | 5 + scripts/touch-support-bundle.test.mjs | 4 +- 9 files changed, 237 insertions(+), 14 deletions(-) create mode 100644 .changeset/finger-scroll-end.md diff --git a/.changeset/finger-scroll-end.md b/.changeset/finger-scroll-end.md new file mode 100644 index 0000000000000..1916017f1fbed --- /dev/null +++ b/.changeset/finger-scroll-end.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: `useFingerScroll(scroller, {onEnd})` calls `onEnd` each time a finger's scroll on the scroller ends, and the hook is re-exported from the internal touch subpath for Lab's ChatVirtualizer. Internal entries are outside the public API and its compatibility promise; the hook is not exported from the package entry point or the gestures barrel. + +@cixzhang diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.md index 7944940789093..4e414f2a4a928 100644 --- a/docs/architecture/react-component-runtime.md +++ b/docs/architecture/react-component-runtime.md @@ -319,7 +319,9 @@ those contracts. `@astryxdesign/core/internal/touch`, a subpath reserved for Astryx's own packages: undocumented, outside the compatibility promise, versioned in lockstep with Core, and limited by lint to Core and Lab (`spec:AST-017` - FR21). + FR21). The finger-scroll watch's hook, `useFingerScroll`, is on that + subpath: it reports whether a scroller's scroll is a finger's and, through + `onEnd`, when that scroll ends. - **INV15 — The animator animates a number.** The animator has a value mode: it plays a number, such as a count or a chart value, on the same timing as its property channels: theme motion tokens for a program-started change, and measured springs only where `spec:AST-094` FR45 keeps them, and hands the value to an `onUpdate` callback each frame for the component to format and write. The component owns diff --git a/packages/core/src/gestures/README.md b/packages/core/src/gestures/README.md index fa28133a0f8d3..e4bb6fc8f7084 100644 --- a/packages/core/src/gestures/README.md +++ b/packages/core/src/gestures/README.md @@ -75,7 +75,10 @@ function Sheet() { while a finger that landed inside it is down, until its `scrollend` (the momentum is still the finger's), or, where the browser fires none (mobile Safari before 26), until its scroll events go quiet. Pass a ref, or the - document for the page. Outside React, `watchFingerScrolls(host, scroller)` and + document for the page. `options.onEnd` runs each time such a scroll ends, + once the reader says `false`; unmounting does not call it. It is + re-exported from `@astryxdesign/core/internal/touch` for Lab's + ChatVirtualizer. Outside React, `watchFingerScrolls(host, scroller)` and `isFingerScroll(host, scroller)` from `fingerScroll.ts` do the same; that module adds passive scroll listeners only while something is watched. diff --git a/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx b/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx index ea484425d0d02..f38b02ea6836d 100644 --- a/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx +++ b/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx @@ -7,17 +7,18 @@ * @output A finger's scroll reads true until the scroller's scrollend; a * scroll with no finger down reads false; the page's own scroll through * the document; the watch follows the ref's node and ends on unmount, and - * lets go of a node it stops following + * lets go of a node it stops following; onEnd runs once per finger scroll + * on each end path, for each watcher, and never on unmount * @position Unit tests of packages/core/src/gestures/useFingerScroll.ts */ import {render} from '@testing-library/react'; import {useRef} from 'react'; -import {afterEach, beforeEach, describe, expect, it} from 'vitest'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {isFingerScroll} from '../fingerScroll'; import {getGestureHost} from '../GestureHost'; import {useFingerScroll} from '../useFingerScroll'; -import {coarsePrimaryPointer} from './pointerQuery'; +import {coarsePrimaryPointer, pointerQuery} from './pointerQuery'; function touch(type: string, target: Element, down: boolean): void { const event = new Event(type, {bubbles: true, cancelable: true}); @@ -71,6 +72,39 @@ function Follower() { return null; } +/** A list that counts its finger scrolls' ends, and what it read then. */ +const ends: {count: number; readAtEnd: boolean[]} = {count: 0, readAtEnd: []}; + +function EndingList({watchers = 1}: {watchers?: number}) { + const ref = useRef(null); + const onEnd = () => { + ends.count += 1; + ends.readAtEnd.push(read()); + }; + read = useFingerScroll(ref, {onEnd}); + // The second watcher renders after the list, so the list's ref is set + // when its attachment runs. + return ( + <> +
+

row

+
+ {watchers > 1 && } + + ); +} + +function SecondWatcher({ + scroller, + onEnd, +}: { + scroller: {current: Element | null}; + onEnd: () => void; +}) { + useFingerScroll(scroller, {onEnd}); + return null; +} + function Page() { read = useFingerScroll(document); return

row

; @@ -184,4 +218,102 @@ describe('useFingerScroll', () => { second.element.remove(); } }); + + describe('onEnd', () => { + beforeEach(() => { + ends.count = 0; + ends.readAtEnd = []; + }); + + it("runs once at the scroller's scrollend after the lift, with the reader already false", () => { + const {getByTestId} = render(); + const list = getByTestId('list'); + fingerScroll(list, getByTestId('row')); + touch('touchend', getByTestId('row'), false); + list.dispatchEvent(new Event('scroll')); + expect(ends.count).toBe(0); + list.dispatchEvent(new Event('scrollend')); + expect(ends.count).toBe(1); + expect(ends.readAtEnd).toEqual([false]); + list.dispatchEvent(new Event('scrollend')); + expect(ends.count).toBe(1); + }); + + it('runs at the lift when the scroll ended under a resting finger', () => { + const {getByTestId} = render(); + const list = getByTestId('list'); + fingerScroll(list, getByTestId('row')); + list.dispatchEvent(new Event('scrollend')); + expect(ends.count).toBe(0); + touch('touchend', getByTestId('row'), false); + expect(ends.count).toBe(1); + }); + + it('runs after the quiet fallback where the browser fires no scrollend', () => { + // A browser with no scrollend (mobile Safari before 26): take jsdom's + // handler slot away for this test. + let owner: object | null = window; + while (owner != null && !Object.hasOwn(owner, 'onscrollend')) { + owner = Object.getPrototypeOf(owner) as object | null; + } + const slot = + owner == null + ? undefined + : Object.getOwnPropertyDescriptor(owner, 'onscrollend'); + if (owner != null) { + delete (owner as Record).onscrollend; + } + vi.useFakeTimers(); + try { + expect('onscrollend' in window).toBe(false); + const {getByTestId} = render(); + const list = getByTestId('list'); + fingerScroll(list, getByTestId('row')); + touch('touchend', getByTestId('row'), false); + vi.advanceTimersByTime(149); + expect(ends.count).toBe(0); + vi.advanceTimersByTime(1); + expect(ends.count).toBe(1); + expect(ends.readAtEnd).toEqual([false]); + } finally { + vi.useRealTimers(); + if (owner != null && slot != null) { + Object.defineProperty(owner, 'onscrollend', slot); + } + } + }); + + it('runs when the primary pointer stops being coarse mid-scroll', () => { + restorePointer(); + const pointer = pointerQuery(true); + restorePointer = pointer.restore; + const {getByTestId} = render(); + fingerScroll(getByTestId('list'), getByTestId('row')); + pointer.set(false); + expect(ends.count).toBe(1); + expect(ends.readAtEnd).toEqual([false]); + touch('touchend', getByTestId('row'), false); + }); + + it('gives two watchers of one scroller one call each per finger scroll', () => { + const {getByTestId} = render(); + const list = getByTestId('list'); + fingerScroll(list, getByTestId('row')); + lift(list, getByTestId('row')); + expect(ends.count).toBe(2); + fingerScroll(list, getByTestId('row')); + lift(list, getByTestId('row')); + expect(ends.count).toBe(4); + }); + + it('does not run on unmount, even mid-scroll', () => { + const {getByTestId, unmount} = render(); + const row = getByTestId('row'); + fingerScroll(getByTestId('list'), row); + unmount(); + expect(ends.count).toBe(0); + touch('touchend', row, false); + expect(ends.count).toBe(0); + }); + }); }); diff --git a/packages/core/src/gestures/fingerScroll.ts b/packages/core/src/gestures/fingerScroll.ts index 1e429e2a220da..b6f9e7b9c929e 100644 --- a/packages/core/src/gestures/fingerScroll.ts +++ b/packages/core/src/gestures/fingerScroll.ts @@ -5,7 +5,8 @@ * @input A scroller (an element, or the document for the page's own scroll), * its document's scroll and scrollend events, and the gesture host's * finger record - * @output Exports watchFingerScrolls and isFingerScroll + * @output Exports watchFingerScrolls and isFingerScroll; a watcher can ask to + * be told when a finger's scroll ends * @position Finger-scroll watch of packages/core/src/gestures (useFingerScroll * reads it), in its own module so a page that never asks never ships it; * internal to the touch module, not in the gestures barrel @@ -40,11 +41,27 @@ interface Watch { readonly fingerScrollers: Set; /** Finger scrolls whose `scrollend` came while the finger still rested. */ readonly endedWhileDown: Set; + /** Per scroller, the watchers to tell when its finger scroll ends. */ + readonly endListeners: Map void>>; stop: (() => void) | null; } const watches = new WeakMap(); +/** + * A scroller's finger scroll is over: it stops counting as the finger's, and + * then its end listeners hear of it, so a listener that reads + * isFingerScroll already reads false. + */ +function endFingerScroll(watch: Watch, scroller: Node): void { + if (!watch.fingerScrollers.delete(scroller)) { + return; + } + for (const listener of [...(watch.endListeners.get(scroller) ?? [])]) { + listener(); + } +} + function start(host: GestureHost, watch: Watch): () => void { const doc = host.document; const scrollerOf = (event: Event): Node | null => { @@ -61,7 +78,7 @@ function start(host: GestureHost, watch: Watch): () => void { // The finger still rests there: the scroll is its until the lift. watch.endedWhileDown.add(scroller); } else { - watch.fingerScrollers.delete(scroller); + endFingerScroll(watch, scroller); } }; const scrollEndFallbacks = new Map>(); @@ -113,7 +130,7 @@ function start(host: GestureHost, watch: Watch): () => void { for (const scroller of watch.endedWhileDown) { if (!host.isFingerDownIn(scroller)) { watch.endedWhileDown.delete(scroller); - watch.fingerScrollers.delete(scroller); + endFingerScroll(watch, scroller); } } }; @@ -139,8 +156,12 @@ function start(host: GestureHost, watch: Watch): () => void { for (const scroller of [...scrollEndFallbacks.keys()]) { clearScrollEndFallback(scroller); } - watch.fingerScrollers.clear(); + // No finger scrolls once the pointer is no longer coarse: each one in + // progress ends here. watch.endedWhileDown.clear(); + for (const scroller of [...watch.fingerScrollers]) { + endFingerScroll(watch, scroller); + } } }; const stopWatchingPointer = watchCoarsePointer(view, listen); @@ -158,12 +179,17 @@ function start(host: GestureHost, watch: Watch): () => void { /** * Keep track of whether the scrolls of `scroller` (an element in `host`'s * document, or the document itself) are a finger's, for isFingerScroll, - * until the returned function runs. + * until the returned function runs. `onEnd`, when given, runs each time a + * finger's scroll on the scroller ends (its `scrollend` after the lift, the + * lift after a `scrollend` that came while the finger rested, the quiet + * fallback, or the pointer turning fine), after isFingerScroll turns false. + * Stopping the watch does not call it. * Internal: not exported from the package. */ export function watchFingerScrolls( host: GestureHost, scroller: Node, + onEnd?: () => void, ): () => void { let watch = watches.get(host); if (watch == null) { @@ -171,12 +197,21 @@ export function watchFingerScrolls( scrollers: new Map(), fingerScrollers: new Set(), endedWhileDown: new Set(), + endListeners: new Map(), stop: null, }; watches.set(host, watch); } const owned = watch; owned.scrollers.set(scroller, (owned.scrollers.get(scroller) ?? 0) + 1); + // Each watch registers its own listener, so two watchers of one scroller + // each hear every end once. + const listener = onEnd == null ? null : () => onEnd(); + if (listener != null) { + const listeners = owned.endListeners.get(scroller) ?? new Set(); + listeners.add(listener); + owned.endListeners.set(scroller, listeners); + } owned.stop ??= start(host, owned); let isWatching = true; return () => { @@ -184,6 +219,13 @@ export function watchFingerScrolls( return; } isWatching = false; + if (listener != null) { + const listeners = owned.endListeners.get(scroller); + listeners?.delete(listener); + if (listeners?.size === 0) { + owned.endListeners.delete(scroller); + } + } const count = (owned.scrollers.get(scroller) ?? 1) - 1; if (count > 0) { owned.scrollers.set(scroller, count); diff --git a/packages/core/src/gestures/useFingerScroll.ts b/packages/core/src/gestures/useFingerScroll.ts index 51224e7f89e3e..838f30eea02ea 100644 --- a/packages/core/src/gestures/useFingerScroll.ts +++ b/packages/core/src/gestures/useFingerScroll.ts @@ -7,7 +7,7 @@ * @input A scroller (a ref to an element, or the document for the page) and * the document's gesture host * @output useFingerScroll: whether the scroller's current scroll is a - * finger's, read at any moment + * finger's, read at any moment, and an optional call when one ends * @position Gesture hook of packages/core/src/gestures, over the * finger-scroll watch (fingerScroll.ts), kept on the scroller's node by * the gesture hooks' shared attachment (hooks/useAttachment.ts). An internal @@ -29,7 +29,7 @@ * SYNC: When modified, update __tests__/useFingerScroll.test.tsx. */ -import {useCallback, useRef, type RefObject} from 'react'; +import {useCallback, useLayoutEffect, useRef, type RefObject} from 'react'; import {isFingerScroll, watchFingerScrolls} from './fingerScroll'; import {getGestureHost} from './GestureHost'; import {useAttachment} from '../hooks/useAttachment'; @@ -43,6 +43,18 @@ function documentOf(node: Element | Document): Document { return isDocument(node) ? node : node.ownerDocument; } +export interface UseFingerScrollOptions { + /** + * Runs each time a finger's scroll on the scroller ends, once the reader + * says `false`: at its `scrollend` after the lift (the momentum is still + * the finger's), at the lift when the scroll ended under a resting finger, + * after the quiet fallback where the browser fires no `scrollend`, or when + * the primary pointer stops being coarse. Unmounting, or the scroller + * changing, does not call it. The latest function is the one called. + */ + onEnd?: () => void; +} + /** * Watch a scroller's finger scrolls. Pass a ref to a scrolling element, or * the document for the page's own scroll. Returns a reader, stable across @@ -51,9 +63,16 @@ function documentOf(node: Element | Document): Document { */ export function useFingerScroll( scroller: RefObject | Document, + {onEnd}: UseFingerScrollOptions = {}, ): () => boolean { /** The node the watch is on now, for the reader. */ const watchedRef = useRef(null); + // The watch outlives renders, so it calls the latest onEnd through a ref + // written at commit. + const onEndRef = useRef(onEnd); + useLayoutEffect(function keepLatestOnEnd() { + onEndRef.current = onEnd; + }); // Keeps the finger-scroll watch on the node the scroller names after each // commit (useAttachment): a ref that now points at another element moves // the watch to it, and unmounting releases it. @@ -61,7 +80,11 @@ export function useFingerScroll( isDocument(scroller) ? {current: scroller} : scroller, node => { watchedRef.current = node; - const stop = watchFingerScrolls(getGestureHost(documentOf(node)), node); + const stop = watchFingerScrolls( + getGestureHost(documentOf(node)), + node, + () => onEndRef.current?.(), + ); return () => { stop(); watchedRef.current = null; diff --git a/packages/core/src/internal/touch.test.ts b/packages/core/src/internal/touch.test.ts index 8c7d5dd507741..77770740e287e 100644 --- a/packages/core/src/internal/touch.test.ts +++ b/packages/core/src/internal/touch.test.ts @@ -84,6 +84,13 @@ describe('internal/touch', () => { } }); + it("re-exports by name what Lab's ChatVirtualizer reads", async () => { + const entry: Record = await import('./touch'); + const fingerScroll = await import('../gestures/useFingerScroll'); + expect(entry.useFingerScroll).toBe(fingerScroll.useFingerScroll); + expect(typeof entry.useFingerScroll).toBe('function'); + }); + it("re-exports by name what Lab's NavigationStack reads", async () => { const entry: Record = await import('./touch'); const edgePan = await import('../gestures/ScreenEdgePanGestureRecognizer'); diff --git a/packages/core/src/internal/touch.ts b/packages/core/src/internal/touch.ts index 7510fb184e95f..df1d4323ea086 100644 --- a/packages/core/src/internal/touch.ts +++ b/packages/core/src/internal/touch.ts @@ -95,3 +95,8 @@ export { } from '../motion/uikit/springs'; export {focusForLastInput, isFocusLost} from '../utils/focusReturn'; export {useInteractionModalityTracking} from '../utils/interactionModality'; + +// Lab's ChatVirtualizer reads whether its scroller's scroll is a finger's, +// and flushes its held writes when that scroll ends. +export {useFingerScroll} from '../gestures/useFingerScroll'; +export type {UseFingerScrollOptions} from '../gestures/useFingerScroll'; diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs index 994efc6214df3..650a4dc162bd0 100644 --- a/scripts/touch-support-bundle.test.mjs +++ b/scripts/touch-support-bundle.test.mjs @@ -117,11 +117,13 @@ function exportsOf(entry) { * and its query, and an element's direction. Lab's NavigationStack reads the * screen-edge pan, the spring solver, the motion resolver, UIKit's * navigation table and its four navigation springs. It also reads the focus - * helpers that follow the last input. + * helpers that follow the last input. Lab's ChatVirtualizer reads the + * finger-scroll watch. */ const LAB_ONLY_NAMES = [ 'PanGestureRecognizer', 'useGestureRecognizer', + 'useFingerScroll', 'createMotionEngine', 'cubicBezier', 'mapProgress', From 740d13a23407c195d5b37950cbdca2a464f35ec4 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 5 Nov 2026 16:35:36 -0800 Subject: [PATCH 2/6] fix(lab): NavigationStack re-measures a screen when its title resizes The large title sat outside the scroll area's content root, so a change of its height alone, such as a longer title, re-measured nothing. A screen that then overflowed stayed clipped: it did not scroll, offered no keyboard stop and contained no overscroll until another change re-measured it. The title is now first in the content root, whose size the scroll area watches. The headers of navigationTransition.ts and the browser spec keep their fields only. The transition's layer notes move to the JSDoc of the type and function they describe. --- .../NavigationStack/NavigationStack.test.tsx | 7 +- .../src/NavigationStack/NavigationStack.tsx | 30 +++++---- ...avigationStack.interaction.browser.spec.ts | 66 ++++++++++++++++--- .../NavigationStack/navigationTransition.ts | 41 +++++------- 4 files changed, 95 insertions(+), 49 deletions(-) diff --git a/packages/lab/src/NavigationStack/NavigationStack.test.tsx b/packages/lab/src/NavigationStack/NavigationStack.test.tsx index b5865f78111a0..62782c7feb4e2 100644 --- a/packages/lab/src/NavigationStack/NavigationStack.test.tsx +++ b/packages/lab/src/NavigationStack/NavigationStack.test.tsx @@ -209,9 +209,10 @@ describe('NavigationStack', () => { render(); const large = screen.getByRole('heading', {level: 1, name: 'Settings'}); // First in the screen's scrolling content. - expect(screenCard('Settings')?.firstElementChild?.firstElementChild).toBe( - large, - ); + expect( + screenCard('Settings')?.firstElementChild?.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, diff --git a/packages/lab/src/NavigationStack/NavigationStack.tsx b/packages/lab/src/NavigationStack/NavigationStack.tsx index f4deb3c734a1c..53668a6def52c 100644 --- a/packages/lab/src/NavigationStack/NavigationStack.tsx +++ b/packages/lab/src/NavigationStack/NavigationStack.tsx @@ -382,7 +382,9 @@ function CardLayer({ const entry = registry.get(model.key) ?? {}; entry.largeTitleElement = title; registry.set(model.key, entry); - const scroller = title?.parentElement ?? null; + // The title is first in the scroll content, so a change of its height + // reaches the scroll area's measure. The scroller holds that content. + const scroller = title?.parentElement?.parentElement ?? null; if (title == null || scroller == null) { return undefined; } @@ -442,18 +444,20 @@ function CardLayer({ {...getViewportProps({ xstyle: [focusOutlineStyles.focusVisible, styles.scroller], })}> - {isLarge ? ( -

- {props.title} -

- ) : null} -
({})}>{props.children}
+
({})}> + {isLarge ? ( +

+ {props.title} +

+ ) : null} + {props.children} +
{ await page.setViewportSize({width: 400, height: 200}); await expect.poll(contain).toBe('contain'); }); + + test('a large title that grows re-measures its screen', async ({page}) => { + await openStack(page, 'large-title'); + const root = card(page, 'root'); + const contain = async () => + root.evaluate( + element => + getComputedStyle(element.firstElementChild ?? element) + .overscrollBehaviorY, + ); + // A viewport just taller than the screen's content: nothing to scroll. + const contentHeight = await root.evaluate( + element => (element.firstElementChild as HTMLElement).scrollHeight, + ); + await page.setViewportSize({width: 400, height: contentHeight + 40}); + await expect.poll(contain).toBe('auto'); + // A font load, the resize and the stack's release of its motion hints + // each start a measurement of their own. Let them end first, so that only + // the title can start the next one. + await page.evaluate(async () => { + await document.fonts.ready; + }); + await expect + .poll(() => + page.evaluate( + () => document.querySelector('[style*="will-change"]') == null, + ), + ) + .toBe(true); + await page.evaluate( + () => + new Promise(resolve => { + let frames = 5; + const tick = () => { + frames -= 1; + if (frames === 0) { + resolve(); + } else { + requestAnimationFrame(tick); + } + }; + requestAnimationFrame(tick); + }), + ); + expect(await contain()).toBe('auto'); + // A taller line makes the title taller, with no font to load. No box but + // the title's own changes size, and the screen now overflows. + await root + .locator('h1') + .evaluate(title => title.style.setProperty('line-height', '400px')); + await expect.poll(contain).toBe('contain'); + }); }); test('a push does no Layout or Paint per frame', async ({ diff --git a/packages/lab/src/NavigationStack/navigationTransition.ts b/packages/lab/src/NavigationStack/navigationTransition.ts index 2cc1ad30c0906..70e09aa23035f 100644 --- a/packages/lab/src/NavigationStack/navigationTransition.ts +++ b/packages/lab/src/NavigationStack/navigationTransition.ts @@ -4,22 +4,21 @@ * @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`). + * @output Pure math for NavigationStack's transition: layer values and + * velocities at a progress (`layersAt`, `layerVelocities`). Also the pop's + * release rule (`shouldFinishPop`) and progress from travel or a caught + * screen (`progressFromTravel`, `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). - * + * SYNC: When modified, update navigationTransition.test.ts. + */ + +import {rubberBand, rubberBandInverse} from '@astryxdesign/core/internal/touch'; + +import {navigation} from './navigationMotion'; + +/** * 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; @@ -29,14 +28,7 @@ * * 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; @@ -49,9 +41,12 @@ export interface TransitionLayers { 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. + * The layers at progress `p` for a container `width` px wide. `p` is the + * share of the width the top card has uncovered: 0 when a push has landed, + * 1 when 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's `percentComplete`). + * `direction` is the writing direction: under RTL cards enter from the left, + * so every x flips. */ export function layersAt( p: number, From fc42cd864b43533d881075b244a2e878676780b9 Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Thu, 5 Nov 2026 18:05:31 -0800 Subject: [PATCH 3/6] fix(core): useFingerScroll keeps the latest onEnd through the isomorphic layout effect Core hooks write commit-time refs with useIsomorphicLayoutEffect, which stays quiet under server rendering. --- packages/core/src/gestures/useFingerScroll.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/core/src/gestures/useFingerScroll.ts b/packages/core/src/gestures/useFingerScroll.ts index 838f30eea02ea..2d1cf15de13ee 100644 --- a/packages/core/src/gestures/useFingerScroll.ts +++ b/packages/core/src/gestures/useFingerScroll.ts @@ -29,10 +29,11 @@ * SYNC: When modified, update __tests__/useFingerScroll.test.tsx. */ -import {useCallback, useLayoutEffect, useRef, type RefObject} from 'react'; +import {useCallback, useRef, type RefObject} from 'react'; import {isFingerScroll, watchFingerScrolls} from './fingerScroll'; import {getGestureHost} from './GestureHost'; import {useAttachment} from '../hooks/useAttachment'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; function isDocument(value: unknown): value is Document { return typeof Document !== 'undefined' && value instanceof Document; @@ -70,7 +71,7 @@ export function useFingerScroll( // The watch outlives renders, so it calls the latest onEnd through a ref // written at commit. const onEndRef = useRef(onEnd); - useLayoutEffect(function keepLatestOnEnd() { + useIsomorphicLayoutEffect(function keepLatestOnEnd() { onEndRef.current = onEnd; }); // Keeps the finger-scroll watch on the node the scroller names after each From 07b5ac2a2a6d77702d1f8e8c7c9f6bbfc5b759bf Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Thu, 5 Nov 2026 18:22:13 -0800 Subject: [PATCH 4/6] docs(core): the finger-scroll re-export names no reader that main does not have The changeset, the internal touch entry, the gestures README and the tests say Lab components that watch a finger's scroll, instead of naming ChatVirtualizer, which is still in an open pull request. Text only. --- .changeset/finger-scroll-end.md | 2 +- packages/core/src/gestures/README.md | 4 ++-- packages/core/src/internal/touch.test.ts | 2 +- packages/core/src/internal/touch.ts | 4 ++-- scripts/touch-support-bundle.test.mjs | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.changeset/finger-scroll-end.md b/.changeset/finger-scroll-end.md index 1916017f1fbed..cc627a04f2155 100644 --- a/.changeset/finger-scroll-end.md +++ b/.changeset/finger-scroll-end.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[chore] Internal: `useFingerScroll(scroller, {onEnd})` calls `onEnd` each time a finger's scroll on the scroller ends, and the hook is re-exported from the internal touch subpath for Lab's ChatVirtualizer. Internal entries are outside the public API and its compatibility promise; the hook is not exported from the package entry point or the gestures barrel. +[chore] Internal: `useFingerScroll(scroller, {onEnd})` calls `onEnd` each time a finger's scroll on the scroller ends, and the hook is re-exported from the internal touch subpath for Lab components that watch a finger's scroll. Internal entries are outside the public API and its compatibility promise; the hook is not exported from the package entry point or the gestures barrel. @cixzhang diff --git a/packages/core/src/gestures/README.md b/packages/core/src/gestures/README.md index e4bb6fc8f7084..e57e6a41c4da4 100644 --- a/packages/core/src/gestures/README.md +++ b/packages/core/src/gestures/README.md @@ -77,8 +77,8 @@ function Sheet() { Safari before 26), until its scroll events go quiet. Pass a ref, or the document for the page. `options.onEnd` runs each time such a scroll ends, once the reader says `false`; unmounting does not call it. It is - re-exported from `@astryxdesign/core/internal/touch` for Lab's - ChatVirtualizer. Outside React, `watchFingerScrolls(host, scroller)` and + re-exported from `@astryxdesign/core/internal/touch` for Lab components + that watch a finger's scroll. Outside React, `watchFingerScrolls(host, scroller)` and `isFingerScroll(host, scroller)` from `fingerScroll.ts` do the same; that module adds passive scroll listeners only while something is watched. diff --git a/packages/core/src/internal/touch.test.ts b/packages/core/src/internal/touch.test.ts index 77770740e287e..29b43412da756 100644 --- a/packages/core/src/internal/touch.test.ts +++ b/packages/core/src/internal/touch.test.ts @@ -84,7 +84,7 @@ describe('internal/touch', () => { } }); - it("re-exports by name what Lab's ChatVirtualizer reads", async () => { + it('re-exports by name the finger-scroll watch Lab components read', async () => { const entry: Record = await import('./touch'); const fingerScroll = await import('../gestures/useFingerScroll'); expect(entry.useFingerScroll).toBe(fingerScroll.useFingerScroll); diff --git a/packages/core/src/internal/touch.ts b/packages/core/src/internal/touch.ts index df1d4323ea086..b7a33df7040af 100644 --- a/packages/core/src/internal/touch.ts +++ b/packages/core/src/internal/touch.ts @@ -96,7 +96,7 @@ export { export {focusForLastInput, isFocusLost} from '../utils/focusReturn'; export {useInteractionModalityTracking} from '../utils/interactionModality'; -// Lab's ChatVirtualizer reads whether its scroller's scroll is a finger's, -// and flushes its held writes when that scroll ends. +// Lab components that watch a finger's scroll read whether a scroller's +// scroll is a finger's, and act when that scroll ends. export {useFingerScroll} from '../gestures/useFingerScroll'; export type {UseFingerScrollOptions} from '../gestures/useFingerScroll'; diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs index 650a4dc162bd0..6e6a0929c48dc 100644 --- a/scripts/touch-support-bundle.test.mjs +++ b/scripts/touch-support-bundle.test.mjs @@ -117,8 +117,8 @@ function exportsOf(entry) { * and its query, and an element's direction. Lab's NavigationStack reads the * screen-edge pan, the spring solver, the motion resolver, UIKit's * navigation table and its four navigation springs. It also reads the focus - * helpers that follow the last input. Lab's ChatVirtualizer reads the - * finger-scroll watch. + * helpers that follow the last input. Lab components that watch a finger's + * scroll read the finger-scroll watch. */ const LAB_ONLY_NAMES = [ 'PanGestureRecognizer', From 33464b1f3e22f98a610e1037d13a6a83892bc9bd Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 5 Nov 2026 18:52:00 -0800 Subject: [PATCH 5/6] feat(lab): under a finger, NavigationStack's bar takes the iOS 26 look Under a finger, NavigationStack's bars paint no background and no hairline, as iOS 26's do. Each screen carries a scroll edge effect: a veil of the body colour that fades in once its content has moved 10px under the bar, on UIKit's measured springs. A push, a pop and a back swipe carry each screen's veil with its card, and the bar a card covers is cut at that card's leading edge. A mouse keeps opaque bars. The veil and the UIKit bar constants live in Lab. The veil reads Core's finger-scroll hook, with its end call, and Core's internal touch entry also names the gesture host and the coarse-pointer check: export-only additions, with no change to Core's behavior. --- .../core-internal-entries-lab-scroll-edge.md | 7 + .../stories/NavigationStack.stories.tsx | 78 ++ packages/core/src/internal/touch.test.ts | 17 + packages/core/src/internal/touch.ts | 7 + .../NavigationStack/NavigationStack.doc.mjs | 2 +- .../NavigationStack/NavigationStack.test.tsx | 35 + .../src/NavigationStack/NavigationStack.tsx | 353 ++++++-- ...avigationStack.interaction.browser.spec.ts | 349 +++++++- ...tackScrollEdge.interaction.browser.spec.ts | 331 ++++++++ .../src/NavigationStack/navigationMotion.ts | 86 +- .../src/internal/__tests__/coarsePointer.ts | 35 + .../src/internal/useScrollEdgeEffect.test.tsx | 757 ++++++++++++++++++ .../lab/src/internal/useScrollEdgeEffect.ts | 357 +++++++++ 13 files changed, 2346 insertions(+), 68 deletions(-) create mode 100644 .changeset/core-internal-entries-lab-scroll-edge.md create mode 100644 packages/lab/src/NavigationStack/__tests__/NavigationStackScrollEdge.interaction.browser.spec.ts create mode 100644 packages/lab/src/internal/__tests__/coarsePointer.ts create mode 100644 packages/lab/src/internal/useScrollEdgeEffect.test.tsx create mode 100644 packages/lab/src/internal/useScrollEdgeEffect.ts diff --git a/.changeset/core-internal-entries-lab-scroll-edge.md b/.changeset/core-internal-entries-lab-scroll-edge.md new file mode 100644 index 0000000000000..654409667acef --- /dev/null +++ b/.changeset/core-internal-entries-lab-scroll-edge.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: Core's internal touch entry also names, for Lab's NavigationStack, the gesture host and the coarse-pointer check. Its scroll edge effect reads the internal finger-scroll hook and its end call. Apps import nothing new. + +@vjeux diff --git a/apps/storybook/stories/NavigationStack.stories.tsx b/apps/storybook/stories/NavigationStack.stories.tsx index 370ea1230c8ab..14ad11773cdf2 100644 --- a/apps/storybook/stories/NavigationStack.stories.tsx +++ b/apps/storybook/stories/NavigationStack.stories.tsx @@ -308,3 +308,81 @@ export const LargeTitle: Story = { name: 'Large title', render: () => , }; + +// ============================================================================= +// Scrolling — content passing under the bar +// ============================================================================= + +const MESSAGES = Array.from({length: 40}, (_, index) => `Message ${index + 1}`); + +function MessageRows() { + const nav = useNavigationStack(); + return ( + + {MESSAGES.map(message => ( + + } + onClick={() => nav.push(message)} + /> + ))} + + ); +} + +function MessageBody({title}: {title: string}) { + return ( + + {Array.from({length: 30}, (_, index) => ( + + ))} + + ); +} + +function ScrollingStack() { + const [path, setPath] = useState([]); + return ( +
+ + + + } + path={path} + onPathChange={setPath} + getKey={entry => entry} + renderScreen={entry => ( + + + + )} + data-testid="navigation-stack" + /> +
+ ); +} + +/** + * Screens long enough to scroll under the bar. On a touch screen the bar + * paints no background. Once a screen's content has moved 10px under it, a + * veil of the body colour fades in, as iOS 26's scroll edge effect does. + * Each screen keeps its own veil through a push, a pop or a back swipe. + */ +export const Scrolling: Story = { + render: () => , +}; diff --git a/packages/core/src/internal/touch.test.ts b/packages/core/src/internal/touch.test.ts index 29b43412da756..c440bf8cb9298 100644 --- a/packages/core/src/internal/touch.test.ts +++ b/packages/core/src/internal/touch.test.ts @@ -137,6 +137,23 @@ describe('internal/touch', () => { expect(entry.navigation).toBeDefined(); }); + it("re-exports by name what NavigationStack's bars and scroll edge effect read", async () => { + const entry: Record = await import('./touch'); + const host = await import('../gestures/GestureHost'); + const pointer = await import('../utils/coarsePointer'); + const fingerScroll = await import('../gestures/useFingerScroll'); + expect(entry.getGestureHost).toBe(host.getGestureHost); + expect(entry.isCoarsePointer).toBe(pointer.isCoarsePointer); + expect(entry.useFingerScroll).toBe(fingerScroll.useFingerScroll); + for (const name of [ + 'getGestureHost', + 'isCoarsePointer', + 'useFingerScroll', + ]) { + expect(typeof entry[name], name).toBe('function'); + } + }); + it('attaches no window or document listeners when it loads', async () => { vi.resetModules(); const onWindow = vi.spyOn(window, 'addEventListener'); diff --git a/packages/core/src/internal/touch.ts b/packages/core/src/internal/touch.ts index b7a33df7040af..f4e8d2f3da7a7 100644 --- a/packages/core/src/internal/touch.ts +++ b/packages/core/src/internal/touch.ts @@ -100,3 +100,10 @@ export {useInteractionModalityTracking} from '../utils/interactionModality'; // scroll is a finger's, and act when that scroll ends. export {useFingerScroll} from '../gestures/useFingerScroll'; export type {UseFingerScrollOptions} from '../gestures/useFingerScroll'; + +// Lab's NavigationStack scroll edge effect reads the finger-scroll hook +// above, and drops the veil's compositing layer when a finger's scroll ends. +// It reads the gesture host for a finger's landing. The stack's bars read the +// coarse-pointer check. +export {getGestureHost} from '../gestures/GestureHost'; +export {isCoarsePointer} from '../utils/coarsePointer'; diff --git a/packages/lab/src/NavigationStack/NavigationStack.doc.mjs b/packages/lab/src/NavigationStack/NavigationStack.doc.mjs index 834b13855b863..7a6b65445f437 100644 --- a/packages/lab/src/NavigationStack/NavigationStack.doc.mjs +++ b/packages/lab/src/NavigationStack/NavigationStack.doc.mjs @@ -25,7 +25,7 @@ export const docs = { 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.", + "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. Under a finger the bar paints no background and no hairline, as iOS 26's does. Once a screen's content has moved 10px under the bar, a veil of the body colour fades in at the top of that screen. Each screen keeps its own veil through a push, a pop or a back swipe. With a mouse the bar keeps its surface and hairline.", props: [ { name: 'root', diff --git a/packages/lab/src/NavigationStack/NavigationStack.test.tsx b/packages/lab/src/NavigationStack/NavigationStack.test.tsx index 62782c7feb4e2..11bc223e5c52f 100644 --- a/packages/lab/src/NavigationStack/NavigationStack.test.tsx +++ b/packages/lab/src/NavigationStack/NavigationStack.test.tsx @@ -219,6 +219,23 @@ describe('NavigationStack', () => { ); }); + it('puts the scroll edge sentinel right after the large title', () => { + render(); + const scroller = screenCard('Settings')?.firstElementChild; + const content = scroller?.firstElementChild; + const [title, sentinel] = Array.from(content?.children ?? []); + expect(title).toBe( + screen.getByRole('heading', {level: 1, name: 'Settings'}), + ); + // It ends where the large title ends, so the veil comes on as the + // bar's title takes over. The scroller holds no other sentinel. + expect(sentinel).toHaveAttribute('data-navigation-scroll-edge-sentinel'); + expect(sentinel).toHaveAttribute('aria-hidden', 'true'); + expect( + scroller?.querySelectorAll('[data-navigation-scroll-edge-sentinel]'), + ).toHaveLength(1); + }); + it('moves focus to the pushed screen’s large title', async () => { render(); const general = screen.getByRole('button', {name: 'General'}); @@ -234,6 +251,24 @@ describe('NavigationStack', () => { }); }); + it('marks the top of an inline screen’s content with the scroll edge sentinel, under its veil', () => { + render(); + const card = screenCard('Settings'); + const [sentinel, content] = Array.from( + card?.firstElementChild?.children ?? [], + ); + // The sentinel sits just above the content, at its static position in + // the scroller. The screen's first element stays the content's first. + expect(sentinel).toHaveAttribute('data-navigation-scroll-edge-sentinel'); + expect( + content?.querySelector('[data-navigation-scroll-edge-sentinel]'), + ).toBeNull(); + // The veil is the card's own child, over the scroller, hidden from + // assistive technology. + const veil = card?.querySelector(':scope > [data-navigation-scroll-edge]'); + expect(veil).toHaveAttribute('aria-hidden', 'true'); + }); + it('shows a screen’s end content in its bar, out of reach once a screen covers it', async () => { render(Edit} />); const edit = screen.getByRole('button', {name: 'Edit'}); diff --git a/packages/lab/src/NavigationStack/NavigationStack.tsx b/packages/lab/src/NavigationStack/NavigationStack.tsx index 53668a6def52c..9d25d78ad7152 100644 --- a/packages/lab/src/NavigationStack/NavigationStack.tsx +++ b/packages/lab/src/NavigationStack/NavigationStack.tsx @@ -7,7 +7,8 @@ * @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. + * Each screen scrolls through Core's useScrollableArea, under Lab's scroll + * edge effect (internal/useScrollEdgeEffect.ts). * @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, @@ -36,12 +37,14 @@ import { import * as stylex from '@stylexjs/stylex'; import { focusForLastInput, + isCoarsePointer, isFocusLost, isRtlElement, resolveMotion, solveSpring, toSpring, useInteractionModalityTracking, + useTouchPresentation, type MotionEngine, type SpringDescription, } from '@astryxdesign/core/internal/touch'; @@ -64,8 +67,9 @@ import { programmaticVelocity, } from './navigationTransition'; import {useBackSwipes, type BackSwipeStack} from './NavigationStackTouch'; -import {navigation, springs} from './navigationMotion'; +import {bars, navigation, springs} from './navigationMotion'; import {useMotionEngine} from '../internal/useMotionEngine'; +import {useScrollEdgeEffect} from '../internal/useScrollEdgeEffect'; // ============================================================================= // Types @@ -169,39 +173,65 @@ const styles = stylex.create({ 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). + // The bar's own background and hairline, under every screen's bar layer, + // which paints its own background over it. iOS 26.2's bar paints neither: + // under a finger the content shows through until the screen's scroll edge + // effect veils it. The literal coarse-pointer key is the resolver's touch + // constant. A mouse keeps both. barBackground: { position: 'absolute', inset: 0, zIndex: -2, - backgroundColor: colorVars['--color-background-surface'], - borderBottomWidth: 1, + backgroundColor: { + default: colorVars['--color-background-surface'], + '@media (pointer: coarse)': 'transparent', + }, + borderBottomWidth: { + default: 1, + '@media (pointer: coarse)': 0, + }, 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. + // does. Under a mouse it has an opaque background of its own + // (barLayerBackground), so the incoming one covers the outgoing title. + // Under a finger the bars are clear, so barClip cuts the covered bar at the + // top card's leading edge. barLayer: { + position: 'absolute', + inset: 0, + // Below the back button: WebKit does not promote the static siblings a + // moving layer crosses, so the moving one goes underneath. + zIndex: -1, + }, + // The box that cuts the bar, moved by the stack. The row inside it moves + // back by as much, so only the cut moves. + barClip: { + position: 'absolute', + inset: 0, + overflow: 'hidden', + }, + barRow: { 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. + // A layer's background, above the bar's hairline. It is clear under a + // finger, as the bar's own background. barLayerBackground: { position: 'absolute', insetInline: 0, top: 0, bottom: 1, zIndex: -1, - backgroundColor: colorVars['--color-background-surface'], + backgroundColor: { + default: colorVars['--color-background-surface'], + '@media (pointer: coarse)': 'transparent', + }, }, // The one back button: it stays put while the bars move under it. backControl: { @@ -303,6 +333,23 @@ const styles = stylex.create({ cardHidden: { contentVisibility: 'hidden', }, + // The scroll edge sentinel stays at its static position, just above the + // content. The scroller is its containing block, so it scrolls with the + // content with no positioned wrapper. On an inline screen it sits outside + // the content, so the screen's first element keeps :first-child. + edgeSentinelStatic: { + insetBlockStart: 'auto', + insetInlineStart: 'auto', + }, + // On a large-title screen the sentinel follows the large title in the + // content and ends where the title ends. So the veil comes on as the bar's + // title takes over. iOS's veil leaves out an expanded large title. The + // margin is the sentinel's 10px height. + edgeSentinelAfterLargeTitle: { + insetBlockStart: 'auto', + insetInlineStart: 'auto', + marginBlockStart: -10, + }, dim: { position: 'absolute', inset: 0, @@ -339,6 +386,14 @@ interface ScreenLayers { dim: MotionEngine; bar: MotionEngine; barDim: MotionEngine; + /** + * The bar's clip box and the row inside it, moved apart: the row moves by + * the opposite of the box. Under a finger the box's edge cuts a covered + * bar at the top card's leading edge, and the row holds still. Identity + * everywhere else. + */ + barClip: MotionEngine; + barClipContent: MotionEngine; titleElement: HTMLElement | null; /** The large title above the content, for `titleDisplayMode="large"`. */ largeTitleElement: HTMLElement | null; @@ -413,6 +468,23 @@ function CardLayer({ ); const card = useMotionEngine(); const dim = useMotionEngine(); + const scrollerRef = useRef(null); + // iOS 26: each screen's scroll view carries its own edge effect, so a push + // or a pop carries each screen's veil with its card. It switches on once + // the content has moved 10px under the bar, which overlays the scroller. + // The veil is half strength at the bar's bottom. A hidden screen, two or + // more levels down, has no layout to measure, so it runs no effect. Once + // revealed it measures and switches at once. + const edge = useScrollEdgeEffect({ + enabled: !isHidden, + root: scrollerRef, + rootInset: BAR_HEIGHT, + edge: `${BAR_HEIGHT}px`, + sentinelXstyle: isLarge + ? styles.edgeSentinelAfterLargeTitle + : styles.edgeSentinelStatic, + springs: bars.scrollEdgeEffect, + }); // A forward Tab into the scroller moves on to its first plain link or // button. const {getViewportProps, getContentProps} = useScrollableArea({ @@ -442,23 +514,34 @@ function CardLayer({ {...stylex.props(styles.card, isHidden && styles.cardHidden)}>
({ + ref: scrollerRef, xstyle: [focusOutlineStyles.focusVisible, styles.scroller], })}> + {isLarge ? null : ( +
+ )}
({})}> {isLarge ? ( -

- {props.title} -

+ <> +

+ {props.title} +

+
+ ) : null} {props.children}
+
(null); @@ -535,25 +629,34 @@ function BarLayer({ data-navigation-bar={model.key} inert={isCovered || undefined} {...stylex.props(styles.barLayer, isCovered && styles.barLayerCovered)}> -
-
-

- {props.title} -

-
{props.endContent}
-
+
+
+
+
+

+ {props.title} +

+
{props.endContent}
+
+
+
); } @@ -691,6 +794,13 @@ function writingDirection(element: HTMLElement | null): 'ltr' | 'rtl' { * chevron fades out at once and the platter leaves with the screen. A back * swipe leaves it alone until the pop finishes. * + * Under a finger the bars paint no background and no hairline, as iOS 26's + * do. Each screen carries a scroll edge effect: a veil of the body colour + * that comes in once the content has moved 10px under the bar. The veil + * fades for a finger's scroll and rides the screen's card through a push, a + * pop or a back swipe. The bar a card covers is cut at that card's leading + * edge. A mouse keeps the bar's surface and hairline. + * * 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 @@ -871,6 +981,85 @@ export function NavigationStack({ [registry], ); + // Under a finger the bars are iOS 26's: clear, so a covered bar would show + // through the card above it. UIKit's covering view cuts the title under it + // at its leading edge. Here the covered bar's clip box follows the top + // card's leading edge, and the row inside it holds still. At rest the box + // is shut. While the cards travel it moves on their spring, or with the + // finger. The stack reads the touch presentation as each move starts, as + // the swipes do. A mouse keeps opaque bars and the boxes at identity. + const clearBarsRef = useRef(false); + const readClearBars = useCallback(() => { + clearBarsRef.current = isCoarsePointer( + containerRef.current?.ownerDocument.defaultView, + ); + return clearBarsRef.current; + }, []); + /** + * Where the covered bar's box goes so its edge meets the top card's + * leading edge (the top card at `topX`, the covered bar at `underBarX`). + */ + const clipXFor = useCallback((topX: number, underBarX: number) => { + const width = cardsRef.current?.clientWidth ?? 0; + const sign = writingDirection(containerRef.current) === 'rtl' ? -1 : 1; + return topX - underBarX - sign * width; + }, []); + const setClip = useCallback( + (key: string | null, x: number) => { + const layers = layersOf(key); + layers?.barClip?.set({x}); + layers?.barClipContent?.set({x: -x}); + }, + [layersOf], + ); + + const shownBarsRef = useRef>(new Set()); + // A bar that mounts covered parks at the parallax, as `settle` parks a + // covered screen. A pop that reveals a screen two levels down brings one. + // Under a finger it is cut away at the top card's leading edge; under a + // mouse it is whole, under the opaque top bar. A bar that was already shown + // keeps its place, and the transition moves it. This drives the bars' + // compositor animators, the system it syncs. + useLayoutEffect(() => { + const before = shownBarsRef.current; + shownBarsRef.current = new Set( + underKey == null ? [topKey] : [topKey, underKey], + ); + if (underKey == null || before.has(underKey)) { + return; + } + const values = layersAt( + 0, + cardsRef.current?.clientWidth ?? 0, + writingDirection(containerRef.current), + ); + layersOf(underKey)?.bar?.set({x: values.underX}); + setClip(underKey, readClearBars() ? clipXFor(0, values.underX) : 0); + }, [topKey, underKey, layersOf, readClearBars, setClip, clipXFor]); + + const {isTouch} = useTouchPresentation(); + const touchSeenRef = useRef(isTouch); + // The touch presentation can change while a screen is covered (a tablet + // losing its mouse). The bars' backgrounds follow it at once, so the + // covered bar's cut follows it too. A running move reads it again as it + // settles. This drives the bars' compositor animators, the system it syncs. + useLayoutEffect(() => { + if (touchSeenRef.current === isTouch) { + return; + } + touchSeenRef.current = isTouch; + const running = runningRef.current; + if (underKey == null || (running != null && !running.done)) { + return; + } + const values = layersAt( + 0, + cardsRef.current?.clientWidth ?? 0, + writingDirection(containerRef.current), + ); + setClip(underKey, readClearBars() ? clipXFor(0, values.underX) : 0); + }, [isTouch, underKey, readClearBars, setClip, clipXFor]); + /** * 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 @@ -893,12 +1082,20 @@ export function NavigationStack({ 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}); + const underBarX = underBar === 'ride' ? values.underX : 0; + underLayers?.bar?.set({x: underBarX}); underLayers?.dim?.set({opacity: values.dim}); underLayers?.barDim?.set({opacity: values.dim}); + // Under a finger the covered bar is cut where the top card's leading + // edge is; under a mouse both bars are whole. + setClip(top, 0); + setClip( + under, + clearBarsRef.current ? clipXFor(values.topX, underBarX) : 0, + ); progressRef.current = p; }, - [layersOf], + [layersOf, setClip, clipXFor], ); /** @@ -975,6 +1172,57 @@ export function NavigationStack({ ), ); } + if (clearBarsRef.current) { + // Under a finger the covered bar's box rides the top card's leading + // edge on the same spring, from the same start and velocity. The + // difference of the two bars' curves is the same curve. There is no + // clamp: an overshoot past rest stays cut. Reduced Motion's + // cross-fade has no travel: the titles swap at once, as UIKit's do. + const underBarTo = + underBar === 'ride' + ? values.underX + : (underLayers?.bar?.get('x') ?? 0); + const clipTo = clipXFor(values.topX, underBarTo); + setClip(top, 0); + if ( + (topLayers?.card?.reducedMotion({touchRelease: release}) ?? 'off') !== + 'off' + ) { + setClip(under, clipTo); + if (to === 1) { + // A pop: the leaving bar goes at once too. + setClip(top, direction === 'rtl' ? width : -width); + } + } else if (underLayers?.barClip && underLayers.barClipContent) { + const clipVelocity = + velocity == null + ? undefined + : velocity.topX - (underBar === 'ride' ? velocity.underX : 0); + handles.push( + underLayers.barClip.animate( + {x: clipTo}, + { + spring, + velocity: clipVelocity == null ? undefined : {x: clipVelocity}, + }, + {at, touchRelease: release}, + ), + underLayers.barClipContent.animate( + {x: -clipTo}, + { + spring, + velocity: clipVelocity == null ? undefined : {x: -clipVelocity}, + }, + {at, touchRelease: release}, + ), + ); + } + } else { + // Under a mouse both bars are whole, also after a pointer that was + // coarse left a cut. + setClip(top, 0); + setClip(under, 0); + } for (const dim of [underLayers?.dim, underLayers?.barDim]) { if (dim == null) { continue; @@ -1001,7 +1249,7 @@ export function NavigationStack({ results => results.every(Boolean), ); }, - [layersOf], + [layersOf, setClip, clipXFor], ); /** @@ -1064,15 +1312,21 @@ export function NavigationStack({ layers?.dim?.set({opacity: 0}); layers?.bar?.set({x: 0}); layers?.barDim?.set({opacity: 0}); + // A screen on top shows its whole bar, under any pointer. + setClip(key, 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}); + // Under a finger cut away at the top card's leading edge (the top + // card at rest); under a mouse whole, parked under the opaque bar. + // Read again here: the pointer may have changed during the move. + setClip(key, readClearBars() ? clipXFor(0, values.underX) : 0); } }, - [layersOf], + [layersOf, readClearBars, setClip, clipXFor], ); const focusAfter = useCallback( @@ -1127,6 +1381,7 @@ export function NavigationStack({ useLayoutEffect(() => { const {view, fadeBack} = transitionInputsRef.current; const transition = view.transition; + readClearBars(); if (transition.kind === 'none') { // Settle every screen where it rests. view.models.forEach((model, index) => { @@ -1229,6 +1484,7 @@ export function NavigationStack({ animateProgress, focusAfter, layersOf, + readClearBars, setProgress, settle, backControl.animator, @@ -1336,7 +1592,8 @@ export function NavigationStack({ }, grab: (top, under) => { // Grab whatever is moving: the top card's presentation value is the - // progress to continue from. + // progress to continue from. A finger's move starts here. + readClearBars(); const width = cardsRef.current?.clientWidth ?? 0; const x = layersOf(top)?.card?.get('x') ?? 0; const direction = writingDirection(containerRef.current); @@ -1346,6 +1603,8 @@ export function NavigationStack({ layers?.dim?.stop(); layers?.bar?.stop(); layers?.barDim?.stop(); + layers?.barClip?.stop(); + layers?.barClipContent?.stop(); } runningRef.current = null; return progressFromScreen(x, width, direction); diff --git a/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts b/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts index 728ff79304dd3..e4b7fcfcbb719 100644 --- a/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts +++ b/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts @@ -298,6 +298,67 @@ const crit = (response: number, ms: number) => { return 1 - (1 + u) * Math.exp(-u); }; +/** The incoming card's, the covered bar's and its cut box's x and boxes. */ +interface CutLayers { + card: number; + bar: number; + cut: number; + cardBox: {left: number; right: number}; + cutBox: {left: number; right: number}; +} + +const cutLayers = (page: Page, covered: string, incoming: string) => + page.evaluate( + ([coveredKey, incomingKey]): CutLayers | null => { + const x = (element: Element) => { + const value = getComputedStyle(element).translate; + return value === 'none' ? 0 : parseFloat(value); + }; + const cardElement = document.querySelector( + `[data-navigation-screen="${incomingKey}"]`, + ); + const barElement = document.querySelector( + `[data-navigation-bar="${coveredKey}"]`, + ); + const cutElement = barElement?.firstElementChild; + if (cardElement == null || barElement == null || cutElement == null) { + return null; + } + const cardBox = cardElement.getBoundingClientRect(); + const cutBox = cutElement.getBoundingClientRect(); + return { + card: x(cardElement), + bar: x(barElement), + cut: x(cutElement), + cardBox: {left: cardBox.left, right: cardBox.right}, + cutBox: {left: cutBox.left, right: cutBox.right}, + }; + }, + [covered, incoming] as const, + ); + +/** + * How far the covered bar's cut is from the incoming card's leading edge at + * `mid`. It reads the layers' animated `translate`, and each edge's static + * part at `rest`, where box and translate agree. Mid-animation, WebKit can + * report one layer's box a frame late and not the other's. The boxes alone + * can then disagree by a pixel or two while the layers move as one. + */ +const cutGap = ( + mid: CutLayers | null, + rest: CutLayers | null, + direction: 'ltr' | 'rtl', +): number => { + if (mid == null || rest == null) { + return Infinity; + } + const cardEdge = direction === 'rtl' ? 'right' : 'left'; + const cutEdge = direction === 'rtl' ? 'left' : 'right'; + const cardStatic = rest.cardBox[cardEdge] - rest.card; + const cutStatic = rest.cutBox[cutEdge] - rest.bar - rest.cut; + return Math.abs(cutStatic + mid.bar + mid.cut - (cardStatic + mid.card)); +}; + const rowCenter = async (page: Page, name: string) => { const box = await page.getByRole('button', {name}).first().boundingBox(); if (box == null) { @@ -880,7 +941,85 @@ test('a push keeps advancing every frame while the main thread is blocked', asyn expect(proof.verdict.failures, proof.summary).toEqual([]); }); -test('the incoming bar covers the old title while the main thread is blocked', async ({ +// With a mouse the bars are opaque: the incoming one covers the old title. +// Under a finger iOS 26's bars are clear (NavigationStackScrollEdge's proofs) +// and the incoming screen cuts the old title instead (the next test). +test('with a mouse, the incoming bar covers the old title while the main thread is blocked', async ({ + browser, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'screencast frame evidence is Chromium-only in Playwright (WebKit: the iOS simulator rig)', + ); + const {context, page} = await newFinePage(browser); + try { + await openStack(page, 'settings', {pointer: 'mouse'}); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + // 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); + const row = await rowCenter(page, 'General'); + await page.mouse.click(row.x, row.y); + await waitForAnimation(card(page, 'screen-General'), {minProgressMs: 16}); + const block = await blockMainThread(page, 900); + 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(); + } finally { + await context.close(); + } +}); + +/** + * How much of bar `key` its clip box shows inside the stack. It is a + * fraction of the stack's width, rounded to 0.01: 0 cut away, 1 whole. + */ +async function readCut(page: Page, key: string) { + return page.evaluate(k => { + const stack = document + .querySelector('[data-testid="navigation-stack"]') + ?.getBoundingClientRect(); + const box = document + .querySelector(`[data-navigation-bar="${k}"]`) + ?.firstElementChild?.getBoundingClientRect(); + if (stack == null || box == null) { + return {shown: -1}; + } + const shown = + Math.max( + 0, + Math.min(box.right, stack.right) - Math.max(box.left, stack.left), + ) / stack.width; + return {shown: Math.round(shown * 100) / 100}; + }, key); +} + +// Under a finger iOS 26's bars are clear, and the bar a card covers is cut +// at that card's leading edge. So the incoming screen still hides the title +// it slides over, even while the main thread is blocked. +test('under a finger, the incoming screen cuts the old title while the main thread is blocked', async ({ page, browserName, }) => { @@ -889,8 +1028,9 @@ test('the incoming bar covers the old title while the main thread is blocked', a '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. + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(true); await page.locator('[data-navigation-bar="root"] h2').evaluate(title => { const element = title as HTMLElement; element.style.position = 'relative'; @@ -916,7 +1056,7 @@ test('the incoming bar covers the old title while the main thread is blocked', a 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. + // Seen while blocked, then cut before the block ends. expect( during.some(f => f.box != null), trace, @@ -924,6 +1064,140 @@ test('the incoming bar covers the old title while the main thread is blocked', a expect(during.at(-1)?.box ?? null, trace).toBeNull(); }); +test('under a finger the cut rides the incoming card’s leading edge', async ({ + page, +}) => { + const {driver} = await openStack(page, 'settings'); + await driver.tap(await rowCenter(page, 'General')); + await waitForAnimation(card(page, 'screen-General'), {minProgressMs: 16}); + // Mid-push the root's bar shows only left of the incoming card: the cut + // and the card's edge move on one spring. + const mid = await cutLayers(page, 'root', 'screen-General'); + await waitForRest(card(page, 'screen-General')); + const rest = await cutLayers(page, 'root', 'screen-General'); + expect(mid).not.toBeNull(); + expect(rest).not.toBeNull(); + expect(cutGap(mid, rest, 'ltr')).toBeLessThan(2); + expect(await readCut(page, 'root')).toEqual({shown: 0}); + expect(await readCut(page, 'screen-General')).toEqual({shown: 1}); +}); + +test('under a finger in a right-to-left stack, the cut mirrors', async ({ + page, +}) => { + const {driver} = await openStack(page, 'settings'); + await page + .getByTestId('navigation-stack') + .evaluate(element => element.setAttribute('dir', 'rtl')); + await driver.tap(await rowCenter(page, 'General')); + await waitForAnimation(card(page, 'screen-General'), {minProgressMs: 16}); + // The incoming card enters from the left: the root's bar shows only right + // of its trailing edge. + const mid = await cutLayers(page, 'root', 'screen-General'); + await waitForRest(card(page, 'screen-General')); + const rest = await cutLayers(page, 'root', 'screen-General'); + expect(mid).not.toBeNull(); + expect(rest).not.toBeNull(); + expect(cutGap(mid, rest, 'rtl')).toBeLessThan(2); + expect(await readCut(page, 'root')).toEqual({shown: 0}); + expect(await readCut(page, 'screen-General')).toEqual({shown: 1}); +}); + +test('a pointer that turns fine after a push leaves the revealed bar whole', async ({ + page, +}) => { + // A tablet that picks up a trackpad. The push runs under a finger, which + // cuts the root's bar away. Then the pointer is fine and Back pops at once. + const {driver} = await openStack(page, 'settings'); + await driver.tap(await rowCenter(page, 'General')); + await waitForRest(card(page, 'screen-General')); + expect(await readCut(page, 'root')).toEqual({shown: 0}); + await page.evaluate(() => { + const matchMedia = window.matchMedia.bind(window); + window.matchMedia = (query: string) => + query.replace(/\s/g, '') === '(pointer:coarse)' + ? matchMedia('(max-width: 0px)') + : matchMedia(query); + }); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + await page.locator('[data-navigation-back]').click(); + await expect(card(page, 'screen-General')).toHaveCount(0); + await waitForRest(card(page, 'root')); + expect(await readCut(page, 'root')).toEqual({shown: 1}); +}); + +test('a pointer that turns coarse while a screen is covered cuts the covered bar away', async ({ + browser, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'Only Chromium turns the primary pointer coarse mid-test (touch emulation).', + ); + // A tablet that loses its mouse. The push runs under a mouse, so the root's + // bar stays whole under the opaque top bar. Then the pointer turns coarse: + // the bars clear, and the covered bar is cut away at once. + const {context, page} = await newFinePage(browser); + try { + await openStack(page, 'settings', {pointer: 'mouse'}); + const row = await rowCenter(page, 'General'); + await page.mouse.click(row.x, row.y); + await waitForRest(card(page, 'screen-General')); + // The root's bar is there and laid out, and whole at the parallax. + const title = page.locator('[data-navigation-bar="root"] h2'); + expect((await title.boundingBox())?.width ?? 0).toBeGreaterThan(0); + expect((await readCut(page, 'root')).shown).toBeGreaterThan(0.5); + const cdp = await context.newCDPSession(page); + await cdp.send('Emulation.setTouchEmulationEnabled', { + enabled: true, + maxTouchPoints: 1, + }); + await expect + .poll(() => page.evaluate(() => matchMedia('(pointer: coarse)').matches)) + .toBe(true); + await expect.poll(() => readCut(page, 'root')).toEqual({shown: 0}); + expect(await readCut(page, 'screen-General')).toEqual({shown: 1}); + } finally { + await context.close(); + } +}); + +test('under a finger, a pop that reveals a screen two levels down leaves its bar cut away', async ({ + page, +}) => { + // The story opens two screens deep, so the root's bar mounts under General + // only once the pop is over. + await openStack(page, 'pushed'); + await page.locator('[data-navigation-back]').click(); + await expect(card(page, 'screen-About')).toHaveCount(0); + await waitForRest(card(page, 'screen-General')); + // The root's bar is there and laid out, so its cut is a real reading. + await expect(page.locator('[data-navigation-bar="root"]')).toHaveCount(1); + const box = await page + .locator('[data-navigation-bar="root"] h2') + .boundingBox(); + expect(box?.width ?? 0).toBeGreaterThan(0); + expect(await readCut(page, 'root')).toEqual({shown: 0}); + expect(await readCut(page, 'screen-General')).toEqual({shown: 1}); +}); + +test('under a finger, Back reveals the covered bar whole', async ({page}) => { + const {driver} = await openStack(page, 'settings'); + await driver.tap(await rowCenter(page, 'General')); + await waitForRest(card(page, 'screen-General')); + expect(await readCut(page, 'root')).toEqual({shown: 0}); + const back = await page.locator('[data-navigation-back]').boundingBox(); + if (back == null) { + throw new Error('no back button'); + } + await driver.tap({x: back.x + back.width / 2, y: back.y + back.height / 2}); + await expect(card(page, 'screen-General')).toHaveCount(0); + await waitForRest(card(page, 'root')); + expect(await readCut(page, 'root')).toEqual({shown: 1}); +}); + test('under a mouse a drag across the content pops, as a finger’s does', async ({ browser, }) => { @@ -1040,25 +1314,53 @@ test.describe('the bars ride with their screens, as UIKit’s', () => { } }); - test('each bar is opaque and stacks over the one it covers', async ({ + test('with a mouse, each bar is opaque and stacks over the one it covers', async ({ + browser, + }) => { + const {context, page} = await newFinePage(browser); + try { + await openStack(page, 'settings', {pointer: 'mouse'}); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + const row = await rowCenter(page, 'General'); + await page.mouse.click(row.x, row.y); + 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 own element. + background: getComputedStyle( + bar.querySelector('[data-navigation-bar-background]') ?? 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\(/); + } + } finally { + await context.close(); + } + }); + + test('under a finger each bar is clear, and the covered one cut away at rest', 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, - })), + [...document.querySelectorAll('[data-navigation-bar-background]')].map( + background => getComputedStyle(background).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\(/); - } + expect(bars).toEqual(['rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0)']); + // iOS 26 cuts the covered screen's bar at the top card's leading edge. + // At rest nothing of it shows, and the top bar is whole. + expect(await readCut(page, 'root')).toEqual({shown: 0}); + expect(await readCut(page, 'screen-General')).toEqual({shown: 1}); }); test('the covered bar’s dimming ends above the bar’s hairline', async ({ @@ -1067,13 +1369,16 @@ test.describe('the bars ride with their screens, as UIKit’s', () => { 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. + // The hairline is the bar's bottom pixel, which the layers' backgrounds + // leave uncovered. Each layer's dimming sits in its cut row. 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, + dimBottom: + bar + .querySelector('[data-navigation-bar-dim]') + ?.getBoundingClientRect().bottom ?? NaN, })), ); expect(layers.map(layer => layer.key)).toEqual(['root', 'screen-General']); @@ -1314,6 +1619,12 @@ test.describe('edge cases', () => { first?.cards['screen-About'] ?? 0, JSON.stringify(first), ).toBeGreaterThan(width * 0.5); + // Under a finger both end at rest. The screen below is cut away, so the + // root's bar is no longer rendered, and the top bar is whole. + await waitForRest(card(page, 'screen-About')); + expect(await page.locator('[data-navigation-bar="root"]').count()).toBe(0); + expect(await readCut(page, 'screen-General')).toEqual({shown: 0}); + expect(await readCut(page, 'screen-About')).toEqual({shown: 1}); }); test('a sideways drag on a strip that can still scroll scrolls it instead of popping', async ({ diff --git a/packages/lab/src/NavigationStack/__tests__/NavigationStackScrollEdge.interaction.browser.spec.ts b/packages/lab/src/NavigationStack/__tests__/NavigationStackScrollEdge.interaction.browser.spec.ts new file mode 100644 index 0000000000000..2e09aac4254b4 --- /dev/null +++ b/packages/lab/src/NavigationStack/__tests__/NavigationStackScrollEdge.interaction.browser.spec.ts @@ -0,0 +1,331 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file NavigationStackScrollEdge.interaction.browser.spec.ts + * @input The built "Scrolling" NavigationStack story on the touch phone + * profile, programmatic and real-touch scrolls, and the interaction harness + * @output Proofs of the bar's iOS 26 look under a finger. The bar paints no + * background or hairline, and each screen's veil switches at 10px. A push + * and a pop keep each screen's veil, and a finger's scroll fades it. A + * screen a pop reveals shows the veil for its own scroll. On a large-title + * screen the veil comes on as the bar's title takes over. The veil is + * hidden from assistive technology. A mouse keeps the bar's surface and + * runs no veil. + * @position Interaction proof for NavigationStack.tsx and Lab's + * internal/useScrollEdgeEffect.ts, run by `pnpm test:interaction`. The + * phone profile's coarse pointer is the touch case in both engines. + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + animationStoryboard, + drag, + frames, + openStory, + releaseAnimations, + touchDriver, + waitForAnimation, + waitForRest, + withStorybook, +} from '@astryxdesign/interaction-harness'; + +const storybook = withStorybook(test); + +const STORY = 'lab-navigationstack--scrolling'; + +const card = (page: Page, screen: string) => + page.locator(`[data-navigation-screen="${screen}"]`); +const veil = (page: Page, screen: string) => + card(page, screen).locator(':scope > [data-navigation-scroll-edge]'); +const scroller = (page: Page, screen: string) => + card(page, screen).locator(':scope > :first-child'); + +async function presentedOpacity(layer: Locator): Promise { + return layer.evaluate(element => Number(getComputedStyle(element).opacity)); +} + +/** Scrolls a screen, lets the observer report, waits for the fade to end. */ +async function settleAt(page: Page, screen: string, top: number) { + await scroller(page, screen).evaluate((element, y) => { + element.scrollTop = y; + }, top); + await frames(page, 3); + await waitForRest(veil(page, screen)); + return presentedOpacity(veil(page, screen)); +} + +/** + * Scrolls a screen while a finger rests on its content, and lifts the finger + * two frames later, after the observer has reported. The gesture host reads + * the scroll as the finger's, so the veil fades. + */ +async function fingerScrollTo(page: Page, screen: string, top: number) { + await scroller(page, screen).evaluate((element, y) => { + const target = element.lastElementChild ?? element; + const touch = {identifier: 7, clientX: 100, clientY: 400, target}; + const fire = (type: string, touches: (typeof touch)[]) => { + const event = new Event(type, {bubbles: true, cancelable: true}); + Object.defineProperty(event, 'changedTouches', {value: [touch]}); + Object.defineProperty(event, 'touches', {value: touches}); + target.dispatchEvent(event); + }; + fire('touchstart', [touch]); + element.scrollTop = y; + requestAnimationFrame(() => + requestAnimationFrame(() => fire('touchend', [])), + ); + }, top); +} + +async function openStack(page: Page, story = STORY) { + await openStory(page, storybook(), story); + await expect(page.getByTestId('navigation-stack')).toBeVisible(); + await expect(veil(page, 'root')).toBeAttached(); +} + +test('the bar paints no background and no hairline under a finger', async ({ + page, +}) => { + await openStack(page); + const background = await page + .getByTestId('navigation-stack') + .evaluate(stack => { + const bar = stack.firstElementChild as HTMLElement; + const style = getComputedStyle(bar.firstElementChild as HTMLElement); + return { + color: style.backgroundColor, + border: style.borderBottomWidth, + }; + }); + expect(background).toEqual({color: 'rgba(0, 0, 0, 0)', border: '0px'}); +}); + +test('a scroll the program drives switches a screen’s veil at once: off through 10px, on beyond, both ways', async ({ + page, +}) => { + await openStack(page); + const steps: [number, number][] = [ + [0, 0], + [5, 0], + [10, 0], + [11, 1], + [200, 1], + [10, 0], + [0, 0], + ]; + const seen: {top: number; opacity: number}[] = []; + for (const [top, expected] of steps) { + const opacity = await settleAt(page, 'root', top); + seen.push({top, opacity}); + expect(opacity, `${top}px under the bar`).toBe(expected); + // At once: the WebKit workaround (no fade on the program's scroll). + expect( + await veil(page, 'root').evaluate( + element => element.getAnimations().length, + ), + ).toBe(0); + } + test + .info() + .annotations.push({type: 'switch', description: JSON.stringify(seen)}); +}); + +test('a push brings the new screen’s own veil; a pop returns to the scrolled screen’s', async ({ + page, +}) => { + await openStack(page); + expect(await settleAt(page, 'root', 300)).toBe(1); + await page.getByRole('button', {name: /Message 9\b/}).click(); + await expect(card(page, 'screen-Message 9')).toHaveAttribute( + 'data-navigation-top', + 'true', + ); + await waitForRest(card(page, 'screen-Message 9')); + await waitForRest(veil(page, 'screen-Message 9')); + // The new screen sits at its top: its own veil is off. The covered screen + // keeps its own, on. + expect(await presentedOpacity(veil(page, 'screen-Message 9'))).toBe(0); + expect(await presentedOpacity(veil(page, 'root'))).toBe(1); + await page.getByRole('button', {name: 'Inbox'}).click(); + await expect(card(page, 'root')).toHaveAttribute( + 'data-navigation-top', + 'true', + ); + await waitForRest(card(page, 'root')); + expect(await presentedOpacity(veil(page, 'root'))).toBe(1); +}); + +test('a screen a pop reveals shows the veil for its own scroll: off at its top', async ({ + page, +}) => { + // The story opens two screens deep, so the root mounts hidden. + await openStack(page, 'lab-navigationstack--pushed'); + const back = page.locator('[data-navigation-back]'); + await back.click(); + await expect(card(page, 'screen-About')).toHaveCount(0); + await waitForRest(card(page, 'screen-General')); + await back.click(); + await expect(card(page, 'root')).toHaveAttribute( + 'data-navigation-top', + 'true', + ); + await waitForRest(card(page, 'root')); + await waitForRest(veil(page, 'root')); + // The veil is there and laid out, so an opacity of 0 is a real reading. + const box = await veil(page, 'root').boundingBox(); + expect(box?.width ?? 0).toBeGreaterThan(0); + expect(box?.height ?? 0).toBeGreaterThan(0); + expect( + await scroller(page, 'root').evaluate(element => element.scrollTop), + ).toBe(0); + expect(await presentedOpacity(veil(page, 'root'))).toBe(0); +}); + +test('on a large-title screen the veil comes on as the bar’s title takes over', async ({ + page, +}) => { + await openStack(page, 'lab-navigationstack--large-title'); + const geometry = await card(page, 'root').evaluate(element => { + const title = element.querySelector('h1'); + const sentinel = element.querySelector( + '[data-navigation-scroll-edge-sentinel]', + ); + const bar = document.querySelector('[data-navigation-bar="root"]'); + if (title == null || sentinel == null || bar == null) { + return null; + } + const titleBox = title.getBoundingClientRect(); + const sentinelBox = sentinel.getBoundingClientRect(); + return { + titleHeight: Math.round(titleBox.height), + titleBottom: Math.round(titleBox.bottom), + sentinelBottom: Math.round(sentinelBox.bottom), + sentinelHeight: Math.round(sentinelBox.height), + // How far the root scrolls before the large title's bottom meets the + // bar's, where the bar's title takes over. + collapseAt: Math.round( + titleBox.bottom - bar.getBoundingClientRect().bottom, + ), + }; + }); + if (geometry == null) { + throw new Error('no large title, scroll edge sentinel or bar'); + } + const {collapseAt, ...ends} = geometry; + expect(ends.titleHeight).toBeGreaterThan(20); + expect(ends.sentinelHeight).toBe(10); + expect(ends.sentinelBottom).toBe(ends.titleBottom); + expect(collapseAt).toBeGreaterThan(10); + const barTitle = page.locator('[data-navigation-bar="root"] h2'); + // Short of it the large title shows: the bar's title is hidden, no veil. + expect(await settleAt(page, 'root', collapseAt - 4)).toBe(0); + await waitForRest(barTitle); + expect(await presentedOpacity(barTitle)).toBe(0); + // Past it the bar's title shows, over the veil. + expect(await settleAt(page, 'root', collapseAt + 4)).toBe(1); + await waitForRest(barTitle); + expect(await presentedOpacity(barTitle)).toBe(1); +}); + +test('a finger scrolling the screen fades the veil in', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'native scrolling from injected touches is Chromium-only (harness README)', + ); + await openStack(page); + const driver = await touchDriver(page); + await driver.play( + drag({x: 200, y: 560}, {x: 200, y: 460}, {durationMs: 300, restMs: 450}), + ); + await waitForRest(veil(page, 'root')); + const top = await scroller(page, 'root').evaluate( + element => element.scrollTop, + ); + expect(top).toBeGreaterThan(10); + expect(await presentedOpacity(veil(page, 'root'))).toBe(1); +}); + +test('the veil and its sentinel are hidden from assistive technology', async ({ + page, +}) => { + await openStack(page); + const hidden = await card(page, 'root').evaluate(element => { + const layer = element.querySelector('[data-navigation-scroll-edge]'); + const sentinel = element.querySelector( + '[data-navigation-scroll-edge-sentinel]', + ); + return { + layer: layer?.getAttribute('aria-hidden'), + sentinel: sentinel?.getAttribute('aria-hidden'), + pointer: layer == null ? null : getComputedStyle(layer).pointerEvents, + }; + }); + expect(hidden).toEqual({layer: 'true', sentinel: 'true', pointer: 'none'}); +}); + +test.describe('with a mouse', () => { + test.use({hasTouch: false, isMobile: false}); + + test('the bar keeps its surface and hairline and runs no veil', async ({ + page, + }) => { + await openStack(page); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + const background = await page + .getByTestId('navigation-stack') + .evaluate(stack => { + const bar = stack.firstElementChild as HTMLElement; + const style = getComputedStyle(bar.firstElementChild as HTMLElement); + return {color: style.backgroundColor, border: style.borderBottomWidth}; + }); + expect(background.color).not.toBe('rgba(0, 0, 0, 0)'); + expect(background.border).toBe('1px'); + await scroller(page, 'root').evaluate(element => { + element.scrollTop = 200; + }); + await frames(page, 5); + expect( + await veil(page, 'root').evaluate(element => ({ + display: getComputedStyle(element).display, + running: element.getAnimations().length, + })), + ).toEqual({display: 'none', running: 0}); + }); +}); + +test( + 'storyboard: a screen’s veil fading in', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + await openStack(page); + const layer = veil(page, 'root'); + const viewport = page.viewportSize() ?? {width: 402, height: 714}; + const clip = {x: 0, y: 0, width: viewport.width, height: 120}; + await fingerScrollTo(page, 'root', 120); + await waitForAnimation(layer); + const {storyboard} = await animationStoryboard(page, { + name: 'navigation-stack-scroll-edge-appear', + clip, + scope: layer, + measure: async () => ({opacity: await presentedOpacity(layer)}), + columns: 6, + cellScale: 0.5, + }); + await releaseAnimations(page, {finish: true}); + await storyboard.write(testInfo); + const ins = storyboard.frames.map(f => f.data.opacity as number); + expect(ins[0]).toBeLessThan(0.05); + expect(ins.every((o, i) => i === 0 || o >= ins[i - 1] - 0.002)).toBe(true); + expect(ins.at(-1)).toBeGreaterThan(0.99); + }, +); diff --git a/packages/lab/src/NavigationStack/navigationMotion.ts b/packages/lab/src/NavigationStack/navigationMotion.ts index 725bc9e4ee321..fdc981d130063 100644 --- a/packages/lab/src/NavigationStack/navigationMotion.ts +++ b/packages/lab/src/NavigationStack/navigationMotion.ts @@ -5,7 +5,8 @@ * @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 + * only NavigationStack reads, each with its measurement. `bars`: iOS 26's + * scroll edge effect under the bar. * @position NavigationStack's motion table. Core's tables keep the values * Core's own components read. */ @@ -103,3 +104,86 @@ export const springs = { */ navigationBackButton: {response: 0.4, dampingRatio: 1}, } as const; + +/** + * iOS 26.2's bars paint no background. The scroll view's edge effect + * separates a bar from the content under it: a veil of one colour, with + * nothing blurred. Its colour is a theme value; this table holds its shape + * and its timing. Lengths are in pt (CSS px). + */ +export const bars = { + scrollEdgeEffect: { + /** + * The veil is off while the content sits at most this far past its rest + * offset, and on beyond it. It is a switch, not a ramp, with no + * hysteresis. Overscroll keeps it off. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, content offset stepped from +7.5 to +12.5 pt past + * rest in 0.25 pt steps, ScrollEdgeEffectView model and presentation + * opacity read after each step and 500 ms later, Oct 23 2026 + */ + switchPt: 10, + /** + * The veil fading in as the content passes the switch: critically + * damped, response 0.2 s. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, `-[CALayer addAnimation:forKey:]` hooked on the effect + * view while crossing the switch (opacity, mass 1, stiffness 986.96, + * damping 62.83, duration 0.294), and its presentation opacity sampled + * every frame through a 100 pt/s HID drag, Oct 23 2026 + */ + appear: {mass: 1, stiffness: 986.96, damping: 62.83}, + /** + * The veil fading out as the content comes back over the switch: + * critically damped, response 0.35 s. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, `-[CALayer addAnimation:forKey:]` hooked on the effect + * view while crossing the switch back (opacity, mass 1, stiffness + * 322.27, damping 35.90, duration 0.514), and its presentation opacity + * sampled every frame through the drag back to rest, Oct 23 2026 + */ + disappear: {mass: 1, stiffness: 322.27, damping: 35.9}, + /** + * How far the soft edge reaches below the bar's bottom edge. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, ScrollEdgeEffectView frame (0, 0, 402, 170.8) under a + * standard navigation bar at y 62, height 54, Oct 23 2026 + */ + softExtentPt: 54.8, + veil: { + /** + * UIKit's highest veil alpha, in light and dark mode alike. iOS adapts + * the veil to the content's luminance. The web veil takes the bar's + * theme colour and plays 0.95, so a bar's title keeps 4.5:1 over + * bright content. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, screenshots of solid black, #808080 and white + * content under the effect read per pt row (y 0–180, light and dark, + * with and without a title), and the LuminanceAdjustment layer's + * opacity (0.85 in both modes), Oct 23 2026 + */ + maxAlpha: 0.85, + /** + * Under a titled bar, the veil's edge is half-transparent this far + * above the bottom of the bar's content. An expanded large title sits + * outside the veil. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, PocketMask's ShadowLayer frame in window coordinates + * with an inline title and with a collapsed large title (bottom edge + * at y 106), with no bar content and with an expanded large title + * (y 51), Oct 23 2026 + */ + edgeAboveContentBottomPt: 10, + /** + * How soft the edge is under a titled bar. The veil's alpha is + * `maxAlpha × (1 − Φ((y − edge) / softnessPt))`, with Φ the standard + * normal CDF. Nothing behind the veil is blurred. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, the ShadowLayer's shadowRadius (18 with a title, 24 + * without), per-pt-row profiles, 1 pt stripe contrast per row, + * Oct 23 2026 + */ + softnessPt: 18, + }, + }, +} as const; diff --git a/packages/lab/src/internal/__tests__/coarsePointer.ts b/packages/lab/src/internal/__tests__/coarsePointer.ts new file mode 100644 index 0000000000000..e873ccf27a45c --- /dev/null +++ b/packages/lab/src/internal/__tests__/coarsePointer.ts @@ -0,0 +1,35 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file coarsePointer.ts + * @input jsdom's window and Core's touch query (its internal touch entry) + * @output coarsePrimaryPointer(): a phone's primary pointer, until restored + * @position Test helper of packages/lab/src/internal. jsdom has no + * matchMedia, and Core's gesture host listens only under a coarse pointer. + */ + +import {TOUCH_QUERY} from '@astryxdesign/core/internal/touch'; + +/** The primary pointer is coarse until the returned restore runs. */ +export function coarsePrimaryPointer(): () => void { + const hadOwn = Object.prototype.hasOwnProperty.call(window, 'matchMedia'); + const original = window.matchMedia; + window.matchMedia = (query: string) => + ({ + matches: query.trim() === TOUCH_QUERY, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + }) as unknown as MediaQueryList; + return () => { + if (hadOwn) { + window.matchMedia = original; + } else { + delete (window as {matchMedia?: unknown}).matchMedia; + } + }; +} diff --git a/packages/lab/src/internal/useScrollEdgeEffect.test.tsx b/packages/lab/src/internal/useScrollEdgeEffect.test.tsx new file mode 100644 index 0000000000000..59326c1e2c053 --- /dev/null +++ b/packages/lab/src/internal/useScrollEdgeEffect.test.tsx @@ -0,0 +1,757 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file useScrollEdgeEffect.test.tsx + * @input vitest (jsdom), React Testing Library, a recording + * IntersectionObserver, a recording animator and Core's gesture host + * @output The effect's decisions: what it observes, against which root, and + * the props it hands out. A finger's scroll fades and the program's + * switches. The layer's promotion and the veil's literals follow the bars + * table. + * @position Unit tests of packages/lab/src/internal/useScrollEdgeEffect.ts. + * NavigationStackScrollEdge.interaction.browser.spec.ts proves the fade. + */ + +import {readFileSync} from 'node:fs'; +import {join} from 'node:path'; +import * as stylex from '@stylexjs/stylex'; +import type {StyleXStyles} from '@stylexjs/stylex'; +import {act, cleanup, render, screen} from '@testing-library/react'; +import {useRef} from 'react'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {getGestureHost} from '@astryxdesign/core/internal/touch'; +import type * as TouchEntry from '@astryxdesign/core/internal/touch'; +import type * as CoreUtils from '@astryxdesign/core/utils'; +import {bars} from '../NavigationStack/navigationMotion'; +import {coarsePrimaryPointer} from './__tests__/coarsePointer'; +import {useScrollEdgeEffect} from './useScrollEdgeEffect'; + +const testStyles = stylex.create({ + staticSentinel: { + insetBlockStart: 'auto', + insetInlineStart: 'auto', + }, +}); + +const animator = { + set: vi.fn(), + animate: vi.fn(), + /** The layer, where a test attaches it (the mocked ref attaches nothing). */ + element: null as HTMLElement | null, +}; + +vi.mock('./useMotionEngine', () => ({ + useMotionEngine: () => ({ref: () => {}, animator}), +})); + +/** + * Core's shared resize observer, as the hook subscribes to it. Like Core's, + * it calls back once as it subscribes. + */ +const resize = {callbacks: [] as Array<() => void>, stops: 0}; +vi.mock('@astryxdesign/core/utils', async importOriginal => ({ + ...(await importOriginal()), + observeResize: (_element: Element, callback: () => void) => { + resize.callbacks.push(callback); + callback(); + return () => { + resize.stops += 1; + }; + }, +})); + +/** The touch presentation the hook sees: a finger unless a test says otherwise. */ +const pointer = {isTouch: true}; +/** + * Core's finger-scroll hook: what the hook asks it to watch, and whether the + * scroll now moving is a finger's. + */ +const host = { + isFinger: true, + watched: [] as unknown[], + /** The hook's latest end call, as the real one keeps it. */ + onEnd: null as (() => void) | null, +}; +/** useFingerScroll's reader is stable across renders, as the real one. */ +const readFingerScroll = () => host.isFinger; +/** The finger-scroll hook saying that the finger's scroll has ended. */ +function endFingerScroll() { + host.isFinger = false; + act(() => { + host.onEnd?.(); + }); +} +vi.mock('@astryxdesign/core/internal/touch', async importOriginal => ({ + ...(await importOriginal()), + useTouchPresentation: () => ({ + isTouch: pointer.isTouch, + isCompact: true, + isCompactTouch: pointer.isTouch, + }), + useFingerScroll: (scroller: unknown, options?: {onEnd?: () => void}) => { + host.watched.push(scroller); + host.onEnd = options?.onEnd ?? null; + return readFingerScroll; + }, +})); + +/** The node the hook last asked useFingerScroll to watch, if any. */ +function watchedNode(): Document | Element | null { + const last = host.watched.at(-1) as + Document | {current: Element | null} | undefined; + return last instanceof Document ? last : (last?.current ?? null); +} + +class RecordingObserver { + static instances: RecordingObserver[] = []; + readonly observed: Element[] = []; + disconnected = false; + constructor( + readonly callback: IntersectionObserverCallback, + readonly options: IntersectionObserverInit = {}, + ) { + RecordingObserver.instances.push(this); + } + observe(target: Element) { + this.observed.push(target); + } + readonly unobserved: Element[] = []; + unobserve(target: Element) { + this.unobserved.push(target); + } + disconnect() { + this.disconnected = true; + } + takeRecords(): IntersectionObserverEntry[] { + return []; + } + /** + * Reports the sentinel intersecting its root (true) or gone (false), with + * the root rectangle's top when given (the engine's, margin applied) and + * its height. + */ + report(isIntersecting: boolean, rootTop?: number, rootHeight = 400) { + act(() => { + this.callback( + [ + { + isIntersecting, + rootBounds: + rootTop == null + ? null + : ({top: rootTop, height: rootHeight} as DOMRectReadOnly), + } as IntersectionObserverEntry, + ], + this as unknown as IntersectionObserver, + ); + }); + } +} + +/** A touch event on `target` from finger 1 (down for touchstart). */ +function touch(type: 'touchstart' | 'touchend', target: Element) { + const event = new Event(type, {bubbles: true, cancelable: true}); + const finger = {identifier: 1, clientX: 10, clientY: 10, target}; + Object.defineProperty(event, 'changedTouches', {value: [finger]}); + Object.defineProperty(event, 'touches', { + value: type === 'touchstart' ? [finger] : [], + }); + act(() => { + target.dispatchEvent(event); + }); +} + +/** + * Takes `onscrollend` off the window, as in a browser that sends no + * `scrollend`; returns the restore. + */ +function withoutScrollEnd(): () => void { + const own = Object.getOwnPropertyDescriptor(window, 'onscrollend'); + const proto = Object.getPrototypeOf(window) as object; + const inherited = Object.getOwnPropertyDescriptor(proto, 'onscrollend'); + Reflect.deleteProperty(window, 'onscrollend'); + Reflect.deleteProperty(proto, 'onscrollend'); + expect('onscrollend' in window).toBe(false); + return () => { + if (inherited != null) { + Object.defineProperty(proto, 'onscrollend', inherited); + } + if (own != null) { + Object.defineProperty(window, 'onscrollend', own); + } + }; +} + +beforeEach(() => { + animator.element = null; + pointer.isTouch = true; + host.isFinger = true; + host.watched = []; + RecordingObserver.instances = []; + host.onEnd = null; + resize.callbacks = []; + resize.stops = 0; + animator.set.mockClear(); + animator.animate.mockClear(); + vi.stubGlobal('IntersectionObserver', RecordingObserver); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +let renders = 0; + +function Bar({ + enabled, + inContainer = false, + sentinelKey = 'a', + rootInset, + color, + sentinelXstyle, +}: { + enabled: boolean; + inContainer?: boolean; + sentinelKey?: string; + rootInset?: number; + color?: string; + sentinelXstyle?: StyleXStyles; +}) { + renders += 1; + const containerRef = useRef(null); + const {layerProps, sentinelProps} = useScrollEdgeEffect({ + enabled, + root: inContainer ? containerRef : undefined, + rootInset, + edge: '44px', + color, + sentinelXstyle, + springs: bars.scrollEdgeEffect, + }); + return ( +
+
+
+
+ ); +} + +/** Gives the test's scroller a layout: jsdom gives every element height 0. */ +function withLayout(container: HTMLElement, top = 16) { + Object.defineProperty(container, 'clientHeight', { + configurable: true, + value: 500, + }); + vi.spyOn(container, 'getBoundingClientRect').mockReturnValue({ + top, + } as DOMRect); +} + +const observer = () => { + const instance = RecordingObserver.instances.at(-1); + if (instance == null) { + throw new Error('no observer'); + } + return instance; +}; + +describe('useScrollEdgeEffect', () => { + it('observes the sentinel against its own document, at threshold 0', () => { + const {getByTestId} = render(); + expect(observer().observed).toEqual([getByTestId('sentinel')]); + expect(observer().options.root).toBe(document); + expect(observer().options.threshold).toBe(0); + }); + + it('observes against the scroll container when given one', () => { + const {getByTestId} = render(); + expect(observer().options.root).toBe(getByTestId('container')); + }); + + it('takes the inset of a bar that overlays its scroller off the root', () => { + render(); + expect(observer().options.rootMargin).toBe('-44px 0px 0px 0px'); + }); + + it('observes the page with no margin', () => { + render(); + expect(observer().options.rootMargin).toBe('0px 0px 0px 0px'); + }); + + it('measures the root on the first report and, where the engine starts it at the content box, observes again from the padding edge', () => { + // WebKit (iOS 26.2 Safari) starts a scroll container's root rectangle at + // its content box. Here that is below a 44px top padding: the first + // report's root top is the padding edge + 44 (padding) + 44 (the inset). + const {getByTestId} = render(); + withLayout(getByTestId('container')); + const first = observer(); + first.report(true, 16 + 44 + 44); + // Not acted on: measured from the content box. + expect(animator.set).not.toHaveBeenCalled(); + expect(first.disconnected).toBe(true); + const second = observer(); + expect(second).not.toBe(first); + expect(second.options.rootMargin).toBe('0px 0px 0px 0px'); + expect(second.observed).toEqual([getByTestId('sentinel')]); + // Its first report puts the effect in place at once. + second.report(true, 16 + 44); + expect(animator.set).toHaveBeenLastCalledWith( + {opacity: 0}, + {promote: false}, + ); + expect(RecordingObserver.instances).toHaveLength(2); + }); + + it('keeps the first observer where the engine starts the root at the padding edge', () => { + // Chromium: the root rectangle is the padding box. + const {getByTestId} = render(); + withLayout(getByTestId('container')); + observer().report(false, 16 + 44); + expect(RecordingObserver.instances).toHaveLength(1); + expect(animator.set).toHaveBeenLastCalledWith( + {opacity: 1}, + {promote: false}, + ); + }); + + it('measures nothing while the scroller has no layout, and observes again once it has one', () => { + // A stack in a hidden panel: the scroller and its root rectangle have no + // size, so the first report holds nothing to measure. + const {getByTestId} = render(); + const first = observer(); + first.report(false, 0, 0); + expect(animator.set).not.toHaveBeenCalled(); + // The call as it subscribes finds no size: it neither stops the wait nor + // observes again. + expect(first.disconnected).toBe(false); + expect(resize.callbacks).toHaveLength(1); + expect(resize.stops).toBe(0); + // A resize that leaves it without layout changes nothing. + act(() => resize.callbacks[0]()); + expect(RecordingObserver.instances).toHaveLength(1); + // Shown: a new observer from the padding edge reports at once, and the + // veil is off at rest. + withLayout(getByTestId('container')); + act(() => resize.callbacks[0]()); + expect(resize.stops).toBe(1); + expect(first.disconnected).toBe(true); + const second = observer(); + expect(second).not.toBe(first); + expect(second.options.rootMargin).toBe('-44px 0px 0px 0px'); + second.report(true, 16 + 44); + expect(RecordingObserver.instances).toHaveLength(2); + expect(animator.set).toHaveBeenLastCalledWith( + {opacity: 0}, + {promote: false}, + ); + }); + + it('measures a laid-out scroller whose root rectangle has no height, with no wait', () => { + // WebKit's content-box root for a scroller no taller than its 44px top + // padding: the rectangle has no height, but its top is a real reading. + const {getByTestId} = render(); + withLayout(getByTestId('container')); + const first = observer(); + first.report(true, 16 + 44 + 44, 0); + expect(resize.callbacks).toHaveLength(0); + expect(first.disconnected).toBe(true); + expect(observer().options.rootMargin).toBe('0px 0px 0px 0px'); + }); + + it('hands out decorative layer and sentinel props, sized by edge', () => { + const {getByTestId} = render(); + const layer = getByTestId('layer'); + expect(layer.getAttribute('aria-hidden')).toBe('true'); + expect(getByTestId('sentinel').getAttribute('aria-hidden')).toBe('true'); + // The veil's colour and height are runtime values, StyleX custom + // properties on the element. The height is the soft extent past the + // bar's bottom, and the bar's bottom under Reduce Transparency. + const style = layer.getAttribute('style') ?? ''; + expect(style).toContain('rgb(1, 2, 3)'); + expect(style).toContain('calc(44px + 54.8px)'); + expect(style).toContain('44px'); + }); + + it("adds the caller's sentinel styles, e.g. its static position", () => { + const plain = render() + .getByTestId('sentinel') + .getAttribute('class'); + cleanup(); + const placed = render( + , + ) + .getByTestId('sentinel') + .getAttribute('class'); + expect(placed).not.toBe(plain); + for (const name of ( + stylex.props(testStyles.staticSentinel).className ?? '' + ).split(' ')) { + expect(placed?.split(' ')).toContain(name); + } + }); + + it('defaults the veil to the body colour', () => { + const {getByTestId} = render(); + expect(getByTestId('layer').getAttribute('style')).toContain( + 'var(--color-background-body)', + ); + }); + + it('puts the first report in place without a fade', () => { + render(); + observer().report(true); + expect(animator.set).toHaveBeenLastCalledWith( + {opacity: 0}, + {promote: false}, + ); + expect(animator.animate).not.toHaveBeenCalled(); + }); + + it('shows the effect at once when the page loads scrolled', () => { + render(); + observer().report(false); + expect(animator.set).toHaveBeenLastCalledWith( + {opacity: 1}, + {promote: false}, + ); + expect(animator.animate).not.toHaveBeenCalled(); + }); + + it('fades in on the appear spring and out on the disappear spring under a finger', () => { + render(); + observer().report(true); + observer().report(false); + expect(animator.animate).toHaveBeenLastCalledWith( + {opacity: 1}, + {spring: bars.scrollEdgeEffect.appear}, + ); + // Back before the fade ended: the animator turns it around. + observer().report(true); + expect(animator.animate).toHaveBeenLastCalledWith( + {opacity: 0}, + {spring: bars.scrollEdgeEffect.disappear}, + ); + expect(animator.animate).toHaveBeenCalledTimes(2); + }); + + it('ignores a report that changes nothing', () => { + render(); + observer().report(true); + observer().report(false); + observer().report(false); + expect(animator.animate).toHaveBeenCalledTimes(1); + }); + + // On iOS 26.2, a fade that starts as the program's scroll crosses the + // switch blanks the sticky bar's items. + it('switches at once, without a fade, for a scroll the program drives', () => { + host.isFinger = false; + render(); + observer().report(true); + observer().report(false); + expect(animator.set).toHaveBeenLastCalledWith( + {opacity: 1}, + {promote: false}, + ); + observer().report(true); + expect(animator.set).toHaveBeenLastCalledWith( + {opacity: 0}, + {promote: false}, + ); + expect(animator.animate).not.toHaveBeenCalled(); + }); + + it('fades for a finger and switches for the program within one page', () => { + render(); + observer().report(true); + // A finger scrolls the content under the bar… + observer().report(false); + expect(animator.animate).toHaveBeenCalledTimes(1); + // …and a status-bar tap brings it back. + host.isFinger = false; + observer().report(true); + expect(animator.set).toHaveBeenLastCalledWith( + {opacity: 0}, + {promote: false}, + ); + expect(animator.animate).toHaveBeenCalledTimes(1); + }); + + it('watches the page’s finger scrolls, or the scroll container’s', () => { + const {unmount} = render(); + expect(watchedNode()).toBe(document); + unmount(); + render(); + expect(watchedNode()).toBe(screen.getByTestId('container')); + }); + + // The sentinel lives in a ref, not React state. + it('attaches the sentinel without re-rendering the host', () => { + renders = 0; + render(); + expect(renders).toBe(1); + expect(observer().observed).toEqual([screen.getByTestId('sentinel')]); + }); + + // The layer is composited only while a finger works the scroller. The + // program's switch writes no compositing layer. + it('a scroll the program drives switches the layer without promotion', () => { + host.isFinger = false; + render(); + observer().report(true); + observer().report(false); + expect(animator.set).toHaveBeenLastCalledWith( + {opacity: 1}, + {promote: false}, + ); + expect(animator.animate).not.toHaveBeenCalled(); + }); + + // The gesture host listens only where the primary pointer is coarse, and + // jsdom has no matchMedia. + describe('under a coarse primary pointer', () => { + let restorePointer: () => void = () => {}; + beforeEach(() => { + restorePointer = coarsePrimaryPointer(); + }); + afterEach(() => { + restorePointer(); + }); + + it('in a scroll container, a finger’s landing composites the layer until it lifts', () => { + host.isFinger = false; + const {getByTestId} = render(); + const layer = getByTestId('layer'); + animator.element = layer; + const promotion = () => + layer.style.getPropertyValue('--_scroll-edge-will-change'); + expect(promotion()).toBe(''); + touch('touchstart', getByTestId('sentinel')); + expect(promotion()).toBe('opacity'); + touch('touchend', getByTestId('sentinel')); + expect(promotion()).toBe(''); + }); + + it('keeps the layer composited through the finger’s momentum, until its scroll ends', () => { + const {getByTestId} = render(); + const layer = getByTestId('layer'); + animator.element = layer; + const promotion = () => + layer.style.getPropertyValue('--_scroll-edge-will-change'); + touch('touchstart', getByTestId('sentinel')); + // Lifted while its scroll still moves (useFingerScroll still reads it). + touch('touchend', getByTestId('sentinel')); + expect(promotion()).toBe('opacity'); + endFingerScroll(); + expect(promotion()).toBe(''); + }); + + // Where the browser sends no `scrollend`, the finger-scroll hook times + // the end itself. The effect keeps no timer: only the hook's end call + // drops the layer. + it('drops the layer only when the finger-scroll hook says the scroll ended, with no timer of its own', () => { + vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout']}); + const restoreScrollEnd = withoutScrollEnd(); + try { + const {getByTestId} = render(); + const container = getByTestId('container'); + const layer = getByTestId('layer'); + animator.element = layer; + const promotion = () => + layer.style.getPropertyValue('--_scroll-edge-will-change'); + touch('touchstart', getByTestId('sentinel')); + container.dispatchEvent(new Event('scroll')); + // Lifted mid-fling: its momentum still scrolls. + touch('touchend', getByTestId('sentinel')); + act(() => { + vi.advanceTimersByTime(1000); + }); + expect(promotion()).toBe('opacity'); + expect(vi.getTimerCount()).toBe(0); + endFingerScroll(); + expect(promotion()).toBe(''); + } finally { + restoreScrollEnd(); + vi.useRealTimers(); + } + }); + + it('adds no scroll listener of its own however many screens run it', () => { + // The gesture host's own listeners start with its first retain. Take + // it first, so that only the hook's are counted. + const releaseHost = getGestureHost(document).retain(); + const onDocument = vi.spyOn(document, 'addEventListener'); + const onWindow = vi.spyOn(window, 'addEventListener'); + const scrollTypes = (spy: typeof onWindow) => + spy.mock.calls + .map(([type]) => type) + .filter(type => type === 'scroll' || type === 'scrollend'); + const three = () => ( + <> + + + + + ); + try { + render(three()); + expect(scrollTypes(onDocument)).toEqual([]); + expect(scrollTypes(onWindow)).toEqual([]); + cleanup(); + onWindow.mockClear(); + // Where the browser sends no `scrollend`, nothing changes here: the + // finger-scroll hook times the end. + const restoreScrollEnd = withoutScrollEnd(); + try { + render(three()); + expect(scrollTypes(onDocument)).toEqual([]); + expect(scrollTypes(onWindow)).toEqual([]); + } finally { + restoreScrollEnd(); + } + } finally { + onDocument.mockRestore(); + onWindow.mockRestore(); + releaseHost(); + } + }); + }); + + it('with a mouse a finger never composites the layer', () => { + pointer.isTouch = false; + const restorePointer = coarsePrimaryPointer(); + try { + const {getByTestId} = render(); + const layer = getByTestId('layer'); + animator.element = layer; + touch('touchstart', getByTestId('sentinel')); + expect(layer.style.getPropertyValue('--_scroll-edge-will-change')).toBe( + '', + ); + touch('touchend', getByTestId('sentinel')); + } finally { + restorePointer(); + } + }); + + it('moves the observer to a replacement sentinel node', () => { + const {rerender} = render(); + const first = screen.getByTestId('sentinel'); + const instance = observer(); + rerender(); + const second = screen.getByTestId('sentinel'); + expect(second).not.toBe(first); + expect(instance.unobserved).toContain(first); + expect(instance.observed.at(-1)).toBe(second); + expect(RecordingObserver.instances.at(-1)).toBe(instance); + }); + + it('observes nothing with a mouse', () => { + pointer.isTouch = false; + expect(window.matchMedia('(pointer: coarse)').matches).toBe(false); + render(); + expect(RecordingObserver.instances).toHaveLength(0); + // Nothing is watched: a mouse costs no touch work. + expect(watchedNode()).toBeNull(); + expect(animator.animate).not.toHaveBeenCalled(); + }); + + it('observes nothing while disabled', () => { + render(); + expect(RecordingObserver.instances).toHaveLength(0); + }); + + it('stops observing and turns transparent when disabled', () => { + const {rerender} = render(); + const first = observer(); + first.report(false); + rerender(); + expect(first.disconnected).toBe(true); + expect(watchedNode()).toBeNull(); + expect(animator.set).toHaveBeenLastCalledWith( + {opacity: 0}, + {promote: false}, + ); + }); + + it('does nothing where IntersectionObserver is missing', () => { + vi.stubGlobal('IntersectionObserver', undefined); + expect(() => render()).not.toThrow(); + expect(animator.set).not.toHaveBeenCalled(); + }); +}); + +describe('the veil follows the constants table', () => { + const source = readFileSync( + join(__dirname, 'useScrollEdgeEffect.ts'), + 'utf8', + ); + + /** The literal block of `styles.` in useScrollEdgeEffect.ts. */ + function styleBlock(name: string): string { + const start = source.indexOf(`\n ${name}: {`); + expect(start, `styles.${name} not found`).toBeGreaterThan(-1); + const end = source.indexOf('\n },', start); + return source.slice(start, end); + } + + // The veil's edge is the bar's bottom. The soft extent reaches + // `softExtentPt` past it, so the edge is that far above the layer's bottom. + const edgeAboveBottom = bars.scrollEdgeEffect.softExtentPt; + // UIKit's edge sits `veil.edgeAboveContentBottomPt` higher; the stops are + // sampled around it. + const {edgeAboveContentBottomPt} = bars.scrollEdgeEffect.veil; + + it('the layer reaches softExtentPt past the bar; Reduce Transparency ends it at the bar', () => { + expect(source).toContain( + 'dynamicStyles.geometry(`calc(${edge} + ' + + edgeAboveBottom + + 'px)`, edge, color)', + ); + }); + + it('the layer’s will-change follows the hook’s promotion property', () => { + expect(styleBlock('layer')).toContain( + "willChange: 'var(--_scroll-edge-will-change, auto)',", + ); + }); + + it('the sentinel is switchPt tall', () => { + expect(styleBlock('sentinel')).toContain( + `height: ${bars.scrollEdgeEffect.switchPt},`, + ); + }); + + // Denser than UIKit's 0.85: 0.95, with the edge at the bar's bottom. A + // bar's title keeps 4.5:1 over the brightest scrolled content (WCAG 1.4.3). + it('the veil is 0.95 × (1 − Φ((y − edge) / softness)), sampled every 6px over ±3σ', () => { + const maxAlpha = 0.95; + const {softnessPt} = bars.scrollEdgeEffect.veil; + expect(maxAlpha).toBeGreaterThan(bars.scrollEdgeEffect.veil.maxAlpha); + const uikitEdge = edgeAboveBottom + edgeAboveContentBottomPt; + const stops: string[] = []; + for (let d = -3 * softnessPt; d <= 3 * softnessPt; d += 6) { + const alpha = + maxAlpha * (1 - normalCdf((d - edgeAboveContentBottomPt) / softnessPt)); + const offset = Math.round((uikitEdge - d) * 10) / 10; + stops.push(`rgb(0 0 0 / ${alpha.toFixed(3)}) calc(100% - ${offset}px)`); + } + expect(styleBlock('layer')).toContain( + `'linear-gradient(to bottom, ${stops.join(', ')})'`, + ); + }); +}); + +/** Standard normal CDF, by Simpson integration of the density (oracle). */ +function normalCdf(z: number): number { + const n = 2000; + const h = Math.abs(z) / n; + let sum = 0; + for (let i = 0; i <= n; i++) { + const t = i * h; + const weight = i === 0 || i === n ? 1 : i % 2 === 1 ? 4 : 2; + sum += weight * Math.exp((-t * t) / 2); + } + const half = (sum * h) / 3 / Math.sqrt(2 * Math.PI); + return z >= 0 ? 0.5 + half : 0.5 - half; +} diff --git a/packages/lab/src/internal/useScrollEdgeEffect.ts b/packages/lab/src/internal/useScrollEdgeEffect.ts new file mode 100644 index 0000000000000..4692d952a2089 --- /dev/null +++ b/packages/lab/src/internal/useScrollEdgeEffect.ts @@ -0,0 +1,357 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useScrollEdgeEffect.ts + * @input React, StyleX, IntersectionObserver, Lab's motion engine, and + * Core's gesture host, finger-scroll hook (with its end call), resize + * observer, touch presentation and colour tokens + * @output useScrollEdgeEffect: props for a bar's scroll edge veil and for the + * sentinel that switches it, fading on the caller's springs + * @position Lab's iOS 26 bar look under a finger, for NavigationStack. Lab's + * entry point does not export it. With a mouse it observes nothing. + * + * SYNC: When modified, update useScrollEdgeEffect.test.tsx and NavigationStack. + */ + +import * as stylex from '@stylexjs/stylex'; +import type {StyleXStyles} from '@stylexjs/stylex'; +import {useCallback, useEffect, useRef, type RefObject} from 'react'; +import { + getGestureHost, + useFingerScroll, + useTouchPresentation, + type SpringDescription, +} from '@astryxdesign/core/internal/touch'; +import {colorVars} from '@astryxdesign/core/theme/tokens.stylex'; +import {observeResize} from '@astryxdesign/core/utils'; +import {useMotionEngine} from './useMotionEngine'; + +/** No scroller: nothing is watched (a mouse, or the effect is off). */ +const NO_SCROLLER: RefObject = {current: null}; + +/** + * The private custom property the layer's `will-change` reads: `opacity` + * while a finger works the scroller, unset otherwise. Only this hook sets it, + * inline; it is not theme data. + */ +export const SCROLL_EDGE_LAYER_PROMOTION = '--_scroll-edge-will-change'; + +const styles = stylex.create({ + // The veil: one colour, never a blur. Its mask is + // 0.95 × (1 − Φ((y − edge) / 18px)), half strength at `edge`, sampled every + // 6px over ±3σ; useScrollEdgeEffect.test.tsx recomputes it. It is denser + // than UIKit's 0.85, so a bar's title keeps 4.5:1 over bright content. + layer: { + display: { + default: 'none', + '@media (pointer: coarse)': 'block', + }, + position: 'absolute', + insetInline: 0, + insetBlockStart: 0, + pointerEvents: 'none', + opacity: 0, + // Composited only while a finger works the scroller. On iOS 26.2, a + // composited layer under a sticky bar blanks the bar's items when the + // program scrolls back to the top. + willChange: 'var(--_scroll-edge-will-change, auto)', + maskImage: { + default: + 'linear-gradient(to bottom, rgb(0 0 0 / 0.950) calc(100% - 118.8px), rgb(0 0 0 / 0.949) calc(100% - 112.8px), rgb(0 0 0 / 0.948) calc(100% - 106.8px), rgb(0 0 0 / 0.945) calc(100% - 100.8px), rgb(0 0 0 / 0.938) calc(100% - 94.8px), rgb(0 0 0 / 0.922) calc(100% - 88.8px), rgb(0 0 0 / 0.893) calc(100% - 82.8px), rgb(0 0 0 / 0.845) calc(100% - 76.8px), rgb(0 0 0 / 0.772) calc(100% - 70.8px), rgb(0 0 0 / 0.675) calc(100% - 64.8px), rgb(0 0 0 / 0.559) calc(100% - 58.8px), rgb(0 0 0 / 0.433) calc(100% - 52.8px), rgb(0 0 0 / 0.312) calc(100% - 46.8px), rgb(0 0 0 / 0.207) calc(100% - 40.8px), rgb(0 0 0 / 0.127) calc(100% - 34.8px), rgb(0 0 0 / 0.071) calc(100% - 28.8px), rgb(0 0 0 / 0.036) calc(100% - 22.8px), rgb(0 0 0 / 0.017) calc(100% - 16.8px), rgb(0 0 0 / 0.007) calc(100% - 10.8px))', + // Reduce Transparency: an opaque band with a hard edge, as UIKit's. + '@media (prefers-reduced-transparency: reduce)': 'none', + }, + }, + // `bars.scrollEdgeEffect.switchPt` (10px) tall, at the top of the content. + sentinel: { + position: 'absolute', + insetBlockStart: 0, + insetInlineStart: 0, + width: 1, + height: 10, + pointerEvents: 'none', + visibility: 'hidden', + }, +}); + +const dynamicStyles = stylex.create({ + // The layer ends 54.8px below the veil's edge (the soft extent). Reduce + // Transparency ends the opaque band at the edge, the bar's bottom. + geometry: (height: string, reducedHeight: string, color: string) => ({ + height: { + default: height, + '@media (prefers-reduced-transparency: reduce)': reducedHeight, + }, + backgroundColor: color, + }), +}); + +export interface UseScrollEdgeEffectOptions { + /** + * Whether the effect runs. When false, and always with a mouse, the veil + * stays transparent and nothing is observed. + * @default true + */ + readonly enabled?: boolean; + /** + * The scroll container whose content passes under the bar. Omit for a + * page that scrolls (the viewport). + */ + readonly root?: RefObject; + /** + * How far, in px, a bar overlays the top of `root` from its padding edge. + * Under a 44px bar it is `44`: the content counts as under the bar once it + * passes the bar's bottom edge. + * @default 0 + */ + readonly rootInset?: number; + /** + * The bar's bottom edge, where the veil is half strength, from the top of + * the layer's containing block. A CSS length without `calc()`: `100%` + * inside the bar, `44px` under a 44px bar that overlays the screen. + */ + readonly edge: string; + /** + * The veil's colour: the colour behind the bar's content. + * @default the body background + */ + readonly color?: string; + /** Extra styles for the layer, e.g. its stacking order. */ + readonly layerXstyle?: StyleXStyles; + /** + * Extra styles for the sentinel. Insets of `auto` leave it at its static + * position, the top of the content, with no positioned wrapper. + */ + readonly sentinelXstyle?: StyleXStyles; + /** The fades' springs: a bar's are `bars.scrollEdgeEffect`'s. */ + readonly springs: { + readonly appear: SpringDescription; + readonly disappear: SpringDescription; + }; +} + +/** Props to spread on an element, ref included. */ +interface ElementProps { + readonly ref: (element: HTMLElement | null) => void; + readonly 'aria-hidden': true; + readonly className?: string; + readonly style?: Readonly>; +} + +export interface UseScrollEdgeEffectResult { + /** + * The veil: spread on an empty element at the top of the bar's containing + * block, above the content and below the bar's items. + */ + readonly layerProps: ElementProps; + /** + * The sentinel: spread on an empty element at the top of the scrolled + * content. With static insets, the scroll container must be its containing + * block, so that it scrolls with the content. + */ + readonly sentinelProps: ElementProps; +} + +/** + * The iOS 26 scroll edge effect of a bar, under a finger. A veil fades in once + * the content has moved more than 10px under the bar, and out when it comes + * back. It is a switch with a timed fade, not a ramp that follows the scroll. + * + * @example + * ``` + * const edge = useScrollEdgeEffect({ + * root: scrollerRef, + * rootInset: 44, + * edge: '44px', + * springs: bars.scrollEdgeEffect, + * }); + *
+ *
…
+ * ``` + */ +export function useScrollEdgeEffect({ + enabled = true, + root, + rootInset = 0, + edge, + color = colorVars['--color-background-body'], + layerXstyle, + sentinelXstyle, + springs, +}: UseScrollEdgeEffectOptions): UseScrollEdgeEffectResult { + const {isTouch} = useTouchPresentation(); + const isOn = enabled && isTouch; + const {ref: layerRef, animator} = useMotionEngine({ + initial: {opacity: 0}, + }); + // The running effect's promotion check. The finger-scroll hook calls it + // when a finger's scroll ends; the effect sets it and clears it. + const updatePromotionRef = useRef<(() => void) | null>(null); + // Watched only while the effect runs, so a mouse costs nothing. A page's + // scroll is the document's; a container scrolls itself. + const isFingerScroll = useFingerScroll( + !isOn + ? NO_SCROLLER + : (root ?? (typeof document === 'undefined' ? NO_SCROLLER : document)), + {onEnd: () => updatePromotionRef.current?.()}, + ); + // The callback ref owns the sentinel, never React state. It moves the + // running observer to a replacement node. + const sentinelElementRef = useRef(null); + const observerRef = useRef(null); + const sentinelRef = useCallback((element: HTMLElement | null) => { + const observer = observerRef.current; + if (observer != null && sentinelElementRef.current != null) { + observer.unobserve(sentinelElementRef.current); + } + sentinelElementRef.current = element; + if (observer != null && element != null) { + observer.observe(element); + } + }, []); + + // Synchronizes with an IntersectionObserver on the sentinel and with the + // gesture host's fingers, which decide the layer's promotion. While the + // scroller has no layout, it also waits on Core's shared resize observer. + useEffect(() => { + if (!isOn || typeof IntersectionObserver === 'undefined') { + return; + } + const sentinel = sentinelElementRef.current; + const doc = sentinel?.ownerDocument ?? document; + const container = root?.current ?? null; + let isShown: boolean | null = null; + // Engines disagree on a scroll container's root rectangle: Chromium + // takes its padding box, WebKit its content box. The first report + // measures the difference; a page has no padding edge. + let rootOffset: number | null = container == null ? 0 : null; + let observer: IntersectionObserver; + let stopWaiting: (() => void) | null = null; + const report = (entries: IntersectionObserverEntry[]) => { + const entry = entries[entries.length - 1]; + if (entry == null) { + return; + } + if (rootOffset == null && container != null) { + const bounds = entry.rootBounds; + // A scroller with no layout (a stack in a hidden panel) gives nothing + // to measure. Wait until it has a size, then observe again: a new + // observer reports at once. The resize observer calls back once as + // it subscribes; the scroller has no size yet, so that call returns. + if (container.clientHeight <= 0) { + stopWaiting ??= observeResize(container, () => { + if (container.clientHeight <= 0) { + return; + } + stopWaiting?.(); + stopWaiting = null; + observer.disconnect(); + observe(); + }); + return; + } + const paddingEdge = + container.getBoundingClientRect().top + container.clientTop; + const offset = + bounds == null ? 0 : Math.round(bounds.top - rootInset - paddingEdge); + rootOffset = offset; + if (offset !== 0) { + // WebKit measured this report from the content box: observe + // again from the padding edge. + observer.disconnect(); + observe(); + return; + } + } + // The sentinel's bottom passes the root's top when the content has + // moved more than 10px under the bar. A box that only touches it + // still intersects: 10px is off, 10.25px is on, as measured. + const next = !entry.isIntersecting; + if (next === isShown) { + return; + } + if (isShown != null && isFingerScroll()) { + // Under Reduce Motion the animator plays its own opacity + // cross-fade on a coarse pointer. + animator.animate( + {opacity: next ? 1 : 0}, + {spring: next ? springs.appear : springs.disappear}, + ); + } else { + // The first report, or the program's scroll: at once, with no + // compositing layer (the WebKit blank on the layer style above). + animator.set({opacity: next ? 1 : 0}, {promote: false}); + } + isShown = next; + }; + const observe = () => { + observer = new IntersectionObserver(report, { + // The sentinel's own document: inside a frame, the implicit root is + // the top-level viewport. + root: container ?? doc, + rootMargin: `${(rootOffset ?? 0) - rootInset}px 0px 0px 0px`, + threshold: 0, + }); + observerRef.current = observer; + const current = sentinelElementRef.current; + if (current != null) { + observer.observe(current); + } + }; + observe(); + // The layer is promoted from a finger's landing until its scroll ends, + // momentum included. A fade that starts mid-drag then finds its layer. + // Drop this once iOS no longer blanks a sticky bar when the program + // scrolls over a composited layer. + const scroller: Node = container ?? doc; + const host = getGestureHost(doc); + const releaseHost = host.retain(); + let isPromoted = false; + const updatePromotion = () => { + const layer = animator.element; + const next = host.isFingerDownIn(scroller) || isFingerScroll(); + if (layer == null || next === isPromoted) { + return; + } + isPromoted = next; + if (next) { + layer.style.setProperty(SCROLL_EDGE_LAYER_PROMOTION, 'opacity'); + } else { + layer.style.removeProperty(SCROLL_EDGE_LAYER_PROMOTION); + } + }; + const unsubscribeFingers = host.onFingersChange(updatePromotion); + // The finger-scroll hook says when the finger's scroll has ended, its + // momentum included, so the layer drops with no listener or timer here. + updatePromotionRef.current = updatePromotion; + return () => { + observerRef.current = null; + observer.disconnect(); + unsubscribeFingers(); + updatePromotionRef.current = null; + stopWaiting?.(); + releaseHost(); + animator.element?.style.removeProperty(SCROLL_EDGE_LAYER_PROMOTION); + animator.set({opacity: 0}, {promote: false}); + }; + }, [isOn, root, rootInset, animator, isFingerScroll, springs]); + + return { + layerProps: { + ref: layerRef, + 'aria-hidden': true, + ...stylex.props( + styles.layer, + dynamicStyles.geometry(`calc(${edge} + 54.8px)`, edge, color), + layerXstyle, + ), + }, + sentinelProps: { + ref: sentinelRef, + 'aria-hidden': true, + ...stylex.props(styles.sentinel, sentinelXstyle), + }, + }; +} From a450587ca1d617dbd9ea017224337bb8a3f6f51d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 5 Nov 2026 23:45:24 -0800 Subject: [PATCH 6/6] test(lab): NavigationStack's cut specs read the push at held times Under load, WebKit can report one moving layer's animated translate a frame late. The old mid-flight read then put the cut 2 to 3 px off the card's edge while the layers moved as one. The two cut specs now freeze the scene while the push runs, move every animation of the push to the same scene times, and read the rendered boxes there. --- ...avigationStack.interaction.browser.spec.ts | 213 ++++++++++++------ 1 file changed, 141 insertions(+), 72 deletions(-) diff --git a/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts b/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts index e4b7fcfcbb719..fa390dc9ba4b9 100644 --- a/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts +++ b/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts @@ -29,7 +29,10 @@ import { countBetween, drag, flick, + freezePageWhen, holdAnimations, + installPageFreeze, + installTimerGate, markElement, openStory, releaseAnimations, @@ -37,6 +40,7 @@ import { sampleRects, startBusyControl, startScreencast, + thawPage, touchDriver, touchStoryboard, traceRendering, @@ -298,66 +302,126 @@ const crit = (response: number, ms: number) => { return 1 - (1 + u) * Math.exp(-u); }; -/** The incoming card's, the covered bar's and its cut box's x and boxes. */ -interface CutLayers { - card: number; - bar: number; - cut: number; - cardBox: {left: number; right: number}; - cutBox: {left: number; right: number}; +/** One scene time of a push: where the incoming card and the cut stand. */ +interface CutSample { + /** The incoming card's leading edge, px. */ + cardEdge: number; + /** How far the covered bar's cut is from that edge, px. */ + gap: number; } -const cutLayers = (page: Page, covered: string, incoming: string) => - page.evaluate( - ([coveredKey, incomingKey]): CutLayers | null => { - const x = (element: Element) => { - const value = getComputedStyle(element).translate; - return value === 'none' ? 0 : parseFloat(value); - }; - const cardElement = document.querySelector( - `[data-navigation-screen="${incomingKey}"]`, - ); - const barElement = document.querySelector( - `[data-navigation-bar="${coveredKey}"]`, - ); - const cutElement = barElement?.firstElementChild; - if (cardElement == null || barElement == null || cutElement == null) { - return null; - } - const cardBox = cardElement.getBoundingClientRect(); - const cutBox = cutElement.getBoundingClientRect(); - return { - card: x(cardElement), - bar: x(barElement), - cut: x(cutElement), - cardBox: {left: cardBox.left, right: cardBox.right}, - cutBox: {left: cutBox.left, right: cutBox.right}, - }; - }, - [covered, incoming] as const, +/** The scene times `cutAcrossPush` reads, ms after the push starts. */ +const CUT_TIMES = [16, 50, 90, 130, 180, 240, 300, 380]; + +/** + * Runs `push`, then reads the incoming card's leading edge and the covered + * bar's cut from their rendered boxes at each of `CUT_TIMES`. The scene + * freezes while the push runs, so nothing moves or retires. Each read moves + * every animation of the push to one scene time first. Mid-flight, WebKit can + * report one moving layer a frame late; at a held time it cannot. A freeze + * that lands late on a busy machine still reads the whole flight. The page + * needs `installPageFreeze` before it loads and `installTimerGate` after. + */ +async function cutAcrossPush( + page: Page, + push: () => Promise, + { + covered, + incoming, + direction, + }: {covered: string; incoming: string; direction: 'ltr' | 'rtl'}, +): Promise { + // Armed before the push, so the scene freezes while it runs. + const frozen = freezePageWhen( + page, + key => + document + .querySelector(`[data-navigation-screen="${key}"]`) + ?.getAnimations() + .some(animation => animation.playState === 'running') === true, + incoming, ); + await push(); + await frozen; + try { + return await page.evaluate( + ([coveredKey, incomingKey, dir, times]) => { + const stack = document.querySelector( + '[data-testid="navigation-stack"]', + ); + const cardElement = document.querySelector( + `[data-navigation-screen="${incomingKey}"]`, + ); + const cutElement = document.querySelector( + `[data-navigation-bar="${coveredKey}"]`, + )?.firstElementChild; + if (stack == null || cardElement == null || cutElement == null) { + return []; + } + const runs = document.getAnimations().filter(animation => { + const target = + animation.effect instanceof KeyframeEffect + ? animation.effect.target + : null; + return ( + target != null && + stack.contains(target) && + animation.startTime != null + ); + }); + // Read once: a held run's start follows its current time. + const starts = runs.map(animation => Number(animation.startTime)); + const heldAt = runs.map(animation => animation.currentTime); + // Scene times count from the incoming card's own start, whatever + // else in the stack animates (a row's press feedback). + const cardRun = runs.findIndex( + animation => + animation.effect instanceof KeyframeEffect && + animation.effect.target === cardElement, + ); + if (cardRun < 0) { + return []; + } + const origin = starts[cardRun]; + const samples = times.map(t => { + runs.forEach((animation, index) => { + animation.currentTime = Math.max(0, origin + t - starts[index]); + }); + const cardBox = cardElement.getBoundingClientRect(); + const cutBox = cutElement.getBoundingClientRect(); + // The cut's trailing edge meets the card's leading edge. + const cardEdge = dir === 'rtl' ? cardBox.right : cardBox.left; + const cutEdge = dir === 'rtl' ? cutBox.left : cutBox.right; + return {cardEdge, gap: Math.abs(cutEdge - cardEdge)}; + }); + // Back where the freeze held them, so the thaw plays on from there. + runs.forEach((animation, index) => { + animation.currentTime = heldAt[index]; + }); + return samples; + }, + [covered, incoming, direction, CUT_TIMES] as const, + ); + } finally { + await thawPage(page); + } +} /** - * How far the covered bar's cut is from the incoming card's leading edge at - * `mid`. It reads the layers' animated `translate`, and each edge's static - * part at `rest`, where box and translate agree. Mid-animation, WebKit can - * report one layer's box a frame late and not the other's. The boxes alone - * can then disagree by a pixel or two while the layers move as one. + * The samples span the flight, and at every one the cut stays on the card's + * leading edge. */ -const cutGap = ( - mid: CutLayers | null, - rest: CutLayers | null, - direction: 'ltr' | 'rtl', -): number => { - if (mid == null || rest == null) { - return Infinity; +function expectCutOnCardEdge(samples: CutSample[], width: number) { + const trace = JSON.stringify(samples); + expect(samples.length, trace).toBeGreaterThanOrEqual(5); + const travel = Math.abs( + samples[0].cardEdge - samples[samples.length - 1].cardEdge, + ); + expect(travel, trace).toBeGreaterThan(width * 0.5); + for (const sample of samples) { + expect(sample.gap, trace).toBeLessThan(2); } - const cardEdge = direction === 'rtl' ? 'right' : 'left'; - const cutEdge = direction === 'rtl' ? 'left' : 'right'; - const cardStatic = rest.cardBox[cardEdge] - rest.card; - const cutStatic = rest.cutBox[cutEdge] - rest.bar - rest.cut; - return Math.abs(cutStatic + mid.bar + mid.cut - (cardStatic + mid.card)); -}; +} const rowCenter = async (page: Page, name: string) => { const box = await page.getByRole('button', {name}).first().boundingBox(); @@ -1067,17 +1131,20 @@ test('under a finger, the incoming screen cuts the old title while the main thre test('under a finger the cut rides the incoming card’s leading edge', async ({ page, }) => { - const {driver} = await openStack(page, 'settings'); - await driver.tap(await rowCenter(page, 'General')); - await waitForAnimation(card(page, 'screen-General'), {minProgressMs: 16}); - // Mid-push the root's bar shows only left of the incoming card: the cut - // and the card's edge move on one spring. - const mid = await cutLayers(page, 'root', 'screen-General'); + // The page clock a freeze needs, installed before the story loads. + await installPageFreeze(page); + const {driver, width} = await openStack(page, 'settings'); + await installTimerGate(page); + const row = await rowCenter(page, 'General'); + // Through the push the root's bar shows only left of the incoming card: + // the cut and the card's edge move on one spring. + const samples = await cutAcrossPush(page, () => driver.tap(row), { + covered: 'root', + incoming: 'screen-General', + direction: 'ltr', + }); + expectCutOnCardEdge(samples, width); await waitForRest(card(page, 'screen-General')); - const rest = await cutLayers(page, 'root', 'screen-General'); - expect(mid).not.toBeNull(); - expect(rest).not.toBeNull(); - expect(cutGap(mid, rest, 'ltr')).toBeLessThan(2); expect(await readCut(page, 'root')).toEqual({shown: 0}); expect(await readCut(page, 'screen-General')).toEqual({shown: 1}); }); @@ -1085,20 +1152,22 @@ test('under a finger the cut rides the incoming card’s leading edge', async ({ test('under a finger in a right-to-left stack, the cut mirrors', async ({ page, }) => { - const {driver} = await openStack(page, 'settings'); + await installPageFreeze(page); + const {driver, width} = await openStack(page, 'settings'); + await installTimerGate(page); await page .getByTestId('navigation-stack') .evaluate(element => element.setAttribute('dir', 'rtl')); - await driver.tap(await rowCenter(page, 'General')); - await waitForAnimation(card(page, 'screen-General'), {minProgressMs: 16}); + const row = await rowCenter(page, 'General'); // The incoming card enters from the left: the root's bar shows only right - // of its trailing edge. - const mid = await cutLayers(page, 'root', 'screen-General'); + // of the card's leading edge. + const samples = await cutAcrossPush(page, () => driver.tap(row), { + covered: 'root', + incoming: 'screen-General', + direction: 'rtl', + }); + expectCutOnCardEdge(samples, width); await waitForRest(card(page, 'screen-General')); - const rest = await cutLayers(page, 'root', 'screen-General'); - expect(mid).not.toBeNull(); - expect(rest).not.toBeNull(); - expect(cutGap(mid, rest, 'rtl')).toBeLessThan(2); expect(await readCut(page, 'root')).toEqual({shown: 0}); expect(await readCut(page, 'screen-General')).toEqual({shown: 1}); });