An open source design system that's fully customizable and agent ready
TypeScript
fix(NavigationStack): fade the veil for a late finger-scroll report (#10540)
Christopher Chedeau33cf413d05ab
diff --git a/.changeset/internal-core-s-internal-finger-scroll-reader-ca-4zb2.md b/.changeset/internal-core-s-internal-finger-scroll-reader-ca-4zb2.mdnew file mode 100644index 0000000000..741db9b4f3--- /dev/null+++ b/.changeset/internal-core-s-internal-finger-scroll-reader-ca-4zb2.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: Core's internal finger-scroll reader can answer for a past time on the page's clock, for Lab's NavigationStack scroll edge. Apps import nothing new.+@vjeuxdiff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.mdindex 39838da9af..734c575117 100644--- a/docs/architecture/react-component-runtime.md+++ b/docs/architecture/react-component-runtime.md@@ -325,8 +325,8 @@ those contracts.packages: undocumented, outside the compatibility promise, versioned inlockstep with Core, and limited by lint to Core and Lab (`spec:AST-017`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.+ subpath: it reports whether a scroller's scroll is a finger's, now or at a+ past time, 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 ownsdiff --git a/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx b/packages/core/src/gestures/__tests__/useFingerScroll.test.tsxindex f38b02ea68..9c738ee151 100644--- a/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx+++ b/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx@@ -28,7 +28,7 @@ function touch(type: string, target: Element, down: boolean): void {target.dispatchEvent(event);}-let read: () => boolean = () => false;+let read: (at?: number) => boolean = () => false;function List({other = false}: {other?: boolean}) {const ref = useRef<HTMLDivElement>(null);@@ -148,6 +148,67 @@ describe('useFingerScroll', () => {expect(read()).toBe(false);});+ it("reads a time inside a finger's scroll as the finger's after it ends, and a program scroll right after as the program's", () => {+ const now = vi.spyOn(window.performance, 'now').mockReturnValue(100);+ try {+ const {getByTestId} = render(<List />);+ const list = getByTestId('list');+ const row = getByTestId('row');+ touch('touchstart', row, true);+ now.mockReturnValue(120);+ list.dispatchEvent(new Event('scroll'));+ now.mockReturnValue(150);+ touch('touchend', row, false);+ now.mockReturnValue(200);+ list.dispatchEvent(new Event('scrollend'));+ expect(read()).toBe(false);+ expect(read(99)).toBe(false);+ expect(read(130)).toBe(true);+ expect(read(200)).toBe(true);+ // The program scrolls right after: the observer records it later.+ now.mockReturnValue(210);+ list.dispatchEvent(new Event('scroll'));+ expect(read()).toBe(false);+ expect(read(216)).toBe(false);+ } finally {+ now.mockRestore();+ }+ });++ it("keeps a scroll that ended under the resting finger the finger's at any time up to the lift", () => {+ const now = vi.spyOn(window.performance, 'now').mockReturnValue(100);+ try {+ const {getByTestId} = render(<List />);+ const list = getByTestId('list');+ const row = getByTestId('row');+ touch('touchstart', row, true);+ now.mockReturnValue(110);+ list.dispatchEvent(new Event('scroll'));+ now.mockReturnValue(120);+ list.dispatchEvent(new Event('scrollend'));+ expect(read(115)).toBe(true);+ now.mockReturnValue(300);+ touch('touchend', row, false);+ expect(read()).toBe(false);+ expect(read(250)).toBe(true);+ expect(read(301)).toBe(false);+ } finally {+ now.mockRestore();+ }+ });++ it("reads a scroll the program drives with no finger as the program's at any time", () => {+ const now = vi.spyOn(window.performance, 'now').mockReturnValue(100);+ try {+ const {getByTestId} = render(<List />);+ getByTestId('list').dispatchEvent(new Event('scroll'));+ expect(read(100)).toBe(false);+ expect(read(50)).toBe(false);+ } finally {+ now.mockRestore();+ }+ });+it("reads a recognizer's own scroll as the program's, even with a finger resting inside", () => {const {getByTestId} = render(<List />);const list = getByTestId('list');diff --git a/packages/core/src/gestures/fingerScroll.ts b/packages/core/src/gestures/fingerScroll.tsindex 597575ba6f..be4e2b2b0f 100644--- a/packages/core/src/gestures/fingerScroll.ts+++ b/packages/core/src/gestures/fingerScroll.ts@@ -5,8 +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; a watcher can ask to- * be told when a finger's scroll ends+ * @output Exports watchFingerScrolls and isFingerScroll (now or at a past+ * time). A watcher can ask to hear 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@@ -35,6 +35,12 @@ import {isNode} from '../utils/nodeType';*/const SCROLL_END_FALLBACK_MS = 150;+/** A finger scroll's span on the page's clock, ms: landing to end. */+interface FingerScrollSpan {+ readonly start: number;+ readonly end: number;+}+interface Watch {/** Watched scrollers, and how many watchers each has. */readonly scrollers: Map<Node, number>;@@ -44,20 +50,31 @@ interface Watch {readonly endedWhileDown: Set<Node>;/** Per scroller, the watchers to tell when its finger scroll ends. */readonly endListeners: Map<Node, Set<() => void>>;+ /** Per watched scroller, when the finger now down in it landed. */+ readonly landings: Map<Node, number>;+ /** Per finger scroll in progress, when its finger landed. */+ readonly fingerScrollStarts: Map<Node, number>;+ /** Per scroller, the span of its last finger scroll that ended. */+ readonly lastFingerScrolls: Map<Node, FingerScrollSpan>;stop: (() => void) | null;}const watches = new WeakMap<GestureHost, Watch>();/**- * 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.+ * A scroller's finger scroll is over at `at`. It stops counting as the+ * finger's, and its span stays readable. Then its end listeners hear of it,+ * so one that reads isFingerScroll already reads false.*/-function endFingerScroll(watch: Watch, scroller: Node): void {+function endFingerScroll(watch: Watch, scroller: Node, at: number): void {if (!watch.fingerScrollers.delete(scroller)) {return;}+ watch.lastFingerScrolls.set(scroller, {+ start: watch.fingerScrollStarts.get(scroller) ?? at,+ end: at,+ });+ watch.fingerScrollStarts.delete(scroller);for (const listener of [...(watch.endListeners.get(scroller) ?? [])]) {listener();}@@ -65,6 +82,8 @@ function endFingerScroll(watch: Watch, scroller: Node): void {function start(host: GestureHost, watch: Watch): () => void {const doc = host.document;+ // The clock of the page's IntersectionObserver entries and events.+ const now = (): number => (doc.defaultView?.performance ?? performance).now();const scrollerOf = (event: Event): Node | null => {const target = event.target === doc ? doc : event.target;return isNode(target) ? target : null;@@ -79,7 +98,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 {- endFingerScroll(watch, scroller);+ endFingerScroll(watch, scroller, now());}};const scrollEndFallbacks = new Map<Node, ReturnType<typeof setTimeout>>();@@ -107,6 +126,12 @@ function start(host: GestureHost, watch: Watch): () => void {}watch.endedWhileDown.delete(scroller);if (host.isFingerDownIn(scroller)) {+ if (!watch.fingerScrollers.has(scroller)) {+ watch.fingerScrollStarts.set(+ scroller,+ watch.landings.get(scroller) ?? now(),+ );+ }watch.fingerScrollers.add(scroller);}if (watch.fingerScrollers.has(scroller) && !hasScrollEnd()) {@@ -126,12 +151,22 @@ function start(host: GestureHost, watch: Watch): () => void {endScroll(scroller);}};- // A scroll that ended while its finger rested ends with the lift.const onFingers = (): void => {+ // A finger scroll's span starts at its finger's landing: the observer+ // records a crossing at its frame's start, before that frame's scroll+ // event runs.+ for (const scroller of watch.scrollers.keys()) {+ if (!host.isFingerDownIn(scroller)) {+ watch.landings.delete(scroller);+ } else if (!watch.landings.has(scroller)) {+ watch.landings.set(scroller, now());+ }+ }+ // A scroll that ended while its finger rested ends with the lift.for (const scroller of watch.endedWhileDown) {if (!host.isFingerDownIn(scroller)) {watch.endedWhileDown.delete(scroller);- endFingerScroll(watch, scroller);+ endFingerScroll(watch, scroller, now());}}};@@ -160,8 +195,9 @@ function start(host: GestureHost, watch: Watch): () => void {// No finger scrolls once the pointer is no longer coarse: each one in// progress ends here.watch.endedWhileDown.clear();+ watch.landings.clear();for (const scroller of [...watch.fingerScrollers]) {- endFingerScroll(watch, scroller);+ endFingerScroll(watch, scroller, now());}}};@@ -199,6 +235,9 @@ export function watchFingerScrolls(fingerScrollers: new Set(),endedWhileDown: new Set(),endListeners: new Map(),+ landings: new Map(),+ fingerScrollStarts: new Map(),+ lastFingerScrolls: new Map(),stop: null,};watches.set(host, watch);@@ -235,6 +274,9 @@ export function watchFingerScrolls(owned.scrollers.delete(scroller);owned.fingerScrollers.delete(scroller);owned.endedWhileDown.delete(scroller);+ owned.landings.delete(scroller);+ owned.fingerScrollStarts.delete(scroller);+ owned.lastFingerScrolls.delete(scroller);if (owned.scrollers.size === 0) {owned.stop?.();owned.stop = null;@@ -243,9 +285,30 @@ export function watchFingerScrolls(}/**- * Whether the scroll now moving a watched `scroller` is a finger's.+ * Whether the scroll now moving a watched `scroller` is a finger's. Given a+ * time on the page's clock (`performance.now()`, like an IntersectionObserver+ * entry's `time`), whether the scroll at that time was a finger's. A finger's+ * scroll runs from the finger's landing to its end, momentum included. A+ * report that runs late, such as an IntersectionObserver callback on a busy+ * page, passes the time it describes.* Internal: not exported from the package.*/-export function isFingerScroll(host: GestureHost, scroller: Node): boolean {- return watches.get(host)?.fingerScrollers.has(scroller) === true;+export function isFingerScroll(+ host: GestureHost,+ scroller: Node,+ at?: number,+): boolean {+ const watch = watches.get(host);+ if (watch == null) {+ return false;+ }+ if (at == null) {+ return watch.fingerScrollers.has(scroller);+ }+ const start = watch.fingerScrollStarts.get(scroller);+ if (start != null && at >= start) {+ return true;+ }+ const last = watch.lastFingerScrolls.get(scroller);+ return last != null && at >= last.start && at <= last.end;}diff --git a/packages/core/src/gestures/useFingerScroll.ts b/packages/core/src/gestures/useFingerScroll.tsindex 7d3fa3ee06..412e944c1d 100644--- a/packages/core/src/gestures/useFingerScroll.ts+++ b/packages/core/src/gestures/useFingerScroll.ts@@ -6,8 +6,8 @@* @file useFingerScroll.ts* @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, and an optional call when one ends+ * @output useFingerScroll: whether the scroller's scroll is a finger's, read+ * now or at a past time, 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@@ -56,13 +56,15 @@ export interface UseFingerScrollOptions {/*** 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- * renders: `true` while the scroller's scroll is a finger's.+ * renders: `true` while the scroller's scroll is a finger's. Given a time on+ * the page's clock (`performance.now()`, as an IntersectionObserver entry's+ * `time` is), it reads whether the scroll at that time was a finger's.* Internal: not exported from the package.*/export function useFingerScroll(scroller: RefObject<Element | null> | Document,{onEnd}: UseFingerScrollOptions = {},-): () => boolean {+): (at?: number) => boolean {/** The node the watch is on now, for the reader. */const watchedRef = useRef<Element | Document | null>(null);// The watch outlives renders, so it calls the latest onEnd through a ref@@ -90,10 +92,10 @@ export function useFingerScroll(},null,);- return useCallback(() => {+ return useCallback((at?: number) => {const node = watchedRef.current;return (- node != null && isFingerScroll(getGestureHost(documentOf(node)), node)+ node != null && isFingerScroll(getGestureHost(documentOf(node)), node, at));}, []);}diff --git a/packages/lab/src/NavigationStack/__tests__/NavigationStackScrollEdge.interaction.browser.spec.ts b/packages/lab/src/NavigationStack/__tests__/NavigationStackScrollEdge.interaction.browser.spec.tsindex 21e0802090..d5163e9ae0 100644--- a/packages/lab/src/NavigationStack/__tests__/NavigationStackScrollEdge.interaction.browser.spec.ts+++ b/packages/lab/src/NavigationStack/__tests__/NavigationStackScrollEdge.interaction.browser.spec.ts@@ -293,6 +293,116 @@ test('a finger scrolling the screen fades the veil in', async ({expect(await presentedOpacity(veil(page, 'root'))).toBe(1);});+/**+ * Holds the page's IntersectionObserver reports from `holdObserverReports()`+ * until the finger's scroll has ended. That is after the `scrollend` that+ * follows the lift, or after the lift when the scroll ended under the resting+ * finger. A busy page runs a report that late. Each entry keeps its own+ * `time`. `releasedReports` counts the reports held, so a test can see the+ * hold.+ */+async function holdReportsPastTheScroll(page: Page) {+ await page.addInitScript(() => {+ const Observer = window.IntersectionObserver;+ const held: Array<() => void> = [];+ let isHolding = false;+ let isLifted = false;+ let hasScrollEnded = false;+ const release = () => {+ isHolding = false;+ // After the gesture host and the finger-scroll watch hear the event.+ setTimeout(() => {+ const runs = held.splice(0);+ Object.assign(window, {releasedReports: runs.length});+ for (const run of runs) {+ run();+ }+ });+ };+ Object.assign(window, {+ releasedReports: 0,+ holdObserverReports: () => {+ isHolding = true;+ isLifted = false;+ hasScrollEnded = false;+ },+ });+ document.addEventListener(+ 'touchend',+ () => {+ if (isHolding) {+ isLifted = true;+ if (hasScrollEnded) {+ release();+ }+ }+ },+ true,+ );+ document.addEventListener(+ 'scrollend',+ () => {+ if (isHolding) {+ hasScrollEnded = true;+ if (isLifted) {+ release();+ }+ }+ },+ true,+ );+ window.IntersectionObserver = class extends Observer {+ constructor(+ callback: IntersectionObserverCallback,+ options?: IntersectionObserverInit,+ ) {+ super((entries, observer) => {+ if (isHolding) {+ held.push(() => callback(entries, observer));+ } else {+ callback(entries, observer);+ }+ }, options);+ }+ };+ });+}++test('a finger’s scroll fades the veil even when its report runs after the scroll ended', async ({+ page,+ browserName,+}) => {+ test.skip(+ browserName !== 'chromium',+ 'native scrolling from injected touches is Chromium-only (harness README)',+ );+ await holdReportsPastTheScroll(page);+ await openStack(page);+ const layer = veil(page, 'root');+ const hold = await armHold(page, layer, {+ judges: {target: layer, property: 'opacity'},+ newOnly: true,+ });+ const driver = await touchDriver(page);+ await page.evaluate(() =>+ (+ window as unknown as {holdObserverReports: () => void}+ ).holdObserverReports(),+ );+ await driver.play(+ drag({x: 200, y: 560}, {x: 200, y: 460}, {durationMs: 300, restMs: 450}),+ );+ // A switch at once runs no animation, so the hold finds none.+ await hold.held();+ expect(+ await page.evaluate(+ () => (window as unknown as {releasedReports: number}).releasedReports,+ ),+ ).toBeGreaterThan(0);+ await releaseAnimations(page, {finish: true});+ expect(await presentedOpacity(layer)).toBe(1);+});+test('the veil and its sentinel are hidden from assistive technology', async ({page,}) => {diff --git a/packages/lab/src/internal/useScrollEdgeEffect.test.tsx b/packages/lab/src/internal/useScrollEdgeEffect.test.tsxindex 59326c1e2c..964945c5cb 100644--- a/packages/lab/src/internal/useScrollEdgeEffect.test.tsx+++ b/packages/lab/src/internal/useScrollEdgeEffect.test.tsx@@ -71,9 +71,12 @@ const host = {watched: [] as unknown[],/** The hook's latest end call, as the real one keeps it. */onEnd: null as (() => void) | null,+ /** Whether the scroll at a past time was a finger's, when a test sets it. */+ fingerAt: null as ((at: number) => boolean) | null,};/** useFingerScroll's reader is stable across renders, as the real one. */-const readFingerScroll = () => host.isFinger;+const readFingerScroll = (at?: number) =>+ at != null && host.fingerAt != null ? host.fingerAt(at) : host.isFinger;/** The finger-scroll hook saying that the finger's scroll has ended. */function endFingerScroll() {host.isFinger = false;@@ -126,11 +129,16 @@ class RecordingObserver {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.+ * Reports the sentinel intersecting its root (true) or gone (false). It+ * passes the root rectangle's top when given (the engine's, margin+ * applied), its height, and the crossing's time when given.*/- report(isIntersecting: boolean, rootTop?: number, rootHeight = 400) {+ report(+ isIntersecting: boolean,+ rootTop?: number,+ rootHeight = 400,+ time?: number,+ ) {act(() => {this.callback([@@ -140,6 +148,7 @@ class RecordingObserver {rootTop == null? null: ({top: rootTop, height: rootHeight} as DOMRectReadOnly),+ ...(time == null ? {} : {time}),} as IntersectionObserverEntry,],this as unknown as IntersectionObserver,@@ -189,6 +198,7 @@ beforeEach(() => {host.watched = [];RecordingObserver.instances = [];host.onEnd = null;+ host.fingerAt = null;resize.callbacks = [];resize.stops = 0;animator.set.mockClear();@@ -477,6 +487,32 @@ describe('useScrollEdgeEffect', () => {expect(animator.animate).toHaveBeenCalledTimes(1);});+ it('fades for a report that runs after the finger’s scroll ended, read at the time the observer recorded it', () => {+ render(<Bar enabled />);+ observer().report(true);+ // The finger's scroll ran from 100 to 200 ms; a busy page reports later.+ host.isFinger = false;+ host.fingerAt = at => at >= 100 && at <= 200;+ observer().report(false, undefined, 400, 150);+ expect(animator.animate).toHaveBeenLastCalledWith(+ {opacity: 1},+ {spring: bars.scrollEdgeEffect.appear},+ );+ });++ it('switches at once for a program scroll right after a finger’s: the observer records it later', () => {+ render(<Bar enabled />);+ observer().report(true);+ host.isFinger = false;+ host.fingerAt = at => at >= 100 && at <= 200;+ observer().report(false, undefined, 400, 216);+ expect(animator.set).toHaveBeenLastCalledWith(+ {opacity: 1},+ {promote: false},+ );+ expect(animator.animate).not.toHaveBeenCalled();+ });+it('watches the page’s finger scrolls, or the scroll container’s', () => {const {unmount} = render(<Bar enabled />);expect(watchedNode()).toBe(document);diff --git a/packages/lab/src/internal/useScrollEdgeEffect.ts b/packages/lab/src/internal/useScrollEdgeEffect.tsindex 4692d952a2..60218a037d 100644--- a/packages/lab/src/internal/useScrollEdgeEffect.ts+++ b/packages/lab/src/internal/useScrollEdgeEffect.ts@@ -272,7 +272,9 @@ export function useScrollEdgeEffect({if (next === isShown) {return;}- if (isShown != null && isFingerScroll()) {+ // A busy page can run the report after the finger's scroll ended: read+ // the scroll at the time the observer recorded the crossing.+ if (isShown != null && isFingerScroll(entry.time)) {// Under Reduce Motion the animator plays its own opacity// cross-fade on a coarse pointer.animator.animate(