Repository navigation
perf(useLayer): placing a context layer re-renders its slot, not its host - #8519
Conversation
…host A context-mode layer resolves where it is hosted from its inert marker once the marker is in the DOM. That mount used to be state on the hook, so every Tooltip, Popover, DropdownMenu, Selector and ComplexSelector rendered twice on a closed mount, the second time with everything under it. The mount now reaches an internal ContextLayerSlot through a store the hook holds; the slot renders the marker and the layer, and the second render is its alone. The DOM, the server markup, hydration and lazyMount are unchanged.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
AI review status for this pull request.
|
PR Analysis Report📚 Storybook Preview🧪 Sandbox PreviewComponent Size
Sizes are gzip. Import counts the JavaScript the import loads eagerly; CSS counts the package stylesheet rules referenced by the modules it can load from its own package, lazily loaded ones included. Bundle Size SummaryGzip figures measure each package's entry file, not the code an import pulls in.
Accessibility AuditStatus: No accessibility violations detected. Visual Regression55 of 502 shot(s) changed. A change here is a question, not a failure: check whether the after is the
and 35 more. Generated by PR Enrichment workflow | Storybook | Sandbox | View full report |
There was a problem hiding this comment.
Requesting changes: the slot cuts the closed-mount host render from two to one for Tooltip, Selector and ComplexSelector, but the slide-rules effect in useLayer.tsx is now keyed on mountGeneration, which the first mount resolution doesn't bump. A layer whose render() call mounts after its host (a Popover leaving its bottom-sheet presentation, a conditional layer.render()) therefore never installs the @position-try sheet, so it cannot slide and on a narrow viewport can cover its own trigger. Please install the sheet where the mount resolves (in requestContextMount or ContextLayerSlot) and add a test that mounts the render call after its host with the sheet removed.
- The changeset lists Popover among components that now render once, but a closed Popover still renders three times on mount, and the doc's "never the component that called the hook" skips the replaced-mount path.
[Automated review]
| ensureSlideRules(doc); | ||
| } | ||
| }, [mode, contextMount]); | ||
| }, [mode, mountGeneration]); |
There was a problem hiding this comment.
This effect now re-runs only when mountGeneration changes, and the first resolution doesn't bump it. When the host's first commit doesn't include layer.render(), doc is undefined here and the slide-rules sheet is never installed. That happens for a Popover leaving its sheet presentation, or for a conditional render call, and the layer then loses its slide options. Installing the sheet where the mount resolves would cover it, for example in requestContextMount from the marker's document before mountStore.set(mount). A test that removes #astryx-layer-slide-rules and mounts the render call late would pin it.
There was a problem hiding this comment.
Right: the first resolution never bumped the generation, so a render call mounting after its host got no sheet. In fcfd008 the effect is gone and requestContextMount installs the sheet on sentinel.ownerDocument as the mount resolves, the one event every mount has. New test "installs the slide rules for a render call that mounts after its host" removes the sheet, mounts the host without layer.render(), then adds the render call; it fails on 0c2a642 (expected null not to be null) and passes on main and now.
| '@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 second render on mount is the slot's alone: a Tooltip, Popover, DropdownMenu, Selector or ComplexSelector and everything under it render once when they mount closed. The DOM, server markup, hydration and `lazyMount` are unchanged. |
There was a problem hiding this comment.
A closed Popover still renders three times on mount, before and after this change, because of its own mount-time state updates. Tooltip, Selector and ComplexSelector do go from two renders to one. Consider naming only the components that change.
There was a problem hiding this comment.
Agreed. The changeset now says the render that places the layer is the slot's alone, that a Tooltip, Selector or ComplexSelector that mounts closed renders once, and that a Popover or DropdownMenu keeps only the renders its own state costs.
| 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, never the component that called the hook; `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.', |
There was a problem hiding this comment.
When a resolved mount is replaced, for example when the render call moves, setMountGeneration re-renders the host, so "never the component that called the hook" is too strong. Scoping it to the first resolution would be accurate.
There was a problem hiding this comment.
Scoped in fcfd008: the doc now says the resolution re-renders the slot, 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.
…changeset names what renders once The slide-rules effect was keyed on mountGeneration, which the first resolution does not bump, so a render call that mounts after its host (a conditional layer.render()) never installed the @position-try sheet. The sheet is now installed in requestContextMount, the one event every mount has. A test mounts the render call after its host with the sheet removed. The changeset and doc stop claiming a Popover renders once: a Popover or DropdownMenu keeps the renders its own state costs, and the host renders again when a resolved mount is replaced.
There was a problem hiding this comment.
Recommending approval: the new slot keeps the marker, corrective-portal and slide-rule behavior intact while closed Tooltip, Selector and ComplexSelector hosts now render once on mount, and the earlier slide-rules and wording findings are fixed. One optional follow-up: under React StrictMode in development the marker's ref replay counts as a replaced mount, so the host still renders twice there; either bump mountGeneration only when a different marker element resolves the mount, or mention that replay in the useLayer.doc.mjs sentence.
[Automated review]
| ? readPortalWritingContext(sentinel, portalTarget) | ||
| : {}, | ||
| }; | ||
| const replaced = contextMountRef.current !== null; |
There was a problem hiding this comment.
Non-blocking: under StrictMode, React 19 attaches, detaches and re-attaches this marker's ref on mount, so the second requestContextMount finds a resolved mount here, bumps mountGeneration and re-renders the host; a StrictMode mount still renders the host twice. Remembering the marker element that produced contextMountRef.current, and bumping only when a different marker resolves the mount, would match the comment above and the new useLayer.doc.mjs sentence; otherwise that sentence could name StrictMode's development replay.
…s tooltip Three tests read a code block header's text right after it appeared. Since meta#8519 the copy button's tooltip arrives one render later, from its own layer slot, so on a busy runner the read could miss it. Each test now waits for the full text inside waitFor.
…s tooltip (#8569) ## Maintainer impact Found when the Spinner and CircularProgress fixes (#8177, #8232) hit this race in CI. Since #8519, `CodeBlockHeaderPlugin.test.tsx` can fail on a busy CI runner with no rich-text change: a header's text read `['ts', 'js']` instead of `['tsCopy code', 'jsCopy code']` on pull requests that touch neither rich text nor layers, which then needed a re-run. ## Intended invariant Each code block header shows its language label and a copy button whose tooltip reads "Copy code" (`spec:AST-061` FR8). The tests assert that text; product behavior stays as it is. ## Change What led to it: a header's text ends with its copy button's tooltip. Since #8519 the tooltip's layer is placed by its own slot one render after the header (the slot gets its mount from a store subscription). Three tests waited for the header to exist, then read its text, so a late slot render left the tooltip out. Options: - Wait for the full text inside `waitFor` (this PR): the tests stop assuming one render. - Render the tooltip in the header's render: a product change that would undo #8519's performance gain. - Retry or skip the flaky tests: that hides the race. This PR takes the first, since the one-render assumption was the tests', not the product's. The first test already finds the button by its accessible name, present from the start, so it is unchanged. ## Evidence - Failure before the change: with the slot seeing its mount 30 ms late (a temporary edit in `useLayer.tsx`), the old tests fail as the failing runs did: `expected '' to be 'Copy code'`, and `['', 'Plaintext']` for `['Copy code', 'PlaintextCopy code']`. - Success after the change: with the same delay the new tests pass, and without it too. - Product/runtime behavior verified unchanged: only the test file changes. ## Scope - [x] No intended public API, product behavior, visual direction, or policy change. - [x] Product changes discovered during the work were removed or split. - [x] Public text and artifacts contain no internal Meta context. ## Testing What I ran and what it showed: 1. `pnpm exec vitest run --project ui packages/richtext/src/CodeBlockHeaderPlugin.test.tsx`: all four tests pass. 2. With the layer mount store's update in `useLayer.tsx` delayed 30 ms, its value and its listeners both (a temporary edit): main's file fails three of the four tests; this file passes all four. 3. Local gates at 7d01151: root build, typecheck, ESLint, Prettier, the duration guard and `pnpm test:ui` (16,446 tests) pass; in the node project, the only failures are `cache.test.mjs`'s two install-lock cases, a known failure on this machine (#8520).
Primary intent
Performance of every context-mode
useLayerhost. A Tooltip, Popover, DropdownMenu, Selector or ComplexSelector that mounts closed renders twice: once with the inert marker, then again when the marker's ref callback resolves the mount and sets it as state on the hook, re-rendering the host and everything under it. Nothing visual or new, so no other template fits.User or maintainer impact
Every application mounting closed layers pays a second render of each host's subtree: a list of rows with menus renders every row twice. In one application's end-to-end suite (7,600 cases, production build), 110,000 of 1.3 million rendering commits had this origin, about 150 components each.
After this change the host renders once. The second render still happens, in an internal slot owning only the
<template>marker and the popover element. The DOM, server markup, hydration,lazyMountand the public API are unchanged.Problem and solution fit
A context layer cannot know its JSX parent until the marker is in the DOM, so the hook learns the mount in a ref callback and publishes it through
useStateon itself; that state re-renders the whole host for a fact that only places one element.The mount now reaches a
ContextLayerSlotchild through a store the hook holds; the slot subscribes withuseSyncExternalStoreand renders the marker and the layer. The hook keeps its synchronous ref forshow()and bumps amountGenerationonly when a resolved mount is replaced (a render call that moved), so the effects bound to the layer element still re-run then.Rejected: an inline first render corrected in the same commit trips React's development nesting validation (
<div>under<p>) and breaks the marker-only server markup of #5039; lazy mounting by default removes the closed layer from the DOM, danglesaria-controlsandaria-describedby, and changes a documented default.Authority
architecture:layer-runtimeINV1: inline when safe, a corrective portal beyond the outermost unsafe ancestor, as before.architecture:react-component-runtimeINV1 and INV4: no marker-only state repaired from a ref callback, and the mount is read through a subscription, not a ref. No record changes;useLayer's exports and options are unchanged.Change and evidence
useLayer.tsx:ContextLayerMountStore,ContextLayerSlot;requestContextMountwrites the store and the generation; the effects keyed oncontextMountkey onmountGeneration.useLayer.test.tsx: the host renders once on a closed mount while the run commits twice; the host renders once with the marker in a<p>, the slot portaling the layer out; server markup carries the marker alone, hydrates with no React error, then mounts the layer. The first two fail onmain.useLayer.doc.mjs: one sentence on what the resolution re-renders. Changeset[perf], patch.Scope
Testing
pnpm exec vitest run packages/core/src/Layer/useLayer.test.tsx: 88 passed (3 new).pnpm exec vitest run packages/core/src/{Layer,Tooltip,HoverCard,Popover,DropdownMenu,ContextMenu,Selector,ComplexSelector,MultiSelector,Combobox,Toast,Breadcrumbs}: 47 files, 1483 passed.pnpm -F @astryxdesign/core typecheck,pnpm exec eslint --max-warnings=0on the touched files,pnpm exec prettier --check,pnpm check:changesets: clean.main'suseLayer.tsx, "renders the host once on a closed mount" and "renders the host once when the marker sits in an unsafe parent" fail (expected 2 to be 1); the hydration case passes on both.