Skip to content

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

TypeScript
63.0 KB
Raw Blame
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
 * @file pressFeedback.test.ts
 * @input pressFeedback.ts, pressGesture.ts and interactionOverlay.stylex.ts
 * @output Unit tests for the DOM half of the touch press model: one delegated
 *   controller, one attribute, and the two properties a per-element hook
 *   would give away — that the paint belongs to the element the finger landed
 *   on and that a list pays nothing per row for it — plus the CSS arms the
 *   attribute drives: the release runs on the machine's own clock
 * @position Testing; validates pressFeedback.ts in jsdom
 */

import * as stylex from '@stylexjs/stylex';
import {readFileSync} from 'node:fs';
import {dirname, join} from 'node:path';
import {fileURLToPath} from 'node:url';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {
  hasReleaseFade,
  readsPressStrength,
  declaresPressPaint,
  rulesDeclaredFor,
  rulesWithSelector,
} from '../__tests__/pressState';
import {reducedMotionFadeConsts} from '../motion/reducedMotion.stylex';
import {interactionOverlayStyles} from './interactionOverlay.stylex';
import {
  installPressFeedback,
  PRESSABLE_ATTRIBUTE,
  PRESSED_ATTRIBUTE,
  pressFadeMs,
} from './pressFeedback';
import {
  isTrackedByGroup,
  pressGroupItemProps,
} from '../privateAttributes/pressGroupItem.stylex';
import {
  PRESS_FADE_MS,
  PRESS_FLASH_MS,
  PRESS_ONSET_MS,
  PRESS_SCROLL_BRAKE_MS,
  PRESS_SLOP_PX,
} from './pressGesture';
import {pointerQuery} from '../gestures/__tests__/pointerQuery';

let release: () => void = () => undefined;
let scroller: HTMLElement;
let rows: HTMLElement[];

function press(
  element: Element,
  type: string,
  x: number,
  y: number,
  pointerType = 'touch',
  timeStamp?: number,
): void {
  const event = new Event(type, {bubbles: true, cancelable: true});
  Object.assign(event, {
    button: 0,
    clientX: x,
    clientY: y,
    pointerId: 1,
    pointerType,
  });
  if (timeStamp != null) {
    Object.defineProperty(event, 'timeStamp', {value: timeStamp});
  }
  element.dispatchEvent(event);
}

const pressedRow = (): number =>
  rows.findIndex(row => row.getAttribute(PRESSED_ATTRIBUTE) === 'on');

function pressable(tag = 'div'): HTMLElement {
  const element = document.createElement(tag);
  element.setAttribute(PRESSABLE_ATTRIBUTE, '');
  return element;
}

/** Make `element` a scroller with content to scroll, as jsdom lays out nothing. */
function makeScroller(element: HTMLElement): void {
  element.style.overflowY = 'auto';
  Object.defineProperty(element, 'clientHeight', {
    configurable: true,
    value: 100,
  });
  Object.defineProperty(element, 'scrollHeight', {
    configurable: true,
    value: 400,
  });
}
/**
 * The primary pointer is coarse (a phone, a tablet) until the returned
 * restore runs: jsdom's matchMedia models a desktop, where touch work stays
 * off (`spec:AST-094` FR19).
 */
function coarsePrimaryPointer(): () => void {
  const matchMedia = window.matchMedia;
  window.matchMedia = (query: string) => ({
    ...matchMedia(query),
    matches: query.includes('(pointer: coarse)') || matchMedia(query).matches,
  });
  const restore = (): void => {
    window.matchMedia = matchMedia;
  };
  matchMediaRestorers.push(restore);
  return restore;
}

/** Restores every pointer stub a test left, so none leaks into the next. */
const matchMediaRestorers: (() => void)[] = [];

beforeEach(() => {
  vi.useFakeTimers();
  document.body.innerHTML = '';
  scroller = document.createElement('div');
  rows = [];
  for (let index = 0; index < 4; index += 1) {
    const row = pressable();
    const label = document.createElement('span');
    label.textContent = `row ${index}`;
    row.appendChild(label);
    scroller.appendChild(row);
    rows.push(row);
  }
  // The rows sit in a list that scrolls, as on a phone: a finger's press
  // waits the content-touch delay there (`spec:AST-094` FR11).
  makeScroller(scroller);
  document.body.appendChild(scroller);
  release = installPressFeedback();
});

afterEach(() => {
  release();
  vi.useRealTimers();
  for (const restore of matchMediaRestorers.splice(0).reverse()) {
    restore();
  }
});

describe('the press reaches the surface the finger landed on', () => {
  it('keeps native long-press selection on the row and its switch input while a finger is held: the hold does nothing (spec:AST-094 FR41)', () => {
    coarsePrimaryPointer();
    const row = pressable('label');
    const input = document.createElement('input');
    input.type = 'checkbox';
    input.setAttribute('role', 'switch');
    row.appendChild(input);
    document.body.appendChild(row);
    press(input, 'pointerdown', 10, 10);
    vi.advanceTimersByTime(600);
    expect(row.style.getPropertyValue('user-select')).toBe('');
    expect(input.style.getPropertyValue('user-select')).toBe('');
    press(input, 'pointerup', 10, 10);
    expect(row.style.getPropertyValue('user-select')).toBe('');
    expect(input.style.getPropertyValue('user-select')).toBe('');
    // A mouse never locks anything.
    press(input, 'pointerdown', 10, 10, 'mouse');
    expect(row.style.getPropertyValue('user-select')).toBe('');
    press(input, 'pointerup', 10, 10, 'mouse');
  });

  it('writes no selection or callout lock on any surface: a link keeps its native menu and a row its long-press selection (spec:AST-094 FR41)', () => {
    coarsePrimaryPointer();
    // jsdom drops -webkit-touch-callout, so every 'none' write is recorded.
    const written: string[] = [];
    const setProperty = CSSStyleDeclaration.prototype.setProperty;
    const spy = vi
      .spyOn(CSSStyleDeclaration.prototype, 'setProperty')
      .mockImplementation(function (
        this: CSSStyleDeclaration,
        name: string,
        value: string | null,
        priority?: string,
      ) {
        if (value === 'none') {
          written.push(name);
        }
        setProperty.call(this, name, value, priority);
      });
    const link = pressable('a');
    link.setAttribute('href', '/next');
    link.textContent = 'Next';
    document.body.appendChild(link);
    for (const surface of [link, rows[0]]) {
      press(surface, 'pointerdown', 10, 10);
      vi.advanceTimersByTime(600);
      press(surface, 'pointerup', 10, 10);
    }
    expect(written).toEqual([]);
    spy.mockRestore();
  });

  it('keeps selection under a mouse, a pen and a finger where the primary pointer is fine, as on main (spec:AST-094 FR19, spec:AST-017 FR59)', () => {
    const row = rows[2];
    press(row, 'pointerdown', 10, 10, 'mouse');
    vi.advanceTimersByTime(600);
    expect(row.style.getPropertyValue('user-select')).toBe('');
    press(row, 'pointerup', 10, 10, 'mouse');
    // A desktop pen tablet: a fine primary pointer.
    press(row, 'pointerdown', 10, 10, 'pen');
    vi.advanceTimersByTime(600);
    expect(row.style.getPropertyValue('user-select')).toBe('');
    press(row, 'pointerup', 10, 10, 'pen');
    vi.advanceTimersByTime(600);
    // A finger on a touchscreen laptop: the primary pointer is still fine.
    press(row, 'pointerdown', 10, 10);
    vi.advanceTimersByTime(600);
    expect(row.style.getPropertyValue('user-select')).toBe('');
    press(row, 'pointerup', 10, 10);
    vi.advanceTimersByTime(600);
    // On a touch device a pen keeps it too: a row's hold does nothing
    // (spec:AST-094 FR41).
    const restore = coarsePrimaryPointer();
    try {
      press(row, 'pointerdown', 10, 10, 'pen');
      vi.advanceTimersByTime(600);
      expect(row.style.getPropertyValue('user-select')).toBe('');
      press(row, 'pointerup', 10, 10, 'pen');
      expect(row.style.getPropertyValue('user-select')).toBe('');
    } finally {
      restore();
    }
  });

  it('paints the row after the delay, not before', () => {
    const label = rows[1].firstElementChild;
    if (label == null) {
      throw new Error('the row has no label to press');
    }
    press(label, 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS - 1);
    expect(pressedRow()).toBe(-1);
    vi.advanceTimersByTime(1);
    expect(pressedRow()).toBe(1);
  });

  it('keeps the press painted through a drag on a surface that holds its drag, and still ends it on a cancel', () => {
    const row = rows[0];
    row.setAttribute('data-astryx-press-holds-drag', '');
    press(row, 'pointerdown', 10, 10);
    press(row, 'pointermove', 40, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(row.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
    press(row, 'pointermove', 80, 10);
    expect(row.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
    press(row, 'pointercancel', 80, 10);
    expect(row.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
    row.removeAttribute('data-astryx-press-holds-drag');
  });

  it('paints the innermost surface when they nest', () => {
    const bubble = pressable('button');
    rows[2].appendChild(bubble);
    press(bubble, 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(bubble.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
    expect(rows[2].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  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('paints a Space press on a tracked action where the primary pointer is fine: a tracked action takes no `:active` paint', () => {
    expect(window.matchMedia('(pointer: coarse)').matches).toBe(false);
    const button = pressable('button');
    for (const [name, value] of Object.entries(
      pressGroupItemProps(['touch', 'pen']),
    )) {
      button.setAttribute(name, value);
    }
    rows[0].appendChild(button);
    button.focus();
    button.dispatchEvent(
      new KeyboardEvent('keydown', {key: ' ', bubbles: true, cancelable: true}),
    );
    expect(button.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
    button.dispatchEvent(
      new KeyboardEvent('keyup', {key: ' ', bubbles: true, cancelable: true}),
    );
    expect(button.getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
  });

  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);
    press(plain, 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(document.querySelectorAll(`[${PRESSED_ATTRIBUTE}]`)).toHaveLength(0);
  });

  it('paints nothing on a disabled surface, and does not light the row around it', () => {
    const button = pressable('button');
    button.setAttribute('disabled', '');
    rows[1].appendChild(button);
    const ariaDisabled = pressable('button');
    ariaDisabled.setAttribute('aria-disabled', 'true');
    rows[2].appendChild(ariaDisabled);
    press(button, 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    press(button, 'pointerup', 10, 10);
    press(ariaDisabled, 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(document.querySelectorAll(`[${PRESSED_ATTRIBUTE}]`)).toHaveLength(0);
  });
});

describe('an action group whose own tracker paints its actions', () => {
  // The group's tracker follows a held pointer across its actions and paints
  // them. The controller must not write the press attribute there too.
  function group(): {actions: HTMLElement[]; field: HTMLElement} {
    const root = document.createElement('div');
    const actions = [pressable('button'), pressable('button')];
    for (const action of actions) {
      for (const [name, value] of Object.entries(
        pressGroupItemProps(['touch', 'pen']),
      )) {
        action.setAttribute(name, value);
      }
      root.appendChild(action);
    }
    // A member the tracker skips (a menu trigger) carries no marker.
    const field = pressable('button');
    root.appendChild(field);
    document.body.appendChild(root);
    return {actions, field};
  }

  it('paints nothing on an action its group tracks', () => {
    const {actions} = group();
    expect(isTrackedByGroup(actions[0])).toBe(true);
    press(actions[0], 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    press(actions[0], 'pointerup', 10, 10);
    vi.advanceTimersByTime(PRESS_FLASH_MS);
    expect(actions[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('leaves the paint the group writes on it alone', () => {
    const {actions} = group();
    actions[1].setAttribute(PRESSED_ATTRIBUTE, 'on');
    press(actions[1], 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    press(actions[1], 'pointercancel', 10, 10);
    expect(actions[1].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });

  it('still paints a member the group does not track', () => {
    const {field} = group();
    press(field, 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(field.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });

  it('still records the touch, so a scroll it drives brakes the next one', () => {
    const {actions} = group();
    scroller.appendChild(actions[0].parentElement as HTMLElement);
    press(actions[0], 'pointerdown', 10, 10);
    // The browser takes the touch to scroll: the cancel records nothing, so
    // the touch-down alone must have recorded the finger.
    press(actions[0], 'pointercancel', 10, 10);
    scroller.dispatchEvent(new Event('scroll'));
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS * 2);
    expect(pressedRow()).toBe(-1);
  });
});

describe('a scroll takes it away and nothing brings it back', () => {
  it('clears on a scroll from the ancestor scroller', () => {
    press(rows[1], 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(1);
    scroller.dispatchEvent(new Event('scroll'));
    expect(pressedRow()).toBe(-1);
  });

  it('clears on `pointercancel`, which iOS fires before the first scroll event', () => {
    press(rows[1], 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    press(rows[1], 'pointercancel', 10, 10);
    expect(pressedRow()).toBe(-1);
  });

  it('does not repaint a later row while the finger stays down', () => {
    // The list scrolls under a stationary finger and the paint would walk
    // down it, because `:active` outlived the scroll on a node a virtualized
    // list had already recycled.
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    scroller.dispatchEvent(new Event('scroll'));
    for (let y = 100; y < 400; y += 20) {
      press(rows[3], 'pointermove', 10, y);
      scroller.dispatchEvent(new Event('scroll'));
      vi.advanceTimersByTime(16);
    }
    press(rows[3], 'pointerup', 10, 400);
    vi.advanceTimersByTime(PRESS_ONSET_MS + PRESS_FADE_MS);
    expect(rows.some(row => row.hasAttribute(PRESSED_ATTRIBUTE))).toBe(false);
  });

  it('paints nothing at all when the scroller claims inside the delay (a fling)', () => {
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(30);
    press(rows[1], 'pointercancel', 10, 80);
    vi.advanceTimersByTime(PRESS_ONSET_MS * 2);
    expect(pressedRow()).toBe(-1);
  });

  it('hears the NEXT press, once the scrolling finger is up', () => {
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    press(rows[1], 'pointermove', 10, 400);
    press(rows[1], 'pointerup', 10, 400);

    press(rows[2], 'pointerdown', 10, 420);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(2);
  });

  it('hears the next press after a scroll that ended in `pointercancel`', () => {
    // A scroll-claimed gesture ends in `pointercancel`, never `pointerup`:
    // that is the shape a real flick has.
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    press(rows[1], 'pointercancel', 10, 100);
    vi.advanceTimersByTime(PRESS_SCROLL_BRAKE_MS + 10);

    press(rows[2], 'pointerdown', 10, 420);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(2);
  });

  it('is a brake, not a press, when it lands on a list that is still moving', () => {
    // Measured on iOS: a touch stopping a decelerating list highlights
    // nothing. Nothing else would cancel this press, because stopping the
    // scroll is what makes the scroll events stop.
    press(rows[0], 'pointerdown', 10, 10);
    press(rows[0], 'pointerup', 10, 10);
    scroller.dispatchEvent(new Event('scroll'));
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS * 2);
    expect(pressedRow()).toBe(-1);
  });

  it('presses normally once the list has come to rest', () => {
    press(rows[0], 'pointerdown', 10, 10);
    press(rows[0], 'pointerup', 10, 10);
    scroller.dispatchEvent(new Event('scroll'));
    vi.advanceTimersByTime(PRESS_SCROLL_BRAKE_MS + 10);
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(1);
  });

  it('a PROGRAMMATIC scroll does not swallow the press', () => {
    // Apps scroll things by themselves constantly: a pane pinned to the bottom
    // scrolls on every streamed frame, keyboard nav calls `scrollIntoView`, a
    // route change restores a position. None of those is a finger braking
    // anything.
    scroller.dispatchEvent(new Event('scroll'));
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(1);
  });

  it('a touch elsewhere does not make a programmatic scroll a brake', () => {
    // "Any finger anywhere, recently" is not enough: tap a control, then press
    // a button inside a pane that is scrolling on its own. No finger drove
    // that scroll, so the press stands.
    const elsewhere = document.createElement('button');
    document.body.appendChild(elsewhere);
    press(elsewhere, 'pointerdown', 10, 500);
    press(elsewhere, 'pointerup', 10, 500);
    scroller.dispatchEvent(new Event('scroll'));
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(1);
  });

  it('a MOUSE release does not count as a finger for the brake', () => {
    // A device can report a coarse pointer and still have a trackpad; a mouse
    // release inside the scroller must not make the next scroll there look
    // finger-driven.
    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(pressedRow()).toBe(1);
  });

  it('a scroll in ANOTHER scroller does not swallow the press', () => {
    const elsewhere = document.createElement('div');
    document.body.appendChild(elsewhere);
    press(rows[0], 'pointerdown', 10, 10);
    press(rows[0], 'pointerup', 10, 10);
    elsewhere.dispatchEvent(new Event('scroll', {bubbles: false}));
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(1);
  });

  it('clears when the finger travels past the slop, before any scroll event', () => {
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    press(rows[1], 'pointermove', 10, 100 + PRESS_SLOP_PX + 1);
    expect(pressedRow()).toBe(-1);
  });

  it('clears when a drag starts from the pressed element', () => {
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    rows[1].dispatchEvent(new Event('dragstart', {bubbles: true}));
    expect(pressedRow()).toBe(-1);
  });
});

describe('a finger waits only inside a scroller (spec:AST-094 FR11)', () => {
  it('outside a scroller, paints in the frame the finger lands', () => {
    const control = pressable('button');
    document.body.appendChild(control);
    press(control, 'pointerdown', 10, 10);
    expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });

  it('inside a scroller, waits the content-touch delay', () => {
    const control = pressable('button');
    scroller.appendChild(control);
    press(control, 'pointerdown', 10, 10);
    expect(control.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });

  it("counts the content-touch delay from the touch's own timestamp, so a listener that runs late still paints on time", () => {
    const control = pressable('button');
    scroller.appendChild(control);
    // The page has run a while, so the touch's time is past zero.
    vi.advanceTimersByTime(1000);
    // A busy main thread runs the listener 60 ms after the touch.
    press(control, 'pointerdown', 10, 10, 'touch', performance.now() - 60);
    vi.advanceTimersByTime(PRESS_ONSET_MS - 60 - 1);
    expect(control.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
    vi.advanceTimersByTime(1);
    expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });

  it('paints at once when the listener runs later than the content-touch delay', () => {
    const control = pressable('button');
    scroller.appendChild(control);
    vi.advanceTimersByTime(1000);
    press(
      control,
      'pointerdown',
      10,
      10,
      'touch',
      performance.now() - PRESS_ONSET_MS - 40,
    );
    vi.advanceTimersByTime(0);
    expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });

  it('waits the whole delay for a touch with no time, a time ahead of now, or an epoch time taken now', () => {
    vi.advanceTimersByTime(1000);
    const stamps = [() => 0, () => performance.now() + 500, () => Date.now()];
    for (const stamp of stamps) {
      const control = pressable('button');
      scroller.appendChild(control);
      press(control, 'pointerdown', 10, 10, 'touch', stamp());
      vi.advanceTimersByTime(PRESS_ONSET_MS - 1);
      expect(control.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
      vi.advanceTimersByTime(1);
      expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
      press(control, 'pointerup', 10, 10, 'touch');
      vi.advanceTimersByTime(PRESS_FADE_MS * 2);
      control.remove();
    }
  });

  it("keeps an epoch stamp's age, as the long-press hold does", () => {
    const control = pressable('button');
    scroller.appendChild(control);
    vi.advanceTimersByTime(1000);
    // jsdom stamps an event with Date.now(); this touch is 60 ms old.
    press(control, 'pointerdown', 10, 10, 'touch', Date.now() - 60);
    vi.advanceTimersByTime(PRESS_ONSET_MS - 60 - 1);
    expect(control.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
    vi.advanceTimersByTime(1);
    expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });

  it('is cancelled by travel past the slop, with no fade', () => {
    const control = pressable('button');
    document.body.appendChild(control);
    press(control, 'pointerdown', 10, 10);
    press(control, 'pointermove', 10, 10 + PRESS_SLOP_PX + 1);
    expect(control.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('slotted into a scroller inside a shadow tree, waits the content-touch delay', () => {
    // The browser scrolls the flat tree: a slotted pressable sits in the
    // shadow tree's scroller, not beside it in the light tree.
    const host = document.createElement('div');
    const shadowScroller = document.createElement('div');
    makeScroller(shadowScroller);
    shadowScroller.appendChild(document.createElement('slot'));
    host.attachShadow({mode: 'open'}).appendChild(shadowScroller);
    const control = pressable('button');
    host.appendChild(control);
    document.body.appendChild(host);
    expect(control.assignedSlot).not.toBeNull();
    press(control, 'pointerdown', 10, 10);
    expect(control.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });

  it('in a fixed bar above a scrolling list, paints in the frame the finger lands', () => {
    const bar = document.createElement('div');
    bar.style.position = 'fixed';
    const control = pressable('button');
    bar.appendChild(control);
    scroller.appendChild(bar);
    press(control, 'pointerdown', 10, 10);
    expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });

  it('fades at the lift, then leaves no attribute behind', () => {
    const control = pressable('button');
    document.body.appendChild(control);
    press(control, 'pointerdown', 10, 10);
    press(control, 'pointerup', 10, 10);
    expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
    vi.advanceTimersByTime(PRESS_FADE_MS);
    expect(control.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('a menu row in a menu that cannot scroll highlights at once (DEC-14)', () => {
    // A menu whose rows fit: overflow set, but nothing to scroll.
    const menu = document.createElement('div');
    menu.setAttribute('role', 'menu');
    menu.style.overflowY = 'auto';
    Object.defineProperty(menu, 'clientHeight', {
      configurable: true,
      value: 200,
    });
    Object.defineProperty(menu, 'scrollHeight', {
      configurable: true,
      value: 200,
    });
    const row = pressable('div');
    row.setAttribute('role', 'menuitem');
    menu.appendChild(row);
    document.body.appendChild(menu);
    press(row, 'pointerdown', 10, 10);
    expect(row.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });

  it('a menu row in a menu that can scroll waits the content-touch delay (DEC-14)', () => {
    const menu = document.createElement('div');
    menu.setAttribute('role', 'menu');
    makeScroller(menu);
    const row = pressable('div');
    row.setAttribute('role', 'menuitem');
    menu.appendChild(row);
    document.body.appendChild(menu);
    press(row, 'pointerdown', 10, 10);
    expect(row.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(row.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });
});

describe('the release clock without a theme', () => {
  it("is the exit duration token's default, 175 ms (spec:AST-094 FR5)", () => {
    expect(PRESS_FADE_MS).toBe(175);
  });
});

describe('the release clock on the pressed element', () => {
  afterEach(() => {
    document.body.replaceChildren();
  });

  /** An element with `tokens` set on it, in the document. */
  function pressed(tokens: Record<string, string> = {}): HTMLElement {
    const element = document.createElement('div');
    for (const [name, value] of Object.entries(tokens)) {
      element.style.setProperty(name, value);
    }
    document.body.appendChild(element);
    return element;
  }

  it('reads --duration-exit where the element is, a zero included', () => {
    expect(pressFadeMs(pressed({'--duration-exit': '250ms'}))).toBe(250);
    expect(pressFadeMs(pressed({'--duration-exit': '0ms'}))).toBe(0);
  });

  it("gives the token's default for no value or a value that is not a time", () => {
    expect(pressFadeMs(pressed())).toBe(PRESS_FADE_MS);
    expect(pressFadeMs(pressed({'--duration-exit': 'fast'}))).toBe(
      PRESS_FADE_MS,
    );
  });
});

/** The Reduce Motion fade, ms: the longest a finger's release plays there. */
const REDUCED_FADE_MS = Number.parseFloat(reducedMotionFadeConsts.duration);

/** Stubs `prefers-reduced-motion: reduce` on; `vi.unstubAllGlobals` undoes it. */
function stubReducedMotion(): void {
  vi.stubGlobal(
    'matchMedia',
    (query: string): MediaQueryList =>
      ({
        matches: /prefers-reduced-motion:\s*reduce/.test(query),
        media: query,
        onchange: null,
        addListener: () => undefined,
        removeListener: () => undefined,
        addEventListener: () => undefined,
        removeEventListener: () => undefined,
        dispatchEvent: () => false,
      }) as MediaQueryList,
  );
}

/** Declares `css` for the test's duration and returns the remover. */
function addRules(css: string): () => void {
  const style = document.createElement('style');
  style.textContent = css;
  document.head.appendChild(style);
  return () => style.remove();
}

describe('the release', () => {
  it('fades, then leaves no attribute behind', () => {
    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');
    vi.advanceTimersByTime(PRESS_FADE_MS);
    expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it("plays the theme's exit duration, however a rule sets it (spec:AST-094 FR5)", () => {
    // Browsers inherit the token from the theme; jsdom only reads it where
    // it is declared.
    const remove = addRules('.slow-row { --duration-exit: 333ms; }');
    rows[0].classList.add('slow-row');
    try {
      press(rows[0], 'pointerdown', 10, 10);
      vi.advanceTimersByTime(PRESS_ONSET_MS);
      press(rows[0], 'pointerup', 10, 10);
      vi.advanceTimersByTime(332);
      expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
      vi.advanceTimersByTime(1);
      expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
    } finally {
      rows[0].classList.remove('slow-row');
      remove();
    }
  });

  it('reads an exit duration written in seconds', () => {
    const remove = addRules('.slow-row { --duration-exit: 0.3s; }');
    rows[0].classList.add('slow-row');
    try {
      press(rows[0], 'pointerdown', 10, 10);
      vi.advanceTimersByTime(PRESS_ONSET_MS);
      press(rows[0], 'pointerup', 10, 10);
      vi.advanceTimersByTime(299);
      expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
      vi.advanceTimersByTime(1);
      expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
    } finally {
      rows[0].classList.remove('slow-row');
      remove();
    }
  });

  it("under Reduce Motion a finger's release plays the exit duration, no longer than design:reduced-motion DR2's bound", () => {
    stubReducedMotion();
    const remove = addRules(
      '.slow-row { --duration-exit: 333ms; } .quick-row { --duration-exit: 120ms; }',
    );
    try {
      rows[0].classList.add('slow-row');
      press(rows[0], 'pointerdown', 10, 10);
      vi.advanceTimersByTime(PRESS_ONSET_MS);
      press(rows[0], 'pointerup', 10, 10);
      vi.advanceTimersByTime(REDUCED_FADE_MS - 1);
      expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
      vi.advanceTimersByTime(1);
      expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
      rows[0].classList.replace('slow-row', 'quick-row');
      press(rows[0], 'pointerdown', 10, 10);
      vi.advanceTimersByTime(PRESS_ONSET_MS);
      press(rows[0], 'pointerup', 10, 10);
      vi.advanceTimersByTime(120);
      expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
    } finally {
      rows[0].classList.remove('slow-row', 'quick-row');
      remove();
      vi.unstubAllGlobals();
    }
  });

  it("the stylesheet's release plays the exit tokens, with DR2's bound under Reduce Motion", () => {
    const source = readFileSync(
      join(
        dirname(fileURLToPath(import.meta.url)),
        'interactionOverlay.stylex.ts',
      ),
      'utf8',
    );
    expect(source).toContain(
      "const PRESS_RELEASE_DURATION = durationVars['--duration-exit'];",
    );
    expect(source).toContain(
      "`min(${durationVars['--duration-exit']}, ${reducedMotionFadeConsts.duration})`",
    );
    expect(source).toContain("const RELEASE_EASE = easeVars['--ease-exit'];");
    expect(source).toMatch(
      /'@media \(prefers-reduced-motion: reduce\)': PRESS_RELEASE_DURATION_REDUCED/,
    );
    // No clock of its own: the tokens already follow the theme's tempo.
    expect(source).not.toContain('--_astryx-motion-tempo');
  });

  it('answers a tap too quick for the delay, at the release', () => {
    press(rows[0], 'pointerdown', 10, 10);
    vi.advanceTimersByTime(20);
    press(rows[0], 'pointerup', 10, 10);
    expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
    vi.advanceTimersByTime(PRESS_FLASH_MS);
    expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
    vi.advanceTimersByTime(PRESS_FADE_MS);
    expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });
});

/**
 * A CSS animation as a browser reports it from `getAnimations()` (jsdom runs
 * none): by default the release the stylesheet starts on the surface's
 * `::before` at the `fading` write, still waiting for its first frame.
 * `end()` finishes it; `cancel()` cancels it, as unmounting or restyling the
 * surface does.
 */
function cssAnimation(
  element: Element,
  {
    target = element,
    playState = 'running',
    endTime = PRESS_FADE_MS,
  }: {target?: Element; playState?: string; endTime?: number} = {},
) {
  let end: () => void = () => undefined;
  let cancel: () => void = () => undefined;
  const finished = new Promise<void>((resolve, reject) => {
    end = resolve;
    cancel = () => reject(new DOMException('cancelled', 'AbortError'));
  });
  finished.catch(() => undefined);
  return {
    animation: {
      animationName: 'release',
      playState,
      finished,
      effect: {
        target,
        pseudoElement: '::before',
        getComputedTiming: () => ({endTime}),
      },
    },
    end: () => end(),
    cancel: () => cancel(),
  };
}

/** The animations a browser would report running on `element` and its pseudo-elements. */
function animate(element: Element, animations: ReadonlyArray<object>): void {
  Object.defineProperty(element, 'getAnimations', {
    configurable: true,
    value: () => animations,
  });
}

/** Let the callbacks a finished or cancelled animation queued run. */
async function settled(): Promise<void> {
  for (let i = 0; i < 4; i += 1) {
    await Promise.resolve();
  }
}

/** A finger's held press on the first row, lifted: the release is written. */
function liftHeldPress(): void {
  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');
}

describe('the release ends with its animation, not its clock', () => {
  it('keeps `fading` until the release animation ends, however late a busy main thread let its first frame come', async () => {
    liftHeldPress();
    // 150 ms of script held the main thread after the lift: the release
    // started at the first frame after it, and is still running.
    const release = cssAnimation(rows[0]);
    animate(rows[0], [release.animation]);
    vi.advanceTimersByTime(PRESS_FADE_MS);
    await settled();
    expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
    release.end();
    await settled();
    expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('waits for a release still waiting for its first frame when the clock ran out', async () => {
    liftHeldPress();
    const release = cssAnimation(rows[0], {playState: 'pending'});
    animate(rows[0], [release.animation]);
    vi.advanceTimersByTime(PRESS_FADE_MS * 3);
    await settled();
    expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
    release.end();
    await settled();
    expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('ends when the release animation is cancelled: the surface was unmounted or restyled', async () => {
    liftHeldPress();
    const release = cssAnimation(rows[0]);
    animate(rows[0], [release.animation]);
    vi.advanceTimersByTime(PRESS_FADE_MS);
    release.cancel();
    await settled();
    expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('ends on its clock where no release animation runs: an instant release, a surface without one, or an engine without Web Animations', async () => {
    liftHeldPress();
    animate(rows[0], []);
    vi.advanceTimersByTime(PRESS_FADE_MS);
    await settled();
    expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('waits for a release a component draws inside the surface, on a descendant whose nearest press owner is the surface', async () => {
    liftHeldPress();
    // The box wrapper's `::after` plays the release for the row's press,
    // 50 ms longer than the row's clock.
    const box = document.createElement('span');
    rows[0].append(box);
    const release = cssAnimation(rows[0], {
      target: box,
      endTime: PRESS_FADE_MS + 50,
    });
    animate(rows[0], [release.animation]);
    vi.advanceTimersByTime(PRESS_FADE_MS);
    await settled();
    expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
    release.end();
    await settled();
    expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('waits for no animation that is not this press’s running release: a nested press owner’s (on it or inside it), an endless one, or one already finished', async () => {
    liftHeldPress();
    // A press owner inside the row: its release is its own press's, never
    // the row's.
    const nested = pressable('span');
    const inside = document.createElement('span');
    nested.append(inside);
    rows[0].append(nested);
    animate(rows[0], [
      cssAnimation(rows[0], {target: nested}).animation,
      cssAnimation(rows[0], {target: inside}).animation,
      cssAnimation(rows[0], {endTime: Infinity}).animation,
      cssAnimation(rows[0], {playState: 'finished'}).animation,
    ]);
    vi.advanceTimersByTime(PRESS_FADE_MS);
    await settled();
    expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('a new press on the surface owns its paint: the old release ending later does not clear it', async () => {
    liftHeldPress();
    const release = cssAnimation(rows[0]);
    animate(rows[0], [release.animation]);
    vi.advanceTimersByTime(PRESS_FADE_MS);
    press(rows[0], 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
    release.end();
    await settled();
    expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });
});

describe('two touches in a row', () => {
  it('answers the second tap while the first is still fading', () => {
    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[2], 'pointerdown', 10, 300);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(2);
    expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('paints nothing for a second finger while the first is still down', () => {
    press(rows[0], 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    const second = new Event('pointerdown', {bubbles: true});
    Object.assign(second, {
      clientX: 10,
      clientY: 300,
      pointerId: 2,
      pointerType: 'touch',
    });
    rows[2].dispatchEvent(second);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(rows.some(row => row.hasAttribute(PRESSED_ATTRIBUTE))).toBe(false);
  });
});

describe('a pointerup that matches no held press', () => {
  it('is ignored when it carries no pointerId and nothing is held', () => {
    // The input stream reports a listener's throw through `reportError`.
    const reportError = vi.fn();
    vi.stubGlobal('reportError', reportError);
    try {
      // A page's own drag script or test helper can dispatch a bare event
      // named `pointerup`; a real PointerEvent always has a numeric pointerId.
      document.body.dispatchEvent(new Event('pointerup', {bubbles: true}));
    } finally {
      vi.unstubAllGlobals();
    }
    expect(reportError).not.toHaveBeenCalled();
  });

  it('leaves a held finger press alone', () => {
    const reportError = vi.fn();
    vi.stubGlobal('reportError', reportError);
    coarsePrimaryPointer();
    try {
      // No box component is mounted, so the finger holds a press but no contact.
      press(rows[0], 'pointerdown', 10, 10);
      vi.advanceTimersByTime(PRESS_ONSET_MS);
      document.body.dispatchEvent(new Event('pointerup', {bubbles: true}));
    } finally {
      vi.unstubAllGlobals();
    }
    expect(reportError).not.toHaveBeenCalled();
    expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
  });
});

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("fades a mouse press on the theme's exit duration too (spec:AST-094 FR5)", () => {
    const remove = addRules('.slow-row { --duration-exit: 333ms; }');
    rows[1].classList.add('slow-row');
    try {
      press(rows[1], 'pointerdown', 10, 100, 'mouse');
      press(rows[1], 'pointerup', 10, 100, 'mouse');
      vi.advanceTimersByTime(332);
      expect(rows[1].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
      vi.advanceTimersByTime(1);
      expect(rows[1].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
    } finally {
      rows[1].classList.remove('slow-row');
      remove();
    }
  });

  function groupAction(
    row: HTMLElement,
    pointerTypes: ReadonlyArray<string> = ['touch', 'pen'],
  ): HTMLButtonElement {
    const action = focusedButton(row);
    for (const [name, value] of Object.entries(
      pressGroupItemProps(pointerTypes),
    )) {
      action.setAttribute(name, value);
    }
    return action;
  }

  it('leaves a mouse press to a tracker that follows a mouse: it paints its own action', () => {
    const action = groupAction(rows[1], ['mouse', 'pen', 'touch']);
    press(action, 'pointerdown', 10, 100, 'mouse');
    expect(action.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
    press(action, 'pointerup', 10, 100, 'mouse');
    expect(action.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('paints a mouse press on an action whose tracker follows a finger and a pen only: that tracker takes no mouse press', () => {
    const action = groupAction(rows[1]);
    press(action, 'pointerdown', 10, 100, 'mouse');
    expect(action.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
    press(action, 'pointerup', 10, 100, 'mouse');
    expect(action.getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
  });

  it('still paints a Space press on a focused action its group tracks: the group tracks pointers only', () => {
    const action = groupAction(rows[1]);
    key(action, 'keydown');
    expect(action.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
    key(action, 'keyup');
    expect(action.getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
  });

  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
  // touching.

  it('a finger jittering inside the slop still gets its press', () => {
    // Every real finger produces `pointermove` during the 150 ms delay; only
    // a synthetic touch holds perfectly still.
    press(rows[1], 'pointerdown', 10, 100);
    for (let tick = 0; tick < 6; tick += 1) {
      vi.advanceTimersByTime(20);
      press(rows[1], 'pointermove', 10 + (tick % 2), 100 + (tick % 3));
    }
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(1);
  });

  it("a cancel inside a quick tap's flash still resolves to nothing", () => {
    // iOS Safari delivers `touchcancel` at `scrollend`, seconds after a tap,
    // so this is the common shape, not a corner case.
    press(rows[0], 'pointerdown', 10, 10);
    vi.advanceTimersByTime(20);
    press(rows[0], 'pointerup', 10, 10);
    expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');

    press(rows[0], 'pointercancel', 10, 10);
    vi.advanceTimersByTime(PRESS_FLASH_MS + PRESS_FADE_MS + 50);
    expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('a scroll inside the release fade still resolves to nothing', () => {
    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');

    scroller.dispatchEvent(new Event('scroll'));
    vi.advanceTimersByTime(PRESS_FADE_MS + 50);
    expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
  });

  it('leaves nothing painted after any of the gestures a finger can produce', () => {
    // The guard for the whole class: whatever the sequence, once it is over
    // and every clock has run out, the list is bare.
    const gestures: (() => void)[] = [
      () => {
        press(rows[0], 'pointerdown', 10, 10);
        press(rows[0], 'pointerup', 10, 10);
        press(rows[0], 'pointercancel', 10, 10);
      },
      () => {
        press(rows[1], 'pointerdown', 10, 100);
        vi.advanceTimersByTime(PRESS_ONSET_MS);
        press(rows[1], 'pointerup', 10, 100);
        scroller.dispatchEvent(new Event('scroll'));
      },
      () => {
        press(rows[2], 'pointerdown', 10, 200);
        vi.advanceTimersByTime(40);
        press(rows[2], 'pointermove', 10, 260);
        press(rows[2], 'pointercancel', 10, 260);
      },
      () => {
        press(rows[3], 'pointerdown', 10, 300);
        vi.advanceTimersByTime(PRESS_ONSET_MS);
        scroller.dispatchEvent(new Event('scroll'));
        press(rows[3], 'pointerup', 10, 300);
      },
      () => {
        press(rows[0], 'pointerdown', 10, 10);
        vi.advanceTimersByTime(PRESS_ONSET_MS);
        Object.defineProperty(document, 'visibilityState', {
          configurable: true,
          value: 'hidden',
        });
        document.dispatchEvent(new Event('visibilitychange'));
        Object.defineProperty(document, 'visibilityState', {
          configurable: true,
          value: 'visible',
        });
      },
    ];
    for (const gesture of gestures) {
      gesture();
      vi.advanceTimersByTime(
        PRESS_ONSET_MS + PRESS_FLASH_MS + PRESS_FADE_MS + 100,
      );
      expect(document.querySelectorAll(`[${PRESSED_ATTRIBUTE}]`)).toHaveLength(
        0,
      );
    }
  });
});

describe('what the list pays for it', () => {
  it('adds no listener to any row', () => {
    const row = pressable();
    const added: string[] = [];
    row.addEventListener = ((type: string) =>
      added.push(type)) as typeof row.addEventListener;
    scroller.appendChild(row);
    press(row, 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(added).toEqual([]);
  });

  it('registers no touch listener on the window or the document where the primary pointer is fine (spec:AST-094 FR24)', () => {
    release();
    matchMediaRestorers.push(pointerQuery(false).restore);
    const added = [
      vi.spyOn(window, 'addEventListener'),
      vi.spyOn(document, 'addEventListener'),
    ];
    try {
      release = installPressFeedback();
      // A finger lands, as on a touchscreen laptop: still none.
      press(rows[0], 'pointerdown', 10, 10);
      press(rows[0], 'pointerup', 10, 10);
      const types = added.flatMap(spy => spy.mock.calls.map(([type]) => type));
      expect(types.filter(type => type.startsWith('touch'))).toEqual([]);
      expect(types).toContain('pointerdown');
    } finally {
      for (const spy of added) {
        spy.mockRestore();
      }
    }
  });

  it('asks no media query when it installs: a page no one touches never reads the pointer', () => {
    release();
    const matchMedia = vi.spyOn(window, 'matchMedia');
    try {
      release = installPressFeedback();
      expect(matchMedia).not.toHaveBeenCalled();
    } finally {
      matchMedia.mockRestore();
    }
  });

  it('hears touchcancel only while the primary pointer is coarse, and follows it', () => {
    release();
    const pointer = pointerQuery(false);
    matchMediaRestorers.push(pointer.restore);
    release = installPressFeedback();
    // A tablet undocks its mouse: the browser's touchcancel ends a press.
    pointer.set(true);
    press(rows[0], 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(0);
    window.dispatchEvent(new Event('touchcancel'));
    expect(pressedRow()).toBe(-1);
    // It docks one again: the touch listener comes down.
    pointer.set(false);
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(1);
    window.dispatchEvent(new Event('touchcancel'));
    expect(pressedRow()).toBe(1);
  });

  it('installs once, however many times it is called, and stays while any holder remains', () => {
    const second = installPressFeedback();
    press(rows[0], 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(0);
    press(rows[0], 'pointerup', 10, 10);
    vi.advanceTimersByTime(PRESS_FADE_MS);
    second();
    // The first holder (beforeEach) is still there: presses are still heard.
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(1);
  });

  it('comes down with the last holder, taking any paint with it', () => {
    press(rows[0], 'pointerdown', 10, 10);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(0);
    release();
    expect(pressedRow()).toBe(-1);
    press(rows[1], 'pointerdown', 10, 100);
    vi.advanceTimersByTime(PRESS_ONSET_MS);
    expect(pressedRow()).toBe(-1);
    // Re-install for afterEach's release.
    release = installPressFeedback();
  });
});

describe('the release fades: the arms the controller writes to', () => {
  // The CSS half of the model, asserted off the StyleX dev runtime's injected
  // rules the way the component tests do. jsdom runs no animation, so what is
  // held here is the declaration: which arm animates, on which clock, and
  // what the paint reads.
  const variants = [
    'backgroundColor',
    'backgroundImage',
    'backgroundImageOnNeutral',
    'pressedBackgroundColor',
  ] as const;

  function surface(
    style: (typeof interactionOverlayStyles)[keyof typeof interactionOverlayStyles],
  ): HTMLElement {
    const element = pressable('button');
    element.className = stylex.props(style).className ?? '';
    document.body.appendChild(element);
    return element;
  }

  it("runs the release animation on the fading arm, for the machine's clock, on every variant", () => {
    for (const variant of variants) {
      expect(
        hasReleaseFade(surface(interactionOverlayStyles[variant])),
        variant,
      ).toBe(true);
    }
    expect(hasReleaseFade(surface(interactionOverlayStyles.pressedAlpha))).toBe(
      true,
    );
  });

  it("without a theme, the stylesheet's release resolves to the machine's clock: the exit token's default", () => {
    expect(hasReleaseFade(surface(interactionOverlayStyles.pressedAlpha))).toBe(
      true,
    );
  });

  it("declares the press's paint at its strength on every variant, the one place the formula lives", () => {
    for (const variant of variants) {
      expect(
        declaresPressPaint(surface(interactionOverlayStyles[variant])),
        variant,
      ).toBe(true);
    }
    expect(
      declaresPressPaint(surface(interactionOverlayStyles.pressedAlpha)),
    ).toBe(true);
  });

  it("paints both touch arms as the pressed token at the press's strength, and declares the strength 1 on both", () => {
    for (const variant of variants) {
      const element = surface(interactionOverlayStyles[variant]);
      expect(
        readsPressStrength(element, '[data-astryx-press="on"]'),
        variant,
      ).toBe(true);
      expect(readsPressStrength(element), variant).toBe(true);
      // The fading arm declares 1, like the on arm: only the animation moves
      // the strength, so nothing a composer transitions changes at the lift.
      for (const arm of [
        '[data-astryx-press="on"]',
        '[data-astryx-press="fading"]',
      ]) {
        expect(
          rulesWithSelector(element, arm).some(rule =>
            /--astryx-press-alpha:\s*1\b/.test(rule),
          ),
          `${variant} ${arm}`,
        ).toBe(true);
      }
      // ...and lands on nothing, not on the hover strength: under a finger
      // there is no hover.
      expect(
        rulesWithSelector(element, '[data-astryx-press="fading"]').some(rule =>
          rule.includes('--color-overlay-hover'),
        ),
        variant,
      ).toBe(false);
    }
  });

  it('pressedAlpha owns the strength and the release and paints nothing itself', () => {
    const element = surface(interactionOverlayStyles.pressedAlpha);
    expect(
      rulesDeclaredFor(element).some(rule => rule.includes('background')),
    ).toBe(false);
    expect(readsPressStrength(element)).toBe(false);
  });
});