An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): TabBar, iOS 26's floating tab bar, with its selection lens and press tracking (#9700)
Christopher Chedeauc18bc584c480
diff --git a/.changeset/cli-discover-tab-bar.md b/.changeset/cli-discover-tab-bar.mdnew file mode 100644index 0000000000..367480325b--- /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`.++@vjeuxdiff --git a/apps/storybook/stories/TabBar.stories.tsx b/apps/storybook/stories/TabBar.stories.tsxnew file mode 100644index 0000000000..b9ee247e57--- /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<typeof TabBar> = {+ // The bar floats over the bottom edge: declared on LayerProvider, menus,+ // popovers and toasts clear it.+ decorators: [+ Story => (+ <LayerProvider inset={{blockEnd: 83}}>+ <Story />+ </LayerProvider>+ ),+ ],+ title: 'Lab/TabBar',+ component: TabBar,+ parameters: {+ layout: 'fullscreen',+ },+};++export default meta;+type Story = StoryObj<typeof TabBar>;++// =============================================================================+// 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 (+ <div style={{padding: '16px 16px 104px'}}>+ <h1 style={{margin: '8px 0 16px', fontSize: 28}}>+ {title || 'No tab selected'}+ </h1>+ <p data-testid="reselects">Reselected {reselects} times</p>+ {Array.from({length: 40}, (_, i) => (+ <p key={i} style={{margin: 0, padding: '12px 0'}}>+ {title} row {i + 1}+ </p>+ ))}+ </div>+ );+}++function Bar({+ sections = SECTIONS,+ initial = 'home',+ badges = {library: 3},+ keeps = [],+ onChange,+}: {+ sections?: Section[];+ initial?: string;+ badges?: Record<string, string | number>;+ /** 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 (+ <>+ <Screen title={title} reselects={reselects} />+ <TabBar+ value={value}+ onChange={next => {+ onChange?.(next);+ if (!keeps.includes(next)) {+ setValue(next);+ }+ }}+ onReselect={() => setReselects(n => n + 1)}+ label="Sections"+ data-testid="tab-bar">+ {sections.map(section => (+ <TabBarItem+ key={section.value}+ value={section.value}+ label={section.label}+ icon={<Icon icon={section.icon} size="lg" />}+ selectedIcon={<Icon icon={section.selectedIcon} size="lg" />}+ badge={badges[section.value]}+ />+ ))}+ </TabBar>+ </>+ );+}++/** Four tabs, a badge on Library. Choosing Home again counts a reselect. */+export const Default: Story = {+ render: () => <Bar />,+};++/** 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 (+ <>+ <div style={{padding: 16, display: 'flex', gap: 8}}>+ <Button label="Add one" onClick={() => setCount(n => n + 1)} />+ <Button label="Add ten" onClick={() => setCount(n => n + 10)} />+ <Button label="Clear" variant="secondary" onClick={() => setCount(0)} />+ </div>+ <TabBarHost badges={{inbox: badge ?? '', browse: '!'}} />+ </>+ );+}++function TabBarHost({badges}: {badges: Record<string, string | number>}) {+ const [value, setValue] = useState('home');+ return (+ <TabBar+ value={value}+ onChange={setValue}+ label="Sections"+ data-testid="tab-bar">+ {[SECTIONS[0], INBOX, SECTIONS[2], SECTIONS[3]].map(section => (+ <TabBarItem+ key={section.value}+ value={section.value}+ label={section.label}+ icon={<Icon icon={section.icon} size="lg" />}+ selectedIcon={<Icon icon={section.selectedIcon} size="lg" />}+ badge={badges[section.value]}+ badgeLabel={+ section.value === 'inbox' && badges.inbox !== ''+ ? `${badges.inbox} unread`+ : undefined+ }+ />+ ))}+ </TabBar>+ );+}++/**+ * 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: () => <Bar keeps={['profile']} />,+};++/** No tab selected (the value matches none): a tap chooses one. */+export const NoSelection: Story = {+ render: () => <Bar initial="none" />,+};++/**+ * 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 ? (+ <Bar+ onChange={value => {+ const log = window as unknown as {__tabBarChanges?: string[]};+ log.__tabBarChanges = [...(log.__tabBarChanges ?? []), value];+ }}+ />+ ) : (+ <p style={{padding: 16}}>Removed</p>+ );+}++export const RemovedOnLift: Story = {+ render: () => <RemovedOnLiftDemo />,+};++/**+ * 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 (+ <Bar+ sections={sections}+ onChange={value => {+ const log = window as unknown as {__tabBarChanges?: string[]};+ log.__tabBarChanges = [...(log.__tabBarChanges ?? []), value];+ }}+ />+ );+}++export const DropsLastTab: Story = {+ render: () => <DropsLastTabDemo />,+};++export const Badges: Story = {+ render: () => <BadgesDemo />,+};++/** Five tabs: the items overlap more, as they do on iOS. */+export const FiveTabs: Story = {+ render: () => (+ <Bar sections={[...SECTIONS.slice(0, 2), INBOX, ...SECTIONS.slice(2)]} />+ ),+};++/** Three tabs: the capsule narrows to its natural width and centres. */+export const ThreeTabs: Story = {+ render: () => <Bar sections={SECTIONS.slice(0, 3)} />,+};++/** Right to left: the first tab sits on the right and the badge on the icon's top-left. */+export const RightToLeft: Story = {+ render: () => (+ <div dir="rtl">+ <Bar initial="library" />+ </div>+ ),+};diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex fad761b17c..1428895946 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -667,6 +667,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.jsonindex fdb101f73f..3b5d5fe07e 100644--- a/packages/cli/assets/discover/official-packages.json+++ b/packages/cli/assets/discover/official-packages.json@@ -180,6 +180,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.mjsnew file mode 100644index 0000000000..4d62a7129b--- /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.tsxnew file mode 100644index 0000000000..9beaf3fbc6--- /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 <svg data-testid={`icon-${name}`} />;+}++function Bar({+ initial = 'home',+ onReselect,+ onChange,+ badges = {},+ ...props+}: Partial<TabBarProps> & {+ initial?: string;+ badges?: Record<string, string | number | undefined>;+}) {+ const [value, setValue] = useState(initial);+ return (+ <TabBar+ value={value}+ onChange={next => {+ setValue(next);+ onChange?.(next);+ }}+ onReselect={onReselect}+ label="Sections"+ data-testid="bar"+ {...props}>+ <TabBarItem value="home" label="Home" icon={<Glyph name="home" />} />+ <TabBarItem+ value="library"+ label="Library"+ icon={<Glyph name="library" />}+ badge={badges.library}+ />+ <TabBarItem+ value="browse"+ label="Browse"+ icon={<Glyph name="browse" />}+ badge={badges.browse}+ badgeLabel="New items"+ />+ <TabBarItem+ value="profile"+ label="Profile"+ icon={<Glyph name="profile" />}+ />+ </TabBar>+ );+}++/**+ * 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(<Bar label={undefined} />);+ expect(screen.getByRole('tablist', {name: 'Tabs'})).toBeInTheDocument();+ });++ it('wires a tab to the panel it controls through panelId (aria-controls)', () => {+ render(+ <TabBar value="home" onChange={() => {}}>+ <TabBarItem+ value="home"+ label="Home"+ icon={null}+ panelId="home-panel"+ />+ <TabBarItem value="library" label="Library" icon={null} />+ </TabBar>,+ );+ 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(<Bar label={undefined} aria-label="Main sections" />);+ 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(+ <>+ <h2 id="sections-heading">Sections heading</h2>+ <Bar label="Ignored" aria-labelledby="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(<Bar initial="library" />);+ 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(<Bar onChange={onChange} onReselect={onReselect} />);+ 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(<Bar onChange={onChange} onReselect={onReselect} />);+ 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(<Bar initial="library" />);+ 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(+ <InternationalizationProvider+ locale="en"+ overrides={{en: {'@astryx.tabBar.badgedItem': '{badge} · {label}'}}}>+ <Bar badges={{library: 3}} />+ </InternationalizationProvider>,+ );+ 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(<Bar badges={{library: 3}} />);+ 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(<Bar badges={{library: '12'}} />);+ expect(badge()).toHaveTextContent('12');+ expect(screen.getByRole('tab', {name: 'Library, 12'})).toBeInTheDocument();+ rerender(<Bar badges={{library: ''}} />);+ expect(badge()).toBeNull();+ expect(screen.getByRole('tab', {name: 'Library'})).toBeInTheDocument();+ });++ it('reads a badge’s label instead of the badge when given one', () => {+ render(<Bar badges={{browse: '!'}} />);+ 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(<Bar badges={{library: 3}} />);+ 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(+ <TabBar value="none" onChange={() => {}}>+ <TabBarItem value="a" label="A" icon={null} />+ <TabBarItem value="b" label="B" icon={null} />+ </TabBar>,+ );+ 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(+ <TabBar value="b" onChange={() => {}}>+ <TabBarItem value="a" label="A" icon={null} />+ <TabBarItem value="b" label="B" icon={null} />+ </TabBar>,+ );+ expect(document.querySelector('[data-tab-bar-lens]')).not.toBeNull();+ });++ it('draws the selected icon on the selected tab itself when one is given', () => {+ render(+ <TabBar value="a" onChange={() => {}}>+ <TabBarItem+ value="a"+ label="A"+ icon={<Glyph name="outline" />}+ selectedIcon={<Glyph name="filled" />}+ />+ </TabBar>,+ );+ 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(<Bar />);+ 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(<Bar />);+ 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(<Bar initial="browse" />);+ 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(+ <TabBar value="a" onChange={() => {}}>+ <TabBarItem value="a" label="A" icon={null} />+ {null}+ <span>stray</span>+ </TabBar>,+ );+ 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.tsxnew file mode 100644index 0000000000..7cf176c50b--- /dev/null+++ b/packages/lab/src/TabBar/TabBar.tsx@@ -0,0 +1,725 @@+// 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 />`). */+ 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<HTMLDivElement>,+ 'onChange'+> {+ /** Ref forwarded to the root element. */+ ref?: React.Ref<HTMLDivElement>;+ /** 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<TabBarItemProps>).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 distance between neighbouring items' centres. */+function pitch(count: number): string {+ return 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} + ${itemWidthCss(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 - ${itemWidthCss(count)} / 2)`,+ };+ }+ const half = `${pitch(count)} / 2`;+ 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} - ${itemWidthCss(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 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.+ '::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'],+ },+ },+ 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 (+ <>+ <span+ aria-hidden+ {...stylex.props(+ styles.icon,+ styles.box(ICON_START, ICON_TOP, ICON_SIZE, ICON_SIZE),+ )}>+ {isSelectedLook ? (item.selectedIcon ?? item.icon) : item.icon}+ </span>+ <span+ aria-hidden={isCopy || undefined}+ {...stylex.props(+ styles.label,+ styles.labelGeometry(LABEL_TOP, LABEL_HEIGHT, LABEL_SIZE),+ isSelectedLook && styles.labelSelected,+ )}>+ {item.label}+ </span>+ </>+ );+}++// =============================================================================+// 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+ * ```+ * <TabBar value={tab} onChange={setTab} onReselect={popToRoot} label="Sections">+ * <TabBarItem value="home" label="Home" icon={<Icon icon={HomeIcon} />} />+ * <TabBarItem value="inbox" label="Inbox" icon={<Icon icon={InboxIcon} />} badge={3} />+ * </TabBar>+ * ```+ */+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<HTMLDivElement | null>(null);+ const {listRef, handleKeyDown, handleFocus} = useListFocus<HTMLDivElement>({+ 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(${itemWidthCss(count)})`;++ return (+ <div+ ref={ref}+ {...mergeProps(+ themeProps('tab-bar'),+ stylex.props(+ styles.root,+ styles.rootInset(px(tabBar.barInset)),+ xstyle,+ ),+ className,+ style,+ )}+ {...props}>+ <div+ ref={mergedCapsuleRef}+ role="tablist"+ aria-label={tabListLabel}+ aria-labelledby={ariaLabelledBy}+ aria-orientation="horizontal"+ onKeyDown={handleKeyDown}+ onFocus={handleFocus}+ {...stylex.props(+ styles.capsule,+ styles.capsuleSize(px(tabBar.barHeight), px(naturalWidth(count))),+ )}>+ {items.map((item, index) => {+ const isSelected = index === selectedIndex;+ const {start, width, itemStart} = column(index, count);+ return (+ <button+ key={item.value}+ type="button"+ role="tab"+ id={`${baseId}-tab-${index}`}+ aria-selected={isSelected}+ aria-controls={item.panelId}+ tabIndex={+ isSelected || (selectedIndex < 0 && index === 0) ? 0 : -1+ }+ // A badge is part of the name: one message with both.+ aria-label={+ hasBadge(item.badge)+ ? t('@astryx.tabBar.badgedItem', {+ label: item.label,+ badge: item.badgeLabel ?? String(item.badge),+ })+ : undefined+ }+ data-tab-bar-value={item.value}+ onClick={() => choose(item)}+ {...mergeProps(+ themeProps('tab-bar-item', {+ selected: isSelected ? 'selected' : null,+ }),+ stylex.props(+ tabBarItemMarker,+ styles.item,+ styles.column(start, width),+ ),+ )}>+ <span+ {...stylex.props(+ styles.itemBox,+ // At rest the tab draws its selected look; while the lens+ // slides, the copy inside it does.+ isSelected && !lens.isCopyShown && styles.itemSelectedLook,+ styles.box(itemStart, ITEM_TOP, itemSize, ITEM_HEIGHT),+ )}>+ <ItemFace+ item={item}+ isSelectedLook={isSelected && !lens.isCopyShown}+ />+ </span>+ </button>+ );+ })}+ {selectedIndex >= 0 ? (+ <div+ aria-hidden+ data-tab-bar-lens=""+ {...stylex.props(+ styles.lens,+ !lens.isCopyShown && styles.lensUnder,+ styles.box(capsuleInset, capsuleInset, itemSize, ITEM_HEIGHT),+ styles.lensRest(lensOffset(restIndex, count)),+ )}>+ <div+ ref={lens.body}+ data-tab-bar-lens-body=""+ {...stylex.props(styles.lensBody)}>+ <div+ ref={lens.clip}+ data-tab-bar-lens-clip=""+ {...stylex.props(styles.lensClip)}>+ {lens.isCopyShown ? (+ <div+ ref={lens.copy}+ data-tab-bar-copy=""+ {...stylex.props(styles.copyInner)}>+ <div+ {...stylex.props(+ styles.copyOuter,+ styles.copyOuterGeometry(+ capsuleInset,+ px(tabBar.barHeight),+ ),+ styles.copyRest(lensOffset(restIndex, count)),+ )}>+ {items.map((item, index) => (+ <span+ key={item.value}+ ref={lens.copyItem(index)}+ data-tab-bar-copy-item={item.value}+ {...stylex.props(+ styles.copyItem,+ styles.box(+ `calc(${center(index, count)} - ${itemWidthCss(count)} / 2)`,+ ITEM_TOP,+ itemSize,+ ITEM_HEIGHT,+ ),+ )}>+ <ItemFace item={item} isSelectedLook isCopy />+ </span>+ ))}+ </div>+ </div>+ ) : null}+ </div>+ </div>+ </div>+ ) : null}+ <div aria-hidden {...stylex.props(styles.badges)}>+ {items.map((item, index) =>+ hasBadge(item.badge) ? (+ <span+ key={item.value}+ data-tab-bar-badge={item.value}+ {...stylex.props(+ styles.badge,+ styles.badgeGeometry(+ `calc(${center(index, count)} + ${px(tabBar.badge.offsetX)})`,+ px(tabBar.itemInset + tabBar.badge.offsetY),+ px(tabBar.badge.height),+ px(tabBar.badge.paddingInline),+ px(tabBar.badge.fontSize),+ ),+ )}>+ {item.badge}+ </span>+ ) : null,+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/packages/lab/src/TabBar/TabBarTouch.ts b/packages/lab/src/TabBar/TabBarTouch.tsnew file mode 100644index 0000000000..cc1cce12e0--- /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.tsnew file mode 100644index 0000000000..ecc9a66605--- /dev/null+++ b/packages/lab/src/TabBar/__tests__/TabBar.interaction.browser.spec.ts@@ -0,0 +1,2154 @@+// 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<Element['animate']>+ ) {+ 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;+}++/** How strongly a tab's press paint shows: its layer's opacity, 0 when off. */+async function itemPaint(page: Page, name: string) {+ return tab(page, name)+ .locator('span')+ .first()+ .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);+ });+}++/**+ * 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, '::before')),+ 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, '::before').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, 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);+ 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, 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(+ 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, 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);+ 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')).toBe(1);+ }+ // 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 DR2)', 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')).toBe(1);+ 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('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,+}) => {+ 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<ReturnType<typeof runningAnimations>>,+) {+ 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<ReturnType<typeof runningAnimations>>,+) {+ 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))}),+ judges: {target: lensBody(page), property: 'translate'},+ 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.tsnew file mode 100644index 0000000000..7441666a5e--- /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.tsnew file mode 100644index 0000000000..eb4b35236f--- /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<typeof stylex.defineMarker> =+ stylex.defineMarker();diff --git a/packages/lab/src/TabBar/tabBarModel.test.ts b/packages/lab/src/TabBar/tabBarModel.test.tsnew file mode 100644index 0000000000..ea577c58af--- /dev/null+++ b/packages/lab/src/TabBar/tabBarModel.test.ts@@ -0,0 +1,179 @@+// 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,+} 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('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.tsnew file mode 100644index 0000000000..42ceee51ce--- /dev/null+++ b/packages/lab/src/TabBar/tabBarModel.ts@@ -0,0 +1,115 @@+// 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, 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;+}++/**+ * 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>): 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.tsnew file mode 100644index 0000000000..b86e77c27f--- /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.tsnew file mode 100644index 0000000000..e2eccde8da--- /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.tsnew file mode 100644index 0000000000..d56d3037a5--- /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<HTMLDivElement | null>;+ 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<Press | null>(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<number | null>(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.tsindex ca6adeb0db..d5fb98d29f 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -342,6 +342,14 @@ export {// PageControl: UIPageControl's row of page indicators.export {PageControl, type PageControlProps} from './PageControl';+// 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';