An open source design system that's fully customizable and agent ready
TypeScript
fix(Tooltip): a tooltip taller than the room around its trigger opens clear of it (#8254)
EJ Hammonda56c06134f1c
diff --git a/.changeset/tooltip-tall-content-keeps-trigger-clear.md b/.changeset/tooltip-tall-content-keeps-trigger-clear.mdnew file mode 100644index 0000000000..0206b291d1--- /dev/null+++ b/.changeset/tooltip-tall-content-keeps-trigger-clear.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `Tooltip`: a tooltip taller than the room above and below its trigger no longer opens over the trigger. It opens beside the trigger when there is room there, otherwise on the other side if it fits there, and otherwise on the side with more room, sized to that room, scrolling content it cannot show. It also moves clear when its content grows, or its trigger or the viewport resizes, while it is open. Before, it slid over its own trigger, where a resting pointer could lose it, and content past the viewport could not be read. Tooltips that fit are placed exactly as before.++@ejhammonddiff --git a/.github/a11y-baseline.json b/.github/a11y-baseline.jsonindex 9bc8abe296..0a3de8f24b 100644--- a/.github/a11y-baseline.json+++ b/.github/a11y-baseline.json@@ -1,7 +1,7 @@{- "$comment": "Known axe violations tolerated by the pr-a11y CI gate. Entries are keyed Component::Story::rule-id. Regenerate with `pnpm a11y:baseline` (requires a built Storybook + Playwright chromium). Remove entries as violations are fixed.",+ "$comment": "Known axe violations tolerated by the pr-a11y CI gate. Entries are keyed package/component::story-id::rule-id; legacy Component::Story::rule-id entries are preserved until their exact story can be migrated. Regenerate with `pnpm a11y:baseline` (requires a built Storybook + Playwright chromium). Remove entries as violations are fixed.","version": 1,- "generatedAt": "2026-07-31T09:21:12.717Z",+ "generatedAt": "2026-10-24T15:57:55.439Z","entries": [{"key": "Badge::Status Labels::color-contrast",@@ -747,6 +747,11 @@"key": "Tokenizer::Disabled::color-contrast","impact": "serious","helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"+ },+ {+ "key": "core/Tooltip::core-tooltip--tall-content-moving-host::scrollable-region-focusable",+ "impact": "serious",+ "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/scrollable-region-focusable?application=playwright"}]}diff --git a/apps/storybook/stories/Tooltip.stories.tsx b/apps/storybook/stories/Tooltip.stories.tsxindex 2edaf747c0..f578b8a95f 100644--- a/apps/storybook/stories/Tooltip.stories.tsx+++ b/apps/storybook/stories/Tooltip.stories.tsx@@ -1,5 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import {useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {Tooltip, useTooltip} from '@astryxdesign/core/Tooltip';import {Button} from '@astryxdesign/core/Button';@@ -163,6 +164,137 @@ export const LongContent: Story = {},};+/** Sixty lines: taller than the room above or below a mid-page trigger. */+const TALL_LINES = Array.from(+ {length: 60},+ (_, i) => `Line ${i + 1} of a tooltip taller than the space around it`,+);++/**+ * Content taller than the room above and below its trigger. The page is two+ * and a half viewports tall so the trigger can be scrolled to any height.+ */+export const TallContent: Story = {+ parameters: {layout: 'fullscreen'},+ args: {+ placement: 'above',+ content: (+ <div>+ {TALL_LINES.map(line => (+ <div key={line}>{line}</div>+ ))}+ </div>+ ),+ children: <Button label="Hover for details">Hover for details</Button>,+ },+ render: args => (+ <div+ style={{+ minHeight: '250vh',+ display: 'grid',+ placeItems: 'center',+ }}>+ <Tooltip {...args} />+ </div>+ ),+};++/**+ * A tall tooltip held open while its render call moves from a plain container+ * into a paragraph, which hosts the layer elsewhere and remounts it. The+ * replacement must keep its trigger clear exactly as the first one did.+ */+export const TallContentMovingHost: Story = {+ parameters: {layout: 'fullscreen'},+ render: function TallContentMovingHostExample() {+ const [inParagraph, setInParagraph] = useState(false);+ const tooltip = useTooltip({placement: 'above', isOpen: true});+ const rendered = tooltip.renderTooltip(+ <div>+ {TALL_LINES.map(line => (+ <div key={line}>{line}</div>+ ))}+ </div>,+ );+ return (+ <div style={{minHeight: '100vh', display: 'grid', placeItems: 'center'}}>+ <div+ style={{+ position: 'fixed',+ insetBlockStart: 16,+ insetInlineStart: 16,+ }}>+ <Button+ label="Move the tooltip's host"+ onClick={() => setInParagraph(value => !value)}>+ Move the tooltip's host+ </Button>+ </div>+ <Button+ label="Tall tooltip trigger"+ ref={tooltip.ref}+ aria-describedby={tooltip.describedBy}>+ Tall tooltip trigger+ </Button>+ {inParagraph ? <p>{rendered}</p> : <div>{rendered}</div>}+ </div>+ );+ },+};++/**+ * A tooltip held open while its caller replaces the trigger element with+ * another one in the same place. The replacement is the anchor from then on,+ * and the tooltip must keep it clear as it moves or resizes.+ */+export const TallContentReplacedTrigger: Story = {+ parameters: {layout: 'fullscreen'},+ render: function TallContentReplacedTriggerExample() {+ const [generation, setGeneration] = useState(0);+ const tooltip = useTooltip({placement: 'above', isOpen: true});+ return (+ <div style={{minHeight: '100vh'}}>+ <div+ style={{+ position: 'fixed',+ insetBlockStart: 16,+ insetInlineStart: 16,+ }}>+ <Button+ label="Replace the trigger"+ onClick={() => setGeneration(value => value + 1)}>+ Replace the trigger+ </Button>+ </div>+ {/* The trigger's bottom edge sits 682px down, so it grows upward. */}+ <div+ style={{+ blockSize: 682,+ display: 'flex',+ justifyContent: 'center',+ alignItems: 'flex-end',+ }}>+ <Button+ key={generation}+ label={`Trigger ${generation + 1}`}+ ref={tooltip.ref}+ aria-describedby={tooltip.describedBy}>+ {`Trigger ${generation + 1}`}+ </Button>+ </div>+ {tooltip.renderTooltip(+ <div>+ <div>A tooltip that stays open</div>+ {Array.from({length: 17}, (_, i) => (+ <div key={i}>{`Line ${i + 1}`}</div>+ ))}+ </div>,+ )}+ </div>+ );+ },+};+export const MultipleTooltips: Story = {render: () => (<div style={{padding: 100}}>diff --git a/docs/architecture/interaction-modality.md b/docs/architecture/interaction-modality.mdindex 0a1eda3d38..cc2c641478 100644--- a/docs/architecture/interaction-modality.md+++ b/docs/architecture/interaction-modality.md@@ -117,7 +117,12 @@ work.and replacement content cannot silently remove the owner's indicator.- **INV4 — Every modality has an operable path.** Keyboard, pointer, and touch orpen can reach each supported interaction. Hover is never the only discovery or- activation path.+ activation path. A tooltip's scrolling overflow is the one exception, as+ `spec:AST-025` FR12 records: a tooltip never takes focus under the ARIA+ tooltip pattern, so content too tall for the viewport scrolls inside it with+ no keyboard path; its full content stays available to assistive technology+ through the trigger's accessible description, and long or essential content+ belongs in a HoverCard or Popover.- **INV5 — Existing state semantics win.** Disabled controls do not becomeinteractive because of modality. Read-only and busy controls preserve theirdocumented focus and activation behavior.diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.mdindex 7c13e10f55..1b96720760 100644--- a/docs/architecture/layer-runtime.md+++ b/docs/architecture/layer-runtime.md@@ -182,7 +182,21 @@ 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.+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. 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'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@@ -190,10 +204,21 @@ 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 thesame frame as the render that produced it; 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. A-layer never paints at a geometry it is about to correct.+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+covers its anchor or leaves the viewport, judged from its box without its own+transform (so an entry animation that starts it closer to the anchor does not+count), 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 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.### Current browser support behavior@@ -373,9 +398,13 @@ layers use Layer rendering without joining Escape/platform dismissal.the same inset, no consumer defines its own, no size is capped to the spanbeside 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 one runtime- observation, anchor visibility, is read before first paint. A layer never- paints at a geometry it is about to correct.+ 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.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@@ -441,7 +470,8 @@ be updated only as that work ships.`Layer/layerStructureReset.stylex.ts` owns the named structural custom-propertyreset applied on layer content roots.- `Layer/layerViewportInset.stylex.ts` owns the gutter and the viewport caps;- `Layer/layerSlideRules.ts` owns the slide options' `@position-try` rules;+ `Layer/layerSlideRules.ts` owns the slide options' `@position-try` rules+ and the anchor-clear list's beside and fit rules;`LayerProvider` publishes the declared inset through `LayerContext`, and`Layer/layerInset.ts` owns the `--astryx-layer-inset-*` properties a layer orthe toast viewport writes on itself to carry it; `Layer/clampInlineSize.ts`diff --git a/docs/specs/AST-025/spec.md b/docs/specs/AST-025/spec.mdindex d11d473df6..5c4978ac9d 100644--- a/docs/specs/AST-025/spec.md+++ b/docs/specs/AST-025/spec.md@@ -11,11 +11,15 @@ approved_at: 2026-09-11phase: acceptedowners: [cixzhang]affects_architecture:- [architecture:container-padding, architecture:public-component-api]+ [+ architecture:container-padding,+ architecture:public-component-api,+ architecture:interaction-modality,+ ]affects_families: [family:layout-regions, family:layout-primitives]affects_contributing: []affects_consumer_docs:- [Layout, Stack, Table, Popover, DropdownMenu, Carousel, CodeBlock]+ [Layout, Stack, Table, Popover, DropdownMenu, Carousel, CodeBlock, Tooltip]---# Scrollable container behavior system spec@@ -152,6 +156,13 @@ the behavior.persistent subtree or ancestor observation for keyboard eligibility; existinggeometry observation remains governed by FR5–FR9. Both paths MUST retain clearaccessible naming and native Arrow/Page access to the full scroll range.+ A tooltip is the one exception: content too tall for the viewport scrolls+ inside it with no keyboard path. Under the ARIA tooltip pattern a tooltip+ never takes focus, and its trigger keeps focus while it is shown; the full+ content stays available to assistive technology through the trigger's+ accessible description; long or essential content belongs in a HoverCard or+ Popover, which do take focus; and the alternative, overflow left outside the+ viewport, reaches no one.- **FR13 — Losing overflow does not move focus.** If a focused viewport stopsoverflowing, the system MAY remove it from future sequential navigation but MUSTNOT move or blur current focus solely because geometry changed.diff --git a/docs/specs/AST-059-layer-viewport-inset/spec.md b/docs/specs/AST-059-layer-viewport-inset/spec.mdindex 86fb61ae80..9956666146 100644--- a/docs/specs/AST-059-layer-viewport-inset/spec.md+++ b/docs/specs/AST-059-layer-viewport-inset/spec.md@@ -47,8 +47,8 @@ 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 fallback order (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 to the other side, and when it fits on neither side it keeps its size and slides along the alignment axis into view while the anchor is in view (FR4, DEC-2). 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). |+| 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). || 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. |@@ -119,10 +119,11 @@ the app reaches every layer instead of the components that happen to read it.## Non-goals-- **Sizing a layer to the room on one side of its trigger on the placement- axis.** A layer taller than the room both above and below its trigger is- capped to the viewport and flipped. Preferring the roomier side is not- settled here.+- **Sizing a standard layer to the room on one side of its trigger on the+ placement axis.** A layer taller than the room both above and below its+ trigger is capped to the viewport and shifted into it. Whether standard+ layers prefer the roomier side is not settled here; a layer that keeps its+ anchor clear is the one case FR4 settles.- **Fullscreen Dialog.** It keeps the same gutter value by convention but isnot an anchor-mode layer; whether the app-declared inset (FR6) reaches it isa later decision. The toast viewport does read it (FR6, DEC-5).@@ -161,9 +162,9 @@ the app reaches every layer instead of the components that happen to read it.capped to the viewport minus both gutters, and the box never exceeds it.A composing component may cap lower (DropdownMenu's 300px) and may become ascroll container when its content exceeds the cap; it may not cap higher.-- **FR4 — One fallback order.** An anchor-mode layer tries, in order: its- preferred position; the flip across the placement axis; the flip across the- alignment axis; both flips; then, while its anchor is in view, a slide+- **FR4 — The runtime's fallback orders.** An anchor-mode layer tries, in order:+ its preferred position; the flip across the placement axis; the flip across+ the alignment axis; both flips; then, while its anchor is in view, a slidealong the alignment axis that keeps the layer's size and moves it the leastdistance that brings it inside the gutters, on the preferred side of thetrigger first and the opposite side second. The slide is a position option@@ -178,8 +179,31 @@ the app reaches every layer instead of the components that happen to read it.layer the same distance from the opposite edge (the size cap stillsubtracts each edge's own gutter). Content taller than either side can holdis capped to the viewport and shifted into it, keeping its anchor clearance- from the edge it meets. The runtime authors this order; a component passes no- fallbacks of its own to an anchor-mode layer.+ 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+ 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+ side, partly off-screen), an above or below layer tries instead beside the+ anchor on the inline end, then on the inline+ start, each at its content's inline size and capped to the viewport, 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 side with more room and sized+ to the room on that side. A layer whose content fits on some side keeps its+ own size there; only content taller than the room on both sides is sized to+ a room. No option is sized to whatever room is left, because a browser keeps+ an open layer on the option it last used for as long as that option still+ fits: when its anchor moves, the layer moves to the side that is now roomier+ rather than shrinking to a sliver. Whether the first list has failed is read+ 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+ 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.- **FR5 — An off-screen anchor holds.** A layer whose anchor has left theviewport does not slide. It keeps the position the flips give it and itssize until the anchor returns (DEC-3).@@ -211,11 +235,24 @@ the app reaches every layer instead of the components that happen to read it.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 therender that produced it; the runtime measures nothing after paint to apply- them. The one observation the runtime makes, whether the anchor is in view- (FR5), is read before the layer's first paint and thereafter only when the+ 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 theanchor's visibility changes, so a layer opened while its anchor is already- out of view holds from its first frame. When a declared inset changes while- a layer is open, the layer and the declaration change in the same frame.+ out of view holds from its first frame. For a layer that keeps its anchor+ clear (FR4), whether its settled box (without its own transform) covers its+ anchor or leaves the viewport, and whether its content overflows the box, are+ read in the same+ call that shows or remounts it, and again while it is open whenever its size,+ its content's size, its anchor's size or the viewport changes, including+ 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,+ the layer+ and the declaration+ change in the same frame.Latency between an app measuring its own bar and declaring the result is theapp's; the runtime renders what is declared, when it is declared. Apaint-then-shift is a failure of this contract, not a quality concern.@@ -316,7 +353,8 @@ When this ships:TopNav menus, and the date inputs render through anchor mode or`usePopover` and receive FR1–FR5 with no change of their own. A layer thatfits is unchanged; one that would overflow the viewport is capped, flipped,- or slid.+ or slid. Tooltip also keeps its anchor clear (FR4) and scrolls content+ taller than the room it is given (FR3).- `ToastViewport` positions itself at the provider's inset on each edge; itsown `inset` keeps its meaning as the per-edge override (FR6, DEC-5).@@ -339,6 +377,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 || 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 |@@ -368,7 +407,8 @@ their stories. Popover is an application of the layer that adds stylingconsiderations on top. A gutter defined once cannot drift; a fallback listauthored once cannot be extended by one component for its own case; a personsees the same edge behavior from a menu, a popover, a typeahead, and a-tooltip.+tooltip, apart from the anchor-clear order FR4 gives a tooltip, which the+runtime also authors.Rejected: a shared constant each component imports while keeping its own fitstyles — it removes the drift and keeps the ownership problem.diff --git a/packages/core/src/Layer/layerSlideRules.ts b/packages/core/src/Layer/layerSlideRules.tsindex abc050f320..7b7d0c2098 100644--- a/packages/core/src/Layer/layerSlideRules.ts+++ b/packages/core/src/Layer/layerSlideRules.ts@@ -3,7 +3,9 @@/*** @file layerSlideRules.ts* @input A layer's placement and alignment- * @output The `@position-try` rules for its slide options and their names+ * @output The `@position-try` rules for its slide options and their names, and+ * the beside and fit options of a layer that must never settle over its+ * anchor* @position Layer runtime geometry; the slide of spec:AST-059 FR4** The slide is a position option whose area spans the whole alignment axis,@@ -16,6 +18,23 @@* 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+ * 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 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`.+ ** The rules are static — the anchor clearance travels through a custom* property — so one style sheet per document carries all of them. It is* installed from a layout effect, before the layer's first paint, rather than@@ -122,14 +141,128 @@ const PLACEMENTS: ReadonlyArray<LayerPlacement> = [];const ALIGNMENTS: ReadonlyArray<LayerAlignment> = ['start', 'center', 'end'];-/** Every slide rule, for every placement and alignment. */+/** 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}`;+}++/**+ * The name of the `fit` option that lands on `side` sized to the room there,+ * which fits only while that side holds at least half of the room the trigger+ * leaves on the block axis.+ */+export function fitRuleName(side: 'above' | 'below'): string {+ return `--astryx-layer-fit-${side}`;+}++/**+ * `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.+ */+function besideRule(side: 'start' | 'end'): string {+ return `@position-try ${besideRuleName(side)}{position-area:${areaFor(side)};${placementMargins(side)}${alignmentMargins(side)}inline-size:max-content;}`;+}++/** The block size of the room on one block side: the area minus its margins. */+function roomCap(gutter: string): string {+ return `calc(100% - ${CLEARANCE} - ${gutter})`;+}++/**+ * Half of the room the trigger leaves on the block axis, minus one side's+ * margins and one pixel: a side whose room is at least this much is the+ * roomier side. The pixel lets both sides fit when the trigger sits at the+ * viewport's middle, where rounding could otherwise fail both.+ */+function halfRoom(viewport: string, gutter: string): string {+ return `calc((${viewport} - anchor-size(block)) / 2 - ${CLEARANCE} - ${gutter} - 1px)`;+}++/**+ * `fit`: the slide's geometry on a block side, sized to the room on that+ * side; the layer scrolls what does not fit (FR3). It is at least half of the+ * room the trigger leaves, so it overflows, and does not fit, on the side+ * with less room.+ */+function fitRule(side: 'above' | 'below'): string {+ const size = (viewport: string, gutter: string) =>+ `max(${roomCap(gutter)}, ${halfRoom(viewport, gutter)})`;+ const blockSize = pair(+ 'block-size',+ size('100vh', layerViewportInset.gutterBlockFallback),+ size('100dvb', layerViewportInset.gutterBlock),+ );+ return `@position-try ${fitRuleName(side)}{position-area:${areaFor(side)};${placementMargins(side)}${alignmentMargins(side)}${blockSize}}`;+}++/**+ * 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.+ */+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)}`;+}++/** 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+ * layer that fits stays a plain box and a wheel over it still scrolls the+ * page.+ */+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;}`;+}++/**+ * Every slide rule, for every placement and alignment, and the beside and fit+ * rules.+ */export function slideRulesCss(): string {- return PLACEMENTS.flatMap(placement =>- ALIGNMENTS.flatMap(alignment => [- rule(placement, alignment, 'same'),- rule(placement, alignment, 'opposite'),- ]),- ).join('');+ return [+ ...PLACEMENTS.flatMap(placement =>+ ALIGNMENTS.flatMap(alignment => [+ rule(placement, alignment, 'same'),+ rule(placement, alignment, 'opposite'),+ ]),+ ),+ besideRule('end'),+ besideRule('start'),+ fitRule('above'),+ fitRule('below'),+ clearSwitchCss(),+ ].join('');}export const SLIDE_RULES_ID = 'astryx-layer-slide-rules';diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsxindex 846229370b..9da52f284b 100644--- a/packages/core/src/Layer/useLayer.test.tsx+++ b/packages/core/src/Layer/useLayer.test.tsx@@ -18,6 +18,7 @@ import {waitFor,} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import {useEffect} from 'react';import * as stylex from '@stylexjs/stylex';import {useKeepLayerOpenProps,@@ -26,6 +27,7 @@ import {getPositionTryFallbacks,getSelfAlignment,} from './useLayer';+import {getAnchorClearFallbacks} from './layerSlideRules';import {typeScaleVars} from '../theme/tokens.stylex';import type {LayerPlacement,@@ -1627,3 +1629,377 @@ describe('wasJustDismissed (light dismiss vs. the trigger click, #5004)', () =>expect(getByTestId('state')).toHaveTextContent('closed');});});++describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {+ function ClearHarness({placement}: {placement?: LayerPlacement}) {+ const layer = useLayerInternal({mode: 'context', keepsAnchorClear: true});+ return (+ <>+ <button type="button" ref={layer.ref} onClick={layer.show}>+ Trigger+ </button>+ <button type="button" onClick={layer.hide}>+ Hide+ </button>+ {layer.render(<span>Layer content</span>, {placement})}+ </>+ );+ }++ function rect(top: number, left: number, height: number, width: number) {+ return {+ top,+ left,+ height,+ width,+ bottom: top + height,+ right: left + width,+ x: left,+ y: top,+ toJSON: () => ({}),+ } as DOMRect;+ }++ /** Lay out the trigger and the layer at the given boxes. */+ function placeBoxes(trigger: DOMRect, layer: DOMRect) {+ return vi+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')+ .mockImplementation(function (this: HTMLElement) {+ return this.hasAttribute('popover') ? layer : trigger;+ });+ }++ const TRIGGER = rect(300, 400, 30, 100);++ /** Give the document a 720px-tall viewport for the duration of a test. */+ function viewport720() {+ return vi+ .spyOn(document.documentElement, 'clientHeight', 'get')+ .mockReturnValue(720);+ }++ 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', () => {+ expect(getAnchorClearFallbacks('above')).toBe(+ '--astryx-layer-beside-end, --astryx-layer-beside-start, flip-block, --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',+ );+ // Side placements already slide along the block axis at full height.+ expect(getAnchorClearFallbacks('start')).toBe('');+ expect(getAnchorClearFallbacks('end')).toBe('');+ // Chromium tries no more than five options.+ for (const placement of ['above', 'below'] as const) {+ expect(+ getAnchorClearFallbacks(placement).split(', ').length,+ ).toBeLessThanOrEqual(5);+ }+ });++ it('installs the beside and fit rules and the switch to the clear list', async () => {+ const user = userEvent.setup();+ const {container} = render(<ClearHarness />);+ await user.click(container.querySelector('button')!);+ const css =+ document.getElementById('astryx-layer-slide-rules')?.textContent ?? '';+ // Beside: an inline side spanning the block axis, at the content's own+ // inline size so a content-sized layer cannot squeeze into a sliver.+ expect(css).toContain(+ '@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;\}/,+ );+ // 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+ // roomier side. No option is sized to whatever room is left: a browser+ // keeps an open layer on its last option while that still fits.+ for (const [side, area] of [+ ['above', 'self-block-start'],+ ['below', 'self-block-end'],+ ]) {+ expect(css).toMatch(+ new RegExp(+ `@position-try --astryx-layer-fit-${side}\\{position-area:${area} span-all;[^}]*block-size:max\\(calc\\(100% - [^}]*anchor-size\\(block\\)[^}]*100dvb`,+ ),+ );+ }+ 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);}',+ );+ });++ it('carries the clear list beside the standard one, which it uses until the switch', async () => {+ const user = userEvent.setup();+ const {container} = 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')})`,+ );+ expect(+ layerEl.style.getPropertyValue('--_astryx-layer-clear-fallbacks'),+ ).toBe(getAnchorClearFallbacks('below'));+ });++ it('switches to the clear list when the shown layer 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');+ });++ 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+ // WebKit leaves a box that fits no option.+ viewport720();+ 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');+ });++ it('keeps the standard list for a layer past the viewport 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.+ 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');+ });++ 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.+ 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');+ });++ it('starts every show from the standard list', async () => {+ const user = userEvent.setup();+ const spy = placeBoxes(TRIGGER, rect(16, 350, 688, 300));+ const {container, getByText} = render(<ClearHarness />);+ await user.click(getByText('Trigger'));+ const layerEl = container.querySelector('[popover]') as HTMLElement;+ expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');++ await user.click(getByText('Hide'));+ spy.mockRestore();+ placeBoxes(TRIGGER, rect(200, 350, 100, 200));+ await user.click(getByText('Trigger'));+ expect(layerEl).not.toHaveAttribute('data-astryx-clears-anchor');+ });++ it('scrolls only while its content overflows the box it was given', async () => {+ const user = userEvent.setup();+ placeBoxes(TRIGGER, rect(200, 350, 100, 200));+ let scrollHeight = 100;+ vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(+ () => scrollHeight,+ );+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(100);+ const {container, getByText} = render(<ClearHarness />);+ await user.click(getByText('Trigger'));+ const layerEl = container.querySelector('[popover]') as HTMLElement;+ // A layer that fits stays a plain box.+ expect(layerEl).not.toHaveAttribute('data-astryx-layer-scrolls');++ await user.click(getByText('Hide'));+ scrollHeight = 900;+ await user.click(getByText('Trigger'));+ expect(layerEl).toHaveAttribute('data-astryx-layer-scrolls');+ const css =+ document.getElementById('astryx-layer-slide-rules')?.textContent ?? '';+ expect(css).toContain(+ '[data-astryx-layer-scrolls]{overflow-y:auto;overscroll-behavior-block:contain;}',+ );+ });++ it('re-reads its geometry while open when it or its content resizes', async () => {+ const callbacks: (() => void)[] = [];+ const observed: Element[] = [];+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ constructor(callback: () => void) {+ callbacks.push(callback);+ }+ observe(target: Element) {+ observed.push(target);+ }+ disconnect() {}+ 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');+ expect(observed).toContain(layerEl);+ expect(observed).toContain(layerEl.firstElementChild);+ expect(observed).toContain(getByText('Trigger'));++ // The content grows and the standard list re-settles over the trigger.+ spy.mockRestore();+ placeBoxes(TRIGGER, rect(16, 350, 688, 300));+ act(() => {+ for (const callback of callbacks) {+ callback();+ }+ });+ expect(layerEl).toHaveAttribute('data-astryx-clears-anchor');+ 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[][] = [];+ const events: string[] = [];+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ targets: Element[] = [];+ observe(target: Element) {+ this.targets.push(target);+ observed.push(target);+ events.push(`observe ${target.textContent}`);+ }+ disconnect() {+ disconnected.push(this.targets);+ events.push(+ `disconnect ${this.targets.map(t => t.textContent).join(',')}`,+ );+ }+ unobserve() {}+ },+ );+ let renders = 0;+ function ReplacingHarness({generation}: {generation: number}) {+ renders += 1;+ const layer = useLayerInternal({+ mode: 'context',+ keepsAnchorClear: true,+ });+ useEffect(() => {+ layer.show();+ }, [layer]);+ return (+ <>+ <button type="button" key={generation} ref={layer.ref}>+ {`Trigger ${generation}`}+ </button>+ {layer.render(<span>Layer content</span>)}+ </>+ );+ }+ placeBoxes(TRIGGER, rect(200, 350, 100, 200));+ const {getByText, rerender} = render(<ReplacingHarness generation={1} />);+ await waitFor(() => {+ expect(observed).toContain(getByText('Trigger 1'));+ });+ const first = getByText('Trigger 1');+ const rendersBefore = renders;++ rerender(<ReplacingHarness generation={2} />);++ await waitFor(() => {+ expect(observed).toContain(getByText('Trigger 2'));+ });+ // The observer that watched the first trigger was disconnected, before+ // the second trigger was observed.+ expect(disconnected.some(targets => targets.includes(first))).toBe(true);+ const disconnectFirst = events.findIndex(+ e => e.startsWith('disconnect') && e.includes('Trigger 1'),+ );+ const observeSecond = events.indexOf('observe Trigger 2');+ expect(disconnectFirst).toBeGreaterThanOrEqual(0);+ expect(disconnectFirst).toBeLessThan(observeSecond);+ // No DOM node is held in React state: replacing the trigger renders the+ // hook once, for the caller's own rerender.+ expect(renders - rendersBefore).toBe(1);+ vi.unstubAllGlobals();+ });++ it('gives a layer remounted while open by a moved render call the same treatment', async () => {+ function MovingClearHarness({unsafe}: {unsafe: boolean}) {+ const layer = useLayerInternal({+ mode: 'context',+ keepsAnchorClear: true,+ });+ const rendered = layer.render(<span>Layer content</span>);+ return (+ <>+ <button type="button" ref={layer.ref} onClick={layer.show}>+ Trigger+ </button>+ {unsafe ? (+ <div data-testid="unsafe-host">+ <p>{rendered}</p>+ </div>+ ) : (+ <section data-testid="safe-host">{rendered}</section>+ )}+ </>+ );+ }+ const showSpy = vi.fn(function (this: HTMLElement) {+ this.dataset.open = 'true';+ });+ HTMLElement.prototype.showPopover = showSpy;+ placeBoxes(TRIGGER, rect(16, 350, 688, 300));+ const {container, getByRole, rerender} = render(+ <MovingClearHarness unsafe />,+ );+ fireEvent.click(getByRole('button', {name: 'Trigger'}));+ await waitFor(() => {+ expect(container.querySelector('[popover]')).toHaveAttribute(+ 'data-astryx-clears-anchor',+ );+ });+ const first = container.querySelector('[popover]');++ rerender(<MovingClearHarness unsafe={false} />);++ await waitFor(() => {+ const layer = container.querySelector('[popover]');+ expect(layer).not.toBe(first);+ expect(layer?.parentElement).toBe(+ container.querySelector('[data-testid="safe-host"]'),+ );+ expect(layer).toHaveAttribute('data-open', 'true');+ expect(layer).toHaveAttribute('data-astryx-clears-anchor');+ });+ });++ it('leaves a standard layer on the standard list alone', async () => {+ const user = userEvent.setup();+ placeBoxes(TRIGGER, rect(16, 350, 688, 300));+ 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(layerEl.style.positionTryFallbacks).toBe(+ getPositionTryFallbacks('above', 'center'),+ );+ expect(+ layerEl.style.getPropertyValue('--_astryx-layer-clear-fallbacks'),+ ).toBe('');+ });+});diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex 1859efc3c2..5bc3624d7f 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -37,7 +37,12 @@ import {layerViewportInset} from './layerViewportInset.stylex';import {layerInsetProperties} from './layerInset';import {LAYER_CLEARANCE_PROPERTY,+ LAYER_CLEARS_ANCHOR_ATTRIBUTE,+ LAYER_SCROLLS_ATTRIBUTE,+ LAYER_CLEAR_FALLBACKS_PROPERTY,+ LAYER_TRY_FALLBACKS_PROPERTY,ensureSlideRules,+ getAnchorClearFallbacks,slideRuleName,} from './layerSlideRules';import {useLayerContext} from './LayerContext';@@ -416,6 +421,21 @@ interface InternalLayerFields {wasJustDismissed: () => boolean;}+/**+ * Context-mode options a core component may pass through `useLayerInternal`;+ * not part of the public `useLayer` options.+ */+interface InternalContextLayerOptions extends ContextLayerOptions {+ /**+ * The layer must never settle over its anchor (spec:AST-059 FR4). When the+ * standard fallback list settles it over its anchor, it switches to its+ * anchor-clear list: beside the trigger, then whichever block side is+ * roomier, sized to its room. For a hover-summoned layer, which the hover on+ * its trigger keeps open.+ */+ keepsAnchorClear?: boolean;+}+type InternalContextLayerReturn = ContextLayerReturn & InternalLayerFields;type InternalFixedLayerReturn = FixedLayerReturn & InternalLayerFields;@@ -423,6 +443,217 @@ function toCssLength(value: number | string): string {return typeof value === 'number' ? `${value}px` : value;}+const TRANSFORM_PROPERTIES = ['transform', 'translate', 'scale', 'rotate'];++function hasTransform(style: CSSStyleDeclaration): boolean {+ return TRANSFORM_PROPERTIES.some(name => {+ const value = style.getPropertyValue(name);+ return value !== '' && value !== 'none';+ });+}++/**+ * `rect`, the box of an element whose computed style still carries a 2D+ * transform, with that transform undone: the transformed box's centre is the+ * image of the element's centre, so undoing the transform about its origin on+ * that centre gives the untransformed box, at the element's layout size. A+ * transform this cannot undo (3D, or a rotation in another unit) leaves `rect`+ * as it is.+ */+function untransform(+ rect: DOMRect,+ layer: HTMLElement,+ style: CSSStyleDeclaration,+): DOMRect {+ const set = (value: string) => value !== '' && value !== 'none';+ if (typeof DOMMatrix === 'undefined' || layer.offsetWidth <= 0) {+ return rect;+ }+ // The individual transform properties apply before `transform`, in this+ // order (CSS Transforms 2).+ let matrix = new DOMMatrix();+ if (set(style.translate)) {+ const [x = '0', y = '0', z] = style.translate.split(' ');+ if (z != null) {+ return rect;+ }+ matrix = matrix.translate(parseFloat(x), parseFloat(y));+ }+ if (set(style.rotate)) {+ if (!/^-?[\d.]+deg$/.test(style.rotate)) {+ return rect;+ }+ matrix = matrix.rotate(parseFloat(style.rotate));+ }+ if (set(style.scale)) {+ const [x = '1', y = x, z] = style.scale.split(' ');+ if (z != null) {+ return rect;+ }+ matrix = matrix.scale(parseFloat(x), parseFloat(y));+ }+ if (set(style.transform)) {+ matrix = matrix.multiply(new DOMMatrix(style.transform));+ }+ if (!matrix.is2D) {+ return rect;+ }+ const [originX = 0, originY = 0] = style.transformOrigin+ .split(' ')+ .map(value => parseFloat(value));+ const width = layer.offsetWidth;+ const height = layer.offsetHeight;+ const centre = matrix.transformPoint(+ new DOMPoint(width / 2 - originX, height / 2 - originY),+ );+ const left = rect.left + rect.width / 2 - centre.x - originX;+ const top = rect.top + rect.height / 2 - centre.y - originY;+ return new DOMRect(left, top, width, height);+}++/**+ * The layer's box where its position option put it, without the transform an+ * entry animation (or anything else) applies to it: a Tooltip enters from a+ * few pixels toward its trigger, scaled down, so the transformed box of a+ * tooltip that fits beside its trigger can read as covering it while it+ * enters. The layer's transforms are overridden with `none !important`, which+ * outranks an animation, for this one read and then restored, in the same+ * task: no frame paints in between and the animation keeps running. Where the+ * engine still applies an animated transform under that override (WebKit),+ * the read box has that transform undone instead (`untransform`). A layer+ * that transitions a transform property is not overridden, since restoring the+ * value would start that transition; its box has its transform undone.+ */+function settledBox(layer: HTMLElement): DOMRect {+ const view = layer.ownerDocument.defaultView;+ const style = view?.getComputedStyle(layer);+ if (style == null || !hasTransform(style)) {+ return layer.getBoundingClientRect();+ }+ const transitions = style.transitionProperty.split(',').map(p => p.trim());+ const durations = style.transitionDuration.split(',').map(parseFloat);+ const transitioned = transitions.some(+ (name, index) =>+ (name === 'all' || TRANSFORM_PROPERTIES.includes(name)) &&+ (durations[index % durations.length] ?? 0) > 0,+ );+ if (transitioned) {+ return untransform(layer.getBoundingClientRect(), layer, style);+ }+ const saved = TRANSFORM_PROPERTIES.map(+ name =>+ [+ name,+ layer.style.getPropertyValue(name),+ layer.style.getPropertyPriority(name),+ ] as const,+ );+ for (const name of TRANSFORM_PROPERTIES) {+ layer.style.setProperty(name, 'none', 'important');+ }+ const box = layer.getBoundingClientRect();+ const under = view?.getComputedStyle(layer);+ const settled =+ under != null && hasTransform(under) ? untransform(box, layer, under) : box;+ for (const [name, value, priority] of saved) {+ if (value === '') {+ layer.style.removeProperty(name);+ } else {+ layer.style.setProperty(name, value, priority);+ }+ }+ return settled;+}++/**+ * Whether the standard list has failed a layer that must keep its anchor+ * clear: its box covers the anchor or, while the anchor is in view, leaves the+ * viewport on the block axis. Only a box that overlaps the anchor counts; a+ * layer flush against it does not.+ */+function failsAnchor(layer: HTMLElement, anchor: HTMLElement): boolean {+ const a = anchor.getBoundingClientRect();+ const l = settledBox(layer);+ if (l.width <= 0 || l.height <= 0) {+ return false;+ }+ const covers =+ l.left < a.right &&+ a.left < l.right &&+ l.top < a.bottom &&+ a.top < l.bottom;+ // The viewport's block extent, as the layer's anchor positioning sees it.+ const viewportBlock = layer.ownerDocument.documentElement.clientHeight;+ const anchorInView = a.bottom > 0 && a.top < viewportBlock;+ return covers || (anchorInView && (l.top < 0 || l.bottom > viewportBlock));+}++/**+ * 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 (FR8). Once switched, a layer keeps+ * its anchor-clear list until it next opens, so it never jumps back over its+ * trigger while open.+ */+function keepAnchorClear(layer: HTMLElement, anchor: HTMLElement | null): void {+ if (anchor && failsAnchor(layer, anchor)) {+ layer.setAttribute(LAYER_CLEARS_ANCHOR_ATTRIBUTE, '');+ }+ // A layer that fits has no scroll range and stays a plain box, so a wheel+ // over it still scrolls the page.+ layer.toggleAttribute(+ LAYER_SCROLLS_ATTRIBUTE,+ layer.scrollHeight > layer.clientHeight + 1,+ );+}++/**+ * 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.+ */+function observeAnchorClearance(+ layer: HTMLElement,+ anchor: HTMLElement,+ isCurrent: () => boolean,+): () => void {+ const view = layer.ownerDocument.defaultView;+ if (!view) {+ return () => {};+ }+ const reread = () => {+ if (isCurrent()) {+ keepAnchorClear(layer, anchor);+ }+ };+ let observer: ResizeObserver | null = null;+ if (typeof ResizeObserver !== 'undefined') {+ observer = new ResizeObserver(reread);+ observer.observe(layer);+ for (const child of Array.from(layer.children)) {+ observer.observe(child);+ }+ observer.observe(anchor);+ }+ view.addEventListener('resize', reread);+ return () => {+ observer?.disconnect();+ view.removeEventListener('resize', reread);+ };+}+/*** Popover operations in flight, per document.*@@ -691,10 +922,12 @@ export function useKeepLayerOpenProps(* ```*/function useLayerImplementation(- options: ContextLayerOptions | FixedLayerOptions,+ options: InternalContextLayerOptions | FixedLayerOptions,): InternalContextLayerReturn | InternalFixedLayerReturn {const {mode, onShow, onHide, lightDismiss = false} = options;const lazyMount = mode === 'context' ? (options.lazyMount ?? false) : false;+ const keepsAnchorClear =+ mode === 'context' ? (options.keepsAnchorClear ?? false) : false;const id = useId();const anchorId = `--astryx-layer-${id.replace(/:/g, '')}`;@@ -861,13 +1094,19 @@ function useLayerImplementation(});return;}+ popover.removeAttribute(LAYER_CLEARS_ANCHOR_ATTRIBUTE);+ popover.removeAttribute(LAYER_SCROLLS_ATTRIBUTE);showPopoverElement(popover);+ if (keepsAnchorClear) {+ keepAnchorClear(popover, triggerRef.current);+ }isOpenRef.current = true;setIsOpen(true);onShow?.();}}, [onShow,+ keepsAnchorClear,requestContextMount,showPopoverElement,isCurrentContextPopover,@@ -909,6 +1148,12 @@ function useLayerImplementation(const showRef = useRef(show);showRef.current = show;+ // The open-state geometry observers of a layer that keeps its anchor clear+ // (`observeAnchorClearance`), as their teardown. The open-state layout+ // effect binds them; the trigger callback ref rebinds them when a caller+ // replaces the trigger element while the layer stays open.+ const clearObserversRef = useRef<(() => void) | null>(null);+// Stable ref for the trigger element (context mode only).const contextRef = useCallback((el: HTMLElement | null) => {@@ -922,9 +1167,28 @@ function useLayerImplementation(addAnchorName(el, anchorId);}+ const previous = triggerRef.current;triggerRef.current = el;++ // A trigger replaced while the layer is open (React detaches the old+ // node with `null`, then attaches the new one): the old trigger's+ // observers are removed before the new trigger's are added (INV6), and+ // binding them reads the new trigger's geometry at once.+ if (keepsAnchorClear && isOpenRef.current && el !== previous) {+ clearObserversRef.current?.();+ clearObserversRef.current = null;+ const layer = popoverRef.current;+ if (el && layer) {+ clearObserversRef.current = observeAnchorClearance(+ layer,+ el,+ () => popoverRef.current === layer && triggerRef.current === el,+ );+ keepAnchorClear(layer, el);+ }+ }},- [anchorId],+ [anchorId, keepsAnchorClear],);// Arm only when the dismissing gesture's click is still ahead of us. Some@@ -1046,6 +1310,9 @@ function useLayerImplementation(// Changing a portal target remounts the popover. Preserve the logical// open state without firing onShow again for the replacement element.showPopoverElement(el);+ if (keepsAnchorClear) {+ keepAnchorClear(el, triggerRef.current);+ }}},[@@ -1054,6 +1321,7 @@ function useLayerImplementation(show,showPopoverElement,isCurrentContextPopover,+ keepsAnchorClear,],);@@ -1140,6 +1408,35 @@ function useLayerImplementation(return () => observer.disconnect();}, [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+ // 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+ // remounted by a moved render call (`contextMount`). A trigger replaced while+ // open is rebound by the trigger callback ref, so no DOM node enters state.+ useIsomorphicLayoutEffect(() => {+ if (!keepsAnchorClear || !isOpen || mode !== 'context') {+ return;+ }+ const layer = popoverRef.current;+ const anchor = triggerRef.current;+ if (!layer || !anchor) {+ return;+ }+ clearObserversRef.current?.();+ clearObserversRef.current = observeAnchorClearance(+ layer,+ anchor,+ () => popoverRef.current === layer && triggerRef.current === anchor,+ );+ return () => {+ clearObserversRef.current?.();+ clearObserversRef.current = null;+ };+ }, [keepsAnchorClear, isOpen, mode, contextMount]);+// Render function for context modeconst renderContext = useCallback((children: ReactNode, props?: ContextRenderProps) => {@@ -1168,6 +1465,16 @@ function useLayerImplementation(} = props || {};// 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).+ 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@@ -1176,10 +1483,9 @@ function useLayerImplementation(: {positionAnchor: anchorId,positionArea: getPositionArea(placement, alignment),- positionTryFallbacks: getPositionTryFallbacks(- placement,- alignment,- ),+ positionTryFallbacks: clearFallbacks+ ? `var(${LAYER_TRY_FALLBACKS_PROPERTY}, ${standardFallbacks})`+ : standardFallbacks,...getSelfAlignment(placement, alignment, isAnchorInView),};@@ -1240,6 +1546,7 @@ function useLayerImplementation(...stylexResult.style,...anchorStyle,...clearanceProperty,+ ...clearFallbacksProperty,...layerInsetProperties(declaredInset),...contextMount.portalStyle,...extraStyle,@@ -1265,6 +1572,7 @@ function useLayerImplementation(declaredInset,id,isAnchorInView,+ keepsAnchorClear,lightDismiss,popoverRefCallback,sentinelRefCallback,@@ -1364,15 +1672,18 @@ export function useLayer(}, [internalLayer]);}-/** @internal Shared with usePopover; not exported from the package barrel. */+/**+ * @internal Shared with usePopover and useTooltip; not exported from the+ * package barrel.+ */export function useLayerInternal(- options: ContextLayerOptions,+ options: InternalContextLayerOptions,): InternalContextLayerReturn;export function useLayerInternal(options: FixedLayerOptions,): InternalFixedLayerReturn;export function useLayerInternal(- options: ContextLayerOptions | FixedLayerOptions,+ options: InternalContextLayerOptions | FixedLayerOptions,): InternalContextLayerReturn | InternalFixedLayerReturn {return useLayerImplementation(options);}diff --git a/packages/core/src/Tooltip/Tooltip.test.tsx b/packages/core/src/Tooltip/Tooltip.test.tsxindex 7e2a5b1108..5eaac92360 100644--- a/packages/core/src/Tooltip/Tooltip.test.tsx+++ b/packages/core/src/Tooltip/Tooltip.test.tsx@@ -112,6 +112,29 @@ 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 () => {+ render(+ <Tooltip content="Tall tooltip" isDefaultOpen placement="below">+ <button type="button">Trigger</button>+ </Tooltip>,+ );+ const tooltip = await waitFor(() => {+ const el = document.querySelector('[role="tooltip"]') as HTMLElement;+ 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',+ );+ });+ });+describe('isDefaultOpen', () => {it('shows tooltip on mount when isDefaultOpen is true', async () => {render(diff --git a/packages/core/src/Tooltip/__tests__/TooltipTallContent.a11y.browser.spec.ts b/packages/core/src/Tooltip/__tests__/TooltipTallContent.a11y.browser.spec.tsnew file mode 100644index 0000000000..97e74e0b46--- /dev/null+++ b/packages/core/src/Tooltip/__tests__/TooltipTallContent.a11y.browser.spec.ts@@ -0,0 +1,646 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TooltipTallContent.a11y.browser.spec.ts+ * @input The `Core/Tooltip` TallContent, TallContentMovingHost and+ * TallContentReplacedTrigger stories in a built Storybook, and real mouse+ * and keyboard input.+ * @output Real-engine proof, in Chromium and WebKit, that a tooltip taller+ * than the room above and below its trigger opens clear of the trigger, and+ * stays clear while it, its content, its trigger or the viewport resizes or+ * it is remounted: it opens beside the trigger when there is room there, or+ * on the side with more room otherwise, stays open under a still pointer+ * (WCAG 2.2 1.4.13 Content on Hover or Focus, persistent), and scrolls its+ * overflow inside a box that stays hoverable; and that a tooltip that fits+ * is unchanged.+ * @position Run with `pnpm test:a11y-contract` (Chromium) and+ * `pnpm exec playwright test TooltipTallContent --project webkit`. Which+ * position option an engine picks, and where it leaves a box that fits no+ * option, is layout only a real engine produces, and the engines differ.+ *+ * SYNC: Fixtures live in /apps/storybook/stories/Tooltip.stories.tsx+ * (TallContent, TallContentMovingHost, 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"]';++/**+ * Count every open and close of the tooltip from here on, and record its box+ * in every frame it is open: a frame callback runs before that frame's paint,+ * so a frame that would paint the tooltip over its trigger is seen.+ */+async function watchTooltip(page: Page) {+ await page.evaluate(sel => {+ const w = window as unknown as {+ __toggles: number;+ __frames: Box[];+ };+ w.__toggles = 0;+ w.__frames = [];+ document.addEventListener(+ 'toggle',+ event => {+ if ((event.target as Element).matches(sel)) {+ w.__toggles += 1;+ }+ },+ true,+ );+ const record = () => {+ const el = document.querySelector(sel);+ if (el?.matches(':popover-open')) {+ const r = el.getBoundingClientRect();+ w.__frames.push({+ top: r.top,+ bottom: r.bottom,+ left: r.left,+ right: r.right,+ });+ }+ requestAnimationFrame(record);+ };+ requestAnimationFrame(record);+ }, TOOLTIP);+}++/** The boxes recorded since frame `from`. */+async function framesFrom(page: Page, from = 0): Promise<Box[]> {+ return page.evaluate(+ start => (window as unknown as {__frames: Box[]}).__frames.slice(start),+ from,+ );+}++/**+ * 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},+ );+}++/**+ * 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;+}++/**+ * Open the TallContent story at a viewport, scroll the trigger's centre to+ * `triggerY`, rest the pointer on the trigger and wait for the tooltip.+ * Returns how many times the tooltip toggled.+ */+async function hoverTallTrigger(+ page: Page,+ viewport: {width: number; height: number},+ triggerY: number,+ args = '',+) {+ await page.setViewportSize(viewport);+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content&viewMode=story${args ? `&args=${args}` : ''}`,+ );+ 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 watchTooltip(page);+ const t = await rect(page, TRIGGER);+ await page.mouse.move((t.left + t.right) / 2, (t.top + t.bottom) / 2);+ const tooltip = page.getByRole('tooltip');+ await expect(tooltip).toBeVisible();+ return {tooltip, trigger: t};+}++/**+ * Sample the open tooltip under a resting pointer: it stays open, never covers+ * the trigger, and stays inside the viewport. A resting hand still jitters, so+ * the pointer moves by one pixel between samples without leaving the trigger;+ * an engine only re-targets hover on pointer movement.+ */+async function expectStillAndClear(+ page: Page,+ trigger: Box,+ viewport: {width: number; height: number},+ fromFrame = 0,+) {+ const cx = (trigger.left + trigger.right) / 2;+ const cy = (trigger.top + trigger.bottom) / 2;+ let last: Box | null = null;+ for (let i = 0; i < 12; i++) {+ await page.mouse.move(cx + (i % 2), cy);+ await page.waitForTimeout(150);+ await expect(page.getByRole('tooltip')).toBeVisible();+ const s = await rect(page, TOOLTIP);+ expect(overlaps(s, trigger), `sample ${i} covers the trigger`).toBe(false);+ expect(s.top).toBeGreaterThanOrEqual(0);+ expect(s.left).toBeGreaterThanOrEqual(0);+ expect(s.bottom).toBeLessThanOrEqual(viewport.height);+ expect(s.right).toBeLessThanOrEqual(viewport.width);+ if (last != null) {+ expect(s).toEqual(last);+ }+ last = s;+ }+ // Opened once, never closed.+ expect(+ await page.evaluate(+ () => (window as unknown as {__toggles: number}).__toggles,+ ),+ ).toBe(1);+ // No frame, the first included, painted it over the trigger.+ const frames = await framesFrom(page, fromFrame);+ expect(frames.length).toBeGreaterThan(0);+ for (const [i, frame] of frames.entries()) {+ expect(overlaps(frame, trigger), `frame ${i} covers the trigger`).toBe(+ false,+ );+ }+ return last as Box;+}++/** The box scrolls its overflow, and the pointer can move in and scroll it. */+async function expectScrollsInside(page: Page) {+ const metrics = await page.evaluate(sel => {+ const el = document.querySelector(sel) as HTMLElement;+ return {scrollHeight: el.scrollHeight, clientHeight: el.clientHeight};+ }, TOOLTIP);+ expect(metrics.scrollHeight).toBeGreaterThan(metrics.clientHeight);++ const s = await rect(page, TOOLTIP);+ await page.mouse.move((s.left + s.right) / 2, (s.top + s.bottom) / 2, {+ steps: 4,+ });+ await page.mouse.wheel(0, 400);+ await expect+ .poll(async () =>+ page.evaluate(+ sel => (document.querySelector(sel) as HTMLElement).scrollTop,+ TOOLTIP,+ ),+ )+ .toBeGreaterThan(0);+ await page.waitForTimeout(300);+ await expect(page.getByRole('tooltip')).toBeVisible();+}++test('desktop: a tall tooltip opens beside its trigger and stays open', async ({+ page,+}) => {+ const viewport = {width: 1280, height: 720};+ const {trigger} = await hoverTallTrigger(page, viewport, 360);+ const s = await expectStillAndClear(page, trigger, viewport);+ // Beside the trigger, on the inline axis.+ expect(s.left >= trigger.right || s.right <= trigger.left).toBe(true);+ await expectScrollsInside(page);+});++test('phone: with no room beside, it opens below when below has more room', async ({+ page,+}) => {+ const viewport = {width: 390, height: 700};+ const {trigger} = await hoverTallTrigger(page, viewport, 200);+ const s = await expectStillAndClear(page, trigger, viewport);+ expect(s.top).toBeGreaterThanOrEqual(trigger.bottom);+ await expectScrollsInside(page);+});++test('phone: with no room beside, it opens above when above has more room', async ({+ page,+}) => {+ const viewport = {width: 390, height: 700};+ const {trigger} = await hoverTallTrigger(page, viewport, 500);+ const s = await expectStillAndClear(page, trigger, viewport);+ expect(s.bottom).toBeLessThanOrEqual(trigger.top);+ await expectScrollsInside(page);+});++test('a tooltip that fits above still opens above, unscrolled', async ({+ page,+}) => {+ await page.setViewportSize({width: 900, height: 600});+ 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 trigger.scrollIntoViewIfNeeded();+ await trigger.hover();+ await expect(page.getByRole('tooltip')).toBeVisible();+ const t = await rect(page, TRIGGER);+ const s = await rect(page, TOOLTIP);+ expect(s.bottom).toBeLessThanOrEqual(t.top);+ const metrics = await page.evaluate(sel => {+ const el = document.querySelector(sel) as HTMLElement;+ return {scrollHeight: el.scrollHeight, clientHeight: el.clientHeight};+ }, TOOLTIP);+ expect(metrics.scrollHeight).toBe(metrics.clientHeight);+});++test('a wheel over a tooltip that fits still scrolls the page', async ({+ page,+}) => {+ const viewport = {width: 900, height: 600};+ await hoverTallTrigger(page, viewport, 300, 'content:A+short+tooltip');+ const s = await rect(page, TOOLTIP);+ // The hover bridge keeps it open while the pointer is on its surface.+ await page.mouse.move((s.left + s.right) / 2, (s.top + s.bottom) / 2, {+ steps: 4,+ });+ const before = await page.evaluate(() => window.scrollY);+ await page.mouse.wheel(0, 300);+ await expect+ .poll(async () => page.evaluate(() => window.scrollY))+ .toBeGreaterThan(before);+ // It has no scroll range of its own, and it is still open.+ const metrics = await page.evaluate(sel => {+ const el = document.querySelector(sel) as HTMLElement;+ return {scrollHeight: el.scrollHeight, clientHeight: el.clientHeight};+ }, TOOLTIP);+ expect(metrics.scrollHeight).toBe(metrics.clientHeight);+ await expect(page.getByRole('tooltip')).toBeVisible();+});++test('a horizontal wheel over a tall tooltip still scrolls a wide page', async ({+ page,+}) => {+ // The tooltip scrolls only on the block axis, so only that axis is+ // contained (spec:AST-025 FR14): a horizontal wheel over it moves on to the+ // page.+ const viewport = {width: 1280, height: 720};+ await page.setViewportSize(viewport);+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content&viewMode=story`,+ );+ await holdMotionStill(page);+ await page.addStyleTag({content: '#storybook-root{min-width:300vw}'});+ const trigger = page.getByRole('button', {name: 'Hover for details'});+ await expect(trigger).toBeVisible();+ await page.evaluate(sel => {+ const el = document.querySelector(sel) as HTMLElement;+ const r = el.getBoundingClientRect();+ window.scrollBy(r.left + r.width / 2 - 640, r.top + r.height / 2 - 360);+ }, TRIGGER);+ const t = await rect(page, TRIGGER);+ await page.mouse.move((t.left + t.right) / 2, (t.top + t.bottom) / 2);+ await expect(page.getByRole('tooltip')).toBeVisible();+ await page.waitForTimeout(200);+ const s = 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(metrics.scrollHeight).toBeGreaterThan(metrics.clientHeight);+ await page.mouse.move((s.left + s.right) / 2, (s.top + s.bottom) / 2, {+ steps: 4,+ });+ const before = await page.evaluate(() => window.scrollX);+ await page.mouse.wheel(300, 0);+ await expect+ .poll(async () => page.evaluate(() => window.scrollX))+ .toBeGreaterThan(before);+});++test('content that grows while the tooltip is open never leaves it over its trigger', async ({+ page,+}) => {+ const viewport = {width: 1280, height: 720};+ const {trigger} = await hoverTallTrigger(+ page,+ viewport,+ 360,+ 'content:A+short+tooltip',+ );+ // It fits above, unscrolled.+ const s = await rect(page, TOOLTIP);+ expect(s.bottom).toBeLessThanOrEqual(trigger.top);+ // Record the tooltip's box from a ResizeObserver created now, after the+ // runtime's own: observers run in creation order after layout and before+ // paint, so this one sees the geometry the frame paints.+ await page.evaluate(sel => {+ const el = document.querySelector(sel) as HTMLElement;+ const w = window as unknown as {__settled: Box[]};+ w.__settled = [];+ const observer = new ResizeObserver(() => {+ const r = el.getBoundingClientRect();+ w.__settled.push({+ top: r.top,+ bottom: r.bottom,+ left: r.left,+ right: r.right,+ });+ });+ observer.observe(el);+ if (el.firstElementChild) {+ observer.observe(el.firstElementChild);+ }+ }, TOOLTIP);+ // Let the observer deliver its initial report first.+ await page.evaluate(+ async () =>+ new Promise(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(resolve)),+ ),+ );+ // Sixty more lines arrive while the pointer rests on the trigger.+ await page.evaluate(sel => {+ const content = document.querySelector(sel)?.firstElementChild;+ for (let i = 1; i <= 60; i++) {+ const line = document.createElement('div');+ line.textContent = `Line ${i} that arrived while the tooltip was open`;+ content?.appendChild(line);+ }+ }, TOOLTIP);+ await page.waitForTimeout(100);+ const settled = await page.evaluate(+ () => (window as unknown as {__settled: Box[]}).__settled,+ );+ // The first entry is the observer's initial report, before the growth.+ expect(settled.length).toBeGreaterThan(1);+ for (const [i, frame] of settled.entries()) {+ expect(overlaps(frame, trigger), `frame ${i} covers the trigger`).toBe(+ false,+ );+ }+ // A frame callback runs before the observers that settle a resize, so only+ // frames after the growth settled are compared here.+ await expectStillAndClear(+ page,+ trigger,+ viewport,+ (await framesFrom(page)).length,+ );+ await expectScrollsInside(page);+});++test('a held-open tooltip whose host moves keeps its trigger clear', async ({+ page,+}) => {+ await page.setViewportSize({width: 1280, height: 720});+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tooltip--tall-content-moving-host&viewMode=story`,+ );+ await holdMotionStill(page);+ await watchTooltip(page);+ const trigger = page.getByRole('button', {name: 'Tall tooltip trigger'});+ await expect(page.getByRole('tooltip')).toBeVisible();+ const t = await trigger.boundingBox();+ if (t == null) {+ throw new Error('the trigger has no layout box');+ }+ const triggerBox = {+ top: t.y,+ bottom: t.y + t.height,+ left: t.x,+ right: t.x + t.width,+ };+ await page.evaluate(sel => {+ const el = document.querySelector(sel) as HTMLElement & {__first?: true};+ el.__first = true;+ }, TOOLTIP);+ expect(overlaps(await rect(page, TOOLTIP), triggerBox)).toBe(false);++ const start = (await framesFrom(page)).length;+ await page.getByRole('button', {name: "Move the tooltip's host"}).click();+ // The layer was hosted elsewhere and remounted as a new element.+ await expect+ .poll(async () =>+ page.evaluate(sel => {+ const el = document.querySelector(sel) as HTMLElement & {+ __first?: true;+ };+ return el != null && el.__first !== true;+ }, TOOLTIP),+ )+ .toBe(true);+ await page.waitForTimeout(200);+ const moved = await framesFrom(page, start);+ expect(moved.length).toBeGreaterThan(0);+ for (const [i, frame] of moved.entries()) {+ expect(overlaps(frame, triggerBox), `frame ${i} covers the trigger`).toBe(+ false,+ );+ }+ expect(overlaps(await rect(page, TOOLTIP), triggerBox)).toBe(false);+});++test('a held-open tooltip keeps a replaced trigger clear when the replacement resizes', async ({+ page,+}) => {+ const top = await openReplacedTrigger(page);+ // It grows from 32px to 342px tall, upward from its bottom edge: its top+ // rises by 310px and the tooltip fits neither above nor below it. A ResizeObserver reports that before paint, so no frame shows the+ // overlap.+ const frames = await moveAndSampleFrames(page, TRIGGER_2, {+ blockSize: '342px',+ });+ const after = await rect(page, TRIGGER_2);+ expect(Math.round(after.top)).toBe(Math.round(top) - 310);+ for (const [i, frame] of frames.entries()) {+ expect(+ overlaps(frame.tooltip, frame.trigger),+ `frame ${i} covers the trigger`,+ ).toBe(false);+ }+ expect(overlaps(await rect(page, TOOLTIP), after)).toBe(false);+});++async function hasSwitched(page: Page): Promise<boolean | undefined> {+ return page.evaluate(+ sel =>+ document.querySelector(sel)?.hasAttribute('data-astryx-clears-anchor'),+ TOOLTIP,+ );+}++test('with motion allowed, a tooltip that fits does not switch at open, and fitting growth keeps its own size and flips', async ({+ page,+}) => {+ // The entry animation moves the tooltip toward its trigger, scaled down,+ // while it enters. The clearance read uses the settled box, so a 28px+ // tooltip that fits above its trigger stays on the standard list.+ await page.setViewportSize({width: 390, height: 700});+ 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;+ const r = el.getBoundingClientRect();+ window.scrollBy(0, r.top + r.height / 2 - 200);+ }, TRIGGER);+ const t = await rect(page, TRIGGER);+ await 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);+ 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:+ // it flips below at its own size, with nothing to scroll.+ await page.evaluate(sel => {+ const content = document.querySelector(sel)?.firstElementChild;+ for (let i = 1; i <= 13; i++) {+ const line = document.createElement('div');+ line.textContent = `Line ${i}`;+ content?.appendChild(line);+ }+ }, TOOLTIP);+ await page.waitForTimeout(400);+ expect(await hasSwitched(page)).toBe(false);+ 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(t.bottom);+ expect(grown.bottom - grown.top).toBeLessThan(400);+ expect(metrics.scrollHeight).toBeLessThanOrEqual(metrics.clientHeight + 1);+});diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsxindex c99b7015e1..56b7e74b62 100644--- a/packages/core/src/Tooltip/useTooltip.tsx+++ b/packages/core/src/Tooltip/useTooltip.tsx@@ -21,7 +21,7 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import {- useLayer,+ useLayerInternal,type ContextRenderProps,type LayerAlignment,type LayerPlacement,@@ -279,10 +279,15 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {onHide,} = options;- const layer = useLayer({+ // A tooltip stays open while its trigger is hovered, so it must never settle+ // over the trigger: content taller than the room above and below opens+ // beside it, or on the roomier side sized to that room, and scrolls what does not+ // fit inside the surface, which stays hoverable (spec:AST-059 FR4).+ const layer = useLayerInternal({mode: 'context',onShow,onHide,+ keepsAnchorClear: true,});const {ref: layerRef,