An open source design system that's fully customizable and agent ready
TypeScript
fix(Layer): a Tooltip re-picks its side once a scroll stops, never mid-scroll (#10439)
Cindy Zhanga21cd3ca07e4
diff --git a/.changeset/layer-no-mid-scroll-repick.md b/.changeset/layer-no-mid-scroll-repick.mdnew file mode 100644index 0000000000..8d23add60b--- /dev/null+++ b/.changeset/layer-no-mid-scroll-repick.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A Tooltip, including a Slider's value bubble, no longer jumps to another side of its trigger in the middle of a scroll. Before, when a scroll carried the trigger toward the edge, the layer runtime took the Tooltip out of rendering for one forced layout so the browser would choose its position again, and it did this again on later frames of the scroll. Now the Tooltip has one fallback list from the start, and no option in it covers the trigger: it tries the opposite side first, then beside the trigger, then a side sized to the room. During a scroll, the Tooltip keeps its side: it is not checked or placed afresh until the scroll stops. In the first frame painted after the scroll stops (at `scrollend`, or 150 ms after the last `scroll` event where the browser has no `scrollend`), it is checked once and moves to the side with room if it needs to. At a show, a remount or a size change it is checked as before.++@cixzhangdiff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.mdindex 96f3d3cf0d..9ff6a796a7 100644--- a/docs/architecture/layer-runtime.md+++ b/docs/architecture/layer-runtime.md@@ -205,39 +205,40 @@ would change a parent's last child.Content taller than the placement axis can hold on either side is capped to theviewport minus both gutters and shifted into the viewport by the browser; itsmargin box stays inside the viewport, so it keeps its anchor clearance from the-edge it meets. A layer that keeps its anchor clear (Tooltip) carries a second-list beside the first: when it finds the first list settled the box over the-anchor or, while the anchor is in view, past the viewport on the block axis-(Chromium shifts a box that fits no option over the anchor; WebKit leaves it on-its preferred side, partly off-screen), it switches to beside the anchor on the-inline end, then the inline start, at the content's inline size, then the-opposite block side at its own size, and only then the preferred block side and-the other, each only while it is the roomier side and sized to the room there;-it keeps that list until it next opens, and scrolls only while its content-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. 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.+edge it meets. A layer that keeps its anchor clear (Tooltip) carries+one combined list from its first frame, in place of the standard list+(`spec:AST-059` DEC-7): the preferred block side at its own size, then the+opposite block side at its own size, then beside the anchor on the inline end,+then on the inline start, at the content's inline size, and only then the+preferred block side and the other, each only while it is the roomier side and+sized to the room there. Every option aligns `unsafe` toward the anchor on the+placement axis, so a box that runs out of room overflows away from the anchor+and no option lets it overlap the anchor. 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. The layer scrolls only while its content overflows. Chromium+tries no more than five options, so this list replaces the standard list+rather than extending it.+During a scroll, Chromium does not choose a CSS-anchored layer's option again,+on a page or inside a scrolling panel, so the runtime checks the layer once a+scroll stops (`spec:AST-059` DEC-8). Where the box still covers the anchor or,+while the anchor is in view, leaves the viewport on the block axis, 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 its list. 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.Once the anchor has left the viewport the runtime pins the layer'sself-alignment `unsafe` toward the anchor, so the layer holds the position itsflips give it and holds its size rather than sliding to the edge. Components@@ -252,24 +253,30 @@ of view holds from its first frame. Whether a layer that keeps its anchor clearcovers its anchor or leaves the viewport, judged from its box without its owntransform (so an entry animation that starts it closer to the anchor does notcount), and whether its content overflows, is read inside `show()` and the-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 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.+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. The one read after a scroll+runs once each time a scroll of the page or of a scrolling ancestor of the+anchor stops: at `scrollend`, or, where the browser does not fire it, after+150 ms with no `scroll` event on those. It runs in the first frame painted+after the stop: the next frame paints, a task runs after that paint, and the+frame after reads and applies. The scroll listeners subscribe to the window's input stream, and listen on+each shadow root along the anchor's flat-tree path, because `scroll` and+`scrollend` are not composed. A `scroll` only cancels a pending check or+starts the timer, and no handler reads layout. Chromium fires `scrollend` per wheel step, so a long+wheel scroll is checked more than once, never during the scroll itself. An+anchor 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-arms from each report+that differs from its threshold; a report that finds an anchor which has not+moved wholly outside that rectangle means a scrolled container clips it, and 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-arms. A reported move+updates only whether the layer scrolls, in the next frame: it never checks the+box and never places the layer afresh, so the layer never changes side in the+middle of a scroll. Apart from the read after a scroll stops, a layer never+paints at a geometry it is about to correct.### Current browser support behavior@@ -550,15 +557,24 @@ layers use Layer rendering without joining Escape/platform dismissal.reported keeps its top until it closes: when the cap lifts it grows downwardin place; when the keyboard rises it moves up above it and then holds.- **INV12 — The first frame is the settled frame.** No input to a layer's- viewport geometry is measured after paint and then applied, with two+ viewport geometry is measured after paint and then applied, with threeexceptions. The runtime observes anchor visibility for every layer, and,for a layer that keeps its anchor clear, whether it covers its anchor orleaves the viewport and whether its content overflows; each is read beforefirst paint and, while the layer is open, from callbacks that run before the- frame paints. The first 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. The second is the software keyboard's cap (`spec:AST-059` FR10).+ frame paints. The first exception is the check after a scroll stops+ (`spec:AST-059` DEC-8): once a scroll of the page or of a scrolling ancestor+ of the anchor stops (`scrollend`, or 150 ms with no `scroll` event where+ `scrollend` is missing), the layer is checked once, in the first frame+ painted after the stop, and placed afresh if it fails. No scroll frame and no+ scroll handler checks the box, re-picks or forces layout for a layer, and no+ option of the layer's list overlaps its anchor, so a frame painted during+ the scroll can show the layer past the viewport edge but never over its+ anchor. The second exception is whether a layer that keeps its anchor+ clear scrolls: a same-size anchor's move, which an intersection observer+ reports after paint, re-reads the layer's scroll and client heights in the+ next frame and updates it; it never checks the box or re-picks. The+ third exception is the software keyboard's cap (`spec:AST-059` FR10).A box's height cannot change on the compositor, so the cap changes once perkeyboard movement: when a rising keyboard has arrived, at once as a fallingkeyboard starts down, and at once for a keyboard that changes without@@ -793,7 +809,8 @@ change the hosting runtime described here.`spec:AST-059` governs the viewport inset projected above: the gutter, thecaps, the fallback order and its anchor-visibility condition, and the-app-declared inset.+app-declared inset. Its DEC-7 and DEC-8 govern the anchor-clear list and the+one check after a scroll stops.`spec:AST-003` is accepted but unimplemented. It defines the approved nextruntime and must move to `shipped` before its requirements are incorporated into@@ -801,22 +818,22 @@ this current architecture record.## Verification-| Invariant | Evidence | Failure signal |-| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| INV1, INV2 | `useLayer.test.tsx` and `layerHost.test.ts` | Invalid DOM, stale host, lost theme/writing context, or portal mistaken for top-layer promotion |-| INV3–INV5 | `useLayer.test.tsx` and `anchorName.test.ts` | A mode leaks geometry, RTL resolves from the wrong context, fallback clips, or a sibling anchor is lost |-| INV11 | `layerViewportInset.test.ts`, `useLayer.test.tsx`, and the `Core/Layer` viewport-inset stories under the story play guard at a desktop and a phone viewport; `BaseTypeahead.incremental.test.tsx` and the Typeahead incremental-results stories for the `spec:AST-092` FR6 exception | A second gutter definition, a `100%`-of-span cap, a layer narrower than its explicit size, a layer box wider than the viewport, a layer inside the gutter, or a layer that slides toward an off-screen anchor; for an open Typeahead popup, a later list for the same query that flips it to the other side or grows it past the room on its side, or a first list for a query that is capped to the span beside the trigger |-| INV12 | The `Core/Layer` viewport-inset stories' first-frame comparison, and `useLayer.test.tsx`'s synchronous anchor read | A layer whose first painted rectangle differs from its settled one |-| INV11, INV12 | The software keyboard's cap: `useLayerKeyboardClearance.test.tsx` for its rule, its timing, its read before first paint, and the inset's hold; the `PopoverKeyboard`, `keyboardCappedLists` and `SelectorKeyboardInset` browser specs for its rendered geometry | A layer that runs under the keyboard, or is capped though the keyboard does not reach it; a cap that changes more than once per keyboard movement or under a press; a layer opened with the keyboard up whose first frame is uncapped or paints its content past its box; a layer that reads the inset and moves down when the keyboard report ends |-| INV13 | `layerExitCopy.test.ts` and `layerExitCopy.interaction.browser.spec.ts` | A copy with an id, a form name, a form owner, or pointer reach; a copy off the layer's drawn box; a copy outside the top layer; a second copy for one layer |-| INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface |-| INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through |-| INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests; `useBackdropPress.test.tsx`; `outsidePress.test.ts` | A current local channel silently changes ownership or policy |-| INV10 | `LayerProvider.tsx`, `toastHost.tsx`, `LayerProvider.test.tsx`, `toastHost.test.tsx`, `toastHost.lateRegistration.test.tsx`, `useToast.tsx`, `ToastViewport.test.tsx`, `ToastViewport.modalHost.test.tsx`, and `scripts/layer-toast-bundle.test.mjs` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, a default provider renders differently from no provider, a Layer import loads a Toast module, or a toast added before Toast loads is lost |-| INV14, INV15 | Source boundary check over Core for top-layer hosts, exit copies, backdrop elements, lift, and rectangle-morph code outside the runtime and the lift module | A component building its own copy of a mechanism INV14 lists (top-layer mounting, close-request delivery, hold, exit copy, or backdrop element), or re-implementing the lift or the grow |-| INV17 | One runtime suite over every kind of layer root: a `useLayer` layer, inline and portaled, and the Dialog, Drawer, Lightbox, MobileNav, BottomSheetPanel, and ToastViewport content roots, each inside a plain `onClick` wrapper and a Core clickable container; nested layers | A click inside a layer root that reaches an ancestor bubble-phase handler, a caller's wrapper included; an outer layer's handler that receives an inner layer's press; or a document listener or light dismiss that no longer receives it |-| INV18 | `useLayer.test.tsx` (a closed trigger has no anchor-name, and the trigger of a shown or fading layer does) and `TooltipClosedTriggerAnchor.interaction.browser.spec.ts` in Chromium and WebKit | A closed trigger with an anchor-name, a shown or fading layer placed away from its anchor, or a surface around a closed trigger that stops while the main thread is busy |-| INV18 | `useLayer.test.tsx`: a closed state that declares a discrete `display` transition or a keyframe animation keeps the trigger's anchor name until those animations end, read from the closed state's style; a layer whose closed state declares neither is not read for animations at the close | A layer with such a closed-state exit placed away from its anchor while it fades, or an animation read on the close of a layer whose closed state declares no exit |+| Invariant | Evidence | Failure signal |+| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| INV1, INV2 | `useLayer.test.tsx` and `layerHost.test.ts` | Invalid DOM, stale host, lost theme/writing context, or portal mistaken for top-layer promotion |+| INV3–INV5 | `useLayer.test.tsx` and `anchorName.test.ts` | A mode leaks geometry, RTL resolves from the wrong context, fallback clips, or a sibling anchor is lost |+| INV11 | `layerViewportInset.test.ts`, `useLayer.test.tsx`, and the `Core/Layer` viewport-inset stories under the story play guard at a desktop and a phone viewport; `BaseTypeahead.incremental.test.tsx` and the Typeahead incremental-results stories for the `spec:AST-092` FR6 exception | A second gutter definition, a `100%`-of-span cap, a layer narrower than its explicit size, a layer box wider than the viewport, a layer inside the gutter, or a layer that slides toward an off-screen anchor; for an open Typeahead popup, a later list for the same query that flips it to the other side or grows it past the room on its side, or a first list for a query that is capped to the span beside the trigger |+| INV12 | The `Core/Layer` viewport-inset stories' first-frame comparison, and `useLayer.test.tsx`'s synchronous anchor read; for the check after a scroll stops, `useLayer.test.tsx`'s `scrollend` and 150 ms fallback cases (one check, in the first painted frame after the stop, with no read in the scroll handler) and the Tooltip suites' scroll-edge cases; a Chromium trace at 4× CPU of a wheel scroll that carries a Tooltip's trigger to the scroll edge counts the forced layouts per scroll before and after DEC-8: page scroll 27–42 → 5, a scrolling panel 7 → 5, the Slider value bubble 12–22 → 5 | A layer whose first painted rectangle differs from its settled one; a box check, a re-pick or a forced layout for a layer in a scroll frame or a scroll handler; a re-pick before the first painted frame after a scroll stops, or more than one per stop; a painted frame that shows a layer that keeps its anchor clear over its anchor |+| INV11, INV12 | The software keyboard's cap: `useLayerKeyboardClearance.test.tsx` for its rule, its timing, its read before first paint, and the inset's hold; the `PopoverKeyboard`, `keyboardCappedLists` and `SelectorKeyboardInset` browser specs for its rendered geometry | A layer that runs under the keyboard, or is capped though the keyboard does not reach it; a cap that changes more than once per keyboard movement or under a press; a layer opened with the keyboard up whose first frame is uncapped or paints its content past its box; a layer that reads the inset and moves down when the keyboard report ends |+| INV13 | `layerExitCopy.test.ts` and `layerExitCopy.interaction.browser.spec.ts` | A copy with an id, a form name, a form owner, or pointer reach; a copy off the layer's drawn box; a copy outside the top layer; a second copy for one layer |+| INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface |+| INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through |+| INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests; `useBackdropPress.test.tsx`; `outsidePress.test.ts` | A current local channel silently changes ownership or policy |+| INV10 | `LayerProvider.tsx`, `toastHost.tsx`, `LayerProvider.test.tsx`, `toastHost.test.tsx`, `toastHost.lateRegistration.test.tsx`, `useToast.tsx`, `ToastViewport.test.tsx`, `ToastViewport.modalHost.test.tsx`, and `scripts/layer-toast-bundle.test.mjs` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, a default provider renders differently from no provider, a Layer import loads a Toast module, or a toast added before Toast loads is lost |+| INV14, INV15 | Source boundary check over Core for top-layer hosts, exit copies, backdrop elements, lift, and rectangle-morph code outside the runtime and the lift module | A component building its own copy of a mechanism INV14 lists (top-layer mounting, close-request delivery, hold, exit copy, or backdrop element), or re-implementing the lift or the grow |+| INV17 | One runtime suite over every kind of layer root: a `useLayer` layer, inline and portaled, and the Dialog, Drawer, Lightbox, MobileNav, BottomSheetPanel, and ToastViewport content roots, each inside a plain `onClick` wrapper and a Core clickable container; nested layers | A click inside a layer root that reaches an ancestor bubble-phase handler, a caller's wrapper included; an outer layer's handler that receives an inner layer's press; or a document listener or light dismiss that no longer receives it |+| INV18 | `useLayer.test.tsx` (a closed trigger has no anchor-name, and the trigger of a shown or fading layer does) and `TooltipClosedTriggerAnchor.interaction.browser.spec.ts` in Chromium and WebKit | A closed trigger with an anchor-name, a shown or fading layer placed away from its anchor, or a surface around a closed trigger that stops while the main thread is busy |+| INV18 | `useLayer.test.tsx`: a closed state that declares a discrete `display` transition or a keyframe animation keeps the trigger's anchor name until those animations end, read from the closed state's style; a layer whose closed state declares neither is not read for animations at the close | A layer with such a closed-state exit placed away from its anchor while it fades, or an animation read on the close of a layer whose closed state declares no exit |Current unit coverage proves emitted styles, reducers, state transitions, and DOMplacement. Native Popover, `<dialog>`, focus, top-layer ordering, and rendereddiff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.jsonindex b3404db88d..718f71e295 100644--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json@@ -559,7 +559,6 @@"FR6","FR8","FR8",- "FR8","INV12","INV6","spec quote",diff --git a/packages/core/src/Layer/layerSlideRules.ts b/packages/core/src/Layer/layerSlideRules.tsindex 7b7d0c2098..29c28233d7 100644--- a/packages/core/src/Layer/layerSlideRules.ts+++ b/packages/core/src/Layer/layerSlideRules.ts@@ -18,22 +18,26 @@* gutter on both alignment-axis edges, and the clearance facing the anchor* with the gutter on the far edge of the side it lands on.*- * A layer that must never settle over its anchor (spec:AST-059 FR4, Tooltip)- * has a second fallback list, for when its settled box covers its anchor:- * content taller than the room above and below its trigger. `beside` lands on a+ * An above or below layer that must never settle over its anchor+ * (spec:AST-059 FR4, Tooltip) uses one combined fallback list from the start,+ * and no option in it overlaps the anchor. `beside` lands on a* side across the alignment axis, spanning the whole block axis, at the* content's own inline size, so it fits only where the layer fits without* squeezing. `fit` lands above or below sized to the room on that side, so* overflow scrolls inside the layer, and is never smaller than half of the room* the trigger leaves on the block axis, so it fits only on the side with more- * room; the list tries both only after the layer's own position, `beside` and- * the opposite side at the layer's own size, so only content taller than the+ * room; the list tries both only after the layer's own position, the opposite+ * side at the layer's own size and `beside`, so only content taller than the* room on both sides is sized to a room. No option is sized to whatever room* is left: a browser keeps a layer on the option it last used for as long as* that option still fits, so such an option would hold an open layer on a side* shrunk to a sliver after its anchor moved. Chromium applies a position* option's width and height properties but not their min/max forms, so the- * sizes are `inline-size` and `block-size`.+ * sizes are `inline-size` and `block-size`. Inside a scrolling panel, Chromium+ * does not choose an option again while the panel scrolls, and it shifts a box+ * that runs out of room back into the room, onto the anchor. So the layer and+ * every option align `unsafe` toward the anchor on the placement axis: a box+ * that runs out of room overflows away from the anchor instead.** The rules are static — the anchor clearance travels through a custom* property — so one style sheet per document carries all of them. It is@@ -141,6 +145,18 @@ const PLACEMENTS: ReadonlyArray<LayerPlacement> = [];const ALIGNMENTS: ReadonlyArray<LayerAlignment> = ['start', 'center', 'end'];+/**+ * The placement-axis alignment of a layer that keeps its anchor clear, on+ * `side` of its anchor: `unsafe`, toward the anchor, so a box that runs out of+ * room overflows away from the anchor rather than being shifted onto it.+ * `flip-block` swaps it with the side.+ */+export function anchorClearAlignment(side: LayerPlacement): string {+ return side === 'above' || side === 'start'+ ? 'unsafe self-end'+ : 'unsafe self-start';+}+/** The name of the `beside` option that lands on `side`, across the block axis. */export function besideRuleName(side: 'start' | 'end'): string {return `--astryx-layer-beside-${side}`;@@ -158,10 +174,12 @@ export function fitRuleName(side: 'above' | 'below'): string {/*** `beside`: the slide's geometry on an inline side, at the content's own* inline size. A content-sized layer would otherwise wrap to whatever sliver- * of room the trigger leaves and always fit.+ * of room the trigger leaves and always fit. On the block axis it drops the+ * layer's own alignment toward its anchor, so it centres on the trigger and+ * slides into view.*/function besideRule(side: 'start' | 'end'): string {- return `@position-try ${besideRuleName(side)}{position-area:${areaFor(side)};${placementMargins(side)}${alignmentMargins(side)}inline-size:max-content;}`;+ return `@position-try ${besideRuleName(side)}{position-area:${areaFor(side)};${placementMargins(side)}${alignmentMargins(side)}inline-size:max-content;align-self:normal;justify-self:${anchorClearAlignment(side)};}`;}/** The block size of the room on one block side: the area minus its margins. */@@ -193,42 +211,30 @@ function fitRule(side: 'above' | 'below'): string {size('100vh', layerViewportInset.gutterBlockFallback),size('100dvb', layerViewportInset.gutterBlock),);- return `@position-try ${fitRuleName(side)}{position-area:${areaFor(side)};${placementMargins(side)}${alignmentMargins(side)}${blockSize}}`;+ return `@position-try ${fitRuleName(side)}{position-area:${areaFor(side)};${placementMargins(side)}${alignmentMargins(side)}${blockSize}align-self:${anchorClearAlignment(side)};}`;}/**- * The fallback list of a layer that must never settle over its anchor, once- * the standard list has failed it (FR4). After the layer's own position (the- * preferred block side, at its own size): beside the trigger on the inline- * end, then the inline start, then the opposite block side at its own size,- * and only then the preferred block side and the opposite one sized to the- * room there, each only while it is the roomier side. Every option before the- * last two keeps the layer at its own size, so a layer whose content fits- * somewhere is never stretched to a room; the last two are for content taller- * than the room on both sides. Chromium tries no more than five options, so- * this replaces the standard list rather than extending it. Side placements- * already slide along the block axis at full height, so they have none.+ * The one combined fallback list of an above or below layer that must never+ * settle over its anchor (FR4). After the layer's own position (the preferred+ * block side, at its own size): the opposite block side at its own size, then+ * beside the trigger on the inline end, then the inline start, and only then+ * the preferred block side and the opposite one sized to the room there, each+ * only while it is the roomier side. Every option before the last two keeps+ * the layer at its own size, so a layer whose content fits somewhere is never+ * stretched to a room; the last two are for content taller than the room on+ * both sides. Chromium tries no more than five options, so this replaces the+ * standard list rather than extending it. Side placements already slide along+ * the block axis at full height, so they have none.*/export function getAnchorClearFallbacks(placement: LayerPlacement): string {if (placement !== 'above' && placement !== 'below') {return '';}const opposite = placement === 'above' ? 'below' : 'above';- return `${besideRuleName('end')}, ${besideRuleName('start')}, flip-block, ${fitRuleName(placement)}, ${fitRuleName(opposite)}`;+ return `flip-block, ${besideRuleName('end')}, ${besideRuleName('start')}, ${fitRuleName(placement)}, ${fitRuleName(opposite)}`;}-/** The custom property a layer writes its anchor-clear fallback list to. */-export const LAYER_CLEAR_FALLBACKS_PROPERTY = '--_astryx-layer-clear-fallbacks';--/** The custom property its `position-try-fallbacks` reads first. */-export const LAYER_TRY_FALLBACKS_PROPERTY = '--_astryx-layer-try-fallbacks';--/**- * The attribute the runtime sets on a layer whose settled box covered its- * anchor; it switches the layer to its anchor-clear list.- */-export const LAYER_CLEARS_ANCHOR_ATTRIBUTE = 'data-astryx-clears-anchor';-/*** The attribute the runtime sets on a layer that keeps its anchor clear while* its content overflows the box it was given; only then does it scroll, so a@@ -237,12 +243,9 @@ export const LAYER_CLEARS_ANCHOR_ATTRIBUTE = 'data-astryx-clears-anchor';*/export const LAYER_SCROLLS_ATTRIBUTE = 'data-astryx-layer-scrolls';-/**- * Switches a layer that set the attribute to its anchor-clear list, and lets- * a layer whose content overflows scroll it.- */-function clearSwitchCss(): string {- return `[${LAYER_CLEARS_ANCHOR_ATTRIBUTE}]{${LAYER_TRY_FALLBACKS_PROPERTY}:var(${LAYER_CLEAR_FALLBACKS_PROPERTY});}[${LAYER_SCROLLS_ATTRIBUTE}]{overflow-y:auto;overscroll-behavior-block:contain;}`;+/** Lets a layer whose content overflows scroll it. */+function scrollsCss(): string {+ return `[${LAYER_SCROLLS_ATTRIBUTE}]{overflow-y:auto;overscroll-behavior-block:contain;}`;}/**@@ -261,7 +264,7 @@ export function slideRulesCss(): string {besideRule('start'),fitRule('above'),fitRule('below'),- clearSwitchCss(),+ scrollsCss(),].join('');}diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsxindex 2f6611bff6..73383d6c5e 100644--- a/packages/core/src/Layer/useLayer.test.tsx+++ b/packages/core/src/Layer/useLayer.test.tsx@@ -9,7 +9,7 @@* SYNC: When useLayer.tsx changes, update tests accordingly*/-import {describe, it, expect, vi, afterEach} from 'vitest';+import {describe, it, expect, vi, afterEach, beforeEach} from 'vitest';import {render,renderHook,@@ -29,6 +29,7 @@ import {getPositionTryFallbacks,getSelfAlignment,} from './useLayer';+import {preserveAnimations} from './preserveAnimations';import {getAnchorClearFallbacks} from './layerSlideRules';import {typeScaleVars} from '../theme/tokens.stylex';import type {@@ -41,6 +42,12 @@ import type {import {useMergedRefs} from '../hooks/useMergedRefs';import {observeBrowserHide} from './popoverOperations';+vi.mock('./preserveAnimations', async importOriginal => {+ const actual: {preserveAnimations: typeof preserveAnimations} =+ await importOriginal();+ return {...actual, preserveAnimations: vi.fn(actual.preserveAnimations)};+});+function mockCSSStyleDeclaration(styles: Partial<CSSStyleDeclaration>,): CSSStyleDeclaration {@@ -3116,16 +3123,26 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {.mockReturnValue(720);}+ /**+ * How many times a layer was placed afresh since the last clear: the+ * runtime keeps every animation through `preserveAnimations` only then.+ */+ const placedAfresh = () => vi.mocked(preserveAnimations).mock.calls.length;++ beforeEach(() => {+ vi.mocked(preserveAnimations).mockClear();+ });+afterEach(() => {vi.restoreAllMocks();});- it('lists beside the trigger, then the other block side at its own size, and only then each block side sized to its room', () => {+ it('lists the other block side at its own size, then beside the trigger, and only then each block side sized to its room', () => {expect(getAnchorClearFallbacks('above')).toBe(- '--astryx-layer-beside-end, --astryx-layer-beside-start, flip-block, --astryx-layer-fit-above, --astryx-layer-fit-below',+ 'flip-block, --astryx-layer-beside-end, --astryx-layer-beside-start, --astryx-layer-fit-above, --astryx-layer-fit-below',);expect(getAnchorClearFallbacks('below')).toBe(- '--astryx-layer-beside-end, --astryx-layer-beside-start, flip-block, --astryx-layer-fit-below, --astryx-layer-fit-above',+ 'flip-block, --astryx-layer-beside-end, --astryx-layer-beside-start, --astryx-layer-fit-below, --astryx-layer-fit-above',);// Side placements already slide along the block axis at full height.expect(getAnchorClearFallbacks('start')).toBe('');@@ -3138,7 +3155,7 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {}});- it('installs the beside and fit rules and the switch to the clear list', async () => {+ it('installs the beside and fit rules, each aligned unsafe toward the anchor', async () => {const user = userEvent.setup();const {container} = render(<ClearHarness />);await user.click(container.querySelector('button')!);@@ -3150,7 +3167,7 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {'@position-try --astryx-layer-beside-end{position-area:self-inline-end span-all;margin-inline-start:var(--_astryx-layer-clearance, 0px);',);expect(css).toMatch(- /@position-try --astryx-layer-beside-start\{[^}]*inline-size:max-content;\}/,+ /@position-try --astryx-layer-beside-start\{[^}]*inline-size:max-content;/,);// Fit: sized to the room on its side and never less than half of the// room the trigger leaves on the block axis, so it fits only on the@@ -3168,34 +3185,55 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {}expect(css).not.toMatch(/--astryx-layer-fit-[a-z]+-roomier/);expect(css.match(/@position-try --astryx-layer-fit-/g)).toHaveLength(2);- expect(css).toContain(- '[data-astryx-clears-anchor]{--_astryx-layer-try-fallbacks:var(--_astryx-layer-clear-fallbacks);}',+ // Every option aligns unsafe toward the anchor on the placement axis, so+ // a box that runs out of room overflows away from the anchor.+ expect(css).toMatch(+ /@position-try --astryx-layer-beside-end\{[^}]*align-self:normal;justify-self:unsafe self-start;\}/,+ );+ expect(css).toMatch(+ /@position-try --astryx-layer-beside-start\{[^}]*justify-self:unsafe self-end;\}/,+ );+ expect(css).toMatch(+ /@position-try --astryx-layer-fit-above\{[^}]*align-self:unsafe self-end;\}/,);+ expect(css).toMatch(+ /@position-try --astryx-layer-fit-below\{[^}]*align-self:unsafe self-start;\}/,+ );+ // One list: no switch to a second one.+ expect(css).not.toContain('clears-anchor');});- it('carries the clear list beside the standard one, which it uses until the switch', async () => {+ it('uses its one combined list from the start, aligned unsafe toward its trigger', async () => {const user = userEvent.setup();- const {container} = render(<ClearHarness placement="below" />);+ const {container, rerender} = render(<ClearHarness placement="below" />);await user.click(container.querySelector('button')!);const layerEl = container.querySelector('[popover]') as HTMLElement;expect(layerEl.style.positionTryFallbacks).toBe(- `var(--_astryx-layer-try-fallbacks, ${getPositionTryFallbacks('below', 'center')})`,+ getAnchorClearFallbacks('below'),);- expect(- layerEl.style.getPropertyValue('--_astryx-layer-clear-fallbacks'),- ).toBe(getAnchorClearFallbacks('below'));+ expect(layerEl.style.alignSelf).toBe('unsafe self-start');+ rerender(<ClearHarness placement="above" />);+ expect(layerEl.style.positionTryFallbacks).toBe(+ getAnchorClearFallbacks('above'),+ );+ expect(layerEl.style.alignSelf).toBe('unsafe self-end');+ // A side placement keeps the standard list.+ rerender(<ClearHarness placement="end" />);+ expect(layerEl.style.positionTryFallbacks).toBe(+ getPositionTryFallbacks('end', 'center'),+ );+ expect(layerEl.style.alignSelf).toBe('');});- it('switches to the clear list when the shown layer covers its trigger', async () => {+ it('places the shown layer afresh from its list when it covers its trigger', async () => {const user = userEvent.setup();placeBoxes(TRIGGER, rect(16, 350, 688, 300));const {container} = render(<ClearHarness />);await user.click(container.querySelector('button')!);- const layerEl = container.querySelector('[popover]') as HTMLElement;- expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBeGreaterThan(0);});- it('places a layer afresh from the clear list when it switches, without closing it or leaving a frame', async () => {+ it('places a layer afresh without closing it or leaving a frame', async () => {const user = userEvent.setup();const onToggle = vi.fn();const displays: string[] = [];@@ -3213,9 +3251,9 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {layerEl.addEventListener('toggle', onToggle);layerEl.addEventListener('beforetoggle', onToggle);await user.click(container.querySelector('button')!);- expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBeGreaterThan(0);// 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+ // stops being rendered: the runtime 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');@@ -3240,7 +3278,7 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {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 () => {+ it('places the shown layer afresh when it 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// WebKit leaves a box that fits no option.@@ -3248,19 +3286,17 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {placeBoxes(TRIGGER, rect(-348, 350, 640, 300));const {container} = render(<ClearHarness />);await user.click(container.querySelector('button')!);- const layerEl = container.querySelector('[popover]') as HTMLElement;- expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBeGreaterThan(0);});- it('keeps the standard list for a layer past the viewport while its trigger is out of view too', async () => {+ it('leaves a layer past the viewport alone while its trigger is out of view too', async () => {const user = userEvent.setup();- // The trigger is above the viewport: the layer holds (FR5), not switches.+ // The trigger is above the viewport: the layer holds (FR5).viewport720();placeBoxes(rect(-80, 400, 30, 100), rect(-200, 350, 100, 200));const {container} = render(<ClearHarness />);await user.click(container.querySelector('button')!);- const layerEl = container.querySelector('[popover]') as HTMLElement;- expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBe(0);});it('does not read on scroll events, when the layer has not followed its anchor yet', async () => {@@ -3269,7 +3305,6 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {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.@@ -3279,32 +3314,171 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {window.dispatchEvent(new Event('scroll'));document.dispatchEvent(new Event('scroll'));});- expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBe(0);+ });++ /** Let the task queued after a frame's paint run, then the next frame. */+ async function afterNextPaint() {+ await nextFrame();+ await act(+ async () =>+ new Promise<void>(resolve => {+ setTimeout(resolve);+ }),+ );+ await nextFrame();+ }++ async function wait(ms: number) {+ await act(+ async () =>+ new Promise<void>(resolve => {+ setTimeout(resolve, ms);+ }),+ );+ }++ it('checks the box once, in the first frame painted after a scroll of its trigger ends, with no read in the scroll handler', async () => {+ const view = window as {onscrollend?: unknown};+ view.onscrollend = null;+ try {+ const user = userEvent.setup();+ viewport720();+ const shown = placeBoxes(TRIGGER, rect(200, 350, 100, 200));+ const {container} = render(<ClearHarness />);+ await user.click(container.querySelector('button')!);+ shown.mockRestore();+ // The scroll carried the trigger to the top: the layer above it now+ // runs past the viewport.+ const reads = placeBoxes(rect(12, 380, 30, 100), rect(-40, 350, 48, 200));+ vi.mocked(preserveAnimations).mockClear();+ // A scroll that does not carry the trigger is not its scroll.+ const other = document.createElement('div');+ document.body.append(other);+ act(() => {+ other.dispatchEvent(new Event('scrollend'));+ });+ await afterNextPaint();+ expect(placedAfresh()).toBe(0);+ reads.mockClear();+ act(() => {+ document.dispatchEvent(new Event('scrollend'));+ });+ expect(reads).not.toHaveBeenCalled();+ await nextFrame();+ expect(placedAfresh()).toBe(0);+ await afterNextPaint();+ expect(placedAfresh()).toBe(1);+ other.remove();+ } finally {+ delete view.onscrollend;+ }+ });++ it('cancels the check when a scroll of its trigger starts again before it, where the browser fires scrollend', async () => {+ const view = window as {onscrollend?: unknown};+ view.onscrollend = null;+ try {+ const user = userEvent.setup();+ viewport720();+ const shown = placeBoxes(TRIGGER, rect(200, 350, 100, 200));+ const {container} = render(<ClearHarness />);+ await user.click(container.querySelector('button')!);+ shown.mockRestore();+ placeBoxes(rect(12, 380, 30, 100), rect(-40, 350, 48, 200));+ vi.mocked(preserveAnimations).mockClear();+ act(() => {+ document.dispatchEvent(new Event('scrollend'));+ });+ await nextFrame();+ act(() => {+ document.dispatchEvent(new Event('scroll'));+ });+ await afterNextPaint();+ expect(placedAfresh()).toBe(0);+ } finally {+ delete view.onscrollend;+ }+ });++ it('hears a scroll that stops inside a shadow root above its trigger', async () => {+ const view = window as {onscrollend?: unknown};+ view.onscrollend = null;+ const host = document.createElement('div');+ document.body.append(host);+ const shadowRoot = host.attachShadow({mode: 'open'});+ const scroller = document.createElement('div');+ shadowRoot.append(scroller);+ try {+ const user = userEvent.setup();+ viewport720();+ const shown = placeBoxes(TRIGGER, rect(200, 350, 100, 200));+ render(<ClearHarness />, {container: scroller});+ await user.click(scroller.querySelector('button')!);+ shown.mockRestore();+ placeBoxes(rect(12, 380, 30, 100), rect(-40, 350, 48, 200));+ vi.mocked(preserveAnimations).mockClear();+ // Not composed: the event stops at the shadow root.+ act(() => {+ scroller.dispatchEvent(new Event('scrollend'));+ });+ await afterNextPaint();+ expect(placedAfresh()).toBe(1);+ } finally {+ delete view.onscrollend;+ host.remove();+ }+ });++ it('checks the box once, 150 ms after the last scroll of its trigger, where the browser fires no scrollend', async () => {+ expect('onscrollend' in window).toBe(false);+ const user = userEvent.setup();+ viewport720();+ const shown = placeBoxes(TRIGGER, rect(200, 350, 100, 200));+ const {container} = render(<ClearHarness />);+ await user.click(container.querySelector('button')!);+ shown.mockRestore();+ const reads = placeBoxes(rect(12, 380, 30, 100), rect(-40, 350, 48, 200));+ vi.mocked(preserveAnimations).mockClear();+ reads.mockClear();+ act(() => {+ document.dispatchEvent(new Event('scroll'));+ });+ await wait(100);+ // Still scrolling: each scroll event starts the wait again.+ act(() => {+ document.dispatchEvent(new Event('scroll'));+ });+ await wait(100);+ expect(reads).not.toHaveBeenCalled();+ expect(placedAfresh()).toBe(0);+ await wait(80);+ await afterNextPaint();+ expect(placedAfresh()).toBe(1);});- it('keeps the standard list when the shown layer sits clear of its trigger, even flush against it', async () => {+ it('leaves the shown layer alone when it 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.placeBoxes(TRIGGER, rect(200, 350, 100, 200));const {container} = render(<ClearHarness />);await user.click(container.querySelector('button')!);- const layerEl = container.querySelector('[popover]') as HTMLElement;- expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBe(0);});- it('starts every show from the standard list', async () => {+ it('judges every show afresh', async () => {const user = userEvent.setup();const spy = placeBoxes(TRIGGER, rect(16, 350, 688, 300));- const {container, getByText} = render(<ClearHarness />);+ const {getByText} = render(<ClearHarness />);await user.click(getByText('Trigger'));- const layerEl = container.querySelector('[popover]') as HTMLElement;- expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBeGreaterThan(0);await user.click(getByText('Hide'));spy.mockRestore();placeBoxes(TRIGGER, rect(200, 350, 100, 200));+ vi.mocked(preserveAnimations).mockClear();await user.click(getByText('Trigger'));- expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBe(0);});it('scrolls only while its content overflows the box it was given', async () => {@@ -3353,7 +3527,7 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {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');+ expect(placedAfresh()).toBe(0);expect(observed).toContain(layerEl);expect(observed).toContain(layerEl.firstElementChild);expect(observed).toContain(getByText('Trigger'));@@ -3366,11 +3540,11 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {callback();}});- expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBeGreaterThan(0);vi.unstubAllGlobals();});- it('re-reads its geometry when its trigger moves in layout without resizing', async () => {+ it('follows a trigger that moves in layout without resizing, and leaves its placement to the engine', async () => {const observers: {callback: (entries: IntersectionObserverEntry[]) => void;options: IntersectionObserverInit;@@ -3396,10 +3570,9 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {);const user = userEvent.setup();const spy = placeBoxes(TRIGGER, rect(200, 350, 100, 200));- const {container, getByText} = render(<ClearHarness />);+ const {getByText} = render(<ClearHarness />);await user.click(getByText('Trigger'));- const layerEl = container.querySelector('[popover]') as HTMLElement;- expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBe(0);// 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);@@ -3409,18 +3582,19 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {// Its initial report: fully inside its own rect.act(() => move?.callback([report(move.options, TRIGGER, 1)]));- expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBe(0);- // The trigger moves; the standard list now settles over it.+ // The trigger moves, and the layer now reads as covering it.spy.mockRestore();placeBoxes(TRIGGER, rect(16, 350, 688, 300));const before = observers.length;act(() => move?.callback([report(move.options, TRIGGER, 0.4)]));- // Re-armed on the new rect at once; read in the next frame.+ // Re-armed on the new rect at once.expect(move?.disconnected).toBe(true);expect(observers.length).toBe(before + 1);+ // A move never places the layer afresh: CSS anchor positioning places it.await nextFrame();- expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBe(0);vi.unstubAllGlobals();});@@ -3492,12 +3666,9 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {vi.unstubAllGlobals();});- it('reads a move its observer reports after paint in the next frame, before that frame paints, never in the reporting task', async () => {- // Placing a layer afresh in the task right after the frame that scrolled- // its anchor lets Chromium lay it out for one more frame against the- // anchor's position before the scroll, over the anchor (spec:AST-059 FR8:- // clear from the second painted frame). The read waits for the next- // frame, before it paints, and several reports in one frame share it.+ it('handles a move its observer reports in the next frame, never in the reporting task, and never checks the box or places the layer afresh', async () => {+ // During a scroll, CSS anchor positioning alone places the layer+ // (spec:AST-059 FR4). Several reports in one frame share one call.const observers: {callback: (entries: IntersectionObserverEntry[]) => void;options: IntersectionObserverInit;@@ -3528,7 +3699,7 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {move?.callback([report(move.options, TRIGGER, 1)]);});await nextFrame();- expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBe(0);// A scroll carries the trigger under the layer; the observer reports it// after the frame that painted the move, twice before the next frame.@@ -3550,13 +3721,24 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {const second = latestMove();second?.callback([report(second.options, TRIGGER, 0.6)]);});- expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBe(0);expect(reads).not.toHaveBeenCalled();- // The next frame reads it once, switches it, and places it afresh.+ // The next frame neither reads the layer's box nor places it afresh, so+ // the layer does not jump to another side mid-scroll.await nextFrame();- expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');- expect(reads).toHaveBeenCalled();+ expect(reads).not.toHaveBeenCalled();+ expect(placedAfresh()).toBe(0);+ expect(layerEl.style.display).not.toBe('none');++ // A later move does neither either.+ act(() => {+ const move = latestMove();+ move?.callback([report(move.options, TRIGGER, 0.5)]);+ });+ await nextFrame();+ expect(reads).not.toHaveBeenCalled();+ expect(placedAfresh()).toBe(0);vi.unstubAllGlobals();});@@ -3596,14 +3778,13 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {const latest = () => moves()[moves().length - 1];const user = userEvent.setup();let spy = placeBoxes(TRIGGER, rect(200, 350, 100, 200));- const {container, getByText} = render(<ClearHarness />);+ const {getByText} = render(<ClearHarness />);await user.click(getByText('Trigger'));- const layerEl = container.querySelector('[popover]') as HTMLElement;- expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBe(0);// 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.+ // move: it re-arms at the reported ratio, and leaves placement to CSS.spy.mockRestore();spy = placeBoxes(TRIGGER, rect(16, 350, 688, 300));let armed = moves().length;@@ -3611,7 +3792,7 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {expect(moves().length).toBe(armed + 1);expect(latest().options.threshold).toBe(0.7);await nextFrame();- expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBe(0);// A first report of 0 for a trigger that moved since the observer read// its rectangle re-arms at once on the new rectangle.@@ -3749,12 +3930,11 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {);fireEvent.click(getByRole('button', {name: 'Trigger'}));await waitFor(() => {- expect(container.querySelector('[popover]')).toHaveAttribute(- 'data-astryx-clears-anchor',- );+ expect(placedAfresh()).toBeGreaterThan(0);});const first = container.querySelector('[popover]');+ vi.mocked(preserveAnimations).mockClear();rerender(<MovingClearHarness unsafe={false} />);await waitFor(() => {@@ -3764,7 +3944,7 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {container.querySelector('[data-testid="safe-host"]'),);expect(layer).toHaveAttribute('data-open', 'true');- expect(layer).toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBeGreaterThan(0);});});@@ -3774,12 +3954,10 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {const {container} = render(<ContextLayerHarness />);await user.click(container.querySelector('button')!);const layerEl = container.querySelector('[popover]') as HTMLElement;- expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');+ expect(placedAfresh()).toBe(0);expect(layerEl.style.positionTryFallbacks).toBe(getPositionTryFallbacks('above', 'center'),);- expect(- layerEl.style.getPropertyValue('--_astryx-layer-clear-fallbacks'),- ).toBe('');+ expect(layerEl.style.alignSelf).toBe('');});});diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex 596c2672f3..10b60e9757 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -42,11 +42,9 @@ import {settledBox} from './settledBox';import {layerInsetProperties} from './layerInset';import {LAYER_CLEARANCE_PROPERTY,- LAYER_CLEARS_ANCHOR_ATTRIBUTE,LAYER_SCROLLS_ATTRIBUTE,- LAYER_CLEAR_FALLBACKS_PROPERTY,- LAYER_TRY_FALLBACKS_PROPERTY,ensureSlideRules,+ anchorClearAlignment,getAnchorClearFallbacks,slideRuleName,} from './layerSlideRules';@@ -61,6 +59,9 @@ import {preserveAnimations} from './preserveAnimations';import {useLayerContext} from './LayerContext';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import {overlayPaddingReset} from '../Layout/overlayPaddingReset.stylex';+import {containsAlongFlatTree, parentAcrossShadow} from '../utils/flatTree';+import {isShadowRoot} from '../utils/nodeType';+import {subscribeInput} from '../utils/inputStream';const styles = stylex.create({// The software keyboard's block-size cap, on the layer's own element. Every@@ -589,37 +590,29 @@ function failsAnchor(layer: HTMLElement, anchor: HTMLElement): boolean {}/**- * For a layer that must never settle over its anchor (spec:AST-059 FR4): read- * where its fallback list settled it and, if its box covers the anchor or,- * while the anchor is in view, leaves the viewport on the block axis, switch it- * to its anchor-clear list; then let it scroll only if its content overflows- * the box it was given (FR3). Engines differ in where they leave a box that- * fits no option: Chromium shifts it into the viewport, over the anchor; WebKit- * keeps it at its preferred position, partly off-screen. Either way the- * 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. A same-size anchor that moves on- * screen, in layout or because something scrolled, is reported after paint by- * the anchor-move observer and read in the next frame, before it paints (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.+ * For a layer that must never settle over its anchor (spec:AST-059 FR4). Every+ * option of its one combined fallback list keeps it clear of its anchor, and+ * the engine picks one. Where the box still covers the anchor or, while the+ * anchor is in view, leaves the viewport on the block axis, the layer is+ * placed afresh (`placeAfresh`) from that list. Then it scrolls only if its+ * content overflows the box it was given (FR3). 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. It also runs once+ * in the first frame painted after a scroll of the anchor stops+ * (`observeScrollStop`), because during a scroll the browser does not choose+ * an option again. A same-size anchor that moves on screen, in layout or+ * because something scrolled, is reported after paint by the anchor-move+ * observer. That call does not check the box and never places the layer+ * afresh, so the layer never jumps to another side mid-scroll.*/-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);- }+function keepAnchorClear(+ layer: HTMLElement,+ anchor: HTMLElement | null,+ cause: 'change' | 'move' = 'change',+): void {+ if (cause === 'change' && anchor && 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.@@ -795,21 +788,132 @@ function observeMove(element: HTMLElement, onMove: () => void): () => void {return stop;}+/**+ * How long a scroll must stay still, in ms, to count as stopped where the+ * browser does not fire `scrollend`.+ */+const SCROLL_STILL_MS = 150;++/**+ * The shadow roots along `node`'s flat-tree path. `scroll` and `scrollend`+ * are not composed, so a scroll inside a shadow tree reaches its shadow root+ * but not the window.+ */+function shadowRootsAbove(node: Node): ShadowRoot[] {+ const roots: ShadowRoot[] = [];+ for (+ let current: Node | null = node;+ current;+ current = parentAcrossShadow(current)+ ) {+ const root = current.getRootNode();+ if (isShadowRoot(root) && !roots.includes(root)) {+ roots.push(root);+ }+ }+ return roots;+}++/**+ * Calls `onStop` once each time a scroll of the page or of an ancestor of+ * `anchor` stops, in the first frame painted after it stops. During a scroll,+ * Chromium does not choose a layer's position option again, so the layer is+ * checked once the scroll stops. A scroll stops at `scrollend`; where the+ * browser does not fire it, a scroll stops after `SCROLL_STILL_MS` with no+ * `scroll` event. A scroll that starts again before the check cancels it. No+ * handler reads layout.+ */+function observeScrollStop(+ view: Window,+ anchor: HTMLElement,+ onStop: () => void,+): () => void {+ let frame: number | null = null;+ let timer: number | null = null;+ const cancel = () => {+ if (frame !== null) {+ view.cancelAnimationFrame(frame);+ frame = null;+ }+ if (timer !== null) {+ view.clearTimeout(timer);+ timer = null;+ }+ };+ // At `scrollend`, and in the frame after it, Chromium still reads the+ // anchored layer at its position before the scroll. After one painted+ // frame it reads the position the scroll gave it.+ const callAfterNextPaint = () => {+ cancel();+ frame = view.requestAnimationFrame(() => {+ frame = null;+ timer = view.setTimeout(() => {+ timer = null;+ frame = view.requestAnimationFrame(() => {+ frame = null;+ onStop();+ });+ });+ });+ };+ const firesScrollEnd =+ (view as {onscrollend?: unknown}).onscrollend !== undefined;+ const isAnchorScroll = (event: Event) =>+ containsAlongFlatTree(event.target as Node, anchor);+ const onScroll = (event: Event) => {+ if (!isAnchorScroll(event)) {+ return;+ }+ cancel();+ if (!firesScrollEnd) {+ timer = view.setTimeout(() => {+ timer = null;+ callAfterNextPaint();+ }, SCROLL_STILL_MS);+ }+ };+ const onScrollEnd = (event: Event) => {+ if (isAnchorScroll(event)) {+ callAfterNextPaint();+ }+ };+ const unsubscribes = [subscribeInput(view, 'scroll', onScroll)];+ if (firesScrollEnd) {+ unsubscribes.push(subscribeInput(view, 'scrollend', onScrollEnd));+ }+ const listening = {capture: true, passive: true};+ const shadowRoots = shadowRootsAbove(anchor);+ for (const shadowRoot of shadowRoots) {+ shadowRoot.addEventListener('scroll', onScroll, listening);+ if (firesScrollEnd) {+ shadowRoot.addEventListener('scrollend', onScrollEnd, listening);+ }+ }+ return () => {+ for (const unsubscribe of unsubscribes) {+ unsubscribe();+ }+ for (const shadowRoot of shadowRoots) {+ shadowRoot.removeEventListener('scroll', onScroll, listening);+ shadowRoot.removeEventListener('scrollend', onScrollEnd, listening);+ }+ cancel();+ };+}+/*** 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, before paint), the viewport resizing (before- * paint), and the anchor moving on screen without resizing, in layout or by a- * scroll (`observeMove`, reported after paint). Each calls `keepAnchorClear`- * for this layer and anchor while `isCurrent` says they are still the live- * pair. A move is read in the next animation frame, not in the task that- * reports it: placing the layer afresh there, right after the frame that- * scrolled its anchor, lets Chromium lay it out for one more frame against- * the anchor's position before the scroll, over the anchor, so the second- * painted frame would still cover it. Read in the next frame, before it- * paints, the fresh placement uses the moved anchor. Reports in one frame- * share one read. Returns the function that removes every observer and+ * paint), a scroll of the anchor stopping (`observeScrollStop`, in the first+ * frame painted after it), and the anchor moving on screen without resizing,+ * in layout or by a scroll (`observeMove`, reported after paint). Each calls+ * `keepAnchorClear` for this layer and anchor while `isCurrent` says they+ * are still the live pair. A move is handled in the next animation frame, not+ * in the task that reports it, and only updates whether the layer scrolls: it+ * never checks the box and never places the layer afresh. Reports in one+ * frame share one call. Returns the function that removes every observer and* listener it added.*/function observeAnchorClearance(@@ -821,14 +925,15 @@ function observeAnchorClearance(if (!view) {return () => {};}- const reread = () => {+ const reread = (cause: 'change' | 'move' = 'change') => {if (isCurrent()) {- keepAnchorClear(layer, anchor);+ keepAnchorClear(layer, anchor, cause);}};+ const rereadAfterChange = () => reread('change');let observer: ResizeObserver | null = null;if (typeof ResizeObserver !== 'undefined') {- observer = new ResizeObserver(reread);+ observer = new ResizeObserver(rereadAfterChange);observer.observe(layer);for (const child of Array.from(layer.children)) {observer.observe(child);@@ -842,18 +947,24 @@ function observeAnchorClearance(}moveFrame = view.requestAnimationFrame(() => {moveFrame = null;- reread();+ reread('move');});});- view.addEventListener('resize', reread);+ view.addEventListener('resize', rereadAfterChange);+ const stopObservingScrollStop = observeScrollStop(+ view,+ anchor,+ rereadAfterChange,+ );return () => {observer?.disconnect();stopObservingMove();+ stopObservingScrollStop();if (moveFrame !== null) {view.cancelAnimationFrame(moveFrame);moveFrame = null;}- view.removeEventListener('resize', reread);+ view.removeEventListener('resize', rereadAfterChange);};}@@ -1472,7 +1583,6 @@ function useLayerImplementation(// before the writes of the show, so the read lays nothing out.const closeTransitionHolds = closeTransitionKeepsShown(popover);const closedAnimations = animationNames(popover);- popover.removeAttribute(LAYER_CLEARS_ANCHOR_ATTRIBUTE);popover.removeAttribute(LAYER_SCROLLS_ATTRIBUTE);applyDeferredWritingContext(popover);// The trigger takes the layer's anchor name in the task that shows the@@ -1947,15 +2057,12 @@ function useLayerImplementation(// CSS anchor positioning (dynamic, not in StyleX)const standardFallbacks = getPositionTryFallbacks(placement, alignment);- // A layer that keeps its anchor clear carries a second list; `show()`- // switches to it when the standard list settles over the anchor (FR4).+ // An above or below layer that keeps its anchor clear uses one combined+ // list whose options never overlap the anchor (FR4).const clearFallbacks =keepsAnchorClear && positioning === 'anchor'? getAnchorClearFallbacks(placement): '';- const clearFallbacksProperty: Record<string, string> = clearFallbacks- ? {[LAYER_CLEAR_FALLBACKS_PROPERTY]: clearFallbacks}- : {};const anchorStyle: React.CSSProperties =positioning === 'custom'? // Consumer authors its own position styles via `style` — keep@@ -1964,9 +2071,10 @@ function useLayerImplementation(: {positionAnchor: anchorId,positionArea: getPositionArea(placement, alignment),- positionTryFallbacks: clearFallbacks- ? `var(${LAYER_TRY_FALLBACKS_PROPERTY}, ${standardFallbacks})`- : standardFallbacks,+ positionTryFallbacks: clearFallbacks || standardFallbacks,+ ...(clearFallbacks+ ? {alignSelf: anchorClearAlignment(placement)}+ : {}),...getSelfAlignment(placement, alignment, isAnchorInView),};@@ -2040,7 +2148,6 @@ function useLayerImplementation(...anchorStyle,...keyboardLiftStyle(keyboardLift),...clearanceProperty,- ...clearFallbacksProperty,...layerInsetProperties(declaredInset),...mount.portalStyle,...extraStyle,diff --git a/packages/core/src/Tooltip/Tooltip.test.tsx b/packages/core/src/Tooltip/Tooltip.test.tsxindex 074fee8d8c..bdae9653f3 100644--- a/packages/core/src/Tooltip/Tooltip.test.tsx+++ b/packages/core/src/Tooltip/Tooltip.test.tsx@@ -120,7 +120,7 @@ describe('Tooltip', () => {});describe('content taller than the room above and below (spec:AST-059 FR4)', () => {- it('carries the anchor-clear fallback list, so it never settles over its trigger', async () => {+ it('carries its one combined fallback list from the start, so it never settles over its trigger', async () => {render(<Tooltip content="Tall tooltip" isDefaultOpen placement="below"><button type="button">Trigger</button>@@ -131,13 +131,8 @@ describe('Tooltip', () => {expect(el).not.toBeNull();return el;});- expect(tooltip.style.positionTryFallbacks).toMatch(- /^var\(--_astryx-layer-try-fallbacks, /,- );- expect(- tooltip.style.getPropertyValue('--_astryx-layer-clear-fallbacks'),- ).toBe(- '--astryx-layer-beside-end, --astryx-layer-beside-start, flip-block, --astryx-layer-fit-below, --astryx-layer-fit-above',+ expect(tooltip.style.positionTryFallbacks).toBe(+ 'flip-block, --astryx-layer-beside-end, --astryx-layer-beside-start, --astryx-layer-fit-below, --astryx-layer-fit-above',);});});diff --git a/packages/core/src/Tooltip/__tests__/TooltipTallContent.a11y.browser.spec.ts b/packages/core/src/Tooltip/__tests__/TooltipTallContent.a11y.browser.spec.tsindex 3d6a110acd..8231b7c9f8 100644--- a/packages/core/src/Tooltip/__tests__/TooltipTallContent.a11y.browser.spec.ts+++ b/packages/core/src/Tooltip/__tests__/TooltipTallContent.a11y.browser.spec.ts@@ -201,13 +201,20 @@ async function openReplacedTrigger(page: Page): Promise<number> {await expect(first).toBeVisible();await expect(page.getByRole('tooltip')).toBeVisible();await page.waitForTimeout(200);- // It opened above the first trigger, on its standard list.+ // It opened above the first trigger, where its own position puts it.expect(await page.evaluate(sel => {- const el = document.querySelector(sel);- return el?.hasAttribute('data-astryx-clears-anchor');+ const tip = (+ document.querySelector(sel) as HTMLElement+ ).getBoundingClientRect();+ const trigger = (+ Array.from(document.querySelectorAll('button')).find(+ button => button.textContent === 'Trigger 1',+ ) as HTMLElement+ ).getBoundingClientRect();+ return tip.bottom <= trigger.top;}, TOOLTIP),- ).toBe(false);+ ).toBe(true);await page.getByRole('button', {name: 'Replace the trigger'}).click();const second = page.getByRole('button', {name: 'Trigger 2'});await expect(second).toBeVisible();@@ -354,13 +361,7 @@ test('desktop, with motion allowed: a tall tooltip opens beside its trigger, andawait page.waitForTimeout(500);const s = await expectStillAndClear(page, trigger, viewport);expect(s.left >= trigger.right || s.right <= trigger.left).toBe(true);- expect(- await page.evaluate(- sel =>- document.querySelector(sel)?.hasAttribute('data-astryx-clears-anchor'),- TOOLTIP,- ),- ).toBe(true);+ expect(await sitsBesideTrigger(page)).toBe(true);});test('phone: with no room beside, it opens below when below has more room', async ({@@ -640,11 +641,24 @@ test('a held-open tooltip keeps a replaced trigger clear when the replacement reexpect(overlaps(await rect(page, TOOLTIP), after)).toBe(false);});-async function hasSwitched(page: Page): Promise<boolean | undefined> {+/**+ * Whether the tooltip sits beside its trigger on the inline axis: level with+ * it, and clear of it to its inline start or end.+ */+async function sitsBesideTrigger(page: Page): Promise<boolean> {return page.evaluate(- sel =>- document.querySelector(sel)?.hasAttribute('data-astryx-clears-anchor'),- TOOLTIP,+ ([tip, sel]) => {+ const l = (+ document.querySelector(tip) as HTMLElement+ ).getBoundingClientRect();+ const a = (+ document.querySelector(sel) as HTMLElement+ ).getBoundingClientRect();+ const level = l.top < a.bottom && a.top < l.bottom;+ const clear = l.right <= a.left || l.left >= a.right;+ return level && clear;+ },+ [TOOLTIP, TRIGGER],);}@@ -669,7 +683,7 @@ test('with motion allowed, a tooltip that fits does not switch at open, and fittawait page.mouse.move((t.left + t.right) / 2, (t.top + t.bottom) / 2);await expect(page.getByRole('tooltip')).toBeVisible();await page.waitForTimeout(400);- expect(await hasSwitched(page)).toBe(false);+ expect(await sitsBesideTrigger(page)).toBe(false);const open = await rect(page, TOOLTIP);expect(open.bottom).toBeLessThanOrEqual(t.top);// Grown to about 290px, which fits below (464px of room) but not above:@@ -683,7 +697,7 @@ test('with motion allowed, a tooltip that fits does not switch at open, and fitt}}, TOOLTIP);await page.waitForTimeout(400);- expect(await hasSwitched(page)).toBe(false);+ expect(await sitsBesideTrigger(page)).toBe(false);const grown = await rect(page, TOOLTIP);const metrics = await page.evaluate(sel => {const el = document.querySelector(sel) as HTMLElement;diff --git a/packages/core/src/Tooltip/__tests__/TooltipTallContentTracking.a11y.browser.spec.ts b/packages/core/src/Tooltip/__tests__/TooltipTallContentTracking.a11y.browser.spec.tsindex af89b9c1c5..0ebd3996d2 100644--- a/packages/core/src/Tooltip/__tests__/TooltipTallContentTracking.a11y.browser.spec.ts+++ b/packages/core/src/Tooltip/__tests__/TooltipTallContentTracking.a11y.browser.spec.ts@@ -167,13 +167,20 @@ async function openReplacedTrigger(page: Page): Promise<number> {await expect(first).toBeVisible();await expect(page.getByRole('tooltip')).toBeVisible();await page.waitForTimeout(200);- // It opened above the first trigger, on its standard list.+ // It opened above the first trigger, where its own position puts it.expect(await page.evaluate(sel => {- const el = document.querySelector(sel);- return el?.hasAttribute('data-astryx-clears-anchor');+ const tip = (+ document.querySelector(sel) as HTMLElement+ ).getBoundingClientRect();+ const trigger = (+ Array.from(document.querySelectorAll('button')).find(+ button => button.textContent === 'Trigger 1',+ ) as HTMLElement+ ).getBoundingClientRect();+ return tip.bottom <= trigger.top;}, TOOLTIP),- ).toBe(false);+ ).toBe(true);await page.getByRole('button', {name: 'Replace the trigger'}).click();const second = page.getByRole('button', {name: 'Trigger 2'});await expect(second).toBeVisible();@@ -288,8 +295,7 @@ function expectReadableOnRoomierSide(frames: Frame[], viewportHeight: number) {/*** 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.+ * at `triggerY`, and wait until the tooltip sits clear of it.*/async function focusTallTriggerOnPhone(page: Page, triggerY: number) {await page.setViewportSize({width: 390, height: 700});@@ -309,7 +315,7 @@ async function focusTallTriggerOnPhone(page: Page, triggerY: number) {);await trigger.focus();await expect(page.getByRole('tooltip')).toBeVisible();- await expectSwitched(page);+ await expectPlacedClear(page);}test('a switched tooltip whose trigger moves toward the far edge moves to the roomier side, readable', async ({@@ -343,12 +349,13 @@ test('a switched tooltip whose trigger moves the other way moves to the roomierexpectReadableOnRoomierSide(frames, 700);});-test('a tooltip that switches lists after it has painted is placed afresh, not left on its old option', async ({+test('a tooltip whose option runs out of room in a scroll is placed afresh once the scroll stops, 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.+ // and a scroll carries its trigger up: the old option leaves the box past+ // the top of the viewport. During the scroll the browser keeps that option;+ // once the scroll stops, the tooltip is placed afresh, clear and in view.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`,@@ -369,15 +376,8 @@ test('a tooltip that switches lists after it has painted is placed afresh, not l}}, 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);- }+ await page.evaluate(() => window.scrollBy(0, 310));+ await expectPlacedClear(page);});/**@@ -407,21 +407,55 @@ async function openHeldTooltip(}/**- * Wait until the tooltip has switched to its anchor-clear list. A switch that- * follows a move waits for the move observer's report, which a loaded- * machine makes later.+ * Wait until the tooltip sits clear of its trigger and inside the viewport on+ * the block axis. A re-pick after a scroll waits for the first frame painted+ * after the scroll stops, which a loaded machine makes later.*/-async function expectSwitched(page: Page) {- await expect(page.locator(TOOLTIP)).toHaveAttribute(- 'data-astryx-clears-anchor',- );+async function expectPlacedClear(page: Page) {+ await expect+ .poll(async () =>+ page.evaluate(+ ([tip, sel]) => {+ const l = (+ document.querySelector(tip) as HTMLElement+ ).getBoundingClientRect();+ const a = (+ document.querySelector(sel) as HTMLElement+ ).getBoundingClientRect();+ const covers =+ l.left < a.right &&+ a.left < l.right &&+ l.top < a.bottom &&+ a.top < l.bottom;+ const inView =+ l.top >= -1 &&+ l.bottom <= document.documentElement.clientHeight + 1;+ return !covers && inView;+ },+ [TOOLTIP, TRIGGER],+ ),+ )+ .toBe(true);}-async function hasSwitched(page: Page): Promise<boolean | undefined> {+/**+ * Whether the tooltip sits beside its trigger on the inline axis: level with+ * it, and clear of it to its inline start or end.+ */+async function sitsBesideTrigger(page: Page): Promise<boolean> {return page.evaluate(- sel =>- document.querySelector(sel)?.hasAttribute('data-astryx-clears-anchor'),- TOOLTIP,+ ([tip, sel]) => {+ const l = (+ document.querySelector(tip) as HTMLElement+ ).getBoundingClientRect();+ const a = (+ document.querySelector(sel) as HTMLElement+ ).getBoundingClientRect();+ const level = l.top < a.bottom && a.top < l.bottom;+ const clear = l.right <= a.left || l.left >= a.right;+ return level && clear;+ },+ [TOOLTIP, TRIGGER],);}@@ -444,14 +478,14 @@ test('a scroll never switches a tooltip that fits, so it still flips below whenawait button.focus();await expect(page.getByRole('tooltip')).toBeVisible();await page.waitForTimeout(200);- const atOpen = await hasSwitched(page);+ const atOpen = await sitsBesideTrigger(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);+ expect(await sitsBesideTrigger(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;@@ -472,7 +506,7 @@ test('a scroll never switches a tooltip that fits, so it still flips below whenexpect(atOpen).toBe(false);expect(tooltip.top).toBeGreaterThanOrEqual(trigger.bottom);expect(tooltip.left).toBeLessThan(trigger.right);- expect(await hasSwitched(page)).toBe(false);+ expect(await sitsBesideTrigger(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 ({@@ -482,7 +516,7 @@ test('a scroll that moves a tall tooltip’s trigger never leaves the tooltip ov// 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);- await expectSwitched(page);+ await expectPlacedClear(page);for (let step = 0; step < 4; step++) {const frames = await page.evaluate(async ({sel, tip}) => {@@ -535,7 +569,7 @@ test('a smooth scroll that carries a tall tooltip’s trigger leaves it clear an// 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);- await expectSwitched(page);+ await expectPlacedClear(page);const settle = async () =>page.evaluate(async () => {const frame = async () =>@@ -644,7 +678,7 @@ test('a trigger that a scrolled container hides for several seconds is followed// that settle before the case starts.await scrollTriggerTo(150);await page.waitForTimeout(1500);- await expectSwitched(page);+ await expectPlacedClear(page);await scrollTriggerTo(-150);await page.waitForTimeout(3500);@@ -666,9 +700,9 @@ test('placing a shown tooltip afresh never replays its entry animation', async (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.+ // short tooltip grows, then a scroll carries its trigger up so its option+ // leaves it past the top of the viewport. Once the scroll stops it is+ // placed afresh, 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`,@@ -696,8 +730,19 @@ test('placing a shown tooltip afresh never replays its entry animation', async (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';+ let placed = false;+ // Placing afresh takes the layer out of rendering for one read.+ const watch = new MutationObserver(records => {+ placed ||= records.some(record =>+ record.oldValue?.includes('display: none'),+ );+ });+ watch.observe(tooltip, {+ attributes: true,+ attributeFilter: ['style'],+ attributeOldValue: true,+ });+ window.scrollBy(0, trigger.getBoundingClientRect().top - 340);const out: number[] = [];for (let i = 0; i < 12; i++) {await new Promise<void>(resolve => {@@ -709,18 +754,16 @@ test('placing a shown tooltip afresh never replays its entry animation', async (});out.push(Number(getComputedStyle(tooltip).opacity));}- return {- out,- switched: tooltip.hasAttribute('data-astryx-clears-anchor'),- };+ watch.disconnect();+ return {out, placed};},{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);+ // During a scroll, Chromium keeps the tooltip on its old option, so the+ // runtime places it afresh once the scroll stops. WebKit can choose again+ // itself, so there it may never need to be placed afresh.+ expect(opacities.placed).toBe(true);}for (const [i, opacity] of opacities.out.entries()) {expect(opacity, `painted frame ${i + 1}`).toBe(1);@@ -1025,20 +1068,18 @@ test('placing a shown tooltip afresh keeps every animation in its content in its};}, 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);+ // A scroll carries the trigger up, so the tooltip is placed afresh once the+ // scroll stops.+ await page.evaluate(() => window.scrollBy(0, 310));await page.waitForTimeout(450);if (browserName === 'chromium') {- await expectSwitched(page);+ await expectPlacedClear(page);}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.)+ // the path that has to put them back. (WebKit can choose again itself, so+ // there the tooltip may never be placed afresh; every row must hold either+ // way.)if (browserName === 'chromium') {expect(after.recreated).toBe(true);}