An open source design system that's fully customizable and agent ready
TypeScript
feat(ToggleButtonGroup): a finger's slide toggles the one it lifts on (#8660)
Christopher Chedeauf75f0f2d3d2b
diff --git a/.changeset/toggle-button-group-press-tracking.md b/.changeset/toggle-button-group-press-tracking.mdnew file mode 100644index 0000000000..1ed20c5c72--- /dev/null+++ b/.changeset/toggle-button-group-press-tracking.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Under the touch presentation, ToggleButtonGroup tracks a finger's or a pen's press across its toggles, like a menu. Press a toggle and slide across the others: the highlight follows, and only the toggle you lift on changes. Lifting outside the group changes nothing. A mouse press is unchanged: it acts as a native toggle's, on the toggle it began on. With a finger, a toggle the group tracks keeps its 44 px target, now drawn by the group. A toggle without a value keeps its own press, and the keyboard is unchanged. Before, each toggle tracked only its own press, and sliding off it changed nothing. An enabled ToggleButtonGroup root is position: relative under a coarse pointer, so absolutely positioned children anchor to the group. With a fine primary pointer, the group is unchanged.++@vjeuxdiff --git a/docs/specs/components/Button/Button.spec.md b/docs/specs/components/Button/Button.spec.mdindex 0fb961cf44..b8a92da60b 100644--- a/docs/specs/components/Button/Button.spec.md+++ b/docs/specs/components/Button/Button.spec.md@@ -257,36 +257,36 @@ anatomy-theming map.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |-| FR1, FR2, AR1 | `Button.test.tsx` label, children, icon-only, end-content presence, and `type` cases; `Button.a11y.test.tsx`; `Button.a11y.chromium.spec.ts` | Text, icon-only, composed label, end content, submit type | A lost name, a wrong default `type`, or end content in icon-only fails. | `audit:Button/anatomy` |-| FR1, FR2 (gaps) | Evidence gap: no test passes `name`, `value`, or `form`, or asserts the order of icon, label, and end content | — | — | `audit:Button/anatomy` |-| FR3 | Evidence gap: no Button-level test of the text-mode icon slot default | `sm`, `md`, `lg` with an unsized Icon | — | `audit:Button/anatomy` |-| FR4 | `ButtonTextSize.interaction.browser.spec.ts` (a label larger than the element size grows its button; the default size keeps the element size). Evidence gap: no test asserts the explicit `size`, then nearest provider, then `md` order | `sm`, `md`, `lg`; inside a size provider | — | `audit:Button/layout` |-| FR5 | `Button.test.tsx` width and narrow-row suites; InputGroup addon case | Numeric and string width, link mode, icon-only, grouped | A Button that overflows its row, stops truncating, or squeezes icon-only fails. | `audit:Button/layout` |-| FR6, FR7 | `Button.test.tsx` click, double-click, and interruptible suites | onClick then clickAction; preventDefault; double-click; re-click | Order flips, a prevented click runs the action, or a fire-once action runs twice fails. | `audit:Button/behavior` |-| FR8, AR4 | `Button.test.tsx` loading, spinner shade, and live-region suites | `isLoading`; pending `clickAction`; first render loading | Missing `aria-busy`, a wrong Spinner shade, or a live region mounted with text fails. | `audit:Button/behavior` |-| FR8 (hide and delay) | Evidence gap: no test asserts the hidden content, the reveal delay, or the reduced-motion path; the shipped Spinner fade fails the fine-pointer reduced-motion clause (Current-state impact) | `isLoading`; pending `clickAction`; interruptible | Under reduced motion with a fine pointer, a Spinner opacity below 1 after the loading state starts. | `audit:Button/behavior` |-| FR8 (outer size) | Evidence gap: no test measures that a pending Button keeps its outer size | Loading text, icon-only, and end-content Buttons | — | `audit:Button/layout` |-| FR9, FR10, AR5 | `Button.test.tsx` aria-disabled, busy-only, and native-disabled suites; `Button.a11y.chromium.spec.ts` | Busy-only, tooltip-disabled, disabled, disabled and loading | A busy Button loses focus, an inert Button fires, or a click reaches an ancestor fails. Native-disabled assertions match the FR10 gap. | `audit:Button/accessibility` |-| FR11 | `Button.test.tsx` link-mode suites | Link, busy-only link, disabled `href` | A disabled link navigates or a busy link turns into a `<button>` fails. | `audit:Button/behavior` |-| FR12 | `Button.a11y.chromium.spec.ts` described state | Disabled with tooltip | A tooltip that does not describe the Button fails. | `audit:Button/accessibility` |-| FR12 (placement and order) | Evidence gap: no test asserts that the tooltip opens above the Button or that its id follows a caller `aria-describedby` | Tooltip with and without a caller description | — | `audit:Button/accessibility` |-| FR13, FR14 | `Button.test.tsx` theme-target and elevation suites; `ButtonGroup.test.tsx` "reports flat on a member, since the group owns the surface" for the grouped `data-elevation="none"` | `secondary` target attributes; every elevation tier | A missing target, or a `data-elevation` other than the effective tier, fails. | `audit:Button/theming` |-| FR13 (painted shadow) | Evidence gap: no test reads the painted shadow, so a grouped Button that paints its own shadow, or swapped tier shadows, would pass | Standalone tiers; grouped member | — | `audit:Button/theming` |-| FR14 (per variant) | Evidence gap: `data-variant` is asserted for `secondary` only | Other variants | — | `audit:Button/theming` |-| FR15 | `Button.test.tsx` touch pressed-state suite | Touch press on and fading | Losing the touch press arm or its release fade fails. | `audit:Button/behavior` |-| FR15 (disabled paint) | `pressFeedback.test.ts` "paints nothing on a disabled surface, and does not light the row around it" for the touch press. Evidence gap: no test of the hover and pressed overlays or the mouse scale on a Button exposed as disabled | Native disabled; `aria-disabled` | A disabled surface that takes the touch press fails. | `audit:Button/behavior` |-| FR15 (reduced motion) | `ReducedMotionPress.a11y.chromium.spec.ts` ("a pressed button never scales under reduced motion, with a mouse or a finger (DR1)") | Mouse press; touch press | A computed transform other than `none` or `scale(1)` during the press. | `audit:Button/behavior` |-| `spec:AST-094` FR42 | `Button.hitArea.test.tsx`: a standalone and a link Button take the touch band on their content wrapper, and a caller's `::after` stays on the button; a disabled, busy-only or grouped Button takes none | standalone; link; caller `::after`; disabled; busy-only; grouped | A Button without the band, or a disabled, busy-only or grouped Button with its own, fails. | `audit:Button/behavior` |-| FR15 (hover and mouse scale) | Evidence gap: no test asserts the hover overlay or the 0.98 mouse-press scale | Hover; mouse press, standalone and grouped | — | `audit:Button/behavior` |-| FR16 | `edgeCompensation.test.tsx` Button data-attribute suite | Ghost and primary | A ghost Button without the marker, or a primary Button with it, fails. | `audit:Button/layout` |-| FR17 | `Button.test.tsx` ref suites and the caller `aria-disabled`/`aria-busy` case | Initial render and rerender; caller `aria-busy` and `aria-disabled` | A dropped or detached ref, or a dropped caller `aria-busy` or `aria-disabled`, fails. Evidence gap: no test asserts that a caller `aria-disabled` leaves the Button operable. | `audit:Button/behavior` |-| ORD1, ORD5 | Evidence gap: no test asserts size precedence (see FR4) or that caller `xstyle`, `className`, and `style` win over Button's own styles | — | — | `audit:Button/behavior` |-| ORD4 | `Button.test.tsx` icon-only and composed-label cases. Evidence gap: no test asserts the `aria-label` set while pending or when `children` differs from `label`, or the content name with icon-slot or end-content text | Icon-only; composed label | An icon-only Button without `aria-label`, or a composed label that gains one, fails. | `audit:Button/accessibility` |-| AR2 | `Button.a11y.chromium.spec.ts` activation and tab-reachability checks. Evidence gap: no test of Enter activation in link mode | Text and icon-only Buttons | A Button that Enter or Space does not activate, or that Tab skips, fails. | `audit:Button/accessibility` |-| AR3 | Evidence gap: no test asserts the focus outline or the destructive error-colored ring | Keyboard focus; destructive | — | `audit:Button/accessibility` |-| AR6, PR1 | Evidence gap: no test measures the target size or asserts that an idle Button schedules nothing | — | — | `audit:Button/behavior` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |+| FR1, FR2, AR1 | `Button.test.tsx` label, children, icon-only, end-content presence, and `type` cases; `Button.a11y.test.tsx`; `Button.a11y.chromium.spec.ts` | Text, icon-only, composed label, end content, submit type | A lost name, a wrong default `type`, or end content in icon-only fails. | `audit:Button/anatomy` |+| FR1, FR2 (gaps) | Evidence gap: no test passes `name`, `value`, or `form`, or asserts the order of icon, label, and end content | — | — | `audit:Button/anatomy` |+| FR3 | Evidence gap: no Button-level test of the text-mode icon slot default | `sm`, `md`, `lg` with an unsized Icon | — | `audit:Button/anatomy` |+| FR4 | `ButtonTextSize.interaction.browser.spec.ts` (a label larger than the element size grows its button; the default size keeps the element size). Evidence gap: no test asserts the explicit `size`, then nearest provider, then `md` order | `sm`, `md`, `lg`; inside a size provider | — | `audit:Button/layout` |+| FR5 | `Button.test.tsx` width and narrow-row suites; InputGroup addon case | Numeric and string width, link mode, icon-only, grouped | A Button that overflows its row, stops truncating, or squeezes icon-only fails. | `audit:Button/layout` |+| FR6, FR7 | `Button.test.tsx` click, double-click, and interruptible suites | onClick then clickAction; preventDefault; double-click; re-click | Order flips, a prevented click runs the action, or a fire-once action runs twice fails. | `audit:Button/behavior` |+| FR8, AR4 | `Button.test.tsx` loading, spinner shade, and live-region suites | `isLoading`; pending `clickAction`; first render loading | Missing `aria-busy`, a wrong Spinner shade, or a live region mounted with text fails. | `audit:Button/behavior` |+| FR8 (hide and delay) | Evidence gap: no test asserts the hidden content, the reveal delay, or the reduced-motion path; the shipped Spinner fade fails the fine-pointer reduced-motion clause (Current-state impact) | `isLoading`; pending `clickAction`; interruptible | Under reduced motion with a fine pointer, a Spinner opacity below 1 after the loading state starts. | `audit:Button/behavior` |+| FR8 (outer size) | Evidence gap: no test measures that a pending Button keeps its outer size | Loading text, icon-only, and end-content Buttons | — | `audit:Button/layout` |+| FR9, FR10, AR5 | `Button.test.tsx` aria-disabled, busy-only, and native-disabled suites; `Button.a11y.chromium.spec.ts` | Busy-only, tooltip-disabled, disabled, disabled and loading | A busy Button loses focus, an inert Button fires, or a click reaches an ancestor fails. Native-disabled assertions match the FR10 gap. | `audit:Button/accessibility` |+| FR11 | `Button.test.tsx` link-mode suites | Link, busy-only link, disabled `href` | A disabled link navigates or a busy link turns into a `<button>` fails. | `audit:Button/behavior` |+| FR12 | `Button.a11y.chromium.spec.ts` described state | Disabled with tooltip | A tooltip that does not describe the Button fails. | `audit:Button/accessibility` |+| FR12 (placement and order) | Evidence gap: no test asserts that the tooltip opens above the Button or that its id follows a caller `aria-describedby` | Tooltip with and without a caller description | — | `audit:Button/accessibility` |+| FR13, FR14 | `Button.test.tsx` theme-target and elevation suites; `ButtonGroup.test.tsx` "reports flat on a member, since the group owns the surface" for the grouped `data-elevation="none"` | `secondary` target attributes; every elevation tier | A missing target, or a `data-elevation` other than the effective tier, fails. | `audit:Button/theming` |+| FR13 (painted shadow) | Evidence gap: no test reads the painted shadow, so a grouped Button that paints its own shadow, or swapped tier shadows, would pass | Standalone tiers; grouped member | — | `audit:Button/theming` |+| FR14 (per variant) | Evidence gap: `data-variant` is asserted for `secondary` only | Other variants | — | `audit:Button/theming` |+| FR15 | `Button.test.tsx` touch pressed-state suite | Touch press on and fading | Losing the touch press arm or its release fade fails. | `audit:Button/behavior` |+| FR15 (disabled paint) | `pressFeedback.test.ts` "paints nothing on a disabled surface, and does not light the row around it" for the touch press. Evidence gap: no test of the hover and pressed overlays or the mouse scale on a Button exposed as disabled | Native disabled; `aria-disabled` | A disabled surface that takes the touch press fails. | `audit:Button/behavior` |+| FR15 (reduced motion) | `ReducedMotionPress.a11y.chromium.spec.ts` ("a pressed button never scales under reduced motion, with a mouse or a finger (DR1)") | Mouse press; touch press | A computed transform other than `none` or `scale(1)` during the press. | `audit:Button/behavior` |+| `spec:AST-094` FR42 | `Button.hitArea.test.tsx`: a standalone and a link Button take the touch band on their content wrapper, and a caller's `::after` stays on the button; a disabled, busy-only or grouped Button, or a Button whose tracking group draws its band, takes none | standalone; link; caller `::after`; disabled; busy-only; grouped; tracking group draws the band | A Button without the band fails. So does a disabled, busy-only or grouped Button with its own, or a Button with its own whose tracking group draws its band. | `audit:Button/behavior` |+| FR15 (hover and mouse scale) | Evidence gap: no test asserts the hover overlay or the 0.98 mouse-press scale | Hover; mouse press, standalone and grouped | — | `audit:Button/behavior` |+| FR16 | `edgeCompensation.test.tsx` Button data-attribute suite | Ghost and primary | A ghost Button without the marker, or a primary Button with it, fails. | `audit:Button/layout` |+| FR17 | `Button.test.tsx` ref suites and the caller `aria-disabled`/`aria-busy` case | Initial render and rerender; caller `aria-busy` and `aria-disabled` | A dropped or detached ref, or a dropped caller `aria-busy` or `aria-disabled`, fails. Evidence gap: no test asserts that a caller `aria-disabled` leaves the Button operable. | `audit:Button/behavior` |+| ORD1, ORD5 | Evidence gap: no test asserts size precedence (see FR4) or that caller `xstyle`, `className`, and `style` win over Button's own styles | — | — | `audit:Button/behavior` |+| ORD4 | `Button.test.tsx` icon-only and composed-label cases. Evidence gap: no test asserts the `aria-label` set while pending or when `children` differs from `label`, or the content name with icon-slot or end-content text | Icon-only; composed label | An icon-only Button without `aria-label`, or a composed label that gains one, fails. | `audit:Button/accessibility` |+| AR2 | `Button.a11y.chromium.spec.ts` activation and tab-reachability checks. Evidence gap: no test of Enter activation in link mode | Text and icon-only Buttons | A Button that Enter or Space does not activate, or that Tab skips, fails. | `audit:Button/accessibility` |+| AR3 | Evidence gap: no test asserts the focus outline or the destructive error-colored ring | Keyboard focus; destructive | — | `audit:Button/accessibility` |+| AR6, PR1 | Evidence gap: no test measures the target size or asserts that an idle Button schedules nothing | — | — | `audit:Button/behavior` |## Current-state impactdiff --git a/docs/specs/components/ToggleButton/ToggleButtonGroup.spec.md b/docs/specs/components/ToggleButton/ToggleButtonGroup.spec.mdindex 2268c88d06..6037570b10 100644--- a/docs/specs/components/ToggleButton/ToggleButtonGroup.spec.md+++ b/docs/specs/components/ToggleButton/ToggleButtonGroup.spec.md@@ -13,6 +13,8 @@ review_triggers: [public-api, behavior, layout, accessibility]verified_by:[packages/core/src/ToggleButton/ToggleButton.test.tsx,+ packages/core/src/ToggleButton/ToggleButtonGroupTracking.test.tsx,+ packages/core/src/ToggleButton/__tests__/ToggleButtonGroupTracking.interaction.browser.spec.ts,packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.test.tsx,packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.chromium.spec.ts,packages/core/src/Layer/layerScopedContext.test.tsx,@@ -35,9 +37,9 @@ system_specs: [spec:AST-085, spec:AST-038]| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || Public contract | None changes. ToggleButtonGroup takes `label`, `type` (`single` or `multiple`), a controlled `value` and `onChange`, `orientation`, `size`, `isDisabled`, `xstyle`, and `data-testid`. || Behavior | A labelled `role="group"` of separate ToggleButtons. Valued members show the group's selection and ask the group to toggle; the group reports the next selection through `onChange`. |-| End-user impact | People pick one or several options with plain toggle buttons. Each member is its own Tab stop. A disabled group's members leave the tab order. |+| End-user impact | People pick one or several options; a touch press can slide across, and only the lifted toggle toggles. Each member is its own Tab stop. A disabled group's members leave the tab order. || Builder impact | None. |-| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. Disabled members use native `disabled` without a tooltip, against `spec:AST-085` FR1 and FR7; listed under Current-state impact. |+| Compatibility/readiness | No API or default change; its DOM change is listed below. Disabled members use native `disabled` without a tooltip, against `spec:AST-085` FR1 and FR7; listed under Current-state impact. || Review checks | Reject a group without a name, a member whose pressed state disagrees with `value`, a member Action started by group activation, a wrapper shadow, or connected surfaces. || Governing rules | `family:buttons` FR8, FR11, FR12, AV5; `spec:AST-085` FR1, FR7. |@@ -51,10 +53,15 @@ assigns. Consumer usage lives in `ToggleButtonGroup.doc.mjs`.## Compatibility and migration-- Released default preserved: `yes`; `type="single"`,+- Released default preserved: `yes` for a mouse; under the touch+ presentation a press gains the slide across the toggles; `type="single"`,`orientation="horizontal"`, `isDisabled={false}`-- Compatibility class: records shipped behavior; no public prop, default,- export, or DOM change+- Compatibility class: no public prop, default, or export change; under the+ touch presentation the DOM gains the action-group item marker on each+ tracked toggle, the gesture host's `data-astryx-touch-action` marker on the+ group root and the hit layer's inset properties, and an enabled group's root+ is also `position: relative`, so absolutely positioned descendants resolve+ against it there- Controlled/uncontrolled behavior: controlled only; the group holds noselection of its own- Migration decision: none@@ -70,11 +77,16 @@ Consumer migration instructions belong in consumer docs and release notes.- Selection: which valued members are pressed, and the next selection a memberactivation requests.- The default size and disabled state valued and unvalued members read.+- The press across members while it tracks a held pointer+ (`family:action-groups`): the press painted on the member under the+ pointer, the lift that runs only that member's click, and the hit layer that+ grows the members' touch targets toward 44 px.**Does not own / non-goals**-- Each member's surface, `aria-pressed`, paint, and disabled rendering — owned- by `component:ToggleButton` and `component:Button`.+- Each member's surface, `aria-pressed`, hover and selected paint, and+ disabled rendering — owned by `component:ToggleButton` and+ `component:Button`.- Connected geometry and a shared elevation — not provided; members areseparate surfaces (`family:buttons` FR12).- Roving focus — not provided; each member is a Tab stop (`family:buttons`@@ -130,9 +142,26 @@ Consumer migration instructions belong in consumer docs and release notes.### Performance and resources-- **PR1 — Group listeners only for press tracking.** The group adds no- observer or measurement, and no event listener beyond the press tracking- `family:action-groups` FR5 gives it.+- **PR1 — Layout reads and listeners only for press tracking.** Every group, a+ disabled one too, reads the touch presentation through+ `useTouchPresentation`, which listens to two media queries. Only an enabled+ group under the touch presentation tracks presses and watches its hit area.+ Any other group reads no box. When a press begins, the tracker reads the+ group's box once. It reads each enabled toggle's box three times for a+ finger, which picks the nearest target, and twice for a pen. A finger's+ press also reads each disabled toggle's box once. It also reads, once, the+ box of each member the group does not track, such as a toggle without a+ value. A finger's press on the group's own box or hit layer first reads each+ member's box once more. The group takes it only where a toggle's target+ holds it. A press reads no box outside the group. Nothing is read per move+ or at the lift. The hit-area watch (`utils/hitArea.ts`) reads the enabled+ tracked toggles' boxes when the group's layout changes, not at a press. It+ listens to the `(pointer: coarse)` query once per page. It sizes each side+ of the hit layer as far as the toggles on that edge grow, against the page's+ interactive elements. It ends at the outer toggles' targets, even where the+ group's box reaches past them. The layer exists while the group tracks+ presses; with no growth it covers nothing. The group adds no other observer+ or listener beyond the press tracking `family:action-groups` FR5 gives it.## Accessibility contract@@ -164,18 +193,19 @@ No design record governs ToggleButtonGroup. Its root carries the## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |-| FR1, AR1 | `ToggleButton.test.tsx` group role and label cases | Single and multiple | A missing name or role fails. Evidence gap: no test asserts the root target, `data-testid`, or `xstyle`. | `audit:ToggleButtonGroup/accessibility` |-| FR3–FR5, ORD1 | `ToggleButton.test.tsx` single and multiple suites | Select, switch, deselect, add, remove | A wrong pressed member or a wrong `onChange` payload fails. | `audit:ToggleButtonGroup/behavior` |-| FR6 | `ToggleButton.test.tsx` group-ownership cases | Members with standalone handlers and `onClick` | A member Action runs, or pressed state moves before `value`, fails. | `audit:ToggleButtonGroup/behavior` |-| FR7, ORD3, AR3 | `ToggleButton.test.tsx` disabled suite; `ToggleButton.a11y.test.tsx` | Member disabled; group disabled; tooltip-bearing member | A disabled member that toggles, or a re-enabled member, fails. The shared disabled states expect native `disabled`, matching the FR7 gap. | `audit:ToggleButtonGroup/accessibility` |-| FR2 | `ToggleButton.test.tsx` grouped elevation case | Member with its own elevation | A member losing its elevation inside the group fails. Evidence gap: no test asserts the spacing or the unpainted wrapper. Evidence gap: no test reads a member's painted shadow. | `audit:ToggleButtonGroup/layout` |-| FR9 (selection) | `layerScopedContext.test.tsx` "ends ancestor selection and callbacks while honoring explicit toggle props" | Member inside a fixed Layer and an inline Dialog | A member inside a layer that follows the outer group's selection or callbacks fails. | `audit:ToggleButtonGroup/behavior` |-| FR8, FR9 (size and disabled) | Evidence gap: no test of member Tab order, or of size and disabled scoping at a layer | — | — | `audit:ToggleButtonGroup/accessibility` |-| FR7 (size), ORD2, PR1 | Evidence gap: no test asserts the group size default, member size precedence, or that the group adds no listeners beyond the press tracking `family:action-groups` FR5 gives it | — | — | `audit:ToggleButtonGroup/behavior` |-| AR2 | `ToggleButton.a11y.test.tsx` and `ToggleButton.a11y.chromium.spec.ts` operable and focusable facts for the single- and multiple-group states | Group members | A group member that is not operable or that Tab does not reach fails. | `audit:ToggleButtonGroup/accessibility` |-| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on `ToggleButton / Group single` | Two adjacent toggle buttons; LTR and RTL | An earlier button that is not at the inline start of the next fails D2. | `audit:ToggleButtonGroup/i18n-rtl` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |+| FR1, AR1 | `ToggleButton.test.tsx` group role and label cases | Single and multiple | A missing name or role fails. Evidence gap: no test asserts the root target, `data-testid`, or `xstyle`. | `audit:ToggleButtonGroup/accessibility` |+| FR3–FR5, ORD1 | `ToggleButton.test.tsx` single and multiple suites | Select, switch, deselect, add, remove | A wrong pressed member or a wrong `onChange` payload fails. | `audit:ToggleButtonGroup/behavior` |+| FR6 | `ToggleButton.test.tsx` group-ownership cases | Members with standalone handlers and `onClick` | A member Action runs, or pressed state moves before `value`, fails. | `audit:ToggleButtonGroup/behavior` |+| FR7, ORD3, AR3 | `ToggleButton.test.tsx` disabled suite; `ToggleButton.a11y.test.tsx` | Member disabled; group disabled; tooltip-bearing member | A disabled member that toggles, or a re-enabled member, fails. The shared disabled states expect native `disabled`, matching the FR7 gap. | `audit:ToggleButtonGroup/accessibility` |+| FR2 | `ToggleButton.test.tsx` grouped elevation case | Member with its own elevation | A member losing its elevation inside the group fails. Evidence gap: no test asserts the spacing or the unpainted wrapper. Evidence gap: no test reads a member's painted shadow. | `audit:ToggleButtonGroup/layout` |+| FR9 (selection) | `layerScopedContext.test.tsx` "ends ancestor selection and callbacks while honoring explicit toggle props" | Member inside a fixed Layer and an inline Dialog | A member inside a layer that follows the outer group's selection or callbacks fails. | `audit:ToggleButtonGroup/behavior` |+| FR8, FR9 (size and disabled) | Evidence gap: no test of member Tab order, or of size and disabled scoping at a layer | — | — | `audit:ToggleButtonGroup/accessibility` |+| FR7 (size), ORD2 | Evidence gap: no test asserts the group size default or member size precedence | — | — | `audit:ToggleButtonGroup/behavior` |+| PR1 | `ToggleButtonGroupTracking.test.tsx` "marks each toggle as a tracked action, and marks none while the group is disabled", the once-per-press case and the count case "reads each box a fixed number of times as a press begins (PR1)", and the band case "draws each tracked toggle's touch band on the group's hit layer: a tracked toggle draws none of its own, and a toggle without a value keeps its own"; `ToggleButtonGroupTracking.interaction.browser.spec.ts` 44 px target case | Group tracking under a finger and a pen; group disabled; a toggle without a value | A disabled group that tracks, a toggle whose target does not reach 44 px under a finger, another number of reads as a press begins, a box read per move, or a tracked toggle with a touch band of its own fails. Evidence gap: no test counts the touch presentation's listeners. | `audit:ToggleButtonGroup/behavior` |+| AR2 | `ToggleButton.a11y.test.tsx` and `ToggleButton.a11y.chromium.spec.ts` operable and focusable facts for the single- and multiple-group states | Group members | A group member that is not operable or that Tab does not reach fails. | `audit:ToggleButtonGroup/accessibility` |+| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on `ToggleButton / Group single` | Two adjacent toggle buttons; LTR and RTL | An earlier button that is not at the inline start of the next fails D2. | `audit:ToggleButtonGroup/i18n-rtl` |## Current-state impactdiff --git a/packages/core/src/Button/Button.hitArea.test.tsx b/packages/core/src/Button/Button.hitArea.test.tsxindex 1aac569db2..c865939e73 100644--- a/packages/core/src/Button/Button.hitArea.test.tsx+++ b/packages/core/src/Button/Button.hitArea.test.tsx@@ -3,9 +3,10 @@/*** @file Button.hitArea.test.tsx* @input Button, ButtonGroup, and the shared hit area (mocked)- * @output Unit coverage that a standalone Button takes the shared touch band,- * on its content wrapper, which leaves a caller's ::after alone, and that a- * grouped, disabled or busy-only Button takes none+ * @output Unit coverage that a standalone Button takes the shared touch band+ * on its content wrapper, which leaves a caller's ::after alone. A grouped+ * Button takes none: a ButtonGroup's, or one whose tracking group draws its+ * band. A disabled or busy-only Button takes none either.* @position Button's FR42 touch-target evidence beside Button.test.tsx*/@@ -16,6 +17,7 @@ import type * as HitAreaModule from '../utils/hitArea';import type {HitInsets} from '../utils/hitArea';import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';import {ButtonGroup} from '../ButtonGroup/ButtonGroup';+import {PressGroupBandContext} from '../hooks/pressGroupContext';import {Button} from './Button';// On a coarse pointer, the shared hit area measures neighbours in a real@@ -130,4 +132,15 @@ describe('Button touch target (AST-094 FR42)', () => {expect(isWatched(cut)).toBe(false);expect(bandElementOf(cut)).toBeUndefined();});++ it('leaves a button to a tracking group that draws its band: it draws none of its own', () => {+ render(+ <PressGroupBandContext value>+ <Button label="Bold" />+ </PressGroupBandContext>,+ );+ const bold = screen.getByRole('button', {name: 'Bold'});+ expect(isWatched(bold)).toBe(false);+ expect(bandElementOf(bold)).toBeUndefined();+ });});diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsxindex 41809f63b4..ec82bfb96e 100644--- a/packages/core/src/Button/Button.tsx+++ b/packages/core/src/Button/Button.tsx@@ -54,6 +54,7 @@ import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';import {useSize} from '../SizeContext/SizeContext';import {useButtonGroup} from '../ButtonGroup/ButtonGroupContext';import {+ PressGroupBandContext,PressGroupContext,pressGroupItemProps,} from '../hooks/pressGroupContext';@@ -755,9 +756,10 @@ export function Button({const isBusyOnlyDisabled =!isTrueDisabled && isLoadingState && !isInterruptible;const buttonDisabled = isTrueDisabled || isBusyOnlyDisabled;- // The group draws one band for all its members.- // A disabled or busy-only button takes no tap.- const hasHitArea = buttonGroup == null && !buttonDisabled;+ // The group draws one band for all its members: a ButtonGroup, or a+ // tracking group that says so. A disabled or busy-only button takes no tap.+ const groupDrawsBand = use(PressGroupBandContext);+ const hasHitArea = buttonGroup == null && !groupDrawsBand && !buttonDisabled;const hitAreaRef = useTouchHitArea(hasHitArea, use(ButtonHitAreaContext));// isIconOnly prop is the source of truth for icon-only rendering.// When false (default), label is always rendered as visible text.diff --git a/packages/core/src/ToggleButton/ToggleButton.tsx b/packages/core/src/ToggleButton/ToggleButton.tsxindex e7109fc089..fee9b42898 100644--- a/packages/core/src/ToggleButton/ToggleButton.tsx+++ b/packages/core/src/ToggleButton/ToggleButton.tsx@@ -21,11 +21,16 @@* - /packages/cli/assets/templates/blocks/components/ToggleButton/ (showcase blocks)*/-import React, {useOptimistic, type ReactNode} from 'react';+import React, {use, useOptimistic, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars, fontWeightVars} from '../theme/tokens.stylex';import {Button, type ButtonSize} from '../Button';+import {+ PressGroupBandContext,+ PressGroupContext,+} from '../hooks/pressGroupContext';+import {GROUP_PRESS_POINTERS} from '../hooks/useGroupPressTracking';import type {Elevation} from '../utils/types';import {useToggleButtonGroup} from './ToggleButtonGroup';import type {BaseProps} from '../BaseProps';@@ -342,40 +347,57 @@ export function ToggleButton({</span>) : undefined;+ // In a group, the group tracks only a toggle with a value. A toggle without+ // one keeps its own press. Outside a group, the toggle follows its parent.+ const parentPointers = use(PressGroupContext);+ const groupPointers =+ group == null+ ? parentPointers+ : group.tracksPress === true && value != null+ ? GROUP_PRESS_POINTERS+ : null;++ // The group's hit layer is the touch band of each toggle it tracks.+ const isInGroupBand = group != null && groupPointers != null;+return (- <Button- ref={ref}- label={label}- variant="ghost"- size={size}- elevation={elevation}- isDisabled={isDisabled}- isLoading={isLoading}- isInterruptible- isIconOnly={isIconOnly}- icon={resolvedIcon}- tooltip={tooltip}- {...mergeProps(- themeProps('toggle-button', {- isPressed: isPressed ? 'true' : 'false',- elevation,- }),- className,- )}- xstyle={[isPressed ? pressedStyles.background : undefined, xstyle]}- style={style}- onClick={handleClick}- clickAction={clickAction}- {...props}- // The pressed state this component owns wins over a caller's- // same-named attributes (public-component-api INV5).- aria-pressed={isPressed}- {...themeDataAttributes({- isPressed: isPressed ? 'true' : 'false',- elevation,- })}>- {labelContent}- </Button>+ <PressGroupContext value={groupPointers}>+ <PressGroupBandContext value={isInGroupBand}>+ <Button+ ref={ref}+ label={label}+ variant="ghost"+ size={size}+ elevation={elevation}+ isDisabled={isDisabled}+ isLoading={isLoading}+ isInterruptible+ isIconOnly={isIconOnly}+ icon={resolvedIcon}+ tooltip={tooltip}+ {...mergeProps(+ themeProps('toggle-button', {+ isPressed: isPressed ? 'true' : 'false',+ elevation,+ }),+ className,+ )}+ xstyle={[isPressed ? pressedStyles.background : undefined, xstyle]}+ style={style}+ onClick={handleClick}+ clickAction={clickAction}+ {...props}+ // The pressed state this component owns wins over a caller's+ // same-named attributes (public-component-api INV5).+ aria-pressed={isPressed}+ {...themeDataAttributes({+ isPressed: isPressed ? 'true' : 'false',+ elevation,+ })}>+ {labelContent}+ </Button>+ </PressGroupBandContext>+ </PressGroupContext>);}diff --git a/packages/core/src/ToggleButton/ToggleButtonGroup.doc.mjs b/packages/core/src/ToggleButton/ToggleButtonGroup.doc.mjsindex d2c754d0d7..6081229025 100644--- a/packages/core/src/ToggleButton/ToggleButtonGroup.doc.mjs+++ b/packages/core/src/ToggleButton/ToggleButtonGroup.doc.mjs@@ -10,7 +10,7 @@ export const docs = {'togglegroup','buttontogglegroup',],- description: 'Groups toggle buttons for exclusive (single) or multi-select behavior. Uses discriminated union on type for type-safe value/onChange.',+ description: 'Groups toggle buttons for exclusive (single) or multi-select behavior. Uses discriminated union on type for type-safe value/onChange. Under the touch presentation a press tracks like a menu: press a toggle and slide across the others, and the highlight follows. Only the toggle you lift on toggles, and lifting outside the group toggles nothing. With a finger, each toggle\'s target grows toward 44 px, up to half the gap to a neighbour, without the toggles growing.',props: [{name: 'children',@@ -85,7 +85,7 @@ export const docs = {export const docsZh = {name: 'ToggleButtonGroup',displayName: 'Toggle Button Group',- description: '将切换按钮分组,支持单选或多选行为。通过 type 判别联合类型实现类型安全。',+ description: '将切换按钮分组,支持单选或多选行为。通过 type 判别联合类型实现类型安全。在触摸呈现下(主要指针为粗指针时),按下时分组像菜单一样跟踪按压:按下一个切换按钮并滑过其他按钮,高亮随之移动。只有松开时所在的按钮会切换,在分组外松开则不切换任何按钮。使用手指时,每个按钮的触控目标向 44 px 扩展,最多到与相邻按钮间距的一半,按钮本身不变大。',propDescriptions: {children: 'ToggleButton 子元素;每个成员都需要 value。分组控制按下状态,并忽略成员的 isPressed、onPressedChange 和 pressedChangeAction。激活成员只调用分组的 onChange,不启动成员的 Action 过渡。',label: '分组的无障碍标签 (aria-label)。',@@ -103,7 +103,7 @@ export const docsZh = {export const docsDense = {name: 'ToggleButtonGroup',displayName: 'Toggle Button Group',- description: 'groups toggle btns for exclusive/multi-select; discriminated union on type',+ description: 'groups toggle btns for exclusive/multi-select; discriminated union on type; on touch a press slides across toggles like a menu and only the one lifted on toggles; a mouse press stays native; finger targets grow toward 44 px, up to half the gap to a neighbour',propDescriptions: {children: 'ToggleButton children; each member needs a value. Group owns pressed state; member isPressed/onPressedChange/pressedChangeAction are ignored. Selection uses group onChange, with no member Action transition.',label: 'a11y label (aria-label)',diff --git a/packages/core/src/ToggleButton/ToggleButtonGroup.tsx b/packages/core/src/ToggleButton/ToggleButtonGroup.tsxindex a0518bd8e7..3965de7193 100644--- a/packages/core/src/ToggleButton/ToggleButtonGroup.tsx+++ b/packages/core/src/ToggleButton/ToggleButtonGroup.tsx@@ -4,7 +4,8 @@/*** @file ToggleButtonGroup.tsx- * @input Layer-scoped React context, ToggleButton children+ * @input Layer-scoped React context, ToggleButton children, and the shared+ * group press tracking (hooks/useGroupPressTracking)* @output Exports ToggleButtonGroup component and types* @position Groups toggle buttons for single or multi-select behavior*@@ -18,12 +19,24 @@* - /packages/cli/assets/templates/blocks/components/ToggleButton/ (showcase blocks)*/-import {useCallback, use, useMemo, type ReactNode} from 'react';+import {+ useCallback,+ use,+ useMemo,+ useRef,+ type ReactNode,+ type Ref,+} from 'react';import {createLayerScopedContext} from '../Layer/layerScopedContext';import * as stylex from '@stylexjs/stylex';import {spacingVars} from '../theme/tokens.stylex';import type {ButtonSize} from '../Button';import type {BaseProps} from '../BaseProps';+import {PressGroupContext} from '../hooks/pressGroupContext';+import {useTouchPresentation} from '../utils/touchPresentation';+import {useGroupPressTracking} from '../hooks/useGroupPressTracking';+import {useMergedRefs} from '../hooks/useMergedRefs';+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';import {mergeProps} from '../utils';import type {StyleXStyles} from '@stylexjs/stylex';import {themeProps} from '../utils/themeProps';@@ -41,6 +54,8 @@ interface ToggleButtonGroupContextValue {size?: ButtonSize;/** Group disabled state. */isDisabled?: boolean;+ /** The group tracks a press across its toggles that have a value. */+ tracksPress?: boolean;}const ToggleButtonGroupContext =@@ -73,6 +88,11 @@ const styles = stylex.create({flexDirection: 'column',alignItems: 'stretch',},+ // While the group tracks presses, its hit layer is the root's `::before`,+ // below its toggles, so the root is the layer's containing block.+ tracking: {+ position: 'relative',+ },});// =============================================================================@@ -237,15 +257,28 @@ export function ToggleButtonGroup(props: ToggleButtonGroupProps): ReactNode {[isMultiple, props.value, props.onChange],);+ // Only under the touch presentation does a press slide across the toggles.+ // A desktop press stays the native toggle's.+ const {isTouch} = useTouchPresentation();+ const tracksPress = !isDisabled && isTouch;const contextValue = useMemo(- () => ({selectedValues, toggle, size, isDisabled}),- [selectedValues, toggle, size, isDisabled],+ () => ({selectedValues, toggle, size, isDisabled, tracksPress}),+ [selectedValues, toggle, size, isDisabled, tracksPress],);+ const groupRef = useRef<HTMLDivElement>(null);+ const {hitAreaRef} = useGroupPressTracking(groupRef, tracksPress);+ // A caller's `ref` reaches the root, like the other host props. The+ // group's own refs join it.+ const callerRef = (+ props as ToggleButtonGroupProps & {ref?: Ref<HTMLDivElement>}+ ).ref;+ const mergedRef = useMergedRefs(callerRef, groupRef, hitAreaRef);return (<ToggleButtonGroupContext value={contextValue}><div{...hostProps}+ ref={mergedRef}role="group"aria-label={label}data-testid={testId}@@ -253,13 +286,17 @@ export function ToggleButtonGroup(props: ToggleButtonGroupProps): ReactNode {themeProps('toggle-button-group'),stylex.props(styles.group,+ tracksPress && styles.tracking,+ tracksPress && touchHitAreaStyles.layerBelowChildren,orientation === 'vertical' && styles.vertical,xstyle,),className,style,)}>- {children}+ {/* Only a ToggleButton with a value joins the tracking (ToggleButton+ reads the group). Any other child keeps its own press. */}+ <PressGroupContext value={null}>{children}</PressGroupContext></div></ToggleButtonGroupContext>);diff --git a/packages/core/src/ToggleButton/ToggleButtonGroupTracking.test.tsx b/packages/core/src/ToggleButton/ToggleButtonGroupTracking.test.tsxnew file mode 100644index 0000000000..45aa5f0607--- /dev/null+++ b/packages/core/src/ToggleButton/ToggleButtonGroupTracking.test.tsx@@ -0,0 +1,659 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ToggleButtonGroupTracking.test.tsx+ * @input ToggleButtonGroup and ToggleButton, driven by synthetic touch, pen and+ * mouse streams under a coarse or a fine primary pointer+ * @output Unit evidence that a toggle group tracks a held pointer across its+ * toggles as one action group (`family:action-groups` FR1–FR5). It toggles+ * only the one lifted on.+ * @position Beside the ToggleButtonGroup tests; the real-browser evidence is+ * __tests__/ToggleButtonGroupTracking.interaction.browser.spec.ts+ */++import * as stylex from '@stylexjs/stylex';+import {createRef, type Ref} from 'react';+import {act, render} from '@testing-library/react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {+ coarsePrimaryPointer,+ pointerQuery,+} from '../gestures/__tests__/pointerQuery';+import {isPressGroupItem} from '../privateAttributes/pressGroupItem.stylex';+import {touchHitAreaStyles} from '../internal/touchHitArea.stylex';+import {Button} from '../Button/Button';+import {ToggleButton} from './ToggleButton';+import {ToggleButtonGroup} from './ToggleButtonGroup';++interface Point {+ x: number;+ y: number;+}++let time = 1000;+let nextTouchId = 1;++/** Dispatch one touch event for a single finger. */+function touch(+ type: 'touchstart' | 'touchmove' | 'touchend' | 'touchcancel',+ target: EventTarget,+ id: number,+ point: Point,+): void {+ time += 16;+ const event = new Event(type, {bubbles: true, cancelable: true});+ const entry = {identifier: id, clientX: point.x, clientY: point.y, target};+ const isLift = type === 'touchend' || type === 'touchcancel';+ Object.defineProperty(event, 'changedTouches', {value: [entry]});+ Object.defineProperty(event, 'touches', {value: isLift ? [] : [entry]});+ Object.defineProperty(event, 'timeStamp', {value: time});+ target.dispatchEvent(event);+}++/** A finger, with a fresh id. */+function finger() {+ const id = nextTouchId++;+ return {+ down: (target: Element, point: Point) => {+ time += 1000;+ touch('touchstart', target, id, point);+ },+ move: (target: Element, point: Point) =>+ touch('touchmove', target, id, point),+ up: (target: Element, point: Point) => touch('touchend', target, id, point),+ };+}++/** Dispatch a pointer event of one kind (a finger, a pen or a mouse). */+function pointer(+ kind: 'touch' | 'pen' | 'mouse',+ type: 'pointerdown' | 'pointermove' | 'pointerup',+ target: Element,+ point: Point,+): void {+ time += 16;+ const event = new PointerEvent(type, {+ bubbles: true,+ cancelable: true,+ pointerId: {touch: 7, pen: 41, mouse: 1}[kind],+ pointerType: kind,+ isPrimary: true,+ button: 0,+ buttons: type === 'pointerup' ? 0 : 1,+ clientX: point.x,+ clientY: point.y,+ });+ Object.defineProperty(event, 'timeStamp', {value: time});+ target.dispatchEvent(event);+}++/** Stub an element's layout box (jsdom lays nothing out). */+function place(+ element: Element,+ box: {left: number; top: number; width: number; height: number},+): void {+ const rect = DOMRect.fromRect({+ x: box.left,+ y: box.top,+ width: box.width,+ height: box.height,+ });+ element.getBoundingClientRect = () => rect;+}++// Three connected 32 px buttons, the way a small horizontal group lays out.+const A = {left: 0, top: 100, width: 80, height: 32};+const B = {left: 80, top: 100, width: 80, height: 32};+const C = {left: 160, top: 100, width: 80, height: 32};+const GROUP = {left: 0, top: 100, width: 240, height: 32};+const centerOf = (box: typeof A): Point => ({+ x: box.left + box.width / 2,+ y: box.top + box.height / 2,+});++const paintOf = (element: Element) => element.getAttribute('data-astryx-press');++function mount({+ type = 'multiple',+ isDisabled = false,+ ref,+}: {+ type?: 'single' | 'multiple';+ isDisabled?: boolean;+ ref?: Ref<HTMLDivElement>;+} = {}) {+ // The group's props do not declare `ref`; a caller passes it at run time.+ const callerRef: object = ref == null ? {} : {ref};+ const onChange = vi.fn();+ const view = render(+ type === 'single' ? (+ <ToggleButtonGroup+ type="single"+ label="Alignment"+ value={null}+ onChange={onChange}+ isDisabled={isDisabled}+ data-testid="group">+ <ToggleButton label="Left" value="left" data-testid="a" />+ <ToggleButton label="Center" value="center" data-testid="b" />+ <ToggleButton label="Right" value="right" data-testid="c" />+ </ToggleButtonGroup>+ ) : (+ <ToggleButtonGroup+ type="multiple"+ label="Formatting"+ value={[]}+ onChange={onChange}+ isDisabled={isDisabled}+ data-testid="group"+ {...callerRef}>+ <ToggleButton label="Bold" value="bold" data-testid="a" />+ <ToggleButton label="Italic" value="italic" data-testid="b" />+ <ToggleButton label="Underline" value="underline" data-testid="c" />+ </ToggleButtonGroup>+ ),+ );+ const group = view.getByTestId('group');+ const a = view.getByTestId('a');+ const b = view.getByTestId('b');+ const c = view.getByTestId('c');+ place(group, GROUP);+ place(a, A);+ place(b, B);+ place(c, C);+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ return {...view, group, a, b, c, onChange};+}++let restorePointer: () => void = () => {};++beforeEach(() => {+ vi.useFakeTimers();+ restorePointer = coarsePrimaryPointer();+});++afterEach(() => {+ vi.runOnlyPendingTimers();+ vi.useRealTimers();+ restorePointer();+});++function finePrimaryPointer(): void {+ restorePointer();+ restorePointer = pointerQuery(false).restore;+}++describe('ToggleButtonGroup tracks a held pointer across its toggles (family:action-groups)', () => {+ it('marks each toggle as a tracked action, and marks none while the group is disabled', () => {+ const {a, b, c, unmount} = mount();+ for (const toggle of [a, b, c]) {+ expect(isPressGroupItem(toggle)).toBe(true);+ }+ unmount();+ const disabled = mount({isDisabled: true});+ for (const toggle of [disabled.a, disabled.b, disabled.c]) {+ expect(isPressGroupItem(toggle)).toBe(false);+ }+ });++ it("draws each tracked toggle's touch band on the group's hit layer: a tracked toggle draws none of its own, and a toggle without a value keeps its own", () => {+ const band = (stylex.props(touchHitAreaStyles.layer).className ?? '')+ .split(' ')+ .filter(Boolean);+ expect(band.length).toBeGreaterThan(0);+ const hasOwnBand = (toggle: Element) =>+ [...toggle.querySelectorAll('*')].some(element =>+ band.every(name => element.classList.contains(name)),+ );+ const view = render(+ <ToggleButtonGroup+ type="multiple"+ label="Formatting"+ value={[]}+ onChange={vi.fn()}+ data-testid="group">+ <ToggleButton label="Bold" value="bold" data-testid="bold" />+ <ToggleButton label="Italic" value="italic" data-testid="italic" />+ <ToggleButton+ label="Wrap"+ isPressed={false}+ onPressedChange={vi.fn()}+ data-testid="wrap"+ />+ </ToggleButtonGroup>,+ );+ expect(hasOwnBand(view.getByTestId('bold'))).toBe(false);+ expect(hasOwnBand(view.getByTestId('italic'))).toBe(false);+ expect(hasOwnBand(view.getByTestId('wrap'))).toBe(true);+ });++ it('gives the root its hit layer only under a coarse primary pointer, so a desktop root keeps its stacking', () => {+ const layer = (+ stylex.props(touchHitAreaStyles.layerBelowChildren).className ?? ''+ )+ .split(' ')+ .filter(Boolean);+ expect(layer.length).toBeGreaterThan(0);+ const coarse = mount();+ expect(layer.filter(name => coarse.group.classList.contains(name))).toEqual(+ layer,+ );+ coarse.unmount();+ finePrimaryPointer();+ const fine = mount();+ expect(layer.filter(name => fine.group.classList.contains(name))).toEqual(+ [],+ );+ });++ it('a finger slid from Bold across Italic to Underline toggles only Underline (FR4)', () => {+ const {a, b, c, onChange} = mount();+ const f = finger();+ f.down(a, centerOf(A));+ f.move(a, centerOf(B));+ expect(paintOf(b)).toBe('on');+ f.move(a, centerOf(C));+ expect(paintOf(c)).toBe('on');+ f.up(a, centerOf(C));+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenLastCalledWith(['underline']);+ });++ it('in a single-select group, the lifted toggle is the one selected (FR1, FR4)', () => {+ const {a, onChange} = mount({type: 'single'});+ const f = finger();+ f.down(a, centerOf(A));+ f.move(a, centerOf(B));+ f.up(a, centerOf(B));+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenLastCalledWith('center');+ });++ it('a lift outside the group toggles nothing (FR3)', () => {+ const {a, onChange} = mount();+ const f = finger();+ f.down(a, centerOf(A));+ f.move(a, {x: 120, y: 260});+ f.up(a, {x: 120, y: 260});+ expect(onChange).not.toHaveBeenCalled();+ });++ it('tracks a pen like a finger: a pen slid from Bold to Underline lights Underline and toggles it once (FR5)', () => {+ const {a, c, onChange} = mount();+ pointer('pen', 'pointerdown', a, centerOf(A));+ expect(paintOf(a)).toBe('on');+ pointer('pen', 'pointermove', a, centerOf(C));+ expect(paintOf(c)).toBe('on');+ expect(paintOf(a)).toBeNull();+ pointer('pen', 'pointerup', c, centerOf(C));+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenLastCalledWith(['underline']);+ });++ for (const primary of ['fine', 'coarse'] as const) {+ it(`leaves a mouse press to the native toggle under a ${primary} primary pointer: a press slid from Bold to Underline toggles nothing (family:action-groups FR1)`, () => {+ if (primary === 'fine') {+ finePrimaryPointer();+ }+ const {group, a, c, onChange} = mount();+ // A desktop group tracks nothing at all.+ expect(isPressGroupItem(a)).toBe(primary === 'coarse');+ pointer('mouse', 'pointerdown', a, centerOf(A));+ pointer('mouse', 'pointermove', a, centerOf(C));+ pointer('mouse', 'pointerup', c, centerOf(C));+ // The browser's own click for that press lands on the toggles' common+ // parent, where the press began and ended apart.+ group.dispatchEvent(+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 1}),+ );+ expect(onChange).not.toHaveBeenCalled();+ });+ }++ it('leaves a member that is not a toggle untracked: a slide from Bold lifted on it runs nothing, and its own tap runs its click', () => {+ const onMore = vi.fn();+ const onChange = vi.fn();+ const view = render(+ <ToggleButtonGroup+ type="multiple"+ label="Formatting"+ value={[]}+ onChange={onChange}+ data-testid="group">+ <ToggleButton label="Bold" value="bold" data-testid="a" />+ <Button label="More" onClick={onMore} data-testid="more" />+ </ToggleButtonGroup>,+ );+ const group = view.getByTestId('group');+ const more = view.getByTestId('more');+ place(group, {left: 0, top: 100, width: 160, height: 32});+ place(view.getByTestId('a'), A);+ place(more, B);+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ expect(isPressGroupItem(more)).toBe(false);+ const slide = finger();+ slide.down(view.getByTestId('a'), centerOf(A));+ slide.move(view.getByTestId('a'), centerOf(B));+ slide.up(view.getByTestId('a'), centerOf(B));+ expect(onMore).not.toHaveBeenCalled();+ expect(onChange).not.toHaveBeenCalled();+ // The guard for the slide's own click lapses before the next tap.+ act(() => {+ vi.advanceTimersByTime(1000);+ });+ const tap = finger();+ tap.down(more, centerOf(B));+ tap.up(more, centerOf(B));+ more.dispatchEvent(+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 1}),+ );+ expect(onMore).toHaveBeenCalledTimes(1);+ expect(onChange).not.toHaveBeenCalled();+ });++ it("a finger slid from Bold that lifts just inside a toggle without a value toggles nothing: Bold's target does not reach into the other's own (spec:AST-094 FR42)", () => {+ const onChange = vi.fn();+ const view = render(+ <ToggleButtonGroup+ type="multiple"+ label="Formatting"+ value={[]}+ onChange={onChange}+ data-testid="group">+ <ToggleButton label="Bold" value="bold" data-testid="a" />+ <ToggleButton label="Wrap" isPressed={false} data-testid="wrap" />+ </ToggleButtonGroup>,+ );+ const bold = view.getByTestId('a');+ const wrap = view.getByTestId('wrap');+ // Two 32 px toggles 4 px apart: grown toward 44 px, Bold's target would+ // reach 2 px into Wrap, which the group does not track.+ place(view.getByTestId('group'), {+ left: 0,+ top: 100,+ width: 68,+ height: 32,+ });+ place(bold, {left: 0, top: 100, width: 32, height: 32});+ place(wrap, {left: 36, top: 100, width: 32, height: 32});+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ const f = finger();+ f.down(bold, {x: 16, y: 116});+ expect(paintOf(bold)).toBe('on');+ f.move(bold, {x: 37, y: 116});+ expect(paintOf(bold)).not.toBe('on');+ f.up(bold, {x: 37, y: 116});+ expect(onChange).not.toHaveBeenCalled();+ });++ it('leaves a toggle without a value standalone (AV1): no group marker, and a press that starts on it and slides onto Bold toggles nothing', () => {+ const onChange = vi.fn();+ const onPressedChange = vi.fn();+ const view = render(+ <ToggleButtonGroup+ type="multiple"+ label="Formatting"+ value={[]}+ onChange={onChange}+ data-testid="group">+ <ToggleButton label="Bold" value="bold" data-testid="a" />+ <ToggleButton+ label="Wrap"+ isPressed={false}+ onPressedChange={onPressedChange}+ data-testid="wrap"+ />+ </ToggleButtonGroup>,+ );+ const group = view.getByTestId('group');+ const bold = view.getByTestId('a');+ const wrap = view.getByTestId('wrap');+ place(group, {left: 0, top: 100, width: 160, height: 32});+ place(bold, A);+ place(wrap, B);+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ expect(isPressGroupItem(bold)).toBe(true);+ expect(isPressGroupItem(wrap)).toBe(false);+ const f = finger();+ f.down(wrap, centerOf(B));+ f.move(wrap, centerOf(A));+ f.up(wrap, centerOf(A));+ expect(onChange).not.toHaveBeenCalled();+ expect(paintOf(bold)).toBeNull();+ // Its own tap is its own, as it would be outside the group.+ f.down(wrap, centerOf(B));+ f.up(wrap, centerOf(B));+ wrap.dispatchEvent(+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 1}),+ );+ expect(onPressedChange).toHaveBeenCalledTimes(1);+ expect(onChange).not.toHaveBeenCalled();+ });++ it('touching toggles take no area from each other: 28 px toggles at x = 0, 80 and 160, a finger at x = 82 toggles only the middle one, and 8 px below a toggle still counts for it', () => {+ const {group, a, b, c, onChange} = mount();+ place(group, {left: 0, top: 100, width: 240, height: 28});+ place(a, {left: 0, top: 100, width: 80, height: 28});+ place(b, {left: 80, top: 100, width: 80, height: 28});+ place(c, {left: 160, top: 100, width: 80, height: 28});+ const tapAt = (point: Point) => {+ const f = finger();+ f.down(group, point);+ f.up(group, point);+ };+ tapAt({x: 82, y: 114});+ expect(onChange).toHaveBeenLastCalledWith(['italic']);+ tapAt({x: 120, y: 136});+ expect(onChange).toHaveBeenCalledTimes(2);+ tapAt({x: 120, y: 137});+ expect(onChange).toHaveBeenCalledTimes(2);+ });++ it('a finger on the edge of a disabled toggle that has a tooltip toggles nothing, not its enabled neighbour', () => {+ const onChange = vi.fn();+ const view = render(+ <ToggleButtonGroup+ type="multiple"+ label="Formatting"+ value={[]}+ onChange={onChange}+ data-testid="group">+ <ToggleButton label="Bold" value="bold" data-testid="a" />+ <ToggleButton+ label="Italic"+ value="italic"+ isDisabled+ tooltip="Italic is not available here"+ data-testid="b"+ />+ <ToggleButton label="Underline" value="underline" data-testid="c" />+ </ToggleButtonGroup>,+ );+ const italic = view.getByTestId('b');+ // Three touching 28 px toggles: Bold's target grows 8 px past its edge,+ // over the disabled Italic.+ place(view.getByTestId('group'), {+ left: 0,+ top: 100,+ width: 84,+ height: 28,+ });+ place(view.getByTestId('a'), {left: 0, top: 100, width: 28, height: 28});+ place(italic, {left: 28, top: 100, width: 28, height: 28});+ place(view.getByTestId('c'), {left: 56, top: 100, width: 28, height: 28});+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ const f = finger();+ f.down(italic, {x: 30, y: 114});+ f.up(italic, {x: 30, y: 114});+ expect(onChange).not.toHaveBeenCalled();+ });++ it('reads the boxes of a disabled toggle and of a toggle without a value once per press, once more on the root, never per move', () => {+ const view = render(+ <ToggleButtonGroup+ type="multiple"+ label="Formatting"+ value={[]}+ onChange={() => {}}+ data-testid="group">+ <ToggleButton label="Bold" value="bold" data-testid="a" />+ <ToggleButton+ label="Italic"+ value="italic"+ isDisabled+ tooltip="Italic is not available here"+ data-testid="b"+ />+ <ToggleButton label="Underline" value="underline" data-testid="c" />+ <ToggleButton label="Wrap" data-testid="d" />+ </ToggleButtonGroup>,+ );+ const group = view.getByTestId('group');+ const italic = view.getByTestId('b');+ const wrap = view.getByTestId('d');+ place(group, {left: 0, top: 100, width: 112, height: 28});+ place(view.getByTestId('a'), {left: 0, top: 100, width: 28, height: 28});+ place(italic, {left: 28, top: 100, width: 28, height: 28});+ place(view.getByTestId('c'), {left: 56, top: 100, width: 28, height: 28});+ place(wrap, {left: 84, top: 100, width: 28, height: 28});+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ const readItalic = vi.spyOn(italic, 'getBoundingClientRect');+ const readWrap = vi.spyOn(wrap, 'getBoundingClientRect');+ const bold = view.getByTestId('a');+ const f = finger();+ f.down(bold, {x: 10, y: 114});+ for (let x = 12; x <= 80; x += 4) {+ f.move(bold, {x, y: 114});+ }+ f.up(bold, {x: 80, y: 114});+ expect(readItalic).toHaveBeenCalledTimes(1);+ expect(readWrap).toHaveBeenCalledTimes(1);+ // On the root, the group first checks that a toggle's target holds the+ // press, which reads each of them once more.+ const g = finger();+ g.down(group, {x: 10, y: 114});+ for (let x = 12; x <= 80; x += 4) {+ g.move(group, {x, y: 114});+ }+ g.up(group, {x: 80, y: 114});+ expect(readItalic).toHaveBeenCalledTimes(3);+ expect(readWrap).toHaveBeenCalledTimes(3);+ });++ it('reads each box a fixed number of times as a press begins (PR1)', () => {+ // [pointer, where it lands, reads at the start of: the group, each+ // toggle, a link elsewhere on the page]. Nothing outside the group is+ // read.+ for (const [kind, landsOn, atStart] of [+ ['finger', 'toggle', [1, 3, 0]],+ ['finger', 'layer', [1, 4, 0]],+ ['finger', 'beside', [1, 1, 0]],+ ['pen', 'toggle', [1, 2, 0]],+ ] as const) {+ const view = render(+ <div>+ <a href="#elsewhere" data-testid="link">+ Elsewhere+ </a>+ <ToggleButtonGroup+ type="multiple"+ label="Formatting"+ value={[]}+ onChange={() => {}}+ data-testid="group">+ <ToggleButton label="Bold" value="bold" data-testid="a" />+ <ToggleButton label="Italic" value="italic" data-testid="b" />+ <ToggleButton label="Underline" value="underline" data-testid="c" />+ </ToggleButtonGroup>+ </div>,+ );+ const group = view.getByTestId('group');+ const link = view.getByTestId('link');+ const toggles = (['a', 'b', 'c'] as const).map(id =>+ view.getByTestId(id),+ );+ // Beside the toggles needs a root that stretches past them.+ place(group, {...GROUP, width: landsOn === 'beside' ? 400 : 240});+ [A, B, C].forEach((box, i) => place(toggles[i], box));+ place(link, {left: 0, top: 0, width: 80, height: 20});+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ const reads = [group, ...toggles, link].map(element =>+ vi.spyOn(element, 'getBoundingClientRect'),+ );+ const counts = () => reads.map(read => read.mock.calls.length);+ const [onGroup, onEachToggle, onLink] = atStart;+ const expected = [+ onGroup,+ onEachToggle,+ onEachToggle,+ onEachToggle,+ onLink,+ ];+ const target = landsOn === 'toggle' ? toggles[0] : group;+ const start =+ landsOn === 'toggle'+ ? centerOf(A)+ : landsOn === 'layer'+ ? {x: 40, y: 137}+ : {x: 320, y: 116};+ const path = [0, 8, 16, 24].map(dx => ({x: start.x + dx, y: start.y}));+ if (kind === 'finger') {+ // A real finger sends each pointer event before its touch event.+ const f = finger();+ pointer('touch', 'pointerdown', target, start);+ f.down(target, start);+ expect(counts()).toEqual(expected);+ for (const point of path) {+ pointer('touch', 'pointermove', target, point);+ f.move(target, point);+ }+ pointer('touch', 'pointerup', target, start);+ f.up(target, start);+ } else {+ pointer('pen', 'pointerdown', target, start);+ expect(counts()).toEqual(expected);+ for (const point of path) {+ pointer('pen', 'pointermove', target, point);+ }+ pointer('pen', 'pointerup', target, start);+ }+ // Nothing is read per move or at the lift.+ expect(counts()).toEqual(expected);+ view.unmount();+ }+ });++ it("passes a caller's ref to the group root, beside the group's own hit layer", () => {+ const ref = createRef<HTMLDivElement>();+ const {group} = mount({ref});+ expect(ref.current).toBe(group);+ const layer = (+ stylex.props(touchHitAreaStyles.layerBelowChildren).className ?? ''+ )+ .split(' ')+ .filter(Boolean);+ expect(layer.filter(name => group.classList.contains(name))).toEqual(layer);+ });++ it('a finger just past a small toggle, inside its 44 px target, toggles it (FR5)', () => {+ const {group, onChange} = mount();+ const f = finger();+ f.down(group, {x: 40, y: 136});+ f.up(group, {x: 40, y: 136});+ expect(onChange).toHaveBeenLastCalledWith(['bold']);+ });+});diff --git a/packages/core/src/ToggleButton/__tests__/ToggleButtonGroupTracking.interaction.browser.spec.ts b/packages/core/src/ToggleButton/__tests__/ToggleButtonGroupTracking.interaction.browser.spec.tsnew file mode 100644index 0000000000..93d08aeb0c--- /dev/null+++ b/packages/core/src/ToggleButton/__tests__/ToggleButtonGroupTracking.interaction.browser.spec.ts@@ -0,0 +1,330 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ToggleButtonGroupTracking.interaction.browser.spec.ts+ * @input The ToggleButton GroupMultiple story, driven by real touches (the+ * interaction harness's touch driver), a real mouse and the keyboard+ * @output Real-browser evidence that a toggle group tracks a held pointer+ * across its toggles (`family:action-groups` FR1–FR5). A slide toggles+ * only the lifted toggle, and a lift outside toggles nothing. A finger's+ * target reaches 44 px through the group's hit layer. Under a mouse, only+ * the highlighted toggle looks pressed. The keyboard is unchanged.+ * @position Beside ToggleButtonGroupTracking.test.tsx (the unit evidence)+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ drag,+ frames,+ openStory,+ tap,+ touchDriver,+ withStorybook,+ type Point,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++const STORY = 'core-togglebutton--group-multiple';++const centerOf = async (locator: Locator): Promise<Point> => {+ const box = await locator.boundingBox();+ if (box == null) {+ throw new Error('no box');+ }+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};+};++const slide = (from: Point, to: Point) =>+ drag(from, to, {durationMs: 240, hz: 60, holdMs: 60, restMs: 120});++async function open(page: Page) {+ await openStory(page, storybook(), STORY);+ const group = page.getByRole('group', {name: 'Text formatting'});+ await expect(group).toBeVisible();+ const toggle = (name: string) => group.getByRole('button', {name});+ return {+ group,+ bold: toggle('Bold'),+ italic: toggle('Italic'),+ underline: toggle('Underline'),+ };+}++/** Which toggles are pressed, in order. */+const pressed = async (group: Locator) =>+ group+ .getByRole('button')+ .evaluateAll(toggles =>+ toggles.map(toggle => toggle.getAttribute('aria-pressed') === 'true'),+ );++test('a finger slid from Bold across Italic to Underline toggles only Underline (family:action-groups FR4)', async ({+ page,+}) => {+ const {group, bold, underline} = await open(page);+ const driver = await touchDriver(page);+ await driver.play(slide(await centerOf(bold), await centerOf(underline)));+ await expect.poll(async () => pressed(group)).toEqual([false, false, true]);+});++/** The accessible name of the focused element, or `body`. */+const focusedName = async (page: Page) =>+ page.evaluate(() => {+ const element = document.activeElement;+ return element == null || element === document.body+ ? 'body'+ : (element.getAttribute('aria-label') ?? element.textContent ?? '');+ });++test('after a finger slides from Bold to Underline, Underline has focus, as a tap on it leaves it (family:action-groups FR1)', async ({+ page,+}) => {+ const {group, bold, underline} = await open(page);+ const driver = await touchDriver(page);+ await driver.play(slide(await centerOf(bold), await centerOf(underline)));+ await expect.poll(async () => pressed(group)).toEqual([false, false, true]);+ expect(await focusedName(page)).toBe('Underline');+});++test('a finger tap on Italic leaves Italic with focus, as a tap on any button does (family:action-groups FR1)', async ({+ page,+}) => {+ const {group, italic} = await open(page);+ const driver = await touchDriver(page);+ await driver.play(tap(await centerOf(italic), {holdMs: 60}));+ await expect.poll(async () => pressed(group)).toEqual([false, true, false]);+ expect(await focusedName(page)).toBe('Italic');+});++test('a finger lifted outside the group toggles nothing (family:action-groups FR3)', async ({+ page,+}) => {+ const {group, bold} = await open(page);+ const box = await group.boundingBox();+ if (box == null) {+ throw new Error('no box');+ }+ const driver = await touchDriver(page);+ await driver.play(+ slide(await centerOf(bold), {+ x: box.x + box.width / 2,+ y: box.y + box.height + 120,+ }),+ );+ // Let any click the browser might still send arrive.+ await frames(page, 4);+ expect(await pressed(group)).toEqual([false, false, false]);+});++test("under a finger an end toggle's target reaches past the group: a tap 3 px left of Bold toggles Bold (spec:AST-094 FR42)", async ({+ page,+}) => {+ const {group, bold} = await open(page);+ const box = await bold.boundingBox();+ if (box == null) {+ throw new Error('no box');+ }+ expect(box.width).toBeLessThan(44);+ const beside = {x: box.x - 3, y: box.y + box.height / 2};+ await expect+ .poll(async () =>+ page.evaluate(+ ({x, y}) =>+ document+ .elementFromPoint(x, y)+ ?.closest('[role="group"]')+ ?.getAttribute('aria-label') ?? null,+ beside,+ ),+ )+ .toBe('Text formatting');+ const driver = await touchDriver(page);+ await driver.play(tap(beside));+ await expect.poll(async () => pressed(group)).toEqual([true, false, false]);+});++test("under a finger a toggle's target reaches 44 px: the point just below it lands on the group, and a tap there toggles it (family:action-groups FR5)", async ({+ page,+}) => {+ const {group, bold} = await open(page);+ const box = await bold.boundingBox();+ if (box == null) {+ throw new Error('no box');+ }+ expect(box.height).toBeLessThan(44);+ const below = {+ x: box.x + box.width / 2,+ y: box.y + box.height + (44 - box.height) / 2 - 1,+ };+ await expect+ .poll(async () =>+ page.evaluate(+ ({x, y}) =>+ document+ .elementFromPoint(x, y)+ ?.closest('[role="group"]')+ ?.getAttribute('aria-label') ?? null,+ below,+ ),+ )+ .toBe('Text formatting');+ const driver = await touchDriver(page);+ await driver.play(tap(below));+ await expect.poll(async () => pressed(group)).toEqual([true, false, false]);+});++/**+ * Layouts that a group's own stacking context would change: a positioned+ * child (as a popover or a tooltip) and a z-indexed sibling over it.+ */+async function stackingOf(group: Locator) {+ return group.evaluate(root => {+ const doc = root.ownerDocument;+ const child = doc.createElement('span');+ child.style.cssText =+ 'position:absolute;top:0;left:0;width:8px;height:8px;z-index:2';+ root.appendChild(child);+ const box = child.getBoundingClientRect();+ // The sibling shares the group's parent, so both meet in one context.+ const sibling = doc.createElement('div');+ sibling.style.cssText = 'position:absolute;width:8px;height:8px;z-index:1';+ root.parentElement?.appendChild(sibling);+ const base = (sibling.offsetParent ?? doc.body).getBoundingClientRect();+ sibling.style.top = `${box.top - base.top}px`;+ sibling.style.left = `${box.left - base.left}px`;+ const over = sibling.getBoundingClientRect();+ const result = {+ position: getComputedStyle(root).position,+ isolation: getComputedStyle(root).isolation,+ siblingOverChild:+ Math.abs(over.top - box.top) < 1 && Math.abs(over.left - box.left) < 1,+ childPlacesAgainstGroup: child.offsetParent === root,+ childAboveSibling:+ doc.elementFromPoint(box.left + 4, box.top + 4) === child,+ };+ child.remove();+ sibling.remove();+ return result;+ });+}++test("under a finger the pixels on a toggle's own edges are the toggle's: the group's hit layer lies below its toggles", async ({+ page,+}) => {+ await openStory(page, storybook(), STORY);+ await expect(page.getByRole('group').first()).toBeVisible();+ // Each toggle's top edge and start edge, exactly on its box. It gives the+ // index of the member there, or -1 for anything else, such as the group.+ const owners = await page.evaluate(() => {+ const group = document.querySelector('[role="group"]');+ const members = group == null ? [] : [...group.querySelectorAll('button')];+ const ownerAt = (x: number, y: number) => {+ const hit = document.elementFromPoint(x, y);+ return members.findIndex(+ member => hit != null && (member === hit || member.contains(hit)),+ );+ };+ return members.map(member => {+ const box = member.getBoundingClientRect();+ return {+ top: ownerAt(box.left + box.width / 2, box.top),+ start: ownerAt(box.left, box.top + box.height / 2),+ };+ });+ });+ expect(owners.length).toBeGreaterThan(1);+ expect(owners).toEqual(+ owners.map((_, index) => ({top: index, start: index})),+ );+});++test("under a finger an enabled group's root is positioned: a positioned child places against the group, and a child's z-index still beats a lower sibling's", async ({+ page,+}) => {+ for (const story of [STORY, 'core-togglebutton--group-single']) {+ await openStory(page, storybook(), story);+ const group = page.getByRole('group').first();+ await expect(group).toBeVisible();+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(true);+ expect(await stackingOf(group)).toEqual({+ position: 'relative',+ isolation: 'auto',+ siblingOverChild: true,+ childPlacesAgainstGroup: true,+ childAboveSibling: true,+ });+ }+});++test.describe('with a mouse', () => {+ test.use({hasTouch: false, isMobile: false});++ test("a desktop group root keeps its stacking: a positioned child places as before, and a child's z-index still beats a lower sibling's", async ({+ page,+ }) => {+ for (const story of [STORY, 'core-togglebutton--group-single']) {+ await openStory(page, storybook(), story);+ const group = page.getByRole('group').first();+ await expect(group).toBeVisible();+ expect(await stackingOf(group)).toEqual({+ position: 'static',+ isolation: 'auto',+ siblingOverChild: true,+ childPlacesAgainstGroup: false,+ childAboveSibling: true,+ });+ }+ });++ test('a mouse press on Bold released on Underline toggles nothing, as a native toggle does: only Bold stays pressed (family:action-groups FR1)', async ({+ page,+ }) => {+ const {group, bold, underline} = await open(page);+ const from = await centerOf(bold);+ const to = await centerOf(underline);+ await page.mouse.move(from.x, from.y);+ await page.mouse.down();+ await page.mouse.move(to.x, to.y, {steps: 8});+ expect(await bold.evaluate(el => el.matches(':active'))).toBe(true);+ expect(await underline.evaluate(el => el.matches(':active'))).toBe(false);+ // No tracker paints a desktop press.+ await expect(group.locator('[data-astryx-press]')).toHaveCount(0);+ await page.mouse.up();+ await frames(page, 2);+ expect(await pressed(group)).toEqual([false, false, false]);+ });++ test('holding Space on a focused toggle scales it, as on any button (family:action-groups FR5: the keyboard is unchanged)', async ({+ page,+ }) => {+ const {bold} = await open(page);+ await bold.focus();+ expect(await bold.evaluate(el => el.matches(':focus-visible'))).toBe(true);+ await page.keyboard.down('Space');+ await expect+ .poll(async () => bold.evaluate(el => getComputedStyle(el).transform))+ .toBe('matrix(0.98, 0, 0, 0.98, 0, 0)');+ await page.keyboard.up('Space');+ });++ test('the keyboard is unchanged: Space on a focused toggle toggles it once', async ({+ page,+ }) => {+ const {group, bold} = await open(page);+ await bold.focus();+ await page.keyboard.press('Space');+ await expect.poll(async () => pressed(group)).toEqual([true, false, false]);+ await page.keyboard.press('Space');+ await expect+ .poll(async () => pressed(group))+ .toEqual([false, false, false]);+ });+});diff --git a/packages/core/src/hooks/pressGroupContext.ts b/packages/core/src/hooks/pressGroupContext.tsindex 7da9fab15d..d15d6d954f 100644--- a/packages/core/src/hooks/pressGroupContext.ts+++ b/packages/core/src/hooks/pressGroupContext.ts@@ -7,8 +7,9 @@* @input The layer-scoped context factory (Layer/layerScopedContext) and* the press-group marker (privateAttributes/pressGroupItem.stylex)* @output PressGroupContext: the pointer types a group's own tracker follows- * on its actions, or null outside one; pressGroupItemProps, the marker- * Button writes+ * on its actions, or null outside one. PressGroupBandContext: whether the+ * group draws an action's touch band. pressGroupItemProps: the marker Button+ * writes* @position Internal; not exported from the hooks entry. Groups that track* presses provide it, and Button reads it. A layer resets it, so a Button* in a member's layer is not tracked.@@ -32,3 +33,15 @@ export const PressGroupContext =null,);PressGroupContext.displayName = 'PressGroupContext';++/**+ * Whether a tracking group draws this action's touch band. Such a group's band+ * covers its tracked actions, and it reads their targets when a press begins.+ * So an action in it draws no band of its own.+ */+export const PressGroupBandContext = createLayerScopedContext<boolean>(+ 'PressGroupBandContext',+ 1,+ false,+);+PressGroupBandContext.displayName = 'PressGroupBandContext';diff --git a/packages/core/src/hooks/useGroupPressTracking.ts b/packages/core/src/hooks/useGroupPressTracking.tsindex 2bef695c79..41347992ba 100644--- a/packages/core/src/hooks/useGroupPressTracking.ts+++ b/packages/core/src/hooks/useGroupPressTracking.ts@@ -6,15 +6,16 @@* @file useGroupPressTracking.ts* @input A group's root ref and whether the group tracks presses: under the* touch presentation only- * @output useGroupPressTracking: the press tracking of a group of buttons;- * GROUP_PRESS_POINTERS, the pointers it follows+ * @output useGroupPressTracking: the press tracking that ButtonGroup and+ * ToggleButtonGroup share; GROUP_PRESS_POINTERS, the pointers it follows* @position Internal hook, not exported from the hooks entry. It drives* useActionGroupTracking and the shared touch hit area (useTouchHitArea)- * for a group's members. ButtonGroup consumes it, and its root applies+ * for a group's members. Each group's root applies* touchHitAreaStyles.layerBelowChildren. AlertDialog's tracking follows* GROUP_PRESS_POINTERS too.*- * SYNC: When modified, update ButtonGroupTracking.test.tsx.+ * SYNC: When modified, update ButtonGroupTracking.test.tsx and+ * ToggleButtonGroupTracking.test.tsx.*/import type {RefCallback, RefObject} from 'react';diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjsindex 77996810ad..898d48e1c5 100644--- a/scripts/touch-support-bundle.test.mjs+++ b/scripts/touch-support-bundle.test.mjs@@ -201,6 +201,9 @@ const GESTURE_USERS = new Set([// ButtonGroup: a finger's or a pen's press, tracked across its buttons// under the touch presentation.'ButtonGroup',+ // ToggleButton: through ToggleButtonGroup, whose toggles' press is tracked+ // across them for a finger and a pen under the touch presentation.+ 'ToggleButton',// Through AlertDialog: Tokenizer's bottom sheet confirms with an alert, and// PowerSearch and Table's filtering render a Tokenizer. Both also reach// TimeInput's wheels: PowerSearch's edit popover and Table's filtering.