An open source design system that's fully customizable and agent ready
TypeScript
fix(core): a finger held on a control's box picks it, not the text (#10091)
Christopher Chedeauadd05168f00c
diff --git a/.changeset/box-hold-no-selection.md b/.changeset/box-hold-no-selection.mdnew file mode 100644index 0000000000..ab2c862a06--- /dev/null+++ b/.changeset/box-hold-no-selection.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Under a finger or a pen, holding the box of a CheckboxInput, a CheckboxList row, a RadioList option or a Switch no longer selects the text beside it, and lifting it activates the control as a tap does. On iOS such a hold selected the label's text and, except on a Switch, toggled nothing. A long press that opens a ContextMenu or runs a row's own long press no longer also toggles a box under it, and a row that opens its own menu from its contextmenu keeps its box unchanged. A long press on the label still selects its text, and a mouse is unchanged.++@vjeuxdiff --git a/apps/storybook/stories/BoxHoldA11y.stories.tsx b/apps/storybook/stories/BoxHoldA11y.stories.tsxnew file mode 100644index 0000000000..753c6419ea--- /dev/null+++ b/apps/storybook/stories/BoxHoldA11y.stories.tsx@@ -0,0 +1,122 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BoxHoldA11y.stories.tsx+ * @input A ContextMenu around a CheckboxInput and a CheckboxList, and a+ * popover ContextMenu around a CheckboxInput. A useLongPress row and an+ * onContextMenu row, each around a CheckboxInput.+ * @output Fixtures for the real-touch check of a long press on a box. Inside+ * a ContextMenu, a long-press row or an onContextMenu row, the long press+ * acts and the box adds no click. The visual matrix skips them.+ * @position Browser fixtures for the box hold+ * (packages/core/src/utils/boxHold.ts)+ */++import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';+import {CheckboxList, CheckboxListItem} from '@astryxdesign/core/CheckboxList';+import {ContextMenu} from '@astryxdesign/core/ContextMenu';+import {useLongPress} from '@astryxdesign/core/hooks';++const meta: Meta = {+ title: 'A11y/BoxHold',+ tags: ['no-visual'],+};++export default meta;++const rowActions = [+ {label: 'Rename', onClick: () => {}},+ {label: 'Archive', onClick: () => {}},+];++export const InContextMenu: StoryObj = {+ name: 'Boxes in a ContextMenu',+ render: function InContextMenuStory() {+ const [isAccepted, setIsAccepted] = useState(false);+ const [channels, setChannels] = useState<string[]>([]);+ return (+ <ContextMenu items={rowActions} label="Row actions">+ <CheckboxInput+ label="Accept terms"+ value={isAccepted}+ onChange={setIsAccepted}+ />+ <CheckboxList+ label="Notifications"+ value={channels}+ onChange={setChannels}>+ <CheckboxListItem label="Email" value="email" />+ <CheckboxListItem label="SMS" value="sms" />+ </CheckboxList>+ </ContextMenu>+ );+ },+};++export const InPopoverContextMenu: StoryObj = {+ name: 'A box in a popover ContextMenu',+ render: function InPopoverContextMenuStory() {+ const [isAccepted, setIsAccepted] = useState(false);+ return (+ <ContextMenu+ items={rowActions}+ label="Row actions"+ presentation="popover">+ <CheckboxInput+ label="Accept terms"+ value={isAccepted}+ onChange={setIsAccepted}+ />+ </ContextMenu>+ );+ },+};++export const InLongPressRow: StoryObj = {+ name: 'A box in a long-press row',+ render: function InLongPressRowStory() {+ const [isAccepted, setIsAccepted] = useState(false);+ const [longPresses, setLongPresses] = useState(0);+ const {onTouchStart, onTouchMove, onTouchEnd, onTouchCancel} = useLongPress(+ {onLongPress: () => setLongPresses(count => count + 1)},+ );+ return (+ <div+ onTouchStart={onTouchStart}+ onTouchMove={onTouchMove}+ onTouchEnd={onTouchEnd}+ onTouchCancel={onTouchCancel}>+ <CheckboxInput+ label="Accept terms"+ value={isAccepted}+ onChange={setIsAccepted}+ />+ <div>{`Long presses: ${longPresses}`}</div>+ </div>+ );+ },+};++export const InOnContextMenuRow: StoryObj = {+ name: 'A box in an onContextMenu row',+ render: function InOnContextMenuRowStory() {+ const [isAccepted, setIsAccepted] = useState(false);+ const [isMenuOpen, setIsMenuOpen] = useState(false);+ return (+ <div+ onContextMenu={event => {+ event.preventDefault();+ setIsMenuOpen(true);+ }}>+ <CheckboxInput+ label="Accept terms"+ value={isAccepted}+ onChange={setIsAccepted}+ />+ <div>{`Row menu: ${isMenuOpen ? 'open' : 'closed'}`}</div>+ </div>+ );+ },+};diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.mdindex ce0b3679f4..dc359d1aa1 100644--- a/docs/specs/AST-094-touch-presentations/spec.md+++ b/docs/specs/AST-094-touch-presentations/spec.md@@ -696,7 +696,9 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 andelement's existing always-on suppression stays as it is. On a label or plaintext whose hold does nothing, such as a checkbox row's label, a long pressselects natively, with the browser's handles; any other element follows its- own record. Keyboard and assistive-technology selection are unchanged. A pen's hold+ own record.+ A finger held on a control's own box (its non-text part) starts no text selection; lifting it activates the control as a tap does. Text beside it keeps native selection.+ Keyboard and assistive-technology selection are unchanged. A pen's holdacts as a finger's; a mouse makes the context request by a right click, nota long press (FR43), and otherwise keeps its released behavior(`spec:AST-017` FR59; DEC-9). A mouse or pen drag that a recognizer claims@@ -1041,6 +1043,7 @@ Motion that FR45 moves, by component. Each component's record carries its own li| FR34, FR35 | Browser tests and storyboards under a finger | a sub-menu drilling in and its Back row returning; a tap and a drag during a popover's and a menu's growth; a pinch during growth; a mouse; a tap and a drag during an alert's, a sheet's, and a dialog's entrance; a key and a screen reader during an entrance; a pinch during an alert's and a sheet's entrance; a tap and a scroll on the page beside an entering non-modal sheet, which pass | a drill-in that leaves the parent's rows in place, a change between levels that does not play on the theme's move duration and easing tokens, a tap during growth that closes, scrolls or moves focus, a pinch blocked other than by the author's `touch-action`, or a changed mouse path, a held key or assistive-technology activation, a hidden content tree, or a tap or drag during an entrance that closes the presentation, scrolls a held page, moves focus or reaches anything beneath, fails || FR36–FR40 | Release tests on synthetic touch streams with explicit timestamps, per use | below and past each commit point; a flick that projects past it; a slow drag past it; a release moving back; Reduce Motion; keyboard and mouse paths | a decision that changes mid-settle, a release moving back that commits, a settle that does not start at the release velocity (a paging release starts its settle per FR6's paging paragraph, DEC-25), or an action with no keyboard or mouse path fails || FR41 | Browser tests with real touch input (`spec:AST-013` FR10) | a tap; a long press on a ContextMenu trigger, a DropdownMenu trigger the caller renders, a row with a context menu, and a slider thumb; a long press on a checkbox row's label and on plain text; a cancelled press; mouse and keyboard selection; a pen long press; a mouse long press, which makes no context request; a mouse drag a recognizer claims, with and without a page selection; a mouse drag that starts on selectable text | a tap that selects, a hold with an action that starts a selection or callout, a label or plain text whose long press does not select natively, a suppression that outlives the press, a change to native selection elsewhere, to keyboard or assistive-technology selection, or to mouse selection outside a drag a recognizer claims, a claimed drag that takes a new selection or after which an existing one does not survive, or a drag starting on text that does not select text fails |+| FR41 (box) | Browser tests with real touch input (`spec:AST-013` FR10), and Mobile Safari on an iOS simulator | a finger held on the box of a checkbox, a CheckboxList row, a radio option and a switch, then lifted still; the same hold on the label beside it; a tap on the box; a hold that moves away; a mouse press on the box | a hold on a box that starts a selection or the callout, a still lift that does not activate the control exactly once, a label whose long press does not select natively, a suppression that outlives the press, or a change to a mouse press fails || FR42 | Default-theme geometry tests under a coarse and a fine pointer, and hit-testing between adjacent targets | every component at phone width with a finger and with a mouse; a dense toolbar; a chip and its remove button; a Switch beside a label link | a default-theme box that grows under touch or at phone width other than with its text, or, where no component or module record sets the hit area, a touch target under 44 px where neighbors allow it or a hit area that overlaps a neighbor's target, fails || FR43 | Browser tests with a mouse, a trackpad, a pen, a finger, and the keyboard, and resource counts | a pan by drag and by wheel; a slider's thumb under a wheel and a trackpad scroll; a ctrl-wheel pinch; a long press, a right click, and Shift+F10; a mouse press; a handle drag; a row swipe with a mouse and a trackpad; a component with no gesture | a gesture missing under a mouse or pen, a mouse-drag swipe action, a pen pinch, an edge pan under a mouse, a trackpad, or a pen, a press delay under a fine pointer, a wheel or trackpad scroll that changes a thumb's value or does not reach the scroll under it, an idle listener in a component with no gesture, or added stylesheet bytes, fails || FR43 trackpad | Unit tests on timed wheel streams; WebKit browser tests with trackpad streams (Chromium's driver wheels read as a mouse wheel) | a form and a required sheet pulled 30 to 240 px by a finger and by a trackpad; mouse lines, notches, ticks and accelerated deltas over a sheet, a pager and a row; ten swipes each starting mid-momentum, ten whose momentum ends, and a slow drag with 150 ms pauses; a trackpad flick and a slow stopped drag on an info sheet; a fling, a slow 60 px swipe, a 42 px spike and back-to-back swipes on a pager; a row opened and swiped back within one gesture, and a long fast swipe; a pinch ending; a trackpad pan through a window blur and through a hidden page | a trackpad stretch that differs from a finger's for the same travel (120 px gives 54 px on the reference sheet), a mouse wheel that moves a sheet, a pager or a row, splitter counts other than ten, ten and one, momentum that moves a surface, a flick released with no velocity, a pager that travels past one page or pages on a spike, an info sheet a flick leaves open or a slow stopped drag closes, an open row that reveals its other side within one gesture, a trackpad pan a window blur or a hidden page leaves mid-gesture, or a pinch that ends after 100 ms fails |diff --git a/packages/core/src/CheckboxInput/CheckboxInput.tsx b/packages/core/src/CheckboxInput/CheckboxInput.tsxindex 9c7b3d6f46..58989d9fc3 100644--- a/packages/core/src/CheckboxInput/CheckboxInput.tsx+++ b/packages/core/src/CheckboxInput/CheckboxInput.tsx@@ -61,6 +61,8 @@ import {themeProps} from '../utils/themeProps';import {useMergedRefs} from '../hooks/useMergedRefs';import {useTouchHitArea} from '../utils/touchHitArea';+import {pressBoxProps} from '../privateAttributes/pressBox.stylex';+import {registerBoxHold} from '../utils/boxHold';import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';import {registerEnglishFallback,@@ -70,6 +72,9 @@ import english from '../i18n/generated-english/CheckboxInput/CheckboxInput.generimport {CheckboxRowPressContext} from './CheckboxRowPressContext';registerEnglishFallback(english);+// Registered here, not in the press controller, so a page with no box carries+// none of its code.+registerBoxHold();/** Written by the touch press controller while the row is pressed. */const PRESSED_ON = '[data-astryx-press="on"]';@@ -562,6 +567,10 @@ export function CheckboxInput({ownsPress && interactionOverlayStyles.pressedAlpha,)}><div+ // iOS answers a long hold on the box with a text selection and no+ // click. The press controller holds the row's selection for a press+ // on the marked box, and checks it if no click comes.+ {...(isDisabled ? undefined : pressBoxProps)}{...stylex.props(styles.checkboxWrapper,wrapperSizeStyles[size],diff --git a/packages/core/src/Indicator/__tests__/BoxHold.interaction.browser.spec.ts b/packages/core/src/Indicator/__tests__/BoxHold.interaction.browser.spec.tsnew file mode 100644index 0000000000..beb4091377--- /dev/null+++ b/packages/core/src/Indicator/__tests__/BoxHold.interaction.browser.spec.ts@@ -0,0 +1,541 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file BoxHold.interaction.browser.spec.ts+ * @input The built CheckboxInput, CheckboxList, RadioList and Switch stories,+ * the A11y/BoxHold fixture, real touch input and the interaction harness+ * @output Proofs that a finger held on a control's box refuses a selection+ * of the text beside it until the lift. The lift toggles the control+ * exactly once. A long press that opens a ContextMenu, that a row around the+ * box runs, or whose contextmenu opens a row's menu, leaves it unchanged. A+ * hold that moves away activates nothing. A tap stays the browser's own: its+ * lift is not cancelled, its click activates, and focus moves as on a plain+ * checkbox. A finger held on the label and a mouse held on the box keep+ * their native behavior.+ * @position Real-engine layer; the unit layers are utils/boxHold.test.ts and+ * Indicator/boxHold.test.tsx+ */++import {+ expect,+ test,+ type Browser,+ type Page,+ type TestInfo,+} from '@astryxdesign/a11y-spec/playwright';+import {+ openStory,+ touchDriver,+ withStorybook,+} from '@astryxdesign/interaction-harness';+import {BROWSER_CLICK_WAIT_MS} from '../../utils/browserClickWait';++const storybook = withStorybook(test);++/** Longer than a long press, so iOS would select instead of clicking. */+const HOLD_MS = 900;++interface Control {+ readonly story: string;+ readonly role: 'checkbox' | 'radio' | 'switch';+ readonly index: number;+}++const CONTROLS: ReadonlyArray<Control> = [+ {story: 'core-checkboxinput--default', role: 'checkbox', index: 0},+ {story: 'core-checkboxlist--default', role: 'checkbox', index: 1},+ {story: 'core-radiolist--default', role: 'radio', index: 1},+ {story: 'core-switch--default', role: 'switch', index: 0},+];++interface Point {+ x: number;+ y: number;+}++/** The centre of the control's box and a point on the text beside it. */+async function pointsOf(page: Page, control: Control) {+ return page+ .getByRole(control.role)+ .nth(control.index)+ .evaluate(input => {+ const box = input.parentElement?.getBoundingClientRect();+ if (box == null) {+ throw new Error('the control has no box');+ }+ return {+ box: {x: box.x + box.width / 2, y: box.y + box.height / 2},+ text: {x: box.right + 24, y: box.y + box.height / 2},+ };+ });+}++/**+ * Counts the control's activations: every `change` of its input from now on.+ */+async function countChanges(page: Page, control: Control): Promise<void> {+ await page+ .getByRole(control.role)+ .nth(control.index)+ .evaluate(input => {+ const host = window as unknown as {__boxHoldChanges: number};+ host.__boxHoldChanges = 0;+ input.addEventListener('change', () => {+ host.__boxHoldChanges += 1;+ });+ });+}++/**+ * How a test finger reaches the page. Touch events sent to the page get the+ * browser's click after a long hold, as on iOS. Chromium's own gesture path+ * sends none, as on Android.+ */+type TouchPath = 'touch events' | 'gesture';++/** The paths each engine offers: the gesture path is Chromium's. */+function touchPaths(browserName: string): ReadonlyArray<TouchPath> {+ return browserName === 'chromium'+ ? ['touch events', 'gesture']+ : ['touch events'];+}++/**+ * A finger held `ms` on `at`, then lifted, resolving once the page has the+ * lift.+ */+async function longTouch(+ page: Page,+ path: TouchPath,+ at: Point,+ ms: number,+): Promise<void> {+ await page.evaluate(() => {+ const host = window as unknown as {__boxHoldLifted: boolean};+ host.__boxHoldLifted = false;+ document.addEventListener(+ 'pointerup',+ () => {+ host.__boxHoldLifted = true;+ },+ {capture: true, once: true},+ );+ });+ if (path === 'gesture') {+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('Input.synthesizeTapGesture', {+ x: at.x,+ y: at.y,+ duration: ms,+ tapCount: 1,+ gestureSourceType: 'touch',+ });+ await cdp.detach();+ } else {+ const driver = await touchDriver(page);+ await driver.play([+ {t: 0, fingers: [{id: 1, ...at}]},+ {t: ms, fingers: []},+ ]);+ }+ await page.waitForFunction(+ () => (window as unknown as {__boxHoldLifted: boolean}).__boxHoldLifted,+ );+}++async function changes(page: Page): Promise<number> {+ return page.evaluate(+ () => (window as unknown as {__boxHoldChanges: number}).__boxHoldChanges,+ );+}++/**+ * Whether a selection that starts at `at` is refused. Each engine refuses+ * one its own way: a style on iOS WebKit, a cancelled `selectstart`+ * elsewhere.+ */+async function refusesSelectionAt(page: Page, at: Point): Promise<boolean> {+ return page.evaluate(({x, y}) => {+ const target = document.elementFromPoint(x, y);+ if (target == null) {+ throw new Error('nothing at the text point');+ }+ if (CSS.supports('(-webkit-touch-callout: none)')) {+ const style = getComputedStyle(target);+ return (+ (style.getPropertyValue('-webkit-user-select') ||+ style.getPropertyValue('user-select')) === 'none'+ );+ }+ const event = new Event('selectstart', {bubbles: true, cancelable: true});+ target.dispatchEvent(event);+ return event.defaultPrevented;+ }, at);+}++/**+ * Resolves after a timer of `ms` queued now on the page. A stand-in click+ * waits on a page timer queued at the lift, before this one. With the same+ * delay, this one runs after it, however late the page runs.+ */+async function afterPageTimer(page: Page, ms: number): Promise<void> {+ await page.evaluate(async delay => {+ await new Promise<void>(resolve => {+ setTimeout(resolve, delay);+ });+ }, ms);+}++/** Holds a finger at `at`, reading `during` while it is down. */+async function holdFinger<T>(+ page: Page,+ at: Point,+ during: () => Promise<T>,+): Promise<T> {+ const driver = await touchDriver(page);+ let read: T | undefined;+ let isRead = false;+ await driver.play(+ [+ {t: 0, fingers: [{id: 1, ...at}]},+ {t: HOLD_MS, fingers: []},+ ],+ {+ onEvent: async step => {+ if (step.type === 'touchStart') {+ read = await during();+ isRead = true;+ }+ },+ },+ );+ if (!isRead) {+ throw new Error('the hold was not read');+ }+ return read as T;+}++/** Where focus is: on the text field, on the tapped control, or elsewhere. */+type FocusKind = 'field' | 'control' | 'other';++/**+ * Adds a text field and a plain checkbox, which no component owns, at the+ * page's foot. The plain checkbox's tap is the engine's own tap.+ */+async function addFieldAndPlainCheckbox(page: Page): Promise<Point> {+ return page.evaluate(() => {+ const field = document.createElement('input');+ field.type = 'text';+ field.id = 'box-hold-field';+ field.style.cssText = 'position:fixed;left:16px;bottom:200px;width:160px';+ const plain = document.createElement('input');+ plain.type = 'checkbox';+ plain.id = 'box-hold-plain';+ plain.style.cssText =+ 'position:fixed;left:16px;bottom:140px;width:24px;height:24px;margin:0';+ document.body.append(field, plain);+ const r = plain.getBoundingClientRect();+ return {x: r.x + r.width / 2, y: r.y + r.height / 2};+ });+}++/** Focuses the text field, taps at `at`, and says where focus went. */+async function tapFromField(+ page: Page,+ at: Point,+ control: string,+): Promise<FocusKind> {+ await page.evaluate(() => document.getElementById('box-hold-field')?.focus());+ const driver = await touchDriver(page);+ await driver.tap(at);+ await page.waitForTimeout(400);+ return page.evaluate(selector => {+ const active = document.activeElement;+ if (active?.id === 'box-hold-field') {+ return 'field';+ }+ return active != null && active === document.querySelector(selector)+ ? 'control'+ : 'other';+ }, control);+}++/** The same story with a mouse: the phone's viewport and scale, a fine pointer. */+async function withMouse<T>(+ browser: Browser,+ testInfo: TestInfo,+ run: (mousePage: Page) => Promise<T>,+): Promise<T> {+ const {viewport, deviceScaleFactor} = testInfo.project.use;+ const context = await browser.newContext({+ viewport,+ deviceScaleFactor,+ hasTouch: false,+ isMobile: false,+ });+ try {+ return await run(await context.newPage());+ } finally {+ await context.close();+ }+}++test.describe('a finger held on a control’s box', () => {+ for (const control of CONTROLS) {+ test(`${control.story}: refuses a selection beside the box until the lift, which toggles it once`, async ({+ page,+ }) => {+ await openStory(page, storybook(), control.story);+ const points = await pointsOf(page, control);+ await countChanges(page, control);+ expect(await refusesSelectionAt(page, points.text)).toBe(false);+ const whileHeld = await holdFinger(page, points.box, async () =>+ refusesSelectionAt(page, points.text),+ );+ expect(whileHeld).toBe(true);+ await expect.poll(async () => changes(page)).toBe(1);+ expect(await refusesSelectionAt(page, points.text)).toBe(false);+ // Nothing activates it a second time once the press has ended.+ await afterPageTimer(page, BROWSER_CLICK_WAIT_MS);+ expect(await changes(page)).toBe(1);+ });+ }++ test('a tap on the box is the browser’s own: its lift is not cancelled, and its click activates', async ({+ page,+ }) => {+ for (const control of CONTROLS) {+ await openStory(page, storybook(), control.story);+ const points = await pointsOf(page, control);+ await countChanges(page, control);+ await page.evaluate(() => {+ const seen = {prevented: null as boolean | null};+ Object.assign(window, {__tapEnd: seen});+ // Bubbling to the window, the lift has passed every handler below.+ window.addEventListener('touchend', event => {+ seen.prevented = event.defaultPrevented;+ });+ });+ const driver = await touchDriver(page);+ await driver.tap(points.box);+ // Before the fallback's wait ends, so only the browser's click counts.+ await page.waitForTimeout(150);+ expect(await changes(page), control.story).toBe(1);+ expect(+ await page.evaluate(+ () =>+ (window as unknown as {__tapEnd: {prevented: boolean | null}})+ .__tapEnd.prevented,+ ),+ control.story,+ ).toBe(false);+ await afterPageTimer(page, BROWSER_CLICK_WAIT_MS);+ expect(await changes(page), control.story).toBe(1);+ }+ });++ test('a tap on a checkbox’s box moves focus as a plain checkbox’s tap does', async ({+ page,+ }) => {+ // These boxes are their inputs, so the plain checkbox is the baseline.+ for (const control of CONTROLS.slice(0, 2)) {+ await openStory(page, storybook(), control.story);+ const plain = await addFieldAndPlainCheckbox(page);+ const points = await pointsOf(page, control);+ await countChanges(page, control);+ const native = await tapFromField(page, plain, '#box-hold-plain');+ // The plain checkbox comes last in the page, so the index still holds.+ await page+ .getByRole(control.role)+ .nth(control.index)+ .evaluate(input => input.setAttribute('data-box-hold-target', ''));+ const own = await tapFromField(+ page,+ points.box,+ '[data-box-hold-target]',+ );+ expect(own, control.story).toBe(native);+ expect(await changes(page), control.story).toBe(1);+ }+ });++ test('a hold on one box, then a tap on the next box inside the wait, activates the held box once', async ({+ page,+ }) => {+ await openStory(page, storybook(), 'core-checkboxlist--default');+ const boxes = page.getByRole('checkbox');+ const first = {story: '', role: 'checkbox', index: 0} as const;+ const second = {story: '', role: 'checkbox', index: 1} as const;+ const at = [await pointsOf(page, first), await pointsOf(page, second)];+ await boxes.evaluateAll(inputs => {+ const counts = [0, 0];+ Object.assign(window, {__boxHoldEach: counts});+ inputs.slice(0, 2).forEach((input, index) => {+ input.addEventListener('change', () => {+ counts[index] += 1;+ });+ });+ });+ const driver = await touchDriver(page);+ await driver.play([+ {t: 0, fingers: [{id: 1, ...at[0].box}]},+ {t: HOLD_MS, fingers: []},+ {t: HOLD_MS + 100, fingers: [{id: 2, ...at[1].box}]},+ {t: HOLD_MS + 150, fingers: []},+ ]);+ const counts = async () =>+ page.evaluate(+ () => (window as unknown as {__boxHoldEach: number[]}).__boxHoldEach,+ );+ await expect.poll(async () => (await counts())[0]).toBe(1);+ await afterPageTimer(page, BROWSER_CLICK_WAIT_MS);+ const [held, tapped] = await counts();+ expect(held).toBe(1);+ // The tap's own activation is the engine's. Chromium clicks it, and+ // WebKit sends no click this soon after the hold, as on main.+ expect(tapped).toBeLessThanOrEqual(1);+ });++ test('a long press that opens a ContextMenu over a box leaves the box unchanged', async ({+ page,+ browserName,+ }) => {+ const cases = [+ {story: 'a11y-boxhold--in-context-menu', index: 0},+ {story: 'a11y-boxhold--in-context-menu', index: 2},+ {story: 'a11y-boxhold--in-popover-context-menu', index: 0},+ ];+ for (const path of touchPaths(browserName)) {+ for (const ms of [HOLD_MS, 1200]) {+ for (const {story, index} of cases) {+ await openStory(page, storybook(), story);+ const control = {story, role: 'checkbox', index} as const;+ const points = await pointsOf(page, control);+ await countChanges(page, control);+ await longTouch(page, path, points.box, ms);+ await expect(page.getByText('Rename').first()).toBeVisible();+ await afterPageTimer(page, BROWSER_CLICK_WAIT_MS);+ expect+ .soft(+ await changes(page),+ `${path}: ${story} box ${index}, ${ms} ms`,+ )+ .toBe(0);+ }+ }+ }+ });++ test('a hold in a long-press row runs the row’s long press and leaves the box unchanged', async ({+ page,+ browserName,+ }) => {+ const story = 'a11y-boxhold--in-long-press-row';+ for (const path of touchPaths(browserName)) {+ for (const ms of [HOLD_MS, 1200]) {+ await openStory(page, storybook(), story);+ const control = {story, role: 'checkbox', index: 0} as const;+ const points = await pointsOf(page, control);+ await countChanges(page, control);+ await longTouch(page, path, points.box, ms);+ await expect(page.getByText('Long presses: 1')).toBeVisible();+ await afterPageTimer(page, BROWSER_CLICK_WAIT_MS);+ expect.soft(await changes(page), `${path}, ${ms} ms`).toBe(0);+ }+ }+ });++ test('a hold in an onContextMenu row opens the row’s menu and leaves the box unchanged', async ({+ page,+ browserName,+ }) => {+ // Chromium on Android sends a long press as a contextmenu, and no click+ // follows. No engine here sends one for a touch. So the page sends it+ // 600 ms into the hold, on paths with no click after a long press.+ const story = 'a11y-boxhold--in-on-context-menu-row';+ const path: TouchPath =+ browserName === 'chromium' ? 'gesture' : 'touch events';+ await openStory(page, storybook(), story);+ const control = {story, role: 'checkbox', index: 0} as const;+ const points = await pointsOf(page, control);+ await countChanges(page, control);+ await page+ .getByRole('checkbox')+ .first()+ .evaluate(input => {+ input.addEventListener(+ 'pointerdown',+ () => {+ setTimeout(() => {+ input.dispatchEvent(+ new MouseEvent('contextmenu', {+ bubbles: true,+ cancelable: true,+ }),+ );+ }, 600);+ },+ {once: true},+ );+ });+ await longTouch(page, path, points.box, 1500);+ await expect(page.getByText('Row menu: open')).toBeVisible();+ await afterPageTimer(page, BROWSER_CLICK_WAIT_MS);+ expect(await changes(page), path).toBe(0);+ });++ test('a hold that moves away activates nothing and leaves no lock', async ({+ page,+ }) => {+ for (const control of CONTROLS.slice(0, 3)) {+ await openStory(page, storybook(), control.story);+ const points = await pointsOf(page, control);+ await countChanges(page, control);+ const away = {x: points.box.x + 60, y: points.box.y};+ const driver = await touchDriver(page);+ await driver.play([+ {t: 0, fingers: [{id: 1, ...points.box}]},+ {t: 600, fingers: [{id: 1, ...points.box}]},+ {t: 700, fingers: [{id: 1, ...away}]},+ {t: HOLD_MS, fingers: []},+ ]);+ await afterPageTimer(page, BROWSER_CLICK_WAIT_MS);+ expect(await changes(page), control.story).toBe(0);+ expect(await refusesSelectionAt(page, points.text), control.story).toBe(+ false,+ );+ }+ });++ test('a finger held on the label takes no lock, so the label keeps native selection', async ({+ page,+ }) => {+ const control = CONTROLS[0];+ await openStory(page, storybook(), control.story);+ const points = await pointsOf(page, control);+ const whileHeld = await holdFinger(page, points.text, async () =>+ refusesSelectionAt(page, points.text),+ );+ expect(whileHeld).toBe(false);+ });++ test('a mouse held on the box takes no lock and toggles once, as before', async ({+ browser,+ }, testInfo) => {+ await withMouse(browser, testInfo, async mousePage => {+ for (const control of CONTROLS) {+ await openStory(mousePage, storybook(), control.story);+ const points = await pointsOf(mousePage, control);+ await countChanges(mousePage, control);+ await mousePage.mouse.move(points.box.x, points.box.y);+ await mousePage.mouse.down();+ await mousePage.waitForTimeout(HOLD_MS);+ expect(+ await refusesSelectionAt(mousePage, points.text),+ control.story,+ ).toBe(false);+ await mousePage.mouse.up();+ await expect.poll(async () => changes(mousePage)).toBe(1);+ }+ });+ });+});diff --git a/packages/core/src/Indicator/boxHold.test.tsx b/packages/core/src/Indicator/boxHold.test.tsxnew file mode 100644index 0000000000..05bd93d001--- /dev/null+++ b/packages/core/src/Indicator/boxHold.test.tsx@@ -0,0 +1,336 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file boxHold.test.tsx+ * @input CheckboxInput, CheckboxList, RadioList and Switch in jsdom, pointer+ * and touch events built by hand, a coarse pointer and fake timers+ * @output Checks that a finger held on each control's box refuses a selection+ * of the label beside it until the lift. A still lift that gets no browser+ * click picks a checkbox, a CheckboxList row and a radio option once, after+ * the wait. A read-only checkbox's lift changes nothing, as its tap does. A+ * long press that opens a ContextMenu around a box, or that a row around it+ * runs, leaves it unchanged: the lift's touchend is cancelled. So does a+ * row that opens its own menu from the hold's contextmenu. A tap on a+ * second box leaves the first box's activation in place. A switch takes the+ * lock. A press on the label takes none.+ * @position Component layer of utils/boxHold.ts (unit layer:+ * utils/boxHold.test.ts); the browser layer is+ * Indicator/__tests__/BoxHold.interaction.browser.spec.ts+ */++import {act, fireEvent, render, screen} from '@testing-library/react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {CheckboxInput} from '../CheckboxInput/CheckboxInput';+import {CheckboxList} from '../CheckboxList/CheckboxList';+import {CheckboxListItem} from '../CheckboxList/CheckboxListItem';+import {ContextMenu} from '../ContextMenu/ContextMenu';+import {useLongPress} from '../hooks/useLongPress';+import {RadioList} from '../RadioList/RadioList';+import {RadioListItem} from '../RadioList/RadioListItem';+import {Switch} from '../Switch/Switch';+import {coarsePrimaryPointer} from '../gestures/__tests__/pointerQuery';+import {stubMatchMedia} from '../__tests__/stubMatchMedia';+import {BROWSER_CLICK_WAIT_MS} from '../utils/browserClickWait';++/** Dispatches a finger's pointer event, which the shared press controller hears. */+function press(target: Element, type: 'pointerdown' | 'pointerup') {+ const event = new Event(type, {bubbles: true, cancelable: true});+ Object.assign(event, {+ button: 0,+ clientX: 1,+ clientY: 1,+ pointerId: 1,+ pointerType: 'touch',+ });+ target.dispatchEvent(event);+}++/**+ * Dispatches a touch event as a browser sends it, for Switch's own tracker.+ * There is no constructible TouchEvent in jsdom, so the touch lists and the+ * time stamp are set on it.+ */+function touch(type: 'touchstart' | 'touchend', target: Element, time: number) {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const entry = {identifier: 1, clientX: 1, clientY: 1, target};+ Object.defineProperty(event, 'changedTouches', {value: [entry]});+ Object.defineProperty(event, 'touches', {+ value: type === 'touchend' ? [] : [entry],+ });+ Object.defineProperty(event, 'timeStamp', {value: time});+ target.dispatchEvent(event);+}++/** A finger held 0.9 s on `target`, then lifted. */+function hold(target: Element, during?: () => void) {+ press(target, 'pointerdown');+ act(() => {+ vi.advanceTimersByTime(900);+ });+ during?.();+ press(target, 'pointerup');+}++/** Runs out the lift's wait for the browser's click. */+function waitForNoClick() {+ act(() => {+ vi.advanceTimersByTime(BROWSER_CLICK_WAIT_MS);+ });+}++/** Whether a selection that starts on `target` is refused. */+function refuses(target: Element): boolean {+ const event = new Event('selectstart', {bubbles: true, cancelable: true});+ target.dispatchEvent(event);+ return event.defaultPrevented;+}++/**+ * A CheckboxList row's own visible text, not the hidden label its checkbox+ * keeps for its name.+ */+function rowLabel(name: string): HTMLElement {+ const label = screen+ .getAllByText(name)+ .find(element => element.closest('label') == null);+ if (label == null) {+ throw new Error(`no row text ${name}`);+ }+ return label;+}++let restorePointer: () => void = () => {};+beforeEach(() => {+ restorePointer = coarsePrimaryPointer();+ vi.useFakeTimers();+});+afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ restorePointer();+});++describe('a finger held on a control’s box', () => {+ it('refuses a selection of a checkbox’s label until the lift, and a lift with no click checks it once', () => {+ const onChange = vi.fn();+ render(+ <CheckboxInput label="Accept terms" value={false} onChange={onChange} />,+ );+ const input = screen.getByRole('checkbox', {name: 'Accept terms'});+ const label = screen.getByText('Accept terms');+ let held = false;+ hold(input, () => {+ held = refuses(label);+ });+ expect(held).toBe(true);+ expect(refuses(label)).toBe(false);+ expect(onChange).not.toHaveBeenCalled();+ waitForNoClick();+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange.mock.calls[0][0]).toBe(true);+ });++ it('leaves a read-only checkbox as its tap leaves it: the lift changes nothing', () => {+ const onChange = vi.fn();+ render(+ <CheckboxInput+ label="Accept terms"+ value={false}+ isReadOnly+ onChange={onChange}+ />,+ );+ const input = screen.getByRole<HTMLInputElement>('checkbox', {+ name: 'Accept terms',+ });+ // The tap's own click, the baseline.+ act(() => {+ input.click();+ });+ expect(onChange).not.toHaveBeenCalled();+ hold(input);+ waitForNoClick();+ expect(onChange).not.toHaveBeenCalled();+ expect(input.checked).toBe(false);+ });++ it('refuses a selection of a CheckboxList row’s label under a coarse pointer, and a lift with no click picks the row once', () => {+ stubMatchMedia({matches: true, pointer: 'coarse'});+ const onChange = vi.fn();+ render(+ <CheckboxList label="Notifications" value={[]} onChange={onChange}>+ <CheckboxListItem label="Email" value="email" />+ <CheckboxListItem label="SMS" value="sms" />+ </CheckboxList>,+ );+ const input = screen.getByRole('checkbox', {name: 'SMS'});+ let held = false;+ let neighbour = true;+ hold(input, () => {+ held = refuses(rowLabel('SMS'));+ // A neighbouring row is not the one the finger holds.+ neighbour = refuses(rowLabel('Email'));+ });+ expect(held).toBe(true);+ expect(neighbour).toBe(false);+ waitForNoClick();+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange.mock.calls[0][0]).toEqual(['sms']);+ });++ it('refuses a selection of a radio option’s label until the lift, and a lift with no click picks the option once', () => {+ const onChange = vi.fn();+ render(+ <RadioList label="Plan" value="a" onChange={onChange}>+ <RadioListItem label="Basic" value="a" />+ <RadioListItem label="Premium" value="b" />+ </RadioList>,+ );+ const input = screen.getByRole('radio', {name: 'Premium'});+ const label = screen.getByText('Premium');+ let held = false;+ hold(input, () => {+ held = refuses(label);+ });+ expect(held).toBe(true);+ expect(refuses(label)).toBe(false);+ waitForNoClick();+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange.mock.calls[0][0]).toBe('b');+ });++ it('leaves a CheckboxList row in a ContextMenu unchanged after a long press that opened the menu', () => {+ stubMatchMedia({matches: true, pointer: 'coarse'});+ const onChange = vi.fn();+ const onOpenChange = vi.fn();+ render(+ <ContextMenu items={[{label: 'Cut'}]} onOpenChange={onOpenChange}>+ <CheckboxList label="Notifications" value={[]} onChange={onChange}>+ <CheckboxListItem label="Email" value="email" />+ <CheckboxListItem label="SMS" value="sms" />+ </CheckboxList>+ </ContextMenu>,+ );+ const input = screen.getByRole('checkbox', {name: 'SMS'});+ press(input, 'pointerdown');+ fireEvent.touchStart(input, {touches: [{clientX: 1, clientY: 1}]});+ act(() => {+ vi.advanceTimersByTime(600);+ });+ expect(onOpenChange).toHaveBeenLastCalledWith(true);+ // The lift stays on the box, under the open menu. Its touchend is+ // cancelled, so the browser sends no click.+ press(input, 'pointerup');+ expect(fireEvent.touchEnd(input)).toBe(false);+ waitForNoClick();+ waitForNoClick();+ expect(onChange).not.toHaveBeenCalled();+ });++ it('leaves a checkbox in a useLongPress row unchanged after a hold that ran the row’s long press', () => {+ const onChange = vi.fn();+ const onLongPress = vi.fn();+ function LongPressRow() {+ const {onTouchStart, onTouchMove, onTouchEnd, onTouchCancel} =+ useLongPress({onLongPress});+ return (+ <div+ onTouchStart={onTouchStart}+ onTouchMove={onTouchMove}+ onTouchEnd={onTouchEnd}+ onTouchCancel={onTouchCancel}>+ <CheckboxInput+ label="Accept terms"+ value={false}+ onChange={onChange}+ />+ </div>+ );+ }+ render(<LongPressRow />);+ const input = screen.getByRole('checkbox', {name: 'Accept terms'});+ press(input, 'pointerdown');+ fireEvent.touchStart(input, {touches: [{clientX: 1, clientY: 1}]});+ act(() => {+ vi.advanceTimersByTime(900);+ });+ expect(onLongPress).toHaveBeenCalledTimes(1);+ press(input, 'pointerup');+ expect(fireEvent.touchEnd(input)).toBe(false);+ waitForNoClick();+ expect(onChange).not.toHaveBeenCalled();+ });++ it('leaves a checkbox in an onContextMenu row unchanged after a hold that opened the row’s menu', () => {+ const onChange = vi.fn();+ const onRowMenu = vi.fn();+ render(+ <div+ onContextMenu={event => {+ event.preventDefault();+ onRowMenu();+ }}>+ <CheckboxInput label="Accept terms" value={false} onChange={onChange} />+ </div>,+ );+ const input = screen.getByRole('checkbox', {name: 'Accept terms'});+ press(input, 'pointerdown');+ act(() => {+ vi.advanceTimersByTime(600);+ });+ // Chromium sends the long press as a contextmenu, and no click follows.+ expect(fireEvent.contextMenu(input)).toBe(false);+ act(() => {+ vi.advanceTimersByTime(300);+ });+ press(input, 'pointerup');+ fireEvent.touchEnd(input);+ waitForNoClick();+ expect(onRowMenu).toHaveBeenCalledTimes(1);+ expect(onChange).not.toHaveBeenCalled();+ });++ it('activates a held checkbox once when a tap on a second one follows inside the wait', () => {+ const onFirst = vi.fn();+ const onSecond = vi.fn();+ render(+ <>+ <CheckboxInput label="First" value={false} onChange={onFirst} />+ <CheckboxInput label="Second" value={false} onChange={onSecond} />+ </>,+ );+ hold(screen.getByRole('checkbox', {name: 'First'}));+ act(() => {+ vi.advanceTimersByTime(100);+ });+ // A tap's activation is the browser's click, which jsdom does not make.+ const second = screen.getByRole('checkbox', {name: 'Second'});+ press(second, 'pointerdown');+ press(second, 'pointerup');+ waitForNoClick();+ expect(onFirst).toHaveBeenCalledTimes(1);+ expect(onSecond).not.toHaveBeenCalled();+ });++ it('refuses a selection of a switch’s label until the lift', () => {+ render(<Switch label="Wi-Fi" value={false} onChange={() => {}} />);+ const input = screen.getByRole('switch', {name: 'Wi-Fi'});+ const label = screen.getByText('Wi-Fi');+ touch('touchstart', input, 0);+ const held = refuses(label);+ touch('touchend', input, 900);+ expect(held).toBe(true);+ expect(refuses(label)).toBe(false);+ });++ it('takes no lock for a press that starts on the label, which keeps native selection', () => {+ render(+ <CheckboxInput label="Accept terms" value={false} onChange={() => {}} />,+ );+ const label = screen.getByText('Accept terms');+ let held = true;+ hold(label, () => {+ held = refuses(label);+ });+ expect(held).toBe(false);+ });+});diff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsxindex ffb1f5a038..0d3984be39 100644--- a/packages/core/src/RadioList/RadioListItem.tsx+++ b/packages/core/src/RadioList/RadioListItem.tsx@@ -34,12 +34,18 @@ import {useIndicatorFocusRing} from '../hooks/useIndicatorFocusRing';import {usePressFeedback} from '../hooks/usePressFeedback';import {useMergedRefs} from '../hooks/useMergedRefs';import {useTouchHitArea} from '../utils/touchHitArea';+import {pressBoxProps} from '../privateAttributes/pressBox.stylex';+import {registerBoxHold} from '../utils/boxHold';import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';import {useIndicator} from '../Indicator/useIndicator';import {Item, type ItemAlign} from '../Item/Item';import {themeProps} from '../utils/themeProps';import {rowPressLayerStyles} from '../privateAttributes/press.stylex';+// Registered here, not in the press controller, so a page with no box carries+// none of its code.+registerBoxHold();+// The touch press's paint, declared by the shared overlay styles on the// element the controller writes to (`pressedAlpha`) at the press's strength,// 1 while on and 1 → 0 over the release, and inherited resolved by the layer@@ -317,6 +323,10 @@ export function RadioListItem({const radioCircle = (<div+ // iOS answers a long hold on the circle with a text selection and no+ // click. The press controller holds the row's selection for a press on+ // the marked circle, and picks the option if no click comes.+ {...(isDisabled ? undefined : pressBoxProps)}{...stylex.props(styles.radioWrapper,wrapperSizeStyles[size],diff --git a/packages/core/src/Switch/useSwitchTouch.ts b/packages/core/src/Switch/useSwitchTouch.tsindex f3ccd90aa2..b7bda6c98e 100644--- a/packages/core/src/Switch/useSwitchTouch.ts+++ b/packages/core/src/Switch/useSwitchTouch.ts@@ -33,6 +33,7 @@ import {registerSwitchTable, switchControl} from '../motion/uikit/switch';import {resolveMotion} from '../motion/resolveMotion';import {useTouchPresentation} from '../utils/touchPresentation';import {awaitBrowserClick, clickForLift} from '../utils/browserClickWait';+import {lockPressedRow} from '../utils/boxHold';import {armClickGuard} from '../utils/clickGuard';import {commitOnRelease,@@ -317,6 +318,8 @@ export class SwitchTouchController {getBounds: () => surface.getBoundingClientRect(),isEnabled: () => this.isInteractive,isBraking: () => host.isScrollBraking(surface),+ // A held finger selects no text beside the switch.+ selectionLock: lockPressedRow,// A held switch opens no menu (UISwitch shows none).holdsContextMenu: () => this.pressTime != null,onControlEvent: (event, touch) => this.onControlEvent(event, touch),diff --git a/packages/core/src/hooks/longPressDetector.test.ts b/packages/core/src/hooks/longPressDetector.test.tsindex 29fbd06b9c..5953f2359c 100644--- a/packages/core/src/hooks/longPressDetector.test.ts+++ b/packages/core/src/hooks/longPressDetector.test.ts@@ -6,12 +6,13 @@* @output Tests the long-press detector with no React: a hand start, a touch* press on the events' clock, a second finger, a late timer, a start handled* late, the movement tolerance, disabled, the latest options, and a touch- * with no time+ * with no time. It also checks the claim a press makes as it fires.* @position Unit coverage for longPressDetector.ts; useLongPress.test.tsx* covers the hook that wraps it*/import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {watchPressClaims} from '../utils/pressClaim';import {createLongPressDetector,type LongPressTouchEvent,@@ -60,6 +61,20 @@ describe('createLongPressDetector', () => {expect(onLongPress).toHaveBeenCalledTimes(1);});+ it('claims the press as it fires, and claims nothing for a press it drops', () => {+ const onClaim = vi.fn();+ const stopWatching = watchPressClaims(onClaim);+ const detector = createLongPressDetector({onLongPress: () => {}});+ detector.start({x: 0, y: 0});+ detector.cancel();+ vi.advanceTimersByTime(1000);+ expect(onClaim).not.toHaveBeenCalled();+ detector.start({x: 0, y: 0});+ vi.advanceTimersByTime(500);+ expect(onClaim).toHaveBeenCalledTimes(1);+ stopWatching();+ });+it('reports a touch press first when its lift is stamped past the deadline, with no timer run', () => {const page = windowAt(1000);const onLongPress = vi.fn();diff --git a/packages/core/src/hooks/longPressDetector.ts b/packages/core/src/hooks/longPressDetector.tsindex 5e9eb04c42..868baf2530 100644--- a/packages/core/src/hooks/longPressDetector.ts+++ b/packages/core/src/hooks/longPressDetector.ts@@ -4,7 +4,8 @@* @file longPressDetector.ts* @input The long-press numbers (motion/uikit/longPress.ts) and touch events* @output createLongPressDetector(): one long press at a time, timed on the- * touch events' clock, with no React+ * touch events' clock, with no React. A press that fires claims the press+ * that is down (utils/pressClaim.ts).* @position Internal; the core of useLongPress and useLongPressDetector* (useLongPress.ts). Not in the hooks entry.*@@ -15,6 +16,7 @@ import {LONG_PRESS_ALLOWABLE_MOVEMENT_PX,LONG_PRESS_DURATION_MS,} from '../motion/uikit/longPress';+import {claimPress} from '../utils/pressClaim';// The hold is a deadline on the touch events' timestamps, on the clock of the// touch's own window. A busy main thread can delay the timer past the@@ -151,6 +153,9 @@ export function createLongPressDetector(return;}cancel();+ // The press acted, so its lift is not a tap: a box under the finger adds+ // no click of its own.+ claimPress();options.onLongPress({x: at.x, y: at.y});};diff --git a/packages/core/src/privateAttributes/pressBox.stylex.ts b/packages/core/src/privateAttributes/pressBox.stylex.tsnew file mode 100644index 0000000000..aac87de9cf--- /dev/null+++ b/packages/core/src/privateAttributes/pressBox.stylex.ts@@ -0,0 +1,29 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file privateAttributes/pressBox.stylex.ts+ * @input A control's box: the non-text part around its input and indicator+ * @output pressBoxProps, which marks the box, and pressBoxAt, which finds the+ * marked box that a press starts in+ * @position Owner module of the private press-box attribute: the only file+ * that writes its name. CheckboxInput and RadioListItem mark their boxes,+ * and utils/boxHold.ts reads the mark. No package entry exports it.+ */++const PRESS_BOX = 'data-astryx-press-box';++/** Spread on the box around a control's input and indicator. */+export const pressBoxProps: Readonly<Record<string, string>> = {+ [PRESS_BOX]: '',+};++/** The marked box that `target` is in, if `surface` contains it. */+export function pressBoxAt(+ target: EventTarget | null,+ surface: Element,+): HTMLElement | null {+ if (!(target instanceof Element)) {+ return null;+ }+ const box = target.closest(`[${PRESS_BOX}]`);+ return box instanceof HTMLElement && surface.contains(box) ? box : null;+}diff --git a/packages/core/src/utils/boxHold.test.ts b/packages/core/src/utils/boxHold.test.tsnew file mode 100644index 0000000000..9fad10e02c--- /dev/null+++ b/packages/core/src/utils/boxHold.test.ts@@ -0,0 +1,513 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file boxHold.test.ts+ * @input The box hold that registerBoxHold installs, and lockPressedRow, in+ * jsdom with hand-built pointer and touch events and fake timers+ * @output Checks that a held box locks its row's selection until the lift. A+ * still lift with no browser click clicks the input once, after the wait,+ * and each box keeps its own wait. A tap, travel, a cancel, a second finger+ * or a cancelled touchend clicks nothing. A claimed hold's touchend is+ * cancelled. A cancelled contextmenu stops the stand-in, and an unhandled+ * one doesn't. A scroll or a brake keeps the lock. A label or mouse press+ * takes no lock, and the last unmount ends a wait.+ * @position Unit layer of utils/boxHold.ts; the component layer is+ * Indicator/boxHold.test.tsx+ */++import {act, render, screen} from '@testing-library/react';+import {createElement} from 'react';+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ onTestFinished,+ vi,+} from 'vitest';+import {usePressFeedback} from '../hooks/usePressFeedback';+import {pressBoxProps} from '../privateAttributes/pressBox.stylex';+import {lockPressedRow, registerBoxHold} from './boxHold';+import {BROWSER_CLICK_WAIT_MS} from './browserClickWait';+import {claimPress} from './pressClaim';+import {PRESS_SLOP_PX} from './pressGesture';++/** Dispatches a pointer event as a finger, a pen or a mouse sends it. */+function press(+ target: Element,+ type: 'pointerdown' | 'pointermove' | 'pointerup' | 'pointercancel',+ at = {x: 1, y: 1},+ pointerType = 'touch',+ pointerId = 1,+): void {+ const event = new Event(type, {bubbles: true, cancelable: true});+ Object.assign(event, {+ button: 0,+ clientX: at.x,+ clientY: at.y,+ pointerId,+ pointerType,+ });+ target.dispatchEvent(event);+}++/** A finger held for longer than a long press on `target`, then lifted. */+/** Runs the fake clock `ms` forward. */+function advance(ms: number): void {+ act(() => {+ vi.advanceTimersByTime(ms);+ });+}++function hold(target: Element): void {+ press(target, 'pointerdown');+ advance(900);+ press(target, 'pointerup');+}++/** Dispatches the touchend that follows a finger's pointerup; returns it. */+function touchEnd(target: Element): Event {+ const event = new Event('touchend', {bubbles: true, cancelable: true});+ Object.defineProperty(event, 'changedTouches', {value: []});+ Object.defineProperty(event, 'touches', {value: []});+ target.dispatchEvent(event);+ return event;+}++/** Whether a selection that starts on `target` is refused. */+function refuses(target: Element): boolean {+ const event = new Event('selectstart', {bubbles: true, cancelable: true});+ target.dispatchEvent(event);+ return event.defaultPrevented;+}++/** Runs out the lift's wait for the browser's click. */+function waitForNoClick() {+ advance(BROWSER_CLICK_WAIT_MS);+}++/** Makes `CSS.supports` answer as iOS WebKit does for its touch callout. */+function asIosWebKit(): () => void {+ const original = globalThis.CSS;+ Object.defineProperty(globalThis, 'CSS', {+ configurable: true,+ value: {+ ...original,+ supports: (query: string) => query === '(-webkit-touch-callout: none)',+ },+ });+ return () => {+ Object.defineProperty(globalThis, 'CSS', {+ configurable: true,+ value: original,+ });+ };+}++// As a box component does when its module loads.+registerBoxHold();++function Row({onClick, name = ''}: {onClick: () => void; name?: string}) {+ const pressable = usePressFeedback();+ return createElement(+ 'div',+ {...pressable, 'data-testid': `row${name}`},+ createElement(+ 'div',+ {...pressBoxProps, 'data-testid': `box${name}`},+ createElement('input', {+ type: 'checkbox',+ 'data-testid': `input${name}`,+ onClick,+ }),+ ),+ createElement('span', {'data-testid': `label${name}`}, 'Accept terms'),+ );+}++beforeEach(() => {+ vi.useFakeTimers();+});+afterEach(() => {+ vi.useRealTimers();+});++describe('the box hold', () => {+ it('refuses a selection of the row a finger holds on the box, until the lift', () => {+ render(createElement(Row, {onClick: () => {}}));+ const input = screen.getByTestId('input');+ const label = screen.getByTestId('label');+ expect(refuses(label)).toBe(false);+ press(input, 'pointerdown');+ expect(refuses(label)).toBe(true);+ press(input, 'pointerup');+ expect(refuses(label)).toBe(false);+ });++ it('clicks the input once when a still lift gets no browser click, after the wait', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId<HTMLInputElement>('input');+ press(input, 'pointerdown');+ advance(900);+ press(input, 'pointerup');+ advance(BROWSER_CLICK_WAIT_MS - 1);+ expect(onClick).not.toHaveBeenCalled();+ advance(1);+ expect(onClick).toHaveBeenCalledTimes(1);+ expect(input.checked).toBe(true);+ waitForNoClick();+ expect(onClick).toHaveBeenCalledTimes(1);+ });++ it('swallows a browser click that comes after its own click: the lift activates once', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId<HTMLInputElement>('input');+ hold(input);+ advance(BROWSER_CLICK_WAIT_MS + 50);+ expect(onClick).toHaveBeenCalledTimes(1);+ // A busy main thread can hold the browser's own click past the wait.+ act(() => {+ input.dispatchEvent(+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 1}),+ );+ });+ expect(onClick).toHaveBeenCalledTimes(1);+ expect(input.checked).toBe(true);+ });++ it('keeps one wait per box: a tap on another box inside the wait leaves the held box’s activation in place', () => {+ const onA = vi.fn();+ const onB = vi.fn();+ render(+ createElement(+ 'div',+ null,+ createElement(Row, {onClick: onA, name: 'A'}),+ createElement(Row, {onClick: onB, name: 'B'}),+ ),+ );+ const inputA = screen.getByTestId('inputA');+ const inputB = screen.getByTestId('inputB');+ press(inputA, 'pointerdown');+ advance(900);+ press(inputA, 'pointerup');+ touchEnd(inputA);+ advance(100);+ // A tap's activation is the browser's click, which jsdom does not make.+ press(inputB, 'pointerdown', undefined, 'touch', 2);+ press(inputB, 'pointerup', undefined, 'touch', 2);+ touchEnd(inputB);+ advance(BROWSER_CLICK_WAIT_MS);+ expect(onA).toHaveBeenCalledTimes(1);+ expect(onB).not.toHaveBeenCalled();+ });++ it('clicks nothing for a lift whose touchend a handler cancelled: the handler took it', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ const takeLift = (event: Event) => event.preventDefault();+ input.addEventListener('touchend', takeLift);+ press(input, 'pointerdown');+ advance(900);+ press(input, 'pointerup');+ expect(touchEnd(input).defaultPrevented).toBe(true);+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ input.removeEventListener('touchend', takeLift);+ });++ it('gives a tap no stand-in click: its activation stays the browser’s own', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ press(input, 'pointerdown');+ advance(300);+ press(input, 'pointerup');+ touchEnd(input);+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ });++ it('takes the lift of a hold whose long press acted, such as a row’s own: its touchend is cancelled and nothing clicks', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ press(input, 'pointerdown');+ advance(500);+ claimPress();+ advance(400);+ press(input, 'pointerup');+ expect(touchEnd(input).defaultPrevented).toBe(true);+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ });++ it('gives a pen hold whose long press acted no stand-in click: a pen sends no touchend to take', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ press(input, 'pointerdown', undefined, 'pen');+ advance(600);+ claimPress();+ advance(300);+ press(input, 'pointerup', undefined, 'pen');+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ });++ it('clicks nothing when a handler cancelled the hold’s contextmenu: the hold opened a menu', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ const openMenu = (event: Event) => event.preventDefault();+ input.addEventListener('contextmenu', openMenu);+ press(input, 'pointerdown');+ advance(600);+ input.dispatchEvent(+ new Event('contextmenu', {bubbles: true, cancelable: true}),+ );+ advance(300);+ press(input, 'pointerup');+ touchEnd(input);+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ input.removeEventListener('contextmenu', openMenu);+ });++ it('clicks nothing when a handler cancels a contextmenu that comes during the wait', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ const openMenu = (event: Event) => event.preventDefault();+ input.addEventListener('contextmenu', openMenu);+ hold(input);+ touchEnd(input);+ input.dispatchEvent(+ new Event('contextmenu', {bubbles: true, cancelable: true}),+ );+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ input.removeEventListener('contextmenu', openMenu);+ });++ it('still clicks when a handler cancels a contextmenu that follows a new press', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ const openMenu = (event: Event) => event.preventDefault();+ document.body.addEventListener('contextmenu', openMenu);+ onTestFinished(() => {+ document.body.removeEventListener('contextmenu', openMenu);+ });+ hold(input);+ touchEnd(input);+ // A right-click elsewhere, inside the wait.+ press(document.body, 'pointerdown', undefined, 'mouse', 2);+ document.body.dispatchEvent(+ new Event('contextmenu', {bubbles: true, cancelable: true}),+ );+ waitForNoClick();+ expect(onClick).toHaveBeenCalledTimes(1);+ });++ it('still clicks after a contextmenu that no handler cancelled', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ press(input, 'pointerdown');+ advance(600);+ input.dispatchEvent(+ new Event('contextmenu', {bubbles: true, cancelable: true}),+ );+ advance(300);+ press(input, 'pointerup');+ touchEnd(input);+ waitForNoClick();+ expect(onClick).toHaveBeenCalledTimes(1);+ });++ it('eats the click after a claimed hold whose touchend could not be cancelled', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ press(input, 'pointerdown');+ advance(600);+ claimPress();+ advance(300);+ press(input, 'pointerup');+ input.dispatchEvent(new Event('touchend', {bubbles: true}));+ // The browser's own click: a tap's click carries a detail of 1.+ input.dispatchEvent(+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 1}),+ );+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ });++ it('takes only the claimed hold’s lift: the next press’s touchend is not cancelled', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ press(input, 'pointerdown');+ advance(600);+ claimPress();+ // The touch is cancelled, so its lift never comes.+ press(input, 'pointercancel');+ const cancel = new Event('touchcancel', {bubbles: true});+ input.dispatchEvent(cancel);+ press(input, 'pointerdown');+ press(input, 'pointerup');+ expect(touchEnd(input).defaultPrevented).toBe(false);+ });++ it('still clicks after a claim that came before the hold', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ claimPress();+ hold(input);+ touchEnd(input);+ waitForNoClick();+ expect(onClick).toHaveBeenCalledTimes(1);+ });++ it('clicks nothing when a second finger lands during the press', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ press(input, 'pointerdown');+ press(input, 'pointerdown', {x: 40, y: 1}, 'touch', 2);+ press(input, 'pointerup');+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ });++ it('clicks nothing for a press that travels past the slop', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ press(input, 'pointerdown');+ press(input, 'pointermove', {x: 1, y: 2 + PRESS_SLOP_PX});+ press(input, 'pointerup', {x: 1, y: 2 + PRESS_SLOP_PX});+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ });++ it('clicks nothing for a cancelled press, and releases its lock', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ press(input, 'pointerdown');+ press(input, 'pointercancel');+ expect(refuses(screen.getByTestId('label'))).toBe(false);+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ });++ it('keeps the lock through a scroll until the lift, and clicks nothing', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ const label = screen.getByTestId('label');+ press(input, 'pointerdown');+ // iOS delivers the stopped scroll's last events after the finger lands.+ document.dispatchEvent(new Event('scroll'));+ expect(refuses(label)).toBe(true);+ press(input, 'pointerup');+ expect(refuses(label)).toBe(false);+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ });++ it('locks the row for a finger that brakes a scroll, and clicks nothing', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ const label = screen.getByTestId('label');+ press(input, 'pointerdown');+ press(input, 'pointerup');+ waitForNoClick();+ onClick.mockClear();+ // A scroll that finger drove: the next touch is a brake, not a press.+ document.dispatchEvent(new Event('scroll'));+ press(input, 'pointerdown');+ expect(refuses(label)).toBe(true);+ press(input, 'pointerup');+ expect(refuses(label)).toBe(false);+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ });++ it('takes no lock and clicks nothing for a press on the label or a mouse’s press', () => {+ const onClick = vi.fn();+ render(createElement(Row, {onClick}));+ const label = screen.getByTestId('label');+ const input = screen.getByTestId('input');+ press(label, 'pointerdown');+ expect(refuses(label)).toBe(false);+ press(label, 'pointerup');+ press(input, 'pointerdown', undefined, 'mouse');+ expect(refuses(label)).toBe(false);+ press(input, 'pointerup', undefined, 'mouse');+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ });++ it('ends the wait when the last pressable unmounts: no click comes later', () => {+ const onClick = vi.fn();+ const {unmount} = render(createElement(Row, {onClick}));+ const input = screen.getByTestId('input');+ hold(input);+ unmount();+ waitForNoClick();+ expect(onClick).not.toHaveBeenCalled();+ });+});++describe('lockPressedRow', () => {+ it('locks the pressed row around an element as well as the element', () => {+ document.body.innerHTML =+ '<div data-astryx-pressable><div id="box"><input id="input" type="checkbox"></div><span id="label">Accept</span></div>';+ const box = document.getElementById('box') as HTMLElement;+ const label = document.getElementById('label') as HTMLElement;+ const release = lockPressedRow([box], document.getElementById('input'));+ expect(refuses(label)).toBe(true);+ release();+ expect(refuses(label)).toBe(false);+ document.body.innerHTML = '';+ });++ it('on iOS, locks the row and the input with styles, and restores them', () => {+ const restore = asIosWebKit();+ try {+ document.body.innerHTML =+ '<div id="row" data-astryx-pressable><div id="box"><input id="input" type="checkbox"></div></div>';+ const row = document.getElementById('row') as HTMLElement;+ const input = document.getElementById('input') as HTMLElement;+ const set = vi.spyOn(row.style, 'setProperty');+ const inputSet = vi.spyOn(input.style, 'setProperty');+ const remove = vi.spyOn(row.style, 'removeProperty');+ const release = lockPressedRow(+ [document.getElementById('box') as HTMLElement],+ input,+ );+ for (const name of [+ '-webkit-touch-callout',+ '-webkit-user-select',+ 'user-select',+ ]) {+ expect(set).toHaveBeenCalledWith(name, 'none');+ expect(inputSet).toHaveBeenCalledWith(name, 'none');+ }+ release();+ expect(remove).toHaveBeenCalledWith('user-select');+ document.body.innerHTML = '';+ } finally {+ restore();+ vi.restoreAllMocks();+ }+ });+});diff --git a/packages/core/src/utils/boxHold.ts b/packages/core/src/utils/boxHold.tsnew file mode 100644index 0000000000..5574fdce2f--- /dev/null+++ b/packages/core/src/utils/boxHold.ts@@ -0,0 +1,180 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file boxHold.ts+ * @input A finger's or a pen's contact that the shared press controller+ * (utils/pressFeedback.ts) follows, and the marked box it starts on. A long+ * press that fires claims the contact (utils/pressClaim.ts). A contextmenu+ * that a handler cancels stops its stand-in click.+ * @output registerBoxHold, which installs the box hold into the controller,+ * and lockPressedRow+ * @position CheckboxInput and RadioListItem call registerBoxHold as they+ * load and mark their boxes with pressBoxProps; Switch's tracker takes+ * lockPressedRow. Builds on utils/selectionLock.ts,+ * utils/browserClickWait.ts and utils/clickGuard.ts.+ */++import {LONG_PRESS_DURATION_MS} from '../motion/uikit/longPress';+import {pressBoxAt} from '../privateAttributes/pressBox.stylex';+import {awaitBrowserClick, clickForLift} from './browserClickWait';+import {armClickGuard} from './clickGuard';+import {subscribeInput} from './inputStream';+import {watchPressClaims} from './pressClaim';+import {installBoxHold, PRESSABLE_ATTRIBUTE} from './pressFeedback';+import {lockSelection} from './selectionLock';++/** The wait for the browser's click after a box's still lift, per box. */+const waits = new Map<HTMLElement, () => void>();++/**+ * The selection lock for a finger or a pen on a control's box. A lock on the+ * box alone lets iOS select a word beside it, so the lock also covers the+ * pressable row around each element.+ */+export function lockPressedRow(+ elements: Iterable<Element>,+ target: EventTarget | null,+): () => void {+ const held = new Set<Element>();+ for (const element of elements) {+ held.add(element);+ held.add(element.closest(`[${PRESSABLE_ATTRIBUTE}]`) ?? element);+ }+ return lockSelection(held, target);+}++/**+ * Starts the hold of a contact on a marked box in `surface`. The box and the+ * surface refuse a selection until the contact ends. Returns the call for the+ * contact's end, or null when the contact is not on a box.+ */+function holdBox(+ surface: HTMLElement,+ target: EventTarget | null,+): ((isStillLift: boolean) => void) | null {+ const box = pressBoxAt(target, surface);+ if (box == null) {+ return null;+ }+ const release = lockSelection([surface, box], target);+ const startedAt = performance.now();+ const view = box.ownerDocument.defaultView;+ let isClaimed = false;+ const stopWatching = watchPressClaims(() => {+ isClaimed = true;+ });+ // Chromium sends a long press as a contextmenu, and no click follows. One+ // that a handler cancelled opened a menu, which is what the hold did.+ const menus: Event[] = [];+ const stopMenus =+ view == null+ ? () => {}+ : subscribeInput(view, 'contextmenu', event => {+ menus.push(event);+ });+ const openedMenu = () => menus.some(event => event.defaultPrevented);+ return isStillLift => {+ release();+ stopWatching();+ if (isClaimed) {+ // A long press that acted, such as a context menu's or a row's own, is+ // what the hold did. Since iOS clicks after a long hold that selects+ // nothing, the guard cancels the lift's touchend and eats any click.+ if (isStillLift) {+ armClickGuard(box.ownerDocument, {cancelsTouchEnd: true});+ }+ stopMenus();+ return;+ }+ // A tap's activation stays the browser's own: only a long press may need+ // a stand-in for the click.+ if (+ !isStillLift ||+ performance.now() - startedAt < LONG_PRESS_DURATION_MS ||+ openedMenu()+ ) {+ stopMenus();+ return;+ }+ waitForClick(box, openedMenu, stopMenus);+ };+}++/**+ * Some engines send no click after a long hold, such as Chromium's own long+ * press, as on Android. So a still lift waits for the browser's own click,+ * and the control clicks its input only if none comes. Nothing clicks for a+ * lift that another element took: its handler cancelled the touchend. Nor+ * does anything click once a handler cancels the hold's contextmenu.+ */+function waitForClick(+ box: HTMLElement,+ openedMenu: () => boolean,+ stopMenus: () => void,+): void {+ waits.get(box)?.();+ const view = box.ownerDocument.defaultView;+ if (view == null) {+ stopMenus();+ return;+ }+ // The lift's own touchend. A new press's touchend and contextmenu are not+ // this hold's.+ let lift: Event | null = null;+ const stopLift = subscribeInput(view, 'touchend', event => {+ lift ??= event;+ });+ const stopListening = [+ stopLift,+ subscribeInput(view, 'pointerdown', () => {+ stopLift();+ stopMenus();+ }),+ stopMenus,+ ];+ let stopWaiting: (() => void) | null = null;+ const end = () => {+ for (const stop of stopListening) {+ stop();+ }+ stopWaiting?.();+ stopWaiting = null;+ if (waits.get(box) === end) {+ waits.delete(box);+ }+ };+ waits.set(box, end);+ stopWaiting = awaitBrowserClick(box, {+ onClicked: () => {+ stopWaiting = null;+ end();+ },+ onNoClick: () => {+ stopWaiting = null;+ end();+ // Read once every handler has run.+ if (lift?.defaultPrevented === true || openedMenu()) {+ return;+ }+ const input = box.querySelector('input');+ if (input != null && input.isConnected) {+ clickForLift(input);+ }+ },+ });+}++/** Ends every wait still running: the controller is going away. */+function endBoxWaits(): void {+ for (const end of [...waits.values()]) {+ end();+ }+}++/**+ * Installs the box hold into the shared press controller. A box component+ * calls it as its module loads, so a page with no box carries none of it.+ */+export function registerBoxHold(): void {+ installBoxHold({start: holdBox, endWaits: endBoxWaits});+}diff --git a/packages/core/src/utils/clickGuard.ts b/packages/core/src/utils/clickGuard.tsindex ec540af1ec..8bd9f8aa70 100644--- a/packages/core/src/utils/clickGuard.ts+++ b/packages/core/src/utils/clickGuard.ts@@ -7,10 +7,11 @@* @output armClickGuard (and its ClickGuardOptions), disarmClickGuard,* isClickGuardArmed, withoutClickGuard and CLICK_GUARD_WINDOW_MS* @position The one guard for the browser's click after a gesture that- * already acted, shared by hooks/useMenuPress.ts and gestures/GestureHost.ts+ * already acted, shared by hooks/useMenuPress.ts, gestures/GestureHost.ts+ * and utils/boxHold.ts*- * SYNC: When modified, update clickGuard.test.ts, hooks/useMenuPress.ts and- * gestures/GestureHost.ts.+ * SYNC: When modified, update clickGuard.test.ts, hooks/useMenuPress.ts,+ * gestures/GestureHost.ts and utils/boxHold.ts.*/// Armed at a tracked release, the guard swallows the next click on thediff --git a/packages/core/src/utils/pressClaim.ts b/packages/core/src/utils/pressClaim.tsnew file mode 100644index 0000000000..c93ade40ee--- /dev/null+++ b/packages/core/src/utils/pressClaim.ts@@ -0,0 +1,28 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file pressClaim.ts+ * @input A long press that fires while its finger is still down+ * @output claimPress, which the long-press detector calls as a press fires,+ * and watchPressClaims, which hears it+ * @position Internal. The long-press detector (hooks/longPressDetector.ts)+ * tells the box hold (utils/boxHold.ts) here that the press acted. It adds+ * no listener to the page.+ */++const watchers = new Set<() => void>();++/** Tells each watcher that a long press acted on the press that is down. */+export function claimPress(): void {+ for (const watcher of [...watchers]) {+ watcher();+ }+}++/** Calls `watcher` at each claim until the returned function runs. */+export function watchPressClaims(watcher: () => void): () => void {+ watchers.add(watcher);+ return () => {+ watchers.delete(watcher);+ };+}diff --git a/packages/core/src/utils/pressFeedback.ts b/packages/core/src/utils/pressFeedback.tsindex 44323dd728..8a1459061b 100644--- a/packages/core/src/utils/pressFeedback.ts+++ b/packages/core/src/utils/pressFeedback.ts@@ -6,7 +6,7 @@* press-group markers, the scroll-view test (scrollView.ts) and the document's pointer, keyboard, scroll and* visibility events* @output PRESSABLE_ATTRIBUTE, PRESSED_ATTRIBUTE, pressableProps,- * pressFadeMs, installPressFeedback and cancelPress+ * pressFadeMs, installPressFeedback, cancelPress and installBoxHold* @position The DOM half of the touch press model. usePressFeedback installs* it, and the CSS arms live in interactionOverlay.stylex.ts.*@@ -132,6 +132,48 @@ interface Slot {}const finger: Slot = {live: null};++/**+ * A finger's or a pen's contact on a control's box (utils/boxHold.ts). It+ * keeps its pointer, the press it started (none for a brake) and the box+ * hold's end.+ * A braking contact counts, and so does one that a scroll cancels. Each ends+ * at its own lift or cancel. Only a press that is still live at the lift is a+ * still lift.+ */+let contact: {+ pointerId: number;+ live: LiveGesture | null;+ end: (isStillLift: boolean) => void;+} | null = null;++/** Ends the box contact and tells its box hold, once. */+function endContact(isStillLift: boolean): void {+ const ended = contact;+ contact = null;+ ended?.end(isStillLift);+}++/** The box hold that a box component installs (utils/boxHold.ts). */+export interface BoxHold {+ /** Starts the hold of a contact. Returns its end, or null off a box. */+ readonly start: (+ surface: HTMLElement,+ target: EventTarget | null,+ ) => ((isStillLift: boolean) => void) | null;+ /** Ends every wait still running, as the controller goes away. */+ readonly endWaits: () => void;+}++let boxHold: BoxHold | null = null;++/**+ * @internal Installs the box hold. Only a page with a box component loads+ * it, so a page of buttons and links carries none of its code.+ */+export function installBoxHold(hold: BoxHold): void {+ boxHold = hold;+}const button: Slot = {live: null};/** How many callers hold the controller installed; listeners exist while > 0. */let holders = 0;@@ -505,6 +547,9 @@ function onPointerDown(event: PointerEvent): void {return;}armTouchCancel();+ // A second finger or a new press ends the last box contact; its lift is not+ // a still lift.+ endContact(false);if (finger.live != null) {const fingerIsUp =finger.live.gesture.phase === 'fading' ||@@ -532,23 +577,30 @@ function onPointerDown(event: PointerEvent): void {// A group's tracker that follows this pointer paints its action, so two// writers would erase each other's paint. The touch still counts for the// brake above.- if (- element == null ||- braking ||- isTrackedByGroup(element, event.pointerType)- ) {+ if (element == null || isTrackedByGroup(element, event.pointerType)) {+ return;+ }+ // A braking finger presses nothing, but a box hold still follows it.+ const end = boxHold?.start(element, event.target) ?? null;+ const live: LiveGesture | null = braking+ ? null+ : {+ element,+ gesture: idlePressGesture(),+ pointerId: event.pointerId,+ timer: null,+ };+ if (end != null) {+ contact = {pointerId: event.pointerId, live, end};+ }+ if (live == null) {return;}takeOver(button, element);- finger.live = {- element,- gesture: idlePressGesture(),- pointerId: event.pointerId,- timer: null,- };+ finger.live = live;apply(finger,- pressGestureStep(finger.live.gesture, {+ pressGestureStep(live.gesture, {kind: 'down',x: event.clientX,y: event.clientY,@@ -596,6 +648,16 @@ function onPointerUp(event: PointerEvent): void {if (event.target instanceof Node) {lastTouchTarget = event.target;}+ if (contact?.pointerId === event.pointerId) {+ // Read before the release step: a press that travelled or that a scroll+ // took is dead or gone by now.+ const pressed = contact.live;+ endContact(+ pressed != null &&+ finger.live === pressed &&+ pressed.gesture.phase !== 'dead',+ );+ }const live = finger.live;if (live == null ||@@ -623,6 +685,11 @@ function onCancel(event?: Event): void {}return;}+ // Only the pointer's own cancel ends its contact. A scroll's cancel keeps it:+ // the finger is still down.+ if (pointer?.pointerId != null && contact?.pointerId === pointer.pointerId) {+ endContact(false);+ }const live = finger.live;if (live == null) {return;@@ -737,6 +804,7 @@ function onBlur(): void {*/function onVisibilityChange(): void {if (document.visibilityState === 'hidden') {+ endContact(false);finish(finger);finish(button);}@@ -801,6 +869,8 @@ function addListeners(): void {}function removeListeners(): void {+ endContact(false);+ boxHold?.endWaits();for (const unsubscribe of unsubscribers.splice(0)) {unsubscribe();}diff --git a/packages/core/src/utils/pressFeedbackImports.test.ts b/packages/core/src/utils/pressFeedbackImports.test.tsindex 2a4348cd57..e748fc4d24 100644--- a/packages/core/src/utils/pressFeedbackImports.test.ts+++ b/packages/core/src/utils/pressFeedbackImports.test.ts@@ -7,6 +7,8 @@* under gestures/: a page whose only touch work is press feedback carries* none of the gesture system (`spec:AST-094` FR24, FR43: pointer queries* live with the environment queries)+ * @output The graph reaches none of the box hold either: only a box component+ * loads it.* @position Source boundary test of packages/core/src/utils/pressFeedback.ts*/@@ -14,42 +16,57 @@ import fs from 'node:fs';import path from 'node:path';import {describe, expect, it} from 'vitest';-describe('the press feedback controller', () => {- it('imports nothing from the gesture system', () => {- const utils = path.resolve(__dirname);- const seen = new Set<string>();- const queue = [path.join(utils, 'pressFeedback.ts')];- const statement =- /^\s*(import|export)\s+(type\s+)?([^'";]*?\s+from\s+)?'([^']+)';/gms;- while (queue.length > 0) {- const file = queue.pop() as string;- if (seen.has(file)) {+/** Every module the controller's own imports reach, relative to src/. */+function controllerModules(): string[] {+ const utils = path.resolve(__dirname);+ const seen = new Set<string>();+ const queue = [path.join(utils, 'pressFeedback.ts')];+ const statement =+ /^\s*(import|export)\s+(type\s+)?([^'";]*?\s+from\s+)?'([^']+)';/gms;+ while (queue.length > 0) {+ const file = queue.pop() as string;+ if (seen.has(file)) {+ continue;+ }+ seen.add(file);+ for (const match of fs.readFileSync(file, 'utf8').matchAll(statement)) {+ const [, , isTypeOnly, , specifier] = match;+ if (isTypeOnly != null || !specifier.startsWith('.')) {continue;}- seen.add(file);- for (const match of fs.readFileSync(file, 'utf8').matchAll(statement)) {- const [, , isTypeOnly, , specifier] = match;- if (isTypeOnly != null || !specifier.startsWith('.')) {- continue;- }- const base = path.resolve(path.dirname(file), specifier);- const resolved = [- `${base}.ts`,- `${base}.tsx`,- path.join(base, 'index.ts'),- ].find(candidate => fs.existsSync(candidate));- if (resolved == null) {- throw new Error(`cannot resolve ${specifier} from ${file}`);- }- queue.push(resolved);+ const base = path.resolve(path.dirname(file), specifier);+ const resolved = [+ `${base}.ts`,+ `${base}.tsx`,+ path.join(base, 'index.ts'),+ ].find(candidate => fs.existsSync(candidate));+ if (resolved == null) {+ throw new Error(`cannot resolve ${specifier} from ${file}`);}+ queue.push(resolved);}- const modules = [...seen].map(file =>- path.relative(path.resolve(utils, '..'), file),- );+ }+ return [...seen].map(file => path.relative(path.resolve(utils, '..'), file));+}++describe('the press feedback controller', () => {+ it('imports nothing from the gesture system', () => {+ const modules = controllerModules();expect(modules).toContain(path.join('utils', 'pressFeedback.ts'));expect(modules.filter(module => module.startsWith(`gestures${path.sep}`)),).toEqual([]);});++ it('imports none of the box hold, so a page of buttons and links carries none of it', () => {+ const modules = controllerModules();+ for (const module of [+ 'boxHold.ts',+ 'browserClickWait.ts',+ 'clickGuard.ts',+ 'selectionLock.ts',+ ]) {+ expect(modules).not.toContain(path.join('utils', module));+ }+ });});