Skip to content

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

TypeScript

fix(layer): host layers outside the ancestors that break them (#5039)

Cindy Zhang5db7f15bd022
diff --git a/.changeset/lucky-layers-travel.md b/.changeset/lucky-layers-travel.md
new file mode 100644
index 0000000000..2389b4a63f
--- /dev/null
+++ b/.changeset/lucky-layers-travel.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Layer: use an inert `<template>` marker to find each context layer's actual JSX position. Safe positions stay inline; positions inside a paragraph, link, button, inline formatting, or a structurally restricted container portal to the nearest safe ancestor. Corrective portals keep CSS custom properties inheriting from that nearby host while preserving direction and writing mode, and `show()` passes the trigger as the popover's invoker `source`. The new `lazyMount` option waits until opening to resolve and mount content; HoverCard uses it so rich content never enters an invalid paragraph during initial render and unmounts again when hidden. Other context layers keep their existing closed-content behavior.
+@cixzhang
diff --git a/apps/storybook/stories/Layer.stories.tsx b/apps/storybook/stories/Layer.stories.tsx
index c44953e873..07f6c8ce87 100644
--- a/apps/storybook/stories/Layer.stories.tsx
+++ b/apps/storybook/stories/Layer.stories.tsx
@@ -1,6 +1,6 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {useState} from 'react';
+import {useRef, useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
import * as stylex from '@stylexjs/stylex';
import {useLayer} from '@astryxdesign/core/Layer';
@@ -223,3 +223,186 @@ function LayerProviderDemo() {
export const Provider: Story = {
render: () => <LayerProviderDemo />,
};
+
+const FILLER =
+ 'Sequential focus follows DOM order, so where a layer is hosted decides what the browser does when focus moves into it. This paragraph is filler, so the container has something to scroll.';
+
+interface HostingProbe {
+ parentTag: string;
+ insideParagraph: boolean;
+ fontSize: string;
+}
+
+function describeFocus(): string {
+ const el = document.activeElement as HTMLElement | null;
+ if (!el || el === document.body) {
+ return 'nothing';
+ }
+ const label = el.textContent?.trim().slice(0, 20);
+ const tag = el.tagName.toLowerCase();
+ return label ? `${tag} "${label}"` : tag;
+}
+
+function InlineHostingDemo() {
+ const layer = useLayer({
+ mode: 'context',
+ lightDismiss: true,
+ lazyMount: true,
+ });
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const paragraphRef = useRef<HTMLParagraphElement>(null);
+ const [probe, setProbe] = useState<HostingProbe | null>(null);
+ const [events, setEvents] = useState<string[]>([]);
+
+ // Samples the scroll offset on both sides of a frame: the browser's
+ // scroll-into-view for the newly focused element lands in between.
+ const record = (label: string, watchScroll = true) => {
+ const before = Math.round(scrollRef.current?.scrollTop ?? 0);
+ requestAnimationFrame(() => {
+ const after = Math.round(scrollRef.current?.scrollTop ?? 0);
+ const scroll = !watchScroll
+ ? `scrollTop ${after}`
+ : before === after
+ ? `scrollTop ${after} (no jump)`
+ : `scrollTop ${before} → ${after}`;
+ const popover = document.getElementById(layer.id);
+ setProbe(
+ popover
+ ? {
+ parentTag: popover.parentElement?.tagName.toLowerCase() ?? '—',
+ insideParagraph: paragraphRef.current?.contains(popover) ?? false,
+ fontSize: window.getComputedStyle(popover).fontSize,
+ }
+ : null,
+ );
+ setEvents(prev =>
+ [`${label} — focus: ${describeFocus()} — ${scroll}`, ...prev].slice(
+ 0,
+ 6,
+ ),
+ );
+ });
+ };
+
+ return (
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 12,
+ maxWidth: 520,
+ }}>
+ <Button label="Before the article" />
+
+ <div
+ ref={scrollRef}
+ onScroll={() => record('scrolled', false)}
+ onFocusCapture={() => record('focus moved')}
+ style={{
+ height: 200,
+ overflow: 'auto',
+ padding: 16,
+ border: '1px solid var(--color-border-default)',
+ borderRadius: 8,
+ }}>
+ <p style={{fontSize: 13, textAlign: 'center'}}>{FILLER}</p>
+ <p style={{fontSize: 13, textAlign: 'center'}}>{FILLER}</p>
+ <p style={{fontSize: 13, textAlign: 'center'}}>{FILLER}</p>
+ <p ref={paragraphRef} style={{fontSize: 13, textAlign: 'center'}}>
+ Reviewed by{' '}
+ <button
+ ref={layer.ref}
+ type="button"
+ onClick={() => {
+ if (layer.isOpen) {
+ layer.hide();
+ } else {
+ layer.show();
+ }
+ record('toggled the card');
+ }}
+ style={{
+ font: 'inherit',
+ color: 'var(--color-content-link)',
+ background: 'none',
+ border: 'none',
+ padding: 0,
+ cursor: 'pointer',
+ textDecoration: 'underline',
+ }}>
+ Jane Doe
+ </button>{' '}
+ earlier today, from inside a 13px centered paragraph.
+ {layer.render(
+ <div {...stylex.props(styles.popoverContent)} style={{width: 240}}>
+ <Text type="body">Jane Doe</Text>
+ <div style={{display: 'flex', gap: 8, marginTop: 8}}>
+ <Button label="Follow" variant="primary" />
+ <Button label="Message" />
+ </div>
+ </div>,
+ {
+ placement: 'below',
+ alignment: 'start',
+ offset: 8,
+ role: 'dialog',
+ 'aria-label': 'Jane Doe',
+ },
+ )}
+ </p>
+ <p style={{fontSize: 13, textAlign: 'center'}}>{FILLER}</p>
+ <p style={{fontSize: 13, textAlign: 'center'}}>{FILLER}</p>
+ <p style={{fontSize: 13, textAlign: 'center'}}>{FILLER}</p>
+ </div>
+
+ <Button label="After the article" />
+
+ <Text type="supporting">
+ Tab in from the button above: the browser scrolls the trigger into view.
+ Open the card, then Tab from the trigger into it and out the far side.
+ Every move is logged with the container&apos;s scroll offset before and
+ after the browser&apos;s scroll-into-view.
+ </Text>
+
+ <dl
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'max-content max-content',
+ gap: '2px 12px',
+ fontSize: 13,
+ margin: 0,
+ }}>
+ <dt>Layer&apos;s parent</dt>
+ <dd style={{margin: 0}}>
+ <code>{probe?.parentTag ?? 'not rendered yet'}</code>
+ </dd>
+ <dt>Inside the paragraph</dt>
+ <dd style={{margin: 0}}>
+ <code>{probe ? String(probe.insideParagraph) : '—'}</code>
+ </dd>
+ <dt>Card font size</dt>
+ <dd style={{margin: 0}}>
+ <code>{probe?.fontSize ?? '—'}</code>
+ </dd>
+ </dl>
+
+ <ol style={{fontSize: 13, lineHeight: 1.6, paddingInlineStart: 20}}>
+ {events.map((event, i) => (
+ <li key={`${event}-${i}`}>{event}</li>
+ ))}
+ </ol>
+ </div>
+ );
+}
+
+export const InlineTriggerHosting: Story = {
+ render: () => <InlineHostingDemo />,
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'A closed context layer leaves only an inert marker at its JSX position. When opened from this unsafe paragraph, the final layer is lazily portaled to the nearest ancestor that can contain it; a layer at a safe position would stay inline. The readout shows where the layer landed and what typography it inherits; the log shows what the browser scrolls as focus moves into and out of it.',
+ },
+ },
+ },
+};
diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsx
index 88191f9821..1f16a532a2 100644
--- a/packages/core/src/Button/Button.tsx
+++ b/packages/core/src/Button/Button.tsx
@@ -438,8 +438,10 @@ const loadingStyles = stylex.create({
*
* Layers always carry the native `popover` attribute (useLayer.tsx), and a
* popover is never an in-flow member — it is `display: none` until shown, then
- * promoted to the top layer. So "last member" is: no following element sibling
- * that isn't a popover.
+ * promoted to the top layer. Context layers also retain an inert `<template>`
+ * marker so they can re-resolve their JSX position. Neither element is a group
+ * member, so "last member" is: no following element sibling besides those two
+ * pieces of layer infrastructure.
*
* Reading it the other way round — marking the *buttons* and testing for a
* marked sibling — is the trap: it silently reclassifies anything it doesn't
@@ -455,7 +457,7 @@ const loadingStyles = stylex.create({
* The leading edge still uses `:first-child` — a member's button always precedes
* its own layer, so the first button is genuinely `:first-child`.
*/
-const IS_LAST_ITEM = ':not(:has(~ *:not([popover])))';
+const IS_LAST_ITEM = ':not(:has(~ *:not([popover]):not(template)))';
const groupStyles = stylex.create({
horizontal: {
diff --git a/packages/core/src/ButtonGroup/ButtonGroup.test.tsx b/packages/core/src/ButtonGroup/ButtonGroup.test.tsx
index 8f49f033ef..6dcf4280eb 100644
--- a/packages/core/src/ButtonGroup/ButtonGroup.test.tsx
+++ b/packages/core/src/ButtonGroup/ButtonGroup.test.tsx
@@ -202,9 +202,9 @@ describe('ButtonGroup', () => {
// Trailing radius (issue #2508)
//
// The trailing end cap cannot be keyed off `:last-child`: members render an
- // invisible layer AFTER their button (tooltip'd Button, DropdownMenu), and
- // useLayer renders it inline rather than portaling it, so the layer steals the
- // slot. See IS_LAST_ITEM in Button.tsx.
+ // invisible layer infrastructure AFTER their button (tooltip'd Button,
+ // DropdownMenu), and useLayer renders a marker plus the layer inline when the
+ // host is safe, so they steal the slot. See IS_LAST_ITEM in Button.tsx.
//
// HOW THESE TESTS CATCH THE BUG
// jsdom applies no StyleX CSS, so a DOM-only test cannot prove which rule
@@ -219,7 +219,9 @@ describe('ButtonGroup', () => {
describe('trailing radius (#2508)', () => {
/** The group members, in DOM order (excludes invisible layer siblings). */
const items = (group: HTMLElement): Element[] =>
- Array.from(group.querySelectorAll(':scope > *:not([popover])'));
+ Array.from(
+ group.querySelectorAll(':scope > *:not([popover]):not(template)'),
+ );
// -- Compiled CSS, read from the source -----------------------------------
@@ -375,6 +377,7 @@ describe('ButtonGroup', () => {
// .stylex.ts file it compiles to a mangled selector like `[x13pbwiz]`
// that matches nothing in the DOM.
expect(selector).toContain('[popover]');
+ expect(selector).toContain('template');
}
},
);
diff --git a/packages/core/src/HoverCard/HoverCard.doc.mjs b/packages/core/src/HoverCard/HoverCard.doc.mjs
index 5a3c6d58ea..e0d7769a32 100644
--- a/packages/core/src/HoverCard/HoverCard.doc.mjs
+++ b/packages/core/src/HoverCard/HoverCard.doc.mjs
@@ -114,7 +114,7 @@ export const docs = {
{ guidance: false, description: 'Place critical actions or required information inside a hover card; users may miss content that only appears on hover.' },
{ guidance: false, description: 'Use a hover card when a simple Tooltip or Popover would suffice.' },
{ guidance: false, description: 'Use a HoverCard for content the user must interact with; it disappears when the cursor leaves.' },
- { guidance: false, description: 'Nest a HoverCard whose content has block elements directly inside phrasing-only contexts such as a <p>, <label>, or heading. The card renders inline, so block content there is invalid HTML the browser reparents. Wrap the surrounding text in a block element (e.g. a <div>) instead.' },
+ { guidance: true, description: 'Prefer placing HoverCard in a block context rather than directly in a <p>, heading, or link. Those placements are supported when necessary through a corrective portal, but the DOM and tab order may differ.' },
],
anatomy: [
{name: 'Trigger', required: true, description: 'The element that opens the hover card on hover or focus: a button, link, or inline text.'},
@@ -229,7 +229,7 @@ export const docsZh = {
{ guidance: false, description: 'Place critical actions or required information inside a hover card; users may miss content that only appears on hover.' },
{ guidance: false, description: 'Use a hover card when a simple Tooltip or Popover would suffice.' },
{ guidance: false, description: 'Use a HoverCard for content the user must interact with; it disappears when the cursor leaves.' },
- { guidance: false, description: 'Nest a HoverCard whose content has block elements directly inside phrasing-only contexts such as a <p>, <label>, or heading. The card renders inline, so block content there is invalid HTML the browser reparents. Wrap the surrounding text in a block element (e.g. a <div>) instead.' },
+ { guidance: true, description: 'Prefer placing HoverCard in a block context rather than directly in a <p>, heading, or link. Those placements are supported when necessary through a corrective portal, but the DOM and tab order may differ.' },
],
},
};
@@ -247,7 +247,7 @@ export const docsDense = {
{ guidance: false, description: 'Place critical actions or required information inside a hover card; users may miss content that only appears on hover.' },
{ guidance: false, description: 'Use a hover card when a simple Tooltip or Popover would suffice.' },
{ guidance: false, description: 'Use a HoverCard for content the user must interact with; it disappears when the cursor leaves.' },
- { guidance: false, description: 'Nest a block-content HoverCard directly inside phrasing-only contexts (<p>, <label>, heading); it renders inline so block content is invalid HTML there. Wrap surrounding text in a block element instead.' },
+ { guidance: true, description: 'Prefer a block context over a direct <p>, heading, or link placement. Those placements work when necessary through a corrective portal, but DOM/tab order may differ.' },
],
},
components: [
diff --git a/packages/core/src/HoverCard/HoverCard.test.tsx b/packages/core/src/HoverCard/HoverCard.test.tsx
index c0d88f3b31..b1fbcf892f 100644
--- a/packages/core/src/HoverCard/HoverCard.test.tsx
+++ b/packages/core/src/HoverCard/HoverCard.test.tsx
@@ -9,11 +9,21 @@
* SYNC: When HoverCard.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';
+import {
+ describe,
+ it,
+ expect,
+ vi,
+ beforeAll,
+ beforeEach,
+ afterAll,
+} from 'vitest';
import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';
import {renderToString} from 'react-dom/server';
import {hydrateRoot} from 'react-dom/client';
import {StrictMode} from 'react';
+import {Button} from '../Button/Button';
+import {Theme, defineTheme} from '../theme';
import {HoverCard} from './HoverCard';
// Store original matches to restore later
@@ -48,6 +58,11 @@ afterAll(() => {
(HTMLElement.prototype as any).matches = originalMatches;
});
+beforeEach(() => {
+ vi.mocked(HTMLElement.prototype.showPopover).mockClear();
+ vi.mocked(HTMLElement.prototype.hidePopover).mockClear();
+});
+
describe('HoverCard', () => {
it('renders trigger element', () => {
render(
@@ -58,31 +73,40 @@ describe('HoverCard', () => {
expect(screen.getByRole('button', {name: 'Trigger'})).toBeInTheDocument();
});
- it('exposes the floating layer as role="group" when no label is provided', () => {
+ it('exposes the floating layer as role="group" when no label is provided', async () => {
render(
- <HoverCard content={<span>Card content</span>}>
+ <HoverCard content={<span>Card content</span>} delay={0}>
<button type="button">Trigger</button>
</HoverCard>,
);
// A group may validly be unnamed; an unnamed dialog may not. Without a
// label the layer must not claim the dialog role.
- expect(screen.getByRole('group', {hidden: true})).toHaveTextContent(
- 'Card content',
- );
+ expect(screen.queryByRole('group', {hidden: true})).toBeNull();
expect(screen.queryByRole('dialog', {hidden: true})).toBeNull();
+
+ fireEvent.mouseEnter(screen.getByRole('button', {name: 'Trigger'}));
+
+ await waitFor(() => {
+ expect(screen.getByRole('group', {hidden: true})).toHaveTextContent(
+ 'Card content',
+ );
+ });
});
- it('exposes the floating layer as a named dialog when label is provided', () => {
+ it('exposes the floating layer as a named dialog when label is provided', async () => {
render(
- <HoverCard content={<span>Card content</span>} label="Profile preview">
+ <HoverCard
+ content={<span>Card content</span>}
+ label="Profile preview"
+ delay={0}>
<button type="button">Trigger</button>
</HoverCard>,
);
- // The layer is hidden while closed, so assert the accessible name via the
- // aria-label attribute on the role-carrying element (same pattern as the
- // Popover dialogLabel test) — accname computation returns '' for hidden
- // elements.
- const dialog = screen.getByRole('dialog', {hidden: true});
+ expect(screen.queryByRole('dialog', {hidden: true})).toBeNull();
+
+ fireEvent.mouseEnter(screen.getByRole('button', {name: 'Trigger'}));
+
+ const dialog = await screen.findByRole('dialog', {hidden: true});
expect(dialog).toHaveAttribute('aria-label', 'Profile preview');
expect(dialog).toHaveTextContent('Card content');
expect(screen.queryByRole('group', {hidden: true})).toBeNull();
@@ -104,52 +128,236 @@ describe('HoverCard', () => {
expect(trigger.parentElement?.tagName).toBe('SPAN');
expect(paragraph?.querySelector('div')).toBeNull();
+ expect(paragraph?.querySelector('template')).not.toBeNull();
});
- it('renders the floating layer with inline-safe markup (no block elements in a paragraph)', () => {
- // HoverCard renders its floating layer inline (no portal), so the layer
- // must be phrasing content to stay valid — and stay put on hydration —
- // inside a <p>. Assert the layer popover element is a <span> and that the
- // paragraph contains no <div> descendants at all.
+ it('portals block content before showing and restores the marker after hiding', async () => {
+ let contentWasPresentAtShow = false;
+ vi.mocked(HTMLElement.prototype.showPopover).mockImplementationOnce(
+ function (this: HTMLElement) {
+ contentWasPresentAtShow =
+ this.textContent?.includes('Block card content') ?? false;
+ popoverOpenState.set(this, true);
+ },
+ );
+ const consoleErrorSpy = vi
+ .spyOn(console, 'error')
+ .mockImplementation(() => {});
+
const {container} = render(
<p>
Before{' '}
- <HoverCard content={<span>Card content</span>}>
- <a href="#trigger">Trigger</a>
+ <HoverCard
+ content={<div>Block card content</div>}
+ delay={0}
+ hideDelay={0}>
+ Trigger
</HoverCard>{' '}
after
</p>,
);
const paragraph = container.querySelector('p');
- const layer = screen.getByText('Card content').closest('[popover]');
+ const trigger = screen.getByText('Trigger');
- expect(layer).not.toBeNull();
- expect(layer?.tagName).toBe('SPAN');
- // The whole layer subtree lives inside the paragraph with no block boxes.
- expect(paragraph?.contains(layer as Node)).toBe(true);
+ expect(screen.queryByText('Block card content')).toBeNull();
+ expect(paragraph?.querySelector('template')).not.toBeNull();
expect(paragraph?.querySelector('div')).toBeNull();
+ expect(consoleErrorSpy).not.toHaveBeenCalled();
+
+ fireEvent.mouseEnter(trigger);
+
+ await waitFor(() => {
+ const content = screen.getByText('Block card content');
+ const layer = content.closest('[popover]');
+
+ expect(layer?.tagName).toBe('DIV');
+ expect(layer?.parentElement).toBe(container);
+ expect(paragraph?.contains(content)).toBe(false);
+ expect(contentWasPresentAtShow).toBe(true);
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
+ expect(consoleErrorSpy).not.toHaveBeenCalled();
+ });
+
+ fireEvent.mouseLeave(trigger);
+
+ await waitFor(() => {
+ expect(screen.queryByText('Block card content')).toBeNull();
+ expect(paragraph?.querySelector('template')).not.toBeNull();
+ });
+
+ consoleErrorSpy.mockRestore();
});
- it('does not show content initially', () => {
+ it('hosts the floating layer outside a wrapping link', async () => {
+ // Interactive ancestors capture the layer's own interactions: a card left
+ // inside an <a> puts its links and buttons inside that link, so clicking
+ // one navigates.
render(
+ <a href="#profile">
+ <HoverCard
+ content={
+ <span>
+ <a href="#inner">Inner link</a>
+ </span>
+ }
+ delay={0}>
+ Trigger
+ </HoverCard>
+ </a>,
+ );
+
+ const link = screen.getByRole('link', {name: /Trigger/});
+ expect(screen.queryByText('Inner link')).toBeNull();
+ fireEvent.mouseEnter(screen.getByText('Trigger'));
+
+ const layer = (await screen.findByText('Inner link')).closest('[popover]');
+
+ expect(layer).not.toBeNull();
+ expect(link.contains(layer as Node)).toBe(false);
+ });
+
+ it('keeps a safe layer inline at its JSX position', async () => {
+ const {container} = render(
+ <>
+ <HoverCard content={<div>Block card content</div>} delay={0}>
+ <button type="button">Trigger</button>
+ </HoverCard>
+ <button type="button">Following control</button>
+ </>,
+ );
+
+ expect(screen.queryByText('Block card content')).toBeNull();
+ fireEvent.mouseEnter(screen.getByRole('button', {name: 'Trigger'}));
+
+ await waitFor(() => {
+ const layer = screen.getByText('Block card content').closest('[popover]');
+ const following = screen.getByRole('button', {name: 'Following control'});
+
+ expect(layer?.parentElement).toBe(container);
+ expect(layer?.nextElementSibling).toBe(following);
+ });
+ });
+
+ it('does not render content initially', () => {
+ const {container} = render(
<HoverCard content={<span>Card content</span>}>
<button type="button">Trigger</button>
</HoverCard>,
);
- // Content is in DOM (popover not open but element exists)
- const content = screen.queryByText('Card content');
- expect(content).toBeInTheDocument();
+ expect(screen.queryByText('Card content')).toBeNull();
+ expect(container.querySelector('[popover]')).toBeNull();
+ expect(container.querySelector('template')).not.toBeNull();
+ });
+
+ it('keeps a paragraph portal inside the nearest nested theme scope', async () => {
+ const outerTheme = defineTheme({name: 'hovercard-outer-test'});
+ const innerTheme = defineTheme({
+ name: 'hovercard-inner-test',
+ components: {
+ hovercard: {base: {borderWidth: '7px'}},
+ button: {base: {fontWeight: '700'}},
+ },
+ });
+
+ const {container} = render(
+ <Theme theme={outerTheme}>
+ <Theme theme={innerTheme}>
+ <p>
+ <HoverCard
+ content={<Button label="View profile">View profile</Button>}
+ delay={0}>
+ Trigger
+ </HoverCard>
+ </p>
+ </Theme>
+ </Theme>,
+ );
+
+ fireEvent.mouseEnter(screen.getByText('Trigger'));
+
+ await waitFor(() => {
+ const button = screen.getByText('View profile').closest('button');
+ const layer = button?.closest('[popover]') ?? null;
+ const innerThemeScope = container.querySelector(
+ '[data-astryx-theme="hovercard-inner-test"]',
+ );
+
+ expect(innerThemeScope).not.toBeNull();
+ expect(button).not.toBeNull();
+ expect(layer?.parentElement).toBe(innerThemeScope);
+ expect(innerThemeScope?.contains(layer)).toBe(true);
+ expect(container.querySelector('p')?.contains(layer)).toBe(false);
+ });
+ });
+
+ it('does not freeze computed CSS variables on a paragraph portal', async () => {
+ const variables = new Map([
+ ['--color-neutral', 'rgb(1, 2, 3)'],
+ ['--color-text-primary', 'rgb(250, 251, 252)'],
+ ]);
+ const getComputedStyleSpy = vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation(
+ element =>
+ ({
+ length: variables.size,
+ item: (index: number) => Array.from(variables.keys())[index] ?? '',
+ getPropertyValue: (property: string) =>
+ variables.get(property) ?? '',
+ direction:
+ element.tagName.toLowerCase() === 'template' ? 'rtl' : 'ltr',
+ writingMode:
+ element.tagName.toLowerCase() === 'template'
+ ? 'vertical-rl'
+ : 'horizontal-tb',
+ }) as CSSStyleDeclaration,
+ );
+
+ const {container} = render(
+ <p>
+ <HoverCard
+ content={<Button label="View profile">View profile</Button>}
+ delay={0}>
+ Trigger
+ </HoverCard>
+ </p>,
+ );
+
+ expect(screen.queryByRole('button', {name: 'View profile'})).toBeNull();
+ fireEvent.mouseEnter(screen.getByText('Trigger'));
+
+ await waitFor(() => {
+ const button = screen.getByRole('button', {name: 'View profile'});
+ const layer = button.closest('[popover]');
+
+ expect(layer?.parentElement).toBe(container);
+ expect(container.querySelector('p')?.contains(button)).toBe(false);
+ expect(layer).not.toBeNull();
+ expect(
+ (layer as HTMLElement).style.getPropertyValue('--color-neutral'),
+ ).toBe('');
+ expect(
+ (layer as HTMLElement).style.getPropertyValue('--color-text-primary'),
+ ).toBe('');
+ expect((layer as HTMLElement).style.direction).toBe('rtl');
+ expect((layer as HTMLElement).style.writingMode).toBe('vertical-rl');
+ });
+
+ getComputedStyleSpy.mockRestore();
});
- it('applies the theme body font to the floating layer', () => {
+ it('applies the theme body font to the floating layer', async () => {
render(
- <HoverCard content={<span>Card content</span>}>
+ <HoverCard content={<span>Card content</span>} delay={0}>
<button type="button">Trigger</button>
</HoverCard>,
);
- const layer = screen.getByText('Card content').closest('[popover]');
+ fireEvent.mouseEnter(screen.getByRole('button', {name: 'Trigger'}));
+ const layer = (await screen.findByText('Card content')).closest(
+ '[popover]',
+ );
expect(layer).not.toBeNull();
expect(getComputedStyle(layer as Element).fontFamily).toBe(
'var(--font-family-body)',
@@ -435,41 +643,57 @@ describe('HoverCard', () => {
// `typeof document !== 'undefined'` gate: the server rendered nothing while
// the first client render emitted the portal, so the two trees disagreed.
//
- // The layer is now rendered inline as inline-safe phrasing markup (a
- // `<span popover>`), identically on the server and the client, so there is
- // nothing for hydration to mismatch.
+ // Context layers now render the same inert <template> marker on the server
+ // and the first client render. Arbitrary content mounts only when the card
+ // is requested and its final inline/portal position is known.
- it('renders the floating layer in server markup (no document gate)', () => {
- const html = renderToString(
+ it('renders only the inert marker before and after hydration', async () => {
+ const tree = (
<HoverCard content={<span>Card content</span>}>
<button type="button">Trigger</button>
- </HoverCard>,
+ </HoverCard>
);
- // The popover element is present in the server output...
- expect(html).toContain('popover="manual"');
- expect(html).toContain('Card content');
- // ...and it is a <span> (inline-safe), not a <div>.
- expect(html).toMatch(/<span[^>]*popover="manual"/);
+ const serverHTML = renderToString(tree);
+ expect(serverHTML).not.toContain('popover=');
+ expect(serverHTML).not.toContain('Card content');
+ expect(serverHTML).toContain('<template');
+
+ const container = document.createElement('div');
+ container.innerHTML = serverHTML;
+ document.body.appendChild(container);
+
+ let root: ReturnType<typeof hydrateRoot>;
+ await act(async () => {
+ root = hydrateRoot(container, tree);
+ });
+
+ expect(container.querySelector('[popover]')).toBeNull();
+ expect(container.querySelector('template')).not.toBeNull();
+
+ await act(async () => {
+ root.unmount();
+ });
+ container.remove();
});
- it('keeps the floating layer inline-safe in server markup inside a paragraph', () => {
+ it('emits only a valid marker inside a paragraph', () => {
const html = renderToString(
<p>
Before{' '}
- <HoverCard content={<span>Card content</span>}>
+ <HoverCard content={<div>Block card content</div>}>
<a href="#trigger">Trigger</a>
</HoverCard>{' '}
after
</p>,
);
- // No <div> is emitted inside the paragraph — the layer and its wrappers
- // are all phrasing content, so the server string is valid <p> markup that
- // the browser parser will not reparent (which would itself desync
- // hydration).
+ // <template> is inert phrasing/script-supporting content, so the parser
+ // has no block layer or consumer content to reparent out of the <p>.
expect(html).not.toContain('<div');
- expect(html).toMatch(/<span[^>]*popover="manual"/);
+ expect(html).not.toContain('popover=');
+ expect(html).not.toContain('Block card content');
+ expect(html).toContain('<template');
});
it('server markup matches the first client render (no hydration mismatch)', async () => {
@@ -477,7 +701,7 @@ describe('HoverCard', () => {
<StrictMode>
<p>
Glossary:{' '}
- <HoverCard content={<span>Definition</span>}>
+ <HoverCard content={<div>Definition</div>}>
<a href="#term">term</a>
</HoverCard>
.
@@ -515,6 +739,8 @@ describe('HoverCard', () => {
expect(hydrationErrors).toEqual([]);
expect(recoverableErrors).toEqual([]);
+ expect(container.querySelector('[popover]')).toBeNull();
+ expect(container.querySelector('template')).not.toBeNull();
await act(async () => {
root.unmount();
@@ -533,10 +759,10 @@ describe('HoverCard', () => {
);
const serverHTML = renderToString(tree);
- // isDefaultOpen must not leak the open state into SSR markup — the open
- // call happens in an effect after hydration, so the server output is the
- // same closed markup the first client render produces.
- expect(serverHTML).toContain('popover="manual"');
+ // isDefaultOpen must not leak the final layer into SSR markup. The marker
+ // hydrates first; the effect then requests and opens the real popover.
+ expect(serverHTML).not.toContain('popover=');
+ expect(serverHTML).toContain('<template');
const container = document.createElement('div');
container.innerHTML = serverHTML;
@@ -568,6 +794,8 @@ describe('HoverCard', () => {
await waitFor(() => {
expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
});
+ expect(container.querySelector('[popover]')).not.toBeNull();
+ expect(container).toHaveTextContent('Default open');
await act(async () => {
root.unmount();
diff --git a/packages/core/src/HoverCard/HoverCard.tsx b/packages/core/src/HoverCard/HoverCard.tsx
index 13796e6ad1..d1355da155 100644
--- a/packages/core/src/HoverCard/HoverCard.tsx
+++ b/packages/core/src/HoverCard/HoverCard.tsx
@@ -6,7 +6,7 @@
* @file HoverCard.tsx
* @input Uses React, useHoverCard hook
* @output Exports HoverCard component for hover/focus triggered layers
- * @position Layer component; uses inline-safe trigger wrapper and renders the floating layer inline
+ * @position Layer component; inline-safe trigger wrapper, floating layer hosted by useLayer
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/HoverCard/HoverCard.test.tsx
@@ -250,18 +250,10 @@ export function HoverCard({
};
}, [textOnly, hoverCard.ref, hoverCard.describedBy]);
- // Render the floating layer inline, in the same place on the server and the
- // client. The layer is a `popover` element opened via the Popover API, so the
- // browser promotes it to the top layer when shown — that already escapes
- // ancestor clipping, stacking, and transform containing-block traps, and CSS
- // anchor positioning resolves the trigger reference regardless of where the
- // element sits in the DOM, so no portal is needed to "escape" layout.
- //
- // The layer renders as inline-safe phrasing markup (a `<span>`, see
- // useHoverCard), which stays put inside a `<p>` instead of being reparented
- // by the HTML parser. That keeps the server markup and the first client
- // render identical, so there is no hydration mismatch — and it preserves the
- // inline-safety guarantee (no block elements injected into a paragraph).
+ // While closed, useLayer leaves only an inert <template> marker at this JSX
+ // position. When the card needs to open, it uses that marker to keep the
+ // final layer inline when the parent is safe or portal it outside a <p>,
+ // link, or other ancestor that cannot contain it safely.
const renderedHoverCard = hoverCard.renderHoverCard(content, {
xstyle,
className,
diff --git a/packages/core/src/HoverCard/useHoverCard.tsx b/packages/core/src/HoverCard/useHoverCard.tsx
index cb369ef86f..f374d4b5be 100644
--- a/packages/core/src/HoverCard/useHoverCard.tsx
+++ b/packages/core/src/HoverCard/useHoverCard.tsx
@@ -43,11 +43,7 @@ const styles = stylex.create({
borderRadius: 'var(--_hovercard-radius)',
boxShadow: shadowVars['--shadow-med'],
},
- // Position-based margin styles
- // Content wrapper for padding and mouse events.
- // `display: block` keeps the wrapper a block box even though it renders as a
- // `span` (the layer uses inline-safe phrasing markup so it is valid inside a
- // paragraph and produces identical server/client markup).
+ // Content wrapper for padding and interaction events.
content: {
display: 'block',
paddingBlockStart: spacingVars['--spacing-3'],
@@ -254,6 +250,7 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
const layer = useLayer({
mode: 'context',
+ lazyMount: true,
onShow,
onHide,
});
@@ -459,7 +456,7 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
// Consumer surface style props land on the layer container — the
// themed surface (bg/radius/shadow) where the theme class lives — so
// customizing the card targets the same element as the theme. The inner
- // span keeps `styles.content` for padding.
+ // div keeps `styles.content` for padding.
xstyle: [
popoverXstyle,
layerAnimations[renderPlacement],
@@ -469,13 +466,13 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
? `${themeClassName} ${props.className}`
: themeClassName,
style: props?.style,
- // Render the layer as inline-safe phrasing markup so HoverCard stays
- // valid (and hydration-stable) inside inline contexts like a `<p>`.
- as: 'span' as const,
+ // useLayer mounts only after it has verified or corrected the parent,
+ // so rich HoverCard content can use block-safe markup.
+ as: 'div' as const,
};
return layer.render(
- <span
+ <div
{...stylex.props(styles.content)}
onMouseEnter={() => {
isHoveringContentRef.current = true;
@@ -517,7 +514,7 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
scheduleHide();
}}>
{children}
- </span>,
+ </div>,
renderProps,
);
},
diff --git a/packages/core/src/InputGroup/groupStyles.ts b/packages/core/src/InputGroup/groupStyles.ts
index d7fbcd037e..f3c341e867 100644
--- a/packages/core/src/InputGroup/groupStyles.ts
+++ b/packages/core/src/InputGroup/groupStyles.ts
@@ -10,6 +10,11 @@
import * as stylex from '@stylexjs/stylex';
import {radiusVars, borderVars} from '../theme/tokens.stylex';
+// A grouped control may be followed by context-layer infrastructure rather
+// than another control. Neither the inert marker nor the popover is a visual
+// group member, so skip both when finding the trailing edge.
+const IS_LAST_ITEM = ':not(:has(~ *:not([popover]):not(template)))';
+
export const groupStyles = stylex.create({
inGroup: {
flex: 1,
@@ -29,17 +34,11 @@ export const groupStyles = stylex.create({
},
borderStartEndRadius: {
default: 0,
- ':last-child': radiusVars['--radius-element'],
- ':has(+ [popover]:last-child)': radiusVars['--radius-element'],
- ':has(+ [popover] + [popover]:last-child)':
- radiusVars['--radius-element'],
+ [IS_LAST_ITEM]: radiusVars['--radius-element'],
},
borderEndEndRadius: {
default: 0,
- ':last-child': radiusVars['--radius-element'],
- ':has(+ [popover]:last-child)': radiusVars['--radius-element'],
- ':has(+ [popover] + [popover]:last-child)':
- radiusVars['--radius-element'],
+ [IS_LAST_ITEM]: radiusVars['--radius-element'],
},
':focus-within': {
zIndex: 1,
diff --git a/packages/core/src/Layer/layerHost.test.ts b/packages/core/src/Layer/layerHost.test.ts
new file mode 100644
index 0000000000..8ad56dc5de
--- /dev/null
+++ b/packages/core/src/Layer/layerHost.test.ts
@@ -0,0 +1,99 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file layerHost.test.ts
+ * @input Tests resolveLayerPortalTarget
+ * @output Coverage for when and where a layer is portaled
+ * @position Test for /packages/core/src/Layer/layerHost.ts
+ */
+
+import {describe, it, expect, afterEach} from 'vitest';
+import {resolveLayerPortalTarget} from './layerHost';
+
+function mount(html: string): HTMLElement {
+ const root = document.createElement('div');
+ root.id = 'root';
+ root.innerHTML = html;
+ document.body.appendChild(root);
+ return root;
+}
+
+afterEach(() => {
+ document.getElementById('root')?.remove();
+});
+
+describe('resolveLayerPortalTarget', () => {
+ it('returns null without an inline parent', () => {
+ expect(resolveLayerPortalTarget(null)).toBeNull();
+ });
+
+ it('returns null when the intended inline position is already safe', () => {
+ const root = mount(
+ '<div id="host"><template id="marker"></template></div>',
+ );
+ const target = resolveLayerPortalTarget(root.querySelector('#host'));
+
+ expect(target).toBeNull();
+ });
+
+ it.each([
+ ['paragraph', '<p><template></template></p>'],
+ ['heading', '<h2><template></template></h2>'],
+ ['link', '<a href="#x"><template></template></a>'],
+ ['button', '<button><template></template></button>'],
+ ['label', '<label><template></template></label>'],
+ ['data', '<data><template></template></data>'],
+ ['definition', '<dfn><template></template></dfn>'],
+ ['meter', '<meter><template></template></meter>'],
+ ['output', '<output><template></template></output>'],
+ ['progress', '<progress><template></template></progress>'],
+ [
+ 'nested inline formatting',
+ '<p><em><b><template id="marker"></template></b></em></p>',
+ ],
+ ])('walks out of a %s', (_name, markup) => {
+ const root = mount(`<div id="host">${markup}</div>`);
+ const marker = root.querySelector('template');
+ const target = resolveLayerPortalTarget(marker?.parentElement ?? null);
+
+ expect(target).toBe(root.querySelector('#host'));
+ });
+
+ it('walks past a safe wrapper nested inside an unsafe ancestor', () => {
+ const root = mount(
+ '<div id="host"><a href="#x"><div id="inline"><template></template></div></a></div>',
+ );
+ const target = resolveLayerPortalTarget(root.querySelector('#inline'));
+
+ expect(target).toBe(root.querySelector('#host'));
+ });
+
+ it.each([
+ [
+ 'table row',
+ '<table><tbody><tr><template></template></tr></tbody></table>',
+ ],
+ ['list', '<ul><template></template></ul>'],
+ ['select', '<select><template></template></select>'],
+ ['heading group', '<hgroup><template></template></hgroup>'],
+ ])('walks out of a structural %s', (_name, markup) => {
+ const root = mount(`<div id="host">${markup}</div>`);
+ const marker = root.querySelector('template');
+ const target = resolveLayerPortalTarget(marker?.parentElement ?? null);
+
+ expect(target).toBe(root.querySelector('#host'));
+ });
+
+ it('stops at the nearest safe ancestor rather than the body', () => {
+ const root = mount(
+ '<section id="outer"><li id="host"><p><span id="t">t</span></p></li></section>',
+ );
+ const marker = root.querySelector('#t');
+ const target = resolveLayerPortalTarget(marker?.parentElement ?? null);
+
+ // The nearest safe ancestor keeps the layer inside the trigger's theme
+ // scope and next to it in the tab order.
+ expect(target).toBe(root.querySelector('#host'));
+ expect(target).not.toBe(document.body);
+ });
+});
diff --git a/packages/core/src/Layer/layerHost.ts b/packages/core/src/Layer/layerHost.ts
new file mode 100644
index 0000000000..3339142da9
--- /dev/null
+++ b/packages/core/src/Layer/layerHost.ts
@@ -0,0 +1,141 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file layerHost.ts
+ * @input Uses the layer's intended inline parent element
+ * @output Exports resolveLayerPortalTarget, the corrective portal target
+ * @position Layer utility; used by useLayer to place the popover in the DOM
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Layer/layerHost.test.ts
+ */
+
+/**
+ * Ancestors a layer must not be hosted inside.
+ *
+ * Two overlapping reasons, both verified in Chrome:
+ *
+ * 1. The HTML parser owns server markup. `<p>` and the heading-ish elements
+ * take phrasing content only, so a block element inside one makes the
+ * parser close the paragraph and reparent the rest — the layer's content
+ * ends up in the page instead of the popover. A nested `<a>` triggers the
+ * same tearing through the adoption agency algorithm.
+ * 2. Interactive ancestors capture the layer's own interactions. A card
+ * hosted inside an `<a>` or `<button>` puts its links and buttons inside
+ * that control: clicking one navigates the wrapping link, and every
+ * focusable in the card joins the control's own tab stop.
+ *
+ * Inline formatting elements are on the list for a third, milder reason: a
+ * layer hosted in one inherits its typography (font-size, text-align), so a
+ * card in a 13px centered paragraph renders 13px and centered.
+ */
+const UNSAFE_HOSTS = new Set([
+ // Phrasing-content-only containers
+ 'p',
+ 'h1',
+ 'h2',
+ 'h3',
+ 'h4',
+ 'h5',
+ 'h6',
+ 'dt',
+ 'pre',
+ 'legend',
+ 'data',
+ 'dfn',
+ 'meter',
+ 'output',
+ 'progress',
+ 'option',
+ 'optgroup',
+ // Structural containers whose direct children are restricted. An inert
+ // <template> marker is valid script-supporting content in these positions,
+ // but the eventual div/span layer is not.
+ 'table',
+ 'thead',
+ 'tbody',
+ 'tfoot',
+ 'tr',
+ 'colgroup',
+ 'ul',
+ 'ol',
+ 'menu',
+ 'dl',
+ 'select',
+ 'datalist',
+ 'picture',
+ 'hgroup',
+ 'ruby',
+ 'rt',
+ 'rp',
+ // Interactive containers
+ 'a',
+ 'button',
+ 'label',
+ 'summary',
+ // Inline formatting context
+ 'span',
+ 'em',
+ 'strong',
+ 'b',
+ 'i',
+ 'u',
+ 's',
+ 'small',
+ 'mark',
+ 'code',
+ 'kbd',
+ 'samp',
+ 'var',
+ 'sub',
+ 'sup',
+ 'abbr',
+ 'cite',
+ 'q',
+ 'time',
+ 'bdi',
+ 'bdo',
+ 'ins',
+ 'del',
+]);
+
+/**
+ * Return the corrective portal target for a layer's intended inline parent.
+ *
+ * A null result means the inline parent and all of its ancestors are safe, so
+ * the layer should stay at its JSX position. Otherwise the result is the
+ * nearest element outside every unsafe ancestor around that position.
+ *
+ * Walking up from the actual render position (rather than the trigger, or
+ * portaling to `document.body`) keeps the two things a layer inherits there:
+ *
+ * - **Theme.** Theme scopes live on DOM ancestors. Staying as close as
+ * possible to the intended render position preserves their component rules
+ * and custom properties; `document.body` may sit outside a nested scope.
+ * - **Tab order.** Sequential focus follows DOM order, so a host near the
+ * trigger keeps the layer's focusables next to it. (`show()` also passes
+ * the trigger as the popover's invoker `source`, which pins focus order to
+ * the invoker in browsers that support it.)
+ *
+ * The outermost unsafe ancestor matters. A safe div may itself sit inside an
+ * anchor; stopping at that div would still put the layer's buttons inside the
+ * link. Walking the whole chain ensures the target is outside both.
+ */
+export function resolveLayerPortalTarget(
+ inlineParent: HTMLElement | null,
+): HTMLElement | null {
+ if (!inlineParent) {
+ return null;
+ }
+
+ let outermostUnsafe: HTMLElement | null = null;
+ let node: HTMLElement | null = inlineParent;
+ while (node) {
+ if (UNSAFE_HOSTS.has(node.tagName.toLowerCase())) {
+ outermostUnsafe = node;
+ }
+ node = node.parentElement;
+ }
+
+ return outermostUnsafe?.parentElement ?? null;
+}
diff --git a/packages/core/src/Layer/useLayer.doc.mjs b/packages/core/src/Layer/useLayer.doc.mjs
index 855fe727a6..5c2e9c6704 100644
--- a/packages/core/src/Layer/useLayer.doc.mjs
+++ b/packages/core/src/Layer/useLayer.doc.mjs
@@ -42,6 +42,13 @@ export const docs = {
'Whether clicking outside should dismiss the layer using native popover light-dismiss behavior.',
default: 'false',
},
+ {
+ name: 'lazyMount',
+ type: 'boolean',
+ description:
+ 'Context mode only. Wait until show() to resolve the inline/portal position and mount content; hide unmounts the content while the inert marker remains.',
+ default: 'false',
+ },
],
returns: [
{
@@ -79,7 +86,7 @@ export const docs = {
name: 'render',
type: '(children: ReactNode, props: ContextRenderProps | FixedRenderProps) => ReactNode',
description:
- 'Render function for the popover element. Pass placement/alignment in context mode or x/y in fixed mode. Placement/alignment are logical: they map to the self-* position-area keyword family, which resolves against the popover\'s own inherited direction, so RTL contexts mirror automatically in pure CSS. Pass `positioning: "custom"` in context mode to author position styles yourself via `style` (e.g. explicit anchor() insets or an anchor-size() cover): the hook keeps the popover behavior and position-anchor wiring but derives no position styles, including the automatic RTL mirroring, which becomes your responsibility. Pass `offset` (a CSS length; a number is px) in context mode for clearance from the anchor: it applies to both edges of the placement axis, so the gap survives a flip. Layers are flush by default. In context mode, pass `as: "span"` to render an inline-safe layer (e.g. inside a paragraph). The layer renders inline in the React tree; the Popover API promotes it to the top layer when shown, so it escapes ancestor clipping and stacking without a portal. When the layer would overflow the viewport, position-try fallbacks flip it to the opposite side; centered layers additionally slide along the alignment axis (span fallbacks) so they stay on-screen near viewport edges.',
+ 'Render function for the popover element. Pass placement/alignment in context mode or x/y in fixed mode. Placement/alignment are logical: they map to the self-* position-area keyword family, which resolves against the popover\'s own inherited direction, so RTL contexts mirror automatically in pure CSS. Pass `positioning: "custom"` in context mode to author position styles yourself via `style` (e.g. explicit anchor() insets or an anchor-size() cover): the hook keeps the popover behavior and position-anchor wiring but derives no position styles, including the automatic RTL mirroring, which becomes your responsibility. Pass `offset` (a CSS length; a number is px) in context mode for clearance from the anchor: it applies to both edges of the placement axis, so the gap survives a flip. Layers are flush by default. Context mode first renders an inert `<template>` marker in matching server and client markup. The final layer stays at that JSX position if its parent is safe; otherwise it is portaled to the nearest ancestor outside paragraphs, links, buttons, inline formatting, and structurally restricted containers. The nearest safe host keeps CSS custom properties inheriting live, while the layer preserves direction and writing mode from its JSX position. By default this resolution occurs after hydration so closed-layer DOM remains available; `lazyMount` defers it until `show()` and unmounts the content again on hide while the marker remains. The Popover API promotes the layer to the top layer when shown, so it escapes ancestor clipping and stacking wherever it is hosted. When the layer would overflow the viewport, position-try fallbacks flip it to the opposite side; centered layers additionally slide along the alignment axis (span fallbacks) so they stay on-screen near viewport edges.',
},
],
usage: {
@@ -99,7 +106,7 @@ export const docs = {
{
guidance: true,
description:
- 'Rely on the Popover API top layer to escape ancestor clipping and stacking: render the layer inline (no portal) so it inherits the trigger\'s theme cascade and keeps a natural focus order. Use `as: "span"` when the layer must be valid inside inline contexts like a paragraph.',
+ "Rely on the Popover API top layer to escape ancestor clipping and stacking, and host the layer near its trigger rather than in the body so it inherits the trigger's theme cascade and keeps a natural focus order.",
},
{
guidance: false,
@@ -123,6 +130,8 @@ export const docsDense = {
onShow: 'fires when layer becomes visible.',
onHide: 'fires when layer hides.',
lightDismiss: 'whether native outside-click light-dismiss is enabled.',
+ lazyMount:
+ 'context only: defer position resolution/content mounting until show; unmount on hide.',
},
returnDescriptions: {
ref: 'trigger ref for context mode; undefined in fixed mode.',
@@ -131,7 +140,8 @@ export const docsDense = {
hide: 'hide layer.',
isOpen: 'whether layer is open.',
id: 'unique ARIA id.',
- render: 'renders popover element; pass placement/alignment or x/y. Placement/alignment logical: mapped to self-* position-area keywords resolved against the popover\'s inherited direction (RTL mirrors in pure CSS). `positioning: "custom"` (context mode) = author position styles yourself via `style`; keeps popover behavior + position-anchor wiring, derives nothing (incl. RTL mirroring, which becomes yours). `offset` (context mode) = clearance from the anchor as a CSS length (number = px), applied to both edges of the placement axis so it survives a flip; layers are flush by default. Context mode accepts `as: "span"` for inline-safe layers. Renders inline; the Popover API top layer escapes clipping/stacking without a portal. Viewport overflow: flips to opposite side; centered layers also slide along the alignment axis (span fallbacks).',
+ render:
+ 'renders popover element; pass placement/alignment or x/y. Placement/alignment logical: mapped to self-* position-area keywords resolved against the popover\'s inherited direction (RTL mirrors in pure CSS). `positioning: "custom"` (context mode) = author position styles yourself via `style`; keeps popover behavior + position-anchor wiring, derives nothing (incl. RTL mirroring, which becomes yours). `offset` (context mode) = clearance from the anchor as a CSS length (number = px), applied to both edges of the placement axis so it survives a flip; layers are flush by default. Context mode begins with an inert `<template>` marker for stable SSR/hydration, then keeps the final layer inline at a safe JSX position or portals it to the nearest safe ancestor; CSS custom properties keep inheriting from that host while direction and writing mode are preserved from the JSX position. `lazyMount` waits for show and unmounts content on hide while the marker remains. The Popover API top layer escapes clipping/stacking wherever it is hosted. Viewport overflow: flips to opposite side; centered layers also slide along the alignment axis (span fallbacks).',
},
usage: {
description:
@@ -150,7 +160,7 @@ export const docsDense = {
{
guidance: true,
description:
- 'Rely on the Popover API top layer to escape clipping/stacking: render inline (no portal) to inherit the trigger theme cascade and natural focus order. Use `as: "span"` when the layer must be valid in inline contexts like a paragraph.',
+ 'Rely on the Popover API top layer to escape clipping/stacking; host the layer near its trigger (not in the body) to inherit the trigger theme cascade and natural focus order.',
},
{
guidance: false,
diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsx
index 4700f7cb60..3590c55402 100644
--- a/packages/core/src/Layer/useLayer.test.tsx
+++ b/packages/core/src/Layer/useLayer.test.tsx
@@ -10,7 +10,7 @@
*/
import {describe, it, expect, vi, afterEach} from 'vitest';
-import {render, act} from '@testing-library/react';
+import {render, act, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {useLayer, getPositionTryFallbacks} from './useLayer';
import type {
@@ -19,6 +19,12 @@ import type {
ContextRenderProps,
} from './useLayer';
+function mockCSSStyleDeclaration(
+ styles: Partial<CSSStyleDeclaration>,
+): CSSStyleDeclaration {
+ return styles as CSSStyleDeclaration;
+}
+
/**
* Minimal harness that exposes the imperative show/hide callbacks and renders
* the layer element so tests can assert on visibility.
@@ -47,7 +53,7 @@ function ContextLayerHarness({
const layer = useLayer({mode: 'context'});
return (
<>
- <button type="button" ref={layer.ref}>
+ <button type="button" ref={layer.ref} onClick={layer.show}>
Trigger
</button>
{layer.render(<span>Layer content</span>, {placement, alignment})}
@@ -55,6 +61,82 @@ function ContextLayerHarness({
);
}
+function ContextHostingHarness({
+ unsafe,
+ themeColor,
+ direction,
+ writingMode,
+}: {
+ unsafe?: boolean;
+ themeColor?: string;
+ direction?: React.CSSProperties['direction'];
+ writingMode?: React.CSSProperties['writingMode'];
+}) {
+ const layer = useLayer({mode: 'context', lazyMount: true});
+ const contents = (
+ <>
+ <button type="button" ref={layer.ref} onClick={layer.show}>
+ Trigger
+ </button>
+ {layer.render(<button type="button">Layer action</button>)}
+ <button type="button">Following control</button>
+ </>
+ );
+
+ const hostStyle = {
+ ...(themeColor ? {'--test-layer-color': themeColor} : {}),
+ direction,
+ writingMode,
+ } as React.CSSProperties;
+
+ return (
+ <div data-testid="host" style={hostStyle}>
+ {unsafe ? <p>{contents}</p> : contents}
+ </div>
+ );
+}
+
+function RelocatingContextHostingHarness({unsafe}: {unsafe: boolean}) {
+ const layer = useLayer({mode: 'context'});
+ const renderedLayer = layer.render(<span>Layer content</span>);
+
+ return unsafe ? (
+ <div data-testid="unsafe-host">
+ <p>{renderedLayer}</p>
+ </div>
+ ) : (
+ <section data-testid="render-position">{renderedLayer}</section>
+ );
+}
+
+function RelocatingOpenContextHostingHarness({
+ unsafe,
+ onShow,
+}: {
+ unsafe: boolean;
+ onShow?: () => void;
+}) {
+ const layer = useLayer({mode: 'context', lazyMount: true, onShow});
+ const renderedLayer = layer.render(
+ <button type="button">Layer action</button>,
+ );
+
+ return (
+ <>
+ <button type="button" ref={layer.ref} onClick={layer.show}>
+ Trigger
+ </button>
+ {unsafe ? (
+ <div data-testid="unsafe-host">
+ <p>{renderedLayer}</p>
+ </div>
+ ) : (
+ <section data-testid="safe-host">{renderedLayer}</section>
+ )}
+ </>
+ );
+}
+
describe('getPositionTryFallbacks (issue #3671)', () => {
const FLIPS = 'flip-block, flip-inline, flip-block flip-inline';
@@ -130,10 +212,12 @@ describe('getPositionTryFallbacks (issue #3671)', () => {
}
});
- it('updates the fallback list when placement/alignment props change on re-render', () => {
+ it('updates the fallback list when placement/alignment props change on re-render', async () => {
+ const user = userEvent.setup();
const {container, rerender} = render(
<ContextLayerHarness placement="above" alignment="center" />,
);
+ await user.click(container.querySelector('button')!);
const layerEl = container.querySelector('[popover]') as HTMLElement;
expect(layerEl.style.positionTryFallbacks).toContain('top span-left');
@@ -158,8 +242,10 @@ describe('getPositionTryFallbacks (issue #3671)', () => {
expect(layerEl.style.top).toBe('20px');
});
- it('applies span fallbacks to the rendered popover for the default (above/center) layer', () => {
+ it('applies span fallbacks to the rendered popover for the default (above/center) layer', async () => {
+ const user = userEvent.setup();
const {container} = render(<ContextLayerHarness />);
+ await user.click(container.querySelector('button')!);
const layerEl = container.querySelector('[popover]') as HTMLElement;
expect(layerEl).not.toBeNull();
expect(layerEl.style.positionTryFallbacks).toBe(
@@ -188,6 +274,231 @@ describe('useLayer', () => {
}
});
+ describe('context hosting', () => {
+ it('keeps closed content mounted by default for existing consumers', () => {
+ const {container} = render(<ContextLayerHarness />);
+
+ expect(container.querySelector('template')).not.toBeNull();
+ expect(container.querySelector('[popover]')).not.toBeNull();
+ expect(container).toHaveTextContent('Layer content');
+ });
+
+ it('renders only an inert marker until show is requested', () => {
+ const {container} = render(<ContextHostingHarness />);
+
+ const sentinel = container.querySelector('template');
+ expect(sentinel).not.toBeNull();
+ expect(sentinel).not.toHaveAttribute('id');
+ expect(container.querySelector('[popover]')).toBeNull();
+ expect(container).not.toHaveTextContent('Layer action');
+ });
+
+ it('keeps the final layer inline when the JSX position is safe', async () => {
+ HTMLElement.prototype.showPopover = vi.fn();
+ const user = userEvent.setup();
+ const {container, getByRole} = render(<ContextHostingHarness />);
+
+ await user.click(getByRole('button', {name: 'Trigger'}));
+
+ const layer = container.querySelector('[popover]');
+ const following = getByRole('button', {name: 'Following control'});
+ expect(layer?.parentElement).toBe(container.firstElementChild);
+ expect(layer?.nextElementSibling).toBe(following);
+ expect(container.querySelector('template')).not.toBeNull();
+ });
+
+ it('portals out of an unsafe parent and preserves its logical writing context', async () => {
+ const getComputedStyleSpy = vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation(() =>
+ mockCSSStyleDeclaration({
+ getPropertyValue: () => '',
+ direction: 'rtl',
+ writingMode: 'vertical-rl',
+ }),
+ );
+ const showSpy = vi.fn();
+ HTMLElement.prototype.showPopover = showSpy;
+ const user = userEvent.setup();
+
+ try {
+ const {container, getByRole} = render(<ContextHostingHarness unsafe />);
+ const trigger = getByRole('button', {name: 'Trigger'});
+
+ await user.click(trigger);
+
+ const host = container.querySelector('[data-testid="host"]');
+ const paragraph = container.querySelector('p');
+ const layer = container.querySelector('[popover]') as HTMLElement;
+ expect(layer.parentElement).toBe(host);
+ expect(paragraph?.contains(layer)).toBe(false);
+ expect(layer).toHaveStyle({
+ direction: 'rtl',
+ writingMode: 'vertical-rl',
+ });
+ expect(showSpy).toHaveBeenCalledWith({source: trigger});
+ } finally {
+ getComputedStyleSpy.mockRestore();
+ }
+ });
+
+ it('inherits custom properties from the corrective host without freezing an inline snapshot', async () => {
+ const originalGetComputedStyle = window.getComputedStyle.bind(window);
+ const getComputedStyleSpy = vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation(element => {
+ if (element.tagName.toLowerCase() !== 'template') {
+ return originalGetComputedStyle(element);
+ }
+ return mockCSSStyleDeclaration({
+ length: 1,
+ item: () => '--test-layer-color',
+ getPropertyValue: property =>
+ property === '--test-layer-color' ? 'rgb(1, 2, 3)' : '',
+ direction: 'ltr',
+ writingMode: 'horizontal-tb',
+ });
+ });
+ HTMLElement.prototype.showPopover = vi.fn();
+ const user = userEvent.setup();
+ try {
+ const {container, getByRole, rerender} = render(
+ <ContextHostingHarness unsafe themeColor="rgb(1, 2, 3)" />,
+ );
+
+ await user.click(getByRole('button', {name: 'Trigger'}));
+
+ let host = container.querySelector(
+ '[data-testid="host"]',
+ ) as HTMLElement;
+ let layer = container.querySelector('[popover]') as HTMLElement;
+ expect(layer.parentElement).toBe(host);
+ expect(layer.style.getPropertyValue('--test-layer-color')).toBe('');
+ expect(host.style.getPropertyValue('--test-layer-color')).toBe(
+ 'rgb(1, 2, 3)',
+ );
+
+ rerender(<ContextHostingHarness unsafe themeColor="rgb(4, 5, 6)" />);
+
+ host = container.querySelector('[data-testid="host"]') as HTMLElement;
+ layer = container.querySelector('[popover]') as HTMLElement;
+ expect(layer.parentElement).toBe(host);
+ expect(layer.style.getPropertyValue('--test-layer-color')).toBe('');
+ expect(host.style.getPropertyValue('--test-layer-color')).toBe(
+ 'rgb(4, 5, 6)',
+ );
+ } finally {
+ getComputedStyleSpy.mockRestore();
+ }
+ });
+
+ it('keeps a shared writing context inheriting live from the corrective host', async () => {
+ const getComputedStyleSpy = vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation(element => {
+ const htmlElement = element as HTMLElement;
+ const host = htmlElement.matches('[data-testid="host"]')
+ ? htmlElement
+ : htmlElement.closest<HTMLElement>('[data-testid="host"]');
+ return mockCSSStyleDeclaration({
+ getPropertyValue: () => '',
+ direction: host?.style.direction || 'ltr',
+ writingMode: host?.style.writingMode || 'horizontal-tb',
+ });
+ });
+ HTMLElement.prototype.showPopover = vi.fn();
+ const user = userEvent.setup();
+
+ try {
+ const {container, getByRole, rerender} = render(
+ <ContextHostingHarness
+ unsafe
+ direction="rtl"
+ writingMode="vertical-rl"
+ />,
+ );
+
+ await user.click(getByRole('button', {name: 'Trigger'}));
+
+ let layer = container.querySelector('[popover]') as HTMLElement;
+ expect(layer.style.direction).toBe('');
+ expect(layer.style.writingMode).toBe('');
+ expect(window.getComputedStyle(layer).direction).toBe('rtl');
+
+ rerender(
+ <ContextHostingHarness
+ unsafe
+ direction="ltr"
+ writingMode="horizontal-tb"
+ />,
+ );
+
+ layer = container.querySelector('[popover]') as HTMLElement;
+ expect(layer.style.direction).toBe('');
+ expect(layer.style.writingMode).toBe('');
+ expect(window.getComputedStyle(layer).direction).toBe('ltr');
+ } finally {
+ getComputedStyleSpy.mockRestore();
+ }
+ });
+
+ it('re-resolves the host when a persistent render call moves', () => {
+ const {container, rerender} = render(
+ <RelocatingContextHostingHarness unsafe />,
+ );
+
+ const host = container.querySelector('[data-testid="unsafe-host"]');
+ const paragraph = container.querySelector('p');
+ let layer = container.querySelector('[popover]');
+ expect(layer?.parentElement).toBe(host);
+ expect(paragraph?.contains(layer)).toBe(false);
+
+ rerender(<RelocatingContextHostingHarness unsafe={false} />);
+
+ const section = container.querySelector('section');
+ layer = container.querySelector('[popover]');
+ expect(layer?.parentElement).toBe(section);
+ expect(section?.querySelector('template')).not.toBeNull();
+ });
+
+ it('reopens an open lazy layer after its render call moves', async () => {
+ const showSpy = vi.fn(function (this: HTMLElement) {
+ if (!this.isConnected) {
+ throw new Error('showPopover called on a detached layer');
+ }
+ this.dataset.open = 'true';
+ });
+ const onShow = vi.fn();
+ HTMLElement.prototype.showPopover = showSpy;
+ const {container, getByRole, rerender} = render(
+ <RelocatingOpenContextHostingHarness unsafe onShow={onShow} />,
+ );
+
+ fireEvent.click(getByRole('button', {name: 'Trigger'}));
+
+ await waitFor(() => {
+ expect(container.querySelector('[popover]')).toHaveAttribute(
+ 'data-open',
+ 'true',
+ );
+ });
+
+ rerender(
+ <RelocatingOpenContextHostingHarness unsafe={false} onShow={onShow} />,
+ );
+
+ await waitFor(() => {
+ const layer = container.querySelector('[popover]');
+ expect(layer?.parentElement).toBe(
+ container.querySelector('[data-testid="safe-host"]'),
+ );
+ expect(layer).toHaveAttribute('data-open', 'true');
+ });
+ expect(showSpy).toHaveBeenCalledTimes(2);
+ expect(onShow).toHaveBeenCalledOnce();
+ });
+ });
+
describe('when the Popover API is supported', () => {
it('calls showPopover/hidePopover on show/hide', () => {
const showSpy = vi.fn();
@@ -485,9 +796,9 @@ describe('useLayer context positioning', () => {
const NONE = {blockStart: '', blockEnd: '', inlineStart: '', inlineEnd: ''};
it('is flush by default', async () => {
- expect(await openAndGetOffsets(<OffsetHarness placement="below" />)).toEqual(
- NONE,
- );
+ expect(
+ await openAndGetOffsets(<OffsetHarness placement="below" />),
+ ).toEqual(NONE);
});
// Both edges of the axis, so the gap survives a position-try-fallbacks
diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx
index 5e4e1744b1..42cb0ca5aa 100644
--- a/packages/core/src/Layer/useLayer.tsx
+++ b/packages/core/src/Layer/useLayer.tsx
@@ -25,7 +25,9 @@ import React, {
} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
+import {createPortal} from 'react-dom';
import {addAnchorName, removeAnchorName} from './anchorName';
+import {resolveLayerPortalTarget} from './layerHost';
import {typographyVars} from '../theme/tokens.stylex';
const styles = stylex.create({
@@ -149,12 +151,11 @@ export interface ContextRenderProps {
/**
* HTML tag to render the popover container as.
*
- * Defaults to `'div'`. Pass `'span'` when the layer must render inline-safe
- * markup — e.g. a `HoverCard` wrapping inline text inside a `<p>`. A `<span>`
- * is phrasing content, so it stays put in the DOM tree instead of being
- * reparented out of a paragraph by the HTML parser, which keeps server and
- * client markup identical. The Popover API and CSS anchor positioning work
- * the same on either tag.
+ * Defaults to `'div'`. Context layers render an inert `<template>` marker at
+ * the JSX position. The marker's parent is checked before the requested
+ * container mounts there or portals outside ancestors that cannot safely
+ * contain it. The marker remains available to detect a new parent if the
+ * render call moves. With `lazyMount`, the first check waits until `show()`.
*
* @default 'div'
*/
@@ -222,6 +223,15 @@ interface BaseLayerOptions {
*/
export interface ContextLayerOptions extends BaseLayerOptions {
mode: 'context';
+ /**
+ * Defer mounting the final layer and resolving its inline/portal position
+ * until `show()` is requested. Hiding unmounts it while the inert marker
+ * remains at the JSX position. Use this when rich content must never enter
+ * an unsafe ancestor, even briefly, and does not need to exist while closed.
+ *
+ * @default false
+ */
+ lazyMount?: boolean;
}
/**
@@ -314,16 +324,51 @@ function toCssLength(value: number | string): string {
return typeof value === 'number' ? `${value}px` : value;
}
+interface ContextLayerMount {
+ /** Null means the marker's parent is safe and the layer stays inline. */
+ portalTarget: HTMLElement | null;
+ /** Logical writing context lost when moving outside an unsafe ancestor. */
+ portalStyle: React.CSSProperties;
+}
+
+function readPortalWritingContext(
+ element: HTMLElement,
+ portalTarget: HTMLElement,
+): React.CSSProperties {
+ const view = element.ownerDocument.defaultView;
+ if (!view) {
+ return {};
+ }
+ const sourceStyle = view.getComputedStyle(element);
+ const targetStyle = view.getComputedStyle(portalTarget);
+
+ // Do not snapshot custom properties here. The portal target is the closest
+ // safe ancestor, so theme variables continue to inherit and update there.
+ // These two properties can be set on the unsafe chain itself and directly
+ // affect the logical anchor-positioning keywords used by the layer. Only
+ // override values the portal would actually lose; matching values should
+ // keep inheriting from the target so later direction changes remain live.
+ return {
+ ...(sourceStyle.direction !== targetStyle.direction && {
+ direction: sourceStyle.direction as React.CSSProperties['direction'],
+ }),
+ ...(sourceStyle.writingMode !== targetStyle.writingMode && {
+ writingMode:
+ sourceStyle.writingMode as React.CSSProperties['writingMode'],
+ }),
+ };
+}
+
/**
* Map logical placement/alignment to a CSS position-area value.
*
* Uses the self-* logical keyword family: the inline axis resolves against
- * the popover's own inherited direction (the layer renders inside the
- * trigger's subtree, so it inherits `direction` and mirrors in RTL with no
- * JS). The block axis is direction-neutral but must come from the same
- * keyword family — mixing physical `top` with `self-inline-*` produces an
- * invalid position-area (computes to `none`, which pins the popover to the
- * viewport corner because styles.base zeroes the UA margins).
+ * the popover's own direction (inherited inline or preserved when portaled),
+ * so it mirrors in RTL without placement-specific JS. The block axis is
+ * direction-neutral but must come from the same keyword family — mixing
+ * physical `top` with `self-inline-*` produces an invalid position-area
+ * (computes to `none`, which pins the popover to the viewport corner because
+ * styles.base zeroes the UA margins).
*
* Note the plain logical family (`inline-start`, no `self-`) is NOT a
* substitute: it resolves against the containing block — the page root for
@@ -406,39 +451,122 @@ export function useLayer(
options: ContextLayerOptions | FixedLayerOptions,
): ContextLayerReturn | FixedLayerReturn {
const {mode, onShow, onHide, lightDismiss = false} = options;
+ const lazyMount = mode === 'context' ? (options.lazyMount ?? false) : false;
const id = useId();
const anchorId = `--astryx-layer-${id.replace(/:/g, '')}`;
const [isOpen, setIsOpen] = useState(false);
const popoverRef = useRef<HTMLElement | null>(null);
+ // The DOM element on which the current logical open state was applied.
+ // A portal target change replaces the popover element; retaining the old
+ // reference lets the ref callback recognize and reopen its replacement.
+ const openedPopoverRef = useRef<HTMLElement | null>(null);
const triggerRef = useRef<HTMLElement | null>(null);
+ // Context layers place a persistent inert marker at their real JSX position.
+ // Its parent tells us whether the final layer can stay inline or needs a
+ // corrective portal, including after the render call moves.
+ const sentinelRef = useRef<HTMLTemplateElement | null>(null);
+ const contextMountRef = useRef<ContextLayerMount | null>(null);
+ const [contextMount, setContextMount] = useState<ContextLayerMount | null>(
+ null,
+ );
+ // A show() that arrives before the final layer mounts is replayed when its
+ // popover ref attaches.
+ const pendingShowRef = useRef(false);
// Ref mirrors isOpen for synchronous reads inside show/hide.
// State drives re-renders; the ref lets the imperative calls avoid
// stale-closure reads of the previous isOpen value.
const isOpenRef = useRef(false);
- const show = useCallback(() => {
- const popover = popoverRef.current;
- if (popover && !isOpenRef.current) {
- // Finding infra-4: the Popover API is unsupported on Safari <17 and
- // Firefox <125. On those browsers `showPopover` does not exist, so
- // calling it unconditionally throws a TypeError and the layer never
- // opens. Guard behind a feature check; when the API is missing, fall
- // back to plain visibility (the [popover] attribute is inert there, so
- // the element sits in normal flow) so the layer still becomes visible.
- if (typeof popover.showPopover === 'function') {
- popover.showPopover();
- } else {
- popover.style.display = 'block';
+ const showPopoverElement = useCallback((popover: HTMLElement) => {
+ // Finding infra-4: the Popover API is unsupported on Safari <17 and
+ // Firefox <125. On those browsers `showPopover` does not exist, so fall
+ // back to plain visibility instead of throwing.
+ if (typeof popover.showPopover === 'function') {
+ // The trigger is passed as the popover's invoker `source`: a layer
+ // hosted away from its trigger then still takes its sequential focus
+ // order (and its popover nesting) from the trigger rather than from its
+ // own DOM position. Browsers without the option ignore it.
+ popover.showPopover({source: triggerRef.current ?? undefined});
+ } else {
+ popover.style.display = 'block';
+ }
+ openedPopoverRef.current = popover;
+ }, []);
+
+ const isCurrentContextPopover = useCallback(
+ (popover: HTMLElement): boolean => {
+ if (mode !== 'context') {
+ return true;
}
+ const mount = contextMountRef.current;
+ if (mount === null) {
+ return false;
+ }
+ const expectedParent =
+ mount.portalTarget ?? sentinelRef.current?.parentElement ?? null;
+ return popover.parentElement === expectedParent;
+ },
+ [mode],
+ );
+
+ const requestContextMount = useCallback(() => {
+ if (mode !== 'context') {
+ return;
+ }
+
+ const sentinel = sentinelRef.current;
+ const inlineParent = sentinel?.parentElement ?? null;
+ if (!sentinel || !inlineParent) {
+ return;
+ }
+
+ const portalTarget = resolveLayerPortalTarget(inlineParent);
+ const mount: ContextLayerMount = {
+ portalTarget,
+ portalStyle: portalTarget
+ ? readPortalWritingContext(sentinel, portalTarget)
+ : {},
+ };
+ contextMountRef.current = mount;
+ setContextMount(mount);
+ }, [mode]);
+
+ const clearContextMount = useCallback(() => {
+ if (mode !== 'context' || !lazyMount) {
+ return;
+ }
+ contextMountRef.current = null;
+ setContextMount(null);
+ }, [mode, lazyMount]);
+
+ const show = useCallback(() => {
+ // A context popover left over until React commits a previous hide must not
+ // be reopened. The synchronous mount ref is the source of truth.
+ const candidate = popoverRef.current;
+ const popover =
+ candidate && isCurrentContextPopover(candidate) ? candidate : null;
+ if (!popover) {
+ pendingShowRef.current = true;
+ requestContextMount();
+ return;
+ }
+ if (!isOpenRef.current) {
+ showPopoverElement(popover);
isOpenRef.current = true;
setIsOpen(true);
onShow?.();
}
- }, [onShow]);
+ }, [
+ onShow,
+ requestContextMount,
+ showPopoverElement,
+ isCurrentContextPopover,
+ ]);
const hide = useCallback(() => {
+ pendingShowRef.current = false;
if (isOpenRef.current) {
const el = popoverRef.current;
// See finding infra-4 note in `show`: mirror the same guard on hide so
@@ -450,11 +578,13 @@ export function useLayer(
el.style.display = 'none';
}
}
+ openedPopoverRef.current = null;
isOpenRef.current = false;
setIsOpen(false);
onHide?.();
}
- }, [onHide]);
+ clearContextMount();
+ }, [onHide, clearContextMount]);
// Ref for trigger element (context mode only)
const ref: RefCallback<HTMLElement> | undefined =
@@ -488,12 +618,14 @@ export function useLayer(
(e: Event) => {
const toggleEvent = e as ToggleEvent;
if (toggleEvent.newState === 'closed' && isOpenRef.current) {
+ openedPopoverRef.current = null;
isOpenRef.current = false;
setIsOpen(false);
onHide?.();
+ clearContextMount();
}
},
- [onHide],
+ [onHide, clearContextMount],
);
// Ref callback for popover element — sets up the `toggle` listener.
@@ -531,8 +663,40 @@ export function useLayer(
(el: HTMLElement | null) => {
popoverRef.current = el;
bindToggleListener(el, handleToggle);
+ if (el && pendingShowRef.current) {
+ pendingShowRef.current = false;
+ show();
+ } else if (
+ el &&
+ isOpenRef.current &&
+ openedPopoverRef.current !== el &&
+ isCurrentContextPopover(el)
+ ) {
+ // Changing a portal target remounts the popover. Preserve the logical
+ // open state without firing onShow again for the replacement element.
+ showPopoverElement(el);
+ }
+ },
+ [
+ handleToggle,
+ bindToggleListener,
+ show,
+ showPopoverElement,
+ isCurrentContextPopover,
+ ],
+ );
+
+ const sentinelRefCallback = useCallback(
+ (el: HTMLTemplateElement | null) => {
+ sentinelRef.current = el;
+ if (el && (!lazyMount || pendingShowRef.current || isOpenRef.current)) {
+ // The render call may have moved while the hook stayed mounted.
+ // Resolve again from the newly attached marker rather than reusing a
+ // portal target from its previous JSX position.
+ requestContextMount();
+ }
},
- [handleToggle, bindToggleListener],
+ [lazyMount, requestContextMount],
);
// Re-bind when the handler identity changes while the element stays mounted,
@@ -556,6 +720,15 @@ export function useLayer(
// Render function for context mode
const renderContext = useCallback(
(children: ReactNode, props?: ContextRenderProps) => {
+ // Keep the marker mounted after resolving the layer. Apart from giving
+ // us the real JSX parent on first show, this lets its ref report when a
+ // persistent hook's render call moves to a different host.
+ const sentinel = <template ref={sentinelRefCallback} />;
+
+ if (contextMount === null) {
+ return <>{sentinel}</>;
+ }
+
const {
placement = 'above',
alignment = 'center',
@@ -598,10 +771,10 @@ export function useLayer(
? `${extraClassName} ${stylexResult.className ?? ''}`
: stylexResult.className;
- // Render as the requested tag. A `span` keeps the layer phrasing content
- // so it is valid (and stays put on hydration) inside inline contexts like
- // a `<p>`; `div` remains the default for block layers.
- return (
+ // The marker gives us the actual JSX parent without mounting arbitrary
+ // children there. Safe positions preserve the existing DOM order and
+ // cascade; unsafe positions use the nearest corrective portal target.
+ const layer = (
<Container
ref={popoverRefCallback}
id={id}
@@ -609,14 +782,35 @@ export function useLayer(
aria-label={ariaLabel}
popover={lightDismiss ? 'auto' : 'manual'}
className={combinedClassName}
- style={{...stylexResult.style, ...anchorStyle, ...extraStyle}}
+ style={{
+ ...stylexResult.style,
+ ...anchorStyle,
+ ...contextMount.portalStyle,
+ ...extraStyle,
+ }}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}>
{children}
</Container>
);
+
+ return (
+ <>
+ {sentinel}
+ {contextMount.portalTarget
+ ? createPortal(layer, contextMount.portalTarget)
+ : layer}
+ </>
+ );
},
- [anchorId, id, lightDismiss, popoverRefCallback],
+ [
+ anchorId,
+ contextMount,
+ id,
+ lightDismiss,
+ popoverRefCallback,
+ sentinelRefCallback,
+ ],
);
// Render function for fixed mode
diff --git a/packages/core/src/Timestamp/Timestamp.test.tsx b/packages/core/src/Timestamp/Timestamp.test.tsx
index 3a29034010..9405d7bcca 100644
--- a/packages/core/src/Timestamp/Timestamp.test.tsx
+++ b/packages/core/src/Timestamp/Timestamp.test.tsx
@@ -16,6 +16,24 @@ import {formatTooltipLines} from './tooltipEntries';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import {InternationalizationProvider} from '../i18n';
+async function openTimestampHoverCard(): Promise<HTMLElement> {
+ const timestamp = document.querySelector('time');
+ if (timestamp == null) {
+ throw new Error('Expected Timestamp to render a <time> element');
+ }
+ const trigger = timestamp.parentElement;
+ if (trigger == null) {
+ throw new Error('Expected Timestamp to render a hover-card trigger');
+ }
+
+ fireEvent.mouseEnter(trigger);
+ await waitFor(() => {
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
+ });
+
+ return screen.getByRole('dialog', {hidden: true});
+}
+
describe('Timestamp', () => {
// The hover card is loaded lazily (React.lazy + Suspense), so its chunk
// resolves asynchronously the first time a card renders. Warm the module
@@ -646,14 +664,13 @@ describe('Timestamp', () => {
);
const el = screen.getByTestId('ts');
- // The card layer mounts inline and carries the full absolute time in
- // its visible form (short timezone abbreviation) as its single default
- // copyable row. The aria-label spells the timezone out in full
- // (WCAG 3.1.4), so the two strings intentionally differ — compare the
- // card against an independently formatted short-form string.
+ // The card carries the full absolute time in its visible form (short
+ // timezone abbreviation) as its single default copyable row. The
+ // aria-label spells the timezone out in full (WCAG 3.1.4), so the two
+ // strings intentionally differ — compare the card against an
+ // independently formatted short-form string after opening it.
// Compare with normalized whitespace: Intl output can contain narrow
// no-break spaces that jest-dom's matcher normalization would break on.
- const card = await screen.findByRole('dialog', {hidden: true});
const normalize = (s: string) => s.replace(/\s+/g, ' ');
const datetime = new Date(el.getAttribute('datetime') ?? '');
const expected = new Intl.DateTimeFormat(undefined, {
@@ -665,14 +682,14 @@ describe('Timestamp', () => {
second: '2-digit',
timeZoneName: 'short',
}).format(datetime);
- expect(normalize(card.textContent ?? '')).toContain(normalize(expected));
-
// Tab onto the timestamp — the only tab stop in the document.
await user.tab();
expect(el).toHaveFocus();
await waitFor(() => {
expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
});
+ const card = screen.getByRole('dialog', {hidden: true});
+ expect(normalize(card.textContent ?? '')).toContain(normalize(expected));
});
it('does not add a tab stop when the hover card is disabled', () => {
@@ -756,7 +773,7 @@ describe('Timestamp', () => {
.queryAllByRole('tooltip', {hidden: true})
.filter(el => !/^(Copy|Copied)$/.test(el.textContent?.trim() ?? '')),
).toHaveLength(0);
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
// The default card is the named details card, exactly as the configured
// one is.
expect(card).toHaveAttribute('aria-label', 'Timestamp details');
@@ -786,7 +803,7 @@ describe('Timestamp', () => {
it("copies the default absolute row's value", async () => {
render(<Timestamp value={Date.now() / 1000 - 3600} format="relative" />);
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
const rowValue = card.querySelector('dd')?.textContent ?? '';
expect(rowValue).toBeTruthy();
fireEvent.click(card.querySelector('button')!);
@@ -802,10 +819,11 @@ describe('Timestamp', () => {
it("shows a 'Copy' tooltip on the copy button, flipping to 'Copied' after a copy", async () => {
render(<Timestamp value={Date.now() / 1000 - 3600} format="relative" />);
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
const button = card.querySelector('button')!;
// The visible tooltip content defaults to the short imperative 'Copy'
// (the full "Copy <value>" string stays the button's aria-label).
+ fireEvent.mouseEnter(button);
await waitFor(() =>
expect(
screen.getByText('Copy', {
@@ -872,7 +890,7 @@ describe('Timestamp', () => {
.queryAllByRole('tooltip', {hidden: true})
.filter(el => !/^(Copy|Copied)$/.test(el.textContent?.trim() ?? '')),
).toHaveLength(0);
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
expect(card).toHaveAttribute('aria-label', 'Timestamp details');
});
@@ -888,7 +906,7 @@ describe('Timestamp', () => {
]}
/>,
);
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
expect(card.querySelectorAll('dd')).toHaveLength(3);
// Entries are read-only unless they opt in, so no copy buttons and no
// trailing action column are rendered.
@@ -915,7 +933,7 @@ describe('Timestamp', () => {
]}
/>,
);
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
// Three rows, but only the opted-in row carries a copy button.
expect(card.querySelectorAll('dd')).toHaveLength(3);
expect(card.querySelectorAll('button')).toHaveLength(1);
@@ -936,7 +954,7 @@ describe('Timestamp', () => {
]}
/>,
);
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
const values = Array.from(card.querySelectorAll('dd')).map(
el => el.textContent,
);
@@ -960,7 +978,7 @@ describe('Timestamp', () => {
]}
/>,
);
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
const [rowValue] = Array.from(card.querySelectorAll('dd')).map(
el => el.textContent ?? '',
);
@@ -991,7 +1009,7 @@ describe('Timestamp', () => {
/>
</InternationalizationProvider>,
);
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
fireEvent.click(card.querySelector('button')!);
await waitFor(() => {
expect(
@@ -1011,7 +1029,7 @@ describe('Timestamp', () => {
);
// Without entries an absolute format has no hover surface at all;
// configuring entries must not be silently ignored.
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
expect(card.textContent).toContain('UTC');
// ...and the anchor becomes keyboard-reachable, as it is for relative.
expect(screen.getByTestId('ts')).toHaveAttribute('tabindex', '0');
@@ -1120,7 +1138,7 @@ describe('Timestamp', () => {
/>,
);
// autoThreshold={0} forces the absolute branch regardless of the clock.
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
expect(card.textContent).toContain('2026-02-19 17:00:00');
expect(screen.getByTestId('ts')).toHaveAttribute('tabindex', '0');
});
@@ -1135,7 +1153,7 @@ describe('Timestamp', () => {
]}
/>,
);
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
expect(card.textContent).toContain('2026-02-19 17:00:00');
});
@@ -1151,7 +1169,7 @@ describe('Timestamp', () => {
]}
/>,
);
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
// An unlabeled entry still emits its label cell, so the grid stays
// aligned and the <dl> stays valid markup.
expect(card.querySelectorAll('dt')).toHaveLength(3);
@@ -1189,7 +1207,7 @@ describe('Timestamp', () => {
]}
/>,
);
- const card = await screen.findByRole('dialog', {hidden: true});
+ const card = await openTimestampHoverCard();
const values = Array.from(card.querySelectorAll('dd')).map(
el => el.textContent,
);
diff --git a/packages/core/src/Toolbar/Toolbar.test.tsx b/packages/core/src/Toolbar/Toolbar.test.tsx
index 40bdcfaf97..744035201f 100644
--- a/packages/core/src/Toolbar/Toolbar.test.tsx
+++ b/packages/core/src/Toolbar/Toolbar.test.tsx
@@ -72,11 +72,11 @@ describe('Toolbar', () => {
expect(screen.getByTestId('end')).toBeInTheDocument();
// Three-slot layout produces 3 child divs (plus the aria-hidden
- // keyboard-hint popover, which is excluded here as an implementation detail)
+ // keyboard-hint layer infrastructure, excluded as an implementation detail)
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.querySelectorAll(':scope > :not([popover])')).toHaveLength(
- 3,
- );
+ expect(
+ toolbar.querySelectorAll(':scope > :not([popover]):not(template)'),
+ ).toHaveLength(3);
});
it('renders two-slot layout without centerContent', () => {
@@ -91,11 +91,11 @@ describe('Toolbar', () => {
expect(screen.getByTestId('end')).toBeInTheDocument();
// Two-slot layout produces 2 child divs (plus the aria-hidden
- // keyboard-hint popover, excluded here)
+ // keyboard-hint layer infrastructure, excluded here)
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.querySelectorAll(':scope > :not([popover])')).toHaveLength(
- 2,
- );
+ expect(
+ toolbar.querySelectorAll(':scope > :not([popover]):not(template)'),
+ ).toHaveLength(2);
});
it('renders start-only layout', () => {
@@ -107,9 +107,9 @@ describe('Toolbar', () => {
);
expect(screen.getByTestId('start')).toBeInTheDocument();
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.querySelectorAll(':scope > :not([popover])')).toHaveLength(
- 1,
- );
+ expect(
+ toolbar.querySelectorAll(':scope > :not([popover]):not(template)'),
+ ).toHaveLength(1);
});
it('renders end-only layout', () => {
@@ -121,9 +121,9 @@ describe('Toolbar', () => {
);
expect(screen.getByTestId('end')).toBeInTheDocument();
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.querySelectorAll(':scope > :not([popover])')).toHaveLength(
- 1,
- );
+ expect(
+ toolbar.querySelectorAll(':scope > :not([popover]):not(template)'),
+ ).toHaveLength(1);
});
it('sets aria-orientation to horizontal by default', () => {