An open source design system that's fully customizable and agent ready
TypeScript
perf(useLayer): placing a context layer re-renders its slot, not its host (#8519)
Christopher Chedeau87a9e776c66b
diff --git a/.changeset/layer-slot-second-render.md b/.changeset/layer-slot-second-render.mdnew file mode 100644index 0000000000..043c32ecea--- /dev/null+++ b/.changeset/layer-slot-second-render.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] useLayer: placing a context layer no longer re-renders its host. The hook still resolves where the layer goes from its inert marker once the marker is in the DOM, but it now hands that mount to an internal slot that renders the marker and the layer, so the render that places the layer is the slot's alone. A Tooltip, Selector or ComplexSelector that mounts closed renders once; a Popover or DropdownMenu keeps only the renders its own state costs. The host still renders when a resolved mount is replaced by a render call that moved to another host. The DOM, server markup, hydration and `lazyMount` are unchanged.++@vjeuxdiff --git a/packages/core/src/Layer/useLayer.doc.mjs b/packages/core/src/Layer/useLayer.doc.mjsindex 7152ae1580..3f7210fa5e 100644--- a/packages/core/src/Layer/useLayer.doc.mjs+++ b/packages/core/src/Layer/useLayer.doc.mjs@@ -86,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. 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.',+ '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, and it re-renders only the slot that holds the marker and the layer, not the component that called the hook (which renders again only when a resolved mount is replaced by a render call that moved to another host); `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: {diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsxindex 79eb6aedd5..87bdc3a693 100644--- a/packages/core/src/Layer/useLayer.test.tsx+++ b/packages/core/src/Layer/useLayer.test.tsx@@ -18,7 +18,9 @@ import {waitFor,} from '@testing-library/react';import userEvent from '@testing-library/user-event';-import {useEffect} from 'react';+import {Profiler, useEffect} from 'react';+import {hydrateRoot} from 'react-dom/client';+import {renderToString} from 'react-dom/server';import * as stylex from '@stylexjs/stylex';import {useKeepLayerOpenProps,@@ -490,6 +492,31 @@ describe('useLayer', () => {});describe('context hosting', () => {+ it('installs the slide rules for a render call that mounts after its host', () => {+ document.getElementById('astryx-layer-slide-rules')?.remove();+ function LateRenderHarness({showLayer}: {readonly showLayer: boolean}) {+ const layer = useLayer({mode: 'context'});+ return (+ <div>+ <button type="button" ref={layer.ref} onClick={layer.show}>+ Trigger+ </button>+ {showLayer ? layer.render(<span>Layer content</span>) : null}+ </div>+ );+ }+ const {rerender} = render(<LateRenderHarness showLayer={false} />);+ expect(document.getElementById('astryx-layer-slide-rules')).toBeNull();++ rerender(<LateRenderHarness showLayer />);+ // The marker's arrival resolves the mount and installs the sheet, so a+ // layer that joins its host later still slides (FR4) instead of+ // covering its own trigger on a narrow viewport.+ expect(+ document.getElementById('astryx-layer-slide-rules'),+ ).not.toBeNull();+ });+it('keeps closed content mounted by default for existing consumers', () => {const {container} = render(<ContextLayerHarness />);@@ -498,6 +525,87 @@ describe('useLayer', () => {expect(container).toHaveTextContent('Layer content');});+ it('renders the host once on a closed mount; the second commit is the slot placing the layer', () => {+ const renders = {host: 0, commits: 0};+ function CountingHarness() {+ renders.host += 1;+ const layer = useLayer({mode: 'context'});+ return (+ <div data-testid="host">+ <button type="button" ref={layer.ref} onClick={layer.show}>+ Trigger+ </button>+ {layer.render(<span>Layer content</span>)}+ </div>+ );+ }+ const {container, getByTestId} = render(+ <Profiler+ id="layer"+ onRender={() => {+ renders.commits += 1;+ }}>+ <CountingHarness />+ </Profiler>,+ );++ expect(renders.host).toBe(1);+ expect(renders.commits).toBe(2);+ const layer = container.querySelector('[popover]');+ expect(layer).not.toBeNull();+ expect(layer?.parentElement).toBe(getByTestId('host'));+ expect(layer?.previousElementSibling?.tagName).toBe('TEMPLATE');+ });++ it('renders the host once when the marker sits in an unsafe parent; the slot portals the layer out', () => {+ const renders = {host: 0};+ function CountingUnsafeHarness() {+ renders.host += 1;+ const layer = useLayer({mode: 'context'});+ return (+ <div data-testid="host">+ <p data-testid="paragraph">+ <button type="button" ref={layer.ref} onClick={layer.show}>+ Trigger+ </button>+ {layer.render(<span>Layer content</span>)}+ </p>+ </div>+ );+ }+ const {container, getByTestId} = render(<CountingUnsafeHarness />);++ expect(renders.host).toBe(1);+ const layer = container.querySelector('[popover]');+ expect(layer?.parentElement).toBe(getByTestId('host'));+ expect(getByTestId('paragraph').querySelector('[popover]')).toBeNull();+ expect(getByTestId('paragraph').querySelector('template')).not.toBeNull();+ });++ it('hydrates server markup that carries the marker alone, then mounts the layer', () => {+ const markup = renderToString(<ContextLayerHarness />);+ expect(markup).toContain('<template');+ expect(markup).not.toContain('popover=');++ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});+ const container = document.createElement('div');+ container.innerHTML = markup;+ document.body.appendChild(container);+ try {+ act(() => {+ hydrateRoot(container, <ContextLayerHarness />);+ });+ expect(errors).not.toHaveBeenCalled();+ const layer = container.querySelector('[popover]');+ expect(layer).not.toBeNull();+ expect(layer?.previousElementSibling?.tagName).toBe('TEMPLATE');+ expect(container).toHaveTextContent('Layer content');+ } finally {+ errors.mockRestore();+ container.remove();+ }+ });+it('renders only an inert marker until show is requested', () => {const {container} = render(<ContextHostingHarness />);diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex 44cf56fd1f..1d0fdc37e7 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -21,6 +21,7 @@ import React, {useMemo,useRef,useState,+ useSyncExternalStore,type ReactNode,type RefCallback,} from 'react';@@ -851,6 +852,81 @@ interface ContextLayerMount {portalStyle: React.CSSProperties;}+/**+ * Where a context layer is hosted, published to the one component that+ * renders it. The hook resolves the mount from the marker's parent once the+ * marker is in the DOM, and the slot below subscribes to it, so the render+ * that places the layer re-renders the slot alone: the hook's host (a+ * Tooltip, a Popover, a menu) and everything under it render once on mount.+ */+interface ContextLayerMountStore {+ readonly get: () => ContextLayerMount | null;+ readonly set: (mount: ContextLayerMount | null) => void;+ readonly subscribe: (onChange: () => void) => () => void;+}++function createContextLayerMountStore(): ContextLayerMountStore {+ let mount: ContextLayerMount | null = null;+ const listeners = new Set<() => void>();+ return {+ get: () => mount,+ set: next => {+ if (next === mount) {+ return;+ }+ mount = next;+ for (const listener of listeners) {+ listener();+ }+ },+ subscribe: onChange => {+ listeners.add(onChange);+ return () => {+ listeners.delete(onChange);+ };+ },+ };+}++const readNoMount = (): ContextLayerMount | null => null;++/**+ * The marker and, once the hook has resolved where it goes, the layer. The+ * server and the hydrating render carry the marker alone, so block content+ * never enters server markup inside `<p>` and its kin; the mount arrives from+ * the marker's ref callback, and only this component re-renders to place the+ * layer.+ */+function ContextLayerSlot({+ mountStore,+ renderLayer,+ sentinelRef,+}: {+ readonly mountStore: ContextLayerMountStore;+ readonly renderLayer: (mount: ContextLayerMount) => ReactNode;+ readonly sentinelRef: RefCallback<HTMLTemplateElement>;+}) {+ const mount = useSyncExternalStore(+ mountStore.subscribe,+ mountStore.get,+ readNoMount,+ );+ // 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={sentinelRef} />;+ if (mount === null) {+ return <>{sentinel}</>;+ }+ const layer = renderLayer(mount);+ return (+ <>+ {sentinel}+ {mount.portalTarget ? createPortal(layer, mount.portalTarget) : layer}+ </>+ );+}+function readPortalWritingContext(element: HTMLElement,portalTarget: HTMLElement,@@ -1113,9 +1189,13 @@ function useLayerImplementation(// 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,- );+ // The resolved mount reaches the slot through this store, never through+ // state on this hook, so placing the layer renders the slot alone. The+ // generation counts mounts that REPLACE a resolved one (a render call that+ // moved to another host): the layer element is recreated then, and the+ // effects below that bind to it re-run.+ const [mountStore] = useState(createContextLayerMountStore);+ const [mountGeneration, setMountGeneration] = useState(0);// A show() that cannot run yet is remembered here and replayed: one that// arrives before the final layer mounts runs when its popover ref attaches;// one that arrives while another popover is mid show/hide runs once that@@ -1198,6 +1278,12 @@ function useLayerImplementation(return;}+ // The slide options' `@position-try` rules (FR4) are installed in the+ // layer's document before its first paint, here where the mount resolves:+ // the marker's arrival is the one event every mount has, whether the+ // render call mounts with its host or later. One sheet serves every layer.+ ensureSlideRules(sentinel.ownerDocument);+const portalTarget = resolveLayerPortalTarget(inlineParent);const mount: ContextLayerMount = {portalTarget,@@ -1205,17 +1291,21 @@ function useLayerImplementation(? readPortalWritingContext(sentinel, portalTarget): {},};+ const replaced = contextMountRef.current !== null;contextMountRef.current = mount;- setContextMount(mount);- }, [mode]);+ mountStore.set(mount);+ if (replaced) {+ setMountGeneration(generation => generation + 1);+ }+ }, [mode, mountStore]);const clearContextMount = useCallback(() => {if (mode !== 'context' || !lazyMount) {return;}contextMountRef.current = null;- setContextMount(null);- }, [mode, lazyMount]);+ mountStore.set(null);+ }, [mode, lazyMount, mountStore]);const show = useCallback(() => {// Every caller lands here, so this is where the dismissing press is@@ -1509,19 +1599,6 @@ function useLayerImplementation(};}, [handleToggle, bindToggleListener]);- // The slide options' `@position-try` rules (FR4) are installed in the- // layer's document before its first paint; one sheet serves every layer.- useIsomorphicLayoutEffect(() => {- if (mode !== 'context') {- return;- }- const doc =- popoverRef.current?.ownerDocument ?? sentinelRef.current?.ownerDocument;- if (doc) {- ensureSlideRules(doc);- }- }, [mode, contextMount]);-// Anchor visibility (FR5). The first frame must already be right (FR8), so// the opening read is synchronous — a layout effect runs before paint, and a// state change inside it re-renders before paint — against the visual@@ -1567,8 +1644,9 @@ function useLayerImplementation(// give the layer a scroll range (`observeAnchorClearance`). The external// systems are those browser observers and listeners; this effect binds them// while the layer is open and removes them when it closes, unmounts or is- // remounted by a moved render call (`contextMount`). A trigger replaced while- // open is rebound by the trigger callback ref, so no DOM node enters state.+ // remounted by a moved render call (`mountGeneration`). A trigger replaced+ // while open is rebound by the trigger callback ref, so no DOM node enters+ // state.useIsomorphicLayoutEffect(() => {if (!keepsAnchorClear || !isOpen || mode !== 'context') {return;@@ -1588,20 +1666,11 @@ function useLayerImplementation(clearObserversRef.current?.();clearObserversRef.current = null;};- }, [keepsAnchorClear, isOpen, mode, contextMount]);+ }, [keepsAnchorClear, isOpen, mode, mountGeneration]);// Render function for context modeconst 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',@@ -1687,7 +1756,8 @@ function useLayerImplementation(// 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 = (+ // The slot renders the layer once the hook has resolved that mount.+ const renderLayer = (mount: ContextLayerMount) => (<Containerref={popoverRefCallback}id={id}@@ -1701,7 +1771,7 @@ function useLayerImplementation(...clearanceProperty,...clearFallbacksProperty,...layerInsetProperties(declaredInset),- ...contextMount.portalStyle,+ ...mount.portalStyle,...extraStyle,}}onMouseEnter={onMouseEnter}@@ -1711,22 +1781,21 @@ function useLayerImplementation();return (- <>- {sentinel}- {contextMount.portalTarget- ? createPortal(layer, contextMount.portalTarget)- : layer}- </>+ <ContextLayerSlot+ mountStore={mountStore}+ renderLayer={renderLayer}+ sentinelRef={sentinelRefCallback}+ />);},[anchorId,- contextMount,declaredInset,id,isAnchorInView,keepsAnchorClear,lightDismiss,+ mountStore,popoverRefCallback,sentinelRefCallback,],