Skip to content

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

TypeScript

fix(core): a finger press on a control inside a list row, TreeList row or Token shows no press on it (#9959)

Cindy Zhang67ad50980715
diff --git a/.changeset/nested-touch-press-all-containers.md b/.changeset/nested-touch-press-all-containers.md
new file mode 100644
index 0000000000..a4e76db598
--- /dev/null
+++ b/.changeset/nested-touch-press-all-containers.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] With a finger, a press that starts on a control inside a list row with `onClick` or `href`, a TreeList row with `onClick` or children, or a clickable or link Token with `onRemove` no longer makes the row or token look pressed, since it does not run the row's or token's action. A press on the row or token itself still looks pressed. Mouse presses are unchanged.
+
+@cixzhang
diff --git a/docs/specs/components/Item/Item.spec.md b/docs/specs/components/Item/Item.spec.md
index a7cba229df..29a43e2bae 100644
--- a/docs/specs/components/Item/Item.spec.md
+++ b/docs/specs/components/Item/Item.spec.md
@@ -13,6 +13,7 @@ review_triggers: [public-api, layout, theming]
verified_by:
[
packages/core/src/Item/Item.test.tsx,
+ packages/core/src/hooks/nestedTouchPress.adopters.test.tsx,
packages/core/src/List/List.test.tsx,
packages/core/src/RadioList/RadioList.test.tsx,
packages/core/src/CheckboxList/CheckboxList.test.tsx,
@@ -102,17 +103,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 |
-| 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 |
+| 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 | An interactive row (an `onClick` row, an `href` row, or a delegated row with `interactiveRef`) shows its touch pressed paint only for a press that would activate it: a finger press on the row's surface or on its own action (its invisible button or link, or the control it delegates to) paints the row, and a finger press that starts on another interactive element inside the row paints none. In a row with a parent-supplied `role`, or a row whose root is a link, a press on a nested control activates the row, so it paints. 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
@@ -186,7 +187,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| 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` |
+| FR9 | `nestedTouchPress.adopters.test.tsx`; `Item.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` |
diff --git a/docs/specs/components/Token/Token.spec.md b/docs/specs/components/Token/Token.spec.md
index 9f7a4879cb..63414ca83f 100644
--- a/docs/specs/components/Token/Token.spec.md
+++ b/docs/specs/components/Token/Token.spec.md
@@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, layout, theming, accessibility]
verified_by:
[
packages/core/src/Token/Token.test.tsx,
+ packages/core/src/hooks/nestedTouchPress.adopters.test.tsx,
packages/core/src/Token/__tests__/TokenRemoveTarget.a11y.chromium.spec.ts,
packages/core/src/theme/themingTargets.test.ts,
packages/core/src/theme/extensibleAxes.test.ts,
@@ -126,7 +127,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR3 | With an enabled `href` and no `onRemove`, the token root is the shared link component carrying the destination; it takes the root ref, passthrough props, and its own focus-visible outline. A supplied `onClick`, as an accepted event input, reaches the element that owns the contract (`architecture:public-component-api` INV5). Implementation gap: in both link structures `onClick` is not attached or called (Current-state impact). | Current source and tests |
| FR4 | With `onClick`, or an enclosing trigger context that resolves the token to a button, the root is a `span` container holding an inner `button` that wraps only the Label and calls `onClick`; a click on the container outside any nested button or link also calls `onClick`, except a click inside an open Tooltip or HoverCard surface (`component:Tooltip` FR11). With an enabled `href` and `onRemove`, the container instead holds an inner link wrapping only the Label; a plain click on the surface outside the Remove button follows that link, and a Cmd/Ctrl-click or middle click on the surface opens it in a new tab. A caller `onMouseUp` on the link-and-remove container runs before its delegation. | Current source and tests |
| FR5 | A disabled token renders at half opacity with pointer events off and fires neither `onClick` nor `onRemove` from pointer, Enter, or Space; inner and Remove buttons stay focusable with `aria-disabled="true"` and never receive native `disabled`. A disabled control keeps its tab stop and exposes its disabled state (`spec:AST-085` FR1, FR5), and the disabled state is reflected on the owning target (`architecture:component-theming-surface` INV6). A disabled token with `href` and no `onClick` or trigger context renders a focusable link with `aria-disabled="true"` and no `href`, and every structure reflects the disabled state on the `token` target. | Current source and tests |
-| FR6 | `onRemove` renders a `type="button"` Remove button holding a close glyph; a click stops propagation before `onRemove` runs, so it never triggers the token's own action or link. The button is a sibling of the inner button or link, never nested in it. | Current source and tests |
+| FR6 | `onRemove` renders a `type="button"` Remove button holding a close glyph; a click stops propagation before `onRemove` runs, so it never triggers the token's own action or link. The button is a sibling of the inner button or link, never nested in it. A finger press that starts on the Remove button, or on a control in end content, paints no press on the token, since it does not run the token's own action; a mouse press keeps the token's `:active` paint. | Current source and tests |
| FR7 | The label never wraps: the root is capped at its container's inline size and clips overflow. In the static and link structures the Label ends in an ellipsis; in the clickable and link-and-remove structures the inner control clips the Label without an ellipsis. `isLabelHidden` keeps the Label in the DOM with a visually hidden clip treatment. | Current source and tests |
| FR8 | `color` defaults to `default`, painting `--color-neutral` with primary text; every other built-in tone paints its tinted background with its matching colored text. The `token` target reflects the resolved `color` and `size` for every value, including a theme-added color, which receives no component fill or text color until a theme paints it. | Current source and tests |
| FR9 | Clickable and link structures paint the shared hover overlay under a hover-capable pointer and the shared pressed overlay for mouse and touch presses; the static structure paints neither. | Current source |
diff --git a/docs/specs/components/TreeList/TreeList.spec.md b/docs/specs/components/TreeList/TreeList.spec.md
index be9d4a5883..3311177b36 100644
--- a/docs/specs/components/TreeList/TreeList.spec.md
+++ b/docs/specs/components/TreeList/TreeList.spec.md
@@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, theming, accessibility]
verified_by:
[
packages/core/src/TreeList/TreeList.test.tsx,
+ packages/core/src/hooks/nestedTouchPress.adopters.test.tsx,
packages/core/src/TreeList/__tests__/TreeListGuideAlignment.interaction.browser.spec.ts,
packages/core/src/theme/themingTargets.test.ts,
scripts/check-knowledge.mjs,
@@ -102,17 +103,17 @@ Supporting one does not justify omitting another from the durable contract.
## Behavioral and layout contract
-| ID | Invariant | Basis | Contract state |
-| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------- |
-| FR1 | The current render contains one Tree list, one Item and Item label per rendered node, optional Header, Chevron, Item description, Start content, End content, and Guide parts, and delegated Chevron glyphs. | Current source, docs, and tests | Current behavior |
-| FR2 | Tree list, Item, Chevron, Item label, and Guide carry the five current `tree-list*` targets documented below. | Current source and target docs | Current behavior |
-| FR3 | Chevron glyph delegates to Icon's `icon` target. Header, Start content, and End content are consumer-owned and have no TreeList target. | Current source and component docs | Current ownership |
-| 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 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 |
+| ID | Invariant | Basis | Contract state |
+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------- |
+| FR1 | The current render contains one Tree list, one Item and Item label per rendered node, optional Header, Chevron, Item description, Start content, End content, and Guide parts, and delegated Chevron glyphs. | Current source, docs, and tests | Current behavior |
+| FR2 | Tree list, Item, Chevron, Item label, and Guide carry the five current `tree-list*` targets documented below. | Current source and target docs | Current behavior |
+| FR3 | Chevron glyph delegates to Icon's `icon` target. Header, Start content, and End content are consumer-owned and have no TreeList target. | Current source and component docs | Current ownership |
+| 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 on any row a touch press that starts on one of them, or on the Chevron of a row whose surface runs a different action, 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 |
### Allowed variation
diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsx
index 287719efc2..80c40fb5b0 100644
--- a/packages/core/src/Item/Item.tsx
+++ b/packages/core/src/Item/Item.tsx
@@ -58,7 +58,10 @@ import {ItemMarkerColumnsContext} from './ItemMarkerColumnsContext';
import {useMergedRefs} from '../hooks/useMergedRefs';
import {computeTargetAndRel} from '../Link/computeTargetAndRel';
import {useLinkComponent} from '../Link/useLinkComponent';
-import {useClickableContainer} from '../hooks/useClickableContainer';
+import {
+ cancelNestedTouchPress,
+ useClickableContainer,
+} from '../hooks/useClickableContainer';
import {useDevWarning} from '../hooks/useDevWarning';
import {themeProps} from '../utils/themeProps';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
@@ -620,7 +623,11 @@ export function Item({
// the router link component, which may require a live href. The element type
// then changes with `isDisabled`, so focus follows the swap (FR4).
const RowAnchor = isDisabled ? 'a' : LinkComponent;
- const anchorRef = useFocusAcrossSwap<HTMLAnchorElement>();
+ // The row's own action, its invisible link or button: a press on it
+ // activates the row.
+ const actionLinkRef = useRef<HTMLAnchorElement | null>(null);
+ const actionButtonRef = useRef<HTMLButtonElement | null>(null);
+ const anchorRef = useFocusAcrossSwap<HTMLAnchorElement>(actionLinkRef);
// Delegation mode: the row is an enlarged click/tap target for a nested
// control (e.g. a checkbox) that owns the keyboard access and action. The
@@ -654,6 +661,18 @@ export function Item({
// component means the root itself is the anchor, so the address rides it
// and the invisible anchor below is not rendered.
const isLinkRoot = typeof Component !== 'string' && href != null;
+ // A press on a nested control does not run this row's action, so the row
+ // shows no touch press. A row with a parent role or a link root runs it, so
+ // it keeps the press. Such a row is not a clickable container: an enclosing
+ // card still treats it as part of its own surface.
+ const hasOwnAction =
+ (onClick != null || href != null) && !hasParentRole && !isLinkRoot;
+ const pressOnRow = (event: React.PointerEvent<HTMLElement>) =>
+ cancelNestedTouchPress(
+ event,
+ event.currentTarget,
+ href != null ? actionLinkRef.current : actionButtonRef.current,
+ );
// Swipe actions exist where the row's role permits interactive descendants
// (a swipe panel's buttons are such descendants): a `listitem`, or no role
@@ -812,6 +831,7 @@ export function Item({
</RowAnchor>
) : onClick != null ? (
<button
+ ref={actionButtonRef}
type="button"
onClick={onClick}
disabled={isDisabled}
@@ -906,7 +926,14 @@ export function Item({
delegatedOnPointerDown,
),
}
- : null)}
+ : hasOwnAction && !isDisabled
+ ? {
+ onPointerDown: chainEventHandlers(
+ swipeHandlers?.onPointerDown ?? restProps.onPointerDown,
+ pressOnRow,
+ ),
+ }
+ : 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 — valid
diff --git a/packages/core/src/Token/Token.tsx b/packages/core/src/Token/Token.tsx
index 0b15aba6da..0fb94aac07 100644
--- a/packages/core/src/Token/Token.tsx
+++ b/packages/core/src/Token/Token.tsx
@@ -39,6 +39,7 @@ import {themeProps} from '../utils/themeProps';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';
import {usePressFeedback} from '../hooks/usePressFeedback';
+import {cancelNestedTouchPress} from '../hooks/useClickableContainer';
import type {TokenColorMap} from './index';
import {disabledInteractionProps} from '../utils/disabledInteraction';
import {TokenNamingContext} from './TokenNamingContext';
@@ -510,6 +511,19 @@ export function Token({
}
effectiveOnClick(e);
};
+ // A finger press on Remove or a control in end content does not run the
+ // token's action, so the token shows no press for it. The inner button,
+ // the first button child, is the token's own action.
+ const handleContainerPointerDown = (
+ e: React.PointerEvent<HTMLSpanElement>,
+ ) => {
+ rest.onPointerDown?.(e);
+ cancelNestedTouchPress(
+ e,
+ e.currentTarget,
+ e.currentTarget.querySelector(':scope > button'),
+ );
+ };
return (
<span
@@ -535,7 +549,10 @@ export function Token({
style,
)}
{...rest}
- {...sharedProps}>
+ {...sharedProps}
+ onPointerDown={
+ isDisabled ? rest.onPointerDown : handleContainerPointerDown
+ }>
{icon}
<button
type="button"
diff --git a/packages/core/src/Token/TokenLink.tsx b/packages/core/src/Token/TokenLink.tsx
index 4c536292fe..792a0566a4 100644
--- a/packages/core/src/Token/TokenLink.tsx
+++ b/packages/core/src/Token/TokenLink.tsx
@@ -90,12 +90,13 @@ export function TokenLink({
removeButton,
onClick: onClickProp,
onMouseUp: onMouseUpProp,
+ onPointerDown: onPointerDownProp,
...containerProps
}: TokenLinkProps) {
const containerRef = useRef<HTMLElement | null>(null);
const linkRef = useRef<HTMLElement | null>(null);
- const {onClick, onMouseUp} = useClickableContainer({
+ const {onClick, onMouseUp, onPointerDown} = useClickableContainer({
containerRef,
interactiveRef: linkRef,
href,
@@ -113,6 +114,11 @@ export function TokenLink({
isDisabled
? onMouseUpProp
: composeEventHandlers(onMouseUpProp, onMouseUp)
+ }
+ onPointerDown={
+ isDisabled
+ ? onPointerDownProp
+ : composeEventHandlers(onPointerDownProp, onPointerDown)
}>
{icon}
{isDisabled ? (
diff --git a/packages/core/src/TreeList/TreeListItem.tsx b/packages/core/src/TreeList/TreeListItem.tsx
index 4ae5429ff7..40858be52e 100644
--- a/packages/core/src/TreeList/TreeListItem.tsx
+++ b/packages/core/src/TreeList/TreeListItem.tsx
@@ -31,6 +31,7 @@ import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';
import {rowPressLayerStyles} from '../privateAttributes/press.stylex';
import {usePressFeedback} from '../hooks/usePressFeedback';
import {
+ cancelNestedTouchPress,
hasInteractiveAncestor,
useClickableContainer,
} from '../hooks/useClickableContainer';
@@ -482,12 +483,33 @@ 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, onPointerDown: pressOnLinkRow} =
- useClickableContainer({
- containerRef: linkRowRef,
- interactiveRef: linkRef,
- disabled: isDisabled || !forwardsToLink,
- });
+ const {onClick: delegateToLink} = useClickableContainer({
+ containerRef: linkRowRef,
+ interactiveRef: linkRef,
+ disabled: isDisabled || !forwardsToLink,
+ });
+
+ // A finger press that starts on a control inside the row does not activate
+ // the row, so the row shows no press for it. The row's own action, its link
+ // or invisible button, activates it. The Chevron does too when the row's
+ // surface toggles, since it runs that same toggle.
+ const actionButtonRef = useRef<HTMLButtonElement>(null);
+ const chevronRef = useRef<HTMLButtonElement>(null);
+ const surfaceToggles = onClick == null && handleClick != null;
+ const pressOnRow = (event: React.PointerEvent<HTMLDivElement>) => {
+ if (isDisabled) {
+ return;
+ }
+ const chevron = chevronRef.current;
+ const ownAction =
+ surfaceToggles &&
+ chevron != null &&
+ event.target instanceof Node &&
+ chevron.contains(event.target)
+ ? chevron
+ : (linkRef.current ?? actionButtonRef.current);
+ cancelNestedTouchPress(event, event.currentTarget, ownAction);
+ };
const {onMouseUp: openLinkOnMiddleClick} = useClickableContainer({
containerRef: linkRowRef,
href,
@@ -569,6 +591,7 @@ export function TreeListItem({
// focusable element to receive Enter/Space). The row's handleClick ignores
// clicks originating inside a <button>, so this never double-toggles.
<button
+ ref={chevronRef}
type="button"
aria-expanded={isExpanded}
aria-label={t('@astryx.treeList.toggleChildren')}
@@ -645,6 +668,7 @@ export function TreeListItem({
</LinkComponent>
) : onClick != null ? (
<button
+ ref={actionButtonRef}
type="button"
onClick={onClick}
aria-disabled={isDisabled || undefined}
@@ -740,7 +764,9 @@ export function TreeListItem({
ref={forwardsToLink ? linkRowRef : undefined}
onClick={forwardsToLink ? delegateToLink : handleClick}
onMouseUp={forwardsToLink ? openLinkOnMiddleClick : undefined}
- onPointerDown={forwardsToLink ? pressOnLinkRow : undefined}>
+ onPointerDown={
+ forwardsToLink || handleClick != null ? pressOnRow : undefined
+ }>
<div {...stylex.props(styles.indentedContent)}>{innerContent}</div>
</div>
</div>
diff --git a/packages/core/src/hooks/nestedTouchPress.adopters.test.tsx b/packages/core/src/hooks/nestedTouchPress.adopters.test.tsx
new file mode 100644
index 0000000000..403188bac9
--- /dev/null
+++ b/packages/core/src/hooks/nestedTouchPress.adopters.test.tsx
@@ -0,0 +1,219 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file nestedTouchPress.adopters.test.tsx
+ * @input vitest (jsdom), React Testing Library, every container that paints
+ * a press and has nested controls, the press controller
+ * @output Checks, for each such container, that a finger press that starts on
+ * a control inside it paints no press on the container, and that a finger
+ * press on the container's own surface or its own action still paints
+ * @position Testing; validates useClickableContainer's touch press rule
+ * across its adopters. A mouse press keeps its `:active` paint; the hook's
+ * own tests check that a mouse or pen press is left alone.
+ */
+
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import {useState, type ReactElement} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {PRESS_ONSET_MS} from '../utils/pressGesture';
+import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback';
+import {SelectableCard} from '../SelectableCard/SelectableCard';
+import {TreeList} from '../TreeList/TreeList';
+import {List} from '../List/List';
+import {ListItem} from '../List/ListItem';
+import {Token} from '../Token/Token';
+import {ClickableCard} from '../ClickableCard/ClickableCard';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+/** Holds a finger on `element` past the press onset; returns whether anything painted a press. */
+function fingerPaints(element: Element): boolean {
+ fireEvent.pointerDown(element, {
+ pointerType: 'touch',
+ pointerId: 1,
+ button: 0,
+ });
+ act(() => {
+ vi.advanceTimersByTime(PRESS_ONSET_MS * 2);
+ });
+ const painted = document.querySelector(`[${PRESSED_ATTRIBUTE}="on"]`) != null;
+ fireEvent.pointerUp(element, {pointerType: 'touch', pointerId: 1, button: 0});
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ return painted;
+}
+
+const Inner = () => <button type="button">Inner</button>;
+const inner = () => screen.getByRole('button', {name: 'Inner'});
+
+function Selectable(): ReactElement {
+ const [isSelected, setIsSelected] = useState(false);
+ return (
+ <SelectableCard
+ label="Pick"
+ isSelected={isSelected}
+ onChange={setIsSelected}>
+ <span>Surface</span>
+ <Inner />
+ </SelectableCard>
+ );
+}
+
+const removeButton = () => screen.getByRole('button', {name: /remove/i});
+
+const containers: ReadonlyArray<
+ readonly [string, () => ReactElement, () => Element, () => Element]
+> = [
+ [
+ 'SelectableCard',
+ () => <Selectable />,
+ inner,
+ () => screen.getByText('Surface'),
+ ],
+ [
+ 'ListItem with onClick',
+ () => (
+ <List>
+ <ListItem label="Row" onClick={() => {}} endContent={<Inner />} />
+ </List>
+ ),
+ inner,
+ () => screen.getByText('Row'),
+ ],
+ [
+ 'ListItem with href',
+ () => (
+ <List>
+ <ListItem label="Link row" href="#row" endContent={<Inner />} />
+ </List>
+ ),
+ inner,
+ () => screen.getByText('Link row'),
+ ],
+ [
+ 'TreeList link row',
+ () => (
+ <TreeList
+ items={[{id: 'a', label: 'Docs', href: '#docs', endContent: <Inner />}]}
+ />
+ ),
+ inner,
+ () => screen.getByText('Docs'),
+ ],
+ [
+ 'TreeList row with onClick',
+ () => (
+ <TreeList
+ items={[
+ {id: 'b', label: 'Run', onClick: () => {}, endContent: <Inner />},
+ ]}
+ />
+ ),
+ inner,
+ () => screen.getByText('Run'),
+ ],
+ [
+ 'TreeList parent row',
+ () => (
+ <TreeList
+ items={[
+ {
+ id: 'c',
+ label: 'Folder',
+ endContent: <Inner />,
+ children: [{id: 'd', label: 'File'}],
+ },
+ ]}
+ />
+ ),
+ inner,
+ () => screen.getByText('Folder'),
+ ],
+ [
+ 'Token with href and onRemove',
+ () => <Token label="Tag" href="#tag" onRemove={() => {}} />,
+ removeButton,
+ () => screen.getByText('Tag'),
+ ],
+ [
+ 'Token with onClick and onRemove',
+ () => <Token label="Filter" onClick={() => {}} onRemove={() => {}} />,
+ removeButton,
+ () => screen.getByText('Filter'),
+ ],
+];
+
+describe('a finger press inside a container that paints a press', () => {
+ for (const [name, ui, child, surface] of containers) {
+ describe(name, () => {
+ it('paints no press on the container for a finger on a control inside it', () => {
+ render(ui());
+ expect(fingerPaints(child())).toBe(false);
+ });
+
+ it('paints the press for a finger on the container itself', () => {
+ render(ui());
+ expect(fingerPaints(surface())).toBe(true);
+ });
+ });
+ }
+});
+
+describe('the Chevron of a TreeList row', () => {
+ const chevron = () => screen.getByRole('button', {name: /children/i});
+
+ it("paints the row when the row's surface toggles, since the Chevron runs that toggle", () => {
+ render(
+ <TreeList
+ items={[
+ {id: 'p', label: 'Folder', children: [{id: 'k', label: 'File'}]},
+ ]}
+ />,
+ );
+ expect(fingerPaints(chevron())).toBe(true);
+ });
+
+ it("paints no press when the row's surface runs a different action", () => {
+ render(
+ <TreeList
+ items={[
+ {
+ id: 'q',
+ label: 'Open',
+ onClick: () => {},
+ children: [{id: 'm', label: 'Child'}],
+ },
+ ]}
+ />,
+ );
+ expect(fingerPaints(chevron())).toBe(false);
+ });
+});
+
+describe('a row with its own action inside a clickable card', () => {
+ it('stays part of the card surface: a mouse click on its start content opens the card', () => {
+ const openCard = vi.fn();
+ render(
+ <ClickableCard label="Card" onClick={openCard}>
+ <List>
+ <ListItem
+ label="Row"
+ onClick={() => {}}
+ startContent={<span>Lead</span>}
+ />
+ </List>
+ </ClickableCard>,
+ );
+ const lead = screen.getByText('Lead');
+ expect(lead.closest('[data-pressable-container]')?.tagName).not.toBe('LI');
+ fireEvent.click(lead);
+ expect(openCard).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/core/src/hooks/useClickableContainer.ts b/packages/core/src/hooks/useClickableContainer.ts
index 2cf16f4d98..cf8080391b 100644
--- a/packages/core/src/hooks/useClickableContainer.ts
+++ b/packages/core/src/hooks/useClickableContainer.ts
@@ -127,6 +127,34 @@ function belongsToSomethingElse(element: Element): boolean {
return matchesInteractiveSelectors(element) || isLayerSurface(element);
}
+/**
+ * The touch half of a container's press rule: a finger press that starts on a nested interactive element
+ * other than the container's own action does not activate the container, so
+ * it ends the press controller's paint on `container`. A mouse or pen press,
+ * and a press on the container's surface or on `ownAction`, are left alone.
+ * Not part of the package's public API.
+ */
+export function cancelNestedTouchPress(
+ event: PointerEvent<HTMLElement>,
+ container: HTMLElement | null,
+ ownAction: Element | null,
+): void {
+ const target = event.target;
+ if (
+ event.pointerType !== 'touch' ||
+ container == null ||
+ !(target instanceof Element) ||
+ target === event.currentTarget ||
+ !hasInteractiveAncestor(target, container) ||
+ // The container's own action, such as the control it delegates to: a
+ // press on it activates the container.
+ ownAction?.contains(target) === true
+ ) {
+ return;
+ }
+ cancelPress(container);
+}
+
/**
* Check if there's a text selection inside the node (don't navigate on text select)
*
@@ -331,22 +359,14 @@ export function useClickableContainer({
// 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
- ) {
+ if (disabled) {
return;
}
- cancelPress(containerEl);
+ cancelNestedTouchPress(
+ event,
+ containerRef.current,
+ interactiveRef?.current ?? null,
+ );
},
[containerRef, interactiveRef, disabled],
);