From f3e826a906d05b19fe0ccbfc645fcda5d7e6d7cc Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 21:00:59 -0800 Subject: [PATCH 1/5] chore(lab): Lab's animator hook, over Core's internal touch entry Internal entries land with their first user, per #8562. Lab components, TabBar first, animate with Core's motion engine and read the touch presentation and the writing direction as Core does. `@astryxdesign/core/internal/touch`, which already carries the pan recognizer, its hook, the engine and the rubber band for Lab's refresh control (#9807), gains by name: - `useTouchPresentation` and `TOUCH_QUERY`, the finger-or-mouse decision in render and outside it; - `isRtlElement`, the writing direction a pan mirrors by; - UIKit's `UIKIT_GESTURES` table. The engine's factory is renamed from `createMotionAnimator` to `createMotionEngine` at its source and in every internal caller, with its types `MotionEngine` and `MotionEngineOptions` (the engine's `Animator` and `AnimatorOptions`), so the engine and the public `createAnimator` differ by more than one word (architecture:react-component-runtime INV13). Named re-exports of code already on main, plus that rename: no behavior changes, no public docs, no root re-export, and the `@astryx/no-core-internal-import` lint rule already limits the entry to Core and Lab. The entry's tests check it re-exports the same values Core imports by path and carries no public factory's name; the touch-support bundle test keeps every Lab-only name out of the root entry. One Lab module those components share comes with them: `internal/useMotionEngine`, a stable motion engine bound to an element through a callback ref. Lab's refresh control now uses it in place of its own identical `RefreshControl/useMotionAnimator.ts`. --- .../core-internal-touch-entry-lab-animator.md | 7 ++ packages/core/src/DateInput/wheelStrip.ts | 4 +- .../useSegmentedSelectionMotion.test.ts | 6 +- .../useSegmentedSelectionMotion.ts | 6 +- .../core/src/Slider/sliderTouchController.ts | 4 +- .../core/src/Switch/useSwitchTouch.test.ts | 2 +- packages/core/src/Switch/useSwitchTouch.ts | 8 +- packages/core/src/animator/createAnimator.ts | 6 +- .../core/src/animator/publicSurface.test.ts | 4 +- .../__tests__/browser/presentedFixture.ts | 4 +- packages/core/src/hooks/usePager.test.ts | 10 +- packages/core/src/internal/touch.test.ts | 32 +++++- packages/core/src/internal/touch.ts | 24 ++-- packages/core/src/motion/README.md | 6 +- .../animator.interaction.browser.spec.ts | 10 +- .../core/src/motion/__tests__/motionBundle.ts | 2 +- packages/core/src/motion/animator.test.ts | 18 +-- packages/core/src/motion/animator.ts | 14 +-- .../core/src/motion/resolveMotion.test.ts | 6 +- .../RefreshControl/refreshTouchController.ts | 6 +- .../src/RefreshControl/useMotionAnimator.ts | 35 ------ .../RefreshControl/useRefreshControl.test.tsx | 23 ++-- .../lab/src/internal/useMotionEngine.test.tsx | 108 ++++++++++++++++++ packages/lab/src/internal/useMotionEngine.ts | 54 +++++++++ scripts/motion-node-load.test.mjs | 8 +- scripts/touch-support-bundle.test.mjs | 14 ++- 26 files changed, 298 insertions(+), 123 deletions(-) create mode 100644 .changeset/core-internal-touch-entry-lab-animator.md delete mode 100644 packages/lab/src/RefreshControl/useMotionAnimator.ts create mode 100644 packages/lab/src/internal/useMotionEngine.test.tsx create mode 100644 packages/lab/src/internal/useMotionEngine.ts diff --git a/.changeset/core-internal-touch-entry-lab-animator.md b/.changeset/core-internal-touch-entry-lab-animator.md new file mode 100644 index 0000000000000..75bf478b46b66 --- /dev/null +++ b/.changeset/core-internal-touch-entry-lab-animator.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: Core's internal motion engine factory is renamed `createMotionEngine` (from `createMotionAnimator`), with its types `MotionEngine` and `MotionEngineOptions`, at its source and in every internal caller. Core's internal touch entry also re-exports, by name, the UIKit gesture values, the right-to-left check, and the touch-presentation hook and query that Lab components read. Lab's `useMotionEngine` hook wraps the engine, and Lab's refresh control uses it. Apps import nothing new. + +@vjeux diff --git a/packages/core/src/DateInput/wheelStrip.ts b/packages/core/src/DateInput/wheelStrip.ts index 8feef24354ca4..506a2f783fda5 100644 --- a/packages/core/src/DateInput/wheelStrip.ts +++ b/packages/core/src/DateInput/wheelStrip.ts @@ -16,7 +16,7 @@ */ import {canVibrate, playHaptic} from '../gestures/haptics'; -import {createMotionAnimator, type MotionCurve} from '../motion/animator'; +import {createMotionEngine, type MotionCurve} from '../motion/animator'; import {reducedMotionFade} from '../motion/reducedMotion'; import {picker} from '../motion/uikit/picker'; import { @@ -132,7 +132,7 @@ function now(): number { * ``` */ export function createWheelStrip(initialLayout: WheelLayout): WheelStrip { - const animator = createMotionAnimator(null); + const animator = createMotionEngine(null); let layout = initialLayout; let running: Running | null = null; let nearestListener: ((position: number) => void) | null = null; diff --git a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts index f88dc63b3b2c0..713644d7f95b0 100644 --- a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts +++ b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts @@ -13,7 +13,7 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {motionRoleOf} from '../motion/roles'; -import {createMotionAnimator, type Animator} from '../motion/animator'; +import {createMotionEngine, type Animator} from '../motion/animator'; import {solveSpring, toSpring} from '../motion/spring'; import {cubicBezier} from '../motion/bezier'; import {segmentedControl, springs} from '../motion/uikit'; @@ -105,12 +105,12 @@ function setup(selected: string, {coarse = true}: {coarse?: boolean} = {}) { document.head.append(style); document.body.append(track); // A finger by default: Reduced Motion fades (design:reduced-motion DR2). - const animator: Animator = createMotionAnimator(null, { + const animator: Animator = createMotionEngine(null, { now: () => clock, pseudoElement: '::before', }); // The ::after: the lifted lens's shadow, or the surface fading out. - const afterAnimator: Animator = createMotionAnimator(null, { + const afterAnimator: Animator = createMotionEngine(null, { now: () => clock, pseudoElement: '::after', initial: {opacity: 0}, diff --git a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts index 69e10fba731b1..3fdf9c0af3c63 100644 --- a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts +++ b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts @@ -25,7 +25,7 @@ import { type RefObject, } from 'react'; import { - createMotionAnimator, + createMotionEngine, type AnimateOptions, type Animator, type MotionCurve, @@ -539,7 +539,7 @@ export class SegmentedSelectionMotion { private readonly after: Animator; constructor( - private readonly animator: Animator = createMotionAnimator(null, { + private readonly animator: Animator = createMotionEngine(null, { pseudoElement: '::before', }), options: SegmentedSelectionMotionOptions = {}, @@ -552,7 +552,7 @@ export class SegmentedSelectionMotion { this.now = options.now ?? defaultNow; this.after = options.afterAnimator ?? - createMotionAnimator(null, { + createMotionEngine(null, { pseudoElement: '::after', initial: {opacity: 0}, }); diff --git a/packages/core/src/Slider/sliderTouchController.ts b/packages/core/src/Slider/sliderTouchController.ts index 5d90e247e1551..916ae87e3124c 100644 --- a/packages/core/src/Slider/sliderTouchController.ts +++ b/packages/core/src/Slider/sliderTouchController.ts @@ -29,7 +29,7 @@ import {TapGestureRecognizer} from '../gestures/TapGestureRecognizer'; import type {PointerKind} from '../gestures/types'; import {isRtlElement} from '../hooks/isRtlElement'; import { - createMotionAnimator, + createMotionEngine, type Animator, type MotionCurve, type MotionHandle, @@ -1186,7 +1186,7 @@ export class SliderTouchController { private animatorFor(element: HTMLElement): Animator { let animator = this.animators.get(element); if (animator == null) { - animator = createMotionAnimator(element); + animator = createMotionEngine(element); this.animators.set(element, animator); } return animator; diff --git a/packages/core/src/Switch/useSwitchTouch.test.ts b/packages/core/src/Switch/useSwitchTouch.test.ts index 63fd79d0771a5..b74e18c8494e2 100644 --- a/packages/core/src/Switch/useSwitchTouch.test.ts +++ b/packages/core/src/Switch/useSwitchTouch.test.ts @@ -39,7 +39,7 @@ vi.mock('../motion/animator', async importOriginal => { const actual = await importOriginal(); return { ...actual, - createMotionAnimator: ( + createMotionEngine: ( element: Element, options: {pseudoElement?: string} = {}, ) => { diff --git a/packages/core/src/Switch/useSwitchTouch.ts b/packages/core/src/Switch/useSwitchTouch.ts index 2422dc0f4735d..888f997b53878 100644 --- a/packages/core/src/Switch/useSwitchTouch.ts +++ b/packages/core/src/Switch/useSwitchTouch.ts @@ -23,7 +23,7 @@ import type {GestureTouch} from '../gestures/types'; import {isRtlElement} from '../hooks/isRtlElement'; import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import { - createMotionAnimator, + createMotionEngine, type Animator, type MotionCurve, } from '../motion/animator'; @@ -282,15 +282,15 @@ export class SwitchTouchController { return; } registerSwitchTable(); - this.thumb = createMotionAnimator(elements.thumb); + this.thumb = createMotionEngine(elements.thumb); // The layer rests clear (its class's opacity 0) while the visuals show // the value; from here its opacity is the animator's. - this.fade = createMotionAnimator(elements.track, { + this.fade = createMotionEngine(elements.track, { pseudoElement: '::after', initial: {opacity: 0}, }); this.fade.set({opacity: 0}); - this.shadow = createMotionAnimator(elements.thumb, { + this.shadow = createMotionEngine(elements.thumb, { pseudoElement: '::after', initial: {opacity: 0}, }); diff --git a/packages/core/src/animator/createAnimator.ts b/packages/core/src/animator/createAnimator.ts index c712bd9467c6b..0fe0663ba43c7 100644 --- a/packages/core/src/animator/createAnimator.ts +++ b/packages/core/src/animator/createAnimator.ts @@ -18,9 +18,9 @@ */ import { - createMotionAnimator, + createMotionEngine, SETTLE_THRESHOLD, - type Animator as MotionAnimator, + type Animator as MotionEngine, type MotionCurve, type MotionProperty, type MotionValues, @@ -199,7 +199,7 @@ export function createAttachableAnimator(): { readonly animator: Animator; readonly attach: (element: HTMLElement | null) => void; } { - const motion: MotionAnimator = createMotionAnimator(null); + const motion: MotionEngine = createMotionEngine(null); // Calls do nothing while no element is attached, before the ref attaches // or after it lets go. They also do nothing after destroy, and animate and // decay then resolve at once. diff --git a/packages/core/src/animator/publicSurface.test.ts b/packages/core/src/animator/publicSurface.test.ts index 00babbcb429af..e2196d246e2f0 100644 --- a/packages/core/src/animator/publicSurface.test.ts +++ b/packages/core/src/animator/publicSurface.test.ts @@ -21,7 +21,7 @@ const SRC = path.join(__dirname, '..'); /** Names of the motion module beneath the public animator. */ const INTERNAL = [ - 'createMotionAnimator', + 'createMotionEngine', 'createAttachableAnimator', 'animatorFor', 'coast', @@ -67,6 +67,6 @@ describe('the public animator surface', () => { 'utf8', ); expect(motion).not.toMatch(/export function createAnimator\b/); - expect(motion).toMatch(/export function createMotionAnimator\b/); + expect(motion).toMatch(/export function createMotionEngine\b/); }); }); diff --git a/packages/core/src/gestures/__tests__/browser/presentedFixture.ts b/packages/core/src/gestures/__tests__/browser/presentedFixture.ts index cc28188bf15eb..28d360831f071 100644 --- a/packages/core/src/gestures/__tests__/browser/presentedFixture.ts +++ b/packages/core/src/gestures/__tests__/browser/presentedFixture.ts @@ -22,7 +22,7 @@ * @position Browser fixture of presentedHitTesting.interaction.browser.spec.ts; test-only */ -import {createMotionAnimator} from '../../../motion/animator'; +import {createMotionEngine} from '../../../motion/animator'; import {presentedOffsetOf} from '../../../motion/presentation'; import {GestureHost} from '../../GestureHost'; import {PanGestureRecognizer} from '../../PanGestureRecognizer'; @@ -101,7 +101,7 @@ const TRAVEL = 444; */ const SPRING = {response: 6, dampingRatio: 1} as const; -const animator = createMotionAnimator(sheet); +const animator = createMotionEngine(sheet); const drawn = (target: Element): DOMRect => Element.prototype.getBoundingClientRect.call(target); diff --git a/packages/core/src/hooks/usePager.test.ts b/packages/core/src/hooks/usePager.test.ts index 46831b156e278..506e985b43ede 100644 --- a/packages/core/src/hooks/usePager.test.ts +++ b/packages/core/src/hooks/usePager.test.ts @@ -17,7 +17,7 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {GestureHost} from '../gestures/GestureHost'; import {PanGestureRecognizer} from '../gestures/PanGestureRecognizer'; import {ManualClock} from '../gestures/__tests__/harness'; -import {createMotionAnimator, type Animator} from '../motion/animator'; +import {createMotionEngine, type Animator} from '../motion/animator'; import {solveAnimatedPageScroll, solvePaging} from '../motion/paging'; import type * as motionResolution from '../motion/resolveMotion'; import {resolveMotion} from '../motion/resolveMotion'; @@ -305,7 +305,7 @@ function setup(options: Partial = {}, rtl = false): Fixture { value: WIDTH, configurable: true, }); - const animator = createMotionAnimator(track, { + const animator = createMotionEngine(track, { now: () => now, requestFrame: callback => { frameQueue.push(callback); @@ -1259,7 +1259,7 @@ describe('createPager', () => { // (DR3). The drag itself follows the pointer. function reducedPager(f: Fixture, defaultIndex: number, coarse: boolean) { stubMedia(true, coarse); - const reduced = createMotionAnimator(f.track, { + const reduced = createMotionEngine(f.track, { now: () => now, requestFrame: callback => { frameQueue.push(callback); @@ -1928,7 +1928,7 @@ function setupChildren( value: WIDTH, configurable: true, }); - const animator = createMotionAnimator(track, { + const animator = createMotionEngine(track, { now: () => now, requestFrame: callback => { frameQueue.push(callback); @@ -2461,7 +2461,7 @@ describe('pre-review fixes', () => { configurable: true, }); const host = {attach: () => () => {}} as unknown as GestureHost; - const animator = createMotionAnimator(track, { + const animator = createMotionEngine(track, { now: () => now, requestFrame: callback => { frameQueue.push(callback); diff --git a/packages/core/src/internal/touch.test.ts b/packages/core/src/internal/touch.test.ts index 0300e71f3886a..02e63f68e064a 100644 --- a/packages/core/src/internal/touch.test.ts +++ b/packages/core/src/internal/touch.test.ts @@ -45,7 +45,7 @@ describe('internal/touch', () => { 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.createMotionEngine).toBe(animator.createMotionEngine); expect(entry.cubicBezier).toBe(bezier.cubicBezier); expect(entry.mapProgress).toBe(progress.mapProgress); expect(entry.parseCssEasing).toBe(roles.parseCssEasing); @@ -54,8 +54,34 @@ describe('internal/touch', () => { 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'); + // No internal factory shares a public factory's name, or a planned one's. + for (const name of [ + 'createAnimator', + 'createPanGesture', + 'createDragToSnapPoints', + ]) { + expect(entry, name).not.toHaveProperty(name); + } + }); + + it('re-exports by name what other Lab components read', async () => { + const entry: Record = await import('./touch'); + const presentation = await import('../utils/touchPresentation'); + const direction = await import('../hooks/isRtlElement'); + const uikitGestures = await import('../motion/uikit/gestures'); + const touchQueries = await import('../utils/touchQueries'); + expect(entry.useTouchPresentation).toBe(presentation.useTouchPresentation); + expect(entry.isRtlElement).toBe(direction.isRtlElement); + expect(entry.UIKIT_GESTURES).toBe(uikitGestures.UIKIT_GESTURES); + expect(entry.TOUCH_QUERY).toBe(touchQueries.TOUCH_QUERY); + // An identity check passes when both sides are undefined, so each name + // must also be defined. + for (const name of ['useTouchPresentation', 'isRtlElement']) { + expect(typeof entry[name], name).toBe('function'); + } + for (const name of ['UIKIT_GESTURES', 'TOUCH_QUERY']) { + expect(entry[name], name).toBeDefined(); + } }); it('attaches no window or document listeners when it loads', async () => { diff --git a/packages/core/src/internal/touch.ts b/packages/core/src/internal/touch.ts index 560cc95f3eeac..c46d3d5a8342e 100644 --- a/packages/core/src/internal/touch.ts +++ b/packages/core/src/internal/touch.ts @@ -3,10 +3,11 @@ /** * @file touch.ts * @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 + * the pan, the motion engine and math, and the touch-presentation and + * direction helpers that Lab components read * @output `@astryxdesign/core/internal/touch`: the gesture core's primitives - * for Lab components, re-exported by name + * and the motion, touch-presentation and direction modules for Lab + * components, re-exported by name * @position An internal entry reserved for Astryx's own packages: * undocumented, outside the public API and its compatibility promise * (spec:AST-017 FR21), versioned in lockstep with Core, and allowed only in @@ -43,7 +44,7 @@ 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 +// starts it. It also reads the motion engine 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. @@ -55,12 +56,12 @@ export type { PointerKind, } from '../gestures/types'; export {useGestureRecognizer} from '../gestures/useGestureRecognizer'; -// The animator's internal factory. The public one, `createAnimator`, plays +// The motion engine's factory. The public one, `createAnimator`, plays // only the theme's state-change motion. -export {createMotionAnimator} from '../motion/animator'; +export {createMotionEngine} from '../motion/animator'; export type { - Animator as MotionAnimator, - AnimatorOptions as MotionAnimatorOptions, + Animator as MotionEngine, + AnimatorOptions as MotionEngineOptions, MotionCurve, } from '../motion/animator'; export {cubicBezier} from '../motion/bezier'; @@ -72,3 +73,10 @@ export { rubberBandSlope, } from '../motion/rubberBand'; export {scroll} from '../motion/uikit/scroll'; + +// Lab components also read the UIKit gesture table, the touch presentation +// and its query, and an element's direction. +export {isRtlElement} from '../hooks/isRtlElement'; +export {UIKIT_GESTURES} from '../motion/uikit/gestures'; +export {useTouchPresentation} from '../utils/touchPresentation'; +export {TOUCH_QUERY} from '../utils/touchQueries'; diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md index 352a45bbd9c4f..bb8df901afb34 100644 --- a/packages/core/src/motion/README.md +++ b/packages/core/src/motion/README.md @@ -69,7 +69,7 @@ the timings that decide who gets a touch are not roles. ## Animator ``` -import {createMotionAnimator} from '../motion/animator'; +import {createMotionEngine} from '../motion/animator'; import {coast} from '../motion/coast'; import {solveSpringTowardRamp, toSpring} from '../motion/spring'; import {resolveMotion} from '../motion/resolveMotion'; @@ -78,7 +78,7 @@ import {registerSpringsTable, springs} from '../motion/uikit'; // Once, so the springs are registered as their roles: registerSpringsTable(); -const animator = createMotionAnimator(sheet); +const animator = createMotionEngine(sheet); // The animator plays a motion role (spec:AST-094 FR4), its table value, as the // per-role tables stay internal (DEC-15); math on a spring reads the role with // resolveMotion. @@ -175,7 +175,7 @@ await handle.finished; // true if it ran to the end, false if interrupted - `animatorFor(element)` returns the one animator for an element, so code that animates it from several places (a swipe on x, a removal on y) composes in one `translate` track. -- `createMotionAnimator(dialog, {pseudoElement: '::backdrop'})` drives a +- `createMotionEngine(dialog, {pseudoElement: '::backdrop'})` drives a pseudo-element; with no inline style to hold it, a static filling animation holds its end value until the next animation replaces it, while the pseudo-element exists. A dialog's `::backdrop` is made again each time the diff --git a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts index 5d69afb906959..e8ca643b2a294 100644 --- a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts +++ b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts @@ -109,7 +109,7 @@ async function open(page: Page) {
-`; +`; await page.route('http://motion.test/', async route => route.fulfill({contentType: 'text/html', body: html}), ); @@ -394,7 +394,7 @@ test('a frame painted before the compositor has the curve shows the element wher document.body.append(element); return { element, - animator: Motion.createMotionAnimator(element, now ? {now} : {}), + animator: Motion.createMotionEngine(element, now ? {now} : {}), }; }; const x = (element: HTMLElement) => @@ -930,7 +930,7 @@ test('a role variable set on a scope changes nothing while touch motion stays in const report: Record = {}; for (const id of ['plain', 'themed'] as const) { const element = document.getElementById(id) as HTMLElement; - const animator = Motion.createMotionAnimator(element); + const animator = Motion.createMotionEngine(element); animator.set({y: 300}); const handle = animator.animate({y: 0}, {spring: Motion.springs.settle}); await handle.started; @@ -1034,7 +1034,7 @@ test('a fade-in on an element its stylesheet hides stays visible once it retires element.style.cssText = 'position:absolute;top:120px;left:0;width:48px;height:48px;background:#c63'; document.body.append(element); - const animator = Motion.createMotionAnimator(element); + const animator = Motion.createMotionEngine(element); animator.set({opacity: 0}); animator.animate({opacity: 1}, {spring}); await new Promise(resolve => { @@ -1106,7 +1106,7 @@ test('a dialog\u2019s ::backdrop plays the curve and holds its end state', async const dialog = document.createElement('dialog'); document.body.append(dialog); dialog.showModal(); - const backdrop = Motion.createMotionAnimator(dialog, { + const backdrop = Motion.createMotionEngine(dialog, { pseudoElement: '::backdrop', }); backdrop.set({opacity: 0}); diff --git a/packages/core/src/motion/__tests__/motionBundle.ts b/packages/core/src/motion/__tests__/motionBundle.ts index 874fb5e2a8d38..097b83e91a4d6 100644 --- a/packages/core/src/motion/__tests__/motionBundle.ts +++ b/packages/core/src/motion/__tests__/motionBundle.ts @@ -8,7 +8,7 @@ * (global `Motion`), and the type of that global */ -export {createMotionAnimator} from '../animator'; +export {createMotionEngine} from '../animator'; export {solveSpring, toSpring} from '../spring'; export {registerSpringsTable, springs} from '../uikit/springs'; export {motionRoleOf} from '../roles'; diff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.ts index a714bf6414137..86c75b2ad3777 100644 --- a/packages/core/src/motion/animator.test.ts +++ b/packages/core/src/motion/animator.test.ts @@ -19,7 +19,7 @@ import path from 'node:path'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import { animatorFor, - createMotionAnimator, + createMotionEngine, END_HOLD_MS, PROMOTION_LINGER_MS, type AnimatorOptions, @@ -205,7 +205,7 @@ function setup({ }: AnimatorOptions & {reduced?: boolean; coarse?: boolean} = {}) { stubMedia(reduced, coarse); const element = document.createElement('div'); - const animator = createMotionAnimator(element, { + const animator = createMotionEngine(element, { now: () => clock, requestFrame, ...options, @@ -2071,11 +2071,11 @@ describe('promotion: a compositing layer while it moves', () => { .mock.calls.filter(([read]) => read === node).length; const removed = document.createElement('div'); document.body.append(removed); - createMotionAnimator(removed, {now: () => clock, requestFrame}); + createMotionEngine(removed, {now: () => clock, requestFrame}); removed.remove(); const kept = document.createElement('div'); document.body.append(kept); - createMotionAnimator(kept, {now: () => clock, requestFrame}); + createMotionEngine(kept, {now: () => clock, requestFrame}); await vi.advanceTimersByTimeAsync(0); expect(readsOf(removed)).toBe(0); // A node still in the document is read, once, in that task. @@ -2089,7 +2089,7 @@ describe('promotion: a compositing layer while it moves', () => { stylesheet['will-change'] = 'transform, opacity'; stubMedia(false, false); const element = document.createElement('div'); - const animator = createMotionAnimator(element, { + const animator = createMotionEngine(element, { now: () => clock, requestFrame, }); @@ -2834,7 +2834,7 @@ describe('Reduced Motion (design:reduced-motion)', () => { it('a running dip survives any re-attach, so the move never passes in view', async () => { const halfway = async ( - animator: ReturnType, + animator: ReturnType, start: number, ): Promise => { // The plan lands by timer: step the clock to the landing. @@ -4171,7 +4171,7 @@ describe('pseudoElement: a dialog\u2019s ::backdrop', () => { describe('attach', () => { it('keeps state without an element and resumes the curve on attach', () => { - const animator = createMotionAnimator(null, { + const animator = createMotionEngine(null, { now: () => clock, }); animator.animate({x: 300}, {spring: springs.settle}); @@ -4262,7 +4262,7 @@ describe('attach', () => { it('writes nothing for channels at identity', () => { const element = document.createElement('div'); - createMotionAnimator(element); + createMotionEngine(element); expect(element.getAttribute('style')).toBeNull(); }); }); @@ -4367,7 +4367,7 @@ describe("a theme's reduced-motion mark", () => { const element = document.createElement('div'); theme.append(element); document.body.append(theme); - const animator = createMotionAnimator(element, { + const animator = createMotionEngine(element, { now: () => clock, requestFrame, }); diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.ts index d9af6ca317e06..ba5ec8421a5f8 100644 --- a/packages/core/src/motion/animator.ts +++ b/packages/core/src/motion/animator.ts @@ -4,7 +4,7 @@ * @file animator.ts * @input An element, target values, and a spring, momentum curves (coast.ts) * or any closed-form curve - * @output Exports `createMotionAnimator`, a compositor animator for + * @output Exports `createMotionEngine`, a compositor animator for * translate, rotate, scale and opacity, and its option, handle and * transition types. It reads presentation values and velocities from the * analytic curves. It retargets with the velocity kept, freezes in place on @@ -299,9 +299,6 @@ export interface MotionCurve { readonly isTransition?: boolean; } -/** - * Options of `createMotionAnimator`. - */ /** How `set` puts values in place. */ export interface SetOptions { /** @@ -317,6 +314,9 @@ export interface SetOptions { promote?: boolean; } +/** + * Options of `createMotionEngine`. + */ export interface AnimatorOptions { /** * Animates a pseudo-element of the element instead (`'::backdrop'` of a @@ -811,7 +811,7 @@ export function animatorFor( const key = options.pseudoElement ?? ''; let animator = byPseudo.get(key); if (animator == null) { - animator = createMotionAnimator(element, options); + animator = createMotionEngine(element, options); byPseudo.set(key, animator); } return animator; @@ -928,7 +928,7 @@ const REDUCED_TRANSITION: SpringTransition = { * * @example * ``` - * const animator = createMotionAnimator(sheet); + * const animator = createMotionEngine(sheet); * // finger lifts at 1200 px/s heading for the detent at 0 (a component * // passes the spring of its motion role): * animator.animate({y: 0}, {spring: {response: 0.45, dampingRatio: 0.9}, velocity: {y: 1200}}); @@ -937,7 +937,7 @@ const REDUCED_TRANSITION: SpringTransition = { * animator.stop(['y']); * ``` */ -export function createMotionAnimator( +export function createMotionEngine( element: HTMLElement | null, options: AnimatorOptions = {}, ): Animator { diff --git a/packages/core/src/motion/resolveMotion.test.ts b/packages/core/src/motion/resolveMotion.test.ts index cf5a3067619ce..3045170905ac6 100644 --- a/packages/core/src/motion/resolveMotion.test.ts +++ b/packages/core/src/motion/resolveMotion.test.ts @@ -12,7 +12,7 @@ */ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; -import {createMotionAnimator} from './animator'; +import {createMotionEngine} from './animator'; import {coast} from './coast'; import {resolveMotion} from './resolveMotion'; import {solveSpring, toSpring} from './spring'; @@ -93,7 +93,7 @@ describe('resolveMotion while the per-role tables stay internal (DEC-15)', () => describe('the animator', () => { it("plays the table's spring even where a scope sets the role's variable", () => { const child = scoped({'--motion-springs-settle': '0.8s 0.3'}); - const animator = createMotionAnimator(child, {now: () => 0}); + const animator = createMotionEngine(child, {now: () => 0}); animator.set({y: 300}); animator.animate({y: 0}, {spring: springs.settle}, {at: 0}); const table = solveSpring(toSpring(springs.settle), {from: 300, to: 0}); @@ -104,7 +104,7 @@ describe('the animator', () => { }); it('a coast plays the table edge spring whatever a scope sets: scroll.bounce is no role', () => { const child = scoped({'--motion-scroll-bounce': '0.8s 0.3'}); - const animator = createMotionAnimator(child, {now: () => 0}); + const animator = createMotionEngine(child, {now: () => 0}); animator.set({x: 60}); // Released past the edge: straight back on the edge spring. animator.decay( diff --git a/packages/lab/src/RefreshControl/refreshTouchController.ts b/packages/lab/src/RefreshControl/refreshTouchController.ts index 9fd8d2cd703b1..e4f66cb91e0c5 100644 --- a/packages/lab/src/RefreshControl/refreshTouchController.ts +++ b/packages/lab/src/RefreshControl/refreshTouchController.ts @@ -55,7 +55,7 @@ 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 {useMotionEngine} from '../internal/useMotionEngine'; import { RefreshPullRecognizer, RefreshScrollPullRecognizer, @@ -186,8 +186,8 @@ export function useRefreshTouchController({ (event: RefreshEvent) => dispatchRef.current(event), [dispatchRef], ); - const content = useMotionAnimator(); - const indicator = useMotionAnimator(); + const content = useMotionEngine(); + const indicator = useMotionEngine(); const contentElement = useRef(null); const indicatorElement = useRef(null); // Whether the content holds the refreshing inset. diff --git a/packages/lab/src/RefreshControl/useMotionAnimator.ts b/packages/lab/src/RefreshControl/useMotionAnimator.ts deleted file mode 100644 index 697641a6e32fc..0000000000000 --- a/packages/lab/src/RefreshControl/useMotionAnimator.ts +++ /dev/null @@ -1,35 +0,0 @@ -// 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 index 062d8d7f25a7a..15695a6a7c4b7 100644 --- a/packages/lab/src/RefreshControl/useRefreshControl.test.tsx +++ b/packages/lab/src/RefreshControl/useRefreshControl.test.tsx @@ -17,10 +17,11 @@ import {act, render, screen, waitFor} from '@testing-library/react'; import { GestureRecognizer, PanGestureRecognizer, - type MotionAnimator, type MotionCurve, + type MotionEngine, } from '@astryxdesign/core/internal/touch'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import type * as MotionEngineModule from '../internal/useMotionEngine'; import {revealProgress} from './refreshPull'; import { useRefreshControl, @@ -30,14 +31,14 @@ import { // 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(); +vi.mock('../internal/useMotionEngine', async importOriginal => { + const real = await importOriginal(); return { ...real, - useMotionAnimator: ( - ...args: Parameters - ): ReturnType => { - const result = real.useMotionAnimator(...args); + useMotionEngine: ( + ...args: Parameters + ): ReturnType => { + const result = real.useMotionEngine(...args); if (!animators.list.includes(result.animator)) { animators.list.push(result.animator); } @@ -54,7 +55,7 @@ vi.mock('./useMotionAnimator', async importOriginal => { function watchFade(settleCurve: () => MotionCurve | null) { const [contentAnimator, indicatorAnimator] = animators.list.slice( -2, - ) as MotionAnimator[]; + ) as MotionEngine[]; let finishSettle: (done: boolean) => void = () => {}; const animate = contentAnimator.animate.bind(contentAnimator); vi.spyOn(contentAnimator, 'animate').mockImplementation( @@ -504,14 +505,14 @@ describe('useRefreshControl', () => {

Inbox

, ); - const [, indicatorAnimator] = animators.list.slice(-2) as MotionAnimator[]; + const [, indicatorAnimator] = animators.list.slice(-2) as MotionEngine[]; 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'] + MotionEngine['play'] >; const shown = Number(reveal()); expect(shown).toBeGreaterThan(0); @@ -1263,7 +1264,7 @@ describe('useRefreshControl', () => { ); const [contentAnimator, indicatorAnimator] = animators.list.slice( -2, - ) as MotionAnimator[]; + ) as MotionEngine[]; const contentAnimate = vi.spyOn(contentAnimator, 'animate'); const indicatorAnimate = vi.spyOn(indicatorAnimator, 'animate'); scrollVelocity.mockClear(); diff --git a/packages/lab/src/internal/useMotionEngine.test.tsx b/packages/lab/src/internal/useMotionEngine.test.tsx new file mode 100644 index 0000000000000..73b76673ab298 --- /dev/null +++ b/packages/lab/src/internal/useMotionEngine.test.tsx @@ -0,0 +1,108 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file useMotionEngine.test.tsx + * @input vitest (jsdom), React Testing Library, the hook + * @output Checks that the animator is stable, attaches through the ref, and + * never re-renders its component while animating, retargeting or tracking + * @position Testing; validates useMotionEngine.ts + */ + +import {act, render} from '@testing-library/react'; +import {useEffect} from 'react'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import type {MotionEngine} from '@astryxdesign/core/internal/touch'; +import {useMotionEngine} from './useMotionEngine'; + +/** A critically damped half-second spring (SwiftUI's default). */ +const SETTLE = {duration: 0.5, bounce: 0} as const; +/** A stiff, heavy spring (UIKit's sheet presentation). */ +const SHEET = {mass: 3, stiffness: 1000, damping: 500} as const; + +beforeEach(() => { + HTMLElement.prototype.animate = function () { + return {startTime: null, cancel: vi.fn()} as unknown as Animation; + }; +}); + +afterEach(() => { + Reflect.deleteProperty(HTMLElement.prototype, 'animate'); +}); + +/** A component that hands its animator out, for the unmount test. */ +function UnmountProbe({box}: {box: {current: MotionEngine | null}}) { + const {ref, animator} = useMotionEngine(); + box.current = animator; + return
; +} + +describe('useMotionEngine', () => { + it('keeps one animator and ref, and never re-renders while animating', () => { + let renders = 0; + const seen = new Set(); + const refs = new Set(); + let api: MotionEngine | null = null; + function Probe() { + renders++; + const {ref, animator} = useMotionEngine(); + seen.add(animator); + refs.add(ref); + useEffect(() => { + api = animator; + }); + return
; + } + const {rerender, getByTestId} = render(); + const before = renders; + act(() => { + api?.animate({x: 100}, {spring: SETTLE}); + for (let x = 0; x < 50; x++) { + api?.set({y: x}); + } + api?.animate({x: 10}, {spring: SETTLE}); + api?.stop(); + }); + expect(renders).toBe(before); + expect(getByTestId('probe').style.translate).not.toBe(''); + rerender(); + expect(seen.size).toBe(1); + expect(refs.size).toBe(1); + }); + + it('attaches on mount and detaches on unmount', () => { + const box: {current: MotionEngine | null} = {current: null}; + function Probe() { + const {ref, animator} = useMotionEngine({initial: {opacity: 0.5}}); + box.current = animator; + return
; + } + const {getByTestId, unmount} = render(); + const element = getByTestId('probe'); + expect(box.current?.element).toBe(element); + expect(element.style.opacity).toBe('0.5'); + unmount(); + expect(box.current?.element).toBeNull(); + }); + + it('ends its callers waits on unmount and keeps no timer for them', async () => { + vi.useFakeTimers(); + try { + const box: {current: MotionEngine | null} = {current: null}; + const {unmount} = render(); + const animator = box.current!; + const handle = animator.animate({x: 100}, {spring: SHEET}); + let rested = false; + void animator.atRest().then(() => { + rested = true; + }); + expect(vi.getTimerCount()).toBeGreaterThan(0); + unmount(); + // Without advancing time: the curve has not ended. + await expect(handle.finished).resolves.toBe(false); + expect(rested).toBe(true); + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/packages/lab/src/internal/useMotionEngine.ts b/packages/lab/src/internal/useMotionEngine.ts new file mode 100644 index 0000000000000..5f0e9c7f00049 --- /dev/null +++ b/packages/lab/src/internal/useMotionEngine.ts @@ -0,0 +1,54 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useMotionEngine.ts + * @input React and Core's motion engine (`createMotionEngine`) + * @output useMotionEngine: a stable motion engine and the callback ref that + * attaches it to an element + * @position Lab's React binding of Core's motion engine, for Lab components. + * Lab's entry point does not export it. + * + * SYNC: When modified, update useMotionEngine.test.tsx + */ + +import {useState} from 'react'; +import { + createMotionEngine, + type MotionEngine, + type MotionEngineOptions, +} from '@astryxdesign/core/internal/touch'; + +export interface UseMotionEngineResult { + /** Callback ref for the animated element; stable. */ + readonly ref: (element: HTMLElement | null) => void; + /** The animator; stable for the component's lifetime. */ + readonly animator: MotionEngine; +} + +/** + * A compositor animator bound to an element through a callback ref. The + * animator never sets state, so a move never re-renders the component. When + * the element unmounts, the ref detaches the animator: its moves stop and its + * values stay, so a remount resumes from them. `options` are read on the + * first render only. + * + * @example + * ``` + * const {ref, animator} = useMotionEngine(); + * // `spring` is the motion role for this move, or the component's own + * // measured spring. + * const open = () => animator.animate({y: 0}, {spring}); + * return
; + * ``` + */ +export function useMotionEngine( + options?: MotionEngineOptions, +): UseMotionEngineResult { + const [result] = useState(() => { + const animator = createMotionEngine(null, options); + return {animator, ref: element => animator.attach(element)}; + }); + return result; +} diff --git a/scripts/motion-node-load.test.mjs b/scripts/motion-node-load.test.mjs index 093ea9eab1682..14fb54553f22f 100644 --- a/scripts/motion-node-load.test.mjs +++ b/scripts/motion-node-load.test.mjs @@ -28,7 +28,7 @@ const coreSrc = path.join(root, 'packages/core/src'); * the press paint's styles). */ const ENTRY = ` -export {createMotionAnimator, animatorFor, SETTLE_THRESHOLD} from './motion/animator'; +export {createMotionEngine, animatorFor, SETTLE_THRESHOLD} from './motion/animator'; export {reducedMotionFade} from './motion/reducedMotion'; export {resolveMotion} from './motion/resolveMotion'; export {solveSpring, toSpring} from './motion/spring'; @@ -105,10 +105,10 @@ describe('the touch motion foundation in plain Node', () => { '-e', `const m = await import(${JSON.stringify(pathToFileURL(file).href)}); m.registerSpringsTable(); - const animator = m.createMotionAnimator(null); + const animator = m.createMotionEngine(null); const pan = new m.PanGestureRecognizer({}); console.log(JSON.stringify({ - createMotionAnimator: typeof m.createMotionAnimator, + createMotionEngine: typeof m.createMotionEngine, set: typeof animator.set, sheet: m.springs.sheetPresent != null, pan: typeof pan.state, @@ -117,7 +117,7 @@ describe('the touch motion foundation in plain Node', () => { {encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']}, ); expect(JSON.parse(out.trim().split('\n').at(-1))).toEqual({ - createMotionAnimator: 'function', + createMotionEngine: 'function', set: 'function', sheet: true, pan: 'string', diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs index 76ebf5bc5b09f..83963a726938b 100644 --- a/scripts/touch-support-bundle.test.mjs +++ b/scripts/touch-support-bundle.test.mjs @@ -110,14 +110,16 @@ function exportsOf(entry) { } /** - * 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. + * What the internal entry gives Lab components, none of it public API. Lab's + * refresh pull reads the pan, its hook, the motion engine, its motion math and + * companion curves, the scroll view's spring and the motion-role parsers. + * Other Lab components read the UIKit gesture table, the touch presentation + * and its query, and an element's direction. */ const LAB_ONLY_NAMES = [ 'PanGestureRecognizer', 'useGestureRecognizer', - 'createMotionAnimator', + 'createMotionEngine', 'cubicBezier', 'mapProgress', 'parseCssEasing', @@ -126,6 +128,10 @@ const LAB_ONLY_NAMES = [ 'rubberBandInverse', 'rubberBandSlope', 'scroll', + 'isRtlElement', + 'UIKIT_GESTURES', + 'useTouchPresentation', + 'TOUCH_QUERY', ]; /** The inputs matching `pattern` that put bytes in `bytes`. */ From 7a64fbf5cb1c65d9ad2acbb11a526835880dba9f Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 17:04:34 -0800 Subject: [PATCH 2/5] chore(core): Core's internal touch entry re-exports the action-group tracking hook, extended for Lab's TabBar, and a tab-bar string joins the catalog Re-exports only on the entry: @astryxdesign/core/internal/touch adds useActionGroupTracking and its options type. So Lab's TabBar presses through the hook AlertDialog uses: a second finger ends the press with nothing acting, and focus follows the lift. The hook gains options for a group that draws its own highlight. All are optional, and without them the hook runs as before, so AlertDialog does not change. A no-paint option leaves the highlight to the group. Press callbacks report the action under the press as it begins and after each move, the lift before its action runs, and a cancel. Core's message catalog gains TabBar's badged-tab name. It lands ahead of the Lab component, so the Lab batch changes only Lab. The entry stays outside the public API: no docs, no root re-export, and the @astryx/no-core-internal-import rule keeps it to Core and Lab. --- .../core-internal-entries-lab-tabbar.md | 7 ++ packages/core/locales/en.json | 4 + .../src/hooks/useActionGroupTracking.test.tsx | 92 ++++++++++++++++++- .../core/src/hooks/useActionGroupTracking.ts | 31 ++++++- packages/core/src/internal/touch.test.ts | 12 +++ packages/core/src/internal/touch.ts | 4 + 6 files changed, 147 insertions(+), 3 deletions(-) create mode 100644 .changeset/core-internal-entries-lab-tabbar.md diff --git a/.changeset/core-internal-entries-lab-tabbar.md b/.changeset/core-internal-entries-lab-tabbar.md new file mode 100644 index 0000000000000..62d4eff726e36 --- /dev/null +++ b/.changeset/core-internal-entries-lab-tabbar.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: Core's internal touch entry re-exports the action-group tracking hook, which gains a no-paint option and press callbacks for Lab's TabBar. A tab-bar string joins Core's message catalog. Apps import nothing new. + +@vjeux diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json index a43e611e5a767..ac06706b0ede6 100644 --- a/packages/core/locales/en.json +++ b/packages/core/locales/en.json @@ -943,6 +943,10 @@ "defaultMessage": "Maximum value", "description": "Accessible name of the upper thumb of a range Slider (two thumbs), announced together with the Slider's own label, for example \"Price range, Maximum value, 80\". Never shown on screen." }, + "@astryx.tabBar.badgedItem": { + "defaultMessage": "{label}, {badge}", + "description": "Screen-reader name of a bottom tab bar item that shows a badge (\"Library, 3\"). {label} is the tab's visible name; {badge} is the badge's count or its own label (\"3 unread\"). Translators may reorder the two or change the separator." + }, "@astryx.tabList.label": { "defaultMessage": "Tabs", "description": "Screen-reader-only fallback name for a horizontal tab bar. Plural noun; \"Tabs\" here = UI tab panels, not browser tabs or the Tab key." diff --git a/packages/core/src/hooks/useActionGroupTracking.test.tsx b/packages/core/src/hooks/useActionGroupTracking.test.tsx index 05d4fe43201eb..922b110bb4f9d 100644 --- a/packages/core/src/hooks/useActionGroupTracking.test.tsx +++ b/packages/core/src/hooks/useActionGroupTracking.test.tsx @@ -12,7 +12,7 @@ * action is skipped; a second finger or the window losing focus cancels; * inside a scroller a flick is left to the scroller; a mouse under a fine * pointer is tracked like a finger; the shared tracker does the tracking; - * no render per move + * a caller's no-paint option and press callbacks; no render per move * @position jsdom tests of packages/core/src/hooks/useActionGroupTracking.ts */ @@ -313,6 +313,96 @@ describe('useActionGroupTracking', () => { expect(onDelete).not.toHaveBeenCalled(); }); + describe('a group that draws its own highlight (Lab TabBar)', () => { + const nameOf = (element: Element | null) => element?.textContent ?? 'none'; + + it('paints nothing with paintsHighlight off, and still runs the action it lifts on', () => { + const {cancel, del, onCancel} = mount({ + options: {paintsHighlight: false}, + }); + const f = finger(); + f.down(cancel, centerOf(CANCEL)); + expect(paintOf(cancel)).toBeNull(); + f.move(cancel, centerOf(DELETE)); + expect(paintOf(del)).toBeNull(); + f.move(cancel, centerOf(CANCEL)); + f.up(cancel, centerOf(CANCEL)); + expect(paintOf(cancel)).toBeNull(); + expect(onCancel).toHaveBeenCalledTimes(1); + }); + + it('reports the press around the tracker: the action at the begin and after each move, then the lift before its action runs', () => { + const log: string[] = []; + const {cancel} = mount({ + options: { + onPressBegin: (_x, _y, action) => log.push(`begin ${nameOf(action)}`), + onPressMove: (_x, _y, action) => log.push(`move ${nameOf(action)}`), + onPressEnd: action => log.push(`end ${nameOf(action)}`), + onPressCancel: () => log.push('cancel'), + onActivate: action => log.push(`activate ${nameOf(action)}`), + }, + }); + const f = finger(); + f.down(cancel, centerOf(CANCEL)); + f.move(cancel, {x: 104, y: 124}); + f.move(cancel, centerOf(DELETE)); + f.up(cancel, centerOf(DELETE)); + expect(log).toEqual([ + 'begin Cancel', + 'move none', + 'move Delete', + 'end Delete', + 'activate Delete', + ]); + }); + + it('reports a press that a second finger ends as a cancel, and runs nothing (family:action-groups FR3)', () => { + const log: string[] = []; + const {cancel, del} = mount({ + options: { + onPressBegin: (_x, _y, action) => log.push(`begin ${nameOf(action)}`), + onPressEnd: () => log.push('end'), + onPressCancel: () => log.push('cancel'), + onActivate: () => log.push('activate'), + }, + }); + const first = {id: nextTouchId++, ...centerOf(CANCEL)}; + const second = {id: nextTouchId++, ...centerOf(DELETE)}; + time += 1000; + touch('touchstart', cancel, first, time); + time += 30; + touch('touchstart', del, second, time, [first]); + time += 16; + touch('touchend', del, second, time, [first]); + time += 16; + touch('touchend', cancel, first, time); + expect(log).toEqual(['begin Cancel', 'cancel']); + }); + + it('reports a press that turning tracking off ends as a cancel, and runs nothing', () => { + const log: string[] = []; + const options: Partial = { + paintsHighlight: false, + onPressBegin: (_x, _y, action) => log.push(`begin ${nameOf(action)}`), + onPressEnd: () => log.push('end'), + onPressCancel: () => log.push('cancel'), + onActivate: () => log.push('activate'), + }; + const view = mount({options}); + const f = finger(); + f.down(view.cancel, centerOf(CANCEL)); + view.rerender( + , + ); + f.up(view.cancel, centerOf(CANCEL)); + expect(log).toEqual(['begin Cancel', 'cancel']); + }); + }); + it('ends the gesture with nothing acting when the window loses focus (family:action-groups FR3)', () => { const {cancel, onCancel} = mount(); const f = finger(); diff --git a/packages/core/src/hooks/useActionGroupTracking.ts b/packages/core/src/hooks/useActionGroupTracking.ts index fb07c7221a9e8..a6525e9fa8a9d 100644 --- a/packages/core/src/hooks/useActionGroupTracking.ts +++ b/packages/core/src/hooks/useActionGroupTracking.ts @@ -9,7 +9,8 @@ * @output Exports useActionGroupTracking and ActionGroupTrackingOptions * @position Internal hook, not exported from the hooks entry. A long press * drives the shared action-group tracker (hooks/actionGroupTracker.ts) for - * a group that a held pointer slides across. AlertDialog consumes it. + * a group that a held pointer slides across. AlertDialog consumes it, and + * Lab components through the internal touch entry. * * SYNC: When modified, update useActionGroupTracking.test.tsx */ @@ -49,6 +50,22 @@ export interface ActionGroupTrackingOptions { manageStyle?: boolean; /** Runs the action under the finger at the lift. @default its own click */ onActivate?: (item: HTMLElement) => void; + /** + * Paint the tracked action with the press attribute. Off, the group draws + * its own highlight. @default true + */ + paintsHighlight?: boolean; + /** A press began at viewport (x, y) on `action` (null: none). */ + onPressBegin?: (x: number, y: number, action: HTMLElement | null) => void; + /** The press moved to viewport (x, y), now on `action` (null: none). */ + onPressMove?: (x: number, y: number, action: HTMLElement | null) => void; + /** The lift, before its action runs, with the tracked action (null: none). */ + onPressEnd?: (action: HTMLElement | null) => void; + /** + * The press ended with nothing acting: a cancel, a second finger, or + * tracking turned off. + */ + onPressCancel?: () => void; } const PRESS = UIKIT_PRESS; @@ -98,6 +115,7 @@ export function useActionGroupTracking( pointerRef.current === 'touch' ? optionsRef.current.highlightExpansion : 0, + paintsHighlight: optionsRef.current.paintsHighlight, onActivate: optionsRef.current.onActivate, // The browser's own click for a press the group ran is taken, so the // action runs once. The gesture host swallows it for a press it claims. @@ -109,11 +127,16 @@ export function useActionGroupTracking( // Synchronizes the tracker with tracking on and mounted. Turning tracking // off, or unmounting, drops a tracked press and ends its release fades. // The host reports no cancellation to a disabled recognizer, and the lift - // that runs an action often closes the owner before its fade ends. + // that runs an action often closes the owner before its fade ends. The + // group hears the dropped press as a cancel, so its own highlight goes out. useEffect( () => () => { + const wasTracking = tracker.isTracking; tracker.cancel(); tracker.dispose(); + if (wasTracking) { + optionsRef.current.onPressCancel?.(); + } }, [tracker, isEnabled], ); @@ -146,14 +169,17 @@ export function useActionGroupTracking( case 'began': { const {x, y} = recognizer.location(); tracker.begin(x, y, {landed: landedRef.current}); + optionsRef.current.onPressBegin?.(x, y, tracker.highlighted); break; } case 'changed': { const {x, y} = recognizer.location(); tracker.move(x, y); + optionsRef.current.onPressMove?.(x, y, tracker.highlighted); break; } case 'ended': { + optionsRef.current.onPressEnd?.(tracker.highlighted); const doc = ref.current?.ownerDocument; const focusedBefore = doc?.activeElement ?? null; const beganOn = tracker.beganOn; @@ -182,6 +208,7 @@ export function useActionGroupTracking( } case 'cancelled': tracker.cancel(); + optionsRef.current.onPressCancel?.(); break; case 'possible': case 'failed': diff --git a/packages/core/src/internal/touch.test.ts b/packages/core/src/internal/touch.test.ts index 02e63f68e064a..8faad12221ebd 100644 --- a/packages/core/src/internal/touch.test.ts +++ b/packages/core/src/internal/touch.test.ts @@ -84,6 +84,18 @@ describe('internal/touch', () => { } }); + it('re-exports the action-group tracking hook by name', async () => { + const entry: Record = await import('./touch'); + // Identity alone passes when both sides are undefined. + expect(typeof entry.useActionGroupTracking).toBe('function'); + const modules: Record> = { + useActionGroupTracking: await import('../hooks/useActionGroupTracking'), + }; + for (const [name, module] of Object.entries(modules)) { + expect(entry[name], name).toBe(module[name]); + } + }); + 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 c46d3d5a8342e..ff151380c618e 100644 --- a/packages/core/src/internal/touch.ts +++ b/packages/core/src/internal/touch.ts @@ -80,3 +80,7 @@ export {isRtlElement} from '../hooks/isRtlElement'; export {UIKIT_GESTURES} from '../motion/uikit/gestures'; export {useTouchPresentation} from '../utils/touchPresentation'; export {TOUCH_QUERY} from '../utils/touchQueries'; + +// Lab's TabBar tracks its press with the shared action-group tracker. +export {useActionGroupTracking} from '../hooks/useActionGroupTracking'; +export type {ActionGroupTrackingOptions} from '../hooks/useActionGroupTracking'; From 0b6f57fc8f46cb3168bd89abc12d758c22ebac48 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 17:28:38 -0800 Subject: [PATCH 3/5] feat(lab): TabBar, iOS 26's floating tab bar, with its selection lens and press tracking TabBar shows an app's top-level sections as iOS 26's floating capsule above the bottom edge, with a selection lens that slides to the chosen tab. Each TabBarItem has an icon, a label and an optional badge. Under a finger, on iOS and Android alike, the lens moves on the springs measured from UIKit on iOS 26.2: it lifts into glass as a finger lands, follows a finger dragged across the tabs and settles on the tab nearest the lift, while the bar flexes. A pen in the touch presentation does the same. Under a fine pointer a press is a plain button press: a click chooses a tab and the lens follows the theme's motion. Sliding off the bar cancels: a press lifted off it chooses nothing. Choosing the selected tab again is reported apart, so a screen can return to its root. Core's action-group tracking owns the press, in the touch presentation only: the tab under it, running that tab at the lift, a second finger's cancel and focus after the lift. TabBar draws the lens. With no tab selected there is no lens, so a held finger paints the tab under it. A tab names the panel it controls through panelId, rendered as aria-controls. TabBar's UIKit values live beside it in uikitTabBar.ts, each with its source, and uikitTabBar.test.ts checks that every value names one. Core's gesture and motion pieces come through Core's internal touch entry. --- .changeset/cli-discover-tab-bar.md | 7 + apps/storybook/stories/TabBar.stories.tsx | 296 +++ internal/shadcn-registry/routes.lock.json | 10 + .../assets/discover/official-packages.json | 8 + packages/lab/src/TabBar/TabBar.doc.mjs | 142 ++ packages/lab/src/TabBar/TabBar.test.tsx | 340 +++ packages/lab/src/TabBar/TabBar.tsx | 720 ++++++ packages/lab/src/TabBar/TabBarTouch.ts | 16 + .../TabBar.interaction.browser.spec.ts | 2095 +++++++++++++++++ packages/lab/src/TabBar/index.ts | 13 + packages/lab/src/TabBar/tabBar.stylex.ts | 18 + packages/lab/src/TabBar/tabBarModel.test.ts | 202 ++ packages/lab/src/TabBar/tabBarModel.ts | 136 ++ packages/lab/src/TabBar/uikitTabBar.test.ts | 168 ++ packages/lab/src/TabBar/uikitTabBar.ts | 243 ++ packages/lab/src/TabBar/useTabBarLens.ts | 604 +++++ packages/lab/src/index.ts | 8 + 17 files changed, 5026 insertions(+) create mode 100644 .changeset/cli-discover-tab-bar.md create mode 100644 apps/storybook/stories/TabBar.stories.tsx create mode 100644 packages/lab/src/TabBar/TabBar.doc.mjs create mode 100644 packages/lab/src/TabBar/TabBar.test.tsx create mode 100644 packages/lab/src/TabBar/TabBar.tsx create mode 100644 packages/lab/src/TabBar/TabBarTouch.ts create mode 100644 packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts create mode 100644 packages/lab/src/TabBar/index.ts create mode 100644 packages/lab/src/TabBar/tabBar.stylex.ts create mode 100644 packages/lab/src/TabBar/tabBarModel.test.ts create mode 100644 packages/lab/src/TabBar/tabBarModel.ts create mode 100644 packages/lab/src/TabBar/uikitTabBar.test.ts create mode 100644 packages/lab/src/TabBar/uikitTabBar.ts create mode 100644 packages/lab/src/TabBar/useTabBarLens.ts diff --git a/.changeset/cli-discover-tab-bar.md b/.changeset/cli-discover-tab-bar.md new file mode 100644 index 0000000000000..367480325b146 --- /dev/null +++ b/.changeset/cli-discover-tab-bar.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/cli': patch +--- + +[experimental] `astryx discover` lists the experimental TabBar and TabBarItem components from `@astryxdesign/lab`. + +@vjeux diff --git a/apps/storybook/stories/TabBar.stories.tsx b/apps/storybook/stories/TabBar.stories.tsx new file mode 100644 index 0000000000000..b9ee247e579a9 --- /dev/null +++ b/apps/storybook/stories/TabBar.stories.tsx @@ -0,0 +1,296 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +import {useEffect, useState} from 'react'; +import {flushSync} from 'react-dom'; +import type {Meta, StoryObj} from '@storybook/react'; +import { + BookOpenIcon as BookOpenOutline, + HomeIcon as HomeOutline, + Squares2X2Icon as GridOutline, + UserCircleIcon as UserOutline, + BellIcon as BellOutline, +} from '@heroicons/react/24/outline'; +import { + BookOpenIcon as BookOpenSolid, + HomeIcon as HomeSolid, + Squares2X2Icon as GridSolid, + UserCircleIcon as UserSolid, + BellIcon as BellSolid, +} from '@heroicons/react/24/solid'; +import {TabBar, TabBarItem} from '@astryxdesign/lab'; +import {Button} from '@astryxdesign/core/Button'; +import {LayerProvider} from '@astryxdesign/core/Layer'; +import {Icon, type IconType} from '@astryxdesign/core/Icon'; + +// ============================================================================= +// Meta +// ============================================================================= + +const meta: Meta = { + // The bar floats over the bottom edge: declared on LayerProvider, menus, + // popovers and toasts clear it. + decorators: [ + Story => ( + + + + ), + ], + title: 'Lab/TabBar', + component: TabBar, + parameters: { + layout: 'fullscreen', + }, +}; + +export default meta; +type Story = StoryObj; + +// ============================================================================= +// The sections UIKit's own captures were taken with: four tabs over long +// scrolling screens +// ============================================================================= + +interface Section { + value: string; + label: string; + icon: IconType; + selectedIcon: IconType; +} + +const SECTIONS: Section[] = [ + {value: 'home', label: 'Home', icon: HomeOutline, selectedIcon: HomeSolid}, + { + value: 'library', + label: 'Library', + icon: BookOpenOutline, + selectedIcon: BookOpenSolid, + }, + { + value: 'browse', + label: 'Browse', + icon: GridOutline, + selectedIcon: GridSolid, + }, + { + value: 'profile', + label: 'Profile', + icon: UserOutline, + selectedIcon: UserSolid, + }, +]; + +const INBOX: Section = { + value: 'inbox', + label: 'Inbox', + icon: BellOutline, + selectedIcon: BellSolid, +}; + +/** A screen long enough to scroll under the bar. */ +function Screen({title, reselects}: {title: string; reselects: number}) { + return ( +
+

+ {title || 'No tab selected'} +

+

Reselected {reselects} times

+ {Array.from({length: 40}, (_, i) => ( +

+ {title} row {i + 1} +

+ ))} +
+ ); +} + +function Bar({ + sections = SECTIONS, + initial = 'home', + badges = {library: 3}, + keeps = [], + onChange, +}: { + sections?: Section[]; + initial?: string; + badges?: Record; + /** Tabs the app declines to switch to (it keeps the selection). */ + keeps?: string[]; + /** Also told of every choice. */ + onChange?: (value: string) => void; +}) { + const [value, setValue] = useState(initial); + const [reselects, setReselects] = useState(0); + const title = sections.find(section => section.value === value)?.label ?? ''; + return ( + <> + + { + onChange?.(next); + if (!keeps.includes(next)) { + setValue(next); + } + }} + onReselect={() => setReselects(n => n + 1)} + label="Sections" + data-testid="tab-bar"> + {sections.map(section => ( + } + selectedIcon={} + badge={badges[section.value]} + /> + ))} + + + ); +} + +/** Four tabs, a badge on Library. Choosing Home again counts a reselect. */ +export const Default: Story = { + render: () => , +}; + +/** Badges appear, change and disappear at once, as UIKit's do. */ +function BadgesDemo() { + const [count, setCount] = useState(0); + const badge = count === 0 ? undefined : count > 99 ? '99+' : count; + return ( + <> +
+
+ + + ); +} + +function TabBarHost({badges}: {badges: Record}) { + const [value, setValue] = useState('home'); + return ( + + {[SECTIONS[0], INBOX, SECTIONS[2], SECTIONS[3]].map(section => ( + } + selectedIcon={} + badge={badges[section.value]} + badgeLabel={ + section.value === 'inbox' && badges.inbox !== '' + ? `${badges.inbox} unread` + : undefined + } + /> + ))} + + ); +} + +/** + * The app keeps the selection when Profile is chosen (say it needs a + * sign-in first): the lens settles back onto the selected tab. + */ +export const KeepsSelection: Story = { + render: () => , +}; + +/** No tab selected (the value matches none): a tap chooses one. */ +export const NoSelection: Story = { + render: () => , +}; + +/** + * The app removes the bar as a finger lifts: the lift reports nothing (each + * choice would be listed on `window.__tabBarChanges`). + */ +function RemovedOnLiftDemo() { + const [isShown, setIsShown] = useState(true); + useEffect(() => { + const hide = () => { + const log = window as unknown as {__tabBarChanges?: string[]}; + log.__tabBarChanges = [...(log.__tabBarChanges ?? []), '(removed)']; + flushSync(() => setIsShown(false)); + }; + window.addEventListener('touchend', hide); + return () => window.removeEventListener('touchend', hide); + }, []); + return isShown ? ( + { + const log = window as unknown as {__tabBarChanges?: string[]}; + log.__tabBarChanges = [...(log.__tabBarChanges ?? []), value]; + }} + /> + ) : ( +

Removed

+ ); +} + +export const RemovedOnLift: Story = { + render: () => , +}; + +/** + * The app drops its last tab on the window event `tabbar:drop-last`, sent while + * a finger holds the bar. The press ends without choosing a tab (each choice + * would be listed on `window.__tabBarChanges`). + */ +function DropsLastTabDemo() { + const [sections, setSections] = useState(SECTIONS); + useEffect(() => { + const drop = () => setSections(current => current.slice(0, -1)); + window.addEventListener('tabbar:drop-last', drop); + return () => window.removeEventListener('tabbar:drop-last', drop); + }, []); + return ( + { + const log = window as unknown as {__tabBarChanges?: string[]}; + log.__tabBarChanges = [...(log.__tabBarChanges ?? []), value]; + }} + /> + ); +} + +export const DropsLastTab: Story = { + render: () => , +}; + +export const Badges: Story = { + render: () => , +}; + +/** Five tabs: the items overlap more, as they do on iOS. */ +export const FiveTabs: Story = { + render: () => ( + + ), +}; + +/** Three tabs: the capsule narrows to its natural width and centres. */ +export const ThreeTabs: Story = { + render: () => , +}; + +/** Right to left: the first tab sits on the right and the badge on the icon's top-left. */ +export const RightToLeft: Story = { + render: () => ( +
+ +
+ ), +}; diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json index 70936da26b23d..ffa763640b1d4 100644 --- a/internal/shadcn-registry/routes.lock.json +++ b/internal/shadcn-registry/routes.lock.json @@ -647,6 +647,16 @@ "path": "components/lab/svg-icon", "aliases": [] }, + { + "name": "component-lab-tab-bar", + "path": "components/lab/tab-bar", + "aliases": [] + }, + { + "name": "component-lab-tab-bar-item", + "path": "components/lab/tab-bar-item", + "aliases": [] + }, { "name": "component-lab-three-d-bar", "path": "components/lab/three-d-bar", diff --git a/packages/cli/assets/discover/official-packages.json b/packages/cli/assets/discover/official-packages.json index 3a1276fa7dd9a..a34967bfa30ac 100644 --- a/packages/cli/assets/discover/official-packages.json +++ b/packages/cli/assets/discover/official-packages.json @@ -164,6 +164,14 @@ "kind": "component", "name": "SVGIcon" }, + { + "kind": "component", + "name": "TabBar" + }, + { + "kind": "component", + "name": "TabBarItem" + }, { "kind": "component", "name": "ThreeDBar" diff --git a/packages/lab/src/TabBar/TabBar.doc.mjs b/packages/lab/src/TabBar/TabBar.doc.mjs new file mode 100644 index 0000000000000..4d62a7129b369 --- /dev/null +++ b/packages/lab/src/TabBar/TabBar.doc.mjs @@ -0,0 +1,142 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */ + +export const docs = { + name: 'TabBar', + displayName: 'Tab Bar', + category: 'Navigation', + keywords: [ + 'tabbar', + 'tab bar', + 'bottom tabs', + 'bottom navigation', + 'bottom bar', + 'tab bar controller', + 'mobile navigation', + 'app sections', + 'badge', + ], + description: + "The bottom tab bar of a phone app, as on iOS 26: the app's top-level sections as a floating capsule above the bottom edge, with a selection lens that slides to the chosen tab. Each tab has an icon, a label and an optional badge. Under a finger, on iOS and Android alike, it behaves like iOS 26's: the lens lifts into glass as a finger lands, follows a finger dragged across the tabs and settles on the tab nearest where it lifts, while the bar flexes; under a mouse, a press is a plain button press: a click chooses a tab and the lens follows the theme's motion. With no tab selected, a held finger highlights the tab under it. Choosing the selected tab again is reported separately, so a screen can return to its root as iOS does. Experimental: lands in lab first.", + components: [ + { + name: 'TabBar', + displayName: 'Tab Bar', + description: + "The bar. It sits fixed at the bottom of the viewport, over the page, so leave 83 px of room at the bottom of the scrolling content, and declare it on LayerProvider (inset={{blockEnd: 83}}) so menus, popovers and toasts clear it. You own the selection: pass the selected tab's value and update it in onChange.", + props: [ + { + name: 'value', + type: 'string', + description: "The selected tab's value.", + required: true, + }, + { + name: 'onChange', + type: '(value: string) => void', + description: + "Called with a tab's value when a different tab is chosen: a finger lifted over it (after a tap or a drag across the bar), a click, or Enter or Space on a focused tab.", + required: true, + }, + { + name: 'onReselect', + type: '(value: string) => void', + description: + "Called with the selected tab's value when it is chosen again, for example to return the tab's navigation stack to its root, as iOS does.", + }, + { + name: 'label', + type: 'string', + description: + 'Names the tab bar for assistive technology. Without it, or aria-label or aria-labelledby (which win over it and reach the tab list), the tab list is named "Tabs" in the reader\'s language.', + }, + { + name: 'children', + type: 'ReactNode', + description: + 'The tabs: TabBarItem elements, in order, as direct children.', + required: true, + }, + ], + }, + { + name: 'TabBarItem', + displayName: 'Tab Bar Item', + description: + 'One tab: its value, label, icon and badge. TabBar reads its props and draws it; it renders nothing on its own.', + props: [ + { + name: 'value', + type: 'string', + description: 'Identifies the tab in value, onChange and onReselect.', + required: true, + }, + { + name: 'label', + type: 'string', + description: + "The tab's name, shown under its icon. Keep it to one short word.", + required: true, + }, + { + name: 'icon', + type: 'ReactNode', + description: + "The tab's icon, an Icon at size lg. It is drawn in the current text colour, and in the accent colour while selected.", + required: true, + }, + { + name: 'selectedIcon', + type: 'ReactNode', + description: + 'The icon while the tab is selected, typically its filled variant. Defaults to icon.', + }, + { + name: 'badge', + type: 'string | number', + description: + 'A badge over the icon\'s top-trailing corner: a count or a short string such as "!". It appears, changes and disappears without animating. Omit it or pass an empty string for none.', + }, + { + name: 'badgeLabel', + type: 'string', + description: + 'What assistive technology reads for the badge after the tab\'s label, such as "3 unread". Defaults to the badge itself.', + }, + { + name: 'panelId', + type: 'string', + description: + "Id of the panel this tab controls, wired up as aria-controls. Put the same id on the section's panel element.", + }, + ], + }, + ], + usage: { + description: + "Use TabBar to switch between an app's three to five top-level sections on a phone, each keeping its own state and navigation stack. Keep each section's navigation stack in the app and return it to its root in onReselect.", + bestPractices: [ + { + guidance: true, + description: + 'Keep every tab visible and the set stable; give each a short label and an outline icon with a filled selectedIcon.', + }, + { + guidance: true, + description: + 'Use a badge for something that needs attention in that section, such as unread items, and say what it counts in badgeLabel.', + }, + { + guidance: true, + description: + "Give each tab a panelId naming its section's panel, so assistive technology can associate the two.", + }, + { + guidance: false, + description: + "Don't use it for actions, for filters within one screen (use SegmentedControl) or for tabs inside a page (use TabList).", + }, + ], + }, +}; diff --git a/packages/lab/src/TabBar/TabBar.test.tsx b/packages/lab/src/TabBar/TabBar.test.tsx new file mode 100644 index 0000000000000..9beaf3fbc66ef --- /dev/null +++ b/packages/lab/src/TabBar/TabBar.test.tsx @@ -0,0 +1,340 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TabBar.test.tsx + * @input vitest, @testing-library/react, TabBar and TabBarItem + * @output jsdom checks of the tab bar's semantics and state: the tablist and + * its keys, choosing and reselecting, badges, the lens at rest and theme + * classes. + * @position Testing; __tests__/TabBar.interaction.browser.spec.ts proves the + * motion in real engines + */ + +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {useState} from 'react'; +import {fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {InternationalizationProvider} from '@astryxdesign/core/i18n'; +import {TOUCH_QUERY} from '@astryxdesign/core/internal/touch'; +import {TabBar, TabBarItem, type TabBarProps} from './TabBar'; + +function Glyph({name}: {name: string}) { + return ; +} + +function Bar({ + initial = 'home', + onReselect, + onChange, + badges = {}, + ...props +}: Partial & { + initial?: string; + badges?: Record; +}) { + const [value, setValue] = useState(initial); + return ( + { + setValue(next); + onChange?.(next); + }} + onReselect={onReselect} + label="Sections" + data-testid="bar" + {...props}> + } /> + } + badge={badges.library} + /> + } + badge={badges.browse} + badgeLabel="New items" + /> + } + /> + + ); +} + +/** + * The primary pointer is coarse until the restore runs: a phone, as the touch + * presentation's gate reads it. Core's own test helper + * (gestures/__tests__/pointerQuery.ts) is out of Lab's reach: Lab's typecheck + * resolves Core through its dist. + */ +function coarsePrimaryPointer(): () => void { + const matchMedia = window.matchMedia; + const query = { + matches: true, + media: TOUCH_QUERY, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + } as unknown as MediaQueryList; + window.matchMedia = (media: string) => + media.trim() === TOUCH_QUERY ? query : matchMedia(media); + return () => { + window.matchMedia = matchMedia; + }; +} + +// The pointer a test models, put back after it. +const restorePointer: Array<() => void> = []; +afterEach(() => { + for (const restore of restorePointer.splice(0)) { + restore(); + } +}); + +describe('TabBar', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('names its tab list "Tabs" when it is given no name', () => { + render(); + expect(screen.getByRole('tablist', {name: 'Tabs'})).toBeInTheDocument(); + }); + + it('wires a tab to the panel it controls through panelId (aria-controls)', () => { + render( + {}}> + + + , + ); + const [home, library] = screen.getAllByRole('tab'); + expect(home).toHaveAttribute('aria-controls', 'home-panel'); + expect(library).not.toHaveAttribute('aria-controls'); + }); + + it('gives aria-label to the tab list, not the root', () => { + render(); + expect( + screen.getByRole('tablist', {name: 'Main sections'}), + ).toBeInTheDocument(); + expect(screen.getByTestId('bar')).not.toHaveAttribute('aria-label'); + }); + + it('names the tab list after the element aria-labelledby points at', () => { + render( + <> +

Sections heading

+ + , + ); + expect( + screen.getByRole('tablist', {name: 'Sections heading'}), + ).toBeInTheDocument(); + expect(screen.getByTestId('bar')).not.toHaveAttribute('aria-labelledby'); + }); + + it('is a named tablist of tabs with the selected one marked', () => { + render(); + const list = screen.getByRole('tablist', {name: 'Sections'}); + expect(list).toBeInTheDocument(); + const tabs = screen.getAllByRole('tab'); + expect(tabs.map(tab => tab.textContent)).toEqual([ + 'Home', + 'Library', + 'Browse', + 'Profile', + ]); + expect(screen.getByRole('tab', {name: 'Library'})).toHaveAttribute( + 'aria-selected', + 'true', + ); + expect(screen.getByRole('tab', {name: 'Home'})).toHaveAttribute( + 'aria-selected', + 'false', + ); + }); + + it('chooses another tab with onChange and moves the selection', () => { + const onChange = vi.fn(); + const onReselect = vi.fn(); + render(); + fireEvent.click(screen.getByRole('tab', {name: 'Browse'})); + expect(onChange).toHaveBeenCalledWith('browse'); + expect(onReselect).not.toHaveBeenCalled(); + expect(screen.getByRole('tab', {name: 'Browse'})).toHaveAttribute( + 'aria-selected', + 'true', + ); + }); + + it('reports choosing the selected tab again as a reselect, not a change', () => { + const onChange = vi.fn(); + const onReselect = vi.fn(); + render(); + fireEvent.click(screen.getByRole('tab', {name: 'Home'})); + expect(onReselect).toHaveBeenCalledWith('home'); + expect(onChange).not.toHaveBeenCalled(); + }); + + it('has one tab stop, on the selected tab, and arrow keys move between tabs', () => { + render(); + const tabs = screen.getAllByRole('tab'); + expect(tabs.map(tab => tab.tabIndex)).toEqual([-1, 0, -1, -1]); + tabs[1].focus(); + fireEvent.keyDown(tabs[1], {key: 'ArrowRight'}); + expect(document.activeElement).toBe(tabs[2]); + fireEvent.keyDown(tabs[2], {key: 'End'}); + expect(document.activeElement).toBe(tabs[3]); + fireEvent.keyDown(tabs[3], {key: 'Home'}); + expect(document.activeElement).toBe(tabs[0]); + // Moving focus does not choose a tab: Enter or Space does. + expect(tabs[1]).toHaveAttribute('aria-selected', 'true'); + }); + + it('names a badged tab with one catalog message, so a translation can reorder it', () => { + render( + + + , + ); + expect(screen.getByRole('tab', {name: '3 · Library'})).toBeInTheDocument(); + }); + + it('puts a badge in its tab’s name and draws it at once', () => { + const {rerender} = render(); + expect(screen.getByRole('tab', {name: 'Library, 3'})).toBeInTheDocument(); + const badge = () => + document.querySelector('[data-tab-bar-badge="library"]'); + expect(badge()).toHaveTextContent('3'); + // Changing or clearing the badge updates it in the same render. + rerender(); + expect(badge()).toHaveTextContent('12'); + expect(screen.getByRole('tab', {name: 'Library, 12'})).toBeInTheDocument(); + rerender(); + expect(badge()).toBeNull(); + expect(screen.getByRole('tab', {name: 'Library'})).toBeInTheDocument(); + }); + + it('reads a badge’s label instead of the badge when given one', () => { + render(); + expect( + screen.getByRole('tab', {name: 'Browse, New items'}), + ).toBeInTheDocument(); + }); + + it('keeps the badges and the lens out of the accessibility tree, and draws each item once at rest', () => { + render(); + const lens = document.querySelector('[data-tab-bar-lens]'); + expect(lens).toHaveAttribute('aria-hidden', 'true'); + const badge = document.querySelector('[data-tab-bar-badge="library"]'); + expect(badge?.closest('[aria-hidden="true"]')).not.toBeNull(); + // At rest the lens carries no copy of the items: each icon is drawn once. + expect(document.querySelector('[data-tab-bar-copy]')).toBeNull(); + expect(lens?.querySelectorAll('[data-testid^="icon-"]')).toHaveLength(0); + expect(document.querySelectorAll('[data-testid^="icon-"]')).toHaveLength(4); + }); + + it('draws the lens only while a tab is selected', () => { + const {rerender} = render( + {}}> + + + , + ); + expect(document.querySelector('[data-tab-bar-lens]')).toBeNull(); + // With nothing selected the first tab keeps the tab stop. + expect(screen.getAllByRole('tab').map(tab => tab.tabIndex)).toEqual([ + 0, -1, + ]); + rerender( + {}}> + + + , + ); + expect(document.querySelector('[data-tab-bar-lens]')).not.toBeNull(); + }); + + it('draws the selected icon on the selected tab itself when one is given', () => { + render( + {}}> + } + selectedIcon={} + /> + , + ); + const tab = screen.getByRole('tab', {name: 'A'}); + expect(tab.querySelector('[data-testid="icon-filled"]')).not.toBeNull(); + expect(tab.querySelector('[data-testid="icon-outline"]')).toBeNull(); + }); + + it('under a mouse never mounts a copy', () => { + render(); + fireEvent.click(screen.getByRole('tab', {name: 'Browse'})); + expect(screen.getByRole('tab', {name: 'Browse'})).toHaveAttribute( + 'aria-selected', + 'true', + ); + expect(document.querySelector('[data-tab-bar-copy]')).toBeNull(); + }); + + it('under a finger a slide mounts the copy only until the lens rests', async () => { + restorePointer.push(coarsePrimaryPointer()); + render(); + expect(document.querySelector('[data-tab-bar-copy]')).toBeNull(); + fireEvent.click(screen.getByRole('tab', {name: 'Browse'})); + // The slide's commit draws the selected look inside the lens… + expect(document.querySelector('[data-tab-bar-copy]')).not.toBeNull(); + // …and once it rests the tab draws it again and the copy goes. + await waitFor(() => + expect(document.querySelector('[data-tab-bar-copy]')).toBeNull(), + ); + expect( + screen + .getByRole('tab', {name: 'Browse'}) + .querySelector('[data-testid="icon-browse"]'), + ).not.toBeNull(); + }); + + it('carries the stable theme classes and the selected state', () => { + render(); + expect(screen.getByTestId('bar')).toHaveClass('astryx-tab-bar'); + const browse = screen.getByRole('tab', {name: 'Browse'}); + expect(browse).toHaveClass('astryx-tab-bar-item'); + expect(browse).toHaveAttribute('data-selected', 'selected'); + expect(screen.getByRole('tab', {name: 'Home'})).not.toHaveAttribute( + 'data-selected', + ); + }); + + it('ignores children that are not TabBarItem', () => { + render( + {}}> + + {null} + stray + , + ); + expect(screen.getAllByRole('tab')).toHaveLength(1); + expect(screen.queryByText('stray')).toBeNull(); + }); +}); diff --git a/packages/lab/src/TabBar/TabBar.tsx b/packages/lab/src/TabBar/TabBar.tsx new file mode 100644 index 0000000000000..2a5e847d754be --- /dev/null +++ b/packages/lab/src/TabBar/TabBar.tsx @@ -0,0 +1,720 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file TabBar.tsx + * @input React, StyleX, Core's theme tokens and hooks, TabBar's touch layer + * (TabBarTouch.ts), its geometry (tabBarModel.ts) and its UIKit values + * (uikitTabBar.ts) + * @output TabBar (iOS 26's floating tab bar) and TabBarItem + * @position Lab component: the phone presentation of an app's top-level + * sections, UITabBarController's counterpart + * + * SYNC: When modified, update TabBar.doc.mjs, TabBar.test.tsx and + * __tests__/TabBar.interaction.browser.spec.ts. + */ + +import { + Children, + isValidElement, + useCallback, + useId, + useRef, + type ReactElement, + type ReactNode, +} from 'react'; +import * as stylex from '@stylexjs/stylex'; +import type {BaseProps} from '@astryxdesign/core'; +import {useListFocus, useMergedRefs} from '@astryxdesign/core/hooks'; +import {useTouchPresentation} from '@astryxdesign/core/internal/touch'; +import { + colorVars, + durationVars, + easeVars, + focusVars, + fontWeightVars, + radiusVars, + shadowVars, + typographyVars, +} from '@astryxdesign/core/theme/tokens.stylex'; +import {useTranslator} from '@astryxdesign/core/i18n'; +import {mergeProps, themeProps} from '@astryxdesign/core/utils'; +import {tabBarItemMarker} from './tabBar.stylex'; +import {tabBar} from './uikitTabBar'; +import {useTabBarLens} from './TabBarTouch'; +import {itemWidthCss, naturalWidth} from './tabBarModel'; + +// ============================================================================= +// Types +// ============================================================================= + +export interface TabBarItemProps { + /** Identifies the tab in `value`, `onChange` and `onReselect`. */ + value: string; + /** The tab's name, shown under its icon. */ + label: string; + /** The tab's icon, drawn in the current text colour (an ``). */ + icon: ReactNode; + /** The icon while the tab is selected (a filled variant). Defaults to `icon`. */ + selectedIcon?: ReactNode; + /** + * A badge over the icon's top-trailing corner: a count or a short string. + * Omit it, or pass an empty string, for no badge. + */ + badge?: string | number; + /** + * What assistive technology reads for the badge, after the label + * ("3 unread"). Defaults to the badge itself. + */ + badgeLabel?: string; + /** + * Id of the panel this tab controls, wired up as `aria-controls`. Put the + * same id on the panel element. + */ + panelId?: string; +} + +export interface TabBarProps extends Omit< + BaseProps, + 'onChange' +> { + /** Ref forwarded to the root element. */ + ref?: React.Ref; + /** The selected tab's `value`. */ + value: string; + /** Called with a tab's `value` when a different tab is chosen. */ + onChange: (value: string) => void; + /** + * Called with the selected tab's `value` when it is chosen again: pop its + * navigation stack to the root, as iOS does. + */ + onReselect?: (value: string) => void; + /** + * Names the tab bar for assistive technology. Without it, or `aria-label` + * or `aria-labelledby`, the tab list is named "Tabs" in the reader's + * language, as TabList's is. + */ + label?: string; + /** Names the tab list, as `label` does; it wins over `label`. */ + 'aria-label'?: string; + /** Names the tab list after another element; it wins over both. */ + 'aria-labelledby'?: string; + /** The tabs: `TabBarItem` elements, in order. */ + children: ReactNode; +} + +/** + * One tab of a TabBar. It renders nothing on its own: TabBar reads its props + * and draws the tab (it must be a direct child of TabBar). + */ +export function TabBarItem(_props: TabBarItemProps): null { + return null; +} + +function readItems(children: ReactNode): TabBarItemProps[] { + return Children.toArray(children).flatMap(child => + isValidElement(child) && child.type === TabBarItem + ? [(child as ReactElement).props] + : [], + ); +} + +function hasBadge(badge: string | number | undefined): boolean { + return badge != null && badge !== ''; +} + +// ============================================================================= +// Geometry, as CSS on the capsule (a size container: 100cqw is its width) +// ============================================================================= + +const px = (value: number) => `${value}px`; +const INSET = px(tabBar.itemInset); + +/** The items' shared width (and the resting lens's), inside a calc(). */ +const size = (count: number) => itemWidthCss(count); + +/** The distance between neighbouring items' centres. */ +function pitch(count: number): string { + return count > 1 + ? `((100cqw - ${px(2 * tabBar.itemInset)} - ${size(count)}) / ${count - 1})` + : '0px'; +} + +/** An item's centre from the capsule's inline start, inside a calc(). */ +function center(index: number, count: number): string { + return count > 1 + ? `${INSET} + ${size(count)} / 2 + ${pitch(count)} * ${index}` + : '50cqw'; +} + +/** + * An item button's column, and where the item starts inside it. The column runs + * from halfway to the previous item to halfway to the next. The first and last + * columns end at the capsule's edges. + */ +function column( + index: number, + count: number, +): {start: string; width: string; itemStart: string} { + if (count <= 1) { + return { + start: '0px', + width: '100cqw', + itemStart: `calc(50cqw - ${size(count)} / 2)`, + }; + } + const half = `${pitch(count)} / 2`; + const edgeWidth = `calc(${INSET} + ${size(count)} / 2 + ${half})`; + if (index === 0) { + return {start: '0px', width: edgeWidth, itemStart: INSET}; + } + return { + start: `calc(${center(index, count)} - ${half})`, + width: index === count - 1 ? edgeWidth : `calc(${pitch(count)})`, + itemStart: `calc(${half} - ${size(count)} / 2)`, + }; +} + +/** How far the lens's resting place is from the first item. */ +function lensOffset(index: number, count: number): string { + return count > 1 ? `calc(${pitch(count)} * ${index})` : '0px'; +} + +// ============================================================================= +// Styles +// ============================================================================= + +const styles = stylex.create({ + root: { + position: 'fixed', + insetInline: 0, + bottom: 0, + // No page-level stacking rank: the lens and the badges order inside the + // bar's own stacking context. + isolation: 'isolate', + display: 'flex', + justifyContent: 'center', + boxSizing: 'border-box', + pointerEvents: 'none', + }, + rootInset: (inset: string) => ({ + paddingInline: inset, + paddingBottom: inset, + }), + capsule: { + position: 'relative', + flexGrow: 1, + minWidth: 0, + containerType: 'inline-size', + pointerEvents: 'auto', + borderRadius: radiusVars['--radius-full'], + backgroundColor: `color-mix(in srgb, ${colorVars['--color-background-popover']} 78%, transparent)`, + backdropFilter: 'blur(16px) saturate(180%)', + boxShadow: shadowVars['--shadow-med'], + touchAction: 'manipulation', + WebkitTapHighlightColor: 'transparent', + }, + capsuleSize: (height: string, maxWidth: string) => ({height, maxWidth}), + item: { + position: 'absolute', + top: 0, + bottom: 0, + margin: 0, + padding: 0, + borderWidth: 0, + backgroundColor: 'transparent', + color: colorVars['--color-text-primary'], + font: 'inherit', + cursor: { + default: 'pointer', + ':is(:disabled,[aria-disabled="true"])': 'default', + }, + outline: 'none', + WebkitTapHighlightColor: 'transparent', + }, + column: (start: string, width: string) => ({ + insetInlineStart: start, + width, + }), + itemBox: { + position: 'absolute', + display: 'block', + borderRadius: radiusVars['--radius-full'], + outlineStyle: { + default: 'none', + [stylex.when.ancestor(':focus-visible', tabBarItemMarker)]: + focusVars['--focus-outline-style'], + }, + outlineWidth: focusVars['--focus-outline-width'], + outlineColor: focusVars['--focus-outline-color'], + outlineOffset: focusVars['--focus-outline-offset'], + // With no tab selected, a held finger paints its tab at once + // (useTabBarLens.ts writes the attribute). The paint fades out after the + // lift on the theme's exit duration and curve. Under Reduce Motion the fade + // stays within 200 ms, whatever the theme's tempo. + backgroundColor: { + default: null, + [stylex.when.ancestor('[data-tab-bar-pressed]', tabBarItemMarker)]: + colorVars['--color-overlay-pressed'], + }, + transitionProperty: 'background-color', + transitionDuration: { + default: durationVars['--duration-exit'], + '@media (prefers-reduced-motion: reduce)': `min(${durationVars['--duration-exit']}, 200ms)`, + // Repeated inside the Reduce Motion branch, where a media rule outranks + // the plain one, so the onset stays at once there too. + [stylex.when.ancestor('[data-tab-bar-pressed]', tabBarItemMarker)]: { + default: '0s', + '@media (prefers-reduced-motion: reduce)': '0s', + }, + }, + transitionTimingFunction: easeVars['--ease-exit'], + }, + box: (start: string, top: string, width: string, height: string) => ({ + insetInlineStart: start, + top, + width, + height, + }), + icon: { + position: 'absolute', + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + }, + label: { + position: 'absolute', + insetInline: 0, + overflow: 'hidden', + textAlign: 'center', + textOverflow: 'ellipsis', + whiteSpace: 'nowrap', + fontFamily: typographyVars['--font-family-body'], + fontWeight: fontWeightVars['--font-weight-medium'], + }, + labelGeometry: (top: string, height: string, fontSize: string) => ({ + top, + height, + fontSize, + lineHeight: height, + }), + labelSelected: { + fontWeight: fontWeightVars['--font-weight-semibold'], + }, + lens: { + position: 'absolute', + pointerEvents: 'none', + transitionProperty: 'translate', + transitionDuration: { + default: durationVars['--duration-medium'], + // Under a finger the animator moves it (TabBarTouch.ts); under Reduce + // Motion a touch screen cross-fades it there and a mouse jumps. + '@media (pointer: coarse)': '0s', + '@media (prefers-reduced-motion: reduce) and (pointer: coarse)': '0s', + '@media (prefers-reduced-motion: reduce) and (not (pointer: coarse))': + '0s', + }, + transitionTimingFunction: easeVars['--ease-standard'], + }, + // At rest the lens is the pill under the selected item, which draws its own + // selected look. While it slides it carries the copy over the items. + lensUnder: { + zIndex: -1, + }, + lensRest: (offset: string) => ({ + translate: { + default: `${offset} 0`, + ':is([dir="rtl"] *)': `calc(-1 * ${offset}) 0`, + }, + }), + lensBody: { + position: 'absolute', + inset: 0, + // The lifted lens's shadow, outside the clip: the animator fades it in. + '::before': { + content: '""', + position: 'absolute', + inset: 0, + borderRadius: radiusVars['--radius-full'], + boxShadow: shadowVars['--shadow-med'], + opacity: 0, + // The animator promotes it while it moves (core's animator.ts). + willChange: 'var(--astryx-motion-will-change-before, auto)', + }, + }, + lensClip: { + position: 'absolute', + inset: 0, + overflow: 'hidden', + borderRadius: radiusVars['--radius-full'], + // Opaque: while it slides it hides the plain items under the copy. + backgroundColor: `color-mix(in srgb, ${colorVars['--color-text-primary']} 9%, ${colorVars['--color-background-popover']})`, + // The lifted lens: the capsule's own surface with a light rim, opaque so + // the plain copy under it stays hidden; the animator fades it in. + '::before': { + content: '""', + position: 'absolute', + inset: 0, + borderRadius: radiusVars['--radius-full'], + backgroundColor: colorVars['--color-background-popover'], + boxShadow: `inset 0 0 0 1px color-mix(in srgb, ${colorVars['--color-text-primary']} 10%, transparent)`, + opacity: 0, + // The animator promotes it while it moves (core's animator.ts). + willChange: 'var(--astryx-motion-will-change-before, auto)', + }, + }, + copyInner: { + position: 'absolute', + inset: 0, + }, + // Mounted only while the lens slides under a finger, where the animator + // moves it: no transition of its own. + copyOuter: { + position: 'absolute', + width: '100cqw', + }, + copyOuterGeometry: (inset: string, height: string) => ({ + insetInlineStart: `calc(-1 * ${inset})`, + top: `calc(-1 * ${inset})`, + height, + }), + copyRest: (offset: string) => ({ + translate: { + default: `calc(-1 * ${offset}) 0`, + ':is([dir="rtl"] *)': `${offset} 0`, + }, + }), + copyItem: { + position: 'absolute', + color: colorVars['--color-accent'], + }, + // The selected tab's own look at rest: the copy's accent. + itemSelectedLook: { + color: colorVars['--color-accent'], + }, + badges: { + position: 'absolute', + inset: 0, + pointerEvents: 'none', + }, + badge: { + position: 'absolute', + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + boxSizing: 'border-box', + whiteSpace: 'nowrap', + fontFamily: typographyVars['--font-family-body'], + fontWeight: fontWeightVars['--font-weight-medium'], + fontVariantNumeric: 'tabular-nums', + backgroundColor: colorVars['--color-error'], + color: colorVars['--color-on-error'], + }, + badgeGeometry: ( + start: string, + top: string, + height: string, + paddingInline: string, + fontSize: string, + ) => ({ + insetInlineStart: start, + top, + height, + minWidth: height, + paddingInline, + borderRadius: `calc(${height} / 2)`, + fontSize, + lineHeight: height, + }), +}); + +// ============================================================================= +// Pieces +// ============================================================================= + +const ITEM_TOP = px(tabBar.itemInset); +const ITEM_HEIGHT = px(tabBar.itemHeight); +const ICON_START = `calc(50% - ${px(tabBar.iconSize / 2)})`; +const ICON_TOP = px(tabBar.iconCenterY - tabBar.iconSize / 2); +const ICON_SIZE = px(tabBar.iconSize); +const LABEL_TOP = px(tabBar.labelTop); +const LABEL_HEIGHT = px(tabBar.labelSize * 1.2); +const LABEL_SIZE = px(tabBar.labelSize); + +/** + * An item's icon and label, in the plain or the selected look; the lens's + * copy keeps them out of the accessibility tree. + */ +function ItemFace({ + item, + isSelectedLook, + isCopy = false, +}: { + item: TabBarItemProps; + isSelectedLook: boolean; + isCopy?: boolean; +}) { + return ( + <> + + {isSelectedLook ? (item.selectedIcon ?? item.icon) : item.icon} + + + {item.label} + + + ); +} + +// ============================================================================= +// TabBar +// ============================================================================= + +/* + * Layout is CSS, so the bar is right before hydration and through a resize. + * Each button spans to halfway to its neighbours, so a press goes to the + * nearest item. While the lens moves under a finger, a copy of the items rides + * in it, so an item half under the lens is half tinted. + */ +/** + * The iOS 26 tab bar: the app's top-level sections as a floating capsule at + * the bottom of the screen. A selection lens slides between them. + * + * @example + * ``` + * + * } /> + * } badge={3} /> + * + * ``` + */ +export function TabBar({ + value, + onChange, + onReselect, + label, + 'aria-label': ariaLabel, + 'aria-labelledby': ariaLabelledBy, + children, + xstyle, + className, + style, + ref, + ...props +}: TabBarProps) { + const t = useTranslator(); + // The tab list always has a name, and the aria naming props reach it rather + // than the root, as TabList's do. + const tabListLabel = + ariaLabelledBy != null + ? undefined + : (ariaLabel ?? label ?? t('@astryx.tabList.label')); + const items = readItems(children); + const count = items.length; + const selectedIndex = items.findIndex(item => item.value === value); + const baseId = useId(); + + // UIKit's motion belongs to a finger (a coarse primary pointer, iOS and + // Android alike). Under a fine pointer a press is a plain button press, and + // the lens keeps the theme's motion. + const isTouch = useTouchPresentation().isTouch; + + const capsuleRef = useRef(null); + const {listRef, handleKeyDown, handleFocus} = useListFocus({ + itemSelector: '[role="tab"]', + orientation: 'horizontal', + hasRovingTabIndex: true, + }); + const choose = useCallback( + (item: TabBarItemProps) => { + if (item.value === value) { + onReselect?.(item.value); + } else { + onChange(item.value); + } + }, + [value, onChange, onReselect], + ); + const lens = useTabBarLens({ + capsuleRef, + count, + selectedIndex, + isTouch, + onLift: index => choose(items[index]), + }); + const mergedCapsuleRef = useMergedRefs(capsuleRef, listRef, lens.capsule); + + const restIndex = Math.max(selectedIndex, 0); + const capsuleInset = px(tabBar.itemInset); + const itemSize = `calc(${size(count)})`; + + return ( +
+
+ {items.map((item, index) => { + const isSelected = index === selectedIndex; + const {start, width, itemStart} = column(index, count); + return ( + + ); + })} + {selectedIndex >= 0 ? ( +
+
+
+ {lens.isCopyShown ? ( +
+
+ {items.map((item, index) => ( + + + + ))} +
+
+ ) : null} +
+
+
+ ) : null} +
+ {items.map((item, index) => + hasBadge(item.badge) ? ( + + {item.badge} + + ) : null, + )} +
+
+
+ ); +} diff --git a/packages/lab/src/TabBar/TabBarTouch.ts b/packages/lab/src/TabBar/TabBarTouch.ts new file mode 100644 index 0000000000000..cc1cce12e06a3 --- /dev/null +++ b/packages/lab/src/TabBar/TabBarTouch.ts @@ -0,0 +1,16 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file TabBarTouch.ts + * @input The touch hooks beside it + * @output TabBar's touch layer, its one import site: every hook that runs + * core's animator or gesture recognizers for TabBar (the exports below) + * @position Internal to the lab TabBar (TabBar.tsx) + * + * It runs only in the touch presentation. Under a fine pointer a press is a + * plain button press. + */ + +export {useTabBarLens} from './useTabBarLens'; diff --git a/packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts b/packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts new file mode 100644 index 0000000000000..6534fa3a73ef9 --- /dev/null +++ b/packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts @@ -0,0 +1,2095 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TabBar.interaction.browser.spec.ts + * @input The built "Lab/TabBar" stories, real touch and mouse input on the + * harness's phone, and the interaction harness + * @output Proofs that TabBar moves like UITabBar on iOS 26.2: the lens's + * slide, its press tracking and drag. Also the mouse presentation. + * @position Interaction proof for the lab TabBar (TabBar.tsx, + * tabBarModel.ts) + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import type {TouchScript} from '@astryxdesign/interaction-harness'; +import { + advanceFrozenPage, + animationStoryboard, + blockMainThread, + busyWindowProof, + castStoryboard, + CONTROL_RGB, + countBetween, + drag, + freezePage, + freezePageOn, + holdAnimations, + installPageFreeze, + installTimerGate, + markElement, + merge, + openStory, + PARTIAL_LIFT_SKIP, + PEN_SKIP, + releaseAnimations, + sampleCurve, + sampleRects, + springStep, + startBusyControl, + startScreencast, + tap as tapScript, + thawPage, + toTouchEvents, + touchDriver, + touchStoryboard, + traceRendering, + trackMarker, + waitForAnimation, + waitForRest, + webInputDriver, + withFinger, + withStorybook, + writeEvidence, +} from '@astryxdesign/interaction-harness'; + +const storybook = withStorybook(test); + +/** + * A mouse case's own guard: its context's primary pointer is fine (a context + * without touch can still match a coarse pointer in the interaction config). + */ +async function expectFinePointer(page: Page) { + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + 'the primary pointer is fine', + ).toBe(false); +} +/** + * The opacity of an element's `::before` at each of `times` (ms into the held + * curves), as sampleCurve reads an element's. The lens's lifted glass is its + * clip's `::before`. + */ +async function samplePseudoOpacity(locator: Locator, times: number[]) { + return locator.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.001); + } + return Number(getComputedStyle(element, '::before').opacity); + }); + }, times); +} + +/** UIKit's lens travel on iOS 26.2 (uikitTabBar.ts `lensTravel`). */ +const LENS_TRAVEL = {response: 0.4, dampingFraction: 0.85}; +/** The lift (`lift`), the flex while pressed and after (`flexPress`, `flexRelease`). */ +const LIFT = {response: 0.25, dampingFraction: 1}; +const FLEX_PRESS = {response: 0.314, dampingFraction: 0.625}; +const FLEX_RELEASE = {response: 0.36, dampingFraction: 0.6}; +const FLEX_SCALE = 1.0488; +/** The lifted lens's scale: the resting lens grown by 8 px on every side. */ +async function liftedScale(page: Page) { + const width = await lensBody(page).evaluate( + element => (element as HTMLElement).offsetWidth, + ); + return {x: (width + 16) / width, y: 70 / 54}; +} + +/** + * Opens a TabBar story on the harness's phone: a coarse primary pointer, so + * the touch presentation applies, whatever the engine (one touch model). + */ +/** + * Page side, from before the story loads: every script animation the page makes + * (the animator's) and the document time it was made. It also records when a + * finger last lifted. The reduced-motion checks read a short cross-fade from it + * after the fade ends. They date "since the lift" by the page's own lift, not + * by a later read. + */ +function animationLog(): void { + const w = window as unknown as { + __tabBarMade?: {animation: Animation; at: number}[]; + __tabBarLifted?: number; + }; + if (w.__tabBarMade != null) { + return; + } + const made: {animation: Animation; at: number}[] = []; + w.__tabBarMade = made; + w.__tabBarLifted = 0; + const now = () => Number(document.timeline.currentTime ?? 0); + const animate = Element.prototype.animate; + Element.prototype.animate = function ( + this: Element, + ...args: Parameters + ) { + const animation = animate.apply(this, args); + made.push({animation, at: now()}); + if (made.length > 5000) { + made.splice(0, made.length - 5000); + } + return animation; + }; + window.addEventListener( + 'touchend', + () => { + w.__tabBarLifted = now(); + }, + true, + ); +} + +/** When a finger last lifted on the page, on the document timeline (0: never). */ +const liftedAt = (page: Page) => + page.evaluate( + () => (window as unknown as {__tabBarLifted?: number}).__tabBarLifted ?? 0, + ); + +async function openBar(page: Page, story = 'default') { + await page.addInitScript(animationLog); + await openStory(page, storybook(), `lab-tabbar--${story}`); + const driver = await touchDriver(page); + const bar = page.getByRole('tablist', {name: 'Sections'}); + await expect(bar).toBeVisible(); + return {driver, bar}; +} + +/** + * `openBar` on a page whose scene the test can freeze: the page clock goes in + * before the story loads, the timer gate after. + */ +async function openFreezableBar(page: Page, story = 'default') { + await installPageFreeze(page); + const opened = await openBar(page, story); + await installTimerGate(page); + return opened; +} + +const tab = (page: Page, name: string | RegExp) => + page.getByRole('tab', {name}); + +/** The centre of a tab's 76 × 54 item, where a finger lands on it. */ +async function itemCenter(page: Page, name: string | RegExp) { + const box = await tab(page, name).locator('span').first().boundingBox(); + if (box == null) { + throw new Error(`no tab ${String(name)}`); + } + return {x: box.x + box.width / 2, y: box.y + box.height / 2}; +} + +const lensBody = (page: Page) => page.locator('[data-tab-bar-lens-body]'); +const lensCopy = (page: Page) => page.locator('[data-tab-bar-copy]'); + +/** The lens's centre on screen. */ +async function lensCenterX(page: Page) { + const box = await lensBody(page).boundingBox(); + if (box == null) { + throw new Error('no lens'); + } + return box.x + box.width / 2; +} + +const TRANSPARENT = 'rgba(0, 0, 0, 0)'; + +/** The background of a tab's item: its press paint, or transparent. */ +async function itemPaint(page: Page, name: string) { + return tab(page, name) + .locator('span') + .first() + .evaluate(element => getComputedStyle(element).backgroundColor); +} + +/** + * Reads the event listeners on what `expression` evaluates to, through CDP + * (Chromium): each as its type and its capture and passive flags. + */ +async function cdpListeners(page: Page) { + const cdp = await page.context().newCDPSession(page); + return async (expression: string) => { + const {result} = await cdp.send('Runtime.evaluate', {expression}); + const {listeners: found} = await cdp.send('DOMDebugger.getEventListeners', { + objectId: result.objectId ?? '', + }); + return found + .map( + listener => + `${listener.type}${listener.useCapture ? '/capture' : ''}${listener.passive ? '/passive' : ''}`, + ) + .sort(); + }; +} + +/** + * An init script that lets a test switch the presentation. It wraps + * `matchMedia` for the coarse-pointer query. Then `window.__setCoarse(false)` + * makes the page's code read a fine primary pointer and hear the change. + * Stylesheets keep the real media. + */ +const PRESENTATION_SWITCH = () => { + const real = window.matchMedia.bind(window); + const listeners = new Set<(event: {matches: boolean}) => void>(); + let coarse: boolean | null = null; + (window as unknown as {__setCoarse: (value: boolean) => void}).__setCoarse = + value => { + coarse = value; + for (const listener of [...listeners]) { + listener({matches: value}); + } + }; + window.matchMedia = (query: string) => { + const list = real(query); + if (query !== '(pointer: coarse)') { + return list; + } + return new Proxy(list, { + get(target, key) { + if (key === 'matches') { + return coarse ?? target.matches; + } + if (key === 'addEventListener') { + return ( + type: string, + listener: (event: {matches: boolean}) => void, + ) => { + if (type === 'change') { + listeners.add(listener); + } + }; + } + if (key === 'removeEventListener') { + return ( + _type: string, + listener: (event: {matches: boolean}) => void, + ) => { + listeners.delete(listener); + }; + } + const value = Reflect.get(target, key, target); + return typeof value === 'function' ? value.bind(target) : value; + }, + }); + }; +}; + +/** + * A tab's paint timing now, beside what `values` resolve to in its place, + * through a probe inside the item. Each is a duration in ms and a curve. + */ +async function paintTimingAgainst( + page: Page, + name: string, + values: {duration: string; easing: string}, +) { + return tab(page, name) + .locator('span') + .first() + .evaluate((element, wanted) => { + const probe = document.createElement('span'); + probe.style.transitionDuration = wanted.duration; + probe.style.transitionTimingFunction = wanted.easing; + element.append(probe); + const read = (style: CSSStyleDeclaration) => ({ + ms: parseFloat(style.transitionDuration) * 1000, + easing: style.transitionTimingFunction, + }); + const result = { + have: read(getComputedStyle(element)), + want: read(getComputedStyle(probe)), + }; + probe.remove(); + return result; + }, values); +} + +/** Gives the bar a theme exit duration of its own. */ +async function setExitDuration(page: Page, value: string) { + await page + .getByRole('tablist', {name: 'Sections'}) + .evaluate( + (element, duration) => + element.style.setProperty('--duration-exit', duration), + value, + ); +} + +/** How long a tab's paint takes to change now, in ms. */ +async function paintFadeMs(page: Page, name: string) { + return tab(page, name) + .locator('span') + .first() + .evaluate( + element => + parseFloat(getComputedStyle(element).transitionDuration) * 1000, + ); +} + +/** + * The elements under test are on screen before anything is measured about + * them: `count` of them, each with a nonzero box. + */ +async function expectPainted(locator: Locator, count = 1) { + await expect(locator).toHaveCount(count); + const boxes = await locator.evaluateAll(elements => + elements.map(element => { + const rect = element.getBoundingClientRect(); + return {width: rect.width, height: rect.height}; + }), + ); + for (const box of boxes) { + expect(box.width, JSON.stringify(boxes)).toBeGreaterThan(0); + expect(box.height, JSON.stringify(boxes)).toBeGreaterThan(0); + } +} + +/** A presented translateX, px (the animator drives `translate`). */ +const translateX = async (locator: Locator) => + locator.evaluate(element => { + const value = getComputedStyle(element).translate; + return value === 'none' ? 0 : parseFloat(value); + }); + +/** A presented scale (the animator drives `scale`). */ +const scaleOf = async (locator: Locator) => + locator.evaluate(element => { + const value = getComputedStyle(element).scale; + if (value === 'none') { + return {x: 1, y: 1}; + } + const [x, y = x] = value.split(' ').map(Number); + return {x, y}; + }); + +/** The capsule's left edge on screen, before its flex (its root is unscaled). */ +async function capsuleLeft(page: Page) { + return page.getByRole('tablist').evaluate(element => { + const root = element.parentElement?.getBoundingClientRect(); + return (root?.left ?? 0) + (element as HTMLElement).offsetLeft; + }); +} + +test('a selection made with the keys slides the lens on UIKit’s spring, the selected copy counter-moving', async ({ + page, +}, testInfo) => { + await openFreezableBar(page); + const from = await itemCenter(page, 'Home'); + const to = await itemCenter(page, 'Browse'); + await tab(page, 'Home').focus(); + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('ArrowRight'); + // The scene stands still from before the key: the slide it starts is held at + // its start. The copy that rides in the lens only while it slides stays + // mounted, however slowly the test process reads them. + await freezePage(page); + await page.keyboard.press('Enter'); + await expect(tab(page, 'Browse')).toHaveAttribute('aria-selected', 'true'); + const body = lensBody(page); + await waitForAnimation(body, {minProgressMs: 0}); + await holdAnimations(page); + + const times = Array.from({length: 49}, (_, i) => i * 16.667); + const bodySamples = await sampleCurve(body, times); + const copySamples = await sampleCurve(lensCopy(page), times); + // The body starts where the lens was (over Home) relative to its new + // resting place (Browse) and springs to 0 from rest. + const start = from.x - to.x; + const samples = times.map((t, i) => ({ + t: +t.toFixed(1), + body: bodySamples[i].transform.translateX, + copy: copySamples[i].transform.translateX, + analytic: start * (1 - springStep(LENS_TRAVEL, t)), + })); + await releaseAnimations(page, {finish: true}); + await thawPage(page); + await writeEvidence( + 'curves/tabbar-lens-travel', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {start, samples}, + null, + 1, + ), + }, + testInfo, + ); + + for (const sample of samples) { + expect( + Math.abs(sample.body - sample.analytic), + JSON.stringify(sample), + ).toBeLessThan(0.5); + // The copy inside undoes the body's travel, so the items stay put. + expect( + Math.abs(sample.copy + sample.body), + JSON.stringify(sample), + ).toBeLessThan(0.3); + } + // UIKit's lens overshoots a little (ζ 0.85) before it settles. + expect(Math.max(...samples.map(s => s.body))).toBeGreaterThan(0.5); + await waitForRest(body); + expect(Math.abs((await lensCenterX(page)) - to.x)).toBeLessThan(0.5); +}); + +test('a second tap mid-slide turns the lens around from where it is, without a jump', async ({ + page, +}) => { + const {driver} = await openFreezableBar(page); + const home = await itemCenter(page, 'Home'); + const profile = await itemCenter(page, 'Profile'); + const library = await itemCenter(page, 'Library'); + // Records the lens's centre as each finger lands: under a finger the + // lens turns for the second finger the moment it lands. + await page.evaluate(() => { + const lens = document.querySelector('[data-tab-bar-lens-body]'); + const landings: number[] = []; + (window as unknown as {__landings: number[]}).__landings = landings; + window.addEventListener( + 'touchstart', + () => { + const box = lens?.getBoundingClientRect(); + if (box != null) { + landings.push(box.x + box.width / 2); + } + }, + {capture: true}, + ); + }); + // The scene stands still from before the first tap: the slide it starts is + // held at its start. Then the scene's own time steps it on until the lens is + // past Library, however late the test process is. The second tap lands there, + // with most of the slide still ahead. + await freezePage(page); + await driver.tap(profile); + let frozenAt = await lensCenterX(page); + for ( + let stepped = 0; + frozenAt <= library.x + 25 && stepped < 1_000; + stepped += 4 + ) { + await advanceFrozenPage(page, 4); + frozenAt = await lensCenterX(page); + } + // Mid-slide: past Library, short of Profile. + expect(frozenAt).toBeGreaterThan(library.x + 5); + expect(frozenAt).toBeLessThan(profile.x - 20); + await driver.tap(library); + await thawPage(page); + // Every frame's lens position from the thaw on, as it turns. Before it the + // test stepped the scene's time itself, several steps to a frame. + const sampling = sampleRects(lensBody(page), 1300); + await expect(tab(page, 'Library')).toHaveAttribute('aria-selected', 'true'); + const turnedAt = await page.evaluate( + () => (window as unknown as {__landings: number[]}).__landings[1], + ); + // The second finger landed on the lens where the scene stood. + expect(Math.abs(turnedAt - frozenAt)).toBeLessThan(0.5); + const samples = (await sampling).flatMap(sample => + sample.box == null + ? [] + : [{t: sample.t, x: sample.box.x + sample.box.width / 2}], + ); + // It went on toward Profile and came back to Library, never jumping. A jump + // to either end would cover the whole remaining distance (over 100 px) in + // one frame. Only consecutive frames are compared, never samples a stall kept + // apart. + const steps = samples + .slice(1) + .flatMap((sample, i) => + sample.t - samples[i].t <= 34 ? [sample.x - samples[i].x] : [], + ); + // The first frame after the thaw starts where the scene stood. + expect(Math.abs(samples[0].x - frozenAt)).toBeLessThan(90); + expect( + Math.max(...steps.map(Math.abs)), + JSON.stringify(samples), + ).toBeLessThan(90); + expect(Math.min(...samples.map(sample => sample.x))).toBeGreaterThan( + home.x - 1, + ); + await waitForRest(lensBody(page)); + expect(Math.abs((await lensCenterX(page)) - library.x)).toBeLessThan(0.5); +}); + +test('a finger landing before the last lift reaches the app keeps the lens heading for it', async ({ + page, +}) => { + const {driver} = await openFreezableBar(page); + const profile = await itemCenter(page, 'Profile'); + const library = await itemCenter(page, 'Library'); + const sampling = sampleRects(lensBody(page), 1400); + // A tap on Profile, then a finger held on Library from right after that lift. + // Inside the frames before the tap's choice reaches the app, which then moves + // the lens's resting place under the held finger. The scene freezes on the + // first finger's pointerdown, before the page's touchstart work starts any + // motion. A loaded box can spend tens of ms in that work. While frozen, the + // scene moves on by the script's own gaps. So the second finger lands 80 ms + // into the first slide of the scene's time, however a loaded box stretches + // the gaps. It thaws once the second finger is down; the hold is a wait after + // the landing. + const script: TouchScript = [ + {t: 0, fingers: [{id: 0, ...profile}]}, + {t: 60, fingers: []}, + {t: 80, fingers: [{id: 1, ...library}]}, + {t: 580, fingers: []}, + ]; + const events = toTouchEvents(script); + await freezePageOn(page, 'pointerdown'); + await driver.play(script, { + realtime: false, + onEvent: async (step, index) => { + if (index < 2) { + await advanceFrozenPage(page, events[index + 1].t - step.t); + } else if (index === 2) { + await thawPage(page); + await page.waitForTimeout(500); + } + }, + }); + await expect(tab(page, 'Library')).toHaveAttribute('aria-selected', 'true'); + const samples = (await sampling).flatMap(sample => + sample.box == null + ? [] + : [{t: sample.t, x: sample.box.x + sample.box.width / 2}], + ); + const centers = samples.map(sample => sample.x); + // Only consecutive frames are compared, never samples a stall kept apart + // (software-rendered WebKit can present no frame for a while around a + // touch). + const steps = samples + .slice(1) + .flatMap((sample, i) => + sample.t - samples[i].t <= 34 ? [sample.x - samples[i].x] : [], + ); + expect( + Math.max(...steps.map(Math.abs)), + JSON.stringify(samples), + ).toBeLessThan(90); + // The lens turned back for the held finger and never reached Profile. + expect(Math.max(...centers), JSON.stringify(centers)).toBeLessThan( + profile.x - 30, + ); + await waitForRest(lensBody(page)); + expect(Math.abs((await lensCenterX(page)) - library.x)).toBeLessThan(0.5); +}); + +test('a tap on the selected tab reselects it: the lens lifts and settles back', async ({ + page, +}) => { + const {driver} = await openBar(page); + const home = await itemCenter(page, 'Home'); + await driver.tap(home); + await expect(page.getByTestId('reselects')).toHaveText('Reselected 1 times'); + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true'); + await waitForRest(page.getByRole('tablist')); + expect(Math.abs((await lensCenterX(page)) - home.x)).toBeLessThan(0.5); + expect(await scaleOf(lensBody(page))).toEqual({x: 1, y: 1}); +}); + +test('with no tab selected, a finger chooses the tab under it', async ({ + page, +}) => { + const {driver} = await openBar(page, 'no-selection'); + await expect(page.getByRole('tab', {selected: true})).toHaveCount(0); + const browse = await itemCenter(page, 'Browse'); + await driver.tap(browse); + await expect(tab(page, 'Browse')).toHaveAttribute('aria-selected', 'true'); +}); + +test('a held finger never starts text selection on the bar', async ({page}) => { + const {driver} = await openBar(page); + const browse = await itemCenter(page, 'Browse'); + const capsule = page.getByRole('tablist'); + // The lens's hold opts into the gesture host's selection lock (spec:AST-094 + // FR41). Off iOS that lock writes no style. It cancels selectstart on what + // the finger holds, so the proof dispatches one there, during the hold and + // after the lift. + const refusesSelection = () => + tab(page, 'Browse').evaluate(element => { + const event = new Event('selectstart', {bubbles: true, cancelable: true}); + element.dispatchEvent(event); + return event.defaultPrevented; + }); + let refusedWhileHeld: boolean | null = null; + await driver.play(tapScript(browse, {holdMs: 600}), { + onEvent: async (_step, index) => { + if (index !== 0) { + return; + } + // The hold has begun once the lens lifts. + await waitForAnimation(capsule); + refusedWhileHeld = await refusesSelection(); + }, + }); + expect(refusedWhileHeld).toBe(true); + expect(await refusesSelection()).toBe(false); +}); + +test('a tap reports its choice once', async ({page}) => { + const {driver} = await openBar(page, 'removed-on-lift'); + const read = () => + page.evaluate( + () => (window as unknown as {__tabBarChanges: string[]}).__tabBarChanges, + ); + await page.evaluate(() => { + (window as unknown as {__tabBarChanges: string[]}).__tabBarChanges = []; + }); + // Under a finger the lift reports, and the click the browser sends after + // it must not report again (`spec:AST-094` FR21). + await driver.tap(await itemCenter(page, 'Library')); + await page.waitForTimeout(400); + expect((await read()).filter(entry => entry === 'library')).toEqual([ + 'library', + ]); +}); + +test('a bar removed as the finger lifts reports nothing after it is gone', async ({ + page, +}) => { + const {driver} = await openBar(page, 'removed-on-lift'); + await page.evaluate(() => { + (window as unknown as {__tabBarChanges: string[]}).__tabBarChanges = []; + }); + await driver.tap(await itemCenter(page, 'Library')); + await expect(page.getByText('Removed')).toBeVisible(); + await page.waitForTimeout(400); + // The lift reports from its own event, so the choice may arrive before + // the app removes the bar in that event, never after. + const log = await page.evaluate( + () => (window as unknown as {__tabBarChanges: string[]}).__tabBarChanges, + ); + expect(log.at(-1)).toBe('(removed)'); + expect(log.filter(entry => entry !== '(removed)')).toEqual( + log.length > 1 ? ['library'] : [], + ); +}); + +test('a press ends without a choice when the tab list changes under it', async ({ + page, +}) => { + const errors: string[] = []; + page.on('pageerror', error => errors.push(error.message)); + const {driver, bar} = await openBar(page, 'drops-last-tab'); + await page.evaluate(() => { + (window as unknown as {__tabBarChanges: string[]}).__tabBarChanges = []; + }); + const profile = await itemCenter(page, 'Profile'); + await driver.play(tapScript(profile, {holdMs: 600}), { + onEvent: async (_step, index) => { + if (index !== 0) { + return; + } + // The hold has begun once the lens lifts; the app then drops Profile, + // the tab under the finger. + await waitForAnimation(bar); + await page.evaluate(() => + window.dispatchEvent(new Event('tabbar:drop-last')), + ); + await expect(tab(page, 'Profile')).toHaveCount(0); + }, + }); + // Settled before anything is read: the lens comes back onto Home after the + // lift, however long a loaded machine takes. + await waitForRest(lensBody(page)); + expect(errors).toEqual([]); + expect( + await page.evaluate( + () => (window as unknown as {__tabBarChanges: string[]}).__tabBarChanges, + ), + ).toEqual([]); + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true'); + // The lens settled back onto Home, in the three-tab bar. + const home = await itemCenter(page, 'Home'); + expect(Math.abs((await lensCenterX(page)) - home.x)).toBeLessThan(1); +}); + +test('a press the tab list ends moves no focus at the lift: it chose nothing (family:action-groups FR1)', async ({ + page, +}) => { + const {driver, bar} = await openBar(page, 'drops-last-tab'); + const library = await itemCenter(page, 'Library'); + await tab(page, 'Home').focus(); + await driver.play(tapScript(library, {holdMs: 600}), { + onEvent: async (_step, index) => { + if (index !== 0) { + return; + } + // The hold has begun once the lens lifts; the app then drops Profile. + // Library, under the finger, stays. + await waitForAnimation(bar); + await page.evaluate(() => + window.dispatchEvent(new Event('tabbar:drop-last')), + ); + await expect(tab(page, 'Profile')).toHaveCount(0); + }, + }); + await waitForRest(lensBody(page)); + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true'); + await expect(tab(page, 'Home')).toBeFocused(); +}); + +test('the bar sets no page-level stacking rank: its layers order inside it', async ({ + page, +}) => { + await openBar(page); + const root = await page.getByTestId('tab-bar').evaluate(element => { + const style = getComputedStyle(element); + return {zIndex: style.zIndex, isolation: style.isolation}; + }); + expect(root).toEqual({zIndex: 'auto', isolation: 'isolate'}); +}); + +test('badges appear, change and clear without animating', async ({page}) => { + const {driver} = await openBar(page, 'badges'); + const badge = page.locator('[data-tab-bar-badge="inbox"]'); + await expect(badge).toHaveCount(0); + await driver.tap( + await page + .getByRole('button', {name: 'Add one'}) + .boundingBox() + .then(box => { + if (box == null) { + throw new Error('no button'); + } + return {x: box.x + box.width / 2, y: box.y + box.height / 2}; + }), + ); + await expect(badge).toHaveText('1'); + expect(await badge.evaluate(element => element.getAnimations().length)).toBe( + 0, + ); + await expect(tab(page, /^Inbox\s*, 1 unread$/)).toBeVisible(); + await page.getByRole('button', {name: 'Add ten'}).click(); + await expect(badge).toHaveText('11'); + // "11" is wider than one digit: the badge grows past its 18.33 px circle. + const box = await badge.boundingBox(); + expect(box?.height).toBeCloseTo(18.33, 1); + expect(box?.width ?? 0).toBeGreaterThan(18.5); + await page.getByRole('button', {name: 'Clear'}).click(); + await expect(badge).toHaveCount(0); +}); + +test('a finger landing lifts the lens and flexes the bar on UIKit’s springs, the lens heading for the finger', async ({ + page, +}, testInfo) => { + const {driver} = await openFreezableBar(page); + const home = await itemCenter(page, 'Home'); + const browse = await itemCenter(page, 'Browse'); + const capsule = page.getByRole('tablist'); + const LIFTED = await liftedScale(page); + const times = Array.from({length: 31}, (_, i) => i * 16.667); + let samples: { + t: number; + flex: number; + liftX: number; + liftY: number; + glass: number; + x: number; + }[] = []; + // The scene freezes as the finger lands. So the lift, the flex and the travel + // it starts are held at their start however slowly the test process reads + // them. + await freezePageOn(page, 'touchstart'); + await driver.play(tapScript(browse, {holdMs: 1200}), { + onEvent: async (_step, index) => { + if (index !== 0) { + return; + } + await waitForAnimation(capsule, {minProgressMs: 0}); + await holdAnimations(page); + const flex = await sampleCurve(capsule, times); + const body = await sampleCurve(lensBody(page), times); + const glass = await samplePseudoOpacity( + page.locator('[data-tab-bar-lens-clip]'), + times, + ); + samples = times.map((t, i) => ({ + t: +t.toFixed(1), + flex: flex[i].transform.scaleX, + liftX: body[i].transform.scaleX, + liftY: body[i].transform.scaleY, + glass: glass[i], + x: body[i].transform.translateX, + })); + await releaseAnimations(page); + await thawPage(page); + }, + }); + await writeEvidence( + 'curves/tabbar-press', + {[`${testInfo.project.name}.json`]: JSON.stringify(samples, null, 1)}, + testInfo, + ); + const travel = browse.x - home.x; + for (const s of samples) { + const lift = springStep(LIFT, s.t); + const where = JSON.stringify(s); + expect( + Math.abs(s.flex - (1 + (FLEX_SCALE - 1) * springStep(FLEX_PRESS, s.t))), + where, + ).toBeLessThan(0.002); + expect(Math.abs(s.liftX - (1 + (LIFTED.x - 1) * lift)), where).toBeLessThan( + 0.005, + ); + expect(Math.abs(s.liftY - (1 + (LIFTED.y - 1) * lift)), where).toBeLessThan( + 0.005, + ); + expect(Math.abs(s.glass - lift), where).toBeLessThan(0.01); + expect( + Math.abs(s.x - travel * springStep(LENS_TRAVEL, s.t)), + where, + ).toBeLessThan(0.5); + } + // The lift commits Browse. + await expect(tab(page, 'Browse')).toHaveAttribute('aria-selected', 'true'); +}); + +test('the lift reports its choice from its own event, the settle already started (react-component-runtime INV2)', async ({ + page, +}) => { + const {driver} = await openBar(page); + const browse = await itemCenter(page, 'Browse'); + await page.evaluate(() => { + const w = window as unknown as { + __lift: { + frames: number; + atLift: number; + atChoice: number; + settling: boolean; + }; + }; + w.__lift = {frames: 0, atLift: -1, atChoice: -1, settling: false}; + const tick = () => { + w.__lift.frames += 1; + requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); + window.addEventListener( + 'touchend', + () => { + w.__lift.atLift = w.__lift.frames; + }, + {capture: true}, + ); + const tab = [...document.querySelectorAll('[role="tab"]')].find(element => + element.textContent?.includes('Browse'), + ); + const body = document.querySelector('[data-tab-bar-lens-body]'); + new MutationObserver(() => { + if (tab?.getAttribute('aria-selected') === 'true') { + w.__lift.atChoice = w.__lift.frames; + w.__lift.settling = (body?.getAnimations().length ?? 0) > 0; + } + }).observe(tab as Element, {attributeFilter: ['aria-selected']}); + }); + await driver.play(tapScript(browse, {holdMs: 200})); + await expect(tab(page, 'Browse')).toHaveAttribute('aria-selected', 'true'); + const lift = await page.evaluate( + () => + ( + window as unknown as { + __lift: { + frames: number; + atLift: number; + atChoice: number; + settling: boolean; + }; + } + ).__lift, + ); + // Chosen in the lift's own task: no frame between the lift and the choice. + expect(lift.atLift).toBeGreaterThanOrEqual(0); + expect(lift.atChoice).toBe(lift.atLift); + // The settle was running when the app heard the choice. + expect(lift.settling).toBe(true); +}); + +test('the lift settles the lens and relaxes the lift and the flex on UIKit’s springs', async ({ + page, +}) => { + const {driver} = await openFreezableBar(page); + const browse = await itemCenter(page, 'Browse'); + const capsule = page.getByRole('tablist'); + const LIFTED = await liftedScale(page); + // The scene freezes as the finger lifts, so the settle the lift starts is + // held at its start however slowly the test process reads it. + await freezePageOn(page, 'touchend'); + // Held long enough for the press springs to settle. + await driver.play(tapScript(browse, {holdMs: 1200})); + // The choice reaches the app from the lift itself and restarts the lens's + // travel from its new resting place. Hold the curves after that, so no held + // animation is one the animator has since replaced. + await expect(tab(page, 'Browse')).toHaveAttribute('aria-selected', 'true'); + await waitForAnimation(capsule, {minProgressMs: 0}); + await holdAnimations(page); + const times = Array.from({length: 37}, (_, i) => i * 16.667); + const flex = await sampleCurve(capsule, times); + const body = await sampleCurve(lensBody(page), times); + await releaseAnimations(page, {finish: true}); + await thawPage(page); + times.forEach((t, i) => { + const where = JSON.stringify({t, flex: flex[i].transform.scaleX}); + expect( + Math.abs( + flex[i].transform.scaleX - + (FLEX_SCALE + (1 - FLEX_SCALE) * springStep(FLEX_RELEASE, t)), + ), + where, + ).toBeLessThan(0.002); + expect( + Math.abs( + body[i].transform.scaleX - + (LIFTED.x + (1 - LIFTED.x) * springStep(LIFT, t)), + ), + where, + ).toBeLessThan(0.005); + }); + await waitForRest(lensBody(page)); + expect(Math.abs((await lensCenterX(page)) - browse.x)).toBeLessThan(0.5); +}); + +test('a drag chases the finger and the lift commits the item nearest it', async ({ + page, +}) => { + const {driver} = await openFreezableBar(page); + const home = await itemCenter(page, 'Home'); + const profile = await itemCenter(page, 'Profile'); + const left = await capsuleLeft(page); + const lags: number[] = []; + let atRest = Infinity; + const script = drag(home, profile, {durationMs: 600, restMs: 400}); + const events = toTouchEvents(script); + // The body's offset is in the capsule's own coordinates, from Home. + const lensX = async () => + (await translateX(lensBody(page))) + (home.x - left); + // The scene's own clock times the drag. Frozen from before the first touch, + // it moves on by each scripted gap. So every lag is read at its scripted + // instant, however late the test process is. + await freezePage(page); + await driver.play(script, { + realtime: false, + onEvent: async (step, index) => { + let stepped = 0; + const finger = step.fingers[0]?.x; + if (finger != null) { + lags.push(finger - left - (await lensX())); + if (index === events.length - 2) { + stepped = 350; + await advanceFrozenPage(page, stepped); + atRest = finger - left - (await lensX()); + } + } + const next = events[index + 1]; + if (next != null) { + await advanceFrozenPage(page, Math.max(0, next.t - step.t - stepped)); + } + }, + }); + await thawPage(page); + // The lens trails a moving finger but keeps up with it, and catches up + // once it rests. + const moving = lags.slice(3, -2); + expect(Math.max(...moving)).toBeGreaterThan(1); + expect(Math.max(...moving.map(Math.abs))).toBeLessThan(40); + expect(Math.abs(atRest)).toBeLessThan(1); + await expect(tab(page, 'Profile')).toHaveAttribute('aria-selected', 'true'); + await waitForRest(page.getByRole('tablist')); + expect(Math.abs((await lensCenterX(page)) - profile.x)).toBeLessThan(0.5); +}); + +test('when the app keeps the old selection, the lens settles back onto it', async ({ + page, +}) => { + const {driver} = await openBar(page, 'keeps-selection'); + const home = await itemCenter(page, 'Home'); + const profile = await itemCenter(page, 'Profile'); + await driver.play(drag(home, profile, {durationMs: 500, restMs: 300})); + // The lift chose Profile; the app kept Home. + await page.waitForTimeout(150); + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true'); + await expect(tab(page, 'Profile')).toHaveAttribute('aria-selected', 'false'); + await waitForRest(page.getByRole('tablist')); + expect(Math.abs((await lensCenterX(page)) - home.x)).toBeLessThan(0.5); + expect(await scaleOf(lensBody(page))).toEqual({x: 1, y: 1}); +}); + +test('right to left, a drag runs from the first tab leftward and commits where it lifts', async ({ + page, +}) => { + const {driver} = await openBar(page, 'right-to-left'); + const library = await itemCenter(page, 'Library'); + const profile = await itemCenter(page, 'Profile'); + // The later tab sits to the left. + expect(profile.x).toBeLessThan(library.x); + await driver.play(drag(library, profile, {durationMs: 500, restMs: 300})); + await expect(tab(page, 'Profile')).toHaveAttribute('aria-selected', 'true'); + await waitForRest(page.getByRole('tablist')); + expect(Math.abs((await lensCenterX(page)) - profile.x)).toBeLessThan(0.5); +}); + +test('a lift between two items commits the nearer one (an exact tie goes to the leading one: tabBarModel.test.ts)', async ({ + page, +}) => { + const {driver} = await openBar(page); + const library = await itemCenter(page, 'Library'); + const browse = await itemCenter(page, 'Browse'); + const midpoint = (library.x + browse.x) / 2; + await driver.play(tapScript({x: midpoint + 3, y: library.y}, {holdMs: 120})); + await expect(tab(page, 'Browse')).toHaveAttribute('aria-selected', 'true'); + await driver.play(tapScript({x: midpoint - 3, y: library.y}, {holdMs: 120})); + await expect(tab(page, 'Library')).toHaveAttribute('aria-selected', 'true'); +}); + +test('a finger dragged off the bar chooses nothing at the lift, and the lens shows the selected tab again: sliding off cancels (family:action-groups FR3)', async ({ + page, +}) => { + const {driver} = await openBar(page); + const home = await itemCenter(page, 'Home'); + const library = await itemCenter(page, 'Library'); + const across = [...drag(home, library, {durationMs: 300})]; + // Without the drag's own lift: the finger lifts off the bar instead. + across.pop(); + const last = across[across.length - 1]; + const up = Array.from({length: 10}, (_, i) => ({ + t: last.t + (i + 1) * 16.7, + fingers: [{id: 0, x: library.x, y: library.y - (i + 1) * 8}], + })); + const end = up[up.length - 1].t + 16.7; + await driver.play([ + ...across, + ...up, + // Held off the bar, then lifted there. + {t: end + 300, fingers: up[up.length - 1].fingers}, + {t: end + 316.7, fingers: []}, + ]); + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true'); + await waitForRest(lensBody(page)); + expect(Math.abs((await lensCenterX(page)) - home.x)).toBeLessThan(0.5); +}); + +test('a second finger landing mid-drag ends the press with nothing chosen, and the lens shows the selected tab again (family:action-groups FR3)', async ({ + page, +}) => { + const {driver} = await openBar(page); + test.skip(!driver.partialLifts, PARTIAL_LIFT_SKIP); + const home = await itemCenter(page, 'Home'); + const browse = await itemCenter(page, 'Browse'); + const profile = await itemCenter(page, 'Profile'); + const first = withFinger( + drag(home, browse, {durationMs: 500, restMs: 300}), + 1, + ); + // The second finger lands mid-drag and lifts before the first. + const second = withFinger(tapScript(profile, {holdMs: 100}), 2, 250); + await driver.play(merge(first, second)); + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true'); + await expect(page.getByTestId('reselects')).toHaveText('Reselected 0 times'); + await waitForRest(lensBody(page)); + expect(Math.abs((await lensCenterX(page)) - home.x)).toBeLessThan(0.5); +}); + +test('after a finger’s slide, focus moves to the chosen tab, as a tap on it does: it never stays on the tab the press left (family:action-groups FR1)', async ({ + page, +}) => { + const {driver} = await openBar(page); + const home = await itemCenter(page, 'Home'); + const library = await itemCenter(page, 'Library'); + await tab(page, 'Home').focus(); + await driver.play(drag(home, library, {durationMs: 500, restMs: 300})); + await expect(tab(page, 'Library')).toHaveAttribute('aria-selected', 'true'); + await expect(tab(page, 'Library')).toBeFocused(); +}); + +test('with no tab selected, a finger held on a tab paints it, and the paint follows a slide (family:action-groups FR2)', async ({ + page, +}) => { + const {driver} = await openBar(page, 'no-selection'); + // No tab is selected, so there is no lens to show the press. + await expect(page.locator('[data-tab-bar-lens]')).toHaveCount(0); + const home = await itemCenter(page, 'Home'); + const library = await itemCenter(page, 'Library'); + const script = drag(home, library, {durationMs: 500, restMs: 300}); + await driver.play(script, { + onEvent: async (_step, index) => { + if (index === 0) { + await expect(tab(page, 'Home')).toHaveAttribute('data-tab-bar-pressed'); + await expect.poll(() => itemPaint(page, 'Home')).not.toBe(TRANSPARENT); + } + // The finger is on Library, before the lift. + if (index === script.length - 2) { + await expect(tab(page, 'Library')).toHaveAttribute( + 'data-tab-bar-pressed', + ); + await expect(tab(page, 'Home')).not.toHaveAttribute( + 'data-tab-bar-pressed', + ); + } + }, + }); + await expect(tab(page, 'Library')).toHaveAttribute('aria-selected', 'true'); +}); + +test('with Reduce Motion a finger paints its tab at once, and its release keeps a fade of 200 ms or less, even on a slow theme (design:reduced-motion DEC-4)', async ({ + page, +}) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + const {driver} = await openBar(page, 'no-selection'); + await setExitDuration(page, '300ms'); + const home = await itemCenter(page, 'Home'); + await driver.play(tapScript(home, {holdMs: 400}), { + onEvent: async (_step, index) => { + if (index === 0) { + await expect(tab(page, 'Home')).toHaveAttribute('data-tab-bar-pressed'); + expect(await itemPaint(page, 'Home')).not.toBe(TRANSPARENT); + expect(await paintFadeMs(page, 'Home')).toBe(0); + } + }, + }); + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true'); + await expect(tab(page, 'Home')).not.toHaveAttribute('data-tab-bar-pressed'); + expect(await paintFadeMs(page, 'Home')).toBe(200); +}); + +test('a finger’s release fades the paint on the theme’s exit duration and curve, and its onset is at once', async ({ + page, +}) => { + const {driver} = await openBar(page, 'no-selection'); + // An exit duration apart from the fast one, so the read tells them apart. + await setExitDuration(page, '90ms'); + const home = await itemCenter(page, 'Home'); + await driver.play(tapScript(home, {holdMs: 400}), { + onEvent: async (_step, index) => { + if (index === 0) { + await expect(tab(page, 'Home')).toHaveAttribute('data-tab-bar-pressed'); + expect(await paintFadeMs(page, 'Home')).toBe(0); + } + }, + }); + await expect(tab(page, 'Home')).not.toHaveAttribute('data-tab-bar-pressed'); + const {have, want} = await paintTimingAgainst(page, 'Home', { + duration: 'var(--duration-exit)', + easing: 'var(--ease-exit)', + }); + expect(want.ms).toBe(90); + expect(have).toEqual(want); +}); + +test('past the last item, still on the bar, the lens rubber-bands beyond it and the lift commits the last item; past the bar’s end the lift chooses nothing', async ({ + page, +}) => { + const {driver} = await openBar(page); + const home = await itemCenter(page, 'Home'); + const profile = await itemCenter(page, 'Profile'); + const left = await capsuleLeft(page); + const right = await page + .getByRole('tablist') + .evaluate(element => (element as HTMLElement).offsetWidth); + // Two px inside the bar's trailing end. + const inside = {x: left + right - 2, y: profile.y}; + const script = drag(home, inside, {durationMs: 500, restMs: 900}); + let past = NaN; + await driver.play(script, { + onEvent: async (_step, index) => { + if (index === script.length - 2) { + await page.waitForTimeout(800); + const lens = (await translateX(lensBody(page))) + (home.x - left); + past = lens - (profile.x - left); + } + }, + }); + // Rubber-banded: past the last item, but by less than the finger is. + expect(past).toBeGreaterThan(0.5); + expect(past).toBeLessThan(inside.x - profile.x); + await expect(tab(page, 'Profile')).toHaveAttribute('aria-selected', 'true'); + // Past the bar's end the finger is off the bar: the lift chooses nothing. + await driver.play( + drag( + profile, + {x: left + right + 20, y: profile.y}, + {durationMs: 400, restMs: 300}, + ), + ); + await expect(tab(page, 'Profile')).toHaveAttribute('aria-selected', 'true'); + await expect(page.getByTestId('reselects')).toHaveText('Reselected 0 times'); +}); + +test('a vertical drag that starts on the bar never scrolls the page, and lifted off the bar it chooses nothing', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'native scrolling from injected touches is Chromium-only in Playwright', + ); + const {driver} = await openBar(page); + const library = await itemCenter(page, 'Library'); + const before = await page.evaluate(() => window.scrollY); + await driver.play( + drag(library, {x: library.x, y: library.y - 300}, {durationMs: 300}), + ); + await page.waitForTimeout(300); + expect(await page.evaluate(() => window.scrollY)).toBe(before); + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true'); +}); + +test('the slide keeps advancing 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)', + ); + const {driver} = await openBar(page); + const body = lensBody(page); + const profile = await itemCenter(page, 'Profile'); + await markElement(body); + // The compositor's own control rides in the same cast. A stall the compositor + // itself makes on a loaded runner stalls it too. So the move is judged + // against what the compositor presented, not against a fixed bound. + await startBusyControl(page); + const cast = await startScreencast(page); + // Armed before the tap, the page blocks itself in the frame that sees the + // slide running. One evaluate sees it and blocks, so no runner latency + // between the two can eat the slide first. The judged part ends where the + // lens settles (settledWithin). + const blocking = blockMainThread(page, 600, {during: body}); + await driver.tap(profile); + const block = await blocking; + await page.waitForTimeout(150); + const castFrames = await cast.stop(); + const tracked = await trackMarker(page, castFrames); + const control = await trackMarker(page, castFrames, {rgb: CONTROL_RGB}); + const proof = busyWindowProof( + tracked, + {from: block.from, to: block.to}, + { + axis: 'x', + settledWithin: 2, + // Screencast throughput, not the animation: no display-rate bound. + maxMedianFrameMs: Infinity, + control, + }, + ); + await writeEvidence( + 'busy-main-thread/tabbar-lens-travel', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {block, proof}, + null, + 1, + ), + }, + testInfo, + ); + const film = await castStoryboard(page, castFrames, { + name: 'tabbar-lens-travel-busy-main-thread', + zero: block.from, + from: block.from - 40, + to: proof.judged.to + 40, + columns: 8, + cellScale: 0.35, + data: t => ({x: tracked.find(f => f.t === t)?.box?.x ?? -1}), + }); + await film.write(testInfo, {block}); + // The harness's verdict: no stall past two dropped screencast frames, and the + // frames moving. A loaded machine drops a frame or two; a frozen slide + // presents none. + expect( + proof.verdict.pass, + `${proof.summary}; ${proof.verdict.failures.join('; ')}`, + ).toBe(true); +}); + +/** + * Notes, on the page, when the DOM change an action makes has rendered. That is + * three frames after the first change once armed (with `attribute`, the first + * that changes it). The three frames are the one that styles, lays out and + * paints the change, the one that paints its animations' layers, and a clean + * one. A rendering proof counts per-frame work from there, not from a fixed + * delay a loaded machine stretches. + */ +async function noteSettle(page: Page, attribute?: string) { + await page.evaluate(attribute => { + const w = window as unknown as {__tabBarSettledAt?: number}; + w.__tabBarSettledAt = 0; + const observer = new MutationObserver(records => { + if ( + attribute != null && + !records.some(record => record.attributeName === attribute) + ) { + return; + } + observer.disconnect(); + let frames = 3; + const next = () => { + frames -= 1; + if (frames === 0) { + w.__tabBarSettledAt = performance.timeOrigin + performance.now(); + return; + } + requestAnimationFrame(next); + }; + requestAnimationFrame(next); + }); + observer.observe(document.documentElement, { + attributes: true, + characterData: true, + childList: true, + subtree: true, + }); + }, attribute ?? null); +} + +/** When `noteSettle` noted the render, epoch ms on the page's clock (0: not yet). */ +const settledAt = (page: Page) => + page.evaluate( + () => + (window as unknown as {__tabBarSettledAt?: number}).__tabBarSettledAt ?? + 0, + ); + +test('a press, its lift, flex and travel, does no Layout or Paint per frame', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only'); + const {driver} = await openBar(page); + const capsule = page.getByRole('tablist'); + const target = await itemCenter(page, 'Profile'); + let press = {from: 0, to: 0}; + // Held for 700 ms: the lens travels, lifts and the bar flexes with no render + // at all. Counted from three frames after the press's own DOM change (its + // render, then the layers its new animations take), not from a fixed delay. + // The count runs until the finger lifts, by the page's own lift time. Nothing + // renders in between, the curves' ends included. + await noteSettle(page); + const trace = await traceRendering(page, async () => { + const playing = driver.play(tapScript(target, {holdMs: 700})); + [press] = await waitForAnimation(capsule); + await playing; + await waitForRest(capsule); + }); + const from = await settledAt(page); + expect(from, 'the press changed no DOM').toBeGreaterThan(0); + const to = await page.evaluate( + () => + performance.timeOrigin + + ((window as unknown as {__tabBarLifted?: number}).__tabBarLifted ?? 0), + ); + expect(to - from, 'counted window, ms').toBeGreaterThan(100); + const during = countBetween(trace, from, to); + const when = trace.events + .filter(e => e.name === 'Layout' || e.name === 'Paint') + .map(e => `${e.name}@${Math.round(e.t - press.from)}`); + expect(during.Layout ?? 0, JSON.stringify({during, when})).toBe(0); + expect(during.Paint ?? 0, JSON.stringify({during, when})).toBe(0); + await expect(tab(page, 'Profile')).toHaveAttribute('aria-selected', 'true'); +}); + +/** The document's timeline now, to read only the animations a change starts. */ +const timelineNow = (page: Page) => + page.evaluate(() => Number(document.timeline.currentTime ?? 0)); + +/** + * Every animation running in the document (CSS transitions included) that + * started at or after `since`, as the reduced-motion checks read it. For each: + * the properties its keyframes interpolate, and when its curve reaches its end + * value (the animator holds the end after it). A value that only jumps, at one + * offset, moves nothing on screen. The animator's own are read from the page's + * log too, so one that ended before the read (a cross-fade is short) is still + * read. + */ +async function runningAnimations(page: Page, since = 0) { + return page.evaluate(since => { + const meta = ['offset', 'computedOffset', 'easing', 'composite']; + const made = ( + ( + window as unknown as { + __tabBarMade?: {animation: Animation; at: number}[]; + } + ).__tabBarMade ?? [] + ) + .filter(entry => entry.at >= since - 50) + .map(entry => entry.animation); + const running = document + .getAnimations() + .filter( + animation => + animation.startTime == null || + Number(animation.startTime) >= since - 50, + ); + return [...new Set([...running, ...made])].map(animation => { + const effect = animation.effect as KeyframeEffect; + const frames = effect.getKeyframes(); + const keys = [ + ...new Set(frames.flatMap(frame => Object.keys(frame))), + ].filter(key => !meta.includes(key)); + const value = (frame: ComputedKeyframe, key: string) => + String(frame[key]); + const interpolated = keys.filter(key => + frames.some( + (frame, index) => + index > 0 && + frame.computedOffset !== frames[index - 1].computedOffset && + value(frame, key) !== value(frames[index - 1], key), + ), + ); + const last = frames[frames.length - 1]; + let end = frames.length - 1; + while ( + end > 0 && + keys.every(key => value(frames[end - 1], key) === value(last, key)) + ) { + end -= 1; + } + const timing = effect.getTiming(); + return { + properties: interpolated, + endsMs: + Number(timing.delay ?? 0) + + (frames[end]?.computedOffset ?? 0) * Number(timing.duration), + }; + }); + }, since); +} + +/** + * design:reduced-motion DR2, on a touch screen: the change cross-fades, every + * animation it starts changes opacity only and ends within 200 ms. + */ +async function expectCrossFade(page: Page, since = 0) { + await expect + .poll( + async () => + (await runningAnimations(page, since)).some( + animation => + animation.properties.includes('opacity') && animation.endsMs > 0, + ), + {message: 'no cross-fade', timeout: 2000}, + ) + .toBe(true); + assertCrossFade(await runningAnimations(page, since)); +} + +/** design:reduced-motion DR2 on animations already read. */ +function assertCrossFade( + animations: Awaited>, +) { + expect( + animations.some( + animation => + animation.properties.includes('opacity') && animation.endsMs > 0, + ), + `no cross-fade: ${JSON.stringify(animations)}`, + ).toBe(true); + assertOpacityOnly(animations); +} + +/** + * design:reduced-motion DR2 on animations already read, the fade itself not + * required: every one changes opacity only and ends within 200 ms. + */ +function assertOpacityOnly( + animations: Awaited>, +) { + for (const animation of animations) { + expect( + animation.properties.filter(property => property !== 'opacity'), + JSON.stringify(animations), + ).toEqual([]); + expect(animation.endsMs, JSON.stringify(animations)).toBeLessThanOrEqual( + 200, + ); + } +} + +/** design:reduced-motion DR3, under a mouse: nothing animates. */ +async function expectNoMotion(page: Page, since = 0) { + await page.waitForTimeout(150); + const animations = await runningAnimations(page, since); + expect( + animations.filter(animation => animation.properties.length > 0), + JSON.stringify(animations), + ).toEqual([]); +} + +/** A tab's label: its weight tells the selected look from the plain one. */ +const labelWeight = (page: Page, name: string) => + tab(page, name) + .locator(':scope > span > span') + .nth(1) + .evaluate(element => getComputedStyle(element).fontWeight); + +test('at rest the selected tab draws its own look; the copy of the items rides in the lens only while it slides', async ({ + page, +}) => { + const {driver} = await openBar(page); + // At rest each item is drawn once, the selected one in its selected look. + await expect(lensCopy(page)).toHaveCount(0); + expect(await labelWeight(page, 'Home')).toBe('600'); + expect(await labelWeight(page, 'Browse')).not.toBe('600'); + await driver.tap(await itemCenter(page, 'Browse')); + // While the lens slides, the selected look rides inside it… + await expect(lensCopy(page)).toHaveCount(1); + expect(await labelWeight(page, 'Browse')).not.toBe('600'); + // …and once it rests the copy goes and the tab draws it again. + await waitForRest(lensBody(page)); + await expect(lensCopy(page)).toHaveCount(0); + expect(await labelWeight(page, 'Browse')).toBe('600'); + expect(await labelWeight(page, 'Home')).not.toBe('600'); +}); + +test.describe('with Reduce Motion (design:reduced-motion)', () => { + test('on a touch screen a tap cross-fades the lens: opacity only, within 200 ms', async ({ + page, + }) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + const {driver} = await openBar(page); + const to = await itemCenter(page, 'Browse'); + const since = await timelineNow(page); + await driver.tap(to); + // The fade starts with the touch; the selection follows the lift a few + // frames later. + await expectCrossFade(page, since); + await expect(tab(page, 'Browse')).toHaveAttribute('aria-selected', 'true'); + assertOpacityOnly(await runningAnimations(page, since)); + await waitForRest(lensBody(page)); + expect(Math.abs((await lensCenterX(page)) - to.x)).toBeLessThan(0.5); + }); + + test('a press neither lifts nor flexes, and a drag’s release cross-fades the settle', async ({ + page, + browserName, + }) => { + test.skip( + browserName !== 'chromium', + 'only Chromium’s touches can be read mid-script', + ); + await page.emulateMedia({reducedMotion: 'reduce'}); + const {driver} = await openBar(page); + const home = await itemCenter(page, 'Home'); + const library = await itemCenter(page, 'Library'); + let held: unknown = null; + await driver.play(tapScript(home, {holdMs: 200}), { + onEvent: async step => { + if (step.type === 'touchStart') { + await page.waitForTimeout(120); + held = { + lens: await scaleOf(lensBody(page)), + bar: await scaleOf(page.getByRole('tablist')), + }; + } + }, + }); + expect(held).toEqual({lens: {x: 1, y: 1}, bar: {x: 1, y: 1}}); + // The lens follows the finger through the drag (direct manipulation); the + // settle its release starts is a transition, so it cross-fades (DR2). + await driver.play(drag(home, library, {durationMs: 400, restMs: 300})); + // Since the page's own lift, not a read the test makes after it. + const released = await liftedAt(page); + expect(released, 'no lift reached the page').toBeGreaterThan(0); + // The fade starts with the input; what it changes follows a few + // frames later. + await expectCrossFade(page, released); + await expect(tab(page, 'Library')).toHaveAttribute('aria-selected', 'true'); + assertOpacityOnly(await runningAnimations(page, released)); + }); +}); + +/** The lens's CSS slide under a mouse: its duration and running transitions. */ +const cssSlide = async (page: Page) => + page.locator('[data-tab-bar-lens]').evaluate(element => ({ + duration: getComputedStyle(element).transitionDuration, + transitions: element + .getAnimations() + .filter(animation => animation instanceof CSSTransition).length, + })); + +/** + * Counts, on the page from now, the CSS transitions the lens starts (one + * transitionrun per property), for `expectCssSlide`. Call it before the + * action that slides the lens. + */ +async function watchCssSlide(page: Page) { + await page.locator('[data-tab-bar-lens]').evaluate(element => { + const w = window as unknown as {__tabBarSlides?: number}; + w.__tabBarSlides = 0; + element.addEventListener('transitionrun', event => { + if (event.target === element) { + w.__tabBarSlides = (w.__tabBarSlides ?? 0) + 1; + } + }); + }); +} + +/** + * Under a mouse the lens slides in CSS on the theme's motion, and its body, + * which the animator moves under a finger, never animates. + */ +async function expectCssSlide(page: Page, {isRunning = true} = {}) { + expect((await cssSlide(page)).duration).not.toBe('0s'); + if (isRunning) { + // Counted on the page from `watchCssSlide`, so a short slide that ends + // before this looks is still seen. + await expect + .poll(() => + page.evaluate( + () => + (window as unknown as {__tabBarSlides?: number}).__tabBarSlides ?? + 0, + ), + ) + .toBe(1); + } + expect( + await lensBody(page).evaluate(element => element.getAnimations().length), + ).toBe(0); +} + +test.describe('touch work costs nothing under a fine pointer', () => { + test.describe('under a mouse', () => { + test.use({hasTouch: false, isMobile: false}); + + test('a click chooses a tab, and so do the keys', async ({page}) => { + await expectFinePointer(page); + await openBar(page); + // The click chooses the tab, as a button's does. + await tab(page, 'Library').click(); + await expect(tab(page, 'Library')).toHaveAttribute( + 'aria-selected', + 'true', + ); + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'false'); + // And from the keyboard, the other route a fine pointer leaves. + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('Enter'); + await expect(tab(page, 'Browse')).toHaveAttribute( + 'aria-selected', + 'true', + ); + }); + + test('a click reports its choice once, and never as a reselect too', async ({ + page, + }) => { + await expectFinePointer(page); + await openBar(page, 'removed-on-lift'); + await page.evaluate(() => { + (window as unknown as {__tabBarChanges: string[]}).__tabBarChanges = []; + }); + await tab(page, 'Library').click(); + await expect(tab(page, 'Library')).toHaveAttribute( + 'aria-selected', + 'true', + ); + // The click chooses Library once. Reported again, it would reach the + // newly selected tab as a reselect. + await page.waitForTimeout(300); + expect( + await page.evaluate( + () => + (window as unknown as {__tabBarChanges: string[]}).__tabBarChanges, + ), + ).toEqual(['library']); + await expect(page.getByTestId('reselects')).toHaveText( + 'Reselected 0 times', + ); + }); + + test('with Reduce Motion a click moves the lens at once', async ({ + page, + }) => { + await expectFinePointer(page); + await page.emulateMedia({reducedMotion: 'reduce'}); + await openStory(page, storybook(), 'lab-tabbar--default'); + await expect(page.getByRole('tablist', {name: 'Sections'})).toBeVisible(); + const since = await timelineNow(page); + await tab(page, 'Browse').click(); + await expect(tab(page, 'Browse')).toHaveAttribute( + 'aria-selected', + 'true', + ); + await expectNoMotion(page, since); + }); + + test('a click draws no copy of the items', async ({page}) => { + await expectFinePointer(page); + await openStory(page, storybook(), 'lab-tabbar--default'); + await expect(page.getByRole('tablist', {name: 'Sections'})).toBeVisible(); + await tab(page, 'Browse').click(); + await expect(tab(page, 'Browse')).toHaveAttribute( + 'aria-selected', + 'true', + ); + // The selected look moves to the tab at once; the lens slides under it. + expect(await labelWeight(page, 'Browse')).toBe('600'); + await expect(lensCopy(page)).toHaveCount(0); + await page.waitForTimeout(400); + await expect(lensCopy(page)).toHaveCount(0); + }); + + test('the bar sets no selection or callout override of its own', async ({ + page, + }) => { + await expectFinePointer(page); + await openStory(page, storybook(), 'lab-tabbar--default'); + const capsule = page.getByRole('tablist', {name: 'Sections'}); + await expect(capsule).toBeVisible(); + // Under a finger the gesture host owns them while a finger is down; + // under a mouse desktop selection is unchanged. + expect( + await capsule.evaluate(element => getComputedStyle(element).userSelect), + ).not.toBe('none'); + }); + + test('a click slides the lens on the theme’s motion', async ({page}) => { + await expectFinePointer(page); + await openStory(page, storybook(), 'lab-tabbar--default'); + await expect(page.getByRole('tablist', {name: 'Sections'})).toBeVisible(); + await watchCssSlide(page); + await tab(page, 'Browse').click(); + await expect(tab(page, 'Browse')).toHaveAttribute( + 'aria-selected', + 'true', + ); + await expectCssSlide(page); + }); + }); +}); + +test('in the touch presentation the bar claims a finger on its own element: one touchmove listener', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'listener counts read CDP (Chromium)'); + await openBar(page); + const listeners = await cdpListeners(page); + expect( + await listeners('document.querySelector(\'[role="tablist"]\')'), + ).toEqual(['touchmove']); +}); + +test('a switch to a fine pointer under a held finger ends the press: the lens lands back and the copy goes', async ({ + page, +}) => { + await page.addInitScript(PRESENTATION_SWITCH); + const {driver} = await openBar(page); + const home = await itemCenter(page, 'Home'); + const library = await itemCenter(page, 'Library'); + await driver.play(tapScript(library, {holdMs: 600}), { + onEvent: async (_step, index) => { + if (index === 0) { + // Lifted under the finger first. + await expect(lensCopy(page)).toHaveCount(1); + await page.evaluate(() => + ( + window as unknown as {__setCoarse: (value: boolean) => void} + ).__setCoarse(false), + ); + await expect(lensCopy(page)).toHaveCount(0); + await expect + .poll(async () => Math.abs((await lensCenterX(page)) - home.x)) + .toBeLessThan(0.5); + await expect.poll(() => scaleOf(lensBody(page))).toEqual({x: 1, y: 1}); + } + }, + }); +}); + +test('a switch to a fine pointer under a held finger takes its paint off the tab', async ({ + page, +}) => { + await page.addInitScript(PRESENTATION_SWITCH); + const {driver} = await openBar(page, 'no-selection'); + const home = await itemCenter(page, 'Home'); + await driver.play(tapScript(home, {holdMs: 600}), { + onEvent: async (_step, index) => { + if (index === 0) { + await expect(tab(page, 'Home')).toHaveAttribute('data-tab-bar-pressed'); + await page.evaluate(() => + ( + window as unknown as {__setCoarse: (value: boolean) => void} + ).__setCoarse(false), + ); + await expect(page.locator('[data-tab-bar-pressed]')).toHaveCount(0); + } + }, + }); + await expect(page.locator('[data-tab-bar-pressed]')).toHaveCount(0); +}); + +test.describe('under a fine pointer a press is a plain button press (family:action-groups FR1, FR5, DEC-1)', () => { + test.use({hasTouch: false, isMobile: false}); + + /** Opens the default bar under the context's fine pointer. */ + async function openFine(page: Page) { + await expectFinePointer(page); + await openStory(page, storybook(), 'lab-tabbar--default'); + await expect(page.getByRole('tablist', {name: 'Sections'})).toBeVisible(); + } + + test('a mouse press paints nothing, and dragged to another tab it moves no lens and chooses nothing', async ({ + page, + }) => { + await openFine(page); + // On screen first: the lens, on Home. + await expectPainted(lensBody(page)); + const home = await itemCenter(page, 'Home'); + const library = await itemCenter(page, 'Library'); + const browse = await itemCenter(page, 'Browse'); + await page.mouse.move(library.x, library.y); + await page.mouse.down(); + for (let step = 1; step <= 12; step++) { + await page.mouse.move( + library.x + ((browse.x - library.x) * step) / 12, + library.y, + ); + } + await page.waitForTimeout(300); + // Held, the press paints no tab and carries no lens. + await expect(page.locator('[data-tab-bar-pressed]')).toHaveCount(0); + expect(Math.abs((await lensCenterX(page)) - home.x)).toBeLessThan(0.5); + await page.mouse.up(); + await page.waitForTimeout(300); + // Released over another tab, it chooses nothing, as a button's press does. + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true'); + await expect(page.getByTestId('reselects')).toHaveText( + 'Reselected 0 times', + ); + }); + + test('a mouse press released off the bar chooses nothing, a tab or a reselect, as a button’s does', async ({ + page, + }) => { + await openFine(page); + const slideOff = async (name: string) => { + const start = await itemCenter(page, name); + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + for (let step = 1; step <= 8; step++) { + await page.mouse.move(start.x, start.y - 15 * step); + } + await page.mouse.up(); + await page.waitForTimeout(300); + }; + await slideOff('Library'); + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true'); + await slideOff('Home'); + await expect(page.getByTestId('reselects')).toHaveText( + 'Reselected 0 times', + ); + // The lens never left the selected tab. + const home = await itemCenter(page, 'Home'); + expect(Math.abs((await lensCenterX(page)) - home.x)).toBeLessThan(0.5); + }); + + test('under a fine primary pointer the capsule keeps touch-action: manipulation (spec:AST-094 FR18)', async ({ + page, + }) => { + await openFine(page); + // TabBar's capsule style sets it whatever the primary pointer, so a + // touchscreen laptop's double tap never zooms the page. + expect( + await page + .getByRole('tablist', {name: 'Sections'}) + .evaluate(element => getComputedStyle(element).touchAction), + ).toBe('manipulation'); + }); + + test('a pen dragged to another tab chooses nothing, as a button’s press does', async ({ + page, + }) => { + await openFine(page); + const input = await webInputDriver(page); + test.skip(!input.pens, PEN_SKIP); + const start = await itemCenter(page, 'Home'); + const end = await itemCenter(page, 'Profile'); + await input.pen( + Array.from({length: 13}, (_, step) => ({ + x: start.x + ((end.x - start.x) * step) / 12, + y: start.y, + t: step * 16, + })), + ); + await page.waitForTimeout(300); + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true'); + await expect(lensCopy(page)).toHaveCount(0); + }); + + test('a pen released off the bar chooses nothing, as a button’s press does', async ({ + page, + }) => { + await openFine(page); + const input = await webInputDriver(page); + test.skip(!input.pens, PEN_SKIP); + const start = await itemCenter(page, 'Library'); + await input.pen( + Array.from({length: 9}, (_, step) => ({ + x: start.x, + y: start.y - 15 * step, + t: step * 16, + })), + ); + await page.waitForTimeout(300); + await expect(tab(page, 'Home')).toHaveAttribute('aria-selected', 'true'); + }); + + test('the bar adds no gesture listener, on its element or on the page during a press', async ({ + page, + browserName, + }) => { + test.skip( + browserName !== 'chromium', + 'listener counts read CDP (Chromium)', + ); + await openFine(page); + const listeners = await cdpListeners(page); + // The reader's own control: a listener planted on a probe shows up. + await page.evaluate(() => { + const probe = document.createElement('div'); + probe.id = 'listener-probe'; + probe.addEventListener('pointerdown', () => {}); + document.body.append(probe); + }); + expect( + await listeners("document.getElementById('listener-probe')"), + ).toEqual(['pointerdown']); + const pageLevel = async () => [ + ...(await listeners('document')).map(entry => `document:${entry}`), + ...(await listeners('window')).map(entry => `window:${entry}`), + ]; + /** What `after` adds to `before` and what it drops, counting repeats. */ + const delta = (before: string[], after: string[]) => { + const added = [...after]; + const removed: string[] = []; + for (const entry of before) { + const index = added.indexOf(entry); + if (index < 0) { + removed.push(entry); + } else { + added.splice(index, 1); + } + } + return {added, removed}; + }; + const capsule = 'document.querySelector(\'[role="tablist"]\')'; + // Nothing listens on the bar itself: its tabs are plain buttons. + expect(await listeners(capsule)).toEqual([]); + // openStory returns while Storybook is still completing the story's render. + // Its own decorators' effects (the measure addon's document pointermove + // among them) run when the render finishes, so the baseline waits for that. + await page.waitForFunction( + () => + ( + window as unknown as { + __STORYBOOK_PREVIEW__?: {currentRender?: {phase?: string}}; + } + ).__STORYBOOK_PREVIEW__?.currentRender?.phase === 'finished', + ); + // The tabs are read first: Playwright's own locator reads add its + // listeners to the window, which are the harness's, not the page's. + const library = await itemCenter(page, 'Library'); + const browse = await itemCenter(page, 'Browse'); + const atRest = await pageLevel(); + const press = async ({x, y}: {x: number; y: number}) => { + await page.mouse.move(x, y); + await page.mouse.down(); + const during = await pageLevel(); + await page.mouse.up(); + return during; + }; + // A press adds no listener to the page, and leaves none behind. + expect(delta(atRest, await press(library)).added).toEqual([]); + expect(delta(atRest, await press(browse)).added).toEqual([]); + expect(delta(atRest, await pageLevel())).toEqual({added: [], removed: []}); + }); +}); + +test( + 'storyboard: a selection from rest slides the lens (a touch first moves it under the finger: see the press storyboard)', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + const {bar} = await openBar(page); + await tab(page, 'Home').focus(); + for (let i = 0; i < 3; i += 1) { + await page.keyboard.press('ArrowRight'); + } + await page.keyboard.press('Enter'); + await expect(tab(page, 'Profile')).toHaveAttribute('aria-selected', 'true'); + await waitForAnimation(lensBody(page)); + const box = await bar.boundingBox(); + if (box == null) { + throw new Error('no bar'); + } + const {storyboard} = await animationStoryboard(page, { + name: 'tabbar-lens-travel', + clip: { + x: 0, + y: box.y - 12, + width: box.x * 2 + box.width, + height: box.height + 24, + }, + times: Array.from({length: 37}, (_, i) => i * 16.667), + measure: async () => ({x: await translateX(lensBody(page))}), + columns: 6, + cellScale: 0.6, + }); + await storyboard.write(testInfo); + await releaseAnimations(page, {finish: true}); + const xs = storyboard.frames.map(f => (f.data as {x: number}).x); + expect(xs[0]).toBeLessThan(-200); + expect(Math.abs(xs.at(-1) ?? Infinity)).toBeLessThan(2); + }, +); + +test( + 'storyboard: a finger lands, drags across the bar and lifts', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + const {driver, bar} = await openBar(page); + const home = await itemCenter(page, 'Home'); + const browse = await itemCenter(page, 'Browse'); + const box = await bar.boundingBox(); + if (box == null) { + throw new Error('no bar'); + } + const storyboard = await touchStoryboard( + page, + driver, + drag(home, browse, {durationMs: 400, hz: 20, holdMs: 250, restMs: 250}), + { + name: 'tabbar-press-drag', + clip: { + x: 0, + y: box.y - 16, + width: box.x * 2 + box.width, + height: box.height + 32, + }, + measure: async () => ({ + x: await translateX(lensBody(page)), + lift: (await scaleOf(lensBody(page))).x, + flex: (await scaleOf(bar)).x, + }), + columns: 5, + cellScale: 0.6, + }, + ); + await storyboard.write(testInfo); + await expect(tab(page, 'Browse')).toHaveAttribute('aria-selected', 'true'); + const frames = storyboard.frames.map( + f => f.data as {lift: number; flex: number}, + ); + // Lifted and flexed while the finger is down. + expect(Math.max(...frames.map(f => f.lift))).toBeGreaterThan(1.1); + expect(Math.max(...frames.map(f => f.flex))).toBeGreaterThan(1.03); + }, +); diff --git a/packages/lab/src/TabBar/index.ts b/packages/lab/src/TabBar/index.ts new file mode 100644 index 0000000000000..7441666a5ee7f --- /dev/null +++ b/packages/lab/src/TabBar/index.ts @@ -0,0 +1,13 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file index.ts + * @input Imports from TabBar.tsx + * @output Re-exports TabBar, TabBarItem and their types + * @position Barrel export; consumed by packages/lab/src/index.ts + */ + +export {TabBar, TabBarItem} from './TabBar'; +export type {TabBarItemProps, TabBarProps} from './TabBar'; diff --git a/packages/lab/src/TabBar/tabBar.stylex.ts b/packages/lab/src/TabBar/tabBar.stylex.ts new file mode 100644 index 0000000000000..eb4b35236f428 --- /dev/null +++ b/packages/lab/src/TabBar/tabBar.stylex.ts @@ -0,0 +1,18 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file tabBar.stylex.ts + * @input StyleX marker system + * @output tabBarItemMarker — a scoped marker on each TabBar item button + * @position Shared StyleX marker consumed by TabBar.tsx + * + * The item buttons span the whole capsule between their neighbours, so a press + * anywhere goes to the nearest item, as on iOS. The focus ring belongs on the + * 76 × 54 item inside. The ring keys off + * `stylex.when.ancestor(':focus-visible', tabBarItemMarker)`. + */ + +import * as stylex from '@stylexjs/stylex'; + +export const tabBarItemMarker: ReturnType = + stylex.defineMarker(); diff --git a/packages/lab/src/TabBar/tabBarModel.test.ts b/packages/lab/src/TabBar/tabBarModel.test.ts new file mode 100644 index 0000000000000..9cbcbd7f2c3f4 --- /dev/null +++ b/packages/lab/src/TabBar/tabBarModel.test.ts @@ -0,0 +1,202 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file tabBarModel.test.ts + * @input vitest and tabBarModel.ts + * @output Checks TabBar's geometry against UIKit's layouts measured on iOS + * 26.2: the capsule's width, the items' width and centres, and right to + * left. Also the item a lift commits, the rubber band, the lifted lens and + * the copy's counter-transform. + * @position Testing; pure math, no DOM + */ + +import {describe, expect, it} from 'vitest'; +import {tabBar} from './uikitTabBar'; +import { + copyTransform, + itemCenters, + itemWidth, + itemWidthCss, + lensTarget, + liftScale, + naturalWidth, + nearestIndex, +} from './tabBarModel'; + +/** + * UIKit's layouts: capsule width, then the items' screen x and width (the + * capsule's own x subtracted below). + */ +const UIKIT_LAYOUTS = [ + {label: '2 tabs', capsuleX: 107, capsule: 188, width: 94, xs: [111, 197]}, + {label: '3 tabs', capsuleX: 64, capsule: 274, width: 94, xs: [68, 154, 240]}, + { + label: '4 tabs', + capsuleX: 21, + capsule: 360, + width: 98, + xs: [25, 109.67, 194.33, 279], + }, + { + label: '5 tabs', + capsuleX: 21, + capsule: 360, + width: 77, + xs: [25, 93.75, 162.5, 231.25, 300], + }, + { + label: '3 tabs and search', + capsuleX: 21, + capsule: 290, + width: 100.67, + xs: [25, 115.67, 206.33], + }, + { + label: '4 tabs and search', + capsuleX: 21, + capsule: 290, + width: 76, + xs: [25, 93.67, 162.33, 231], + }, +]; + +describe('naturalWidth', () => { + it('is UIKit’s capsule for two and three tabs, and reaches the 360 pt screen with four', () => { + expect(naturalWidth(2)).toBe(188); + expect(naturalWidth(3)).toBe(274); + expect(naturalWidth(4)).toBe(360); + }); +}); + +describe('itemWidth and itemCenters', () => { + for (const layout of UIKIT_LAYOUTS) { + it(`match UIKit within a point: ${layout.label}`, () => { + const n = layout.xs.length; + expect( + Math.abs(itemWidth(layout.capsule, n) - layout.width), + ).toBeLessThan(1); + const centers = itemCenters(layout.capsule, n); + centers.forEach((center, i) => { + const uikit = layout.xs[i] - layout.capsuleX + layout.width / 2; + expect(Math.abs(center - uikit)).toBeLessThan(1); + }); + }); + } + + it('keeps the first and last items one inset from the edges, the rest evenly between', () => { + const centers = itemCenters(360, 5); + const size = itemWidth(360, 5); + expect(centers[0]).toBeCloseTo(4 + size / 2, 9); + expect(centers[4]).toBeCloseTo(360 - 4 - size / 2, 9); + const steps = centers.slice(1).map((center, i) => center - centers[i]); + for (const step of steps) { + expect(step).toBeCloseTo(steps[0], 9); + } + }); + + it('mirrors in a right-to-left capsule (the first item on the right)', () => { + expect(itemCenters(290, 4, true)).toEqual( + itemCenters(290, 4).map(x => 290 - x), + ); + }); + + it('centres a single item and has nothing for none', () => { + expect(itemCenters(200, 1)).toEqual([100]); + expect(itemCenters(200, 0)).toEqual([]); + }); + + it('spells the same width in CSS', () => { + expect(itemWidthCss(4)).toBe( + 'min(1.0659 * 100cqw / 4 + 0.0436 * 100cqw - 14.61px, 100cqw - 8px)', + ); + }); +}); + +describe('nearestIndex: the item a lift commits', () => { + const centers = itemCenters(290, 4); + + it('picks the nearest centre', () => { + expect(nearestIndex(centers[2] + 20, centers)).toBe(2); + expect(nearestIndex(centers[1] - 30, centers)).toBe(1); + }); + + it('gives a tie to the leading (earlier) item, as UIKit did between items 2 and 3', () => { + const midpoint = (centers[1] + centers[2]) / 2; + expect(nearestIndex(midpoint, centers)).toBe(1); + // In a right-to-left capsule the earlier item is on the right. + const rtl = itemCenters(290, 4, true); + expect(nearestIndex((rtl[1] + rtl[2]) / 2, rtl)).toBe(1); + }); + + it('commits the last item for a finger 60 px past it, and the first before it', () => { + expect(nearestIndex(centers[3] + 60, centers)).toBe(3); + expect(nearestIndex(-40, centers)).toBe(0); + }); +}); + +describe('lensTarget', () => { + const centers = itemCenters(290, 4); + + it('follows the finger between the first and last centres', () => { + expect(lensTarget(150, centers)).toBe(150); + }); + + it('rubber-bands past the ends: 60 px past the last item leaves the lens ~8 px past it', () => { + expect(lensTarget(centers[3] + 60, centers) - centers[3]).toBeCloseTo( + 7.98, + 1, + ); + expect(lensTarget(centers[0] - 60, centers) - centers[0]).toBeCloseTo( + -7.98, + 1, + ); + }); + + it('never passes the rubber band’s dimension however far the finger goes', () => { + expect(lensTarget(centers[3] + 10_000, centers) - centers[3]).toBeLessThan( + tabBar.lensEdgeDimension, + ); + }); +}); + +describe('liftScale', () => { + it('grows a 76 × 54 lens to 92 × 70, and a 98 px one to 114 px', () => { + const lifted = liftScale(76); + expect(76 * lifted.x).toBeCloseTo(92, 6); + expect(tabBar.itemHeight * lifted.y).toBeCloseTo(70, 6); + expect(98 * liftScale(98).x).toBeCloseTo(114, 6); + }); +}); + +describe('copyTransform', () => { + it('undoes the lens’s translate and scale about the same origin', () => { + // A point p in the copy maps to the lens as O + T_c + S_c (p − O). It then + // maps to the capsule as O + T + S (q − O), and the composition must be p. + const origin = {x: 38, y: 27}; + const lifted = liftScale(76); + for (const [x, sx, sy] of [ + [0, 1, 1], + [42.5, 1, 1], + [-80, lifted.x, lifted.y], + [13.25, 1.31, 0.87], + ]) { + const copy = copyTransform(x, sx, sy); + for (const p of [ + {x: 0, y: 0}, + {x: 120, y: 31}, + {x: -55.5, y: 9}, + ]) { + const q = { + x: origin.x + copy.x + copy.scaleX * (p.x - origin.x), + y: origin.y + copy.scaleY * (p.y - origin.y), + }; + const onScreen = { + x: origin.x + x + sx * (q.x - origin.x), + y: origin.y + sy * (q.y - origin.y), + }; + expect(onScreen.x).toBeCloseTo(p.x, 9); + expect(onScreen.y).toBeCloseTo(p.y, 9); + } + } + }); +}); diff --git a/packages/lab/src/TabBar/tabBarModel.ts b/packages/lab/src/TabBar/tabBarModel.ts new file mode 100644 index 0000000000000..1ab86f537798f --- /dev/null +++ b/packages/lab/src/TabBar/tabBarModel.ts @@ -0,0 +1,136 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file tabBarModel.ts + * @input TabBar's UIKit values (uikitTabBar.ts) + * @output TabBar's pure geometry: the items' widths and centres, the item a + * lift commits, and the lens's target and scale. + * @position Math of the lab TabBar; no DOM, no React. Coordinates are the + * capsule's own, in px, before its flex scale. x runs from its left edge, + * and items go in logical order. + * + * SYNC: When modified, update tabBarModel.test.ts, TabBar.tsx (its CSS + * spelling of the same geometry) and uikitTabBar.ts. + */ + +import {rubberBand} from '@astryxdesign/core/internal/touch'; +import {tabBar} from './uikitTabBar'; + +/** The widest a capsule of `count` tabs gets without a search tab, px. */ +export function naturalWidth(count: number): number { + return tabBar.naturalWidth.base + tabBar.naturalWidth.perTab * count; +} + +/** + * The width every item (and the resting lens) has in a capsule `width` px + * wide, never wider than the capsule's inside. + */ +export function itemWidth(width: number, count: number): number { + const {perSlot, perBar, offset} = tabBar.itemWidth; + return Math.min( + (perSlot * width) / Math.max(count, 1) + perBar * width + offset, + width - 2 * tabBar.itemInset, + ); +} + +/** + * The same width as a CSS expression of the capsule's width, `100cqw` (the + * capsule is the size container), for use inside `calc()`. + */ +export function itemWidthCss(count: number): string { + const {perSlot, perBar, offset} = tabBar.itemWidth; + const sign = offset < 0 ? '-' : '+'; + const inside = `100cqw - ${2 * tabBar.itemInset}px`; + return `min(${perSlot} * 100cqw / ${Math.max(count, 1)} + ${perBar} * 100cqw ${sign} ${Math.abs(offset)}px, ${inside})`; +} + +/** + * The centres of `count` items in a capsule `width` px wide, in logical order. + * The first and last items sit `itemInset` from the edges and the others are + * spread evenly between them. In a right-to-left capsule the first item is on + * the right. + */ +export function itemCenters( + width: number, + count: number, + isRtl = false, +): number[] { + if (count <= 0) { + return []; + } + const size = itemWidth(width, count); + const first = tabBar.itemInset + size / 2; + const centers = + count === 1 + ? [width / 2] + : Array.from( + {length: count}, + (_, i) => first + ((width - 2 * first) * i) / (count - 1), + ); + return isRtl ? centers.map(center => width - center) : centers; +} + +/** + * The item a finger lifted at `x` commits: the one whose centre is nearest, + * the earlier one on a tie. No projection: a flick commits where it lifts. + */ +export function nearestIndex( + x: number, + centers: ReadonlyArray, +): number { + let best = 0; + let bestDistance = Infinity; + centers.forEach((center, index) => { + const distance = Math.abs(x - center); + // Strictly nearer only: a tie keeps the earlier (leading) item. + if (distance < bestDistance - 1e-9) { + best = index; + bestDistance = distance; + } + }); + return best; +} + +/** + * Where the lens heads for a finger at `x`: the finger itself between the + * first and last centres, rubber-banded past them. + */ +export function lensTarget(x: number, centers: ReadonlyArray): number { + if (centers.length === 0) { + return x; + } + const min = Math.min(...centers); + const max = Math.max(...centers); + if (x < min) { + return min + rubberBand(x - min, tabBar.lensEdgeDimension); + } + if (x > max) { + return max + rubberBand(x - max, tabBar.lensEdgeDimension); + } + return x; +} + +/** + * The lifted lens's scale on each axis for items `width` px wide: the item + * grown by `liftOutset` on every side. + */ +export function liftScale(width: number): {x: number; y: number} { + return { + x: (width + 2 * tabBar.liftOutset) / width, + y: (tabBar.itemHeight + 2 * tabBar.liftOutset) / tabBar.itemHeight, + }; +} + +/** + * The selected copy of the items lives inside the lens, which moves by `x` and + * scales by (`scaleX`, `scaleY`) about its centre. Applied to the copy about + * the same point, this transform puts the copy back where the items are. So the + * lens shows the selected look of whatever is under it. + */ +export function copyTransform( + x: number, + scaleX: number, + scaleY: number, +): {x: number; scaleX: number; scaleY: number} { + return {x: -x / scaleX, scaleX: 1 / scaleX, scaleY: 1 / scaleY}; +} diff --git a/packages/lab/src/TabBar/uikitTabBar.test.ts b/packages/lab/src/TabBar/uikitTabBar.test.ts new file mode 100644 index 0000000000000..b86e77c27f0f0 --- /dev/null +++ b/packages/lab/src/TabBar/uikitTabBar.test.ts @@ -0,0 +1,168 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file uikitTabBar.test.ts + * @input vitest, uikitTabBar.ts and its source text + * @output Checks that every value of TabBar's UIKit table names an allowed + * source. A measurement names its iOS version and date, and a guess names + * an open measurement task. No value ships its source. + * @position Testing; validates uikitTabBar.ts without a browser, by the rules + * Core's UIKit table follows + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import {describe, expect, it} from 'vitest'; +import {tabBar} from './uikitTabBar'; + +const FILE = 'uikitTabBar.ts'; +const TEXT = fs.readFileSync(path.resolve(__dirname, FILE), 'utf8'); +// Where a number comes from is documentation: a value that carried it would +// ship it in every bundle that reads the value. +const PROVENANCE_KEYS = new Set(['source', 'guess', 'measure']); +/** A measurement names its subject, the iOS version it ran on and its date. */ +const MEASURED = + /^@source measured: .*iOS \d.*(\b20\d\d-\d\d-\d\d\b|\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* \d{1,2},? 20\d\d\b)/; +const SOURCE_KINDS = + /^@source (apple-docs https:\/\/developer\.apple\.com\/|wwdc \d{4}-\d+ |webkit Source\/|measured: .*iOS \d|GUESS — )/; + +interface Leaf { + key: string; + doc: string; +} + +/** A JSDoc line without its comment markers. */ +const bare = (line: string) => line.trim().replace(/^\/?\*+\/?\s?/, ''); + +/** + * Every leaf of the exported table with the JSDoc block right above it. A + * line ending in `{` opens a group (no source of its own); any other + * `key: value,` line is a leaf. + */ +function leaves(): Leaf[] { + const lines = TEXT.split('\n'); + const start = lines.findIndex(line => + /^export const tabBar = \{$/.test(line), + ); + expect(start, 'the table').toBeGreaterThan(-1); + const found: Leaf[] = []; + let doc = ''; + let inDoc = false; + const groupLeafCount: number[] = []; + for (const line of lines.slice(start + 1)) { + const trimmed = line.trim(); + if (trimmed.startsWith('/**')) { + inDoc = true; + doc = ''; + } + if (inDoc) { + doc += bare(trimmed) + '\n'; + if (trimmed.endsWith('*/')) { + inDoc = false; + } + continue; + } + if (trimmed === '' || trimmed.startsWith('//')) { + continue; + } + if (/^(\w+): \{$/.test(trimmed)) { + groupLeafCount.push(0); + doc = ''; + continue; + } + if (/^\},?$/.test(trimmed)) { + expect(groupLeafCount.pop(), 'an empty group').toBeGreaterThan(0); + continue; + } + if (trimmed.startsWith('} as const')) { + break; + } + const leaf = /^(\w+): .+,$/.exec(trimmed); + expect(leaf, `unexpected line ${JSON.stringify(trimmed)}`).not.toBeNull(); + if (leaf) { + found.push({key: leaf[1], doc}); + groupLeafCount.forEach((count, index) => { + groupLeafCount[index] = count + 1; + }); + } + doc = ''; + } + return found; +} + +/** The open measurement tasks the file lists above the table. */ +const OPEN = new Set( + TEXT.slice(0, TEXT.indexOf('export const tabBar')) + .split('\n') + .map(line => /^\s*\*\s+- (M-[A-Z0-9]+),/.exec(line)?.[1]) + .filter((id): id is string => id != null), +); + +/** The JSDoc rules every sourced value follows. */ +function expectSourced(key: string, doc: string) { + // Each tag with its continuation lines folded onto it. + const tags = doc + .split(/\n(?=@)/) + .map(tag => tag.replace(/\s*\n\s*/g, ' ').trim()) + .filter(tag => tag.startsWith('@')); + const sources = tags.filter(tag => tag.startsWith('@source ')); + expect(sources.length, `${key} has no @source`).toBeGreaterThan(0); + for (const source of sources) { + expect(source, `${key}: unknown source kind`).toMatch(SOURCE_KINDS); + if (source.startsWith('@source measured: ')) { + expect(source, `${key}: a measurement needs its date`).toMatch(MEASURED); + } + } + const measures = tags.filter(tag => tag.startsWith('@measure ')); + if (sources.some(source => /^@source (GUESS|webkit)/.test(source))) { + expect( + measures.length, + `${key} is unconfirmed but names no @measure task`, + ).toBeGreaterThan(0); + } + for (const measure of measures) { + const id = /^@measure (M-[A-Z0-9]+)$/.exec(measure)?.[1]; + expect(id, `${key}: malformed ${measure}`).toBeDefined(); + expect( + OPEN.has(id ?? ''), + `${id} is not listed as an open measurement`, + ).toBe(true); + } +} + +describe('TabBar UIKit table: every value is sourced', () => { + const found = leaves(); + + it('finds the table entries', () => { + expect(found.length).toBeGreaterThan(20); + expect(found.map(leaf => leaf.key)).toEqual( + expect.arrayContaining(['barHeight', 'lensTravel', 'lensTrack']), + ); + expect(Object.keys(tabBar)).toEqual( + expect.arrayContaining(['barHeight', 'lensTravel', 'lensTrack']), + ); + }); + + it('lists only open measurements a value names', () => { + for (const id of OPEN) { + expect(TEXT, `${id} names no value`).toMatch( + new RegExp(`@measure ${id}\\n`), + ); + } + }); + + for (const {key, doc} of found) { + it(key, () => { + expect( + PROVENANCE_KEYS.has(key), + `${key}: a source belongs in the JSDoc, not in the value`, + ).toBe(false); + expectSourced(key, doc); + }); + } + + it('ships no source in a value', () => { + const code = TEXT.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, ''); + expect(code).not.toMatch(/\b(source|guess|measure)\s*:/); + }); +}); diff --git a/packages/lab/src/TabBar/uikitTabBar.ts b/packages/lab/src/TabBar/uikitTabBar.ts new file mode 100644 index 0000000000000..e2eccde8daed6 --- /dev/null +++ b/packages/lab/src/TabBar/uikitTabBar.ts @@ -0,0 +1,243 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file uikitTabBar.ts + * @input Nothing; data only + * @output Exports `tabBar`: the iOS 26 floating tab bar's geometry, its + * badge, and the selection lens's springs and values. + * @position TabBar's own UIKit values, beside the component that reads them; + * read by its touch presentation and tabBarModel.ts + * + * SYNC: When modified, update tabBarModel.ts and uikitTabBar.test.ts. + */ + +/** + * Every value was read from a stock UITabBarController on the iOS 26.2 + * simulator, iPhone 17 Pro (402 × 874 pt, bottom safe area 34 pt). The + * controller held four UITabs and a UISearchTab, each a UINavigationController + * over a long table. The sources were the bar's view tree, its presentation + * frames every frame, the springs UIKit attached, and HID touches. Geometry is + * in points, in the bar's own coordinates unless a value says otherwise. + * Springs keep UIKit's terms (response in seconds, damping ratio). No value is + * a motion role: each plays as measured. + */ + +/** + * UITabBar on iOS 26 (floating, Liquid Glass). + */ +export const tabBar = { + /** + * The capsule that holds the items: 62 pt tall. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, `_UITabBarPlatterView` frame 290 × 62 at (21, 791), + * Oct 23 2026 + */ + barHeight: 62, + /** + * The capsule's distance from the screen's leading and trailing edges, and + * from its bottom edge. The capsule sits 13 pt inside the 34 pt home + * indicator area. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, iPhone + * 17 Pro, `_UITabBarPlatterView` at x 21 and y 791 + 62 = 853 on an 874 pt + * screen, Oct 23 2026 + */ + barInset: 21, + /** + * Without a search tab the capsule is no wider than 16 + 86 pt per tab. It is + * centred when that is narrower than the screen allows: 188 pt with two tabs, + * 274 with three. Four tabs reach the 360 pt an iPhone 17 Pro allows. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, iPhone + * 17 Pro, `_UITabBarPlatterView` 188 pt at x 107 (two tabs) and 274 pt at x + * 64 (three tabs), 360 pt at x 21 (four and five tabs), Oct 24 2026 + */ + naturalWidth: {base: 16, perTab: 86}, + /** + * Every item, and the resting lens over the selected one, has one width. For + * n tabs in a capsule P pt wide it is 1.0659 × P ÷ n + 0.0436 × P − 14.61. + * That is 98 for four tabs in 360 pt, and 76 with the search tab's 290 pt. + * The first and last items sit `itemInset` from the capsule's edges and the + * others are spread evenly between them, so neighbours overlap. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, iPhone + * 17 Pro, `_UITabButton` frames in eight layouts (two to five tabs, with + * and without the search tab): least-squares fit, within 1 pt of every row; + * one-letter labels give the same widths, a label wider than ~60 pt widens + * every item (not modelled), Oct 24 2026 + */ + itemWidth: {perSlot: 1.0659, perBar: 0.0436, offset: -14.61}, + /** + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, `_UITabButton` 54 pt tall at y 795, Oct 23 2026 + */ + itemHeight: 54, + /** + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, items at y 795 in the capsule at y 791, the first at + * x 25 in the capsule at x 21, Oct 23 2026 + */ + itemInset: 4, + /** + * The icon's box, centred in the item 20 pt below its top. SF Symbols render + * 25 to 29 pt tall and 25 to 33 pt wide in the stock bar. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, iPhone + * 17 Pro, `UIImageView` frames (33.3 × 28, 27 × 25, 33.3 × 29.3, 25.3 × + * 24.7, centres 19.7 to 20 pt below the item's top), Oct 23 2026 + */ + iconSize: 28, + /** + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, icon centres at y 814.7 to 815 for items at y 795, + * Oct 23 2026 + */ + iconCenterY: 20, + /** + * The label: 10 pt, medium; the selected look is semibold. Its 12 pt box + * starts 35 pt below the item's top. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, `.SFUI-Medium 10.0` / `.SFUI-Semibold 10.0`, label + * frames 12 pt tall at y 830, Oct 23 2026 + */ + labelSize: 10, + /** + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, label frames at y 830 for items at y 795, Oct 23 2026 + */ + labelTop: 35, + + badge: { + /** + * The badge's height (a 55 ÷ 3 pt capsule), and its minimum width: a + * one-character value is a circle, "12" is 21.33 wide. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, `_UIBarBadgeView` 18.33 × 18.33 for "1", "3" and "!", + * 21.33 × 18.33 for "12", corner radius 9.17, Oct 23 2026 + */ + height: 18.333, + /** + * Horizontal padding around the text (the label sits 4 pt in, 2 pt down). + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, badge at x 140.67, its label at x 144.67, Oct 23 2026 + */ + paddingInline: 4, + /** + * The text: 12 pt, medium, white on the system red. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, badge label `SF Medium 12` (weight 0.23), white, fill + * systemRed (1, 0.220, 0.235) light / (1, 0.259, 0.271) dark, + * Oct 24 2026 + */ + fontSize: 12, + /** + * Where it sits: its leading edge 9 pt after the item's centre, its top + * 2 pt below the item's top (over the icon's top-trailing corner). + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, badge at (140.67, 797) on the item centred at 131.67 + * with its top at 795, Oct 23 2026 + */ + offsetX: 9, + /** + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, badge top 797, item top 795, Oct 23 2026 + */ + offsetY: 2, + /** + * Setting, changing or clearing the value never animates. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, `UITab.badgeValue` nil → "1" → "12" → "!" → nil at + * 1 s intervals, per-frame badge frames and opacity, Oct 23 2026 + */ + animates: false, + }, + + /** + * The lens travelling to a landing finger, and the slide of a selection set + * without a finger (keys, the app). Response 0.40 s, damping ratio 0.85, the + * same spring as the segmented control's selection. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, iPhone + * 17 Pro, UIViewSpringAnimationBehavior (dampingRatio 0.85, response 0.4) + * attached at touch-down, Oct 23 2026 + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, iPhone + * 17 Pro, least-squares fit of the lens's per-frame position in the bar's + * coordinates: a press travelling 137 pt (rms 0.84 pt) and three + * programmatic changes (rms 0.28 to 0.77 pt), Oct 23 2026 + */ + lensTravel: {response: 0.4, dampingRatio: 0.85}, + /** + * The lens chasing a dragging finger. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIViewSpringAnimationBehavior tracking response 0.15, + * damping ratio 1, and a spring-chasing-the-finger fit of the lens over + * a 600 ms drag (rms 0.83 pt) and a 150 ms drag (rms 1.6 pt), + * Oct 23 2026 + */ + lensTrack: {response: 0.15, dampingRatio: 1}, + /** + * The lens settling onto the committed item after the finger lifts, + * starting from its velocity on screen. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIViewSpringAnimationBehavior (dampingRatio 1, + * response 0.5) attached at the lift, and a fit of the settle after a + * drag released at 1500 pt/s (rms 0.67 pt), Oct 23 2026 + */ + lensSettle: {response: 0.5, dampingRatio: 1}, + /** + * The lift, as one progress from rest (0) to lifted (1). The lens's outset, + * its resting fill fading out and the magnification all follow it, on the + * press and on the release alike. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, iPhone + * 17 Pro, UIViewSpringAnimationBehavior (dampingRatio 1, response 0.25) + * attached at touch-down and at the lift; the fill's opacity fits it with + * rms 0.0004 (press) and 0.0013 (release), the outset with rms 0.2 pt, Oct + * 23 2026 + */ + lift: {response: 0.25, dampingRatio: 1}, + /** + * How far the lifted lens grows past the item on every side, in the bar's + * own coordinates: 76 × 54 becomes 92 × 70. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, the lens held still for 1 s: 91.9 × 70.15 in the + * bar's coordinates (96.4 × 73.6 on screen under the flex), Oct 23 2026 + */ + liftOutset: 8, + /** + * The selected copy of the items under the lifted lens grows by this + * factor about each item's centre (the copy outside the lens does not). + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, the selected `_UITabButton`'s scale reads 1.16 while + * held and follows 1 + 0.16 × the lift progress (1.0990 at a progress + * of 0.619, 1.1356 at 0.848), Oct 23 2026 + */ + liftMagnification: 1.16, + /** + * While a finger is on the bar the whole capsule grows about its centre + * by this factor (290 × 62 becomes 304.1 × 65.0). + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, `_UITabBarPlatterView` 304.14 × 65.02 while held, + * Oct 23 2026 + */ + flexScale: 1.0488, + /** + * The flex growing while the finger is down. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIViewSpringAnimationBehavior tracking damping ratio + * 0.625, response 0.314; the capsule's scale fits it with rms 0.00009, + * Oct 23 2026 + */ + flexPress: {response: 0.314, dampingRatio: 0.625}, + /** + * The flex relaxing after the lift. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIViewSpringAnimationBehavior (dampingRatio 0.6, + * response 0.36); the capsule's scale fits it with rms 0.0002, + * Oct 23 2026 + */ + flexRelease: {response: 0.36, dampingRatio: 0.6}, + /** + * Past the first or last item's centre the lens rubber-bands with UIKit's + * formula (c = 0.55) over this dimension. A finger 60 pt past the last item + * leaves the lens 8 pt past it. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, iPhone + * 17 Pro, a drag held 60 pt past the last item: the lens rests 7.98 pt past + * its centre, Oct 23 2026 + */ + lensEdgeDimension: 10.5, +} as const; diff --git a/packages/lab/src/TabBar/useTabBarLens.ts b/packages/lab/src/TabBar/useTabBarLens.ts new file mode 100644 index 0000000000000..d56d3037a587e --- /dev/null +++ b/packages/lab/src/TabBar/useTabBarLens.ts @@ -0,0 +1,604 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useTabBarLens.ts + * @input The capsule, the item count, the selected index, the presentation, + * and the lift's handler. Core's motion engine and action-group tracking + * (internal/touch), uikitTabBar.ts and tabBarModel.ts. + * @output useTabBarLens: the selection lens's motion and press tracking, and + * the refs TabBar puts on the capsule and the lens's layers + * @position Part of TabBar's touch layer (TabBarTouch.ts) + * + * SYNC: When modified, update TabBar.tsx, tabBarModel.ts and + * __tests__/TabBar.interaction.browser.spec.ts. + */ + +import { + useCallback, + useLayoutEffect, + useRef, + useState, + type RefObject, +} from 'react'; +import {flushSync} from 'react-dom'; +import { + createMotionEngine, + isRtlElement, + type MotionCurve, + type MotionEngine, + UIKIT_GESTURES, + useActionGroupTracking, +} from '@astryxdesign/core/internal/touch'; +import { + copyTransform, + itemCenters, + itemWidth, + lensTarget, + liftScale, +} from './tabBarModel'; +import {useMotionEngine} from '../internal/useMotionEngine'; +import {tabBar} from './uikitTabBar'; + +/** A finger that has moved this far from where it landed is dragging. */ +const DRAG_SLOP = UIKIT_GESTURES.longPress.allowableMovement.value; + +/** How long the selected copy's curves run: past any lens spring's settle. */ +const COPY_HORIZON_S = 1.5; + +/** Seconds between the samples a derived curve's velocity is read from. */ +const VELOCITY_STEP_S = 0.001; + +interface Press { + /** The items' centres in the capsule, physical px, before the flex. */ + readonly centers: number[]; + /** The items' (and the resting lens's) width, px. */ + readonly size: number; + /** The capsule's left edge in client px, before the flex. */ + readonly left: number; + readonly startX: number; + lastX: number; + isDragging: boolean; + /** A tab was selected when the finger landed: the lens follows it. */ + hasLens: boolean; + readonly count: number; + /** No tab was selected when it landed, so no lens shows it: it paints. */ + readonly paints: boolean; + /** The tab the press paints now, if any. */ + painted: HTMLElement | null; +} + +/** The attribute on a painted tab; TabBar.tsx's item style reads it. */ +const PAINTED_ATTRIBUTE = 'data-tab-bar-pressed'; + +/** Moves the press's paint to `tab` (null: none). */ +function paintTab(press: Press, tab: HTMLElement | null): void { + if (!press.paints || press.painted === tab) { + return; + } + press.painted?.removeAttribute(PAINTED_ATTRIBUTE); + press.painted = tab; + tab?.setAttribute(PAINTED_ATTRIBUTE, ''); +} + +export interface UseTabBarLensOptions { + readonly capsuleRef: RefObject; + readonly count: number; + readonly selectedIndex: number; + /** + * The touch presentation (a coarse primary pointer): a finger or a pen lifts + * the lens on springs. Otherwise a press is a plain button press. + */ + readonly isTouch: boolean; + /** A press lifted over the item at `index`. */ + readonly onLift: (index: number) => void; +} + +export interface TabBarLensRefs { + /** The capsule. Its scale is the press flex. */ + readonly capsule: (element: HTMLElement | null) => void; + /** + * The lens body: its offset and lift, and its `::before`, the lifted lens's + * shadow (outside the clip). + */ + readonly body: (element: HTMLElement | null) => void; + /** The lens's clip: its `::before` is the lifted lens's glass. */ + readonly clip: (element: HTMLElement | null) => void; + /** The selected copy of the items. */ + readonly copy: (element: HTMLElement | null) => void; + /** One copied item, by index: the magnification. */ + readonly copyItem: (index: number) => (element: HTMLElement | null) => void; + /** + * The copy is drawn: the lens is lifted, or moving under a finger. At rest + * the selected tab draws its own look and the copy is not mounted. + */ + readonly isCopyShown: boolean; +} + +/** One animator per copied item, stable across renders. */ +function useAnimatorList(count: number) { + const listRef = useRef<{ + animators: MotionEngine[]; + refs: Array<(element: HTMLElement | null) => void>; + }>({animators: [], refs: []}); + const list = listRef.current; + while (list.animators.length < count) { + const animator = createMotionEngine(null); + list.animators.push(animator); + list.refs.push(element => animator.attach(element)); + } + return list; +} + +/** + * WHAT MOVES (uikitTabBar.ts, all measured on iOS 26.2) + * + * The lens is a CSS resting place over the selected item (TabBar.tsx) with a + * body inside it that this hook moves. `x` is its offset from the resting + * place, `scaleX` / `scaleY` its lift, and its `::before` the shadow that fades + * in as it lifts. Inside the body, a clip holds the selected copy of the items + * while the lens moves. The clip's background is the opaque fill, and its + * `::before` is the glass that fades in as the lens lifts. The copy is + * counter-transformed so the items stay put while the lens moves over them. Its + * curves derive from the body's (tabBarModel's `copyTransform`). Each copied + * item grows by the lift's magnification about its own centre. The copy mounts + * when a finger lands or a slide starts and goes once everything rests. At rest + * the selected tab draws its own look (TabBar.tsx). + * + * Under a finger or a pen in the touch presentation, iOS and Android alike. + * The press is a long press with no delay, so it begins on the touch, as + * UIKit's selection tracker does: + * - landing: the lens travels toward the finger (`lensTravel`) and lifts + * (`lift`: outset, glass, magnification), and the capsule flexes + * (`flexPress`); + * - dragging (past the long press's allowable movement): the lens chases the + * finger (`lensTrack`), rubber-banded past the first and last items; + * - lifting: the item nearest the finger is chosen, the lens settles onto it + * (`lensSettle`), the lift and the flex relax (`lift`, `flexRelease`). A + * cancelled touch settles back onto the selected item. + * - off the bar: the lens shows the selected item again, and a lift there + * chooses nothing. Sliding off cancels. + * The choice reaches the app (`onLift`) from the lift itself, right after the + * settle has started in the same task. The settle's first frame waits for the + * browser's commit, so the app rendering the new tab delays its start rather + * than freezing it midway. The report renders synchronously, and if the app + * keeps the old selection the lens settles back onto it. The finger is read in + * the capsule's own coordinates, before its flex scale, as UIKit reads it. + * Under the flex the lens drifts slightly away from the finger toward the ends, + * as on iOS. + * + * A selection change slides the body from where the lens was on screen to its + * new resting place. On `lensTravel` from rest (a key, the app), or continuing + * the settle a lift started. Every animation runs on the compositor; a finger's + * moves retarget them, so the lens keeps moving through a busy main thread. + * Under Reduce Motion the animator cross-fades instead of moving and a press + * scales nothing. Each spring plays as measured, from the UIKit table. + * + * Under a fine pointer nothing here runs. A press there is a plain button + * press: its click chooses the tab, and TabBar's CSS slides the lens. + */ +export function useTabBarLens({ + capsuleRef, + count, + selectedIndex, + isTouch, + onLift, +}: UseTabBarLensOptions): TabBarLensRefs { + const capsule = useMotionEngine(); + const body = useMotionEngine(); + // The lifted look, the body's and the clip's `::before`, starts hidden (an + // animator's values start at identity). + const shadow = useMotionEngine({ + pseudoElement: '::before', + initial: {opacity: 0}, + }); + const glass = useMotionEngine({ + pseudoElement: '::before', + initial: {opacity: 0}, + }); + const bodyRef = useCallback( + (element: HTMLElement | null) => { + body.ref(element); + shadow.ref(element); + }, + [body, shadow], + ); + const copy = useMotionEngine(); + const copyItems = useAnimatorList(count); + + const pressRef = useRef(null); + // The settle a lift started toward a newly chosen item, until the new + // selection renders (or the app keeps the old one). + const settleRef = useRef(null); + const selectedRef = useRef(selectedIndex); + selectedRef.current = selectedIndex; + const onLiftRef = useRef(onLift); + onLiftRef.current = onLift; + const tabsOf = (capsule: HTMLElement) => + [...capsule.children].filter( + (child): child is HTMLElement => child.getAttribute('role') === 'tab', + ); + // What the lift does with the tab it chose: set as the press ends, run by + // the shared tracker once it takes that tab. + const liftRef = useRef<((tab: HTMLElement) => void) | null>(null); + // Whether the press is on a tab now, where the lift would choose it. Each + // tab's button spans to halfway to its neighbours, and the end ones to the + // capsule's edges. So the tab under a press is the nearest one. Off the bar + // there is none, so sliding off cancels. + const isOnBarRef = useRef(false); + /** + * Where the lens heads for a press at `x`: after it, rubber-banded past + * the end items. Off the bar, where the lift would choose nothing, the lens + * shows the selected tab again. + */ + const chaseTarget = (x: number, centers: number[]) => + isOnBarRef.current + ? lensTarget(x, centers) + : centers[Math.max(selectedRef.current, 0)]; + + // The copy is drawn from a finger landing, or a slide starting, until + // everything the lens moves rests. A new selection under a finger is + // seen during render, so the frame that starts the slide already draws it. + const [isCopyShown, setIsCopyShown] = useState(false); + const [seenIndex, setSeenIndex] = useState(selectedIndex); + if (seenIndex !== selectedIndex) { + setSeenIndex(selectedIndex); + if ( + isTouch && + seenIndex >= 0 && + seenIndex < count && + selectedIndex >= 0 && + body.animator.reducedMotion({}) === 'off' + ) { + setIsCopyShown(true); + } + } + const motionRef = useRef(0); + /** Drops the copy once this motion, or a later one, rests, with no finger down. */ + const dropCopyAtRest = () => { + const motion = ++motionRef.current; + void Promise.all([ + body.animator.atRest(), + glass.animator.atRest(), + shadow.animator.atRest(), + ...copyItems.animators.slice(0, count).map(item => item.atRest()), + ]).then(() => { + if (motionRef.current === motion && pressRef.current == null) { + setIsCopyShown(false); + } + }); + }; + + /** + * Plays the selected copy's counter-transform from `at`, derived from the + * body's curves as they now stand. Called after every change to the body. + */ + const playCopy = (at: number) => { + const sample = (t: number) => { + const time = at + t * 1000; + return copyTransform( + body.animator.get('x', time), + body.animator.get('scaleX', time), + body.animator.get('scaleY', time), + ); + }; + const curve = (key: 'x' | 'scaleX' | 'scaleY'): MotionCurve => ({ + duration: COPY_HORIZON_S, + at: t => sample(t)[key], + velocity: t => + (sample(t + VELOCITY_STEP_S)[key] - + sample(Math.max(0, t - VELOCITY_STEP_S))[key]) / + (t >= VELOCITY_STEP_S ? 2 * VELOCITY_STEP_S : VELOCITY_STEP_S), + }); + copy.animator.play( + {x: curve('x'), scaleX: curve('scaleX'), scaleY: curve('scaleY')}, + {at}, + ); + }; + + /** + * Lifts (true) or lowers (false) a lens `size` px wide and flexes the + * capsule. Under Reduce Motion a press scales nothing: the glass and its + * shadow only fade. + */ + const lift = ( + isLifted: boolean, + at: number, + size: number, + touchRelease = false, + ) => { + const options = {at, touchRelease}; + const spring = {spring: tabBar.lift}; + shadow.animator.animate({opacity: isLifted ? 1 : 0}, spring, options); + glass.animator.animate({opacity: isLifted ? 1 : 0}, spring, options); + if (body.animator.reducedMotion({touchRelease}) !== 'off') { + return; + } + const lifted = liftScale(size); + body.animator.animate( + isLifted ? {scaleX: lifted.x, scaleY: lifted.y} : {scaleX: 1, scaleY: 1}, + spring, + options, + ); + for (const item of copyItems.animators.slice(0, count)) { + item.animate( + {scale: isLifted ? tabBar.liftMagnification : 1}, + spring, + options, + ); + } + capsule.animator.animate( + {scale: isLifted ? tabBar.flexScale : 1}, + {spring: isLifted ? tabBar.flexPress : tabBar.flexRelease}, + options, + ); + }; + + const begin = (clientX: number, tab: HTMLElement | null) => { + const element = capsuleRef.current; + const selected = selectedRef.current; + const root = element?.parentElement; + if (element == null || root == null) { + return; + } + // Read before anything moves: the capsule's layout box (its flex is a + // transform, which layout ignores) placed by its unscaled parent. + const rootBox = root.getBoundingClientRect(); + const left = rootBox.left + element.offsetLeft; + const isRtl = isRtlElement(element); + const centers = itemCenters(element.offsetWidth, count, isRtl); + const size = itemWidth(element.offsetWidth, count); + const x = clientX - left; + pressRef.current = { + centers, + size, + left, + startX: x, + lastX: x, + isDragging: false, + hasLens: selected >= 0, + count, + paints: selected < 0, + painted: null, + }; + isOnBarRef.current = tab != null; + paintTab(pressRef.current, tab); + // No tab selected: there is no lens to move; the lift chooses the tab + // nearest the finger. + if (selected < 0) { + return; + } + // The lifted lens magnifies the selected look: its copy mounts now, in + // this event (its animators attach to it with their curves running). + // Under Reduce Motion nothing lifts or travels, so no copy mounts. + motionRef.current += 1; + if (body.animator.reducedMotion({}) === 'off') { + flushSync(() => setIsCopyShown(true)); + } + const at = performance.now(); + body.animator.animate( + {x: chaseTarget(x, centers) - centers[selected]}, + {spring: tabBar.lensTravel}, + {at}, + ); + lift(true, at, size); + playCopy(at); + }; + + const move = (clientX: number, tab: HTMLElement | null) => { + const press = pressRef.current; + const selected = selectedRef.current; + if (press == null) { + return; + } + isOnBarRef.current = tab != null; + paintTab(press, tab); + const x = clientX - press.left; + press.lastX = x; + press.isDragging ||= Math.abs(x - press.startX) > DRAG_SLOP; + if (!press.hasLens || selected < 0) { + return; + } + const at = performance.now(); + body.animator.animate( + {x: chaseTarget(x, press.centers) - press.centers[selected]}, + {spring: press.isDragging ? tabBar.lensTrack : tabBar.lensTravel}, + {at}, + ); + playCopy(at); + }; + + const end = (tracked: HTMLElement | null, wasCancelled: boolean) => { + const press = pressRef.current; + pressRef.current = null; + liftRef.current = null; + if (press != null) { + paintTab(press, null); + } + const selected = selectedRef.current; + const element = capsuleRef.current; + if (press == null || element == null) { + return; + } + // The tab list changed under the press. Its centres name the old list, so + // it ends as a cancel and the lens settles to its resting place. + const isStale = press.count !== count; + // The tab the tracker took for the lift, if any. + const lifted = wasCancelled || isStale ? null : tracked; + const chosen = lifted == null ? -1 : tabsOf(element).indexOf(lifted); + // The app's answer to this lift, as rendered now: the tab the finger + // chose is the one under it at the lift, whatever renders after. + const deliver = onLiftRef.current; + if (!press.hasLens || selected < 0) { + // No lens moved: the tab the tracker took runs at once. + if (chosen >= 0) { + liftRef.current = () => flushSync(() => deliver(chosen)); + } + return; + } + const target = chosen >= 0 ? chosen : selected; + const at = performance.now(); + body.animator.animate( + {x: isStale ? 0 : press.centers[target] - press.centers[selected]}, + {spring: tabBar.lensSettle}, + {at, touchRelease: true}, + ); + lift(false, at, press.size, true); + playCopy(at); + dropCopyAtRest(); + if (chosen < 0) { + return; + } + if (chosen !== selected) { + settleRef.current = chosen; + } + // The lift reports its choice from the same event, the settle already + // started. Its first frame waits for the browser's commit, so the app + // rendering the chosen tab delays it rather than freezing it midway. + // Rendered at once, so the selection reads the app's answer right after. + liftRef.current = () => { + flushSync(() => deliver(chosen)); + if ( + chosen !== selected && + settleRef.current === chosen && + selectedRef.current === selected + ) { + // The app kept the old selection: the lens settles back. + settleRef.current = null; + const now = performance.now(); + body.animator.animate( + {x: 0}, + {spring: tabBar.lensSettle}, + {at: now, touchRelease: true}, + ); + playCopy(now); + dropCopyAtRest(); + } + }; + }; + + // Core's action-group tracking owns the press: the tab under it, running + // that tab at the lift, a second finger's cancel and focus after the lift. + // TabBar picks the tab and draws the lens. + const groupPress = useActionGroupTracking(capsuleRef, { + itemSelector: '[role="tab"]', + highlightOnsetMs: 0, + highlightExpansion: 0, + // A finger and a pen, in the touch presentation only. A mouse press, and + // every press under a fine pointer, stays a plain button press. + pointerTypes: ['touch', 'pen'], + isEnabled: isTouch, + paintsHighlight: false, + onPressBegin: (x, _y, tab) => begin(x, tab), + onPressMove: (x, _y, tab) => move(x, tab), + onPressEnd: tracked => end(tracked, false), + onPressCancel: () => end(null, true), + onActivate: tab => { + const run = liftRef.current; + liftRef.current = null; + run?.(tab); + }, + }); + + const endRef = useRef(end); + endRef.current = end; + + // Synchronizes the recognizer's press and the lens's animations with the tab + // list. When it changes under a held finger, the press ends here, as a + // cancel, rather than at the lift. So no move chases the old centres. + useLayoutEffect(() => { + if (pressRef.current != null && pressRef.current.count !== count) { + groupPress.cancel(); + endRef.current(null, true); + } + }, [count, groupPress]); + + // Synchronizes the lens's compositor animations (the animator's Web + // Animations on its body and copy) with the selected tab. + // A new selection: the resting place jumped to the new item (CSS, this + // frame); the body starts where the lens was on screen. After a lift it + // continues the settle the lift started; otherwise it slides from rest. + // Under a fine pointer TabBar's CSS slides the lens. + const previousIndexRef = useRef(selectedIndex); + useLayoutEffect(() => { + const from = previousIndexRef.current; + previousIndexRef.current = selectedIndex; + const element = capsuleRef.current; + const fromLift = settleRef.current === selectedIndex; + settleRef.current = null; + if ( + !isTouch || + element == null || + from === selectedIndex || + from < 0 || + selectedIndex < 0 || + from >= count + ) { + return; + } + const isRtl = isRtlElement(element); + const centers = itemCenters(element.offsetWidth, count, isRtl); + const now = performance.now(); + const shift = centers[from] - centers[selectedIndex]; + const offset = body.animator.get('x', now) + shift; + const velocity = body.animator.getVelocity('x', now); + body.animator.set({x: offset}); + const press = pressRef.current; + if (press != null) { + // A finger is down (the selection changed under it): the lens keeps + // heading for the finger, now measured from its new resting place. + body.animator.animate( + { + x: + chaseTarget(press.lastX, press.centers) - + press.centers[selectedIndex], + }, + { + spring: press.isDragging ? tabBar.lensTrack : tabBar.lensTravel, + velocity: {x: velocity}, + }, + {at: now}, + ); + playCopy(now); + return; + } + if (fromLift || velocity !== 0) { + // Motion on screen: continue it from now, the copy derived from it. + body.animator.animate( + {x: 0}, + { + spring: fromLift ? tabBar.lensSettle : tabBar.lensTravel, + velocity: {x: velocity}, + }, + {at: now, touchRelease: fromLift}, + ); + playCopy(now); + dropCopyAtRest(); + return; + } + // From rest (a key, the app), the body starts when the browser commits the + // frame, with the lens's jump to its new place. The copy plays the body's + // own curve on the body's clock. Two calls on two animators would each take + // their own start, which WebKit's late-start correction can part under a + // busy main thread. + copy.animator.set({x: -offset}); + const call = body.animator.animate({x: 0}, {spring: tabBar.lensTravel}); + dropCopyAtRest(); + const motion = motionRef.current; + void call.started.then(start => { + if (motionRef.current === motion) { + playCopy(start); + } + }); + }, [selectedIndex, count, isTouch, capsuleRef, body, copy]); + + return { + capsule: capsule.ref, + body: bodyRef, + clip: glass.ref, + copy: copy.ref, + copyItem: index => copyItems.refs[index], + isCopyShown, + }; +} diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts index 92178abd14e8e..4101eb103d5af 100644 --- a/packages/lab/src/index.ts +++ b/packages/lab/src/index.ts @@ -324,6 +324,14 @@ export { type DiffViewerSide, } from './DiffViewer'; +// TabBar: the floating bottom tab bar of iOS 26's UITabBarController. +export { + TabBar, + TabBarItem, + type TabBarItemProps, + type TabBarProps, +} from './TabBar'; + // 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'; From 270f341cb6b8d3d1b15a1d037ec4adcf736d6b30 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 5 Nov 2026 23:27:08 -0800 Subject: [PATCH 4/5] fix(lab): TabBar's finger paint fades on the compositor With no tab selected, a held finger paints its tab, and the paint fades after the lift on the theme's exit duration and curve. The fade was a background-color transition, which runs on the main thread. The paint is now a layer, and only its opacity fades, so the compositor runs the fade through a main-thread block. Its timing is unchanged: at once on the touch, then the theme's exit duration and curve at the lift, within 200 ms under Reduce Motion. Also: TabBar calls itemWidthCss directly, the test-only nearestIndex is gone (the shared tracker decides the tab a lift commits), and the Reduce Motion case cites design:reduced-motion DR2. --- packages/lab/src/TabBar/TabBar.tsx | 59 ++++++++++--------- .../TabBar.interaction.browser.spec.ts | 55 ++++++++++++++--- packages/lab/src/TabBar/tabBarModel.test.ts | 23 -------- packages/lab/src/TabBar/tabBarModel.ts | 25 +------- 4 files changed, 80 insertions(+), 82 deletions(-) diff --git a/packages/lab/src/TabBar/TabBar.tsx b/packages/lab/src/TabBar/TabBar.tsx index 2a5e847d754be..7cf176c50ba74 100644 --- a/packages/lab/src/TabBar/TabBar.tsx +++ b/packages/lab/src/TabBar/TabBar.tsx @@ -131,20 +131,17 @@ function hasBadge(badge: string | number | undefined): boolean { const px = (value: number) => `${value}px`; const INSET = px(tabBar.itemInset); -/** The items' shared width (and the resting lens's), inside a calc(). */ -const size = (count: number) => itemWidthCss(count); - /** The distance between neighbouring items' centres. */ function pitch(count: number): string { return count > 1 - ? `((100cqw - ${px(2 * tabBar.itemInset)} - ${size(count)}) / ${count - 1})` + ? `((100cqw - ${px(2 * tabBar.itemInset)} - ${itemWidthCss(count)}) / ${count - 1})` : '0px'; } /** An item's centre from the capsule's inline start, inside a calc(). */ function center(index: number, count: number): string { return count > 1 - ? `${INSET} + ${size(count)} / 2 + ${pitch(count)} * ${index}` + ? `${INSET} + ${itemWidthCss(count)} / 2 + ${pitch(count)} * ${index}` : '50cqw'; } @@ -161,18 +158,18 @@ function column( return { start: '0px', width: '100cqw', - itemStart: `calc(50cqw - ${size(count)} / 2)`, + itemStart: `calc(50cqw - ${itemWidthCss(count)} / 2)`, }; } const half = `${pitch(count)} / 2`; - const edgeWidth = `calc(${INSET} + ${size(count)} / 2 + ${half})`; + const edgeWidth = `calc(${INSET} + ${itemWidthCss(count)} / 2 + ${half})`; if (index === 0) { return {start: '0px', width: edgeWidth, itemStart: INSET}; } return { start: `calc(${center(index, count)} - ${half})`, width: index === count - 1 ? edgeWidth : `calc(${pitch(count)})`, - itemStart: `calc(${half} - ${size(count)} / 2)`, + itemStart: `calc(${half} - ${itemWidthCss(count)} / 2)`, }; } @@ -250,26 +247,34 @@ const styles = stylex.create({ outlineColor: focusVars['--focus-outline-color'], outlineOffset: focusVars['--focus-outline-offset'], // With no tab selected, a held finger paints its tab at once - // (useTabBarLens.ts writes the attribute). The paint fades out after the - // lift on the theme's exit duration and curve. Under Reduce Motion the fade + // (useTabBarLens.ts writes the attribute). The paint is a layer, and only + // its opacity fades after the lift, so the compositor runs the fade. It + // plays the theme's exit duration and curve. Under Reduce Motion the fade // stays within 200 ms, whatever the theme's tempo. - backgroundColor: { - default: null, - [stylex.when.ancestor('[data-tab-bar-pressed]', tabBarItemMarker)]: - colorVars['--color-overlay-pressed'], - }, - transitionProperty: 'background-color', - transitionDuration: { - default: durationVars['--duration-exit'], - '@media (prefers-reduced-motion: reduce)': `min(${durationVars['--duration-exit']}, 200ms)`, - // Repeated inside the Reduce Motion branch, where a media rule outranks - // the plain one, so the onset stays at once there too. - [stylex.when.ancestor('[data-tab-bar-pressed]', tabBarItemMarker)]: { - default: '0s', - '@media (prefers-reduced-motion: reduce)': '0s', + '::before': { + content: '""', + position: 'absolute', + inset: 0, + borderRadius: 'inherit', + backgroundColor: colorVars['--color-overlay-pressed'], + pointerEvents: 'none', + opacity: { + default: 0, + [stylex.when.ancestor('[data-tab-bar-pressed]', tabBarItemMarker)]: 1, + }, + transitionProperty: 'opacity', + transitionDuration: { + default: durationVars['--duration-exit'], + '@media (prefers-reduced-motion: reduce)': `min(${durationVars['--duration-exit']}, 200ms)`, + // Repeated inside the Reduce Motion branch, where a media rule + // outranks the plain one, so the onset stays at once there too. + [stylex.when.ancestor('[data-tab-bar-pressed]', tabBarItemMarker)]: { + default: '0s', + '@media (prefers-reduced-motion: reduce)': '0s', + }, }, + transitionTimingFunction: easeVars['--ease-exit'], }, - transitionTimingFunction: easeVars['--ease-exit'], }, box: (start: string, top: string, width: string, height: string) => ({ insetInlineStart: start, @@ -558,7 +563,7 @@ export function TabBar({ const restIndex = Math.max(selectedIndex, 0); const capsuleInset = px(tabBar.itemInset); - const itemSize = `calc(${size(count)})`; + const itemSize = `calc(${itemWidthCss(count)})`; return (
getComputedStyle(element).backgroundColor); + .evaluate(element => { + const layer = getComputedStyle(element, '::before'); + // A layer with no color paints nothing, whatever its opacity. + return layer.backgroundColor === 'rgba(0, 0, 0, 0)' + ? 0 + : Number(layer.opacity); + }); } /** @@ -303,7 +307,7 @@ async function paintTimingAgainst( easing: style.transitionTimingFunction, }); const result = { - have: read(getComputedStyle(element)), + have: read(getComputedStyle(element, '::before')), want: read(getComputedStyle(probe)), }; probe.remove(); @@ -329,7 +333,8 @@ async function paintFadeMs(page: Page, name: string) { .first() .evaluate( element => - parseFloat(getComputedStyle(element).transitionDuration) * 1000, + parseFloat(getComputedStyle(element, '::before').transitionDuration) * + 1000, ); } @@ -1121,7 +1126,7 @@ test('with no tab selected, a finger held on a tab paints it, and the paint foll onEvent: async (_step, index) => { if (index === 0) { await expect(tab(page, 'Home')).toHaveAttribute('data-tab-bar-pressed'); - await expect.poll(() => itemPaint(page, 'Home')).not.toBe(TRANSPARENT); + await expect.poll(() => itemPaint(page, 'Home')).toBe(1); } // The finger is on Library, before the lift. if (index === script.length - 2) { @@ -1137,7 +1142,7 @@ test('with no tab selected, a finger held on a tab paints it, and the paint foll await expect(tab(page, 'Library')).toHaveAttribute('aria-selected', 'true'); }); -test('with Reduce Motion a finger paints its tab at once, and its release keeps a fade of 200 ms or less, even on a slow theme (design:reduced-motion DEC-4)', async ({ +test('with Reduce Motion a finger paints its tab at once, and its release keeps a fade of 200 ms or less, even on a slow theme (design:reduced-motion DR2)', async ({ page, }) => { await page.emulateMedia({reducedMotion: 'reduce'}); @@ -1148,7 +1153,7 @@ test('with Reduce Motion a finger paints its tab at once, and its release keeps onEvent: async (_step, index) => { if (index === 0) { await expect(tab(page, 'Home')).toHaveAttribute('data-tab-bar-pressed'); - expect(await itemPaint(page, 'Home')).not.toBe(TRANSPARENT); + expect(await itemPaint(page, 'Home')).toBe(1); expect(await paintFadeMs(page, 'Home')).toBe(0); } }, @@ -1182,6 +1187,38 @@ test('a finger’s release fades the paint on the theme’s exit duration and cu expect(have).toEqual(want); }); +test('a finger’s release fades only its paint layer’s opacity, which the compositor runs (spec:AST-094 FR5)', async ({ + page, +}) => { + const {driver} = await openBar(page, 'no-selection'); + // A slow exit, so the fade still runs when it is read. + await setExitDuration(page, '5000ms'); + const home = await itemCenter(page, 'Home'); + await driver.play(tapScript(home, {holdMs: 400})); + await expect(tab(page, 'Home')).not.toHaveAttribute('data-tab-bar-pressed'); + const fades = await tab(page, 'Home') + .locator('span') + .first() + .evaluate(box => + box.getAnimations({subtree: true}).flatMap(animation => { + const effect = animation.effect as KeyframeEffect | null; + if (effect?.target !== box) { + return []; + } + return [ + { + property: + animation instanceof CSSTransition + ? animation.transitionProperty + : 'animation', + layer: effect.pseudoElement, + }, + ]; + }), + ); + expect(fades).toEqual([{property: 'opacity', layer: '::before'}]); +}); + test('past the last item, still on the bar, the lens rubber-bands beyond it and the lift commits the last item; past the bar’s end the lift chooses nothing', async ({ page, }) => { diff --git a/packages/lab/src/TabBar/tabBarModel.test.ts b/packages/lab/src/TabBar/tabBarModel.test.ts index 9cbcbd7f2c3f4..ea577c58afde4 100644 --- a/packages/lab/src/TabBar/tabBarModel.test.ts +++ b/packages/lab/src/TabBar/tabBarModel.test.ts @@ -20,7 +20,6 @@ import { lensTarget, liftScale, naturalWidth, - nearestIndex, } from './tabBarModel'; /** @@ -112,28 +111,6 @@ describe('itemWidth and itemCenters', () => { }); }); -describe('nearestIndex: the item a lift commits', () => { - const centers = itemCenters(290, 4); - - it('picks the nearest centre', () => { - expect(nearestIndex(centers[2] + 20, centers)).toBe(2); - expect(nearestIndex(centers[1] - 30, centers)).toBe(1); - }); - - it('gives a tie to the leading (earlier) item, as UIKit did between items 2 and 3', () => { - const midpoint = (centers[1] + centers[2]) / 2; - expect(nearestIndex(midpoint, centers)).toBe(1); - // In a right-to-left capsule the earlier item is on the right. - const rtl = itemCenters(290, 4, true); - expect(nearestIndex((rtl[1] + rtl[2]) / 2, rtl)).toBe(1); - }); - - it('commits the last item for a finger 60 px past it, and the first before it', () => { - expect(nearestIndex(centers[3] + 60, centers)).toBe(3); - expect(nearestIndex(-40, centers)).toBe(0); - }); -}); - describe('lensTarget', () => { const centers = itemCenters(290, 4); diff --git a/packages/lab/src/TabBar/tabBarModel.ts b/packages/lab/src/TabBar/tabBarModel.ts index 1ab86f537798f..42ceee51ce6fc 100644 --- a/packages/lab/src/TabBar/tabBarModel.ts +++ b/packages/lab/src/TabBar/tabBarModel.ts @@ -3,8 +3,8 @@ /** * @file tabBarModel.ts * @input TabBar's UIKit values (uikitTabBar.ts) - * @output TabBar's pure geometry: the items' widths and centres, the item a - * lift commits, and the lens's target and scale. + * @output TabBar's pure geometry: the items' widths and centres, and the + * lens's target and scale. * @position Math of the lab TabBar; no DOM, no React. Coordinates are the * capsule's own, in px, before its flex scale. x runs from its left edge, * and items go in logical order. @@ -70,27 +70,6 @@ export function itemCenters( return isRtl ? centers.map(center => width - center) : centers; } -/** - * The item a finger lifted at `x` commits: the one whose centre is nearest, - * the earlier one on a tie. No projection: a flick commits where it lifts. - */ -export function nearestIndex( - x: number, - centers: ReadonlyArray, -): number { - let best = 0; - let bestDistance = Infinity; - centers.forEach((center, index) => { - const distance = Math.abs(x - center); - // Strictly nearer only: a tie keeps the earlier (leading) item. - if (distance < bestDistance - 1e-9) { - best = index; - bestDistance = distance; - } - }); - return best; -} - /** * Where the lens heads for a finger at `x`: the finger itself between the * first and last centres, rubber-banded past them. From a309756e1923db5e7837274e3ed60914172bc176 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 02:33:08 -0800 Subject: [PATCH 5/5] test(lab): TabBar's spring cases name the motion each hold judges Main's interaction harness now requires every hold sent from a test to name the motion it judges. Each TabBar case names what it samples after the hold: - the keyed slide: the lens body's and the lens copy's translate; - the finger landing: the capsule's scale, the lens body's scale and translate, and the lens clip's ::before opacity; - the lift: the capsule's and the lens body's scale; - the selection storyboard: the lens body's translate. --- .../TabBar.interaction.browser.spec.ts | 28 +++++++++++++++++-- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts b/packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts index acbaa33cda1cd..ecc9a666054fc 100644 --- a/packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts +++ b/packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts @@ -399,7 +399,12 @@ test('a selection made with the keys slides the lens on UIKit’s spring, the se await expect(tab(page, 'Browse')).toHaveAttribute('aria-selected', 'true'); const body = lensBody(page); await waitForAnimation(body, {minProgressMs: 0}); - await holdAnimations(page); + await holdAnimations(page, undefined, { + judges: [ + {target: body, property: 'translate'}, + {target: lensCopy(page), property: 'translate'}, + ], + }); const times = Array.from({length: 49}, (_, i) => i * 16.667); const bodySamples = await sampleCurve(body, times); @@ -809,7 +814,18 @@ test('a finger landing lifts the lens and flexes the bar on UIKit’s springs, t return; } await waitForAnimation(capsule, {minProgressMs: 0}); - await holdAnimations(page); + await holdAnimations(page, undefined, { + judges: [ + {target: capsule, property: 'scale'}, + {target: lensBody(page), property: 'scale'}, + {target: lensBody(page), property: 'translate'}, + { + target: page.locator('[data-tab-bar-lens-clip]'), + property: 'opacity', + pseudoElement: '::before', + }, + ], + }); const flex = await sampleCurve(capsule, times); const body = await sampleCurve(lensBody(page), times); const glass = await samplePseudoOpacity( @@ -934,7 +950,12 @@ test('the lift settles the lens and relaxes the lift and the flex on UIKit’s s // animation is one the animator has since replaced. await expect(tab(page, 'Browse')).toHaveAttribute('aria-selected', 'true'); await waitForAnimation(capsule, {minProgressMs: 0}); - await holdAnimations(page); + await holdAnimations(page, undefined, { + judges: [ + {target: capsule, property: 'scale'}, + {target: lensBody(page), property: 'scale'}, + ], + }); const times = Array.from({length: 37}, (_, i) => i * 16.667); const flex = await sampleCurve(capsule, times); const body = await sampleCurve(lensBody(page), times); @@ -2077,6 +2098,7 @@ test( }, times: Array.from({length: 37}, (_, i) => i * 16.667), measure: async () => ({x: await translateX(lensBody(page))}), + judges: {target: lensBody(page), property: 'translate'}, columns: 6, cellScale: 0.6, });