An open source design system that's fully customizable and agent ready
TypeScript
fix(Toast): a quick flick dismisses a toast of any height (#8047)
Christopher Chedeaudc6dadbb72c1
diff --git a/.changeset/toast-clears-home-indicator.md b/.changeset/toast-clears-home-indicator.mdnew file mode 100644index 0000000000..f958962b7b--- /dev/null+++ b/.changeset/toast-clears-home-indicator.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A bottom toast now keeps its 16 px gap above the bottom safe-area inset instead of sitting on the inset's edge. Under a coarse pointer it clears at least 34 px plus that gap, even on a page that reports no inset (Safari reports one only with `viewport-fit=cover`).++@vjeuxdiff --git a/.changeset/toast-empty-viewport.md b/.changeset/toast-empty-viewport.mdnew file mode 100644index 0000000000..e85e303a9c--- /dev/null+++ b/.changeset/toast-empty-viewport.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] An empty toast viewport now has no box, so iOS Safari's bottom toolbar returns to the page color once the last toast leaves. Before, a toast swiped out through the bottom edge left its color on the toolbar until the page reloaded.++@vjeuxdiff --git a/.changeset/toast-first-move-claim.md b/.changeset/toast-first-move-claim.mdnew file mode 100644index 0000000000..3da444adb1--- /dev/null+++ b/.changeset/toast-first-move-claim.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A touch on a toast is now decided by its first move. A first move toward the toast's edge belongs to the swipe and never scrolls the page; any other first move leaves the page its scroll. The shared gesture host makes that claim, so importing Toast now brings in the host: about 24 KB gzip on its own (Toast from about 74 KB to 99 KB), and nothing more on a page whose other touch components already load it. LayerProvider without a Toast import is unchanged.++@vjeuxdiff --git a/.changeset/toast-flick-any-height.md b/.changeset/toast-flick-any-height.mdnew file mode 100644index 0000000000..d9629239f4--- /dev/null+++ b/.changeset/toast-flick-any-height.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A quick flick toward a toast's edge now dismisses it whatever its height. Before, a flick also had to travel 48 px (the distance that already dismisses a one-line toast), so on any toast up to 120 px tall a flick could only snap back; and its speed was timed by when the browser handled the touches rather than when they happened, which in browsers that deliver moves on the next frame made a quick flick look up to twice as slow.++@vjeuxdiff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.mdindex d228f7f81f..ce0b3679f4 100644--- a/docs/specs/AST-094-touch-presentations/spec.md+++ b/docs/specs/AST-094-touch-presentations/spec.md@@ -490,7 +490,7 @@ a measured, sourced difference exists.that gesture's click (DEC-17). A recognizer that begins MUST claim its touches by cancelling`touchmove` through a non-passive listener on its element; a watcher,which never claims, is exempt (DEC-7). A `touchmove` of a touch no recognizer owns MUST NOT be cancelled, with- four exceptions. While a scroll lock under a modal presentation holds the+ five exceptions. While a scroll lock under a modal presentation holds thepage, it MAY cancel the moves of a one-finger touch that no recognizer ownswhen that pan would scroll the page; a second finger is never cancelled(FR10), and the page keeps pinch-zoom. A modal overlay that takes the page@@ -503,7 +503,9 @@ a measured, sourced difference exists.first move, only while every scroller under the finger sits at its edge andthe drag moves toward that edge (FR14), and only the moves the browser wouldrubber-band, never a real scroll; the pan itself still begins at FR17's- 10 pt, as UIKit's sheet pull does (DEC-18).+ 10 pt, as UIKit's sheet pull does (DEC-18). A toast's swipe MAY cancel its+ touch's moves from a first move toward its dismiss edge (`component:Toast`+ FR4).A recognizer that is cancelled while its touch is moving, other than by thebrowser taking that touch (FR20), such as a long press dragged past itstolerance after it began, keeps owning that touch until it lifts and MAY@@ -1028,7 +1030,7 @@ Motion that FR45 moves, by component. Each component's record carries its own li| FR13 | Resolver unit tests and a server-render test | coarse and fine pointer; narrow, wide and short; server render; hydrating render | a component that answers the conditions differently, or a touch presentation in the server or hydrating render, fails || FR14 | Browser tests of a sheet over a scrolled list | scrolled and at its top | a midway handoff fails || FR15–FR17 | Recognizer unit tests on synthetic streams with explicit timestamps | exclusive, simultaneous, require-to-fail, nested; a watcher beside a claiming winner; a blocked main thread; a pan at 10 pt per axis | a wrong winner, a late deadline, or a translation that keeps the hysteresis, or a watcher failed or cancelled by a claiming winner fails |-| FR18–FR22 | Browser tests with real touch input (`spec:AST-013` FR10) | per-axis pans beside native scrolling, page zoom, cancelled touches, clicks after taps, keyboard activation, a modal scroll lock, a control that keeps its press through a drag; a still finger with sub-pixel jitter over a scroll view; a finger moved 9 px and 10 px straight, and (7, 7) and (8, 8) diagonally; a recognizer on an element whose author `touch-action` is narrower, including one without `pinch-zoom`; a screen-edge pan landing at 40 px and at 41 px from the edge, at 14 px and 15 px of travel, and a horizontal scroll that starts outside the band; a screen-edge pan on an element within the band, and on one that reaches beyond it; a sheet's pull from a list at its top, and from a list scrolled away from its top; a long press dragged past its tolerance after it began, which never scrolls the page | a ghost click, a scroll or zoom blocked other than by the author's `touch-action`, or a cancelled unowned touchmove outside FR19's four exceptions, a tap cancelled by sub-pixel movement or by under 10 px of travel, a scroll that does not take the touch at 10 px, or a derived `touch-action` wider than the author's, a screen-edge pan that claims outside its band or before 15 px on an element within the band, or has not claimed at 15 px, or an author scroll outside the band that is blocked, a band claim of `pan-x` on an element that reaches beyond the band, or a 15 px start there, or a scroll-edge pan that cancels a move a scroller could scroll, or begins before 10 pt, fails |+| FR18–FR22 | Browser tests with real touch input (`spec:AST-013` FR10) | per-axis pans beside native scrolling, page zoom, cancelled touches, clicks after taps, keyboard activation, a modal scroll lock, a control that keeps its press through a drag; a still finger with sub-pixel jitter over a scroll view; a finger moved 9 px and 10 px straight, and (7, 7) and (8, 8) diagonally; a recognizer on an element whose author `touch-action` is narrower, including one without `pinch-zoom`; a screen-edge pan landing at 40 px and at 41 px from the edge, at 14 px and 15 px of travel, and a horizontal scroll that starts outside the band; a screen-edge pan on an element within the band, and on one that reaches beyond it; a sheet's pull from a list at its top, and from a list scrolled away from its top; a long press dragged past its tolerance after it began, which never scrolls the page | a ghost click, a scroll or zoom blocked other than by the author's `touch-action`, or a cancelled unowned touchmove outside FR19's five exceptions, a tap cancelled by sub-pixel movement or by under 10 px of travel, a scroll that does not take the touch at 10 px, or a derived `touch-action` wider than the author's, a screen-edge pan that claims outside its band or before 15 px on an element within the band, or has not claimed at 15 px, or an author scroll outside the band that is blocked, a band claim of `pan-x` on an element that reaches beyond the band, or a 15 px start there, or a scroll-edge pan that cancels a move a scroller could scroll, or begins before 10 pt, fails || FR20 | Browser tests with real touch input in Chromium phone emulation (`spec:AST-013` FR10) | a horizontal drag under `pan-y`; a vertical drag under `pan-y` over a scroller with room; a vertical drag where no scroller has room | a horizontal drag under `pan-y` counted as the browser taking the touch, a vertical one over a scroller with room not counted, or a later uncancelable move counted, fails || FR23 | Haptics tests on the recorded moments | tap, drag, lift | a haptic outside a native moment fails || FR24 | Resource tests counting listeners, observers and timers | fine primary pointer; coarse pointer enabled and disabled; many instances; unmount | a gesture listener in a component that uses no gesture, an idle document listener outside a press other than the one shared press controller and the one stray-click swallower, a second press controller, a per-instance `document` or `window` listener, or a leak fails |diff --git a/docs/specs/components/Toast/Toast.spec.md b/docs/specs/components/Toast/Toast.spec.mdindex 8402216782..ed27be7882 100644--- a/docs/specs/components/Toast/Toast.spec.md+++ b/docs/specs/components/Toast/Toast.spec.md@@ -17,6 +17,9 @@ verified_by:packages/core/src/Layer/toastHost.lateRegistration.test.tsx,packages/core/src/Toast/ToastViewport.test.tsx,packages/core/src/Toast/ToastViewport.modalHost.test.tsx,+ packages/core/src/Toast/__tests__/ToastSafeArea.a11y.chromium.spec.ts,+ packages/core/src/Toast/__tests__/ToastSwipeScroll.interaction.browser.spec.ts,+ packages/core/src/Toast/__tests__/ToastEmptyViewport.interaction.browser.spec.ts,packages/core/src/Toast/useToast.test.tsx,apps/storybook/stories/Toast.stories.tsx,scripts/check-knowledge.mjs,@@ -52,7 +55,7 @@ system_specs:| Behavior | A stack of non-modal notification cards at one viewport corner. Each toast is announced once, can auto-hide (pausing while hovered, focused, touched, or the window is blurred), and dismisses by its button, a vertical swipe toward its edge, or code. F6 moves focus into the newest toast. || End-user impact | Users get brief notices without losing their place; screen-reader users hear each toast once; keyboard users reach toast controls with F6 and land somewhere sensible after dismissing; touch users swipe toasts away. || Builder impact | None. |-| Compatibility/readiness | Records shipped behavior; no public change. Sixteen implementation gaps, listed under Current-state impact. |+| Compatibility/readiness | Records shipped behavior; no public change. Seventeen implementation gaps, listed under Current-state impact. || Review checks | Reject a toast announced more than once per show, a dismissal that drops focus to the body, an auto-hide that runs while the user is reading or interacting, or a swipe as the only way to dismiss. || Governing rules | `spec:AST-086` FR1; `spec:AST-003` (modal rehosting); `spec:AST-094`; `spec:AST-100`; `spec:AST-059` FR6; `architecture:layer-runtime`; `design:bidirectionality`; `design:reduced-motion`. |@@ -140,6 +143,19 @@ Consumer migration instructions belong in consumer docs and release notes.- **The viewport sets a page-level z-index.** The viewport carries`z-index: 500`; `spec:AST-027` FR1 keeps z-index local only, and FR8 ordersfloating surfaces through the browser top layer.+- **A swiped toast can tint Safari's toolbar.** While other toasts remain, a+ swiped toast's exit can tint iOS Safari's bottom toolbar until the last+ toast leaves. Once the last toast's exit ends, Safari restores the toolbar's+ color about 0.25 s later.++FR4's first-move rule has two accepted tradeoffs, which are not gaps:++- **A slight first move toward the edge keeps the page still.** A touch whose+ first move goes 1 px toward the dismiss edge belongs to the swipe. If it+ then turns away from the edge, the page does not scroll for that touch.+- **A wobbly first move gives the touch to the page.** A swipe whose first+ move is sideways, diagonal, or 1 px away from the edge does not start, and+ that touch scrolls the page instead.## Ownership boundary@@ -170,20 +186,20 @@ Consumer migration instructions belong in consumer docs and release notes.## Behavioral and layout contract-| ID | Invariant | Basis |-| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |-| FR1 | A card carries `toast` with `type` and shows `body` and, on its first line, `endContent` then a dismiss Button named by `@astryx.toast.dismiss`; long body text wraps below. `renderContent` replaces that layout, receives `body`, `endContent`, `type`, timing, and a `dismiss` function, and gets no injected dismiss control. | Current source and tests |-| FR2 | With auto-hide on (the default for `info`, off for `error`), the card dismisses with reason `auto` after `autoHideDuration` ms. The timer pauses while the pointer is over the card, focus is inside it, a touch or pen gesture is active, or the window is blurred, and resumes with the remaining time (at least 1 s). Each pause condition holds the timer on its own: one ending resumes it only when no other still holds, and focus moving between the card's own controls keeps it held. A toast raised while the window is already blurred starts with its timer held. | Current source and tests |-| FR3 | The dismiss button, a swipe, a `dismiss` call, or the returned dismiss function dismiss with reason `manual`; `onHide` fires at most once, when the toast is dismissed, even when dismissed twice during its exit or before it shows. A toast replaced through `uniqueID` is not dismissed and reports no `onHide`. | Current source and tests |-| FR4 | A drag toward the position's block edge, from any pointer (`spec:AST-094` FR43), decides once, at release, per `spec:AST-094` FR36–FR37: projected travel past the commit point dismisses, and a release moving back toward the start cancels. A short drag snaps back; horizontal intent, a second touch, or a gesture starting on an interactive descendant does not dismiss. Native page scrolling continues until touch intent matches the dismiss edge. In the default layout the visible dismiss button stays as a non-gesture alternative; custom content supplies its own. Implementation gaps: the shipped rule dismisses on net travel past a distance threshold or a fast flick timed by its own average speed, even after the finger moves back, and recognizes only touch and pen drags, not a mouse (Current-state impact). | Current source and tests |-| FR5 | A new card slides in from its edge and fades in; a dismissed card collapses and fades before it unmounts; both slide only along the block axis. A dismissal without a swipe uses theme timing; a swipe's commit and snap-back start at the release velocity (`spec:AST-094` FR38). Under reduced motion the entrance and dismissal are an opacity-only fade of 200 ms or less on a coarse pointer or after a touch release (`design:reduced-motion` DR2) and immediate otherwise (DR3), and the card still unmounts. Implementation gaps: a swipe's settle is a CSS transition at theme timing, and under reduced motion every transition, including the row collapse and the swipe's throw, runs for 0.01 ms on every pointer (Current-state impact). | Current source and tests |-| FR6 | The viewport stacks toasts at `position`, newest nearest the configured edge, with an 8 px gap and no extra space at the edge beyond the safe-area gutter it keeps; it spans the inline axis within its inset, honoring start and end insets in either direction. Each edge sits at the provider's `layerInset`, and a `toast.inset` edge, when set, replaces it (`spec:AST-059` FR6). Implementation gaps: a `toast.inset` edge set to 0 does not replace the provider's value, and an edge opposite the position, such as `top` for a bottom stack, moves the stack to that edge (Current-state impact). | Current source and tests |-| FR7 | With `maxVisible` of 1 or more, at most that many toasts show; when more are raised, the oldest wait hidden and return as visible toasts leave. `maxVisible={0}` shows every toast. | Current source and tests |-| FR8 | A toast whose `uniqueID` matches a toast the viewport holds, whether shown, hidden by the cap, or exiting, replaces it in place under `overwrite` (and is announced again; the card updates in place under the same key, so focus inside it stays on the same control, or moves per FR10 when that control no longer exists), and is dropped unshown and unannounced under `ignore`, even when both are raised before the first renders. Implementation gap: overwriting a toast hidden by the cap announces it while it is not shown, and nothing is announced when it surfaces (Current-state impact). | Current source and tests |-| FR9 | Each shown toast has one announcement owner (`spec:AST-086` FR1): the viewport announces it once, when it is shown, `error` assertively and `info` politely, using the toast's text content, through its own persistent polite and assertive containers, which move with it into a modal (`spec:AST-086` FR10). Unrelated renders do not re-announce. Implementation gaps: the viewport announces through the shared body-level channel, which a modal hides, and announces at dispatch rather than when a toast appears (Current-state impact). | `spec:AST-086`; tests |-| FR10 | F6 moves focus to the first control in the newest toast. Focus entering the viewport, by F6, Tab or a click, records where it was. Dismissing a toast that holds focus moves focus to a control in a remaining toast, or back to the remembered element when none remain. When focus reached the viewport by Tab or a click, dismissing the focused toast follows the same handoff: a control in a remaining toast, else the remembered element; with no control in the target toast, F6 leaves focus where it was, and a handoff never drops focus to the page body. | Current source and tests |-| FR11 | While a toast is visible the viewport is a `region` landmark named by `@astryx.toast.viewport`, without `aria-modal`; it exposes no landmark when empty, so an empty nested viewport adds none. Implementation gap: nested viewports that each hold a toast expose two landmarks (Current-state impact). | Current source and tests |-| FR12 | A top-layer viewport moves into the latest open Dialog, modal Drawer, scrim sheet, or modal flow step, following the top of a stack and handing back to the one beneath when it closes, and returns to its place when none remains, keeping each toast, its timer, and focus inside the viewport. It re-enters the top layer in place when a non-modal sheet or a drawer without a scrim opens after it, and stays in place when rendered in place, or when an inline dialog, a sheet without a scrim, or a non-modal flow opens. | `spec:AST-003`; tests |+| ID | Invariant | Basis |+| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |+| FR1 | A card carries `toast` with `type` and shows `body` and, on its first line, `endContent` then a dismiss Button named by `@astryx.toast.dismiss`; long body text wraps below. `renderContent` replaces that layout, receives `body`, `endContent`, `type`, timing, and a `dismiss` function, and gets no injected dismiss control. | Current source and tests |+| FR2 | With auto-hide on (the default for `info`, off for `error`), the card dismisses with reason `auto` after `autoHideDuration` ms. The timer pauses while the pointer is over the card, focus is inside it, a touch or pen gesture is active, or the window is blurred, and resumes with the remaining time (at least 1 s). Each pause condition holds the timer on its own: one ending resumes it only when no other still holds, and focus moving between the card's own controls keeps it held. A toast raised while the window is already blurred starts with its timer held. | Current source and tests |+| FR3 | The dismiss button, a swipe, a `dismiss` call, or the returned dismiss function dismiss with reason `manual`; `onHide` fires at most once, when the toast is dismissed, even when dismissed twice during its exit or before it shows. A toast replaced through `uniqueID` is not dismissed and reports no `onHide`. | Current source and tests |+| FR4 | A drag toward the position's block edge, from any pointer (`spec:AST-094` FR43), decides once, at release, per `spec:AST-094` FR36–FR37: projected travel past the commit point dismisses, and a release moving back toward the start cancels. A short drag snaps back; horizontal intent, a second touch, or a gesture starting on an interactive descendant does not dismiss. Native page scrolling continues until touch intent matches the dismiss edge. On a touch screen, the touch's first move decides: toward the dismiss edge, the swipe owns the touch. In the default layout the visible dismiss button stays as a non-gesture alternative; custom content supplies its own. Implementation gaps: the shipped rule dismisses on net travel past a distance threshold or a fast flick timed by its own average speed, even after the finger moves back, and recognizes only touch and pen drags, not a mouse (Current-state impact). | Current source and tests |+| FR5 | A new card slides in from its edge and fades in; a dismissed card collapses and fades before it unmounts; both slide only along the block axis. A dismissal without a swipe uses theme timing; a swipe's commit and snap-back start at the release velocity (`spec:AST-094` FR38). Under reduced motion the entrance and dismissal are an opacity-only fade of 200 ms or less on a coarse pointer or after a touch release (`design:reduced-motion` DR2) and immediate otherwise (DR3), and the card still unmounts. Implementation gaps: a swipe's settle is a CSS transition at theme timing, and under reduced motion every transition, including the row collapse and the swipe's throw, runs for 0.01 ms on every pointer (Current-state impact). | Current source and tests |+| FR6 | The viewport stacks toasts at `position`, newest nearest the configured edge, with an 8 px gap and no extra space at the edge beyond the safe-area gutter it keeps; it spans the inline axis within its inset, honoring start and end insets in either direction. The bottom gutter is 16 px beyond the bottom safe-area inset; under a coarse pointer it is 16 px beyond the larger of that inset and 34 px (`16px + max(env(safe-area-inset-bottom), 34px)`), so a toast clears the home indicator even where the page reports no inset. With a fine pointer and no inset it is 16 px. The 34 px floor is the iPhone home indicator's height; it applies on every coarse-pointer device, since browsers report the inset only when a page opts in. Each edge sits at the provider's `layerInset`, and a `toast.inset` edge, when set, replaces it (`spec:AST-059` FR6). Implementation gaps: a `toast.inset` edge set to 0 does not replace the provider's value, and an edge opposite the position, such as `top` for a bottom stack, moves the stack to that edge (Current-state impact). | Current source and tests |+| FR7 | With `maxVisible` of 1 or more, at most that many toasts show; when more are raised, the oldest wait hidden and return as visible toasts leave. `maxVisible={0}` shows every toast. | Current source and tests |+| FR8 | A toast whose `uniqueID` matches a toast the viewport holds, whether shown, hidden by the cap, or exiting, replaces it in place under `overwrite` (and is announced again; the card updates in place under the same key, so focus inside it stays on the same control, or moves per FR10 when that control no longer exists), and is dropped unshown and unannounced under `ignore`, even when both are raised before the first renders. Implementation gap: overwriting a toast hidden by the cap announces it while it is not shown, and nothing is announced when it surfaces (Current-state impact). | Current source and tests |+| FR9 | Each shown toast has one announcement owner (`spec:AST-086` FR1): the viewport announces it once, when it is shown, `error` assertively and `info` politely, using the toast's text content, through its own persistent polite and assertive containers, which move with it into a modal (`spec:AST-086` FR10). Unrelated renders do not re-announce. Implementation gaps: the viewport announces through the shared body-level channel, which a modal hides, and announces at dispatch rather than when a toast appears (Current-state impact). | `spec:AST-086`; tests |+| FR10 | F6 moves focus to the first control in the newest toast. Focus entering the viewport, by F6, Tab or a click, records where it was. Dismissing a toast that holds focus moves focus to a control in a remaining toast, or back to the remembered element when none remain. When focus reached the viewport by Tab or a click, dismissing the focused toast follows the same handoff: a control in a remaining toast, else the remembered element; with no control in the target toast, F6 leaves focus where it was, and a handoff never drops focus to the page body. | Current source and tests |+| FR11 | While a toast is visible the viewport is a `region` landmark named by `@astryx.toast.viewport`, without `aria-modal`; it exposes no landmark when empty, so an empty nested viewport adds none. Implementation gap: nested viewports that each hold a toast expose two landmarks (Current-state impact). | Current source and tests |+| FR12 | A top-layer viewport moves into the latest open Dialog, modal Drawer, scrim sheet, or modal flow step, following the top of a stack and handing back to the one beneath when it closes, and returns to its place when none remains, keeping each toast, its timer, and focus inside the viewport. It re-enters the top layer in place when a non-modal sheet or a drawer without a scrim opens after it, and stays in place when rendered in place, or when an inline dialog, a sheet without a scrim, or a non-modal flow opens. | `spec:AST-003`; tests |### Allowed variation@@ -243,16 +259,16 @@ button), so no anatomy part can own the `toast` target.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | --------------------------- |-| FR1, FR3 | `ToastViewport.test.tsx` layout, custom content, and onHide tests; `Layer/toastHost.test.tsx` and `toastHost.lateRegistration.test.tsx` toasts dismissed or replaced before they show | Default, custom content, double dismiss, a dismissal before the toast shows | Dropped controls or a repeated `onHide` fails. | `audit:Toast/behavior` |-| FR2 | `ToastViewport.test.tsx` blur-pause, pause-source and raised-while-blurred tests | Window blur, toast raised while blurred, new toast during pause, overlapping pointer/focus/window holds, focus moving inside | A timer running while paused, or resuming while another hold remains, fails. | `audit:Toast/behavior` |-| FR4, FR5 | `ToastViewport.test.tsx` gesture and motion tests | Pen and touch thresholds, short drag, horizontal intent, second touch, interactive descendant, RTL | A dismissal from a rejected gesture, a lost snap-back, or off-axis drift fails. | `audit:Toast/behavior` |-| FR6–FR8 | `ToastViewport.test.tsx` placement, cap, and uniqueID tests; `Layer/LayerProvider.test.tsx` inset tests | Each position, cap 1 and an explicit cap, overwrite, ignore | Wrong order, cap, or collision fails. | `audit:Toast/layout` |-| FR9–FR11 | `ToastViewport.test.tsx` announcement, F6, focus, landmark tests | Info, error, StrictMode, nested viewports | A repeated or wrong-urgency announcement, or focus to the body after F6 entry, fails. | `audit:Toast/accessibility` |-| FR2, FR8–FR10 | `ToastViewport.test.tsx` "keeps focus on a control inside a toast that an overwrite updates", "hands focus off when an overwrite removes the focused control", "updates a settled toast in place when an overwrite replaces it through uniqueID", "announces an overwrite once, through the viewport only", "auto-hides a control-free replacement after the update removes the focused control" | Overwrite with focus inside; overwrite that removes the focused control | A remounted card, or focus dropping to the page body, fails. | `audit:Toast/accessibility` |-| FR10 | `ToastViewport.test.tsx` "restores focus after a toast reached with Tab rather than F6 is dismissed", "restores the remembered element when only a control-free toast remains" | Tab- or click-reached toast dismissed; a control-free toast remaining | Focus dropping to the page body after a dismissal fails. | `audit:Toast/accessibility` |-| FR12 | `ToastViewport.modalHost.test.tsx` | Dialog, nested dialogs, modal and scrimless drawers, sheets and sheet stacks, modal flows | A lost toast, timer, or focus, or the wrong outlet, fails. | `audit:Toast/layering` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- |+| FR1, FR3 | `ToastViewport.test.tsx` layout, custom content, and onHide tests; `Layer/toastHost.test.tsx` and `toastHost.lateRegistration.test.tsx` toasts dismissed or replaced before they show | Default, custom content, double dismiss, a dismissal before the toast shows | Dropped controls or a repeated `onHide` fails. | `audit:Toast/behavior` |+| FR2 | `ToastViewport.test.tsx` blur-pause, pause-source and raised-while-blurred tests | Window blur, toast raised while blurred, new toast during pause, overlapping pointer/focus/window holds, focus moving inside | A timer running while paused, or resuming while another hold remains, fails. | `audit:Toast/behavior` |+| FR4, FR5 | `ToastViewport.test.tsx` gesture and motion tests; `ToastSwipeScroll.interaction.browser.spec.ts` first move toward and away from the edge, slow and quick, from three offsets | Pen and touch thresholds, short drag, horizontal intent, second touch, interactive descendant, RTL | A dismissal from a rejected gesture, a lost snap-back, or off-axis drift fails. | `audit:Toast/behavior` |+| FR6–FR8 | `ToastViewport.test.tsx` placement, cap, and uniqueID tests; `Layer/LayerProvider.test.tsx` inset tests; `ToastSafeArea.a11y.chromium.spec.ts` bottom gutter, under a finger and a mouse, with insets of 0, 34 and 48 px | Each position, cap 1 and an explicit cap, overwrite, ignore | Wrong order, cap, or collision, or a bottom gap other than 16 px beyond the inset, or beyond the larger of the inset and 34 px under a coarse pointer, fails. | `audit:Toast/layout` |+| FR9–FR11 | `ToastViewport.test.tsx` announcement, F6, focus, landmark and empty-viewport tests; `ToastEmptyViewport.interaction.browser.spec.ts` no box once the last toast leaves | Info, error, StrictMode, nested viewports | A repeated or wrong-urgency announcement, or focus to the body after F6 entry, fails. | `audit:Toast/accessibility` |+| FR2, FR8–FR10 | `ToastViewport.test.tsx` "keeps focus on a control inside a toast that an overwrite updates", "hands focus off when an overwrite removes the focused control", "updates a settled toast in place when an overwrite replaces it through uniqueID", "announces an overwrite once, through the viewport only", "auto-hides a control-free replacement after the update removes the focused control" | Overwrite with focus inside; overwrite that removes the focused control | A remounted card, or focus dropping to the page body, fails. | `audit:Toast/accessibility` |+| FR10 | `ToastViewport.test.tsx` "restores focus after a toast reached with Tab rather than F6 is dismissed", "restores the remembered element when only a control-free toast remains" | Tab- or click-reached toast dismissed; a control-free toast remaining | Focus dropping to the page body after a dismissal fails. | `audit:Toast/accessibility` |+| FR12 | `ToastViewport.modalHost.test.tsx` | Dialog, nested dialogs, modal and scrimless drawers, sheets and sheet stacks, modal flows | A lost toast, timer, or focus, or the wrong outlet, fails. | `audit:Toast/layering` |Read from source, with no focused test yet:diff --git a/packages/core/src/Toast/ToastViewport.test.tsx b/packages/core/src/Toast/ToastViewport.test.tsxindex 0960d273d8..4e313c2799 100644--- a/packages/core/src/Toast/ToastViewport.test.tsx+++ b/packages/core/src/Toast/ToastViewport.test.tsx@@ -21,6 +21,7 @@ import {beforeAll,beforeEach,afterEach,+ onTestFinished,} from 'vitest';import {cleanup,@@ -1675,6 +1676,27 @@ describe('Toast native motion contract', () => {});describe('Toast swipe dismissal', () => {+ /**+ * A phone's coarse pointer, under which the gesture host listens for+ * fingers. Returns the restore.+ */+ function onTouchScreen(): () => void {+ const original = window.matchMedia;+ window.matchMedia = vi.fn().mockImplementation((query: string) => ({+ matches: query === '(pointer: coarse)',+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ }));+ return () => {+ window.matchMedia = original;+ };+ }+function renderSwipeToast(options: ToastOptions = SWIPE_TOAST,position: React.ComponentProps<@@ -1793,37 +1815,240 @@ describe('Toast swipe dismissal', () => {}});- it('snaps back without dismissing after a short drag', () => {- const {visualToast, onHide} = renderSwipeToast();+ // A one-line toast is 56 px tall, and 40% of that is below the 48 px floor.+ // A short swipe dismisses it only as a flick.+ function mockClock(start = 1_000) {+ let time = start;+ const spy = vi.spyOn(Date, 'now').mockImplementation(() => time);+ return {+ advance(ms: number) {+ time += ms;+ },+ restore() {+ spy.mockRestore();+ },+ };+ }- act(() => {- fireEvent.pointerDown(visualToast, {- pointerId: 7,- pointerType: 'pen',- button: 0,- clientX: 0,- clientY: 0,+ it('dismisses a quick pen flick on a one-line toast', () => {+ const clock = mockClock();+ try {+ const {visualToast, onHide} = renderSwipeToast(+ SWIPE_TOAST,+ 'bottomEnd',+ 'Swipe toast',+ 56,+ );++ act(() => {+ fireEvent.pointerDown(visualToast, {+ pointerId: 9,+ pointerType: 'pen',+ button: 0,+ clientX: 0,+ clientY: 0,+ });});- fireEvent.pointerMove(visualToast, {- pointerId: 7,- pointerType: 'pen',- clientX: 0,- clientY: 24,+ clock.advance(30);+ act(() => {+ fireEvent.pointerMove(visualToast, {+ pointerId: 9,+ pointerType: 'pen',+ clientX: 0,+ clientY: 40,+ });+ fireEvent.pointerUp(visualToast, {+ pointerId: 9,+ pointerType: 'pen',+ clientX: 0,+ clientY: 40,+ });});- fireEvent.pointerUp(visualToast, {- pointerId: 7,- pointerType: 'pen',- clientX: 0,- clientY: 24,++ expect(onHide).toHaveBeenCalledWith('manual');+ expect(onHide).toHaveBeenCalledTimes(1);+ } finally {+ clock.restore();+ }+ });++ it('dismisses a quick touch flick on a one-line toast at the top', () => {+ const clock = mockClock();+ const restorePointer = onTouchScreen();+ try {+ const {visualToast, onHide} = renderSwipeToast(+ SWIPE_TOAST,+ 'topEnd',+ 'Swipe toast',+ 56,+ );+ const touchEvent = (+ type: 'touchstart' | 'touchmove' | 'touchend',+ clientY: number,+ ) => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const touch = {identifier: 32, clientX: 10, clientY};+ Object.defineProperty(event, 'touches', {+ value: type === 'touchend' ? [] : [touch],+ });+ Object.defineProperty(event, 'changedTouches', {value: [touch]});+ visualToast.dispatchEvent(event);+ return event;+ };++ act(() => {+ touchEvent('touchstart', 100);+ });+ clock.advance(15);+ let move: Event;+ act(() => {+ move = touchEvent('touchmove', 80);+ });+ clock.advance(15);+ act(() => {+ touchEvent('touchmove', 60);+ touchEvent('touchend', 60);});- });- expect(onHide).not.toHaveBeenCalled();- expect(visualToast.style.getPropertyValue('--_toast-swipe-y')).toBe('');- expect(visualToast.style.getPropertyValue('--_toast-swipe-opacity')).toBe(- '',- );- expect(visualToast.style.getPropertyValue('--_toast-swipe-scale')).toBe('');+ expect(move!.defaultPrevented).toBe(true);+ expect(onHide).toHaveBeenCalledWith('manual');+ expect(onHide).toHaveBeenCalledTimes(1);+ } finally {+ restorePointer();+ clock.restore();+ }+ });++ it('times a flick by its input events, not by when the handlers run', () => {+ // Browsers can run move handlers well after the finger moved. Here the+ // 40 px flick takes 30 ms, and the page handles its moves and lift 60 ms+ // after touch-down.+ const clock = mockClock();+ try {+ const {visualToast, onHide} = renderSwipeToast(+ SWIPE_TOAST,+ 'topEnd',+ 'Swipe toast',+ 56,+ );+ const touchEvent = (+ type: 'touchstart' | 'touchmove' | 'touchend',+ clientY: number,+ ) => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const touch = {identifier: 33, clientX: 10, clientY};+ Object.defineProperty(event, 'touches', {+ value: type === 'touchend' ? [] : [touch],+ });+ Object.defineProperty(event, 'changedTouches', {value: [touch]});+ return event;+ };++ act(() => {+ visualToast.dispatchEvent(touchEvent('touchstart', 100));+ });+ clock.advance(15);+ const firstMove = touchEvent('touchmove', 80);+ clock.advance(15);+ const secondMove = touchEvent('touchmove', 60);+ const lift = touchEvent('touchend', 60);+ clock.advance(30);+ act(() => {+ visualToast.dispatchEvent(firstMove);+ visualToast.dispatchEvent(secondMove);+ visualToast.dispatchEvent(lift);+ });++ expect(onHide).toHaveBeenCalledWith('manual');+ } finally {+ clock.restore();+ }+ });++ it('snaps back after a slow short drag on a one-line toast', () => {+ const clock = mockClock();+ try {+ const {visualToast, onHide} = renderSwipeToast(+ SWIPE_TOAST,+ 'bottomEnd',+ 'Swipe toast',+ 56,+ );++ act(() => {+ fireEvent.pointerDown(visualToast, {+ pointerId: 10,+ pointerType: 'pen',+ button: 0,+ clientX: 0,+ clientY: 0,+ });+ });+ clock.advance(400);+ act(() => {+ fireEvent.pointerMove(visualToast, {+ pointerId: 10,+ pointerType: 'pen',+ clientX: 0,+ clientY: 40,+ });+ fireEvent.pointerUp(visualToast, {+ pointerId: 10,+ pointerType: 'pen',+ clientX: 0,+ clientY: 40,+ });+ });++ expect(onHide).not.toHaveBeenCalled();+ expect(visualToast.style.getPropertyValue('--_toast-swipe-y')).toBe('');+ } finally {+ clock.restore();+ }+ });++ it('snaps back without dismissing after a short drag', () => {+ // A slow drag: 24 px over 400 ms is far below flick speed.+ const clock = mockClock();+ try {+ const {visualToast, onHide} = renderSwipeToast();++ act(() => {+ fireEvent.pointerDown(visualToast, {+ pointerId: 7,+ pointerType: 'pen',+ button: 0,+ clientX: 0,+ clientY: 0,+ });+ });+ clock.advance(400);+ act(() => {+ fireEvent.pointerMove(visualToast, {+ pointerId: 7,+ pointerType: 'pen',+ clientX: 0,+ clientY: 24,+ });+ fireEvent.pointerUp(visualToast, {+ pointerId: 7,+ pointerType: 'pen',+ clientX: 0,+ clientY: 24,+ });+ });++ expect(onHide).not.toHaveBeenCalled();+ expect(visualToast.style.getPropertyValue('--_toast-swipe-y')).toBe('');+ expect(visualToast.style.getPropertyValue('--_toast-swipe-opacity')).toBe(+ '',+ );+ expect(visualToast.style.getPropertyValue('--_toast-swipe-scale')).toBe(+ '',+ );+ } finally {+ clock.restore();+ }});it('fades and subtly scales only after accepted vertical edge swipe intent', () => {@@ -2110,6 +2335,8 @@ describe('Toast swipe dismissal', () => {});it('allows native page scrolling until touch intent matches the dismiss edge', () => {+ const restorePointer = onTouchScreen();+ onTestFinished(restorePointer);const {visualToast, onHide} = renderSwipeToast(SWIPE_TOAST,'topEnd',@@ -2147,6 +2374,10 @@ describe('Toast swipe dismissal', () => {'changedTouches',{value: [{identifier: 31, clientX: 80, clientY: 104}]},);+ // A real touchmove lists the finger in `touches` too.+ Object.defineProperty(move, 'touches', {+ value: [{identifier: 31, clientX: 80, clientY: 104}],+ });act(() => {visualToast.dispatchEvent(move);});@@ -2165,7 +2396,111 @@ describe('Toast swipe dismissal', () => {expect(onHide).toHaveBeenCalledWith('manual');});+ it("ends the swipe when the gesture host leaves the touch to the page, in Chromium's pointer-before-touch order", () => {+ const restorePointer = onTouchScreen();+ onTestFinished(restorePointer);+ const {visualToast, onHide} = renderSwipeToast();+ const touchEvent = (+ type: 'touchstart' | 'touchmove' | 'touchend',+ clientY: number,+ ) => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const touch = {identifier: 33, clientX: 10, clientY, target: visualToast};+ Object.defineProperty(event, 'touches', {+ value: type === 'touchend' ? [] : [touch],+ });+ Object.defineProperty(event, 'changedTouches', {value: [touch]});+ visualToast.dispatchEvent(event);+ return event;+ };+ const finger = {pointerId: 9, pointerType: 'touch', isPrimary: true};++ act(() => {+ fireEvent.pointerDown(visualToast, {+ ...finger,+ clientX: 10,+ clientY: 100,+ });+ touchEvent('touchstart', 100);+ });+ // Chromium sends the finger's pointermoves inside its touch slop and holds+ // back the touchmoves. The first sample goes 1 px away from the edge.+ act(() => {+ fireEvent.pointerMove(visualToast, {...finger, clientX: 10, clientY: 99});+ });+ let move: Event;+ act(() => {+ move = touchEvent('touchmove', 117);+ });+ expect(move!.defaultPrevented).toBe(false);+ act(() => {+ fireEvent.pointerMove(visualToast, {+ ...finger,+ clientX: 10,+ clientY: 160,+ });+ touchEvent('touchmove', 160);+ });+ expect(visualToast.style.getPropertyValue('--_toast-swipe-y')).toBe('');+ act(() => {+ touchEvent('touchend', 160);+ });+ expect(onHide).not.toHaveBeenCalled();+ });++ it('swipes normally on the next touch after a first touch the page took', () => {+ const restorePointer = onTouchScreen();+ onTestFinished(restorePointer);+ const {visualToast, onHide} = renderSwipeToast();+ const touchEvent = (+ type: 'touchstart' | 'touchmove' | 'touchend',+ identifier: number,+ clientX: number,+ clientY: number,+ ) => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const touch = {identifier, clientX, clientY, target: visualToast};+ Object.defineProperty(event, 'touches', {+ value: type === 'touchend' ? [] : [touch],+ });+ Object.defineProperty(event, 'changedTouches', {value: [touch]});+ visualToast.dispatchEvent(event);+ return event;+ };++ // The first touch moves sideways first, so the page keeps it.+ act(() => {+ touchEvent('touchstart', 35, 10, 100);+ });+ let move: Event;+ act(() => {+ move = touchEvent('touchmove', 35, 13, 100);+ });+ expect(move!.defaultPrevented).toBe(false);+ act(() => {+ touchEvent('touchmove', 35, 13, 160);+ touchEvent('touchend', 35, 13, 160);+ });+ expect(onHide).not.toHaveBeenCalled();++ // The next touch moves toward the edge first, so the swipe owns it.+ act(() => {+ touchEvent('touchstart', 36, 10, 100);+ });+ act(() => {+ move = touchEvent('touchmove', 36, 10, 101);+ });+ expect(move!.defaultPrevented).toBe(true);+ act(() => {+ touchEvent('touchmove', 36, 10, 160);+ touchEvent('touchend', 36, 10, 160);+ });+ expect(onHide).toHaveBeenCalledWith('manual');+ });+it('resets an accepted touch gesture on native touchcancel', () => {+ const restorePointer = onTouchScreen();+ onTestFinished(restorePointer);const {visualToast, onHide} = renderSwipeToast();const touch = (type: 'touchstart' | 'touchmove', clientY: number) => {const event = new Event(type, {bubbles: true, cancelable: true});@@ -2310,14 +2645,32 @@ describe('Toast swipe dismissal', () => {});});- it('removes native touch listeners when a Toast unmounts', () => {- const {visualToast, unmount} = renderSwipeToast();- const removeListener = vi.spyOn(visualToast, 'removeEventListener');-- unmount();-- for (const type of ['touchstart', 'touchmove', 'touchend', 'touchcancel']) {- expect(removeListener).toHaveBeenCalledWith(type, expect.any(Function));+ it('leaves no touch listener on the card once a Toast unmounts', () => {+ const addListener = vi.spyOn(HTMLElement.prototype, 'addEventListener');+ const removeListener = vi.spyOn(+ HTMLElement.prototype,+ 'removeEventListener',+ );+ try {+ const {visualToast, unmount} = renderSwipeToast();+ unmount();+ const touchListeners = (spy: typeof addListener) =>+ spy.mock.calls+ .filter(+ ([type], call) =>+ spy.mock.contexts[call] === visualToast &&+ type.startsWith('touch'),+ )+ .map(([type, listener]) => [type, listener]);+ const added = touchListeners(addListener);+ const removed = touchListeners(removeListener);+ // The gesture host's own listener shows that the spies see the card.+ expect(added.length).toBeGreaterThan(0);+ expect(removed).toHaveLength(added.length);+ expect(removed).toEqual(expect.arrayContaining(added));+ } finally {+ addListener.mockRestore();+ removeListener.mockRestore();}});@@ -2474,6 +2827,37 @@ describe('Toast swipe dismissal', () => {});});+describe('ToastViewport with no toasts', () => {+ // iOS Safari keeps a toolbar color that it took from the viewport while+ // the viewport has a box.+ it('has no box once its last toast has left, and a box for the next toast', () => {+ renderViewport(<ShowToastButton options={SWIPE_TOAST} />);+ act(() => {+ fireEvent.click(screen.getByText('Trigger'));+ });+ const viewport = screen.getByRole('region', {name: 'Notifications'});+ expect(getComputedStyle(viewport).display).toBe('flex');++ const wrapper = getToastWrapperByText('Swipe toast');+ act(() => {+ fireEvent.click(+ within(wrapper).getByRole('button', {name: 'Dismiss notification'}),+ );+ });+ // The leaving toast keeps the box until its exit ends.+ expect(getComputedStyle(viewport).display).toBe('flex');+ act(() => {+ completeExit(wrapper.dataset.toastId ?? '');+ });+ expect(getComputedStyle(viewport).display).toBe('none');++ act(() => {+ fireEvent.click(screen.getByText('Trigger'));+ });+ expect(getComputedStyle(viewport).display).toBe('flex');+ });+});+describe('ToastViewport region ARIA', () => {it('does not expose an empty notifications landmark', () => {renderViewport(<ShowToastButton />);diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsxindex 71b4c8a238..2937d66550 100644--- a/packages/core/src/Toast/ToastViewport.tsx+++ b/packages/core/src/Toast/ToastViewport.tsx@@ -63,7 +63,13 @@ registerEnglishFallback(english);const SAFE_AREA_INLINE_START = `max(${spacingVars['--spacing-4']}, env(safe-area-inset-left, 0px))`;const SAFE_AREA_INLINE_END = `max(${spacingVars['--spacing-4']}, env(safe-area-inset-right, 0px))`;const SAFE_AREA_BLOCK_START = `max(${spacingVars['--spacing-4']}, env(safe-area-inset-top, 0px))`;-const SAFE_AREA_BLOCK_END = `max(${spacingVars['--spacing-4']}, env(safe-area-inset-bottom, 0px))`;+// On an iPhone, a downward swipe that starts in the bottom inset can pull the+// whole screen down. Keep the toast clear of that inset.+const SAFE_AREA_BLOCK_END = `calc(${spacingVars['--spacing-4']} + env(safe-area-inset-bottom, 0px))`;+// Safari reports the inset only to a page with `viewport-fit=cover`. Under a+// coarse pointer the gutter clears 34 px anyway: a Face ID iPhone's bottom+// inset in portrait.+const SAFE_AREA_BLOCK_END_TOUCH = `calc(${spacingVars['--spacing-4']} + max(env(safe-area-inset-bottom, 0px), 34px))`;const TOAST_EDGE_DRIFT = spacingVars['--spacing-2'];const TOAST_EDGE_DRIFT_NEGATIVE = `calc(-1 * ${TOAST_EDGE_DRIFT})`;@@ -78,7 +84,10 @@ const styles = stylex.create({boxSizing: 'border-box',flexDirection: 'column',paddingBlockStart: SAFE_AREA_BLOCK_START,- paddingBlockEnd: SAFE_AREA_BLOCK_END,+ paddingBlockEnd: {+ default: SAFE_AREA_BLOCK_END,+ '@media (pointer: coarse)': SAFE_AREA_BLOCK_END_TOUCH,+ },paddingInlineStart: {default: SAFE_AREA_INLINE_START,':is([dir="rtl"] *)': SAFE_AREA_INLINE_END,@@ -108,6 +117,13 @@ const styles = stylex.create({backgroundColor: 'transparent',overflow: 'visible',},+ // iOS Safari colors its toolbar from a fixed element at the bottom edge. A+ // toast that a swipe sends through that edge gives the viewport its color.+ // Safari keeps that color while the viewport has a box, so an empty+ // viewport has none.+ viewportEmpty: {+ display: 'none',+ },// The viewport sits at the inset the app declared on LayerProvider for a// bar floating over that edge (spec:AST-059 FR6); unset, each reads 0px.// A toast-only `inset` prop writes the same edges inline and wins.@@ -947,6 +963,7 @@ export function ToastViewport({styles.viewport,styles.viewportInlineSpan,posStyle,+ !hasToasts && styles.viewportEmpty,),{style: Object.keys(insetStyle).length > 0 ? insetStyle : undefined,diff --git a/packages/core/src/Toast/__tests__/ToastEmptyViewport.interaction.browser.spec.ts b/packages/core/src/Toast/__tests__/ToastEmptyViewport.interaction.browser.spec.tsnew file mode 100644index 0000000000..6316fb632e--- /dev/null+++ b/packages/core/src/Toast/__tests__/ToastEmptyViewport.interaction.browser.spec.ts@@ -0,0 +1,99 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ToastEmptyViewport.interaction.browser.spec.ts+ * @input The ErrorPersists story, whose toast stays until dismissed, on a+ * phone page, with a finger, in Chromium and WebKit.+ * @output Tests that the toast viewport has no box once its last toast has+ * left, by a swipe or by its dismiss button. The viewport has a box again+ * for the next toast.+ * @position iOS Safari colors its toolbar from a fixed element at the bottom+ * edge. A swiped toast leaves through that edge, and Safari keeps its color+ * while the viewport has a box.+ */+import {+ expect,+ test,+ type ElementHandle,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ drag,+ openStory,+ touchDriver,+ waitForRest,+ withStorybook,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++test.use({+ viewport: {width: 390, height: 844},+ isMobile: true,+ hasTouch: true,+});++async function showToast(page: Page): Promise<Locator> {+ await page.getByRole('button', {name: 'Trigger error'}).click();+ const card = page.locator('.astryx-toast').first();+ await expect(card).toBeVisible();+ await waitForRest(card);+ return card;+}++/** The viewport keeps its element when it empties, so a handle outlives its landmark role. */+async function viewportOf(page: Page): Promise<ElementHandle<HTMLElement>> {+ const handle = await page+ .getByRole('region', {name: 'Notifications'})+ .elementHandle();+ if (handle == null) {+ throw new Error('no toast viewport');+ }+ return handle as ElementHandle<HTMLElement>;+}++const boxCount = async (viewport: ElementHandle<HTMLElement>) =>+ viewport.evaluate(element => element.getClientRects().length);++test('the viewport has no box once a swipe sends its last toast away', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-toast--error-persists');+ const driver = await touchDriver(page);+ const card = await showToast(page);+ const viewport = await viewportOf(page);+ expect(await boxCount(viewport)).toBeGreaterThan(0);++ const box = await card.boundingBox();+ if (box == null) {+ throw new Error('no toast');+ }+ const from = {+ x: Math.round(box.x + box.width / 2),+ y: Math.round(box.y + box.height / 2),+ };+ await driver.play(+ drag(+ from,+ {x: from.x, y: from.y + 90},+ {durationMs: 120, hz: 60, restMs: 0},+ ),+ );+ await expect(page.locator('.astryx-toast')).toHaveCount(0);+ await expect.poll(async () => boxCount(viewport)).toBe(0);++ await showToast(page);+ expect(await boxCount(viewport)).toBeGreaterThan(0);+});++test('the viewport has no box once its dismiss button sends its last toast away', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-toast--error-persists');+ const card = await showToast(page);+ const viewport = await viewportOf(page);+ await card.getByRole('button', {name: 'Dismiss notification'}).click();+ await expect(page.locator('.astryx-toast')).toHaveCount(0);+ await expect.poll(async () => boxCount(viewport)).toBe(0);+});diff --git a/packages/core/src/Toast/__tests__/ToastSafeArea.a11y.chromium.spec.ts b/packages/core/src/Toast/__tests__/ToastSafeArea.a11y.chromium.spec.tsnew file mode 100644index 0000000000..d118ceb0b4--- /dev/null+++ b/packages/core/src/Toast/__tests__/ToastSafeArea.a11y.chromium.spec.ts@@ -0,0 +1,110 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ToastSafeArea.a11y.chromium.spec.ts+ * @input The Default story on an iPhone-sized page in Chromium, whose DevTools+ * protocol emulates the bottom safe-area inset (34 px in portrait).+ * @output Tests that a bottom toast sits its 16 px gap above that inset. Under a+ * finger it clears 34 px even with no reported inset. With a mouse and no+ * inset the gap is 16 px.+ * @position Chromium only: Playwright's WebKit has no safe-area emulation.+ */+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();+});++// An iPhone 17 Pro page in Safari, portrait.+test.use({+ viewport: {width: 402, height: 714},+ deviceScaleFactor: 3,+ isMobile: true,+ hasTouch: true,+});++const GAP = 16;++async function emulateBottomInset(page: Page, bottom: number): Promise<void> {+ const session = await page.context().newCDPSession(page);+ await session.send('Emulation.setSafeAreaInsetsOverride', {+ insets: {+ top: 0,+ topMax: 0,+ bottom,+ bottomMax: bottom,+ left: 0,+ leftMax: 0,+ right: 0,+ rightMax: 0,+ },+ });+}++/** From the shown toast's bottom edge to the screen's bottom edge, px. */+async function bottomGap(page: Page): Promise<number> {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-toast--default&viewMode=story`,+ );+ await page.getByRole('button', {name: 'Show toast'}).click();+ const card = page.locator('.astryx-toast').first();+ await expect(card).toBeVisible();+ // The toast rests once the page's animations end, canceled ones included.+ await page.evaluate(async () => {+ await Promise.allSettled(+ document+ .getAnimations()+ .filter(+ animation => animation.effect?.getTiming().iterations !== Infinity,+ )+ .map(async animation => animation.finished),+ );+ });+ return card.evaluate(+ element => window.innerHeight - element.getBoundingClientRect().bottom,+ );+}++test('a bottom toast sits its 16 px gap above the bottom safe-area inset', async ({+ page,+}) => {+ await emulateBottomInset(page, 34);+ expect(await bottomGap(page)).toBeCloseTo(34 + GAP, 0);+});++test('under a finger with no reported inset, a bottom toast still clears 34 px', async ({+ page,+}) => {+ await emulateBottomInset(page, 0);+ expect(await bottomGap(page)).toBeCloseTo(34 + GAP, 0);+});++test('a bottom inset above 34 px adds its own size', async ({page}) => {+ await emulateBottomInset(page, 48);+ expect(await bottomGap(page)).toBeCloseTo(48 + GAP, 0);+});++test.describe('with a mouse', () => {+ test.use({isMobile: false, hasTouch: false});++ test('with no inset, a bottom toast keeps its 16 px gap', async ({page}) => {+ await emulateBottomInset(page, 0);+ expect(await bottomGap(page)).toBeCloseTo(GAP, 0);+ });++ test('a bottom toast sits its 16 px gap above the inset', async ({page}) => {+ await emulateBottomInset(page, 34);+ expect(await bottomGap(page)).toBeCloseTo(34 + GAP, 0);+ });+});diff --git a/packages/core/src/Toast/__tests__/ToastSwipeScroll.interaction.browser.spec.ts b/packages/core/src/Toast/__tests__/ToastSwipeScroll.interaction.browser.spec.tsnew file mode 100644index 0000000000..e9777a640a--- /dev/null+++ b/packages/core/src/Toast/__tests__/ToastSwipeScroll.interaction.browser.spec.ts@@ -0,0 +1,212 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ToastSwipeScroll.interaction.browser.spec.ts+ * @input The ErrorPersists story, whose toast stays until dismissed, on a+ * phone page taller than the screen, with a finger, in Chromium and WebKit.+ * @output Tests that a bottom toast decides a touch on its first move. The+ * test starts from three offsets on the card, slowly and quickly. A first+ * move toward the edge is the swipe's and never scrolls the page. A first+ * move away from the edge leaves the page its scroll.+ * @position iOS commits a page scroll on the first move that no listener+ * prevents, so the first move decides.+ */+import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ drag,+ openStory,+ touchDriver,+ waitForRest,+ withStorybook,+ type TouchDriver,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++test.use({+ viewport: {width: 390, height: 844},+ isMobile: true,+ hasTouch: true,+});++const SCROLLED_TO = 600;+const OFFSETS = [0.25, 0.5, 0.75] as const;+// A quick start toward the edge can be a flick that dismisses the toast.+const STARTS = [+ {label: 'toward the edge, slowly', dy: 24, durationMs: 600, owns: true},+ {label: 'toward the edge, quickly', dy: 40, durationMs: 100, owns: true},+ {label: 'away from the edge, slowly', dy: -60, durationMs: 600, owns: false},+ {label: 'away from the edge, quickly', dy: -60, durationMs: 120, owns: false},+] as const;++type Recorder = {__firstMovePrevented?: boolean | null};++async function scrollTop(page: Page): Promise<number> {+ return page.evaluate(() => document.scrollingElement?.scrollTop ?? 0);+}++/** Waits until the page holds still for 500 ms, so a fling has ended. */+async function waitForStillPage(page: Page): Promise<void> {+ await page.evaluate(+ async () =>+ new Promise<void>(resolve => {+ let last = document.scrollingElement?.scrollTop ?? 0;+ let stillSince = performance.now();+ const timer = setInterval(() => {+ const top = document.scrollingElement?.scrollTop ?? 0;+ if (top !== last) {+ last = top;+ stillSince = performance.now();+ } else if (performance.now() - stillSince >= 500) {+ clearInterval(timer);+ resolve();+ }+ }, 50);+ }),+ );+}++/** Scrolls the page back to its start once it holds still. */+async function resetScroll(page: Page): Promise<void> {+ await waitForStillPage(page);+ await page.evaluate(top => window.scrollTo(0, top), SCROLLED_TO);+ await waitForStillPage(page);+ expect(await scrollTop(page)).toBe(SCROLLED_TO);+}++async function showToast(page: Page): Promise<Locator> {+ // A script click, so the scrolled page stays where it is.+ await page+ .getByRole('button', {name: 'Trigger error'})+ .evaluate(element => (element as HTMLElement).click());+ const card = page.locator('.astryx-toast').first();+ await expect(card).toBeVisible();+ await waitForRest(card);+ return card;+}++async function openScrolledPage(page: Page): Promise<TouchDriver> {+ await openStory(page, storybook(), 'core-toast--error-persists');+ const driver = await touchDriver(page);+ // A page taller than the screen, scrolled partway down. A passive window+ // listener runs after the card's own and reads whether it prevented the+ // touch's first move.+ await page.evaluate(top => {+ const spacer = document.createElement('div');+ spacer.style.height = '4000px';+ document.body.append(spacer);+ window.scrollTo(0, top);+ const recorder = window as unknown as Recorder;+ recorder.__firstMovePrevented = null;+ window.addEventListener(+ 'touchmove',+ event => {+ if (recorder.__firstMovePrevented == null) {+ recorder.__firstMovePrevented = event.defaultPrevented;+ }+ },+ {passive: true},+ );+ }, SCROLLED_TO);+ await expect.poll(async () => scrollTop(page)).toBe(SCROLLED_TO);+ return driver;+}++/** Swipes from `offset` of the card and returns whether the toast prevented the first move. */+async function swipe(+ page: Page,+ driver: TouchDriver,+ card: Locator,+ offset: number,+ start: (typeof STARTS)[number],+): Promise<boolean | null> {+ const box = await card.boundingBox();+ if (box == null) {+ throw new Error('no toast');+ }+ const from = {+ x: Math.round(box.x + box.width / 2),+ y: Math.round(box.y + box.height * offset),+ };+ await page.evaluate(() => {+ (window as unknown as Recorder).__firstMovePrevented = null;+ });+ await driver.play(+ drag(+ from,+ {x: from.x, y: from.y + start.dy},+ {durationMs: start.durationMs, hz: 60, restMs: 0},+ ),+ );+ return page.evaluate(+ () => (window as unknown as Recorder).__firstMovePrevented ?? null,+ );+}++/** Shows a new toast if the last swipe dismissed it. */+async function restoreToast(page: Page, card: Locator): Promise<Locator> {+ if ((await page.locator('.astryx-toast').count()) === 0) {+ return showToast(page);+ }+ await waitForRest(card);+ return card;+}++test('a touch on a bottom toast is decided by its first move', async ({+ page,+}) => {+ test.setTimeout(120_000);+ const driver = await openScrolledPage(page);+ let card = await showToast(page);+ for (const offset of OFFSETS) {+ for (const start of STARTS) {+ const prevented = await swipe(page, driver, card, offset, start);+ expect(prevented, `${start.label}, at ${offset} of the card`).toBe(+ start.owns,+ );+ card = await restoreToast(page, card);+ await resetScroll(page);+ }+ }+});++test('a first move toward the edge never scrolls the page, and one away from it scrolls as usual', async ({+ page,+ browserName,+}) => {+ test.skip(+ browserName !== 'chromium',+ "Playwright's WebKit scrolls no page from a synthetic touch",+ );+ test.setTimeout(120_000);+ const driver = await openScrolledPage(page);+ // Control: the same swipe on the page itself scrolls it.+ await driver.play(+ drag({x: 195, y: 300}, {x: 195, y: 240}, {durationMs: 600, hz: 60}),+ );+ await expect.poll(async () => scrollTop(page)).toBeGreaterThan(SCROLLED_TO);+ await resetScroll(page);+ let card = await showToast(page);+ for (const offset of OFFSETS) {+ for (const start of STARTS) {+ const before = await scrollTop(page);+ await swipe(page, driver, card, offset, start);+ const label = `${start.label}, at ${offset} of the card`;+ if (start.owns) {+ await waitForStillPage(page);+ expect(await scrollTop(page), label).toBe(before);+ } else {+ await expect+ .poll(async () => scrollTop(page), {message: label})+ .toBeGreaterThan(SCROLLED_TO);+ }+ card = await restoreToast(page, card);+ await resetScroll(page);+ }+ }+});diff --git a/packages/core/src/Toast/useToastGesture.ts b/packages/core/src/Toast/useToastGesture.tsindex d0b0167555..3931c29aac 100644--- a/packages/core/src/Toast/useToastGesture.ts+++ b/packages/core/src/Toast/useToastGesture.ts@@ -6,16 +6,26 @@* @file useToastGesture.ts* @input Uses a resolved Toast edge direction, timer pause/resume hooks,* dismissal callback, enabled state, and interactive-descendant policy- * @output Returns the Toast card root ref and touch/pen gesture bindings+ * @output Returns the Toast card root ref and touch/pen gesture bindings; the+ * gesture host claims a finger's touch through a one-way pan* @position Internal Toast gesture unit; attached to the Toast card root*/import {useCallback, useEffect, useRef} from 'react';-import type {PointerEvent as ReactPointerEvent, RefObject} from 'react';+import type {+ PointerEvent as ReactPointerEvent,+ RefObject,+ Touch as ReactTouch,+ TouchEvent as ReactTouchEvent,+} from 'react';+import {PanGestureRecognizer} from '../gestures/PanGestureRecognizer';+import {useGestureRecognizer} from '../gestures/useGestureRecognizer';const DRAG_PROMOTION_SLOP = 8;const SWIPE_DISMISS_RATIO = 0.4;-const FLICK_MIN_DISTANCE = 48;+/** The dismiss distance of a card too short for its height ratio to reach it. */+const SWIPE_DISMISS_MIN_DISTANCE = 48;+/** Average speed, px/ms, at which a release dismisses whatever its travel. */const FLICK_VELOCITY = 1.2;const VERTICAL_INTENT_RATIO = 1.2;const SWIPE_EXIT_DISTANCE = '120%';@@ -29,6 +39,11 @@ interface GesturePoint {pointerId: number;clientX: number;clientY: number;+ /**+ * The input event's `timeStamp`, which is when the finger was there.+ * Browsers can run a move's handler a frame or two later.+ */+ time: number;}interface GestureState {@@ -64,6 +79,10 @@ interface ToastGestureBindings {onPointerUp: (event: ReactPointerEvent<HTMLDivElement>) => void;onPointerCancel: (event: ReactPointerEvent<HTMLDivElement>) => void;onLostPointerCapture: (event: ReactPointerEvent<HTMLDivElement>) => void;+ onTouchStart: (event: ReactTouchEvent<HTMLDivElement>) => void;+ onTouchMove: (event: ReactTouchEvent<HTMLDivElement>) => void;+ onTouchEnd: (event: ReactTouchEvent<HTMLDivElement>) => void;+ onTouchCancel: (event: ReactTouchEvent<HTMLDivElement>) => void;}interface UseToastGestureResult {@@ -95,6 +114,37 @@ export function useToastGesture({}: UseToastGestureOptions): UseToastGestureResult {const rootRef = useRef<HTMLDivElement>(null);const gestureRef = useRef<GestureState | null>(null);+ const shouldIgnoreTargetRef = useRef(shouldIgnoreTarget);+ shouldIgnoreTargetRef.current = shouldIgnoreTarget;++ // The gesture host's pan only claims the touch and never begins. This hook+ // draws the swipe.+ const claim = useGestureRecognizer(+ rootRef,+ () =>+ new PanGestureRecognizer({+ name: 'toast-swipe',+ direction: direction === 1 ? 'down' : 'up',+ firstMoveDecides: true,+ maximumNumberOfTouches: 1,+ hysteresis: Number.POSITIVE_INFINITY,+ cancelsTouchesInView: false,+ shouldReceiveTouch: (_recognizer, touch) => {+ const root = rootRef.current;+ return (+ touch.pointerType === 'touch' &&+ root != null &&+ !shouldIgnoreTargetRef.current(touch.target as EventTarget, root)+ );+ },+ }),+ undefined,+ {isEnabled: enabled, manageStyle: false},+ );+ // Syncs the gesture host's pan with the edge this toast dismisses toward.+ useEffect(() => {+ claim.setDirection(direction === 1 ? 'down' : 'up');+ }, [claim, direction]);const resetGesture = useCallback((shouldResume: boolean) => {@@ -132,14 +182,14 @@ export function useToastGesture({pointerId: point.pointerId,startX: point.clientX,startY: point.clientY,- startTime: Date.now(),+ startTime: point.time,direction,intent: 'pending',pausedTimer,surfaceSize,dismissThreshold: Math.max(surfaceSize * SWIPE_DISMISS_RATIO,- FLICK_MIN_DISTANCE,+ SWIPE_DISMISS_MIN_DISTANCE,),};return true;@@ -157,7 +207,7 @@ export function useToastGesture({const moveGesture = useCallback((point: GesturePoint,- preventDefault: () => void,+ preventDefault?: () => void,releaseCapture?: () => void,) => {const state = gestureRef.current;@@ -194,7 +244,7 @@ export function useToastGesture({}root.style.setProperty('transition-duration', '0s');}- preventDefault();+ preventDefault?.();const travel = Math.max(0, deltaY * state.direction);const progress = swipeProgressValue(travel, state.surfaceSize);root.style.setProperty(@@ -229,11 +279,12 @@ export function useToastGesture({0,(point.clientY - state.startY) * state.direction,);- const elapsed = Math.max(1, Date.now() - state.startTime);+ const elapsed = Math.max(1, point.time - state.startTime);+ // A flick needs no travel floor. Intent turns vertical only past the 8 px+ // slop toward the edge.const isDismissed =state.intent === 'vertical' &&- (travel >= state.dismissThreshold ||- (travel >= FLICK_MIN_DISTANCE && travel / elapsed > FLICK_VELOCITY));+ (travel >= state.dismissThreshold || travel / elapsed > FLICK_VELOCITY);gestureRef.current = null;root.style.removeProperty('transition-duration');@@ -270,6 +321,7 @@ export function useToastGesture({pointerId: event.pointerId,clientX: event.clientX,clientY: event.clientY,+ time: event.timeStamp,},event.target,)@@ -291,6 +343,7 @@ export function useToastGesture({pointerId: event.pointerId,clientX: event.clientX,clientY: event.clientY,+ time: event.timeStamp,},() => event.preventDefault(),() => rootRef.current?.releasePointerCapture?.(event.pointerId),@@ -310,6 +363,7 @@ export function useToastGesture({pointerId: event.pointerId,clientX: event.clientX,clientY: event.clientY,+ time: event.timeStamp,});},[endGesture],@@ -328,28 +382,41 @@ export function useToastGesture({[resetGesture],);- useEffect(() => {- const root = rootRef.current;- if (!root || !enabled) {- return;- }- const point = (touch: Touch): GesturePoint => ({+ // A finger's swipe is drawn from React's touch events. The gesture host's+ // pan claims the touch, so nothing here prevents a default.+ const touchPoint = useCallback(+ (+ touch: ReactTouch,+ event: ReactTouchEvent<HTMLDivElement>,+ ): GesturePoint => ({source: 'touch',pointerId: touch.identifier,clientX: touch.clientX,clientY: touch.clientY,- });- const changedTouch = (event: TouchEvent) => {+ time: event.timeStamp,+ }),+ [],+ );++ const changedTouch = useCallback(+ (event: ReactTouchEvent<HTMLDivElement>): ReactTouch | undefined => {const state = gestureRef.current;const pointerId = state?.source === 'touch' ? state.pointerId : null;return pointerId == null? undefined- : [...event.changedTouches].find(+ : Array.from(event.changedTouches).find(touch => touch.identifier === pointerId,);- };- const handleTouchStart = (event: TouchEvent) => {- if (event.touches?.length !== 1) {+ },+ [],+ );++ const handleTouchStart = useCallback(+ (event: ReactTouchEvent<HTMLDivElement>) => {+ if (!enabled) {+ return;+ }+ if (event.touches.length !== 1) {// A second contact means the browser may be handling pinch zoom or// two-finger scrolling. Abandon any accepted one-finger swipe before// touchmove can suppress that native gesture.@@ -358,48 +425,59 @@ export function useToastGesture({}const touch = event.changedTouches[0];if (touch != null) {- beginGesture(point(touch), event.target);+ beginGesture(touchPoint(touch, event), event.target);}- };- const handleTouchMove = (event: TouchEvent) => {- if (event.touches?.length !== 1) {+ },+ [beginGesture, enabled, resetGesture, touchPoint],+ );++ const handleTouchMove = useCallback(+ (event: ReactTouchEvent<HTMLDivElement>) => {+ if (!enabled) {+ return;+ }+ if (event.touches.length !== 1) {+ resetGesture(true);+ return;+ }+ // The gesture host's pan decides the touch from its first move. Once+ // the pan fails, the page has the touch, so the swipe ends too.+ if (gestureRef.current != null && claim.state === 'failed') {resetGesture(true);return;}const touch = changedTouch(event);if (touch) {- moveGesture(point(touch), () => {- if (event.cancelable) {- event.preventDefault();- }- });+ moveGesture(touchPoint(touch, event));+ }+ },+ [changedTouch, claim, enabled, moveGesture, resetGesture, touchPoint],+ );++ const handleTouchEnd = useCallback(+ (event: ReactTouchEvent<HTMLDivElement>) => {+ if (!enabled) {+ return;}- };- const handleTouchEnd = (event: TouchEvent) => {if (event.touches.length > 0) {resetGesture(true);return;}const touch = changedTouch(event);if (touch) {- endGesture(point(touch));- } else if (event.touches.length === 0) {+ endGesture(touchPoint(touch, event));+ } else {resetGesture(true);}- };- const handleTouchCancel = () => resetGesture(true);+ },+ [changedTouch, enabled, endGesture, resetGesture, touchPoint],+ );- root.addEventListener('touchstart', handleTouchStart, {passive: true});- root.addEventListener('touchmove', handleTouchMove, {passive: false});- root.addEventListener('touchend', handleTouchEnd, {passive: true});- root.addEventListener('touchcancel', handleTouchCancel, {passive: true});- return () => {- root.removeEventListener('touchstart', handleTouchStart);- root.removeEventListener('touchmove', handleTouchMove);- root.removeEventListener('touchend', handleTouchEnd);- root.removeEventListener('touchcancel', handleTouchCancel);- };- }, [beginGesture, enabled, endGesture, moveGesture, resetGesture]);+ const handleTouchCancel = useCallback(() => {+ if (enabled) {+ resetGesture(true);+ }+ }, [enabled, resetGesture]);return {rootRef,@@ -409,6 +487,10 @@ export function useToastGesture({onPointerUp: handlePointerUp,onPointerCancel: handlePointerCancel,onLostPointerCapture: handlePointerCancel,+ onTouchStart: handleTouchStart,+ onTouchMove: handleTouchMove,+ onTouchEnd: handleTouchEnd,+ onTouchCancel: handleTouchCancel,},};}diff --git a/packages/core/src/gestures/PanGestureRecognizer.ts b/packages/core/src/gestures/PanGestureRecognizer.tsindex 692604e6f4..26a3e22b95 100644--- a/packages/core/src/gestures/PanGestureRecognizer.ts+++ b/packages/core/src/gestures/PanGestureRecognizer.ts@@ -29,6 +29,8 @@* scroll for that movement — the finger landed at the edge and pulls away* from it. The browser has not committed yet, so beginning claims the* touch and the browser never scrolls.+ * - `firstMoveDecides`: a one-way pan holds the touch from a first move its+ * own way. Any other first move fails it, so the page keeps the touch.** Who gets the drag is decided once, when it begins: a drag that began as* the browser's scroll stays the browser's to the lift and rubber-bands at@@ -88,6 +90,12 @@ export interface PanGestureRecognizerOptions extends GestureRecognizerOptions<PaallowedScrollTypes?: ReadonlyArray<'continuous'>;/** Begin only when the native scrollers under the touch are at the edge. */scrollEdge?: boolean;+ /**+ * A one-way pan decides on the touch's first move. A first move its own way+ * holds the touch from that move. Any other first move fails the pan, so the+ * page keeps the touch. A toast's swipe works this way.+ */+ firstMoveDecides?: boolean;}const ZERO: Point = {x: 0, y: 0};@@ -116,6 +124,7 @@ export class PanGestureRecognizer extends GestureRecognizer {axisRatio: number;lockAxis: boolean;scrollEdge: boolean;+ firstMoveDecides: boolean;/** The axis a `lockAxis` pan locked to when it began. */lockedAxis: 'x' | 'y' | null = null;/** The movement the begin threshold took (excluded from `translation()`). */@@ -136,6 +145,8 @@ export class PanGestureRecognizer extends GestureRecognizer {/** Translation since touch-down, before `setTranslation` offsets. */private raw: Point = ZERO;private offset: Point = ZERO;+ /** How a `firstMoveDecides` pan read the touch's first move, once it moved. */+ private firstMove: 'begin' | 'fail' | 'wait' | null = null;constructor(options: PanGestureRecognizerOptions = {}) {super(options);@@ -150,6 +161,7 @@ export class PanGestureRecognizer extends GestureRecognizer {this.axisRatio = options.axisRatio ?? 1;this.lockAxis = options.lockAxis ?? false;this.scrollEdge = options.scrollEdge ?? false;+ this.firstMoveDecides = options.firstMoveDecides ?? false;this.tracker = new VelocityTracker();}@@ -277,6 +289,17 @@ export class PanGestureRecognizer extends GestureRecognizer {): void {this.track(event.time);if (this.state === 'possible') {+ if (+ this.firstMoveDecides &&+ this.firstMove == null &&+ (this.raw.x !== 0 || this.raw.y !== 0)+ ) {+ this.firstMove = this.classify(this.raw);+ if (this.firstMove !== 'begin') {+ this.setState('failed');+ return;+ }+ }this.tryBegin();} else if (isActive(this.state)) {this.setState('changed');@@ -314,6 +337,7 @@ export class PanGestureRecognizer extends GestureRecognizer {this.raw = ZERO;this.offset = ZERO;this.releaseTime = undefined;+ this.firstMove = null;this.tracker.reset();}@@ -409,7 +433,7 @@ export class PanGestureRecognizer extends GestureRecognizer {protected override keepsTouch(touchId: number): boolean {const touch = this.touches.get(touchId);if (- !this.scrollEdge ||+ (!this.scrollEdge && !this.firstMoveDecides) ||this.state !== 'possible' ||// A lone finger only: two fingers before a claim are the page's pinch// (spec:AST-094 FR10).@@ -420,6 +444,10 @@ export class PanGestureRecognizer extends GestureRecognizer {) {return false;}+ if (this.firstMoveDecides) {+ // A first move its own way holds the finger until the pan begins.+ return this.firstMove === 'begin';+ }const moved = this.raw;return ((moved.x !== 0 || moved.y !== 0) &&diff --git a/packages/core/src/gestures/README.md b/packages/core/src/gestures/README.mdindex fa28133a0f..b87f68c4d8 100644--- a/packages/core/src/gestures/README.md+++ b/packages/core/src/gestures/README.md@@ -92,7 +92,7 @@ Once a drag has claimed its finger, a second finger never breaks it.| -------------------------------- | ---------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || `TapGestureRecognizer` | `UITapGestureRecognizer` | discrete | `numberOfTapsRequired`, `numberOfTouchesRequired`; fails past 45 px of travel, on extra fingers, a hold over 1.5 s, a late or far next tap || `LongPressGestureRecognizer` | `UILongPressGestureRecognizer` | continuous | `minimumPressDuration` 500 ms, `allowableMovement` 10 px (a distance, not per axis), `numberOfTapsRequired`; a zero duration begins on the touch itself (a selection tracker over a group of actions) |-| `PanGestureRecognizer` | `UIPanGestureRecognizer` | continuous | min/max touches, `direction` (axis or one-way) with `axisRatio`, `lockAxis`, `scrollEdge`; `translation()`, `totalTranslation()`, `velocity()`, `scrollVelocity()` |+| `PanGestureRecognizer` | `UIPanGestureRecognizer` | continuous | min/max touches, `direction` (axis or one-way) with `axisRatio`, `lockAxis`, `scrollEdge`, `firstMoveDecides`; `translation()`, `totalTranslation()`, `velocity()`, `scrollVelocity()` || `SwipeGestureRecognizer` | `UISwipeGestureRecognizer` | discrete | recognized during the motion; one or more directions, `numberOfTouchesRequired`; 50 px along, at most 50 px across, 500 ms || `PinchGestureRecognizer` | `UIPinchGestureRecognizer` | continuous | `scale` (settable, to re-base it), `velocity` in scale per second, `focalPoint()` || `ScreenEdgePanGestureRecognizer` | `UIScreenEdgePanGestureRecognizer` | continuous | `edges`: `leading` / `trailing`, resolved against the view's writing direction; attached to an edge zone the view lies within; fails as soon as the touch lands outside every requested edge band; a finger's only |@@ -360,11 +360,13 @@ presses nothing.- **Claim at the begin.** A pan claims its touch only as it begins, atUIKit's 10 pt (`spec:AST-094` FR19), before WebKit commits a slow drag toa scroll at 10–11 px; a drag the browser took first stays the browser's- (FR14). One exception: a `scrollEdge` pan cancels its finger's moves from+ (FR14). Two exceptions: a `scrollEdge` pan cancels its finger's moves fromthe first one while every scroller under the finger is at its edge andthe finger pulls away from it, the pan's own way (the browser could only- rubber-band there); it still begins at 10 pt. It holds only while that is- the one finger on the screen: with a second down anywhere, the moves stay+ rubber-band there); it still begins at 10 pt. A `firstMoveDecides` pan, a+ toast's swipe (`component:Toast` FR4), holds its finger from a first move+ its own way and fails on any other first move. Each holds only while that+ is the one finger on the screen: with a second down anywhere, the moves staythe browser's, for its pinch (FR10).Measured in Mobile Safari (iOS 26.2): `touchmove` arrives from the firstpixel; on a scrollable element WebKit commits to scrolling at 10 to 11 pxdiff --git a/packages/core/src/gestures/__tests__/GestureHost.test.ts b/packages/core/src/gestures/__tests__/GestureHost.test.tsindex decc4be8c2..5c350f9467 100644--- a/packages/core/src/gestures/__tests__/GestureHost.test.ts+++ b/packages/core/src/gestures/__tests__/GestureHost.test.ts@@ -1518,6 +1518,81 @@ describe('GestureHost', () => {});});+ describe('a pan whose first move decides (firstMoveDecides)', () => {+ /** A toast card whose one-way pan toward the bottom decides on the first move. */+ function toastCard() {+ const {card} = mount('<div id="card"></div>');+ const pan = new PanGestureRecognizer({+ name: 'toast',+ direction: 'down',+ firstMoveDecides: true,+ });+ detachers.push(host.attach(card, pan));+ const finger = {id: 1, x: 50, y: 100};+ touch('touchstart', card, [finger], [finger], 0);+ const at = (x: number, y: number, time: number) =>+ touch(+ 'touchmove',+ card,+ [{...finger, x, y}],+ [{...finger, x, y}],+ time,+ );+ const lift = (x: number, y: number, time: number) =>+ touch('touchend', card, [{...finger, x, y}], [], time);+ return {card, pan, finger, at, lift};+ }++ it('holds every move from a first move its own way, and still begins at 10 px', () => {+ const {pan, at, lift} = toastCard();+ expect(at(50, 101, 16).defaultPrevented).toBe(true);+ expect(pan.state).toBe('possible');+ // The first move decided: a move back the other way stays held.+ expect(at(50, 98, 32).defaultPrevented).toBe(true);+ expect(pan.state).toBe('possible');+ expect(at(50, 112, 48).defaultPrevented).toBe(true);+ expect(pan.state).toBe('began');+ lift(50, 112, 64);+ });++ it('fails on a first move the other way and leaves every move to the page', () => {+ const {pan, at, lift} = toastCard();+ expect(at(50, 99, 16).defaultPrevented).toBe(false);+ expect(pan.state).toBe('failed');+ expect(at(50, 120, 32).defaultPrevented).toBe(false);+ lift(50, 120, 48);+ });++ it('fails on a sideways first move', () => {+ const {pan, at, lift} = toastCard();+ expect(at(51, 100, 16).defaultPrevented).toBe(false);+ expect(pan.state).toBe('failed');+ lift(51, 100, 32);+ });++ it('fails on a diagonal first move that is no more down than across', () => {+ const {pan, at, lift} = toastCard();+ expect(at(51, 101, 16).defaultPrevented).toBe(false);+ expect(pan.state).toBe('failed');+ lift(51, 101, 32);+ });++ it('holds nothing while two fingers are down, so a pinch stays the page\u2019s', () => {+ const {card, finger, at} = toastCard();+ expect(at(50, 101, 16).defaultPrevented).toBe(true);+ const second = {id: 2, x: 150, y: 100};+ touch('touchstart', card, [second], [{...finger, y: 101}, second], 24);+ const moved = [+ {...finger, y: 104},+ {...second, y: 96},+ ];+ expect(touch('touchmove', card, moved, moved, 32).defaultPrevented).toBe(+ false,+ );+ touch('touchend', card, moved, [], 48);+ });+ });+it('names the pointer a finger, a pen or a mouse is driven by', () => {const {box} = mount('<div id="box"></div>');const press = new LongPressGestureRecognizer({name: 'press'});diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjsindex 994efc6214..84ef5eb4b1 100644--- a/scripts/touch-support-bundle.test.mjs+++ b/scripts/touch-support-bundle.test.mjs@@ -231,6 +231,8 @@ const GESTURE_USERS = new Set(['SideNav','TimeInput','TopNav',+ // Toast: its swipe's claim, a one-way pan whose first move decides.+ 'Toast',// The public pan, which the root's createPanGesture shares.'hooks: usePanGesture',]);