Skip to content

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

TypeScript

fix(theme): a themed :active follows the touch press model (#10420)

Cindy Zhang74f1fb96f657
diff --git a/.changeset/theme-active-follows-touch-press.md b/.changeset/theme-active-follows-touch-press.md
new file mode 100644
index 0000000000..6e8e19a7ab
--- /dev/null
+++ b/.changeset/theme-active-follows-touch-press.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Theming: a theme's `:active` override now follows the touch press model. With a mouse it still paints on `:active`. Under a finger it paints only while Astryx believes the press, so a themed control no longer flashes the theme's press color on the touch itself or while the page scrolls.
+
+@cixzhang
diff --git a/apps/storybook/stories/Theme.stories.tsx b/apps/storybook/stories/Theme.stories.tsx
index e7bd54f9f3..325ce2ab4e 100644
--- a/apps/storybook/stories/Theme.stories.tsx
+++ b/apps/storybook/stories/Theme.stories.tsx
@@ -7,6 +7,8 @@ import {Card} from '@astryxdesign/core/Card';
import {Stack} from '@astryxdesign/core/Stack';
import {Heading} from '@astryxdesign/core/Text';
import {Badge} from '@astryxdesign/core/Badge';
+import {Button} from '@astryxdesign/core/Button';
+import {List, ListItem} from '@astryxdesign/core/List';
import {neutralTheme} from '@astryxdesign/theme-neutral';
// =============================================================================
@@ -426,3 +428,41 @@ export const TokenInspectorStory: StoryObj = {
</div>
),
};
+
+const pressTheme = defineTheme({
+ name: 'themed-press',
+ components: {
+ button: {
+ base: {':active': {backgroundColor: '#7c3aed', color: '#ffffff'}},
+ },
+ item: {
+ base: {':active': {backgroundColor: '#ede9fe'}},
+ },
+ },
+});
+
+const PRESS_ROWS = Array.from({length: 30}, (_, index) => `Row ${index + 1}`);
+
+/**
+ * A theme that overrides `:active` on Button and on list rows. With a mouse
+ * the theme's press paints on `:active`. Under a finger it follows the touch
+ * press model: it paints once the press is believed, never on the touch
+ * itself or through a scroll.
+ */
+export const ThemedPress: StoryObj = {
+ name: 'Themed press',
+ render: () => (
+ <Theme theme={pressTheme} mode="light">
+ <Stack direction="vertical" gap={3}>
+ <Button label="Themed button" variant="secondary" onClick={() => {}} />
+ <div style={{height: 320, overflowY: 'auto'}}>
+ <List aria-label="Themed rows">
+ {PRESS_ROWS.map(row => (
+ <ListItem key={row} label={row} onClick={() => {}} />
+ ))}
+ </List>
+ </div>
+ </Stack>
+ </Theme>
+ ),
+};
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index 219175b686..3eb3839533 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -434,6 +434,11 @@ a measured, sourced difference exists.
unclaimed, which FR19 allows (DEC-14). FR6's
rule that at most one row of a menu is lit still holds, so a finger that
slides from one row to another lights only the row under it.
+ A theme's `:active` override paints with the component's own press paint:
+ under a coarse pointer only while Core believes the press
+ (`data-astryx-press="on"` on the pressed element or around it), so a scroll
+ that starts on a control never shows it; under a fine pointer from the
+ press's start.
- **FR12 — Long press and rubber band are per use.** A long press MUST use the
thresholds its UIKit counterpart uses: 0.5 s and 10 pt for a plain long
press, the measured values for context menus and menus. A rubber band MUST
@@ -1059,6 +1064,7 @@ Motion that FR45 moves, by component. Each component's record carries its own li
| FR45 | Browser frame capture of companion motion in a gesture and a tap component | a sheet's scrim, handle and content fade; a Lightbox's chrome fade; a menu's backdrop | a companion fade on its own duration fails; one driven by the main motion's progress or settle time passes |
| FR9, FR10 | Recognizer unit tests on synthetic streams and browser tests with real touch input | drag, second finger, pinch, page zoom, main-thread block | a second finger that breaks a drag, or a page pinch blocked other than by the author's `touch-action`, fails |
| FR11, FR12 | Press and long-press tests on synthetic streams with explicit timestamps | inside and outside a scroll view; a drag the browser takes; a lift inside; a menu row under a finger; a press on a row of a menu whose rows fit and of one that scrolls; a slide-off lift on a Switch and on a Radio | the wrong profile's timing, a press that survives the browser taking the touch, or a control outside an action group activated other than by the browser's click, outside `spec:AST-020` FR9's slide-off exception, a row of a menu whose rows fit that waits 150 ms, or one of a scrolling menu that does not, or a slide-off lift that completes a control outside `spec:AST-020` FR9's exception, fails |
+| FR11 theme | `generateThemeRules.test.ts` themed-`:active` cases; real-browser forced `:active` on the Themed press story | a theme `:active` on a base and on a variant with a trailing pseudo; fine pointer; coarse pointer with forced `:active` and with the press attribute | a bare theme `:active` rule a coarse pointer matches, or a coarse arm keyed on `:active`, fails |
| FR13 | Resolver unit tests and a server-render test | coarse and fine pointer; narrow, wide and short; server render; hydrating render | a component that answers the conditions differently, or a touch presentation in the server or hydrating render, fails |
| FR14 | Browser tests of a sheet over a scrolled list | scrolled and at its top | a midway handoff fails |
| FR15–FR17 | Recognizer unit tests on synthetic streams with explicit timestamps | exclusive, simultaneous, require-to-fail, nested; a watcher beside a claiming winner; a blocked main thread; a pan at 10 pt per axis | a wrong winner, a late deadline, or a translation that keeps the hysteresis, or a watcher failed or cancelled by a claiming winner fails |
diff --git a/packages/core/src/privateAttributes/press.test.ts b/packages/core/src/privateAttributes/press.test.ts
new file mode 100644
index 0000000000..39099097be
--- /dev/null
+++ b/packages/core/src/privateAttributes/press.test.ts
@@ -0,0 +1,72 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file press.test.ts
+ * @input PRESS_BELIEVED_SELECTOR and hand-built press markup.
+ * @output Which elements a believed press reaches under a coarse pointer.
+ * @position Unit tests for the private press attribute's selector.
+ */
+
+import {afterEach, describe, expect, it} from 'vitest';
+import {PRESS_BELIEVED_SELECTOR} from './press';
+
+function mount(html: string) {
+ document.body.innerHTML = html;
+ return (id: string) =>
+ document.getElementById(id)!.matches(PRESS_BELIEVED_SELECTOR);
+}
+
+afterEach(() => {
+ document.body.innerHTML = '';
+});
+
+describe('PRESS_BELIEVED_SELECTOR', () => {
+ it('reaches the pressed element and the themed parts inside it', () => {
+ // Switch marks its unclassed row; the themed track and thumb sit inside.
+ const matches = mount(`
+ <div id="row" data-astryx-pressable data-astryx-press="on">
+ <span id="track" class="astryx-switch"><span id="thumb"></span></span>
+ </div>`);
+ expect(matches('row')).toBe(true);
+ expect(matches('track')).toBe(true);
+ expect(matches('thumb')).toBe(true);
+ });
+
+ it('does not reach a control inside a pressed row', () => {
+ const matches = mount(`
+ <div id="row" data-astryx-pressable data-astryx-press="on">
+ <span id="label">Label</span>
+ <button id="button" data-astryx-pressable><span id="icon"></span></button>
+ </div>`);
+ expect(matches('row')).toBe(true);
+ expect(matches('label')).toBe(true);
+ expect(matches('button')).toBe(false);
+ expect(matches('icon')).toBe(false);
+ });
+
+ it('does not reach a pressable row around a pressed control', () => {
+ const matches = mount(`
+ <div id="row" data-astryx-pressable>
+ <button id="button" data-astryx-pressable data-astryx-press="on"></button>
+ </div>`);
+ expect(matches('button')).toBe(true);
+ expect(matches('row')).toBe(false);
+ });
+
+ it('reaches a non-pressable themed element around the pressed one', () => {
+ const matches = mount(`
+ <span id="wrapper" class="astryx-checkbox">
+ <input id="input" data-astryx-pressable data-astryx-press="on" />
+ </span>`);
+ expect(matches('wrapper')).toBe(true);
+ });
+
+ it('matches nothing while no press is believed', () => {
+ const matches = mount(`
+ <div id="row" data-astryx-pressable>
+ <button id="button" data-astryx-pressable></button>
+ </div>`);
+ expect(matches('row')).toBe(false);
+ expect(matches('button')).toBe(false);
+ });
+});
diff --git a/packages/core/src/privateAttributes/press.ts b/packages/core/src/privateAttributes/press.ts
new file mode 100644
index 0000000000..cd85f9d311
--- /dev/null
+++ b/packages/core/src/privateAttributes/press.ts
@@ -0,0 +1,31 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file privateAttributes/press.ts
+ * @input None.
+ * @output `PRESS_BELIEVED_SELECTOR`, which matches an element while the press
+ * controller believes a press on it, inside it, or around it.
+ * @position Owner module of the private press attribute. The press controller
+ * (utils/pressFeedback.ts) writes the attribute. Its `.stylex.ts` sibling
+ * writes the styles that read it, and the theme engine (theme/) builds a
+ * themed press on this selector. No package entry exports it.
+ */
+
+const PRESS_ON = '[data-astryx-press="on"]';
+// The public pressable marker (`utils/pressFeedback.ts` PRESSABLE_ATTRIBUTE).
+// The theme engine cannot import that runtime module.
+const PRESSABLE = '[data-astryx-pressable]';
+
+/**
+ * The controller marks the innermost pressable element only. That element can
+ * wrap the themed element (Switch's row) or sit inside it. The selector
+ * matches the marked element, its descendants up to a nested pressable, and a
+ * non-pressable element around it. A pressable row therefore does not paint
+ * the controls inside it, and a pressed control does not paint the pressable
+ * row around it. Each argument has the specificity of one attribute, as
+ * `:active` has one pseudo-class.
+ */
+export const PRESS_BELIEVED_SELECTOR =
+ `:is(${PRESS_ON}, ` +
+ `${PRESS_ON} :where(:not(${PRESSABLE}, ${PRESS_ON} ${PRESSABLE} *)), ` +
+ `:where(:not(${PRESSABLE})):has(${PRESS_ON}))`;
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index d2e4546f9c..bb2ecac6cd 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -184,6 +184,10 @@ export type TokenValue = string | [light: string, dark: string];
* `:hover` would otherwise still match. Style the disabled state through
* `:disabled` instead.
*
+ * An `:active` override follows the touch press model: it applies to a mouse
+ * press, and under a coarse primary pointer it applies while Astryx believes
+ * the press, not on the touch or through a scroll.
+ *
* @example
* ```ts
* {
diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.ts
index 1c43039fe8..5ec4f08246 100644
--- a/packages/core/src/theme/generateThemeRules.test.ts
+++ b/packages/core/src/theme/generateThemeRules.test.ts
@@ -6,6 +6,7 @@
* correct, consistently ordered CSS for both runtime and build paths.
*/
+import {PRESS_BELIEVED_SELECTOR} from '../privateAttributes/press';
import {describe, it, expect, vi} from 'vitest';
import {
defineTheme,
@@ -182,6 +183,73 @@ describe('generateThemeRules', () => {
expect(buttonRule).toContain('light-dark(rgba(5, 54, 89, 0.1)');
});
+ // A themed press follows the touch press model: `:active` stays for a fine
+ // pointer, and under a coarse pointer the press controller's attribute
+ // takes its place, so a finger paints the theme's press only when the
+ // press is believed, never on the touch or through a scroll.
+ it('emits a themed :active as the press model does: :active for a fine pointer, the press attribute under a coarse one', () => {
+ const pressTheme = defineTheme({
+ name: 'press-dual',
+ components: {
+ button: {
+ base: {
+ ':active': {backgroundColor: 'rebeccapurple'},
+ },
+ },
+ },
+ });
+ const css = generateThemeRules(pressTheme).join('\n');
+ const fine = css.match(
+ /@media not all and \(pointer: coarse\) \{\s*([^{]+)\{([^}]*)\}/,
+ );
+ expect(fine?.[1]).toContain('.astryx-button:active');
+ expect(fine?.[2]).toContain('background-color: rebeccapurple');
+ const coarse = css.match(
+ /@media \(pointer: coarse\) \{\s*([^{]+)\{([^}]*)\}/,
+ );
+ expect(coarse?.[1]).toContain(`.astryx-button${PRESS_BELIEVED_SELECTOR}`);
+ expect(coarse?.[1]).not.toContain(':active');
+ expect(coarse?.[2]).toContain('background-color: rebeccapurple');
+ // No bare :active rule a finger would match on the touch.
+ const outsideFineArm = css.replace(
+ /@media not all and \(pointer: coarse\) \{[^{}]*\{[^}]*\}\s*\}/g,
+ '',
+ );
+ expect(outsideFineArm).not.toContain('.astryx-button:active');
+ });
+
+ // The press controller marks Switch's row, which wraps the themed
+ // `astryx-switch`, so the coarse arm reaches a mark around the element.
+ it('reaches a press marked on a wrapper or inside the themed element under a coarse pointer', () => {
+ const pressTheme = defineTheme({
+ name: 'press-dual-switch',
+ components: {
+ switch: {base: {':active': {backgroundColor: 'rebeccapurple'}}},
+ },
+ });
+ const css = generateThemeRules(pressTheme).join('\n');
+ const coarse = css.match(
+ /@media \(pointer: coarse\) \{\s*([^{]+)\{([^}]*)\}/,
+ );
+ expect(coarse?.[1]).toContain(`.astryx-switch${PRESS_BELIEVED_SELECTOR}`);
+ });
+
+ it('keeps the rest of a selector around a themed :active in both arms', () => {
+ const pressTheme = defineTheme({
+ name: 'press-dual-compound',
+ components: {
+ button: {
+ 'variant:primary': {
+ ':active:not(:focus-visible)': {color: 'white'},
+ },
+ },
+ },
+ });
+ const css = generateThemeRules(pressTheme).join('\n');
+ expect(css).toContain(':active:not(:focus-visible)');
+ expect(css).toContain(`${PRESS_BELIEVED_SELECTOR}:not(:focus-visible)`);
+ });
+
it('applies pseudo-class suffixes to the canonical selector', () => {
const pseudoTheme = defineTheme({
name: 'pseudo-canonical',
diff --git a/packages/core/src/theme/generateThemeRules.ts b/packages/core/src/theme/generateThemeRules.ts
index e29c1de708..6c8e290081 100644
--- a/packages/core/src/theme/generateThemeRules.ts
+++ b/packages/core/src/theme/generateThemeRules.ts
@@ -42,6 +42,7 @@ import {
checkDeclarationName,
checkDeclarationValue,
} from './declarationBoundary';
+import {PRESS_BELIEVED_SELECTOR} from '../privateAttributes/press';
/**
* Theme @scope selectors.
@@ -129,6 +130,37 @@ function appendPseudoToSelectorList(selector: string, pseudo: string): string {
return parts.map(part => `${part}${guarded}`).join(', ');
}
+/**
+ * The touch press model (utils/interactionOverlay.stylex.ts, pressFeedback.ts).
+ * A mouse keeps `:active`. Under a coarse primary pointer, the press
+ * controller marks a press it believes. A finger then paints no press on the
+ * touch or through a scroll.
+ */
+const COARSE_POINTER_QUERY = '(pointer: coarse)';
+const ACTIVE_PSEUDO = /:active(?![-\w])/g;
+
+/**
+ * The rules for one themed pseudo-class override. A themed `:active` follows
+ * the press model: the `:active` rule applies only off a coarse pointer, and
+ * under one the press attribute takes `:active`'s place.
+ */
+function pseudoRules(
+ baseSelector: string,
+ pseudo: string,
+ declarations: string,
+): string[] {
+ if (!new RegExp(ACTIVE_PSEUDO.source).test(pseudo)) {
+ return [
+ ` ${appendPseudoToSelectorList(baseSelector, pseudo)} {\n${declarations}\n }`,
+ ];
+ }
+ const pressed = pseudo.replace(ACTIVE_PSEUDO, PRESS_BELIEVED_SELECTOR);
+ return [
+ ` @media not all and ${COARSE_POINTER_QUERY} {\n ${appendPseudoToSelectorList(baseSelector, pseudo)} {\n${declarations}\n }\n }`,
+ ` @media ${COARSE_POINTER_QUERY} {\n ${appendPseudoToSelectorList(baseSelector, pressed)} {\n${declarations}\n }\n }`,
+ ];
+}
+
/** Insert the disabled guard into a `:hover` pseudo, keeping any pseudo-element last. */
function guardHoverPseudo(pseudo: string): string {
if (!/^:hover(?![-\w])/.test(pseudo) || pseudo.includes('[aria-disabled')) {
@@ -1436,9 +1468,7 @@ function generateComponentRules(
sink,
toKebabCase,
);
- parts.push(
- ` ${appendPseudoToSelectorList(baseSelector, pseudo)} {\n${declarations}\n }`,
- );
+ parts.push(...pseudoRules(baseSelector, pseudo, declarations));
}
}
}
diff --git a/packages/core/src/utils/pressableCoverage.test.ts b/packages/core/src/utils/pressableCoverage.test.ts
index c4b2c88b0c..965ab38c0c 100644
--- a/packages/core/src/utils/pressableCoverage.test.ts
+++ b/packages/core/src/utils/pressableCoverage.test.ts
@@ -33,12 +33,14 @@ import {describe, expect, it} from 'vitest';
const SRC = path.resolve(__dirname, '..');
/**
- * The utility, the list row's press layer and the controller define the
+ * The utility, the list row's press layer, the press attribute's owner
+ * module (the selector a themed press uses) and the controller define the
* model; they are not surfaces.
*/
const MODEL_FILES = new Set([
'utils/interactionOverlay.stylex.ts',
'privateAttributes/press.stylex.ts',
+ 'privateAttributes/press.ts',
'utils/pressFeedback.ts',
'utils/pressGesture.ts',
]);