An open source design system that's fully customizable and agent ready
TypeScript
perf(Layer): anchored entrances play on the surface (#10561)
Christopher Chedeau9dca386298bc
diff --git a/.changeset/layer-entrance-on-surface.md b/.changeset/layer-entrance-on-surface.mdnew file mode 100644index 0000000000..955dca965b--- /dev/null+++ b/.changeset/layer-entrance-on-surface.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] Popover, DropdownMenu and its submenus, Selector, ComplexSelector, PowerSearch and Breadcrumbs' menu play their entrance on the surface inside the layer, not on the anchored layer. Chromium laid the anchored layer out again on every frame of its 150 ms entrance, two to four times per frame, whenever the page had other frame work. The entrance looks the same. `layerAnimations` is unchanged; its docs now say to apply it to the surface. Applied to the layer, it still plays as before.++@vjeuxdiff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.mdindex 44394852c9..a61af7c5a2 100644--- a/docs/architecture/layer-runtime.md+++ b/docs/architecture/layer-runtime.md@@ -679,6 +679,15 @@ inside a layer within the card, so before the layer's own handlers; the changeis staged as `[breaking]` (`spec:AST-017` FR32) and `component:SelectableCard``CLN-0026` removes that handler.+Tooltip, HoverCard and ContextMenu's entrance layout is a performance gap. They+play their entrance on the anchored layer itself. Tooltip and HoverCard's layer+is their themed surface: it carries the theme class and the caller's `xstyle`,+`className` and `style`. Chromium lays an anchored element out again each time+its own style changes. On a page with work on every frame, each frame of their+150 ms entrance therefore runs two to four layouts. A Tooltip entrance runs+about 14 to 18 layouts. The other components that play `layerAnimations` play+it on the surface inside the layer and run no layout while it plays.+## Change coupling- A change to `useLayer` hosting or lifecycle verifies safe inline placement,diff --git a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsxindex 098835876f..a2d1f85b7f 100644--- a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx+++ b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx@@ -559,6 +559,9 @@ function BreadcrumbMenuTrigger({// The popup's own role="menu" is the exposed semantics; a modal dialog// wrapper would announce an unnamed dialog around the menu.role: 'none',+ // The entrance runs on the surface: an anchored layer lays out again on+ // each frame its own style animates.+ xstyle: layerAnimations.below,});const closeMenu = useCallback(() => {@@ -740,7 +743,7 @@ function BreadcrumbMenuTrigger({{placement: 'below',alignment: 'start',- xstyle: [menuStyles.popover, layerAnimations.below],+ xstyle: menuStyles.popover,},)}</>diff --git a/packages/core/src/ComplexSelector/ComplexSelector.tsx b/packages/core/src/ComplexSelector/ComplexSelector.tsxindex e6a3add8b6..14e46ef4c4 100644--- a/packages/core/src/ComplexSelector/ComplexSelector.tsx+++ b/packages/core/src/ComplexSelector/ComplexSelector.tsx@@ -656,6 +656,9 @@ export function ComplexSelector<Value>({surfaceTarget: 'complex-selector-popup',onShow: handlePopoverShow,onHide: handlePopoverHide,+ // The entrance runs on the surface: an anchored layer lays out again on+ // each frame its own style animates.+ xstyle: layerAnimations[placement],});popupContentRef.current = popover.contentRef.current;@@ -803,7 +806,7 @@ export function ComplexSelector<Value>({placement,alignment,offset: spacingVars['--spacing-1'],- xstyle: [styles.popover, layerAnimations[placement]],+ xstyle: styles.popover,});if (renderTrigger != null) {diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsxindex f0c2a4140d..f6143dedef 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx@@ -2969,8 +2969,9 @@ describe('DropdownMenu entrance under a finger', () => {}/**- * Gives each popover a running entrance (Web Animations' `getAnimations()`,- * which jsdom lacks) whose end the test decides.+ * Gives each popover's surface, the layer's first child where the entrance+ * plays, a running entrance. Its end is the test's to decide, since jsdom+ * lacks Web Animations' `getAnimations()`.*/function stubEntrance() {let end = () => {};@@ -2985,7 +2986,11 @@ describe('DropdownMenu entrance under a finger', () => {Object.defineProperty(Element.prototype, 'getAnimations', {configurable: true,value(this: Element) {- return this.matches('[popover]') ? [entrance] : [];+ const layer = this.parentElement;+ return layer?.matches('[popover]') === true &&+ layer.firstElementChild === this+ ? [entrance]+ : [];},});return {diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex 31ea12aa27..3eab074bf5 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -1113,6 +1113,9 @@ function DropdownMenuPopover({dialogLabel: hasRegions? (menuLabel ?? t(DEFAULT_BUTTON_I18N_KEY)): undefined,+ // The entrance runs on the surface: an anchored layer lays out again on+ // each frame its own style animates.+ xstyle: layerAnimations[placement],});const closeMenu = useCallback(() => {@@ -1220,9 +1223,14 @@ function DropdownMenuPopover({pressTouchModel === 'uikit'? listRef.current?.closest('[popover]'): null;+ // The entrance plays on the popover's surface, inside the layer.releaseEntranceRef.current =- layer == null ? null : holdEntranceInput(layer);- }, [listRef, pressTouchModel]);+ layer == null+ ? null+ : holdEntranceInput(layer, {+ entrance: popover.contentRef.current ?? layer,+ });+ }, [listRef, pressTouchModel, popover.contentRef]);holdEntranceRef.current = holdEntrance;// The layer runtime's input hold: an unmount during the entrance releases it.useEffect(@@ -1787,7 +1795,6 @@ function DropdownMenuPopover({resolvedMaxHeight != null &&dynamicStyles.popoverViewportMaxBlockSize(resolvedMaxHeight),popoverXstyle,- layerAnimations[placement],],},)}diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsxindex f1abc419b2..806c1f570c 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx@@ -1155,7 +1155,13 @@ export function DropdownMenuSubMenu(// on it; a drilled-in view sits inside the root's surface.mergeProps(themeProps('dropdown-menu', {presentation: 'popover'}),- stylex.props(regionStyles.frame, regionStyles.flyoutSurface),+ stylex.props(+ regionStyles.frame,+ regionStyles.flyoutSurface,+ // The entrance runs on the surface: an anchored layer lays out again on+ // each frame its own style animates.+ layerAnimations.end,+ ),): stylex.props(regionStyles.frame,@@ -1380,6 +1386,7 @@ export function DropdownMenuSubMenu(? flyoutStyles.touchPanYPinchZoom: flyoutStyles.touchPinchZoom,hasOverflow && flyoutStyles.scrollable,+ layerAnimations.end,),)}>{nestedContent}@@ -1389,11 +1396,7 @@ export function DropdownMenuSubMenu(placement: 'end',alignment: 'start',offset: spacingVars['--spacing-1'],- xstyle: [- flyoutStyles.popoverViewport,- popoverXstyle,- layerAnimations.end,- ],+ xstyle: [flyoutStyles.popoverViewport, popoverXstyle],},),)}diff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuEntranceHold.interaction.browser.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuEntranceHold.interaction.browser.spec.tsindex 6ab8db5a4e..b7a3855dce 100644--- a/packages/core/src/DropdownMenu/__tests__/DropdownMenuEntranceHold.interaction.browser.spec.ts+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuEntranceHold.interaction.browser.spec.ts@@ -112,27 +112,32 @@ const activeDescription = async (page: Page) =>const menuLayer = (page: Page) =>page.locator('[popover]:has([role="menu"])').first();-/** Makes every popover's entrance last 10 s, so input lands inside it. */+/**+ * Makes every popover's entrance last 10 s, so input lands inside it. The+ * entrance runs on the surface, the layer's child.+ */async function lengthenEntrance(page: Page) {await page.addStyleTag({- content: '[popover] { animation-duration: 10s !important; }',+ content: '[popover], [popover] > * { animation-duration: 10s !important; }',});}-/** How many entrance animations run on the menu's layer now. */+/** How many entrance animations run on the menu's layer or its surface now. */const runningEntrances = async (layer: Locator) =>layer.evaluate(element =>- element- .getAnimations()+ [element, element.firstElementChild]+ .flatMap(node => node?.getAnimations() ?? []).filter(animation => animation.playState === 'running').length,);/** Ends the layer's entrance at once, as if its time had run out. */async function finishEntrance(page: Page, layer: Locator) {await layer.evaluate(element => {- for (const animation of element.getAnimations()) {- animation.finish();+ for (const node of [element, element.firstElementChild]) {+ for (const animation of node?.getAnimations() ?? []) {+ animation.finish();+ }}});await frames(page, 2);diff --git a/packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.tsindex e903035e21..fdce5367b7 100644--- a/packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts+++ b/packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts@@ -50,6 +50,7 @@ async function mount(page: Page, story: string) {/*** Waits until the open menu has finished entering. Under a finger, input that* lands during the entrance is held, as UIMenu takes none until it is shown.+ * The entrance runs on the surface, the layer's child.*/async function presented(page: Page) {const layer = page.locator('[popover]:has([role="menu"])').first();@@ -57,8 +58,8 @@ async function presented(page: Page) {.poll(async () =>layer.evaluate(element =>- element- .getAnimations()+ [element, element.firstElementChild]+ .flatMap(node => node?.getAnimations() ?? []).filter(animation => animation.playState === 'running').length,),)diff --git a/packages/core/src/Layer/__tests__/LayerCloseLayout.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/LayerCloseLayout.interaction.browser.spec.tsindex 275a52fe4c..a60fb6392a 100644--- a/packages/core/src/Layer/__tests__/LayerCloseLayout.interaction.browser.spec.ts+++ b/packages/core/src/Layer/__tests__/LayerCloseLayout.interaction.browser.spec.ts@@ -87,10 +87,11 @@ async function traceCloses(page: Page, route: CloseRoute): Promise<Closes> {}await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);}- // An anchored layer lays out on every frame of its entrance, and a busy- // runner can start the entrance late. The close is traced once the layer- // is at rest.- await waitForRest(shown.locator('xpath=ancestor-or-self::*[@popover][1]'));+ // A busy runner can start the entrance late. The close is traced once+ // the entrance, on the layer's surface, is at rest.+ await waitForRest(+ shown.locator('xpath=ancestor-or-self::*[@popover][1]/*[1]'),+ );const trace = await traceRendering(page, async () => {if (route.press == null) {await page.keyboard.press('Escape');diff --git a/packages/core/src/Layer/__tests__/LayerEntranceLayout.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/LayerEntranceLayout.interaction.browser.spec.tsnew file mode 100644index 0000000000..ef993cab35--- /dev/null+++ b/packages/core/src/Layer/__tests__/LayerEntranceLayout.interaction.browser.spec.ts@@ -0,0 +1,218 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file LayerEntranceLayout.interaction.browser.spec.ts+ * @input The Core/Popover, Core/DropdownMenu (default and submenu) and+ * Core/Selector stories, the interaction harness's Chromium rendering trace+ * @output Proves an anchored layer's entrance runs no layout while it plays,+ * on a page with a callback on every frame. Chromium lays an anchored+ * element out again each time its own style changes, so the entrance runs+ * on the surface inside the layer. The surface is the layer's only child+ * and fills its box, so it scales about the same center+ * @position Interaction proofs for layerAnimations.stylex.ts, run in+ * Chromium, the engine with a rendering trace+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ countBetween,+ openStory,+ traceRendering,+ waitForRest,+ withStorybook,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++// A desktop page: on a phone, a Popover plays its own growth in place of the+// CSS entrance.+test.use({+ viewport: {width: 1280, height: 800},+ isMobile: false,+ hasTouch: false,+});++const OPENS = 3;++interface EntranceWindow {+ __entrance: {start: number; end: number};+}++interface EntranceRoute {+ readonly name: string;+ readonly story: string;+ readonly open: (page: Page) => Promise<void>;+ // An element inside the layer that the open shows.+ readonly shown: (page: Page) => Locator;+ // Runs before each open, outside the trace.+ readonly prepare?: (page: Page) => Promise<void>;+ // The layer runs a transition of its own inside the entrance's window.+ readonly hasOwnTransition?: boolean;+}++const layerOf = (locator: Locator) =>+ locator.locator('xpath=ancestor-or-self::*[@popover][1]');++const routes: ReadonlyArray<EntranceRoute> = [+ {+ name: 'Popover',+ story: 'core-popover--default',+ open: async page => page.getByRole('button', {name: 'Settings'}).click(),+ shown: page => page.locator('[popover]:has([role="dialog"])').first(),+ },+ {+ name: 'DropdownMenu',+ story: 'core-dropdownmenu--default',+ open: async page => page.getByRole('button', {name: 'Actions'}).click(),+ shown: page => page.getByRole('menuitem', {name: 'Edit'}),+ },+ {+ name: 'Selector',+ story: 'core-selector--default',+ open: async page =>+ page.locator('button[aria-haspopup="listbox"]').first().click(),+ shown: page => page.getByRole('listbox'),+ // Its list fades in, and that transition lays out once as it ends.+ hasOwnTransition: true,+ },+ {+ name: 'A DropdownMenu submenu',+ story: 'core-dropdownmenu--submenu',+ // The root menu opens and its own entrance ends first.+ prepare: async page => {+ await page.getByRole('button', {name: 'Actions'}).click();+ const row = page.getByRole('menuitem', {name: 'Rename'});+ await expect(row).toBeVisible();+ await waitForRest(layerOf(row));+ },+ open: async page => page.getByRole('menuitem', {name: 'Move to'}).click(),+ shown: page => page.getByRole('menuitem', {name: 'Folder A'}),+ },+];++// A callback on every frame, as on a page with frame work of its own, makes+// each frame a main-thread one. The entrance's window runs from its+// `animationstart` to its `animationend`, on any element in an anchored layer.+async function watchEntrances(page: Page): Promise<void> {+ await page.evaluate(() => {+ const w = window as unknown as EntranceWindow;+ w.__entrance = {start: 0, end: 0};+ const tick = () => requestAnimationFrame(tick);+ requestAnimationFrame(tick);+ const inLayer = (target: EventTarget | null) =>+ target instanceof Element &&+ target.closest('[data-layer-anchored]') != null;+ addEventListener(+ 'animationstart',+ event => {+ if (inLayer(event.target) && w.__entrance.start === 0) {+ w.__entrance.start = performance.timeOrigin + event.timeStamp;+ }+ },+ true,+ );+ addEventListener(+ 'animationend',+ event => {+ if (inLayer(event.target)) {+ w.__entrance.end = performance.timeOrigin + event.timeStamp;+ }+ },+ true,+ );+ });+}++async function closeAll(page: Page): Promise<void> {+ const open = page.locator('[data-layer-anchored]:popover-open');+ for (let press = 0; press < 3 && (await open.count()) > 0; press++) {+ await page.keyboard.press('Escape');+ }+ await expect(open).toHaveCount(0);+}++// The rendering work inside one entrance's window.+async function traceEntrance(+ page: Page,+ route: EntranceRoute,+): Promise<Record<string, number>> {+ await route.prepare?.(page);+ await page.evaluate(() => {+ (window as unknown as EntranceWindow).__entrance = {start: 0, end: 0};+ });+ const trace = await traceRendering(page, async () => {+ await route.open(page);+ await expect(route.shown(page)).toBeVisible();+ await page.waitForFunction(+ () => (window as unknown as EntranceWindow).__entrance.end > 0,+ );+ });+ const {start, end} = await page.evaluate(+ () => (window as unknown as EntranceWindow).__entrance,+ );+ expect(start).toBeGreaterThan(0);+ return countBetween(trace, start, end);+}++for (const route of routes.filter(route => !route.hasOwnTransition)) {+ test(`${route.name}: the entrance runs no layout while it plays`, async ({+ page,+ browserName,+ }) => {+ test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');+ await openStory(page, storybook(), route.story);+ await watchEntrances(page);+ const layouts: number[] = [];+ const restyles: number[] = [];+ for (let open = 0; open < OPENS; open++) {+ const during = await traceEntrance(page, route);+ layouts.push(during.Layout ?? 0);+ restyles.push(during.UpdateLayoutTree ?? 0);+ await closeAll(page);+ }+ // The entrance played across frames: its element restyled on several.+ expect(Math.min(...restyles)).toBeGreaterThanOrEqual(3);+ expect(layouts).toEqual(Array(OPENS).fill(0));+ });+}++for (const route of routes) {+ test(`${route.name}: the entrance runs on the layer's only child, which fills the layer's box`, async ({+ page,+ }) => {+ await openStory(page, storybook(), route.story);+ await route.prepare?.(page);+ await route.open(page);+ const shown = route.shown(page);+ await expect(shown).toBeVisible();+ const layer = layerOf(shown);+ await waitForRest(layer);+ const read = await layer.evaluate(element => {+ const box = (node: Element) => {+ const rect = node.getBoundingClientRect();+ return [rect.left, rect.top, rect.width, rect.height];+ };+ const surface = element.firstElementChild;+ const animated = [element, ...Array.from(element.querySelectorAll('*'))]+ .filter(node => getComputedStyle(node).animationName !== 'none')+ .map(node => (node === surface ? 'surface' : node.tagName));+ return {+ children: element.childElementCount,+ animated,+ layer: box(element),+ surface: surface == null ? [] : box(surface),+ };+ });+ expect(read.children).toBe(1);+ expect(read.animated).toEqual(['surface']);+ expect(read.surface).toHaveLength(4);+ read.surface.forEach((value, index) => {+ expect(Math.abs(value - read.layer[index])).toBeLessThanOrEqual(0.5);+ });+ });+}diff --git a/packages/core/src/Layer/layerAnimations.stylex.ts b/packages/core/src/Layer/layerAnimations.stylex.tsindex 921e767ae5..87cbc90f04 100644--- a/packages/core/src/Layer/layerAnimations.stylex.ts+++ b/packages/core/src/Layer/layerAnimations.stylex.ts@@ -8,22 +8,24 @@* @position Shared animation primitives; consumed by DropdownMenu, Popover,* HoverCard, Tooltip, Selector, and any component using useLayer*- * Provides opt-in entry animations for popover/layer components.- * Components apply these via the `xstyle` prop on `layer.render()`.+ * Provides opt-in entry animations for popover/layer components. Apply one+ * to the element that fills the layer (its surface), not to the layer.+ * Chromium lays an anchored layer out again on each frame that its own+ * style animates. On the layer the entrance still plays, at that cost.** @example* ```* import {layerAnimations} from '../Layer/layerAnimations.stylex';** // Direction-aware (for components that know placement):- * layer.render(<Content />, {- * xstyle: layerAnimations[placement],- * });+ * layer.render(+ * <div {...stylex.props(styles.surface, layerAnimations[placement])}>+ * <Content />+ * </div>,+ * );*- * // Fixed direction:- * layer.render(<Content />, {- * xstyle: layerAnimations.below,- * });+ * // usePopover's surface takes the hook's `xstyle`:+ * const popover = usePopover({xstyle: layerAnimations.below});* ```*/diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsxindex 576d14996c..382dc44060 100644--- a/packages/core/src/Popover/Popover.tsx+++ b/packages/core/src/Popover/Popover.tsx@@ -587,6 +587,9 @@ export function Popover({xstyle: [styles.surfaceViewportFit,hasOverflow && styles.surfaceScrollable,+ // The entrance runs on the surface: an anchored layer lays out again on+ // each frame its own style animates.+ layerAnimations[placement],xstyle,],className,@@ -603,6 +606,7 @@ export function Popover({surfaceMotion.present(surfaceRef.current?.closest<HTMLElement>('[popover]') ?? null,anchorElementRef.current,+ surfaceRef.current,);};// A controlled popover opens on the surface its presentation resolves to@@ -1050,7 +1054,6 @@ export function Popover({? width.trim(): clampInlineSize(width, layerViewportInset.maxInlineSizeFallback),);- const layerXstyle = [popoverSizeXstyle, layerAnimations[placement]];// One instance of the content at a time: the sheet holds it while it is// mounted, the anchored layer otherwise.@@ -1100,7 +1103,7 @@ export function Popover({placement,alignment,offset: spacingVars['--spacing-1'],- xstyle: layerXstyle,+ xstyle: popoverSizeXstyle,});// Sibling mode: render only the popover (no wrapper needed)diff --git a/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts b/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.tsindex 662f5eac9a..9d38cebb9f 100644--- a/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts+++ b/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts@@ -400,23 +400,26 @@ test.describe('with a mouse (a fine primary pointer)', () => {await trigger.click();await expect(trigger).toHaveAttribute('aria-expanded', 'true');const layer = page.locator('[popover]:has(.astryx-popover)').first();- // The layer's own CSS entrance runs; no UIKit scale is set or played.- const entrance = await layer.evaluate(element => ({- inlineScale: (element as HTMLElement).style.getPropertyValue('scale'),- inlineAnimation: (element as HTMLElement).style.getPropertyValue(- 'animation-name',- ),- animationName: getComputedStyle(element).animationName,- played: element- .getAnimations()- .some(- animation =>- !(animation instanceof CSSAnimation) &&- (animation.effect as KeyframeEffect | null)- ?.getKeyframes()- .some(frame => 'scale' in frame) === true,- ),- }));+ // The surface's CSS entrance runs; no UIKit scale is set or played.+ const entrance = await layer.evaluate(element => {+ const surface = element.querySelector<HTMLElement>('.astryx-popover');+ return {+ inlineScale: (element as HTMLElement).style.getPropertyValue('scale'),+ inlineAnimation:+ surface?.style.getPropertyValue('animation-name') ?? 'no surface',+ animationName:+ surface == null ? 'none' : getComputedStyle(surface).animationName,+ played: element+ .getAnimations({subtree: true})+ .some(+ animation =>+ !(animation instanceof CSSAnimation) &&+ (animation.effect as KeyframeEffect | null)+ ?.getKeyframes()+ .some(frame => 'scale' in frame) === true,+ ),+ };+ });expect(entrance.inlineScale).toBe('');expect(entrance.inlineAnimation).toBe('');expect(entrance.animationName).not.toBe('none');@@ -892,7 +895,7 @@ test('a style read after the opening tap finds no CSS entrance running on the la}resolve(layer- .getAnimations()+ .getAnimations({subtree: true}).filter(animation =>animation instanceof CSSAnimation &&diff --git a/packages/core/src/Popover/popoverSurfaceMotion.test.ts b/packages/core/src/Popover/popoverSurfaceMotion.test.tsindex 12969671f9..7727160f21 100644--- a/packages/core/src/Popover/popoverSurfaceMotion.test.ts+++ b/packages/core/src/Popover/popoverSurfaceMotion.test.ts@@ -257,7 +257,10 @@ describe('createPopoverSurfaceMotion', () => {vi.unstubAllGlobals();});- const create = (reducedMotion = false, {scheduled = true} = {}) => {+ const create = (+ reducedMotion = false,+ {scheduled = true, entrance = false} = {},+ ) => {const host = document.createElement('section');document.body.appendChild(host);const element = document.createElement('div');@@ -278,6 +281,10 @@ describe('createPopoverSurfaceMotion', () => {// The touch presentation runs under a coarse pointer, where Reduce// Motion cross-fades.stubMedia(reducedMotion, true);+ // The surface, where the pointer presentation's CSS entrance runs.+ const surface = entrance+ ? element.querySelector<HTMLElement>('[role="dialog"]')+ : null;const motion = createPopoverSurfaceMotion(element,scheduled@@ -289,8 +296,9 @@ describe('createPopoverSurfaceMotion', () => {return lastFrame;},cancelFrame: handle => frames.delete(handle),+ entrance: surface,}- : {now: () => clock},+ : {now: () => clock, entrance: surface},);return {element, motion};};@@ -717,6 +725,25 @@ describe('createPopoverSurfaceMotion', () => {expect(copyOf(element)).toBeNull();});+ it('turns the CSS entrance off on the surface too, and gives it back where it gives the layer\u2019s back', async () => {+ const {element, motion} = create(false, {entrance: true});+ const surface = element.querySelector<HTMLElement>('[role="dialog"]')!;+ motion.enter(() => GEOMETRY);+ await Promise.resolve();+ expect(surface.style.getPropertyValue('animation-name')).toBe('none');+ frame();+ expect(surface.style.getPropertyValue('animation-name')).toBe('none');+ motion.reset();+ expect(surface.style.getPropertyValue('animation-name')).toBe('');+ // A close after the opening task ends, before the frame.+ motion.enter(() => GEOMETRY);+ await Promise.resolve();+ expect(surface.style.getPropertyValue('animation-name')).toBe('none');+ motion.exit();+ frame();+ expect(surface.style.getPropertyValue('animation-name')).toBe('');+ });+it('reset leaves the element as the component styles it', () => {const {element, motion} = create();motion.enter(() => GEOMETRY);diff --git a/packages/core/src/Popover/popoverSurfaceMotion.ts b/packages/core/src/Popover/popoverSurfaceMotion.tsindex df025fe5b9..fb3ff9f304 100644--- a/packages/core/src/Popover/popoverSurfaceMotion.ts+++ b/packages/core/src/Popover/popoverSurfaceMotion.ts@@ -162,12 +162,19 @@ export function createPopoverSurfaceMotion({requestFrame,cancelFrame,+ entrance = null,...animatorOptions}: Pick<AnimatorOptions, 'now'> & {/** Schedules the presentation's read (default: the window's animation frame). */requestFrame?: (callback: () => void) => number;/** Cancels a read that `requestFrame` scheduled. */cancelFrame?: (handle: number) => void;+ /**+ * The surface inside the layer, where the pointer presentation's CSS+ * entrance runs. The touch presentation turns that entrance off there+ * as on the element.+ */+ entrance?: HTMLElement | null;} = {},): PopoverSurfaceMotion {const animator = createMotionEngine(element, animatorOptions);@@ -217,6 +224,13 @@ export function createPopoverSurfaceMotion(exiting = null;};+ // The CSS entrance belongs to the pointer presentation. This presentation+ // plays its own growth instead.+ const holdEntrance = () => {+ element.style.setProperty('animation-name', 'none');+ entrance?.style.setProperty('animation-name', 'none');+ };+const reset = () => {cancelPending();collapsed = null;@@ -228,6 +242,7 @@ export function createPopoverSurfaceMotion(for (const property of MOTION_STYLE_PROPERTIES) {element.style.removeProperty(property);}+ entrance?.style.removeProperty('animation-name');};const enter = (measure: () => PopoverSurfaceGeometry) => {@@ -267,7 +282,7 @@ export function createPopoverSurfaceMotion(// no entrance for the frame to cancel.queueMicrotask(() => {if (pendingPresentFrame === frame) {- element.style.setProperty('animation-name', 'none');+ holdEntrance();}});}@@ -288,8 +303,7 @@ export function createPopoverSurfaceMotion(// The start frame goes first. The motion engine may read the element's// will-change as it sets it, before any write of ours.animator.set(frameOf(start, next.axis));- // The layer's own CSS entrance belongs to the pointer presentation.- element.style.setProperty('animation-name', 'none');+ holdEntrance();element.style.setProperty('transform-origin',`${next.originX}px ${next.originY}px`,@@ -324,6 +338,7 @@ export function createPopoverSurfaceMotion(for (const property of MOTION_STYLE_PROPERTIES) {element.style.removeProperty(property);}+ entrance?.style.removeProperty('animation-name');return;}const target = collapsed;diff --git a/packages/core/src/Popover/usePopoverSurfaceMotion.ts b/packages/core/src/Popover/usePopoverSurfaceMotion.tsindex 2ad13b9512..025f3b933b 100644--- a/packages/core/src/Popover/usePopoverSurfaceMotion.ts+++ b/packages/core/src/Popover/usePopoverSurfaceMotion.ts@@ -46,9 +46,14 @@ function boxOf(element: Element): PopoverSurfaceRect {export interface PopoverSurfaceMotionCalls {/*** Call as the popover opens, right after the browser shows it and before- * it paints.+ * it paints. `entrance` is the surface that carries the pointer+ * presentation's CSS entrance; the touch presentation turns it off there.*/- present: (layer: HTMLElement | null, source: HTMLElement | null) => void;+ present: (+ layer: HTMLElement | null,+ source: HTMLElement | null,+ entrance?: HTMLElement | null,+ ) => void;/** Call as the popover starts to close, while the browser still shows it. */closeStart: () => void;}@@ -56,6 +61,7 @@ export interface PopoverSurfaceMotionCalls {export function usePopoverSurfaceMotion(): PopoverSurfaceMotionCalls {const motionRef = useRef<{element: HTMLElement;+ entrance: HTMLElement | null;motion: PopoverSurfaceMotion;} | null>(null);const isTouchPresentationRef = useRef(false);@@ -65,23 +71,30 @@ export function usePopoverSurfaceMotion(): PopoverSurfaceMotionCalls {motionRef.current = null;}, []);- const motionFor = useCallback((element: HTMLElement) => {- const current = motionRef.current;- if (current?.element === element) {- return current.motion;- }- current?.motion.dispose();- const motion = createPopoverSurfaceMotion(element);- motionRef.current = {element, motion};- return motion;- }, []);+ const motionFor = useCallback(+ (element: HTMLElement, entrance: HTMLElement | null) => {+ const current = motionRef.current;+ if (current?.element === element && current.entrance === entrance) {+ return current.motion;+ }+ current?.motion.dispose();+ const motion = createPopoverSurfaceMotion(element, {entrance});+ motionRef.current = {element, entrance, motion};+ return motion;+ },+ [],+ );// Releases the motion's compositor animations, and any exit copy still on// screen, at unmount.useEffect(() => release, [release]);const present = useCallback(- (layer: HTMLElement | null, source: HTMLElement | null) => {+ (+ layer: HTMLElement | null,+ source: HTMLElement | null,+ entrance: HTMLElement | null = null,+ ) => {if (layer == null) {return;}@@ -96,7 +109,7 @@ export function usePopoverSurfaceMotion(): PopoverSurfaceMotionCalls {release();return;}- motionFor(layer).enter(() => ({+ motionFor(layer, entrance).enter(() => ({surface: boxOf(layer),source: boxOf(source),}));diff --git a/packages/core/src/PowerSearch/PowerSearch.tsx b/packages/core/src/PowerSearch/PowerSearch.tsxindex 39895dda6d..22ebd7f13a 100644--- a/packages/core/src/PowerSearch/PowerSearch.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.tsx@@ -783,6 +783,9 @@ export function PowerSearch({editedBuiltInFilter != null? tokenText(editedBuiltInFilter).full: undefined,+ // The entrance runs on the surface: an anchored layer lays out again on+ // each frame its own style animates.+ xstyle: layerAnimations.below,});// A presentation swap removes the focused control, so the other@@ -1656,7 +1659,7 @@ export function PowerSearch({placement: 'below',alignment: 'start',offset: spacingVars['--spacing-1'],- xstyle: [popoverLayerStyles.layer, layerAnimations.below],+ xstyle: popoverLayerStyles.layer,})}</>);diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex c53231f57d..c697f28e52 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -1370,6 +1370,9 @@ export function Selector<T extends SelectorOptionType>(// The theme target belongs on the SURFACE that paints the popup, which// `usePopover` owns — not on the scrolling list inside it.surfaceTarget: 'selector-popup',+ // The entrance runs on the surface: an anchored layer lays out again on+ // each frame its own style animates.+ xstyle: layerAnimations[placement ?? 'below'],},});const {popover} = surface;@@ -2111,7 +2114,7 @@ export function Selector<T extends SelectorOptionType>(offset: shouldOverlaySelectedItem? undefined: spacingVars['--spacing-1'],- xstyle: [styles.popover, layerAnimations[popoverPlacement]],+ xstyle: styles.popover,style: popoverOffsetStyle,});}diff --git a/packages/core/src/Selector/__tests__/SelectorKeyboardInset.a11y.chromium.spec.ts b/packages/core/src/Selector/__tests__/SelectorKeyboardInset.a11y.chromium.spec.tsindex a0eb2af35b..d791eb2eb8 100644--- a/packages/core/src/Selector/__tests__/SelectorKeyboardInset.a11y.chromium.spec.ts+++ b/packages/core/src/Selector/__tests__/SelectorKeyboardInset.a11y.chromium.spec.ts@@ -96,6 +96,45 @@ async function coverAndTrackTop(page: Page, cover = 0): Promise<number[]> {}, cover);}+/**+ * Waits for the open's own animations to end. Until then the entrance, on the+ * popover's surface, moves the list's box. A wait past 2 s fails and names+ * what still runs.+ */+async function openEnded(page: Page): Promise<void> {+ await page.getByRole('listbox').evaluate(async list => {+ const layer = list.closest('[popover]') ?? list;+ const finite = layer+ .getAnimations({subtree: true})+ .filter(+ animation => animation.effect?.getComputedTiming().endTime !== Infinity,+ );+ const ended = Promise.all(+ finite.map(async animation => animation.finished.catch(() => undefined)),+ ).then(() => 'ended' as const);+ const cap = new Promise<'cap'>(resolve => {+ setTimeout(() => resolve('cap'), 2_000);+ });+ if ((await Promise.race([ended, cap])) === 'cap') {+ const running = finite+ .filter(animation => animation.playState !== 'finished')+ .map(animation => {+ const target = (animation.effect as KeyframeEffect | null)?.target;+ const name =+ animation instanceof CSSAnimation+ ? animation.animationName+ : animation instanceof CSSTransition+ ? animation.transitionProperty+ : 'script';+ return `${target?.tagName ?? 'no target'} ${name} ${animation.playState}`;+ });+ throw new Error(+ `The open's animations still run after 2 s: ${running.join('; ')}`,+ );+ }+ });+}+function expectTopHeld(tops: number[], top: number, detail: string) {expect(tops.length, detail).toBeGreaterThan(0);for (const each of tops) {@@ -191,6 +230,7 @@ for (const drop of [80, 150, 190]) {await raiseKeyboard(page);await trigger.click();await expect(page.getByRole('listbox')).toBeVisible();+ await openEnded(page);await expect(async () => {expectClearOfKeyboard(await listFacts(page));}).toPass({timeout: 3_000});@@ -253,6 +293,7 @@ test('a list the cap holds above the keyboard grows downward in place when the rawait trigger.click();const listbox = page.getByRole('listbox');await expect(listbox).toBeVisible();+ await openEnded(page);const read = async () =>listbox.evaluate(list => {const box = list.getBoundingClientRect();diff --git a/packages/lab/src/Schedule/MonthlyView.tsx b/packages/lab/src/Schedule/MonthlyView.tsxindex f51d098893..50ccf67953 100644--- a/packages/lab/src/Schedule/MonthlyView.tsx+++ b/packages/lab/src/Schedule/MonthlyView.tsx@@ -15,7 +15,6 @@import {useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';-import {layerAnimations} from '@astryxdesign/core/Layer';import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';import {focusOutlineStyles,@@ -463,7 +462,6 @@ function ScheduleMonthlyView({placement: 'below',alignment: 'start',offset: spacingVars['--spacing-1'],- xstyle: layerAnimations.below,})}</ScheduleFrame>);diff --git a/packages/lab/src/Schedule/TimeGridView.tsx b/packages/lab/src/Schedule/TimeGridView.tsxindex a9bc6a5b3e..b938f17207 100644--- a/packages/lab/src/Schedule/TimeGridView.tsx+++ b/packages/lab/src/Schedule/TimeGridView.tsx@@ -257,6 +257,9 @@ export function TimeGridView({// Popover's own defaults, spelled out where the hook's differ.padding: 3,surfaceTarget: 'popover',+ // The entrance runs on the surface: an anchored layer lays out again on+ // each frame its own style animates.+ xstyle: layerAnimations.below,onHide: useCallback(() => {setOpenBlock(null);}, []),@@ -689,7 +692,6 @@ export function TimeGridView({placement: 'below',alignment: 'start',offset: spacingVars['--spacing-1'],- xstyle: layerAnimations.below,},)}</>diff --git a/packages/lab/src/Schedule/useScheduleViewPopover.ts b/packages/lab/src/Schedule/useScheduleViewPopover.tsindex 96ef24dd41..432b85e774 100644--- a/packages/lab/src/Schedule/useScheduleViewPopover.ts+++ b/packages/lab/src/Schedule/useScheduleViewPopover.ts@@ -21,6 +21,7 @@ import {type MouseEvent as ReactMouseEvent,type PointerEvent as ReactPointerEvent,} from 'react';+import {layerAnimations} from '@astryxdesign/core/Layer';import {usePopover, type UsePopoverReturn} from '@astryxdesign/core/Popover';const TRIGGER_ATTRIBUTE = 'data-schedule-popover-trigger';@@ -82,6 +83,9 @@ export function useScheduleViewPopover(// Popover's own defaults, spelled out where the hook's differ.padding: 3,surfaceTarget: 'popover',+ // The entrance runs on the surface: an anchored layer lays out again on+ // each frame its own style animates.+ xstyle: layerAnimations.below,onHide: useCallback(() => {setOpenKey(null);}, []),