Skip to content

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

TypeScript

perf(Layer): a closed layer reads its writing context when it first opens, not on mount (#9012)

Cindy Zhange9ac835eb318
diff --git a/.changeset/layer-closed-mount-no-style-read.md b/.changeset/layer-closed-mount-no-style-read.md
new file mode 100644
index 0000000000..56091064a7
--- /dev/null
+++ b/.changeset/layer-closed-mount-no-style-read.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[perf] Pages with many closed popovers, tooltips and menus mount faster. A layer that renders closed outside an inline or interactive parent no longer reads computed style when it mounts; it reads its writing direction when it first opens, before its first frame. On a page with hundreds of closed layers, each of those mount-time reads forced its own style recalculation. Open layers look and behave as before, in right-to-left and vertical text too.
+
+@cixzhang
diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsx
index 87bdc3a693..54738b9c73 100644
--- a/packages/core/src/Layer/useLayer.test.tsx
+++ b/packages/core/src/Layer/useLayer.test.tsx
@@ -116,6 +116,24 @@ function ContextHostingHarness({
);
}
+function EagerContextHostingHarness({
+ layerStyle,
+}: {
+ layerStyle?: React.CSSProperties;
+}) {
+ const layer = useLayer({mode: 'context'});
+ return (
+ <div data-testid="host">
+ <p>
+ <button type="button" ref={layer.ref} onClick={layer.show}>
+ Trigger
+ </button>
+ {layer.render(<span>Layer content</span>, {style: layerStyle})}
+ </p>
+ </div>
+ );
+}
+
function RelocatingContextHostingHarness({unsafe}: {unsafe: boolean}) {
const layer = useLayer({mode: 'context'});
const renderedLayer = layer.render(<span>Layer content</span>);
@@ -665,6 +683,95 @@ describe('useLayer', () => {
}
});
+ it('reads no computed style for a closed layer mounted ahead of its first show', () => {
+ const getComputedStyleSpy = vi.spyOn(window, 'getComputedStyle');
+ try {
+ const {container} = render(<EagerContextHostingHarness />);
+ const layer = container.querySelector('[popover]') as HTMLElement;
+ // Mounted closed, outside the unsafe paragraph, with no style read.
+ expect(layer.parentElement).toBe(
+ container.querySelector('[data-testid="host"]'),
+ );
+ expect(getComputedStyleSpy).not.toHaveBeenCalled();
+ expect(layer.style.direction).toBe('');
+ } finally {
+ getComputedStyleSpy.mockRestore();
+ }
+ });
+
+ it("applies a closed layer's deferred writing context before it opens", async () => {
+ const getComputedStyleSpy = vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation(element =>
+ mockCSSStyleDeclaration({
+ getPropertyValue: () => '',
+ // The marker sits in a right-to-left, vertical paragraph; the
+ // corrective host does not.
+ direction:
+ element.tagName.toLowerCase() === 'template' ? 'rtl' : 'ltr',
+ writingMode:
+ element.tagName.toLowerCase() === 'template'
+ ? 'vertical-rl'
+ : 'horizontal-tb',
+ }),
+ );
+ const atShow: {direction: string; writingMode: string}[] = [];
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ atShow.push({
+ direction: this.style.direction,
+ writingMode: this.style.writingMode,
+ });
+ });
+ const user = userEvent.setup();
+ try {
+ const {container, getByRole} = render(<EagerContextHostingHarness />);
+ expect(getComputedStyleSpy).not.toHaveBeenCalled();
+
+ await user.click(getByRole('button', {name: 'Trigger'}));
+
+ // Present when the popover opened, and kept by the render after it.
+ expect(atShow).toEqual([
+ {direction: 'rtl', writingMode: 'vertical-rl'},
+ ]);
+ const layer = container.querySelector('[popover]') as HTMLElement;
+ expect(layer.style.direction).toBe('rtl');
+ expect(layer.style.writingMode).toBe('vertical-rl');
+ } finally {
+ getComputedStyleSpy.mockRestore();
+ }
+ });
+
+ it("keeps the caller's own direction over a deferred writing context", async () => {
+ const getComputedStyleSpy = vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation(element =>
+ mockCSSStyleDeclaration({
+ getPropertyValue: () => '',
+ direction:
+ element.tagName.toLowerCase() === 'template' ? 'rtl' : 'ltr',
+ writingMode: 'horizontal-tb',
+ }),
+ );
+ const atShow: string[] = [];
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ atShow.push(this.style.direction);
+ });
+ const user = userEvent.setup();
+ try {
+ const {container, getByRole} = render(
+ <EagerContextHostingHarness layerStyle={{direction: 'ltr'}} />,
+ );
+
+ await user.click(getByRole('button', {name: 'Trigger'}));
+
+ expect(atShow).toEqual(['ltr']);
+ const layer = container.querySelector('[popover]') as HTMLElement;
+ expect(layer.style.direction).toBe('ltr');
+ } 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
diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx
index 1d0fdc37e7..3c0a6fe442 100644
--- a/packages/core/src/Layer/useLayer.tsx
+++ b/packages/core/src/Layer/useLayer.tsx
@@ -848,8 +848,13 @@ function isPopoverOperationInFlight(doc: Document): boolean {
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;
+ /**
+ * Logical writing context lost when moving outside an unsafe ancestor, or
+ * null until it is read. A closed layer mounted ahead of its first show
+ * reads it in `show()`, before the layer opens: reading computed style for
+ * every closed layer on mount forces a style recalculation per layer.
+ */
+ portalStyle: React.CSSProperties | null;
}
/**
@@ -1285,11 +1290,17 @@ function useLayerImplementation(
ensureSlideRules(sentinel.ownerDocument);
const portalTarget = resolveLayerPortalTarget(inlineParent);
+ // A mount for a layer that is opening or open reads its writing context
+ // now; a closed layer's waits for its first show.
+ const opening = pendingShowRef.current || isOpenRef.current;
const mount: ContextLayerMount = {
portalTarget,
- portalStyle: portalTarget
- ? readPortalWritingContext(sentinel, portalTarget)
- : {},
+ portalStyle:
+ portalTarget == null
+ ? {}
+ : opening
+ ? readPortalWritingContext(sentinel, portalTarget)
+ : null,
};
const replaced = contextMountRef.current !== null;
contextMountRef.current = mount;
@@ -1299,6 +1310,40 @@ function useLayerImplementation(
}
}, [mode, mountStore]);
+ // Reads the writing context a closed layer's mount deferred, before the
+ // layer opens. It is written on the popover at once, so the first open frame
+ // already has it (layer-runtime INV12), and published to the slot, whose
+ // render writes the same values. A value the caller's own `style` sets is
+ // already inline and wins, as it does in render.
+ const applyDeferredWritingContext = useCallback(
+ (popover: HTMLElement) => {
+ const mount = contextMountRef.current;
+ const sentinel = sentinelRef.current;
+ if (
+ mount === null ||
+ mount.portalTarget === null ||
+ mount.portalStyle !== null ||
+ sentinel === null
+ ) {
+ return;
+ }
+ const portalStyle = readPortalWritingContext(
+ sentinel,
+ mount.portalTarget,
+ );
+ if (portalStyle.direction != null && popover.style.direction === '') {
+ popover.style.direction = portalStyle.direction;
+ }
+ if (portalStyle.writingMode != null && popover.style.writingMode === '') {
+ popover.style.writingMode = portalStyle.writingMode;
+ }
+ const next: ContextLayerMount = {...mount, portalStyle};
+ contextMountRef.current = next;
+ mountStore.set(next);
+ },
+ [mountStore],
+ );
+
const clearContextMount = useCallback(() => {
if (mode !== 'context' || !lazyMount) {
return;
@@ -1339,6 +1384,7 @@ function useLayerImplementation(
}
popover.removeAttribute(LAYER_CLEARS_ANCHOR_ATTRIBUTE);
popover.removeAttribute(LAYER_SCROLLS_ATTRIBUTE);
+ applyDeferredWritingContext(popover);
showPopoverElement(popover);
if (keepsAnchorClear) {
keepAnchorClear(popover, triggerRef.current);
@@ -1351,6 +1397,7 @@ function useLayerImplementation(
onShow,
keepsAnchorClear,
requestContextMount,
+ applyDeferredWritingContext,
showPopoverElement,
isCurrentContextPopover,
wasJustDismissed,