Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/alertdialog-touch-action-tracking.md
Original file line number Diff line number Diff line change
@@ -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
7 changes: 7 additions & 0 deletions .changeset/press-group-item-marker.md
Original file line number Diff line number Diff line change
@@ -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
28 changes: 14 additions & 14 deletions docs/specs/components/AlertDialog/AlertDialog.spec.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -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"
],
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/AlertDialog/AlertDialog.doc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
222 changes: 218 additions & 4 deletions packages/core/src/AlertDialog/AlertDialog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,46 @@
* 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,
waitFor,
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,
Expand All @@ -32,6 +60,7 @@ function stubAlertDialogMedia({
noHover: boolean;
reduceMotion?: boolean;
}): void {
isCoarsePrimaryPointer = coarsePointer;
vi.stubGlobal(
'matchMedia',
vi.fn((query: string) => {
Expand Down Expand Up @@ -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,
Expand All @@ -81,6 +119,7 @@ beforeEach(() => {

afterEach(() => {
vi.unstubAllGlobals();
isCoarsePrimaryPointer = false;
});

describe('AlertDialog', () => {
Expand Down Expand Up @@ -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();
Expand All @@ -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');
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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 = () => {};

Expand Down
Loading
Loading