Skip to content

Commit 37860b7

Browse files
committed
fix(AlertDialog): a finger that slides between the actions runs the one it lifts on
On a touch screen the two actions are tracked as one group, the way iOS tracks an alert's actions (measured on the iOS 26.2 simulator): - the touched action highlights in the touch-down frame, not 150 ms later; - the highlight follows the finger from one action to the other, and is cut when the finger leaves an action (no expanded bounds); - lifting runs the action under the finger, once; off both, nothing; - a touch that lands on the message can slide onto an action; - the backdrop is not part of the group. One zero-duration long press over the dialog surface does it (internal useActionGroupTracking hook, shared with menus and action sheets later). The action runs through its own click inside the lift, so a mouse, the keyboard and assistive technology are unchanged, and text stays selectable with a mouse. The measured values live in motion/uikit/alert.ts.
1 parent 5eed478 commit 37860b7

10 files changed

Lines changed: 1188 additions & 8 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[fix] AlertDialog: on a touch screen the two actions are tracked as one group, the way iOS tracks an alert's actions. A finger that lands on one action and slides to the other now runs the action it lifts on. Before, iOS Safari ran the action the finger first touched (Delete, when the finger slid to Cancel), and other browsers ran nothing and left the alert open. The touched action highlights as soon as it is touched instead of 150 ms later, the highlight follows the finger between the actions, and lifting off both still runs nothing. A mouse, the keyboard and assistive technology keep each button's own click, and text stays selectable with a mouse.
6+
7+
@vjeux

‎packages/core/src/AlertDialog/AlertDialog.doc.mjs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ export const docs = {
2121
],
2222
usage: {
2323
description:
24-
'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.',
24+
'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\nOn a touch screen the two actions are tracked as one group, the way iOS tracks the actions of an alert: the action under the finger highlights as soon as it is touched, the highlight follows the finger from one action to the other, and lifting the finger runs the action under it. Lifting it off both actions runs nothing. A mouse, 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.',
2525
bestPractices: [
2626
{
2727
guidance: true,
@@ -196,7 +196,7 @@ export const docsDense = {
196196
'Confirms destructive/irreversible action before it happens (delete, revoke access, discard unsaved changes).',
197197
usage: {
198198
description:
199-
'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.',
199+
'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. Touch: both actions tracked as one group like iOS alerts (action under finger highlights at once, highlight follows finger between actions, lift runs action under finger, lift off both runs nothing); mouse/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.',
200200
bestPractices: [
201201
{
202202
guidance: true,

‎packages/core/src/AlertDialog/AlertDialog.test.tsx‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,122 @@ describe('AlertDialog', () => {
433433
});
434434
});
435435

436+
/**
437+
* Touch tracking: a finger is tracked across both actions as one group, as
438+
* UIKit tracks an alert's actions (measured on iOS 26.2). The tracking hook's
439+
* own contract is covered in hooks/useActionGroupTracking.test.tsx; these
440+
* cover AlertDialog's wiring of it.
441+
*/
442+
describe('AlertDialog touch tracking', () => {
443+
let touchClock = 10_000;
444+
let touchId = 500;
445+
446+
function touch(
447+
type: 'touchstart' | 'touchmove' | 'touchend',
448+
target: Element,
449+
point: {x: number; y: number},
450+
id: number,
451+
): void {
452+
touchClock += 16;
453+
const event = new Event(type, {bubbles: true, cancelable: true});
454+
const entry = {identifier: id, clientX: point.x, clientY: point.y, target};
455+
Object.defineProperty(event, 'changedTouches', {value: [entry]});
456+
Object.defineProperty(event, 'touches', {
457+
value: type === 'touchend' ? [] : [entry],
458+
});
459+
Object.defineProperty(event, 'timeStamp', {value: touchClock});
460+
target.dispatchEvent(event);
461+
}
462+
463+
function place(element: Element, left: number, top: number): void {
464+
const rect = DOMRect.fromRect({x: left, y: top, width: 120, height: 32});
465+
element.getBoundingClientRect = () => rect;
466+
}
467+
468+
function renderOpen(props: {isInline?: boolean} = {}) {
469+
stubAlertDialogMedia({
470+
smallScreen: true,
471+
coarsePointer: true,
472+
noHover: true,
473+
});
474+
const onOpenChange = vi.fn();
475+
const onAction = vi.fn();
476+
render(
477+
<AlertDialog
478+
isOpen
479+
isInline={props.isInline}
480+
onOpenChange={onOpenChange}
481+
title="Delete item?"
482+
description="This cannot be undone."
483+
actionLabel="Delete"
484+
onAction={onAction}
485+
/>,
486+
);
487+
const cancel = screen.getByRole('button', {name: 'Cancel'});
488+
const action = screen.getByRole('button', {name: 'Delete'});
489+
// Stacked on a narrow screen: the action above Cancel.
490+
place(action, 16, 100);
491+
place(cancel, 16, 140);
492+
return {onOpenChange, onAction, cancel, action};
493+
}
494+
495+
afterEach(() => {
496+
vi.unstubAllGlobals();
497+
});
498+
499+
it('marks both actions for the tracking and takes them off the document press controller', () => {
500+
const {cancel, action} = renderOpen();
501+
for (const button of [cancel, action]) {
502+
expect(button).toHaveAttribute('data-astryx-alert-action');
503+
expect(button).not.toHaveAttribute('data-astryx-pressable');
504+
}
505+
});
506+
507+
it('keeps the document press controller in the inline preview, which is not tracked', () => {
508+
const {cancel, action} = renderOpen({isInline: true});
509+
for (const button of [cancel, action]) {
510+
expect(button).toHaveAttribute('data-astryx-pressable');
511+
}
512+
});
513+
514+
it('cancels when a finger lands on the action and lifts on Cancel', () => {
515+
const {onOpenChange, onAction, cancel, action} = renderOpen();
516+
const id = touchId++;
517+
touch('touchstart', action, {x: 60, y: 116}, id);
518+
expect(action).toHaveAttribute('data-astryx-press', 'on');
519+
touch('touchmove', action, {x: 60, y: 156}, id);
520+
expect(action).not.toHaveAttribute('data-astryx-press');
521+
expect(cancel).toHaveAttribute('data-astryx-press', 'on');
522+
touch('touchend', action, {x: 60, y: 156}, id);
523+
expect(onOpenChange).toHaveBeenCalledTimes(1);
524+
expect(onOpenChange).toHaveBeenCalledWith(false);
525+
expect(onAction).not.toHaveBeenCalled();
526+
});
527+
528+
it('runs the action when a finger slides from Cancel onto it', () => {
529+
const {onOpenChange, onAction, cancel} = renderOpen();
530+
const id = touchId++;
531+
touch('touchstart', cancel, {x: 60, y: 156}, id);
532+
touch('touchmove', cancel, {x: 60, y: 116}, id);
533+
touch('touchend', cancel, {x: 60, y: 116}, id);
534+
expect(onAction).toHaveBeenCalledTimes(1);
535+
expect(onOpenChange).not.toHaveBeenCalled();
536+
});
537+
538+
it('does not track a touch that starts on the backdrop', () => {
539+
const {onOpenChange, onAction, cancel} = renderOpen();
540+
const dialog = screen.getByRole('alertdialog');
541+
const id = touchId++;
542+
// A touch on ::backdrop targets the dialog element itself.
543+
touch('touchstart', dialog, {x: 60, y: 400}, id);
544+
touch('touchmove', dialog, {x: 60, y: 156}, id);
545+
expect(cancel).not.toHaveAttribute('data-astryx-press');
546+
touch('touchend', dialog, {x: 60, y: 156}, id);
547+
expect(onOpenChange).not.toHaveBeenCalled();
548+
expect(onAction).not.toHaveBeenCalled();
549+
});
550+
});
551+
436552
describe('useImperativeAlertDialog', () => {
437553
const noop = () => {};
438554

‎packages/core/src/AlertDialog/AlertDialog.tsx‎

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,29 @@
44

55
/**
66
* @file AlertDialog.tsx
7-
* @input Uses React, StyleX, Dialog, Layout, Heading, Text, Button
7+
* @input Uses React, StyleX, Dialog, Layout, Heading, Text, Button,
8+
* useActionGroupTracking and the alert entries of the UIKit constants table
89
* @output Exports AlertDialog component, AlertDialogProps type
910
* @position Core implementation; consumed by index.ts, tested by AlertDialog.test.tsx
1011
*
12+
* Under a finger the two actions are tracked as one group, as UIKit tracks an
13+
* alert's actions: the action under the finger highlights at once, the
14+
* highlight follows the finger from one action to the other, and lifting runs
15+
* the action under the finger (none when it is off both). Tracking spans the
16+
* whole surface, so a touch that lands on the message can still slide onto an
17+
* action. A mouse, the keyboard and assistive technology keep the buttons'
18+
* own click.
19+
*
1120
* SYNC: When modified, update these files to stay in sync:
1221
* - /packages/core/src/AlertDialog/AlertDialog.doc.mjs (props table, features, examples)
1322
* - /packages/core/src/AlertDialog/AlertDialog.test.tsx (tests for new/changed behavior)
1423
* - /packages/core/src/AlertDialog/index.ts (exports if types change)
24+
* - /packages/core/src/AlertDialog/__tests__/AlertDialog.interaction.browser.spec.ts (touch tracking)
1525
* - /apps/storybook/stories/AlertDialog.stories.tsx (storybook stories)
1626
* - /packages/cli/assets/templates/blocks/components/AlertDialog/ (showcase blocks)
1727
*/
1828

19-
import React, {useId, useCallback} from 'react';
29+
import React, {useId, useCallback, useRef} from 'react';
2030
import * as stylex from '@stylexjs/stylex';
2131
import {Dialog} from '../Dialog';
2232
import {Layout} from '../Layout/Layout';
@@ -31,10 +41,27 @@ import {mergeProps} from '../utils';
3141
import {themeProps} from '../utils/themeProps';
3242
import {useTranslator} from '../i18n';
3343
import {useMediaQuery} from '../hooks';
44+
import {useActionGroupTracking} from '../hooks/useActionGroupTracking';
45+
import {useMergedRefs} from '../hooks/useMergedRefs';
46+
import {alertController} from '../motion/uikit/alert';
3447

3548
const SMALL_SCREEN_QUERY = '(max-width: 640px)';
3649

50+
/** Marks the actions the touch tracking hit-tests. */
51+
const ACTION_ATTRIBUTE = 'data-astryx-alert-action';
52+
3753
const styles = stylex.create({
54+
// The action tracking claims a touch on the surface the moment it lands, as
55+
// a long press does: the browser keeps panning and zooming a touch nobody
56+
// claims, and a held finger opens no callout and starts no text selection
57+
// (an alert's text is not selectable under a finger). A mouse keeps
58+
// selecting text, which is why the gesture host does not write these.
59+
trackingSurface: {
60+
touchAction: 'manipulation',
61+
WebkitTouchCallout: {default: null, '@media (pointer: coarse)': 'none'},
62+
WebkitUserSelect: {default: null, '@media (pointer: coarse)': 'none'},
63+
userSelect: {default: null, '@media (pointer: coarse)': 'none'},
64+
},
3865
action: {
3966
maxWidth: '100%',
4067
minWidth: 0,
@@ -170,6 +197,28 @@ export function AlertDialog({
170197
onOpenChange(false);
171198
}, [onOpenChange]);
172199

200+
// A finger is tracked across both actions as one group (UIKit's alert
201+
// tracking); the backdrop, where a touch targets the dialog itself, is not
202+
// part of it. Each action opts out of its own press tracking while the
203+
// group owns its touches, and runs through its own click at the lift.
204+
const surfaceRef = useRef<HTMLDialogElement>(null);
205+
const mergedRef = useMergedRefs(ref, surfaceRef);
206+
const isTracking = isOpen && !isInline;
207+
useActionGroupTracking(surfaceRef, {
208+
itemSelector: `[${ACTION_ATTRIBUTE}]`,
209+
highlightOnsetMs: alertController.actions.highlightOnsetMs,
210+
highlightExpansion: alertController.actions.highlightExpansion,
211+
shouldTrack: target => target !== surfaceRef.current,
212+
isEnabled: isTracking,
213+
manageStyle: false,
214+
});
215+
const actionTrackingProps = {
216+
[ACTION_ATTRIBUTE]: '',
217+
// Overrides Button's own marker for the document press controller, which
218+
// would otherwise paint (and un-paint) the same attribute on its own clock.
219+
'data-astryx-pressable': isTracking ? undefined : '',
220+
};
221+
173222
const buttonActionStyle = [
174223
styles.action,
175224
isSmallScreen && styles.stackedAction,
@@ -181,6 +230,7 @@ export function AlertDialog({
181230
label={cancelLabel}
182231
onClick={handleCancel}
183232
xstyle={buttonActionStyle}
233+
{...actionTrackingProps}
184234
// Dialog focuses [data-autofocus] itself after showModal(), because
185235
// React's autoFocus runs during commit while the dialog is invisible.
186236
// Cancel is least destructive, so it remains the autofocus target even
@@ -196,13 +246,14 @@ export function AlertDialog({
196246
onClick={onAction}
197247
isLoading={isActionLoading}
198248
xstyle={buttonActionStyle}
249+
{...actionTrackingProps}
199250
/>
200251
);
201252

202253
return (
203254
<Dialog
204255
{...rest}
205-
ref={ref}
256+
ref={mergedRef}
206257
isOpen={isOpen}
207258
isInline={isInline}
208259
onOpenChange={onOpenChange}
@@ -217,7 +268,7 @@ export function AlertDialog({
217268
aria-labelledby={titleId}
218269
aria-describedby={descriptionId}
219270
{...mergeProps(themeProps('alert-dialog'), {className, style})}
220-
xstyle={xstyle}
271+
xstyle={[isTracking && styles.trackingSurface, xstyle]}
221272
data-testid={testId}>
222273
<Layout
223274
content={

0 commit comments

Comments
 (0)