An open source design system that's fully customizable and agent ready
TypeScript
fix(ClickableCard, SelectableCard): no touch pressed look for a finger press that starts on a control inside the card (#9801)
Cindy Zhangf59ffe15563c
diff --git a/.changeset/clickable-container-nested-press.md b/.changeset/clickable-container-nested-press.mdnew file mode 100644index 0000000000..5f8c762332--- /dev/null+++ b/.changeset/clickable-container-nested-press.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] ClickableCard and SelectableCard no longer show their pressed look when a finger press starts on a control inside them, such as an info button, a button, or a link. A mouse press is unchanged. `useClickableContainer` returns `onPointerDown`; on a container that paints its press with `usePressFeedback`, spreading it drops a touch press that starts on a nested control. A mouse `:active` press paint is unchanged. A container that does not spread it works as before.++@cixzhangdiff --git a/docs/specs/components/ClickableCard/ClickableCard.spec.md b/docs/specs/components/ClickableCard/ClickableCard.spec.mdindex 1b116eed33..4996d05bf1 100644--- a/docs/specs/components/ClickableCard/ClickableCard.spec.md+++ b/docs/specs/components/ClickableCard/ClickableCard.spec.md@@ -50,15 +50,15 @@ system_specs: [spec:AST-005, spec:AST-009, spec:AST-085]## Contract at a glance-| Area | Contract |-| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Public contract | A Card with a required `label` and either `onClick` (action) or `href` (navigation), plus `isDisabled` and Card's padding, variant, elevation, and size inputs. |-| Behavior | A visually hidden native button or link owns the card's action; the whole card surface activates it, while nested controls and selected text keep their own outcomes. |-| End-user impact | People can activate a card from anywhere on it, by pointer or keyboard, and a disabled card stays reachable and announced while doing nothing. |-| Builder impact | None; the record describes shipped behavior. |-| Compatibility/readiness | Released behavior recorded as current; no API, default, or output changes. Two implementation gaps are listed under Current-state impact. |-| Review checks | Reject a live destination while disabled, duplicate activation, activation from a nested control or selected text, a destination that skips the shared decision, or lost focus paint. |-| Governing rules | `family:navigation-destinations/FR1,FR3–FR5`; `architecture:interaction-modality/INV2–INV5`; `architecture:public-component-api/INV5–INV8`; `spec:AST-085` FR1, FR2, FR5, FR6. |+| Area | Contract |+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | A Card with a required `label` and either `onClick` (action) or `href` (navigation), plus `isDisabled` and Card's padding, variant, elevation, and size inputs. The card is built on `useClickableContainer`, which returns `onPointerDown`, which a container spreads so a touch press that starts on a nested interactive element shows no pressed state (FR5). |+| Behavior | A visually hidden native button or link owns the card's action; the whole card surface activates it, while nested controls and selected text keep their own outcomes. |+| End-user impact | People can activate a card from anywhere on it, by pointer or keyboard, and a disabled card stays reachable and announced while doing nothing. |+| Builder impact | None; the record describes shipped behavior. |+| Compatibility/readiness | Released behavior recorded as current; no API, default, or output changes. Two implementation gaps are listed under Current-state impact. |+| Review checks | Reject a live destination while disabled, duplicate activation, activation from a nested control or selected text, a destination that skips the shared decision, or lost focus paint. |+| Governing rules | `family:navigation-destinations/FR1,FR3–FR5`; `architecture:interaction-modality/INV2–INV5`; `architecture:public-component-api/INV5–INV8`; `spec:AST-085` FR1, FR2, FR5, FR6. |This table is a review projection; the body below is authoritative.@@ -124,7 +124,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR2 | A primary-button press on the card surface calls `onClick` once with the card as `currentTarget`, then performs an accepted navigation unless the callback cancels it. A middle press on the surface of a card given `href` opens an accepted destination in a new tab without calling `onClick`. A press inside a nested interactive descendant, inside an open Tooltip or HoverCard surface (`component:Tooltip` FR11), or one that ends a text selection, does not activate the card. Activating the hidden button of an action card calls `onClick` once; activating the hidden link navigates without calling `onClick`. | Current source and tests; `architecture:public-component-api` INV7 || FR3 | Plain, new-tab, modified, middle-click, and surface-delegated navigation use the shared destination decision; a blocked destination does not navigate. | `family:navigation-destinations` FR1, FR3–FR5 || FR4 | `isDisabled` keeps the hidden control focusable with `aria-disabled="true"`; Enter, Space, and clicks on it do nothing. A disabled link keeps its link role and name but has no `href` or `target`. The control stays focusable and announced (`spec:AST-085` FR1, FR2, FR5); the card's own click and mouseup handling and the caller's `onMouseUp` are removed, other caller event props still reach the root, and the surface shows no hover or pressed paint (`spec:AST-085` FR6), and renders at half opacity. The disabled state is reflected on the owning target (`architecture:component-theming-surface` INV6). Implementation gap: the `clickable-card` target reflects no disabled state (Current-state impact). | Current source and tests |-| FR5 | While enabled, the root paints the shared hover overlay under a hover-capable pointer and the pressed overlay for mouse and touch presses, and a bordered card's border responds to hover. Keyboard focus on the hidden control shows the shared focus outline on the root. | Current source, stories, and `architecture:interaction-modality` |+| FR5 | While enabled, the root paints the shared hover overlay under a hover-capable pointer and the pressed overlay for mouse and touch presses that would activate the card; a touch press that starts on a nested interactive element shows no pressed paint, since it does not activate the card (the counterpart of FR2's activation rule), while a mouse press there keeps the `:active` paint, and a bordered card's border responds to hover. Keyboard focus on the hidden control shows the shared focus outline on the root. | Current source, stories, and `architecture:interaction-modality` || FR6 | The root carries the `clickable-card` target reflecting `variant` beside Card's target. `ref` reaches the root; supported DOM, ARIA, data, and event props reach it; a caller `onMouseUp` runs after the card's own; `xstyle`, `className`, and `style` compose after the component styles. | Current source and tests; `architecture:public-component-api` INV5–INV8 |### Allowed variationdiff --git a/docs/specs/components/Item/Item.spec.md b/docs/specs/components/Item/Item.spec.mdindex 5077c1af80..a7cba229df 100644--- a/docs/specs/components/Item/Item.spec.md+++ b/docs/specs/components/Item/Item.spec.md@@ -102,16 +102,17 @@ Consumer migration instructions belong in consumer docs and release notes.## Behavioral and layout contract-| ID | Invariant | Basis | Draft review state |-| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | ------------------ |-| FR1 | Item MUST accept `align` with exactly `center`, `start`, and `first-line`, and MUST resolve an omitted value to `center`. The geometry of `center` and `start` MUST NOT change. | `component:Item/DEC-1` | settled |-| FR2 | Under `first-line`, the block-axis center of each rendered start-content and end-content slot MUST coincide with the block-axis center of the label's first line box, for every slot block size. | Owner direction | settled |-| FR3 | Under `first-line`, a slot taller than the label's first line MUST stay inside the row's content box: the label and description move down by the difference, and the row grows to fit. No slot is clipped or painted into the row's block padding. | Owner direction | settled |-| FR4 | A row whose label renders a single line and which has no description MUST render identically under `first-line` and `center`, for every slot block size. | Follows from FR2 and FR3 | settled |-| FR5 | The first line box is the label line as Item styles it, from the active theme's body text size and leading. A theme that changes those tokens moves the alignment with them. Caller content inside `label` that sets its own font size or line height is outside the FR2 guarantee. | Shared typography source | settled |-| FR6 | `first-line` MUST hold in every density, in `stacked` and `inline` layouts, with `labelLines` truncation, and in plain, button, link, link-root, delegated, and parent-role rows. In right-to-left text it MUST produce the same block-axis placement with the slots mirrored by logical order and no DOM reordering. | `architecture:internationalization` | settled |-| FR7 | The `item` theme target MUST reflect the resolved alignment as its existing `align` selector axis, including `first-line`, and Item's public theming metadata MUST list that value. No new target, state, or theme-level default is added. | `architecture:component-theming-surface/INV6`; `component:Item/DEC-2` | settled |-| FR8 | ListItem, RadioListItem, and CheckboxListItem MUST expose `align` with Item's values and default and forward it unchanged to the Item row they render. A composing row MUST NOT drop, remap, or narrow the value. | Owner direction | settled |+| ID | Invariant | Basis | Draft review state |+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ------------------ |+| FR1 | Item MUST accept `align` with exactly `center`, `start`, and `first-line`, and MUST resolve an omitted value to `center`. The geometry of `center` and `start` MUST NOT change. | `component:Item/DEC-1` | settled |+| FR2 | Under `first-line`, the block-axis center of each rendered start-content and end-content slot MUST coincide with the block-axis center of the label's first line box, for every slot block size. | Owner direction | settled |+| FR3 | Under `first-line`, a slot taller than the label's first line MUST stay inside the row's content box: the label and description move down by the difference, and the row grows to fit. No slot is clipped or painted into the row's block padding. | Owner direction | settled |+| FR4 | A row whose label renders a single line and which has no description MUST render identically under `first-line` and `center`, for every slot block size. | Follows from FR2 and FR3 | settled |+| FR5 | The first line box is the label line as Item styles it, from the active theme's body text size and leading. A theme that changes those tokens moves the alignment with them. Caller content inside `label` that sets its own font size or line height is outside the FR2 guarantee. | Shared typography source | settled |+| FR6 | `first-line` MUST hold in every density, in `stacked` and `inline` layouts, with `labelLines` truncation, and in plain, button, link, link-root, delegated, and parent-role rows. In right-to-left text it MUST produce the same block-axis placement with the slots mirrored by logical order and no DOM reordering. | `architecture:internationalization` | settled |+| FR7 | The `item` theme target MUST reflect the resolved alignment as its existing `align` selector axis, including `first-line`, and Item's public theming metadata MUST list that value. No new target, state, or theme-level default is added. | `architecture:component-theming-surface/INV6`; `component:Item/DEC-2` | settled |+| FR8 | ListItem, RadioListItem, and CheckboxListItem MUST expose `align` with Item's values and default and forward it unchanged to the Item row they render. A composing row MUST NOT drop, remap, or narrow the value. | Owner direction | settled |+| FR9 | A delegated row (`interactiveRef`) shows its touch pressed paint only for a press that would activate it: a finger press on the row's surface or on the control it delegates to paints the row, and a finger press that starts on another interactive element inside the row paints none. A mouse press keeps the row's `:active` paint. | Owner direction, 2026-11-03: no pressed state on a container for a press that does not activate it | settled |### Allowed variation@@ -180,13 +181,14 @@ Consumer migration instructions belong in consumer docs and release notes.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| -------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------- |-| FR1, FR7 | `Item.test.tsx` alignment and theme-reflection suites; public type test | Omitted, `center`, `start`, `first-line` | A changed default, a missing `data-align="first-line"`, or a widened type fails. | `audit:Item/api` |-| FR2–FR6 | Real-Chromium geometry assertions over the Item alignment stories | Wrapped label with dot and age; avatar; densities; RTL; theme | A slot center off the first line center by more than 0.5px, or a clipped slot, fails. | `audit:Item/layout` |-| FR8 | `List.test.tsx`, `RadioList.test.tsx`, `CheckboxList.test.tsx` forwarding cases | Each composing row with `align="first-line"` | A row whose Item root lacks `data-align="first-line"` fails. | `audit:Item/api` |-| AR1, AR2 | Accessibility-tree snapshot of a `first-line` row against a `center` row | Plain and option rows | Any difference in name, role, description, or order fails. | `audit:Item/a11y` |-| PR1 | Source review of Item's alignment styles | All values | A ref, observer, or Effect added for alignment fails review. | `audit:Item/layout` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| -------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------- |+| FR1, FR7 | `Item.test.tsx` alignment and theme-reflection suites; public type test | Omitted, `center`, `start`, `first-line` | A changed default, a missing `data-align="first-line"`, or a widened type fails. | `audit:Item/api` |+| FR2–FR6 | Real-Chromium geometry assertions over the Item alignment stories | Wrapped label with dot and age; avatar; densities; RTL; theme | A slot center off the first line center by more than 0.5px, or a clipped slot, fails. | `audit:Item/layout` |+| FR8 | `List.test.tsx`, `RadioList.test.tsx`, `CheckboxList.test.tsx` forwarding cases | Each composing row with `align="first-line"` | A row whose Item root lacks `data-align="first-line"` fails. | `audit:Item/api` |+| FR9 | `Item.nestedPress.test.tsx`; `ClickableCard.nestedPress.test.tsx` | A finger on the delegated control; a finger on another control in the row | A row painted for a press on another control, or not painted for a press on its delegated control, fails. | `audit:Item/behavior` |+| AR1, AR2 | Accessibility-tree snapshot of a `first-line` row against a `center` row | Plain and option rows | Any difference in name, role, description, or order fails. | `audit:Item/a11y` |+| PR1 | Source review of Item's alignment styles | All values | A ref, observer, or Effect added for alignment fails review. | `audit:Item/layout` |## Decision logdiff --git a/docs/specs/components/SelectableCard/SelectableCard.spec.md b/docs/specs/components/SelectableCard/SelectableCard.spec.mdindex a1fabcafa0..83d3d70d97 100644--- a/docs/specs/components/SelectableCard/SelectableCard.spec.md+++ b/docs/specs/components/SelectableCard/SelectableCard.spec.md@@ -146,7 +146,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR1 | SelectableCard renders `component:Card` with the given `variant`, `elevation`, `padding`, and sizing. The root also carries the `selectable-card` target reflecting `variant` and `selected`, and the first child is a visually hidden native `input type="checkbox"` named by `label` with `checked` equal to `isSelected`. | Current source and tests || FR2 | While enabled, a click on the card surface, a click or Space on the checkbox, or Enter on the checkbox calls `onChange(!isSelected)` exactly once. A click that belongs to nested interactive content, an open Tooltip or HoverCard surface (`component:Tooltip` FR11), or selected text does not toggle. A caller `onClick` runs after the toggle for a surface click, before it for a click or Space on the checkbox, and not at all for Enter; it also runs for clicks that do not toggle, including a click inside an open Tooltip or HoverCard surface. At the next minor, staged as `[breaking]`, a click inside an open layer stops at the layer root and the caller `onClick` no longer receives it (`architecture:layer-runtime` INV17); implementation gap: not built. A caller `onMouseUp` runs after the card's own handling. | Current source and tests || FR3 | Selection adds a 2px inset ring through Card's ring variable, so layout does not move, and composes with any elevation shadow. `default`, `transparent`, and `muted` ring in `--color-accent`; each palette variant rings in its `--color-border-<name>`; a theme-added variant rings in `--selectable-card-ring-color`. Selection also colors the border in the ring color where Card draws one, which is only the `default` variant. | Current source and tests |-| FR4 | While enabled, the surface paints the shared hover overlay under a hover-capable pointer and the pressed overlay for mouse and touch presses. Keyboard focus on the hidden checkbox shows one indicator on the card root (`architecture:interaction-modality` INV3). Implementation gap: the root outlines while any descendant has `:focus-visible`, so focusing a nested control draws both the card outline and the control's own (Current-state impact). | Current source and tests |+| FR4 | While enabled, the surface paints the shared hover overlay under a hover-capable pointer and the pressed overlay for mouse and touch presses; a touch press that starts on a nested interactive element shows no pressed paint, since it does not activate the card, while a mouse press there keeps the `:active` paint. Keyboard focus on the hidden checkbox shows one indicator on the card root (`architecture:interaction-modality` INV3). Implementation gap: the root outlines while any descendant has `:focus-visible`, so focusing a nested control draws both the card outline and the control's own (Current-state impact). | Current source and tests || FR5 | `isDisabled` dims the card to half opacity, removes the card's own click and mouseup handling and the caller's `onClick` and `onMouseUp` (other caller event props still reach the root) and the hover and pressed overlays (`spec:AST-085` FR6), and keeps the checkbox focusable with `aria-disabled="true"`; no click, Space, or Enter calls `onChange`. The disabled state is reflected on the owning target (`architecture:component-theming-surface` INV6). Implementation gap: the `selectable-card` target reflects `variant` and `selected` but not the disabled state (Current-state impact). | Current source and tests || FR6 | `ref` reaches the Card root. Supported DOM, ARIA, data, and event props reach the root; `xstyle`, `className`, and `style` merge after the component's interactive styles. | Current source and tests |diff --git a/docs/specs/components/TreeList/TreeList.spec.md b/docs/specs/components/TreeList/TreeList.spec.mdindex 0de4b600fe..be9d4a5883 100644--- a/docs/specs/components/TreeList/TreeList.spec.md+++ b/docs/specs/components/TreeList/TreeList.spec.md@@ -110,7 +110,7 @@ Supporting one does not justify omitting another from the durable contract.| FR4 | Item description is a stable library-rendered part below Item label and currently has no public target. It does not inherit through `tree-list-item-label`; both spans are siblings inside the row content. | Current source and target docs | Current reachability gap; no new target is accepted || FR5 | `TreeListItemData` MUST admit `className`, `style`, and `xstyle` as one per-item styling seam. Every supplied value MUST compose on the same Item row box; an implementation MUST NOT treat current support for only one mechanism as authority to exclude the other two. | Owner decision; `architecture:public-component-api` INV5–INV6; `spec:AST-002/DEC-1` | Settled intent; implementation may be staged || FR6 | The Item row box is the logical element that paints the row, owns its hover state, and contains Start content, Item label and description, and End content. The styling seam MUST NOT move to the semantic `<li>` or another element without a compatibility decision. | Owner decision and the caller-owned per-row interaction boundary | Settled intent |-| FR7 | A click on an Item row outside its Item label performs the row's action: an Item with `onClick` runs it; otherwise an Item with children toggles; otherwise an Item whose only action is its link follows that link as Enter does, with modified and middle clicks following the shared enlarged-surface rule in `family:navigation-destinations`. The Chevron and controls in Start content and End content keep their own activation, and a disabled Item does nothing. A press inside an open Tooltip or HoverCard surface performs no row action (`component:Tooltip` FR11). | Owner decision; `family:navigation-destinations` | Settled intent; implementation may be staged |+| FR7 | A click on an Item row outside its Item label performs the row's action: an Item with `onClick` runs it; otherwise an Item with children toggles; otherwise an Item whose only action is its link follows that link as Enter does, with modified and middle clicks following the shared enlarged-surface rule in `family:navigation-destinations`. The Chevron and controls in Start content and End content keep their own activation, and on a link row a touch press that starts on one of them shows no pressed paint on the row (a mouse press keeps the `:active` paint, as `component:Item` FR9 states); a disabled Item does nothing. A press inside an open Tooltip or HoverCard surface performs no row action (`component:Tooltip` FR11). | Owner decision; `family:navigation-destinations` | Settled intent; implementation may be staged || FR8 | Expanding or collapsing an Item with children MUST play its group's own motion: under a coarse primary pointer its rows slide out from under the parent as one block, clipped to the group's box, and back on collapse, a collapsing group's rows leaving the accessibility tree as the slide starts, while the Chevron turns, by transform only, on the theme's duration and easing tokens (`spec:AST-094` FR5, FR45); under a fine pointer the group appears and leaves at once. With an `animatedLayout` handle, the group and the rows after it follow `spec:AST-105`'s shared motion under every pointer (FR4, FR5); without one, the group's own slide stays touch-only and the rows after the group take their places at once (`spec:AST-105` FR2). | UIKit outline list (`UICollectionView`), iOS 26.2; `spec:AST-105` FR2 | Proposed; awaiting an engineering owner's approval || FR9 | `TreeList` MUST accept `animatedLayout?: AnimatedLayout`. With a handle, expanding and collapsing a row report the row's size change through it, so the content after the row glides inside the handle's container, and the shown rows and the row's Chevron move on the same motion (`spec:AST-105` FR1–FR4; `spec:AST-108` FR4a). Without one, expanding and collapsing follow FR8. The prop MUST NOT change tree semantics or keyboard behavior. | `spec:AST-105` FR1, FR2; `spec:AST-108` FR4a | Current behavior |diff --git a/packages/core/api-report.md b/packages/core/api-report.mdindex 8be8627ae7..49edb3a493 100644--- a/packages/core/api-report.md+++ b/packages/core/api-report.md@@ -3871,6 +3871,7 @@ interface ClickableCardProps extends BaseProps (props of ClickableCard)interface ClickableContainerResultonClick: (event: MouseEvent<HTMLElement>) => voidonMouseUp: (event: MouseEvent<HTMLElement>) => void+ onPointerDown: (event: PointerEvent<HTMLElement>) => voidinterface CodeBlockProps extends BaseProps<HTMLPreElement> (props of CodeBlock)type CodeColor = 'primary' | 'secondary' | 'inherit'type CodeLanguagediff --git a/packages/core/src/ClickableCard/ClickableCard.nestedPress.test.tsx b/packages/core/src/ClickableCard/ClickableCard.nestedPress.test.tsxnew file mode 100644index 0000000000..fcaaa91467--- /dev/null+++ b/packages/core/src/ClickableCard/ClickableCard.nestedPress.test.tsx@@ -0,0 +1,106 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ClickableCard.nestedPress.test.tsx+ * @input vitest (jsdom), React Testing Library, ClickableCard, InfoTip, the+ * press controller+ * @output Checks that a ClickableCard shows its pressed state only for a press+ * that would activate it: a press that starts on an interactive element+ * inside the card (an InfoTip, a button, a link) paints no press on the+ * card for a finger; a press on the card's own surface still paints. A+ * mouse press keeps its `:active` paint (checked in a real browser)+ * @position Testing; validates useClickableContainer's pointerdown callback+ * through ClickableCard+ */++import {act, fireEvent, render, screen} from '@testing-library/react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {InfoTip} from '../InfoTip/InfoTip';+import {PRESS_ONSET_MS} from '../utils/pressGesture';+import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback';+import {ClickableCard} from './ClickableCard';++function Card(props: {onPointerDown?: () => void}) {+ return (+ <ClickableCard+ label="Open billing"+ onClick={() => {}}+ onPointerDown={props.onPointerDown}>+ <span>Billing summary</span>+ <InfoTip content="Billed monthly" label="About billing" />+ <button type="button">Plain button</button>+ <a href="#details">Details link</a>+ </ClickableCard>+ );+}++function cardOf(element: Element): HTMLElement {+ const card = element.closest('[data-pressable-container]');+ if (!(card instanceof HTMLElement)) {+ throw new Error('no clickable card around the element');+ }+ return card;+}++function pointer(+ element: Element,+ type: 'pointerDown' | 'pointerUp',+ pointerType: 'touch',+) {+ fireEvent[type](element, {pointerType, pointerId: 1, button: 0});+}++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+});++const nestedTargets = [+ ['an InfoTip', () => screen.getByRole('button', {name: 'About billing'})],+ ['a button', () => screen.getByRole('button', {name: 'Plain button'})],+ ['a link', () => screen.getByRole('link', {name: 'Details link'})],+] as const;++describe('a press that starts on an interactive element inside the card', () => {+ for (const [name, target] of nestedTargets) {+ it(`shows no press on the card for a finger on ${name}`, () => {+ render(<Card />);+ const element = target();+ pointer(element, 'pointerDown', 'touch');+ act(() => {+ vi.advanceTimersByTime(PRESS_ONSET_MS * 2);+ });+ expect(cardOf(element).hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);+ pointer(element, 'pointerUp', 'touch');+ });+ }+});++describe("a press on the card's own surface", () => {+ it('paints the press for a finger', () => {+ render(<Card />);+ const surface = screen.getByText('Billing summary');+ pointer(surface, 'pointerDown', 'touch');+ act(() => {+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ });+ expect(cardOf(surface).getAttribute(PRESSED_ATTRIBUTE)).toBe('on');+ pointer(surface, 'pointerUp', 'touch');+ });+});++it("calls the caller's onPointerDown beside the card's own", () => {+ const onPointerDown = vi.fn();+ render(<Card onPointerDown={onPointerDown} />);+ const element = screen.getByRole('button', {name: 'Plain button'});+ pointer(element, 'pointerDown', 'touch');+ act(() => {+ vi.advanceTimersByTime(PRESS_ONSET_MS * 2);+ });+ expect(onPointerDown).toHaveBeenCalledTimes(1);+ expect(cardOf(element).hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);+ pointer(element, 'pointerUp', 'touch');+});diff --git a/packages/core/src/ClickableCard/ClickableCard.tsx b/packages/core/src/ClickableCard/ClickableCard.tsxindex 34ae48b55b..bc12e6b14f 100644--- a/packages/core/src/ClickableCard/ClickableCard.tsx+++ b/packages/core/src/ClickableCard/ClickableCard.tsx@@ -46,6 +46,7 @@ import {} from '../theme/tokens.stylex';import type {SizeValue, SpacingStep, Elevation} from '../utils/types';import {mergeProps} from '../utils';+import {chainEventHandlers} from '../utils/chainEventHandlers';import {Card} from '../Card/Card';import type {CardVariant} from '../Card/Card';import {useClickableContainer} from '../hooks/useClickableContainer';@@ -314,6 +315,7 @@ export function ClickableCard({label,onClick: onClickProp,onMouseUp: onMouseUpProp,+ onPointerDown: onPointerDownProp,href,target,isDisabled = false,@@ -370,7 +372,7 @@ export function ClickableCard({const LinkComponent = useLinkComponent();- const {onClick, onMouseUp} = useClickableContainer({+ const {onClick, onMouseUp, onPointerDown} = useClickableContainer({containerRef,interactiveRef,onClick: onClickProp,@@ -427,6 +429,11 @@ export function ClickableCard({}onClick={!isDisabled ? onClick : undefined}onMouseUp={!isDisabled ? handleMouseUp : undefined}+ onPointerDown={+ !isDisabled+ ? chainEventHandlers(onPointerDown, onPointerDownProp)+ : onPointerDownProp+ }{...props}>{isLink ? (<LinkRootdiff --git a/packages/core/src/Item/Item.nestedPress.test.tsx b/packages/core/src/Item/Item.nestedPress.test.tsxnew file mode 100644index 0000000000..310a689b96--- /dev/null+++ b/packages/core/src/Item/Item.nestedPress.test.tsx@@ -0,0 +1,74 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Item.nestedPress.test.tsx+ * @input vitest (jsdom), React Testing Library, Item in delegation mode, the+ * press controller+ * @output Checks a delegated row's pressed state for a finger: a press on the+ * control the row delegates to paints the row, since it is the row's+ * action; a press on another control inside the row paints none+ * @position Testing; validates useClickableContainer's pointerdown callback+ * through Item+ */++import {act, fireEvent, render, screen} from '@testing-library/react';+import {useRef} from 'react';+import {afterEach, beforeEach, expect, it, vi} from 'vitest';+import {PRESS_ONSET_MS} from '../utils/pressGesture';+import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback';+import {Item} from './Item';++function DelegatingRow() {+ const ref = useRef<HTMLInputElement>(null);+ return (+ <Item+ label="Row"+ interactiveRef={ref}+ startContent={<input ref={ref} type="checkbox" aria-label="Pick row" />}+ endContent={+ <button type="button" aria-label="More">+ ⋯+ </button>+ }+ />+ );+}++function rowOf(element: Element): Element {+ const row = element.closest('[data-pressable-container]');+ if (row == null) {+ throw new Error('no delegated row around the element');+ }+ return row;+}++function fingerOn(element: Element) {+ fireEvent.pointerDown(element, {pointerType: 'touch', pointerId: 1});+ act(() => {+ vi.advanceTimersByTime(PRESS_ONSET_MS * 2);+ });+}++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+});++it("paints the row for a finger on the control it delegates to: that press is the row's action", () => {+ render(<DelegatingRow />);+ const checkbox = screen.getByRole('checkbox', {name: 'Pick row'});+ fingerOn(checkbox);+ expect(rowOf(checkbox).getAttribute(PRESSED_ATTRIBUTE)).toBe('on');+ fireEvent.pointerUp(checkbox, {pointerType: 'touch', pointerId: 1});+});++it('paints no press on the row for a finger on another control inside it', () => {+ render(<DelegatingRow />);+ const more = screen.getByRole('button', {name: 'More'});+ fingerOn(more);+ expect(rowOf(more).hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);+ fireEvent.pointerUp(more, {pointerType: 'touch', pointerId: 1});+});diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsxindex 316a0397a6..509ed694df 100644--- a/packages/core/src/Item/Item.tsx+++ b/packages/core/src/Item/Item.tsx@@ -50,6 +50,7 @@ import {import type {BaseProps} from '../BaseProps';import {isRenderable} from '../utils/isRenderable';import {mergeProps} from '../utils/mergeProps';+import {chainEventHandlers} from '../utils/chainEventHandlers';import {useFocusAcrossSwap} from '../utils/useFocusAcrossSwap';import {ItemDescriptionContext} from './ItemDescriptionContext';import {ItemMarkerColumnsContext} from './ItemMarkerColumnsContext';@@ -627,11 +628,12 @@ export function Item({const containerRef = useRef<HTMLElement | null>(null);// Only onClick is needed: onMouseUp handles middle-click href navigation,// which delegation mode never has (href is ignored here).- const {onClick: delegatedOnClick} = useClickableContainer({- containerRef,- interactiveRef: interactiveRef ?? undefined,- disabled: isDisabled,- });+ const {onClick: delegatedOnClick, onPointerDown: delegatedOnPointerDown} =+ useClickableContainer({+ containerRef,+ interactiveRef: interactiveRef ?? undefined,+ disabled: isDisabled,+ });useDevWarning('Item',@@ -896,6 +898,14 @@ export function Item({{...restProps}{...swipeHandlers}{...linkRootProps}+ {...(isDelegate+ ? {+ onPointerDown: chainEventHandlers(+ restProps.onPointerDown,+ delegatedOnPointerDown,+ ),+ }+ : null)}aria-selected={(allowsAriaSelected && isSelected) || undefined}// aria-selected is invalid on roles that don't permit it (listitem, a// bare div, etc.). For those, convey selection via aria-current — validdiff --git a/packages/core/src/SelectableCard/SelectableCard.tsx b/packages/core/src/SelectableCard/SelectableCard.tsxindex f4c2d262b7..0f2188f70d 100644--- a/packages/core/src/SelectableCard/SelectableCard.tsx+++ b/packages/core/src/SelectableCard/SelectableCard.tsx@@ -44,6 +44,7 @@ import type {StyleXStyles} from '@stylexjs/stylex';import {colorVars, durationVars, easeVars} from '../theme/tokens.stylex';import type {Elevation, SizeValue, SpacingStep} from '../utils/types';import {isImeKeyEvent, mergeProps} from '../utils';+import {chainEventHandlers} from '../utils/chainEventHandlers';import {Card} from '../Card/Card';import type {CardVariant} from '../Card/Card';import {useClickableContainer} from '../hooks/useClickableContainer';@@ -398,6 +399,7 @@ export function SelectableCard({onChange,onClick: onClickProp,onMouseUp: onMouseUpProp,+ onPointerDown: onPointerDownProp,isDisabled = false,children,padding,@@ -458,7 +460,7 @@ export function SelectableCard({[isDisabled, requestChange],);- const {onClick, onMouseUp} = useClickableContainer({+ const {onClick, onMouseUp, onPointerDown} = useClickableContainer({containerRef,interactiveRef,onClick: handleClick,@@ -530,6 +532,11 @@ export function SelectableCard({}onClick={!isDisabled ? composedOnClick : undefined}onMouseUp={!isDisabled ? composedOnMouseUp : undefined}+ onPointerDown={+ !isDisabled+ ? chainEventHandlers(onPointerDown, onPointerDownProp)+ : onPointerDownProp+ }{...props}onClickCapture={!isDisabled && handleLayerClickCapturediff --git a/packages/core/src/TreeList/TreeListItem.tsx b/packages/core/src/TreeList/TreeListItem.tsxindex e7d5395b27..62b60b4f53 100644--- a/packages/core/src/TreeList/TreeListItem.tsx+++ b/packages/core/src/TreeList/TreeListItem.tsx@@ -480,11 +480,12 @@ export function TreeListItem({// a plain element and both hook instances stay inert on it.const forwardsToLink = href != null && handleClick == null;const linkRowRef = useRef<HTMLDivElement>(null);- const {onClick: delegateToLink} = useClickableContainer({- containerRef: linkRowRef,- interactiveRef: linkRef,- disabled: isDisabled || !forwardsToLink,- });+ const {onClick: delegateToLink, onPointerDown: pressOnLinkRow} =+ useClickableContainer({+ containerRef: linkRowRef,+ interactiveRef: linkRef,+ disabled: isDisabled || !forwardsToLink,+ });const {onMouseUp: openLinkOnMiddleClick} = useClickableContainer({containerRef: linkRowRef,href,@@ -732,7 +733,8 @@ export function TreeListItem({)}ref={forwardsToLink ? linkRowRef : undefined}onClick={forwardsToLink ? delegateToLink : handleClick}- onMouseUp={forwardsToLink ? openLinkOnMiddleClick : undefined}>+ onMouseUp={forwardsToLink ? openLinkOnMiddleClick : undefined}+ onPointerDown={forwardsToLink ? pressOnLinkRow : undefined}><div {...stylex.props(styles.indentedContent)}>{innerContent}</div></div></div>diff --git a/packages/core/src/hooks/useClickableContainer.doc.mjs b/packages/core/src/hooks/useClickableContainer.doc.mjsindex d47236c36b..7b6b3b2cff 100644--- a/packages/core/src/hooks/useClickableContainer.doc.mjs+++ b/packages/core/src/hooks/useClickableContainer.doc.mjs@@ -61,12 +61,17 @@ export const docs = {type: '(event: MouseEvent<HTMLElement>) => void',description: 'Mouse up handler to attach to the container (handles middle-click navigation for href).',},+ {+ name: 'onPointerDown',+ type: '(event: PointerEvent<HTMLElement>) => void',+ description: 'Pointer down handler to attach to the container. On a container that paints its press with usePressFeedback, it drops a touch press that starts on a nested interactive element, which does not activate the container. A mouse :active press paint is unchanged. Without it, the container keeps its click rules and its pressed state for every press.',+ },],usage: {description:'Makes a container element clickable while preserving nested interactive element behavior. Solves the "nested interactive elements" problem: when a card is clickable but contains buttons/links, clicking those should NOT trigger the card\'s action. Detects interactive ancestors between the click target and the container, and ignores text selections. Supports href navigation (including middle-click and Ctrl/Cmd+click for new tabs).',bestPractices: [- { guidance: true, description: 'Attach both onClick and onMouseUp to the container element for full click handling including middle-click.' },+ { guidance: true, description: 'Attach onClick, onMouseUp and onPointerDown to the container element: full click handling including middle-click, and no touch pressed state for a press on a nested control.' },{ guidance: true, description: 'Use inside ClickableCard or SelectableCard for the standard card interaction pattern.' },{ guidance: false, description: 'Use when the entire container is a single interactive element; just use a <button> or <a> directly.' },],@@ -93,12 +98,13 @@ export const docsDense = {returnDescriptions: {onClick: 'click handler for container element.',onMouseUp: 'mouse up handler for container (handles middle-click navigation for href).',+ onPointerDown: 'pointer down handler for container: drops usePressFeedback touch press starting on nested interactive element; mouse :active paint unchanged.',},usage: {description:'Makes container element clickable while preserving nested interactive element behavior. Solves "nested interactive elements" problem: when card is clickable but contains buttons/links, clicking those must NOT trigger card\'s action. Detects interactive ancestors between click target + container, ignores text selections. Supports href navigation (incl. middle-click + Ctrl/Cmd+click for new tabs).',bestPractices: [- { guidance: true, description: 'Attach both onClick + onMouseUp to container element for full click handling incl. middle-click.' },+ { guidance: true, description: 'Attach onClick + onMouseUp + onPointerDown to container element: full click handling incl. middle-click, no touch pressed state for press on nested control.' },{ guidance: true, description: 'Use inside ClickableCard / SelectableCard for standard card interaction pattern.' },{ guidance: false, description: 'Use when entire container is single interactive element; just use <button> / <a> directly.' },],diff --git a/packages/core/src/hooks/useClickableContainer.test.tsx b/packages/core/src/hooks/useClickableContainer.test.tsxindex 81dcede631..79a44f2b64 100644--- a/packages/core/src/hooks/useClickableContainer.test.tsx+++ b/packages/core/src/hooks/useClickableContainer.test.tsx@@ -16,6 +16,12 @@ import {useRef} from 'react';import {fireEvent, render, screen} from '@testing-library/react';import {useClickableContainer} from './useClickableContainer';+const {cancelPress} = vi.hoisted(() => ({cancelPress: vi.fn()}));+vi.mock('../utils/pressFeedback', async importOriginal => ({+ ...(await importOriginal<typeof import('../utils/pressFeedback')>()),+ cancelPress,+}));+// The scheme the rule exists to stop (kept in consts so the JSX below stays// lint-clean — the tests are ABOUT these URLs never navigating).const scriptUrl = 'javascript:alert(1)';@@ -234,3 +240,55 @@ describe('useClickableContainer navigation — blocked href keeps the rest', ()expect(open).not.toHaveBeenCalled();});});++describe('onPointerDown', () => {+ function Harness({disabled = false}: {disabled?: boolean}) {+ const containerRef = useRef<HTMLDivElement>(null);+ const {onClick, onPointerDown} = useClickableContainer({+ containerRef,+ onClick: () => {},+ disabled,+ });+ return (+ <div+ data-testid="container"+ ref={containerRef}+ onClick={onClick}+ onPointerDown={onPointerDown}>+ <span>Surface</span>+ <button type="button">Nested</button>+ </div>+ );+ }++ afterEach(() => {+ cancelPress.mockClear();+ });++ it('cancels the press on the container for a finger press that starts on a nested control', () => {+ render(<Harness />);+ fireEvent.pointerDown(screen.getByRole('button', {name: 'Nested'}), {+ pointerType: 'touch',+ });+ expect(cancelPress).toHaveBeenCalledWith(screen.getByTestId('container'));+ });++ it('leaves a mouse or pen press to the paint it has today', () => {+ render(<Harness />);+ const nested = screen.getByRole('button', {name: 'Nested'});+ fireEvent.pointerDown(nested, {pointerType: 'mouse'});+ fireEvent.pointerDown(nested, {pointerType: 'pen'});+ expect(cancelPress).not.toHaveBeenCalled();+ });++ it('leaves a finger press on the surface, or in a disabled container, alone', () => {+ const {unmount} = render(<Harness />);+ fireEvent.pointerDown(screen.getByText('Surface'), {pointerType: 'touch'});+ unmount();+ render(<Harness disabled />);+ fireEvent.pointerDown(screen.getByRole('button', {name: 'Nested'}), {+ pointerType: 'touch',+ });+ expect(cancelPress).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/hooks/useClickableContainer.ts b/packages/core/src/hooks/useClickableContainer.tsindex 6d0d4e24e5..2cf16f4d98 100644--- a/packages/core/src/hooks/useClickableContainer.ts+++ b/packages/core/src/hooks/useClickableContainer.ts@@ -5,19 +5,28 @@/*** @file useClickableContainer.ts* @input Container ref, interactive element ref, click/href handlers- * @output onClick and onMouseUp handlers for the container; INTERACTIVE_SELECTORS list;+ * @output onClick, onMouseUp and onPointerDown handlers for the container;+ * INTERACTIVE_SELECTORS list;* hasInteractiveAncestor and the shared innermostInteractive walk* @position Core hook for clickable containers with nested interactive* elements. A click on a nested button or link does not run the card's- * action. Each navigation passes the rule in utils/safeUrl.ts first.+ * action, and a finger press there shows no press on the card. Each navigation+ * passes the rule in utils/safeUrl.ts first.** SYNC: When modified, update:* - /packages/core/src/hooks/index.ts (export)*/-import {useCallback, useEffect, type RefObject, type MouseEvent} from 'react';+import {+ useCallback,+ useEffect,+ type RefObject,+ type MouseEvent,+ type PointerEvent,+} from 'react';import {isLayerSurface} from '../Layer/layerSurfacePress';import {isSafeUrl} from '../utils/safeUrl';+import {cancelPress} from '../utils/pressFeedback';/*** The attribute this hook sets on the container it makes clickable. A click@@ -159,6 +168,14 @@ export interface UseClickableContainerOptions {export interface ClickableContainerResult {onClick: (event: MouseEvent<HTMLElement>) => void;onMouseUp: (event: MouseEvent<HTMLElement>) => void;+ /**+ * Spread on the container with `onClick`. A press that starts on a nested+ * interactive element does not activate the container. On a container that+ * paints its press with `usePressFeedback`, this drops that touch press.+ * A mouse `:active` press paint is unchanged. A container without it keeps+ * its activation rule and shows its pressed state for every press.+ */+ onPointerDown: (event: PointerEvent<HTMLElement>) => void;}/**@@ -176,12 +193,16 @@ export interface ClickableContainerResult {* @example* ```* const containerRef = useRef<HTMLDivElement>(null);- * const { onClick, onMouseUp } = useClickableContainer({+ * const { onClick, onMouseUp, onPointerDown } = useClickableContainer({* containerRef,* onClick: () => console.log('card clicked'),* });* return (- * <div ref={containerRef} onClick={onClick} onMouseUp={onMouseUp}>+ * <div+ * ref={containerRef}+ * onClick={onClick}+ * onMouseUp={onMouseUp}+ * onPointerDown={onPointerDown}>* <p>Click anywhere on this card</p>* <button onClick={() => alert('button')}>Nested button</button>* </div>@@ -305,5 +326,30 @@ export function useClickableContainer({[containerRef, href, disabled],);- return {onClick, onMouseUp};+ // The press-state counterpart of onClick's rule, for touch: a finger press+ // that would not activate the container shows no press on it. A mouse or+ // pen press keeps its `:active` paint.+ const onPointerDown = useCallback(+ (event: PointerEvent<HTMLElement>) => {+ const containerEl = containerRef.current;+ const eventTarget = event.target;+ if (+ event.pointerType !== 'touch' ||+ disabled ||+ containerEl == null ||+ !(eventTarget instanceof Element) ||+ eventTarget === event.currentTarget ||+ !hasInteractiveAncestor(eventTarget, containerEl) ||+ // The control the container delegates to is the container's own+ // action: a press on it activates the container.+ interactiveRef?.current?.contains(eventTarget) === true+ ) {+ return;+ }+ cancelPress(containerEl);+ },+ [containerRef, interactiveRef, disabled],+ );++ return {onClick, onMouseUp, onPointerDown};}diff --git a/packages/core/src/utils/pressFeedback.ts b/packages/core/src/utils/pressFeedback.tsindex d2602d579a..3eb167b1db 100644--- a/packages/core/src/utils/pressFeedback.ts+++ b/packages/core/src/utils/pressFeedback.ts@@ -6,7 +6,7 @@* press-group markers and the document's pointer, keyboard, scroll and* visibility events* @output PRESSABLE_ATTRIBUTE, PRESSED_ATTRIBUTE, pressableProps,- * pressFadeMs and installPressFeedback+ * pressFadeMs, installPressFeedback and cancelPress* @position The DOM half of the touch press model. usePressFeedback installs* it, and the CSS arms live in interactionOverlay.stylex.ts.*@@ -381,6 +381,21 @@ function finish(slot: Slot): void {}}+/**+ * Ends the press the controller follows on `element`, and its paint, at once.+ * A clickable container calls it when a press starts on an interactive+ * element inside it: that press does not activate the container, so the+ * container shows no press.+ */+export function cancelPress(element: Element): void {+ if (finger.live?.element === element) {+ finish(finger);+ }+ if (button.live?.element === element) {+ finish(button);+ }+}+/** A new press on an element owns its paint: the other slot's gesture there ends. */function takeOver(other: Slot, element: HTMLElement): void {if (other.live?.element === element) {