An open source design system that's fully customizable and agent ready
TypeScript
fix(HoverCard): render layer inline to fix SSR hydration mismatch (#3153)
Cindy Zhangb6ade741b201
diff --git a/.changeset/hovercard-ssr-hydration-inline.md b/.changeset/hovercard-ssr-hydration-inline.mdnew file mode 100644index 0000000000..af9b532041--- /dev/null+++ b/.changeset/hovercard-ssr-hydration-inline.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Fix HoverCard SSR hydration mismatch when used inside an SSR Client Component (#3107). The floating layer now renders inline instead of portaling to `document.body`, so server and client markup match. No API change.+@cixzhangdiff --git a/packages/core/src/HoverCard/HoverCard.doc.mjs b/packages/core/src/HoverCard/HoverCard.doc.mjsindex e75ede3254..11478a930c 100644--- a/packages/core/src/HoverCard/HoverCard.doc.mjs+++ b/packages/core/src/HoverCard/HoverCard.doc.mjs@@ -108,6 +108,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.' },],anatomy: [{name: 'Trigger', required: true, description: 'The element that opens the hover card on hover or focus: a button, link, or inline text.'},@@ -216,6 +217,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.' },],},};@@ -233,6 +235,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.' },],},components: [diff --git a/packages/core/src/HoverCard/HoverCard.test.tsx b/packages/core/src/HoverCard/HoverCard.test.tsxindex d10c6b5c73..fdb75f311e 100644--- a/packages/core/src/HoverCard/HoverCard.test.tsx+++ b/packages/core/src/HoverCard/HoverCard.test.tsx@@ -10,7 +10,10 @@*/import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';-import {render, screen, fireEvent, waitFor} from '@testing-library/react';+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 {HoverCard} from './HoverCard';// Store original matches to restore later@@ -73,6 +76,31 @@ describe('HoverCard', () => {expect(paragraph?.querySelector('div')).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.+ const {container} = render(+ <p>+ Before{' '}+ <HoverCard content={<span>Card content</span>}>+ <a href="#trigger">Trigger</a>+ </HoverCard>{' '}+ after+ </p>,+ );++ const paragraph = container.querySelector('p');+ const layer = screen.getByText('Card content').closest('[popover]');++ 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(paragraph?.querySelector('div')).toBeNull();+ });+it('does not show content initially', () => {render(<HoverCard content={<span>Card content</span>}>@@ -84,7 +112,7 @@ describe('HoverCard', () => {expect(content).toBeInTheDocument();});- it('applies the theme body font to the portaled layer', () => {+ it('applies the theme body font to the floating layer', () => {render(<HoverCard content={<span>Card content</span>}><button type="button">Trigger</button>@@ -370,4 +398,152 @@ describe('HoverCard', () => {expect(onOpenChange).not.toHaveBeenCalledWith(true);});});++ describe('SSR / hydration', () => {+ // Regression coverage for the hydration mismatch (#3107). The floating+ // layer used to be portaled into document.body behind a+ // `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.++ it('renders the floating layer in server markup (no document gate)', () => {+ const html = renderToString(+ <HoverCard content={<span>Card content</span>}>+ <button type="button">Trigger</button>+ </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"/);+ });++ it('keeps the floating layer inline-safe in server markup inside a paragraph', () => {+ const html = renderToString(+ <p>+ Before{' '}+ <HoverCard content={<span>Card content</span>}>+ <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).+ expect(html).not.toContain('<div');+ expect(html).toMatch(/<span[^>]*popover="manual"/);+ });++ it('server markup matches the first client render (no hydration mismatch)', async () => {+ const tree = (+ <StrictMode>+ <p>+ Glossary:{' '}+ <HoverCard content={<span>Definition</span>}>+ <a href="#term">term</a>+ </HoverCard>+ .+ </p>+ </StrictMode>+ );++ const serverHTML = renderToString(tree);++ const container = document.createElement('div');+ container.innerHTML = serverHTML;+ document.body.appendChild(container);++ // Capture any hydration diagnostics. React reports hydration mismatches+ // both through console.error and through onRecoverableError.+ const consoleErrorSpy = vi+ .spyOn(console, 'error')+ .mockImplementation(() => {});+ const recoverableErrors: unknown[] = [];++ let root: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree, {+ onRecoverableError: error => {+ recoverableErrors.push(error);+ },+ });+ });++ const hydrationErrors = consoleErrorSpy.mock.calls.filter(call =>+ String(call[0] ?? '')+ .toLowerCase()+ .includes('hydrat'),+ );++ expect(hydrationErrors).toEqual([]);+ expect(recoverableErrors).toEqual([]);++ await act(async () => {+ root.unmount();+ });+ consoleErrorSpy.mockRestore();+ container.remove();+ });++ it('hydrates a default-open hover card without a mismatch', async () => {+ vi.mocked(HTMLElement.prototype.showPopover).mockClear();++ const tree = (+ <HoverCard content={<span>Default open</span>} isDefaultOpen>+ <button type="button">Trigger</button>+ </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"');++ const container = document.createElement('div');+ container.innerHTML = serverHTML;+ document.body.appendChild(container);++ const consoleErrorSpy = vi+ .spyOn(console, 'error')+ .mockImplementation(() => {});+ const recoverableErrors: unknown[] = [];++ let root: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree, {+ onRecoverableError: error => {+ recoverableErrors.push(error);+ },+ });+ });++ const hydrationErrors = consoleErrorSpy.mock.calls.filter(call =>+ String(call[0] ?? '')+ .toLowerCase()+ .includes('hydrat'),+ );+ expect(hydrationErrors).toEqual([]);+ expect(recoverableErrors).toEqual([]);++ // The card opens after hydration via the mount effect.+ await waitFor(() => {+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();+ });++ await act(async () => {+ root.unmount();+ });+ consoleErrorSpy.mockRestore();+ container.remove();+ });+ });});diff --git a/packages/core/src/HoverCard/HoverCard.tsx b/packages/core/src/HoverCard/HoverCard.tsxindex 0fe6a0491d..d1fa4e71e5 100644--- a/packages/core/src/HoverCard/HoverCard.tsx+++ b/packages/core/src/HoverCard/HoverCard.tsx@@ -4,9 +4,9 @@/*** @file HoverCard.tsx- * @input Uses React, ReactDOM createPortal, useHoverCard hook+ * @input Uses React, useHoverCard hook* @output Exports HoverCard component for hover/focus triggered layers- * @position Layer component; uses inline-safe trigger wrapper and portals floating layer+ * @position Layer component; uses inline-safe trigger wrapper and renders the floating layer inline** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/HoverCard/HoverCard.test.tsx@@ -15,13 +15,7 @@* - /packages/cli/templates/blocks/components/HoverCard/ (showcase blocks)*/-import React, {- useCallback,- useRef,- type ReactElement,- type ReactNode,-} from 'react';-import {createPortal} from 'react-dom';+import {useCallback, useRef, type ReactElement, type ReactNode} from 'react';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import * as stylex from '@stylexjs/stylex';import {useHoverCard, type HoverCardFocusTrigger} from './useHoverCard';@@ -245,13 +239,23 @@ export function HoverCard({};}, [textOnly, hoverCard.ref, hoverCard.describedBy]);- const renderedHoverCard =- typeof document !== 'undefined'- ? createPortal(- hoverCard.renderHoverCard(content, {xstyle, className, style}),- document.body,- )- : null;+ // 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).+ const renderedHoverCard = hoverCard.renderHoverCard(content, {+ xstyle,+ className,+ style,+ });// For text-only children: use inline span with ref on wrapperif (textOnly) {diff --git a/packages/core/src/HoverCard/useHoverCard.tsx b/packages/core/src/HoverCard/useHoverCard.tsxindex b3f9cf8456..decd4ddc86 100644--- a/packages/core/src/HoverCard/useHoverCard.tsx+++ b/packages/core/src/HoverCard/useHoverCard.tsx@@ -58,8 +58,12 @@ const styles = stylex.create({marginInlineStart: spacingVars['--spacing-1'],marginInlineEnd: spacingVars['--spacing-1'],},- // Content wrapper for padding and mouse events+ // 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: {+ display: 'block',paddingBlockStart: spacingVars['--spacing-3'],paddingBlockEnd: spacingVars['--spacing-3'],paddingInlineStart: spacingVars['--spacing-3'],@@ -234,9 +238,7 @@ function isFocusable(element: HTMLElement): boolean {* {hoverCard.renderHoverCard(<ProfileCard user={user} />)}* ```*/-export function useHoverCard(- options: HoverCardOptions = {},-): HoverCardReturn {+export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {const {placement = 'above',alignment = 'center',@@ -454,14 +456,14 @@ export function useHoverCard(placement: renderPlacement,alignment: props?.alignment ?? alignment,xstyle: [popoverXstyle, layerAnimations[renderPlacement]],+ // 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,};return layer.render(- <div- {...mergeProps(- themeProps('hovercard'),- stylex.props(styles.content),- )}+ <span+ {...mergeProps(themeProps('hovercard'), stylex.props(styles.content))}onMouseEnter={() => {isHoveringContentRef.current = true;clearTimeouts();@@ -502,7 +504,7 @@ export function useHoverCard(scheduleHide();}}>{children}- </div>,+ </span>,renderProps,);},diff --git a/packages/core/src/Layer/useLayer.doc.mjs b/packages/core/src/Layer/useLayer.doc.mjsindex 8d221535f8..bbbf6634dd 100644--- a/packages/core/src/Layer/useLayer.doc.mjs+++ b/packages/core/src/Layer/useLayer.doc.mjs@@ -78,7 +78,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.',+ 'Render function for the popover element. Pass placement/alignment in context mode or x/y in fixed mode. 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.',},],usage: {@@ -95,6 +95,11 @@ export const docs = {description:'Build on higher-level components like Popover, HoverCard, and Tooltip for common overlay patterns.',},+ {+ 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\u2019s theme cascade and keeps a natural focus order. Use `as: "span"` when the layer must be valid inside inline contexts like a paragraph.',+ },{guidance: false,description:@@ -125,7 +130,7 @@ 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.',+ render: 'renders popover element; pass placement/alignment or x/y. Context mode accepts `as: "span"` for inline-safe layers. Renders inline; the Popover API top layer escapes clipping/stacking without a portal.',},usage: {description:diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex 9d792baaa3..8a70cfe708 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -79,6 +79,19 @@ export interface ContextRenderProps {* Merged after StyleX and anchor positioning styles.*/style?: React.CSSProperties;+ /**+ * 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.+ *+ * @default 'div'+ */+ as?: 'div' | 'span';}/**@@ -369,6 +382,7 @@ export function useLayer(xstyle,className: extraClassName,style: extraStyle,+ as: Container = 'div',} = props || {};// CSS anchor positioning (dynamic, not in StyleX)@@ -383,15 +397,18 @@ 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 (- <div+ <Containerref={popoverRefCallback}id={id}popover={lightDismiss ? 'auto' : 'manual'}className={combinedClassName}style={{...stylexResult.style, ...anchorStyle, ...extraStyle}}>{children}- </div>+ </Container>);},[anchorId, id, lightDismiss, popoverRefCallback],