An open source design system that's fully customizable and agent ready
TypeScript
fix(Layer): a closed layer's trigger is no CSS anchor (#9963)
Christopher Chedeau5c91e81ee776
diff --git a/.changeset/layer-closed-trigger-no-anchor.md b/.changeset/layer-closed-trigger-no-anchor.mdnew file mode 100644index 0000000000..157c52c317--- /dev/null+++ b/.changeset/layer-closed-trigger-no-anchor.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A layer's trigger (Tooltip, Popover, HoverCard, DropdownMenu, ContextMenu and every other `useLayer` caller) now carries its CSS `anchor-name` only while the layer is shown or its exit animation runs. A closed trigger is no anchor, so in WebKit's Linux ports a transform animation on an element that contains a closed trigger keeps running while the main thread is busy. A layer that fades out keeps its trigger's anchor name until the fade ends. If you write a layer's `anchorId` as an anchor name yourself, write it only while the layer is shown or its exit animation runs.++@vjeuxdiff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.mdindex dbb4db24b8..8eb9f41c6f 100644--- a/docs/architecture/layer-runtime.md+++ b/docs/architecture/layer-runtime.md@@ -44,6 +44,7 @@ verified_by:packages/core/src/hooks/useMenuHover.test.tsx,packages/core/src/Toast/ToastViewport.test.tsx,packages/core/src/Toast/ToastViewport.modalHost.test.tsx,+ packages/core/src/Tooltip/__tests__/TooltipClosedTriggerAnchor.interaction.browser.spec.ts,]deciding_specs: [spec:AST-038, spec:AST-059]---@@ -65,7 +66,8 @@ deciding_specs: [spec:AST-038, spec:AST-059]"INV12","INV14","INV15",- "INV17"+ "INV17",+ "INV18"],"layout": ["INV3", "INV11", "INV12"]}@@ -537,6 +539,9 @@ layers use Layer rendering without joining Escape/platform dismissal.layer stops at its own root. The native event is not stopped, so documentand window listeners and light dismiss still receive it. Keyboard, focus,input, wheel, and drag events are out of scope.+- **INV18 — Only a shown layer's trigger is an anchor.**+ A trigger carries its CSS anchor name only while its layer is shown; a closed trigger is not an anchor, so a surface that moves around it keeps its transform animation off the main thread.+ A layer that animates out counts as shown until its animations end.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@@ -710,6 +715,7 @@ this current architecture record.| INV10 | `LayerProvider.tsx`, `LayerProvider.test.tsx`, `useToast.tsx`, `ToastViewport.test.tsx`, and `ToastViewport.modalHost.test.tsx` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, or a default provider renders differently from no provider || 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 |Current unit coverage proves emitted styles, reducers, state transitions, and DOMplacement. Native Popover, `<dialog>`, focus, top-layer ordering, and rendereddiff --git a/docs/specs/components/Popover/Popover.spec.md b/docs/specs/components/Popover/Popover.spec.mdindex a4cc71dcbb..82067f19c6 100644--- a/docs/specs/components/Popover/Popover.spec.md+++ b/docs/specs/components/Popover/Popover.spec.md@@ -152,7 +152,7 @@ table owns their semantic effect.| Output concept | Meaning and lifetime || --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Trigger binding | A ref binding establishes the anchor while attached; ARIA trigger state tracks the current role and open state; a stable anchor identifier supports advanced composition. Detaching the trigger removes its anchor association. |+| Trigger binding | While the popover shows or animates out, the attached trigger is its anchor; ARIA trigger state tracks the current role and open state; a stable anchor identifier supports advanced composition. Detaching removes the anchor. || Visibility operations | `show`, `hide`, and `toggle` are the canonical operations for the mounted hook instance. Public signatures remain unchanged, and every opening path inherits same-gesture reopen protection. || Open state | Reflects the hook's reconciled visibility. Browser-initiated close is observed on the queued native toggle event, so DOM visibility may lead React state briefly. || Surface binding | A content ref identifies the focus-trap surface while mounted. |@@ -161,8 +161,9 @@ table owns their semantic effect.### Side effects and lifetime-- Attaching the trigger ref assigns and removes the CSS anchor name used by the- Layer runtime.+- While the popover is shown, and until its exit animations end, the attached+ trigger carries the CSS anchor name used by the Layer runtime+ (`architecture:layer-runtime` INV18). Detaching the trigger removes it.- Every opening path applies same-gesture reopen protection before changingvisibility. A rejected opening does not invoke `onShow`.- Successful visibility operations call the browser popover methods whendiff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsxindex e14cd2eeda..3d321df7fb 100644--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx@@ -1080,8 +1080,11 @@ describe('ContextMenu compound mode', () => {);const anchor = getCursorAnchor(screen.getByTestId('ctx'));expect(anchor.tagName).toBe('SPAN');- // Carries an anchor-name so the menu can be anchored to it via CSS- // anchor positioning (context mode), not fixed viewport coordinates.+ // Carries an anchor-name while the menu is open, so the menu is+ // anchored to it via CSS anchor positioning (context mode), not fixed+ // viewport coordinates. Closed, it is no anchor.+ expect(anchor.style.anchorName).toBe('');+ openMenu();expect(anchor.style.anchorName).toMatch(/^--astryx-layer-/);// Owns a box: WebKit counts an empty anchor box inside a scroll// container as clipped, and `position-visibility` hides the menu.diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsxindex 93de5e8543..f8b25a4edb 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx@@ -4688,9 +4688,12 @@ describe('DropdownMenu trigger refs across renders', () => {}const {rerender} = render(<Menu count={0} />);const trigger = screen.getByRole('button', {name: /^Menu/});+ // Neither the closed menu nor the closed tooltip makes it an anchor.+ expect(anchorNames(trigger)).toBe('');+ // The open menu's anchor, on the trigger that also carries the tooltip.+ fireEvent.click(trigger);const before = anchorNames(trigger);- // The menu's anchor and the tooltip's, on one element.- expect(before.split(',')).toHaveLength(2);+ expect(before.split(',')).toHaveLength(1);const stopWatching = watchStyleWrites(trigger);rerender(<Menu count={1} />);@@ -4716,8 +4719,10 @@ describe('DropdownMenu trigger refs across renders', () => {}const {rerender} = render(<Menu count={0} />);const trigger = screen.getByRole('button', {name: 'Actions'});+ expect(anchorNames(trigger)).toBe('');+ fireEvent.click(trigger);const before = anchorNames(trigger);- expect(before.split(',')).toHaveLength(2);+ expect(before.split(',')).toHaveLength(1);const stopWatching = watchStyleWrites(trigger);rerender(<Menu count={1} />);diff --git a/packages/core/src/HoverCard/useHoverCard.tsx b/packages/core/src/HoverCard/useHoverCard.tsxindex 0a258f2373..003b0f8a48 100644--- a/packages/core/src/HoverCard/useHoverCard.tsx+++ b/packages/core/src/HoverCard/useHoverCard.tsx@@ -177,7 +177,8 @@ export interface HoverCardReturn {/*** Ref for the positioning anchor element.- * Injects anchorName style for CSS anchor positioning.+ * While the layer is shown, and until its exit animation ends, the trigger+ * carries the layer's CSS anchor name.*/positionRef: RefCallback<HTMLElement>;@@ -191,6 +192,7 @@ export interface HoverCardReturn {/*** The CSS anchor name to use for positioning.* Use this when you need to set anchorName manually (e.g., display:contents wrapper).+ * Set it only while the layer is shown or its exit animation runs.*/anchorId: string;diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsxindex b7d8f1b3bc..203e4ebdd7 100644--- a/packages/core/src/Layer/useLayer.test.tsx+++ b/packages/core/src/Layer/useLayer.test.tsx@@ -38,6 +38,8 @@ import type {ContextLayerReturn,FixedLayerReturn,} from './useLayer';+import {useMergedRefs} from '../hooks/useMergedRefs';+import {observeBrowserHide} from './popoverOperations';function mockCSSStyleDeclaration(styles: Partial<CSSStyleDeclaration>,@@ -1672,6 +1674,315 @@ describe('useLayer', () => {});});+ describe('the trigger is an anchor only while its layer is shown', () => {+ const anchorNames = (element: Element) =>+ (element as HTMLElement).style+ .getPropertyValue('anchor-name')+ .split(',')+ .map(name => name.trim())+ .filter(Boolean);++ function SharedTriggerHarness({+ onReady,+ }: {+ onReady: (api: {+ tooltip: {show: () => void; hide: () => void};+ menu: {show: () => void; hide: () => void};+ }) => void;+ }) {+ const tooltip = useLayer({mode: 'context'});+ const menu = useLayer({mode: 'context'});+ onReady({+ tooltip: {show: tooltip.show, hide: tooltip.hide},+ menu: {show: menu.show, hide: menu.hide},+ });+ const ref = useMergedRefs(tooltip.ref, menu.ref);+ return (+ <>+ <button type="button" ref={ref}>+ Trigger+ </button>+ {tooltip.render(<span>Tooltip</span>)}+ {menu.render(<span>Menu</span>)}+ </>+ );+ }++ function SwappedTriggerHarness({+ second,+ onReady,+ }: {+ second: boolean;+ onReady: (api: {show: () => void; hide: () => void}) => void;+ }) {+ const layer = useLayer({mode: 'context'});+ onReady({show: layer.show, hide: layer.hide});+ return (+ <>+ {second ? (+ <button type="button" key="second" ref={layer.ref}>+ Second+ </button>+ ) : (+ <button type="button" key="first" ref={layer.ref}>+ First+ </button>+ )}+ {layer.render(<span>Layer content</span>)}+ </>+ );+ }++ it('gives a closed trigger no anchor name, and a shown layer\u2019s trigger its own', () => {+ const {getByRole, container} = render(<ContextLayerHarness />);+ const trigger = getByRole('button', {name: 'Trigger'});+ const layer = container.querySelector('[popover]') as HTMLElement;+ expect(anchorNames(trigger)).toEqual([]);++ fireEvent.click(trigger);++ const names = anchorNames(trigger);+ expect(names).toHaveLength(1);+ expect(layer.getAttribute('style')).toContain(names[0]);+ });++ it('takes the anchor name away when the layer hides, and when the browser closes it', () => {+ let api = {show: () => {}, hide: () => {}};+ const {getByRole, container} = render(+ <SwappedTriggerHarness second={false} onReady={a => (api = a)} />,+ );+ const trigger = getByRole('button', {name: 'First'});+ act(() => api.show());+ expect(anchorNames(trigger)).toHaveLength(1);++ act(() => api.hide());+ expect(anchorNames(trigger)).toEqual([]);++ act(() => api.show());+ expect(anchorNames(trigger)).toHaveLength(1);+ const layer = container.querySelector('[popover]') as HTMLElement;+ act(() => {+ layer.dispatchEvent(+ Object.assign(new Event('toggle'), {+ oldState: 'open',+ newState: 'closed',+ }),+ );+ });+ expect(anchorNames(trigger)).toEqual([]);+ });++ it('keeps the name while the layer fades out, and for a show during the fade', async () => {+ let api = {show: () => {}, hide: () => {}};+ const {getByRole, container} = render(+ <SwappedTriggerHarness second={false} onReady={a => (api = a)} />,+ );+ const trigger = getByRole('button', {name: 'First'});+ const layer = container.querySelector('[popover]') as HTMLElement;+ // A close fade the browser runs after the hide, as TopNavMegaMenu's.+ const fade = () => {+ let end = () => {};+ const finished = new Promise<void>(resolve => {+ end = resolve;+ });+ layer.getAnimations = () =>+ [+ {+ finished,+ playState: 'running',+ effect: {getComputedTiming: () => ({endTime: 200})},+ },+ ] as unknown as Animation[];+ return {end, finished};+ };++ let exit = fade();+ act(() => api.show());+ act(() => api.hide());+ // Still painting, so still placed against its trigger.+ expect(anchorNames(trigger)).toHaveLength(1);+ await act(async () => {+ exit.end();+ await exit.finished;+ });+ expect(anchorNames(trigger)).toEqual([]);++ exit = fade();+ act(() => api.show());+ act(() => api.hide());+ act(() => api.show());+ await act(async () => {+ exit.end();+ await exit.finished;+ });+ expect(anchorNames(trigger)).toHaveLength(1);+ });++ it('keeps the name on a trigger that attaches again while the layer fades out', async () => {+ let api = {show: () => {}, hide: () => {}};+ const {getByRole, container, rerender} = render(+ <SwappedTriggerHarness second={false} onReady={a => (api = a)} />,+ );+ const layer = container.querySelector('[popover]') as HTMLElement;+ let end = () => {};+ const finished = new Promise<void>(resolve => {+ end = resolve;+ });+ layer.getAnimations = () =>+ [+ {+ finished,+ playState: 'running',+ effect: {getComputedTiming: () => ({endTime: 200})},+ },+ ] as unknown as Animation[];+ act(() => api.show());+ act(() => api.hide());+ // A render during the fade attaches another trigger element.+ rerender(<SwappedTriggerHarness second onReady={a => (api = a)} />);+ const second = getByRole('button', {name: 'Second'});+ expect(anchorNames(second)).toHaveLength(1);+ await act(async () => {+ end();+ await finished;+ });+ expect(anchorNames(second)).toEqual([]);+ });++ it('keeps the name for a show the browser refuses while the layer fades out', async () => {+ let api = {show: () => {}, hide: () => {}};+ const {getByRole, container} = render(+ <SwappedTriggerHarness second={false} onReady={a => (api = a)} />,+ );+ const trigger = getByRole('button', {name: 'First'});+ const layer = container.querySelector('[popover]') as HTMLElement;+ let end = () => {};+ const finished = new Promise<void>(resolve => {+ end = resolve;+ });+ layer.getAnimations = () =>+ [+ {+ finished,+ playState: 'running',+ effect: {getComputedTiming: () => ({endTime: 200})},+ },+ ] as unknown as Animation[];+ act(() => api.show());+ act(() => api.hide());+ // Another popover's hide, which the browser runs itself, is in flight,+ // and the browser refuses the show.+ const other = document.createElement('div');+ document.body.append(other);+ observeBrowserHide(other);+ const refuse = vi.spyOn(layer, 'showPopover').mockImplementation(() => {+ throw new DOMException(+ 'Invalid to show a popover during another show operation',+ 'InvalidStateError',+ );+ });+ act(() => api.show());+ expect(anchorNames(trigger)).toHaveLength(1);+ refuse.mockRestore();+ // A hide forgets the parked show; the fade still paints.+ act(() => api.hide());+ expect(anchorNames(trigger)).toHaveLength(1);+ other.dispatchEvent(new Event('toggle'));+ other.remove();+ await act(async () => {+ end();+ await finished;+ });+ expect(anchorNames(trigger)).toEqual([]);+ });++ it('takes the name away at once when the layer\u2019s only animation is paused', () => {+ let api = {show: () => {}, hide: () => {}};+ const {getByRole, container} = render(+ <SwappedTriggerHarness second={false} onReady={a => (api = a)} />,+ );+ const trigger = getByRole('button', {name: 'First'});+ const layer = container.querySelector('[popover]') as HTMLElement;+ // A paused animation never finishes, so it must not hold the name.+ layer.getAnimations = () =>+ [+ {+ finished: new Promise(() => {}),+ playState: 'paused',+ effect: {getComputedTiming: () => ({endTime: 200})},+ },+ ] as unknown as Animation[];+ act(() => api.show());+ act(() => api.hide());+ expect(anchorNames(trigger)).toEqual([]);+ });++ it('takes the name away at once when the layer only runs an animation that never ends', () => {+ let api = {show: () => {}, hide: () => {}};+ const {getByRole, container} = render(+ <SwappedTriggerHarness second={false} onReady={a => (api = a)} />,+ );+ const trigger = getByRole('button', {name: 'First'});+ const layer = container.querySelector('[popover]') as HTMLElement;+ layer.getAnimations = () =>+ [+ {+ finished: new Promise(() => {}),+ playState: 'running',+ effect: {getComputedTiming: () => ({endTime: Infinity})},+ },+ ] as unknown as Animation[];+ act(() => api.show());+ act(() => api.hide());+ expect(anchorNames(trigger)).toEqual([]);+ });++ it('keeps each layer\u2019s name on a shared trigger for as long as that layer is shown', () => {+ let api = {+ tooltip: {show: () => {}, hide: () => {}},+ menu: {show: () => {}, hide: () => {}},+ };+ const {getByRole} = render(+ <SharedTriggerHarness onReady={a => (api = a)} />,+ );+ const trigger = getByRole('button', {name: 'Trigger'});+ expect(anchorNames(trigger)).toEqual([]);++ act(() => api.tooltip.show());+ const [tooltipName] = anchorNames(trigger);+ act(() => api.menu.show());+ expect(anchorNames(trigger)).toHaveLength(2);+ const menuName = anchorNames(trigger).find(name => name !== tooltipName);++ act(() => api.tooltip.hide());+ expect(anchorNames(trigger)).toEqual([menuName]);+ act(() => api.menu.hide());+ expect(anchorNames(trigger)).toEqual([]);+ });++ it('moves the name to a trigger that replaces a shown layer\u2019s, and gives none to one that replaces a closed layer\u2019s', () => {+ let api = {show: () => {}, hide: () => {}};+ const {getByRole, rerender} = render(+ <SwappedTriggerHarness second={false} onReady={a => (api = a)} />,+ );+ const first = getByRole('button', {name: 'First'});+ act(() => api.show());++ rerender(<SwappedTriggerHarness second onReady={a => (api = a)} />);++ const second = getByRole('button', {name: 'Second'});+ expect(anchorNames(first)).toEqual([]);+ expect(anchorNames(second)).toHaveLength(1);++ act(() => api.hide());+ rerender(+ <SwappedTriggerHarness second={false} onReady={a => (api = a)} />,+ );+ expect(anchorNames(getByRole('button', {name: 'First'}))).toEqual([]);+ expect(anchorNames(second)).toEqual([]);+ });+ });+describe('when the Popover API is unsupported (Safari <17 / Firefox <125)', () => {it('show() does not throw when showPopover is undefined and the layer becomes visible', () => {// Simulate a browser without the Popover API (finding infra-4).diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex a1b531ff3d..5e30b548c9 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -354,13 +354,15 @@ export interface FixedLayerOptions extends BaseLayerOptions {export interface ContextLayerReturn {/*** Ref to attach to trigger element.- * Injects anchorName style for CSS anchor positioning.+ * While the layer is shown, and until its exit animation ends, the trigger+ * carries the layer's CSS anchor name.*/ref: RefCallback<HTMLElement>;/*** The CSS anchor name to use for positioning.* Use this when you need to set anchorName manually (e.g., display:contents wrapper).+ * Set it only while the layer is shown or its exit animation runs.*/anchorId: string;@@ -547,6 +549,24 @@ function untransform(return new DOMRect(left, top, width, height);}+/**+ * The finite animations still running on `layer` and its content. A layer+ * that fades out keeps running them after the browser hides it, and it stays+ * placed against its anchor until they end.+ */+function exitAnimations(layer: HTMLElement | null): Animation[] {+ if (layer == null || typeof layer.getAnimations !== 'function') {+ return [];+ }+ return layer+ .getAnimations({subtree: true})+ .filter(+ animation =>+ animation.playState === 'running' &&+ animation.effect?.getComputedTiming().endTime !== Infinity,+ );+}+/*** 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@@ -1216,6 +1236,41 @@ function useLayerImplementation(// stale-closure reads of the previous isOpen value.const isOpenRef = useRef(false);+ // The exit of the layer that closed last, while it still paints. Its+ // trigger stays an anchor until it ends, also when the trigger attaches+ // again during it. Null once it has ended.+ const exitRef = useRef<object | null>(null);++ // A closed trigger is no anchor, once the layer stops painting. A show+ // during the exit keeps the name, and so does a later exit.+ const releaseAnchor = useCallback(+ (layer: HTMLElement | null) => {+ const exit = {};+ exitRef.current = exit;+ const release = () => {+ if (exitRef.current !== exit) {+ return;+ }+ exitRef.current = null;+ const trigger = triggerRef.current;+ if (!isOpenRef.current && trigger != null) {+ removeAnchorName(trigger, anchorId);+ }+ };+ const running = exitAnimations(layer);+ if (running.length === 0) {+ release();+ return;+ }+ void Promise.all(+ running.map(async animation =>+ animation.finished.catch(() => undefined),+ ),+ ).then(release);+ },+ [anchorId],+ );+// The gesture during which the browser last closed this layer on its own.// Read through wasJustDismissed by triggers deciding whether a click is// theirs to act on.@@ -1416,6 +1471,12 @@ function useLayerImplementation(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+ // layer, so the layer's first frame is placed against it.+ const anchor = triggerRef.current;+ if (anchor != null) {+ addAnchorName(anchor, anchorId);+ }// A hide the browser runs itself (an Escape its close watcher answers)// is counted too, from `beforetoggle` until the element's `toggle`, a// task after the hide has returned. The show is asked of the browser@@ -1423,6 +1484,11 @@ function useLayerImplementation(// light dismiss at pointerup, then this show at the click); only a show// it refuses replays once the hide's count has ended.if (!showPopoverElement(popover)) {+ // The replay anchors the trigger again; until then it is closed. An+ // exit still running keeps the name.+ if (anchor != null && exitRef.current == null) {+ removeAnchorName(anchor, anchorId);+ }replayWhenSettled();return;}@@ -1434,6 +1500,7 @@ function useLayerImplementation(onShow?.();}}, [+ anchorId,onShow,keepsAnchorClear,requestContextMount,@@ -1470,8 +1537,9 @@ function useLayerImplementation(setIsOpen(false);onHide?.();}+ releaseAnchor(popoverRef.current);clearContextMount();- }, [onHide, clearContextMount]);+ }, [onHide, clearContextMount, releaseAnchor]);// A deferred show() replays through a ref so the queued closure reaches the// current callback rather than the one captured when it was queued.@@ -1493,7 +1561,11 @@ function useLayerImplementation(removeAnchorName(triggerRef.current, anchorId);}- if (el) {+ // Only a shown layer's trigger is an anchor. WebKit's Linux ports run the+ // transform animation of an element that holds an anchor on the main+ // thread. A busy task would then freeze a surface that moves around a+ // closed trigger.+ if (el && (isOpenRef.current || exitRef.current != null)) {addAnchorName(el, anchorId);}@@ -1603,12 +1675,13 @@ function useLayerImplementation(rememberDismissal((e.currentTarget as HTMLElement | null)?.ownerDocument ?? document,);+ releaseAnchor(e.currentTarget as HTMLElement | null);setIsOpen(false);onHide?.();clearContextMount();}},- [onHide, clearContextMount, rememberDismissal],+ [onHide, clearContextMount, rememberDismissal, releaseAnchor],);// Ref callback for popover element — sets up the `toggle` listener.diff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsxindex ff51e0f451..5c3e24039a 100644--- a/packages/core/src/Popover/Popover.test.tsx+++ b/packages/core/src/Popover/Popover.test.tsx@@ -1666,13 +1666,22 @@ describe('usePopover trigger ref', () => {function Trigger({count}: {count: number}) {const popover = usePopover({onShow: () => {}, onHide: () => {}});return (- <button type="button" ref={popover.triggerRef}>- Open {count}- </button>+ <>+ <button+ type="button"+ ref={popover.triggerRef}+ onClick={() => popover.show()}>+ Open {count}+ </button>+ {popover.render(<span>Details</span>)}+ </>);}const {rerender} = render(<Trigger count={0} />);const trigger = screen.getByRole('button', {name: /^Open/});+ // A closed popover's trigger is no anchor; a shown one's is.+ expect(trigger.style.getPropertyValue('anchor-name')).toBe('');+ fireEvent.click(trigger);const anchorName = trigger.style.getPropertyValue('anchor-name');expect(anchorName).toMatch(/^--astryx-layer-/);const records: MutationRecord[] = [];diff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsxindex 677ec07921..6bf22e828a 100644--- a/packages/core/src/Popover/usePopover.tsx+++ b/packages/core/src/Popover/usePopover.tsx@@ -298,6 +298,7 @@ export interface UsePopoverReturn {/*** The CSS anchor name to use for positioning.* Use when you need to set anchorName manually (e.g., display:contents wrapper).+ * Set it only while the layer is shown or its exit animation runs.*/anchorId: string;diff --git a/packages/core/src/SideNav/SideNav.test.tsx b/packages/core/src/SideNav/SideNav.test.tsxindex d99bd08cf5..7ba5905e84 100644--- a/packages/core/src/SideNav/SideNav.test.tsx+++ b/packages/core/src/SideNav/SideNav.test.tsx@@ -825,10 +825,12 @@ describe('SideNavHeading collapsed', () => {const popoverEl = document.querySelector('[popover]') as HTMLElement;const anchorId = popoverEl.style.positionAnchor;expect(anchorId).not.toBe('');- const triggerAnchorNames = trigger.style.anchorName- .split(',')- .map(s => s.trim());- expect(triggerAnchorNames).toContain(anchorId);+ const triggerAnchorNames = () =>+ trigger.style.anchorName.split(',').map(s => s.trim());+ // A closed menu's trigger is no anchor; an open one's is.+ expect(triggerAnchorNames()).not.toContain(anchorId);+ fireEvent.click(trigger);+ expect(triggerAnchorNames()).toContain(anchorId);});});diff --git a/packages/core/src/Table/plugins/rowStatus/useTableRowStatus.test.tsx b/packages/core/src/Table/plugins/rowStatus/useTableRowStatus.test.tsxindex 74fa8bc824..18b4067c28 100644--- a/packages/core/src/Table/plugins/rowStatus/useTableRowStatus.test.tsx+++ b/packages/core/src/Table/plugins/rowStatus/useTableRowStatus.test.tsx@@ -200,7 +200,8 @@ describe('useTableRowStatus', () => {expect(indicator).toContainElement(glyph);expect(screen.queryByTestId('semantic-warning')).not.toBeInTheDocument();- expect(indicator.getAttribute('style')).not.toContain('--color-icon');+ // A closed tooltip leaves its trigger with no inline style at all.+ expect(indicator.getAttribute('style') ?? '').not.toContain('--color-icon');expect(glyph.parentElement).toHaveAttribute('data-color', 'warning');});diff --git a/packages/core/src/Tooltip/__tests__/TooltipClosedTriggerAnchor.interaction.browser.spec.ts b/packages/core/src/Tooltip/__tests__/TooltipClosedTriggerAnchor.interaction.browser.spec.tsnew file mode 100644index 0000000000..d8ae7437d9--- /dev/null+++ b/packages/core/src/Tooltip/__tests__/TooltipClosedTriggerAnchor.interaction.browser.spec.ts@@ -0,0 +1,243 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TooltipClosedTriggerAnchor.interaction.browser.spec.ts+ * @input The Core/Tooltip default and Core/TopNavMenu mega menu stories, the+ * interaction harness's screencast, main-thread block and compositor control+ * @output Proves a closed tooltip's trigger is no CSS anchor, so a surface that+ * moves around it keeps animating through a busy main thread. A shown+ * tooltip's trigger is its anchor until the tooltip hides. A mega menu that+ * fades out stays placed against its anchor until the fade ends.+ * @position Interaction proofs for the layer runtime's anchor names, run in+ * Chromium and WebKit+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ blockMainThread,+ busyWindowProof,+ markElement,+ openStory,+ startBusyControl,+ startScreencast,+ trackControl,+ trackMarker,+ withStorybook,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++interface Surface {+ readonly surface: Locator;+ readonly trigger: Locator;+}++// The story's root box moves, with the tooltip's trigger inside it. It rests+// `top` px down, clear of the strip the compositor control crosses.+async function openSurface(page: Page, top: number): Promise<Surface> {+ await openStory(page, storybook(), 'core-tooltip--default');+ const trigger = page.getByRole('button', {name: 'Hover me'});+ await expect(trigger).toBeVisible();+ const surface = page.locator('#storybook-root');+ await surface.evaluate((el, px) => {+ (el as HTMLElement).style.marginTop = `${px}px`;+ }, top);+ await expect(surface).toBeVisible();+ return {surface, trigger};+}++const anchorNameOf = async (element: Locator) =>+ element.evaluate(el => getComputedStyle(el).getPropertyValue('anchor-name'));++test('a surface around a closed tooltip trigger keeps moving through a 500 ms main-thread block', async ({+ page,+}) => {+ const {surface, trigger} = await openSurface(page, 60);+ test.info().annotations.push({+ type: 'closed trigger anchor-name',+ description: await anchorNameOf(trigger),+ });+ await markElement(surface);+ // Before the surface moves, so the control is on the compositor first.+ await startBusyControl(page);+ const cast = await startScreencast(page);+ await surface.evaluate(el => {+ const box = el as HTMLElement;+ box.style.willChange = 'translate';+ // About 4 px a frame, so every frame shows a whole-pixel step.+ box.animate([{translate: '0px 0px'}, {translate: '0px 560px'}], {+ duration: 2000,+ easing: 'linear',+ fill: 'both',+ });+ });+ // Two frames, so the browser has committed the animation before the block.+ await page.evaluate(+ async () =>+ new Promise(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(resolve)),+ ),+ );+ const block = await blockMainThread(page, 500, {+ during: surface,+ minProgressMs: 70,+ });+ await page.waitForTimeout(150);+ const frames = await cast.stop();+ const tracked = await trackMarker(page, frames);+ const control = await trackControl(page, frames);+ // Judged against the compositor control in the same frames: the surface+ // moves on every frame the control does.+ const proof = busyWindowProof(tracked, block, {settledWithin: 2, control});+ test.info().annotations.push({+ type: 'busy main thread',+ description: proof.summary,+ });+ expect(proof.verdict.failures, proof.summary).toEqual([]);+ expect(proof.monotonic).toBe(true);+});++test('a shown tooltip is placed against its trigger, which stays its anchor until the tooltip hides, also as the surface moves', async ({+ page,+}) => {+ // Room for the tooltip above its trigger.+ const {surface, trigger} = await openSurface(page, 200);+ // Keyboard focus shows the tooltip and holds it while the surface moves+ // away from the pointer.+ await page.keyboard.press('Tab');+ await expect(trigger).toBeFocused();+ const tooltip = page.getByRole('tooltip');+ await expect(tooltip).toBeVisible();+ expect(await anchorNameOf(trigger)).toMatch(/^--astryx-layer-/);++ // Boxes read once the tooltip's entry animation has ended.+ const boxes = async () => {+ await tooltip.evaluate(async el => {+ await Promise.all(+ el+ .getAnimations({subtree: true})+ .map(async animation => animation.finished.catch(() => undefined)),+ );+ });+ const shown = await tooltip.boundingBox();+ const anchor = await trigger.boundingBox();+ if (shown == null || anchor == null) {+ throw new Error('The tooltip or its trigger has no box.');+ }+ return {shown, anchor, gap: anchor.y - (shown.y + shown.height)};+ };+ // Above its trigger, over the trigger's centre. The viewport gutter can+ // slide it along the inline axis, so it need not be centred.+ const before = await boxes();+ expect(before.gap).toBeGreaterThanOrEqual(0);+ expect(before.gap).toBeLessThan(24);+ const centre = before.anchor.x + before.anchor.width / 2;+ expect(before.shown.x).toBeLessThanOrEqual(centre);+ expect(before.shown.x + before.shown.width).toBeGreaterThanOrEqual(centre);++ // The surface moves while the tooltip is shown: the tooltip follows its+ // anchor and keeps its gap.+ await surface.evaluate(el => {+ (el as HTMLElement).style.translate = '0px 120px';+ });+ await page.evaluate(+ async () =>+ new Promise(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(resolve)),+ ),+ );+ const moved = await boxes();+ expect(moved.anchor.y - before.anchor.y).toBeCloseTo(120, 0);+ expect(moved.shown.y - before.shown.y).toBeCloseTo(120, 0);+ expect(moved.shown.x).toBeCloseTo(before.shown.x, 0);+ expect(moved.gap).toBeCloseTo(before.gap, 0);++ await page.keyboard.press('Escape');+ await expect(tooltip).toBeHidden();+ expect(await anchorNameOf(trigger)).toBe('none');+});++test.describe('a layer that fades out', () => {+ // A desktop window, where TopNav shows its mega menu.+ test.use({+ viewport: {width: 1280, height: 800},+ isMobile: false,+ hasTouch: false,+ });++ test('stays placed against its anchor through the fade, and only then takes the anchor name away', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName === 'webkit',+ 'WebKit paints no close fade: the panel has display: none on the first frame after it closes.',+ );+ await openStory(page, storybook(), 'core-topnavmenu--mega-menu');+ // TopNav places its mega menus against its <nav>.+ const anchor = page.getByRole('navigation', {name: 'Marketing navigation'});+ await page.getByRole('button', {name: 'Products'}).click();+ const panel = page.locator('[popover]:popover-open', {+ hasText: 'Analytics',+ });+ await expect(panel).toBeVisible();+ expect(await anchorNameOf(anchor)).toMatch(/^--astryx-layer-/);+ await panel.evaluate(async el => {+ el.setAttribute('data-fading-layer', '');+ await Promise.all(+ el+ .getAnimations({subtree: true})+ .map(async animation => animation.finished.catch(() => undefined)),+ );+ });+ const open = await page.locator('[data-fading-layer]').boundingBox();+ if (open == null) {+ throw new Error('The open panel has no box.');+ }+ // Every frame from just before the close until the fade has ended: the+ // panel's box, its opacity and whether it is still shown.+ await page.evaluate(() => {+ const el = document.querySelector('[data-fading-layer]') as HTMLElement;+ const frames: number[][] = [];+ (window as unknown as {__fade: number[][]}).__fade = frames;+ const start = performance.now();+ const tick = () => {+ const box = el.getBoundingClientRect();+ const style = getComputedStyle(el);+ frames.push([+ box.x,+ box.y,+ Number(style.opacity),+ el.matches(':popover-open') ? 1 : 0,+ style.display === 'none' ? 0 : 1,+ ]);+ if (performance.now() - start < 1500) {+ requestAnimationFrame(tick);+ }+ };+ requestAnimationFrame(tick);+ });+ await page.keyboard.press('Escape');+ await page.waitForTimeout(1600);+ const frames = await page.evaluate(+ () => (window as unknown as {__fade: number[][]}).__fade,+ );+ const fading = frames.filter(+ ([, , opacity, shown, displayed]) =>+ shown === 0 && displayed === 1 && opacity > 0.05,+ );+ // The fade is painted: closed, still displayed and still visible.+ expect(fading.length).toBeGreaterThan(0);+ for (const [x, y] of fading) {+ expect(Math.abs(x - open.x)).toBeLessThan(2);+ // The fade lifts the panel 4 px.+ expect(Math.abs(y - open.y)).toBeLessThan(8);+ }+ await expect.poll(async () => anchorNameOf(anchor)).toBe('none');+ });+});diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsxindex 510381753e..a1733343ec 100644--- a/packages/core/src/Tooltip/useTooltip.tsx+++ b/packages/core/src/Tooltip/useTooltip.tsx@@ -185,7 +185,8 @@ export interface TooltipReturn {/*** Ref for the positioning anchor element.- * Injects anchorName style for CSS anchor positioning.+ * While the layer is shown, and until its exit animation ends, the trigger+ * carries the layer's CSS anchor name.*/positionRef: RefCallback<HTMLElement>;@@ -199,6 +200,7 @@ export interface TooltipReturn {/*** The CSS anchor name to use for positioning.* Use this when you need to set anchorName manually (e.g., display:contents wrapper).+ * Set it only while the layer is shown or its exit animation runs.*/anchorId: string;