An open source design system that's fully customizable and agent ready
TypeScript
perf(Layer): an anchored layer's own hide runs only its layout (#10346)
Christopher Chedeau698487f45c87
diff --git a/.changeset/layer-close-one-layout.md b/.changeset/layer-close-one-layout.mdnew file mode 100644index 0000000000..b69ad6b16a--- /dev/null+++ b/.changeset/layer-close-one-layout.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] Closing a Popover or DropdownMenu with Escape, or a DropdownMenu with a pick or a press on its trigger, runs one layout again, not two. A closed trigger stops being a CSS anchor, and these closes took the trigger's anchor name away after the hide's own layout, so the browser laid out once more. Our hide now drops the name before its layout, unless the layer's closed state keeps it shown to fade out. A close the browser runs itself, such as a light dismiss, still drops the name at its toggle event. A layer that fades out keeps the name until its fade ends.++@vjeuxdiff --git a/packages/core/src/Layer/__tests__/LayerCloseLayout.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/LayerCloseLayout.interaction.browser.spec.tsnew file mode 100644index 0000000000..f26205246b--- /dev/null+++ b/packages/core/src/Layer/__tests__/LayerCloseLayout.interaction.browser.spec.ts@@ -0,0 +1,168 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file LayerCloseLayout.interaction.browser.spec.ts+ * @input The Core/Popover and Core/DropdownMenu default stories, the+ * interaction harness's Chromium rendering trace+ * @output Proves the closes that move focus (Escape, a menu pick, a press on+ * the menu's trigger) run the hide's own layout and no other. The element+ * that held the anchor name stops being a CSS anchor inside that layout+ * @position Interaction proofs for the layer runtime's anchor names, run in+ * Chromium, the engine with a rendering trace+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ openStory,+ traceRendering,+ withStorybook,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++// A desktop page, as the overlay-churn perf scene measures: on a phone, a+// Popover plays its own close motion, which lays out on every frame.+test.use({+ viewport: {width: 1280, height: 800},+ isMobile: false,+ hasTouch: false,+});++const CLOSES = 5;+const HOLDER = 'data-test-anchor-holder';++interface Closes {+ readonly layouts: ReadonlyArray<number>;+ readonly anchorNames: ReadonlyArray<string>;+}++interface CloseRoute {+ readonly name: string;+ readonly story: string;+ readonly trigger: (page: Page) => Locator;+ readonly shown: (page: Page) => Locator;+ // What a press closes the layer on. Without one, Escape closes it.+ readonly press?: (page: Page) => Locator;+}++async function frames(page: Page): Promise<void> {+ await page.evaluate(+ async () =>+ new Promise(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(resolve)),+ ),+ );+}++// Opens and closes the layer CLOSES times. Each close, from the Escape press+// or the pointer press until the layer is hidden, runs under the rendering+// trace. Before it, the pointer rests on what it presses, so the trace holds+// no hover change.+async function traceCloses(page: Page, route: CloseRoute): Promise<Closes> {+ const trigger = route.trigger(page);+ const shown = route.shown(page);+ const layouts: number[] = [];+ const anchorNames: string[] = [];+ for (let close = 0; close < CLOSES; close++) {+ await page.mouse.move(5, 5);+ await trigger.click();+ await expect(shown).toBeVisible();+ // The trigger, or the element that wraps it, holds the anchor name while+ // the layer is open.+ const held = await trigger.evaluate((element, attribute) => {+ for (+ let node: Element | null = element;+ node != null;+ node = node.parentElement+ ) {+ if (getComputedStyle(node).getPropertyValue('anchor-name') !== 'none') {+ node.setAttribute(attribute, '');+ return true;+ }+ }+ return false;+ }, HOLDER);+ expect(held, 'an anchor name while the layer is open').toBe(true);+ if (route.press != null) {+ const box = await route.press(page).boundingBox();+ if (box == null) {+ throw new Error(`nothing to press in ${route.name}`);+ }+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);+ }+ // The open's own frames end before the close is traced.+ await frames(page);+ const trace = await traceRendering(page, async () => {+ if (route.press == null) {+ await page.keyboard.press('Escape');+ } else {+ await page.mouse.down();+ await page.mouse.up();+ }+ await expect(shown).toBeHidden();+ });+ layouts.push(trace.layout);+ const holder = page.locator(`[${HOLDER}]`);+ anchorNames.push(+ await holder.evaluate((element, attribute) => {+ element.removeAttribute(attribute);+ return getComputedStyle(element).getPropertyValue('anchor-name');+ }, HOLDER),+ );+ }+ return {layouts, anchorNames};+}++function median(values: ReadonlyArray<number>): number {+ return [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)];+}++const popover = {+ story: 'core-popover--default',+ trigger: (page: Page) => page.getByRole('button', {name: 'Settings'}),+ shown: (page: Page) => page.locator('[popover]:has([role="dialog"])').first(),+};+const menu = {+ story: 'core-dropdownmenu--default',+ trigger: (page: Page) => page.getByRole('button', {name: 'Actions'}),+ shown: (page: Page) => page.getByRole('menuitem', {name: 'Edit'}),+};++const routes: ReadonlyArray<CloseRoute> = [+ {name: 'Escape on a Popover', ...popover},+ {name: 'Escape on a DropdownMenu', ...menu},+ {+ name: 'a pick in a DropdownMenu',+ ...menu,+ press: page => page.getByRole('menuitem', {name: 'Edit'}),+ },+ {+ name: 'a press on a DropdownMenu\u2019s trigger',+ ...menu,+ press: page => page.getByRole('button', {name: 'Actions'}),+ },+];++for (const route of routes) {+ test(`${route.name} closes with one layout and leaves its trigger no anchor`, async ({+ page,+ browserName,+ }) => {+ test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');+ await openStory(page, storybook(), route.story);+ const closes = await traceCloses(page, route);+ const detail = JSON.stringify(closes);+ // The hide's own layout: the trace counts it.+ expect(Math.min(...closes.layouts), detail).toBeGreaterThanOrEqual(1);+ // And no other one for the trigger's anchor name.+ expect(median(closes.layouts), detail).toBe(1);+ expect(closes.anchorNames, detail).toEqual(+ Array.from({length: CLOSES}, () => 'none'),+ );+ });+}diff --git a/packages/core/src/Layer/anchorName.test.ts b/packages/core/src/Layer/anchorName.test.tsindex 8ab9017dd2..df62ea586d 100644--- a/packages/core/src/Layer/anchorName.test.ts+++ b/packages/core/src/Layer/anchorName.test.ts@@ -135,6 +135,25 @@ describe('removeAnchorName', () => {expect(readAnchorNames(el)).toEqual(['--layer-1', '--layer-2']);});+ it('writes the style only when the name is present, since a write invalidates style', () => {+ const el = createMockElement();+ let value = '--layer-1';+ let writes = 0;+ Object.defineProperty(el.style, 'anchorName', {+ configurable: true,+ get: () => value,+ set: (next: string) => {+ writes += 1;+ value = next;+ },+ });+ removeAnchorName(el, '--layer-2');+ expect(writes).toBe(0);+ removeAnchorName(el, '--layer-1');+ expect(writes).toBe(1);+ expect(value).toBe('');+ });+it('handles multiple add/remove cycles correctly', () => {const el = createMockElement();addAnchorName(el, '--menu-a');diff --git a/packages/core/src/Layer/anchorName.ts b/packages/core/src/Layer/anchorName.tsindex f7f8f71a9b..847329a1d7 100644--- a/packages/core/src/Layer/anchorName.ts+++ b/packages/core/src/Layer/anchorName.ts@@ -39,8 +39,12 @@ export function addAnchorName(el: HTMLElement, name: string): void {}export function removeAnchorName(el: HTMLElement, name: string): void {- writeAnchorNames(- el,- readAnchorNames(el).filter(existing => existing !== name),- );+ const names = readAnchorNames(el);+ // A write invalidates the element's style even when the value is the same.+ if (names.includes(name)) {+ writeAnchorNames(+ el,+ names.filter(existing => existing !== name),+ );+ }}diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsxindex f6c2805164..2f6611bff6 100644--- a/packages/core/src/Layer/useLayer.test.tsx+++ b/packages/core/src/Layer/useLayer.test.tsx@@ -1910,6 +1910,236 @@ describe('useLayer', () => {expect(anchorNames(trigger)).toEqual([]);});+ const closing = () =>+ Object.assign(new Event('beforetoggle'), {+ oldState: 'open',+ newState: 'closed',+ });++ // The layer's own transition, set on its style while it is closed.+ function declareTransition(+ layer: HTMLElement,+ transition: {+ property: string;+ behavior: string;+ duration: string;+ delay: string;+ },+ ) {+ layer.style.setProperty('transition-property', transition.property);+ layer.style.setProperty('transition-behavior', transition.behavior);+ layer.style.setProperty('transition-duration', transition.duration);+ layer.style.setProperty('transition-delay', transition.delay);+ }++ // A running exit animation that ends when `end` is called.+ function exitAnimation() {+ let end = () => {};+ const finished = new Promise<void>(resolve => {+ end = resolve;+ });+ const animation = {+ finished,+ playState: 'running',+ effect: {getComputedTiming: () => ({endTime: 200})},+ } as unknown as Animation;+ return {animation, finished, end: () => end()};+ }++ it('drops the name inside our hide, in the layer\u2019s beforetoggle, and reads no animations after the hide', () => {+ 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;+ const getAnimations = vi.fn(() => [] as Animation[]);+ layer.getAnimations = getAnimations;+ // A browser fires `beforetoggle` inside the hide, before the hide's own+ // layout.+ let namesInHide: string[] = [];+ const hidePopover = vi+ .spyOn(layer, 'hidePopover')+ .mockImplementation(() => {+ layer.dispatchEvent(closing());+ namesInHide = anchorNames(trigger);+ });+ try {+ act(() => api.show());+ act(() => api.hide());+ expect(namesInHide).toEqual([]);+ expect(anchorNames(trigger)).toEqual([]);+ // Nothing keeps the hidden layer shown, so the release reads nothing.+ expect(getAnimations).not.toHaveBeenCalled();+ } finally {+ hidePopover.mockRestore();+ }+ });++ it('keeps the name through the beforetoggle of a close the browser runs itself, and releases it from the toggle event', 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;+ const toggle = () =>+ act(() => {+ layer.dispatchEvent(+ Object.assign(new Event('toggle'), {+ oldState: 'open',+ newState: 'closed',+ }),+ );+ });+ const exit = exitAnimation();+ layer.getAnimations = () => [exit.animation];++ // No exit: the toggle releases the name.+ act(() => api.show());+ act(() => {+ layer.dispatchEvent(closing());+ });+ expect(anchorNames(trigger)).toHaveLength(1);+ toggle();+ expect(anchorNames(trigger)).toEqual([]);++ // A close fade: the name stays until the fade ends.+ declareCloseFade(layer);+ act(() => api.show());+ act(() => {+ layer.dispatchEvent(closing());+ });+ toggle();+ expect(anchorNames(trigger)).toHaveLength(1);+ await act(async () => {+ exit.end();+ await exit.finished;+ });+ expect(anchorNames(trigger)).toEqual([]);+ });++ it('keeps the name through our hide for a layer whose closed state alone declares the fade, until the fade ends', 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');+ });+ const exit = exitAnimation();+ layer.getAnimations = () => [exit.animation];+ let namesInHide: string[] = [];+ const hidePopover = vi+ .spyOn(layer, 'hidePopover')+ .mockImplementation(() => {+ layer.dispatchEvent(closing());+ namesInHide = anchorNames(trigger);+ });+ try {+ act(() => api.show());+ act(() => api.hide());+ expect(namesInHide).toHaveLength(1);+ // Still painting, so still placed against its trigger.+ expect(anchorNames(trigger)).toHaveLength(1);+ await act(async () => {+ exit.end();+ await exit.finished;+ });+ expect(anchorNames(trigger)).toEqual([]);+ } finally {+ hidePopover.mockRestore();+ }+ });++ it.each([+ {+ transition: {+ property: 'opacity, display, overlay',+ behavior: 'normal, allow-discrete, allow-discrete',+ duration: '0.2s',+ delay: '0s',+ },+ keepsShown: true,+ },+ {+ transition: {+ property: 'all',+ behavior: 'allow-discrete',+ duration: '150ms',+ delay: '0s',+ },+ keepsShown: true,+ },+ {+ transition: {+ property: 'display',+ behavior: 'normal',+ duration: '0.2s',+ delay: '0s',+ },+ keepsShown: false,+ },+ {+ transition: {+ property: 'display',+ behavior: 'allow-discrete',+ duration: '0s',+ delay: '0s',+ },+ keepsShown: false,+ },+ {+ transition: {+ property: 'opacity',+ behavior: 'allow-discrete',+ duration: '0.2s',+ delay: '0s',+ },+ keepsShown: false,+ },+ {+ transition: {+ property: 'overlay',+ behavior: 'allow-discrete',+ duration: '0.2s',+ delay: '0s',+ },+ keepsShown: false,+ },+ ])(+ 'in our hide\u2019s beforetoggle, keeps the name only for a layer its closed state keeps shown: $transition.property $transition.duration $transition.behavior',+ ({transition, keepsShown}) => {+ 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;+ declareTransition(layer, transition);+ layer.getAnimations = () => [];+ let namesInHide: string[] = [];+ const hidePopover = vi+ .spyOn(layer, 'hidePopover')+ .mockImplementation(() => {+ layer.dispatchEvent(closing());+ namesInHide = anchorNames(trigger);+ });+ try {+ act(() => api.show());+ act(() => api.hide());+ expect(namesInHide).toHaveLength(keepsShown ? 1 : 0);+ } finally {+ hidePopover.mockRestore();+ }+ },+ );+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(diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex 75b8e877b7..52d207f73c 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -30,7 +30,7 @@ import type {StyleXStyles} from '@stylexjs/stylex';import {createPortal} from 'react-dom';import {LayerContentBoundary} from './layerScopedContext';import {layerClickBoundary} from './layerClickBoundary';-import {addAnchorName, removeAnchorName} from './anchorName';+import {addAnchorName, readAnchorNames, removeAnchorName} from './anchorName';import {currentGesture, currentGestureHasClicked} from './gestureCounter';import {resolveLayerPortalTarget} from './layerHost';import {layerTextReset} from './layerTextReset.stylex';@@ -1673,14 +1673,35 @@ function useLayerImplementation(// hide starts; the ledger counts the hide from there until the element's// own `toggle`, independent of this hook's bindings, which a render inside// the hide can replace.- const handleBeforeToggle = useCallback((e: Event) => {- const toggleEvent = e as ToggleEvent;- const el = e.currentTarget as HTMLElement | null;- if (toggleEvent.newState === 'closed' && isOpenRef.current && el != null) {- observeBrowserHide(el);- onCloseStartRef.current?.();- }- }, []);+ const handleBeforeToggle = useCallback(+ (e: Event) => {+ const toggleEvent = e as ToggleEvent;+ const el = e.currentTarget as HTMLElement | null;+ if (toggleEvent.newState !== 'closed' || el == null) {+ return;+ }+ if (isOpenRef.current) {+ observeBrowserHide(el);+ onCloseStartRef.current?.();+ // The browser's own close releases the name from its toggle event.+ return;+ }+ // Our hide drops its trigger's anchor name here, inside the hide, so the+ // hide's own layout covers the change. A name dropped after that layout+ // costs one more. A layer that the closed state keeps shown keeps the+ // name until its exit ends.+ const trigger = triggerRef.current;+ if (+ trigger != null &&+ readAnchorNames(trigger).includes(anchorId) &&+ !closeKeepsShownRef.current+ ) {+ exitRef.current = null;+ removeAnchorName(trigger, anchorId);+ }+ },+ [anchorId],+ );const handleToggle = useCallback((e: Event) => {