An open source design system that's fully customizable and agent ready
TypeScript
Pressed state for Switch, SegmentedControl, TabList, Link, Slider, CheckboxInput, RadioList, Collapsible (#6380)
Christopher Chedeau6203871c7d53
diff --git a/.changeset/pressed-state-eight-components.md b/.changeset/pressed-state-eight-components.mdnew file mode 100644index 0000000000..d2cf0c11b4--- /dev/null+++ b/.changeset/pressed-state-eight-components.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Add pressed feedback to CheckboxInput, Collapsible, Link, Slider, Switch, TabList, RadioList, and unselected SegmentedControl items. Enabled controls paint `--color-overlay-pressed` on their interaction surface during pointer hold or drag; disabled controls and selected SegmentedControl items keep their existing surfaces.++@vjeuxdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 21b8c490bd..0414028d15 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -800,8 +800,19 @@ jobs:# Chromium guards for the same reason they are: pr-a11y is the blocking# job that runs whenever components change.- name: Run accessibility spec-test contracts+ env:+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}run: pnpm test:a11y-contract+ - name: Upload pressed-state pixel evidence+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: pressed-state-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: test-results/pressed-state-evidence/+ retention-days: 30+ if-no-files-found: error+# Build package test owner. The plugin's production CSS partition is a Build# integration contract: source inspection cannot prove which declaration# paints after Vite emits the final bundle. The `test-build` name makes thatdiff --git a/apps/storybook/stories/CheckboxInput.stories.tsx b/apps/storybook/stories/CheckboxInput.stories.tsxindex 64e3385584..375113c916 100644--- a/apps/storybook/stories/CheckboxInput.stories.tsx+++ b/apps/storybook/stories/CheckboxInput.stories.tsx@@ -568,3 +568,41 @@ export const ThemedCheckboxTarget: Story = {</Theme>),};++export const PressedState: Story = {+ name: 'Pressed state',+ parameters: {+ docs: {+ description: {+ story:+ "Press and hold an enabled row to paint the system's `--color-overlay-pressed` layer on its indicator. Checked and unchecked indicators both respond; the disabled example remains visually unchanged.",+ },+ },+ },+ render: () => {+ const [unchecked, setUnchecked] = useState<boolean | 'indeterminate'>(+ false,+ );+ const [checked, setChecked] = useState<boolean | 'indeterminate'>(true);+ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>+ <CheckboxInput+ label="Unchecked — press and hold"+ value={unchecked}+ onChange={setUnchecked}+ />+ <CheckboxInput+ label="Checked — press and hold"+ value={checked}+ onChange={setChecked}+ />+ <CheckboxInput+ label="Disabled — no pressed state"+ value={false}+ onChange={() => {}}+ isDisabled+ />+ </div>+ );+ },+};diff --git a/apps/storybook/stories/Collapsible.stories.tsx b/apps/storybook/stories/Collapsible.stories.tsxindex 4b6e30d3af..a272fbf767 100644--- a/apps/storybook/stories/Collapsible.stories.tsx+++ b/apps/storybook/stories/Collapsible.stories.tsx@@ -345,3 +345,31 @@ export const FAQ: Story = {</CollapsibleGroup>),};++export const PressedState: Story = {+ name: 'Pressed state',+ parameters: {+ docs: {+ description: {+ story:+ "Press and hold the enabled trigger to paint the system's `--color-overlay-pressed` layer across its row. The disabled trigger remains visually unchanged and cannot expand or collapse.",+ },+ },+ },+ render: () => (+ <VStack gap={2}>+ <Card>+ <Collapsible trigger="Details — press and hold">+ <p {...stylex.props(styles.text)}>+ The pressed overlay covers the trigger row.+ </p>+ </Collapsible>+ </Card>+ <Card>+ <Collapsible trigger="Unavailable — no pressed state" isDisabled>+ <p {...stylex.props(styles.text)}>Never opens.</p>+ </Collapsible>+ </Card>+ </VStack>+ ),+};diff --git a/apps/storybook/stories/Link.stories.tsx b/apps/storybook/stories/Link.stories.tsxindex e63e13840b..4e301ab5cd 100644--- a/apps/storybook/stories/Link.stories.tsx+++ b/apps/storybook/stories/Link.stories.tsx@@ -378,3 +378,27 @@ export const LinkVsButtonComparison: Story = {},},};++export const PressedState: Story = {+ name: 'Pressed state',+ parameters: {+ docs: {+ description: {+ story:+ "Press and hold to see the system's `--color-overlay-pressed` layer behind the link text. The disabled example remains visually unchanged and cannot navigate.",+ },+ },+ },+ render: () => (+ <Text>+ Read the{' '}+ <Link href="/docs" onClick={e => e.preventDefault()}>+ documentation — press and hold+ </Link>{' '}+ or <Link onClick={() => {}}>open the panel (button form)</Link>.{' '}+ <Link href="/unavailable" isDisabled>+ Unavailable — no pressed state+ </Link>+ </Text>+ ),+};diff --git a/apps/storybook/stories/RadioList.stories.tsx b/apps/storybook/stories/RadioList.stories.tsxindex 524452daf7..183be701ae 100644--- a/apps/storybook/stories/RadioList.stories.tsx+++ b/apps/storybook/stories/RadioList.stories.tsx@@ -401,3 +401,43 @@ export const DisabledWithMessage: Story = {disabledMessage: 'Upgrade your account to change preferences',},};++export const PressedState: Story = {+ name: 'Pressed state',+ parameters: {+ docs: {+ description: {+ story:+ "Press and hold an enabled option row to paint the system's `--color-overlay-pressed` layer on its indicator. Selected and unselected indicators both respond; the disabled example and the SMS row's nested link remain visually independent and cannot change selection.",+ },+ },+ },+ render: () => {+ const [value, setValue] = useState('email');+ return (+ <RadioList+ label="Notification preference"+ value={value}+ onChange={setValue}>+ <RadioListItem label="Email — selected, press and hold" value="email" />+ <RadioListItem+ label={+ <>+ <span data-testid="radio-row-press-target">+ SMS — press and hold+ </span>{' '}+ <Link href="#details">Details — independent link</Link>+ </>+ }+ aria-label="SMS — press and hold"+ value="sms"+ />+ <RadioListItem+ label="Push — disabled, no pressed state"+ value="push"+ isDisabled+ />+ </RadioList>+ );+ },+};diff --git a/apps/storybook/stories/SegmentedControl.stories.tsx b/apps/storybook/stories/SegmentedControl.stories.tsxindex 250220409c..5d973b41f3 100644--- a/apps/storybook/stories/SegmentedControl.stories.tsx+++ b/apps/storybook/stories/SegmentedControl.stories.tsx@@ -244,3 +244,30 @@ export const DisabledWithMessage: Story = {);},};++export const PressedState: Story = {+ name: 'Pressed state',+ parameters: {+ docs: {+ description: {+ story:+ "Press and hold an unselected item to see the system's `--color-overlay-pressed` layer. The selected item keeps its raised surface, and the disabled item remains visually unchanged and cannot be selected.",+ },+ },+ },+ render: () => {+ const [value, setValue] = useState('grid');+ return (+ <SegmentedControl value={value} onChange={setValue} label="View mode">+ <SegmentedControlItem value="grid" label="Grid — selected" />+ <SegmentedControlItem value="list" label="List — press and hold" />+ <SegmentedControlItem value="board" label="Board" />+ <SegmentedControlItem+ value="unavailable"+ label="Unavailable — no pressed state"+ isDisabled+ />+ </SegmentedControl>+ );+ },+};diff --git a/apps/storybook/stories/Slider.stories.tsx b/apps/storybook/stories/Slider.stories.tsxindex bd68607387..c9d78bf625 100644--- a/apps/storybook/stories/Slider.stories.tsx+++ b/apps/storybook/stories/Slider.stories.tsx@@ -270,3 +270,39 @@ export const DisabledWithMessage: Story = {disabledMessage: 'Volume is locked while sharing your screen',},};++export const PressedState: Story = {+ name: 'Pressed state',+ parameters: {+ docs: {+ description: {+ story:+ "Press and drag to paint the system's `--color-overlay-pressed` layer on only the thumb being dragged. The disabled example remains visually unchanged and its value cannot move.",+ },+ },+ },+ render: () => {+ const [value, setValue] = useState(40);+ const [range, setRange] = useState<[number, number]>([20, 80]);+ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: 24}}>+ <Slider+ label="Volume — press and drag"+ value={value}+ onChange={setValue}+ />+ <Slider+ label="Price range — only the dragged thumb presses"+ value={range}+ onChange={setRange}+ />+ <Slider+ label="Unavailable — no pressed state"+ value={60}+ onChange={() => {}}+ isDisabled+ />+ </div>+ );+ },+};diff --git a/apps/storybook/stories/Switch.stories.tsx b/apps/storybook/stories/Switch.stories.tsxindex 969345273a..8d3ea25adf 100644--- a/apps/storybook/stories/Switch.stories.tsx+++ b/apps/storybook/stories/Switch.stories.tsx@@ -620,3 +620,31 @@ export const Loading: Story = {isLoading: true,},};++export const PressedState: Story = {+ name: 'Pressed state',+ parameters: {+ docs: {+ description: {+ story:+ "Press and hold an enabled switch to paint the system's `--color-overlay-pressed` layer on its track and thumb together. The disabled example remains visually unchanged and cannot toggle.",+ },+ },+ },+ render: () => {+ const [off, setOff] = useState(false);+ const [on, setOn] = useState(true);+ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>+ <Switch label="Off — press and hold" value={off} onChange={setOff} />+ <Switch label="On — press and hold" value={on} onChange={setOn} />+ <Switch+ label="Disabled — no pressed state"+ value={false}+ onChange={() => {}}+ isDisabled+ />+ </div>+ );+ },+};diff --git a/apps/storybook/stories/TabList.stories.tsx b/apps/storybook/stories/TabList.stories.tsxindex f88ab8d6d8..415af603e0 100644--- a/apps/storybook/stories/TabList.stories.tsx+++ b/apps/storybook/stories/TabList.stories.tsx@@ -1039,3 +1039,30 @@ export const TabsPattern: Story = {);},};++export const PressedState: Story = {+ name: 'Pressed state',+ parameters: {+ docs: {+ description: {+ story:+ "Press and hold an enabled tab to paint the system's `--color-overlay-pressed` layer on its surface. The disabled tab remains visually unchanged and cannot change selection.",+ },+ },+ },+ render: () => {+ const [value, setValue] = useState('home');+ return (+ <TabList value={value} onChange={setValue}>+ <Tab value="home" label="Home" />+ <Tab value="projects" label="Projects — press and hold" />+ <Tab value="settings" label="Settings" />+ <Tab+ value="unavailable"+ label="Unavailable — no pressed state"+ aria-disabled="true"+ />+ </TabList>+ );+ },+};diff --git a/docs/design/user-states.md b/docs/design/user-states.mdindex dc688b6bf1..ded895ea65 100644--- a/docs/design/user-states.md+++ b/docs/design/user-states.md@@ -3,16 +3,37 @@ schema_version: 1template_version: 1kind: designid: design:user-states-authority: draft+authority: currentarchive_reason: nullsuperseded_by: null-approved_by: null-approved_at: null+approved_by: cixzhang+approved_at: 2026-09-19owners: [ernestt, cixzhang]review_triggers: [visual, interaction, accessibility]-verified_by: []+verified_by:+ [+ packages/core/src/__tests__/PressedState.a11y.chromium.spec.ts,+ packages/core/src/CheckboxInput/CheckboxInput.test.tsx,+ packages/core/src/Collapsible/Collapsible.test.tsx,+ packages/core/src/Link/Link.test.tsx,+ packages/core/src/RadioList/RadioList.test.tsx,+ packages/core/src/SegmentedControl/SegmentedControl.test.tsx,+ packages/core/src/Slider/Slider.test.tsx,+ packages/core/src/Switch/Switch.test.tsx,+ packages/core/src/TabList/TabList.test.tsx,+ ]architecture: [architecture:interaction-modality, architecture:theme-tokens]-components: []+components:+ [+ component:CheckboxInput,+ component:Collapsible,+ component:Link,+ component:Slider,+ component:Switch,+ component:TabList,+ component:RadioList,+ component:SegmentedControl,+ ]families: []deciding_specs: []---@@ -21,108 +42,108 @@ deciding_specs: []## User intent-A person should recognize whether an element is available, hovered, pressed,-focused, or selected without learning a new visual language for every component.-Each family should reuse the smallest suitable set of state representations.+A pointer user holding or dragging an enabled control should receive immediate,+consistent feedback on the surface being manipulated. The feedback must not imply+that a disabled control responded, and it must not erase a persistent selected+surface.## Design principles-- **DR1 — Minimize representations per intention.** A component MUST reuse an- established treatment before introducing another visual for the same state.-- **DR2 — Design the complete user-driven interaction cycle.** Every interactive- component MUST account for rest, hover where available, focus, press or- activation, and its selected state where relevant. Disabled, loading, and- status representations belong to `design:system-states`.-- **DR3 — Family consistency comes first.** A component MUST choose the treatment- that fits its interaction archetype and remain consistent with sibling- components before pursuing superficial system-wide sameness.-- **DR4 — Selection is one intention with archetype-specific treatments.** A- selected item MUST remain perceivable, while its visual treatment MAY differ- for toggles, segments, navigation, cards, and rows.+- **DR1 — Press the manipulated surface.** During pointer hold or drag, each+ enabled surface in the matrix below MUST paint `--color-overlay-pressed` on+ the named visual part. The overlay is transient and MUST clear when the press+ or drag ends.+- **DR2 — Disabled means no response.** A disabled control in the matrix MUST+ remain inoperable and MUST NOT gain a pressed visual treatment.+- **DR3 — Persistent selection wins.** A selected SegmentedControl item MUST+ keep its raised selected surface during pointer hold; only an unselected item+ receives the pressed overlay.## Anatomy and hierarchy-| Role | Purpose | Required relationship |-| --------------------------- | --------------------------------------------------- | ---------------------------------------------------------------------- |-| base surface | Establishes the component's resting role | Remains identifiable under every transient state treatment |-| interaction overlay or ring | Signals pointer response | Adds feedback without replacing content or semantic meaning |-| focus indicator | Shows the current keyboard focus owner | Has one clear owner and remains distinct from hover and selection |-| selection indicator | Shows persistent current or chosen state | Fits the component archetype and remains stable after interaction ends |-| content | Carries the component's label, value, or affordance | Remains legible through transient and persistent states |+| Role | Purpose | Required relationship |+| --------------------------- | ---------------------------------------- | ----------------------------------------------------------------------------- |+| interaction target | Receives the pointer hold or drag | Owns or controls the paint surface named in the matrix |+| pressed overlay | Confirms the active manipulation | Composes over the existing fill without replacing content or persistent state |+| persistent selected surface | Communicates an already-selected segment | Remains visually unchanged during pointer hold |## State representation-| State | Required representation | Allowed variation |-| -------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |-| rest | Uses base role tokens without transient interaction decoration | Theme controls visual character |-| hovered, surface archetype | A quiet overlay changes the surface while preserving its base | Overlay strength may vary by theme |-| hovered, field archetype | Border or inset treatment makes the field boundary more apparent | Field families may tune the ring treatment |-| pressed | Immediate tactile compression or stronger surface feedback confirms activation | Components that cannot transform may use another established family response |-| focused, action archetype | A clearly separated external indicator identifies the focus owner | Shape follows the focused element |-| focused, field archetype | An emphasized border and inset treatment identify the owning field | Composed fields may paint on an owning wrapper or visual proxy |-| selected, filled | A compact binary control fills to communicate on or chosen | Used for checks, radios, and switches where the control itself carries state |-| selected, surface | The active segment separates from its containing track | Used for segmented choices |-| selected, edge | An edge or underline marks the current destination or step | Used for tabs, entries, and ordered progress |-| selected, border | A selected container receives a clear boundary treatment | Used for selectable cards and similar surfaces |-| selected, depressed | A persistent quiet fill marks the current row or toggle action | Used for navigation rows, list rows, and toggle buttons |-| reordering | Uses the drag and insertion treatment owned by `design:ordered-collection-reordering` | Applies only to ordered collections with a dedicated handle |+| Component | Enabled pointer hold or drag | Disabled pointer hold |+| ---------------- | --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |+| CheckboxInput | Indicator paints `--color-overlay-pressed` | Indicator remains unchanged |+| Collapsible | Trigger row paints `--color-overlay-pressed` | Trigger row remains unchanged and does not expand or collapse |+| Link | Text surface paints `--color-overlay-pressed` | Text surface remains unchanged and does not activate |+| Slider | Only the dragged thumb paints `--color-overlay-pressed` | Thumb remains unchanged and the value does not change |+| Switch | Track and thumb both paint `--color-overlay-pressed` | Track and thumb remain unchanged and the value does not change |+| TabList Tab | Tab surface paints `--color-overlay-pressed` | Tab surface remains unchanged and selection does not change |+| RadioList | Indicator paints `--color-overlay-pressed` | Indicator remains unchanged and selection does not change |+| SegmentedControl | An unselected item paints `--color-overlay-pressed`; the selected item keeps its raised surface unchanged | Item surface remains unchanged and selection does not change |++This table is the complete current claim. It does not approve pressed treatment+for other components or settle their state design.## Responsive and input behavior-- **DR5 — Hover remains conditional.** Hover treatment MUST appear only where the- input can intentionally hover and MUST NOT be required to discover or activate- the control.-- **DR6 — Focus follows the semantic owner.** Responsive composition MAY move or- visually proxy a control, but it MUST preserve one perceivable focus indicator- for the semantic focus owner.-- **DR7 — Persistent state survives reflow.** Selection MUST remain perceivable- when labels wrap, navigation collapses, or a control changes orientation.+- **DR4 — Follow the real interaction.** Hold-driven controls keep the overlay+ only while the pointer is down. Slider follows its existing drag state so the+ overlay stays on the thumb being dragged, including when the drag began on the+ track.+- **DR5 — Preserve the resting result.** After release or cancellation, the+ component MUST return to the same visual state it would otherwise have had;+ pressed feedback does not create a persistent state.## Accessibility intent-Keyboard users should always be able to identify the current focus owner.-Pointer, touch, and pen users should receive feedback without sticky or-misleading hover. Selection must not be communicated by a subtle color change-alone when shape, edge, fill, or text can provide a durable cue.--Interaction modality mechanics, selectors, ARIA mapping, and component event-behavior are owned by architecture and component contracts.+Pressed feedback supplements, and never replaces, the control's semantic state,+label, focus indication, or disabled behavior. A control that is exposed as+disabled must remain inoperable even when its implementation keeps it focusable+to explain why it is unavailable.## Representative examples-- A secondary action moves from rest to hover, press, and keyboard focus without- changing the meaning or position of its label.-- A field uses its family ring treatment rather than borrowing an action outline.-- Tabs use an edge indicator while a checkbox uses a filled indicator; both- clearly communicate the same selected intention through their archetypes.+- Holding an enabled CheckboxInput row darkens its indicator; releasing outside+ without activation restores the original indicator pixels.+- Dragging a range Slider paints only the thumb currently being moved.+- Holding the selected SegmentedControl item leaves its raised surface unchanged;+ holding an unselected item paints the pressed overlay.## Visual references-No normative assets are included in this seed draft. Approved examples should be-copied into `docs/design/assets/user-states/` with state, theme,-viewport, demonstrated decision, and alt-text metadata before promotion.+The real-Chromium evidence generated by+`packages/core/src/__tests__/PressedState.a11y.chromium.spec.ts` captures matched+rest, held-pointer, released, disabled, and selected-exception surfaces for the+eight components. CI publishes those PNGs, pixel diffs, Chromium version,+viewport, story IDs, hashes, and exact PR-head SHA in the+`pressed-state-evidence` artifact. Generated evidence validates this record but+is not a normative design asset.## Component contract links-No component contract links are asserted in this seed draft. Candidate component-and family adoptions should cite individual `DR` requirements after review.+The `components` frontmatter list is the machine-readable adoption matrix for+DR1–DR5. Component records do not duplicate this cross-component decision.## Decision log-No repository design decision has approved this record yet. It distills the-human-facing state vocabulary from the public Design Conventions wiki while-leaving implementation and component semantics with their current owners.+### DEC-1 — Use the system pressed overlay on the bounded eight-component matrix++**Reference:** `design:user-states/DEC-1`+**Decider:** `cixzhang`, 2026-09-19++Consistent feedback helps pointer users understand which enabled surface is+actively responding. The decision is intentionally limited to the surfaces in+the matrix, preserves disabled behavior, and keeps an already-selected segment's+raised surface stable.## Open questions-- **OQ1 — Representative set.** Which components are the canonical examples for- each hover, focus, and selection archetype?-- **OQ2 — Cross-family exceptions.** Which shipped components intentionally use- a different state treatment, and should the family or this design record own- each exception?+None for this bounded pressed-state decision. Hover, focus, selection treatments+outside the selected-segment exception, and adoption by other components remain+outside this record's current claim.## Content boundary-This file defines visual intent for user-driven states. It does not define prop-names, selectors, ARIA attributes, focus-management mechanics, token names,-component behavior, audit results, or consumer guidance.+This file defines the approved cross-component pressed-state intent and its+bounded adoption matrix. Component implementations own selectors and event+mechanics; architecture records own interaction modality and token behavior;+tests and CI artifacts own current conformance evidence.diff --git a/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs b/packages/core/src/CheckboxInput/CheckboxInput.doc.mjsindex cf44949e7d..2046ffa8fc 100644--- a/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs+++ b/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs@@ -137,6 +137,17 @@ export const docs = {],},usage: {+ accessibility: [+ {+ name: 'Checkbox box',+ category: 'Color contrast',+ criterion: '1.4.11 Non-text Contrast',+ requirement: '3:1',+ states: ['Rest', 'Hover', 'Pointer down', 'Checked'],+ description:+ 'The box edge (unchecked) and fill (checked) must have at least 3:1 contrast with the surface behind them. For Hover and Pointer down, measure the final colors after the tint and the pressed overlay are applied.',+ },+ ],description: 'CheckboxInput toggles a single on/off value. Use it for settings like "Enable notifications", terms acceptance, or opt-in choices. For multiple checkboxes in a group, use CheckboxList instead.',bestPractices: [{ guidance: true, description: 'Always provide a visible label so the user knows what they are toggling. Use isLabelHidden only when surrounding context makes it obvious.' },diff --git a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx b/packages/core/src/CheckboxInput/CheckboxInput.test.tsxindex 547546b58b..e8d0b20e75 100644--- a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx+++ b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx@@ -15,6 +15,7 @@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 {CheckboxInput} from './CheckboxInput';import {Theme} from '../theme/Theme';import {defineTheme} from '../theme/defineTheme';@@ -763,3 +764,36 @@ describe('label theme target', () => {expect(label).toHaveClass('astryx-checkbox-label');});});++describe('pressed state', () => {+ it('paints the pressed overlay over the indicator while the row is pressed', () => {+ const {container} = render(+ <CheckboxInput label="Accept terms" value={false} onChange={() => {}} />,+ );+ const box = container.querySelector('.astryx-checkbox-indicator');+ const wrapper = box?.parentElement?.parentElement;+ if (wrapper == null) {+ throw new Error('the checkbox has no indicator wrapper to press');+ }+ // The owner paints over the resolved indicator, so the treatment survives a+ // theme replacement that does not forward style props.+ expect(hasPressedArm(wrapper)).toBe(true);+ });++ it('does not expose a pressed arm on a disabled checkbox', () => {+ const {container} = render(+ <CheckboxInput+ label="Unavailable"+ value={false}+ onChange={() => {}}+ isDisabled+ />,+ );+ const box = container.querySelector('.astryx-checkbox-indicator');+ const wrapper = box?.parentElement?.parentElement;+ if (wrapper == null) {+ throw new Error('the checkbox has no indicator wrapper');+ }+ expect(hasPressedArm(wrapper)).toBe(false);+ });+});diff --git a/packages/core/src/CheckboxInput/CheckboxInput.tsx b/packages/core/src/CheckboxInput/CheckboxInput.tsxindex 81d4c75696..26ae1709e8 100644--- a/packages/core/src/CheckboxInput/CheckboxInput.tsx+++ b/packages/core/src/CheckboxInput/CheckboxInput.tsx@@ -70,6 +70,22 @@ const styles = stylex.create({flexShrink: 0,isolation: 'isolate',},+ // The owner paints this layer over the resolved indicator, so a theme+ // replacement cannot accidentally drop the component's pressed contract.+ indicatorPressOverlay: {+ '::after': {+ content: '""',+ position: 'absolute',+ inset: 0,+ borderRadius: radiusVars['--radius-inner'],+ pointerEvents: 'none',+ backgroundColor: {+ default: 'transparent',+ [stylex.when.ancestor(':active', indicatorScope)]:+ colorVars['--color-overlay-pressed'],+ },+ },+ },// Holds only the indicator, so the focus ring has one unambiguous target.// `display: contents` adds no box of its own — the indicator keeps whatever// layout relationship it already had with the wrapper.@@ -399,7 +415,11 @@ export function CheckboxInput({!isDisabled && indicatorScope,)}><div- {...stylex.props(styles.checkboxWrapper, wrapperSizeStyles[size])}+ {...stylex.props(+ styles.checkboxWrapper,+ wrapperSizeStyles[size],+ !isDisabled && styles.indicatorPressOverlay,+ )}{...focusProps}><input{...rest}diff --git a/packages/core/src/Collapsible/Collapsible.doc.mjs b/packages/core/src/Collapsible/Collapsible.doc.mjsindex 6805783d66..998b6ea398 100644--- a/packages/core/src/Collapsible/Collapsible.doc.mjs+++ b/packages/core/src/Collapsible/Collapsible.doc.mjs@@ -82,6 +82,17 @@ export const docs = {{name: 'CollapsibleGroup'},],usage: {+ accessibility: [+ {+ name: 'Trigger label',+ category: 'Color contrast',+ criterion: '1.4.3 Contrast (Minimum)',+ requirement: '4.5:1',+ states: ['Rest', 'Pointer down'],+ description:+ 'The trigger text must have at least 4.5:1 contrast with the surface behind it. For Pointer down, measure against the pressed overlay the trigger row paints while it is pressed.',+ },+ ],description: 'Collapsible hides and reveals content behind a trigger button. Use it in settings panels, FAQ pages, or detail views to keep the page scannable while letting users drill into sections they care about. Wrap multiple collapsibles in CollapsibleGroup for accordion behavior. For custom collapsible components, use the `useCollapsible` hook directly (`astryx hook useCollapsible`).',bestPractices: [{ guidance: true, description: 'Use hasDividers on CollapsibleGroup for FAQ-style lists: built-in row hairlines with themed border tokens, no hand-rolled borders.' },diff --git a/packages/core/src/Collapsible/Collapsible.test.tsx b/packages/core/src/Collapsible/Collapsible.test.tsxindex ce046f896b..96b47013a8 100644--- a/packages/core/src/Collapsible/Collapsible.test.tsx+++ b/packages/core/src/Collapsible/Collapsible.test.tsx@@ -12,6 +12,7 @@import {describe, it, expect, vi} from 'vitest';import {render, screen, within} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import {hasPressedArm} from '../__tests__/pressState';import {Collapsible} from './Collapsible';import {CollapsibleGroup} from './CollapsibleGroup';@@ -615,3 +616,23 @@ describe('Collapsible', () => {});});});++describe('pressed state', () => {+ it('paints the pressed overlay on the trigger row while it is pressed', () => {+ render(+ <Collapsible trigger="Details">+ <p>Body</p>+ </Collapsible>,+ );+ expect(hasPressedArm(screen.getByRole('button'))).toBe(true);+ });++ it('does not press a disabled trigger', () => {+ render(+ <Collapsible trigger="Details" isDisabled>+ <p>Body</p>+ </Collapsible>,+ );+ expect(hasPressedArm(screen.getByRole('button'))).toBe(false);+ });+});diff --git a/packages/core/src/Collapsible/Collapsible.tsx b/packages/core/src/Collapsible/Collapsible.tsxindex e18c37c5e4..15dfa04b82 100644--- a/packages/core/src/Collapsible/Collapsible.tsx+++ b/packages/core/src/Collapsible/Collapsible.tsx@@ -48,6 +48,7 @@ import {mergeProps} from '../utils';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';+import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';const styles = stylex.create({root: {@@ -411,6 +412,10 @@ export function Collapsible({focusOutlineProps.focusVisible(styles.trigger,density != null && triggerDensity[density],+ // The system's pressed overlay on the disclosure row. The trigger+ // has no hover surface of its own, so this is the one background+ // it paints, and only while it is pressed.+ !isDisabled && interactionOverlayStyles.pressedBackgroundColor,isDisabled && styles.triggerDisabled,),)}>diff --git a/packages/core/src/Link/Link.doc.mjs b/packages/core/src/Link/Link.doc.mjsindex 48cc492bdb..991abcef05 100644--- a/packages/core/src/Link/Link.doc.mjs+++ b/packages/core/src/Link/Link.doc.mjs@@ -164,6 +164,17 @@ export const docs = {},],usage: {+ accessibility: [+ {+ name: 'Link text',+ category: 'Color contrast',+ criterion: '1.4.3 Contrast (Minimum)',+ requirement: '4.5:1',+ states: ['Rest', 'Hover', 'Pointer down'],+ description:+ 'Link text must have at least 4.5:1 contrast with the background behind it. For Pointer down, measure against the pressed overlay the link paints behind its text.',+ },+ ],description:'A styled anchor for inline and standalone text navigation. Supports external links, underline variants, tooltips, and custom link components for router integration. Use it for navigating between pages or to external URLs.',bestPractices: [diff --git a/packages/core/src/Link/Link.test.tsx b/packages/core/src/Link/Link.test.tsxindex 5cefec2574..826c931cb6 100644--- a/packages/core/src/Link/Link.test.tsx+++ b/packages/core/src/Link/Link.test.tsx@@ -12,6 +12,7 @@import {describe, it, expect, vi} from 'vitest';import {fireEvent, render, screen} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import {hasPressedArm} from '../__tests__/pressState';import {Link} from './Link';import {LinkProvider} from './LinkProvider';@@ -417,3 +418,26 @@ describe('Link', () => {expect(link).toHaveAttribute('data-color', 'secondary');});});++describe('pressed state', () => {+ it('paints the pressed overlay behind a link while it is pressed', () => {+ render(<Link href="/docs">Docs</Link>);+ expect(hasPressedArm(screen.getByRole('link', {name: 'Docs'}))).toBe(true);+ });++ it('paints it on the button form too', () => {+ render(<Link onClick={() => {}}>Open</Link>);+ expect(hasPressedArm(screen.getByRole('button', {name: 'Open'}))).toBe(+ true,+ );+ });++ it('does not press a disabled link', () => {+ render(+ <Link href="/docs" isDisabled>+ Docs+ </Link>,+ );+ expect(hasPressedArm(screen.getByText('Docs').closest('a')!)).toBe(false);+ });+});diff --git a/packages/core/src/Link/Link.tsx b/packages/core/src/Link/Link.tsxindex 72ffa07cdd..4d6ab015c9 100644--- a/packages/core/src/Link/Link.tsx+++ b/packages/core/src/Link/Link.tsx@@ -45,6 +45,7 @@ import {computeTargetAndRel} from './computeTargetAndRel';import {useInteractiveRole} from '../hooks/useInteractiveRole';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';+import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';import {useTranslator} from '../i18n';/**@@ -368,6 +369,9 @@ export function Link({styles.base,styles.buttonReset,linkColorStyles[color],+ // The system's pressed overlay behind the text; the hover stays the+ // colour change above, so a press is the one background it paints.+ !isDisabled && interactionOverlayStyles.pressedBackgroundColor,hasUnderline && styles.hasUnderline,isStandalone && styles.standalone,isDisabled && styles.disabled,@@ -427,6 +431,7 @@ export function Link({focusOutlineProps.focusVisible(styles.base,linkColorStyles[color],+ !isDisabled && interactionOverlayStyles.pressedBackgroundColor,hasUnderline && styles.hasUnderline,isStandalone && styles.standalone,isDisabled && styles.disabled,diff --git a/packages/core/src/RadioList/RadioList.doc.mjs b/packages/core/src/RadioList/RadioList.doc.mjsindex 313ade7e6a..b34cc6295a 100644--- a/packages/core/src/RadioList/RadioList.doc.mjs+++ b/packages/core/src/RadioList/RadioList.doc.mjs@@ -132,6 +132,17 @@ export const docs = {{name: 'RadioListItem'},],usage: {+ accessibility: [+ {+ name: 'Radio circle',+ category: 'Color contrast',+ criterion: '1.4.11 Non-text Contrast',+ requirement: '3:1',+ states: ['Rest', 'Hover', 'Pointer down', 'Selected'],+ description:+ 'The circle edge (unselected) and fill (selected) must have at least 3:1 contrast with the surface behind them. For Hover and Pointer down, measure the final colors after the tint and the pressed overlay are applied.',+ },+ ],description:'A group of options where only one can be selected at a time. All options are visible at once, making it easy to compare choices. Use it when users need to pick one option from a small set.',bestPractices: [diff --git a/packages/core/src/RadioList/RadioList.test.tsx b/packages/core/src/RadioList/RadioList.test.tsxindex 97e0e43b53..e7868ab490 100644--- a/packages/core/src/RadioList/RadioList.test.tsx+++ b/packages/core/src/RadioList/RadioList.test.tsx@@ -15,6 +15,7 @@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 {RadioList} from './RadioList';import {RadioListItem} from './RadioListItem';import {getForcedColorsRules} from '../__tests__/forcedColors';@@ -856,3 +857,34 @@ describe('forced colors (WCAG 1.4.11)', () => {expect(getForcedColorsRules()).toContain('background-color: canvastext;');});});++describe('pressed state', () => {+ it('paints the pressed overlay over the radio indicator while the row is pressed', () => {+ 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;+ if (wrapper == null) {+ throw new Error('the radio has no indicator wrapper to press');+ }+ expect(hasPressedArm(wrapper)).toBe(true);+ });++ it('does not expose a pressed arm on a disabled radio', () => {+ const {container} = render(+ <RadioList label="Plan" value="a" onChange={() => {}}>+ <RadioListItem label="Unavailable" value="b" isDisabled />+ </RadioList>,+ );+ const circle = container.querySelector('.astryx-radio-indicator');+ const wrapper = circle?.parentElement?.parentElement;+ if (wrapper == null) {+ throw new Error('the radio has no indicator wrapper');+ }+ expect(hasPressedArm(wrapper)).toBe(false);+ });+});diff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsxindex aa33555e5b..259fb84633 100644--- a/packages/core/src/RadioList/RadioListItem.tsx+++ b/packages/core/src/RadioList/RadioListItem.tsx@@ -23,6 +23,7 @@ import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import {RadioListContext} from './RadioList';+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';@@ -39,6 +40,25 @@ const styles = stylex.create({flexShrink: 0,isolation: 'isolate',},+ // 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.+ indicatorPressOverlay: {+ '::after': {+ content: '""',+ position: 'absolute',+ inset: 0,+ borderRadius: radiusVars['--radius-full'],+ pointerEvents: 'none',+ backgroundColor: {+ default: 'transparent',+ [stylex.when.ancestor(+ ':active:not(:has(a:active,button:active,[role="button"]:active,[role="link"]:active))',+ indicatorScope,+ )]: colorVars['--color-overlay-pressed'],+ },+ },+ },input: {position: 'absolute',top: '50%',@@ -222,7 +242,11 @@ export function RadioListItem({const radioCircle = (<div- {...stylex.props(styles.radioWrapper, wrapperSizeStyles[size])}+ {...stylex.props(+ styles.radioWrapper,+ wrapperSizeStyles[size],+ !isDisabled && styles.indicatorPressOverlay,+ )}{...focusProps}><inputref={radioRef}diff --git a/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs b/packages/core/src/SegmentedControl/SegmentedControl.doc.mjsindex dbea79cecc..17678441b8 100644--- a/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs+++ b/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs@@ -129,9 +129,9 @@ export const docs = {category: 'Color contrast',criterion: '1.4.3 Contrast (Minimum)',requirement: '4.5:1',- states: ['Rest', 'Hover', 'Selected'],+ states: ['Rest', 'Hover', 'Pointer down', 'Selected'],description:- 'Each label must have at least 4.5:1 contrast with its segment background. Check unselected, Hover, and selected colors as they appear on screen.',+ 'Each label must have at least 4.5:1 contrast with its segment background. Check unselected, Hover, Pointer down, and selected colors as they appear on screen. For Hover and Pointer down, measure the final background after the overlay is applied.',},{name: 'Essential icon',diff --git a/packages/core/src/SegmentedControl/SegmentedControl.test.tsx b/packages/core/src/SegmentedControl/SegmentedControl.test.tsxindex 32c645cd76..699046b8ef 100644--- a/packages/core/src/SegmentedControl/SegmentedControl.test.tsx+++ b/packages/core/src/SegmentedControl/SegmentedControl.test.tsx@@ -15,6 +15,7 @@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 {SegmentedControl} from './SegmentedControl';import {SegmentedControlItem} from './SegmentedControlItem';import {@@ -672,3 +673,33 @@ describe('forced colors (WCAG 1.4.11)', () => {expect(getAllInjectedCss()).toContain('forced-color-adjust: none;');});});++describe('pressed state', () => {+ it('paints the pressed overlay on a segment while it is pressed', () => {+ render(+ <SegmentedControl value="grid" onChange={() => {}} label="View mode">+ <SegmentedControlItem value="grid" label="Grid" />+ <SegmentedControlItem value="list" label="List" />+ </SegmentedControl>,+ );+ // The unselected segment is the one a press can change; it carries the+ // system's hover and pressed overlay.+ expect(hasPressedArm(screen.getByRole('radio', {name: 'List'}))).toBe(true);+ // The selected segment keeps its raised surface as it is.+ expect(hasPressedArm(screen.getByRole('radio', {name: 'Grid'}))).toBe(+ false,+ );+ });++ it('does not press a disabled segment', () => {+ render(+ <SegmentedControl value="grid" onChange={() => {}} label="View mode">+ <SegmentedControlItem value="grid" label="Grid" />+ <SegmentedControlItem value="list" label="List" isDisabled />+ </SegmentedControl>,+ );+ expect(hasPressedArm(screen.getByRole('radio', {name: 'List'}))).toBe(+ false,+ );+ });+});diff --git a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx b/packages/core/src/SegmentedControl/SegmentedControlItem.tsxindex ac78900e5d..2d4bc34791 100644--- a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx+++ b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx@@ -33,6 +33,7 @@ import {mergeProps, composeEventHandlers} from '../utils';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';+import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';export interface SegmentedControlItemProps extends BaseProps<HTMLButtonElement> {ref?: React.Ref<HTMLButtonElement>;@@ -91,14 +92,6 @@ const styles = stylex.create({transitionDuration: durationVars['--duration-fast'],transitionTimingFunction: easeVars['--ease-standard'],},- hover: {- backgroundColor: {- default: null,- ':hover:where(:not(:disabled,[aria-disabled="true"]))': {- '@media (hover: hover)': colorVars['--color-overlay-hover'],- },- },- },selected: {// Forced colors (Windows High Contrast) strips the painted surface fill// and box shadow, which would leave the selected segment with no state@@ -248,7 +241,11 @@ export function SegmentedControlItem({sizeStyles[size],isFill && styles.fill,isSelected && styles.selected,- !isSelected && !isItemDisabled && styles.hover,+ // The shared hover and pressed overlay, on the segments a press can+ // change: the selected segment keeps its raised surface as it is.+ !isSelected &&+ !isItemDisabled &&+ interactionOverlayStyles.backgroundColor,isItemDisabled && styles.disabled,xstyle,),diff --git a/packages/core/src/Slider/Slider.doc.mjs b/packages/core/src/Slider/Slider.doc.mjsindex 8d2f4a4ca4..c3a135a347 100644--- a/packages/core/src/Slider/Slider.doc.mjs+++ b/packages/core/src/Slider/Slider.doc.mjs@@ -255,6 +255,17 @@ export const docs = {],},usage: {+ accessibility: [+ {+ name: 'Thumb',+ category: 'Color contrast',+ criterion: '1.4.11 Non-text Contrast',+ requirement: '3:1',+ states: ['Rest', 'Hover', 'Pointer down'],+ description:+ 'The thumb must have at least 3:1 contrast with the track and the surface behind it. Pointer down is the whole drag: measure the thumb with the pressed overlay applied.',+ },+ ],anatomy,description:'A draggable control for selecting a numeric value or range within defined bounds. Supports single value and range selection, tick marks, custom value formatting, and vertical orientation. Use it when users need to explore a continuous range, such as volume, price, or percentage.',diff --git a/packages/core/src/Slider/Slider.test.tsx b/packages/core/src/Slider/Slider.test.tsxindex 4535627f7d..b1e7cf4365 100644--- a/packages/core/src/Slider/Slider.test.tsx+++ b/packages/core/src/Slider/Slider.test.tsx@@ -13,6 +13,7 @@ import {useState} from 'react';import {describe, it, expect, vi, beforeEach} from 'vitest';import {render, screen, act, fireEvent, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import {declaresPressedOverlay} from '../__tests__/pressState';import * as stylex from '@stylexjs/stylex';import {Slider} from './Slider';import {focusOutlineStyles} from '../utils/focusOutline.stylex';@@ -1101,3 +1102,130 @@ describe('Slider', () => {});});});++describe('pressed state', () => {+ it('paints the pressed overlay on the thumb for as long as it is dragged, from wherever the press lands', () => {+ render(+ <Slider label="Volume" value={50} min={0} max={100} onChange={vi.fn()} />,+ );+ const thumb = screen.getByRole('slider');+ const trackContainer = thumb.parentElement!;+ trackContainer.getBoundingClientRect = () => ({+ left: 0,+ top: 0,+ right: 200,+ bottom: 20,+ width: 200,+ height: 20,+ x: 0,+ y: 0,+ toJSON: () => {},+ });++ expect(declaresPressedOverlay(thumb)).toBe(false);+ // A slider is a drag: the press lands on the track, not the thumb, and+ // the thumb follows it. The pressed paint follows the drag.+ fireEvent.pointerDown(trackContainer, {+ clientX: 20,+ clientY: 10,+ pointerId: 1,+ });+ expect(declaresPressedOverlay(thumb)).toBe(true);+ fireEvent.pointerMove(trackContainer, {+ clientX: 120,+ clientY: 10,+ pointerId: 1,+ });+ expect(declaresPressedOverlay(thumb)).toBe(true);+ fireEvent.pointerUp(trackContainer, {+ clientX: 120,+ clientY: 10,+ pointerId: 1,+ });+ expect(declaresPressedOverlay(thumb)).toBe(false);+ });++ it('paints only the thumb being dragged in a range slider', () => {+ render(+ <Slider+ label="Price"+ value={[20, 80] as [number, number]}+ min={0}+ max={100}+ onChange={vi.fn()}+ />,+ );+ const [start, end] = screen.getAllByRole('slider');+ // In range mode the control is the group; each thumb sits in its own+ // value-tooltip wrapper.+ const trackContainer = screen.getByRole('group');+ trackContainer.getBoundingClientRect = () => ({+ left: 0,+ top: 0,+ right: 200,+ bottom: 20,+ width: 200,+ height: 20,+ x: 0,+ y: 0,+ toJSON: () => {},+ });+ fireEvent.pointerDown(trackContainer, {+ clientX: 170,+ clientY: 10,+ pointerId: 1,+ });+ expect(declaresPressedOverlay(end)).toBe(true);+ expect(declaresPressedOverlay(start)).toBe(false);+ fireEvent.pointerUp(trackContainer, {+ clientX: 170,+ clientY: 10,+ pointerId: 1,+ });+ expect(declaresPressedOverlay(end)).toBe(false);+ });++ it('keeps a direct press on the visible upper thumb when range values coincide', () => {+ render(+ <Slider+ label="Price"+ value={[50, 50] as [number, number]}+ min={0}+ max={100}+ onChange={vi.fn()}+ />,+ );+ const [start, end] = screen.getAllByRole('slider');+ const trackContainer = screen.getByRole('group');+ trackContainer.getBoundingClientRect = () => ({+ left: 0,+ top: 0,+ right: 200,+ bottom: 20,+ width: 200,+ height: 20,+ x: 0,+ y: 0,+ toJSON: () => {},+ });++ fireEvent.pointerDown(end, {+ clientX: 100,+ clientY: 10,+ pointerId: 1,+ });+ expect(declaresPressedOverlay(end)).toBe(true);+ expect(declaresPressedOverlay(start)).toBe(false);+ });++ it('does not press a disabled slider', () => {+ render(<Slider label="Volume" value={50} isDisabled onChange={vi.fn()} />);+ const thumb = screen.getByRole('slider');+ fireEvent.pointerDown(thumb.parentElement!, {+ clientX: 20,+ clientY: 10,+ pointerId: 1,+ });+ expect(declaresPressedOverlay(thumb)).toBe(false);+ });+});diff --git a/packages/core/src/Slider/Slider.tsx b/packages/core/src/Slider/Slider.tsxindex fe57dea652..22a7ff83ac 100644--- a/packages/core/src/Slider/Slider.tsx+++ b/packages/core/src/Slider/Slider.tsx@@ -288,6 +288,15 @@ const styles = stylex.create({},},},+ // Pressed: the system's pressed overlay over the thumb's fill for as long+ // as the thumb is being dragged. A slider is a drag, not a tap — the finger+ // lands anywhere on the track and the thumb follows it — so the pressed+ // paint follows the drag state the pointer handlers already keep, on a+ // mouse and on a finger alike, rather than `:active` on the thumb itself+ // (which a press on the track never activates).+ thumbPressed: {+ backgroundImage: `linear-gradient(${colorVars['--color-overlay-pressed']}, ${colorVars['--color-overlay-pressed']})`,+ },thumbDisabled: {backgroundColor: colorVars['--color-background-muted'],cursor: 'default',@@ -701,17 +710,25 @@ export function Slider({ref, ...props}: SliderProps) {const newVal = markEl? Number(markEl.dataset.markValue): getValueFromPosition(e.clientX, e.clientY);- const thumbIndex = getClosestThumb(newVal);+ const track = trackRef.current;+ const thumbs = track?.querySelectorAll<HTMLElement>('[role="slider"]');+ const pressedThumb = (e.target as Element).closest<HTMLElement>(+ '[role="slider"]',+ );+ const pressedThumbIndex =+ pressedThumb == null || thumbs == null+ ? -1+ : Array.from(thumbs).indexOf(pressedThumb);+ // A direct thumb press owns that thumb even when range values coincide.+ // Track and mark presses still choose the nearest value.+ const thumbIndex =+ pressedThumbIndex >= 0 ? pressedThumbIndex : getClosestThumb(newVal);draggingThumbRef.current = thumbIndex;setDraggingThumb(thumbIndex);updateValue(thumbIndex, newVal);- // Focus the closest thumb- const track = trackRef.current;- if (track) {- const thumbs = track.querySelectorAll<HTMLElement>('[role="slider"]');- thumbs[thumbIndex]?.focus();- }+ // Focus the thumb that owns this drag.+ thumbs?.[thumbIndex]?.focus();// Also clear it explicitly: focusing an already-focused thumb fires no// focus event, so a thumb the user had tabbed to would keep its ring// through the drag.@@ -908,6 +925,7 @@ export function Slider({ref, ...props}: SliderProps) {? styles.thumbHorizontal: rtlStyles.centerInline('50%'),!isDisabled && styles.thumbHover,+ !isDisabled && draggingThumb === thumbIndex && styles.thumbPressed,!isDisabled &&keyboardFocusThumb === thumbIndex &&focusOutlineStyles.focusVisible,diff --git a/packages/core/src/Switch/Switch.doc.mjs b/packages/core/src/Switch/Switch.doc.mjsindex 2a1796f1de..136244e4e2 100644--- a/packages/core/src/Switch/Switch.doc.mjs+++ b/packages/core/src/Switch/Switch.doc.mjs@@ -210,6 +210,17 @@ export const docs = {],},usage: {+ accessibility: [+ {+ name: 'Track and thumb',+ category: 'Color contrast',+ criterion: '1.4.11 Non-text Contrast',+ requirement: '3:1',+ states: ['Rest', 'Hover', 'Pointer down'],+ description:+ 'The on and off tracks must each have at least 3:1 contrast with the surface behind them, and the thumb with its track. For Hover and Pointer down, measure the final colors after the tint and the pressed overlay are applied.',+ },+ ],anatomy,description:'A toggle control for on/off states that take effect immediately. Supports labels, descriptions, loading states, and validation. Use it for settings or preferences that apply instantly. For changes requiring a form submission, use a checkbox instead.',diff --git a/packages/core/src/Switch/Switch.test.tsx b/packages/core/src/Switch/Switch.test.tsxindex 436c3e2a23..b71c31c68d 100644--- a/packages/core/src/Switch/Switch.test.tsx+++ b/packages/core/src/Switch/Switch.test.tsx@@ -30,6 +30,7 @@ import {getAllInjectedCss,getForcedColorsRules,} from '../__tests__/forcedColors';+import {hasPressedArm} from '../__tests__/pressState';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';afterEach(() => {@@ -755,6 +756,21 @@ describe('Switch', () => {});});+ describe('pressed state', () => {+ it('paints the pressed overlay on the track and the thumb while the row is pressed', () => {+ const {container} = render(+ <Switch label="Notifications" value={false} onChange={() => {}} />,+ );+ const track = container.querySelector('.astryx-switch');+ const thumb = container.querySelector('.astryx-switch-thumb');+ if (track == null || thumb == null) {+ throw new Error('the switch has no track or thumb to press');+ }+ expect(hasPressedArm(track)).toBe(true);+ expect(hasPressedArm(thumb)).toBe(true);+ });+ });+describe('coarse pointer and RTL hit-target positioning', () => {it.each([['sm', 'ltr'],diff --git a/packages/core/src/Switch/Switch.tsx b/packages/core/src/Switch/Switch.tsxindex b303937e4b..8698d6a96b 100644--- a/packages/core/src/Switch/Switch.tsx+++ b/packages/core/src/Switch/Switch.tsx@@ -122,6 +122,15 @@ const thumbOnSizeStyles = stylex.create({},});+// The pressed overlay, painted as a gradient layer OVER the track's and+// thumb's own fills so it composes with the on/off colors and the hover tint+// instead of replacing them. Same token Button's overlay paints with. The+// switch is a two-part control whose focusable input sits beside the track,+// so the press is read off the shared scope marker (the row), the way the+// 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']})`;+const labelWrapperSizeStyles = stylex.create({sm: {minHeight: 20,@@ -207,6 +216,15 @@ const styles = stylex.create({default: null,'@media (forced-colors: active)': 'CanvasText',},+ // Pressed: the overlay rides on top of the on/off fill. Gated like the+ // hover tint so forced colors keeps its system-color track.+ backgroundImage: {+ default: null,+ [stylex.when.ancestor(':active', switchScope)]: {+ default: null,+ '@media (forced-colors: none)': pressedImage,+ },+ },},// The one ring in the system not drawn by focusOutlineStyles. The focusable// input is a sibling of the track, so the condition has to reach the shared@@ -278,6 +296,16 @@ const styles = stylex.create({'@media (prefers-reduced-motion: reduce)': '0s',},transitionTimingFunction: easeVars['--ease-standard'],+ // Pressed: the same overlay as the track, so the whole control darkens+ // under the finger rather than the thumb standing out against a darker+ // track.+ backgroundImage: {+ default: null,+ [stylex.when.ancestor(':active', switchScope)]: {+ default: null,+ '@media (forced-colors: none)': pressedImage,+ },+ },},// The thumb fill lives on the on/off styles (not the shared thumb style)// because forced colors needs a per-state system color: CanvasText on thediff --git a/packages/core/src/TabList/Tab.tsx b/packages/core/src/TabList/Tab.tsxindex dfa5fc593b..f3c60c6dfe 100644--- a/packages/core/src/TabList/Tab.tsx+++ b/packages/core/src/TabList/Tab.tsx@@ -137,6 +137,15 @@ const styles = stylex.create({[stylex.when.ancestor(':hover', tabScope)]: {'@media (hover: hover)': colorVars['--color-overlay-hover'],},+ // Pressed: the same layer steps up to the pressed overlay, read off the+ // tab the way the hover is, so a press paints on a finger too. Repeated+ // inside the hover-capable branch so it outranks the hover rule there+ // (a media-nested rule carries extra generated priority; see+ // interactionOverlay.stylex.ts).+ [stylex.when.ancestor(':active', tabScope)]: {+ default: colorVars['--color-overlay-pressed'],+ '@media (hover: hover)': colorVars['--color-overlay-pressed'],+ },},transitionProperty: 'background-color',transitionDuration: durationVars['--duration-fast'],@@ -249,6 +258,7 @@ export function Tab({xstyle,className,style,+ onClick,...restProps}: TabProps) {const tabListCtx = useTabListContext();@@ -263,9 +273,23 @@ export function Tab({const displayIcon = isSelected && selectedIcon ? selectedIcon : icon;const hasVisibleLabel = !isLabelHidden && label !== '';- const handleSelect = useCallback(() => {- tabListCtx.onChange(value);- }, [tabListCtx, value]);+ const isDisabled =+ restProps['aria-disabled'] === true ||+ restProps['aria-disabled'] === 'true';++ const handleSelect = useCallback(+ (event: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => {+ if (isDisabled) {+ event.preventDefault();+ return;+ }+ onClick?.(event as React.MouseEvent<HTMLButtonElement>);+ if (!event.defaultPrevented) {+ tabListCtx.onChange(value);+ }+ },+ [isDisabled, onClick, tabListCtx, value],+ );useDevWarning('Tab',@@ -339,7 +363,7 @@ export function Tab({sizeStyles[size],isSelected && styles.selected,isFill && layoutStyles.fill,- tabScope,+ !isDisabled && tabScope,xstyle,),className,@@ -382,10 +406,14 @@ export function Tab({) : null;if (isLink) {+ // A disabled link tab must not reach a router component: some routers reject+ // a missing destination, while others treat it as the current route. A+ // plain anchor without href preserves the element shape but cannot navigate.+ const LinkRoot = isDisabled ? 'a' : LinkComponent;return (- <LinkComponent+ <LinkRootref={ref}- href={href}+ href={isDisabled ? undefined : href}onClick={handleSelect}{...sharedProps}>{hoverBgElement}@@ -393,7 +421,7 @@ export function Tab({{labelElement}{endContentElement}{indicatorElement}- </LinkComponent>+ </LinkRoot>);}diff --git a/packages/core/src/TabList/TabList.doc.mjs b/packages/core/src/TabList/TabList.doc.mjsindex 81daa36102..701b56be91 100644--- a/packages/core/src/TabList/TabList.doc.mjs+++ b/packages/core/src/TabList/TabList.doc.mjs@@ -103,6 +103,17 @@ export const docs = {{name: 'TabMenu'},],usage: {+ accessibility: [+ {+ name: 'Tab label',+ category: 'Color contrast',+ criterion: '1.4.3 Contrast (Minimum)',+ requirement: '4.5:1',+ states: ['Rest', 'Hover', 'Pointer down', 'Selected'],+ description:+ 'Each label must have at least 4.5:1 contrast with the tab surface behind it. For Hover and Pointer down, measure the final background after the overlay layer is applied.',+ },+ ],description:'TabList provides tab-style navigation for organizing content into categorized sections. Use it to let users switch between related views without leaving the page, with overflow items handled by a built-in "more" menu.',bestPractices: [diff --git a/packages/core/src/TabList/TabList.test.tsx b/packages/core/src/TabList/TabList.test.tsxindex d6558e795e..020a7fedfb 100644--- a/packages/core/src/TabList/TabList.test.tsx+++ b/packages/core/src/TabList/TabList.test.tsx@@ -12,6 +12,7 @@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 {TabList} from './TabList';import type {TabListProps} from './TabList';import {Tab} from './Tab';@@ -1515,3 +1516,68 @@ describe('TabList ARIA pattern — any other role', () => {);});});++describe('pressed state', () => {+ it('paints the pressed overlay on the tab surface while the tab is pressed', () => {+ render(+ <TabList value="home" onChange={() => {}}>+ <Tab value="home" label="Home" />+ <Tab value="settings" label="Settings" />+ </TabList>,+ );+ const tab = screen.getByRole('button', {name: 'Settings'});+ // The hover surface is a child layer read off the tab; the press paints+ // the same layer, so the assertion is on that layer.+ const surface = tab.querySelector('span[aria-hidden="true"]');+ if (surface == null) {+ throw new Error('the tab has no hover surface to press');+ }+ expect(hasPressedArm(surface)).toBe(true);+ });++ it('does not activate a disabled button tab or call its handler', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ const onClick = vi.fn();+ render(+ <TabList value="home" onChange={onChange}>+ <Tab value="home" label="Home" />+ <Tab+ value="settings"+ label="Settings"+ aria-disabled="true"+ onClick={onClick}+ />+ </TabList>,+ );+ const tab = screen.getByRole('button', {name: 'Settings'});+ await user.click(tab);+ expect(onClick).not.toHaveBeenCalled();+ expect(onChange).not.toHaveBeenCalled();+ });++ it('removes navigation from a disabled link tab', () => {+ const onChange = vi.fn();+ const {container} = render(+ <LinkProvider component={CustomLink}>+ <TabList value="home" onChange={onChange}>+ <Tab value="home" label="Home" />+ <Tab+ value="settings"+ label="Settings"+ href="/settings"+ aria-disabled="true"+ />+ </TabList>+ </LinkProvider>,+ );+ const tab = container.querySelector('a');+ if (tab == null) {+ throw new Error('the disabled link tab did not render an anchor');+ }+ expect(tab).not.toHaveAttribute('data-custom-link');+ expect(tab).not.toHaveAttribute('href');+ fireEvent.click(tab);+ expect(onChange).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/TabList/__tests__/Tabs.a11y.known-failures.ts b/packages/core/src/TabList/__tests__/Tabs.a11y.known-failures.tsindex e2b73d8a5e..114e55b685 100644--- a/packages/core/src/TabList/__tests__/Tabs.a11y.known-failures.ts+++ b/packages/core/src/TabList/__tests__/Tabs.a11y.known-failures.ts@@ -9,37 +9,4 @@import type {KnownFailure} from '@astryxdesign/a11y-spec';-const COMMON = {- binding: 'Tab',- state: 'tab-disabled-unselected',- evidenceLayer: 'real-browser',- standardsReference:- 'WCAG 2.2 4.1.2 Name, Role, Value; WAI-ARIA 1.2 aria-disabled',- reason:- 'This migration records the existing behavior without changing the component interaction contract.',-} as const;--export const TABS_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [- {- ...COMMON,- expectation: 'tabs.tab.unavailable-pointer-inert',- failureEquals:- 'the tab is reported unavailable, but clicking it selected it',- userImpact:- 'A pointer user can activate a tab that assistive technology reports as unavailable.',- },- {- ...COMMON,- expectation: 'tabs.tab.unavailable-enter-inert',- failureEquals: 'the tab is reported unavailable, but Enter selected it',- userImpact:- 'A keyboard user can activate a focusable tab with Enter after assistive technology reports it unavailable.',- },- {- ...COMMON,- expectation: 'tabs.tab.unavailable-space-inert',- failureEquals: 'the tab is reported unavailable, but Space selected it',- userImpact:- 'A keyboard user can activate a focusable tab with Space after assistive technology reports it unavailable.',- },-];+export const TABS_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [];diff --git a/packages/core/src/__tests__/PressedState.a11y.chromium.spec.ts b/packages/core/src/__tests__/PressedState.a11y.chromium.spec.tsnew file mode 100644index 0000000000..0ba695d807--- /dev/null+++ b/packages/core/src/__tests__/PressedState.a11y.chromium.spec.ts@@ -0,0 +1,813 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PressedState.a11y.chromium.spec.ts+ * @input Uses the eight public Pressed state stories and a built Storybook+ * @output Pixel proof for enabled press feedback, release recovery, disabled+ * non-response, and the selected SegmentedControl exception+ * @position Real-Chromium evidence for design:user-states; DOM emulation and+ * generated CSS inspection cannot prove which pixels a held pointer paints.+ */++import {createHash} from 'node:crypto';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {expect, test, type Locator, type Page} from '@playwright/test';+import pixelmatch from 'pixelmatch';+// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.+import {PNG} from 'pngjs';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const OUTPUT = path.resolve('test-results/pressed-state-evidence');++type MountedCase = {+ target: Locator;+ surfaces: Record<string, Locator>;+ state: () => Promise<string>;+ disabledTarget: Locator;+ disabledSurfaces: Record<string, Locator>;+ disabledState: () => Promise<string>;+ independentTarget?: Locator;+ independentSurfaces?: Record<string, Locator>;+ independentState?: () => Promise<string>;+ independentActivated?: () => Promise<boolean>;+ selectedTarget?: Locator;+ selectedSurfaces?: Record<string, Locator>;+ selectedState?: () => Promise<string>;+};++type MatrixCase = {+ component: string;+ storyId: string;+ releaseInPlace?: boolean;+ mount: (root: Locator) => MountedCase;+};++type Shot = {+ file: string;+ sha256: string;+ width: number;+ height: number;+};++type Result = {+ component: string;+ storyId: string;+ shots: Record<string, Shot>;+ comparisons: {+ surface: string;+ pressedDiffPixels: number;+ releasedDiffPixels: number;+ disabledDiffPixels: number;+ independentDiffPixels?: number;+ selectedDiffPixels?: number;+ }[];+};++const results: Result[] = [];+let storybook: StaticServer;+let browserVersion = 'unknown';+let viewport: {width: number; height: number} | null = null;++test.beforeAll(async () => {+ fs.rmSync(OUTPUT, {recursive: true, force: true});+ fs.mkdirSync(OUTPUT, {recursive: true});+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ fs.writeFileSync(+ path.join(OUTPUT, 'manifest.json'),+ `${JSON.stringify(+ {+ version: 1,+ headSha:+ process.env.ASTRYX_HEAD_SHA ??+ process.env.GITHUB_SHA ??+ 'local-working-copy',+ checkoutSha: process.env.GITHUB_SHA ?? 'local-working-copy',+ browser: browserVersion,+ viewport,+ stories: results,+ },+ null,+ 2,+ )}\n`,+ );+ await storybook?.close();+});++const checkedState = (locator: Locator) => async () =>+ JSON.stringify({+ ariaChecked: await locator.getAttribute('aria-checked'),+ nativeChecked: await locator.evaluate(element =>+ element instanceof HTMLInputElement ? element.checked : null,+ ),+ });++const attributeState = (locator: Locator, name: string) => async () =>+ JSON.stringify({value: await locator.getAttribute(name)});++const MATRIX: MatrixCase[] = [+ {+ component: 'checkbox-input',+ storyId: 'core-checkboxinput--pressed-state',+ mount: root => {+ const target = root.getByRole('checkbox', {+ name: 'Unchecked — press and hold',+ });+ const disabledTarget = root.getByRole('checkbox', {+ name: 'Disabled — no pressed state',+ });+ const surfaces = root.locator('.astryx-checkbox-indicator');+ return {+ target,+ surfaces: {indicator: surfaces.nth(0)},+ state: checkedState(target),+ disabledTarget,+ disabledSurfaces: {indicator: surfaces.nth(2)},+ disabledState: checkedState(disabledTarget),+ };+ },+ },+ {+ component: 'collapsible',+ storyId: 'core-collapsible--pressed-state',+ mount: root => {+ const target = root.getByRole('button', {+ name: 'Details — press and hold',+ });+ const disabledTarget = root.getByRole('button', {+ name: 'Unavailable — no pressed state',+ });+ return {+ target,+ surfaces: {trigger: target},+ state: attributeState(target, 'aria-expanded'),+ disabledTarget,+ disabledSurfaces: {trigger: disabledTarget},+ disabledState: attributeState(disabledTarget, 'aria-expanded'),+ };+ },+ },+ {+ component: 'link',+ storyId: 'core-link--pressed-state',+ mount: root => {+ const target = root.getByRole('link', {+ name: 'documentation — press and hold',+ });+ const disabledTarget = root.locator('a[aria-disabled="true"]', {+ hasText: 'Unavailable — no pressed state',+ });+ return {+ target,+ surfaces: {text: target},+ state: attributeState(target, 'href'),+ disabledTarget,+ disabledSurfaces: {text: disabledTarget},+ disabledState: attributeState(disabledTarget, 'href'),+ };+ },+ },+ {+ component: 'slider',+ storyId: 'core-slider--pressed-state',+ releaseInPlace: true,+ mount: root => {+ const target = root.getByRole('slider', {+ name: 'Volume — press and drag',+ });+ const disabledTarget = root.getByRole('slider', {+ name: 'Unavailable — no pressed state',+ });+ return {+ target,+ surfaces: {thumb: target},+ state: attributeState(target, 'aria-valuenow'),+ disabledTarget,+ disabledSurfaces: {thumb: disabledTarget},+ disabledState: attributeState(disabledTarget, 'aria-valuenow'),+ };+ },+ },+ {+ component: 'switch',+ storyId: 'core-switch--pressed-state',+ mount: root => {+ const target = root.getByRole('switch', {name: 'Off — press and hold'});+ const disabledTarget = root.getByRole('switch', {+ name: 'Disabled — no pressed state',+ });+ const tracks = root.locator('.astryx-switch');+ const thumbs = root.locator('.astryx-switch-thumb');+ return {+ target,+ surfaces: {track: tracks.nth(0), thumb: thumbs.nth(0)},+ state: checkedState(target),+ disabledTarget,+ disabledSurfaces: {track: tracks.nth(2), thumb: thumbs.nth(2)},+ disabledState: checkedState(disabledTarget),+ };+ },+ },+ {+ component: 'tab',+ storyId: 'core-tablist--pressed-state',+ mount: root => {+ const target = root.getByRole('button', {+ name: 'Projects — press and hold',+ });+ const disabledTarget = root.getByRole('button', {+ name: 'Unavailable — no pressed state',+ });+ return {+ target,+ surfaces: {+ surface: target.locator('span[aria-hidden="true"]').first(),+ },+ state: attributeState(target, 'aria-current'),+ disabledTarget,+ disabledSurfaces: {+ surface: disabledTarget.locator('span[aria-hidden="true"]').first(),+ },+ disabledState: attributeState(disabledTarget, 'aria-current'),+ };+ },+ },+ {+ component: 'radio-list',+ storyId: 'core-radiolist--pressed-state',+ mount: root => {+ const radio = root.getByRole('radio', {name: 'SMS — press and hold'});+ const target = root.getByTestId('radio-row-press-target');+ const disabledTarget = root.getByRole('radio', {+ name: 'Push — disabled, no pressed state',+ });+ const independentTarget = root.getByRole('link', {+ name: 'Details — independent link',+ });+ const surfaces = root.locator('.astryx-radio-indicator');+ return {+ target,+ surfaces: {indicator: surfaces.nth(1)},+ state: checkedState(radio),+ disabledTarget,+ disabledSurfaces: {indicator: surfaces.nth(2)},+ disabledState: checkedState(disabledTarget),+ independentTarget,+ independentSurfaces: {indicator: surfaces.nth(1)},+ independentState: checkedState(radio),+ independentActivated: async () =>+ root.page().url().endsWith('#details'),+ };+ },+ },+ {+ component: 'segmented-control',+ storyId: 'core-segmentedcontrol--pressed-state',+ mount: root => {+ const target = root.getByRole('radio', {+ name: 'List — press and hold',+ });+ const disabledTarget = root.getByRole('radio', {+ name: 'Unavailable — no pressed state',+ });+ const selectedTarget = root.getByRole('radio', {+ name: 'Grid — selected',+ });+ return {+ target,+ surfaces: {item: target},+ state: checkedState(target),+ disabledTarget,+ disabledSurfaces: {item: disabledTarget},+ disabledState: checkedState(disabledTarget),+ selectedTarget,+ selectedSurfaces: {item: selectedTarget},+ selectedState: checkedState(selectedTarget),+ };+ },+ },+];++async function settle(page: Page): Promise<void> {+ await page.evaluate(+ async () =>+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),+ );+}++async function focusForComparison(target: Locator): Promise<void> {+ await target.evaluate(element => {+ if (element instanceof HTMLElement) {+ element.focus({preventScroll: true});+ }+ });+}++async function pointerCenter(+ locator: Locator,+): Promise<{x: number; y: number}> {+ await locator.scrollIntoViewIfNeeded();+ const box = await locator.boundingBox();+ if (box == null) {+ throw new Error('pointer target has no rendered bounds');+ }+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};+}++async function capture(+ locator: Locator,+ component: string,+ surface: string,+ state: string,+): Promise<{bytes: Buffer; shot: Shot}> {+ await locator.waitFor({state: 'visible'});+ const bytes = await locator.screenshot({animations: 'disabled'});+ const png = PNG.sync.read(bytes);+ const file = `${component}-${surface}-${state}.png`;+ fs.writeFileSync(path.join(OUTPUT, file), bytes);+ return {+ bytes,+ shot: {+ file,+ sha256: createHash('sha256').update(bytes).digest('hex'),+ width: png.width,+ height: png.height,+ },+ };+}++async function captureSurfaces(+ locators: Record<string, Locator>,+ component: string,+ state: string,+ shots: Record<string, Shot>,+): Promise<Record<string, Buffer>> {+ const buffers: Record<string, Buffer> = {};+ for (const [surface, locator] of Object.entries(locators)) {+ const captured = await capture(locator, component, surface, state);+ buffers[surface] = captured.bytes;+ shots[`${surface}-${state}`] = captured.shot;+ }+ return buffers;+}++function diffPixels(before: Buffer, after: Buffer, file: string): number {+ const beforePng = PNG.sync.read(before);+ const afterPng = PNG.sync.read(after);+ if (+ beforePng.width !== afterPng.width ||+ beforePng.height !== afterPng.height+ ) {+ throw new Error(`${file}: surface dimensions changed`);+ }+ const diff = new PNG({width: beforePng.width, height: beforePng.height});+ const count = pixelmatch(+ beforePng.data,+ afterPng.data,+ diff.data,+ beforePng.width,+ beforePng.height,+ {threshold: 0.01, includeAA: true, alpha: 0.2},+ );+ fs.writeFileSync(path.join(OUTPUT, file), PNG.sync.write(diff));+ return count;+}++async function press(page: Page, target: Locator): Promise<void> {+ const point = await pointerCenter(target);+ await page.mouse.move(point.x, point.y);+ await settle(page);+ await page.mouse.down();+ await settle(page);+}++async function releaseAway(page: Page): Promise<void> {+ await page.mouse.move(1, 1);+ await page.mouse.up();+ await settle(page);+}++test('a range Slider keeps the pressed overlay on only the track-selected thumb throughout a drag', async ({+ page,+}) => {+ test.setTimeout(2 * 60 * 1000);+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-slider--pressed-state&viewMode=story`,+ {waitUntil: 'load'},+ );+ await holdMotionStill(page);++ const root = page.locator('#storybook-root');+ const range = root.getByRole('group', {+ name: 'Price range — only the dragged thumb presses',+ });+ const thumbs = range.getByRole('slider');+ const start = thumbs.nth(0);+ const end = thumbs.nth(1);+ await end.waitFor({state: 'visible'});++ const result: Result = {+ component: 'slider-range',+ storyId: 'core-slider--pressed-state',+ shots: {},+ comparisons: [],+ };+ results.push(result);++ await page.mouse.move(1, 1);+ await settle(page);+ const rest = await captureSurfaces(+ {start, end},+ 'slider-range',+ 'rest',+ result.shots,+ );+ const startValue = await start.getAttribute('aria-valuenow');+ const endValue = await end.getAttribute('aria-valuenow');++ const box = await range.boundingBox();+ const startBox = await start.boundingBox();+ const endBox = await end.boundingBox();+ if (box == null || startBox == null || endBox == null) {+ throw new Error('range Slider has no rendered drag geometry');+ }+ const dragStart = {+ x: box.x + box.width * 0.65,+ y: box.y + box.height / 2,+ };+ const isInside = (+ point: {x: number; y: number},+ rect: {x: number; y: number; width: number; height: number},+ ) =>+ point.x >= rect.x &&+ point.x <= rect.x + rect.width &&+ point.y >= rect.y &&+ point.y <= rect.y + rect.height;+ expect(isInside(dragStart, startBox)).toBe(false);+ expect(isInside(dragStart, endBox)).toBe(false);++ await page.mouse.move(dragStart.x, dragStart.y);+ await page.mouse.down();+ await settle(page);+ await page.mouse.move(box.x + box.width * 0.6, dragStart.y);+ await settle(page);+ const dragged = await captureSurfaces(+ {start, end},+ 'slider-range',+ 'dragged',+ result.shots,+ );++ const startDiff = diffPixels(+ rest.start,+ dragged.start,+ 'slider-range-start-stable-diff.png',+ );+ expect(startDiff).toBe(0);+ expect(await start.getAttribute('aria-valuenow')).toBe(startValue);+ expect(await end.getAttribute('aria-valuenow')).not.toBe(endValue);+ const draggedEndValue = await end.getAttribute('aria-valuenow');++ // Release without moving the pointer so the comparison keeps the same thumb+ // value, geometry, hover, and focus. The remaining changed pixels are the+ // pressed overlay that persisted through the drag.+ await page.mouse.up();+ await settle(page);+ const hoverAfterDrag = await captureSurfaces(+ {end},+ 'slider-range',+ 'hover-after-drag',+ result.shots,+ );+ const endDiff = diffPixels(+ hoverAfterDrag.end,+ dragged.end,+ 'slider-range-end-pressed-diff.png',+ );+ expect(endDiff).toBeGreaterThan(0);+ expect(await end.getAttribute('aria-valuenow')).toBe(draggedEndValue);++ await page.mouse.move(1, 1);+ await settle(page);+ const released = await captureSurfaces(+ {end},+ 'slider-range',+ 'released',+ result.shots,+ );+ await page.mouse.move(box.x + box.width * 0.6, dragStart.y);+ await settle(page);+ await page.mouse.move(1, 1);+ await settle(page);+ const settled = await captureSurfaces(+ {end},+ 'slider-range',+ 'rest-after-release',+ result.shots,+ );+ const releasedDiff = diffPixels(+ settled.end,+ released.end,+ 'slider-range-end-released-diff.png',+ );+ expect(releasedDiff).toBe(0);++ result.comparisons.push(+ {+ surface: 'dragged-end-thumb',+ pressedDiffPixels: endDiff,+ releasedDiffPixels: releasedDiff,+ disabledDiffPixels: 0,+ },+ {+ surface: 'stationary-start-thumb',+ pressedDiffPixels: startDiff,+ releasedDiffPixels: 0,+ disabledDiffPixels: 0,+ },+ );+});++test('the bounded pressed matrix paints only enabled transient surfaces', async ({+ page,+}) => {+ test.setTimeout(5 * 60 * 1000);+ browserVersion = page.context().browser()?.version() ?? 'unknown';+ viewport = page.viewportSize();+ const failures: string[] = [];++ for (const entry of MATRIX) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${entry.storyId}&viewMode=story`,+ {waitUntil: 'load'},+ );+ await holdMotionStill(page);+ const mounted = entry.mount(page.locator('#storybook-root'));+ await mounted.target.waitFor({state: 'visible'});++ const result: Result = {+ component: entry.component,+ storyId: entry.storyId,+ shots: {},+ comparisons: [],+ };+ results.push(result);++ const initialState = await mounted.state();++ // Prime each target with a canceled pointer cycle before collecting the+ // baseline. That leaves focus and input modality in the same pointer-owned+ // state used by the measured press, so focus pixels cannot masquerade as+ // pressed feedback.+ await press(page, mounted.target);+ if (entry.releaseInPlace) {+ await page.mouse.up();+ await page.mouse.move(1, 1);+ await settle(page);+ } else {+ await releaseAway(page);+ }+ if ((await mounted.state()) !== initialState) {+ failures.push(`${entry.component}: priming press activated the control`);+ }++ await captureSurfaces(+ mounted.surfaces,+ entry.component,+ 'rest',+ result.shots,+ );++ const point = await pointerCenter(mounted.target);+ await page.mouse.move(point.x, point.y);+ await settle(page);+ const hover = await captureSurfaces(+ mounted.surfaces,+ entry.component,+ 'hover',+ result.shots,+ );+ await page.mouse.down();+ await settle(page);+ const pressed = await captureSurfaces(+ mounted.surfaces,+ entry.component,+ 'pressed',+ result.shots,+ );+ if (entry.releaseInPlace) {+ await page.mouse.up();+ await page.mouse.move(1, 1);+ await settle(page);+ } else {+ await releaseAway(page);+ }+ const released = await captureSurfaces(+ mounted.surfaces,+ entry.component,+ 'released',+ result.shots,+ );+ // Revisit hover, then rest, without another press. This makes the release+ // comparison share the same pointer-owned focus state as the released shot.+ await page.mouse.move(point.x, point.y);+ await settle(page);+ await page.mouse.move(1, 1);+ await settle(page);+ const settledRest = await captureSurfaces(+ mounted.surfaces,+ entry.component,+ 'rest-after-release',+ result.shots,+ );++ for (const surface of Object.keys(mounted.surfaces)) {+ const pressedCount = diffPixels(+ hover[surface],+ pressed[surface],+ `${entry.component}-${surface}-pressed-diff.png`,+ );+ const releasedCount = diffPixels(+ settledRest[surface],+ released[surface],+ `${entry.component}-${surface}-released-diff.png`,+ );+ if (pressedCount === 0) {+ failures.push(+ `${entry.component} ${surface}: held pointer changed no pixels beyond hover`,+ );+ }+ if (releasedCount !== 0) {+ failures.push(+ `${entry.component} ${surface}: release left ${releasedCount} pixels changed`,+ );+ }+ result.comparisons.push({+ surface,+ pressedDiffPixels: pressedCount,+ releasedDiffPixels: releasedCount,+ disabledDiffPixels: 0,+ });+ }+ if ((await mounted.state()) !== initialState) {+ failures.push(`${entry.component}: canceled press activated the control`);+ }++ await page.mouse.move(1, 1);+ await focusForComparison(mounted.disabledTarget);+ await settle(page);+ const disabledRest = await captureSurfaces(+ mounted.disabledSurfaces,+ entry.component,+ 'disabled-rest',+ result.shots,+ );+ const disabledState = await mounted.disabledState();+ await press(page, mounted.disabledTarget);+ const disabledPressed = await captureSurfaces(+ mounted.disabledSurfaces,+ entry.component,+ 'disabled-pressed',+ result.shots,+ );+ await page.mouse.up();+ await settle(page);+ for (const surface of Object.keys(mounted.disabledSurfaces)) {+ const count = diffPixels(+ disabledRest[surface],+ disabledPressed[surface],+ `${entry.component}-${surface}-disabled-diff.png`,+ );+ if (count !== 0) {+ failures.push(+ `${entry.component} ${surface}: disabled hold changed ${count} pixels`,+ );+ }+ const comparison = result.comparisons.find(+ item => item.surface === surface,+ );+ if (comparison != null) {+ comparison.disabledDiffPixels = count;+ }+ }+ if ((await mounted.disabledState()) !== disabledState) {+ failures.push(`${entry.component}: disabled press activated the control`);+ }++ if (+ mounted.independentTarget != null &&+ mounted.independentSurfaces != null &&+ mounted.independentState != null+ ) {+ await page.mouse.move(1, 1);+ await focusForComparison(mounted.independentTarget);+ const independentPoint = await pointerCenter(mounted.independentTarget);+ await page.mouse.move(independentPoint.x, independentPoint.y);+ await settle(page);+ const independentHover = await captureSurfaces(+ mounted.independentSurfaces,+ entry.component,+ 'independent-hover',+ result.shots,+ );+ const independentState = await mounted.independentState();+ await page.mouse.down();+ await settle(page);+ const independentPressed = await captureSurfaces(+ mounted.independentSurfaces,+ entry.component,+ 'independent-pressed',+ result.shots,+ );+ await page.mouse.up();+ await settle(page);+ for (const surface of Object.keys(mounted.independentSurfaces)) {+ const count = diffPixels(+ independentHover[surface],+ independentPressed[surface],+ `${entry.component}-${surface}-independent-diff.png`,+ );+ if (count !== 0) {+ failures.push(+ `${entry.component} ${surface}: nested action hold changed ${count} pixels`,+ );+ }+ const comparison = result.comparisons.find(+ item => item.surface === surface,+ );+ if (comparison != null) {+ comparison.independentDiffPixels = count;+ }+ }+ if ((await mounted.independentState()) !== independentState) {+ failures.push(+ `${entry.component}: nested action changed control state`,+ );+ }+ if (+ mounted.independentActivated != null &&+ !(await mounted.independentActivated())+ ) {+ failures.push(`${entry.component}: nested action did not activate`);+ }+ }++ if (+ mounted.selectedTarget != null &&+ mounted.selectedSurfaces != null &&+ mounted.selectedState != null+ ) {+ await page.mouse.move(1, 1);+ await focusForComparison(mounted.selectedTarget);+ await settle(page);+ const selectedRest = await captureSurfaces(+ mounted.selectedSurfaces,+ entry.component,+ 'selected-rest',+ result.shots,+ );+ const selectedState = await mounted.selectedState();+ await press(page, mounted.selectedTarget);+ const selectedPressed = await captureSurfaces(+ mounted.selectedSurfaces,+ entry.component,+ 'selected-pressed',+ result.shots,+ );+ await releaseAway(page);+ for (const surface of Object.keys(mounted.selectedSurfaces)) {+ const count = diffPixels(+ selectedRest[surface],+ selectedPressed[surface],+ `${entry.component}-${surface}-selected-diff.png`,+ );+ if (count !== 0) {+ failures.push(+ `${entry.component} ${surface}: selected hold changed ${count} pixels`,+ );+ }+ const comparison = result.comparisons.find(+ item => item.surface === surface,+ );+ if (comparison != null) {+ comparison.selectedDiffPixels = count;+ }+ }+ if ((await mounted.selectedState()) !== selectedState) {+ failures.push(`${entry.component}: selected exception changed state`);+ }+ }+ }++ expect(failures).toEqual([]);+});diff --git a/packages/core/src/__tests__/pressState.ts b/packages/core/src/__tests__/pressState.tsnew file mode 100644index 0000000000..2fbebcded2--- /dev/null+++ b/packages/core/src/__tests__/pressState.ts@@ -0,0 +1,93 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file pressState.ts+ * @input Uses document.styleSheets (populated by StyleX runtime injection)+ * @output Exports rulesDeclaredFor and expectPressedArm 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+ * test asserts the next-best thing: that the StyleX dev runtime injected a+ * rule, keyed to the element's own classes, that paints the design system's+ * pressed overlay token while the control is pressed. The selector shape is+ * deliberately not pinned — a press may be read off the element itself+ * (`.x:active`) or off an ancestor scope marker (`.x:where(.marker:active *)`).+ *+ * SYNC: When modified, update this header.+ */++const PRESSED_TOKEN = '--color-overlay-pressed';++function walk(list: CSSRuleList, visit: (rule: CSSRule) => void): void {+ for (const rule of Array.from(list)) {+ visit(rule);+ const nested = (rule as CSSGroupingRule).cssRules;+ if (nested != null) {+ walk(nested, visit);+ }+ }+}++/**+ * Every injected style rule (rules nested in `@media` included) whose selector+ * names one of the element's classes, as `selector {declarations}` text.+ */+export function rulesDeclaredFor(el: Element): string[] {+ const classes = el.className+ .split(/\s+/)+ .filter(Boolean)+ .map(name => `.${name}`);+ const out: string[] = [];+ for (const sheet of Array.from(document.styleSheets)) {+ let rules: CSSRuleList;+ try {+ rules = sheet.cssRules;+ } catch {+ continue;+ }+ walk(rules, rule => {+ if (!(rule instanceof CSSStyleRule)) {+ return;+ }+ const selector = rule.selectorText;+ if (classes.some(cls => selector.startsWith(cls))) {+ out.push(`${selector} {${rule.style.cssText}}`);+ }+ });+ }+ return out;+}++/** The rules on `el` whose selector matches `pseudo` (e.g. `:active`). */+export function rulesWithSelector(el: Element, pseudo: string): string[] {+ return rulesDeclaredFor(el).filter(rule => {+ const selector = rule.slice(0, rule.indexOf('{'));+ return selector.includes(pseudo);+ });+}++/**+ * Does one of the element's own rules paint the pressed overlay token while+ * `pseudo` matches? `pseudo` defaults to `:active`, the arm a mouse press+ * takes.+ */+export function hasPressedArm(el: Element, pseudo = ':active'): boolean {+ return rulesWithSelector(el, pseudo).some(rule =>+ rule.includes(PRESSED_TOKEN),+ );+}++/**+ * Does one of the element's own classes paint the pressed overlay token+ * unconditionally — no pseudo-class, no ancestor scope — because the component+ * applies the class while it holds the press itself (a dragged slider thumb)?+ * StyleX's specificity padding (`:not(#\#)`) is not a condition.+ */+export function declaresPressedOverlay(el: Element): boolean {+ return rulesDeclaredFor(el).some(rule => {+ const selector = rule+ .slice(0, rule.indexOf('{'))+ .replaceAll(':not(#\\#)', '');+ return !selector.includes(':') && rule.includes(PRESSED_TOKEN);+ });+}diff --git a/packages/core/src/utils/interactionOverlay.stylex.ts b/packages/core/src/utils/interactionOverlay.stylex.tsindex 740054b7ad..843186b730 100644--- a/packages/core/src/utils/interactionOverlay.stylex.ts+++ b/packages/core/src/utils/interactionOverlay.stylex.ts@@ -10,6 +10,11 @@* @output Exports reusable background-color and background-image state styles* @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.+ ** 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@@ -71,4 +76,19 @@ 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.+ */+ pressedBackgroundColor: {+ backgroundColor: {+ default: null,+ [ENABLED]: {+ default: null,+ ':active': colorVars['--color-overlay-pressed'],+ },+ },+ },});