Skip to content

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

TypeScript

feat(Layer): one input hold, first used by Dialog, Drawer and MobileNav (spec:AST-094 FR35) (#8342)

Christopher Chedeau252b45bb1cd0
diff --git a/.changeset/dialog-drawer-touch-entrance-hold.md b/.changeset/dialog-drawer-touch-entrance-hold.md
new file mode 100644
index 0000000000..d8bffe2b35
--- /dev/null
+++ b/.changeset/dialog-drawer-touch-entrance-hold.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] On a phone or tablet (a coarse primary pointer), a tap or a drag that lands while a `Dialog` or a `Drawer` is still entering no longer closes it, runs one of its actions, moves focus or scrolls the page: it reaches nothing until the entrance has played, and the dialog or drawer finishes entering and stays open. Around a `Drawer` without a scrim only a tap or a drag on the panel is held, and the page stays live. Keys and assistive technology stay live during the entrance, the content stays in the accessibility tree, a pinch still zooms the page, and a mouse or a trackpad still clicks: at once when it was the last pointer used, otherwise once it moves.
+
+@vjeux
diff --git a/.changeset/layer-input-hold.md b/.changeset/layer-input-hold.md
new file mode 100644
index 0000000000..128ee5c515
--- /dev/null
+++ b/.changeset/layer-input-hold.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: one input hold for every layer (`Layer/inputHold`). While a layer presents, a finger's or a pen's touch, press or click reaches nothing: anywhere around a modal layer, and only on the layer itself around a non-modal one, whose page stays live. A mouse passes once it moves, at once when the page last heard a mouse (keys and assistive technology still act, and a pinch still zooms the page). While it dismisses, every press and click reaches nothing, and the layer's content is inert. The gesture host asks the hold about each touch (`holdsTouch`), and `isInputShield` lets a hit test see past a hold's shield. Not exported from the package entry point; Dialog's and Drawer's entrance holds and MobileNav's drawer use it.
+
+@vjeux
diff --git a/.changeset/mobile-nav-touch-presentation.md b/.changeset/mobile-nav-touch-presentation.md
new file mode 100644
index 0000000000..849c4d7a81
--- /dev/null
+++ b/.changeset/mobile-nav-touch-presentation.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] On a phone or tablet (a coarse primary pointer), a tap or a drag during MobileNav's slide-in reaches nothing; keys and assistive technology stay live, and a mouse or a trackpad still clicks: at once when it was the last pointer used, otherwise once it moves.
+
+@vjeux
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index fb49a046df..dcdca813ff 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -28,6 +28,8 @@ affects_consumer_docs: []
```json
{
"paths": [
+ "packages/core/src/Layer/holdEntranceInput.ts",
+ "packages/core/src/Layer/inputHold.ts",
"packages/core/src/motion/uikit/segmented.ts",
"packages/core/src/motion/uikit/slider.ts"
]
@@ -827,7 +829,13 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and
let a scrim or overlay tap close at any time (`spec:AST-003` FR10 and
`architecture:layer-runtime` INV14 leave dismissal to the component). Toast and a non-modal sheet (`component:BottomSheetSwitcher` FR5 and its
Non-modal state) do not hold the page: the page behind them stays live, and
- only the sheet itself holds a tap or a drag while it enters.
+ only the sheet itself holds a tap or a drag while it enters. Dialog, Drawer
+ and MobileNav hold an entrance only under a coarse primary pointer: where
+ the primary pointer is fine and the screen also takes touch (a touchscreen
+ laptop), a finger's tap or drag during the entrance is not held. After a
+ finger, the first press of a mouse that has not moved since lands on the
+ entering presentation's shield and does nothing, where FR35 keeps today's
+ behavior for a mouse (DEC-16); a move of the mouse lowers the shield first.
- BottomSheet, Toast, Lightbox, NavigationStack and keyboard dismissal: a
drag that commits follows FR36–FR40.
- `spec:AST-100` owns release velocity, which FR17 reads.
diff --git a/docs/specs/components/AlertDialog/AlertDialog.spec.md b/docs/specs/components/AlertDialog/AlertDialog.spec.md
index e683fdcded..7dfa5af902 100644
--- a/docs/specs/components/AlertDialog/AlertDialog.spec.md
+++ b/docs/specs/components/AlertDialog/AlertDialog.spec.md
@@ -19,6 +19,7 @@ verified_by:
packages/core/src/AlertDialog/__tests__/AlertDialog.a11y.test.tsx,
packages/core/src/AlertDialog/__tests__/AlertDialog.a11y.chromium.spec.ts,
packages/core/src/Dialog/Dialog.test.tsx,
+ packages/core/src/Dialog/__tests__/DialogTouchEntrance.interaction.browser.spec.ts,
scripts/check-knowledge.mjs,
apps/storybook/rtl-audit/targets.json,
]
@@ -52,7 +53,7 @@ system_specs:
| Behavior | A modal confirmation that interrupts: it opens through the native dialog, cannot be dismissed by a click outside, closes on Escape or Cancel through `onOpenChange(false)`, and runs `onAction` on the action button. |
| End-user impact | A keyboard or screen-reader user is told a decision is needed (the title and description are announced), lands on Cancel, and cannot lose the dialog by clicking past it. On a touch screen the alert scales in and fades out with iOS's look, on the theme's motion tokens, and ignores taps while it enters (FR6, FR7), and on a phone it is 320 px wide (FR9); on a touch screen a press slid from Cancel to the action runs the lifted action; a mouse's press acts natively (FR8). |
| Builder impact | None. |
-| Compatibility/readiness | FR1–FR5, FR8 and AR1 record shipped behavior, apart from AR1's Tab wrap. FR6, FR7 and FR9 are requirements not shipped yet. Each gap is listed under Current-state impact. |
+| Compatibility/readiness | FR1–FR5, FR8 and AR1 record shipped behavior, apart from AR1's Tab wrap. FR7 ships in part, and FR6 and FR9 are requirements not shipped yet. Each gap is listed under Current-state impact. |
| Review checks | Reject a modal AlertDialog without `role="alertdialog"`, a title or description not linked by id, initial focus on the destructive action, or a backdrop click that dismisses it. |
| Governing rules | `architecture:public-component-api/INV1,INV5–INV8`; `architecture:component-theming-surface/INV3–INV7`; `architecture:layer-runtime`; `component:Dialog/AR1–AR3`; `spec:AST-020/FR15`; `spec:AST-094` FR4, FR7, FR45, FR13, FR35, DEC-15, DEC-17; `family:action-groups`; `design:reduced-motion`; `spec:AST-017`. |
@@ -85,8 +86,9 @@ Consumer migration instructions belong in consumer docs and release notes.
- **The touch presentation is not shipped (FR6).** Under a touch presentation
the alert opens and closes with Dialog's default motion, not the scale-in and
fade-out FR6 requires.
-- **Pointer input is not held while the alert enters (FR7).** A tap that lands
- during the entrance reaches the alert; `spec:AST-094` FR35 holds it.
+- **Only the entrance hold ships (FR7).** Under a touch presentation, Dialog
+ holds pointer input while the alert enters. Nothing makes the content inert
+ while the alert leaves, because its dismissal fade has not shipped (FR6).
- **The phone width is not shipped (FR9).** On a phone the alert keeps its
default width rather than 320 px.
- **Tab leaves the alert (AR1).** Dialog does not yet contain Tab, so Tab from
@@ -130,7 +132,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR4 | `isInline` renders the same anatomy without modality and without the alert-dialog role. | shipped source and public docs |
| FR5 | `useImperativeAlertDialog` returns `show`, `hide`, and the element to render, and owns `isOpen`/`onOpenChange` for its caller. | shipped source and focused tests |
| FR6 | Under a touch presentation (`spec:AST-094` FR13), a modal AlertDialog presents by scaling from 1.2 to 1 with its opacity and its backdrop's dimming rising from 0 to 1 on the theme's entrance duration and easing tokens (`spec:AST-094` FR45), started at the browser's commit, with the larger start kept inside the viewport; it dismisses by a fade alone on the theme's exit duration and easing, `--duration-exit` and `--ease-exit` (`spec:AST-094` FR7; `spec:AST-090` FR14), and closes at the fade's end; a close during the presentation, or a reopen during the dismissal, turns back from where it is. `springs.alertPresent` and `springs.alertDismiss` stay as UIKit's measured reference, and no motion plays them (`spec:AST-094` FR4). Under Reduce Motion both are the shared cross-fade (`design:reduced-motion` DR1–DR3). A fine primary pointer keeps today's motion (`spec:AST-094` FR13 and its Non-goals). Implementation gap: not shipped yet (Current-state impact). | proposed from measured iOS 26.2 behavior |
-| FR7 | Under a touch presentation, pointer input to the alert is held while it enters (`spec:AST-094` FR35); keyboard and assistive-technology input are never held, and the entrance never makes the content inert. While the alert leaves, its content is inert for the dismissal fade. The hold's timing stays internal (`spec:AST-002` FR3). Implementation gap: not shipped yet (Current-state impact). | `spec:AST-094` FR35; owner decision (DEC-1) |
+| FR7 | Under a touch presentation, pointer input to the alert is held while it enters (`spec:AST-094` FR35); keyboard and assistive-technology input are never held, and the entrance never makes the content inert. While the alert leaves, its content is inert for the dismissal fade. The hold's timing stays internal (`spec:AST-002` FR3). Implementation gap: the entrance hold ships through Dialog, and the leaving alert's inert content waits for FR6's dismissal (Current-state impact). | `spec:AST-094` FR35; owner decision (DEC-1) |
| FR8 | AlertDialog's actions are an action group (`family:action-groups`): under the touch presentation (`spec:AST-094` FR13), a press that slides across them runs the action it lifts on, and a lift outside them runs nothing; a mouse press acts as the platform's native button does; keyboard and assistive-technology behavior is unchanged. | `family:action-groups`; `spec:AST-094` DEC-17; DEC-3 |
| FR9 | On a phone, a compact window (`spec:AST-012` FR9: narrower than `md` or shorter than 500 px) under a coarse primary pointer, the alert is 320 px wide in every theme, as iOS's is; no theme role sets it. A caller's explicit `width` still wins there (`architecture:public-component-api` INV5), and Dialog's viewport clamp still applies on a screen narrower than the alert. Elsewhere it keeps today's width. Implementation gap: not shipped yet (Current-state impact). | owner decision (DEC-2) |
@@ -229,7 +231,7 @@ The dialog surface (the Dialog element AlertDialog renders) carries `alert-dialo
| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| FR1–FR5 | `AlertDialog.test.tsx` ("calls onOpenChange(false) on Escape", "does not call onOpenChange when action is clicked", "does not call onAction on Escape", "does not disable the cancel button while the action is loading", "exposes a named group instead, with no aria-modal") and `useImperativeAlertDialog.test.tsx` ("opens on show()", "closes on hide()") | open, loading, inline, imperative | Escape not cancelling, the action closing by itself, or the inline path claiming the role fails. | `audit:AlertDialog/behavior` |
| FR6, PR2 | Browser tests under a coarse pointer in Chromium and WebKit, a theme-token curve oracle for the present and the dismissal, a busy-main-thread case, real-device clips on iOS Safari, and Android Chrome clips in the Android emulator (`spec:AST-094` DEC-27) | present, dismiss, close during present, reopen during dismiss, Reduce Motion, a fine pointer, a narrow viewport | a present or a tap-, key- or program-started dismissal that plays a measured role instead of the theme's entrance or exit duration and easing, a start outside the viewport, a jump on interruption, a scale under Reduce Motion, changed motion under a fine pointer, or an added element fails. No test exists yet; FR6 is not shipped. | `audit:AlertDialog/behavior` |
-| FR7 | Browser tests under a coarse pointer, with keyboard and assistive-technology input | a tap during the presentation, Enter and Escape during it, a screen reader's activation, a tap during the dismissal; a mouse click during the presentation under a fine pointer | a held key or assistive-technology action, content made inert during the entrance, a tap that reaches a leaving alert, or a mouse click held under a fine pointer fails. No test exists yet; FR7 is not shipped. | `audit:AlertDialog/behavior` |
+| FR7 | `DialogTouchEntrance.interaction.browser.spec.ts` ("a tap on an alert's action while it enters runs nothing, and once it has entered the same tap runs it"; "keys and assistive technology stay live while the dialog enters") | a tap during the presentation, Enter and Escape during it, a screen reader's activation, a tap during the dismissal; a mouse click during the presentation under a fine pointer | a held key or assistive-technology action, content made inert during the entrance, a tap that reaches a leaving alert, or a mouse click held under a fine pointer fails. No test covers the leaving alert, which FR6's dismissal brings. | `audit:AlertDialog/behavior` |
| FR8 | `AlertDialog.test.tsx` ("AlertDialog action tracking"), `useActionGroupTracking.test.tsx` and `AlertDialog.interaction.browser.spec.ts` | a press on Cancel slid onto the action and lifted, and a press lifted outside the actions, each with a mouse, a pen, and a finger; Enter and Space on each action | the press-start action running after a slide, any action running on a lift outside, or a changed keyboard or assistive-technology activation fails. | `audit:AlertDialog/behavior` |
| FR9 | Browser tests at a phone width and at a desktop width, in the default and an alternate theme | a phone width and a desktop width, in the default and an alternate theme; a caller `width` at a phone width; a screen narrower than 320 px; a narrow window under a fine pointer; a coarse screen that is not compact | a phone-width alert other than 320 px in any theme without a caller `width`, a caller `width` overridden, a desktop width changed, an alert wider than the viewport, or a 320 px alert in a narrow fine-pointer window or on a non-compact coarse screen fails. No test exists yet; FR9 is not shipped. | `audit:AlertDialog/behavior` |
| AR1 | `AlertDialog.test.tsx` ("links title via aria-labelledby", "marks cancel as the initial focus target", "keeps the initial focus target on the least destructive action", "calls onOpenChange(false) on Escape", "stacks long destructive action labels above cancel on a narrow fine-pointer screen", "reaches both buttons by Tab, cancel first", "is a modal alertdialog", "does not claim the alertdialog role") and `useImperativeAlertDialog.test.tsx`; the Alert Dialog accessibility contract binding in `__tests__/AlertDialog.a11y.test.tsx` and `__tests__/AlertDialog.a11y.chromium.spec.ts` (role, description link, no backdrop dismiss, focus delegation) | open modal; after Escape; after Cancel | The role, name link, description link, or Cancel initial focus is lost, or a click outside dismisses the dialog. Gap: the contract keeps `alertdialog.focus.least-destructive-first` and `alertdialog.dismissal.click-beside-is-inert` advisory, so a regression in either only reports; `spec:AST-020` FR9 makes them required once this record is current. No test covers Tab wrapping inside the alert (Current-state impact). | `audit:AlertDialog/accessibility` |
diff --git a/docs/specs/components/Dialog/Dialog.spec.md b/docs/specs/components/Dialog/Dialog.spec.md
index 009503d0c6..8673561fcc 100644
--- a/docs/specs/components/Dialog/Dialog.spec.md
+++ b/docs/specs/components/Dialog/Dialog.spec.md
@@ -31,7 +31,7 @@ architecture:
architecture:react-component-runtime,
]
contributing: []
-system_specs: [spec:AST-013, spec:AST-020, spec:AST-021]
+system_specs: [spec:AST-013, spec:AST-020, spec:AST-021, spec:AST-094/FR35]
---
# Dialog component contract
diff --git a/docs/specs/components/Drawer/Drawer.spec.md b/docs/specs/components/Drawer/Drawer.spec.md
index ac12067eb8..f5d47c6fba 100644
--- a/docs/specs/components/Drawer/Drawer.spec.md
+++ b/docs/specs/components/Drawer/Drawer.spec.md
@@ -95,10 +95,13 @@ Consumer migration instructions belong in consumer docs and release notes.
motion the slide and the scrim transition still run for 0.01 s. For a fine
pointer, `design:reduced-motion` DR1 forbids the travel and DR3 allows no
animated property; a touch user gets no opacity fade, which DR2 calls for.
-- **A tap during the entrance is not held.** Under a finger, a scrim tap that
- lands while the drawer is still entering closes an `info` drawer, and a tap
- or drag reaches the panel. `spec:AST-094` FR35 holds pointer input until the
- entrance finishes.
+- **A finger is held during the entrance only under a coarse primary
+ pointer.** There, a tap or a drag that lands while the drawer is still
+ entering reaches nothing, and around a non-modal drawer only one on the
+ panel is held. Where the primary pointer is fine and the screen also takes
+ touch (a touchscreen laptop), a finger's scrim tap during the entrance
+ closes an `info` drawer, and a tap or drag reaches the panel.
+ `spec:AST-094` FR35 holds pointer input until the entrance finishes.
- **A consumer `onCancel` never runs.** Drawer sets its own `onCancel` after
the caller's props, so a caller's `onCancel` is dropped.
`architecture:public-component-api` INV5 has accepted event inputs reach the
diff --git a/docs/specs/components/MobileNav/MobileNav.spec.md b/docs/specs/components/MobileNav/MobileNav.spec.md
index 5a1d45f9e9..c3d2f32f5c 100644
--- a/docs/specs/components/MobileNav/MobileNav.spec.md
+++ b/docs/specs/components/MobileNav/MobileNav.spec.md
@@ -24,6 +24,7 @@ verified_by:
packages/core/src/MobileNav/MobileNavPinchZoom.a11y.chromium.spec.ts,
packages/core/src/Layer/layerDismissalFamilies.test.tsx,
packages/core/src/MobileNav/__tests__/MobileNavWidth.a11y.chromium.spec.ts,
+ packages/core/src/MobileNav/__tests__/MobileNavTouchPresentation.a11y.chromium.spec.ts,
packages/core/src/theme/themingTargets.test.ts,
scripts/check-knowledge.mjs,
apps/storybook/rtl-audit/targets.json,
@@ -40,7 +41,7 @@ architecture:
architecture:public-component-api,
]
contributing: []
-system_specs: []
+system_specs: [spec:AST-094/FR13, spec:AST-094/FR35]
---
# MobileNav component contract
@@ -142,7 +143,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR2 | `isOpen` and `onOpenChange` win when given; otherwise the drawer reads and changes the enclosing AppShell's drawer state. The dialog uses AppShell's drawer id when there is one, else its own; a caller `id` replaces either (Current-state impact). | Current source and tests |
| FR3 | Opening calls `showModal()`, and records the focused element as the opener; where focus lands inside the open drawer is uncontracted here. While open, the page's scroller clips its overflow and keeps its scrollbar gutter: the root, or `<body>` when `<body>` sets its own overflow and the root's stays `visible`. Pull-to-refresh and the page's bounce stop, because a scroll lock under a modal holds the page (`spec:AST-094` FR19). Closing releases all three. | Current source and tests |
| FR4 | The native cancel request (Escape) is routed through the shared dismissal stack and requests close only when this drawer is topmost. A click on the overlay outside the Drawer requests close; a click inside does not. The Close button, named by `@astryx.mobileNav.closeNavigation`, requests close. A caller `onClick` on the dialog runs before the backdrop check; one that calls `preventDefault()` cancels that backdrop close. | Current source and tests |
-| FR5 | After a close request the drawer slides out while the dialog stays open, and the dialog closes within its slide-out transition and no later than 250 ms after the request (on the next task, never in the commit that requests it, under reduced motion or a zero-length transition). Reopening before then cancels the close. Unmounting closes the dialog. | Current source and tests |
+| FR5 | After a close request the drawer slides out while the dialog stays open, and the dialog closes within its slide-out transition and no later than 250 ms after the request (on the next task, never in the commit that requests it, under reduced motion or a zero-length transition). Reopening before then cancels the close. Unmounting closes the dialog. After the dialog closes, the rest of the slide-out is inert. | Current source and tests |
| FR6 | When the dialog closes, focus returns to the recorded opener if it is still connected and was not the document body; otherwise focus is left alone. A reopen that interrupted a close keeps the original opener. | Current source and tests |
| FR7 | The Drawer enters from its resolved inline edge, from off-screen to on-screen, and the backdrop fades in from transparent, without a reduced-motion preference. Under reduced motion, motion follows `design:reduced-motion` DR1–DR3 (Current-state impact records today's shortfall). The overlay clips the off-screen drawer without becoming a scroll container and allows pinch zoom. | Current source and tests |
| FR8 | `side="start"` or `"end"` sets the edge. `side="auto"` MUST keep the drawer's start and end relationship to the element that opened it (`design:bidirectionality` DR7). Implementation gap: it resolves on each open from the focused element's physical half of the viewport (left half picks `start`, otherwise `end`); when nothing is focused at open it keeps its last value, and before any open it is `end`. | Current source |
@@ -270,6 +271,7 @@ ownership.
| FR2, FR3, FR4 | `MobileNav.test.tsx`; `MobileNavCloseEdgeCases.test.tsx`; `MobileNavScrollbarGutter.test.tsx`; `MobileNavRootScrollClaim.test.tsx` | Escape, backdrop, content click, Close | A wrong close source or a lingering scroll lock fails. | `audit:MobileNav/behavior` |
| FR4 | `layerDismissalFamilies.test.tsx` MobileNav cases | Escape over a required Dialog; cancel while topmost and while not | Closing when not topmost, or not closing when topmost, fails. | `audit:MobileNav/behavior` |
| FR5, ORD3 | `MobileNavCloseVisibility.test.tsx`; `MobileNavCloseEdgeCases.test.tsx`; `MobileNavCloseTiming.test.ts` | Close, reduced motion, reopen, unmount, the 250 ms bound | Closing before the slide-out or a stuck dialog fails. | `audit:MobileNav/behavior` |
+| FR5 | `MobileNavTouchPresentation.a11y.chromium.spec.ts` (the slide-out after the close) | Closed dialog, drawer still sliding out; open drawer | A tap on the leaving drawer reaching it, or the browser's accessibility tree exposing the dialog or its links after the close, fails. | `audit:MobileNav/behavior` |
| FR6, AR2 | `MobileNavFocus.test.tsx` | Standalone, AppShell, Escape, removed opener | Focus not returned, or returned too early, fails. | `audit:MobileNav/accessibility` |
| FR7 | `MobileNavEntryAnimation.test.tsx` | Start and end edges | Missing starting style or a scroll-container overlay fails. | `audit:MobileNav/behavior` |
| FR11, AR3 | `MobileNavToggle.test.tsx`; `MobileNavReopen.test.tsx` | Closed, open, reopen | Broken expanded state or id link fails. | `audit:MobileNav/accessibility` |
diff --git a/packages/core/src/Dialog/Dialog.doc.mjs b/packages/core/src/Dialog/Dialog.doc.mjs
index 515489b4c5..76da568936 100644
--- a/packages/core/src/Dialog/Dialog.doc.mjs
+++ b/packages/core/src/Dialog/Dialog.doc.mjs
@@ -69,7 +69,7 @@ export const docs = {
],
},
description:
- 'Modal dialog using the native <dialog> element. Modal and inline content starts with theme body text defaults. Ancestor surface/group membership ends as a whole, including group-owned state. Explicit props and unrelated contexts remain unchanged. Place intentional groups and complete required providers inside the dialog. With reduced motion the dialog never slides or scales in: on a touch screen it fades in, in 200 ms or less, and with a mouse it appears at once.',
+ 'Modal dialog using the native <dialog> element. Modal and inline content starts with theme body text defaults. Ancestor surface/group membership ends as a whole, including group-owned state. Explicit props and unrelated contexts remain unchanged. Place intentional groups and complete required providers inside the dialog. With reduced motion the dialog never slides or scales in: on a touch screen it fades in, in 200 ms or less, and with a mouse it appears at once. On a phone or tablet (a coarse primary pointer), a tap or a drag that lands while the dialog is still entering reaches nothing, and the dialog finishes entering; keys and assistive technology stay live, and a mouse or a trackpad still clicks: at once when it was the last pointer used, otherwise once it moves.',
props: [
{
name: 'isOpen',
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index a97d4d56b3..4b896e341b 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -5,7 +5,7 @@
/**
* @file Dialog.tsx
* @input Uses React, DialogHTMLAttributes, ReactNode, container (Layout), DialogContext, layerTextReset,
- * layerStructureReset, modalOutlet, interactionModality, chainEventHandlers
+ * layerStructureReset, modalOutlet, interactionModality, chainEventHandlers, holdEntranceInput
* @output Exports Dialog component, DialogProps, DialogVariant, DialogPurpose types
* @position Core implementation; consumed by index.ts, tested by Dialog.test.tsx
*
@@ -27,6 +27,7 @@
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Dialog/Dialog.doc.mjs (props table, features, implementation notes)
* - /packages/core/src/Dialog/Dialog.test.tsx (tests for new/changed behavior)
+ * - /packages/core/src/Dialog/__tests__/DialogTouchEntrance.interaction.browser.spec.ts (the touch entrance hold)
* - /packages/core/src/Dialog/index.ts (exports if types change)
* - /apps/storybook/stories/Dialog.stories.tsx (storybook stories)
* - /packages/cli/assets/templates/blocks/components/Dialog/ (showcase blocks)
@@ -51,6 +52,7 @@ import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
import {layerClickBoundary} from '../Layer/layerClickBoundary';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
+import {holdEntranceInput} from '../Layer/holdEntranceInput';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {useBackdropPress} from '../Layer/useBackdropPress';
import {useModalOutlet} from '../Layer/modalOutlet';
@@ -642,6 +644,11 @@ export function Dialog({
focusForLastInput(autofocusTarget);
}
}
+ // Under a coarse primary pointer, a tap or a drag during the entrance
+ // reaches nothing. Keys and assistive technology stay live. The hold
+ // ends with the entrance, or with this effect's cleanup on a close or
+ // unmount.
+ return holdEntranceInput(dialog) ?? undefined;
} else {
if (dialog.open) {
dialog.close();
diff --git a/packages/core/src/Dialog/DialogTouchEntrance.test.tsx b/packages/core/src/Dialog/DialogTouchEntrance.test.tsx
new file mode 100644
index 0000000000..398897832e
--- /dev/null
+++ b/packages/core/src/Dialog/DialogTouchEntrance.test.tsx
@@ -0,0 +1,143 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {act, render, screen} from '@testing-library/react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {TOUCH_QUERY} from '../utils/touchQueries';
+import {Dialog} from './Dialog';
+
+/** Ends the entrance every dialog reports (jsdom runs no CSS animation). */
+let finishEntrance: () => void = () => {};
+
+/** The primary pointer: a finger (`coarse`, a touch screen) or a mouse. */
+function stubPointer(coarse: boolean) {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn((query: string) => ({
+ matches: coarse && query === TOUCH_QUERY,
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ })),
+ );
+}
+
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+ const finished = new Promise<void>(resolve => {
+ finishEntrance = resolve;
+ });
+ Object.defineProperty(Element.prototype, 'getAnimations', {
+ configurable: true,
+ value: () => [
+ {
+ playState: 'running',
+ finished,
+ effect: {getComputedTiming: () => ({endTime: 300})},
+ },
+ ],
+ });
+});
+
+afterEach(() => {
+ delete (Element.prototype as {getAnimations?: unknown}).getAnimations;
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+const noop = () => {};
+
+function TestDialog({
+ isOpen,
+ onAct = noop,
+}: {
+ isOpen: boolean;
+ onAct?: () => void;
+}) {
+ return (
+ <>
+ <button type="button" onClick={onAct}>
+ Outside
+ </button>
+ <Dialog isOpen={isOpen} onOpenChange={() => {}} aria-label="Held">
+ <button type="button" onClick={onAct}>
+ Act
+ </button>
+ </Dialog>
+ </>
+ );
+}
+
+const INIT = {bubbles: true, cancelable: true, composed: true};
+
+/** A press and its click, as a browser sends them for `pointerType`. */
+function tap(element: Element, pointerType: string, pointerId: number) {
+ element.dispatchEvent(
+ new PointerEvent('pointerdown', {...INIT, pointerId, pointerType}),
+ );
+ element.dispatchEvent(
+ new PointerEvent('pointerup', {...INIT, pointerId, pointerType}),
+ );
+ element.dispatchEvent(
+ new PointerEvent('click', {...INIT, pointerType, detail: 1}),
+ );
+}
+
+const button = (name: string) =>
+ screen.getByRole('button', {name, hidden: true});
+
+describe('Dialog entrance (spec:AST-094 FR35)', () => {
+ it("holds a finger's tap on its action while it enters, and lets one through once it has entered", async () => {
+ stubPointer(true);
+ const onAct = vi.fn();
+ render(<TestDialog isOpen onAct={onAct} />);
+
+ tap(button('Act'), 'touch', 1);
+ expect(onAct).not.toHaveBeenCalled();
+
+ await act(async () => {
+ finishEntrance();
+ await Promise.resolve();
+ });
+ tap(button('Act'), 'touch', 2);
+ expect(onAct).toHaveBeenCalledTimes(1);
+ });
+
+ it('lets input through again when it closes mid-entrance', () => {
+ stubPointer(true);
+ const onAct = vi.fn();
+ const view = render(<TestDialog isOpen onAct={onAct} />);
+
+ view.rerender(<TestDialog isOpen={false} onAct={onAct} />);
+ tap(button('Outside'), 'touch', 1);
+ expect(onAct).toHaveBeenCalledTimes(1);
+ });
+
+ it("leaves a mouse's click alone, even where the primary pointer is a finger", () => {
+ stubPointer(true);
+ const onAct = vi.fn();
+ render(<TestDialog isOpen onAct={onAct} />);
+
+ tap(button('Act'), 'mouse', 1);
+ expect(onAct).toHaveBeenCalledTimes(1);
+ });
+
+ it("holds nothing where the primary pointer is a mouse, a finger's tap included (a touchscreen laptop: an implementation gap on FR35's adoption)", () => {
+ stubPointer(false);
+ const onAct = vi.fn();
+ render(<TestDialog isOpen onAct={onAct} />);
+
+ tap(button('Act'), 'touch', 1);
+ expect(onAct).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/core/src/Dialog/__tests__/DialogTouchEntrance.interaction.browser.spec.ts b/packages/core/src/Dialog/__tests__/DialogTouchEntrance.interaction.browser.spec.ts
new file mode 100644
index 0000000000..553dad7d13
--- /dev/null
+++ b/packages/core/src/Dialog/__tests__/DialogTouchEntrance.interaction.browser.spec.ts
@@ -0,0 +1,452 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DialogTouchEntrance.interaction.browser.spec.ts
+ * @input The built Dialog stories "Purpose Info" and "Scrolling Content" and
+ * the AlertDialog story "Delete", real touch input through the interaction
+ * harness in its phone context, and a mouse there and on a fine-pointer
+ * page
+ * @output Browser evidence for spec:AST-094 FR35 on Dialog: under a finger, a
+ * tap or a drag that lands while the dialog is still entering closes
+ * nothing, runs no action, moves no focus and scrolls nothing, and the
+ * dialog finishes entering and stays open; keys stay live and the content
+ * stays in the accessibility tree meanwhile; an alert's entrance holds its
+ * action alike. With a mouse, a click during the entrance acts as before:
+ * on a touch screen the hold decides by each event's pointer, and a press
+ * where the mouse already rests acts once the page last heard a mouse;
+ * under a fine primary pointer nothing is held.
+ * @position Browser proof for Dialog's entrance hold (Dialog.tsx, through the
+ * Layer module's holdEntranceInput); the hold itself is proven in
+ * Layer/__tests__/inputHold.interaction.browser.spec.ts
+ *
+ * Each case slows the entrance to a minute before opening (a machine as busy
+ * as a 3-CPU runner can play a normal one out before a case looks) and holds
+ * it where it is (holdAnimations), so every touch lands while the dialog is
+ * still entering; the slowing then goes, so the exit keeps its own timing,
+ * and finishing the entrance ends it at once.
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ drag,
+ frames,
+ holdAnimations,
+ openStory,
+ releaseAnimations,
+ touchDriver,
+ withStorybook,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+type Point = {x: number; y: number};
+
+const INFO = 'core-dialog--purpose-info';
+const SCROLLING = 'core-dialog--scrolling-content';
+const ALERT = 'core-alertdialog--delete';
+
+/** A point on the backdrop: the top of the viewport, above the dialog. */
+const BACKDROP: Point = {x: 201, y: 6};
+
+async function centerOf(locator: Locator): Promise<Point> {
+ const box = await locator.boundingBox();
+ if (box == null) {
+ throw new Error('the element did not render');
+ }
+ return {
+ x: Math.round(box.x + box.width / 2),
+ y: Math.round(box.y + box.height / 2),
+ };
+}
+
+const openDialogs = (page: Page) => page.locator('dialog[open]');
+
+/** Waits until the open dialog's entrance is running, then holds it there. */
+async function holdEntrance(page: Page): Promise<void> {
+ await page.waitForFunction(
+ () =>
+ document
+ .querySelector('dialog[open]')
+ ?.getAnimations()
+ .some(animation => animation.playState === 'running') ?? false,
+ );
+ const held = await holdAnimations(page, openDialogs(page));
+ // Held: later transitions (an exit, the next open) keep their own timing.
+ await page.evaluate(() =>
+ document.getElementById('__slowEntrance')?.remove(),
+ );
+ expect(held.length, 'the dialog is still entering').toBeGreaterThan(0);
+}
+
+/**
+ * Slows the next entrance to a minute, so the dialog is still entering when a
+ * case holds it however busy the machine is; holdEntrance and
+ * finishEntrance take the slowing away again.
+ */
+async function slowNextEntrance(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const style = document.createElement('style');
+ style.id = '__slowEntrance';
+ style.textContent =
+ 'dialog, dialog *, dialog::backdrop { transition-duration: 60s !important; animation-duration: 60s !important; }';
+ document.head.append(style);
+ });
+}
+
+/** Ends the entrance at once, held or not. */
+async function finishEntrance(page: Page): Promise<void> {
+ await releaseAnimations(page, {finish: true});
+ await openDialogs(page).evaluate(async dialog => {
+ document.getElementById('__slowEntrance')?.remove();
+ // An entrance no case held (opened only to be finished) ends here too.
+ for (const animation of dialog.getAnimations()) {
+ const end = animation.effect?.getComputedTiming().endTime;
+ if (typeof end === 'number' && Number.isFinite(end)) {
+ animation.finish();
+ }
+ }
+ await Promise.all(
+ dialog.getAnimations().map(async animation =>
+ animation.finished.catch((error: unknown) => {
+ // A canceled animation's `finished` rejects with an AbortError:
+ // it ended. Anything else is a failure, and it surfaces.
+ if (!(error instanceof DOMException && error.name === 'AbortError')) {
+ throw error;
+ }
+ }),
+ ),
+ );
+ });
+ await frames(page);
+}
+
+/** Opens the story's dialog with a tap and holds its entrance midway. */
+async function openMidEntrance(
+ page: Page,
+ story: string,
+ opener: string,
+): Promise<TouchDriver> {
+ await openStory(page, storybook(), story);
+ await slowNextEntrance(page);
+ const driver = await touchDriver(page);
+ await driver.tap(await centerOf(page.getByRole('button', {name: opener})));
+ await holdEntrance(page);
+ return driver;
+}
+
+/**
+ * Records every touch the page receives, and whether the browser took one to
+ * pan something (a `pointercancel`): a window capture listener added before
+ * the page's own scripts, so it sees a touch even when the input hold stops
+ * it there. Install it before opening the story.
+ */
+async function installTouchProbe(page: Page): Promise<void> {
+ await page.addInitScript(() => {
+ const seen: string[] = [];
+ (window as unknown as {__touchProbe: string[]}).__touchProbe = seen;
+ for (const type of [
+ 'touchstart',
+ 'touchmove',
+ 'touchend',
+ 'touchcancel',
+ 'pointercancel',
+ ]) {
+ window.addEventListener(type, () => seen.push(type), {
+ capture: true,
+ passive: true,
+ });
+ }
+ });
+}
+
+/** What the probe saw since the last read, emptying it. */
+const takeTouchProbe = async (page: Page) =>
+ page.evaluate(() => {
+ const seen = (window as unknown as {__touchProbe: string[]}).__touchProbe;
+ return seen.splice(0);
+ });
+
+/**
+ * Plays one drag and returns what the page received: its touch events, and
+ * whether the browser took the touch to pan something (a `pointercancel`).
+ * A drag the page never received shows here, so it cannot pass as one that
+ * scrolled nothing.
+ */
+async function playDrag(
+ page: Page,
+ driver: TouchDriver,
+ script: Parameters<TouchDriver['play']>[0],
+): Promise<{received: string[]; panned: boolean}> {
+ await takeTouchProbe(page);
+ await driver.play(script);
+ await frames(page, 4);
+ const seen = await takeTouchProbe(page);
+ return {
+ received: seen.filter(type => type.startsWith('touch')),
+ panned: seen.includes('pointercancel'),
+ };
+}
+
+/** The whole drag reached the page: a touchstart, its moves and its touchend. */
+function expectDelivered(played: {received: string[]}): void {
+ expect(played.received[0], 'the drag reached the page').toBe('touchstart');
+ expect(played.received).toContain('touchmove');
+ expect(played.received.at(-1)).toBe('touchend');
+}
+
+/** What has focus: its tag and accessible name. */
+const focusedElement = async (page: Page) =>
+ page.evaluate(() => {
+ const element = document.activeElement;
+ if (element == null) {
+ return 'none';
+ }
+ const name =
+ element.getAttribute('aria-label') ?? element.textContent?.trim() ?? '';
+ return `${element.tagName.toLowerCase()}:${name.slice(0, 40)}`;
+ });
+
+test.describe('under a finger (spec:AST-094 FR35)', () => {
+ test('a tap on the backdrop while the dialog enters closes nothing, and once it has entered the same tap closes it', async ({
+ page,
+ }) => {
+ const driver = await openMidEntrance(page, INFO, 'Open Info Modal');
+
+ await driver.tap(BACKDROP);
+ await frames(page);
+ await expect(openDialogs(page)).toHaveCount(1);
+
+ await finishEntrance(page);
+ await expect(page.getByRole('dialog', {name: 'Information'})).toBeVisible();
+
+ await driver.tap(BACKDROP);
+ await expect(openDialogs(page)).toHaveCount(0);
+ });
+
+ test('a tap on an action while the dialog enters runs nothing and moves no focus', async ({
+ page,
+ }) => {
+ const driver = await openMidEntrance(page, INFO, 'Open Info Modal');
+ const action = page.getByRole('button', {name: 'Got it'});
+ // Focus starts inside the dialog, where opening it put it.
+ expect(
+ await openDialogs(page).evaluate(dialog =>
+ dialog.contains(document.activeElement),
+ ),
+ ).toBe(true);
+ const focused = await focusedElement(page);
+
+ await driver.tap(await centerOf(action));
+ await frames(page);
+ await expect(openDialogs(page)).toHaveCount(1);
+ expect(await focusedElement(page)).toBe(focused);
+
+ await finishEntrance(page);
+ await expect(openDialogs(page)).toHaveCount(1);
+
+ await driver.tap(await centerOf(action));
+ await expect(openDialogs(page)).toHaveCount(0);
+ });
+
+ test('a drag while the dialog enters scrolls nothing, and once it has entered the same drag scrolls its content', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName === 'webkit',
+ 'needs native scrolling from injected touches (the WebKit driver has none)',
+ );
+ await installTouchProbe(page);
+ const driver = await openMidEntrance(
+ page,
+ SCROLLING,
+ 'Open Scrolling Modal',
+ );
+ // The dialog's own scroller: its content area.
+ const content = await openDialogs(page).evaluateHandle(dialog => {
+ for (const element of dialog.querySelectorAll('*')) {
+ const {overflowY} = getComputedStyle(element);
+ if (
+ (overflowY === 'auto' || overflowY === 'scroll') &&
+ element.scrollHeight > element.clientHeight
+ ) {
+ return element;
+ }
+ }
+ throw new Error('the dialog has no scrolling content');
+ });
+ const box = await content.asElement()?.boundingBox();
+ if (box == null) {
+ throw new Error('the content did not render');
+ }
+ const x = Math.round(box.x + box.width / 2);
+ const up = drag(
+ {x, y: Math.round(box.y + box.height * 0.8)},
+ {x, y: Math.round(box.y + box.height * 0.2)},
+ // A rest before the lift: no fling outlives the pan.
+ {durationMs: 200, restMs: 150},
+ );
+ const scrollTop = async () =>
+ content.evaluate(element => element.scrollTop);
+
+ const held = await playDrag(page, driver, up);
+ expectDelivered(held);
+ expect(held.panned, 'the browser panned nothing').toBe(false);
+ expect(await scrollTop()).toBe(0);
+ await expect(openDialogs(page)).toHaveCount(1);
+
+ await finishEntrance(page);
+ const free = await playDrag(page, driver, up);
+ expectDelivered(free);
+ expect(free.panned, 'the browser took the drag to scroll').toBe(true);
+ expect(await scrollTop()).toBeGreaterThan(0);
+ });
+
+ test("a tap on an alert's action while it enters runs nothing, and once it has entered the same tap runs it", async ({
+ page,
+ }) => {
+ const driver = await openMidEntrance(page, ALERT, 'Delete item');
+ const action = page.getByRole('button', {name: 'Delete', exact: true});
+
+ await driver.tap(await centerOf(action));
+ await frames(page);
+ await expect(openDialogs(page)).toHaveCount(1);
+
+ await finishEntrance(page);
+ await expect(openDialogs(page)).toHaveCount(1);
+
+ await driver.tap(await centerOf(action));
+ await expect(openDialogs(page)).toHaveCount(0);
+ });
+
+ test('keys and assistive technology stay live while the dialog enters', async ({
+ page,
+ }) => {
+ await openMidEntrance(page, INFO, 'Open Info Modal');
+
+ // The content stays in the accessibility tree, action included.
+ const tree = await page
+ .getByRole('dialog', {name: 'Information'})
+ .ariaSnapshot();
+ expect(tree).toContain('button "Got it"');
+
+ // A key acts at once: Escape closes the dialog mid-entrance.
+ await page.keyboard.press('Escape');
+ await expect(openDialogs(page)).toHaveCount(0);
+ });
+});
+
+test.describe('with a mouse on a touch screen', () => {
+ test('a click on the backdrop while the dialog enters closes it, as before: only a finger is held', async ({
+ page,
+ }) => {
+ await openMidEntrance(page, INFO, 'Open Info Modal');
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ 'the primary pointer is a finger',
+ ).toBe(true);
+
+ await page.mouse.click(BACKDROP.x, BACKDROP.y);
+ await expect(openDialogs(page)).toHaveCount(0);
+ });
+
+ test('while the dialog enters, a press where the mouse already rests reaches its action: the page last heard a mouse (spec:AST-094 FR35)', async ({
+ page,
+ }) => {
+ // Under Reduce Motion the dialog only fades in, so its action stays where
+ // the mouse rests.
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ await openStory(page, storybook(), INFO);
+ const opener = page.getByRole('button', {name: 'Open Info Modal'});
+ // A first presentation, which a mouse opens and a key closes, finds where
+ // the action appears.
+ await opener.click();
+ await expect(openDialogs(page)).toHaveCount(1);
+ await finishEntrance(page);
+ const action = await centerOf(page.getByRole('button', {name: 'Got it'}));
+ await page.keyboard.press('Escape');
+ await expect(openDialogs(page)).toHaveCount(0);
+ // The mouse comes to rest where the action appears; a key opens the
+ // dialog again.
+ await page.mouse.move(action.x - 40, action.y);
+ await page.mouse.move(action.x, action.y, {steps: 4});
+ // What each click lands on, heard first, before any hold.
+ await page.evaluate(() => {
+ const clicks: string[] = [];
+ (window as unknown as {__clicks: string[]}).__clicks = clicks;
+ window.addEventListener(
+ 'click',
+ event => {
+ const target = event.target as Element;
+ clicks.push(target.closest('button')?.textContent?.trim() ?? '');
+ },
+ {capture: true},
+ );
+ });
+ await slowNextEntrance(page);
+ await opener.focus();
+ await page.keyboard.press('Enter');
+ await holdEntrance(page);
+
+ const clicks = async () =>
+ page.evaluate(() => (window as unknown as {__clicks: string[]}).__clicks);
+ await expect(openDialogs(page)).toHaveCount(1);
+ await expect(page.getByRole('button', {name: 'Got it'})).toBeVisible();
+ // A press where the mouse already is, with no movement first. The page's
+ // input stream heard the mouse move last, so the hold lets it through,
+ // and it reaches the action (after the key's own click on the opener).
+ await page.mouse.down();
+ await page.mouse.up();
+ await expect.poll(clicks).toEqual(['Open Info Modal', 'Got it']);
+ await expect(openDialogs(page)).toHaveCount(0);
+ });
+});
+
+test.describe('with a mouse', () => {
+ test.use({hasTouch: false, isMobile: false});
+
+ test('a click on the backdrop while the dialog enters closes it, as before', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), INFO);
+ await slowNextEntrance(page);
+ await page.getByRole('button', {name: 'Open Info Modal'}).click();
+ await holdEntrance(page);
+
+ await page.mouse.click(BACKDROP.x, BACKDROP.y);
+ await expect(openDialogs(page)).toHaveCount(0);
+ });
+
+ test('a press where the mouse already rests closes the dialog from its backdrop while it enters: under a fine primary pointer nothing is held (spec:AST-094 FR35, FR24)', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), INFO);
+ // The mouse comes to rest on the backdrop's spot before the dialog
+ // opens, and a key opens it: no move happens during the entrance.
+ await page.mouse.move(BACKDROP.x, BACKDROP.y);
+ await slowNextEntrance(page);
+ await page.getByRole('button', {name: 'Open Info Modal'}).focus();
+ await page.keyboard.press('Enter');
+ await holdEntrance(page);
+ // The dialog is up and painted, still entering ...
+ await expect(openDialogs(page)).toHaveCount(1);
+ expect(
+ (await openDialogs(page).boundingBox())?.height ?? 0,
+ ).toBeGreaterThan(0);
+ // ... and nothing holds it: no shield.
+ await expect(
+ page.locator('dialog[open] > [popover]'),
+ 'no input hold, so no shield',
+ ).toHaveCount(0);
+
+ await page.mouse.down();
+ await page.mouse.up();
+ await expect(openDialogs(page)).toHaveCount(0);
+ });
+});
diff --git a/packages/core/src/Drawer/Drawer.doc.mjs b/packages/core/src/Drawer/Drawer.doc.mjs
index 7b33dd420f..f125546705 100644
--- a/packages/core/src/Drawer/Drawer.doc.mjs
+++ b/packages/core/src/Drawer/Drawer.doc.mjs
@@ -172,7 +172,7 @@ export const docs = {
usage: {
anatomy,
description:
- 'A side panel that floats above page content for inspectors and detail views: the "click a table row, see its details" pattern. Unlike a docked panel it overlays the layout instead of reflowing it. Works on desktop and touch: the width budget applies on desktop and the panel preserves a 56px page reveal below 640px without exceeding the width budget. Escape closes the drawer (unless purpose is required) and focus returns to the element that opened it. Entry/exit slide animation respects prefers-reduced-motion. Stacking contract: sibling drawers stack last-opened on top, Escape closes only the topmost, and closing peels innermost-first; render them as siblings, never nested.\n\nLike Dialog, the drawer is a container: its content area is inset by --spacing-4 (16px) by default, by the padding prop, or by a theme\'s padding on drawer. Compose the header, body, and footer the way Dialog does, with a Layout: DrawerHeader in the header slot (it shows a close button when you pass it onOpenChange, like DialogHeader), the body in LayoutContent, and actions in LayoutFooter. The Layout redistributes the inset to those regions so they line up on one content line, and the header is not inset twice. A lone Section child also escapes the inset. Drawer renders no close button of its own, so give every drawer a visible way to close, especially a non-modal one, which has no scrim to click. Put data-autofocus on the control that should receive focus on open.\n\nChoosing a surface: use Dialog for a centered decision or short form, Drawer for full-height side detail that keeps the page in sight, BottomSheet for block-axis sheets on touch, and a docked panel (a layout column) when content should reflow the page instead of floating over it.\n\nTheming: the panel is the single stable target (astryx-drawer, with data-side reflecting side), and the scrim is the panel\'s native ::backdrop. DrawerHeader exposes astryx-drawer-header targets for its row, slots, and close icon.',
+ 'A side panel that floats above page content for inspectors and detail views: the "click a table row, see its details" pattern. Unlike a docked panel it overlays the layout instead of reflowing it. Works on desktop and touch: the width budget applies on desktop and the panel preserves a 56px page reveal below 640px without exceeding the width budget. Escape closes the drawer (unless purpose is required) and focus returns to the element that opened it. Entry/exit slide animation respects prefers-reduced-motion. On a phone or tablet (a coarse primary pointer), a tap or a drag that lands while the drawer is still sliding in reaches nothing (for a drawer without a scrim, only one on the panel: the page stays live), and the drawer finishes sliding in; keys and assistive technology stay live, and a mouse or a trackpad still clicks: at once when it was the last pointer used, otherwise once it moves. Stacking contract: sibling drawers stack last-opened on top, Escape closes only the topmost, and closing peels innermost-first; render them as siblings, never nested.\n\nLike Dialog, the drawer is a container: its content area is inset by --spacing-4 (16px) by default, by the padding prop, or by a theme\'s padding on drawer. Compose the header, body, and footer the way Dialog does, with a Layout: DrawerHeader in the header slot (it shows a close button when you pass it onOpenChange, like DialogHeader), the body in LayoutContent, and actions in LayoutFooter. The Layout redistributes the inset to those regions so they line up on one content line, and the header is not inset twice. A lone Section child also escapes the inset. Drawer renders no close button of its own, so give every drawer a visible way to close, especially a non-modal one, which has no scrim to click. Put data-autofocus on the control that should receive focus on open.\n\nChoosing a surface: use Dialog for a centered decision or short form, Drawer for full-height side detail that keeps the page in sight, BottomSheet for block-axis sheets on touch, and a docked panel (a layout column) when content should reflow the page instead of floating over it.\n\nTheming: the panel is the single stable target (astryx-drawer, with data-side reflecting side), and the scrim is the panel\'s native ::backdrop. DrawerHeader exposes astryx-drawer-header targets for its row, slots, and close icon.',
bestPractices: [
{
guidance: true,
diff --git a/packages/core/src/Drawer/DrawerTouchEntrance.test.tsx b/packages/core/src/Drawer/DrawerTouchEntrance.test.tsx
new file mode 100644
index 0000000000..64a73e18eb
--- /dev/null
+++ b/packages/core/src/Drawer/DrawerTouchEntrance.test.tsx
@@ -0,0 +1,157 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {act, render, screen} from '@testing-library/react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {TOUCH_QUERY} from '../utils/touchQueries';
+import {Drawer} from './Drawer';
+
+/** Ends the slide-in every drawer reports (jsdom runs no CSS transition). */
+let finishEntrance: () => void = () => {};
+
+/** The primary pointer: a finger (`coarse`, a touch screen) or a mouse. */
+function stubPointer(coarse: boolean) {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn((query: string) => ({
+ matches: coarse && query === TOUCH_QUERY,
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ })),
+ );
+}
+
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('open', '');
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('open');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+ const finished = new Promise<void>(resolve => {
+ finishEntrance = resolve;
+ });
+ Object.defineProperty(Element.prototype, 'getAnimations', {
+ configurable: true,
+ value: () => [
+ {
+ playState: 'running',
+ finished,
+ effect: {getComputedTiming: () => ({endTime: 250})},
+ },
+ ],
+ });
+});
+
+afterEach(() => {
+ delete (Element.prototype as {getAnimations?: unknown}).getAnimations;
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+const noop = () => {};
+
+function TestDrawer({
+ isOpen,
+ hasScrim = true,
+ onAct = noop,
+}: {
+ isOpen: boolean;
+ hasScrim?: boolean;
+ onAct?: () => void;
+}) {
+ return (
+ <>
+ <button type="button" onClick={onAct}>
+ Outside
+ </button>
+ <Drawer
+ isOpen={isOpen}
+ onOpenChange={() => {}}
+ label="Held"
+ hasScrim={hasScrim}>
+ <button type="button" onClick={onAct}>
+ Act
+ </button>
+ </Drawer>
+ </>
+ );
+}
+
+const INIT = {bubbles: true, cancelable: true, composed: true};
+
+/** A press and its click, as a browser sends them for `pointerType`. */
+function tap(element: Element, pointerType: string, pointerId: number) {
+ element.dispatchEvent(
+ new PointerEvent('pointerdown', {...INIT, pointerId, pointerType}),
+ );
+ element.dispatchEvent(
+ new PointerEvent('pointerup', {...INIT, pointerId, pointerType}),
+ );
+ element.dispatchEvent(
+ new PointerEvent('click', {...INIT, pointerType, detail: 1}),
+ );
+}
+
+const button = (name: string) =>
+ screen.getByRole('button', {name, hidden: true});
+
+describe('Drawer slide-in (spec:AST-094 FR35)', () => {
+ it("holds a finger's tap while it slides in, and lets one through once the slide-in ends", async () => {
+ stubPointer(true);
+ const onAct = vi.fn();
+ render(<TestDrawer isOpen onAct={onAct} />);
+
+ tap(button('Act'), 'touch', 1);
+ expect(onAct).not.toHaveBeenCalled();
+
+ await act(async () => {
+ finishEntrance();
+ await Promise.resolve();
+ });
+ tap(button('Act'), 'touch', 2);
+ expect(onAct).toHaveBeenCalledTimes(1);
+ });
+
+ it("holds only a non-modal drawer's panel: a finger's tap on the page beside it acts", () => {
+ stubPointer(true);
+ const onAct = vi.fn();
+ render(<TestDrawer isOpen hasScrim={false} onAct={onAct} />);
+
+ tap(button('Act'), 'touch', 1);
+ expect(onAct).not.toHaveBeenCalled();
+ tap(button('Outside'), 'touch', 2);
+ expect(onAct).toHaveBeenCalledTimes(1);
+ });
+
+ it('lets input through again when it closes mid-slide', () => {
+ stubPointer(true);
+ const onAct = vi.fn();
+ const view = render(<TestDrawer isOpen onAct={onAct} />);
+
+ view.rerender(<TestDrawer isOpen={false} onAct={onAct} />);
+ tap(button('Outside'), 'touch', 1);
+ expect(onAct).toHaveBeenCalledTimes(1);
+ });
+
+ it("leaves a mouse's click alone, even where the primary pointer is a finger", () => {
+ stubPointer(true);
+ const onAct = vi.fn();
+ render(<TestDrawer isOpen onAct={onAct} />);
+
+ tap(button('Act'), 'mouse', 1);
+ expect(onAct).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/core/src/Drawer/__tests__/DrawerTouchEntrance.interaction.browser.spec.ts b/packages/core/src/Drawer/__tests__/DrawerTouchEntrance.interaction.browser.spec.ts
new file mode 100644
index 0000000000..56700c27a3
--- /dev/null
+++ b/packages/core/src/Drawer/__tests__/DrawerTouchEntrance.interaction.browser.spec.ts
@@ -0,0 +1,454 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DrawerTouchEntrance.interaction.browser.spec.ts
+ * @input The built Drawer stories "Showcase" (modal, with a scrim) and "Row
+ * Inspector" (non-modal), real touch input through the interaction harness
+ * in its phone context, and a mouse there and on a fine-pointer page
+ * @output Browser evidence for spec:AST-094 FR35 on Drawer: under a finger, a
+ * tap or a drag that lands while the drawer is still sliding in closes
+ * nothing, runs no action, moves no focus and scrolls nothing, and the
+ * drawer finishes sliding in and stays open; around a non-modal drawer only
+ * a tap on the panel is held, and the page stays live; keys stay live and
+ * the content stays in the accessibility tree meanwhile. With a mouse, a
+ * click during the slide-in acts as before: on a touch screen the hold
+ * decides by each event's pointer, and under a fine primary pointer nothing
+ * is held, a press where the mouse already rests included.
+ * @position Browser proof for Drawer's entrance hold (useDrawerDialogPresence,
+ * through the Layer module's holdEntranceInput); the hold itself is proven
+ * in Layer/__tests__/inputHold.interaction.browser.spec.ts
+ *
+ * Each case slows the slide-in to a minute before opening (a machine as busy
+ * as a 3-CPU runner can play a normal one out before a case looks) and holds
+ * it where it is (holdAnimations), so every touch lands while the drawer is
+ * still entering; the slowing then goes, so the exit keeps its own timing,
+ * and finishing the slide-in ends it at once.
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ drag,
+ frames,
+ holdAnimations,
+ openStory,
+ releaseAnimations,
+ seekAnimations,
+ touchDriver,
+ withStorybook,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+type Point = {x: number; y: number};
+
+const MODAL = 'core-drawer--showcase';
+const NON_MODAL = 'core-drawer--row-inspector';
+
+/** A point in the strip the drawer leaves free: the scrim, or the page. */
+const STRIP: Point = {x: 20, y: 357};
+
+const OPEN = 'dialog[open], dialog:popover-open';
+
+async function centerOf(locator: Locator): Promise<Point> {
+ const box = await locator.boundingBox();
+ if (box == null) {
+ throw new Error('the element did not render');
+ }
+ return {
+ x: Math.round(box.x + box.width / 2),
+ y: Math.round(box.y + box.height / 2),
+ };
+}
+
+const openDrawers = (page: Page) => page.locator(OPEN);
+
+/** Waits until the open drawer's slide-in is running, then holds it there. */
+async function holdEntrance(page: Page): Promise<void> {
+ await page.waitForFunction(
+ selector =>
+ document
+ .querySelector(selector)
+ ?.getAnimations()
+ .some(animation => animation.playState === 'running') ?? false,
+ OPEN,
+ );
+ const held = await holdAnimations(page, openDrawers(page));
+ // Held: later transitions (an exit, the next open) keep their own timing.
+ await page.evaluate(() =>
+ document.getElementById('__slowEntrance')?.remove(),
+ );
+ expect(held.length, 'the drawer is still sliding in').toBeGreaterThan(0);
+}
+
+/**
+ * Moves the held slide-in to 30 ms before its end: the panel is nearly in
+ * place, so a control inside it is on screen, and the drawer is still
+ * entering.
+ */
+async function seekNearEnd(page: Page): Promise<void> {
+ const endMs = await openDrawers(page).evaluate(drawer =>
+ Math.max(
+ ...drawer
+ .getAnimations()
+ .map(animation =>
+ Number(animation.effect?.getComputedTiming().endTime ?? 0),
+ ),
+ ),
+ );
+ await seekAnimations(page, endMs - 30);
+}
+
+/**
+ * Slows the next entrance to a minute, so the drawer is still entering when a
+ * case holds it however busy the machine is; holdEntrance and
+ * finishEntrance take the slowing away again.
+ */
+async function slowNextEntrance(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const style = document.createElement('style');
+ style.id = '__slowEntrance';
+ style.textContent =
+ 'dialog, dialog *, dialog::backdrop { transition-duration: 60s !important; animation-duration: 60s !important; }';
+ document.head.append(style);
+ });
+}
+
+/** Ends the slide-in at once, held or not. */
+async function finishEntrance(page: Page): Promise<void> {
+ await releaseAnimations(page, {finish: true});
+ await openDrawers(page).evaluate(async drawer => {
+ document.getElementById('__slowEntrance')?.remove();
+ // An entrance no case held (opened only to be finished) ends here too.
+ for (const animation of drawer.getAnimations()) {
+ const end = animation.effect?.getComputedTiming().endTime;
+ if (typeof end === 'number' && Number.isFinite(end)) {
+ animation.finish();
+ }
+ }
+ await Promise.all(
+ drawer.getAnimations().map(async animation =>
+ animation.finished.catch((error: unknown) => {
+ // A canceled animation's `finished` rejects with an AbortError:
+ // it ended. Anything else is a failure, and it surfaces.
+ if (!(error instanceof DOMException && error.name === 'AbortError')) {
+ throw error;
+ }
+ }),
+ ),
+ );
+ });
+ await frames(page);
+}
+
+/** Opens the story's drawer with a tap and holds its slide-in midway. */
+async function openMidEntrance(
+ page: Page,
+ story: string,
+ opener: string,
+): Promise<TouchDriver> {
+ await openStory(page, storybook(), story);
+ await slowNextEntrance(page);
+ const driver = await touchDriver(page);
+ await driver.tap(await centerOf(page.getByRole('button', {name: opener})));
+ await holdEntrance(page);
+ return driver;
+}
+
+/**
+ * Records every touch the page receives, and whether the browser took one to
+ * pan something (a `pointercancel`): a window capture listener added before
+ * the page's own scripts, so it sees a touch even when the input hold stops
+ * it there. Install it before opening the story.
+ */
+async function installTouchProbe(page: Page): Promise<void> {
+ await page.addInitScript(() => {
+ const seen: string[] = [];
+ (window as unknown as {__touchProbe: string[]}).__touchProbe = seen;
+ for (const type of [
+ 'touchstart',
+ 'touchmove',
+ 'touchend',
+ 'touchcancel',
+ 'pointercancel',
+ ]) {
+ window.addEventListener(type, () => seen.push(type), {
+ capture: true,
+ passive: true,
+ });
+ }
+ });
+}
+
+/** What the probe saw since the last read, emptying it. */
+const takeTouchProbe = async (page: Page) =>
+ page.evaluate(() => {
+ const seen = (window as unknown as {__touchProbe: string[]}).__touchProbe;
+ return seen.splice(0);
+ });
+
+/**
+ * Plays one drag and returns what the page received: its touch events, and
+ * whether the browser took the touch to pan something (a `pointercancel`).
+ * A drag the page never received shows here, so it cannot pass as one that
+ * scrolled nothing.
+ */
+async function playDrag(
+ page: Page,
+ driver: TouchDriver,
+ script: Parameters<TouchDriver['play']>[0],
+): Promise<{received: string[]; panned: boolean}> {
+ await takeTouchProbe(page);
+ await driver.play(script);
+ await frames(page, 4);
+ const seen = await takeTouchProbe(page);
+ return {
+ received: seen.filter(type => type.startsWith('touch')),
+ panned: seen.includes('pointercancel'),
+ };
+}
+
+/** The whole drag reached the page: a touchstart, its moves and its touchend. */
+function expectDelivered(played: {received: string[]}): void {
+ expect(played.received[0], 'the drag reached the page').toBe('touchstart');
+ expect(played.received).toContain('touchmove');
+ expect(played.received.at(-1)).toBe('touchend');
+}
+
+/** What has focus: its tag and accessible name. */
+const focusedElement = async (page: Page) =>
+ page.evaluate(() => {
+ const element = document.activeElement;
+ if (element == null) {
+ return 'none';
+ }
+ const name =
+ element.getAttribute('aria-label') ?? element.textContent?.trim() ?? '';
+ return `${element.tagName.toLowerCase()}:${name.slice(0, 40)}`;
+ });
+
+test.describe('under a finger (spec:AST-094 FR35)', () => {
+ test('a tap on the scrim while the drawer slides in closes nothing, and once it is in the same tap closes it', async ({
+ page,
+ }) => {
+ const driver = await openMidEntrance(page, MODAL, 'Open inspector');
+
+ await driver.tap(STRIP);
+ await frames(page);
+ await expect(openDrawers(page)).toHaveCount(1);
+
+ await finishEntrance(page);
+ await expect(
+ page.getByRole('dialog', {name: 'Deployment details'}),
+ ).toBeVisible();
+
+ await driver.tap(STRIP);
+ await expect(openDrawers(page)).toHaveCount(0);
+ });
+
+ test('a tap on its close button while the drawer slides in runs nothing and moves no focus', async ({
+ page,
+ }) => {
+ const driver = await openMidEntrance(page, MODAL, 'Open inspector');
+ await seekNearEnd(page);
+ const close = openDrawers(page).getByRole('button', {name: 'Close'});
+ const target = await centerOf(close);
+ expect(target.x, 'the close button is on screen').toBeLessThan(
+ page.viewportSize()?.width ?? 0,
+ );
+ // Focus starts inside the drawer, on its content area.
+ expect(
+ await openDrawers(page).evaluate(drawer =>
+ drawer.contains(document.activeElement),
+ ),
+ ).toBe(true);
+ const focused = await focusedElement(page);
+
+ await driver.tap(target);
+ await frames(page);
+ await expect(openDrawers(page)).toHaveCount(1);
+ expect(await focusedElement(page)).toBe(focused);
+
+ await finishEntrance(page);
+ await expect(openDrawers(page)).toHaveCount(1);
+
+ await driver.tap(await centerOf(close));
+ await expect(openDrawers(page)).toHaveCount(0);
+ });
+
+ test('around a non-modal drawer sliding in the page stays live: a drag scrolls it and a tap reaches it, while a tap on the drawer reaches nothing (spec:AST-094 FR35)', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName === 'webkit',
+ 'needs native scrolling from injected touches (the WebKit driver has none)',
+ );
+ await installTouchProbe(page);
+ await openStory(page, storybook(), NON_MODAL);
+ // A page that scrolls behind the drawer, which leaves it interactive.
+ await page.evaluate(() => {
+ const spacer = document.createElement('div');
+ spacer.style.height = '300vh';
+ document.body.append(spacer);
+ });
+ const driver = await touchDriver(page);
+ const up = drag(
+ {x: STRIP.x, y: 600},
+ {x: STRIP.x, y: 250},
+ // A rest before the lift: no fling outlives the pan.
+ {durationMs: 200, restMs: 150},
+ );
+ // Where the visual viewport is in the document. This story's page is
+ // wider than the phone, so a pan first moves the visual viewport inside
+ // the layout viewport, which `window.scrollY` does not report.
+ const pageTop = async () =>
+ page.evaluate(() => {
+ if (window.visualViewport == null) {
+ throw new Error('the page has no visual viewport');
+ }
+ return window.visualViewport.pageTop;
+ });
+
+ const opener = page.getByRole('button', {name: 'Open drawer'});
+ await opener.evaluate(element => element.scrollIntoView({block: 'center'}));
+ await frames(page, 2);
+ await slowNextEntrance(page);
+ await driver.tap(await centerOf(opener));
+ await holdEntrance(page);
+ // The panel nearly in place, so its close button is on screen.
+ await seekNearEnd(page);
+ // Every click, split by where it landed: on the page or in the drawer.
+ await page.evaluate(() => {
+ const clicks = {page: [] as string[], drawer: [] as string[]};
+ (window as unknown as {__clicks: typeof clicks}).__clicks = clicks;
+ document.addEventListener(
+ 'click',
+ event => {
+ const target = event.target as Element;
+ const inDrawer = target.closest('dialog') != null;
+ (inDrawer ? clicks.drawer : clicks.page).push(
+ target.tagName.toLowerCase(),
+ );
+ },
+ {capture: true},
+ );
+ });
+ const clicks = async () =>
+ page.evaluate(
+ () =>
+ (window as unknown as {__clicks: {page: string[]; drawer: string[]}})
+ .__clicks,
+ );
+
+ // The drawer and its close button are up and painted.
+ await expect(
+ page.getByRole('button', {name: 'Close inspector'}),
+ ).toBeVisible();
+ // A tap on the drawer while it slides in reaches nothing.
+ await driver.tap(
+ await centerOf(page.getByRole('button', {name: 'Close inspector'})),
+ );
+ await frames(page);
+ expect((await clicks()).drawer).toEqual([]);
+ await expect(openDrawers(page)).toHaveCount(1);
+
+ // The page beside it stays live: a drag scrolls it ...
+ const before = await pageTop();
+ const free = await playDrag(page, driver, up);
+ expectDelivered(free);
+ expect(free.panned, 'the browser took the drag to scroll').toBe(true);
+ expect(await pageTop()).toBeGreaterThan(before);
+ // ... and a tap reaches it.
+ await driver.tap(STRIP);
+ await expect.poll(async () => (await clicks()).page.length).toBe(1);
+ await expect(openDrawers(page)).toHaveCount(1);
+ });
+
+ test('keys and assistive technology stay live while the drawer slides in', async ({
+ page,
+ }) => {
+ await openMidEntrance(page, MODAL, 'Open inspector');
+
+ // The content stays in the accessibility tree, close button included.
+ const tree = await page
+ .getByRole('dialog', {name: 'Deployment details'})
+ .ariaSnapshot();
+ expect(tree).toContain('button "Close"');
+
+ // A key acts at once: Escape closes the drawer mid-slide.
+ await page.keyboard.press('Escape');
+ await expect(
+ page.getByRole('dialog', {name: 'Deployment details'}),
+ ).toBeHidden();
+ });
+});
+
+test.describe('with a mouse on a touch screen', () => {
+ test('a click on the scrim while the drawer slides in closes it, as before: only a finger is held', async ({
+ page,
+ }) => {
+ await openMidEntrance(page, MODAL, 'Open inspector');
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ 'the primary pointer is a finger',
+ ).toBe(true);
+
+ await page.mouse.click(STRIP.x, STRIP.y);
+ await expect(
+ page.getByRole('dialog', {name: 'Deployment details'}),
+ ).toBeHidden();
+ });
+});
+
+test.describe('with a mouse', () => {
+ test.use({hasTouch: false, isMobile: false});
+
+ test('a click on the scrim while the drawer slides in closes it, as before', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), MODAL);
+ await slowNextEntrance(page);
+ await page.getByRole('button', {name: 'Open inspector'}).click();
+ await holdEntrance(page);
+
+ await page.mouse.click(STRIP.x, STRIP.y);
+ await expect(
+ page.getByRole('dialog', {name: 'Deployment details'}),
+ ).toBeHidden();
+ });
+
+ test('a press where the mouse already rests closes the drawer from its scrim while it slides in: under a fine primary pointer nothing is held (spec:AST-094 FR35, FR24)', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), MODAL);
+ // The mouse comes to rest on the scrim's spot before the drawer opens,
+ // and a key opens it: no move happens during the slide-in.
+ await page.mouse.move(STRIP.x, STRIP.y);
+ await slowNextEntrance(page);
+ await page.getByRole('button', {name: 'Open inspector'}).focus();
+ await page.keyboard.press('Enter');
+ await holdEntrance(page);
+ // The drawer is up and painted, still sliding in ...
+ await expect(openDrawers(page)).toHaveCount(1);
+ expect((await openDrawers(page).boundingBox())?.width ?? 0).toBeGreaterThan(
+ 0,
+ );
+ // ... and nothing holds it: no shield.
+ await expect(
+ page.locator('dialog[open] > [popover]'),
+ 'no input hold, so no shield',
+ ).toHaveCount(0);
+
+ await page.mouse.down();
+ await page.mouse.up();
+ await expect(
+ page.getByRole('dialog', {name: 'Deployment details'}),
+ ).toBeHidden();
+ });
+});
diff --git a/packages/core/src/Drawer/useDrawerDialogPresence.ts b/packages/core/src/Drawer/useDrawerDialogPresence.ts
index 7279429c89..43f0e435f1 100644
--- a/packages/core/src/Drawer/useDrawerDialogPresence.ts
+++ b/packages/core/src/Drawer/useDrawerDialogPresence.ts
@@ -5,7 +5,7 @@
/**
* @file useDrawerDialogPresence.ts
* @input Controlled open state, modal mode, dialog ref, and rendered-state setter
- * @output Coordinates native top-layer presence, exit timing, focus restoration, and unmount cleanup
+ * @output Coordinates native top-layer presence, the touch entrance's input hold, exit timing, focus restoration, and unmount cleanup
* @position Drawer-internal hook; consumed only by Drawer.tsx
*
* The drawer has two independent notions of presence:
@@ -21,6 +21,7 @@
*
* SYNC: When modified, update:
* - /packages/core/src/Drawer/Drawer.test.tsx
+ * - /packages/core/src/Drawer/__tests__/DrawerTouchEntrance.interaction.browser.spec.ts
* - /.github/scripts/modal-close-visibility.js
*/
@@ -32,6 +33,7 @@ import {
type SetStateAction,
} from 'react';
import {flushSync} from 'react-dom';
+import {holdEntranceInput} from '../Layer/holdEntranceInput';
import {notifyTopLayerEntry} from '../Layer/modalOutlet';
import {runPopoverOperation} from '../Layer/popoverOperations';
@@ -149,7 +151,12 @@ export function useDrawerDialogPresence({
// contract as Dialog).
dialog.querySelector<HTMLElement>('[data-autofocus]')?.focus();
}
- return;
+ // Under a coarse primary pointer, a tap or a drag during the slide-in
+ // reaches nothing. A non-modal drawer holds only its panel, so its page
+ // stays live. Keys and assistive technology stay live. The hold ends
+ // with the slide-in, or with this effect's cleanup on a close or
+ // unmount.
+ return holdEntranceInput(dialog, {isModal}) ?? undefined;
}
if (!isDrawerHostOpen(dialog, isModal)) {
diff --git a/packages/core/src/Layer/__tests__/inputHold.fixture.ts b/packages/core/src/Layer/__tests__/inputHold.fixture.ts
new file mode 100644
index 0000000000..84cfc1b93f
--- /dev/null
+++ b/packages/core/src/Layer/__tests__/inputHold.fixture.ts
@@ -0,0 +1,137 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file inputHold.fixture.ts
+ * @input Nothing: bundled by esbuild and injected into a blank page
+ * @output A page whose whole area is a button (`#under`), a modal dialog
+ * (`#dialog`: text, an action, and a gesture-host tap recognizer on the
+ * dialog itself, an ancestor of the hold's shield), a light-dismissing
+ * popover (`#pop`) and a full-viewport layer (`#lift`) whose content and
+ * tint take the hits while a test may make its root take none, plus
+ * `window.__hold`: open a layer, hold and
+ * release it, read what an element at a point is and what lies past a
+ * hold's shield there, and a log of every
+ * click, tap recognition and popover toggle
+ * @position Browser fixture of inputHold.interaction.browser.spec.ts;
+ * test-only
+ */
+
+import {getGestureHost} from '../../gestures/GestureHost';
+import {TapGestureRecognizer} from '../../gestures/TapGestureRecognizer';
+import {holdInput, isInputShield, type InputHoldScope} from '../inputHold';
+
+type LayerId = 'dialog' | 'pop' | 'lift';
+
+interface HoldLog {
+ clicks: string[];
+ taps: number;
+ toggles: string[];
+}
+
+declare global {
+ interface Window {
+ __hold: {
+ log: HoldLog;
+ open: (id: LayerId) => void;
+ hold: (id: LayerId, scope: InputHoldScope) => void;
+ release: () => void;
+ hitAt: (x: number, y: number) => string;
+ hitPast: (x: number, y: number) => string;
+ };
+ }
+}
+
+document.body.style.margin = '0';
+document.body.innerHTML = `
+ <button id="under" style="position: fixed; inset: 0; width: 100vw; height: 100vh; font: 14px sans-serif">page</button>
+ <dialog id="dialog" style="width: 240px; padding: 16px; font: 14px sans-serif">
+ <p id="message" style="height: 48px; margin: 0 0 16px">Delete this item?</p>
+ <button id="action" style="width: 200px; height: 48px">Delete</button>
+ </dialog>
+ <div id="pop" popover="auto" style="width: 200px; padding: 16px; font: 14px sans-serif">
+ <button id="popAction" style="width: 160px; height: 48px">Copy</button>
+ </div>
+ <div id="lift" style="position: fixed; inset: 0; display: none; font: 14px sans-serif">
+ <div id="tint" style="position: absolute; inset: 0; background: rgba(0, 0, 0, 0.2); pointer-events: auto; visibility: visible"></div>
+ <button id="liftAction" style="position: absolute; top: 120px; left: 40px; width: 160px; height: 48px; pointer-events: auto; visibility: visible">Copy</button>
+ </div>`;
+
+function element(id: string): HTMLElement {
+ const found = document.getElementById(id);
+ if (found == null) {
+ throw new Error(`missing #${id}`);
+ }
+ return found;
+}
+
+const log: HoldLog = {clicks: [], taps: 0, toggles: []};
+
+document.addEventListener(
+ 'click',
+ event => {
+ const target = event.target;
+ if (target instanceof Element) {
+ const button = target.closest('button');
+ if (button != null) {
+ log.clicks.push(button.id);
+ }
+ }
+ },
+ true,
+);
+element('pop').addEventListener('toggle', event => {
+ log.toggles.push(`pop:${event.newState}`);
+});
+
+// A recognizer on the dialog itself sees every touch inside it, the hold's
+// shield included: only the gesture host's touch gate keeps it away.
+const tap = new TapGestureRecognizer({name: 'dialogTap'});
+tap.addTransitionListener((_current, _from, to) => {
+ if (to === 'ended') {
+ log.taps += 1;
+ }
+});
+getGestureHost(document).attach(element('dialog'), tap);
+
+let release: (() => void) | null = null;
+
+window.__hold = {
+ log,
+ open(id) {
+ if (id === 'dialog') {
+ (element('dialog') as HTMLDialogElement).showModal();
+ } else if (id === 'pop') {
+ element('pop').showPopover();
+ } else {
+ element('lift').style.display = 'block';
+ }
+ },
+ hold(id, scope) {
+ release = holdInput(element(id), {
+ until: new Promise(() => {}),
+ scope,
+ });
+ },
+ release() {
+ release?.();
+ release = null;
+ },
+ hitAt(x, y) {
+ return describe(document.elementFromPoint(x, y));
+ },
+ hitPast(x, y) {
+ return describe(
+ document.elementsFromPoint(x, y).find(el => !isInputShield(el)) ?? null,
+ );
+ },
+};
+
+function describe(hit: Element | null): string {
+ if (hit == null) {
+ return 'nothing';
+ }
+ if (isInputShield(hit)) {
+ return `shield:${hit.parentElement?.id ?? ''}`;
+ }
+ return hit.id !== '' ? hit.id : hit.tagName.toLowerCase();
+}
diff --git a/packages/core/src/Layer/__tests__/inputHold.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/inputHold.interaction.browser.spec.ts
new file mode 100644
index 0000000000..cb39c9c83f
--- /dev/null
+++ b/packages/core/src/Layer/__tests__/inputHold.interaction.browser.spec.ts
@@ -0,0 +1,572 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file inputHold.interaction.browser.spec.ts
+ * @input The input-hold fixture bundled with esbuild, a phone-sized
+ * touch screen, and real engine touch input (touchDriver)
+ * @output Browser proof of what the unit tests cannot see: the hold's shield
+ * is the hit target over the whole viewport, above a modal dialog in the
+ * top layer; a tap during a hold reaches no click and no recognizer on the
+ * layer (the gesture host's touch gate) and leaves a light-dismissing
+ * popover open; a mouse the page heard last passes a presentation's hold,
+ * and after a finger a mouse press meets its shield to the press's end; a
+ * layer root that takes no hits itself (pointer-events:
+ * none, or visibility: hidden, its content opting back in) is held all the
+ * same; keys still act during a presentation's input hold; a dismissal's
+ * hold makes the content inert and moves focus out of it, so no key acts
+ * on it either (a focused button that turns inert still takes Enter and
+ * Space in both engines); each release gives input back; a hit test
+ * that skips shields (isInputShield) finds what lies beneath, and
+ * a layer above the held one still wins; a one-finger
+ * pan on the shield scrolls nothing while a pinch on it still zooms the
+ * page (spec:AST-094 FR10, FR18, FR35; Chromium, which pinch-zooms from
+ * injected touches)
+ * @position Browser tests of packages/core/src/Layer/inputHold.ts, run
+ * by the interaction project (`pnpm test:interaction inputHold`)
+ */
+
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {build} from 'esbuild';
+import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
+import {
+ drag,
+ pinch,
+ touchDriver,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+
+type Point = {x: number; y: number};
+type Scope = 'viewport' | 'layer';
+type LayerId = 'dialog' | 'pop' | 'lift';
+
+interface HoldApi {
+ log: {clicks: string[]; taps: number; toggles: string[]};
+ open: (id: LayerId) => void;
+ hold: (id: LayerId, scope: Scope) => void;
+ release: () => void;
+ hitAt: (x: number, y: number) => string;
+ hitPast: (x: number, y: number) => string;
+}
+
+let bundle = '';
+
+/** What the page throws during a case, a listener's included: none is expected. */
+let pageErrors: string[] = [];
+test.beforeEach(({page}) => {
+ pageErrors = [];
+ page.on('pageerror', error => {
+ pageErrors.push(error.message);
+ });
+});
+test.afterEach(() => {
+ expect(pageErrors).toEqual([]);
+});
+
+test.beforeAll(async () => {
+ const result = await build({
+ entryPoints: [
+ path.join(
+ path.dirname(fileURLToPath(import.meta.url)),
+ 'inputHold.fixture.ts',
+ ),
+ ],
+ bundle: true,
+ write: false,
+ format: 'iife',
+ platform: 'browser',
+ target: 'es2022',
+ });
+ bundle = result.outputFiles[0].text;
+});
+
+async function load(page: Page): Promise<TouchDriver> {
+ // A real navigation first: touch emulation exposes the Touch Events API to
+ // documents it creates.
+ await page.goto('about:blank');
+ await page.setContent(
+ '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><body></body>',
+ );
+ await page.addScriptTag({content: bundle});
+ return touchDriver(page);
+}
+
+type HoldWindow = {__hold: HoldApi};
+
+const open = async (page: Page, id: LayerId) =>
+ page.evaluate(layer => {
+ (window as unknown as HoldWindow).__hold.open(layer);
+ }, id);
+const hold = async (page: Page, id: LayerId, scope: Scope) =>
+ page.evaluate(
+ ([layer, how]) => {
+ (window as unknown as HoldWindow).__hold.hold(layer, how);
+ },
+ [id, scope] as const,
+ );
+const release = async (page: Page) =>
+ page.evaluate(() => {
+ (window as unknown as HoldWindow).__hold.release();
+ });
+const hitAt = async (page: Page, point: Point) =>
+ page.evaluate(
+ at => (window as unknown as HoldWindow).__hold.hitAt(at.x, at.y),
+ point,
+ );
+const hitPast = async (page: Page, point: Point) =>
+ page.evaluate(
+ at => (window as unknown as HoldWindow).__hold.hitPast(at.x, at.y),
+ point,
+ );
+const readLog = async (page: Page) =>
+ page.evaluate(() => (window as unknown as HoldWindow).__hold.log);
+
+async function centre(page: Page, id: string): Promise<Point> {
+ const box = await page.locator(`#${id}`).boundingBox();
+ if (box == null) {
+ throw new Error(`#${id} has no box`);
+ }
+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};
+}
+
+// A tap's click (or its recognition) lands within a few frames.
+const settle = async (page: Page) => page.waitForTimeout(250);
+
+test("during a presentation's input hold on a modal dialog, a tap on it or beside it reaches nothing, keys still act, and the release gives touch back", async ({
+ page,
+}) => {
+ const driver = await load(page);
+ await open(page, 'dialog');
+ const action = await centre(page, 'action');
+ const message = await centre(page, 'message');
+ const beside = {x: 12, y: 12};
+ await hold(page, 'dialog', 'viewport');
+ // The shield is what a touch hits, on the dialog and over its backdrop.
+ expect(await hitAt(page, action)).toBe('shield:dialog');
+ expect(await hitAt(page, beside)).toBe('shield:dialog');
+ await driver.tap(action);
+ await driver.tap(message);
+ await settle(page);
+ // No click, and the recognizer on the dialog saw nothing: the gate.
+ expect(await readLog(page)).toEqual({clicks: [], taps: 0, toggles: []});
+ // Keys still act during a presentation's input hold.
+ await page.locator('#action').focus();
+ await page.keyboard.press('Enter');
+ await expect
+ .poll(async () => (await readLog(page)).clicks)
+ .toEqual(['action']);
+ await release(page);
+ expect(await hitAt(page, action)).toBe('action');
+ expect(await hitAt(page, beside)).toBe('dialog');
+ await driver.tap(message);
+ await expect.poll(async () => (await readLog(page)).taps).toBe(1);
+});
+
+test("a mouse on a touch screen keeps today's behavior during a presentation's hold: the dialog's recognizer takes its press, as with no hold, while a finger's tap before it and right after it is held (spec:AST-094 FR35)", async ({
+ page,
+}) => {
+ const driver = await load(page);
+ await open(page, 'dialog');
+ const action = await centre(page, 'action');
+ await hold(page, 'dialog', 'viewport');
+ await driver.tap(action);
+ await settle(page);
+ expect(await readLog(page)).toEqual({clicks: [], taps: 0, toggles: []});
+ // A mouse or a trackpad on the same touch screen moves to the action and
+ // presses it: the shield lets it through and the gesture host's gate
+ // passes it, so the recognizer on the dialog takes it, as with no hold.
+ await page.mouse.move(action.x - 40, action.y);
+ await page.mouse.move(action.x, action.y, {steps: 4});
+ await page.mouse.down();
+ await page.mouse.up();
+ await expect.poll(async () => (await readLog(page)).taps).toBe(1);
+ // A finger right after it is held again.
+ await driver.tap(action);
+ await settle(page);
+ expect(await readLog(page)).toEqual({clicks: [], taps: 1, toggles: []});
+ await release(page);
+ await driver.tap(action);
+ await expect.poll(async () => (await readLog(page)).taps).toBe(2);
+});
+
+test("a mouse clicks a held light-dismissing popover's action, and a click outside dismisses it, as with no hold, while a finger's tap outside between them is held and leaves it open (spec:AST-094 FR35)", async ({
+ page,
+}) => {
+ const driver = await load(page);
+ await open(page, 'pop');
+ const action = await centre(page, 'popAction');
+ const viewport = page.viewportSize();
+ if (viewport == null) {
+ throw new Error('no viewport');
+ }
+ const outside = {x: viewport.width / 2, y: viewport.height - 40};
+ const isOpen = async () =>
+ page.evaluate(() =>
+ document.getElementById('pop')?.matches(':popover-open'),
+ );
+ await hold(page, 'pop', 'viewport');
+ // A mouse moves to the popover's action and clicks it: the click lands.
+ await page.mouse.move(action.x - 40, action.y);
+ await page.mouse.move(action.x, action.y, {steps: 4});
+ await page.mouse.down();
+ await page.mouse.up();
+ await expect
+ .poll(async () => (await readLog(page)).clicks)
+ .toEqual(['popAction']);
+ // A finger's tap outside while the shield lets the mouse through is still
+ // held, and its release stays the hold's, so the browser's light dismiss
+ // leaves the popover open.
+ await page.mouse.move(outside.x, outside.y - 40, {steps: 4});
+ await driver.tap(outside);
+ await settle(page);
+ expect(await isOpen()).toBe(true);
+ expect(await readLog(page)).toEqual({
+ clicks: ['popAction'],
+ taps: 0,
+ toggles: ['pop:open'],
+ });
+ // The mouse moves again and clicks outside: the popover light-dismisses
+ // and the page takes the click, as with no hold.
+ await page.mouse.move(outside.x, outside.y, {steps: 4});
+ await page.mouse.down();
+ await page.mouse.up();
+ await expect
+ .poll(async () => (await readLog(page)).toggles)
+ .toEqual(['pop:open', 'pop:closed']);
+ expect((await readLog(page)).clicks).toEqual(['popAction', 'under']);
+});
+
+/** Records where each `pointerup` and `click` lands: the shield, or an id. */
+async function recordLandings(page: Page): Promise<() => Promise<string[]>> {
+ await page.evaluate(() => {
+ const seen: string[] = [];
+ (window as unknown as {__seen: string[]}).__seen = seen;
+ for (const type of ['pointerup', 'click']) {
+ window.addEventListener(
+ type,
+ event => {
+ const target = event.target as Element;
+ const name =
+ target.hasAttribute('popover') && target.id === ''
+ ? 'shield'
+ : target.id === ''
+ ? target.tagName.toLowerCase()
+ : target.id;
+ seen.push(`${type}:${name}`);
+ },
+ true,
+ );
+ }
+ });
+ return async () =>
+ page.evaluate(() => (window as unknown as {__seen: string[]}).__seen);
+}
+
+test("a mouse the page heard last passes a presentation's hold at once: a press where it rests reaches the dialog's recognizer, as with no hold (spec:AST-094 FR35)", async ({
+ page,
+}) => {
+ await load(page);
+ await open(page, 'dialog');
+ const action = await centre(page, 'action');
+ // The mouse comes to rest over the action before the hold. The gesture
+ // host hears its moves through the page's input stream.
+ await page.mouse.move(action.x - 40, action.y);
+ await page.mouse.move(action.x, action.y, {steps: 4});
+ const landings = await recordLandings(page);
+ await hold(page, 'dialog', 'viewport');
+ await page.mouse.down();
+ await page.mouse.up();
+ await expect.poll(async () => (await readLog(page)).taps).toBe(1);
+ expect(await landings()).toEqual(['pointerup:action', 'click:action']);
+});
+
+test("after a finger, a mouse press made before the mouse moves meets a presentation's shield to its end: its release and click land on the shield and reach nothing, and once the mouse moves its press reaches the dialog's recognizer (spec:AST-094 FR35)", async ({
+ page,
+}) => {
+ const driver = await load(page);
+ await open(page, 'dialog');
+ const action = await centre(page, 'action');
+ const message = await centre(page, 'message');
+ await page.mouse.move(action.x - 40, action.y);
+ await page.mouse.move(action.x, action.y, {steps: 4});
+ // A finger is the page's last pointer: it taps the dialog's text, which
+ // the recognizer on the dialog counts.
+ await driver.tap(message);
+ await expect.poll(async () => (await readLog(page)).taps).toBe(1);
+ const landings = await recordLandings(page);
+ await hold(page, 'dialog', 'viewport');
+ await page.mouse.down();
+ await page.mouse.up();
+ await settle(page);
+ expect(await landings()).toEqual(['pointerup:shield', 'click:shield']);
+ expect(await readLog(page)).toEqual({clicks: [], taps: 1, toggles: []});
+ // The mouse moves: its next press reaches the dialog's recognizer, as with
+ // no hold.
+ await page.mouse.move(action.x + 4, action.y, {steps: 4});
+ await page.mouse.down();
+ await page.mouse.up();
+ await expect.poll(async () => (await readLog(page)).taps).toBe(2);
+});
+
+test('a touch that lands during a hold and lifts after its release reaches nothing to its end: no release, end or click lands anywhere, and the next tap clicks (spec:AST-094 FR35)', async ({
+ page,
+}) => {
+ const driver = await load(page);
+ await open(page, 'pop');
+ const action = await centre(page, 'popAction');
+ await hold(page, 'pop', 'viewport');
+ await page.evaluate(() => {
+ const seen: string[] = [];
+ (window as unknown as {__seen: string[]}).__seen = seen;
+ // Everything of the touch that reaches the document: a held touch never
+ // does, from its start (which proves it landed under the hold) to its
+ // end.
+ for (const type of [
+ 'touchstart',
+ 'touchmove',
+ 'pointerup',
+ 'touchend',
+ 'click',
+ ]) {
+ document.addEventListener(
+ type,
+ event => {
+ const target = event.target as Element;
+ seen.push(
+ `${type}:${target.id === '' ? target.tagName.toLowerCase() : target.id}`,
+ );
+ },
+ true,
+ );
+ }
+ });
+ // A drag that lands during the hold and is still moving when it releases:
+ // the release runs between two of its moves, a third of the way in (the
+ // driver dispatches each step, then runs onEvent, before the next).
+ let released = false;
+ await driver.play(
+ drag(action, {x: action.x, y: action.y + 120}, {durationMs: 760, hz: 60}),
+ {
+ onEvent: async step => {
+ if (!released && step.type === 'touchMove' && step.t >= 250) {
+ released = true;
+ await release(page);
+ }
+ },
+ },
+ );
+ expect(released).toBe(true);
+ await settle(page);
+ expect(
+ await page.evaluate(() => (window as unknown as {__seen: string[]}).__seen),
+ ).toEqual([]);
+ expect(await readLog(page)).toEqual({
+ clicks: [],
+ taps: 0,
+ toggles: ['pop:open'],
+ });
+ // The next tap is the layer's: its click lands.
+ await driver.tap(action);
+ await expect
+ .poll(async () => (await readLog(page)).clicks)
+ .toEqual(['popAction']);
+});
+
+test('while a dismissal holds it, its content is inert, focus and keys leave it, and the shield still takes every tap; the release restores both', async ({
+ page,
+}) => {
+ const driver = await load(page);
+ await open(page, 'dialog');
+ const action = await centre(page, 'action');
+ const message = await centre(page, 'message');
+ // The dialog moved focus to its action when it opened.
+ expect(await page.evaluate(() => document.activeElement?.id ?? null)).toBe(
+ 'action',
+ );
+ await hold(page, 'dialog', 'layer');
+ // A key reaches nothing: the focused action left the inert content.
+ await page.keyboard.press('Enter');
+ await page.keyboard.press('Space');
+ await settle(page);
+ expect((await readLog(page)).clicks).toEqual([]);
+ // An inert subtree is no hit target: the shield, in the dialog, is.
+ expect(await hitAt(page, action)).toBe('shield:dialog');
+ const state = async () =>
+ page.evaluate(() => {
+ const button = document.getElementById('action');
+ button?.focus();
+ return {
+ inert: button?.closest('[inert]') != null,
+ focused: document.activeElement === button,
+ };
+ });
+ expect(await state()).toEqual({inert: true, focused: false});
+ await driver.tap(action);
+ await driver.tap(message);
+ await settle(page);
+ expect(await readLog(page)).toEqual({clicks: [], taps: 0, toggles: []});
+ await release(page);
+ expect(await state()).toEqual({inert: false, focused: true});
+ expect(await hitAt(page, action)).toBe('action');
+ await driver.tap(message);
+ await expect.poll(async () => (await readLog(page)).taps).toBe(1);
+});
+
+test('a light-dismissing popover stays open when a hold takes a tap outside it; after the release the same tap dismisses it', async ({
+ page,
+}) => {
+ const driver = await load(page);
+ await open(page, 'pop');
+ const viewport = page.viewportSize();
+ if (viewport == null) {
+ throw new Error('no viewport');
+ }
+ const outside = {x: viewport.width / 2, y: viewport.height - 40};
+ expect(await hitAt(page, outside)).toBe('under');
+ await hold(page, 'pop', 'viewport');
+ expect(await hitAt(page, outside)).toBe('shield:pop');
+ await driver.tap(outside);
+ await settle(page);
+ expect(
+ await page.evaluate(() =>
+ document.getElementById('pop')?.matches(':popover-open'),
+ ),
+ ).toBe(true);
+ expect(await readLog(page)).toEqual({
+ clicks: [],
+ taps: 0,
+ toggles: ['pop:open'],
+ });
+ await release(page);
+ await driver.tap(outside);
+ await expect
+ .poll(async () => (await readLog(page)).toggles)
+ .toEqual(['pop:open', 'pop:closed']);
+});
+
+test('a hit test that skips shields sees past a hold: under a held modal dialog’s shield, its own action', async ({
+ page,
+}) => {
+ await load(page);
+ await open(page, 'dialog');
+ const action = await centre(page, 'action');
+ await hold(page, 'dialog', 'viewport');
+ // The opening finger's press resolves its row past the shield.
+ expect(await hitAt(page, action)).toBe('shield:dialog');
+ expect(await hitPast(page, action)).toBe('action');
+ await release(page);
+ expect(await hitAt(page, action)).toBe('action');
+});
+
+test('a layer opened above a held one is what that hit test finds, and past the shield the held layer’s content', async ({
+ page,
+}) => {
+ await load(page);
+ await open(page, 'lift');
+ const liftAction = await centre(page, 'liftAction');
+ await hold(page, 'lift', 'viewport');
+ expect(await hitAt(page, liftAction)).toBe('shield:lift');
+ expect(await hitPast(page, liftAction)).toBe('liftAction');
+ await open(page, 'pop');
+ const popAction = await centre(page, 'popAction');
+ expect(await hitAt(page, popAction)).toBe('popAction');
+ expect(await hitPast(page, popAction)).toBe('popAction');
+});
+
+// A full-viewport layer whose root takes no hits itself and lets its tint
+// and content take them (ContextMenu's lift layer is pointer-events: none):
+// the shield, inside that root, must not inherit that.
+for (const rootStyle of ['pointer-events: none', 'visibility: hidden']) {
+ test(`a layer root with ${rootStyle} (its content opting back in) is held all the same: a tap reaches neither the content nor the page`, async ({
+ page,
+ }) => {
+ const driver = await load(page);
+ await page.evaluate(style => {
+ const lift = document.getElementById('lift');
+ if (lift != null) {
+ lift.style.cssText += `; ${style}`;
+ }
+ }, rootStyle);
+ await open(page, 'lift');
+ const action = await centre(page, 'liftAction');
+ const tint = {x: 12, y: 12};
+ // Unheld, the content and the tint take the hits.
+ expect(await hitAt(page, action)).toBe('liftAction');
+ expect(await hitAt(page, tint)).toBe('tint');
+ await hold(page, 'lift', 'layer');
+ expect(await hitAt(page, action)).toBe('shield:lift');
+ expect(await hitAt(page, tint)).toBe('shield:lift');
+ await driver.tap(action);
+ await driver.tap(tint);
+ await settle(page);
+ expect((await readLog(page)).clicks).toEqual([]);
+ await release(page);
+ expect(await hitAt(page, action)).toBe('liftAction');
+ });
+}
+
+// Page zoom stays the browser's while a layer is held (spec:AST-094 FR10,
+// FR18 and FR35; WCAG 1.4.4): the shield starts no pan, but a pinch on it
+// still zooms the page.
+for (const [id, scope] of [
+ ['pop', 'viewport'],
+ ['dialog', 'layer'],
+] as const) {
+ test(`while a ${scope === 'viewport' ? 'presentation' : 'dismissal'} holds ${id === 'pop' ? 'a popover' : 'a modal dialog'}, a one-finger pan scrolls nothing and a pinch still zooms the page; neither reaches the layer or the page`, async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName === 'webkit',
+ 'needs native scrolling and pinch-zoom from injected touches (Mobile Safari on the simulator)',
+ );
+ const driver = await load(page);
+ const viewport = page.viewportSize();
+ if (viewport == null) {
+ throw new Error('no viewport');
+ }
+ const middle = {x: viewport.width / 2, y: viewport.height / 2};
+ const panUp = drag(
+ {x: middle.x, y: middle.y + 150},
+ {x: middle.x, y: middle.y - 150},
+ // A rest before the lift: no fling outlives the pan.
+ {durationMs: 200, restMs: 150},
+ );
+ // A page that scrolls under the layer: unheld, the same pan scrolls it.
+ await page.evaluate(() => {
+ const spacer = document.createElement('div');
+ spacer.style.height = '300vh';
+ document.body.append(spacer);
+ });
+ await driver.play(panUp);
+ await expect
+ .poll(async () => page.evaluate(() => window.scrollY))
+ .toBeGreaterThan(0);
+ await settle(page);
+ await page.evaluate(() => window.scrollTo(0, 0));
+ await settle(page);
+ expect(await page.evaluate(() => window.scrollY)).toBe(0);
+ await open(page, id);
+ await hold(page, id, scope);
+ expect(await hitAt(page, middle)).toBe(`shield:${id}`);
+ await driver.play(panUp);
+ await settle(page);
+ expect(await page.evaluate(() => window.scrollY)).toBe(0);
+ await driver.play(
+ pinch({
+ center: middle,
+ fromDistance: 60,
+ toDistance: 220,
+ durationMs: 200,
+ }),
+ );
+ await expect
+ .poll(async () => page.evaluate(() => window.visualViewport?.scale ?? 1))
+ .toBeGreaterThan(1.2);
+ expect(await readLog(page)).toEqual({
+ clicks: [],
+ taps: 0,
+ toggles: id === 'pop' ? ['pop:open'] : [],
+ });
+ });
+}
diff --git a/packages/core/src/Layer/holdEntranceInput.test.ts b/packages/core/src/Layer/holdEntranceInput.test.ts
new file mode 100644
index 0000000000..036631b33f
--- /dev/null
+++ b/packages/core/src/Layer/holdEntranceInput.test.ts
@@ -0,0 +1,236 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {stubMatchMedia} from '../__tests__/stubMatchMedia';
+import {holdEntranceInput} from './holdEntranceInput';
+import {isInHeldLayer, isInputShield} from './inputHold';
+
+function deferred() {
+ let resolve: () => void = () => {};
+ let reject: (error: unknown) => void = () => {};
+ const promise = new Promise<void>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return {promise, resolve, reject};
+}
+
+/** A fake animation: running, and ending at `endTime` (Infinity: endless). */
+function fakeAnimation(
+ finished: Promise<unknown>,
+ {
+ endTime = 300,
+ playState = 'running',
+ }: {endTime?: number; playState?: AnimationPlayState} = {},
+): Animation {
+ return {
+ playState,
+ finished,
+ effect: {getComputedTiming: () => ({endTime})},
+ } as unknown as Animation;
+}
+
+/** A layer root in the document whose own animations are `animations`. */
+function mountLayer(animations: Animation[]): HTMLElement {
+ const layer = document.createElement('div');
+ layer.append(document.createElement('button'));
+ document.body.append(layer);
+ Object.defineProperty(layer, 'getAnimations', {
+ configurable: true,
+ value: () => animations,
+ });
+ return layer;
+}
+
+const INIT = {bubbles: true, cancelable: true, composed: true};
+
+/** A press and its click on `element`: the events that reached it. */
+function tap(element: Element, pointerType: string, pointerId: number) {
+ const reached: string[] = [];
+ const record = (event: Event) => reached.push(event.type);
+ const types = ['pointerdown', 'pointerup', 'click'];
+ for (const type of types) {
+ element.addEventListener(type, record);
+ }
+ element.dispatchEvent(
+ new PointerEvent('pointerdown', {...INIT, pointerId, pointerType}),
+ );
+ element.dispatchEvent(
+ new PointerEvent('pointerup', {...INIT, pointerId, pointerType}),
+ );
+ element.dispatchEvent(
+ new PointerEvent('click', {...INIT, pointerType, detail: 1}),
+ );
+ for (const type of types) {
+ element.removeEventListener(type, record);
+ }
+ return reached;
+}
+
+/** The holds a case starts, released after it: a hold listens on the window. */
+const releases: (() => void)[] = [];
+
+function hold(layer: Element): (() => void) | null {
+ const release = holdEntranceInput(layer);
+ if (release != null) {
+ releases.push(release);
+ }
+ return release;
+}
+
+const flush = async () => {
+ for (let i = 0; i < 4; i += 1) {
+ await Promise.resolve();
+ }
+};
+
+// A touch presentation: the primary pointer is coarse (spec:AST-094 FR13).
+beforeEach(() => {
+ stubMatchMedia({pointer: 'coarse'});
+});
+
+afterEach(() => {
+ for (const release of releases.splice(0)) {
+ release();
+ }
+ document.body.replaceChildren();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('holdEntranceInput', () => {
+ it('holds the layer until its entrance ends under a coarse primary pointer', async () => {
+ const entrance = deferred();
+ const layer = mountLayer([fakeAnimation(entrance.promise)]);
+
+ expect(hold(layer)).toBeTypeOf('function');
+ expect(isInHeldLayer(layer.firstElementChild)).toBe(true);
+
+ entrance.resolve();
+ await flush();
+ expect(isInHeldLayer(layer.firstElementChild)).toBe(false);
+ });
+
+ it('waits for every animation of the entrance', async () => {
+ const short = deferred();
+ const long = deferred();
+ const layer = mountLayer([
+ fakeAnimation(short.promise, {endTime: 200}),
+ fakeAnimation(long.promise, {endTime: 400}),
+ ]);
+
+ hold(layer);
+ short.resolve();
+ await flush();
+ expect(isInHeldLayer(layer)).toBe(true);
+
+ long.resolve();
+ await flush();
+ expect(isInHeldLayer(layer)).toBe(false);
+ });
+
+ it('ends the hold when the entrance is canceled (a close midway)', async () => {
+ const entrance = deferred();
+ const layer = mountLayer([fakeAnimation(entrance.promise)]);
+
+ hold(layer);
+ entrance.reject(new DOMException('canceled', 'AbortError'));
+ await flush();
+ expect(isInHeldLayer(layer)).toBe(false);
+ });
+
+ it('returns a release that ends the hold early', () => {
+ const layer = mountLayer([fakeAnimation(new Promise(() => {}))]);
+
+ const release = hold(layer);
+ release?.();
+ expect(isInHeldLayer(layer)).toBe(false);
+ });
+
+ it("decides by each event's pointer: a finger's tap is held, a mouse's click passes (spec:AST-094 FR35)", () => {
+ const layer = mountLayer([fakeAnimation(new Promise(() => {}))]);
+ const button = layer.firstElementChild as Element;
+
+ hold(layer);
+ expect(tap(button, 'touch', 1)).toEqual([]);
+ expect(tap(button, 'pen', 2)).toEqual([]);
+ expect(tap(button, 'mouse', 3)).toEqual([
+ 'pointerdown',
+ 'pointerup',
+ 'click',
+ ]);
+ });
+
+ it('holds nothing under a fine primary pointer: a mouse press made before the mouse moves reaches the layer, and no window listener is added (spec:AST-094 FR35, FR24)', () => {
+ stubMatchMedia({pointer: 'fine'});
+ const added = vi.spyOn(window, 'addEventListener');
+ const layer = mountLayer([fakeAnimation(new Promise(() => {}))]);
+ const button = layer.firstElementChild as Element;
+
+ expect(hold(layer)).toBeNull();
+ expect(isInHeldLayer(button)).toBe(false);
+ expect([...layer.children].some(child => isInputShield(child))).toBe(false);
+ expect(added).not.toHaveBeenCalled();
+ expect(tap(button, 'mouse', 4)).toEqual([
+ 'pointerdown',
+ 'pointerup',
+ 'click',
+ ]);
+ });
+
+ it("reads the entrance from another element and holds the layer until that element's entrance ends", async () => {
+ const layer = mountLayer([]);
+ const panel = mountLayer([]);
+ const slide = deferred();
+ Object.defineProperty(panel, 'getAnimations', {
+ configurable: true,
+ value: () => [fakeAnimation(slide.promise)],
+ });
+ const release = holdEntranceInput(layer, {entrance: panel});
+ expect(release).not.toBeNull();
+ releases.push(release as () => void);
+ expect(isInHeldLayer(layer)).toBe(true);
+ expect(isInHeldLayer(panel)).toBe(false);
+
+ slide.resolve();
+ await flush();
+ expect(isInHeldLayer(layer)).toBe(false);
+ });
+
+ it('ends the hold at `capMs` when the entrance runs longer, and not before', async () => {
+ vi.useFakeTimers();
+ try {
+ const layer = mountLayer([fakeAnimation(new Promise(() => {}))]);
+ const release = holdEntranceInput(layer, {capMs: 550});
+ releases.push(release as () => void);
+ vi.advanceTimersByTime(540);
+ await flush();
+ expect(isInHeldLayer(layer)).toBe(true);
+
+ vi.advanceTimersByTime(20);
+ await flush();
+ expect(isInHeldLayer(layer)).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('holds nothing when the entrance element is missing', () => {
+ const layer = mountLayer([fakeAnimation(new Promise(() => {}))]);
+ expect(holdEntranceInput(layer, {entrance: null})).toBeNull();
+ expect(isInHeldLayer(layer)).toBe(false);
+ });
+
+ it('holds nothing when no entrance runs: none, finished, or endless', () => {
+ const never = new Promise(() => {});
+ for (const animations of [
+ [],
+ [fakeAnimation(Promise.resolve(), {playState: 'finished'})],
+ [fakeAnimation(never, {endTime: Infinity})],
+ ]) {
+ const layer = mountLayer(animations);
+ expect(hold(layer)).toBeNull();
+ expect(isInHeldLayer(layer)).toBe(false);
+ }
+ });
+});
diff --git a/packages/core/src/Layer/holdEntranceInput.ts b/packages/core/src/Layer/holdEntranceInput.ts
new file mode 100644
index 0000000000..07128b34d3
--- /dev/null
+++ b/packages/core/src/Layer/holdEntranceInput.ts
@@ -0,0 +1,84 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file holdEntranceInput.ts
+ * @input A layer root whose CSS entrance has just started
+ * @output holdEntranceInput: under a coarse primary pointer, a finger's or a
+ * pen's input held away from the layer until its entrance ends
+ * @position The entrance hold for layers that enter through CSS (Dialog,
+ * Drawer, MobileNav), on the Layer module's input hold (inputHold.ts)
+ *
+ * SYNC: When modified, update holdEntranceInput.test.ts and its callers
+ * (Dialog.tsx, Drawer/useDrawerDialogPresence.ts, MobileNav/MobileNav.tsx).
+ */
+
+import {isCoarsePointer} from '../utils/coarsePointer';
+import {holdInput} from './inputHold';
+
+/** Options for {@link holdEntranceInput}. */
+export interface EntranceHoldOptions {
+ /**
+ * Holds input anywhere while true. While false, only what lands on the layer
+ * is held, and the page stays live.
+ * @default true
+ */
+ isModal?: boolean;
+ /**
+ * The element whose animations are the entrance, when it is not the layer
+ * itself (a drawer inside its dialog).
+ * @default the layer
+ */
+ entrance?: Element | null;
+ /** The longest the hold lasts, ms. An entrance that runs longer ends it. */
+ capMs?: number;
+}
+
+/**
+ * Holds a finger's and a pen's input away from `layer` until its entrance
+ * ends, or at most `capMs`. Returns the release, or `null` when nothing is
+ * held: no entrance runs, or the primary pointer is fine.
+ */
+export function holdEntranceInput(
+ layer: Element,
+ {isModal = true, entrance: animated = layer, capMs}: EntranceHoldOptions = {},
+): (() => void) | null {
+ if (animated == null || typeof animated.getAnimations !== 'function') {
+ return null;
+ }
+ // getAnimations() flushes styles, so it lists an entrance the open has just
+ // started. A theme's duration, a shorter reduced-motion entrance and a
+ // canceled entrance all end the hold when they end.
+ const entrance = animated.getAnimations().filter(isEntrance);
+ if (entrance.length === 0) {
+ return null;
+ }
+ // A touch presentation only, read as the layer opens. A finger on a device
+ // whose primary pointer is fine, such as a touchscreen laptop, is not held.
+ if (!isCoarsePointer(layer.ownerDocument.defaultView)) {
+ return null;
+ }
+ const ended = Promise.all(
+ entrance.map(async animation => animation.finished),
+ );
+ return holdInput(layer, {
+ until: capMs == null ? ended : Promise.race([ended, after(capMs)]),
+ scope: isModal ? 'viewport' : 'surface',
+ });
+}
+
+async function after(ms: number): Promise<void> {
+ await new Promise(resolve => {
+ setTimeout(resolve, ms);
+ });
+}
+
+/** A running animation that ends on its own: an entrance, not a spin. */
+function isEntrance(animation: Animation): boolean {
+ if (animation.playState !== 'running') {
+ return false;
+ }
+ const end = animation.effect?.getComputedTiming().endTime;
+ return typeof end === 'number' && Number.isFinite(end);
+}
diff --git a/packages/core/src/Layer/inputHold.test.tsx b/packages/core/src/Layer/inputHold.test.tsx
new file mode 100644
index 0000000000..14d180b8e2
--- /dev/null
+++ b/packages/core/src/Layer/inputHold.test.tsx
@@ -0,0 +1,699 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ onTestFinished,
+ vi,
+} from 'vitest';
+import {GestureHost} from '../gestures/GestureHost';
+import {subscribeInput} from '../utils/inputStream';
+import {
+ holdInput,
+ holdsTouch,
+ isInHeldLayer,
+ isInputShield,
+ type InputHoldScope,
+} from './inputHold';
+
+function deferred() {
+ let resolve: () => void = () => {};
+ let reject: (error: unknown) => void = () => {};
+ const promise = new Promise<void>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return {promise, resolve, reject};
+}
+
+/** A layer root with a child, in the document. */
+function mountLayer(): {layer: HTMLElement; child: HTMLElement} {
+ const layer = document.createElement('div');
+ const child = document.createElement('button');
+ layer.append(child);
+ document.body.append(layer);
+ return {layer, child};
+}
+
+const flush = async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+};
+
+/**
+ * What a listener throws during a case: jsdom reports it as an `error` event
+ * on the window and goes on dispatching, so a hold whose listener throws
+ * would otherwise pass. None is expected.
+ */
+const listenerErrors: unknown[] = [];
+window.addEventListener('error', event => {
+ listenerErrors.push(event.error);
+});
+
+afterEach(() => {
+ document.body.replaceChildren();
+ vi.restoreAllMocks();
+ expect(listenerErrors.splice(0)).toEqual([]);
+});
+
+describe('holdInput', () => {
+ it('holds a presenting layer with a shield over the viewport until its end settles', async () => {
+ const {layer, child} = mountLayer();
+ const outside = document.createElement('div');
+ document.body.append(outside);
+ const end = deferred();
+ holdInput(layer, {until: end.promise, scope: 'viewport'});
+ const shield = layer.lastElementChild as HTMLElement;
+ expect(shield).not.toBe(child);
+ expect(shield.getAttribute('popover')).toBe('manual');
+ expect(shield.style.position).toBe('fixed');
+ // No pan, and a pinch still zooms the page (spec:AST-094 FR10).
+ expect(shield.style.touchAction).toBe('pinch-zoom');
+ // Its own hit-testing, whatever the layer root's (the browser proof holds
+ // a root that is pointer-events: none).
+ expect(shield.style.pointerEvents).toBe('auto');
+ expect(shield.style.visibility).toBe('visible');
+ expect(isInHeldLayer(child)).toBe(true);
+ expect(isInHeldLayer(shield)).toBe(true);
+ expect(isInHeldLayer(outside)).toBe(false);
+ // Keys and assistive technology stay live while presenting.
+ expect(layer.hasAttribute('inert')).toBe(false);
+ end.resolve();
+ await flush();
+ expect(shield.isConnected).toBe(false);
+ expect(isInHeldLayer(child)).toBe(false);
+ });
+
+ it('swallows a press and a click on the shield before they reach the page, and leaves a touch its start so a pinch can still zoom', () => {
+ const {layer} = mountLayer();
+ holdInput(layer, {until: new Promise(() => {}), scope: 'viewport'});
+ const shield = layer.lastElementChild as HTMLElement;
+ const seen: string[] = [];
+ for (const type of ['pointerdown', 'click', 'touchstart']) {
+ document.addEventListener(type, () => seen.push(type));
+ }
+ const press = new Event('pointerdown', {bubbles: true, cancelable: true});
+ const click = new MouseEvent('click', {bubbles: true, cancelable: true});
+ const touch = new Event('touchstart', {bubbles: true, cancelable: true});
+ // A touch event carries its touch lists.
+ Object.defineProperty(touch, 'changedTouches', {value: [{identifier: 0}]});
+ Object.defineProperty(touch, 'touches', {value: [{identifier: 0}]});
+ shield.dispatchEvent(press);
+ shield.dispatchEvent(click);
+ shield.dispatchEvent(touch);
+ // A touch that starts also ends.
+ const touchEnd = new Event('touchend', {bubbles: true, cancelable: true});
+ Object.defineProperty(touchEnd, 'changedTouches', {
+ value: [{identifier: 0}],
+ });
+ Object.defineProperty(touchEnd, 'touches', {value: []});
+ shield.dispatchEvent(touchEnd);
+ expect(seen).toEqual([]);
+ expect(press.defaultPrevented).toBe(true);
+ expect(click.defaultPrevented).toBe(true);
+ // Cancelling a touch's start would cancel the page's pinch-zoom too.
+ expect(touch.defaultPrevented).toBe(false);
+ });
+
+ it("holds only a non-modal layer's own box with a 'surface' hold: its shield covers the layer, not the viewport (spec:AST-094 FR35)", async () => {
+ const {layer, child} = mountLayer();
+ const outside = document.createElement('div');
+ document.body.append(outside);
+ const end = deferred();
+ holdInput(layer, {until: end.promise, scope: 'surface'});
+ const shield = layer.lastElementChild as HTMLElement;
+ expect(shield).not.toBe(child);
+ // Inside the layer's box, not over the viewport from the top layer.
+ expect(shield.hasAttribute('popover')).toBe(false);
+ expect(shield.style.position).toBe('absolute');
+ expect(shield.style.inset).toBe('0');
+ expect(shield.style.touchAction).toBe('pinch-zoom');
+ expect(shield.style.pointerEvents).toBe('auto');
+ expect(isInputShield(shield)).toBe(true);
+ expect(isInHeldLayer(child)).toBe(true);
+ expect(isInHeldLayer(outside)).toBe(false);
+ expect(layer.hasAttribute('inert')).toBe(false);
+ end.resolve();
+ await flush();
+ expect(shield.isConnected).toBe(false);
+ });
+
+ it("holds a dismissing layer: its content inert, the layer itself live under the shield, each element's inert given back", async () => {
+ const {layer, child} = mountLayer();
+ const already = document.createElement('div');
+ already.setAttribute('inert', '');
+ layer.append(already);
+ child.focus();
+ expect(document.activeElement).toBe(child);
+ const end = deferred();
+ holdInput(layer, {until: end.promise, scope: 'layer'});
+ // Focus leaves the content: a focused element that turns inert would
+ // keep its key activation.
+ expect(document.activeElement).not.toBe(child);
+ const shield = layer.lastElementChild as HTMLElement;
+ expect(shield.getAttribute('popover')).toBe('manual');
+ // The layer stays live so the shield inside it catches every hit: an
+ // inert subtree is no hit target.
+ expect(layer.hasAttribute('inert')).toBe(false);
+ expect(shield.hasAttribute('inert')).toBe(false);
+ expect(child.hasAttribute('inert')).toBe(true);
+ expect(isInHeldLayer(child)).toBe(true);
+ end.reject(new Error('interrupted'));
+ await flush();
+ expect(child.hasAttribute('inert')).toBe(false);
+ expect(already.hasAttribute('inert')).toBe(true);
+ expect(shield.isConnected).toBe(false);
+ expect(isInHeldLayer(child)).toBe(false);
+ });
+
+ it('names a live hold’s shield, and only it, so a hit test can skip it', () => {
+ const {layer, child} = mountLayer();
+ const popover = document.createElement('div');
+ popover.setAttribute('popover', 'manual');
+ document.body.append(popover);
+ const release = holdInput(layer, {
+ until: new Promise(() => {}),
+ scope: 'viewport',
+ });
+ const shield = layer.lastElementChild as HTMLElement;
+ expect(isInputShield(shield)).toBe(true);
+ for (const other of [layer, child, popover, null]) {
+ expect(isInputShield(other)).toBe(false);
+ }
+ release();
+ expect(isInputShield(shield)).toBe(false);
+ });
+
+ it('sees slotted content as held: the flat tree, a slotted node to its slot', () => {
+ const host = document.createElement('div');
+ const slotted = document.createElement('button');
+ host.append(slotted);
+ document.body.append(host);
+ const root = host.attachShadow({mode: 'open'});
+ const layer = document.createElement('div');
+ layer.append(document.createElement('slot'));
+ root.append(layer);
+ expect(isInHeldLayer(slotted)).toBe(false);
+ const release = holdInput(layer, {
+ until: new Promise(() => {}),
+ scope: 'viewport',
+ });
+ expect(isInHeldLayer(slotted)).toBe(true);
+ release();
+ expect(isInHeldLayer(slotted)).toBe(false);
+ });
+
+ it('takes an animator handle, ending with its finished', async () => {
+ const {layer, child} = mountLayer();
+ const end = deferred();
+ holdInput(layer, {until: {finished: end.promise}, scope: 'layer'});
+ expect(isInHeldLayer(child)).toBe(true);
+ end.resolve();
+ await flush();
+ expect(isInHeldLayer(child)).toBe(false);
+ });
+
+ it('stacks holds on one layer, either scope, under one shield: it comes back when the last one ends', () => {
+ const {layer, child} = mountLayer();
+ const first = holdInput(layer, {
+ until: new Promise(() => {}),
+ scope: 'viewport',
+ });
+ const second = holdInput(layer, {
+ until: new Promise(() => {}),
+ scope: 'layer',
+ });
+ expect(layer.querySelectorAll('[popover]')).toHaveLength(1);
+ expect(child.hasAttribute('inert')).toBe(true);
+ first();
+ first();
+ expect(isInHeldLayer(child)).toBe(true);
+ expect(layer.querySelectorAll('[popover]')).toHaveLength(1);
+ second();
+ expect(isInHeldLayer(child)).toBe(false);
+ expect(child.hasAttribute('inert')).toBe(false);
+ expect(layer.querySelectorAll('[popover]')).toHaveLength(0);
+ });
+
+ it('registers nothing with the gesture host: the host asks holdsTouch for each touch', () => {
+ const addTouchGate = vi.spyOn(GestureHost.prototype, 'addTouchGate');
+ const {layer, child} = mountLayer();
+ const releaseLayer = holdInput(layer, {
+ until: new Promise(() => {}),
+ scope: 'layer',
+ });
+ const release = holdInput(layer, {
+ until: new Promise(() => {}),
+ scope: 'viewport',
+ });
+ expect(addTouchGate).not.toHaveBeenCalled();
+ expect(isInHeldLayer(child)).toBe(true);
+ expect(holdsTouch(child)).toBe(true);
+ expect(holdsTouch(document.body)).toBe(false);
+ release();
+ releaseLayer();
+ expect(isInHeldLayer(child)).toBe(false);
+ expect(holdsTouch(child)).toBe(false);
+ });
+});
+
+describe("holdInput decides by each event's pointer (spec:AST-094 FR35)", () => {
+ const INIT = {bubbles: true, cancelable: true, composed: true};
+
+ /** The holds a case starts, released after it: a hold listens on the window. */
+ const releases: (() => void)[] = [];
+ const hold = (layer: Element, scope: InputHoldScope = 'viewport') => {
+ const release = holdInput(layer, {until: new Promise(() => {}), scope});
+ releases.push(release);
+ return release;
+ };
+
+ /** Makes `type` the stream's last pointer, as a page's earlier input does. */
+ function lastPointerWas(type: string) {
+ const stop = subscribeInput(window, 'pointermove', () => {});
+ pointer(document.body, 'pointermove', type);
+ stop();
+ }
+
+ // Each case starts as after a finger: no earlier case's mouse lowers its
+ // shield.
+ beforeEach(() => {
+ lastPointerWas('touch');
+ });
+
+ afterEach(() => {
+ for (const release of releases.splice(0)) {
+ release();
+ }
+ // A new press ends a released hold's click window (the held press's
+ // click can no longer come), so its subscriptions end before the next
+ // case rather than lingering into it.
+ pointer(document.body, 'pointerdown', 'mouse');
+ pointer(document.body, 'pointerup', 'mouse');
+ });
+
+ /** A button that records every event that reaches it. */
+ function recorder(parent: Element = document.body) {
+ const button = document.createElement('button');
+ parent.append(button);
+ const reached: string[] = [];
+ for (const type of [
+ 'pointerdown',
+ 'pointermove',
+ 'pointerup',
+ 'touchstart',
+ 'touchmove',
+ 'touchend',
+ 'mousedown',
+ 'mouseup',
+ 'click',
+ 'contextmenu',
+ ]) {
+ button.addEventListener(type, () => reached.push(type));
+ }
+ return {button, reached};
+ }
+
+ function pointer(
+ element: Element,
+ type: string,
+ pointerType: string,
+ pointerId = 1,
+ buttons = 0,
+ ): Event {
+ const event = new PointerEvent(type, {
+ ...INIT,
+ pointerId,
+ pointerType,
+ buttons,
+ });
+ element.dispatchEvent(event);
+ return event;
+ }
+
+ /** A click as a browser sends it: a pointer event naming its pointer. */
+ function click(element: Element, pointerType: string, detail = 1): Event {
+ const event = new PointerEvent('click', {...INIT, pointerType, detail});
+ element.dispatchEvent(event);
+ return event;
+ }
+
+ /** A compatibility mouse event, or a click sent as a plain mouse event. */
+ function mouse(element: Element, type: string, detail = 1): Event {
+ const event = new MouseEvent(type, {...INIT, detail});
+ element.dispatchEvent(event);
+ return event;
+ }
+
+ function touch(
+ element: Element,
+ type: string,
+ identifiers: number[],
+ down: number = identifiers.length,
+ ): Event {
+ const event = new Event(type, INIT);
+ const list = identifiers.map(identifier => ({identifier, target: element}));
+ Object.defineProperty(event, 'changedTouches', {value: list});
+ Object.defineProperty(event, 'touches', {
+ value: Array.from({length: down}, (_, identifier) => ({identifier})),
+ });
+ element.dispatchEvent(event);
+ return event;
+ }
+
+ /** A finger's or a pen's tap: down, up, then the browser's click. */
+ function tap(element: Element, pointerType: 'touch' | 'pen', pointerId = 1) {
+ pointer(element, 'pointerdown', pointerType, pointerId);
+ pointer(element, 'pointerup', pointerType, pointerId);
+ click(element, pointerType);
+ }
+
+ it("keeps a held press from the input stream's other subscribers, so press feedback and the gesture host never hear it", () => {
+ const {layer} = mountLayer();
+ const heard: string[] = [];
+ // Subscribed before the hold, as press feedback is on a page with a
+ // pressable.
+ const stops = (['pointerdown', 'pointerup'] as const).map(type =>
+ subscribeInput(window, type, event => {
+ heard.push(`${type}:${event.pointerType}`);
+ }),
+ );
+ hold(layer);
+ pointer(document.body, 'pointerdown', 'touch', 7);
+ pointer(document.body, 'pointerup', 'touch', 7);
+ expect(heard).toEqual([]);
+ // A mouse's press is not held: the other subscribers hear it.
+ pointer(document.body, 'pointerdown', 'mouse', 8);
+ pointer(document.body, 'pointerup', 'mouse', 8);
+ expect(heard).toEqual(['pointerdown:mouse', 'pointerup:mouse']);
+ for (const stop of stops) {
+ stop();
+ }
+ });
+ it("holds a finger's press anywhere in the page, with its moves, release and click, whatever the primary pointer", () => {
+ const {layer} = mountLayer();
+ const {button, reached} = recorder();
+ hold(layer);
+ const down = pointer(button, 'pointerdown', 'touch');
+ pointer(button, 'pointermove', 'touch');
+ pointer(button, 'pointerup', 'touch');
+ click(button, 'touch');
+ // Canceled: the browser sends no compatibility mouse events for it, and
+ // no focus move.
+ expect(down.defaultPrevented).toBe(true);
+ expect(reached).toEqual([]);
+ });
+
+ it("holds a finger's press on a layer under a 'surface' hold and leaves one on the page alone, with its moves, release and click (spec:AST-094 FR35)", () => {
+ const {layer} = mountLayer();
+ const onLayer = recorder(layer);
+ const onPage = recorder();
+ hold(layer, 'surface');
+ // On the page: the page stays live.
+ const down = pointer(onPage.button, 'pointerdown', 'touch', 1);
+ pointer(onPage.button, 'pointermove', 'touch', 1);
+ pointer(onPage.button, 'pointerup', 'touch', 1);
+ click(onPage.button, 'touch');
+ expect(down.defaultPrevented).toBe(false);
+ expect(onPage.reached).toEqual([
+ 'pointerdown',
+ 'pointermove',
+ 'pointerup',
+ 'click',
+ ]);
+ const start = touch(onPage.button, 'touchstart', [7]);
+ const move = touch(onPage.button, 'touchmove', [7]);
+ touch(onPage.button, 'touchend', [7], 0);
+ expect(move.defaultPrevented).toBe(false);
+ expect(start.defaultPrevented).toBe(false);
+ expect(onPage.reached.slice(-3)).toEqual([
+ 'touchstart',
+ 'touchmove',
+ 'touchend',
+ ]);
+ expect(holdsTouch(onPage.button)).toBe(false);
+ // On the layer: held, as under a presentation's hold.
+ tap(onLayer.button, 'touch', 2);
+ expect(onLayer.reached).toEqual([]);
+ expect(holdsTouch(onLayer.button)).toBe(true);
+ });
+
+ it("holds a pen's press as a finger's", () => {
+ const {layer} = mountLayer();
+ const {button, reached} = recorder(layer);
+ hold(layer);
+ tap(button, 'pen');
+ expect(reached).toEqual([]);
+ });
+
+ it("leaves a mouse's press and click alone during a presentation, a click sent as a plain mouse event included", () => {
+ const {layer} = mountLayer();
+ const {button, reached} = recorder(layer);
+ hold(layer);
+ const down = pointer(button, 'pointerdown', 'mouse');
+ mouse(button, 'mousedown');
+ pointer(button, 'pointerup', 'mouse');
+ mouse(button, 'mouseup');
+ click(button, 'mouse');
+ mouse(button, 'click');
+ expect(down.defaultPrevented).toBe(false);
+ expect(reached).toEqual([
+ 'pointerdown',
+ 'mousedown',
+ 'pointerup',
+ 'mouseup',
+ 'click',
+ 'click',
+ ]);
+ });
+
+ it("lets a mouse through a presentation's shield once it moves, takes hits again at a finger's press, and keeps a dismissal's shield taking every hit", () => {
+ const {layer} = mountLayer();
+ const {button} = recorder(layer);
+ hold(layer);
+ const shield = layer.lastElementChild as HTMLElement;
+ expect(shield.style.pointerEvents).toBe('auto');
+ // A mouse or a trackpad moving on a touch screen: what it points at is
+ // hit, as with no hold.
+ pointer(document.body, 'pointermove', 'mouse');
+ expect(shield.style.pointerEvents).toBe('none');
+ // A finger: the shield is the hit target again for the next one.
+ pointer(button, 'pointerdown', 'touch', 2);
+ expect(shield.style.pointerEvents).toBe('auto');
+ pointer(button, 'pointerup', 'touch', 2);
+ // A dismissal's content is inert: a mouse would fall through it to the
+ // page, so its shield keeps every hit.
+ hold(layer, 'layer');
+ pointer(document.body, 'pointermove', 'mouse');
+ expect(shield.style.pointerEvents).toBe('auto');
+ });
+
+ it("starts a presentation's shield lowered when the stream last heard a mouse: a press where the mouse rests reaches the layer (spec:AST-094 FR35)", () => {
+ const {layer, child} = mountLayer();
+ const {button, reached} = recorder(layer);
+ // Press feedback hears the page's pointer moves through the stream on any
+ // page with a pressable; the mouse moved last, before the layer opened.
+ const stop = subscribeInput(window, 'pointermove', () => {});
+ pointer(document.body, 'pointermove', 'mouse');
+ stop();
+ hold(layer);
+ const shield = layer.lastElementChild as HTMLElement;
+ expect(isInputShield(shield)).toBe(true);
+ expect(shield.style.pointerEvents).toBe('none');
+ expect(holdsTouch(child)).toBe(false);
+ // A key opened the layer; the resting mouse presses without moving.
+ pointer(button, 'pointerdown', 'mouse', 1, 1);
+ pointer(button, 'pointerup', 'mouse');
+ click(button, 'mouse');
+ expect(reached).toEqual(['pointerdown', 'pointerup', 'click']);
+ // A dismissal's shield still takes every hit.
+ hold(layer, 'layer');
+ expect(shield.style.pointerEvents).toBe('auto');
+ });
+
+ it("starts a presentation's shield up when the stream last heard a finger, or no pointer at all", () => {
+ const {layer, child} = mountLayer();
+ lastPointerWas('touch');
+ hold(layer);
+ const shield = layer.lastElementChild as HTMLElement;
+ expect(shield.style.pointerEvents).toBe('auto');
+ expect(holdsTouch(child)).toBe(true);
+ // Once a mouse moves during the hold, it passes.
+ pointer(document.body, 'pointermove', 'mouse');
+ expect(shield.style.pointerEvents).toBe('none');
+ expect(holdsTouch(child)).toBe(false);
+ });
+
+ it('adds its window listeners only while a layer is held, once per document however many layers are held, and removes every one after the last hold ends (spec:AST-094 FR24)', () => {
+ const added = vi.spyOn(window, 'addEventListener');
+ const removed = vi.spyOn(window, 'removeEventListener');
+ const listening = () => added.mock.calls.length - removed.mock.calls.length;
+ const first = mountLayer().layer;
+ const second = mountLayer().layer;
+ const releaseFirst = hold(first);
+ const once = listening();
+ expect(once).toBeGreaterThan(0);
+ const releaseSecond = hold(second, 'layer');
+ expect(listening()).toBe(once);
+ releaseFirst();
+ expect(listening()).toBe(once);
+ releaseSecond();
+ expect(listening()).toBe(0);
+ });
+
+ it("answers the gesture host's question only while a layer is held, and false after the last hold ends, registering nothing (spec:AST-094 FR24)", () => {
+ const addTouchGate = vi.spyOn(GestureHost.prototype, 'addTouchGate');
+ const {layer, child} = mountLayer();
+ const release = hold(layer);
+ expect(holdsTouch(child)).toBe(true);
+ hold(mountLayer().layer)();
+ expect(holdsTouch(child)).toBe(true);
+ release();
+ expect(holdsTouch(child)).toBe(false);
+ expect(addTouchGate).not.toHaveBeenCalled();
+ });
+
+ it("lets the gesture host's gate pass a mouse during a presentation and hold it during a dismissal", () => {
+ const {layer, child} = mountLayer();
+ hold(layer);
+ // What the gesture host asks the hold for every touch.
+ const isGated = holdsTouch;
+ // Before any pointer: held.
+ expect(isGated(child)).toBe(true);
+ pointer(child, 'pointermove', 'mouse');
+ pointer(child, 'pointerdown', 'mouse');
+ expect(isGated(child)).toBe(false);
+ pointer(child, 'pointerup', 'mouse');
+ pointer(child, 'pointerdown', 'touch', 2);
+ expect(isGated(child)).toBe(true);
+ pointer(child, 'pointerup', 'touch', 2);
+ hold(layer, 'layer');
+ pointer(child, 'pointermove', 'mouse');
+ pointer(child, 'pointerdown', 'mouse');
+ expect(isGated(child)).toBe(true);
+ expect(isGated(document.body)).toBe(false);
+ });
+
+ it("keeps a presentation's shield up for a mouse press that begins on it, to that press's end, and the gate holds what lands on the shield: its release and click are the shield's, not what lies beneath", () => {
+ const {layer, child} = mountLayer();
+ hold(layer);
+ const shield = layer.lastElementChild as HTMLElement;
+ const isGated = holdsTouch;
+ // A mouse that has not moved during the hold presses: the press meets
+ // the shield, which stays up through the press, a drag included.
+ pointer(shield, 'pointerdown', 'mouse', 1, 1);
+ expect(shield.style.pointerEvents).toBe('auto');
+ pointer(shield, 'pointermove', 'mouse', 1, 1);
+ expect(shield.style.pointerEvents).toBe('auto');
+ expect(isGated(shield)).toBe(true);
+ pointer(shield, 'pointerup', 'mouse');
+ // Only a mouse moving with no button down lets it through.
+ pointer(document.body, 'pointermove', 'mouse');
+ expect(shield.style.pointerEvents).toBe('none');
+ expect(isGated(child)).toBe(false);
+ // What lands on a shield is held, a mouse's press included.
+ expect(isGated(shield)).toBe(true);
+ });
+
+ it('swallows a synthetic press that lands past a lowered shield without capturing it: it has no active pointer to capture', () => {
+ // jsdom implements no pointer capture; a browser's setPointerCapture
+ // throws NotFoundError for a pointer that is not active, as a synthetic
+ // press's is not.
+ const setPointerCapture = vi.fn();
+ Object.defineProperty(HTMLElement.prototype, 'setPointerCapture', {
+ configurable: true,
+ value: setPointerCapture,
+ });
+ onTestFinished(() => {
+ Reflect.deleteProperty(HTMLElement.prototype, 'setPointerCapture');
+ });
+ const {layer} = mountLayer();
+ const {button, reached} = recorder();
+ hold(layer);
+ // A moving mouse lowers the shield, so the finger lands past it.
+ pointer(document.body, 'pointermove', 'mouse');
+ const down = pointer(button, 'pointerdown', 'touch');
+ pointer(button, 'pointerup', 'touch');
+ click(button, 'touch');
+ expect(setPointerCapture).not.toHaveBeenCalled();
+ expect(down.defaultPrevented).toBe(true);
+ expect(reached).toEqual([]);
+ });
+
+ it('lets a key or assistive technology click through: it counts no press', () => {
+ const {layer} = mountLayer();
+ const {button, reached} = recorder(layer);
+ hold(layer);
+ pointer(button, 'pointerdown', 'touch');
+ pointer(button, 'pointerup', 'touch');
+ click(button, '', 0);
+ expect(reached).toEqual(['click']);
+ });
+
+ it("never cancels a touch's start, and cancels a move only while one finger is down", () => {
+ const {layer} = mountLayer();
+ const {button, reached} = recorder(layer);
+ hold(layer);
+ expect(touch(button, 'touchstart', [1]).defaultPrevented).toBe(false);
+ expect(touch(button, 'touchmove', [1]).defaultPrevented).toBe(true);
+ // A second finger: a pinch, which still zooms the page.
+ expect(touch(button, 'touchstart', [2], 2).defaultPrevented).toBe(false);
+ expect(touch(button, 'touchmove', [1, 2]).defaultPrevented).toBe(false);
+ touch(button, 'touchend', [1, 2], 0);
+ expect(reached).toEqual([]);
+ });
+
+ it('swallows the compatibility mouse events and the click a browser sends after a held touch', () => {
+ const {layer} = mountLayer();
+ const {button, reached} = recorder(layer);
+ hold(layer);
+ touch(button, 'touchstart', [1]);
+ expect(touch(button, 'touchend', [1], 0).defaultPrevented).toBe(true);
+ mouse(button, 'mousedown');
+ mouse(button, 'mouseup');
+ mouse(button, 'click');
+ expect(reached).toEqual([]);
+ });
+
+ it('follows a press that landed during the hold to its end, past the release, and leaves the next tap alone', () => {
+ const {layer} = mountLayer();
+ const {button, reached} = recorder();
+ const release = hold(layer);
+ pointer(button, 'pointerdown', 'touch');
+ release();
+ pointer(button, 'pointerup', 'touch');
+ click(button, 'touch');
+ expect(reached).toEqual([]);
+ // The next tap is the page's again.
+ tap(button, 'touch', 2);
+ expect(reached).toEqual(['pointerdown', 'pointerup', 'click']);
+ });
+
+ it('lets a touch after the release through when a held touch ended where the window could not hear it, its identifier reused', () => {
+ const {layer} = mountLayer();
+ const {button, reached} = recorder();
+ const release = hold(layer);
+ // A held touch whose end went to its removed target, unheard here.
+ touch(button, 'touchstart', [0]);
+ release();
+ // The next touch reuses its identifier: it is the page's, and so is its
+ // end, which the browser follows with a click.
+ touch(button, 'touchstart', [0]);
+ const end = touch(button, 'touchend', [0], 0);
+ expect(end.defaultPrevented).toBe(false);
+ mouse(button, 'click');
+ expect(reached).toEqual(['touchstart', 'touchend', 'click']);
+ });
+
+ it('holds nothing once its layer has left the document', () => {
+ const {layer} = mountLayer();
+ hold(layer);
+ layer.remove();
+ const {button, reached} = recorder();
+ tap(button, 'touch');
+ expect(reached).toEqual(['pointerdown', 'pointerup', 'click']);
+ });
+});
diff --git a/packages/core/src/Layer/inputHold.ts b/packages/core/src/Layer/inputHold.ts
new file mode 100644
index 0000000000..d00e234a74
--- /dev/null
+++ b/packages/core/src/Layer/inputHold.ts
@@ -0,0 +1,734 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file inputHold.ts
+ * @input A layer root, what ends its hold (a promise or an animator handle),
+ * and the hold's scope
+ * @output holdInput, holdsTouch, isInHeldLayer and isInputShield: input held
+ * away from a layer while it presents or dismisses
+ * @position The Layer module's one input hold, for components whose layer
+ * presents under a finger
+ *
+ * SYNC: When modified, update inputHold.test.tsx,
+ * __tests__/inputHold.interaction.browser.spec.ts and the holdInput callers.
+ */
+
+import {
+ containsAlongFlatTree,
+ deepActiveElement,
+ parentAcrossShadow,
+} from '../utils/flatTree';
+import {getLastPointerType, subscribeInput} from '../utils/inputStream';
+
+/**
+ * What a hold does. `'viewport'` and `'layer'` add one shield over the whole
+ * viewport. `'layer'` also makes the layer's content inert and moves focus
+ * out of it. `'surface'` shields only the layer's own box, and the page
+ * around it stays live.
+ */
+export type InputHoldScope = 'viewport' | 'layer' | 'surface';
+
+/** What ends a hold: a promise, or an animator handle (its `finished`). */
+export type InputHoldEnd =
+ PromiseLike<unknown> | {readonly finished: PromiseLike<unknown>};
+
+export interface InputHoldOptions {
+ /** The hold ends when this settles. */
+ until: InputHoldEnd;
+ /**
+ * `'viewport'` while presenting, `'layer'` while dismissing, `'surface'`
+ * while a non-modal layer presents.
+ */
+ scope: InputHoldScope;
+}
+
+interface HeldLayer {
+ viewport: number;
+ layer: number;
+ surface: number;
+ shield: HTMLElement | null;
+ /** Whether the shield covers the viewport, or only the layer's box. */
+ isShieldFull: boolean;
+ /** The content a dismissal made inert, and whether each was already. */
+ inertContent: Map<Element, boolean> | null;
+}
+
+/** A document while any of its layers is held. */
+interface HeldDocument {
+ /** Its held layers, oldest first. */
+ readonly layers: Set<Element>;
+}
+
+/** A document's press hold, while its window listeners are on. */
+interface PressHold {
+ /** New presses are held again (a layer is held). */
+ hold: () => void;
+ /** No new press is held; held ones are followed to their end. */
+ release: () => void;
+}
+
+const held = new WeakMap<Element, HeldLayer>();
+const heldDocuments = new WeakMap<Document, HeldDocument>();
+const pressHolds = new WeakMap<Document, PressHold>();
+const liveShields = new WeakSet<Node>();
+
+/** Whether the shared input stream last delivered a mouse's pointer event. */
+function isMouseLast(doc: Document | null): boolean {
+ const view = doc?.defaultView;
+ return view != null && getLastPointerType(view) === 'mouse';
+}
+
+/**
+ * Whether `node` is the shield of a live hold. A hit test that must see past
+ * held input takes the first element of `elementsFromPoint` that is not one.
+ */
+export function isInputShield(node: Node | null): boolean {
+ return node != null && liveShields.has(node);
+}
+
+/**
+ * Whether `target` is inside a held layer. It walks the flat tree as the
+ * gesture host does: a slotted node goes to its slot, and a shadow root to
+ * its host.
+ */
+export function isInHeldLayer(target: Node | null): boolean {
+ for (
+ let node: Node | null = target;
+ node != null;
+ node = parentAcrossShadow(node)
+ ) {
+ if (node instanceof Element && held.has(node)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Whether the gesture host holds `target` away for the current pointer. A
+ * dismissing layer holds every pointer. A presenting layer holds every
+ * pointer but a mouse, which keeps today's behavior. The host asks this for
+ * every touch. So this module imports nothing from gestures/, and a
+ * root-entry component can hold its layer without gesture code. With nothing
+ * held, this answers false.
+ */
+export function holdsTouch(target: Node): boolean {
+ const doc = target instanceof Document ? target : target.ownerDocument;
+ // The gesture host asks for every touch: with nothing held, answer at once.
+ if (doc == null || !heldDocuments.has(doc)) {
+ return false;
+ }
+ // What lands on a shield is held, a mouse's press included.
+ if (isInputShield(target)) {
+ return true;
+ }
+ let isHeld = false;
+ for (
+ let node: Node | null = target;
+ node != null;
+ node = parentAcrossShadow(node)
+ ) {
+ const state = node instanceof Element ? held.get(node) : undefined;
+ if (state != null) {
+ if (state.layer > 0) {
+ return true;
+ }
+ isHeld = true;
+ }
+ }
+ return isHeld && !isMouseLast(doc);
+}
+
+/**
+ * Starts holding `layer`. A document's first held layer turns its press hold
+ * on, with one stream subscription per event type, however many layers are
+ * held. The hold subscribes to nothing while nothing is held.
+ */
+function startHolding(layer: Element): void {
+ const doc = layer.ownerDocument;
+ let state = heldDocuments.get(doc);
+ if (state == null) {
+ state = {layers: new Set()};
+ heldDocuments.set(doc, state);
+ }
+ state.layers.add(layer);
+ pressHoldFor(doc)?.hold();
+}
+
+/** Stops holding `layer`; after the document's last one, ends its holding. */
+function stopHolding(layer: Element): void {
+ heldDocuments.get(layer.ownerDocument)?.layers.delete(layer);
+ liveLayers(layer.ownerDocument);
+}
+
+/**
+ * The document's held layers still in it, oldest first. A layer that has
+ * left the document holds nothing more. When none is left, `holdsTouch`
+ * answers false and the press hold takes no new press. Its subscriptions end
+ * once the presses it holds have ended.
+ */
+function liveLayers(doc: Document): Element[] {
+ const state = heldDocuments.get(doc);
+ if (state == null) {
+ return [];
+ }
+ for (const layer of state.layers) {
+ if (!layer.isConnected) {
+ state.layers.delete(layer);
+ }
+ }
+ if (state.layers.size > 0) {
+ return [...state.layers];
+ }
+ heldDocuments.delete(doc);
+ pressHolds.get(doc)?.release();
+ return [];
+}
+
+const SWALLOWED = [
+ 'pointerdown',
+ 'pointerup',
+ 'touchstart',
+ 'touchend',
+ 'mousedown',
+ 'mouseup',
+ 'click',
+ 'contextmenu',
+] as const;
+
+const swallow = (event: Event) => {
+ // A touch's start stays uncancelled: cancelling it would cancel the page's
+ // pinch-zoom too. The shield's `touch-action: pinch-zoom` keeps a finger
+ // from panning. A tap's mouse events and click land on the shield, which
+ // swallows them.
+ if (event.cancelable && event.type !== 'touchstart') {
+ event.preventDefault();
+ }
+ event.stopPropagation();
+};
+
+/**
+ * A transparent cover inside `layer`: of the viewport from the top layer
+ * (`isFull`), or of the layer's own box alone. Because the cover is inside
+ * the layer, a tap on it lands in the layer, and a light-dismissing layer
+ * stays open.
+ */
+function addShield(layer: Element, isFull: boolean): HTMLElement {
+ const shield = layer.ownerDocument.createElement('div');
+ if (isFull) {
+ shield.setAttribute('popover', 'manual');
+ }
+ shield.setAttribute('aria-hidden', 'true');
+ Object.assign(shield.style, {
+ position: isFull ? 'fixed' : 'absolute',
+ inset: '0',
+ width: isFull ? '100vw' : '100%',
+ height: isFull ? '100vh' : '100%',
+ // Above the layer's own content.
+ zIndex: isFull ? 'auto' : '2147483647',
+ maxWidth: 'none',
+ maxHeight: 'none',
+ margin: '0',
+ padding: '0',
+ border: '0',
+ background: 'transparent',
+ overflow: 'hidden',
+ touchAction: 'pinch-zoom',
+ // These two inherited properties decide hit-testing. A layer root can opt
+ // out of hits, as a full-viewport layer does when a backdrop child takes
+ // them. Inherited from such a root, they would let a held tap fall through
+ // to the page.
+ pointerEvents: 'auto',
+ visibility: 'visible',
+ });
+ for (const type of SWALLOWED) {
+ shield.addEventListener(type, swallow, {capture: true, passive: false});
+ }
+ layer.append(shield);
+ liveShields.add(shield);
+ if (isFull && typeof shield.showPopover === 'function') {
+ try {
+ shield.showPopover();
+ } catch {
+ // Not connected, or popovers unsupported: the shield still covers
+ // what it can as a fixed element.
+ }
+ }
+ return shield;
+}
+
+/**
+ * Holds input away from `layer` until `until` settles. Returns the release
+ * (idempotent), for a hold that ends early. Holds on one layer stack, and
+ * the layer comes back when the last one ends. Each event is judged by its
+ * own pointer, never by the primary pointer. So a mouse on a touch screen
+ * keeps its clicks during a presentation.
+ */
+export function holdInput(
+ layer: Element,
+ {until, scope}: InputHoldOptions,
+): () => void {
+ let state = held.get(layer);
+ if (state == null) {
+ state = {
+ viewport: 0,
+ layer: 0,
+ surface: 0,
+ shield: null,
+ isShieldFull: false,
+ inertContent: null,
+ };
+ held.set(layer, state);
+ }
+ startHolding(layer);
+ const isFull = scope !== 'surface';
+ if (state.shield != null && isFull && !state.isShieldFull) {
+ // A surface hold's shield gives way to one over the viewport.
+ liveShields.delete(state.shield);
+ state.shield.remove();
+ state.shield = null;
+ }
+ if (state.shield == null) {
+ state.isShieldFull = isFull || state.viewport + state.layer > 0;
+ state.shield = addShield(layer, state.isShieldFull);
+ // A presentation lets a mouse through from the start when the stream's
+ // last pointer was a mouse. A press where the mouse rests then acts.
+ if (scope !== 'layer' && isMouseLast(layer.ownerDocument)) {
+ state.shield.style.pointerEvents = 'none';
+ }
+ }
+ if (scope === 'viewport') {
+ state.viewport += 1;
+ } else if (scope === 'surface') {
+ state.surface += 1;
+ } else {
+ state.layer += 1;
+ // A dismissal's shield takes every hit, a mouse's included.
+ state.shield.style.pointerEvents = 'auto';
+ if (state.layer === 1) {
+ state.inertContent = makeContentInert(layer, state.shield);
+ }
+ }
+ let isReleased = false;
+ const release = () => {
+ if (isReleased) {
+ return;
+ }
+ isReleased = true;
+ const current = held.get(layer);
+ if (current == null) {
+ return;
+ }
+ if (scope === 'viewport') {
+ current.viewport -= 1;
+ } else if (scope === 'surface') {
+ current.surface -= 1;
+ } else {
+ current.layer -= 1;
+ if (current.layer === 0 && current.inertContent != null) {
+ restoreInert(current.inertContent);
+ current.inertContent = null;
+ }
+ }
+ if (
+ current.viewport === 0 &&
+ current.layer === 0 &&
+ current.surface === 0
+ ) {
+ if (current.shield != null) {
+ liveShields.delete(current.shield);
+ current.shield.remove();
+ }
+ held.delete(layer);
+ stopHolding(layer);
+ }
+ };
+ const end = 'finished' in until ? until.finished : until;
+ void Promise.resolve(end).then(release, release);
+ return release;
+}
+
+const HELD_POINTERS: ReadonlySet<string> = new Set(['touch', 'pen']);
+
+/**
+ * How long after a held press ends its click and compatibility mouse events
+ * still count as its own (WebKit sends them after `touchend`).
+ */
+const CLICK_WINDOW_MS = 800;
+
+/** How long a held press is followed past the hold's end, at most. */
+const STRAY_PRESS_MS = 10_000;
+
+const POINTER_EVENTS = [
+ 'pointerdown',
+ 'pointermove',
+ 'pointerup',
+ 'pointercancel',
+] as const;
+const TOUCH_EVENTS = [
+ 'touchstart',
+ 'touchmove',
+ 'touchend',
+ 'touchcancel',
+] as const;
+const PRESS_EVENTS = [
+ 'mousedown',
+ 'mouseup',
+ 'click',
+ 'auxclick',
+ 'dblclick',
+ 'contextmenu',
+] as const;
+
+/** The document's press hold, turned on if it is off. */
+function pressHoldFor(doc: Document): PressHold | null {
+ let hold = pressHolds.get(doc) ?? null;
+ if (hold == null) {
+ hold = createPressHold(doc);
+ if (hold != null) {
+ pressHolds.set(doc, hold);
+ }
+ }
+ return hold;
+}
+
+/**
+ * Holds each finger or pen press that lands in `doc`'s window while any of
+ * its layers is held. Each press is held to its own end, even past the
+ * hold's end. A moving mouse passes through a presentation's shield. The
+ * hold hears input through the shared input stream, before its other
+ * subscribers, and stops each held event there. So no document or element
+ * listener hears it, and neither does press feedback or the gesture host.
+ * There is one per document. Its subscriptions end once nothing is held and
+ * the held presses and their clicks have ended.
+ */
+function createPressHold(doc: Document): PressHold | null {
+ const view = doc.defaultView;
+ if (view == null) {
+ return null;
+ }
+ /** Whether a new press is held: until the release. */
+ let isHolding = true;
+ let isListening = true;
+ /** The held presses still down, by pointer id and by touch identifier. */
+ const pointers = new Set<number>();
+ const touches = new Set<number>();
+ /** Whose press the next click is: a held one's, or any other's. */
+ let lastPress: 'held' | 'free' | null = null;
+ /** Until when a click with no pointer type is a held press's. */
+ let clickUntil = -Infinity;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ const now = () => view.performance.now();
+ const isPressDown = () => pointers.size > 0 || touches.size > 0;
+
+ const swallow = (event: Event) => {
+ if (event.cancelable) {
+ event.preventDefault();
+ }
+ event.stopImmediatePropagation();
+ };
+
+ /** After the release: stops once the last held press and its click end. */
+ const settle = () => {
+ if (isHolding || !isListening) {
+ return;
+ }
+ if (timer !== undefined) {
+ clearTimeout(timer);
+ }
+ if (isPressDown()) {
+ timer = setTimeout(stop, STRAY_PRESS_MS);
+ return;
+ }
+ const wait = clickUntil - now();
+ if (wait > 0) {
+ timer = setTimeout(stop, wait);
+ } else {
+ stop();
+ }
+ };
+
+ /** Whether a layer is still held (one that left the document is not). */
+ const holdsNewPress = () => {
+ if (isHolding) {
+ liveLayers(doc);
+ }
+ return isHolding;
+ };
+
+ /**
+ * Whether a new press that lands on `target` is held. While a layer is held
+ * over the viewport, a press anywhere is held. While a layer is held only
+ * to its box (a `'surface'` hold), only a press on the layer is held. The
+ * page around it stays live.
+ */
+ const holdsPressAt = (target: EventTarget | null) => {
+ if (!holdsNewPress()) {
+ return false;
+ }
+ for (const layer of liveLayers(doc)) {
+ const state = held.get(layer);
+ if (state == null) {
+ continue;
+ }
+ if (state.viewport > 0 || state.layer > 0) {
+ return true;
+ }
+ if (
+ state.surface > 0 &&
+ target instanceof Node &&
+ containsAlongFlatTree(layer, target)
+ ) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ const pressEnded = () => {
+ clickUntil = now() + CLICK_WINDOW_MS;
+ settle();
+ };
+
+ /** A shield takes hits for a finger or a pen, not for a moving mouse. */
+ const followPointer = (pointerType: string) => {
+ for (const layer of liveLayers(doc)) {
+ const state = held.get(layer);
+ if (state?.shield == null) {
+ continue;
+ }
+ const value =
+ pointerType === 'mouse' && state.layer === 0 ? 'none' : 'auto';
+ if (state.shield.style.pointerEvents !== value) {
+ state.shield.style.pointerEvents = value;
+ }
+ }
+ };
+
+ /**
+ * A held press that landed past the shield, which had let a mouse through,
+ * is captured to the shield. Its release then stays the hold's, and a
+ * light-dismissing layer stays open. A synthetic press has no active
+ * pointer to capture, so `setPointerCapture` throws NotFoundError. Its
+ * events are swallowed all the same.
+ */
+ const captureToShield = (event: PointerEvent) => {
+ if (!event.isTrusted) {
+ return;
+ }
+ const top = liveLayers(doc).at(-1);
+ const shield = top == null ? null : held.get(top)?.shield;
+ if (shield == null || isInputShield(event.target as Node | null)) {
+ return;
+ }
+ shield.setPointerCapture(event.pointerId);
+ };
+
+ const onPointer = (event: Event): boolean => {
+ const {pointerId, pointerType, type} = event as PointerEvent;
+ // A finger or a pen raises the shields. Only a mouse that moves with no
+ // button down lowers them. So a mouse press that began on a shield stays
+ // the shield's to its end. Otherwise its click would go to the two
+ // targets' common ancestor, a dialog that reads it as a backdrop click.
+ const isFollowed = HELD_POINTERS.has(pointerType)
+ ? type === 'pointerdown' || type === 'pointermove'
+ : pointerType === 'mouse' &&
+ type === 'pointermove' &&
+ (event as PointerEvent).buttons === 0;
+ if (isFollowed && holdsNewPress()) {
+ followPointer(pointerType);
+ }
+ if (type === 'pointerdown') {
+ if (!HELD_POINTERS.has(pointerType) || !holdsPressAt(event.target)) {
+ // A mouse's press, or one after the hold: its click is its own, and a
+ // held press with its id ended unheard.
+ pointers.delete(pointerId);
+ lastPress = 'free';
+ clickUntil = -Infinity;
+ settle();
+ return false;
+ }
+ pointers.add(pointerId);
+ lastPress = 'held';
+ captureToShield(event as PointerEvent);
+ } else if (!pointers.has(pointerId)) {
+ return false;
+ }
+ // Canceling the press keeps the browser from sending its compatibility
+ // mouse events, and with them a focus move.
+ swallow(event);
+ if (type === 'pointerup' || type === 'pointercancel') {
+ pointers.delete(pointerId);
+ pressEnded();
+ }
+ return true;
+ };
+
+ const onTouch = (event: Event): boolean => {
+ const {changedTouches, touches: down, type} = event as TouchEvent;
+ const changed = Array.from(changedTouches);
+ if (type === 'touchstart') {
+ // A held touch that the screen no longer has ended unheard. Its target,
+ // the shield, left the document at the release, so its end reached no
+ // listener here.
+ const live = new Set(Array.from(down, touch => touch.identifier));
+ for (const identifier of touches) {
+ if (!live.has(identifier)) {
+ touches.delete(identifier);
+ }
+ }
+ const heldTouches = changed.filter(touch => holdsPressAt(touch.target));
+ if (heldTouches.length === 0) {
+ // A touch after the hold, or one beside a layer held only to its
+ // box, is a new one, whatever its identifier.
+ for (const touch of changed) {
+ touches.delete(touch.identifier);
+ }
+ lastPress = 'free';
+ clickUntil = -Infinity;
+ settle();
+ return false;
+ }
+ for (const touch of heldTouches) {
+ touches.add(touch.identifier);
+ }
+ lastPress = 'held';
+ // Never canceled: canceling a touch's start would cancel the page's
+ // pinch-zoom with it.
+ event.stopImmediatePropagation();
+ return true;
+ }
+ if (!changed.some(touch => touches.has(touch.identifier))) {
+ return false;
+ }
+ if (type === 'touchmove') {
+ event.stopImmediatePropagation();
+ // One finger pans nothing; two still zoom the page.
+ if (down.length === 1 && event.cancelable) {
+ event.preventDefault();
+ }
+ return true;
+ }
+ // A canceled end sends no click and no compatibility mouse events.
+ swallow(event);
+ for (const touch of changed) {
+ touches.delete(touch.identifier);
+ }
+ pressEnded();
+ return true;
+ };
+
+ const onPress = (event: Event): boolean => {
+ // A click a key or assistive technology sends counts no press.
+ if ((event as MouseEvent).detail === 0) {
+ return false;
+ }
+ // A click that names its pointer is judged by that pointer. A
+ // compatibility mouse event, or a click sent as a plain mouse event,
+ // belongs to the last press.
+ const {pointerType} = event as Partial<PointerEvent>;
+ const isHeldPress =
+ lastPress === 'held' &&
+ (pointerType == null ||
+ pointerType === '' ||
+ HELD_POINTERS.has(pointerType));
+ if (isHeldPress && (isPressDown() || now() <= clickUntil)) {
+ swallow(event);
+ return true;
+ }
+ return false;
+ };
+
+ function stop(): void {
+ if (!isListening) {
+ return;
+ }
+ isListening = false;
+ if (pressHolds.get(doc) === pressHold) {
+ pressHolds.delete(doc);
+ }
+ if (timer !== undefined) {
+ clearTimeout(timer);
+ }
+ for (const unsubscribe of unsubscribers.splice(0)) {
+ unsubscribe();
+ }
+ }
+
+ // A touch's start and cancel are never canceled, so their subscriptions
+ // keep the stream passive for them. The hold hears each event first, so a
+ // held one reaches no other subscriber: press feedback and the gesture host
+ // never hear it.
+ const unsubscribers = [
+ ...POINTER_EVENTS.map(type =>
+ subscribeInput(view, type, onPointer, {cancels: true, first: true}),
+ ),
+ ...TOUCH_EVENTS.map(type =>
+ subscribeInput(view, type, onTouch, {
+ cancels: type === 'touchmove' || type === 'touchend',
+ first: true,
+ }),
+ ),
+ ...PRESS_EVENTS.map(type =>
+ subscribeInput(view, type, onPress, {cancels: true, first: true}),
+ ),
+ ];
+
+ const pressHold: PressHold = {
+ hold() {
+ isHolding = true;
+ if (timer !== undefined) {
+ clearTimeout(timer);
+ timer = undefined;
+ }
+ },
+ release() {
+ if (!isHolding) {
+ return;
+ }
+ isHolding = false;
+ settle();
+ },
+ };
+ return pressHold;
+}
+
+/**
+ * Makes the layer's content inert, except the shield, and moves focus out of
+ * it. An element that turns inert while focused keeps its focus and its key
+ * activation. Enter and Space still click such a button until the engine's
+ * focus fixup runs, if it runs. Blurring it leaves focus on the document, as
+ * that fixup does. The layer element itself stays live. An inert subtree is
+ * no hit target, so the shield inside the layer still catches every hit.
+ */
+function makeContentInert(
+ layer: Element,
+ shield: Element,
+): Map<Element, boolean> {
+ const content = new Map<Element, boolean>();
+ for (const child of layer.children) {
+ if (child !== shield) {
+ content.set(child, child.hasAttribute('inert'));
+ child.setAttribute('inert', '');
+ }
+ }
+ const focused = deepActiveElement(layer.ownerDocument);
+ if (
+ focused instanceof HTMLElement &&
+ [...content.keys()].some(child => containsAlongFlatTree(child, focused))
+ ) {
+ focused.blur();
+ }
+ return content;
+}
+
+function restoreInert(content: Map<Element, boolean>): void {
+ for (const [element, wasInert] of content) {
+ if (!wasInert) {
+ element.removeAttribute('inert');
+ }
+ }
+}
diff --git a/packages/core/src/MobileNav/MobileNav.doc.mjs b/packages/core/src/MobileNav/MobileNav.doc.mjs
index b60f705494..b150f2b535 100644
--- a/packages/core/src/MobileNav/MobileNav.doc.mjs
+++ b/packages/core/src/MobileNav/MobileNav.doc.mjs
@@ -98,7 +98,7 @@ export const docs = {
name: 'onOpenChange',
type: '(isOpen: boolean) => void',
description:
- 'Called when the drawer visibility changes (backdrop click, Escape key, or close button). Inside AppShell, this is managed automatically via context.',
+ 'Called when the drawer visibility changes (backdrop click, Escape key, or close button). Inside AppShell, this is managed automatically via context. On a phone or tablet (a coarse primary pointer), the drawer takes no tap or drag while it slides in; keys and assistive technology still act. After a close, focus returns to the element that opened it once its dialog closes.',
},
{
name: 'children',
@@ -203,7 +203,7 @@ export const docsZh = {
name: 'onOpenChange',
type: '(isOpen: boolean) => void',
description:
- '当抽屉可见性变化时调用(点击背景遮罩、按 Escape 键或点击关闭按钮)。',
+ '当抽屉可见性变化时调用(点击背景遮罩、按 Escape 键或点击关闭按钮)。在手机或平板上(主指针为粗指针时),抽屉滑入期间不接受点按或拖动;键盘和辅助技术仍可操作。关闭后,焦点会在对话框关闭时回到打开它的元素。',
required: true,
},
{
@@ -311,7 +311,7 @@ export const docsDense = {
propDescriptions: {
isOpen: 'whether drawer is open',
onOpenChange:
- 'called when drawer visibility changes (backdrop click, Escape, close button)',
+ 'called when drawer visibility changes (backdrop click, Escape, close button); under a coarse primary pointer the drawer takes no tap or drag while it slides in (keys still act)',
children:
'drawer content; typically SideNavSection/SideNavItem or any ReactNode',
header:
diff --git a/packages/core/src/MobileNav/MobileNav.tsx b/packages/core/src/MobileNav/MobileNav.tsx
index a09e28856c..58e3d529af 100644
--- a/packages/core/src/MobileNav/MobileNav.tsx
+++ b/packages/core/src/MobileNav/MobileNav.tsx
@@ -4,7 +4,8 @@
/**
* @file MobileNav.tsx
- * @input Uses React, useEffect, useRef, useCallback, ReactNode, StyleX
+ * @input Uses React, useEffect, useRef, useCallback, ReactNode, StyleX and
+ * the Layer module's entrance hold
* @output Exports MobileNav component and MobileNavProps
* @position Core implementation; consumed by index.ts
*
@@ -38,6 +39,7 @@
* - /packages/core/src/MobileNav/index.ts (exports if types change)
* - /packages/core/src/Layer/useLayerDismissal.ts (dismissal stack)
* - /packages/core/src/hooks/useScrollLock.ts (the page's scroll lock)
+ * - /packages/core/src/MobileNav/MobileNavTouchPresentation.test.tsx (touch)
* - /packages/cli/assets/templates/blocks/components/MobileNav/ (showcase blocks)
*/
@@ -63,6 +65,7 @@ import {Button} from '../Button';
import {Icon} from '../Icon';
import {Heading} from '../Heading/Heading';
import {useAppShellMobile} from '../AppShell/AppShellMobileContext';
+import {holdEntranceInput} from '../Layer/holdEntranceInput';
import {mergeProps, composeEventHandlers} from '../utils';
import {layerTextReset} from '../Layer/layerTextReset.stylex';
import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
@@ -282,6 +285,14 @@ const dynamicStyles = stylex.create({
* own scheduled `dialog.close()` has a chance to run (#5701).
*/
export const MAX_CLOSE_DELAY_MS = 250;
+/**
+ * Longest the drawer slides in or out for, in ms. Both run for the theme's
+ * `--duration-medium`: 410 ms by default, and at most 545 ms on the default
+ * scale (`--duration-medium-max`). The slide-out keeps playing after the
+ * dialog closes, while the dialog's `display` transition keeps it rendered.
+ * The touch hold on the slide-in ends by this time.
+ */
+export const MAX_EXIT_MS = 550;
/** Fraction of the hold to close at, so the close never lands on its boundary. */
const CLOSE_WITHIN_HOLD = 0.6;
@@ -504,7 +515,11 @@ export function MobileNav({
);
const dialogRef = useRef<HTMLDialogElement>(null);
+ const drawerRef = useRef<HTMLDivElement>(null);
const closeTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);
+ // The input hold on the drawer's layer while it slides in under a coarse
+ // primary pointer. It is null under a fine one and once the slide-in ends.
+ const releaseHoldRef = useRef<(() => void) | null>(null);
// Element that was focused when the drawer opened; focus goes back to it
// once the native dialog has closed (see closeAndRestoreFocus).
const triggerElementRef = useRef<HTMLElement | null>(null);
@@ -569,6 +584,8 @@ export function MobileNav({
}
if (isOpen) {
+ releaseHoldRef.current?.();
+ releaseHoldRef.current = null;
if (!dialog.open) {
// Capture the opener before showModal() pulls focus into the top
// layer. Only on the transition into open: a reopen while the delayed
@@ -578,7 +595,16 @@ export function MobileNav({
document.activeElement as HTMLElement | null;
dialog.showModal();
}
+ // Under a coarse primary pointer, nothing takes a touch until the
+ // slide-in ends, at most MAX_EXIT_MS in. A close holds nothing, because
+ // only an entrance is held. Under a fine one, nothing is held.
+ releaseHoldRef.current = holdEntranceInput(dialog, {
+ entrance: drawerRef.current,
+ capMs: MAX_EXIT_MS,
+ });
} else if (dialog.open) {
+ releaseHoldRef.current?.();
+ releaseHoldRef.current = null;
closeTimeoutRef.current = setTimeout(() => {
closeAndRestoreFocus(dialog, triggerElementRef);
setIsCloseHeld(false);
@@ -594,6 +620,10 @@ export function MobileNav({
clearTimeout(closeTimeoutRef.current);
closeTimeoutRef.current = null;
}
+ // The hold this run took ends with it: a reopen, a close or an
+ // unmount mid-slide never leaves input blocked.
+ releaseHoldRef.current?.();
+ releaseHoldRef.current = null;
};
}, [isOpen]);
@@ -613,6 +643,8 @@ export function MobileNav({
useEffect(() => {
const dialog = dialogRef.current;
return () => {
+ releaseHoldRef.current?.();
+ releaseHoldRef.current = null;
if (dialog?.open) {
closeAndRestoreFocus(dialog, triggerElementRef);
}
@@ -704,6 +736,7 @@ export function MobileNav({
<LayerContentBoundary>
{/* Drawer panel — tabIndex so showModal() focuses the drawer, not the close button */}
<div
+ ref={drawerRef}
tabIndex={-1}
{...stylex.props(
styles.drawer,
diff --git a/packages/core/src/MobileNav/MobileNavTouchPresentation.test.tsx b/packages/core/src/MobileNav/MobileNavTouchPresentation.test.tsx
new file mode 100644
index 0000000000..60116f848f
--- /dev/null
+++ b/packages/core/src/MobileNav/MobileNavTouchPresentation.test.tsx
@@ -0,0 +1,268 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file MobileNavTouchPresentation.test.tsx
+ * @input Uses vitest, @testing-library/react, MobileNav and the Layer
+ * module's input hold
+ * @output Tests that under a finger the drawer takes no touch until its
+ * slide-in ends, at most MAX_EXIT_MS in, while keys and assistive
+ * technology stay live; that a close holds nothing and keeps the mouse's
+ * timing; that a drawer with no slide-in holds nothing; and that under a
+ * mouse nothing is held
+ * @position Unit tests for MobileNav's touch presentation
+ *
+ * SYNC: When modified, update the header comment in MobileNav.tsx.
+ */
+
+import {useState} from 'react';
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import {
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+import {stubMatchMedia} from '../__tests__/stubMatchMedia';
+import {isInHeldLayer} from '../Layer/inputHold';
+import {MAX_CLOSE_DELAY_MS, MAX_EXIT_MS, MobileNav} from './MobileNav';
+
+function Harness() {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Open
+ </button>
+ <MobileNav
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ data-testid="mobile-nav">
+ <a href="#home">Home</a>
+ </MobileNav>
+ </>
+ );
+}
+
+// jsdom has no Web Animations, so a case under a finger gives the drawer a
+// slide-in (stubSlideIn) that ends when the case says, or at MAX_EXIT_MS.
+// jsdom resolves no `var()`, so a close lands MAX_CLOSE_DELAY_MS in.
+async function advance(ms: number) {
+ await act(async () => {
+ vi.advanceTimersByTime(ms);
+ });
+}
+
+beforeAll(() => {
+ // jsdom has no showModal/close: model the dialog focusing steps
+ // (showModal() moves focus into the dialog; close() restores nothing).
+ HTMLDialogElement.prototype.showModal = function (this: HTMLDialogElement) {
+ this.setAttribute('open', '');
+ this.querySelector<HTMLElement>('[tabindex]')?.focus();
+ };
+ HTMLDialogElement.prototype.close = function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ };
+});
+
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.stubGlobal('ResizeObserver', MockResizeObserver);
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ document.documentElement.style.overflow = '';
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+/**
+ * Gives the drawer a running slide-in transition (Web Animations'
+ * `getAnimations()`, which jsdom lacks) whose end the test decides.
+ */
+function stubSlideIn() {
+ let end = () => {};
+ const finished = new Promise<void>(resolve => {
+ end = resolve;
+ });
+ const slideIn = {
+ playState: 'running',
+ finished,
+ effect: {getComputedTiming: () => ({endTime: 410})},
+ };
+ Object.defineProperty(Element.prototype, 'getAnimations', {
+ configurable: true,
+ value(this: Element) {
+ return this.matches('dialog [tabindex="-1"]') ? [slideIn] : [];
+ },
+ });
+ return {
+ async end() {
+ await act(async () => {
+ end();
+ });
+ },
+ };
+}
+
+describe('MobileNav under a finger', () => {
+ beforeEach(() => {
+ stubMatchMedia({reduceMotion: false, pointer: 'coarse'});
+ });
+
+ afterEach(() => {
+ Reflect.deleteProperty(Element.prototype, 'getAnimations');
+ });
+
+ it('takes no touch until the slide-in ends, at most MAX_EXIT_MS in', async () => {
+ stubSlideIn();
+ render(<Harness />);
+ const open = screen.getByRole('button', {name: 'Open'});
+ open.focus();
+ fireEvent.click(open);
+ const dialog = screen.getByTestId('mobile-nav');
+ expect(dialog).toHaveAttribute('open');
+ expect(isInHeldLayer(dialog)).toBe(true);
+
+ await advance(MAX_EXIT_MS + 10);
+ expect(isInHeldLayer(dialog)).toBe(false);
+ });
+
+ it('takes touch again when its slide-in transition ends, however soon (FR35)', async () => {
+ const slideIn = stubSlideIn();
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+ const dialog = screen.getByTestId('mobile-nav');
+ await advance(300);
+ expect(isInHeldLayer(dialog)).toBe(true);
+
+ await slideIn.end();
+ expect(isInHeldLayer(dialog)).toBe(false);
+ });
+
+ it('holds until its slide-in transition ends, past a timer of its duration (FR35)', async () => {
+ // A 410 ms slide-in starts a frame or two after the drawer opens, so it
+ // ends after a 410 ms timer started on open would.
+ const slideIn = stubSlideIn();
+ render(<Harness />);
+ const drawer = screen
+ .getByTestId('mobile-nav')
+ .querySelector<HTMLElement>('[tabindex="-1"]');
+ drawer?.style.setProperty('transition-duration', '0.41s');
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+ const dialog = screen.getByTestId('mobile-nav');
+ await advance(420);
+ expect(isInHeldLayer(dialog)).toBe(true);
+
+ await slideIn.end();
+ expect(isInHeldLayer(dialog)).toBe(false);
+ });
+
+ it('keeps keys and assistive technology live while it slides in (spec:AST-094 FR35)', () => {
+ stubSlideIn();
+ render(<Harness />);
+ const open = screen.getByRole('button', {name: 'Open'});
+ open.focus();
+ fireEvent.click(open);
+ const dialog = screen.getByTestId('mobile-nav');
+ expect(isInHeldLayer(dialog)).toBe(true);
+
+ // Only pointer input is held: the drawer keeps the focus showModal()
+ // gave it, and its content stays out of any inert or hidden subtree, so
+ // keys and assistive technology still reach it.
+ expect(dialog.contains(document.activeElement)).toBe(true);
+ const home = screen.getByRole('link', {name: 'Home'});
+ expect(home.closest('[inert]')).toBeNull();
+ expect(home.closest('[aria-hidden="true"]')).toBeNull();
+ home.focus();
+ expect(document.activeElement).toBe(home);
+ });
+
+ it('holds nothing once a close is requested: the leaving drawer stays live until the dialog closes, at most 250 ms in (FR5), then gives focus back (spec:AST-094 FR35 holds entrances only)', async () => {
+ stubSlideIn();
+ render(<Harness />);
+ const open = screen.getByRole('button', {name: 'Open'});
+ open.focus();
+ fireEvent.click(open);
+ await advance(MAX_EXIT_MS + 10);
+ const dialog = screen.getByTestId('mobile-nav');
+
+ fireEvent.click(screen.getByRole('button', {name: /close navigation/i}));
+ await advance(100);
+ // Before the close: still open and modal, and nothing is held.
+ expect(dialog).toHaveAttribute('open');
+ expect(isInHeldLayer(dialog)).toBe(false);
+ expect(
+ screen.getByRole('link', {name: 'Home', hidden: true}).closest('[inert]'),
+ ).toBeNull();
+
+ // The close keeps the mouse's timing, at most MAX_CLOSE_DELAY_MS in.
+ await advance(MAX_CLOSE_DELAY_MS - 100 + 10);
+ expect(dialog).not.toHaveAttribute('open');
+ expect(document.activeElement).toBe(open);
+ });
+
+ it('reopened before the dialog closes, keeps focus in the drawer', async () => {
+ stubSlideIn();
+ render(<Harness />);
+ const open = screen.getByRole('button', {name: 'Open'});
+ open.focus();
+ fireEvent.click(open);
+ await advance(MAX_EXIT_MS + 10);
+ const dialog = screen.getByTestId('mobile-nav');
+
+ fireEvent.click(screen.getByRole('button', {name: /close navigation/i}));
+ await advance(100);
+ fireEvent.click(open);
+ expect(dialog).toHaveAttribute('open');
+ expect(dialog.contains(document.activeElement)).toBe(true);
+ expect(
+ screen.getByRole('link', {name: 'Home', hidden: true}).closest('[inert]'),
+ ).toBeNull();
+
+ await advance(MAX_EXIT_MS + 10);
+ expect(dialog).toHaveAttribute('open');
+ expect(isInHeldLayer(dialog)).toBe(false);
+ });
+ it('holds nothing when the drawer has no slide-in to wait for', () => {
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+ const dialog = screen.getByTestId('mobile-nav');
+ expect(dialog).toHaveAttribute('open');
+ expect(isInHeldLayer(dialog)).toBe(false);
+ });
+});
+
+describe('MobileNav under a mouse', () => {
+ beforeEach(() => {
+ stubMatchMedia({reduceMotion: false, pointer: 'fine'});
+ });
+
+ it('holds nothing, and closes on its own timing as before', async () => {
+ render(<Harness />);
+ const open = screen.getByRole('button', {name: 'Open'});
+ open.focus();
+ fireEvent.click(open);
+ const dialog = screen.getByTestId('mobile-nav');
+ expect(dialog).toHaveAttribute('open');
+ expect(isInHeldLayer(dialog)).toBe(false);
+
+ fireEvent.click(screen.getByRole('button', {name: /close navigation/i}));
+ expect(isInHeldLayer(dialog)).toBe(false);
+ expect(
+ screen.getByRole('link', {name: 'Home', hidden: true}).closest('[inert]'),
+ ).toBeNull();
+ await advance(260);
+ expect(dialog).not.toHaveAttribute('open');
+ expect(document.activeElement).toBe(open);
+ });
+});
diff --git a/packages/core/src/MobileNav/__tests__/MobileNavTouchPresentation.a11y.chromium.spec.ts b/packages/core/src/MobileNav/__tests__/MobileNavTouchPresentation.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..6aae34b7e7
--- /dev/null
+++ b/packages/core/src/MobileNav/__tests__/MobileNavTouchPresentation.a11y.chromium.spec.ts
@@ -0,0 +1,520 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file MobileNavTouchPresentation.a11y.chromium.spec.ts
+ * @input The built MobileNav "Default" story, real Chromium touch input in a
+ * phone context and a mouse on a fine-pointer page
+ * @output Browser evidence that under a finger the drawer takes no tap while
+ * it slides in, while keys and assistive technology stay live; that a close
+ * holds nothing (spec:AST-094 FR35 holds entrances only): the dialog closes
+ * on its own timing (at most 250 ms in, FR5), when focus returns to the
+ * opener and the page takes taps again; the rest of the slide-out after the
+ * close takes no tap and is hidden from assistive technology (FR5). Under a
+ * mouse nothing is held and the close keeps its timing.
+ * @position Chromium proof for MobileNav's touch presentation (MobileNav.tsx);
+ * the jsdom layer is MobileNavTouchPresentation.test.tsx
+ *
+ * A case that must act inside the slide-in or the close stops the page's
+ * clock first, so the close's own delay and the slide-in's cap wait for it
+ * however long the runner takes between steps, and
+ * it runs the clock on by exact amounts. Where the drawer's place or its
+ * slide-in matters, the slide is slowed to a minute; the close keeps its own
+ * timing either way.
+ */
+
+import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+test.use({
+ hasTouch: true,
+ isMobile: true,
+ viewport: {width: 402, height: 714},
+ deviceScaleFactor: 1,
+});
+
+test.beforeEach(async ({page}) => {
+ // The page's clock runs with real time until a case stops it (stopClock).
+ await page.clock.install();
+ // Counts the key presses that reach the window (settleInput).
+ await page.addInitScript(() => {
+ const counter = window as unknown as {__keydowns: number};
+ counter.__keydowns = 0;
+ window.addEventListener(
+ 'keydown',
+ () => {
+ counter.__keydowns += 1;
+ },
+ true,
+ );
+ });
+});
+
+const MOBILE_NAV_STORY = 'core-mobilenav--default';
+
+interface LoggedEvent {
+ type: 'click' | 'focus' | 'open';
+ /** performance.now() in the page, ms. */
+ t: number;
+ /** The event's target is inside the dialog (or is the dialog). */
+ inDialog?: boolean;
+ /** The event's target is the dialog itself: its backdrop. */
+ onBackdrop?: boolean;
+ /** The event's target is inside the drawer panel. */
+ inDrawer?: boolean;
+ /** The focused element's accessible name, for focus events. */
+ name?: string | null;
+ /** The dialog's `open` attribute, for open events. */
+ open?: boolean;
+}
+
+/**
+ * Opens the drawer from its button with a tap, waits for the slide-in, and
+ * starts logging clicks, focus moves and the dialog's `open` attribute.
+ */
+async function openNav(
+ page: Page,
+ {
+ input = 'touch',
+ tokenDefault = false,
+ }: {
+ input?: 'touch' | 'mouse';
+ /**
+ * Runs the slide at the token default, `--duration-medium: 410ms`, rather
+ * than the story theme's 300 ms, so a close at the end of the slide-out
+ * (410 ms) and one on FR5's timing (at most 250 ms) are far apart.
+ */
+ tokenDefault?: boolean;
+ } = {},
+) {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${MOBILE_NAV_STORY}&viewMode=story`,
+ );
+ if (tokenDefault) {
+ await page.addStyleTag({
+ content: '* { --duration-medium: 410ms !important; }',
+ });
+ }
+ const opener = page.getByRole('button', {name: 'Open Navigation'});
+ // A tap focuses the button in Chromium; focusing it first makes the opener
+ // explicit for the focus-return assertions.
+ await opener.focus();
+ if (input === 'mouse') {
+ await opener.click();
+ } else {
+ await opener.tap();
+ }
+ const nav = page.getByRole('dialog');
+ await expect(nav).toBeVisible();
+ const drawer = nav.locator('[tabindex="-1"]').first();
+ await drawer.evaluate(async element => {
+ await Promise.all(element.getAnimations().map(async a => a.finished));
+ });
+ const box = await drawer.boundingBox();
+ const viewport = page.viewportSize();
+ if (box == null || viewport == null) {
+ throw new Error('the drawer did not render');
+ }
+ const durationMs = await drawer.evaluate(element => {
+ const value = getComputedStyle(element).transitionDuration.split(',')[0];
+ return value.endsWith('ms') ? parseFloat(value) : parseFloat(value) * 1000;
+ });
+ await page.evaluate(() => {
+ const events: LoggedEvent[] = [];
+ (window as unknown as {__events: LoggedEvent[]}).__events = events;
+ const dialog = document.querySelector('dialog');
+ if (dialog == null) {
+ throw new Error('no dialog');
+ }
+ new MutationObserver(() => {
+ events.push({
+ type: 'open',
+ t: performance.now(),
+ open: dialog.hasAttribute('open'),
+ });
+ }).observe(dialog, {attributes: true, attributeFilter: ['open']});
+ document.addEventListener(
+ 'click',
+ event => {
+ const target = event.target as Element;
+ // Keep the story's nav links from navigating the frame.
+ if (target.closest('a')) {
+ event.preventDefault();
+ }
+ events.push({
+ type: 'click',
+ t: performance.now(),
+ inDialog: target.closest('dialog') != null,
+ onBackdrop: target === dialog,
+ inDrawer: target.closest('dialog [tabindex="-1"]') != null,
+ });
+ },
+ true,
+ );
+ document.addEventListener(
+ 'focusin',
+ event => {
+ const target = event.target as HTMLElement;
+ events.push({
+ type: 'focus',
+ t: performance.now(),
+ name: target.getAttribute('aria-label') ?? target.textContent,
+ });
+ },
+ true,
+ );
+ });
+ // The backdrop is the strip the drawer leaves free.
+ const strip =
+ box.x > 0.5
+ ? {from: 0, to: box.x}
+ : {from: box.x + box.width, to: viewport.width};
+ const backdrop = {x: (strip.from + strip.to) / 2, y: viewport.height / 2};
+ return {nav, drawer, durationMs, backdrop};
+}
+
+const loggedEvents = async (page: Page) =>
+ page.evaluate(
+ () => (window as unknown as {__events: LoggedEvent[]}).__events,
+ );
+
+const now = async (page: Page) => page.evaluate(() => performance.now());
+
+/** The dialog's state at this instant. */
+const state = async (page: Page) =>
+ page.evaluate(() => {
+ const dialog = document.querySelector('dialog');
+ const drawer = dialog?.querySelector<HTMLElement>('[tabindex="-1"]');
+ return {
+ modal: dialog?.matches(':modal') ?? false,
+ drawerInert: drawer?.inert ?? false,
+ scrim:
+ dialog == null ? null : +getComputedStyle(dialog, '::backdrop').opacity,
+ focusInDrawer: drawer != null && drawer.contains(document.activeElement),
+ focusOnOpener:
+ document.activeElement?.getAttribute('aria-label') ===
+ 'Open Navigation',
+ };
+ });
+
+const middleOf = (box: {x: number; y: number; width: number; height: number}) =>
+ [box.x + box.width / 2, box.y + box.height / 2] as const;
+
+/**
+ * Stops the page's clock: no timer fires (the close's own delay, the
+ * slide-in's cap) until `advance` runs the clock on.
+ * Until here it runs with real time; the pause is a minute ahead, so always in
+ * its future.
+ */
+async function stopClock(page: Page) {
+ const pageNow = await page.evaluate(() => Date.now());
+ await page.clock.pauseAt(pageNow + 60_000);
+ return {
+ /** Runs the page's clock `ms` on, firing every timer due by then. */
+ advance: async (ms: number) => page.clock.runFor(ms),
+ };
+}
+
+/** Slows the drawer's slide to a minute, so it is still moving at each step. */
+const slowSlide = async (page: Page) =>
+ page.addStyleTag({content: '* { --duration-medium: 60s !important; }'});
+
+/**
+ * Waits until every tap sent before has reached the page, clicks and all: a
+ * Shift press goes through the same input queue after them, and no hold takes
+ * keys (FR35).
+ */
+async function settleInput(page: Page) {
+ const keydowns = async () =>
+ page.evaluate(() => (window as unknown as {__keydowns: number}).__keydowns);
+ const before = await keydowns();
+ await page.keyboard.press('Shift');
+ await expect.poll(keydowns).toBe(before + 1);
+}
+
+test('a close holds nothing: the dialog closes at most 250 ms in (FR5), then focus returns', async ({
+ page,
+}) => {
+ const {durationMs, backdrop} = await openNav(page, {tokenDefault: true});
+ expect(durationMs).toBeGreaterThan(400);
+
+ const clock = await stopClock(page);
+ await page.touchscreen.tap(backdrop.x, backdrop.y);
+ const closeTapped = await now(page);
+ await settleInput(page);
+ // Inside the close, which cannot end while the page's clock is stopped:
+ // still the modal dialog with its drawer laid out, and nothing held
+ // (spec:AST-094 FR35 holds an entrance only): no shield, the leaving
+ // drawer live.
+ const early = await state(page);
+ expect(early.modal).toBe(true);
+ const drawerBox = await page
+ .locator('dialog [tabindex="-1"]')
+ .first()
+ .boundingBox();
+ expect(drawerBox?.width ?? 0).toBeGreaterThan(0);
+ expect(early.drawerInert).toBe(false);
+ await expect(page.locator('dialog > [popover]')).toHaveCount(0);
+
+ await clock.advance(1000);
+ // The dialog closed on its own timing, at most 250 ms in, well before the
+ // 410 ms slide-out ended...
+ const events = await loggedEvents(page);
+ const closed = events.find(e => e.type === 'open' && e.open === false);
+ expect(closed).toBeDefined();
+ const closedIn = (closed?.t ?? Infinity) - closeTapped;
+ expect(closedIn).toBeGreaterThan(0);
+ expect(closedIn).toBeLessThanOrEqual(250);
+ // ...and focus went back to the opener as it did, in the same task.
+ const returned = events.find(
+ e => e.type === 'focus' && e.name === 'Open Navigation',
+ );
+ expect(returned?.t).toBe(closed?.t);
+ const after = await state(page);
+ expect(after.modal).toBe(false);
+ expect(after.drawerInert).toBe(false);
+});
+
+test('the page takes taps again once the dialog has closed', async ({page}) => {
+ const {backdrop} = await openNav(page, {tokenDefault: true});
+ await slowSlide(page);
+
+ const clock = await stopClock(page);
+ await page.touchscreen.tap(backdrop.x, backdrop.y);
+ await settleInput(page);
+ await clock.advance(1000);
+ expect((await state(page)).modal).toBe(false);
+ // The dialog has closed while the drawer still slides out (a minute long
+ // here): the page takes the next tap.
+ await page.touchscreen.tap(backdrop.x, backdrop.y);
+ await settleInput(page);
+
+ const events = await loggedEvents(page);
+ const closed = events.find(e => e.type === 'open' && e.open === false);
+ expect(closed).toBeDefined();
+ const clicks = events.filter(e => e.type === 'click');
+ const pageClicks = clicks.filter(e => !e.inDialog);
+ // Two clicks: the close tap's on the backdrop, and the page's after the
+ // close.
+ expect(clicks).toHaveLength(2);
+ expect(clicks[0].onBackdrop).toBe(true);
+ expect(clicks[0].t).toBeLessThan(closed?.t ?? -Infinity);
+ expect(pageClicks).toHaveLength(1);
+ expect(pageClicks[0]).toBe(clicks[1]);
+ expect(pageClicks[0].t).toBeGreaterThan(closed?.t ?? Infinity);
+});
+
+/**
+ * The roles and names the browser's accessibility tree gives assistive
+ * technology: its nodes that are not ignored.
+ */
+async function exposedToAssistiveTech(page: Page): Promise<string[]> {
+ const cdp = await page.context().newCDPSession(page);
+ try {
+ const {nodes} = (await cdp.send('Accessibility.getFullAXTree')) as {
+ nodes: {
+ ignored: boolean;
+ role?: {value: string};
+ name?: {value: string};
+ }[];
+ };
+ return nodes
+ .filter(node => !node.ignored)
+ .map(node =>
+ `${node.role?.value ?? ''} ${node.name?.value ?? ''}`.trim(),
+ );
+ } finally {
+ await cdp.detach();
+ }
+}
+
+/** Whether a hit at a point lands inside the drawer panel. */
+const hitsDrawer = async (page: Page, point: readonly [number, number]) =>
+ page.evaluate(
+ ([x, y]) =>
+ document.elementFromPoint(x, y)?.closest('dialog [tabindex="-1"]') !=
+ null,
+ point,
+ );
+
+test('after the dialog closes, the rest of the slide-out takes no tap and is hidden from assistive technology (FR5)', async ({
+ page,
+}) => {
+ const {backdrop} = await openNav(page, {tokenDefault: true});
+ const link = page.locator('dialog a', {hasText: 'Dashboard'});
+ const linkBox = async () => {
+ const box = await link.boundingBox();
+ if (box == null) {
+ throw new Error('no link box');
+ }
+ return box;
+ };
+ // Open, its link takes a hit and assistive technology reads the dialog and
+ // its links: what the checks below look for is there to find.
+ expect(await hitsDrawer(page, middleOf(await linkBox()))).toBe(true);
+ expect(await exposedToAssistiveTech(page)).toEqual(
+ expect.arrayContaining(['dialog Navigation', 'link Dashboard']),
+ );
+
+ await slowSlide(page);
+ const clock = await stopClock(page);
+ await page.touchscreen.tap(backdrop.x, backdrop.y);
+ await settleInput(page);
+ await clock.advance(1000);
+ // The dialog has closed while the drawer still slides out (a minute long
+ // here): the drawer and its link are there, painted on screen.
+ expect((await state(page)).modal).toBe(false);
+ expect(
+ await page.evaluate(() => document.querySelector('dialog')?.open),
+ ).toBe(false);
+ const tail = await linkBox();
+ const viewport = page.viewportSize();
+ expect(tail.width).toBeGreaterThan(0);
+ expect(tail.x).toBeGreaterThanOrEqual(0);
+ expect(tail.x + tail.width).toBeLessThanOrEqual(viewport?.width ?? 0);
+ const onLink = middleOf(tail);
+ // A tap on the leaving drawer reaches the page, not the drawer...
+ expect(await hitsDrawer(page, onLink)).toBe(false);
+ await page.touchscreen.tap(...onLink);
+ await settleInput(page);
+ const clicks = (await loggedEvents(page)).filter(e => e.type === 'click');
+ // The close tap's click on the backdrop, then the page's.
+ expect(clicks).toHaveLength(2);
+ expect(clicks[0].onBackdrop).toBe(true);
+ expect(clicks[1].inDialog).toBe(false);
+ // ...and assistive technology reads none of it.
+ const exposed = await exposedToAssistiveTech(page);
+ expect(exposed).not.toContain('dialog Navigation');
+ expect(exposed).not.toContain('link Dashboard');
+ expect(exposed).not.toContain('button Close navigation');
+});
+
+/** Opens the drawer with a tap while the page's clock is stopped. */
+async function openInsideSlideIn(page: Page) {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${MOBILE_NAV_STORY}&viewMode=story`,
+ );
+ await slowSlide(page);
+ const opener = await page
+ .getByRole('button', {name: 'Open Navigation'})
+ .boundingBox();
+ if (opener == null) {
+ throw new Error('no opener box');
+ }
+ const clock = await stopClock(page);
+ await page.touchscreen.tap(...middleOf(opener));
+ await settleInput(page);
+ await expect.poll(async () => (await state(page)).modal).toBe(true);
+ return clock;
+}
+
+test('a tap during the slide-in reaches nothing', async ({page}) => {
+ const clock = await openInsideSlideIn(page);
+ const viewport = page.viewportSize();
+ if (viewport == null) {
+ throw new Error('no viewport');
+ }
+ // Early in the slide-in, on the strip the drawer leaves free: under iOS's
+ // rule the tap is dropped, so it does not close the drawer. The point is
+ // the backdrop's: inside the dialog, outside the drawer, which is there
+ // and laid out.
+ const tap = {x: 8, y: viewport.height / 2};
+ const dialogBox = await page.locator('dialog').boundingBox();
+ const drawerBox = await page
+ .locator('dialog [tabindex="-1"]')
+ .first()
+ .boundingBox();
+ if (dialogBox == null || drawerBox == null) {
+ throw new Error('no dialog or drawer box');
+ }
+ expect(drawerBox.width).toBeGreaterThan(0);
+ expect(drawerBox.height).toBeGreaterThan(0);
+ expect(tap.x).toBeGreaterThan(dialogBox.x);
+ expect(tap.x).toBeLessThan(dialogBox.x + dialogBox.width);
+ expect(tap.x < drawerBox.x || tap.x > drawerBox.x + drawerBox.width).toBe(
+ true,
+ );
+ await page.touchscreen.tap(tap.x, tap.y);
+ await settleInput(page);
+ // A close asked for would have closed the dialog by now: the page's clock
+ // ran past the close's delay and the slide-in's cap.
+ await clock.advance(1000);
+ expect(
+ await page.evaluate(() => document.querySelector('dialog')?.open),
+ ).toBe(true);
+});
+
+test('keys and assistive technology stay live during the slide-in (spec:AST-094 FR35)', async ({
+ page,
+}) => {
+ await openInsideSlideIn(page);
+ // Early in the slide-in, while a tap is still held: a key moves focus into
+ // the drawer, and its links stay in the accessibility tree.
+ await page.keyboard.press('Tab');
+ const live = await page.evaluate(() => {
+ const dialog = document.querySelector('dialog');
+ const drawer = dialog?.querySelector('[tabindex="-1"]');
+ const focused = document.activeElement;
+ return {
+ sliding:
+ drawer?.getAnimations().some(a => a.playState === 'running') ?? false,
+ focusInDialog: dialog?.contains(focused) ?? false,
+ focusInert: focused?.closest('[inert]') != null,
+ };
+ });
+ expect(live.sliding).toBe(true);
+ expect(live.focusInDialog).toBe(true);
+ expect(live.focusInert).toBe(false);
+ await expect(page.getByRole('link', {name: 'Dashboard'})).toHaveCount(1);
+});
+
+test.describe('under a mouse', () => {
+ test.use({hasTouch: false, isMobile: false});
+
+ test('nothing is held, and the dialog closes partway into the slide-out, as before', async ({
+ page,
+ }) => {
+ const {drawer, durationMs, backdrop} = await openNav(page, {
+ input: 'mouse',
+ });
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: fine)').matches),
+ ).toBe(true);
+
+ const clock = await stopClock(page);
+ await page.mouse.click(backdrop.x, backdrop.y);
+ const closeClicked = await now(page);
+ await settleInput(page);
+ // No hold: the leaving drawer is not inert.
+ expect(
+ await drawer.evaluate(element => (element as HTMLElement).inert),
+ ).toBe(false);
+ await clock.advance(1000);
+
+ const events = await loggedEvents(page);
+ const closed = events.find(e => e.type === 'open' && e.open === false);
+ expect(closed).toBeDefined();
+ // The close's own timing: at most 250 ms in, well before the slide-out
+ // ends.
+ const closedIn = (closed?.t ?? Infinity) - closeClicked;
+ expect(closedIn).toBeGreaterThan(0);
+ expect(closedIn).toBeLessThan(durationMs);
+ expect(closedIn).toBeLessThanOrEqual(250);
+ expect(
+ events.some(e => e.type === 'focus' && e.name === 'Open Navigation'),
+ ).toBe(true);
+ });
+});
diff --git a/packages/core/src/__tests__/stubMatchMedia.test.ts b/packages/core/src/__tests__/stubMatchMedia.test.ts
index 01846d67f3..4b749123c5 100644
--- a/packages/core/src/__tests__/stubMatchMedia.test.ts
+++ b/packages/core/src/__tests__/stubMatchMedia.test.ts
@@ -55,6 +55,17 @@ describe('stubMatchMedia', () => {
expect(matchMedia('(max-width: 768px)').matches).toBe(true);
});
+ it('answers the pointer queries from their own knob, fine by default', () => {
+ stubMatchMedia();
+ expect(matchMedia('(pointer: coarse)').matches).toBe(false);
+ expect(matchMedia('(pointer: fine)').matches).toBe(true);
+
+ stubMatchMedia({pointer: 'coarse'});
+ expect(matchMedia('(pointer: coarse)').matches).toBe(true);
+ expect(matchMedia('(pointer: fine)').matches).toBe(false);
+ expect(matchMedia('(max-width: 768px)').matches).toBe(true);
+ });
+
it('lets a non-motion query be answered false', () => {
// Above the breakpoint, motion still reduced — the other axis of the
// combination, so neither knob can be quietly driving both.
diff --git a/packages/core/src/__tests__/stubMatchMedia.ts b/packages/core/src/__tests__/stubMatchMedia.ts
index 5fad7a2030..5c66262ed4 100644
--- a/packages/core/src/__tests__/stubMatchMedia.ts
+++ b/packages/core/src/__tests__/stubMatchMedia.ts
@@ -19,9 +19,11 @@
* it is exercising the real delay. The failure mode is invisible: every test
* still passes.
*
- * So the two answers are separate knobs here. `reduceMotion` answers
- * `prefers-reduced-motion` only; `matches` answers everything else (breakpoint
- * width queries, which tests below a breakpoint want to be true).
+ * So the answers are separate knobs here. `reduceMotion` answers
+ * `prefers-reduced-motion` only; `pointer` answers the pointer queries (a
+ * blanket `true` would also make the pointer coarse, rerouting anything that
+ * behaves differently under a finger); `matches` answers everything else
+ * (breakpoint width queries, which tests below a breakpoint want to be true).
*
* SYNC: When modified, update this header.
*/
@@ -31,10 +33,26 @@ import {vi} from 'vitest';
export interface StubMatchMediaOptions {
/** Whether the user prefers reduced motion. */
reduceMotion?: boolean;
+ /** The primary pointer: `(pointer: coarse)` matches only for `'coarse'`. */
+ pointer?: 'fine' | 'coarse';
/** Answer for every other query — width breakpoints, hover, etc. */
matches?: boolean;
}
+/** Answer a `pointer` query, or null if it isn't one. */
+function answerPointer(
+ query: string,
+ pointer: 'fine' | 'coarse',
+): boolean | null {
+ if (query.includes('pointer: coarse')) {
+ return pointer === 'coarse';
+ }
+ if (query.includes('pointer: fine')) {
+ return pointer === 'fine';
+ }
+ return null;
+}
+
/**
* Answer a `prefers-reduced-motion` query, or null if it isn't one.
*
@@ -77,12 +95,16 @@ function answerReducedMotion(
*/
export function stubMatchMedia({
reduceMotion = false,
+ pointer = 'fine',
matches = true,
}: StubMatchMediaOptions = {}): void {
vi.stubGlobal(
'matchMedia',
vi.fn((query: string) => ({
- matches: answerReducedMotion(query, reduceMotion) ?? matches,
+ matches:
+ answerReducedMotion(query, reduceMotion) ??
+ answerPointer(query, pointer) ??
+ matches,
media: query,
onchange: null,
addEventListener: vi.fn(),
diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.ts
index a6f9aa0389..69b5cb6ea3 100644
--- a/packages/core/src/gestures/GestureHost.ts
+++ b/packages/core/src/gestures/GestureHost.ts
@@ -3,7 +3,8 @@
/**
* @file GestureHost.ts
* @input DOM touch, pointer, click, contextmenu, scroll and focus events of
- * one document; elements with recognizers and consumers attached
+ * one document; elements with recognizers and consumers attached; the
+ * input hold's held layers (Layer/inputHold `holdsTouch`)
* @output Exports GestureHost (the DOM side of the gesture system) and
* getGestureHost (one host per document)
* @position Browser adapter of packages/core/src/gestures: turns real events
@@ -149,6 +150,7 @@ import {
import {containsAlongFlatTree} from '../utils/flatTree';
import {isIosWebKit} from '../utils/touchQueries';
import {type WheelSegment, WheelSegmenter} from './wheelSegmenter';
+import {holdsTouch} from '../Layer/inputHold';
import {
gestureHostStyle,
type GestureHostStyle,
@@ -2126,9 +2128,12 @@ export class GestureHost {
const recognizers: GestureRecognizer[] = [];
let consumer: TouchConsumer | null = null;
let consumerElement: Element | null = null;
+ // A layer that the input hold holds takes no touch while it presents.
+ // The host asks the hold, so the hold needs nothing from gestures/. A
+ // root-entry component can then use the hold with no gesture code.
if (
target instanceof Node &&
- [...this.touchGates].some(gate => gate(target))
+ (holdsTouch(target) || [...this.touchGates].some(gate => gate(target)))
) {
return {recognizers, consumer, consumerElement};
}
@@ -2868,8 +2873,8 @@ export class GestureHost {
/**
* Hold touches away from every participant while `gate(target)` answers
- * true (a presentation running in a layer: its content takes no touch
- * until it settles). Returns the release.
+ * true. Returns the release. The input hold's held layers need no gate,
+ * because the host asks `holdsTouch` for every touch.
*/
addTouchGate(gate: (target: Node) => boolean): () => void {
this.touchGates.add(gate);
diff --git a/packages/core/src/gestures/README.md b/packages/core/src/gestures/README.md
index 18df55bba6..83a7159509 100644
--- a/packages/core/src/gestures/README.md
+++ b/packages/core/src/gestures/README.md
@@ -434,11 +434,15 @@ subscriber cancels it: the host cancels `touchend` and `contextmenu` there
while a claiming participant is attached, never a `touchstart` or a
`touchmove`, and the click guard (`../utils/clickGuard.ts`) keeps a
cancelling `click` while it is armed, and from the menu press model's first
-arm on. A blocking `touchmove` sits on a claiming
+arm on. A layer's input hold (`../Layer/inputHold.ts`) cancels pointer and
+mouse events, clicks, `touchmove` and `touchend` there while a layer is held,
+never a `touchstart`. A blocking `touchmove` sits on a claiming
element and on a claimed touch's target, on the document while an element a
claiming recognizer lives in is moving (Touches on moving elements), or on
-the window only while a page hold is held, so a page of pressables blocks
-no scroll.
+the window only while a page hold or a layer's input hold is held, so a page
+of pressables blocks no scroll. The stream records the type of the latest
+pointer event it delivers (`getLastPointerType`); the input hold reads it as
+a layer opens.
### Holding the page still
diff --git a/packages/core/src/gestures/__tests__/GestureHost.test.ts b/packages/core/src/gestures/__tests__/GestureHost.test.ts
index da5738d2f2..decc4be8c2 100644
--- a/packages/core/src/gestures/__tests__/GestureHost.test.ts
+++ b/packages/core/src/gestures/__tests__/GestureHost.test.ts
@@ -29,6 +29,7 @@ import {TapGestureRecognizer} from '../TapGestureRecognizer';
import {createNativeScrollProbe} from '../nativeScroll';
import {gestureHosts} from '../hostRegistry';
import {holdPageScroll, type PageScrollDecision} from '../pageHold';
+import {holdInput} from '../../Layer/inputHold';
import {ManualClock, RecordingConsumer} from './harness';
import {TOUCH_QUERY} from '../../utils/touchQueries';
import {registerPresentedOffset} from '../../motion/presentation';
@@ -3740,6 +3741,26 @@ describe('touch gates and a second finger', () => {
touch('touchend', button, [finger], [], 140);
});
+ it("holds a held layer's targets away from every participant with no gate: the host asks the input hold", () => {
+ const {layer, button} = mount(
+ '<div id="layer"><div id="button"></div></div>',
+ );
+ const tap = new TapGestureRecognizer({name: 'tap'});
+ detachers.push(host.attach(button, tap));
+ const release = holdInput(layer, {
+ until: new Promise(() => {}),
+ scope: 'viewport',
+ });
+ const finger = {id: 1, x: 5, y: 5};
+ touch('touchstart', button, [finger], [finger], 0);
+ expect(tap.numberOfTouches).toBe(0);
+ touch('touchend', button, [finger], [], 40);
+ release();
+ touch('touchstart', button, [finger], [finger], 100);
+ expect(tap.numberOfTouches).toBe(1);
+ touch('touchend', button, [finger], [], 140);
+ });
+
it('fails a one-finger pan that has not claimed when a second finger lands anywhere, so the browser can pinch', () => {
const {row, text} = mount('<div id="row"></div><p id="text">plain</p>');
const swipe = new PanGestureRecognizer({
diff --git a/packages/core/src/utils/flatTree.test.ts b/packages/core/src/utils/flatTree.test.ts
index 7837af699d..4c12f03770 100644
--- a/packages/core/src/utils/flatTree.test.ts
+++ b/packages/core/src/utils/flatTree.test.ts
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {afterEach, describe, expect, it} from 'vitest';
-import {containsAlongFlatTree} from './flatTree';
+import {containsAlongFlatTree, deepActiveElement} from './flatTree';
afterEach(() => {
document.body.innerHTML = '';
@@ -40,3 +40,29 @@ describe('containsAlongFlatTree', () => {
expect(containsAlongFlatTree(a, document.createElement('i'))).toBe(false);
});
});
+
+describe('deepActiveElement', () => {
+ it("is the document's focused element in light DOM, and null without a document", () => {
+ document.body.innerHTML = '<input id="field" />';
+ const field = document.getElementById('field') as HTMLInputElement;
+ field.focus();
+ expect(deepActiveElement(document)).toBe(field);
+ expect(deepActiveElement(null)).toBeNull();
+ expect(deepActiveElement(undefined)).toBeNull();
+ });
+
+ it('goes down through open shadow roots to the element that has focus', () => {
+ const outer = document.createElement('div');
+ document.body.append(outer);
+ const outerRoot = outer.attachShadow({mode: 'open'});
+ const inner = document.createElement('span');
+ outerRoot.append(inner);
+ const innerRoot = inner.attachShadow({mode: 'open'});
+ const button = document.createElement('button');
+ innerRoot.append(button);
+ button.focus();
+ // The document sees only the outermost host.
+ expect(document.activeElement).toBe(outer);
+ expect(deepActiveElement(document)).toBe(button);
+ });
+});
diff --git a/packages/core/src/utils/flatTree.ts b/packages/core/src/utils/flatTree.ts
index f43ed609e9..de9dcc8f39 100644
--- a/packages/core/src/utils/flatTree.ts
+++ b/packages/core/src/utils/flatTree.ts
@@ -3,11 +3,12 @@
/**
* @file flatTree.ts
* @input A DOM node
- * @output Exports parentAcrossShadow, and containsAlongFlatTree, which walks it
+ * @output Exports parentAcrossShadow, containsAlongFlatTree, which walks it,
+ * and deepActiveElement
* @position The flat-tree parent the browser scrolls and dispatches
- * through, shared by the gesture host's native-scroll probe and the
+ * through, shared by the gesture host's native-scroll probe, the
* selection lock (which the press feedback controller uses without the
- * gesture system)
+ * gesture system) and the Layer module's input hold
*/
/** The node's parent, crossing out of shadow roots. */
@@ -38,3 +39,14 @@ export function containsAlongFlatTree(ancestor: Node, node: Node): boolean {
}
return false;
}
+
+/** The focused element of `doc`, inside open shadow roots too. */
+export function deepActiveElement(
+ doc: Document | null | undefined,
+): Element | null {
+ let active = doc?.activeElement ?? null;
+ while (active?.shadowRoot?.activeElement != null) {
+ active = active.shadowRoot.activeElement;
+ }
+ return active;
+}
diff --git a/packages/core/src/utils/inputStream.test.ts b/packages/core/src/utils/inputStream.test.ts
index 08201a7033..7c21056e4d 100644
--- a/packages/core/src/utils/inputStream.test.ts
+++ b/packages/core/src/utils/inputStream.test.ts
@@ -10,7 +10,9 @@
* window, stopImmediatePropagation on the document) starves no subscriber; events
* fired at the document reach the stream; a page of pressables registers
* no non-passive listener, and the gesture host none that holds a scroll;
- * the press feedback controller imports nothing from gestures/
+ * the press feedback controller imports nothing from gestures/; the
+ * latest delivered pointer event's type is readable, and none is recorded
+ * while no subscriber hears pointer events
* @position Unit tests of packages/core/src/utils/inputStream.ts
*/
@@ -19,7 +21,7 @@ import path from 'node:path';
import {afterEach, describe, expect, it, vi} from 'vitest';
import {getGestureHost} from '../gestures/GestureHost';
-import {subscribeInput} from './inputStream';
+import {getLastPointerType, subscribeInput} from './inputStream';
import {installPressFeedback} from './pressFeedback';
type Registration = {
@@ -80,6 +82,32 @@ describe('inputStream', () => {
expect(removed.map(r => r.type)).toEqual(['pointerdown']);
});
+ it('runs a first subscriber before the others, even subscribed after them, and its true ends the dispatch', () => {
+ const calls: string[] = [];
+ let isHeld = false;
+ // Only a first subscriber's true ends the dispatch.
+ subscribe(window, 'pointerdown', () => {
+ calls.push('press feedback');
+ return true;
+ });
+ subscribe(
+ window,
+ 'pointerdown',
+ () => {
+ calls.push('hold');
+ return isHeld;
+ },
+ {first: true},
+ );
+ subscribe(window, 'pointerdown', () => calls.push('gesture host'));
+ pointerDown(document.body);
+ expect(calls).toEqual(['hold', 'press feedback', 'gesture host']);
+ calls.length = 0;
+ isHeld = true;
+ pointerDown(document.body);
+ expect(calls).toEqual(['hold']);
+ });
+
it('delivers to every subscriber in subscription order, each isolated from another that throws', () => {
const reported = vi.fn();
vi.stubGlobal('reportError', reported);
@@ -204,6 +232,29 @@ describe('inputStream', () => {
detach();
});
+ it("records the latest delivered pointer event's type, before its subscribers run, and only while one hears pointer events", () => {
+ const view = document.defaultView as Window;
+ const heard: (string | null)[] = [];
+ const stop = subscribeInput(view, 'pointermove', () => {
+ heard.push(getLastPointerType(view));
+ });
+ document.body.dispatchEvent(
+ new PointerEvent('pointermove', {bubbles: true, pointerType: 'mouse'}),
+ );
+ expect(getLastPointerType(view)).toBe('mouse');
+ document.body.dispatchEvent(
+ new PointerEvent('pointermove', {bubbles: true, pointerType: 'touch'}),
+ );
+ expect(heard).toEqual(['mouse', 'touch']);
+ stop();
+
+ // No subscriber, no native listener: the stream hears nothing.
+ document.body.dispatchEvent(
+ new PointerEvent('pointermove', {bubbles: true, pointerType: 'pen'}),
+ );
+ expect(getLastPointerType(view)).toBe('touch');
+ });
+
it('keeps the press feedback controller free of the gesture system', () => {
const utils = path.resolve(__dirname);
const seen = new Set<string>();
diff --git a/packages/core/src/utils/inputStream.ts b/packages/core/src/utils/inputStream.ts
index 663c6bcca6..1fdcc35f8f 100644
--- a/packages/core/src/utils/inputStream.ts
+++ b/packages/core/src/utils/inputStream.ts
@@ -4,7 +4,8 @@
* @file inputStream.ts
* @input A window, and subscribers to its input events (the press feedback
* controller, the gesture host)
- * @output subscribeInput
+ * @output subscribeInput, and getLastPointerType: the type of the latest
+ * pointer event the stream delivered
* @position The one entry for document-wide input listeners in core: one
* native listener per event type on the window's capture phase, shared by
* every subscriber
@@ -22,18 +23,21 @@
// `blur` or `focus`. A subscriber for the window's own event checks
// `event.target`.
//
-// Subscribers run in subscription order. One that throws is reported, and
-// the rest still run.
+// Subscribers run in subscription order, after the ones subscribed `first`.
+// A first subscriber that returns `true` ends the dispatch: no later
+// subscriber hears the event. One that throws is reported, and the rest still
+// run.
//
// A type's native listener is passive, so it blocks no scroll. It is
// non-passive only while a subscriber that cancels the event
// (`{cancels: true}`) is subscribed. With no subscriber left, it is removed.
-type InputListener = (event: Event) => void;
+type InputListener = (event: Event) => unknown;
interface Subscriber {
readonly listener: InputListener;
readonly cancels: boolean;
+ readonly isFirst: boolean;
}
interface Channel {
@@ -50,12 +54,30 @@ export interface InputSubscriptionOptions {
* @default false
*/
readonly cancels?: boolean;
+ /**
+ * The subscriber runs before every subscriber that is not first. When it
+ * returns `true`, no later subscriber hears the event.
+ * @default false
+ */
+ readonly first?: boolean;
}
/** The events a window's capture phase sees: its own, and the document's. */
export type InputEventMap = WindowEventMap & DocumentEventMap;
const streams = new WeakMap<Window, Map<string, Channel>>();
+/** The type of the latest pointer event each window's stream delivered. */
+const lastPointerTypes = new WeakMap<Window, string>();
+
+/**
+ * The type of the latest pointer event `view`'s stream delivered: `mouse`,
+ * `pen` or `touch`, or `null` before any. The stream hears a pointer event
+ * type only while a subscriber listens to it, as press feedback does on any
+ * page with a pressable. Reading it adds no listener.
+ */
+export function getLastPointerType(view: Window): string | null {
+ return lastPointerTypes.get(view) ?? null;
+}
/**
* Listen to `type` on `view`'s capture phase through its shared native
@@ -64,8 +86,8 @@ const streams = new WeakMap<Window, Map<string, Channel>>();
export function subscribeInput<K extends keyof InputEventMap>(
view: Window,
type: K,
- listener: (event: InputEventMap[K]) => void,
- {cancels = false}: InputSubscriptionOptions = {},
+ listener: (event: InputEventMap[K]) => unknown,
+ {cancels = false, first = false}: InputSubscriptionOptions = {},
): () => void {
let channels = streams.get(view);
if (channels == null) {
@@ -80,8 +102,16 @@ export function subscribeInput<K extends keyof InputEventMap>(
const subscriber: Subscriber = {
listener: listener as InputListener,
cancels,
+ isFirst: first,
};
- channel.subscribers.push(subscriber);
+ const firstLater = first
+ ? channel.subscribers.findIndex(other => !other.isFirst)
+ : -1;
+ if (firstLater === -1) {
+ channel.subscribers.push(subscriber);
+ } else {
+ channel.subscribers.splice(firstLater, 0, subscriber);
+ }
register(view, type, channel);
let isSubscribed = true;
return () => {
@@ -124,12 +154,17 @@ function register(view: Window, type: string, channel: Channel): void {
if (wanted == null) {
return;
}
- const listener: InputListener = event => dispatch(channel, event);
+ const listener: InputListener = event => dispatch(view, channel, event);
view.addEventListener(type, listener, {capture: true, passive: !wanted});
channel.native = {listener, cancels: wanted};
}
-function dispatch(channel: Channel, event: Event): void {
+function dispatch(view: Window, channel: Channel, event: Event): void {
+ // Recorded before any subscriber runs, so each reads the pointer at hand.
+ const {pointerType} = event as Partial<PointerEvent>;
+ if (typeof pointerType === 'string' && pointerType !== '') {
+ lastPointerTypes.set(view, pointerType);
+ }
// A subscriber may subscribe or unsubscribe while the event runs; the
// event goes to those subscribed when it arrived.
for (const subscriber of [...channel.subscribers]) {
@@ -137,7 +172,9 @@ function dispatch(channel: Channel, event: Event): void {
continue;
}
try {
- subscriber.listener(event);
+ if (subscriber.listener(event) === true && subscriber.isFirst) {
+ return;
+ }
} catch (error) {
report(error);
}
diff --git a/packages/core/src/utils/selectionLock.ts b/packages/core/src/utils/selectionLock.ts
index 180334113d..9ca4f1f196 100644
--- a/packages/core/src/utils/selectionLock.ts
+++ b/packages/core/src/utils/selectionLock.ts
@@ -28,7 +28,11 @@
//
// A mouse never takes the lock, so its released behavior stays (AST-017).
-import {containsAlongFlatTree, parentAcrossShadow} from './flatTree';
+import {
+ containsAlongFlatTree,
+ deepActiveElement,
+ parentAcrossShadow,
+} from './flatTree';
import {subscribeInput} from './inputStream';
import {isIosWebKit} from './touchQueries';
@@ -616,15 +620,6 @@ function openShadowRootsOf(target: EventTarget | null): ShadowRoot[] {
return roots;
}
-/** The focused element, inside open shadow roots too. */
-function deepActiveElement(doc: Document | null): Element | null {
- let active = doc?.activeElement ?? null;
- while (active?.shadowRoot?.activeElement != null) {
- active = active.shadowRoot.activeElement;
- }
- return active;
-}
-
/**
* The selection-lock styles on `set`, refcounted per element; idempotent
* release.
diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs
index af25cc6328..2b7504521c 100644
--- a/scripts/touch-support-bundle.test.mjs
+++ b/scripts/touch-support-bundle.test.mjs
@@ -359,6 +359,22 @@ describe('the touch module in bundles', () => {
}
});
+ it('is absent from a component that holds its layer (Layer/inputHold)', () => {
+ // A component in the root entry may hold its layer's input statically
+ // (a popover's presentation): the hold brings no gesture code with it.
+ const holder = entryWith(
+ 'Holder.ts',
+ `import {holdInput} from ${JSON.stringify(
+ path.join(CORE_SRC, 'Layer/inputHold.ts'),
+ )};
+export const Holder = holdInput;
+`,
+ );
+ for (const bytes of outputsOf([holder])) {
+ expect(bytesOf(bytes)).toEqual([]);
+ }
+ });
+
it('is one copy that two components importing it share', () => {
const component = name =>
entryWith(