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 4dabcc7737144..b6cb8e0a16ddb 100644 --- a/docs/architecture/layer-runtime.md +++ b/docs/architecture/layer-runtime.md @@ -38,6 +38,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, @@ -68,6 +70,7 @@ deciding_specs: [spec:AST-038, spec:AST-059] "INV7", "INV11", "INV12", + "INV13", "INV14", "INV15", "INV17", @@ -315,6 +318,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 @@ -546,6 +569,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 @@ -613,11 +642,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 @@ -677,6 +707,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 @@ -711,6 +747,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. @@ -767,6 +805,7 @@ this current architecture record. | INV11 | `layerViewportInset.test.ts`, `useLayer.test.tsx`, and the `Core/Layer` viewport-inset stories under the story play guard at a desktop and a phone viewport; `BaseTypeahead.incremental.test.tsx` and the Typeahead incremental-results stories for the `spec:AST-092` FR6 exception | A second gutter definition, a `100%`-of-span cap, a layer narrower than its explicit size, a layer box wider than the viewport, a layer inside the gutter, or a layer that slides toward an off-screen anchor; for an open Typeahead popup, a later list for the same query that flips it to the other side or grows it past the room on its side, or a first list for a query that is capped to the span beside the trigger | | INV12 | The `Core/Layer` viewport-inset stories' first-frame comparison, and `useLayer.test.tsx`'s synchronous anchor read | A layer whose first painted rectangle differs from its settled one | | INV11, INV12 | The software keyboard's cap: `useLayerKeyboardClearance.test.tsx` for its rule, its timing, and its read before first paint; `PopoverKeyboard.interaction.browser.spec.ts` and `keyboardCappedLists.interaction.browser.spec.ts` for its rendered geometry in Chromium and WebKit | A layer that runs under the keyboard, or is capped though the keyboard does not reach it; a cap that changes more than once per keyboard movement or under a press; a layer opened with the keyboard up whose first frame is uncapped or paints its content past its box | +| INV13 | `layerExitCopy.test.ts` and `layerExitCopy.interaction.browser.spec.ts` | A copy with an id, a form name, a form owner, or pointer reach; a copy off the layer's drawn box; a copy outside the top layer; a second copy for one layer | | INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface | | INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through | | INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests; `useBackdropPress.test.tsx`; `outsidePress.test.ts` | A current local channel silently changes ownership or policy | 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..20c71cbbe887b --- /dev/null +++ b/packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts @@ -0,0 +1,319 @@ +// 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. 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'; +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(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; + } + 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..8a4cc08b1394a --- /dev/null +++ b/packages/core/src/Layer/layerExitCopy.test.ts @@ -0,0 +1,642 @@ +// 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("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(); + 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('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(); + // 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..655517dbbef98 --- /dev/null +++ b/packages/core/src/Layer/layerExitCopy.ts @@ -0,0 +1,305 @@ +// 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(); + +/** + * Shows the copies of layers inside `element` again, so they stay above the + * 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 element.querySelectorAll( + '[popover], dialog', + )) { + const copy = copies.get(layer); + if (copy?.isConnected === true && 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 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 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 { + // 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 => { + 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); + } + }; + 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 index 92de387c6522a..fe142a442802e 100644 --- a/packages/core/src/Layer/settledBox.ts +++ b/packages/core/src/Layer/settledBox.ts @@ -5,13 +5,14 @@ * @input A layer element * @output Exports `settledBox`: the layer's box where its position option put * it, without the transform an entrance (or anything else) applies to it - * @position Layer runtime: the one box read the fallback order and the - * software keyboard's cap both measure with (useLayer.tsx, - * useLayerKeyboardClearance.ts) + * @position Layer runtime: the one box read the fallback order, the software + * keyboard's cap and the exit copy measure with. Its readers are listed + * below. * * SYNC: When modified, update: * - /packages/core/src/Layer/useLayer.tsx * - /packages/core/src/Layer/useLayerKeyboardClearance.ts + * - /packages/core/src/Layer/layerExitCopy.ts */ const TRANSFORM_PROPERTIES = ['transform', 'translate', 'scale', 'rotate']; 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 f99fb39d3bbe5..d2695c70fac66 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 a child of * `host` (before `beforeNode`, else last), wherever its containing block is: @@ -258,19 +328,7 @@ export function placeOver( height: `${rect.height}px`, }); host.insertBefore(element, beforeNode); - // 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 @@ -294,15 +352,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);