Skip to content

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

TypeScript

fix(core): a button's touch press release runs on the compositor (#9783)

Cindy Zhange8ecde4ff82d
diff --git a/.changeset/press-release-compositor.md b/.changeset/press-release-compositor.md
new file mode 100644
index 0000000000..42c64c815a
--- /dev/null
+++ b/.changeset/press-release-compositor.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Under a coarse primary pointer (a touch screen as the main input), a button's touch press release now runs on the compositor. It keeps fading while the page's script is busy, instead of freezing at full strength and snapping off, and it paints nothing per frame. The release keeps the theme's exit motion timing. With any other pointer, a finger on a touch screen beside a mouse included, nothing changes. Under a coarse primary pointer, while a press is on or fading, Button paints it on its own `::before` and sets `isolation: isolate`. At rest it adds neither, so a `::before` you style, through `xstyle` or a `className` rule, merges into that layer only during a press. Style a child element to keep it unchanged.
+
+@vjeux
diff --git a/docs/specs/components/Button/Button.spec.md b/docs/specs/components/Button/Button.spec.md
index e19ef3c678..35ebe25d01 100644
--- a/docs/specs/components/Button/Button.spec.md
+++ b/docs/specs/components/Button/Button.spec.md
@@ -116,25 +116,25 @@ Consumer migration instructions belong in consumer docs and release notes.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
-| FR1 | Without link mode Button renders one native `<button>` with `type="button"` unless `type` says otherwise; `name`, `value`, and `form` reach that element. | `family:buttons` FR2; current source and tests |
-| FR2 | Content renders in this order: the leading `icon` slot, the label text (`children` when supplied, else `label`), then `endContent`. Icon-only renders the icon alone and omits the label text and `endContent`. `endContent` inherits the Button's text color. | `family:buttons` AV2; current source and tests |
-| FR3 | An Astryx Icon in the `icon` slot without an explicit size renders `sm` in `sm` and `md` Buttons and `md` in `lg` Buttons; an explicit Icon size wins. | `family:buttons` FR7; current source |
-| FR4 | Height comes from the shared element size for the resolved size, as a minimum that grows with a set text size under `spec:AST-102` FR4 (today's fixed height is a gap): an explicit `size` wins, then the nearest size provider, then `md`. Icon-only is square (`--button-icon-only-aspect`, default `1 / 1`) with no padding. | `family:buttons` FR7; `architecture:component-size-cascade` INV3–INV5 |
-| FR5 | The label stays on one line. A labelled Button may shrink in a row, never exceeds its container's inline size, and truncates the label with an ellipsis. An explicit `width` applies in button and link modes and is still capped at the container. Icon-only does not shrink and is not capped. | Current source and tests |
-| FR6 | On activation `onClick` runs first. If it calls `preventDefault()`, `clickAction` does not run. Otherwise `clickAction` runs, and the Button is pending until its promise settles. | `family:buttons` FR5; current source and tests |
-| FR7 | A fire-once `clickAction` runs once per in-flight action: a second activation while it is pending, including a same-tick double-click, does nothing. With `isInterruptible`, a pending Button stays operable and each activation starts a new `clickAction`. | `family:buttons` FR5; current source and tests |
-| FR8 | While pending, Button sets `aria-busy="true"`, hides its content from assistive technology, makes content that takes the Button's text color transparent while it keeps its place in layout, and centers a small Spinner in the inherited foreground color over it. Outer size does not change. On a Button that is not interruptible and has no action pending, explicit `isLoading` hides the content and shows the Spinner at once. For a pending `clickAction`, or any pending state on an interruptible Button, the content stays painted and the content hide and the Spinner reveal both wait the medium motion delay, so a fast action never flashes a Spinner or an empty Button. The Spinner fades in over the fast duration. Under reduced motion there is no delay, and with a fine pointer the Spinner MUST appear at once (`design:reduced-motion` DR3). `aria-busy` is set at once in every case. Implementation gap: under reduced motion the Spinner still fades in over the fast duration with every pointer. Implementation gap: content that paints its own colors, such as a Badge in `endContent`, stays visible beside the Spinner. | `family:buttons` FR4; current source and tests |
-| FR9 | Busy-only (pending, not disabled, not interruptible): Button exposes `aria-disabled="true"`, keeps its tab stop, renders no native `disabled`, and keeps full opacity. Pointer activation is cancelled and does not reach ancestor click handlers; Enter and Space are suppressed; other keys still reach the caller's `onKeyDown`. A link-mode Button stays a link while busy-only. | `spec:AST-085` FR1, FR2, FR6; current source and tests |
-| FR10 | Disabled (`isDisabled`, or a disabled enclosing ButtonGroup) MUST stay focusable with `aria-disabled="true"`, keep its tab stop and focus, apply FR9's guards, never run `onClick` or `clickAction`, and paint at half opacity. Disabled wins over pending: a disabled, loading Button shows the Spinner and `aria-busy` but follows this row. Implementation gap: only a disabled Button with a `tooltip` renders this shape; without a tooltip it renders native `disabled`, which removes it from the tab order and drops focus when it becomes disabled. | `family:buttons` FR3; `spec:AST-085`; current source and tests |
-| FR11 | With `href` and not disabled, Button renders the link component resolved from `as`, then `LinkProvider`, then a native anchor, with `target` and `rel`, full button styling, and no text decoration. Destination handling follows `family:navigation-destinations`. A disabled Button with `href` renders a `<button>` that follows FR10 and never navigates. Implementation gap: a focused link Button that becomes disabled is replaced by that new `<button>`, so focus falls to the page with or without a `tooltip`; without a `tooltip` the `<button>` also carries native `disabled` (FR10). | `family:navigation-destinations` FR1–FR7; current source and tests |
-| FR12 | With `tooltip`, the tooltip attaches to the Button element itself (no wrapper element), opens above it, and its content is added to `aria-describedby` after any caller value, unless its trimmed text equals the Button's accessible name as its props decide it (the derived or caller `aria-label`, or `label` when `icon` and `endContent` render nothing or a decorative Icon), as Avatar AR5 does, so a tooltip that repeats the name is not read twice. When the name comes from elsewhere (`aria-labelledby`, or other content in `icon` or `endContent`), the tooltip still describes the Button. IconButton inherits this. | Current source; real-browser accessibility test |
-| FR13 | A standalone Button paints the shadow token for its `elevation`. Inside a ButtonGroup it paints no shadow and reflects `data-elevation="none"`, whatever `elevation` says. | `family:buttons` FR8–FR10; current source and tests |
-| FR14 | The root carries `astryx-button` and reflects the effective `data-variant`, `data-size`, and `data-elevation`. | `family:buttons` FR10; `architecture:component-theming-surface`; tests |
-| FR15 | Hover paints the shared interaction overlay on hover-capable pointers, and a press paints the shared pressed overlay through the press controller: at once under a mouse or a pen (`spec:AST-094` FR11's fine-pointer profile) and on FR11's control profile under a finger, fading out on release on the theme's exit motion tokens (`--duration-exit`, `--ease-exit`; `spec:AST-094` FR5). Without a reduced-motion preference, a standalone Button also scales to 0.98 on a mouse press, or while the touch press reads on; under reduced motion it MUST NOT scale (`design:reduced-motion` DR1). All of this paint follows the element's exposed disabled state: a Button that is natively disabled or exposes `aria-disabled="true"` (busy-only, disabled with a tooltip, or a caller's own `aria-disabled`) shows no overlay and no press scale, even when it stays operable. Inside a ButtonGroup the press scale does not apply. Button's hover and press transitions are fast, and instant under reduced motion. | Current source and tests; `spec:AST-094` FR11 and DEC-21 for the mouse and pen press |
-| FR16 | The ghost variant carries the edge-compensation marker so an enclosing container can align it flush with its edge; other variants do not. | Current source; edge-compensation tests |
-| FR17 | `ref`, `className`, `style`, `xstyle`, and other DOM props reach the root element. A caller's own `aria-busy` and `aria-disabled` are kept beside Button's own (either one sets the attribute); a caller `aria-disabled` changes exposure and paint only and does not make the Button inert. The tooltip trigger shares the caller's `ref`, which stays attached across rerenders. | Current source and tests |
+| ID | Invariant | Basis |
+| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
+| FR1 | Without link mode Button renders one native `<button>` with `type="button"` unless `type` says otherwise; `name`, `value`, and `form` reach that element. | `family:buttons` FR2; current source and tests |
+| FR2 | Content renders in this order: the leading `icon` slot, the label text (`children` when supplied, else `label`), then `endContent`. Icon-only renders the icon alone and omits the label text and `endContent`. `endContent` inherits the Button's text color. | `family:buttons` AV2; current source and tests |
+| FR3 | An Astryx Icon in the `icon` slot without an explicit size renders `sm` in `sm` and `md` Buttons and `md` in `lg` Buttons; an explicit Icon size wins. | `family:buttons` FR7; current source |
+| FR4 | Height comes from the shared element size for the resolved size, as a minimum that grows with a set text size under `spec:AST-102` FR4 (today's fixed height is a gap): an explicit `size` wins, then the nearest size provider, then `md`. Icon-only is square (`--button-icon-only-aspect`, default `1 / 1`) with no padding. | `family:buttons` FR7; `architecture:component-size-cascade` INV3–INV5 |
+| FR5 | The label stays on one line. A labelled Button may shrink in a row, never exceeds its container's inline size, and truncates the label with an ellipsis. An explicit `width` applies in button and link modes and is still capped at the container. Icon-only does not shrink and is not capped. | Current source and tests |
+| FR6 | On activation `onClick` runs first. If it calls `preventDefault()`, `clickAction` does not run. Otherwise `clickAction` runs, and the Button is pending until its promise settles. | `family:buttons` FR5; current source and tests |
+| FR7 | A fire-once `clickAction` runs once per in-flight action: a second activation while it is pending, including a same-tick double-click, does nothing. With `isInterruptible`, a pending Button stays operable and each activation starts a new `clickAction`. | `family:buttons` FR5; current source and tests |
+| FR8 | While pending, Button sets `aria-busy="true"`, hides its content from assistive technology, makes content that takes the Button's text color transparent while it keeps its place in layout, and centers a small Spinner in the inherited foreground color over it. Outer size does not change. On a Button that is not interruptible and has no action pending, explicit `isLoading` hides the content and shows the Spinner at once. For a pending `clickAction`, or any pending state on an interruptible Button, the content stays painted and the content hide and the Spinner reveal both wait the medium motion delay, so a fast action never flashes a Spinner or an empty Button. The Spinner fades in over the fast duration. Under reduced motion there is no delay, and with a fine pointer the Spinner MUST appear at once (`design:reduced-motion` DR3). `aria-busy` is set at once in every case. Implementation gap: under reduced motion the Spinner still fades in over the fast duration with every pointer. Implementation gap: content that paints its own colors, such as a Badge in `endContent`, stays visible beside the Spinner. | `family:buttons` FR4; current source and tests |
+| FR9 | Busy-only (pending, not disabled, not interruptible): Button exposes `aria-disabled="true"`, keeps its tab stop, renders no native `disabled`, and keeps full opacity. Pointer activation is cancelled and does not reach ancestor click handlers; Enter and Space are suppressed; other keys still reach the caller's `onKeyDown`. A link-mode Button stays a link while busy-only. | `spec:AST-085` FR1, FR2, FR6; current source and tests |
+| FR10 | Disabled (`isDisabled`, or a disabled enclosing ButtonGroup) MUST stay focusable with `aria-disabled="true"`, keep its tab stop and focus, apply FR9's guards, never run `onClick` or `clickAction`, and paint at half opacity. Disabled wins over pending: a disabled, loading Button shows the Spinner and `aria-busy` but follows this row. Implementation gap: only a disabled Button with a `tooltip` renders this shape; without a tooltip it renders native `disabled`, which removes it from the tab order and drops focus when it becomes disabled. | `family:buttons` FR3; `spec:AST-085`; current source and tests |
+| FR11 | With `href` and not disabled, Button renders the link component resolved from `as`, then `LinkProvider`, then a native anchor, with `target` and `rel`, full button styling, and no text decoration. Destination handling follows `family:navigation-destinations`. A disabled Button with `href` renders a `<button>` that follows FR10 and never navigates. Implementation gap: a focused link Button that becomes disabled is replaced by that new `<button>`, so focus falls to the page with or without a `tooltip`; without a `tooltip` the `<button>` also carries native `disabled` (FR10). | `family:navigation-destinations` FR1–FR7; current source and tests |
+| FR12 | With `tooltip`, the tooltip attaches to the Button element itself (no wrapper element), opens above it, and its content is added to `aria-describedby` after any caller value, unless its trimmed text equals the Button's accessible name as its props decide it (the derived or caller `aria-label`, or `label` when `icon` and `endContent` render nothing or a decorative Icon), as Avatar AR5 does, so a tooltip that repeats the name is not read twice. When the name comes from elsewhere (`aria-labelledby`, or other content in `icon` or `endContent`), the tooltip still describes the Button. IconButton inherits this. | Current source; real-browser accessibility test |
+| FR13 | A standalone Button paints the shadow token for its `elevation`. Inside a ButtonGroup it paints no shadow and reflects `data-elevation="none"`, whatever `elevation` says. | `family:buttons` FR8–FR10; current source and tests |
+| FR14 | The root carries `astryx-button` and reflects the effective `data-variant`, `data-size`, and `data-elevation`. | `family:buttons` FR10; `architecture:component-theming-surface`; tests |
+| FR15 | Hover paints the shared interaction overlay on hover-capable pointers, and a press paints the shared pressed overlay through the press controller: at once under a mouse or a pen (`spec:AST-094` FR11's fine-pointer profile) and on FR11's control profile under a finger, fading out on release on the theme's exit motion tokens (`--duration-exit`, `--ease-exit`; `spec:AST-094` FR5). Under a coarse pointer, while a press is on or fading, Button paints the press on its own `::before`; a caller's `::before` styles apply on top of that layer and win where they overlap, so a decoration that must stay through a touch press belongs on a child element. Without a reduced-motion preference, a standalone Button also scales to 0.98 on a mouse press, or while the touch press reads on; under reduced motion it MUST NOT scale (`design:reduced-motion` DR1). All of this paint follows the element's exposed disabled state: a Button that is natively disabled or exposes `aria-disabled="true"` (busy-only, disabled with a tooltip, or a caller's own `aria-disabled`) shows no overlay and no press scale, even when it stays operable. Inside a ButtonGroup the press scale does not apply. Button's hover and press transitions are fast, and instant under reduced motion. | Current source and tests; `spec:AST-094` FR11 and DEC-21 for the mouse and pen press |
+| FR16 | The ghost variant carries the edge-compensation marker so an enclosing container can align it flush with its edge; other variants do not. | Current source; edge-compensation tests |
+| FR17 | `ref`, `className`, `style`, `xstyle`, and other DOM props reach the root element. A caller's own `aria-busy` and `aria-disabled` are kept beside Button's own (either one sets the attribute); a caller `aria-disabled` changes exposure and paint only and does not make the Button inert. The tooltip trigger shares the caller's `ref`, which stays attached across rerenders. | Current source and tests |
### Allowed variation
diff --git a/packages/cli/clients/cli/commands/write-failure.test.mjs b/packages/cli/clients/cli/commands/write-failure.test.mjs
index 39186a3a50..cb4f06cbcf 100644
--- a/packages/cli/clients/cli/commands/write-failure.test.mjs
+++ b/packages/cli/clients/cli/commands/write-failure.test.mjs
@@ -99,6 +99,11 @@ describe.skipIf(asRoot)('a failed write reports ERR_WRITE_FAILED', () => {
});
});
+/** A path as the CLI reports it: relative to the project, with `/`. */
+function fromProject(file) {
+ return path.relative(dir, file).split(path.sep).join('/');
+}
+
describe.skipIf(asRoot)('a swizzle that fails part-way undoes what it wrote', () => {
it('restores replaced files, removes created ones, and says nothing was written', async () => {
// Learn the component's files, in copy order, from a successful swizzle.
@@ -110,10 +115,13 @@ describe.skipIf(asRoot)('a swizzle that fails part-way undoes what it wrote', ()
// The first file exists (replaceable), the middle ones do not, and the
// last one is read-only, so --overwrite fails after writing the others.
+ // The last file can be a carried module beside the component folder
+ // (`../privateAttributes/…`), so its folder is made too.
const first = files[0];
const middle = files.slice(1, -1);
const last = files[files.length - 1];
fs.mkdirSync(outDir, {recursive: true});
+ fs.mkdirSync(path.dirname(path.join(outDir, last)), {recursive: true});
fs.writeFileSync(path.join(outDir, first), 'before first\n');
fs.writeFileSync(path.join(outDir, last), 'before last\n');
fs.chmodSync(path.join(outDir, last), 0o444);
@@ -129,7 +137,7 @@ describe.skipIf(asRoot)('a swizzle that fails part-way undoes what it wrote', ()
expect(status).toBe(1);
expect(body.code).toBe('ERR_WRITE_FAILED');
- expect(body.error).toContain(last);
+ expect(body.error).toContain(fromProject(path.join(outDir, last)));
expect(body.error).toContain('Nothing was written.');
expect(body.error).not.toContain(dir);
expect(fs.readFileSync(path.join(outDir, first), 'utf8')).toBe('before first\n');
@@ -150,6 +158,7 @@ describe.skipIf(asRoot)('a swizzle that fails part-way undoes what it wrote', ()
const first = files[0];
const middle = files.slice(1, -1);
const last = files[files.length - 1];
+ fs.mkdirSync(outDir, {recursive: true});
fs.mkdirSync(path.join(outDir, last), {recursive: true});
fs.writeFileSync(path.join(outDir, first), 'before first\n');
@@ -163,7 +172,7 @@ describe.skipIf(asRoot)('a swizzle that fails part-way undoes what it wrote', ()
expect(status).toBe(1);
expect(body.code).toBe('ERR_WRITE_FAILED');
- expect(body.error).toContain(last);
+ expect(body.error).toContain(fromProject(path.join(outDir, last)));
expect(body.error).toContain('Nothing was written.');
expect(body.error).not.toContain(dir);
expect(fs.readFileSync(path.join(outDir, first), 'utf8')).toBe('before first\n');
diff --git a/packages/core/src/Button/Button.doc.mjs b/packages/core/src/Button/Button.doc.mjs
index d0c7c2eacf..e4659769fb 100644
--- a/packages/core/src/Button/Button.doc.mjs
+++ b/packages/core/src/Button/Button.doc.mjs
@@ -22,6 +22,7 @@ export const docs = {
{guidance: false, description: 'Place more than one primary button in the same view; this dilutes the visual hierarchy.'},
{guidance: false, description: 'Use the destructive variant without a confirmation step for irreversible actions like deleting data.'},
{guidance: false, description: 'Use a button for navigation. If it only takes the user to another page, use a link instead. Buttons are for actions like saving, deleting, or submitting.'},
+ {guidance: false, description: "Restyle Button's `::before` (through `xstyle` or a `className` rule) and expect it to hold through a touch press: under a coarse primary pointer, while a press is on or fading, Button paints the press on that pseudo-element (`z-index: -1`, its opacity animated), so your styles merge into the press layer for that moment. At rest Button adds nothing there. Style a child element instead."},
],
accessibility: [
{
@@ -407,6 +408,7 @@ export const docsDense = {
{guidance: false, description: 'Multiple primary buttons in one view; dilutes hierarchy.'},
{guidance: false, description: 'Destructive without confirmation for irreversible actions.'},
{guidance: false, description: 'Button for navigation; use a link if it only takes the user to another page.'},
+ {guidance: false, description: 'xstyle or className on ::before: under a coarse primary pointer it is the touch press layer while a press is on or fading (z-index -1, opacity animated); nothing at rest.'},
],
},
propDescriptions: {
diff --git a/packages/core/src/Button/Button.test.tsx b/packages/core/src/Button/Button.test.tsx
index e18fa6efea..14d0f82d6e 100644
--- a/packages/core/src/Button/Button.test.tsx
+++ b/packages/core/src/Button/Button.test.tsx
@@ -25,9 +25,12 @@ import {Icon} from '../Icon/Icon';
import * as stylex from '@stylexjs/stylex';
import {
hasPressedArm,
- hasReleaseFade,
- readsPressStrength,
+ keepsPressOutsideCoarse,
+ layerOnlyWhilePressed,
+ releasesOnLayer,
+ showsLayerPress,
} from '../__tests__/pressState';
+import {PRESS_FADE_MS} from '../utils/pressGesture';
import {Badge} from '../Badge/Badge';
import {ButtonGroup} from '../ButtonGroup';
import {InputGroup} from '../InputGroup';
@@ -945,16 +948,32 @@ describe('Button', () => {
});
describe('Button pressed state (touch)', () => {
- it('fades the touch press out over the release, painting the pressed token at its strength on both arms', () => {
+ it('paints the touch press on a compositor layer and releases it on the press clock', () => {
render(<Button label="Save" />);
const button = screen.getByRole('button', {name: 'Save'});
- // The touch arms the controller writes: `on` paints the pressed token at
- // strength 1 on the first frame; `fading` keeps the paint and runs the
- // release animation on the machine's clock. A mouse keeps `:active`.
+ // The touch arms the controller writes, under a coarse primary pointer:
+ // `on` shows the pressed token on the button's `::before` layer on the
+ // first frame; `fading` runs the layer's opacity release on the press
+ // clock. A mouse keeps `:active`.
expect(button).toHaveAttribute('data-astryx-pressable');
expect(hasPressedArm(button)).toBe(true);
- expect(readsPressStrength(button, '[data-astryx-press="on"]')).toBe(true);
- expect(readsPressStrength(button)).toBe(true);
- expect(hasReleaseFade(button)).toBe(true);
+ expect(showsLayerPress(button)).toBe(true);
+ expect(releasesOnLayer(button, '::before', PRESS_FADE_MS)).toBe(true);
+ });
+
+ it('has no press layer and no isolation at rest under a coarse pointer, only while a press is on or fading', () => {
+ render(<Button label="Save" />);
+ const button = screen.getByRole('button', {name: 'Save'});
+ // At rest the button is no stacking context, and a `::before` a caller
+ // styles through `xstyle` keeps its own opacity, z-index and position.
+ expect(layerOnlyWhilePressed(button, '::before')).toBe(true);
+ });
+
+ it('keeps the press it always had under any other pointer: no layer, no isolation, the strength’s release', () => {
+ render(<Button label="Save" />);
+ const button = screen.getByRole('button', {name: 'Save'});
+ // A finger on a touch screen beside a mouse, and the mouse itself, see
+ // what they always saw.
+ expect(keepsPressOutsideCoarse(button, '::before')).toBe(true);
});
});
diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsx
index 3eaebc8f06..6f36a1d610 100644
--- a/packages/core/src/Button/Button.tsx
+++ b/packages/core/src/Button/Button.tsx
@@ -70,6 +70,10 @@ import type {LinkComponentType} from '../Link/types';
import {themeProps} from '../utils/themeProps';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';
+import {
+ controlPressLayerStyles,
+ rowPressLayerStyles,
+} from '../privateAttributes/press.stylex';
import {usePressFeedback} from '../hooks/usePressFeedback';
import type {ButtonVariantMap} from './index';
import {
@@ -811,6 +815,11 @@ export function Button({
sizeStyles[size],
isIconOnly && styles.iconOnly,
interactionOverlayStyles.backgroundImage,
+ // The press the controller writes, on a layer under the label whose
+ // release runs on the compositor.
+ rowPressLayerStyles.cell,
+ rowPressLayerStyles.cellOnImage,
+ controlPressLayerStyles.control,
isGroupTracked && styles.trackedOverlay,
buttonDisabled && styles.inactive,
isTrueDisabled && styles.disabled,
diff --git a/packages/core/src/Button/__tests__/ButtonPressRelease.interaction.browser.spec.ts b/packages/core/src/Button/__tests__/ButtonPressRelease.interaction.browser.spec.ts
new file mode 100644
index 0000000000..2f9b4dccb1
--- /dev/null
+++ b/packages/core/src/Button/__tests__/ButtonPressRelease.interaction.browser.spec.ts
@@ -0,0 +1,763 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ButtonPressRelease.interaction.browser.spec.ts
+ * @input The built press feedback Buttons story, real touch input (Chromium
+ * CDP / WebKit's input command), the interaction harness, and the theme's
+ * exit motion tokens as the story's page resolves them
+ * @output Animation proofs for a control's press release on the
+ * compositor: it follows the exit curve on the button's layer (sampled
+ * frame by frame, both engines), keeps fading on
+ * every frame while the main thread is blocked, starts at the first frame
+ * after a busy one and keeps its layer until the strength reaches 0 (both
+ * engines), and does no Layout or Paint; a second tap 70 ms after the
+ * first leaves nothing pressed (both engines); under reduced motion it is
+ * one opacity cross-fade of 200 ms or less on a coarse pointer; a
+ * storyboard of the release, its trace asserted
+ * @position Interaction evidence for privateAttributes/press.stylex.ts
+ * (`control`) as Button composes it; the tracking itself is
+ * proven in ButtonPress.interaction.browser.spec.ts
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ animationStoryboard,
+ blockMainThread,
+ castStoryboard,
+ compareCurve,
+ countBetween,
+ cubicBezier,
+ freezeTimers,
+ holdAnimations,
+ installTimerGate,
+ openStory,
+ releaseAnimations,
+ seekAnimations,
+ startScreencast,
+ tap,
+ thawTimers,
+ timeline,
+ touchDriver,
+ traceRendering,
+ waitForAnimation,
+ withStorybook,
+ writeEvidence,
+ type CastFrame,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+/**
+ * The press release's clock and curve: the theme's `--duration-exit` and
+ * `--ease-exit`, the same on a control's layer as on the strength. Read once
+ * from the Buttons story's page (see `beforeAll` below), so a theme change
+ * does not break the proofs.
+ */
+let RELEASE_MS = 0;
+let RELEASE_CURVE: [number, number, number, number] = [0, 0, 1, 1];
+let releaseEase: (t: number) => number = t => t;
+/** The layer's opacity t ms into the release: the strength, 1 → 0. */
+const expectedStrength = (t: number) =>
+ 1 - releaseEase(Math.min(1, Math.max(0, t / RELEASE_MS)));
+/**
+ * The most a frame within one frame of the release's end may still show:
+ * the exit curve leaves fastest at its end, so that frame is not near 0.
+ */
+const ONE_FRAME_FROM_REST = () =>
+ expectedStrength(RELEASE_MS - 1000 / 60) + 0.01;
+/** A held press, then the lift: the release starts at the lift. */
+const HOLD_MS = 400;
+
+/** The longest of the animations running: the release, not a shorter one. */
+function longestOf<T extends {durationMs: number}>(
+ running: ReadonlyArray<T>,
+): T {
+ let longest = running[0];
+ for (const animation of running) {
+ if (animation.durationMs > longest.durationMs) {
+ longest = animation;
+ }
+ }
+ return longest;
+}
+
+const BUTTONS = 'core-press-feedback-touch--buttons';
+
+test.beforeAll(async ({browser}) => {
+ const page = await browser.newPage();
+ try {
+ await openStory(page, storybook(), BUTTONS);
+ const tokens = await page
+ .locator('#storybook-root [data-astryx-pressable]')
+ .first()
+ .evaluate(el => {
+ const style = getComputedStyle(el);
+ return {
+ time: style.getPropertyValue('--duration-exit').trim(),
+ curve: style.getPropertyValue('--ease-exit').trim(),
+ };
+ });
+ RELEASE_MS = tokens.time.endsWith('ms')
+ ? Number.parseFloat(tokens.time)
+ : Number.parseFloat(tokens.time) * 1000;
+ const points = (tokens.curve.match(/-?\d*\.?\d+/g) ?? []).map(Number);
+ expect(points, tokens.curve).toHaveLength(4);
+ RELEASE_CURVE = points as [number, number, number, number];
+ releaseEase = cubicBezier(...RELEASE_CURVE);
+ } finally {
+ await page.close();
+ }
+});
+
+interface Opened {
+ driver: TouchDriver;
+ surface: Locator;
+ center: {x: number; y: number};
+ /** A point on the surface's fill, clear of its label, CSS px. */
+ probe: {x: number; y: number};
+ /** What the page saw, on its own clock (performance.now()). */
+ log: () => Promise<LogEntry[]>;
+}
+
+type LogEntry = [kind: string, t: number, value: string | null];
+
+/** A press state and what the button's own layer computes in it. */
+interface LayerState {
+ press: string | null;
+ layer: string;
+ isolation: string;
+}
+
+async function openSurface(
+ page: Page,
+ story: string,
+ surface: (page: Page) => Locator,
+ probeAt: (box: {width: number; height: number}) => {
+ x: number;
+ y: number;
+ } = box => ({
+ x: box.width - 6,
+ y: box.height / 2,
+ }),
+): Promise<Opened> {
+ await openStory(page, storybook(), story);
+ const driver = await touchDriver(page);
+ const element = surface(page);
+ await expect(element).toBeVisible();
+ const box = await element.boundingBox();
+ if (box == null) {
+ throw new Error(`${story}: the surface has no box`);
+ }
+ const offset = probeAt(box);
+ await element.evaluate(el => {
+ const entries: LogEntry[] = [];
+ (window as unknown as {__press: LogEntry[]}).__press = entries;
+ for (const type of ['pointerdown', 'pointerup', 'pointercancel', 'click']) {
+ document.addEventListener(
+ type,
+ () => entries.push([type, performance.now(), null]),
+ true,
+ );
+ }
+ new MutationObserver(records => {
+ for (const record of records) {
+ entries.push([
+ 'press',
+ performance.now(),
+ (record.target as Element).getAttribute('data-astryx-press'),
+ ]);
+ }
+ }).observe(el, {attributes: true, attributeFilter: ['data-astryx-press']});
+ });
+ return {
+ driver,
+ surface: element,
+ center: {x: box.x + box.width / 2, y: box.y + box.height / 2},
+ probe: {x: Math.round(box.x + offset.x), y: Math.round(box.y + offset.y)},
+ log: async () =>
+ page.evaluate(() => (window as unknown as {__press: LogEntry[]}).__press),
+ };
+}
+
+const secondaryButton = (page: Page) =>
+ page.getByRole('button', {name: 'Secondary', exact: true});
+/** Opacity of a surface's press layer, as the engine presents it. */
+const layerOpacity = async (surface: Locator, pseudo: '::before' | '::after') =>
+ surface.evaluate(
+ (el, which) => Number(getComputedStyle(el, which).opacity),
+ pseudo,
+ );
+
+for (const [name, story, locate] of [
+ ['a button', BUTTONS, secondaryButton],
+] as const) {
+ test(`under reduced motion the release of ${name} is one opacity cross-fade of 200 ms or less (design:reduced-motion DR2)`, async ({
+ page,
+ }) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const opened = await openSurface(page, story, locate);
+ await installTimerGate(page);
+ await opened.driver.play(tap(opened.center, {holdMs: HOLD_MS}));
+ expect(await opened.surface.getAttribute('data-astryx-press')).toBe(
+ 'fading',
+ );
+ await freezeTimers(page);
+ const held = await holdAnimations(page, opened.surface);
+ await releaseAnimations(page, {finish: true});
+ await thawTimers(page);
+ // One animation, of opacity alone, finished within 200 ms; nothing
+ // else on the surface (no transform, no size) animates.
+ expect(held, JSON.stringify(held)).toHaveLength(1);
+ const [release] = held;
+ expect(release.kind).toBe('CSSAnimation');
+ // A cross-fade, not a jump: the policy's 200 ms.
+ expect(release.durationMs).toBeGreaterThan(0);
+ expect(release.durationMs).toBeLessThanOrEqual(200);
+ const animated = new Set(
+ release.keyframes.flatMap(frame =>
+ Object.keys(frame).filter(
+ key =>
+ !['offset', 'computedOffset', 'easing', 'composite'].includes(key),
+ ),
+ ),
+ );
+ expect([...animated]).toEqual(['opacity']);
+ });
+}
+
+for (const [name, story, locate, pseudo] of [
+ ['a button', BUTTONS, secondaryButton, '::before'],
+] as const) {
+ test(`with a fine primary pointer, a finger’s release of ${name} is the strength’s release it always had (the desktop rule)`, async ({
+ browser,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'a touch screen beside a fine primary pointer is emulated through CDP',
+ );
+ // `spec:AST-017` FR59/DEC-25: touch work leaves a fine pointer's behavior as it
+ // is. A laptop's touch screen: no touch emulation, so the primary pointer
+ // stays fine, and the touches arrive through CDP.
+ const context = await browser.newContext({
+ viewport: {width: 402, height: 714},
+ hasTouch: false,
+ isMobile: false,
+ });
+ const page = await context.newPage();
+ try {
+ const opened = await openSurface(page, story, locate);
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ await installTimerGate(page);
+ await opened.driver.play(tap(opened.center, {holdMs: HOLD_MS}));
+ expect(await opened.surface.getAttribute('data-astryx-press')).toBe(
+ 'fading',
+ );
+ await freezeTimers(page);
+ const held = (await holdAnimations(page, opened.surface)).filter(
+ animation => animation.kind === 'CSSAnimation',
+ );
+ const layer = await opened.surface.evaluate(
+ el => getComputedStyle(el, '::before').content,
+ );
+ await releaseAnimations(page, {finish: true});
+ await thawTimers(page);
+ // One release, of the strength on the element (not a layer's
+ // opacity), on the exit clock and curve.
+ expect(held, JSON.stringify(held)).toHaveLength(1);
+ const [release] = held;
+ const animated = new Set(
+ release.keyframes.flatMap(frame =>
+ Object.keys(frame).filter(
+ key =>
+ !['offset', 'computedOffset', 'easing', 'composite'].includes(
+ key,
+ ),
+ ),
+ ),
+ );
+ expect(animated.has('opacity'), JSON.stringify(release)).toBe(false);
+ expect(release.durationMs).toBe(RELEASE_MS);
+ // A CSS animation's curve rides on its keyframes, not its timing.
+ expect(
+ (String(release.keyframes[0].easing).match(/-?\d*\.?\d+/g) ?? []).map(
+ Number,
+ ),
+ ).toEqual(RELEASE_CURVE);
+ expect(['none', 'normal']).toContain(layer);
+ } finally {
+ await context.close();
+ }
+ });
+
+ test(`the release of ${name} follows the release curve, sampled frame by frame`, async ({
+ page,
+ }, testInfo) => {
+ const opened = await openSurface(page, story, locate);
+ if (pseudo === '::before') {
+ // At rest the button has no layer: it exists only while a press is on
+ // or fading.
+ expect(['none', 'normal']).toContain(
+ await opened.surface.evaluate(
+ el => getComputedStyle(el, '::before').content,
+ ),
+ );
+ }
+ // Gate the page's timers before the press, so the release timer (which
+ // removes the attribute when the clock runs out) holds while seeking.
+ await installTimerGate(page);
+ await opened.driver.play(tap(opened.center, {holdMs: HOLD_MS}));
+ expect(await opened.surface.getAttribute('data-astryx-press')).toBe(
+ 'fading',
+ );
+ await freezeTimers(page);
+ const held = await holdAnimations(page, opened.surface);
+ const release = held.find(
+ a => a.kind === 'CSSAnimation' && a.durationMs === RELEASE_MS,
+ );
+ expect(release, JSON.stringify(held)).toBeDefined();
+ const samples: {t: number; value: number}[] = [];
+ for (const t of timeline(RELEASE_MS)) {
+ await seekAnimations(page, t);
+ samples.push({t, value: await layerOpacity(opened.surface, pseudo)});
+ }
+ await releaseAnimations(page, {finish: true});
+ await thawTimers(page);
+ const comparison = compareCurve(samples, expectedStrength, 0.005);
+ await writeEvidence(
+ `curves/${story}-press-release`,
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {
+ releaseMs: RELEASE_MS,
+ curve: RELEASE_CURVE,
+ held,
+ samples,
+ comparison,
+ },
+ null,
+ 2,
+ ),
+ },
+ testInfo,
+ );
+ expect(samples[0].value).toBeCloseTo(1, 2);
+ expect(
+ comparison.maxError,
+ JSON.stringify(comparison.worst),
+ ).toBeLessThanOrEqual(0.005);
+ await expect
+ .poll(async () => opened.surface.getAttribute('data-astryx-press'))
+ .toBeNull();
+ });
+}
+
+interface PixelFrame {
+ readonly t: number;
+ /** Mean of the RGB channels at the probe point, 0–255. */
+ readonly value: number;
+}
+
+/** The probe point's value in every frame, decoded in a scratch page. */
+test('with a fine primary pointer, a mouse press on a button adds no layer and no isolation (the desktop rule)', async ({
+ browser,
+}) => {
+ // `spec:AST-017` FR59/DEC-25: touch work leaves a fine pointer's behavior as it
+ // is. A desktop: no touch, a mouse.
+ const context = await browser.newContext({
+ viewport: {width: 402, height: 714},
+ hasTouch: false,
+ isMobile: false,
+ });
+ const page = await context.newPage();
+ try {
+ await openStory(page, storybook(), BUTTONS);
+ const surface = secondaryButton(page);
+ await expect(surface).toBeVisible();
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const read = async () =>
+ surface.evaluate(el => ({
+ layer: getComputedStyle(el, '::before').content,
+ isolation: getComputedStyle(el).isolation,
+ press: el.getAttribute('data-astryx-press'),
+ }));
+ const box = await surface.boundingBox();
+ if (box == null) {
+ throw new Error('the button has no box');
+ }
+ const states = [await read()];
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.down();
+ states.push(await read());
+ await page.mouse.up();
+ states.push(await read());
+ for (const state of states) {
+ expect(['none', 'normal'], JSON.stringify(state)).toContain(state.layer);
+ expect(state.isolation).toBe('auto');
+ // A mouse's press is `:active`'s: the controller writes nothing.
+ // Button's record lists the controller's mouse and pen press (FR15)
+ // as not implemented; this pins today's behavior, not the record.
+ expect(state.press).toBeNull();
+ }
+ } finally {
+ await context.close();
+ }
+});
+
+test('with a coarse primary pointer, a button has no press layer and no isolation at rest, only while its press is on or fading', async ({
+ page,
+}) => {
+ const opened = await openSurface(page, BUTTONS, secondaryButton);
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(true);
+ // Every state the press passes through, read as the attribute changes. At
+ // rest the button is no stacking context and has no `::before` of its own,
+ // so a caller's `::before` keeps its styles.
+ await opened.surface.evaluate(el => {
+ const states: LayerState[] = [];
+ const read = () => {
+ states.push({
+ press: el.getAttribute('data-astryx-press'),
+ layer: getComputedStyle(el, '::before').content,
+ isolation: getComputedStyle(el).isolation,
+ });
+ };
+ read();
+ new MutationObserver(read).observe(el, {
+ attributes: true,
+ attributeFilter: ['data-astryx-press'],
+ });
+ (window as unknown as {__layer: LayerState[]}).__layer = states;
+ });
+ await opened.driver.play(tap(opened.center, {holdMs: HOLD_MS}));
+ await expect
+ .poll(async () => opened.surface.getAttribute('data-astryx-press'))
+ .toBeNull();
+ const states = await page.evaluate(
+ () => (window as unknown as {__layer: LayerState[]}).__layer,
+ );
+ const log = JSON.stringify(states);
+ const pressed = states.filter(state => state.press != null);
+ expect(
+ pressed.map(state => state.press),
+ log,
+ ).toEqual(['on', 'fading']);
+ for (const state of pressed) {
+ expect(state.layer, log).toBe('""');
+ expect(state.isolation, log).toBe('isolate');
+ }
+ const rest = states.filter(state => state.press == null);
+ // Before the press and after its release.
+ expect(rest.length, log).toBe(2);
+ for (const state of rest) {
+ expect(['none', 'normal'], log).toContain(state.layer);
+ expect(state.isolation, log).toBe('auto');
+ }
+});
+
+async function samplePixel(
+ page: Page,
+ frames: ReadonlyArray<CastFrame>,
+ probe: {x: number; y: number},
+): Promise<PixelFrame[]> {
+ const scratch = await page.context().newPage();
+ try {
+ const out: PixelFrame[] = [];
+ for (let i = 0; i < frames.length; i += 12) {
+ const batch = frames.slice(i, i + 12);
+ const values = await scratch.evaluate(
+ async ({items, at}) => {
+ const results: number[] = [];
+ for (const item of items) {
+ const bitmap = await createImageBitmap(
+ await (
+ await fetch(`data:image/${item.format};base64,${item.data}`)
+ ).blob(),
+ );
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext('2d');
+ if (context == null) {
+ throw new Error('no 2d context');
+ }
+ context.drawImage(bitmap, 0, 0);
+ const scale = bitmap.width / item.viewportWidth;
+ const px = context.getImageData(
+ Math.round(at.x * scale),
+ Math.round(at.y * scale),
+ 1,
+ 1,
+ ).data;
+ results.push((px[0] + px[1] + px[2]) / 3);
+ }
+ return results;
+ },
+ {
+ items: batch.map(f => ({
+ data: f.data,
+ format: f.format,
+ viewportWidth: f.viewportWidth,
+ })),
+ at: probe,
+ },
+ );
+ values.forEach((value, k) => out.push({t: batch[k].t, value}));
+ }
+ return out;
+ } finally {
+ await scratch.close();
+ }
+}
+
+test('the release of a button keeps fading on every frame while the main thread is blocked', async ({
+ page,
+ browserName,
+}, testInfo) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'screencast frame evidence is Chromium-only in Playwright; the iOS simulator covers Safari',
+ );
+ const opened = await openSurface(page, BUTTONS, secondaryButton);
+ // A long exit duration on the button, so the block spans enough delivered
+ // frames to judge whatever the theme's own value is.
+ await opened.surface.evaluate(el =>
+ (el as HTMLElement).style.setProperty('--duration-exit', '400ms'),
+ );
+ const cast = await startScreencast(page);
+ await opened.driver.play(tap(opened.center, {holdMs: HOLD_MS}));
+ // The release is the longest animation running: the `::before`
+ // opacity fade, not the 125 ms press-scale transition that starts with it.
+ const running = await waitForAnimation(opened.surface, {minProgressMs: 16});
+ const release = longestOf(running);
+ // A 1 s block, as spec:AST-094 FR5's verification names, covers the
+ // whole release.
+ const block = await blockMainThread(page, 1000);
+ await page.waitForTimeout(150);
+ const frames = await cast.stop();
+ const pixels = await samplePixel(page, frames, opened.probe);
+ const rest = pixels[0].value;
+ const pressed = Math.min(
+ ...pixels.filter(p => p.t < release.from).map(p => p.value),
+ );
+ const strength = (v: number) => (rest - v) / (rest - pressed);
+ const end = Math.min(block.to, release.to) - 10;
+ const during = pixels.filter(p => p.t > block.from && p.t <= end);
+ const strengths = during.map(p => ({
+ t: +(p.t - block.from).toFixed(1),
+ strength: +strength(p.value).toFixed(3),
+ }));
+ const intervals = during
+ .map((p, i) => (i === 0 ? p.t - block.from : p.t - during[i - 1].t))
+ .filter(dt => dt > 0);
+ const longestGap = Math.max(
+ end - (during.at(-1)?.t ?? block.from),
+ ...intervals,
+ );
+ await writeEvidence(
+ 'busy-main-thread/button-press-release',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {block, release, rest, pressed, strengths},
+ null,
+ 1,
+ ),
+ },
+ testInfo,
+ );
+ const film = await castStoryboard(page, frames, {
+ name: 'button-press-release-busy-main-thread',
+ zero: block.from,
+ from: release.from - 40,
+ to: release.to + 40,
+ columns: 6,
+ cellScale: 0.45,
+ data: t => {
+ const p = pixels.find(f => f.t === t);
+ return {strength: p == null ? -1 : +strength(p.value).toFixed(3)};
+ },
+ });
+ await film.write(testInfo, {block, release});
+ expect(rest - pressed).toBeGreaterThan(10);
+ expect(during.length, JSON.stringify(strengths)).toBeGreaterThanOrEqual(
+ Math.floor((end - block.from) / (1000 / 60)) - 2,
+ );
+ expect(longestGap).toBeLessThan(40);
+ for (let i = 1; i < strengths.length; i++) {
+ expect(strengths[i].strength).toBeLessThanOrEqual(
+ strengths[i - 1].strength + 0.01,
+ );
+ }
+ const last = strengths.at(-1);
+ expect(last).toBeDefined();
+ expect(strengths[0].strength).toBeGreaterThan((last?.strength ?? 1) + 0.2);
+});
+
+test('after a busy first frame, the release starts at that frame and keeps a button’s layer until its strength reaches 0', async ({
+ page,
+ browserName,
+}) => {
+ const opened = await openSurface(page, BUTTONS, secondaryButton);
+ // A release longer than the 150 ms block, so in both engines it is still
+ // running when the block ends, whatever the theme's own exit duration is.
+ const releaseMs = 400;
+ await opened.surface.evaluate(
+ (el, ms) =>
+ (el as HTMLElement).style.setProperty('--duration-exit', `${ms}ms`),
+ releaseMs,
+ );
+ const strengthAt = (t: number) =>
+ 1 - releaseEase(Math.min(1, Math.max(0, t / releaseMs)));
+ // When the press controller writes the release, 150 ms of script hold the
+ // main thread before the first frame, so the release animation starts
+ // late. Each frame after that records whether the release is still
+ // written and the layer's strength, until the release is gone.
+ await opened.surface.evaluate(el => {
+ type Frame = [press: string | null, strength: number];
+ (window as unknown as {__release: Promise<Frame[]>}).__release =
+ new Promise(resolve => {
+ const frames: Frame[] = [];
+ const observer = new MutationObserver(() => {
+ if (el.getAttribute('data-astryx-press') !== 'fading') {
+ return;
+ }
+ observer.disconnect();
+ const until = performance.now() + 150;
+ while (performance.now() < until) {
+ // Busy: the main thread is held.
+ }
+ const sample = () => {
+ const press = el.getAttribute('data-astryx-press');
+ frames.push([
+ press,
+ Number(getComputedStyle(el, '::before').opacity),
+ ]);
+ if (press !== 'fading') {
+ resolve(frames);
+ return;
+ }
+ requestAnimationFrame(sample);
+ };
+ requestAnimationFrame(sample);
+ });
+ observer.observe(el, {attributeFilter: ['data-astryx-press']});
+ });
+ });
+ await opened.driver.play(tap(opened.center, {holdMs: HOLD_MS}));
+ const frames = await page.evaluate(
+ async () =>
+ (
+ window as unknown as {
+ __release: Promise<[string | null, number][]>;
+ }
+ ).__release,
+ );
+ const fading = frames.filter(([press]) => press === 'fading');
+ // Chromium starts the release when it first styles it, after the block:
+ // the first frame shows it at most two frames in. WebKit starts it at the
+ // time the busy script began, so its first frame shows it 150 ms in; the
+ // checks below still hold there.
+ if (browserName !== 'webkit') {
+ expect(fading[0]?.[1], JSON.stringify(frames)).toBeGreaterThan(
+ strengthAt((2 * 1000) / 60),
+ );
+ }
+ // It ran on frames after the block, and its last frame still written
+ // shows the layer at rest: the release went when its animation ended, not
+ // partway through it.
+ expect(fading.length, JSON.stringify(frames)).toBeGreaterThan(2);
+ expect(fading.at(-1)?.[1], JSON.stringify(frames)).toBeLessThanOrEqual(
+ strengthAt(releaseMs - 1000 / 60) + 0.01,
+ );
+});
+
+test('a second tap 70 ms after the first leaves nothing pressed', async ({
+ page,
+}) => {
+ const opened = await openSurface(page, BUTTONS, secondaryButton);
+ // Two quick taps, the second while the first one's release still runs:
+ // the second press is lifted too, so its release runs and the press goes.
+ await page.touchscreen.tap(opened.center.x, opened.center.y);
+ await page.waitForTimeout(70);
+ await page.touchscreen.tap(opened.center.x, opened.center.y);
+ await expect
+ .poll(async () => opened.surface.getAttribute('data-astryx-press'), {
+ timeout: 2000,
+ })
+ .toBeNull();
+});
+
+test('the release of a button does no Layout or Paint per frame', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');
+ const opened = await openSurface(page, BUTTONS, secondaryButton);
+ let release = {from: 0, to: 0};
+ const trace = await traceRendering(page, async () => {
+ await opened.driver.play(tap(opened.center, {holdMs: HOLD_MS}));
+ // The release is the longest animation running: the `::before`
+ // opacity fade, not the 125 ms press-scale transition that starts with it.
+ const running = await waitForAnimation(opened.surface);
+ release = longestOf(running);
+ await page.waitForTimeout(RELEASE_MS + 100);
+ });
+ // The steady part of the release: its first and last frames may commit.
+ const during = countBetween(trace, release.from + 30, release.to - 30);
+ expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0);
+ expect(during.Paint ?? 0, JSON.stringify(during)).toBe(0);
+});
+
+test(
+ 'storyboard: a button released after a hold',
+ {tag: '@storyboard'},
+ async ({page}, testInfo) => {
+ const opened = await openSurface(page, BUTTONS, secondaryButton);
+ await installTimerGate(page);
+ const box = await opened.surface.boundingBox();
+ if (box == null) {
+ throw new Error('no button');
+ }
+ const clip = {
+ x: Math.max(0, box.x - 16),
+ y: Math.max(0, box.y - 16),
+ width: box.width + 32,
+ height: box.height + 32,
+ };
+ await opened.driver.play(tap(opened.center, {holdMs: HOLD_MS}));
+ await freezeTimers(page);
+ const {storyboard} = await animationStoryboard(page, {
+ name: 'button-press-release',
+ clip,
+ scope: opened.surface,
+ times: timeline(RELEASE_MS),
+ measure: async () => ({
+ opacity: await layerOpacity(opened.surface, '::before'),
+ state: await opened.surface.getAttribute('data-astryx-press'),
+ }),
+ columns: 8,
+ cellScale: 0.6,
+ });
+ await releaseAnimations(page, {finish: true});
+ await thawTimers(page);
+ await storyboard.write(testInfo);
+ const opacities = storyboard.frames.map(f => f.data.opacity as number);
+ expect(opacities[0]).toBeCloseTo(1, 2);
+ expect(opacities.at(-1)).toBeLessThanOrEqual(ONE_FRAME_FROM_REST());
+ for (let i = 1; i < opacities.length; i++) {
+ expect(opacities[i]).toBeLessThanOrEqual(opacities[i - 1] + 1e-6);
+ }
+ storyboard.frames.forEach(f =>
+ expect(f.data.opacity as number).toBeCloseTo(expectedStrength(f.t), 2),
+ );
+ },
+);
diff --git a/packages/core/src/Button/__tests__/ButtonPressTiming.interaction.browser.spec.ts b/packages/core/src/Button/__tests__/ButtonPressTiming.interaction.browser.spec.ts
new file mode 100644
index 0000000000..24ff3077f6
--- /dev/null
+++ b/packages/core/src/Button/__tests__/ButtonPressTiming.interaction.browser.spec.ts
@@ -0,0 +1,302 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ButtonPressTiming.interaction.browser.spec.ts
+ * @input The press feedback stories' Secondary button and first list row on
+ * a touch-first device (coarse primary pointer), pressed by a real finger,
+ * a mouse and the Space key
+ * @output Real-engine proof of how long each press's release runs on a
+ * touch-first device: a finger's release on a control's layer, a mouse's
+ * or the Space key's press, and a list row's release all run the one press
+ * clock. Each release animation's own duration is read
+ * when `fading` is written; `fading` outlasts the animation (its progress
+ * has reached its end when `fading` goes) and goes within a few frames of
+ * that end. The animation's own progress and frames, not ms, bound it, so
+ * a loaded machine running the page late cannot fail it
+ * @position Interaction evidence beside
+ * ButtonPressRelease.interaction.browser.spec.ts (the release's curve and
+ * layer)
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ openStory,
+ tap,
+ touchDriver,
+ withStorybook,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+const BUTTONS = 'core-press-feedback-touch--buttons';
+const ROWS = 'core-press-feedback-touch--rows';
+/**
+ * Every press release plays the theme's `--duration-exit`: a finger's on a
+ * control's layer, a mouse's or the Space key's on a touch-first device, and
+ * a list row's. Read once from the Buttons story's page.
+ */
+let EXIT_MS = 0;
+
+test.beforeAll(async ({browser}) => {
+ const page = await browser.newPage();
+ try {
+ await openStory(page, storybook(), BUTTONS);
+ const time = await page
+ .locator('#storybook-root [data-astryx-pressable]')
+ .first()
+ .evaluate(el =>
+ getComputedStyle(el).getPropertyValue('--duration-exit').trim(),
+ );
+ EXIT_MS = time.endsWith('ms')
+ ? Number.parseFloat(time)
+ : Number.parseFloat(time) * 1000;
+ expect(EXIT_MS, time).toBeGreaterThan(0);
+ } finally {
+ await page.close();
+ }
+});
+/** A held press: the release starts at the lift. */
+const HOLD_MS = 400;
+/**
+ * How many frames after the release animation finishes `fading` may still be
+ * on: the controller ends it at the animation's end, or at its own check if
+ * that comes later. Counted in frames, not ms, so a loaded machine that runs
+ * the page late cannot make it fail.
+ */
+const MAX_FRAMES_AFTER_FINISH = 3;
+
+interface ReleaseRecord {
+ fadingAt: number | null;
+ goneAt: number | null;
+ animationMs: number | null;
+ /** The release animation's start on the document timeline, ms. */
+ startedAt: number | null;
+ /** The document timeline's time when `fading` went, ms. */
+ removedAt: number | null;
+ finishedAt: number | null;
+ framesAfterFinish: number | null;
+ cancelled: boolean;
+}
+
+type Recorded = Window & {__release?: ReleaseRecord};
+
+async function openSurface(
+ page: Page,
+ story: string,
+ locate: (page: Page) => Locator,
+) {
+ await openStory(page, storybook(), story);
+ const button = locate(page);
+ await expect(button).toBeVisible();
+ // A touch-first device: the primary pointer is coarse.
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(true);
+ await button.evaluate(el => {
+ const record: ReleaseRecord = {
+ fadingAt: null,
+ goneAt: null,
+ animationMs: null,
+ startedAt: null,
+ removedAt: null,
+ finishedAt: null,
+ framesAfterFinish: null,
+ cancelled: false,
+ };
+ (window as Recorded).__release = record;
+ new MutationObserver(() => {
+ const value = el.getAttribute('data-astryx-press');
+ const now = performance.now();
+ if (value === 'fading' && record.fadingAt == null) {
+ record.fadingAt = now;
+ // The release animation the `fading` write starts, on the surface or
+ // its own pseudo-elements; reading it flushes the new style.
+ const releases = el
+ .getAnimations({subtree: true})
+ .filter(
+ animation =>
+ 'animationName' in animation &&
+ (animation.effect as KeyframeEffect | null)?.target === el,
+ );
+ const durationOf = (animation: Animation) =>
+ Number(
+ (animation.effect as KeyframeEffect).getComputedTiming().duration,
+ );
+ const longest = releases.reduce<Animation | null>(
+ (best, animation) =>
+ best == null || durationOf(animation) > durationOf(best)
+ ? animation
+ : best,
+ null,
+ );
+ record.animationMs = longest == null ? null : durationOf(longest);
+ // Its start is a frame's time, which can come before the write, so
+ // the page's clock is not what says whether it ran to its end.
+ longest?.ready.then(
+ () => {
+ record.startedAt = Number(longest.startTime);
+ },
+ () => undefined,
+ );
+ longest?.finished.then(
+ () => {
+ record.finishedAt = performance.now();
+ // Count the frames from the animation's end until `fading` goes.
+ let frames = 0;
+ const tick = () => {
+ if (record.goneAt != null) {
+ record.framesAfterFinish = frames;
+ return;
+ }
+ frames += 1;
+ requestAnimationFrame(tick);
+ };
+ tick();
+ },
+ () => {
+ // Cancelled: the paint was removed while it still ran.
+ record.cancelled = true;
+ },
+ );
+ } else if (
+ value == null &&
+ record.fadingAt != null &&
+ record.goneAt == null
+ ) {
+ record.goneAt = now;
+ record.removedAt = Number(document.timeline.currentTime);
+ }
+ }).observe(el, {attributes: true, attributeFilter: ['data-astryx-press']});
+ });
+ const box = await button.boundingBox();
+ if (box == null) {
+ throw new Error(`${story}: the surface has no box`);
+ }
+ return {
+ button,
+ center: {x: box.x + box.width / 2, y: box.y + box.height / 2},
+ };
+}
+
+const secondaryButton = (page: Page) =>
+ page.getByRole('button', {name: 'Secondary', exact: true});
+const firstRow = (page: Page) =>
+ page
+ .locator('[data-astryx-pressable]')
+ .filter({hasText: 'Conversation 1'})
+ .first();
+
+const openButton = async (page: Page) =>
+ openSurface(page, BUTTONS, secondaryButton);
+
+interface Release {
+ /** The release animation's own duration, read when `fading` is written. */
+ animationMs: number | null;
+ /** How long `fading` lasted on the page's clock. */
+ fadingMs: number;
+ /**
+ * How far the animation had run on the document timeline when `fading`
+ * went; null when it had not started.
+ */
+ ranMs: number | null;
+ /**
+ * Frames from the animation's end until `fading` went, or 0 when `fading`
+ * went first: the animation then stopped with it.
+ */
+ framesAfterFinish: number;
+}
+
+/** The release that just ran, once `fading` has gone. */
+async function releaseOf(page: Page): Promise<Release> {
+ await expect
+ .poll(
+ async () =>
+ page.evaluate(() => {
+ const record = (window as Recorded).__release;
+ return (
+ record != null &&
+ (record.cancelled ||
+ (record.goneAt != null && record.framesAfterFinish != null))
+ );
+ }),
+ {timeout: 3000},
+ )
+ .toBe(true);
+ const record = await page.evaluate(() => (window as Recorded).__release);
+ if (record?.fadingAt == null || record.goneAt == null) {
+ throw new Error('no release was recorded');
+ }
+ return {
+ animationMs: record.animationMs,
+ fadingMs: record.goneAt - record.fadingAt,
+ ranMs:
+ record.startedAt == null || record.removedAt == null
+ ? null
+ : record.removedAt - record.startedAt,
+ framesAfterFinish: record.cancelled
+ ? 0
+ : (record.framesAfterFinish ?? Number.POSITIVE_INFINITY),
+ };
+}
+
+/**
+ * A release of `ms`: its animation runs `ms`, `fading` stays until the
+ * animation has run to its end, and goes within a few frames of that end.
+ */
+function expectRelease(release: Release, ms: number): void {
+ expect(release.animationMs).toBe(ms);
+ expect(release.ranMs, JSON.stringify(release)).not.toBeNull();
+ expect(release.ranMs, JSON.stringify(release)).toBeGreaterThanOrEqual(ms - 1);
+ expect(release.framesAfterFinish).toBeLessThanOrEqual(
+ MAX_FRAMES_AFTER_FINISH,
+ );
+}
+
+test("a finger's release on a button's layer runs the press clock", async ({
+ page,
+}) => {
+ const {center} = await openButton(page);
+ const driver = await touchDriver(page);
+ await driver.play(tap(center, {holdMs: HOLD_MS}));
+ const release = await releaseOf(page);
+ expectRelease(release, EXIT_MS);
+});
+
+test("a mouse press's release on the same device runs the press clock", async ({
+ page,
+}) => {
+ const {center} = await openButton(page);
+ await page.mouse.move(center.x, center.y);
+ await page.mouse.down();
+ await page.waitForTimeout(HOLD_MS);
+ await page.mouse.up();
+ const release = await releaseOf(page);
+ expectRelease(release, EXIT_MS);
+});
+
+test("a Space press's release on the same device runs the press clock", async ({
+ page,
+}) => {
+ const {button} = await openButton(page);
+ await button.focus();
+ await page.keyboard.down('Space');
+ await page.waitForTimeout(HOLD_MS);
+ await page.keyboard.up('Space');
+ const release = await releaseOf(page);
+ expectRelease(release, EXIT_MS);
+});
+
+test("a finger's release on a list row runs the press clock", async ({
+ page,
+}) => {
+ const {center} = await openSurface(page, ROWS, firstRow);
+ const driver = await touchDriver(page);
+ await driver.play(tap(center, {holdMs: HOLD_MS}));
+ const release = await releaseOf(page);
+ expectRelease(release, EXIT_MS);
+});
diff --git a/packages/core/src/Item/Item.test.tsx b/packages/core/src/Item/Item.test.tsx
index 9c3ed716d6..2e9c9fda3b 100644
--- a/packages/core/src/Item/Item.test.tsx
+++ b/packages/core/src/Item/Item.test.tsx
@@ -20,7 +20,7 @@ import {
vi,
} from 'vitest';
import {act, cleanup, fireEvent, render, screen} from '@testing-library/react';
-import {rulesDeclaredFor} from '../__tests__/pressState';
+import {layerOnlyWhilePressed, rulesDeclaredFor} from '../__tests__/pressState';
import {swipeLayerLoaded} from './__tests__/swipeLayerLoaded';
import userEvent from '@testing-library/user-event';
import {LinkProvider} from '../Link/LinkProvider';
@@ -874,6 +874,16 @@ describe('Item', () => {
}
});
+ it('keeps its touch press layer to a press: on or fading', () => {
+ render(<Item label="Row" onClick={() => {}} data-testid="row" />);
+ // Under a coarse pointer the row's `::before` layer and its isolation
+ // apply only on a press arm; at rest a caller's own `::before` keeps its
+ // styles.
+ expect(layerOnlyWhilePressed(screen.getByTestId('row'), '::before')).toBe(
+ true,
+ );
+ });
+
it('truncates the label and description to the lines it is given', () => {
// The clamp count reaches CSS through a custom property, so resolve it.
const lineClamp = (element: HTMLElement) => {
diff --git a/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts b/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts
index 1860de1318..faebfe27c7 100644
--- a/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts
+++ b/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts
@@ -1,5 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-// @pr-a11y scope core/Button ^packages/core/src/(utils/(pressFeedback|pressGesture|interactionOverlay|touchPresentation)|hooks/usePressFeedback)
+// @pr-a11y scope core/Button ^packages/core/src/(utils/(pressFeedback|pressGesture|interactionOverlay|touchPresentation)|hooks/usePressFeedback|privateAttributes/press)
/**
* @file PressModality.a11y.chromium.spec.ts
diff --git a/packages/core/src/__tests__/pressState.ts b/packages/core/src/__tests__/pressState.ts
index 86c9a966d2..f573b43d1b 100644
--- a/packages/core/src/__tests__/pressState.ts
+++ b/packages/core/src/__tests__/pressState.ts
@@ -34,6 +34,7 @@ const PRESS_STRENGTH = '--astryx-press-alpha';
/** The press's paint at its strength, declared once by the shared styles. */
const PRESS_PAINT = '--_press-paint';
const FADING_ARM = '[data-astryx-press="fading"]';
+const ON_ARM = '[data-astryx-press="on"]';
const selectorOf = (rule: string) => rule.slice(0, rule.indexOf('{'));
const onPseudoElement = (rule: string) => selectorOf(rule).includes('::');
@@ -76,6 +77,10 @@ const UNDER_COARSE: RuleFilter = {
insideMedia: COARSE_MEDIA,
outsideMedia: REDUCED_MEDIA,
};
+/** Rules for any other primary pointer, Reduce Motion's arms left out. */
+const UNDER_FINE: RuleFilter = {
+ outsideMedia: /prefers-reduced-motion|\(pointer: coarse\)/,
+};
/**
* Every injected style rule (rules nested in `@media` included) whose selector
@@ -344,3 +349,75 @@ export function releasesOnLayer(
own(coarseFading).some(stopsAnimation)
);
}
+
+/**
+ * Does the element paint the press on its `::before` compositor layer? The
+ * layer shows the pressed token, exists only while a press does (see
+ * {@link layerOnlyWhilePressed}), and on the on arm shows at once: opacity 1,
+ * no animation.
+ */
+export function showsLayerPress(el: Element): boolean {
+ const layer = rulesDeclaredFor(el).filter(rule =>
+ selectorOf(rule).includes('::before'),
+ );
+ const on = layer.filter(rule => selectorOf(rule).includes(ON_ARM));
+ return (
+ layer.some(rule =>
+ /background-color:[^;}]*--color-overlay-pressed/.test(rule),
+ ) &&
+ layerOnlyWhilePressed(el, '::before') &&
+ on.some(rule => /opacity:\s*1\b/.test(rule)) &&
+ !on.some(runsAnimation)
+ );
+}
+
+/**
+ * Under a coarse primary pointer, does every declaration of the element's
+ * press layer on `pseudo`, and its `isolation`, apply only while a press is
+ * on or fading? At rest the element then has no layer and is no stacking
+ * context, and a caller's own `pseudo` keeps its styles.
+ */
+export function layerOnlyWhilePressed(
+ el: Element,
+ pseudo: '::before' | '::after',
+): boolean {
+ const declarations = (rule: string) => rule.slice(rule.indexOf('{'));
+ const layer = rulesDeclaredFor(el, {insideMedia: COARSE_MEDIA}).filter(
+ rule =>
+ selectorOf(rule).includes(pseudo) ||
+ /(^|[{;\s])isolation:/.test(declarations(rule)),
+ );
+ const onPressArm = (rule: string) =>
+ [ON_ARM, FADING_ARM].some(arm => selectorOf(rule).includes(arm));
+ return layer.length > 0 && layer.every(onPressArm);
+}
+
+/**
+ * Under any pointer but a coarse primary one, does the element keep the
+ * press it always had? Nothing animates `pseudo`, a `::before` is not
+ * created at all (a card's `::after` is the card's own box), there is no
+ * `isolation`, and the strength's release runs on the element on the press
+ * clock.
+ */
+export function keepsPressOutsideCoarse(
+ el: Element,
+ pseudo: '::before' | '::after',
+): boolean {
+ const fine = rulesDeclaredFor(el, UNDER_FINE);
+ const layer = fine.filter(rule => selectorOf(rule).includes(pseudo));
+ const fading = rulesWithSelector(el, FADING_ARM, UNDER_FINE).filter(
+ rule => !onPseudoElement(rule),
+ );
+ const clock = durationsOf(fading);
+ return (
+ (pseudo === '::after' ||
+ !layer.some(rule =>
+ /(^|[{;\s])content:/.test(rule.slice(rule.indexOf('{'))),
+ )) &&
+ !layer.some(rule => /animation-(name|duration):/.test(rule)) &&
+ !fine.some(rule => /isolation:\s*isolate/.test(rule)) &&
+ fading.some(runsAnimation) &&
+ clock.length === 1 &&
+ clock[0] === PRESS_FADE_MS
+ );
+}
diff --git a/packages/core/src/__tests__/stylexDeclarations.ts b/packages/core/src/__tests__/stylexDeclarations.ts
index 230a1b8f83..dc8e44a9ba 100644
--- a/packages/core/src/__tests__/stylexDeclarations.ts
+++ b/packages/core/src/__tests__/stylexDeclarations.ts
@@ -16,7 +16,8 @@
* comparisons meaningless.
*
* Later rules win, matching the cascade for the equal-specificity atomic
- * classes StyleX emits.
+ * classes StyleX emits. Rules that style a pseudo-element of the element are
+ * not its declarations and are skipped.
*
* SYNC: When modified, update this header.
*/
@@ -42,6 +43,11 @@ export function declaredValue(el: Element, property: string): string | null {
if (owner == null || !classes.has(owner)) {
continue;
}
+ // A pseudo-element's declaration (a press layer's `::before`) is that
+ // box's value, not the element's.
+ if (rule.selectorText.includes('::')) {
+ continue;
+ }
const declared = rule.style.getPropertyValue(property);
if (declared !== '') {
value = declared;
diff --git a/packages/core/src/privateAttributes/press.stylex.ts b/packages/core/src/privateAttributes/press.stylex.ts
index 15f0dacf03..5401e4b695 100644
--- a/packages/core/src/privateAttributes/press.stylex.ts
+++ b/packages/core/src/privateAttributes/press.stylex.ts
@@ -6,15 +6,17 @@
/**
* @file privateAttributes/press.stylex.ts
* @input StyleX, the overlay color tokens, the touch press strength
- * (`pressVars`) and the row layer's clocks (utils/rowPressLayer.stylex.ts)
+ * (`pressVars`) and the theme's exit motion tokens
* @output `rowPressLayerStyles`, the compositor press layer for list rows
* (`cell`, `cellOnImage` for a `backgroundImage` row,
- * `cellOnImagePressOnly` for a row whose fill is the hover tone), and
- * `rowPressPaintStyles`, a CheckboxList row's press paint for its box
+ * `cellOnImagePressOnly` for a row whose fill is the hover tone), which
+ * Button also composes; `controlPressLayerStyles`, what Button adds to that
+ * layer (`control`); and `rowPressPaintStyles`, a CheckboxList row's press
+ * paint for its box
* @position Owner module of the private press attribute: the press controller
* (utils/pressFeedback.ts) writes it, and this file reads it. No package
- * entry exports it. Item, TreeList and CheckboxListItem compose its styles;
- * utils/interactionOverlay.cell.test.ts tests the row layer.
+ * entry exports it. Item, TreeList, Button and CheckboxListItem compose its
+ * styles; utils/interactionOverlay.cell.test.ts tests the row layer.
*/
import * as stylex from '@stylexjs/stylex';
@@ -53,7 +55,7 @@ const pressRelease = stylex.keyframes({
});
/**
- * The row layer's clock as CSS: the strength release's clock, the theme's
+ * A press layer's clock as CSS: the strength release's clock, the theme's
* exit duration, so the layer and the strength land together.
*/
const CELL_RELEASE = durationVars['--duration-exit'];
@@ -72,15 +74,15 @@ const RELEASE_EASE = easeVars['--ease-exit'];
export const rowPressLayerStyles = stylex.create({
/**
- * A list row's touch press on a compositor layer (Item, and TreeList's row
- * box), composed AFTER the row's overlay variant (StyleX is last-wins per
+ * A touch press on a compositor layer (Item, TreeList's row box, and
+ * Button), composed AFTER the overlay variant (StyleX is last-wins per
* property). The variant's own touch paint, a gradient whose strength is a
* registered custom property, animates on the main thread: while script
* runs, a pressed row would stay at full strength and every frame of the
* fade would paint. Here the press is an element-sized `::before` under the
* row's content whose OPACITY is the strength: `on` shows it at once and
- * `fading` runs a keyframe animation of its opacity, 1 → 0, on the cell's
- * release clock (`timing.press`), which engines run on the compositor:
+ * `fading` runs a keyframe animation of its opacity, 1 → 0, on the
+ * theme's exit motion tokens, which engines run on the compositor:
* it keeps advancing while the main thread is blocked and lays out and
* paints nothing. Same pixels as the variant's paint at that strength. The
* variant keeps the hover and a mouse's `:active`. The row must be
@@ -262,6 +264,25 @@ export const rowPressLayerStyles = stylex.create({
},
});
+export const controlPressLayerStyles = stylex.create({
+ /**
+ * A control whose press lives on its own surface: Button (and the
+ * IconButton and ToggleButton built on it), composed after
+ * `rowPressLayerStyles.cell` and `cellOnImage`, which give it the row's
+ * compositor press layer under a coarse primary pointer. Button's press
+ * scale runs as a transition: the browser makes a layer for it and drops
+ * that layer at its end, which repaints the button. Under a coarse primary
+ * pointer, a layer kept from the touch to the end of the release keeps the
+ * release free of Paint. With any other pointer nothing here applies.
+ */
+ control: {
+ willChange: {
+ default: null,
+ [COARSE]: {default: null, [PRESSED_ANY]: 'transform'},
+ },
+ },
+});
+
export const rowPressPaintStyles = stylex.create({
// A box reads its nearest row's value, so a list in a row's content keeps
// its own rows' paint.
diff --git a/packages/core/src/utils/interactionOverlay.cell.test.ts b/packages/core/src/utils/interactionOverlay.cell.test.ts
index b4a9fa38aa..993e74ad3c 100644
--- a/packages/core/src/utils/interactionOverlay.cell.test.ts
+++ b/packages/core/src/utils/interactionOverlay.cell.test.ts
@@ -62,7 +62,12 @@ function rulesIn(el: Element, media: string | null): string[] {
walk(rule.cssRules, rule.media.mediaText);
} else if (rule instanceof CSSStyleRule) {
const selector = rule.selectorText;
- const here = media == null ? inside == null : inside?.includes(media);
+ // A `not (…)` query names the media only to exclude it.
+ const here =
+ media == null
+ ? inside == null
+ : inside?.includes(media) === true &&
+ !inside.includes(`not ${media}`);
if (here && classes.some(cls => selector.startsWith(cls))) {
out.push(`${selector} {${rule.style.cssText}}`);
}
diff --git a/packages/core/src/utils/interactionOverlay.exports.test.ts b/packages/core/src/utils/interactionOverlay.exports.test.ts
index 6620786f34..3f77a057d5 100644
--- a/packages/core/src/utils/interactionOverlay.exports.test.ts
+++ b/packages/core/src/utils/interactionOverlay.exports.test.ts
@@ -17,8 +17,8 @@ import {describe, expect, it} from 'vitest';
import * as utils from './index';
import * as overlay from './interactionOverlay.stylex';
-const ROW_LAYER_STYLES = ['cell', 'cellOnImage'];
-const ROW_LAYER_EXPORTS = ['rowPressLayerStyles'];
+const ROW_LAYER_STYLES = ['cell', 'cellOnImage', 'control'];
+const ROW_LAYER_EXPORTS = ['rowPressLayerStyles', 'controlPressLayerStyles'];
describe("the list row's press layer stays internal", () => {
it('is not exported from @astryxdesign/core/utils/interactionOverlay.stylex', () => {