Skip to content

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

TypeScript

fix(Button): under a finger, a Button's target grows toward 44 px through the shared touch band (#10216)

Cindy Zhange10347c4e930
diff --git a/.changeset/button-touch-band.md b/.changeset/button-touch-band.md
new file mode 100644
index 0000000000..d14916cb49
--- /dev/null
+++ b/.changeset/button-touch-band.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Under a finger, a `Button` or `IconButton` is easier to hit. Its touch target grows toward 44 px through an invisible band, as far as its neighbors leave room, and its box doesn't change. A disabled button, or a busy one that can't be interrupted, gets no band, and a button in a `ButtonGroup` uses the group's band. Input clear buttons now use the same band in place of their fixed 24 px overlay, and in Safari a tap on that band clears the field. Nothing changes under a mouse. Swizzling a ListItem, CheckboxInput, RadioListItem, InfoTip or SegmentedControl no longer leaves an import of the touch band's styles that can't resolve.
+
+@cixzhang
diff --git a/apps/storybook/stories/Button.stories.tsx b/apps/storybook/stories/Button.stories.tsx
index a9617af6e2..b3e73478df 100644
--- a/apps/storybook/stories/Button.stories.tsx
+++ b/apps/storybook/stories/Button.stories.tsx
@@ -480,3 +480,84 @@ export const Elevations: Story = {
</div>
),
};
+
+export const TouchTargets: Story = {
+ name: 'Touch targets',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'A dense toolbar, 4 px apart, a pair offset 4 px on both axes, and a field with a clear button. Under a coarse pointer each button’s invisible hit area grows toward 44 px, but stops halfway to a neighbor, so a tap lands on the button nearest to it and no box changes size.',
+ },
+ },
+ },
+ render: () => {
+ const [taps, setTaps] = useState({
+ bold: 0,
+ italic: 0,
+ underline: 0,
+ undo: 0,
+ redo: 0,
+ });
+ const [query, setQuery] = useState('quarterly report');
+ const count = (key: keyof typeof taps) => () =>
+ setTaps(current => ({...current, [key]: current[key] + 1}));
+ return (
+ <VStack gap={3} hAlign="start">
+ <HStack gap={1}>
+ <IconButton
+ label="Bold"
+ size="sm"
+ variant="ghost"
+ icon={<Icon icon={Cog6ToothIcon} />}
+ onClick={count('bold')}
+ />
+ <IconButton
+ label="Italic"
+ size="sm"
+ variant="ghost"
+ icon={<Icon icon={TrashIcon} />}
+ onClick={count('italic')}
+ />
+ <IconButton
+ label="Underline"
+ size="sm"
+ variant="ghost"
+ icon={<Icon icon={Cog6ToothIcon} />}
+ onClick={count('underline')}
+ />
+ </HStack>
+ <output aria-label="Taps">
+ Bold {taps.bold}, Italic {taps.italic}, Underline {taps.underline}
+ </output>
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'auto auto',
+ gap: 4,
+ }}>
+ <IconButton
+ label="Undo"
+ size="sm"
+ variant="ghost"
+ icon={<Icon icon={Cog6ToothIcon} />}
+ onClick={count('undo')}
+ />
+ <span />
+ <span />
+ <IconButton
+ label="Redo"
+ size="sm"
+ variant="ghost"
+ icon={<Icon icon={TrashIcon} />}
+ onClick={count('redo')}
+ />
+ </div>
+ <output aria-label="Offset taps">
+ Undo {taps.undo}, Redo {taps.redo}
+ </output>
+ <TextInput label="Search" value={query} onChange={setQuery} hasClear />
+ </VStack>
+ );
+ },
+};
diff --git a/docs/specs/components/Button/Button.spec.md b/docs/specs/components/Button/Button.spec.md
index e955ed99ed..ff1bbe18c4 100644
--- a/docs/specs/components/Button/Button.spec.md
+++ b/docs/specs/components/Button/Button.spec.md
@@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, layout, theming, accessibility]
verified_by:
[
packages/core/src/Button/Button.test.tsx,
+ packages/core/src/Button/Button.hitArea.test.tsx,
packages/core/src/ButtonGroup/ButtonGroup.test.tsx,
packages/core/src/Button/__tests__/Button.a11y.test.tsx,
packages/core/src/Button/__tests__/Button.a11y.chromium.spec.ts,
@@ -79,6 +80,9 @@ Consumer migration instructions belong in consumer docs and release notes.
interruptible opt-out.
- Pending presentation: Spinner overlay, hidden content, `aria-busy`, and the
loading announcement region.
+- The touch band under a coarse pointer (`spec:AST-094` FR42), carried by the
+ content wrapper's `::after`; the root's `::before` and `::after` stay as FR15
+ and callers use them.
- Busy-only and disabled operability guards.
- Link mode's rendering choice and its disabled fallback.
- Standalone resting elevation and the `button` theme target.
@@ -231,8 +235,9 @@ record governs Button; exact paint stays in code and visual evidence.
The root carries the one `button` target (FR14). Icon, Label, and End content
have no target of their own and take color from `button`; the Spinner is a
-Spinner instance with the inherited shade. The consumer anatomy names no root
-part, so this record carries no anatomy-theming map.
+Spinner instance with the inherited shade. The touch band has no target. The
+consumer anatomy names no root part, so this record carries no
+anatomy-theming map.
## Family and system relationships
@@ -272,6 +277,7 @@ part, so this record carries no anatomy-theming map.
| FR15 | `Button.test.tsx` touch pressed-state suite | Touch press on and fading | Losing the touch press arm or its release fade fails. | `audit:Button/behavior` |
| FR15 (disabled paint) | `pressFeedback.test.ts` "paints nothing on a disabled surface, and does not light the row around it" for the touch press. Evidence gap: no test of the hover and pressed overlays or the mouse scale on a Button exposed as disabled | Native disabled; `aria-disabled` | A disabled surface that takes the touch press fails. | `audit:Button/behavior` |
| FR15 (reduced motion) | `ReducedMotionPress.a11y.chromium.spec.ts` ("a pressed button never scales under reduced motion, with a mouse or a finger (DR1)") | Mouse press; touch press | A computed transform other than `none` or `scale(1)` during the press. | `audit:Button/behavior` |
+| `spec:AST-094` FR42 | `Button.hitArea.test.tsx`: a standalone and a link Button take the touch band on their content wrapper, and a caller's `::after` stays on the button; a disabled, busy-only or grouped Button takes none | standalone; link; caller `::after`; disabled; busy-only; grouped | A Button without the band, or a disabled, busy-only or grouped Button with its own, fails. | `audit:Button/behavior` |
| FR15 (hover and mouse scale) | Evidence gap: no test asserts the hover overlay or the 0.98 mouse-press scale | Hover; mouse press, standalone and grouped | — | `audit:Button/behavior` |
| FR16 | `edgeCompensation.test.tsx` Button data-attribute suite | Ghost and primary | A ghost Button without the marker, or a primary Button with it, fails. | `audit:Button/layout` |
| FR17 | `Button.test.tsx` ref suites and the caller `aria-disabled`/`aria-busy` case | Initial render and rerender; caller `aria-busy` and `aria-disabled` | A dropped or detached ref, or a dropped caller `aria-busy` or `aria-disabled`, fails. Evidence gap: no test asserts that a caller `aria-disabled` leaves the Button operable. | `audit:Button/behavior` |
diff --git a/docs/specs/components/Field/Field.spec.md b/docs/specs/components/Field/Field.spec.md
index 1386b75b0d..6a80f42450 100644
--- a/docs/specs/components/Field/Field.spec.md
+++ b/docs/specs/components/Field/Field.spec.md
@@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, layout, theming, accessibility]
verified_by:
[
packages/core/src/Field/Field.test.tsx,
+ packages/core/src/Button/__tests__/ButtonHitArea.interaction.browser.spec.ts,
packages/core/src/FormLayout/FormLayout.test.tsx,
packages/core/src/theme/themingTargets.test.ts,
packages/core/src/docPropLiterals.test.ts,
@@ -202,6 +203,7 @@ The ordinary description remains stable consumer anatomy without a Field-owned t
| FR8 | `Field.test.tsx` attached-layer and local-stacking cases | Attached, no status, custom control | Removing isolation or ranking the root outside its parent fails. | `audit:Field/code-health` |
| FR9 | `Field.test.tsx` attached-layer case for a custom control | Custom control with an attached status | The test pins the current attached default, so it changes when the FR9 gap closes. | `audit:Field/behavior` |
| PR1 | Evidence gap: no test asserts the absence of per-field global resources | — | — | `audit:Field/code-health` |
+| `spec:AST-094` FR42 | `ButtonHitArea.interaction.browser.spec.ts` clear-band and clearable-Selector chevron cases | A text input's clear button beside its text; a clearable Selector's beside its chevron | A clear band past half the gap to the text or to the field's next part, or a chevron tap that clears, fails. | `audit:Field/behavior` |
| Theming anatomy | `scripts/check-knowledge.mjs`; `themingTargets.test.ts` | Field root, label, description, caller control, status, shared input affordances, indicator, tooltip | Invalid dispositions, or a rendered class absent from the documented targets, fails. | `audit:Field/theming` |
| Documentation projection | `docPropLiterals.test.ts`; `docPropReferences.test.ts` | Status placements, `labelIcon`, and other documented props | A documented literal or prop reference that drifts from the source type fails. | `audit:Field/docs` |
| RTL applicability | `apps/storybook/rtl-audit/verified-not-applicable.json` entry for `core/Field` | Checked-in Field stories | A story that gains directional placement or behavior makes the not-applicable entry stale. | `audit:Field/i18n-rtl` |
diff --git a/packages/core/package.json b/packages/core/package.json
index 0cadbdb5f5..44f49b17e8 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -834,6 +834,11 @@
"types": "./dist/internal/indicatorPress.stylex.d.ts",
"default": "./dist/internal/indicatorPress.stylex.js"
},
+ "./internal/touchHitArea.stylex": {
+ "source": "./src/internal/touchHitArea.stylex.ts",
+ "types": "./dist/internal/touchHitArea.stylex.d.ts",
+ "default": "./dist/internal/touchHitArea.stylex.js"
+ },
"./internal/touch": {
"source": "./src/internal/touch.ts",
"types": "./dist/internal/touch.d.ts",
diff --git a/packages/core/src/Button/Button.hitArea.test.tsx b/packages/core/src/Button/Button.hitArea.test.tsx
new file mode 100644
index 0000000000..1aac569db2
--- /dev/null
+++ b/packages/core/src/Button/Button.hitArea.test.tsx
@@ -0,0 +1,133 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Button.hitArea.test.tsx
+ * @input Button, ButtonGroup, and the shared hit area (mocked)
+ * @output Unit coverage that a standalone Button takes the shared touch band,
+ * on its content wrapper, which leaves a caller's ::after alone, and that a
+ * grouped, disabled or busy-only Button takes none
+ * @position Button's FR42 touch-target evidence beside Button.test.tsx
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {describe, it, expect, vi} from 'vitest';
+import {act, render, screen} from '@testing-library/react';
+import type * as HitAreaModule from '../utils/hitArea';
+import type {HitInsets} from '../utils/hitArea';
+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';
+import {ButtonGroup} from '../ButtonGroup/ButtonGroup';
+import {Button} from './Button';
+
+// On a coarse pointer, the shared hit area measures neighbours in a real
+// layout. Here it reports what it was asked to watch, and each test answers
+// for it.
+const hitAreaWatches = vi.hoisted(
+ () => [] as {element: Element; onInsets: (insets: HitInsets) => void}[],
+);
+vi.mock('../utils/hitArea', async importOriginal => ({
+ ...(await importOriginal<typeof HitAreaModule>()),
+ watchHitArea: (element: Element, onInsets: (insets: HitInsets) => void) => {
+ const watch = {element, onInsets};
+ hitAreaWatches.push(watch);
+ return () => {
+ hitAreaWatches.splice(hitAreaWatches.indexOf(watch), 1);
+ };
+ },
+}));
+
+const bandClasses = (stylex.props(touchHitAreaStyles.layer).className ?? '')
+ .split(/\s+/)
+ .filter(Boolean);
+
+function isWatched(element: Element): boolean {
+ return hitAreaWatches.some(entry => entry.element === element);
+}
+
+/** The element inside the button that carries the band, if any. */
+function bandElementOf(button: Element): Element | undefined {
+ return [...button.querySelectorAll('*')].find(element =>
+ bandClasses.every(bandClass => element.classList.contains(bandClass)),
+ );
+}
+
+const callerStyles = stylex.create({
+ dot: {
+ '::after': {
+ content: '""',
+ position: 'absolute',
+ top: '4px',
+ insetInlineEnd: '4px',
+ },
+ },
+});
+
+describe('Button touch target (AST-094 FR42)', () => {
+ it('grows a standalone button toward 44 px as far as the shared hit area allows', () => {
+ render(<Button label="Save" />);
+ const button = screen.getByRole('button', {name: 'Save'});
+ expect(bandClasses.length).toBeGreaterThan(0);
+ const band = bandElementOf(button);
+ expect(band).toBeDefined();
+ expect(button).toHaveAccessibleName('Save');
+ const watch = hitAreaWatches.find(entry => entry.element === button);
+ expect(watch).toBeDefined();
+ act(() => watch?.onInsets({top: 6, right: 0, bottom: 6, left: 0}));
+ expect(button.style.getPropertyValue('--astryx-hit-inset-top')).toBe('6px');
+ });
+
+ it("leaves a caller's ::after decoration on the button itself, and the band on its content wrapper", () => {
+ render(<Button label="Inbox" xstyle={callerStyles.dot} />);
+ const button = screen.getByRole('button', {name: 'Inbox'});
+ const callerClasses = (stylex.props(callerStyles.dot).className ?? '')
+ .split(/\s+/)
+ .filter(Boolean);
+ expect(callerClasses.length).toBeGreaterThan(0);
+ for (const callerClass of callerClasses) {
+ expect(button).toHaveClass(callerClass);
+ }
+ for (const bandClass of bandClasses) {
+ expect(button).not.toHaveClass(bandClass);
+ }
+ expect(bandElementOf(button)).toBeDefined();
+ expect(button).toHaveAccessibleName('Inbox');
+ });
+
+ it('gives a link button the same band', () => {
+ render(<Button label="Docs" href="/docs" />);
+ expect(isWatched(screen.getByRole('link', {name: 'Docs'}))).toBe(true);
+ });
+
+ it('gives a disabled or busy-only button no band, since it takes no tap', () => {
+ render(
+ <>
+ <Button label="Delete" isDisabled />
+ <Button label="Sending" isLoading />
+ </>,
+ );
+ const disabled = screen.getByRole('button', {name: 'Delete'});
+ const busy = screen.getByRole('button', {name: 'Sending'});
+ expect(isWatched(disabled)).toBe(false);
+ expect(isWatched(busy)).toBe(false);
+ expect(bandElementOf(disabled)).toBeUndefined();
+ expect(bandElementOf(busy)).toBeUndefined();
+ });
+
+ it('keeps the band on a busy button that can still be interrupted', () => {
+ render(<Button label="Stop upload" isLoading isInterruptible />);
+ expect(isWatched(screen.getByRole('button', {name: 'Stop upload'}))).toBe(
+ true,
+ );
+ });
+
+ it('leaves a grouped button to the group: it draws no band of its own', () => {
+ render(
+ <ButtonGroup label="Actions">
+ <Button label="Cut" />
+ <Button label="Copy" />
+ </ButtonGroup>,
+ );
+ const cut = screen.getByRole('button', {name: 'Cut'});
+ expect(isWatched(cut)).toBe(false);
+ expect(bandElementOf(cut)).toBeUndefined();
+ });
+});
diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsx
index f06edfc73f..d4d36e25d2 100644
--- a/packages/core/src/Button/Button.tsx
+++ b/packages/core/src/Button/Button.tsx
@@ -65,6 +65,9 @@ import {
} from '../InputGroup/groupStyles';
import {mergeProps} from '../utils/mergeProps';
import {useMergedRefs} from '../hooks/useMergedRefs';
+import {useTouchHitArea} from '../utils/touchHitArea';
+import {ButtonHitAreaContext} from './buttonHitArea';
+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';
import {useLinkComponent} from '../Link/useLinkComponent';
import type {LinkComponentType} from '../Link/types';
import {themeProps} from '../utils/themeProps';
@@ -749,6 +752,10 @@ export function Button({
const isBusyOnlyDisabled =
!isTrueDisabled && isLoadingState && !isInterruptible;
const buttonDisabled = isTrueDisabled || isBusyOnlyDisabled;
+ // The group draws one band for all its members.
+ // A disabled or busy-only button takes no tap.
+ const hasHitArea = buttonGroup == null && !buttonDisabled;
+ const hitAreaRef = useTouchHitArea(hasHitArea, use(ButtonHitAreaContext));
// isIconOnly prop is the source of truth for icon-only rendering.
// When false (default), label is always rendered as visible text.
@@ -893,6 +900,10 @@ export function Button({
<span
{...stylex.props(
styles.contentWrapper,
+ // The content wrapper's `::after` carries the touch band, so the
+ // button's own `::before` (the touch press) and `::after` (a
+ // caller's decoration) stay as they are.
+ hasHitArea && touchHitAreaStyles.layer,
isLoadingState &&
(delaySpinner
? loadingStyles.hiddenContentDelayed
@@ -968,6 +979,7 @@ export function Button({
const mergedButtonRef = useMergedRefs(
ref,
tooltip != null ? tooltipHook.ref : undefined,
+ hitAreaRef,
);
let element: ReactNode;
diff --git a/packages/core/src/Button/__tests__/ButtonHitArea.interaction.browser.spec.ts b/packages/core/src/Button/__tests__/ButtonHitArea.interaction.browser.spec.ts
new file mode 100644
index 0000000000..f4cba06b22
--- /dev/null
+++ b/packages/core/src/Button/__tests__/ButtonHitArea.interaction.browser.spec.ts
@@ -0,0 +1,225 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ButtonHitArea.interaction.browser.spec.ts
+ * @input The built "Touch targets" Button story and real touch input on a
+ * phone-sized touch context
+ * @output Browser proofs that a Button's touch target grows toward 44 px
+ * through an invisible band, stops halfway to a neighbor, never takes a
+ * neighbor's tap, and changes no box (spec:AST-094 FR42)
+ * @position Browser layer of Button's hit band; the band itself is
+ * internal/touchHitArea.stylex.ts
+ */
+
+import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
+import {
+ openStory,
+ tap,
+ touchDriver,
+ withStorybook,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+const STORY = 'core-button--touch-targets';
+// The clear button's name is the field's label in the default locale.
+const CLEAR = /^Clear/;
+
+interface Box {
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+}
+
+async function tapAt(
+ driver: TouchDriver,
+ at: {x: number; y: number},
+): Promise<void> {
+ if (driver.engine === 'webkit') {
+ await driver.tap(at);
+ } else {
+ await driver.play(tap(at, {holdMs: 50}));
+ }
+}
+
+function buttonNamed(page: Page, name: string | RegExp) {
+ return page
+ .locator('#storybook-root')
+ .getByRole('button', {name, exact: true});
+}
+
+/** Waits until utils/hitArea has written the insets of every named button. */
+async function waitForHitArea(
+ page: Page,
+ names: (string | RegExp)[],
+): Promise<void> {
+ for (const name of names) {
+ await expect
+ .poll(async () =>
+ buttonNamed(page, name).evaluate(button =>
+ (button as HTMLElement).style.getPropertyValue(
+ '--astryx-hit-inset-top',
+ ),
+ ),
+ )
+ .not.toBe('');
+ }
+}
+
+async function measure(page: Page, name: string | RegExp) {
+ return buttonNamed(page, name).evaluate(element => {
+ const button = element as HTMLElement;
+ const r = button.getBoundingClientRect();
+ const inset = (side: string) =>
+ Number.parseFloat(
+ button.style.getPropertyValue(`--astryx-hit-inset-${side}`) || '0',
+ );
+ return {
+ box: {left: r.left, top: r.top, right: r.right, bottom: r.bottom},
+ insets: {
+ top: inset('top'),
+ right: inset('right'),
+ bottom: inset('bottom'),
+ left: inset('left'),
+ },
+ };
+ });
+}
+
+const middleY = (box: Box) => (box.top + box.bottom) / 2;
+
+test.describe('Button touch target (spec:AST-094 FR42), under a finger', () => {
+ test('a toolbar button’s band grows toward 44 px, stops at half the gap, and grows no box', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), STORY);
+ await waitForHitArea(page, ['Bold', 'Italic', 'Underline']);
+ const bold = await measure(page, 'Bold');
+ const italic = await measure(page, 'Italic');
+ const height = italic.box.bottom - italic.box.top;
+ expect(height).toBeLessThan(44);
+ const gap = italic.box.left - bold.box.right;
+ expect(italic.insets.left).toBeLessThanOrEqual(gap / 2 + 0.5);
+ expect(bold.insets.right).toBeLessThanOrEqual(gap / 2 + 0.5);
+ expect(italic.insets.top).toBeGreaterThan(0);
+ });
+
+ test('a tap in the gap goes to the nearer button, never its neighbor', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), STORY);
+ await waitForHitArea(page, ['Bold', 'Italic', 'Underline']);
+ const driver = await touchDriver(page);
+ const bold = await measure(page, 'Bold');
+ const italic = await measure(page, 'Italic');
+ const taps = page.locator('#storybook-root output[aria-label="Taps"]');
+ const y = middleY(italic.box);
+ await tapAt(driver, {x: italic.box.left - 0.75, y});
+ await expect(taps).toHaveText('Bold 0, Italic 1, Underline 0');
+ await tapAt(driver, {x: bold.box.right + 0.75, y});
+ await expect(taps).toHaveText('Bold 1, Italic 1, Underline 0');
+ await tapAt(driver, {
+ x: (italic.box.left + italic.box.right) / 2,
+ y: italic.box.top - italic.insets.top + 1,
+ });
+ await expect(taps).toHaveText('Bold 1, Italic 2, Underline 0');
+ });
+
+ test('a tap nearer an offset neighbour never presses the farther button', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), STORY);
+ await waitForHitArea(page, ['Undo', 'Redo']);
+ const driver = await touchDriver(page);
+ const undo = await measure(page, 'Undo');
+ const redo = await measure(page, 'Redo');
+ const taps = page.locator(
+ '#storybook-root output[aria-label="Offset taps"]',
+ );
+ // Redo sits past Undo's corner on both axes. This point is in Undo's
+ // band but nearer Redo's box. It is a whole pixel because the WebKit
+ // driver rounds a tap to one.
+ const at = {
+ x: Math.ceil(undo.box.right) + 1,
+ y: Math.floor(redo.box.top) + 3,
+ };
+ expect(at.x).toBeLessThanOrEqual(undo.box.right + undo.insets.right);
+ expect(at.y).toBeLessThanOrEqual(undo.box.bottom + undo.insets.bottom);
+ expect(redo.box.left - at.x).toBeLessThan(at.y - undo.box.bottom);
+ await tapAt(driver, at);
+ await expect(taps).toContainText('Undo 0');
+ });
+
+ test('the clear button’s band stops short of the field’s text', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), STORY);
+ await waitForHitArea(page, [CLEAR]);
+ const driver = await touchDriver(page);
+ const clear = await measure(page, CLEAR);
+ const input = page.locator('#storybook-root input');
+ const inputBox = await input.evaluate(element => {
+ const r = element.getBoundingClientRect();
+ return {left: r.left, top: r.top, right: r.right, bottom: r.bottom};
+ });
+ // The band never reaches into the text box: at most half the gap.
+ expect(clear.insets.left).toBeLessThanOrEqual(
+ Math.max(0, (clear.box.left - inputBox.right) / 2) + 0.5,
+ );
+ // A tap in the text, beside the gap, places the caret and clears nothing.
+ await tapAt(driver, {x: inputBox.right - 2, y: middleY(clear.box)});
+ await expect(input).toHaveValue('quarterly report');
+ await expect(input).toBeFocused();
+ });
+
+ test('a tap on the band just past the clear button’s edge clears', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), STORY);
+ await waitForHitArea(page, [CLEAR]);
+ const driver = await touchDriver(page);
+ const clear = await measure(page, CLEAR);
+ expect(clear.insets.bottom).toBeGreaterThan(1);
+ await tapAt(driver, {
+ x: (clear.box.left + clear.box.right) / 2,
+ y: clear.box.bottom + clear.insets.bottom - 1,
+ });
+ await expect(page.locator('#storybook-root input')).toHaveValue('');
+ });
+
+ test('a tap on a clearable selector’s chevron opens it and keeps the value', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-selector--clearable');
+ await waitForHitArea(page, [CLEAR]);
+ const driver = await touchDriver(page);
+ const clear = await measure(page, CLEAR);
+ // The chevron is the next part of the field that has a box.
+ const chevron = await buttonNamed(page, CLEAR).evaluate(button => {
+ let part = button.nextElementSibling;
+ while (part != null && part.getBoundingClientRect().width === 0) {
+ part = part.nextElementSibling;
+ }
+ if (part == null) {
+ return null;
+ }
+ const r = part.getBoundingClientRect();
+ return {
+ x: (r.left + r.right) / 2,
+ y: (r.top + r.bottom) / 2,
+ gap: r.left - button.getBoundingClientRect().right,
+ };
+ });
+ expect(chevron).not.toBeNull();
+ // The band stops at half the gap to the chevron, and within 2 px of the
+ // clear button: WebKit moves a tap toward a clickable element near it.
+ expect(clear.insets.right).toBeLessThanOrEqual(chevron!.gap / 2 + 0.5);
+ expect(clear.insets.right).toBeLessThanOrEqual(2.5);
+ await tapAt(driver, {x: Math.round(chevron!.x), y: Math.round(chevron!.y)});
+ await expect(
+ page.locator('#storybook-root').getByRole('combobox'),
+ ).toHaveAttribute('aria-expanded', 'true');
+ await expect(buttonNamed(page, CLEAR)).toBeVisible();
+ });
+});
diff --git a/packages/core/src/Button/buttonHitArea.ts b/packages/core/src/Button/buttonHitArea.ts
new file mode 100644
index 0000000000..dfd0f06daa
--- /dev/null
+++ b/packages/core/src/Button/buttonHitArea.ts
@@ -0,0 +1,26 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file buttonHitArea.ts
+ * @input Uses React createContext and the touch hit-area options type
+ * @output Exports ButtonHitAreaContext, the touch hit-area options a Button
+ * passes to useTouchHitArea, and BUTTON_HIT_AREA, their default
+ * @position Internal to Core. A Core part that renders a Button and needs a
+ * different band, such as InputClearButton, provides its own options.
+ */
+
+import {createContext} from 'react';
+import type {TouchHitAreaOptions} from '../utils/touchHitArea';
+
+// The band is on the content wrapper, so a band tap lands on a descendant.
+// Button's content never paints past its box, so such a tap nearer a
+// neighbour is the neighbour's, not this button's.
+export const BUTTON_HIT_AREA: TouchHitAreaOptions = {
+ ownsDescendantTouches: false,
+};
+
+export const ButtonHitAreaContext =
+ createContext<TouchHitAreaOptions>(BUTTON_HIT_AREA);
+ButtonHitAreaContext.displayName = 'ButtonHitAreaContext';
diff --git a/packages/core/src/ButtonGroup/ButtonGroup.tsx b/packages/core/src/ButtonGroup/ButtonGroup.tsx
index a27fac9183..f59cf8f3fe 100644
--- a/packages/core/src/ButtonGroup/ButtonGroup.tsx
+++ b/packages/core/src/ButtonGroup/ButtonGroup.tsx
@@ -35,7 +35,7 @@ import {
useGroupPressTracking,
} from '../hooks/useGroupPressTracking';
import {useTouchPresentation} from '../utils/touchPresentation';
-import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';
+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';
import {mergeProps, composeEventHandlers} from '../utils';
import type {BaseProps} from '../BaseProps';
import {ButtonGroupContext} from './ButtonGroupContext';
diff --git a/packages/core/src/ButtonGroup/ButtonGroupTracking.test.tsx b/packages/core/src/ButtonGroup/ButtonGroupTracking.test.tsx
index 298fc776ed..2e9da21c5d 100644
--- a/packages/core/src/ButtonGroup/ButtonGroupTracking.test.tsx
+++ b/packages/core/src/ButtonGroup/ButtonGroupTracking.test.tsx
@@ -19,7 +19,7 @@ import {
pointerQuery,
} from '../gestures/__tests__/pointerQuery';
import {isPressGroupItem} from '../privateAttributes/pressGroupItem.stylex';
-import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';
+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';
import {Button} from '../Button/Button';
import {DropdownMenu} from '../DropdownMenu/DropdownMenu';
import {ButtonGroup} from './ButtonGroup';
diff --git a/packages/core/src/CheckboxInput/CheckboxInput.tsx b/packages/core/src/CheckboxInput/CheckboxInput.tsx
index 58989d9fc3..b934e87256 100644
--- a/packages/core/src/CheckboxInput/CheckboxInput.tsx
+++ b/packages/core/src/CheckboxInput/CheckboxInput.tsx
@@ -63,7 +63,7 @@ import {useMergedRefs} from '../hooks/useMergedRefs';
import {useTouchHitArea} from '../utils/touchHitArea';
import {pressBoxProps} from '../privateAttributes/pressBox.stylex';
import {registerBoxHold} from '../utils/boxHold';
-import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';
+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';
import {
registerEnglishFallback,
useComponentTranslator,
diff --git a/packages/core/src/Field/Field.doc.mjs b/packages/core/src/Field/Field.doc.mjs
index ad2e0b0008..1c1ff3441d 100644
--- a/packages/core/src/Field/Field.doc.mjs
+++ b/packages/core/src/Field/Field.doc.mjs
@@ -40,8 +40,6 @@ export const docs = {
vars: [
{name: '--_field-radius', description: 'Border radius of input fields', default: 'var(--radius-element)', private: true},
{name: '--_field-status-overlap', description: 'Amount an attached FieldStatus extends behind the lower half of the control. Set from the rendered control size.', default: 'calc(var(--size-element-md) / 2)', private: true},
- {name: '--_input-clear-hit-inset', description: 'Outset of the clear (\u2715) button\'s invisible hit area, applied to a ::after overlay. 0 on a fine pointer; negative on a coarse one, which grows the 20px button to the 24px touch target without changing what is drawn.', default: '0px', private: true},
- {name: '--_input-clear-hit-content', description: 'Whether the clear (\u2715) button\'s invisible hit overlay exists. `none` on a fine pointer, so no ::after is generated and hover still reaches the glyph; `""` on a coarse one, where the overlay provides the 24px touch target.', default: 'none', private: true},
],
derived: [
{property: 'borderRadius', vars: ['--_field-radius']},
diff --git a/packages/core/src/Field/InputClearButton.test.tsx b/packages/core/src/Field/InputClearButton.test.tsx
index fe32801b24..ddd8da673c 100644
--- a/packages/core/src/Field/InputClearButton.test.tsx
+++ b/packages/core/src/Field/InputClearButton.test.tsx
@@ -29,45 +29,13 @@ import {InternationalizationProvider} from '../i18n';
import {defineTheme} from '../theme/defineTheme';
import {generateThemeCSS} from '../theme/generateThemeRules';
import {declaredValue} from '../__tests__/stylexDeclarations';
+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';
function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {
const {prose, component} = generateThemeCSS(theme);
return [prose, component].filter(Boolean).join('\n\n');
}
-interface InjectedRule {
- selector: string;
- text: string;
- media: string | null;
-}
-
-/**
- * Every style rule StyleX has injected at runtime (`runtimeInjection` in the
- * root vitest config), flattened out of any at-rule wrapper and tagged with
- * that wrapper's condition — so a `@media (pointer: coarse)` rule stays
- * distinguishable from the unconditional one.
- */
-function injectedRules(): InjectedRule[] {
- const walk = (rules: CSSRuleList, condition: string | null) =>
- [...rules].flatMap((rule): InjectedRule[] => {
- const {selectorText} = rule as CSSStyleRule;
- if (typeof selectorText === 'string') {
- return [{selector: selectorText, text: rule.cssText, media: condition}];
- }
- // A grouping rule (@media, @keyframes, ...): descend, carrying the
- // innermost condition down. jsdom hangs an empty `cssRules` off plain
- // style rules too, which is why the leaf check comes first.
- const nested = (rule as CSSGroupingRule).cssRules;
- if (nested == null) {
- return [];
- }
- const own = (rule as CSSMediaRule).media?.mediaText;
- return walk(nested, own != null && own !== '' ? own : condition);
- });
-
- return [...document.styleSheets].flatMap(sheet => walk(sheet.cssRules, null));
-}
-
const getGlyph = (): HTMLElement => {
const button = screen.getByRole('button', {name: 'Clear'});
const icon = button.querySelector('.astryx-icon');
@@ -253,75 +221,25 @@ describe('InputClearButton', () => {
expect(declaredValue(screen.getByRole('button'), 'width')).toBe('999px');
});
- it('grows the hit area to 24px on a coarse pointer only (WCAG 2.5.8 AA)', () => {
- // The visual glyph stays 20px; an ::after overlay expands only the
- // tappable region, and only under a coarse pointer. Asserted against the
- // CSS StyleX injects at runtime, because jsdom resolves neither media
- // queries nor pseudo-element boxes.
+ it("takes Button's shared touch band rather than a fixed 24px overlay of its own", () => {
+ // Under a finger the clear button's target grows toward 44 px where its
+ // neighbors leave room, through Button's band (AST-094 FR42).
render(<InputClearButton label="Clear" onClick={() => {}} />);
const button = screen.getByRole('button', {name: 'Clear'});
- const classes = new Set(button.className.split(' ').filter(Boolean));
-
- const css = injectedRules();
- const rulesForButton = css.filter(({selector}) =>
- [...classes].some(c => selector.includes(`.${c}`)),
+ const bandClasses = (stylex.props(touchHitAreaStyles.layer).className ?? '')
+ .split(/\s+/)
+ .filter(Boolean);
+ expect(bandClasses.length).toBeGreaterThan(0);
+ const band = [...button.querySelectorAll('*')].find(element =>
+ bandClasses.every(bandClass => element.classList.contains(bandClass)),
);
- // Guards every assertion below against silently passing if StyleX's
- // runtime injection or the class plumbing ever changes shape.
- expect(rulesForButton.length).toBeGreaterThan(0);
-
- const decl = (pattern: RegExp, inMedia?: string) =>
- rulesForButton.some(
- ({text, media}) =>
- pattern.test(text) &&
- (inMedia == null ? media == null : (media ?? '').includes(inMedia)),
- );
-
- // Fine pointer: hit area == the 20px visual glyph, no expansion.
- expect(decl(/--_input-clear-hit-inset\s*:\s*0px/)).toBe(true);
- // Coarse pointer: 20px + 2px on each side = 24x24, the AA floor.
- expect(decl(/--_input-clear-hit-inset\s*:\s*-2px/, 'pointer: coarse')).toBe(
- true,
- );
- // ...and nothing wider than that, which would reach into the adornment
- // gap and the input's caret area. Scoped to the coarse block, because
- // that is the only place a wider value can appear.
- expect(
- decl(
- /--_input-clear-hit-inset\s*:\s*-(?:[3-9]|\d{2,})px/,
- 'pointer: coarse',
- ),
- ).toBe(false);
- // The overlay exists only on touch. On a fine pointer a generated
- // ::after would cover the button and take hover away from the glyph
- // target, so `content` is gated the same way the inset is.
- expect(decl(/--_input-clear-hit-content\s*:\s*none/)).toBe(true);
- expect(decl(/--_input-clear-hit-content\s*:\s*""/, 'pointer: coarse')).toBe(
- true,
- );
- // The overlay itself is what carries the expansion, and what is gated.
- expect(
- decl(/::after\s*\{[^}]*inset\s*:\s*var\(--_input-clear-hit-inset\)/),
- ).toBe(true);
- expect(
- decl(/::after\s*\{[^}]*content\s*:\s*var\(--_input-clear-hit-content\)/),
- ).toBe(true);
- });
-
- it('declares its own containing block for the hit overlay', () => {
- // The ::after overlay must resolve against this button. Button happens to
- // set `position: relative` on itself, so at runtime the overlay is
- // correctly placed either way — and StyleX compiles both declarations to
- // the same atomic class, so the rendered CSS cannot tell the two apart.
- // Assert on the source instead, so a future edit can't quietly leave the
- // overlay depending on another component's internal.
+ expect(band).toBeDefined();
const source = readFileSync(
path.resolve(__dirname, './InputClearButton.tsx'),
'utf-8',
);
- const buttonStyle = source.match(/button:\s*\{[\s\S]*?\n {2}\},/)?.[0];
- expect(buttonStyle).toBeDefined();
- expect(buttonStyle).toMatch(/position:\s*'relative'/);
+ expect(source).not.toContain('--_input-clear-hit-inset');
+ expect(source).not.toContain("'::after'");
});
it('exposes input-clear-button so a theme controls the button size and hover', () => {
@@ -392,4 +310,21 @@ describe('InputClearButton pointer and focus interactions', () => {
expect(handlePointerDown).toHaveBeenCalledTimes(1);
expect(pointerDownEvent).toBe(false);
});
+
+ it('leaves a touch pointerdown uncancelled so the tap still clicks, and still keeps focus through mousedown', () => {
+ const handlePointerDown = vi.fn();
+ render(
+ <InternalInputClearButton
+ label="Clear"
+ onClick={() => {}}
+ onPointerDown={handlePointerDown}
+ onClickCapture={() => {}}
+ />,
+ );
+ const button = screen.getByRole('button', {name: 'Clear'});
+
+ expect(fireEvent.pointerDown(button, {pointerType: 'touch'})).toBe(true);
+ expect(handlePointerDown).toHaveBeenCalledTimes(1);
+ expect(fireEvent.mouseDown(button)).toBe(false);
+ });
});
diff --git a/packages/core/src/Field/InputClearButton.tsx b/packages/core/src/Field/InputClearButton.tsx
index 0e55aafda0..09501b710e 100644
--- a/packages/core/src/Field/InputClearButton.tsx
+++ b/packages/core/src/Field/InputClearButton.tsx
@@ -19,6 +19,9 @@
import type {ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {Button} from '../Button/Button';
+import {BUTTON_HIT_AREA, ButtonHitAreaContext} from '../Button/buttonHitArea';
+import {clampedHitInsets, type HitInsets, type HitRect} from '../utils/hitArea';
+import type {TouchHitAreaOptions} from '../utils/touchHitArea';
import {Icon} from '../Icon/Icon';
import {themeProps} from '../utils/themeProps';
import {
@@ -29,48 +32,61 @@ import english from '../i18n/generated-english/Field/InputClearButton.generated'
registerEnglishFallback(english);
+// WebKit moves a tap toward a clickable element near it. The field's other
+// parts, such as the chevron, are not clickable themselves. So a band that
+// comes near one takes a tap on it. Toward a part, the band reaches at most
+// this far, in px.
+const PART_REACH = 2;
+
+/**
+ * How far the clear button's band grows on each side. It grows toward the
+ * minimum target and stops at half the gap to each of the field's other parts
+ * (the chevron, the status icon, the spinner). A tap on a part is the
+ * field's. No hit-area neighbour stops the band there, because the parts are
+ * not interactive. Toward a part beside it, the band also stops at
+ * `PART_REACH`.
+ */
+function clearButtonGrowth(
+ target: HitRect,
+ toLayout: (rect: HitRect) => HitRect,
+ element: HTMLElement,
+): HitInsets {
+ const parts: HitRect[] = [];
+ for (const part of element.parentElement?.children ?? []) {
+ const box = part.getBoundingClientRect();
+ if (part !== element && box.width > 0 && box.height > 0) {
+ parts.push(
+ toLayout({
+ left: box.left,
+ top: box.top,
+ right: box.right,
+ bottom: box.bottom,
+ }),
+ );
+ }
+ }
+ const insets = {...clampedHitInsets(target, parts)};
+ for (const rect of parts) {
+ if (rect.top < target.bottom && target.top < rect.bottom) {
+ if (rect.left >= target.right) {
+ insets.right = Math.min(insets.right, PART_REACH);
+ } else if (rect.right <= target.left) {
+ insets.left = Math.min(insets.left, PART_REACH);
+ }
+ }
+ }
+ return insets;
+}
+
+const CLEAR_BUTTON_HIT_AREA: TouchHitAreaOptions = {
+ ...BUTTON_HIT_AREA,
+ growth: clearButtonGrowth,
+};
+
const styles = stylex.create({
button: {
height: '20px',
flexShrink: 0,
- // Containing block for the ::after hit overlay below. Button sets its own
- // `position: relative`, so the overlay would resolve correctly without
- // this — but that is another component's internal, and if it ever changes
- // the overlay silently reattaches to some ancestor and the hit area lands
- // in the wrong place. Declaring it here keeps the containing block
- // colocated with the thing that depends on it. No-op at runtime.
- position: 'relative',
- // Expand the tap target to 24px ONLY on touch (WCAG 2.5.8 AA is a touch
- // requirement, and its floor is 24x24). On a fine pointer the 20px glyph
- // is precise enough, and an unconditional overlay could overlap
- // neighboring controls in dense layouts. The inset is 0 by default (hit
- // area == visual glyph) and grows to -2px (=> 24x24) under a coarse
- // pointer — no further, because at -4px the overlay reaches into the 8px
- // adornment gap and, on the inline-start side, over the input's own caret
- // area. Driven through a custom property because StyleX only allows plain
- // values inside a pseudo-element; the conditional lives on this top-level
- // property instead. Private (--_) because it is an internal implementation
- // detail, not a themeable target.
- '--_input-clear-hit-inset': {
- default: '0px',
- '@media (pointer: coarse)': '-2px',
- },
- // The overlay itself is gated too, not just its size. An ::after that is
- // generated on a fine pointer sits exactly over the button at inset 0,
- // where it adds no hit area but is the topmost hit-test box — so hover
- // stops reaching the descendants and `.astryx-input-clear-icon:hover`, a
- // public theme target, no longer matches. `content: none` means the
- // pseudo-element is not generated at all, so on a fine pointer the
- // overlay does not exist.
- '--_input-clear-hit-content': {
- default: 'none',
- '@media (pointer: coarse)': '""',
- },
- '::after': {
- content: 'var(--_input-clear-hit-content)',
- position: 'absolute',
- inset: 'var(--_input-clear-hit-inset)',
- },
},
});
@@ -108,38 +124,44 @@ function renderInputClearButton({
const {className: iconTargetClassName} = themeProps('input-clear-icon');
const {className: buttonTargetClassName} = themeProps('input-clear-button');
return (
- <Button
- variant="ghost"
- size="sm"
- label={label}
- // The field's label already sits beside the glyph, so the tooltip names
- // only the action; repeating a long label reads as awkward copy. The
- // contextual label stays the accessible name, which still contains
- // the visible word (WCAG 2.5.3, label in name).
- tooltip={tooltip}
- className={buttonTargetClassName}
- icon={
- <Icon
- icon="close"
- size="sm"
- color="secondary"
- className={
- iconClassName != null
- ? `${iconTargetClassName} ${iconClassName}`
- : iconTargetClassName
+ <ButtonHitAreaContext value={CLEAR_BUTTON_HIT_AREA}>
+ <Button
+ variant="ghost"
+ size="sm"
+ label={label}
+ // The field's label already sits beside the glyph, so the tooltip names
+ // only the action; repeating a long label reads as awkward copy. The
+ // contextual label stays the accessible name, which still contains
+ // the visible word (WCAG 2.5.3, label in name).
+ tooltip={tooltip}
+ className={buttonTargetClassName}
+ icon={
+ <Icon
+ icon="close"
+ size="sm"
+ color="secondary"
+ className={
+ iconClassName != null
+ ? `${iconTargetClassName} ${iconClassName}`
+ : iconTargetClassName
+ }
+ />
+ }
+ onPointerDown={e => {
+ // WebKit drops the click of a touch whose pointerdown is cancelled.
+ // For touch, the mousedown handler below keeps focus in the field.
+ if (e.pointerType !== 'touch') {
+ e.preventDefault();
}
- />
- }
- onPointerDown={e => {
- e.preventDefault();
- onPointerDown?.(e);
- }}
- onMouseDown={e => e.preventDefault()}
- onClick={onClick}
- onClickCapture={onClickCapture}
- isIconOnly
- xstyle={[styles.button, xstyle]}
- />
+ onPointerDown?.(e);
+ }}
+ onMouseDown={e => e.preventDefault()}
+ onClick={onClick}
+ onClickCapture={onClickCapture}
+ isIconOnly
+ xstyle={[styles.button, xstyle]}
+ />
+ </ButtonHitAreaContext>
);
}
diff --git a/packages/core/src/Indicator/touchTarget.test.tsx b/packages/core/src/Indicator/touchTarget.test.tsx
index 5a8ec0be4a..97a6cdcfb3 100644
--- a/packages/core/src/Indicator/touchTarget.test.tsx
+++ b/packages/core/src/Indicator/touchTarget.test.tsx
@@ -21,7 +21,7 @@ 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';
+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';
interface Declared {
media: string | null;
diff --git a/packages/core/src/InfoTip/InfoTip.tsx b/packages/core/src/InfoTip/InfoTip.tsx
index 9534101abd..adffb922fe 100644
--- a/packages/core/src/InfoTip/InfoTip.tsx
+++ b/packages/core/src/InfoTip/InfoTip.tsx
@@ -48,7 +48,7 @@ import {
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {mergeProps} from '../utils/mergeProps';
import {useTouchHitArea} from '../utils/touchHitArea';
-import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';
+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';
registerEnglishFallback(english);
diff --git a/packages/core/src/List/ListItem.tsx b/packages/core/src/List/ListItem.tsx
index 48360b4b98..60a04b670f 100644
--- a/packages/core/src/List/ListItem.tsx
+++ b/packages/core/src/List/ListItem.tsx
@@ -50,7 +50,7 @@ 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';
+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';
// =============================================================================
// Types
@@ -231,7 +231,7 @@ const styles = stylex.create({
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
+ // its insets are measured from (internal/touchHitArea.stylex.ts). The width
// sits on the layer itself, so content inside the row never inherits it.
'::after': {
'--_hit-border-bottom': {
diff --git a/packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.ts
index 5472795721..08d4c419d6 100644
--- a/packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.ts
+++ b/packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.ts
@@ -8,7 +8,7 @@
* 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)
+ * (internal/touchHitArea.stylex.ts, kept live by utils/touchHitArea.ts)
*/
// Geometry is read from the layer's computed edges. Chromium's
diff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsx
index 0d3984be39..73b893e01f 100644
--- a/packages/core/src/RadioList/RadioListItem.tsx
+++ b/packages/core/src/RadioList/RadioListItem.tsx
@@ -36,7 +36,7 @@ import {useMergedRefs} from '../hooks/useMergedRefs';
import {useTouchHitArea} from '../utils/touchHitArea';
import {pressBoxProps} from '../privateAttributes/pressBox.stylex';
import {registerBoxHold} from '../utils/boxHold';
-import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';
+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';
import {useIndicator} from '../Indicator/useIndicator';
import {Item, type ItemAlign} from '../Item/Item';
import {themeProps} from '../utils/themeProps';
diff --git a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx
index a866ad5332..fe833a3850 100644
--- a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx
+++ b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx
@@ -42,7 +42,7 @@ import {usePressFeedback} from '../hooks/usePressFeedback';
import {isRenderable} from '../utils/isRenderable';
import {useMergedRefs} from '../hooks/useMergedRefs';
import {useTouchHitArea} from '../utils/touchHitArea';
-import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';
+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';
export interface SegmentedControlItemProps extends BaseProps<HTMLButtonElement> {
ref?: React.Ref<HTMLButtonElement>;
diff --git a/packages/core/src/SegmentedControl/__tests__/SegmentedControlHitArea.interaction.browser.spec.ts b/packages/core/src/SegmentedControl/__tests__/SegmentedControlHitArea.interaction.browser.spec.ts
index 3be6a50fae..073d05532f 100644
--- a/packages/core/src/SegmentedControl/__tests__/SegmentedControlHitArea.interaction.browser.spec.ts
+++ b/packages/core/src/SegmentedControl/__tests__/SegmentedControlHitArea.interaction.browser.spec.ts
@@ -9,7 +9,7 @@
* box (spec:AST-094 FR42)
* @position Browser layer of SegmentedControlItem's hit band and
* useSegmentedTouchTracking's lift bounds; the band itself is
- * utils/touchHitArea.stylex.ts
+ * internal/touchHitArea.stylex.ts
*/
import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
diff --git a/packages/core/src/__tests__/publicStyleXNamespaces.test.ts b/packages/core/src/__tests__/publicStyleXNamespaces.test.ts
index 4faf6c3cc4..31a009e3fa 100644
--- a/packages/core/src/__tests__/publicStyleXNamespaces.test.ts
+++ b/packages/core/src/__tests__/publicStyleXNamespaces.test.ts
@@ -31,6 +31,7 @@ import * as stack from '@astryxdesign/core/Stack/stack.stylex';
import * as stackItem from '@astryxdesign/core/Stack/stackItem.stylex';
import * as text from '@astryxdesign/core/Text/text.stylex';
import * as indicatorPress from '@astryxdesign/core/internal/indicatorPress.stylex';
+import * as touchHitArea from '@astryxdesign/core/internal/touchHitArea.stylex';
import * as dataTokens from '@astryxdesign/core/theme/dataTokens.stylex';
import * as tokens from '@astryxdesign/core/theme/tokens.stylex';
import * as focusOutline from '@astryxdesign/core/utils/focusOutline.stylex';
@@ -73,8 +74,9 @@ type XstyleNamespaces = {
/**
* The style namespaces that go through `stylex.props`, not `xstyle`. A style
* that sets only custom properties shares no property with the `xstyle` type,
- * and `displayStyles` sets `overflowWrap` to a `var()`, which StyleX's
- * `overflowWrap` type does not list.
+ * `displayStyles` sets `overflowWrap` to a `var()`, which StyleX's
+ * `overflowWrap` type does not list, and `touchHitAreaStyles` styles only a
+ * pseudo-element.
*/
type PropsOnlyNamespaces = {
containerPaddingBlockEndVarStyles: typeof padding.containerPaddingBlockEndVarStyles;
@@ -87,6 +89,7 @@ type PropsOnlyNamespaces = {
overlayPaddingReset: typeof padding.overlayPaddingReset;
sectionPaddingPropagationStyles: typeof padding.sectionPaddingPropagationStyles;
displayStyles: typeof text.displayStyles;
+ touchHitAreaStyles: typeof touchHitArea.touchHitAreaStyles;
focusOutlineStylesPublishedVars: Pick<
typeof focusOutline.focusOutlineStyles,
'publishFocusVisibleVars'
@@ -190,6 +193,7 @@ const styleNamespacesBySubpath = {
'wordBreakStyles',
],
'./internal/indicatorPress.stylex': [],
+ './internal/touchHitArea.stylex': ['touchHitAreaStyles'],
'./theme/dataTokens.stylex': [],
'./theme/tokens.stylex': [],
'./utils/focusOutline.stylex': ['focusOutlineStyles'],
@@ -214,6 +218,7 @@ const modulesBySubpath: Readonly<
'./Stack/stackItem.stylex': stackItem,
'./Text/text.stylex': text,
'./internal/indicatorPress.stylex': indicatorPress,
+ './internal/touchHitArea.stylex': touchHitArea,
'./theme/dataTokens.stylex': dataTokens,
'./theme/tokens.stylex': tokens,
'./utils/focusOutline.stylex': focusOutline,
diff --git a/packages/core/src/internal/touch.test.ts b/packages/core/src/internal/touch.test.ts
index 2e5233336b..781e603e1f 100644
--- a/packages/core/src/internal/touch.test.ts
+++ b/packages/core/src/internal/touch.test.ts
@@ -142,7 +142,7 @@ describe('internal/touch', () => {
const animator = await import('../motion/animator');
const reduced = await import('../motion/reducedMotion');
const hitArea = await import('../utils/touchHitArea');
- const hitAreaStyles = await import('../utils/touchHitArea.stylex');
+ const hitAreaStyles = await import('./touchHitArea.stylex');
expect(entry.animatorFor).toBe(animator.animatorFor);
expect(entry.reducedMotionFade).toBe(reduced.reducedMotionFade);
expect(entry.useTouchHitArea).toBe(hitArea.useTouchHitArea);
diff --git a/packages/core/src/internal/touch.ts b/packages/core/src/internal/touch.ts
index 3b812d8ddd..f74dfe63c4 100644
--- a/packages/core/src/internal/touch.ts
+++ b/packages/core/src/internal/touch.ts
@@ -112,4 +112,4 @@ export {isCoarsePointer} from '../utils/coarsePointer';
export {animatorFor} from '../motion/animator';
export {reducedMotionFade} from '../motion/reducedMotion';
export {useTouchHitArea} from '../utils/touchHitArea';
-export {touchHitAreaStyles} from '../utils/touchHitArea.stylex';
+export {touchHitAreaStyles} from './touchHitArea.stylex';
diff --git a/packages/core/src/utils/touchHitArea.stylex.ts b/packages/core/src/internal/touchHitArea.stylex.ts
similarity index 78%
rename from packages/core/src/utils/touchHitArea.stylex.ts
rename to packages/core/src/internal/touchHitArea.stylex.ts
index 1a7a2de2f2..df5855c59d 100644
--- a/packages/core/src/utils/touchHitArea.stylex.ts
+++ b/packages/core/src/internal/touchHitArea.stylex.ts
@@ -6,17 +6,21 @@
* @output Exports `touchHitAreaStyles.layer`, a host's invisible hit band
* under a coarse pointer, and `touchHitAreaStyles.layerBelowChildren`, the
* same band drawn below the host's children
- * @position Internal styling utility for CheckboxInput, RadioListItem, List
- * rows, InfoTip, SegmentedControl segments and the press-tracking groups.
- * Each keeps its insets live with `useTouchHitArea` (utils/touchHitArea.ts).
+ * @position Internal styling utility for Button (and so the input clear
+ * button), CheckboxInput, RadioListItem, List rows, InfoTip,
+ * SegmentedControl segments and the press-tracking groups. 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. A host whose children fill its box,
+ * A tap on the band lands on the host. Button draws the band on its content
+ * wrapper instead, which leaves its own `::after` to callers. The insets then
+ * reach the wrapper by inheritance, a tap on the band lands on that
+ * descendant, and the watch has `ownsDescendantTouches` off. A host whose children fill its box,
* such as a press-tracking group, takes `layerBelowChildren`. That band is its
* `::before`, so its positioned children paint over the clip path's edge, and
- * the pixels on their own edges stay theirs. SYNC: hitArea.ts
- * HIT_INSET_PROPERTIES, touchHitArea.ts and touchHitArea.test.tsx.
+ * the pixels on their own edges stay theirs. SYNC: utils/hitArea.ts
+ * HIT_INSET_PROPERTIES, utils/touchHitArea.ts and utils/touchHitArea.test.tsx.
*/
import * as stylex from '@stylexjs/stylex';
diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.ts
index 57bda7a7c5..96b2446abb 100644
--- a/packages/core/src/theme/derivedVarRegistry.test.ts
+++ b/packages/core/src/theme/derivedVarRegistry.test.ts
@@ -357,7 +357,6 @@ const VARS_WITHOUT_DERIVED_MAPPING = new Set([
// generated at all — `inset` and `content` on a pseudo-element are not
// properties a theme author sets on the component.
'--_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).
@@ -381,7 +380,6 @@ const VARS_WITHOUT_DERIVED_MAPPING = new Set([
// A CheckboxList row's own press paint, handed to its checkbox's box:
// written by the row's own press arms, never a value a theme author sets.
'--_checkbox-row-press-paint',
- '--_input-clear-hit-content',
'--_power-search-sheet-hit-content',
// Placement and swipe lifecycle values are private Toast behavior. A theme
// author controls the surface transform/opacity as a whole, not these values.
diff --git a/packages/core/src/utils/touchHitArea.test.tsx b/packages/core/src/utils/touchHitArea.test.tsx
index 6217bded10..21eb887939 100644
--- a/packages/core/src/utils/touchHitArea.test.tsx
+++ b/packages/core/src/utils/touchHitArea.test.tsx
@@ -8,7 +8,7 @@
* the hook watches, an owner's growth and press check, 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
+ * internal/touchHitArea.stylex.ts. List/ListItem.hitArea.test.tsx covers the
* row wiring.
*/
@@ -54,7 +54,7 @@ vi.mock('./hitArea', async importOriginal => {
});
import {useTouchHitArea} from './touchHitArea';
-import {touchHitAreaStyles} from './touchHitArea.stylex';
+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';
function Host({
enabled,
@@ -164,10 +164,10 @@ describe('useTouchHitArea', () => {
expect(watches[1].stop).toHaveBeenCalledTimes(1);
});
- it("passes an owner's growth, with the element, and its press check to the watch; a plain watch keeps the defaults", () => {
+ it("passes an owner's growth, with the element, its press check and its descendant-touch choice to the watch; a plain watch keeps the defaults", () => {
const grown = {top: 1, right: 2, bottom: 3, left: 4};
const growth = vi.fn(() => grown);
- const options = {growth, checkAtPress: false};
+ const options = {growth, checkAtPress: false, ownsDescendantTouches: false};
function Owner() {
const hitAreaRef = useTouchHitArea(true, options);
return <span data-testid="owner" ref={hitAreaRef} />;
@@ -184,12 +184,14 @@ describe('useTouchHitArea', () => {
watch => watch.element === screen.getByTestId('host'),
);
expect(ownerWatch?.options?.checkAtPress).toBe(false);
+ expect(ownerWatch?.options?.ownsDescendantTouches).toBe(false);
const box = {left: 0, top: 0, right: 32, bottom: 32};
const toLayout = (rect: HitRect) => rect;
expect(ownerWatch?.options?.growth?.(box, toLayout)).toBe(grown);
expect(growth).toHaveBeenCalledWith(box, toLayout, owner);
expect(plainWatch?.options?.growth).toBeUndefined();
expect(plainWatch?.options?.checkAtPress).toBeUndefined();
+ expect(plainWatch?.options?.ownsDescendantTouches).toBe(true);
});
it('follows a replaced element: the new element is watched and the old one’s watch stops', async () => {
diff --git a/packages/core/src/utils/touchHitArea.ts b/packages/core/src/utils/touchHitArea.ts
index 48aa997412..79fd7be0fb 100644
--- a/packages/core/src/utils/touchHitArea.ts
+++ b/packages/core/src/utils/touchHitArea.ts
@@ -13,7 +13,7 @@
* press-tracking groups use it, and so can any control whose target outgrows
* its box under a finger.
*
- * SYNC: When modified, update utils/touchHitArea.stylex.ts and
+ * SYNC: When modified, update internal/touchHitArea.stylex.ts and
* touchHitArea.test.tsx.
*/
@@ -47,6 +47,15 @@ export interface TouchHitAreaOptions {
* @default true
*/
readonly checkAtPress?: boolean;
+ /**
+ * Whether a finger's press that lands on a descendant is the element's,
+ * however near a neighbour is, read as `watchHitArea`'s
+ * `ownsDescendantTouches`. An owner that draws the band on a descendant,
+ * and whose content never paints past its box, turns it off, so a band
+ * press nearer a neighbour is not the element's.
+ * @default true
+ */
+ readonly ownsDescendantTouches?: boolean;
}
const NO_OPTIONS: TouchHitAreaOptions = {};
@@ -88,7 +97,7 @@ function settlingAnimations(element: HTMLElement): Animation[] {
function watchAtRest(
element: HTMLElement,
minSize: number,
- {growth, checkAtPress}: TouchHitAreaOptions,
+ {growth, checkAtPress, ownsDescendantTouches = true}: TouchHitAreaOptions,
): () => void {
let stopWatch = (): void => {};
let isStopped = false;
@@ -128,11 +137,12 @@ function watchAtRest(
}
});
},
- // 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.
+ // By default 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,
+ ownsDescendantTouches,
growth:
growth == null
? undefined
@@ -196,8 +206,9 @@ function holdWatch(
* 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
+ * on the same element, or on a descendant with `ownsDescendantTouches` off.
+ * 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. `options` set how the element grows. Keep
* them stable, as a module constant. An element's first holder sets them.
*
diff --git a/scripts/sync-exports.js b/scripts/sync-exports.js
index 2b63f64225..87ffabaf02 100644
--- a/scripts/sync-exports.js
+++ b/scripts/sync-exports.js
@@ -238,6 +238,7 @@ const FILE_MODULE_SUBPATH_EXPORTS = [
// public API, and allowed by lint only in Core and Lab
// (architecture:react-component-runtime INV13).
'internal/indicatorPress.stylex',
+ 'internal/touchHitArea.stylex',
'internal/touch',
'internal/selectable-card',
'internal/spinner-rotor',