Skip to content

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

TypeScript

fix(core): a card's press overlay paints a finger's press (#8057)

Christopher Chedeaua88f185a1aa1
diff --git a/.changeset/card-press-overlay-touch.md b/.changeset/card-press-overlay-touch.md
new file mode 100644
index 0000000000..e91846e8c2
--- /dev/null
+++ b/.changeset/card-press-overlay-touch.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] ClickableCard, SelectableCard and an interactive Thumbnail now show the pressed overlay under a finger in apps that compile Astryx from source with cascade layers (the Vite and PostCSS integrations, and Storybook). The touch press was written as an arm of a custom property whose own default sits outside the cascade layer the arm lands in, so the default always won and a touch press painted nothing. The press now paints as the overlay's own image, at the press's strength, and fades at the lift; mouse hover and press are unchanged, and the precompiled stylesheet keeps the same pixels.
+
+@vjeux
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8634edd39f..6e149451bc 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1617,6 +1617,16 @@ jobs:
--project chromium \
--output menu-header-footer-output
+ # A card's press overlay paints a finger's press only if its arms win
+ # the cascade of the layered stylesheet Storybook builds, which jsdom
+ # does not model; the real engine shows the pixels under a held touch.
+ - name: Run card press overlay contract
+ run: |
+ pnpm exec playwright test \
+ packages/core/src/__tests__/CardPress.a11y.chromium.spec.ts \
+ --project chromium \
+ --output card-press-output
+
# A menu inside a shadow root must act on the row under a released
# pointer; at the document level a real engine resolves that point to
# the shadow host, which jsdom cannot show.
diff --git a/packages/core/src/ClickableCard/ClickableCard.doc.mjs b/packages/core/src/ClickableCard/ClickableCard.doc.mjs
index 9a164ebee9..6a144cdf50 100644
--- a/packages/core/src/ClickableCard/ClickableCard.doc.mjs
+++ b/packages/core/src/ClickableCard/ClickableCard.doc.mjs
@@ -38,8 +38,7 @@ export const docs = {
container: true,
targets: [{className: 'astryx-clickable-card', visualProps: ['variant']}],
vars: [
- {name: '--_press-overlay', description: 'Fill of the ::after interaction overlay: transparent at rest, the hover overlay token on hover (hover-capable pointers), the pressed overlay token while pressed (`:active` on a mouse; `data-astryx-press="on"` written by the touch press controller under a finger) and the hover token for the release fade. Set on the card element by its own interaction arms.', default: 'transparent', private: true},
- {name: '--_press-overlay-transition', description: 'Duration of the overlay\'s background-color transition: the fast duration token, except 0s while a believed touch press paints so it lands on the first frame.', default: 'var(--duration-fast)', private: true},
+ {name: '--_press-overlay', description: 'Colour of the ::after interaction overlay for the hover and mouse states: transparent at rest, the hover overlay token on hover (hover-capable pointers), the pressed overlay token while a mouse holds `:active`. A press the touch press controller paints (`data-astryx-press`) is the overlay\'s image instead, at the press\'s strength, and the colour yields to it. Set on the card element by its own interaction arms.', default: 'transparent', private: true},
],
},
playground: {
diff --git a/packages/core/src/ClickableCard/ClickableCard.test.tsx b/packages/core/src/ClickableCard/ClickableCard.test.tsx
index ffa4877812..031be76ade 100644
--- a/packages/core/src/ClickableCard/ClickableCard.test.tsx
+++ b/packages/core/src/ClickableCard/ClickableCard.test.tsx
@@ -4,7 +4,12 @@ import {describe, it, expect, vi} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {ClickableCard} from './ClickableCard';
-import {hasReleaseFade, readsPressStrength} from '../__tests__/pressState';
+import {
+ afterPaintsPress,
+ hasReleaseFade,
+ pressArmsShadowedByDefault,
+ readsPressStrength,
+} from '../__tests__/pressState';
describe('ClickableCard', () => {
it('renders children', () => {
@@ -257,11 +262,17 @@ describe('ClickableCard pressed state (touch)', () => {
throw new Error('the card carries no pressable marker');
}
// The controller writes the card; the card owns the strength and its
- // release, and `--_press-overlay` (what the `::after` paints) is the
- // pressed token at that strength on both touch arms.
+ // release, and its `::after` paints the pressed token at that strength
+ // as its image on both arms, its hover and mouse colour yielding.
expect(hasReleaseFade(card)).toBe(true);
expect(readsPressStrength(card, '[data-astryx-press="on"]')).toBe(true);
expect(readsPressStrength(card)).toBe(true);
+ expect(afterPaintsPress(card, '[data-astryx-press="on"]')).toBe(true);
+ expect(afterPaintsPress(card)).toBe(true);
+ // No press arm sits on a custom property the card also declares without
+ // it: in a layered stylesheet that declaration wins and the press never
+ // paints.
+ expect(pressArmsShadowedByDefault(card)).toEqual([]);
});
it('carries none of it when disabled', () => {
diff --git a/packages/core/src/ClickableCard/ClickableCard.tsx b/packages/core/src/ClickableCard/ClickableCard.tsx
index 0a63ec80b0..c9fc344bef 100644
--- a/packages/core/src/ClickableCard/ClickableCard.tsx
+++ b/packages/core/src/ClickableCard/ClickableCard.tsx
@@ -60,7 +60,11 @@ import {disabledInteractionProps} from '../utils/disabledInteraction';
// element the controller writes to (`pressedAlpha`) at the press's strength,
// 1 while on and 1 → 0 over the release, and inherited resolved by the
// `::after` that paints it. See interactionOverlay.stylex.ts.
-const pressedOverlayColor = 'var(--_press-paint)';
+const pressedOverlayImage = 'var(--_press-paint-image)';
+/** Written by the press controller while it paints a press. */
+const PRESSED_ON = '[data-astryx-press="on"]';
+/** Written by the press controller for the press's release. */
+const PRESSED_FADING = '[data-astryx-press="fading"]';
const styles = stylex.create({
interactive: {
@@ -74,16 +78,18 @@ const styles = stylex.create({
},
// Hover and pressed overlay. Hover is guarded by @media (hover: hover) so
// touch devices don't show a stuck hover state; the press has two arms,
- // `:active` for a mouse and `data-astryx-press` for a finger.
+ // `:active` for a mouse and `data-astryx-press` for the press controller.
overlay: {
- // The `::after` layer paints whatever `--_press-overlay` says, and the
- // interaction arms set that variable on the element itself. Setting the
- // pseudo-element's colour from compound keys (`:active::after`) would
- // leave the touch arms unable to outrank the mouse arm: a pseudo-element
- // key carries the highest generated priority, and the `data-astryx-press`
- // attribute the touch press model writes must win over `:active`, which
- // still matches under a finger (see interactionOverlay.stylex.ts). Same
- // enabled guard as the shared overlay utility.
+ // The `::after` layer paints the hover and mouse states as its colour,
+ // `--_press-overlay`, which their arms set on the element itself (same
+ // enabled guard as the shared overlay utility). The press the controller
+ // paints (a finger's, and on a touch-first device a mouse's or a key's)
+ // is the same layer's image, keyed on the `data-astryx-press` attribute
+ // the controller writes. Every arm of that press is a plain property of
+ // the `::after`, which outranks the layer's own defaults in a layered
+ // stylesheet and a flat one alike. A custom property's attribute arm
+ // does not: a layered build emits the property's default outside the
+ // priority layers its attribute arms land in, and the default wins.
'--_press-overlay': {
default: 'transparent',
':where(:not(:disabled,[aria-disabled="true"]))': {
@@ -98,32 +104,42 @@ const styles = stylex.create({
colorVars['--color-overlay-hover'],
':active': colorVars['--color-overlay-pressed'],
},
- // The touch arms paint through the press's strength, which the
- // card's `pressedAlpha` arms own: 1 on the first frame of a believed
- // press, then 1 → 0 over the release. The `::after` inherits the
- // resolved colour and repaints with it on every frame of the fade.
- '[data-astryx-press="on"]': pressedOverlayColor,
- '[data-astryx-press="fading"]': pressedOverlayColor,
},
},
- // A believed touch press paints on the first frame, and the release is the
- // strength's own animation, so neither may pass through the layer's colour
- // transition (it would fade the onset in, and drag behind the release).
- // The mouse states keep the fast fade.
- '--_press-overlay-transition': {
- default: durationVars['--duration-fast'],
- '[data-astryx-press="on"]': '0s',
- '[data-astryx-press="fading"]': '0s',
- },
'::after': {
content: '""',
position: 'absolute',
inset: 0,
pointerEvents: 'none',
- transitionProperty: 'background-color',
- transitionDuration: 'var(--_press-overlay-transition)',
+ // A press the controller paints shows on its first frame and fades on
+ // its strength's own animation, so the colour it replaces drops out at
+ // once rather than crossfading: no transition while it paints. The
+ // mouse states keep the fast fade.
+ transitionProperty: {
+ default: 'background-color',
+ [PRESSED_ON]: 'none',
+ [PRESSED_FADING]: 'none',
+ },
+ transitionDuration: durationVars['--duration-fast'],
transitionTimingFunction: easeVars['--ease-standard'],
- backgroundColor: 'var(--_press-overlay)',
+ // While the controller paints, the colour yields to the image: a
+ // touchscreen beside a fine pointer still matches `:active` under a
+ // finger, and the press would otherwise paint twice.
+ backgroundColor: {
+ default: 'var(--_press-overlay)',
+ [PRESSED_ON]: 'transparent',
+ [PRESSED_FADING]: 'transparent',
+ },
+ // The press at its strength, which the card's `pressedAlpha` arms own:
+ // 1 on the first frame of a believed press, then 1 → 0 over the
+ // release. The `::after` inherits the resolved paint and repaints with
+ // it on every frame of the fade. Read only inside this element's own
+ // arms, so a pressed ancestor's strength never paints here.
+ backgroundImage: {
+ default: null,
+ [PRESSED_ON]: pressedOverlayImage,
+ [PRESSED_FADING]: pressedOverlayImage,
+ },
},
},
// Borderless variants (everything except `default`): drop the transparent
diff --git a/packages/core/src/SelectableCard/SelectableCard.doc.mjs b/packages/core/src/SelectableCard/SelectableCard.doc.mjs
index 456d80579f..67d1adc0e0 100644
--- a/packages/core/src/SelectableCard/SelectableCard.doc.mjs
+++ b/packages/core/src/SelectableCard/SelectableCard.doc.mjs
@@ -39,8 +39,7 @@ export const docs = {
targets: [{className: 'astryx-selectable-card', visualProps: ['selected', 'variant']}],
vars: [
{name: '--selectable-card-ring-color', description: 'Colour of the selection ring drawn for a variant a theme added. The built-in variants each ring in their own border token and ignore this; a theme that adds a variant sets it in the same rule as that variant\'s `backgroundColor`, because no token the component could pick is guaranteed to contrast with a fill it cannot know.', default: 'var(--color-accent)'},
- {name: '--_press-overlay', description: 'Fill of the ::after interaction overlay: transparent at rest, the hover overlay token on hover (hover-capable pointers), the pressed overlay token while pressed (`:active` on a mouse; `data-astryx-press="on"` written by the touch press controller under a finger) and the hover token for the release fade. Set on the card element by its own interaction arms.', default: 'transparent', private: true},
- {name: '--_press-overlay-transition', description: 'Duration of the overlay\'s background-color transition: the fast duration token, except 0s while a believed touch press paints so it lands on the first frame.', default: 'var(--duration-fast)', private: true},
+ {name: '--_press-overlay', description: 'Colour of the ::after interaction overlay for the hover and mouse states: transparent at rest, the hover overlay token on hover (hover-capable pointers), the pressed overlay token while a mouse holds `:active`. A press the touch press controller paints (`data-astryx-press`) is the overlay\'s image instead, at the press\'s strength, and the colour yields to it. Set on the card element by its own interaction arms.', default: 'transparent', private: true},
],
},
playground: {
diff --git a/packages/core/src/SelectableCard/SelectableCard.test.tsx b/packages/core/src/SelectableCard/SelectableCard.test.tsx
index ce4c314569..6279ef0c28 100644
--- a/packages/core/src/SelectableCard/SelectableCard.test.tsx
+++ b/packages/core/src/SelectableCard/SelectableCard.test.tsx
@@ -11,7 +11,12 @@
import {describe, it, expect, vi} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
import {SelectableCard} from './SelectableCard';
-import {hasReleaseFade, readsPressStrength} from '../__tests__/pressState';
+import {
+ afterPaintsPress,
+ hasReleaseFade,
+ pressArmsShadowedByDefault,
+ readsPressStrength,
+} from '../__tests__/pressState';
describe('SelectableCard', () => {
it('renders children', () => {
@@ -202,5 +207,10 @@ describe('SelectableCard pressed state (touch)', () => {
expect(hasReleaseFade(card)).toBe(true);
expect(readsPressStrength(card, '[data-astryx-press="on"]')).toBe(true);
expect(readsPressStrength(card)).toBe(true);
+ expect(afterPaintsPress(card, '[data-astryx-press="on"]')).toBe(true);
+ expect(afterPaintsPress(card)).toBe(true);
+ // In a layered stylesheet a press arm on a custom property the card also
+ // declares without it never applies.
+ expect(pressArmsShadowedByDefault(card)).toEqual([]);
});
});
diff --git a/packages/core/src/SelectableCard/SelectableCard.tsx b/packages/core/src/SelectableCard/SelectableCard.tsx
index eb758cf6d2..0a41a28326 100644
--- a/packages/core/src/SelectableCard/SelectableCard.tsx
+++ b/packages/core/src/SelectableCard/SelectableCard.tsx
@@ -59,7 +59,11 @@ import {useMergedRefs} from '../hooks/useMergedRefs';
// element the controller writes to (`pressedAlpha`) at the press's strength,
// 1 while on and 1 → 0 over the release, and inherited resolved by the
// `::after` that paints it. See interactionOverlay.stylex.ts.
-const pressedOverlayColor = 'var(--_press-paint)';
+const pressedOverlayImage = 'var(--_press-paint-image)';
+/** Written by the press controller while it paints a press. */
+const PRESSED_ON = '[data-astryx-press="on"]';
+/** Written by the press controller for the press's release. */
+const PRESSED_FADING = '[data-astryx-press="fading"]';
const styles = stylex.create({
interactive: {
@@ -78,16 +82,18 @@ const styles = stylex.create({
},
// Hover and pressed overlay. Hover is guarded by @media (hover: hover) so
// touch devices don't show a stuck hover state; the press has two arms,
- // `:active` for a mouse and `data-astryx-press` for a finger.
+ // `:active` for a mouse and `data-astryx-press` for the press controller.
overlay: {
- // The `::after` layer paints whatever `--_press-overlay` says, and the
- // interaction arms set that variable on the element itself. Setting the
- // pseudo-element's colour from compound keys (`:active::after`) would
- // leave the touch arms unable to outrank the mouse arm: a pseudo-element
- // key carries the highest generated priority, and the `data-astryx-press`
- // attribute the touch press model writes must win over `:active`, which
- // still matches under a finger (see interactionOverlay.stylex.ts). Same
- // enabled guard as the shared overlay utility.
+ // The `::after` layer paints the hover and mouse states as its colour,
+ // `--_press-overlay`, which their arms set on the element itself (same
+ // enabled guard as the shared overlay utility). The press the controller
+ // paints (a finger's, and on a touch-first device a mouse's or a key's)
+ // is the same layer's image, keyed on the `data-astryx-press` attribute
+ // the controller writes. Every arm of that press is a plain property of
+ // the `::after`, which outranks the layer's own defaults in a layered
+ // stylesheet and a flat one alike. A custom property's attribute arm
+ // does not: a layered build emits the property's default outside the
+ // priority layers its attribute arms land in, and the default wins.
'--_press-overlay': {
default: 'transparent',
':where(:not(:disabled,[aria-disabled="true"]))': {
@@ -102,33 +108,43 @@ const styles = stylex.create({
colorVars['--color-overlay-hover'],
':active': colorVars['--color-overlay-pressed'],
},
- // The touch arms paint through the press's strength, which the
- // card's `pressedAlpha` arms own: 1 on the first frame of a believed
- // press, then 1 → 0 over the release. The `::after` inherits the
- // resolved colour and repaints with it on every frame of the fade.
- '[data-astryx-press="on"]': pressedOverlayColor,
- '[data-astryx-press="fading"]': pressedOverlayColor,
},
},
- // A believed touch press paints on the first frame, and the release is the
- // strength's own animation, so neither may pass through the layer's colour
- // transition (it would fade the onset in, and drag behind the release).
- // The mouse states keep the fast fade.
- '--_press-overlay-transition': {
- default: durationVars['--duration-fast'],
- '[data-astryx-press="on"]': '0s',
- '[data-astryx-press="fading"]': '0s',
- },
'::after': {
content: '""',
position: 'absolute',
inset: 0,
borderRadius: 'inherit',
pointerEvents: 'none',
- transitionProperty: 'background-color',
- transitionDuration: 'var(--_press-overlay-transition)',
+ // A press the controller paints shows on its first frame and fades on
+ // its strength's own animation, so the colour it replaces drops out at
+ // once rather than crossfading: no transition while it paints. The
+ // mouse states keep the fast fade.
+ transitionProperty: {
+ default: 'background-color',
+ [PRESSED_ON]: 'none',
+ [PRESSED_FADING]: 'none',
+ },
+ transitionDuration: durationVars['--duration-fast'],
transitionTimingFunction: easeVars['--ease-standard'],
- backgroundColor: 'var(--_press-overlay)',
+ // While the controller paints, the colour yields to the image: a
+ // touchscreen beside a fine pointer still matches `:active` under a
+ // finger, and the press would otherwise paint twice.
+ backgroundColor: {
+ default: 'var(--_press-overlay)',
+ [PRESSED_ON]: 'transparent',
+ [PRESSED_FADING]: 'transparent',
+ },
+ // The press at its strength, which the card's `pressedAlpha` arms own:
+ // 1 on the first frame of a believed press, then 1 → 0 over the
+ // release. The `::after` inherits the resolved paint and repaints with
+ // it on every frame of the fade. Read only inside this element's own
+ // arms, so a pressed ancestor's strength never paints here.
+ backgroundImage: {
+ default: null,
+ [PRESSED_ON]: pressedOverlayImage,
+ [PRESSED_FADING]: pressedOverlayImage,
+ },
},
},
disabled: {
diff --git a/packages/core/src/Thumbnail/Thumbnail.doc.mjs b/packages/core/src/Thumbnail/Thumbnail.doc.mjs
index bf6fbd6aaa..280ebc9197 100644
--- a/packages/core/src/Thumbnail/Thumbnail.doc.mjs
+++ b/packages/core/src/Thumbnail/Thumbnail.doc.mjs
@@ -79,8 +79,7 @@ export const docs = {
],
vars: [
{name: '--_thumbnail-hit-inset', description: 'Outset of the remove button\'s invisible hit area, applied to a ::after overlay. 0 on a fine pointer; negative on a coarse one, which grows the 20px button to the 24px touch target without changing what is drawn.', default: '0px', private: true},
- {name: '--_press-overlay', description: 'Fill of the ::after interaction overlay: transparent at rest, the hover overlay token on hover (hover-capable pointers), the pressed overlay token while pressed (`:active` on a mouse; `data-astryx-press="on"` written by the touch press controller under a finger) and the hover token for the release fade. Set on the card element by its own interaction arms.', default: 'transparent', private: true},
- {name: '--_press-overlay-transition', description: 'Duration of the overlay\'s background-color transition: the fast duration token, except 0s while a believed touch press paints so it lands on the first frame.', default: 'var(--duration-fast)', private: true},
+ {name: '--_press-overlay', description: 'Colour of the ::after interaction overlay for the hover and mouse states: transparent at rest, the hover overlay token on hover (hover-capable pointers), the pressed overlay token while a mouse holds `:active`. A press the touch press controller paints (`data-astryx-press`) is the overlay\'s image instead, at the press\'s strength, and the colour yields to it. Set on the card element by its own interaction arms.', default: 'transparent', private: true},
],
},
usage: {
diff --git a/packages/core/src/Thumbnail/Thumbnail.test.tsx b/packages/core/src/Thumbnail/Thumbnail.test.tsx
index 712487288a..19bc7c36ee 100644
--- a/packages/core/src/Thumbnail/Thumbnail.test.tsx
+++ b/packages/core/src/Thumbnail/Thumbnail.test.tsx
@@ -4,7 +4,12 @@ import {describe, it, expect, vi} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {Thumbnail} from './Thumbnail';
-import {hasReleaseFade, readsPressStrength} from '../__tests__/pressState';
+import {
+ afterPaintsPress,
+ hasReleaseFade,
+ pressArmsShadowedByDefault,
+ readsPressStrength,
+} from '../__tests__/pressState';
describe('Thumbnail', () => {
it('renders an image when src is provided', () => {
@@ -262,6 +267,11 @@ describe('Thumbnail pressed state (touch)', () => {
expect(hasReleaseFade(surface)).toBe(true);
expect(readsPressStrength(surface, '[data-astryx-press="on"]')).toBe(true);
expect(readsPressStrength(surface)).toBe(true);
+ expect(afterPaintsPress(surface, '[data-astryx-press="on"]')).toBe(true);
+ expect(afterPaintsPress(surface)).toBe(true);
+ // In a layered stylesheet a press arm on a custom property the container
+ // also declares without it never applies.
+ expect(pressArmsShadowedByDefault(surface)).toEqual([]);
});
it('carries none of it when not interactive', () => {
diff --git a/packages/core/src/Thumbnail/Thumbnail.tsx b/packages/core/src/Thumbnail/Thumbnail.tsx
index bf537534b2..120a11edba 100644
--- a/packages/core/src/Thumbnail/Thumbnail.tsx
+++ b/packages/core/src/Thumbnail/Thumbnail.tsx
@@ -127,7 +127,11 @@ export interface ThumbnailProps extends BaseProps<HTMLDivElement> {
// element the controller writes to (`pressedAlpha`) at the press's strength,
// 1 while on and 1 → 0 over the release, and inherited resolved by the
// `::after` that paints it. See interactionOverlay.stylex.ts.
-const pressedOverlayColor = 'var(--_press-paint)';
+const pressedOverlayImage = 'var(--_press-paint-image)';
+/** Written by the press controller while it paints a press. */
+const PRESSED_ON = '[data-astryx-press="on"]';
+/** Written by the press controller for the press's release. */
+const PRESSED_FADING = '[data-astryx-press="fading"]';
const styles = stylex.create({
root: {
@@ -178,14 +182,16 @@ const styles = stylex.create({
// shifting shadow or opacity. Guarded by @media (hover: hover) so touch
// devices don't show a stuck hover state; active/pressed works everywhere.
overlay: {
- // The `::after` layer paints whatever `--_press-overlay` says, and the
- // interaction arms set that variable on the element itself. Setting the
- // pseudo-element's colour from compound keys (`:active::after`) would
- // leave the touch arms unable to outrank the mouse arm: a pseudo-element
- // key carries the highest generated priority, and the `data-astryx-press`
- // attribute the touch press model writes must win over `:active`, which
- // still matches under a finger (see interactionOverlay.stylex.ts). Same
- // enabled guard as the shared overlay utility.
+ // The `::after` layer paints the hover and mouse states as its colour,
+ // `--_press-overlay`, which their arms set on the element itself (same
+ // enabled guard as the shared overlay utility). The press the controller
+ // paints (a finger's, and on a touch-first device a mouse's or a key's)
+ // is the same layer's image, keyed on the `data-astryx-press` attribute
+ // the controller writes. Every arm of that press is a plain property of
+ // the `::after`, which outranks the layer's own defaults in a layered
+ // stylesheet and a flat one alike. A custom property's attribute arm
+ // does not: a layered build emits the property's default outside the
+ // priority layers its attribute arms land in, and the default wins.
'--_press-overlay': {
default: 'transparent',
':where(:not(:disabled,[aria-disabled="true"]))': {
@@ -200,33 +206,43 @@ const styles = stylex.create({
colorVars['--color-overlay-hover'],
':active': colorVars['--color-overlay-pressed'],
},
- // The touch arms paint through the press's strength, which the
- // container's `pressedAlpha` arms own: 1 on the first frame of a
- // believed press, then 1 → 0 over the release. The `::after` inherits
- // the resolved colour and repaints with it on every frame of the fade.
- '[data-astryx-press="on"]': pressedOverlayColor,
- '[data-astryx-press="fading"]': pressedOverlayColor,
},
},
- // A believed touch press paints on the first frame, and the release is the
- // strength's own animation, so neither may pass through the layer's colour
- // transition (it would fade the onset in, and drag behind the release).
- // The mouse states keep the fast fade.
- '--_press-overlay-transition': {
- default: durationVars['--duration-fast'],
- '[data-astryx-press="on"]': '0s',
- '[data-astryx-press="fading"]': '0s',
- },
'::after': {
content: '""',
position: 'absolute',
inset: 0,
borderRadius: 'inherit',
pointerEvents: 'none',
- transitionProperty: 'background-color',
- transitionDuration: 'var(--_press-overlay-transition)',
+ // A press the controller paints shows on its first frame and fades on
+ // its strength's own animation, so the colour it replaces drops out at
+ // once rather than crossfading: no transition while it paints. The
+ // mouse states keep the fast fade.
+ transitionProperty: {
+ default: 'background-color',
+ [PRESSED_ON]: 'none',
+ [PRESSED_FADING]: 'none',
+ },
+ transitionDuration: durationVars['--duration-fast'],
transitionTimingFunction: easeVars['--ease-standard'],
- backgroundColor: 'var(--_press-overlay)',
+ // While the controller paints, the colour yields to the image: a
+ // touchscreen beside a fine pointer still matches `:active` under a
+ // finger, and the press would otherwise paint twice.
+ backgroundColor: {
+ default: 'var(--_press-overlay)',
+ [PRESSED_ON]: 'transparent',
+ [PRESSED_FADING]: 'transparent',
+ },
+ // The press at its strength, which the container's `pressedAlpha` arms
+ // own: 1 on the first frame of a believed press, then 1 → 0 over the
+ // release. The `::after` inherits the resolved paint and repaints with
+ // it on every frame of the fade. Read only inside this element's own
+ // arms, so a pressed ancestor's strength never paints here.
+ backgroundImage: {
+ default: null,
+ [PRESSED_ON]: pressedOverlayImage,
+ [PRESSED_FADING]: pressedOverlayImage,
+ },
},
},
interactiveButton: {
diff --git a/packages/core/src/__tests__/CardPress.a11y.chromium.spec.ts b/packages/core/src/__tests__/CardPress.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..9fa4887123
--- /dev/null
+++ b/packages/core/src/__tests__/CardPress.a11y.chromium.spec.ts
@@ -0,0 +1,352 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CardPress.a11y.chromium.spec.ts
+ * @input The ClickableCard, SelectableCard and Thumbnail stories in a built
+ * Storybook (a layered stylesheet), real touch input through CDP and a
+ * real mouse
+ * @output Real-engine proof that a finger's press on a card paints the
+ * pressed overlay a desktop mouse press paints and fades at the lift, and
+ * that where a fine pointer's `:active` also matches under the finger the
+ * press is painted once, not twice
+ * @position Run with `pnpm test:a11y-contract`. Browser layer of the cards'
+ * press overlay; the jsdom layer is each card's own test and
+ * utils/customPropertyArmLayering.test.ts.
+ *
+ * Storybook builds StyleX with cascade layers, where a custom property's
+ * own declaration outranks every attribute arm of it, so this is where a
+ * press painted through such an arm stays invisible.
+ */
+
+import {
+ expect,
+ test,
+ type Browser,
+ type CDPSession,
+ type Page,
+} from '@playwright/test';
+// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.
+import {PNG} from 'pngjs';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+/** A phone: touch screen, primary pointer coarse. */
+const PHONE = {
+ viewport: {width: 402, height: 714},
+ deviceScaleFactor: 1,
+ isMobile: true,
+ hasTouch: true,
+} as const;
+/** A desktop: primary pointer fine. */
+const DESKTOP = {
+ viewport: {width: 1024, height: 768},
+ deviceScaleFactor: 1,
+ isMobile: false,
+ hasTouch: false,
+} as const;
+
+type RGB = [number, number, number];
+type Point = {x: number; y: number};
+
+interface Surface {
+ name: string;
+ story: string;
+ /** Which marked pressable of the story to press. */
+ index: number;
+ /** Where to read the overlay, from the surface's box: clear of content. */
+ sample: (box: {width: number; height: number}) => Point;
+}
+
+const SURFACES: Surface[] = [
+ {
+ name: 'ClickableCard',
+ story: 'core-clickablecard--with-on-click',
+ index: 0,
+ sample: box => ({x: box.width - 24, y: 8}),
+ },
+ {
+ // The second card: the first starts selected.
+ name: 'SelectableCard',
+ story: 'core-selectablecard--single-select',
+ index: 1,
+ sample: box => ({x: box.width - 24, y: 8}),
+ },
+ {
+ name: 'Thumbnail',
+ story: 'core-thumbnail--clickable',
+ index: 0,
+ sample: box => ({x: box.width / 2, y: box.height / 2}),
+ },
+];
+
+/** A flat grey stand-in for remote demo media, so every run reads the same pixels. */
+const GREY_PNG = ((): Buffer => {
+ const png = new PNG({width: 8, height: 8});
+ png.data.fill(128);
+ for (let i = 3; i < png.data.length; i += 4) {
+ png.data[i] = 255;
+ }
+ return PNG.sync.write(png);
+})();
+
+interface Opened {
+ page: Page;
+ /** One session per page: CDP keeps a touch's state per session. */
+ cdp: CDPSession;
+ close: () => Promise<void>;
+ /** The press point and the overlay sample point, in page coordinates. */
+ center: Point;
+ sample: Point;
+}
+
+async function open(
+ browser: Browser,
+ device: typeof PHONE | typeof DESKTOP,
+ surface: Surface,
+): Promise<Opened> {
+ const context = await browser.newContext(device);
+ const page = await context.newPage();
+ await page.route(
+ url => url.origin !== storybook.origin,
+ async route => {
+ if (route.request().resourceType() === 'image') {
+ await route.fulfill({contentType: 'image/png', body: GREY_PNG});
+ } else {
+ await route.abort();
+ }
+ },
+ );
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${surface.story}&viewMode=story`,
+ );
+ const element = page
+ .locator('#storybook-root [data-astryx-pressable]')
+ .nth(surface.index);
+ await element.waitFor();
+ await page.evaluate(async () => {
+ await Promise.all(
+ Array.from(document.images, async image =>
+ image.decode().catch(() => {}),
+ ),
+ );
+ });
+ // The press is the subject, not the activation: keep a selection from
+ // toggling and a link from navigating, so the release reads the rest pixel.
+ await page.evaluate(() => {
+ document.addEventListener('click', event => event.preventDefault(), true);
+ });
+ const box = await element.boundingBox();
+ if (box == null) {
+ throw new Error(`${surface.name} rendered no pressable surface`);
+ }
+ await page.mouse.move(1, 1);
+ const sample = surface.sample(box);
+ return {
+ page,
+ cdp: await context.newCDPSession(page),
+ close: async () => context.close(),
+ center: {x: box.x + box.width / 2, y: box.y + box.height / 2},
+ sample: {x: box.x + sample.x, y: box.y + sample.y},
+ };
+}
+
+/** The mean colour of a 2 × 2 CSS px patch, as presented. */
+async function pixel(page: Page, at: Point): Promise<RGB> {
+ const png = PNG.sync.read(
+ await page.screenshot({
+ clip: {
+ x: Math.round(at.x) - 1,
+ y: Math.round(at.y) - 1,
+ width: 2,
+ height: 2,
+ },
+ animations: 'allow',
+ caret: 'hide',
+ }),
+ );
+ const sum = [0, 0, 0];
+ const count = png.width * png.height;
+ for (let i = 0; i < count; i++) {
+ sum[0] += png.data[i * 4];
+ sum[1] += png.data[i * 4 + 1];
+ sum[2] += png.data[i * 4 + 2];
+ }
+ return sum.map(value => Math.round(value / count)) as RGB;
+}
+
+/** The pixel once two reads a frame apart agree (transitions finished). */
+async function steadyPixel(page: Page, at: Point): Promise<RGB> {
+ let last = await pixel(page, at);
+ for (let tries = 0; tries < 40; tries++) {
+ await page.waitForTimeout(50);
+ const next = await pixel(page, at);
+ if (next.every((value, channel) => value === last[channel])) {
+ return next;
+ }
+ last = next;
+ }
+ return last;
+}
+
+async function pressAttribute(opened: Opened, surface: Surface) {
+ return opened.page
+ .locator('#storybook-root [data-astryx-pressable]')
+ .nth(surface.index)
+ .getAttribute('data-astryx-press');
+}
+
+function expectSameColour(actual: RGB, expected: RGB): void {
+ for (let channel = 0; channel < 3; channel++) {
+ expect(
+ Math.abs(actual[channel] - expected[channel]),
+ `${JSON.stringify(actual)} vs ${JSON.stringify(expected)}`,
+ ).toBeLessThanOrEqual(2);
+ }
+}
+
+async function touch(
+ opened: Opened,
+ type: 'touchStart' | 'touchEnd',
+): Promise<void> {
+ await opened.cdp.send('Input.dispatchTouchEvent', {
+ type,
+ touchPoints:
+ type === 'touchStart'
+ ? [{x: opened.center.x, y: opened.center.y, id: 1}]
+ : [],
+ });
+}
+
+/** Forces (or releases) `:active` on the surface through DevTools. */
+async function forceActive(
+ opened: Opened,
+ surface: Surface,
+ on: boolean,
+): Promise<void> {
+ const {root} = await opened.cdp.send('DOM.getDocument', {depth: 0});
+ const {nodeIds} = await opened.cdp.send('DOM.querySelectorAll', {
+ nodeId: root.nodeId,
+ selector: '#storybook-root [data-astryx-pressable]',
+ });
+ await opened.cdp.send('CSS.enable');
+ await opened.cdp.send('CSS.forcePseudoState', {
+ nodeId: nodeIds[surface.index],
+ forcedPseudoClasses: on ? ['active'] : [],
+ });
+}
+
+/** What a desktop mouse press paints on the surface: the reference. */
+async function desktopPress(
+ browser: Browser,
+ surface: Surface,
+): Promise<{rest: RGB; pressed: RGB}> {
+ const desktop = await open(browser, DESKTOP, surface);
+ try {
+ const rest = await steadyPixel(desktop.page, desktop.sample);
+ await desktop.page.mouse.move(desktop.center.x, desktop.center.y);
+ await desktop.page.mouse.down();
+ const pressed = await steadyPixel(desktop.page, desktop.sample);
+ await desktop.page.mouse.up();
+ return {rest, pressed};
+ } finally {
+ await desktop.close();
+ }
+}
+
+for (const surface of SURFACES) {
+ test(`${surface.name}: a finger's press paints what a desktop press paints, then fades at the lift`, async ({
+ browser,
+ }) => {
+ const reference = await desktopPress(browser, surface);
+ expect(reference.pressed).not.toEqual(reference.rest);
+
+ const phone = await open(browser, PHONE, surface);
+ try {
+ const rest = await steadyPixel(phone.page, phone.sample);
+ expectSameColour(rest, reference.rest);
+
+ await touch(phone, 'touchStart');
+ await phone.page.waitForTimeout(250);
+ expect(await pressAttribute(phone, surface)).toBe('on');
+ expectSameColour(
+ await steadyPixel(phone.page, phone.sample),
+ reference.pressed,
+ );
+
+ await touch(phone, 'touchEnd');
+ expect(await pressAttribute(phone, surface)).toBe('fading');
+ await expect.poll(async () => pressAttribute(phone, surface)).toBeNull();
+ expectSameColour(await steadyPixel(phone.page, phone.sample), rest);
+ } finally {
+ await phone.close();
+ }
+ });
+
+ test(`${surface.name}: a desktop mouse is unchanged: hover, \`:active\`, release, leave`, async ({
+ browser,
+ }) => {
+ const desktop = await open(browser, DESKTOP, surface);
+ try {
+ const rest = await steadyPixel(desktop.page, desktop.sample);
+ await desktop.page.mouse.move(desktop.center.x, desktop.center.y);
+ const hover = await steadyPixel(desktop.page, desktop.sample);
+ await desktop.page.mouse.down();
+ const pressed = await steadyPixel(desktop.page, desktop.sample);
+ // A fine pointer's press is `:active` alone: the controller writes nothing.
+ expect(await pressAttribute(desktop, surface)).toBeNull();
+ await desktop.page.mouse.up();
+ const released = await steadyPixel(desktop.page, desktop.sample);
+ await desktop.page.mouse.move(1, 1);
+ const left = await steadyPixel(desktop.page, desktop.sample);
+ expect(hover).not.toEqual(rest);
+ expect(pressed).not.toEqual(hover);
+ expectSameColour(released, hover);
+ expectSameColour(left, rest);
+ } finally {
+ await desktop.close();
+ }
+ });
+
+ test(`${surface.name}: \`:active\` beside the controller's press paints it once`, async ({
+ browser,
+ }) => {
+ const reference = await desktopPress(browser, surface);
+ // A touchscreen beside a fine pointer: the primary pointer stays fine, so
+ // the mouse arms are live, and a real finger also matches `:active` on
+ // such a device while the controller paints. CDP touch input does not
+ // set `:active`, so DevTools forces it for the length of the press.
+ const laptop = await open(browser, DESKTOP, surface);
+ try {
+ expect(
+ await laptop.page.evaluate(() => matchMedia('(pointer: fine)').matches),
+ ).toBe(true);
+ await touch(laptop, 'touchStart');
+ await laptop.page.waitForTimeout(250);
+ expect(await pressAttribute(laptop, surface)).toBe('on');
+ await forceActive(laptop, surface, true);
+ expectSameColour(
+ await steadyPixel(laptop.page, laptop.sample),
+ reference.pressed,
+ );
+ await forceActive(laptop, surface, false);
+ await touch(laptop, 'touchEnd');
+ } finally {
+ await laptop.close();
+ }
+ });
+}
diff --git a/packages/core/src/__tests__/pressState.ts b/packages/core/src/__tests__/pressState.ts
index 8caabfda94..352f450af3 100644
--- a/packages/core/src/__tests__/pressState.ts
+++ b/packages/core/src/__tests__/pressState.ts
@@ -5,7 +5,8 @@
* @input Uses document.styleSheets (populated by StyleX runtime injection) and
* the press machine's release clock (utils/pressGesture.ts)
* @output Exports rulesDeclaredFor, rulesWithSelector, hasPressedArm,
- * declaresPressedOverlay, readsPressStrength and hasReleaseFade test helpers
+ * declaresPressedOverlay, readsPressStrength, afterPaintsPress,
+ * pressArmsShadowedByDefault and hasReleaseFade test helpers
* @position Shared test helper for asserting a control paints a pressed state
*
* jsdom does not compute `:active` (there is no real pointer), so a component
@@ -120,6 +121,47 @@ export function readsPressStrength(el: Element, arm = FADING_ARM): boolean {
);
}
+/**
+ * Does the element's `::after` paint the press the controller writes as its
+ * image while `arm` matches (`var(--_press-paint-image)`), with the layer's
+ * own colour yielding to it (`transparent`) on the same arm? A card's overlay
+ * layer paints this way; `arm` defaults to the release's.
+ */
+export function afterPaintsPress(el: Element, arm = FADING_ARM): boolean {
+ const rules = rulesWithSelector(el, arm).filter(rule =>
+ rule.slice(0, rule.indexOf('{')).includes('::after'),
+ );
+ return (
+ rules.some(rule =>
+ /background-image:\s*var\(--_press-paint-image\)/.test(rule),
+ ) && rules.some(rule => /background-color:\s*transparent/.test(rule))
+ );
+}
+
+/**
+ * The custom properties the element sets on a `data-astryx-press` arm that it
+ * also declares without that attribute (unconditionally, or on a pseudo-class
+ * or media arm). A layered stylesheet emits such a property's other
+ * declarations outside the priority layers its attribute arms land in, and
+ * those win whatever the arm's specificity, so the press never applies. An
+ * element passes when this is empty.
+ */
+export function pressArmsShadowedByDefault(el: Element): string[] {
+ const keyedOnPress = (rule: string) =>
+ rule.slice(0, rule.indexOf('{')).includes('[data-astryx-press');
+ const declared = (rule: string) =>
+ Array.from(rule.slice(rule.indexOf('{')).matchAll(/(--[\w-]+)\s*:/g)).map(
+ match => match[1],
+ );
+ const rules = rulesDeclaredFor(el);
+ const elsewhere = new Set(
+ rules.filter(rule => !keyedOnPress(rule)).flatMap(declared),
+ );
+ return Array.from(
+ new Set(rules.filter(keyedOnPress).flatMap(declared)),
+ ).filter(name => elsewhere.has(name));
+}
+
/**
* Does the element declare the press's paint, `--_press-paint`, as the pressed
* token at the press's strength? That declaration lives in the shared overlay
diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.ts
index 97395a1616..681fddf513 100644
--- a/packages/core/src/theme/derivedVarRegistry.test.ts
+++ b/packages/core/src/theme/derivedVarRegistry.test.ts
@@ -292,12 +292,11 @@ const VARS_WITHOUT_DERIVED_MAPPING = new Set([
// properties a theme author sets on the component.
'--_thumbnail-hit-inset',
'--_input-clear-hit-inset',
- // The interaction overlay's fill and its transition on the ::after layer of
- // the cards: written by the component's own hover / pressed arms (mouse
- // `:active`, touch `data-astryx-press`), never a value a theme author sets; the
- // overlay colours themselves are the shared interaction tokens.
+ // The interaction overlay's colour on the ::after layer of the cards:
+ // written by the component's own hover and mouse `:active` arms, never a
+ // value a theme author sets; the overlay colours themselves are the shared
+ // interaction tokens.
'--_press-overlay',
- '--_press-overlay-transition',
// The touch press's paint at its current strength, declared once by the
// shared overlay styles on the element the controller writes to and read
// by whatever paints it. A theme sets `--color-overlay-pressed`, not this.
diff --git a/packages/core/src/utils/customPropertyArmLayering.test.ts b/packages/core/src/utils/customPropertyArmLayering.test.ts
new file mode 100644
index 0000000000..8fc64aa78b
--- /dev/null
+++ b/packages/core/src/utils/customPropertyArmLayering.test.ts
@@ -0,0 +1,131 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file customPropertyArmLayering.test.ts
+ * @input Every non-test source file under packages/core/src
+ * @output A guard that no StyleX custom property pairs a default of its own
+ * with an attribute-selector arm (`'[data-…]'`, the press arms included)
+ * @position Testing; the cascade half of the touch press model's contract
+ * (pressableCoverage.test.ts is the reach half)
+ *
+ * A layered stylesheet (StyleX's `useLayers`, which Storybook, the Vite
+ * integration and the PostCSS plugin use) emits its lowest priority group
+ * without a layer: the theme's variables, and with them every custom
+ * property's own declarations and pseudo-class arms. An unlayered
+ * declaration beats a layered one whatever the specificity. An attribute arm
+ * lands in a priority layer, so `'--x': {default: …, '[data-astryx-press="on"]': …}`
+ * never applies there, though the flat package stylesheet, which orders by
+ * specificity instead, applies it. Put the arm on a plain property instead
+ * (as the cards' `::after` does for the press), or give the custom property
+ * no default of its own (as `pressedAlpha` does for the press's strength).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {describe, expect, it} from 'vitest';
+
+const SRC = path.resolve(__dirname, '..');
+
+function* sourceFiles(dir: string): Generator<string> {
+ for (const entry of fs.readdirSync(dir)) {
+ const full = path.join(dir, entry);
+ if (fs.statSync(full).isDirectory()) {
+ if (entry !== 'node_modules' && entry !== 'dist') {
+ yield* sourceFiles(full);
+ }
+ } else if (/\.tsx?$/.test(entry) && !/\.test\.tsx?$/.test(entry)) {
+ yield full;
+ }
+ }
+}
+
+/** The text of the object literal whose `{` sits at `open`, braces balanced. */
+function objectAt(code: string, open: number): string {
+ let depth = 0;
+ for (let i = open; i < code.length; i++) {
+ if (code[i] === '{') {
+ depth++;
+ } else if (code[i] === '}') {
+ depth--;
+ if (depth === 0) {
+ return code.slice(open + 1, i);
+ }
+ }
+ }
+ return code.slice(open + 1);
+}
+
+/** The value of the object's own `default:` key (not a nested one), if any. */
+function ownDefault(body: string): string | null {
+ let depth = 0;
+ for (let i = 0; i < body.length; i++) {
+ const char = body[i];
+ if (char === '{' || char === '[' || char === '(') {
+ depth++;
+ } else if (char === '}' || char === ']' || char === ')') {
+ depth--;
+ } else if (depth === 0 && body.startsWith('default:', i)) {
+ const rest = body.slice(i + 'default:'.length);
+ return rest.slice(0, rest.search(/,|$/)).trim();
+ }
+ }
+ return null;
+}
+
+/**
+ * An attribute-selector key (`'[data-astryx-press="on"]'`, `'[aria-busy]'`),
+ * or the press arms by their usual constant names.
+ */
+const ATTRIBUTE_ARM =
+ /(['"])\[[\w-]+(?:[~|^$*]?=[^\]]*)?\]\1\s*:|\[PRESSED_(?:ON|FADING)\]\s*:/;
+
+/** Custom-property keys whose own default stands beside an attribute arm. */
+function shadowedAttributeArms(code: string): string[] {
+ const out: string[] = [];
+ for (const match of code.matchAll(/(['"])(--[\w-]+)\1\s*:\s*\{/g)) {
+ const body = objectAt(code, (match.index ?? 0) + match[0].length - 1);
+ const fallback = ownDefault(body);
+ if (ATTRIBUTE_ARM.test(body) && fallback != null && fallback !== 'null') {
+ out.push(match[2]);
+ }
+ }
+ return out;
+}
+
+describe("a custom property's attribute arm is never shadowed by its own default", () => {
+ it('finds the pattern it guards against', () => {
+ expect(
+ shadowedAttributeArms(`'--_x': {default: 'transparent', ':active': 'red',
+ '[data-astryx-press="on"]': 'blue'}`),
+ ).toEqual(['--_x']);
+ expect(
+ shadowedAttributeArms(
+ `'--_x': {default: '0', '[aria-busy="true"]': '1'}`,
+ ),
+ ).toEqual(['--_x']);
+ expect(
+ shadowedAttributeArms(`'--_x': {default: 1, [PRESSED_FADING]: 0}`),
+ ).toEqual(['--_x']);
+ expect(
+ shadowedAttributeArms(`'--_x': {default: null, [PRESSED_ON]: 1}`),
+ ).toEqual([]);
+ expect(
+ shadowedAttributeArms(`'--_x': {default: 'a', ':hover': 'b'}`),
+ ).toEqual([]);
+ });
+
+ it('holds across the core source', () => {
+ const offenders: string[] = [];
+ for (const file of sourceFiles(SRC)) {
+ // Comments describe the pattern in words; only code counts.
+ const code = fs
+ .readFileSync(file, 'utf8')
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/^\s*\/\/.*$/gm, '');
+ for (const name of shadowedAttributeArms(code)) {
+ offenders.push(`${path.relative(SRC, file)}: ${name}`);
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
+});