Skip to content

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

TypeScript

fix(core): the click guard takes a claimed touch's late mousedown and mouseup (#9677)

Christopher Chedeau4a8a76eeb4be
diff --git a/.changeset/click-guard-late-mouse.md b/.changeset/click-guard-late-mouse.md
new file mode 100644
index 0000000000..d20aebc261
--- /dev/null
+++ b/.changeset/click-guard-late-mouse.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] After a gesture takes a touch, the page no longer sees that touch's late `mousedown` and `mouseup`. WebKit sends them a few milliseconds after a held tap's cancelled `touchend`, aimed at whatever is under the finger by then; they now go with the click.
+
+@vjeux
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index 0732ea85d8..1a1cb7e695 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -370,11 +370,13 @@ a measured, sourced difference exists.
scroll to the lift (DEC-7).
- **FR21 — Clicks follow the gesture.** When a gesture takes a touch, its
`touchend` MUST be cancelled, and no click or compatibility mouse event
- reaches the page. A click held for a recognizer that may still recognize (a
- tap that a double tap may claim) MUST be replayed on its target if that
- recognizer fails. Activation with `detail === 0` (keyboard, assistive
- technology) MUST always pass. A tap MUST NOT wait for the browser's
- double-tap delay.
+ reaches the page. The click guard that the gesture host arms at that lift
+ takes them: the click, and the late `mousedown` and `mouseup` that WebKit
+ sends after a held tap's cancelled `touchend`. A click held for a
+ recognizer that may still recognize (a tap that a double tap may claim)
+ MUST be replayed on its target if that recognizer fails. Activation with
+ `detail === 0` (keyboard, assistive technology) MUST always pass. A tap
+ MUST NOT wait for the browser's double-tap delay.
- **FR22 — The platform keeps its edge gestures.** iOS Safari's back swipe
from the screen edge and Android's system back gesture MUST stay the
browser's and the system's; a touch presentation never overrides them.
diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.ts
index e9d15b3fa4..0d76e45f55 100644
--- a/packages/core/src/gestures/GestureHost.ts
+++ b/packages/core/src/gestures/GestureHost.ts
@@ -1203,12 +1203,17 @@ export class GestureHost {
* cancels it (or the click guard drops it, a late one included) and this one
* is the tap's single activation.
*/
- private clickRetargeted(target: EventTarget, x: number, y: number): void {
+ private clickRetargeted(
+ target: EventTarget,
+ x: number,
+ y: number,
+ pointerType: string,
+ ): void {
const view = this.doc.defaultView;
if (!(target instanceof Element) || !target.isConnected || view == null) {
return;
}
- armClickGuard(this.doc);
+ armClickGuard(this.doc, {takesLateMouse: pointerType === 'touch'});
if (
target instanceof view.HTMLElement &&
target.matches('input, textarea, select, [contenteditable]')
@@ -3146,7 +3151,14 @@ export class GestureHost {
// A tap sent to what is drawn: the engine's click would hit the layout
// position, so it is cancelled and the tap clicks what it touched.
for (const end of retargetedEnds) {
- if (this.clickRetargetedTap(end.landed, end, dispositions.get(end.id))) {
+ if (
+ this.clickRetargetedTap(
+ end.landed,
+ end,
+ dispositions.get(end.id),
+ 'touch',
+ )
+ ) {
cancelsClick = true;
}
}
@@ -3154,7 +3166,7 @@ export class GestureHost {
if (event.cancelable) {
event.preventDefault();
}
- armClickGuard(this.doc);
+ armClickGuard(this.doc, {takesLateMouse: true});
}
};
@@ -3168,6 +3180,7 @@ export class GestureHost {
landed: {x: number; y: number; target: EventTarget} | undefined,
end: {x: number; y: number},
disposition: ClickDisposition | undefined,
+ pointerType: string,
): boolean {
if (landed == null || disposition !== 'allow') {
return false;
@@ -3176,7 +3189,7 @@ export class GestureHost {
if (moved > UIKIT_TAP.allowableMovement.value) {
return false;
}
- this.clickRetargeted(landed.target, end.x, end.y);
+ this.clickRetargeted(landed.target, end.x, end.y, pointerType);
return true;
}
@@ -3610,9 +3623,10 @@ export class GestureHost {
landed,
{x: event.clientX, y: event.clientY},
dispositions.get(id),
+ event.pointerType,
);
if (!clicked && needsSuppression(dispositions)) {
- armClickGuard(this.doc);
+ armClickGuard(this.doc, {takesLateMouse: event.pointerType === 'touch'});
}
// A finger read from its pointer events: the touchend that follows the
// lift is cancelled when a gesture took it, which the lift itself may
diff --git a/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts b/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts
index d2d2024dcd..5918594b1a 100644
--- a/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts
+++ b/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts
@@ -8,7 +8,8 @@
* @output Browser proof of the negotiation the unit tests cannot see:
* touch-action per element, touchmove cancelled exactly while a recognizer
* owns the finger, native scrolling untouched otherwise, click suppression
- * with no ghost click, a drag that began as a scroll staying the browser's, pinch-zoom
+ * with no ghost click or late mouse event, a drag that began as a scroll
+ * staying the browser's, pinch-zoom
* left to the browser, a second finger that never breaks the first,
* timing taken from event timestamps under a blocked main thread, gestures
* for every pointer with nothing listening while idle where the primary
@@ -1051,6 +1052,70 @@ test('a tap recognizer replaces the click: no ghost click, no compatibility mous
);
});
+test("a tap a recognizer claims keeps its late mouse events from the page until their click: WebKit sends them after a held tap's cancelled touchend (spec:AST-094 FR21)", async ({
+ page,
+ browserName,
+}) => {
+ const driver = await open(page, browserName);
+ await page.evaluate(() => {
+ const late = window as unknown as {
+ __late: string[];
+ __lateSent: boolean;
+ __sendLate: () => void;
+ };
+ late.__late = [];
+ late.__lateSent = false;
+ for (const type of ['mousedown', 'mouseup', 'click']) {
+ document.body.addEventListener(type, event =>
+ late.__late.push(`${type}:${(event as MouseEvent).detail}`),
+ );
+ }
+ const tapper = document.getElementById('tapper') as HTMLElement;
+ late.__sendLate = () => {
+ for (const type of ['mousedown', 'mouseup', 'click']) {
+ tapper.dispatchEvent(
+ new MouseEvent(type, {bubbles: true, cancelable: true, detail: 1}),
+ );
+ }
+ };
+ // Neither engine here sends a held tap's late compatibility events, so
+ // the page sends them just after the tap's touchend, as iOS WebKit does.
+ window.addEventListener(
+ 'touchend',
+ () =>
+ setTimeout(() => {
+ late.__sendLate();
+ late.__lateSent = true;
+ }, 0),
+ {once: true},
+ );
+ });
+ await driver.tap(await center(page, 'tapper'));
+ expect(states(await log(page), 'tap')).toEqual(['ended', 'possible']);
+ await expect
+ .poll(async () =>
+ page.evaluate(
+ () => (window as unknown as {__lateSent: boolean}).__lateSent,
+ ),
+ )
+ .toBe(true);
+ expect(
+ await page.evaluate(() => (window as unknown as {__late: string[]}).__late),
+ ).toEqual([]);
+ // That click spent the guard: the next ones reach the page.
+ expect(
+ await page.evaluate(() => {
+ const late = window as unknown as {
+ __late: string[];
+ __sendLate: () => void;
+ };
+ late.__late.length = 0;
+ late.__sendLate();
+ return [...late.__late];
+ }),
+ ).toEqual(['mousedown:1', 'mouseup:1', 'click:1']);
+});
+
test('a keyboard activation inside the click window after a claimed drag still clicks: the swallower passes a click whose detail is 0 (FR21)', async ({
page,
browserName,
diff --git a/packages/core/src/gestures/__tests__/presentedHitTesting.test.ts b/packages/core/src/gestures/__tests__/presentedHitTesting.test.ts
index 8669603aa3..981d2c53ce 100644
--- a/packages/core/src/gestures/__tests__/presentedHitTesting.test.ts
+++ b/packages/core/src/gestures/__tests__/presentedHitTesting.test.ts
@@ -8,7 +8,8 @@
* draws the sheet elsewhere (motion/presentation.ts)
* @output A finger on the drawn sheet reaches the sheet, not the scrim under
* its start, and its tap clicks the drawn button once (the engine's click
- * cancelled, a late one swallowed); a finger where the sheet was but is no
+ * cancelled, a late one swallowed, with a finger's late mousedown and
+ * mouseup); a finger where the sheet was but is no
* longer drawn reaches what is drawn there; press bounds follow the drawn
* box, a control slotted into a moving shadow-tree panel's included; a
* claiming recognizer across a shadow boundary from the moving element
@@ -63,6 +64,29 @@ function touch(
return event;
}
+/** A finger's pointer event, for a host that reads fingers from them. */
+function fingerPointer(
+ type: 'pointerdown' | 'pointerup',
+ target: EventTarget,
+ at: {x: number; y: number},
+ time: number,
+): Event {
+ const event = new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId: 1,
+ pointerType: 'touch',
+ isPrimary: true,
+ clientX: at.x,
+ clientY: at.y,
+ buttons: type === 'pointerdown' ? 1 : 0,
+ });
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ target.dispatchEvent(event);
+ return event;
+}
+
let clock: ManualClock;
let cleanups: (() => void)[];
let scrim: HTMLElement;
@@ -287,6 +311,43 @@ describe('presented hit testing (iOS WebKit hit-tests compositor motion at layou
expect(clicks).toEqual(['done']);
});
+ it("takes a retargeted finger tap's late mousedown and mouseup with the engine's click where the host reads fingers from pointer events (spec:AST-094 FR21)", () => {
+ mount({left: 0, top: 844, right: 390, bottom: 1244}, -544);
+ const gestures = new GestureHost(document, {
+ clock,
+ presentedHitTesting: 'always',
+ inputMode: 'pointer-events',
+ });
+ cleanups.push(
+ gestures.attach(
+ scrim,
+ new TapGestureRecognizer({name: 'scrim', claimsTouches: false}),
+ ),
+ gestures.attach(
+ sheet,
+ new PanGestureRecognizer({
+ name: 'sheet',
+ direction: 'down',
+ claimsTouches: false,
+ }),
+ ),
+ );
+ const onDone = {x: 340, y: 330};
+ fingerPointer('pointerdown', scrim, onDone, 0);
+ fingerPointer('pointerup', scrim, onDone, 80);
+ expect(clicks).toEqual(['done']);
+ for (const type of ['mousedown', 'mouseup', 'click']) {
+ const late = new MouseEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ detail: 1,
+ });
+ scrim.dispatchEvent(late);
+ expect(late.defaultPrevented, type).toBe(true);
+ }
+ expect(clicks).toEqual(['done']);
+ });
+
it('descends into an open shadow root on the drawn sheet: the tap reaches and clicks the control inside it', () => {
// A sheet whose content lives in an open shadow root: the document's hit
// test answers its host, the root's answers the control.
diff --git a/packages/core/src/utils/clickGuard.test.ts b/packages/core/src/utils/clickGuard.test.ts
index 6b4ae7cd3a..9590d37956 100644
--- a/packages/core/src/utils/clickGuard.test.ts
+++ b/packages/core/src/utils/clickGuard.test.ts
@@ -9,7 +9,8 @@
* pointerdown and the window disarm it; it hears pointerdown only while
* armed; the menu press model's click listener stays, one per document,
* ahead of later ones, while the gesture host's lasts only while armed;
- * the menu press model and the gesture host arm this one guard
+ * the menu press model and the gesture host arm this one guard; an arm at
+ * a claimed touch's lift also takes that touch's late mousedown and mouseup
* @position Unit tests of packages/core/src/utils/clickGuard.ts
*/
@@ -46,6 +47,29 @@ function click(target: EventTarget, detail = 1): MouseEvent {
return event;
}
+function mouse(
+ type: 'mousedown' | 'mouseup',
+ target: EventTarget,
+ detail = 1,
+): MouseEvent {
+ const event = new MouseEvent(type, {bubbles: true, cancelable: true, detail});
+ target.dispatchEvent(event);
+ return event;
+}
+
+/** A tap that a recognizer on `target` claims, by touch events. */
+function claimedTap(target: HTMLElement) {
+ const contact = {identifier: 1, clientX: 5, clientY: 5, target};
+ for (const type of ['touchstart', 'touchend'] as const) {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ Object.defineProperty(event, 'changedTouches', {value: [contact]});
+ Object.defineProperty(event, 'touches', {
+ value: type === 'touchend' ? [] : [contact],
+ });
+ target.dispatchEvent(event);
+ }
+}
+
function button(): HTMLButtonElement {
const element = document.createElement('button');
document.body.append(element);
@@ -105,6 +129,67 @@ describe('clickGuard', () => {
expect(clicks(add)).toBe(3);
});
+ it("armed at a claimed touch's lift, also takes that touch's late mousedown and mouseup, until its click (spec:AST-094 FR21)", () => {
+ const target = button();
+ const heard = vi.fn();
+ const types = ['mousedown', 'mouseup', 'click'] as const;
+ for (const type of types) {
+ document.addEventListener(type, heard, {capture: true});
+ }
+ try {
+ armClickGuard(document, {takesLateMouse: true});
+ expect(mouse('mousedown', target).defaultPrevented).toBe(true);
+ expect(mouse('mouseup', target).defaultPrevented).toBe(true);
+ expect(click(target).defaultPrevented).toBe(true);
+ expect(heard).not.toHaveBeenCalled();
+ // Spent at the click: the next press is the page's.
+ expect(mouse('mousedown', target).defaultPrevented).toBe(false);
+ expect(heard).toHaveBeenCalledTimes(1);
+ } finally {
+ for (const type of types) {
+ document.removeEventListener(type, heard, {capture: true});
+ }
+ }
+ });
+
+ it("leaves mousedown and mouseup to the page on any other arm, and always lets a keyboard's or the caller's through", () => {
+ const target = button();
+ armClickGuard(document);
+ expect(mouse('mousedown', target).defaultPrevented).toBe(false);
+ expect(mouse('mouseup', target).defaultPrevented).toBe(false);
+ armClickGuard(document, {takesLateMouse: true});
+ expect(mouse('mousedown', target, 0).defaultPrevented).toBe(false);
+ expect(
+ withoutClickGuard(() => mouse('mouseup', target)).defaultPrevented,
+ ).toBe(false);
+ expect(isClickGuardArmed(document)).toBe(true);
+ });
+
+ it('hears mousedown and mouseup only while armed at a claimed touch, and drops them when it disarms (spec:AST-094 FR24)', () => {
+ vi.useFakeTimers();
+ const target = button();
+ const add = vi.spyOn(window, 'addEventListener');
+ const remove = vi.spyOn(window, 'removeEventListener');
+ const late = (spy: typeof add) =>
+ spy.mock.calls
+ .map(call => call[0])
+ .filter(type => type === 'mousedown' || type === 'mouseup');
+ armClickGuard(document);
+ expect(late(add)).toEqual([]);
+ armClickGuard(document, {takesLateMouse: true});
+ expect(late(add)).toEqual(['mousedown', 'mouseup']);
+ target.dispatchEvent(new Event('pointerdown', {bubbles: true}));
+ expect(late(remove)).toEqual(['mousedown', 'mouseup']);
+ armClickGuard(document, {takesLateMouse: true});
+ vi.advanceTimersByTime(CLICK_GUARD_WINDOW_MS);
+ expect(late(remove)).toEqual([
+ 'mousedown',
+ 'mouseup',
+ 'mousedown',
+ 'mouseup',
+ ]);
+ });
+
it("lets through a keyboard's or a screen reader's click, a click the caller dispatches, and the haptic switch's", () => {
const target = button();
armClickGuard(document);
@@ -157,15 +242,7 @@ describe('clickGuard', () => {
const target = button();
const tap = new TapGestureRecognizer({name: 'tap'});
const detach = host.attach(target, tap);
- const contact = {identifier: 1, clientX: 5, clientY: 5, target};
- for (const type of ['touchstart', 'touchend'] as const) {
- const event = new Event(type, {bubbles: true, cancelable: true});
- Object.defineProperty(event, 'changedTouches', {value: [contact]});
- Object.defineProperty(event, 'touches', {
- value: type === 'touchend' ? [] : [contact],
- });
- target.dispatchEvent(event);
- }
+ claimedTap(target);
expect(isClickGuardArmed(document)).toBe(true);
expect(click(target).defaultPrevented).toBe(true);
detach();
@@ -173,4 +250,23 @@ describe('clickGuard', () => {
restorePointer();
}
});
+
+ it("takes a claimed tap's late mousedown and mouseup with its click: WebKit sends them after the cancelled touchend of a held tap (spec:AST-094 FR21)", () => {
+ const restorePointer = coarsePrimaryPointer();
+ try {
+ const host = new GestureHost(document);
+ const target = button();
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ const detach = host.attach(target, tap);
+ claimedTap(target);
+ expect(mouse('mousedown', target).defaultPrevented).toBe(true);
+ expect(mouse('mouseup', target).defaultPrevented).toBe(true);
+ expect(click(target).defaultPrevented).toBe(true);
+ // The next press is the page's.
+ expect(mouse('mousedown', target).defaultPrevented).toBe(false);
+ detach();
+ } finally {
+ restorePointer();
+ }
+ });
});
diff --git a/packages/core/src/utils/clickGuard.ts b/packages/core/src/utils/clickGuard.ts
index 2a81b7b85a..31418199f6 100644
--- a/packages/core/src/utils/clickGuard.ts
+++ b/packages/core/src/utils/clickGuard.ts
@@ -21,6 +21,11 @@
// page adds later (AST-057, AST-094). If only the gesture host arms it, the
// click listener stays only while the guard is armed.
//
+// An arm at a claimed touch's lift also takes that touch's late `mousedown`
+// and `mouseup`. WebKit sends them a few ms after a held tap's cancelled
+// `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.
+//
// Some clicks always pass:
// - a click with `detail` 0: a keyboard's, a screen reader's, or one that the
// page dispatches;
@@ -45,6 +50,12 @@ export interface ClickGuardOptions {
* @default false
*/
readonly staysInstalled?: boolean;
+ /**
+ * The gesture host's arm at a claimed touch's lift: the guard also takes
+ * that touch's late `mousedown` and `mouseup` while it is armed.
+ * @default false
+ */
+ readonly takesLateMouse?: boolean;
}
interface Guard {
@@ -78,7 +89,7 @@ function listenForClicks(view: Window): () => void {
/** Swallow the browser's next click on `doc` (see the file header). */
export function armClickGuard(
doc: Document,
- {staysInstalled = false}: ClickGuardOptions = {},
+ {staysInstalled = false, takesLateMouse = false}: ClickGuardOptions = {},
): void {
const view = doc.defaultView;
if (view == null) {
@@ -98,6 +109,13 @@ export function armClickGuard(
// The next press is a new gesture: its click must never be eaten.
subscribeInput(view, 'pointerdown', () => disarmClickGuard(doc)),
);
+ if (takesLateMouse) {
+ for (const type of ['mousedown', 'mouseup'] as const) {
+ guard.unsubscribers.push(
+ subscribeInput(view, type, swallowLateMouse, {cancels: true}),
+ );
+ }
+ }
guard.timer = setTimeout(() => disarmClickGuard(doc), CLICK_GUARD_WINDOW_MS);
}
@@ -149,6 +167,15 @@ export function __resetClickGuardForTest(): void {
}
}
+/** Swallows a claimed touch's late `mousedown` or `mouseup`. */
+function swallowLateMouse(event: MouseEvent): void {
+ if (isExempt(event)) {
+ return;
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+}
+
function isExempt(event: MouseEvent): boolean {
if (event.detail === 0 || unguardedDepth > 0) {
return true;