diff --git a/.changeset/menu-outside-tap-swallow.md b/.changeset/menu-outside-tap-swallow.md new file mode 100644 index 0000000000000..dbdd75c01df0c --- /dev/null +++ b/.changeset/menu-outside-tap-swallow.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] Under a finger or a pen, a touch outside an open DropdownMenu now only closes it, as a native menu's does. The control under the finger no longer gets the touch's press, its compatibility mouse events or its click. A tap closes the menu at its lift, and a pan as it begins; the page still scrolls and zooms. A mouse and `presentation="popover"` keep their behavior. + +@vjeux diff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsx index 69383fc38da93..a6ef35c3038d3 100644 --- a/apps/storybook/stories/DropdownMenu.stories.tsx +++ b/apps/storybook/stories/DropdownMenu.stories.tsx @@ -4,7 +4,7 @@ import type {Meta, StoryObj} from '@storybook/react'; import * as stylex from '@stylexjs/stylex'; import {Badge} from '@astryxdesign/core/Badge'; import {IconButton} from '@astryxdesign/core/IconButton'; -import {useState} from 'react'; +import {useMemo, useState} from 'react'; import { DropdownMenu, DropdownMenuItem, @@ -21,6 +21,10 @@ import {CheckboxInput} from '@astryxdesign/core/CheckboxInput'; import {Switch} from '@astryxdesign/core/Switch'; import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList'; import {TextInput} from '@astryxdesign/core/TextInput'; +import {List, ListItem} from '@astryxdesign/core/List'; +import {Slider} from '@astryxdesign/core/Slider'; +import {createSwipe} from '@astryxdesign/core/Swipe'; +import {Switch} from '@astryxdesign/core/Switch'; import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex'; import { PencilIcon, @@ -87,6 +91,30 @@ type Story = StoryObj; // Story args the tooltip regression spec drives through the URL. type StoryArgs = Omit; +const outsideTouchStyles = stylex.create({ + page: { + display: 'flex', + flexDirection: 'column', + alignItems: 'flex-start', + gap: spacingVars['--spacing-4'], + }, + // Below where the open menu reaches, so a touch can land beside it. + controls: { + display: 'flex', + flexDirection: 'column', + gap: spacingVars['--spacing-4'], + marginTop: 240, + width: 320, + }, + scroller: { + height: 160, + overflowY: 'auto', + }, + scrollerRow: { + paddingBlock: spacingVars['--spacing-2'], + }, +}); + const readinessStyles = stylex.create({ viewportStoryCanvas: { boxSizing: 'border-box', @@ -1838,3 +1866,91 @@ export const InClosedInFlowDialog: Story = { ); }, }; + +/** + * A menu above controls that act on a touch: a Switch, a Slider, a list that + * scrolls and a row with a swipe action. Each control shows what reached it. + * A touch outside the open menu reaches none of them, and a pan outside it + * still scrolls the list. + */ +export const OutsideTapReachesNothing: Story = { + render: ({presentation: _, ...args}: StoryArgs) => { + const [isOn, setIsOn] = useState(false); + const [switchActs, setSwitchActs] = useState(0); + const [level, setLevel] = useState(50); + const [sliderActs, setSliderActs] = useState(0); + const [scrollOffset, setScrollOffset] = useState(0); + const [swipes, setSwipes] = useState(0); + const swipe = useMemo( + () => + createSwipe({ + trailing: [ + { + id: 'archive', + label: 'Archive', + onActivate: () => setSwipes(count => count + 1), + }, + ], + swipeBehavior: 'commit', + }), + [], + ); + return ( +
+ + {}} /> + {}} /> + {}} /> + +
+ { + setIsOn(checked); + setSwitchActs(count => count + 1); + }} + /> + Switch acts: {switchActs} + { + setLevel(value); + setSliderActs(count => count + 1); + }} + /> + Slider acts: {sliderActs} +
+ setScrollOffset(Math.round(event.currentTarget.scrollTop)) + }> + {Array.from({length: 30}, (_, index) => ( +
+ Row {index + 1} +
+ ))} +
+ + Scroll offset: {scrollOffset}px + + + {}} + /> + + Swipes: {swipes} +
+
+ ); + }, +}; diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md index 1ce1093203dbd..b397fe34d6db7 100644 --- a/docs/architecture/layer-runtime.md +++ b/docs/architecture/layer-runtime.md @@ -710,7 +710,13 @@ layers use Layer rendering without joining Escape/platform dismissal. are for their dismissal. A blur hold leaves a nested layer, its path, and a child live region live, such as a toast viewport that a leaving alert hosts. The component - still decides where focus returns. A component that holds input uses this hold rather + still decides where focus returns. An anchored menu that is open under the + touch presentation takes the hold's `'outside'` scope (`spec:AST-094` + FR32). A finger's or a pen's press that starts outside the menu, its + trigger and any live shield is held to its end. None of its events reaches + the page. Its moves are never canceled, so a pan still scrolls the page and + a pinch still zooms it. The menu closes as the press begins to pan or at + its lift, and the newest menu's scope decides. A component that holds input uses this hold rather than building its own. It is separate from INV14's presentation hold, which keeps a layer's chosen presentation. - **INV17 — A click inside a layer stops at the layer root.** A pointer, @@ -1001,7 +1007,7 @@ this current architecture record. | INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests; `useBackdropPress.test.tsx`; `outsidePress.test.ts` | A current local channel silently changes ownership or policy | | INV10 | `LayerProvider.tsx`, `toastHost.tsx`, `LayerProvider.test.tsx`, `toastHost.test.tsx`, `toastHost.lateRegistration.test.tsx`, `useToast.tsx`, `ToastViewport.test.tsx`, `ToastViewport.modalHost.test.tsx`, and `scripts/layer-toast-bundle.test.mjs` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, a default provider renders differently from no provider, a Layer import loads a Toast module, or a toast added before Toast loads is lost | | INV14, INV15 | Source boundary check over Core for top-layer hosts, exit copies, backdrop elements, lift, and rectangle-morph code outside the runtime and the lift module | A component building its own copy of a mechanism INV14 lists (top-layer mounting, close-request delivery, hold, exit copy, or backdrop element), or re-implementing the lift or the grow | -| INV16 | `inputHold.test.tsx` (including its `'kept-inside'` dismissal cases), `holdEntranceInput.test.ts`, `inputHold.interaction.browser.spec.ts`, and `BottomSheetCloseFocus.test.tsx`; the Dialog and Drawer touch-entrance proofs in Chromium and WebKit | A component that holds input on its own, a held key or assistive-technology action during a presentation, a pinch that no longer zooms, or a dismissal that lets its content be activated, inert content that still holds focus, or content made inert or blurred while focus stays inside a layer whose record keeps it live fails | +| INV16 | `inputHold.test.tsx` (including its `'kept-inside'` dismissal cases), `holdEntranceInput.test.ts`, `inputHold.interaction.browser.spec.ts`, and `BottomSheetCloseFocus.test.tsx`; the Dialog and Drawer touch-entrance proofs in Chromium and WebKit; its `'outside'` cases and `DropdownMenuOutsideTap.test.tsx` | A component that holds input on its own, a held key or assistive-technology action during a presentation, a pinch that no longer zooms, or a dismissal that lets its content be activated, inert content that still holds focus, or content made inert or blurred while focus stays inside a layer whose record keeps it live, or an outside press that reaches the page or cancels a move, fails | | INV17 | One runtime suite over every kind of layer root: a `useLayer` layer, inline and portaled, and the Dialog, Drawer, Lightbox, MobileNav, BottomSheetPanel, and ToastViewport content roots, each inside a plain `onClick` wrapper and a Core clickable container; nested layers | A click inside a layer root that reaches an ancestor bubble-phase handler, a caller's wrapper included; an outer layer's handler that receives an inner layer's press; or a document listener or light dismiss that no longer receives it | | INV18 | `useLayer.test.tsx` (a closed trigger has no anchor-name, and the trigger of a shown or fading layer does) and `TooltipClosedTriggerAnchor.interaction.browser.spec.ts` in Chromium and WebKit | A closed trigger with an anchor-name, a shown or fading layer placed away from its anchor, or a surface around a closed trigger that stops while the main thread is busy | | INV18 | `useLayer.test.tsx`: a closed state that declares a discrete `display` transition or a keyframe animation keeps the trigger's anchor name until those animations end, read from the closed state's style; a layer whose closed state declares neither is not read for animations at the close | A layer with such a closed-state exit placed away from its anchor while it fades, or an animation read on the close of a layer whose closed state declares no exit | diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index 15363bb922a7c..e9c5c44f13c63 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -681,8 +681,10 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and programmatic open and a press the menu's press model ignores, such as a second finger. - **FR32 — A pan outside dismisses.** Under a finger, an open anchored menu MUST close as a touch outside it - begins to pan, and at the lift of a tap or hold outside it. A Popover's - dismissal is unchanged. A pinch stays available over it: its surface + begins to pan, and at the lift of a tap or hold outside it. A tap outside + closes the menu and reaches nothing beneath it, under a finger or pen. The + dismissing touch, like UIKit's, reaches nothing beneath; native scrolling + continues. A Popover's dismissal is unchanged. A pinch stays available over it: its surface never takes `touch-action: none`, so the page keeps zooming unless the author's own `touch-action` leaves out `pinch-zoom` (FR10, FR18; WCAG 2.2 SC 1.4.4). Listening for that outside touch costs nothing once it ends (FR24). A menu diff --git a/docs/specs/components/DropdownMenu/DropdownMenu.spec.md b/docs/specs/components/DropdownMenu/DropdownMenu.spec.md index e67be234c3e9e..9291c1b6a1731 100644 --- a/docs/specs/components/DropdownMenu/DropdownMenu.spec.md +++ b/docs/specs/components/DropdownMenu/DropdownMenu.spec.md @@ -14,6 +14,8 @@ verified_by: [ packages/core/src/DropdownMenu/DropdownMenu.test.tsx, packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx, + packages/core/src/DropdownMenu/DropdownMenuOutsideTap.test.tsx, + packages/core/src/DropdownMenu/__tests__/DropdownMenuOutsideTap.interaction.browser.spec.ts, packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts, packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts, packages/core/src/DropdownMenu/__tests__/DropdownMenuTouchPress.interaction.browser.spec.ts, @@ -42,15 +44,15 @@ system_specs: [spec:AST-020/FR15, spec:AST-094, spec:AST-102, spec:AST-116] ## Contract at a glance -| Area | Contract | -| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Public contract | None changes. DropdownMenu takes a `button` (Button props) or `renderTrigger`, data-driven `items` or compound children, `presentation`, `isMenuOpen` and `onOpenChange`, placement and alignment, `menuMaxHeight`, `header`, and `footer`. | -| Behavior | A Menu Button trigger opens an anchored pointer menu or a bottom-sheet action list. Rows act on the release under the shared press model; sub-menus fly out beside their row or drill in on a compact touch display; a header or footer makes the pointer popover a modal dialog around the menu. | -| End-user impact | People pick actions by mouse, finger, or keyboard; keyboard users get a focus return with a ring and pointer users without one; on a phone sub-menus replace the rows instead of flying off-screen. Under a finger the menu opens as the finger presses, or after the content-touch delay inside a scroll view; it grows out of its trigger and shrinks back into it, and a pan outside does not close it. | -| Builder impact | Builders choose the trigger, the rows, and the regions; rows stay menu items and every non-item control goes in `header` or `footer`. | -| Compatibility/readiness | Records shipped behavior; no API change; a disabled row gains `tabindex="-1"`; the released behavior under a finger moves as `spec:AST-094` FR25 lists, with `presentation="popover"` keeping it. Pan dismissal (FR21), the still mouse (FR22), and Trigger Button gaps are in Current-state impact. | -| Review checks | Reject a control placed among the rows, a lost trigger ARIA wiring, a drilled-in view that leaves the menu box, a header or footer without the dialog, a lost focus-return modality, or a target moved off its painted element. | -| Governing rules | `spec:AST-020` FR15; `spec:AST-094` FR26–FR35; `module:DropdownMenu/useMenuPress`; `architecture:interaction-modality` INV1; `architecture:component-theming-surface`; `architecture:layer-runtime`; `family:overlay-dismissal`; `family:navigation-destinations`. | +| Area | Contract | +| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Public contract | None changes. DropdownMenu takes a `button` (Button props) or `renderTrigger`, data-driven `items` or compound children, `presentation`, `isMenuOpen` and `onOpenChange`, placement and alignment, `menuMaxHeight`, `header`, and `footer`. | +| Behavior | A Menu Button trigger opens an anchored pointer menu or a bottom-sheet action list. Rows act on the release under the shared press model; sub-menus fly out beside their row or drill in on a compact touch display; a header or footer makes the pointer popover a modal dialog around the menu. | +| End-user impact | People pick actions by mouse, finger, or keyboard; keyboard users get a focus return with a ring and pointer users without one; on a phone sub-menus replace the rows instead of flying off-screen. Under a finger the menu opens as the finger presses, or after the content-touch delay inside a scroll view; it grows out of its trigger and shrinks back into it. | +| Builder impact | Builders choose the trigger, the rows, and the regions; rows stay menu items and every non-item control goes in `header` or `footer`. | +| Compatibility/readiness | Records shipped behavior; no API change; a disabled row gains `tabindex="-1"`; the released behavior under a finger moves as `spec:AST-094` FR25 lists, with `presentation="popover"` keeping it. The still mouse (FR22) and Trigger Button gaps are in Current-state impact. | +| Review checks | Reject a control placed among the rows, a lost trigger ARIA wiring, a drilled-in view that leaves the menu box, a header or footer without the dialog, a lost focus-return modality, or a target moved off its painted element. | +| Governing rules | `spec:AST-020` FR15; `spec:AST-094` FR26–FR35; `module:DropdownMenu/useMenuPress`; `architecture:interaction-modality` INV1; `architecture:component-theming-surface`; `architecture:layer-runtime`; `family:overlay-dismissal`; `family:navigation-destinations`. | This table is a review projection; the body below is authoritative. @@ -146,7 +148,7 @@ component-local concepts; each keeps its released default. | FR16 | Checkbox rows follow `component:DropdownMenuCheckboxItem`. | Current source | | FR17 | A disabled menu row MUST be reached by the keyboard and stay inert (DEC-11): in DropdownMenu, its sub-menus, MoreMenu, ContextMenu and NavHeadingMenu, ArrowDown, ArrowUp, Home, End and type-ahead visit a disabled row as they visit any other row, the row takes focus and exposes `aria-disabled="true"`, and Enter, Space or a click on it does nothing and leaves the menu open. Opening a menu from the keyboard still lands on an enabled row: the first, or the last after ArrowUp on the trigger (FR12, AR4). | DEC-11; WAI-ARIA Menu pattern | | FR20 | With `header` or `footer` on a sub-menu (`DropdownMenuSubMenu`), its surface is a modal dialog named by its row (AR7), holding the header, the sub-menu's `role="menu"` (rows only), then the footer. It sits in a host `DropdownMenu` renders beside its menu, never inside a menu; under a root with no such host (`ContextMenu`) the sub-menu shows its rows alone. On a fine pointer the dialog is the flyout; on a compact touch display, the drilled-in view, which replaces the root's menu and regions until popped. A region keeps its own keys and presses. The rows are one Tab stop: Tab and Shift+Tab walk the header's controls, the rows, then the footer's, and wrap; from a deeper flyout, that flyout closes and the walk goes on from the rows. An open lands as for any sub-menu (FR11, FR12), not on a region. Escape in the dialog, outside an IME composition and unless a control there handled it, returns focus to the row and leaves the root open. A pointer leaving the flyout keeps it open until focus leaves, and it closes with the flyout holding its row. Without either prop nothing changes. | Current behavior; FR15; AR5 | -| FR21 | Under a finger, in the touch modes (`presentation` not pinned to `'popover'`), the pointer menu MUST grow out of the Trigger button on the theme's entrance duration and easing tokens and collapse back into it on the theme's exit duration and easing (`spec:AST-094` FR7, FR31, FR45), and MUST close as a pan that starts outside it begins (FR32); a pinned `'popover'` keeps the layer's own entrance. A pan dismissal is the menu's own close: focus that was in the menu returns to the Trigger button, whose `aria-expanded` turns false. A finger's or a pen's open grows the menu, a tap's open at its lift included, and the grow follows the popover's path. A mouse and the keyboard keep the layer's own entrance and exit. Under Reduce Motion, where the primary pointer is coarse, the menu fades in at its size and fades out where it stands (`design:reduced-motion` DR2). Under a coarse primary pointer, taps stay held from the open until the menu is visible. Implementation gap: the menu has no pan-outside dismissal of its own. | `spec:AST-094` FR31, FR32; `family:overlay-dismissal` AV6 | +| FR21 | Under a finger, in the touch modes (`presentation` not pinned to `'popover'`), the pointer menu MUST grow out of the Trigger button on the theme's entrance duration and easing tokens and collapse back into it on the theme's exit duration and easing (`spec:AST-094` FR7, FR31, FR45), and MUST close as a pan that starts outside it begins (FR32); a pinned `'popover'` keeps the layer's own entrance. A pan dismissal is the menu's own close: focus that was in the menu returns to the Trigger button, whose `aria-expanded` turns false. A finger's or a pen's open grows the menu, a tap's open at its lift included, and the grow follows the popover's path. A mouse and the keyboard keep the layer's own entrance and exit. Under Reduce Motion, where the primary pointer is coarse, the menu fades in at its size and fades out where it stands (`design:reduced-motion` DR2). Under a coarse primary pointer, taps stay held from the open until the menu is visible. | `spec:AST-094` FR31, FR32; `family:overlay-dismissal` AV6 | | FR22 | Under a finger, in the touch modes, where the primary pointer is coarse (a phone or a tablet), a tap or a drag that lands while the pointer menu enters MUST reach nothing: it closes nothing, scrolls nothing, moves no focus and clicks nothing (`spec:AST-094` FR35). The finger that opened the menu still picks the row it lifts on (FR8). Keys and assistive technology stay live. A mouse, a pinned `'popover'` and a finger where the primary pointer is fine (a touchscreen laptop) hold nothing, as for `component:Drawer`. Implementation gap: after a finger, a still mouse's first press lands on the entering menu's shield unless the mouse rests where the page last heard it when the shield came up (`spec:AST-094` FR35). | `spec:AST-094` FR35; `architecture:layer-runtime` | | FR23 | Tab or Shift+Tab on a row at any level of a menu without `header` or `footer`, its own rows or an open sub-menu flyout's at any depth, closes every open level and the menu, calls `onOpenChange(false)` once, and leaves focus to move on from the trigger in page order (WAI-ARIA Menu Button). A level with a header or footer keeps FR15's and FR20's Tab cycle within it. | WAI-ARIA Menu Button pattern; current tests | | FR24 | A sub-menu row's chevron points the way its sub-menu opens, and a Back control's chevron points the way it returns, in the menu's own direction (its nearest `dir`), not the page's: in the pointer menu, its flyouts and drill-in views, and the touch sheet, in DropdownMenu and in ContextMenu (`docs/design/bidirectionality.md` DR6). | Bidirectionality guide DR6; current tests | | @@ -376,7 +378,7 @@ than adding a DropdownMenu-owned heading target. | FR15, AR5 | `DropdownMenu.test.tsx` header and footer cases, including the hidden-control, open-sub-menu, and header radio-group cases; `MenuHeaderFooter.a11y.chromium.spec.ts` | Regions present and absent; hidden controls; open flyout; custom trigger; bottom sheet | A region inside the menu, a missing or unnamed dialog, a wrong `aria-haspopup`, a Tab that leaves the popover, a hidden control taken as a stop, or a region whose keys the menu takes fails. | `audit:DropdownMenu/accessibility` | | FR17, AR6 | DropdownMenu, MoreMenu, ContextMenu and NavHeadingMenu keyboard tests, plus a real-browser keyboard check of focus order and blocked activation and a real-browser accessibility-tree check that a focused disabled row is announced as disabled (`spec:AST-085` Platform support); disabled-row cases | Disabled rows | A disabled row that runs a caller handler, closes the menu, is skipped by the arrow keys or type-ahead, or is not announced as disabled fails. | `audit:DropdownMenu/accessibility` | | FR20, AR7 | `DropdownMenuSubMenu.test.tsx` header and footer cases, including "on a phone"; `SubMenuHeaderFooter.a11y.chromium.spec.ts`; `ContextMenu.test.tsx` "shows a sub-menu with a header or footer as its rows alone, and says why in development" | Fine pointer and phone; Escape paths; nested flyouts; pointer leaving | A region inside a menu, an unnamed dialog, a Tab walk that does not wrap, an Escape that closes the root, or a flyout that closes while focus is inside fails. | `audit:DropdownMenu/accessibility` | -| FR21 | `DropdownMenuTouchGrow.test.tsx` (which opens grow); `DropdownMenuTouchGrow.interaction.browser.spec.ts` (Chromium, WebKit): the first tap after load, a tap in scrolling content and a held finger grow the menu out of its trigger, on the popover's path and timing. Evidence gap: pan dismissal, matching the FR21 gap | — | — | `audit:DropdownMenu/behavior` | +| FR21 | `DropdownMenuTouchGrow.test.tsx` (which opens grow); `DropdownMenuTouchGrow.interaction.browser.spec.ts` (Chromium, WebKit): the first tap after load, a tap in scrolling content and a held finger grow the menu out of its trigger, on the popover's path and timing. `DropdownMenuOutsideTap.test.tsx` and its browser spec (Chromium, WebKit): the menu closes as a pan outside begins | a pan, a tap and a pinch outside under a finger or pen | A pan outside that leaves the menu open, or an outside touch that reaches the control beneath, fails | `audit:DropdownMenu/behavior` | | FR22 | `DropdownMenu.test.tsx` "DropdownMenu entrance under a finger" cases; `useMenuPress.test.tsx` "an input hold over the menu" cases; `DropdownMenuEntranceHold.interaction.browser.spec.ts` | A tap outside and a finger's slide while the menu enters; a mouse click | A tap during the entrance that closes the menu, clicks the page or moves focus, a slide that picks nothing, or a held mouse fails. | `audit:DropdownMenu/behavior` | | FR23 | `DropdownMenu.test.tsx` Tab cases; `DropdownMenuSubMenu.test.tsx` "Tab from a flyout leaves the whole menu" suite | top level, one and two levels down, Shift+Tab | A Tab that leaves any level open, a second `onOpenChange(false)`, or a prevented Tab fails. | `audit:DropdownMenu/accessibility` | | FR24 | `DropdownMenuSubMenu.test.tsx` direction cases (flyout and drill-in); `DropdownMenu.test.tsx` and `ContextMenu.test.tsx` "points the sheet … chevron by the menu direction, not the page" | an LTR menu in an RTL page and an RTL menu in an LTR page, flyout, drill-in and touch sheet | A chevron that flips by the page's direction instead of the menu's fails. | `audit:DropdownMenu/accessibility` | @@ -386,8 +388,6 @@ than adding a DropdownMenu-owned heading target. ## Current-state impact -- **Pan dismissal (FR21).** Under a finger a pan that starts outside the menu - does not close it, against `spec:AST-094` FR32. - **Still mouse after a finger (FR22).** Known gap: after a finger, a still mouse's first press does nothing unless the mouse rests where the page last heard it when the entering menu's shield came up. diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx index 4d5cfcb161326..9b2de45891825 100644 --- a/packages/core/src/DropdownMenu/DropdownMenu.tsx +++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx @@ -45,11 +45,13 @@ import React, { useState, type ReactNode, } from 'react'; -import {useCommittedRefInto} from '../hooks/useCommittedRef'; +import {useCommittedRef, useCommittedRefInto} from '../hooks/useCommittedRef'; import {labelledByText, readAccessibleName} from '../utils/accessibleName'; import * as stylex from '@stylexjs/stylex'; import {usePopoverInternal} from '../Popover/usePopover'; import {holdEntranceInput} from '../Layer/holdEntranceInput'; +import {holdInput} from '../Layer/inputHold'; +import {hasPanBegun, noteOutsideDismissal} from '../Layer/outsidePress'; import {usePopoverSurfaceMotion} from '../Popover/usePopoverSurfaceMotion'; import { claimPress, @@ -1057,6 +1059,10 @@ function DropdownMenuPopover({ // the list ref exists, and its release is kept for the close. const holdEntranceRef = useRef<() => void>(() => {}); const releaseEntranceRef = useRef<(() => void) | null>(null); + // The outside hold also starts as the layer shows, and its release is kept + // for the close. + const holdOutsideRef = useRef<() => void>(() => {}); + const releaseOutsideRef = useRef<(() => void) | null>(null); // The trigger press that asks the menu to open. The show holds the trigger // as the invoker through that press; that hold is set below, once the // popover exists. @@ -1124,6 +1130,8 @@ function DropdownMenuPopover({ touchOpenRef.current = null; releaseEntranceRef.current?.(); releaseEntranceRef.current = null; + releaseOutsideRef.current?.(); + releaseOutsideRef.current = null; // Whatever closed the menu — light dismiss, the dismissal stack, Escape // or a controlled close — its flyouts close with it. hideOpenFlyouts(); @@ -1199,6 +1207,7 @@ function DropdownMenuPopover({ presentSurfaceRef.current(); touchOpenRef.current = null; holdEntranceRef.current(); + holdOutsideRef.current(); resetFocusReturn(); if (renderTrigger != null) { setTriggerName(readAccessibleName(buttonRef.current)); @@ -1407,11 +1416,39 @@ function DropdownMenuPopover({ // The show's entrance hold, written at commit before any layout effect. The // controlled-open layout effect above can show the menu then. useCommittedRefInto(holdEntranceRef, holdEntrance); - // The layer runtime's input hold: an unmount during the entrance releases it. + + // Under the touch presentation, a finger's or a pen's touch outside the open + // menu only closes it, as a native menu's does. Nothing beneath gets it. + const closeMenuRef = useCommittedRef(closeMenu); + const holdOutside = useCallback(() => { + releaseOutsideRef.current?.(); + const layer = + pressTouchModel === 'uikit' + ? listRef.current?.closest('[popover]') + : null; + releaseOutsideRef.current = + layer == null + ? null + : holdInput(layer, { + scope: 'outside', + owner: buttonRef.current, + hasPanBegun, + onOutside: () => { + noteOutsideDismissal(layer.ownerDocument); + closeMenuRef.current(); + }, + }); + }, [listRef, pressTouchModel, closeMenuRef]); + useCommittedRefInto(holdOutsideRef, holdOutside); + + // The layer runtime's input holds: an unmount during the entrance, or while + // the menu is open, releases them. useEffect( () => () => { releaseEntranceRef.current?.(); releaseEntranceRef.current = null; + releaseOutsideRef.current?.(); + releaseOutsideRef.current = null; }, [], ); diff --git a/packages/core/src/DropdownMenu/DropdownMenuOutsideTap.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuOutsideTap.test.tsx new file mode 100644 index 0000000000000..02a11b819dac5 --- /dev/null +++ b/packages/core/src/DropdownMenu/DropdownMenuOutsideTap.test.tsx @@ -0,0 +1,554 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file DropdownMenuOutsideTap.test.tsx + * @input An open DropdownMenu above a control, under a coarse primary + * pointer. A tap, a pan, a pinch or a mouse press outside the menu, as + * pointer, touch and mouse events in jsdom + * @output Under the touch presentation, a finger's or a pen's touch outside + * the open menu reaches nothing beneath. That holds for its pointer, touch + * and mouse events and its click, also when the touchstart was not + * cancelable. A tap closes + * the menu at its lift, and a pan as it begins. The pan and a pinch are not + * canceled, and the next touch acts. A mouse press outside and + * `presentation="popover"` keep their behavior. + * @position Unit evidence for DropdownMenu's outside touch, through the + * input hold's `'outside'` scope. The browser half is + * __tests__/DropdownMenuOutsideTap.interaction.browser.spec.ts + */ + +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {useState} from 'react'; +import {DropdownMenu} from './DropdownMenu'; +import {DropdownMenuItem} from './DropdownMenuItem'; +import {__resetMenuPressForTest} from '../hooks/useMenuPress'; +import {CLICK_GUARD_WINDOW_MS} from '../utils/clickGuard'; +import {TOUCH_QUERY} from '../utils/touchPresentation'; + +interface TouchOptions { + readonly cancelable?: boolean; + /** The identifiers of the touches still on the screen after the event. */ + readonly down?: ReadonlyArray; +} + +/** A touch event at `target` whose changed touches have `identifiers`. */ +function fireTouch( + target: Element, + type: 'touchstart' | 'touchmove' | 'touchend', + identifiers: number | ReadonlyArray, + {cancelable = true, down}: TouchOptions = {}, +): Event { + const changed = typeof identifiers === 'number' ? [identifiers] : identifiers; + const event = new Event(type, {bubbles: true, cancelable}); + Object.defineProperty(event, 'changedTouches', { + value: changed.map(identifier => ({identifier, target})), + }); + const still = down ?? (type === 'touchend' ? [] : changed); + Object.defineProperty(event, 'touches', { + value: still.map(identifier => ({identifier, target})), + }); + target.dispatchEvent(event); + return event; +} + +function pointer( + pointerType: 'touch' | 'pen' | 'mouse', + pointerId: number, + x = 10, + y = 10, +) { + return {pointerType, pointerId, isPrimary: true, clientX: x, clientY: y}; +} + +/** A finger's tap or a pen's at `target`, up to its lift. */ +function tapAt( + target: Element, + pointerType: 'touch' | 'pen', + {id = 9, touchStartCancelable = true} = {}, +): void { + fireEvent.pointerDown(target, pointer(pointerType, id)); + if (pointerType === 'touch') { + fireTouch(target, 'touchstart', id, {cancelable: touchStartCancelable}); + } + fireEvent.pointerUp(target, pointer(pointerType, id)); +} + +/** The browser's click for a touch: only after a touchend nothing canceled. */ +function browserClickAfter(touchEnd: Event, target: Element): void { + if (!touchEnd.defaultPrevented) { + target.dispatchEvent( + new MouseEvent('click', {bubbles: true, cancelable: true, detail: 1}), + ); + } +} + +/** Dispatches mouse events at `target`; returns each one. */ +function mouseEvents( + target: Element, + types: ReadonlyArray<'mousedown' | 'mouseup' | 'click'>, +): MouseEvent[] { + return types.map(type => { + const event = new MouseEvent(type, { + bubbles: true, + cancelable: true, + detail: 1, + }); + target.dispatchEvent(event); + return event; + }); +} + +/** + * A control that acts on press, as a Switch or a slider thumb does. It logs + * each event that reaches it. + */ +function PressControl({ + label, + heard, +}: { + label: string; + heard: (type: string) => void; +}) { + const log = (event: {type: string}) => { + heard(event.type); + }; + return ( + + ); +} + +/** Renders a menu above a press-acting control and opens it. */ +async function openMenuOver(presentation?: 'popover') { + const heard: string[] = []; + render( + <> + heard.push(type)} /> + + {}} /> + {}} /> + + , + ); + const trigger = screen.getByRole('button', {name: /Actions/}); + fireEvent.click(trigger); + await waitFor(() => { + expect(trigger).toHaveAttribute('aria-expanded', 'true'); + }); + return { + heard, + trigger, + beneath: screen.getByRole('button', {name: 'Beneath'}), + }; +} + +/** A menu whose open state its caller owns. */ +function ControlledMenu({ + onOpenChange, +}: { + onOpenChange: (isOpen: boolean) => void; +}) { + const [isOpen, setIsOpen] = useState(false); + return ( + { + onOpenChange(next); + setIsOpen(next); + }}> + {}} /> + + ); +} + +/** A menu whose app shows a scrim only while the menu is open. */ +function MenuWithScrim() { + const [isOpen, setIsOpen] = useState(false); + return ( + <> + {isOpen ?
: null} + + {}} /> + + + ); +} + +describe('DropdownMenu: a touch outside the open menu (spec:AST-094 FR32)', () => { + beforeEach(() => { + __resetMenuPressForTest(); + vi.stubGlobal( + 'matchMedia', + vi.fn().mockImplementation((query: string) => ({ + matches: query === TOUCH_QUERY || query === '(pointer: coarse)', + media: query, + onchange: null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + ); + }); + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + __resetMenuPressForTest(); + }); + + it("a finger's tap closes the menu at its lift, and nothing beneath hears it: no pointer, touch or mouse event, and no click", async () => { + const {heard, trigger, beneath} = await openMenuOver(); + tapAt(beneath, 'touch'); + expect(trigger).toHaveAttribute('aria-expanded', 'false'); + const touchEnd = fireTouch(beneath, 'touchend', 9); + expect(touchEnd.defaultPrevented).toBe(true); + browserClickAfter(touchEnd, beneath); + expect(heard).toEqual([]); + }); + + it('after a touchstart that was not cancelable, the compatibility mouse events and click that follow the canceled touchend reach nothing beneath', async () => { + const {heard, trigger, beneath} = await openMenuOver(); + vi.useFakeTimers(); + tapAt(beneath, 'touch', {touchStartCancelable: false}); + expect(fireTouch(beneath, 'touchend', 9).defaultPrevented).toBe(true); + vi.advanceTimersByTime(20); + const late = mouseEvents(beneath, ['mousedown', 'mouseup', 'click']); + expect(late.map(event => event.defaultPrevented)).toEqual([ + true, + true, + true, + ]); + expect(heard).toEqual([]); + expect(trigger).toHaveAttribute('aria-expanded', 'false'); + }); + + it("in a Home Screen web app, WebKit's late click, which names the mouse, reaches nothing beneath", async () => { + const {heard, beneath} = await openMenuOver(); + vi.useFakeTimers(); + tapAt(beneath, 'touch', {touchStartCancelable: false}); + expect(fireTouch(beneath, 'touchend', 9).defaultPrevented).toBe(true); + vi.advanceTimersByTime(20); + const [mouseDown, mouseUp] = mouseEvents(beneath, ['mousedown', 'mouseup']); + const click = new MouseEvent('click', { + bubbles: true, + cancelable: true, + detail: 1, + }); + Object.defineProperty(click, 'pointerType', {value: 'mouse'}); + beneath.dispatchEvent(click); + expect( + [mouseDown, mouseUp, click].map(event => event.defaultPrevented), + ).toEqual([true, true, true]); + expect(heard).toEqual([]); + }); + + it("a mouse's press within the click window keeps its click", async () => { + const {heard, beneath} = await openMenuOver(); + vi.useFakeTimers(); + tapAt(beneath, 'touch'); + expect(fireTouch(beneath, 'touchend', 9).defaultPrevented).toBe(true); + vi.advanceTimersByTime(50); + fireEvent.pointerDown(beneath, pointer('mouse', 1)); + const [mouseDown] = mouseEvents(beneath, ['mousedown']); + fireEvent.pointerUp(beneath, pointer('mouse', 1)); + const [mouseUp] = mouseEvents(beneath, ['mouseup']); + const click = new MouseEvent('click', { + bubbles: true, + cancelable: true, + detail: 1, + }); + Object.defineProperty(click, 'pointerType', {value: 'mouse'}); + beneath.dispatchEvent(click); + expect( + [mouseDown, mouseUp, click].map(event => event.defaultPrevented), + ).toEqual([false, false, false]); + expect(heard).toEqual([ + 'pointerdown', + 'mousedown', + 'pointerup', + 'mouseup', + 'click', + ]); + }); + + it("a pen's tap closes the menu at its lift, and nothing beneath hears it", async () => { + const {heard, trigger, beneath} = await openMenuOver(); + tapAt(beneath, 'pen'); + const [mouseUp, click] = mouseEvents(beneath, ['mouseup', 'click']); + expect(mouseUp.defaultPrevented).toBe(true); + expect(click.defaultPrevented).toBe(true); + expect(heard).toEqual([]); + expect(trigger).toHaveAttribute('aria-expanded', 'false'); + }); + + it('a pan closes the menu as it begins, and the page keeps it: no touchstart or touchmove is canceled, and nothing beneath hears it', async () => { + const {heard, trigger, beneath} = await openMenuOver(); + fireEvent.pointerDown(beneath, pointer('touch', 9, 10, 100)); + const touchStart = fireTouch(beneath, 'touchstart', 9); + fireEvent.pointerMove(beneath, pointer('touch', 9, 10, 95)); + expect(trigger).toHaveAttribute('aria-expanded', 'true'); + fireEvent.pointerMove(beneath, pointer('touch', 9, 10, 80)); + expect(trigger).toHaveAttribute('aria-expanded', 'false'); + const touchMove = fireTouch(beneath, 'touchmove', 9); + fireEvent.pointerCancel(beneath, pointer('touch', 9, 10, 80)); + fireTouch(beneath, 'touchend', 9, {cancelable: false}); + expect(touchStart.defaultPrevented).toBe(false); + expect(touchMove.defaultPrevented).toBe(false); + expect(heard).toEqual([]); + }); + + it("a pinch's two fingers are not canceled, so the page still zooms, and nothing beneath hears them", async () => { + const {heard, beneath} = await openMenuOver(); + fireEvent.pointerDown(beneath, pointer('touch', 9, 10, 100)); + const first = fireTouch(beneath, 'touchstart', 9); + fireEvent.pointerDown(beneath, { + ...pointer('touch', 10, 60, 100), + isPrimary: false, + }); + const second = fireTouch(beneath, 'touchstart', 10, {down: [9, 10]}); + const pinch = fireTouch(beneath, 'touchmove', [9, 10], {down: [9, 10]}); + fireEvent.pointerCancel(beneath, pointer('touch', 9)); + fireEvent.pointerCancel(beneath, pointer('touch', 10)); + fireTouch(beneath, 'touchend', [9, 10], {cancelable: false}); + expect([first, second, pinch].map(event => event.defaultPrevented)).toEqual( + [false, false, false], + ); + expect(heard).toEqual([]); + }); + + it("a mouse's press outside keeps every event and its click", async () => { + const {heard, beneath} = await openMenuOver(); + fireEvent.pointerDown(beneath, pointer('mouse', 1)); + const [mouseDown] = mouseEvents(beneath, ['mousedown']); + fireEvent.pointerUp(beneath, pointer('mouse', 1)); + const [mouseUp, click] = mouseEvents(beneath, ['mouseup', 'click']); + expect( + [mouseDown, mouseUp, click].map(event => event.defaultPrevented), + ).toEqual([false, false, false]); + expect(heard).toEqual([ + 'pointerdown', + 'mousedown', + 'pointerup', + 'mouseup', + 'click', + ]); + }); + + it('with presentation="popover", a finger\'s tap keeps every event and its click (FR25)', async () => { + const {heard, beneath} = await openMenuOver('popover'); + tapAt(beneath, 'touch'); + const touchEnd = fireTouch(beneath, 'touchend', 9); + expect(touchEnd.defaultPrevented).toBe(false); + browserClickAfter(touchEnd, beneath); + expect(heard).toEqual([ + 'pointerdown', + 'touchstart', + 'pointerup', + 'touchend', + 'click', + ]); + }); + + it('the hold ends with the gesture: the next tap on the control acts, also within the click window', async () => { + const {heard, trigger, beneath} = await openMenuOver(); + vi.useFakeTimers(); + tapAt(beneath, 'touch'); + expect(fireTouch(beneath, 'touchend', 9).defaultPrevented).toBe(true); + expect(trigger).toHaveAttribute('aria-expanded', 'false'); + vi.advanceTimersByTime(50); + tapAt(beneath, 'touch', {id: 11}); + const soon = fireTouch(beneath, 'touchend', 11); + expect(soon.defaultPrevented).toBe(false); + browserClickAfter(soon, beneath); + vi.advanceTimersByTime(CLICK_GUARD_WINDOW_MS + 100); + tapAt(beneath, 'touch', {id: 12}); + const later = fireTouch(beneath, 'touchend', 12); + expect(later.defaultPrevented).toBe(false); + browserClickAfter(later, beneath); + const tap = ['pointerdown', 'touchstart', 'pointerup', 'touchend', 'click']; + expect(heard).toEqual([...tap, ...tap]); + }); + + it("a finger's tap on the trigger is the trigger's own: its touchend is not canceled, and the menu does not close at its lift", async () => { + const {trigger} = await openMenuOver(); + tapAt(trigger, 'touch'); + expect(trigger).toHaveAttribute('aria-expanded', 'true'); + const touchEnd = fireTouch(trigger, 'touchend', 9); + expect(touchEnd.defaultPrevented).toBe(false); + }); + + it("a finger's tap on a control in the menu's header is inside: the menu stays open, and the control gets its click", async () => { + const onFilter = vi.fn(); + render( + + Filter + + }> + {}} /> + , + ); + const trigger = screen.getByRole('button', {name: /Actions/}); + fireEvent.click(trigger); + await waitFor(() => { + expect(trigger).toHaveAttribute('aria-expanded', 'true'); + }); + const filter = screen.getByRole('button', {name: 'Filter', hidden: true}); + tapAt(filter, 'touch'); + const touchEnd = fireTouch(filter, 'touchend', 9); + expect(touchEnd.defaultPrevented).toBe(false); + browserClickAfter(touchEnd, filter); + expect(onFilter).toHaveBeenCalledTimes(1); + expect(trigger).toHaveAttribute('aria-expanded', 'true'); + }); + + it("a controlled menu: a finger's tap outside asks its caller to close it, and nothing beneath hears it", async () => { + const onOpenChange = vi.fn(); + const heard: string[] = []; + render( + <> + heard.push(type)} /> + + , + ); + const trigger = screen.getByRole('button', {name: /Actions/}); + fireEvent.click(trigger); + await waitFor(() => { + expect(trigger).toHaveAttribute('aria-expanded', 'true'); + }); + const beneath = screen.getByRole('button', {name: 'Beneath'}); + tapAt(beneath, 'touch'); + const touchEnd = fireTouch(beneath, 'touchend', 9); + expect(touchEnd.defaultPrevented).toBe(true); + browserClickAfter(touchEnd, beneath); + expect(heard).toEqual([]); + await waitFor(() => { + expect(onOpenChange).toHaveBeenLastCalledWith(false); + }); + expect(trigger).toHaveAttribute('aria-expanded', 'false'); + }); + + it("after a menu in the open menu's header closes, a finger's tap outside the open menu still reaches nothing", async () => { + const heard: string[] = []; + render( + <> + heard.push(type)} /> + + {}} /> + + }> + {}} /> + + , + ); + const outer = screen.getByRole('button', {name: /Actions/}); + fireEvent.click(outer); + await waitFor(() => { + expect(outer).toHaveAttribute('aria-expanded', 'true'); + }); + const inner = screen.getByRole('button', {name: /Sort/, hidden: true}); + fireEvent.click(inner); + await waitFor(() => { + expect(inner).toHaveAttribute('aria-expanded', 'true'); + }); + fireEvent.click(inner); + await waitFor(() => { + expect(inner).toHaveAttribute('aria-expanded', 'false'); + }); + expect(outer).toHaveAttribute('aria-expanded', 'true'); + const beneath = screen.getByRole('button', {name: 'Beneath'}); + tapAt(beneath, 'touch'); + const touchEnd = fireTouch(beneath, 'touchend', 9); + expect(touchEnd.defaultPrevented).toBe(true); + browserClickAfter(touchEnd, beneath); + expect(heard).toEqual([]); + await waitFor(() => { + expect(outer).toHaveAttribute('aria-expanded', 'false'); + }); + }); + + it("a finger's tap on an app's scrim that leaves with the menu ends at its lift: the next tap on the page acts", async () => { + const heard: string[] = []; + render( + <> + heard.push(type)} /> + + , + ); + const trigger = screen.getByRole('button', {name: /Actions/}); + fireEvent.click(trigger); + await waitFor(() => { + expect(trigger).toHaveAttribute('aria-expanded', 'true'); + }); + const scrim = screen.getByTestId('scrim'); + tapAt(scrim, 'touch'); + await waitFor(() => { + expect(scrim.isConnected).toBe(false); + }); + // The browser still sends the touchend to the scrim, which has left the + // page, so no listener on the window hears it. + fireTouch(scrim, 'touchend', 9); + expect(trigger).toHaveAttribute('aria-expanded', 'false'); + vi.useFakeTimers(); + vi.advanceTimersByTime(2000); + const beneath = screen.getByRole('button', {name: 'Beneath'}); + tapAt(beneath, 'touch', {id: 11}); + const touchEnd = fireTouch(beneath, 'touchend', 11); + expect(touchEnd.defaultPrevented).toBe(false); + browserClickAfter(touchEnd, beneath); + expect(heard).toEqual([ + 'pointerdown', + 'touchstart', + 'pointerup', + 'touchend', + 'click', + ]); + }); + + it('after the browser takes a pan outside, a second finger is a new touch: every one of its events reaches the page', async () => { + const {heard, trigger, beneath} = await openMenuOver(); + fireEvent.pointerDown(beneath, pointer('touch', 9, 10, 100)); + fireTouch(beneath, 'touchstart', 9); + fireEvent.pointerMove(beneath, pointer('touch', 9, 10, 80)); + expect(trigger).toHaveAttribute('aria-expanded', 'false'); + // The browser takes the pan, and the first finger still scrolls. + fireEvent.pointerCancel(beneath, pointer('touch', 9, 10, 80)); + fireTouch(beneath, 'touchmove', 9); + fireEvent.pointerDown(beneath, pointer('touch', 11)); + fireTouch(beneath, 'touchstart', 11, {down: [9, 11]}); + fireEvent.pointerUp(beneath, pointer('touch', 11)); + const touchEnd = fireTouch(beneath, 'touchend', 11, {down: [9]}); + expect(touchEnd.defaultPrevented).toBe(false); + browserClickAfter(touchEnd, beneath); + expect(heard).toEqual([ + 'pointerdown', + 'touchstart', + 'pointerup', + 'touchend', + 'click', + ]); + }); +}); diff --git a/packages/core/src/DropdownMenu/DropdownMenuTouchGrow.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuTouchGrow.test.tsx index 0d545f8507b5a..04a77fb15aba4 100644 --- a/packages/core/src/DropdownMenu/DropdownMenuTouchGrow.test.tsx +++ b/packages/core/src/DropdownMenu/DropdownMenuTouchGrow.test.tsx @@ -37,15 +37,24 @@ const entranceHold = vi.hoisted(() => vi.fn(() => null)); vi.mock('../Layer/holdEntranceInput', () => ({ holdEntranceInput: entranceHold, })); -// Counts the input holds that are up, with each hold's layer and scope. jsdom -// hit-tests nothing, so no shield is drawn. +// Counts the presentation holds that are up, with each hold's layer and +// scope. jsdom hit-tests nothing, so no shield is drawn. An open menu's +// `'outside'` scope holds nothing on the menu, so it is left out +// (DropdownMenuOutsideTap.test.tsx covers it). const inputHolds = vi.hoisted(() => ({ up: 0, raised: [] as {layer: Element; scope: string}[], })); vi.mock('../Layer/inputHold', async importOriginal => ({ ...(await importOriginal()), - holdInput: (layer: Element, {until, scope}: InputHold.InputHoldOptions) => { + holdInput: ( + layer: Element, + options: InputHold.InputHoldOptions | InputHold.OutsideInputHoldOptions, + ) => { + if (options.scope === 'outside') { + return () => {}; + } + const {until, scope} = options; inputHolds.up += 1; inputHolds.raised.push({layer, scope}); let isUp = true; diff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuOutsideTap.interaction.browser.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuOutsideTap.interaction.browser.spec.ts new file mode 100644 index 0000000000000..051be40eda1b9 --- /dev/null +++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuOutsideTap.interaction.browser.spec.ts @@ -0,0 +1,153 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file DropdownMenuOutsideTap.interaction.browser.spec.ts + * @input The built Submenu DropdownMenu story on a phone, real touch input + * (Chromium CDP, WebKit's tap path), a mouse, and the interaction harness + * @output A finger's tap outside the open menu closes it. The control under + * the finger hears no pointer, touch or mouse event, and no click. A pan + * outside closes the menu as it begins, and the page still + * scrolls. A mouse's click outside closes the menu and keeps its events. + * @position Real-engine half of ../DropdownMenuOutsideTap.test.tsx + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + openStory, + touchDriver, + withStorybook, +} from '@astryxdesign/interaction-harness'; + +const storybook = withStorybook(test); + +const STORY = 'core-dropdownmenu--submenu'; + +async function center(locator: Locator): Promise<{x: number; y: number}> { + const box = await locator.boundingBox(); + if (box == null) { + throw new Error('center: the element has no box'); + } + // WebKit's touch command takes whole pixels. + return { + x: Math.round(box.x + box.width / 2), + y: Math.round(box.y + box.height / 2), + }; +} + +/** + * Adds a control in the page's bottom corner, outside the menu, that logs + * each pointer, touch and mouse event and each click that reaches it. With + * `scrolls`, it also adds a spacer that lets the page scroll. + */ +async function addControlBeneath( + page: Page, + {scrolls = false} = {}, +): Promise { + await page.evaluate(hasSpacer => { + const log: string[] = []; + (window as unknown as {outsideLog: string[]}).outsideLog = log; + if (hasSpacer) { + const spacer = document.createElement('div'); + spacer.style.cssText = 'height:3000px'; + document.body.append(spacer); + } + const control = document.createElement('button'); + control.type = 'button'; + control.textContent = 'Beneath'; + control.style.cssText = + 'position:fixed;right:8px;bottom:8px;width:120px;height:120px;margin:0'; + for (const type of [ + 'pointerdown', + 'pointerup', + 'touchstart', + 'touchend', + 'mousedown', + 'mouseup', + 'click', + ]) { + control.addEventListener(type, event => { + if (event.isTrusted) { + log.push(`beneath ${type}`); + } + }); + } + document.body.append(control); + }, scrolls); + return page.getByRole('button', {name: 'Beneath'}); +} + +async function outsideLog(page: Page): Promise { + return page.evaluate( + () => (window as unknown as {outsideLog: string[]}).outsideLog, + ); +} + +/** Opens the menu with a finger, then adds the control beneath it. */ +async function openWithFinger(page: Page, {scrolls = false} = {}) { + await openStory(page, storybook(), STORY); + const driver = await touchDriver(page); + const trigger = page.getByRole('button', {name: 'Actions'}).first(); + await driver.tap(await center(trigger)); + await expect(page.getByRole('menuitem', {name: 'Move to'})).toBeVisible(); + // Past the entrance, whose hold would take the next touch. + await page.waitForTimeout(600); + const beneath = await addControlBeneath(page, {scrolls}); + return {beneath, driver, trigger}; +} + +test.describe('a touch outside the open menu (spec:AST-094 FR32)', () => { + test("a finger's tap closes the menu, and the control beneath hears nothing", async ({ + page, + }) => { + const {beneath, driver, trigger} = await openWithFinger(page); + await driver.tap(await center(beneath)); + await expect(trigger).toHaveAttribute('aria-expanded', 'false'); + await page.waitForTimeout(800); + expect(await outsideLog(page)).toEqual([]); + }); + + test('a pan closes the menu as it begins, the page scrolls, and the control beneath hears nothing', async ({ + page, + }) => { + const {beneath, driver, trigger} = await openWithFinger(page, { + scrolls: true, + }); + const start = await center(beneath); + const finger = await driver.press(start); + for (let step = 1; step <= 8; step += 1) { + await finger.move({x: start.x, y: start.y - step * 20}); + } + await expect(trigger).toHaveAttribute('aria-expanded', 'false'); + await finger.lift(); + await page.waitForTimeout(800); + expect(await outsideLog(page)).toEqual([]); + if (driver.drivesNativeGestures) { + expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0); + } + }); + + test("a mouse's click closes the menu and keeps its events", async ({ + page, + }) => { + await openStory(page, storybook(), STORY); + const beneath = await addControlBeneath(page); + const trigger = page.getByRole('button', {name: 'Actions'}).first(); + await trigger.click(); + await expect(page.getByRole('menuitem', {name: 'Move to'})).toBeVisible(); + await page.waitForTimeout(600); + await beneath.click(); + await expect(trigger).toHaveAttribute('aria-expanded', 'false'); + expect(await outsideLog(page)).toEqual([ + 'beneath pointerdown', + 'beneath mousedown', + 'beneath pointerup', + 'beneath mouseup', + 'beneath click', + ]); + }); +}); diff --git a/packages/core/src/Layer/__tests__/LayerPanLightDismiss.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/LayerPanLightDismiss.interaction.browser.spec.ts index dd2e869376ff0..8a1fa30c4cfc4 100644 --- a/packages/core/src/Layer/__tests__/LayerPanLightDismiss.interaction.browser.spec.ts +++ b/packages/core/src/Layer/__tests__/LayerPanLightDismiss.interaction.browser.spec.ts @@ -9,7 +9,7 @@ * an open Popover or Selector list, with and without pointercancel. That * includes a pan that the browser itself reads as a tap. A tap outside * still closes the layer, also after a pan. The menus keep their own - * outside behavior + * outside behavior: a tap outside a DropdownMenu makes no click * @position Evidence for `architecture:layer-runtime` INV7 (native light * dismiss identifies gestures); the watch and the claim are unit-tested in * outsidePress.test.ts and gestureCounter.test.ts @@ -387,12 +387,24 @@ test.describe('DropdownMenu', () => { .toBe(false); }); - test('a tap outside closes it', async ({page}) => { + test('a tap outside closes it, and the tap makes no click (spec:AST-094 FR32)', async ({ + page, + }) => { const {driver, outside} = await openSurface(page, DROPDOWN_MENU); - await tapClosesLayer(page, driver, outside); + await page.waitForTimeout(TAP_AFTER_PAN_MS); + await driver.tap(outside); + await expect + .poll(async () => isLayerOpen(page), { + message: 'a tap outside closes the menu', + timeout: 2000, + }) + .toBe(false); + const press = await readPress(page); + expect(press.types, 'the tap made no click').not.toContain('click'); + expect(press.types).not.toContain('pointerup'); }); - test.fixme('a pan that scrolls the page (pointercancel): closes as a pan outside begins (FR21 gap)', async ({ + test('a pan that scrolls the page (pointercancel): closes as a pan outside begins', async ({ page, }) => { const {driver, outside} = await openSurface(page, DROPDOWN_MENU); @@ -400,7 +412,7 @@ test.describe('DropdownMenu', () => { expect(await isLayerOpen(page)).toBe(false); }); - test.fixme('a 40 px pan with no pointercancel: closes as a pan outside begins (FR21 gap)', async ({ + test('a 40 px pan with no pointercancel: closes as a pan outside begins', async ({ page, }) => { const {outside} = await openSurface(page, DROPDOWN_MENU); diff --git a/packages/core/src/Layer/inputHold.test.tsx b/packages/core/src/Layer/inputHold.test.tsx index f676dd435e6b7..9d643dddd9039 100644 --- a/packages/core/src/Layer/inputHold.test.tsx +++ b/packages/core/src/Layer/inputHold.test.tsx @@ -23,6 +23,7 @@ import { type InputHoldScope, } from './inputHold'; import {subscribeModalOutlets, type ModalOutletChange} from './modalOutlet'; +import {hasPanBegun} from './outsidePress'; function deferred() { let resolve: () => void = () => {}; @@ -1393,12 +1394,11 @@ describe("holdInput decides by each event's pointer (spec:AST-094 FR35)", () => clock.time += LATE_PRESS_MS + 200; vi.advanceTimersByTime(LATE_PRESS_MS + 200); expect(listening()).toBe(once); - const up = pointer(button, 'pointerup', 'touch', 1, 0, clock.time); + pointer(button, 'pointerup', 'touch', 1, 0, clock.time); const end = touch(button, 'touchend', [0], 0, clock.time); mouse(button, 'mousedown'); mouse(button, 'mouseup'); click(button, 'touch'); - expect(up.defaultPrevented).toBe(true); expect(end.defaultPrevented).toBe(true); expect(reached).toEqual([]); // Its click window ends, and so do the subscriptions. @@ -1625,6 +1625,186 @@ describe("holdInput decides by each event's pointer (spec:AST-094 FR35)", () => tap(button, 'touch'); expect(reached).toEqual(['pointerdown', 'pointerup', 'click']); }); + + /** An `'outside'` hold on `layer`, released after the case. */ + const holdOutside = (layer: Element, owner: Element | null = null) => { + const onOutside = vi.fn(); + const release = holdInput(layer, { + scope: 'outside', + owner, + onOutside, + hasPanBegun, + }); + releases.push(release); + return {onOutside, release}; + }; + + /** A finger's pointer event at a height on the page. */ + function fingerAt( + element: Element, + type: string, + pointerId: number, + y: number, + ) { + const event = new PointerEvent(type, { + ...INIT, + pointerId, + pointerType: 'touch', + clientX: 10, + clientY: y, + }); + element.dispatchEvent(event); + return event; + } + + it("under an 'outside' scope, holds a finger's tap outside the layer to its end and closes the layer at its lift (spec:AST-094 FR32)", () => { + const {layer} = mountLayer(); + const {button, reached} = recorder(); + const {onOutside} = holdOutside(layer); + const down = pointer(button, 'pointerdown', 'touch', 3); + const start = touch(button, 'touchstart', [3]); + expect(onOutside).not.toHaveBeenCalled(); + pointer(button, 'pointerup', 'touch', 3); + expect(onOutside).toHaveBeenCalledTimes(1); + const end = touch(button, 'touchend', [3], 0); + // In a Home Screen web app, WebKit's late click after a tap names the + // mouse. + click(button, 'mouse'); + expect(down.defaultPrevented).toBe(true); + expect(start.defaultPrevented).toBe(false); + expect(end.defaultPrevented).toBe(true); + expect(reached).toEqual([]); + }); + + it("under an 'outside' scope, leaves a press on the layer or on its owner alone", () => { + const {layer} = mountLayer(); + const onLayer = recorder(layer); + const owner = recorder(); + const {onOutside} = holdOutside(layer, owner.button); + tap(onLayer.button, 'touch', 4); + tap(owner.button, 'touch', 5); + expect(onLayer.reached).toEqual(['pointerdown', 'pointerup', 'click']); + expect(owner.reached).toEqual(['pointerdown', 'pointerup', 'click']); + expect(onOutside).not.toHaveBeenCalled(); + }); + + it("under an 'outside' scope, closes the layer as an outside press begins to pan and cancels none of its moves, so the page still scrolls", () => { + const {layer} = mountLayer(); + const {button, reached} = recorder(); + const {onOutside} = holdOutside(layer); + fingerAt(button, 'pointerdown', 6, 100); + const start = touch(button, 'touchstart', [6]); + fingerAt(button, 'pointermove', 6, 95); + expect(onOutside).not.toHaveBeenCalled(); + fingerAt(button, 'pointermove', 6, 85); + expect(onOutside).toHaveBeenCalledTimes(1); + const move = touch(button, 'touchmove', [6]); + // The browser takes the pan. + fingerAt(button, 'pointercancel', 6, 85); + touch(button, 'touchend', [6], 0); + expect(start.defaultPrevented).toBe(false); + expect(move.defaultPrevented).toBe(false); + expect(onOutside).toHaveBeenCalledTimes(1); + expect(reached).toEqual([]); + }); + + it("the newest 'outside' scope decides, and after it ends the one below it holds again", () => { + const outer = mountLayer(); + const inner = mountLayer(); + const {button, reached} = recorder(); + const outerHold = holdOutside(outer.layer); + const innerHold = holdOutside(inner.layer); + tap(button, 'touch', 7); + expect(innerHold.onOutside).toHaveBeenCalledTimes(1); + expect(outerHold.onOutside).not.toHaveBeenCalled(); + innerHold.release(); + tap(button, 'touch', 8); + expect(outerHold.onOutside).toHaveBeenCalledTimes(1); + expect(reached).toEqual([]); + }); + + it("an 'outside' press ends with its gesture: after its layer's release, the next tap reaches the page", () => { + const {layer} = mountLayer(); + const {button, reached} = recorder(); + const {release} = holdOutside(layer); + tap(button, 'touch', 9); + release(); + tap(button, 'touch', 10); + expect(reached).toEqual(['pointerdown', 'pointerup', 'click']); + }); + + it("an 'outside' scope never holds a mouse's press", () => { + const {layer} = mountLayer(); + const {button, reached} = recorder(); + const {onOutside} = holdOutside(layer); + pointer(button, 'pointerdown', 'mouse'); + pointer(button, 'pointerup', 'mouse'); + click(button, 'mouse'); + expect(reached).toEqual(['pointerdown', 'pointerup', 'click']); + expect(onOutside).not.toHaveBeenCalled(); + }); + + it("schedules no frame for an open menu with no entering presentation: its 'outside' scope alone requests none over the menu's open life, an outside tap included (spec:AST-094 FR24)", () => { + const clock = clockAt(1000); + const frames = framesOn(clock); + const requested = () => + vi.mocked(window.requestAnimationFrame).mock.calls.length; + const {layer} = mountLayer(); + const {button} = recorder(); + const {onOutside} = holdOutside(layer); + expect(requested()).toBe(0); + // A second of the open menu's life, with an outside tap at its end. + frames.draw(...at60Hz(1000, 60)); + clock.time = 2000; + pointer(button, 'pointerdown', 'touch', 1, 0, 2000); + touch(button, 'touchstart', [0], 1, 2000); + clock.time = 2010; + pointer(button, 'pointerup', 'touch', 1, 0, 2010); + touch(button, 'touchend', [0], 0, 2010); + expect(onOutside).toHaveBeenCalledTimes(1); + expect(requested()).toBe(0); + expect(frames.waiting).toBe(0); + }); + + it("watches frames only while a presentation holds: an 'outside' scope alone requests none, and a presentation under it stops its frame request at its release (spec:AST-094 FR24)", () => { + const clock = clockAt(1000); + const frames = framesOn(clock); + const {layer} = mountLayer(); + holdOutside(layer); + expect(frames.waiting).toBe(0); + const release = hold(layer); + expect(frames.waiting).toBe(1); + frames.draw(...at60Hz(1000, 3)); + expect(frames.waiting).toBe(1); + clock.time = 1060; + release(); + expect(frames.waiting).toBe(0); + }); + + it("holds a late press under an 'outside' scope as the ended presentation's: it reaches nothing and closes nothing, and a press stamped after the release closes the layer (spec:AST-094 FR35, FR32)", () => { + const clock = clockAt(1000); + const frames = framesOn(clock); + const {layer} = mountLayer(); + const {button, reached} = recorder(); + const {onOutside} = holdOutside(layer); + const release = hold(layer); + frames.draw(...at60Hz(1000, 4)); + // A long task ends the hold: its release comes 100 ms after a frame. + clock.time = 1150; + release(); + clock.time = 1160; + pointer(button, 'pointerdown', 'touch', 1, 0, 1140); + clock.time = 1200; + pointer(button, 'pointerup', 'touch', 1, 0, 1200); + click(button, 'touch'); + expect(reached).toEqual([]); + expect(onOutside).not.toHaveBeenCalled(); + clock.time = 1300; + pointer(button, 'pointerdown', 'touch', 2, 0, 1300); + pointer(button, 'pointerup', 'touch', 2, 0, 1310); + expect(reached).toEqual([]); + expect(onOutside).toHaveBeenCalledTimes(1); + }); }); describe("holdInput's dismissal that keeps focus inside (component:BottomSheet FR9)", () => { diff --git a/packages/core/src/Layer/inputHold.ts b/packages/core/src/Layer/inputHold.ts index 46b019b0903ee..d877d80d43116 100644 --- a/packages/core/src/Layer/inputHold.ts +++ b/packages/core/src/Layer/inputHold.ts @@ -8,7 +8,8 @@ * and the hold's scope * @output holdInput, holdsTouch, isInHeldLayer, isInputShield, LATE_PRESS_MS * and LATE_RELEASE_FRAMES: input held away from a layer while it presents - * or dismisses, or while it dismisses with focus kept inside + * or dismisses, or while it dismisses with focus kept inside, and a press + * held outside an open menu * @position The Layer module's one input hold, for components whose layer * presents under a finger * @@ -29,7 +30,13 @@ import { type MousePoint, } from '../utils/inputStream'; import {timeOn} from '../utils/inputAge'; -import {isDocument, isElement, isHTMLElement, isNode} from '../utils/nodeType'; +import { + isDocument, + isElement, + isHTMLElement, + isNode, + isShadowRoot, +} from '../utils/nodeType'; import {observeMutations} from '../utils/sharedMutationObserver'; import {realmValue, sharedKey} from '../utils/sharedRealm'; import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector'; @@ -73,6 +80,40 @@ export interface InputHoldOptions { focus?: 'blur' | 'kept-inside'; } +/** + * The hold's `'outside'` scope, which an anchored menu takes while it is open + * under the touch presentation. A finger's or a pen's press that starts + * outside the layer, its owner and any live shield is held to its end. None + * of its events reaches the page. Its moves are never canceled, so a pan + * still scrolls the page and a pinch still zooms it. The layer closes, + * through `onOutside`, as the press begins to pan or at its lift. The scope + * ends when its release runs. + */ +export interface OutsideInputHoldOptions { + scope: 'outside'; + /** The control that opens the layer. A press on it stays the control's. */ + owner?: Element | null; + /** Closes the layer. */ + onOutside: () => void; + /** + * Whether an outside press that went down at `start` has begun to pan at + * `point`. The caller passes the pan test, so this module carries no + * gesture constants into pages that never open a menu. + */ + hasPanBegun: ( + start: {readonly x: number; readonly y: number}, + point: PointerEvent, + ) => boolean; +} + +/** An `'outside'` scope while it holds. */ +interface OutsideScope { + /** Whether a press with this composed path is the layer's own. */ + readonly isInside: (path: ReadonlyArray) => boolean; + readonly onOutside: () => void; + readonly hasPanBegun: OutsideInputHoldOptions['hasPanBegun']; +} + interface HeldLayer { viewport: number; layer: number; @@ -104,6 +145,8 @@ interface PressHold { release: () => void; /** Whether the press with this pointer id is held to its end. */ holds: (pointerId: number) => boolean; + /** Brings its `touchmove` subscription in line with the held scopes. */ + sync: () => void; /** Notes a hold that has ended, for a press that went down during it. */ ended: (hold: EndedHold) => void; } @@ -139,6 +182,12 @@ const {held, heldDocuments, pressHolds, liveShields} = realmValue( }), ); +// The layers that hold an `'outside'` scope, registered for the same reason. +const outsideScopes = realmValue( + sharedKey('layer/input-hold-outside', 1), + () => new WeakMap(), +); + /** Whether the shared input stream last delivered a mouse's pointer event. */ function isMouseLast(doc: Document | null): boolean { const view = doc?.defaultView; @@ -481,8 +530,12 @@ function openToEarlierPresses(state: HeldLayer, doc: Document): void { */ export function holdInput( layer: Element, - {until, scope, focus = 'blur'}: InputHoldOptions, + options: InputHoldOptions | OutsideInputHoldOptions, ): () => void { + if (options.scope === 'outside') { + return holdOutside(layer, options); + } + const {until, scope, focus = 'blur'} = options; if (scope === 'layer' && focus === 'kept-inside') { return holdKeptInside(layer, until); } @@ -537,6 +590,7 @@ export function holdInput( openToEarlierPresses(state, layer.ownerDocument); } openToMouse(state, layer.ownerDocument); + pressHolds.get(layer.ownerDocument)?.sync(); const clock = layer.ownerDocument.defaultView?.performance; const from = clock?.now() ?? 0; let isReleased = false; @@ -573,14 +627,59 @@ export function holdInput( current.shield.remove(); } held.delete(layer); - stopHolding(layer); + if (!outsideScopes.has(layer)) { + stopHolding(layer); + } } + pressHolds.get(layer.ownerDocument)?.sync(); }; const end = 'finished' in until ? until.finished : until; void Promise.resolve(end).then(release, release); return release; } +/** The `'outside'` scope (see {@link OutsideInputHoldOptions}). */ +function holdOutside( + layer: Element, + {owner = null, onOutside, hasPanBegun}: OutsideInputHoldOptions, +): () => void { + const doc = layer.ownerDocument; + const root = layer.getRootNode(); + // The window sees a press inside a closed shadow root as a press on its + // host, so a press there counts as the layer's. + const closedHost = + isShadowRoot(root) && root.mode === 'closed' ? root.host : null; + const scope: OutsideScope = { + isInside: path => + path.some( + target => + target === layer || + (owner != null && target === owner) || + (closedHost != null && target === closedHost) || + (isNode(target) && liveShields.has(target)), + ), + onOutside, + hasPanBegun, + }; + outsideScopes.set(layer, scope); + startHolding(layer); + pressHolds.get(doc)?.sync(); + let isReleased = false; + return () => { + if (isReleased) { + return; + } + isReleased = true; + if (outsideScopes.get(layer) === scope) { + outsideScopes.delete(layer); + } + if (!held.has(layer) && !outsideScopes.has(layer)) { + stopHolding(layer); + } + pressHolds.get(doc)?.sync(); + }; +} + /** The keys a dismissing layer that keeps focus lets through. */ const KEPT_INSIDE_KEYS: ReadonlySet = new Set(['Tab']); @@ -794,16 +893,17 @@ function isPressHeldBy( * engine dispatches it after the hold's end. After a release in time, it * waits LATE_RELEASE_FRAMES of the hold's frame intervals. After a release in * a long task, which the hold reads from the frames that the page draws while - * it holds, it waits LATE_PRESS_MS. A finger's or a pen's press is judged - * once: its pointerdown and its touchstart give the same time and target, - * and the second follows the first, even after the wait. 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 + * a presentation holds, it waits LATE_PRESS_MS. A finger's or a pen's press is + * judged once: its pointerdown and its touchstart give the same time and + * target, and the second follows the first, even after the wait. 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, the - * held presses and their clicks have ended, and no late press can still - * arrive. + * press feedback or the gesture host. Under an `'outside'` scope, a press + * that starts outside the layer is held with every finger that joins it. The + * layer closes as the press begins to pan or at its lift. There is one per + * document. Its subscriptions end once nothing is held, the held presses and + * their clicks have ended, and no late press can still arrive. */ function createPressHold(doc: Document): PressHold | null { const view = doc.defaultView; @@ -816,6 +916,24 @@ function createPressHold(doc: Document): PressHold | null { /** The held presses still down, by pointer id and by touch identifier. */ const pointers = new Set(); const touches = new Set(); + /** The held touches a presentation holds: their one-finger moves pan nothing. */ + const presentationTouches = new Set(); + /** + * The held press that started outside an `'outside'` scope's layer: its + * fingers, where its first finger went down, and whether it closed the layer. + */ + let outside: { + readonly scope: OutsideScope; + readonly id: number; + readonly x: number; + readonly y: number; + readonly pointers: Set; + readonly touches: Set; + isClosed: boolean; + } | null = null; + /** Whether the `touchmove` subscription cancels, and its end. */ + let movesCancel: boolean | null = null; + let stopMoves: (() => void) | null = null; /** * The held finger and pen starts whose other start has not come yet. Such * a press starts twice, with a pointerdown and a touchstart that give the @@ -828,6 +946,8 @@ function createPressHold(doc: Document): PressHold | null { const heldTouchStarts: HeldStart[] = []; /** Whose press the next click is: a held one's, or any other's. */ let lastPress: 'held' | 'free' | null = null; + /** Whether the last held press started outside an `'outside'` scope's layer. */ + let wasLastOutside = false; /** Until when a click with no pointer type is a held press's. */ let clickUntil = -Infinity; /** Ended holds whose late presses can still arrive. */ @@ -846,6 +966,17 @@ function createPressHold(doc: Document): PressHold | null { const now = () => view.performance.now(); const isPressDown = () => pointers.size > 0 || touches.size > 0; + /** Whether a presentation holds a layer of the document. */ + const holdsPresentation = () => { + for (const layer of heldDocuments.get(doc)?.layers ?? []) { + const state = held.get(layer); + if (state != null && state.viewport + state.layer + state.surface > 0) { + return true; + } + } + return false; + }; + /** Takes the held start at `time` on `target`, if one is waiting. */ const takeHeldStart = ( starts: HeldStart[], @@ -862,11 +993,16 @@ function createPressHold(doc: Document): PressHold | null { return true; }; - /** Notes each frame the page draws while a layer is held. */ + /** + * Notes each frame the page draws while a presentation holds a layer. An + * `'outside'` scope alone draws on no frame: its release ends no + * presentation. + */ const watchFrames = () => { if ( frameRequest != null || - typeof view.requestAnimationFrame !== 'function' + typeof view.requestAnimationFrame !== 'function' || + !holdsPresentation() ) { return; } @@ -1053,6 +1189,43 @@ function createPressHold(doc: Document): PressHold | null { return false; }; + /** + * The newest held layer's `'outside'` scope, when a press with this + * composed path starts outside that layer. + */ + const outsideScopeAt = (path: ReadonlyArray) => { + if (!holdsNewPress()) { + return null; + } + const layers = liveLayers(doc); + for (let index = layers.length - 1; index >= 0; index -= 1) { + const scope = outsideScopes.get(layers[index]); + if (scope != null) { + return scope.isInside(path) ? null : scope; + } + } + return null; + }; + + /** The outside press closes its layer, once. */ + const closeOutside = () => { + if (outside != null && !outside.isClosed) { + outside.isClosed = true; + outside.scope.onOutside(); + } + }; + + /** The outside press ends with its last finger. */ + const endOutsideIfDone = () => { + if ( + outside != null && + outside.pointers.size === 0 && + outside.touches.size === 0 + ) { + outside = null; + } + }; + const pressEnded = () => { clickUntil = now() + CLICK_WINDOW_MS; settle(); @@ -1135,14 +1308,30 @@ function createPressHold(doc: Document): PressHold | null { followPointer(pointerType); } if (type === 'pointerdown') { + const isHeldType = HELD_POINTERS.has(pointerType); + // Another finger of an outside press, such as a pinch's second one, + // joins it while one of the press's pointers is still down. + const joinsOutside = + isHeldType && outside != null && outside.pointers.size > 0; + // A pointerdown that gives a held touchstart's time and target is the + // same press: it takes that start's verdict. const followsHeldTouch = - HELD_POINTERS.has(pointerType) && + isHeldType && + !joinsOutside && takeHeldStart(heldTouchStarts, time, event.target); - const isHeld = - followsHeldTouch || - (HELD_POINTERS.has(pointerType) && - (holdsPressAt(event.target) || wasHeldAt(event.target, time))); - if (!isHeld) { + // A late press is the ended hold's, not the outside scope's: it closes + // nothing. + const isPresented = + isHeldType && + !joinsOutside && + (followsHeldTouch || + holdsPressAt(event.target) || + wasHeldAt(event.target, time)); + const scope = + isHeldType && !joinsOutside && !isPresented + ? outsideScopeAt(event.composedPath()) + : null; + if (!joinsOutside && !isPresented && scope == null) { // 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); @@ -1151,41 +1340,95 @@ function createPressHold(doc: Document): PressHold | null { settle(); return false; } + if (scope != null) { + const {clientX, clientY} = event as PointerEvent; + outside = { + scope, + id: pointerId, + x: clientX, + y: clientY, + pointers: new Set(), + touches: new Set(), + isClosed: false, + }; + } + outside?.pointers.add(pointerId); pointers.add(pointerId); - if (!followsHeldTouch) { + if (isPresented && !followsHeldTouch) { heldPointerStarts.push({time, target: event.target}); } lastPress = 'held'; + wasLastOutside = outside != null; // A late press is held to its end: no stop runs while it is down. settle(); - captureToShield(event as PointerEvent); - } else if (!pointers.has(pointerId)) { + if (isPresented) { + captureToShield(event as PointerEvent); + } + // Canceling the press keeps the browser from sending its compatibility + // mouse events, and with them a focus move. + swallow(event); + return true; + } + 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); + event.stopImmediatePropagation(); + if ( + type === 'pointermove' && + outside?.id === pointerId && + outside.scope.hasPanBegun(outside, event as PointerEvent) + ) { + closeOutside(); + } if (type === 'pointerup' || type === 'pointercancel') { pointers.delete(pointerId); + const isOutsideLift = outside?.id === pointerId; + // The click window opens first: the close can end the hold, and a + // pen's mouse events and click follow its lift. pressEnded(); + // The lift of a tap or a hold, or a pan the browser took. + if (isOutsideLift) { + closeOutside(); + } + outside?.pointers.delete(pointerId); + endOutsideIfDone(); } return true; }; const onTouch = (event: Event): boolean => { - const {changedTouches, touches: down, type} = event as TouchEvent; + // A script's touch event may leave out its touch lists. + const {changedTouches, touches: down, type} = event as Partial; const time = timeOfInput(event); noteInputAt(time); - const changed = Array.from(changedTouches); + 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)); + const live = new Set(Array.from(down ?? [], touch => touch.identifier)); for (const identifier of touches) { if (!live.has(identifier)) { touches.delete(identifier); + presentationTouches.delete(identifier); + outside?.touches.delete(identifier); + } + } + // An outside press whose target left the page with its layer ends here: + // its touchend reached no listener on the window. + endOutsideIfDone(); + // A touch joins an outside press on the same terms as its pointer. Once + // the browser takes the press's pan, a later finger is a new touch. + if (outside != null && outside.pointers.size > 0) { + for (const touch of changed) { + touches.add(touch.identifier); + outside.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; } const followers = changed.filter(touch => takeHeldStart(heldPointerStarts, time, touch.target), @@ -1209,10 +1452,12 @@ function createPressHold(doc: Document): PressHold | null { } for (const touch of heldTouches) { touches.add(touch.identifier); + presentationTouches.add(touch.identifier); if (!followers.includes(touch)) { heldTouchStarts.push({time, target: touch.target}); } } + sync(); lastPress = 'held'; settle(); // Never canceled: canceling a touch's start would cancel the page's @@ -1225,8 +1470,13 @@ function createPressHold(doc: Document): PressHold | null { } if (type === 'touchmove') { event.stopImmediatePropagation(); - // One finger pans nothing; two still zoom the page. - if (down.length === 1 && event.cancelable) { + // One finger of a presentation's press pans nothing; two still zoom the + // page. An outside press's moves are never canceled. + if ( + down?.length === 1 && + event.cancelable && + changed.some(touch => presentationTouches.has(touch.identifier)) + ) { event.preventDefault(); } return true; @@ -1235,7 +1485,11 @@ function createPressHold(doc: Document): PressHold | null { swallow(event); for (const touch of changed) { touches.delete(touch.identifier); + presentationTouches.delete(touch.identifier); + outside?.touches.delete(touch.identifier); } + endOutsideIfDone(); + sync(); pressEnded(); return true; }; @@ -1248,11 +1502,14 @@ function createPressHold(doc: Document): PressHold | null { } // 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. + // belongs to the last press. So does every click after an outside press: + // in a Home Screen web app, WebKit's late click after a tap names the + // mouse. A mouse's own press marks the next click free. const {pointerType} = event as Partial; const isHeldPress = lastPress === 'held' && - (pointerType == null || + (wasLastOutside || + pointerType == null || pointerType === '' || HELD_POINTERS.has(pointerType)); if (isHeldPress && (isPressDown() || now() <= clickUntil)) { @@ -1282,19 +1539,59 @@ function createPressHold(doc: Document): PressHold | null { for (const unsubscribe of unsubscribers.splice(0)) { unsubscribe(); } + stopMoves?.(); + stopMoves = null; + movesCancel = null; } - // 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. + /** + * Whether a held one-finger move is canceled: a presentation holds a layer + * of the document, or a touch it held is still down. + */ + const cancelsMoves = () => + presentationTouches.size > 0 || holdsPresentation(); + + /** Subscribes `touchmove` to cancel only while a move may be canceled. */ + const sync = (): void => { + if (!isListening) { + return; + } + if (!holdsPresentation()) { + stopWatchingFrames(); + } else if (frameRequest == null) { + // A presentation's frames begin at its hold. + lastFrameAt = now(); + frameBeforeAt = null; + watchFrames(); + } + const wanted = cancelsMoves(); + if (wanted === movesCancel) { + return; + } + stopMoves?.(); + movesCancel = wanted; + stopMoves = subscribeInput(view, 'touchmove', onTouch, { + cancels: wanted, + first: true, + }); + }; + + // Of the pointer and touch events, only a held press's `pointerdown`, a + // tap's `touchend` and a presentation's one-finger `touchmove` are + // canceled. Their other subscriptions stay passive. `touchmove` subscribes + // through `sync`. It cancels only while a presentation holds. 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}), + subscribeInput(view, type, onPointer, { + cancels: type === 'pointerdown', + first: true, + }), ), - ...TOUCH_EVENTS.map(type => + ...TOUCH_EVENTS.filter(type => type !== 'touchmove').map(type => subscribeInput(view, type, onTouch, { - cancels: type === 'touchmove' || type === 'touchend', + cancels: type === 'touchend', first: true, }), ), @@ -1305,16 +1602,11 @@ function createPressHold(doc: Document): PressHold | null { const pressHold: PressHold = { hold() { - if (!isHolding) { - lastFrameAt = now(); - frameBeforeAt = null; - } isHolding = true; if (timer !== undefined) { clearTimeout(timer); timer = undefined; } - watchFrames(); }, release() { if (!isHolding) { @@ -1325,6 +1617,7 @@ function createPressHold(doc: Document): PressHold | null { settle(); }, holds: pointerId => pointers.has(pointerId), + sync, ended(hold) { forgetEndedHolds(() => false); if (!hold.layer.isConnected) { @@ -1337,7 +1630,6 @@ function createPressHold(doc: Document): PressHold | null { watchLayers(); }, }; - watchFrames(); return pressHold; } diff --git a/packages/core/src/Layer/outsidePress.ts b/packages/core/src/Layer/outsidePress.ts index 2f500423e74f1..77c21d3ea2c0f 100644 --- a/packages/core/src/Layer/outsidePress.ts +++ b/packages/core/src/Layer/outsidePress.ts @@ -9,7 +9,8 @@ * @output watchOutsidePress, and useOutsidePress, one watch per component. * noteOutsideDismissal and outsideDismissalCount keep a per-document count * of layers that an outside press or focus move closed. The inside tests - * are isPressInsideOwnedLayer and isFocusInsideOwnedLayer + * are isPressInsideOwnedLayer and isFocusInsideOwnedLayer. hasPanBegun is + * the pan test that the watch and an anchored menu's outside hold share * @position Internal to Layer: the outside-press dismissal for a manual * popover whose owner decides what counts as inside. Not exported. */ @@ -22,6 +23,19 @@ import {isElement, isNode} from '../utils/nodeType'; import {touchActionAllowsPan} from '../utils/scrollView'; import {sharedWeakMap} from '../utils/sharedRealm'; +/** Whether a press that went down at `start` has begun to pan at `point`. */ +export function hasPanBegun( + start: {readonly x: number; readonly y: number}, + point: {readonly clientX: number; readonly clientY: number}, +): boolean { + return ( + Math.max( + Math.abs(point.clientX - start.x), + Math.abs(point.clientY - start.y), + ) >= UIKIT_PAN.hysteresis.value + ); +} + export interface OutsidePressOptions { /** The pointer types the watch follows; every type when omitted. */ readonly pointerTypes?: ReadonlyArray; @@ -156,13 +170,7 @@ export function watchOutsidePress( } }; const handleMove = (event: PointerEvent) => { - if ( - panStart?.id === event.pointerId && - Math.max( - Math.abs(event.clientX - panStart.x), - Math.abs(event.clientY - panStart.y), - ) >= UIKIT_PAN.hysteresis.value - ) { + if (panStart?.id === event.pointerId && hasPanBegun(panStart, event)) { if (reportPan != null) { const axis = Math.abs(event.clientX - panStart.x) >=