Skip to content

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

TypeScript

fix(AlertDialog): a press that slides between the actions runs the one it lifts on (#8083)

Christopher Chedeaud43f4078596d
diff --git a/.changeset/alertdialog-touch-action-tracking.md b/.changeset/alertdialog-touch-action-tracking.md
new file mode 100644
index 0000000000..6b8bc346fb
--- /dev/null
+++ b/.changeset/alertdialog-touch-action-tracking.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] AlertDialog: its two actions are tracked as one group under every pointer, the way iOS tracks an alert's actions. A press that lands on one action and slides to the other runs the action it lifts on, and lifting off both runs nothing. The pressed action highlights at once, and the highlight follows the pointer between the actions. A second finger or the window losing focus ends the press with nothing run. A press on the title or the message is not tracked. The keyboard and assistive technology keep each button's own activation.
+
+@vjeux
diff --git a/.changeset/press-group-item-marker.md b/.changeset/press-group-item-marker.md
new file mode 100644
index 0000000000..a7f0b9d44e
--- /dev/null
+++ b/.changeset/press-group-item-marker.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the touch press controller leaves the press of an action that its group's own tracker paints (`data-astryx-press-group-item`) to that tracker, so one writer paints each press. A key's press on the action still paints as before.
+
+@vjeux
diff --git a/docs/specs/components/AlertDialog/AlertDialog.spec.md b/docs/specs/components/AlertDialog/AlertDialog.spec.md
index 7a35b27e55..1f67f08357 100644
--- a/docs/specs/components/AlertDialog/AlertDialog.spec.md
+++ b/docs/specs/components/AlertDialog/AlertDialog.spec.md
@@ -14,6 +14,8 @@ verified_by:
[
packages/core/src/AlertDialog/AlertDialog.test.tsx,
packages/core/src/AlertDialog/useImperativeAlertDialog.test.tsx,
+ packages/core/src/AlertDialog/__tests__/AlertDialog.interaction.browser.spec.ts,
+ packages/core/src/hooks/useActionGroupTracking.test.tsx,
packages/core/src/AlertDialog/__tests__/AlertDialog.a11y.test.tsx,
packages/core/src/AlertDialog/__tests__/AlertDialog.a11y.chromium.spec.ts,
packages/core/src/Dialog/Dialog.test.tsx,
@@ -50,7 +52,7 @@ system_specs:
| Behavior | A modal confirmation that interrupts: it opens through the native dialog, cannot be dismissed by a click outside, closes on Escape or Cancel through `onOpenChange(false)`, and runs `onAction` on the action button. |
| End-user impact | A keyboard or screen-reader user is told a decision is needed (the title and description are announced), lands on Cancel, and cannot lose the dialog by clicking past it. On a touch screen the alert scales in and fades out as iOS's does and ignores taps while it enters (FR6, FR7), and on a phone it is 320 px wide (FR9); under every pointer, mouse included, a press that slides from Cancel to the action runs the action it lifts on (FR8). |
| Builder impact | None. |
-| Compatibility/readiness | FR1–FR5 and AR1 record shipped behavior, apart from AR1's Tab wrap. FR6–FR9 are requirements not shipped yet. Each gap is listed under Current-state impact. |
+| Compatibility/readiness | FR1–FR5, FR8 and AR1 record shipped behavior, apart from AR1's Tab wrap. FR6, FR7 and FR9 are requirements not shipped yet. Each gap is listed under Current-state impact. |
| Review checks | Reject a modal AlertDialog without `role="alertdialog"`, a title or description not linked by id, initial focus on the destructive action, or a backdrop click that dismisses it. |
| Governing rules | `architecture:public-component-api/INV1,INV5–INV8`; `architecture:component-theming-surface/INV3–INV7`; `architecture:layer-runtime`; `component:Dialog/AR1–AR3`; `spec:AST-020/FR15`; `spec:AST-094` FR4, FR13, FR35, DEC-15, DEC-17; `family:action-groups`; `design:reduced-motion`; `spec:AST-017`. |
@@ -65,10 +67,11 @@ confirmation without assembling it.
## Compatibility and migration
-- Released default preserved: `yes` today; shipping FR6–FR9 changes the touch
- presentation, the phone width, and action activation under a slide
-- Compatibility class: nonbreaking behavior change when FR6–FR9 ship; no public
- API, DOM, or target change
+- Released default preserved: `no` — FR8 changes action activation under a
+ slide; shipping FR6, FR7 and FR9 changes the touch presentation and the
+ phone width
+- Compatibility class: nonbreaking behavior change; no public API, DOM, or
+ target change
- Controlled/uncontrolled behavior: unchanged — `isOpen` with `onOpenChange` is
controlled; `useImperativeAlertDialog` owns that pair for a caller that wants
`show`/`hide`
@@ -83,9 +86,6 @@ Consumer migration instructions belong in consumer docs and release notes.
fade-out FR6 requires.
- **Pointer input is not held while the alert enters (FR7).** A tap that lands
during the entrance reaches the alert; `spec:AST-094` FR35 holds it.
-- **The actions are not an action group yet (FR8).** A press that slides from
- Cancel to the action runs nothing on lift; each button activates on its own
- click (`family:action-groups`).
- **The phone width is not shipped (FR9).** On a phone the alert keeps its
default width rather than 320 px.
- **Tab leaves the alert (AR1).** Dialog does not yet contain Tab, so Tab from
@@ -130,7 +130,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR5 | `useImperativeAlertDialog` returns `show`, `hide`, and the element to render, and owns `isOpen`/`onOpenChange` for its caller. | shipped source and focused tests |
| FR6 | Under a touch presentation (`spec:AST-094` FR13), a modal AlertDialog presents by scaling from 1.2 to 1 with its opacity and its backdrop's dimming rising from 0 to 1 on the motion role `springs.alertPresent`, started at the browser's commit, with the larger start kept inside the viewport; it dismisses by a fade alone on `springs.alertDismiss` and closes at the fade's end; a close during the presentation, or a reopen during the dismissal, springs from where it is. The roles are internal, with UIKit's measured values at `tempo` 1 and `'standard'`, and follow the theme's motion knobs (`spec:AST-094` FR4, DEC-15). Under Reduce Motion both are the shared cross-fade (`design:reduced-motion` DR1–DR3). A fine primary pointer keeps today's motion (`spec:AST-094` FR13 and its Non-goals). Implementation gap: not shipped yet (Current-state impact). | proposed from measured iOS 26.2 behavior |
| FR7 | Under a touch presentation, pointer input to the alert is held while it enters (`spec:AST-094` FR35); keyboard and assistive-technology input are never held, and the entrance never makes the content inert. While the alert leaves, its content is inert for the dismissal fade. The hold's timing stays internal (`spec:AST-002` FR3). Implementation gap: not shipped yet (Current-state impact). | `spec:AST-094` FR35; owner decision (DEC-1) |
-| FR8 | AlertDialog's actions are an action group (`family:action-groups`): a press that slides across them runs the action it lifts on, and a lift outside them runs nothing, under every pointer; keyboard and assistive-technology behavior is unchanged. Implementation gap: not shipped yet (Current-state impact). | `family:action-groups`; `spec:AST-094` DEC-17; DEC-3 |
+| FR8 | AlertDialog's actions are an action group (`family:action-groups`): a press that slides across them runs the action it lifts on, and a lift outside them runs nothing, under every pointer; keyboard and assistive-technology behavior is unchanged. | `family:action-groups`; `spec:AST-094` DEC-17; DEC-3 |
| FR9 | On a phone, a compact window (`spec:AST-012` FR9: narrower than `md` or shorter than 500 px) under a coarse primary pointer, the alert is 320 px wide in every theme, as iOS's is; no theme role sets it. A caller's explicit `width` still wins there (`architecture:public-component-api` INV5), and Dialog's viewport clamp still applies on a screen narrower than the alert. Elsewhere it keeps today's width. Implementation gap: not shipped yet (Current-state impact). | owner decision (DEC-2) |
### Allowed variation
@@ -154,10 +154,10 @@ Consumer migration instructions belong in consumer docs and release notes.
### Performance and resources
-- **PR1 — Dialog-owned resources.** AlertDialog's own listener is the
- small-screen media query behind the button order, joined by the press
- tracking `family:action-groups` FR5 gives its actions once FR8 ships; Dialog
- owns the modal lifecycle.
+- **PR1 — Dialog-owned resources.** AlertDialog's own listeners are the
+ small-screen media query behind the button order and the press tracking
+ `family:action-groups` FR5 gives its actions; Dialog owns the modal
+ lifecycle.
- **PR2 — The touch presentation adds no element.** The motion plays on the
dialog surface and its `::backdrop`; AlertDialog renders no extra element
@@ -229,7 +229,7 @@ The dialog surface (the Dialog element AlertDialog renders) carries `alert-dialo
| FR1–FR5 | `AlertDialog.test.tsx` ("calls onOpenChange(false) on Escape", "does not call onOpenChange when action is clicked", "does not call onAction on Escape", "does not disable the cancel button while the action is loading", "exposes a named group instead, with no aria-modal") and `useImperativeAlertDialog.test.tsx` ("opens on show()", "closes on hide()") | open, loading, inline, imperative | Escape not cancelling, the action closing by itself, or the inline path claiming the role fails. | `audit:AlertDialog/behavior` |
| FR6, PR2 | Browser tests under a coarse pointer in Chromium and WebKit, a spring-curve oracle, a busy-main-thread case, and real-device clips on iOS Safari and Android Chrome | present, dismiss, close during present, reopen during dismiss, Reduce Motion, a fine pointer, a narrow viewport | a curve off its role, a start outside the viewport, a jump on interruption, a scale under Reduce Motion, changed motion under a fine pointer, or an added element fails. No test exists yet; FR6 is not shipped. | `audit:AlertDialog/behavior` |
| FR7 | Browser tests under a coarse pointer, with keyboard and assistive-technology input | a tap during the presentation, Enter and Escape during it, a screen reader's activation, a tap during the dismissal; a mouse click during the presentation under a fine pointer | a held key or assistive-technology action, content made inert during the entrance, a tap that reaches a leaving alert, or a mouse click held under a fine pointer fails. No test exists yet; FR7 is not shipped. | `audit:AlertDialog/behavior` |
-| FR8 | Pointer-stream tests with a mouse, a pen, and a finger, and keyboard tests | a press on Cancel slid onto the action and lifted, and a press lifted outside the actions, each with a mouse, a pen, and a finger; Enter and Space on each action | the press-start action running after a slide, any action running on a lift outside, or a changed keyboard or assistive-technology activation fails. No test exists yet; FR8 is not shipped. | `audit:AlertDialog/behavior` |
+| FR8 | `AlertDialog.test.tsx` ("AlertDialog action tracking"), `useActionGroupTracking.test.tsx` and `AlertDialog.interaction.browser.spec.ts` | a press on Cancel slid onto the action and lifted, and a press lifted outside the actions, each with a mouse, a pen, and a finger; Enter and Space on each action | the press-start action running after a slide, any action running on a lift outside, or a changed keyboard or assistive-technology activation fails. | `audit:AlertDialog/behavior` |
| FR9 | Browser tests at a phone width and at a desktop width, in the default and an alternate theme | a phone width and a desktop width, in the default and an alternate theme; a caller `width` at a phone width; a screen narrower than 320 px; a narrow window under a fine pointer; a coarse screen that is not compact | a phone-width alert other than 320 px in any theme without a caller `width`, a caller `width` overridden, a desktop width changed, an alert wider than the viewport, or a 320 px alert in a narrow fine-pointer window or on a non-compact coarse screen fails. No test exists yet; FR9 is not shipped. | `audit:AlertDialog/behavior` |
| AR1 | `AlertDialog.test.tsx` ("links title via aria-labelledby", "marks cancel as the initial focus target", "keeps the initial focus target on the least destructive action", "calls onOpenChange(false) on Escape", "stacks long destructive action labels above cancel on a narrow fine-pointer screen", "reaches both buttons by Tab, cancel first", "is a modal alertdialog", "does not claim the alertdialog role") and `useImperativeAlertDialog.test.tsx`; the Alert Dialog accessibility contract binding in `__tests__/AlertDialog.a11y.test.tsx` and `__tests__/AlertDialog.a11y.chromium.spec.ts` (role, description link, no backdrop dismiss, focus delegation) | open modal; after Escape; after Cancel | The role, name link, description link, or Cancel initial focus is lost, or a click outside dismisses the dialog. Gap: the contract keeps `alertdialog.focus.least-destructive-first` and `alertdialog.dismissal.click-beside-is-inert` advisory, so a regression in either only reports; `spec:AST-020` FR9 makes them required once this record is current. No test covers Tab wrapping inside the alert (Current-state impact). | `audit:AlertDialog/accessibility` |
| PR1 | Source review | Small and wide screens | Gap: no automated check fails if AlertDialog adds a listener beyond the small-screen media query. | `audit:AlertDialog/behavior` |
diff --git a/internal/eslint-plugin-astryx/no-raw-private-attribute.baseline.json b/internal/eslint-plugin-astryx/no-raw-private-attribute.baseline.json
index 399f2de0a6..673d42376c 100644
--- a/internal/eslint-plugin-astryx/no-raw-private-attribute.baseline.json
+++ b/internal/eslint-plugin-astryx/no-raw-private-attribute.baseline.json
@@ -1,9 +1,5 @@
{
- "packages/core/src/Button/Button.tsx": [
- "data-astryx-press",
- "data-astryx-press",
- "data-astryx-press"
- ],
+ "packages/core/src/Button/Button.tsx": ["data-astryx-press"],
"packages/core/src/Chat/ChatComposerInput.tsx": [
"data-astryx-dictation-interim"
],
diff --git a/packages/core/src/AlertDialog/AlertDialog.doc.mjs b/packages/core/src/AlertDialog/AlertDialog.doc.mjs
index 135cd637e5..12b9de6ca4 100644
--- a/packages/core/src/AlertDialog/AlertDialog.doc.mjs
+++ b/packages/core/src/AlertDialog/AlertDialog.doc.mjs
@@ -21,7 +21,7 @@ export const docs = {
],
usage: {
description:
- 'AlertDialog asks the user to confirm a destructive or irreversible action before it happens. Use it for things like deleting content, revoking access, or discarding unsaved changes.\n\nIt implements the WAI-ARIA APG [Alert Dialog pattern](https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/): `role="alertdialog"`, a title linked by `aria-labelledby`, a consequence description linked by `aria-describedby`, focus moved into the dialog on open and returned to the trigger on close, and no dismissal by clicking outside. Escape cancels.\n\nAlertDialog passes its requested width through to Dialog, which clamps the surface to the container and dynamic viewport with token gutters. Generic Dialog footers should wrap, but Dialog does not own action semantics or order; consumer composition controls that. AlertDialog owns its confirmation semantics: above 640px, actions render horizontally and may move onto another row; at 640px and below, the destructive action appears above Cancel and both buttons fill the footer width. Button labels retain their standard single-line behavior. The breakpoint follows available width, not pointer or hover capability. The body scrolls when block space is constrained.\n\nFor cases where you want to show an alert without managing open state, use the `useImperativeAlertDialog` hook: call `alert.show(options)` and render `alert.element` in your tree.',
+ 'AlertDialog asks the user to confirm a destructive or irreversible action before it happens. Use it for things like deleting content, revoking access, or discarding unsaved changes.\n\nIt implements the WAI-ARIA APG [Alert Dialog pattern](https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/): `role="alertdialog"`, a title linked by `aria-labelledby`, a consequence description linked by `aria-describedby`, focus moved into the dialog on open and returned to the trigger on close, and no dismissal by clicking outside. Escape cancels.\n\nAlertDialog passes its requested width through to Dialog, which clamps the surface to the container and dynamic viewport with token gutters. Generic Dialog footers should wrap, but Dialog does not own action semantics or order; consumer composition controls that. AlertDialog owns its confirmation semantics: above 640px, actions render horizontally and may move onto another row; at 640px and below, the destructive action appears above Cancel and both buttons fill the footer width. Button labels retain their standard single-line behavior. The breakpoint follows available width, not pointer or hover capability. The body scrolls when block space is constrained.\n\nThe two actions are tracked as one group under every pointer, the way iOS tracks the actions of an alert: the action under the pointer highlights as soon as it is pressed, the highlight follows the pointer from one action to the other, and the release runs the action under it. Releasing off both actions runs nothing. The keyboard and assistive technology keep the click of each button.\n\nFor cases where you want to show an alert without managing open state, use the `useImperativeAlertDialog` hook: call `alert.show(options)` and render `alert.element` in your tree.',
bestPractices: [
{
guidance: true,
@@ -196,7 +196,7 @@ export const docsDense = {
'Confirms destructive/irreversible action before it happens (delete, revoke access, discard unsaved changes).',
usage: {
description:
- 'AlertDialog confirms destructive/irreversible action (delete, revoke access, discard changes). Implements WAI-ARIA APG Alert Dialog pattern (https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/): role="alertdialog", aria-labelledby title, aria-describedby description, focus into dialog on open + back to trigger on close, no outside-click dismissal, Escape cancels. Dialog preserves requested width + clamps it to container/dynamic viewport gutters. Generic Dialog footers wrap while consumers own action order. AlertDialog owns confirmation action layout: >640px horizontal buttons may move to another row; <=640px puts the destructive action above Cancel and makes both buttons full width regardless of pointer/hover capability. Button labels remain single-line. Body scrolls when height constrained. To show w/o managing open state, use useImperativeAlertDialog hook: call alert.show(options) + render alert.element in tree.',
+ 'AlertDialog confirms destructive/irreversible action (delete, revoke access, discard changes). Implements WAI-ARIA APG Alert Dialog pattern (https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/): role="alertdialog", aria-labelledby title, aria-describedby description, focus into dialog on open + back to trigger on close, no outside-click dismissal, Escape cancels. Dialog preserves requested width + clamps it to container/dynamic viewport gutters. Generic Dialog footers wrap while consumers own action order. AlertDialog owns confirmation action layout: >640px horizontal buttons may move to another row; <=640px puts the destructive action above Cancel and makes both buttons full width regardless of pointer/hover capability. Button labels remain single-line. Body scrolls when height constrained. Every pointer: both actions tracked as one group like iOS alerts (action under pointer highlights at once, highlight follows pointer between actions, release runs action under pointer, release off both runs nothing); keyboard/AT keep each button click. To show w/o managing open state, use useImperativeAlertDialog hook: call alert.show(options) + render alert.element in tree.',
bestPractices: [
{
guidance: true,
diff --git a/packages/core/src/AlertDialog/AlertDialog.test.tsx b/packages/core/src/AlertDialog/AlertDialog.test.tsx
index 1c88d6a6d0..e1fd8ccfbc 100644
--- a/packages/core/src/AlertDialog/AlertDialog.test.tsx
+++ b/packages/core/src/AlertDialog/AlertDialog.test.tsx
@@ -9,8 +9,17 @@
* SYNC: When AlertDialog.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {
+ describe,
+ it,
+ expect,
+ vi,
+ beforeAll,
+ beforeEach,
+ afterEach,
+} from 'vitest';
+import {
+ cleanup,
render,
screen,
fireEvent,
@@ -18,9 +27,28 @@ import {
within,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import {getGestureHost} from '../gestures/GestureHost';
+import {isTrackedByGroup} from '../privateAttributes/pressGroupItem.stylex';
import {AlertDialog} from './AlertDialog';
import {useImperativeAlertDialog} from './useImperativeAlertDialog';
+// The gesture host reads `(pointer: coarse)` once per document and keeps that
+// query for the document's life: it gets this live one (see beforeAll), whose
+// answer each test's media stub sets.
+let isCoarsePrimaryPointer = false;
+const hostCoarseQuery = {
+ get matches() {
+ return isCoarsePrimaryPointer;
+ },
+ media: '(pointer: coarse)',
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+};
+
function stubAlertDialogMedia({
smallScreen,
coarsePointer,
@@ -32,6 +60,7 @@ function stubAlertDialogMedia({
noHover: boolean;
reduceMotion?: boolean;
}): void {
+ isCoarsePrimaryPointer = coarsePointer;
vi.stubGlobal(
'matchMedia',
vi.fn((query: string) => {
@@ -68,6 +97,15 @@ function stubAlertDialogMedia({
);
}
+beforeAll(() => {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn(() => hostCoarseQuery),
+ );
+ getGestureHost(document);
+ vi.unstubAllGlobals();
+});
+
beforeEach(() => {
HTMLDialogElement.prototype.showModal = vi.fn(function (
this: HTMLDialogElement,
@@ -81,6 +119,7 @@ beforeEach(() => {
afterEach(() => {
vi.unstubAllGlobals();
+ isCoarsePrimaryPointer = false;
});
describe('AlertDialog', () => {
@@ -145,6 +184,39 @@ describe('AlertDialog', () => {
expect(onOpenChange).not.toHaveBeenCalled();
});
+ it("runs onAction for a user-event click on the action and leaves Cancel alone, as a consumer's test clicks it", async () => {
+ const user = userEvent.setup();
+ const onAction = vi.fn();
+ const onOpenChange = vi.fn();
+ render(
+ <AlertDialog
+ {...defaultProps}
+ onAction={onAction}
+ onOpenChange={onOpenChange}
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Delete'}));
+ expect(onAction).toHaveBeenCalledTimes(1);
+ expect(onOpenChange).not.toHaveBeenCalled();
+ await user.click(screen.getByRole('button', {name: 'Cancel'}));
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ expect(onAction).toHaveBeenCalledTimes(1);
+ });
+
+ it('opens under a fine pointer with no console warning', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ render(<AlertDialog {...defaultProps} />);
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument();
+ expect(warn).not.toHaveBeenCalled();
+ expect(error).not.toHaveBeenCalled();
+ } finally {
+ warn.mockRestore();
+ error.mockRestore();
+ }
+ });
+
it('does not render when isOpen is false', () => {
render(<AlertDialog {...defaultProps} isOpen={false} />);
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
@@ -169,7 +241,8 @@ describe('AlertDialog', () => {
render(<AlertDialog {...defaultProps} />);
expect(window.matchMedia).toHaveBeenCalledWith('(max-width: 640px)');
- expect(window.matchMedia).not.toHaveBeenCalledWith('(pointer: coarse)');
+ // The layout reads the width alone. The pointer query only turns the
+ // touch layer on, never the order or the stacking.
expect(window.matchMedia).not.toHaveBeenCalledWith('(hover: none)');
const dialog = screen.getByRole('alertdialog');
const buttons = within(dialog).getAllByRole('button');
@@ -230,7 +303,8 @@ describe('AlertDialog', () => {
);
expect(window.matchMedia).toHaveBeenCalledWith('(max-width: 640px)');
- expect(window.matchMedia).not.toHaveBeenCalledWith('(pointer: coarse)');
+ // The layout reads the width alone. The pointer query only turns the
+ // touch layer on, never the order or the stacking.
expect(window.matchMedia).not.toHaveBeenCalledWith('(hover: none)');
const dialog = screen.getByRole('alertdialog');
const buttons = within(dialog).getAllByRole('button');
@@ -264,7 +338,8 @@ describe('AlertDialog', () => {
);
expect(window.matchMedia).toHaveBeenCalledWith('(max-width: 640px)');
- expect(window.matchMedia).not.toHaveBeenCalledWith('(pointer: coarse)');
+ // The layout reads the width alone. The pointer query only turns the
+ // touch layer on, never the order or the stacking.
expect(window.matchMedia).not.toHaveBeenCalledWith('(hover: none)');
const dialog = screen.getByRole('alertdialog');
const buttons = within(dialog).getAllByRole('button');
@@ -433,6 +508,145 @@ describe('AlertDialog', () => {
});
});
+/**
+ * Touch tracking: a finger is tracked across both actions as one group, as
+ * UIKit tracks an alert's actions (measured on iOS 26.2). The tracking hook's
+ * own contract is covered in hooks/useActionGroupTracking.test.tsx; these
+ * cover AlertDialog's wiring of it.
+ */
+describe('AlertDialog action tracking', () => {
+ let touchClock = 10_000;
+ let touchId = 500;
+
+ function touch(
+ type: 'touchstart' | 'touchmove' | 'touchend',
+ target: Element,
+ point: {x: number; y: number},
+ id: number,
+ ): void {
+ touchClock += 16;
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const entry = {identifier: id, clientX: point.x, clientY: point.y, target};
+ Object.defineProperty(event, 'changedTouches', {value: [entry]});
+ Object.defineProperty(event, 'touches', {
+ value: type === 'touchend' ? [] : [entry],
+ });
+ Object.defineProperty(event, 'timeStamp', {value: touchClock});
+ target.dispatchEvent(event);
+ }
+
+ function place(element: Element, left: number, top: number): void {
+ const rect = DOMRect.fromRect({x: left, y: top, width: 120, height: 32});
+ element.getBoundingClientRect = () => rect;
+ }
+
+ function renderOpen(props: {isInline?: boolean; coarse?: boolean} = {}) {
+ const isCoarse = props.coarse ?? true;
+ stubAlertDialogMedia({
+ smallScreen: true,
+ coarsePointer: isCoarse,
+ noHover: isCoarse,
+ });
+ const onOpenChange = vi.fn();
+ const onAction = vi.fn();
+ render(
+ <AlertDialog
+ isOpen
+ isInline={props.isInline}
+ onOpenChange={onOpenChange}
+ title="Delete item?"
+ description="This cannot be undone."
+ actionLabel="Delete"
+ onAction={onAction}
+ />,
+ );
+ const cancel = screen.getByRole('button', {name: 'Cancel'});
+ const action = screen.getByRole('button', {name: 'Delete'});
+ // Stacked on a narrow screen: the action above Cancel.
+ place(action, 16, 100);
+ place(cancel, 16, 140);
+ return {onOpenChange, onAction, cancel, action};
+ }
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('marks both actions as tracked group items from the first render, keeping their pressable marker', () => {
+ const {cancel, action} = renderOpen();
+ for (const button of [cancel, action]) {
+ // The document press controller leaves a pointer's press on a marked
+ // item to the group's tracker, its one painter; it still records the
+ // touch for the scroll brake, through the pressable marker.
+ expect(isTrackedByGroup(button)).toBe(true);
+ expect(button).toHaveAttribute('data-astryx-pressable');
+ }
+ });
+
+ it('leaves the actions to the document press controller in the inline preview, which is not tracked', () => {
+ const {cancel, action} = renderOpen({isInline: true});
+ for (const button of [cancel, action]) {
+ expect(isTrackedByGroup(button)).toBe(false);
+ expect(button).toHaveAttribute('data-astryx-pressable');
+ }
+ });
+
+ it('runs the action a finger lifts on: from the action to Cancel cancels, from Cancel to the action runs it', () => {
+ const {onOpenChange, onAction, cancel, action} = renderOpen();
+ let id = touchId++;
+ touch('touchstart', action, {x: 60, y: 116}, id);
+ expect(action).toHaveAttribute('data-astryx-press', 'on');
+ touch('touchmove', action, {x: 60, y: 156}, id);
+ expect(action).not.toHaveAttribute('data-astryx-press');
+ expect(cancel).toHaveAttribute('data-astryx-press', 'on');
+ touch('touchend', action, {x: 60, y: 156}, id);
+ expect(onOpenChange).toHaveBeenCalledTimes(1);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ expect(onAction).not.toHaveBeenCalled();
+ id = touchId++;
+ touch('touchstart', cancel, {x: 60, y: 156}, id);
+ touch('touchmove', cancel, {x: 60, y: 116}, id);
+ touch('touchend', cancel, {x: 60, y: 116}, id);
+ expect(onAction).toHaveBeenCalledTimes(1);
+ expect(onOpenChange).toHaveBeenCalledTimes(1);
+ });
+ it('keeps the keyboard on the buttons under every pointer: Enter runs the action and Space cancels (FR8)', async () => {
+ for (const coarse of [true, false]) {
+ const user = userEvent.setup();
+ const {onOpenChange, onAction, cancel, action} = renderOpen({coarse});
+ action.focus();
+ await user.keyboard('{Enter}');
+ expect(onAction).toHaveBeenCalledTimes(1);
+ cancel.focus();
+ await user.keyboard(' ');
+ expect(onOpenChange).toHaveBeenCalledTimes(1);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ expect(onAction).toHaveBeenCalledTimes(1);
+ cleanup();
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('tracks only the actions: a press that lands on the title, the message or the backdrop and slides onto an action runs nothing', () => {
+ const {onOpenChange, onAction, cancel} = renderOpen();
+ const dialog = screen.getByRole('alertdialog');
+ // A touch on ::backdrop targets the dialog element itself.
+ for (const start of [
+ screen.getByText('Delete item?'),
+ screen.getByText('This cannot be undone.'),
+ dialog,
+ ]) {
+ const id = touchId++;
+ touch('touchstart', start, {x: 60, y: 40}, id);
+ touch('touchmove', start, {x: 60, y: 156}, id);
+ expect(cancel).not.toHaveAttribute('data-astryx-press');
+ touch('touchend', start, {x: 60, y: 156}, id);
+ }
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(onAction).not.toHaveBeenCalled();
+ });
+});
+
describe('useImperativeAlertDialog', () => {
const noop = () => {};
diff --git a/packages/core/src/AlertDialog/AlertDialog.tsx b/packages/core/src/AlertDialog/AlertDialog.tsx
index 54e4e88105..83b542e42c 100644
--- a/packages/core/src/AlertDialog/AlertDialog.tsx
+++ b/packages/core/src/AlertDialog/AlertDialog.tsx
@@ -4,7 +4,9 @@
/**
* @file AlertDialog.tsx
- * @input Uses React, StyleX, Dialog, Layout, Heading, Text, Button
+ * @input Uses React, StyleX, Dialog, Layout, Heading, Text, Button, the
+ * action-group tracking (hooks/useActionGroupTracking) and the press-group
+ * marker (privateAttributes/pressGroupItem.stylex)
* @output Exports AlertDialog component, AlertDialogProps type
* @position Core implementation; consumed by index.ts, tested by AlertDialog.test.tsx
*
@@ -12,11 +14,12 @@
* - /packages/core/src/AlertDialog/AlertDialog.doc.mjs (props table, features, examples)
* - /packages/core/src/AlertDialog/AlertDialog.test.tsx (tests for new/changed behavior)
* - /packages/core/src/AlertDialog/index.ts (exports if types change)
+ * - /packages/core/src/AlertDialog/__tests__/AlertDialog.interaction.browser.spec.ts (touch tracking)
* - /apps/storybook/stories/AlertDialog.stories.tsx (storybook stories)
* - /packages/cli/assets/templates/blocks/components/AlertDialog/ (showcase blocks)
*/
-import React, {useId, useCallback} from 'react';
+import React, {useId, useCallback, useRef} from 'react';
import * as stylex from '@stylexjs/stylex';
import {Dialog} from '../Dialog/Dialog';
import {Layout} from '../Layout/Layout';
@@ -36,12 +39,22 @@ import {
useComponentTranslator,
} from '../i18n/useComponentTranslator';
import english from '../i18n/generated-english/AlertDialog/AlertDialog.generated';
+import {useActionGroupTracking} from '../hooks/useActionGroupTracking';
+import {PressGroupContext} from '../hooks/pressGroupContext';
+import {alertController} from '../motion/uikit/alert';
+import {pressGroupItemProps} from '../privateAttributes/pressGroupItem.stylex';
registerEnglishFallback(english);
const SMALL_SCREEN_QUERY = '(max-width: 640px)';
const styles = stylex.create({
+ // The browser may pinch-zoom on the actions but never pans there. Chrome on
+ // Android cancels a pointer it pans, which would cancel the group's press.
+ // The gesture host keeps an author's narrower touch-action.
+ trackingRow: {
+ touchAction: 'pinch-zoom',
+ },
action: {
maxWidth: '100%',
minWidth: 0,
@@ -177,6 +190,19 @@ export function AlertDialog({
onOpenChange(false);
}, [onOpenChange]);
+ // Each action carries the press-group marker from its first render, so the
+ // tracker is its only painter.
+ const actionsRef = useRef<HTMLElement>(null);
+ const isTracking = isOpen && isInline !== true;
+ useActionGroupTracking(actionsRef, {
+ // The actions row holds only the two buttons.
+ itemSelector: 'button',
+ highlightOnsetMs: alertController.actions.highlightOnsetMs,
+ highlightExpansion: alertController.actions.highlightExpansion,
+ isEnabled: isTracking,
+ });
+ const actionTrackingProps = isTracking ? pressGroupItemProps : undefined;
+
const buttonActionStyle = [
styles.action,
isSmallScreen && styles.stackedAction,
@@ -188,6 +214,7 @@ export function AlertDialog({
label={cancelLabel}
onClick={handleCancel}
xstyle={buttonActionStyle}
+ {...actionTrackingProps}
// Dialog focuses [data-autofocus] itself after showModal(), because
// React's autoFocus runs during commit while the dialog is invisible.
// Cancel is least destructive, so it remains the autofocus target even
@@ -203,6 +230,7 @@ export function AlertDialog({
onClick={onAction}
isLoading={isActionLoading}
xstyle={buttonActionStyle}
+ {...actionTrackingProps}
/>
);
@@ -244,13 +272,17 @@ export function AlertDialog({
destructive-above-Cancel narrow order because confirmation
actions have component-specific meaning here. */}
<Stack
+ ref={actionsRef}
+ xstyle={isTracking && styles.trackingRow}
direction={isSmallScreen ? 'vertical' : 'horizontal'}
gap={2}
hAlign={isSmallScreen ? 'stretch' : 'end'}
wrap={isSmallScreen ? 'nowrap' : 'wrap'}>
- {isSmallScreen
- ? [actionButton, cancelButton]
- : [cancelButton, actionButton]}
+ <PressGroupContext value={isTracking}>
+ {isSmallScreen
+ ? [actionButton, cancelButton]
+ : [cancelButton, actionButton]}
+ </PressGroupContext>
</Stack>
</LayoutFooter>
}
diff --git a/packages/core/src/AlertDialog/__tests__/AlertDialog.interaction.browser.spec.ts b/packages/core/src/AlertDialog/__tests__/AlertDialog.interaction.browser.spec.ts
new file mode 100644
index 0000000000..380749c6e0
--- /dev/null
+++ b/packages/core/src/AlertDialog/__tests__/AlertDialog.interaction.browser.spec.ts
@@ -0,0 +1,451 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file AlertDialog.interaction.browser.spec.ts
+ * @input The built "Delete" AlertDialog story on the phone profile, real
+ * touch input (Chromium CDP / WebKit's input command) and the interaction
+ * harness
+ * @output Proofs that a finger or a mouse is tracked across the alert's two
+ * actions: the highlight follows it, the lift runs the action under it once,
+ * only the actions are tracked, one action looks pressed at a time, and a
+ * held finger refuses a text selection only while it holds
+ * @position Touch lane of AlertDialog, beside the accessibility bindings in
+ * this folder. Run with `pnpm test:interaction AlertDialog`.
+ */
+
+import {expect, test, type Locator, type Page} from '@playwright/test';
+import {
+ drag,
+ frames,
+ openStory,
+ tap,
+ touchDriver,
+ waitForRest,
+ withStorybook,
+ type Point,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+interface OpenAlert {
+ driver: TouchDriver;
+ dialog: Locator;
+ cancel: Locator;
+ del: Locator;
+ centers: {cancel: Point; del: Point; message: Point};
+ /** Bottom edge of the alert surface, CSS px. */
+ bottom: number;
+}
+
+const centerOf = async (locator: Locator): Promise<Point> => {
+ const box = await locator.boundingBox();
+ if (box == null) {
+ throw new Error('no box');
+ }
+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};
+};
+
+/**
+ * Opens the story's alert with a tap on its trigger, waits for the entrance
+ * to rest, and starts a page-side log: every click an action receives, and
+ * every write of the press attribute with the animation frame it landed in.
+ */
+async function openAlert(
+ page: Page,
+ story = 'core-alertdialog--delete',
+): Promise<OpenAlert> {
+ await openStory(page, storybook(), story);
+ const driver = await touchDriver(page);
+ await driver.tap(
+ await centerOf(page.getByRole('button', {name: 'Delete item'})),
+ );
+ const dialog = page.getByRole('alertdialog', {name: 'Delete item?'});
+ await expect(dialog).toBeVisible();
+ await waitForRest(dialog);
+ const cancel = dialog.getByRole('button', {name: 'Cancel'});
+ const del = dialog.getByRole('button', {name: 'Delete'});
+ const message = dialog.getByText('This action cannot be undone', {
+ exact: false,
+ });
+ await page.evaluate(() => {
+ const log = {
+ clicks: [] as string[],
+ paints: [] as string[],
+ touchFrames: [] as number[],
+ frame: 0,
+ };
+ (window as unknown as {__alertLog: typeof log}).__alertLog = log;
+ const tick = () => {
+ log.frame += 1;
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ document.addEventListener(
+ 'click',
+ event => {
+ const button = (event.target as Element).closest('button');
+ if (button != null) {
+ log.clicks.push(button.textContent ?? '');
+ }
+ },
+ true,
+ );
+ document.addEventListener(
+ 'touchstart',
+ () => log.touchFrames.push(log.frame),
+ true,
+ );
+ new MutationObserver(records => {
+ for (const record of records) {
+ const target = record.target as Element;
+ log.paints.push(
+ `${target.textContent}=${target.getAttribute('data-astryx-press') ?? '-'}@${log.frame}`,
+ );
+ }
+ }).observe(document.body, {
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['data-astryx-press'],
+ });
+ });
+ const box = await dialog.boundingBox();
+ if (box == null) {
+ throw new Error('no dialog box');
+ }
+ return {
+ driver,
+ dialog,
+ cancel,
+ del,
+ centers: {
+ cancel: await centerOf(cancel),
+ del: await centerOf(del),
+ message: await centerOf(message),
+ },
+ bottom: box.y + box.height,
+ };
+}
+
+const readLog = async (page: Page) =>
+ page.evaluate(
+ () =>
+ (
+ window as unknown as {
+ __alertLog: {
+ clicks: string[];
+ paints: string[];
+ touchFrames: number[];
+ };
+ }
+ ).__alertLog,
+ );
+
+const paintOf = async (locator: Locator) =>
+ locator.evaluate(el => el.getAttribute('data-astryx-press'));
+
+/** A slow slide that rests before the lift, as a finger reconsidering. */
+const slide = (from: Point, to: Point) =>
+ drag(from, to, {durationMs: 240, hz: 60, holdMs: 60, restMs: 120});
+
+test('a finger that lands on Delete and lifts on Cancel cancels, in every engine', async ({
+ page,
+}) => {
+ const {driver, dialog, centers} = await openAlert(page);
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(true);
+ await driver.play(slide(centers.del, centers.cancel));
+ await expect(dialog).toBeHidden();
+ expect((await readLog(page)).clicks).toEqual(['Cancel']);
+});
+
+test('reopened, the alert tracks again: a slide from Delete to Cancel runs Cancel', async ({
+ page,
+}) => {
+ const {driver, dialog, centers} = await openAlert(page);
+ await driver.play(tap(centers.cancel, {holdMs: 80}));
+ await expect(dialog).toBeHidden();
+ await driver.tap(
+ await centerOf(page.getByRole('button', {name: 'Delete item'})),
+ );
+ await expect(dialog).toBeVisible();
+ await waitForRest(dialog);
+ await driver.play(slide(centers.del, centers.cancel));
+ await expect(dialog).toBeHidden();
+ // The log holds every button's click, the opener's included.
+ expect((await readLog(page)).clicks).toEqual([
+ 'Cancel',
+ 'Delete item',
+ 'Cancel',
+ ]);
+});
+
+test('the touched action is highlighted in the frame of the touch, and the highlight follows the finger', async ({
+ page,
+}) => {
+ const {driver, dialog, cancel, del, centers} = await openAlert(page);
+ await driver.play(slide(centers.del, centers.cancel), {
+ onEvent: async (step, index) => {
+ if (index !== 0) {
+ return;
+ }
+ // Read synchronously after the touch-down was dispatched.
+ expect(step.type).toBe('touchStart');
+ expect(await paintOf(del)).toBe('on');
+ expect(await paintOf(cancel)).toBeNull();
+ },
+ });
+ await expect(dialog).toBeHidden();
+ const {paints, clicks, touchFrames} = await readLog(page);
+ // The first write is Delete's, in the animation frame of the touchstart.
+ expect(touchFrames).toHaveLength(1);
+ expect(paints[0]).toBe(`Delete=on@${touchFrames[0]}`);
+ // Delete is cut (no fade) when the finger leaves it; Cancel lights when it
+ // enters; the lift fades Cancel, and the alert closing (here at once, with
+ // no exit) ends that fade with the tracking.
+ const sequence = paints.map(entry => entry.split('@')[0]);
+ expect(sequence).toEqual([
+ 'Delete=on',
+ 'Delete=-',
+ 'Cancel=on',
+ 'Cancel=fading',
+ 'Cancel=-',
+ ]);
+ expect(clicks).toEqual(['Cancel']);
+});
+
+test('a lift off both actions runs nothing and leaves the alert open', async ({
+ page,
+}) => {
+ const {driver, dialog, del, centers, bottom} = await openAlert(page);
+ await driver.play(slide(centers.del, {x: centers.del.x, y: bottom + 60}));
+ expect(await paintOf(del)).toBeNull();
+ await expect(dialog).toBeVisible();
+ expect((await readLog(page)).clicks).toEqual([]);
+});
+
+test('a held finger on the actions refuses a text selection only while it holds; at rest nothing about selection changes (spec:AST-094 FR41)', async ({
+ page,
+}) => {
+ const {driver, dialog, del, centers, bottom} = await openAlert(page);
+ const userSelect = async (locator: Locator) =>
+ locator.evaluate(element => {
+ const style = getComputedStyle(element);
+ return (
+ style.getPropertyValue('user-select') ||
+ style.getPropertyValue('-webkit-user-select')
+ );
+ });
+ // Whether a selection that starts on Delete's label is refused.
+ const refusesSelection = async () =>
+ del.evaluate(element => {
+ const event = new Event('selectstart', {bubbles: true, cancelable: true});
+ element.dispatchEvent(event);
+ return event.defaultPrevented;
+ });
+ // At rest: no style refuses a selection, on the actions or around them.
+ expect(await userSelect(del.locator('..'))).not.toBe('none');
+ expect(await userSelect(dialog.getByRole('heading'))).not.toBe('none');
+ expect(await refusesSelection()).toBe(false);
+ // While a finger holds the actions, a selection there is refused.
+ let refusedWhileHeld: boolean | null = null;
+ await driver.play(slide(centers.del, {x: centers.del.x, y: bottom + 60}), {
+ onEvent: async (step, index) => {
+ if (index !== 1) {
+ return;
+ }
+ expect(step.type).toBe('touchMove');
+ refusedWhileHeld = await refusesSelection();
+ },
+ });
+ expect(refusedWhileHeld).toBe(true);
+ // After the lift, nothing is refused again.
+ expect(await refusesSelection()).toBe(false);
+ await expect(dialog).toBeVisible();
+});
+
+test("no pan can take the group's press: the actions allow only pinch-zoom, and the rest of the alert keeps its pan", async ({
+ page,
+}) => {
+ // Chrome on Android cancels a pointer it pans (pointercancel), which ends
+ // the long press that tracks the group: where the group owns a press, the
+ // browser may pinch-zoom but not pan. Only the actions are the group.
+ const {dialog, cancel} = await openAlert(page);
+ const touchAction = async (locator: Locator) =>
+ locator.evaluate(element => getComputedStyle(element).touchAction);
+ // The actions' row, the group's element.
+ expect(await touchAction(cancel.locator('..'))).toBe('pinch-zoom');
+ expect(await touchAction(dialog)).toBe('auto');
+ const message = dialog.getByText('This action cannot be undone', {
+ exact: false,
+ });
+ expect(await touchAction(message.locator('..'))).toBe('auto');
+});
+
+test('only the actions are tracked: a touch that lands on the message and slides onto Cancel runs nothing', async ({
+ page,
+}) => {
+ const {driver, dialog, centers} = await openAlert(page);
+ await driver.play(slide(centers.message, centers.cancel));
+ await frames(page, 4);
+ await expect(dialog).toBeVisible();
+ expect((await readLog(page)).clicks).toEqual([]);
+});
+
+test('a tap runs its action exactly once', async ({page}) => {
+ const {driver, dialog, centers} = await openAlert(page);
+ await driver.play(tap(centers.cancel, {holdMs: 80}));
+ await expect(dialog).toBeHidden();
+ // Let any click the browser might still synthesize arrive.
+ await frames(page, 4);
+ expect((await readLog(page)).clicks).toEqual(['Cancel']);
+});
+
+test.describe('with a mouse', () => {
+ test.use({hasTouch: false, isMobile: false});
+
+ test('a press on Delete slid to Cancel runs Cancel once, and a click on Delete runs Delete once (family:action-groups FR5)', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-alertdialog--delete');
+ // A fine pointer in this context, before anything is checked.
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const open = async () => {
+ await page.getByRole('button', {name: 'Delete item'}).click();
+ const dialog = page.getByRole('alertdialog', {name: 'Delete item?'});
+ await expect(dialog).toBeVisible();
+ return dialog;
+ };
+ const clicks: string[] = [];
+ await page.exposeFunction('__alertClick', (label: string) => {
+ clicks.push(label);
+ });
+ await page.evaluate(() => {
+ document.addEventListener(
+ 'click',
+ event => {
+ const action = (event.target as Element).closest('dialog button');
+ if (action != null) {
+ (
+ window as unknown as {__alertClick: (label: string) => void}
+ ).__alertClick(action.textContent ?? '');
+ }
+ },
+ true,
+ );
+ });
+ let dialog = await open();
+ const del = await centerOf(dialog.getByRole('button', {name: 'Delete'}));
+ const cancel = await centerOf(dialog.getByRole('button', {name: 'Cancel'}));
+ await page.mouse.move(del.x, del.y);
+ await page.mouse.down();
+ await page.mouse.move(cancel.x, cancel.y, {steps: 8});
+ await page.mouse.up();
+ await expect(dialog).toBeHidden();
+ expect(clicks).toEqual(['Cancel']);
+ // A plain click: the group's click runs it, and the browser's own click
+ // for the same press is swallowed.
+ clicks.length = 0;
+ dialog = await open();
+ await dialog.getByRole('button', {name: 'Delete'}).click();
+ await expect.poll(() => clicks.length).toBe(1);
+ await frames(page, 4);
+ expect(clicks).toEqual(['Delete']);
+ });
+
+ test('a press held on Delete and slid onto Cancel lights only Cancel: Delete keeps no pressed look (family:action-groups FR2)', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-alertdialog--delete');
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ await page.getByRole('button', {name: 'Delete item'}).click();
+ const dialog = page.getByRole('alertdialog', {name: 'Delete item?'});
+ await expect(dialog).toBeVisible();
+ await waitForRest(dialog);
+ const delButton = dialog.getByRole('button', {name: 'Delete'});
+ const cancelButton = dialog.getByRole('button', {name: 'Cancel'});
+ // Whether an action looks pressed: its press paint, its press scale, or
+ // a pressed overlay image of nonzero size.
+ const looksPressed = async (locator: Locator) =>
+ locator.evaluate(element => {
+ const style = getComputedStyle(element);
+ const scale =
+ style.transform !== 'none' &&
+ !/^matrix\(1, 0, 0, 1, 0, 0\)$/.test(style.transform);
+ return {
+ paint: element.getAttribute('data-astryx-press'),
+ scaled: scale,
+ image:
+ style.backgroundImage !== 'none' &&
+ style.backgroundSize !== '0px 0px',
+ };
+ });
+ // Both painted and at rest before the press.
+ await expect(delButton).toBeVisible();
+ await expect(cancelButton).toBeVisible();
+ expect(await looksPressed(delButton)).toEqual({
+ paint: null,
+ scaled: false,
+ image: false,
+ });
+ const del = await centerOf(delButton);
+ const cancel = await centerOf(cancelButton);
+ await page.mouse.move(del.x, del.y);
+ await page.mouse.down();
+ await expect
+ .poll(async () => (await looksPressed(delButton)).paint)
+ .toBe('on');
+ await page.mouse.move(cancel.x, cancel.y, {steps: 8});
+ await expect
+ .poll(async () => (await looksPressed(cancelButton)).paint)
+ .toBe('on');
+ await expect
+ .poll(async () => looksPressed(delButton))
+ .toEqual({paint: null, scaled: false, image: false});
+ const lit = await looksPressed(cancelButton);
+ await page.mouse.up();
+ expect(lit.paint).toBe('on');
+ expect(lit.image).toBe(true);
+ });
+
+ test('the dialog keeps its base styles: its text stays selectable', async ({
+ page,
+ }) => {
+ // Only the actions' row, the group, takes no text selection: with a
+ // mouse the dialog's title and message stay selectable.
+ await openStory(page, storybook(), 'core-alertdialog--delete');
+ // A fine pointer in this context, before anything is checked.
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ await page.getByRole('button', {name: 'Delete item'}).click();
+ const dialog = page.getByRole('alertdialog', {name: 'Delete item?'});
+ await expect(dialog).toBeVisible();
+ const styles = await dialog.evaluate(element => {
+ const title = element.querySelector('h2') as HTMLElement;
+ return {
+ dialog: getComputedStyle(element).userSelect,
+ title: getComputedStyle(title).userSelect,
+ };
+ });
+ expect(styles.dialog).not.toBe('none');
+ expect(styles.title).not.toBe('none');
+ });
+});
+
+test('on a touch screen a mouse click runs its action once', async ({page}) => {
+ const {dialog, centers} = await openAlert(page);
+ // A mouse on a touch screen: the primary pointer is coarse, and the group
+ // tracks every pointer, so the click runs Cancel through the group, once.
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(true);
+ await page.mouse.click(centers.cancel.x, centers.cancel.y);
+ await expect(dialog).toBeHidden();
+ expect((await readLog(page)).clicks).toEqual(['Cancel']);
+});
diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsx
index 86bf661c3c..4ad53ceff4 100644
--- a/packages/core/src/Button/Button.tsx
+++ b/packages/core/src/Button/Button.tsx
@@ -53,6 +53,7 @@ import {iconBoxSizeStyles, type IconSize} from '../Icon/IconSize.stylex';
import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';
import {useSize} from '../SizeContext/SizeContext';
import {useButtonGroup} from '../ButtonGroup/ButtonGroupContext';
+import {PressGroupContext} from '../hooks/pressGroupContext';
import {useInputGroup} from '../InputGroup/InputGroupContext';
import {InputGroupInternalContext} from '../InputGroup/InputGroupInternalContext';
import {
@@ -77,6 +78,12 @@ import {isRenderable} from '../utils/isRenderable';
registerEnglishFallback(english);
+/**
+ * Written by the press controller or a group's tracker while a press is
+ * believed. Typed `string`, so StyleX reads it as a computed key.
+ */
+const PRESSED_ON: string = '[data-astryx-press="on"]';
+
/**
* Base button styles
* Pseudo-classes are nested within properties per StyleX recommendation:
@@ -138,7 +145,19 @@ const styles = stylex.create({
default: 'scale(0.98)',
'@media (pointer: coarse)': 'scale(1)',
},
- '[data-astryx-press="on"]': 'scale(0.98)',
+ [PRESSED_ON]: 'scale(0.98)',
+ },
+ },
+ // A tracked action's own `:active` image paints nothing: the tracker paints
+ // the action under the pointer, which need not be the one pressed first.
+ trackedOverlay: {
+ backgroundSize: {default: null, [`:active:not(${PRESSED_ON})`]: '0 0'},
+ },
+ // A tracked action's press is painted by its group's tracker alone.
+ pressableTracked: {
+ transform: {
+ default: 'scale(1)',
+ [PRESSED_ON]: 'scale(0.98)',
},
},
inactive: {
@@ -147,7 +166,7 @@ const styles = stylex.create({
transform: {
default: 'none',
':active': 'none',
- '[data-astryx-press="on"]': 'none',
+ [PRESSED_ON]: 'none',
},
},
disabled: {
@@ -160,7 +179,7 @@ const styles = stylex.create({
backgroundImage: {
default: 'none',
':active': 'none',
- '[data-astryx-press="on"]': 'none',
+ [PRESSED_ON]: 'none',
},
},
iconOnly: {
@@ -632,6 +651,7 @@ export function Button({
const t = useComponentTranslator();
const size = useSize(sizeProp, 'md');
const buttonGroup = useButtonGroup();
+ const isGroupTracked = use(PressGroupContext);
const inputGroup = useInputGroup();
const [isPending, startTransition] = useTransition();
@@ -760,11 +780,13 @@ export function Button({
sizeStyles[size],
isIconOnly && styles.iconOnly,
interactionOverlayStyles.backgroundImage,
+ isGroupTracked && styles.trackedOverlay,
buttonDisabled && styles.inactive,
isTrueDisabled && styles.disabled,
useAriaDisabled && styles.ariaDisabled,
renderAsLink && styles.link,
- !buttonGroup && styles.pressable,
+ !buttonGroup &&
+ (isGroupTracked ? styles.pressableTracked : styles.pressable),
buttonGroup &&
(buttonGroup.orientation === 'horizontal'
? groupStyles.horizontal
diff --git a/packages/core/src/hooks/actionGroupTracker.test.ts b/packages/core/src/hooks/actionGroupTracker.test.ts
index 09a2f63958..54001b8c1c 100644
--- a/packages/core/src/hooks/actionGroupTracker.test.ts
+++ b/packages/core/src/hooks/actionGroupTracker.test.ts
@@ -155,6 +155,17 @@ describe('createActionGroupTracker', () => {
expect(second.onClick).not.toHaveBeenCalled();
});
+ it('where several actions hold the point, the one the press landed on wins (a test renderer lays out nothing)', () => {
+ place(first.button, {left: 0, top: 0, width: 0, height: 0});
+ place(second.button, {left: 0, top: 0, width: 0, height: 0});
+ const group = tracker();
+ group.begin(0, 0, {landed: second.button.firstChild});
+ expect(group.highlighted).toBe(second.button);
+ group.end();
+ expect(second.onClick).toHaveBeenCalledTimes(1);
+ expect(first.onClick).not.toHaveBeenCalled();
+ });
+
it('skips disabled actions', () => {
second.button.disabled = true;
const group = tracker();
diff --git a/packages/core/src/hooks/actionGroupTracker.ts b/packages/core/src/hooks/actionGroupTracker.ts
index 4c86343941..0bd3462cf9 100644
--- a/packages/core/src/hooks/actionGroupTracker.ts
+++ b/packages/core/src/hooks/actionGroupTracker.ts
@@ -57,7 +57,8 @@ export interface ActionGroupTrackerOptions {
* target past the group's ends commits the lift there wherever the finger
* lifts.
* @default the target whose rect, grown by `highlightExpansion`, holds the
- * point; none between or outside them
+ * point, the one the press landed on where several do; none between or
+ * outside them
*/
resolveTarget?: (
x: number,
@@ -83,8 +84,13 @@ export interface ActionGroupTracker {
/**
* A press began at viewport (x, y): read the actions' rects once and
* highlight the one under it. An inert press is taken but tracks nothing.
+ * `landed` is the node the press landed on.
*/
- begin(x: number, y: number, options?: {inert?: boolean}): void;
+ begin(
+ x: number,
+ y: number,
+ options?: {inert?: boolean; landed?: Node | null},
+ ): void;
/** The finger moved to viewport (x, y). */
move(x: number, y: number): void;
/**
@@ -150,6 +156,7 @@ export function createActionGroupTracker(
let actions: TrackedAction[] = [];
let highlighted: HTMLElement | null = null;
let beganOn: HTMLElement | null = null;
+ let landedOn: Node | null = null;
let isTracking = false;
let isInert = false;
// The finger's last position: `remeasure` resolves it again.
@@ -241,6 +248,9 @@ export function createActionGroupTracker(
if (resolveTarget != null) {
return actions.length === 0 ? null : resolveTarget(x, y, actions);
}
+ // Rects that share an edge, or that have no layout (a test renderer), can
+ // both hold the point: the one the press landed on wins.
+ let first: HTMLElement | null = null;
for (const action of actions) {
if (
x >= action.left - margin &&
@@ -248,22 +258,26 @@ export function createActionGroupTracker(
y >= action.top - margin &&
y <= action.bottom + margin
) {
- return action.element;
+ if (landedOn != null && action.element.contains(landedOn)) {
+ return action.element;
+ }
+ first ??= action.element;
}
}
- return null;
+ return first;
};
const reset = () => {
actions = [];
highlighted = null;
beganOn = null;
+ landedOn = null;
isTracking = false;
isInert = false;
};
return {
- begin(x, y, {inert = false} = {}) {
+ begin(x, y, {inert = false, landed = null} = {}) {
// A press can begin while another is tracked, when a second recognizer
// takes over the finger (a trigger's held press, then the menu's): the
// action the first one lit loses its paint.
@@ -276,6 +290,7 @@ export function createActionGroupTracker(
highlighted = null;
isTracking = true;
isInert = inert;
+ landedOn = landed;
lastX = x;
lastY = y;
getOptions().onMove?.(x, y);
diff --git a/packages/core/src/hooks/pressGroupContext.ts b/packages/core/src/hooks/pressGroupContext.ts
new file mode 100644
index 0000000000..0fe3719fce
--- /dev/null
+++ b/packages/core/src/hooks/pressGroupContext.ts
@@ -0,0 +1,21 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file pressGroupContext.ts
+ * @input Nothing
+ * @output PressGroupContext: true inside a group whose own tracker paints
+ * its actions' press
+ * @position Internal; not exported from the hooks entry. AlertDialog
+ * provides it around its tracked actions, and Button reads it.
+ */
+
+import {createContext} from 'react';
+
+/**
+ * True inside a group whose tracker paints a pointer's press on its actions.
+ * Those actions take no `:active` paint, so one press never lights two.
+ */
+export const PressGroupContext = createContext(false);
+PressGroupContext.displayName = 'PressGroupContext';
diff --git a/packages/core/src/hooks/useActionGroupTracking.test.tsx b/packages/core/src/hooks/useActionGroupTracking.test.tsx
new file mode 100644
index 0000000000..05d4fe4320
--- /dev/null
+++ b/packages/core/src/hooks/useActionGroupTracking.test.tsx
@@ -0,0 +1,686 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useActionGroupTracking.test.tsx
+ * @input A component using useActionGroupTracking over two actions and a
+ * message, laid out with stubbed rects, and touch, pointer and click events
+ * dispatched on it with explicit timestamps
+ * @output The group tracking contract: the action under the finger is
+ * painted in the touch-down event; the paint follows the finger and is cut,
+ * not faded, when it leaves; the lift runs only the action under the
+ * finger, once; a touch on the message or a cancel runs nothing; a disabled
+ * action is skipped; a second finger or the window losing focus cancels;
+ * inside a scroller a flick is left to the scroller; a mouse under a fine
+ * pointer is tracked like a finger; the shared tracker does the tracking;
+ * no render per move
+ * @position jsdom tests of packages/core/src/hooks/useActionGroupTracking.ts
+ */
+
+import {act, render} from '@testing-library/react';
+import {useRef} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {GestureHost} from '../gestures/GestureHost';
+import {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer';
+import {lockSelection} from '../utils/selectionLock';
+import {
+ coarsePrimaryPointer,
+ pointerQuery,
+} from '../gestures/__tests__/pointerQuery';
+import {UIKIT_PRESS} from '../motion/uikit/gestures';
+import {PRESS_FADE_MS} from '../utils/pressGesture';
+import {createActionGroupTracker} from './actionGroupTracker';
+import type * as ActionGroupTrackerModule from './actionGroupTracker';
+import {
+ useActionGroupTracking,
+ type ActionGroupTrackingOptions,
+} from './useActionGroupTracking';
+
+// The shared tracker, spied on as it runs (family:action-groups: one module).
+vi.mock('./actionGroupTracker', async importOriginal => {
+ const actual = await importOriginal<typeof ActionGroupTrackerModule>();
+ return {
+ ...actual,
+ createActionGroupTracker: vi.fn(actual.createActionGroupTracker),
+ };
+});
+
+interface Contact {
+ id: number;
+ x: number;
+ y: number;
+}
+
+/**
+ * Dispatch a touch event for `contact`. `others` are the fingers that stay
+ * on the glass through it (the event's `touches` lists them too).
+ */
+function touch(
+ type: 'touchstart' | 'touchmove' | 'touchend' | 'touchcancel',
+ target: EventTarget,
+ contact: Contact,
+ time: number,
+ others: ReadonlyArray<Contact> = [],
+): Event {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const toEntry = (finger: Contact) => ({
+ identifier: finger.id,
+ clientX: finger.x,
+ clientY: finger.y,
+ target,
+ });
+ const isLift = type === 'touchend' || type === 'touchcancel';
+ const entry = toEntry(contact);
+ Object.defineProperty(event, 'changedTouches', {value: [entry]});
+ Object.defineProperty(event, 'touches', {
+ value: [...others.map(toEntry), ...(isLift ? [] : [entry])],
+ });
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ target.dispatchEvent(event);
+ return event;
+}
+
+/** Stub an element's layout box (jsdom lays nothing out). */
+function place(
+ element: Element,
+ box: {left: number; top: number; width: number; height: number},
+): void {
+ const rect = DOMRect.fromRect({
+ x: box.left,
+ y: box.top,
+ width: box.width,
+ height: box.height,
+ });
+ element.getBoundingClientRect = () => rect;
+}
+
+// Cancel and Delete side by side with an 8 px gap, under a message, the way
+// an alert lays out two actions.
+const MESSAGE = {left: 0, top: 0, width: 208, height: 90};
+const CANCEL = {left: 0, top: 100, width: 100, height: 48};
+const DELETE = {left: 108, top: 100, width: 100, height: 48};
+const centerOf = (box: typeof CANCEL) => ({
+ x: box.left + box.width / 2,
+ y: box.top + box.height / 2,
+});
+
+let renders = 0;
+let nextTouchId = 1;
+let time = 1000;
+
+/** A finger, with fresh ids and a clock that only moves forward. */
+function finger() {
+ const id = nextTouchId++;
+ return {
+ down(target: Element, point: {x: number; y: number}) {
+ time += 1000;
+ return touch('touchstart', target, {id, ...point}, time);
+ },
+ move(target: Element, point: {x: number; y: number}, after = 16) {
+ time += after;
+ return touch('touchmove', target, {id, ...point}, time);
+ },
+ up(target: Element, point: {x: number; y: number}, after = 16) {
+ time += after;
+ return touch('touchend', target, {id, ...point}, time);
+ },
+ cancel(target: Element, point: {x: number; y: number}) {
+ time += 16;
+ return touch('touchcancel', target, {id, ...point}, time);
+ },
+ };
+}
+
+const NO_OPTIONS: Partial<ActionGroupTrackingOptions> = {};
+
+function Group({
+ onCancel,
+ onDelete,
+ isDeleteDisabled = false,
+ options = NO_OPTIONS,
+}: {
+ onCancel: () => void;
+ onDelete: () => void;
+ isDeleteDisabled?: boolean;
+ options?: Partial<ActionGroupTrackingOptions>;
+}) {
+ renders += 1;
+ const ref = useRef<HTMLDivElement>(null);
+ useActionGroupTracking(ref, {
+ itemSelector: '[data-action]',
+ highlightOnsetMs: 0,
+ highlightExpansion: 0,
+ ...options,
+ });
+ return (
+ <div ref={ref} data-testid="group">
+ <p data-testid="message">Delete this item?</p>
+ <button type="button" data-action data-testid="cancel" onClick={onCancel}>
+ Cancel
+ </button>
+ <button
+ type="button"
+ data-action
+ data-testid="delete"
+ aria-disabled={isDeleteDisabled || undefined}
+ onClick={onDelete}>
+ Delete
+ </button>
+ </div>
+ );
+}
+
+/** Runs the frame in which the gesture host styles what it just attached. */
+function runAttachFrame(): void {
+ act(() => {
+ vi.advanceTimersToNextFrame();
+ });
+}
+
+function mount(props: Partial<Parameters<typeof Group>[0]> = {}) {
+ const onCancel = vi.fn();
+ const onDelete = vi.fn();
+ const view = render(
+ <Group onCancel={onCancel} onDelete={onDelete} {...props} />,
+ );
+ const message = view.getByTestId('message');
+ const cancel = view.getByTestId('cancel');
+ const del = view.getByTestId('delete');
+ place(message, MESSAGE);
+ place(cancel, CANCEL);
+ place(del, DELETE);
+ return {...view, onCancel, onDelete, message, cancel, del};
+}
+
+const paintOf = (element: Element) => element.getAttribute('data-astryx-press');
+
+// A phone: the gesture host attaches nothing where the primary pointer is
+// fine (`spec:AST-094` FR19).
+let restorePointer: () => void = () => {};
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ restorePointer = coarsePrimaryPointer();
+ renders = 0;
+});
+
+afterEach(() => {
+ vi.runOnlyPendingTimers();
+ vi.useRealTimers();
+ restorePointer();
+});
+
+describe('useActionGroupTracking', () => {
+ it('paints the touched action in the touch-down event and runs it once at the lift', () => {
+ const {cancel, del, onCancel, onDelete} = mount();
+ const f = finger();
+ f.down(cancel, centerOf(CANCEL));
+ expect(paintOf(cancel)).toBe('on');
+ expect(paintOf(del)).toBeNull();
+ expect(onCancel).not.toHaveBeenCalled();
+ f.up(cancel, centerOf(CANCEL), 80);
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ expect(onDelete).not.toHaveBeenCalled();
+ expect(paintOf(cancel)).toBe('fading');
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ expect(paintOf(cancel)).toBeNull();
+ });
+
+ it('moves the highlight with the finger and runs the action it lifts on', () => {
+ const {cancel, del, onCancel, onDelete} = mount();
+ const f = finger();
+ f.down(del, centerOf(DELETE));
+ expect(paintOf(del)).toBe('on');
+ // Into the gap between the actions: nothing is highlighted, and the
+ // action the finger left is cut, not faded.
+ f.move(del, {x: 104, y: 124});
+ expect(paintOf(del)).toBeNull();
+ expect(paintOf(cancel)).toBeNull();
+ f.move(del, centerOf(CANCEL));
+ expect(paintOf(cancel)).toBe('on');
+ expect(paintOf(del)).toBeNull();
+ f.up(del, centerOf(CANCEL));
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ expect(onDelete).not.toHaveBeenCalled();
+ });
+
+ it('keeps no margin around an action: 1 px outside clears it and a lift there runs nothing', () => {
+ const {del, onCancel, onDelete} = mount();
+ const f = finger();
+ f.down(del, centerOf(DELETE));
+ f.move(del, {x: 150, y: DELETE.top + DELETE.height});
+ expect(paintOf(del)).toBe('on');
+ f.move(del, {x: 150, y: DELETE.top + DELETE.height + 1});
+ expect(paintOf(del)).toBeNull();
+ f.up(del, {x: 150, y: DELETE.top + DELETE.height + 1});
+ expect(onCancel).not.toHaveBeenCalled();
+ expect(onDelete).not.toHaveBeenCalled();
+ expect(paintOf(del)).toBeNull();
+ });
+
+ it('tracks a touch that lands on the message: a tap there runs nothing, and a slide onto an action does', () => {
+ const {message, cancel, onCancel, onDelete} = mount();
+ const f = finger();
+ f.down(message, {x: 50, y: 40});
+ f.up(message, {x: 50, y: 40}, 80);
+ expect(onCancel).not.toHaveBeenCalled();
+ expect(onDelete).not.toHaveBeenCalled();
+ f.down(message, {x: 50, y: 40});
+ expect(paintOf(cancel)).toBeNull();
+ f.move(message, centerOf(CANCEL));
+ expect(paintOf(cancel)).toBe('on');
+ f.up(message, centerOf(CANCEL));
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('cuts the highlight and runs nothing when the touch is cancelled', () => {
+ const {cancel, onCancel} = mount();
+ const f = finger();
+ f.down(cancel, centerOf(CANCEL));
+ f.cancel(cancel, centerOf(CANCEL));
+ expect(paintOf(cancel)).toBeNull();
+ expect(onCancel).not.toHaveBeenCalled();
+ });
+
+ it('skips a disabled action: no highlight, and a lift on it runs nothing', () => {
+ const {cancel, del, onCancel, onDelete} = mount({isDeleteDisabled: true});
+ const f = finger();
+ f.down(cancel, centerOf(CANCEL));
+ f.move(cancel, centerOf(DELETE));
+ expect(paintOf(del)).toBeNull();
+ expect(paintOf(cancel)).toBeNull();
+ f.up(cancel, centerOf(DELETE));
+ expect(onDelete).not.toHaveBeenCalled();
+ expect(onCancel).not.toHaveBeenCalled();
+ });
+
+ it('ends the gesture with nothing acting when a second finger lands (family:action-groups FR3)', () => {
+ const {cancel, del, onCancel, onDelete} = mount();
+ const first = {id: nextTouchId++, ...centerOf(CANCEL)};
+ const second = {id: nextTouchId++, ...centerOf(DELETE)};
+ time += 1000;
+ touch('touchstart', cancel, first, time);
+ expect(paintOf(cancel)).toBe('on');
+ time += 30;
+ touch('touchstart', del, second, time, [first]);
+ // The second finger ends the gesture: its highlight is cut.
+ expect(paintOf(cancel)).toBeNull();
+ expect(paintOf(del)).toBeNull();
+ time += 16;
+ touch('touchend', del, second, time, [first]);
+ time += 16;
+ touch('touchend', cancel, first, time);
+ expect(onCancel).not.toHaveBeenCalled();
+ expect(onDelete).not.toHaveBeenCalled();
+ });
+
+ it('ends the gesture with nothing acting when the window loses focus (family:action-groups FR3)', () => {
+ const {cancel, onCancel} = mount();
+ const f = finger();
+ f.down(cancel, centerOf(CANCEL));
+ expect(paintOf(cancel)).toBe('on');
+ act(() => {
+ window.dispatchEvent(new Event('blur'));
+ });
+ expect(paintOf(cancel)).toBeNull();
+ f.up(cancel, centerOf(CANCEL));
+ expect(onCancel).not.toHaveBeenCalled();
+ });
+
+ it('tracks through the shared action-group tracker', () => {
+ vi.mocked(createActionGroupTracker).mockClear();
+ const {cancel, onCancel} = mount();
+ expect(createActionGroupTracker).toHaveBeenCalledTimes(1);
+ const f = finger();
+ f.down(cancel, centerOf(CANCEL));
+ f.up(cancel, centerOf(CANCEL));
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ expect(createActionGroupTracker).toHaveBeenCalledTimes(1);
+ });
+
+ it("tracks a mouse under a fine pointer: a press on Delete slid to Cancel runs Cancel once, and the browser's own click runs nothing more (family:action-groups FR5)", () => {
+ const {cancel, del, onCancel, onDelete} = mountFine();
+ mouseOn(del, 'pointerdown', centerOf(DELETE));
+ expect(paintOf(del)).toBe('on');
+ mouseOn(del, 'pointermove', centerOf(CANCEL));
+ expect(paintOf(del)).toBeNull();
+ expect(paintOf(cancel)).toBe('on');
+ mouseOn(cancel, 'pointerup', centerOf(CANCEL));
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ // The browser's own click for that press (on the buttons' common
+ // parent, where the press began and ended apart) runs nothing more.
+ cancel.parentElement?.dispatchEvent(
+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 1}),
+ );
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ expect(onDelete).not.toHaveBeenCalled();
+ });
+
+ it('expands the hit area for a finger only: a mouse hit-tests the exact rects (family:action-groups FR5)', () => {
+ const outside = {x: DELETE.left + DELETE.width + 5, y: centerOf(DELETE).y};
+ // A finger 5 px past Delete's edge, inside a 10 px expansion, keeps it lit.
+ const touched = mount({options: {highlightExpansion: 10}});
+ const f = finger();
+ f.down(touched.del, centerOf(DELETE));
+ f.move(touched.del, outside);
+ expect(paintOf(touched.del)).toBe('on');
+ f.cancel(touched.del, outside);
+ touched.unmount();
+ // A mouse under a fine pointer at the same point is off Delete: nothing
+ // is lit, and the release there runs nothing.
+ const {del, onCancel, onDelete} = mountFine({
+ options: {highlightExpansion: 10},
+ });
+ mouseOn(del, 'pointerdown', centerOf(DELETE));
+ expect(paintOf(del)).toBe('on');
+ mouseOn(del, 'pointermove', outside);
+ expect(paintOf(del)).toBeNull();
+ mouseOn(del, 'pointerup', outside);
+ expect(onDelete).not.toHaveBeenCalled();
+ expect(onCancel).not.toHaveBeenCalled();
+ });
+
+ /** A mouse's pointer event on `target` at `point`. */
+ function mouseOn(
+ target: Element,
+ type: string,
+ point: {x: number; y: number},
+ ) {
+ time += 16;
+ const event = new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ pointerId: 1,
+ pointerType: 'mouse',
+ isPrimary: true,
+ button: 0,
+ buttons: type === 'pointerup' ? 0 : 1,
+ clientX: point.x,
+ clientY: point.y,
+ });
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ target.dispatchEvent(event);
+ }
+
+ /** Mounts the group under a fine primary pointer, as on a desktop. */
+ function mountFine(props: Partial<Parameters<typeof Group>[0]> = {}) {
+ restorePointer();
+ restorePointer = pointerQuery(false).restore;
+ const mounted = mount(props);
+ runAttachFrame();
+ return mounted;
+ }
+
+ /** A button outside the group that holds focus before the press. */
+ function focusOutside(): HTMLButtonElement {
+ const outside = document.createElement('button');
+ document.body.appendChild(outside);
+ outside.focus();
+ return outside;
+ }
+
+ describe('focus after a slide (family:action-groups FR1)', () => {
+ it('moves focus to the lifted action when the press focused the one it began on, as a click on the lifted action does', () => {
+ const {cancel, del} = mountFine();
+ mouseOn(del, 'pointerdown', centerOf(DELETE));
+ // Chromium and Firefox focus a pressed button; Safari does not.
+ del.focus();
+ mouseOn(del, 'pointermove', centerOf(CANCEL));
+ mouseOn(cancel, 'pointerup', centerOf(CANCEL));
+ expect(document.activeElement).toBe(cancel);
+ });
+
+ it("leaves focus where it was when the press did not focus the action it began on (Safari's buttons)", () => {
+ const outside = focusOutside();
+ const {cancel, del} = mountFine();
+ mouseOn(del, 'pointerdown', centerOf(DELETE));
+ mouseOn(del, 'pointermove', centerOf(CANCEL));
+ mouseOn(cancel, 'pointerup', centerOf(CANCEL));
+ expect(document.activeElement).toBe(outside);
+ outside.remove();
+ });
+
+ it("keeps the focus the lifted action's own click moved", () => {
+ const elsewhere = focusOutside();
+ const {cancel, del} = mountFine({onCancel: () => elsewhere.focus()});
+ mouseOn(del, 'pointerdown', centerOf(DELETE));
+ del.focus();
+ mouseOn(del, 'pointermove', centerOf(CANCEL));
+ mouseOn(cancel, 'pointerup', centerOf(CANCEL));
+ expect(document.activeElement).toBe(elsewhere);
+ elsewhere.remove();
+ });
+
+ it('under a finger, a slide or a tap leaves focus on the lifted action, and a lift outside moves none', () => {
+ const outside = focusOutside();
+ const {cancel, del} = mount();
+ const f = finger();
+ f.down(del, centerOf(DELETE));
+ f.move(del, centerOf(CANCEL));
+ f.up(del, centerOf(CANCEL));
+ expect(document.activeElement).toBe(cancel);
+ outside.focus();
+ f.down(del, centerOf(DELETE));
+ f.up(del, centerOf(DELETE), 80);
+ expect(document.activeElement).toBe(del);
+ outside.focus();
+ f.down(del, centerOf(DELETE));
+ f.move(del, {x: 150, y: 400});
+ f.up(del, {x: 150, y: 400});
+ expect(document.activeElement).toBe(outside);
+ outside.remove();
+ });
+
+ it('where a tap focuses no button (iOS WebKit), a finger leaves focus where it was', () => {
+ vi.stubGlobal('CSS', {
+ ...globalThis.CSS,
+ supports: (query: string) => query === '(-webkit-touch-callout: none)',
+ });
+ try {
+ const outside = focusOutside();
+ const {del} = mount();
+ const f = finger();
+ f.down(del, centerOf(DELETE));
+ f.move(del, centerOf(CANCEL));
+ f.up(del, centerOf(CANCEL));
+ expect(document.activeElement).toBe(outside);
+ outside.remove();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+ });
+
+ /** A pen's pointer event on `target` at `point`. */
+ function pen(target: Element, type: string, point: {x: number; y: number}) {
+ time += 16;
+ const event = new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ pointerId: 41,
+ pointerType: 'pen',
+ isPrimary: true,
+ button: 0,
+ buttons: type === 'pointerup' ? 0 : 1,
+ clientX: point.x,
+ clientY: point.y,
+ });
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ target.dispatchEvent(event);
+ }
+
+ it('tracks a pen like a finger: a slide from Delete to Cancel runs Cancel, and a lift off both runs nothing', () => {
+ const {cancel, del, onCancel, onDelete} = mount();
+ pen(del, 'pointerdown', centerOf(DELETE));
+ expect(paintOf(del)).toBe('on');
+ pen(del, 'pointermove', centerOf(CANCEL));
+ expect(paintOf(del)).toBeNull();
+ expect(paintOf(cancel)).toBe('on');
+ pen(del, 'pointerup', centerOf(CANCEL));
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ const off = {x: centerOf(DELETE).x, y: 260};
+ pen(del, 'pointerdown', centerOf(DELETE));
+ pen(del, 'pointermove', off);
+ expect(paintOf(del)).toBeNull();
+ pen(del, 'pointerup', off);
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ expect(onDelete).not.toHaveBeenCalled();
+ });
+
+ it('leaves no fade behind when tracking turns off or the group unmounts', () => {
+ const view = mount();
+ const {cancel} = view;
+ // The gesture host reads the surface's touch-action in the frame after it
+ // attaches (spec:AST-094 FR18): that frame runs first. Only the fade's
+ // own timer is counted below: other timers a lift may arm outlive the
+ // group on purpose (a click guard must still swallow the lift's click
+ // after the alert closes), so each check counts the timers that go.
+ runAttachFrame();
+ const f = finger();
+ const beforeFade = vi.getTimerCount();
+ f.down(cancel, centerOf(CANCEL));
+ f.up(cancel, centerOf(CANCEL));
+ expect(paintOf(cancel)).toBe('fading');
+ const fading = vi.getTimerCount();
+ // The fade's timer is running.
+ expect(fading).toBeGreaterThan(beforeFade);
+ // The lift closed the alert: tracking stops before the fade ends, and
+ // the fade's timer goes with it.
+ view.rerender(
+ <Group
+ onCancel={view.onCancel}
+ onDelete={view.onDelete}
+ options={{isEnabled: false}}
+ />,
+ );
+ expect(paintOf(cancel)).toBeNull();
+ expect(vi.getTimerCount()).toBe(fading - 1);
+ view.rerender(<Group onCancel={view.onCancel} onDelete={view.onDelete} />);
+ runAttachFrame();
+ const g = finger();
+ g.down(cancel, centerOf(CANCEL));
+ g.up(cancel, centerOf(CANCEL));
+ expect(paintOf(cancel)).toBe('fading');
+ const fadingAgain = vi.getTimerCount();
+ view.unmount();
+ expect(paintOf(cancel)).toBeNull();
+ expect(vi.getTimerCount()).toBe(fadingAgain - 1);
+ });
+
+ it('drops its highlight when tracking turns off mid-touch, and the lift runs nothing', () => {
+ const view = mount();
+ const {cancel} = view;
+ const f = finger();
+ f.down(cancel, centerOf(CANCEL));
+ expect(paintOf(cancel)).toBe('on');
+ // The alert closes by other means while the finger rests on Cancel.
+ view.rerender(
+ <Group
+ onCancel={view.onCancel}
+ onDelete={view.onDelete}
+ options={{isEnabled: false}}
+ />,
+ );
+ expect(paintOf(cancel)).toBeNull();
+ f.up(cancel, centerOf(CANCEL));
+ expect(view.onCancel).not.toHaveBeenCalled();
+ // Turned back on, it starts clean.
+ view.rerender(<Group onCancel={view.onCancel} onDelete={view.onDelete} />);
+ const g = finger();
+ g.down(cancel, centerOf(CANCEL));
+ g.up(cancel, centerOf(CANCEL));
+ expect(view.onCancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('suppresses text selection under a held finger: the group’s hold does something (spec:AST-094 FR41)', () => {
+ const attach = vi.spyOn(GestureHost.prototype, 'attach');
+ mount();
+ const recognizer = attach.mock.calls[0]?.[1];
+ expect(recognizer).toBeInstanceOf(LongPressGestureRecognizer);
+ expect(recognizer?.selectionLock).toBe(lockSelection);
+ attach.mockRestore();
+ });
+
+ it('attaches nothing while tracking is off, and attaches when it turns on', () => {
+ const attach = vi.spyOn(GestureHost.prototype, 'attach');
+ const view = mount({options: {isEnabled: false}});
+ expect(attach).not.toHaveBeenCalled();
+ view.rerender(<Group onCancel={view.onCancel} onDelete={view.onDelete} />);
+ expect(attach).toHaveBeenCalledTimes(1);
+ attach.mockRestore();
+ });
+
+ it('tracks nothing while disabled', () => {
+ const {cancel, del, onCancel, onDelete} = mount({
+ options: {isEnabled: false},
+ });
+ const f = finger();
+ f.down(del, centerOf(DELETE));
+ expect(paintOf(del)).toBeNull();
+ f.move(del, centerOf(CANCEL));
+ f.up(del, centerOf(CANCEL));
+ expect(onCancel).not.toHaveBeenCalled();
+ expect(onDelete).not.toHaveBeenCalled();
+ expect(paintOf(cancel)).toBeNull();
+ });
+
+ it('does not render per move', () => {
+ const {cancel, del} = mount();
+ const before = renders;
+ const f = finger();
+ f.down(del, centerOf(DELETE));
+ for (let x = 150; x >= 50; x -= 10) {
+ f.move(del, {x, y: 124});
+ }
+ f.up(cancel, centerOf(CANCEL));
+ expect(renders).toBe(before);
+ });
+
+ it('leaves a touch the caller rejects to the browser', () => {
+ const {cancel, message, onCancel} = mount({
+ options: {shouldTrack: target => target !== message},
+ });
+ const f = finger();
+ f.down(message, {x: 50, y: 40});
+ f.move(message, centerOf(CANCEL));
+ expect(paintOf(cancel)).toBeNull();
+ f.up(message, centerOf(CANCEL));
+ expect(onCancel).not.toHaveBeenCalled();
+ });
+
+ describe('inside a scroller', () => {
+ function mountInScroller() {
+ const mounted = mount();
+ const group = mounted.getByTestId('group');
+ // The message scrolls: a scroller under the touch that has room.
+ group.style.overflowY = 'auto';
+ Object.defineProperty(group, 'scrollHeight', {value: 400});
+ Object.defineProperty(group, 'clientHeight', {value: 200});
+ return mounted;
+ }
+
+ it('leaves a flick to the scroller: travel past the slop before the delay tracks nothing', () => {
+ const {message, cancel, onCancel} = mountInScroller();
+ const f = finger();
+ f.down(message, {x: 50, y: 40});
+ f.move(message, {x: 50, y: 40 + UIKIT_PRESS.slop.value + 2}, 30);
+ f.move(message, centerOf(CANCEL), 30);
+ expect(paintOf(cancel)).toBeNull();
+ f.up(message, centerOf(CANCEL));
+ expect(onCancel).not.toHaveBeenCalled();
+ });
+
+ it('tracks once the finger has rested for the content-touch delay', () => {
+ const {message, cancel, onCancel} = mountInScroller();
+ const f = finger();
+ f.down(message, {x: 50, y: 40});
+ f.move(
+ message,
+ centerOf(CANCEL),
+ UIKIT_PRESS.contentTouchDelay.value + 10,
+ );
+ expect(paintOf(cancel)).toBe('on');
+ f.up(message, centerOf(CANCEL));
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/packages/core/src/hooks/useActionGroupTracking.ts b/packages/core/src/hooks/useActionGroupTracking.ts
new file mode 100644
index 0000000000..fb07c7221a
--- /dev/null
+++ b/packages/core/src/hooks/useActionGroupTracking.ts
@@ -0,0 +1,224 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useActionGroupTracking.ts
+ * @input A ref to a group of sibling actions, the actions' selector, and the
+ * component's tracking constants
+ * @output Exports useActionGroupTracking and ActionGroupTrackingOptions
+ * @position Internal hook, not exported from the hooks entry. A long press
+ * drives the shared action-group tracker (hooks/actionGroupTracker.ts) for
+ * a group that a held pointer slides across. AlertDialog consumes it.
+ *
+ * SYNC: When modified, update useActionGroupTracking.test.tsx
+ */
+
+import {useEffect, useRef, useState, type RefObject} from 'react';
+import {isActive} from '../gestures/GestureRecognizer';
+import {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer';
+import {lockSelection} from '../utils/selectionLock';
+import type {GestureTouch, PointerKind} from '../gestures/types';
+import {useGestureRecognizer} from '../gestures/useGestureRecognizer';
+import {UIKIT_PRESS} from '../motion/uikit/gestures';
+import {isIosWebKit} from '../utils/touchQueries';
+import {createActionGroupTracker} from './actionGroupTracker';
+import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';
+
+export interface ActionGroupTrackingOptions {
+ /** Selects the actions inside the tracked element. */
+ itemSelector: string;
+ /** How long after touch-down the touched action highlights, ms. */
+ highlightOnsetMs: number;
+ /**
+ * How far outside an action a finger keeps it highlighted, px. A mouse or a
+ * pen hit-tests the actions' exact rects.
+ */
+ highlightExpansion: number;
+ /** Pointers that are tracked; others keep the browser's click. @default every pointer */
+ pointerTypes?: ReadonlyArray<PointerKind>;
+ /** A press whose target this rejects is not tracked. */
+ shouldTrack?: (target: unknown) => boolean;
+ /** Off, nothing is attached and nothing is tracked. @default true */
+ isEnabled?: boolean;
+ /**
+ * Let the gesture host write the group's `touch-action` and refuse a text
+ * selection while a finger or a pen holds it.
+ * @default true
+ */
+ manageStyle?: boolean;
+ /** Runs the action under the finger at the lift. @default its own click */
+ onActivate?: (item: HTMLElement) => void;
+}
+
+const PRESS = UIKIT_PRESS;
+
+/** The ref handed to the recognizer while tracking is off: no element. */
+const DETACHED: RefObject<Element | null> = {current: null};
+
+const EVERY_POINTER: ReadonlyArray<PointerKind> = ['touch', 'pen', 'mouse'];
+
+/**
+ * The group's press: a long press that a second finger on the group ends with
+ * nothing acting. A plain long press ignores a second finger.
+ */
+class ActionGroupPress extends LongPressGestureRecognizer {
+ protected override acceptsTouch(touch: GestureTouch): boolean {
+ if (isActive(this.state)) {
+ this.setState('cancelled');
+ return false;
+ }
+ return super.acceptsTouch(touch);
+ }
+}
+
+/**
+ * Track a held pointer on the group behind `ref` across the actions inside
+ * it, through the shared action-group tracker.
+ */
+export function useActionGroupTracking(
+ ref: RefObject<HTMLElement | null>,
+ options: ActionGroupTrackingOptions,
+): ActionGroupPress {
+ const optionsRef = useRef(options);
+ // Keeps the recognizer's delegate and the tracker, which run outside
+ // render, reading the latest options.
+ useIsomorphicLayoutEffect(() => {
+ optionsRef.current = options;
+ });
+ // The pointer that started the current press. Only a finger gets the hit
+ // expansion; a mouse or a pen hit-tests the actions' exact rects.
+ const pointerRef = useRef<PointerKind>('touch');
+ const landedRef = useRef<Node | null>(null);
+ const [tracker] = useState(() =>
+ createActionGroupTracker(() => ({
+ roots: () => [ref.current],
+ itemSelector: optionsRef.current.itemSelector,
+ highlightExpansion:
+ pointerRef.current === 'touch'
+ ? optionsRef.current.highlightExpansion
+ : 0,
+ onActivate: optionsRef.current.onActivate,
+ // The browser's own click for a press the group ran is taken, so the
+ // action runs once. The gesture host swallows it for a press it claims.
+ // This covers one it does not claim, a mouse under a coarse pointer.
+ swallowsNativeClick: true,
+ })),
+ );
+ const isEnabled = options.isEnabled ?? true;
+ // Synchronizes the tracker with tracking on and mounted. Turning tracking
+ // off, or unmounting, drops a tracked press and ends its release fades.
+ // The host reports no cancellation to a disabled recognizer, and the lift
+ // that runs an action often closes the owner before its fade ends.
+ useEffect(
+ () => () => {
+ tracker.cancel();
+ tracker.dispose();
+ },
+ [tracker, isEnabled],
+ );
+
+ return useGestureRecognizer(
+ isEnabled ? ref : DETACHED,
+ () =>
+ new ActionGroupPress({
+ name: 'ActionGroupTracking',
+ minimumPressDuration: options.highlightOnsetMs,
+ allowableMovement: Number.POSITIVE_INFINITY,
+ allowedPointerTypes: options.pointerTypes ?? EVERY_POINTER,
+ delaysTouchesBegan: true,
+ // The hold picks an action, so a held finger or pen starts no text
+ // selection and opens no callout while down. A long press brings this
+ // lock by default; this hold has no minimum duration, so it names it.
+ selectionLock: lockSelection,
+ shouldReceiveTouch: (recognizer, touch) => {
+ if (recognizer.numberOfTouches === 0) {
+ pointerRef.current = touch.pointerType;
+ const target = touch.target as Node | null;
+ landedRef.current =
+ typeof target?.nodeType === 'number' ? target : null;
+ }
+ return receiveTouch(recognizer, touch, optionsRef.current);
+ },
+ }),
+ recognizer => {
+ switch (recognizer.state) {
+ case 'began': {
+ const {x, y} = recognizer.location();
+ tracker.begin(x, y, {landed: landedRef.current});
+ break;
+ }
+ case 'changed': {
+ const {x, y} = recognizer.location();
+ tracker.move(x, y);
+ break;
+ }
+ case 'ended': {
+ const doc = ref.current?.ownerDocument;
+ const focusedBefore = doc?.activeElement ?? null;
+ const beganOn = tracker.beganOn;
+ // Whether a click on the lifted action would focus it. A mouse's or
+ // a pen's pointerdown already gave the engine's answer, on the action
+ // it began on. A tap focuses on a later mousedown, which the claimed
+ // touch cancels, so the platform answers for a finger.
+ // iOS WebKit focuses no tapped button; Chromium and Firefox do.
+ const clickFocuses =
+ pointerRef.current === 'touch'
+ ? !isIosWebKit(doc?.defaultView)
+ : beganOn != null && focusedBefore === beganOn;
+ const lifted = tracker.end();
+ // The lift runs the action's own click(), which moves no focus. So
+ // focus moves to the lifted action, unless its click moved focus.
+ if (
+ clickFocuses &&
+ lifted != null &&
+ lifted.isConnected &&
+ doc?.activeElement === focusedBefore &&
+ focusedBefore !== lifted
+ ) {
+ lifted.focus({preventScroll: true, focusVisible: false});
+ }
+ break;
+ }
+ case 'cancelled':
+ tracker.cancel();
+ break;
+ case 'possible':
+ case 'failed':
+ // Listeners are not called for these.
+ break;
+ }
+ },
+ {
+ isEnabled,
+ manageStyle: options.manageStyle ?? true,
+ actionGroup: true,
+ },
+ );
+}
+
+/**
+ * The recognizer's should-receive delegate. It also picks the press's clock.
+ * Inside a scroller the press waits the content-touch delay and fails past
+ * the slop, so the scroller takes a flick. Elsewhere it begins at once, with
+ * no movement limit.
+ */
+function receiveTouch(
+ recognizer: LongPressGestureRecognizer,
+ touch: GestureTouch,
+ options: ActionGroupTrackingOptions,
+): boolean {
+ if (options.shouldTrack?.(touch.target) === false) {
+ return false;
+ }
+ if (recognizer.numberOfTouches === 0) {
+ const isInsideScroller = touch.scroll?.isInsideScroller === true;
+ recognizer.minimumPressDuration = isInsideScroller
+ ? PRESS.contentTouchDelay.value
+ : options.highlightOnsetMs;
+ recognizer.allowableMovement = isInsideScroller
+ ? PRESS.slop.value
+ : Number.POSITIVE_INFINITY;
+ }
+ return true;
+}
diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md
index 5c81bb7ae5..05e5a15d62 100644
--- a/packages/core/src/motion/README.md
+++ b/packages/core/src/motion/README.md
@@ -19,6 +19,7 @@ roles through `resolveMotion`.
| `uikit/scroll.ts` | UIScrollView: deceleration rates, rubber band, bounce-back spring, `delaysContentTouches`, scroll to top. |
| `uikit/timing.ts` | Non-spring clocks and curves: press highlight, Core Animation's named curves, keyboard, Reduced Motion cross-fade. |
| `uikit/paging.ts` | A paging UIScrollView: the integrator that settles a release on its page, the page rule, the catch, `setContentOffset(animated:)`. |
+| `uikit/alert.ts` | UIAlertController: how a finger is tracked across the actions (highlight onset and bounds). |
| `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. |
| `uikit/progressBar.ts` | UIProgressView's fill: the whole-track duration and curve, its minimum length and empty alpha; the reduced-motion pulse (three roles). |
| `uikit/gestures.ts` | Gesture recognizer thresholds, the velocity filter and haptic stand-ins, as `{value, unit}` entries (sources in JSDoc). |
diff --git a/packages/core/src/motion/uikit/alert.ts b/packages/core/src/motion/uikit/alert.ts
new file mode 100644
index 0000000000..6649ade95a
--- /dev/null
+++ b/packages/core/src/motion/uikit/alert.ts
@@ -0,0 +1,43 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file alert.ts
+ * @input Nothing; data only
+ * @output Exports `alertController`: how UIAlertController (`.alert`) tracks
+ * a finger across its actions
+ * @position The alert domain of the UIKit constants table (motion/uikit);
+ * its springs are `springs.alertPresent` and `springs.alertDismiss`
+ *
+ * Every value was read from UIKit on the iOS 26.2 simulator. A host app
+ * presented `UIAlertController(.alert)` with two and with three actions.
+ * Real HID touches drove it, and the action views' highlight was sampled
+ * every frame. Lengths are in pt (CSS px), durations in ms.
+ *
+ * Every leaf carries one or more `@source`; GUESS values also carry the
+ * `@measure` task that will confirm or replace them. uikit.test.ts enforces
+ * both.
+ *
+ * SYNC: When modified, update /packages/core/src/motion/MEASUREMENTS.md
+ */
+
+export const alertController = {
+ actions: {
+ /**
+ * How long after touch-down the touched action highlights: none, it is
+ * highlighted in the touch-down frame (a tap and a 300 ms hold alike).
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, per-frame highlight of the action views under real HID
+ * touches, Oct 23 2026
+ */
+ highlightOnsetMs: 0,
+ /**
+ * How far outside an action the finger may go and keep it highlighted:
+ * none. The highlight cleared 1 pt below the action, and a lift there ran
+ * nothing. UIButton keeps 70 pt; an alert action does not.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, per-frame highlight of the action views under real HID
+ * touches, Oct 23 2026
+ */
+ highlightExpansion: 0,
+ },
+} as const;
diff --git a/packages/core/src/privateAttributes/pressGroupItem.stylex.ts b/packages/core/src/privateAttributes/pressGroupItem.stylex.ts
new file mode 100644
index 0000000000..aa938f26bf
--- /dev/null
+++ b/packages/core/src/privateAttributes/pressGroupItem.stylex.ts
@@ -0,0 +1,23 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file privateAttributes/pressGroupItem.stylex.ts
+ * @input Nothing: the private press-group-item attribute
+ * @output pressGroupItemProps, which marks an action a group's tracker
+ * follows, and isTrackedByGroup, which reads the mark
+ * @position Owner module of the private press-group-item attribute: the only
+ * file that writes its name. AlertDialog marks its actions, and the press
+ * controller (utils/pressFeedback.ts) leaves their press to the group's
+ * tracker. No package entry exports it.
+ */
+
+const PRESS_GROUP_ITEM = 'data-astryx-press-group-item';
+
+/** Spread on each action that a group's tracker follows. */
+export const pressGroupItemProps: Readonly<Record<string, string>> = {
+ [PRESS_GROUP_ITEM]: '',
+};
+
+/** Whether a group's tracker paints the press on `element` or an ancestor. */
+export function isTrackedByGroup(element: Element): boolean {
+ return element.closest(`[${PRESS_GROUP_ITEM}]`) != null;
+}
diff --git a/packages/core/src/utils/interactionOverlay.stylex.ts b/packages/core/src/utils/interactionOverlay.stylex.ts
index d2fde43b41..4b3fc3349c 100644
--- a/packages/core/src/utils/interactionOverlay.stylex.ts
+++ b/packages/core/src/utils/interactionOverlay.stylex.ts
@@ -15,8 +15,9 @@
* SYNC: When modified, update pressFeedback.ts, pressGesture.ts (the fade
* clock), hooks/usePressFeedback.doc.mjs, the components that paint the touch
* press off an ancestor scope or a pseudo-element (Switch, Tab,
- * CheckboxInput, RadioListItem, ClickableCard, SelectableCard, Thumbnail)
- * and scripts/build-css.test.mjs.
+ * CheckboxInput, RadioListItem, ClickableCard, SelectableCard, Thumbnail),
+ * Button (a tracked action sizes its `:active` image to zero) and
+ * scripts/build-css.test.mjs.
*/
// Every surface that paints a press uses one of these styles, so a change to
diff --git a/packages/core/src/utils/pressFeedback.test.ts b/packages/core/src/utils/pressFeedback.test.ts
index 470126e029..940b2dc4ae 100644
--- a/packages/core/src/utils/pressFeedback.test.ts
+++ b/packages/core/src/utils/pressFeedback.test.ts
@@ -33,6 +33,10 @@ import {
PRESSABLE_ATTRIBUTE,
PRESSED_ATTRIBUTE,
} from './pressFeedback';
+import {
+ isTrackedByGroup,
+ pressGroupItemProps,
+} from '../privateAttributes/pressGroupItem.stylex';
import {
PRESS_FADE_MS,
PRESS_FLASH_MS,
@@ -249,6 +253,24 @@ describe('the press reaches the surface the finger landed on', () => {
expect(pressedRow()).toBe(-1);
});
+ it('paints a Space press on a tracked action where the primary pointer is fine: a tracked action takes no `:active` paint', () => {
+ expect(window.matchMedia('(pointer: coarse)').matches).toBe(false);
+ const button = pressable('button');
+ for (const [name, value] of Object.entries(pressGroupItemProps)) {
+ button.setAttribute(name, value);
+ }
+ rows[0].appendChild(button);
+ button.focus();
+ button.dispatchEvent(
+ new KeyboardEvent('keydown', {key: ' ', bubbles: true, cancelable: true}),
+ );
+ expect(button.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ button.dispatchEvent(
+ new KeyboardEvent('keyup', {key: ' ', bubbles: true, cancelable: true}),
+ );
+ expect(button.getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ });
+
it('leaves a Space press to `:active` where the primary pointer is fine', () => {
expect(window.matchMedia('(pointer: coarse)').matches).toBe(false);
const button = pressable('button');
@@ -283,6 +305,65 @@ describe('the press reaches the surface the finger landed on', () => {
});
});
+describe('an action group whose own tracker paints its actions', () => {
+ // The group's tracker follows a held pointer across its actions and paints
+ // them. The controller must not write the press attribute there too.
+ function group(): {actions: HTMLElement[]; field: HTMLElement} {
+ const root = document.createElement('div');
+ const actions = [pressable('button'), pressable('button')];
+ for (const action of actions) {
+ for (const [name, value] of Object.entries(pressGroupItemProps)) {
+ action.setAttribute(name, value);
+ }
+ root.appendChild(action);
+ }
+ // A member the tracker skips (a menu trigger) carries no marker.
+ const field = pressable('button');
+ root.appendChild(field);
+ document.body.appendChild(root);
+ return {actions, field};
+ }
+
+ it('paints nothing on an action its group tracks', () => {
+ const {actions} = group();
+ expect(isTrackedByGroup(actions[0])).toBe(true);
+ press(actions[0], 'pointerdown', 10, 10);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ press(actions[0], 'pointerup', 10, 10);
+ vi.advanceTimersByTime(PRESS_FLASH_MS);
+ expect(actions[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('leaves the paint the group writes on it alone', () => {
+ const {actions} = group();
+ actions[1].setAttribute(PRESSED_ATTRIBUTE, 'on');
+ press(actions[1], 'pointerdown', 10, 10);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ press(actions[1], 'pointercancel', 10, 10);
+ expect(actions[1].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+
+ it('still paints a member the group does not track', () => {
+ const {field} = group();
+ press(field, 'pointerdown', 10, 10);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ expect(field.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+
+ it('still records the touch, so a scroll it drives brakes the next one', () => {
+ const {actions} = group();
+ scroller.appendChild(actions[0].parentElement as HTMLElement);
+ press(actions[0], 'pointerdown', 10, 10);
+ // The browser takes the touch to scroll: the cancel records nothing, so
+ // the touch-down alone must have recorded the finger.
+ press(actions[0], 'pointercancel', 10, 10);
+ scroller.dispatchEvent(new Event('scroll'));
+ press(rows[1], 'pointerdown', 10, 100);
+ vi.advanceTimersByTime(PRESS_ONSET_MS * 2);
+ expect(pressedRow()).toBe(-1);
+ });
+});
+
describe('a scroll takes it away and nothing brings it back', () => {
it('clears on a scroll from the ancestor scroller', () => {
press(rows[1], 'pointerdown', 10, 10);
@@ -678,6 +759,32 @@ describe('a phone or tablet paints a mouse or Space press itself', () => {
}
});
+ function groupAction(row: HTMLElement): HTMLButtonElement {
+ const action = focusedButton(row);
+ for (const [name, value] of Object.entries(pressGroupItemProps)) {
+ action.setAttribute(name, value);
+ }
+ return action;
+ }
+
+ it("leaves a mouse press on an action its group tracks to the group's tracker", () => {
+ const action = groupAction(rows[1]);
+ press(action, 'pointerdown', 10, 100, 'mouse');
+ expect(action.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ // The tracker's own paint is left alone through the release.
+ action.setAttribute(PRESSED_ATTRIBUTE, 'on');
+ press(action, 'pointerup', 10, 100, 'mouse');
+ expect(action.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+
+ it('still paints a Space press on a focused action its group tracks: the group tracks pointers only', () => {
+ const action = groupAction(rows[1]);
+ key(action, 'keydown');
+ expect(action.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ key(action, 'keyup');
+ expect(action.getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ });
+
it('keeps the paint while the mouse is dragged off the surface, as `:active` does', () => {
press(rows[1], 'pointerdown', 10, 100, 'mouse');
press(document.body, 'pointermove', 400, 900, 'mouse');
diff --git a/packages/core/src/utils/pressFeedback.ts b/packages/core/src/utils/pressFeedback.ts
index 971d6aedbc..f1de60107b 100644
--- a/packages/core/src/utils/pressFeedback.ts
+++ b/packages/core/src/utils/pressFeedback.ts
@@ -2,8 +2,8 @@
/**
* @file pressFeedback.ts
- * @input The press state machine (pressGesture.ts), the menu-press marker
- * (hooks/menuPressMarker.ts) and the document's pointer, keyboard, scroll and
+ * @input The press state machine (pressGesture.ts), the menu-press and
+ * press-group markers and the document's pointer, keyboard, scroll and
* visibility events
* @output PRESSABLE_ATTRIBUTE, PRESSED_ATTRIBUTE, pressableProps and
* installPressFeedback
@@ -46,6 +46,7 @@ import {isCoarsePointer, watchCoarsePointer} from './coarsePointer';
import {subscribeInput} from './inputStream';
import {TOUCH_QUERY} from './touchPresentation';
import {holdsPressThroughDrag} from '../privateAttributes/pressHoldsDrag.stylex';
+import {isTrackedByGroup} from '../privateAttributes/pressGroupItem.stylex';
/**
* The marker the controller finds with `closest()`. Every Astryx component
@@ -325,8 +326,9 @@ function stylesheetDroppedActive(): boolean {
/**
* The surface a mouse button's or the Space key's press paints, if any: the
- * innermost marked surface, outside a menu. A key's press paints only a
- * focused element that is itself the surface, as `:active` does.
+ * innermost marked surface, outside a menu and off a tracked action. A key's
+ * press paints only a focused element that is itself the surface, as
+ * `:active` does.
*/
function buttonSurfaceAt(
target: EventTarget | null,
@@ -336,6 +338,10 @@ function buttonSurfaceAt(
if (element == null || element.closest(MENU_PRESS_ROOT) != null) {
return null;
}
+ // A group's tracker follows pointers only, so a key's press stays here.
+ if (pointerId != null && isTrackedByGroup(element)) {
+ return null;
+ }
if (pointerId == null && element !== target) {
return null;
}
@@ -414,7 +420,9 @@ function onPointerDown(event: PointerEvent): void {
const braking = element != null && scrollerIsBraking(element);
lastTouchAt = Date.now();
lastTouchTarget = event.target instanceof Node ? event.target : null;
- if (element == null || braking) {
+ // A group's tracker paints a tracked action, so two writers would erase each
+ // other's paint. The touch still counts for the brake above.
+ if (element == null || braking || isTrackedByGroup(element)) {
return;
}
takeOver(button, element);
@@ -560,6 +568,11 @@ function activatesOnSpace(target: EventTarget | null): boolean {
);
}
+/** A tracked action takes no `:active` paint, so a key's press paints here. */
+function isTrackedAction(target: EventTarget | null): boolean {
+ return target instanceof Element && isTrackedByGroup(target);
+}
+
/**
* Space went down on a focused button that is itself a pressable surface.
* Heard in the BUBBLE phase, after the page's own handlers, so a press the
@@ -573,7 +586,7 @@ function onKeyDown(event: KeyboardEvent): void {
event.isComposing ||
event.defaultPrevented ||
!activatesOnSpace(event.target) ||
- !stylesheetDroppedActive()
+ !(stylesheetDroppedActive() || isTrackedAction(event.target))
) {
return;
}
diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs
index 3e7004ca92..e5bd50531b 100644
--- a/scripts/touch-support-bundle.test.mjs
+++ b/scripts/touch-support-bundle.test.mjs
@@ -138,6 +138,13 @@ function filesUnder(dir, pattern) {
* that reaches it, with a comment naming the gesture.
*/
const GESTURE_USERS = new Set([
+ // AlertDialog: its actions' press, tracked across both for every pointer.
+ 'AlertDialog',
+ // Through AlertDialog: Tokenizer's bottom sheet confirms with an alert, and
+ // PowerSearch and Table's filtering render a Tokenizer.
+ 'PowerSearch',
+ 'Table',
+ 'Tokenizer',
// Slider's thumb.
'Slider',
// Switch: its press tracking and its drag, for every pointer.