From 980a495828a2a255bd1dfe78a376a716d18ce135 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 22:58:24 -0800 Subject: [PATCH 1/3] feat(ToggleButtonGroup): a finger's slide toggles the one it lifts on Under the touch presentation, ToggleButtonGroup's toggles are an action group for a finger and a pen, through the same tracking as ButtonGroup: the toggle under the pointer highlights, the highlight follows it, and the lift toggles only the toggle under it; a lift outside the group toggles nothing. A finger picks the nearest toggle whose 44 px target holds it, through a hit layer on the group. A mouse press acts as a native toggle's, as before. A toggle without a value keeps its own press, and the keyboard is unchanged. --- .../toggle-button-group-press-tracking.md | 7 + .../ToggleButton/ToggleButtonGroup.spec.md | 74 ++- .../core/src/ToggleButton/ToggleButton.tsx | 78 ++- .../ToggleButton/ToggleButtonGroup.doc.mjs | 6 +- .../src/ToggleButton/ToggleButtonGroup.tsx | 47 +- .../ToggleButtonGroupTracking.test.tsx | 628 ++++++++++++++++++ ...nGroupTracking.interaction.browser.spec.ts | 330 +++++++++ .../core/src/hooks/useGroupPressTracking.ts | 9 +- scripts/touch-support-bundle.test.mjs | 3 + 9 files changed, 1116 insertions(+), 66 deletions(-) create mode 100644 .changeset/toggle-button-group-press-tracking.md create mode 100644 packages/core/src/ToggleButton/ToggleButtonGroupTracking.test.tsx create mode 100644 packages/core/src/ToggleButton/__tests__/ToggleButtonGroupTracking.interaction.browser.spec.ts diff --git a/.changeset/toggle-button-group-press-tracking.md b/.changeset/toggle-button-group-press-tracking.md new file mode 100644 index 0000000000000..4913af73a108c --- /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, each toggle's target grows toward 44 px, up to half the gap to a neighbour, without the toggles growing. 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. + +@vjeux diff --git a/docs/specs/components/ToggleButton/ToggleButtonGroup.spec.md b/docs/specs/components/ToggleButton/ToggleButtonGroup.spec.md index 2268c88d06c7d..032680e1984f7 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 no selection 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 member activation 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 are separate 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)"; `ToggleButtonGroupTracking.interaction.browser.spec.ts` 44 px target case | Group tracking under a finger and a pen; group disabled | 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, or a box read per move 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 impact diff --git a/packages/core/src/ToggleButton/ToggleButton.tsx b/packages/core/src/ToggleButton/ToggleButton.tsx index e7109fc089bdd..009af135e3af6 100644 --- a/packages/core/src/ToggleButton/ToggleButton.tsx +++ b/packages/core/src/ToggleButton/ToggleButton.tsx @@ -21,11 +21,13 @@ * - /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 {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 +344,52 @@ export function ToggleButton({ ) : undefined; + // In a group, only a toggle with a value is tracked; 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; + return ( - + })}> + {labelContent} + + ); } diff --git a/packages/core/src/ToggleButton/ToggleButtonGroup.doc.mjs b/packages/core/src/ToggleButton/ToggleButtonGroup.doc.mjs index d2c754d0d7579..608122902517d 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.tsx index bcd9f264c22a4..9a37744d2d18d 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 as createContext} 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 '../utils/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 = @@ -69,6 +84,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', + }, }); // ============================================================================= @@ -233,15 +253,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(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} + ).ref; + const mergedRef = useMergedRefs(callerRef, groupRef, hitAreaRef); return (
- {children} + {/* Only a ToggleButton with a value joins the tracking (ToggleButton + reads the group). Any other child keeps its own press. */} + {children}
); diff --git a/packages/core/src/ToggleButton/ToggleButtonGroupTracking.test.tsx b/packages/core/src/ToggleButton/ToggleButtonGroupTracking.test.tsx new file mode 100644 index 0000000000000..54408e63e34b2 --- /dev/null +++ b/packages/core/src/ToggleButton/ToggleButtonGroupTracking.test.tsx @@ -0,0 +1,628 @@ +// 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 '../utils/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; +} = {}) { + // 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' ? ( + + + + + + ) : ( + + + + + + ), + ); + 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('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( + + + + })}> + {labelContent} + + ); } diff --git a/packages/core/src/ToggleButton/ToggleButtonGroupTracking.test.tsx b/packages/core/src/ToggleButton/ToggleButtonGroupTracking.test.tsx index 0a5292b596401..45aa5f06074bf 100644 --- a/packages/core/src/ToggleButton/ToggleButtonGroupTracking.test.tsx +++ b/packages/core/src/ToggleButton/ToggleButtonGroupTracking.test.tsx @@ -198,6 +198,37 @@ describe('ToggleButtonGroup tracks a held pointer across its toggles (family:act } }); + 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( + + + + + , + ); + 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 ?? '' diff --git a/packages/core/src/ToggleButton/__tests__/ToggleButtonGroupTracking.interaction.browser.spec.ts b/packages/core/src/ToggleButton/__tests__/ToggleButtonGroupTracking.interaction.browser.spec.ts index 3a1a1cd37233a..93d08aeb0c83a 100644 --- a/packages/core/src/ToggleButton/__tests__/ToggleButtonGroupTracking.interaction.browser.spec.ts +++ b/packages/core/src/ToggleButton/__tests__/ToggleButtonGroupTracking.interaction.browser.spec.ts @@ -219,8 +219,8 @@ test("under a finger the pixels on a toggle's own edges are the toggle's: the gr }) => { await openStory(page, storybook(), STORY); await expect(page.getByRole('group').first()).toBeVisible(); - // Each toggle's top edge, and its start edge, exactly on its box: the index - // of the member there (-1 for anything else, such as the group). + // 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')]; diff --git a/packages/core/src/hooks/pressGroupContext.ts b/packages/core/src/hooks/pressGroupContext.ts index 7da9fab15d28c..d15d6d954f880 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( + 'PressGroupBandContext', + 1, + false, +); +PressGroupBandContext.displayName = 'PressGroupBandContext'; From 0c70bbffe4030f7bfa84662536c1ebc87f42fa41 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 07:13:24 -0800 Subject: [PATCH 3/3] docs(ToggleButtonGroup): a tracked toggle keeps its 44 px target Since Button's touch band, every grouped toggle already has its 44 px target, so the changeset no longer says the group grows it: a toggle the group tracks keeps it, now drawn by the group. A comment in ToggleButton reads in two short active sentences. --- .changeset/toggle-button-group-press-tracking.md | 2 +- packages/core/src/ToggleButton/ToggleButton.tsx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.changeset/toggle-button-group-press-tracking.md b/.changeset/toggle-button-group-press-tracking.md index 4913af73a108c..1ed20c5c724f1 100644 --- a/.changeset/toggle-button-group-press-tracking.md +++ b/.changeset/toggle-button-group-press-tracking.md @@ -2,6 +2,6 @@ '@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, each toggle's target grows toward 44 px, up to half the gap to a neighbour, without the toggles growing. 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. +[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. @vjeux diff --git a/packages/core/src/ToggleButton/ToggleButton.tsx b/packages/core/src/ToggleButton/ToggleButton.tsx index 997715c48a43d..fee9b42898d24 100644 --- a/packages/core/src/ToggleButton/ToggleButton.tsx +++ b/packages/core/src/ToggleButton/ToggleButton.tsx @@ -347,8 +347,8 @@ export function ToggleButton({ ) : undefined; - // In a group, only a toggle with a value is tracked; a toggle without one - // keeps its own press. Outside a group, the toggle follows its parent. + // 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