An open source design system that's fully customizable and agent ready
TypeScript
feat(List): a row's touch target grows toward 44 px where its neighbors leave room (#8085)
Christopher Chedeau7b71d71b495b
diff --git a/.changeset/list-touch-hit-area.md b/.changeset/list-touch-hit-area.mdnew file mode 100644index 0000000000..8cba495d31--- /dev/null+++ b/.changeset/list-touch-hit-area.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Under a finger (a coarse primary pointer), an interactive `List` row's hit target grows toward 44px where its neighbors leave room: the shared touch hit area measures each row and stops at half the gap to the nearest neighboring row or control. Rows look and lay out exactly as before, and a mouse is unchanged. Under a finger a list row's `::after` is that invisible layer, so decorate a row with a child instead. An `Item` that stops delegating to a nested control now drops its pressable-container marker, so a clickable card around it gets a mouse click in the row's padding again. `InfoTip`'s button takes taps through the same layer: it still grows toward 44px where its neighbors leave room, and waits for motion around it to end before it grows; it clears when it stops taking taps. A labelled `CheckboxInput` and a `RadioListItem` option keep their band's insets through the same hook, so the insets clear when the control stops taking taps.++@vjeuxdiff --git a/apps/storybook/stories/InfoTip.stories.tsx b/apps/storybook/stories/InfoTip.stories.tsxindex 18fe06b97a..9958fe10e2 100644--- a/apps/storybook/stories/InfoTip.stories.tsx+++ b/apps/storybook/stories/InfoTip.stories.tsx@@ -3,6 +3,7 @@import type {Meta, StoryObj} from '@storybook/react';import {InfoTip} from '@astryxdesign/core/InfoTip';import {HStack} from '@astryxdesign/core/Layout';+import {List, ListItem} from '@astryxdesign/core/List';import {Text} from '@astryxdesign/core/Text';const meta: Meta<typeof InfoTip> = {@@ -72,3 +73,35 @@ export const Sizes: Story = {</div>),};++/**+ * Info buttons at the end of divided List rows. Under a finger each button+ * takes taps out toward 44 px, as anywhere else. The row's divider never+ * widens that reach.+ */+export const InADividedList: Story = {+ render: () => (+ <div style={{maxWidth: 360}}>+ <List hasDividers>+ <ListItem+ label="Rolling average"+ endContent={+ <InfoTip+ content="30-day rolling average, recomputed nightly."+ label="About rolling average"+ />+ }+ />+ <ListItem+ label="Peak"+ endContent={+ <InfoTip+ content="The highest daily value this month."+ label="About peak"+ />+ }+ />+ </List>+ </div>+ ),+};diff --git a/apps/storybook/stories/List.stories.tsx b/apps/storybook/stories/List.stories.tsxindex fd49a67d67..bba5e975f8 100644--- a/apps/storybook/stories/List.stories.tsx+++ b/apps/storybook/stories/List.stories.tsx@@ -13,11 +13,13 @@ import type {Meta, StoryObj} from '@storybook/react';import {List, ListItem} from '@astryxdesign/core/List';import {Avatar} from '@astryxdesign/core/Avatar';import {Badge} from '@astryxdesign/core/Badge';+import {Button} from '@astryxdesign/core/Button';import {Card} from '@astryxdesign/core/Card';import {Icon} from '@astryxdesign/core/Icon';import {Switch} from '@astryxdesign/core/Switch';import {Heading, Text} from '@astryxdesign/core/Text';import {VStack} from '@astryxdesign/core/Layout';+import {rtlStyles} from '@astryxdesign/core/utils';import {Cog6ToothIcon,BellIcon,@@ -257,6 +259,77 @@ export const Links: Story = {),};+function EndControlsDemo() {+ const [isWifiOn, setIsWifiOn] = useState(true);+ return (+ // The button after the list sits 4 px below its last row.+ <div style={{display: 'flex', flexDirection: 'column', gap: 4}}>+ <List+ density="compact"+ hasDividers+ header={+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <Text type="label" size="lg">+ Connections+ </Text>+ <Button label="Edit" variant="ghost" size="sm" />+ </div>+ }>+ <ListItem+ label="Network"+ onClick={() => {}}+ endContent={+ <Icon icon={ChevronRightIcon} xstyle={rtlStyles.mirror} />+ }+ swipeActions={{trailing: [{label: 'Forget', onActivate: () => {}}]}}+ />+ <ListItem+ label="Wi-Fi"+ endContent={+ <Switch+ label="Wi-Fi"+ isLabelHidden+ value={isWifiOn}+ onChange={checked => setIsWifiOn(checked)}+ />+ }+ />+ <ListItem+ label="Bluetooth"+ onClick={() => {}}+ endContent={+ <Icon icon={ChevronRightIcon} xstyle={rtlStyles.mirror} />+ }+ />+ </List>+ <Button label="Load more" variant="secondary" />+ </div>+ );+}++export const WithEndControls: Story = {+ render: () => <EndControlsDemo />,+ parameters: {+ docs: {+ description: {+ story:+ 'A compact row whose end content is its own control, a switch, ' ++ 'between two interactive rows (the first one swipeable), under a ' ++ 'header with its own button ' ++ 'and above a button 4 px after the list. Under a finger, the ' ++ 'interactive rows grow ' ++ 'their touch targets only where nothing is near, never into the ' ++ "control's row, and a tap on the switch stays the switch's.",+ },+ },+ },+};+export const OrderedList: Story = {render: args => (<List listStyle="decimal" {...args}>diff --git a/docs/specs/components/List/List.spec.md b/docs/specs/components/List/List.spec.mdindex ca0af676dd..7da2fb008a 100644--- a/docs/specs/components/List/List.spec.md+++ b/docs/specs/components/List/List.spec.md@@ -14,6 +14,8 @@ verified_by:[packages/core/src/List/List.test.tsx,packages/core/src/Item/Item.test.tsx,+ packages/core/src/List/ListItem.hitArea.test.tsx,+ packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.ts,packages/core/src/theme/derivedVarRegistry.test.ts,packages/core/src/theme/generateThemeRules.test.ts,apps/storybook/stories/List.stories.tsx,@@ -49,7 +51,7 @@ system_specs:| Behavior | One edge treatment applies to every ListItem row and decides where row content and row paint sit relative to the list's edges and the host's padding. With `reorderable`, rows reorder by dragging a handle or through reorder mode (`spec:AST-103` FR3, FR4). Under a coarse pointer a row's press follows the cell profile (`spec:AST-094` FR11); with `animatedLayout`, row updates animate (`spec:AST-105`). A row menu opens from the row's own `<li>` on the context request (FR13). || End-user impact | Row text can share the line of the list header and a heading above, with row paint stopping at the text, reaching into the host padding, or reaching the host edges. Touch users get a 44 px row target (FR10) and the cell press (FR11); with `animatedLayout`, row updates animate for every pointer (FR12). A row with a menu opens it by a long press, a right click, or Shift+F10, or through its More actions button (FR13). || Builder impact | One `edge` choice per list. `flush` works anywhere; `outset` and `bleed` act only inside a host that publishes container padding. Passing an `animatedLayout` handle is one new choice, and a row menu is the other: the caller passes a ListItem's ref to `useContextMenu` (FR13), and who draws a plain row's More actions button is open (OQ2); and rows animate only with an `itemKey`; the touch target and press need none. |-| Compatibility/readiness | Additive; omission keeps current geometry; `edgeCompensation` keeps working with a codemod to `edge`. `reorderable` and `itemKey` are additive and stable, specified and not implemented yet; without them nothing changes. `animatedLayout` is additive and specified, not implemented yet. The touch target (FR10) is specified, not implemented yet; the press's compositor release (FR11) is implemented. Neither changes anything under a fine pointer. Row menus (FR13) are additive and specified, not implemented yet. |+| Compatibility/readiness | Additive; omission keeps current geometry; `edgeCompensation` keeps working with a codemod to `edge`. `reorderable` and `itemKey` are additive and stable, specified and not implemented yet; without them nothing changes. `animatedLayout` is additive and specified, not implemented yet. The touch target (FR10) and the press's compositor release (FR11) are implemented under coarse primary pointers. Neither changes anything under a fine pointer. Row menus (FR13) are additive and specified, not implemented yet. || Review checks | Reject header movement, row paint past the host's padding edge, duplicated padding values, physical-edge logic, automatic opt-in, a ListItem-level edge prop, or a second prop that can contradict `edge`. || Governing rules | `architecture:container-padding/INV3`, `INV9–INV11`; `spec:AST-002/DEC-1–DEC-2`; `spec:AST-017/FR4`; `spec:AST-057/FR9`. `spec:AST-103`. `spec:AST-094` FR4, FR5, FR11, FR13; `spec:AST-105` FR1–FR5, FR8. `spec:AST-107` FR8 (row menus). |@@ -80,6 +82,8 @@ from its rows, and the choice must hold for the whole collection.and where the List also spreads props (`spec:AST-017` FR29c–FR29d). A spread onto aList that never writes `edgeCompensation` stays unchanged (`spec:AST-040` FR1);the `@deprecated` type reports a typed use where the props are written.+- Current state: Under a finger, a caller's `::after` on an interactive ListItem+ row is replaced by the touch hit area.Consumer migration instructions belong in consumer docs and release notes.@@ -130,7 +134,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR8 | `outset` and `bleed` are valid only under a host state whose published inline inset matches its applied padding: a visually neutral host, such as a Layout region with explicit padding or a padded ScrollableArea, or the content area of a Card, Section (any variant), Dialog, or BottomSheet. Those hosts bound their padding with a border, background, or clip; FR6 keeps row paint inside the padding edge, so it never covers the border or changes the host's outline. Automatic LayoutContent/LayoutPanel states with a known publication mismatch are not eligible until that gap is fixed, and Drawer's content area is not admitted until it has its own evidence. | `architecture:container-padding/INV8–INV11`; real-browser evidence in each admitted host | Accepted contract || FR9 | The list element containing the rows MUST clip in the inline axis with `overflow-inline: clip`, never `hidden`, except for static Markdown document lists that expose no swipe actions (DEC-5). Those Markdown lists, ordered or unordered, MAY use visible inline overflow so their own or descendant number markers remain whole while retaining AST-061 FR11's text starts and nested insets. General Lists and any collection with swipe-capable rows MUST retain the clip. Under `outset` and `bleed` its inline edges MUST reach the host's padding edge, so the clip never cuts resting row paint and a swiped row paints no further than that edge. | `spec:AST-057/FR9`; `component:List/DEC-5`; `spec:AST-061/FR11` | Verified by `List.test.tsx` and real-browser geometry || FR10 | Under a coarse primary pointer (`spec:AST-094` FR13), every ListItem row MUST offer a hit target at least 44 px tall, through its padding or an invisible hit area, with no visual change, where its neighbors leave room: the hit area never overlaps a neighboring row's or control's target, and between close neighbors it is clamped to half the gap; row height and geometry stay as they are at every density. A fine pointer keeps today's hit target. | Owner decision, 2026-10-26: no row-height change, a 44 px touch target | Accepted contract |-| FR11 | Under a coarse primary pointer, an interactive row's press MUST follow the cell profile (`spec:AST-094` FR11): it paints the `--color-overlay-pressed` token above the row's background and below its content without adding an element, and its release fades on the theme's exit motion tokens (`--duration-exit`, `--ease-exit`) on the compositor (`spec:AST-094` FR5). The row's dividers stay drawn while it is pressed, in every theme. At rest the row's paint and stacking are as they were. Under the touch presentation, an interactive Item, ListItem or TreeList row uses its `::before` as the press layer, and a pressed row's divider keeps its resting colour. A caller's own `::before` on such a row merges into the press layer only while it is pressed; use `::after` or a child for decoration. | `spec:AST-094` FR5, FR11; `component:List/DEC-6` | Accepted contract |+| FR11 | Under a coarse primary pointer, an interactive row's press MUST follow the cell profile (`spec:AST-094` FR11): it paints the `--color-overlay-pressed` token above the row's background and below its content without adding an element, and its release fades on the theme's exit motion tokens (`--duration-exit`, `--ease-exit`) on the compositor (`spec:AST-094` FR5). The row's dividers stay drawn while it is pressed, in every theme. At rest the row's paint and stacking are as they were. Under the touch presentation, an interactive Item, ListItem or TreeList row uses its `::before` as the press layer, and a pressed row's divider keeps its resting colour. A caller's own `::before` on such a row merges into the press layer only while it is pressed; use `::after` or a child for decoration. An interactive ListItem row also uses its `::after` as its touch hit area (FR10), so decorate such a row with a child. | `spec:AST-094` FR5, FR11; `component:List/DEC-6` | Accepted contract || FR12 | List MUST take an `animatedLayout` handle (`spec:AST-105` FR1) and report each row inserted, removed, or moved between renders. With a handle, an inserted row enters, a removed row collapses in place, inert and hidden from assistive technology until it is gone, and a row crossing rows moving the other way rides above them on the list's surface, while the rows after a change glide to their new places (`spec:AST-105` FR3), all starting on one frame on the shared motion role (`spec:AST-105` FR4). Without a handle the list changes at once (`spec:AST-105` FR2). A row's identity is its `itemKey` (`spec:AST-103` DEC-4); a row without one changes at once. With a handle, a row also reports a change to its start or end content: content that appears enters, content that leaves exits (a slot that sets the row's height hides at once instead, and the row's other content and the rows after it take their final places at once, as `spec:AST-105`'s Coverage states), content replaced in the same slot swaps in place (`spec:AST-105` FR4, FR8), and the row's other content glides within the row; a slot whose content changes without changing size does not animate. The reorder handle's appearance (`spec:AST-103`) is such a change. A slot control that leaves is inert and hidden from assistive technology as its exit starts; if it held focus, focus moves to the row's focus target (or to the row, which takes focus programmatically for the handoff) without scrolling. | `spec:AST-105` FR1–FR5; `spec:AST-103` DEC-4; `spec:AST-105` FR8; `spec:AST-103` FR2 (the handle renders only with `reorderable`) | Accepted contract || FR13 | A row menu on a ListItem attaches to the row's own `<li>`, keeping `ul > li` with no wrapper element: the caller passes the ListItem's ref to `useContextMenu` (`spec:AST-107` FR8), with no ListItem prop of its own; the whole row is its hit area, it opens on the context request (a long press, a right click, or Shift+F10), under a finger, the row takes the press paint (FR11; on a plain row, part of OQ2) and lifts as the menu grows from it, `useContextMenu` lifting the element it is attached to (`spec:AST-094` FR31, FR33), while a mouse, the keyboard, and `presentation: 'popover'` open the released menu without the lift (`spec:AST-094` FR41), and focus returns to the row's focus target when the menu closes. A row that is already focusable (`onClick` or `href`) takes Shift+F10 and the context-menu key directly, and a row with an `interactiveRef` takes them on that element; neither shows a "More actions" button; a row with none of these shows a visible "More actions" button named with the row's label, such as "More actions for Inbox", its keyboard and screen-reader path to the menu. When a menu opens, focus moves into it; when it closes, focus returns to the row's focus target, or to the "More actions" button on a row that shows one. Who moves focus there, since `useContextMenu` returns focus to the `<li>`, which takes none, is part of OQ2. A reorderable row always has its handle (`spec:AST-103` FR3), so when it also has a row menu, a hold on the handle picks the row up and a hold anywhere else on the row opens the menu. | Owner decision, 2026-10-26; `spec:AST-107` FR8 | Accepted contract |@@ -317,10 +321,11 @@ Rejected: widening a finite marker gutter, because it only moves the counter-wid**Decider:** cixzhang, 2026-10-25Under the touch presentation, an interactive row paints its press on its own-`::before`, the one paint the compositor can fade while script runs. A-caller's own `::before` on the row merges into that layer only while the row-is pressed, so decoration that must stay through a press goes on `::after` or-a child. A pressed row's divider keeps its resting colour.+`::before`, the one paint the compositor can fade while script runs. A caller's+own `::before` on the row merges into that layer only while the row is pressed,+so decoration that must stay through a press goes on a child, or on `::after`+where it is free. An interactive ListItem row's `::after` is its touch hit area+(FR10). A pressed row's divider keeps its resting colour.Rejected: leaving a caller's `::before` intact through a press, because therow then needs a second element or a main-thread paint for its press.diff --git a/packages/core/src/CheckboxInput/CheckboxInput.tsx b/packages/core/src/CheckboxInput/CheckboxInput.tsxindex 66325fc72d..e5ce3784c0 100644--- a/packages/core/src/CheckboxInput/CheckboxInput.tsx+++ b/packages/core/src/CheckboxInput/CheckboxInput.tsx@@ -57,7 +57,7 @@ import {useIndicator} from '../Indicator/useIndicator';import {themeProps} from '../utils/themeProps';import {useMergedRefs} from '../hooks/useMergedRefs';-import {watchHitArea, writeHitInsets} from '../utils/hitArea';+import {useTouchHitArea} from '../utils/touchHitArea';import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';import {registerEnglishFallback,@@ -420,17 +420,9 @@ export function CheckboxInput({// checkbox is a marker in another component's row, which keeps its target.const hasHitArea = !isLabelHidden && !isDisabled && !isReadOnly;const inputRef = useRef<HTMLInputElement>(null);- // The watch lives as long as the row is attached: the ref's cleanup stops- // it, and a replaced row starts its own.- const watchRowHitArea = useCallback(- (row: HTMLDivElement | null) => {- if (row == null || !hasHitArea) {- return;- }- return watchHitArea(row, insets => writeHitInsets(row, insets));- },- [hasHitArea],- );+ // The band's insets stay live while the row takes taps, and clear when it+ // stops.+ const watchRowHitArea = useTouchHitArea(hasHitArea);// The disabled-message tooltip listens for hover and focus on the whole// row, a larger trigger. It anchors on the checkbox itself (below), so it// shows next to the control. Its handlers check isEnabled, so the rowdiff --git a/packages/core/src/Indicator/touchTarget.test.tsx b/packages/core/src/Indicator/touchTarget.test.tsxindex 9bb3611973..5a8ec0be4a 100644--- a/packages/core/src/Indicator/touchTarget.test.tsx+++ b/packages/core/src/Indicator/touchTarget.test.tsx@@ -280,6 +280,48 @@ describe('the hit band is at least 44 px and never smaller than the row (FR42)',}});+ it('clears a checkbox row’s insets when it stops taking taps', async () => {+ const {rerender} = render(+ <CheckboxInput label="Accept" value={false} onChange={() => {}} />,+ );+ const row = closestOrThrow(+ screen.getByRole('checkbox', {name: 'Accept'}),+ '[data-astryx-pressable]',+ );+ measure(row, 24);+ expect(row.style.getPropertyValue(HIT_INSET_PROPERTIES.top)).toBe('10px');+ rerender(+ <CheckboxInput+ label="Accept"+ value={false}+ onChange={() => {}}+ isDisabled+ />,+ );+ await Promise.resolve();+ expect(row.style.getPropertyValue(HIT_INSET_PROPERTIES.top)).toBe('0px');+ expect(row.style.getPropertyValue(HIT_INSET_PROPERTIES.bottom)).toBe('0px');+ });++ it('clears a radio option’s insets when it stops taking taps', async () => {+ const options = (isDisabled: boolean) => (+ <RadioList label="Plan" value="a" onChange={() => {}}>+ <RadioListItem label="Option A" value="a" isDisabled={isDisabled} />+ </RadioList>+ );+ const {rerender} = render(options(false));+ const row = closestOrThrow(+ screen.getByRole('radio', {name: 'Option A'}),+ '.astryx-item',+ );+ measure(row, 24);+ expect(row.style.getPropertyValue(HIT_INSET_PROPERTIES.top)).toBe('10px');+ rerender(options(true));+ await Promise.resolve();+ expect(row.style.getPropertyValue(HIT_INSET_PROPERTIES.top)).toBe('0px');+ expect(row.style.getPropertyValue(HIT_INSET_PROPERTIES.bottom)).toBe('0px');+ });+it('grows a 24 px radio option to 44 px, and leaves a 60 px one at its own box', () => {for (const [height, expected] of [[24, 44],diff --git a/packages/core/src/InfoTip/InfoTip.test.tsx b/packages/core/src/InfoTip/InfoTip.test.tsxindex 5f61601a51..c07c565050 100644--- a/packages/core/src/InfoTip/InfoTip.test.tsx+++ b/packages/core/src/InfoTip/InfoTip.test.tsx@@ -414,7 +414,7 @@ describe('InfoTip', () => {});describe('touch hit area (AR1)', () => {- it('grows the button toward 44 px as far as the shared hit area allows', () => {+ it('grows the button toward 44 px as far as the shared hit area allows', async () => {const {unmount} = render(<InfoTip content="Helpful context" />);const trigger = screen.getByRole('button', {name: 'More information'});const watch = hitAreaWatches.find(entry => entry.element === trigger);@@ -429,9 +429,29 @@ describe('InfoTip', () => {);unmount();+ await Promise.resolve();expect(hitAreaWatches.some(entry => entry.element === trigger)).toBe(false,);});++ it('clears the button’s insets when its watch stops', async () => {+ const {unmount} = render(<InfoTip content="Helpful context" />);+ const trigger = screen.getByRole('button', {name: 'More information'});+ const watch = hitAreaWatches.find(entry => entry.element === trigger);+ act(() => watch?.onInsets({top: 12, right: 6, bottom: 12, left: 4}));+ expect(trigger.style.getPropertyValue('--astryx-hit-inset-top')).toBe(+ '12px',+ );++ unmount();+ await Promise.resolve();+ expect(trigger.style.getPropertyValue('--astryx-hit-inset-top')).toBe(+ '0px',+ );+ expect(trigger.style.getPropertyValue('--astryx-hit-inset-left')).toBe(+ '0px',+ );+ });});});diff --git a/packages/core/src/InfoTip/InfoTip.tsx b/packages/core/src/InfoTip/InfoTip.tsxindex 34874bc8ca..9534101abd 100644--- a/packages/core/src/InfoTip/InfoTip.tsx+++ b/packages/core/src/InfoTip/InfoTip.tsx@@ -47,7 +47,8 @@ import {} from '../theme/tokens.stylex';import {focusOutlineStyles} from '../utils/focusOutline.stylex';import {mergeProps} from '../utils/mergeProps';-import {watchHitArea, writeHitInsets} from '../utils/hitArea';+import {useTouchHitArea} from '../utils/touchHitArea';+import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';registerEnglishFallback(english);@@ -107,21 +108,6 @@ const styles = stylex.create({transitionDuration: durationVars['--duration-fast'],transitionTimingFunction: easeVars['--ease-standard'],},- // The invisible hit area. Under a coarse pointer, the shared hit area writes- // how far the button may grow toward 44 px on each side. It never takes a- // neighbour's tap, and it writes 0 elsewhere. This layer takes taps out to- // there.- // SYNC: /packages/core/src/utils/hitArea.ts (HIT_INSET_PROPERTIES)- hitArea: {- '::after': {- content: '""',- position: 'absolute',- // Physical sides on purpose: the shared hit area measures each side- // from the page's rects, left and right included, in any direction.- inset:- 'calc(var(--astryx-hit-inset-top, 0px) * -1) calc(var(--astryx-hit-inset-right, 0px) * -1) calc(var(--astryx-hit-inset-bottom, 0px) * -1) calc(var(--astryx-hit-inset-left, 0px) * -1)',- },- },});/**@@ -151,15 +137,7 @@ export function InfoTip({style,}: InfoTipProps): ReactNode {const t = useComponentTranslator();- // Under a coarse pointer the button takes taps out toward 44 px. The watch- // lives as long as the button is attached: the ref's cleanup stops it, and a- // replaced button starts its own.- const watchButtonHitArea = useCallback((button: HTMLButtonElement | null) => {- if (button == null) {- return;- }- return watchHitArea(button, insets => writeHitInsets(button, insets));- }, []);+ const hitAreaRef = useTouchHitArea(true);// Whether a press pinned the help. A hover or focus preview is not pinned.const [isPinned, setIsPinned] = useState(false);// Whether the help shows, pinned or previewed: the button names it in@@ -173,7 +151,7 @@ export function InfoTip({setIsPinned(false);}, []);const tooltip = useTooltip({onShow: handleShow, onHide: handleHide});- const mergedRef = useMergedRefs(ref, watchButtonHitArea, tooltip.ref);+ const mergedRef = useMergedRefs(ref, hitAreaRef, tooltip.ref);// A primary mouse or pen press on a preview calls show() first. The hook's// press-to-close then leaves it open. The click pins it.@@ -227,7 +205,7 @@ export function InfoTip({stylex.props(focusOutlineStyles.focusVisible,styles.trigger,- styles.hitArea,+ touchHitAreaStyles.layer,xstyle,),className,diff --git a/packages/core/src/InfoTip/__tests__/InfoTipTouch.a11y.chromium.spec.ts b/packages/core/src/InfoTip/__tests__/InfoTipTouch.a11y.chromium.spec.tsindex 0e67976db3..6274c90ef4 100644--- a/packages/core/src/InfoTip/__tests__/InfoTipTouch.a11y.chromium.spec.ts+++ b/packages/core/src/InfoTip/__tests__/InfoTipTouch.a11y.chromium.spec.ts@@ -178,6 +178,42 @@ test('the hit area stops halfway to a neighbouring button', async ({}});+test('inside a divided List row the info button reaches its measured inset and no further', async ({+ browser,+}) => {+ const page = await pageWith(browser, 'coarse');+ await openStory(page, 'in-a-divided-list');+ const buttons = page.locator('#storybook-root').getByRole('button');+ await expect(buttons).toHaveCount(2);+ const button = buttons.first();+ const box = await button.boundingBox();+ expect(box?.width ?? 0).toBeGreaterThan(0);+ expect(box?.height ?? 0).toBeGreaterThan(0);+ await expect+ .poll(async () =>+ button.evaluate(element =>+ Number.parseFloat(+ getComputedStyle(element).getPropertyValue(+ '--astryx-hit-inset-bottom',+ ),+ ),+ ),+ )+ .toBeGreaterThan(0);+ const [inset, layerBottom, inheritedBorder] = await button.evaluate(+ element => [+ Number.parseFloat(+ getComputedStyle(element).getPropertyValue('--astryx-hit-inset-bottom'),+ ),+ Number.parseFloat(getComputedStyle(element, '::after').bottom),+ getComputedStyle(element).getPropertyValue('--_hit-border-bottom').trim(),+ ],+ );+ // The row's divider width stays on the row's own layer.+ expect(inheritedBorder).toBe('');+ expect(layerBottom).toBeCloseTo(-inset, 1);+});+test('under a fine pointer the info button grows nothing', async ({browser,}) => {diff --git a/packages/core/src/Item/Item.nestedPress.test.tsx b/packages/core/src/Item/Item.nestedPress.test.tsxindex 310a689b96..522e7a3915 100644--- a/packages/core/src/Item/Item.nestedPress.test.tsx+++ b/packages/core/src/Item/Item.nestedPress.test.tsx@@ -72,3 +72,14 @@ it('paints no press on the row for a finger on another control inside it', () =>expect(rowOf(more).hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);fireEvent.pointerUp(more, {pointerType: 'touch', pointerId: 1});});++it('keeps the row marked as a pressable container while a finger on another control inside it paints no press', () => {+ render(<DelegatingRow />);+ const more = screen.getByRole('button', {name: 'More'});+ const row = rowOf(more);+ expect(row.getAttribute('data-pressable-container')).toBe('true');+ fingerOn(more);+ expect(row.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);+ expect(row.getAttribute('data-pressable-container')).toBe('true');+ fireEvent.pointerUp(more, {pointerType: 'touch', pointerId: 1});+});diff --git a/packages/core/src/Item/Item.test.tsx b/packages/core/src/Item/Item.test.tsxindex b8993bb481..aaf6529f40 100644--- a/packages/core/src/Item/Item.test.tsx+++ b/packages/core/src/Item/Item.test.tsx@@ -9,7 +9,7 @@* SYNC: When Item component changes, update tests to match new behavior*/-import {use, useRef, type ReactNode} from 'react';+import {Activity, use, useRef, type ReactNode} from 'react';import {afterEach,beforeAll,@@ -25,6 +25,7 @@ import {swipeLayerLoaded} from './__tests__/swipeLayerLoaded';import userEvent from '@testing-library/user-event';import {LinkProvider} from '../Link/LinkProvider';import {Item} from './Item';+import {useClickableContainer} from '../hooks/useClickableContainer';import {ItemDescriptionContext} from './ItemDescriptionContext';import {List, ListItem} from '../List';@@ -287,6 +288,39 @@ describe('Item', () => {expect(document.body).toHaveFocus();});+ it('drops its pressable marker when a row stops delegating, so a mouse click in its padding reaches a clickable container around it', () => {+ const cardClick = vi.fn();+ function Card({delegates}: {delegates: boolean}) {+ const cardRef = useRef<HTMLDivElement | null>(null);+ const checkboxRef = useRef<HTMLInputElement>(null);+ const {onClick} = useClickableContainer({+ containerRef: cardRef,+ onClick: cardClick,+ });+ return (+ <div ref={cardRef} onClick={onClick}>+ <Item+ label="Row"+ interactiveRef={delegates ? checkboxRef : undefined}+ startContent={+ <input ref={checkboxRef} type="checkbox" aria-label="Pick row" />+ }+ />+ </div>+ );+ }+ const {container, rerender} = render(<Card delegates />);+ const row = container.firstElementChild?.firstElementChild as HTMLElement;+ expect(row).toHaveAttribute('data-pressable-container', 'true');++ rerender(<Card delegates={false} />);+ expect(row).not.toHaveAttribute('data-pressable-container');+ withPrimaryPointer(false, () => {+ fireEvent.click(row, {detail: 1});+ });+ expect(cardClick).toHaveBeenCalledTimes(1);+ });+it('delegates a row-surface click to the interactive control', async () => {const user = userEvent.setup();const onToggle = vi.fn();@@ -341,6 +375,243 @@ describe('Item', () => {expect(anchor?.textContent).toContain('Link');});+ /** A List link row whose box spans x 0–100 and y 10–50, its anchor followed. */+ function linkRow(endContent?: ReactNode) {+ const {container} = render(+ <List>+ <ListItem label="Link" href="/docs" endContent={endContent} />+ </List>,+ );+ const anchor = container.querySelector('a') as HTMLAnchorElement;+ const followed = vi.fn((event: MouseEvent) => event.preventDefault());+ anchor.addEventListener('click', followed);+ const row = container.querySelector('li') as HTMLElement;+ vi.spyOn(row, 'getBoundingClientRect').mockReturnValue(+ DOMRect.fromRect({x: 0, y: 10, width: 100, height: 40}),+ );+ return {anchor, followed, row};+ }++ it('follows the link on a tap in a List link row’s touch band, past its box', () => {+ const {anchor, followed, row} = linkRow();+ fireEvent.click(row, {clientX: 50, clientY: 5, detail: 1});+ expect(followed).toHaveBeenCalledTimes(1);+ // A click on the anchor itself follows it once, not twice.+ fireEvent.click(anchor);+ expect(followed).toHaveBeenCalledTimes(2);+ // Modifier keys carry over, so a ctrl or cmd tap opens as on the label.+ fireEvent.click(row, {clientX: 50, clientY: 55, detail: 1, ctrlKey: true});+ expect(followed).toHaveBeenCalledTimes(3);+ expect(followed.mock.calls[2][0].ctrlKey).toBe(true);+ });++ it('does nothing for a mouse click inside a List link row’s box but outside its anchor', () => {+ const {followed, row} = linkRow();+ fireEvent.click(row, {clientX: 4, clientY: 30, detail: 1});+ expect(followed).not.toHaveBeenCalled();+ });++ /** Runs `body` with the primary pointer coarse or fine. */+ function withPrimaryPointer(coarse: boolean, body: () => void) {+ const original = window.matchMedia;+ window.matchMedia = ((query: string) => ({+ matches: coarse && query === '(pointer: coarse)',+ media: query,+ addEventListener() {},+ removeEventListener() {},+ })) as unknown as typeof window.matchMedia;+ try {+ body();+ } finally {+ window.matchMedia = original;+ }+ }++ it('decides a tap in a List link row’s own padding by the primary pointer, not the pointer that made it', () => {+ const {followed, row} = linkRow();+ // A fine primary pointer keeps the anchor as the target: a finger's tap in+ // the padding (a touch screen beside a mouse) does nothing.+ withPrimaryPointer(false, () => {+ fireEvent.pointerDown(row, {pointerType: 'touch'});+ fireEvent.click(row, {clientX: 4, clientY: 30, detail: 1});+ });+ expect(followed).not.toHaveBeenCalled();+ // Under a coarse primary pointer the padding is part of the row's+ // target, whatever pointer made the click (WebKit reports a finger's+ // click as `mouse`).+ withPrimaryPointer(true, () => {+ fireEvent.pointerDown(row, {pointerType: 'mouse'});+ fireEvent.click(row, {clientX: 4, clientY: 30, detail: 1});+ });+ expect(followed).toHaveBeenCalledTimes(1);+ });++ it('keeps a standalone link Item to its anchor under a finger: a tap in its padding or past its box does nothing', () => {+ const {container} = render(<Item label="Link" href="/docs" />);+ const anchor = container.querySelector('a') as HTMLAnchorElement;+ const followed = vi.fn((event: MouseEvent) => event.preventDefault());+ anchor.addEventListener('click', followed);+ const row = container.firstElementChild as HTMLElement;+ vi.spyOn(row, 'getBoundingClientRect').mockReturnValue(+ DOMRect.fromRect({x: 0, y: 10, width: 100, height: 40}),+ );+ withPrimaryPointer(true, () => {+ fireEvent.click(row, {clientX: 4, clientY: 30, detail: 1});+ fireEvent.click(row, {clientX: 50, clientY: 5, detail: 1});+ });+ expect(followed).not.toHaveBeenCalled();+ // Present first: its anchor itself still follows.+ fireEvent.click(anchor);+ expect(followed).toHaveBeenCalledTimes(1);+ });++ it('keeps a link Item inside a List row’s content to its anchor under a finger', () => {+ const {container} = render(+ <List>+ <ListItem label="Row" endContent={<Item label="Nested" href="/n" />} />+ </List>,+ );+ const nested = container.querySelector('li [href="/n"]')?.parentElement;+ const anchor = container.querySelector('[href="/n"]') as HTMLElement;+ const followed = vi.fn((event: MouseEvent) => event.preventDefault());+ anchor.addEventListener('click', followed);+ // Present first: the nested Item is in the row.+ expect(nested).not.toBeNull();+ withPrimaryPointer(true, () => {+ fireEvent.click(nested as HTMLElement, {detail: 1});+ });+ expect(followed).not.toHaveBeenCalled();+ });++ it('under a finger, leaves a tap on a control in a List link row’s end content to that control', () => {+ const control = vi.fn();+ const {followed} = linkRow(+ <span role="button" tabIndex={0} onClick={control}>+ More+ </span>,+ );+ withPrimaryPointer(true, () => {+ fireEvent.click(screen.getByRole('button', {name: 'More'}), {detail: 1});+ });+ expect(control).toHaveBeenCalledTimes(1);+ expect(followed).not.toHaveBeenCalled();+ });++ it('under a finger, does not follow a List link row’s link on the click that ends a text selection in it', () => {+ const {followed, row} = linkRow();+ // Present first: the same tap with no selection follows the link.+ withPrimaryPointer(true, () => {+ fireEvent.click(row, {clientX: 4, clientY: 30, detail: 1});+ });+ expect(followed).toHaveBeenCalledTimes(1);+ const selection = document.getSelection() as Selection;+ selection.selectAllChildren(row);+ try {+ withPrimaryPointer(true, () => {+ fireEvent.click(row, {clientX: 4, clientY: 30, detail: 1});+ });+ expect(followed).toHaveBeenCalledTimes(1);+ } finally {+ selection.removeAllRanges();+ }+ });++ it('with a mouse, leaves a click in a List link row’s padding to a clickable container around it', () => {+ const cardClick = vi.fn();+ function Card({children}: {children: ReactNode}) {+ const cardRef = useRef<HTMLDivElement | null>(null);+ const {onClick} = useClickableContainer({+ containerRef: cardRef,+ onClick: cardClick,+ });+ return (+ <div ref={cardRef} onClick={onClick}>+ {children}+ </div>+ );+ }+ const {container} = render(+ <Card>+ <List>+ <ListItem label="Link" href="/docs" />+ </List>+ </Card>,+ );+ const row = container.querySelector('li') as HTMLElement;+ const anchor = row.querySelector('a') as HTMLAnchorElement;+ const followed = vi.fn((event: MouseEvent) => event.preventDefault());+ anchor.addEventListener('click', followed);+ vi.spyOn(row, 'getBoundingClientRect').mockReturnValue(+ DOMRect.fromRect({x: 0, y: 10, width: 100, height: 40}),+ );+ withPrimaryPointer(false, () => {+ fireEvent.click(row, {clientX: 4, clientY: 30, detail: 1});+ });+ expect(followed).not.toHaveBeenCalled();+ expect(cardClick).toHaveBeenCalledTimes(1);+ expect(row).not.toHaveAttribute('data-pressable-container');+ });++ it('keeps a List link row unmarked after its Activity hides and shows, so a mouse click in its padding still reaches the card around it', () => {+ const cardClick = vi.fn();+ function Card({hidden}: {hidden: boolean}) {+ const cardRef = useRef<HTMLDivElement | null>(null);+ const {onClick} = useClickableContainer({+ containerRef: cardRef,+ onClick: cardClick,+ });+ return (+ <div ref={cardRef} onClick={onClick}>+ <Activity mode={hidden ? 'hidden' : 'visible'}>+ <List>+ <ListItem label="Link" href="/docs" />+ </List>+ </Activity>+ </div>+ );+ }+ const {container, rerender} = render(<Card hidden={false} />);+ const row = container.querySelector('li') as HTMLElement;+ const anchor = row.querySelector('a') as HTMLAnchorElement;+ const followed = vi.fn((event: MouseEvent) => event.preventDefault());+ anchor.addEventListener('click', followed);+ vi.spyOn(row, 'getBoundingClientRect').mockReturnValue(+ DOMRect.fromRect({x: 0, y: 10, width: 100, height: 40}),+ );+ // A finger's tap in the padding follows the link.+ withPrimaryPointer(true, () => {+ fireEvent.click(row, {clientX: 4, clientY: 30, detail: 1});+ });+ expect(followed).toHaveBeenCalledTimes(1);+ rerender(<Card hidden />);+ rerender(<Card hidden={false} />);+ expect(row).not.toHaveAttribute('data-pressable-container');+ withPrimaryPointer(false, () => {+ fireEvent.click(row, {clientX: 4, clientY: 30, detail: 1});+ });+ expect(cardClick).toHaveBeenCalledTimes(1);+ expect(followed).toHaveBeenCalledTimes(1);+ });++ it('does nothing for a click with no pointer behind it', () => {+ const {followed, row} = linkRow();+ fireEvent.click(row, {clientX: 50, clientY: 5, detail: 0});+ expect(followed).not.toHaveBeenCalled();+ });++ it('keeps a row with both onClick and href on onClick for a click in its own box', () => {+ const onClick = vi.fn();+ const {container} = render(+ <Item label="Both" href="/docs" onClick={onClick} />,+ );+ const anchor = container.querySelector('a') as HTMLAnchorElement;+ const followed = vi.fn((event: MouseEvent) => event.preventDefault());+ anchor.addEventListener('click', followed);+ fireEvent.click(container.firstElementChild as HTMLElement);+ expect(onClick).toHaveBeenCalledTimes(1);+ expect(followed).not.toHaveBeenCalled();+ });+it('sets target on anchor when provided', () => {const {container} = render(<Item label="External" href="https://example.com" target="_blank" />,diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsxindex 80c40fb5b0..19ac9ef222 100644--- a/packages/core/src/Item/Item.tsx+++ b/packages/core/src/Item/Item.tsx@@ -54,19 +54,22 @@ import {mergeProps} from '../utils/mergeProps';import {chainEventHandlers} from '../utils/chainEventHandlers';import {useFocusAcrossSwap} from '../utils/useFocusAcrossSwap';import {ItemDescriptionContext} from './ItemDescriptionContext';+import {ItemListRowContext} from './ItemListRowContext';import {ItemMarkerColumnsContext} from './ItemMarkerColumnsContext';import {useMergedRefs} from '../hooks/useMergedRefs';import {computeTargetAndRel} from '../Link/computeTargetAndRel';import {useLinkComponent} from '../Link/useLinkComponent';import {cancelNestedTouchPress,- useClickableContainer,+ PRESSABLE_CONTAINER_ATTRIBUTE,+ useClickableContainerProxy,} from '../hooks/useClickableContainer';import {useDevWarning} from '../hooks/useDevWarning';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';import {rowPressLayerStyles} from '../privateAttributes/press.stylex';+import {isCoarsePointer} from '../utils/coarsePointer';import {usePressFeedback} from '../hooks/usePressFeedback';import type {ItemSwipeBridge} from './ItemSwipeLayer';@@ -340,6 +343,41 @@ const ARIA_SELECTED_ROLES = new Set([*/const SWIPE_ROLES = new Set(['listitem']);+/**+ * Whether a row serves swipe actions, and so is a stacking context at rest:+ * its root translates (`styles.swipeRoot`). Swipe actions need a+ * role that permits interactive descendants, since a swipe panel holds+ * buttons. That is a `listitem`, or no role at all. A root that is itself a+ * link is not served, nor is a role that forbids interactive descendants. A+ * disabled row, a row with no entry on either side, and the enlarged target of+ * a nested control are not served either. Internal: under a finger,+ * List/ListItem.tsx raises such a row, so its touch band stays above the rows+ * after it.+ */+export function servesSwipeActions({+ swipeActions,+ isDisabled,+ isDelegate,+ isLinkRoot,+ role,+}: {+ readonly swipeActions: ItemSwipeActions | undefined;+ readonly isDisabled: boolean;+ readonly isDelegate: boolean;+ readonly isLinkRoot: boolean;+ readonly role: string | null | undefined;+}): boolean {+ return (+ swipeActions != null &&+ ((swipeActions.leading?.length ?? 0) > 0 ||+ (swipeActions.trailing?.length ?? 0) > 0) &&+ !isDisabled &&+ !isDelegate &&+ !isLinkRoot &&+ (role == null || SWIPE_ROLES.has(role))+ );+}+/** The travel a drag writes on the row root, in physical px (see useSwipeAction). */const SWIPE_TRAVEL = 'var(--_item-swipe-travel, 0px)';/** The settle clock, `0s` while the finger drives the row. */@@ -616,6 +654,7 @@ export function Item({}: ItemProps) {const pressable = usePressFeedback();const columnMarker = use(ItemMarkerColumnsContext);+ const isListRow = use(ItemListRowContext);const LinkComponent = useLinkComponent();// A disabled row's anchor has no destination, so no activation path (a// screen reader's click, Enter, a link context menu) can navigate@@ -635,11 +674,12 @@ export function Item({const isDelegate = interactiveRef != null;const containerRef = useRef<HTMLElement | null>(null);// Only onClick is needed: onMouseUp handles middle-click href navigation,- // which delegation mode never has (href is ignored here).- const {onClick: delegatedOnClick, onPointerDown: delegatedOnPointerDown} =- useClickableContainer({+ // which delegation mode never has (href is ignored here). A List link row's+ // surface click goes to its anchor through the same hook and its guards.+ const {onClick: containerOnClick, onPointerDown: delegatedOnPointerDown} =+ useClickableContainerProxy({containerRef,- interactiveRef: interactiveRef ?? undefined,+ interactiveRef: interactiveRef ?? actionLinkRef,disabled: isDisabled,});@@ -674,19 +714,15 @@ export function Item({href != null ? actionLinkRef.current : actionButtonRef.current,);- // Swipe actions exist where the row's role permits interactive descendants- // (a swipe panel's buttons are such descendants): a `listitem`, or no role- // at all. A root that is itself a link, a row whose role forbids them, and- // a row that is the enlarged target of a nested control are not served.const leadingSwipe = swipeActions?.leading ?? [];const trailingSwipe = swipeActions?.trailing ?? [];- const hasSwipe =- swipeActions != null &&- (leadingSwipe.length > 0 || trailingSwipe.length > 0) &&- !isDisabled &&- !isDelegate &&- !isLinkRoot &&- (role == null || SWIPE_ROLES.has(role));+ const hasSwipe = servesSwipeActions({+ swipeActions,+ isDisabled,+ isDelegate,+ isLinkRoot,+ role,+ });useDevWarning('Item','`swipeBehavior="commit"` fires only the outermost entry of a side; the ' +@@ -781,6 +817,8 @@ export function Item({</>);+ const isLinkRow = isListRow && onClick == null && href != null && !isLinkRoot;+const handleContainerClick = (e: React.MouseEvent) => {if (isDisabled) {return;@@ -789,6 +827,25 @@ export function Item({if (target.closest('button, a, input, select, textarea')) {return;}+ if (isLinkRow) {+ // Under a coarse primary pointer, a tap in the row's padding or band+ // follows its link, with the click's modifier keys. The primary pointer+ // decides, as it decides the band, not the pointer that made the click.+ const row = e.currentTarget as HTMLElement;+ const box = row.getBoundingClientRect();+ const isInBand =+ e.clientX < box.left ||+ e.clientX > box.right ||+ e.clientY < box.top ||+ e.clientY > box.bottom;+ if (+ e.detail > 0 &&+ (isInBand || isCoarsePointer(row.ownerDocument.defaultView))+ ) {+ containerOnClick(e as React.MouseEvent<HTMLElement>);+ }+ return;+ }onClick?.(e);};@@ -868,14 +925,14 @@ export function Item({const mergedRef = useMergedRefs(ref, containerRef);const rootRef = useMergedRefs(- (isDelegate ? mergedRef : ref) as React.Ref<HTMLElement>,+ (isDelegate || isLinkRow ? mergedRef : ref) as React.Ref<HTMLElement>,hasSwipe ? swipeRootRef : undefined,);// The row's own primary, which the click the browser synthesizes after a// drag must not fire.const primaryOnClick = isDelegate- ? delegatedOnClick+ ? containerOnClick: hasParentRole? onClick: isInteractive@@ -934,6 +991,9 @@ export function Item({),}: null)}+ // Only a delegate row is a pressable container. So a mouse click in a+ // link row's padding still reaches a clickable container around it.+ {...(isDelegate ? {[PRESSABLE_CONTAINER_ATTRIBUTE]: 'true'} : undefined)}aria-selected={(allowsAriaSelected && isSelected) || undefined}// aria-selected is invalid on roles that don't permit it (listitem, a// bare div, etc.). For those, convey selection via aria-current — valid@@ -972,18 +1032,20 @@ export function Item({onClick={rootOnClick}><ItemDescriptionContextvalue={hasRenderableDescription ? descriptionID : null}>- {isRenderable(marker) && marker}- {isRenderable(marker) && columnMarker === marker ? (- <span- {...stylex.props(- styles.markerContent,- align === 'first-line' && styles.markerContentFirstLine,- )}>- {content}- </span>- ) : (- content- )}+ <ItemListRowContext value={false}>+ {isRenderable(marker) && marker}+ {isRenderable(marker) && columnMarker === marker ? (+ <span+ {...stylex.props(+ styles.markerContent,+ align === 'first-line' && styles.markerContentFirstLine,+ )}>+ {content}+ </span>+ ) : (+ content+ )}+ </ItemListRowContext></ItemDescriptionContext>{hasSwipe && (// The panels: out-of-flow children of this root, so the DOM is the onediff --git a/packages/core/src/Item/ItemListRowContext.tsx b/packages/core/src/Item/ItemListRowContext.tsxnew file mode 100644index 0000000000..6bbf3bafc6--- /dev/null+++ b/packages/core/src/Item/ItemListRowContext.tsx@@ -0,0 +1,18 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file ItemListRowContext.tsx+ * @input Uses React createContext+ * @output Exports ItemListRowContext+ * @position Internal seam between ListItem and the Item it renders. Under a+ * coarse primary pointer a List row's whole touch target follows its link,+ * so ListItem marks its Item as a List row. Item clears the mark for its own+ * content, and a standalone Item has none.+ */++import {createContext} from 'react';++export const ItemListRowContext = createContext(false);+ItemListRowContext.displayName = 'ItemListRowContext';diff --git a/packages/core/src/List/List.doc.mjs b/packages/core/src/List/List.doc.mjsindex 81b2acaba5..dd41c8fce1 100644--- a/packages/core/src/List/List.doc.mjs+++ b/packages/core/src/List/List.doc.mjs@@ -13,6 +13,15 @@ export const docs = {{className: 'astryx-list', visualProps: ['density', 'listStyle']},{className: 'astryx-list-item'},],+ vars: [+ {+ name: '--_hit-border-bottom',+ description:+ "Width of the divider below a divided row, 0 on the last row. The row's touch hit layer adds it to its offset, so its band starts past the divider. ListItem sets it on the row's own ::after from --border-width under hasDividers, so content inside the row never inherits it, and a theme changes the divider through that token.",+ default: '0px',+ private: true,+ },+ ],},description: 'List container with density, dividers, and header support.',props: [@@ -32,7 +41,7 @@ export const docs = {{name: 'density',type: "'compact' | 'balanced' | 'spacious'",- description: 'Spacing density for items.',+ description: "Spacing density for items. Under a finger, an interactive row's hit target reaches 44px where its neighbors leave room, with no change to how rows look or lay out.",default: "'balanced'",},{diff --git a/packages/core/src/List/List.test.tsx b/packages/core/src/List/List.test.tsxindex ea930d22f6..0cbcdbaf9a 100644--- a/packages/core/src/List/List.test.tsx+++ b/packages/core/src/List/List.test.tsx@@ -9,14 +9,51 @@* SYNC: When modified, update this header*/+import {useRef} from 'react';import {describe, it, expect, vi} from 'vitest';import {cleanup, render, screen} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {rulesDeclaredFor} from '../__tests__/pressState';import {swipeLayerLoaded} from '../Item/__tests__/swipeLayerLoaded';++/**+ * The element's injected rules split by the touch gate: inside+ * `@media (pointer: coarse)` (TOUCH_QUERY, utils/touchQueries.ts), or+ * not.+ */+function touchGatedRules(el: Element): {touch: string[]; other: string[]} {+ const classes = el.className+ .split(/\s+/)+ .filter(Boolean)+ .map(name => `.${name}`);+ const out = {touch: [] as string[], other: [] as string[]};+ const visit = (rules: CSSRuleList, touch: boolean) => {+ for (const rule of Array.from(rules)) {+ if (rule instanceof CSSStyleRule) {+ if (classes.some(cls => rule.selectorText.startsWith(cls))) {+ (touch ? out.touch : out.other).push(+ `${rule.selectorText} {${rule.style.cssText}}`,+ );+ }+ continue;+ }+ const nested = (rule as CSSGroupingRule).cssRules;+ if (nested == null) {+ continue;+ }+ const condition = (rule as CSSConditionRule).conditionText ?? '';+ visit(nested, touch || condition.includes('pointer: coarse'));+ }+ };+ for (const sheet of Array.from(document.styleSheets)) {+ visit(sheet.cssRules, false);+ }+ return out;+}import {List} from './List';import {ListItem} from './ListItem';import {ListMarkerScope} from './ListContext';+import {HIT_INSET_PROPERTIES} from '../utils/hitArea';describe('List', () => {it('forwards ListItem align to its Item row unchanged', () => {@@ -489,6 +526,69 @@ describe('List', () => {expect(hrs).toHaveLength(0);});+ // ===========================================================================+ // Touch hit area+ // ===========================================================================++ /** The rules among `rules` whose selector reaches the row's `::after`. */+ const afterRules = (rules: string[]): string[] =>+ rules.filter(rule => rule.slice(0, rule.indexOf('{')).includes('::after'));++ it('gives an interactive, enabled row an invisible hit layer under a finger only', () => {+ render(+ <List>+ <ListItem label="Pressable" onClick={() => {}} />+ <ListItem label="Link" href="#settings" />+ <ListItem label="Read-only" />+ <ListItem label="Disabled" onClick={() => {}} isDisabled />+ </List>,+ );+ const row = (text: string) => screen.getByText(text).closest('li')!;+ for (const text of ['Pressable', 'Link']) {+ const {touch, other} = touchGatedRules(row(text));+ const layer = afterRules(touch).join('\n');+ // Positioned past the row by the measured insets, clipped to the band+ // outside the row's own box, and painting nothing.+ expect(layer).toContain('position: absolute');+ expect(layer).toMatch(/clip-path: polygon\(evenodd/);+ // One inset per side, in physical order: top, right, bottom, left.+ const offset = (side: keyof typeof HIT_INSET_PROPERTIES) =>+ `calc\\(\\(var\\(${HIT_INSET_PROPERTIES[side]}, ?0px\\) \\+ var\\(--_hit-border-${side}, ?0px\\)\\) \\* -1\\)`;+ expect(layer).toMatch(+ new RegExp(+ `inset: ${offset('top')} ${offset('right')} ${offset('bottom')} ${offset('left')}`,+ ),+ );+ // Above the rows after it, so a later row does not hit-test over the+ // band; painting nothing.+ expect(layer).toMatch(/z-index: 1/);+ expect(layer).not.toMatch(+ /[{;]\s*(?:background|border|box-shadow|outline)[\w-]*\s*:/,+ );+ // The row itself takes no z-index: it stays no stacking context.+ expect(+ touch.filter(+ rule =>+ !rule.slice(0, rule.indexOf('{')).includes('::') &&+ rule.includes('z-index'),+ ),+ ).toEqual([]);+ // At rest the row's stacking stays as it was: a rule that isolates the+ // row is keyed on a press.+ for (const rule of touch.filter(r => r.includes('isolation'))) {+ expect(rule.slice(0, rule.indexOf('{'))).toContain(+ '[data-astryx-press',+ );+ }+ // With a mouse: no pseudo-element.+ expect(afterRules(other)).toEqual([]);+ }+ // A row with nothing to press offers no target.+ for (const text of ['Read-only', 'Disabled']) {+ expect(afterRules(touchGatedRules(row(text)).touch)).toEqual([]);+ }+ });+// ===========================================================================// Interactive items — onClick (invisible button pattern)// ===========================================================================@@ -1013,6 +1113,23 @@ describe('List', () => {});});+/** A row whose press goes to a control inside it (`interactiveRef`), with swipe actions. */+function DelegateSwipeRow() {+ const ref = useRef<HTMLButtonElement>(null);+ return (+ <ListItem+ label="Delegate"+ interactiveRef={ref}+ endContent={+ <button ref={ref} type="button">+ Open+ </button>+ }+ swipeActions={{trailing: [{label: 'Archive', onActivate: () => {}}]}}+ />+ );+}+describe('List and swipe actions', () => {it('clips the rows in the inline axis with clip, never hidden, so a row dragged aside paints no further than the list', () => {render(@@ -1027,6 +1144,96 @@ describe('List and swipe actions', () => {expect(rules.some(r => /overflow[-a-z]*: hidden/.test(r))).toBe(false);});+ it('under a finger, isolates its rows, so what rises inside the list stays below a sticky header; with a mouse it keeps its stacking', () => {+ render(+ <List>+ <ListItem label="A" onClick={() => {}} />+ </List>,+ );+ const {touch, other} = touchGatedRules(screen.getByRole('list'));+ // Under a finger the list is the isolation boundary for its rows'+ // z-index. So a page-level sticky header at z-index 1 stays above every+ // part of the list.+ expect(touch.join('\n')).toMatch(/isolation: isolate/);+ // With a mouse nothing rises, so the list is no stacking context.+ expect(other.filter(rule => rule.includes('isolation'))).toEqual([]);+ });++ it('under a finger, raises a swipeable interactive row above the rows after it: it is a stacking context, so its touch band’s own z-index orders only inside it', () => {+ render(+ <List>+ <ListItem+ label="Swipeable"+ onClick={() => {}}+ swipeActions={{trailing: [{label: 'Archive', onActivate: () => {}}]}}+ />+ <ListItem label="Pressable" onClick={() => {}} />+ <ListItem+ label="Static"+ swipeActions={{trailing: [{label: 'Archive', onActivate: () => {}}]}}+ />+ <ListItem+ label="Empty sides"+ onClick={() => {}}+ swipeActions={{leading: [], trailing: []}}+ />+ <DelegateSwipeRow />+ </List>,+ );+ const row = (text: string) => screen.getByText(text).closest('li')!;+ const rowZ = (el: Element) => {+ const {touch, other} = touchGatedRules(el);+ const own = (rules: string[]) =>+ rules.filter(+ rule =>+ !rule.slice(0, rule.indexOf('{')).includes('::') &&+ rule.includes('z-index:'),+ );+ return {touch: own(touch), other: own(other)};+ };+ const swipeable = rowZ(row('Swipeable'));+ expect(swipeable.touch.join('\n')).toMatch(/z-index: 1/);+ // With a mouse there is no band, and nothing changes.+ expect(swipeable.other).toEqual([]);+ // A row that is no stacking context needs no raise (its band's own+ // z-index orders it), and a swipeable row with no band gets none.+ expect(rowZ(row('Pressable')).touch).toEqual([]);+ expect(rowZ(row('Static')).touch).toEqual([]);+ // Item serves no swipe actions on a row with no entry on either side. Nor+ // does it on a row whose press goes to a control inside it. Neither row is+ // a stacking context, so neither is raised.+ expect(rowZ(row('Empty sides')).touch).toEqual([]);+ expect(rowZ(row('Delegate')).touch).toEqual([]);+ });++ it('raises nothing in a ListItem outside a List, where nothing isolates it: its touch band and a swipeable row take no z-index', () => {+ render(+ <ul>+ <ListItem+ label="Outside"+ onClick={() => {}}+ swipeActions={{trailing: [{label: 'Archive', onActivate: () => {}}]}}+ />+ </ul>,+ );+ const {touch} = touchGatedRules(screen.getByText('Outside').closest('li')!);+ // It keeps its touch target, the band past its box.+ expect(+ touch+ .filter(rule => rule.slice(0, rule.indexOf('{')).includes('::after'))+ .join('\n'),+ ).toContain('position: absolute');+ // But nothing it draws rises: not the band, not the row. A rule keyed on+ // a press is left out, since it orders layers only inside the pressed row.+ expect(+ touch.filter(+ rule =>+ rule.includes('z-index') &&+ !rule.slice(0, rule.indexOf('{')).includes('[data-astryx-press'),+ ),+ ).toEqual([]);+ });+it('passes swipeActions and swipeBehavior through to the row unchanged', async () => {render(<List>diff --git a/packages/core/src/List/List.tsx b/packages/core/src/List/List.tsxindex ebc3fca933..359d8738c2 100644--- a/packages/core/src/List/List.tsx+++ b/packages/core/src/List/List.tsx@@ -148,6 +148,11 @@ const styles = stylex.create({// `hidden`: hidden makes a scroll container, which fights the list's// vertical scroller. (StyleX emits the physical longhand of this axis.)overflowInline: 'clip',+ // Under a finger, the isolation boundary for what rises inside the list.+ // A row's touch band and a swipeable row order above the rows after them.+ // They stay below a page-level sticky header at the same z-index. With a+ // mouse nothing rises, so the list keeps its stacking.+ isolation: {default: null, '@media (pointer: coarse)': 'isolate'},},// Subgridded numbered rows contribute their marker's intrinsic width to// one column, so text and nested lists never move with an individual number.diff --git a/packages/core/src/List/ListItem.hitArea.test.tsx b/packages/core/src/List/ListItem.hitArea.test.tsxnew file mode 100644index 0000000000..ff2e644214--- /dev/null+++ b/packages/core/src/List/ListItem.hitArea.test.tsx@@ -0,0 +1,145 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ListItem.hitArea.test.tsx+ * @input Vitest, Testing Library, and utils/hitArea.ts with `watchHitArea`+ * spied (the rest real)+ * @output Checks that ListItem keeps an enabled interactive row's touch hit+ * insets live. It covers the rows watched, the insets, the target size, a+ * mid-motion measurement, and the stop.+ * @position Test for ListItem's hit area wiring. List.test.tsx checks the+ * layer's CSS, and ListTouchHitArea.interaction.browser.spec.ts its hit+ * testing.+ */++import {createRef} from 'react';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {render, screen} from '@testing-library/react';+import type * as HitAreaModule from '../utils/hitArea';+import type {HitInsets} from '../utils/hitArea';++const watches = vi.hoisted(+ () =>+ [] as {+ element: Element;+ onInsets: (insets: HitInsets) => void;+ minSize: number | undefined;+ stop: ReturnType<typeof vi.fn>;+ }[],+);++vi.mock('../utils/hitArea', async importOriginal => {+ const actual = await importOriginal<typeof HitAreaModule>();+ return {+ ...actual,+ watchHitArea: (+ element: Element,+ onInsets: (insets: HitInsets) => void,+ options?: {readonly minSize?: number},+ ) => {+ const stop = vi.fn();+ watches.push({element, onInsets, minSize: options?.minSize, stop});+ return stop;+ },+ };+});++import {List} from './List';+import {ListItem} from './ListItem';++describe('ListItem touch hit area', () => {+ afterEach(() => {+ watches.length = 0;+ });++ const row = (text: string) => screen.getByText(text).closest('li')!;++ it('watches each interactive, enabled row, and no other', () => {+ const control = createRef<HTMLButtonElement>();+ render(+ <List>+ <ListItem label="Pressable" onClick={() => {}} />+ <ListItem label="Link" href="#settings" />+ <ListItem+ label="Delegated"+ interactiveRef={control}+ endContent={+ <button type="button" ref={control}>+ Toggle+ </button>+ }+ />+ <ListItem label="Read-only" />+ <ListItem label="Disabled" onClick={() => {}} isDisabled />+ </List>,+ );+ expect(watches.map(watch => watch.element)).toEqual([+ row('Pressable'),+ row('Link'),+ row('Delegated'),+ ]);+ });++ it('puts the measured insets on the row, where its layer reads them', () => {+ render(+ <List>+ <ListItem label="Pressable" onClick={() => {}} />+ </List>,+ );+ expect(watches).toHaveLength(1);+ watches[0].onInsets({top: 4, right: 0, bottom: 1, left: 0});+ const style = row('Pressable').style;+ expect(style.getPropertyValue('--astryx-hit-inset-top')).toBe('4px');+ expect(style.getPropertyValue('--astryx-hit-inset-bottom')).toBe('1px');+ expect(style.getPropertyValue('--astryx-hit-inset-left')).toBe('0px');+ });++ it('stops watching when the row goes or turns disabled', async () => {+ const {rerender, unmount} = render(+ <List>+ <ListItem label="Pressable" onClick={() => {}} />+ </List>,+ );+ expect(watches).toHaveLength(1);+ rerender(+ <List>+ <ListItem label="Pressable" onClick={() => {}} isDisabled />+ </List>,+ );+ await Promise.resolve();+ expect(watches[0].stop).toHaveBeenCalledTimes(1);+ expect(watches).toHaveLength(1);+ rerender(+ <List>+ <ListItem label="Pressable" onClick={() => {}} />+ </List>,+ );+ expect(watches).toHaveLength(2);+ unmount();+ await Promise.resolve();+ expect(watches[1].stop).toHaveBeenCalledTimes(1);+ });++ it('keeps its watch and its insets when a parent re-render passes a new inline ref', async () => {+ const rowRef = (tick: number) => (node: HTMLLIElement | null) => {+ node?.setAttribute('data-tick', String(tick));+ };+ const {rerender} = render(+ <List>+ <ListItem label="Filter" onClick={() => {}} ref={rowRef(0)} />+ </List>,+ );+ const row = screen.getByRole('listitem');+ watches[0].onInsets({top: 4, right: 0, bottom: 4, left: 0});+ rerender(+ <List>+ <ListItem label="Filter" onClick={() => {}} ref={rowRef(1)} />+ </List>,+ );+ await Promise.resolve();+ expect(row.getAttribute('data-tick')).toBe('1');+ expect(watches).toHaveLength(1);+ expect(watches[0].stop).not.toHaveBeenCalled();+ expect(row.style.getPropertyValue('--astryx-hit-inset-top')).toBe('4px');+ });+});diff --git a/packages/core/src/List/ListItem.tsx b/packages/core/src/List/ListItem.tsxindex 78574a62e8..81b11413e9 100644--- a/packages/core/src/List/ListItem.tsx+++ b/packages/core/src/List/ListItem.tsx@@ -4,10 +4,11 @@/*** @file ListItem.tsx- * @input Uses React, ReactNode, StyleXStyles, theme tokens, the List row edge- * treatment, CheckboxInput, and the marker or task checkbox a- * ListMarkerScope sets (Markdown's nested lists and the task items of mixed- * lists), and Item's private exact-marker formatting scope for numbered+ * @input Uses React, ReactNode, StyleXStyles, theme tokens and the List row+ * edge treatment. It also uses the touch hit area (utils/touchHitArea.ts and+ * its layer) and CheckboxInput. It reads the marker or task checkbox a+ * ListMarkerScope sets, for Markdown's nested lists and the task items of mixed+ * lists. It also reads Item's private exact-marker formatting scope for numbered* rows. Number markers stay on one line in the List's shared column,* keeping every sibling's text and nested list on the same start line;* they end on one line too, right-aligned with tabular figures, and hang@@ -41,10 +42,14 @@ import type {BaseProps} from '../BaseProps';import {ListContext, type ListMarker} from './ListContext';import {CheckboxInput} from '../CheckboxInput/CheckboxInput';import {mergeProps} from '../utils/mergeProps';-import {Item} from '../Item/Item';+import {Item, servesSwipeActions} from '../Item/Item';+import {ItemListRowContext} from '../Item/ItemListRowContext';import {ItemMarkerColumnsContext} from '../Item/ItemMarkerColumnsContext';import type {ItemAlign, ItemSwipeActions, ItemSwipeBehavior} from '../Item';import {themeProps} from '../utils/themeProps';+import {useMergedRefs} from '../hooks/useMergedRefs';+import {useTouchHitArea} from '../utils/touchHitArea';+import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';// =============================================================================// Types@@ -198,6 +203,21 @@ const styles = stylex.create({'max(var(--container-padding-inline-end, 0px), var(--_item-inset-inline))',borderRadius: 0,},+ // Under a finger, the row's touch band rises above the rows after it. A+ // later row is positioned with no z-index, so it would paint and hit-test+ // over the band. Only inside a List (isInList).+ bandRaised: {+ '::after': {+ zIndex: {default: null, '@media (pointer: coarse)': 1},+ },+ },+ // A swipeable row is a stacking context at rest, since Item translates its+ // swipe root. So its band's own z-index orders only inside it. Under a+ // finger the row itself rises above the rows after it, whose boxes its band+ // reaches into. The list isolates, so the row stays below a sticky header.+ swipeRaised: {+ zIndex: {default: null, '@media (pointer: coarse)': 1},+ },withDivider: {borderBlockEndWidth: borderVars['--border-width'],borderBlockEndStyle: 'solid',@@ -209,6 +229,15 @@ const styles = stylex.create({':last-child': {borderBlockEndWidth: 0,},+ // The touch hit layer's band starts past the divider, the edge of the box+ // its insets are measured from (utils/touchHitArea.stylex.ts). The width+ // sits on the layer itself, so content inside the row never inherits it.+ '::after': {+ '--_hit-border-bottom': {+ default: borderVars['--border-width'],+ ':last-child': '0px',+ },+ },},});@@ -378,6 +407,28 @@ export function ListItem({...restProps}: ListItemProps) {const ctx = use(ListContext);+ // A List isolates its rows, so what a row raises stays below a page-level+ // sticky header. Outside a List nothing bounds a raise, so a row raises+ // nothing there.+ const isInList = ctx != null;+ // Under a finger, the row's hit target grows where its neighbors leave room.+ const isTouchTarget =+ (onClick != null || href != null || interactiveRef != null) && !isDisabled;+ const hitAreaRef = useTouchHitArea(isTouchTarget);+ const mergedRef = useMergedRefs(ref, hitAreaRef);+ // A row that Item serves swipe actions on is a stacking context at rest. So+ // its band's own z-index orders only inside it, and under a finger the row+ // raises itself. Its root is its `<li>`, never a link.+ const isRaisedSwipeRow =+ isInList &&+ isTouchTarget &&+ servesSwipeActions({+ swipeActions: restProps.swipeActions,+ isDisabled,+ isDelegate: interactiveRef != null,+ isLinkRoot: false,+ role: restProps.role,+ });const density = ctx?.density ?? 'balanced';const hasDividers = ctx?.hasDividers ?? false;const edge = ctx?.edge ?? 'padded';@@ -432,7 +483,7 @@ export function ListItem({const item = (<Itemas="li"- ref={ref}+ ref={mergedRef}marker={marker}startContent={startContent}label={label}@@ -453,6 +504,9 @@ export function ListItem({hasMarkers && styles.withCounter,hasDividers && styles.withDivider,hasDividers && embeddedStyles.noRadius,+ isTouchTarget && touchHitAreaStyles.layer,+ isTouchTarget && isInList && styles.bandRaised,+ isRaisedSwipeRow && styles.swipeRaised,edge === 'flush' && styles.edgeFlush,edge === 'outset' && styles.edgeOutset,edge === 'bleed' && styles.edgeBleed,@@ -463,12 +517,13 @@ export function ListItem({{...restProps}/>);+ const row = <ItemListRowContext value>{item}</ItemListRowContext>;// Only numbered rows contribute two cells to List's shared counter grid.// Passing the marker identity keeps this request off unrelated Items in slots.return listStyle === 'decimal' ? (- <ItemMarkerColumnsContext value={marker}>{item}</ItemMarkerColumnsContext>+ <ItemMarkerColumnsContext value={marker}>{row}</ItemMarkerColumnsContext>) : (- item+ row);}diff --git a/packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.tsnew file mode 100644index 0000000000..5472795721--- /dev/null+++ b/packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.ts@@ -0,0 +1,706 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ListTouchHitArea.interaction.browser.spec.ts+ * @input The built List stories in the touch phone context, and in a mouse+ * context of the same viewport and scale+ * @output Proofs that an interactive row's hit layer grows toward the touch+ * target under a finger, with no overlap, layout or paint. A mouse gets no+ * layer.+ * @position Interaction evidence for ListItem's touch hit area+ * (utils/touchHitArea.stylex.ts, kept live by utils/touchHitArea.ts)+ */++// Geometry is read from the layer's computed edges. Chromium's+// elementFromPoint snaps a point to whole CSS pixels, which is too coarse for+// a 1 px half gap. So the hit tests probe whole pixels inside a wider growth.++import {+ expect,+ test,+ type Browser,+ type Page,+ type TestInfo,+} from '@astryxdesign/a11y-spec/playwright';+import {openStory, withStorybook} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++interface Row {+ readonly text: string;+ readonly top: number;+ readonly bottom: number;+ readonly height: number;+ readonly x: number;+ readonly layer: {+ readonly content: string;+ readonly top: number;+ readonly bottom: number;+ readonly paint: string;+ };+ readonly isolation: string;+ readonly written: string;+}++/** The story's rows (Storybook's own hidden error page has list items too). */+async function rowsOf(page: Page): Promise<Row[]> {+ return page.locator('#storybook-root li').evaluateAll(elements =>+ elements.map(el => {+ const box = el.getBoundingClientRect();+ const layer = getComputedStyle(el, '::after');+ const own = getComputedStyle(el);+ return {+ text: el.textContent?.trim() ?? '',+ top: box.top,+ bottom: box.bottom,+ height: box.height,+ x: box.left + box.width / 2,+ layer: {+ content: layer.content,+ // How far the layer reaches past the row's border box, in px. Its+ // offsets start at the row's padding box, so past a border, such as+ // a divided row's, it reaches that much less.+ top:+ layer.content === 'none'+ ? 0+ : 0 -+ Number.parseFloat(layer.top) -+ Number.parseFloat(own.borderTopWidth),+ bottom:+ layer.content === 'none'+ ? 0+ : 0 -+ Number.parseFloat(layer.bottom) -+ Number.parseFloat(own.borderBottomWidth),+ paint: [+ layer.backgroundColor,+ layer.backgroundImage,+ layer.boxShadow,+ layer.borderTopWidth,+ layer.outlineStyle,+ ].join(' | '),+ },+ isolation: getComputedStyle(el).isolation,+ written: (el as HTMLElement).style.getPropertyValue(+ '--astryx-hit-inset-top',+ ),+ };+ }),+ );+}++/**+ * The rows once the shared hit area has measured them. Its pass runs in a+ * frame after the rows show, and writes only insets that differ from 0. So+ * wait a few frames, and then until two frames read the same.+ */+async function measuredRowsOf(page: Page): Promise<Row[]> {+ const frames = async (count: number) =>+ page.evaluate(async n => {+ for (let i = 0; i < n; i++) {+ await new Promise(resolve => requestAnimationFrame(resolve));+ }+ }, count);+ await frames(4);+ let previous = JSON.stringify(await rowsOf(page));+ await expect+ .poll(async () => {+ await frames(2);+ const current = JSON.stringify(await rowsOf(page));+ const settled = current === previous;+ previous = current;+ return settled;+ })+ .toBe(true);+ return rowsOf(page);+}++/** A page that sets `--size-touch-target`, before the story renders. */+async function themeTouchTarget(page: Page, size: string): Promise<void> {+ // Storybook rewrites the root element's style attribute, so a stylesheet.+ await page.addInitScript(value => {+ document.addEventListener('DOMContentLoaded', () => {+ const style = document.createElement('style');+ style.textContent = `:root { --size-touch-target: ${value}; }`;+ document.head.append(style);+ });+ }, size);+}++/** The story row the browser hit-tests at a point, by its text. */+async function rowAt(page: Page, x: number, y: number): Promise<string | null> {+ return page.evaluate(+ ([px, py]) =>+ document+ .elementFromPoint(px, py)+ ?.closest('#storybook-root li')+ ?.textContent?.trim() ?? null,+ [x, y] as const,+ );+}++const isTouch = async (page: Page) =>+ page.evaluate(() => matchMedia('(pointer: coarse)').matches);++/** No row's area reaches into the next row's area. */+function expectNoOverlap(rows: ReadonlyArray<Row>): void {+ for (let i = 0; i + 1 < rows.length; i++) {+ expect(+ rows[i].bottom + rows[i].layer.bottom,+ JSON.stringify(rows),+ ).toBeLessThanOrEqual(rows[i + 1].top - rows[i + 1].layer.top + 0.01);+ }+}++/** The same page with a mouse: the phone's viewport and scale, a fine pointer. */+async function withMouse<T>(+ browser: Browser,+ testInfo: TestInfo,+ run: (page: Page) => Promise<T>,+): Promise<T> {+ const {viewport, deviceScaleFactor} = testInfo.project.use;+ const context = await browser.newContext({+ viewport,+ deviceScaleFactor,+ hasTouch: false,+ isMobile: false,+ });+ try {+ const page = await context.newPage();+ return await run(page);+ } finally {+ await context.close();+ }+}++test('under a finger, a short interactive row takes half the gap to each neighbor and grows toward the touch target where nothing is near', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-list--interactive');+ test.skip(!(await isTouch(page)), 'the hit area applies under a finger only');+ const rows = await measuredRowsOf(page);+ expect(rows).toHaveLength(3);+ const gap = rows[1].top - rows[0].bottom;+ const grow = (44 - rows[0].height) / 2;+ const summary = JSON.stringify({gap, grow, rows});+ // One-line rows, shorter than the 44px touch target, 2px apart.+ expect(rows[0].height, summary).toBeLessThan(44);+ expect(gap, summary).toBeCloseTo(2, 1);+ // Half the gap between rows; the full growth past the list's ends, where+ // nothing interactive is near.+ const reach = rows.map(row => [row.layer.top, row.layer.bottom]);+ expect(reach, summary).toEqual([+ [grow, gap / 2],+ [gap / 2, gap / 2],+ [gap / 2, grow],+ ]);+ expectNoOverlap(rows);+});++test('under a finger, a tap in a row’s growth activates that row, and nothing is hit past it', async ({+ page,+}) => {+ test.skip(!(await isTouch(page)), 'the hit area applies under a finger only');+ await openStory(page, storybook(), 'core-list--interactive');+ const rows = await measuredRowsOf(page);+ // The growth past the list's first row, toward 44px.+ const grow = (44 - rows[0].height) / 2;+ expect(grow, JSON.stringify(rows)).toBeGreaterThanOrEqual(1.5);+ expect(rows[0].layer.top, JSON.stringify(rows)).toBeCloseTo(grow, 1);+ const inside = rows[0].top - grow / 2;+ const outside = Math.round(rows[0].top - grow - 3);+ // The browser's own hit test at each point, then a real tap in the growth.+ // (No tap past it: a touch engine's own touch adjustment may move a tap+ // that lands a few pixels from a target onto it.)+ expect(await rowAt(page, rows[0].x, inside)).toBe(rows[0].text);+ expect(await rowAt(page, rows[0].x, outside)).toBe(null);+ await page.evaluate(() => {+ const taps: string[] = [];+ (window as unknown as {taps: string[]}).taps = taps;+ for (const row of document.querySelectorAll('#storybook-root li')) {+ row.addEventListener('click', () =>+ taps.push(row.textContent?.trim() ?? ''),+ );+ }+ });+ await page.touchscreen.tap(rows[0].x, inside);+ expect(+ await page.evaluate(() => (window as unknown as {taps: string[]}).taps),+ ).toEqual([rows[0].text]);+});++test('under a finger, the row’s own content keeps its taps', async ({page}) => {+ await openStory(page, storybook(), 'core-list--interactive');+ test.skip(!(await isTouch(page)), 'the hit area applies under a finger only');+ await measuredRowsOf(page);+ const hits = await page.locator('#storybook-root li').evaluateAll(rows =>+ rows.map(row => {+ // The row's end content (its chevron), above the layer.+ const icons = row.querySelectorAll('svg');+ const end = icons[icons.length - 1];+ const box = end.getBoundingClientRect();+ const hit = document.elementFromPoint(+ box.left + box.width / 2,+ box.top + box.height / 2,+ );+ return hit != null && hit !== row && row.contains(hit);+ }),+ );+ expect(hits).toEqual([true, true, true]);+});++test('under a finger, a row’s end control keeps its taps, and the interactive rows beside it grow short of it', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-list--with-end-controls');+ test.skip(!(await isTouch(page)), 'the hit area applies under a finger only');+ const rows = await measuredRowsOf(page);+ // (The switch's own hidden label repeats the row's text, and Network's+ // swipe action adds its own.)+ expect(rows.map(row => row.text)).toEqual([+ expect.stringMatching(/^Network/),+ expect.stringMatching(/^Wi-Fi/),+ expect.stringMatching(/^Bluetooth/),+ ]);+ // The control's row is not interactive: it has no hit area of its own.+ expect(rows[1].layer.content, JSON.stringify(rows)).toBe('none');+ const toggle = page.getByRole('switch', {name: 'Wi-Fi'});+ await expect(toggle).toBeChecked();+ const control = await toggle.evaluate(input => {+ const box = (input.parentElement ?? input).getBoundingClientRect();+ const own = input.getBoundingClientRect();+ return {+ top: box.top,+ bottom: box.bottom,+ x: own.left + own.width / 2,+ y: own.top + own.height / 2,+ };+ });+ // The rows beside it grow only to half the gap to the control. The other+ // half belongs to the control.+ const [above, , below] = rows;+ expect(above.layer.bottom, JSON.stringify({rows, control})).toBeCloseTo(+ (control.top - above.bottom) / 2,+ 1,+ );+ expect(below.layer.top, JSON.stringify({rows, control})).toBeCloseTo(+ (below.top - control.bottom) / 2,+ 1,+ );+ expect(+ above.bottom + above.layer.bottom,+ JSON.stringify({rows, control}),+ ).toBeLessThanOrEqual(control.top);+ expect(+ below.top - below.layer.top,+ JSON.stringify({rows, control}),+ ).toBeGreaterThanOrEqual(control.bottom);+ // The browser sends a tap in Network's band to Network, over the static+ // row after it, up to the band's end. A tap in Bluetooth's band goes to+ // Bluetooth. Network is swipeable, so it is a stacking context at rest, and+ // its band still wins. These are hit tests, not taps, because a touch+ // engine may move a tap a few pixels onto a target.+ const owner = async (y: number) =>+ page.evaluate(+ ({x, y: at}) => {+ const row = document+ .elementFromPoint(x, at)+ ?.closest('#storybook-root li');+ if (row == null) {+ return null;+ }+ // The row's own text, without its swipe actions' labels.+ const copy = row.cloneNode(true) as Element;+ for (const panel of copy.querySelectorAll('[data-swipe-panel]')) {+ panel.remove();+ }+ return (copy.textContent ?? '').trim().split(/\s+/)[0] ?? null;+ },+ {x: above.x, y},+ );+ // A swipeable row is a stacking context: its root translates.+ expect(+ await page+ .locator('#storybook-root li')+ .first()+ .evaluate(row => getComputedStyle(row).transform),+ ).not.toBe('none');+ expect(above.layer.bottom, JSON.stringify(rows)).toBeGreaterThan(1);+ expect(await owner(above.bottom + 0.5)).toBe('Network');+ expect(await owner(above.bottom + above.layer.bottom - 0.5)).toBe('Network');+ expect(await owner(above.bottom + above.layer.bottom + 0.5)).toBe('Wi-Fi');+ expect(await owner(below.top - below.layer.top + 0.5)).toBe('Bluetooth');+ // The browser hit-tests the control there, and a real tap toggles it,+ // with no tap reaching the rows beside it.+ expect(+ await page.evaluate(+ ({x, y}) =>+ document.elementFromPoint(x, y)?.closest('[role="switch"]') != null,+ control,+ ),+ ).toBe(true);+ await page.evaluate(() => {+ const taps: string[] = [];+ (window as unknown as {taps: string[]}).taps = taps;+ for (const row of document.querySelectorAll('#storybook-root li')) {+ row.addEventListener('click', event => {+ if (+ !(event.target instanceof Element) ||+ event.target.closest('[role="switch"]') == null+ ) {+ taps.push(row.textContent?.trim() ?? '');+ }+ });+ }+ });+ await page.touchscreen.tap(control.x, control.y);+ await expect(toggle).not.toBeChecked();+ expect(+ await page.evaluate(() => (window as unknown as {taps: string[]}).taps),+ ).toEqual([]);+});++test('under a finger, a row’s band takes no tap from a control near the list: a button in its header, or a button just after it', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-list--with-end-controls');+ test.skip(!(await isTouch(page)), 'the hit area applies under a finger only');+ const rows = await measuredRowsOf(page);+ const first = rows[0];+ const last = rows[rows.length - 1];+ const box = async (name: string) =>+ page.getByRole('button', {name, exact: true}).evaluate(el => {+ const r = el.getBoundingClientRect();+ return {top: r.top, bottom: r.bottom, x: r.left + r.width / 2};+ });+ const edit = await box('Edit');+ const more = await box('Load more');+ // What the browser hit-tests at a point: a button's name, or a row's+ // first word.+ const hit = async (x: number, y: number) =>+ page.evaluate(+ ({x: px, y: py}) => {+ const el = document.elementFromPoint(px, py);+ const button = el?.closest('button');+ if (button != null && button.closest('li') == null) {+ return button.textContent?.trim() ?? '';+ }+ return (+ (el?.closest('#storybook-root li')?.textContent ?? '')+ .trim()+ .split(/\s+/)[0] || null+ );+ },+ {x, y},+ );+ // The button sits 4 px after the list. The last row's band stops at half+ // that gap. So the button keeps every point of its own box, and the band+ // keeps its half.+ expect(more.top - last.bottom, JSON.stringify({rows, more})).toBeCloseTo(+ 4,+ 0,+ );+ expect(last.layer.bottom, JSON.stringify({rows, more})).toBeLessThanOrEqual(+ (more.top - last.bottom) / 2 + 0.01,+ );+ expect(await hit(more.x, more.top + 0.5)).toBe('Load more');+ expect(await hit(last.x, last.bottom + last.layer.bottom - 0.5)).toBe(+ 'Bluetooth',+ );+ // The header's button above the first row keeps its own box too.+ expect(+ first.top - first.layer.top,+ JSON.stringify({rows, edit}),+ ).toBeGreaterThanOrEqual(edit.bottom - 0.01);+ expect(await hit(edit.x, edit.bottom - 0.5)).toBe('Edit');+});++test('under a finger, a sticky header above the list keeps its taps over the first row’s band: the list isolates what its rows raise', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-list--compact');+ test.skip(!(await isTouch(page)), 'the hit area applies under a finger only');+ const result = await page.evaluate(() => {+ const first = document.querySelector<HTMLElement>('#storybook-root li');+ const list = first?.parentElement;+ if (first == null || list == null) {+ throw new Error('no list row');+ }+ const reach =+ parseFloat(+ getComputedStyle(first).getPropertyValue('--astryx-hit-inset-top'),+ ) || 0;+ const top = first.getBoundingClientRect().top;+ // A page header before the list in the document, at z-index 1, as+ // AppShell's sticky header is. It ends halfway into the band above the+ // first row, as if the list had scrolled under it.+ const header = document.createElement('div');+ Object.assign(header.style, {+ position: 'fixed',+ insetInline: '0',+ top: '0',+ height: `${top - reach / 2}px`,+ zIndex: '1',+ });+ document.body.prepend(header);+ const x = first.getBoundingClientRect().left + 40;+ const y = top - (reach * 3) / 4;+ const hit = () => {+ const element = document.elementFromPoint(x, y);+ return element === header+ ? 'header'+ : element?.closest('li') != null+ ? 'row'+ : String(element?.tagName);+ };+ const isolated = hit();+ // The control: without the list's isolation the band, raised above the+ // rows after it, would also rise above the header and take its tap.+ list.style.isolation = 'auto';+ const unisolated = hit();+ list.style.isolation = '';+ header.remove();+ return {reach, isolated, unisolated};+ });+ expect(result.reach, JSON.stringify(result)).toBeGreaterThan(2);+ expect(result.isolated, JSON.stringify(result)).toBe('header');+ expect(result.unisolated, JSON.stringify(result)).toBe('row');+});++test('under a finger, an interactive spacious list: its one-line rows, 48px tall, are already past the touch target, so they gain nothing and overlap nothing', async ({+ page,+}) => {+ // The Interactive story at `density="spacious"`, the density of the+ // bottom-sheet menu rows.+ await openStory(page, storybook(), 'core-list--interactive', {+ density: 'spacious',+ });+ test.skip(!(await isTouch(page)), 'the hit area applies under a finger only');+ const rows = await measuredRowsOf(page);+ const summary = JSON.stringify(rows);+ expect(rows.length, summary).toBeGreaterThan(1);+ for (const row of rows) {+ // Spacious, not the balanced 40px.+ expect(row.height, summary).toBeGreaterThanOrEqual(47.5);+ expect([row.layer.top, row.layer.bottom], summary).toEqual([0, 0]);+ }+ expectNoOverlap(rows);+});++test('under a finger, a row already as tall as the touch target gains nothing, rows that touch take nothing from each other, and a disabled row has no layer', async ({+ page,+}) => {+ test.slow();+ // Links: a one-line row, then two rows with descriptions (taller than the+ // touch target): only the short row grows.+ await openStory(page, storybook(), 'core-list--links');+ test.skip(!(await isTouch(page)), 'the hit area applies under a finger only');+ const links = await measuredRowsOf(page);+ const summary = JSON.stringify(links);+ expect(links[0].height, summary).toBeLessThan(44);+ expect(links[0].layer.bottom, summary).toBeCloseTo(+ (links[1].top - links[0].bottom) / 2,+ 1,+ );+ for (const row of links.slice(1)) {+ expect(row.height, summary).toBeGreaterThanOrEqual(44);+ expect([row.layer.top, row.layer.bottom], summary).toEqual([0, 0]);+ }+ expectNoOverlap(links);+ // Compact with dividers: the rows touch, so between them nothing grows.+ await openStory(page, storybook(), 'core-list--compact');+ const compact = await measuredRowsOf(page);+ expect(compact.length).toBeGreaterThan(1);+ for (let i = 0; i + 1 < compact.length; i++) {+ expect(compact[i].layer.bottom, JSON.stringify(compact)).toBe(0);+ expect(compact[i + 1].layer.top, JSON.stringify(compact)).toBe(0);+ }+ expectNoOverlap(compact);+ // The divider's width reaches the row's own layer, never the row's content.+ const borders = await page.locator('#storybook-root li').evaluateAll(rows =>+ rows.map(row => [+ getComputedStyle(row, '::after')+ .getPropertyValue('--_hit-border-bottom')+ .trim(),+ getComputedStyle(row.firstElementChild ?? row)+ .getPropertyValue('--_hit-border-bottom')+ .trim(),+ ]),+ );+ expect(borders.length, JSON.stringify(borders)).toBeGreaterThan(1);+ for (const [layer, content] of borders.slice(0, -1)) {+ expect(layer, JSON.stringify(borders)).not.toMatch(/^(0px)?$/);+ expect(content, JSON.stringify(borders)).toBe('');+ }+ expect(borders.at(-1), JSON.stringify(borders)).toEqual(['0px', '']);+ // A disabled row offers no target: no layer, nothing measured.+ await openStory(page, storybook(), 'core-list--disabled-items');+ await measuredRowsOf(page);+ const disabled = await page+ .locator('#storybook-root li[aria-disabled="true"]')+ .evaluateAll(rows =>+ rows.map(row => [+ getComputedStyle(row, '::after').content,+ (row as HTMLElement).style.getPropertyValue('--astryx-hit-inset-top'),+ ]),+ );+ expect(disabled.length).toBeGreaterThan(0);+ for (const [content, written] of disabled) {+ expect(content).toBe('none');+ expect(written).toBe('');+ }+});++test('under a finger, a page’s `--size-touch-target` leaves the 44px target, which no token admits yet, and row padding reaches the layer', async ({+ page,+}) => {+ test.skip(!(await isTouch(page)), 'the hit area applies under a finger only');+ // The rows grow toward 44 px, whatever a page sets.+ await openStory(page, storybook(), 'core-list--interactive');+ const plain = (await measuredRowsOf(page)).map(row => row.layer);+ expect(plain.some(layer => layer.top > 0 || layer.bottom > 0)).toBe(true);+ await themeTouchTarget(page, '60px');+ await openStory(page, storybook(), 'core-list--interactive');+ expect((await measuredRowsOf(page)).map(row => row.layer)).toEqual(plain);+ await themeTouchTarget(page, '30px');+ await openStory(page, storybook(), 'core-list--interactive');+ expect((await measuredRowsOf(page)).map(row => row.layer)).toEqual(plain);+ // Row padding that makes the row as tall as the target.+ await page.addInitScript(() => {+ document.addEventListener('DOMContentLoaded', () => {+ const style = document.createElement('style');+ style.textContent =+ '#storybook-root li { padding-block: 12px !important; }';+ document.head.append(style);+ });+ });+ await openStory(page, storybook(), 'core-list--interactive');+ const padded = await measuredRowsOf(page);+ expect(padded[0].height).toBeGreaterThanOrEqual(44);+ for (const row of padded) {+ expect([row.layer.top, row.layer.bottom]).toEqual([0, 0]);+ }+});++test('under a finger, a tap in a link row’s growth follows its link', async ({+ page,+}) => {+ test.skip(!(await isTouch(page)), 'the hit area applies under a finger only');+ await openStory(page, storybook(), 'core-list--links');+ const rows = await measuredRowsOf(page);+ // The growth above the first row, toward 44px, outside the row's anchor.+ const grow = rows[0].layer.top;+ expect(grow, JSON.stringify(rows)).toBeGreaterThanOrEqual(1.5);+ const inside = rows[0].top - grow / 2;+ expect(await rowAt(page, rows[0].x, inside)).toBe(rows[0].text);+ // The row is the Links story's "Documentation" (`href="/docs"`).+ const followed = page.waitForURL(/\/docs$/, {timeout: 5000});+ await page.touchscreen.tap(rows[0].x, inside);+ await followed;+});++test('under a finger, a tap in a link row’s own padding, outside its anchor, follows its link', async ({+ page,+}) => {+ test.skip(!(await isTouch(page)), 'the hit area applies under a finger only');+ await openStory(page, storybook(), 'core-list--links');+ const row = page.locator('#storybook-root li').first();+ const box = await row.boundingBox();+ if (box == null) {+ throw new Error('no row');+ }+ // The row's leading padding: inside its box, outside its anchor. (Chromium+ // also moves a tap this close onto the anchor by its touch adjustment;+ // WebKit does not, and its click from a finger says `mouse`.)+ const x = box.x + 2;+ const y = box.y + box.height / 2;+ expect(+ await page.evaluate(+ ([px, py]) => document.elementFromPoint(px, py)?.closest('a') == null,+ [x, y],+ ),+ ).toBe(true);+ // The row is the Links story's "Documentation" (`href="/docs"`).+ const followed = page.waitForURL(/\/docs$/, {timeout: 5000});+ await page.touchscreen.tap(x, y);+ await followed;+});++test('a mouse click in a link row’s padding does nothing, as before', async ({+ browser,+}) => {+ const context = await browser.newContext({+ hasTouch: false,+ isMobile: false,+ viewport: {width: 900, height: 700},+ });+ const page = await context.newPage();+ try {+ await openStory(page, storybook(), 'core-list--links');+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ const row = page.locator('#storybook-root li').first();+ const box = await row.boundingBox();+ if (box == null) {+ throw new Error('no row');+ }+ const url = page.url();+ // The row's leading padding: inside its box, outside its anchor.+ await page.mouse.click(box.x + 2, box.y + box.height / 2);+ await page.waitForTimeout(500);+ expect(page.url()).toBe(url);+ } finally {+ await context.close();+ }+});++for (const story of [+ 'core-list--interactive',+ 'core-list--links',+ 'core-list--compact',+ 'core-list--with-media',+]) {+ test(`${story}: the layer adds no layout and paints nothing, and a mouse gets none`, async ({+ browser,+ page,+ }, testInfo) => {+ await openStory(page, storybook(), story);+ test.skip(+ !(await isTouch(page)),+ 'the hit area applies under a finger only',+ );+ const touch = await measuredRowsOf(page);+ // The same page with every row's layer taken away: the same boxes.+ await page.addStyleTag({+ content: '#storybook-root li::after { display: none !important; }',+ });+ const bare = await rowsOf(page);+ const mouse = await withMouse(browser, testInfo, async mousePage => {+ await openStory(mousePage, storybook(), story);+ expect(await isTouch(mousePage)).toBe(false);+ // A frame for a pass that must not come.+ await mousePage.evaluate(async () => {+ await new Promise(resolve => requestAnimationFrame(resolve));+ });+ return rowsOf(mousePage);+ });+ const summary = JSON.stringify({touch, bare, mouse});+ expect(touch.length, summary).toBeGreaterThan(0);+ expect(bare.length, summary).toBe(touch.length);+ expect(mouse.length, summary).toBe(touch.length);+ for (const [i, row] of touch.entries()) {+ expect(row.top, summary).toBeCloseTo(bare[i].top, 2);+ expect(row.height, summary).toBeCloseTo(bare[i].height, 2);+ if (row.layer.content !== 'none') {+ expect(row.layer.paint, summary).toMatch(+ /^rgba\(0, 0, 0, 0\) \| none \| none \| 0px \| none$/,+ );+ }+ // A mouse: no pseudo-element, no stacking context, nothing measured.+ expect(mouse[i].layer.content, summary).toBe('none');+ expect(mouse[i].isolation, summary).toBe('auto');+ expect(mouse[i].written, summary).toBe('');+ }+ });+}diff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsxindex 8373b4f458..ffb1f5a038 100644--- a/packages/core/src/RadioList/RadioListItem.tsx+++ b/packages/core/src/RadioList/RadioListItem.tsx@@ -18,7 +18,7 @@* - /packages/cli/assets/templates/blocks/components/RadioList/ (showcase blocks)*/-import React, {use, useCallback, useId, useRef, type ReactNode} from 'react';+import React, {use, useId, useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';@@ -33,7 +33,7 @@ import {indicatorScope} from '../Indicator/indicator.markers.stylex';import {useIndicatorFocusRing} from '../hooks/useIndicatorFocusRing';import {usePressFeedback} from '../hooks/usePressFeedback';import {useMergedRefs} from '../hooks/useMergedRefs';-import {watchHitArea, writeHitInsets} from '../utils/hitArea';+import {useTouchHitArea} from '../utils/touchHitArea';import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';import {useIndicator} from '../Indicator/useIndicator';import {Item, type ItemAlign} from '../Item/Item';@@ -310,17 +310,9 @@ export function RadioListItem({// Under a coarse pointer an option's row grows toward 44 px through an// invisible band, and the row keeps its size. A tap on the band lands on- // the row, which hands it to the radio. The watch lives as long as the row- // is attached: the ref's cleanup stops it.- const watchRowHitArea = useCallback(- (row: HTMLDivElement | null) => {- if (row == null || isDisabled) {- return;- }- return watchHitArea(row, insets => writeHitInsets(row, insets));- },- [isDisabled],- );+ // the row, which hands it to the radio. The band's insets stay live while+ // the row takes taps, and clear when it stops.+ const watchRowHitArea = useTouchHitArea(!isDisabled);const mergedRowRef = useMergedRefs(ref, watchRowHitArea);const radioCircle = (diff --git a/packages/core/src/hooks/useClickableContainer.ts b/packages/core/src/hooks/useClickableContainer.tsindex cf8080391b..cd84e105ed 100644--- a/packages/core/src/hooks/useClickableContainer.ts+++ b/packages/core/src/hooks/useClickableContainer.ts@@ -6,8 +6,9 @@* @file useClickableContainer.ts* @input Container ref, interactive element ref, click/href handlers* @output onClick, onMouseUp and onPointerDown handlers for the container;- * INTERACTIVE_SELECTORS list;- * hasInteractiveAncestor and the shared innermostInteractive walk+ * INTERACTIVE_SELECTORS list; hasInteractiveAncestor and the shared+ * innermostInteractive walk; the internal useClickableContainerProxy, the+ * handlers without the marker* @position Core hook for clickable containers with nested interactive* elements. A click on a nested button or link does not run the card's* action, and a finger press there shows no press on the card. Each navigation@@ -237,14 +238,10 @@ export interface ClickableContainerResult {* );* ```*/-export function useClickableContainer({- containerRef,- interactiveRef,- onClick: onClickProp,- href,- target,- disabled = false,-}: UseClickableContainerOptions): ClickableContainerResult {+export function useClickableContainer(+ options: UseClickableContainerOptions,+): ClickableContainerResult {+ const {containerRef} = options;// Mark container as pressable for the interactive selector checkuseEffect(() => {const el = containerRef.current;@@ -252,7 +249,22 @@ export function useClickableContainer({el.setAttribute(PRESSABLE_CONTAINER_ATTRIBUTE, 'true');}}, [containerRef]);+ return useClickableContainerProxy(options);+}+/**+ * `useClickableContainer`'s click handlers, without its marker. Internal: Item+ * serves its delegate and List link rows from one call, and renders the marker+ * on a delegate row itself.+ */+export function useClickableContainerProxy({+ containerRef,+ interactiveRef,+ onClick: onClickProp,+ href,+ target,+ disabled = false,+}: UseClickableContainerOptions): ClickableContainerResult {const onClick = useCallback((event: MouseEvent<HTMLElement>) => {if (disabled) {diff --git a/packages/core/src/privateAttributes/press.stylex.ts b/packages/core/src/privateAttributes/press.stylex.tsindex ddeb6a358f..783425c916 100644--- a/packages/core/src/privateAttributes/press.stylex.ts+++ b/packages/core/src/privateAttributes/press.stylex.ts@@ -91,6 +91,8 @@ export const rowPressLayerStyles = stylex.create({* a row's own `::before` and its stacking are as they were; during a press* the layer is the row's `::before`, so a caller's decoration there merges* into the layer for that time (decorate with `::after` or a child).+ * Under a finger an interactive List row's `::after` is its touch hit area,+ * so decorate that row with a child.** Under a finger only (a coarse primary pointer): a fine pointer keeps the* variant exactly, with no layer, no stacking context and its own touchdiff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.tsindex d8a0cccef2..1974f63700 100644--- a/packages/core/src/theme/derivedVarRegistry.test.ts+++ b/packages/core/src/theme/derivedVarRegistry.test.ts@@ -341,6 +341,12 @@ const VARS_WITHOUT_DERIVED_MAPPING = new Set(['--_thumbnail-hit-inset','--_input-clear-hit-inset','--_power-search-sheet-hit-inset',+ // The border width a host draws where its touch hit layer reaches past,+ // such as a divided ListItem's divider (0 on the last row).+ // The ::after layer adds it to its offset, so the band starts past the+ // border. It is the layer's geometry, not a property a theme author sets. A+ // theme changes the divider through `--border-width`, which this follows.+ '--_hit-border-bottom',// The interaction overlay's colour on the ::after layer of the cards:// written by the component's own hover and mouse `:active` arms, never a// value a theme author sets; the overlay colours themselves are the shareddiff --git a/packages/core/src/utils/hitArea.test.ts b/packages/core/src/utils/hitArea.test.tsindex ab54d41acc..85a601f8b8 100644--- a/packages/core/src/utils/hitArea.test.ts+++ b/packages/core/src/utils/hitArea.test.ts@@ -528,6 +528,77 @@ describe('watchHitArea', () => {stop();});+ it('leaves a touch on content that the element paints past its own box to that content, however near a neighbour is', () => {+ // A row moved aside, its panel's entry painted beside it, and the next+ // row 2 px below the touch.+ document.body.insertAdjacentHTML(+ 'beforeend',+ '<div id="row"><button id="entry">Read</button></div>' ++ '<a id="next" href="#next">Next</a>',+ );+ const row = byId('row');+ const entry = byId('entry');+ place(row, rect(88, 16, 388, 60));+ place(entry, rect(16, 16, 72, 60));+ place(byId('next'), rect(16, 78, 388, 60));+ const stop = watchHitArea(row, () => {}, {ownsDescendantTouches: true});+ show(row);+ flush();+ // On the entry: 36 px from the row's box, 32 px from the next row.+ const press = new Event('pointerdown', {bubbles: true});+ Object.assign(press, {pointerType: 'touch', clientX: 52, clientY: 46});+ entry.dispatchEvent(press);+ const click = new MouseEvent('click', {+ bubbles: true,+ cancelable: true,+ detail: 1,+ });+ entry.dispatchEvent(click);+ expect(click.defaultPrevented).toBe(false);+ // The same touch on the row itself, in its band, is still checked.+ const bandPress = new Event('pointerdown', {bubbles: true});+ Object.assign(bandPress, {+ pointerType: 'touch',+ clientX: 52,+ clientY: 46,+ });+ row.dispatchEvent(bandPress);+ const bandClick = new MouseEvent('click', {+ bubbles: true,+ cancelable: true,+ detail: 1,+ });+ row.dispatchEvent(bandClick);+ expect(bandClick.defaultPrevented).toBe(true);+ stop();+ });++ it('still swallows a touch on a control’s own grown input that a neighbour is nearer, unless the watch owns its descendants’ touches', () => {+ // A switch whose invisible input grows past its track, as its coarse hit+ // area. A link moved to 2 px past the switch.+ const control = byId('switch');+ control.insertAdjacentHTML('beforeend', '<input id="input" />');+ const input = byId('input');+ place(control, rect(100, 100, 24, 24));+ place(input, rect(100, 100, 28, 24));+ place(byId('link'), rect(126, 100, 60, 24));+ const stop = watchHitArea(control, () => {});+ show(control);+ flush();+ // On the input, 2.5 px past the switch and 0.5 px from the link.+ const press = new Event('pointerdown', {bubbles: true});+ Object.assign(press, {pointerType: 'touch', clientX: 126.5, clientY: 112});+ input.dispatchEvent(press);+ const click = new MouseEvent('click', {+ bubbles: true,+ cancelable: true,+ detail: 1,+ });+ input.dispatchEvent(click);+ expect(click.defaultPrevented).toBe(true);+ stop();+ });+it('swallows a touch inside the fresh area that an offset neighbour is nearer (a corner)', () => {const control = byId('switch');// A tall link beside it, 8 px to the right, reaching far below.@@ -677,6 +748,17 @@ describe('watchHitArea', () => {flush();expect(heard).toEqual([]);});++ it('stops a watch whose window closed before it, as a removed iframe’s', () => {+ const iframe = document.body.appendChild(document.createElement('iframe'));+ const frameDocument = iframe.contentDocument as Document;+ const control = frameDocument.body.appendChild(+ frameDocument.createElement('button'),+ );+ const stop = watchHitArea(control, () => {});+ iframe.remove();+ expect(() => stop()).not.toThrow();+ });});describe('the package surface', () => {diff --git a/packages/core/src/utils/hitArea.ts b/packages/core/src/utils/hitArea.tsindex 3d93264d23..68113e5915 100644--- a/packages/core/src/utils/hitArea.ts+++ b/packages/core/src/utils/hitArea.ts@@ -267,6 +267,7 @@ function now(): number {interface Watch {readonly element: Element;readonly minSize: number;+ readonly ownsDescendantTouches: boolean;readonly onInsets: (insets: HitInsets) => void;isVisible: boolean;last: HitInsets;@@ -287,6 +288,8 @@ const observedSizes = new WeakMap<Element, string>();const scopeTimers = new Map<Element, ReturnType<typeof setTimeout>>();let frame: number | null = null;let view: Window | null = null;+/** The document the shared press listener is on, while it is on one. */+let pressDocument: Document | null = null;let pointer: MediaQueryList | null = null;let visibility: IntersectionObserver | null = null;let resize: ResizeObserver | null = null;@@ -599,7 +602,16 @@ function checkPress(element: Element, event: PointerEvent): void {const own = distanceTo(target, x, y);isNearerNeighbour ||= neighbours.some(rect => distanceTo(rect, x, y) < own);}- if (isNearerNeighbour) {+ // A watch can own its descendants' touches. Then a press that the browser+ // hit-tests onto a descendant lands on content the element paints, even+ // past its own box. A swipe panel's entry beside a moved row is such+ // content. That touch is the element's.+ const isOnOwnContent =+ [...entry.watches].some(watch => watch.ownsDescendantTouches) &&+ press.target instanceof Node &&+ press.target !== element &&+ element.contains(press.target);+ if (isNearerNeighbour && !isOnOwnContent) {const swallow = (click: Event) => {disarm();// A keyboard or assistive-technology activation (detail 0) is never@@ -687,7 +699,8 @@ function startObserving(): void {return;}view.addEventListener('resize', scheduleAll);- view.document.addEventListener('pointerdown', onPress, PASSIVE_CAPTURE);+ pressDocument = view.document;+ pressDocument.addEventListener('pointerdown', onPress, PASSIVE_CAPTURE);if (typeof IntersectionObserver === 'function') {visibility = new IntersectionObserver(entries => {for (const entry of entries) {@@ -743,7 +756,10 @@ function stopObserving(): void {entry.release = null;}view?.removeEventListener('resize', scheduleAll);- view?.document.removeEventListener('pointerdown', onPress, PASSIVE_CAPTURE);+ // The listener leaves the document it went on. A window can close first, as+ // a removed iframe's, and then it has no document to read.+ pressDocument?.removeEventListener('pointerdown', onPress, PASSIVE_CAPTURE);+ pressDocument = null;visibility?.disconnect();resize?.disconnect();visibility = null;@@ -777,6 +793,13 @@ function onPointerChange(): void {export interface WatchHitAreaOptions {/** The size to grow toward, px. @default 44 */readonly minSize?: number;+ /**+ * A touch that the browser hit-tests onto a descendant is the element's,+ * however near a neighbour is. Set it for a host whose content can paint+ * past its box, such as a list row with a swipe panel. A control whose+ * grown input is its descendant leaves it off. @default false+ */+ readonly ownsDescendantTouches?: boolean;}/**@@ -808,7 +831,10 @@ export function resetHitAreaForTests(): void {export function watchHitArea(element: Element,onInsets: (insets: HitInsets) => void,- {minSize = MIN_TOUCH_TARGET}: WatchHitAreaOptions = {},+ {+ minSize = MIN_TOUCH_TARGET,+ ownsDescendantTouches = false,+ }: WatchHitAreaOptions = {},): () => void {const owner = element.ownerDocument.defaultView;if (owner == null) {@@ -828,6 +854,7 @@ export function watchHitArea(const watch: Watch = {element,minSize,+ ownsDescendantTouches,onInsets,isVisible: isCoarse && visibility == null,last: NO_HIT_INSETS,diff --git a/packages/core/src/utils/touchHitArea.stylex.ts b/packages/core/src/utils/touchHitArea.stylex.tsindex 2eb4461fe4..17ef5f52ed 100644--- a/packages/core/src/utils/touchHitArea.stylex.ts+++ b/packages/core/src/utils/touchHitArea.stylex.ts@@ -5,11 +5,14 @@* @input Uses StyleX and the insets that utils/hitArea.ts writes on a host* @output Exports `touchHitAreaStyles.layer`, a host's invisible hit band* under a coarse pointer- * @position Internal styling utility for CheckboxInput and RadioListItem+ * @position Internal styling utility for CheckboxInput, RadioListItem, List+ * rows and InfoTip. Each keeps its insets live with `useTouchHitArea`+ * (utils/touchHitArea.ts).** The band is the host's `::after`, grown past each edge by the measured* inset. A clip path cuts out the host's box, so its content keeps its taps.- * A tap on the band lands on the host. SYNC: hitArea.ts HIT_INSET_PROPERTIES.+ * A tap on the band lands on the host. SYNC: hitArea.ts HIT_INSET_PROPERTIES,+ * touchHitArea.ts and touchHitArea.test.tsx.*/import * as stylex from '@stylexjs/stylex';@@ -21,7 +24,19 @@ const TOP = 'var(--astryx-hit-inset-top, 0px)';const RIGHT = 'var(--astryx-hit-inset-right, 0px)';const BOTTOM = 'var(--astryx-hit-inset-bottom, 0px)';const LEFT = 'var(--astryx-hit-inset-left, 0px)';+// The insets start at the host's border box, but the band's offsets start at+// its padding box. So a host that draws a border declares its width on that+// side, 0 by default. It declares it on its own `::after`, so content inside+// the host never inherits it.+const BORDER_TOP = 'var(--_hit-border-top, 0px)';+const BORDER_RIGHT = 'var(--_hit-border-right, 0px)';+const BORDER_BOTTOM = 'var(--_hit-border-bottom, 0px)';+const BORDER_LEFT = 'var(--_hit-border-left, 0px)';+// The host is the band's containing block, so a host that is not positioned+// sets `position: relative`. The band has no z-index of its own. Inside a+// List, which isolates its rows, ListItem raises it. Under a finger the host's+// `::after` is this band, so decorate the host with a child.export const touchHitAreaStyles = stylex.create({layer: {'::after': {@@ -29,7 +44,7 @@ export const touchHitAreaStyles = stylex.create({position: {default: null, [TOUCH]: 'absolute'},inset: {default: null,- [TOUCH]: `calc(${TOP} * -1) calc(${RIGHT} * -1) calc(${BOTTOM} * -1) calc(${LEFT} * -1)`,+ [TOUCH]: `calc((${TOP} + ${BORDER_TOP}) * -1) calc((${RIGHT} + ${BORDER_RIGHT}) * -1) calc((${BOTTOM} + ${BORDER_BOTTOM}) * -1) calc((${LEFT} + ${BORDER_LEFT}) * -1)`,},// The outer rectangle, then the host's box as an even-odd hole.clipPath: {diff --git a/packages/core/src/utils/touchHitArea.test.tsx b/packages/core/src/utils/touchHitArea.test.tsxnew file mode 100644index 0000000000..8e4e341b9a--- /dev/null+++ b/packages/core/src/utils/touchHitArea.test.tsx@@ -0,0 +1,342 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file touchHitArea.test.tsx+ * @input Vitest, Testing Library, StyleX's injected rules, and a stubbed+ * watchHitArea (utils/hitArea.ts)+ * @output Tests for the shared touch hit area hook and layer. They cover what+ * the hook watches, a measurement while the parent moves, the stop, and the+ * layer's CSS.+ * @position Unit test for utils/touchHitArea.ts and+ * utils/touchHitArea.stylex.ts. List/ListItem.hitArea.test.tsx covers the+ * row wiring.+ */++import {useCallback} from 'react';+import * as stylex from '@stylexjs/stylex';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {render, screen} from '@testing-library/react';+import type * as HitAreaModule from './hitArea';+import {HIT_INSET_PROPERTIES, type HitInsets} from './hitArea';+import {useMergedRefs} from '../hooks/useMergedRefs';++const watches = vi.hoisted(+ () =>+ [] as {+ element: Element;+ onInsets: (insets: HitInsets) => void;+ minSize: number | undefined;+ stop: ReturnType<typeof vi.fn>;+ }[],+);++vi.mock('./hitArea', async importOriginal => {+ const actual = await importOriginal<typeof HitAreaModule>();+ return {+ ...actual,+ watchHitArea: (+ element: Element,+ onInsets: (insets: HitInsets) => void,+ options?: {readonly minSize?: number},+ ) => {+ const stop = vi.fn();+ watches.push({element, onInsets, minSize: options?.minSize, stop});+ return stop;+ },+ };+});++import {useTouchHitArea} from './touchHitArea';+import {touchHitAreaStyles} from './touchHitArea.stylex';++function Host({+ enabled,+ target,+ swap = false,+}: {+ enabled: boolean;+ target?: string;+ swap?: boolean;+}) {+ const hitAreaRef = useTouchHitArea(enabled);+ // The page's touch target, set before the hit area reads the element.+ const setTarget = useCallback(+ (node: HTMLSpanElement | null) => {+ if (node != null && target != null) {+ node.style.setProperty('--size-touch-target', target);+ }+ },+ [target],+ );+ const ref = useMergedRefs(setTarget, hitAreaRef);+ return (+ <div>+ <span+ key={swap ? 'replaced' : 'first'}+ data-testid="host"+ ref={ref}+ {...stylex.props(touchHitAreaStyles.layer)}+ />+ </div>+ );+}++/** The element's injected `::after` rules, split by the touch gate. */+function afterRules(el: Element): {touch: string[]; other: string[]} {+ const classes = el.className+ .split(/\s+/)+ .filter(Boolean)+ .map(name => `.${name}`);+ const out = {touch: [] as string[], other: [] as string[]};+ const visit = (rules: CSSRuleList, touch: boolean) => {+ for (const rule of Array.from(rules)) {+ if (rule instanceof CSSStyleRule) {+ if (+ rule.selectorText.includes('::after') &&+ classes.some(cls => rule.selectorText.startsWith(cls))+ ) {+ (touch ? out.touch : out.other).push(+ `${rule.selectorText} {${rule.style.cssText}}`,+ );+ }+ continue;+ }+ const nested = (rule as CSSGroupingRule).cssRules;+ if (nested == null) {+ continue;+ }+ const condition = (rule as CSSConditionRule).conditionText ?? '';+ visit(nested, touch || condition.includes('pointer: coarse'));+ }+ };+ for (const sheet of Array.from(document.styleSheets)) {+ visit(sheet.cssRules, false);+ }+ return out;+}++function stubCoarse(): void {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: query === '(pointer: coarse)',+ media: query,+ addEventListener: () => {},+ removeEventListener: () => {},+ }));+}++describe('useTouchHitArea', () => {+ afterEach(() => {+ watches.length = 0;+ vi.unstubAllGlobals();+ });++ it('watches the element while enabled, toward 44 px, and stops when disabled or unmounted', async () => {+ const {rerender, unmount} = render(<Host enabled={false} />);+ expect(watches).toHaveLength(0);+ rerender(<Host enabled />);+ expect(watches.map(watch => watch.element)).toEqual([+ screen.getByTestId('host'),+ ]);+ // No coarse pointer here: the 44 px minimum.+ expect(watches[0].minSize).toBe(44);+ rerender(<Host enabled={false} />);+ await Promise.resolve();+ expect(watches[0].stop).toHaveBeenCalledTimes(1);+ unmount();++ stubCoarse();+ const host = render(<Host enabled />);+ const element = screen.getByTestId('host');+ expect(watches[1].element).toBe(element);+ expect(watches[1].minSize).toBe(44);+ host.unmount();+ await Promise.resolve();+ expect(watches[1].stop).toHaveBeenCalledTimes(1);+ });++ it('follows a replaced element: the new element is watched and the old one’s watch stops', async () => {+ const {rerender} = render(<Host enabled />);+ const first = screen.getByTestId('host');+ expect(watches.map(watch => watch.element)).toEqual([first]);+ rerender(<Host enabled swap />);+ await Promise.resolve();+ const replaced = screen.getByTestId('host');+ expect(replaced).not.toBe(first);+ expect(watches[0].stop).toHaveBeenCalledTimes(1);+ expect(watches.map(watch => watch.element)).toEqual([first, replaced]);+ });++ it('keeps the 44 px target under a finger whatever a page sets: no token admits `--size-touch-target` yet', () => {+ stubCoarse();+ render(<Host enabled target="60px" />);+ expect(watches[0].minSize).toBe(44);+ });++ it('listens to no media query of its own: the shared hit area owns the pointer query', () => {+ const listeners: string[] = [];+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: query === '(pointer: coarse)',+ media: query,+ addEventListener: () => listeners.push(query),+ removeEventListener: () => {},+ }));+ render(<Host enabled target="60px" />);+ // Present first: the hit area is on, watching the element.+ expect(watches).toHaveLength(1);+ expect(listeners).toEqual([]);+ });++ it('writes the insets it hears on the element', () => {+ render(<Host enabled />);+ watches[0].onInsets({top: 3, right: 2, bottom: 1, left: 0});+ const element = screen.getByTestId('host');+ expect(element.style.getPropertyValue(HIT_INSET_PROPERTIES.top)).toBe(+ '3px',+ );+ expect(element.style.getPropertyValue(HIT_INSET_PROPERTIES.right)).toBe(+ '2px',+ );+ });++ it('clears the insets when a watch stops, so a fresh watch that measures zero leaves none behind', async () => {+ const {rerender} = render(<Host enabled />);+ watches[0].onInsets({top: 6, right: 0, bottom: 6, left: 0});+ const element = screen.getByTestId('host');+ expect(element.style.getPropertyValue(HIT_INSET_PROPERTIES.top)).toBe(+ '6px',+ );+ // Watched afresh. The new watch hears no zero measurement, since it+ // starts at zero, so the stop clears the old insets.+ rerender(<Host enabled={false} />);+ await Promise.resolve();+ rerender(<Host enabled />);+ expect(watches).toHaveLength(2);+ expect(element.style.getPropertyValue(HIT_INSET_PROPERTIES.top)).toBe(+ '0px',+ );+ expect(element.style.getPropertyValue(HIT_INSET_PROPERTIES.bottom)).toBe(+ '0px',+ );+ });++ it('drops a measurement taken while the element’s parent moves, and watches afresh once the motion ends', async () => {+ render(<Host enabled />);+ const element = screen.getByTestId('host');+ const parent = element.parentElement!;+ let finish = (): void => {};+ const finished = new Promise<void>(resolve => {+ finish = resolve;+ });+ const slide = {+ playState: 'running',+ effect: {getComputedTiming: () => ({endTime: 300})},+ finished,+ } as unknown as Animation;+ parent.getAnimations = () => [slide];+ watches[0].onInsets({top: 3, right: 0, bottom: 1, left: 0});+ expect(element.style.getPropertyValue(HIT_INSET_PROPERTIES.top)).toBe('');+ parent.getAnimations = () => [];+ finish();+ await vi.waitFor(() => expect(watches).toHaveLength(2));+ expect(watches[0].stop).toHaveBeenCalledTimes(1);+ watches[1].onInsets({top: 4, right: 0, bottom: 1, left: 0});+ expect(element.style.getPropertyValue(HIT_INSET_PROPERTIES.top)).toBe(+ '4px',+ );+ });++ it('does not wait on an endless animation nearby (a spinner)', () => {+ render(<Host enabled />);+ const element = screen.getByTestId('host');+ const spinner = {+ playState: 'running',+ effect: {getComputedTiming: () => ({endTime: Infinity})},+ finished: new Promise<void>(() => {}),+ } as unknown as Animation;+ element.parentElement!.getAnimations = () => [spinner];+ watches[0].onInsets({top: 2, right: 0, bottom: 2, left: 0});+ expect(element.style.getPropertyValue(HIT_INSET_PROPERTIES.top)).toBe(+ '2px',+ );+ });+});++describe('useTouchHitArea across re-renders', () => {+ afterEach(() => {+ watches.length = 0;+ });++ /** A host that merges whatever ref its caller passes. */+ function RefHost({+ nodeRef,+ }: {+ nodeRef: (node: HTMLSpanElement | null) => void;+ }) {+ const hitAreaRef = useTouchHitArea(true);+ const ref = useMergedRefs(nodeRef, hitAreaRef);+ return <span data-testid="host" ref={ref} />;+ }++ /** The caller, which passes a new inline ref on every render. */+ function InlineRefHost({tick}: {tick: number}) {+ return (+ <RefHost+ nodeRef={node => {+ node?.setAttribute('data-tick', String(tick));+ }}+ />+ );+ }++ it('keeps one watch, and its insets, when a re-render hands the element a new merged ref', async () => {+ const {rerender} = render(<InlineRefHost tick={0} />);+ const element = screen.getByTestId('host');+ watches[0].onInsets({top: 6, right: 0, bottom: 6, left: 0});+ rerender(<InlineRefHost tick={1} />);+ await Promise.resolve();+ expect(element.getAttribute('data-tick')).toBe('1');+ expect(watches).toHaveLength(1);+ expect(watches[0].stop).not.toHaveBeenCalled();+ expect(element.style.getPropertyValue(HIT_INSET_PROPERTIES.top)).toBe(+ '6px',+ );+ });++ it('writes no insets on an element whose watch never measured, as under a mouse', async () => {+ const {rerender} = render(<Host enabled />);+ const element = screen.getByTestId('host');+ rerender(<Host enabled={false} />);+ await Promise.resolve();+ expect(watches[0].stop).toHaveBeenCalledTimes(1);+ expect(element.style.getPropertyValue(HIT_INSET_PROPERTIES.top)).toBe('');+ });+});++describe('touchHitAreaStyles.layer', () => {+ it('is a coarse-only ::after grown on all four sides by the inset properties past the host’s border, the element as its clip-path hole, with no z-index of its own, painting nothing, and the host starting no stacking context', () => {+ render(<Host enabled={false} />);+ const {touch, other} = afterRules(screen.getByTestId('host'));+ const layer = touch.join('\n');+ expect(layer).toContain('position: absolute');+ // Offset from the host's padding box: the inset, plus the border the host+ // declares on that side (the inset is measured from its border box). One+ // per side, in physical order: top, right, bottom, left.+ const offset = (side: keyof typeof HIT_INSET_PROPERTIES) =>+ `calc\\(\\(var\\(${HIT_INSET_PROPERTIES[side]}, ?0px\\) \\+ var\\(--_hit-border-${side}, ?0px\\)\\) \\* -1\\)`;+ expect(layer).toMatch(+ new RegExp(+ `inset: ${offset('top')} ${offset('right')} ${offset('bottom')} ${offset('left')}`,+ ),+ );+ expect(layer).toMatch(/clip-path: polygon\(evenodd/);+ // No z-index of its own: what bounds a raise is the host's container's+ // call (a List raises its rows' layers and isolates them, ListItem).+ expect(layer).not.toMatch(/z-index/);+ // It paints nothing: no paint declaration of its own.+ expect(layer).not.toMatch(+ /[{;]\s*(?:background|border|box-shadow|outline|isolation)[\w-]*\s*:/,+ );+ // With a mouse: no pseudo-element.+ expect(other).toEqual([]);+ });+});diff --git a/packages/core/src/utils/touchHitArea.ts b/packages/core/src/utils/touchHitArea.tsnew file mode 100644index 0000000000..14d62441d9--- /dev/null+++ b/packages/core/src/utils/touchHitArea.ts@@ -0,0 +1,177 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file touchHitArea.ts+ * @input Whether an element takes taps, the shared touch hit area+ * (utils/hitArea.ts) and the Web Animations around the element+ * @output `useTouchHitArea`, a callback ref that keeps an element's hit insets+ * live for its invisible layer (`touchHitAreaStyles.layer`)+ * @position Core-internal hook for the coarse-only 44 px target. List rows,+ * InfoTip, CheckboxInput and RadioListItem use it, and so can any control+ * whose target grows under a finger without growing its box.+ *+ * SYNC: When modified, update utils/touchHitArea.stylex.ts and+ * touchHitArea.test.tsx.+ */++import {useCallback, type RefCallback} from 'react';+import {+ MIN_TOUCH_TARGET,+ NO_HIT_INSETS,+ watchHitArea,+ writeHitInsets,+} from './hitArea';++/**+ * The finite animations running or held in the element's parent, the element+ * included: a row's own motion and its neighbors'. An endless one (a spinner)+ * moves nothing that comes to rest, so it holds nothing.+ */+function settlingAnimations(element: HTMLElement): Animation[] {+ const scope = element.parentElement ?? element;+ if (typeof scope.getAnimations !== 'function') {+ return [];+ }+ return scope.getAnimations({subtree: true}).filter(animation => {+ if (animation.playState !== 'running' && animation.playState !== 'paused') {+ return false;+ }+ const end = animation.effect?.getComputedTiming().endTime;+ return typeof end === 'number' && Number.isFinite(end);+ });+}++/**+ * Watches `element` and takes its insets only at rest. Returns the stop.+ *+ * Under a coarse primary pointer, the shared utility measures how far the+ * element's hit target may grow without reaching a neighbor's half of the+ * gap. This writes those insets on the element, where its layer reads them.+ * Under a fine pointer the shared utility starts no observer.+ *+ * Elements move by transform: a list row in an update's slide, a swipe, or+ * neighbors that slide past. The shared measurement reads them as they stand+ * in one frame. So a measurement that arrives while the parent has a finite+ * animation running or held is dropped. When those animations end, the+ * element is watched again. The insets are then taken at rest, and no frame+ * of a compositor-only motion lays out or paints for them.+ */+function watchAtRest(element: HTMLElement, minSize: number): () => void {+ let stopWatch = (): void => {};+ let isStopped = false;+ let isWaiting = false;+ let hasWritten = false;+ // A stopped watch clears the insets it wrote. A fresh watch skips a+ // measurement equal to its start, zero, so old insets would otherwise stay.+ // A watch that wrote nothing, as under a mouse, writes nothing.+ const stop = (): void => {+ stopWatch();+ if (hasWritten) {+ hasWritten = false;+ writeHitInsets(element, NO_HIT_INSETS);+ }+ };+ const watch = (): void => {+ stopWatch = watchHitArea(+ element,+ insets => {+ const moving = settlingAnimations(element);+ if (moving.length === 0) {+ hasWritten = true;+ writeHitInsets(element, insets);+ return;+ }+ if (isWaiting) {+ return;+ }+ isWaiting = true;+ void Promise.allSettled(+ moving.map(async animation => animation.finished),+ ).then(() => {+ isWaiting = false;+ if (!isStopped) {+ stop();+ watch();+ }+ });+ },+ // The layer is the host's own `::after`, so a touch on the host's+ // content is the host's, even where that content paints past its box.+ {minSize, ownsDescendantTouches: true},+ );+ };+ watch();+ return () => {+ isStopped = true;+ stop();+ };+}++/** The watch on an element, and how many attached refs hold it. */+interface HeldWatch {+ readonly stop: () => void;+ holders: number;+}++const heldWatches = new WeakMap<HTMLElement, HeldWatch>();++/**+ * Holds the element's watch, and starts it on the first hold. Returns the+ * release. A ref that changes, such as a merge with a caller's inline ref,+ * detaches and attaches again in one commit. So the last release waits a+ * microtask, and an attach in between keeps the watch and its insets.+ */+function holdWatch(element: HTMLElement): () => void {+ let held = heldWatches.get(element);+ if (held == null) {+ held = {stop: watchAtRest(element, MIN_TOUCH_TARGET), holders: 0};+ heldWatches.set(element, held);+ }+ held.holders += 1;+ const entry = held;+ let isReleased = false;+ return () => {+ if (isReleased) {+ return;+ }+ isReleased = true;+ entry.holders -= 1;+ queueMicrotask(() => {+ if (entry.holders === 0 && heldWatches.get(element) === entry) {+ heldWatches.delete(element);+ entry.stop();+ }+ });+ };+}++/**+ * A callback ref that keeps its element's hit insets live while `enabled`:+ * the element takes taps, so it is interactive and not disabled or read-only.+ * Merge it into the element's ref, and pair it with `touchHitAreaStyles.layer`+ * on the same element. The watch lasts while the element is attached, so a+ * replaced element starts its own. A re-render that hands the same element a+ * new merged ref keeps its watch.+ *+ * @example+ * ```+ * const hitAreaRef = useTouchHitArea(isInteractive && !isDisabled);+ * <li ref={hitAreaRef} {...stylex.props(isInteractive && touchHitAreaStyles.layer)} />+ * ```+ */+export function useTouchHitArea(enabled: boolean): RefCallback<HTMLElement> {+ // Syncs with an external system: the shared touch hit area+ // (utils/hitArea.ts) measures the element against its neighbors and writes+ // its insets on it. The ref's cleanup stops the watch.+ return useCallback(+ (element: HTMLElement | null) => {+ if (!enabled || element == null) {+ return undefined;+ }+ return holdWatch(element);+ },+ [enabled],+ );+}diff --git a/scripts/build-css.test.mjs b/scripts/build-css.test.mjsindex 5b2257c33f..e9bb569cb6 100644--- a/scripts/build-css.test.mjs+++ b/scripts/build-css.test.mjs@@ -406,4 +406,45 @@ describe('build-css astryx.css', () => {expect(costly).toEqual([]);});});++ describe("the list rows' touch hit layer", () => {+ /**+ * A rule the build puts inside the touch gate (TOUCH_QUERY,+ * utils/touchQueries.ts): a coarse primary pointer, iOS and Android alike,+ * never a mouse. No engine condition: one touch model.+ */+ const TOUCH_GATED = /^@media \(pointer: coarse\)\{(?!@supports)/;+ const rules = () => astryxCss.split('\n').map(line => line.trim());++ it('gives an interactive row its hit layer only under a finger, and no row a new height', () => {+ // Each edge grows by the inset utils/hitArea.ts measures, plus the+ // border the row declares on that side. The layer's offsets start at the+ // row's padding box, but the insets start at its border box. One inset+ // per side, in physical order: top, right, bottom, left.+ const offset = side =>+ `calc\\(\\(var\\(--astryx-hit-inset-${side}, ?0px\\) ?\\+ ?var\\(--_hit-border-${side}, ?0px\\)\\) ?\\* ?-1\\)`;+ const band = new RegExp(+ `::after\\{inset:${offset('top')} ${offset('right')} ${offset('bottom')} ${offset('left')}\\}`,+ );+ const edges = rules().filter(rule => band.test(rule));+ expect(edges.length).toBeGreaterThan(0);+ for (const rule of edges) {+ expect(rule).toMatch(TOUCH_GATED);+ }+ // Row height and geometry stay as they are, under every pointer.+ expect(+ rules().filter(rule => /\{min-height:(52|62)px\}/.test(rule)),+ ).toEqual([]);+ });++ it('declares a row’s border width on its layer alone, so content inside the row never inherits it', () => {+ const declared = rules().filter(rule =>+ /\{--_hit-border-(top|right|bottom|left):/.test(rule),+ );+ expect(declared.length).toBeGreaterThan(0);+ for (const rule of declared) {+ expect(rule).toMatch(/::after\{--_hit-border-/);+ }+ });+ });});