Skip to content

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

TypeScript

feat(core): under a finger a pressable highlights at touch-down outside scroll views (#9765)

Cindy Zhang3d225c35b904
diff --git a/.changeset/press-touch-down-highlight.md b/.changeset/press-touch-down-highlight.md
new file mode 100644
index 0000000000..d0d42c6c9b
--- /dev/null
+++ b/.changeset/press-touch-down-highlight.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Under a finger, a pressable (a button, card, link, list row or any other surface) outside a scroll view now highlights in the frame the finger lands, as UIKit's controls do, instead of after a 150 ms delay. Inside a scroll view it still waits that delay, so a flick paints nothing, and a scroll that takes a held press cancels it with no fade. A page that scrolls counts as a scroll view, so on a page taller than the screen a press still waits; a control in a fixed bar, or on a page that fits, highlights at once. A mouse on a desktop keeps `:active`.
+
+@vjeux
diff --git a/.github/scripts/ci-interaction-webkit.test.mjs b/.github/scripts/ci-interaction-webkit.test.mjs
index 3511110846..c3abb33b42 100644
--- a/.github/scripts/ci-interaction-webkit.test.mjs
+++ b/.github/scripts/ci-interaction-webkit.test.mjs
@@ -255,6 +255,7 @@ describe('WebKit interaction proof routing', () => {
'packages/core/src/hooks/useIsomorphicLayoutEffect.ts',
'packages/core/src/hooks/useAttachment.ts',
'packages/core/src/utils/sharedResizeObserver.ts',
+ 'packages/core/src/utils/scrollView.ts',
'packages/core/src/hooks/__tests__/usePager.interaction.browser.spec.ts',
'packages/core/src/hooks/__tests__/pagerBundle.ts',
'internal/interaction-harness/src/webInput.ts',
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 79396151c2..e3764eafa8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2526,7 +2526,7 @@ jobs:
id: scope
uses: ./.test-scope/.github/actions/test-scope
with:
- paths: '^(packages/core/src/gestures/|packages/core/src/motion/|packages/core/src/internal/touch|packages/core/src/utils/(press|touch|primaryClick|isApplePlatform|flatTree|inputStream|clickGuard|selectionLock|coarsePointer|sharedResizeObserver)|packages/core/src/privateAttributes/(hapticSwitch|reducedMotion)\.stylex\.ts$|packages/core/src/Layer/inputHold\.ts$|packages/core/src/hooks/(useMenuPress|menuPress|useLongPress|usePressFeedback|isRtlElement|useIsomorphicLayoutEffect|useAttachment|usePager|__tests__/(usePager|pagerBundle))|internal/interaction-harness/|internal/a11y-spec/|playwright\.interaction\.config\.ts$|packages/themes/[^/]+/src/|apps/storybook/|\.github/workflows/ci\.yml$|package\.json$|pnpm-lock\.yaml$|\.github/scripts/(interaction-legs|a11y-pr-contracts)\.mjs$|scripts/lib/duration-split\.mjs$|\.github/interaction-durations\.json$|\.github/actions/test-scope/)'
+ paths: '^(packages/core/src/gestures/|packages/core/src/motion/|packages/core/src/internal/touch|packages/core/src/utils/(press|touch|primaryClick|isApplePlatform|flatTree|inputStream|clickGuard|selectionLock|coarsePointer|sharedResizeObserver|scrollView)|packages/core/src/privateAttributes/(hapticSwitch|reducedMotion)\.stylex\.ts$|packages/core/src/Layer/inputHold\.ts$|packages/core/src/hooks/(useMenuPress|menuPress|useLongPress|usePressFeedback|isRtlElement|useIsomorphicLayoutEffect|useAttachment|usePager|__tests__/(usePager|pagerBundle))|internal/interaction-harness/|internal/a11y-spec/|playwright\.interaction\.config\.ts$|packages/themes/[^/]+/src/|apps/storybook/|\.github/workflows/ci\.yml$|package\.json$|pnpm-lock\.yaml$|\.github/scripts/(interaction-legs|a11y-pr-contracts)\.mjs$|scripts/lib/duration-split\.mjs$|\.github/interaction-durations\.json$|\.github/actions/test-scope/)'
outside-pull-request: skip
requires-head-file: playwright.interaction.config.ts
diff --git a/apps/storybook/stories/PressFeedback.stories.tsx b/apps/storybook/stories/PressFeedback.stories.tsx
index f788d42bd5..7f765a2725 100644
--- a/apps/storybook/stories/PressFeedback.stories.tsx
+++ b/apps/storybook/stories/PressFeedback.stories.tsx
@@ -26,11 +26,11 @@ import {VStack} from '@astryxdesign/core/Layout';
* View these with a coarse pointer: in Chromium, open DevTools, toggle the
* device toolbar (a phone preset), and use the touch cursor; or open Storybook
* on a phone. Under a finger the bare `:active` arm is dropped and the press
- * follows the clocks a native list uses: nothing paints for 150 ms; a held
- * press then paints the full pressed overlay on the next frame; travelling
- * 10 px, or a scroll claiming the gesture, cancels it with no fade and nothing
- * repaints until a new touch; a tap shorter than the delay paints at the lift;
- * the release fades over 200 ms. A mouse keeps `:active`.
+ * follows UIKit. A surface highlights in the frame the finger lands, or
+ * 150 ms later inside a scroller, where a flick paints nothing; travelling
+ * 10 px, or the browser taking the touch to scroll, cancels it with no fade;
+ * a tap shorter than the delay paints at the lift; the lift fades it out. A
+ * mouse keeps `:active` on a desktop.
*/
const meta: Meta = {
title: 'Core/Press feedback (touch)',
@@ -39,7 +39,7 @@ const meta: Meta = {
docs: {
description: {
component:
- 'The touch press model on every pressable surface. View with a coarse pointer (DevTools device toolbar, or a phone). Under a finger the bare `:active` arm is dropped and one document-level controller writes `data-astryx-press="on"` once a press is believed (150 ms, no travel, no scroll) and `data-astryx-press="fading"` for the 200 ms release; a scroll or 10 px of travel cancels with no fade, and nothing repaints until a new touch. A mouse keeps `:active`. Scroll the list stories with a finger: no row paints while the list moves.',
+ 'The touch press model on every pressable surface. View with a coarse pointer (DevTools device toolbar, or a phone). Under a finger the bare `:active` arm is dropped and one document-level controller writes `data-astryx-press="on"` while a press is held and `data-astryx-press="fading"` for the release. A surface highlights in the frame the finger lands (150 ms later inside a scroller) and fades at the lift; 10 px of travel or a scroll claiming the touch cancels it with no fade. A mouse keeps `:active` on a desktop. Scroll the list stories with a finger: nothing paints while the list moves.',
},
},
},
@@ -48,12 +48,12 @@ const meta: Meta = {
export default meta;
type Story = StoryObj;
-const touchNote = (what: string) =>
- `${what} Hold: paints after 150 ms. Tap: paints at the lift. Drag or scroll: never paints, and stays dark until the finger lifts and lands again.`;
+const controlNote = (what: string) =>
+ `${what} Touch: paints in the frame the finger lands. Lift: fades out. A scroll that takes the touch: the paint goes at once, with no fade and no click.`;
export const Buttons: Story = {
parameters: {
- docs: {description: {story: touchNote('Buttons under a finger.')}},
+ docs: {description: {story: controlNote('Buttons under a finger.')}},
},
render: () => (
<VStack gap={3}>
@@ -70,9 +70,8 @@ export const Rows: Story = {
parameters: {
docs: {
description: {
- story: touchNote(
- 'Item rows, a menu, and a clickable card. The list scrolls: flick it and no row paints; stop it with a finger and that touch is a brake, not a press.',
- ),
+ story:
+ 'Item rows, a menu, and a clickable card. The rows sit in a scroller, so a held row paints after 150 ms, a tap paints at the lift, and a drag or scroll never paints; the card, outside it, paints in the frame the finger lands. Flick the list and no row paints.',
},
},
},
@@ -113,7 +112,7 @@ export const Controls: Story = {
parameters: {
docs: {
description: {
- story: touchNote(
+ story: controlNote(
'The eight components that gained a pressed state, under a finger.',
),
},
@@ -159,3 +158,30 @@ export const Controls: Story = {
);
},
};
+
+export const ButtonsInScroller: Story = {
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Buttons in a scrolling list, under a finger: a held button paints 150 ms after the finger lands (UIScrollView.delaysContentTouches); a flick scrolls the list and paints nothing; a scroll that starts after the button painted takes the touch, and the paint goes at once with no fade and no click.',
+ },
+ },
+ },
+ render: () => (
+ <div
+ data-testid="button-scroller"
+ style={{height: 240, overflowY: 'auto', border: '1px solid transparent'}}>
+ <VStack gap={3}>
+ {Array.from({length: 16}, (_, index) => (
+ <Button
+ key={index}
+ label={`Action ${index + 1}`}
+ variant="secondary"
+ onClick={() => {}}
+ />
+ ))}
+ </VStack>
+ </div>
+ ),
+};
diff --git a/packages/core/src/Button/__tests__/ButtonPress.interaction.browser.spec.ts b/packages/core/src/Button/__tests__/ButtonPress.interaction.browser.spec.ts
new file mode 100644
index 0000000000..3386f5f53e
--- /dev/null
+++ b/packages/core/src/Button/__tests__/ButtonPress.interaction.browser.spec.ts
@@ -0,0 +1,305 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ButtonPress.interaction.browser.spec.ts
+ * @input The built press feedback stories (Buttons, Buttons in a scroller),
+ * real touch input (Chromium CDP / WebKit's input command), the
+ * interaction harness, and the touch press model's clocks
+ * (utils/pressGesture.ts)
+ * @output Interaction proofs for a finger's press on a button
+ * (`spec:AST-094` FR11): outside a scroller it highlights in the frame it
+ * lands and releases on the shared release clock; inside one it waits
+ * UIScrollView's content-touch delay, a flick paints nothing, and a scroll
+ * that takes a held press cancels it with no fade and no click; a quick
+ * tap highlights at the lift; the engine's own tap paints and activates
+ * once; a storyboard of a press, its trace asserted
+ * @position Interaction evidence for the touch press model
+ * (utils/pressFeedback.ts, as installed by hooks/usePressFeedback.ts)
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ flick,
+ freezeTimers,
+ holdThenDrag,
+ installTimerGate,
+ openStory,
+ tap,
+ thawTimers,
+ touchDriver,
+ touchStoryboard,
+ withStorybook,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+import {scroll} from '../../motion/uikit/scroll';
+
+const storybook = withStorybook(test);
+
+/**
+ * The release clock: `PRESS_FADE_MS` in utils/pressGesture.ts, which this
+ * runner cannot import (it compiles StyleX). pressFeedback.test.ts holds the
+ * two equal.
+ */
+const RELEASE_MS = 200;
+const CONTENT_TOUCH_DELAY_MS = scroll.delaysContentTouchesMs;
+/** Long enough that a press in a scroller is believed. */
+const HOLD_MS = 400;
+/** Two frames at 60 Hz: "in the frame the finger lands", with dispatch slack. */
+const SAME_FRAME_MS = 34;
+
+const BUTTONS = 'core-press-feedback-touch--buttons';
+const SCROLLER = 'core-press-feedback-touch--buttons-in-scroller';
+
+interface Opened {
+ driver: TouchDriver;
+ surface: Locator;
+ center: {x: number; y: number};
+ /** What the page saw, on its own clock (performance.now()). */
+ log: () => Promise<LogEntry[]>;
+}
+
+type LogEntry = [kind: string, t: number, value: string | null];
+
+async function openSurface(
+ page: Page,
+ story: string,
+ surface: (page: Page) => Locator,
+): Promise<Opened> {
+ await openStory(page, storybook(), story);
+ const driver = await touchDriver(page);
+ const element = surface(page);
+ await expect(element).toBeVisible();
+ const box = await element.boundingBox();
+ if (box == null) {
+ throw new Error(`${story}: the surface has no box`);
+ }
+ await element.evaluate(el => {
+ const entries: LogEntry[] = [];
+ (window as unknown as {__press: LogEntry[]}).__press = entries;
+ for (const type of ['pointerdown', 'pointerup', 'pointercancel', 'click']) {
+ document.addEventListener(
+ type,
+ () => entries.push([type, performance.now(), null]),
+ true,
+ );
+ }
+ new MutationObserver(records => {
+ for (const record of records) {
+ entries.push([
+ 'press',
+ performance.now(),
+ (record.target as Element).getAttribute('data-astryx-press'),
+ ]);
+ }
+ }).observe(el, {attributes: true, attributeFilter: ['data-astryx-press']});
+ });
+ return {
+ driver,
+ surface: element,
+ center: {x: box.x + box.width / 2, y: box.y + box.height / 2},
+ log: async () =>
+ page.evaluate(() => (window as unknown as {__press: LogEntry[]}).__press),
+ };
+}
+
+const secondaryButton = (page: Page) =>
+ page.getByRole('button', {name: 'Secondary', exact: true});
+const scrollerButton = (page: Page) =>
+ page.getByRole('button', {name: 'Action 2', exact: true});
+
+const first = (entries: LogEntry[], kind: string, value?: string | null) =>
+ entries.find(
+ ([k, , v]) => k === kind && (value === undefined || v === value),
+ );
+
+test('outside a scroller, a finger’s press highlights in the frame it lands, and the lift fades it on the shared release clock', async ({
+ page,
+}) => {
+ const opened = await openSurface(page, BUTTONS, secondaryButton);
+ await opened.driver.play(tap(opened.center, {holdMs: 300}));
+ await expect
+ .poll(async () => opened.surface.getAttribute('data-astryx-press'))
+ .toBeNull();
+ const entries = await opened.log();
+ const down = first(entries, 'pointerdown');
+ const on = first(entries, 'press', 'on');
+ const up = first(entries, 'pointerup');
+ const fading = first(entries, 'press', 'fading');
+ const gone = first(entries, 'press', null);
+ expect(
+ down && on && up && fading && gone,
+ JSON.stringify(entries),
+ ).toBeTruthy();
+ if (!down || !on || !up || !fading || !gone) {
+ return;
+ }
+ expect(on[1] - down[1]).toBeLessThan(SAME_FRAME_MS);
+ expect(fading[1] - up[1]).toBeLessThan(SAME_FRAME_MS);
+ // The attribute leaves when the shared release clock runs out.
+ expect(gone[1] - fading[1]).toBeGreaterThanOrEqual(RELEASE_MS - 5);
+ expect(gone[1] - fading[1]).toBeLessThan(RELEASE_MS + 80);
+ // WebKit synthesises a click only from its own tap path, not from a raw
+ // touch sequence (harness README, engine limits); Chromium does from both.
+ if (opened.driver.engine === 'chromium') {
+ expect(entries.filter(([k]) => k === 'click')).toHaveLength(1);
+ }
+});
+
+test('inside a scroller, a held press waits UIScrollView’s content-touch delay', async ({
+ page,
+}) => {
+ const opened = await openSurface(page, SCROLLER, scrollerButton);
+ await opened.driver.play(tap(opened.center, {holdMs: HOLD_MS}));
+ const entries = await opened.log();
+ const down = first(entries, 'pointerdown');
+ const on = first(entries, 'press', 'on');
+ expect(down && on, JSON.stringify(entries)).toBeTruthy();
+ if (!down || !on) {
+ return;
+ }
+ expect(on[1] - down[1]).toBeGreaterThanOrEqual(CONTENT_TOUCH_DELAY_MS - 5);
+ expect(on[1] - down[1]).toBeLessThan(CONTENT_TOUCH_DELAY_MS + 60);
+ // WebKit synthesises a click only from its own tap path, not from a raw
+ // touch sequence (harness README, engine limits); Chromium does from both.
+ if (opened.driver.engine === 'chromium') {
+ expect(entries.filter(([k]) => k === 'click')).toHaveLength(1);
+ }
+});
+
+test('inside a scroller, a tap quicker than the delay highlights at the lift, then fades', async ({
+ page,
+}) => {
+ const opened = await openSurface(page, SCROLLER, scrollerButton);
+ await opened.driver.play(tap(opened.center, {holdMs: 60}));
+ await expect
+ .poll(async () => opened.surface.getAttribute('data-astryx-press'))
+ .toBeNull();
+ const entries = await opened.log();
+ const up = first(entries, 'pointerup');
+ const on = first(entries, 'press', 'on');
+ const fading = first(entries, 'press', 'fading');
+ expect(up && on && fading, JSON.stringify(entries)).toBeTruthy();
+ if (!up || !on || !fading) {
+ return;
+ }
+ // Nothing before the lift, the highlight at it, held for the quick-tap
+ // flash, then the release.
+ expect(on[1]).toBeGreaterThanOrEqual(up[1] - 5);
+ expect(fading[1] - on[1]).toBeGreaterThanOrEqual(90);
+ // WebKit synthesises a click only from its own tap path, not from a raw
+ // touch sequence (harness README, engine limits); Chromium does from both.
+ if (opened.driver.engine === 'chromium') {
+ expect(entries.filter(([k]) => k === 'click')).toHaveLength(1);
+ }
+});
+
+test('a tap through the engine’s own tap path paints the press and activates once', async ({
+ page,
+}) => {
+ const opened = await openSurface(page, BUTTONS, secondaryButton);
+ await opened.driver.tap(opened.center);
+ await expect
+ .poll(async () => opened.surface.getAttribute('data-astryx-press'))
+ .toBeNull();
+ const entries = await opened.log();
+ expect(first(entries, 'press', 'on'), JSON.stringify(entries)).toBeTruthy();
+ expect(first(entries, 'press', 'fading')).toBeTruthy();
+ expect(entries.filter(([k]) => k === 'click')).toHaveLength(1);
+});
+
+test('inside a scroller, a flick scrolls the list and paints nothing', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'injected touches start no native scroll in this WebKit build; the iOS simulator covers it',
+ );
+ const opened = await openSurface(page, SCROLLER, scrollerButton);
+ await opened.driver.play(
+ flick(opened.center, {velocity: {x: 0, y: -1500}, durationMs: 80}),
+ );
+ await page.waitForTimeout(300);
+ const entries = await opened.log();
+ expect(
+ entries.filter(([k]) => k === 'press'),
+ JSON.stringify(entries),
+ ).toEqual([]);
+ expect(entries.filter(([k]) => k === 'click')).toHaveLength(0);
+ const scrolled = await page
+ .getByTestId('button-scroller')
+ .evaluate(el => el.scrollTop);
+ expect(scrolled).toBeGreaterThan(0);
+});
+
+test('inside a scroller, a scroll that takes a held press cancels it: the paint goes at once, with no fade and no click', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'injected touches start no native scroll in this WebKit build; the iOS simulator covers it',
+ );
+ const opened = await openSurface(page, SCROLLER, scrollerButton);
+ await opened.driver.play(
+ holdThenDrag(
+ opened.center,
+ {x: opened.center.x, y: opened.center.y - 150},
+ {holdMs: 300, durationMs: 300},
+ ),
+ );
+ await page.waitForTimeout(100);
+ const entries = await opened.log();
+ const presses = entries.filter(([k]) => k === 'press').map(([, , v]) => v);
+ // Highlighted while held; the browser's takeover removes it, never fades it.
+ expect(presses, JSON.stringify(entries)).toEqual(['on', null]);
+ expect(first(entries, 'pointercancel')).toBeTruthy();
+ expect(entries.filter(([k]) => k === 'click')).toHaveLength(0);
+ const scrolled = await page
+ .getByTestId('button-scroller')
+ .evaluate(el => el.scrollTop);
+ expect(scrolled).toBeGreaterThan(0);
+});
+
+test(
+ 'storyboard: a button pressed and lifted outside a scroller',
+ {tag: '@storyboard'},
+ async ({page}, testInfo) => {
+ const opened = await openSurface(page, BUTTONS, secondaryButton);
+ await installTimerGate(page);
+ const box = await opened.surface.boundingBox();
+ if (box == null) {
+ throw new Error('no button');
+ }
+ const clip = {
+ x: Math.max(0, box.x - 16),
+ y: Math.max(0, box.y - 16),
+ width: box.width + 32,
+ height: box.height + 32,
+ };
+ const storyboard = await touchStoryboard(
+ page,
+ opened.driver,
+ tap(opened.center, {holdMs: 300}),
+ {
+ name: 'button-press-touch-down',
+ clip,
+ measure: async () => ({
+ state: await opened.surface.getAttribute('data-astryx-press'),
+ }),
+ columns: 3,
+ },
+ );
+ await freezeTimers(page);
+ await storyboard.write(testInfo);
+ await thawTimers(page);
+ const states = storyboard.frames.map(f => f.data.state as string | null);
+ // Before the touch, the touch itself (already highlighted), the lift.
+ expect(states).toEqual([null, 'on', 'fading']);
+ },
+);
diff --git a/packages/core/src/List/__tests__/ListRowPress.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListRowPress.interaction.browser.spec.ts
index 5450adc88b..9c8ac9b1d3 100644
--- a/packages/core/src/List/__tests__/ListRowPress.interaction.browser.spec.ts
+++ b/packages/core/src/List/__tests__/ListRowPress.interaction.browser.spec.ts
@@ -288,7 +288,10 @@ for (const story of [LIST_ROW, SCROLLER_ROW, TREE_ROW]) {
await page.waitForTimeout(150);
const frames = await cast.stop();
const pixels = await samplePixel(page, frames, probe);
- const rest = pixels[0].value;
+ // The last frame is the row at rest: the release ended inside the block.
+ // The first frame can already show the press, because a row outside a
+ // scroller paints in the frame the finger lands.
+ const rest = pixels[pixels.length - 1].value;
const pressedFrames = pixels.filter(p => p.t < release.from);
const pressed = Math.min(...pressedFrames.map(p => p.value));
const strength = (v: number) => (rest - v) / (rest - pressed);
diff --git a/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts b/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts
index 3ed3f3fbf5..1860de1318 100644
--- a/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts
+++ b/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts
@@ -9,8 +9,8 @@
* @output Real-engine proof that on a touch-first device a held mouse press
* and a held Space press paint the pressed state with the same pixels and
* scale a desktop `:active` press paints, and fade at the release; that a
- * desktop press is still `:active` alone; and that a finger's press still
- * waits for the touch press model's onset
+ * desktop press is still `:active` alone; and that a finger's press on a
+ * control is highlighted as the finger lands
* @position Run with `pnpm test:a11y-contract`. Browser layer of the touch
* press model (utils/pressFeedback.ts); the jsdom layer is
* utils/pressFeedback.test.ts.
@@ -274,7 +274,7 @@ test('a desktop press is unchanged: `:active` paints it and the controller write
expectSameColour(space.pressed, mouse.pressed);
});
-test("a finger's press is unchanged: it waits for the onset, then fades at the lift", async ({
+test("a finger's press on a control highlights as the finger lands, then fades at the lift", async ({
browser,
browserName,
}) => {
@@ -294,14 +294,19 @@ test("a finger's press is unchanged: it waits for the onset, then fades at the l
: [],
});
await touch('touchStart');
- await phone.page.waitForTimeout(60);
- const early = await pressAttribute(phone.page);
- await phone.page.waitForTimeout(190);
- const believed = await pressAttribute(phone.page);
+ // Outside a scroller a control highlights in the frame the finger lands
+ // (UIControl's touchDown); nothing waits for a scroll that cannot come.
+ await phone.page.evaluate(
+ async () =>
+ new Promise(resolve => requestAnimationFrame(() => resolve(null))),
+ );
+ const landed = await pressAttribute(phone.page);
+ await phone.page.waitForTimeout(250);
+ const held = await pressAttribute(phone.page);
await touch('touchEnd');
const lifted = await pressAttribute(phone.page);
- expect(early).toBeNull();
- expect(believed).toBe('on');
+ expect(landed).toBe('on');
+ expect(held).toBe('on');
expect(lifted).toBe('fading');
} finally {
await phone.close();
diff --git a/packages/core/src/gestures/nativeScroll.ts b/packages/core/src/gestures/nativeScroll.ts
index bea018ef49..43b5d5a493 100644
--- a/packages/core/src/gestures/nativeScroll.ts
+++ b/packages/core/src/gestures/nativeScroll.ts
@@ -31,33 +31,18 @@
import {isRtlElement} from '../hooks/isRtlElement';
import type {NativeScrollProbe} from './types';
import {parentAcrossShadow} from '../utils/flatTree';
+import {
+ isInsideScrollView,
+ parseTouchAction,
+ rootOverflow,
+ SCROLLABLE_OVERFLOW as SCROLLABLE,
+ type AllowedPans,
+} from '../utils/scrollView';
export {parentAcrossShadow};
-export interface AllowedPans {
- readonly x: boolean;
- readonly y: boolean;
-}
-
-/** Which pans a `touch-action` value lets the browser perform. */
-export function parseTouchAction(value: string): AllowedPans {
- const tokens = value.trim().split(/\s+/);
- if (tokens.includes('auto') || tokens.includes('manipulation')) {
- return {x: true, y: true};
- }
- if (tokens.includes('none')) {
- return {x: false, y: false};
- }
- return {
- x: tokens.some(
- token =>
- token === 'pan-x' || token === 'pan-left' || token === 'pan-right',
- ),
- y: tokens.some(
- token => token === 'pan-y' || token === 'pan-up' || token === 'pan-down',
- ),
- };
-}
+export {parseTouchAction};
+export type {AllowedPans};
interface ChainEntry {
readonly element: Element;
@@ -66,15 +51,8 @@ interface ChainEntry {
readonly isRtl: boolean;
readonly stopsX: boolean;
readonly stopsY: boolean;
- /**
- * The scroller sits beyond a `position: fixed` ancestor of the touch: it
- * still scrolls under the finger, but it does not carry the touched
- * element, so the element is not inside a scroll view (spec:AST-094 FR11).
- */
- readonly isBeyondFixed: boolean;
}
-const SCROLLABLE = new Set(['auto', 'scroll', 'overlay']);
const EDGE_TOLERANCE = 1;
interface Chain {
@@ -94,7 +72,6 @@ function buildChain(target: Element, readsTouchAction: boolean): Chain {
let allowX = true;
let allowY = true;
let reachedRoot = false;
- let isBeyondFixed = false;
for (
let node: Node | null = target;
node != null;
@@ -128,15 +105,11 @@ function buildChain(target: Element, readsTouchAction: boolean): Chain {
isRtl: isRtlElement(element as HTMLElement),
stopsX: behaviorX !== 'auto',
stopsY: behaviorY !== 'auto',
- isBeyondFixed,
});
}
if (isRoot) {
break;
}
- if (style.position === 'fixed') {
- isBeyondFixed = true;
- }
}
if (!reachedRoot && root instanceof Element) {
chain.push({
@@ -146,7 +119,6 @@ function buildChain(target: Element, readsTouchAction: boolean): Chain {
isRtl: false,
stopsX: false,
stopsY: false,
- isBeyondFixed,
});
}
return {entries: chain, allowsPan: allowX || allowY};
@@ -167,28 +139,6 @@ function overscrollBehavior(style: CSSStyleDeclaration): [string, string] {
return [x || first, y || second];
}
-/**
- * The viewport scrolls unless the root or the body clips it (a scroll lock
- * sets `overflow: hidden` on one of them).
- */
-function rootOverflow(doc: Document, axis: 'x' | 'y'): string {
- const view = doc.defaultView;
- if (view == null) {
- return 'hidden';
- }
- for (const element of [doc.documentElement, doc.body]) {
- if (element == null) {
- continue;
- }
- const style = view.getComputedStyle(element);
- const value = axis === 'x' ? style.overflowX : style.overflowY;
- if (value === 'hidden' || value === 'clip') {
- return 'hidden';
- }
- }
- return 'auto';
-}
-
function canMoveY(element: Element, dy: number): boolean {
if (element.scrollHeight - element.clientHeight <= EDGE_TOLERANCE) {
return false;
@@ -288,15 +238,9 @@ export function createNativeScrollProbe(
return chain?.allowsPan === true;
},
get isInsideScroller(): boolean {
- return getChain().some(
- entry =>
- !entry.isBeyondFixed &&
- ((entry.y &&
- entry.element.scrollHeight - entry.element.clientHeight >
- EDGE_TOLERANCE) ||
- (entry.x &&
- entry.element.scrollWidth - entry.element.clientWidth >
- EDGE_TOLERANCE)),
+ return (
+ target instanceof Element &&
+ isInsideScrollView(target, {readsTouchAction})
);
},
};
diff --git a/packages/core/src/hooks/usePressFeedback.doc.mjs b/packages/core/src/hooks/usePressFeedback.doc.mjs
index d33540b8ee..b749480c2a 100644
--- a/packages/core/src/hooks/usePressFeedback.doc.mjs
+++ b/packages/core/src/hooks/usePressFeedback.doc.mjs
@@ -20,12 +20,12 @@ export const docs = {
name: 'pressableProps',
type: "{'data-astryx-pressable': ''}",
description:
- "The marker attribute to spread on the element that paints the press. Compose one of `interactionOverlayStyles` (from `@astryxdesign/core/utils`) on the same element — `backgroundColor` or `backgroundImage` for a surface whose hover and press are the system's overlays, `pressedBackgroundColor` for one whose hover is its own — and it paints the pressed token at the press's strength on the first frame of a believed press and fades it over the release, keeping `:active` for a mouse on a desktop. On a phone or tablet, where the stylesheet drops `:active`, the controller also paints a mouse, trackpad or Space-key press: at once, held while the button or key is down, faded at the release. A press is themed through `--color-overlay-pressed`.",
+ "The marker attribute to spread on the element that paints the press. Compose one of `interactionOverlayStyles` (from `@astryxdesign/core/utils`) on the same element — `backgroundColor` or `backgroundImage` for a surface whose hover and press are the system's overlays, `pressedBackgroundColor` for one whose hover is its own — and it paints the pressed token on the first frame of a press and fades it over the release, keeping `:active` for a mouse on a desktop. On a phone or tablet, where the stylesheet drops `:active`, the controller also paints a mouse, trackpad or Space-key press: at once, held while the button or key is down, faded at the release. A press is themed through `--color-overlay-pressed`.",
},
],
usage: {
description:
- 'The touch press model every Astryx pressable uses, for a local component that paints its own press. Under a finger, CSS `:active` paints on the touch itself and can outlive the start of a scroll; the press model instead waits 150 ms before believing a press, cancels it the moment the finger travels 10 px or a scroll claims the gesture, never brings it back inside that gesture, answers a quick tap at the lift, and fades the release over 200 ms — the clocks a native list uses. One document-level controller does this for every marked element (installed by the first pressable to mount, removed by the last to unmount), so calling the hook adds no listener or state to your element. On a desktop a mouse press is still your `:active` rule: keep it, and drop it under `@media (pointer: coarse)` the way the built-in components do. That query reads the primary pointer, so on a phone or tablet it also drops `:active` for a connected mouse, trackpad or keyboard; the controller paints those presses there (at once, faded at the release), so nothing goes unanswered.',
+ 'The touch press model every Astryx pressable uses, for a local component that paints its own press. Under a finger, CSS `:active` paints on the touch itself and can outlive the start of a scroll; the press model instead tracks the touch the way UIKit tracks a control: it highlights as the finger lands (after the content-touch delay inside a scroller, where a flick paints nothing), a quick tap answers at the lift, and a scroll that takes the touch cancels it with no fade. One document-level controller does this for every marked element (installed by the first pressable to mount, removed by the last to unmount), so calling the hook adds no listener or state to your element. On a desktop a mouse press is still your `:active` rule: keep it, and drop it under `@media (pointer: coarse)` the way the built-in components do. That query reads the primary pointer, so on a phone or tablet it also drops `:active` for a connected mouse, trackpad or keyboard; the controller paints those presses there (at once, faded at the release), so nothing goes unanswered.',
bestPractices: [
{
guidance: true,
@@ -58,7 +58,7 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
export const docsDense = {
description:
- 'Marks an element as a pressable surface of the touch press model (150 ms onset, 10 px slop, cancel on scroll, tap answers at lift, 200 ms fade) and installs the shared document controller; on a coarse primary pointer it also paints mouse, trackpad and Space-key presses at once. Returns the data-astryx-pressable marker to spread; compose one of interactionOverlayStyles on the same element to paint.',
+ 'Marks an element as a pressable surface of the touch press model, tracked like a UIKit control (highlight as the finger lands, 150 ms inside a scroller, fade at the lift), and installs the shared document controller; on a coarse primary pointer it also paints mouse, trackpad and Space-key presses at once. Returns the data-astryx-pressable marker to spread; compose one of interactionOverlayStyles on the same element to paint.',
paramDescriptions: {},
returnDescriptions: {
pressableProps:
diff --git a/packages/core/src/hooks/usePressFeedback.ts b/packages/core/src/hooks/usePressFeedback.ts
index d8801ab514..9d3bda758e 100644
--- a/packages/core/src/hooks/usePressFeedback.ts
+++ b/packages/core/src/hooks/usePressFeedback.ts
@@ -26,11 +26,11 @@ import {installPressFeedback, pressableProps} from '../utils/pressFeedback';
* `interactionOverlayStyles` (from `@astryxdesign/core/utils`) on the same
* element: `backgroundColor` or `backgroundImage` for a surface whose hover
* and press are the system's overlays, `pressedBackgroundColor` for one
- * whose hover is its own. The controller writes its attribute on the element
- * while a touch press is believed (after the onset delay, cancelled by travel
- * or by a scroll) and for the release, and the composed style paints the
- * pressed token at the press's strength on the first frame and fades it over
- * the release, keeping `:active` for a mouse on a desktop. On a phone or
+ * whose hover is its own. Under a finger the controller tracks the press the
+ * way UIKit tracks a control and writes its
+ * attribute on the element while the press is held and for the release; the
+ * composed style paints the pressed token on the first frame and fades it
+ * over the release, keeping `:active` for a mouse on a desktop. On a phone or
* tablet the stylesheet drops `:active` for every press, so the controller
* also paints a mouse, trackpad or Space-key press there, at once. A press is
* themed through `--color-overlay-pressed`, which the hold, the flash and the
@@ -46,7 +46,7 @@ import {installPressFeedback, pressableProps} from '../utils/pressFeedback';
* @example
* ```
* const pressable = usePressFeedback();
- * return <div role="button" {...pressable} {...stylex.props(styles.row)} />;
+ * return <button {...pressable} {...stylex.props(styles.button)} />;
* ```
*/
export function usePressFeedback(): typeof pressableProps {
diff --git a/packages/core/src/utils/pressFeedback.test.ts b/packages/core/src/utils/pressFeedback.test.ts
index d7e1fc70aa..01003cb397 100644
--- a/packages/core/src/utils/pressFeedback.test.ts
+++ b/packages/core/src/utils/pressFeedback.test.ts
@@ -77,6 +77,18 @@ function pressable(tag = 'div'): HTMLElement {
return element;
}
+/** Make `element` a scroller with content to scroll, as jsdom lays out nothing. */
+function makeScroller(element: HTMLElement): void {
+ element.style.overflowY = 'auto';
+ Object.defineProperty(element, 'clientHeight', {
+ configurable: true,
+ value: 100,
+ });
+ Object.defineProperty(element, 'scrollHeight', {
+ configurable: true,
+ value: 400,
+ });
+}
/**
* The primary pointer is coarse (a phone, a tablet) until the returned
* restore runs: jsdom's matchMedia models a desktop, where touch work stays
@@ -111,6 +123,9 @@ beforeEach(() => {
scroller.appendChild(row);
rows.push(row);
}
+ // The rows sit in a list that scrolls, as on a phone: a finger's press
+ // waits the content-touch delay there (`spec:AST-094` FR11).
+ makeScroller(scroller);
document.body.appendChild(scroller);
release = installPressFeedback();
});
@@ -518,6 +533,111 @@ describe('a scroll takes it away and nothing brings it back', () => {
});
});
+describe('a finger waits only inside a scroller (spec:AST-094 FR11)', () => {
+ it('outside a scroller, paints in the frame the finger lands', () => {
+ const control = pressable('button');
+ document.body.appendChild(control);
+ press(control, 'pointerdown', 10, 10);
+ expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+
+ it('inside a scroller, waits the content-touch delay', () => {
+ const control = pressable('button');
+ scroller.appendChild(control);
+ press(control, 'pointerdown', 10, 10);
+ expect(control.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+
+ it('is cancelled by travel past the slop, with no fade', () => {
+ const control = pressable('button');
+ document.body.appendChild(control);
+ press(control, 'pointerdown', 10, 10);
+ press(control, 'pointermove', 10, 10 + PRESS_SLOP_PX + 1);
+ expect(control.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('slotted into a scroller inside a shadow tree, waits the content-touch delay', () => {
+ // The browser scrolls the flat tree: a slotted pressable sits in the
+ // shadow tree's scroller, not beside it in the light tree.
+ const host = document.createElement('div');
+ const shadowScroller = document.createElement('div');
+ makeScroller(shadowScroller);
+ shadowScroller.appendChild(document.createElement('slot'));
+ host.attachShadow({mode: 'open'}).appendChild(shadowScroller);
+ const control = pressable('button');
+ host.appendChild(control);
+ document.body.appendChild(host);
+ expect(control.assignedSlot).not.toBeNull();
+ press(control, 'pointerdown', 10, 10);
+ expect(control.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+
+ it('in a fixed bar above a scrolling list, paints in the frame the finger lands', () => {
+ const bar = document.createElement('div');
+ bar.style.position = 'fixed';
+ const control = pressable('button');
+ bar.appendChild(control);
+ scroller.appendChild(bar);
+ press(control, 'pointerdown', 10, 10);
+ expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+
+ it('fades at the lift, then leaves no attribute behind', () => {
+ const control = pressable('button');
+ document.body.appendChild(control);
+ press(control, 'pointerdown', 10, 10);
+ press(control, 'pointerup', 10, 10);
+ expect(control.getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ expect(control.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('a menu row in a menu that cannot scroll highlights at once (DEC-14)', () => {
+ // A menu whose rows fit: overflow set, but nothing to scroll.
+ const menu = document.createElement('div');
+ menu.setAttribute('role', 'menu');
+ menu.style.overflowY = 'auto';
+ Object.defineProperty(menu, 'clientHeight', {
+ configurable: true,
+ value: 200,
+ });
+ Object.defineProperty(menu, 'scrollHeight', {
+ configurable: true,
+ value: 200,
+ });
+ const row = pressable('div');
+ row.setAttribute('role', 'menuitem');
+ menu.appendChild(row);
+ document.body.appendChild(menu);
+ press(row, 'pointerdown', 10, 10);
+ expect(row.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+
+ it('a menu row in a menu that can scroll waits the content-touch delay (DEC-14)', () => {
+ const menu = document.createElement('div');
+ menu.setAttribute('role', 'menu');
+ makeScroller(menu);
+ const row = pressable('div');
+ row.setAttribute('role', 'menuitem');
+ menu.appendChild(row);
+ document.body.appendChild(menu);
+ press(row, 'pointerdown', 10, 10);
+ expect(row.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ expect(row.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+});
+
+describe('the release clock the browser specs read', () => {
+ it('is 200 ms (ButtonPress.interaction.browser.spec.ts RELEASE_MS)', () => {
+ expect(PRESS_FADE_MS).toBe(200);
+ });
+});
+
describe('the release', () => {
it('fades, then leaves no attribute behind', () => {
press(rows[0], 'pointerdown', 10, 10);
diff --git a/packages/core/src/utils/pressFeedback.ts b/packages/core/src/utils/pressFeedback.ts
index 3eb167b1db..7bd08417af 100644
--- a/packages/core/src/utils/pressFeedback.ts
+++ b/packages/core/src/utils/pressFeedback.ts
@@ -3,7 +3,7 @@
/**
* @file pressFeedback.ts
* @input The press state machine (pressGesture.ts), the menu-press and
- * press-group markers and the document's pointer, keyboard, scroll and
+ * 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
@@ -23,9 +23,13 @@
// Where the primary pointer is fine, the controller ignores the mouse and the
// keyboard, and CSS `:active` keeps their press. Under a coarse primary
// pointer the CSS drops `:active`, so the controller paints every press. A
-// finger's press paints after the delay. A mouse, trackpad or Space press
-// paints at once. The controller reads the same query as the stylesheet, so
-// they agree.
+// mouse, trackpad or Space press paints at once. The controller reads the
+// same query as the stylesheet, so they agree.
+//
+// A finger waits only inside a scroller. Outside one, a surface highlights in
+// the frame the finger lands, as a UIControl does. Inside one, it waits the
+// content-touch delay, because the touch can become a scroll. Rows follow the
+// same rule.
//
// A surface's hold does nothing, so it keeps the browser's long-press text
// selection (AST-094). Only an element whose hold does something suppresses
@@ -44,6 +48,7 @@ import {
} from './pressGesture';
import {isCoarsePointer, watchCoarsePointer} from './coarsePointer';
import {subscribeInput} from './inputStream';
+import {isInsideScrollView} from './scrollView';
import {TOUCH_QUERY} from './touchPresentation';
import {holdsPressThroughDrag} from '../privateAttributes/pressHoldsDrag.stylex';
import {isTrackedByGroup} from '../privateAttributes/pressGroupItem.stylex';
@@ -247,7 +252,11 @@ function paintElement(element: HTMLElement, paint: PressPaint): void {
element.removeAttribute(PRESSED_ATTRIBUTE);
return;
}
- element.setAttribute(PRESSED_ATTRIBUTE, paint);
+ // A step that keeps the paint writes nothing, so the element sees one
+ // change per paint.
+ if (element.getAttribute(PRESSED_ATTRIBUTE) !== paint) {
+ element.setAttribute(PRESSED_ATTRIBUTE, paint);
+ }
}
function clearTimer(slot: Slot): void {
@@ -536,6 +545,7 @@ function onPointerDown(event: PointerEvent): void {
kind: 'down',
x: event.clientX,
y: event.clientY,
+ delayed: isInsideScrollView(element),
}),
);
}
diff --git a/packages/core/src/utils/pressGesture.test.ts b/packages/core/src/utils/pressGesture.test.ts
index f292cd81a2..e244a5ffc1 100644
--- a/packages/core/src/utils/pressGesture.test.ts
+++ b/packages/core/src/utils/pressGesture.test.ts
@@ -330,3 +330,48 @@ describe('on a touch-first device, a mouse button or the Space key presses at on
expect(paints).toEqual(['on', 'fading', 'on']);
});
});
+
+describe('a control with no scroller above it does not wait', () => {
+ const now = (x = 100, y = 100): PressEvent => ({
+ kind: 'down',
+ x,
+ y,
+ delayed: false,
+ });
+
+ it('paints in the frame the finger lands, with no timer', () => {
+ const step = pressGestureStep(idlePressGesture(), now());
+ expect(step.paint).toBe('on');
+ expect(step.gesture.phase).toBe('pressed');
+ expect(step.timer).toBeNull();
+ });
+
+ it('is still cancelled by travel past the slop, with no fade', () => {
+ expect(run([now(), move(100, 100 + PRESS_SLOP_PX + 1)]).paints).toEqual([
+ 'on',
+ 'none',
+ ]);
+ });
+
+ it('is still cancelled by the scroll that takes the touch', () => {
+ expect(run([now(), {kind: 'cancel'}]).paints).toEqual(['on', 'none']);
+ });
+
+ it('fades at the lift', () => {
+ const {paints, gesture} = run([now(), {kind: 'up'}]);
+ expect(paints).toEqual(['on', 'fading']);
+ expect(gesture.phase).toBe('fading');
+ });
+
+ it('a delayed touch still waits, which is the default', () => {
+ expect(
+ pressGestureStep(idlePressGesture(), {
+ kind: 'down',
+ x: 100,
+ y: 100,
+ delayed: true,
+ }).paint,
+ ).toBe('none');
+ expect(pressGestureStep(idlePressGesture(), down()).paint).toBe('none');
+ });
+});
diff --git a/packages/core/src/utils/pressGesture.ts b/packages/core/src/utils/pressGesture.ts
index ecfb5e979c..b1e63c0d05 100644
--- a/packages/core/src/utils/pressGesture.ts
+++ b/packages/core/src/utils/pressGesture.ts
@@ -21,6 +21,10 @@
// primary pointer, so a mouse, trackpad or Space press on such a device comes
// here as `buttonDown`: painted at once and faded on release.
//
+// Only a finger inside a scroller waits. The controller tells the machine
+// which touch waits (`down`'s `delayed`), and a touch that does not wait goes
+// straight to `pressed`. After that the machine is the same.
+//
// The constants were measured against native apps. The machine knows nothing
// of the DOM, so {@link pressGestureStep}'s cases are the state diagram.
@@ -105,7 +109,17 @@ export interface PressGesture {
}
export type PressEvent =
- | {kind: 'down'; x: number; y: number}
+ | {
+ kind: 'down';
+ x: number;
+ y: number;
+ /**
+ * Whether this touch waits {@link PRESS_ONSET_MS} before it paints:
+ * a surface inside a scroller. Defaults to
+ * `true`.
+ */
+ delayed?: boolean;
+ }
/**
* A mouse button or the Space key went down on the surface. The
* controller sends this only where the stylesheet has dropped `:active`
@@ -167,6 +181,15 @@ export function pressGestureStep(
event: PressEvent,
): PressStep {
if (event.kind === 'down') {
+ // A surface with no scroller above it: nothing can turn this touch into a
+ // scroll, so it paints in the frame it lands, as a UIControl highlights.
+ if (event.delayed === false) {
+ return {
+ gesture: {originX: event.x, originY: event.y, phase: 'pressed'},
+ paint: 'on',
+ timer: null,
+ };
+ }
// A new touch always starts armed and painting nothing, whatever the last
// gesture ended as. This is the only way out of `dead`.
return {
diff --git a/packages/core/src/utils/scrollView.ts b/packages/core/src/utils/scrollView.ts
new file mode 100644
index 0000000000..62b7430def
--- /dev/null
+++ b/packages/core/src/utils/scrollView.ts
@@ -0,0 +1,135 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file scrollView.ts
+ * @input An element and its computed styles
+ * @output Exports parseTouchAction, rootOverflow, SCROLLABLE_OVERFLOW and
+ * isInsideScrollView: whether a touch on the element lands inside a box the
+ * browser can scroll
+ * @position The one definition of "inside a scroll view", shared by the
+ * press feedback controller (utils/pressFeedback.ts) and the gesture
+ * core's native-scroll probe (gestures/nativeScroll.ts), so Core's main
+ * entry can ask it without the gesture core
+ */
+
+import {parentAcrossShadow} from './flatTree';
+
+/** Overflow values that let a box scroll. */
+export const SCROLLABLE_OVERFLOW: ReadonlySet<string> = new Set([
+ 'auto',
+ 'scroll',
+ 'overlay',
+]);
+
+/** How far a box must overflow, in px, before it counts as scrolling. */
+const OVERFLOW_TOLERANCE_PX = 1;
+
+export interface AllowedPans {
+ readonly x: boolean;
+ readonly y: boolean;
+}
+
+/** Which pans a `touch-action` value lets the browser perform. */
+export function parseTouchAction(value: string): AllowedPans {
+ const tokens = value.trim().split(/\s+/);
+ if (tokens.includes('auto') || tokens.includes('manipulation')) {
+ return {x: true, y: true};
+ }
+ if (tokens.includes('none')) {
+ return {x: false, y: false};
+ }
+ return {
+ x: tokens.some(
+ token =>
+ token === 'pan-x' || token === 'pan-left' || token === 'pan-right',
+ ),
+ y: tokens.some(
+ token => token === 'pan-y' || token === 'pan-up' || token === 'pan-down',
+ ),
+ };
+}
+
+/**
+ * The viewport's overflow on an axis. It scrolls unless the root or the body
+ * clips it, as a scroll lock does with `overflow: hidden`.
+ */
+export function rootOverflow(doc: Document, axis: 'x' | 'y'): string {
+ const view = doc.defaultView;
+ if (view == null) {
+ return 'hidden';
+ }
+ for (const element of [doc.documentElement, doc.body]) {
+ if (element == null) {
+ continue;
+ }
+ const style = view.getComputedStyle(element);
+ const value = axis === 'x' ? style.overflowX : style.overflowY;
+ if (value === 'hidden' || value === 'clip') {
+ return 'hidden';
+ }
+ }
+ return 'auto';
+}
+
+function overflows(element: Element, axis: 'x' | 'y'): boolean {
+ return axis === 'y'
+ ? element.scrollHeight - element.clientHeight > OVERFLOW_TOLERANCE_PX
+ : element.scrollWidth - element.clientWidth > OVERFLOW_TOLERANCE_PX;
+}
+
+/**
+ * Whether a touch on `element` lands inside a scroll view, UIKit's question
+ * for a touch: a box above it, the page included, overflows on an axis it
+ * scrolls, and `touch-action` on the way up leaves that axis to the browser.
+ * A `position: fixed` box ends the walk, because it does not move with any
+ * scroller above it. A wheel scrolls whatever `touch-action` says, so a
+ * wheel's question passes `readsTouchAction: false`.
+ */
+export function isInsideScrollView(
+ element: Element,
+ {readsTouchAction = true}: {readsTouchAction?: boolean} = {},
+): boolean {
+ const doc = element.ownerDocument;
+ const view = doc.defaultView;
+ if (view == null) {
+ return false;
+ }
+ const root = doc.scrollingElement ?? doc.documentElement;
+ let panX = true;
+ let panY = true;
+ for (let node: Node | null = element; node != null;) {
+ if (node instanceof Element) {
+ const style = view.getComputedStyle(node);
+ if (readsTouchAction) {
+ const pans = parseTouchAction(style.touchAction || 'auto');
+ panX &&= pans.x;
+ panY &&= pans.y;
+ }
+ if (node === root || node === doc.documentElement) {
+ break;
+ }
+ if (
+ (panY &&
+ SCROLLABLE_OVERFLOW.has(style.overflowY) &&
+ overflows(node, 'y')) ||
+ (panX &&
+ SCROLLABLE_OVERFLOW.has(style.overflowX) &&
+ overflows(node, 'x'))
+ ) {
+ return true;
+ }
+ if (style.position === 'fixed') {
+ return false;
+ }
+ }
+ node = parentAcrossShadow(node);
+ }
+ return (
+ (panY &&
+ SCROLLABLE_OVERFLOW.has(rootOverflow(doc, 'y')) &&
+ overflows(root, 'y')) ||
+ (panX &&
+ SCROLLABLE_OVERFLOW.has(rootOverflow(doc, 'x')) &&
+ overflows(root, 'x'))
+ );
+}