An open source design system that's fully customizable and agent ready
TypeScript
fix(CheckboxListItem): a row answers a finger the same wherever it lands (#8212)
Christopher Chedeaua6a9b9c50f2a
diff --git a/.changeset/checkbox-row-one-press-surface.md b/.changeset/checkbox-row-one-press-surface.mdnew file mode 100644index 0000000000..5e5d0318a8--- /dev/null+++ b/.changeset/checkbox-row-one-press-surface.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] On a touch screen, a CheckboxList row now answers a finger the same way wherever it lands. Under a finger, pressing a row's label painted the whole row while pressing its box painted only the box; under a coarse primary pointer the row is now the one touch press surface, so the row and its checkbox show the pressed state together whether the finger lands on the label, the description or the box. Where the primary pointer is fine (a mouse, a trackpad, or a pen on a desktop page), the box keeps its own press and hover, as before.++@vjeuxdiff --git a/.changeset/use-media-query-one-watch.md b/.changeset/use-media-query-one-watch.mdnew file mode 100644index 0000000000..156ffb6e98--- /dev/null+++ b/.changeset/use-media-query-one-watch.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `useMediaQuery` now shares one listener per query among all its callers, so a long list of components that ask the same query adds one listener, not one per component. Every caller still reads the same answer. It also listens on Safari before 14, which has only the older listener pair, where it threw before.++@vjeuxdiff --git a/apps/storybook/stories/CheckboxList.stories.tsx b/apps/storybook/stories/CheckboxList.stories.tsxindex fe58d67731..6d8aabde95 100644--- a/apps/storybook/stories/CheckboxList.stories.tsx+++ b/apps/storybook/stories/CheckboxList.stories.tsx@@ -3,9 +3,11 @@import {useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {CheckboxList, CheckboxListItem} from '@astryxdesign/core/CheckboxList';+import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';import {List} from '@astryxdesign/core/List';import {Badge} from '@astryxdesign/core/Badge';import {Card} from '@astryxdesign/core/Card';+import {ClickableCard} from '@astryxdesign/core/ClickableCard';import {Link} from '@astryxdesign/core/Link';import CheckboxListSelectAllPattern from '../../../packages/cli/assets/templates/blocks/components/CheckboxList/CheckboxListSelectAllPattern';@@ -199,6 +201,62 @@ export const ReadOnly: Story = {),};+/**+ * A checkbox placed in a row's content is its own control. Under a finger it+ * paints its own press, and the row it sits in does not.+ */+export const CheckboxInRowContent: Story = {+ name: "Checkbox in a row's content",+ render: () => {+ const [value, setValue] = useState<string[]>([]);+ const [digest, setDigest] = useState(false);+ return (+ <CheckboxList label="Notifications" value={value} onChange={setValue}>+ <CheckboxListItem+ label="Email"+ value="email"+ endContent={+ <CheckboxInput+ label="Daily digest"+ value={digest}+ onChange={setDigest}+ />+ }+ />+ <CheckboxListItem label="SMS" value="sms" />+ </CheckboxList>+ );+ },+};++// A CheckboxList placed in a row's content keeps its own rows' press: holding+// the outer row leaves the inner list's boxes at rest.+export const CheckboxListInRowContent: Story = {+ name: "Checkbox list in a row's content",+ render: () => {+ const [value, setValue] = useState<string[]>([]);+ const [channels, setChannels] = useState<string[]>([]);+ return (+ <CheckboxList label="Notifications" value={value} onChange={setValue}>+ <CheckboxListItem+ label="Email"+ value="email"+ endContent={+ <CheckboxList+ label="Email channels"+ value={channels}+ onChange={setChannels}>+ <CheckboxListItem label="Work" value="work" />+ <CheckboxListItem label="Personal" value="personal" />+ </CheckboxList>+ }+ />+ <CheckboxListItem label="SMS" value="sms" />+ </CheckboxList>+ );+ },+};+export const SelectAllWithIndeterminate: Story = {render: () => {const allItems = ['email', 'sms', 'push'];@@ -556,6 +614,28 @@ export const InsideCardWithDividers: Story = {},};+// A list inside a ClickableCard. Nested controls work independently, so a+// finger on the card presses the card, and a finger on a row presses that row.+export const InsideClickableCard: Story = {+ name: 'Inside a clickable card',+ render() {+ const [selected, setSelected] = useState<string[]>(['email']);+ return (+ <div style={{maxWidth: 400}}>+ <ClickableCard label="Notification settings" onClick={() => {}}>+ <CheckboxList+ label="Notifications"+ value={selected}+ onChange={setSelected}>+ <CheckboxListItem value="email" label="Email" />+ <CheckboxListItem value="sms" label="SMS" />+ </CheckboxList>+ </ClickableCard>+ </div>+ );+ },+};+// Long option content in a sized field. String labels and descriptions stay on// one line with an ellipsis (the full string still names the checkbox); rich// labels and descriptions wrap. `width` sizes the label, list, and statusdiff --git a/docs/specs/components/CheckboxList/CheckboxListItem.spec.md b/docs/specs/components/CheckboxList/CheckboxListItem.spec.mdindex 78bea1a960..7053d8e5c5 100644--- a/docs/specs/components/CheckboxList/CheckboxListItem.spec.md+++ b/docs/specs/components/CheckboxList/CheckboxListItem.spec.md@@ -27,6 +27,7 @@ verified_by:[packages/core/src/CheckboxList/CheckboxList.test.tsx,packages/core/src/CheckboxList/__tests__/CheckboxList.a11y.chromium.spec.ts,+ packages/core/src/CheckboxList/__tests__/CheckboxListPress.a11y.chromium.spec.ts,packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.test.tsx,packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.chromium.spec.ts,apps/storybook/rtl-audit/targets.json,@@ -201,6 +202,7 @@ durable constraints and their verification target.MUST follow the same availability and change rules as pointer activation.- **AR3 — Enlarged target.** The row surface MUST act as the checkbox's pointerand touch target without becoming a second control.+ Under a coarse pointer, a finger held on the box of a click-delegating row presses and paints the whole row, as a press on the row does (owner pass, 2026-11-04).- **AR4 — Busy perception.** A busy option MUST expose busy state in theaccessibility tree and visibly through Spinner.- **AR5 — Focus visibility.** Keyboard focus on the checkbox MUST stay visible;@@ -245,6 +247,7 @@ and CheckboxListItem owns no target of its own.| Contract | Verification | Representative states | Mutation or failure expectation | Audit section || ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- || FR1, FR9, AR2, AR3 | `CheckboxList.test.tsx` single-tab-stop, row-click, link-in-label, and interactive end-content cases | Collection option; row-surface click; link in a rich label; interactive end content | A second tab stop, lost delegation, or a toggle from an interactive descendant fails. | `audit:CheckboxListItem/interaction` |+| AR3 (finger) | `CheckboxList.test.tsx` press-surface cases; `CheckboxListPress.a11y.chromium.spec.ts` | Coarse and fine pointer; label, description and box; nested checkbox | A finger on the box that paints only the box, a mouse press that paints the row, or a nested checkbox pressing the row fails. | `audit:CheckboxListItem/interaction` || FR2, FR3, AR1 | `CheckboxList.test.tsx` accessible-name and description cases; shared checkbox bindings | String and rich label; `aria-label`; string and node description; absent description | A wrong name or description, or `aria-label` on the row, fails. | `audit:CheckboxListItem/accessibility` || FR4, FR5 | `CheckboxList.test.tsx` collection, standalone, and select-all cases | Add, remove, missing `value`, mixed, select-all, `isChecked` with a parent array | A wrong array or boolean, a missing error, or `isChecked` overriding membership fails. | `audit:CheckboxListItem/behavior` || FR6–FR8, AR4 | `CheckboxList.test.tsx` disabled, loading, pending, and read-only cases; `CheckboxList.a11y.chromium.spec.ts` `disabled-*`, `loading-item`, `pending-*`, and `read-only` cases | Item and group disabled; reason; loading; pending; read-only | A toggle while disabled, read-only, or busy, or a lost busy state, fails. | `audit:CheckboxListItem/accessibility` |diff --git a/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs b/packages/core/src/CheckboxInput/CheckboxInput.doc.mjsindex e64927e31d..3c0907ef96 100644--- a/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs+++ b/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs@@ -155,7 +155,7 @@ export const docs = {{name: '--_indicator-press-image',description:- "The row's touch press image, handed down to a first-party indicator that paints its own press. Set from the press paint only while the row itself is pressed; only this row declares it.",+ "The row's touch press image, handed down to a first-party indicator that paints its own press. Set from the press paint only while the row itself is pressed, or, under a CheckboxList row that owns the press, from that row's press paint. Only this row declares it.",default: 'none',private: true,},@@ -404,7 +404,7 @@ export const docsZh = {{name: '--_indicator-press-image',description:- '复选框行的触摸按下图像,传递给自行绘制按下效果的第一方指示器。仅在该行自身被按下时根据按下涂层设置,只有该行声明它。',+ '复选框行的触摸按下图像,传递给自行绘制按下效果的第一方指示器。仅在该行自身被按下时根据按下涂层设置;在拥有按下效果的 CheckboxList 行中,取该行的按下涂层。只有该行声明它。',default: 'none',private: true,},diff --git a/packages/core/src/CheckboxInput/CheckboxInput.tsx b/packages/core/src/CheckboxInput/CheckboxInput.tsxindex e5ce3784c0..a7f1596aa0 100644--- a/packages/core/src/CheckboxInput/CheckboxInput.tsx+++ b/packages/core/src/CheckboxInput/CheckboxInput.tsx@@ -4,7 +4,8 @@/*** @file CheckboxInput.tsx- * @input Uses React, useId, ChangeEvent, FieldLabel, FieldStatus, IconType, InputStatus, useTooltip+ * @input Uses React, useId, ChangeEvent, FieldLabel, FieldStatus, IconType, InputStatus, useTooltip,+ * CheckboxRowPressContext (a row around the checkbox that owns its press)* @output Exports CheckboxInput component, CheckboxInputProps* @position Core implementation; consumed by index.ts, tested by CheckboxInput.test.tsx*@@ -17,6 +18,7 @@*/import {+ use,useId,useCallback,useOptimistic,@@ -64,6 +66,7 @@ import {useComponentTranslator,} from '../i18n/useComponentTranslator';import english from '../i18n/generated-english/CheckboxInput/CheckboxInput.generated';+import {CheckboxRowPressContext} from './CheckboxRowPressContext';registerEnglishFallback(english);@@ -94,7 +97,7 @@ const styles = stylex.create({// An indicator in another package may not name this row's private press// attribute. So the row hands its touch press image down to an indicator// that paints its own press, but only in its own press states. A pressed- // ancestor row reaches it no more than it reaches the built-in box. The+ // outer row hands down nothing, as for the built-in box. The// property has no default: a layered stylesheet ranks a default above the// arms. Only this row declares it. A menu item paints its own press, so a// mapped indicator there paints none.@@ -105,6 +108,12 @@ const styles = stylex.create({[PRESSED_FADING]: 'var(--_press-paint-image)',},},+ // Under a row that owns the press (CheckboxRowPressContext), this row is+ // never pressed. So it hands down that row's press paint, which the+ // built-in box reads too.+ indicatorRowPressImage: {+ '--_indicator-press-image': 'var(--_checkbox-row-press-paint, none)',+ },checkboxWrapper: {position: 'relative',display: 'flex',@@ -116,11 +125,12 @@ const styles = stylex.create({// The owner paints this layer over the resolved indicator, so a plain theme// replacement keeps the pressed feedback. An indicator with// `indicatorPressScope` paints its own press from what the row hands down,- // so this layer stays off over it.- // 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.+ // so this layer stays off over it. A mouse keeps `:active` (see+ // interactionOverlay.stylex.ts). Under a coarse pointer that arm is dropped.+ // The touch press controller then writes the press attribute on the row.+ // This layer reads it off the scope marker, as the hover tint does. Under a+ // row that owns the press (CheckboxRowPressContext), the row's own checkbox+ // paints that row's press paint instead (indicatorRowPressOverlay).indicatorPressOverlay: {'::after': {// `when.descendant` takes a pseudo-class; `:is(*)` matches any marked@@ -157,6 +167,15 @@ const styles = stylex.create({},},},+ // The row's own checkbox when its row owns the press+ // (CheckboxRowPressContext). It paints only the paint that row declares+ // (`--_checkbox-row-press-paint`). No outer row, card or fine pointer+ // reaches it.+ indicatorRowPressOverlay: {+ '::after': {+ backgroundImage: 'var(--_checkbox-row-press-paint, none)',+ },+ },// 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.@@ -381,6 +400,13 @@ export function CheckboxInput({// 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();+ // A row around the checkbox that answers a press anywhere on it (a+ // CheckboxListItem) owns the touch press instead. The checkbox then carries+ // no press marker of its own. So the controller's innermost-wins rule finds+ // the row for a finger on the label, the description or the box. The+ // overlay below paints that row's press.+ const isRowPressSurface = use(CheckboxRowPressContext);+ const ownsPress = !isDisabled && !isRowPressSurface;const generatedId = useId();const id = idProp || generatedId;const descriptionID = useId();@@ -515,7 +541,7 @@ export function CheckboxInput({ref={rowRef}onPointerDown={hasHitArea ? handleRowPointerDown : undefined}onClick={hasHitArea ? handleRowClick : undefined}- {...(isDisabled ? undefined : pressable)}+ {...(ownsPress ? pressable : undefined)}{...stylex.props(styles.container,isLabelHidden && styles.containerLabelHidden,@@ -524,17 +550,22 @@ export function CheckboxInput({// Hover and focus reach the checkbox visual through this ancestor// marker rather than props, so the whole row drives it.!isDisabled && indicatorScope,- !isDisabled && styles.indicatorPressImage,+ !isDisabled &&+ (isRowPressSurface+ ? styles.indicatorRowPressImage+ : styles.indicatorPressImage),// 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,+ // and paints it. Under a row that owns the press, the box inherits+ // that row's strength instead.+ ownsPress && interactionOverlayStyles.pressedAlpha,)}><div{...stylex.props(styles.checkboxWrapper,wrapperSizeStyles[size],!isDisabled && styles.indicatorPressOverlay,+ !isDisabled && isRowPressSurface && styles.indicatorRowPressOverlay,)}{...focusProps}><inputdiff --git a/packages/core/src/CheckboxInput/CheckboxRowPressContext.ts b/packages/core/src/CheckboxInput/CheckboxRowPressContext.tsnew file mode 100644index 0000000000..3b7753a909--- /dev/null+++ b/packages/core/src/CheckboxInput/CheckboxRowPressContext.ts@@ -0,0 +1,22 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file CheckboxRowPressContext.ts+ * @input Uses the private layer-scoped context factory+ * @output CheckboxRowPressContext: whether the row is its checkbox's press surface+ * @position Internal; CheckboxListItem provides it, CheckboxInput reads it+ *+ * Such a row carries the shared press marker (utils/pressFeedback.ts). Its+ * checkbox carries none, so a finger anywhere on the row presses the row.+ * It is layer-scoped and wraps only the row's own checkbox.+ *+ * SYNC: When modified, update CheckboxInput.tsx and+ * ../CheckboxList/CheckboxListItem.tsx.+ */++import {createLayerScopedContext} from '../Layer/layerScopedContext';++export const CheckboxRowPressContext = createLayerScopedContext(false);+CheckboxRowPressContext.displayName = 'CheckboxRowPressContext';diff --git a/packages/core/src/CheckboxList/CheckboxList.doc.mjs b/packages/core/src/CheckboxList/CheckboxList.doc.mjsindex 5af6a76370..170021db12 100644--- a/packages/core/src/CheckboxList/CheckboxList.doc.mjs+++ b/packages/core/src/CheckboxList/CheckboxList.doc.mjs@@ -258,6 +258,15 @@ export const docs = {},theming: {targets: [{className: 'astryx-checkbox-list'}],+ vars: [+ {+ name: '--_checkbox-row-press-paint',+ description:+ "The touch press paint a row that owns its checkbox's press hands that checkbox's box: none at rest, and the press paint at the press's strength while the touch press controller presses that row under a coarse pointer. Set on the row by its own press arms; the box reads its nearest row's value, so a list placed in a row's content keeps its own rows' paint.",+ default: 'none',+ private: true,+ },+ ],},};diff --git a/packages/core/src/CheckboxList/CheckboxList.test.tsx b/packages/core/src/CheckboxList/CheckboxList.test.tsxindex 8857c399a9..a743d5332f 100644--- a/packages/core/src/CheckboxList/CheckboxList.test.tsx+++ b/packages/core/src/CheckboxList/CheckboxList.test.tsx@@ -19,12 +19,21 @@ import {waitFor,} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import * as stylex from '@stylexjs/stylex';import {CheckboxList} from './CheckboxList';import {CheckboxListItem} from './CheckboxListItem';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';import {__resetInteractionModalityForTest} from '../utils/interactionModality';import {List} from '../List/List';+import {CheckboxInput} from '../CheckboxInput/CheckboxInput';import {FormLayout} from '../FormLayout/FormLayout';+import {indicatorScope} from '../Indicator/indicator.markers.stylex';+import {stubMatchMedia} from '../__tests__/stubMatchMedia';+import {+ declaresPressPaint,+ hasPressedArm,+ hasReleaseFade,+} from '../__tests__/pressState';// FieldStatus announces status messages through the persistent useAnnounce// singletons; remove them between tests so role/aria-live queries in this@@ -1420,3 +1429,331 @@ describe('CheckboxList group disabled state', () => {);});});++describe('CheckboxListItem press surface', () => {+ const hoverScopeClass = stylex.props(indicatorScope).className ?? '';++ // The row owns its checkbox's press only under a coarse primary pointer (a+ // finger). On a fine-pointer page the box keeps its own press.+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ /** A coarse primary pointer: every non-motion query matches. */+ function withCoarsePointer() {+ stubMatchMedia({matches: true, pointer: 'coarse'});+ }++ /** The row's checkbox: its indicator wrapper and the control around it. */+ function parts(row: HTMLElement) {+ const box = row.querySelector('.astryx-checkbox-indicator');+ const wrapper = box?.parentElement?.parentElement;+ const control = wrapper?.parentElement;+ if (wrapper == null || control == null) {+ throw new Error('the row has no checkbox to press');+ }+ return {wrapper, control};+ }++ function rowOf(name: string): HTMLElement {+ const row = screen.getByRole('checkbox', {name}).closest('li');+ if (row == null) {+ throw new Error(`no row for ${name}`);+ }+ return row;+ }++ function classesOf(element: Element): string[] {+ return element.className.split(/\s+/);+ }++ /**+ * The rules for an element's own classes that declare a property, each+ * with its selector, the media conditions around it and the value.+ */+ function rulesFor(+ element: Element,+ read: (style: CSSStyleDeclaration) => string,+ ): {selector: string; conditions: string[]; value: string}[] {+ const classes = Array.from(element.classList).map(name => `.${name}`);+ const rules: {selector: string; conditions: string[]; value: string}[] = [];+ const walk = (list: CSSRuleList, conditions: string[]) => {+ for (const rule of Array.from(list)) {+ if (rule instanceof CSSMediaRule) {+ walk(rule.cssRules, [...conditions, rule.media.mediaText]);+ } else if (+ rule instanceof CSSStyleRule &&+ classes.some(cls => rule.selectorText.startsWith(cls))+ ) {+ const value = read(rule.style).trim();+ if (value !== '') {+ rules.push({selector: rule.selectorText, conditions, value});+ }+ }+ }+ };+ for (const sheet of Array.from(document.styleSheets)) {+ walk(sheet.cssRules, []);+ }+ return rules;+ }++ /**+ * Does the row declare its own press paint for its box? It is none at rest.+ * Under a coarse pointer it is the press paint, only inside the row's own+ * `data-astryx-press` arms (on the row itself, not an ancestor).+ */+ function declaresRowPressPaint(row: Element): boolean {+ const rules = rulesFor(row, style =>+ style.getPropertyValue('--_checkbox-row-press-paint'),+ );+ const rest = rules.filter(+ rule =>+ rule.conditions.length === 0 &&+ !rule.selector.includes('data-astryx-press'),+ );+ const pressed = rules.filter(rule =>+ rule.value.includes('var(--_press-paint-image)'),+ );+ return (+ rest.length > 0 &&+ rest.every(rule => rule.value === 'none') &&+ pressed.length > 0 &&+ pressed.every(+ rule =>+ /^\.[\w-]+(?:\.[\w-]+)*:is\(\[data-astryx-press="(?:on|fading)"\]\)(?::not\(#\\#\))*$/.test(+ rule.selector,+ ) &&+ rule.conditions.some(condition =>+ condition.includes('pointer: coarse'),+ ),+ )+ );+ }++ /**+ * Does the layer over the box paint its own row's press paint+ * (`--_checkbox-row-press-paint`), and nothing it would inherit from+ * further out (the shared `--_press-paint-image`)?+ */+ function readsRowPressPaint(wrapper: Element): boolean {+ const layer = rulesFor(wrapper, style => style.backgroundImage).filter(+ rule => rule.selector.includes('::after'),+ );+ return (+ layer.some(rule =>+ rule.value.includes('var(--_checkbox-row-press-paint'),+ ) && !layer.some(rule => rule.value.includes('var(--_press-paint-image)'))+ );+ }++ it('makes the row the one press surface, so the label and the box press the same element', () => {+ withCoarsePointer();+ render(+ <CheckboxList label="Notifications" value={['email']} onChange={() => {}}>+ <CheckboxListItem label="Email" value="email" />+ <CheckboxListItem label="SMS" value="sms" description="Rates apply" />+ </CheckboxList>,+ );+ expect(hoverScopeClass).not.toBe('');+ for (const name of ['Email', 'SMS']) {+ const row = rowOf(name);+ const {wrapper, control} = parts(row);+ // The touch press paints the innermost marked element under the+ // finger: with nothing marked inside the row, every point of it presses+ // the row.+ expect(row).toHaveAttribute('data-astryx-pressable');+ expect(row.querySelectorAll('[data-astryx-pressable]')).toHaveLength(0);+ expect(control).not.toHaveAttribute('data-astryx-pressable');+ // The row declares the press paint at the press's strength and runs+ // the release. It hands its box that paint through its own press+ // paint, set only while the row itself is pressed under a coarse+ // pointer. The box reads nothing else: no outer row, pressed ancestor+ // or pen on a fine-pointer page.+ expect(declaresPressPaint(row)).toBe(true);+ expect(hasReleaseFade(row)).toBe(true);+ expect(declaresRowPressPaint(row)).toBe(true);+ expect(readsRowPressPaint(wrapper)).toBe(true);+ // A mouse's press and hover stay the checkbox's own.+ expect(classesOf(control)).toContain(hoverScopeClass);+ expect(classesOf(row)).not.toContain(hoverScopeClass);+ expect(hasPressedArm(wrapper)).toBe(true);+ }+ });++ it("keeps the strength's release on a row that owns the press, so its box fades with the row", () => {+ withCoarsePointer();+ render(+ <CheckboxList label="Notifications" value={[]} onChange={() => {}}>+ <CheckboxListItem label="Email" value="email" />+ </CheckboxList>,+ );+ const row = rowOf('Email');+ // Item's row layer turns the release off under a finger. A row that owns+ // the press must not keep that arm, or its box stays at full strength.+ const dropped = rulesFor(row, style => style.animationName).filter(+ rule =>+ rule.selector.includes('[data-astryx-press="fading"]') &&+ !rule.selector.includes('::') &&+ rule.value === 'none',+ );+ expect(dropped).toEqual([]);+ expect(hasReleaseFade(row)).toBe(true);+ });++ it('makes a standalone row with a check handler its press surface too', () => {+ withCoarsePointer();+ render(+ <List>+ <CheckboxListItem+ label="Accept terms"+ isChecked={false}+ onCheck={() => {}}+ />+ </List>,+ );+ const row = rowOf('Accept terms');+ expect(row).toHaveAttribute('data-astryx-pressable');+ expect(row.querySelectorAll('[data-astryx-pressable]')).toHaveLength(0);+ expect(declaresPressPaint(row)).toBe(true);+ });++ it('hands an indicator that paints its own press the row’s press paint, as the box reads it', () => {+ withCoarsePointer();+ render(+ <CheckboxList label="Notifications" value={[]} onChange={() => {}}>+ <CheckboxListItem label="Email" value="email" />+ </CheckboxList>,+ );+ const {control} = parts(rowOf('Email'));+ // The checkbox's own row is never pressed here, so its own press states+ // would hand the indicator nothing.+ const handed = rulesFor(+ control,+ style =>+ /--_indicator-press-image:\s*([^;]+)/.exec(style.cssText)?.[1] ?? '',+ ).map(rule => rule.value);+ expect(handed).toHaveLength(1);+ expect(handed[0]).toMatch(/^var\(--_checkbox-row-press-paint,\s*none\)$/);+ });++ it('keeps the box its own press owner on a fine-pointer page', () => {+ // On a fine-pointer page, a pen or a finger on a touchscreen laptop+ // presses the box itself. The box keeps its own press marker, so it is+ // the innermost pressable under the pen. The row hands its box no press+ // paint, so no row press fades after the lift.+ stubMatchMedia({matches: false});+ render(+ <CheckboxList label="Notifications" value={['email']} onChange={() => {}}>+ <CheckboxListItem label="Email" value="email" />+ </CheckboxList>,+ );+ const row = rowOf('Email');+ const {wrapper, control} = parts(row);+ expect(control).toHaveAttribute('data-astryx-pressable');+ expect(Array.from(row.querySelectorAll('[data-astryx-pressable]'))).toEqual(+ [control],+ );+ expect(declaresRowPressPaint(row)).toBe(false);+ expect(readsRowPressPaint(wrapper)).toBe(false);+ expect(hasPressedArm(wrapper)).toBe(true);+ });++ it('holds one touch-query listener however many rows there are, and none once they unmount', () => {+ // A repeated row adds no touch observer of its own. Every row reads one+ // shared answer, on a fine pointer and on a coarse one alike.+ for (const coarse of [false, true]) {+ let live = 0;+ const count = (query: string, delta: number) => {+ if (query.includes('pointer: coarse')) {+ live += delta;+ }+ };+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ matches: query.includes('pointer: coarse') ? coarse : false,+ media: query,+ onchange: null,+ addEventListener: () => count(query, 1),+ removeEventListener: () => count(query, -1),+ addListener: () => count(query, 1),+ removeListener: () => count(query, -1),+ dispatchEvent: () => false,+ })),+ );+ const {unmount} = render(+ <CheckboxList label="Many" value={['v0']} onChange={() => {}}>+ {Array.from({length: 40}, (_, index) => (+ <CheckboxListItem+ key={index}+ label={`Option ${index}`}+ value={`v${index}`}+ />+ ))}+ </CheckboxList>,+ );+ // The rows still answer the pointer they are on: under a finger the+ // row owns its box's press, so the box carries no press marker.+ const {control} = parts(rowOf('Option 3'));+ expect(control.hasAttribute('data-astryx-pressable')).toBe(!coarse);+ expect(live).toBe(1);+ unmount();+ expect(live).toBe(0);+ vi.unstubAllGlobals();+ }+ });++ it('leaves a row that does not respond to presses out of it', () => {+ // A standalone row with no check handler delegates nothing, so its+ // checkbox keeps its own press.+ render(+ <List>+ <CheckboxListItem label="Completed task" isChecked />+ </List>,+ );+ const row = rowOf('Completed task');+ const {control} = parts(row);+ expect(row).not.toHaveAttribute('data-astryx-pressable');+ expect(control).toHaveAttribute('data-astryx-pressable');+ expect(declaresRowPressPaint(row)).toBe(false);+ expect(readsRowPressPaint(parts(row).wrapper)).toBe(false);+ });++ it('paints no press on a disabled item', () => {+ render(+ <CheckboxList label="Notifications" value={[]} onChange={() => {}}>+ <CheckboxListItem label="Email" value="email" isDisabled />+ </CheckboxList>,+ );+ const row = rowOf('Email');+ const {wrapper, control} = parts(row);+ expect(row.querySelectorAll('[data-astryx-pressable]')).toHaveLength(0);+ expect(control).not.toHaveAttribute('data-astryx-pressable');+ expect(declaresRowPressPaint(row)).toBe(false);+ expect(readsRowPressPaint(wrapper)).toBe(false);+ expect(hasPressedArm(wrapper)).toBe(false);+ });++ it("keeps a checkbox placed in the row's content its own press surface", () => {+ render(+ <CheckboxList label="Notifications" value={[]} onChange={() => {}}>+ <CheckboxListItem+ label="Email"+ value="email"+ endContent={+ <CheckboxInput+ label="Daily digest"+ value={false}+ onChange={() => {}}+ />+ }+ />+ </CheckboxList>,+ );+ const nested = screen.getByRole('checkbox', {name: 'Daily digest'});+ const nestedSurface = nested.closest('[data-astryx-pressable]');+ expect(nestedSurface).not.toBeNull();+ expect(nestedSurface?.tagName).not.toBe('LI');+ });+});diff --git a/packages/core/src/CheckboxList/CheckboxListItem.doc.mjs b/packages/core/src/CheckboxList/CheckboxListItem.doc.mjsindex 8dfac9edc6..f8d9ddf96f 100644--- a/packages/core/src/CheckboxList/CheckboxListItem.doc.mjs+++ b/packages/core/src/CheckboxList/CheckboxListItem.doc.mjs@@ -8,7 +8,7 @@ export const docs = {displayName: 'Checkbox List Item',isHiddenFromOverview: true,description:- 'Individual checkbox item with label, description, and end content slot. Works in collection mode (inside a CheckboxList with a value array) or standalone mode (inside List, or inside a CheckboxList without value, such as a select-all item).',+ 'Individual checkbox item with label, description, and end content slot. Works in collection mode (inside a CheckboxList with a value array) or standalone mode (inside List, or inside a CheckboxList without value, such as a select-all item). On a touch screen (a coarse primary pointer), a toggleable row is one press target: a touch on the label, the description or the box itself shows the pressed state on the row and its checkbox together. Where the primary pointer is fine, the box keeps its own press.',props: [{name: 'label',@@ -105,7 +105,7 @@ export const docsZh = {isHiddenFromOverview: true,displayName: 'Checkbox List Item',description:- '单个复选框选项,包含标签、描述和尾部内容插槽。可在集合模式(位于带 value 数组的 CheckboxList 内)或独立模式(位于 List 内,或位于不带 value 的 CheckboxList 内,例如“全选”选项)下使用。',+ '单个复选框选项,包含标签、描述和尾部内容插槽。可在集合模式(位于带 value 数组的 CheckboxList 内)或独立模式(位于 List 内,或位于不带 value 的 CheckboxList 内,例如“全选”选项)下使用。在触摸屏上,可切换的行是一个整体的按压目标:手指按在标签、描述或复选框本身上,行与其复选框会一起显示按下状态。主指针为精细指针时,复选框保留自己的按下效果。',props: [{name: 'label',@@ -177,7 +177,7 @@ export const docsDense = {isHiddenFromOverview: true,displayName: 'Checkbox List Item',description:- 'Individual checkbox item w/ label, description, end content slot. Collection mode inside CheckboxList with value; standalone inside List or CheckboxList without value.',+ 'Individual checkbox item w/ label, description, end content slot. Collection mode inside CheckboxList with value; standalone inside List or CheckboxList without value. On a touch screen a toggleable row presses as one target, box included; with a fine primary pointer the box keeps its own press.',propDescriptions: {align:"Start/end content alignment, passed to Item: 'center' (default), 'start', or 'first-line' (centered on the label's first line).",diff --git a/packages/core/src/CheckboxList/CheckboxListItem.tsx b/packages/core/src/CheckboxList/CheckboxListItem.tsxindex 836dd2c4dd..08279a1d22 100644--- a/packages/core/src/CheckboxList/CheckboxListItem.tsx+++ b/packages/core/src/CheckboxList/CheckboxListItem.tsx@@ -4,7 +4,8 @@/*** @file CheckboxListItem.tsx- * @input Uses React, CheckboxInput, ListItem, CheckboxListContext+ * @input Uses React, CheckboxInput, ListItem, CheckboxListContext,+ * CheckboxRowPressContext, the touch presentation and the row press paint* @output Exports CheckboxListItem component, CheckboxListItemProps* @position Core implementation; consumed by index.ts, tested by CheckboxList.test.tsx*@@ -25,6 +26,10 @@ import type {BaseProps} from '../BaseProps';import {CheckboxInput} from '../CheckboxInput/CheckboxInput';import type {CheckboxInputProps} from '../CheckboxInput/CheckboxInput';import type {InputStatus} from '../Field/types';+import {CheckboxRowPressContext} from '../CheckboxInput/CheckboxRowPressContext';+import {rowPressPaintStyles} from '../privateAttributes/press.stylex';+import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';+import {useTouchPresentation} from '../utils/touchPresentation';import {ListItem} from '../List/ListItem';import {ListContext} from '../List/ListContext';import {CheckboxListContext} from './CheckboxListContext';@@ -305,6 +310,12 @@ export function CheckboxListItem({registerWithRequiredGroup,);+ // Under a finger, a delegating row is the option's only press surface. A+ // touch anywhere on it presses the row. A fine pointer keeps the box's own+ // press.+ const {isTouch} = useTouchPresentation();+ const rowOwnsPress = isTouch && hasRowInteraction && !effectiveDisabled;+// A read-only checkbox carries aria-readonly, which the row's clickable// container treats as a non-interactive target, so a click on it would be// delegated straight back to the checkbox without end. Stop that click at@@ -359,6 +370,12 @@ export function CheckboxListItem({aria-busy={isBusy || undefined}xstyle={[+ // The row's own press paint, which the layer over its box reads.+ rowOwnsPress && rowPressPaintStyles.checkboxRow,+ // Item's row layer drops the strength's release, and the box paints+ // at that strength. So the row brings the release back, and the box+ // fades with the row.+ rowOwnsPress && interactionOverlayStyles.pressedAlpha,resolvedChecked === true &&!effectiveDisabled &&!effectiveReadOnly &&@@ -369,19 +386,23 @@ export function CheckboxListItem({className={className}style={style}startContent={- <DescribedCheckboxInput- ref={checkboxInputRef}- label={checkboxLabel}- aria-labelledby={namesFromVisibleLabel ? labelID : undefined}- isLabelHidden- value={resolvedChecked}- onChange={() => handleToggle()}- onClick={handleCheckboxClick}- isDisabled={effectiveDisabled}- isReadOnly={effectiveReadOnly}- isLoading={isBusy}- size={checkboxSize}- />+ // Only the row's own checkbox: a checkbox placed in the row's content+ // keeps its own press.+ <CheckboxRowPressContext value={rowOwnsPress}>+ <DescribedCheckboxInput+ ref={checkboxInputRef}+ label={checkboxLabel}+ aria-labelledby={namesFromVisibleLabel ? labelID : undefined}+ isLabelHidden+ value={resolvedChecked}+ onChange={() => handleToggle()}+ onClick={handleCheckboxClick}+ isDisabled={effectiveDisabled}+ isReadOnly={effectiveReadOnly}+ isLoading={isBusy}+ size={checkboxSize}+ />+ </CheckboxRowPressContext>}/>);diff --git a/packages/core/src/CheckboxList/__tests__/CheckboxListPress.a11y.chromium.spec.ts b/packages/core/src/CheckboxList/__tests__/CheckboxListPress.a11y.chromium.spec.tsnew file mode 100644index 0000000000..8a23a88c0c--- /dev/null+++ b/packages/core/src/CheckboxList/__tests__/CheckboxListPress.a11y.chromium.spec.ts@@ -0,0 +1,593 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CheckboxListPress.a11y.chromium.spec.ts+ * @input The CheckboxList Default story in a built Storybook (a layered+ * stylesheet) and real touch input through CDP+ * @output Real-engine proof that a finger on a CheckboxList row's label and on+ * its box press the same surface and paint the same pixels. The box fades+ * with the row on the lift. A pen on a fine-pointer page, a pressed+ * ClickableCard and an outer row paint none of the box's press+ * @position Run with `pnpm test:a11y-contract`. Browser layer of the row's+ * press surface; the jsdom layer is CheckboxList.test.tsx ("CheckboxListItem+ * press surface").+ */++import {+ expect,+ test,+ type Browser,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.+import {PNG} from 'pngjs';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';+import {+ freezeTimers,+ holdAnimations,+ installTimerGate,+ releaseAnimations,+ seekAnimations,+ thawTimers,+} from '@astryxdesign/interaction-harness';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++/** A phone: touch screen, primary pointer coarse. */+const PHONE = {+ viewport: {width: 402, height: 714},+ deviceScaleFactor: 1,+ isMobile: true,+ hasTouch: true,+} as const;++/** A mouse and a fine pointer: the `:active` path. */+const DESKTOP = {+ viewport: {width: 800, height: 600},+ deviceScaleFactor: 1,+ isMobile: false,+ hasTouch: false,+} as const;++/** Resolves after `n` animation frames have presented. */+async function frames(page: Page, n: number): Promise<void> {+ await page.evaluate(+ async count =>+ new Promise<void>(resolve => {+ const step = (left: number) => {+ if (left === 0) {+ resolve();+ } else {+ requestAnimationFrame(() => step(left - 1));+ }+ };+ step(count);+ }),+ n,+ );+}++/** How many animations run in the page, a press release included. */+async function running(page: Page): Promise<number> {+ return page.evaluate(() => document.getAnimations().length);+}++/**+ * Waits until nothing in the page animates. The two frames first let the+ * last input's style change start.+ */+async function untilStill(page: Page): Promise<void> {+ await frames(page, 2);+ await expect.poll(async () => running(page)).toBe(0);+ await frames(page, 2);+}++type RGB = [number, number, number];+type Point = {x: number; y: number};++interface Row {+ page: Page;+ close: () => Promise<void>;+ /** Where a finger lands on the label, and on the box. */+ label: Point;+ box: Point;+ /** Where the press is read: inside the box, and on the row clear of content. */+ boxSample: Point;+ rowSample: Point;+ press: (at: Point) => Promise<void>;+ lift: (at: Point) => Promise<void>;+}++async function openRow(+ browser: Browser,+ story: string,+ name: string,+ device: typeof PHONE | typeof DESKTOP = PHONE,+): Promise<Row> {+ const context = await browser.newContext(device);+ const page = await context.newPage();+ await page.goto(`${storybook.origin}/iframe.html?id=${story}&viewMode=story`);+ const checkbox = page.getByRole('checkbox', {name});+ await checkbox.waitFor({state: 'attached'});+ const geometry = await checkbox.evaluate(input => {+ const row = input.closest('li');+ const box = row?.querySelector('.astryx-checkbox-indicator');+ const label = Array.from(row?.querySelectorAll('span') ?? []).find(+ span => span.children.length === 0 && span.textContent !== '',+ );+ if (row == null || box == null || label == null) {+ return null;+ }+ const rect = (element: Element) => {+ const r = element.getBoundingClientRect();+ return {x: r.x, y: r.y, width: r.width, height: r.height};+ };+ return {row: rect(row), box: rect(box), label: rect(label)};+ });+ if (geometry == null) {+ throw new Error(`${story} has no row for ${name}`);+ }+ const cdp = await context.newCDPSession(page);+ const {row, box, label} = geometry;+ return {+ page,+ close: async () => context.close(),+ label: {x: label.x + label.width / 2, y: label.y + label.height / 2},+ box: {x: box.x + box.width / 2, y: box.y + box.height / 2},+ boxSample: {x: box.x + box.width / 2, y: box.y + box.height - 5},+ rowSample: {x: row.x + row.width - 12, y: row.y + row.height / 2},+ press: async at => {+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [{x: at.x, y: at.y, id: 1}],+ });+ },+ lift: async () => {+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ },+ };+}++/** The colour of a 2 × 2 CSS px patch, as presented. */+async function pixel(page: Page, at: Point): Promise<RGB> {+ const png = PNG.sync.read(+ await page.screenshot({+ clip: {+ x: Math.round(at.x) - 1,+ y: Math.round(at.y) - 1,+ width: 2,+ height: 2,+ },+ animations: 'allow',+ caret: 'hide',+ }),+ );+ const sum = [0, 0, 0];+ const count = png.width * png.height;+ for (let i = 0; i < count; i++) {+ sum[0] += png.data[i * 4];+ sum[1] += png.data[i * 4 + 1];+ sum[2] += png.data[i * 4 + 2];+ }+ return sum.map(value => Math.round(value / count)) as RGB;+}++/** Which element carries the press, described by its tag. */+async function pressedSurface(page: Page): Promise<string | null> {+ return page.evaluate(() => {+ const pressed = document.querySelector('[data-astryx-press]');+ return pressed == null ? null : pressed.tagName.toLowerCase();+ });+}++/** Waits until a press is painted: an element carries it, and nothing animates. */+async function untilPressed(page: Page): Promise<void> {+ await expect.poll(async () => pressedSurface(page)).not.toBeNull();+ await untilStill(page);+}++/** The press state a CheckboxList row carries, or null. */+async function rowPress(page: Page): Promise<string | null> {+ return page.evaluate(+ () =>+ document+ .querySelector('li[data-astryx-press]')+ ?.getAttribute('data-astryx-press') ?? null,+ );+}++const darker = (a: RGB, b: RGB) => a.every((value, i) => value < b[i]);++/**+ * The alpha of the press paint over a row's box, as computed: 0 when the+ * layer paints no image.+ */+async function boxPaint(page: Page, name: string): Promise<number> {+ return page.getByRole('checkbox', {name}).evaluate(input => {+ const layer = input+ .closest('li')+ ?.querySelector('.astryx-checkbox-indicator')+ ?.parentElement?.parentElement;+ if (layer == null) {+ throw new Error('no layer over the box');+ }+ const image = getComputedStyle(layer, '::after').backgroundImage;+ const alphas = Array.from(+ image.matchAll(/rgba\([^)]*?,\s*([\d.]+)\)|\/\s*([\d.]+)\s*\)/g),+ match => Number(match[1] ?? match[2]),+ );+ return alphas.length === 0 ? 0 : Math.max(...alphas);+ });+}++/** The opacity of the pressed row's own layer (Item's `::before`). */+async function layerOpacity(page: Page): Promise<number> {+ return page.evaluate(() => {+ const row = document.querySelector('li[data-astryx-press]');+ return row == null ? 0 : Number(getComputedStyle(row, '::before').opacity);+ });+}++interface PressRead {+ surface: string | null;+ box: RGB;+ row: RGB;+}++test.describe('CheckboxList row press', () => {+ test('a finger on the label and a finger on the box press the same surface and paint the same pixels', async ({+ browser,+ }) => {+ const reads = new Map<'label' | 'box', PressRead>();+ let rest: {box: RGB; row: RGB} | null = null;+ for (const where of ['label', 'box'] as const) {+ // A fresh page per press: the lift toggles the option.+ const row = await openRow(browser, 'core-checkboxlist--default', 'SMS');+ try {+ rest ??= {+ box: await pixel(row.page, row.boxSample),+ row: await pixel(row.page, row.rowSample),+ };+ await row.press(row[where]);+ await untilPressed(row.page);+ reads.set(where, {+ surface: await pressedSurface(row.page),+ box: await pixel(row.page, row.boxSample),+ row: await pixel(row.page, row.rowSample),+ });+ await row.lift(row[where]);+ } finally {+ await row.close();+ }+ }+ const onLabel = reads.get('label');+ const onBox = reads.get('box');+ if (rest == null || onLabel == null || onBox == null) {+ throw new Error('the presses were not read');+ }+ // One surface: the row itself, wherever the finger landed.+ expect(onLabel.surface).toBe('li');+ expect(onBox.surface).toBe('li');+ // The row and the box over it are both painted, the same either way.+ expect(darker(onLabel.row, rest.row)).toBe(true);+ expect(darker(onLabel.box, rest.box)).toBe(true);+ expect(onBox.row).toEqual(onLabel.row);+ expect(onBox.box).toEqual(onLabel.box);+ });++ test('a mouse press runs no touch press, and the label and the box keep their own :active paint', async ({+ browser,+ }) => {+ const reads = new Map<'label' | 'box', PressRead>();+ let rest: {box: RGB; row: RGB} | null = null;+ for (const where of ['label', 'box'] as const) {+ const row = await openRow(+ browser,+ 'core-checkboxlist--default',+ 'SMS',+ DESKTOP,+ );+ try {+ // A fine-pointer case proves nothing under a coarse primary pointer.+ expect(+ await row.page.evaluate(+ () => matchMedia('(pointer: coarse)').matches,+ ),+ ).toBe(false);+ rest ??= {+ box: await pixel(row.page, row.boxSample),+ row: await pixel(row.page, row.rowSample),+ };+ const at = row[where];+ await row.page.mouse.move(at.x, at.y);+ await row.page.mouse.down();+ await untilStill(row.page);+ reads.set(where, {+ surface: await pressedSurface(row.page),+ box: await pixel(row.page, row.boxSample),+ row: await pixel(row.page, row.rowSample),+ });+ await row.page.mouse.up();+ } finally {+ await row.close();+ }+ }+ const onLabel = reads.get('label');+ const onBox = reads.get('box');+ if (rest == null || onLabel == null || onBox == null) {+ throw new Error('the presses were not read');+ }+ // The touch press never runs for a mouse.+ expect(onLabel.surface).toBeNull();+ expect(onBox.surface).toBeNull();+ // Mouse hover and `:active`: on the label the row paints and the box+ // stays blank; on the box the box paints too.+ expect(darker(onLabel.row, rest.row)).toBe(true);+ expect(onLabel.box).toEqual(rest.box);+ expect(darker(onBox.box, rest.box)).toBe(true);+ expect(darker(onBox.row, rest.row)).toBe(true);+ });++ test('a pen on a fine-pointer page presses the box as a mouse does, never the row', async ({+ browser,+ }) => {+ // The row takes the press only under a coarse primary pointer. So on a+ // fine-pointer page a pen presses the box itself and shows only the box's+ // own `:active` paint. The row never paints a press.+ const row = await openRow(+ browser,+ 'core-checkboxlist--default',+ 'Email',+ DESKTOP,+ );+ try {+ expect(+ await row.page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ const cdp = await row.page.context().newCDPSession(row.page);+ const send = async (type: string, pointerType: 'mouse' | 'pen') =>+ cdp.send('Input.dispatchMouseEvent', {+ type: type as 'mousePressed',+ x: row.box.x,+ y: row.box.y,+ button: 'left',+ buttons: type === 'mouseReleased' ? 0 : 1,+ clickCount: 1,+ pointerType,+ });+ const hold = async (pointerType: 'mouse' | 'pen'): Promise<RGB> => {+ await send('mouseMoved', pointerType);+ await send('mousePressed', pointerType);+ await untilStill(row.page);+ const read = await pixel(row.page, row.boxSample);+ await send('mouseReleased', pointerType);+ await untilStill(row.page);+ return read;+ };+ const rest = await pixel(row.page, row.boxSample);+ // Each hold toggles the box, so the mouse toggles it back once before+ // its own read: both reads see the same checked state.+ const pen = await hold('pen');+ await hold('mouse');+ const mouse = await hold('mouse');+ expect(darker(mouse, rest)).toBe(true);+ expect(pen).toEqual(mouse);+ // On a fine-pointer page a pen presses the box, never the row. So right+ // after a quick tap's lift, no row carries a press that would fade out.+ const tap = async (+ pointerType: 'mouse' | 'pen',+ ): Promise<string | null> => {+ await send('mouseMoved', pointerType);+ await send('mousePressed', pointerType);+ // A quick tap: the lift follows a few frames later.+ await frames(row.page, 4);+ await send('mouseReleased', pointerType);+ const left = await rowPress(row.page);+ await untilStill(row.page);+ return left;+ };+ // Each tap toggles the box, so the mouse taps twice: both reads see the+ // same checked state.+ const penTap = await tap('pen');+ await tap('mouse');+ const mouseTap = await tap('mouse');+ expect(penTap).toBeNull();+ expect(mouseTap).toBeNull();+ } finally {+ await row.close();+ }+ });++ test('a finger on a ClickableCard around the list leaves its boxes to the card', async ({+ browser,+ }) => {+ // The card's press is the card's own. Its overlay covers its content, so+ // a box under it shows the card's tint and no press paint of its own.+ const row = await openRow(+ browser,+ 'core-checkboxlist--inside-clickable-card',+ 'SMS',+ );+ try {+ const card = await row.page.evaluate(() => {+ const list = document.querySelector('#storybook-root ul');+ const surface = list?.parentElement?.closest('[data-astryx-pressable]');+ if (surface == null) {+ return null;+ }+ const r = surface.getBoundingClientRect();+ return {x: r.x + 6, y: r.y + 6};+ });+ if (card == null) {+ throw new Error('the story has no pressable card around the list');+ }+ const cardRest = await pixel(row.page, card);+ const boxRest = await pixel(row.page, row.boxSample);+ await row.press(card);+ await untilPressed(row.page);+ const surface = await pressedSurface(row.page);+ const cardHeld = await pixel(row.page, card);+ const boxHeld = await pixel(row.page, row.boxSample);+ await row.lift(card);+ expect(surface).not.toBe('li');+ expect(darker(cardHeld, cardRest)).toBe(true);+ // An unchecked box is the card's own surface colour at rest, so under+ // the card's tint alone it matches the card.+ expect(boxRest).toEqual(cardRest);+ expect(boxHeld).toEqual(cardHeld);+ } finally {+ await row.close();+ }+ });++ test("a list in a row's content keeps its boxes at rest while the outer row is held", async ({+ browser,+ }) => {+ // Each row hands its box its own press paint, so a box reads its nearest+ // row.+ const row = await openRow(+ browser,+ 'core-checkboxlist--checkbox-list-in-row-content',+ 'Email',+ );+ try {+ const inner = await row.page+ .getByRole('checkbox', {name: 'Work'})+ .evaluate(input => {+ const box = input+ .closest('li')+ ?.querySelector('.astryx-checkbox-indicator');+ if (box == null) {+ return null;+ }+ const r = box.getBoundingClientRect();+ return {x: r.x + r.width / 2, y: r.y + r.height - 5};+ });+ if (inner == null) {+ throw new Error('the story has no inner row');+ }+ const outerRest = await pixel(row.page, row.boxSample);+ const innerRest = await pixel(row.page, inner);+ await row.press(row.label);+ await untilPressed(row.page);+ const surface = await pressedSurface(row.page);+ const outerHeld = await pixel(row.page, row.boxSample);+ const innerHeld = await pixel(row.page, inner);+ await row.lift(row.label);+ expect(surface).toBe('li');+ expect(darker(outerHeld, outerRest)).toBe(true);+ expect(innerHeld).toEqual(innerRest);+ } finally {+ await row.close();+ }+ });++ test('holding the row leaves a checkbox in its content at rest', async ({+ browser,+ }) => {+ const row = await openRow(+ browser,+ 'core-checkboxlist--checkbox-in-row-content',+ 'Email',+ );+ try {+ const nested = await row.page+ .getByRole('checkbox', {name: 'Daily digest'})+ .evaluate(input => {+ const box = input.parentElement?.querySelector(+ '.astryx-checkbox-indicator',+ );+ if (box == null) {+ return null;+ }+ const r = box.getBoundingClientRect();+ return {x: r.x + r.width / 2, y: r.y + r.height - 5};+ });+ if (nested == null) {+ throw new Error('the nested checkbox has no box');+ }+ const rest = {+ box: await pixel(row.page, row.boxSample),+ nested: await pixel(row.page, nested),+ };+ await row.press(row.label);+ await untilPressed(row.page);+ const held = {+ surface: await pressedSurface(row.page),+ box: await pixel(row.page, row.boxSample),+ nested: await pixel(row.page, nested),+ };+ await row.lift(row.label);+ // The row owns the press and paints its own box…+ expect(held.surface).toBe('li');+ expect(darker(held.box, rest.box)).toBe(true);+ // …and the checkbox in its content keeps its own press: at rest.+ expect(held.nested).toEqual(rest.nested);+ } finally {+ await row.close();+ }+ });++ test('the box fades with the row when the finger lifts', async ({+ browser,+ }) => {+ const row = await openRow(browser, 'core-checkboxlist--default', 'SMS');+ try {+ const {page} = row;+ // Gate the page's timers before the press, so the controller's end of+ // the release can be held while the release is seeked.+ await installTimerGate(page);+ await row.press(row.label);+ await untilPressed(page);+ const held = await boxPaint(page, 'SMS');+ await row.lift(row.label);+ await freezeTimers(page);+ expect(await rowPress(page)).toBe('fading');+ const animations = await holdAnimations(+ page,+ page.locator('li[data-astryx-press]'),+ );+ expect(animations.length, JSON.stringify(animations)).toBeGreaterThan(0);+ const releaseMs = Math.max(...animations.map(a => a.durationMs));+ await seekAnimations(page, releaseMs / 2);+ const mid = {+ box: await boxPaint(page, 'SMS'),+ layer: await layerOpacity(page),+ };+ await releaseAnimations(page, {finish: true});+ await thawTimers(page);+ expect(held).toBeGreaterThan(0);+ // Half way through the release the row's layer is part way out…+ expect(mid.layer).toBeGreaterThan(0.05);+ expect(mid.layer).toBeLessThan(0.95);+ // …and the box has faded by the same share: its alpha is the overlay's+ // alpha times the strength, on the layer's clock and curve. The bound+ // covers the engine's rounding of the alpha it serializes.+ expect(+ Math.abs(mid.box / held - mid.layer),+ JSON.stringify({held, mid}),+ ).toBeLessThanOrEqual(0.02);+ await expect.poll(async () => rowPress(page)).toBeNull();+ expect(await boxPaint(page, 'SMS')).toBe(0);+ } finally {+ await row.close();+ }+ });+});diff --git a/packages/core/src/hooks/useMediaQuery.test.ts b/packages/core/src/hooks/useMediaQuery.test.tsindex 0d3979a0ec..90bdbd79a3 100644--- a/packages/core/src/hooks/useMediaQuery.test.ts+++ b/packages/core/src/hooks/useMediaQuery.test.ts@@ -173,3 +173,88 @@ describe('useMediaQuery', () => {on.unmount();});});++describe('useMediaQuery shared watch', () => {+ /** A matchMedia whose lists count their live listeners per query. */+ function stubCountingMatchMedia(options: {legacy?: boolean} = {}) {+ const live = new Map<string, number>();+ const handlers = new Map<string, Set<() => void>>();+ let matches = false;+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => {+ const add = (handler: () => void): void => {+ live.set(query, (live.get(query) ?? 0) + 1);+ const set = handlers.get(query) ?? new Set<() => void>();+ set.add(handler);+ handlers.set(query, set);+ };+ const remove = (handler: () => void): void => {+ live.set(query, (live.get(query) ?? 0) - 1);+ handlers.get(query)?.delete(handler);+ };+ const list = {+ media: query,+ get matches() {+ return matches;+ },+ };+ return options.legacy === true+ ? {...list, addListener: add, removeListener: remove}+ : {+ ...list,+ addEventListener: (_type: string, handler: () => void) =>+ add(handler),+ removeEventListener: (_type: string, handler: () => void) =>+ remove(handler),+ };+ }),+ );+ return {+ live: (query: string) => live.get(query) ?? 0,+ change(next: boolean) {+ matches = next;+ for (const set of handlers.values()) {+ for (const handler of Array.from(set)) {+ handler();+ }+ }+ },+ };+ }++ it('holds one listener per query for all its callers, and none after the last unmounts', () => {+ const media = stubCountingMatchMedia();+ const callers = [+ ...[0, 1, 2].map(() =>+ renderHook(() => useMediaQuery('(max-width: 768px)')),+ ),+ ...[0, 1].map(() => renderHook(() => useMediaQuery('(pointer: coarse)'))),+ ];+ expect(media.live('(max-width: 768px)')).toBe(1);+ expect(media.live('(pointer: coarse)')).toBe(1);+ for (const caller of callers) {+ caller.unmount();+ }+ expect(media.live('(max-width: 768px)')).toBe(0);+ expect(media.live('(pointer: coarse)')).toBe(0);+ });++ it('moves every caller of a query when it changes', () => {+ const media = stubCountingMatchMedia();+ const a = renderHook(() => useMediaQuery('(max-width: 768px)'));+ const b = renderHook(() => useMediaQuery('(max-width: 768px)'));+ act(() => media.change(true));+ expect([a.result.current, b.result.current]).toEqual([true, true]);+ });++ it('listens through the older pair on Safari before 14, which has no addEventListener', () => {+ const media = stubCountingMatchMedia({legacy: true});+ const caller = renderHook(() => useMediaQuery('(max-width: 768px)'));+ expect(media.live('(max-width: 768px)')).toBe(1);+ act(() => media.change(true));+ expect(caller.result.current).toBe(true);+ caller.unmount();+ expect(media.live('(max-width: 768px)')).toBe(0);+ });+});diff --git a/packages/core/src/hooks/useMediaQuery.ts b/packages/core/src/hooks/useMediaQuery.tsindex 1546d313b1..9afeb5efc4 100644--- a/packages/core/src/hooks/useMediaQuery.ts+++ b/packages/core/src/hooks/useMediaQuery.ts@@ -4,24 +4,61 @@/*** @file useMediaQuery.ts- * @input Uses React useSyncExternalStore, useCallback+ * @input Uses React useSyncExternalStore, useCallback, and watchMediaQuery+ * (utils/coarsePointer.ts)* @output Exports useMediaQuery hook for responsive breakpoint detection* @position Core hook; used by consumers for responsive patterns** SSR-safe media query hook that subscribes to window.matchMedia changes* via useSyncExternalStore — the canonical React pattern for external- * browser state.+ * browser state. Every caller of a query shares one watch.** SYNC: When modified, update:* - /packages/core/src/hooks/index.ts*/import {useCallback, useSyncExternalStore} from 'react';+import {watchMediaQuery} from '../utils/coarsePointer';++interface SharedWatch {+ readers: Set<() => void>;+ stop: () => void;+}++const watches = new Map<string, SharedWatch>();++function subscribeToQuery(query: string, reader: () => void): () => void {+ // A DOM without `matchMedia`, such as a test DOM, has nothing to watch.+ if (typeof window.matchMedia !== 'function') {+ return () => {};+ }+ let watch = watches.get(query);+ if (watch == null) {+ const readers = new Set<() => void>();+ const stop = watchMediaQuery(window, query, () => {+ for (const each of Array.from(readers)) {+ each();+ }+ });+ watch = {readers, stop};+ watches.set(query, watch);+ }+ const entry = watch;+ entry.readers.add(reader);+ return () => {+ entry.readers.delete(reader);+ if (entry.readers.size === 0 && watches.get(query) === entry) {+ entry.stop();+ watches.delete(query);+ }+ };+}/*** SSR-safe media query hook.* Returns whether the given media query matches. Where the window has no- * `matchMedia`, as in a test DOM, it returns `serverDefault`.+ * `matchMedia`, as in a test DOM, it returns `serverDefault`. All callers of+ * the same query share one listener.** @param query - CSS media query string* @param serverDefault - Value to return during SSR. Pass a server-side hint@@ -35,15 +72,7 @@ import {useCallback, useSyncExternalStore} from 'react';*/export function useMediaQuery(query: string, serverDefault = false): boolean {const subscribe = useCallback(- (onStoreChange: () => void) => {- // A DOM without `matchMedia`, such as a test DOM, has nothing to watch.- if (typeof window.matchMedia !== 'function') {- return () => {};- }- const mql = window.matchMedia(query);- mql.addEventListener('change', onStoreChange);- return () => mql.removeEventListener('change', onStoreChange);- },+ (onStoreChange: () => void) => subscribeToQuery(query, onStoreChange),[query],);diff --git a/packages/core/src/privateAttributes/press.stylex.ts b/packages/core/src/privateAttributes/press.stylex.tsindex 783425c916..05dd0369ef 100644--- a/packages/core/src/privateAttributes/press.stylex.ts+++ b/packages/core/src/privateAttributes/press.stylex.ts@@ -5,17 +5,15 @@/*** @file privateAttributes/press.stylex.ts- * @input StyleX, the semantic overlay color tokens, the touch press strength- * (`pressVars`, utils/interactionOverlay.stylex.ts) and the row layer's- * clocks (utils/rowPressLayer.stylex.ts)- * @output `rowPressLayerStyles`: the compositor press layer for list rows- * (`cell`) and its own-image arms for a row on the `backgroundImage`- * variant (`cellOnImage`)- * @position Owner module of the private press attribute for the row layer:- * the press controller (utils/pressFeedback.ts) writes the attribute, and- * this file reads it. No package entry exports it. Item and TreeList- * compose these styles after their overlay variant;- * utils/interactionOverlay.cell.test.ts tests them.+ * @input StyleX, the overlay color tokens, the touch press strength+ * (`pressVars`) and the row layer's clocks (utils/rowPressLayer.stylex.ts)+ * @output `rowPressLayerStyles`, the compositor press layer for list rows+ * (`cell`, `cellOnImage` for a `backgroundImage` row), and+ * `rowPressPaintStyles`, a CheckboxList row's press paint for its box+ * @position Owner module of the private press attribute: the press controller+ * (utils/pressFeedback.ts) writes it, and this file reads it. No package+ * entry exports it. Item, TreeList and CheckboxListItem compose its styles;+ * utils/interactionOverlay.cell.test.ts tests the row layer.*/import * as stylex from '@stylexjs/stylex';@@ -243,3 +241,21 @@ export const rowPressLayerStyles = stylex.create({},},});++export const rowPressPaintStyles = stylex.create({+ // A box reads its nearest row's value, so a list in a row's content keeps+ // its own rows' paint.+ checkboxRow: {+ '--_checkbox-row-press-paint': {+ default: 'none',+ ':is([data-astryx-press="on"])': {+ default: 'none',+ '@media (pointer: coarse)': 'var(--_press-paint-image)',+ },+ ':is([data-astryx-press="fading"])': {+ default: 'none',+ '@media (pointer: coarse)': 'var(--_press-paint-image)',+ },+ },+ },+});diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.tsindex 1974f63700..45593ae153 100644--- a/packages/core/src/theme/derivedVarRegistry.test.ts+++ b/packages/core/src/theme/derivedVarRegistry.test.ts@@ -360,6 +360,9 @@ const VARS_WITHOUT_DERIVED_MAPPING = new Set([// A checkbox row's touch press image, which an indicator that paints its// own press inherits. The row writes it from the press paint above.'--_indicator-press-image',+ // A CheckboxList row's own press paint, handed to its checkbox's box:+ // written by the row's own press arms, never a value a theme author sets.+ '--_checkbox-row-press-paint','--_input-clear-hit-content','--_power-search-sheet-hit-content',// Placement and swipe lifecycle values are private Toast behavior. A themediff --git a/packages/core/src/utils/coarsePointer.test.ts b/packages/core/src/utils/coarsePointer.test.tsindex 3b33f30f55..a58285ec20 100644--- a/packages/core/src/utils/coarsePointer.test.ts+++ b/packages/core/src/utils/coarsePointer.test.ts@@ -3,12 +3,17 @@/*** @file coarsePointer.test.ts* @input coarsePointer.ts and the gestures' pointer test helper- * @output The gate reads and follows the primary pointer+ * @output The gate reads and follows the primary pointer, and watches any+ * media query* @position Unit tests of packages/core/src/utils/coarsePointer.ts*/import {describe, expect, it} from 'vitest';-import {isCoarsePointer, watchCoarsePointer} from './coarsePointer';+import {+ isCoarsePointer,+ watchCoarsePointer,+ watchMediaQuery,+} from './coarsePointer';import {pointerQuery} from '../gestures/__tests__/pointerQuery';describe('coarsePointer', () => {@@ -33,4 +38,30 @@ describe('coarsePointer', () => {expect(isCoarsePointer(null)).toBe(false);expect(watchCoarsePointer(null, () => {})).toBeTypeOf('function');});++ it('watches any media query, through the older pair where there is no addEventListener', () => {+ const handlers = new Set<() => void>();+ let matches = false;+ const view = {+ matchMedia: (query: string) => ({+ media: query,+ get matches() {+ return matches;+ },+ addListener: (handler: () => void) => handlers.add(handler),+ removeListener: (handler: () => void) => handlers.delete(handler),+ }),+ } as unknown as Window;+ const seen: boolean[] = [];+ const stop = watchMediaQuery(view, '(max-width: 600px)', next =>+ seen.push(next),+ );+ matches = true;+ for (const handler of Array.from(handlers)) {+ handler();+ }+ stop();+ expect(seen).toEqual([true]);+ expect(handlers.size).toBe(0);+ });});diff --git a/packages/core/src/utils/coarsePointer.ts b/packages/core/src/utils/coarsePointer.tsindex a4fca81351..14b727cba5 100644--- a/packages/core/src/utils/coarsePointer.ts+++ b/packages/core/src/utils/coarsePointer.ts@@ -3,11 +3,12 @@/*** @file coarsePointer.ts* @input A window- * @output Exports isCoarsePointer and watchCoarsePointer: whether the- * primary pointer is coarse (TOUCH_QUERY), and when it changes+ * @output Exports isCoarsePointer, watchCoarsePointer and watchMediaQuery:+ * whether the primary pointer is coarse (TOUCH_QUERY), and when it or any+ * media query changes* @position The coarse-pointer gate of packages/core/src/gestures and of* the press controller (pressFeedback.ts): touch-only work registers only- * while it holds+ * while it holds. useMediaQuery watches through watchMediaQuery** Under a coarse primary pointer, a phone's touch work stays registered: the* gesture host's page listeners, the page hold and the finger scroll. Under a@@ -29,23 +30,35 @@ export function isCoarsePointer(view: Window | null | undefined): boolean {}/**- * Call `listener` with the new answer each time the primary pointer of- * `view` turns coarse or fine, until the returned function is called.+ * Call `listener` with the new answer each time `query` starts or stops+ * matching in `view`, until the returned function is called.*/-export function watchCoarsePointer(+export function watchMediaQuery(view: Window | null | undefined,- listener: (isCoarse: boolean) => void,+ query: string,+ listener: (matches: boolean) => void,): () => void {if (typeof view?.matchMedia !== 'function') {return () => {};}- const query = view.matchMedia(TOUCH_QUERY);- const onChange = (): void => listener(query.matches);- if (typeof query.addEventListener === 'function') {- query.addEventListener('change', onChange);- return () => query.removeEventListener('change', onChange);+ const list = view.matchMedia(query);+ const onChange = (): void => listener(list.matches);+ if (typeof list.addEventListener === 'function') {+ list.addEventListener('change', onChange);+ return () => list.removeEventListener('change', onChange);}// Safari before 14 only has the older pair.- query.addListener(onChange);- return () => query.removeListener(onChange);+ list.addListener(onChange);+ return () => list.removeListener(onChange);+}++/**+ * Call `listener` with the new answer each time the primary pointer of+ * `view` turns coarse or fine, until the returned function is called.+ */+export function watchCoarsePointer(+ view: Window | null | undefined,+ listener: (isCoarse: boolean) => void,+): () => void {+ return watchMediaQuery(view, TOUCH_QUERY, listener);}diff --git a/packages/core/src/utils/pressableCoverage.test.ts b/packages/core/src/utils/pressableCoverage.test.tsindex 6431ef1607..c4b2c88b0c 100644--- a/packages/core/src/utils/pressableCoverage.test.ts+++ b/packages/core/src/utils/pressableCoverage.test.ts@@ -67,12 +67,41 @@ const source = new Map(files.map(file => [path.relative(SRC, file), fs.readFileSync(file, 'utf8')]),);-const PRESS_ARM = /':active|'\[data-astryx-press=|interactionOverlayStyles\./;+// A press arm keys on `:active` or on the attribute the controller writes, as+// a bare attribute selector or inside `:is(…)`.+const PRESS_ARM =+ /':active|'(?::is\()?\[data-astryx-press=|interactionOverlayStyles\./;const ANCESTOR_ARM =- /stylex\.when\.ancestor\(\s*'(?::active|\[data-astryx-press=[^)]*)',\s*(\w+)\s*\)/g;+ /stylex\.when\.ancestor\(\s*'(?::active|\[data-astryx-press=[^)]*)',\s*(\w+)\s*,?\s*\)/g;++/** Whether `text` renders a ListItem or Item with an `interactiveRef` prop. */+function delegatesToItem(text: string): boolean {+ for (const match of text.matchAll(/<(?:List)?Item\b/g)) {+ // The opening tag ends at the first `>` outside braces.+ let depth = 0;+ for (let i = match.index + match[0].length; i < text.length; i++) {+ if (text[i] === '{') {+ depth++;+ } else if (text[i] === '}') {+ depth--;+ } else if (text[i] === '>' && depth === 0) {+ if (text.slice(match.index, i).includes('interactiveRef=')) {+ return true;+ }+ break;+ }+ }+ }+ return false;+}+/**+ * Whether a file marks its pressable: it calls `usePressFeedback`, or it+ * hands a ListItem or Item an `interactiveRef`, which Item marks itself.+ */function isMarked(file: string): boolean {- return (source.get(file) ?? '').includes('usePressFeedback(');+ const text = source.get(file) ?? '';+ return text.includes('usePressFeedback(') || delegatesToItem(text);}/** Files (other than `except`) that apply the scope marker `name` to an element. */@@ -169,6 +198,20 @@ describe('every surface that paints a press is reachable by the touch press cont},);+ it('counts a ListItem or Item handed an interactiveRef as marked', () => {+ expect(delegatesToItem('<ListItem label="a" interactiveRef={ref} />')).toBe(+ true,+ );+ expect(+ delegatesToItem('<Item\n interactiveRef={on ? ref : undefined}\n/>'),+ ).toBe(true);+ expect(delegatesToItem('<ListItem onClick={() => {}} />')).toBe(false);+ expect(delegatesToItem('<ListItem label={<b>x</b>} />')).toBe(false);+ expect(delegatesToItem('<CheckboxListItem interactiveRef={ref} />')).toBe(+ false,+ );+ });+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