From aaeeced38af606ad951ad2bde2908a93b879a64b Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 4 Nov 2026 13:05:19 -0800 Subject: [PATCH 1/3] chore(core): the motion and gesture internals that Lab's refresh pull reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Core's internal touch entry re-exports, by name, what Lab's useRefreshControl imports: the pan recognizer, its hook and the gesture types; the motion animator; the cubic Bézier, the rubber band with its inverse and slope, and the map of a companion curve; the UIKit scroll table; and the motion-role parsers. Each one is an existing internal, and Core's behavior does not change. A bundle test checks that the public entry exports none of them. --- .../core-internal-touch-refresh-pull.md | 7 ++++ packages/core/src/internal/touch.test.ts | 25 +++++++++++ packages/core/src/internal/touch.ts | 35 +++++++++++++++- scripts/touch-support-bundle.test.mjs | 41 ++++++++++++++++++- 4 files changed, 106 insertions(+), 2 deletions(-) create mode 100644 .changeset/core-internal-touch-refresh-pull.md diff --git a/.changeset/core-internal-touch-refresh-pull.md b/.changeset/core-internal-touch-refresh-pull.md new file mode 100644 index 0000000000000..d254751990373 --- /dev/null +++ b/.changeset/core-internal-touch-refresh-pull.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: Core's internal touch entry re-exports what Lab's useRefreshControl reads. That is the pan recognizer, its hook and the gesture types, and the motion animator. It is also the motion math, the map of a companion curve, the UIKit scroll table of its pull, and the motion-role parsers. None is in the public entry. Apps import nothing new. + +@vjeux diff --git a/packages/core/src/internal/touch.test.ts b/packages/core/src/internal/touch.test.ts index 2f175885dbf4e..0300e71f3886a 100644 --- a/packages/core/src/internal/touch.test.ts +++ b/packages/core/src/internal/touch.test.ts @@ -33,6 +33,31 @@ describe('internal/touch', () => { expect(entry).not.toHaveProperty('touchModule'); }); + it("re-exports by name what Lab's useRefreshControl reads", async () => { + const entry: Record = await import('./touch'); + const pan = await import('../gestures/PanGestureRecognizer'); + const hook = await import('../gestures/useGestureRecognizer'); + const animator = await import('../motion/animator'); + const bezier = await import('../motion/bezier'); + const progress = await import('../motion/progress'); + const roles = await import('../motion/roles'); + const band = await import('../motion/rubberBand'); + const scroll = await import('../motion/uikit/scroll'); + expect(entry.PanGestureRecognizer).toBe(pan.PanGestureRecognizer); + expect(entry.useGestureRecognizer).toBe(hook.useGestureRecognizer); + expect(entry.createMotionAnimator).toBe(animator.createMotionAnimator); + expect(entry.cubicBezier).toBe(bezier.cubicBezier); + expect(entry.mapProgress).toBe(progress.mapProgress); + expect(entry.parseCssEasing).toBe(roles.parseCssEasing); + expect(entry.parseMotionRoleValue).toBe(roles.parseMotionRoleValue); + expect(entry.rubberBand).toBe(band.rubberBand); + expect(entry.rubberBandInverse).toBe(band.rubberBandInverse); + expect(entry.rubberBandSlope).toBe(band.rubberBandSlope); + expect(entry.scroll).toBe(scroll.scroll); + // No internal factory shares a public factory's name. + expect(entry).not.toHaveProperty('createAnimator'); + }); + 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 b1ff8a168bdb0..560cc95f3eeac 100644 --- a/packages/core/src/internal/touch.ts +++ b/packages/core/src/internal/touch.ts @@ -2,7 +2,9 @@ /** * @file touch.ts - * @input The gesture core: the arena, the recognizers, and their geometry + * @input The gesture core: the arena, the recognizers, and their geometry; + * the pan, the motion animator and the motion math that Lab's + * useRefreshControl reads * @output `@astryxdesign/core/internal/touch`: the gesture core's primitives * for Lab components, re-exported by name * @position An internal entry reserved for Astryx's own packages: @@ -39,3 +41,34 @@ export { export {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer'; export {TapGestureRecognizer} from '../gestures/TapGestureRecognizer'; export {DEFAULT_ENVIRONMENT} from '../gestures/types'; + +// Lab's useRefreshControl reads these: its pull's pan and the hook that +// starts it. It also reads the motion animator and math, and the scroll +// view's bounce spring, for its pull, settle and end. Its indicator fades +// along the settle's curve, and the motion-role parsers read the theme's +// tokens for its end. +export {PanGestureRecognizer} from '../gestures/PanGestureRecognizer'; +export type {PanGestureRecognizerOptions} from '../gestures/PanGestureRecognizer'; +export type { + GestureEventContext, + GestureTouch, + PointerKind, +} from '../gestures/types'; +export {useGestureRecognizer} from '../gestures/useGestureRecognizer'; +// The animator's internal factory. The public one, `createAnimator`, plays +// only the theme's state-change motion. +export {createMotionAnimator} from '../motion/animator'; +export type { + Animator as MotionAnimator, + AnimatorOptions as MotionAnimatorOptions, + MotionCurve, +} from '../motion/animator'; +export {cubicBezier} from '../motion/bezier'; +export {mapProgress} from '../motion/progress'; +export {parseCssEasing, parseMotionRoleValue} from '../motion/roles'; +export { + rubberBand, + rubberBandInverse, + rubberBandSlope, +} from '../motion/rubberBand'; +export {scroll} from '../motion/uikit/scroll'; diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs index 2b7504521c4f2..76ebf5bc5b09f 100644 --- a/scripts/touch-support-bundle.test.mjs +++ b/scripts/touch-support-bundle.test.mjs @@ -13,7 +13,8 @@ * carries only the gesture code its touch components import; two components * that import the touch module share one copy per page; only the internal * `internal/touch` entry reaches it, and no consumer doc or component - * `import()` does + * `import()` does; the names that entry gives Lab are not in the root + * entry * @position Node test over source, so it needs no build. Its build files * live under the repository's `node_modules/.cache`, never the system temp * directory, whose listing esbuild would read for every build @@ -100,6 +101,33 @@ function outputsOf(entries) { ); } +/** The names a build of `entry` exports, read from esbuild's metafile. */ +function exportsOf(entry) { + const result = esbuild.buildSync({...BUILD_OPTIONS, entryPoints: [entry]}); + return Object.values(result.metafile.outputs).flatMap( + output => output.exports ?? [], + ); +} + +/** + * What the internal entry gives Lab's refresh pull: the pan, its hook, the + * motion animator, its motion math and companion curves, the scroll view's + * spring and the motion-role parsers. None is public API. + */ +const LAB_ONLY_NAMES = [ + 'PanGestureRecognizer', + 'useGestureRecognizer', + 'createMotionAnimator', + 'cubicBezier', + 'mapProgress', + 'parseCssEasing', + 'parseMotionRoleValue', + 'rubberBand', + 'rubberBandInverse', + 'rubberBandSlope', + 'scroll', +]; + /** The inputs matching `pattern` that put bytes in `bytes`. */ function bytesOf(bytes, pattern = PRIMITIVE_INPUT) { return Object.entries(bytes).filter( @@ -403,6 +431,17 @@ describe('the touch module internals', () => { ); }); + it('give Lab names that the public entry does not export', () => { + const internal = new Set( + exportsOf(path.join(CORE_SRC, 'internal/touch.ts')), + ); + const root = new Set(exportsOf(path.join(CORE_SRC, 'index.ts'))); + // The root build reads its exports: a public component is among them. + expect(root.has('Button')).toBe(true); + expect(LAB_ONLY_NAMES.filter(name => !internal.has(name))).toEqual([]); + expect(LAB_ONLY_NAMES.filter(name => root.has(name))).toEqual([]); + }, 120_000); + it('have no entry in the exports map beside the internal touch entry', () => { const {exports} = JSON.parse( fs.readFileSync(path.join(REPO, 'packages/core/package.json'), 'utf8'), From 99435f3b70b68a704d6b2c50d9192933281ae8fe Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 4 Nov 2026 13:05:19 -0800 Subject: [PATCH 2/3] feat(lab): useRefreshControl, UIKit's pull to refresh for an app's scroll container Lab's useRefreshControl gives an app's own scroll container UIKit's pull to refresh. The pull follows UIKit's measured mapping and triggers with the finger down. A release settles onto the refreshing inset on the scroll view's bounce. The end slides away on the theme's duration and move easing tokens. The app draws the indicator. The hook pins it at the top of the scroll view and writes how much of it the pull reveals. The app also supplies the announcement text. A finger and a trackpad's two-finger scroll pull. A mouse or pen drag stays the browser's, for text selection. The pull applies in the nearest scroll container that overflows, never on the page itself. --- .../RefreshControl/RefreshPullRecognizer.ts | 104 ++ ...RefreshControl.interaction.browser.spec.ts | 1454 +++++++++++++++++ packages/lab/src/RefreshControl/index.ts | 18 + .../src/RefreshControl/refreshIndicator.ts | 12 + .../src/RefreshControl/refreshModel.test.ts | 174 ++ .../lab/src/RefreshControl/refreshModel.ts | 117 ++ .../src/RefreshControl/refreshPull.test.ts | 270 +++ .../lab/src/RefreshControl/refreshPull.ts | 186 +++ .../RefreshControl/refreshTouchController.ts | 838 ++++++++++ .../lab/src/RefreshControl/refreshValues.ts | 80 + .../src/RefreshControl/useMotionAnimator.ts | 35 + .../RefreshControl/useRefreshControl.test.tsx | 1315 +++++++++++++++ .../src/RefreshControl/useRefreshControl.ts | 255 +++ packages/lab/src/index.ts | 9 + 14 files changed, 4867 insertions(+) create mode 100644 packages/lab/src/RefreshControl/RefreshPullRecognizer.ts create mode 100644 packages/lab/src/RefreshControl/__tests__/RefreshControl.interaction.browser.spec.ts create mode 100644 packages/lab/src/RefreshControl/index.ts create mode 100644 packages/lab/src/RefreshControl/refreshIndicator.ts create mode 100644 packages/lab/src/RefreshControl/refreshModel.test.ts create mode 100644 packages/lab/src/RefreshControl/refreshModel.ts create mode 100644 packages/lab/src/RefreshControl/refreshPull.test.ts create mode 100644 packages/lab/src/RefreshControl/refreshPull.ts create mode 100644 packages/lab/src/RefreshControl/refreshTouchController.ts create mode 100644 packages/lab/src/RefreshControl/refreshValues.ts create mode 100644 packages/lab/src/RefreshControl/useMotionAnimator.ts create mode 100644 packages/lab/src/RefreshControl/useRefreshControl.test.tsx create mode 100644 packages/lab/src/RefreshControl/useRefreshControl.ts diff --git a/packages/lab/src/RefreshControl/RefreshPullRecognizer.ts b/packages/lab/src/RefreshControl/RefreshPullRecognizer.ts new file mode 100644 index 0000000000000..242465436ca72 --- /dev/null +++ b/packages/lab/src/RefreshControl/RefreshPullRecognizer.ts @@ -0,0 +1,104 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file RefreshPullRecognizer.ts + * @input Touches from the gesture arena (Core's internal touch entry) + * @output Exports RefreshPullRecognizer, the vertical pan that reads a pull + * to refresh without taking the touch, and RefreshScrollPullRecognizer + * @position The gesture of useRefreshControl, on the foundation's + * PanGestureRecognizer + * + * SYNC: When modified, update: + * - /packages/lab/src/RefreshControl/useRefreshControl.ts + */ + +// UIKit's refresh pull is the scroll view's own drag, not a second gesture. +// One touch can scroll, pull past the top, and scroll the same content again. +// So this pan never claims its touch, and only watches it. The browser keeps +// the finger for native scrolling, so nothing changes hands midway. The pan +// reads the finger to draw the overscroll, because the scroll owner's +// `overscroll-behavior-y` is `none` near the top. +// +// The pan begins on vertical travel past its hysteresis. The touch layer +// starts the pull where the content is at its top and the finger moves down. +// When the browser takes the touch to scroll, the pan keeps reading it to the +// lift. A second finger is the browser's, for pinch-zoom. +// +// A trackpad's scroll pulls through RefreshScrollPullRecognizer. A pen's or +// a mouse's drag stays the browser's, for text selection: the pan takes only +// a finger. `pointerType` and `scrollType` record the first contact's input. +// `onTouchDown` reports that contact landing, so a settle in flight can stop +// where it is, as UIScrollView brakes on touch-down. + +import { + PanGestureRecognizer, + type PanGestureRecognizerOptions, +} from '@astryxdesign/core/internal/touch'; +import type { + GestureEventContext, + GestureTouch, + PointerKind, +} from '@astryxdesign/core/internal/touch'; + +export class RefreshPullRecognizer extends PanGestureRecognizer { + /** Called when the first contact of a gesture lands, with its timestamp. */ + onTouchDown: ((time: number) => void) | null = null; + /** The pointer of the gesture's first contact. */ + pointerType: PointerKind = 'touch'; + /** Set when the gesture is a trackpad's scroll rather than a contact. */ + scrollType: GestureTouch['scrollType'] | null = null; + + constructor(options: PanGestureRecognizerOptions = {}) { + super({ + name: 'RefreshPull', + direction: 'vertical', + maximumNumberOfTouches: 1, + allowedPointerTypes: ['touch'], + ...options, + }); + } + + /** Native scrolling keeps the finger: the pull only reads it. */ + override get claimsTouches(): boolean { + return false; + } + + protected override touchesBegan( + touches: ReadonlyArray, + event: GestureEventContext, + ): void { + if (this.numberOfTouches === touches.length) { + const touch = touches[0]; + this.pointerType = touch?.pointerType ?? 'touch'; + this.scrollType = touch?.scrollType ?? null; + this.onTouchDown?.(event.time); + } + super.touchesBegan(touches, event); + } +} + +/** + * The scroll pull: a trackpad's two-finger scroll at the top. It is a + * scroll-edge pan that takes a trackpad's scroll and no pointer. So it takes a + * scroll only where nothing under the pointer could scroll: the owner at its + * top and the content moving down. The host cancels each wheel event of a + * gesture that it takes, so its element gets a blocking `wheel` listener. Only + * a recognizer that claims may register one. It takes no pointer, so it adds + * no `touchmove` listener. + */ +export class RefreshScrollPullRecognizer extends RefreshPullRecognizer { + constructor(options: PanGestureRecognizerOptions = {}) { + super({ + name: 'RefreshScrollPull', + scrollEdge: true, + allowedPointerTypes: [], + allowedScrollTypes: ['continuous'], + ...options, + }); + } + + /** The scroll it takes is its own: the host cancels its wheel events. */ + override get claimsTouches(): boolean { + return true; + } +} diff --git a/packages/lab/src/RefreshControl/__tests__/RefreshControl.interaction.browser.spec.ts b/packages/lab/src/RefreshControl/__tests__/RefreshControl.interaction.browser.spec.ts new file mode 100644 index 0000000000000..5eb67caa51ad7 --- /dev/null +++ b/packages/lab/src/RefreshControl/__tests__/RefreshControl.interaction.browser.spec.ts @@ -0,0 +1,1454 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file RefreshControl.interaction.browser.spec.ts + * @input The built pull-to-refresh stories (useRefreshControl in an app's + * scroll container), real touch input (Chromium CDP and WebKit's input + * command) and the interaction harness + * @output Interaction and animation proofs for the pull to refresh + * @position Interaction tests of packages/lab/src/RefreshControl + * (useRefreshControl), on the shape of the BottomSheetDetent exemplar + */ + +// The proofs: the pull follows UIKit's measured mapping and settles back below +// the trigger. Past the trigger, the refresh starts with the finger down, and +// the content settles onto the 60 px inset. The settle follows the scroll +// view's bounce spring. The end plays the theme's duration token nearest +// UIKit's 0.3 s, on the move easing. The settle keeps moving through a +// blocked main thread, with no Layout or Paint per frame. A list that fits +// its container keeps the browser's scroll. Under Reduce Motion, a release +// and the end only fade, within 200 ms. A trackpad's scroll at the top +// pulls. A mouse's or a pen's drag stays the browser's, and a mouse wheel's +// notches never pull. +// +// The harness's touch contexts report a coarse pointer in both engines, so +// every proof runs as a phone. The desktop proofs report a fine one. +// +// The oracles are UIKit's numbers, written here apart from the code under +// test. The pan's hysteresis is 10 px, and 60 px follow one to one. Then +// UIScrollView's rubber band applies to the excess (c = 0.55, d = the +// scroller's height). The trigger is at max(73, 0.198 × d) px of overscroll. +// The settle uses response 0.5 s and damping 1. UIKit's end takes 300 ms, +// and the page's own tokens give the end's duration and easing. + +import { + expect, + test, + type Browser, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + blockMainThread, + busyWindowProof, + compareCurve, + countBetween, + cubicBezier, + drag, + frames, + markElement, + openStory, + path, + releaseAnimations, + rubberBand, + springStep, + startBusyControl, + startCompositorTrace, + startScreencast, + timeline, + trackControl, + touchDriver, + toTouchEvents, + traceRendering, + trackMarker, + withStorybook, + writeEvidence, + type TouchDriver, + PEN_SKIP, + webInputDriver, +} from '@astryxdesign/interaction-harness'; + +import {refreshControl} from '../refreshValues'; + +const storybook = withStorybook(test); + +/** UIKit's end, measured: `endRefreshing()` moves the content over 0.3 s. */ +const UIKIT_END_MS = 300; + +/** A CSS time in ms, for the page's duration tokens. */ +function timeMs(value: string): number { + const match = /^\s*(\d*\.?\d+)(ms|s)\s*$/.exec(value); + if (match == null) { + throw new Error(`timeMs: not a CSS time: "${value}"`); + } + return Number(match[1]) * (match[2] === 's' ? 1000 : 1); +} + +/** The control points of a CSS cubic-bezier easing, for the page's tokens. */ +function bezierPoints(value: string): [number, number, number, number] { + const match = /^\s*cubic-bezier\(([^)]*)\)\s*$/.exec(value); + const points = match?.[1].split(',').map(Number) ?? []; + if (points.length !== 4 || points.some(n => !Number.isFinite(n))) { + throw new Error(`bezierPoints: not a cubic-bezier: "${value}"`); + } + return points as [number, number, number, number]; +} + +/** The theme tokens at the content, as the page computes them. */ +const tokensAt = (content: Locator, names: readonly string[]) => + content.evaluate( + (element, list) => + Object.fromEntries( + list.map(name => [ + name, + getComputedStyle(element).getPropertyValue(name).trim(), + ]), + ), + [...names], + ); + +const HYSTERESIS = 10; +const HEIGHT = 60; +/** + * Three frames at 60 Hz. A Web Animation's start resolves to the time of the + * frame that started it. On a loaded machine, that frame can lie a frame or + * two before the task that made it. A start dated before a busy task that it + * waited on lies a whole block earlier. + */ +const START_SLACK_MS = 50; + +/** UIKit's trigger distance for a scroll view `dimension` tall. */ +const triggerFor = (dimension: number) => Math.max(73, 0.198 * dimension); + +/** UIKit's refresh pull: overscroll shown for `travel` px of finger travel. */ +function uikitPull(travel: number, dimension: number): number { + const u = travel - HYSTERESIS; + if (u <= 0) { + return 0; + } + return u <= HEIGHT ? u : HEIGHT + rubberBand(u - HEIGHT, dimension); +} + +interface Opened { + driver: TouchDriver; + /** The pulled content (the element under the hook's `contentRef`). */ + content: Locator; + /** Where the finger lands: on the list, near the top of the screen. */ + start: {x: number; y: number}; + /** The scroll owner's height: the rubber band's dimension. */ + dimension: number; +} + +async function openRefresh( + page: Page, + story = 'lab-pull-to-refresh--in-a-scroll-container', + args: Record = {}, +): Promise { + await openStory(page, storybook(), story, args); + const driver = await touchDriver(page); + const content = page.locator('[data-refresh-content]').first(); + await expect(content).toBeVisible(); + const dimension = await content.evaluate(element => { + for (let node = element.parentElement; node; node = node.parentElement) { + const overflow = getComputedStyle(node).overflowY; + if (overflow === 'auto' || overflow === 'scroll') { + return node.clientHeight; + } + } + return window.innerHeight; + }); + return {driver, content, start: {x: 200, y: 160}, dimension}; +} + +/** The content's presented translation, px (works while animations are held). */ +const shownPull = (content: Locator) => + content.evaluate(element => { + const value = getComputedStyle(element).translate; + if (value === 'none' || value === '') { + return 0; + } + return parseFloat(value.split(/\s+/)[1] ?? '0'); + }); + +const isBusy = (content: Locator) => + content.evaluate(element => element.getAttribute('aria-busy') === 'true'); + +/** + * Ends the story's refresh, which `refreshMs: '-1'` holds until now. A test + * that times the end starts it on cue, so a slow pull cannot outrun a clock. + */ +const endRefresh = (page: Page) => + page.evaluate(() => { + window.dispatchEvent(new Event('refreshcontrol-story-end')); + }); + +/** + * Waits for an animation of the content itself (not an indicator's endless + * spin inside it) and returns its active interval on the page clock. With + * `afterRefresh`, only once the refresh has ended (the end of a refresh); + * with `hold`, it is paused where it was found, ready for sampling. + */ +async function waitForSettle( + content: Locator, + { + minProgressMs = 1, + afterRefresh = false, + hold = false, + timeout = 6000, + }: { + minProgressMs?: number; + afterRefresh?: boolean; + hold?: boolean; + timeout?: number; + } = {}, +): Promise<{from: number; to: number}> { + return content.evaluate( + (element, options) => + new Promise<{from: number; to: number}>((resolve, reject) => { + const deadline = performance.now() + options.timeout; + const tick = () => { + const running = element + .getAnimations() + .filter( + a => + a.playState === 'running' && + a.startTime != null && + Number(a.currentTime ?? 0) >= options.minProgressMs, + ); + const ready = + running.length > 0 && + (!options.afterRefresh || + element.getAttribute('aria-busy') !== 'true'); + if (ready) { + if (options.hold) { + for (const animation of running) { + animation.pause(); + } + ( + window as unknown as {__harnessHeld?: Animation[]} + ).__harnessHeld = running; + } + const timing = running[0].effect?.getComputedTiming(); + const from = + performance.timeOrigin + + Number(running[0].startTime) + + Number(timing?.delay ?? 0); + resolve({from, to: from + Number(timing?.activeDuration ?? 0)}); + return; + } + if (performance.now() > deadline) { + reject(new Error('waitForSettle: no animation on the content')); + return; + } + requestAnimationFrame(tick); + }; + tick(); + }), + {minProgressMs, afterRefresh, hold, timeout}, + ); +} + +/** Resolves once the content itself holds still (an indicator may spin on). */ +async function waitForContentRest( + content: Locator, + timeout = 6000, +): Promise { + await content.evaluate( + (element, ms) => + new Promise((resolve, reject) => { + const deadline = performance.now() + ms; + let last = ''; + let still = 0; + const tick = () => { + const translate = getComputedStyle(element).translate; + const moving = element + .getAnimations() + .some(a => a.playState === 'running'); + still = !moving && translate === last ? still + 1 : 0; + last = translate; + if (still >= 2) { + resolve(); + return; + } + if (performance.now() > deadline) { + reject( + new Error(`waitForContentRest: still moving (${translate})`), + ); + return; + } + requestAnimationFrame(tick); + }; + tick(); + }), + timeout, + ); +} + +/** A slow pull that rests before the lift (release velocity 0). */ +function slowPull(from: {x: number; y: number}, dy: number, restMs = 150) { + return drag( + from, + {x: from.x, y: from.y + dy}, + {durationMs: Math.max(200, dy * 5), hz: 60, restMs}, + ); +} + +/** Samples a held animation's presented translation at each time. */ +async function sampleTranslate( + content: Locator, + times: readonly number[], +): Promise<{t: number; value: number}[]> { + return content.evaluate( + (element, ts) => { + const held = + (window as unknown as {__harnessHeld?: Animation[]}).__harnessHeld ?? + []; + return ts.map(t => { + for (const animation of held) { + const end = Number( + animation.effect?.getComputedTiming().endTime ?? Infinity, + ); + animation.currentTime = Math.min(t, end - 0.5); + } + const value = getComputedStyle(element).translate; + return { + t, + value: + value === 'none' || value === '' + ? 0 + : parseFloat(value.split(/\s+/)[1] ?? '0'), + }; + }); + }, + [...times], + ); +} + +/** Reads the shown pull after every move of a script, while the finger is down. */ +async function playReading( + page: Page, + driver: TouchDriver, + content: Locator, + script: ReturnType, + onLastMove?: () => Promise, +): Promise<{travel: number; shown: number}[]> { + const startY = script[0].fingers[0].y; + const moves = toTouchEvents(script).filter(e => e.type === 'touchMove'); + const readings: {travel: number; shown: number}[] = []; + let index = 0; + await driver.play(script, { + onEvent: async step => { + if (step.type !== 'touchMove') { + return; + } + await frames(page, 1); + const y = step.changed[0]?.y ?? step.fingers[0]?.y ?? startY; + readings.push({travel: y - startY, shown: await shownPull(content)}); + if (index === moves.length - 1) { + await onLastMove?.(); + } + index++; + }, + }); + return readings; +} + +test('a pull follows UIKit’s mapping and settles back below the trigger', async ({ + page, +}) => { + const {driver, content, start, dimension} = await openRefresh(page); + const readings = await playReading( + page, + driver, + content, + slowPull(start, 76), + ); + // Every reading sits on UIKit's curve for its finger travel (the page may + // lag the finger by a frame: compare with the travel's neighbours). + const last = readings.at(-1); + expect(last?.shown ?? NaN).toBeCloseTo(uikitPull(76, dimension), 0); + for (const {travel, shown} of readings) { + expect(shown).toBeLessThanOrEqual(uikitPull(travel, dimension) + 1); + } + expect(Math.max(...readings.map(r => r.shown))).toBeLessThan( + triggerFor(dimension), + ); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(0, 1); + expect(await isBusy(content)).toBe(false); +}); + +test('past the trigger the refresh starts with the finger down, then settles onto the inset', async ({ + page, +}) => { + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '6000', + }); + let busyWhileDown = false; + await playReading( + page, + driver, + content, + slowPull(start, 300, 200), + async () => { + busyWhileDown = await isBusy(content); + }, + ); + expect(busyWhileDown).toBe(true); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 0); + expect(await isBusy(content)).toBe(true); +}); + +test('the settle onto the inset follows the scroll view’s bounce spring', async ({ + page, +}, testInfo) => { + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '6000', + }); + await driver.play(slowPull(start, 300, 200)); + await waitForSettle(content, {hold: true}); + const times = timeline(700); + const samples = await sampleTranslate(content, times); + await releaseAnimations(page); + const from = samples[0].value; + // scroll.bounce: {duration 0.5, bounce 0} = response 0.5 s, damping 1. + const oracle = (t: number) => + from + (HEIGHT - from) * springStep({response: 0.5, dampingFraction: 1}, t); + const result = compareCurve(samples, oracle, 1); + await writeEvidence( + 'curves/refresh-settle', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {samples, result}, + null, + 1, + ), + }, + testInfo, + ); + expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual(1); + expect(samples.at(-1)?.value).toBeCloseTo(HEIGHT, 0); +}); + +test('the end slides the content up on the theme’s duration and move easing tokens (spec:AST-094 FR45)', async ({ + page, +}, testInfo) => { + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '-1', + }); + const tokens = await tokensAt(content, ['--duration-medium', '--ease-move']); + const ms = timeMs(tokens['--duration-medium']); + await driver.play(slowPull(start, 300, 200)); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 0); + await endRefresh(page); + await waitForSettle(content, {afterRefresh: true, hold: true}); + const samples = await sampleTranslate(content, timeline(ms)); + await releaseAnimations(page); + const ease = cubicBezier(...bezierPoints(tokens['--ease-move'])); + const oracle = (t: number) => HEIGHT * (1 - ease(Math.min(1, t / ms))); + const result = compareCurve(samples, oracle, 0.75); + await writeEvidence( + 'curves/refresh-end', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {samples, result}, + null, + 1, + ), + }, + testInfo, + ); + expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual( + 0.75, + ); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(0, 1); +}); + +test('the settle keeps moving every frame while the main thread is blocked', async ({ + page, + browserName, +}, testInfo) => { + test.skip( + browserName !== 'chromium', + 'screencast frame evidence is Chromium-only in Playwright (WebKit: the iOS simulator rig)', + ); + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '6000', + }); + await markElement(content); + // The harness's busy-window control: a box the compositor moves along the + // top edge, in the same screencast. The settle is judged against what the + // compositor presented, not against a frame rate. + const control = await startBusyControl(page); + const cast = await startScreencast(page); + // The compositor's own frames: a loaded machine's screencast skips frames + // the compositor still presents, and the verdict measures those gaps + // between the compositor's frames instead. + const compositor = await startCompositorTrace(page); + await driver.play(slowPull(start, 300, 200)); + // The settle must be running (and composited) before the block: an + // animation cannot start while the main thread is held. + const settle = await waitForSettle(content, {minProgressMs: 16}); + const block = await blockMainThread(page, 400); + await page.waitForTimeout(150); + const castFrames = await cast.stop(); + const presented = await compositor.stop(); + await control.remove(); + const tracked = await trackMarker(page, castFrames); + const controlFrames = await trackControl( + page, + castFrames.filter(f => f.t >= block.from - 300 && f.t <= block.to + 100), + ); + const proof = busyWindowProof( + tracked, + {from: block.from, to: Math.min(block.to, settle.to)}, + {settledWithin: 3, presented, control: controlFrames}, + ); + await writeEvidence( + 'busy-main-thread/refresh-settle', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + { + block, + settle, + proof, + frames: tracked.map(f => ({ + t: +(f.t - settle.from).toFixed(1), + y: f.box?.y ?? null, + })), + }, + null, + 1, + ), + }, + testInfo, + ); + // The screencast resolves whole CSS pixels, so the proof judges until 3 px + // from rest. The settle moves on every frame the control moves on, and it + // stalls no longer than the control. + expect(proof.verdict.failures, proof.summary).toEqual([]); +}); + +test('the settle does no Layout or Paint per frame', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only'); + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '6000', + }); + // The indicator is the app's: Core's Spinner here. Its turn does style work + // every few frames, and that paints inside the moving band. With the turn + // paused, the settle paints nothing. So the proof pauses the turn, and the + // Spinner stays in place, laid out and painted. + const spinner = await content.evaluate(element => { + const band = element.querySelector(':scope > :last-child > div'); + for (const node of band?.querySelectorAll('*') ?? []) { + if (getComputedStyle(node).animationName !== 'none') { + node.style.animationPlayState = 'paused'; + } + } + const box = band?.querySelector('svg')?.getBoundingClientRect(); + return {width: box?.width ?? 0, height: box?.height ?? 0}; + }); + expect(spinner.width).toBeGreaterThan(0); + expect(spinner.height).toBeGreaterThan(0); + let settle = {from: 0, to: 0}; + let steadyFrom = 0; + const trace = await traceRendering(page, async () => { + await driver.play(slowPull(start, 300, 200)); + settle = await waitForSettle(content); + // The release commits over the settle's first frames. The steady part + // starts once the page renders three more frames. They are counted in + // frames, not ms, so a loaded machine that draws them late is judged the + // same. + steadyFrom = await page.evaluate( + () => + new Promise(resolve => { + let left = 3; + const tick = () => { + left -= 1; + if (left > 0) { + requestAnimationFrame(tick); + return; + } + // A task after this frame has rendered. + setTimeout(() => + resolve(performance.timeOrigin + performance.now()), + ); + }; + requestAnimationFrame(tick); + }), + ); + // A fixed wait: polling the content's style every frame would itself + // recalculate style. + await page.waitForTimeout(900); + }); + // The steady part of the settle, until it is within a pixel of rest. + const from = Math.max(settle.from + 50, steadyFrom); + const to = settle.from + 600; + const judged = `judged ${(from - settle.from).toFixed(0)}–600 ms into the settle`; + // Too little left to judge fails rather than passes. + expect(to - from, judged).toBeGreaterThan(200); + const during = countBetween(trace, from, to); + expect(during.Layout ?? 0, `${judged}: ${JSON.stringify(during)}`).toBe(0); + expect(during.Paint ?? 0, `${judged}: ${JSON.stringify(during)}`).toBe(0); + // Main-thread work during that part; the pull's trigger and the release's + // render are not the settle's. + const blocking = trace.longTasks.filter( + task => task.start < to && task.start + task.durationMs > from, + ); + expect( + blocking, + `${judged}; long tasks, ms into the settle: ${JSON.stringify( + trace.longTasks.map(task => [ + +(task.start - settle.from).toFixed(1), + +task.durationMs.toFixed(1), + ]), + )}`, + ).toEqual([]); +}); + +test('a list shorter than the screen still pulls and refreshes', async ({ + page, +}) => { + // The story's content is 1 px taller than its container, so the container + // overflows. + const {driver, content, start} = await openRefresh( + page, + 'lab-pull-to-refresh--short-list', + {refreshMs: '6000'}, + ); + await driver.play(slowPull(start, 300, 200)); + await waitForContentRest(content); + expect(await isBusy(content)).toBe(true); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 0); +}); + +test('a list that fits its container leaves the scroll to the browser: no containment and no pull (spec:AST-025 FR14)', async ({ + page, +}) => { + const {driver, content, start} = await openRefresh( + page, + 'lab-pull-to-refresh--short-list', + {refreshMs: '6000'}, + ); + const scroller = page.locator('[data-refresh-scroller]').first(); + const containment = () => + scroller.evaluate(element => getComputedStyle(element).overscrollBehaviorY); + // With the extra pixel, the container overflows and the pull holds its top. + await expect.poll(containment).toBe('none'); + // Without it, the list fits. + await content.evaluate(element => { + element.style.minHeight = '0px'; + }); + await expect.poll(containment).toBe('auto'); + await driver.play(slowPull(start, 300, 200)); + await page.waitForTimeout(250); + expect(await isBusy(content)).toBe(false); + expect(await shownPull(content)).toBe(0); +}); + +test('a pull pushed back past its start hands the finger to native scrolling', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'native scrolling from injected touches is Chromium-only (WebKit: the iOS simulator rig)', + ); + const {driver, content, start} = await openRefresh(page); + const scrollTop = () => + page + .locator('[data-refresh-scroller]') + .first() + .evaluate(el => el.scrollTop); + // Down 50 px, then up 250 px, in one touch. + const at = (progress: number) => + progress < 0.25 + ? {x: start.x, y: start.y + 50 * (progress / 0.25)} + : {x: start.x, y: start.y + 50 - 250 * ((progress - 0.25) / 0.75)}; + await driver.play(path(at, {durationMs: 900, hz: 60, restMs: 150})); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(0, 1); + expect(await isBusy(content)).toBe(false); + expect(await scrollTop()).toBeGreaterThan(50); +}); + +test('a drag that began as a scroll pulls once the content reaches the top, in the same touch', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'native scrolling from injected touches is Chromium-only (WebKit: the iOS simulator rig)', + ); + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '6000', + }); + const scroller = page.locator('[data-refresh-scroller]').first(); + const scrollTop = () => scroller.evaluate(el => el.scrollTop); + await scroller.evaluate(el => { + el.scrollTop = 80; + }); + await expect.poll(scrollTop).toBe(80); + // Down 450 px in one touch: the first 80 px scroll the content to its top + // natively, and the rest pulls past the trigger. + await driver.play(slowPull(start, 450, 200)); + await waitForContentRest(content); + expect(await scrollTop()).toBe(0); + expect(await isBusy(content)).toBe(true); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 0); +}); + +test('a pull while refreshing stretches from the inset and settles back onto it', async ({ + page, +}) => { + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '6000', + }); + await driver.play(slowPull(start, 300, 200)); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 0); + let deepest = 0; + await playReading( + page, + driver, + content, + slowPull(start, 200, 200), + async () => { + deepest = await shownPull(content); + }, + ); + // The second pull starts from the inset, not from the top. + expect(deepest).toBeGreaterThan(HEIGHT + 60); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 0); + expect(await isBusy(content)).toBe(true); +}); + +test('a finger catching the settle holds it where it is, then pulls on from there', async ({ + page, +}) => { + const {driver, content, start} = await openRefresh(page); + await driver.play(slowPull(start, 76, 150)); + // The settle back to the top is running: catch it 100 ms in. + await waitForSettle(content); + await page.waitForTimeout(100); + // Where the settle stood as the finger landed. A listener reads it before + // anything handles the touch. A reading taken earlier misses how far the + // settle moved before the touch arrived. + await content.evaluate(element => { + window.addEventListener( + 'touchstart', + () => { + const value = getComputedStyle(element).translate; + element.dataset.caughtAt = String( + value === 'none' || value === '' + ? 0 + : parseFloat(value.split(/\s+/)[1] ?? '0'), + ); + }, + {capture: true, once: true}, + ); + }); + const readings = await playReading( + page, + driver, + content, + drag( + start, + {x: start.x, y: start.y + 30}, + {durationMs: 300, hz: 60, restMs: 100}, + ), + ); + const caught = Number( + await content.evaluate(element => element.dataset.caughtAt), + ); + expect(caught).toBeGreaterThan(5); + // No jump at the catch: the first reading is where the settle stood, and + // the pull goes on from there. + expect(Math.abs(readings[0].shown - caught)).toBeLessThan(6); + expect(readings.at(-1)?.shown ?? 0).toBeGreaterThan(caught); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(0, 1); +}); + +/** The primary pointer the page reports: coarse (a touch screen) or fine. */ +async function primaryPointer(page: Page, kind: 'coarse' | 'fine') { + await page.addInitScript(coarse => { + const native = window.matchMedia.bind(window); + window.matchMedia = (query: string) => { + const pointer = /^\(\s*pointer\s*:\s*(coarse|fine|none)\s*\)$/.exec( + query.trim(), + ); + if (pointer == null) { + return native(query); + } + // A static list: the primary pointer never changes in a test. + const list = { + matches: (pointer[1] === 'coarse') === coarse, + media: query, + onchange: null, + addEventListener() {}, + removeEventListener() {}, + addListener() {}, + removeListener() {}, + dispatchEvent: () => false, + }; + return list as unknown as MediaQueryList; + }; + }, kind === 'coarse'); +} + +interface RecordedAnimation { + part: 'content' | 'band' | 'other'; + properties: string[]; + /** How long the animated values change, ms (the held end excluded). */ + movingMs: number; + /** + * Whether anything but opacity passes through values in between (travel); + * a value that lands at once (two keyframes at one offset) does not. + */ + travels: boolean; + /** Repeats forever (an indicator's own spin, outside the record). */ + endless: boolean; + /** When it was created (`performance.now()`). */ + at: number; +} + +/** + * Records every animation the page creates from now on, and when the + * refresh's busy state clears. + */ +async function recordAnimations(page: Page) { + await page.evaluate(() => { + const log: unknown[] = []; + const record = window as unknown as { + __animations: unknown[]; + __endedAt: number | null; + }; + record.__animations = log; + record.__endedAt = null; + const content = document.querySelector('[data-refresh-content]'); + if (content != null) { + new MutationObserver(() => { + if (!content.hasAttribute('aria-busy') && record.__endedAt == null) { + record.__endedAt = performance.now(); + } + }).observe(content, {attributes: true, attributeFilter: ['aria-busy']}); + } + const native = Element.prototype.animate; + Element.prototype.animate = function (keyframes, options) { + const animation = native.call(this, keyframes, options); + const content = document.querySelector('[data-refresh-content]'); + const band = content?.querySelector(':scope > :last-child > div'); + const part = + this === content ? 'content' : this === band ? 'band' : 'other'; + const effect = animation.effect as KeyframeEffect | null; + const frames = effect?.getKeyframes() ?? []; + const skip = new Set(['offset', 'computedOffset', 'easing', 'composite']); + const properties = [ + ...new Set( + frames.flatMap(f => Object.keys(f).filter(k => !skip.has(k))), + ), + ]; + const timing = effect?.getComputedTiming(); + const duration = Number(timing?.duration ?? 0); + const last = frames.at(-1); + let movingMs = 0; + for (let i = frames.length - 1; i > 0; i--) { + if (properties.some(p => frames[i - 1][p] !== last?.[p])) { + movingMs = Number(frames[i].computedOffset) * duration; + break; + } + } + const travels = properties + .filter(p => p !== 'opacity') + .some(p => + frames.some((frame, i) => { + const next = frames[i + 1]; + return ( + next != null && + frame[p] !== next[p] && + Number(next.computedOffset) > Number(frame.computedOffset) && + !/^step/.test(String(frame.easing ?? 'linear')) + ); + }), + ); + log.push({ + part, + properties, + movingMs, + travels, + endless: timing?.iterations === Infinity, + at: performance.now(), + }); + return animation; + }; + }); +} + +const recordedAnimations = (page: Page) => + page.evaluate( + () => + (window as unknown as {__animations: RecordedAnimation[]}).__animations, + ); + +/** The animations created once the refresh's busy state cleared: the end's. */ +const recordedEnd = (page: Page) => + page.evaluate(() => { + const record = window as unknown as { + __animations: RecordedAnimation[]; + __endedAt: number | null; + }; + const endedAt = record.__endedAt ?? Infinity; + return record.__animations.filter(a => a.at >= endedAt); + }); + +/** + * The record's failures among recorded transitions (spins excluded): travel, + * or values still changing after 200 ms. + */ +function reducedMotionFailures(log: readonly RecordedAnimation[]) { + return log.filter( + a => a.part !== 'other' && !a.endless && (a.travels || a.movingMs > 200), + ); +} + +test('under Reduce Motion a release cross-fades onto the inset: opacity only, within 200 ms', async ({ + page, +}) => { + // Under Reduce Motion, a transition that a touch release starts only fades + // its opacity, in 200 ms or less. Nothing moves. + await page.emulateMedia({reducedMotion: 'reduce'}); + await primaryPointer(page, 'coarse'); + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '6000', + }); + await recordAnimations(page); + await driver.play(slowPull(start, 300, 200)); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 1); + const log = await recordedAnimations(page); + expect(reducedMotionFailures(log), JSON.stringify(log)).toEqual([]); + // A change with no cross-fade fails too. + expect( + log.some(a => a.part === 'content' && a.properties.includes('opacity')), + JSON.stringify(log), + ).toBe(true); +}); + +test('under Reduce Motion the end cross-fades on a touch screen, and a `--motion-…` variable changes nothing', async ({ + page, +}) => { + // The refresh control's values are internal constants. So no `--motion-…` + // variable restores travel or a longer animation under Reduce Motion. + await page.emulateMedia({reducedMotion: 'reduce'}); + await primaryPointer(page, 'coarse'); + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '-1', + }); + await page.evaluate(() => { + const root = document.documentElement.style; + root.setProperty('--motion-refresh-control-end-ms', '2000ms'); + root.setProperty('--motion-refresh-control-exit-ms', '2000ms'); + }); + await recordAnimations(page); + await driver.play(slowPull(start, 300, 200)); + await waitForContentRest(content); + await endRefresh(page); + await expect.poll(() => isBusy(content), {timeout: 8000}).toBe(false); + await page.waitForTimeout(100); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(0, 1); + const log = await recordedEnd(page); + expect(reducedMotionFailures(log), JSON.stringify(log)).toEqual([]); + expect( + log.some(a => a.part === 'content' && a.properties.includes('opacity')), + JSON.stringify(log), + ).toBe(true); +}); + +test('the end plays the neutral theme’s duration token nearest UIKit’s measured end (spec:AST-094 FR45)', async ({ + page, +}) => { + const {content} = await openRefresh(page, undefined, {refreshMs: '-1'}); + const steps = ['fast', 'medium', 'slow'].flatMap(band => [ + `--duration-${band}-min`, + `--duration-${band}`, + `--duration-${band}-max`, + ]); + const tokens = await tokensAt(content, steps); + // The Storybook theme is neutral: its fast, medium and slow bases. + expect( + ['--duration-fast', '--duration-medium', '--duration-slow'].map(name => + timeMs(tokens[name]), + ), + JSON.stringify(tokens), + ).toEqual([125, 300, 700]); + const nearest = steps.reduce((best, name) => + Math.abs(timeMs(tokens[name]) - UIKIT_END_MS) < + Math.abs(timeMs(tokens[best]) - UIKIT_END_MS) + ? name + : best, + ); + // The measurement stays in the motion table as the reference. + expect(refreshControl.endMs).toBe(UIKIT_END_MS); + expect(refreshControl.endDurationToken, JSON.stringify(tokens)).toBe(nearest); +}); + +test('a theme’s duration token retimes the end, and a `--motion-…` variable does not (spec:AST-094 FR45)', async ({ + page, +}) => { + // The end reads the theme's duration token at its start. The refresh + // control's own values are internal constants, so no variable retunes them. + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '-1', + }); + await content.evaluate(element => { + element.style.setProperty('--duration-medium', '600ms'); + document.documentElement.style.setProperty( + '--motion-refresh-control-end-ms', + '2000ms', + ); + }); + await recordAnimations(page); + await driver.play(slowPull(start, 300, 200)); + await waitForContentRest(content); + await endRefresh(page); + await expect.poll(() => isBusy(content), {timeout: 8000}).toBe(false); + await page.waitForTimeout(100); + await waitForContentRest(content); + const log = await recordedEnd(page); + const slide = log.find( + a => a.part === 'content' && a.properties.includes('translate'), + ); + expect(slide, JSON.stringify(log)).toBeDefined(); + expect(Math.abs((slide?.movingMs ?? 0) - 600)).toBeLessThan(20); +}); + +/** A desktop context: no touch screen, so CSS and script read a fine pointer. */ +async function desktopPage( + browser: Browser, + options: {reducedMotion?: 'reduce'} = {}, +) { + const context = await browser.newContext({ + viewport: {width: 402, height: 714}, + hasTouch: false, + isMobile: false, + ...options, + }); + const page = await context.newPage(); + await openStory( + page, + storybook(), + 'lab-pull-to-refresh--in-a-scroll-container', + { + refreshMs: '6000', + }, + ); + const pointer = await page.evaluate(() => ({ + coarse: matchMedia('(pointer: coarse)').matches, + fine: matchMedia('(pointer: fine)').matches, + })); + expect(pointer).toEqual({coarse: false, fine: true}); + const content = page.locator('[data-refresh-content]').first(); + await expect(content).toBeVisible(); + return {context, page, content}; +} + +/** A mouse drag down from the top of the page, 15 px a step. */ +async function mousePull(page: Page, content: Locator, steps: number) { + await page.mouse.move(200, 160); + await page.mouse.down(); + const shown: number[] = []; + for (let step = 1; step <= steps; step++) { + await page.mouse.move(200, 160 + step * 15); + shown.push(await shownPull(content)); + } + await page.mouse.up(); + return shown; +} + +/** A pen stroke down from the top of the page: 300 px, 15 px every 16 ms. */ +async function penPull(page: Page) { + const driver = await webInputDriver(page); + await driver.pen( + Array.from({length: 21}, (_, step) => ({ + x: 200, + y: 160 + step * 15, + t: step * 16, + })), + ); +} + +/** + * Resolves once the content's settle starts: the release of a pull that + * ended without a lift (a trackpad's scroll ends when its gesture does). + */ +async function waitForSettleStart(content: Locator, timeout = 3000) { + await content.evaluate( + (element, ms) => + new Promise((resolve, reject) => { + const deadline = performance.now() + ms; + const tick = () => { + if (element.getAnimations().some(a => a.playState === 'running')) { + resolve(); + return; + } + if (performance.now() > deadline) { + reject( + new Error('waitForSettleStart: the pull was never released'), + ); + return; + } + requestAnimationFrame(tick); + }; + tick(); + }), + timeout, + ); +} + +/** The list's scroll position once it has stopped moving (a smooth scroll ends). */ +async function listScrollRest(page: Page, timeout = 3000): Promise { + return page.evaluate( + ms => + new Promise((resolve, reject) => { + const deadline = performance.now() + ms; + const scroller = document.querySelector('[data-refresh-scroller]'); + let last = Number.NaN; + let still = 0; + const tick = () => { + const y = scroller?.scrollTop ?? Number.NaN; + still = y === last ? still + 1 : 0; + last = y; + if (still >= 3) { + resolve(y); + return; + } + if (performance.now() > deadline) { + reject(new Error(`listScrollRest: still scrolling (${y})`)); + return; + } + requestAnimationFrame(tick); + }; + tick(); + }), + timeout, + ); +} + +/** Why the trackpad proofs run in WebKit only. */ +const TRACKPAD_SKIP = + "Chromium's driver sends each wheel step as a mouse wheel's notch; WebKit's sends a trackpad's precise deltas"; +/** Why the mouse wheel proof runs in Chromium only. */ +const MOUSE_WHEEL_SKIP = + "WebKit's driver sends a trackpad's precise deltas; Chromium's sends each wheel step as a mouse wheel's notch"; + +/** + * Wheel steps of `dy` CSS px over the content. Chromium's driver sends each + * step as a mouse wheel's notch, and WebKit's as a trackpad's precise deltas. + */ +async function scrollWheel(page: Page, steps: number, dy: number) { + const driver = await webInputDriver(page); + for (let step = 0; step < steps; step++) { + await driver.wheel({x: 200, y: 300, dy}); + } +} + +test('with a trackpad, a two-finger scroll at the top pulls and refreshes as a finger does (spec:AST-094 FR43)', async ({ + browser, + browserName, +}) => { + test.skip(browserName === 'chromium', TRACKPAD_SKIP); + const {context, page, content} = await desktopPage(browser); + try { + // 300 px of scroll toward the top: past the trigger. + await scrollWheel(page, 30, -10); + // The scroll's gesture ends after its last step. The pull's release + // starts the settle, and the content comes to rest on the inset. + await waitForSettleStart(content); + await waitForContentRest(content); + expect(await isBusy(content)).toBe(true); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 0); + } finally { + await context.close(); + } +}); + +test('a scroll down the list and back up short of its top stays the list’s and pulls nothing (spec:AST-094 FR43)', async ({ + browser, +}) => { + const {context, page, content} = await desktopPage(browser); + try { + // A scroll down from the top is the list's, not the pull's. + await scrollWheel(page, 20, 10); + const scrolled = await listScrollRest(page); + expect(scrolled).toBeGreaterThan(100); + // Back up, short of the top: still the list's. + await scrollWheel(page, 5, -10); + const back = await listScrollRest(page); + expect(back).toBeLessThan(scrolled); + expect(back).toBeGreaterThan(0); + expect(await shownPull(content)).toBe(0); + expect(await isBusy(content)).toBe(false); + } finally { + await context.close(); + } +}); + +test('a mouse wheel’s notches at the top never pull: they scroll what is under the pointer (spec:AST-094 FR43)', async ({ + browser, + browserName, +}) => { + test.skip(browserName !== 'chromium', MOUSE_WHEEL_SKIP); + const {context, page, content} = await desktopPage(browser); + try { + await scrollWheel(page, 3, -100); + await page.waitForTimeout(250); + expect(await shownPull(content)).toBe(0); + expect(await isBusy(content)).toBe(false); + } finally { + await context.close(); + } +}); + +test('with a mouse, a drag at the top stays the browser’s and never pulls', async ({ + browser, +}) => { + const {context, page, content} = await desktopPage(browser); + try { + const shown = await mousePull(page, content, 20); + expect(shown, JSON.stringify(shown)).toEqual(shown.map(() => 0)); + expect(await isBusy(content)).toBe(false); + } finally { + await context.close(); + } +}); + +test('with a pen, a drag at the top stays the browser’s and never pulls', async ({ + browser, + browserName, +}) => { + // A pen exists only in Chromium's input. + test.skip(browserName !== 'chromium', PEN_SKIP); + const {context, page, content} = await desktopPage(browser); + try { + await penPull(page); + await page.waitForTimeout(250); + expect(await shownPull(content)).toBe(0); + expect(await isBusy(content)).toBe(false); + } finally { + await context.close(); + } +}); + +/** The top of the indicator band, in px below the scroll view's top. */ +const indicatorTop = (content: Locator) => + content.evaluate(element => { + const band = element.querySelector(':scope > :last-child > div'); + let scroller = element.parentElement; + while ( + scroller != null && + !/auto|scroll/.test(getComputedStyle(scroller).overflowY) + ) { + scroller = scroller.parentElement; + } + const top = scroller?.getBoundingClientRect().top ?? 0; + return (band?.getBoundingClientRect().top ?? NaN) - top; + }); + +test('the indicator stays at the top of the scroll view while the content is pulled and settles, as UIRefreshControl’s does', async ({ + page, +}) => { + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '6000', + }); + const readings: {shown: number; indicator: number}[] = []; + await driver.play(slowPull(start, 300, 150), { + onEvent: async step => { + if (step.type !== 'touchMove') { + return; + } + await frames(page, 1); + readings.push({ + shown: await shownPull(content), + indicator: await indicatorTop(content), + }); + }, + }); + await waitForContentRest(content); + const revealed = readings.filter(r => r.shown >= HEIGHT + 10); + const shown = revealed.map(r => r.shown); + const indicator = revealed.map(r => r.indicator); + // The content travelled while the indicator held still. + expect(Math.max(...shown) - Math.min(...shown)).toBeGreaterThan(40); + expect(Math.max(...indicator) - Math.min(...indicator)).toBeLessThanOrEqual( + 1, + ); + // Settled onto the inset, it is where it was during the pull. + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 0); + expect( + Math.abs((await indicatorTop(content)) - indicator[0]), + ).toBeLessThanOrEqual(1); +}); + +/** + * Watches the content's animations every frame from `from`: the finger's lift + * or the refresh's end. Right after it, the watcher blocks the main thread for + * `blockMs`, as a busy app would, and records when the block ends. After the + * lift, the block runs in its own task, and on a loaded machine the next frame + * can come first. After the end, it runs in the commit that ends the busy + * state. For each animation on the content, the watcher records when the main + * thread first saw it, and when its curve starts on the document timeline. + */ +async function sampleAfter( + content: Locator, + from: 'lift' | 'end', + blockMs: number, +): Promise { + await content.evaluate( + (element, {from, blockMs}) => { + let frames = 0; + const tracked: { + animation: Animation; + seen: number; + start: number | null; + }[] = []; + (window as unknown as {__tracked: typeof tracked}).__tracked = tracked; + const track = () => { + const now = performance.now(); + for (const animation of element.getAnimations()) { + let entry = tracked.find(item => item.animation === animation); + if (entry == null) { + entry = {animation, seen: now, start: null}; + tracked.push(entry); + } + if (entry.start == null && animation.startTime != null) { + entry.start = Number(animation.startTime); + } + } + }; + const block = () => { + const until = performance.now() + blockMs; + while (performance.now() < until) { + // A busy app. + } + (window as unknown as {__blockEnd: number}).__blockEnd = + performance.now(); + }; + const watch = () => { + track(); + frames += 1; + if (frames < 90) { + requestAnimationFrame(watch); + } + }; + const begin = () => { + track(); + requestAnimationFrame(watch); + }; + if (from === 'lift') { + addEventListener( + 'touchend', + () => { + begin(); + setTimeout(block, 0); + }, + {once: true}, + ); + } else { + const observer = new MutationObserver(() => { + if (element.getAttribute('aria-busy') !== 'true') { + observer.disconnect(); + begin(); + block(); + } + }); + observer.observe(element, { + attributes: true, + attributeFilter: ['aria-busy'], + }); + } + }, + {from, blockMs}, + ); +} + +/** + * The first animation the content ran after `sampleAfter`'s moment: when the + * main thread first saw it, and when its curve starts on the document + * timeline. + */ +async function firstAnimation( + page: Page, +): Promise<{seen: number; start: number | null} | null> { + return page.evaluate(() => { + const [first] = ( + window as unknown as { + __tracked: {seen: number; start: number | null}[]; + } + ).__tracked; + return first == null ? null : {seen: first.seen, start: first.start}; + }); +} + +test('the settle starts where its curve starts, even when the page is busy right after the lift', async ({ + page, +}) => { + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '6000', + }); + await sampleAfter(content, 'lift', 250); + await driver.play(slowPull(start, 300, 150)); + await page.waitForTimeout(1200); + // The settle is made in the lift's own task. It starts at the next frame + // that the main thread commits, before or after the busy task. Before it, + // the compositor plays the settle through the block. Either way, its curve + // starts at the frame it was made for, so its first frames show. A start + // dated before a block that it waited on would skip them. The content's + // place in the first frame after the block tells the cases apart only by + // luck. That frame carries the time it was due, or the current time on a + // loaded machine. So the proof reads the animation's own start. + const settle = await firstAnimation(page); + expect(settle).not.toBeNull(); + expect(settle?.start).not.toBeNull(); + expect(settle?.start ?? 0).toBeGreaterThanOrEqual( + (settle?.seen ?? 0) - START_SLACK_MS, + ); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 0); +}); + +test('the end slides from its start, even when the page is busy as the refresh ends', async ({ + page, +}) => { + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '-1', + }); + await sampleAfter(content, 'end', 250); + await driver.play(slowPull(start, 300, 150)); + await waitForContentRest(content); + await endRefresh(page); + await waitForSettle(content, {afterRefresh: true}); + await page.waitForTimeout(800); + // The block runs in the commit that ends the refresh, and the slide is + // made two frames later. A start dated before the block would skip the + // slide's first frames. The content's place in the first frame after the + // block tells this apart only by luck on a loaded machine. So the proof + // reads the animation's own start, as the settle's proof does. + const end = await firstAnimation(page); + const blockEnd = await page.evaluate( + () => (window as unknown as {__blockEnd: number}).__blockEnd, + ); + // The end animation and the block's end are both present first, so a + // missing one fails by name. + expect(end, JSON.stringify({end, blockEnd})).not.toBeNull(); + expect(typeof end?.start).toBe('number'); + expect(typeof blockEnd).toBe('number'); + expect(end?.start ?? 0).toBeGreaterThanOrEqual(blockEnd - START_SLACK_MS); +}); diff --git a/packages/lab/src/RefreshControl/index.ts b/packages/lab/src/RefreshControl/index.ts new file mode 100644 index 0000000000000..f20c32be64434 --- /dev/null +++ b/packages/lab/src/RefreshControl/index.ts @@ -0,0 +1,18 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file index.ts + * @input Imports from useRefreshControl + * @output Exports useRefreshControl, its types and the reveal's custom + * property + * @position Entry point for Lab's pull to refresh; re-exported by + * /packages/lab/src/index.ts + */ + +export {REFRESH_REVEAL_VAR, useRefreshControl} from './useRefreshControl'; +export type { + UseRefreshControlOptions, + UseRefreshControlResult, +} from './useRefreshControl'; diff --git a/packages/lab/src/RefreshControl/refreshIndicator.ts b/packages/lab/src/RefreshControl/refreshIndicator.ts new file mode 100644 index 0000000000000..9523c00970a3c --- /dev/null +++ b/packages/lab/src/RefreshControl/refreshIndicator.ts @@ -0,0 +1,12 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file refreshIndicator.ts + * @output The name of the custom property the touch layer writes and the + * app's indicator styles may read + * @position Internal to useRefreshControl; re-exported for the app's + * indicator styles + */ + +/** CSS custom property the indicator reads: how much of it is revealed (0–1). */ +export const REFRESH_REVEAL_VAR = '--astryx-refresh-reveal'; diff --git a/packages/lab/src/RefreshControl/refreshModel.test.ts b/packages/lab/src/RefreshControl/refreshModel.test.ts new file mode 100644 index 0000000000000..0a718622e7a8e --- /dev/null +++ b/packages/lab/src/RefreshControl/refreshModel.test.ts @@ -0,0 +1,174 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file refreshModel.test.ts + * @input vitest, refreshModel + * @output Walks UIRefreshControl's state machine: trigger once with the + * finger down, settle targets, cancel, programmatic begin and end, a pull + * while refreshing, and no-ops + * @position Testing; colocated with refreshModel.ts + */ + +import {describe, expect, it} from 'vitest'; +import { + INITIAL_REFRESH_STATE, + reduceRefresh, + type RefreshEffect, + type RefreshEvent, + type RefreshState, +} from './refreshModel'; + +function run( + events: ReadonlyArray, + from: RefreshState = INITIAL_REFRESH_STATE, +): {state: RefreshState; effects: RefreshEffect[]} { + let state = from; + const effects: RefreshEffect[] = []; + for (const event of events) { + const next = reduceRefresh(state, event); + state = next.state; + effects.push(...next.effects); + } + return {state, effects}; +} + +describe('reduceRefresh', () => { + it('triggers once, with the finger down, when the pull reaches the trigger distance', () => { + const {state, effects} = run([ + {type: 'pullStart'}, + {type: 'pullMove', overscroll: 40, trigger: 74}, + {type: 'pullMove', overscroll: 73.33, trigger: 74}, + {type: 'pullMove', overscroll: 74, trigger: 74}, + {type: 'pullMove', overscroll: 95, trigger: 74}, + ]); + expect(effects).toEqual([{type: 'trigger'}]); + expect(state).toEqual({ + isRefreshing: true, + isPulling: true, + hasTriggered: true, + }); + }); + + it('settles onto the inset when released while refreshing', () => { + const {state, effects} = run([ + {type: 'pullStart'}, + {type: 'pullMove', overscroll: 80, trigger: 74}, + {type: 'pullEnd'}, + ]); + expect(effects).toEqual([{type: 'trigger'}, {type: 'settle', to: 'inset'}]); + expect(state.isPulling).toBe(false); + expect(state.isRefreshing).toBe(true); + }); + + it('settles back to the top when released below the trigger', () => { + const {state, effects} = run([ + {type: 'pullStart'}, + {type: 'pullMove', overscroll: 50, trigger: 74}, + {type: 'pullEnd'}, + ]); + expect(effects).toEqual([{type: 'settle', to: 'top'}]); + expect(state.isRefreshing).toBe(false); + }); + + it('keeps refreshing when a pull that triggered is pushed back before the lift', () => { + const {state, effects} = run([ + {type: 'pullStart'}, + {type: 'pullMove', overscroll: 90, trigger: 74}, + {type: 'pullMove', overscroll: 10, trigger: 74}, + {type: 'pullEnd'}, + ]); + expect(effects).toEqual([{type: 'trigger'}, {type: 'settle', to: 'inset'}]); + expect(state.isRefreshing).toBe(true); + }); + + it('settles a cancelled pull like a release', () => { + expect( + run([ + {type: 'pullStart'}, + {type: 'pullMove', overscroll: 30, trigger: 74}, + {type: 'pullCancel'}, + ]).effects, + ).toEqual([{type: 'settle', to: 'top'}]); + expect( + run([ + {type: 'pullStart'}, + {type: 'pullMove', overscroll: 99, trigger: 74}, + {type: 'pullCancel'}, + ]).effects, + ).toEqual([{type: 'trigger'}, {type: 'settle', to: 'inset'}]); + }); + + it('never triggers from movement that no finger is pulling (a momentum overshoot)', () => { + expect( + run([{type: 'pullMove', overscroll: 120, trigger: 74}]).effects, + ).toEqual([]); + }); + + it('never triggers again on a pull while refreshing: one refresh runs at a time', () => { + const refreshing = run([ + {type: 'pullStart'}, + {type: 'pullMove', overscroll: 80, trigger: 74}, + {type: 'pullEnd'}, + ]).state; + // Far past the trigger, and past it beyond the inset too. + const far = run( + [ + {type: 'pullStart'}, + {type: 'pullMove', overscroll: 134, trigger: 74}, + {type: 'pullMove', overscroll: 200, trigger: 74}, + {type: 'pullEnd'}, + ], + refreshing, + ); + expect(far.effects).toEqual([{type: 'settle', to: 'inset'}]); + expect(far.state.isRefreshing).toBe(true); + }); + + it('begins programmatically, calling the handler only for the user’s request', () => { + expect(run([{type: 'begin', source: 'user'}]).effects).toEqual([ + {type: 'begin', callHandler: true}, + ]); + expect(run([{type: 'begin', source: 'program'}]).effects).toEqual([ + {type: 'begin', callHandler: false}, + ]); + // Already refreshing: nothing new starts. + expect( + run([ + {type: 'begin', source: 'program'}, + {type: 'begin', source: 'user'}, + ]).effects, + ).toEqual([{type: 'begin', callHandler: false}]); + }); + + it('ends a running refresh once, and ignores an end with nothing running', () => { + expect(run([{type: 'end'}]).effects).toEqual([]); + const {state, effects} = run([ + {type: 'begin', source: 'program'}, + {type: 'end'}, + {type: 'end'}, + ]); + expect(effects).toEqual([ + {type: 'begin', callHandler: false}, + {type: 'end'}, + ]); + expect(state.isRefreshing).toBe(false); + }); + + it('ends a refresh under the finger without settling; the lift then settles to the top', () => { + const {effects} = run([ + {type: 'pullStart'}, + {type: 'pullMove', overscroll: 80, trigger: 74}, + {type: 'end'}, + {type: 'pullEnd'}, + ]); + expect(effects).toEqual([ + {type: 'trigger'}, + {type: 'end'}, + {type: 'settle', to: 'top'}, + ]); + }); + + it('ignores a release with no pull in progress', () => { + expect(run([{type: 'pullEnd'}]).effects).toEqual([]); + }); +}); diff --git a/packages/lab/src/RefreshControl/refreshModel.ts b/packages/lab/src/RefreshControl/refreshModel.ts new file mode 100644 index 0000000000000..53aa74ac14bdd --- /dev/null +++ b/packages/lab/src/RefreshControl/refreshModel.ts @@ -0,0 +1,117 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file refreshModel.ts + * @input Pull events from the refresh pull recognizer, and programmatic begin + * and end requests + * @output Exports reduceRefresh (UIRefreshControl's state machine as a pure + * reducer that returns the effects to run), the initial state and types + * @position Pure logic for useRefreshControl; no DOM, no React + * + * SYNC: When modified, update: + * - /packages/lab/src/RefreshControl/refreshModel.test.ts + */ + +// The rules, as UIKit runs them: +// - A pull triggers once, with the finger down, when its overscroll reaches +// the trigger distance. Only overscroll that a finger drives triggers, never +// a momentum overshoot. +// - A release settles onto the refreshing inset while refreshing, and back to +// the top otherwise. A cancelled pull settles the same way. +// - A programmatic begin puts the control in the refreshing state. It calls +// the refresh handler only when it stands for the user's request, not when +// the app reports a refresh that it started. +// - Ending a refresh that is not running does nothing. +// +// One refresh runs at a time: a pull while refreshing only stretches. + +export interface RefreshState { + /** A refresh is in progress (`UIRefreshControl.isRefreshing`). */ + readonly isRefreshing: boolean; + /** A finger is pulling the content. */ + readonly isPulling: boolean; + /** The current pull has triggered (its mapping turns one to one). */ + readonly hasTriggered: boolean; +} + +export type RefreshEvent = + | {readonly type: 'pullStart'} + | { + readonly type: 'pullMove'; + readonly overscroll: number; + /** The trigger distance for this scroll owner. */ + readonly trigger: number; + } + | {readonly type: 'pullEnd'} + | {readonly type: 'pullCancel'} + | {readonly type: 'begin'; readonly source: 'user' | 'program'} + | {readonly type: 'end'}; + +export type RefreshEffect = + /** The pull reached the trigger: spin, announce, call the handler. */ + | {readonly type: 'trigger'} + /** A refresh started without a pull; `callHandler` for the user's request. */ + | {readonly type: 'begin'; readonly callHandler: boolean} + /** The finger let go: settle onto the inset or back to the top. */ + | {readonly type: 'settle'; readonly to: 'inset' | 'top'} + /** The refresh ended: remove the inset and hide the indicator. */ + | {readonly type: 'end'}; + +export const INITIAL_REFRESH_STATE: RefreshState = { + isRefreshing: false, + isPulling: false, + hasTriggered: false, +}; + +export function reduceRefresh( + state: RefreshState, + event: RefreshEvent, +): {state: RefreshState; effects: ReadonlyArray} { + switch (event.type) { + case 'pullStart': + return { + state: {...state, isPulling: true, hasTriggered: false}, + effects: [], + }; + case 'pullMove': { + // One refresh at a time: a pull while refreshing only stretches. + if ( + !state.isPulling || + state.hasTriggered || + state.isRefreshing || + event.overscroll < event.trigger + ) { + return {state, effects: []}; + } + return { + state: {...state, isRefreshing: true, hasTriggered: true}, + effects: [{type: 'trigger'}], + }; + } + case 'pullEnd': + case 'pullCancel': + if (!state.isPulling) { + return {state, effects: []}; + } + return { + state: {...state, isPulling: false}, + effects: [{type: 'settle', to: state.isRefreshing ? 'inset' : 'top'}], + }; + case 'begin': + if (state.isRefreshing) { + return {state, effects: []}; + } + return { + state: {...state, isRefreshing: true}, + effects: [{type: 'begin', callHandler: event.source === 'user'}], + }; + case 'end': + if (!state.isRefreshing) { + return {state, effects: []}; + } + return { + state: {...state, isRefreshing: false}, + effects: [{type: 'end'}], + }; + } +} diff --git a/packages/lab/src/RefreshControl/refreshPull.test.ts b/packages/lab/src/RefreshControl/refreshPull.test.ts new file mode 100644 index 0000000000000..d1a1d60b9a1c3 --- /dev/null +++ b/packages/lab/src/RefreshControl/refreshPull.test.ts @@ -0,0 +1,270 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file refreshPull.test.ts + * @input vitest, refreshPull + * @output Holds the pull mapping to UIKit's own frames, and the trigger + * distance to UIKit's on four view heights. Checks the inverse, the reveal, + * the release target, the end motion and the end's theme timing + * @position Testing; colocated with refreshPull.ts + */ + +import {describe, expect, it} from 'vitest'; +import { + endMotion, + endTiming, + modeAfterTrigger, + pullOverscroll, + pullSlope, + pullTravel, + REFRESH_HEIGHT, + releaseTarget, + revealFraction, + revealProgress, + triggerDistance, +} from './refreshPull'; + +/** + * UIKit lab capture: a UIRefreshControl on a 334 pt tall scroll view, iOS 26.2 + * simulator, HID drags at about 150 pt/s. Each row is [finger travel since + * touch-down, overscroll shown, whether the pull triggered], from the + * setContentOffset log. The pan's 10 pt hysteresis is part of the travel here. + */ +const UIKIT_PULLS: Record> = { + pull120: [ + [12.67, 2.67, 0], + [15, 5, 0], + [20, 10, 0], + [25, 15, 0], + [27.67, 17.67, 0], + [32.33, 22.33, 0], + [35, 25, 0], + [40, 30, 0], + [45, 35, 0], + [50, 40, 0], + [52.67, 42.67, 0], + [55, 45, 0], + [60, 50, 0], + [62.33, 52.33, 0], + [67.67, 57.67, 0], + [70, 60, 0], + [75, 62.67, 0], + [77.33, 64, 0], + [82.67, 66.67, 0], + [87.67, 69.33, 0], + [92.33, 72, 0], + [95, 73.33, 0], + [100, 75.67, 0], + [105, 95, 1], + [110, 100, 1], + [115, 105, 1], + [117.67, 107.67, 1], + [120, 110, 1], + ], + pull200: [ + [15, 5, 0], + [20, 10, 0], + [25, 15, 0], + [30, 20, 0], + [35, 25, 0], + [37.67, 27.67, 0], + [40, 30, 0], + [42.67, 32.67, 0], + [47.33, 37.33, 0], + [52.67, 42.67, 0], + [57.67, 47.67, 0], + [62.33, 52.33, 0], + [67.67, 57.67, 0], + [72.67, 61.33, 0], + [75, 62.67, 0], + [80, 65.33, 0], + [85, 68, 0], + [90, 70.67, 0], + [95, 73.33, 0], + [97.67, 74.67, 0], + [102.67, 92.67, 1], + [107.33, 97.33, 1], + [110, 100, 1], + [112.67, 102.67, 1], + [115, 105, 1], + [120, 110, 1], + [125, 115, 1], + [127.67, 117.67, 1], + ], +}; +const UIKIT_VIEW_HEIGHT = 334; +const HYSTERESIS = 10; + +describe('pullOverscroll', () => { + it('reproduces UIKit’s pull frame by frame, before and after the trigger', () => { + for (const [name, rows] of Object.entries(UIKIT_PULLS)) { + for (const [travel, shown, triggered] of rows) { + const model = pullOverscroll( + travel - HYSTERESIS, + UIKIT_VIEW_HEIGHT, + triggered === 1 ? modeAfterTrigger(travel - HYSTERESIS) : 'reveal', + ); + expect( + Math.abs(model - shown), + `${name} at ${travel} pt of travel: ${model} vs ${shown}`, + ).toBeLessThanOrEqual(triggered === 1 ? 0.01 : 0.2); + } + } + }); + + it('tracks the finger one to one up to the control’s height', () => { + expect(REFRESH_HEIGHT).toBe(60); + for (const travel of [0.5, 10, 30, 59.9, 60]) { + expect(pullOverscroll(travel, 800, 'reveal')).toBe(travel); + } + }); + + it('rubber-bands the excess past the height, never reaching the view’s height', () => { + const at = (travel: number) => pullOverscroll(travel, 800, 'reveal'); + expect(at(61)).toBeGreaterThan(60); + expect(at(61) - 60).toBeLessThan(1); + expect(at(2000)).toBeLessThan(60 + 800); + expect(at(200)).toBeGreaterThan(at(150)); + }); + + it('is one to one up to twice the height in the band', () => { + expect(pullOverscroll(95, 800, 'band')).toBe(95); + expect(pullOverscroll(120, 800, 'band')).toBe(120); + expect(pullOverscroll(121, 800, 'band')).toBeLessThan(121); + }); + + it('steps onto the finger only for a trigger within the band', () => { + expect(modeAfterTrigger(90)).toBe('band'); + expect(modeAfterTrigger(120)).toBe('band'); + // A tall view triggers past the band: the pull keeps its curve. + expect(modeAfterTrigger(296)).toBe('reveal'); + }); + + it('shows nothing for a pull that has not started or went the other way', () => { + expect(pullOverscroll(0, 800, 'reveal')).toBe(0); + expect(pullOverscroll(-25, 800, 'reveal')).toBe(0); + expect(pullOverscroll(Number.NaN, 800, 'reveal')).toBe(0); + }); +}); + +describe('pullTravel', () => { + it('inverts pullOverscroll in both modes', () => { + for (const mode of ['reveal', 'band'] as const) { + for (const travel of [0, 12, 60, 61, 90, 140, 400]) { + const shown = pullOverscroll(travel, 874, mode); + expect(pullTravel(shown, 874, mode)).toBeCloseTo(travel, 6); + } + } + }); +}); + +describe('trigger and reveal', () => { + it('triggers at UIKit’s distance for each view height', () => { + // Measured: 334 pt → 73.0–73.3; 400 → 79.0–79.3; 874 → 168.3–173.7; + // 1366 → about 271. + expect(triggerDistance(334)).toBeCloseTo(73, 0); + expect(triggerDistance(400)).toBeGreaterThanOrEqual(79); + expect(triggerDistance(400)).toBeLessThanOrEqual(79.3); + expect(triggerDistance(874)).toBeGreaterThanOrEqual(168.3); + expect(triggerDistance(874)).toBeLessThanOrEqual(173.7); + expect(Math.abs(triggerDistance(1366) - 271)).toBeLessThan(2); + // Never below the floor, even for a view with no height yet. + expect(triggerDistance(0)).toBe(73); + }); + + it('triggers on UIKit’s frames, at most one frame ahead of UIKit’s own report', () => { + // UIKit reports valueChanged on the frame after the crossing. + const trigger = triggerDistance(UIKIT_VIEW_HEIGHT); + for (const rows of Object.values(UIKIT_PULLS)) { + const reported = rows.findIndex(row => row[2] === 1); + const shown = (travel: number) => + pullOverscroll(travel - HYSTERESIS, UIKIT_VIEW_HEIGHT, 'reveal'); + expect(shown(rows[reported - 1][0])).toBeGreaterThanOrEqual(trigger); + expect(shown(rows[reported - 3][0])).toBeLessThan(trigger); + } + }); + + it('reveals in proportion to the pull, fully at the trigger', () => { + expect(revealFraction(0, 874)).toBe(0); + expect(revealFraction(triggerDistance(874) / 2, 874)).toBeCloseTo(0.5, 6); + expect(revealFraction(triggerDistance(874), 874)).toBe(1); + expect(revealFraction(500, 874)).toBe(1); + expect(revealFraction(-5, 874)).toBe(0); + }); + + it('eases the reveal on UIKit’s reveal curve (0.42, 0, 0.58, 1)', () => { + const trigger = triggerDistance(334); + expect(revealProgress(0, 334)).toBe(0); + expect(revealProgress(trigger, 334)).toBeCloseTo(1, 6); + // The ease-in-out curve is symmetric: halfway through is halfway. + expect(revealProgress(trigger / 2, 334)).toBeCloseTo(0.5, 3); + expect(revealProgress(trigger / 4, 334)).toBeLessThan(0.25); + }); +}); + +describe('release and end', () => { + it('releases onto the inset while refreshing and back to the top otherwise', () => { + expect(releaseTarget(true)).toBe(60); + expect(releaseTarget(false)).toBe(0); + }); + + it('slides the content up to close a visible gap, then drops inset and offset together', () => { + expect(endMotion(0)).toEqual({animateTo: 0, scrollBy: -0}); + expect(endMotion(25)).toEqual({animateTo: 25, scrollBy: -25}); + }); + + it('moves nothing when the control has scrolled out of view', () => { + expect(endMotion(60)).toEqual({animateTo: null, scrollBy: -60}); + expect(endMotion(500)).toEqual({animateTo: null, scrollBy: -60}); + }); +}); + +describe('the end’s timing from the theme’s tokens', () => { + it('plays the theme’s duration and move easing tokens as the element computes them (spec:AST-094 FR45)', () => { + const style = (values: Record) => ({ + getPropertyValue: (name: string) => values[name] ?? '', + }); + expect( + endTiming( + style({ + '--duration-medium': '300ms', + '--ease-move': 'cubic-bezier(0.24, 1, 0.4, 1)', + }), + ), + ).toEqual({ms: 300, points: [0.24, 1, 0.4, 1]}); + // A theme's tempo reaches the end through the token's value. + expect( + endTiming(style({'--duration-medium': '450ms', '--ease-move': 'ease'})) + ?.ms, + ).toBe(450); + // No tokens, or tokens in a form it cannot read: no slide. + expect( + endTiming( + style({'--duration-medium': 'calc(300ms * 1)', '--ease-move': 'ease'}), + ), + ).toBeNull(); + expect(endTiming(style({}))).toBeNull(); + }); +}); + +describe('pullSlope', () => { + it('is 1 where the pull tracks the finger, and the rubber band slope past it', () => { + expect(pullSlope(0, 334, 'reveal')).toBe(0); + expect(pullSlope(30, 334, 'reveal')).toBeCloseTo(1, 6); + const past = 100; + const slope = pullSlope(past, 334, 'reveal'); + expect(slope).toBeGreaterThan(0); + expect(slope).toBeLessThan(1); + // The slope of the mapping itself, and it falls as the band stretches. + const step = 0.5; + expect(slope).toBeCloseTo( + (pullOverscroll(past + step, 334, 'reveal') - + pullOverscroll(past - step, 334, 'reveal')) / + (2 * step), + 3, + ); + expect(pullSlope(past + 100, 334, 'reveal')).toBeLessThan(slope); + // The band after a trigger tracks one to one for twice as long. + expect(pullSlope(100, 334, 'band')).toBeCloseTo(1, 6); + }); +}); diff --git a/packages/lab/src/RefreshControl/refreshPull.ts b/packages/lab/src/RefreshControl/refreshPull.ts new file mode 100644 index 0000000000000..c8d935ffa640d --- /dev/null +++ b/packages/lab/src/RefreshControl/refreshPull.ts @@ -0,0 +1,186 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file refreshPull.ts + * @input The pull values (refreshValues.ts), and the rubber band, the cubic + * Bézier and the motion-role parsers (Core's internal touch entry) + * @output Exports the pull mapping (finger travel → overscroll), its slope + * and its inverse, and the trigger distance. It also exports the reveal, a + * refresh's release and end targets, and the end's timing from the theme's + * tokens. + * @position Pure math for useRefreshControl; no DOM, no React + * + * SYNC: When modified, update: + * - /packages/lab/src/RefreshControl/refreshPull.test.ts + */ + +// UIKit's refresh pull, as measured: the first `height` of overscroll tracks +// the finger one to one, after the pan's hysteresis. Past it, the scroll +// view's rubber band applies to the excess. The trigger distance grows with +// the scroll view's height. After a trigger within twice the height, the +// overscroll steps back onto the finger. It stays one to one up to twice the +// height, with resistance past that. + +import {cubicBezier} from '@astryxdesign/core/internal/touch'; +import { + rubberBand, + rubberBandInverse, + rubberBandSlope, +} from '@astryxdesign/core/internal/touch'; +import { + parseCssEasing, + parseMotionRoleValue, +} from '@astryxdesign/core/internal/touch'; +import {refreshControl} from './refreshValues'; + +/** The refreshing inset and one-to-one stretch, pt. */ +export const REFRESH_HEIGHT: number = refreshControl.height; + +/** + * Which mapping a pull follows. + * - `reveal`: before the trigger. One to one up to `height`, then the rubber + * band on the excess. + * - `band`: after a trigger within twice the height, and for a pull from the + * refreshing inset. One to one up to twice the height, then the rubber band. + */ +export type PullMode = 'reveal' | 'band'; + +function linearStretch(mode: PullMode): number { + return mode === 'band' + ? refreshControl.height * refreshControl.postTriggerLinearHeights + : refreshControl.height; +} + +/** + * Overscroll shown for `travel` px of pull (the pan's translation, which + * already leaves out its hysteresis). `dimension` is the scroll owner's + * height, the rubber band's dimension. + */ +export function pullOverscroll( + travel: number, + dimension: number, + mode: PullMode, +): number { + if (!(travel > 0)) { + return 0; + } + const linear = linearStretch(mode); + if (travel <= linear) { + return travel; + } + return linear + rubberBand(travel - linear, dimension); +} + +/** + * How fast the overscroll moves per px of finger travel at `travel`: 1 where + * it tracks the finger, the rubber band's slope past it. A release's speed + * times this slope is the content's speed, which its settle starts at. + */ +export function pullSlope( + travel: number, + dimension: number, + mode: PullMode, +): number { + if (!(travel > 0)) { + return 0; + } + const linear = linearStretch(mode); + return travel <= linear ? 1 : rubberBandSlope(travel - linear, dimension); +} + +/** + * The travel that shows `overscroll`: where a finger landing on content + * already pulled (a re-grab mid-settle) resumes without a jump. + */ +export function pullTravel( + overscroll: number, + dimension: number, + mode: PullMode, +): number { + if (!(overscroll > 0)) { + return 0; + } + const linear = linearStretch(mode); + if (overscroll <= linear) { + return overscroll; + } + return linear + rubberBandInverse(overscroll - linear, dimension); +} + +/** + * The mapping after a trigger at `travel`. It is the one-to-one band when the + * trigger falls within it, and the next frame steps onto the finger. Otherwise + * it is the reveal mapping, as when a tall scroll view triggers past the band. + */ +export function modeAfterTrigger(travel: number): PullMode { + return travel <= linearStretch('band') ? 'band' : 'reveal'; +} + +/** + * The overscroll at which a pull triggers, for a scroll owner `dimension` + * tall: a fraction of its height, never below the minimum. + */ +export function triggerDistance(dimension: number): number { + return Math.max( + refreshControl.triggerMinimum, + refreshControl.triggerHeightFraction * Math.max(0, dimension), + ); +} + +/** How much of the indicator a pull reveals, 0 to 1 (linear in the pull). */ +export function revealFraction(overscroll: number, dimension: number): number { + return Math.min(1, Math.max(0, overscroll / triggerDistance(dimension))); +} + +const revealEasing = cubicBezier(refreshControl.revealCurve); + +/** The reveal fraction on UIKit's reveal curve: the indicator's opacity. */ +export function revealProgress(overscroll: number, dimension: number): number { + return revealEasing(revealFraction(overscroll, dimension)); +} + +/** + * Where the content comes to rest when the finger lifts: on the refreshing + * inset while refreshing, back at the top otherwise. + */ +export function releaseTarget(isRefreshing: boolean): number { + return isRefreshing ? refreshControl.height : 0; +} + +/** + * How the end of a refresh moves the content. `scrolled` (≥ 0) is how far the + * scroll owner is scrolled with the inset still in place. While the gap + * shows, the content slides up until the gap closes: the inset animates from + * `height` to `scrolled`. Then the inset and the scroll offset drop together + * with no visible change. Scrolled past the gap, nothing moves, and the inset + * and the offset drop at once. + */ +export function endMotion(scrolled: number): { + animateTo: number | null; + scrollBy: number; +} { + const height = refreshControl.height; + const offset = Math.max(0, scrolled); + if (offset >= height) { + return {animateTo: null, scrollBy: -height}; + } + return {animateTo: offset, scrollBy: -offset}; +} + +/** + * The end's duration and curve: the theme tokens that `refreshControl` names, + * as the end's element computes them. Null when either token is missing or + * in a form it cannot read, such as `calc()`, `var()` or `steps()`. + */ +export function endTiming( + style: Pick, +): {ms: number; points: readonly [number, number, number, number]} | null { + const ms = parseMotionRoleValue( + 'duration', + style.getPropertyValue(refreshControl.endDurationToken), + ); + const points = parseCssEasing( + style.getPropertyValue(refreshControl.endEasingToken), + ); + return ms == null || points == null ? null : {ms, points}; +} diff --git a/packages/lab/src/RefreshControl/refreshTouchController.ts b/packages/lab/src/RefreshControl/refreshTouchController.ts new file mode 100644 index 0000000000000..9fd8d2cd703b1 --- /dev/null +++ b/packages/lab/src/RefreshControl/refreshTouchController.ts @@ -0,0 +1,838 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file refreshTouchController.ts + * @input The refresh's state and dispatch (refreshModel.ts), the pull's + * mapping (refreshPull.ts), and Core's internal touch entry + * @output useRefreshTouchController: the refresh's touch layer (the pull, the + * inset, the indicator's place and every motion) and its refs + * @position Internal to useRefreshControl; useRefreshControl.ts is its one + * import site, so a page loads this code only with the hook. + * + * SYNC: When modified, update: + * - /packages/lab/src/RefreshControl/useRefreshControl.ts + * - /packages/lab/src/RefreshControl/useRefreshControl.test.tsx + */ + +// A pull at the top translates the content by the overscroll that UIKit shows +// for that travel: one write per move, and no React render. The pull applies +// in the nearest element that scrolls and overflows, never on the page +// itself. While that element overflows, it gets `overscroll-behavior-y: none` +// near its top, so the browser draws no rubber band where the pull draws +// instead. A scroll container that fits passes scrolls on to its ancestors, +// so it gets nothing. Scrolling stays native. +// +// The pull triggers with the finger down, and the refresh starts. A release +// settles onto the refreshing inset, or back to the top, on the scroll view's +// bounce. The end slides the content up by the inset. When the content is out +// of view, the end drops the inset and the matching offset in one task. A +// programmatic begin adds the inset with no motion. +// +// The indicator is the app's. The touch layer pins it at the top of the +// scroll view and writes how much of it the pull reveals. It fades it as a +// settle takes the content back. +// +// The settle hands the table's spring to the animator. The end plays the +// theme's duration and move easing tokens, read at its start, so the theme's +// tempo scales it. Finger tracking runs on the main thread, because the +// browser has no refresh pull to ride. Every release, settle and end runs on +// the compositor. + +import { + useCallback, + useEffect, + useMemo, + useRef, + useState, + type RefCallback, +} from 'react'; +import type {PointerKind} from '@astryxdesign/core/internal/touch'; +import {useGestureRecognizer} from '@astryxdesign/core/internal/touch'; +import type {MotionCurve} from '@astryxdesign/core/internal/touch'; +import {cubicBezier} from '@astryxdesign/core/internal/touch'; +import {mapProgress} from '@astryxdesign/core/internal/touch'; +import {scroll} from '@astryxdesign/core/internal/touch'; +import {observeResize} from '@astryxdesign/core/utils'; +import {useMotionAnimator} from './useMotionAnimator'; +import { + RefreshPullRecognizer, + RefreshScrollPullRecognizer, +} from './RefreshPullRecognizer'; +import {REFRESH_REVEAL_VAR} from './refreshIndicator'; +import type {RefreshEvent, RefreshState} from './refreshModel'; +import { + endMotion, + endTiming, + modeAfterTrigger, + pullOverscroll, + pullSlope, + pullTravel, + REFRESH_HEIGHT, + releaseTarget, + revealProgress, + triggerDistance, + type PullMode, +} from './refreshPull'; + +export interface RefreshTouchControllerOptions { + /** Whether the pull applies. */ + readonly isPullEnabled: boolean; + /** The state machine's state, shared with the wiring. */ + readonly model: {readonly current: RefreshState}; + /** The wiring's dispatch: the pull's events go to the state machine. */ + readonly dispatchRef: {readonly current: (event: RefreshEvent) => void}; +} + +export interface RefreshTouchController { + readonly contentRef: RefCallback; + readonly indicatorRef: RefCallback; + /** A pull triggered: the indicator shows in full; the release settles onto the inset. */ + trigger(): void; + /** A refresh began without a pull: the inset arrives with no visible motion. */ + begin(): void; + /** The release settles onto the inset or back to the top. */ + settle(to: 'inset' | 'top'): void; + /** The refresh ended. */ + end(): void; +} + +/** The ancestors of `start` that scroll on y, nearest first, below the page. */ +function scrollContainersOf(start: HTMLElement): HTMLElement[] { + const doc = start.ownerDocument; + const containers: HTMLElement[] = []; + for ( + let node = start.parentElement; + node != null && node !== doc.body && node !== doc.documentElement; + node = node.parentElement + ) { + const overflowY = getComputedStyle(node).overflowY; + if ( + overflowY === 'auto' || + overflowY === 'scroll' || + overflowY === 'overlay' + ) { + containers.push(node); + } + } + return containers; +} + +function overflows(element: HTMLElement): boolean { + return element.scrollHeight > element.clientHeight; +} + +/** + * The element whose scroll moves the content: the nearest scroll container + * that overflows. A container that fits passes scrolls on to its ancestors, + * so it is not the owner. Null when none overflows: the page itself is never + * the pull's. + */ +function findScrollOwner(start: HTMLElement): HTMLElement | null { + return scrollContainersOf(start).find(overflows) ?? null; +} + +function scrollTopOf(owner: HTMLElement | null): number { + return owner?.scrollTop ?? 0; +} + +function heightOf(owner: HTMLElement): number { + return owner.clientHeight; +} + +function scrollOwnerBy(owner: HTMLElement | null, delta: number): void { + if (owner != null && delta !== 0) { + owner.scrollTop += delta; + } +} + +/** A curve from `from` to `to` over `ms` on a cubic bézier. */ +function bezierCurve( + from: number, + to: number, + ms: number, + points: readonly [number, number, number, number], +): MotionCurve { + const ease = cubicBezier(points); + const duration = ms / 1000; + const at = (t: number) => + from + (to - from) * ease(Math.min(1, Math.max(0, t / duration))); + return {duration, at, velocity: derivative(at, duration)}; +} + +function derivative( + at: (t: number) => number, + duration: number, +): (t: number) => number { + const step = 1 / 1000; + return t => { + const a = Math.max(0, t - step); + const b = Math.min(duration, t + step); + return b > a ? (at(b) - at(a)) / (b - a) : 0; + }; +} + +/** + * The refresh's touch layer. The wiring owns the state and the + * announcements; this owns everything a finger drives. + */ +export function useRefreshTouchController({ + isPullEnabled, + model, + dispatchRef, +}: RefreshTouchControllerOptions): RefreshTouchController { + const dispatch = useCallback( + (event: RefreshEvent) => dispatchRef.current(event), + [dispatchRef], + ); + const content = useMotionAnimator(); + const indicator = useMotionAnimator(); + const contentElement = useRef(null); + const indicatorElement = useRef(null); + // Whether the content holds the refreshing inset. + const hasInset = useRef(false); + // An end waiting for the frame after its render, and that frame. + const pendingEnd = useRef<(() => void) | null>(null); + const endFrame = useRef(null); + // Counts ends: each one renders, and the slide starts after that commit. + const [endTick, setEndTick] = useState(0); + const cancelPendingEnd = useCallback(() => { + pendingEnd.current = null; + if (endFrame.current != null) { + cancelAnimationFrame(endFrame.current); + endFrame.current = null; + } + }, []); + + const owner = useRef(null); + const pull = useRef<{ + travel0: number; + scrollTop0: number; + dimension: number; + floor: number; + trigger: number; + mode: PullMode; + }>({ + travel0: 0, + scrollTop0: 0, + dimension: 1, + floor: 0, + trigger: triggerDistance(1), + mode: 'reveal', + }); + // How fast the overscroll follows the finger at its last move. + const fingerSlope = useRef(0); + // The content's speed as the finger lifts, px/s, for the settle it starts. + const releaseVelocity = useRef(0); + + // -- Indicator ------------------------------------------------------------ + + const setReveal = useCallback((value: number) => { + indicatorElement.current?.style.setProperty( + REFRESH_REVEAL_VAR, + String(value), + ); + }, []); + + /** + * The pointer of the latest pull. Under Reduce Motion, a finger's release + * cross-fades, as the animator does for any release under a coarse primary + * pointer. A trackpad's release lands at once. + */ + const pullPointer = useRef('touch'); + + /** + * Places the content at `y` and pins the indicator at the top of the scroll + * view. The indicator rides on the content's edge, so it moves by the inset + * minus `y`. + */ + const place = useCallback( + (y: number) => { + content.animator.set({y}); + indicator.animator.set({y: REFRESH_HEIGHT - y}); + }, + [content.animator, indicator.animator], + ); + const stopPlacing = useCallback(() => { + content.animator.stop(['y']); + indicator.animator.stop(['y']); + }, [content.animator, indicator.animator]); + + /** + * Puts the indicator back to opaque, and writes only if it changed. Each + * animator write promotes its layer for a while. A release of that layer + * during a settle costs a layout and a paint. + */ + const restoreIndicator = useCallback(() => { + if (indicator.animator.get('opacity') !== 1) { + indicator.animator.set({opacity: 1}); + } + }, [indicator.animator]); + + const resetIndicator = useCallback(() => { + setReveal(0); + restoreIndicator(); + }, [restoreIndicator, setReveal]); + + /** + * Ends the indicator's fade and keeps what it shows. A finger that catches + * the settle back to the top pulls on, or resumes the settle, from the + * screen. + */ + const keepShownIndicator = useCallback(() => { + const opacity = indicator.animator.get('opacity'); + if (opacity === 1) { + return; + } + const shown = Number( + indicatorElement.current?.style.getPropertyValue(REFRESH_REVEAL_VAR) || 0, + ); + setReveal(shown * opacity); + restoreIndicator(); + }, [indicator.animator, restoreIndicator, setReveal]); + + /** The indicator in full: a trigger, or a refresh begun without a pull. */ + const showIndicator = useCallback(() => { + setReveal(1); + restoreIndicator(); + }, [restoreIndicator, setReveal]); + + // -- Scroll owner and its top-edge policy ---------------------------------- + + const edge = useRef<{element: HTMLElement | null; saved: string | null}>({ + element: null, + saved: null, + }); + + const releaseEdge = useCallback(() => { + const state = edge.current; + if (state.element != null && state.saved != null) { + state.element.style.overscrollBehaviorY = state.saved; + } + edge.current = {element: null, saved: null}; + }, []); + + const isPullEnabledRef = useRef(isPullEnabled); + isPullEnabledRef.current = isPullEnabled; + + /** + * Near the top, the browser draws no overscroll: the pull does. Only an + * element that scrolls and overflows: a container that fits, and the + * page's own top edge, stay the browser's. + */ + const applyEdge = useCallback(() => { + const current = owner.current; + const near = + isPullEnabledRef.current && + current != null && + overflows(current) && + scrollTopOf(current) < Math.max(heightOf(current), REFRESH_HEIGHT); + const state = edge.current; + if (!near || state.element !== current) { + releaseEdge(); + } + if (!near || current == null) { + return; + } + if (current.style.overscrollBehaviorY !== 'none') { + // First claim, or the owner's own render replaced the value. + edge.current = { + element: current, + saved: current.style.overscrollBehaviorY, + }; + current.style.overscrollBehaviorY = 'none'; + } + }, [releaseEdge]); + + // The owner's own scroll moves its top edge, so the pull listens there and + // nowhere else, and only while a finger can pull. The listener moves with + // the owner. + const ownerScroll = useRef<{ + isActive: boolean; + element: HTMLElement | null; + }>({isActive: false, element: null}); + const onOwnerScroll = useCallback(() => applyEdge(), [applyEdge]); + const listenToOwner = useCallback(() => { + const state = ownerScroll.current; + const next = state.isActive ? owner.current : null; + if (next !== state.element) { + state.element?.removeEventListener('scroll', onOwnerScroll); + next?.addEventListener('scroll', onOwnerScroll, {passive: true}); + state.element = next; + } + }, [onOwnerScroll]); + + const resolveOwner = useCallback((): HTMLElement | null => { + const element = contentElement.current; + if (element == null) { + return owner.current; + } + const next = findScrollOwner(element); + if (next !== owner.current) { + releaseEdge(); + owner.current = next; + listenToOwner(); + } + return next; + }, [listenToOwner, releaseEdge]); + + // Content that mounts after the hook has no owner, listener or resize + // observation yet, so attaching it runs the edge setup again. + const setUpEdge = useRef<(() => void) | null>(null); + + useEffect(() => { + // The pull watches the owner and its top edge only while a finger can + // pull. Otherwise it holds no listener, and a contact re-resolves the + // owner. The edge is claimed before a touch lands. The gesture host's + // listeners are passive, so a claim at touch-down can come after the + // browser's own overscroll starts. + if (!isPullEnabled) { + releaseEdge(); + return undefined; + } + ownerScroll.current.isActive = true; + const update = () => { + if (contentElement.current == null) { + // Detached content leaves no owner to claim or listen to. + releaseEdge(); + owner.current = null; + } else { + resolveOwner(); + applyEdge(); + } + listenToOwner(); + }; + // A container starts or stops overflowing as the content or the + // container resizes, with no scroll event. So the owner is read again on + // each resize of the content and of its scroll containers. + let unobserve: (() => void)[] = []; + const observe = () => { + for (const stop of unobserve) { + stop(); + } + const element = contentElement.current; + unobserve = + element == null + ? [] + : [element, ...scrollContainersOf(element)].map(node => + observeResize(node, update), + ); + }; + const setUp = () => { + update(); + observe(); + }; + setUpEdge.current = setUp; + setUp(); + // A scroll container can scroll only after its own effects run, which is + // after this effect. ScrollableArea clips its viewport until it measures + // it. So the owner is read again once those effects render. + let frame = requestAnimationFrame(() => { + frame = requestAnimationFrame(setUp); + }); + return () => { + setUpEdge.current = null; + cancelAnimationFrame(frame); + for (const stop of unobserve) { + stop(); + } + ownerScroll.current.isActive = false; + listenToOwner(); + releaseEdge(); + }; + }, [applyEdge, isPullEnabled, listenToOwner, releaseEdge, resolveOwner]); + + // -- Motion of the state machine's effects ---------------------------------- + + const startSettle = useCallback( + (to: 'inset' | 'top') => { + const target = releaseTarget(to === 'inset'); + const from = content.animator.get('y'); + // The settle starts at the content's speed as the finger lifts. A + // caught settle that resumes starts from rest. + const velocity = releaseVelocity.current; + releaseVelocity.current = 0; + // No start time: the animator starts the settle when the compositor + // does, so its first frame is the curve's start. A finger's release + // starts it as a touch release. So under Reduce Motion the animator + // cross-fades it instead of moving it, as it does for any release under + // a coarse primary pointer. A trackpad's release lands at once. + const touchRelease = pullPointer.current === 'touch'; + const contentSettle = content.animator.animate( + {y: target}, + {spring: scroll.bounce, velocity: {y: velocity}}, + {touchRelease}, + ); + indicator.animator.animate( + {y: REFRESH_HEIGHT - target}, + {spring: scroll.bounce, velocity: {y: -velocity}}, + {touchRelease}, + ); + if (to === 'top' && !model.current.isRefreshing && from > 0) { + // The indicator fades as the content covers it, along the content's + // own settle curve. Started in the same task, the two start on the + // same compositor frame. Under Reduce Motion the settle has no curve, + // and the indicator resets once the settle ends. + const curve = contentSettle.curve('y'); + const {dimension} = pull.current; + const start = revealProgress(from, dimension) || 1; + const finished = + curve == null + ? contentSettle.finished + : indicator.animator.play( + { + opacity: mapProgress( + curve, + y => revealProgress(y, dimension) / start, + ), + }, + {touchRelease}, + ).finished; + finished.then(done => { + if (done && !model.current.isRefreshing) { + resetIndicator(); + } + }); + } + }, + [content.animator, indicator.animator, resetIndicator], + ); + + const settle = useCallback( + (to: 'inset' | 'top') => { + if (to === 'inset') { + hasInset.current = true; + } + // Started in the lift's own task. The frame right after a long task + // carries the time it was due. An animation started there would begin + // in the past. + startSettle(to); + }, + [startSettle], + ); + + const end = useCallback(() => { + const hadInset = hasInset.current; + hasInset.current = false; + if (model.current.isPulling) { + // Under the finger: the release settles back to the top, and the + // indicator retracts with it. + pull.current.floor = 0; + return; + } + if (!hadInset) { + // A refresh that never showed (begun without a finger): nothing to move. + resetIndicator(); + return; + } + // From rest: a settle still easing onto the inset stops where it is + // shown. Ending over it would continue it with a fixed start time, which + // WebKit skips past when a block follows. + stopPlacing(); + const current = resolveOwner(); + const {animateTo, scrollBy} = endMotion(scrollTopOf(current)); + if (animateTo == null) { + place(0); + scrollOwnerBy(current, scrollBy); + resetIndicator(); + return; + } + // The slide starts two frames after the refresh's end renders, with the + // app's update and the busy state. WebKit starts an animation created just + // before a long task at the frame before that task. The first frame after + // a long task carries the time it was due. Either way, the start of the + // slide would never show. + pendingEnd.current = () => { + // The indicator stays opaque while the content slides up over its gap + // (UIKit holds it at opacity 1 for nearly the whole end). Under Reduce + // Motion, the animator cross-fades the slide. + const from = content.animator.get('y'); + const element = contentElement.current; + const finish = () => { + place(0); + scrollOwnerBy(current, scrollBy); + if (!model.current.isRefreshing) { + resetIndicator(); + } + }; + // The theme's tokens as they apply here, at the end's start. With no + // tokens, or tokens in a form it cannot read, the end has no slide. + const timing = + element == null ? null : endTiming(getComputedStyle(element)); + if (timing == null || timing.ms <= 0) { + finish(); + return; + } + const {ms, points} = timing; + indicator.animator.play({ + y: bezierCurve( + REFRESH_HEIGHT - from, + REFRESH_HEIGHT - animateTo, + ms, + points, + ), + }); + content.animator + .play({y: bezierCurve(from, animateTo, ms, points)}) + .finished.then(done => { + if (done) { + finish(); + } + }); + }; + setEndTick(tick => tick + 1); + }, [ + content.animator, + indicator.animator, + place, + resetIndicator, + resolveOwner, + stopPlacing, + ]); + + // Plays a pending end once the refresh's end renders. This effect runs + // after the commit that carries the end's tick, and the slide starts two + // frames later. A tick is used, not the rendered `isRefreshing`. A refresh + // that begins and ends before React renders never changes `isRefreshing`, + // for example a timer's `refresh()` whose `onRefresh` settles at once. + useEffect(() => { + if (pendingEnd.current == null) { + return; + } + endFrame.current = requestAnimationFrame(() => { + endFrame.current = requestAnimationFrame(() => { + endFrame.current = null; + const play = pendingEnd.current; + pendingEnd.current = null; + play?.(); + }); + }); + }, [endTick]); + useEffect( + () => () => { + if (endFrame.current != null) { + cancelAnimationFrame(endFrame.current); + } + }, + [], + ); + + // -- The pull ------------------------------------------------------------- + + // The pan's vertical translation where the pull starts: null until the + // content is at its top under a finger moving down. + const anchor = useRef(null); + const lastTranslation = useRef(0); + // A settle a finger caught (it stops where it is on touch-down) resumes + // when no pull follows. + const resumeSettle = useCallback(() => { + if (model.current.isPulling) { + return; + } + const target = releaseTarget(model.current.isRefreshing); + if (Math.abs(content.animator.get('y') - target) > 0.05) { + settle(model.current.isRefreshing ? 'inset' : 'top'); + } + }, [content.animator, model, settle]); + + const onPull = (pan: RefreshPullRecognizer) => { + const state = model.current; + if (pan.state === 'began' || pan.state === 'changed') { + const translation = pan.translation().y; + if (anchor.current == null) { + // Not pulling yet: the browser can be scrolling the content, in a drag + // that began as a scroll. The pull starts in the same touch once the + // content is at its top and the finger moves down. The browser keeps + // the finger all along, and the pan only watches, so nothing changes + // hands. + const current = pan.state === 'began' ? resolveOwner() : owner.current; + // At `began` the finger's whole move counts, the threshold's + // included (a slow drag begins at a translation of zero). + const isMovingDown = + pan.state === 'began' + ? translation + pan.travelAtBegan.y > 0 + : translation > lastTranslation.current; + lastTranslation.current = translation; + if (!isMovingDown || current == null || scrollTopOf(current) > 0) { + return; + } + // From rest the travel is the pan's (which leaves out its + // hysteresis, as UIKit's does); past a scroll it starts where the + // content ran out. + anchor.current = pan.state === 'began' ? 0 : translation; + pullPointer.current = pan.pointerType; + const shown = content.animator.get('y'); + stopPlacing(); + const dimension = heightOf(current); + const mode: PullMode = state.isRefreshing ? 'band' : 'reveal'; + pull.current = { + dimension, + mode, + trigger: triggerDistance(dimension), + floor: state.isRefreshing ? REFRESH_HEIGHT : 0, + travel0: pullTravel(shown, dimension, mode), + scrollTop0: scrollTopOf(current), + }; + dispatch({type: 'pullStart'}); + } + lastTranslation.current = translation; + const geometry = pull.current; + // A browser that scrolls the content back as the finger returns + // (Chromium) takes over from the pull. + const scrolledBack = + scrollTopOf(owner.current) - geometry.scrollTop0 > 0.5; + const travel = scrolledBack + ? 0 + : geometry.travel0 + (translation - anchor.current); + const pulled = pullOverscroll(travel, geometry.dimension, geometry.mode); + const overscroll = Math.max(geometry.floor, pulled); + // The content follows the finger by the pull's slope, unless the + // refreshing inset holds it. + fingerSlope.current = + pulled > geometry.floor + ? pullSlope(travel, geometry.dimension, geometry.mode) + : 0; + const hadTriggered = model.current.hasTriggered; + dispatch({type: 'pullMove', overscroll, trigger: geometry.trigger}); + if (!hadTriggered && model.current.hasTriggered) { + // The frame after the trigger steps onto the finger (within the + // one-to-one band). + geometry.mode = + geometry.mode === 'band' ? 'band' : modeAfterTrigger(travel); + } + place(overscroll); + if (!model.current.isRefreshing) { + setReveal(revealProgress(overscroll, geometry.dimension)); + } + return; + } + if (pan.state !== 'ended' && pan.state !== 'cancelled') { + return; + } + const wasPulling = anchor.current != null; + anchor.current = null; + if (!wasPulling) { + // A scroll that never reached the top: a settle the finger caught + // resumes. + resumeSettle(); + return; + } + // A lift hands the content's speed to the settle: the scroll view's + // release velocity times the pull's slope. A cancelled pull's finger never + // lifted, so its settle starts from rest. + releaseVelocity.current = + pan.state === 'ended' ? pan.scrollVelocity().y * fingerSlope.current : 0; + dispatch({type: pan.state === 'ended' ? 'pullEnd' : 'pullCancel'}); + releaseVelocity.current = 0; + }; + // The touch pull takes no scroll. It watches a contact from the start of a + // drag, so it would take a scroll in the middle of the page. + const recognizer = useGestureRecognizer( + contentElement, + () => new RefreshPullRecognizer(), + onPull, + ); + // A trackpad's two-finger scroll pulls through a second pan, which takes + // only that scroll and never a mouse wheel's notches. It begins only where + // nothing under the pointer could scroll: the owner at its top and the + // content moving down. It claims what it takes, so its blocking `wheel` + // listener is a claimer's. + const scrollRecognizer = useGestureRecognizer( + contentElement, + () => new RefreshScrollPullRecognizer(), + onPull, + ); + // Syncs whether the pull applies with the recognizer, an object outside + // React. Turned off mid-pull, the recognizer reports `cancelled` to the + // listener above. The listener settles the content back and ends the pull, + // where the hook's own `isEnabled` would end it silently. + useEffect(() => { + recognizer.setEnabled(isPullEnabled); + scrollRecognizer.setEnabled(isPullEnabled); + }, [isPullEnabled, recognizer, scrollRecognizer]); + + useEffect(() => { + // A finger landing on a settle in flight stops it (UIScrollView brakes), + // as a trackpad's scroll starting does; if no pull follows, the settle + // resumes. + const pans = [recognizer, scrollRecognizer]; + const stops = pans.map(pan => { + pan.onTouchDown = () => { + resolveOwner(); + applyEdge(); + cancelPendingEnd(); + stopPlacing(); + keepShownIndicator(); + }; + return pan.addTransitionListener(current => { + if (current.state === 'failed') { + resumeSettle(); + } + }); + }); + return () => { + for (const pan of pans) { + pan.onTouchDown = null; + } + for (const stop of stops) { + stop(); + } + }; + }, [ + applyEdge, + cancelPendingEnd, + keepShownIndicator, + recognizer, + resolveOwner, + resumeSettle, + scrollRecognizer, + stopPlacing, + ]); + + const contentRef = useCallback( + (element: HTMLElement | null) => { + contentElement.current = element; + content.ref(element); + setUpEdge.current?.(); + }, + [content], + ); + const indicatorRef = useCallback( + (element: HTMLElement | null) => { + indicatorElement.current = element; + indicator.ref(element); + }, + [indicator], + ); + + const trigger = useCallback(() => { + // Only a pull triggers: it settles onto the inset. + hasInset.current = true; + showIndicator(); + }, [showIndicator]); + + const begin = useCallback(() => { + showIndicator(); + if (!model.current.isPulling) { + // The inset arrives with no visible motion, as beginRefreshing(). + cancelPendingEnd(); + const current = resolveOwner(); + place(REFRESH_HEIGHT); + scrollOwnerBy(current, REFRESH_HEIGHT); + hasInset.current = true; + } + }, [cancelPendingEnd, model, place, resolveOwner, showIndicator]); + + return useMemo( + () => ({ + contentRef, + indicatorRef, + trigger, + begin, + settle, + end, + }), + [begin, contentRef, end, indicatorRef, settle, trigger], + ); +} diff --git a/packages/lab/src/RefreshControl/refreshValues.ts b/packages/lab/src/RefreshControl/refreshValues.ts new file mode 100644 index 0000000000000..e431e6361241e --- /dev/null +++ b/packages/lab/src/RefreshControl/refreshValues.ts @@ -0,0 +1,80 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file refreshValues.ts + * @input Nothing; data only + * @output Exports `refreshControl`, UIRefreshControl's pull values: the + * refreshing inset, the trigger, the pull after it, the reveal, the end, and + * the theme tokens the end plays + * @position Internal to the refresh pull. A release onto the inset uses Core's + * `scroll.bounce`, and a pull past `height` uses Core's rubber band. + */ + +// Lengths are in pt (CSS px), durations in ms, and curves are cubic-bézier +// control points. +export const refreshControl = { + /** + * The refreshing inset: while refreshing, the content rests this far below + * the top of the scroll view, with the indicator in the gap. Also the + * stretch of a pull that tracks the finger one to one before the rubber + * band starts. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIRefreshControl on a 334 pt scroll view: content held + * at −60.33 while refreshing (inset top 60), offset equal to finger + * travel − 10 pt up to 60, Oct 23 2026 + */ + height: 60, + /** + * The trigger distance as a fraction of the scroll view's height. A pull + * triggers when its overscroll reaches this × the height, or + * `triggerMinimum` if that is larger. The indicator is then fully revealed. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIRefreshControl on scroll views 400 pt (trigger at + * 79.0–79.3), 874 pt (168.3–173.7) and 1366 pt (about 271, from the + * reveal's slope) tall, Oct 23 2026 + */ + triggerHeightFraction: 0.198, + /** + * The shortest trigger distance, pt of overscroll: short scroll views + * trigger here. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIRefreshControl on a 334 pt scroll view: trigger at + * 73.0–73.3 at the top of the screen and 540 pt down, Oct 23 2026 + */ + triggerMinimum: 73, + /** + * After the trigger, the offset follows the finger one to one again, up to + * this many `height`s of overscroll. Past it, the pull resists again. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIRefreshControl on a 334 pt scroll view, setContentOffset + * log: one to one from the frame after the trigger to −117.67, Oct 23 2026 + */ + postTriggerLinearHeights: 2, + /** + * The indicator's reveal curve: the reveal goes from 0 to 1 on it as the + * overscroll goes from 0 to the trigger distance. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, CAAnimation dump (CABasicAnimation on the indicator's + * opacity, 1 s, timing function (0.42, 0, 0.58, 1)) and per-frame reads + * of its speed, timeOffset and opacity, Oct 23 2026 + */ + revealCurve: [0.42, 0, 0.58, 1], + /** + * `endRefreshing()` while the control is visible: the inset leaves (the + * content moves up by `height`) over this long. The end plays the theme + * duration token nearest it (`endDurationToken`). This value stays as the + * reference for that choice. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, setContentOffset per frame over 0.3 s inside + * UIView.animate(withDuration: 0.3), three runs at rest identical to the + * frame, Oct 23 2026 + */ + endMs: 300, + /** + * The theme duration token that the end plays. In the neutral theme its + * value is the one nearest `endMs`: 300 ms. The theme's tempo scales it. + */ + endDurationToken: '--duration-medium', + /** The easing token that the end plays: the content moves. */ + endEasingToken: '--ease-move', +} as const; diff --git a/packages/lab/src/RefreshControl/useMotionAnimator.ts b/packages/lab/src/RefreshControl/useMotionAnimator.ts new file mode 100644 index 0000000000000..697641a6e32fc --- /dev/null +++ b/packages/lab/src/RefreshControl/useMotionAnimator.ts @@ -0,0 +1,35 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useMotionAnimator.ts + * @input Core's internal motion animator (internal/touch) + * @output useMotionAnimator: one motion animator for a component's lifetime, + * and the ref that attaches it to an element + * @position Internal to useRefreshControl; refreshTouchController calls it. + * Core's public `useAnimator` plays only the theme's state-change motion. + */ + +import {useState} from 'react'; +import { + createMotionAnimator, + type MotionAnimator, + type MotionAnimatorOptions, +} from '@astryxdesign/core/internal/touch'; + +export interface UseMotionAnimatorResult { + readonly ref: (element: HTMLElement | null) => void; + readonly animator: MotionAnimator; +} + +/** One motion animator for the component's lifetime, attached through `ref`. */ +export function useMotionAnimator( + options?: MotionAnimatorOptions, +): UseMotionAnimatorResult { + const [result] = useState(() => { + const animator = createMotionAnimator(null, options); + return {animator, ref: element => animator.attach(element)}; + }); + return result; +} diff --git a/packages/lab/src/RefreshControl/useRefreshControl.test.tsx b/packages/lab/src/RefreshControl/useRefreshControl.test.tsx new file mode 100644 index 0000000000000..062d8d7f25a7a --- /dev/null +++ b/packages/lab/src/RefreshControl/useRefreshControl.test.tsx @@ -0,0 +1,1315 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file useRefreshControl.test.tsx + * @input vitest (jsdom), useRefreshControl in a minimal app scroll + * container, input events on its content, and stand-ins for a touch screen + * and a non-iOS WebKit + * @output Covers the pull, the end, controlled and programmatic refreshes, and + * the announcement. Also covers the inputs that pull and those that do not, + * the disabled state and the scroll container's top-edge overscroll policy + * @position Testing; colocated with useRefreshControl.ts. A real browser + * checks the motion itself (the interaction spec and its storyboards) + */ + +import {useState, type ReactNode} from 'react'; +import {act, render, screen, waitFor} from '@testing-library/react'; +import { + GestureRecognizer, + PanGestureRecognizer, + type MotionAnimator, + type MotionCurve, +} from '@astryxdesign/core/internal/touch'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {revealProgress} from './refreshPull'; +import { + useRefreshControl, + type UseRefreshControlOptions, +} from './useRefreshControl'; + +// Records the animators that the touch layer creates, the content's first, +// so a test can watch the settle and the indicator's fade. +const animators = vi.hoisted(() => ({list: [] as unknown[]})); +vi.mock('./useMotionAnimator', async importOriginal => { + const real = await importOriginal(); + return { + ...real, + useMotionAnimator: ( + ...args: Parameters + ): ReturnType => { + const result = real.useMotionAnimator(...args); + if (!animators.list.includes(result.animator)) { + animators.list.push(result.animator); + } + return result; + }, + }; +}); + +/** + * Gives the content's settle back to the top the curve from `settleCurve` + * and an end that the test controls. Records the curves that the indicator + * plays on its opacity. + */ +function watchFade(settleCurve: () => MotionCurve | null) { + const [contentAnimator, indicatorAnimator] = animators.list.slice( + -2, + ) as MotionAnimator[]; + let finishSettle: (done: boolean) => void = () => {}; + const animate = contentAnimator.animate.bind(contentAnimator); + vi.spyOn(contentAnimator, 'animate').mockImplementation( + (to, transition, options) => { + const handle = animate(to, transition, options); + if (to.y !== 0) { + return handle; + } + const curve = settleCurve(); + const finished = new Promise(resolve => { + finishSettle = resolve; + }); + return {...handle, finished, curve: () => curve}; + }, + ); + const play = vi.spyOn(indicatorAnimator, 'play'); + return { + fades: () => + play.mock.calls + .map(([curves]) => curves.opacity) + .filter((curve): curve is MotionCurve => curve != null), + finishSettle: (done: boolean) => finishSettle(done), + }; +} + +/** + * Gives a scroll container the height of the scroll view that UIKit's frames + * were measured on, and content that overflows it. The trigger distance is + * then UIKit's floor, 73 px of overscroll. jsdom lays nothing out. + */ +function measured(element: HTMLElement | null): void { + if (element != null) { + sized(element, {client: 334, scroll: 1000}); + } +} + +/** Gives an element a height and a content height. */ +function sized( + element: HTMLElement, + {client, scroll}: {client: number; scroll: number}, +): void { + Object.defineProperty(element, 'clientHeight', { + value: client, + configurable: true, + }); + Object.defineProperty(element, 'scrollHeight', { + value: scroll, + configurable: true, + }); +} + +/** + * The structure the hook drives: the app's scroll container, the pulled + * content and an indicator. With `isBare`, the test supplies the container. + */ +function Refreshable({ + children, + 'data-testid': testId, + isBare = false, + announce = 'Refreshing', + ...options +}: UseRefreshControlOptions & { + children: ReactNode; + 'data-testid'?: string; + isBare?: boolean; +}) { + const control = useRefreshControl({announce, ...options}); + const pulled = ( +
+
+ {children} +
+ ); + return isBare ? ( + pulled + ) : ( +
+ {pulled} +
+ ); +} + +const COARSE = /\(\s*pointer\s*:\s*coarse\s*\)/; +let originalMatchMedia: typeof window.matchMedia; +let originalInnerHeight: number; +const originalCss = Object.getOwnPropertyDescriptor(window, 'CSS'); + +/** Whether the engine answers iOS WebKit's `CSS.supports` query. */ +function useIos(isIos: boolean): void { + Object.defineProperty(window, 'CSS', { + configurable: true, + writable: true, + value: { + escape: (value: string) => value, + supports: (query: string) => + isIos && query === '(-webkit-touch-callout: none)', + }, + }); +} + +function useTouchScreen(isTouch: boolean): void { + window.matchMedia = (query: string) => + ({ + matches: isTouch && COARSE.test(query), + media: query, + onchange: null, + addListener: () => {}, + removeListener: () => {}, + addEventListener: () => {}, + removeEventListener: () => {}, + dispatchEvent: () => false, + }) as MediaQueryList; +} + +let clock = 0; +function touch( + type: string, + target: EventTarget, + y: number, + isLift = false, +): void { + clock += 16; + const event = new Event(type, {bubbles: true, cancelable: true}); + const entry = {identifier: 1, clientX: 100, clientY: y, target}; + Object.defineProperty(event, 'changedTouches', {value: [entry]}); + Object.defineProperty(event, 'touches', {value: isLift ? [] : [entry]}); + Object.defineProperty(event, 'timeStamp', {value: clock}); + act(() => { + target.dispatchEvent(event); + }); +} + +/** A one-finger drag from y 100 down by each step in turn. */ +function pull(target: EventTarget, steps: number[], lift = true): void { + let y = 100; + touch('touchstart', target, y); + for (const step of steps) { + y += step; + touch('touchmove', target, y); + } + if (lift) { + touch('touchend', target, y, true); + } +} + +/** + * A drag with a mouse or a pen from y 100. `move` goes down by a step with the + * button held, and `lift` releases the button. + */ +function pointerDrag(target: EventTarget, pointerType: 'mouse' | 'pen') { + let y = 100; + const send = (type: string, buttons: number) => { + clock += 16; + const event = new PointerEvent(type, { + bubbles: true, + cancelable: true, + composed: true, + pointerId: 7, + pointerType, + isPrimary: true, + clientX: 100, + clientY: y, + button: 0, + buttons, + }); + Object.defineProperty(event, 'timeStamp', {value: clock}); + act(() => { + target.dispatchEvent(event); + }); + }; + send('pointerdown', 1); + return { + move(step: number) { + y += step; + send('pointermove', 1); + }, + lift() { + send('pointerup', 0); + }, + }; +} + +/** + * Wheel steps of `dy` px each. `trackpad` adds the legacy `wheelDeltaY` that + * Chromium and WebKit report for a trackpad, three times each delta against + * the content. Without it, the gesture host reads a mouse wheel. + */ +function wheel( + target: EventTarget, + steps: number[], + {trackpad}: {trackpad: boolean}, +): void { + for (const dy of steps) { + clock += 16; + const event = new WheelEvent('wheel', { + bubbles: true, + cancelable: true, + composed: true, + clientX: 100, + clientY: 100, + deltaY: dy, + deltaMode: 0, + }); + Object.defineProperty(event, 'timeStamp', {value: clock}); + if (trackpad) { + Object.defineProperty(event, 'wheelDeltaX', {value: 0}); + Object.defineProperty(event, 'wheelDeltaY', {value: -3 * dy}); + } + act(() => { + target.dispatchEvent(event); + }); + } +} + +function translateY(element: HTMLElement): number { + const value = element.style.getPropertyValue('translate'); + if (value === '' || value === 'none') { + return 0; + } + const parts = value.trim().split(/\s+/); + return parseFloat(parts[1] ?? '0'); +} + +/** The app's indicator. */ +function indicator(): HTMLElement { + return content().firstElementChild as HTMLElement; +} + +/** How much of the indicator the touch layer reveals, 0 to 1. */ +function reveal(): string { + return indicator().style.getPropertyValue('--astryx-refresh-reveal'); +} + +function content(): HTMLElement { + return screen.getByTestId('refresh'); +} + +describe('useRefreshControl', () => { + beforeEach(() => { + originalMatchMedia = window.matchMedia; + originalInnerHeight = window.innerHeight; + useTouchScreen(true); + // The page as tall as the scroll container, for anything that reads it. + Object.defineProperty(window, 'innerHeight', { + value: 334, + configurable: true, + }); + clock = 0; + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.useRealTimers(); + Reflect.deleteProperty(HTMLElement.prototype, 'animate'); + window.matchMedia = originalMatchMedia; + if (originalCss) { + Object.defineProperty(window, 'CSS', originalCss); + } else { + Reflect.deleteProperty(window, 'CSS'); + } + Object.defineProperty(window, 'innerHeight', { + value: originalInnerHeight, + configurable: true, + }); + document.documentElement.style.overscrollBehaviorY = ''; + }); + + it('pulls the content as UIKit does: one to one past the hysteresis, up to the height', () => { + render( + {}}> +

Inbox

+
, + ); + pull(content(), [12, 8, 20], false); + // 40 px of finger travel, 10 of them the pan's hysteresis. + expect(translateY(content())).toBeCloseTo(30, 5); + touch('touchmove', content(), 170); + expect(translateY(content())).toBeCloseTo(60, 5); + touch('touchend', content(), 170, true); + }); + + it('triggers with the finger still down, then settles onto the refreshing inset', async () => { + const onRefresh = vi.fn(() => new Promise(() => {})); + render( + +

Inbox

+
, + ); + pull(content(), [20, 20, 20, 20], false); + expect(onRefresh).not.toHaveBeenCalled(); + // 105 px of travel: past the trigger (73 px of overscroll). + touch('touchmove', content(), 205); + expect(onRefresh).toHaveBeenCalledTimes(1); + expect(content()).toHaveAttribute('aria-busy', 'true'); + expect(translateY(content())).toBeGreaterThan(74); + expect(translateY(content())).toBeLessThan(95); + // The next frame snaps to one to one with the finger, as UIKit does. + touch('touchmove', content(), 210); + expect(translateY(content())).toBeCloseTo(100, 5); + touch('touchend', content(), 210, true); + // The settle starts in the next frame; jsdom has no compositor, so it + // lands on its target at once. + await waitFor(() => expect(translateY(content())).toBeCloseTo(60, 5)); + await waitFor(() => expect(document.body).toHaveTextContent('Refreshing')); + }); + + it('pulls from the move that crosses the hysteresis, even one that lands on it exactly', () => { + render( + {}}> +

Inbox

+
, + ); + // 5 px steps: the second lands on the 10 px hysteresis, where the pan + // begins at a translation of zero. The two after it pull 10 px. + pull(content(), [5, 5, 5, 5], false); + expect(translateY(content())).toBe(10); + }); + + it('keeps the indicator at the top of the scroll view while the content is pulled, settles and ends', async () => { + let resolve: () => void = () => {}; + render( + + new Promise(done => { + resolve = done; + }) + }> +

Inbox

+
, + ); + const indicator = content().firstElementChild as HTMLElement; + pull(content(), [30, 30, 30, 30], false); + // UIRefreshControl stays where it is while the content moves away from it. + // The indicator rides on the content's edge, so it moves back by what the + // content moved past the inset. + const pulled = translateY(content()); + expect(pulled).toBeGreaterThan(60); + expect(translateY(indicator)).toBeCloseTo(60 - pulled, 5); + touch('touchend', content(), 220, true); + await waitFor(() => expect(translateY(content())).toBeCloseTo(60, 5)); + expect(translateY(indicator)).toBeCloseTo(0, 5); + await act(async () => { + resolve(); + }); + await waitFor(() => expect(translateY(content())).toBe(0)); + // Back at the top, the content's edge covers it. + expect(translateY(indicator)).toBeCloseTo(60, 5); + }); + + it('leaves the content’s compositor layer to the animator: promoted once while it moves, given back at rest', async () => { + let resolve: () => void = () => {}; + render( + + new Promise(done => { + resolve = done; + }) + }> +

Inbox

+
, + ); + const willChange = () => content().style.willChange; + // A tap at the top moves nothing, so nothing is promoted. + touch('touchstart', content(), 100); + touch('touchend', content(), 100, true); + expect(willChange()).toBe(''); + // A pull is promoted from its first move, once, and keeps the layer + // through the refresh until the end has run. + pull(content(), [30, 30, 30, 30]); + expect(willChange()).toBe('translate'); + await act(async () => { + resolve(); + }); + await waitFor(() => expect(willChange()).toBe(''), {timeout: 3000}); + }); + + it('settles back to the top without refreshing below the trigger', async () => { + const onRefresh = vi.fn(); + render( + +

Inbox

+
, + ); + pull(content(), [20, 20, 20, 10]); + expect(onRefresh).not.toHaveBeenCalled(); + await waitFor(() => expect(translateY(content())).toBe(0)); + expect(content()).not.toHaveAttribute('aria-busy'); + }); + + it('fades the indicator along the content settle curve when a pull ends below the trigger', () => { + animators.list.length = 0; + render( + {}}> +

Inbox

+
, + ); + // A curve that no spring makes: the fade follows the settle's own curve. + let from = 0; + const settle: MotionCurve = { + duration: 0.8, + at: t => from * Math.max(0, 1 - t / 0.8), + velocity: t => (t < 0.8 ? -from / 0.8 : 0), + }; + const fade = watchFade(() => settle); + pull(content(), [20, 20, 20, 10], false); + from = translateY(content()); + expect(from).toBeGreaterThan(0); + touch('touchend', content(), 170, true); + const fades = fade.fades(); + expect(fades).toHaveLength(1); + expect(fades[0].duration).toBe(0.8); + const start = revealProgress(from, 334); + for (const time of [0, 0.2, 0.4, 0.6, 0.8]) { + expect(fades[0].at(time)).toBeCloseTo( + revealProgress(settle.at(time), 334) / start, + 6, + ); + } + }); + + it('holds the indicator under Reduce Motion, where the settle has no curve, and resets it once the content settles', async () => { + animators.list.length = 0; + render( + {}}> +

Inbox

+
, + ); + const fade = watchFade(() => null); + pull(content(), [20, 20, 20, 10]); + expect(Number(reveal())).toBeGreaterThan(0); + expect(fade.fades()).toEqual([]); + await act(async () => { + fade.finishSettle(true); + }); + await waitFor(() => expect(reveal()).toBe('0')); + }); + + it('keeps what the indicator shows when a finger catches its fade, and the fade no longer resets it under the finger', async () => { + animators.list.length = 0; + render( + {}}> +

Inbox

+
, + ); + const [, indicatorAnimator] = animators.list.slice(-2) as MotionAnimator[]; + const play = vi.spyOn(indicatorAnimator, 'play'); + // Released below the trigger: the settle back and the fade start. + pull(content(), [20, 20, 20, 10]); + const fadeAt = play.mock.calls.findIndex(([curves]) => 'opacity' in curves); + expect(fadeAt).toBeGreaterThanOrEqual(0); + const fade = play.mock.results[fadeAt].value as ReturnType< + MotionAnimator['play'] + >; + const shown = Number(reveal()); + expect(shown).toBeGreaterThan(0); + // A finger catches the settle halfway through the fade. + const presentedGet = indicatorAnimator.get.bind(indicatorAnimator); + const presented = vi + .spyOn(indicatorAnimator, 'get') + .mockImplementation(property => + property === 'opacity' ? 0.5 : presentedGet(property), + ); + const set = vi.spyOn(indicatorAnimator, 'set'); + touch('touchstart', content(), 100); + presented.mockRestore(); + expect(Number(reveal())).toBeCloseTo(shown * 0.5, 6); + expect(set).toHaveBeenCalledWith({opacity: 1}); + // The finger pulls on. The fade ends stopped, so it never resets the + // indicator under the finger. + touch('touchmove', content(), 110); + touch('touchmove', content(), 120); + let isFadeDone: boolean | undefined; + await act(async () => { + isFadeDone = await fade.finished; + }); + expect(isFadeDone).toBe(false); + expect(Number(reveal())).toBeGreaterThan(0); + }); + + it('ends when the promise from onRefresh settles, and removes the inset', async () => { + let resolve: () => void = () => {}; + const onRefresh = vi.fn( + () => + new Promise(done => { + resolve = done; + }), + ); + render( + +

Inbox

+
, + ); + pull(content(), [30, 30, 30, 30]); + expect(content()).toHaveAttribute('aria-busy', 'true'); + await act(async () => { + resolve(); + }); + expect(content()).not.toHaveAttribute('aria-busy'); + // The slide starts in the frame after the end has rendered. + await waitFor(() => expect(translateY(content())).toBe(0)); + }); + + it('ends after a rejected refresh as well', async () => { + let reject: () => void = () => {}; + render( + + new Promise((_, fail) => { + reject = () => fail(new Error('offline')); + }) + }> +

Inbox

+
, + ); + pull(content(), [30, 30, 30, 30]); + await act(async () => { + reject(); + }); + expect(content()).not.toHaveAttribute('aria-busy'); + }); + + it('follows a controlled isRefreshing without calling onRefresh for it', () => { + const onRefresh = vi.fn(); + const {rerender} = render( + +

Inbox

+
, + ); + rerender( + +

Inbox

+
, + ); + expect(content()).toHaveAttribute('aria-busy', 'true'); + expect(onRefresh).not.toHaveBeenCalled(); + rerender( + +

Inbox

+
, + ); + expect(content()).not.toHaveAttribute('aria-busy'); + }); + + it('keeps a pulled refresh running while a controlled parent holds it, until the parent ends it', async () => { + let end: () => void = () => {}; + function Parent() { + const [refreshing, setRefreshing] = useState(false); + end = () => setRefreshing(false); + return ( + setRefreshing(true)} + isRefreshing={refreshing}> +

Inbox

+
+ ); + } + render(); + pull(content(), [30, 30, 30, 30]); + await waitFor(() => expect(content()).toHaveAttribute('aria-busy', 'true')); + await act(async () => { + await new Promise(resolve => setTimeout(resolve, 50)); + }); + expect(content()).toHaveAttribute('aria-busy', 'true'); + act(() => { + end(); + }); + await waitFor(() => expect(content()).not.toHaveAttribute('aria-busy')); + }); + + it.each(['pen', 'mouse'] as const)( + 'never pulls under a %s drag: it stays the browser’s, for text selection', + pointerType => { + useTouchScreen(false); + const onRefresh = vi.fn(); + render( + +

Inbox

+
, + ); + const drag = pointerDrag(content(), pointerType); + // 105 px of travel: past the trigger, were it a finger. + for (const step of [12, 8, 20, 20, 20, 25]) { + drag.move(step); + } + expect(translateY(content())).toBe(0); + drag.lift(); + expect(onRefresh).not.toHaveBeenCalled(); + expect(content()).not.toHaveAttribute('aria-busy'); + }, + ); + + it('takes a scroll only through a pan that claims it: the touch pull is a watcher and takes none, and the content’s only blocking listener is the scroll pull’s `wheel` (spec:AST-094 FR20)', () => { + useTouchScreen(false); + const enabled = vi.spyOn(GestureRecognizer.prototype, 'setEnabled'); + const added = vi.spyOn(HTMLElement.prototype, 'addEventListener'); + try { + render( + {}}> +

Inbox

+
, + ); + const pans = [...new Set(enabled.mock.contexts as GestureRecognizer[])]; + expect(pans).toHaveLength(2); + for (const pan of pans) { + // A watcher registers only passive listeners. A pan that takes a + // scroll gets a blocking `wheel` listener, so only a claimer may take a + // scroll. + expect(pan.allowedScrollTypes.size > 0).toBe(pan.claimsTouches); + } + const blocking = added.mock.calls + .filter( + (call, index) => + added.mock.contexts[index] === content() && + typeof call[2] === 'object' && + call[2] != null && + call[2].passive === false, + ) + .map(call => call[0]); + expect(blocking).toEqual(['wheel']); + } finally { + enabled.mockRestore(); + added.mockRestore(); + } + }); + + it('pulls under a trackpad’s two-finger scroll at the top as under a finger: the same mapping, a trigger, the settle onto the inset once the scroll ends (spec:AST-094 FR43)', async () => { + useTouchScreen(false); + const onRefresh = vi.fn(() => new Promise(() => {})); + render( + +

Inbox

+
, + ); + wheel(content(), [-12, -8, -20], {trackpad: true}); + // 40 px of scroll toward the top, 10 of them the pan's hysteresis, as + // under a finger. + expect(translateY(content())).toBeCloseTo(30, 5); + wheel(content(), [-20, -20, -25], {trackpad: true}); + // 105 px: past the trigger (73 px of overscroll), mid-scroll. + expect(onRefresh).toHaveBeenCalledTimes(1); + expect(content()).toHaveAttribute('aria-busy', 'true'); + // The scroll ends 100 ms after its last step: the content settles onto + // the inset. + await waitFor(() => expect(translateY(content())).toBeCloseTo(60, 5)); + }); + + it('keeps the page’s text selection through a trackpad pull: a scroll selects nothing (spec:AST-094 FR43)', async () => { + useTouchScreen(false); + render( + {}}> +

Inbox

+
, + ); + act(() => { + document.getSelection()?.selectAllChildren(content()); + }); + wheel(content(), [-12, -8, -20], {trackpad: true}); + expect(translateY(content())).toBeGreaterThan(0); + expect(document.getSelection()?.isCollapsed).toBe(false); + await waitFor(() => expect(translateY(content())).toBe(0)); + expect(document.getSelection()?.isCollapsed).toBe(false); + }); + + it('never pulls under a mouse wheel’s notches: they scroll what is under the pointer (spec:AST-094 FR43)', () => { + useTouchScreen(false); + const onRefresh = vi.fn(); + render( + +

Inbox

+
, + ); + wheel(content(), [-100, -100], {trackpad: false}); + expect(translateY(content())).toBe(0); + expect(onRefresh).not.toHaveBeenCalled(); + }); + + it('pulls on any touch screen, an Android phone’s included: one touch model, no iOS check', async () => { + useIos(false); + const onRefresh = vi.fn(); + const {unmount} = render( + +

Inbox

+
, + ); + // The pull owns its container's top edge, so the browser draws no + // overscroll of its own there. + expect(screen.getByTestId('list').style.overscrollBehaviorY).toBe('none'); + pull(content(), [30, 30, 30, 30]); + expect(onRefresh).toHaveBeenCalledTimes(1); + await waitFor(() => expect(content()).not.toHaveAttribute('aria-busy')); + await waitFor(() => expect(translateY(content())).toBe(0)); + unmount(); + render(

Gone

); + }); + + it('ends a pulled refresh on the next commit when a controlled isRefreshing stays false', async () => { + // The parent never takes the refresh (or sets true then false in one + // handler): the prop is the source, so the refresh ends. + const onRefresh = vi.fn(); + render( + +

Inbox

+
, + ); + pull(content(), [30, 30, 30, 30]); + expect(onRefresh).toHaveBeenCalledTimes(1); + await waitFor(() => expect(content()).not.toHaveAttribute('aria-busy')); + await waitFor(() => expect(translateY(content())).toBe(0)); + }); + + it('renders a controlled isRefreshing from its first render', () => { + const seen: boolean[] = []; + function Probe({isRefreshing}: {isRefreshing: boolean}) { + const control = useRefreshControl({isRefreshing}); + seen.push(control.isRefreshing); + return
; + } + render(); + // No first render with the refresh off. + expect(seen[0]).toBe(true); + }); + + it('leaves no inline translate on the content at rest, so its fixed children stay fixed', async () => { + let resolve: () => void = () => {}; + render( + + new Promise(done => { + resolve = done; + }) + }> +

Inbox

+
, + ); + // Any translate, 0 included, makes the content the containing block of + // its `position: fixed` children. + pull(content(), [20, 20, 20, 10]); + await waitFor(() => + expect(content().style.getPropertyValue('translate')).toBe(''), + ); + pull(content(), [30, 30, 30, 30]); + await waitFor(() => expect(translateY(content())).toBeCloseTo(60, 5)); + await act(async () => { + resolve(); + }); + await waitFor(() => + expect(content().style.getPropertyValue('translate')).toBe(''), + ); + }); + + it('holds one scroll listener, on its scroll container, only while enabled, and no resize listener (spec:AST-094 FR24)', () => { + // Optional behavior holds its resources only while enabled. Other parts, + // such as the gesture host, keep their own, so the test compares a + // disabled pull with an enabled one. + const listenersFor = (isDisabled: boolean) => { + const onDocument = vi.spyOn(document, 'addEventListener'); + const onElements = vi.spyOn(HTMLElement.prototype, 'addEventListener'); + const onWindow = vi.spyOn(window, 'addEventListener'); + const {unmount} = render( + {}} + isDisabled={isDisabled}> +

Inbox

+
, + ); + const list = screen.getByTestId('list'); + const counts = { + documentScroll: onDocument.mock.calls.filter( + call => call[0] === 'scroll', + ).length, + listScroll: onElements.mock.instances.filter( + (element, index) => + element === list && onElements.mock.calls[index][0] === 'scroll', + ).length, + resize: onWindow.mock.calls.filter(call => call[0] === 'resize').length, + }; + unmount(); + onDocument.mockRestore(); + onElements.mockRestore(); + onWindow.mockRestore(); + return counts; + }; + const disabled = listenersFor(true); + const enabled = listenersFor(false); + expect(enabled.documentScroll).toBe(0); + expect(enabled.listScroll - disabled.listScroll).toBe(1); + expect(enabled.resize - disabled.resize).toBe(0); + render(

Gone

); + }); + + it('sets up the edge for content that mounts after the hook: its container is claimed near the top, given back when scrolled away, and given back when the content leaves', async () => { + function Late({isShown}: {isShown: boolean}) { + const control = useRefreshControl({ + onRefresh: () => {}, + announce: 'Refreshing', + }); + return ( +
+ {isShown ? ( +
+
+

Inbox

+
+ ) : null} +
+ ); + } + const {rerender} = render(); + // The hook's own setup, two frames after it mounts, finds no content. + await act(async () => { + for (let frame = 0; frame < 3; frame += 1) { + await new Promise(resolve => { + requestAnimationFrame(() => resolve()); + }); + } + }); + const list = screen.getByTestId('list'); + const onList = vi.spyOn(list, 'addEventListener'); + const offList = vi.spyOn(list, 'removeEventListener'); + rerender(); + expect(list.style.overscrollBehaviorY).toBe('none'); + expect(onList.mock.calls.filter(call => call[0] === 'scroll')).toHaveLength( + 1, + ); + // Scrolled away from the top, the container's edge is the browser's + // again; back at the top, the pull claims it again. + const scrollTo = (top: number) => { + list.scrollTop = top; + act(() => { + list.dispatchEvent(new Event('scroll')); + }); + }; + scrollTo(500); + expect(list.style.overscrollBehaviorY).toBe(''); + scrollTo(0); + expect(list.style.overscrollBehaviorY).toBe('none'); + rerender(); + expect(list.style.overscrollBehaviorY).toBe(''); + expect( + offList.mock.calls.filter(call => call[0] === 'scroll'), + ).toHaveLength(1); + onList.mockRestore(); + offList.mockRestore(); + }); + + it('ends a refresh that begins and ends before React renders: refresh() from a timer, with an onRefresh that settles at once', async () => { + let refresh: () => void = () => {}; + function Probe() { + const control = useRefreshControl({onRefresh: () => {}}); + refresh = control.refresh; + return ( +
+
+

Inbox

+
+ ); + } + render(); + // Outside any React event, so the begin and the end land in one render + // and the rendered `isRefreshing` never changes. + await new Promise(resolve => + setTimeout(() => { + refresh(); + resolve(); + }, 0), + ); + // The inset went on with no visible motion; the end slides it off. + await waitFor(() => expect(translateY(content())).toBe(0), { + timeout: 3000, + }); + expect(content()).not.toHaveAttribute('aria-busy'); + }); + + it('does not pull while disabled', () => { + const onRefresh = vi.fn(); + render( + +

Inbox

+
, + ); + pull(content(), [30, 30, 30, 30]); + expect(onRefresh).not.toHaveBeenCalled(); + expect(translateY(content())).toBe(0); + }); + + it('owns the top edge of the scroll container it sits in, not the page’s', () => { + const {unmount} = render( +
+ {}}> +

Inbox

+
+
, + ); + const scroller = screen.getByTestId('scroller'); + expect(scroller.style.overscrollBehaviorY).toBe('none'); + expect(document.documentElement.style.overscrollBehaviorY).toBe(''); + unmount(); + }); + + it('finds a scroll container that starts scrolling only after mount, as ScrollableArea does once it has measured', async () => { + const {unmount} = render( +
+ {}}> +

Inbox

+
+
, + ); + const scroller = screen.getByTestId('scroller'); + // Not scrolling yet: no element scrolls, and the page's own top edge + // stays the browser's. + expect(scroller.style.overscrollBehaviorY).toBe('auto'); + expect(document.documentElement.style.overscrollBehaviorY).toBe(''); + // The container's next render makes it scroll. + scroller.style.overflowY = 'auto'; + await waitFor(() => + expect(scroller.style.overscrollBehaviorY).toBe('none'), + ); + expect(document.documentElement.style.overscrollBehaviorY).toBe(''); + unmount(); + expect(scroller.style.overscrollBehaviorY).toBe('auto'); + }); + + it('follows its scroll container’s scrolls: the top edge is the pull’s only near the top', () => { + render( +
+ {}}> +

Inbox

+
+
, + ); + const scroller = screen.getByTestId('scroller'); + expect(scroller.style.overscrollBehaviorY).toBe('none'); + const scrollTo = (top: number) => { + Object.defineProperty(scroller, 'scrollTop', { + value: top, + configurable: true, + }); + act(() => { + scroller.dispatchEvent(new Event('scroll')); + }); + }; + // Far from the top the browser keeps its own overscroll (the bottom + // bounce), and near the top the pull takes it back. + scrollTo(500); + expect(scroller.style.overscrollBehaviorY).toBe(''); + scrollTo(0); + expect(scroller.style.overscrollBehaviorY).toBe('none'); + }); + + it('restores the scroll container’s own value when it unmounts', () => { + function Host({hasControl}: {hasControl: boolean}) { + return ( +
+ {hasControl ? ( + {}}> +

Inbox

+
+ ) : ( +

Inbox

+ )} +
+ ); + } + const {rerender} = render(); + const scroller = screen.getByTestId('scroller'); + expect(scroller.style.overscrollBehaviorY).toBe('none'); + rerender(); + expect(scroller.style.overscrollBehaviorY).toBe(''); + }); + it('shows the indicator in full for a refresh begun without a pull', () => { + function WithButton() { + const control = useRefreshControl({ + onRefresh: () => new Promise(() => {}), + }); + return ( +
+
+
+ +
+
+ ); + } + render(); + expect(reveal()).toBe(''); + act(() => { + screen.getByRole('button', {name: 'Refresh'}).click(); + }); + expect(reveal()).toBe('1'); + }); + + it('reveals the indicator with the pull, and hides it again when a refresh ends under the finger', async () => { + function Controlled({isRefreshing}: {isRefreshing: boolean}) { + return ( + {}}> +

Inbox

+
+ ); + } + const {rerender} = render(); + // Part of the way to the trigger: part of the indicator. + pull(content(), [20, 20], false); + const partway = Number(reveal()); + expect(partway).toBeGreaterThan(0); + expect(partway).toBeLessThan(1); + // Past the trigger, the finger still down: all of it. + for (const step of [30, 30]) { + touch('touchmove', content(), 140 + step); + } + rerender(); + expect(reveal()).toBe('1'); + rerender(); + touch('touchend', content(), 200, true); + await waitFor(() => expect(reveal()).toBe('0')); + }); + + it('pulls only in an element that scrolls: on the page itself the browser keeps its own top edge', () => { + document.documentElement.style.overscrollBehaviorY = 'auto'; + const onRefresh = vi.fn(); + render( + +

Inbox

+
, + ); + expect(document.documentElement.style.overscrollBehaviorY).toBe('auto'); + pull(content(), [30, 30, 30, 30]); + expect(onRefresh).not.toHaveBeenCalled(); + expect(translateY(content())).toBe(0); + document.documentElement.style.overscrollBehaviorY = ''; + }); + + it('leaves a scroll container that fits to the browser: no top-edge claim and no pull (spec:AST-025 FR14, FR18)', () => { + const onRefresh = vi.fn(); + render( +
{ + if (element != null) { + sized(element, {client: 334, scroll: 334}); + } + }} + style={{overflowY: 'auto'}}> + +

Inbox

+
+
, + ); + // A scroll that starts here belongs to the page around the list. So the + // list keeps no containment, and the pull takes nothing. + expect(screen.getByTestId('scroller').style.overscrollBehaviorY).toBe(''); + pull(content(), [30, 30, 30, 30]); + expect(onRefresh).not.toHaveBeenCalled(); + expect(translateY(content())).toBe(0); + }); + + it('claims the top edge once its container overflows, and gives it back when the content fits again (spec:AST-025 FR14)', () => { + type Dispatch = (entries: ResizeObserverEntry[]) => void; + const observers: {callback: Dispatch; isConnected: boolean}[] = []; + vi.stubGlobal( + 'ResizeObserver', + class { + state: {callback: Dispatch; isConnected: boolean}; + constructor(callback: Dispatch) { + this.state = {callback, isConnected: true}; + observers.push(this.state); + } + observe() { + this.state.isConnected = true; + } + unobserve() {} + disconnect() { + this.state.isConnected = false; + } + }, + ); + const {unmount} = render( +
{ + if (element != null) { + sized(element, {client: 334, scroll: 334}); + } + }} + style={{overflowY: 'auto'}}> + {}}> +

Inbox

+
+
, + ); + const scroller = screen.getByTestId('scroller'); + const resize = (scroll: number) => { + sized(scroller, {client: 334, scroll}); + act(() => { + for (const observer of observers) { + observer.callback([ + {target: scroller} as unknown as ResizeObserverEntry, + ]); + } + }); + }; + expect(scroller.style.overscrollBehaviorY).toBe(''); + resize(1000); + expect(scroller.style.overscrollBehaviorY).toBe('none'); + resize(334); + expect(scroller.style.overscrollBehaviorY).toBe(''); + unmount(); + expect(observers.length).toBeGreaterThan(0); + expect(observers.some(observer => observer.isConnected)).toBe(false); + }); + + it('never scrolls the page: a refresh begun with no container that overflows moves no scroll', () => { + const scrollTo = vi.fn(); + vi.stubGlobal('scrollTo', scrollTo); + function OnThePage() { + const control = useRefreshControl({ + onRefresh: () => new Promise(() => {}), + }); + return ( +
+
+ +
+ ); + } + render(); + act(() => { + screen.getByRole('button', {name: 'Refresh'}).click(); + }); + expect(scrollTo).not.toHaveBeenCalled(); + }); + + it('calls onRefresh once: a pull while refreshing only stretches', async () => { + const onRefresh = vi.fn(() => new Promise(() => {})); + render( + +

Inbox

+
, + ); + pull(content(), [30, 30, 30, 30]); + expect(onRefresh).toHaveBeenCalledTimes(1); + await waitFor(() => expect(translateY(content())).toBeCloseTo(60, 5)); + // Far past the trigger again, beyond the inset too. + pull(content(), [30, 30, 30, 30, 30, 30]); + expect(onRefresh).toHaveBeenCalledTimes(1); + expect(content()).toHaveAttribute('aria-busy', 'true'); + }); + + it("starts each release's settle at the content's speed as the finger lifts: the finger's speed where it tracks one to one, less in the rubber band, and the same onto the refreshing inset", () => { + // The gesture arena keeps one clock for the page across tests. The + // events start past it, and the browser's clock follows them, so real + // time between two events never reads as a pause before a lift. Both + // clocks are put back afterwards. + const eventClock = clock; + clock = performance.now() + 100_000; + const browserNow = vi + .spyOn(performance, 'now') + .mockImplementation(() => clock); + const scrollVelocity = vi.spyOn( + PanGestureRecognizer.prototype, + 'scrollVelocity', + ); + try { + const release = ( + steps: number[], + onRefresh: UseRefreshControlOptions['onRefresh'] = () => {}, + ) => { + animators.list.length = 0; + const {unmount} = render( + +

Inbox

+
, + ); + const [contentAnimator, indicatorAnimator] = animators.list.slice( + -2, + ) as MotionAnimator[]; + const contentAnimate = vi.spyOn(contentAnimator, 'animate'); + const indicatorAnimate = vi.spyOn(indicatorAnimator, 'animate'); + scrollVelocity.mockClear(); + pull(content(), steps); + const [to, transition] = contentAnimate.mock.calls.at(-1) ?? []; + const result = { + to: to?.y, + content: transition?.velocity?.y, + indicator: indicatorAnimate.mock.calls.at(-1)?.[1].velocity?.y, + scroll: scrollVelocity.mock.results.at(-1)?.value?.y as + number | undefined, + isBusy: content().getAttribute('aria-busy') === 'true', + }; + unmount(); + return result; + }; + // 10 px a frame of 16 ms is 625 px/s. + const tracked = release([10, 10, 10, 10, 10]); + expect(tracked.to).toBe(0); + expect(tracked.content).toBeCloseTo(625, 6); + expect(tracked.indicator).toBeCloseTo(-625, 6); + // Past the one-to-one stretch the content moves slower than the finger. + const banded = release([10, 10, 10, 10, 10, 10, 10, 10]); + expect(banded.content).toBeGreaterThan(0); + expect(banded.content).toBeLessThan(625); + expect(banded.indicator).toBeCloseTo(-(banded.content ?? 0), 6); + // An accelerating flick hands the scroll view's release velocity, the + // blend of the pan's last two values, below its last frame's speed. + const flick = release([5, 5, 5, 10, 15]); + expect(flick.scroll).toBeGreaterThan(0); + expect(flick.content).toBeCloseTo(flick.scroll ?? Number.NaN, 6); + expect(flick.content).toBeLessThan(15 / 0.016); + // A finger that held still before it lifted hands no speed. + expect(release([10, 10, 10, 10, 0, 0, 0, 0, 0, 0]).content).toBe(0); + // A pull that triggers carries its speed onto the refreshing inset. + const inset = release( + [20, 20, 20, 20, 20, 20, 20, 20], + () => new Promise(() => {}), + ); + expect(inset.isBusy).toBe(true); + expect(inset.to).toBe(60); + expect(inset.content).toBeGreaterThan(600); + } finally { + scrollVelocity.mockRestore(); + browserNow.mockRestore(); + clock = eventClock; + } + }); +}); diff --git a/packages/lab/src/RefreshControl/useRefreshControl.ts b/packages/lab/src/RefreshControl/useRefreshControl.ts new file mode 100644 index 0000000000000..d614c13a68cf0 --- /dev/null +++ b/packages/lab/src/RefreshControl/useRefreshControl.ts @@ -0,0 +1,255 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useRefreshControl.ts + * @input onRefresh, isRefreshing, isDisabled and announce; the touch + * layer (refreshTouchController.ts) + * @output Exports useRefreshControl: refs for the pulled content and the + * app's indicator, `isRefreshing`, and `refresh()` for the non-gesture path + * @position Lab's pull to refresh: the state, `onRefresh`, the announcement + * and the gate. refreshTouchController.ts holds everything a finger drives, + * and only this file imports it. + * + * SYNC: When modified, update: + * - /packages/lab/src/RefreshControl/refreshTouchController.ts + * - /packages/lab/src/RefreshControl/useRefreshControl.test.tsx + */ + +// A finger pulls, and so does a trackpad's two-finger scroll once the content +// is at its top, with the same mapping, trigger and settle. The pull applies +// in an element that scrolls. A mouse or pen drag stays the browser's, for +// text selection. The app draws the indicator and says what is announced. + +import { + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, + type RefCallback, +} from 'react'; +import {useAnnounce} from '@astryxdesign/core/hooks'; +import { + INITIAL_REFRESH_STATE, + reduceRefresh, + type RefreshEffect, + type RefreshEvent, + type RefreshState, +} from './refreshModel'; +import {useRefreshTouchController} from './refreshTouchController'; + +export {REFRESH_REVEAL_VAR} from './refreshIndicator'; + +export interface UseRefreshControlOptions { + /** + * Called when a pull triggers, or when `refresh()` runs. Return a promise to + * keep the control refreshing until it settles (uncontrolled use). + */ + onRefresh?: () => unknown; + /** + * Controlled refreshing state: `true` puts the control in the refreshing + * state (as `beginRefreshing()`), `false` ends it (as `endRefreshing()`). + * Omit it to let the promise `onRefresh` returns decide. + */ + isRefreshing?: boolean; + /** Turns the pull off. A refresh in progress keeps running. */ + isDisabled?: boolean; + /** + * Announced politely when a refresh starts, for example "Refreshing". The + * app supplies it in its own language. Omit it to announce nothing. + */ + announce?: string; +} + +export interface UseRefreshControlResult { + /** Attach to the element that wraps the scrolled content (it is pulled). */ + contentRef: RefCallback; + /** + * Attach this ref to the app's indicator, for example a Spinner. The + * indicator is a band as tall as the refresh height. It sits at the bottom + * of an overflow-hidden box that rides on the content's top edge. The hook + * moves the band against the content, so it stays pinned at the top of the + * scroll view, where UIRefreshControl sits. The content's edge covers it. + * The hook writes how much of it the pull reveals, 0 to 1, to + * `REFRESH_REVEAL_VAR`, and fades it as a settle takes the content back. + */ + indicatorRef: RefCallback; + /** Whether a refresh is in progress. */ + isRefreshing: boolean; + /** Starts a refresh without a pull (the non-gesture path). */ + refresh: () => void; +} + +/** + * Pull to refresh, as UIRefreshControl, for the app's own scroll container. + * Pulling the content down past the top reveals the app's indicator. Pulling + * past the trigger starts a refresh with the finger still down. Letting go + * settles the content onto the refreshing inset until the refresh ends, and + * then it slides back up. + * + * A finger pulls, and so does a trackpad's two-finger scroll at the top. A + * mouse or pen drag stays the browser's, for text selection, and a mouse + * wheel's notches never pull. Always give people another way to refresh, such + * as a button that calls `refresh()`: a pull has no keyboard or + * assistive-technology equivalent. + * + * @example + * ``` + * const pull = useRefreshControl({onRefresh: reload, announce: 'Refreshing'}); + *
+ *
+ * … + *
+ *
+ * + *
+ *
+ *
+ *
+ * ``` + */ +export function useRefreshControl({ + onRefresh, + isRefreshing: isRefreshingProp, + isDisabled = false, + announce, +}: UseRefreshControlOptions = {}): UseRefreshControlResult { + const announcer = useAnnounce(); + const [isRefreshing, setIsRefreshing] = useState(false); + // Controlled: a refresh the hook started waits one commit for the parent + // to take it. + const awaitingProp = useRef(false); + const [controlledCheck, setControlledCheck] = useState(0); + + const model = useRef(INITIAL_REFRESH_STATE); + const refreshToken = useRef(0); + const isControlled = isRefreshingProp !== undefined; + const latest = useRef({onRefresh, isControlled, announce, announcer}); + // Syncs the handlers' ref with the newest options. + useLayoutEffect(() => { + latest.current = {onRefresh, isControlled, announce, announcer}; + }); + + const dispatchRef = useRef<(event: RefreshEvent) => void>(() => {}); + const touch = useRefreshTouchController({ + isPullEnabled: !isDisabled, + model, + dispatchRef, + }); + + // -- Effects of the state machine ----------------------------------------- + + const callHandler = useCallback(() => { + const token = ++refreshToken.current; + const result = latest.current.onRefresh?.(); + if (latest.current.isControlled) { + // The prop is the source: unless the parent takes this refresh by + // setting `isRefreshing`, it ends on the next commit. + awaitingProp.current = true; + setControlledCheck(count => count + 1); + return; + } + const settle = () => { + if (token === refreshToken.current) { + dispatchRef.current({type: 'end'}); + } + }; + void Promise.resolve(result).then(settle, settle); + }, []); + + const run = useCallback( + (effect: RefreshEffect) => { + const {announce: words, announcer: say} = latest.current; + switch (effect.type) { + case 'trigger': + setIsRefreshing(true); + touch.trigger(); + if (words) { + say(words); + } + callHandler(); + break; + case 'begin': { + setIsRefreshing(true); + if (words) { + say(words); + } + touch.begin(); + if (effect.callHandler) { + callHandler(); + } + break; + } + case 'settle': + touch.settle(effect.to); + break; + case 'end': + setIsRefreshing(false); + touch.end(); + break; + } + }, + [callHandler, touch], + ); + + const dispatch = useCallback( + (event: RefreshEvent) => { + const next = reduceRefresh(model.current, event); + model.current = next.state; + for (const effect of next.effects) { + run(effect); + } + }, + [run], + ); + dispatchRef.current = dispatch; + + // -- Programmatic control ------------------------------------------------- + + // Syncs a controlled `isRefreshing` into the systems outside React: the + // touch layer and the announcer. The touch layer runs the inset and the + // slide on the compositor. The rendered value is the prop itself. + useEffect(() => { + if (isRefreshingProp === undefined) { + return; + } + dispatch( + isRefreshingProp ? {type: 'begin', source: 'program'} : {type: 'end'}, + ); + }, [dispatch, isRefreshingProp]); + + // A refresh that the hook started, by a pull or `refresh()`, under a + // controlled `isRefreshing`. If the prop is now true, the parent took it. + // Otherwise the refresh ends, for example when a parent keeps false. The end + // goes to the touch layer, outside React, and slides the inset off. + useEffect(() => { + if (!awaitingProp.current) { + return; + } + awaitingProp.current = false; + if (isRefreshingProp === false) { + dispatch({type: 'end'}); + } + }, [controlledCheck, dispatch, isRefreshingProp]); + + const refresh = useCallback(() => { + dispatch({type: 'begin', source: 'user'}); + }, [dispatch]); + + useEffect( + () => () => { + refreshToken.current++; + }, + [], + ); + + return { + contentRef: touch.contentRef, + indicatorRef: touch.indicatorRef, + // Controlled, the prop is the source from the first render. + isRefreshing: isControlled ? Boolean(isRefreshingProp) : isRefreshing, + refresh, + }; +} diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts index c28ce99d491b0..92178abd14e8e 100644 --- a/packages/lab/src/index.ts +++ b/packages/lab/src/index.ts @@ -327,3 +327,12 @@ export { // RichTextEditor (RFC meta/astryx#3899) moved out of @astryxdesign/lab into // its own package, @astryxdesign/richtext. Import it from there: // import {RichTextEditor, RichTextView} from '@astryxdesign/richtext'; + +// Pull to refresh as UIRefreshControl, applied by the app to its own scroll +// container, on Core's touch foundation. +export { + REFRESH_REVEAL_VAR, + useRefreshControl, + type UseRefreshControlOptions, + type UseRefreshControlResult, +} from './RefreshControl'; From d511e523f32a83ebc00a2ed40a230155c312a4e4 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 4 Nov 2026 13:05:20 -0800 Subject: [PATCH 3/3] chore(lab): the pull-to-refresh story A Storybook story shows useRefreshControl on a plain scroll container, with Core's Spinner as the app's indicator. The interaction spec opens it, and the story can hold a refresh until a test ends it. --- .../stories/PullToRefresh.stories.tsx | 234 ++++++++++++++++++ 1 file changed, 234 insertions(+) create mode 100644 apps/storybook/stories/PullToRefresh.stories.tsx diff --git a/apps/storybook/stories/PullToRefresh.stories.tsx b/apps/storybook/stories/PullToRefresh.stories.tsx new file mode 100644 index 0000000000000..0dbb6e0302335 --- /dev/null +++ b/apps/storybook/stories/PullToRefresh.stories.tsx @@ -0,0 +1,234 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +import {useCallback, useState, type ReactNode} from 'react'; +import type {Meta, StoryObj} from '@storybook/react'; +import {REFRESH_REVEAL_VAR, useRefreshControl} from '@astryxdesign/lab'; +import {Button} from '@astryxdesign/core/Button'; +import {List, ListItem} from '@astryxdesign/core/List'; +import {Spinner} from '@astryxdesign/core/Spinner'; + +interface StoryArgs { + /** + * How long a refresh takes, in ms. Below 0, it lasts until the page + * dispatches `refreshcontrol-story-end` on `window`, so a test ends it. + */ + refreshMs: number; + /** Rows in the list. */ + rows: number; +} + +const meta: Meta = { + title: 'Lab/Pull to refresh', + parameters: { + layout: 'fullscreen', + }, + args: { + refreshMs: 1500, + rows: 40, + }, + argTypes: { + refreshMs: {control: {type: 'number', min: 0, step: 100}}, + rows: {control: {type: 'number', min: 1, step: 1}}, + }, +}; + +export default meta; + +type Story = StoryObj; + +const wait = (ms: number) => + new Promise(resolve => { + setTimeout(resolve, ms); + }); + +/** One refresh: `ms`, or until the page ends it when `ms` is below 0. */ +function refreshFor(ms: number): Promise { + if (Number(ms) >= 0) { + return wait(ms); + } + return new Promise(resolve => { + window.addEventListener('refreshcontrol-story-end', () => resolve(), { + once: true, + }); + }); +} + +function Messages({rows, count}: {rows: number; count: number}) { + return ( + + {Array.from({length: rows}, (_, index) => ( + + ))} + + ); +} + +/** The app's indicator shows as much of itself as the pull reveals. */ +const revealed = {opacity: `var(${REFRESH_REVEAL_VAR}, 0)`}; + +/** + * What an app writes: its own scroll container, the content the hook pulls, + * and its own indicator, here Core's Spinner. The indicator band sits at the + * bottom of an overflow-hidden box on the content's top edge, after the + * content. + */ +function PullToRefresh({ + onRefresh, + isRefreshing, + text, + count, + isAlwaysScrollable = false, + children, +}: { + onRefresh: () => unknown; + isRefreshing?: boolean; + text: string; + count: number; + /** + * Makes the content 1 px taller than the container. The pull applies only + * in a container that overflows, so a short list pulls only with this. + */ + isAlwaysScrollable?: boolean; + children: ReactNode; +}) { + const control = useRefreshControl({ + onRefresh, + isRefreshing, + announce: 'Refreshing', + }); + return ( +
+
+ {children} +
+
+ + + +
+
+
+
+ ); +} + +function useInbox(refreshMs: number) { + const [count, setCount] = useState(0); + const onRefresh = useCallback(async () => { + await refreshFor(refreshMs); + setCount(value => value + 1); + }, [refreshMs]); + return {count, onRefresh}; +} + +/** + * A list in the app's own scroll container. Pull it down past the top on a + * touch screen, or with a trackpad's two-finger scroll. Past the trigger, the + * refresh starts with the finger down. + */ +export const InAScrollContainer: Story = { + render: function InAScrollContainerStory({refreshMs, rows}) { + const {count, onRefresh} = useInbox(refreshMs); + return ( +
+ + + +
+ ); + }, +}; + +/** + * Controlled: the button refreshes too (the pull has no keyboard or + * screen-reader equivalent), and the app sets `isRefreshing` itself. + */ +export const Controlled: Story = { + render: function ControlledStory({refreshMs, rows}) { + const [isRefreshing, setIsRefreshing] = useState(false); + const [count, setCount] = useState(0); + const refresh = useCallback(() => { + setIsRefreshing(true); + void refreshFor(refreshMs).then(() => { + setCount(value => value + 1); + setIsRefreshing(false); + }); + }, [refreshMs]); + return ( +
+
+
+
+ + + +
+
+ ); + }, +}; + +/** + * A list shorter than the screen still pulls: the app makes its content 1 px + * taller than the container, so the container overflows. + */ +export const ShortList: Story = { + args: {rows: 3}, + render: function ShortListStory({refreshMs, rows}) { + const {count, onRefresh} = useInbox(refreshMs); + return ( +
+ + + +
+ ); + }, +};