An open source design system that's fully customizable and agent ready
TypeScript
perf(Layer): a closing layer reads its animations only when its closed state declares an exit (#10368)
Cindy Zhang2816569ac57c
diff --git a/.changeset/layer-close-no-extra-layout.md b/.changeset/layer-close-no-extra-layout.mdnew file mode 100644index 0000000000..47e3edf613--- /dev/null+++ b/.changeset/layer-close-no-extra-layout.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] Closing a Popover, menu or other anchored layer no longer lays out the page an extra time. The layer runtime reads a closing layer's animations only when the layer's closed state declares a discrete `display` transition or a keyframe animation. It reads that style while the layer is still closed. Such a layer, as TopNavMegaMenu's panel is, still keeps its trigger's anchor name until its fade ends. An animation a script starts is not tracked.++@cixzhangdiff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.mdindex 6213da25df..96f3d3cf0d 100644--- a/docs/architecture/layer-runtime.md+++ b/docs/architecture/layer-runtime.md@@ -614,7 +614,7 @@ layers use Layer rendering without joining Escape/platform dismissal.input, wheel, and drag events are out of scope.- **INV18 — Only a shown layer's trigger is an anchor.**A trigger carries its CSS anchor name only while its layer is shown; a closed trigger is not an anchor, so a surface that moves around it keeps its transform animation off the main thread.- A layer that animates out counts as shown until its animations end.+ A layer that animates out through a CSS transition or keyframe animation it declares for its closed state counts as shown until those animations end; an animation a script starts is not tracked.This record does not make future eligible-owner, branch-association, global-host,or browser-support requirements current. It does not own component focus entry or@@ -801,21 +801,22 @@ this current architecture record.## Verification-| Invariant | Evidence | Failure signal |-| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| INV1, INV2 | `useLayer.test.tsx` and `layerHost.test.ts` | Invalid DOM, stale host, lost theme/writing context, or portal mistaken for top-layer promotion |-| INV3–INV5 | `useLayer.test.tsx` and `anchorName.test.ts` | A mode leaks geometry, RTL resolves from the wrong context, fallback clips, or a sibling anchor is lost |-| INV11 | `layerViewportInset.test.ts`, `useLayer.test.tsx`, and the `Core/Layer` viewport-inset stories under the story play guard at a desktop and a phone viewport; `BaseTypeahead.incremental.test.tsx` and the Typeahead incremental-results stories for the `spec:AST-092` FR6 exception | A second gutter definition, a `100%`-of-span cap, a layer narrower than its explicit size, a layer box wider than the viewport, a layer inside the gutter, or a layer that slides toward an off-screen anchor; for an open Typeahead popup, a later list for the same query that flips it to the other side or grows it past the room on its side, or a first list for a query that is capped to the span beside the trigger |-| INV12 | The `Core/Layer` viewport-inset stories' first-frame comparison, and `useLayer.test.tsx`'s synchronous anchor read | A layer whose first painted rectangle differs from its settled one |-| INV11, INV12 | The software keyboard's cap: `useLayerKeyboardClearance.test.tsx` for its rule, its timing, its read before first paint, and the inset's hold; the `PopoverKeyboard`, `keyboardCappedLists` and `SelectorKeyboardInset` browser specs for its rendered geometry | A layer that runs under the keyboard, or is capped though the keyboard does not reach it; a cap that changes more than once per keyboard movement or under a press; a layer opened with the keyboard up whose first frame is uncapped or paints its content past its box; a layer that reads the inset and moves down when the keyboard report ends |-| INV13 | `layerExitCopy.test.ts` and `layerExitCopy.interaction.browser.spec.ts` | A copy with an id, a form name, a form owner, or pointer reach; a copy off the layer's drawn box; a copy outside the top layer; a second copy for one layer |-| INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface |-| INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through |-| INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests; `useBackdropPress.test.tsx`; `outsidePress.test.ts` | A current local channel silently changes ownership or policy |-| INV10 | `LayerProvider.tsx`, `toastHost.tsx`, `LayerProvider.test.tsx`, `toastHost.test.tsx`, `toastHost.lateRegistration.test.tsx`, `useToast.tsx`, `ToastViewport.test.tsx`, `ToastViewport.modalHost.test.tsx`, and `scripts/layer-toast-bundle.test.mjs` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, a default provider renders differently from no provider, a Layer import loads a Toast module, or a toast added before Toast loads is lost |-| INV14, INV15 | Source boundary check over Core for top-layer hosts, exit copies, backdrop elements, lift, and rectangle-morph code outside the runtime and the lift module | A component building its own copy of a mechanism INV14 lists (top-layer mounting, close-request delivery, hold, exit copy, or backdrop element), or re-implementing the lift or the grow |-| INV17 | One runtime suite over every kind of layer root: a `useLayer` layer, inline and portaled, and the Dialog, Drawer, Lightbox, MobileNav, BottomSheetPanel, and ToastViewport content roots, each inside a plain `onClick` wrapper and a Core clickable container; nested layers | A click inside a layer root that reaches an ancestor bubble-phase handler, a caller's wrapper included; an outer layer's handler that receives an inner layer's press; or a document listener or light dismiss that no longer receives it |-| INV18 | `useLayer.test.tsx` (a closed trigger has no anchor-name, and the trigger of a shown or fading layer does) and `TooltipClosedTriggerAnchor.interaction.browser.spec.ts` in Chromium and WebKit | A closed trigger with an anchor-name, a shown or fading layer placed away from its anchor, or a surface around a closed trigger that stops while the main thread is busy |+| Invariant | Evidence | Failure signal |+| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| INV1, INV2 | `useLayer.test.tsx` and `layerHost.test.ts` | Invalid DOM, stale host, lost theme/writing context, or portal mistaken for top-layer promotion |+| INV3–INV5 | `useLayer.test.tsx` and `anchorName.test.ts` | A mode leaks geometry, RTL resolves from the wrong context, fallback clips, or a sibling anchor is lost |+| INV11 | `layerViewportInset.test.ts`, `useLayer.test.tsx`, and the `Core/Layer` viewport-inset stories under the story play guard at a desktop and a phone viewport; `BaseTypeahead.incremental.test.tsx` and the Typeahead incremental-results stories for the `spec:AST-092` FR6 exception | A second gutter definition, a `100%`-of-span cap, a layer narrower than its explicit size, a layer box wider than the viewport, a layer inside the gutter, or a layer that slides toward an off-screen anchor; for an open Typeahead popup, a later list for the same query that flips it to the other side or grows it past the room on its side, or a first list for a query that is capped to the span beside the trigger |+| INV12 | The `Core/Layer` viewport-inset stories' first-frame comparison, and `useLayer.test.tsx`'s synchronous anchor read | A layer whose first painted rectangle differs from its settled one |+| INV11, INV12 | The software keyboard's cap: `useLayerKeyboardClearance.test.tsx` for its rule, its timing, its read before first paint, and the inset's hold; the `PopoverKeyboard`, `keyboardCappedLists` and `SelectorKeyboardInset` browser specs for its rendered geometry | A layer that runs under the keyboard, or is capped though the keyboard does not reach it; a cap that changes more than once per keyboard movement or under a press; a layer opened with the keyboard up whose first frame is uncapped or paints its content past its box; a layer that reads the inset and moves down when the keyboard report ends |+| INV13 | `layerExitCopy.test.ts` and `layerExitCopy.interaction.browser.spec.ts` | A copy with an id, a form name, a form owner, or pointer reach; a copy off the layer's drawn box; a copy outside the top layer; a second copy for one layer |+| INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface |+| INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through |+| INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests; `useBackdropPress.test.tsx`; `outsidePress.test.ts` | A current local channel silently changes ownership or policy |+| INV10 | `LayerProvider.tsx`, `toastHost.tsx`, `LayerProvider.test.tsx`, `toastHost.test.tsx`, `toastHost.lateRegistration.test.tsx`, `useToast.tsx`, `ToastViewport.test.tsx`, `ToastViewport.modalHost.test.tsx`, and `scripts/layer-toast-bundle.test.mjs` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, a default provider renders differently from no provider, a Layer import loads a Toast module, or a toast added before Toast loads is lost |+| INV14, INV15 | Source boundary check over Core for top-layer hosts, exit copies, backdrop elements, lift, and rectangle-morph code outside the runtime and the lift module | A component building its own copy of a mechanism INV14 lists (top-layer mounting, close-request delivery, hold, exit copy, or backdrop element), or re-implementing the lift or the grow |+| INV17 | One runtime suite over every kind of layer root: a `useLayer` layer, inline and portaled, and the Dialog, Drawer, Lightbox, MobileNav, BottomSheetPanel, and ToastViewport content roots, each inside a plain `onClick` wrapper and a Core clickable container; nested layers | A click inside a layer root that reaches an ancestor bubble-phase handler, a caller's wrapper included; an outer layer's handler that receives an inner layer's press; or a document listener or light dismiss that no longer receives it |+| INV18 | `useLayer.test.tsx` (a closed trigger has no anchor-name, and the trigger of a shown or fading layer does) and `TooltipClosedTriggerAnchor.interaction.browser.spec.ts` in Chromium and WebKit | A closed trigger with an anchor-name, a shown or fading layer placed away from its anchor, or a surface around a closed trigger that stops while the main thread is busy |+| INV18 | `useLayer.test.tsx`: a closed state that declares a discrete `display` transition or a keyframe animation keeps the trigger's anchor name until those animations end, read from the closed state's style; a layer whose closed state declares neither is not read for animations at the close | A layer with such a closed-state exit placed away from its anchor while it fades, or an animation read on the close of a layer whose closed state declares no exit |Current unit coverage proves emitted styles, reducers, state transitions, and DOMplacement. Native Popover, `<dialog>`, focus, top-layer ordering, and rendereddiff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsxindex 0c61d45358..f6c2805164 100644--- a/packages/core/src/Layer/useLayer.test.tsx+++ b/packages/core/src/Layer/useLayer.test.tsx@@ -1720,6 +1720,13 @@ describe('useLayer', () => {.map(name => name.trim()).filter(Boolean);+ /** The close fade TopNavMegaMenu declares: the hidden layer stays shown. */+ const declareCloseFade = (layer: HTMLElement) => {+ layer.style.setProperty('transition-property', 'opacity, display');+ layer.style.setProperty('transition-behavior', 'allow-discrete');+ layer.style.setProperty('transition-duration', '0.2s');+ };+function SharedTriggerHarness({onReady,}: {@@ -1810,6 +1817,99 @@ describe('useLayer', () => {expect(anchorNames(trigger)).toEqual([]);});+ it('reads no animations when nothing keeps the hidden layer shown', () => {+ let api = {show: () => {}, hide: () => {}};+ const {getByRole, container} = render(+ <SwappedTriggerHarness second={false} onReady={a => (api = a)} />,+ );+ const trigger = getByRole('button', {name: 'First'});+ const layer = container.querySelector('[popover]') as HTMLElement;+ // Without a discrete `display` transition the layer stops painting as+ // it hides. Reading the animations would lay the page out once more.+ layer.style.setProperty('transition-property', 'opacity, overlay');+ layer.style.setProperty('transition-behavior', 'allow-discrete');+ layer.style.setProperty('transition-duration', '0.2s');+ const read = vi.fn((): Animation[] => []);+ layer.getAnimations = read;+ act(() => api.show());+ act(() => api.hide());+ expect(read).not.toHaveBeenCalled();+ expect(anchorNames(trigger)).toEqual([]);++ act(() => api.show());+ act(() => {+ layer.dispatchEvent(+ Object.assign(new Event('toggle'), {+ oldState: 'open',+ newState: 'closed',+ }),+ );+ });+ expect(read).not.toHaveBeenCalled();+ expect(anchorNames(trigger)).toEqual([]);+ });++ it('reads the animations of a layer whose closed state alone declares a keyframe animation', () => {+ let api = {show: () => {}, hide: () => {}};+ const {container} = render(+ <SwappedTriggerHarness second={false} onReady={a => (api = a)} />,+ );+ const layer = container.querySelector('[popover]') as HTMLElement;+ const read = vi.fn((): Animation[] => []);+ layer.getAnimations = read;+ // An entrance that both states declare: the hide stops it.+ layer.style.setProperty('animation-name', 'layer-enter');+ act(() => api.show());+ act(() => api.hide());+ expect(read).not.toHaveBeenCalled();++ // An exit that only the closed state declares starts at the close, and+ // it can animate `display`.+ layer.style.setProperty('animation-name', 'layer-exit');+ const show = vi.spyOn(layer, 'showPopover').mockImplementation(() => {+ layer.style.setProperty('animation-name', 'layer-enter');+ });+ act(() => api.show());+ act(() => api.hide());+ expect(read).toHaveBeenCalledTimes(1);+ show.mockRestore();+ });++ it('reads the close transition from the closed state\u2019s style', async () => {+ let api = {show: () => {}, hide: () => {}};+ const {getByRole, container} = render(+ <SwappedTriggerHarness second={false} onReady={a => (api = a)} />,+ );+ const trigger = getByRole('button', {name: 'First'});+ const layer = container.querySelector('[popover]') as HTMLElement;+ // An instant open and a fading close: only the closed state declares+ // the transition.+ declareCloseFade(layer);+ vi.spyOn(layer, 'showPopover').mockImplementation(() => {+ layer.style.setProperty('transition-duration', '0s');+ });+ let end = () => {};+ const finished = new Promise<void>(resolve => {+ end = resolve;+ });+ layer.getAnimations = () =>+ [+ {+ finished,+ playState: 'running',+ effect: {getComputedTiming: () => ({endTime: 200})},+ },+ ] as unknown as Animation[];+ act(() => api.show());+ act(() => api.hide());+ expect(anchorNames(trigger)).toHaveLength(1);+ await act(async () => {+ end();+ await finished;+ });+ expect(anchorNames(trigger)).toEqual([]);+ });+it('keeps the name while the layer fades out, and for a show during the fade', async () => {let api = {show: () => {}, hide: () => {}};const {getByRole, container} = render(@@ -1818,6 +1918,7 @@ describe('useLayer', () => {const trigger = getByRole('button', {name: 'First'});const layer = container.querySelector('[popover]') as HTMLElement;// A close fade the browser runs after the hide, as TopNavMegaMenu's.+ declareCloseFade(layer);const fade = () => {let end = () => {};const finished = new Promise<void>(resolve => {@@ -1862,6 +1963,7 @@ describe('useLayer', () => {<SwappedTriggerHarness second={false} onReady={a => (api = a)} />,);const layer = container.querySelector('[popover]') as HTMLElement;+ declareCloseFade(layer);let end = () => {};const finished = new Promise<void>(resolve => {end = resolve;@@ -1894,6 +1996,7 @@ describe('useLayer', () => {);const trigger = getByRole('button', {name: 'First'});const layer = container.querySelector('[popover]') as HTMLElement;+ declareCloseFade(layer);let end = () => {};const finished = new Promise<void>(resolve => {end = resolve;@@ -1942,6 +2045,7 @@ describe('useLayer', () => {const trigger = getByRole('button', {name: 'First'});const layer = container.querySelector('[popover]') as HTMLElement;// A paused animation never finishes, so it must not hold the name.+ declareCloseFade(layer);layer.getAnimations = () =>[{@@ -1962,6 +2066,7 @@ describe('useLayer', () => {);const trigger = getByRole('button', {name: 'First'});const layer = container.querySelector('[popover]') as HTMLElement;+ declareCloseFade(layer);layer.getAnimations = () =>[{diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex 9ef4938b6e..75b8e877b7 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -528,6 +528,43 @@ function exitAnimations(layer: HTMLElement | null): Animation[] {);}+/**+ * Whether the closed state's transition keeps `layer` shown after it hides.+ * Only a discrete `display` transition holds a hidden layer shown, until it+ * ends. Read it while the layer is closed: the close takes its values from+ * the closed state's style.+ */+function closeTransitionKeepsShown(layer: HTMLElement): boolean {+ const style = layer.ownerDocument.defaultView?.getComputedStyle(layer);+ if (style == null) {+ return false;+ }+ const list = (name: string) =>+ style+ .getPropertyValue(name)+ .split(',')+ .map(value => value.trim());+ const behaviors = list('transition-behavior');+ const durations = list('transition-duration').map(parseFloat);+ const delays = list('transition-delay').map(parseFloat);+ return list('transition-property').some((name, index) => {+ const behavior = behaviors[index % behaviors.length];+ const duration = durations[index % durations.length] || 0;+ const delay = delays[index % delays.length] || 0;+ return (+ (name === 'all' || name === 'display') &&+ behavior === 'allow-discrete' &&+ duration + Math.max(0, delay) > 0+ );+ });+}++/** The keyframe animations that `layer`'s style declares, or `none`. */+function animationNames(layer: HTMLElement): string {+ const style = layer.ownerDocument.defaultView?.getComputedStyle(layer);+ return style?.getPropertyValue('animation-name').trim() || 'none';+}+/*** Whether the standard list has failed a layer that must keep its anchor* clear: its box covers the anchor or, while the anchor is in view, leaves the@@ -1199,6 +1236,9 @@ function useLayerImplementation(// again during it. Null once it has ended.const exitRef = useRef<object | null>(null);+ // Read at the last show, from the closed state's style.+ const closeKeepsShownRef = useRef(false);+// A closed trigger is no anchor, once the layer stops painting. A show// during the exit keeps the name, and so does a later exit.const releaseAnchor = useCallback(@@ -1215,7 +1255,9 @@ function useLayerImplementation(removeAnchorName(trigger, anchorId);}};- const running = exitAnimations(layer);+ // The animation read lays out the page between the writes of the close.+ // Skip it when the layer stops painting as it hides.+ const running = closeKeepsShownRef.current ? exitAnimations(layer) : [];if (running.length === 0) {release();return;@@ -1426,6 +1468,10 @@ function useLayerImplementation(replayWhenSettled();return;}+ // The close takes its values from the closed state's style. Read it+ // before the writes of the show, so the read lays nothing out.+ const closeTransitionHolds = closeTransitionKeepsShown(popover);+ const closedAnimations = animationNames(popover);popover.removeAttribute(LAYER_CLEARS_ANCHOR_ATTRIBUTE);popover.removeAttribute(LAYER_SCROLLS_ATTRIBUTE);applyDeferredWritingContext(popover);@@ -1450,6 +1496,13 @@ function useLayerImplementation(replayWhenSettled();return;}+ // A keyframe animation that only the closed state declares starts at+ // the close, and it can animate `display`. One that both states declare+ // is the entrance, and the hide stops it.+ const closeStartsAnimation =+ closedAnimations !== 'none' &&+ closedAnimations !== animationNames(popover);+ closeKeepsShownRef.current = closeTransitionHolds || closeStartsAnimation;if (keepsAnchorClear) {keepAnchorClear(popover, triggerRef.current);}