An open source design system that's fully customizable and agent ready
TypeScript
feat(ButtonGroup): a finger's slide runs the button it lifts on (#8657)
Christopher Chedeauddb8b34621e7
diff --git a/.changeset/button-group-press-tracking.md b/.changeset/button-group-press-tracking.mdnew file mode 100644index 0000000000..9c2e0efe3c--- /dev/null+++ b/.changeset/button-group-press-tracking.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Under the touch presentation, ButtonGroup tracks a finger's or a pen's press across its buttons, like a menu. Press a button and slide across the others: the highlight follows, and the button you lift on runs. Lifting outside the group runs nothing. A mouse press is unchanged: it acts as a native button's, on the button it began on. With a finger, each button's target grows toward 44 px, up to half the gap to a neighbour, without the buttons growing. A menu trigger in the group keeps its own opening, and the keyboard is unchanged. Before, each button tracked only its own press, and sliding off it ran nothing. An enabled ButtonGroup 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/apps/storybook/stories/ButtonGroup.stories.tsx b/apps/storybook/stories/ButtonGroup.stories.tsxindex 5d4b6e56ea..609b9747ac 100644--- a/apps/storybook/stories/ButtonGroup.stories.tsx+++ b/apps/storybook/stories/ButtonGroup.stories.tsx@@ -1,5 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import {useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {ButtonGroup} from '@astryxdesign/core/ButtonGroup';import {Button} from '@astryxdesign/core/Button';@@ -48,6 +49,33 @@ export const Horizontal: Story = {),};+/**+ * Under the touch presentation a press tracks like a menu. Press a button and+ * slide across the others: the highlight follows, and the button you lift on+ * runs. A lift outside the group runs nothing. A mouse press acts as a native+ * button's. With a finger, each small button's target grows toward 44 px, up+ * to half the gap to a neighbour.+ */+export const SlideAcross: Story = {+ render: function SlideAcrossStory() {+ const [log, setLog] = useState<ReadonlyArray<string>>([]);+ const press = (label: string) => () =>+ setLog(previous => [...previous, label]);+ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: 24}}>+ <ButtonGroup label="Edit actions" size="sm">+ <Button label="Cut" onClick={press('Cut')} />+ <Button label="Copy" onClick={press('Copy')} />+ <Button label="Paste" onClick={press('Paste')} />+ </ButtonGroup>+ <output data-testid="slide-log">+ {log.length === 0 ? 'Nothing pressed' : `Pressed: ${log.join(', ')}`}+ </output>+ </div>+ );+ },+};+/** Vertical button group. */export const Vertical: Story = {render: () => (diff --git a/docs/specs/components/ButtonGroup/ButtonGroup.spec.md b/docs/specs/components/ButtonGroup/ButtonGroup.spec.mdindex 18440b3757..cbec996548 100644--- a/docs/specs/components/ButtonGroup/ButtonGroup.spec.md+++ b/docs/specs/components/ButtonGroup/ButtonGroup.spec.md@@ -40,7 +40,7 @@ system_specs: [spec:AST-038, spec:AST-085]| Behavior | A labelled `role="group"` that joins its Button members into one connected surface, gives them a default size and its disabled state, owns one shared elevation, and is one Tab stop with arrow-key roving. || End-user impact | Keyboard users reach the whole group with one Tab and move through it with arrows, which skip disabled members. A disabled group without tooltips has no Tab stop, so keyboard users cannot find it or hear that it is disabled. || Builder impact | None. |-| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. Disabled members use native `disabled`, the Tab stop leaves disabled and busy-only members, and wrapped members lose connected geometry; all are listed under Current-state impact. |+| Compatibility/readiness | No API or default change; its DOM change is listed below. Disabled members use native `disabled`, the Tab stop leaves disabled and busy-only members, and wrapped members lose connected geometry; all are listed under Current-state impact. || Review checks | Reject a group without a name, gaps between members, rounded inner corners, a shadow on a member, more than one Tab stop, arrows that land on a disabled member, or arrows that steal keys from a member's open menu. || Governing rules | `family:buttons` FR3, FR8, FR10–FR12, AV5; `architecture:component-size-cascade` INV3–INV8; `spec:AST-085` FR1, FR7; `spec:AST-038` FR7, FR8. |@@ -55,10 +55,16 @@ size and disabled state, and the group's single-Tab-stop keyboard model, as## Compatibility and migration-- Released default preserved: `yes`; `orientation="horizontal"`, `size="md"`,- `elevation="none"`, `isDisabled={false}`-- Compatibility class: records shipped behavior; no public prop, default,- export, or DOM change+- Released default preserved: `yes` for a mouse; under the touch+ presentation a press gains the slide across the buttons;+ `orientation="horizontal"`, `size="md"`, `elevation="none"`,+ `isDisabled={false}`+- Compatibility class: no public prop, default, or export change; under the+ touch presentation the DOM gains the action-group item marker on each+ tracked button, 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: not applicable- Migration decision: nonediff --git a/packages/core/src/AlertDialog/AlertDialog.tsx b/packages/core/src/AlertDialog/AlertDialog.tsxindex 9c518a4f5d..ccb49bb5b8 100644--- a/packages/core/src/AlertDialog/AlertDialog.tsx+++ b/packages/core/src/AlertDialog/AlertDialog.tsx@@ -5,8 +5,9 @@/*** @file AlertDialog.tsx* @input Uses React, StyleX, Dialog, Layout, Heading, Text, Button, the- * action-group tracking (hooks/useActionGroupTracking) and the press-group- * marker (privateAttributes/pressGroupItem.stylex)+ * action-group tracking (hooks/useActionGroupTracking), the press-group+ * context (hooks/pressGroupContext) and the group pointers+ * (hooks/useGroupPressTracking)* @output Exports AlertDialog component, AlertDialogProps type* @position Core implementation; consumed by index.ts, tested by AlertDialog.test.tsx*@@ -42,14 +43,11 @@ import {import english from '../i18n/generated-english/AlertDialog/AlertDialog.generated';import {useActionGroupTracking} from '../hooks/useActionGroupTracking';import {PressGroupContext} from '../hooks/pressGroupContext';+import {GROUP_PRESS_POINTERS} from '../hooks/useGroupPressTracking';import {alertController} from '../motion/uikit/alert';-import {pressGroupItemProps} from '../privateAttributes/pressGroupItem.stylex';registerEnglishFallback(english);-const SLIDING_POINTERS = ['touch', 'pen'] as const;-const ACTION_TRACKING_PROPS = pressGroupItemProps(SLIDING_POINTERS);-const SMALL_SCREEN_QUERY = '(max-width: 640px)';const styles = stylex.create({@@ -194,8 +192,8 @@ export function AlertDialog({onOpenChange(false);}, [onOpenChange]);- // Each action carries the press-group marker from its first render, so the- // tracker is its only painter.+ // Through the group's context, each action's Button writes the press-group+ // marker from its first render. So the tracker is its only painter.const actionsRef = useRef<HTMLElement>(null);// Only under the touch presentation does a press slide across the// actions. A desktop press stays the native button's.@@ -207,10 +205,9 @@ export function AlertDialog({highlightOnsetMs: alertController.actions.highlightOnsetMs,highlightExpansion: alertController.actions.highlightExpansion,// A mouse press acts as a native button's under any presentation.- pointerTypes: SLIDING_POINTERS,+ pointerTypes: GROUP_PRESS_POINTERS,isEnabled: isTracking,});- const actionTrackingProps = isTracking ? ACTION_TRACKING_PROPS : undefined;const buttonActionStyle = [styles.action,@@ -223,7 +220,6 @@ export function AlertDialog({label={cancelLabel}onClick={handleCancel}xstyle={buttonActionStyle}- {...actionTrackingProps}// Dialog focuses [data-autofocus] itself after showModal(), because// React's autoFocus runs during commit while the dialog is invisible.// Cancel is least destructive, so it remains the autofocus target even@@ -239,7 +235,6 @@ export function AlertDialog({onClick={onAction}isLoading={isActionLoading}xstyle={buttonActionStyle}- {...actionTrackingProps}/>);@@ -287,7 +282,8 @@ export function AlertDialog({gap={2}hAlign={isSmallScreen ? 'stretch' : 'end'}wrap={isSmallScreen ? 'nowrap' : 'wrap'}>- <PressGroupContext value={isTracking}>+ <PressGroupContext+ value={isTracking ? GROUP_PRESS_POINTERS : null}>{isSmallScreen? [actionButton, cancelButton]: [cancelButton, actionButton]}diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsxindex 4ad53ceff4..124224b1c3 100644--- a/packages/core/src/Button/Button.tsx+++ b/packages/core/src/Button/Button.tsx@@ -53,7 +53,10 @@ import {iconBoxSizeStyles, type IconSize} from '../Icon/IconSize.stylex';import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';import {useSize} from '../SizeContext/SizeContext';import {useButtonGroup} from '../ButtonGroup/ButtonGroupContext';-import {PressGroupContext} from '../hooks/pressGroupContext';+import {+ PressGroupContext,+ pressGroupItemProps,+} from '../hooks/pressGroupContext';import {useInputGroup} from '../InputGroup/InputGroupContext';import {InputGroupInternalContext} from '../InputGroup/InputGroupInternalContext';import {@@ -84,6 +87,9 @@ registerEnglishFallback(english);*/const PRESSED_ON: string = '[data-astryx-press="on"]';+/** `aria-haspopup` values of a trigger that keeps its own press and opening. */+const MENU_POPUPS: ReadonlySet<string> = new Set(['true', 'menu', 'listbox']);+/*** Base button styles* Pseudo-classes are nested within properties per StyleX recommendation:@@ -651,7 +657,14 @@ export function Button({const t = useComponentTranslator();const size = useSize(sizeProp, 'md');const buttonGroup = useButtonGroup();- const isGroupTracked = use(PressGroupContext);+ // A tracking group's tracker paints this button's pointer press. A menu+ // trigger is not tracked: it keeps its own press and opening.+ const groupPointers = use(PressGroupContext);+ const groupItemProps =+ groupPointers != null && !MENU_POPUPS.has(String(props['aria-haspopup']))+ ? pressGroupItemProps(groupPointers)+ : undefined;+ const isGroupTracked = groupItemProps != null;const inputGroup = useInputGroup();const [isPending, startTransition] = useTransition();@@ -928,6 +941,7 @@ export function Button({: undefined)}{...sharedMergedProps}{...pressFeedback}+ {...groupItemProps}{...props}{...ariaLabelProp}{...describedByProp}@@ -952,6 +966,7 @@ export function Button({: undefined)}{...sharedMergedProps}{...pressFeedback}+ {...groupItemProps}{...props}{...ariaLabelProp}{...describedByProp}diff --git a/packages/core/src/ButtonGroup/ButtonGroup.doc.mjs b/packages/core/src/ButtonGroup/ButtonGroup.doc.mjsindex 08a0f67682..20cd9b1b3a 100644--- a/packages/core/src/ButtonGroup/ButtonGroup.doc.mjs+++ b/packages/core/src/ButtonGroup/ButtonGroup.doc.mjs@@ -22,7 +22,7 @@ export const docs = {{name: 'ButtonGroup',displayName: 'Button Group',- description: 'Groups multiple buttons together with connected styling: shared borders, proper border-radius handling (only on outer edges), and horizontal or vertical orientation.',+ description: 'Groups multiple buttons together with connected styling: shared borders, proper border-radius handling (only on outer edges), and horizontal or vertical orientation. Under the touch presentation a press tracks like a menu: press a button and slide across the others, and the highlight follows. The button you lift on runs, and lifting outside the group runs nothing. A mouse press acts as a native button\'s. With a finger, each button\'s target grows toward 44 px, up to half the gap to a neighbour, without the buttons growing. A menu trigger in the group keeps its own opening.',props: [{name: 'children', type: 'ReactNode', description: 'Button or IconButton children.', required: true, slotElements: [{__element: 'Button', props: {label: 'Action'}}]},{name: 'label', type: 'string', description: 'Accessible label for the group (aria-label).', required: true},@@ -110,7 +110,7 @@ export const docsZh = {{name: 'ButtonGroup',displayName: 'Button Group',- description: '将多个按钮组合在一起,带有连接样式:共享边框、正确的圆角处理(仅外边缘),以及水平或垂直方向。',+ description: '将多个按钮组合在一起,带有连接样式:共享边框、正确的圆角处理(仅外边缘),以及水平或垂直方向。在触摸呈现下(主要指针为粗指针时),按下时按钮组像菜单一样跟踪按压:按下一个按钮并滑过其他按钮,高亮随之移动。松开时所在的按钮执行,在组外松开则什么都不执行。鼠标按下与原生按钮相同。使用手指时,每个按钮的触控目标向 44 px 扩展,最多到与相邻按钮间距的一半,按钮本身不变大。组内的菜单触发器保留自己的打开方式。',propDescriptions: {children: 'Button 或 IconButton 子元素。',label: '按钮组的无障碍标签 (aria-label)。',@@ -160,6 +160,7 @@ export const docsDense = {{guidance: false, description: "Don't nest ButtonGroups."},{guidance: true, description: 'Label the group for what its buttons act on; it is the accessible name.'},{guidance: true, description: 'Single Tab stop; arrows move between members, Home/End to ends, disabled skipped (APG roving tabindex).'},+ {guidance: true, description: 'Under the touch presentation a press tracks like a menu: slide across, the lifted button runs, a lift outside runs nothing. A mouse press acts as a native button\'s. Finger targets grow toward 44 px, up to half the gap to a neighbour; a menu trigger keeps its own opening.'},{guidance: false, description: "Don't disable the group for an in-flight action; a disabled member drops focus."},],},diff --git a/packages/core/src/ButtonGroup/ButtonGroup.tsx b/packages/core/src/ButtonGroup/ButtonGroup.tsxindex 631d0fefce..5df3d49e1c 100644--- a/packages/core/src/ButtonGroup/ButtonGroup.tsx+++ b/packages/core/src/ButtonGroup/ButtonGroup.tsx@@ -4,7 +4,8 @@/*** @file ButtonGroup.tsx- * @input Uses React, StyleX, Button/IconButton children+ * @input Uses React, StyleX, Button/IconButton children, and the shared group+ * press tracking (hooks/useGroupPressTracking)* @output Exports ButtonGroup component, context, and types* @position Groups buttons with connected styling; consumed by index.ts*@@ -21,13 +22,20 @@* - /packages/cli/assets/templates/blocks/components/ButtonGroup/ (showcase blocks)*/-import {useMemo, type ReactNode} from 'react';+import {useMemo, useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import type {ButtonSize} from '../Button';import {radiusVars, shadowVars} from '../theme/tokens.stylex';import type {Elevation} from '../utils/types';import {SizeProvider, useSize} from '../SizeContext/SizeContext';import {useListFocus} from '../hooks/useListFocus';+import {PressGroupContext} from '../hooks/pressGroupContext';+import {+ GROUP_PRESS_POINTERS,+ useGroupPressTracking,+} from '../hooks/useGroupPressTracking';+import {useTouchPresentation} from '../utils/touchPresentation';+import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';import {mergeProps, composeEventHandlers} from '../utils';import type {BaseProps} from '../BaseProps';import {ButtonGroupContext} from './ButtonGroupContext';@@ -98,6 +106,11 @@ const styles = stylex.create({vertical: {flexDirection: 'column',},+ // While the group tracks presses, its hit layer is the root's `::before`,+ // below its buttons, so the root is the layer's containing block.+ tracking: {+ position: 'relative',+ },});// Resting elevation for the whole group — the connected buttons share one@@ -197,16 +210,25 @@ export function ButtonGroup({[orientation, isDisabled],);+ // Only under the touch presentation does a press slide across the buttons.+ // A desktop press stays the native button's.+ const {isTouch} = useTouchPresentation();+ const tracksPress = !isDisabled && isTouch;+ const groupRef = useRef<HTMLDivElement>(null);+ const {hitAreaRef} = useGroupPressTracking(groupRef, tracksPress);+return (<ButtonGroupContext value={contextValue}><SizeProvider value={size}><div- ref={useMergedRefs(ref, listRef)}+ ref={useMergedRefs(ref, listRef, groupRef, hitAreaRef)}{...props}{...mergeProps(themeProps('button-group', {size, orientation, elevation}),stylex.props(styles.group,+ tracksPress && styles.tracking,+ tracksPress && touchHitAreaStyles.layerBelowChildren,orientation === 'vertical' && styles.vertical,elevationStyles[elevation],xstyle,@@ -220,7 +242,9 @@ export function ButtonGroup({onFocus={composeEventHandlers(onFocus, handleFocus)}aria-disabled={isDisabled || undefined}data-testid={testId}>- {children}+ <PressGroupContext value={tracksPress ? GROUP_PRESS_POINTERS : null}>+ {children}+ </PressGroupContext></div></SizeProvider></ButtonGroupContext>diff --git a/packages/core/src/ButtonGroup/ButtonGroupTracking.test.tsx b/packages/core/src/ButtonGroup/ButtonGroupTracking.test.tsxnew file mode 100644index 0000000000..298fc776ed--- /dev/null+++ b/packages/core/src/ButtonGroup/ButtonGroupTracking.test.tsx@@ -0,0 +1,855 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ButtonGroupTracking.test.tsx+ * @input ButtonGroup and Button, driven by synthetic touch, pen and mouse+ * streams under a coarse or a fine primary pointer+ * @output Unit evidence that a button group tracks a held pointer across its+ * buttons as one action group (`family:action-groups` FR1–FR5)+ * @position Beside ButtonGroup.test.tsx; the real-browser evidence is+ * __tests__/ButtonGroupTracking.interaction.browser.spec.ts+ */++import * as stylex from '@stylexjs/stylex';+import {act, render} from '@testing-library/react';+import {useLayoutEffect, useState} from '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 {DropdownMenu} from '../DropdownMenu/DropdownMenu';+import {ButtonGroup} from './ButtonGroup';++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,+): Event {+ 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);+ return event;+}++/** A finger, with a fresh id. */+function finger() {+ const id = nextTouchId++;+ return {+ down: (target: Element, point: Point) => {+ time += 1000;+ return 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),+ };+}++/** Modifier keys held during a pointer event. */+type Modifiers = Partial<+ Pick<MouseEventInit, 'ctrlKey' | 'metaKey' | 'shiftKey' | 'altKey'>+>;++/** 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,+ modifiers: Modifiers = {},+): 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,+ ...modifiers,+ });+ 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');+const hitLayer = (+ stylex.props(touchHitAreaStyles.layerBelowChildren).className ?? ''+)+ .split(' ')+ .filter(Boolean);+/** The hit layer's atomic classes that `group` carries. */+const hitLayerOn = (group: Element) =>+ hitLayer.filter(name => group.classList.contains(name));++function mount({+ isDisabled = false,+ isBDisabled = false,+ isCMenuTrigger = false,+ cHasPopup,+ groupBox = GROUP,+}: {+ isDisabled?: boolean;+ isBDisabled?: boolean;+ isCMenuTrigger?: boolean;+ /** The third button's own `aria-haspopup` (a menu trigger sets 'menu'). */+ cHasPopup?: 'true' | 'menu' | 'listbox' | 'dialog' | 'grid' | 'tree';+ /** The root's box: wider than the buttons when it stretches. */+ groupBox?: typeof GROUP;+} = {}) {+ const onA = vi.fn();+ const onB = vi.fn();+ const onC = vi.fn();+ const view = render(+ <ButtonGroup label="Edit" isDisabled={isDisabled} data-testid="group">+ <Button label="Cut" onClick={onA} data-testid="a" />+ <Button+ label="Copy"+ onClick={onB}+ isDisabled={isBDisabled}+ data-testid="b"+ />+ <Button+ label="More"+ onClick={onC}+ data-testid="c"+ {...(isCMenuTrigger ? {'aria-haspopup': 'menu' as const} : {})}+ {...(cHasPopup != null ? {'aria-haspopup': cHasPopup} : {})}+ />+ </ButtonGroup>,+ );+ const group = view.getByTestId('group');+ const a = view.getByTestId('a');+ const b = view.getByTestId('b');+ const c = view.getByTestId('c');+ place(group, groupBox);+ place(a, A);+ place(b, B);+ place(c, C);+ // The gesture host styles what it attached in the next frame.+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ return {...view, group, a, b, c, onA, onB, onC};+}++let restorePointer: () => void = () => {};++beforeEach(() => {+ vi.useFakeTimers();+ restorePointer = coarsePrimaryPointer();+});++afterEach(() => {+ vi.runOnlyPendingTimers();+ vi.useRealTimers();+ restorePointer();+});++/** Switch the primary pointer to a mouse (fine) for one case. */+function finePrimaryPointer(): void {+ restorePointer();+ restorePointer = pointerQuery(false).restore;+}++describe('ButtonGroup tracks a held pointer across its buttons (family:action-groups)', () => {+ it('marks each button as a tracked action, and marks none while the group is disabled', () => {+ const {a, b, c, unmount} = mount();+ for (const button of [a, b, c]) {+ expect(isPressGroupItem(button)).toBe(true);+ }+ unmount();+ const disabled = mount({isDisabled: true});+ for (const button of [disabled.a, disabled.b, disabled.c]) {+ expect(isPressGroupItem(button)).toBe(false);+ }+ });++ it('gives the root no hit layer under a fine primary pointer, so a desktop root keeps its stacking', () => {+ finePrimaryPointer();+ const {group} = mount();+ expect(hitLayerOn(group)).toEqual([]);+ });++ it("keeps its hit layer, and reads the page no more, when a parent's re-render hands it a new inline ref", () => {+ let rerenderPage = () => {};+ function Page() {+ const [, setTick] = useState(0);+ rerenderPage = () => setTick(tick => tick + 1);+ return (+ <>+ <ButtonGroup+ label="Edit"+ data-testid="group"+ // A new callback on every render, as a caller's inline ref is.+ ref={(node: HTMLDivElement | null) => {+ void node;+ }}>+ <Button label="Cut" onClick={() => {}} data-testid="a" />+ <Button label="Copy" onClick={() => {}} data-testid="b" />+ <Button label="More" onClick={() => {}} data-testid="c" />+ </ButtonGroup>+ <button type="button" data-testid="outside">+ Outside+ </button>+ </>+ );+ }+ const view = render(<Page />);+ const group = view.getByTestId('group');+ place(group, GROUP);+ place(view.getByTestId('a'), A);+ place(view.getByTestId('b'), B);+ place(view.getByTestId('c'), C);+ // A control elsewhere on the page. A measure pass reads its box.+ const outside = view.getByTestId('outside');+ const outsideBox = DOMRect.fromRect({x: 0, y: 300, width: 80, height: 32});+ let outsideReads = 0;+ outside.getBoundingClientRect = () => {+ outsideReads += 1;+ return outsideBox;+ };+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ const inset = (side: string) =>+ group.style.getPropertyValue(`--astryx-hit-inset-${side}`);+ expect(inset('top')).toBe('6px');+ expect(outsideReads).toBeGreaterThan(0);+ const classes = group.className;+ const reads = outsideReads;+ act(() => {+ rerenderPage();+ });+ // The root keeps its classes, so its hit layer never drops.+ expect(group.className).toBe(classes);+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ // The watch held: no new measure pass reads the page.+ expect(outsideReads).toBe(reads);+ expect(inset('top')).toBe('6px');+ });++ for (const primary of ['fine', 'coarse'] as const) {+ it(`leaves a mouse press to the native button under a ${primary} primary pointer: a press slid from Cut to More runs nothing (family:action-groups FR1)`, () => {+ if (primary === 'fine') {+ finePrimaryPointer();+ }+ const {group, a, c, onA, onC} = 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));+ expect(paintOf(c)).toBeNull();+ pointer('mouse', 'pointerup', c, centerOf(C));+ // The browser's own click for that press lands on the buttons' common+ // parent, where the press began and ended apart.+ group.dispatchEvent(+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 1}),+ );+ expect(onA).not.toHaveBeenCalled();+ expect(onC).not.toHaveBeenCalled();+ });+ }++ it('paints a mouse press under the touch presentation as `:active` would: the group leaves it to the native button', () => {+ const {a, b} = mount();+ pointer('mouse', 'pointerdown', a, centerOf(A));+ expect(paintOf(a)).toBe('on');+ expect(paintOf(b)).toBeNull();+ pointer('mouse', 'pointerup', a, centerOf(A));+ act(() => {+ vi.runOnlyPendingTimers();+ });+ expect(paintOf(a)).not.toBe('on');+ });++ it("grows the end buttons' targets past the group under a finger, as far as each would grow alone, and a hidden member grows and runs nothing (spec:AST-094 FR42, family:action-groups FR2, FR3)", () => {+ const onGone = vi.fn();+ const view = render(+ <ButtonGroup label="Format" data-testid="group">+ <Button label="B" isIconOnly icon="bold" data-testid="a" />+ <Button label="I" isIconOnly icon="italic" data-testid="b" />+ <Button label="U" isIconOnly icon="underline" data-testid="c" />+ <Button+ label="S"+ onClick={onGone}+ style={{display: 'none'}}+ data-testid="d"+ />+ </ButtonGroup>,+ );+ const group = view.getByTestId('group');+ // Three 32 px buttons in a 96 × 32 row. The hidden fourth has an empty+ // box at the viewport's corner.+ place(group, {left: 0, top: 100, width: 96, height: 32});+ for (const [id, left] of [+ ['a', 0],+ ['b', 32],+ ['c', 64],+ ] as const) {+ place(view.getByTestId(id), {left, top: 100, width: 32, height: 32});+ }+ place(view.getByTestId('d'), {left: 0, top: 0, width: 0, height: 0});+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ const inset = (side: string) =>+ group.style.getPropertyValue(`--astryx-hit-inset-${side}`);+ expect(['top', 'right', 'bottom', 'left'].map(inset)).toEqual([+ '6px',+ '6px',+ '6px',+ '6px',+ ]);+ // The root carries the hit layer while it tracks presses.+ expect(hitLayerOn(group)).toEqual(hitLayer);+ // A finger slid to the hidden member's corner lights and runs nothing.+ const f = finger();+ f.down(view.getByTestId('a'), {x: 16, y: 116});+ f.move(view.getByTestId('a'), {x: 0, y: 0});+ expect(paintOf(view.getByTestId('d'))).toBeNull();+ f.up(view.getByTestId('a'), {x: 0, y: 0});+ expect(onGone).not.toHaveBeenCalled();+ });++ it("takes a finger's press on a root wider than its buttons only where a button's target holds it, so a tap beside them keeps its click (FR5)", () => {+ // The root stretches to 400 px, as a flex child does; the buttons end at+ // 240. Their 32 px height grows 6 px above and below.+ const {group, onA, onB, onC} = mount({+ groupBox: {left: 0, top: 100, width: 400, height: 32},+ });+ const inset = (side: string) =>+ group.style.getPropertyValue(`--astryx-hit-inset-${side}`);+ // The hit layer ends at the last button's edge.+ expect(['top', 'right', 'bottom', 'left'].map(inset)).toEqual([+ '6px',+ '-160px',+ '6px',+ '0px',+ ]);+ for (const point of [+ {x: 320, y: 116},+ {x: 320, y: 135},+ ]) {+ const f = finger();+ f.down(group, point);+ const lift = f.up(group, point);+ // Nothing takes the press, so the browser's click for it still runs.+ expect(lift.defaultPrevented).toBe(false);+ }+ expect(onA).not.toHaveBeenCalled();+ expect(onB).not.toHaveBeenCalled();+ expect(onC).not.toHaveBeenCalled();+ // Just below the last button, inside its target, the group takes it.+ const f = finger();+ f.down(group, {x: 200, y: 135});+ const lift = f.up(group, {x: 200, y: 135});+ expect(onC).toHaveBeenCalledTimes(1);+ expect(lift.defaultPrevented).toBe(true);+ });++ for (const [name, extra] of [+ ['a header', {header: <span>Approve</span>}],+ ['a bottom sheet', {presentation: 'bottom-sheet' as const}],+ ] as const) {+ it(`leaves a DropdownMenu's trigger with ${name} its own press: a slide from it onto a button runs nothing`, () => {+ const onAllow = vi.fn();+ const view = render(+ <ButtonGroup label="Approve action" data-testid="group">+ <Button label="Allow once" onClick={onAllow} data-testid="a" />+ <DropdownMenu+ button={{label: 'Allow options'}}+ items={[{label: 'Always allow'}]}+ {...extra}+ />+ </ButtonGroup>,+ );+ const trigger = view.getByRole('button', {name: 'Allow options'});+ const allow = view.getByTestId('a');+ expect(isPressGroupItem(trigger)).toBe(false);+ place(view.getByTestId('group'), GROUP);+ place(allow, A);+ place(trigger, B);+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ const f = finger();+ f.down(trigger, centerOf(B));+ f.move(trigger, centerOf(A));+ f.up(trigger, centerOf(A));+ expect(onAllow).not.toHaveBeenCalled();+ });+ }++ it('runs the button a finger lifts on, once, through its own click, after sliding there from another (FR1, FR2)', () => {+ const {a, b, c, onA, onB, onC} = mount();+ const f = finger();+ f.down(a, centerOf(A));+ expect(paintOf(a)).toBe('on');+ f.move(a, centerOf(B));+ expect(paintOf(a)).toBeNull();+ expect(paintOf(b)).toBe('on');+ f.move(a, centerOf(C));+ expect(paintOf(b)).toBeNull();+ expect(paintOf(c)).toBe('on');+ f.up(a, centerOf(C));+ expect(onC).toHaveBeenCalledTimes(1);+ expect(onA).not.toHaveBeenCalled();+ expect(onB).not.toHaveBeenCalled();+ });++ it('runs nothing for a lift outside the group, and the highlight goes as the finger leaves (FR3)', () => {+ const {a, b, c, onA, onB, onC} = mount();+ const f = finger();+ f.down(a, centerOf(A));+ f.move(a, {x: 120, y: 260});+ expect([paintOf(a), paintOf(b), paintOf(c)]).toEqual([null, null, null]);+ f.up(a, {x: 120, y: 260});+ expect(onA).not.toHaveBeenCalled();+ expect(onB).not.toHaveBeenCalled();+ expect(onC).not.toHaveBeenCalled();+ });++ it('tracks a pen like a finger (FR5)', () => {+ const {a, b, onA, onB} = mount();+ pointer('pen', 'pointerdown', a, centerOf(A));+ expect(paintOf(a)).toBe('on');+ pointer('pen', 'pointermove', a, centerOf(B));+ expect(paintOf(b)).toBe('on');+ pointer('pen', 'pointerup', b, centerOf(B));+ expect(onB).toHaveBeenCalledTimes(1);+ expect(onA).not.toHaveBeenCalled();+ });++ for (const key of ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'] as const) {+ it(`leaves a mouse press with ${key} held on a link member to the browser: its own click runs, carrying the key`, () => {+ const onDocs = vi.fn();+ const view = render(+ <ButtonGroup label="Help" data-testid="group">+ <Button label="Docs" href="/docs" onClick={onDocs} data-testid="a" />+ <Button label="Ask" data-testid="b" />+ </ButtonGroup>,+ );+ const docs = view.getByTestId('a');+ place(view.getByTestId('group'), GROUP);+ place(docs, A);+ place(view.getByTestId('b'), B);+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ pointer('mouse', 'pointerdown', docs, centerOf(A), {[key]: true});+ // The press controller paints the press, as `:active` would; the+ // group's tracker takes no mouse press.+ expect(paintOf(docs)).toBe('on');+ pointer('mouse', 'pointerup', docs, centerOf(A), {[key]: true});+ // The browser's own click for that press opens the link elsewhere, so+ // nothing may replace or cancel it.+ const click = new MouseEvent('click', {+ bubbles: true,+ cancelable: true,+ detail: 1,+ [key]: true,+ });+ docs.dispatchEvent(click);+ expect(onDocs).toHaveBeenCalledTimes(1);+ expect(onDocs.mock.calls[0][0][key]).toBe(true);+ expect(click.defaultPrevented).toBe(false);+ });+ }++ it("keeps a selection that the lifted button's click makes in a layout effect, after its render (spec:AST-094 FR41)", async () => {+ function SelectOnClick() {+ const [clicks, setClicks] = useState(0);+ useLayoutEffect(() => {+ const text = document.querySelector('[data-testid="text"]');+ if (clicks > 0 && text != null) {+ getSelection()?.selectAllChildren(text);+ }+ }, [clicks]);+ return (+ <Button+ label="Select"+ onClick={() => setClicks(count => count + 1)}+ data-testid="select"+ />+ );+ }+ const view = render(+ <>+ <p data-testid="text">Text a layout effect selects</p>+ <ButtonGroup label="Text" data-testid="group">+ <SelectOnClick />+ <Button label="Clear" data-testid="b" />+ </ButtonGroup>+ </>,+ );+ const select = view.getByTestId('select');+ place(view.getByTestId('group'), GROUP);+ place(select, A);+ place(view.getByTestId('b'), B);+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ const f = finger();+ f.down(select, centerOf(A));+ f.up(select, centerOf(A));+ // React renders the click's update in a microtask.+ await Promise.resolve();+ await Promise.resolve();+ act(() => {+ vi.runOnlyPendingTimers();+ });+ expect(String(getSelection())).toBe('Text a layout effect selects');+ getSelection()?.removeAllRanges();+ });++ it('a finger on the edge of a disabled button that has a tooltip runs nothing, not its enabled neighbour (FR2)', () => {+ const onCut = vi.fn();+ const view = render(+ <ButtonGroup label="Edit" data-testid="group">+ <Button label="Cut" onClick={onCut} data-testid="a" />+ <Button+ label="Copy"+ isDisabled+ tooltip="Nothing to copy"+ data-testid="b"+ />+ <Button label="Paste" data-testid="c" />+ </ButtonGroup>,+ );+ const copy = view.getByTestId('b');+ // Three touching 28 px buttons: Cut's target grows 8 px past its edge,+ // over the disabled Copy.+ 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(copy, {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(copy, {x: 30, y: 114});+ expect(paintOf(view.getByTestId('a'))).toBeNull();+ f.up(copy, {x: 30, y: 114});+ expect(onCut).not.toHaveBeenCalled();+ });++ it("leaves a finger's tap on a disabled button that has a tooltip its click, which opens the reason (component:Tooltip FR5)", () => {+ const view = render(+ <ButtonGroup label="Edit" data-testid="group">+ <Button label="Cut" data-testid="a" />+ <Button+ label="Copy"+ isDisabled+ tooltip="Nothing to copy"+ data-testid="b"+ />+ <Button label="Paste" data-testid="c" />+ </ButtonGroup>,+ );+ const copy = view.getByTestId('b');+ 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(copy, {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(copy, {x: 42, y: 114});+ const lift = f.up(copy, {x: 42, y: 114});+ // Nothing takes the press, so the browser still sends the click.+ expect(lift.defaultPrevented).toBe(false);+ });++ it("reads no box outside the group at a finger's press, on a page with 2,000 links", () => {+ const view = render(+ <div>+ {Array.from({length: 2000}, (_, i) => (+ <a key={i} href={`#link-${i}`}>+ Link {i}+ </a>+ ))}+ <ButtonGroup label="Edit" data-testid="group">+ <Button label="Cut" data-testid="a" />+ <Button label="Copy" data-testid="b" />+ <Button label="More" data-testid="c" />+ </ButtonGroup>+ </div>,+ );+ let pageReads = 0;+ view.container.querySelectorAll('a').forEach((link, i) => {+ const box = DOMRect.fromRect({+ x: (i % 40) * 30,+ y: 400,+ width: 24,+ height: 20,+ });+ link.getBoundingClientRect = () => {+ pageReads += 1;+ return box;+ };+ });+ const group = view.getByTestId('group');+ const a = view.getByTestId('a');+ place(group, GROUP);+ place(a, A);+ place(view.getByTestId('b'), B);+ place(view.getByTestId('c'), C);+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ pageReads = 0;+ // A finger on a button, then one on the group's hit layer below it. A+ // real finger sends each pointer event before its touch event.+ for (const [target, point] of [+ [a, centerOf(A)],+ [group, {x: 40, y: 137}],+ ] as const) {+ const f = finger();+ pointer('touch', 'pointerdown', target, point);+ f.down(target, point);+ pointer('touch', 'pointerup', target, point);+ f.up(target, point);+ }+ expect(pageReads).toBe(0);+ });++ it('skips a disabled button: no highlight, and a lift on it runs nothing (FR2)', () => {+ const {a, b, onB} = mount({isBDisabled: true});+ const f = finger();+ f.down(a, centerOf(A));+ f.move(a, centerOf(B));+ expect(paintOf(b)).toBeNull();+ expect(paintOf(a)).toBeNull();+ f.up(a, centerOf(B));+ expect(onB).not.toHaveBeenCalled();+ });++ it('leaves a menu trigger in the group untracked: it carries no marker, as a menu keeps its own opening (spec:AST-094 FR29)', () => {+ const {a, c} = mount({isCMenuTrigger: true});+ expect(isPressGroupItem(a)).toBe(true);+ expect(isPressGroupItem(c)).toBe(false);+ });++ it('tracks a member that opens a dialog: it carries the marker, and a slide lifted on it runs it (family:action-groups: only menus keep their own opening)', () => {+ const {a, c, onA, onC} = mount({cHasPopup: 'dialog'});+ expect(isPressGroupItem(c)).toBe(true);+ const f = finger();+ f.down(a, centerOf(A));+ f.move(a, centerOf(C));+ f.up(a, centerOf(C));+ expect(onC).toHaveBeenCalledTimes(1);+ expect(onA).not.toHaveBeenCalled();+ });++ it('tracks a member that opens a grid or a tree, as any button', () => {+ for (const popup of ['grid', 'tree'] as const) {+ const {c, unmount} = mount({cHasPopup: popup});+ expect(isPressGroupItem(c)).toBe(true);+ unmount();+ }+ });++ it('leaves a menu-like trigger untracked: `aria-haspopup` of true or listbox, as menu', () => {+ for (const popup of ['true', 'listbox'] as const) {+ const {c, unmount} = mount({cHasPopup: popup});+ expect(isPressGroupItem(c)).toBe(false);+ unmount();+ }+ });++ it("a finger slid from Cut that lifts just inside a menu trigger runs nothing: Cut's target does not reach into the trigger's own (spec:AST-094 FR42)", () => {+ const onCut = vi.fn();+ const onMore = vi.fn();+ const view = render(+ <ButtonGroup label="Edit" data-testid="group">+ <Button label="Cut" onClick={onCut} data-testid="a" />+ <Button+ label="More"+ aria-haspopup="menu"+ onClick={onMore}+ data-testid="more"+ />+ </ButtonGroup>,+ );+ const cut = view.getByTestId('a');+ const more = view.getByTestId('more');+ // Two 32 px buttons 4 px apart: grown toward 44 px, Cut's target would+ // reach 2 px into More, which the group does not track.+ place(view.getByTestId('group'), {+ left: 0,+ top: 100,+ width: 68,+ height: 32,+ });+ place(cut, {left: 0, top: 100, width: 32, height: 32});+ place(more, {left: 36, top: 100, width: 32, height: 32});+ act(() => {+ vi.advanceTimersToNextFrame();+ });+ const f = finger();+ f.down(cut, {x: 16, y: 116});+ expect(paintOf(cut)).toBe('on');+ f.move(cut, {x: 37, y: 116});+ expect(paintOf(cut)).not.toBe('on');+ f.up(cut, {x: 37, y: 116});+ expect(onCut).not.toHaveBeenCalled();+ });++ it('leaves a menu trigger its own click: the group does not take a press that lands on it (spec:AST-094 FR29)', () => {+ const {c, onC} = mount({isCMenuTrigger: true});+ const f = finger();+ f.down(c, centerOf(C));+ f.up(c, centerOf(C));+ // The browser's own click for that tap reaches the trigger.+ c.dispatchEvent(+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 1}),+ );+ expect(onC).toHaveBeenCalledTimes(1);+ });++ it("leaves a menu trigger a mouse's click too", () => {+ finePrimaryPointer();+ const {c, onC} = mount({isCMenuTrigger: true});+ pointer('mouse', 'pointerdown', c, centerOf(C));+ pointer('mouse', 'pointerup', c, centerOf(C));+ c.dispatchEvent(+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 1}),+ );+ expect(onC).toHaveBeenCalledTimes(1);+ });++ describe('touching buttons take no area from each other (FR5)', () => {+ // 28 px buttons sit side by side at x = 0, 80 and 160. A finger's target+ // grows 8 px above and below each, and none grows into a neighbour.+ const TALL = 28;+ function mountTouching() {+ const view = mount();+ place(view.group, {left: 0, top: 100, width: 240, height: TALL});+ place(view.a, {left: 0, top: 100, width: 80, height: TALL});+ place(view.b, {left: 80, top: 100, width: 80, height: TALL});+ place(view.c, {left: 160, top: 100, width: 80, height: TALL});+ return view;+ }+ const tapAt = (target: Element, point: Point) => {+ const f = finger();+ f.down(target, point);+ f.up(target, point);+ };++ it('a finger at x = 82 runs only the middle button, and at x = 78 only the first', () => {+ const {group, onA, onB, onC} = mountTouching();+ tapAt(group, {x: 82, y: 114});+ expect([onA, onB, onC].map(fn => fn.mock.calls.length)).toEqual([+ 0, 1, 0,+ ]);+ tapAt(group, {x: 78, y: 114});+ expect([onA, onB, onC].map(fn => fn.mock.calls.length)).toEqual([+ 1, 1, 0,+ ]);+ });++ it('a finger 8 px below a button still counts for that button, and 9 px below for none', () => {+ const {group, onA, onB, onC} = mountTouching();+ tapAt(group, {x: 120, y: 100 + TALL + 8});+ expect([onA, onB, onC].map(fn => fn.mock.calls.length)).toEqual([+ 0, 1, 0,+ ]);+ tapAt(group, {x: 120, y: 100 + TALL + 9});+ expect([onA, onB, onC].map(fn => fn.mock.calls.length)).toEqual([+ 0, 1, 0,+ ]);+ });+ });++ describe('the 44 px touch target (FR5)', () => {+ // 4 px below Cut: outside its 32 px box, inside the 44 px it grows to.+ const BELOW_A = {x: 40, y: 136};++ it('a finger just past a small button, inside its 44 px target, presses that button', () => {+ const {group, a, onA} = mount();+ const f = finger();+ f.down(group, BELOW_A);+ expect(paintOf(a)).toBe('on');+ f.up(group, BELOW_A);+ expect(onA).toHaveBeenCalledTimes(1);+ });++ it('a finger past the 44 px target presses nothing', () => {+ const {group, a, onA} = mount();+ const f = finger();+ f.down(group, {x: 40, y: 140});+ expect(paintOf(a)).toBeNull();+ f.up(group, {x: 40, y: 140});+ expect(onA).not.toHaveBeenCalled();+ });++ it('a mouse under a fine pointer gets no growth: the same point presses nothing', () => {+ finePrimaryPointer();+ const {group, a, onA} = mount();+ pointer('mouse', 'pointerdown', group, BELOW_A);+ expect(paintOf(a)).toBeNull();+ pointer('mouse', 'pointerup', group, BELOW_A);+ expect(onA).not.toHaveBeenCalled();+ });+ });+});diff --git a/packages/core/src/ButtonGroup/__tests__/ButtonGroupTracking.interaction.browser.spec.ts b/packages/core/src/ButtonGroup/__tests__/ButtonGroupTracking.interaction.browser.spec.tsnew file mode 100644index 0000000000..2ea581b6e9--- /dev/null+++ b/packages/core/src/ButtonGroup/__tests__/ButtonGroupTracking.interaction.browser.spec.ts@@ -0,0 +1,522 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ButtonGroupTracking.interaction.browser.spec.ts+ * @input The ButtonGroup SlideAcross story, driven by real touches (the+ * interaction harness's touch driver), a real mouse and the keyboard+ * @output Real-browser evidence that a button group tracks a held pointer+ * across its buttons (`family:action-groups` FR1–FR5). A slide runs the+ * button lifted on, and a lift outside runs nothing. A finger's target+ * reaches 44 px through the group's hit layer, and a mouse's does not.+ * Under a mouse, only the highlighted button looks pressed. The keyboard is+ * unchanged.+ * @position Beside ButtonGroupTracking.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-buttongroup--slide-across';++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: 'Edit actions'});+ await expect(group).toBeVisible();+ const button = (name: string) => group.getByRole('button', {name});+ return {+ group,+ cut: button('Cut'),+ copy: button('Copy'),+ paste: button('Paste'),+ log: page.getByTestId('slide-log'),+ };+}++/**+ * A point just below Cut: outside its box, inside the 44 px a finger's+ * target reaches. That is half the shortfall below a small button, less 1 px.+ */+async function justBelow(button: Locator): Promise<Point> {+ const box = await button.boundingBox();+ if (box == null) {+ throw new Error('no box');+ }+ expect(box.height).toBeLessThan(44);+ return {+ x: box.x + box.width / 2,+ y: box.y + box.height + (44 - box.height) / 2 - 1,+ };+}++/** The accessible name of the group the topmost element at `point` is in. */+const groupAt = async (page: Page, point: Point) =>+ page.evaluate(({x, y}) => {+ const element = document.elementFromPoint(x, y);+ return (+ element?.closest('[role="group"]')?.getAttribute('aria-label') ?? null+ );+ }, point);++test('a finger that presses Cut and slides to Paste runs Paste, once (family:action-groups FR1)', async ({+ page,+}) => {+ const {cut, paste, log} = await open(page);+ const driver = await touchDriver(page);+ await driver.play(slide(await centerOf(cut), await centerOf(paste)));+ await expect(log).toHaveText('Pressed: Paste');+});++/** 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 Cut to Paste, Paste has focus, as a tap on it leaves it (family:action-groups FR1)', async ({+ page,+}) => {+ const {cut, paste, log} = await open(page);+ const driver = await touchDriver(page);+ await driver.play(slide(await centerOf(cut), await centerOf(paste)));+ await expect(log).toHaveText('Pressed: Paste');+ expect(await focusedName(page)).toBe('Paste');+});++test('a finger tap on Copy leaves Copy with focus, as a tap on any button does (family:action-groups FR1)', async ({+ page,+}) => {+ const {copy, log} = await open(page);+ const driver = await touchDriver(page);+ await driver.play(tap(await centerOf(copy), {holdMs: 60}));+ await expect(log).toHaveText('Pressed: Copy');+ expect(await focusedName(page)).toBe('Copy');+});++test('a finger lifted outside the group runs nothing (family:action-groups FR3)', async ({+ page,+}) => {+ const {group, cut, log} = 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(cut), {+ 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);+ await expect(log).toHaveText('Nothing pressed');+});++test("under a finger a small button's target reaches 44 px: the point just below it lands on the group, and a tap there runs it (family:action-groups FR5)", async ({+ page,+}) => {+ const {cut, log} = await open(page);+ const below = await justBelow(cut);+ // The hit layer's insets are measured in the frame after the group shows.+ await expect.poll(async () => groupAt(page, below)).toBe('Edit actions');+ const driver = await touchDriver(page);+ await driver.play(tap(below));+ await expect(log).toHaveText('Pressed: Cut');+});++test('under a finger a group wider than its buttons takes only presses their targets hold: a tap beside them keeps its click (family:action-groups FR5)', async ({+ page,+}) => {+ const {group, cut, paste, log} = await open(page);+ const root = await group.boundingBox();+ const first = await cut.boundingBox();+ const last = await paste.boundingBox();+ if (root == null || first == null || last == null) {+ throw new Error('no box');+ }+ // The story's column stretches the root past its last button.+ expect(first.width).toBeGreaterThan(0);+ expect(last.height).toBeGreaterThan(0);+ expect(root.x + root.width - (last.x + last.width)).toBeGreaterThan(60);+ // The hit layer is up: just below Cut is the group's.+ await expect+ .poll(async () => groupAt(page, await justBelow(cut)))+ .toBe('Edit actions');+ const x = root.x + root.width - 20;+ const beside = {x, y: root.y + root.height / 2};+ const below = {x, y: root.y + root.height + 4};+ // The layer covers only the buttons' targets: below the empty part is not+ // the group.+ expect(await groupAt(page, below)).toBeNull();+ // Each lift's final default, read after its dispatch ends.+ await page.evaluate(() => {+ const lifts: boolean[] = [];+ Object.assign(window, {lifts});+ window.addEventListener('touchend', event => {+ setTimeout(() => lifts.push(event.defaultPrevented));+ });+ });+ const driver = await touchDriver(page);+ await driver.play(tap(beside));+ await driver.play(tap(below));+ await frames(page, 4);+ // Nothing took either press, so the browser's click for each still runs.+ expect(+ await page.evaluate(() => (window as unknown as {lifts: boolean[]}).lifts),+ ).toEqual([false, false]);+ await expect(log).toHaveText('Nothing pressed');+});++test("under a finger the end buttons' targets reach past the group, and a hidden member grows nothing (spec:AST-094 FR42)", async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-buttongroup--icon-only');+ const group = page.getByRole('group', {name: 'Text formatting'});+ const first = await group.getByRole('button', {name: 'Bold'}).boundingBox();+ const last = await group+ .getByRole('button', {name: 'Underline'})+ .boundingBox();+ if (first == null || last == null) {+ throw new Error('no box');+ }+ expect(first.width).toBeLessThan(44);+ const middle = first.y + first.height / 2;+ for (const point of [+ {x: first.x - 3, y: middle},+ {x: last.x + last.width + 3, y: middle},+ ]) {+ await expect.poll(async () => groupAt(page, point)).toBe('Text formatting');+ }+ // A hidden member's empty box sits at the viewport's corner and grows+ // nothing: nothing of the group lies over a link far above it.+ const above = await group.evaluate(root => {+ const link = root.ownerDocument.createElement('a');+ link.href = '#above';+ link.textContent = 'Above';+ link.style.cssText = 'display:block;height:20px;margin-bottom:100px';+ root.before(link);+ root+ .querySelector<HTMLElement>('[aria-label="Italic"]')+ ?.style.setProperty('display', 'none');+ const box = link.getBoundingClientRect();+ return {x: box.left + 20, y: box.top + 10};+ });+ // The hit area re-measures in the frames after the group resizes.+ await frames(page, 6);+ const link = await page.getByRole('link', {name: 'Above'}).boundingBox();+ expect(link?.width ?? 0).toBeGreaterThan(0);+ expect(link?.height ?? 0).toBeGreaterThan(0);+ // A finger there lands on the link itself, not on the group's hit area.+ await expect+ .poll(async () =>+ page.evaluate(+ ({x, y}) => document.elementFromPoint(x, y)?.textContent ?? '',+ above,+ ),+ )+ .toBe('Above');+});++test("the selection that the lifted button's own click makes stays, after a tap and after a slide (spec:AST-094 FR41)", async ({+ page,+}) => {+ const {cut, copy, log} = await open(page);+ await page.evaluate(() => {+ const paragraph = document.createElement('p');+ paragraph.textContent = 'Text the Cut action selects';+ document.body.prepend(paragraph);+ const cutButton = [...document.querySelectorAll('button')].find(+ button => button.textContent === 'Cut',+ );+ cutButton?.addEventListener('click', () => {+ getSelection()?.selectAllChildren(paragraph);+ });+ });+ const selected = async () => page.evaluate(() => String(getSelection()));+ const driver = await touchDriver(page);+ const at = await centerOf(cut);+ await driver.play(tap(at));+ await expect(log).toHaveText('Pressed: Cut');+ // Past the lift's click and the tasks after it.+ await frames(page, 4);+ expect(await selected()).toBe('Text the Cut action selects');+ await page.evaluate(() => getSelection()?.removeAllRanges());+ await driver.play(slide(await centerOf(copy), at));+ await expect(log).toHaveText('Pressed: Cut, Cut');+ await frames(page, 4);+ expect(await selected()).toBe('Text the Cut action selects');+});++test('a menu trigger in the group keeps its own opening: a tap on it opens its menu (spec:AST-094 FR29)', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-buttongroup--with-dropdown-menu');+ const trigger = page.getByRole('button', {name: 'Allow options'});+ await expect(trigger).toBeVisible();+ // The engine's own tap path: WebKit synthesises the click only from it,+ // and the trigger opens on that click.+ const driver = await touchDriver(page);+ await driver.tap(await centerOf(trigger));+ await expect(+ page.getByRole('menuitem', {name: 'Always allow'}),+ ).toBeVisible();+});++/**+ * 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 button's own edges are the button's: the group's hit layer lies below its buttons", async ({+ page,+}) => {+ await openStory(page, storybook(), STORY);+ await expect(page.getByRole('group').first()).toBeVisible();+ // Each button'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).+ 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 [+ 'core-buttongroup--horizontal',+ 'core-buttongroup--with-dropdown-menu',+ ]) {+ 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,+ }) => {+ // Stories that main ships too, so this case runs on a build of main.+ for (const story of [+ 'core-buttongroup--horizontal',+ 'core-buttongroup--with-dropdown-menu',+ ]) {+ 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's target does not grow: the point just below a small button is not the group", async ({+ page,+ }) => {+ const {cut} = await open(page);+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ const below = await justBelow(cut);+ // Give a hit-area measurement its frames: a fine pointer gets none.+ await frames(page, 4);+ expect(await groupAt(page, below)).toBeNull();+ });++ test('a mouse press on Cut released on Paste runs nothing, as a native button does: only Cut stays pressed (family:action-groups FR1)', async ({+ page,+ }) => {+ const {group, cut, paste, log} = await open(page);+ const from = await centerOf(cut);+ const to = await centerOf(paste);+ await page.mouse.move(from.x, from.y);+ await page.mouse.down();+ await page.mouse.move(to.x, to.y, {steps: 8});+ expect(await cut.evaluate(el => el.matches(':active'))).toBe(true);+ expect(await paste.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);+ await expect(log).toHaveText('Nothing pressed');+ });++ test("a click on Cut keeps the page's text selection, so a copy or cut action has text to act on (spec:AST-094 FR41)", async ({+ page,+ }) => {+ const {cut, log} = await open(page);+ const text = 'Text a Cut or Copy action reads';+ await page.evaluate(probe => {+ const paragraph = document.createElement('p');+ paragraph.textContent = probe;+ document.body.prepend(paragraph);+ const range = document.createRange();+ range.selectNodeContents(paragraph);+ const selection = getSelection();+ selection?.removeAllRanges();+ selection?.addRange(range);+ }, text);+ const selected = async () => page.evaluate(() => String(getSelection()));+ expect(await selected()).toBe(text);+ const at = await centerOf(cut);+ await page.mouse.click(at.x, at.y);+ await expect(log).toHaveText('Pressed: Cut');+ expect(await selected()).toBe(text);+ });++ test('the selection that the clicked button’s own click makes stays', async ({+ page,+ }) => {+ const {cut, log} = await open(page);+ const text = 'Text the Cut action selects';+ await page.evaluate(probe => {+ const paragraph = document.createElement('p');+ paragraph.textContent = probe;+ document.body.prepend(paragraph);+ const cutButton = [...document.querySelectorAll('button')].find(+ button => button.textContent === 'Cut',+ );+ cutButton?.addEventListener('click', () => {+ const range = document.createRange();+ range.selectNodeContents(paragraph);+ getSelection()?.removeAllRanges();+ getSelection()?.addRange(range);+ });+ }, text);+ const selected = async () => page.evaluate(() => String(getSelection()));+ const at = await centerOf(cut);+ await page.mouse.click(at.x, at.y);+ await expect(log).toHaveText('Pressed: Cut');+ // Past the press's own mouseup and click, and the task after them.+ await frames(page, 4);+ expect(await selected()).toBe(text);+ });++ test('holding Space on a focused button still paints its pressed look (the keyboard is unchanged)', async ({+ page,+ }) => {+ const {cut} = await open(page);+ await cut.focus();+ await page.keyboard.down('Space');+ await expect+ .poll(async () =>+ cut.evaluate(el => getComputedStyle(el).backgroundImage),+ )+ .not.toBe('none');+ await page.keyboard.up('Space');+ });++ test('a menu trigger in the group keeps its own opening: a click on it opens its menu', async ({+ page,+ }) => {+ await openStory(page, storybook(), 'core-buttongroup--with-dropdown-menu');+ await page.getByRole('button', {name: 'Allow options'}).click();+ await expect(+ page.getByRole('menuitem', {name: 'Always allow'}),+ ).toBeVisible();+ });++ test('the keyboard is unchanged: Space and Enter on a focused button run it once each', async ({+ page,+ }) => {+ const {cut, log} = await open(page);+ await cut.focus();+ await page.keyboard.press('Space');+ await expect(log).toHaveText('Pressed: Cut');+ await page.keyboard.press('Enter');+ await expect(log).toHaveText('Pressed: Cut, Cut');+ });+});diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex b33c453243..b7fea7a022 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -77,6 +77,7 @@ import type {MenuPressPointerType} from '../hooks/menuPressGesture';import {useTypeahead} from '../hooks/useTypeahead';import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';import {returnFocusForLastInput} from '../utils/focusReturn';+import {PressGroupContext} from '../hooks/pressGroupContext';import {useMenuOverflow} from './useMenuOverflow';import {MenuRegionsContext} from './menuRegionsContext';import {moveRegionsTab} from './menuRegionStops';@@ -1828,19 +1829,25 @@ export function DropdownMenu(props: DropdownMenuProps) {props.items !== undefined) {return (- <DropdownMenuBottomSheet- {...(sharedProps as DropdownMenuDataProps)}- presentation="bottom-sheet"- />+ <PressGroupContext value={null}>+ <DropdownMenuBottomSheet+ {...(sharedProps as DropdownMenuDataProps)}+ presentation="bottom-sheet"+ />+ </PressGroupContext>);}+ // In a group that tracks presses, the trigger keeps its own press and+ // opening, whatever its `aria-haspopup`.return (- <DropdownMenuPopover- {...sharedProps}- presentation="popover"- pressTouchModel={props.presentation === 'popover' ? 'pointer' : 'uikit'}- />+ <PressGroupContext value={null}>+ <DropdownMenuPopover+ {...sharedProps}+ presentation="popover"+ pressTouchModel={props.presentation === 'popover' ? 'pointer' : 'uikit'}+ />+ </PressGroupContext>);}diff --git a/packages/core/src/hooks/actionGroupTracker.test.ts b/packages/core/src/hooks/actionGroupTracker.test.tsindex 771238dc4b..d959d6b082 100644--- a/packages/core/src/hooks/actionGroupTracker.test.ts+++ b/packages/core/src/hooks/actionGroupTracker.test.ts@@ -25,6 +25,7 @@ import {reducedMotionFadeConsts} from '../motion/reducedMotion.stylex';import {PRESS_FADE_MS} from '../utils/pressGesture';import {createActionGroupTracker,+ measureActions,type ActionGroupTarget,type ActionGroupTrackerOptions,} from './actionGroupTracker';@@ -497,3 +498,27 @@ describe('createActionGroupTracker: options for other trackers', () => {expect(isClickGuardArmed(document)).toBe(true);});});++describe('measureActions', () => {+ it('measures the enabled actions the filter keeps, in document order, and reads each box once', () => {+ const group = document.createElement('div');+ const kept = action('Kept', {left: 0, top: 0, width: 40, height: 20});+ const off = action('Off', {left: 40, top: 0, width: 40, height: 20});+ off.button.disabled = true;+ const other = action('Other', {left: 80, top: 0, width: 40, height: 20});+ const last = action('Last', {left: 120, top: 0, width: 40, height: 20});+ group.append(kept.button, off.button, other.button, last.button);+ const targets = measureActions(+ [null, group],+ '[data-action]',+ element => element !== other.button,+ );+ expect(targets).toEqual([+ {element: kept.button, left: 0, top: 0, right: 40, bottom: 20},+ {element: last.button, left: 120, top: 0, right: 160, bottom: 20},+ ]);+ expect(+ [kept, off, other, last].map(({rectSpy}) => rectSpy.mock.calls.length),+ ).toEqual([1, 0, 0, 1]);+ });+});diff --git a/packages/core/src/hooks/actionGroupTracker.ts b/packages/core/src/hooks/actionGroupTracker.tsindex 60d839139e..92feea68c4 100644--- a/packages/core/src/hooks/actionGroupTracker.ts+++ b/packages/core/src/hooks/actionGroupTracker.ts@@ -5,7 +5,8 @@* @input The tracked elements, the action selector and hit expansion, and the* press paint and the press controller's fade clock* @output createActionGroupTracker, ActionGroupTracker,- * ActionGroupTrackerOptions, ActionGroupTarget+ * ActionGroupTrackerOptions, ActionGroupTarget, measureActions (the actions+ * the tracker tracks, measured) and DISABLED_SELECTOR (the actions it skips)* @position Internal core tracker for a held finger that slides across a* group of actions. Gesture recognizers drive it.*@@ -17,7 +18,7 @@ import {armClickGuard} from '../utils/clickGuard';import {PRESSED_ATTRIBUTE, pressFadeMs} from '../utils/pressFeedback';/** An action that is not enabled takes no highlight and does not run. */-const DISABLED = ':disabled, [aria-disabled="true"]';+export const DISABLED_SELECTOR = ':disabled, [aria-disabled="true"]';/** A target the tracker measured: its element and viewport rect, px. */export interface ActionGroupTarget {@@ -28,11 +29,38 @@ export interface ActionGroupTarget {readonly bottom: number;}+/**+ * The actions under `roots` that `itemSelector` selects, that are enabled and+ * that `isItem` keeps, in document order. Each box is read once.+ */+export function measureActions(+ roots: Iterable<Element | null | undefined>,+ itemSelector: string,+ isItem?: (element: HTMLElement) => boolean,+): ActionGroupTarget[] {+ const targets: ActionGroupTarget[] = [];+ for (const root of roots) {+ if (root == null) {+ continue;+ }+ for (const element of root.querySelectorAll<HTMLElement>(itemSelector)) {+ if (element.matches(DISABLED_SELECTOR) || isItem?.(element) === false) {+ continue;+ }+ const {left, top, right, bottom} = element.getBoundingClientRect();+ targets.push({element, left, top, right, bottom});+ }+ }+ return targets;+}+export interface ActionGroupTrackerOptions {/** The elements whose actions are tracked, read when a press begins. */roots: () => Iterable<Element | null | undefined>;/** Selects the actions inside the roots. */itemSelector: string;+ /** Keeps only the actions this accepts among those `itemSelector` selects. */+ isItem?: (element: HTMLElement) => boolean;/** How far outside an action the finger keeps it highlighted, px. */highlightExpansion: number;/**@@ -221,27 +249,8 @@ export function createActionGroupTracker(};const measure = (): TrackedAction[] => {- const {roots, itemSelector} = getOptions();- const next: TrackedAction[] = [];- for (const root of roots()) {- if (root == null) {- continue;- }- for (const element of root.querySelectorAll<HTMLElement>(itemSelector)) {- if (element.matches(DISABLED)) {- continue;- }- const rect = element.getBoundingClientRect();- next.push({- element,- left: rect.left,- top: rect.top,- right: rect.right,- bottom: rect.bottom,- });- }- }- return next;+ const {roots, itemSelector, isItem} = getOptions();+ return measureActions(roots(), itemSelector, isItem);};const actionAt = (x: number, y: number): HTMLElement | null => {@@ -322,7 +331,7 @@ export function createActionGroupTracker(return null;}release(lifted);- if (lifted.matches(DISABLED)) {+ if (lifted.matches(DISABLED_SELECTOR)) {return null;}const {onActivate, onActivated, swallowsNativeClick} = getOptions();diff --git a/packages/core/src/hooks/pressGroupContext.ts b/packages/core/src/hooks/pressGroupContext.tsindex 0fe3719fce..b58d58c342 100644--- a/packages/core/src/hooks/pressGroupContext.ts+++ b/packages/core/src/hooks/pressGroupContext.ts@@ -4,18 +4,27 @@/*** @file pressGroupContext.ts- * @input Nothing- * @output PressGroupContext: true inside a group whose own tracker paints- * its actions' press- * @position Internal; not exported from the hooks entry. AlertDialog- * provides it around its tracked actions, and Button reads it.+ * @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+ * @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.*/-import {createContext} from 'react';+import {createLayerScopedContext} from '../Layer/layerScopedContext';++// Button reads the marker here, not from its private StyleX module: a+// swizzled Button imports each StyleX module by its public path.+export {pressGroupItemProps} from '../privateAttributes/pressGroupItem.stylex';/**- * True inside a group whose tracker paints a pointer's press on its actions.- * Those actions take no `:active` paint, so one press never lights two.+ * The pointer types a group's tracker follows on its actions, such as+ * `['touch', 'pen']`, or null outside a tracking group. Those actions take no+ * `:active` paint, so one press never lights two.*/-export const PressGroupContext = createContext(false);+export const PressGroupContext =+ createLayerScopedContext<ReadonlyArray<string> | null>(null);PressGroupContext.displayName = 'PressGroupContext';diff --git a/packages/core/src/hooks/useActionGroupTracking.test.tsx b/packages/core/src/hooks/useActionGroupTracking.test.tsxindex 05d4fe4320..3d7fd52668 100644--- a/packages/core/src/hooks/useActionGroupTracking.test.tsx+++ b/packages/core/src/hooks/useActionGroupTracking.test.tsx@@ -337,6 +337,85 @@ describe('useActionGroupTracking', () => {expect(createActionGroupTracker).toHaveBeenCalledTimes(1);});+ /** A caller's resolution that always picks the second action. */+ const pickSecond = () =>+ vi.fn(+ (+ _x: number,+ _y: number,+ targets: ReadonlyArray<ActionGroupTrackerModule.ActionGroupTarget>,+ _neighbours: ReadonlyArray<ActionGroupTrackerModule.ActionGroupTarget>,+ ) => targets[1]?.element ?? null,+ );++ it("picks a finger's action through the caller's resolveTarget, handing it the press's neighbours", () => {+ const resolveTarget = pickSecond();+ const {cancel, del, message, onCancel, onDelete} = mount({+ options: {resolveTarget},+ });+ const f = finger();+ // On the message, outside both actions, where no margin reaches.+ f.down(message, centerOf(MESSAGE));+ expect(paintOf(del)).toBe('on');+ expect(paintOf(cancel)).toBeNull();+ f.up(message, centerOf(MESSAGE));+ expect(onDelete).toHaveBeenCalledTimes(1);+ expect(onCancel).not.toHaveBeenCalled();+ // No action is disabled, so the press has no neighbours.+ expect(resolveTarget).toHaveBeenCalledWith(+ centerOf(MESSAGE).x,+ centerOf(MESSAGE).y,+ expect.any(Array),+ [],+ );+ });++ it("hands the caller's resolveTarget a disabled action as a neighbour", () => {+ const resolveTarget = pickSecond();+ const {cancel, del} = mount({+ isDeleteDisabled: true,+ options: {resolveTarget},+ });+ const f = finger();+ f.down(cancel, centerOf(CANCEL));+ const neighbours = resolveTarget.mock.calls[0]?.[3] as+ ReadonlyArray<ActionGroupTrackerModule.ActionGroupTarget> | undefined;+ expect(neighbours?.map(neighbour => neighbour.element)).toEqual([del]);+ f.up(cancel, centerOf(CANCEL));+ });++ it("lets a mouse hit-test the exact rects even with a resolveTarget, which is a finger's (family:action-groups FR5)", () => {+ const resolveTarget = pickSecond();+ const {cancel, del, message, onCancel, onDelete} = mount({+ options: {resolveTarget},+ });+ const mouse = (type: string, point: {x: number; y: number}) => {+ time += 16;+ const event = new PointerEvent(type, {+ bubbles: true,+ cancelable: true,+ pointerId: 1,+ pointerType: 'mouse',+ isPrimary: true,+ button: 0,+ buttons: type === 'pointerup' ? 0 : 1,+ clientX: point.x,+ clientY: point.y,+ });+ Object.defineProperty(event, 'timeStamp', {value: time});+ message.dispatchEvent(event);+ };+ // A mouse beside a coarse primary pointer, on the message: outside both+ // actions it highlights nothing and runs nothing.+ mouse('pointerdown', centerOf(MESSAGE));+ expect(paintOf(del)).toBeNull();+ expect(paintOf(cancel)).toBeNull();+ mouse('pointerup', centerOf(MESSAGE));+ expect(onDelete).not.toHaveBeenCalled();+ expect(onCancel).not.toHaveBeenCalled();+ expect(resolveTarget).not.toHaveBeenCalled();+ });+it("tracks a mouse under a fine pointer: a press on Delete slid to Cancel runs Cancel once, and the browser's own click runs nothing more (family:action-groups FR5)", () => {const {cancel, del, onCancel, onDelete} = mountFine();mouseOn(del, 'pointerdown', centerOf(DELETE));@@ -637,7 +716,7 @@ describe('useActionGroupTracking', () => {it('leaves a touch the caller rejects to the browser', () => {const {cancel, message, onCancel} = mount({- options: {shouldTrack: target => target !== message},+ options: {shouldTrack: touch => touch.target !== message},});const f = finger();f.down(message, {x: 50, y: 40});@@ -669,6 +748,29 @@ describe('useActionGroupTracking', () => {expect(onCancel).not.toHaveBeenCalled();});+ it("lights a mouse's press at once: a finger and a pen wait the content-touch delay", () => {+ restorePointer();+ restorePointer = pointerQuery(false).restore;+ const {del, cancel, onCancel} = mountInScroller();+ runAttachFrame();+ mouseOn(del, 'pointerdown', centerOf(DELETE));+ expect(paintOf(del)).toBe('on');+ mouseOn(del, 'pointermove', centerOf(CANCEL));+ expect(paintOf(cancel)).toBe('on');+ mouseOn(cancel, 'pointerup', centerOf(CANCEL));+ expect(onCancel).toHaveBeenCalledTimes(1);+ });++ it("leaves a pen's flick to the scroller, as a finger's: travel past the slop before the delay tracks nothing", () => {+ const {message, cancel, onCancel} = mountInScroller();+ pen(message, 'pointerdown', {x: 50, y: 40});+ pen(message, 'pointermove', {x: 50, y: 40 + UIKIT_PRESS.slop.value + 2});+ pen(message, 'pointermove', centerOf(CANCEL));+ expect(paintOf(cancel)).toBeNull();+ pen(message, 'pointerup', centerOf(CANCEL));+ expect(onCancel).not.toHaveBeenCalled();+ });+it('tracks once the finger has rested for the content-touch delay', () => {const {message, cancel, onCancel} = mountInScroller();const f = finger();diff --git a/packages/core/src/hooks/useActionGroupTracking.ts b/packages/core/src/hooks/useActionGroupTracking.tsindex fb07c7221a..15a8fc0073 100644--- a/packages/core/src/hooks/useActionGroupTracking.ts+++ b/packages/core/src/hooks/useActionGroupTracking.ts@@ -6,10 +6,13 @@* @file useActionGroupTracking.ts* @input A ref to a group of sibling actions, the actions' selector, and the* component's tracking constants- * @output Exports useActionGroupTracking and ActionGroupTrackingOptions+ * @output Exports useActionGroupTracking, ActionGroupTrackingOptions,+ * resolveNearestAction, the finger resolution of a group whose targets grow,+ * and measureNeighbours, the members that resolution must not reach into* @position Internal hook, not exported from the hooks entry. A long press* drives the shared action-group tracker (hooks/actionGroupTracker.ts) for- * a group that a held pointer slides across. AlertDialog consumes it.+ * a group that a held pointer slides across. AlertDialog and+ * useGroupPressTracking consume it.** SYNC: When modified, update useActionGroupTracking.test.tsx*/@@ -21,13 +24,20 @@ import {lockSelection} from '../utils/selectionLock';import type {GestureTouch, PointerKind} from '../gestures/types';import {useGestureRecognizer} from '../gestures/useGestureRecognizer';import {UIKIT_PRESS} from '../motion/uikit/gestures';+import {INTERACTIVE_SELECTOR, resolveHitTarget} from '../utils/hitArea';import {isIosWebKit} from '../utils/touchQueries';-import {createActionGroupTracker} from './actionGroupTracker';+import {+ createActionGroupTracker,+ DISABLED_SELECTOR,+ type ActionGroupTarget,+} from './actionGroupTracker';import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';export interface ActionGroupTrackingOptions {/** Selects the actions inside the tracked element. */itemSelector: string;+ /** Keeps only the actions this accepts among those `itemSelector` selects. */+ isItem?: (element: HTMLElement) => boolean;/** How long after touch-down the touched action highlights, ms. */highlightOnsetMs: number;/**@@ -35,10 +45,22 @@ export interface ActionGroupTrackingOptions {* pen hit-tests the actions' exact rects.*/highlightExpansion: number;+ /**+ * Picks the action under a finger, in place of the flat expansion. It gets+ * the actions measured when the press begins, and their neighbours: the+ * disabled actions and the members the group does not track. A mouse or a+ * pen hit-tests the exact rects.+ */+ resolveTarget?: (+ x: number,+ y: number,+ targets: ReadonlyArray<ActionGroupTarget>,+ neighbours: ReadonlyArray<ActionGroupTarget>,+ ) => HTMLElement | null;/** Pointers that are tracked; others keep the browser's click. @default every pointer */pointerTypes?: ReadonlyArray<PointerKind>;- /** A press whose target this rejects is not tracked. */- shouldTrack?: (target: unknown) => boolean;+ /** A press this rejects is not tracked, and its click stays the browser's. */+ shouldTrack?: (touch: GestureTouch) => boolean;/** Off, nothing is attached and nothing is tracked. @default true */isEnabled?: boolean;/**@@ -53,6 +75,62 @@ export interface ActionGroupTrackingOptions {const PRESS = UIKIT_PRESS;+const NO_TARGETS: ReadonlyArray<ActionGroupTarget> = [];++/**+ * The action under a finger: the nearest enabled action whose target, grown+ * toward 44 px, holds the point. A neighbour counts for nearness but+ * resolves to none. So nothing highlights over a disabled action, and no+ * grown target reaches into another member.+ */+export function resolveNearestAction(+ x: number,+ y: number,+ targets: ReadonlyArray<ActionGroupTarget>,+ neighbours: ReadonlyArray<ActionGroupTarget>,+): HTMLElement | null {+ const index = resolveHitTarget(+ x,+ y,+ neighbours.length === 0 ? targets : [...targets, ...neighbours],+ );+ return index >= 0 && index < targets.length ? targets[index].element : null;+}++/**+ * The members inside `root` that a finger must not reach through, with their+ * boxes: the disabled actions and every member the group does not track.+ */+export function measureNeighbours(+ root: HTMLElement | null,+ {+ itemSelector,+ isItem,+ }: Pick<ActionGroupTrackingOptions, 'itemSelector' | 'isItem'>,+): ReadonlyArray<ActionGroupTarget> {+ if (root == null) {+ return NO_TARGETS;+ }+ const isTracked = (element: HTMLElement) =>+ element.matches(itemSelector) && isItem?.(element) !== false;+ const neighbours: ActionGroupTarget[] = [];+ for (const element of root.querySelectorAll<HTMLElement>(+ `${itemSelector}, ${INTERACTIVE_SELECTOR}`,+ )) {+ // A tracked action is a neighbour only when it is disabled. An untracked+ // member inside a tracked action is part of that action.+ const host = element.parentElement?.closest<HTMLElement>(itemSelector);+ const isNeighbour = isTracked(element)+ ? element.matches(DISABLED_SELECTOR)+ : host == null || !root.contains(host) || !isTracked(host);+ if (isNeighbour) {+ const {left, top, right, bottom} = element.getBoundingClientRect();+ neighbours.push({element, left, top, right, bottom});+ }+ }+ return neighbours;+}+/** The ref handed to the recognizer while tracking is off: no element. */const DETACHED: RefObject<Element | null> = {current: null};@@ -90,14 +168,23 @@ export function useActionGroupTracking(// expansion; a mouse or a pen hit-tests the actions' exact rects.const pointerRef = useRef<PointerKind>('touch');const landedRef = useRef<Node | null>(null);+ // A finger press's neighbours, read once when it begins, for the caller's+ // `resolveTarget`. Nothing is read per move.+ const neighboursRef = useRef(NO_TARGETS);const [tracker] = useState(() =>createActionGroupTracker(() => ({roots: () => [ref.current],itemSelector: optionsRef.current.itemSelector,+ isItem: optionsRef.current.isItem,highlightExpansion:pointerRef.current === 'touch'? optionsRef.current.highlightExpansion: 0,+ ...fingerResolver(+ pointerRef.current,+ optionsRef.current.resolveTarget,+ neighboursRef.current,+ ),onActivate: optionsRef.current.onActivate,// The browser's own click for a press the group ran is taken, so the// action runs once. The gesture host swallows it for a press it claims.@@ -145,6 +232,11 @@ export function useActionGroupTracking(switch (recognizer.state) {case 'began': {const {x, y} = recognizer.location();+ neighboursRef.current =+ pointerRef.current === 'touch' &&+ optionsRef.current.resolveTarget != null+ ? measureNeighbours(ref.current, optionsRef.current)+ : NO_TARGETS;tracker.begin(x, y, {landed: landedRef.current});break;}@@ -166,21 +258,25 @@ export function useActionGroupTracking(pointerRef.current === 'touch'? !isIosWebKit(doc?.defaultView): beganOn != null && focusedBefore === beganOn;- const lifted = tracker.end();- // The lift runs the action's own click(), which moves no focus. So- // focus moves to the lifted action, unless its click moved focus.+ // The lifted action takes focus first, as a native press gives it+ // before the click. Then its click runs, so a click that moves focus+ // or selects text keeps its result.+ const toLift = tracker.highlighted;if (clickFocuses &&- lifted != null &&- lifted.isConnected &&- doc?.activeElement === focusedBefore &&- focusedBefore !== lifted+ toLift != null &&+ toLift.isConnected &&+ !toLift.matches(DISABLED_SELECTOR) &&+ focusedBefore !== toLift) {- lifted.focus({preventScroll: true, focusVisible: false});+ toLift.focus({preventScroll: true, focusVisible: false});}+ tracker.end();+ neighboursRef.current = NO_TARGETS;break;}case 'cancelled':+ neighboursRef.current = NO_TARGETS;tracker.cancel();break;case 'possible':@@ -198,21 +294,45 @@ export function useActionGroupTracking(}/**- * The recognizer's should-receive delegate. It also picks the press's clock.- * Inside a scroller the press waits the content-touch delay and fails past- * the slop, so the scroller takes a flick. Elsewhere it begins at once, with- * no movement limit.+ * A finger's resolver: the caller's `resolveTarget` with the press's+ * neighbours. Without one, and for a mouse or a pen, the tracker's own hit+ * test applies.+ */+function fingerResolver(+ pointer: PointerKind,+ resolve: ActionGroupTrackingOptions['resolveTarget'],+ neighbours: ReadonlyArray<ActionGroupTarget>,+): {+ resolveTarget?: (+ x: number,+ y: number,+ targets: ReadonlyArray<ActionGroupTarget>,+ ) => HTMLElement | null;+} {+ if (pointer !== 'touch' || resolve == null) {+ return {};+ }+ return {resolveTarget: (x, y, targets) => resolve(x, y, targets, neighbours)};+}++/**+ * The recognizer's should-receive delegate. It declines a press the caller+ * rejects. It also picks the press's clock. Inside a scroller a finger's or a+ * pen's press waits the content-touch delay and fails past the slop. So the+ * scroller takes a flick, and an iPad's Pencil scrolls a page too. A mouse, or+ * a press elsewhere, begins at once, with no movement limit.*/function receiveTouch(recognizer: LongPressGestureRecognizer,touch: GestureTouch,options: ActionGroupTrackingOptions,): boolean {- if (options.shouldTrack?.(touch.target) === false) {+ if (options.shouldTrack?.(touch) === false) {return false;}if (recognizer.numberOfTouches === 0) {- const isInsideScroller = touch.scroll?.isInsideScroller === true;+ const isInsideScroller =+ touch.pointerType !== 'mouse' && touch.scroll?.isInsideScroller === true;recognizer.minimumPressDuration = isInsideScroller? PRESS.contentTouchDelay.value: options.highlightOnsetMs;diff --git a/packages/core/src/hooks/useGroupPressTracking.ts b/packages/core/src/hooks/useGroupPressTracking.tsnew file mode 100644index 0000000000..2bef695c79--- /dev/null+++ b/packages/core/src/hooks/useGroupPressTracking.ts@@ -0,0 +1,154 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @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+ * @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+ * touchHitAreaStyles.layerBelowChildren. AlertDialog's tracking follows+ * GROUP_PRESS_POINTERS too.+ *+ * SYNC: When modified, update ButtonGroupTracking.test.tsx.+ */++import type {RefCallback, RefObject} from 'react';+import type {GestureTouch} from '../gestures/types';+import {isPressGroupItem} from '../privateAttributes/pressGroupItem.stylex';+import {groupGrowth} from '../utils/hitArea';+import {useTouchHitArea, type TouchHitAreaOptions} from '../utils/touchHitArea';+import {+ DISABLED_SELECTOR,+ measureActions,+ type ActionGroupTarget,+} from './actionGroupTracker';+import {+ measureNeighbours,+ resolveNearestAction,+ useActionGroupTracking,+} from './useActionGroupTracking';++/** What a member Button renders. The tracker keeps the marked ones. */+const MEMBER_ELEMENTS = 'button, a[href]';++/**+ * Whether `box` has an area. A hidden member's box is empty, at the+ * viewport's corner, so it neither tracks a press nor grows a target.+ */+function hasArea(box: Omit<ActionGroupTarget, 'element'>): boolean {+ return box.right > box.left && box.bottom > box.top;+}++/** Whether the group tracks `member`, read without its box. */+function isTrackedMember(member: Element): boolean {+ return isPressGroupItem(member) && !member.matches(DISABLED_SELECTOR);+}++/**+ * The tracked, enabled members with a box, each box read once. The tracker+ * measures its actions with the same function.+ */+function trackedTargets(group: HTMLElement): ActionGroupTarget[] {+ return measureActions([group], MEMBER_ELEMENTS, isTrackedMember).filter(+ hasArea,+ );+}++/**+ * The group's hit area. Each side grows as far as the members on that edge+ * would. The tracker reads the members when a press begins, so a press reads+ * nothing else on the page.+ */+const GROUP_HIT_AREA: TouchHitAreaOptions = {+ growth: (box, toLayout, group) =>+ groupGrowth(box, trackedTargets(group).map(toLayout)),+ checkAtPress: false,+};++/**+ * Whether the group takes `touch`'s press. It takes one on an enabled tracked+ * member. A press on a disabled member keeps its click, so its tooltip can+ * open. It takes a finger's press on its own box or hit layer only where a+ * member's grown target holds it. Any other press keeps its own click, so a+ * tap beside the members of a wide group reaches the page. A member the group+ * does not track, such as a menu trigger, keeps its own press. A group with+ * no box takes none.+ */+function takesPress(group: HTMLElement | null, touch: GestureTouch): boolean {+ const {target} = touch;+ // A node check, not `instanceof`: the group may render in another window.+ if (group == null || (target as Node | null)?.nodeType !== 1) {+ return false;+ }+ const box = group.getBoundingClientRect();+ if (box.width <= 0 || box.height <= 0) {+ return false;+ }+ if (target !== group) {+ const member = (target as Element).closest(MEMBER_ELEMENTS);+ return member != null && group.contains(member) && isTrackedMember(member);+ }+ return (+ touch.pointerType === 'touch' &&+ resolveNearestAction(+ touch.startX,+ touch.startY,+ trackedTargets(group),+ // The tracked members are read once above, so the neighbour test reads+ // only the others.+ measureNeighbours(group, {+ itemSelector: MEMBER_ELEMENTS,+ isItem: isTrackedMember,+ }),+ ) != null+ );+}++export interface GroupPressTracking {+ /**+ * Merge into the group's root: it keeps the hit layer's insets live. While+ * the group tracks presses, the root applies+ * `touchHitAreaStyles.layerBelowChildren` and is positioned, as the layer's+ * containing block.+ */+ readonly hitAreaRef: RefCallback<HTMLElement>;+}++/** The pointers a group's press slides for: a finger and a pen. */+export const GROUP_PRESS_POINTERS = ['touch', 'pen'] as const;++/**+ * Track a held finger or pen across the marked members of the group behind+ * `ref`, while `isEnabled`. The member under it highlights at once, and the+ * lift runs it through its own click. A finger picks the nearest member whose+ * grown target holds it.+ */+export function useGroupPressTracking(+ ref: RefObject<HTMLElement | null>,+ isEnabled: boolean,+): GroupPressTracking {+ useActionGroupTracking(ref, {+ itemSelector: MEMBER_ELEMENTS,+ // A disabled member is the tracker's neighbour. A hidden member has no box,+ // so it is no item.+ isItem: member =>+ isTrackedMember(member) && hasArea(member.getBoundingClientRect()),+ pointerTypes: GROUP_PRESS_POINTERS,+ highlightOnsetMs: 0,+ highlightExpansion: 0,+ resolveTarget: resolveNearestAction,+ shouldTrack: touch => takesPress(ref.current, touch),+ isEnabled,+ });+ // A finger's target grows toward 44 px through the hit layer, not the+ // members. A finger just past a small member lands on the layer, and the+ // tracker picks that member. The shared watch grows a target only under a+ // coarse primary pointer.+ const hitAreaRef = useTouchHitArea(isEnabled, GROUP_HIT_AREA);+ return {hitAreaRef};+}diff --git a/packages/core/src/privateAttributes/pressGroupItem.stylex.ts b/packages/core/src/privateAttributes/pressGroupItem.stylex.tsindex 98ce94f4c4..244025596a 100644--- a/packages/core/src/privateAttributes/pressGroupItem.stylex.ts+++ b/packages/core/src/privateAttributes/pressGroupItem.stylex.ts@@ -3,12 +3,13 @@* @file privateAttributes/pressGroupItem.stylex.ts* @input Nothing: the private press-group-item attribute* @output pressGroupItemProps, which marks an action a group's tracker- * follows with the pointers it follows, and isTrackedByGroup, which reads- * the mark+ * follows with the pointers it follows, and the readers isPressGroupItem+ * and isTrackedByGroup* @position Owner module of the private press-group-item attribute: the only- * file that writes its name. AlertDialog marks its actions, and the press- * controller (utils/pressFeedback.ts) leaves a press of those pointers to- * the group's tracker. No package entry exports it.+ * file that writes its name. AlertDialog's actions and a Button inside a+ * tracking group carry the mark. The press controller+ * (utils/pressFeedback.ts) leaves a press of those pointers to the group's+ * tracker. No package entry exports it.*/const PRESS_GROUP_ITEM = 'data-astryx-press-group-item';@@ -23,6 +24,11 @@ export function pressGroupItemProps(return {[PRESS_GROUP_ITEM]: pointerTypes.join(' ')};}+/** Whether `element` is an action that a group's tracker follows. */+export function isPressGroupItem(element: Element): boolean {+ return element.hasAttribute(PRESS_GROUP_ITEM);+}+/*** Whether a group's tracker paints the press on `element` or an ancestor: a* press of `pointerType`, or any press when it is null.diff --git a/packages/core/src/utils/hitArea.test.ts b/packages/core/src/utils/hitArea.test.tsindex 85a601f8b8..f366893c6b 100644--- a/packages/core/src/utils/hitArea.test.ts+++ b/packages/core/src/utils/hitArea.test.ts@@ -16,6 +16,7 @@ import path from 'node:path';import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import {clampedHitInsets,+ groupGrowth,HIT_INSET_PROPERTIES,type HitInsets,type HitRect,@@ -30,6 +31,47 @@ function rect(left: number, top: number, width: number, height: number) {return {left, top, right: left + width, bottom: top + height};}+describe('groupGrowth', () => {+ it('grows each side of a row as far as the member on that edge would, and a wide group by its narrow end members', () => {+ // Three 32 px toggles in a 104 × 32 row, 4 px apart.+ const row = rect(0, 100, 104, 32);+ const members = [+ rect(0, 100, 32, 32),+ rect(36, 100, 32, 32),+ rect(72, 100, 32, 32),+ ];+ expect(groupGrowth(row, members)).toEqual({+ top: 6,+ right: 6,+ bottom: 6,+ left: 6,+ });+ // A column of wide members grows only at its top and bottom.+ const column = rect(0, 0, 120, 64);+ expect(+ groupGrowth(column, [rect(0, 0, 120, 32), rect(0, 32, 120, 32)]),+ ).toEqual({top: 6, right: 0, bottom: 6, left: 0});+ // A row wider than its members shrinks past its last member, so it+ // covers only their targets: 32 px buttons ending 160 px short.+ expect(groupGrowth(rect(0, 100, 264, 32), members)).toEqual({+ top: 6,+ right: -154,+ bottom: 6,+ left: 6,+ });+ expect(groupGrowth(row, [])).toEqual(NO_HIT_INSETS);+ // The full growth it gives stops at a neighbour, as a control's does.+ expect(+ clampedHitInsets(+ row,+ [rect(-8, 100, 4, 32)],+ 44,+ groupGrowth(row, members),+ ).left,+ ).toBe(2);+ });+});+describe('clampedHitInsets', () => {it('grows a lone 24 px target to 44 px, centered', () => {expect(clampedHitInsets(rect(100, 100, 24, 24), [])).toEqual({@@ -323,6 +365,40 @@ describe('watchHitArea', () => {stops.forEach(stop => stop());});+ it("reads a group's growth from its members in its layout px, so a group in an opening layer keeps its insets", () => {+ // As above, the layer opens from half size about the page origin.+ const half = ({left, top, right, bottom}: HitRect) => ({+ left: left / 2,+ top: top / 2,+ right: right / 2,+ bottom: bottom / 2,+ });+ const group = byId('other');+ Object.assign(group.style, {+ width: '68px',+ height: '32px',+ boxSizing: 'border-box',+ });+ layOut(group, 68, 32);+ place(group, half(rect(200, 300, 68, 32)));+ place(byId('switch'), half(rect(100, 100, 24, 24)));+ place(byId('link'), half(rect(132, 100, 60, 24)));+ // Two 32 px members, each 6 px short of 44 on each axis.+ const members = [+ half(rect(200, 300, 32, 32)),+ half(rect(236, 300, 32, 32)),+ ];+ const heard: HitInsets[] = [];+ const stop = watchHitArea(group, insets => heard.push(insets), {+ growth: (box, toLayout) => groupGrowth(box, members.map(toLayout)),+ });+ show(group);+ flush();+ // At half size the members would read 16 px and grow 14 px.+ expect(heard).toEqual([{top: 6, right: 6, bottom: 6, left: 6}]);+ stop();+ });+it('measures nothing off screen', () => {const control = byId('switch');place(control, rect(100, 100, 24, 24));@@ -505,6 +581,31 @@ describe('watchHitArea', () => {stop();});+ it('reads nothing on the page at a finger’s press, and swallows no click, for a watch whose owner reads its own targets (checkAtPress off)', () => {+ const control = byId('switch');+ const link = byId('link');+ place(control, rect(100, 100, 24, 24));+ place(link, rect(400, 100, 60, 24));+ const stop = watchHitArea(control, () => {}, {checkAtPress: false});+ show(control);+ flush();+ // The link moved to 8 px away with nothing re-measuring yet.+ place(link, rect(132, 100, 60, 24));+ const read = vi.spyOn(link, 'getBoundingClientRect');+ const press = new Event('pointerdown', {bubbles: true});+ Object.assign(press, {pointerType: 'touch', clientX: 130, clientY: 112});+ control.dispatchEvent(press);+ expect(read).not.toHaveBeenCalled();+ const click = new MouseEvent('click', {+ bubbles: true,+ cancelable: true,+ detail: 1,+ });+ control.dispatchEvent(click);+ expect(click.defaultPrevented).toBe(false);+ stop();+ });+it('runs no observer or window listener for hit areas while the primary pointer is fine', () => {coarse = false;const constructed = vi.fn();diff --git a/packages/core/src/utils/hitArea.ts b/packages/core/src/utils/hitArea.tsindex 68113e5915..1fb8e1cd14 100644--- a/packages/core/src/utils/hitArea.ts+++ b/packages/core/src/utils/hitArea.ts@@ -8,8 +8,10 @@* the element and the page around it)* @output The touch hit area: how far a target may grow toward 44 px on each* side without taking a tap that is nearer a neighbour. `clampedHitInsets`- * and `resolveHitTarget` answer from rects; `watchHitArea` keeps a control's- * insets live where the primary pointer is coarse+ * and `resolveHitTarget` answer from rects. `watchHitArea` keeps a control's+ * insets live where the primary pointer is coarse. `groupGrowth` sizes a+ * group's box from its edge members, and shrinks a side the members do not+ * reach. `INTERACTIVE_SELECTOR` names what a touch can land on* @position Core-internal utility, not exported from `@astryxdesign/core/utils`.* Groups that measure their actions at press start pass `resolveHitTarget`;* a standalone control writes `watchHitArea`'s insets to an invisible@@ -96,6 +98,43 @@ function growth(rect: HitRect, minSize: number): HitInsets {return {top: y, right: x, bottom: y, left: x};}+/**+ * How far a group's box grows on each side before any neighbour stops it: as+ * far as its members on that edge grow toward `minSize`. So an end member's+ * target reaches past the group, as a lone control's would. A side that+ * reaches past its edge member shrinks to that member's grown edge, a+ * negative growth. So a box wider than its members covers only their targets.+ */+export function groupGrowth(+ group: HitRect,+ members: ReadonlyArray<HitRect>,+ minSize: number = MIN_TOUCH_TARGET,+): HitInsets {+ if (members.length === 0) {+ return NO_HIT_INSETS;+ }+ const insets = {+ top: -Infinity,+ right: -Infinity,+ bottom: -Infinity,+ left: -Infinity,+ };+ for (const member of members) {+ const own = growth(member, minSize);+ insets.top = Math.max(insets.top, own.top - (member.top - group.top));+ insets.right = Math.max(+ insets.right,+ own.right - (group.right - member.right),+ );+ insets.bottom = Math.max(+ insets.bottom,+ own.bottom - (group.bottom - member.bottom),+ );+ insets.left = Math.max(insets.left, own.left - (member.left - group.left));+ }+ return insets;+}+/*** How far `target` may grow on each side: toward `minSize` on each axis,* centered, and on each side no further than half the gap to a neighbour.@@ -103,6 +142,7 @@ function growth(rect: HitRect, minSize: number): HitInsets {* reach into the other's half of the gap, or their full areas would meet; it* stops the side facing it, or,* for a neighbour apart on both axes (diagonal), the side with the larger gap.+ * `full` replaces the centered growth, as `groupGrowth` gives a group's box.* That decision rests on the two rects alone, so the neighbour decides the* same about this target and the two areas never overlap. A neighbour* overlapping the target (an ancestor, an overlay) is not beside it and stops@@ -112,9 +152,14 @@ export function clampedHitInsets(target: HitRect,neighbours: ReadonlyArray<HitRect>,minSize: number = MIN_TOUCH_TARGET,+ full: HitInsets = growth(target, minSize),): HitInsets {- const full = growth(target, minSize);- if (full.top === 0 && full.left === 0) {+ if (+ full.top === 0 &&+ full.right === 0 &&+ full.bottom === 0 &&+ full.left === 0+ ) {return NO_HIT_INSETS;}const insets = {...full};@@ -212,7 +257,7 @@ export function writeHitInsets(element: HTMLElement, insets: HitInsets): void {// --- Live controls -----------------------------------------------------------/** What a touch can land on: the neighbours a hit area must not take from. */-const INTERACTIVE = [+export const INTERACTIVE_SELECTOR = ['a[href]','area[href]','button',@@ -268,6 +313,11 @@ interface Watch {readonly element: Element;readonly minSize: number;readonly ownsDescendantTouches: boolean;+ readonly growth?: (+ target: HitRect,+ toLayout: (rect: HitRect) => HitRect,+ ) => HitInsets;+ readonly checkAtPress: boolean;readonly onInsets: (insets: HitInsets) => void;isVisible: boolean;last: HitInsets;@@ -452,7 +502,7 @@ function watchedOwner(element: Element): Element | null {function readCandidates(doc: Document): Candidate[] {const seen = new Set<Element>();const candidates: Candidate[] = [];- for (const found of doc.querySelectorAll(INTERACTIVE)) {+ for (const found of doc.querySelectorAll(INTERACTIVE_SELECTOR)) {const element = watchedOwner(found) ?? found;if (!seen.has(element)) {seen.add(element);@@ -498,6 +548,9 @@ function measureOne(inLayout(target, target, scale),neighbours.map(rect => inLayout(rect, target, scale)),watch.minSize,+ watch.growth?.(inLayout(target, target, scale), rect =>+ inLayout(rect, target, scale),+ ),),neighbours,};@@ -559,7 +612,8 @@ function scheduleAll(): void {* touch is outside the fresh area (a neighbour moved nearer since the last* measurement), the control's click is swallowed. The tap then does* nothing rather than toggle the wrong control; nothing is re-sent to the- * neighbour, and the next tap uses the fresh insets.+ * neighbour, and the next tap uses the fresh insets. A watch whose owner reads+ * its own targets when a press begins skips this (`checkAtPress`).*/function onPress(event: Event): void {// One listener on the document for every watched control, so a control, row@@ -589,6 +643,10 @@ function checkPress(element: Element, event: PointerEvent): void {if (!isCoarse || press.pointerType !== 'touch') {return;}+ const checked = [...entry.watches].filter(watch => watch.checkAtPress);+ if (checked.length === 0) {+ return;+ }const candidates = readCandidates(element.ownerDocument);const x = press.clientX;const y = press.clientY;@@ -596,7 +654,7 @@ function checkPress(element: Element, event: PointerEvent): void {// fresh area too (a corner beside an offset or diagonal neighbour), and// a few px past it, where a browser's own touch adjustment reaches.let isNearerNeighbour = false;- for (const watch of entry.watches) {+ for (const watch of checked) {const {target, insets, neighbours} = measureOne(watch, candidates);deliver(watch, insets);const own = distanceTo(target, x, y);@@ -800,6 +858,24 @@ export interface WatchHitAreaOptions {* grown input is its descendant leaves it off. @default false*/readonly ownsDescendantTouches?: boolean;+ /**+ * How far the control grows on each side before any neighbour stops it,+ * read in the measure pass. A group passes `groupGrowth` of its members.+ * It gets the control's box in layout px, and `toLayout` maps a rect the+ * owner reads into the same px.+ * @default toward `minSize` on each axis, centered+ */+ readonly growth?: (+ target: HitRect,+ toLayout: (rect: HitRect) => HitRect,+ ) => HitInsets;+ /**+ * Whether a finger's press on the control re-measures it against every+ * interactive element on the page, at once. An owner that reads its own+ * targets when a press begins, such as a group's tracker, turns it off.+ * @default true+ */+ readonly checkAtPress?: boolean;}/**@@ -834,6 +910,8 @@ export function watchHitArea({minSize = MIN_TOUCH_TARGET,ownsDescendantTouches = false,+ growth: growthOf,+ checkAtPress = true,}: WatchHitAreaOptions = {},): () => void {const owner = element.ownerDocument.defaultView;@@ -855,6 +933,8 @@ export function watchHitArea(element,minSize,ownsDescendantTouches,+ growth: growthOf,+ checkAtPress,onInsets,isVisible: isCoarse && visibility == null,last: NO_HIT_INSETS,diff --git a/packages/core/src/utils/touchHitArea.stylex.ts b/packages/core/src/utils/touchHitArea.stylex.tsindex 17ef5f52ed..cbbf93b929 100644--- a/packages/core/src/utils/touchHitArea.stylex.ts+++ b/packages/core/src/utils/touchHitArea.stylex.ts@@ -4,15 +4,19 @@* @file touchHitArea.stylex.ts* @input Uses StyleX and the insets that utils/hitArea.ts writes on a host* @output Exports `touchHitAreaStyles.layer`, a host's invisible hit band- * under a coarse pointer+ * under a coarse pointer, and `touchHitAreaStyles.layerBelowChildren`, the+ * same band drawn below the host's children* @position Internal styling utility for CheckboxInput, RadioListItem, List- * rows and InfoTip. Each keeps its insets live with `useTouchHitArea`- * (utils/touchHitArea.ts).+ * rows, InfoTip and the press-tracking groups. Each keeps its insets live+ * with `useTouchHitArea` (utils/touchHitArea.ts).** The band is the host's `::after`, grown past each edge by the measured* inset. A clip path cuts out the host's box, so its content keeps its taps.- * A tap on the band lands on the host. SYNC: hitArea.ts HIT_INSET_PROPERTIES,- * touchHitArea.ts and touchHitArea.test.tsx.+ * A tap on the band lands on the host. A host whose children fill its box,+ * such as a press-tracking group, takes `layerBelowChildren`. That band is its+ * `::before`, so its positioned children paint over the clip path's edge, and+ * the pixels on their own edges stay theirs. SYNC: hitArea.ts+ * HIT_INSET_PROPERTIES, touchHitArea.ts and touchHitArea.test.tsx.*/import * as stylex from '@stylexjs/stylex';@@ -36,21 +40,27 @@ const BORDER_LEFT = 'var(--_hit-border-left, 0px)';// The host is the band's containing block, so a host that is not positioned// sets `position: relative`. The band has no z-index of its own. Inside a// List, which isolates its rows, ListItem raises it. Under a finger the host's-// `::after` is this band, so decorate the host with a child.+// `::after`, or `::before` below its children, is this band, so decorate the+// host with a child.+const BAND = {+ content: {default: null, [TOUCH]: '""'},+ position: {default: null, [TOUCH]: 'absolute'},+ inset: {+ default: null,+ [TOUCH]: `calc((${TOP} + ${BORDER_TOP}) * -1) calc((${RIGHT} + ${BORDER_RIGHT}) * -1) calc((${BOTTOM} + ${BORDER_BOTTOM}) * -1) calc((${LEFT} + ${BORDER_LEFT}) * -1)`,+ },+ // The outer rectangle, then the host's box as an even-odd hole.+ clipPath: {+ default: null,+ [TOUCH]: `polygon(evenodd, 0 0, 100% 0, 100% 100%, 0 100%, 0 0, ${LEFT} ${TOP}, calc(100% - ${RIGHT}) ${TOP}, calc(100% - ${RIGHT}) calc(100% - ${BOTTOM}), ${LEFT} calc(100% - ${BOTTOM}), ${LEFT} ${TOP})`,+ },+} as const;+export const touchHitAreaStyles = stylex.create({layer: {- '::after': {- content: {default: null, [TOUCH]: '""'},- position: {default: null, [TOUCH]: 'absolute'},- inset: {- default: null,- [TOUCH]: `calc((${TOP} + ${BORDER_TOP}) * -1) calc((${RIGHT} + ${BORDER_RIGHT}) * -1) calc((${BOTTOM} + ${BORDER_BOTTOM}) * -1) calc((${LEFT} + ${BORDER_LEFT}) * -1)`,- },- // The outer rectangle, then the host's box as an even-odd hole.- clipPath: {- default: null,- [TOUCH]: `polygon(evenodd, 0 0, 100% 0, 100% 100%, 0 100%, 0 0, ${LEFT} ${TOP}, calc(100% - ${RIGHT}) ${TOP}, calc(100% - ${RIGHT}) calc(100% - ${BOTTOM}), ${LEFT} calc(100% - ${BOTTOM}), ${LEFT} ${TOP})`,- },- },+ '::after': BAND,+ },+ layerBelowChildren: {+ '::before': BAND,},});diff --git a/packages/core/src/utils/touchHitArea.test.tsx b/packages/core/src/utils/touchHitArea.test.tsxindex 8e4e341b9a..6217bded10 100644--- a/packages/core/src/utils/touchHitArea.test.tsx+++ b/packages/core/src/utils/touchHitArea.test.tsx@@ -5,8 +5,8 @@* @input Vitest, Testing Library, StyleX's injected rules, and a stubbed* watchHitArea (utils/hitArea.ts)* @output Tests for the shared touch hit area hook and layer. They cover what- * the hook watches, a measurement while the parent moves, the stop, and the- * layer's CSS.+ * the hook watches, an owner's growth and press check, a measurement while+ * the parent moves, the stop, and the layer's CSS.* @position Unit test for utils/touchHitArea.ts and* utils/touchHitArea.stylex.ts. List/ListItem.hitArea.test.tsx covers the* row wiring.@@ -17,7 +17,7 @@ import * as stylex from '@stylexjs/stylex';import {afterEach, describe, expect, it, vi} from 'vitest';import {render, screen} from '@testing-library/react';import type * as HitAreaModule from './hitArea';-import {HIT_INSET_PROPERTIES, type HitInsets} from './hitArea';+import {HIT_INSET_PROPERTIES, type HitInsets, type HitRect} from './hitArea';import {useMergedRefs} from '../hooks/useMergedRefs';const watches = vi.hoisted(@@ -26,6 +26,7 @@ const watches = vi.hoisted(element: Element;onInsets: (insets: HitInsets) => void;minSize: number | undefined;+ options: HitAreaModule.WatchHitAreaOptions | undefined;stop: ReturnType<typeof vi.fn>;}[],);@@ -37,10 +38,16 @@ vi.mock('./hitArea', async importOriginal => {watchHitArea: (element: Element,onInsets: (insets: HitInsets) => void,- options?: {readonly minSize?: number},+ options?: HitAreaModule.WatchHitAreaOptions,) => {const stop = vi.fn();- watches.push({element, onInsets, minSize: options?.minSize, stop});+ watches.push({+ element,+ onInsets,+ minSize: options?.minSize,+ options,+ stop,+ });return stop;},};@@ -81,8 +88,11 @@ function Host({);}-/** The element's injected `::after` rules, split by the touch gate. */-function afterRules(el: Element): {touch: string[]; other: string[]} {+/** The element's injected rules for `pseudo`, split by the touch gate. */+function pseudoRules(+ el: Element,+ pseudo: '::after' | '::before' = '::after',+): {touch: string[]; other: string[]} {const classes = el.className.split(/\s+/).filter(Boolean)@@ -92,7 +102,7 @@ function afterRules(el: Element): {touch: string[]; other: string[]} {for (const rule of Array.from(rules)) {if (rule instanceof CSSStyleRule) {if (- rule.selectorText.includes('::after') &&+ rule.selectorText.includes(pseudo) &&classes.some(cls => rule.selectorText.startsWith(cls))) {(touch ? out.touch : out.other).push(@@ -154,6 +164,34 @@ describe('useTouchHitArea', () => {expect(watches[1].stop).toHaveBeenCalledTimes(1);});+ it("passes an owner's growth, with the element, and its press check to the watch; a plain watch keeps the defaults", () => {+ const grown = {top: 1, right: 2, bottom: 3, left: 4};+ const growth = vi.fn(() => grown);+ const options = {growth, checkAtPress: false};+ function Owner() {+ const hitAreaRef = useTouchHitArea(true, options);+ return <span data-testid="owner" ref={hitAreaRef} />;+ }+ render(+ <>+ <Owner />+ <Host enabled />+ </>,+ );+ const owner = screen.getByTestId('owner');+ const ownerWatch = watches.find(watch => watch.element === owner);+ const plainWatch = watches.find(+ watch => watch.element === screen.getByTestId('host'),+ );+ expect(ownerWatch?.options?.checkAtPress).toBe(false);+ const box = {left: 0, top: 0, right: 32, bottom: 32};+ const toLayout = (rect: HitRect) => rect;+ expect(ownerWatch?.options?.growth?.(box, toLayout)).toBe(grown);+ expect(growth).toHaveBeenCalledWith(box, toLayout, owner);+ expect(plainWatch?.options?.growth).toBeUndefined();+ expect(plainWatch?.options?.checkAtPress).toBeUndefined();+ });+it('follows a replaced element: the new element is watched and the old one’s watch stops', async () => {const {rerender} = render(<Host enabled />);const first = screen.getByTestId('host');@@ -315,7 +353,7 @@ describe('useTouchHitArea across re-renders', () => {describe('touchHitAreaStyles.layer', () => {it('is a coarse-only ::after grown on all four sides by the inset properties past the host’s border, the element as its clip-path hole, with no z-index of its own, painting nothing, and the host starting no stacking context', () => {render(<Host enabled={false} />);- const {touch, other} = afterRules(screen.getByTestId('host'));+ const {touch, other} = pseudoRules(screen.getByTestId('host'));const layer = touch.join('\n');expect(layer).toContain('position: absolute');// Offset from the host's padding box: the inset, plus the border the host@@ -340,3 +378,28 @@ describe('touchHitAreaStyles.layer', () => {expect(other).toEqual([]);});});++describe('touchHitAreaStyles.layerBelowChildren', () => {+ it("is the same coarse-only band as the host's ::before, so the host's positioned children paint over its edge, and draws no ::after", () => {+ render(+ <>+ <span+ data-testid="below"+ {...stylex.props(touchHitAreaStyles.layerBelowChildren)}+ />+ <span data-testid="above" {...stylex.props(touchHitAreaStyles.layer)} />+ </>,+ );+ const below = screen.getByTestId('below');+ const declarations = (rules: string[]) =>+ rules.map(rule => rule.slice(rule.indexOf('{'))).sort();+ const band = pseudoRules(below, '::before');+ expect(band.touch.length).toBeGreaterThan(0);+ expect(declarations(band.touch)).toEqual(+ declarations(pseudoRules(screen.getByTestId('above')).touch),+ );+ // With a mouse: no pseudo-element, and never an `::after`.+ expect(band.other).toEqual([]);+ expect(pseudoRules(below)).toEqual({touch: [], other: []});+ });+});diff --git a/packages/core/src/utils/touchHitArea.ts b/packages/core/src/utils/touchHitArea.tsindex 14d62441d9..32fe6fbc21 100644--- a/packages/core/src/utils/touchHitArea.ts+++ b/packages/core/src/utils/touchHitArea.ts@@ -4,13 +4,13 @@/*** @file touchHitArea.ts- * @input Whether an element takes taps, the shared touch hit area- * (utils/hitArea.ts) and the Web Animations around the element+ * @input Whether an element takes taps, how it grows, the shared touch hit+ * area (utils/hitArea.ts) and the Web Animations around the element* @output `useTouchHitArea`, a callback ref that keeps an element's hit insets* live for its invisible layer (`touchHitAreaStyles.layer`)* @position Core-internal hook for the coarse-only 44 px target. List rows,- * InfoTip, CheckboxInput and RadioListItem use it, and so can any control- * whose target grows under a finger without growing its box.+ * InfoTip, CheckboxInput, RadioListItem and the press-tracking groups use+ * it, and so can any control whose target outgrows its box under a finger.** SYNC: When modified, update utils/touchHitArea.stylex.ts and* touchHitArea.test.tsx.@@ -22,8 +22,34 @@ import {NO_HIT_INSETS,watchHitArea,writeHitInsets,+ type HitInsets,+ type HitRect,} from './hitArea';+/** How an owner's element grows, for an owner with its own rule. */+export interface TouchHitAreaOptions {+ /**+ * How far the element grows on each side before any neighbour stops it,+ * read as `watchHitArea`'s `growth`. It also gets the element. A group+ * passes `groupGrowth` of its members.+ * @default toward 44 px on each axis, centered+ */+ readonly growth?: (+ target: HitRect,+ toLayout: (rect: HitRect) => HitRect,+ element: HTMLElement,+ ) => HitInsets;+ /**+ * Whether a finger's press on the element re-measures it against every+ * interactive element on the page. An owner that reads its own targets+ * when a press begins turns it off.+ * @default true+ */+ readonly checkAtPress?: boolean;+}++const NO_OPTIONS: TouchHitAreaOptions = {};+/*** The finite animations running or held in the element's parent, the element* included: a row's own motion and its neighbors'. An endless one (a spinner)@@ -58,7 +84,11 @@ function settlingAnimations(element: HTMLElement): Animation[] {* element is watched again. The insets are then taken at rest, and no frame* of a compositor-only motion lays out or paints for them.*/-function watchAtRest(element: HTMLElement, minSize: number): () => void {+function watchAtRest(+ element: HTMLElement,+ minSize: number,+ {growth, checkAtPress}: TouchHitAreaOptions,+): () => void {let stopWatch = (): void => {};let isStopped = false;let isWaiting = false;@@ -99,7 +129,15 @@ function watchAtRest(element: HTMLElement, minSize: number): () => void {},// The layer is the host's own `::after`, so a touch on the host's// content is the host's, even where that content paints past its box.- {minSize, ownsDescendantTouches: true},+ {+ minSize,+ ownsDescendantTouches: true,+ growth:+ growth == null+ ? undefined+ : (target, toLayout) => growth(target, toLayout, element),+ checkAtPress,+ },);};watch();@@ -123,10 +161,16 @@ const heldWatches = new WeakMap<HTMLElement, HeldWatch>();* detaches and attaches again in one commit. So the last release waits a* microtask, and an attach in between keeps the watch and its insets.*/-function holdWatch(element: HTMLElement): () => void {+function holdWatch(+ element: HTMLElement,+ options: TouchHitAreaOptions,+): () => void {let held = heldWatches.get(element);if (held == null) {- held = {stop: watchAtRest(element, MIN_TOUCH_TARGET), holders: 0};+ held = {+ stop: watchAtRest(element, MIN_TOUCH_TARGET, options),+ holders: 0,+ };heldWatches.set(element, held);}held.holders += 1;@@ -153,7 +197,8 @@ function holdWatch(element: HTMLElement): () => void {* Merge it into the element's ref, and pair it with `touchHitAreaStyles.layer`* on the same element. The watch lasts while the element is attached, so a* replaced element starts its own. A re-render that hands the same element a- * new merged ref keeps its watch.+ * new merged ref keeps its watch. `options` set how the element grows. Keep+ * them stable, as a module constant. An element's first holder sets them.** @example* ```@@ -161,7 +206,10 @@ function holdWatch(element: HTMLElement): () => void {* <li ref={hitAreaRef} {...stylex.props(isInteractive && touchHitAreaStyles.layer)} />* ```*/-export function useTouchHitArea(enabled: boolean): RefCallback<HTMLElement> {+export function useTouchHitArea(+ enabled: boolean,+ options: TouchHitAreaOptions = NO_OPTIONS,+): RefCallback<HTMLElement> {// Syncs with an external system: the shared touch hit area// (utils/hitArea.ts) measures the element against its neighbors and writes// its insets on it. The ref's cleanup stops the watch.@@ -170,8 +218,8 @@ export function useTouchHitArea(enabled: boolean): RefCallback<HTMLElement> {if (!enabled || element == null) {return undefined;}- return holdWatch(element);+ return holdWatch(element, options);},- [enabled],+ [enabled, options],);}diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjsindex 6f8ff47283..a7df56763c 100644--- a/scripts/touch-support-bundle.test.mjs+++ b/scripts/touch-support-bundle.test.mjs@@ -172,8 +172,12 @@ function filesUnder(dir, pattern) {* that reaches it, with a comment naming the gesture.*/const GESTURE_USERS = new Set([- // AlertDialog: its actions' press, tracked across both for every pointer.+ // AlertDialog: its actions' press, tracked across both for a finger and a+ // pen under the touch presentation.'AlertDialog',+ // ButtonGroup: a finger's or a pen's press, tracked across its buttons+ // under the touch presentation.+ 'ButtonGroup',// 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.