Skip to content

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

TypeScript

fix(Tooltip): an open tooltip follows a trigger that moves on screen (#8364)

EJ Hammond116f54be56f0
diff --git a/.changeset/tooltip-tall-content-follows-trigger.md b/.changeset/tooltip-tall-content-follows-trigger.md
new file mode 100644
index 0000000000..f8c87d90c4
--- /dev/null
+++ b/.changeset/tooltip-tall-content-follows-trigger.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `Tooltip`: an open tooltip that has moved clear of its trigger now also stays clear when the trigger moves on screen without resizing, in layout or because the page scrolled, at most one painted frame later. Moving it keeps every animation in its content where it was.
+
+@ejhammond
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 1b96720760..6383127499 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -195,7 +195,25 @@ overflows. Content that fits on some side keeps its own size there, and no
option is sized to whatever room is left: a browser keeps an open layer on the
option it last used while that
option still fits, so an anchor that moves takes the layer to the side now
-roomier instead of shrinking it. Chromium tries no more than five
+roomier instead of shrinking it. A browser also keeps a laid-out layer on its
+last option when its list changes, so when a switch does not take effect at
+once the runtime takes the layer out of rendering for one forced layout in the
+same task (no frame paints, the popover stays open, no toggle event fires), and
+the engine places it afresh from the new list; a later read that finds it
+failing again does the same, since no engine re-runs the list when a scroll
+carries the anchor. Leaving rendering cancels the CSS animations and
+transitions of the layer and its content: the browser recreates the animations
+at their start and the transitions not at all. `Layer/preserveAnimations.ts`
+reads every accessor with a setter on each animation's and effect's prototype
+chains, the effect's timing and keyframes, and the play and replace state,
+before the reset, and writes back whatever differs on the recreated animation;
+it resumes each transition with a script animation in the same state and
+finishes a recreated animation that had no predecessor. Script animations are
+untouched. The Animation and effect objects of CSS animations and transitions
+are new (their listeners and promises stay with the old ones, and the browser
+fires their cancel and start events), and a finished animation's start time is
+counted again from now while its held end time is kept.
+Chromium tries no more than five
options, so the second list replaces the first rather than extending it.
Once the anchor has left the viewport the runtime pins the layer's
self-alignment `unsafe` toward the anchor, so the layer holds the position its
@@ -203,8 +221,8 @@ flips give it and holds its size rather than sliding to the edge. Components
pass no fallbacks of their own to an anchor-mode layer.
Every one of these inputs is resolved by the browser's style and layout in the
-same frame as the render that produced it; the runtime measures nothing after
-paint to apply them. Anchor visibility is read
+same frame as the render that produced it; apart from the one case below, the
+runtime measures nothing after paint to apply them. Anchor visibility is read
synchronously in a layout effect before the layer's first paint and then
observed while the layer is open, so a layer opened with its anchor already out
of view holds from its first frame. Whether a layer that keeps its anchor clear
@@ -215,10 +233,20 @@ open-remount path right after the popover is shown,
and again while it is open from ResizeObserver callbacks and resize events, all
of which run before the frame paints; the observers move to the replacement when
the caller replaces the anchor element while the layer stays open. An anchor
-that moves on screen without resizing, in layout or by a scroll, is not
-observed: no observer that runs before paint reports it, so the runtime does
-not re-read the layer then. A layer never paints at a geometry it is about to
-correct.
+that moves on screen without resizing, in layout or by a scroll, is reported
+only by an intersection observer on the anchor, whose root is the viewport
+shrunk to the anchor's rectangle and which re-reads and re-arms on each report
+that differs from its threshold, a fresh observer's first report included, so
+an anchor that keeps moving, as through a smooth scroll, is followed frame by
+frame. A report that finds an anchor which has not moved wholly outside that
+rectangle means a scrolled container clips it; re-arming then would report the
+same every frame, so a second intersection observer, rooted at the viewport
+with a threshold of 0, waits for the anchor to come back into view and then
+re-reads and re-arms. No timer runs.
+It reports after paint, so on that one path at most one painted frame shows
+the layer over its anchor before it is corrected. Scroll events are not read: one fires before
+the layer has followed its anchor. Apart from that, a layer never paints at a
+geometry it is about to correct.
### Current browser support behavior
@@ -398,13 +426,18 @@ layers use Layer rendering without joining Escape/platform dismissal.
the same inset, no consumer defines its own, no size is capped to the span
beside the trigger, and a consumer minimum is clamped by the runtime's cap.
- **INV12 — The first frame is the settled frame.** No input to a layer's
- viewport geometry is measured after paint and then applied. The runtime
- observes anchor visibility for every layer, and, for a layer that keeps its
- anchor clear, whether it covers its anchor or leaves the viewport and
- whether its content overflows; each is read before first paint and, while
- the layer is open, from callbacks that run before the frame paints. A layer
- never paints at a geometry it is about to correct, and the runtime polls
- nothing.
+ viewport geometry is measured after paint and then applied, with one
+ exception. The runtime observes anchor visibility for every layer, and,
+ for a layer that keeps its anchor clear, whether it covers its anchor or
+ leaves the viewport and whether its content overflows; each is read before
+ first paint and, while the layer is open, from callbacks that run before the
+ frame paints. The exception is a same-size anchor that moves on screen, in
+ layout or by a scroll, which only an intersection observer reports, after
+ paint: at most one painted frame shows the layer over its anchor before the
+ correction. Otherwise a layer never paints at a geometry it is about to
+ correct, and the runtime polls nothing: an anchor that a scrolled
+ container hides is followed again when an intersection observer reports it
+ back in view.
This record does not make future eligible-owner, branch-association, global-host,
or browser-support requirements current. It does not own component focus entry or
@@ -476,6 +509,9 @@ be updated only as that work ships.
`Layer/layerInset.ts` owns the `--astryx-layer-inset-*` properties a layer or
the toast viewport writes on itself to carry it; `Layer/clampInlineSize.ts`
owns the clamp a consumer applies to a size of its own.
+- `Layer/preserveAnimations.ts` owns carrying the CSS animations and
+ transitions of a layer and its content across the re-placement's display
+ reset.
- `Layer/gestureCounter.ts` owns physical pointer/key gesture identity.
- `Layer/layerStack.ts`, `Layer/useLayerDismissal.ts`, and
`Layer/LayerDepthContext.tsx` own current registration, presence, ordering, and
diff --git a/docs/specs/AST-059-layer-viewport-inset/spec.md b/docs/specs/AST-059-layer-viewport-inset/spec.md
index 9956666146..c355f85689 100644
--- a/docs/specs/AST-059-layer-viewport-inset/spec.md
+++ b/docs/specs/AST-059-layer-viewport-inset/spec.md
@@ -48,11 +48,11 @@ review_triggers: [layering, layout, behavior, public-api]
| Area | Contract |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Public contract | The layer runtime owns the viewport inset: one gutter definition (FR1), one size cap — the viewport, never the span beside the trigger (FR2, FR3) — one standard fallback order and an anchor-clear order for a layer that keeps its anchor clear (FR4, FR5), and one place an app declares a persistent bar floating over a viewport edge: `LayerProvider`'s `inset`, read by anchored layers and the toast viewport alike (FR6, DEC-4, DEC-5). Popover is an application of the layer that adds styling on top (DEC-1). |
-| Behavior | A layer renders at its own size — the caller's explicit size, or its content's — up to the viewport minus its gutters, and never beyond: content that cannot fit the viewport overflows inside the layer, where the composing component scrolls or clips it (FR2, FR3). Content that can wrap fits beside the trigger by wrapping; a size that cannot shrink flips, and fitting neither side it keeps its size and slides along the alignment axis into view (FR4, DEC-2); a tooltip instead goes beside its trigger or to the roomier side (FR4). A layer whose anchor has left the viewport holds its position and its size (FR5, DEC-3). The first frame a layer paints is its settled frame; it never paints and then moves (FR8). |
+| Behavior | A layer renders at its own size — the caller's explicit size, or its content's — up to the viewport minus its gutters, and never beyond: content that cannot fit the viewport overflows inside the layer, where the composing component scrolls or clips it (FR2, FR3). Content that can wrap fits beside the trigger by wrapping; a size that cannot shrink flips, and fitting neither side it keeps its size and slides along the alignment axis into view (FR4, DEC-2); a tooltip instead goes beside its trigger or to the roomier side (FR4). A layer whose anchor has left the viewport holds its position and its size (FR5, DEC-3). The first frame a layer paints is its settled frame; it never paints and then moves, save the one-frame case FR8 names. |
| End-user impact | A person who opens a 352px menu from a control near the edge of a panel gets a 352px menu, not a 274px one. A long menu on a phone keeps its labels readable instead of squeezing beside its trigger. A layer never ends under a phone navigation bar the app has declared (FR6). Nothing moves for an app that declares no bar. |
| Builder impact | `Popover.width` and `DropdownMenu.menuWidth` become ordinary sizes. An app with a floating bar declares it once, as `inset` on the `LayerProvider` it already mounts, beside `toast`; toasts and anchored layers both clear it. Components that compose `useLayer` or `usePopover` inherit the gutter, the caps, and the fallbacks without a record change (FR7). |
| Compatibility/readiness | Behavior change, one additive prop. An explicit size near an edge renders at its size instead of shrinking; unwrappable content near an edge flips or slides instead of overflowing its box; prose still wraps beside its trigger (DEC-2). Every anchor-mode layer gains the gutter and caps (FR7). `LayerProvider.inset` defaults to zero on every edge, so an app that declares none renders as before, with or without a provider; an existing `toast.inset` keeps its meaning (DEC-5). Authority: `current`, approved by the owner on 2026-10-03. |
-| Review checks | Reject a second definition of the viewport gutter outside the layer runtime; a `max-inline-size` resolved against the anchor's span; a layer box that can exceed the viewport on either axis; a fallback list authored by a component for an anchor-mode layer; a branch on whether a size was explicit; a slide that continues once the anchor has left the viewport; a `layer` theme target or a theme value standing in for an app's bar; a second place to declare the bar beside `LayerProvider.inset`; a consumer minimum that is not clamped by the runtime's cap; a layer under a default provider that renders differently from one with no provider; any geometry input the runtime measures after paint and then applies; a story that asserts only settled geometry. |
+| Review checks | Reject a second definition of the viewport gutter outside the layer runtime; a `max-inline-size` resolved against the anchor's span; a layer box that can exceed the viewport on either axis; a fallback list authored by a component for an anchor-mode layer; a branch on whether a size was explicit; a slide that continues once the anchor has left the viewport; a `layer` theme target or a theme value standing in for an app's bar; a second place to declare the bar beside `LayerProvider.inset`; a consumer minimum that is not clamped by the runtime's cap; a layer under a default provider that renders differently from one with no provider; a geometry input read after paint and applied, except as FR8 permits; a story that asserts only settled geometry. |
| Governing rules | [`architecture:layer-runtime`](../../architecture/layer-runtime.md) INV3, INV5 for anchor-mode placement, fallbacks, and direction, INV10 for what `LayerProvider` is; [`spec:AST-003`](../AST-003/spec.md) FR21–FR23 for the reduced behavior where CSS Anchor Positioning is absent; `component:Popover` FR4, ORD4 for Popover's conditional scrolling, which this record leaves in place. |
This table is a review projection; the body below is authoritative.
@@ -180,9 +180,9 @@ the app reaches every layer instead of the components that happen to read it.
subtracts each edge's own gutter). Content taller than either side can hold
is capped to the viewport and shifted into it, keeping its anchor clearance
from the edge it meets. A layer that keeps its anchor clear — Tooltip, which
- the hover on its trigger keeps open — opens clear of its anchor and stays
- clear while it, its content, its anchor or the viewport resizes and when it
- is remounted (FR8). When the order above leaves
+ the hover on its trigger keeps open — never settles over its anchor, and
+ no painted frame shows it there except the one FR8 allows when a same-size
+ anchor moves on screen, in layout or by a scroll. When the order above leaves
its box over the anchor or, while the anchor is in view, past the viewport
on the block axis (engines differ in where they leave a box that fits no
option: one shifts it over the anchor, another leaves it on its preferred
@@ -200,7 +200,18 @@ the app reaches every layer instead of the components that happen to read it.
from the layer's settled box, without the transform its entry animation
applies while it enters. It scrolls what it cannot show, and only
then, so a layer that fits stays a plain box (FR3). Once switched, it keeps
- the second list until it next opens. Chromium tries no more than five position
+ the second list until it next opens; a switch that the engine does not apply
+ at once places it afresh from the second list in the same frame, without
+ closing it, and so does a later read that finds it failing again, because
+ no engine re-runs the list when a scroll carries the anchor. Every CSS
+ animation and transition of the layer and its content keeps every writable
+ member the engine exposes on it and its effect, its timing, keyframes, play
+ and replace state, and its time. Three things are not kept: the Animation
+ and effect objects (the browser replaces them, with their listeners and
+ promises, and fires cancel and start events), a finished animation's start
+ time (its held end time is kept), and a transition's own object (a script
+ animation resumes it, so it fires no `transitionend`).
+ Chromium tries no more than five position
options, so this is a second list that replaces the first, not an extension
of it. The runtime authors both orders; a component passes no fallbacks of
its own to an anchor-mode layer.
@@ -234,8 +245,9 @@ the app reaches every layer instead of the components that happen to read it.
geometry it is about to correct. Every input to a layer's geometry under
this record — the gutter, the caps, the declared inset, the fallback order —
is resolved by the browser's style and layout in the same frame as the
- render that produced it; the runtime measures nothing after paint to apply
- them. The runtime makes two observations. Whether the anchor is in view
+ render that produced it; apart from the one case below, the runtime
+ measures nothing after paint to apply them. The runtime makes two
+ observations. Whether the anchor is in view
(FR5) is read before the layer's first paint and thereafter only when the
anchor's visibility changes, so a layer opened while its anchor is already
out of view holds from its first frame. For a layer that keeps its anchor
@@ -247,15 +259,21 @@ the app reaches every layer instead of the components that happen to read it.
after the caller replaces the anchor element while the layer stays open;
each of those reads lands before the next frame paints. A same-size anchor
that moves on screen, in layout (content above it grows, a margin changes)
- or because something scrolled, is not observed: no observer that runs
- before paint reports it, so the layer is not re-read then. The runtime polls
- nothing. When a declared inset changes while a layer is open,
+ or because something scrolled, is reported by no observer that runs before
+ paint, and a scroll event fires before the layer has followed its anchor;
+ the runtime learns of the move from an intersection observer on the anchor,
+ which reports after paint, so on that one path at most one painted frame
+ shows the layer over its anchor before the next frame corrects it. An
+ anchor that a scrolled container hides is followed again when it comes
+ back into view, which a second intersection observer reports. The runtime
+ polls nothing. When a declared inset changes while a layer is open,
the layer
and the declaration
change in the same frame.
Latency between an app measuring its own bar and declaring the result is the
- app's; the runtime renders what is declared, when it is declared. A
- paint-then-shift is a failure of this contract, not a quality concern.
+ app's; the runtime renders what is declared, when it is declared. Apart from
+ that one-frame correction, a paint-then-shift is a failure of this
+ contract, not a quality concern.
### Platform support
@@ -297,7 +315,9 @@ When this ships:
from the provider's context and carries it on itself, so hosting never
decides whether it arrives, and no layer resolves placement through it.
- Add an invariant for FR8: no geometry input is measured after paint and
- then applied; the first painted frame is the settled frame.
+ then applied; the first painted frame is the settled frame. The one
+ exception is FR8's one-frame correction for a layer that keeps its anchor
+ clear when a same-size anchor moves on screen, in layout or by a scroll.
- Owning code: add the module that holds the gutter and cap expressions, and
`LayerProvider` as the owner of the declared inset.
- Change coupling: the positioning row already names viewport-edge fallbacks;
@@ -377,7 +397,7 @@ for any row.
| FR2 | Stories "explicit size near an edge (352px)", "content-sized, fits beside the trigger", "content-sized, does not fit beside the trigger", "neither side fits" at both viewports; clamp strings in Popover and DropdownMenu suites | 352px end-aligned on a trigger 45px from the edge; a short content-sized layer; an unbreakable run wider than a phone; a 1000px layer on a phone, where the cap is 358px | A layer narrower than `min(asked, cap)`, a layer box wider than the cap at any viewport, or `100%` of the anchor span in a cap |
| FR3 | Story "taller than the viewport" at both viewports; the runtime's viewport-fit style on every anchor-mode layer | Content 2000px tall | The layer box's block size exceeds the viewport minus gutters |
| FR4 | Stories "content-sized, does not fit beside the trigger", "trigger near an edge flips", "neither side fits", "trigger near the bottom flips above", "wide layer, trigger near the bottom" at both viewports | A flip to end alignment at content size and at an explicit size; a 1000px layer slid inside the gutters where it fits; a block flip with room only above; a block flip when the inline axis is also capped | A layer squeezed into the span, a flipped edge off the trigger's edge, a layer outside the gutters on either axis, or a layer left on the side with no room |
-| FR4, Tooltip | The `TooltipTallContent` real-engine suite (Chromium, WebKit) at 1280×720 and 390×700; the runtime's anchor-clear unit suite | A 60-line tooltip mid-page (beside it); on a phone, trigger in the upper or lower half (roomier side); a fitting tooltip; content growth, host move, replaced trigger resize, entry motion | Covers its trigger in a painted frame, closes under a resting pointer, leaves the viewport, won't scroll, or a tooltip that fits moves |
+| FR4, Tooltip | The `TooltipTallContent` and `TooltipTallContentTracking` real-engine suites (Chromium, WebKit) at 1280×720 and 390×700; the runtime's anchor-clear unit suite | A 60-line tooltip mid-page (beside it); on a phone, trigger in the upper or lower half (roomier side); a fitting tooltip; content growth, host move, trigger move by layout or scroll, replaced trigger | Covers its trigger in a frame (past the first after a same-size trigger moves by layout or scroll), closes under a resting pointer, leaves the viewport, won't scroll, or a fitting tooltip moves |
| FR5 | Stories "anchor leaves the viewport" and "anchor already off-screen when the layer opens"; the runtime's anchor-visibility unit suite | Horizontal scroll carries the trigger out of view while the layer is open, then back; a layer opened with its anchor already off-screen | The layer slides toward the viewport edge after the anchor is gone, changes size, does not return with its anchor, or opens pinned to the edge |
| FR6 | Stories "app-declared inset (floating bar)" and "layer portaled out of its JSX position"; `LayerProvider` and `ToastViewport` unit suites | An 80px bar declared as `inset={{blockEnd: 80}}`; a toast under the same provider; a `toast.inset` override; no provider; a layer hosted outside the paragraph it was rendered in | A layer or toast ends under the bar, an unset edge moves anything, a `toast.inset` edge stops overriding, no-provider geometry differs from the default provider's, or a portaled layer loses the inset |
| FR8 | Every story above (first frame compared with settled); stories "inset changes while the layer is open", "layer opens in the frame the inset arrives", "inset measured by the app", "anchor already off-screen when the layer opens" | The provider's inset changes 80→160 with the layer open; a layer mounted open in the provider's first commit; a bar the app measures before paint and declares; an off-screen anchor at open | The first frame's rectangle differs from the settled one, or the first frame after a declaration change is not already at the new geometry |
diff --git a/packages/core/src/Layer/preserveAnimations.ts b/packages/core/src/Layer/preserveAnimations.ts
new file mode 100644
index 0000000000..eb4eb9825b
--- /dev/null
+++ b/packages/core/src/Layer/preserveAnimations.ts
@@ -0,0 +1,304 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file preserveAnimations.ts
+ * @input An element whose subtree is about to leave rendering for one forced
+ * layout, and the function that does it
+ * @output The same CSS animations and transitions afterwards, in the state
+ * they were in before
+ * @position Layer runtime; the re-placement of a layer that keeps its anchor
+ * clear (spec:AST-059 FR4)
+ *
+ * Taking an element out of rendering cancels every CSS animation and
+ * transition of it and its subtree. When it returns, the browser creates the
+ * animations again from the stylesheet, at their start, and the transitions
+ * not at all; script-created animations are untouched. `preserveAnimations`
+ * reads every animation's state first and, afterwards, gives each recreated
+ * CSS animation that state and resumes each cancelled transition with a
+ * script animation at the same point.
+ *
+ * The state is read generically, from what the platform exposes: every
+ * accessor with a setter on the animation's and its effect's prototype
+ * chains, every field of the effect's timing, and its keyframes. Only values
+ * that differ from the recreated animation's are written, so a value the
+ * stylesheet controls stays under its control. A few members are not plain
+ * state and are handled in their own step (`ORDERED`); the rest need no
+ * handling (`DERIVED`). What cannot be carried over is the Animation and
+ * effect objects themselves: the old ones are idle, their `addEventListener`
+ * listeners and `finished`/`ready` promises stay with them, and the browser
+ * fires `animationcancel`/`transitioncancel` for them and `animationstart`
+ * for the new ones.
+ */
+
+/**
+ * Animation members written in a fixed order rather than generically: the
+ * timeline before the range that is measured on it, the rate before the
+ * time, and the start time (or, for a paused animation, the current time)
+ * last, once the play state is set. `effect` is not
+ * replaced, because a CSS animation whose effect script replaces leaves the
+ * stylesheet's control; its state is copied onto the new effect instead.
+ */
+const ORDERED = new Set([
+ 'effect',
+ 'timeline',
+ 'rangeStart',
+ 'rangeEnd',
+ 'playbackRate',
+ 'startTime',
+ 'currentTime',
+]);
+
+type Writable = Record<string, unknown>;
+
+/** Every accessor with a setter on `object`'s prototype chain. */
+function writableAccessors(object: object): string[] {
+ const names = new Set<string>();
+ for (
+ let proto: object | null = Object.getPrototypeOf(object);
+ proto != null && proto !== Object.prototype;
+ proto = Object.getPrototypeOf(proto)
+ ) {
+ for (const [name, descriptor] of Object.entries(
+ Object.getOwnPropertyDescriptors(proto),
+ )) {
+ if (descriptor.set != null) {
+ names.add(name);
+ }
+ }
+ }
+ return [...names];
+}
+
+/**
+ * A textual form of a value that is compared by content rather than by
+ * identity: a CSS numeric value (as in a timeline range offset) through its
+ * serialization, a plain object (a range) through its members. Anything else
+ * is compared by identity (`null`).
+ */
+function contentOf(value: unknown): string | null {
+ if (
+ typeof CSSNumericValue !== 'undefined' &&
+ value instanceof CSSNumericValue
+ ) {
+ return value.toString();
+ }
+ if (
+ value != null &&
+ typeof value === 'object' &&
+ Object.getPrototypeOf(value) === Object.prototype
+ ) {
+ return Object.entries(value)
+ .map(([key, inner]) => `${key}:${contentOf(inner) ?? String(inner)}`)
+ .join(';');
+ }
+ return null;
+}
+
+function differs(a: unknown, b: unknown): boolean {
+ if (a === b) {
+ return false;
+ }
+ const textA = contentOf(a);
+ return textA == null || textA !== contentOf(b);
+}
+
+interface Saved {
+ animation: Animation;
+ name: string;
+ target: Element | null;
+ pseudoElement: string | null;
+ values: Writable;
+ effectValues: Writable;
+ timing: EffectTiming | null;
+ keyframes: ComputedKeyframe[] | null;
+ playState: AnimationPlayState;
+ replaceState: AnimationReplaceState;
+}
+
+function save(animation: Animation): Saved {
+ const effect = animation.effect as KeyframeEffect | null;
+ const values: Writable = {};
+ for (const name of writableAccessors(animation)) {
+ values[name] = (animation as unknown as Writable)[name];
+ }
+ const effectValues: Writable = {};
+ if (effect != null) {
+ for (const name of writableAccessors(effect)) {
+ effectValues[name] = (effect as unknown as Writable)[name];
+ }
+ }
+ return {
+ animation,
+ name:
+ (animation as Animation & {animationName?: string}).animationName ?? '',
+ target: effect?.target ?? null,
+ pseudoElement: effect?.pseudoElement ?? null,
+ values,
+ effectValues,
+ timing: effect?.getTiming() ?? null,
+ keyframes: effect?.getKeyframes() ?? null,
+ playState: animation.playState,
+ replaceState: animation.replaceState,
+ };
+}
+
+function write(object: object, name: string, value: unknown): void {
+ (object as Writable)[name] = value;
+}
+
+/** Give `next` the effect state `saved` had: every writable member. */
+function restoreEffect(next: KeyframeEffect, saved: Saved): void {
+ for (const name of writableAccessors(next)) {
+ if (
+ name in saved.effectValues &&
+ differs(saved.effectValues[name], (next as unknown as Writable)[name])
+ ) {
+ write(next, name, saved.effectValues[name]);
+ }
+ }
+ if (saved.timing != null) {
+ const timing = next.getTiming() as unknown as Writable;
+ const changed: Writable = {};
+ for (const [field, value] of Object.entries(saved.timing)) {
+ if (differs(value, timing[field])) {
+ changed[field] = value;
+ }
+ }
+ if (Object.keys(changed).length > 0) {
+ next.updateTiming(changed);
+ }
+ }
+ if (
+ saved.keyframes != null &&
+ JSON.stringify(saved.keyframes) !== JSON.stringify(next.getKeyframes())
+ ) {
+ next.setKeyframes(saved.keyframes);
+ }
+}
+
+/** Give `next` the state `saved` had, member by member. */
+function restore(next: Animation, saved: Saved): void {
+ const effect = next.effect as KeyframeEffect | null;
+ if (effect != null) {
+ restoreEffect(effect, saved);
+ }
+ const current = next as unknown as Writable;
+ for (const name of ['timeline', 'rangeStart', 'rangeEnd']) {
+ if (name in saved.values && differs(saved.values[name], current[name])) {
+ write(next, name, saved.values[name]);
+ }
+ }
+ for (const name of writableAccessors(next)) {
+ if (
+ !ORDERED.has(name) &&
+ name in saved.values &&
+ differs(saved.values[name], current[name])
+ ) {
+ write(next, name, saved.values[name]);
+ }
+ }
+ if (saved.replaceState === 'persisted' && next.replaceState !== 'persisted') {
+ next.persist();
+ }
+ const rate = saved.values.playbackRate;
+ if (typeof rate === 'number' && rate !== next.playbackRate) {
+ next.playbackRate = rate;
+ }
+ if (saved.playState === 'paused' && next.playState !== 'paused') {
+ next.pause();
+ } else if (saved.playState !== 'paused' && next.playState === 'paused') {
+ next.play();
+ }
+ // A running animation is anchored to its timeline by its start time, which
+ // carries its current time on exactly. A paused one has none and keeps its
+ // current time. A finished one holds its end: finishing it again holds the
+ // same time, though its start time is then counted from now, since script
+ // cannot set a start time and a held time together.
+ const start = saved.values.startTime as CSSNumberish | null | undefined;
+ const time = saved.values.currentTime as CSSNumberish | null | undefined;
+ if (saved.playState === 'finished') {
+ next.finish();
+ } else if (start != null) {
+ next.startTime = start;
+ } else if (time != null) {
+ next.currentTime = time;
+ }
+}
+
+/** Resume a cancelled CSS transition with a script animation in its state. */
+function resumeTransition(saved: Saved): void {
+ if (saved.target == null || saved.keyframes == null) {
+ return;
+ }
+ const replacement = saved.target.animate(saved.keyframes, {
+ pseudoElement: saved.pseudoElement ?? undefined,
+ });
+ restore(replacement, saved);
+}
+
+function isTransition(animation: Animation): boolean {
+ return (
+ typeof CSSTransition !== 'undefined' && animation instanceof CSSTransition
+ );
+}
+
+/**
+ * Run `reset`, which takes `root` out of rendering and back, and put every
+ * CSS animation and transition of `root` and its subtree back in the state it
+ * was in before. Recreated animations are matched to the ones they replace by
+ * element, pseudo-element and name, in order, and then by name alone (an
+ * effect script moved to another element or pseudo-element); a recreated
+ * animation with no predecessor (an entry animation that had already played
+ * and been dropped) is finished.
+ */
+export function preserveAnimations(root: Element, reset: () => void): void {
+ if (typeof root.getAnimations !== 'function') {
+ reset();
+ return;
+ }
+ const before = root.getAnimations({subtree: true});
+ const saved = before.map(save);
+ reset();
+ const after = root.getAnimations({subtree: true});
+ const current = new Set(after);
+ const survivors = new Set(before);
+ const cancelled: Saved[] = [];
+ for (const state of saved) {
+ if (current.has(state.animation)) {
+ continue;
+ }
+ if (isTransition(state.animation)) {
+ resumeTransition(state);
+ } else {
+ cancelled.push(state);
+ }
+ }
+ const recreated = after.filter(animation => !survivors.has(animation));
+ const unmatched: Animation[] = [];
+ for (const animation of recreated) {
+ const effect = animation.effect as KeyframeEffect | null;
+ const name =
+ (animation as Animation & {animationName?: string}).animationName ?? '';
+ const index = cancelled.findIndex(
+ state =>
+ state.name === name &&
+ state.target === (effect?.target ?? null) &&
+ state.pseudoElement === (effect?.pseudoElement ?? null),
+ );
+ if (index === -1) {
+ unmatched.push(animation);
+ } else {
+ restore(animation, cancelled.splice(index, 1)[0]);
+ }
+ }
+ for (const animation of unmatched) {
+ const name =
+ (animation as Animation & {animationName?: string}).animationName ?? '';
+ const index = cancelled.findIndex(state => state.name === name);
+ if (index === -1) {
+ animation.finish();
+ } else {
+ restore(animation, cancelled.splice(index, 1)[0]);
+ }
+ }
+}
diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsx
index 9da52f284b..79eb6aedd5 100644
--- a/packages/core/src/Layer/useLayer.test.tsx
+++ b/packages/core/src/Layer/useLayer.test.tsx
@@ -1757,6 +1757,51 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {
expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');
});
+ it('places a layer afresh from the clear list when it switches, without closing it or leaving a frame', async () => {
+ const user = userEvent.setup();
+ const onToggle = vi.fn();
+ const displays: string[] = [];
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(
+ function (this: HTMLElement) {
+ if (this.hasAttribute('popover')) {
+ displays.push(this.style.display);
+ return rect(16, 350, 688, 300);
+ }
+ return TRIGGER;
+ },
+ );
+ const {container} = render(<ClearHarness />);
+ const layerEl = container.querySelector('[popover]') as HTMLElement;
+ layerEl.addEventListener('toggle', onToggle);
+ layerEl.addEventListener('beforetoggle', onToggle);
+ await user.click(container.querySelector('button')!);
+ expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');
+ // A browser keeps a laid-out layer on its last option until the layer
+ // stops being rendered: the switch takes it out of rendering for one
+ // forced layout, then restores its own display, in the same task.
+ expect(displays).toContain('none');
+ expect(layerEl.style.display).not.toBe('none');
+ // Only the show itself opened it; the re-placement neither closed nor
+ // re-opened it.
+ expect(
+ onToggle.mock.calls.map(([e]) => (e as ToggleEvent).newState),
+ ).not.toContain('closed');
+ // A later read that finds it failing again places it afresh again; one
+ // that finds it clear leaves it alone.
+ displays.length = 0;
+ act(() => {
+ window.dispatchEvent(new Event('resize'));
+ });
+ expect(displays).toContain('none');
+ vi.restoreAllMocks();
+ placeBoxes(TRIGGER, rect(200, 350, 100, 200));
+ const spy = vi.spyOn(layerEl.style, 'display', 'set');
+ act(() => {
+ window.dispatchEvent(new Event('resize'));
+ });
+ expect(spy).not.toHaveBeenCalled();
+ });
+
it('switches to the clear list when the shown layer leaves the viewport on the block axis while its trigger is in view', async () => {
const user = userEvent.setup();
// Above the trigger, clear of it, but its top past the viewport: where
@@ -1780,6 +1825,25 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {
expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');
});
+ it('does not read on scroll events, when the layer has not followed its anchor yet', async () => {
+ const user = userEvent.setup();
+ viewport720();
+ const spy = placeBoxes(TRIGGER, rect(200, 350, 100, 200));
+ const {container} = render(<ClearHarness />);
+ await user.click(container.querySelector('button')!);
+ const layerEl = container.querySelector('[popover]') as HTMLElement;
+ // Mid-scroll: the trigger has moved under the layer's stale box, which
+ // reads as covering it and past the viewport. A scroll is read only once
+ // it has painted, by the anchor-move observer.
+ spy.mockRestore();
+ placeBoxes(rect(-40, 380, 30, 100), rect(-60, 350, 100, 200));
+ act(() => {
+ window.dispatchEvent(new Event('scroll'));
+ document.dispatchEvent(new Event('scroll'));
+ });
+ expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');
+ });
+
it('keeps the standard list when the shown layer sits clear of its trigger, even flush against it', async () => {
const user = userEvent.setup();
// Directly above the trigger, its bottom edge on the trigger's top edge.
@@ -1868,6 +1932,145 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {
vi.unstubAllGlobals();
});
+ it('re-reads its geometry when its trigger moves in layout without resizing', async () => {
+ const observers: {
+ callback: (entries: {intersectionRatio: number}[]) => void;
+ options: IntersectionObserverInit;
+ disconnected: boolean;
+ }[] = [];
+ vi.stubGlobal(
+ 'IntersectionObserver',
+ class {
+ record: (typeof observers)[number];
+ constructor(
+ callback: (entries: {intersectionRatio: number}[]) => void,
+ options: IntersectionObserverInit,
+ ) {
+ this.record = {callback, options, disconnected: false};
+ observers.push(this.record);
+ }
+ observe() {}
+ disconnect() {
+ this.record.disconnected = true;
+ }
+ unobserve() {}
+ },
+ );
+ const user = userEvent.setup();
+ const spy = placeBoxes(TRIGGER, rect(200, 350, 100, 200));
+ const {container, getByText} = render(<ClearHarness />);
+ await user.click(getByText('Trigger'));
+ const layerEl = container.querySelector('[popover]') as HTMLElement;
+ expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');
+ // The move observer's root is the viewport shrunk to the trigger's rect.
+ const move = observers.find(o => o.options?.root === document);
+ expect(move?.options.threshold).toBe(1);
+ expect(move?.options.rootMargin).toBe(
+ `-300px ${-(document.documentElement.clientWidth - 500)}px ${-(document.documentElement.clientHeight - 330)}px -400px`,
+ );
+
+ // Its initial report: fully inside its own rect.
+ act(() => move?.callback([{intersectionRatio: 1}]));
+ expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');
+
+ // The trigger moves; the standard list now settles over it.
+ spy.mockRestore();
+ placeBoxes(TRIGGER, rect(16, 350, 688, 300));
+ const before = observers.length;
+ act(() => move?.callback([{intersectionRatio: 0.4}]));
+ expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');
+ // Re-armed on the new rect.
+ expect(move?.disconnected).toBe(true);
+ expect(observers.length).toBe(before + 1);
+ vi.unstubAllGlobals();
+ });
+
+ it('follows a move that spans several frames and never goes idle while a scrolled container clips its trigger', async () => {
+ type Entry = {intersectionRatio: number; isIntersecting?: boolean};
+ const observers: {
+ callback: (entries: Entry[]) => void;
+ options: IntersectionObserverInit;
+ disconnected: boolean;
+ }[] = [];
+ vi.stubGlobal(
+ 'IntersectionObserver',
+ class {
+ record: (typeof observers)[number];
+ constructor(
+ callback: (entries: Entry[]) => void,
+ options: IntersectionObserverInit,
+ ) {
+ this.record = {callback, options, disconnected: false};
+ observers.push(this.record);
+ }
+ observe() {}
+ disconnect() {
+ this.record.disconnected = true;
+ }
+ unobserve() {}
+ },
+ );
+ const moves = () =>
+ observers.filter(
+ o => o.options?.root === document && o.options.rootMargin != null,
+ );
+ const visibilities = () =>
+ observers.filter(
+ o => o.options?.root === document && o.options.rootMargin == null,
+ );
+ const latest = () => moves()[moves().length - 1];
+ const user = userEvent.setup();
+ let spy = placeBoxes(TRIGGER, rect(200, 350, 100, 200));
+ const {container, getByText} = render(<ClearHarness />);
+ await user.click(getByText('Trigger'));
+ const layerEl = container.querySelector('[popover]') as HTMLElement;
+ expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');
+
+ // A fresh observer's first report already differs: the trigger kept
+ // moving after its rectangle was read, as in a smooth scroll. That is a
+ // move: it re-reads, and re-arms at the reported ratio.
+ spy.mockRestore();
+ spy = placeBoxes(TRIGGER, rect(16, 350, 688, 300));
+ let armed = moves().length;
+ act(() => latest().callback([{intersectionRatio: 0.7}]));
+ expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');
+ expect(moves().length).toBe(armed + 1);
+ expect(latest().options.threshold).toBe(0.7);
+
+ // A first report of 0 for a trigger that moved since the observer read
+ // its rectangle re-arms at once on the new rectangle.
+ spy.mockRestore();
+ spy = placeBoxes(rect(260, 400, 30, 100), rect(16, 350, 688, 300));
+ armed = moves().length;
+ act(() => latest().callback([{intersectionRatio: 0}]));
+ expect(moves().length).toBe(armed + 1);
+ expect(latest().options.threshold).toBe(1);
+
+ // A first report of 0 for a trigger that has not moved: a scrolled
+ // container clips it. No timer runs; a visibility observer rooted at the
+ // viewport waits for it to come back into view, however long that takes.
+ const timers = vi.spyOn(globalThis, 'setTimeout');
+ armed = moves().length;
+ act(() => latest().callback([{intersectionRatio: 0}]));
+ expect(moves().length).toBe(armed);
+ expect(timers).not.toHaveBeenCalled();
+ const visibility = visibilities()[visibilities().length - 1];
+ expect(visibility?.options.threshold).toBe(0);
+ act(() =>
+ visibility?.callback([{intersectionRatio: 0, isIntersecting: false}]),
+ );
+ expect(moves().length).toBe(armed);
+ // Back in view: it re-reads and re-arms, and the visibility observer goes.
+ act(() =>
+ visibility?.callback([{intersectionRatio: 0.2, isIntersecting: true}]),
+ );
+ expect(moves().length).toBe(armed + 1);
+ expect(visibility?.disconnected).toBe(true);
+ expect(timers).not.toHaveBeenCalled();
+ spy.mockRestore();
+ vi.unstubAllGlobals();
+ });
+
it('moves its open-state observers to a trigger the caller replaces while it is open', async () => {
const observed: Element[] = [];
const disconnected: Element[][] = [];
diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx
index 5bc3624d7f..44cf56fd1f 100644
--- a/packages/core/src/Layer/useLayer.tsx
+++ b/packages/core/src/Layer/useLayer.tsx
@@ -45,6 +45,7 @@ import {
getAnchorClearFallbacks,
slideRuleName,
} from './layerSlideRules';
+import {preserveAnimations} from './preserveAnimations';
import {useLayerContext} from './LayerContext';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {overlayPaddingReset} from '../Layout/padding.stylex';
@@ -443,6 +444,24 @@ function toCssLength(value: number | string): string {
return typeof value === 'number' ? `${value}px` : value;
}
+/**
+ * Make the engine choose a shown layer's position option afresh: a browser
+ * keeps a laid-out layer on the option it last used until the layer stops
+ * being rendered, so the layer is taken out of rendering for one forced
+ * layout and restored, in the same task. No frame paints in between and the
+ * popover stays open, so no toggle event fires and focus and hover are
+ * untouched. Every CSS animation and transition of the layer and its content
+ * is put back in the state it was in (`preserveAnimations`).
+ */
+function placeAfresh(layer: HTMLElement): void {
+ preserveAnimations(layer, () => {
+ const display = layer.style.display;
+ layer.style.display = 'none';
+ layer.getBoundingClientRect();
+ layer.style.display = display;
+ });
+}
+
const TRANSFORM_PROPERTIES = ['transform', 'translate', 'scale', 'rotate'];
function hasTransform(style: CSSStyleDeclaration): boolean {
@@ -599,13 +618,26 @@ function failsAnchor(layer: HTMLElement, anchor: HTMLElement): boolean {
* standard list has failed it. The runtime calls this in the same task as
* every show and remount, and while the layer is open whenever its size, its
* content's size, its anchor's size or the viewport changes; each of those
- * reads lands before the next frame paints (FR8). Once switched, a layer keeps
- * its anchor-clear list until it next opens, so it never jumps back over its
- * trigger while open.
+ * reads lands before the next frame paints. A same-size anchor that moves on
+ * screen, in layout or because something scrolled, is read after paint, from
+ * the anchor-move observer (FR8). Scroll events are not read: during one the
+ * anchor has moved but the layer anchored to it not yet, so the read would
+ * compare a moved anchor with a stale layer. Once switched, a layer keeps its
+ * anchor-clear list until it next opens, so it never jumps back over its
+ * trigger while open; it is placed afresh (`placeAfresh`) only when the switch
+ * does not take effect at once, or when a later read finds it failing again.
*/
function keepAnchorClear(layer: HTMLElement, anchor: HTMLElement | null): void {
if (anchor && failsAnchor(layer, anchor)) {
+ const switching = !layer.hasAttribute(LAYER_CLEARS_ANCHOR_ATTRIBUTE);
layer.setAttribute(LAYER_CLEARS_ANCHOR_ATTRIBUTE, '');
+ // A switch usually takes effect at once. The engine may instead keep the
+ // option it last used, even one the new list does not contain or one a
+ // scroll has since made fail: then, and on any later read that finds the
+ // switched layer failing again, place it afresh.
+ if (!switching || failsAnchor(layer, anchor)) {
+ placeAfresh(layer);
+ }
}
// A layer that fits has no scroll range and stays a plain box, so a wheel
// over it still scrolls the page.
@@ -615,14 +647,133 @@ function keepAnchorClear(layer: HTMLElement, anchor: HTMLElement | null): void {
);
}
+/**
+ * Call `onMove` when an element moves on screen without changing size: in
+ * layout (a sibling above it grows, a margin changes) or because something
+ * scrolled. ResizeObserver sees only size. The element is observed by an
+ * IntersectionObserver whose root is the viewport shrunk, through
+ * `rootMargin`, to the element's own rectangle (the layout-shift technique of
+ * `@floating-ui/dom`'s `observeMove`), so any move changes the intersection
+ * ratio and fires the callback, which calls `onMove` and re-arms on the new
+ * rectangle. Intersection callbacks run after the frame that moved the
+ * element has painted, so the caller corrects that move in the next frame.
+ *
+ * A fresh observer's first report can already differ from its threshold: the
+ * element is partly outside the viewport, or it kept moving between the
+ * rectangle read and the observer's first check, as it does every frame of a
+ * smooth scroll. Any such report calls `onMove` and re-arms, at the reported
+ * ratio, or at once on the element's new rectangle when the report is 0 and
+ * the element moved, so a move that spans many frames is followed frame by
+ * frame. A report of 0 for an element that has not moved means a scrolled
+ * container clips it wholly; re-arming then would report 0 again every frame.
+ * Instead a second IntersectionObserver, rooted at the viewport with a
+ * threshold of 0 (it counts every ancestor's overflow clip), waits for the
+ * element to come back into view, then calls `onMove` and re-arms. Nothing
+ * runs on a timer. Returns the function that stops observing.
+ */
+function observeMove(element: HTMLElement, onMove: () => void): () => void {
+ const doc = element.ownerDocument;
+ if (typeof IntersectionObserver === 'undefined') {
+ return () => {};
+ }
+ let observer: IntersectionObserver | null = null;
+ let visibility: IntersectionObserver | null = null;
+ const stop = () => {
+ observer?.disconnect();
+ observer = null;
+ visibility?.disconnect();
+ visibility = null;
+ };
+ const moved = (threshold: number) => {
+ onMove();
+ arm(threshold);
+ };
+ const arm = (threshold: number) => {
+ stop();
+ const root = doc.documentElement;
+ const rect = element.getBoundingClientRect();
+ if (rect.width === 0 || rect.height === 0) {
+ return;
+ }
+ const top = Math.floor(rect.top);
+ const left = Math.floor(rect.left);
+ const right = Math.floor(root.clientWidth - rect.right);
+ const bottom = Math.floor(root.clientHeight - rect.bottom);
+ const hasMoved = () => {
+ const now = element.getBoundingClientRect();
+ return (
+ now.top !== rect.top ||
+ now.left !== rect.left ||
+ now.width !== rect.width ||
+ now.height !== rect.height
+ );
+ };
+ // Clipped by a scrolled container: wait, without a timer, for the
+ // element to come back into view. A first report that already finds it
+ // in view only counts if it has moved, so a clip the move observer and
+ // this one judge differently cannot re-arm every frame.
+ const awaitVisible = () => {
+ let isFirstVisible = true;
+ visibility = new IntersectionObserver(
+ entries => {
+ const visible = entries[entries.length - 1]?.isIntersecting ?? false;
+ const firstVisible = isFirstVisible;
+ isFirstVisible = false;
+ if (visible && (!firstVisible || hasMoved())) {
+ moved(1);
+ }
+ },
+ {root: doc, threshold: 0},
+ );
+ visibility.observe(element);
+ };
+ let isFirst = true;
+ observer = new IntersectionObserver(
+ entries => {
+ const ratio = entries[entries.length - 1]?.intersectionRatio ?? 0;
+ const first = isFirst;
+ isFirst = false;
+ if (ratio === threshold) {
+ // Still over its own rectangle, but a move smaller than the
+ // rounding of the root margin can leave the ratio at 1.
+ if (ratio === 1 && hasMoved()) {
+ moved(1);
+ }
+ return;
+ }
+ if (!first || ratio > 0) {
+ moved(first ? ratio : 1);
+ return;
+ }
+ if (hasMoved()) {
+ moved(1);
+ return;
+ }
+ if (visibility === null) {
+ awaitVisible();
+ }
+ },
+ {
+ root: doc,
+ rootMargin: `${-top}px ${-right}px ${-bottom}px ${-left}px`,
+ threshold,
+ },
+ );
+ observer.observe(element);
+ };
+ arm(1);
+ return stop;
+}
+
/**
* Watch an open layer that keeps its anchor clear, and its anchor, for every
* change that can re-settle the layer over the anchor or give it a scroll
* range (spec:AST-059 FR4, FR8): the layer, its content or the anchor
- * resizing (ResizeObserver) and the viewport resizing, all reported before
- * the frame paints. Each calls `keepAnchorClear` for this layer and anchor
- * while `isCurrent` says they are still the live pair. Returns the function
- * that removes every observer and listener it added.
+ * resizing (ResizeObserver, before paint), the viewport resizing (before
+ * paint), and the anchor moving on screen without resizing, in layout or by a
+ * scroll (`observeMove`, after paint). Each calls `keepAnchorClear` for this layer and anchor while
+ * `isCurrent` says they are still the live pair. Returns the function that
+ * removes every observer and listener it added.
*/
function observeAnchorClearance(
layer: HTMLElement,
@@ -647,9 +798,11 @@ function observeAnchorClearance(
}
observer.observe(anchor);
}
+ const stopObservingMove = observeMove(anchor, reread);
view.addEventListener('resize', reread);
return () => {
observer?.disconnect();
+ stopObservingMove();
view.removeEventListener('resize', reread);
};
}
@@ -1409,8 +1562,8 @@ function useLayerImplementation(
}, [isOpen, mode, updateAnchorInView]);
// A layer that keeps its anchor clear (FR4) re-reads its geometry while it
- // is open: content that grows, an anchor that resizes or a viewport resize
- // can each re-settle the standard list over the anchor or
+ // is open: content that grows, an anchor that resizes or moves (in layout or
+ // by a scroll) or a viewport resize can each re-settle the standard list over the anchor or
// give the layer a scroll range (`observeAnchorClearance`). The external
// systems are those browser observers and listeners; this effect binds them
// while the layer is open and removes them when it closes, unmounts or is
diff --git a/packages/core/src/Tooltip/__tests__/TooltipTallContentTracking.a11y.browser.spec.ts b/packages/core/src/Tooltip/__tests__/TooltipTallContentTracking.a11y.browser.spec.ts
new file mode 100644
index 0000000000..1eb9c5e29a
--- /dev/null
+++ b/packages/core/src/Tooltip/__tests__/TooltipTallContentTracking.a11y.browser.spec.ts
@@ -0,0 +1,1162 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TooltipTallContentTracking.a11y.browser.spec.ts
+ * @input The `Core/Tooltip` TallContent and TallContentReplacedTrigger
+ * stories in a built Storybook, and real keyboard input and scrolling.
+ * @output Real-engine proof, in Chromium and WebKit, that an open tooltip
+ * that keeps its trigger clear follows a same-size trigger that moves on
+ * screen, in layout or because the page scrolled: at most the first painted
+ * frame after the move shows it over the trigger, a smooth scroll is
+ * followed through every frame and later moves are still observed (also
+ * after a scrolled container has hidden the trigger), it
+ * ends on the roomier side at a readable size, a scroll alone never
+ * switches a tooltip that fits, and placing a shown tooltip afresh keeps
+ * every animation in its content in its exact state.
+ * @position Run with `pnpm test:a11y-contract` (Chromium) and
+ * `pnpm exec playwright test TooltipTallContentTracking --project webkit`.
+ * The tracking reads geometry after paint, which only a real engine paints.
+ *
+ * SYNC: Fixtures live in /apps/storybook/stories/Tooltip.stories.tsx
+ * (TallContent, TallContentReplacedTrigger).
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
+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();
+});
+
+interface Box {
+ top: number;
+ bottom: number;
+ left: number;
+ right: number;
+}
+
+function overlaps(a: Box, b: Box): boolean {
+ return (
+ a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom
+ );
+}
+
+async function rect(page: Page, selector: string): Promise<Box> {
+ return page.evaluate(sel => {
+ const el = document.querySelector(sel);
+ if (el == null) {
+ throw new Error(`${sel} is not in the document`);
+ }
+ const r = el.getBoundingClientRect();
+ return {top: r.top, bottom: r.bottom, left: r.left, right: r.right};
+ }, selector);
+}
+
+/** The story's trigger; Storybook's own buttons share the iframe. */
+const TRIGGER = '#storybook-root button';
+const TOOLTIP = '[role="tooltip"]';
+
+/**
+ * The replacement trigger in the TallContentReplacedTrigger story, once
+ * `openReplacedTrigger` has marked it.
+ */
+const TRIGGER_2 = '[data-test-replacement]';
+
+interface Frame {
+ tooltip: Box;
+ trigger: Box;
+ /** The tooltip's visible content height in that frame. */
+ tooltipHeight: number;
+}
+
+/**
+ * Apply `style` to the element `selector` names, then read the tooltip's and
+ * that element's boxes as each of the next eight frames painted them.
+ */
+async function moveAndSampleFrames(
+ page: Page,
+ selector: string,
+ style: Partial<
+ Record<
+ 'marginBlockEnd' | 'blockSize' | 'position' | 'insetBlockStart',
+ string
+ >
+ >,
+): Promise<Frame[]> {
+ return page.evaluate(
+ async ({sel, tip, changes}) => {
+ const box = (el: Element) => {
+ const r = el.getBoundingClientRect();
+ return {top: r.top, bottom: r.bottom, left: r.left, right: r.right};
+ };
+ const el = document.querySelector<HTMLElement>(sel);
+ if (el == null) {
+ throw new Error(`${sel} is not in the document`);
+ }
+ Object.assign(el.style, changes);
+ const frames: {tooltip: Box; trigger: Box; tooltipHeight: number}[] = [];
+ // A message posted from a frame callback runs as the first task after
+ // that frame has painted, before the tasks the frame itself queued
+ // (intersection observer callbacks among them), so it reads what the
+ // frame painted.
+ const afterPaint = async () =>
+ new Promise<void>(resolve => {
+ requestAnimationFrame(() => {
+ const channel = new MessageChannel();
+ channel.port1.onmessage = () => resolve();
+ channel.port2.postMessage(null);
+ });
+ });
+ for (let i = 0; i < 8; i++) {
+ await afterPaint();
+ const t = document.querySelector(tip);
+ if (t != null) {
+ frames.push({
+ tooltip: box(t),
+ trigger: box(el),
+ tooltipHeight: (t as HTMLElement).clientHeight,
+ });
+ }
+ }
+ return frames;
+ },
+ {sel: selector, tip: TOOLTIP, changes: style},
+ );
+}
+
+/** At most the first painted frame after a move may show the overlap. */
+function expectClearFromSecondFrame(frames: Frame[]) {
+ expect(frames.length).toBe(8);
+ for (const [i, frame] of frames.entries()) {
+ if (i === 0) {
+ continue;
+ }
+ expect(
+ overlaps(frame.tooltip, frame.trigger),
+ `painted frame ${i + 1} after the move covers the trigger`,
+ ).toBe(false);
+ }
+}
+
+/**
+ * Open the TallContentReplacedTrigger story, whose trigger sits near the
+ * bottom of the viewport where the held-open tooltip fits above it, then
+ * replace the trigger with a new element in the same place. Returns the
+ * replacement's top.
+ */
+async function openReplacedTrigger(page: Page): Promise<number> {
+ await page.setViewportSize({width: 1280, height: 720});
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content-replaced-trigger&viewMode=story`,
+ );
+ await holdMotionStill(page);
+ const first = page.getByRole('button', {name: 'Trigger 1'});
+ await expect(first).toBeVisible();
+ await expect(page.getByRole('tooltip')).toBeVisible();
+ await page.waitForTimeout(200);
+ // It opened above the first trigger, on its standard list.
+ expect(
+ await page.evaluate(sel => {
+ const el = document.querySelector(sel);
+ return el?.hasAttribute('data-astryx-clears-anchor');
+ }, TOOLTIP),
+ ).toBe(false);
+ await page.getByRole('button', {name: 'Replace the trigger'}).click();
+ const second = page.getByRole('button', {name: 'Trigger 2'});
+ await expect(second).toBeVisible();
+ await second.evaluate(el => el.setAttribute('data-test-replacement', ''));
+ await page.waitForTimeout(200);
+ const t = await second.boundingBox();
+ if (t == null) {
+ throw new Error('the replacement trigger has no layout box');
+ }
+ expect(overlaps(await rect(page, TOOLTIP), await rect(page, TRIGGER_2))).toBe(
+ false,
+ );
+ await expect(page.getByRole('tooltip')).toBeVisible();
+ return t.y;
+}
+
+test('a trigger that moves in layout while its tooltip is open, without resizing or scrolling, is kept clear', async ({
+ page,
+ browserName,
+}) => {
+ await page.setViewportSize({width: 1280, height: 720});
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content&viewMode=story&args=content:A+short+tooltip`,
+ );
+ await holdMotionStill(page);
+ const trigger = page.getByRole('button', {name: 'Hover for details'});
+ await expect(trigger).toBeVisible();
+ // The trigger's top at 650px, near the bottom of a 720px viewport.
+ await page.evaluate(sel => {
+ const el = document.querySelector(sel) as HTMLElement;
+ window.scrollBy(0, el.getBoundingClientRect().top - 650);
+ }, TRIGGER);
+ // Opened from the keyboard, so no pointer is involved.
+ await trigger.focus();
+ await expect(page.getByRole('tooltip')).toBeVisible();
+ // Its content becomes 368px tall: it still fits above the trigger.
+ await page.evaluate(sel => {
+ const content = document.querySelector(sel)?.firstElementChild;
+ for (let i = 1; i <= 17; i++) {
+ const line = document.createElement('div');
+ line.textContent = `Line ${i}`;
+ content?.appendChild(line);
+ }
+ }, TOOLTIP);
+ await page.waitForTimeout(200);
+ const before = await rect(page, TRIGGER);
+ expect(overlaps(await rect(page, TOOLTIP), before)).toBe(false);
+ const scrollY = await page.evaluate(() => window.scrollY);
+
+ // The same-size trigger moves up to 340px in layout. Nothing resizes or
+ // scrolls; now the tooltip fits neither above nor below it. Only an
+ // intersection observer reports that move, after the frame that shows it
+ // has painted, so at most that first painted frame may show the overlap;
+ // the frame after it must not.
+ const frames = await moveAndSampleFrames(page, TRIGGER, {
+ position: 'relative',
+ insetBlockStart: '-310px',
+ });
+ // WebKit scrolls the page itself when an open popover's anchor moves (it
+ // does on the base too), so the trigger's move is measured in the document.
+ const after = await rect(page, TRIGGER);
+ const scrolled = (await page.evaluate(() => window.scrollY)) - scrollY;
+ expect(Math.round(after.top + scrolled)).toBe(Math.round(before.top) - 310);
+ if (browserName === 'chromium') {
+ // A pure layout move: nothing scrolled.
+ expect(scrolled).toBe(0);
+ }
+ expect(after.bottom - after.top).toBe(before.bottom - before.top);
+ expectClearFromSecondFrame(frames);
+ await expect(page.getByRole('tooltip')).toBeVisible();
+ expect(overlaps(await rect(page, TOOLTIP), after)).toBe(false);
+});
+
+test('a held-open tooltip keeps a replaced trigger clear when the replacement moves', async ({
+ page,
+}) => {
+ const top = await openReplacedTrigger(page);
+ const frames = await moveAndSampleFrames(page, TRIGGER_2, {
+ marginBlockEnd: '310px',
+ });
+ const after = await rect(page, TRIGGER_2);
+ expect(Math.round(after.top)).toBe(Math.round(top) - 310);
+ expect(Math.round(after.bottom - after.top)).toBe(32);
+ expectClearFromSecondFrame(frames);
+ expect(overlaps(await rect(page, TOOLTIP), after)).toBe(false);
+});
+
+/**
+ * From the second painted frame after a move, the tooltip is clear of the
+ * trigger, inside the viewport, on the block side with more room, and tall
+ * enough to read.
+ */
+function expectReadableOnRoomierSide(frames: Frame[], viewportHeight: number) {
+ expectClearFromSecondFrame(frames);
+ for (const [i, {tooltip, trigger, tooltipHeight}] of frames.entries()) {
+ if (i === 0) {
+ continue;
+ }
+ expect(tooltip.top).toBeGreaterThanOrEqual(0);
+ expect(tooltip.bottom).toBeLessThanOrEqual(viewportHeight);
+ expect(
+ tooltipHeight,
+ `painted frame ${i + 1} squeezes the tooltip to ${tooltipHeight}px`,
+ ).toBeGreaterThan(200);
+ if (trigger.top > viewportHeight - trigger.bottom) {
+ expect(tooltip.bottom).toBeLessThanOrEqual(trigger.top);
+ } else {
+ expect(tooltip.top).toBeGreaterThanOrEqual(trigger.bottom);
+ }
+ }
+}
+
+/**
+ * Focus the trigger of a 60-line tooltip on a phone, with the trigger's centre
+ * at `triggerY`, and wait until the tooltip has switched to its anchor-clear
+ * list.
+ */
+async function focusTallTriggerOnPhone(page: Page, triggerY: number) {
+ await page.setViewportSize({width: 390, height: 700});
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content&viewMode=story`,
+ );
+ await holdMotionStill(page);
+ const trigger = page.getByRole('button', {name: 'Hover for details'});
+ await expect(trigger).toBeVisible();
+ await page.evaluate(
+ ([sel, y]) => {
+ const el = document.querySelector(sel as string) as HTMLElement;
+ const r = el.getBoundingClientRect();
+ window.scrollBy(0, r.top + r.height / 2 - (y as number));
+ },
+ [TRIGGER, triggerY],
+ );
+ await trigger.focus();
+ await expect(page.getByRole('tooltip')).toBeVisible();
+ await page.waitForTimeout(200);
+ expect(
+ await page.evaluate(
+ sel =>
+ document.querySelector(sel)?.hasAttribute('data-astryx-clears-anchor'),
+ TOOLTIP,
+ ),
+ ).toBe(true);
+}
+
+test('a switched tooltip whose trigger moves toward the far edge moves to the roomier side, readable', async ({
+ page,
+}) => {
+ // The 390×700 case: opened below a trigger in the upper half, the tooltip
+ // must not stay below, squeezed to a sliver, once the trigger moves down.
+ await focusTallTriggerOnPhone(page, 200);
+ const before = await rect(page, TOOLTIP);
+ const trigger = await rect(page, TRIGGER);
+ expect(before.top).toBeGreaterThanOrEqual(trigger.bottom);
+ const frames = await moveAndSampleFrames(page, TRIGGER, {
+ position: 'relative',
+ insetBlockStart: '460px',
+ });
+ expectReadableOnRoomierSide(frames, 700);
+});
+
+test('a switched tooltip whose trigger moves the other way moves to the roomier side, readable', async ({
+ page,
+}) => {
+ // Opened above a trigger in the lower half, then the trigger moves up.
+ await focusTallTriggerOnPhone(page, 500);
+ const before = await rect(page, TOOLTIP);
+ const trigger = await rect(page, TRIGGER);
+ expect(before.bottom).toBeLessThanOrEqual(trigger.top);
+ const frames = await moveAndSampleFrames(page, TRIGGER, {
+ position: 'relative',
+ insetBlockStart: '-400px',
+ });
+ expectReadableOnRoomierSide(frames, 700);
+});
+
+test('a tooltip that switches lists after it has painted is placed afresh, not left on its old option', async ({
+ page,
+}) => {
+ // A held-open short tooltip paints above its trigger, then grows to 368px
+ // and its trigger moves up: the old option leaves the box past the top of
+ // the viewport, so the tooltip switches lists while it is showing.
+ await page.setViewportSize({width: 1280, height: 720});
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content&viewMode=story&args=content:A+short+tooltip;isOpen:!true`,
+ );
+ await holdMotionStill(page);
+ await expect(page.getByRole('tooltip')).toBeVisible();
+ await page.evaluate(sel => {
+ const el = document.querySelector(sel) as HTMLElement;
+ window.scrollBy(0, el.getBoundingClientRect().top - 650);
+ }, TRIGGER);
+ await page.waitForTimeout(200);
+ await page.evaluate(sel => {
+ const content = document.querySelector(sel)?.firstElementChild;
+ for (let i = 1; i <= 17; i++) {
+ const line = document.createElement('div');
+ line.textContent = `Line ${i}`;
+ content?.appendChild(line);
+ }
+ }, TOOLTIP);
+ await page.waitForTimeout(200);
+ const frames = await moveAndSampleFrames(page, TRIGGER, {
+ position: 'relative',
+ insetBlockStart: '-310px',
+ });
+ expectClearFromSecondFrame(frames);
+ for (const {tooltip} of frames.slice(1)) {
+ expect(tooltip.top).toBeGreaterThanOrEqual(0);
+ expect(tooltip.bottom).toBeLessThanOrEqual(720);
+ }
+});
+
+/**
+ * Open the held-open TallContent story with `content` at `viewport`, with the
+ * trigger's centre at `triggerY`.
+ */
+async function openHeldTooltip(
+ page: Page,
+ viewport: {width: number; height: number},
+ content: string,
+ triggerY: number,
+) {
+ await page.setViewportSize(viewport);
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content&viewMode=story&args=isOpen:!true${content ? `;content:${content}` : ''}`,
+ );
+ await holdMotionStill(page);
+ await expect(page.getByRole('tooltip')).toBeVisible();
+ await page.evaluate(
+ ([sel, y]) => {
+ const el = document.querySelector(sel as string) as HTMLElement;
+ const r = el.getBoundingClientRect();
+ window.scrollBy(0, r.top + r.height / 2 - (y as number));
+ },
+ [TRIGGER, triggerY],
+ );
+ await page.waitForTimeout(300);
+}
+
+async function hasSwitched(page: Page): Promise<boolean | undefined> {
+ return page.evaluate(
+ sel =>
+ document.querySelector(sel)?.hasAttribute('data-astryx-clears-anchor'),
+ TOOLTIP,
+ );
+}
+
+test('a scroll never switches a tooltip that fits, so it still flips below when it grows', async ({
+ page,
+}) => {
+ // A short tooltip opened by keyboard focus above a trigger near the top.
+ await page.setViewportSize({width: 1280, height: 720});
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content&viewMode=story&args=content:A+short+tooltip`,
+ );
+ await holdMotionStill(page);
+ const button = page.getByRole('button', {name: 'Hover for details'});
+ await expect(button).toBeVisible();
+ await page.evaluate(sel => {
+ const el = document.querySelector(sel) as HTMLElement;
+ const r = el.getBoundingClientRect();
+ window.scrollBy(0, r.top + r.height / 2 - 200);
+ }, TRIGGER);
+ await button.focus();
+ await expect(page.getByRole('tooltip')).toBeVisible();
+ await page.waitForTimeout(200);
+ const atOpen = await hasSwitched(page);
+ // Small scroll steps, each one painted, with the tooltip open throughout.
+ for (let i = 0; i < 10; i++) {
+ await page.evaluate(() => window.scrollBy(0, 6));
+ await page.waitForTimeout(40);
+ }
+ await page.waitForTimeout(200);
+ expect(await hasSwitched(page)).toBe(atOpen);
+ // Grown past the room above, it stays clear of its trigger and in view.
+ await page.evaluate(sel => {
+ const content = document.querySelector(sel)?.firstElementChild;
+ for (let i = 1; i <= 12; i++) {
+ const line = document.createElement('div');
+ line.textContent = `Line ${i}`;
+ content?.appendChild(line);
+ }
+ }, TOOLTIP);
+ await page.waitForTimeout(300);
+ const tooltip = await rect(page, TOOLTIP);
+ const trigger = await rect(page, TRIGGER);
+ expect(overlaps(tooltip, trigger)).toBe(false);
+ expect(tooltip.top).toBeGreaterThanOrEqual(0);
+ expect(tooltip.bottom).toBeLessThanOrEqual(720);
+ // On the standard list it flips below, as any layer does, rather than
+ // moving beside its trigger.
+ expect(atOpen).toBe(false);
+ expect(tooltip.top).toBeGreaterThanOrEqual(trigger.bottom);
+ expect(tooltip.left).toBeLessThan(trigger.right);
+ expect(await hasSwitched(page)).toBe(false);
+});
+
+test('a scroll that moves a tall tooltip’s trigger never leaves the tooltip over it past the first painted frame, and it ends on the roomier side', async ({
+ page,
+}) => {
+ // The 60-line tooltip, switched and below a trigger in the upper half of a
+ // phone; the page scrolls in steps that carry the trigger down the screen,
+ // past the middle, until the room above is the larger.
+ await openHeldTooltip(page, {width: 390, height: 700}, '', 150);
+ expect(await hasSwitched(page)).toBe(true);
+ for (let step = 0; step < 4; step++) {
+ const frames = await page.evaluate(
+ async ({sel, tip}) => {
+ const box = (el: Element) => {
+ const r = el.getBoundingClientRect();
+ return {top: r.top, bottom: r.bottom, left: r.left, right: r.right};
+ };
+ window.scrollBy(0, -110);
+ const out: {tooltip: Box; trigger: Box}[] = [];
+ for (let i = 0; i < 4; i++) {
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => {
+ const channel = new MessageChannel();
+ channel.port1.onmessage = () => resolve();
+ channel.port2.postMessage(null);
+ });
+ });
+ const t = document.querySelector(tip);
+ const a = document.querySelector(sel);
+ if (t != null && a != null) {
+ out.push({tooltip: box(t), trigger: box(a)});
+ }
+ }
+ return out;
+ },
+ {sel: TRIGGER, tip: TOOLTIP},
+ );
+ expect(frames.length).toBe(4);
+ for (const [i, frame] of frames.entries()) {
+ if (i === 0) {
+ continue;
+ }
+ expect(
+ overlaps(frame.tooltip, frame.trigger),
+ `scroll step ${step + 1}, painted frame ${i + 1} covers the trigger`,
+ ).toBe(false);
+ }
+ }
+ const trigger = await rect(page, TRIGGER);
+ const tooltip = await rect(page, TOOLTIP);
+ expect(trigger.top).toBeGreaterThan(700 - trigger.bottom);
+ expect(tooltip.bottom).toBeLessThanOrEqual(trigger.top);
+});
+
+test('a smooth scroll that carries a tall tooltip’s trigger leaves it clear and in view, and a later scroll is still followed', async ({
+ page,
+}) => {
+ // The 60-line tooltip, switched and below a trigger near the top of a
+ // phone. One smooth scroll carries the trigger 440px down the screen over
+ // many frames; the observer must follow every frame of it, not only the
+ // first, and stay armed for the next move.
+ await openHeldTooltip(page, {width: 390, height: 700}, '', 150);
+ expect(await hasSwitched(page)).toBe(true);
+ const settle = async () =>
+ page.evaluate(async () => {
+ const frame = async () =>
+ new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
+ let last = Number.NaN;
+ let still = 0;
+ while (still < 5) {
+ await frame();
+ still = window.scrollY === last ? still + 1 : 0;
+ last = window.scrollY;
+ }
+ });
+ await page.evaluate(() => window.scrollBy({top: -440, behavior: 'smooth'}));
+ await settle();
+ let trigger = await rect(page, TRIGGER);
+ let tooltip = await rect(page, TOOLTIP);
+ expect(trigger.top).toBeGreaterThan(500);
+ expect(overlaps(tooltip, trigger), 'covers the trigger').toBe(false);
+ expect(tooltip.top).toBeGreaterThanOrEqual(0);
+ expect(tooltip.bottom).toBeLessThanOrEqual(700);
+ expect(tooltip.bottom - tooltip.top).toBeGreaterThan(200);
+
+ // A later instant scroll that would carry the tooltip past the top of the
+ // viewport is still observed and corrected by the second painted frame.
+ const frames = await page.evaluate(
+ async ({sel, tip}) => {
+ const box = (el: Element) => {
+ const r = el.getBoundingClientRect();
+ return {top: r.top, bottom: r.bottom, left: r.left, right: r.right};
+ };
+ window.scrollBy(0, 240);
+ const out: {tooltip: Box; trigger: Box}[] = [];
+ for (let i = 0; i < 4; i++) {
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => {
+ const channel = new MessageChannel();
+ channel.port1.onmessage = () => resolve();
+ channel.port2.postMessage(null);
+ });
+ });
+ const t = document.querySelector(tip);
+ const a = document.querySelector(sel);
+ if (t != null && a != null) {
+ out.push({tooltip: box(t), trigger: box(a)});
+ }
+ }
+ return out;
+ },
+ {sel: TRIGGER, tip: TOOLTIP},
+ );
+ expect(frames.length).toBe(4);
+ for (const [i, frame] of frames.entries()) {
+ if (i === 0) {
+ continue;
+ }
+ expect(
+ overlaps(frame.tooltip, frame.trigger),
+ `painted frame ${i + 1} covers the trigger`,
+ ).toBe(false);
+ expect(
+ frame.tooltip.top,
+ `painted frame ${i + 1} leaves the viewport`,
+ ).toBeGreaterThanOrEqual(0);
+ expect(frame.tooltip.bottom).toBeLessThanOrEqual(700);
+ }
+ await settle();
+ trigger = await rect(page, TRIGGER);
+ tooltip = await rect(page, TOOLTIP);
+ expect(overlaps(tooltip, trigger)).toBe(false);
+ expect(tooltip.bottom - tooltip.top).toBeGreaterThan(200);
+});
+
+test('a trigger that a scrolled container hides for several seconds is followed again when it scrolls back into view', async ({
+ page,
+}) => {
+ // The 60-line tooltip, held open, with the page inside a 700px scroll
+ // container on a phone. The container scrolls the trigger out of its view
+ // for longer than any short retry would wait, then scrolls it back to
+ // where the room above is the larger.
+ await page.setViewportSize({width: 390, height: 700});
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content&viewMode=story&args=isOpen:!true`,
+ );
+ await holdMotionStill(page);
+ await page.addStyleTag({
+ content: '#storybook-root{height:700px;overflow:auto}',
+ });
+ await expect(page.getByRole('tooltip')).toBeVisible();
+ // Scroll the container so the trigger's centre lands at `y` in the
+ // viewport.
+ const scrollTriggerTo = async (y: number) =>
+ page.evaluate(
+ ([sel, y]) => {
+ const el = document.querySelector(sel as string);
+ if (el == null) {
+ return;
+ }
+ const r = el.getBoundingClientRect();
+ document
+ .getElementById('storybook-root')
+ ?.scrollBy(0, r.top + r.height / 2 - (y as number));
+ },
+ [TRIGGER, y],
+ );
+ // Making the container clips the trigger for a moment; let any recheck of
+ // that settle before the case starts.
+ await scrollTriggerTo(150);
+ await page.waitForTimeout(1500);
+ expect(await hasSwitched(page)).toBe(true);
+
+ await scrollTriggerTo(-150);
+ await page.waitForTimeout(3500);
+ expect((await rect(page, TRIGGER)).bottom).toBeLessThan(0);
+
+ await scrollTriggerTo(590);
+ await page.waitForTimeout(300);
+ const trigger = await rect(page, TRIGGER);
+ const tooltip = await rect(page, TOOLTIP);
+ expect(trigger.top).toBeGreaterThan(500);
+ expect(overlaps(tooltip, trigger), 'covers the trigger').toBe(false);
+ expect(tooltip.top).toBeGreaterThanOrEqual(0);
+ expect(tooltip.bottom).toBeLessThanOrEqual(700);
+ expect(tooltip.bottom - tooltip.top).toBeGreaterThan(200);
+});
+
+test('placing a shown tooltip afresh never replays its entry animation', async ({
+ page,
+ browserName,
+}) => {
+ // Motion allowed: the entry fade plays once, at open. A keyboard-focused
+ // short tooltip grows, then its trigger moves up so the old option leaves
+ // it past the top of the viewport: it switches lists after it has painted,
+ // and that re-placement must not fade it in again.
+ await page.setViewportSize({width: 1280, height: 720});
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content&viewMode=story&args=content:A+short+tooltip`,
+ );
+ const button = page.getByRole('button', {name: 'Hover for details'});
+ await expect(button).toBeVisible();
+ await page.evaluate(sel => {
+ const el = document.querySelector(sel) as HTMLElement;
+ window.scrollBy(0, el.getBoundingClientRect().top - 650);
+ }, TRIGGER);
+ await button.focus();
+ await expect(page.getByRole('tooltip')).toBeVisible();
+ // Let the entry fade finish.
+ await page.waitForTimeout(600);
+ await page.evaluate(sel => {
+ const content = document.querySelector(sel)?.firstElementChild;
+ for (let i = 1; i <= 17; i++) {
+ const line = document.createElement('div');
+ line.textContent = `Line ${i}`;
+ content?.appendChild(line);
+ }
+ }, TOOLTIP);
+ await page.waitForTimeout(300);
+ const opacities = await page.evaluate(
+ async ({sel, tip}) => {
+ const trigger = document.querySelector(sel) as HTMLElement;
+ const tooltip = document.querySelector(tip) as HTMLElement;
+ trigger.style.position = 'relative';
+ trigger.style.insetBlockStart = '-310px';
+ const out: number[] = [];
+ for (let i = 0; i < 12; i++) {
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => {
+ const channel = new MessageChannel();
+ channel.port1.onmessage = () => resolve();
+ channel.port2.postMessage(null);
+ });
+ });
+ out.push(Number(getComputedStyle(tooltip).opacity));
+ }
+ return {
+ out,
+ switched: tooltip.hasAttribute('data-astryx-clears-anchor'),
+ };
+ },
+ {sel: TRIGGER, tip: TOOLTIP},
+ );
+ if (browserName === 'chromium') {
+ // Chromium keeps the tooltip on its old option until the runtime
+ // switches and re-places it; WebKit re-runs the standard list itself when
+ // the trigger moves, so there it never fails and is never re-placed.
+ expect(opacities.switched).toBe(true);
+ }
+ for (const [i, opacity] of opacities.out.entries()) {
+ expect(opacity, `painted frame ${i + 1}`).toBe(1);
+ }
+});
+
+/**
+ * The animation-state regression for the re-placement, driven by what the
+ * engine exposes. In the page it lists every accessor with a setter on a CSS
+ * animation's and its keyframe effect's prototype chains, plus every field of
+ * the effect's timing, and fails if any has no row here. Each row gives one
+ * content element's animation a non-default value for that member (or a
+ * method-only state), and the test checks that the element's whole
+ * animation state is the same after the after-paint re-placement as before.
+ */
+const STATE_ROWS: Record<
+ string,
+ {css?: string; extraCss?: string; set?: string}
+> = {
+ // Animation accessors.
+ currentTime: {set: 'a.currentTime = 4321'},
+ startTime: {set: 'a.startTime = document.timeline.currentTime - 2500'},
+ playbackRate: {set: 'a.playbackRate = 2'},
+ id: {set: "a.id = 'kept'"},
+ onfinish: {set: 'a.onfinish = window.__handler'},
+ oncancel: {set: 'a.oncancel = window.__handler'},
+ onremove: {set: 'a.onremove = window.__handler'},
+ timeline: {
+ set: 'a.timeline = new ScrollTimeline({source: document.documentElement})',
+ },
+ rangeStart: {
+ css: 'animation-timeline:scroll(nearest block);animation-range:entry 10% exit 80%',
+ set: "a.rangeStart = 'cover 20%'",
+ },
+ rangeEnd: {
+ css: 'animation-timeline:scroll(nearest block);animation-range:entry 10% exit 80%',
+ set: "a.rangeEnd = 'cover 70%'",
+ },
+ effect: {
+ set: "a.effect = new KeyframeEffect(el, [{translate: '0px'}, {translate: '30px'}], {duration: 7000, fill: 'both'})",
+ },
+ // Keyframe effect accessors.
+ target: {set: 'a.effect.target = el.nextElementSibling'},
+ pseudoElement: {
+ extraCss: '[data-row="pseudoElement"]::before{content:"·"}',
+ set: "a.effect.pseudoElement = '::before'",
+ },
+ composite: {set: "a.effect.composite = 'add'"},
+ iterationComposite: {set: "a.effect.iterationComposite = 'accumulate'"},
+ // Effect timing fields.
+ delay: {set: 'a.effect.updateTiming({delay: 500})'},
+ direction: {set: "a.effect.updateTiming({direction: 'alternate'})"},
+ duration: {set: 'a.effect.updateTiming({duration: 20000})'},
+ easing: {set: "a.effect.updateTiming({easing: 'ease-in'})"},
+ endDelay: {set: 'a.effect.updateTiming({endDelay: 300})'},
+ fill: {set: "a.effect.updateTiming({fill: 'forwards'})"},
+ iterationStart: {set: 'a.effect.updateTiming({iterationStart: 0.25})'},
+ iterations: {set: 'a.effect.updateTiming({iterations: 3})'},
+ // Method-only state.
+ keyframes: {
+ set: "a.effect.setKeyframes([{translate: '0px'}, {translate: '50px'}])",
+ },
+ paused: {set: 'a.pause()'},
+ reversed: {set: 'a.reverse()'},
+ finished: {css: 'animation-duration:1ms;animation-fill-mode:forwards'},
+ persisted: {set: 'a.persist()'},
+ // Shapes.
+ running: {},
+ 'stylesheet-paused': {css: 'animation-play-state:paused'},
+ duplicate: {
+ css: 'animation:test-shift 10s linear both,test-shift 10s linear both;animation-composition:add,add',
+ set: 'el.getAnimations()[1].currentTime = Number(a.currentTime) + 3000',
+ },
+ descendant: {},
+ script: {
+ css: 'animation:none',
+ set: "window.__scriptAnimation = el.animate([{translate: '0px'}, {translate: '100px'}], {duration: 10000})",
+ },
+ transition: {
+ css: 'animation:none;transition:translate 10s linear',
+ set: "el.style.translate = '100px'",
+ },
+};
+
+test('placing a shown tooltip afresh keeps every animation in its content in its exact state', async ({
+ page,
+ browserName,
+}) => {
+ await page.setViewportSize({width: 1280, height: 720});
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content&viewMode=story&args=content:A+short+tooltip;isOpen:!true`,
+ );
+ await expect(page.getByRole('tooltip')).toBeVisible();
+ await page.evaluate(sel => {
+ const el = document.querySelector(sel) as HTMLElement;
+ window.scrollBy(0, el.getBoundingClientRect().top - 650);
+ }, TRIGGER);
+ await page.waitForTimeout(300);
+ await page.addStyleTag({
+ content: `@keyframes test-shift{from{translate:0}to{translate:100px}}[data-row]{display:inline-block;margin-inline-end:4px;animation:test-shift 10s linear both}${Object.entries(
+ STATE_ROWS,
+ )
+ .map(
+ ([name, row]) =>
+ (row.css ? `[data-row="${name}"]{${row.css}}` : '') +
+ (row.extraCss ?? ''),
+ )
+ .join('')}`,
+ });
+ // One element per row (and a spare sibling to retarget to), then enough
+ // lines for the switch below.
+ const uncovered = await page.evaluate(
+ ({sel, names}) => {
+ const content = document.querySelector(sel)?.firstElementChild;
+ for (const name of names) {
+ let host = content;
+ if (name === 'descendant') {
+ for (let i = 0; i < 3; i++) {
+ const wrapper = document.createElement('span');
+ host?.appendChild(wrapper);
+ host = wrapper;
+ }
+ }
+ const row = document.createElement('span');
+ row.dataset.row = name;
+ row.textContent = name.slice(0, 2);
+ host?.appendChild(row);
+ const spare = document.createElement('span');
+ spare.textContent = '·';
+ host?.appendChild(spare);
+ }
+ for (let i = 1; i <= 17; i++) {
+ const line = document.createElement('div');
+ line.textContent = `Line ${i}`;
+ content?.appendChild(line);
+ }
+ // What the engine exposes as writable state.
+ const sample = document.querySelector('[data-row="running"]') as Element;
+ const animation = sample.getAnimations()[0];
+ const accessors = (object: object) => {
+ const out: string[] = [];
+ for (
+ let proto = Object.getPrototypeOf(object);
+ proto != null && proto !== Object.prototype;
+ proto = Object.getPrototypeOf(proto)
+ ) {
+ for (const [key, d] of Object.entries(
+ Object.getOwnPropertyDescriptors(proto),
+ )) {
+ if (d.set != null) {
+ out.push(key);
+ }
+ }
+ }
+ return out;
+ };
+ const members = [
+ ...accessors(animation),
+ ...accessors(animation.effect as object),
+ ...Object.keys((animation.effect as KeyframeEffect).getTiming()),
+ ];
+ return members.filter(member => !names.includes(member));
+ },
+ {sel: TOOLTIP, names: Object.keys(STATE_ROWS)},
+ );
+ expect(uncovered, 'writable animation members with no row').toEqual([]);
+ await page.waitForTimeout(700);
+ // Give each row its state. A row whose member this engine lacks (WebKit's
+ // `iterationComposite` is missing from Chromium) is skipped.
+ await page.evaluate(() => {
+ (window as unknown as {__handler: unknown}).__handler =
+ function handler() {};
+ });
+ const skipped: string[] = [];
+ for (const [name, row] of Object.entries(STATE_ROWS)) {
+ if (row.set == null) {
+ continue;
+ }
+ const applied = await page.evaluate(
+ `(() => {
+ const el = document.querySelector('[data-row="${name}"]');
+ const a = el.getAnimations()[0];
+ if (${name === 'iterationComposite'} && !('iterationComposite' in a.effect)) {
+ return false;
+ }
+ ${row.set};
+ return true;
+ })()`,
+ );
+ if (applied !== true) {
+ skipped.push(name);
+ }
+ }
+ await page.evaluate(() => {
+ (window as unknown as {__runningBefore: unknown}).__runningBefore = (
+ document.querySelector('[data-row="running"]') as Element
+ ).getAnimations()[0];
+ });
+ await page.waitForTimeout(100);
+ const read = async () =>
+ page.evaluate(names => {
+ const handler = (window as unknown as {__handler: unknown}).__handler;
+ type Serialized =
+ | string
+ | number
+ | boolean
+ | null
+ | undefined
+ | {[key: string]: Serialized};
+ const ser = (value: unknown): Serialized => {
+ if (
+ value == null ||
+ typeof value === 'boolean' ||
+ typeof value === 'string'
+ ) {
+ return value;
+ }
+ if (typeof value === 'number') {
+ return Math.round(value * 10) / 10;
+ }
+ if (typeof value === 'function') {
+ return value === handler ? 'handler' : 'function';
+ }
+ if (
+ typeof CSSNumericValue !== 'undefined' &&
+ value instanceof CSSNumericValue
+ ) {
+ return value.toString();
+ }
+ if (value instanceof Element) {
+ return (value as HTMLElement).dataset.row ?? value.textContent;
+ }
+ if (Object.getPrototypeOf(value) === Object.prototype) {
+ return Object.fromEntries(
+ Object.entries(value).map(([k, v]) => [k, ser(v)]),
+ );
+ }
+ return value.constructor.name;
+ };
+ const stateOf = (a: Animation) => {
+ const effect = a.effect as KeyframeEffect;
+ const out: Record<string, unknown> = {};
+ for (const object of [a, effect]) {
+ for (
+ let proto = Object.getPrototypeOf(object);
+ proto != null && proto !== Object.prototype;
+ proto = Object.getPrototypeOf(proto)
+ ) {
+ for (const [key, d] of Object.entries(
+ Object.getOwnPropertyDescriptors(proto),
+ )) {
+ if (d.get != null && d.set != null && !(key in out)) {
+ out[key] = ser(
+ (object as unknown as Record<string, unknown>)[key],
+ );
+ }
+ }
+ }
+ }
+ out.timing = ser(effect.getTiming());
+ out.keyframes = JSON.stringify(effect.getKeyframes());
+ out.playState = a.playState;
+ out.replaceState = a.replaceState;
+ return out;
+ };
+ const rows: Record<string, Record<string, unknown>[]> = {};
+ for (const name of names) {
+ const el = document.querySelector(`[data-row="${name}"]`) as Element;
+ // Its animations, including one moved to a pseudo-element or (for a
+ // retargeted effect) to the spare sibling.
+ const tooltip = document.querySelector('[role="tooltip"]') as Element;
+ rows[name] = tooltip
+ .getAnimations({subtree: true})
+ .filter(animation => {
+ const target = (animation.effect as KeyframeEffect).target;
+ return target === el || target === el.nextElementSibling;
+ })
+ .map(stateOf);
+ }
+ const script = (
+ document.querySelector('[data-row="script"]') as Element
+ ).getAnimations()[0];
+ const running = (
+ document.querySelector('[data-row="running"]') as Element
+ ).getAnimations()[0];
+ const w = window as unknown as Record<string, unknown>;
+ return {
+ rows,
+ at: performance.now(),
+ scrollY: window.scrollY,
+ scriptSame: script === w.__scriptAnimation,
+ recreated: running !== w.__runningBefore,
+ };
+ }, Object.keys(STATE_ROWS));
+ const before = await read();
+ await page.evaluate(sel => {
+ const el = document.querySelector(sel) as HTMLElement;
+ el.style.position = 'relative';
+ el.style.insetBlockStart = '-310px';
+ }, TRIGGER);
+ await page.waitForTimeout(450);
+ if (browserName === 'chromium') {
+ expect(await hasSwitched(page)).toBe(true);
+ }
+ const after = await read();
+ // In Chromium the browser recreated the content's CSS animations: this is
+ // the path that has to put them back. (WebKit re-runs the standard list
+ // itself when the trigger moves, so there the tooltip is never re-placed;
+ // every row must hold either way.)
+ if (browserName === 'chromium') {
+ expect(after.recreated).toBe(true);
+ }
+ expect(after.scriptSame).toBe(true);
+ const elapsed = after.at - before.at;
+ const failed: string[] = [];
+ for (const name of Object.keys(STATE_ROWS)) {
+ if (skipped.includes(name)) {
+ continue;
+ }
+ const b = before.rows[name];
+ const a = after.rows[name];
+ if (a.length !== b.length) {
+ failed.push(`${name}: ${b.length} animations before, ${a.length} after`);
+ continue;
+ }
+ for (const [i, stateBefore] of b.entries()) {
+ const stateAfter = a[i];
+ // Times move on with the clock; every other member must be unchanged.
+ const {currentTime: t0, startTime: s0, ...restBefore} = stateBefore;
+ const {currentTime: t1, startTime: s1, ...restAfter} = stateAfter;
+ if (JSON.stringify(restBefore) !== JSON.stringify(restAfter)) {
+ failed.push(
+ `${name}: ${JSON.stringify(restBefore)} -> ${JSON.stringify(restAfter)}`,
+ );
+ continue;
+ }
+ const rate = Number(stateBefore.playbackRate);
+ // A scroll-driven animation's time follows the page's scroll position,
+ // which WebKit moves by itself when an open popover's anchor moves.
+ const scrollDriven = stateBefore.timeline !== 'DocumentTimeline';
+ if (scrollDriven && after.scrollY !== before.scrollY) {
+ // Its time is the browser's to change; the rest was compared above.
+ } else if (typeof t0 === 'number' && typeof t1 === 'number') {
+ const expected =
+ stateBefore.playState === 'running' &&
+ stateBefore.timeline === 'DocumentTimeline'
+ ? t0 + rate * elapsed
+ : t0;
+ if (Math.abs(t1 - expected) > 150) {
+ failed.push(
+ `${name}: currentTime ${t0} -> ${t1}, expected about ${Math.round(expected)}`,
+ );
+ }
+ } else if (t0 !== t1) {
+ failed.push(`${name}: currentTime ${String(t0)} -> ${String(t1)}`);
+ }
+ // A finished animation's start time is the one documented limitation:
+ // script cannot set a start time and a held end time together.
+ if (
+ stateBefore.playState !== 'finished' &&
+ typeof s0 === 'number' &&
+ typeof s1 === 'number' &&
+ Math.abs(s1 - s0) > 50
+ ) {
+ failed.push(`${name}: startTime ${s0} -> ${s1}`);
+ }
+ }
+ }
+ expect(failed).toEqual([]);
+ // The stylesheet still controls the animation it paused.
+ await page.addStyleTag({
+ content: '[data-row="stylesheet-paused"]{animation-play-state:running}',
+ });
+ await page.waitForTimeout(100);
+ expect(
+ await page.evaluate(
+ () =>
+ (
+ document.querySelector(
+ '[data-row="stylesheet-paused"]',
+ ) as HTMLElement
+ ).getAnimations()[0].playState,
+ ),
+ ).toBe('running');
+});
+
+test('a short, wide tooltip carried past the viewport edge moves to the other side at its own size', async ({
+ page,
+}) => {
+ // A held-open tooltip too wide to go beside its trigger on a phone sits
+ // above a trigger near the bottom. A scroll carries the trigger to the top,
+ // so the tooltip can no longer fit above: it moves below, keeping its size
+ // rather than stretching to the room there, and still keeps its size when
+ // its content then grows within that room.
+ await page.setViewportSize({width: 390, height: 700});
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content&viewMode=story&args=isOpen:!true;content:A+short+but+wide+tooltip+whose+text+wraps+onto+a+few+lines+here`,
+ );
+ await holdMotionStill(page);
+ await expect(page.getByRole('tooltip')).toBeVisible();
+ const scrollTriggerTo = async (y: number) => {
+ await page.evaluate(
+ ([sel, top]) => {
+ const el = document.querySelector(sel as string) as HTMLElement;
+ const r = el.getBoundingClientRect();
+ window.scrollBy(0, r.top + r.height / 2 - (top as number));
+ },
+ [TRIGGER, y],
+ );
+ await page.waitForTimeout(400);
+ };
+ await scrollTriggerTo(650);
+ const before = await rect(page, TOOLTIP);
+ const triggerBefore = await rect(page, TRIGGER);
+ expect(before.bottom).toBeLessThanOrEqual(triggerBefore.top);
+ const height = before.bottom - before.top;
+ expect(height).toBeLessThan(120);
+ await scrollTriggerTo(28);
+ const after = await rect(page, TOOLTIP);
+ const trigger = await rect(page, TRIGGER);
+ expect(overlaps(after, trigger)).toBe(false);
+ expect(after.top).toBeGreaterThanOrEqual(trigger.bottom);
+ expect(Math.abs(after.bottom - after.top - height)).toBeLessThanOrEqual(1);
+ // Grown within the room below, it still takes only the room it needs.
+ await page.evaluate(sel => {
+ const content = document.querySelector(sel)?.firstElementChild;
+ for (let i = 1; i <= 10; i++) {
+ const line = document.createElement('div');
+ line.textContent = `Line ${i}`;
+ content?.appendChild(line);
+ }
+ }, TOOLTIP);
+ await page.waitForTimeout(400);
+ const grown = await rect(page, TOOLTIP);
+ const metrics = await page.evaluate(sel => {
+ const el = document.querySelector(sel) as HTMLElement;
+ return {scrollHeight: el.scrollHeight, clientHeight: el.clientHeight};
+ }, TOOLTIP);
+ expect(grown.top).toBeGreaterThanOrEqual(trigger.bottom);
+ expect(grown.bottom - grown.top).toBeLessThan(400);
+ expect(metrics.scrollHeight).toBeLessThanOrEqual(metrics.clientHeight + 1);
+});