Skip to content

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

TypeScript

fix(DropdownMenu): a late native click after a touch drill-in no longer picks a row (#8275)

Christopher Chedeaucec65f35fef5
diff --git a/.changeset/menu-press-late-touch-click.md b/.changeset/menu-press-late-touch-click.md
new file mode 100644
index 0000000000..b725283d4a
--- /dev/null
+++ b/.changeset/menu-press-late-touch-click.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A finger's tap that a DropdownMenu (or any menu on the press model) tracks now cancels that touch's `touchend`, on every device, so the browser sends no click and no compatibility mouse events for it. Before, a busy main thread could hold that click past the 400 ms click guard window. After a tap that drilled into a sub-menu, the late click picked the sub-menu row that had come under the finger and closed the menu. A mouse or pen release keeps the 400 ms window.
+
+@vjeux
diff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts
index 8621a1ecea..a2694f1531 100644
--- a/packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts
+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts
@@ -144,6 +144,54 @@ test.describe('on a phone (coarse pointer)', () => {
await page.getByRole('menuitem', {name: 'Folder A'}).tap();
await expect(trigger).toHaveAttribute('aria-expanded', 'false');
});
+
+ test("a drill-in tap's touch sends no click and no mouse event to the page (spec:AST-094 FR21)", async ({
+ page,
+ }) => {
+ await mount(page);
+ const trigger = page.getByRole('button', {name: 'Actions'});
+ await trigger.tap();
+ await expect(page.getByRole('menu', {name: 'Actions'})).toBeVisible();
+
+ // What the browser sends for the next touch, logged ahead of the page's own
+ // listeners, and, for the touchend, after them (whether it was cancelled).
+ await page.evaluate(() => {
+ const log: string[] = [];
+ (window as unknown as {fr21Log: string[]}).fr21Log = log;
+ for (const type of ['pointerup', 'mousedown', 'mouseup', 'click']) {
+ window.addEventListener(
+ type,
+ event => {
+ if (event.isTrusted) {
+ log.push(type);
+ }
+ },
+ true,
+ );
+ }
+ window.addEventListener('touchend', event => {
+ if (event.isTrusted) {
+ log.push(event.defaultPrevented ? 'touchend cancelled' : 'touchend');
+ }
+ });
+ });
+ await page.getByRole('menuitem', {name: 'Move to'}).tap();
+ await expect(page.getByRole('menu', {name: 'Move to'})).toBeVisible();
+ // Past the stray-click window, so a late click would have shown by now.
+ await page.waitForTimeout(700);
+
+ expect(
+ await page.evaluate(
+ () => (window as unknown as {fr21Log: string[]}).fr21Log,
+ ),
+ ).toEqual(['pointerup', 'touchend cancelled']);
+ await expect(shownRows(page)).toHaveText([
+ 'Back to Actions',
+ 'Folder A',
+ 'Folder B',
+ 'Archive',
+ ]);
+ });
});
test.describe('on a laptop (fine pointer)', () => {
diff --git a/packages/core/src/hooks/useMenuPress.test.tsx b/packages/core/src/hooks/useMenuPress.test.tsx
index 2fddd8e788..f2a7f13c0c 100644
--- a/packages/core/src/hooks/useMenuPress.test.tsx
+++ b/packages/core/src/hooks/useMenuPress.test.tsx
@@ -108,6 +108,14 @@ function Harness({
const row = (label: string) => screen.getByRole('menuitem', {name: label});
const touch = (pointerId = 1) => ({pointerType: 'touch', pointerId});
const mouse = (pointerId = 1) => ({pointerType: 'mouse', pointerId, button: 0});
+const pen = (pointerId = 1) => ({pointerType: 'pen', pointerId, button: 0});
+
+/** A cancelable `touchend` at `target`, as a browser fires it after the touch's `pointerup`. */
+function fireTouchEnd(target: Element): Event {
+ const event = new Event('touchend', {bubbles: true, cancelable: true});
+ target.dispatchEvent(event);
+ return event;
+}
beforeEach(() => {
__resetMenuPressForTest();
@@ -304,6 +312,153 @@ describe('useMenuPress — one gesture, one activation', () => {
});
});
+describe("useMenuPress — a finger's touchend (spec:AST-094 FR21)", () => {
+ // A phone or tablet (a coarse primary pointer), or a touchscreen laptop
+ // (a fine one): FR21 covers a finger on every device (spec:AST-094 FR43).
+ const stubPrimaryPointer = (kind: 'coarse' | 'fine') => {
+ vi.stubGlobal('matchMedia', (query: string) => ({
+ matches: kind === 'coarse' && query === '(pointer: coarse)',
+ media: query,
+ onchange: null,
+ addListener: () => {},
+ removeListener: () => {},
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ dispatchEvent: () => false,
+ }));
+ };
+ beforeEach(() => {
+ stubPrimaryPointer('coarse');
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("a finger's tap on a row cancels that touch's touchend, so the browser sends no click", () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerUp(row('A'), touch());
+ expect(fireTouchEnd(row('A')).defaultPrevented).toBe(true);
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ expect(onSelect).toHaveBeenCalledWith('A');
+ });
+
+ it('a finger that slides onto another row and lifts there cancels its touchend', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerMove(row('B'), touch());
+ fireEvent.pointerUp(row('B'), touch());
+ // The touch's events stay with the element it landed on.
+ expect(fireTouchEnd(row('A')).defaultPrevented).toBe(true);
+ expect(onSelect).toHaveBeenCalledWith('B');
+ });
+
+ it('a finger released outside the menu cancels its touchend, and the menu stays open', () => {
+ const onDismiss = vi.fn();
+ render(<Harness onDismiss={onDismiss} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerMove(screen.getByTestId('outside'), touch());
+ fireEvent.pointerUp(screen.getByTestId('outside'), touch());
+ expect(fireTouchEnd(row('A')).defaultPrevented).toBe(true);
+ expect(onDismiss).not.toHaveBeenCalled();
+ });
+
+ it('the finger that opened the menu from the trigger cancels its touchend at the lift', () => {
+ vi.useFakeTimers();
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, touch());
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS);
+ });
+ fireEvent.pointerMove(row('C'), touch());
+ fireEvent.pointerUp(row('C'), touch());
+ expect(fireTouchEnd(trigger).defaultPrevented).toBe(true);
+ expect(onSelect).toHaveBeenCalledWith('C');
+ });
+
+ it("a finger's tap on the trigger keeps its touchend: its click opens the menu", () => {
+ const onOpenChange = vi.fn();
+ render(<Harness onOpenChange={onOpenChange} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, touch());
+ fireEvent.pointerUp(trigger, touch());
+ expect(fireTouchEnd(trigger).defaultPrevented).toBe(false);
+ fireEvent.click(trigger, {detail: 1});
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ });
+
+ it('a mouse or a pen release cancels no touchend; its stray click is still swallowed', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ for (const pointer of [mouse, pen]) {
+ fireEvent.pointerDown(row('A'), pointer());
+ fireEvent.pointerUp(row('A'), pointer());
+ expect(fireTouchEnd(row('A')).defaultPrevented).toBe(false);
+ fireEvent.click(row('A'), {detail: 1});
+ }
+ expect(onSelect).toHaveBeenCalledTimes(2);
+ });
+
+ it('a touch the browser took (pointercancel) has its touchend left alone', () => {
+ render(<Harness />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerCancel(row('A'), touch());
+ expect(fireTouchEnd(row('A')).defaultPrevented).toBe(false);
+ });
+
+ it('once the touchend is cancelled, the swallower stands down: a later click with no press behind it acts (module FR5)', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerUp(row('A'), touch());
+ expect(fireTouchEnd(row('A')).defaultPrevented).toBe(true);
+ // Well inside the stray-click window, a click that no tracked gesture
+ // explains, a script's say.
+ fireEvent.click(row('B'), {detail: 1});
+ expect(onSelect.mock.calls).toEqual([['A'], ['B']]);
+ });
+
+ it('where the primary pointer is fine too, a finger\u2019s tracked release cancels its touchend, and its stray click acts on nothing (spec:AST-094 FR21, FR43)', () => {
+ stubPrimaryPointer('fine');
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerMove(row('B'), touch());
+ fireEvent.pointerUp(row('B'), touch());
+ expect(fireTouchEnd(row('B')).defaultPrevented).toBe(true);
+ expect(onSelect.mock.calls).toEqual([['B']]);
+ });
+
+ it('where the primary pointer is fine too, a finger that lifts outside the menu has its touchend cancelled, and the menu stays open (spec:AST-094 FR21, FR28, FR43)', () => {
+ stubPrimaryPointer('fine');
+ const onDismiss = vi.fn();
+ render(<Harness onDismiss={onDismiss} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerMove(screen.getByTestId('outside'), touch());
+ fireEvent.pointerUp(screen.getByTestId('outside'), touch());
+ expect(fireTouchEnd(screen.getByTestId('outside')).defaultPrevented).toBe(
+ true,
+ );
+ expect(onDismiss).not.toHaveBeenCalled();
+ });
+
+ it('cancels only that touch: the next press ends the wait, and a later touchend passes', () => {
+ render(<Harness />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerUp(row('A'), touch());
+ expect(fireTouchEnd(row('A')).defaultPrevented).toBe(true);
+ expect(fireTouchEnd(row('A')).defaultPrevented).toBe(false);
+ fireEvent.pointerDown(row('B'), touch(2));
+ fireEvent.pointerUp(row('B'), touch(2));
+ fireEvent.pointerDown(screen.getByTestId('outside'), touch(3));
+ expect(fireTouchEnd(row('B')).defaultPrevented).toBe(false);
+ });
+});
+
describe('useMenuPress — release outside and cancellation', () => {
it('a mouse released outside acts on nothing and dismisses the menu', () => {
const onSelect = vi.fn();
diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts
index 5caaf73606..97086b473a 100644
--- a/packages/core/src/hooks/useMenuPress.ts
+++ b/packages/core/src/hooks/useMenuPress.ts
@@ -483,7 +483,10 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
// Detach before acting: the activation usually closes the menu.
endGesture();
// Once armed, the one swallower stays installed.
- armClickGuard(doc, {staysInstalled: true});
+ armClickGuard(doc, {
+ staysInstalled: true,
+ cancelsTouchEnd: native?.pointerType === 'touch',
+ });
if (native != null) {
activate(effect.row, native);
}
@@ -492,7 +495,10 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
case 'settle': {
endGesture();
if (effect.stray) {
- armClickGuard(doc, {staysInstalled: true});
+ armClickGuard(doc, {
+ staysInstalled: true,
+ cancelsTouchEnd: native?.pointerType === 'touch',
+ });
}
if (effect.dismiss) {
optionsRef.current.onDismiss?.();
diff --git a/packages/core/src/utils/clickGuard.test.ts b/packages/core/src/utils/clickGuard.test.ts
index 9590d37956..115a2dd6f3 100644
--- a/packages/core/src/utils/clickGuard.test.ts
+++ b/packages/core/src/utils/clickGuard.test.ts
@@ -70,6 +70,13 @@ function claimedTap(target: HTMLElement) {
}
}
+/** A `touchend` at `target`, as a browser fires it after the touch's `pointerup`. */
+function touchEnd(target: EventTarget, cancelable = true): Event {
+ const event = new Event('touchend', {bubbles: true, cancelable});
+ target.dispatchEvent(event);
+ return event;
+}
+
function button(): HTMLButtonElement {
const element = document.createElement('button');
document.body.append(element);
@@ -269,4 +276,53 @@ describe('clickGuard', () => {
restorePointer();
}
});
+
+ it("armed at a finger's release, cancels that touch's touchend and disarms: no click follows it", () => {
+ const target = button();
+ armClickGuard(document, {staysInstalled: true, cancelsTouchEnd: true});
+ expect(touchEnd(target).defaultPrevented).toBe(true);
+ expect(isClickGuardArmed(document)).toBe(false);
+ // The next touch's touchend, and a click with no press behind it, are the page's.
+ expect(touchEnd(target).defaultPrevented).toBe(false);
+ expect(click(target).defaultPrevented).toBe(false);
+ });
+
+ it('leaves an uncancelable touchend alone, and stays armed for a click that may follow it', () => {
+ const target = button();
+ armClickGuard(document, {cancelsTouchEnd: true});
+ expect(touchEnd(target, false).defaultPrevented).toBe(false);
+ expect(isClickGuardArmed(document)).toBe(true);
+ // Only that touch's touchend is its: a later one is the page's.
+ expect(touchEnd(target).defaultPrevented).toBe(false);
+ expect(click(target).defaultPrevented).toBe(true);
+ });
+
+ it('cancels no touchend on any other arm', () => {
+ const target = button();
+ armClickGuard(document, {staysInstalled: true});
+ expect(touchEnd(target).defaultPrevented).toBe(false);
+ armClickGuard(document, {takesLateMouse: true});
+ expect(touchEnd(target).defaultPrevented).toBe(false);
+ expect(isClickGuardArmed(document)).toBe(true);
+ });
+
+ it('hears touchend only while armed with it, and drops it at the next pointerdown and after its window', () => {
+ vi.useFakeTimers();
+ const target = button();
+ const add = vi.spyOn(window, 'addEventListener');
+ const remove = vi.spyOn(window, 'removeEventListener');
+ const touchEnds = (spy: typeof add) =>
+ spy.mock.calls.map(call => call[0]).filter(type => type === 'touchend');
+ armClickGuard(document);
+ expect(touchEnds(add)).toEqual([]);
+ armClickGuard(document, {cancelsTouchEnd: true});
+ expect(touchEnds(add)).toEqual(['touchend']);
+ target.dispatchEvent(new Event('pointerdown', {bubbles: true}));
+ expect(touchEnds(remove)).toEqual(['touchend']);
+ expect(touchEnd(target).defaultPrevented).toBe(false);
+ armClickGuard(document, {cancelsTouchEnd: true});
+ vi.advanceTimersByTime(CLICK_GUARD_WINDOW_MS);
+ expect(isClickGuardArmed(document)).toBe(false);
+ expect(touchEnds(remove)).toEqual(['touchend', 'touchend']);
+ });
});
diff --git a/packages/core/src/utils/clickGuard.ts b/packages/core/src/utils/clickGuard.ts
index 31418199f6..ec540af1ec 100644
--- a/packages/core/src/utils/clickGuard.ts
+++ b/packages/core/src/utils/clickGuard.ts
@@ -26,6 +26,11 @@
// `touchend`, aimed at whatever is under the finger by then. They go with
// the click, the next `pointerdown` or the window, as the guard does.
//
+// The menu press model's arm at a finger's release also cancels that touch's
+// `touchend`, so the browser creates no click and no compatibility mouse
+// events. A busy main thread can otherwise hold that click past the window,
+// when a drill-in has put another row under the finger.
+//
// Some clicks always pass:
// - a click with `detail` 0: a keyboard's, a screen reader's, or one that the
// page dispatches;
@@ -56,6 +61,13 @@ export interface ClickGuardOptions {
* @default false
*/
readonly takesLateMouse?: boolean;
+ /**
+ * The menu press model's arm at a finger's release: the guard also cancels
+ * that touch's `touchend`, so the browser creates no click for it. A
+ * cancelled `touchend` disarms the guard.
+ * @default false
+ */
+ readonly cancelsTouchEnd?: boolean;
}
interface Guard {
@@ -89,7 +101,11 @@ function listenForClicks(view: Window): () => void {
/** Swallow the browser's next click on `doc` (see the file header). */
export function armClickGuard(
doc: Document,
- {staysInstalled = false, takesLateMouse = false}: ClickGuardOptions = {},
+ {
+ staysInstalled = false,
+ takesLateMouse = false,
+ cancelsTouchEnd = false,
+ }: ClickGuardOptions = {},
): void {
const view = doc.defaultView;
if (view == null) {
@@ -116,6 +132,26 @@ export function armClickGuard(
);
}
}
+ if (cancelsTouchEnd) {
+ // A touch sends its pointerup before its touchend, so the next touchend is
+ // that touch's own. The next pointerdown disarms the guard first.
+ const stopTouchEnd = subscribeInput(
+ view,
+ 'touchend',
+ event => {
+ stopTouchEnd();
+ // A touchend that the browser took for a scroll is not cancelable.
+ // The guard stays armed for a click that may follow it.
+ if (event.cancelable) {
+ event.preventDefault();
+ // No click follows a cancelled touchend.
+ disarmClickGuard(doc);
+ }
+ },
+ {cancels: true},
+ );
+ guard.unsubscribers.push(stopTouchEnd);
+ }
guard.timer = setTimeout(() => disarmClickGuard(doc), CLICK_GUARD_WINDOW_MS);
}