diff --git a/.changeset/toggle-button-group-press-tracking.md b/.changeset/toggle-button-group-press-tracking.md new file mode 100644 index 0000000000000..1ed20c5c724f1 --- /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. + +@vjeux diff --git a/docs/specs/components/Button/Button.spec.md b/docs/specs/components/Button/Button.spec.md index 0fb961cf44fd6..b8a92da60ba70 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 ` + + + + + ); } 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 a0518bd8e7ab5..3965de7193b06 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(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..45aa5f06074bf --- /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; +} = {}) { + // 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("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 ?? '' + ) + .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( + + +