From 1fda0191072c43a1489a5796c1aaab7abc9f67f5 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 4 Nov 2026 15:53:44 -0800 Subject: [PATCH 1/4] chore(core): the layer runtime's exit copy, for a touch presentation's close placeLayerExitCopy puts a static, inert copy of a closing layer where the layer was drawn, in the top layer, for a touch presentation's close to play on: the browser hides a popover the moment it closes. The copy keeps the layer's box, transform, presented look, overflow and scroll positions; has no ids, anchor names, form names or form owner; is inert and hidden from assistive technology; and its descendants' keyframe animations and transitions do not start again. A refused show during the closing toggle waits, hidden, until the toggle is over. A layer inside other layers gets its copy after the outermost one, with what it inherited there (its color scheme included), so a close that takes the layers around it too still draws the copy. That copy is shown again above the copy the same close then places for a layer around it. A layer has one copy. The layer-runtime record states it, and that the presentation plays its exit on the copy (AST-094 FR7). Core's shared inertCopy now takes every copied native control and form-associated custom element out of any form with form="", as its documentation says, so the swap's copies join no form either. It also sets anchor-name: none on each copied element that has an anchor name, so no live anchor gets a second element. --- .changeset/layer-exit-copy.md | 7 + docs/architecture/layer-runtime.md | 49 +- .../layerExitCopy.interaction.browser.spec.ts | 316 ++++++++++ packages/core/src/Layer/layerExitCopy.test.ts | 574 ++++++++++++++++++ packages/core/src/Layer/layerExitCopy.ts | 315 ++++++++++ packages/core/src/Layer/settledBox.ts | 132 ++++ packages/core/src/Layer/useLayer.tsx | 123 +--- .../motion/animatedLayout.boundary.test.ts | 7 +- .../core/src/motion/transientCopy.test.ts | 73 +++ packages/core/src/motion/transientCopy.ts | 128 ++-- 10 files changed, 1556 insertions(+), 168 deletions(-) create mode 100644 .changeset/layer-exit-copy.md create mode 100644 packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts create mode 100644 packages/core/src/Layer/layerExitCopy.test.ts create mode 100644 packages/core/src/Layer/layerExitCopy.ts create mode 100644 packages/core/src/Layer/settledBox.ts create mode 100644 packages/core/src/motion/transientCopy.test.ts diff --git a/.changeset/layer-exit-copy.md b/.changeset/layer-exit-copy.md new file mode 100644 index 0000000000000..1de201856e16d --- /dev/null +++ b/.changeset/layer-exit-copy.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: the layer runtime gains one exit copy for touch presentations that animate a popover out: a static, inert copy of the closing popover, shown only in the top layer where the popover was drawn, for the close to play on. Core's other inert copies now join no form, carry no anchor name and keep their color scheme, as their documentation says. + +@vjeux diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md index 8eb9f41c6f8b7..77945773730b7 100644 --- a/docs/architecture/layer-runtime.md +++ b/docs/architecture/layer-runtime.md @@ -34,6 +34,8 @@ verified_by: packages/core/src/Layer/useLayerDismissal.test.tsx, packages/core/src/Layer/layerClickBoundary.test.tsx, packages/core/src/Layer/layerDismissalInvariants.test.tsx, + packages/core/src/Layer/layerExitCopy.test.ts, + packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts, packages/core/src/Popover/Popover.test.tsx, packages/core/src/DropdownMenu/DropdownMenu.test.tsx, packages/core/src/ContextMenu/ContextMenu.test.tsx, @@ -64,6 +66,7 @@ deciding_specs: [spec:AST-038, spec:AST-059] "INV7", "INV11", "INV12", + "INV13", "INV14", "INV15", "INV17", @@ -311,6 +314,26 @@ else closes the layer, a scroll or pinch that starts outside does not, and Escape stays on the shared stack. Focus leaving the field stays each owner's to handle (`family:overlay-dismissal` AV4). +### Exit copy + +The browser hides a popover the moment it closes, whether by a pick, Escape, or +its own light dismiss. A touch presentation whose close stays on screen plays it +on an exit copy: a static copy of the layer that `placeLayerExitCopy` takes as +the layer closes. The copy is laid out on the layer's own box and carries the +transform and opacity the layer is drawn with, so a copy taken while the layer +is still entering holds where it was drawn. It carries no ids, form names, or +form owner; it is `inert`, hidden from assistive technology, and out of pointer +reach; it keeps the layer's scroll positions. It is shown only in the top layer, +as a manual popover, so a clipping, transformed, or sticky ancestor neither cuts +nor moves it; a fixed box or a larger `z-index` is no substitute +(`spec:AST-027` FR8). Where the browser refuses that show during the closing +popover's own toggle, the copy waits, hidden, and enters the top layer once the +toggle is over: after the script that closed the layer, or in the next frame +before it paints. Where there is no top layer (no popover API), or the browser +still refuses, there is no copy and the close is immediate. The presentation +that placed the copy plays its exit on it (`spec:AST-094` FR7) and removes it +when its close settles. + ### Current dismissal plumbing `family:overlay-dismissal` owns the shipped Escape/platform-close membership @@ -504,6 +527,12 @@ layers use Layer rendering without joining Escape/platform dismissal. correct, and the runtime polls nothing: an anchor that a scrolled container hides is followed again when an intersection observer reports it back in view. +- **INV13 — One exit copy per closing layer.** A layer's close plays on at most + one exit copy, made by `placeLayerExitCopy`: drawn where the layer was drawn, + inert, hidden from assistive technology, without ids, form names, or form + owner, shown only in the top layer, and removed by its owner when the close + settles. Placing a second copy for the same layer removes the first; another + layer's copy stays. - **INV14 — The runtime owns every layer's shared mechanism.** Internally, the layer runtime owns the shared mechanism layers use: top-layer mounting, close-request delivery, the presentation hold (keeping a layer's chosen presentation from the open until @@ -571,11 +600,12 @@ Current gaps are observable facts, not current target behavior: migration, verification, and completion criteria for these gaps. This record must be updated only as that work ships. -INV14 and INV15 are not met yet, and `spec:AST-003` does not cover them: no -shared presentation hold, exit copy, runtime backdrop tint, or lift module -exists, and Dialog, Drawer, BottomSheet, Lightbox, MobileNav, ToastViewport, -and Selector each build their own top-layer mounting, exit, or backdrop, and -Popover builds its own presentation hold for its sheet presentation. +INV14 and INV15 are not met yet, and `spec:AST-003` does not cover them. The +runtime owns the shared exit copy (INV13, `placeLayerExitCopy`); no shared +presentation hold, runtime backdrop tint or lift module exists, Dialog, Drawer, +BottomSheet, Lightbox, MobileNav, ToastViewport, and Selector each build their +own top-layer mounting, exit, or backdrop, and Popover builds its own +presentation hold for its sheet presentation. BottomSheet's own includes its sheet stack's mounting — the re-show that keeps a document's sheets in open order, a step dialog's modal present, and the non-modal sheet's popover host — alongside its scrim; the ordering rules @@ -628,6 +658,12 @@ is staged as `[breaking]` (`spec:AST-017` FR32) and `component:SelectableCard` entry/return, and controlled close behavior. - A browser fallback change updates public `useLayer` and Popover docs and tests for both the native path and actual fallback. +- An exit-copy change verifies, where each can be observed: the copy's reach, + accessibility and form exclusion in jsdom; its top-layer show (from script + and by light dismiss), its place mid-entrance, and that a layer keeps one + copy, in jsdom and in Chromium and WebKit; and the refused show's wait in + jsdom and on Chromium 150 and later, the engines that refuse a show during + another popover's toggle (Chromium 149 accepts it). ## Owning code @@ -657,6 +693,8 @@ is staged as `[breaking]` (`spec:AST-017` FR32) and `component:SelectableCard` `stopPropagation()` also stops the native event in React 19, which would break ContextMenu's outside `mousedown`, Typeahead's pending click, and the layer's keep-open `pointerup`, so the seam never stops the native event. +- `Layer/layerExitCopy.ts` owns the exit copy a touch presentation's close plays + on. - `Layer/layerStack.ts`, `Layer/useLayerDismissal.ts`, and `Layer/LayerDepthContext.tsx` own current registration, presence, ordering, and Escape/platform routing. @@ -709,6 +747,7 @@ this current architecture record. | 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 | +| 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 | A current local channel silently changes ownership or policy | diff --git a/packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts new file mode 100644 index 0000000000000..4d64047b4a2a7 --- /dev/null +++ b/packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts @@ -0,0 +1,316 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file layerExitCopy.interaction.browser.spec.ts + * @input The exit copy bundled with esbuild onto a blank fixture page, in + * Chromium and WebKit. The page holds a popover layer inside a clipping, + * transformed panel, with an entrance curve held halfway. + * @output Proof that the engine shows the copy where the layer was drawn. + * The copy is placed as the layer closes, from script and by the browser's + * own light dismiss. It is in the top layer as a manual popover with no + * `z-index`. The clipping panel does not cut it. Its drawn box equals the + * layer's drawn box mid-entrance, within half a px. A second copy for the + * same layer replaces the first, while another layer's copy stays. + * @position Browser proof for layerExitCopy.ts, run by `pnpm + * test:interaction`; jsdom has no layout and no top layer. Android + * Chromium 158 refuses a show during another popover's toggle. These + * engines do not refuse, so the refusal path is proven on an Android + * emulator instead. + */ + +import {fileURLToPath} from 'node:url'; +import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright'; +import {build} from 'esbuild'; + +declare global { + interface Window { + ExitCopy: typeof import('../layerExitCopy'); + } +} + +let script = ''; + +test.beforeAll(async () => { + const result = await build({ + entryPoints: [ + fileURLToPath(new URL('../layerExitCopy.ts', import.meta.url)), + ], + bundle: true, + write: false, + format: 'iife', + globalName: 'ExitCopy', + target: 'es2022', + }); + script = result.outputFiles[0].text; +}); + +const ATTRIBUTE = 'data-exit-copy'; + +// A real navigation (not setContent): the page keeps its own window. The +// layer sits in a panel that clips and is transformed. A fixed box placed +// there would be cut and moved; the top layer is neither. +async function open(page: Page) { + const html = ` + +
+

One

+
Other
+
+`; + await page.route('http://exit-copy.test/', async route => + route.fulfill({contentType: 'text/html', body: html}), + ); + await page.goto('http://exit-copy.test/'); +} + +test('a copy placed as a layer closes mid-entrance is in the top layer, where the layer was drawn', async ({ + page, +}) => { + await open(page); + const result = await page.evaluate( + async ({attribute}) => { + const layer = document.getElementById('layer') as HTMLElement; + layer.showPopover(); + // An entrance halfway through: drawn at 60 % about its top-left corner. + const entrance = layer.animate( + [ + {scale: '0.2', transformOrigin: '0 0'}, + {scale: '1', transformOrigin: '0 0'}, + ], + {duration: 1000, fill: 'both'}, + ); + entrance.pause(); + entrance.currentTime = 500; + const drawn = layer.getBoundingClientRect(); + let copy: HTMLElement | null = null; + layer.addEventListener( + 'beforetoggle', + event => { + if (event.newState === 'closed') { + copy = window.ExitCopy.placeLayerExitCopy(layer, attribute); + } + }, + {once: true}, + ); + layer.hidePopover(); + await new Promise(resolve => requestAnimationFrame(resolve)); + const placed = copy as HTMLElement | null; + if (placed == null) { + return null; + } + const rect = placed.getBoundingClientRect(); + return { + drawn: [drawn.left, drawn.top, drawn.width, drawn.height], + copy: [rect.left, rect.top, rect.width, rect.height], + open: placed.matches(':popover-open'), + popover: placed.getAttribute('popover'), + zIndex: getComputedStyle(placed).zIndex, + layerOpen: layer.matches(':popover-open'), + }; + }, + {attribute: ATTRIBUTE}, + ); + expect(result).not.toBeNull(); + expect(result!.layerOpen).toBe(false); + expect(result!.open).toBe(true); + expect(result!.popover).toBe('manual'); + expect(result!.zIndex).toBe('auto'); + // Mid-entrance the drawn box is not the layout box; the copy holds it. + expect(result!.drawn[2]).toBeLessThan(280); + result!.copy.forEach((value, index) => { + expect(Math.abs(value - result!.drawn[index])).toBeLessThanOrEqual(0.5); + }); +}); + +test('the browser\u2019s own light dismiss gets the copy too, uncut by the clipping panel', async ({ + page, +}) => { + await open(page); + await page.evaluate(attribute => { + const layer = document.getElementById('layer') as HTMLElement; + layer.showPopover(); + layer.addEventListener( + 'beforetoggle', + event => { + if (event.newState === 'closed') { + window.ExitCopy.placeLayerExitCopy(layer, attribute); + } + }, + {once: true}, + ); + }, ATTRIBUTE); + // A press outside: the browser closes the layer by itself. + await page.mouse.click(360, 700); + const result = await page.evaluate(attribute => { + const copy = document.querySelector(`[${attribute}]`); + if (copy == null) { + return null; + } + const rect = copy.getBoundingClientRect(); + return { + open: copy.matches(':popover-open'), + rect: [rect.left, rect.top, rect.width, rect.height], + layerOpen: document.getElementById('layer')!.matches(':popover-open'), + }; + }, ATTRIBUTE); + expect(result).not.toBeNull(); + expect(result!.layerOpen).toBe(false); + expect(result!.open).toBe(true); + // Where the layer stood, at its full size: the 60 x 40 clipping panel and + // its 30 px transform neither cut nor moved it. + expect(result!.rect).toEqual([40, 120, 280, 200]); +}); + +test('a layer that closes with the layer around it gets a copy that is drawn, outside both', async ({ + page, +}) => { + await open(page); + const result = await page.evaluate(async attribute => { + const outer = document.createElement('div'); + outer.setAttribute('popover', 'auto'); + outer.style.setProperty('--tone', 'rgb(10, 20, 30)'); + // A dark scheme scope between the two layers, as a Theme inside a Dialog. + const scope = document.createElement('div'); + scope.style.setProperty('color-scheme', 'dark'); + const inner = document.createElement('div'); + inner.setAttribute('popover', 'auto'); + inner.style.setProperty('top', '360px'); + inner.style.setProperty( + 'background', + 'light-dark(rgb(255, 255, 255), rgb(31, 31, 34))', + ); + inner.innerHTML = '

Nested

'; + scope.append(inner); + outer.append(scope); + document.body.append(outer); + outer.showPopover(); + inner.showPopover(); + let copy: HTMLElement | null = null; + inner.addEventListener( + 'beforetoggle', + event => { + if (event.newState === 'closed') { + copy = window.ExitCopy.placeLayerExitCopy(inner, attribute); + } + }, + {once: true}, + ); + // The outer layer's close takes the inner one with it, in one step. + outer.hidePopover(); + // Where the browser refuses a show during the toggle, the copy opens + // after this script, before the next frame paints. + await new Promise(resolve => requestAnimationFrame(resolve)); + const placed = copy as HTMLElement | null; + if (placed == null) { + return null; + } + const rect = placed.getBoundingClientRect(); + return { + open: placed.matches(':popover-open'), + visible: placed.checkVisibility(), + rect: [rect.left, rect.top, rect.width, rect.height], + insideOuter: outer.contains(placed), + tone: getComputedStyle(placed.querySelector('p')!).color, + background: getComputedStyle(placed).backgroundColor, + layersOpen: [outer, inner].map(layer => layer.matches(':popover-open')), + }; + }, ATTRIBUTE); + expect(result).not.toBeNull(); + expect(result!.layersOpen).toEqual([false, false]); + expect(result!.open).toBe(true); + // Drawn where the inner layer was: not a 0 x 0 box in a hidden layer. + expect(result!.visible).toBe(true); + expect(result!.rect).toEqual([40, 360, 280, 200]); + expect(result!.insideOuter).toBe(false); + // What the copy inherited inside the outer layer, outside it: its custom + // properties, and its scheme for `light-dark()`. + expect(result!.tone).toBe('rgb(10, 20, 30)'); + expect(result!.background).toBe('rgb(31, 31, 34)'); +}); + +test('when the close of the layer around it closes it too, its copy stays above that layer\u2019s copy', async ({ + page, +}) => { + await open(page); + const result = await page.evaluate(async attribute => { + const outer = document.createElement('div'); + outer.setAttribute('popover', 'auto'); + const inner = document.createElement('div'); + inner.setAttribute('popover', 'auto'); + // Over part of the outer layer, as a menu over its Popover. + inner.style.setProperty('top', '200px'); + inner.style.setProperty('background', 'rgb(200, 30, 30)'); + outer.append(inner); + document.body.append(outer); + outer.showPopover(); + inner.showPopover(); + const placed = new Map(); + for (const layer of [outer, inner]) { + layer.addEventListener( + 'beforetoggle', + event => { + if (event.newState === 'closed') { + const copy = window.ExitCopy.placeLayerExitCopy(layer, attribute); + if (copy != null) { + placed.set(layer, copy); + } + } + }, + {once: true}, + ); + } + // The browser closes the inner layer first, then the outer one. + outer.hidePopover(); + // A refused show opens the copies before the next frame paints. + await new Promise(resolve => requestAnimationFrame(resolve)); + const innerCopy = placed.get(inner); + const outerCopy = placed.get(outer); + if (innerCopy == null || outerCopy == null) { + return null; + } + // Hit testing finds the topmost box once the copies take part in it. + for (const copy of [innerCopy, outerCopy]) { + copy.removeAttribute('inert'); + copy.style.setProperty('pointer-events', 'auto'); + } + const hit = document.elementFromPoint(100, 260); + return { + open: [innerCopy, outerCopy].map(copy => copy.matches(':popover-open')), + innerOnTop: hit != null && innerCopy.contains(hit), + outerUnder: document + .elementsFromPoint(100, 260) + .some(element => outerCopy.contains(element)), + }; + }, ATTRIBUTE); + expect(result).not.toBeNull(); + expect(result!.open).toEqual([true, true]); + expect(result!.outerUnder).toBe(true); + expect(result!.innerOnTop).toBe(true); +}); + +test('a second copy for the same layer replaces the first; another layer\u2019s copy stays', async ({ + page, +}) => { + await open(page); + const result = await page.evaluate(attribute => { + const layer = document.getElementById('layer') as HTMLElement; + const other = document.getElementById('other') as HTMLElement; + layer.showPopover(); + other.showPopover(); + const otherCopy = window.ExitCopy.placeLayerExitCopy(other, attribute); + const first = window.ExitCopy.placeLayerExitCopy(layer, attribute); + const second = window.ExitCopy.placeLayerExitCopy(layer, attribute); + return { + first: first?.isConnected, + second: second?.isConnected && second.matches(':popover-open'), + other: otherCopy?.isConnected && otherCopy.matches(':popover-open'), + copies: document.querySelectorAll(`[${attribute}]`).length, + }; + }, ATTRIBUTE); + expect(result).toEqual({first: false, second: true, other: true, copies: 2}); +}); diff --git a/packages/core/src/Layer/layerExitCopy.test.ts b/packages/core/src/Layer/layerExitCopy.test.ts new file mode 100644 index 0000000000000..035384cbbb35f --- /dev/null +++ b/packages/core/src/Layer/layerExitCopy.test.ts @@ -0,0 +1,574 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file layerExitCopy.test.ts + * @input vitest (jsdom), layerExitCopy + * @output Checks the static copy a closing layer leaves for its close to + * play on. It is out of reach and out of the accessibility tree, with no + * ids or form names. It is only in the top layer: hidden until a refused + * show succeeds, and none without the popover API or past the copy cap. It + * sits on the layer's layout box with fractions, and with the transform and + * opacity it was drawn with. No keyframes or transitions replay, there is + * one copy per layer, and it is scrolled where the layer was. + * @position Testing; the browser proofs are in + * __tests__/layerExitCopy.interaction.browser.spec.ts + */ + +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {placeLayerExitCopy} from './layerExitCopy'; + +const BOX = {left: 41, top: 204, width: 320, height: 253}; +const ATTRIBUTE = 'data-test-exit'; + +/** A layer drawn on BOX (jsdom has no layout). */ +function layer(): HTMLElement { + const host = document.createElement('section'); + document.body.appendChild(host); + const element = document.createElement('div'); + element.id = 'layer'; + element.setAttribute('popover', 'auto'); + element.style.setProperty('position-anchor', '--trigger'); + element.style.setProperty('scale', '0.5 0.4'); + element.style.setProperty('opacity', '0.3'); + element.style.setProperty('transition', 'opacity 1s'); + element.innerHTML = + ''; + host.appendChild(element); + element.getBoundingClientRect = () => ({ + ...BOX, + x: BOX.left, + y: BOX.top, + right: BOX.left + BOX.width, + bottom: BOX.top + BOX.height, + toJSON: () => ({}), + }); + // Its layout box, which a fixed layer's offset box reports in viewport px. + for (const [name, value] of [ + ['offsetLeft', BOX.left], + ['offsetTop', BOX.top], + ['offsetWidth', BOX.width], + ['offsetHeight', BOX.height], + ] as const) { + Object.defineProperty(element, name, {configurable: true, value}); + } + return element; +} + +describe('placeLayerExitCopy', () => { + const originalShow = Object.getOwnPropertyDescriptor( + HTMLElement.prototype, + 'showPopover', + ); + /** The popover API, stood in for (jsdom has none), or taken away. */ + const popoverApi = (present: boolean) => { + if (present) { + const show = vi.fn(); + Object.defineProperty(HTMLElement.prototype, 'showPopover', { + configurable: true, + writable: true, + value: show, + }); + return show; + } + Reflect.deleteProperty(HTMLElement.prototype, 'showPopover'); + return null; + }; + afterEach(() => { + if (originalShow == null) { + Reflect.deleteProperty(HTMLElement.prototype, 'showPopover'); + } else { + Object.defineProperty(HTMLElement.prototype, 'showPopover', originalShow); + } + vi.restoreAllMocks(); + document.body.innerHTML = ''; + }); + + const place = (element: HTMLElement) => { + const copy = placeLayerExitCopy(element, ATTRIBUTE); + if (copy == null) { + throw new Error('no copy'); + } + return copy; + }; + + it('puts a static copy right after the layer, out of reach and out of the accessibility tree', () => { + popoverApi(true); + const element = layer(); + const copy = place(element); + expect(copy.previousElementSibling).toBe(element); + expect(copy.hasAttribute(ATTRIBUTE)).toBe(true); + expect(copy.getAttribute('aria-hidden')).toBe('true'); + expect(copy.hasAttribute('inert')).toBe(true); + expect(copy.id).toBe(''); + expect(copy.querySelectorAll('[id]')).toHaveLength(0); + // The content is the layer's, classes and all. + expect(copy.querySelector('.list')?.textContent).toBe('One'); + expect(copy.style.getPropertyValue('pointer-events')).toBe('none'); + }); + + it('lays the copy of a layer inside other layers after the outermost one, with what it inherited there', () => { + popoverApi(true); + const sheet = document.createElement('style'); + sheet.textContent = + '#layer { --menu-tone: rgb(1, 2, 3); color-scheme: dark; }'; + document.head.append(sheet); + const element = layer(); + const host = element.parentElement as HTMLElement; + const outer = document.createElement('div'); + outer.setAttribute('popover', 'auto'); + const inner = document.createElement('div'); + inner.setAttribute('popover', 'manual'); + host.append(outer); + outer.append(inner); + inner.append(element); + const copy = place(element); + sheet.remove(); + // Outside both: a closing layer around it would hide it. + expect(copy.parentElement).toBe(host); + expect(copy.previousElementSibling).toBe(outer); + // The copy has no id, so only the written values carry the tone and the + // scheme. + expect(copy.style.getPropertyValue('--menu-tone')).toBe('rgb(1, 2, 3)'); + expect(copy.style.getPropertyValue('color-scheme')).toBe('dark'); + }); + + it('takes the copy out of every form and radio group, so the live selection stays', () => { + popoverApi(true); + const element = layer(); + element.insertAdjacentHTML( + 'beforeend', + '', + ); + const live = element.querySelector('input[value="m"]')!; + const copy = place(element); + expect(copy.querySelectorAll('[name]')).toHaveLength(0); + // Every cloned control names a form that cannot exist, so none has an + // owner, whatever the copy stands inside. + expect( + [...copy.querySelectorAll('input')].map(node => + node.getAttribute('form'), + ), + ).toEqual(['', '', '']); + expect(live.checked).toBe(true); + expect(live.getAttribute('name')).toBe('size'); + }); + + it('leaves a form around the layer valid while the copy stands in it', () => { + popoverApi(true); + const element = layer(); + const form = document.createElement('form'); + element.parentElement!.append(form); + form.append(element); + element.insertAdjacentHTML( + 'beforeend', + '', + ); + // The live layer's own fields are the form's while it is open. + expect(form.checkValidity()).toBe(false); + const copy = place(element); + // The copy stands right after the layer, so inside the form; its + // controls belong to no form, and the live fields are unchanged. + expect(copy.closest('form')).toBe(form); + expect([...form.elements]).toHaveLength(3); + for (const node of copy.querySelectorAll('input, select, textarea')) { + expect((node as HTMLInputElement).form).toBeNull(); + } + }); + + it('keeps one copy per layer: a second takes only that layer\u2019s first away', () => { + popoverApi(true); + const element = layer(); + // Another layer beside it, closing too, with its own copy. + const other = layer(); + element.parentElement!.append(other); + const otherCopy = place(other); + const first = place(element); + const second = place(element); + expect(first.isConnected).toBe(false); + expect(second.isConnected).toBe(true); + expect(otherCopy.isConnected).toBe(true); + expect(document.querySelectorAll(`[${ATTRIBUTE}]`)).toHaveLength(2); + }); + + it('stands on the layer\u2019s box, free of the live layer\u2019s anchoring, drawn with its inline scale and opacity', () => { + popoverApi(true); + const element = layer(); + const copy = place(element); + expect(copy.style.getPropertyValue('position')).toBe('fixed'); + expect(copy.style.getPropertyValue('left')).toBe('41px'); + expect(copy.style.getPropertyValue('top')).toBe('204px'); + expect(copy.style.getPropertyValue('width')).toBe('320px'); + expect(copy.style.getPropertyValue('height')).toBe('253px'); + for (const property of ['position-anchor', 'transition']) { + expect(copy.style.getPropertyValue(property), property).toBe(''); + } + // A layer drawn with these and no animation closes from a copy drawn the + // same, not at full size and full opacity. + expect(copy.style.getPropertyValue('scale')).toBe('0.5 0.4'); + expect(copy.style.getPropertyValue('opacity')).toBe('0.3'); + expect(copy.style.getPropertyValue('animation-name')).toBe('none'); + // No alignment against the anchor it left (a phone menu's anchor-center). + expect(copy.style.getPropertyValue('justify-self')).toBe('normal'); + expect(copy.style.getPropertyValue('align-self')).toBe('normal'); + }); + + it('holds where a layer still entering was drawn: its layout box with fractions, with the transform it was drawn with', () => { + popoverApi(true); + const element = layer(); + // Mid-entrance: drawn at half size about its top-left corner, at a + // fractional position its whole-pixel offsets round away. + const laidOut = {left: 40.391, top: 120.594, width: 320.4, height: 253}; + const drawn = {...laidOut, width: 160.2, height: 126.5}; + // jsdom keeps no `!important`: the read's override shows as `none`. + const settled = () => element.style.getPropertyValue('scale') === 'none'; + element.getBoundingClientRect = () => { + const box = settled() ? laidOut : drawn; + return { + ...box, + x: box.left, + y: box.top, + right: box.left + box.width, + bottom: box.top + box.height, + toJSON: () => ({}), + }; + }; + for (const [name, value] of [ + ['offsetLeft', 40], + ['offsetTop', 121], + ['offsetWidth', 320], + ['offsetHeight', 253], + ] as const) { + Object.defineProperty(element, name, {configurable: true, value}); + } + element.getAnimations = () => + [ + {effect: {target: element, pseudoElement: null}}, + ] as unknown as Animation[]; + const presented: Record = { + scale: '0.5', + 'transform-origin': '0px 0px', + width: '320.4px', + height: '253px', + 'box-sizing': 'border-box', + }; + const original = window.getComputedStyle.bind(window); + vi.spyOn(window, 'getComputedStyle').mockImplementation((node, pseudo) => + node === element + ? ({ + getPropertyValue: (property: string) => + property === 'scale' && settled() + ? 'none' + : (presented[property] ?? ''), + transitionProperty: 'all', + transitionDuration: '0s', + } as unknown as CSSStyleDeclaration) + : original(node, pseudo), + ); + const copy = place(element); + // Laid out where the layer is, at its used size, fractions kept... + expect(copy.style.getPropertyValue('left')).toBe('40.391px'); + expect(copy.style.getPropertyValue('top')).toBe('120.594px'); + expect(copy.style.getPropertyValue('width')).toBe('320.4px'); + expect(copy.style.getPropertyValue('height')).toBe('253px'); + // ...and drawn as it was drawn. + expect(copy.style.getPropertyValue('scale')).toBe('0.5'); + expect(copy.style.getPropertyValue('transform-origin')).toBe('0px 0px'); + // The read leaves the live layer's own transform as it was. + expect(element.style.getPropertyValue('scale')).toBe('0.5 0.4'); + }); + + it('shows the copy only in the top layer, as a manual popover, with no z-index', () => { + const show = popoverApi(true)!; + const element = layer(); + const copy = place(element); + expect(copy.getAttribute('popover')).toBe('manual'); + expect(show).toHaveBeenCalledTimes(1); + expect(show.mock.contexts[0]).toBe(copy); + expect(copy.style.getPropertyValue('z-index')).toBe(''); + expect(copy.style.getPropertyValue('display')).toBe(''); + // The UA's popover inset does not over-constrain the box. + expect(copy.style.getPropertyValue('right')).toBe('auto'); + expect(copy.style.getPropertyValue('bottom')).toBe('auto'); + }); + + it('waits, hidden, when the browser refuses the show during the closing toggle, and shows once it is over', async () => { + const show = popoverApi(true)!; + // Android Chromium 158 refuses a show inside another popover's toggle. + show.mockImplementationOnce(() => { + throw new DOMException( + 'Invalid to show a popover during another show operation', + 'InvalidStateError', + ); + }); + const element = layer(); + let copy: HTMLElement | null = null; + expect(() => { + copy = place(element); + }).not.toThrow(); + // Not shown yet, and nothing stands in for the top layer: the UA keeps a + // popover that is not open out of view. + expect(copy!.isConnected).toBe(true); + expect(copy!.style.getPropertyValue('display')).toBe(''); + expect(copy!.style.getPropertyValue('z-index')).toBe(''); + expect(show).toHaveBeenCalledTimes(1); + // The script that closed the layer is over: shown. + await Promise.resolve(); + expect(show).toHaveBeenCalledTimes(2); + expect(copy!.isConnected).toBe(true); + }); + + it('tries again in the next frame, and takes the copy away if the browser still refuses', async () => { + const show = popoverApi(true)!; + show.mockImplementation(() => { + throw new DOMException('refused', 'InvalidStateError'); + }); + const frames: FrameRequestCallback[] = []; + vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { + frames.push(callback); + return frames.length; + }); + const element = layer(); + const copy = place(element); + await Promise.resolve(); + expect(frames).toHaveLength(1); + frames[0](0); + expect(show).toHaveBeenCalledTimes(3); + expect(copy.isConnected).toBe(false); + }); + + it('does not reach for the top layer for a copy already taken away', async () => { + const show = popoverApi(true)!; + show.mockImplementationOnce(() => { + throw new DOMException('refused', 'InvalidStateError'); + }); + const copy = place(layer()); + copy.remove(); + await Promise.resolve(); + expect(show).toHaveBeenCalledTimes(1); + }); + + it('places no copy without the popover API: the close is immediate', () => { + popoverApi(false); + const element = layer(); + expect(placeLayerExitCopy(element, ATTRIBUTE)).toBeNull(); + expect(document.querySelector(`[${ATTRIBUTE}]`)).toBeNull(); + }); + + it('starts as the layer looks: values its running animations hold are written onto the copy', () => { + popoverApi(true); + const element = layer(); + const dialog = element.querySelector('[role="dialog"]')!; + const list = element.querySelector('.list')!; + // A compositor curve on the layer and one on its dialog; the list has none. + element.getAnimations = () => + [element, dialog].map(target => ({ + effect: {target, pseudoElement: null}, + })) as unknown as Animation[]; + const presented = new Map>([ + [element, {opacity: '0.7', 'transform-origin': '160px 0px'}], + [dialog, {translate: '0px 12px', opacity: '0.5'}], + ]); + const original = window.getComputedStyle.bind(window); + vi.spyOn(window, 'getComputedStyle').mockImplementation((node, pseudo) => { + const values = presented.get(node); + if (values == null) { + return original(node, pseudo); + } + return { + getPropertyValue: (property: string) => values[property] ?? '', + } as CSSStyleDeclaration; + }); + const copy = place(element); + expect(copy.style.getPropertyValue('opacity')).toBe('0.7'); + expect(copy.style.getPropertyValue('transform-origin')).toBe('160px 0px'); + const copyDialog = copy.querySelector('[role="dialog"]')!; + expect(copyDialog.style.getPropertyValue('translate')).toBe('0px 12px'); + expect(copyDialog.style.getPropertyValue('opacity')).toBe('0.5'); + // Nothing is written where nothing runs. + expect( + copy.querySelector('.list')!.getAttribute('style'), + ).toBe(list.getAttribute('style')); + }); + + it.each(['iframe', 'object', 'embed', 'video', 'audio'])( + 'copies a %s with no source, so nothing loads or plays again', + tag => { + popoverApi(true); + const element = layer(); + const live = document.createElement(tag); + live.className = 'media'; + live.setAttribute('src', 'about:blank'); + live.setAttribute('data', 'about:blank'); + live.setAttribute('autoplay', ''); + element.querySelector('.list')!.appendChild(live); + const copy = place(element); + const copied = copy.querySelector('.list > .media')!; + expect(copied.localName).toBe(tag); + for (const name of ['src', 'data', 'autoplay']) { + expect(copied.hasAttribute(name)).toBe(false); + } + // The live one is untouched. + expect(element.querySelector(tag)).toBe(live); + expect(live.getAttribute('src')).toBe('about:blank'); + }, + ); + + it('places no copy for content holding a canvas that reads back empty: the close is immediate', () => { + popoverApi(true); + const element = layer(); + const canvas = document.createElement('canvas'); + canvas.width = 4; + canvas.height = 4; + element.querySelector('.list')!.appendChild(canvas); + // A canvas whose pixels read back empty: a WebGL one without + // preserveDrawingBuffer, or a tainted one. + vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ + drawImage: () => {}, + getImageData: () => ({data: new Uint8ClampedArray(64)}), + } as unknown as CanvasRenderingContext2D); + expect(placeLayerExitCopy(element, ATTRIBUTE)).toBeNull(); + expect(document.querySelector(`[${ATTRIBUTE}]`)).toBeNull(); + }); + + it('carries no test ids, label targets or autofocus, so a query or the focus finds only the live layer', () => { + popoverApi(true); + const element = layer(); + element.setAttribute('data-testid', 'menu'); + const label = document.createElement('label'); + label.htmlFor = 'live-field'; + const field = document.createElement('input'); + field.id = 'live-field'; + field.autofocus = true; + field.setAttribute('data-testid', 'field'); + element.querySelector('.list')!.append(label, field); + const copy = place(element); + expect(copy.hasAttribute('data-testid')).toBe(false); + expect(copy.querySelector('[data-testid]')).toBeNull(); + expect(copy.querySelector('label')!.hasAttribute('for')).toBe(false); + expect(copy.querySelector('input')!.hasAttribute('autofocus')).toBe(false); + expect(document.querySelectorAll('[data-testid="field"]')).toHaveLength(1); + }); + + it('restores scroll positions at once, whatever the scroller\u2019s own scroll-behavior', () => { + popoverApi(true); + const element = layer(); + const list = element.querySelector('.list')!; + list.style.setProperty('scroll-behavior', 'smooth'); + list.scrollTop = 120; + const original = Object.getOwnPropertyDescriptor( + Element.prototype, + 'scrollTo', + ); + const scrollTo = vi.fn(); + Object.defineProperty(Element.prototype, 'scrollTo', { + configurable: true, + writable: true, + value: scrollTo, + }); + try { + const copy = place(element); + expect(scrollTo).toHaveBeenCalledWith({ + top: 120, + left: 0, + behavior: 'instant', + }); + expect(scrollTo.mock.contexts).toContain(copy.querySelector('.list')); + } finally { + if (original == null) { + Reflect.deleteProperty(Element.prototype, 'scrollTo'); + } else { + Object.defineProperty(Element.prototype, 'scrollTo', original); + } + } + }); + + it('keeps scrolled content where it was scrolled to', () => { + popoverApi(true); + const element = layer(); + const list = element.querySelector('.list')!; + list.scrollTop = 120; + const copy = place(element); + expect(copy.querySelector('.list')!.scrollTop).toBe(120); + }); + + it('keeps a scrolling layer\u2019s own overflow and its own scroll position', () => { + popoverApi(true); + const element = layer(); + element.style.setProperty('overflow-y', 'auto'); + element.scrollTop = 80; + const copy = place(element); + expect(copy.style.getPropertyValue('overflow-y')).toBe('auto'); + expect(copy.scrollTop).toBe(80); + }); + + it('takes a form-associated custom element out of every form, as it does a native control', () => { + popoverApi(true); + if (customElements.get('x-exit-form-field') == null) { + customElements.define( + 'x-exit-form-field', + class extends HTMLElement { + static formAssociated = true; + }, + ); + } + const element = layer(); + element + .querySelector('.list')! + .insertAdjacentHTML( + 'beforeend', + '', + ); + const copy = place(element); + expect(copy.querySelector('x-exit-form-field')?.getAttribute('form')).toBe( + '', + ); + expect(copy.querySelector('x-exit-plain')?.hasAttribute('form')).toBe( + false, + ); + }); + + it('keeps its descendants\u2019 keyframes from starting again, and writes nothing where none are set', () => { + popoverApi(true); + const element = layer(); + element + .querySelector('[role="dialog"]')! + .style.setProperty('animation-name', 'rise'); + const copy = place(element); + expect( + copy + .querySelector('[role="dialog"]')! + .style.getPropertyValue('animation-name'), + ).toBe('none'); + expect( + copy.querySelector('.list')!.getAttribute('style'), + ).toBe(element.querySelector('.list')!.getAttribute('style')); + }); + + it('stops the transitions the layer and its descendants run, so none replays its entry in the copy', () => { + popoverApi(true); + const element = layer(); + element.style.setProperty('transition-duration', '0.2s'); + element + .querySelector('[role="dialog"]')! + .style.setProperty('transition-duration', '0s, 0.3s'); + const copy = place(element); + expect(copy.style.getPropertyValue('transition')).toBe('none'); + expect( + copy + .querySelector('[role="dialog"]')! + .style.getPropertyValue('transition'), + ).toBe('none'); + // Nothing is written where no transition runs. + expect( + copy.querySelector('.list')!.getAttribute('style'), + ).toBe(element.querySelector('.list')!.getAttribute('style')); + }); + + it('places no copy for content past the copy cap, as the swap does: the close is immediate', () => { + popoverApi(true); + const element = layer(); + element.querySelector('.list')!.innerHTML = ''.repeat(1600); + expect(placeLayerExitCopy(element, ATTRIBUTE)).toBeNull(); + expect(document.querySelector(`[${ATTRIBUTE}]`)).toBeNull(); + }); +}); diff --git a/packages/core/src/Layer/layerExitCopy.ts b/packages/core/src/Layer/layerExitCopy.ts new file mode 100644 index 0000000000000..571cd4e19cfa2 --- /dev/null +++ b/packages/core/src/Layer/layerExitCopy.ts @@ -0,0 +1,315 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file layerExitCopy.ts + * @input A layer's popover element as it closes, and Core's shared inert copy + * (motion/transientCopy.ts) + * @output Exports `placeLayerExitCopy`, a static, inert copy of the layer in + * the top layer for a touch presentation's close to play on, and + * `LayerExitBox` + * @position Layer runtime helper for a touch presentation that animates a + * popover out: the one exit copy a layer may have + * + * SYNC: When modified, update: + * - /packages/core/src/Layer/layerExitCopy.test.ts + * - /packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts + * - /docs/architecture/layer-runtime.md + */ + +import { + inertCopy, + isCopyable, + keepInherited, + restoreScrollOffsets, +} from '../motion/transientCopy'; +import {settledBox} from './settledBox'; + +/** A box in viewport px. */ +export interface LayerExitBox { + left: number; + top: number; + width: number; + height: number; +} + +/** + * Properties a running animation may hold, which the copy takes from what + * the layer presents. + */ +const PRESENTED_PROPERTIES = [ + 'translate', + 'rotate', + 'scale', + 'transform', + 'transform-origin', + 'opacity', +] as const; + +/** Inline properties the copy must not keep from the live layer. */ +const LIVE_ONLY_PROPERTIES = [ + 'position-anchor', + 'position-area', + 'position-try-fallbacks', + 'inset', + 'right', + 'bottom', + 'transition', +] as const; + +/** + * Writes onto `copy` what `element` and its subtree present through running + * animations: the copy starts as the layer looks, not as its inline styles + * say. + */ +function commitPresented(element: HTMLElement, copy: HTMLElement): void { + const view = element.ownerDocument.defaultView; + if (view == null || typeof element.getAnimations !== 'function') { + return; + } + const animated = new Set(); + for (const animation of element.getAnimations({subtree: true})) { + const effect = animation.effect as KeyframeEffect | null; + if (effect?.target != null && effect.pseudoElement == null) { + animated.add(effect.target); + } + } + if (animated.size === 0) { + return; + } + const sources = [element, ...element.querySelectorAll('*')]; + const copies = [copy, ...copy.querySelectorAll('*')]; + sources.forEach((source, index) => { + const target = copies[index]; + if (!animated.has(source) || !(target instanceof view.Element)) { + return; + } + const computed = view.getComputedStyle(source); + const {style} = target as HTMLElement; + for (const property of PRESENTED_PROPERTIES) { + style.setProperty(property, computed.getPropertyValue(property)); + } + }); +} + +/** The outermost layer around `element` in its own tree, if any. */ +function outermostLayer(element: HTMLElement): HTMLElement | null { + let outer: HTMLElement | null = null; + for ( + let node = element.parentElement; + node != null; + node = node.parentElement + ) { + if (node.matches('[popover], dialog')) { + outer = node; + } + } + return outer; +} + +/** Each layer's copy: placing another for the same layer replaces it. */ +const copies = new WeakMap(); + +/** Layers whose copies may still stand. */ +const copiedLayers = new Set(); + +/** + * Shows the copies of layers inside `element` again, so they stay above the + * copy just shown for it. Those layers were drawn above it. + */ +function raiseInnerCopies(element: HTMLElement): void { + const inner: HTMLElement[] = []; + for (const layer of copiedLayers) { + const copy = copies.get(layer); + if (copy?.isConnected !== true) { + copiedLayers.delete(layer); + } else if ( + layer !== element && + element.contains(layer) && + copy.matches(':popover-open') + ) { + inner.push(layer); + } + } + // Outer layers first, so the innermost copy ends on top. + inner.sort((a, b) => (a.contains(b) ? -1 : b.contains(a) ? 1 : 0)); + for (const layer of inner) { + const copy = copies.get(layer); + if (copy != null) { + copy.hidePopover(); + copy.showPopover(); + restoreScrollOffsets(copy); + } + } +} + +/** A duration list with any part above zero. */ +const hasDuration = (value: string): boolean => + value.split(',').some(part => parseFloat(part) > 0); + +/** + * Where `element` is laid out, in viewport px, fractions kept. It is the box + * without the transform a presentation in progress draws it with; the copy + * carries that transform itself. + */ +function layoutBox(element: HTMLElement): LayerExitBox { + const {left, top, width, height} = settledBox(element); + return {left, top, width, height}; +} + +/** + * Copies `element` into a static box where it is drawn, marked with + * `attribute`. It inserts the copy after the outermost layer around the + * element, or after the element when no layer encloses it. It shows the copy + * in the top layer. Returns null where there is no top layer to show it in (no + * popover API). It also returns null for content past the copy cap, or + * holding a canvas that reads back empty. The close is then immediate. + * + * The browser hides a popover the moment it closes (a pick, Escape, its own + * light dismiss). A close that has to stay on screen plays on this copy, + * taken as the popover closes. It has the same place, size, inherited theme + * and look, values its running animations hold included. A clone keeps only + * inline styles, and a compositor curve holds its value outside them. It is + * laid out on the layer's own box and carries the transform the layer was + * drawn with. So a copy taken mid-entrance holds where it was drawn. It + * keeps the layer's overflow and every scroll position, the layer's own + * included. + * + * It is Core's shared inert copy (`inertCopy`). It has no ids, test ids, form + * names or label targets, and no form owner. A cloned checked radio then + * cannot take the live group's selection, and a named field cannot submit. + * It is `inert`, hidden from assistive technology, and out of pointer reach. + * Its frames and media load nothing, and a canvas shows its pixels. Content + * holding a canvas that reads back empty gets no copy: the close is then + * immediate. Its descendants' keyframe animations do not start again. A + * layer has one copy: placing another for the same layer takes the previous + * one away. + * + * It is shown only in the top layer, as a manual popover, so a clipping, + * transformed or sticky ancestor neither cuts nor moves it. A fixed box or a + * larger `z-index` is no substitute. Where the browser refuses the show + * during the closing popover's own toggle (Chromium 150 and later), the copy + * waits, hidden. It shows once the toggle is over: after the script that + * closed the layer or, failing that, in the next frame before it paints. Its + * owner animates it and removes it when its exit ends; nothing on the + * main thread runs per frame while it moves. + */ +export function placeLayerExitCopy( + element: HTMLElement, + attribute: string, +): HTMLElement | null { + const view = element.ownerDocument.defaultView; + if (view == null || typeof element.showPopover !== 'function') { + return null; + } + // One copy per layer: a close during a close replaces it. + copies.get(element)?.remove(); + // Past the copy cap, or with a canvas that reads back empty, there is no + // copy, so the close is immediate. + if (!isCopyable(element)) { + return null; + } + const box = layoutBox(element); + const copy = inertCopy(element); + if (copy == null) { + return null; + } + copy.setAttribute(attribute, ''); + copy.setAttribute('popover', 'manual'); + const {style} = copy; + for (const property of LIVE_ONLY_PROPERTIES) { + style.removeProperty(property); + } + commitPresented(element, copy); + // On the layer's box: in the top layer the viewport is its containing + // block. No alignment against an anchor or the viewport: a phone menu + // centered on its trigger with `anchor-center` would otherwise shift. The + // UA's popover inset would over-constrain the box, and win in RTL. + style.setProperty('position', 'fixed'); + style.setProperty('margin', '0'); + style.setProperty('left', `${box.left}px`); + style.setProperty('top', `${box.top}px`); + style.setProperty('right', 'auto'); + style.setProperty('bottom', 'auto'); + style.setProperty('width', `${box.width}px`); + style.setProperty('height', `${box.height}px`); + style.setProperty('box-sizing', 'border-box'); + style.setProperty('justify-self', 'normal'); + style.setProperty('align-self', 'normal'); + style.setProperty('animation-name', 'none'); + const layerStyle = view.getComputedStyle(element); + if (hasDuration(layerStyle.getPropertyValue('transition-duration'))) { + style.setProperty('transition', 'none'); + } + // A cloned descendant restarts its keyframes from the first frame, and a + // transition with a starting style replays its entry. Stop both; + // `commitPresented` already wrote what running ones held. + const liveNodes = element.querySelectorAll('*'); + copy.querySelectorAll('*').forEach((node, index) => { + const live = liveNodes[index]; + if ( + live == null || + !(node instanceof view.HTMLElement || node instanceof view.SVGElement) + ) { + return; + } + const liveStyle = view.getComputedStyle(live); + const name = liveStyle.getPropertyValue('animation-name'); + if (name !== '' && name !== 'none') { + node.style.setProperty('animation-name', 'none'); + } + if (hasDuration(liveStyle.getPropertyValue('transition-duration'))) { + node.style.setProperty('transition', 'none'); + } + }); + // The layer's own overflow, so a layer that scrolls its content keeps its + // clip. A popover's user-agent style scrolls as well. + style.setProperty('overflow-x', layerStyle.getPropertyValue('overflow-x')); + style.setProperty('overflow-y', layerStyle.getPropertyValue('overflow-y')); + // A layer inside another layer that closes in the same step would leave its + // copy inside a hidden box. The copy goes after the outermost one, with + // what it inherited where it was. + const outer = outermostLayer(element); + if (outer?.parentElement == null) { + element.after(copy); + } else { + outer.after(copy); + keepInherited(copy, outer.parentElement); + } + copies.set(element, copy); + copiedLayers.add(element); + const show = (): boolean => { + try { + copy.showPopover(); + } catch { + return false; + } + // A hidden box keeps no scroll position, so scrolled content, the layer's + // own included, goes back where it was once the copy is shown. + restoreScrollOffsets(copy); + raiseInnerCopies(element); + return true; + }; + const giveUp = () => { + copy.remove(); + if (copies.get(element) === copy) { + copies.delete(element); + copiedLayers.delete(element); + } + }; + if (!show()) { + // Refused during the closing popover's toggle: hidden until it is over. + view.queueMicrotask(() => { + if (!copy.isConnected || show()) { + return; + } + view.requestAnimationFrame(() => { + if (copy.isConnected && !show()) { + giveUp(); + } + }); + }); + } + return copy; +} diff --git a/packages/core/src/Layer/settledBox.ts b/packages/core/src/Layer/settledBox.ts new file mode 100644 index 0000000000000..09b8cdf2d60a2 --- /dev/null +++ b/packages/core/src/Layer/settledBox.ts @@ -0,0 +1,132 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file settledBox.ts + * @input A layer element and its computed transforms + * @output settledBox, the layer's box without the transform an entry + * animation applies, with fractions + * @position Layer runtime helper; useLayer.tsx reads it for the anchor + * check, and layerExitCopy.ts for the copy's box + */ + +const TRANSFORM_PROPERTIES = ['transform', 'translate', 'scale', 'rotate']; + +function hasTransform(style: CSSStyleDeclaration): boolean { + return TRANSFORM_PROPERTIES.some(name => { + const value = style.getPropertyValue(name); + return value !== '' && value !== 'none'; + }); +} + +/** + * `rect`, the box of an element whose computed style still carries a 2D + * transform, with that transform undone: the transformed box's centre is the + * image of the element's centre, so undoing the transform about its origin on + * that centre gives the untransformed box, at the element's layout size. A + * transform this cannot undo (3D, or a rotation in another unit) leaves `rect` + * as it is. + */ +function untransform( + rect: DOMRect, + layer: HTMLElement, + style: CSSStyleDeclaration, +): DOMRect { + const set = (value: string) => value !== '' && value !== 'none'; + if (typeof DOMMatrix === 'undefined' || layer.offsetWidth <= 0) { + return rect; + } + // The individual transform properties apply before `transform`, in this + // order (CSS Transforms 2). + let matrix = new DOMMatrix(); + if (set(style.translate)) { + const [x = '0', y = '0', z] = style.translate.split(' '); + if (z != null) { + return rect; + } + matrix = matrix.translate(parseFloat(x), parseFloat(y)); + } + if (set(style.rotate)) { + if (!/^-?[\d.]+deg$/.test(style.rotate)) { + return rect; + } + matrix = matrix.rotate(parseFloat(style.rotate)); + } + if (set(style.scale)) { + const [x = '1', y = x, z] = style.scale.split(' '); + if (z != null) { + return rect; + } + matrix = matrix.scale(parseFloat(x), parseFloat(y)); + } + if (set(style.transform)) { + matrix = matrix.multiply(new DOMMatrix(style.transform)); + } + if (!matrix.is2D) { + return rect; + } + const [originX = 0, originY = 0] = style.transformOrigin + .split(' ') + .map(value => parseFloat(value)); + const width = layer.offsetWidth; + const height = layer.offsetHeight; + const centre = matrix.transformPoint( + new DOMPoint(width / 2 - originX, height / 2 - originY), + ); + const left = rect.left + rect.width / 2 - centre.x - originX; + const top = rect.top + rect.height / 2 - centre.y - originY; + return new DOMRect(left, top, width, height); +} + +/** + * The layer's box where its position option put it, without the transform an + * entry animation (or anything else) applies to it: a Tooltip enters from a + * few pixels toward its trigger, scaled down, so the transformed box of a + * tooltip that fits beside its trigger can read as covering it while it + * enters. The layer's transforms are overridden with `none !important`, which + * outranks an animation, for this one read and then restored, in the same + * task: no frame paints in between and the animation keeps running. Where the + * engine still applies an animated transform under that override (WebKit), + * the read box has that transform undone instead (`untransform`). A layer + * that transitions a transform property is not overridden, since restoring the + * value would start that transition; its box has its transform undone. + */ +export function settledBox(layer: HTMLElement): DOMRect { + const view = layer.ownerDocument.defaultView; + const style = view?.getComputedStyle(layer); + if (style == null || !hasTransform(style)) { + return layer.getBoundingClientRect(); + } + const transitions = style.transitionProperty.split(',').map(p => p.trim()); + const durations = style.transitionDuration.split(',').map(parseFloat); + const transitioned = transitions.some( + (name, index) => + (name === 'all' || TRANSFORM_PROPERTIES.includes(name)) && + (durations[index % durations.length] ?? 0) > 0, + ); + if (transitioned) { + return untransform(layer.getBoundingClientRect(), layer, style); + } + const saved = TRANSFORM_PROPERTIES.map( + name => + [ + name, + layer.style.getPropertyValue(name), + layer.style.getPropertyPriority(name), + ] as const, + ); + for (const name of TRANSFORM_PROPERTIES) { + layer.style.setProperty(name, 'none', 'important'); + } + const box = layer.getBoundingClientRect(); + const under = view?.getComputedStyle(layer); + const settled = + under != null && hasTransform(under) ? untransform(box, layer, under) : box; + for (const [name, value, priority] of saved) { + if (value === '') { + layer.style.removeProperty(name); + } else { + layer.style.setProperty(name, value, priority); + } + } + return settled; +} diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx index 5e30b548c90e5..23d6423b11b8a 100644 --- a/packages/core/src/Layer/useLayer.tsx +++ b/packages/core/src/Layer/useLayer.tsx @@ -56,6 +56,7 @@ import { } from './popoverOperations'; import {preserveAnimations} from './preserveAnimations'; import {useLayerContext} from './LayerContext'; +import {settledBox} from './settledBox'; import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import {overlayPaddingReset} from '../Layout/overlayPaddingReset.stylex'; @@ -481,74 +482,6 @@ function placeAfresh(layer: HTMLElement): void { }); } -const TRANSFORM_PROPERTIES = ['transform', 'translate', 'scale', 'rotate']; - -function hasTransform(style: CSSStyleDeclaration): boolean { - return TRANSFORM_PROPERTIES.some(name => { - const value = style.getPropertyValue(name); - return value !== '' && value !== 'none'; - }); -} - -/** - * `rect`, the box of an element whose computed style still carries a 2D - * transform, with that transform undone: the transformed box's centre is the - * image of the element's centre, so undoing the transform about its origin on - * that centre gives the untransformed box, at the element's layout size. A - * transform this cannot undo (3D, or a rotation in another unit) leaves `rect` - * as it is. - */ -function untransform( - rect: DOMRect, - layer: HTMLElement, - style: CSSStyleDeclaration, -): DOMRect { - const set = (value: string) => value !== '' && value !== 'none'; - if (typeof DOMMatrix === 'undefined' || layer.offsetWidth <= 0) { - return rect; - } - // The individual transform properties apply before `transform`, in this - // order (CSS Transforms 2). - let matrix = new DOMMatrix(); - if (set(style.translate)) { - const [x = '0', y = '0', z] = style.translate.split(' '); - if (z != null) { - return rect; - } - matrix = matrix.translate(parseFloat(x), parseFloat(y)); - } - if (set(style.rotate)) { - if (!/^-?[\d.]+deg$/.test(style.rotate)) { - return rect; - } - matrix = matrix.rotate(parseFloat(style.rotate)); - } - if (set(style.scale)) { - const [x = '1', y = x, z] = style.scale.split(' '); - if (z != null) { - return rect; - } - matrix = matrix.scale(parseFloat(x), parseFloat(y)); - } - if (set(style.transform)) { - matrix = matrix.multiply(new DOMMatrix(style.transform)); - } - if (!matrix.is2D) { - return rect; - } - const [originX = 0, originY = 0] = style.transformOrigin - .split(' ') - .map(value => parseFloat(value)); - const width = layer.offsetWidth; - const height = layer.offsetHeight; - const centre = matrix.transformPoint( - new DOMPoint(width / 2 - originX, height / 2 - originY), - ); - const left = rect.left + rect.width / 2 - centre.x - originX; - const top = rect.top + rect.height / 2 - centre.y - originY; - return new DOMRect(left, top, width, height); -} - /** * The finite animations still running on `layer` and its content. A layer * that fades out keeps running them after the browser hides it, and it stays @@ -567,60 +500,6 @@ function exitAnimations(layer: HTMLElement | null): Animation[] { ); } -/** - * The layer's box where its position option put it, without the transform an - * entry animation (or anything else) applies to it: a Tooltip enters from a - * few pixels toward its trigger, scaled down, so the transformed box of a - * tooltip that fits beside its trigger can read as covering it while it - * enters. The layer's transforms are overridden with `none !important`, which - * outranks an animation, for this one read and then restored, in the same - * task: no frame paints in between and the animation keeps running. Where the - * engine still applies an animated transform under that override (WebKit), - * the read box has that transform undone instead (`untransform`). A layer - * that transitions a transform property is not overridden, since restoring the - * value would start that transition; its box has its transform undone. - */ -function settledBox(layer: HTMLElement): DOMRect { - const view = layer.ownerDocument.defaultView; - const style = view?.getComputedStyle(layer); - if (style == null || !hasTransform(style)) { - return layer.getBoundingClientRect(); - } - const transitions = style.transitionProperty.split(',').map(p => p.trim()); - const durations = style.transitionDuration.split(',').map(parseFloat); - const transitioned = transitions.some( - (name, index) => - (name === 'all' || TRANSFORM_PROPERTIES.includes(name)) && - (durations[index % durations.length] ?? 0) > 0, - ); - if (transitioned) { - return untransform(layer.getBoundingClientRect(), layer, style); - } - const saved = TRANSFORM_PROPERTIES.map( - name => - [ - name, - layer.style.getPropertyValue(name), - layer.style.getPropertyPriority(name), - ] as const, - ); - for (const name of TRANSFORM_PROPERTIES) { - layer.style.setProperty(name, 'none', 'important'); - } - const box = layer.getBoundingClientRect(); - const under = view?.getComputedStyle(layer); - const settled = - under != null && hasTransform(under) ? untransform(box, layer, under) : box; - for (const [name, value, priority] of saved) { - if (value === '') { - layer.style.removeProperty(name); - } else { - layer.style.setProperty(name, value, priority); - } - } - return settled; -} - /** * 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 diff --git a/packages/core/src/motion/animatedLayout.boundary.test.ts b/packages/core/src/motion/animatedLayout.boundary.test.ts index 7e426f5977bcc..aef8bdf66c80f 100644 --- a/packages/core/src/motion/animatedLayout.boundary.test.ts +++ b/packages/core/src/motion/animatedLayout.boundary.test.ts @@ -127,14 +127,17 @@ describe('architecture:react-component-runtime INV12 source boundary', () => { } }); - it("keeps the swap's copy mechanism private to the module", () => { + it("keeps the copy mechanism to the swap and the layer's exit copy", () => { const users = sourceFiles(coreSrc) .filter(path => /from '[./]+(motion\/)?transientCopy'/.test(readFileSync(path, 'utf8')), ) .map(path => relative(coreSrc, path)) .sort(); - expect(users).toEqual(['motion/animatedLayout.ts']); + expect(users).toEqual([ + 'Layer/layerExitCopy.ts', + 'motion/animatedLayout.ts', + ]); }); it('is used only by the hook and the components that adopt it', () => { diff --git a/packages/core/src/motion/transientCopy.test.ts b/packages/core/src/motion/transientCopy.test.ts new file mode 100644 index 0000000000000..0a59559940474 --- /dev/null +++ b/packages/core/src/motion/transientCopy.test.ts @@ -0,0 +1,73 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file transientCopy.test.ts + * @input vitest, inertCopy + * @output Unit coverage for the inert copy's form and anchor-name exclusion + * @position Unit coverage for transientCopy.ts; the exit copy's own cases + * are in Layer/layerExitCopy.test.ts + */ + +import {afterEach, describe, expect, it} from 'vitest'; +import {inertCopy} from './transientCopy'; + +class CopyField extends HTMLElement { + static formAssociated = true; +} +customElements.define('copy-field', CopyField); + +afterEach(() => { + document.body.replaceChildren(); +}); + +describe('inertCopy', () => { + it('gives no copied element an anchor name, so no live anchor has a second element', () => { + const sheet = document.createElement('style'); + sheet.textContent = '.anchored { anchor-name: --row-anchor; }'; + document.head.append(sheet); + const element = document.createElement('div'); + element.style.setProperty('anchor-name', '--menu-anchor'); + element.innerHTML = + ''; + document.body.append(element); + const copy = inertCopy(element); + sheet.remove(); + if (copy == null) { + throw new Error('no copy'); + } + for (const node of [ + copy, + copy.querySelector('input'), + copy.querySelector('b'), + ]) { + expect(node?.style.getPropertyValue('anchor-name')).toBe('none'); + } + // A copied element with no anchor name gets no style written. + expect(copy.querySelector('span')?.getAttribute('style')).toBeNull(); + expect(element.style.getPropertyValue('anchor-name')).toBe('--menu-anchor'); + expect( + element.querySelector('input')?.style.getPropertyValue('anchor-name'), + ).toBe('--field-anchor'); + }); + + it('joins no form when it is laid inside one, nor does a form-associated custom element', () => { + const form = document.createElement('form'); + document.body.append(form); + const element = document.createElement('div'); + element.innerHTML = + ''; + form.append(element); + const copy = inertCopy(element); + if (copy == null) { + throw new Error('no copy'); + } + form.append(copy); + expect(copy.querySelector('input')?.form).toBeNull(); + expect(copy.querySelector('button')?.form).toBeNull(); + expect(copy.querySelector('copy-field')?.getAttribute('form')).toBe(''); + expect(form.checkValidity()).toBe(false); + element.remove(); + // Only the copy's empty required field is left: it must not count. + expect(form.checkValidity()).toBe(true); + }); +}); diff --git a/packages/core/src/motion/transientCopy.ts b/packages/core/src/motion/transientCopy.ts index b060208bd608e..c3765e95ab35c 100644 --- a/packages/core/src/motion/transientCopy.ts +++ b/packages/core/src/motion/transientCopy.ts @@ -3,13 +3,13 @@ /** * @file transientCopy.ts * @input The DOM - * @output Exports `isCopyable`, `inertCopy`, `visiblePartCopy`, `placeOver`, - * `paintedBackground` and `wrapText`: how Core makes, lays out and fades one - * transient copy of old content + * @output Exports `isCopyable`, `inertCopy`, `restoreScrollOffsets`, + * `visiblePartCopy`, `placeOver`, `paintedBackground` and `wrapText`: how + * Core makes, lays out and fades one transient copy of old content * @position Motion foundation, internal to core; the copy mechanism the * in-place swap uses (`spec:AST-105` FR8, - * `architecture:component-style-authoring` INV7). Only - * motion/animatedLayout.ts imports it. + * `architecture:component-style-authoring` INV7), and the layer's exit copy. + * motion/animatedLayout.ts and Layer/layerExitCopy.ts import it. * * A copy takes no part in the page: it is inert and hidden from assistive * technology, carries no ids or test ids, joins no form or radio group (a @@ -28,7 +28,9 @@ * canvas that cannot be read back (a WebGL canvas without * `preserveDrawingBuffer`, a tainted one) or a blank one. * - * SYNC: When modified, update /packages/core/src/motion/animatedLayout.ts + * SYNC: When modified, update: + * - /packages/core/src/motion/animatedLayout.ts + * - /packages/core/src/Layer/layerExitCopy.ts */ import { @@ -79,6 +81,7 @@ function paintCanvas( /** Inherited properties a copy carries when laid outside its ancestors. */ const INHERITED_PROPERTIES = [ 'color', + 'color-scheme', 'cursor', 'direction', 'font-family', @@ -154,6 +157,23 @@ function readInherited(element: Element): Map { return values; } +/** The listed controls a form can own. */ +const FORM_CONTROLS = + 'button, fieldset, input, object, output, select, textarea'; + +/** Whether `node` is a custom element defined as form-associated. */ +function isFormAssociated( + node: Element, + registry: CustomElementRegistry | undefined, +): boolean { + if (!node.localName.includes('-')) { + return false; + } + const definition = registry?.get(node.localName) as + {formAssociated?: boolean} | undefined; + return definition?.formAssociated === true; +} + /** Scroll offsets a copy restores once laid out (a clone carries none). */ const scrollOffsets = new WeakMap< HTMLElement, @@ -173,9 +193,10 @@ const carriedMotion = new WeakMap< /** * A copy that takes no part: no ids or test ids, no form or radio group (a * copied checked radio would uncheck the live one), no label for a live - * control, and copied frames and media load nothing. Scrolled descendants - * keep their offsets. The CSS animations and transitions running in it carry - * on from where they were, once the copy is laid out (`placeOver`). + * control, and copied frames and media load nothing. Copied elements carry no + * anchor name. Scrolled descendants keep their offsets. The CSS animations + * and transitions running in it carry on from where they were, once the copy + * is laid out (`placeOver`). */ export function inertCopy(element: HTMLElement): HTMLElement | null { const copy = element.cloneNode(true) as HTMLElement; @@ -194,17 +215,31 @@ export function inertCopy(element: HTMLElement): HTMLElement | null { copyOf: new Map(sourceNodes.map((node, index) => [node, copyNodes[index]])), }); for (const node of copyNodes) { - for (const name of [ - 'id', - 'data-testid', - 'name', - 'form', - 'for', - 'autofocus', - ]) { + for (const name of ['id', 'data-testid', 'name', 'for', 'autofocus']) { node.removeAttribute(name); } } + // A second element with a live anchor's name makes the engine lay out + // every frame while the copy moves. + const view = element.ownerDocument.defaultView; + sourceNodes.forEach((source, index) => { + const name = view?.getComputedStyle(source).getPropertyValue('anchor-name'); + if (name != null && name !== '' && name !== 'none') { + (copyNodes[index] as Partial).style?.setProperty( + 'anchor-name', + 'none', + ); + } + }); + // A copy laid inside a `
` would join it, and a copied empty + // `required` field would block its submit. `form=""` matches no form's id, + // so no form owns a copied control, a form-associated custom element too. + const registry = element.ownerDocument.defaultView?.customElements; + for (const node of copyNodes) { + if (node.matches(FORM_CONTROLS) || isFormAssociated(node, registry)) { + node.setAttribute('form', ''); + } + } for (const node of copy.querySelectorAll( 'iframe, video, audio, source, embed, object', )) { @@ -225,6 +260,22 @@ export function inertCopy(element: HTMLElement): HTMLElement | null { return copy; } +/** + * Puts a copy's scrolled descendants, and the copy, at the offsets its element + * had when `inertCopy` made it. It scrolls at once, whatever their + * `scroll-behavior`. A box keeps no scroll position until it is laid out. + */ +export function restoreScrollOffsets(copy: HTMLElement): void { + for (const [node, top, left] of scrollOffsets.get(copy) ?? []) { + if (typeof node.scrollTo === 'function') { + node.scrollTo({top, left, behavior: 'instant'}); + } else { + node.scrollTop = top; + node.scrollLeft = left; + } + } +} + /** The background `element` shows: its own, or the nearest ancestor's. */ export function paintedBackground(element: Element): string { for (let node: Element | null = element; node; node = node.parentElement) { @@ -236,6 +287,25 @@ export function paintedBackground(element: Element): string { return 'Canvas'; } +/** + * Writes on a copy what it inherited where its element was, where its new + * parent `host` passes something else. + */ +export function keepInherited(copy: HTMLElement, host: Element): void { + const hostStyle = getComputedStyle(host); + for (const [name, value] of inheritedValues.get(copy) ?? []) { + // A line-height is always written: the host may pass the same number as + // the other kind (a factor against a length), which descendants inherit + // differently. + if ( + value !== '' && + (name === 'line-height' || hostStyle.getPropertyValue(name) !== value) + ) { + copy.style.setProperty(name, value); + } + } +} + /** * Lay `element` over `rect` (viewport coordinates), absolutely, as the last * child of `host`, wherever its containing block is: no ancestor's position @@ -257,19 +327,7 @@ export function placeOver( height: `${rect.height}px`, }); host.appendChild(element); - // What it inherited where it was, where the host passes something else. - const hostStyle = getComputedStyle(host); - for (const [name, value] of inheritedValues.get(element) ?? []) { - // A line-height is always written: the host may pass the same number as - // the other kind (a factor against a length), which descendants inherit - // differently. - if ( - value !== '' && - (name === 'line-height' || hostStyle.getPropertyValue(name) !== value) - ) { - element.style.setProperty(name, value); - } - } + keepInherited(element, host); // The origin, and the host's scale: the rect is in viewport pixels, the // copy's styles in the host's own. // The rendered size over the layout size, as the glide's `scaleOf` reads @@ -293,15 +351,7 @@ export function placeOver( element.style.height = `${rect.height / scaleY}px`; element.style.left = `${(rect.left - origin.left) / scaleX}px`; element.style.top = `${(rect.top - origin.top) / scaleY}px`; - for (const [node, top, left] of scrollOffsets.get(element) ?? []) { - // At once, whatever the element's own `scroll-behavior`. - if (typeof node.scrollTo === 'function') { - node.scrollTo({top, left, behavior: 'instant'}); - } else { - node.scrollTop = top; - node.scrollLeft = left; - } - } + restoreScrollOffsets(element); const carried = carriedMotion.get(element); if (carried != null) { carriedMotion.delete(element); From 544ddee94218878fd9b2c04c198c3520882dd694 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 5 Nov 2026 08:29:29 -0800 Subject: [PATCH 2/4] fix(core): the exit copy keeps no closed layer The exit copy found the inner layers to raise through a module-level set of every copied layer. A layer React removed on close stayed reachable there until a later close showed a copy. The inner layers are inside the closing layer, so they are now found there, and nothing keeps a layer once it is gone. Chromium 150 and later refuse a show during another popover's toggle, so the copy can open in the next frame. The browser spec's light-dismiss case now reads the copy after a frame, as its nested-close cases do. The cap check's comment now names only the copy cap. --- .../layerExitCopy.interaction.browser.spec.ts | 13 +++--- packages/core/src/Layer/layerExitCopy.test.ts | 41 +++++++++++++++++++ packages/core/src/Layer/layerExitCopy.ts | 23 ++++------- 3 files changed, 56 insertions(+), 21 deletions(-) diff --git a/packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts index 4d64047b4a2a7..20c71cbbe887b 100644 --- a/packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts +++ b/packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts @@ -12,10 +12,10 @@ * layer's drawn box mid-entrance, within half a px. A second copy for the * same layer replaces the first, while another layer's copy stays. * @position Browser proof for layerExitCopy.ts, run by `pnpm - * test:interaction`; jsdom has no layout and no top layer. Android - * Chromium 158 refuses a show during another popover's toggle. These - * engines do not refuse, so the refusal path is proven on an Android - * emulator instead. + * test:interaction`; jsdom has no layout and no top layer. Chromium 150 + * and later refuse a show during another popover's toggle. There the copy + * opens after the closing script, or in the next frame. So a case that + * closes a layer reads the copy after a frame. */ import {fileURLToPath} from 'node:url'; @@ -146,7 +146,10 @@ test('the browser\u2019s own light dismiss gets the copy too, uncut by the clipp }, ATTRIBUTE); // A press outside: the browser closes the layer by itself. await page.mouse.click(360, 700); - const result = await page.evaluate(attribute => { + const result = await page.evaluate(async attribute => { + // A refused show during the light dismiss opens the copy in the next + // frame. + await new Promise(resolve => requestAnimationFrame(resolve)); const copy = document.querySelector(`[${attribute}]`); if (copy == null) { return null; diff --git a/packages/core/src/Layer/layerExitCopy.test.ts b/packages/core/src/Layer/layerExitCopy.test.ts index 035384cbbb35f..61363a10b6128 100644 --- a/packages/core/src/Layer/layerExitCopy.test.ts +++ b/packages/core/src/Layer/layerExitCopy.test.ts @@ -175,6 +175,47 @@ describe('placeLayerExitCopy', () => { } }); + it('shows the copy of a layer inside again after the copy of the layer around it, so it stays on top', () => { + // The popover API, with an open state the top-layer order is read from. + const shown: Element[] = []; + Object.defineProperty(HTMLElement.prototype, 'showPopover', { + configurable: true, + writable: true, + value(this: HTMLElement) { + this.setAttribute('data-open', ''); + shown.push(this); + }, + }); + Object.defineProperty(HTMLElement.prototype, 'hidePopover', { + configurable: true, + writable: true, + value(this: HTMLElement) { + this.removeAttribute('data-open'); + }, + }); + const matches = HTMLElement.prototype.matches; + vi.spyOn(HTMLElement.prototype, 'matches').mockImplementation(function ( + this: HTMLElement, + selector: string, + ) { + return selector === ':popover-open' + ? this.hasAttribute('data-open') + : matches.call(this, selector); + }); + try { + const outer = layer(); + const inner = layer(); + inner.id = 'inner'; + outer.querySelector('#list')!.append(inner); + const innerCopy = place(inner); + const outerCopy = place(outer); + expect(shown.slice(-2)).toEqual([outerCopy, innerCopy]); + expect(innerCopy.hasAttribute('data-open')).toBe(true); + } finally { + Reflect.deleteProperty(HTMLElement.prototype, 'hidePopover'); + } + }); + it('keeps one copy per layer: a second takes only that layer\u2019s first away', () => { popoverApi(true); const element = layer(); diff --git a/packages/core/src/Layer/layerExitCopy.ts b/packages/core/src/Layer/layerExitCopy.ts index 571cd4e19cfa2..516bfcc3e1abf 100644 --- a/packages/core/src/Layer/layerExitCopy.ts +++ b/packages/core/src/Layer/layerExitCopy.ts @@ -111,24 +111,18 @@ function outermostLayer(element: HTMLElement): HTMLElement | null { /** Each layer's copy: placing another for the same layer replaces it. */ const copies = new WeakMap(); -/** Layers whose copies may still stand. */ -const copiedLayers = new Set(); - /** * Shows the copies of layers inside `element` again, so they stay above the - * copy just shown for it. Those layers were drawn above it. + * copy just shown for it. Those layers were drawn above it. They are found + * in `element` itself, so no closed layer is kept here once it is gone. */ function raiseInnerCopies(element: HTMLElement): void { const inner: HTMLElement[] = []; - for (const layer of copiedLayers) { + for (const layer of element.querySelectorAll( + '[popover], dialog', + )) { const copy = copies.get(layer); - if (copy?.isConnected !== true) { - copiedLayers.delete(layer); - } else if ( - layer !== element && - element.contains(layer) && - copy.matches(':popover-open') - ) { + if (copy?.isConnected === true && copy.matches(':popover-open')) { inner.push(layer); } } @@ -205,8 +199,7 @@ export function placeLayerExitCopy( } // One copy per layer: a close during a close replaces it. copies.get(element)?.remove(); - // Past the copy cap, or with a canvas that reads back empty, there is no - // copy, so the close is immediate. + // Past the copy cap there is no copy, so the close is immediate. if (!isCopyable(element)) { return null; } @@ -278,7 +271,6 @@ export function placeLayerExitCopy( keepInherited(copy, outer.parentElement); } copies.set(element, copy); - copiedLayers.add(element); const show = (): boolean => { try { copy.showPopover(); @@ -295,7 +287,6 @@ export function placeLayerExitCopy( copy.remove(); if (copies.get(element) === copy) { copies.delete(element); - copiedLayers.delete(element); } }; if (!show()) { From 0e69c33e6163e4252c71002640572c0d2a620dfc Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 5 Nov 2026 12:48:08 -0800 Subject: [PATCH 3/4] docs(core): the exit copy's JSDoc states the empty-canvas rule once The empty-canvas rule stays in the first paragraph, and the inert-copy paragraph no longer repeats it or `inertCopy`'s own contract. --- packages/core/src/Layer/layerExitCopy.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/packages/core/src/Layer/layerExitCopy.ts b/packages/core/src/Layer/layerExitCopy.ts index 516bfcc3e1abf..752f317315b67 100644 --- a/packages/core/src/Layer/layerExitCopy.ts +++ b/packages/core/src/Layer/layerExitCopy.ts @@ -174,11 +174,8 @@ function layoutBox(element: HTMLElement): LayerExitBox { * names or label targets, and no form owner. A cloned checked radio then * cannot take the live group's selection, and a named field cannot submit. * It is `inert`, hidden from assistive technology, and out of pointer reach. - * Its frames and media load nothing, and a canvas shows its pixels. Content - * holding a canvas that reads back empty gets no copy: the close is then - * immediate. Its descendants' keyframe animations do not start again. A - * layer has one copy: placing another for the same layer takes the previous - * one away. + * Its descendants' keyframe animations do not start again. A layer has one + * copy: placing another for the same layer takes the previous one away. * * It is shown only in the top layer, as a manual popover, so a clipping, * transformed or sticky ancestor neither cuts nor moves it. A fixed box or a From 30e42aeb1296f9e14bcd91b92426d297ddbbf7d7 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 6 Nov 2026 03:13:44 -0800 Subject: [PATCH 4/4] fix(core): the exit copy reads its host's style before the insertion keepInherited read the outer layer's parent's computed style right after the copy was inserted there: a style read after a write. It reads only that host and writes only on the still-detached copy, so it now runs before the insertion. What the copy inherits is unchanged. --- packages/core/src/Layer/layerExitCopy.test.ts | 27 +++++++++++++++++++ packages/core/src/Layer/layerExitCopy.ts | 4 ++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/core/src/Layer/layerExitCopy.test.ts b/packages/core/src/Layer/layerExitCopy.test.ts index 61363a10b6128..8a4cc08b1394a 100644 --- a/packages/core/src/Layer/layerExitCopy.test.ts +++ b/packages/core/src/Layer/layerExitCopy.test.ts @@ -132,6 +132,33 @@ describe('placeLayerExitCopy', () => { expect(copy.style.getPropertyValue('color-scheme')).toBe('dark'); }); + it("reads what the outer layer's parent passes before it inserts the copy there, so no style read follows that write", () => { + popoverApi(true); + const element = layer(); + const host = element.parentElement as HTMLElement; + const outer = document.createElement('div'); + outer.setAttribute('popover', 'auto'); + host.append(outer); + outer.append(element); + const order: string[] = []; + const read = window.getComputedStyle.bind(window); + vi.spyOn(window, 'getComputedStyle').mockImplementation((node, pseudo) => { + if (node === host) { + order.push('read the host'); + } + return read(node, pseudo); + }); + const insert = outer.after.bind(outer); + outer.after = (...nodes: (Node | string)[]) => { + order.push('insert the copy'); + insert(...nodes); + }; + const copy = place(element); + expect(copy.parentElement).toBe(host); + expect(order).toContain('read the host'); + expect(order.at(-1)).toBe('insert the copy'); + }); + it('takes the copy out of every form and radio group, so the live selection stays', () => { popoverApi(true); const element = layer(); diff --git a/packages/core/src/Layer/layerExitCopy.ts b/packages/core/src/Layer/layerExitCopy.ts index 752f317315b67..655517dbbef98 100644 --- a/packages/core/src/Layer/layerExitCopy.ts +++ b/packages/core/src/Layer/layerExitCopy.ts @@ -264,8 +264,10 @@ export function placeLayerExitCopy( if (outer?.parentElement == null) { element.after(copy); } else { - outer.after(copy); + // keepInherited reads the host's style, so it runs before the insertion: + // no style read follows that write. keepInherited(copy, outer.parentElement); + outer.after(copy); } copies.set(element, copy); const show = (): boolean => {