Skip to content

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

TypeScript

fix(core): a mouse or Space press on a touch-first device paints the pressed state (#8046)

Christopher Chedeau0913354f06b9
diff --git a/.changeset/press-coarse-device-mouse-keyboard.md b/.changeset/press-coarse-device-mouse-keyboard.md
new file mode 100644
index 0000000000..0c640fa632
--- /dev/null
+++ b/.changeset/press-coarse-device-mouse-keyboard.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] On a phone or tablet, a press made with a mouse, a trackpad or the Space key now shows the pressed state. Touch devices drop the CSS `:active` press so a finger only sees the touch press model, but that rule keys on the device's primary pointer, so a tablet with a trackpad and keyboard (or a phone with a mouse) lost the pressed state for every press that was not a finger. The touch press controller now paints those presses on such devices with the same pixels a desktop press has: at once, held while the button or key is down, faded at the release. As on a desktop, Space paints only a focused button that is itself the pressed surface (a checkbox's or radio's row stays at rest), and a menu row keeps the menu's own highlight. Desktop presses and finger presses are unchanged.
+
+@vjeux
diff --git a/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts b/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..17cf2a6076
--- /dev/null
+++ b/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts
@@ -0,0 +1,392 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope core/Button ^packages/core/src/(utils/(pressFeedback|pressGesture|interactionOverlay|touchPresentation)|hooks/usePressFeedback)
+
+/**
+ * @file PressModality.a11y.chromium.spec.ts
+ * @input The `Core/Button` Secondary story in a built Storybook, real mouse,
+ * keyboard and touch input in a phone context (primary pointer coarse) and
+ * a desktop context (primary pointer fine)
+ * @output Real-engine proof that on a touch-first device a held mouse press
+ * and a held Space press paint the pressed state with the same pixels and
+ * scale a desktop `:active` press paints, and fade at the release; that a
+ * desktop press is still `:active` alone; and that a finger's press still
+ * waits for the touch press model's onset
+ * @position Run with `pnpm test:a11y-contract`. Browser layer of the touch
+ * press model (utils/pressFeedback.ts); the jsdom layer is
+ * utils/pressFeedback.test.ts.
+ *
+ * The stylesheet drops every `:active` arm under `@media (pointer: coarse)`,
+ * which reads the PRIMARY pointer, so on such a device the press controller
+ * is the only thing that can paint a mouse or keyboard press.
+ */
+
+import {expect, test, type Browser, type Page} from '@playwright/test';
+// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.
+import {PNG} from 'pngjs';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+const STORY = 'core-button--secondary';
+const SURFACE = '#storybook-root [data-astryx-pressable]';
+/** A phone: touch screen, mobile viewport rules, primary pointer coarse. */
+const PHONE = {
+ viewport: {width: 402, height: 714},
+ deviceScaleFactor: 1,
+ isMobile: true,
+ hasTouch: true,
+} as const;
+/** A desktop: primary pointer fine, hover, no touch. */
+const DESKTOP = {
+ viewport: {width: 1024, height: 768},
+ deviceScaleFactor: 1,
+ isMobile: false,
+ hasTouch: false,
+} as const;
+
+type RGB = [number, number, number];
+
+interface Opened {
+ page: Page;
+ close: () => Promise<void>;
+ center: {x: number; y: number};
+ /** A point on the button's fill, clear of its label. */
+ fill: {x: number; y: number};
+}
+
+async function open(
+ browser: Browser,
+ device: typeof PHONE | typeof DESKTOP,
+): Promise<Opened> {
+ const context = await browser.newContext(device);
+ const page = await context.newPage();
+ await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);
+ // Each case runs on the device it claims: a coarse primary pointer for the
+ // phone, a fine one for the desktop.
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(device.hasTouch);
+ const box = await page.locator(SURFACE).first().boundingBox();
+ if (box == null) {
+ throw new Error('the Button story rendered no pressable surface');
+ }
+ await page.mouse.move(1, 1);
+ return {
+ page,
+ close: async () => context.close(),
+ center: {x: box.x + box.width / 2, y: box.y + box.height / 2},
+ fill: {x: box.x + 6, y: box.y + box.height / 2},
+ };
+}
+
+/** The mean colour of a 2 × 2 CSS px patch, as presented. */
+async function pixel(page: Page, at: {x: number; y: number}): Promise<RGB> {
+ const png = PNG.sync.read(
+ await page.screenshot({
+ clip: {
+ x: Math.round(at.x) - 1,
+ y: Math.round(at.y) - 1,
+ width: 2,
+ height: 2,
+ },
+ animations: 'allow',
+ caret: 'hide',
+ }),
+ );
+ const sum = [0, 0, 0];
+ const count = png.width * png.height;
+ for (let i = 0; i < count; i++) {
+ sum[0] += png.data[i * 4];
+ sum[1] += png.data[i * 4 + 1];
+ sum[2] += png.data[i * 4 + 2];
+ }
+ return sum.map(v => Math.round(v / count)) as RGB;
+}
+
+/** Resolves once nothing on the surface animates and its transform is still. */
+async function settled(page: Page): Promise<void> {
+ await page
+ .locator(SURFACE)
+ .first()
+ .evaluate(
+ async element =>
+ new Promise<void>(resolve => {
+ let last = '';
+ let still = 0;
+ const tick = () => {
+ const transform = getComputedStyle(element).transform;
+ const running = element
+ .getAnimations()
+ .some(animation => animation.playState === 'running');
+ still = !running && transform === last ? still + 1 : 0;
+ last = transform;
+ if (still >= 2) {
+ resolve();
+ } else {
+ requestAnimationFrame(tick);
+ }
+ };
+ requestAnimationFrame(tick);
+ }),
+ );
+}
+
+async function pressAttribute(page: Page): Promise<string | null> {
+ return page.locator(SURFACE).first().getAttribute('data-astryx-press');
+}
+
+async function scale(page: Page): Promise<number> {
+ return page
+ .locator(SURFACE)
+ .first()
+ .evaluate(element => {
+ const transform = getComputedStyle(element).transform;
+ return transform === 'none' ? 1 : new DOMMatrixReadOnly(transform).a;
+ });
+}
+
+async function coarse(page: Page): Promise<boolean> {
+ return page.evaluate(() => matchMedia('(pointer: coarse)').matches);
+}
+
+function expectSameColour(actual: RGB, expected: RGB): void {
+ for (let channel = 0; channel < 3; channel++) {
+ expect(
+ Math.abs(actual[channel] - expected[channel]),
+ `${JSON.stringify(actual)} vs ${JSON.stringify(expected)}`,
+ ).toBeLessThanOrEqual(2);
+ }
+}
+
+type Press = 'mouse' | 'space';
+
+async function holdPress(opened: Opened, press: Press): Promise<void> {
+ if (press === 'mouse') {
+ await opened.page.mouse.move(opened.center.x, opened.center.y);
+ await opened.page.mouse.down();
+ } else {
+ await opened.page.locator(SURFACE).first().focus();
+ await opened.page.keyboard.down('Space');
+ }
+}
+
+async function releasePress(opened: Opened, press: Press): Promise<void> {
+ if (press === 'mouse') {
+ await opened.page.mouse.up();
+ } else {
+ await opened.page.keyboard.up('Space');
+ }
+}
+
+/** What a desktop paints for the press: the reference, and proof the controller stays out. */
+async function desktopReference(
+ browser: Browser,
+ press: Press,
+): Promise<{rest: RGB; pressed: RGB; scale: number; attribute: string | null}> {
+ const desktop = await open(browser, DESKTOP);
+ try {
+ expect(await coarse(desktop.page)).toBe(false);
+ const rest = await pixel(desktop.page, desktop.fill);
+ await holdPress(desktop, press);
+ await settled(desktop.page);
+ return {
+ rest,
+ pressed: await pixel(desktop.page, desktop.fill),
+ scale: await scale(desktop.page),
+ attribute: await pressAttribute(desktop.page),
+ };
+ } finally {
+ await desktop.close();
+ }
+}
+
+for (const press of ['mouse', 'space'] as const) {
+ test(`on a touch-first device a held ${press} press paints what a desktop press paints, then fades`, async ({
+ browser,
+ }) => {
+ const reference = await desktopReference(browser, press);
+ expect(reference.pressed).not.toEqual(reference.rest);
+
+ const phone = await open(browser, PHONE);
+ try {
+ expect(await coarse(phone.page)).toBe(true);
+ await phone.page.evaluate(() => {
+ const target = window as unknown as {__clicks: number};
+ target.__clicks = 0;
+ document.addEventListener('click', () => {
+ target.__clicks += 1;
+ });
+ });
+ const rest = await pixel(phone.page, phone.fill);
+ expectSameColour(rest, reference.rest);
+
+ await holdPress(phone, press);
+ await phone.page.waitForTimeout(250);
+ expect(await pressAttribute(phone.page)).toBe('on');
+ await settled(phone.page);
+ expectSameColour(await pixel(phone.page, phone.fill), reference.pressed);
+ expect(await scale(phone.page)).toBeCloseTo(reference.scale, 3);
+
+ await releasePress(phone, press);
+ expect(await pressAttribute(phone.page)).toBe('fading');
+ expect(
+ await phone.page.evaluate(
+ () => (window as unknown as {__clicks: number}).__clicks,
+ ),
+ ).toBe(1);
+ await expect.poll(async () => pressAttribute(phone.page)).toBeNull();
+ await settled(phone.page);
+ expectSameColour(await pixel(phone.page, phone.fill), rest);
+ } finally {
+ await phone.close();
+ }
+ });
+}
+
+test('a desktop press is unchanged: `:active` paints it and the controller writes nothing', async ({
+ browser,
+}) => {
+ const mouse = await desktopReference(browser, 'mouse');
+ expect(mouse.attribute).toBeNull();
+ expect(mouse.pressed).not.toEqual(mouse.rest);
+ expect(mouse.scale).toBeCloseTo(0.98, 3);
+ const space = await desktopReference(browser, 'space');
+ expect(space.attribute).toBeNull();
+ expectSameColour(space.pressed, mouse.pressed);
+});
+
+test("a finger's press is unchanged: it waits for the onset, then fades at the lift", async ({
+ browser,
+ browserName,
+}) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'touch input goes through CDP, which only Chromium has',
+ );
+ const phone = await open(browser, PHONE);
+ try {
+ const cdp = await phone.page.context().newCDPSession(phone.page);
+ const touch = async (type: 'touchStart' | 'touchEnd') =>
+ cdp.send('Input.dispatchTouchEvent', {
+ type,
+ touchPoints:
+ type === 'touchStart'
+ ? [{x: phone.center.x, y: phone.center.y, id: 1}]
+ : [],
+ });
+ await touch('touchStart');
+ await phone.page.waitForTimeout(60);
+ const early = await pressAttribute(phone.page);
+ await phone.page.waitForTimeout(190);
+ const believed = await pressAttribute(phone.page);
+ await touch('touchEnd');
+ const lifted = await pressAttribute(phone.page);
+ expect(early).toBeNull();
+ expect(believed).toBe('on');
+ expect(lifted).toBe('fading');
+ } finally {
+ await phone.close();
+ }
+});
+
+test('a mouse press dragged across menu rows lights only the row under the pointer', async ({
+ browser,
+}) => {
+ // useMenuPress FR6 and DEC-6: a menu's highlight is its only paint, so a
+ // row pressed and then left must not stay painted beside the highlight.
+ const context = await browser.newContext(PHONE);
+ const page = await context.newPage();
+ try {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-dropdownmenu--mounted-open&viewMode=story`,
+ );
+ // A mouse on a touch-first device: the primary pointer is coarse.
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(true);
+ const rows = page.getByRole('menuitem');
+ await rows.first().waitFor();
+ const menu = await page.locator('[data-astryx-menu-press]').boundingBox();
+ const first = await rows.nth(0).boundingBox();
+ const second = await rows.nth(1).boundingBox();
+ if (menu == null || first == null || second == null) {
+ throw new Error('the menu story rendered no rows');
+ }
+ // Sampled in a row's leading padding, clear of its label and its check
+ // mark; the menu's own surface above the first row is what an unlit row
+ // shows there.
+ const on = (box: {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ }) => ({x: box.x + 4, y: box.y + box.height / 2});
+ const unlit = await pixel(page, {x: first.x + 4, y: menu.y + 2});
+ await page.mouse.move(on(first).x, on(first).y);
+ await page.mouse.down();
+ await page.mouse.move(on(second).x, on(second).y, {steps: 6});
+ await page.waitForTimeout(250);
+ const painted = await page
+ .locator('[data-astryx-menu-press] [data-astryx-press]')
+ .count();
+ const left = await pixel(page, on(first));
+ await page.mouse.up();
+ expect(painted).toBe(0);
+ expectSameColour(left, unlit);
+ } finally {
+ await context.close();
+ }
+});
+
+test('Space on a focused checkbox leaves its row at rest, as on a desktop', async ({
+ browser,
+}) => {
+ for (const device of [DESKTOP, PHONE]) {
+ const context = await browser.newContext(device);
+ const page = await context.newPage();
+ try {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-press-feedback-touch--controls&viewMode=story`,
+ );
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(device.hasTouch);
+ const checkbox = page.getByRole('checkbox', {name: 'Accept terms'});
+ await checkbox.waitFor({state: 'attached'});
+ const box = await checkbox.evaluate(element => {
+ const visual = (
+ element.parentElement ?? element
+ ).getBoundingClientRect();
+ return {
+ x: visual.x + visual.width / 2,
+ y: visual.y + visual.height / 2,
+ };
+ });
+ await checkbox.focus();
+ const rest = await pixel(page, box);
+ await page.keyboard.down(' ');
+ await page.waitForTimeout(150);
+ const held = await pixel(page, box);
+ const painted = await page.locator('[data-astryx-press]').count();
+ await page.keyboard.up(' ');
+ expect(painted, device.isMobile ? 'phone' : 'desktop').toBe(0);
+ expectSameColour(held, rest);
+ } finally {
+ await context.close();
+ }
+ }
+});
diff --git a/packages/core/src/hooks/usePressFeedback.doc.mjs b/packages/core/src/hooks/usePressFeedback.doc.mjs
index 713eea27a0..d33540b8ee 100644
--- a/packages/core/src/hooks/usePressFeedback.doc.mjs
+++ b/packages/core/src/hooks/usePressFeedback.doc.mjs
@@ -20,12 +20,12 @@ export const docs = {
name: 'pressableProps',
type: "{'data-astryx-pressable': ''}",
description:
- "The marker attribute to spread on the element that paints the press. Compose one of `interactionOverlayStyles` (from `@astryxdesign/core/utils`) on the same element — `backgroundColor` or `backgroundImage` for a surface whose hover and press are the system's overlays, `pressedBackgroundColor` for one whose hover is its own — and it paints the pressed token at the press's strength on the first frame of a believed press and fades it over the release, keeping `:active` for a mouse. A press is themed through `--color-overlay-pressed`.",
+ "The marker attribute to spread on the element that paints the press. Compose one of `interactionOverlayStyles` (from `@astryxdesign/core/utils`) on the same element — `backgroundColor` or `backgroundImage` for a surface whose hover and press are the system's overlays, `pressedBackgroundColor` for one whose hover is its own — and it paints the pressed token at the press's strength on the first frame of a believed press and fades it over the release, keeping `:active` for a mouse on a desktop. On a phone or tablet, where the stylesheet drops `:active`, the controller also paints a mouse, trackpad or Space-key press: at once, held while the button or key is down, faded at the release. A press is themed through `--color-overlay-pressed`.",
},
],
usage: {
description:
- 'The touch press model every Astryx pressable uses, for a local component that paints its own press. Under a finger, CSS `:active` paints on the touch itself and can outlive the start of a scroll; the press model instead waits 150 ms before believing a press, cancels it the moment the finger travels 10 px or a scroll claims the gesture, never brings it back inside that gesture, answers a quick tap at the lift, and fades the release over 200 ms — the clocks a native list uses. One document-level controller does this for every marked element (installed by the first pressable to mount, removed by the last to unmount), so calling the hook adds no listener or state to your element. Under a mouse nothing changes: keep your `:active` rule, and drop it under `@media (pointer: coarse)` the way the built-in components do.',
+ 'The touch press model every Astryx pressable uses, for a local component that paints its own press. Under a finger, CSS `:active` paints on the touch itself and can outlive the start of a scroll; the press model instead waits 150 ms before believing a press, cancels it the moment the finger travels 10 px or a scroll claims the gesture, never brings it back inside that gesture, answers a quick tap at the lift, and fades the release over 200 ms — the clocks a native list uses. One document-level controller does this for every marked element (installed by the first pressable to mount, removed by the last to unmount), so calling the hook adds no listener or state to your element. On a desktop a mouse press is still your `:active` rule: keep it, and drop it under `@media (pointer: coarse)` the way the built-in components do. That query reads the primary pointer, so on a phone or tablet it also drops `:active` for a connected mouse, trackpad or keyboard; the controller paints those presses there (at once, faded at the release), so nothing goes unanswered.',
bestPractices: [
{
guidance: true,
@@ -35,7 +35,7 @@ export const docs = {
{
guidance: true,
description:
- 'Let the composed style own the press on every pointer: it keeps `:active` for a mouse and drops it under `@media (pointer: coarse)`, so a finger sees only the press model. A rule of your own that paints `:active` would paint under a finger too, on the touch and through a scroll.',
+ 'Let the composed style own the press on every pointer: it keeps `:active` for a desktop mouse and drops it under `@media (pointer: coarse)`, where the controller paints every press (a finger through the press model, a mouse or Space key at once). A rule of your own that paints `:active` would paint under a finger too, on the touch and through a scroll.',
},
{
guidance: false,
@@ -58,7 +58,7 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
export const docsDense = {
description:
- 'Marks an element as a pressable surface of the touch press model (150 ms onset, 10 px slop, cancel on scroll, tap answers at lift, 200 ms fade) and installs the shared document controller. Returns the data-astryx-pressable marker to spread; compose one of interactionOverlayStyles on the same element to paint.',
+ 'Marks an element as a pressable surface of the touch press model (150 ms onset, 10 px slop, cancel on scroll, tap answers at lift, 200 ms fade) and installs the shared document controller; on a coarse primary pointer it also paints mouse, trackpad and Space-key presses at once. Returns the data-astryx-pressable marker to spread; compose one of interactionOverlayStyles on the same element to paint.',
paramDescriptions: {},
returnDescriptions: {
pressableProps:
diff --git a/packages/core/src/hooks/usePressFeedback.ts b/packages/core/src/hooks/usePressFeedback.ts
index 1939ef5049..d3292cf6be 100644
--- a/packages/core/src/hooks/usePressFeedback.ts
+++ b/packages/core/src/hooks/usePressFeedback.ts
@@ -30,8 +30,11 @@ import {installPressFeedback, pressableProps} from '../utils/pressFeedback';
* while a touch press is believed (after the onset delay, cancelled by travel
* or by a scroll) and for the release, and the composed style paints the
* pressed token at the press's strength on the first frame and fades it over
- * the release, keeping `:active` for a mouse. A press is themed through
- * `--color-overlay-pressed`, which the hold, the flash and the fade all read.
+ * the release, keeping `:active` for a mouse on a desktop. On a phone or
+ * tablet the stylesheet drops `:active` for every press, so the controller
+ * also paints a mouse, trackpad or Space-key press there, at once. A press is
+ * themed through `--color-overlay-pressed`, which the hold, the flash and the
+ * fade all read.
* Every Astryx component that paints a press already does this; reach for it
* when a local component paints its own press and must behave like the rest
* of the system under a finger.
diff --git a/packages/core/src/utils/interactionOverlay.stylex.ts b/packages/core/src/utils/interactionOverlay.stylex.ts
index d35bc996c6..5e65e0e0d7 100644
--- a/packages/core/src/utils/interactionOverlay.stylex.ts
+++ b/packages/core/src/utils/interactionOverlay.stylex.ts
@@ -31,7 +31,10 @@
* dropped and the press is written by the touch press controller
* (`utils/pressFeedback.ts`) as `data-astryx-press="on"` once the press is
* believed (150 ms, no travel, no scroll) and `data-astryx-press="fading"` for the
- * 200 ms release. The two arms paint those through ONE number:
+ * 200 ms release. The query reads the PRIMARY pointer, so on a phone or tablet
+ * a mouse, trackpad or Space-key press loses `:active` too; the controller
+ * writes the same attribute for those, at once. The two arms paint those
+ * through ONE number:
*
* - `--astryx-press-alpha` is the press's strength, 0 to 1. It is a
* registered custom property (`@property`, syntax `<number>`, declared once
diff --git a/packages/core/src/utils/pressFeedback.test.ts b/packages/core/src/utils/pressFeedback.test.ts
index 454a276da4..588625e840 100644
--- a/packages/core/src/utils/pressFeedback.test.ts
+++ b/packages/core/src/utils/pressFeedback.test.ts
@@ -50,7 +50,13 @@ function press(
pointerType = 'touch',
): void {
const event = new Event(type, {bubbles: true, cancelable: true});
- Object.assign(event, {clientX: x, clientY: y, pointerId: 1, pointerType});
+ Object.assign(event, {
+ button: 0,
+ clientX: x,
+ clientY: y,
+ pointerId: 1,
+ pointerType,
+ });
element.dispatchEvent(event);
}
@@ -107,12 +113,26 @@ describe('the press reaches the surface the finger landed on', () => {
expect(rows[2].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
});
- it('ignores a mouse entirely', () => {
+ it('leaves a mouse press to `:active` where the primary pointer is fine', () => {
+ // The test environment is a desktop: `(pointer: coarse)` does not match,
+ // so the stylesheet keeps `:active` for the mouse and the controller
+ // stays out of its way.
+ expect(window.matchMedia('(pointer: coarse)').matches).toBe(false);
press(rows[0], 'pointerdown', 10, 10, 'mouse');
vi.advanceTimersByTime(PRESS_ONSET_MS * 2);
expect(pressedRow()).toBe(-1);
});
+ 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');
+ rows[0].appendChild(button);
+ button.dispatchEvent(
+ new KeyboardEvent('keydown', {key: ' ', bubbles: true, cancelable: true}),
+ );
+ expect(button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
it('ignores a touch that lands outside every pressable', () => {
const plain = document.createElement('div');
document.body.appendChild(plain);
@@ -338,6 +358,294 @@ describe('two touches in a row', () => {
});
});
+describe('a phone or tablet paints a mouse or Space press itself', () => {
+ // `(pointer: coarse)` reads the PRIMARY pointer. Where it matches, the
+ // stylesheet drops every `:active` arm, so a trackpad click or a Space press
+ // on a focused button would paint nothing at all unless the controller
+ // paints it: a tablet with a keyboard and trackpad, a phone with a mouse.
+ const coarse = (query: string): MediaQueryList =>
+ ({
+ matches: /\(\s*pointer\s*:\s*coarse\s*\)/.test(query),
+ media: query,
+ onchange: null,
+ addListener: () => undefined,
+ removeListener: () => undefined,
+ addEventListener: () => undefined,
+ removeEventListener: () => undefined,
+ dispatchEvent: () => false,
+ }) as MediaQueryList;
+
+ function key(target: Element, type: 'keydown' | 'keyup', init = {}): void {
+ target.dispatchEvent(
+ new KeyboardEvent(type, {
+ key: ' ',
+ bubbles: true,
+ cancelable: true,
+ ...init,
+ }),
+ );
+ }
+
+ function focusedButton(row: HTMLElement): HTMLButtonElement {
+ const button = document.createElement('button');
+ button.setAttribute(PRESSABLE_ATTRIBUTE, '');
+ row.appendChild(button);
+ button.focus();
+ return button;
+ }
+
+ beforeEach(() => {
+ release();
+ vi.stubGlobal('matchMedia', coarse);
+ // These are a mouse or a key on a touch-first device: coarse primary.
+ expect(window.matchMedia('(pointer: coarse)').matches).toBe(true);
+ release = installPressFeedback();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('paints a mouse press at once, holds it, and fades it at the release', () => {
+ press(rows[1], 'pointerdown', 10, 100, 'mouse');
+ // No onset delay: a mouse button cannot become a scroll.
+ expect(rows[1].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ vi.advanceTimersByTime(1000);
+ expect(rows[1].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ press(rows[1], 'pointerup', 10, 100, 'mouse');
+ expect(rows[1].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ expect(rows[1].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ 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');
+ scroller.dispatchEvent(new Event('scroll'));
+ expect(rows[1].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ press(document.body, 'pointerup', 400, 900, 'mouse');
+ expect(rows[1].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ });
+
+ it('paints only the primary button', () => {
+ const secondary = new Event('pointerdown', {bubbles: true});
+ Object.assign(secondary, {
+ button: 2,
+ clientX: 10,
+ clientY: 10,
+ pointerId: 1,
+ pointerType: 'mouse',
+ });
+ rows[0].dispatchEvent(secondary);
+ expect(pressedRow()).toBe(-1);
+ });
+
+ it('paints the innermost surface, and nothing on a disabled one', () => {
+ const inner = pressable('button');
+ rows[2].appendChild(inner);
+ press(inner, 'pointerdown', 10, 200, 'mouse');
+ expect(inner.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ expect(rows[2].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ press(inner, 'pointerup', 10, 200, 'mouse');
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+
+ const disabled = pressable('button');
+ disabled.setAttribute('aria-disabled', 'true');
+ rows[3].appendChild(disabled);
+ press(disabled, 'pointerdown', 10, 300, 'mouse');
+ expect(document.querySelectorAll(`[${PRESSED_ATTRIBUTE}]`)).toHaveLength(0);
+ });
+
+ it('drops the paint at once when the pointer is cancelled or a drag starts', () => {
+ press(rows[0], 'pointerdown', 10, 10, 'mouse');
+ press(rows[0], 'pointercancel', 10, 10, 'mouse');
+ expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+
+ press(rows[1], 'pointerdown', 10, 100, 'mouse');
+ rows[1].dispatchEvent(new Event('dragstart', {bubbles: true}));
+ expect(rows[1].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ // The slot is free again: the next press paints.
+ press(rows[2], 'pointerdown', 10, 200, 'mouse');
+ expect(rows[2].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+
+ it("a finger's press and a mouse press keep their own slots", () => {
+ press(rows[0], 'pointerdown', 10, 10, 'mouse');
+ const touch = new Event('pointerdown', {bubbles: true});
+ Object.assign(touch, {
+ button: 0,
+ clientX: 10,
+ clientY: 100,
+ pointerId: 7,
+ pointerType: 'touch',
+ });
+ rows[1].dispatchEvent(touch);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ expect(rows[1].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ press(rows[0], 'pointerup', 10, 10, 'mouse');
+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ expect(rows[1].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+
+ it("a mouse press on a surface a finger's release is still fading keeps its paint", () => {
+ press(rows[0], 'pointerdown', 10, 10);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ press(rows[0], 'pointerup', 10, 10);
+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ press(rows[0], 'pointerdown', 10, 10, 'mouse');
+ // The finger's fade timer would have removed the attribute here.
+ vi.advanceTimersByTime(PRESS_FADE_MS * 2);
+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+
+ it('a mouse press never arms the scroll brake', () => {
+ press(rows[0], 'pointerdown', 10, 10, 'mouse');
+ press(rows[0], 'pointerup', 10, 10, 'mouse');
+ scroller.dispatchEvent(new Event('scroll'));
+ press(rows[1], 'pointerdown', 10, 100);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ expect(rows[1].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+
+ it('paints a Space press on a focused button while the key is down', () => {
+ const button = focusedButton(rows[0]);
+ key(button, 'keydown');
+ expect(button.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ vi.advanceTimersByTime(1000);
+ key(button, 'keydown', {repeat: true});
+ expect(button.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ key(button, 'keyup');
+ expect(button.getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ expect(button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('listens for the key’s release and focus loss only while Space holds a press', () => {
+ const attached = new Set<string>();
+ const add = vi.spyOn(window, 'addEventListener');
+ const remove = vi.spyOn(window, 'removeEventListener');
+ const sync = () => {
+ for (const [type] of add.mock.calls.splice(0)) {
+ attached.add(type);
+ }
+ for (const [type] of remove.mock.calls.splice(0)) {
+ attached.delete(type);
+ }
+ };
+ const button = focusedButton(rows[0]);
+ key(button, 'keydown');
+ sync();
+ expect([...attached].sort()).toEqual(['blur', 'keyup']);
+ key(button, 'keyup');
+ sync();
+ expect([...attached]).toEqual([]);
+ add.mockRestore();
+ remove.mockRestore();
+ });
+
+ it('leaves the row around a focused checkbox or radio at rest, as desktop browsers do', () => {
+ // Only the input matches `:active` for a Space press; the row around it,
+ // the pressable surface, stays at rest in desktop Chromium and WebKit.
+ for (const type of ['checkbox', 'radio']) {
+ const input = document.createElement('input');
+ input.type = type;
+ rows[2].appendChild(input);
+ input.focus();
+ key(input, 'keydown');
+ expect(rows[2].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ key(input, 'keyup');
+ }
+ });
+
+ it('paints a Space press only on a focused element that is itself the surface', () => {
+ const plain = document.createElement('button');
+ rows[2].appendChild(plain);
+ plain.focus();
+ key(plain, 'keydown');
+ expect(rows[2].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ key(plain, 'keyup');
+ });
+
+ it('leaves a menu row to the menu: its highlight is the only paint', () => {
+ // useMenuPress FR6 and DEC-6: a press held on one row while the highlight
+ // follows the pointer to another would light two rows.
+ const menu = document.createElement('div');
+ menu.setAttribute('data-astryx-menu-press', '');
+ const first = pressable('button');
+ const second = pressable('button');
+ menu.append(first, second);
+ document.body.appendChild(menu);
+ try {
+ press(first, 'pointerdown', 10, 10, 'mouse');
+ press(second, 'pointermove', 10, 40, 'mouse');
+ expect(first.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ press(second, 'pointerup', 10, 40, 'mouse');
+ first.focus();
+ key(first, 'keydown');
+ expect(first.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ key(first, 'keyup');
+ } finally {
+ menu.remove();
+ }
+ });
+
+ it('paints nothing where Space activates nothing, for Enter, or for a press the page cancelled', () => {
+ const link = document.createElement('a');
+ link.href = '#';
+ link.setAttribute(PRESSABLE_ATTRIBUTE, '');
+ rows[0].appendChild(link);
+ key(link, 'keydown');
+
+ const roleButton = pressable('div');
+ roleButton.setAttribute('role', 'button');
+ roleButton.tabIndex = 0;
+ rows[1].appendChild(roleButton);
+ key(roleButton, 'keydown');
+
+ const button = focusedButton(rows[2]);
+ key(button, 'keydown', {key: 'Enter'});
+ button.addEventListener('keydown', event => event.preventDefault(), {
+ once: true,
+ });
+ key(button, 'keydown');
+ expect(document.querySelectorAll(`[${PRESSED_ATTRIBUTE}]`)).toHaveLength(0);
+ });
+
+ it('ends the press with its fade when focus leaves before the key comes up', () => {
+ const button = focusedButton(rows[0]);
+ key(button, 'keydown');
+ button.dispatchEvent(new FocusEvent('blur'));
+ expect(button.getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ expect(button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('leaves nothing painted when the page hides or the controller comes down', () => {
+ const button = focusedButton(rows[0]);
+ key(button, 'keydown');
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ value: 'hidden',
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ value: 'visible',
+ });
+ expect(button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+
+ press(rows[1], 'pointerdown', 10, 100, 'mouse');
+ release();
+ expect(rows[1].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ key(button, 'keydown');
+ press(rows[2], 'pointerdown', 10, 200, 'mouse');
+ expect(document.querySelectorAll(`[${PRESSED_ATTRIBUTE}]`)).toHaveLength(0);
+ // Re-install for afterEach's release.
+ release = installPressFeedback();
+ });
+});
+
describe('no gesture is ever left painted', () => {
// Every case here strands a pending timer if `apply` clears timers
// unconditionally, and each one ends with a paint on a row nobody is
diff --git a/packages/core/src/utils/pressFeedback.ts b/packages/core/src/utils/pressFeedback.ts
index 60294c0851..3aada91bec 100644
--- a/packages/core/src/utils/pressFeedback.ts
+++ b/packages/core/src/utils/pressFeedback.ts
@@ -3,7 +3,7 @@
/**
* @file pressFeedback.ts
* @input The press state machine (pressGesture.ts) and the document's pointer,
- * scroll and visibility events
+ * keyboard, scroll and visibility events
* @output Exports PRESSABLE_ATTRIBUTE, PRESSED_ATTRIBUTE, pressableProps and
* installPressFeedback
* @position The DOM half of the touch press model: one delegated controller
@@ -18,18 +18,30 @@
* Why a delegated document-level controller and not a hook on the element: a
* virtualized list can carry more than a thousand rows, and four listeners
* plus a state hook per row is not a cost a list like that can pay. This is
- * six listeners for the whole document, and a press costs one attribute write
- * on one element: no React render, no subscription, no per-element anything.
- * It also makes the behaviour uniform for free: every component that paints a
- * press carries {@link PRESSABLE_ATTRIBUTE}, so all of them change together.
+ * a handful of listeners for the whole document, and a press costs one
+ * attribute write on one element: no React render, no subscription, no
+ * per-element anything. It also makes the behaviour uniform for free: every
+ * component that paints a press carries {@link PRESSABLE_ATTRIBUTE}, so all of
+ * them change together.
*
- * Under a mouse the controller does nothing and CSS `:active` keeps the press,
- * as it always has. Under a finger the `:active` arm is dropped by the CSS
- * (`@media (pointer: coarse)`) and this writes `data-astryx-press="on"` when the
- * press is believed and `data-astryx-press="fading"` for the release's exit.
+ * Where the primary pointer is fine (a desktop), the controller ignores the
+ * mouse and the keyboard: CSS `:active` keeps their press, as it always has,
+ * and the mouse path costs nothing. Under a finger the `:active` arm is
+ * dropped by the CSS (`@media (pointer: coarse)`) and this writes
+ * `data-astryx-press="on"` when the press is believed and
+ * `data-astryx-press="fading"` for the release's exit.
+ *
+ * That query reads the PRIMARY pointer, so on a phone or a tablet the
+ * stylesheet drops `:active` for every press, including a mouse or trackpad
+ * click and a Space press on a focused button. There, the controller paints
+ * those too: at once (no scroller can claim a mouse button or a key, so
+ * nothing waits), held while the button or key is down, and faded at the
+ * release, the way a finger's press leaves. The query is the stylesheet's
+ * own, so the two cannot disagree about which presses are the controller's.
*
* SYNC: When modified, update pressGesture.ts, hooks/usePressFeedback.ts,
- * utils/interactionOverlay.stylex.ts and pressFeedback.test.ts.
+ * hooks/usePressFeedback.doc.mjs, utils/interactionOverlay.stylex.ts and
+ * pressFeedback.test.ts.
*/
import type {PressGesture, PressPaint, PressStep} from './pressGesture';
@@ -41,6 +53,7 @@ import {
PRESS_SCROLL_BRAKE_MS,
pressGestureStep,
} from './pressGesture';
+import {TOUCH_QUERY} from './touchPresentation';
/**
* The marker the controller finds with `closest()`. Every Astryx component
@@ -51,7 +64,11 @@ import {
*/
export const PRESSABLE_ATTRIBUTE = 'data-astryx-pressable';
-/** `on` while the press is believed and the finger is down; `fading` for the release's exit. */
+/**
+ * `on` while the press is believed and the finger (or, where the controller
+ * paints them, the mouse button or Space key) is down; `fading` for the
+ * release's exit.
+ */
export const PRESSED_ATTRIBUTE = 'data-astryx-press';
/** Spread onto the element that paints the press. */
@@ -70,17 +87,55 @@ export const PRESS_GESTURE_MEMORY_MS = 3000;
/** A surface that is not enabled does not press, however it is touched. */
const DISABLED = ':disabled, [aria-disabled="true"]';
+/**
+ * The `<input>` types a Space press activates as a button. Browsers hold
+ * `:active` on these (and on `<button>`) while Space is down; on a link or a
+ * `role="button"` element Space does nothing, so neither paints there. A
+ * checkbox or radio is left out: its pressable surface is the row around it,
+ * and desktop Chromium and WebKit leave that row at rest for a Space press
+ * (only the input matches `:active`), so it paints nothing here either.
+ */
+const SPACE_ACTIVATED_INPUT_TYPES: ReadonlySet<string> = new Set([
+ 'button',
+ 'image',
+ 'reset',
+ 'submit',
+]);
+
+/**
+ * A menu's own highlight is its only paint (`module:DropdownMenu/useMenuPress`
+ * FR6, DEC-6): a press held on one row while the highlight follows the
+ * pointer to another would light two rows.
+ */
+const MENU_PRESS_ROOT = '[data-astryx-menu-press]';
+
interface LiveGesture {
element: HTMLElement;
gesture: PressGesture;
- /** The pointer this gesture belongs to; a second finger is ignored. */
+ /**
+ * The pointer this gesture belongs to; a second finger is ignored. `null`
+ * for a press of the Space key.
+ */
pointerId: number | null;
timer: ReturnType<typeof setTimeout> | null;
}
-let live: LiveGesture | null = null;
+/**
+ * One tracking slot. A finger's press runs the whole machine (the delay, the
+ * slop, the scroll that takes it away). A mouse button's or the Space key's
+ * press is believed at once and only waits for its release, so it has a slot
+ * of its own: a finger landing never ends it, and it never swallows a
+ * finger's press.
+ */
+interface Slot {
+ live: LiveGesture | null;
+}
+
+const finger: Slot = {live: null};
+const button: Slot = {live: null};
/** How many callers hold the controller installed; listeners exist while > 0. */
let holders = 0;
+/** Whether the stylesheet left mouse and keyboard presses to the controller; read at the first one. */
/**
* When a scroller last moved UNDER A FINGER OF ITS OWN, and which one.
*
@@ -115,10 +170,10 @@ function paintElement(element: HTMLElement, paint: PressPaint): void {
element.setAttribute(PRESSED_ATTRIBUTE, paint);
}
-function clearTimer(): void {
- if (live?.timer != null) {
- clearTimeout(live.timer);
- live.timer = null;
+function clearTimer(slot: Slot): void {
+ if (slot.live?.timer != null) {
+ clearTimeout(slot.live.timer);
+ slot.live.timer = null;
}
}
@@ -142,18 +197,19 @@ function clearTimer(): void {
* controller's single tracking slot, holding a reference to an element a
* virtualized list may already have unmounted.
*/
-function apply(step: PressStep): void {
+function apply(slot: Slot, step: PressStep): void {
+ const live = slot.live;
if (live == null) {
return;
}
const phaseMoved = step.gesture.phase !== live.gesture.phase;
if (step.timer != null || phaseMoved) {
- clearTimer();
+ clearTimer(slot);
}
live.gesture = step.gesture;
paintElement(live.element, step.paint);
if (step.gesture.phase === 'idle') {
- live = null;
+ slot.live = null;
return;
}
if (step.timer != null) {
@@ -162,11 +218,12 @@ function apply(step: PressStep): void {
// while a scroll runs, so a frame-based delay would fire late, after the
// scroll, and paint a control nobody is pressing any more.
live.timer = setTimeout(() => {
- if (live != null) {
- live.timer = null;
+ if (slot.live != null) {
+ slot.live.timer = null;
}
apply(
- pressGestureStep(live?.gesture ?? idlePressGesture(), {
+ slot,
+ pressGestureStep(slot.live?.gesture ?? idlePressGesture(), {
kind: TIMER_EVENT[kind],
}),
);
@@ -222,50 +279,136 @@ function scrollerIsBraking(element: HTMLElement): boolean {
}
/**
- * Let go of the controller's one tracking slot once the gesture is over.
+ * Let go of a slot once its gesture is over.
*
* A gesture that became a scroll ends in `pointercancel`, not `pointerup`, so
* without this the dead gesture holds the slot for ever and every press after
* the first scroll is swallowed.
*/
-function releaseIfDead(): void {
- if (live?.gesture.phase === 'dead') {
- clearTimer();
- live = null;
+function releaseIfDead(slot: Slot): void {
+ if (slot.live?.gesture.phase === 'dead') {
+ clearTimer(slot);
+ slot.live = null;
}
}
/** Drop the paint and forget the gesture, without running the machine. */
-function finish(): void {
+function finish(slot: Slot): void {
+ const live = slot.live;
if (live == null) {
return;
}
- clearTimer();
+ clearTimer(slot);
live.element.removeAttribute(PRESSED_ATTRIBUTE);
- live = null;
+ slot.live = null;
+ if (slot === button) {
+ holdKey(false);
+ }
+}
+
+/** A new press on an element owns its paint: the other slot's gesture there ends. */
+function takeOver(other: Slot, element: HTMLElement): void {
+ if (other.live?.element === element) {
+ finish(other);
+ }
+}
+
+/**
+ * Whether presses with a mouse or a key are the controller's to paint here.
+ * Asked at each such press: rendering a pressable never queries the pointer,
+ * so a layout that must not depend on it stays independent.
+ */
+function stylesheetDroppedActive(): boolean {
+ // The shared touch resolver's key (`spec:AST-012` FR2): the condition the
+ // stylesheet drops `:active` under (`COARSE` in
+ // interactionOverlay.stylex.ts), read once per press.
+ return (
+ typeof window.matchMedia === 'function' &&
+ window.matchMedia(TOUCH_QUERY).matches
+ );
+}
+
+/**
+ * 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.
+ */
+function buttonSurfaceAt(
+ target: EventTarget | null,
+ pointerId: number | null,
+): HTMLElement | null {
+ const element = surfaceAt(target);
+ if (element == null || element.closest(MENU_PRESS_ROOT) != null) {
+ return null;
+ }
+ if (pointerId == null && element !== target) {
+ return null;
+ }
+ return element;
+}
+
+/** Start a mouse button's or the Space key's press on the surface, if there is one. */
+function pressButton(
+ target: EventTarget | null,
+ pointerId: number | null,
+): void {
+ // A press still fading elsewhere goes now: the new one owns the slot.
+ finish(button);
+ const element = buttonSurfaceAt(target, pointerId);
+ if (element == null) {
+ return;
+ }
+ takeOver(finger, element);
+ button.live = {element, gesture: idlePressGesture(), pointerId, timer: null};
+ holdKey(pointerId == null);
+ apply(button, pressGestureStep(button.live.gesture, {kind: 'buttonDown'}));
+}
+
+/** The mouse button or the key came up: the press fades like a finger's. */
+function releaseButton(): void {
+ holdKey(false);
+ if (button.live == null) {
+ return;
+ }
+ apply(button, pressGestureStep(button.live.gesture, {kind: 'up'}));
+}
+
+/** The platform took the mouse's press away: the paint goes at once. */
+function cancelButton(): void {
+ holdKey(false);
+ if (button.live == null) {
+ return;
+ }
+ apply(button, pressGestureStep(button.live.gesture, {kind: 'cancel'}));
+ releaseIfDead(button);
}
function onPointerDown(event: PointerEvent): void {
- // A mouse already has hover and keeps `:active`; the treatment's CSS is
- // inside `@media (pointer: coarse)`. Not tracking it keeps desktop identical
- // and costs the mouse path nothing.
if (event.pointerType === 'mouse') {
+ // A mouse already has hover and keeps `:active` where the primary pointer
+ // is fine; the touch treatment's CSS is inside `@media (pointer: coarse)`.
+ // Not tracking it there keeps desktop identical and costs the mouse path
+ // nothing. Only the primary button: that is the press `:active` paints.
+ if (event.button === 0 && stylesheetDroppedActive()) {
+ pressButton(event.target, event.pointerId);
+ }
return;
}
- if (live != null) {
+ if (finger.live != null) {
const fingerIsUp =
- live.gesture.phase === 'fading' || live.gesture.phase === 'flash';
+ finger.live.gesture.phase === 'fading' ||
+ finger.live.gesture.phase === 'flash';
// A finger still down means a SECOND finger: a pinch or a two-finger
// scroll is not a press, so the first gesture ends and the second paints
// nothing.
if (!fingerIsUp) {
- finish();
+ finish(finger);
return;
}
// A finger already up means the last tap is still fading. The new touch
// owns the surface from here; swallowing it would make the second of two
// quick taps answer with nothing.
- finish();
+ finish(finger);
}
const element = surfaceAt(event.target);
// The touch clock is stamped AFTER the brake reads it, deliberately: the
@@ -278,14 +421,16 @@ function onPointerDown(event: PointerEvent): void {
if (element == null || braking) {
return;
}
- live = {
+ takeOver(button, element);
+ finger.live = {
element,
gesture: idlePressGesture(),
pointerId: event.pointerId,
timer: null,
};
apply(
- pressGestureStep(live.gesture, {
+ finger,
+ pressGestureStep(finger.live.gesture, {
kind: 'down',
x: event.clientX,
y: event.clientY,
@@ -294,6 +439,7 @@ function onPointerDown(event: PointerEvent): void {
}
function onPointerMove(event: PointerEvent): void {
+ const live = finger.live;
if (
live == null ||
(live.pointerId != null && event.pointerId !== live.pointerId)
@@ -301,6 +447,7 @@ function onPointerMove(event: PointerEvent): void {
return;
}
apply(
+ finger,
pressGestureStep(live.gesture, {
kind: 'move',
x: event.clientX,
@@ -316,6 +463,9 @@ function onPointerUp(event: PointerEvent): void {
// press landing inside the brake window. A coarse pointer and a mouse can
// both be present on one device.
if (event.pointerType === 'mouse') {
+ if (button.live != null && button.live.pointerId === event.pointerId) {
+ releaseButton();
+ }
return;
}
// The lift is when momentum starts, so it is the clock the brake wants most.
@@ -323,14 +473,15 @@ function onPointerUp(event: PointerEvent): void {
if (event.target instanceof Node) {
lastTouchTarget = event.target;
}
+ const live = finger.live;
if (
live == null ||
(live.pointerId != null && event.pointerId !== live.pointerId)
) {
return;
}
- apply(pressGestureStep(live.gesture, {kind: 'up'}));
- releaseIfDead();
+ apply(finger, pressGestureStep(live.gesture, {kind: 'up'}));
+ releaseIfDead(finger);
}
/**
@@ -341,14 +492,34 @@ function onPointerUp(event: PointerEvent): void {
* against +47 ms on a fling), which is what puts this cancel one frame ahead
* of the list's motion, the way UIKit's `touchesCancelled` is.
*/
-function onCancel(): void {
+function onCancel(event?: Event): void {
+ // A cancelled mouse pointer ends the mouse's press, not a finger's.
+ const pointer = event as Partial<PointerEvent> | undefined;
+ if (pointer?.pointerType === 'mouse') {
+ if (button.live != null && button.live.pointerId === pointer.pointerId) {
+ cancelButton();
+ }
+ return;
+ }
+ const live = finger.live;
if (live == null) {
return;
}
- apply(pressGestureStep(live.gesture, {kind: 'cancel'}));
+ apply(finger, pressGestureStep(live.gesture, {kind: 'cancel'}));
// The pointer is gone: a scroll-claimed gesture sends no further pointer
// events, so nothing else would ever free the slot.
- releaseIfDead();
+ releaseIfDead(finger);
+}
+
+/**
+ * `dragstart`, and NOT `contextmenu`: a press that becomes a drag has taken
+ * the gesture, whatever pressed it, but a right-click is a mouse act this
+ * controller never tracks, and listening for it would read as a takeover of
+ * the browser's own menu.
+ */
+function onDragStart(): void {
+ onCancel();
+ cancelButton();
}
/** A scroll anywhere above the pressed element, caught in the capture phase. */
@@ -365,11 +536,13 @@ function onScroll(event: Event): void {
lastScrollAt = Date.now();
lastScroller = scroller;
}
+ const live = finger.live;
if (live == null) {
return;
}
// The CANCEL arm is deliberately wider than the brake: any scroll above the
- // pressed element takes the gesture, driven by a finger or not.
+ // pressed element takes the gesture, driven by a finger or not. A mouse's
+ // or a key's press is not a finger's and keeps going, as `:active` does.
const reaches = scroller === document || scroller.contains(live.element);
if (!reaches) {
return;
@@ -377,6 +550,57 @@ function onScroll(event: Event): void {
onCancel();
}
+/** Whether a Space press on this element is an activation browsers paint as `:active`. */
+function activatesOnSpace(target: EventTarget | null): boolean {
+ if (target instanceof HTMLButtonElement) {
+ return true;
+ }
+ return (
+ target instanceof HTMLInputElement &&
+ SPACE_ACTIVATED_INPUT_TYPES.has(target.type)
+ );
+}
+
+/**
+ * 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
+ * page cancelled (`preventDefault`) paints nothing, exactly as `:active` does
+ * not engage for one.
+ */
+function onKeyDown(event: KeyboardEvent): void {
+ if (
+ event.key !== ' ' ||
+ event.repeat ||
+ event.isComposing ||
+ event.defaultPrevented ||
+ !activatesOnSpace(event.target) ||
+ !stylesheetDroppedActive()
+ ) {
+ return;
+ }
+ pressButton(event.target, null);
+}
+
+function onKeyUp(event: KeyboardEvent): void {
+ if (
+ event.key === ' ' &&
+ button.live != null &&
+ button.live.pointerId == null
+ ) {
+ releaseButton();
+ }
+}
+
+/**
+ * Focus left the pressed button, or the window lost focus: the key's release
+ * may never arrive here, so the press ends now, with its fade.
+ */
+function onBlur(): void {
+ if (button.live != null && button.live.pointerId == null) {
+ releaseButton();
+ }
+}
+
/**
* The backstop: a surface that leaves the document while it is painted must
* not come back painted. A virtualized list mounts and unmounts rows as they
@@ -386,11 +610,13 @@ function onScroll(event: Event): void {
*/
function onVisibilityChange(): void {
if (document.visibilityState === 'hidden') {
- finish();
+ finish(finger);
+ finish(button);
}
}
const PASSIVE_CAPTURE = {capture: true, passive: true} as const;
+const PASSIVE = {passive: true} as const;
function addListeners(): void {
window.addEventListener('pointerdown', onPointerDown, PASSIVE_CAPTURE);
@@ -398,15 +624,14 @@ function addListeners(): void {
window.addEventListener('pointerup', onPointerUp, PASSIVE_CAPTURE);
window.addEventListener('pointercancel', onCancel, PASSIVE_CAPTURE);
window.addEventListener('touchcancel', onCancel, PASSIVE_CAPTURE);
- // `dragstart`, and NOT `contextmenu`: a long press that becomes a drag has
- // taken the gesture, but a right-click is a mouse act this controller never
- // tracks, and listening for it would read as a takeover of the browser's
- // own menu.
- window.addEventListener('dragstart', onCancel, PASSIVE_CAPTURE);
+ window.addEventListener('dragstart', onDragStart, PASSIVE_CAPTURE);
// `scroll` does not bubble, so the capture phase is the only way one
// listener hears every scroller in the document.
document.addEventListener('scroll', onScroll, PASSIVE_CAPTURE);
document.addEventListener('visibilitychange', onVisibilityChange);
+ // Only Space's press needs the key's release and focus loss, so those two
+ // are attached while it is held (holdKey).
+ window.addEventListener('keydown', onKeyDown, PASSIVE);
}
function removeListeners(): void {
@@ -415,9 +640,35 @@ function removeListeners(): void {
window.removeEventListener('pointerup', onPointerUp, PASSIVE_CAPTURE);
window.removeEventListener('pointercancel', onCancel, PASSIVE_CAPTURE);
window.removeEventListener('touchcancel', onCancel, PASSIVE_CAPTURE);
- window.removeEventListener('dragstart', onCancel, PASSIVE_CAPTURE);
+ window.removeEventListener('dragstart', onDragStart, PASSIVE_CAPTURE);
document.removeEventListener('scroll', onScroll, PASSIVE_CAPTURE);
document.removeEventListener('visibilitychange', onVisibilityChange);
+ window.removeEventListener('keydown', onKeyDown);
+ holdKey(false);
+}
+
+/** Whether the key-release listeners are attached. */
+let keyHeld = false;
+
+/**
+ * Attach the key's release and focus-loss listeners while Space holds a
+ * press, and take them down when it ends: at rest the key path costs one
+ * `keydown` listener.
+ */
+function holdKey(held: boolean): void {
+ if (held === keyHeld) {
+ return;
+ }
+ keyHeld = held;
+ if (held) {
+ window.addEventListener('keyup', onKeyUp, PASSIVE);
+ // `blur` does not bubble: the capture phase hears the element losing
+ // focus and the window losing it.
+ window.addEventListener('blur', onBlur, PASSIVE_CAPTURE);
+ } else {
+ window.removeEventListener('keyup', onKeyUp);
+ window.removeEventListener('blur', onBlur, PASSIVE_CAPTURE);
+ }
}
/**
@@ -452,7 +703,8 @@ export function installPressFeedback(): () => void {
return;
}
removeListeners();
- finish();
+ finish(finger);
+ finish(button);
lastScrollAt = 0;
lastScroller = null;
lastTouchAt = 0;
diff --git a/packages/core/src/utils/pressGesture.test.ts b/packages/core/src/utils/pressGesture.test.ts
index 90bcecc5d6..5bf49e0ee9 100644
--- a/packages/core/src/utils/pressGesture.test.ts
+++ b/packages/core/src/utils/pressGesture.test.ts
@@ -271,3 +271,53 @@ describe('the release fades', () => {
expect(pressGestureStep(pressed, {kind: 'up'}).timer).toBe('fade');
});
});
+
+describe('on a touch-first device, a mouse button or the Space key presses at once', () => {
+ // The stylesheet drops `:active` by the PRIMARY pointer, so on a phone or
+ // a tablet a trackpad click or a Space press has nothing else to paint it.
+ // Nothing can turn either into a scroll, so nothing waits.
+ const buttonDown: PressEvent = {kind: 'buttonDown'};
+
+ it('paints on the press itself and arms no timer', () => {
+ const step = pressGestureStep(idlePressGesture(), buttonDown);
+ expect(step.paint).toBe('on');
+ expect(step.timer).toBeNull();
+ expect(step.gesture.phase).toBe('buttonHeld');
+ });
+
+ it('keeps the paint through any travel, as a held mouse keeps `:active`', () => {
+ const {paints, gesture} = run([
+ buttonDown,
+ move(100 + PRESS_SLOP_PX * 10, 100),
+ move(-500, -500),
+ {kind: 'onset'},
+ ]);
+ expect(paints).toEqual(['on', 'on', 'on', 'on']);
+ expect(gesture.phase).toBe('buttonHeld');
+ });
+
+ it("fades at the release with a finger's fade, and ends idle", () => {
+ const held = pressGestureStep(idlePressGesture(), buttonDown).gesture;
+ const release = pressGestureStep(held, {kind: 'up'});
+ expect(release.paint).toBe('fading');
+ expect(release.timer).toBe('fade');
+ const {paints, gesture} = run([
+ buttonDown,
+ {kind: 'up'},
+ {kind: 'fadeEnd'},
+ ]);
+ expect(paints).toEqual(['on', 'fading', 'none']);
+ expect(gesture.phase).toBe('idle');
+ });
+
+ it('drops the paint at once when the platform takes the press away', () => {
+ const {paints, gesture} = run([buttonDown, {kind: 'cancel'}]);
+ expect(paints).toEqual(['on', 'none']);
+ expect(gesture.phase).toBe('dead');
+ });
+
+ it('takes over a surface whose last press is still fading', () => {
+ const {paints} = run([buttonDown, {kind: 'up'}, buttonDown]);
+ expect(paints).toEqual(['on', 'fading', 'on']);
+ });
+});
diff --git a/packages/core/src/utils/pressGesture.ts b/packages/core/src/utils/pressGesture.ts
index 96e3b1000b..9798f7c61a 100644
--- a/packages/core/src/utils/pressGesture.ts
+++ b/packages/core/src/utils/pressGesture.ts
@@ -2,7 +2,7 @@
/**
* @file pressGesture.ts
- * @input A press gesture's current phase and one pointer or timer event
+ * @input A press gesture's current phase and one pointer, key or timer event
* @output Exports the press state machine (pressGestureStep, idlePressGesture),
* its clocks (PRESS_ONSET_MS, PRESS_SLOP_PX, PRESS_FLASH_MS, PRESS_FADE_MS,
* PRESS_SCROLL_BRAKE_MS) and their types
@@ -18,6 +18,11 @@
* still painted 1.6 s into a scroll. So on a coarse pointer the pressed state
* is owned here, in JavaScript, and `:active` keeps only the mouse.
*
+ * The stylesheet drops `:active` by the PRIMARY pointer, so a mouse, trackpad
+ * or Space key on such a device has lost `:active` too. Their presses come
+ * here as `buttonDown`: painted at once, held through any travel, faded on
+ * release like a finger's.
+ *
* Every constant below was measured against the real Settings and Contacts
* apps on an iPhone simulator, driven with real HID touches at 60 fps, before
* it was written down. The machine is deliberately ignorant of the DOM: it
@@ -92,9 +97,13 @@ export type PressPaint = 'none' | 'on' | 'fading';
* until the finger lifts and a new one starts, so a finger that stops moving,
* or comes back to the control it started on, paints nothing. That is the
* difference between this and `:active`.
+ *
+ * `buttonHeld` is a press made with a mouse button or the Space key. No
+ * scroller can claim one, so it paints at once, travel does not end it, and
+ * only the release does.
*/
export type PressPhase =
- 'idle' | 'armed' | 'pressed' | 'flash' | 'fading' | 'dead';
+ 'idle' | 'armed' | 'pressed' | 'buttonHeld' | 'flash' | 'fading' | 'dead';
export interface PressGesture {
readonly phase: PressPhase;
@@ -105,6 +114,12 @@ export interface PressGesture {
export type PressEvent =
| {kind: 'down'; x: number; y: number}
+ /**
+ * A mouse button or the Space key went down on the surface. The
+ * controller sends this only where the stylesheet has dropped `:active`
+ * (a coarse primary pointer), which would otherwise paint it.
+ */
+ | {kind: 'buttonDown'}
/** A touch point moved. Coordinates are client-space, like the origin. */
| {kind: 'move'; x: number; y: number}
| {kind: 'up'}
@@ -168,6 +183,15 @@ export function pressGestureStep(
timer: 'onset',
};
}
+ if (event.kind === 'buttonDown') {
+ // Nothing can turn a mouse button or a key into a scroll, so there is
+ // nothing to wait for: paint now, as `:active` does on a desktop.
+ return {
+ gesture: {originX: 0, originY: 0, phase: 'buttonHeld'},
+ paint: 'on',
+ timer: null,
+ };
+ }
switch (gesture.phase) {
case 'armed':
@@ -211,6 +235,20 @@ export function pressGestureStep(
}
return {gesture, paint: 'on', timer: null};
+ case 'buttonHeld':
+ // Travel is not a scroll here (a mouse dragged off a button keeps its
+ // `:active` until the button comes up), so only the release ends the
+ // press, with the same fade a finger's release gets.
+ if (event.kind === 'up') {
+ return step(gesture, 'fading', 'fading', 'fade');
+ }
+ // The platform took it (a drag began, the pointer was cancelled): the
+ // paint goes at once, as for a finger.
+ if (event.kind === 'cancel') {
+ return step(gesture, 'dead', 'none', null);
+ }
+ return {gesture, paint: 'on', timer: null};
+
case 'flash':
// The full-strength hold is over; hand it to the same fade a long press
// gets, so both releases leave the same way.