Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(core): one tracker for a held finger across any group of targets (#8346)

Christopher Chedeau167a3de8f8d9
diff --git a/.changeset/action-group-tracker.md b/.changeset/action-group-tracker.md
new file mode 100644
index 0000000000..a3f9633a00
--- /dev/null
+++ b/.changeset/action-group-tracker.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[internal] One tracker for a held finger across a group of targets (an alert's or an action sheet's actions, a menu's rows, a segmented control's segments, a page control's dots): it reads the targets' rects once, resolves the finger against them (or by the owner's rule), paints or reports the highlight, and runs the target through its own click at the lift. Nothing a consumer sees changes.
+
+@vjeux
diff --git a/packages/core/src/hooks/actionGroupTracker.exports.test.ts b/packages/core/src/hooks/actionGroupTracker.exports.test.ts
new file mode 100644
index 0000000000..fc6b4e3340
--- /dev/null
+++ b/packages/core/src/hooks/actionGroupTracker.exports.test.ts
@@ -0,0 +1,28 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file actionGroupTracker.exports.test.ts
+ * @input The core package's hooks entry point and its package exports
+ * @output Proof that the action-group tracker stays internal: neither the
+ * hooks entry point nor the package's `exports` map reaches it
+ * @position Export lock for /packages/core/src/hooks/actionGroupTracker.ts
+ */
+
+import {readFileSync} from 'node:fs';
+import {resolve} from 'node:path';
+import {describe, expect, it} from 'vitest';
+import * as hooks from './index';
+
+describe('the action-group tracker is internal to core', () => {
+ it('is not exported from the hooks entry point', () => {
+ expect(Object.keys(hooks)).not.toContain('createActionGroupTracker');
+ });
+
+ it('has no package export of its own', () => {
+ const manifest = readFileSync(
+ resolve(__dirname, '../../package.json'),
+ 'utf8',
+ );
+ expect(manifest).not.toContain('actionGroupTracker');
+ });
+});
diff --git a/packages/core/src/hooks/actionGroupTracker.test.ts b/packages/core/src/hooks/actionGroupTracker.test.ts
new file mode 100644
index 0000000000..1719962cec
--- /dev/null
+++ b/packages/core/src/hooks/actionGroupTracker.test.ts
@@ -0,0 +1,510 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file actionGroupTracker.test.ts
+ * @input vitest (jsdom), createActionGroupTracker over actions laid out with
+ * stubbed rects
+ * @output The tracker's contract, driven directly as a recognizer elsewhere
+ * would drive it: begin highlights the action under the point and reads
+ * layout only then; move follows the finger and cuts (not fades) the action
+ * it leaves; end fades and runs only the action under the finger, once;
+ * cancel and an inert press run nothing; disabled actions are skipped;
+ * several roots are one group; offsetBy shifts the cached rects; the
+ * highlight callback (with the target it replaces) and the opt-out of the
+ * paint; an owner's own target resolution (a row of segments, past its
+ * ends), the finger's raw moves, the begin target, remeasure, a cancelled
+ * click reported, and the browser's own click swallowed once
+ * @position jsdom tests of packages/core/src/hooks/actionGroupTracker.ts
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback';
+import {PRESS_FADE_MS} from '../utils/pressGesture';
+import {
+ createActionGroupTracker,
+ type ActionGroupTarget,
+ type ActionGroupTrackerOptions,
+} from './actionGroupTracker';
+
+function place(
+ element: Element,
+ box: {left: number; top: number; width: number; height: number},
+) {
+ const rect = DOMRect.fromRect({
+ x: box.left,
+ y: box.top,
+ width: box.width,
+ height: box.height,
+ });
+ const spy = vi.fn(() => rect);
+ element.getBoundingClientRect = spy;
+ return spy;
+}
+
+function action(label: string, box: Parameters<typeof place>[1]) {
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.textContent = label;
+ button.setAttribute('data-action', '');
+ const rectSpy = place(button, box);
+ const onClick = vi.fn();
+ button.addEventListener('click', onClick);
+ return {button, onClick, rectSpy};
+}
+
+let root: HTMLDivElement;
+let first: ReturnType<typeof action>;
+let second: ReturnType<typeof action>;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ root = document.createElement('div');
+ first = action('First', {left: 0, top: 0, width: 200, height: 40});
+ second = action('Second', {left: 0, top: 50, width: 200, height: 40});
+ root.append(first.button, second.button);
+ document.body.append(root);
+});
+
+afterEach(() => {
+ root.remove();
+ vi.useRealTimers();
+});
+
+function tracker(options: Partial<ActionGroupTrackerOptions> = {}) {
+ return createActionGroupTracker(() => ({
+ roots: () => [root],
+ itemSelector: '[data-action]',
+ highlightExpansion: 0,
+ ...options,
+ }));
+}
+
+describe('createActionGroupTracker', () => {
+ it('begin highlights the action under the point and reads layout only then', () => {
+ const group = tracker();
+ group.begin(100, 20);
+ expect(group.highlighted).toBe(first.button);
+ expect(first.button.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ group.move(100, 25);
+ group.move(100, 70);
+ group.move(100, 72);
+ expect(first.rectSpy).toHaveBeenCalledTimes(1);
+ expect(second.rectSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('move follows the finger: the action it leaves is cut, not faded', () => {
+ const group = tracker();
+ group.begin(100, 20);
+ group.move(100, 70);
+ expect(first.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ expect(second.button.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ // Between the actions nothing is highlighted.
+ group.move(100, 45);
+ expect(group.highlighted).toBeNull();
+ expect(second.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('end fades the action under the finger and runs it once, from inside the call', () => {
+ const group = tracker();
+ group.begin(100, 20);
+ group.move(100, 70);
+ expect(group.end()).toBe(second.button);
+ expect(second.onClick).toHaveBeenCalledTimes(1);
+ expect(first.onClick).not.toHaveBeenCalled();
+ expect(second.button.getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ expect(second.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ // A second end has nothing to run.
+ expect(group.end()).toBeNull();
+ expect(second.onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('a lift with no action under the finger runs nothing', () => {
+ const group = tracker();
+ group.begin(100, 20);
+ group.move(100, 200);
+ expect(group.end()).toBeNull();
+ expect(first.onClick).not.toHaveBeenCalled();
+ });
+
+ it('cancel cuts the highlight, reports it gone and runs nothing', () => {
+ const onHighlightChange =
+ vi.fn<(item: HTMLElement | null, previous: HTMLElement | null) => void>();
+ const group = tracker({onHighlightChange});
+ group.begin(100, 20);
+ group.cancel();
+ expect(onHighlightChange).toHaveBeenLastCalledWith(null, first.button);
+ expect(first.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ expect(group.isTracking).toBe(false);
+ expect(group.end()).toBeNull();
+ expect(first.onClick).not.toHaveBeenCalled();
+ });
+
+ it('an inert press is taken but paints and runs nothing', () => {
+ const group = tracker();
+ group.begin(100, 20, {inert: true});
+ expect(group.isTracking).toBe(true);
+ expect(group.highlighted).toBeNull();
+ expect(first.rectSpy).not.toHaveBeenCalled();
+ group.move(100, 70);
+ expect(group.end()).toBeNull();
+ expect(first.onClick).not.toHaveBeenCalled();
+ expect(second.onClick).not.toHaveBeenCalled();
+ });
+
+ it('skips disabled actions', () => {
+ second.button.disabled = true;
+ const group = tracker();
+ group.begin(100, 70);
+ expect(group.highlighted).toBeNull();
+ expect(group.end()).toBeNull();
+ });
+
+ it('tracks the actions of several roots as one group', () => {
+ const flyout = document.createElement('div');
+ const third = action('Third', {left: 220, top: 0, width: 200, height: 40});
+ flyout.append(third.button);
+ document.body.append(flyout);
+ const group = tracker({roots: () => [root, flyout]});
+ group.begin(100, 20);
+ group.move(300, 20);
+ expect(group.highlighted).toBe(third.button);
+ group.end();
+ expect(third.onClick).toHaveBeenCalledTimes(1);
+ flyout.remove();
+ });
+
+ it('offsetBy shifts the cached rects when the content moves under a still finger', () => {
+ const group = tracker();
+ group.begin(100, 20);
+ // The list scrolled up by 50: the second action is now under the finger.
+ group.offsetBy(0, -50);
+ group.move(100, 20);
+ expect(group.highlighted).toBe(second.button);
+ expect(second.rectSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports highlight changes, and can leave the paint to its owner', () => {
+ const onHighlightChange = vi.fn<(item: HTMLElement | null) => void>();
+ const onActivate = vi.fn();
+ const group = tracker({
+ paintsHighlight: false,
+ onHighlightChange,
+ onActivate,
+ });
+ group.begin(100, 20);
+ group.move(100, 70);
+ group.end();
+ // The lift leaves the highlight to the activation: no change reported.
+ expect(onHighlightChange.mock.calls.map(([item]) => item)).toEqual([
+ first.button,
+ second.button,
+ ]);
+ expect(first.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ expect(second.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ // onActivate replaces the action's own click.
+ expect(onActivate).toHaveBeenCalledWith(second.button);
+ expect(second.onClick).not.toHaveBeenCalled();
+ });
+
+ it('a press that begins while another is tracked takes the paint off the first one', () => {
+ const onHighlightChange = vi.fn<(item: HTMLElement | null) => void>();
+ const group = tracker({onHighlightChange});
+ group.begin(100, 20);
+ expect(first.button.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ // A second recognizer takes over the finger without an end or a cancel.
+ group.begin(100, 70);
+ expect(first.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ expect(second.button.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ // Taken over onto nothing: the highlight is gone, and the owner is told.
+ group.begin(100, 200);
+ expect(second.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ expect(onHighlightChange.mock.calls.map(([item]) => item)).toEqual([
+ first.button,
+ second.button,
+ null,
+ ]);
+ });
+
+ it('dispose finishes a pending release fade', () => {
+ const group = tracker();
+ group.begin(100, 20);
+ group.end();
+ expect(first.button.getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ group.dispose();
+ expect(first.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ expect(first.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('reads no idiom: an Android finger (no -webkit-touch-callout) tracks, fades and runs the same way', () => {
+ vi.stubGlobal('CSS', {supports: () => false});
+ try {
+ const group = tracker();
+ group.begin(100, 20);
+ group.move(100, 70);
+ expect(group.end()).toBe(second.button);
+ expect(second.onClick).toHaveBeenCalledTimes(1);
+ expect(second.button.getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ expect(second.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('expands each action\u2019s hit area by the given margin', () => {
+ const group = tracker({highlightExpansion: 6});
+ group.begin(100, 44);
+ expect(group.highlighted).toBe(first.button);
+ });
+});
+
+describe('createActionGroupTracker: options for other trackers', () => {
+ // A row of two segments, side by side with a 2 px gap: x 0-99 and 101-200.
+ let left: ReturnType<typeof action>;
+ let right: ReturnType<typeof action>;
+ beforeEach(() => {
+ left = action('Left', {left: 0, top: 0, width: 99, height: 30});
+ right = action('Right', {left: 101, top: 0, width: 99, height: 30});
+ root.replaceChildren(left.button, right.button);
+ });
+
+ /** The nearest segment along x: the gap counts for the nearer one, past the ends the end one. */
+ const nearestAlongX = (
+ x: number,
+ _y: number,
+ targets: ReadonlyArray<ActionGroupTarget>,
+ ) => {
+ let best: ActionGroupTarget | null = null;
+ let bestDistance = Infinity;
+ for (const target of targets) {
+ const distance =
+ x < target.left
+ ? target.left - x
+ : x > target.right
+ ? x - target.right
+ : 0;
+ if (distance < bestDistance) {
+ best = target;
+ bestDistance = distance;
+ }
+ }
+ return best?.element ?? null;
+ };
+
+ it('resolves the target with the owner\u2019s rule, from the rects read at the begin', () => {
+ const group = tracker({resolveTarget: nearestAlongX});
+ group.begin(99.6, 200);
+ expect(group.highlighted).toBe(left.button);
+ group.move(100.6, 200);
+ expect(group.highlighted).toBe(right.button);
+ // Past the end (and far below the row) the end segment is the target, and
+ // the lift runs it wherever the finger lifts.
+ group.move(400, 300);
+ expect(group.highlighted).toBe(right.button);
+ expect(group.end()).toBe(right.button);
+ expect(right.onClick).toHaveBeenCalledTimes(1);
+ expect(left.rectSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('hands every finger position to onMove before resolving it', () => {
+ const order: string[] = [];
+ const group = tracker({
+ onMove: (x, y) => order.push(`move ${x},${y}`),
+ onHighlightChange: item => order.push(`highlight ${item?.textContent}`),
+ });
+ group.begin(50, 10);
+ group.move(150, 12);
+ group.move(160, 14);
+ expect(order).toEqual([
+ 'move 50,10',
+ 'highlight Left',
+ 'move 150,12',
+ 'highlight Right',
+ 'move 160,14',
+ ]);
+ });
+
+ it('reports the target each highlight replaces, and the target the press began on', () => {
+ const onHighlightChange =
+ vi.fn<(item: HTMLElement | null, previous: HTMLElement | null) => void>();
+ const group = tracker({onHighlightChange});
+ group.begin(50, 10);
+ expect(group.beganOn).toBe(left.button);
+ group.move(150, 10);
+ group.move(150, 100);
+ expect(group.beganOn).toBe(left.button);
+ expect(onHighlightChange.mock.calls).toEqual([
+ [left.button, null],
+ [right.button, left.button],
+ [null, right.button],
+ ]);
+ group.cancel();
+ expect(group.beganOn).toBeNull();
+ // An inert press began on nothing.
+ group.begin(50, 10, {inert: true});
+ expect(group.beganOn).toBeNull();
+ });
+
+ it('remeasure reads the targets again and resolves the finger\u2019s last position', () => {
+ const group = tracker();
+ group.begin(50, 10);
+ expect(group.highlighted).toBe(left.button);
+ // The row moved 120 px down under the still finger (a scroll the owner
+ // did not run): the finger is now over neither segment.
+ place(left.button, {left: 0, top: 120, width: 99, height: 30});
+ place(right.button, {left: 101, top: 120, width: 99, height: 30});
+ group.remeasure();
+ expect(group.highlighted).toBeNull();
+ expect(left.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ group.move(150, 130);
+ expect(group.highlighted).toBe(right.button);
+ });
+
+ it('reports whether a click handler cancelled the activation', () => {
+ const onActivated = vi.fn();
+ right.button.addEventListener('click', event => event.preventDefault());
+ const group = tracker({onActivated});
+ group.begin(50, 10);
+ group.end();
+ group.begin(150, 10);
+ group.end();
+ expect(onActivated.mock.calls).toEqual([
+ [left.button, false],
+ [right.button, true],
+ ]);
+ // With onActivate the owner runs the action; there is no click to report.
+ const onActivate = vi.fn();
+ const owned = tracker({onActivate, onActivated});
+ owned.begin(50, 10);
+ owned.end();
+ expect(onActivate).toHaveBeenCalledWith(left.button);
+ expect(onActivated).toHaveBeenCalledTimes(2);
+ });
+
+ it('swallows the browser\u2019s own click after the lift once, listening only until then', () => {
+ const add = vi.spyOn(window, 'addEventListener');
+ const remove = vi.spyOn(window, 'removeEventListener');
+ try {
+ const group = tracker({swallowsNativeClick: true});
+ group.begin(50, 10);
+ add.mockClear();
+ group.end();
+ // The tracker's own click ran inside end, before the swallower.
+ expect(left.onClick).toHaveBeenCalledTimes(1);
+ // Listening now: what end added and did not take off again (the
+ // capture that reads its own click comes and goes inside the call).
+ const gone = new Set(remove.mock.calls.map(([, listener]) => listener));
+ const armed = add.mock.calls.filter(
+ ([, listener, capture]) => capture === true && !gone.has(listener),
+ );
+ expect(armed.map(([type]) => type).sort()).toEqual([
+ 'click',
+ 'keydown',
+ 'pointerdown',
+ ]);
+ remove.mockClear();
+ // A script's click is not the browser's: it passes.
+ const onDocumentClick = vi.fn();
+ document.addEventListener('click', onDocumentClick);
+ left.button.click();
+ expect(onDocumentClick).toHaveBeenCalledTimes(1);
+ // The browser's click for the touch is taken once, and the swallower goes.
+ const swallow = armed.find(([type]) => type === 'click')?.[1] as (
+ event: unknown,
+ ) => void;
+ const trusted = {
+ isTrusted: true,
+ preventDefault: vi.fn(),
+ stopImmediatePropagation: vi.fn(),
+ };
+ swallow(trusted);
+ expect(trusted.preventDefault).toHaveBeenCalled();
+ expect(trusted.stopImmediatePropagation).toHaveBeenCalled();
+ const removed = remove.mock.calls
+ .filter(([, , capture]) => capture === true)
+ .map(([type]) => type)
+ .sort();
+ expect(removed).toEqual(['click', 'keydown', 'pointerdown']);
+ document.removeEventListener('click', onDocumentClick);
+ } finally {
+ add.mockRestore();
+ remove.mockRestore();
+ }
+ });
+
+ it('lets an activation with detail 0 (keyboard, assistive technology) through while it waits for the browser\u2019s click (spec:AST-094 FR21)', () => {
+ const add = vi.spyOn(window, 'addEventListener');
+ const remove = vi.spyOn(window, 'removeEventListener');
+ try {
+ const group = tracker({swallowsNativeClick: true});
+ group.begin(50, 10);
+ add.mockClear();
+ group.end();
+ const gone = new Set(remove.mock.calls.map(([, listener]) => listener));
+ const swallow = add.mock.calls.find(
+ ([type, listener, capture]) =>
+ type === 'click' && capture === true && !gone.has(listener),
+ )?.[1] as (event: unknown) => void;
+ remove.mockClear();
+ // A screen reader's or a key's activation is not the touch's click: it
+ // passes, and the swallower keeps waiting for the touch's own.
+ const activation = {
+ isTrusted: true,
+ detail: 0,
+ preventDefault: vi.fn(),
+ stopImmediatePropagation: vi.fn(),
+ };
+ swallow(activation);
+ expect(activation.preventDefault).not.toHaveBeenCalled();
+ expect(activation.stopImmediatePropagation).not.toHaveBeenCalled();
+ expect(remove).not.toHaveBeenCalled();
+ // The touch's own click (detail 1) is still taken once.
+ const touchClick = {
+ isTrusted: true,
+ detail: 1,
+ preventDefault: vi.fn(),
+ stopImmediatePropagation: vi.fn(),
+ };
+ swallow(touchClick);
+ expect(touchClick.preventDefault).toHaveBeenCalled();
+ expect(touchClick.stopImmediatePropagation).toHaveBeenCalled();
+ } finally {
+ add.mockRestore();
+ remove.mockRestore();
+ }
+ });
+
+ it('a press or a key before the browser\u2019s click ends the swallowing; without the option nothing stays listening', () => {
+ const add = vi.spyOn(window, 'addEventListener');
+ const remove = vi.spyOn(window, 'removeEventListener');
+ const listening = () => {
+ const gone = new Set(remove.mock.calls.map(([, listener]) => listener));
+ return add.mock.calls
+ .filter(([, listener]) => !gone.has(listener))
+ .map(([type]) => type)
+ .sort();
+ };
+ try {
+ const plain = tracker();
+ plain.begin(50, 10);
+ plain.end();
+ expect(listening()).toEqual([]);
+ const group = tracker({swallowsNativeClick: true});
+ group.begin(50, 10);
+ group.end();
+ expect(listening()).toEqual(['click', 'keydown', 'pointerdown']);
+ // The next press comes first (the browser gave no click): disarmed.
+ window.dispatchEvent(new PointerEvent('pointerdown'));
+ expect(listening()).toEqual([]);
+ group.begin(50, 10);
+ group.end();
+ window.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));
+ expect(listening()).toEqual([]);
+ } finally {
+ add.mockRestore();
+ remove.mockRestore();
+ }
+ });
+});
diff --git a/packages/core/src/hooks/actionGroupTracker.ts b/packages/core/src/hooks/actionGroupTracker.ts
new file mode 100644
index 0000000000..37529246ad
--- /dev/null
+++ b/packages/core/src/hooks/actionGroupTracker.ts
@@ -0,0 +1,449 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file actionGroupTracker.ts
+ * @input The elements whose actions are tracked, the actions' selector and
+ * hit expansion, and the press paint and fade clocks
+ * @output Exports createActionGroupTracker, ActionGroupTracker,
+ * ActionGroupTrackerOptions and ActionGroupTarget: UIKit's tracking of a
+ * held finger across a group of targets, as a plain object any gesture
+ * recognizer can drive
+ * @position The one tracker for a held finger that slides onto an action,
+ * internal to core. Gesture recognizers drive it: an alert's or an action
+ * sheet's long press on its group of actions, a menu trigger whose held
+ * finger slides into the menu it opened, a menu's list, a segmented
+ * control's segments, a page control's dots
+ *
+ * UIKit tracks a group of actions (an alert's, an action sheet's, a menu's)
+ * as one control, not as separate buttons (measured on iOS 26.2):
+ *
+ * - the action under the finger highlights; sliding off it cuts its highlight
+ * and sliding onto another highlights that one; between or outside the
+ * actions nothing is highlighted;
+ * - lifting runs the action under the finger, and nothing when there is none;
+ * the lifted action's highlight fades (PRESS_FADE_MS);
+ * - a press the owner calls inert (an alert during its transitions) is taken
+ * but paints and runs nothing.
+ *
+ * Which target a finger is on is the hit test above by default; an owner
+ * whose targets are a row of segments or dots resolves it itself
+ * (`resolveTarget`: the nearest segment along the axis, the end one past the
+ * ends), from the same rects. The finger's raw position reaches `onMove`
+ * (a lens that chases it), and an owner that shows the highlight another way
+ * (focus, a dimmed title) turns the paint off and follows
+ * `onHighlightChange(next, previous)`.
+ *
+ * Nothing reads layout after a press begins: the actions' rects are read once
+ * in `begin`, then hit-tested; `offsetBy` shifts them when the content moves
+ * under a still finger (autoscroll). A move costs at most two attribute writes
+ * and never a render. The action runs through its own `click()` inside `end`,
+ * so the recognizer must call `end` from the lift's event (its touchend): that
+ * keeps the user activation and every click handler. `onActivated` learns
+ * whether a handler cancelled that click (`preventDefault()` vetoes, and the
+ * owner can undo its visual at once). A recognizer that does not claim the
+ * touch leaves the browser its own click for it; `swallowsNativeClick` takes
+ * that one click, so the action runs exactly once (the swallower listens only
+ * from that lift until the click, or the next press or key).
+ *
+ * This is core's one track-across-items loop. Menus still run their own copy
+ * of it in useMenuPress.ts; the change after the in-flight menu press work
+ * moves that copy here, and useMenuPress keeps only its menu-only parts (a
+ * trigger's press or held finger opening the menu, the settle rule, edge
+ * autoscroll, the highlight as DOM focus). Add no third copy meanwhile.
+ * Nothing in core drives this tracker yet; its first adopters (the segmented
+ * control and the action groups) arrive in their own changes.
+ *
+ * SYNC: When modified, update actionGroupTracker.test.ts
+ */
+
+import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback';
+import {PRESS_FADE_MS} from '../utils/pressGesture';
+
+/** An action that is not enabled takes no highlight and does not run. */
+const DISABLED = ':disabled, [aria-disabled="true"]';
+
+/** A target the tracker measured: its element and viewport rect, px. */
+export interface ActionGroupTarget {
+ readonly element: HTMLElement;
+ readonly left: number;
+ readonly top: number;
+ readonly right: number;
+ readonly bottom: number;
+}
+
+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;
+ /** How far outside an action the finger keeps it highlighted, px. */
+ highlightExpansion: number;
+ /**
+ * Paint the highlighted action with the press attribute (`on`, then
+ * `fading` at the lift). @default true
+ */
+ paintsHighlight?: boolean;
+ /**
+ * Called whenever the highlighted action changes (null: none), with the
+ * one it replaces.
+ */
+ onHighlightChange?: (
+ item: HTMLElement | null,
+ previous: HTMLElement | null,
+ ) => void;
+ /** Runs the action under the finger at the lift. @default its own click */
+ onActivate?: (item: HTMLElement) => void;
+ /**
+ * Picks the target for a finger at viewport (x, y) from the enabled
+ * targets measured at the press's begin, in document order. Returning a
+ * target past the group's ends commits the lift there wherever the finger
+ * lifts.
+ * @default the target whose rect, grown by `highlightExpansion`, holds the
+ * point; none between or outside them
+ */
+ resolveTarget?: (
+ x: number,
+ y: number,
+ targets: ReadonlyArray<ActionGroupTarget>,
+ ) => HTMLElement | null;
+ /** Every finger position it is given (the begin and each move), first. */
+ onMove?: (x: number, y: number) => void;
+ /**
+ * After the lift ran an action through its own click: whether a click
+ * handler cancelled it (`preventDefault()`). Not called with `onActivate`.
+ */
+ onActivated?: (item: HTMLElement, cancelled: boolean) => void;
+ /**
+ * After the lift ran an action, take the browser's own click for that
+ * touch (left to it by a recognizer that did not claim the touch), so the
+ * action runs once. @default false
+ */
+ swallowsNativeClick?: boolean;
+}
+
+export interface ActionGroupTracker {
+ /**
+ * A press began at viewport (x, y): read the actions' rects once and
+ * highlight the one under it. An inert press is taken but tracks nothing.
+ */
+ begin(x: number, y: number, options?: {inert?: boolean}): void;
+ /** The finger moved to viewport (x, y). */
+ move(x: number, y: number): void;
+ /**
+ * The lift: the highlighted action's paint fades and the action runs.
+ * Call it from the lift's event. Returns the action that ran, if any. The
+ * highlight is left to the activation (no onHighlightChange): an owner
+ * that shows it as focus keeps focus on the action it runs.
+ */
+ end(): HTMLElement | null;
+ /** The press was taken away (a cancel): the highlight is cut, nothing runs. */
+ cancel(): void;
+ /**
+ * The tracked content moved by (dx, dy) under the finger (an autoscroll):
+ * shift the cached rects without reading layout.
+ */
+ offsetBy(dx: number, dy: number): void;
+ /**
+ * The targets moved in a way the owner cannot express as an offset (a
+ * scroll it did not run, a view that changed): read their rects again and
+ * resolve the finger's last position against them.
+ */
+ remeasure(): void;
+ /** The action highlighted now. */
+ readonly highlighted: HTMLElement | null;
+ /** The target the press began on (null: none, or an inert press). */
+ readonly beganOn: HTMLElement | null;
+ /** Whether a press is being tracked (between begin and end or cancel). */
+ readonly isTracking: boolean;
+ /**
+ * Finish every pending release fade now (its paint comes off) and forget
+ * the press: for the owner's unmount.
+ */
+ dispose(): void;
+}
+
+interface TrackedAction {
+ readonly element: HTMLElement;
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+}
+
+/**
+ * The browser's own click for a touch the lift already acted on: swallowed
+ * once, by listeners that exist only from that lift until the click, or the
+ * next press or key (whichever comes first). An activation with
+ * `detail === 0` (a key, assistive technology) is not that click: it always
+ * passes, and the swallower keeps waiting (`spec:AST-094` FR21).
+ */
+function swallowNextClick(view: Window): void {
+ const disarm = () => {
+ view.removeEventListener('click', onClick, true);
+ view.removeEventListener('pointerdown', disarm, true);
+ view.removeEventListener('keydown', disarm, true);
+ };
+ const onClick = (event: MouseEvent) => {
+ if (!event.isTrusted || event.detail === 0) {
+ return;
+ }
+ disarm();
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ };
+ view.addEventListener('click', onClick, true);
+ view.addEventListener('pointerdown', disarm, true);
+ view.addEventListener('keydown', disarm, true);
+}
+
+/**
+ * Click `element` (its own `click()`, so its activation behavior and every
+ * handler run as for any click) and report whether a handler cancelled it.
+ * The event is read from a capture listener that exists only for the call.
+ */
+function clickAndReport(element: HTMLElement): boolean {
+ const view = element.ownerDocument.defaultView;
+ let clicked: Event | null = null;
+ const grab = (event: Event) => {
+ if (clicked == null && event.target === element) {
+ clicked = event;
+ }
+ };
+ view?.addEventListener('click', grab, true);
+ try {
+ element.click();
+ } finally {
+ view?.removeEventListener('click', grab, true);
+ }
+ return (clicked as Event | null)?.defaultPrevented === true;
+}
+
+/**
+ * Create a tracker. `getOptions` is read on every call, so a hook can pass
+ * the latest props without recreating it.
+ */
+export function createActionGroupTracker(
+ getOptions: () => ActionGroupTrackerOptions,
+): ActionGroupTracker {
+ let actions: TrackedAction[] = [];
+ let highlighted: HTMLElement | null = null;
+ let beganOn: HTMLElement | null = null;
+ let isTracking = false;
+ let isInert = false;
+ // The finger's last position: `remeasure` resolves it again.
+ let lastX = 0;
+ let lastY = 0;
+ const fades = new Map<Element, ReturnType<typeof setTimeout>>();
+
+ const paints = () => getOptions().paintsHighlight !== false;
+
+ const clearFade = (element: Element) => {
+ const fade = fades.get(element);
+ if (fade != null) {
+ clearTimeout(fade);
+ fades.delete(element);
+ }
+ };
+ const paint = (element: HTMLElement) => {
+ if (!paints()) {
+ return;
+ }
+ clearFade(element);
+ element.setAttribute(PRESSED_ATTRIBUTE, 'on');
+ };
+ const cut = (element: HTMLElement) => {
+ if (!paints()) {
+ return;
+ }
+ clearFade(element);
+ element.removeAttribute(PRESSED_ATTRIBUTE);
+ };
+ const release = (element: HTMLElement) => {
+ if (!paints()) {
+ return;
+ }
+ clearFade(element);
+ element.setAttribute(PRESSED_ATTRIBUTE, 'fading');
+ fades.set(
+ element,
+ setTimeout(() => {
+ fades.delete(element);
+ if (element.getAttribute(PRESSED_ATTRIBUTE) === 'fading') {
+ element.removeAttribute(PRESSED_ATTRIBUTE);
+ }
+ }, PRESS_FADE_MS),
+ );
+ };
+
+ const highlight = (next: HTMLElement | null) => {
+ if (next === highlighted) {
+ return;
+ }
+ const previous = highlighted;
+ if (previous != null) {
+ cut(previous);
+ }
+ highlighted = next;
+ if (next != null) {
+ paint(next);
+ }
+ getOptions().onHighlightChange?.(next, previous);
+ };
+
+ 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 actionAt = (x: number, y: number): HTMLElement | null => {
+ const {resolveTarget, highlightExpansion: margin} = getOptions();
+ if (resolveTarget != null) {
+ return actions.length === 0 ? null : resolveTarget(x, y, actions);
+ }
+ for (const action of actions) {
+ if (
+ x >= action.left - margin &&
+ x <= action.right + margin &&
+ y >= action.top - margin &&
+ y <= action.bottom + margin
+ ) {
+ return action.element;
+ }
+ }
+ return null;
+ };
+
+ const reset = () => {
+ actions = [];
+ highlighted = null;
+ beganOn = null;
+ isTracking = false;
+ isInert = false;
+ };
+
+ return {
+ begin(x, y, {inert = false} = {}) {
+ // A press can begin while another is tracked, when a second recognizer
+ // takes over the finger (a trigger's held press, then the menu's): the
+ // action the first one lit loses its paint.
+ const previous = highlighted;
+ if (previous != null) {
+ cut(previous);
+ }
+ // An inert press tracks no action: nothing to paint, nothing to run.
+ actions = inert ? [] : measure();
+ highlighted = null;
+ isTracking = true;
+ isInert = inert;
+ lastX = x;
+ lastY = y;
+ getOptions().onMove?.(x, y);
+ const target = actionAt(x, y);
+ beganOn = target;
+ if (target != null) {
+ highlighted = target;
+ paint(target);
+ }
+ if (target !== previous) {
+ getOptions().onHighlightChange?.(target, previous);
+ }
+ },
+ move(x, y) {
+ if (!isTracking) {
+ return;
+ }
+ lastX = x;
+ lastY = y;
+ getOptions().onMove?.(x, y);
+ highlight(actionAt(x, y));
+ },
+ end() {
+ const lifted = highlighted;
+ const wasTracking = isTracking;
+ reset();
+ if (!wasTracking || lifted == null) {
+ return null;
+ }
+ release(lifted);
+ if (lifted.matches(DISABLED)) {
+ return null;
+ }
+ const {onActivate, onActivated, swallowsNativeClick} = getOptions();
+ if (onActivate != null) {
+ onActivate(lifted);
+ } else {
+ const cancelled = clickAndReport(lifted);
+ onActivated?.(lifted, cancelled);
+ }
+ const view = lifted.ownerDocument.defaultView;
+ if (swallowsNativeClick === true && view != null) {
+ swallowNextClick(view);
+ }
+ return lifted;
+ },
+ cancel() {
+ const current = highlighted;
+ const wasTracking = isTracking;
+ reset();
+ if (current != null) {
+ cut(current);
+ if (wasTracking) {
+ getOptions().onHighlightChange?.(null, current);
+ }
+ }
+ },
+ offsetBy(dx, dy) {
+ for (const action of actions) {
+ action.left += dx;
+ action.right += dx;
+ action.top += dy;
+ action.bottom += dy;
+ }
+ },
+ remeasure() {
+ if (!isTracking || isInert) {
+ return;
+ }
+ actions = measure();
+ highlight(actionAt(lastX, lastY));
+ },
+ get highlighted() {
+ return highlighted;
+ },
+ get beganOn() {
+ return beganOn;
+ },
+ get isTracking() {
+ return isTracking;
+ },
+ dispose() {
+ for (const [element, fade] of fades) {
+ clearTimeout(fade);
+ if (element.getAttribute(PRESSED_ATTRIBUTE) === 'fading') {
+ element.removeAttribute(PRESSED_ATTRIBUTE);
+ }
+ }
+ fades.clear();
+ reset();
+ },
+ };
+}