An open source design system that's fully customizable and agent ready
TypeScript
feat(core): touch press model — a delegated controller replaces :active under a coarse pointer (#6383)
Christopher Chedeau33a14a20527e
diff --git a/.changeset/touch-press-controller.md b/.changeset/touch-press-controller.mdnew file mode 100644index 0000000000..845bff460c--- /dev/null+++ b/.changeset/touch-press-controller.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Touch press model: under a coarse pointer the bare `:active` arm is dropped and a delegated, document-level controller paints the press the way a native list does — nothing for 150 ms, then the full pressed overlay on the next frame; cancelled with no fade by 10 px of travel or by a scroll claiming the gesture, and dead until a new touch; a tap shorter than the delay paints at the lift; the release fades over 200 ms, a real fade on every surface: the pressed overlay is the pressed token at `--astryx-press-alpha`, a registered custom property (`@property`, syntax `<number>`) the release arm animates 1 → 0, declared once by the shared overlay styles as `--_press-paint` and read by whatever paints it. The controller writes `data-astryx-press="on"|"fading"` on the nearest element marked `data-astryx-pressable`, which every Astryx surface that paints a press now carries; a mouse keeps `:active`. Public API for a local pressable: `usePressFeedback()` from `@astryxdesign/core/hooks` (returns the marker to spread; installs the controller on first mount) and `interactionOverlayStyles` from `@astryxdesign/core/utils` (compose one of its variants on the marked element). A press is themed through `--color-overlay-pressed`, which the hold, the flash and the fade all read.++@vjeuxdiff --git a/.github/scripts/press-release-fade.js b/.github/scripts/press-release-fade.jsnew file mode 100644index 0000000000..b50b974686--- /dev/null+++ b/.github/scripts/press-release-fade.js@@ -0,0 +1,298 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @description Proves the touch press's release FADES in a real engine: the+ * pressed overlay on a Button, sampled frame by frame through the+ * `data-pressed="fading"` arm, interpolates from the pressed strength to+ * nothing over the release clock rather than stepping+ * @input [--storybook-dir <path>] [--story <id>] [--port <n>] [--webkit]+ * @output The sampled overlay alpha at ~0, 100 and 200 ms into the release (and+ * the whole trace), per engine; exit 1 when the samples are not three+ * distinct, monotonically falling values, when the paint is still there+ * past the clock, or when the onset was not instant+ *+ * WHY A BROWSER: jsdom runs no animation and computes no `color-mix()`, so the+ * unit tests can only hold the DECLARATION (the fading arm carries the release+ * animation on the machine's clock; the paint reads the registered strength).+ * Whether a gradient layer written as+ * `linear-gradient(color-mix(in srgb, pressed calc(var(--astryx-press-alpha)+ * * 100%), transparent), ...)` actually re-resolves on every frame of an+ * animation of that registered custom property is an engine fact, and it is+ * the whole mechanism (see utils/interactionOverlay.stylex.ts). The Button is+ * the sharpest case: it transitions `background-image` itself, and a+ * composer's own transition must not take the release over.+ *+ * The page is the checked-in `Core/Press feedback (touch)` › Buttons story out+ * of a built Storybook, under Chromium's touch emulation (`pointer: coarse`,+ * no hover), the same artifact the accessibility contracts drive:+ *+ * pnpm storybook:build+ * pnpm exec playwright install chromium # and `webkit` for --webkit+ * pnpm guard:press-release-fade+ *+ * The controller is not driven here — its clocks are unit-tested in+ * utils/pressFeedback.test.ts — the attribute is written the way it writes it,+ * and the paint is read off the pixels' source of truth, the computed style.+ */++const {chromium, webkit} = require('playwright');+const fs = require('node:fs');+const http = require('node:http');+const path = require('node:path');++const args = process.argv.slice(2);+const getArg = name => {+ const index = args.indexOf(`--${name}`);+ return index === -1 ? null : args[index + 1];+};+const hasFlag = name => args.includes(`--${name}`);++const storybookDir = path.resolve(+ process.cwd(),+ getArg('storybook-dir') || 'apps/storybook/dist',+);+const storyId = getArg('story') || 'core-press-feedback-touch--buttons';+const port = Number(getArg('port') || 0);++/**+ * The release clock, read from the machine so this probe cannot drift from+ * it: `PRESS_FADE_MS` in packages/core/src/utils/pressGesture.ts.+ */+function releaseClockMs() {+ const source = fs.readFileSync(+ path.resolve(process.cwd(), 'packages/core/src/utils/pressGesture.ts'),+ 'utf8',+ );+ const match = source.match(/export const PRESS_FADE_MS = (\d+);/);+ if (!match) {+ throw new Error('PRESS_FADE_MS not found in pressGesture.ts');+ }+ return Number(match[1]);+}++const MIME = {+ '.html': 'text/html',+ '.js': 'text/javascript',+ '.mjs': 'text/javascript',+ '.css': 'text/css',+ '.json': 'application/json',+ '.svg': 'image/svg+xml',+ '.png': 'image/png',+ '.woff': 'font/woff',+ '.woff2': 'font/woff2',+};++function serve(dir) {+ return new Promise(resolve => {+ const server = http.createServer((request, response) => {+ const url = new URL(request.url, 'http://127.0.0.1');+ const file = path.join(dir, decodeURIComponent(url.pathname));+ if (!file.startsWith(dir) || !fs.existsSync(file)) {+ response.writeHead(404);+ response.end();+ return;+ }+ response.writeHead(200, {+ 'Content-Type': MIME[path.extname(file)] || 'application/octet-stream',+ });+ fs.createReadStream(file).pipe(response);+ });+ server.listen(port, '127.0.0.1', () =>+ resolve({server, port: server.address().port}),+ );+ });+}++/**+ * Runs in the page. Writes the attribute the way the controller does and+ * samples the overlay on every frame: the registered strength and the alpha+ * of the gradient layer's first colour, parsed off the computed+ * `background-image` (`rgba(r, g, b, a)` or `color(srgb r g b / a)`).+ */+async function sampleRelease(button, clockMs) {+ const frame = () => new Promise(resolve => requestAnimationFrame(resolve));+ const alphaOf = image => {+ // A colour channel may serialize in exponent form near zero (`9.8e-7`).+ const number = '[\\d.]+(?:e[+-]?\\d+)?';+ const legacy = image.match(+ new RegExp(`rgba?\\(\\s*${number},\\s*${number},\\s*${number}(?:,\\s*(${number}))?\\s*\\)`),+ );+ if (legacy) {+ return legacy[1] == null ? 1 : Number(legacy[1]);+ }+ const modern = image.match(new RegExp(`color\\(srgb[^)]*?/\\s*(${number})\\s*\\)`));+ if (modern) {+ return Number(modern[1]);+ }+ return image === 'none' ? 0 : Number.NaN;+ };+ const read = () => {+ const style = getComputedStyle(button);+ return {+ strength: Number(style.getPropertyValue('--astryx-press-alpha')),+ alpha: alphaOf(style.backgroundImage),+ image: style.backgroundImage,+ };+ };++ const rest = read();+ button.setAttribute('data-pressed', 'on');+ await frame();+ const onFirstFrame = read();+ await frame();+ await frame();+ const onHeld = read();++ const trace = [];+ const start = performance.now();+ button.setAttribute('data-pressed', 'fading');+ // The attribute is on; the first sample is this same frame, before the+ // engine has advanced the animation.+ while (performance.now() - start < clockMs + 80) {+ trace.push({t: performance.now() - start, ...read()});+ await frame();+ }+ button.removeAttribute('data-pressed');+ await frame();+ const after = read();+ return {rest, onFirstFrame, onHeld, trace, after};+}++function nearest(trace, t) {+ return trace.reduce((best, sample) =>+ Math.abs(sample.t - t) < Math.abs(best.t - t) ? sample : best,+ );+}++const fmt = n => (Number.isFinite(n) ? n.toFixed(4) : String(n));++async function probe(browserType, name, origin, clockMs, failures) {+ let browser;+ try {+ browser = await browserType.launch();+ } catch (error) {+ console.log(`- ${name}: not installed, skipped (${error.message.split('\n')[0]})`);+ return null;+ }+ try {+ const context = await browser.newContext({+ hasTouch: true,+ isMobile: true,+ viewport: {width: 390, height: 844},+ });+ const page = await context.newPage();+ await page.goto(`${origin}/iframe.html?id=${storyId}&viewMode=story`, {+ waitUntil: 'load',+ });+ const button = page.locator('#storybook-root button:not([disabled])').first();+ await button.waitFor({state: 'attached'});++ const media = await page.evaluate(() => ({+ coarse: matchMedia('(pointer: coarse)').matches,+ hover: matchMedia('(hover: hover)').matches,+ }));+ if (!media.coarse || media.hover) {+ failures.push(+ `${name}: touch context reports pointer: coarse=${media.coarse}, hover: hover=${media.hover}`,+ );+ }+ const marked = await button.getAttribute('data-astryx-pressable');+ if (marked == null) {+ failures.push(`${name}: the button carries no data-astryx-pressable marker`);+ }++ const result = await button.evaluate(sampleRelease, clockMs);+ const {rest, onFirstFrame, onHeld, trace, after} = result;+ const at0 = trace[0];+ const at100 = nearest(trace, clockMs / 2);+ const at200 = nearest(trace, clockMs);+ const last = trace[trace.length - 1];++ console.log(`\n${name}:`);+ console.log(` rest alpha ${fmt(rest.alpha)} strength ${fmt(rest.strength)} (${rest.image})`);+ console.log(` on, frame 1 alpha ${fmt(onFirstFrame.alpha)} strength ${fmt(onFirstFrame.strength)}`);+ console.log(` on, held alpha ${fmt(onHeld.alpha)} strength ${fmt(onHeld.strength)}`);+ console.log(' fading:');+ for (const sample of [at0, at100, at200]) {+ console.log(` t=${sample.t.toFixed(1).padStart(6)} ms alpha ${fmt(sample.alpha)} strength ${fmt(sample.strength)}`);+ }+ console.log(` last sampled t=${last.t.toFixed(1)} ms alpha ${fmt(last.alpha)} strength ${fmt(last.strength)}`);+ console.log(` after removal alpha ${fmt(after.alpha)} (${after.image})`);+ console.log(+ ` trace (${trace.length} frames): ${trace.map(s => `${s.t.toFixed(0)}:${s.alpha.toFixed(3)}`).join(' ')}`,+ );++ // The onset is instant and complete: full pressed strength on the first+ // frame, and no stronger when held.+ if (!(onFirstFrame.strength === 1 && onFirstFrame.alpha > 0)) {+ failures.push(`${name}: the onset did not paint on the first frame (alpha ${fmt(onFirstFrame.alpha)}, strength ${fmt(onFirstFrame.strength)})`);+ }+ if (Math.abs(onHeld.alpha - onFirstFrame.alpha) > 1e-3) {+ failures.push(`${name}: the onset faded in (frame 1 alpha ${fmt(onFirstFrame.alpha)}, held ${fmt(onHeld.alpha)})`);+ }+ // The release interpolates: three distinct, falling values...+ const distinct = new Set([at0.alpha, at100.alpha, at200.alpha].map(a => a.toFixed(4)));+ if (distinct.size !== 3 || !(at0.alpha > at100.alpha && at100.alpha > at200.alpha)) {+ failures.push(`${name}: the release did not interpolate (alpha ${fmt(at0.alpha)} → ${fmt(at100.alpha)} → ${fmt(at200.alpha)})`);+ }+ // ...starting from the pressed strength, monotonic all the way...+ if (Math.abs(at0.alpha - onHeld.alpha) > 1e-3) {+ failures.push(`${name}: the release did not start from the pressed strength (${fmt(at0.alpha)} vs ${fmt(onHeld.alpha)})`);+ }+ const bumps = trace.filter((s, i) => i > 0 && s.alpha > trace[i - 1].alpha + 1e-4);+ if (bumps.length > 0) {+ failures.push(`${name}: the release is not monotonic (${bumps.length} frame(s) rose: ${bumps.map(s => `${s.t.toFixed(0)}ms ${fmt(s.alpha)}`).join(', ')})`);+ }+ // ...and gone by the clock the controller removes the attribute on.+ if (!(at200.alpha <= onHeld.alpha * 0.02 && last.strength === 0)) {+ failures.push(`${name}: the paint outlived the release clock (alpha ${fmt(at200.alpha)} at ${at200.t.toFixed(0)} ms, strength ${fmt(last.strength)} at ${last.t.toFixed(0)} ms)`);+ }+ if (after.alpha !== 0) {+ failures.push(`${name}: paint left behind after the attribute was removed (${after.image})`);+ }+ await context.close();+ return {at0, at100, at200, onHeld, trace};+ } finally {+ await browser.close();+ }+}++async function run() {+ if (!fs.existsSync(path.join(storybookDir, 'iframe.html'))) {+ throw new Error(+ `${storybookDir} has no iframe.html — run \`pnpm storybook:build\` first.`,+ );+ }+ const clockMs = releaseClockMs();+ console.log(`Release clock: ${clockMs} ms (PRESS_FADE_MS). Story: ${storyId}`);+ const {server, port: servedPort} = await serve(storybookDir);+ const origin = `http://127.0.0.1:${servedPort}`;+ const failures = [];+ try {+ await probe(chromium, 'Chromium', origin, clockMs, failures);+ if (hasFlag('webkit')) {+ await probe(webkit, 'WebKit', origin, clockMs, failures);+ }+ } finally {+ server.close();+ }+ if (failures.length > 0) {+ console.error('');+ for (const failure of failures) console.error(`✗ ${failure}`);+ return 1;+ }+ console.log('\nThe release fades: the pressed overlay interpolates to nothing over the release clock.');+ return 0;+}++if (require.main === module) {+ run()+ .then(code => {+ process.exitCode = code;+ })+ .catch(error => {+ console.error('Press release fade guard failed:', error);+ process.exit(1);+ });+}diff --git a/apps/storybook/stories/PressFeedback.stories.tsx b/apps/storybook/stories/PressFeedback.stories.tsxnew file mode 100644index 0000000000..f788d42bd5--- /dev/null+++ b/apps/storybook/stories/PressFeedback.stories.tsx@@ -0,0 +1,161 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {Button} from '@astryxdesign/core/Button';+import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';+import {ClickableCard} from '@astryxdesign/core/ClickableCard';+import {Collapsible} from '@astryxdesign/core/Collapsible';+import {DropdownMenu, DropdownMenuItem} from '@astryxdesign/core/DropdownMenu';++import {Item} from '@astryxdesign/core/Item';+import {Link} from '@astryxdesign/core/Link';+import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList';+import {+ SegmentedControl,+ SegmentedControlItem,+} from '@astryxdesign/core/SegmentedControl';+import {Switch} from '@astryxdesign/core/Switch';+import {Tab, TabList} from '@astryxdesign/core/TabList';+import {Text} from '@astryxdesign/core/Text';+import {VStack} from '@astryxdesign/core/Layout';++/**+ * The touch press model, on every kind of pressable surface.+ *+ * View these with a coarse pointer: in Chromium, open DevTools, toggle the+ * device toolbar (a phone preset), and use the touch cursor; or open Storybook+ * on a phone. Under a finger the bare `:active` arm is dropped and the press+ * follows the clocks a native list uses: nothing paints for 150 ms; a held+ * press then paints the full pressed overlay on the next frame; travelling+ * 10 px, or a scroll claiming the gesture, cancels it with no fade and nothing+ * repaints until a new touch; a tap shorter than the delay paints at the lift;+ * the release fades over 200 ms. A mouse keeps `:active`.+ */+const meta: Meta = {+ title: 'Core/Press feedback (touch)',+ parameters: {+ layout: 'padded',+ docs: {+ description: {+ component:+ 'The touch press model on every pressable surface. View with a coarse pointer (DevTools device toolbar, or a phone). Under a finger the bare `:active` arm is dropped and one document-level controller writes `data-astryx-press="on"` once a press is believed (150 ms, no travel, no scroll) and `data-astryx-press="fading"` for the 200 ms release; a scroll or 10 px of travel cancels with no fade, and nothing repaints until a new touch. A mouse keeps `:active`. Scroll the list stories with a finger: no row paints while the list moves.',+ },+ },+ },+};++export default meta;+type Story = StoryObj;++const touchNote = (what: string) =>+ `${what} Hold: paints after 150 ms. Tap: paints at the lift. Drag or scroll: never paints, and stays dark until the finger lifts and lands again.`;++export const Buttons: Story = {+ parameters: {+ docs: {description: {story: touchNote('Buttons under a finger.')}},+ },+ render: () => (+ <VStack gap={3}>+ <Button label="Primary" variant="primary" />+ <Button label="Secondary" variant="secondary" />+ <Button label="Ghost" variant="ghost" />+ <Button label="Destructive" variant="destructive" />+ <Button label="Disabled — never presses" isDisabled />+ </VStack>+ ),+};++export const Rows: Story = {+ parameters: {+ docs: {+ description: {+ story: touchNote(+ 'Item rows, a menu, and a clickable card. The list scrolls: flick it and no row paints; stop it with a finger and that touch is a brake, not a press.',+ ),+ },+ },+ },+ render: () => (+ <VStack gap={4}>+ <div+ style={{+ height: 220,+ overflowY: 'auto',+ border: '1px solid transparent',+ }}>+ {Array.from({length: 24}, (_, index) => (+ <Item+ key={index}+ label={`Conversation ${index + 1}`}+ description="Press and hold, or scroll past"+ onClick={() => {}}+ />+ ))}+ </div>+ <DropdownMenu button={{label: 'Menu'}}>+ <DropdownMenuItem label="Rename" onClick={() => {}} />+ <DropdownMenuItem label="Duplicate" onClick={() => {}} />+ <DropdownMenuItem+ label="Delete"+ variant="destructive"+ onClick={() => {}}+ />+ </DropdownMenu>+ <ClickableCard label="A clickable card" onClick={() => {}}>+ <Text>A clickable card: press and hold</Text>+ </ClickableCard>+ </VStack>+ ),+};++export const Controls: Story = {+ parameters: {+ docs: {+ description: {+ story: touchNote(+ 'The eight components that gained a pressed state, under a finger.',+ ),+ },+ },+ },+ render: () => {+ const [on, setOn] = useState(false);+ const [checked, setChecked] = useState<boolean | 'indeterminate'>(false);+ const [radio, setRadio] = useState('email');+ const [segment, setSegment] = useState('grid');+ const [tab, setTab] = useState('home');+ return (+ <VStack gap={4}>+ <Switch label="Notifications" value={on} onChange={setOn} />+ <CheckboxInput+ label="Accept terms"+ value={checked}+ onChange={setChecked}+ />+ <RadioList label="Channel" value={radio} onChange={setRadio}>+ <RadioListItem label="Email" value="email" />+ <RadioListItem label="SMS" value="sms" />+ </RadioList>+ <SegmentedControl value={segment} onChange={setSegment} label="View">+ <SegmentedControlItem value="grid" label="Grid" />+ <SegmentedControlItem value="list" label="List" />+ </SegmentedControl>+ <TabList value={tab} onChange={setTab}>+ <Tab value="home" label="Home" />+ <Tab value="settings" label="Settings" />+ </TabList>+ <Text>+ Read the{' '}+ <Link href="#docs" onClick={e => e.preventDefault()}>+ documentation+ </Link>+ .+ </Text>+ <Collapsible trigger="Details">+ <Text>The trigger row presses.</Text>+ </Collapsible>+ </VStack>+ );+ },+};diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex cbb3e00418..b6a26fd111 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -3810,6 +3810,11 @@"path": "hooks/use-popover","aliases": []},+ {+ "name": "hook-use-press-feedback",+ "path": "hooks/use-press-feedback",+ "aliases": []+ },{"name": "hook-use-resizable","path": "hooks/use-resizable",diff --git a/package.json b/package.jsonindex 114d97c8b7..4819814cb3 100644--- a/package.json+++ b/package.json@@ -48,6 +48,7 @@"guard:theme-layers": "node .github/scripts/theme-layer-cascade.js","guard:disabled-hover": "node .github/scripts/disabled-hover-audit.js","guard:pressed-overlay": "node .github/scripts/pressed-overlay-cascade.js",+ "guard:press-release-fade": "node .github/scripts/press-release-fade.js","guard:disabled-cursor": "node .github/scripts/disabled-cursor-audit.js","storybook": "pnpm -F @astryxdesign/storybook dev","storybook:build": "pnpm -F @astryxdesign/storybook build",diff --git a/packages/cli/test/doc-routes.ids.json b/packages/cli/test/doc-routes.ids.jsonindex f53ae51db1..9d2b0fed48 100644--- a/packages/cli/test/doc-routes.ids.json+++ b/packages/cli/test/doc-routes.ids.json@@ -221,6 +221,7 @@"useMergedRefs","useOverflow","usePopover",+ "usePressFeedback","useResizable","useScrollableArea","useScrollLock",diff --git a/packages/core/src/AvatarGroup/AvatarGroupOverflow.tsx b/packages/core/src/AvatarGroup/AvatarGroupOverflow.tsxindex 158c2d6e9f..62103c7352 100644--- a/packages/core/src/AvatarGroup/AvatarGroupOverflow.tsx+++ b/packages/core/src/AvatarGroup/AvatarGroupOverflow.tsx@@ -31,6 +31,7 @@ import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useTranslator} from '../i18n';const BORDER_WIDTH = 2;@@ -158,6 +159,7 @@ export function AvatarGroupOverflow({style,...rest}: AvatarGroupOverflowProps): ReactNode {+ const pressable = usePressFeedback();const t = useTranslator();const group = useAvatarGroup();const size = group?.size ?? 'md';@@ -181,6 +183,7 @@ export function AvatarGroupOverflow({{...rest}aria-label={label}data-avatar-item=""+ {...pressable}{...mergeProps(themeProps('avatar-group-overflow', {size, shape}),focusOutlineProps.focusVisible(diff --git a/packages/core/src/Button/Button.test.tsx b/packages/core/src/Button/Button.test.tsxindex f52c7eafb9..da3a8f500d 100644--- a/packages/core/src/Button/Button.test.tsx+++ b/packages/core/src/Button/Button.test.tsx@@ -14,6 +14,11 @@ import {render, screen, fireEvent, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {Button} from './Button';import * as stylex from '@stylexjs/stylex';+import {+ hasPressedArm,+ hasReleaseFade,+ readsPressStrength,+} from '../__tests__/pressState';import {Badge} from '../Badge/Badge';import {ButtonGroup} from '../ButtonGroup';import {IconButton} from '../IconButton';@@ -641,3 +646,18 @@ describe('Button', () => {expect(link).not.toHaveAttribute('aria-busy');});});++describe('Button pressed state (touch)', () => {+ it('fades the touch press out over the release, painting the pressed token at its strength on both arms', () => {+ 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`.+ 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);+ });+});diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsxindex 33c53a07dd..fb52d7c152 100644--- a/packages/core/src/Button/Button.tsx+++ b/packages/core/src/Button/Button.tsx@@ -51,6 +51,7 @@ import type {LinkComponentType} from '../Link/types';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useTranslator} from '../i18n';import type {ButtonVariantMap} from './index';@@ -108,7 +109,14 @@ const styles = stylex.create({pressable: {transform: {default: 'scale(1)',- ':active:where(:not(:disabled,[aria-disabled="true"]))': 'scale(0.98)',+ // A mouse press. Under a coarse pointer `:active` is not a press (it+ // paints on the touch and outlives a scroll), so the touch press model+ // writes `data-astryx-press` instead; see interactionOverlay.stylex.ts.+ ':active:where(:not(:disabled,[aria-disabled="true"]))': {+ default: 'scale(0.98)',+ '@media (pointer: coarse)': 'scale(1)',+ },+ '[data-astryx-press="on"]': 'scale(0.98)',},},inactive: {@@ -117,6 +125,7 @@ const styles = stylex.create({transform: {default: 'none',':active': 'none',+ '[data-astryx-press="on"]': 'none',},},disabled: {@@ -129,6 +138,7 @@ const styles = stylex.create({backgroundImage: {default: 'none',':active': 'none',+ '[data-astryx-press="on"]': 'none',},},iconOnly: {@@ -562,6 +572,7 @@ export function Button({ref,...props}: ButtonProps): ReactNode {+ const pressFeedback = usePressFeedback();const t = useTranslator();const size = useSize(sizeProp, 'md');const buttonGroup = useButtonGroup();@@ -776,6 +787,7 @@ export function Button({target={target}rel={rel}{...sharedMergedProps}+ {...pressFeedback}{...props}{...ariaLabelProp}{...describedByProp}@@ -792,6 +804,7 @@ export function Button({type={type}disabled={useAriaDisabled ? undefined : buttonDisabled}{...sharedMergedProps}+ {...pressFeedback}{...props}{...ariaLabelProp}{...describedByProp}diff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsxindex 71795ea008..a3f433f1aa 100644--- a/packages/core/src/Calendar/Calendar.tsx+++ b/packages/core/src/Calendar/Calendar.tsx@@ -61,6 +61,7 @@ import {import {mergeProps, composeEventHandlers, rtlStyles} from '../utils';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {getInitialFocusDate} from './getInitialFocusDate';import {computeDayCellState,@@ -1035,6 +1036,7 @@ function DayCell({}: DayCellProps) {const t = useTranslator();const locale = useLocale();+ const pressable = usePressFeedback();const {date, isOutside, dayNumber} = day;if (isOutside && !hasOutsideDays) {@@ -1158,6 +1160,7 @@ function DayCell({onClick={() => !state.effectivelyDisabled && onDayClick(date)}onMouseEnter={() => !state.effectivelyDisabled && onDayHover(date)}onMouseLeave={() => onDayHover(null)}+ {...pressable}{...mergeProps(themeProps('calendar-day', {selected: endpoint ? 'selected' : null,diff --git a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx b/packages/core/src/CheckboxInput/CheckboxInput.test.tsxindex fc5dbf64e1..5d4b39281f 100644--- a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx+++ b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx@@ -15,7 +15,11 @@import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {render, screen, fireEvent, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';-import {hasPressedArm} from '../__tests__/pressState';+import {+ hasPressedArm,+ hasReleaseFade,+ readsPressStrength,+} from '../__tests__/pressState';import {CheckboxInput} from './CheckboxInput';import {Theme} from '../theme/Theme';import {defineTheme} from '../theme/defineTheme';@@ -828,4 +832,22 @@ describe('pressed state', () => {}expect(hasPressedArm(wrapper)).toBe(false);});++ it('fades the touch press out from the row, with the overlay reading its strength', () => {+ const {container} = render(+ <CheckboxInput label="Accept terms" value={false} onChange={() => {}} />,+ );+ const box = container.querySelector('.astryx-checkbox-indicator');+ const wrapper = box?.parentElement?.parentElement;+ const row = box?.closest('[data-astryx-pressable]');+ if (wrapper == null || row == null) {+ throw new Error('the checkbox has no pressable row or indicator wrapper');+ }+ // The controller writes the row; the row owns the strength and its+ // release, and the owner-drawn layer over the indicator paints the pressed+ // token at that strength on both touch arms.+ expect(hasReleaseFade(row)).toBe(true);+ expect(readsPressStrength(wrapper, '[data-astryx-press="on"]')).toBe(true);+ expect(readsPressStrength(wrapper)).toBe(true);+ });});diff --git a/packages/core/src/CheckboxInput/CheckboxInput.tsx b/packages/core/src/CheckboxInput/CheckboxInput.tsxindex 98d2dd638b..67447d171c 100644--- a/packages/core/src/CheckboxInput/CheckboxInput.tsx+++ b/packages/core/src/CheckboxInput/CheckboxInput.tsx@@ -46,13 +46,22 @@ import {Spinner} from '../Spinner';import {useTooltip} from '../Tooltip';import {mergeProps, rtlStyles} from '../utils';import {indicatorScope} from '../Indicator/indicator.markers.stylex';+import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';import {useIndicatorFocusRing} from '../hooks/useIndicatorFocusRing';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useResolvedRequired} from '../hooks/useResolvedRequired';import {useIndicator} from '../Indicator';import {themeProps} from '../utils/themeProps';import {CheckboxListContext} from '../CheckboxList/CheckboxListContext';import {useMergedRefs} from '../hooks/useMergedRefs';++// The touch press's paint, declared by the shared overlay styles on the+// 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 layer+// that paints it. See interactionOverlay.stylex.ts.+const pressedOverlayImage = 'var(--_press-paint-image)';+const styles = stylex.create({container: {display: 'flex',@@ -72,6 +81,10 @@ const styles = stylex.create({},// The owner paints this layer over the resolved indicator, so a theme// replacement cannot accidentally drop the component's pressed contract.+ // Two pointers, two press models (see interactionOverlay.stylex.ts): a+ // mouse keeps `:active`; under a coarse pointer that arm is dropped and the+ // touch press controller writes `data-astryx-press` on the row, which this layer+ // reads off the same scope marker as the hover tint.indicatorPressOverlay: {'::after': {content: '""',@@ -81,8 +94,26 @@ const styles = stylex.create({pointerEvents: 'none',backgroundColor: {default: 'transparent',- [stylex.when.ancestor(':active', indicatorScope)]:- colorVars['--color-overlay-pressed'],+ [stylex.when.ancestor(':active', indicatorScope)]: {+ default: colorVars['--color-overlay-pressed'],+ '@media (pointer: coarse)': 'transparent',+ },+ },+ // The touch press, as an image layer over the colour: an image change is+ // discrete, so no transition can delay the onset, and the strength the+ // row's `pressedAlpha` arms own (1 while on, 1 → 0 over the release) is+ // what moves. Coarse pointers only, like the drop above.+ backgroundImage: {+ default: null,+ [stylex.when.ancestor('[data-astryx-press="on"]', indicatorScope)]: {+ default: null,+ '@media (pointer: coarse)': pressedOverlayImage,+ },+ [stylex.when.ancestor('[data-astryx-press="fading"]', indicatorScope)]:+ {+ default: null,+ '@media (pointer: coarse)': pressedOverlayImage,+ },},},},@@ -306,6 +337,9 @@ export function CheckboxInput({'aria-describedby': ariaDescribedByProp,...rest}: CheckboxInputProps) {+ // The row is the pressable: the overlay's pressed arm reads the row's+ // scope marker, the way the indicator's hover tint does.+ const pressable = usePressFeedback();const id = useId();const descriptionID = useId();const statusMessageID = useId();@@ -407,12 +441,17 @@ export function CheckboxInput({// unconditionally is safe.disabledMessageTooltip.interactionRef(el);}}+ {...(isDisabled ? undefined : pressable)}{...stylex.props(styles.container,isLabelHidden && styles.containerLabelHidden,// Hover and focus reach the checkbox visual through this ancestor// marker rather than props, so the whole row drives it.!isDisabled && indicatorScope,+ // The touch press's strength and release live on the row the+ // controller writes to; the layer over the checkbox box inherits+ // and paints it.+ !isDisabled && interactionOverlayStyles.pressedAlpha,)}><div{...stylex.props(diff --git a/packages/core/src/ClickableCard/ClickableCard.doc.mjs b/packages/core/src/ClickableCard/ClickableCard.doc.mjsindex 53c2bb216c..7417c34169 100644--- a/packages/core/src/ClickableCard/ClickableCard.doc.mjs+++ b/packages/core/src/ClickableCard/ClickableCard.doc.mjs@@ -37,6 +37,10 @@ export const docs = {theming: {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},+ ],},playground: {defaults: {diff --git a/packages/core/src/ClickableCard/ClickableCard.test.tsx b/packages/core/src/ClickableCard/ClickableCard.test.tsxindex 40d9eb56a7..e71db24338 100644--- a/packages/core/src/ClickableCard/ClickableCard.test.tsx+++ b/packages/core/src/ClickableCard/ClickableCard.test.tsx@@ -4,6 +4,7 @@ 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';describe('ClickableCard', () => {it('renders children', () => {@@ -242,3 +243,32 @@ describe('ClickableCard', () => {});});});++describe('ClickableCard pressed state (touch)', () => {+ it('fades the touch press out on the card, whose overlay layer reads its strength', () => {+ const {container} = render(+ <ClickableCard label="Test card" onClick={() => {}}>+ <span>Content</span>+ </ClickableCard>,+ );+ const card = container.querySelector('[data-astryx-pressable]');+ if (card == null) {+ 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.+ expect(hasReleaseFade(card)).toBe(true);+ expect(readsPressStrength(card, '[data-astryx-press="on"]')).toBe(true);+ expect(readsPressStrength(card)).toBe(true);+ });++ it('carries none of it when disabled', () => {+ const {container} = render(+ <ClickableCard label="Test card" onClick={() => {}} isDisabled>+ <span>Content</span>+ </ClickableCard>,+ );+ expect(container.querySelector('[data-astryx-pressable]')).toBeNull();+ });+});diff --git a/packages/core/src/ClickableCard/ClickableCard.tsx b/packages/core/src/ClickableCard/ClickableCard.tsxindex 9d3ca1ee78..51716e1979 100644--- a/packages/core/src/ClickableCard/ClickableCard.tsx+++ b/packages/core/src/ClickableCard/ClickableCard.tsx@@ -47,12 +47,20 @@ import type {BaseProps} from '../BaseProps';import {useLinkComponent} from '../Link/useLinkComponent';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';+import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useMergedRefs} from '../hooks/useMergedRefs';// =============================================================================// Styles — only the interactive layer, Card handles everything else// =============================================================================+// The touch press's paint, declared by the shared overlay styles on the+// 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 styles = stylex.create({interactive: {position: 'relative',@@ -63,28 +71,58 @@ const styles = stylex.create({textDecoration: 'none',color: 'inherit',},- // Hover overlay — guarded by @media (hover: hover) so touch devices- // don't show a stuck hover state. Active/pressed state works everywhere.+ // 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.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.+ '--_press-overlay': {+ default: 'transparent',+ ':where(:not(:disabled,[aria-disabled="true"]))': {+ default: null,+ ':active': {+ default: colorVars['--color-overlay-pressed'],+ '@media (pointer: coarse)': 'transparent',+ },+ '@media (hover: hover)': {+ default: null,+ ':hover:where(:not(:disabled,[aria-disabled="true"]))':+ 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: durationVars['--duration-fast'],+ transitionDuration: 'var(--_press-overlay-transition)',transitionTimingFunction: easeVars['--ease-standard'],- backgroundColor: 'transparent',- },- ':active::after': {- backgroundColor: colorVars['--color-overlay-pressed'],- },- },- hoverOnPointer: {- '@media (hover: hover)': {- ':hover:where(:not(:disabled,[aria-disabled="true"]))::after': {- backgroundColor: colorVars['--color-overlay-hover'],- },+ backgroundColor: 'var(--_press-overlay)',},},// Borderless variants (everything except `default`): drop the transparent@@ -273,6 +311,7 @@ export function ClickableCard({style,...props}: ClickableCardProps) {+ const pressable = usePressFeedback();const containerRef = useRef<HTMLDivElement | null>(null);const interactiveRef = useRef<HTMLElement | null>(null);const LinkComponent = useLinkComponent();@@ -303,6 +342,7 @@ export function ClickableCard({return (<Cardref={useMergedRefs(ref, containerRef)}+ {...(isDisabled ? undefined : pressable)}width={width}height={height}maxWidth={maxWidth}@@ -320,7 +360,9 @@ export function ClickableCard({styles.interactive,hasBorder ? styles.bordered : styles.borderless,!isDisabled && styles.overlay,- !isDisabled && styles.hoverOnPointer,+ // The touch press's strength and release, on the element the+ // controller writes to; the `::after` above paints off it.+ !isDisabled && interactionOverlayStyles.pressedAlpha,!isDisabled && hasBorder && styles.borderedHoverOnPointer,isDisabled && styles.disabled,xstyleProp,diff --git a/packages/core/src/Collapsible/Collapsible.tsx b/packages/core/src/Collapsible/Collapsible.tsxindex efb3ac295f..db4ba0d6eb 100644--- a/packages/core/src/Collapsible/Collapsible.tsx+++ b/packages/core/src/Collapsible/Collapsible.tsx@@ -49,6 +49,7 @@ import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';const styles = stylex.create({root: {@@ -322,6 +323,7 @@ export function Collapsible({style,...props}: CollapsibleProps) {+ const pressable = usePressFeedback();// Build the config for the hookconst collapsibleConfig =controlledIsOpen !== undefined@@ -408,6 +410,7 @@ export function Collapsible({// the system-wide disabled convention (never native `disabled`, which// would swallow events like a wrapping tooltip's hover).tabIndex={isDisabled ? -1 : undefined}+ {...(isDisabled ? undefined : pressable)}{...mergeProps(themeProps('collapsible-trigger', {density: density ?? undefined,diff --git a/packages/core/src/CommandPalette/CommandPaletteItem.tsx b/packages/core/src/CommandPalette/CommandPaletteItem.tsxindex 3279efd70e..0a1fa645b4 100644--- a/packages/core/src/CommandPalette/CommandPaletteItem.tsx+++ b/packages/core/src/CommandPalette/CommandPaletteItem.tsx@@ -27,6 +27,7 @@ import {useCommandPaletteContext} from './CommandPaletteContext';import {useDialogContext} from '../Dialog/DialogContext';import {themeProps} from '../utils/themeProps';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useMergedRefs} from '../hooks/useMergedRefs';@@ -127,6 +128,7 @@ export function CommandPaletteItem({onMouseEnter: onMouseEnterProp,...props}: CommandPaletteItemProps) {+ const pressable = usePressFeedback();const ctx = useCommandPaletteContext();const dialogContext = useDialogContext();const isInlineDialog = dialogContext?.isInline === true;@@ -191,6 +193,7 @@ export function CommandPaletteItem({aria-selected={isSelected}aria-disabled={isDisabled || undefined}data-value={value}+ {...pressable}onClick={composeEventHandlers(onClickProp, handleClick)}onMouseEnter={onMouseEnterProp}{...mergeProps(diff --git a/packages/core/src/ComplexSelector/ComplexSelector.tsx b/packages/core/src/ComplexSelector/ComplexSelector.tsxindex 4d5027de30..ac61f47d36 100644--- a/packages/core/src/ComplexSelector/ComplexSelector.tsx+++ b/packages/core/src/ComplexSelector/ComplexSelector.tsx@@ -51,6 +51,7 @@ import {isRenderable, mergeProps} from '../utils';import {composeEventHandlers} from '../utils/composeEventHandlers';import {focusOutlineStyles} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import type {SizeValue} from '../utils/types';import {themeProps} from '../utils/themeProps';@@ -134,7 +135,13 @@ const styles = stylex.create({'background-image, background-color, color, opacity, transform',transform: {default: 'scale(1)',- ':active': 'scale(0.98)',+ // A mouse press; under a coarse pointer the touch press model writes+ // `data-astryx-press` instead (see interactionOverlay.stylex.ts).+ ':active': {+ default: 'scale(0.98)',+ '@media (pointer: coarse)': 'scale(1)',+ },+ '[data-astryx-press="on"]': 'scale(0.98)',},},triggerGhostDisabled: {@@ -142,6 +149,7 @@ const styles = stylex.create({transform: {default: 'none',':active': 'none',+ '[data-astryx-press="on"]': 'none',},},// Only what Icon does not already provide: `sm` gives the 16px box and@@ -410,6 +418,7 @@ export function ComplexSelector<Value>({...props}: ComplexSelectorProps<Value>) {const t = useTranslator();+ const pressable = usePressFeedback();const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});const placeholder = placeholderFromProps ?? t('@astryx.selector.placeholder');const effectiveStatusVariant =@@ -570,6 +579,7 @@ export function ComplexSelector<Value>({<divref={popover.triggerRef}data-testid={testId}+ {...pressable}{...props}onClick={composeEventHandlers(onClickProp, handleTriggerClick)}{...mergeProps(diff --git a/packages/core/src/DateInput/TouchDateField.tsx b/packages/core/src/DateInput/TouchDateField.tsxindex 860bf2d26a..c8a7a9d3ac 100644--- a/packages/core/src/DateInput/TouchDateField.tsx+++ b/packages/core/src/DateInput/TouchDateField.tsx@@ -111,6 +111,7 @@ import {type ISODateString,} from '../utils';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {normalizeDayOfWeek} from '../utils/dateTypes';import {MonthScroller, type MonthScrollerHandle} from './MonthScroller';import {MonthYearWheels} from './MonthYearWheels';@@ -577,6 +578,7 @@ export function TouchDateField({ref,...rest}: DateInputProps) {+ const pressable = usePressFeedback();const t = useTranslator();const locale = useLocale();const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});@@ -954,6 +956,7 @@ export function TouchDateField({// restyle the header button. Adding a target later is additive;// withdrawing one is not.data-title="month-year"+ {...pressable}{...stylex.props(styles.title,interactionOverlayStyles.backgroundColor,diff --git a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuItem.tsxindex 5c1a698919..269706dff6 100644--- a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx@@ -46,6 +46,7 @@ import {useDropdownMenuContext} from './DropdownMenuContext';import {focusMenuItemOnHover} from './menuItemHover';import {isModifiedClick} from './menuItemRoles';import {themeProps} from '../utils/themeProps';+import {usePressFeedback} from '../hooks/usePressFeedback';const menuItemStyles = stylex.create({root: {@@ -194,6 +195,10 @@ export function DropdownMenuItem({}: DropdownMenuItemProps) {const ctx = useDropdownMenuContext();const menuSize = ctx?.menuSize ?? 'md';+ // Item marks itself as a pressable surface too; naming the row here as well+ // keeps this file's own press arms (above) verifiably reachable by the+ // touch press controller (pressableCoverage.test.ts).+ const pressable = usePressFeedback();const handleClick = useCallback((event: MouseEvent) => {@@ -258,6 +263,7 @@ export function DropdownMenuItem({role="menuitem"tabIndex={isDisabled ? undefined : -1}onPointerMove={handlePointerMove}+ {...pressable}startContent={icon? renderIconSlot(icon, {diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsxindex e0d8194194..d7bf5a72b6 100644--- a/packages/core/src/Item/Item.tsx+++ b/packages/core/src/Item/Item.tsx@@ -37,6 +37,7 @@ import {useDevWarning} from '../hooks/useDevWarning';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';// =============================================================================// Types@@ -424,6 +425,7 @@ export function Item({role,...restProps}: ItemProps) {+ const pressable = usePressFeedback();const LinkComponent = useLinkComponent();// Delegation mode: the row is an enlarged click/tap target for a nested@@ -631,6 +633,7 @@ export function Item({(isSelected && !allowsAriaSelected ? true : undefined)}aria-disabled={isDisabled || undefined}+ {...(isInteractive ? pressable : undefined)}{...mergeProps(themeProps('item', {density, align}),focusOutlineProps.focusWithin(diff --git a/packages/core/src/Link/Link.tsx b/packages/core/src/Link/Link.tsxindex 4d6ab015c9..3dde606b92 100644--- a/packages/core/src/Link/Link.tsx+++ b/packages/core/src/Link/Link.tsx@@ -46,6 +46,7 @@ import {useInteractiveRole} from '../hooks/useInteractiveRole';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useTranslator} from '../i18n';/**@@ -316,6 +317,10 @@ export function Link({ref,...props}: LinkProps) {+ // Constant marker props; the hook's only effect is installing the shared+ // document controller once, so the link's output stays a pure function of+ // its props.+ const pressable = usePressFeedback();const t = useTranslator();const newTabLabel = newTabLabelFromProps ?? t('@astryx.link.newTab');const LinkComponent = useLinkComponent(as);@@ -359,6 +364,7 @@ export function Link({ref={ref as React.Ref<HTMLButtonElement>}type="button"onClick={onClick}+ {...(isDisabled ? undefined : pressable)}aria-label={label || undefined}aria-disabled={isDisabled || undefined}tabIndex={isDisabled ? -1 : undefined}@@ -423,6 +429,7 @@ export function Link({target={target}rel={rel}onClick={onClick}+ {...(isDisabled ? undefined : pressable)}aria-label={label || undefined}aria-disabled={isDisabled || undefined}tabIndex={isDisabled ? -1 : undefined}diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsxindex 126f0f08ad..e04f60b1a9 100644--- a/packages/core/src/MultiSelector/MultiSelector.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.tsx@@ -83,6 +83,7 @@ import {useSize} from '../SizeContext/SizeContext';import {themeProps} from '../utils/themeProps';import {focusOutlineStyles} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {stableClassName} from '../naming';import {groupStyles} from '../InputGroup/groupStyles';import {useInputGroup} from '../InputGroup/InputGroupContext';@@ -223,7 +224,13 @@ const styles = stylex.create({'background-image, background-color, color, opacity, transform',transform: {default: 'scale(1)',- ':active': 'scale(0.98)',+ // A mouse press; under a coarse pointer the touch press model writes+ // `data-astryx-press` instead (see interactionOverlay.stylex.ts).+ ':active': {+ default: 'scale(0.98)',+ '@media (pointer: coarse)': 'scale(1)',+ },+ '[data-astryx-press="on"]': 'scale(0.98)',},},triggerGhostDisabled: {@@ -231,6 +238,7 @@ const styles = stylex.create({transform: {default: 'none',':active': 'none',+ '[data-astryx-press="on"]': 'none',},},triggerReadOnly: {@@ -241,6 +249,7 @@ const styles = stylex.create({transform: {default: 'none',':active': 'none',+ '[data-astryx-press="on"]': 'none',},},@@ -959,6 +968,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({onFocus,}: MultiSelectorProps<T>) {const t = useTranslator();+ const pressable = usePressFeedback();const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});const placeholder =placeholderFromProps ?? t('@astryx.multiSelector.selectPlaceholder');@@ -2131,6 +2141,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({}}onClick={onTriggerClick}data-testid={testId}+ {...pressable}{...mergeProps(themeProps('multi-selector', {variant,diff --git a/packages/core/src/NavItem/navItemStyles.stylex.ts b/packages/core/src/NavItem/navItemStyles.stylex.tsindex d1a8c73569..a6580560ce 100644--- a/packages/core/src/NavItem/navItemStyles.stylex.ts+++ b/packages/core/src/NavItem/navItemStyles.stylex.ts@@ -110,6 +110,23 @@ export const navItemStyles = stylex.create({'@media (forced-colors: active)': 'Highlight',},},+ // The touch press model writes these instead of `:active`; the selected+ // item keeps its fill under a finger the way it does under a mouse, and+ // paints no overlay at any phase of the press.+ '[data-astryx-press="on"]': {+ backgroundColor: {+ default: colorVars['--color-neutral'],+ '@media (forced-colors: active)': 'Highlight',+ },+ backgroundImage: 'none',+ },+ '[data-astryx-press="fading"]': {+ backgroundColor: {+ default: colorVars['--color-neutral'],+ '@media (forced-colors: active)': 'Highlight',+ },+ backgroundImage: 'none',+ },},/** Disabled state — muted color, no interaction */diff --git a/packages/core/src/NumberInput/NumberInput.tsx b/packages/core/src/NumberInput/NumberInput.tsxindex 66ae43a7fd..3d0a2074b3 100644--- a/packages/core/src/NumberInput/NumberInput.tsx+++ b/packages/core/src/NumberInput/NumberInput.tsx@@ -52,6 +52,7 @@ import {VisuallyHidden} from '../VisuallyHidden';import {useTooltip} from '../Tooltip';import {getInputARIA} from '../utils';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useSize} from '../SizeContext/SizeContext';import {useInputContainer} from '../hooks/useInputContainer';import {useInputStatusIcon} from '../hooks/useInputStatusIcon';@@ -566,6 +567,7 @@ export function NumberInput({ref,...rest}: NumberInputProps) {+ const pressable = usePressFeedback();const t = useTranslator();const locale = useLocale();const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});@@ -971,6 +973,7 @@ export function NumberInput({<buttontype="button"tabIndex={-1}+ {...pressable}disabled={isDisabled || isReadOnly || !canIncrement}aria-label={t('@astryx.numberInput.incrementLabel', {label})}onPointerDown={event => event.preventDefault()}@@ -994,6 +997,7 @@ export function NumberInput({<buttontype="button"tabIndex={-1}+ {...pressable}disabled={isDisabled || isReadOnly || !canDecrement}aria-label={t('@astryx.numberInput.decrementLabel', {label})}onPointerDown={event => event.preventDefault()}diff --git a/packages/core/src/Outline/Outline.tsx b/packages/core/src/Outline/Outline.tsxindex e2aa14ad25..c6e6333c13 100644--- a/packages/core/src/Outline/Outline.tsx+++ b/packages/core/src/Outline/Outline.tsx@@ -44,6 +44,7 @@ import type {OutlineItem} from './types';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';@@ -323,6 +324,7 @@ export function Outline({'data-testid': testId,...props}: OutlineProps) {+ const pressable = usePressFeedback();const t = useTranslator();const label = labelFromProps ?? t('@astryx.outline.label');const rootRef = useRef<HTMLElement | null>(null);@@ -465,6 +467,7 @@ export function Outline({aria-current={isActive ? 'location' : undefined}onClick={handleClick(item.id)}onKeyDown={handleKeyDown(item.id)}+ {...pressable}{...mergeProps(themeProps('outline-item', {active: isActive ? 'active' : null,diff --git a/packages/core/src/RadioList/RadioList.test.tsx b/packages/core/src/RadioList/RadioList.test.tsxindex e7868ab490..45abe1862f 100644--- a/packages/core/src/RadioList/RadioList.test.tsx+++ b/packages/core/src/RadioList/RadioList.test.tsx@@ -15,7 +15,11 @@import {describe, it, expect, vi, beforeEach} from 'vitest';import {render, screen, fireEvent, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';-import {hasPressedArm} from '../__tests__/pressState';+import {+ hasPressedArm,+ hasReleaseFade,+ readsPressStrength,+} from '../__tests__/pressState';import {RadioList} from './RadioList';import {RadioListItem} from './RadioListItem';import {getForcedColorsRules} from '../__tests__/forcedColors';@@ -887,4 +891,28 @@ describe('pressed state', () => {}expect(hasPressedArm(wrapper)).toBe(false);});++ it('fades the touch press out from the row, with the overlay reading its strength', () => {+ const {container} = render(+ <RadioList label="Plan" value="a" onChange={() => {}}>+ <RadioListItem label="Option A" value="a" />+ <RadioListItem label="Option B" value="b" />+ </RadioList>,+ );+ const circle = container.querySelector('.astryx-radio-indicator');+ const wrapper = circle?.parentElement?.parentElement;+ const row = circle?.closest('[data-astryx-pressable]');+ if (wrapper == null || row == null) {+ throw new Error('the radio has no pressable row or indicator wrapper');+ }+ // The controller writes the row; the row owns the strength and its+ // release, and the owner-drawn layer over the circle paints the pressed+ // token at that strength on both touch arms.+ expect(hasReleaseFade(row)).toBe(true);+ expect(readsPressStrength(wrapper, '[data-astryx-press="on"]')).toBe(true);+ expect(readsPressStrength(wrapper)).toBe(true);+ // The row itself paints nothing under a finger, as under a mouse: only+ // the circle answers.+ expect(readsPressStrength(row, '[data-astryx-press="on"]')).toBe(false);+ });});diff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsxindex 259fb84633..34e7d91128 100644--- a/packages/core/src/RadioList/RadioListItem.tsx+++ b/packages/core/src/RadioList/RadioListItem.tsx@@ -27,10 +27,17 @@ import {colorVars, radiusVars} from '../theme/tokens.stylex';import {mergeProps, isRenderable, rtlStyles} from '../utils';import {indicatorScope} from '../Indicator/indicator.markers.stylex';import {useIndicatorFocusRing} from '../hooks/useIndicatorFocusRing';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useIndicator} from '../Indicator';import {Item} from '../Item';import {themeProps} from '../utils/themeProps';+// The touch press's paint, declared by the shared overlay styles on the+// 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 layer+// that paints it. See interactionOverlay.stylex.ts.+const pressedOverlayImage = 'var(--_press-paint-image)';+const styles = stylex.create({radioWrapper: {position: 'relative',@@ -43,6 +50,12 @@ const styles = stylex.create({// The row remains the large press target, but nested links and buttons keep// their independent action and do not make the radio appear pressed. This// owner-drawn layer also survives a theme replacing the indicator component.+ // Two pointers, two press models (see interactionOverlay.stylex.ts): a+ // mouse keeps `:active`; under a coarse pointer that arm is dropped and the+ // touch press controller writes `data-astryx-press` on the row, which this layer+ // reads off the same scope marker as the hover tint. The controller paints+ // the innermost pressable, so a nested link or button takes the press+ // itself and the row never carries the attribute for it.indicatorPressOverlay: {'::after': {content: '""',@@ -55,7 +68,26 @@ const styles = stylex.create({[stylex.when.ancestor(':active:not(:has(a:active,button:active,[role="button"]:active,[role="link"]:active))',indicatorScope,- )]: colorVars['--color-overlay-pressed'],+ )]: {+ default: colorVars['--color-overlay-pressed'],+ '@media (pointer: coarse)': 'transparent',+ },+ },+ // The touch press, as an image layer over the colour: an image change is+ // discrete, so no transition can delay the onset, and the strength the+ // row's `pressedAlpha` arms own (1 while on, 1 → 0 over the release) is+ // what moves. Coarse pointers only, like the drop above.+ backgroundImage: {+ default: null,+ [stylex.when.ancestor('[data-astryx-press="on"]', indicatorScope)]: {+ default: null,+ '@media (pointer: coarse)': pressedOverlayImage,+ },+ [stylex.when.ancestor('[data-astryx-press="fading"]', indicatorScope)]:+ {+ default: null,+ '@media (pointer: coarse)': pressedOverlayImage,+ },},},},@@ -114,6 +146,11 @@ const rowStyles = stylex.create({// Suppress Item's interactive hover/press background so the resting and// hovered row look identical by default (a theme can restyle either).backgroundColor: 'transparent',+ // ...and the touch press's overlay image, for the same reason: under a+ // finger only the radio circle paints, as under a mouse. The press's+ // strength still lands on the row, which is where the layer over the+ // circle reads it.+ backgroundImage: 'none',},});@@ -201,6 +238,11 @@ export function RadioListItem({onClick,...rest}: RadioListItemProps) {+ // Item marks itself as a pressable surface (the row delegates to the radio,+ // so it is interactive); naming the row here as well keeps the overlay's+ // pressed arm, which reads the row's scope marker, verifiably reachable by+ // the touch press controller (pressableCoverage.test.ts).+ const pressable = usePressFeedback();const context = use(RadioListContext);if (!context) {throw new Error('RadioListItem must be used within an RadioList');@@ -309,6 +351,7 @@ export function RadioListItem({return (<Itemref={ref}+ {...(isDisabled ? undefined : pressable)}startContent={mediaContent}// Delegate row-surface clicks (label text, description, and the empty// hover area) to the radio input. The input stays the option's solediff --git a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx b/packages/core/src/SegmentedControl/SegmentedControlItem.tsxindex 7bf85de193..c2382f99cd 100644--- a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx+++ b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx@@ -34,6 +34,7 @@ import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';export interface SegmentedControlItemProps extends BaseProps<HTMLButtonElement> {ref?: React.Ref<HTMLButtonElement>;@@ -193,6 +194,7 @@ export function SegmentedControlItem({xstyle,...rest}: SegmentedControlItemProps) {+ const pressable = usePressFeedback();const ctx = useSegmentedControlContext();const isSelected = ctx.value === value;@@ -228,6 +230,7 @@ export function SegmentedControlItem({aria-disabled={isItemDisabled || undefined}aria-label={isLabelHidden ? label : undefined}data-value={value}+ {...(!isSelected && !isItemDisabled ? pressable : undefined)}// Disabled items (including when the whole group is disabled) are not tab// stops — otherwise the selected segment stays keyboard-focusable but is// silently dead (arrows and activation are no-ops) (navigation-13). Thediff --git a/packages/core/src/SelectableCard/SelectableCard.doc.mjs b/packages/core/src/SelectableCard/SelectableCard.doc.mjsindex 49fe31583e..456d80579f 100644--- a/packages/core/src/SelectableCard/SelectableCard.doc.mjs+++ b/packages/core/src/SelectableCard/SelectableCard.doc.mjs@@ -39,6 +39,8 @@ 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},],},playground: {diff --git a/packages/core/src/SelectableCard/SelectableCard.test.tsx b/packages/core/src/SelectableCard/SelectableCard.test.tsxindex dc4d0c2e38..ce4c314569 100644--- a/packages/core/src/SelectableCard/SelectableCard.test.tsx+++ b/packages/core/src/SelectableCard/SelectableCard.test.tsx@@ -11,6 +11,7 @@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';describe('SelectableCard', () => {it('renders children', () => {@@ -186,3 +187,20 @@ describe('SelectableCard', () => {});});});++describe('SelectableCard pressed state (touch)', () => {+ it('fades the touch press out on the card, whose overlay layer reads its strength', () => {+ const {container} = render(+ <SelectableCard label="Test" isSelected={false} onChange={() => {}}>+ Content+ </SelectableCard>,+ );+ const card = container.querySelector('[data-astryx-pressable]');+ if (card == null) {+ throw new Error('the card carries no pressable marker');+ }+ expect(hasReleaseFade(card)).toBe(true);+ expect(readsPressStrength(card, '[data-astryx-press="on"]')).toBe(true);+ expect(readsPressStrength(card)).toBe(true);+ });+});diff --git a/packages/core/src/SelectableCard/SelectableCard.tsx b/packages/core/src/SelectableCard/SelectableCard.tsxindex 4453ce6dc9..eb758cf6d2 100644--- a/packages/core/src/SelectableCard/SelectableCard.tsx+++ b/packages/core/src/SelectableCard/SelectableCard.tsx@@ -47,12 +47,20 @@ import {useClickableContainer} from '../hooks/useClickableContainer';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';+import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useMergedRefs} from '../hooks/useMergedRefs';// =============================================================================// Styles — selection + interaction; Card handles the rest// =============================================================================+// The touch press's paint, declared by the shared overlay styles on the+// 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 styles = stylex.create({interactive: {// Declared here, on the element that carries the `astryx-selectable-card`@@ -68,9 +76,49 @@ const styles = stylex.create({transitionDuration: durationVars['--duration-fast'],transitionTimingFunction: easeVars['--ease-standard'],},- // Hover overlay — guarded by @media (hover: hover) so touch devices- // don't show a stuck hover state. Active/pressed state works everywhere.+ // 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.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.+ '--_press-overlay': {+ default: 'transparent',+ ':where(:not(:disabled,[aria-disabled="true"]))': {+ default: null,+ ':active': {+ default: colorVars['--color-overlay-pressed'],+ '@media (pointer: coarse)': 'transparent',+ },+ '@media (hover: hover)': {+ default: null,+ ':hover:where(:not(:disabled,[aria-disabled="true"]))':+ 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',@@ -78,19 +126,9 @@ const styles = stylex.create({borderRadius: 'inherit',pointerEvents: 'none',transitionProperty: 'background-color',- transitionDuration: durationVars['--duration-fast'],+ transitionDuration: 'var(--_press-overlay-transition)',transitionTimingFunction: easeVars['--ease-standard'],- backgroundColor: 'transparent',- },- ':active::after': {- backgroundColor: colorVars['--color-overlay-pressed'],- },- },- hoverOnPointer: {- '@media (hover: hover)': {- ':hover:where(:not(:disabled,[aria-disabled="true"]))::after': {- backgroundColor: colorVars['--color-overlay-hover'],- },+ backgroundColor: 'var(--_press-overlay)',},},disabled: {@@ -315,6 +353,7 @@ export function SelectableCard({style,...props}: SelectableCardProps) {+ const pressable = usePressFeedback();const containerRef = useRef<HTMLDivElement | null>(null);const interactiveRef = useRef<HTMLInputElement | null>(null);@@ -370,6 +409,7 @@ export function SelectableCard({return (<Cardref={useMergedRefs(ref, containerRef)}+ {...(isDisabled ? undefined : pressable)}width={width}height={height}maxWidth={maxWidth}@@ -390,7 +430,9 @@ export function SelectableCard({styles.interactive,isSelected && selectedStyleForVariant(variant),!isDisabled && styles.overlay,- !isDisabled && styles.hoverOnPointer,+ // The touch press's strength and release, on the element the+ // controller writes to; the `::after` above paints off it.+ !isDisabled && interactionOverlayStyles.pressedAlpha,isDisabled && styles.disabled,xstyleProp,] as unknown as StyleXStylesdiff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex abb9aeb46e..73bc817452 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -85,6 +85,7 @@ import type {SizeValue} from '../utils/types';import {themeProps} from '../utils/themeProps';import {focusOutlineStyles} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {stableClassName} from '../naming';import {groupStyles} from '../InputGroup/groupStyles';import {useInputGroup} from '../InputGroup/InputGroupContext';@@ -245,7 +246,13 @@ const styles = stylex.create({'background-image, background-color, color, opacity, transform',transform: {default: 'scale(1)',- ':active': 'scale(0.98)',+ // A mouse press; under a coarse pointer the touch press model writes+ // `data-astryx-press` instead (see interactionOverlay.stylex.ts).+ ':active': {+ default: 'scale(0.98)',+ '@media (pointer: coarse)': 'scale(1)',+ },+ '[data-astryx-press="on"]': 'scale(0.98)',},},triggerGhostDisabled: {@@ -253,6 +260,7 @@ const styles = stylex.create({transform: {default: 'none',':active': 'none',+ '[data-astryx-press="on"]': 'none',},},triggerReadOnly: {@@ -263,6 +271,7 @@ const styles = stylex.create({transform: {default: 'none',':active': 'none',+ '[data-astryx-press="on"]': 'none',},},@@ -854,6 +863,7 @@ export function Selector<T extends SelectorOptionType>(props: SelectorProps<T>,) {const t = useTranslator();+ const pressable = usePressFeedback();const {label,isLabelHidden = false,@@ -1792,6 +1802,7 @@ export function Selector<T extends SelectorOptionType>(}}onClick={onTriggerClick}data-testid={testId}+ {...pressable}{...mergeProps(themeProps('selector', {variant,diff --git a/packages/core/src/SideNav/SideNavHeading.tsx b/packages/core/src/SideNav/SideNavHeading.tsxindex 45181f94b5..69d337dfec 100644--- a/packages/core/src/SideNav/SideNavHeading.tsx+++ b/packages/core/src/SideNav/SideNavHeading.tsx@@ -38,6 +38,7 @@ import {Tooltip} from '../Tooltip';import {navItemStyles} from '../NavItem/navItemStyles.stylex';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useSideNavCollapse} from './SideNavCollapseContext';import {useLinkComponent} from '../Link/useLinkComponent';import type {LinkComponentType} from '../Link/types';@@ -368,6 +369,7 @@ export function SideNavHeading({ref,...props}: SideNavHeadingProps) {+ const pressable = usePressFeedback();const t = useTranslator();const LinkComponent = useLinkComponent(as);const {isCollapsed} = useSideNavCollapse();@@ -430,6 +432,7 @@ export function SideNavHeading({ref={collapsedSetRef as React.Ref<HTMLAnchorElement>}href={headingHref}aria-label={heading}+ {...pressable}data-testid={testId}{...mergeProps(themeProps('side-nav-heading'),@@ -452,6 +455,7 @@ export function SideNavHeading({ref={collapsedSetRef}type="button"aria-label={heading}+ {...pressable}data-testid={testId}{...popover.triggerProps}{...triggerProps}diff --git a/packages/core/src/SideNav/SideNavItem.tsx b/packages/core/src/SideNav/SideNavItem.tsxindex 6c581d4218..de841443b5 100644--- a/packages/core/src/SideNav/SideNavItem.tsx+++ b/packages/core/src/SideNav/SideNavItem.tsx@@ -56,6 +56,7 @@ import {navItemStyles, type NavItemSize} from '../NavItem/navItemStyles.stylex';import {SizeProvider} from '../SizeContext/SizeContext';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useSideNavCollapse,SideNavCollapseContext,@@ -443,6 +444,9 @@ export function SideNavItem({xstyle,...rest}: SideNavItemProps) {+ // The row (or, collapsed, the trigger/link/button) is the pressable; the+ // expand toggle inside it is its own.+ const pressable = usePressFeedback();const t = useTranslator();const {isCollapsed} = useSideNavCollapse();const renderMode = useSideNavRenderMode();@@ -555,23 +559,26 @@ export function SideNavItem({// Shared collapsed item styles — used by trigger, link, and button.// All three render a focusable element, so each draws the shared ring.- const collapsedItemStyles = mergeProps(- themeProps('side-nav-item', {- size,- selected: isSelected ? 'selected' : null,- disabled: isDisabled ? 'disabled' : null,- }),- focusOutlineProps.focusVisible(- navItemStyles.item,- interactionOverlayStyles.backgroundColor,- navItemStyles[size],- styles.itemCollapsed,- size === 'sm' && styles.itemCollapsedSm,- size === 'lg' && styles.itemCollapsedLg,- isSelected && navItemStyles.selected,- isDisabled && navItemStyles.disabled,+ const collapsedItemStyles = {+ ...mergeProps(+ themeProps('side-nav-item', {+ size,+ selected: isSelected ? 'selected' : null,+ disabled: isDisabled ? 'disabled' : null,+ }),+ focusOutlineProps.focusVisible(+ navItemStyles.item,+ interactionOverlayStyles.backgroundColor,+ navItemStyles[size],+ styles.itemCollapsed,+ size === 'sm' && styles.itemCollapsedSm,+ size === 'lg' && styles.itemCollapsedLg,+ isSelected && navItemStyles.selected,+ isDisabled && navItemStyles.disabled,+ ),),- );+ ...pressable,+ };const collapsedAccessibleLabel =rest['aria-label'] != null && rest['aria-label'].trim() !== ''@@ -688,15 +695,24 @@ export function SideNavItem({// only. The wrapper is not a tab stop, so `:focus-visible` on it would// never match, and matching any descendant instead would light the whole// row around the chevron's or an action's own ring.- const rowProps = mergeProps(itemThemeProps, stylex.props(...itemStyleArgs));- const focusableRowProps = mergeProps(- itemThemeProps,- focusOutlineProps.focusVisible(...itemStyleArgs),- );- const actionsRowProps = mergeProps(- itemThemeProps,- focusOutlineProps.focusWithinFirstChild(...itemStyleArgs),- );+ const rowProps = {+ ...mergeProps(itemThemeProps, stylex.props(...itemStyleArgs)),+ ...pressable,+ };+ const focusableRowProps = {+ ...mergeProps(+ itemThemeProps,+ focusOutlineProps.focusVisible(...itemStyleArgs),+ ),+ ...pressable,+ };+ const actionsRowProps = {+ ...mergeProps(+ itemThemeProps,+ focusOutlineProps.focusWithinFirstChild(...itemStyleArgs),+ ),+ ...pressable,+ };// Row-wrapper path: primary element + row controls as siblings.//@@ -750,6 +766,7 @@ export function SideNavItem({}aria-expanded={!isItemCollapsed}aria-controls={`${id}-children`}+ {...pressable}{...focusOutlineProps.focusVisible(styles.expandToggle,interactionOverlayStyles.backgroundColor,diff --git a/packages/core/src/Stepper/Step.tsx b/packages/core/src/Stepper/Step.tsxindex 23075a55a5..23264ca57c 100644--- a/packages/core/src/Stepper/Step.tsx+++ b/packages/core/src/Stepper/Step.tsx@@ -59,6 +59,7 @@ import {themeProps,} from '../utils';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import type {BaseProps} from '../BaseProps';import {Icon} from '../Icon';import {VisuallyHidden} from '../VisuallyHidden';@@ -1001,6 +1002,7 @@ export function Step({'data-testid': dataTestId,...rest}: StepProps) {+ const pressable = usePressFeedback();const t = useTranslator();const ctx = useStepperInternalContext();const {@@ -1598,6 +1600,7 @@ export function Step({type="button"onClick={handleClick}aria-label={stepAriaLabel}+ {...pressable}{...stylex.props(styles.otInteractive,interactionOverlayStyles.backgroundColor,@@ -1688,6 +1691,7 @@ export function Step({type="button"onClick={handleClick}aria-label={stepAriaLabel}+ {...pressable}{...stylex.props(styles.otInteractive,interactionOverlayStyles.backgroundColor,@@ -1747,6 +1751,7 @@ export function Step({type="button"onClick={handleClick}aria-label={stepAriaLabel}+ {...pressable}{...stylex.props(styles.buttonReset,interactionOverlayStyles.backgroundColor,diff --git a/packages/core/src/Switch/Switch.test.tsx b/packages/core/src/Switch/Switch.test.tsxindex 524748879c..f3a765aa2e 100644--- a/packages/core/src/Switch/Switch.test.tsx+++ b/packages/core/src/Switch/Switch.test.tsx@@ -30,7 +30,11 @@ import {getAllInjectedCss,getForcedColorsRules,} from '../__tests__/forcedColors';-import {hasPressedArm} from '../__tests__/pressState';+import {+ hasPressedArm,+ hasReleaseFade,+ readsPressStrength,+} from '../__tests__/pressState';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';import {InternationalizationProvider} from '../i18n';@@ -845,6 +849,26 @@ describe('Switch', () => {expect(hasPressedArm(track)).toBe(true);expect(hasPressedArm(thumb)).toBe(true);});++ it('fades the touch press out from the row, with the track and thumb reading its strength', () => {+ const {container} = render(+ <Switch label="Notifications" value={false} onChange={() => {}} />,+ );+ const track = container.querySelector('.astryx-switch');+ const thumb = container.querySelector('.astryx-switch-thumb');+ const row = track?.closest('[data-astryx-pressable]');+ if (track == null || thumb == null || row == null) {+ throw new Error('the switch has no pressable row, track or thumb');+ }+ // The controller writes the row; the row owns the strength and its+ // release, and the two parts paint the pressed token at that strength+ // on both touch arms, so they fade together.+ expect(hasReleaseFade(row)).toBe(true);+ for (const part of [track, thumb]) {+ expect(readsPressStrength(part, '[data-astryx-press="on"]')).toBe(true);+ expect(readsPressStrength(part)).toBe(true);+ }+ });});describe('coarse pointer and RTL hit-target positioning', () => {diff --git a/packages/core/src/Switch/Switch.tsx b/packages/core/src/Switch/Switch.tsxindex 156187cd2d..df64e0a9ad 100644--- a/packages/core/src/Switch/Switch.tsx+++ b/packages/core/src/Switch/Switch.tsx@@ -44,6 +44,7 @@ import {Spinner} from '../Spinner';import {useTooltip} from '../Tooltip';import {mergeProps, mergeRefs, rtlStyles} from '../utils';import {switchScope} from './switch.markers.stylex';+import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';import type {BaseProps} from '../BaseProps';import type {SizeValue} from '../utils/types';import {themeProps} from '../utils/themeProps';@@ -52,6 +53,7 @@ import {useResolvedRequired} from '../hooks/useResolvedRequired';import {useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';+import {usePressFeedback} from '../hooks/usePressFeedback';const wrapperSizeStyles = stylex.create({sm: {width: 32,@@ -132,6 +134,11 @@ const thumbOnSizeStyles = stylex.create({// hover tint already is: pressing the input, the track or the label all// activate the row.const pressedImage = `linear-gradient(${colorVars['--color-overlay-pressed']}, ${colorVars['--color-overlay-pressed']})`;+// The touch press's paint, declared by the shared overlay styles on the+// 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 layer+// that paints it. See interactionOverlay.stylex.ts.+const pressedOverlayImage = 'var(--_press-paint-image)';const labelWrapperSizeStyles = stylex.create({sm: {@@ -224,7 +231,28 @@ const styles = stylex.create({default: null,[stylex.when.ancestor(':active', switchScope)]: {default: null,- '@media (forced-colors: none)': pressedImage,+ '@media (forced-colors: none)': {+ default: pressedImage,+ // Under a coarse pointer the touch press model writes `data-astryx-press`+ // on the row instead; see interactionOverlay.stylex.ts.+ '@media (pointer: coarse)': 'none',+ },+ },+ // Nested in the same media as the arm above so it outranks the drop: an+ // ancestor-scoped attribute selector gets no priority of its own.+ [stylex.when.ancestor('[data-astryx-press="on"]', switchScope)]: {+ default: null,+ '@media (forced-colors: none)': {+ default: null,+ '@media (pointer: coarse)': pressedOverlayImage,+ },+ },+ [stylex.when.ancestor('[data-astryx-press="fading"]', switchScope)]: {+ default: null,+ '@media (forced-colors: none)': {+ default: null,+ '@media (pointer: coarse)': pressedOverlayImage,+ },},},},@@ -305,7 +333,26 @@ const styles = stylex.create({default: null,[stylex.when.ancestor(':active', switchScope)]: {default: null,- '@media (forced-colors: none)': pressedImage,+ '@media (forced-colors: none)': {+ default: pressedImage,+ '@media (pointer: coarse)': 'none',+ },+ },+ // Nested in the same media as the arm above so it outranks the drop: an+ // ancestor-scoped attribute selector gets no priority of its own.+ [stylex.when.ancestor('[data-astryx-press="on"]', switchScope)]: {+ default: null,+ '@media (forced-colors: none)': {+ default: null,+ '@media (pointer: coarse)': pressedOverlayImage,+ },+ },+ [stylex.when.ancestor('[data-astryx-press="fading"]', switchScope)]: {+ default: null,+ '@media (forced-colors: none)': {+ default: null,+ '@media (pointer: coarse)': pressedOverlayImage,+ },},},},@@ -523,6 +570,9 @@ export function Switch({}: SwitchProps) {const t = useTranslator();const id = useId();+ // The row is the pressable: the input, the track and the label all sit+ // inside it, and the pressed arms above read the row's scope marker.+ const pressable = usePressFeedback();const descriptionID = useId();const statusMessageID = useId();// Announce the effective required state (form default included) while the@@ -697,11 +747,15 @@ export function Switch({// unconditionally is safe.disabledMessageTooltip.interactionRef(el);}}+ {...(isDisabled ? undefined : pressable)}{...stylex.props(styles.container,isLabelHidden && styles.containerLabelHidden,labelSpacing === 'spread' && styles.containerSpread,!isDisabled && switchScope,+ // The touch press's strength and release live on the row the+ // controller writes to; the track and thumb inherit and paint it.+ !isDisabled && interactionOverlayStyles.pressedAlpha,)}>{' '}{labelPosition === 'start' ? (diff --git a/packages/core/src/TabList/Tab.tsx b/packages/core/src/TabList/Tab.tsxindex f3c60c6dfe..fb1d9a14bc 100644--- a/packages/core/src/TabList/Tab.tsx+++ b/packages/core/src/TabList/Tab.tsx@@ -33,6 +33,8 @@ import type {BaseProps} from '../BaseProps';import {useTabListContext} from './TabListContext';import type {TabListSize} from './TabListContext';import {tabScope} from './tab.markers.stylex';+import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useLinkComponent} from '../Link/useLinkComponent';import type {LinkComponentType} from '../Link/types';import {mergeProps} from '../utils';@@ -98,6 +100,12 @@ export interface TabProps extends BaseProps<HTMLButtonElement> {// Styles// =============================================================================+// The touch press's paint, declared by the shared overlay styles on the+// 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 layer+// that paints it. See interactionOverlay.stylex.ts.+const pressedOverlayImage = 'var(--_press-paint-image)';+const styles = stylex.create({base: {position: 'relative',@@ -145,6 +153,25 @@ const styles = stylex.create({[stylex.when.ancestor(':active', tabScope)]: {default: colorVars['--color-overlay-pressed'],'@media (hover: hover)': colorVars['--color-overlay-pressed'],+ // Under a coarse pointer the touch press model writes `data-astryx-press`+ // on the tab instead, and paints as an image below.+ '@media (pointer: coarse)': 'transparent',+ },+ },+ // The touch press, as an image layer over the colour: an image change is+ // discrete, so the layer's colour transition cannot fade the onset in,+ // and the strength the tab's `pressedAlpha` arms own (1 while on, 1 → 0+ // over the release) is what moves. Coarse pointers only, like the colour+ // arms above; see interactionOverlay.stylex.ts.+ backgroundImage: {+ default: null,+ [stylex.when.ancestor('[data-astryx-press="on"]', tabScope)]: {+ default: null,+ '@media (pointer: coarse)': pressedOverlayImage,+ },+ [stylex.when.ancestor('[data-astryx-press="fading"]', tabScope)]: {+ default: null,+ '@media (pointer: coarse)': pressedOverlayImage,},},transitionProperty: 'background-color',@@ -261,6 +288,7 @@ export function Tab({onClick,...restProps}: TabProps) {+ const pressable = usePressFeedback();const tabListCtx = useTabListContext();const LinkComponent = useLinkComponent(as);@@ -327,6 +355,7 @@ export function Tab({const sharedProps = {...restProps,+ ...pressable,...(isLabelHidden ? {'aria-label': label} : {}),[EDGE_COMP_ATTR]: '','data-tab-value': value,@@ -364,6 +393,9 @@ export function Tab({isSelected && styles.selected,isFill && layoutStyles.fill,!isDisabled && tabScope,+ // The touch press's strength and release live on the tab the+ // controller writes to; the hover layer inherits and paints it.+ !isDisabled && interactionOverlayStyles.pressedAlpha,xstyle,),className,diff --git a/packages/core/src/TabList/TabList.test.tsx b/packages/core/src/TabList/TabList.test.tsxindex 020a7fedfb..a238c11387 100644--- a/packages/core/src/TabList/TabList.test.tsx+++ b/packages/core/src/TabList/TabList.test.tsx@@ -12,7 +12,11 @@import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';import {render, screen, fireEvent} from '@testing-library/react';import userEvent from '@testing-library/user-event';-import {hasPressedArm} from '../__tests__/pressState';+import {+ hasPressedArm,+ hasReleaseFade,+ readsPressStrength,+} from '../__tests__/pressState';import {TabList} from './TabList';import type {TabListProps} from './TabList';import {Tab} from './Tab';@@ -1580,4 +1584,24 @@ describe('pressed state', () => {fireEvent.click(tab);expect(onChange).not.toHaveBeenCalled();});++ it('fades the touch press out from the tab, with the surface reading its strength', () => {+ render(+ <TabList value="home" onChange={() => {}}>+ <Tab value="home" label="Home" />+ <Tab value="settings" label="Settings" />+ </TabList>,+ );+ const tab = screen.getByRole('button', {name: 'Settings'});+ const surface = tab.querySelector('span[aria-hidden="true"]');+ if (surface == null) {+ throw new Error('the tab has no hover surface to press');+ }+ // The controller writes the tab; the tab owns the strength and its+ // release, and the surface paints the pressed token at that strength on+ // both touch arms.+ expect(hasReleaseFade(tab)).toBe(true);+ expect(readsPressStrength(surface, '[data-astryx-press="on"]')).toBe(true);+ expect(readsPressStrength(surface)).toBe(true);+ });});diff --git a/packages/core/src/Thumbnail/Thumbnail.doc.mjs b/packages/core/src/Thumbnail/Thumbnail.doc.mjsindex 4e36bd7095..bf6fbd6aaa 100644--- a/packages/core/src/Thumbnail/Thumbnail.doc.mjs+++ b/packages/core/src/Thumbnail/Thumbnail.doc.mjs@@ -79,6 +79,8 @@ 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},],},usage: {diff --git a/packages/core/src/Thumbnail/Thumbnail.test.tsx b/packages/core/src/Thumbnail/Thumbnail.test.tsxindex 771a60fa84..3758cc00fd 100644--- a/packages/core/src/Thumbnail/Thumbnail.test.tsx+++ b/packages/core/src/Thumbnail/Thumbnail.test.tsx@@ -4,6 +4,7 @@ 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';describe('Thumbnail', () => {it('renders an image when src is provided', () => {@@ -243,3 +244,23 @@ describe('Thumbnail', () => {expect(img).toHaveAttribute('src', '/fixed.jpg');});});++describe('Thumbnail pressed state (touch)', () => {+ it('fades the touch press out on the interactive container, whose overlay layer reads its strength', () => {+ const {container} = render(+ <Thumbnail src="/img.jpg" alt="Clickable" onClick={vi.fn()} />,+ );+ const surface = container.querySelector('[data-astryx-pressable]');+ if (surface == null) {+ throw new Error('the interactive thumbnail carries no pressable marker');+ }+ expect(hasReleaseFade(surface)).toBe(true);+ expect(readsPressStrength(surface, '[data-astryx-press="on"]')).toBe(true);+ expect(readsPressStrength(surface)).toBe(true);+ });++ it('carries none of it when not interactive', () => {+ const {container} = render(<Thumbnail src="/img.jpg" alt="Static" />);+ expect(container.querySelector('[data-astryx-pressable]')).toBeNull();+ });+});diff --git a/packages/core/src/Thumbnail/Thumbnail.tsx b/packages/core/src/Thumbnail/Thumbnail.tsxindex 0366fde553..8f70540342 100644--- a/packages/core/src/Thumbnail/Thumbnail.tsx+++ b/packages/core/src/Thumbnail/Thumbnail.tsx@@ -45,6 +45,8 @@ import type {BaseProps} from '../BaseProps';import {mergeProps} from '../utils';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';+import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useTranslator} from '../i18n';export interface ThumbnailProps extends BaseProps<HTMLDivElement> {@@ -120,6 +122,12 @@ export interface ThumbnailProps extends BaseProps<HTMLDivElement> {// Styles// =============================================================================+// The touch press's paint, declared by the shared overlay styles on the+// 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 styles = stylex.create({root: {position: 'relative',@@ -164,11 +172,50 @@ const styles = stylex.create({':is(:disabled,[aria-disabled="true"])': 'default',},},- // Hover/pressed overlay — the exact same treatment as ClickableCard and+ // Hover and pressed overlay — the exact same treatment as ClickableCard and// SelectableCard. A transparent `::after` tints on hover/press instead of// 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.+ '--_press-overlay': {+ default: 'transparent',+ ':where(:not(:disabled,[aria-disabled="true"]))': {+ default: null,+ ':active': {+ default: colorVars['--color-overlay-pressed'],+ '@media (pointer: coarse)': 'transparent',+ },+ '@media (hover: hover)': {+ default: null,+ ':hover:where(:not(:disabled,[aria-disabled="true"]))':+ 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',@@ -176,19 +223,9 @@ const styles = stylex.create({borderRadius: 'inherit',pointerEvents: 'none',transitionProperty: 'background-color',- transitionDuration: durationVars['--duration-fast'],+ transitionDuration: 'var(--_press-overlay-transition)',transitionTimingFunction: easeVars['--ease-standard'],- backgroundColor: 'transparent',- },- ':active::after': {- backgroundColor: colorVars['--color-overlay-pressed'],- },- },- hoverOnPointer: {- '@media (hover: hover)': {- ':hover:where(:not(:disabled,[aria-disabled="true"]))::after': {- backgroundColor: colorVars['--color-overlay-hover'],- },+ backgroundColor: 'var(--_press-overlay)',},},interactiveButton: {@@ -303,6 +340,7 @@ export function Thumbnail({ref,...props}: ThumbnailProps) {+ const pressable = usePressFeedback();const t = useTranslator();// Track the exact src that failed (rather than a boolean) so a changed src@@ -409,12 +447,15 @@ export function Thumbnail({)}{...props}><div+ {...(isInteractive ? pressable : undefined)}{...mergeProps(focusOutlineProps.focusWithin(styles.imageContainer,isInteractive && styles.interactive,isInteractive && styles.overlay,- isInteractive && styles.hoverOnPointer,+ // The touch press's strength and release, on the element the+ // controller writes to; the `::after` above paints off it.+ isInteractive && interactionOverlayStyles.pressedAlpha,),isHoverReveal ? getContainerProps() : {},)}>diff --git a/packages/core/src/Token/Token.tsx b/packages/core/src/Token/Token.tsxindex 9ceecf1663..ec52cf6db4 100644--- a/packages/core/src/Token/Token.tsx+++ b/packages/core/src/Token/Token.tsx@@ -38,6 +38,7 @@ import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useTranslator} from '../i18n';import type {TokenColorMap} from './index';@@ -300,6 +301,10 @@ export function Token({ref,...rest}: TokenProps) {+ // Constant marker props; the hook's only effect is installing the shared+ // document controller once, so the token's output stays a pure function+ // of its props.+ const pressable = usePressFeedback();const t = useTranslator();const LinkComponent = useLinkComponent();const role = useInteractiveRole({href, onClick, isDisabled});@@ -346,6 +351,7 @@ export function Token({<LinkComponentref={ref as React.Ref<HTMLAnchorElement>}href={href as string}+ {...pressable}{...mergeProps(themeProps('token', {color, size}),focusOutlineProps.focusVisible(@@ -385,6 +391,7 @@ export function Token({endContent={endContent}removeButton={removeButton}linkStyleProps={stylex.props(styles.invisibleButton)}+ {...pressable}labelContent={<span{...stylex.props(@@ -427,6 +434,7 @@ export function Token({<spanref={ref}onClick={isDisabled ? undefined : handleContainerClick}+ {...pressable}{...mergeProps(themeProps('token', {color, size}),focusOutlineProps.focusWithin(diff --git a/packages/core/src/TopNav/TopNavItem.tsx b/packages/core/src/TopNav/TopNavItem.tsxindex 09111856d6..d69607f1cb 100644--- a/packages/core/src/TopNav/TopNavItem.tsx+++ b/packages/core/src/TopNav/TopNavItem.tsx@@ -37,6 +37,7 @@ import {useAppShellMobile} from '../AppShell/AppShellMobileContext';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';/*** NavItem styles with hover/selected states@@ -71,6 +72,16 @@ const styles = stylex.create({'@media (hover: hover)': colorVars['--color-neutral'],},':active': colorVars['--color-neutral'],+ // The touch press model writes these instead of `:active`; the selected+ // item keeps its fill under a finger the way it does under a mouse, and+ // paints no overlay at any phase of the press.+ '[data-astryx-press="on"]': colorVars['--color-neutral'],+ '[data-astryx-press="fading"]': colorVars['--color-neutral'],+ },+ backgroundImage: {+ default: null,+ '[data-astryx-press="on"]': 'none',+ '[data-astryx-press="fading"]': 'none',},},iconOnly: {@@ -185,6 +196,7 @@ export function TopNavItem({ref,...props}: TopNavItemProps) {+ const pressable = usePressFeedback();const LinkComponent = useLinkComponent(as);const renderMode = useTopNavRenderMode();const {closeMobileNav} = useAppShellMobile();@@ -221,6 +233,7 @@ export function TopNavItem({aria-current={isSelected ? 'page' : undefined}aria-disabled={isDisabled || undefined}tabIndex={isDisabled ? -1 : undefined}+ {...pressable}{...mergeProps(themeProps('top-nav-item', {mode: 'drawer',@@ -259,6 +272,7 @@ export function TopNavItem({aria-current={isSelected ? 'page' : undefined}aria-disabled={isDisabled || undefined}tabIndex={isDisabled ? -1 : undefined}+ {...pressable}{...mergeProps(themeProps('top-nav-item', {selected: isSelected ? 'selected' : null,diff --git a/packages/core/src/TopNav/TopNavMegaMenu.tsx b/packages/core/src/TopNav/TopNavMegaMenu.tsxindex a41daee9d3..e2308da7f1 100644--- a/packages/core/src/TopNav/TopNavMegaMenu.tsx+++ b/packages/core/src/TopNav/TopNavMegaMenu.tsx@@ -61,6 +61,7 @@ import {useTopNavRenderMode} from './TopNavRenderContext';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {useMergedRefs} from '../hooks/useMergedRefs';// =============================================================================@@ -553,6 +554,7 @@ function DrawerMegaMenu({}: Pick<TopNavMegaMenuProps, 'label' | 'items' | 'featured'> &BaseProps<HTMLButtonElement>) {const [isExpanded, setIsExpanded] = useState(false);+ const pressable = usePressFeedback();const menuId = `mega-menu-${label.toLowerCase().replace(/\s+/g, '-')}`;return (@@ -566,6 +568,7 @@ function DrawerMegaMenu({)}aria-expanded={isExpanded}aria-controls={`${menuId}-items`}+ {...pressable}{...mergeProps(themeProps('top-nav-mega-menu', {mode: 'drawer'}),focusOutlineProps.focusVisible(diff --git a/packages/core/src/TopNav/TopNavMegaMenuItem.tsx b/packages/core/src/TopNav/TopNavMegaMenuItem.tsxindex aeeb6d443c..c38cde52ae 100644--- a/packages/core/src/TopNav/TopNavMegaMenuItem.tsx+++ b/packages/core/src/TopNav/TopNavMegaMenuItem.tsx@@ -36,6 +36,7 @@ import {useAppShellMobile} from '../AppShell/AppShellMobileContext';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';// =============================================================================// Styles@@ -191,6 +192,7 @@ export function TopNavMegaMenuItem({as,tabIndex,}: TopNavMegaMenuItemProps) {+ const pressable = usePressFeedback();const renderMode = useTopNavRenderMode();const LinkComponent = useLinkComponent(as);const {closeMobileNav} = useAppShellMobile();@@ -209,6 +211,7 @@ export function TopNavMegaMenuItem({<Elementref={ref}href={href}+ {...pressable}onClick={handleDrawerClick}{...elementProps}{...mergeProps(@@ -240,6 +243,7 @@ export function TopNavMegaMenuItem({<Elementref={ref}href={href}+ {...pressable}onClick={onClick}tabIndex={tabIndex}{...mergeProps(diff --git a/packages/core/src/TopNav/TopNavMenu.tsx b/packages/core/src/TopNav/TopNavMenu.tsxindex 8f17336b53..9a44336883 100644--- a/packages/core/src/TopNav/TopNavMenu.tsx+++ b/packages/core/src/TopNav/TopNavMenu.tsx@@ -41,6 +41,7 @@ import {isSafeUrl} from '../utils/safeUrl';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {colorVars,spacingVars,@@ -345,6 +346,7 @@ export function TopNavMenu({onMouseLeave: onMouseLeaveProp,...rest}: TopNavMenuProps) {+ const pressable = usePressFeedback();const renderMode = useTopNavRenderMode();const {closeMobileNav} = useAppShellMobile();const LinkComponent = useLinkComponent();@@ -460,6 +462,7 @@ export function TopNavMenu({)}aria-expanded={drawerExpanded}aria-controls={`${menuId}-items`}+ {...pressable}{...mergeProps(focusOutlineProps.focusVisible(navItemStyles.item,@@ -492,6 +495,7 @@ export function TopNavMenu({<LinkComponentkey={getMenuItemKey(item)}href={item.href}+ {...pressable}onClick={(_e: React.MouseEvent) => {item.onClick?.();closeMobileNav();diff --git a/packages/core/src/TreeList/TreeListItem.tsx b/packages/core/src/TreeList/TreeListItem.tsxindex 09309ccb78..0a5acb2263 100644--- a/packages/core/src/TreeList/TreeListItem.tsx+++ b/packages/core/src/TreeList/TreeListItem.tsx@@ -26,6 +26,7 @@ import {} from '../theme/tokens.stylex';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {usePressFeedback} from '../hooks/usePressFeedback';import {Icon} from '../Icon';import {mergeProps} from '../utils';import {useLinkComponent} from '../Link/useLinkComponent';@@ -363,6 +364,7 @@ export function TreeListItem({setSize,isTabbable,}: TreeListItemInternalProps) {+ const pressable = usePressFeedback();const t = useTranslator();const labelId = useId();const descriptionId = useId();@@ -580,6 +582,9 @@ export function TreeListItem({)}<div {...stylex.props(styles.rowWrapper)}><div+ {...(isInteractive || (hasChildren && onClick == null)+ ? pressable+ : undefined)}{...mergeProps(themeProps('tree-list-item', {density,diff --git a/packages/core/src/__tests__/pressState.ts b/packages/core/src/__tests__/pressState.tsindex 2fbebcded2..8caabfda94 100644--- a/packages/core/src/__tests__/pressState.ts+++ b/packages/core/src/__tests__/pressState.ts@@ -2,8 +2,10 @@/*** @file pressState.ts- * @input Uses document.styleSheets (populated by StyleX runtime injection)- * @output Exports rulesDeclaredFor and expectPressedArm test helpers+ * @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* @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@@ -13,10 +15,21 @@* deliberately not pinned — a press may be read off the element itself* (`.x:active`) or off an ancestor scope marker (`.x:where(.marker:active *)`).*+ * The touch arms are asserted the same way: the paint reads the press's+ * strength (`--astryx-press-alpha`, see utils/interactionOverlay.stylex.ts)+ * and the element the controller writes to runs the release animation on the+ * machine's own clock.+ ** SYNC: When modified, update this header.*/+import {PRESS_FADE_MS} from '../utils/pressGesture';+const PRESSED_TOKEN = '--color-overlay-pressed';+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"]';function walk(list: CSSRuleList, visit: (rule: CSSRule) => void): void {for (const rule of Array.from(list)) {@@ -91,3 +104,67 @@ export function declaresPressedOverlay(el: Element): boolean {return !selector.includes(':') && rule.includes(PRESSED_TOKEN);});}++/**+ * Does the element paint the touch press through the press's strength while+ * `arm` matches — the pressed token at `var(--astryx-press-alpha)`? That one+ * declaration is the instant onset (strength 1 on the on arm) and the fade+ * (the release animates it to 0), so it is asserted on both arms; `arm`+ * defaults to the release's.+ */+export function readsPressStrength(el: Element, arm = FADING_ARM): boolean {+ return rulesWithSelector(el, arm).some(+ rule =>+ rule.includes(`var(${PRESS_PAINT}`) ||+ (rule.includes(PRESSED_TOKEN) && rule.includes(PRESS_STRENGTH)),+ );+}++/**+ * 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+ * styles and nowhere else; an element that composes one of them carries it,+ * and whatever paints for it reads the variable.+ */+export function declaresPressPaint(el: Element): boolean {+ return rulesDeclaredFor(el).some(+ rule =>+ rule.includes(`${PRESS_PAINT}:`) &&+ rule.includes(PRESSED_TOKEN) &&+ rule.includes(PRESS_STRENGTH),+ );+}++/** `.2s`, `200ms`, `0.2s` → 200. */+export function durationToMs(value: string): number {+ const match = value.trim().match(/^([\d.]+)(ms|s)$/);+ if (match == null) {+ return Number.NaN;+ }+ return Number(match[1]) * (match[2] === 's' ? 1000 : 1);+}++/**+ * Does the element run the release animation on the fading arm, for exactly+ * the machine's release clock ({@link PRESS_FADE_MS}), with no animation on+ * the on arm (the onset is instant)? Asserted on the element the controller+ * writes to — the one that composes `pressedAlpha` or an overlay variant — not+ * on a descendant that merely reads the strength.+ */+export function hasReleaseFade(el: Element): boolean {+ const fading = rulesWithSelector(el, FADING_ARM);+ const durations = fading.flatMap(rule => {+ const match = rule.match(/animation-duration:\s*([^;}]+)/);+ return match == null ? [] : [durationToMs(match[1])];+ });+ const named = fading.some(rule => /animation-name:\s*(?!none)/.test(rule));+ const onArmAnimates = rulesWithSelector(el, '[data-astryx-press="on"]').some(+ rule => rule.includes('animation'),+ );+ return (+ named &&+ durations.length === 1 &&+ durations[0] === PRESS_FADE_MS &&+ !onArmAnimates+ );+}diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex 52594de0aa..8b5ec922fe 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -124,6 +124,8 @@ export type {export {useLongPress} from './useLongPress';export type {UseLongPressOptions, UseLongPressHandlers} from './useLongPress';+export {usePressFeedback} from './usePressFeedback';+export {useDevWarning} from './useDevWarning';export {useIndicatorFocusRing} from './useIndicatorFocusRing';diff --git a/packages/core/src/hooks/usePressFeedback.doc.mjs b/packages/core/src/hooks/usePressFeedback.doc.mjsnew file mode 100644index 0000000000..713eea27a0--- /dev/null+++ b/packages/core/src/hooks/usePressFeedback.doc.mjs@@ -0,0 +1,83 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').HookDoc} */+export const docs = {+ name: 'usePressFeedback',+ displayName: 'usePressFeedback',+ keywords: [+ 'press',+ 'pressed',+ 'active',+ 'touch',+ 'tap',+ 'coarse pointer',+ 'pressable',+ 'interaction state',+ ],+ params: [],+ returns: [+ {+ name: 'pressableProps',+ type: "{'data-astryx-pressable': ''}",+ description:+ "The marker attribute to spread on the element that paints the press. Compose one of `interactionOverlayStyles` (from `@astryxdesign/core/utils`) on the same element — `backgroundColor` or `backgroundImage` for a surface whose hover and press are the system's overlays, `pressedBackgroundColor` for one whose hover is its own — and it paints the pressed token at the press's strength on the first frame of a believed press and fades it over the release, keeping `:active` for a mouse. A press is themed through `--color-overlay-pressed`.",+ },+ ],+ usage: {+ description:+ 'The touch press model every Astryx pressable uses, for a local component that paints its own press. Under a finger, CSS `:active` paints on the touch itself and can outlive the start of a scroll; the press model instead waits 150 ms before believing a press, cancels it the moment the finger travels 10 px or a scroll claims the gesture, never brings it back inside that gesture, answers a quick tap at the lift, and fades the release over 200 ms — the clocks a native list uses. One document-level controller does this for every marked element (installed by the first pressable to mount, removed by the last to unmount), so calling the hook adds no listener or state to your element. Under a mouse nothing changes: keep your `:active` rule, and drop it under `@media (pointer: coarse)` the way the built-in components do.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Spread the result on the element whose background paints the press and compose one of `interactionOverlayStyles` on it; the composed style is the instant onset, the hold and the fade, and it is themed through `--color-overlay-pressed`.',+ },+ {+ guidance: true,+ description:+ 'Let the composed style own the press on every pointer: it keeps `:active` for a mouse and drops it under `@media (pointer: coarse)`, so a finger sees only the press model. A rule of your own that paints `:active` would paint under a finger too, on the touch and through a scroll.',+ },+ {+ guidance: false,+ description:+ 'Add a pointer listener or React state to the element to track the press; the controller already writes the attribute, and per-element listeners are what a long list cannot afford.',+ },+ {+ guidance: false,+ description:+ 'Call it for a control rendered by an Astryx component; those are marked already, and the innermost marked element takes the press.',+ },+ ],+ },+ relatedComponents: ['Button', 'Item', 'ClickableCard'],+ relatedHooks: ['useLongPress'],+ importPath: '@astryxdesign/core/hooks',+ category: 'interaction',+};++/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */+export const docsDense = {+ description:+ 'Marks an element as a pressable surface of the touch press model (150 ms onset, 10 px slop, cancel on scroll, tap answers at lift, 200 ms fade) and installs the shared document controller. Returns the data-astryx-pressable marker to spread; compose one of interactionOverlayStyles on the same element to paint.',+ paramDescriptions: {},+ returnDescriptions: {+ pressableProps:+ 'marker attribute to spread on the painting element; compose one of interactionOverlayStyles (backgroundColor, backgroundImage, pressedBackgroundColor) there, which paints the press on every pointer; themed through --color-overlay-pressed.',+ },+ usage: {+ description:+ 'For a local component that paints its own press and must match Astryx under a finger. No per-element listener or state; one controller per document.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Spread on the painting element and compose one of interactionOverlayStyles there; add no :active rule of your own.',+ },+ {+ guidance: false,+ description:+ 'Track the press with your own pointer listeners or state, or call it on an Astryx component (already marked).',+ },+ ],+ },+};diff --git a/packages/core/src/hooks/usePressFeedback.ts b/packages/core/src/hooks/usePressFeedback.tsnew file mode 100644index 0000000000..1939ef5049--- /dev/null+++ b/packages/core/src/hooks/usePressFeedback.ts@@ -0,0 +1,52 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file usePressFeedback.ts+ * @input The document-level press controller (utils/pressFeedback.ts)+ * @output Exports usePressFeedback+ * @position Core hook; every component that paints a press calls it and+ * spreads its result on the element that paints+ *+ * SYNC: When modified, update:+ * - /packages/core/src/hooks/index.ts+ * - /packages/core/src/hooks/usePressFeedback.doc.mjs+ * - /packages/core/src/utils/pressFeedback.ts+ */++import {useEffect} from 'react';+import {installPressFeedback, pressableProps} from '../utils/pressFeedback';++/**+ * Mark an element as a pressable surface of the touch press model, and make+ * sure the document-level controller that drives it is installed.+ *+ * Spread the result on the element that paints the press, and compose one of+ * `interactionOverlayStyles` (from `@astryxdesign/core/utils`) on the same+ * element: `backgroundColor` or `backgroundImage` for a surface whose hover+ * and press are the system's overlays, `pressedBackgroundColor` for one+ * whose hover is its own. The controller writes its attribute on the element+ * while a touch press is believed (after the onset delay, cancelled by travel+ * or by a scroll) and for the release, and the composed style paints the+ * pressed token at the press's strength on the first frame and fades it over+ * the release, keeping `:active` for a mouse. A press is themed through+ * `--color-overlay-pressed`, which the hold, the flash and the fade all read.+ * Every Astryx component that paints a press already does this; reach for it+ * when a local component paints its own press and must behave like the rest+ * of the system under a finger.+ *+ * Installation is shared and counted: the first mounted pressable installs+ * the controller, the last one to unmount removes it. No per-element listener+ * or state is added — a press costs one attribute write on one element.+ *+ * @example+ * ```+ * const pressable = usePressFeedback();+ * return <div role="button" {...pressable} {...stylex.props(styles.row)} />;+ * ```+ */+export function usePressFeedback(): typeof pressableProps {+ useEffect(() => installPressFeedback(), []);+ return pressableProps;+}diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.tsindex ea421a4918..c19bf822db 100644--- a/packages/core/src/theme/derivedVarRegistry.test.ts+++ b/packages/core/src/theme/derivedVarRegistry.test.ts@@ -282,6 +282,17 @@ 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.+ '--_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.+ '--_press-paint',+ '--_press-paint-image','--_input-clear-hit-content',// Placement and swipe lifecycle values are private Toast behavior. A theme// author controls the surface transform/opacity as a whole, not these values.diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.tsindex 1f8e7157a9..c07928f4b7 100644--- a/packages/core/src/utils/index.ts+++ b/packages/core/src/utils/index.ts@@ -111,3 +111,10 @@ export {rtlStyles} from './rtlStyles';export {focusOutlineStyles, focusOutlineProps} from './focusOutline.stylex';export {isImeKeyEvent} from './ime';++// The touch press model's one composable: the shared hover and pressed overlay+// styles, which carry the press's strength, its release and its paint. A local+// pressable spreads the result of the `usePressFeedback` hook on the element+// that paints and composes one of these on it; the controller, its attributes+// and its clocks are internals.+export {interactionOverlayStyles} from './interactionOverlay.stylex';diff --git a/packages/core/src/utils/interactionOverlay.stylex.ts b/packages/core/src/utils/interactionOverlay.stylex.tsindex 843186b730..d35bc996c6 100644--- a/packages/core/src/utils/interactionOverlay.stylex.ts+++ b/packages/core/src/utils/interactionOverlay.stylex.ts@@ -7,72 +7,286 @@/*** @file Shared hover and pressed overlay states* @input Uses StyleX and the semantic interaction-overlay color tokens- * @output Exports reusable background-color and background-image state styles+ * @output Exports reusable background-color and background-image state styles,+ * the touch press's registered strength variable (`pressVars`) and its+ * clocks (`pressConsts`)* @position Internal styling utility for interactive core surfaces** Every surface that paints a press composes one of these (or carries its own- * `:active` rule), so a change to how the system answers a press is made here- * once. `pressedBackgroundColor` is the press without the hover, for controls- * whose hover is a colour or nothing.+ * `:active` rule in the same shape), so a change to how the system answers a+ * press is made here once. `pressedBackgroundColor` is the press without the+ * hover, for controls whose hover is a colour or nothing. `pressedAlpha` is the+ * touch press's strength alone, for an owner whose pressed paint lives on a+ * descendant or a pseudo-element.** Keep the enabled guard outside the individual states. StyleX assigns an* extra priority bucket (and generated selector specificity) to media-nested* rules. Repeating `:active` inside the hover-capable branch gives hover and* press the same generated specificity; StyleX's native pseudo-state ordering- * then emits `:active` last. The bare `:active` branch remains the touch- * fallback, where `(hover: hover)` does not match.+ * then emits `:active` last.+ *+ * TWO POINTERS, TWO PRESS MODELS. A mouse keeps `:active`. A finger does not:+ * on iOS Safari `:active` paints on the touch itself and can outlive the start+ * of a scroll, so under `@media (pointer: coarse)` the bare `:active` arm is+ * dropped and the press is written by the touch press controller+ * (`utils/pressFeedback.ts`) as `data-astryx-press="on"` once the press is+ * believed (150 ms, no travel, no scroll) and `data-astryx-press="fading"` for the+ * 200 ms release. The two arms paint those through ONE number:+ *+ * - `--astryx-press-alpha` is the press's strength, 0 to 1. It is a+ * registered custom property (`@property`, syntax `<number>`, declared once+ * in the shipped stylesheet by {@link pressVars}), which is what lets it+ * animate: the overlay itself is a gradient layer, and gradients do not+ * interpolate, but a registered number does, and every declaration that+ * reads it is re-resolved on each frame. The touch paint is the pressed+ * token at that strength — `color-mix(in srgb, pressed calc(alpha * 100%),+ * transparent)` — declared once here as `--_press-paint` and painted as a+ * background IMAGE: an image change is discrete, so a composer's colour+ * transition cannot fade the onset in.+ * - `[data-astryx-press="on"]` sets the strength to 1 and paints, on the+ * first frame. Nothing transitions a custom property a composer never named.+ * - `[data-astryx-press="fading"]` keeps the same paint and runs the release+ * animation, strength 1 → 0 over {@link PRESS_RELEASE_DURATION} (UIKit's+ * deselect crossfade; the controller removes the attribute when the same+ * clock runs out, and by then the paint is gone). It fades to nothing, not+ * to the hover strength: under a finger there is no hover to land on.+ *+ * WHY AN ANIMATION AND NOT A TRANSITION. Two reasons, both about composers.+ * StyleX is last-wins per property, and composers own their `transition-*`+ * longhands (Button, Item, Tab, Link, ...): the utility can neither append the+ * strength to their transition list nor set one of its own without taking the+ * whole property from them. No composer sets `animation-*` on the element that+ * composes these, so those longhands are free. And a transition needs the+ * declared value to change at the style change, which would make the release+ * arm declare strength 0; every property reading the strength would then+ * change computed value at the lift, and a composer that transitions+ * `background-image` (Button, Token, TreeListItem — Chromium interpolates+ * same-shape gradients) would start its own, shorter fade over this one. With+ * keyframes owning both ends the release arm declares 1 like the on arm, so at+ * the lift nothing a composer transitions changes; only the animation moves.+ *+ * Browser support: Chromium 111+, Safari 16.4+ and Firefox 128+ register the+ * property and interpolate. An engine without `@property` ignores the rule,+ * animates the unregistered value discretely (the paint holds for half the+ * release, then goes) — a step, no worse than the arm before this one.+ *+ * Composers must not set `backgroundImage` of their own on the colour variants+ * (none do): the touch arms own it. Composers must not set `animation-*` on+ * the element that composes any of these (none do): StyleX would drop either+ * the release animation or theirs.+ *+ * SYNC: When modified, update pressFeedback.ts, pressGesture.ts (the fade+ * clock), hooks/usePressFeedback.doc.mjs, the components that paint the touch+ * press off an ancestor scope or a pseudo-element (Switch, Tab,+ * CheckboxInput, RadioListItem, ClickableCard, SelectableCard, Thumbnail)+ * and scripts/build-css.test.mjs.*/import * as stylex from '@stylexjs/stylex';import {colorVars} from '../theme/tokens.stylex';+/**+ * The touch press's strength on the surface the controller painted, 0 to 1.+ *+ * Registered (`@property --astryx-press-alpha { syntax: "<number>";+ * initial-value: 0 }`) so it interpolates, and inherited, so an owner's+ * strength reaches the descendant that paints for it (a switch's track and+ * thumb, a tab's hover layer) and a card's or an indicator wrapper's+ * `::after`. Read it with `pressVars['--astryx-press-alpha']`, only inside a+ * `data-astryx-press` arm:+ * a pressed row's strength is 1 for everything inside the row.+ */+export const pressVars = stylex.defineVars({+ '--astryx-press-alpha': stylex.types.number(0),+});++/**+ * The touch press's clocks that both the stylesheet and the controller read.+ *+ * `defineConsts`, so the one number is inlined here at build time and is the+ * controller's constant at run time (`PRESS_FADE_MS` in pressGesture.ts):+ * the release animation and the timer that removes the attribute after it+ * cannot drift apart.+ */+export const pressConsts = stylex.defineConsts({+ /** How long the release takes, in ms. UIKit's deselect clock. */+ releaseMs: 200,+});++/** The release's clock as CSS. */+const PRESS_RELEASE_DURATION = `${pressConsts.releaseMs}ms`;+const ENABLED = ':where(:not(:disabled,[aria-disabled="true"]))';const HOVER_HOVER = '@media (hover: hover)';+const COARSE = '@media (pointer: coarse)';+/**+ * Written by the touch press controller while a press is believed. The+ * attribute is the system's own (`data-astryx-*`, like the pressable marker),+ * outside the namespace a theme's state keys generate into (`[data-<state>]`),+ * so a theme state can never collide with it.+ */+const PRESSED_ON = '[data-astryx-press="on"]';+/** Written by the touch press controller for the release's exit. */+const PRESSED_FADING = '[data-astryx-press="fading"]';++const PRESS_ALPHA = pressVars['--astryx-press-alpha'];const hoverImage = `linear-gradient(${colorVars['--color-overlay-hover']}, ${colorVars['--color-overlay-hover']})`;const pressedImage = `linear-gradient(${colorVars['--color-overlay-pressed']}, ${colorVars['--color-overlay-pressed']})`;const neutralImage = `linear-gradient(${colorVars['--color-neutral']}, ${colorVars['--color-neutral']})`;+/**+ * The pressed token at the touch press's current strength: the one+ * declaration of the press's paint. Declared as `--_press-paint` on the+ * element the controller writes to (every style below carries it), where the+ * strength is 1 while a press is believed and animates 1 → 0 over the+ * release, so its computed value follows the fade frame by frame and is+ * inherited, resolved, by whatever paints it: the element's own arms, a+ * descendant (a switch's track and thumb, a tab's hover layer), or a `::after`+ * (a card, an indicator owner). Those paint `var(--_press-paint)` or+ * `var(--_press-paint-image)` and never rebuild the expression;+ * pressPaintSource.test.ts holds it to this file.+ */+const pressedOverlayColor = `color-mix(in srgb, ${colorVars['--color-overlay-pressed']} calc(${PRESS_ALPHA} * 100%), transparent)`;+const pressPaint = {+ '--_press-paint': pressedOverlayColor,+ '--_press-paint-image':+ 'linear-gradient(var(--_press-paint), var(--_press-paint))',+};+/** The paint, read back off the element: the overlay's gradient layer. */+const pressedOverlayImage = 'var(--_press-paint-image)';++/** Strength 1 → 0; the release arm runs it over {@link PRESS_RELEASE_DURATION}. */+const pressRelease = stylex.keyframes({+ from: {[PRESS_ALPHA]: 1},+ to: {[PRESS_ALPHA]: 0},+});++/**+ * The release's curve: a gentle ease-out that spends the whole clock fading+ * (strength ≈ 0.2 at the midpoint), which is what a deselect crossfade reads+ * as. Not the system's `--ease-standard`: that curve is for things that move,+ * and is so front-loaded (strength 0.05 at the midpoint) that the release+ * would read as half its clock.+ */+const RELEASE_EASE = 'cubic-bezier(0, 0, 0.2, 1)';++/**+ * The touch press's strength and its release, on the element the controller+ * writes to. Every variant below carries both, as `[PRESS_ALPHA]:+ * pressStrength` and `...pressReleaseAnimation`; `pressedAlpha` is the pair+ * alone.+ *+ * Both objects are written with literal keys, and the strength's own key is+ * spelled inside each variant rather than here, on purpose. StyleX reads a+ * `stylex.create` call from the raw AST, so a computed key written inside+ * the call is still a computed key when it evaluates it. An object hoisted+ * out of the call has been through every other Babel plugin by the time the+ * spread is resolved, and a preset that lowers ES2015 (`next/babel` under+ * the default browserslist: apps/sandbox, and a consumer's source build) has+ * rewritten its computed keys into `_defineProperty` helper calls the+ * evaluator cannot follow, failing the build with "Referenced constant is+ * not defined". Literal keys survive the lowering; `PRESS_ALPHA` cannot be+ * one, since the variable's name is generated, so it stays at each use. The+ * literal keys equal PRESSED_ON and PRESSED_FADING above.+ */+const pressStrength = {+ default: null,+ '[data-astryx-press="on"]': 1,+ '[data-astryx-press="fading"]': 1,+};+const pressReleaseAnimation = {+ animationName: {+ default: null,+ '[data-astryx-press="fading"]': pressRelease,+ },+ animationDuration: {+ default: null,+ '[data-astryx-press="fading"]': PRESS_RELEASE_DURATION,+ },+ animationTimingFunction: {+ default: null,+ '[data-astryx-press="fading"]': RELEASE_EASE,+ },+ animationFillMode: {default: null, '[data-astryx-press="fading"]': 'both'},+};+export const interactionOverlayStyles = stylex.create({backgroundColor: {+ [PRESS_ALPHA]: pressStrength,+ ...pressReleaseAnimation,+ ...pressPaint,backgroundColor: {default: 'transparent',[ENABLED]: {default: null,- ':active': colorVars['--color-overlay-pressed'],+ ':active': {+ default: colorVars['--color-overlay-pressed'],+ [COARSE]: 'transparent',+ },[HOVER_HOVER]: {default: null,':hover': colorVars['--color-overlay-hover'],':active': colorVars['--color-overlay-pressed'],},+ // While the controller paints, the colour arms yield to the image. A+ // device with a touchscreen beside a mouse matches `:active` and the+ // emulated `:hover` under a finger too, and the press would otherwise+ // paint twice.+ [PRESSED_ON]: 'transparent',+ [PRESSED_FADING]: 'transparent',+ },+ },+ backgroundImage: {+ default: null,+ [ENABLED]: {+ default: null,+ [PRESSED_ON]: pressedOverlayImage,+ [PRESSED_FADING]: pressedOverlayImage,},},},backgroundImage: {+ [PRESS_ALPHA]: pressStrength,+ ...pressReleaseAnimation,+ ...pressPaint,backgroundImage: {default: null,[ENABLED]: {default: null,- ':active': pressedImage,+ ':active': {+ default: pressedImage,+ [COARSE]: 'none',+ },[HOVER_HOVER]: {default: null,':hover': hoverImage,':active': pressedImage,},+ [PRESSED_ON]: pressedOverlayImage,+ [PRESSED_FADING]: pressedOverlayImage,},},},backgroundImageOnNeutral: {+ [PRESS_ALPHA]: pressStrength,+ ...pressReleaseAnimation,+ ...pressPaint,backgroundImage: {default: neutralImage,[ENABLED]: {default: null,- ':active': `${pressedImage}, ${neutralImage}`,+ ':active': {+ default: `${pressedImage}, ${neutralImage}`,+ [COARSE]: neutralImage,+ },[HOVER_HOVER]: {default: null,':hover': `${hoverImage}, ${neutralImage}`,':active': `${pressedImage}, ${neutralImage}`,},+ [PRESSED_ON]: `${pressedOverlayImage}, ${neutralImage}`,+ [PRESSED_FADING]: `${pressedOverlayImage}, ${neutralImage}`,},},},@@ -80,15 +294,47 @@ export const interactionOverlayStyles = stylex.create({* The pressed arm alone, for a control whose hover answer is its own — a* text link changes colour, a disclosure row has none — so a press paints* the system's pressed overlay without adding a hover surface the control- * never had. Same enabled guard as the paired states above.+ * never had. Same enabled guard and the same two pointers as above.*/pressedBackgroundColor: {+ [PRESS_ALPHA]: pressStrength,+ ...pressReleaseAnimation,+ ...pressPaint,backgroundColor: {default: null,[ENABLED]: {default: null,- ':active': colorVars['--color-overlay-pressed'],+ ':active': {+ default: colorVars['--color-overlay-pressed'],+ [COARSE]: 'transparent',+ },+ // The mouse arm yields to the image while the controller paints; see+ // the colour variant above.+ [PRESSED_ON]: 'transparent',+ [PRESSED_FADING]: 'transparent',},},+ backgroundImage: {+ default: null,+ [ENABLED]: {+ default: null,+ [PRESSED_ON]: pressedOverlayImage,+ [PRESSED_FADING]: pressedOverlayImage,+ },+ },+ },+ /**+ * The touch press's strength and release, and no paint of its own, for the+ * element the controller writes to when the pressed paint lives elsewhere:+ * a switch row (its track and thumb paint), a checkbox or radio row (the+ * owner's layer over the indicator paints), a tab (its hover layer paints),+ * a card (its `::after` paints). Those paint `var(--_press-paint)` (or+ * `var(--_press-paint-image)`), which this element declares at its+ * strength, so the owner and the paint fade as one.+ */+ pressedAlpha: {+ [PRESS_ALPHA]: pressStrength,+ ...pressReleaseAnimation,+ ...pressPaint,},});diff --git a/packages/core/src/utils/pressFeedback.test.ts b/packages/core/src/utils/pressFeedback.test.tsnew file mode 100644index 0000000000..454a276da4--- /dev/null+++ b/packages/core/src/utils/pressFeedback.test.ts@@ -0,0 +1,566 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file pressFeedback.test.ts+ * @input pressFeedback.ts, pressGesture.ts and interactionOverlay.stylex.ts+ * @output Unit tests for the DOM half of the touch press model: one delegated+ * controller, one attribute, and the two properties a per-element hook+ * would give away — that the paint belongs to the element the finger landed+ * on and that a list pays nothing per row for it — plus the CSS arms the+ * attribute drives: the release runs on the machine's own clock+ * @position Testing; validates pressFeedback.ts in jsdom+ */++import * as stylex from '@stylexjs/stylex';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {+ durationToMs,+ hasReleaseFade,+ readsPressStrength,+ declaresPressPaint,+ rulesDeclaredFor,+ rulesWithSelector,+} from '../__tests__/pressState';+import {+ interactionOverlayStyles,+ pressConsts,+} from './interactionOverlay.stylex';+import {+ installPressFeedback,+ PRESSABLE_ATTRIBUTE,+ PRESSED_ATTRIBUTE,+} from './pressFeedback';+import {+ PRESS_FADE_MS,+ PRESS_FLASH_MS,+ PRESS_ONSET_MS,+ PRESS_SCROLL_BRAKE_MS,+ PRESS_SLOP_PX,+} from './pressGesture';++let release: () => void = () => undefined;+let scroller: HTMLElement;+let rows: HTMLElement[];++function press(+ element: Element,+ type: string,+ x: number,+ y: number,+ pointerType = 'touch',+): void {+ const event = new Event(type, {bubbles: true, cancelable: true});+ Object.assign(event, {clientX: x, clientY: y, pointerId: 1, pointerType});+ element.dispatchEvent(event);+}++const pressedRow = (): number =>+ rows.findIndex(row => row.getAttribute(PRESSED_ATTRIBUTE) === 'on');++function pressable(tag = 'div'): HTMLElement {+ const element = document.createElement(tag);+ element.setAttribute(PRESSABLE_ATTRIBUTE, '');+ return element;+}++beforeEach(() => {+ vi.useFakeTimers();+ document.body.innerHTML = '';+ scroller = document.createElement('div');+ rows = [];+ for (let index = 0; index < 4; index += 1) {+ const row = pressable();+ const label = document.createElement('span');+ label.textContent = `row ${index}`;+ row.appendChild(label);+ scroller.appendChild(row);+ rows.push(row);+ }+ document.body.appendChild(scroller);+ release = installPressFeedback();+});++afterEach(() => {+ release();+ vi.useRealTimers();+});++describe('the press reaches the surface the finger landed on', () => {+ it('paints the row after the delay, not before', () => {+ const label = rows[1].firstElementChild;+ if (label == null) {+ throw new Error('the row has no label to press');+ }+ press(label, 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS - 1);+ expect(pressedRow()).toBe(-1);+ vi.advanceTimersByTime(1);+ expect(pressedRow()).toBe(1);+ });++ it('paints the innermost surface when they nest', () => {+ const bubble = pressable('button');+ rows[2].appendChild(bubble);+ press(bubble, 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(bubble.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');+ expect(rows[2].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);+ });++ it('ignores a mouse entirely', () => {+ press(rows[0], 'pointerdown', 10, 10, 'mouse');+ vi.advanceTimersByTime(PRESS_ONSET_MS * 2);+ expect(pressedRow()).toBe(-1);+ });++ it('ignores a touch that lands outside every pressable', () => {+ const plain = document.createElement('div');+ document.body.appendChild(plain);+ press(plain, 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(document.querySelectorAll(`[${PRESSED_ATTRIBUTE}]`)).toHaveLength(0);+ });++ it('paints nothing on a disabled surface, and does not light the row around it', () => {+ const button = pressable('button');+ button.setAttribute('disabled', '');+ rows[1].appendChild(button);+ const ariaDisabled = pressable('button');+ ariaDisabled.setAttribute('aria-disabled', 'true');+ rows[2].appendChild(ariaDisabled);+ press(button, 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ press(button, 'pointerup', 10, 10);+ press(ariaDisabled, 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(document.querySelectorAll(`[${PRESSED_ATTRIBUTE}]`)).toHaveLength(0);+ });+});++describe('a scroll takes it away and nothing brings it back', () => {+ it('clears on a scroll from the ancestor scroller', () => {+ press(rows[1], 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(1);+ scroller.dispatchEvent(new Event('scroll'));+ expect(pressedRow()).toBe(-1);+ });++ it('clears on `pointercancel`, which iOS fires before the first scroll event', () => {+ press(rows[1], 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ press(rows[1], 'pointercancel', 10, 10);+ expect(pressedRow()).toBe(-1);+ });++ it('does not repaint a later row while the finger stays down', () => {+ // The list scrolls under a stationary finger and the paint would walk+ // down it, because `:active` outlived the scroll on a node a virtualized+ // list had already recycled.+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ scroller.dispatchEvent(new Event('scroll'));+ for (let y = 100; y < 400; y += 20) {+ press(rows[3], 'pointermove', 10, y);+ scroller.dispatchEvent(new Event('scroll'));+ vi.advanceTimersByTime(16);+ }+ press(rows[3], 'pointerup', 10, 400);+ vi.advanceTimersByTime(PRESS_ONSET_MS + PRESS_FADE_MS);+ expect(rows.some(row => row.hasAttribute(PRESSED_ATTRIBUTE))).toBe(false);+ });++ it('paints nothing at all when the scroller claims inside the delay (a fling)', () => {+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(30);+ press(rows[1], 'pointercancel', 10, 80);+ vi.advanceTimersByTime(PRESS_ONSET_MS * 2);+ expect(pressedRow()).toBe(-1);+ });++ it('hears the NEXT press, once the scrolling finger is up', () => {+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ press(rows[1], 'pointermove', 10, 400);+ press(rows[1], 'pointerup', 10, 400);++ press(rows[2], 'pointerdown', 10, 420);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(2);+ });++ it('hears the next press after a scroll that ended in `pointercancel`', () => {+ // A scroll-claimed gesture ends in `pointercancel`, never `pointerup`:+ // that is the shape a real flick has.+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ press(rows[1], 'pointercancel', 10, 100);+ vi.advanceTimersByTime(PRESS_SCROLL_BRAKE_MS + 10);++ press(rows[2], 'pointerdown', 10, 420);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(2);+ });++ it('is a brake, not a press, when it lands on a list that is still moving', () => {+ // Measured on iOS: a touch stopping a decelerating list highlights+ // nothing. Nothing else would cancel this press, because stopping the+ // scroll is what makes the scroll events stop.+ press(rows[0], 'pointerdown', 10, 10);+ press(rows[0], 'pointerup', 10, 10);+ scroller.dispatchEvent(new Event('scroll'));+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS * 2);+ expect(pressedRow()).toBe(-1);+ });++ it('presses normally once the list has come to rest', () => {+ press(rows[0], 'pointerdown', 10, 10);+ press(rows[0], 'pointerup', 10, 10);+ scroller.dispatchEvent(new Event('scroll'));+ vi.advanceTimersByTime(PRESS_SCROLL_BRAKE_MS + 10);+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(1);+ });++ it('a PROGRAMMATIC scroll does not swallow the press', () => {+ // Apps scroll things by themselves constantly: a pane pinned to the bottom+ // scrolls on every streamed frame, keyboard nav calls `scrollIntoView`, a+ // route change restores a position. None of those is a finger braking+ // anything.+ scroller.dispatchEvent(new Event('scroll'));+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(1);+ });++ it('a touch elsewhere does not make a programmatic scroll a brake', () => {+ // "Any finger anywhere, recently" is not enough: tap a control, then press+ // a button inside a pane that is scrolling on its own. No finger drove+ // that scroll, so the press stands.+ const elsewhere = document.createElement('button');+ document.body.appendChild(elsewhere);+ press(elsewhere, 'pointerdown', 10, 500);+ press(elsewhere, 'pointerup', 10, 500);+ scroller.dispatchEvent(new Event('scroll'));+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(1);+ });++ it('a MOUSE release does not count as a finger for the brake', () => {+ // A device can report a coarse pointer and still have a trackpad; a mouse+ // release inside the scroller must not make the next scroll there look+ // finger-driven.+ press(rows[0], 'pointerdown', 10, 10, 'mouse');+ press(rows[0], 'pointerup', 10, 10, 'mouse');+ scroller.dispatchEvent(new Event('scroll'));+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(1);+ });++ it('a scroll in ANOTHER scroller does not swallow the press', () => {+ const elsewhere = document.createElement('div');+ document.body.appendChild(elsewhere);+ press(rows[0], 'pointerdown', 10, 10);+ press(rows[0], 'pointerup', 10, 10);+ elsewhere.dispatchEvent(new Event('scroll', {bubbles: false}));+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(1);+ });++ it('clears when the finger travels past the slop, before any scroll event', () => {+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ press(rows[1], 'pointermove', 10, 100 + PRESS_SLOP_PX + 1);+ expect(pressedRow()).toBe(-1);+ });++ it('clears when a drag starts from the pressed element', () => {+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ rows[1].dispatchEvent(new Event('dragstart', {bubbles: true}));+ expect(pressedRow()).toBe(-1);+ });+});++describe('the release', () => {+ it('fades, then leaves no attribute behind', () => {+ press(rows[0], 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ press(rows[0], 'pointerup', 10, 10);+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');+ vi.advanceTimersByTime(PRESS_FADE_MS);+ expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);+ });++ it('answers a tap too quick for the delay, at the release', () => {+ press(rows[0], 'pointerdown', 10, 10);+ vi.advanceTimersByTime(20);+ press(rows[0], 'pointerup', 10, 10);+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');+ vi.advanceTimersByTime(PRESS_FLASH_MS);+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');+ vi.advanceTimersByTime(PRESS_FADE_MS);+ expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);+ });+});++describe('two touches in a row', () => {+ it('answers the second tap while the first is still fading', () => {+ press(rows[0], 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ press(rows[0], 'pointerup', 10, 10);+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');++ press(rows[2], 'pointerdown', 10, 300);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(2);+ expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);+ });++ it('paints nothing for a second finger while the first is still down', () => {+ press(rows[0], 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ const second = new Event('pointerdown', {bubbles: true});+ Object.assign(second, {+ clientX: 10,+ clientY: 300,+ pointerId: 2,+ pointerType: 'touch',+ });+ rows[2].dispatchEvent(second);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(rows.some(row => row.hasAttribute(PRESSED_ATTRIBUTE))).toBe(false);+ });+});++describe('no gesture is ever left painted', () => {+ // Every case here strands a pending timer if `apply` clears timers+ // unconditionally, and each one ends with a paint on a row nobody is+ // touching.++ it('a finger jittering inside the slop still gets its press', () => {+ // Every real finger produces `pointermove` during the 150 ms delay; only+ // a synthetic touch holds perfectly still.+ press(rows[1], 'pointerdown', 10, 100);+ for (let tick = 0; tick < 6; tick += 1) {+ vi.advanceTimersByTime(20);+ press(rows[1], 'pointermove', 10 + (tick % 2), 100 + (tick % 3));+ }+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(1);+ });++ it("a cancel inside a quick tap's flash still resolves to nothing", () => {+ // iOS Safari delivers `touchcancel` at `scrollend`, seconds after a tap,+ // so this is the common shape, not a corner case.+ press(rows[0], 'pointerdown', 10, 10);+ vi.advanceTimersByTime(20);+ press(rows[0], 'pointerup', 10, 10);+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');++ press(rows[0], 'pointercancel', 10, 10);+ vi.advanceTimersByTime(PRESS_FLASH_MS + PRESS_FADE_MS + 50);+ expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);+ });++ it('a scroll inside the release fade still resolves to nothing', () => {+ press(rows[0], 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ press(rows[0], 'pointerup', 10, 10);+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');++ scroller.dispatchEvent(new Event('scroll'));+ vi.advanceTimersByTime(PRESS_FADE_MS + 50);+ expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);+ });++ it('leaves nothing painted after any of the gestures a finger can produce', () => {+ // The guard for the whole class: whatever the sequence, once it is over+ // and every clock has run out, the list is bare.+ const gestures: (() => void)[] = [+ () => {+ press(rows[0], 'pointerdown', 10, 10);+ press(rows[0], 'pointerup', 10, 10);+ press(rows[0], 'pointercancel', 10, 10);+ },+ () => {+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ press(rows[1], 'pointerup', 10, 100);+ scroller.dispatchEvent(new Event('scroll'));+ },+ () => {+ press(rows[2], 'pointerdown', 10, 200);+ vi.advanceTimersByTime(40);+ press(rows[2], 'pointermove', 10, 260);+ press(rows[2], 'pointercancel', 10, 260);+ },+ () => {+ press(rows[3], 'pointerdown', 10, 300);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ scroller.dispatchEvent(new Event('scroll'));+ press(rows[3], 'pointerup', 10, 300);+ },+ () => {+ press(rows[0], 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ Object.defineProperty(document, 'visibilityState', {+ configurable: true,+ value: 'hidden',+ });+ document.dispatchEvent(new Event('visibilitychange'));+ Object.defineProperty(document, 'visibilityState', {+ configurable: true,+ value: 'visible',+ });+ },+ ];+ for (const gesture of gestures) {+ gesture();+ vi.advanceTimersByTime(+ PRESS_ONSET_MS + PRESS_FLASH_MS + PRESS_FADE_MS + 100,+ );+ expect(document.querySelectorAll(`[${PRESSED_ATTRIBUTE}]`)).toHaveLength(+ 0,+ );+ }+ });+});++describe('what the list pays for it', () => {+ it('adds no listener to any row', () => {+ const row = pressable();+ const added: string[] = [];+ row.addEventListener = ((type: string) =>+ added.push(type)) as typeof row.addEventListener;+ scroller.appendChild(row);+ press(row, 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(added).toEqual([]);+ });++ it('installs once, however many times it is called, and stays while any holder remains', () => {+ const second = installPressFeedback();+ press(rows[0], 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(0);+ press(rows[0], 'pointerup', 10, 10);+ vi.advanceTimersByTime(PRESS_FADE_MS);+ second();+ // The first holder (beforeEach) is still there: presses are still heard.+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(1);+ });++ it('comes down with the last holder, taking any paint with it', () => {+ press(rows[0], 'pointerdown', 10, 10);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(0);+ release();+ expect(pressedRow()).toBe(-1);+ press(rows[1], 'pointerdown', 10, 100);+ vi.advanceTimersByTime(PRESS_ONSET_MS);+ expect(pressedRow()).toBe(-1);+ // Re-install for afterEach's release.+ release = installPressFeedback();+ });+});++describe('the release fades: the arms the controller writes to', () => {+ // The CSS half of the model, asserted off the StyleX dev runtime's injected+ // rules the way the component tests do. jsdom runs no animation, so what is+ // held here is the declaration: which arm animates, on which clock, and+ // what the paint reads.+ const variants = [+ 'backgroundColor',+ 'backgroundImage',+ 'backgroundImageOnNeutral',+ 'pressedBackgroundColor',+ ] as const;++ function surface(+ style: (typeof interactionOverlayStyles)[keyof typeof interactionOverlayStyles],+ ): HTMLElement {+ const element = pressable('button');+ element.className = stylex.props(style).className ?? '';+ document.body.appendChild(element);+ return element;+ }++ it("runs the release animation on the fading arm, for the machine's clock, on every variant", () => {+ for (const variant of variants) {+ expect(+ hasReleaseFade(surface(interactionOverlayStyles[variant])),+ variant,+ ).toBe(true);+ }+ expect(hasReleaseFade(surface(interactionOverlayStyles.pressedAlpha))).toBe(+ true,+ );+ });++ it("the machine's clock is the stylesheet's constant: one number", () => {+ expect(PRESS_FADE_MS).toBe(pressConsts.releaseMs);+ expect(hasReleaseFade(surface(interactionOverlayStyles.pressedAlpha))).toBe(+ true,+ );+ });++ it("declares the press's paint at its strength on every variant, the one place the formula lives", () => {+ for (const variant of variants) {+ expect(+ declaresPressPaint(surface(interactionOverlayStyles[variant])),+ variant,+ ).toBe(true);+ }+ expect(+ declaresPressPaint(surface(interactionOverlayStyles.pressedAlpha)),+ ).toBe(true);+ });++ it("paints both touch arms as the pressed token at the press's strength, and declares the strength 1 on both", () => {+ for (const variant of variants) {+ const element = surface(interactionOverlayStyles[variant]);+ expect(+ readsPressStrength(element, '[data-astryx-press="on"]'),+ variant,+ ).toBe(true);+ expect(readsPressStrength(element), variant).toBe(true);+ // The fading arm declares 1, like the on arm: only the animation moves+ // the strength, so nothing a composer transitions changes at the lift.+ for (const arm of [+ '[data-astryx-press="on"]',+ '[data-astryx-press="fading"]',+ ]) {+ expect(+ rulesWithSelector(element, arm).some(rule =>+ /--astryx-press-alpha:\s*1\b/.test(rule),+ ),+ `${variant} ${arm}`,+ ).toBe(true);+ }+ // ...and lands on nothing, not on the hover strength: under a finger+ // there is no hover.+ expect(+ rulesWithSelector(element, '[data-astryx-press="fading"]').some(rule =>+ rule.includes('--color-overlay-hover'),+ ),+ variant,+ ).toBe(false);+ }+ });++ it('pressedAlpha owns the strength and the release and paints nothing itself', () => {+ const element = surface(interactionOverlayStyles.pressedAlpha);+ expect(+ rulesDeclaredFor(element).some(rule => rule.includes('background')),+ ).toBe(false);+ expect(readsPressStrength(element)).toBe(false);+ });+});diff --git a/packages/core/src/utils/pressFeedback.ts b/packages/core/src/utils/pressFeedback.tsnew file mode 100644index 0000000000..60294c0851--- /dev/null+++ b/packages/core/src/utils/pressFeedback.ts@@ -0,0 +1,461 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file pressFeedback.ts+ * @input The press state machine (pressGesture.ts) and the document's pointer,+ * scroll and visibility events+ * @output Exports PRESSABLE_ATTRIBUTE, PRESSED_ATTRIBUTE, pressableProps and+ * installPressFeedback+ * @position The DOM half of the touch press model: one delegated controller+ * per document that writes `data-astryx-press` on the nearest pressable surface.+ * Installed by usePressFeedback (hooks/usePressFeedback.ts) on first mount;+ * the CSS arms that read the attribute live in interactionOverlay.stylex.ts+ * and in each component with its own `:active` rule. Tested by+ * pressFeedback.test.ts.+ *+ * ONE listener set for every pressable surface in the document.+ *+ * Why a delegated document-level controller and not a hook on the element: a+ * virtualized list can carry more than a thousand rows, and four listeners+ * plus a state hook per row is not a cost a list like that can pay. This is+ * six listeners for the whole document, and a press costs one attribute write+ * on one element: no React render, no subscription, no per-element anything.+ * It also makes the behaviour uniform for free: every component that paints a+ * press carries {@link PRESSABLE_ATTRIBUTE}, so all of them change together.+ *+ * Under a mouse the controller does nothing and CSS `:active` keeps the press,+ * as it always has. Under a finger the `:active` arm is dropped by the CSS+ * (`@media (pointer: coarse)`) and this writes `data-astryx-press="on"` when the+ * press is believed and `data-astryx-press="fading"` for the release's exit.+ *+ * SYNC: When modified, update pressGesture.ts, hooks/usePressFeedback.ts,+ * utils/interactionOverlay.stylex.ts and pressFeedback.test.ts.+ */++import type {PressGesture, PressPaint, PressStep} from './pressGesture';+import {+ idlePressGesture,+ PRESS_FADE_MS,+ PRESS_FLASH_MS,+ PRESS_ONSET_MS,+ PRESS_SCROLL_BRAKE_MS,+ pressGestureStep,+} from './pressGesture';++/**+ * The marker the controller finds with `closest()`. Every Astryx component+ * that paints a press carries it on the element that paints; a local+ * component can opt in by spreading {@link pressableProps} (or calling+ * `usePressFeedback`) on its own pressable element and reading+ * {@link PRESSED_ATTRIBUTE} in its styles.+ */+export const PRESSABLE_ATTRIBUTE = 'data-astryx-pressable';++/** `on` while the press is believed and the finger is down; `fading` for the release's exit. */+export const PRESSED_ATTRIBUTE = 'data-astryx-press';++/** Spread onto the element that paints the press. */+export const pressableProps: {readonly [PRESSABLE_ATTRIBUTE]: ''} = {+ [PRESSABLE_ATTRIBUTE]: '',+};++/**+ * How long after a touch a scroll can still be that finger's momentum.+ *+ * iOS momentum runs for a second or two after the lift; past this window a+ * scroll is the program moving something, not a list still gliding.+ */+export const PRESS_GESTURE_MEMORY_MS = 3000;++/** A surface that is not enabled does not press, however it is touched. */+const DISABLED = ':disabled, [aria-disabled="true"]';++interface LiveGesture {+ element: HTMLElement;+ gesture: PressGesture;+ /** The pointer this gesture belongs to; a second finger is ignored. */+ pointerId: number | null;+ timer: ReturnType<typeof setTimeout> | null;+}++let live: LiveGesture | null = null;+/** How many callers hold the controller installed; listeners exist while > 0. */+let holders = 0;+/**+ * When a scroller last moved UNDER A FINGER OF ITS OWN, and which one.+ *+ * Only a finger-driven scroll is recorded, so the brake cannot fire for a+ * scroll the app performed itself. The test is the touch's own target: a+ * scroll is that finger's if the finger was inside the scroller that moved,+ * within {@link PRESS_GESTURE_MEMORY_MS}.+ */+let lastScrollAt = 0;+let lastScroller: Node | null = null;+/** When a finger was last on the glass, and where it landed. */+let lastTouchAt = 0;+let lastTouchTarget: Node | null = null;++const TIMER_MS: Record<NonNullable<PressStep['timer']>, number> = {+ fade: PRESS_FADE_MS,+ flash: PRESS_FLASH_MS,+ onset: PRESS_ONSET_MS,+};++const TIMER_EVENT = {+ fade: 'fadeEnd',+ flash: 'flashEnd',+ onset: 'onset',+} as const;++function paintElement(element: HTMLElement, paint: PressPaint): void {+ if (paint === 'none') {+ element.removeAttribute(PRESSED_ATTRIBUTE);+ return;+ }+ element.setAttribute(PRESSED_ATTRIBUTE, paint);+}++function clearTimer(): void {+ if (live?.timer != null) {+ clearTimeout(live.timer);+ live.timer = null;+ }+}++/**+ * Run one event through the machine and make the DOM say what it answered.+ *+ * THE TIMER RULE, and why it is not "clear, then maybe re-arm": a step that+ * returns `timer: null` WITHOUT changing phase is a pass-through, and the+ * phase it left running still owes its transition. Clearing unconditionally+ * strands three gestures, each ending with a paint on a control nobody is+ * touching, until some later touch happens to clean it up:+ *+ * - a finger that jitters inside the slop during the 150 ms delay (which is+ * every real finger; only a synthetic touch holds perfectly still) kills+ * the onset timer, so the press never paints at all;+ * - a `pointercancel` or a scroll inside a quick tap's 100 ms flash kills+ * `flashEnd`, leaving `data-astryx-press="on"` painted indefinitely. iOS Safari+ * delivers that cancel at `scrollend`, seconds after the tap, so it is not+ * a corner case;+ * - the same inside the 200 ms fade strands `data-astryx-press="fading"` and the+ * controller's single tracking slot, holding a reference to an element a+ * virtualized list may already have unmounted.+ */+function apply(step: PressStep): void {+ if (live == null) {+ return;+ }+ const phaseMoved = step.gesture.phase !== live.gesture.phase;+ if (step.timer != null || phaseMoved) {+ clearTimer();+ }+ live.gesture = step.gesture;+ paintElement(live.element, step.paint);+ if (step.gesture.phase === 'idle') {+ live = null;+ return;+ }+ if (step.timer != null) {+ const kind = step.timer;+ // A TIMER, never `requestAnimationFrame`: iOS throttles frame callbacks+ // while a scroll runs, so a frame-based delay would fire late, after the+ // scroll, and paint a control nobody is pressing any more.+ live.timer = setTimeout(() => {+ if (live != null) {+ live.timer = null;+ }+ apply(+ pressGestureStep(live?.gesture ?? idlePressGesture(), {+ kind: TIMER_EVENT[kind],+ }),+ );+ }, TIMER_MS[kind]);+ }+}++/**+ * The innermost pressable surface at the touch, or nothing.+ *+ * Innermost wins: a button inside a pressable row takes the press, the way a+ * button inside a native cell takes the highlight instead of the cell. A+ * disabled surface takes it and paints nothing, so a press on a disabled+ * control does not light the row around it.+ */+function surfaceAt(target: EventTarget | null): HTMLElement | null {+ if (!(target instanceof Element)) {+ return null;+ }+ const found = target.closest(`[${PRESSABLE_ATTRIBUTE}]`);+ if (!(found instanceof HTMLElement) || found.matches(DISABLED)) {+ return null;+ }+ return found;+}++/**+ * Is this touch a BRAKE on a list the finger set moving, rather than a press?+ *+ * A native list highlights nothing for one, and nothing else would cancel it:+ * stopping the scroll is exactly what makes the scroll events stop arriving,+ * so there is no later signal to react to.+ *+ * Two narrowings, because "a scroll happened recently" is far too broad and+ * would swallow presses nobody asked it to. Apps scroll things by themselves+ * all the time: a transcript pinned to the bottom scrolls on every streamed+ * frame, keyboard navigation calls `scrollIntoView`, a route change restores+ * a position. None of those is a finger braking anything.+ *+ * 1. The scroller must CONTAIN the pressed element. A pane scrolling itself+ * says nothing about a control elsewhere.+ * 2. The scroll must have been driven by a finger IN THAT SCROLLER, which is+ * what `onScroll` records. "Any finger anywhere, recently" is not enough:+ * tap a control, then within the memory window press a button inside a+ * pane that is scrolling on its own, and that press would be swallowed by+ * a scroll no finger drove.+ */+function scrollerIsBraking(element: HTMLElement): boolean {+ if (Date.now() - lastScrollAt >= PRESS_SCROLL_BRAKE_MS) {+ return false;+ }+ return lastScroller instanceof Node && lastScroller.contains(element);+}++/**+ * Let go of the controller's one tracking slot once the gesture is over.+ *+ * A gesture that became a scroll ends in `pointercancel`, not `pointerup`, so+ * without this the dead gesture holds the slot for ever and every press after+ * the first scroll is swallowed.+ */+function releaseIfDead(): void {+ if (live?.gesture.phase === 'dead') {+ clearTimer();+ live = null;+ }+}++/** Drop the paint and forget the gesture, without running the machine. */+function finish(): void {+ if (live == null) {+ return;+ }+ clearTimer();+ live.element.removeAttribute(PRESSED_ATTRIBUTE);+ live = null;+}++function onPointerDown(event: PointerEvent): void {+ // A mouse already has hover and keeps `:active`; the treatment's CSS is+ // inside `@media (pointer: coarse)`. Not tracking it keeps desktop identical+ // and costs the mouse path nothing.+ if (event.pointerType === 'mouse') {+ return;+ }+ if (live != null) {+ const fingerIsUp =+ live.gesture.phase === 'fading' || live.gesture.phase === 'flash';+ // A finger still down means a SECOND finger: a pinch or a two-finger+ // scroll is not a press, so the first gesture ends and the second paints+ // nothing.+ if (!fingerIsUp) {+ finish();+ return;+ }+ // A finger already up means the last tap is still fading. The new touch+ // owns the surface from here; swallowing it would make the second of two+ // quick taps answer with nothing.+ finish();+ }+ const element = surfaceAt(event.target);+ // The touch clock is stamped AFTER the brake reads it, deliberately: the+ // question the brake asks is whether a PREVIOUS finger could still be+ // driving this scroll, and stamping first would make every first touch on a+ // freshly restored page answer yes.+ const braking = element != null && scrollerIsBraking(element);+ lastTouchAt = Date.now();+ lastTouchTarget = event.target instanceof Node ? event.target : null;+ if (element == null || braking) {+ return;+ }+ live = {+ element,+ gesture: idlePressGesture(),+ pointerId: event.pointerId,+ timer: null,+ };+ apply(+ pressGestureStep(live.gesture, {+ kind: 'down',+ x: event.clientX,+ y: event.clientY,+ }),+ );+}++function onPointerMove(event: PointerEvent): void {+ if (+ live == null ||+ (live.pointerId != null && event.pointerId !== live.pointerId)+ ) {+ return;+ }+ apply(+ pressGestureStep(live.gesture, {+ kind: 'move',+ x: event.clientX,+ y: event.clientY,+ }),+ );+}++function onPointerUp(event: PointerEvent): void {+ // The mouse exclusion applies to the brake's clocks too, not only to the+ // paint: a mouse release inside a scroller would make the next wheel or+ // programmatic scroll there look finger-driven, which swallows a real touch+ // press landing inside the brake window. A coarse pointer and a mouse can+ // both be present on one device.+ if (event.pointerType === 'mouse') {+ return;+ }+ // The lift is when momentum starts, so it is the clock the brake wants most.+ lastTouchAt = Date.now();+ if (event.target instanceof Node) {+ lastTouchTarget = event.target;+ }+ if (+ live == null ||+ (live.pointerId != null && event.pointerId !== live.pointerId)+ ) {+ return;+ }+ apply(pressGestureStep(live.gesture, {kind: 'up'}));+ releaseIfDead();+}++/**+ * The scroller claimed the gesture, or the platform took it.+ *+ * `pointercancel` is the primary one: measured on iOS 26.2 it fires before+ * the first `scroll` event (+303 ms against +304 ms on a slow drag, +31 ms+ * against +47 ms on a fling), which is what puts this cancel one frame ahead+ * of the list's motion, the way UIKit's `touchesCancelled` is.+ */+function onCancel(): void {+ if (live == null) {+ return;+ }+ apply(pressGestureStep(live.gesture, {kind: 'cancel'}));+ // The pointer is gone: a scroll-claimed gesture sends no further pointer+ // events, so nothing else would ever free the slot.+ releaseIfDead();+}++/** A scroll anywhere above the pressed element, caught in the capture phase. */+function onScroll(event: Event): void {+ const scroller = event.target instanceof Node ? event.target : document;+ // A scroll counts as a finger's only if that finger was inside THIS+ // scroller, recently. Anything else is the program moving something, and+ // must leave the brake unarmed rather than merely un-refreshed.+ const driven =+ Date.now() - lastTouchAt < PRESS_GESTURE_MEMORY_MS &&+ lastTouchTarget != null &&+ scroller.contains(lastTouchTarget);+ if (driven) {+ lastScrollAt = Date.now();+ lastScroller = scroller;+ }+ if (live == null) {+ return;+ }+ // The CANCEL arm is deliberately wider than the brake: any scroll above the+ // pressed element takes the gesture, driven by a finger or not.+ const reaches = scroller === document || scroller.contains(live.element);+ if (!reaches) {+ return;+ }+ onCancel();+}++/**+ * The backstop: a surface that leaves the document while it is painted must+ * not come back painted. A virtualized list mounts and unmounts rows as they+ * cross the scrollport, and React re-uses elements; the scroll cancel already+ * makes that unreachable while a press is live, because recycling needs a+ * scroll.+ */+function onVisibilityChange(): void {+ if (document.visibilityState === 'hidden') {+ finish();+ }+}++const PASSIVE_CAPTURE = {capture: true, passive: true} as const;++function addListeners(): void {+ window.addEventListener('pointerdown', onPointerDown, PASSIVE_CAPTURE);+ window.addEventListener('pointermove', onPointerMove, PASSIVE_CAPTURE);+ window.addEventListener('pointerup', onPointerUp, PASSIVE_CAPTURE);+ window.addEventListener('pointercancel', onCancel, PASSIVE_CAPTURE);+ window.addEventListener('touchcancel', onCancel, PASSIVE_CAPTURE);+ // `dragstart`, and NOT `contextmenu`: a long press that becomes a drag has+ // taken the gesture, but a right-click is a mouse act this controller never+ // tracks, and listening for it would read as a takeover of the browser's+ // own menu.+ window.addEventListener('dragstart', onCancel, PASSIVE_CAPTURE);+ // `scroll` does not bubble, so the capture phase is the only way one+ // listener hears every scroller in the document.+ document.addEventListener('scroll', onScroll, PASSIVE_CAPTURE);+ document.addEventListener('visibilitychange', onVisibilityChange);+}++function removeListeners(): void {+ window.removeEventListener('pointerdown', onPointerDown, PASSIVE_CAPTURE);+ window.removeEventListener('pointermove', onPointerMove, PASSIVE_CAPTURE);+ window.removeEventListener('pointerup', onPointerUp, PASSIVE_CAPTURE);+ window.removeEventListener('pointercancel', onCancel, PASSIVE_CAPTURE);+ window.removeEventListener('touchcancel', onCancel, PASSIVE_CAPTURE);+ window.removeEventListener('dragstart', onCancel, PASSIVE_CAPTURE);+ document.removeEventListener('scroll', onScroll, PASSIVE_CAPTURE);+ document.removeEventListener('visibilitychange', onVisibilityChange);+}++/**+ * Install the touch press controller on this document, once, however many+ * times it is called: the listeners exist while at least one caller holds it.+ *+ * Every Astryx pressable calls this through `usePressFeedback` on mount, so+ * an app needs no wiring; call it directly from module scope when a page has+ * pressable surfaces of its own and no Astryx component on it.+ *+ * @returns A release function. Call it once per install; the listeners come+ * down when the last holder releases, and the paint and the brake's clocks+ * are reset with them, so a later install never inherits a gesture that+ * never happened.+ */+export function installPressFeedback(): () => void {+ if (typeof window === 'undefined') {+ return () => undefined;+ }+ if (holders === 0) {+ addListeners();+ }+ holders += 1;+ let released = false;+ return () => {+ if (released) {+ return;+ }+ released = true;+ holders -= 1;+ if (holders > 0) {+ return;+ }+ removeListeners();+ finish();+ lastScrollAt = 0;+ lastScroller = null;+ lastTouchAt = 0;+ lastTouchTarget = null;+ };+}diff --git a/packages/core/src/utils/pressGesture.test.ts b/packages/core/src/utils/pressGesture.test.tsnew file mode 100644index 0000000000..90bcecc5d6--- /dev/null+++ b/packages/core/src/utils/pressGesture.test.ts@@ -0,0 +1,273 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file pressGesture.test.ts+ * @input pressGesture.ts+ * @output Unit tests for the press state machine, one case per requirement+ * of the touch press model, in the model's order+ * @position Testing; validates pressGesture.ts without a browser+ *+ * Every number these assert against was measured on an iPhone simulator+ * driving the real Settings and Contacts apps with real HID touches at+ * 60 fps. The test names say the behaviour, not the mechanism, so a rewrite+ * of the machine still has to keep them.+ */++import {describe, expect, it} from 'vitest';+import type {PressEvent, PressGesture, PressPaint} from './pressGesture';+import {+ idlePressGesture,+ PRESS_FADE_MS,+ PRESS_FLASH_MS,+ PRESS_ONSET_MS,+ PRESS_SLOP_PX,+ pressGestureStep,+} from './pressGesture';++/** Drive a gesture and collect what was painted after each event. */+function run(events: PressEvent[]): {+ paints: PressPaint[];+ gesture: PressGesture;+} {+ let gesture = idlePressGesture();+ const paints: PressPaint[] = [];+ for (const event of events) {+ const step = pressGestureStep(gesture, event);+ gesture = step.gesture;+ paints.push(step.paint);+ }+ return {gesture, paints};+}++const down = (x = 100, y = 100): PressEvent => ({kind: 'down', x, y});+const move = (x: number, y: number): PressEvent => ({kind: 'move', x, y});++describe('the clocks are the native ones', () => {+ it("waits the scroll view's content-touch delay before believing a press", () => {+ // `UIScrollView.delaysContentTouches` holds a content touch 0.15 s.+ // Measured: a 1.5 s hold painted the native highlight for 1.34 s.+ expect(PRESS_ONSET_MS).toBe(150);+ });++ it("uses the scroller's own slop, the release's own fade, and a flash for a quick tap", () => {+ expect(PRESS_SLOP_PX).toBe(10);+ expect(PRESS_FADE_MS).toBe(200);+ expect(PRESS_FLASH_MS).toBe(100);+ });+});++describe('nothing paints until the press is believed', () => {+ it('paints nothing on the touch itself', () => {+ const {paints, gesture} = run([down()]);+ expect(paints).toEqual(['none']);+ expect(gesture.phase).toBe('armed');+ });++ it('asks for the onset timer, and only then', () => {+ expect(pressGestureStep(idlePressGesture(), down()).timer).toBe('onset');+ });++ it('never paints for a fling: the scroller claims it inside the delay', () => {+ // Measured: `pointercancel` at +31 ms on a fling, 119 ms before the onset+ // timer would have fired.+ const {paints} = run([down(), move(100, 90), {kind: 'cancel'}]);+ expect(paints).toEqual(['none', 'none', 'none']);+ });+});++describe('a held press paints instantly and completely', () => {+ it('paints on the onset, with no transition state in between', () => {+ const {paints, gesture} = run([down(), {kind: 'onset'}]);+ expect(paints).toEqual(['none', 'on']);+ expect(gesture.phase).toBe('pressed');+ });+});++describe('travel cancels, and a shaky hand does not', () => {+ it('keeps the press while the finger stays inside the slop', () => {+ // Measured: a 4 pt drag over 2 s kept the native highlight for the whole+ // gesture.+ const inside = PRESS_SLOP_PX - 1;+ const {paints, gesture} = run([+ down(),+ {kind: 'onset'},+ move(100, 100 + inside),+ ]);+ expect(paints).toEqual(['none', 'on', 'on']);+ expect(gesture.phase).toBe('pressed');+ });++ it('cancels the moment the finger passes the slop, painted or not', () => {+ const beyond = PRESS_SLOP_PX + 1;+ const painted = run([down(), {kind: 'onset'}, move(100, 100 + beyond)]);+ expect(painted.paints.at(-1)).toBe('none');+ expect(painted.gesture.phase).toBe('dead');++ const unpainted = run([down(), move(100, 100 + beyond)]);+ expect(unpainted.paints).toEqual(['none', 'none']);+ expect(unpainted.gesture.phase).toBe('dead');+ });++ it('measures travel from where the finger landed, not from the last move', () => {+ // Otherwise a slow drag never trips the slop: each step is small, and the+ // press would ride a scroll all the way down the list.+ const creep: PressEvent[] = [];+ for (let y = 101; y <= 100 + PRESS_SLOP_PX + 2; y += 1) {+ creep.push(move(100, y));+ }+ const {gesture} = run([down(), {kind: 'onset'}, ...creep]);+ expect(gesture.phase).toBe('dead');+ });+});++describe("the scroller's claim cancels", () => {+ it('drops the paint with no fade', () => {+ // Measured: the native highlight goes from full to bare in ONE frame, and+ // 45 ms BEFORE the list's content first moves.+ const {paints, gesture} = run([down(), {kind: 'onset'}, {kind: 'cancel'}]);+ expect(paints).toEqual(['none', 'on', 'none']);+ expect(gesture.phase).toBe('dead');+ });++ it('asks for no timer on the way out, so nothing can fire later', () => {+ const armed = pressGestureStep(idlePressGesture(), down()).gesture;+ const pressed = pressGestureStep(armed, {kind: 'onset'}).gesture;+ expect(pressGestureStep(pressed, {kind: 'cancel'}).timer).toBeNull();+ });+});++describe('a cancelled gesture is dead', () => {+ it('does not come back when the finger stops moving', () => {+ const {paints, gesture} = run([+ down(),+ {kind: 'onset'},+ move(100, 200),+ move(100, 200),+ move(100, 201),+ ]);+ expect(paints.slice(2)).toEqual(['none', 'none', 'none']);+ expect(gesture.phase).toBe('dead');+ });++ it('does not come back when the finger returns to where it started', () => {+ const {paints} = run([+ down(),+ {kind: 'onset'},+ move(100, 200),+ move(100, 100),+ ]);+ expect(paints.at(-1)).toBe('none');+ });++ it('does not paint on the release either', () => {+ const {paints} = run([+ down(),+ {kind: 'onset'},+ {kind: 'cancel'},+ {kind: 'up'},+ ]);+ expect(paints.at(-1)).toBe('none');+ });++ it('does not paint if the onset timer fires late, after the scroll took the gesture', () => {+ // iOS throttles frame callbacks during a scroll and a queued timer can+ // land after the cancel; the phase, not the timer, decides.+ const {paints} = run([down(), {kind: 'cancel'}, {kind: 'onset'}]);+ expect(paints).toEqual(['none', 'none', 'none']);+ });++ it('only a new touch revives it', () => {+ const {paints, gesture} = run([+ down(),+ {kind: 'cancel'},+ down(120, 300),+ {kind: 'onset'},+ ]);+ expect(paints.at(-1)).toBe('on');+ expect(gesture.phase).toBe('pressed');+ });++ it('ends when the finger lifts, so the NEXT press is heard', () => {+ // The gesture holds the controller's one tracking slot until it resolves.+ // A `dead` gesture that never resolved is how every press after the first+ // scroll would answer with nothing.+ const {gesture} = run([+ down(),+ {kind: 'onset'},+ move(100, 300),+ {kind: 'up'},+ ]);+ expect(gesture.phase).toBe('idle');+ });+});++describe('a press after a scroll', () => {+ it('paints, the way the first one did', () => {+ const {paints, gesture} = run([+ down(),+ {kind: 'onset'},+ move(100, 400),+ {kind: 'up'},+ down(100, 420),+ {kind: 'onset'},+ ]);+ expect(paints.at(-1)).toBe('on');+ expect(gesture.phase).toBe('pressed');+ });+});++describe('the paint does not survive its gesture', () => {+ it('leaves nothing painted once a cancelled gesture is over', () => {+ const {paints, gesture} = run([+ down(),+ {kind: 'onset'},+ {kind: 'cancel'},+ {kind: 'up'},+ ]);+ expect(paints.at(-1)).toBe('none');+ expect(gesture.phase).toBe('idle');+ });+});++describe('a tap too quick for the delay still answers', () => {+ it('paints at the release and holds it at full strength', () => {+ const {paints, gesture} = run([down(), {kind: 'up'}]);+ expect(paints).toEqual(['none', 'on']);+ expect(gesture.phase).toBe('flash');+ });++ it('arms the flash hold, then hands over to the same fade a long press gets', () => {+ const armed = pressGestureStep(idlePressGesture(), down()).gesture;+ const flash = pressGestureStep(armed, {kind: 'up'});+ expect(flash.timer).toBe('flash');+ const fading = pressGestureStep(flash.gesture, {kind: 'flashEnd'});+ expect(fading.paint).toBe('fading');+ expect(fading.timer).toBe('fade');+ });++ it('is not clipped by the cancel iOS sends after the tap', () => {+ // iOS Safari delivers `touchcancel` at `scrollend`, up to seconds after a+ // tap. It must not cut the answer the tap earned.+ const {paints} = run([down(), {kind: 'up'}, {kind: 'cancel'}]);+ expect(paints.at(-1)).toBe('on');+ });+});++describe('the release fades', () => {+ it('fades from a held press and ends idle', () => {+ const {paints, gesture} = run([+ down(),+ {kind: 'onset'},+ {kind: 'up'},+ {kind: 'fadeEnd'},+ ]);+ expect(paints).toEqual(['none', 'on', 'fading', 'none']);+ expect(gesture.phase).toBe('idle');+ });++ it('asks for the fade timer so the state cannot be left behind', () => {+ const armed = pressGestureStep(idlePressGesture(), down()).gesture;+ const pressed = pressGestureStep(armed, {kind: 'onset'}).gesture;+ expect(pressGestureStep(pressed, {kind: 'up'}).timer).toBe('fade');+ });+});diff --git a/packages/core/src/utils/pressGesture.ts b/packages/core/src/utils/pressGesture.tsnew file mode 100644index 0000000000..96e3b1000b--- /dev/null+++ b/packages/core/src/utils/pressGesture.ts@@ -0,0 +1,251 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file pressGesture.ts+ * @input A press gesture's current phase and one pointer or timer event+ * @output Exports the press state machine (pressGestureStep, idlePressGesture),+ * its clocks (PRESS_ONSET_MS, PRESS_SLOP_PX, PRESS_FLASH_MS, PRESS_FADE_MS,+ * PRESS_SCROLL_BRAKE_MS) and their types+ * @position Pure half of the touch press model; driven by pressFeedback.ts,+ * tested by pressGesture.test.ts without a browser+ *+ * WHAT A FINGER MEANS, AS A STATE MACHINE.+ *+ * A native (UIKit) list delays a press by 0.15 s, cancels it the instant a+ * scroll claims the gesture, never brings it back inside that gesture, and+ * fades it only on release. CSS `:active` on iOS Safari does none of those+ * things: measured on iOS 26.2, it paints within 14 ms of the touch and was+ * still painted 1.6 s into a scroll. So on a coarse pointer the pressed state+ * is owned here, in JavaScript, and `:active` keeps only the mouse.+ *+ * Every constant below was measured against the real Settings and Contacts+ * apps on an iPhone simulator, driven with real HID touches at 60 fps, before+ * it was written down. The machine is deliberately ignorant of the DOM: it+ * takes what happened and answers with what should be painted, so+ * {@link pressGestureStep}'s table of cases IS the state diagram, one arm per+ * requirement.+ *+ * SYNC: When modified, update pressFeedback.ts (the controller) and+ * pressGesture.test.ts.+ */++import {pressConsts} from './interactionOverlay.stylex';++/**+ * How long a finger must stay put before the surface believes it.+ *+ * UIKit's own number: `UIScrollView.delaysContentTouches` holds a content+ * touch for 0.15 s. Measured rather than taken on faith: a 1.5 s hold on a+ * Settings row painted the native highlight for 1.34 s, a 1.2 s hold for+ * 1.24 s. It is the whole reason a flick paints nothing: the scroller claims+ * a fling about 30 ms in, which is inside this window.+ */+export const PRESS_ONSET_MS = 150;++/**+ * How far a finger may travel and still be a press, in CSS pixels.+ *+ * iOS Safari's own scroller claims the gesture at about this distance (the+ * measured slow drag got its `pointercancel` after ~12 px of travel).+ * Cancelling on the distance as well as on the claim keeps the two in step+ * when the scroller is slower to decide: a list already at its end, a+ * horizontal drag on a vertical scroller.+ */+export const PRESS_SLOP_PX = 10;++/**+ * How long a too-quick tap holds the paint at full strength before fading.+ *+ * A UIKit scroll view forwards the delayed touch and the release together+ * when the finger lifts early, so the cell highlights AT THE LIFT and the+ * paint is still there while the next screen slides over it. Without this+ * the most common interaction there is would answer with nothing at all.+ */+export const PRESS_FLASH_MS = 100;++/**+ * How long the paint takes to leave after a release: UIKit's deselect+ * crossfade. The one number, shared with the stylesheet: the release+ * animation in interactionOverlay.stylex.ts runs on the same constant, so the+ * timer that removes the attribute and the fade cannot drift apart.+ */+export const PRESS_FADE_MS: number = pressConsts.releaseMs;++/**+ * How recently a scroller must have moved for a touch on it to be a BRAKE+ * rather than a press.+ *+ * Measured: a touch landing on a list that was still decelerating stopped it+ * and highlighted nothing. On the web that touch ends the momentum, so no+ * further scroll event arrives to cancel the press, and without this the+ * paint would arrive 150 ms after a finger that was only stopping the list.+ */+export const PRESS_SCROLL_BRAKE_MS = 150;++/** What the surface should be painting. `fading` is the release's exit. */+export type PressPaint = 'none' | 'on' | 'fading';++/**+ * Where a gesture is.+ *+ * `dead` is the load-bearing one: a gesture that became a scroll stays dead+ * until the finger lifts and a new one starts, so a finger that stops moving,+ * or comes back to the control it started on, paints nothing. That is the+ * difference between this and `:active`.+ */+export type PressPhase =+ 'idle' | 'armed' | 'pressed' | 'flash' | 'fading' | 'dead';++export interface PressGesture {+ readonly phase: PressPhase;+ /** Where the finger landed, in client coordinates. */+ readonly originX: number;+ readonly originY: number;+}++export type PressEvent =+ | {kind: 'down'; x: number; y: number}+ /** A touch point moved. Coordinates are client-space, like the origin. */+ | {kind: 'move'; x: number; y: number}+ | {kind: 'up'}+ /** The platform took the gesture away: `pointercancel`, `touchcancel`, a scroll, a drag. */+ | {kind: 'cancel'}+ /** {@link PRESS_ONSET_MS} elapsed with the finger still down. */+ | {kind: 'onset'}+ /** {@link PRESS_FLASH_MS} elapsed on a too-quick tap. */+ | {kind: 'flashEnd'}+ /** {@link PRESS_FADE_MS} elapsed; the paint is gone. */+ | {kind: 'fadeEnd'};++export interface PressStep {+ readonly gesture: PressGesture;+ readonly paint: PressPaint;+ /**+ * The timer this step wants armed.+ *+ * `null` means "arm nothing NEW", which is not the same as "cancel what is+ * running": a step that returns `null` without changing phase is a+ * pass-through, and the phase it leaves running still owes its transition+ * (`armed` owes `onset`, `flash` owes `flashEnd`, `fading` owes `fadeEnd`).+ * The caller keeps a pending timer across such a step and drops it only+ * when the phase moves; `pressFeedback.ts` says what stranding one costs.+ */+ readonly timer: 'onset' | 'flash' | 'fade' | null;+}++const IDLE: PressGesture = {originX: 0, originY: 0, phase: 'idle'};++/** A finger that has gone this far is scrolling, not pressing. */+function travelled(gesture: PressGesture, x: number, y: number): boolean {+ return Math.hypot(x - gesture.originX, y - gesture.originY) > PRESS_SLOP_PX;+}++function step(+ gesture: PressGesture,+ phase: PressPhase,+ paint: PressPaint,+ timer: PressStep['timer'],+): PressStep {+ return {gesture: {...gesture, phase}, paint, timer};+}++/**+ * One event, one answer.+ *+ * The caller owns the DOM and the clock, and nothing here reads either, so a+ * test drives the whole contract by handing it events.+ */+export function pressGestureStep(+ gesture: PressGesture,+ event: PressEvent,+): PressStep {+ if (event.kind === 'down') {+ // A new touch always starts armed and painting nothing, whatever the last+ // gesture ended as. This is the only way out of `dead`.+ return {+ gesture: {originX: event.x, originY: event.y, phase: 'armed'},+ paint: 'none',+ timer: 'onset',+ };+ }++ switch (gesture.phase) {+ case 'armed':+ if (event.kind === 'move') {+ // Travel is a scroll. Nothing was painted, so nothing is removed; the+ // gesture is simply over.+ return travelled(gesture, event.x, event.y)+ ? step(gesture, 'dead', 'none', null)+ : {gesture, paint: 'none', timer: null};+ }+ // The scroller claimed it before the delay elapsed: the fling case, and+ // the reason a flick paints nothing at all.+ if (event.kind === 'cancel') {+ return step(gesture, 'dead', 'none', null);+ }+ // The finger stayed. Paint, instantly and completely.+ if (event.kind === 'onset') {+ return step(gesture, 'pressed', 'on', null);+ }+ // Too quick for the delay. UIKit forwards the held touch and the release+ // together, so the paint appears HERE, at the lift.+ if (event.kind === 'up') {+ return step(gesture, 'flash', 'on', 'flash');+ }+ return {gesture, paint: 'none', timer: null};++ case 'pressed':+ if (event.kind === 'move' && !travelled(gesture, event.x, event.y)) {+ // A press with a shaky hand is still a press: measured, a 4 pt drag+ // over 2 s kept the native highlight for the whole gesture.+ return {gesture, paint: 'on', timer: null};+ }+ // A cancel removes the paint with no transition, one frame BEFORE the+ // list moves.+ if (event.kind === 'move' || event.kind === 'cancel') {+ return step(gesture, 'dead', 'none', null);+ }+ // A release fades.+ if (event.kind === 'up') {+ return step(gesture, 'fading', 'fading', 'fade');+ }+ return {gesture, paint: 'on', timer: null};++ case 'flash':+ // The full-strength hold is over; hand it to the same fade a long press+ // gets, so both releases leave the same way.+ if (event.kind === 'flashEnd') {+ return step(gesture, 'fading', 'fading', 'fade');+ }+ // The finger is already up. A cancel here is the platform tidying up+ // after the tap (iOS sends `pointercancel` at `scrollend`), and it must+ // not clip the answer the tap earned.+ return {gesture, paint: 'on', timer: null};++ case 'fading':+ if (event.kind === 'fadeEnd') {+ return {gesture: IDLE, paint: 'none', timer: null};+ }+ return {gesture, paint: 'fading', timer: null};++ case 'dead':+ // The finger lifting is what ends a cancelled gesture: until it does, a+ // second finger is a second finger and not a press. Resolving to idle+ // here is what lets the NEXT touch be heard at all; without it a gesture+ // that became a scroll holds the controller's one slot for ever, and+ // every press after the first scroll answers with nothing.+ if (event.kind === 'up') {+ return {gesture: IDLE, paint: 'none', timer: null};+ }+ return {gesture, paint: 'none', timer: null};++ case 'idle':+ // Only a touch (handled above) starts a gesture; anything else while+ // idle is a stray timer or a release with nothing to release.+ return {gesture: IDLE, paint: 'none', timer: null};+ }+}++export function idlePressGesture(): PressGesture {+ return IDLE;+}diff --git a/packages/core/src/utils/pressPaintSource.test.ts b/packages/core/src/utils/pressPaintSource.test.tsnew file mode 100644index 0000000000..77ced48932--- /dev/null+++ b/packages/core/src/utils/pressPaintSource.test.ts@@ -0,0 +1,65 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file pressPaintSource.test.ts+ * @input The core source tree+ * @output Fails when the touch press's paint formula is written anywhere but+ * interactionOverlay.stylex.ts+ * @position Guards the one-source rule for the press paint: a copied+ * `color-mix` across files is where a component quietly stops responding to+ * the theme while the rest keep working. Components paint+ * `var(--_press-paint)` / `var(--_press-paint-image)` instead.+ */++import {readdirSync, readFileSync, statSync} from 'node:fs';+import {join, relative} from 'node:path';+import {describe, expect, it} from 'vitest';++const SRC = join(__dirname, '..');+const ONE_SOURCE = 'utils/interactionOverlay.stylex.ts';+/**+ * The formula's shape: the pressed token mixed at a computed strength, as+ * StyleX source (`${colorVars['--color-overlay-pressed']}`) or as plain CSS.+ */+const FORMULA =+ /color-mix\(in srgb,\s*(?:\$\{colorVars\['--color-overlay-pressed'\]\}|var\(--color-overlay-pressed\))\s*calc\(/;++function* sourceFiles(dir: string): Generator<string> {+ for (const entry of readdirSync(dir)) {+ const path = join(dir, entry);+ if (statSync(path).isDirectory()) {+ if (entry === 'node_modules' || entry === 'dist') {+ continue;+ }+ yield* sourceFiles(path);+ } else if (+ /\.(ts|tsx|mjs)$/.test(entry) &&+ !/\.test\.(ts|tsx|mjs)$/.test(entry)+ ) {+ yield path;+ }+ }+}++describe('the touch press paint has one source', () => {+ it('writes the pressed-token-at-strength formula in interactionOverlay.stylex.ts and nowhere else', () => {+ const offenders: string[] = [];+ let declaredInSource = 0;+ for (const file of sourceFiles(SRC)) {+ const text = readFileSync(file, 'utf8');+ const rel = relative(SRC, file).split('\\').join('/');+ // Doc comments describe the formula in words; only code counts.+ const code = text+ .replace(/\/\*[\s\S]*?\*\//g, '')+ .replace(/^\s*\/\/.*$/gm, '');+ const hits = code.match(new RegExp(FORMULA.source, 'g')) ?? [];+ if (rel === ONE_SOURCE) {+ declaredInSource = hits.length;+ } else if (hits.length > 0) {+ offenders.push(`${rel} (${hits.length})`);+ }+ }+ expect(declaredInSource).toBe(1);+ expect(offenders).toEqual([]);+ });+});diff --git a/packages/core/src/utils/pressableCoverage.test.ts b/packages/core/src/utils/pressableCoverage.test.tsnew file mode 100644index 0000000000..d6509ed8d9--- /dev/null+++ b/packages/core/src/utils/pressableCoverage.test.ts@@ -0,0 +1,192 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file pressableCoverage.test.ts+ * @input Every non-test source file under packages/core/src+ * @output A guard that every file which paints a press is reachable by the+ * touch press controller+ * @position Testing; the structural half of the touch press model's contract+ *+ * The touch press controller (utils/pressFeedback.ts) can only paint what+ * carries `data-astryx-pressable`, and under a coarse pointer the `:active`+ * arm is dropped, so a surface that paints a press without the marker would+ * press on a mouse and stay dead under a finger. This test enumerates the+ * pressable set from the source itself — never from a hand-kept list — and+ * holds it equal to the marked set:+ *+ * - A file paints a press when its StyleX carries an `':active` key, a+ * `[data-astryx-press` arm, or composes `interactionOverlayStyles`.+ * - A file is marked when it calls `usePressFeedback(`.+ * - A file whose press arms are read off an ancestor scope marker+ * (`stylex.when.ancestor(':active', someScope)`, the way an indicator+ * reads its owner row) is covered when every file that applies that scope+ * marker is marked, since the controller writes `data-astryx-press` on the+ * element carrying the scope.+ * - A styles-only module (`*.stylex.ts`) is covered when every file that+ * imports it is marked.+ */++import fs from 'node:fs';+import path from 'node:path';+import {describe, expect, it} from 'vitest';++const SRC = path.resolve(__dirname, '..');++/** The utility and the controller define the model; they are not surfaces. */+const MODEL_FILES = new Set([+ 'utils/interactionOverlay.stylex.ts',+ 'utils/pressFeedback.ts',+ 'utils/pressGesture.ts',+]);++function walk(dir: string, out: string[] = []): string[] {+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (entry.name === '__tests__') {+ continue;+ }+ walk(full, out);+ } else if (+ /\.(ts|tsx)$/.test(entry.name) &&+ !/\.(test|stories|spec)\./.test(entry.name) &&+ !entry.name.endsWith('.d.ts')+ ) {+ out.push(full);+ }+ }+ return out;+}++const files = walk(SRC);+const source = new Map(+ files.map(file => [path.relative(SRC, file), fs.readFileSync(file, 'utf8')]),+);++const PRESS_ARM = /':active|'\[data-astryx-press=|interactionOverlayStyles\./;+const ANCESTOR_ARM =+ /stylex\.when\.ancestor\(\s*'(?::active|\[data-astryx-press=[^)]*)',\s*(\w+)\s*\)/g;++function isMarked(file: string): boolean {+ return (source.get(file) ?? '').includes('usePressFeedback(');+}++/** Files (other than `except`) that apply the scope marker `name` to an element. */+function referrers(name: string, except: string): string[] {+ const pattern = new RegExp(`\\b${name}\\b`);+ return [...source.entries()]+ .filter(([file, text]) => {+ if (file === except || file.endsWith('.markers.stylex.ts')) {+ return false;+ }+ // Mentioning the marker is not applying it: a reader names it inside+ // `stylex.when.*()`, an index re-exports it, a doc comment describes it.+ const applied = text+ .replace(/\/\*[\s\S]*?\*\//g, '')+ .replace(/^\s*\/\/.*$/gm, '')+ .replace(/import[\s\S]*?from\s+'[^']+';/g, '')+ .replace(/export\s*(?:type\s*)?\{[\s\S]*?\}\s*from\s+'[^']+';/g, '')+ .replace(/stylex\.when\.\w+\([^)]*\)/g, '');+ return pattern.test(applied);+ })+ .map(([file]) => file);+}++/** Files that import the module at `file` (by its relative specifier). */+function importers(file: string): string[] {+ const stem = file.replace(/\.tsx?$/, '');+ return [...source.entries()]+ .filter(([other, text]) => {+ if (other === file) {+ return false;+ }+ const dir = path.dirname(other);+ const specifiers = [...text.matchAll(/from\s+'([^']+)'/g)].map(m =>+ path.normalize(path.join(dir, m[1])),+ );+ return specifiers.includes(stem);+ })+ .map(([other]) => other);+}++const pressArmFiles = [...source.entries()]+ .filter(([file, text]) => !MODEL_FILES.has(file) && PRESS_ARM.test(text))+ .map(([file]) => file)+ .sort();++describe('every surface that paints a press is reachable by the touch press controller', () => {+ it('finds the pressable set from the source (a sanity floor, not a list)', () => {+ // Button, Item, the eight components of the first press PR and the ~20+ // composers of the overlay utility: well above this floor, and a regex+ // that stopped matching would fall below it.+ expect(pressArmFiles.length).toBeGreaterThan(25);+ });++ it.each(pressArmFiles)(+ '%s carries the marker, or its scope owners do',+ file => {+ const text = source.get(file) ?? '';+ if (isMarked(file)) {+ return;+ }++ const problems: string[] = [];++ if (file.endsWith('.stylex.ts')) {+ // A styles-only module: its arms land on whichever component composes+ // it, so each importer must be a marked surface.+ const users = importers(file);+ expect(users, `${file} is imported by nobody`).not.toHaveLength(0);+ for (const user of users) {+ if (!isMarked(user)) {+ problems.push(`${user} composes ${file} unmarked`);+ }+ }+ } else {+ // A component whose arms read an ancestor scope marker: the owners that+ // apply the marker are the pressables, and each must be marked.+ const scopes = [...text.matchAll(ANCESTOR_ARM)].map(m => m[1]);+ expect(+ scopes,+ `${file} paints a press without usePressFeedback() and without an ancestor scope`,+ ).not.toHaveLength(0);+ for (const scope of new Set(scopes)) {+ const owners = referrers(scope, file);+ expect(owners, `${scope} is applied by nobody`).not.toHaveLength(0);+ for (const owner of owners) {+ if (!isMarked(owner)) {+ problems.push(`${owner} applies ${scope} unmarked`);+ }+ }+ }+ }++ expect(problems).toEqual([]);+ },+ );++ it('marks nothing that does not paint a press', () => {+ // The converse: a marker with no arm would ask the controller to write an+ // attribute nothing reads. Every marked file must paint a press itself or+ // apply a scope an indicator reads.+ const marked = [...source.entries()]+ .filter(([, text]) => text.includes('usePressFeedback('))+ .map(([file]) => file)+ .filter(file => file !== 'hooks/usePressFeedback.ts');+ const scopeNames = new Set(+ [...source.values()].flatMap(text =>+ [...text.matchAll(ANCESTOR_ARM)].map(m => m[1]),+ ),+ );+ const unexplained = marked.filter(file => {+ const text = source.get(file) ?? '';+ if (PRESS_ARM.test(text)) {+ return false;+ }+ return ![...scopeNames].some(scope =>+ new RegExp(`\\b${scope}\\b`).test(text),+ );+ });+ expect(unexplained).toEqual([]);+ });+});diff --git a/scripts/build-css.test.mjs b/scripts/build-css.test.mjsindex 945b5b2578..cc45dee66c 100644--- a/scripts/build-css.test.mjs+++ b/scripts/build-css.test.mjs@@ -5,7 +5,9 @@* Integration test for build-css.mjs** Validates that astryx.css contains expected @media wrappers and- * prefers-reduced-motion rules.+ * prefers-reduced-motion rules, and that the touch press's release ships as a+ * real fade: the press strength is a registered `<number>` the fading arm+ * animates on the machine's own clock (utils/interactionOverlay.stylex.ts).*/import {describe, it, expect, beforeAll} from 'vitest';@@ -14,6 +16,29 @@ import path from 'node:path';import {fileURLToPath} from 'node:url';import {ensureCoreBuilt} from '../packages/cli/clients/cli/commands/ensure-core-built.mjs';+/**+ * The release clock, read off its one source: `pressConsts.releaseMs` in+ * utils/interactionOverlay.stylex.ts, which both the stylesheet (at build+ * time) and the controller (at run time) take it from. The module itself+ * cannot be imported here, since a StyleX source file only runs compiled.+ */+async function readReleaseMs() {+ const source = await fs.readFile(+ path.join(+ path.dirname(fileURLToPath(import.meta.url)),+ '../packages/core/src/utils/interactionOverlay.stylex.ts',+ ),+ 'utf8',+ );+ const match = source.match(/releaseMs:\s*(\d+)/);+ if (match == null) {+ throw new Error(+ 'pressConsts.releaseMs not found in interactionOverlay.stylex.ts',+ );+ }+ return Number(match[1]);+}+const __dirname = path.dirname(fileURLToPath(import.meta.url));const ROOT = path.resolve(__dirname, '..');const CORE_DIST = path.resolve(ROOT, 'packages/core/dist');@@ -213,4 +238,90 @@ describe('build-css astryx.css', () => {),).resolves.toBe(false);});++ describe('the touch press release (utils/interactionOverlay.stylex.ts)', () => {+ /** `.2s`, `200ms`, `0.2s` → 200. */+ const toMs = value => {+ const match = value.trim().match(/^([\d.]+)(ms|s)$/);+ return match == null+ ? Number.NaN+ : Number(match[1]) * (match[2] === 's' ? 1000 : 1);+ };+ const lines = () => astryxCss.split('\n');++ it('registers the press strength as an interpolable number, once', () => {+ // The pressed overlay is a gradient layer, and gradients do not+ // interpolate; the registered number the layer reads does. This is the+ // declaration that makes the release a fade rather than a step.+ const registrations =+ astryxCss.match(/@property --astryx-press-alpha \{[^}]*\}/g) ?? [];+ expect(registrations).toHaveLength(1);+ expect(registrations[0]).toContain('syntax: "<number>"');+ expect(registrations[0]).toContain('initial-value: 0');+ expect(astryxCss).toMatch(/:root[^{]*\{--astryx-press-alpha:0;?\}/);+ });++ it("animates the strength 1 → 0 on the fading arm, on the machine's own clock", async () => {+ const keyframes = astryxCss.match(+ /@keyframes ([\w-]+)\{from\{--astryx-press-alpha:1;?\}to\{--astryx-press-alpha:0;?\}\}/,+ );+ expect(keyframes).not.toBeNull();+ const fading = lines().filter(line =>+ line.includes('[data-astryx-press="fading"]'),+ );+ expect(+ fading.some(line => line.includes(`animation-name:${keyframes[1]}`)),+ ).toBe(true);+ const durations = fading+ .map(line => line.match(/animation-duration:\s*([^;}]+)/))+ .filter(Boolean)+ .map(match => toMs(match[1]));+ // One clock, the one the controller removes the attribute on.+ expect(durations).toEqual([await readReleaseMs()]);+ // The onset is instant: nothing animates on the on arm.+ const on = lines().filter(line =>+ line.includes('[data-astryx-press="on"]'),+ );+ expect(on.length).toBeGreaterThan(0);+ expect(on.some(line => line.includes('animation'))).toBe(false);+ });++ it('declares the press paint once, as the pressed token at the strength, and paints every touch arm through it', () => {+ // The one source: `--_press-paint`, the pressed token mixed at the+ // press's strength, declared by the shared overlay styles on the element+ // the controller writes to. StyleX deduplicates the identical+ // declaration across the variants, so the shipped sheet carries it once.+ const declarations = lines().filter(line =>+ /\{--_press-paint:/.test(line),+ );+ expect(declarations).toHaveLength(1);+ expect(declarations[0]).toContain('var(--color-overlay-pressed)');+ expect(declarations[0]).toContain('var(--astryx-press-alpha)');+ expect(declarations[0]).not.toContain('--color-overlay-hover');+ // No second copy of the formula anywhere in the sheet.+ const formulas = astryxCss.match(+ /color-mix\(in srgb,\s*var\(--color-overlay-pressed\)\s*calc\(/g,+ );+ expect(formulas).toHaveLength(1);+ // Every overlay variant, the cards' `--_press-overlay`, and the+ // ancestor-scoped paints (switch, the checkbox and radio overlays, tab)+ // read it back: twelve lines today, fewer than the arms because StyleX+ // deduplicates identical rules. A regex that stopped matching would+ // fall well below this floor.+ const paints = lines().filter(+ line =>+ /\[data-astryx-press="(?:on|fading)"\]/.test(line) &&+ line.includes('var(--_press-paint'),+ );+ expect(paints.length).toBeGreaterThanOrEqual(10);+ // Not the hover strength: under a finger there is no hover to land on,+ // and a paint that stepped there would still have to step off.+ const arms = lines().filter(line =>+ /\[data-astryx-press="(?:on|fading)"\]/.test(line),+ );+ expect(arms.some(line => line.includes('--color-overlay-hover'))).toBe(+ false,+ );+ });+ });});