Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(core): a checkbox's or radio option's hit area grows toward 44 px (#8241)

Christopher Chedeau9bd11b3635ec
diff --git a/.changeset/selection-touch-targets.md b/.changeset/selection-touch-targets.md
new file mode 100644
index 0000000000..261fc9cf9f
--- /dev/null
+++ b/.changeset/selection-touch-targets.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Under a finger, a labelled CheckboxInput and each RadioList option get an invisible hit area. It grows toward 44 px, never makes the target smaller than the control’s own box, and stops at half the gap to a closer neighbour, so neighbouring targets never overlap. Nothing changes size. Under a finger a RadioListItem row’s `::after` is that hit area, so decorate a row with a child. A label-hidden checkbox inside another component’s row keeps that row’s target. With a mouse or trackpad nothing changes.
+
+@vjeux
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index f01a260ee8..8de97d2d93 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -662,8 +662,9 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and
that grows only with its text, such as a Button whose label follows the
16 px reading base:
the 16 px mobile reading base (`design:mobile-typography` DR1, DR3) and the
- 16 px text-entry floor (`family:input-fields` FR9) are unaffected. Under a
- coarse pointer, touch targets meet 44 px through an invisible hit area. A
+ 16 px text-entry floor (`family:input-fields` FR9) are unaffected.
+ Under a coarse pointer, the touch target grows toward 44 × 44 px, up to halfway to a neighboring target, and is never smaller than the control's own box (owner decision, 2026-11-04; `spec:AST-094` FR42).
+ It grows through an invisible hit area. A
hit-area expansion never overlaps a neighboring interactive element's own
target: where neighbors are closer than 44 px, the expansion is clamped to
half the gap, or skipped, so each element stays reachable; an expansion a
diff --git a/docs/specs/components/CheckboxInput/CheckboxInput.spec.md b/docs/specs/components/CheckboxInput/CheckboxInput.spec.md
index f9e21441ea..20d2d975e2 100644
--- a/docs/specs/components/CheckboxInput/CheckboxInput.spec.md
+++ b/docs/specs/components/CheckboxInput/CheckboxInput.spec.md
@@ -30,6 +30,8 @@ verified_by:
packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.chromium.spec.ts,
packages/core/src/theme/themingTargets.test.ts,
packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx,
+ packages/core/src/Indicator/touchTarget.test.tsx,
+ packages/core/src/Indicator/__tests__/TouchTargets.interaction.browser.spec.ts,
]
modules: []
families: []
@@ -118,6 +120,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR11 | CheckboxInput applies `design:user-states` DR1 and DR2 for the pressed overlay, painting it on the indicator while the row is pressed, except over an indicator that paints its own press (AV1). | `design:user-states/DR1–DR5` |
| FR12 | `sm` and `md` MUST keep the native input, indicator, focus paint, and row geometry aligned; field `width` MUST size the whole field rather than only the input. | shipped source, tests, and stories |
| FR13 | With neither `onChange` nor `changeAction`, activation changes nothing the caller can observe. Implementation gap: the checkbox declares no read-only or unavailable state; its meaning is OQ1 (Current-state impact). | shared checkbox known-failure record |
+| FR14 | Under a coarse pointer, the touch target grows toward 44 × 44 px, up to halfway to a neighboring target, and is never smaller than the control's own box (owner decision, 2026-11-04; `spec:AST-094` FR42). It grows through an invisible band on a labelled, enabled, editable checkbox's row, and nothing changes size. A label-hidden checkbox keeps its composer's target. | `spec:AST-094` FR42; current source and tests |
### Allowed variation
@@ -190,6 +193,7 @@ The consumer record includes composed targets owned by CheckboxIndicator, FieldL
| FR10, AR3 | `CheckboxInput.test.tsx` focus-ring ownership suite | Built-in and prop-dropping replacement indicators; blur | A ring on the wrong element, or none, fails. | `audit:CheckboxInput/a11y` |
| FR11 | `CheckboxInput.test.tsx` pressed-state suite and its suite for an indicator that paints its own press | Enabled press; disabled; touch fade | A missing overlay, or one on a disabled box, fails. | `audit:CheckboxInput/visual` |
| FR12, AR5 | `CheckboxInput.test.tsx` coarse-pointer, RTL, and forced-colors suites | `sm`, `md`; RTL; forced colors | A misplaced hit target or a mark lost in forced colors fails. Evidence gap: no test asserts field `width`. | `audit:CheckboxInput/layout` |
+| FR14 | `touchTarget.test.tsx` hit-band, band-press and minimum cases; `TouchTargets.interaction.browser.spec.ts` checkbox cases | Labelled, label-hidden, disabled and read-only; 24 and 60 px rows; a finger, a tap whose click lands on the row's edge, and a mouse | A band where none belongs, a band under a mouse, a row that changes size, a 24 px row short of 44 px, a 60 px row with a band, or a band press that does not toggle fails. | `audit:CheckboxInput/behavior` |
| ORD1–ORD4, PR1 | ORD4 is covered by the FR8 rest-precedence case and ORD3 by the shared accessibility suite's disabled, disabled-reason, and read-only states. Evidence gap: no test asserts the optimistic value between `value` and the indicator (ORD1), the `preventDefault` check before `changeAction` (ORD2), or the absence of global listeners | — | — | `audit:CheckboxInput/behavior` |
## Current-state impact
diff --git a/docs/specs/components/RadioList/RadioListItem.spec.md b/docs/specs/components/RadioList/RadioListItem.spec.md
index 699f618ef7..386e002aec 100644
--- a/docs/specs/components/RadioList/RadioListItem.spec.md
+++ b/docs/specs/components/RadioList/RadioListItem.spec.md
@@ -30,6 +30,8 @@ verified_by:
packages/core/src/RadioList/__tests__/RadioGroup.a11y.test.tsx,
packages/core/src/RadioList/__tests__/RadioGroup.a11y.chromium.spec.ts,
apps/storybook/rtl-audit/targets.json,
+ packages/core/src/Indicator/touchTarget.test.tsx,
+ packages/core/src/Indicator/__tests__/TouchTargets.interaction.browser.spec.ts,
]
modules: []
families: []
@@ -124,6 +126,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR10 | Under forced colors, the selected dot stays visible. | WCAG 1.4.11; current tests |
| FR11 | The painted row element carries `astryx-radio-list-item` (alongside Item's own target) and reflects `data-size`, `data-selected` when checked, and `data-disabled` when disabled. A theme's `radio-list-item` styles override the bare default row. | `architecture:component-theming-surface` INV6; current tests |
| FR12 | `ref`, `className`, `style`, `xstyle`, `align`, `data-*`, `id`, and ARIA other than `aria-label` reach the row. | Current tests |
+| FR13 | Under a coarse pointer, the touch target grows toward 44 × 44 px, up to halfway to a neighboring target, and is never smaller than the control's own box (owner decision, 2026-11-04; `spec:AST-094` FR42). It grows through an invisible band on an enabled option's row, and the row keeps its size. | `spec:AST-094` FR42; current source and tests |
### Allowed variation
@@ -188,6 +191,7 @@ No design record beyond `design:user-states` governs RadioListItem.
| FR8 | `RadioList.test.tsx` pressed-state and bare-row cases; `RadioListItem.press.source-build.test.mjs` | Enabled, disabled, touch | Press paint on a disabled option, or a default row background, fails. Evidence gap: no test asserts the hover tint. | `audit:RadioListItem/visual` |
| FR9, FR10, AR3, AR4 | `RadioList.test.tsx` coarse-pointer, RTL, and forced-colors cases | Coarse pointer; RTL; forced colors | Evidence gap: the forced-colors case passes on any matching rule (the checkbox mark supplies one), so it does not prove the dot; the coarse-pointer and RTL cases check only the direction-symmetric centering class, not the 24 by 24 minimum or RTL placement. | `audit:RadioListItem/accessibility` |
| FR11, FR12 | `RadioList.test.tsx` theme-target and rest-forwarding cases | Sizes; selected; disabled | A target off the painted row, or a missing state, fails. Evidence gap: no test asserts `ref`, `className`, `style`, or `xstyle` on the row. | `audit:RadioListItem/theming` |
+| FR13 | `touchTarget.test.tsx` hit-band and minimum cases; `TouchTargets.interaction.browser.spec.ts` RadioList and mouse cases | Enabled and disabled; both orientations; 24 and 60 px; a mouse | A band on a disabled option, a band under a mouse, a row or gap that changes size, a band past half the gap, a 24 px row short of 44 px, or a 60 px row with a band fails. | `audit:RadioListItem/behavior` |
| PR1 | Evidence gap: no test asserts the absence of observers or global listeners | — | — | `audit:RadioListItem/behavior` |
| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on `RadioList / Default` | Indicator and label; LTR and RTL | An indicator that is not at the inline start of its label fails D2. | `audit:RadioListItem/i18n-rtl` |
diff --git a/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs b/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs
index 7faefaa61a..e64927e31d 100644
--- a/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs
+++ b/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs
@@ -109,7 +109,7 @@ export const docs = {
name: 'size',
type: "'sm' | 'md'",
description:
- 'The size of the checkbox. sm for compact layouts, md for default.',
+ 'The size of the checkbox. sm for compact layouts, md for default. Under a coarse pointer a labelled checkbox’s target grows toward 44 px through an invisible hit area. It never shrinks below the row and stops at half the gap to a closer neighbour; nothing changes size.',
default: "'md'",
},
{
@@ -361,7 +361,8 @@ export const docsZh = {
{
name: 'size',
type: "'sm' | 'md'",
- description: '复选框尺寸。sm 用于紧凑布局,md 为默认。',
+ description:
+ '复选框尺寸。sm 用于紧凑布局,md 为默认。在粗指针(触摸)下,带可见标签的复选框的目标通过不可见的点击区域向 44 px 扩展。它不小于所在行,与相邻控件较近时止于间距的一半;尺寸不变。',
default: "'md'",
},
{
diff --git a/packages/core/src/CheckboxInput/CheckboxInput.tsx b/packages/core/src/CheckboxInput/CheckboxInput.tsx
index 0a53411352..66325fc72d 100644
--- a/packages/core/src/CheckboxInput/CheckboxInput.tsx
+++ b/packages/core/src/CheckboxInput/CheckboxInput.tsx
@@ -24,6 +24,8 @@ import {
useTransition,
type ChangeEvent,
type FocusEvent,
+ type MouseEvent as ReactMouseEvent,
+ type PointerEvent as ReactPointerEvent,
type ReactNode,
} from 'react';
import * as stylex from '@stylexjs/stylex';
@@ -55,6 +57,8 @@ import {useIndicator} from '../Indicator/useIndicator';
import {themeProps} from '../utils/themeProps';
import {useMergedRefs} from '../hooks/useMergedRefs';
+import {watchHitArea, writeHitInsets} from '../utils/hitArea';
+import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';
import {
registerEnglishFallback,
useComponentTranslator,
@@ -83,6 +87,10 @@ const styles = stylex.create({
containerLabelHidden: {
gap: 0,
},
+ // Under a coarse pointer the row contains its hit band.
+ hitAreaHost: {
+ position: {default: null, '@media (pointer: coarse)': 'relative'},
+ },
// An indicator in another package may not name this row's private press
// attribute. So the row hands its touch press image down to an indicator
// that paints its own press, but only in its own press states. A pressed
@@ -407,6 +415,63 @@ export function CheckboxInput({
useBusyAnnouncement(isBusy, t('@astryx.spinner.loading'), indicatorRef);
const {focusProps} = useIndicatorFocusRing(indicatorRef);
+ // Under a coarse pointer a labelled checkbox's row grows toward 44 px
+ // through an invisible band, and nothing changes size. A label-hidden
+ // 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 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 row
+ // always attaches them.
+ const rowRef = useMergedRefs(
+ disabledMessageTooltip.interactionRef,
+ watchRowHitArea,
+ );
+ // Where a press on the row itself began. A browser can move a tap's click
+ // onto the row's edge, so the band is judged from the press.
+ const pressPointRef = useRef<{x: number; y: number} | null>(null);
+ const handleRowPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
+ pressPointRef.current =
+ event.target === event.currentTarget
+ ? {x: event.clientX, y: event.clientY}
+ : null;
+ };
+ // A press that began on the band, outside the row's box, toggles the
+ // checkbox, as a tap on the box does. A click from code has no press count
+ // (`detail` is 0), so it never toggles from here.
+ const handleRowClick = (event: ReactMouseEvent<HTMLDivElement>) => {
+ const press = pressPointRef.current;
+ pressPointRef.current = null;
+ if (
+ press == null ||
+ event.detail === 0 ||
+ event.target !== event.currentTarget
+ ) {
+ return;
+ }
+ const box = event.currentTarget.getBoundingClientRect();
+ const isOnBand =
+ press.x < box.left ||
+ press.x > box.right ||
+ press.y < box.top ||
+ press.y > box.bottom;
+ if (isOnBand) {
+ inputRef.current?.click();
+ }
+ };
+
const isIndeterminate = optimisticValue === 'indeterminate';
const isChecked = optimisticValue === true;
@@ -455,19 +520,15 @@ export function CheckboxInput({
style,
)}>
<div
- ref={el => {
- // Interaction (hover/focus) listeners for the disabled-message
- // tooltip attach to the whole row for a larger trigger target;
- // positioning anchors on the checkbox itself (below) so the tooltip
- // appears next to the control, not the far edge of the row.
- // Handlers are gated internally by isEnabled, so attaching
- // unconditionally is safe.
- disabledMessageTooltip.interactionRef(el);
- }}
+ ref={rowRef}
+ onPointerDown={hasHitArea ? handleRowPointerDown : undefined}
+ onClick={hasHitArea ? handleRowClick : undefined}
{...(isDisabled ? undefined : pressable)}
{...stylex.props(
styles.container,
isLabelHidden && styles.containerLabelHidden,
+ hasHitArea && styles.hitAreaHost,
+ hasHitArea && touchHitAreaStyles.layer,
// Hover and focus reach the checkbox visual through this ancestor
// marker rather than props, so the whole row drives it.
!isDisabled && indicatorScope,
@@ -490,6 +551,7 @@ export function CheckboxInput({
ref,
indeterminateRef,
disabledMessageTooltip.positionRef,
+ inputRef,
)}
id={id}
type="checkbox"
diff --git a/packages/core/src/Indicator/__tests__/TouchTargets.interaction.browser.spec.ts b/packages/core/src/Indicator/__tests__/TouchTargets.interaction.browser.spec.ts
new file mode 100644
index 0000000000..ad99fa9a0f
--- /dev/null
+++ b/packages/core/src/Indicator/__tests__/TouchTargets.interaction.browser.spec.ts
@@ -0,0 +1,432 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file TouchTargets.interaction.browser.spec.ts
+ * @input The built CheckboxInput, RadioList, CheckboxList and MultiSelector
+ * stories, real touch input and the interaction harness
+ * @output Proofs of the hit band under a finger. A labelled checkbox and a
+ * radio option keep their boxes. The band is at least 44 px and never
+ * smaller than the row. It stops at half the gap to a neighbour. A tap on
+ * it picks the control. A mouse gets no band.
+ * @position Real-engine layer; the unit layer is Indicator/touchTarget.test.tsx
+ */
+
+import {
+ expect,
+ test,
+ type Browser,
+ type Page,
+ type TestInfo,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ openStory,
+ touchDriver,
+ withStorybook,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+/** The minimum touch target, CSS px. */
+const SIZE = 44;
+
+interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+async function checkboxGeometry(page: Page) {
+ return page
+ .getByRole('checkbox')
+ .first()
+ .evaluate(input => {
+ const rect = (el: Element) => {
+ const r = el.getBoundingClientRect();
+ return {x: r.x, y: r.y, width: r.width, height: r.height};
+ };
+ const box = input
+ .closest('[data-astryx-pressable]')
+ ?.querySelector('.astryx-checkbox-indicator');
+ const row = input.closest('[data-astryx-pressable]');
+ if (box == null || row == null) {
+ throw new Error('no checkbox box or row');
+ }
+ return {input: rect(input), box: rect(box), row: rect(row)};
+ });
+}
+
+async function radioRows(page: Page): Promise<Rect[]> {
+ return page.getByRole('radio').evaluateAll(inputs =>
+ inputs.map(input => {
+ const row = input.closest('.astryx-item');
+ if (row == null) {
+ throw new Error('no radio row');
+ }
+ const r = row.getBoundingClientRect();
+ return {x: r.x, y: r.y, width: r.width, height: r.height};
+ }),
+ );
+}
+
+const centre = (r: Rect) => ({x: r.x + r.width / 2, y: r.y + r.height / 2});
+
+/** A band's insets on an element, px, as `watchHitArea` writes them. */
+async function hitInsets(page: Page, selector: string, index = 0) {
+ return page
+ .locator(selector)
+ .nth(index)
+ .evaluate(el => {
+ const style = getComputedStyle(el);
+ const read = (side: string) =>
+ parseFloat(style.getPropertyValue(`--astryx-hit-inset-${side}`)) || 0;
+ return {
+ top: read('top'),
+ right: read('right'),
+ bottom: read('bottom'),
+ left: read('left'),
+ };
+ });
+}
+
+const insetSum = (insets: Awaited<ReturnType<typeof hitInsets>>) =>
+ insets.top + insets.right + insets.bottom + insets.left;
+
+/** The insets once the band's first measurement has landed. */
+async function measuredInsets(page: Page, selector: string, index = 0) {
+ await expect
+ .poll(async () => insetSum(await hitInsets(page, selector, index)))
+ .toBeGreaterThan(0);
+ return hitInsets(page, selector, index);
+}
+
+/** Whether the element under a point is inside `selector`'s nth match. */
+async function ownsPoint(
+ page: Page,
+ selector: string,
+ index: number,
+ point: {x: number; y: number},
+) {
+ return page.evaluate(
+ ({css, n, x, y}) => {
+ const host = document.querySelectorAll(css)[n];
+ const hit = document.elementFromPoint(x, y);
+ return host != null && hit != null && host.contains(hit);
+ },
+ {css: selector, n: index, ...point},
+ );
+}
+
+/** The same story with a mouse: the phone's viewport and scale, a fine pointer. */
+async function withMouse<T>(
+ browser: Browser,
+ testInfo: TestInfo,
+ run: (mousePage: Page) => Promise<T>,
+): Promise<T> {
+ const {viewport, deviceScaleFactor} = testInfo.project.use;
+ const context = await browser.newContext({
+ viewport,
+ deviceScaleFactor,
+ hasTouch: false,
+ isMobile: false,
+ });
+ try {
+ return await run(await context.newPage());
+ } finally {
+ await context.close();
+ }
+}
+
+/**
+ * Measures with the band on every `selector` match taken away, then gives it
+ * back: the same page, so the same text and scale.
+ */
+async function withoutLayer<T>(
+ page: Page,
+ selector: string,
+ measure: () => Promise<T>,
+): Promise<T> {
+ const style = await page.addStyleTag({
+ content: `${selector}::after { display: none !important; }`,
+ });
+ try {
+ return await measure();
+ } finally {
+ await style.evaluate(async el => {
+ (el as Element).remove();
+ });
+ }
+}
+
+/**
+ * A finger-sized tap. Chromium moves a finger's click onto a nearby target's
+ * box (touch adjustment), so there the click lands away from the press.
+ * WebKit's driver taps a point.
+ */
+async function fingerTap(
+ page: Page,
+ browserName: string,
+ at: {x: number; y: number},
+): Promise<void> {
+ if (browserName !== 'chromium') {
+ const driver = await touchDriver(page);
+ await driver.tap(at);
+ return;
+ }
+ const cdp = await page.context().newCDPSession(page);
+ const finger = {x: at.x, y: at.y, radiusX: 11, radiusY: 11, force: 1};
+ await cdp.send('Input.dispatchTouchEvent', {
+ type: 'touchStart',
+ touchPoints: [finger],
+ });
+ await cdp.send('Input.dispatchTouchEvent', {
+ type: 'touchEnd',
+ touchPoints: [],
+ });
+ await cdp.detach();
+}
+
+/** Two frames: the band measures in the frame after a change. */
+async function nextFrames(page: Page): Promise<void> {
+ await page.evaluate(async () => {
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ });
+ });
+}
+
+/** The rows of the story's CheckboxList, as boxes. */
+async function checkboxListRows(page: Page): Promise<Rect[]> {
+ return page.locator(LIST_ROW).evaluateAll(rows =>
+ rows.map(row => {
+ const r = row.getBoundingClientRect();
+ return {x: r.x, y: r.y, width: r.width, height: r.height};
+ }),
+ );
+}
+
+const CHECKBOX_ROW = '#storybook-root [data-astryx-pressable]';
+const RADIO_ROW = '#storybook-root .astryx-item';
+const LIST_ROW = '#storybook-root li:has(input[type="checkbox"])';
+
+test.describe('selection controls under a finger', () => {
+ test('a labelled checkbox keeps its size under a finger, and a tap just outside its box toggles it (FR42)', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-checkboxinput--default');
+ const insets = await measuredInsets(page, CHECKBOX_ROW);
+ const finger = await checkboxGeometry(page);
+ // The band adds no layout: the same boxes without it.
+ expect(finger).toEqual(
+ await withoutLayer(page, CHECKBOX_ROW, async () =>
+ checkboxGeometry(page),
+ ),
+ );
+ // The input keeps its drawn size, centred on the box.
+ expect(finger.input.width).toBeLessThanOrEqual(24.5);
+ expect(
+ Math.abs(centre(finger.input).x - centre(finger.box).x),
+ ).toBeLessThanOrEqual(1);
+ // The row is shorter than the minimum, so the band takes it to 44 px.
+ expect(finger.row.height).toBeLessThan(SIZE);
+ expect(finger.row.height + insets.top + insets.bottom).toBeCloseTo(SIZE, 0);
+ const point = {
+ x: Math.round(centre(finger.box).x),
+ y: Math.floor(finger.row.y - insets.top / 2),
+ };
+ expect(point.y).toBeLessThan(finger.row.y);
+ expect(await ownsPoint(page, CHECKBOX_ROW, 0, point)).toBe(true);
+ const checkbox = page.getByRole('checkbox').first();
+ const before = await checkbox.isChecked();
+ const driver = await touchDriver(page);
+ await driver.tap(point);
+ await expect(checkbox).toBeChecked({checked: !before});
+ });
+
+ test('a tap that starts on the band toggles the checkbox even when its click lands on the row’s edge (FR42)', async ({
+ page,
+ browserName,
+ }) => {
+ await openStory(page, storybook(), 'core-checkboxinput--default');
+ const insets = await measuredInsets(page, CHECKBOX_ROW);
+ const {row, box} = await checkboxGeometry(page);
+ // 1 px inside the band's outer edge: 9 px above a 24 px row.
+ const point = {
+ x: Math.round(centre(box).x),
+ y: Math.ceil(row.y - insets.top + 1),
+ };
+ expect(point.y).toBeLessThan(row.y);
+ expect(await ownsPoint(page, CHECKBOX_ROW, 0, point)).toBe(true);
+ const checkbox = page.getByRole('checkbox').first();
+ const before = await checkbox.isChecked();
+ // Chromium's touch adjustment can move such a tap's click onto the row's
+ // top edge. That press and click, as the engine delivers them:
+ await page
+ .locator(CHECKBOX_ROW)
+ .first()
+ .evaluate((el, at) => {
+ const top = el.getBoundingClientRect().top;
+ el.dispatchEvent(
+ new PointerEvent('pointerdown', {
+ bubbles: true,
+ clientX: at.x,
+ clientY: at.y,
+ pointerType: 'touch',
+ isPrimary: true,
+ }),
+ );
+ el.dispatchEvent(
+ new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ clientX: at.x,
+ clientY: top,
+ detail: 1,
+ }),
+ );
+ }, point);
+ await expect(checkbox).toBeChecked({checked: !before});
+ // A real finger-sized tap at the same point toggles it back.
+ await fingerTap(page, browserName, point);
+ await expect(checkbox).toBeChecked({checked: before});
+ });
+
+ test('a checkbox row taller than 44 px keeps a hit area equal to its own box (FR42)', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-checkboxinput--default');
+ // First the short row's band, so the tall row's zero insets are a change.
+ expect(insetSum(await measuredInsets(page, CHECKBOX_ROW))).toBeGreaterThan(
+ 0,
+ );
+ await page.addStyleTag({
+ content: `${CHECKBOX_ROW} { min-height: 60px; }`,
+ });
+ await expect
+ .poll(async () => insetSum(await hitInsets(page, CHECKBOX_ROW)))
+ .toBe(0);
+ const {row, box} = await checkboxGeometry(page);
+ expect(row.height).toBeCloseTo(60, 0);
+ expect(row.width).toBeGreaterThan(SIZE);
+ const x = Math.round(centre(box).x);
+ // The row's own edge is its target; just past it is not.
+ expect(
+ await ownsPoint(page, CHECKBOX_ROW, 0, {x, y: Math.ceil(row.y + 1)}),
+ ).toBe(true);
+ expect(
+ await ownsPoint(page, CHECKBOX_ROW, 0, {x, y: Math.floor(row.y - 2)}),
+ ).toBe(false);
+ });
+
+ test('RadioList rows keep their geometry under a finger, and a tap in a row’s half of the gap selects it (FR42)', async ({
+ page,
+ }) => {
+ for (const orientation of ['vertical', 'horizontal']) {
+ await openStory(page, storybook(), 'core-radiolist--default', {
+ orientation,
+ });
+ await measuredInsets(page, RADIO_ROW);
+ const finger = await radioRows(page);
+ expect(finger.length).toBeGreaterThan(1);
+ expect(finger).toEqual(
+ await withoutLayer(page, RADIO_ROW, async () => radioRows(page)),
+ );
+ }
+ await openStory(page, storybook(), 'core-radiolist--default');
+ const [first, second] = await radioRows(page);
+ const gap = second.y - (first.y + first.height);
+ expect(gap).toBeGreaterThan(0);
+ const insets = await measuredInsets(page, RADIO_ROW, 1);
+ // The two bands meet in the middle of the gap and never overlap.
+ expect(insets.top).toBeGreaterThan(0);
+ expect(insets.top).toBeLessThanOrEqual(gap / 2 + 0.5);
+ const point = {
+ x: Math.round(second.x + second.width / 2),
+ y: Math.floor(second.y - insets.top / 2),
+ };
+ expect(await ownsPoint(page, RADIO_ROW, 1, point)).toBe(true);
+ // The other half of the gap belongs to the first row.
+ expect(
+ await ownsPoint(page, RADIO_ROW, 0, {
+ x: point.x,
+ y: Math.ceil(first.y + first.height + 0.5),
+ }),
+ ).toBe(true);
+ const driver = await touchDriver(page);
+ await driver.tap(point);
+ await expect(page.getByRole('radio').nth(1)).toBeChecked();
+ });
+
+ test('a CheckboxList’s rows keep their geometry under a finger at every density', async ({
+ page,
+ }) => {
+ for (const density of ['compact', 'balanced', 'spacious']) {
+ await openStory(page, storybook(), 'core-checkboxlist--default', {
+ density,
+ });
+ const finger = await checkboxListRows(page);
+ expect(finger.length).toBeGreaterThan(1);
+ expect(finger).toEqual(
+ await withoutLayer(page, LIST_ROW, async () => checkboxListRows(page)),
+ );
+ }
+ });
+
+ test('a MultiSelector option keeps its height under a finger', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-multiselector--default');
+ await page.getByRole('combobox').first().tap();
+ const option = page.getByRole('option').first();
+ await option.waitFor();
+ const marker = await option.evaluate(el => {
+ const input = el.querySelector('input[type="checkbox"]');
+ if (input == null) {
+ throw new Error('no checkbox in the option');
+ }
+ const r = input.getBoundingClientRect();
+ return {
+ option: el.getBoundingClientRect().height,
+ input: {width: r.width, height: r.height},
+ };
+ });
+ expect(marker.option).toBeLessThan(SIZE);
+ expect(marker.input.width).toBeLessThanOrEqual(24.5);
+ expect(marker.input.height).toBeLessThanOrEqual(24.5);
+ });
+
+ test('a mouse gets no band and keeps the drawn sizes (negative control)', async ({
+ browser,
+ }, testInfo) => {
+ await withMouse(browser, testInfo, async mousePage => {
+ await openStory(mousePage, storybook(), 'core-checkboxinput--default');
+ expect(
+ await mousePage.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const {input, box, row} = await checkboxGeometry(mousePage);
+ expect(input.width).toBeCloseTo(box.width, 0);
+ expect(row.height).toBeLessThan(SIZE);
+ await nextFrames(mousePage);
+ expect(await hitInsets(mousePage, CHECKBOX_ROW)).toEqual({
+ top: 0,
+ right: 0,
+ bottom: 0,
+ left: 0,
+ });
+ expect(
+ await mousePage
+ .locator(CHECKBOX_ROW)
+ .first()
+ .evaluate(el => getComputedStyle(el, '::after').content),
+ ).toMatch(/^(none|normal)$/);
+ await openStory(mousePage, storybook(), 'core-radiolist--default');
+ await nextFrames(mousePage);
+ expect(insetSum(await hitInsets(mousePage, RADIO_ROW))).toBe(0);
+ expect(
+ await mousePage
+ .locator(RADIO_ROW)
+ .first()
+ .evaluate(el => getComputedStyle(el, '::after').content),
+ ).toMatch(/^(none|normal)$/);
+ });
+ });
+});
diff --git a/packages/core/src/Indicator/touchTarget.test.tsx b/packages/core/src/Indicator/touchTarget.test.tsx
new file mode 100644
index 0000000000..9bb3611973
--- /dev/null
+++ b/packages/core/src/Indicator/touchTarget.test.tsx
@@ -0,0 +1,397 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file touchTarget.test.tsx
+ * @input CheckboxInput, RadioList and CheckboxList in jsdom, their injected
+ * styles, the shared hit band, and stubbed matchMedia, IntersectionObserver,
+ * requestAnimationFrame and element rects
+ * @output Checks the hit band under a coarse pointer. A labelled checkbox and
+ * an enabled radio option carry it and keep their size. It is at least
+ * 44 px and never smaller than the row. A tap on a checkbox's band toggles
+ * it. Composed rows keep their pitch.
+ * @position Unit layer; the browser layer is
+ * Indicator/__tests__/TouchTargets.interaction.browser.spec.ts
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {fireEvent, render, screen} from '@testing-library/react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {CheckboxInput} from '../CheckboxInput/CheckboxInput';
+import {CheckboxList} from '../CheckboxList/CheckboxList';
+import {CheckboxListItem} from '../CheckboxList/CheckboxListItem';
+import {RadioList} from '../RadioList/RadioList';
+import {RadioListItem} from '../RadioList/RadioListItem';
+import {HIT_INSET_PROPERTIES, resetHitAreaForTests} from '../utils/hitArea';
+import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';
+
+interface Declared {
+ media: string | null;
+ text: string;
+}
+
+/** Every injected rule naming one of the element's classes, with its media. */
+function declaredFor(el: Element): Declared[] {
+ const classes = el.className
+ .split(/\s+/)
+ .filter(Boolean)
+ .map(name => `.${name}`);
+ const out: Declared[] = [];
+ const walk = (rules: CSSRuleList, media: string | null) => {
+ for (const rule of Array.from(rules)) {
+ if (rule instanceof CSSMediaRule) {
+ walk(rule.cssRules, rule.media.mediaText);
+ } else if (
+ rule instanceof CSSStyleRule &&
+ classes.some(cls => rule.selectorText.startsWith(cls))
+ ) {
+ out.push({media, text: rule.style.cssText});
+ }
+ }
+ };
+ for (const sheet of Array.from(document.styleSheets)) {
+ walk(sheet.cssRules, null);
+ }
+ return out;
+}
+
+/** The value `property` takes on `el` under `media` (null: unconditionally). */
+function valueOf(
+ el: Element,
+ property: string,
+ media: string | null,
+): string | undefined {
+ for (const rule of declaredFor(el)) {
+ if (rule.media !== media) {
+ continue;
+ }
+ const match = new RegExp(`(?:^|;\\s*)${property}:\\s*([^;]+)`).exec(
+ rule.text,
+ );
+ if (match) {
+ return match[1].trim();
+ }
+ }
+ return undefined;
+}
+
+/** The block padding `el` declares under `media`, as [start, end]. */
+function paddingBlockOf(el: Element, media: string | null): string[] {
+ const both = valueOf(el, 'padding-block', media);
+ if (both != null) {
+ const [start, end = start] = both.split(/\s+(?![^(]*\))/);
+ return [start, end];
+ }
+ const start =
+ valueOf(el, 'padding-top', media) ??
+ valueOf(el, 'padding-block-start', media);
+ const end =
+ valueOf(el, 'padding-bottom', media) ??
+ valueOf(el, 'padding-block-end', media);
+ return start == null && end == null ? [] : [start ?? '', end ?? ''];
+}
+
+/** Whether `el` carries every class of the shared hit band. */
+function hasHitLayer(el: Element): boolean {
+ const layer = (stylex.props(touchHitAreaStyles.layer).className ?? '')
+ .split(/\s+/)
+ .filter(Boolean);
+ if (layer.length === 0) {
+ throw new Error('the hit band has no classes');
+ }
+ return layer.every(name => el.classList.contains(name));
+}
+
+function closestOrThrow(el: Element, selector: string): HTMLElement {
+ const found = el.closest(selector);
+ if (!(found instanceof HTMLElement)) {
+ throw new Error(`no ${selector} around the control`);
+ }
+ return found;
+}
+
+const TOUCH = '(pointer: coarse)';
+
+describe('CheckboxInput under a finger', () => {
+ it('keeps a labelled checkbox’s row at its size and gives it the hit band (FR42)', () => {
+ render(
+ <CheckboxInput label="Accept terms" value={false} onChange={() => {}} />,
+ );
+ const row = closestOrThrow(
+ screen.getByRole('checkbox', {name: 'Accept terms'}),
+ '[data-astryx-pressable]',
+ );
+ expect(valueOf(row, 'min-height', TOUCH)).toBeUndefined();
+ expect(valueOf(row, 'min-height', null)).toBeUndefined();
+ expect(hasHitLayer(row)).toBe(true);
+ // The row holds the band only under a finger; a mouse sees no change.
+ expect(valueOf(row, 'position', TOUCH)).toBe('relative');
+ expect(valueOf(row, 'position', null)).toBeUndefined();
+ });
+
+ it('gives a label-hidden, disabled or read-only checkbox no hit band', () => {
+ render(
+ <>
+ <CheckboxInput
+ label="Marker"
+ isLabelHidden
+ value={false}
+ onChange={() => {}}
+ />
+ <CheckboxInput
+ label="Disabled"
+ isDisabled
+ value={false}
+ onChange={() => {}}
+ />
+ <CheckboxInput
+ label="Read-only"
+ isReadOnly
+ value={false}
+ onChange={() => {}}
+ />
+ </>,
+ );
+ for (const name of ['Marker', 'Disabled', 'Read-only']) {
+ const input = screen.getByRole('checkbox', {name});
+ const row =
+ input.closest('[data-astryx-pressable]') ?? input.parentElement;
+ if (row == null) {
+ throw new Error(`no row for ${name}`);
+ }
+ expect(hasHitLayer(row), name).toBe(false);
+ }
+ });
+
+ it('toggles on a press that begins on the band, even when its click lands on the row’s edge, and not on a press inside the row or a click from code', () => {
+ const onChange = vi.fn();
+ render(
+ <CheckboxInput label="Accept terms" value={false} onChange={onChange} />,
+ );
+ const row = closestOrThrow(
+ screen.getByRole('checkbox', {name: 'Accept terms'}),
+ '[data-astryx-pressable]',
+ );
+ vi.spyOn(row, 'getBoundingClientRect').mockReturnValue(
+ DOMRect.fromRect({x: 10, y: 10, width: 200, height: 24}),
+ );
+ // A press inside the row's own box (between box and label): unchanged.
+ fireEvent.pointerDown(row, {clientX: 30, clientY: 20});
+ fireEvent.click(row, {clientX: 30, clientY: 20, detail: 1});
+ // A click from code on the band, with no press: unchanged.
+ fireEvent.click(row, {clientX: 30, clientY: 5});
+ expect(onChange).not.toHaveBeenCalled();
+ // A press on the band whose click the browser moved onto the row's top.
+ fireEvent.pointerDown(row, {clientX: 30, clientY: 2});
+ fireEvent.click(row, {clientX: 30, clientY: 10, detail: 1});
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange.mock.calls[0][0]).toBe(true);
+ });
+});
+
+describe('the hit band is at least 44 px and never smaller than the row (FR42)', () => {
+ let frames: (() => void)[];
+ let intersection: ((entries: IntersectionObserverEntry[]) => void) | null;
+
+ beforeEach(() => {
+ frames = [];
+ intersection = null;
+ vi.stubGlobal('matchMedia', (media: string) => ({
+ media,
+ matches: media === TOUCH,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ }));
+ vi.stubGlobal(
+ 'IntersectionObserver',
+ class {
+ constructor(callback: (entries: IntersectionObserverEntry[]) => void) {
+ intersection = callback;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ vi.stubGlobal('requestAnimationFrame', (run: () => void) => {
+ frames.push(run);
+ return frames.length;
+ });
+ vi.stubGlobal('cancelAnimationFrame', () => {});
+ });
+
+ afterEach(() => {
+ resetHitAreaForTests();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ /** Lays the row out at `height` px, shows it, and runs the next frame. */
+ function measure(row: HTMLElement, height: number): void {
+ vi.spyOn(row, 'getBoundingClientRect').mockReturnValue(
+ DOMRect.fromRect({x: 100, y: 100, width: 200, height}),
+ );
+ intersection?.([
+ {
+ target: row,
+ isIntersecting: true,
+ } as unknown as IntersectionObserverEntry,
+ ]);
+ const due = frames;
+ frames = [];
+ due.forEach(run => run());
+ }
+
+ /** The row's target, px: its box grown by the band's written insets. */
+ function target(row: HTMLElement, height: number) {
+ const inset = (side: keyof typeof HIT_INSET_PROPERTIES) =>
+ parseFloat(row.style.getPropertyValue(HIT_INSET_PROPERTIES[side])) || 0;
+ return {
+ width: 200 + inset('left') + inset('right'),
+ height: height + inset('top') + inset('bottom'),
+ hasBand: hasHitLayer(row),
+ };
+ }
+
+ it('grows a 24 px checkbox row to 44 px, and leaves a 60 px one at its own box', () => {
+ for (const [height, expected] of [
+ [24, 44],
+ [60, 60],
+ ] as const) {
+ const {unmount} = render(
+ <CheckboxInput
+ label={`Accept ${height}`}
+ value={false}
+ onChange={() => {}}
+ />,
+ );
+ const row = closestOrThrow(
+ screen.getByRole('checkbox', {name: `Accept ${height}`}),
+ '[data-astryx-pressable]',
+ );
+ measure(row, height);
+ expect(target(row, height), `${height} px row`).toEqual({
+ width: 200,
+ height: expected,
+ hasBand: true,
+ });
+ unmount();
+ resetHitAreaForTests();
+ }
+ });
+
+ 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],
+ [60, 60],
+ ] as const) {
+ const {unmount} = render(
+ <RadioList label={`Plan ${height}`} value="a" onChange={() => {}}>
+ <RadioListItem label={`Option ${height}`} value="a" />
+ </RadioList>,
+ );
+ const row = closestOrThrow(
+ screen.getByRole('radio', {name: `Option ${height}`}),
+ '.astryx-item',
+ );
+ measure(row, height);
+ expect(target(row, height), `${height} px option`).toEqual({
+ width: 200,
+ height: expected,
+ hasBand: true,
+ });
+ unmount();
+ resetHitAreaForTests();
+ }
+ });
+});
+
+describe('CheckboxList under a finger', () => {
+ function rowOf(name: string): Element {
+ return closestOrThrow(screen.getByRole('checkbox', {name}), 'li');
+ }
+
+ it('sets no touch row height or padding at any density', () => {
+ for (const density of ['compact', 'balanced', 'spacious'] as const) {
+ const {unmount} = render(
+ <CheckboxList
+ label={`Notifications ${density}`}
+ value={['email']}
+ onChange={() => {}}
+ density={density}>
+ <CheckboxListItem
+ label={`Email ${density}`}
+ value="email"
+ description="Weekly digest"
+ />
+ <CheckboxListItem label={`SMS ${density}`} value="sms" />
+ </CheckboxList>,
+ );
+ for (const name of [`Email ${density}`, `SMS ${density}`]) {
+ expect(valueOf(rowOf(name), 'min-height', TOUCH), name).toBeUndefined();
+ expect(paddingBlockOf(rowOf(name), TOUCH), name).toEqual([]);
+ }
+ unmount();
+ }
+ });
+
+ it('keeps a read-only compact list at its pitch, as Markdown’s task list', () => {
+ render(
+ <CheckboxList
+ label="Tasks"
+ isLabelHidden
+ value={['done']}
+ onChange={() => {}}
+ isReadOnly
+ density="compact">
+ <CheckboxListItem label="Done" value="done" />
+ <CheckboxListItem label="Open" value="open" />
+ </CheckboxList>,
+ );
+ expect(valueOf(rowOf('Open'), 'min-height', TOUCH)).toBeUndefined();
+ expect(paddingBlockOf(rowOf('Open'), TOUCH)).toEqual([]);
+ });
+});
+
+describe('RadioList under a finger', () => {
+ it('keeps each row’s size and the list’s gap: no touch height, padding or gap (FR42)', () => {
+ for (const orientation of ['vertical', 'horizontal'] as const) {
+ const {unmount} = render(
+ <RadioList
+ label={`Plan ${orientation}`}
+ value="a"
+ orientation={orientation}
+ onChange={() => {}}>
+ <RadioListItem label={`Option A ${orientation}`} value="a" />
+ <RadioListItem label={`Option B ${orientation}`} value="b" />
+ </RadioList>,
+ );
+ const row = closestOrThrow(
+ screen.getByRole('radio', {name: `Option B ${orientation}`}),
+ '.astryx-item',
+ );
+ expect(valueOf(row, 'min-height', TOUCH)).toBeUndefined();
+ expect(paddingBlockOf(row, TOUCH)).toEqual([]);
+ const touchGaps = declaredFor(screen.getByRole('radiogroup')).filter(
+ rule =>
+ rule.media?.startsWith(TOUCH) === true &&
+ /(?:^|;\s*)(?:row-)?gap:/.test(rule.text),
+ );
+ expect(touchGaps).toEqual([]);
+ unmount();
+ }
+ });
+
+ it('gives each enabled option the hit band and a disabled one none (FR42)', () => {
+ render(
+ <RadioList label="Plan" value="a" onChange={() => {}}>
+ <RadioListItem label="Option A" value="a" />
+ <RadioListItem label="Option B" value="b" isDisabled />
+ </RadioList>,
+ );
+ const rowOf = (name: string) =>
+ closestOrThrow(screen.getByRole('radio', {name}), '.astryx-item');
+ expect(hasHitLayer(rowOf('Option A'))).toBe(true);
+ expect(hasHitLayer(rowOf('Option B'))).toBe(false);
+ });
+});
diff --git a/packages/core/src/RadioList/RadioListItem.doc.mjs b/packages/core/src/RadioList/RadioListItem.doc.mjs
index f784cb28d3..be01cb504a 100644
--- a/packages/core/src/RadioList/RadioListItem.doc.mjs
+++ b/packages/core/src/RadioList/RadioListItem.doc.mjs
@@ -8,7 +8,7 @@ export const docs = {
displayName: 'Radio List Item',
isHiddenFromOverview: true,
description:
- 'Individual radio item with label, description, and content slots.',
+ 'Individual radio item with label, description, and content slots. Under a coarse pointer an enabled option’s target grows toward 44 px through an invisible hit area. It never shrinks below the row and stops at half the gap to a closer neighbour; the row keeps its size. That hit area is the row’s `::after`, so decorate a row with a child.',
// RadioListItem requires RadioList context; wrap it so the preview doesn't throw.
playground: {
defaults: {value: 'option-1', label: 'Option'},
@@ -97,7 +97,8 @@ export const docsZh = {
name: 'RadioListItem',
isHiddenFromOverview: true,
displayName: 'Radio List Item',
- description: '单个单选选项,包含标签、描述和内容插槽。',
+ description:
+ '单个单选选项,包含标签、描述和内容插槽。在粗指针(触摸)下,已启用选项的目标通过不可见的点击区域向 44 px 扩展。它不小于所在行,与相邻控件较近时止于间距的一半;行尺寸不变。该点击区域是行的 `::after`,因此请用子元素装饰行。',
props: [
{
name: 'label',
diff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsx
index 6b22daceee..8373b4f458 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, useId, useRef, type ReactNode} from 'react';
+import React, {use, useCallback, useId, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
@@ -32,6 +32,9 @@ import {rtlStyles} from '../utils/rtlStyles';
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 {touchHitAreaStyles} from '../utils/touchHitArea.stylex';
import {useIndicator} from '../Indicator/useIndicator';
import {Item, type ItemAlign} from '../Item/Item';
import {themeProps} from '../utils/themeProps';
@@ -305,6 +308,21 @@ export function RadioListItem({
// `<label htmlFor>` would double-fire under delegation.
const radioRef = useRef<HTMLInputElement>(null);
+ // 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],
+ );
+ const mergedRowRef = useMergedRefs(ref, watchRowHitArea);
+
const radioCircle = (
<div
{...stylex.props(
@@ -387,7 +405,7 @@ export function RadioListItem({
return (
<Item
- ref={ref}
+ ref={mergedRowRef}
{...(isDisabled ? undefined : pressable)}
startContent={mediaContent}
// Delegate row-surface clicks (label text, description, and the empty
@@ -419,6 +437,7 @@ export function RadioListItem({
// still overrides it from the higher `astryx-theme` layer.
rowStyles.root,
!isDisabled && rowStyles.press,
+ !isDisabled && touchHitAreaStyles.layer,
xstyle,
] as StyleXStyles
}
diff --git a/packages/core/src/utils/touchHitArea.stylex.ts b/packages/core/src/utils/touchHitArea.stylex.ts
new file mode 100644
index 0000000000..2eb4461fe4
--- /dev/null
+++ b/packages/core/src/utils/touchHitArea.stylex.ts
@@ -0,0 +1,41 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file touchHitArea.stylex.ts
+ * @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
+ *
+ * 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.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+
+// StyleX reads these at build time, so they are spelled out.
+const TOUCH = '@media (pointer: coarse)';
+// The insets are measured in the viewport, so the sides are physical.
+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)';
+
+export const touchHitAreaStyles = stylex.create({
+ layer: {
+ '::after': {
+ content: {default: null, [TOUCH]: '""'},
+ position: {default: null, [TOUCH]: 'absolute'},
+ inset: {
+ default: null,
+ [TOUCH]: `calc(${TOP} * -1) calc(${RIGHT} * -1) calc(${BOTTOM} * -1) calc(${LEFT} * -1)`,
+ },
+ // The outer rectangle, then the host's box as an even-odd hole.
+ clipPath: {
+ default: null,
+ [TOUCH]: `polygon(evenodd, 0 0, 100% 0, 100% 100%, 0 100%, 0 0, ${LEFT} ${TOP}, calc(100% - ${RIGHT}) ${TOP}, calc(100% - ${RIGHT}) calc(100% - ${BOTTOM}), ${LEFT} calc(100% - ${BOTTOM}), ${LEFT} ${TOP})`,
+ },
+ },
+ },
+});