From b83240b68adda601b522b6ecd714f9b4dee225c4 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 3 Nov 2026 09:14:43 -0800 Subject: [PATCH 1/8] 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 | 311 ++++++++++ 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 | 126 ++-- 10 files changed, 1550 insertions(+), 167 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 dbb4db24b8192..b7b81d0f68153 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, @@ -63,6 +65,7 @@ deciding_specs: [spec:AST-038, spec:AST-059] "INV7", "INV11", "INV12", + "INV13", "INV14", "INV15", "INV17" @@ -309,6 +312,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 @@ -502,6 +525,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 @@ -566,11 +595,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 @@ -623,6 +653,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 @@ -652,6 +688,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. @@ -704,6 +742,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..483fb496ee8dd --- /dev/null +++ b/packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts @@ -0,0 +1,311 @@ +// 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: a + * popover layer inside a clipping, transformed panel, an entrance curve + * held halfway, and Chromium and WebKit + * @output Proof that the engine shows the copy where the layer was drawn: + * 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`, + * uncut by the clipping panel, and 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. The refusal + * path (Android Chromium 158 refuses a show during another popover's + * toggle) is proven on the Android gate emulator (pull request evidence): + * these engines do not refuse. + */ + +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(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(); + 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(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(); + 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..8ed3c95c9cc06 --- /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: out of reach and out of the accessibility tree, no ids or form + * names, only in the top layer (hidden until a refused show succeeds, none + * without the popover API or past the copy cap), on the layer's layout box + * with fractions and the transform and opacity it was drawn with, with no + * keyframes or transitions replaying, one per layer, 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..87422fccd2b0f --- /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, and shows it 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 a1b531ff3d27f..dfaddc14eec21 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'; @@ -479,128 +480,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 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 32bb8e65830f8..4d230eaa22676 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 @@ -25,7 +25,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 */ /** Above this many elements, old content is not copied: the new one enters. */ @@ -70,6 +72,7 @@ function paintCanvas( /** Inherited properties a copy carries when laid outside its ancestors. */ const INHERITED_PROPERTIES = [ 'color', + 'color-scheme', 'cursor', 'direction', 'font-family', @@ -145,6 +148,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, @@ -154,8 +174,9 @@ const scrollOffsets = 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 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 once the copy is laid + * out (`placeOver`). */ export function inertCopy(element: HTMLElement): HTMLElement | null { const copy = element.cloneNode(true) as HTMLElement; @@ -170,17 +191,31 @@ export function inertCopy(element: HTMLElement): HTMLElement | null { scrollOffsets.set(copy, offsets); inheritedValues.set(copy, readInherited(element)); 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', )) { @@ -201,6 +236,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) { @@ -212,6 +263,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 @@ -232,19 +302,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 @@ -268,15 +326,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); } /** From fbe71dfa6fc2329939eec647c81cdb23c669dc8f Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 14:45:48 -0800 Subject: [PATCH 2/8] feat(Layer): one input hold, first used by Dialog, Drawer and MobileNav (spec:AST-094 FR35) Layer/inputHold holds a layer's pointer input while its presentation enters or leaves. holdInput(layer, {until, scope}) raises a shield: 'viewport' over the whole viewport while a modal layer enters; 'surface' over the layer's own box while a non-modal one enters, the page around it live; 'layer' over the viewport, its content inert, while a layer leaves. It decides by each event's pointer (a finger's or a pen's press is held to its end; a mouse passes once it moves with no button down, or from the start when the page last heard a mouse, DEC-16), never cancels a touch's start, and cancels a one-finger move so a pinch still zooms (FR10). It hears input through Core's shared input stream before every other subscriber, and ends the dispatch for a held event, so press feedback and the gesture host never hear it; the stream gains first subscribers and records the type of the latest pointer event it delivers (getLastPointerType). The gesture host asks the hold for each touch (holdsTouch), so the hold imports nothing from gestures/ and a component in the root entry may use it statically (architecture:react-component-runtime INV13). Its first users hold only under a coarse primary pointer, a touch presentation (FR13): Dialog, Drawer and MobileNav hold a finger's tap or drag while they enter (holdEntranceInput, which reads the entrance's own animations; MobileNav's slide-in is capped at 550 ms), a non-modal Drawer only on its panel. Under a fine primary pointer nothing is held and nothing listens (FR24). Where the primary pointer is fine and the screen also takes touch, a finger is not held yet; AST-094's current-state impact and Drawer's record name that gap. AST-094's current-state impact also names the first press of a still mouse after a finger, which lands on an entering presentation's shield. AlertDialog renders Dialog, so its entrance is held too: its record says FR7 ships in part, the leaving alert's inert content waiting for FR6's dismissal. Every browser proof lands its input at an exact point (an entrance held where it is, the page's clock, or an exact step of a drag) and plays once. The WebKit interaction lane's scope includes Layer/inputHold.ts: the gesture host imports it, so the gesture specs' fixture bundles it. MobileNav's record states what the rest of the slide-out after the close does: it is inert, taking no input and hidden from assistive technology (FR5). A browser case proves both against the open drawer. From #8342 and its per-event offer, #8630 (Dialog and Drawer) and #8374 (MobileNav). Co-authored-by: Cindy Zhang --- .../dialog-drawer-touch-entrance-hold.md | 7 + .changeset/layer-input-hold.md | 7 + .changeset/mobile-nav-touch-presentation.md | 7 + .../specs/AST-094-touch-presentations/spec.md | 10 +- .../AlertDialog/AlertDialog.spec.md | 12 +- docs/specs/components/Dialog/Dialog.spec.md | 2 +- docs/specs/components/Drawer/Drawer.spec.md | 11 +- .../components/MobileNav/MobileNav.spec.md | 6 +- packages/core/src/Dialog/Dialog.doc.mjs | 2 +- packages/core/src/Dialog/Dialog.tsx | 9 +- .../src/Dialog/DialogTouchEntrance.test.tsx | 143 ++++ ...gTouchEntrance.interaction.browser.spec.ts | 452 +++++++++++ packages/core/src/Drawer/Drawer.doc.mjs | 2 +- .../src/Drawer/DrawerTouchEntrance.test.tsx | 157 ++++ ...rTouchEntrance.interaction.browser.spec.ts | 454 +++++++++++ .../src/Drawer/useDrawerDialogPresence.ts | 11 +- .../src/Layer/__tests__/inputHold.fixture.ts | 137 ++++ .../inputHold.interaction.browser.spec.ts | 572 ++++++++++++++ .../core/src/Layer/holdEntranceInput.test.ts | 236 ++++++ packages/core/src/Layer/holdEntranceInput.ts | 84 ++ packages/core/src/Layer/inputHold.test.tsx | 699 +++++++++++++++++ packages/core/src/Layer/inputHold.ts | 734 ++++++++++++++++++ packages/core/src/MobileNav/MobileNav.doc.mjs | 6 +- packages/core/src/MobileNav/MobileNav.tsx | 35 +- .../MobileNavTouchPresentation.test.tsx | 268 +++++++ ...NavTouchPresentation.a11y.chromium.spec.ts | 520 +++++++++++++ .../core/src/__tests__/stubMatchMedia.test.ts | 11 + packages/core/src/__tests__/stubMatchMedia.ts | 30 +- packages/core/src/gestures/GestureHost.ts | 13 +- packages/core/src/gestures/README.md | 10 +- .../gestures/__tests__/GestureHost.test.ts | 21 + packages/core/src/utils/flatTree.test.ts | 28 +- packages/core/src/utils/flatTree.ts | 18 +- packages/core/src/utils/inputStream.test.ts | 55 +- packages/core/src/utils/inputStream.ts | 57 +- packages/core/src/utils/selectionLock.ts | 15 +- scripts/touch-support-bundle.test.mjs | 16 + 37 files changed, 4798 insertions(+), 59 deletions(-) create mode 100644 .changeset/dialog-drawer-touch-entrance-hold.md create mode 100644 .changeset/layer-input-hold.md create mode 100644 .changeset/mobile-nav-touch-presentation.md create mode 100644 packages/core/src/Dialog/DialogTouchEntrance.test.tsx create mode 100644 packages/core/src/Dialog/__tests__/DialogTouchEntrance.interaction.browser.spec.ts create mode 100644 packages/core/src/Drawer/DrawerTouchEntrance.test.tsx create mode 100644 packages/core/src/Drawer/__tests__/DrawerTouchEntrance.interaction.browser.spec.ts create mode 100644 packages/core/src/Layer/__tests__/inputHold.fixture.ts create mode 100644 packages/core/src/Layer/__tests__/inputHold.interaction.browser.spec.ts create mode 100644 packages/core/src/Layer/holdEntranceInput.test.ts create mode 100644 packages/core/src/Layer/holdEntranceInput.ts create mode 100644 packages/core/src/Layer/inputHold.test.tsx create mode 100644 packages/core/src/Layer/inputHold.ts create mode 100644 packages/core/src/MobileNav/MobileNavTouchPresentation.test.tsx create mode 100644 packages/core/src/MobileNav/__tests__/MobileNavTouchPresentation.a11y.chromium.spec.ts diff --git a/.changeset/dialog-drawer-touch-entrance-hold.md b/.changeset/dialog-drawer-touch-entrance-hold.md new file mode 100644 index 0000000000000..d8bffe2b35dfe --- /dev/null +++ b/.changeset/dialog-drawer-touch-entrance-hold.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] On a phone or tablet (a coarse primary pointer), a tap or a drag that lands while a `Dialog` or a `Drawer` is still entering no longer closes it, runs one of its actions, moves focus or scrolls the page: it reaches nothing until the entrance has played, and the dialog or drawer finishes entering and stays open. Around a `Drawer` without a scrim only a tap or a drag on the panel is held, and the page stays live. Keys and assistive technology stay live during the entrance, the content stays in the accessibility tree, a pinch still zooms the page, and a mouse or a trackpad still clicks: at once when it was the last pointer used, otherwise once it moves. + +@vjeux diff --git a/.changeset/layer-input-hold.md b/.changeset/layer-input-hold.md new file mode 100644 index 0000000000000..128ee5c515017 --- /dev/null +++ b/.changeset/layer-input-hold.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: one input hold for every layer (`Layer/inputHold`). While a layer presents, a finger's or a pen's touch, press or click reaches nothing: anywhere around a modal layer, and only on the layer itself around a non-modal one, whose page stays live. A mouse passes once it moves, at once when the page last heard a mouse (keys and assistive technology still act, and a pinch still zooms the page). While it dismisses, every press and click reaches nothing, and the layer's content is inert. The gesture host asks the hold about each touch (`holdsTouch`), and `isInputShield` lets a hit test see past a hold's shield. Not exported from the package entry point; Dialog's and Drawer's entrance holds and MobileNav's drawer use it. + +@vjeux diff --git a/.changeset/mobile-nav-touch-presentation.md b/.changeset/mobile-nav-touch-presentation.md new file mode 100644 index 0000000000000..849c4d7a81f30 --- /dev/null +++ b/.changeset/mobile-nav-touch-presentation.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] On a phone or tablet (a coarse primary pointer), a tap or a drag during MobileNav's slide-in reaches nothing; keys and assistive technology stay live, and a mouse or a trackpad still clicks: at once when it was the last pointer used, otherwise once it moves. + +@vjeux diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index fb49a046dfa0f..dcdca813ff3b0 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -28,6 +28,8 @@ affects_consumer_docs: [] ```json { "paths": [ + "packages/core/src/Layer/holdEntranceInput.ts", + "packages/core/src/Layer/inputHold.ts", "packages/core/src/motion/uikit/segmented.ts", "packages/core/src/motion/uikit/slider.ts" ] @@ -827,7 +829,13 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and let a scrim or overlay tap close at any time (`spec:AST-003` FR10 and `architecture:layer-runtime` INV14 leave dismissal to the component). Toast and a non-modal sheet (`component:BottomSheetSwitcher` FR5 and its Non-modal state) do not hold the page: the page behind them stays live, and - only the sheet itself holds a tap or a drag while it enters. + only the sheet itself holds a tap or a drag while it enters. Dialog, Drawer + and MobileNav hold an entrance only under a coarse primary pointer: where + the primary pointer is fine and the screen also takes touch (a touchscreen + laptop), a finger's tap or drag during the entrance is not held. After a + finger, the first press of a mouse that has not moved since lands on the + entering presentation's shield and does nothing, where FR35 keeps today's + behavior for a mouse (DEC-16); a move of the mouse lowers the shield first. - BottomSheet, Toast, Lightbox, NavigationStack and keyboard dismissal: a drag that commits follows FR36–FR40. - `spec:AST-100` owns release velocity, which FR17 reads. diff --git a/docs/specs/components/AlertDialog/AlertDialog.spec.md b/docs/specs/components/AlertDialog/AlertDialog.spec.md index e683fdcded155..7dfa5af902816 100644 --- a/docs/specs/components/AlertDialog/AlertDialog.spec.md +++ b/docs/specs/components/AlertDialog/AlertDialog.spec.md @@ -19,6 +19,7 @@ verified_by: packages/core/src/AlertDialog/__tests__/AlertDialog.a11y.test.tsx, packages/core/src/AlertDialog/__tests__/AlertDialog.a11y.chromium.spec.ts, packages/core/src/Dialog/Dialog.test.tsx, + packages/core/src/Dialog/__tests__/DialogTouchEntrance.interaction.browser.spec.ts, scripts/check-knowledge.mjs, apps/storybook/rtl-audit/targets.json, ] @@ -52,7 +53,7 @@ system_specs: | Behavior | A modal confirmation that interrupts: it opens through the native dialog, cannot be dismissed by a click outside, closes on Escape or Cancel through `onOpenChange(false)`, and runs `onAction` on the action button. | | End-user impact | A keyboard or screen-reader user is told a decision is needed (the title and description are announced), lands on Cancel, and cannot lose the dialog by clicking past it. On a touch screen the alert scales in and fades out with iOS's look, on the theme's motion tokens, and ignores taps while it enters (FR6, FR7), and on a phone it is 320 px wide (FR9); on a touch screen a press slid from Cancel to the action runs the lifted action; a mouse's press acts natively (FR8). | | Builder impact | None. | -| Compatibility/readiness | FR1–FR5, FR8 and AR1 record shipped behavior, apart from AR1's Tab wrap. FR6, FR7 and FR9 are requirements not shipped yet. Each gap is listed under Current-state impact. | +| Compatibility/readiness | FR1–FR5, FR8 and AR1 record shipped behavior, apart from AR1's Tab wrap. FR7 ships in part, and FR6 and FR9 are requirements not shipped yet. Each gap is listed under Current-state impact. | | Review checks | Reject a modal AlertDialog without `role="alertdialog"`, a title or description not linked by id, initial focus on the destructive action, or a backdrop click that dismisses it. | | Governing rules | `architecture:public-component-api/INV1,INV5–INV8`; `architecture:component-theming-surface/INV3–INV7`; `architecture:layer-runtime`; `component:Dialog/AR1–AR3`; `spec:AST-020/FR15`; `spec:AST-094` FR4, FR7, FR45, FR13, FR35, DEC-15, DEC-17; `family:action-groups`; `design:reduced-motion`; `spec:AST-017`. | @@ -85,8 +86,9 @@ Consumer migration instructions belong in consumer docs and release notes. - **The touch presentation is not shipped (FR6).** Under a touch presentation the alert opens and closes with Dialog's default motion, not the scale-in and fade-out FR6 requires. -- **Pointer input is not held while the alert enters (FR7).** A tap that lands - during the entrance reaches the alert; `spec:AST-094` FR35 holds it. +- **Only the entrance hold ships (FR7).** Under a touch presentation, Dialog + holds pointer input while the alert enters. Nothing makes the content inert + while the alert leaves, because its dismissal fade has not shipped (FR6). - **The phone width is not shipped (FR9).** On a phone the alert keeps its default width rather than 320 px. - **Tab leaves the alert (AR1).** Dialog does not yet contain Tab, so Tab from @@ -130,7 +132,7 @@ Consumer migration instructions belong in consumer docs and release notes. | FR4 | `isInline` renders the same anatomy without modality and without the alert-dialog role. | shipped source and public docs | | FR5 | `useImperativeAlertDialog` returns `show`, `hide`, and the element to render, and owns `isOpen`/`onOpenChange` for its caller. | shipped source and focused tests | | FR6 | Under a touch presentation (`spec:AST-094` FR13), a modal AlertDialog presents by scaling from 1.2 to 1 with its opacity and its backdrop's dimming rising from 0 to 1 on the theme's entrance duration and easing tokens (`spec:AST-094` FR45), started at the browser's commit, with the larger start kept inside the viewport; it dismisses by a fade alone on the theme's exit duration and easing, `--duration-exit` and `--ease-exit` (`spec:AST-094` FR7; `spec:AST-090` FR14), and closes at the fade's end; a close during the presentation, or a reopen during the dismissal, turns back from where it is. `springs.alertPresent` and `springs.alertDismiss` stay as UIKit's measured reference, and no motion plays them (`spec:AST-094` FR4). Under Reduce Motion both are the shared cross-fade (`design:reduced-motion` DR1–DR3). A fine primary pointer keeps today's motion (`spec:AST-094` FR13 and its Non-goals). Implementation gap: not shipped yet (Current-state impact). | proposed from measured iOS 26.2 behavior | -| FR7 | Under a touch presentation, pointer input to the alert is held while it enters (`spec:AST-094` FR35); keyboard and assistive-technology input are never held, and the entrance never makes the content inert. While the alert leaves, its content is inert for the dismissal fade. The hold's timing stays internal (`spec:AST-002` FR3). Implementation gap: not shipped yet (Current-state impact). | `spec:AST-094` FR35; owner decision (DEC-1) | +| FR7 | Under a touch presentation, pointer input to the alert is held while it enters (`spec:AST-094` FR35); keyboard and assistive-technology input are never held, and the entrance never makes the content inert. While the alert leaves, its content is inert for the dismissal fade. The hold's timing stays internal (`spec:AST-002` FR3). Implementation gap: the entrance hold ships through Dialog, and the leaving alert's inert content waits for FR6's dismissal (Current-state impact). | `spec:AST-094` FR35; owner decision (DEC-1) | | FR8 | AlertDialog's actions are an action group (`family:action-groups`): under the touch presentation (`spec:AST-094` FR13), a press that slides across them runs the action it lifts on, and a lift outside them runs nothing; a mouse press acts as the platform's native button does; keyboard and assistive-technology behavior is unchanged. | `family:action-groups`; `spec:AST-094` DEC-17; DEC-3 | | FR9 | On a phone, a compact window (`spec:AST-012` FR9: narrower than `md` or shorter than 500 px) under a coarse primary pointer, the alert is 320 px wide in every theme, as iOS's is; no theme role sets it. A caller's explicit `width` still wins there (`architecture:public-component-api` INV5), and Dialog's viewport clamp still applies on a screen narrower than the alert. Elsewhere it keeps today's width. Implementation gap: not shipped yet (Current-state impact). | owner decision (DEC-2) | @@ -229,7 +231,7 @@ The dialog surface (the Dialog element AlertDialog renders) carries `alert-dialo | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | | FR1–FR5 | `AlertDialog.test.tsx` ("calls onOpenChange(false) on Escape", "does not call onOpenChange when action is clicked", "does not call onAction on Escape", "does not disable the cancel button while the action is loading", "exposes a named group instead, with no aria-modal") and `useImperativeAlertDialog.test.tsx` ("opens on show()", "closes on hide()") | open, loading, inline, imperative | Escape not cancelling, the action closing by itself, or the inline path claiming the role fails. | `audit:AlertDialog/behavior` | | FR6, PR2 | Browser tests under a coarse pointer in Chromium and WebKit, a theme-token curve oracle for the present and the dismissal, a busy-main-thread case, real-device clips on iOS Safari, and Android Chrome clips in the Android emulator (`spec:AST-094` DEC-27) | present, dismiss, close during present, reopen during dismiss, Reduce Motion, a fine pointer, a narrow viewport | a present or a tap-, key- or program-started dismissal that plays a measured role instead of the theme's entrance or exit duration and easing, a start outside the viewport, a jump on interruption, a scale under Reduce Motion, changed motion under a fine pointer, or an added element fails. No test exists yet; FR6 is not shipped. | `audit:AlertDialog/behavior` | -| FR7 | Browser tests under a coarse pointer, with keyboard and assistive-technology input | a tap during the presentation, Enter and Escape during it, a screen reader's activation, a tap during the dismissal; a mouse click during the presentation under a fine pointer | a held key or assistive-technology action, content made inert during the entrance, a tap that reaches a leaving alert, or a mouse click held under a fine pointer fails. No test exists yet; FR7 is not shipped. | `audit:AlertDialog/behavior` | +| FR7 | `DialogTouchEntrance.interaction.browser.spec.ts` ("a tap on an alert's action while it enters runs nothing, and once it has entered the same tap runs it"; "keys and assistive technology stay live while the dialog enters") | a tap during the presentation, Enter and Escape during it, a screen reader's activation, a tap during the dismissal; a mouse click during the presentation under a fine pointer | a held key or assistive-technology action, content made inert during the entrance, a tap that reaches a leaving alert, or a mouse click held under a fine pointer fails. No test covers the leaving alert, which FR6's dismissal brings. | `audit:AlertDialog/behavior` | | FR8 | `AlertDialog.test.tsx` ("AlertDialog action tracking"), `useActionGroupTracking.test.tsx` and `AlertDialog.interaction.browser.spec.ts` | a press on Cancel slid onto the action and lifted, and a press lifted outside the actions, each with a mouse, a pen, and a finger; Enter and Space on each action | the press-start action running after a slide, any action running on a lift outside, or a changed keyboard or assistive-technology activation fails. | `audit:AlertDialog/behavior` | | FR9 | Browser tests at a phone width and at a desktop width, in the default and an alternate theme | a phone width and a desktop width, in the default and an alternate theme; a caller `width` at a phone width; a screen narrower than 320 px; a narrow window under a fine pointer; a coarse screen that is not compact | a phone-width alert other than 320 px in any theme without a caller `width`, a caller `width` overridden, a desktop width changed, an alert wider than the viewport, or a 320 px alert in a narrow fine-pointer window or on a non-compact coarse screen fails. No test exists yet; FR9 is not shipped. | `audit:AlertDialog/behavior` | | AR1 | `AlertDialog.test.tsx` ("links title via aria-labelledby", "marks cancel as the initial focus target", "keeps the initial focus target on the least destructive action", "calls onOpenChange(false) on Escape", "stacks long destructive action labels above cancel on a narrow fine-pointer screen", "reaches both buttons by Tab, cancel first", "is a modal alertdialog", "does not claim the alertdialog role") and `useImperativeAlertDialog.test.tsx`; the Alert Dialog accessibility contract binding in `__tests__/AlertDialog.a11y.test.tsx` and `__tests__/AlertDialog.a11y.chromium.spec.ts` (role, description link, no backdrop dismiss, focus delegation) | open modal; after Escape; after Cancel | The role, name link, description link, or Cancel initial focus is lost, or a click outside dismisses the dialog. Gap: the contract keeps `alertdialog.focus.least-destructive-first` and `alertdialog.dismissal.click-beside-is-inert` advisory, so a regression in either only reports; `spec:AST-020` FR9 makes them required once this record is current. No test covers Tab wrapping inside the alert (Current-state impact). | `audit:AlertDialog/accessibility` | diff --git a/docs/specs/components/Dialog/Dialog.spec.md b/docs/specs/components/Dialog/Dialog.spec.md index 009503d0c6eea..8673561fccb96 100644 --- a/docs/specs/components/Dialog/Dialog.spec.md +++ b/docs/specs/components/Dialog/Dialog.spec.md @@ -31,7 +31,7 @@ architecture: architecture:react-component-runtime, ] contributing: [] -system_specs: [spec:AST-013, spec:AST-020, spec:AST-021] +system_specs: [spec:AST-013, spec:AST-020, spec:AST-021, spec:AST-094/FR35] --- # Dialog component contract diff --git a/docs/specs/components/Drawer/Drawer.spec.md b/docs/specs/components/Drawer/Drawer.spec.md index ac12067eb8652..f5d47c6fbaab8 100644 --- a/docs/specs/components/Drawer/Drawer.spec.md +++ b/docs/specs/components/Drawer/Drawer.spec.md @@ -95,10 +95,13 @@ Consumer migration instructions belong in consumer docs and release notes. motion the slide and the scrim transition still run for 0.01 s. For a fine pointer, `design:reduced-motion` DR1 forbids the travel and DR3 allows no animated property; a touch user gets no opacity fade, which DR2 calls for. -- **A tap during the entrance is not held.** Under a finger, a scrim tap that - lands while the drawer is still entering closes an `info` drawer, and a tap - or drag reaches the panel. `spec:AST-094` FR35 holds pointer input until the - entrance finishes. +- **A finger is held during the entrance only under a coarse primary + pointer.** There, a tap or a drag that lands while the drawer is still + entering reaches nothing, and around a non-modal drawer only one on the + panel is held. Where the primary pointer is fine and the screen also takes + touch (a touchscreen laptop), a finger's scrim tap during the entrance + closes an `info` drawer, and a tap or drag reaches the panel. + `spec:AST-094` FR35 holds pointer input until the entrance finishes. - **A consumer `onCancel` never runs.** Drawer sets its own `onCancel` after the caller's props, so a caller's `onCancel` is dropped. `architecture:public-component-api` INV5 has accepted event inputs reach the diff --git a/docs/specs/components/MobileNav/MobileNav.spec.md b/docs/specs/components/MobileNav/MobileNav.spec.md index 5a1d45f9e9813..c3d2f32f5cb95 100644 --- a/docs/specs/components/MobileNav/MobileNav.spec.md +++ b/docs/specs/components/MobileNav/MobileNav.spec.md @@ -24,6 +24,7 @@ verified_by: packages/core/src/MobileNav/MobileNavPinchZoom.a11y.chromium.spec.ts, packages/core/src/Layer/layerDismissalFamilies.test.tsx, packages/core/src/MobileNav/__tests__/MobileNavWidth.a11y.chromium.spec.ts, + packages/core/src/MobileNav/__tests__/MobileNavTouchPresentation.a11y.chromium.spec.ts, packages/core/src/theme/themingTargets.test.ts, scripts/check-knowledge.mjs, apps/storybook/rtl-audit/targets.json, @@ -40,7 +41,7 @@ architecture: architecture:public-component-api, ] contributing: [] -system_specs: [] +system_specs: [spec:AST-094/FR13, spec:AST-094/FR35] --- # MobileNav component contract @@ -142,7 +143,7 @@ Consumer migration instructions belong in consumer docs and release notes. | FR2 | `isOpen` and `onOpenChange` win when given; otherwise the drawer reads and changes the enclosing AppShell's drawer state. The dialog uses AppShell's drawer id when there is one, else its own; a caller `id` replaces either (Current-state impact). | Current source and tests | | FR3 | Opening calls `showModal()`, and records the focused element as the opener; where focus lands inside the open drawer is uncontracted here. While open, the page's scroller clips its overflow and keeps its scrollbar gutter: the root, or `` when `` sets its own overflow and the root's stays `visible`. Pull-to-refresh and the page's bounce stop, because a scroll lock under a modal holds the page (`spec:AST-094` FR19). Closing releases all three. | Current source and tests | | FR4 | The native cancel request (Escape) is routed through the shared dismissal stack and requests close only when this drawer is topmost. A click on the overlay outside the Drawer requests close; a click inside does not. The Close button, named by `@astryx.mobileNav.closeNavigation`, requests close. A caller `onClick` on the dialog runs before the backdrop check; one that calls `preventDefault()` cancels that backdrop close. | Current source and tests | -| FR5 | After a close request the drawer slides out while the dialog stays open, and the dialog closes within its slide-out transition and no later than 250 ms after the request (on the next task, never in the commit that requests it, under reduced motion or a zero-length transition). Reopening before then cancels the close. Unmounting closes the dialog. | Current source and tests | +| FR5 | After a close request the drawer slides out while the dialog stays open, and the dialog closes within its slide-out transition and no later than 250 ms after the request (on the next task, never in the commit that requests it, under reduced motion or a zero-length transition). Reopening before then cancels the close. Unmounting closes the dialog. After the dialog closes, the rest of the slide-out is inert. | Current source and tests | | FR6 | When the dialog closes, focus returns to the recorded opener if it is still connected and was not the document body; otherwise focus is left alone. A reopen that interrupted a close keeps the original opener. | Current source and tests | | FR7 | The Drawer enters from its resolved inline edge, from off-screen to on-screen, and the backdrop fades in from transparent, without a reduced-motion preference. Under reduced motion, motion follows `design:reduced-motion` DR1–DR3 (Current-state impact records today's shortfall). The overlay clips the off-screen drawer without becoming a scroll container and allows pinch zoom. | Current source and tests | | FR8 | `side="start"` or `"end"` sets the edge. `side="auto"` MUST keep the drawer's start and end relationship to the element that opened it (`design:bidirectionality` DR7). Implementation gap: it resolves on each open from the focused element's physical half of the viewport (left half picks `start`, otherwise `end`); when nothing is focused at open it keeps its last value, and before any open it is `end`. | Current source | @@ -270,6 +271,7 @@ ownership. | FR2, FR3, FR4 | `MobileNav.test.tsx`; `MobileNavCloseEdgeCases.test.tsx`; `MobileNavScrollbarGutter.test.tsx`; `MobileNavRootScrollClaim.test.tsx` | Escape, backdrop, content click, Close | A wrong close source or a lingering scroll lock fails. | `audit:MobileNav/behavior` | | FR4 | `layerDismissalFamilies.test.tsx` MobileNav cases | Escape over a required Dialog; cancel while topmost and while not | Closing when not topmost, or not closing when topmost, fails. | `audit:MobileNav/behavior` | | FR5, ORD3 | `MobileNavCloseVisibility.test.tsx`; `MobileNavCloseEdgeCases.test.tsx`; `MobileNavCloseTiming.test.ts` | Close, reduced motion, reopen, unmount, the 250 ms bound | Closing before the slide-out or a stuck dialog fails. | `audit:MobileNav/behavior` | +| FR5 | `MobileNavTouchPresentation.a11y.chromium.spec.ts` (the slide-out after the close) | Closed dialog, drawer still sliding out; open drawer | A tap on the leaving drawer reaching it, or the browser's accessibility tree exposing the dialog or its links after the close, fails. | `audit:MobileNav/behavior` | | FR6, AR2 | `MobileNavFocus.test.tsx` | Standalone, AppShell, Escape, removed opener | Focus not returned, or returned too early, fails. | `audit:MobileNav/accessibility` | | FR7 | `MobileNavEntryAnimation.test.tsx` | Start and end edges | Missing starting style or a scroll-container overlay fails. | `audit:MobileNav/behavior` | | FR11, AR3 | `MobileNavToggle.test.tsx`; `MobileNavReopen.test.tsx` | Closed, open, reopen | Broken expanded state or id link fails. | `audit:MobileNav/accessibility` | diff --git a/packages/core/src/Dialog/Dialog.doc.mjs b/packages/core/src/Dialog/Dialog.doc.mjs index 515489b4c5b47..76da568936ae1 100644 --- a/packages/core/src/Dialog/Dialog.doc.mjs +++ b/packages/core/src/Dialog/Dialog.doc.mjs @@ -69,7 +69,7 @@ export const docs = { ], }, description: - 'Modal dialog using the native element. Modal and inline content starts with theme body text defaults. Ancestor surface/group membership ends as a whole, including group-owned state. Explicit props and unrelated contexts remain unchanged. Place intentional groups and complete required providers inside the dialog. With reduced motion the dialog never slides or scales in: on a touch screen it fades in, in 200 ms or less, and with a mouse it appears at once.', + 'Modal dialog using the native element. Modal and inline content starts with theme body text defaults. Ancestor surface/group membership ends as a whole, including group-owned state. Explicit props and unrelated contexts remain unchanged. Place intentional groups and complete required providers inside the dialog. With reduced motion the dialog never slides or scales in: on a touch screen it fades in, in 200 ms or less, and with a mouse it appears at once. On a phone or tablet (a coarse primary pointer), a tap or a drag that lands while the dialog is still entering reaches nothing, and the dialog finishes entering; keys and assistive technology stay live, and a mouse or a trackpad still clicks: at once when it was the last pointer used, otherwise once it moves.', props: [ { name: 'isOpen', diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx index a97d4d56b3478..4b896e341b156 100644 --- a/packages/core/src/Dialog/Dialog.tsx +++ b/packages/core/src/Dialog/Dialog.tsx @@ -5,7 +5,7 @@ /** * @file Dialog.tsx * @input Uses React, DialogHTMLAttributes, ReactNode, container (Layout), DialogContext, layerTextReset, - * layerStructureReset, modalOutlet, interactionModality, chainEventHandlers + * layerStructureReset, modalOutlet, interactionModality, chainEventHandlers, holdEntranceInput * @output Exports Dialog component, DialogProps, DialogVariant, DialogPurpose types * @position Core implementation; consumed by index.ts, tested by Dialog.test.tsx * @@ -27,6 +27,7 @@ * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/Dialog/Dialog.doc.mjs (props table, features, implementation notes) * - /packages/core/src/Dialog/Dialog.test.tsx (tests for new/changed behavior) + * - /packages/core/src/Dialog/__tests__/DialogTouchEntrance.interaction.browser.spec.ts (the touch entrance hold) * - /packages/core/src/Dialog/index.ts (exports if types change) * - /apps/storybook/stories/Dialog.stories.tsx (storybook stories) * - /packages/cli/assets/templates/blocks/components/Dialog/ (showcase blocks) @@ -51,6 +52,7 @@ import {layerStructureReset} from '../Layer/layerStructureReset.stylex'; import {LayerContentBoundary} from '../Layer/layerScopedContext'; import {layerClickBoundary} from '../Layer/layerClickBoundary'; import {LayerDepthProvider} from '../Layer/LayerDepthContext'; +import {holdEntranceInput} from '../Layer/holdEntranceInput'; import {useLayerDismissal} from '../Layer/useLayerDismissal'; import {useBackdropPress} from '../Layer/useBackdropPress'; import {useModalOutlet} from '../Layer/modalOutlet'; @@ -642,6 +644,11 @@ export function Dialog({ focusForLastInput(autofocusTarget); } } + // Under a coarse primary pointer, a tap or a drag during the entrance + // reaches nothing. Keys and assistive technology stay live. The hold + // ends with the entrance, or with this effect's cleanup on a close or + // unmount. + return holdEntranceInput(dialog) ?? undefined; } else { if (dialog.open) { dialog.close(); diff --git a/packages/core/src/Dialog/DialogTouchEntrance.test.tsx b/packages/core/src/Dialog/DialogTouchEntrance.test.tsx new file mode 100644 index 0000000000000..398897832e264 --- /dev/null +++ b/packages/core/src/Dialog/DialogTouchEntrance.test.tsx @@ -0,0 +1,143 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +import {act, render, screen} from '@testing-library/react'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {TOUCH_QUERY} from '../utils/touchQueries'; +import {Dialog} from './Dialog'; + +/** Ends the entrance every dialog reports (jsdom runs no CSS animation). */ +let finishEntrance: () => void = () => {}; + +/** The primary pointer: a finger (`coarse`, a touch screen) or a mouse. */ +function stubPointer(coarse: boolean) { + vi.stubGlobal( + 'matchMedia', + vi.fn((query: string) => ({ + matches: coarse && query === TOUCH_QUERY, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + })), + ); +} + +beforeEach(() => { + HTMLDialogElement.prototype.showModal = vi.fn(function ( + this: HTMLDialogElement, + ) { + this.setAttribute('open', ''); + }); + HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) { + this.removeAttribute('open'); + }); + const finished = new Promise(resolve => { + finishEntrance = resolve; + }); + Object.defineProperty(Element.prototype, 'getAnimations', { + configurable: true, + value: () => [ + { + playState: 'running', + finished, + effect: {getComputedTiming: () => ({endTime: 300})}, + }, + ], + }); +}); + +afterEach(() => { + delete (Element.prototype as {getAnimations?: unknown}).getAnimations; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +const noop = () => {}; + +function TestDialog({ + isOpen, + onAct = noop, +}: { + isOpen: boolean; + onAct?: () => void; +}) { + return ( + <> + + {}} aria-label="Held"> + + + + ); +} + +const INIT = {bubbles: true, cancelable: true, composed: true}; + +/** A press and its click, as a browser sends them for `pointerType`. */ +function tap(element: Element, pointerType: string, pointerId: number) { + element.dispatchEvent( + new PointerEvent('pointerdown', {...INIT, pointerId, pointerType}), + ); + element.dispatchEvent( + new PointerEvent('pointerup', {...INIT, pointerId, pointerType}), + ); + element.dispatchEvent( + new PointerEvent('click', {...INIT, pointerType, detail: 1}), + ); +} + +const button = (name: string) => + screen.getByRole('button', {name, hidden: true}); + +describe('Dialog entrance (spec:AST-094 FR35)', () => { + it("holds a finger's tap on its action while it enters, and lets one through once it has entered", async () => { + stubPointer(true); + const onAct = vi.fn(); + render(); + + tap(button('Act'), 'touch', 1); + expect(onAct).not.toHaveBeenCalled(); + + await act(async () => { + finishEntrance(); + await Promise.resolve(); + }); + tap(button('Act'), 'touch', 2); + expect(onAct).toHaveBeenCalledTimes(1); + }); + + it('lets input through again when it closes mid-entrance', () => { + stubPointer(true); + const onAct = vi.fn(); + const view = render(); + + view.rerender(); + tap(button('Outside'), 'touch', 1); + expect(onAct).toHaveBeenCalledTimes(1); + }); + + it("leaves a mouse's click alone, even where the primary pointer is a finger", () => { + stubPointer(true); + const onAct = vi.fn(); + render(); + + tap(button('Act'), 'mouse', 1); + expect(onAct).toHaveBeenCalledTimes(1); + }); + + it("holds nothing where the primary pointer is a mouse, a finger's tap included (a touchscreen laptop: an implementation gap on FR35's adoption)", () => { + stubPointer(false); + const onAct = vi.fn(); + render(); + + tap(button('Act'), 'touch', 1); + expect(onAct).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/core/src/Dialog/__tests__/DialogTouchEntrance.interaction.browser.spec.ts b/packages/core/src/Dialog/__tests__/DialogTouchEntrance.interaction.browser.spec.ts new file mode 100644 index 0000000000000..553dad7d13967 --- /dev/null +++ b/packages/core/src/Dialog/__tests__/DialogTouchEntrance.interaction.browser.spec.ts @@ -0,0 +1,452 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file DialogTouchEntrance.interaction.browser.spec.ts + * @input The built Dialog stories "Purpose Info" and "Scrolling Content" and + * the AlertDialog story "Delete", real touch input through the interaction + * harness in its phone context, and a mouse there and on a fine-pointer + * page + * @output Browser evidence for spec:AST-094 FR35 on Dialog: under a finger, a + * tap or a drag that lands while the dialog is still entering closes + * nothing, runs no action, moves no focus and scrolls nothing, and the + * dialog finishes entering and stays open; keys stay live and the content + * stays in the accessibility tree meanwhile; an alert's entrance holds its + * action alike. With a mouse, a click during the entrance acts as before: + * on a touch screen the hold decides by each event's pointer, and a press + * where the mouse already rests acts once the page last heard a mouse; + * under a fine primary pointer nothing is held. + * @position Browser proof for Dialog's entrance hold (Dialog.tsx, through the + * Layer module's holdEntranceInput); the hold itself is proven in + * Layer/__tests__/inputHold.interaction.browser.spec.ts + * + * Each case slows the entrance to a minute before opening (a machine as busy + * as a 3-CPU runner can play a normal one out before a case looks) and holds + * it where it is (holdAnimations), so every touch lands while the dialog is + * still entering; the slowing then goes, so the exit keeps its own timing, + * and finishing the entrance ends it at once. + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + drag, + frames, + holdAnimations, + openStory, + releaseAnimations, + touchDriver, + withStorybook, + type TouchDriver, +} from '@astryxdesign/interaction-harness'; + +const storybook = withStorybook(test); + +type Point = {x: number; y: number}; + +const INFO = 'core-dialog--purpose-info'; +const SCROLLING = 'core-dialog--scrolling-content'; +const ALERT = 'core-alertdialog--delete'; + +/** A point on the backdrop: the top of the viewport, above the dialog. */ +const BACKDROP: Point = {x: 201, y: 6}; + +async function centerOf(locator: Locator): Promise { + const box = await locator.boundingBox(); + if (box == null) { + throw new Error('the element did not render'); + } + return { + x: Math.round(box.x + box.width / 2), + y: Math.round(box.y + box.height / 2), + }; +} + +const openDialogs = (page: Page) => page.locator('dialog[open]'); + +/** Waits until the open dialog's entrance is running, then holds it there. */ +async function holdEntrance(page: Page): Promise { + await page.waitForFunction( + () => + document + .querySelector('dialog[open]') + ?.getAnimations() + .some(animation => animation.playState === 'running') ?? false, + ); + const held = await holdAnimations(page, openDialogs(page)); + // Held: later transitions (an exit, the next open) keep their own timing. + await page.evaluate(() => + document.getElementById('__slowEntrance')?.remove(), + ); + expect(held.length, 'the dialog is still entering').toBeGreaterThan(0); +} + +/** + * Slows the next entrance to a minute, so the dialog is still entering when a + * case holds it however busy the machine is; holdEntrance and + * finishEntrance take the slowing away again. + */ +async function slowNextEntrance(page: Page): Promise { + await page.evaluate(() => { + const style = document.createElement('style'); + style.id = '__slowEntrance'; + style.textContent = + 'dialog, dialog *, dialog::backdrop { transition-duration: 60s !important; animation-duration: 60s !important; }'; + document.head.append(style); + }); +} + +/** Ends the entrance at once, held or not. */ +async function finishEntrance(page: Page): Promise { + await releaseAnimations(page, {finish: true}); + await openDialogs(page).evaluate(async dialog => { + document.getElementById('__slowEntrance')?.remove(); + // An entrance no case held (opened only to be finished) ends here too. + for (const animation of dialog.getAnimations()) { + const end = animation.effect?.getComputedTiming().endTime; + if (typeof end === 'number' && Number.isFinite(end)) { + animation.finish(); + } + } + await Promise.all( + dialog.getAnimations().map(async animation => + animation.finished.catch((error: unknown) => { + // A canceled animation's `finished` rejects with an AbortError: + // it ended. Anything else is a failure, and it surfaces. + if (!(error instanceof DOMException && error.name === 'AbortError')) { + throw error; + } + }), + ), + ); + }); + await frames(page); +} + +/** Opens the story's dialog with a tap and holds its entrance midway. */ +async function openMidEntrance( + page: Page, + story: string, + opener: string, +): Promise { + await openStory(page, storybook(), story); + await slowNextEntrance(page); + const driver = await touchDriver(page); + await driver.tap(await centerOf(page.getByRole('button', {name: opener}))); + await holdEntrance(page); + return driver; +} + +/** + * Records every touch the page receives, and whether the browser took one to + * pan something (a `pointercancel`): a window capture listener added before + * the page's own scripts, so it sees a touch even when the input hold stops + * it there. Install it before opening the story. + */ +async function installTouchProbe(page: Page): Promise { + await page.addInitScript(() => { + const seen: string[] = []; + (window as unknown as {__touchProbe: string[]}).__touchProbe = seen; + for (const type of [ + 'touchstart', + 'touchmove', + 'touchend', + 'touchcancel', + 'pointercancel', + ]) { + window.addEventListener(type, () => seen.push(type), { + capture: true, + passive: true, + }); + } + }); +} + +/** What the probe saw since the last read, emptying it. */ +const takeTouchProbe = async (page: Page) => + page.evaluate(() => { + const seen = (window as unknown as {__touchProbe: string[]}).__touchProbe; + return seen.splice(0); + }); + +/** + * Plays one drag and returns what the page received: its touch events, and + * whether the browser took the touch to pan something (a `pointercancel`). + * A drag the page never received shows here, so it cannot pass as one that + * scrolled nothing. + */ +async function playDrag( + page: Page, + driver: TouchDriver, + script: Parameters[0], +): Promise<{received: string[]; panned: boolean}> { + await takeTouchProbe(page); + await driver.play(script); + await frames(page, 4); + const seen = await takeTouchProbe(page); + return { + received: seen.filter(type => type.startsWith('touch')), + panned: seen.includes('pointercancel'), + }; +} + +/** The whole drag reached the page: a touchstart, its moves and its touchend. */ +function expectDelivered(played: {received: string[]}): void { + expect(played.received[0], 'the drag reached the page').toBe('touchstart'); + expect(played.received).toContain('touchmove'); + expect(played.received.at(-1)).toBe('touchend'); +} + +/** What has focus: its tag and accessible name. */ +const focusedElement = async (page: Page) => + page.evaluate(() => { + const element = document.activeElement; + if (element == null) { + return 'none'; + } + const name = + element.getAttribute('aria-label') ?? element.textContent?.trim() ?? ''; + return `${element.tagName.toLowerCase()}:${name.slice(0, 40)}`; + }); + +test.describe('under a finger (spec:AST-094 FR35)', () => { + test('a tap on the backdrop while the dialog enters closes nothing, and once it has entered the same tap closes it', async ({ + page, + }) => { + const driver = await openMidEntrance(page, INFO, 'Open Info Modal'); + + await driver.tap(BACKDROP); + await frames(page); + await expect(openDialogs(page)).toHaveCount(1); + + await finishEntrance(page); + await expect(page.getByRole('dialog', {name: 'Information'})).toBeVisible(); + + await driver.tap(BACKDROP); + await expect(openDialogs(page)).toHaveCount(0); + }); + + test('a tap on an action while the dialog enters runs nothing and moves no focus', async ({ + page, + }) => { + const driver = await openMidEntrance(page, INFO, 'Open Info Modal'); + const action = page.getByRole('button', {name: 'Got it'}); + // Focus starts inside the dialog, where opening it put it. + expect( + await openDialogs(page).evaluate(dialog => + dialog.contains(document.activeElement), + ), + ).toBe(true); + const focused = await focusedElement(page); + + await driver.tap(await centerOf(action)); + await frames(page); + await expect(openDialogs(page)).toHaveCount(1); + expect(await focusedElement(page)).toBe(focused); + + await finishEntrance(page); + await expect(openDialogs(page)).toHaveCount(1); + + await driver.tap(await centerOf(action)); + await expect(openDialogs(page)).toHaveCount(0); + }); + + test('a drag while the dialog enters scrolls nothing, and once it has entered the same drag scrolls its content', async ({ + page, + browserName, + }) => { + test.skip( + browserName === 'webkit', + 'needs native scrolling from injected touches (the WebKit driver has none)', + ); + await installTouchProbe(page); + const driver = await openMidEntrance( + page, + SCROLLING, + 'Open Scrolling Modal', + ); + // The dialog's own scroller: its content area. + const content = await openDialogs(page).evaluateHandle(dialog => { + for (const element of dialog.querySelectorAll('*')) { + const {overflowY} = getComputedStyle(element); + if ( + (overflowY === 'auto' || overflowY === 'scroll') && + element.scrollHeight > element.clientHeight + ) { + return element; + } + } + throw new Error('the dialog has no scrolling content'); + }); + const box = await content.asElement()?.boundingBox(); + if (box == null) { + throw new Error('the content did not render'); + } + const x = Math.round(box.x + box.width / 2); + const up = drag( + {x, y: Math.round(box.y + box.height * 0.8)}, + {x, y: Math.round(box.y + box.height * 0.2)}, + // A rest before the lift: no fling outlives the pan. + {durationMs: 200, restMs: 150}, + ); + const scrollTop = async () => + content.evaluate(element => element.scrollTop); + + const held = await playDrag(page, driver, up); + expectDelivered(held); + expect(held.panned, 'the browser panned nothing').toBe(false); + expect(await scrollTop()).toBe(0); + await expect(openDialogs(page)).toHaveCount(1); + + await finishEntrance(page); + const free = await playDrag(page, driver, up); + expectDelivered(free); + expect(free.panned, 'the browser took the drag to scroll').toBe(true); + expect(await scrollTop()).toBeGreaterThan(0); + }); + + test("a tap on an alert's action while it enters runs nothing, and once it has entered the same tap runs it", async ({ + page, + }) => { + const driver = await openMidEntrance(page, ALERT, 'Delete item'); + const action = page.getByRole('button', {name: 'Delete', exact: true}); + + await driver.tap(await centerOf(action)); + await frames(page); + await expect(openDialogs(page)).toHaveCount(1); + + await finishEntrance(page); + await expect(openDialogs(page)).toHaveCount(1); + + await driver.tap(await centerOf(action)); + await expect(openDialogs(page)).toHaveCount(0); + }); + + test('keys and assistive technology stay live while the dialog enters', async ({ + page, + }) => { + await openMidEntrance(page, INFO, 'Open Info Modal'); + + // The content stays in the accessibility tree, action included. + const tree = await page + .getByRole('dialog', {name: 'Information'}) + .ariaSnapshot(); + expect(tree).toContain('button "Got it"'); + + // A key acts at once: Escape closes the dialog mid-entrance. + await page.keyboard.press('Escape'); + await expect(openDialogs(page)).toHaveCount(0); + }); +}); + +test.describe('with a mouse on a touch screen', () => { + test('a click on the backdrop while the dialog enters closes it, as before: only a finger is held', async ({ + page, + }) => { + await openMidEntrance(page, INFO, 'Open Info Modal'); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + 'the primary pointer is a finger', + ).toBe(true); + + await page.mouse.click(BACKDROP.x, BACKDROP.y); + await expect(openDialogs(page)).toHaveCount(0); + }); + + test('while the dialog enters, a press where the mouse already rests reaches its action: the page last heard a mouse (spec:AST-094 FR35)', async ({ + page, + }) => { + // Under Reduce Motion the dialog only fades in, so its action stays where + // the mouse rests. + await page.emulateMedia({reducedMotion: 'reduce'}); + await openStory(page, storybook(), INFO); + const opener = page.getByRole('button', {name: 'Open Info Modal'}); + // A first presentation, which a mouse opens and a key closes, finds where + // the action appears. + await opener.click(); + await expect(openDialogs(page)).toHaveCount(1); + await finishEntrance(page); + const action = await centerOf(page.getByRole('button', {name: 'Got it'})); + await page.keyboard.press('Escape'); + await expect(openDialogs(page)).toHaveCount(0); + // The mouse comes to rest where the action appears; a key opens the + // dialog again. + await page.mouse.move(action.x - 40, action.y); + await page.mouse.move(action.x, action.y, {steps: 4}); + // What each click lands on, heard first, before any hold. + await page.evaluate(() => { + const clicks: string[] = []; + (window as unknown as {__clicks: string[]}).__clicks = clicks; + window.addEventListener( + 'click', + event => { + const target = event.target as Element; + clicks.push(target.closest('button')?.textContent?.trim() ?? ''); + }, + {capture: true}, + ); + }); + await slowNextEntrance(page); + await opener.focus(); + await page.keyboard.press('Enter'); + await holdEntrance(page); + + const clicks = async () => + page.evaluate(() => (window as unknown as {__clicks: string[]}).__clicks); + await expect(openDialogs(page)).toHaveCount(1); + await expect(page.getByRole('button', {name: 'Got it'})).toBeVisible(); + // A press where the mouse already is, with no movement first. The page's + // input stream heard the mouse move last, so the hold lets it through, + // and it reaches the action (after the key's own click on the opener). + await page.mouse.down(); + await page.mouse.up(); + await expect.poll(clicks).toEqual(['Open Info Modal', 'Got it']); + await expect(openDialogs(page)).toHaveCount(0); + }); +}); + +test.describe('with a mouse', () => { + test.use({hasTouch: false, isMobile: false}); + + test('a click on the backdrop while the dialog enters closes it, as before', async ({ + page, + }) => { + await openStory(page, storybook(), INFO); + await slowNextEntrance(page); + await page.getByRole('button', {name: 'Open Info Modal'}).click(); + await holdEntrance(page); + + await page.mouse.click(BACKDROP.x, BACKDROP.y); + await expect(openDialogs(page)).toHaveCount(0); + }); + + test('a press where the mouse already rests closes the dialog from its backdrop while it enters: under a fine primary pointer nothing is held (spec:AST-094 FR35, FR24)', async ({ + page, + }) => { + await openStory(page, storybook(), INFO); + // The mouse comes to rest on the backdrop's spot before the dialog + // opens, and a key opens it: no move happens during the entrance. + await page.mouse.move(BACKDROP.x, BACKDROP.y); + await slowNextEntrance(page); + await page.getByRole('button', {name: 'Open Info Modal'}).focus(); + await page.keyboard.press('Enter'); + await holdEntrance(page); + // The dialog is up and painted, still entering ... + await expect(openDialogs(page)).toHaveCount(1); + expect( + (await openDialogs(page).boundingBox())?.height ?? 0, + ).toBeGreaterThan(0); + // ... and nothing holds it: no shield. + await expect( + page.locator('dialog[open] > [popover]'), + 'no input hold, so no shield', + ).toHaveCount(0); + + await page.mouse.down(); + await page.mouse.up(); + await expect(openDialogs(page)).toHaveCount(0); + }); +}); diff --git a/packages/core/src/Drawer/Drawer.doc.mjs b/packages/core/src/Drawer/Drawer.doc.mjs index 7b33dd420f52f..f1255467058a9 100644 --- a/packages/core/src/Drawer/Drawer.doc.mjs +++ b/packages/core/src/Drawer/Drawer.doc.mjs @@ -172,7 +172,7 @@ export const docs = { usage: { anatomy, description: - 'A side panel that floats above page content for inspectors and detail views: the "click a table row, see its details" pattern. Unlike a docked panel it overlays the layout instead of reflowing it. Works on desktop and touch: the width budget applies on desktop and the panel preserves a 56px page reveal below 640px without exceeding the width budget. Escape closes the drawer (unless purpose is required) and focus returns to the element that opened it. Entry/exit slide animation respects prefers-reduced-motion. Stacking contract: sibling drawers stack last-opened on top, Escape closes only the topmost, and closing peels innermost-first; render them as siblings, never nested.\n\nLike Dialog, the drawer is a container: its content area is inset by --spacing-4 (16px) by default, by the padding prop, or by a theme\'s padding on drawer. Compose the header, body, and footer the way Dialog does, with a Layout: DrawerHeader in the header slot (it shows a close button when you pass it onOpenChange, like DialogHeader), the body in LayoutContent, and actions in LayoutFooter. The Layout redistributes the inset to those regions so they line up on one content line, and the header is not inset twice. A lone Section child also escapes the inset. Drawer renders no close button of its own, so give every drawer a visible way to close, especially a non-modal one, which has no scrim to click. Put data-autofocus on the control that should receive focus on open.\n\nChoosing a surface: use Dialog for a centered decision or short form, Drawer for full-height side detail that keeps the page in sight, BottomSheet for block-axis sheets on touch, and a docked panel (a layout column) when content should reflow the page instead of floating over it.\n\nTheming: the panel is the single stable target (astryx-drawer, with data-side reflecting side), and the scrim is the panel\'s native ::backdrop. DrawerHeader exposes astryx-drawer-header targets for its row, slots, and close icon.', + 'A side panel that floats above page content for inspectors and detail views: the "click a table row, see its details" pattern. Unlike a docked panel it overlays the layout instead of reflowing it. Works on desktop and touch: the width budget applies on desktop and the panel preserves a 56px page reveal below 640px without exceeding the width budget. Escape closes the drawer (unless purpose is required) and focus returns to the element that opened it. Entry/exit slide animation respects prefers-reduced-motion. On a phone or tablet (a coarse primary pointer), a tap or a drag that lands while the drawer is still sliding in reaches nothing (for a drawer without a scrim, only one on the panel: the page stays live), and the drawer finishes sliding in; keys and assistive technology stay live, and a mouse or a trackpad still clicks: at once when it was the last pointer used, otherwise once it moves. Stacking contract: sibling drawers stack last-opened on top, Escape closes only the topmost, and closing peels innermost-first; render them as siblings, never nested.\n\nLike Dialog, the drawer is a container: its content area is inset by --spacing-4 (16px) by default, by the padding prop, or by a theme\'s padding on drawer. Compose the header, body, and footer the way Dialog does, with a Layout: DrawerHeader in the header slot (it shows a close button when you pass it onOpenChange, like DialogHeader), the body in LayoutContent, and actions in LayoutFooter. The Layout redistributes the inset to those regions so they line up on one content line, and the header is not inset twice. A lone Section child also escapes the inset. Drawer renders no close button of its own, so give every drawer a visible way to close, especially a non-modal one, which has no scrim to click. Put data-autofocus on the control that should receive focus on open.\n\nChoosing a surface: use Dialog for a centered decision or short form, Drawer for full-height side detail that keeps the page in sight, BottomSheet for block-axis sheets on touch, and a docked panel (a layout column) when content should reflow the page instead of floating over it.\n\nTheming: the panel is the single stable target (astryx-drawer, with data-side reflecting side), and the scrim is the panel\'s native ::backdrop. DrawerHeader exposes astryx-drawer-header targets for its row, slots, and close icon.', bestPractices: [ { guidance: true, diff --git a/packages/core/src/Drawer/DrawerTouchEntrance.test.tsx b/packages/core/src/Drawer/DrawerTouchEntrance.test.tsx new file mode 100644 index 0000000000000..64a73e18eb19e --- /dev/null +++ b/packages/core/src/Drawer/DrawerTouchEntrance.test.tsx @@ -0,0 +1,157 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +import {act, render, screen} from '@testing-library/react'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {TOUCH_QUERY} from '../utils/touchQueries'; +import {Drawer} from './Drawer'; + +/** Ends the slide-in every drawer reports (jsdom runs no CSS transition). */ +let finishEntrance: () => void = () => {}; + +/** The primary pointer: a finger (`coarse`, a touch screen) or a mouse. */ +function stubPointer(coarse: boolean) { + vi.stubGlobal( + 'matchMedia', + vi.fn((query: string) => ({ + matches: coarse && query === TOUCH_QUERY, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + })), + ); +} + +beforeEach(() => { + HTMLDialogElement.prototype.showModal = vi.fn(function ( + this: HTMLDialogElement, + ) { + this.setAttribute('open', ''); + }); + HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) { + this.setAttribute('open', ''); + }); + HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) { + this.removeAttribute('open'); + }); + HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) { + this.removeAttribute('open'); + }); + const finished = new Promise(resolve => { + finishEntrance = resolve; + }); + Object.defineProperty(Element.prototype, 'getAnimations', { + configurable: true, + value: () => [ + { + playState: 'running', + finished, + effect: {getComputedTiming: () => ({endTime: 250})}, + }, + ], + }); +}); + +afterEach(() => { + delete (Element.prototype as {getAnimations?: unknown}).getAnimations; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +const noop = () => {}; + +function TestDrawer({ + isOpen, + hasScrim = true, + onAct = noop, +}: { + isOpen: boolean; + hasScrim?: boolean; + onAct?: () => void; +}) { + return ( + <> + + {}} + label="Held" + hasScrim={hasScrim}> + + + + ); +} + +const INIT = {bubbles: true, cancelable: true, composed: true}; + +/** A press and its click, as a browser sends them for `pointerType`. */ +function tap(element: Element, pointerType: string, pointerId: number) { + element.dispatchEvent( + new PointerEvent('pointerdown', {...INIT, pointerId, pointerType}), + ); + element.dispatchEvent( + new PointerEvent('pointerup', {...INIT, pointerId, pointerType}), + ); + element.dispatchEvent( + new PointerEvent('click', {...INIT, pointerType, detail: 1}), + ); +} + +const button = (name: string) => + screen.getByRole('button', {name, hidden: true}); + +describe('Drawer slide-in (spec:AST-094 FR35)', () => { + it("holds a finger's tap while it slides in, and lets one through once the slide-in ends", async () => { + stubPointer(true); + const onAct = vi.fn(); + render(); + + tap(button('Act'), 'touch', 1); + expect(onAct).not.toHaveBeenCalled(); + + await act(async () => { + finishEntrance(); + await Promise.resolve(); + }); + tap(button('Act'), 'touch', 2); + expect(onAct).toHaveBeenCalledTimes(1); + }); + + it("holds only a non-modal drawer's panel: a finger's tap on the page beside it acts", () => { + stubPointer(true); + const onAct = vi.fn(); + render(); + + tap(button('Act'), 'touch', 1); + expect(onAct).not.toHaveBeenCalled(); + tap(button('Outside'), 'touch', 2); + expect(onAct).toHaveBeenCalledTimes(1); + }); + + it('lets input through again when it closes mid-slide', () => { + stubPointer(true); + const onAct = vi.fn(); + const view = render(); + + view.rerender(); + tap(button('Outside'), 'touch', 1); + expect(onAct).toHaveBeenCalledTimes(1); + }); + + it("leaves a mouse's click alone, even where the primary pointer is a finger", () => { + stubPointer(true); + const onAct = vi.fn(); + render(); + + tap(button('Act'), 'mouse', 1); + expect(onAct).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/core/src/Drawer/__tests__/DrawerTouchEntrance.interaction.browser.spec.ts b/packages/core/src/Drawer/__tests__/DrawerTouchEntrance.interaction.browser.spec.ts new file mode 100644 index 0000000000000..56700c27a3718 --- /dev/null +++ b/packages/core/src/Drawer/__tests__/DrawerTouchEntrance.interaction.browser.spec.ts @@ -0,0 +1,454 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file DrawerTouchEntrance.interaction.browser.spec.ts + * @input The built Drawer stories "Showcase" (modal, with a scrim) and "Row + * Inspector" (non-modal), real touch input through the interaction harness + * in its phone context, and a mouse there and on a fine-pointer page + * @output Browser evidence for spec:AST-094 FR35 on Drawer: under a finger, a + * tap or a drag that lands while the drawer is still sliding in closes + * nothing, runs no action, moves no focus and scrolls nothing, and the + * drawer finishes sliding in and stays open; around a non-modal drawer only + * a tap on the panel is held, and the page stays live; keys stay live and + * the content stays in the accessibility tree meanwhile. With a mouse, a + * click during the slide-in acts as before: on a touch screen the hold + * decides by each event's pointer, and under a fine primary pointer nothing + * is held, a press where the mouse already rests included. + * @position Browser proof for Drawer's entrance hold (useDrawerDialogPresence, + * through the Layer module's holdEntranceInput); the hold itself is proven + * in Layer/__tests__/inputHold.interaction.browser.spec.ts + * + * Each case slows the slide-in to a minute before opening (a machine as busy + * as a 3-CPU runner can play a normal one out before a case looks) and holds + * it where it is (holdAnimations), so every touch lands while the drawer is + * still entering; the slowing then goes, so the exit keeps its own timing, + * and finishing the slide-in ends it at once. + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + drag, + frames, + holdAnimations, + openStory, + releaseAnimations, + seekAnimations, + touchDriver, + withStorybook, + type TouchDriver, +} from '@astryxdesign/interaction-harness'; + +const storybook = withStorybook(test); + +type Point = {x: number; y: number}; + +const MODAL = 'core-drawer--showcase'; +const NON_MODAL = 'core-drawer--row-inspector'; + +/** A point in the strip the drawer leaves free: the scrim, or the page. */ +const STRIP: Point = {x: 20, y: 357}; + +const OPEN = 'dialog[open], dialog:popover-open'; + +async function centerOf(locator: Locator): Promise { + const box = await locator.boundingBox(); + if (box == null) { + throw new Error('the element did not render'); + } + return { + x: Math.round(box.x + box.width / 2), + y: Math.round(box.y + box.height / 2), + }; +} + +const openDrawers = (page: Page) => page.locator(OPEN); + +/** Waits until the open drawer's slide-in is running, then holds it there. */ +async function holdEntrance(page: Page): Promise { + await page.waitForFunction( + selector => + document + .querySelector(selector) + ?.getAnimations() + .some(animation => animation.playState === 'running') ?? false, + OPEN, + ); + const held = await holdAnimations(page, openDrawers(page)); + // Held: later transitions (an exit, the next open) keep their own timing. + await page.evaluate(() => + document.getElementById('__slowEntrance')?.remove(), + ); + expect(held.length, 'the drawer is still sliding in').toBeGreaterThan(0); +} + +/** + * Moves the held slide-in to 30 ms before its end: the panel is nearly in + * place, so a control inside it is on screen, and the drawer is still + * entering. + */ +async function seekNearEnd(page: Page): Promise { + const endMs = await openDrawers(page).evaluate(drawer => + Math.max( + ...drawer + .getAnimations() + .map(animation => + Number(animation.effect?.getComputedTiming().endTime ?? 0), + ), + ), + ); + await seekAnimations(page, endMs - 30); +} + +/** + * Slows the next entrance to a minute, so the drawer is still entering when a + * case holds it however busy the machine is; holdEntrance and + * finishEntrance take the slowing away again. + */ +async function slowNextEntrance(page: Page): Promise { + await page.evaluate(() => { + const style = document.createElement('style'); + style.id = '__slowEntrance'; + style.textContent = + 'dialog, dialog *, dialog::backdrop { transition-duration: 60s !important; animation-duration: 60s !important; }'; + document.head.append(style); + }); +} + +/** Ends the slide-in at once, held or not. */ +async function finishEntrance(page: Page): Promise { + await releaseAnimations(page, {finish: true}); + await openDrawers(page).evaluate(async drawer => { + document.getElementById('__slowEntrance')?.remove(); + // An entrance no case held (opened only to be finished) ends here too. + for (const animation of drawer.getAnimations()) { + const end = animation.effect?.getComputedTiming().endTime; + if (typeof end === 'number' && Number.isFinite(end)) { + animation.finish(); + } + } + await Promise.all( + drawer.getAnimations().map(async animation => + animation.finished.catch((error: unknown) => { + // A canceled animation's `finished` rejects with an AbortError: + // it ended. Anything else is a failure, and it surfaces. + if (!(error instanceof DOMException && error.name === 'AbortError')) { + throw error; + } + }), + ), + ); + }); + await frames(page); +} + +/** Opens the story's drawer with a tap and holds its slide-in midway. */ +async function openMidEntrance( + page: Page, + story: string, + opener: string, +): Promise { + await openStory(page, storybook(), story); + await slowNextEntrance(page); + const driver = await touchDriver(page); + await driver.tap(await centerOf(page.getByRole('button', {name: opener}))); + await holdEntrance(page); + return driver; +} + +/** + * Records every touch the page receives, and whether the browser took one to + * pan something (a `pointercancel`): a window capture listener added before + * the page's own scripts, so it sees a touch even when the input hold stops + * it there. Install it before opening the story. + */ +async function installTouchProbe(page: Page): Promise { + await page.addInitScript(() => { + const seen: string[] = []; + (window as unknown as {__touchProbe: string[]}).__touchProbe = seen; + for (const type of [ + 'touchstart', + 'touchmove', + 'touchend', + 'touchcancel', + 'pointercancel', + ]) { + window.addEventListener(type, () => seen.push(type), { + capture: true, + passive: true, + }); + } + }); +} + +/** What the probe saw since the last read, emptying it. */ +const takeTouchProbe = async (page: Page) => + page.evaluate(() => { + const seen = (window as unknown as {__touchProbe: string[]}).__touchProbe; + return seen.splice(0); + }); + +/** + * Plays one drag and returns what the page received: its touch events, and + * whether the browser took the touch to pan something (a `pointercancel`). + * A drag the page never received shows here, so it cannot pass as one that + * scrolled nothing. + */ +async function playDrag( + page: Page, + driver: TouchDriver, + script: Parameters[0], +): Promise<{received: string[]; panned: boolean}> { + await takeTouchProbe(page); + await driver.play(script); + await frames(page, 4); + const seen = await takeTouchProbe(page); + return { + received: seen.filter(type => type.startsWith('touch')), + panned: seen.includes('pointercancel'), + }; +} + +/** The whole drag reached the page: a touchstart, its moves and its touchend. */ +function expectDelivered(played: {received: string[]}): void { + expect(played.received[0], 'the drag reached the page').toBe('touchstart'); + expect(played.received).toContain('touchmove'); + expect(played.received.at(-1)).toBe('touchend'); +} + +/** What has focus: its tag and accessible name. */ +const focusedElement = async (page: Page) => + page.evaluate(() => { + const element = document.activeElement; + if (element == null) { + return 'none'; + } + const name = + element.getAttribute('aria-label') ?? element.textContent?.trim() ?? ''; + return `${element.tagName.toLowerCase()}:${name.slice(0, 40)}`; + }); + +test.describe('under a finger (spec:AST-094 FR35)', () => { + test('a tap on the scrim while the drawer slides in closes nothing, and once it is in the same tap closes it', async ({ + page, + }) => { + const driver = await openMidEntrance(page, MODAL, 'Open inspector'); + + await driver.tap(STRIP); + await frames(page); + await expect(openDrawers(page)).toHaveCount(1); + + await finishEntrance(page); + await expect( + page.getByRole('dialog', {name: 'Deployment details'}), + ).toBeVisible(); + + await driver.tap(STRIP); + await expect(openDrawers(page)).toHaveCount(0); + }); + + test('a tap on its close button while the drawer slides in runs nothing and moves no focus', async ({ + page, + }) => { + const driver = await openMidEntrance(page, MODAL, 'Open inspector'); + await seekNearEnd(page); + const close = openDrawers(page).getByRole('button', {name: 'Close'}); + const target = await centerOf(close); + expect(target.x, 'the close button is on screen').toBeLessThan( + page.viewportSize()?.width ?? 0, + ); + // Focus starts inside the drawer, on its content area. + expect( + await openDrawers(page).evaluate(drawer => + drawer.contains(document.activeElement), + ), + ).toBe(true); + const focused = await focusedElement(page); + + await driver.tap(target); + await frames(page); + await expect(openDrawers(page)).toHaveCount(1); + expect(await focusedElement(page)).toBe(focused); + + await finishEntrance(page); + await expect(openDrawers(page)).toHaveCount(1); + + await driver.tap(await centerOf(close)); + await expect(openDrawers(page)).toHaveCount(0); + }); + + test('around a non-modal drawer sliding in the page stays live: a drag scrolls it and a tap reaches it, while a tap on the drawer reaches nothing (spec:AST-094 FR35)', async ({ + page, + browserName, + }) => { + test.skip( + browserName === 'webkit', + 'needs native scrolling from injected touches (the WebKit driver has none)', + ); + await installTouchProbe(page); + await openStory(page, storybook(), NON_MODAL); + // A page that scrolls behind the drawer, which leaves it interactive. + await page.evaluate(() => { + const spacer = document.createElement('div'); + spacer.style.height = '300vh'; + document.body.append(spacer); + }); + const driver = await touchDriver(page); + const up = drag( + {x: STRIP.x, y: 600}, + {x: STRIP.x, y: 250}, + // A rest before the lift: no fling outlives the pan. + {durationMs: 200, restMs: 150}, + ); + // Where the visual viewport is in the document. This story's page is + // wider than the phone, so a pan first moves the visual viewport inside + // the layout viewport, which `window.scrollY` does not report. + const pageTop = async () => + page.evaluate(() => { + if (window.visualViewport == null) { + throw new Error('the page has no visual viewport'); + } + return window.visualViewport.pageTop; + }); + + const opener = page.getByRole('button', {name: 'Open drawer'}); + await opener.evaluate(element => element.scrollIntoView({block: 'center'})); + await frames(page, 2); + await slowNextEntrance(page); + await driver.tap(await centerOf(opener)); + await holdEntrance(page); + // The panel nearly in place, so its close button is on screen. + await seekNearEnd(page); + // Every click, split by where it landed: on the page or in the drawer. + await page.evaluate(() => { + const clicks = {page: [] as string[], drawer: [] as string[]}; + (window as unknown as {__clicks: typeof clicks}).__clicks = clicks; + document.addEventListener( + 'click', + event => { + const target = event.target as Element; + const inDrawer = target.closest('dialog') != null; + (inDrawer ? clicks.drawer : clicks.page).push( + target.tagName.toLowerCase(), + ); + }, + {capture: true}, + ); + }); + const clicks = async () => + page.evaluate( + () => + (window as unknown as {__clicks: {page: string[]; drawer: string[]}}) + .__clicks, + ); + + // The drawer and its close button are up and painted. + await expect( + page.getByRole('button', {name: 'Close inspector'}), + ).toBeVisible(); + // A tap on the drawer while it slides in reaches nothing. + await driver.tap( + await centerOf(page.getByRole('button', {name: 'Close inspector'})), + ); + await frames(page); + expect((await clicks()).drawer).toEqual([]); + await expect(openDrawers(page)).toHaveCount(1); + + // The page beside it stays live: a drag scrolls it ... + const before = await pageTop(); + const free = await playDrag(page, driver, up); + expectDelivered(free); + expect(free.panned, 'the browser took the drag to scroll').toBe(true); + expect(await pageTop()).toBeGreaterThan(before); + // ... and a tap reaches it. + await driver.tap(STRIP); + await expect.poll(async () => (await clicks()).page.length).toBe(1); + await expect(openDrawers(page)).toHaveCount(1); + }); + + test('keys and assistive technology stay live while the drawer slides in', async ({ + page, + }) => { + await openMidEntrance(page, MODAL, 'Open inspector'); + + // The content stays in the accessibility tree, close button included. + const tree = await page + .getByRole('dialog', {name: 'Deployment details'}) + .ariaSnapshot(); + expect(tree).toContain('button "Close"'); + + // A key acts at once: Escape closes the drawer mid-slide. + await page.keyboard.press('Escape'); + await expect( + page.getByRole('dialog', {name: 'Deployment details'}), + ).toBeHidden(); + }); +}); + +test.describe('with a mouse on a touch screen', () => { + test('a click on the scrim while the drawer slides in closes it, as before: only a finger is held', async ({ + page, + }) => { + await openMidEntrance(page, MODAL, 'Open inspector'); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + 'the primary pointer is a finger', + ).toBe(true); + + await page.mouse.click(STRIP.x, STRIP.y); + await expect( + page.getByRole('dialog', {name: 'Deployment details'}), + ).toBeHidden(); + }); +}); + +test.describe('with a mouse', () => { + test.use({hasTouch: false, isMobile: false}); + + test('a click on the scrim while the drawer slides in closes it, as before', async ({ + page, + }) => { + await openStory(page, storybook(), MODAL); + await slowNextEntrance(page); + await page.getByRole('button', {name: 'Open inspector'}).click(); + await holdEntrance(page); + + await page.mouse.click(STRIP.x, STRIP.y); + await expect( + page.getByRole('dialog', {name: 'Deployment details'}), + ).toBeHidden(); + }); + + test('a press where the mouse already rests closes the drawer from its scrim while it slides in: under a fine primary pointer nothing is held (spec:AST-094 FR35, FR24)', async ({ + page, + }) => { + await openStory(page, storybook(), MODAL); + // The mouse comes to rest on the scrim's spot before the drawer opens, + // and a key opens it: no move happens during the slide-in. + await page.mouse.move(STRIP.x, STRIP.y); + await slowNextEntrance(page); + await page.getByRole('button', {name: 'Open inspector'}).focus(); + await page.keyboard.press('Enter'); + await holdEntrance(page); + // The drawer is up and painted, still sliding in ... + await expect(openDrawers(page)).toHaveCount(1); + expect((await openDrawers(page).boundingBox())?.width ?? 0).toBeGreaterThan( + 0, + ); + // ... and nothing holds it: no shield. + await expect( + page.locator('dialog[open] > [popover]'), + 'no input hold, so no shield', + ).toHaveCount(0); + + await page.mouse.down(); + await page.mouse.up(); + await expect( + page.getByRole('dialog', {name: 'Deployment details'}), + ).toBeHidden(); + }); +}); diff --git a/packages/core/src/Drawer/useDrawerDialogPresence.ts b/packages/core/src/Drawer/useDrawerDialogPresence.ts index 7279429c89f4e..43f0e435f1037 100644 --- a/packages/core/src/Drawer/useDrawerDialogPresence.ts +++ b/packages/core/src/Drawer/useDrawerDialogPresence.ts @@ -5,7 +5,7 @@ /** * @file useDrawerDialogPresence.ts * @input Controlled open state, modal mode, dialog ref, and rendered-state setter - * @output Coordinates native top-layer presence, exit timing, focus restoration, and unmount cleanup + * @output Coordinates native top-layer presence, the touch entrance's input hold, exit timing, focus restoration, and unmount cleanup * @position Drawer-internal hook; consumed only by Drawer.tsx * * The drawer has two independent notions of presence: @@ -21,6 +21,7 @@ * * SYNC: When modified, update: * - /packages/core/src/Drawer/Drawer.test.tsx + * - /packages/core/src/Drawer/__tests__/DrawerTouchEntrance.interaction.browser.spec.ts * - /.github/scripts/modal-close-visibility.js */ @@ -32,6 +33,7 @@ import { type SetStateAction, } from 'react'; import {flushSync} from 'react-dom'; +import {holdEntranceInput} from '../Layer/holdEntranceInput'; import {notifyTopLayerEntry} from '../Layer/modalOutlet'; import {runPopoverOperation} from '../Layer/popoverOperations'; @@ -149,7 +151,12 @@ export function useDrawerDialogPresence({ // contract as Dialog). dialog.querySelector('[data-autofocus]')?.focus(); } - return; + // Under a coarse primary pointer, a tap or a drag during the slide-in + // reaches nothing. A non-modal drawer holds only its panel, so its page + // stays live. Keys and assistive technology stay live. The hold ends + // with the slide-in, or with this effect's cleanup on a close or + // unmount. + return holdEntranceInput(dialog, {isModal}) ?? undefined; } if (!isDrawerHostOpen(dialog, isModal)) { diff --git a/packages/core/src/Layer/__tests__/inputHold.fixture.ts b/packages/core/src/Layer/__tests__/inputHold.fixture.ts new file mode 100644 index 0000000000000..84cfc1b93f198 --- /dev/null +++ b/packages/core/src/Layer/__tests__/inputHold.fixture.ts @@ -0,0 +1,137 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file inputHold.fixture.ts + * @input Nothing: bundled by esbuild and injected into a blank page + * @output A page whose whole area is a button (`#under`), a modal dialog + * (`#dialog`: text, an action, and a gesture-host tap recognizer on the + * dialog itself, an ancestor of the hold's shield), a light-dismissing + * popover (`#pop`) and a full-viewport layer (`#lift`) whose content and + * tint take the hits while a test may make its root take none, plus + * `window.__hold`: open a layer, hold and + * release it, read what an element at a point is and what lies past a + * hold's shield there, and a log of every + * click, tap recognition and popover toggle + * @position Browser fixture of inputHold.interaction.browser.spec.ts; + * test-only + */ + +import {getGestureHost} from '../../gestures/GestureHost'; +import {TapGestureRecognizer} from '../../gestures/TapGestureRecognizer'; +import {holdInput, isInputShield, type InputHoldScope} from '../inputHold'; + +type LayerId = 'dialog' | 'pop' | 'lift'; + +interface HoldLog { + clicks: string[]; + taps: number; + toggles: string[]; +} + +declare global { + interface Window { + __hold: { + log: HoldLog; + open: (id: LayerId) => void; + hold: (id: LayerId, scope: InputHoldScope) => void; + release: () => void; + hitAt: (x: number, y: number) => string; + hitPast: (x: number, y: number) => string; + }; + } +} + +document.body.style.margin = '0'; +document.body.innerHTML = ` + + +

Delete this item?

+ +
+
+ +
+ `; + +function element(id: string): HTMLElement { + const found = document.getElementById(id); + if (found == null) { + throw new Error(`missing #${id}`); + } + return found; +} + +const log: HoldLog = {clicks: [], taps: 0, toggles: []}; + +document.addEventListener( + 'click', + event => { + const target = event.target; + if (target instanceof Element) { + const button = target.closest('button'); + if (button != null) { + log.clicks.push(button.id); + } + } + }, + true, +); +element('pop').addEventListener('toggle', event => { + log.toggles.push(`pop:${event.newState}`); +}); + +// A recognizer on the dialog itself sees every touch inside it, the hold's +// shield included: only the gesture host's touch gate keeps it away. +const tap = new TapGestureRecognizer({name: 'dialogTap'}); +tap.addTransitionListener((_current, _from, to) => { + if (to === 'ended') { + log.taps += 1; + } +}); +getGestureHost(document).attach(element('dialog'), tap); + +let release: (() => void) | null = null; + +window.__hold = { + log, + open(id) { + if (id === 'dialog') { + (element('dialog') as HTMLDialogElement).showModal(); + } else if (id === 'pop') { + element('pop').showPopover(); + } else { + element('lift').style.display = 'block'; + } + }, + hold(id, scope) { + release = holdInput(element(id), { + until: new Promise(() => {}), + scope, + }); + }, + release() { + release?.(); + release = null; + }, + hitAt(x, y) { + return describe(document.elementFromPoint(x, y)); + }, + hitPast(x, y) { + return describe( + document.elementsFromPoint(x, y).find(el => !isInputShield(el)) ?? null, + ); + }, +}; + +function describe(hit: Element | null): string { + if (hit == null) { + return 'nothing'; + } + if (isInputShield(hit)) { + return `shield:${hit.parentElement?.id ?? ''}`; + } + return hit.id !== '' ? hit.id : hit.tagName.toLowerCase(); +} diff --git a/packages/core/src/Layer/__tests__/inputHold.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/inputHold.interaction.browser.spec.ts new file mode 100644 index 0000000000000..cb39c9c83f943 --- /dev/null +++ b/packages/core/src/Layer/__tests__/inputHold.interaction.browser.spec.ts @@ -0,0 +1,572 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file inputHold.interaction.browser.spec.ts + * @input The input-hold fixture bundled with esbuild, a phone-sized + * touch screen, and real engine touch input (touchDriver) + * @output Browser proof of what the unit tests cannot see: the hold's shield + * is the hit target over the whole viewport, above a modal dialog in the + * top layer; a tap during a hold reaches no click and no recognizer on the + * layer (the gesture host's touch gate) and leaves a light-dismissing + * popover open; a mouse the page heard last passes a presentation's hold, + * and after a finger a mouse press meets its shield to the press's end; a + * layer root that takes no hits itself (pointer-events: + * none, or visibility: hidden, its content opting back in) is held all the + * same; keys still act during a presentation's input hold; a dismissal's + * hold makes the content inert and moves focus out of it, so no key acts + * on it either (a focused button that turns inert still takes Enter and + * Space in both engines); each release gives input back; a hit test + * that skips shields (isInputShield) finds what lies beneath, and + * a layer above the held one still wins; a one-finger + * pan on the shield scrolls nothing while a pinch on it still zooms the + * page (spec:AST-094 FR10, FR18, FR35; Chromium, which pinch-zooms from + * injected touches) + * @position Browser tests of packages/core/src/Layer/inputHold.ts, run + * by the interaction project (`pnpm test:interaction inputHold`) + */ + +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {build} from 'esbuild'; +import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright'; +import { + drag, + pinch, + touchDriver, + type TouchDriver, +} from '@astryxdesign/interaction-harness'; + +type Point = {x: number; y: number}; +type Scope = 'viewport' | 'layer'; +type LayerId = 'dialog' | 'pop' | 'lift'; + +interface HoldApi { + log: {clicks: string[]; taps: number; toggles: string[]}; + open: (id: LayerId) => void; + hold: (id: LayerId, scope: Scope) => void; + release: () => void; + hitAt: (x: number, y: number) => string; + hitPast: (x: number, y: number) => string; +} + +let bundle = ''; + +/** What the page throws during a case, a listener's included: none is expected. */ +let pageErrors: string[] = []; +test.beforeEach(({page}) => { + pageErrors = []; + page.on('pageerror', error => { + pageErrors.push(error.message); + }); +}); +test.afterEach(() => { + expect(pageErrors).toEqual([]); +}); + +test.beforeAll(async () => { + const result = await build({ + entryPoints: [ + path.join( + path.dirname(fileURLToPath(import.meta.url)), + 'inputHold.fixture.ts', + ), + ], + bundle: true, + write: false, + format: 'iife', + platform: 'browser', + target: 'es2022', + }); + bundle = result.outputFiles[0].text; +}); + +async function load(page: Page): Promise { + // A real navigation first: touch emulation exposes the Touch Events API to + // documents it creates. + await page.goto('about:blank'); + await page.setContent( + '', + ); + await page.addScriptTag({content: bundle}); + return touchDriver(page); +} + +type HoldWindow = {__hold: HoldApi}; + +const open = async (page: Page, id: LayerId) => + page.evaluate(layer => { + (window as unknown as HoldWindow).__hold.open(layer); + }, id); +const hold = async (page: Page, id: LayerId, scope: Scope) => + page.evaluate( + ([layer, how]) => { + (window as unknown as HoldWindow).__hold.hold(layer, how); + }, + [id, scope] as const, + ); +const release = async (page: Page) => + page.evaluate(() => { + (window as unknown as HoldWindow).__hold.release(); + }); +const hitAt = async (page: Page, point: Point) => + page.evaluate( + at => (window as unknown as HoldWindow).__hold.hitAt(at.x, at.y), + point, + ); +const hitPast = async (page: Page, point: Point) => + page.evaluate( + at => (window as unknown as HoldWindow).__hold.hitPast(at.x, at.y), + point, + ); +const readLog = async (page: Page) => + page.evaluate(() => (window as unknown as HoldWindow).__hold.log); + +async function centre(page: Page, id: string): Promise { + const box = await page.locator(`#${id}`).boundingBox(); + if (box == null) { + throw new Error(`#${id} has no box`); + } + return {x: box.x + box.width / 2, y: box.y + box.height / 2}; +} + +// A tap's click (or its recognition) lands within a few frames. +const settle = async (page: Page) => page.waitForTimeout(250); + +test("during a presentation's input hold on a modal dialog, a tap on it or beside it reaches nothing, keys still act, and the release gives touch back", async ({ + page, +}) => { + const driver = await load(page); + await open(page, 'dialog'); + const action = await centre(page, 'action'); + const message = await centre(page, 'message'); + const beside = {x: 12, y: 12}; + await hold(page, 'dialog', 'viewport'); + // The shield is what a touch hits, on the dialog and over its backdrop. + expect(await hitAt(page, action)).toBe('shield:dialog'); + expect(await hitAt(page, beside)).toBe('shield:dialog'); + await driver.tap(action); + await driver.tap(message); + await settle(page); + // No click, and the recognizer on the dialog saw nothing: the gate. + expect(await readLog(page)).toEqual({clicks: [], taps: 0, toggles: []}); + // Keys still act during a presentation's input hold. + await page.locator('#action').focus(); + await page.keyboard.press('Enter'); + await expect + .poll(async () => (await readLog(page)).clicks) + .toEqual(['action']); + await release(page); + expect(await hitAt(page, action)).toBe('action'); + expect(await hitAt(page, beside)).toBe('dialog'); + await driver.tap(message); + await expect.poll(async () => (await readLog(page)).taps).toBe(1); +}); + +test("a mouse on a touch screen keeps today's behavior during a presentation's hold: the dialog's recognizer takes its press, as with no hold, while a finger's tap before it and right after it is held (spec:AST-094 FR35)", async ({ + page, +}) => { + const driver = await load(page); + await open(page, 'dialog'); + const action = await centre(page, 'action'); + await hold(page, 'dialog', 'viewport'); + await driver.tap(action); + await settle(page); + expect(await readLog(page)).toEqual({clicks: [], taps: 0, toggles: []}); + // A mouse or a trackpad on the same touch screen moves to the action and + // presses it: the shield lets it through and the gesture host's gate + // passes it, so the recognizer on the dialog takes it, as with no hold. + await page.mouse.move(action.x - 40, action.y); + await page.mouse.move(action.x, action.y, {steps: 4}); + await page.mouse.down(); + await page.mouse.up(); + await expect.poll(async () => (await readLog(page)).taps).toBe(1); + // A finger right after it is held again. + await driver.tap(action); + await settle(page); + expect(await readLog(page)).toEqual({clicks: [], taps: 1, toggles: []}); + await release(page); + await driver.tap(action); + await expect.poll(async () => (await readLog(page)).taps).toBe(2); +}); + +test("a mouse clicks a held light-dismissing popover's action, and a click outside dismisses it, as with no hold, while a finger's tap outside between them is held and leaves it open (spec:AST-094 FR35)", async ({ + page, +}) => { + const driver = await load(page); + await open(page, 'pop'); + const action = await centre(page, 'popAction'); + const viewport = page.viewportSize(); + if (viewport == null) { + throw new Error('no viewport'); + } + const outside = {x: viewport.width / 2, y: viewport.height - 40}; + const isOpen = async () => + page.evaluate(() => + document.getElementById('pop')?.matches(':popover-open'), + ); + await hold(page, 'pop', 'viewport'); + // A mouse moves to the popover's action and clicks it: the click lands. + await page.mouse.move(action.x - 40, action.y); + await page.mouse.move(action.x, action.y, {steps: 4}); + await page.mouse.down(); + await page.mouse.up(); + await expect + .poll(async () => (await readLog(page)).clicks) + .toEqual(['popAction']); + // A finger's tap outside while the shield lets the mouse through is still + // held, and its release stays the hold's, so the browser's light dismiss + // leaves the popover open. + await page.mouse.move(outside.x, outside.y - 40, {steps: 4}); + await driver.tap(outside); + await settle(page); + expect(await isOpen()).toBe(true); + expect(await readLog(page)).toEqual({ + clicks: ['popAction'], + taps: 0, + toggles: ['pop:open'], + }); + // The mouse moves again and clicks outside: the popover light-dismisses + // and the page takes the click, as with no hold. + await page.mouse.move(outside.x, outside.y, {steps: 4}); + await page.mouse.down(); + await page.mouse.up(); + await expect + .poll(async () => (await readLog(page)).toggles) + .toEqual(['pop:open', 'pop:closed']); + expect((await readLog(page)).clicks).toEqual(['popAction', 'under']); +}); + +/** Records where each `pointerup` and `click` lands: the shield, or an id. */ +async function recordLandings(page: Page): Promise<() => Promise> { + await page.evaluate(() => { + const seen: string[] = []; + (window as unknown as {__seen: string[]}).__seen = seen; + for (const type of ['pointerup', 'click']) { + window.addEventListener( + type, + event => { + const target = event.target as Element; + const name = + target.hasAttribute('popover') && target.id === '' + ? 'shield' + : target.id === '' + ? target.tagName.toLowerCase() + : target.id; + seen.push(`${type}:${name}`); + }, + true, + ); + } + }); + return async () => + page.evaluate(() => (window as unknown as {__seen: string[]}).__seen); +} + +test("a mouse the page heard last passes a presentation's hold at once: a press where it rests reaches the dialog's recognizer, as with no hold (spec:AST-094 FR35)", async ({ + page, +}) => { + await load(page); + await open(page, 'dialog'); + const action = await centre(page, 'action'); + // The mouse comes to rest over the action before the hold. The gesture + // host hears its moves through the page's input stream. + await page.mouse.move(action.x - 40, action.y); + await page.mouse.move(action.x, action.y, {steps: 4}); + const landings = await recordLandings(page); + await hold(page, 'dialog', 'viewport'); + await page.mouse.down(); + await page.mouse.up(); + await expect.poll(async () => (await readLog(page)).taps).toBe(1); + expect(await landings()).toEqual(['pointerup:action', 'click:action']); +}); + +test("after a finger, a mouse press made before the mouse moves meets a presentation's shield to its end: its release and click land on the shield and reach nothing, and once the mouse moves its press reaches the dialog's recognizer (spec:AST-094 FR35)", async ({ + page, +}) => { + const driver = await load(page); + await open(page, 'dialog'); + const action = await centre(page, 'action'); + const message = await centre(page, 'message'); + await page.mouse.move(action.x - 40, action.y); + await page.mouse.move(action.x, action.y, {steps: 4}); + // A finger is the page's last pointer: it taps the dialog's text, which + // the recognizer on the dialog counts. + await driver.tap(message); + await expect.poll(async () => (await readLog(page)).taps).toBe(1); + const landings = await recordLandings(page); + await hold(page, 'dialog', 'viewport'); + await page.mouse.down(); + await page.mouse.up(); + await settle(page); + expect(await landings()).toEqual(['pointerup:shield', 'click:shield']); + expect(await readLog(page)).toEqual({clicks: [], taps: 1, toggles: []}); + // The mouse moves: its next press reaches the dialog's recognizer, as with + // no hold. + await page.mouse.move(action.x + 4, action.y, {steps: 4}); + await page.mouse.down(); + await page.mouse.up(); + await expect.poll(async () => (await readLog(page)).taps).toBe(2); +}); + +test('a touch that lands during a hold and lifts after its release reaches nothing to its end: no release, end or click lands anywhere, and the next tap clicks (spec:AST-094 FR35)', async ({ + page, +}) => { + const driver = await load(page); + await open(page, 'pop'); + const action = await centre(page, 'popAction'); + await hold(page, 'pop', 'viewport'); + await page.evaluate(() => { + const seen: string[] = []; + (window as unknown as {__seen: string[]}).__seen = seen; + // Everything of the touch that reaches the document: a held touch never + // does, from its start (which proves it landed under the hold) to its + // end. + for (const type of [ + 'touchstart', + 'touchmove', + 'pointerup', + 'touchend', + 'click', + ]) { + document.addEventListener( + type, + event => { + const target = event.target as Element; + seen.push( + `${type}:${target.id === '' ? target.tagName.toLowerCase() : target.id}`, + ); + }, + true, + ); + } + }); + // A drag that lands during the hold and is still moving when it releases: + // the release runs between two of its moves, a third of the way in (the + // driver dispatches each step, then runs onEvent, before the next). + let released = false; + await driver.play( + drag(action, {x: action.x, y: action.y + 120}, {durationMs: 760, hz: 60}), + { + onEvent: async step => { + if (!released && step.type === 'touchMove' && step.t >= 250) { + released = true; + await release(page); + } + }, + }, + ); + expect(released).toBe(true); + await settle(page); + expect( + await page.evaluate(() => (window as unknown as {__seen: string[]}).__seen), + ).toEqual([]); + expect(await readLog(page)).toEqual({ + clicks: [], + taps: 0, + toggles: ['pop:open'], + }); + // The next tap is the layer's: its click lands. + await driver.tap(action); + await expect + .poll(async () => (await readLog(page)).clicks) + .toEqual(['popAction']); +}); + +test('while a dismissal holds it, its content is inert, focus and keys leave it, and the shield still takes every tap; the release restores both', async ({ + page, +}) => { + const driver = await load(page); + await open(page, 'dialog'); + const action = await centre(page, 'action'); + const message = await centre(page, 'message'); + // The dialog moved focus to its action when it opened. + expect(await page.evaluate(() => document.activeElement?.id ?? null)).toBe( + 'action', + ); + await hold(page, 'dialog', 'layer'); + // A key reaches nothing: the focused action left the inert content. + await page.keyboard.press('Enter'); + await page.keyboard.press('Space'); + await settle(page); + expect((await readLog(page)).clicks).toEqual([]); + // An inert subtree is no hit target: the shield, in the dialog, is. + expect(await hitAt(page, action)).toBe('shield:dialog'); + const state = async () => + page.evaluate(() => { + const button = document.getElementById('action'); + button?.focus(); + return { + inert: button?.closest('[inert]') != null, + focused: document.activeElement === button, + }; + }); + expect(await state()).toEqual({inert: true, focused: false}); + await driver.tap(action); + await driver.tap(message); + await settle(page); + expect(await readLog(page)).toEqual({clicks: [], taps: 0, toggles: []}); + await release(page); + expect(await state()).toEqual({inert: false, focused: true}); + expect(await hitAt(page, action)).toBe('action'); + await driver.tap(message); + await expect.poll(async () => (await readLog(page)).taps).toBe(1); +}); + +test('a light-dismissing popover stays open when a hold takes a tap outside it; after the release the same tap dismisses it', async ({ + page, +}) => { + const driver = await load(page); + await open(page, 'pop'); + const viewport = page.viewportSize(); + if (viewport == null) { + throw new Error('no viewport'); + } + const outside = {x: viewport.width / 2, y: viewport.height - 40}; + expect(await hitAt(page, outside)).toBe('under'); + await hold(page, 'pop', 'viewport'); + expect(await hitAt(page, outside)).toBe('shield:pop'); + await driver.tap(outside); + await settle(page); + expect( + await page.evaluate(() => + document.getElementById('pop')?.matches(':popover-open'), + ), + ).toBe(true); + expect(await readLog(page)).toEqual({ + clicks: [], + taps: 0, + toggles: ['pop:open'], + }); + await release(page); + await driver.tap(outside); + await expect + .poll(async () => (await readLog(page)).toggles) + .toEqual(['pop:open', 'pop:closed']); +}); + +test('a hit test that skips shields sees past a hold: under a held modal dialog’s shield, its own action', async ({ + page, +}) => { + await load(page); + await open(page, 'dialog'); + const action = await centre(page, 'action'); + await hold(page, 'dialog', 'viewport'); + // The opening finger's press resolves its row past the shield. + expect(await hitAt(page, action)).toBe('shield:dialog'); + expect(await hitPast(page, action)).toBe('action'); + await release(page); + expect(await hitAt(page, action)).toBe('action'); +}); + +test('a layer opened above a held one is what that hit test finds, and past the shield the held layer’s content', async ({ + page, +}) => { + await load(page); + await open(page, 'lift'); + const liftAction = await centre(page, 'liftAction'); + await hold(page, 'lift', 'viewport'); + expect(await hitAt(page, liftAction)).toBe('shield:lift'); + expect(await hitPast(page, liftAction)).toBe('liftAction'); + await open(page, 'pop'); + const popAction = await centre(page, 'popAction'); + expect(await hitAt(page, popAction)).toBe('popAction'); + expect(await hitPast(page, popAction)).toBe('popAction'); +}); + +// A full-viewport layer whose root takes no hits itself and lets its tint +// and content take them (ContextMenu's lift layer is pointer-events: none): +// the shield, inside that root, must not inherit that. +for (const rootStyle of ['pointer-events: none', 'visibility: hidden']) { + test(`a layer root with ${rootStyle} (its content opting back in) is held all the same: a tap reaches neither the content nor the page`, async ({ + page, + }) => { + const driver = await load(page); + await page.evaluate(style => { + const lift = document.getElementById('lift'); + if (lift != null) { + lift.style.cssText += `; ${style}`; + } + }, rootStyle); + await open(page, 'lift'); + const action = await centre(page, 'liftAction'); + const tint = {x: 12, y: 12}; + // Unheld, the content and the tint take the hits. + expect(await hitAt(page, action)).toBe('liftAction'); + expect(await hitAt(page, tint)).toBe('tint'); + await hold(page, 'lift', 'layer'); + expect(await hitAt(page, action)).toBe('shield:lift'); + expect(await hitAt(page, tint)).toBe('shield:lift'); + await driver.tap(action); + await driver.tap(tint); + await settle(page); + expect((await readLog(page)).clicks).toEqual([]); + await release(page); + expect(await hitAt(page, action)).toBe('liftAction'); + }); +} + +// Page zoom stays the browser's while a layer is held (spec:AST-094 FR10, +// FR18 and FR35; WCAG 1.4.4): the shield starts no pan, but a pinch on it +// still zooms the page. +for (const [id, scope] of [ + ['pop', 'viewport'], + ['dialog', 'layer'], +] as const) { + test(`while a ${scope === 'viewport' ? 'presentation' : 'dismissal'} holds ${id === 'pop' ? 'a popover' : 'a modal dialog'}, a one-finger pan scrolls nothing and a pinch still zooms the page; neither reaches the layer or the page`, async ({ + page, + browserName, + }) => { + test.skip( + browserName === 'webkit', + 'needs native scrolling and pinch-zoom from injected touches (Mobile Safari on the simulator)', + ); + const driver = await load(page); + const viewport = page.viewportSize(); + if (viewport == null) { + throw new Error('no viewport'); + } + const middle = {x: viewport.width / 2, y: viewport.height / 2}; + const panUp = drag( + {x: middle.x, y: middle.y + 150}, + {x: middle.x, y: middle.y - 150}, + // A rest before the lift: no fling outlives the pan. + {durationMs: 200, restMs: 150}, + ); + // A page that scrolls under the layer: unheld, the same pan scrolls it. + await page.evaluate(() => { + const spacer = document.createElement('div'); + spacer.style.height = '300vh'; + document.body.append(spacer); + }); + await driver.play(panUp); + await expect + .poll(async () => page.evaluate(() => window.scrollY)) + .toBeGreaterThan(0); + await settle(page); + await page.evaluate(() => window.scrollTo(0, 0)); + await settle(page); + expect(await page.evaluate(() => window.scrollY)).toBe(0); + await open(page, id); + await hold(page, id, scope); + expect(await hitAt(page, middle)).toBe(`shield:${id}`); + await driver.play(panUp); + await settle(page); + expect(await page.evaluate(() => window.scrollY)).toBe(0); + await driver.play( + pinch({ + center: middle, + fromDistance: 60, + toDistance: 220, + durationMs: 200, + }), + ); + await expect + .poll(async () => page.evaluate(() => window.visualViewport?.scale ?? 1)) + .toBeGreaterThan(1.2); + expect(await readLog(page)).toEqual({ + clicks: [], + taps: 0, + toggles: id === 'pop' ? ['pop:open'] : [], + }); + }); +} diff --git a/packages/core/src/Layer/holdEntranceInput.test.ts b/packages/core/src/Layer/holdEntranceInput.test.ts new file mode 100644 index 0000000000000..036631b33f691 --- /dev/null +++ b/packages/core/src/Layer/holdEntranceInput.test.ts @@ -0,0 +1,236 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {stubMatchMedia} from '../__tests__/stubMatchMedia'; +import {holdEntranceInput} from './holdEntranceInput'; +import {isInHeldLayer, isInputShield} from './inputHold'; + +function deferred() { + let resolve: () => void = () => {}; + let reject: (error: unknown) => void = () => {}; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return {promise, resolve, reject}; +} + +/** A fake animation: running, and ending at `endTime` (Infinity: endless). */ +function fakeAnimation( + finished: Promise, + { + endTime = 300, + playState = 'running', + }: {endTime?: number; playState?: AnimationPlayState} = {}, +): Animation { + return { + playState, + finished, + effect: {getComputedTiming: () => ({endTime})}, + } as unknown as Animation; +} + +/** A layer root in the document whose own animations are `animations`. */ +function mountLayer(animations: Animation[]): HTMLElement { + const layer = document.createElement('div'); + layer.append(document.createElement('button')); + document.body.append(layer); + Object.defineProperty(layer, 'getAnimations', { + configurable: true, + value: () => animations, + }); + return layer; +} + +const INIT = {bubbles: true, cancelable: true, composed: true}; + +/** A press and its click on `element`: the events that reached it. */ +function tap(element: Element, pointerType: string, pointerId: number) { + const reached: string[] = []; + const record = (event: Event) => reached.push(event.type); + const types = ['pointerdown', 'pointerup', 'click']; + for (const type of types) { + element.addEventListener(type, record); + } + element.dispatchEvent( + new PointerEvent('pointerdown', {...INIT, pointerId, pointerType}), + ); + element.dispatchEvent( + new PointerEvent('pointerup', {...INIT, pointerId, pointerType}), + ); + element.dispatchEvent( + new PointerEvent('click', {...INIT, pointerType, detail: 1}), + ); + for (const type of types) { + element.removeEventListener(type, record); + } + return reached; +} + +/** The holds a case starts, released after it: a hold listens on the window. */ +const releases: (() => void)[] = []; + +function hold(layer: Element): (() => void) | null { + const release = holdEntranceInput(layer); + if (release != null) { + releases.push(release); + } + return release; +} + +const flush = async () => { + for (let i = 0; i < 4; i += 1) { + await Promise.resolve(); + } +}; + +// A touch presentation: the primary pointer is coarse (spec:AST-094 FR13). +beforeEach(() => { + stubMatchMedia({pointer: 'coarse'}); +}); + +afterEach(() => { + for (const release of releases.splice(0)) { + release(); + } + document.body.replaceChildren(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('holdEntranceInput', () => { + it('holds the layer until its entrance ends under a coarse primary pointer', async () => { + const entrance = deferred(); + const layer = mountLayer([fakeAnimation(entrance.promise)]); + + expect(hold(layer)).toBeTypeOf('function'); + expect(isInHeldLayer(layer.firstElementChild)).toBe(true); + + entrance.resolve(); + await flush(); + expect(isInHeldLayer(layer.firstElementChild)).toBe(false); + }); + + it('waits for every animation of the entrance', async () => { + const short = deferred(); + const long = deferred(); + const layer = mountLayer([ + fakeAnimation(short.promise, {endTime: 200}), + fakeAnimation(long.promise, {endTime: 400}), + ]); + + hold(layer); + short.resolve(); + await flush(); + expect(isInHeldLayer(layer)).toBe(true); + + long.resolve(); + await flush(); + expect(isInHeldLayer(layer)).toBe(false); + }); + + it('ends the hold when the entrance is canceled (a close midway)', async () => { + const entrance = deferred(); + const layer = mountLayer([fakeAnimation(entrance.promise)]); + + hold(layer); + entrance.reject(new DOMException('canceled', 'AbortError')); + await flush(); + expect(isInHeldLayer(layer)).toBe(false); + }); + + it('returns a release that ends the hold early', () => { + const layer = mountLayer([fakeAnimation(new Promise(() => {}))]); + + const release = hold(layer); + release?.(); + expect(isInHeldLayer(layer)).toBe(false); + }); + + it("decides by each event's pointer: a finger's tap is held, a mouse's click passes (spec:AST-094 FR35)", () => { + const layer = mountLayer([fakeAnimation(new Promise(() => {}))]); + const button = layer.firstElementChild as Element; + + hold(layer); + expect(tap(button, 'touch', 1)).toEqual([]); + expect(tap(button, 'pen', 2)).toEqual([]); + expect(tap(button, 'mouse', 3)).toEqual([ + 'pointerdown', + 'pointerup', + 'click', + ]); + }); + + it('holds nothing under a fine primary pointer: a mouse press made before the mouse moves reaches the layer, and no window listener is added (spec:AST-094 FR35, FR24)', () => { + stubMatchMedia({pointer: 'fine'}); + const added = vi.spyOn(window, 'addEventListener'); + const layer = mountLayer([fakeAnimation(new Promise(() => {}))]); + const button = layer.firstElementChild as Element; + + expect(hold(layer)).toBeNull(); + expect(isInHeldLayer(button)).toBe(false); + expect([...layer.children].some(child => isInputShield(child))).toBe(false); + expect(added).not.toHaveBeenCalled(); + expect(tap(button, 'mouse', 4)).toEqual([ + 'pointerdown', + 'pointerup', + 'click', + ]); + }); + + it("reads the entrance from another element and holds the layer until that element's entrance ends", async () => { + const layer = mountLayer([]); + const panel = mountLayer([]); + const slide = deferred(); + Object.defineProperty(panel, 'getAnimations', { + configurable: true, + value: () => [fakeAnimation(slide.promise)], + }); + const release = holdEntranceInput(layer, {entrance: panel}); + expect(release).not.toBeNull(); + releases.push(release as () => void); + expect(isInHeldLayer(layer)).toBe(true); + expect(isInHeldLayer(panel)).toBe(false); + + slide.resolve(); + await flush(); + expect(isInHeldLayer(layer)).toBe(false); + }); + + it('ends the hold at `capMs` when the entrance runs longer, and not before', async () => { + vi.useFakeTimers(); + try { + const layer = mountLayer([fakeAnimation(new Promise(() => {}))]); + const release = holdEntranceInput(layer, {capMs: 550}); + releases.push(release as () => void); + vi.advanceTimersByTime(540); + await flush(); + expect(isInHeldLayer(layer)).toBe(true); + + vi.advanceTimersByTime(20); + await flush(); + expect(isInHeldLayer(layer)).toBe(false); + } finally { + vi.useRealTimers(); + } + }); + + it('holds nothing when the entrance element is missing', () => { + const layer = mountLayer([fakeAnimation(new Promise(() => {}))]); + expect(holdEntranceInput(layer, {entrance: null})).toBeNull(); + expect(isInHeldLayer(layer)).toBe(false); + }); + + it('holds nothing when no entrance runs: none, finished, or endless', () => { + const never = new Promise(() => {}); + for (const animations of [ + [], + [fakeAnimation(Promise.resolve(), {playState: 'finished'})], + [fakeAnimation(never, {endTime: Infinity})], + ]) { + const layer = mountLayer(animations); + expect(hold(layer)).toBeNull(); + expect(isInHeldLayer(layer)).toBe(false); + } + }); +}); diff --git a/packages/core/src/Layer/holdEntranceInput.ts b/packages/core/src/Layer/holdEntranceInput.ts new file mode 100644 index 0000000000000..07128b34d3cd1 --- /dev/null +++ b/packages/core/src/Layer/holdEntranceInput.ts @@ -0,0 +1,84 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file holdEntranceInput.ts + * @input A layer root whose CSS entrance has just started + * @output holdEntranceInput: under a coarse primary pointer, a finger's or a + * pen's input held away from the layer until its entrance ends + * @position The entrance hold for layers that enter through CSS (Dialog, + * Drawer, MobileNav), on the Layer module's input hold (inputHold.ts) + * + * SYNC: When modified, update holdEntranceInput.test.ts and its callers + * (Dialog.tsx, Drawer/useDrawerDialogPresence.ts, MobileNav/MobileNav.tsx). + */ + +import {isCoarsePointer} from '../utils/coarsePointer'; +import {holdInput} from './inputHold'; + +/** Options for {@link holdEntranceInput}. */ +export interface EntranceHoldOptions { + /** + * Holds input anywhere while true. While false, only what lands on the layer + * is held, and the page stays live. + * @default true + */ + isModal?: boolean; + /** + * The element whose animations are the entrance, when it is not the layer + * itself (a drawer inside its dialog). + * @default the layer + */ + entrance?: Element | null; + /** The longest the hold lasts, ms. An entrance that runs longer ends it. */ + capMs?: number; +} + +/** + * Holds a finger's and a pen's input away from `layer` until its entrance + * ends, or at most `capMs`. Returns the release, or `null` when nothing is + * held: no entrance runs, or the primary pointer is fine. + */ +export function holdEntranceInput( + layer: Element, + {isModal = true, entrance: animated = layer, capMs}: EntranceHoldOptions = {}, +): (() => void) | null { + if (animated == null || typeof animated.getAnimations !== 'function') { + return null; + } + // getAnimations() flushes styles, so it lists an entrance the open has just + // started. A theme's duration, a shorter reduced-motion entrance and a + // canceled entrance all end the hold when they end. + const entrance = animated.getAnimations().filter(isEntrance); + if (entrance.length === 0) { + return null; + } + // A touch presentation only, read as the layer opens. A finger on a device + // whose primary pointer is fine, such as a touchscreen laptop, is not held. + if (!isCoarsePointer(layer.ownerDocument.defaultView)) { + return null; + } + const ended = Promise.all( + entrance.map(async animation => animation.finished), + ); + return holdInput(layer, { + until: capMs == null ? ended : Promise.race([ended, after(capMs)]), + scope: isModal ? 'viewport' : 'surface', + }); +} + +async function after(ms: number): Promise { + await new Promise(resolve => { + setTimeout(resolve, ms); + }); +} + +/** A running animation that ends on its own: an entrance, not a spin. */ +function isEntrance(animation: Animation): boolean { + if (animation.playState !== 'running') { + return false; + } + const end = animation.effect?.getComputedTiming().endTime; + return typeof end === 'number' && Number.isFinite(end); +} diff --git a/packages/core/src/Layer/inputHold.test.tsx b/packages/core/src/Layer/inputHold.test.tsx new file mode 100644 index 0000000000000..14d180b8e2691 --- /dev/null +++ b/packages/core/src/Layer/inputHold.test.tsx @@ -0,0 +1,699 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +import { + afterEach, + beforeEach, + describe, + expect, + it, + onTestFinished, + vi, +} from 'vitest'; +import {GestureHost} from '../gestures/GestureHost'; +import {subscribeInput} from '../utils/inputStream'; +import { + holdInput, + holdsTouch, + isInHeldLayer, + isInputShield, + type InputHoldScope, +} from './inputHold'; + +function deferred() { + let resolve: () => void = () => {}; + let reject: (error: unknown) => void = () => {}; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return {promise, resolve, reject}; +} + +/** A layer root with a child, in the document. */ +function mountLayer(): {layer: HTMLElement; child: HTMLElement} { + const layer = document.createElement('div'); + const child = document.createElement('button'); + layer.append(child); + document.body.append(layer); + return {layer, child}; +} + +const flush = async () => { + await Promise.resolve(); + await Promise.resolve(); +}; + +/** + * What a listener throws during a case: jsdom reports it as an `error` event + * on the window and goes on dispatching, so a hold whose listener throws + * would otherwise pass. None is expected. + */ +const listenerErrors: unknown[] = []; +window.addEventListener('error', event => { + listenerErrors.push(event.error); +}); + +afterEach(() => { + document.body.replaceChildren(); + vi.restoreAllMocks(); + expect(listenerErrors.splice(0)).toEqual([]); +}); + +describe('holdInput', () => { + it('holds a presenting layer with a shield over the viewport until its end settles', async () => { + const {layer, child} = mountLayer(); + const outside = document.createElement('div'); + document.body.append(outside); + const end = deferred(); + holdInput(layer, {until: end.promise, scope: 'viewport'}); + const shield = layer.lastElementChild as HTMLElement; + expect(shield).not.toBe(child); + expect(shield.getAttribute('popover')).toBe('manual'); + expect(shield.style.position).toBe('fixed'); + // No pan, and a pinch still zooms the page (spec:AST-094 FR10). + expect(shield.style.touchAction).toBe('pinch-zoom'); + // Its own hit-testing, whatever the layer root's (the browser proof holds + // a root that is pointer-events: none). + expect(shield.style.pointerEvents).toBe('auto'); + expect(shield.style.visibility).toBe('visible'); + expect(isInHeldLayer(child)).toBe(true); + expect(isInHeldLayer(shield)).toBe(true); + expect(isInHeldLayer(outside)).toBe(false); + // Keys and assistive technology stay live while presenting. + expect(layer.hasAttribute('inert')).toBe(false); + end.resolve(); + await flush(); + expect(shield.isConnected).toBe(false); + expect(isInHeldLayer(child)).toBe(false); + }); + + it('swallows a press and a click on the shield before they reach the page, and leaves a touch its start so a pinch can still zoom', () => { + const {layer} = mountLayer(); + holdInput(layer, {until: new Promise(() => {}), scope: 'viewport'}); + const shield = layer.lastElementChild as HTMLElement; + const seen: string[] = []; + for (const type of ['pointerdown', 'click', 'touchstart']) { + document.addEventListener(type, () => seen.push(type)); + } + const press = new Event('pointerdown', {bubbles: true, cancelable: true}); + const click = new MouseEvent('click', {bubbles: true, cancelable: true}); + const touch = new Event('touchstart', {bubbles: true, cancelable: true}); + // A touch event carries its touch lists. + Object.defineProperty(touch, 'changedTouches', {value: [{identifier: 0}]}); + Object.defineProperty(touch, 'touches', {value: [{identifier: 0}]}); + shield.dispatchEvent(press); + shield.dispatchEvent(click); + shield.dispatchEvent(touch); + // A touch that starts also ends. + const touchEnd = new Event('touchend', {bubbles: true, cancelable: true}); + Object.defineProperty(touchEnd, 'changedTouches', { + value: [{identifier: 0}], + }); + Object.defineProperty(touchEnd, 'touches', {value: []}); + shield.dispatchEvent(touchEnd); + expect(seen).toEqual([]); + expect(press.defaultPrevented).toBe(true); + expect(click.defaultPrevented).toBe(true); + // Cancelling a touch's start would cancel the page's pinch-zoom too. + expect(touch.defaultPrevented).toBe(false); + }); + + it("holds only a non-modal layer's own box with a 'surface' hold: its shield covers the layer, not the viewport (spec:AST-094 FR35)", async () => { + const {layer, child} = mountLayer(); + const outside = document.createElement('div'); + document.body.append(outside); + const end = deferred(); + holdInput(layer, {until: end.promise, scope: 'surface'}); + const shield = layer.lastElementChild as HTMLElement; + expect(shield).not.toBe(child); + // Inside the layer's box, not over the viewport from the top layer. + expect(shield.hasAttribute('popover')).toBe(false); + expect(shield.style.position).toBe('absolute'); + expect(shield.style.inset).toBe('0'); + expect(shield.style.touchAction).toBe('pinch-zoom'); + expect(shield.style.pointerEvents).toBe('auto'); + expect(isInputShield(shield)).toBe(true); + expect(isInHeldLayer(child)).toBe(true); + expect(isInHeldLayer(outside)).toBe(false); + expect(layer.hasAttribute('inert')).toBe(false); + end.resolve(); + await flush(); + expect(shield.isConnected).toBe(false); + }); + + it("holds a dismissing layer: its content inert, the layer itself live under the shield, each element's inert given back", async () => { + const {layer, child} = mountLayer(); + const already = document.createElement('div'); + already.setAttribute('inert', ''); + layer.append(already); + child.focus(); + expect(document.activeElement).toBe(child); + const end = deferred(); + holdInput(layer, {until: end.promise, scope: 'layer'}); + // Focus leaves the content: a focused element that turns inert would + // keep its key activation. + expect(document.activeElement).not.toBe(child); + const shield = layer.lastElementChild as HTMLElement; + expect(shield.getAttribute('popover')).toBe('manual'); + // The layer stays live so the shield inside it catches every hit: an + // inert subtree is no hit target. + expect(layer.hasAttribute('inert')).toBe(false); + expect(shield.hasAttribute('inert')).toBe(false); + expect(child.hasAttribute('inert')).toBe(true); + expect(isInHeldLayer(child)).toBe(true); + end.reject(new Error('interrupted')); + await flush(); + expect(child.hasAttribute('inert')).toBe(false); + expect(already.hasAttribute('inert')).toBe(true); + expect(shield.isConnected).toBe(false); + expect(isInHeldLayer(child)).toBe(false); + }); + + it('names a live hold’s shield, and only it, so a hit test can skip it', () => { + const {layer, child} = mountLayer(); + const popover = document.createElement('div'); + popover.setAttribute('popover', 'manual'); + document.body.append(popover); + const release = holdInput(layer, { + until: new Promise(() => {}), + scope: 'viewport', + }); + const shield = layer.lastElementChild as HTMLElement; + expect(isInputShield(shield)).toBe(true); + for (const other of [layer, child, popover, null]) { + expect(isInputShield(other)).toBe(false); + } + release(); + expect(isInputShield(shield)).toBe(false); + }); + + it('sees slotted content as held: the flat tree, a slotted node to its slot', () => { + const host = document.createElement('div'); + const slotted = document.createElement('button'); + host.append(slotted); + document.body.append(host); + const root = host.attachShadow({mode: 'open'}); + const layer = document.createElement('div'); + layer.append(document.createElement('slot')); + root.append(layer); + expect(isInHeldLayer(slotted)).toBe(false); + const release = holdInput(layer, { + until: new Promise(() => {}), + scope: 'viewport', + }); + expect(isInHeldLayer(slotted)).toBe(true); + release(); + expect(isInHeldLayer(slotted)).toBe(false); + }); + + it('takes an animator handle, ending with its finished', async () => { + const {layer, child} = mountLayer(); + const end = deferred(); + holdInput(layer, {until: {finished: end.promise}, scope: 'layer'}); + expect(isInHeldLayer(child)).toBe(true); + end.resolve(); + await flush(); + expect(isInHeldLayer(child)).toBe(false); + }); + + it('stacks holds on one layer, either scope, under one shield: it comes back when the last one ends', () => { + const {layer, child} = mountLayer(); + const first = holdInput(layer, { + until: new Promise(() => {}), + scope: 'viewport', + }); + const second = holdInput(layer, { + until: new Promise(() => {}), + scope: 'layer', + }); + expect(layer.querySelectorAll('[popover]')).toHaveLength(1); + expect(child.hasAttribute('inert')).toBe(true); + first(); + first(); + expect(isInHeldLayer(child)).toBe(true); + expect(layer.querySelectorAll('[popover]')).toHaveLength(1); + second(); + expect(isInHeldLayer(child)).toBe(false); + expect(child.hasAttribute('inert')).toBe(false); + expect(layer.querySelectorAll('[popover]')).toHaveLength(0); + }); + + it('registers nothing with the gesture host: the host asks holdsTouch for each touch', () => { + const addTouchGate = vi.spyOn(GestureHost.prototype, 'addTouchGate'); + const {layer, child} = mountLayer(); + const releaseLayer = holdInput(layer, { + until: new Promise(() => {}), + scope: 'layer', + }); + const release = holdInput(layer, { + until: new Promise(() => {}), + scope: 'viewport', + }); + expect(addTouchGate).not.toHaveBeenCalled(); + expect(isInHeldLayer(child)).toBe(true); + expect(holdsTouch(child)).toBe(true); + expect(holdsTouch(document.body)).toBe(false); + release(); + releaseLayer(); + expect(isInHeldLayer(child)).toBe(false); + expect(holdsTouch(child)).toBe(false); + }); +}); + +describe("holdInput decides by each event's pointer (spec:AST-094 FR35)", () => { + const INIT = {bubbles: true, cancelable: true, composed: true}; + + /** The holds a case starts, released after it: a hold listens on the window. */ + const releases: (() => void)[] = []; + const hold = (layer: Element, scope: InputHoldScope = 'viewport') => { + const release = holdInput(layer, {until: new Promise(() => {}), scope}); + releases.push(release); + return release; + }; + + /** Makes `type` the stream's last pointer, as a page's earlier input does. */ + function lastPointerWas(type: string) { + const stop = subscribeInput(window, 'pointermove', () => {}); + pointer(document.body, 'pointermove', type); + stop(); + } + + // Each case starts as after a finger: no earlier case's mouse lowers its + // shield. + beforeEach(() => { + lastPointerWas('touch'); + }); + + afterEach(() => { + for (const release of releases.splice(0)) { + release(); + } + // A new press ends a released hold's click window (the held press's + // click can no longer come), so its subscriptions end before the next + // case rather than lingering into it. + pointer(document.body, 'pointerdown', 'mouse'); + pointer(document.body, 'pointerup', 'mouse'); + }); + + /** A button that records every event that reaches it. */ + function recorder(parent: Element = document.body) { + const button = document.createElement('button'); + parent.append(button); + const reached: string[] = []; + for (const type of [ + 'pointerdown', + 'pointermove', + 'pointerup', + 'touchstart', + 'touchmove', + 'touchend', + 'mousedown', + 'mouseup', + 'click', + 'contextmenu', + ]) { + button.addEventListener(type, () => reached.push(type)); + } + return {button, reached}; + } + + function pointer( + element: Element, + type: string, + pointerType: string, + pointerId = 1, + buttons = 0, + ): Event { + const event = new PointerEvent(type, { + ...INIT, + pointerId, + pointerType, + buttons, + }); + element.dispatchEvent(event); + return event; + } + + /** A click as a browser sends it: a pointer event naming its pointer. */ + function click(element: Element, pointerType: string, detail = 1): Event { + const event = new PointerEvent('click', {...INIT, pointerType, detail}); + element.dispatchEvent(event); + return event; + } + + /** A compatibility mouse event, or a click sent as a plain mouse event. */ + function mouse(element: Element, type: string, detail = 1): Event { + const event = new MouseEvent(type, {...INIT, detail}); + element.dispatchEvent(event); + return event; + } + + function touch( + element: Element, + type: string, + identifiers: number[], + down: number = identifiers.length, + ): Event { + const event = new Event(type, INIT); + const list = identifiers.map(identifier => ({identifier, target: element})); + Object.defineProperty(event, 'changedTouches', {value: list}); + Object.defineProperty(event, 'touches', { + value: Array.from({length: down}, (_, identifier) => ({identifier})), + }); + element.dispatchEvent(event); + return event; + } + + /** A finger's or a pen's tap: down, up, then the browser's click. */ + function tap(element: Element, pointerType: 'touch' | 'pen', pointerId = 1) { + pointer(element, 'pointerdown', pointerType, pointerId); + pointer(element, 'pointerup', pointerType, pointerId); + click(element, pointerType); + } + + it("keeps a held press from the input stream's other subscribers, so press feedback and the gesture host never hear it", () => { + const {layer} = mountLayer(); + const heard: string[] = []; + // Subscribed before the hold, as press feedback is on a page with a + // pressable. + const stops = (['pointerdown', 'pointerup'] as const).map(type => + subscribeInput(window, type, event => { + heard.push(`${type}:${event.pointerType}`); + }), + ); + hold(layer); + pointer(document.body, 'pointerdown', 'touch', 7); + pointer(document.body, 'pointerup', 'touch', 7); + expect(heard).toEqual([]); + // A mouse's press is not held: the other subscribers hear it. + pointer(document.body, 'pointerdown', 'mouse', 8); + pointer(document.body, 'pointerup', 'mouse', 8); + expect(heard).toEqual(['pointerdown:mouse', 'pointerup:mouse']); + for (const stop of stops) { + stop(); + } + }); + it("holds a finger's press anywhere in the page, with its moves, release and click, whatever the primary pointer", () => { + const {layer} = mountLayer(); + const {button, reached} = recorder(); + hold(layer); + const down = pointer(button, 'pointerdown', 'touch'); + pointer(button, 'pointermove', 'touch'); + pointer(button, 'pointerup', 'touch'); + click(button, 'touch'); + // Canceled: the browser sends no compatibility mouse events for it, and + // no focus move. + expect(down.defaultPrevented).toBe(true); + expect(reached).toEqual([]); + }); + + it("holds a finger's press on a layer under a 'surface' hold and leaves one on the page alone, with its moves, release and click (spec:AST-094 FR35)", () => { + const {layer} = mountLayer(); + const onLayer = recorder(layer); + const onPage = recorder(); + hold(layer, 'surface'); + // On the page: the page stays live. + const down = pointer(onPage.button, 'pointerdown', 'touch', 1); + pointer(onPage.button, 'pointermove', 'touch', 1); + pointer(onPage.button, 'pointerup', 'touch', 1); + click(onPage.button, 'touch'); + expect(down.defaultPrevented).toBe(false); + expect(onPage.reached).toEqual([ + 'pointerdown', + 'pointermove', + 'pointerup', + 'click', + ]); + const start = touch(onPage.button, 'touchstart', [7]); + const move = touch(onPage.button, 'touchmove', [7]); + touch(onPage.button, 'touchend', [7], 0); + expect(move.defaultPrevented).toBe(false); + expect(start.defaultPrevented).toBe(false); + expect(onPage.reached.slice(-3)).toEqual([ + 'touchstart', + 'touchmove', + 'touchend', + ]); + expect(holdsTouch(onPage.button)).toBe(false); + // On the layer: held, as under a presentation's hold. + tap(onLayer.button, 'touch', 2); + expect(onLayer.reached).toEqual([]); + expect(holdsTouch(onLayer.button)).toBe(true); + }); + + it("holds a pen's press as a finger's", () => { + const {layer} = mountLayer(); + const {button, reached} = recorder(layer); + hold(layer); + tap(button, 'pen'); + expect(reached).toEqual([]); + }); + + it("leaves a mouse's press and click alone during a presentation, a click sent as a plain mouse event included", () => { + const {layer} = mountLayer(); + const {button, reached} = recorder(layer); + hold(layer); + const down = pointer(button, 'pointerdown', 'mouse'); + mouse(button, 'mousedown'); + pointer(button, 'pointerup', 'mouse'); + mouse(button, 'mouseup'); + click(button, 'mouse'); + mouse(button, 'click'); + expect(down.defaultPrevented).toBe(false); + expect(reached).toEqual([ + 'pointerdown', + 'mousedown', + 'pointerup', + 'mouseup', + 'click', + 'click', + ]); + }); + + it("lets a mouse through a presentation's shield once it moves, takes hits again at a finger's press, and keeps a dismissal's shield taking every hit", () => { + const {layer} = mountLayer(); + const {button} = recorder(layer); + hold(layer); + const shield = layer.lastElementChild as HTMLElement; + expect(shield.style.pointerEvents).toBe('auto'); + // A mouse or a trackpad moving on a touch screen: what it points at is + // hit, as with no hold. + pointer(document.body, 'pointermove', 'mouse'); + expect(shield.style.pointerEvents).toBe('none'); + // A finger: the shield is the hit target again for the next one. + pointer(button, 'pointerdown', 'touch', 2); + expect(shield.style.pointerEvents).toBe('auto'); + pointer(button, 'pointerup', 'touch', 2); + // A dismissal's content is inert: a mouse would fall through it to the + // page, so its shield keeps every hit. + hold(layer, 'layer'); + pointer(document.body, 'pointermove', 'mouse'); + expect(shield.style.pointerEvents).toBe('auto'); + }); + + it("starts a presentation's shield lowered when the stream last heard a mouse: a press where the mouse rests reaches the layer (spec:AST-094 FR35)", () => { + const {layer, child} = mountLayer(); + const {button, reached} = recorder(layer); + // Press feedback hears the page's pointer moves through the stream on any + // page with a pressable; the mouse moved last, before the layer opened. + const stop = subscribeInput(window, 'pointermove', () => {}); + pointer(document.body, 'pointermove', 'mouse'); + stop(); + hold(layer); + const shield = layer.lastElementChild as HTMLElement; + expect(isInputShield(shield)).toBe(true); + expect(shield.style.pointerEvents).toBe('none'); + expect(holdsTouch(child)).toBe(false); + // A key opened the layer; the resting mouse presses without moving. + pointer(button, 'pointerdown', 'mouse', 1, 1); + pointer(button, 'pointerup', 'mouse'); + click(button, 'mouse'); + expect(reached).toEqual(['pointerdown', 'pointerup', 'click']); + // A dismissal's shield still takes every hit. + hold(layer, 'layer'); + expect(shield.style.pointerEvents).toBe('auto'); + }); + + it("starts a presentation's shield up when the stream last heard a finger, or no pointer at all", () => { + const {layer, child} = mountLayer(); + lastPointerWas('touch'); + hold(layer); + const shield = layer.lastElementChild as HTMLElement; + expect(shield.style.pointerEvents).toBe('auto'); + expect(holdsTouch(child)).toBe(true); + // Once a mouse moves during the hold, it passes. + pointer(document.body, 'pointermove', 'mouse'); + expect(shield.style.pointerEvents).toBe('none'); + expect(holdsTouch(child)).toBe(false); + }); + + it('adds its window listeners only while a layer is held, once per document however many layers are held, and removes every one after the last hold ends (spec:AST-094 FR24)', () => { + const added = vi.spyOn(window, 'addEventListener'); + const removed = vi.spyOn(window, 'removeEventListener'); + const listening = () => added.mock.calls.length - removed.mock.calls.length; + const first = mountLayer().layer; + const second = mountLayer().layer; + const releaseFirst = hold(first); + const once = listening(); + expect(once).toBeGreaterThan(0); + const releaseSecond = hold(second, 'layer'); + expect(listening()).toBe(once); + releaseFirst(); + expect(listening()).toBe(once); + releaseSecond(); + expect(listening()).toBe(0); + }); + + it("answers the gesture host's question only while a layer is held, and false after the last hold ends, registering nothing (spec:AST-094 FR24)", () => { + const addTouchGate = vi.spyOn(GestureHost.prototype, 'addTouchGate'); + const {layer, child} = mountLayer(); + const release = hold(layer); + expect(holdsTouch(child)).toBe(true); + hold(mountLayer().layer)(); + expect(holdsTouch(child)).toBe(true); + release(); + expect(holdsTouch(child)).toBe(false); + expect(addTouchGate).not.toHaveBeenCalled(); + }); + + it("lets the gesture host's gate pass a mouse during a presentation and hold it during a dismissal", () => { + const {layer, child} = mountLayer(); + hold(layer); + // What the gesture host asks the hold for every touch. + const isGated = holdsTouch; + // Before any pointer: held. + expect(isGated(child)).toBe(true); + pointer(child, 'pointermove', 'mouse'); + pointer(child, 'pointerdown', 'mouse'); + expect(isGated(child)).toBe(false); + pointer(child, 'pointerup', 'mouse'); + pointer(child, 'pointerdown', 'touch', 2); + expect(isGated(child)).toBe(true); + pointer(child, 'pointerup', 'touch', 2); + hold(layer, 'layer'); + pointer(child, 'pointermove', 'mouse'); + pointer(child, 'pointerdown', 'mouse'); + expect(isGated(child)).toBe(true); + expect(isGated(document.body)).toBe(false); + }); + + it("keeps a presentation's shield up for a mouse press that begins on it, to that press's end, and the gate holds what lands on the shield: its release and click are the shield's, not what lies beneath", () => { + const {layer, child} = mountLayer(); + hold(layer); + const shield = layer.lastElementChild as HTMLElement; + const isGated = holdsTouch; + // A mouse that has not moved during the hold presses: the press meets + // the shield, which stays up through the press, a drag included. + pointer(shield, 'pointerdown', 'mouse', 1, 1); + expect(shield.style.pointerEvents).toBe('auto'); + pointer(shield, 'pointermove', 'mouse', 1, 1); + expect(shield.style.pointerEvents).toBe('auto'); + expect(isGated(shield)).toBe(true); + pointer(shield, 'pointerup', 'mouse'); + // Only a mouse moving with no button down lets it through. + pointer(document.body, 'pointermove', 'mouse'); + expect(shield.style.pointerEvents).toBe('none'); + expect(isGated(child)).toBe(false); + // What lands on a shield is held, a mouse's press included. + expect(isGated(shield)).toBe(true); + }); + + it('swallows a synthetic press that lands past a lowered shield without capturing it: it has no active pointer to capture', () => { + // jsdom implements no pointer capture; a browser's setPointerCapture + // throws NotFoundError for a pointer that is not active, as a synthetic + // press's is not. + const setPointerCapture = vi.fn(); + Object.defineProperty(HTMLElement.prototype, 'setPointerCapture', { + configurable: true, + value: setPointerCapture, + }); + onTestFinished(() => { + Reflect.deleteProperty(HTMLElement.prototype, 'setPointerCapture'); + }); + const {layer} = mountLayer(); + const {button, reached} = recorder(); + hold(layer); + // A moving mouse lowers the shield, so the finger lands past it. + pointer(document.body, 'pointermove', 'mouse'); + const down = pointer(button, 'pointerdown', 'touch'); + pointer(button, 'pointerup', 'touch'); + click(button, 'touch'); + expect(setPointerCapture).not.toHaveBeenCalled(); + expect(down.defaultPrevented).toBe(true); + expect(reached).toEqual([]); + }); + + it('lets a key or assistive technology click through: it counts no press', () => { + const {layer} = mountLayer(); + const {button, reached} = recorder(layer); + hold(layer); + pointer(button, 'pointerdown', 'touch'); + pointer(button, 'pointerup', 'touch'); + click(button, '', 0); + expect(reached).toEqual(['click']); + }); + + it("never cancels a touch's start, and cancels a move only while one finger is down", () => { + const {layer} = mountLayer(); + const {button, reached} = recorder(layer); + hold(layer); + expect(touch(button, 'touchstart', [1]).defaultPrevented).toBe(false); + expect(touch(button, 'touchmove', [1]).defaultPrevented).toBe(true); + // A second finger: a pinch, which still zooms the page. + expect(touch(button, 'touchstart', [2], 2).defaultPrevented).toBe(false); + expect(touch(button, 'touchmove', [1, 2]).defaultPrevented).toBe(false); + touch(button, 'touchend', [1, 2], 0); + expect(reached).toEqual([]); + }); + + it('swallows the compatibility mouse events and the click a browser sends after a held touch', () => { + const {layer} = mountLayer(); + const {button, reached} = recorder(layer); + hold(layer); + touch(button, 'touchstart', [1]); + expect(touch(button, 'touchend', [1], 0).defaultPrevented).toBe(true); + mouse(button, 'mousedown'); + mouse(button, 'mouseup'); + mouse(button, 'click'); + expect(reached).toEqual([]); + }); + + it('follows a press that landed during the hold to its end, past the release, and leaves the next tap alone', () => { + const {layer} = mountLayer(); + const {button, reached} = recorder(); + const release = hold(layer); + pointer(button, 'pointerdown', 'touch'); + release(); + pointer(button, 'pointerup', 'touch'); + click(button, 'touch'); + expect(reached).toEqual([]); + // The next tap is the page's again. + tap(button, 'touch', 2); + expect(reached).toEqual(['pointerdown', 'pointerup', 'click']); + }); + + it('lets a touch after the release through when a held touch ended where the window could not hear it, its identifier reused', () => { + const {layer} = mountLayer(); + const {button, reached} = recorder(); + const release = hold(layer); + // A held touch whose end went to its removed target, unheard here. + touch(button, 'touchstart', [0]); + release(); + // The next touch reuses its identifier: it is the page's, and so is its + // end, which the browser follows with a click. + touch(button, 'touchstart', [0]); + const end = touch(button, 'touchend', [0], 0); + expect(end.defaultPrevented).toBe(false); + mouse(button, 'click'); + expect(reached).toEqual(['touchstart', 'touchend', 'click']); + }); + + it('holds nothing once its layer has left the document', () => { + const {layer} = mountLayer(); + hold(layer); + layer.remove(); + const {button, reached} = recorder(); + tap(button, 'touch'); + expect(reached).toEqual(['pointerdown', 'pointerup', 'click']); + }); +}); diff --git a/packages/core/src/Layer/inputHold.ts b/packages/core/src/Layer/inputHold.ts new file mode 100644 index 0000000000000..d00e234a74d4a --- /dev/null +++ b/packages/core/src/Layer/inputHold.ts @@ -0,0 +1,734 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file inputHold.ts + * @input A layer root, what ends its hold (a promise or an animator handle), + * and the hold's scope + * @output holdInput, holdsTouch, isInHeldLayer and isInputShield: input held + * away from a layer while it presents or dismisses + * @position The Layer module's one input hold, for components whose layer + * presents under a finger + * + * SYNC: When modified, update inputHold.test.tsx, + * __tests__/inputHold.interaction.browser.spec.ts and the holdInput callers. + */ + +import { + containsAlongFlatTree, + deepActiveElement, + parentAcrossShadow, +} from '../utils/flatTree'; +import {getLastPointerType, subscribeInput} from '../utils/inputStream'; + +/** + * What a hold does. `'viewport'` and `'layer'` add one shield over the whole + * viewport. `'layer'` also makes the layer's content inert and moves focus + * out of it. `'surface'` shields only the layer's own box, and the page + * around it stays live. + */ +export type InputHoldScope = 'viewport' | 'layer' | 'surface'; + +/** What ends a hold: a promise, or an animator handle (its `finished`). */ +export type InputHoldEnd = + PromiseLike | {readonly finished: PromiseLike}; + +export interface InputHoldOptions { + /** The hold ends when this settles. */ + until: InputHoldEnd; + /** + * `'viewport'` while presenting, `'layer'` while dismissing, `'surface'` + * while a non-modal layer presents. + */ + scope: InputHoldScope; +} + +interface HeldLayer { + viewport: number; + layer: number; + surface: number; + shield: HTMLElement | null; + /** Whether the shield covers the viewport, or only the layer's box. */ + isShieldFull: boolean; + /** The content a dismissal made inert, and whether each was already. */ + inertContent: Map | null; +} + +/** A document while any of its layers is held. */ +interface HeldDocument { + /** Its held layers, oldest first. */ + readonly layers: Set; +} + +/** A document's press hold, while its window listeners are on. */ +interface PressHold { + /** New presses are held again (a layer is held). */ + hold: () => void; + /** No new press is held; held ones are followed to their end. */ + release: () => void; +} + +const held = new WeakMap(); +const heldDocuments = new WeakMap(); +const pressHolds = new WeakMap(); +const liveShields = new WeakSet(); + +/** Whether the shared input stream last delivered a mouse's pointer event. */ +function isMouseLast(doc: Document | null): boolean { + const view = doc?.defaultView; + return view != null && getLastPointerType(view) === 'mouse'; +} + +/** + * Whether `node` is the shield of a live hold. A hit test that must see past + * held input takes the first element of `elementsFromPoint` that is not one. + */ +export function isInputShield(node: Node | null): boolean { + return node != null && liveShields.has(node); +} + +/** + * Whether `target` is inside a held layer. It walks the flat tree as the + * gesture host does: a slotted node goes to its slot, and a shadow root to + * its host. + */ +export function isInHeldLayer(target: Node | null): boolean { + for ( + let node: Node | null = target; + node != null; + node = parentAcrossShadow(node) + ) { + if (node instanceof Element && held.has(node)) { + return true; + } + } + return false; +} + +/** + * Whether the gesture host holds `target` away for the current pointer. A + * dismissing layer holds every pointer. A presenting layer holds every + * pointer but a mouse, which keeps today's behavior. The host asks this for + * every touch. So this module imports nothing from gestures/, and a + * root-entry component can hold its layer without gesture code. With nothing + * held, this answers false. + */ +export function holdsTouch(target: Node): boolean { + const doc = target instanceof Document ? target : target.ownerDocument; + // The gesture host asks for every touch: with nothing held, answer at once. + if (doc == null || !heldDocuments.has(doc)) { + return false; + } + // What lands on a shield is held, a mouse's press included. + if (isInputShield(target)) { + return true; + } + let isHeld = false; + for ( + let node: Node | null = target; + node != null; + node = parentAcrossShadow(node) + ) { + const state = node instanceof Element ? held.get(node) : undefined; + if (state != null) { + if (state.layer > 0) { + return true; + } + isHeld = true; + } + } + return isHeld && !isMouseLast(doc); +} + +/** + * Starts holding `layer`. A document's first held layer turns its press hold + * on, with one stream subscription per event type, however many layers are + * held. The hold subscribes to nothing while nothing is held. + */ +function startHolding(layer: Element): void { + const doc = layer.ownerDocument; + let state = heldDocuments.get(doc); + if (state == null) { + state = {layers: new Set()}; + heldDocuments.set(doc, state); + } + state.layers.add(layer); + pressHoldFor(doc)?.hold(); +} + +/** Stops holding `layer`; after the document's last one, ends its holding. */ +function stopHolding(layer: Element): void { + heldDocuments.get(layer.ownerDocument)?.layers.delete(layer); + liveLayers(layer.ownerDocument); +} + +/** + * The document's held layers still in it, oldest first. A layer that has + * left the document holds nothing more. When none is left, `holdsTouch` + * answers false and the press hold takes no new press. Its subscriptions end + * once the presses it holds have ended. + */ +function liveLayers(doc: Document): Element[] { + const state = heldDocuments.get(doc); + if (state == null) { + return []; + } + for (const layer of state.layers) { + if (!layer.isConnected) { + state.layers.delete(layer); + } + } + if (state.layers.size > 0) { + return [...state.layers]; + } + heldDocuments.delete(doc); + pressHolds.get(doc)?.release(); + return []; +} + +const SWALLOWED = [ + 'pointerdown', + 'pointerup', + 'touchstart', + 'touchend', + 'mousedown', + 'mouseup', + 'click', + 'contextmenu', +] as const; + +const swallow = (event: Event) => { + // A touch's start stays uncancelled: cancelling it would cancel the page's + // pinch-zoom too. The shield's `touch-action: pinch-zoom` keeps a finger + // from panning. A tap's mouse events and click land on the shield, which + // swallows them. + if (event.cancelable && event.type !== 'touchstart') { + event.preventDefault(); + } + event.stopPropagation(); +}; + +/** + * A transparent cover inside `layer`: of the viewport from the top layer + * (`isFull`), or of the layer's own box alone. Because the cover is inside + * the layer, a tap on it lands in the layer, and a light-dismissing layer + * stays open. + */ +function addShield(layer: Element, isFull: boolean): HTMLElement { + const shield = layer.ownerDocument.createElement('div'); + if (isFull) { + shield.setAttribute('popover', 'manual'); + } + shield.setAttribute('aria-hidden', 'true'); + Object.assign(shield.style, { + position: isFull ? 'fixed' : 'absolute', + inset: '0', + width: isFull ? '100vw' : '100%', + height: isFull ? '100vh' : '100%', + // Above the layer's own content. + zIndex: isFull ? 'auto' : '2147483647', + maxWidth: 'none', + maxHeight: 'none', + margin: '0', + padding: '0', + border: '0', + background: 'transparent', + overflow: 'hidden', + touchAction: 'pinch-zoom', + // These two inherited properties decide hit-testing. A layer root can opt + // out of hits, as a full-viewport layer does when a backdrop child takes + // them. Inherited from such a root, they would let a held tap fall through + // to the page. + pointerEvents: 'auto', + visibility: 'visible', + }); + for (const type of SWALLOWED) { + shield.addEventListener(type, swallow, {capture: true, passive: false}); + } + layer.append(shield); + liveShields.add(shield); + if (isFull && typeof shield.showPopover === 'function') { + try { + shield.showPopover(); + } catch { + // Not connected, or popovers unsupported: the shield still covers + // what it can as a fixed element. + } + } + return shield; +} + +/** + * Holds input away from `layer` until `until` settles. Returns the release + * (idempotent), for a hold that ends early. Holds on one layer stack, and + * the layer comes back when the last one ends. Each event is judged by its + * own pointer, never by the primary pointer. So a mouse on a touch screen + * keeps its clicks during a presentation. + */ +export function holdInput( + layer: Element, + {until, scope}: InputHoldOptions, +): () => void { + let state = held.get(layer); + if (state == null) { + state = { + viewport: 0, + layer: 0, + surface: 0, + shield: null, + isShieldFull: false, + inertContent: null, + }; + held.set(layer, state); + } + startHolding(layer); + const isFull = scope !== 'surface'; + if (state.shield != null && isFull && !state.isShieldFull) { + // A surface hold's shield gives way to one over the viewport. + liveShields.delete(state.shield); + state.shield.remove(); + state.shield = null; + } + if (state.shield == null) { + state.isShieldFull = isFull || state.viewport + state.layer > 0; + state.shield = addShield(layer, state.isShieldFull); + // A presentation lets a mouse through from the start when the stream's + // last pointer was a mouse. A press where the mouse rests then acts. + if (scope !== 'layer' && isMouseLast(layer.ownerDocument)) { + state.shield.style.pointerEvents = 'none'; + } + } + if (scope === 'viewport') { + state.viewport += 1; + } else if (scope === 'surface') { + state.surface += 1; + } else { + state.layer += 1; + // A dismissal's shield takes every hit, a mouse's included. + state.shield.style.pointerEvents = 'auto'; + if (state.layer === 1) { + state.inertContent = makeContentInert(layer, state.shield); + } + } + let isReleased = false; + const release = () => { + if (isReleased) { + return; + } + isReleased = true; + const current = held.get(layer); + if (current == null) { + return; + } + if (scope === 'viewport') { + current.viewport -= 1; + } else if (scope === 'surface') { + current.surface -= 1; + } else { + current.layer -= 1; + if (current.layer === 0 && current.inertContent != null) { + restoreInert(current.inertContent); + current.inertContent = null; + } + } + if ( + current.viewport === 0 && + current.layer === 0 && + current.surface === 0 + ) { + if (current.shield != null) { + liveShields.delete(current.shield); + current.shield.remove(); + } + held.delete(layer); + stopHolding(layer); + } + }; + const end = 'finished' in until ? until.finished : until; + void Promise.resolve(end).then(release, release); + return release; +} + +const HELD_POINTERS: ReadonlySet = new Set(['touch', 'pen']); + +/** + * How long after a held press ends its click and compatibility mouse events + * still count as its own (WebKit sends them after `touchend`). + */ +const CLICK_WINDOW_MS = 800; + +/** How long a held press is followed past the hold's end, at most. */ +const STRAY_PRESS_MS = 10_000; + +const POINTER_EVENTS = [ + 'pointerdown', + 'pointermove', + 'pointerup', + 'pointercancel', +] as const; +const TOUCH_EVENTS = [ + 'touchstart', + 'touchmove', + 'touchend', + 'touchcancel', +] as const; +const PRESS_EVENTS = [ + 'mousedown', + 'mouseup', + 'click', + 'auxclick', + 'dblclick', + 'contextmenu', +] as const; + +/** The document's press hold, turned on if it is off. */ +function pressHoldFor(doc: Document): PressHold | null { + let hold = pressHolds.get(doc) ?? null; + if (hold == null) { + hold = createPressHold(doc); + if (hold != null) { + pressHolds.set(doc, hold); + } + } + return hold; +} + +/** + * Holds each finger or pen press that lands in `doc`'s window while any of + * its layers is held. Each press is held to its own end, even past the + * hold's end. A moving mouse passes through a presentation's shield. The + * hold hears input through the shared input stream, before its other + * subscribers, and stops each held event there. So no document or element + * listener hears it, and neither does press feedback or the gesture host. + * There is one per document. Its subscriptions end once nothing is held and + * the held presses and their clicks have ended. + */ +function createPressHold(doc: Document): PressHold | null { + const view = doc.defaultView; + if (view == null) { + return null; + } + /** Whether a new press is held: until the release. */ + let isHolding = true; + let isListening = true; + /** The held presses still down, by pointer id and by touch identifier. */ + const pointers = new Set(); + const touches = new Set(); + /** Whose press the next click is: a held one's, or any other's. */ + let lastPress: 'held' | 'free' | null = null; + /** Until when a click with no pointer type is a held press's. */ + let clickUntil = -Infinity; + let timer: ReturnType | undefined; + + const now = () => view.performance.now(); + const isPressDown = () => pointers.size > 0 || touches.size > 0; + + const swallow = (event: Event) => { + if (event.cancelable) { + event.preventDefault(); + } + event.stopImmediatePropagation(); + }; + + /** After the release: stops once the last held press and its click end. */ + const settle = () => { + if (isHolding || !isListening) { + return; + } + if (timer !== undefined) { + clearTimeout(timer); + } + if (isPressDown()) { + timer = setTimeout(stop, STRAY_PRESS_MS); + return; + } + const wait = clickUntil - now(); + if (wait > 0) { + timer = setTimeout(stop, wait); + } else { + stop(); + } + }; + + /** Whether a layer is still held (one that left the document is not). */ + const holdsNewPress = () => { + if (isHolding) { + liveLayers(doc); + } + return isHolding; + }; + + /** + * Whether a new press that lands on `target` is held. While a layer is held + * over the viewport, a press anywhere is held. While a layer is held only + * to its box (a `'surface'` hold), only a press on the layer is held. The + * page around it stays live. + */ + const holdsPressAt = (target: EventTarget | null) => { + if (!holdsNewPress()) { + return false; + } + for (const layer of liveLayers(doc)) { + const state = held.get(layer); + if (state == null) { + continue; + } + if (state.viewport > 0 || state.layer > 0) { + return true; + } + if ( + state.surface > 0 && + target instanceof Node && + containsAlongFlatTree(layer, target) + ) { + return true; + } + } + return false; + }; + + const pressEnded = () => { + clickUntil = now() + CLICK_WINDOW_MS; + settle(); + }; + + /** A shield takes hits for a finger or a pen, not for a moving mouse. */ + const followPointer = (pointerType: string) => { + for (const layer of liveLayers(doc)) { + const state = held.get(layer); + if (state?.shield == null) { + continue; + } + const value = + pointerType === 'mouse' && state.layer === 0 ? 'none' : 'auto'; + if (state.shield.style.pointerEvents !== value) { + state.shield.style.pointerEvents = value; + } + } + }; + + /** + * A held press that landed past the shield, which had let a mouse through, + * is captured to the shield. Its release then stays the hold's, and a + * light-dismissing layer stays open. A synthetic press has no active + * pointer to capture, so `setPointerCapture` throws NotFoundError. Its + * events are swallowed all the same. + */ + const captureToShield = (event: PointerEvent) => { + if (!event.isTrusted) { + return; + } + const top = liveLayers(doc).at(-1); + const shield = top == null ? null : held.get(top)?.shield; + if (shield == null || isInputShield(event.target as Node | null)) { + return; + } + shield.setPointerCapture(event.pointerId); + }; + + const onPointer = (event: Event): boolean => { + const {pointerId, pointerType, type} = event as PointerEvent; + // A finger or a pen raises the shields. Only a mouse that moves with no + // button down lowers them. So a mouse press that began on a shield stays + // the shield's to its end. Otherwise its click would go to the two + // targets' common ancestor, a dialog that reads it as a backdrop click. + const isFollowed = HELD_POINTERS.has(pointerType) + ? type === 'pointerdown' || type === 'pointermove' + : pointerType === 'mouse' && + type === 'pointermove' && + (event as PointerEvent).buttons === 0; + if (isFollowed && holdsNewPress()) { + followPointer(pointerType); + } + if (type === 'pointerdown') { + if (!HELD_POINTERS.has(pointerType) || !holdsPressAt(event.target)) { + // A mouse's press, or one after the hold: its click is its own, and a + // held press with its id ended unheard. + pointers.delete(pointerId); + lastPress = 'free'; + clickUntil = -Infinity; + settle(); + return false; + } + pointers.add(pointerId); + lastPress = 'held'; + captureToShield(event as PointerEvent); + } else if (!pointers.has(pointerId)) { + return false; + } + // Canceling the press keeps the browser from sending its compatibility + // mouse events, and with them a focus move. + swallow(event); + if (type === 'pointerup' || type === 'pointercancel') { + pointers.delete(pointerId); + pressEnded(); + } + return true; + }; + + const onTouch = (event: Event): boolean => { + const {changedTouches, touches: down, type} = event as TouchEvent; + const changed = Array.from(changedTouches); + if (type === 'touchstart') { + // A held touch that the screen no longer has ended unheard. Its target, + // the shield, left the document at the release, so its end reached no + // listener here. + const live = new Set(Array.from(down, touch => touch.identifier)); + for (const identifier of touches) { + if (!live.has(identifier)) { + touches.delete(identifier); + } + } + const heldTouches = changed.filter(touch => holdsPressAt(touch.target)); + if (heldTouches.length === 0) { + // A touch after the hold, or one beside a layer held only to its + // box, is a new one, whatever its identifier. + for (const touch of changed) { + touches.delete(touch.identifier); + } + lastPress = 'free'; + clickUntil = -Infinity; + settle(); + return false; + } + for (const touch of heldTouches) { + touches.add(touch.identifier); + } + lastPress = 'held'; + // Never canceled: canceling a touch's start would cancel the page's + // pinch-zoom with it. + event.stopImmediatePropagation(); + return true; + } + if (!changed.some(touch => touches.has(touch.identifier))) { + return false; + } + if (type === 'touchmove') { + event.stopImmediatePropagation(); + // One finger pans nothing; two still zoom the page. + if (down.length === 1 && event.cancelable) { + event.preventDefault(); + } + return true; + } + // A canceled end sends no click and no compatibility mouse events. + swallow(event); + for (const touch of changed) { + touches.delete(touch.identifier); + } + pressEnded(); + return true; + }; + + const onPress = (event: Event): boolean => { + // A click a key or assistive technology sends counts no press. + if ((event as MouseEvent).detail === 0) { + return false; + } + // A click that names its pointer is judged by that pointer. A + // compatibility mouse event, or a click sent as a plain mouse event, + // belongs to the last press. + const {pointerType} = event as Partial; + const isHeldPress = + lastPress === 'held' && + (pointerType == null || + pointerType === '' || + HELD_POINTERS.has(pointerType)); + if (isHeldPress && (isPressDown() || now() <= clickUntil)) { + swallow(event); + return true; + } + return false; + }; + + function stop(): void { + if (!isListening) { + return; + } + isListening = false; + if (pressHolds.get(doc) === pressHold) { + pressHolds.delete(doc); + } + if (timer !== undefined) { + clearTimeout(timer); + } + for (const unsubscribe of unsubscribers.splice(0)) { + unsubscribe(); + } + } + + // A touch's start and cancel are never canceled, so their subscriptions + // keep the stream passive for them. The hold hears each event first, so a + // held one reaches no other subscriber: press feedback and the gesture host + // never hear it. + const unsubscribers = [ + ...POINTER_EVENTS.map(type => + subscribeInput(view, type, onPointer, {cancels: true, first: true}), + ), + ...TOUCH_EVENTS.map(type => + subscribeInput(view, type, onTouch, { + cancels: type === 'touchmove' || type === 'touchend', + first: true, + }), + ), + ...PRESS_EVENTS.map(type => + subscribeInput(view, type, onPress, {cancels: true, first: true}), + ), + ]; + + const pressHold: PressHold = { + hold() { + isHolding = true; + if (timer !== undefined) { + clearTimeout(timer); + timer = undefined; + } + }, + release() { + if (!isHolding) { + return; + } + isHolding = false; + settle(); + }, + }; + return pressHold; +} + +/** + * Makes the layer's content inert, except the shield, and moves focus out of + * it. An element that turns inert while focused keeps its focus and its key + * activation. Enter and Space still click such a button until the engine's + * focus fixup runs, if it runs. Blurring it leaves focus on the document, as + * that fixup does. The layer element itself stays live. An inert subtree is + * no hit target, so the shield inside the layer still catches every hit. + */ +function makeContentInert( + layer: Element, + shield: Element, +): Map { + const content = new Map(); + for (const child of layer.children) { + if (child !== shield) { + content.set(child, child.hasAttribute('inert')); + child.setAttribute('inert', ''); + } + } + const focused = deepActiveElement(layer.ownerDocument); + if ( + focused instanceof HTMLElement && + [...content.keys()].some(child => containsAlongFlatTree(child, focused)) + ) { + focused.blur(); + } + return content; +} + +function restoreInert(content: Map): void { + for (const [element, wasInert] of content) { + if (!wasInert) { + element.removeAttribute('inert'); + } + } +} diff --git a/packages/core/src/MobileNav/MobileNav.doc.mjs b/packages/core/src/MobileNav/MobileNav.doc.mjs index b60f705494546..b150f2b535ac6 100644 --- a/packages/core/src/MobileNav/MobileNav.doc.mjs +++ b/packages/core/src/MobileNav/MobileNav.doc.mjs @@ -98,7 +98,7 @@ export const docs = { name: 'onOpenChange', type: '(isOpen: boolean) => void', description: - 'Called when the drawer visibility changes (backdrop click, Escape key, or close button). Inside AppShell, this is managed automatically via context.', + 'Called when the drawer visibility changes (backdrop click, Escape key, or close button). Inside AppShell, this is managed automatically via context. On a phone or tablet (a coarse primary pointer), the drawer takes no tap or drag while it slides in; keys and assistive technology still act. After a close, focus returns to the element that opened it once its dialog closes.', }, { name: 'children', @@ -203,7 +203,7 @@ export const docsZh = { name: 'onOpenChange', type: '(isOpen: boolean) => void', description: - '当抽屉可见性变化时调用(点击背景遮罩、按 Escape 键或点击关闭按钮)。', + '当抽屉可见性变化时调用(点击背景遮罩、按 Escape 键或点击关闭按钮)。在手机或平板上(主指针为粗指针时),抽屉滑入期间不接受点按或拖动;键盘和辅助技术仍可操作。关闭后,焦点会在对话框关闭时回到打开它的元素。', required: true, }, { @@ -311,7 +311,7 @@ export const docsDense = { propDescriptions: { isOpen: 'whether drawer is open', onOpenChange: - 'called when drawer visibility changes (backdrop click, Escape, close button)', + 'called when drawer visibility changes (backdrop click, Escape, close button); under a coarse primary pointer the drawer takes no tap or drag while it slides in (keys still act)', children: 'drawer content; typically SideNavSection/SideNavItem or any ReactNode', header: diff --git a/packages/core/src/MobileNav/MobileNav.tsx b/packages/core/src/MobileNav/MobileNav.tsx index a09e28856c13d..58e3d529afbec 100644 --- a/packages/core/src/MobileNav/MobileNav.tsx +++ b/packages/core/src/MobileNav/MobileNav.tsx @@ -4,7 +4,8 @@ /** * @file MobileNav.tsx - * @input Uses React, useEffect, useRef, useCallback, ReactNode, StyleX + * @input Uses React, useEffect, useRef, useCallback, ReactNode, StyleX and + * the Layer module's entrance hold * @output Exports MobileNav component and MobileNavProps * @position Core implementation; consumed by index.ts * @@ -38,6 +39,7 @@ * - /packages/core/src/MobileNav/index.ts (exports if types change) * - /packages/core/src/Layer/useLayerDismissal.ts (dismissal stack) * - /packages/core/src/hooks/useScrollLock.ts (the page's scroll lock) + * - /packages/core/src/MobileNav/MobileNavTouchPresentation.test.tsx (touch) * - /packages/cli/assets/templates/blocks/components/MobileNav/ (showcase blocks) */ @@ -63,6 +65,7 @@ import {Button} from '../Button'; import {Icon} from '../Icon'; import {Heading} from '../Heading/Heading'; import {useAppShellMobile} from '../AppShell/AppShellMobileContext'; +import {holdEntranceInput} from '../Layer/holdEntranceInput'; import {mergeProps, composeEventHandlers} from '../utils'; import {layerTextReset} from '../Layer/layerTextReset.stylex'; import {layerStructureReset} from '../Layer/layerStructureReset.stylex'; @@ -282,6 +285,14 @@ const dynamicStyles = stylex.create({ * own scheduled `dialog.close()` has a chance to run (#5701). */ export const MAX_CLOSE_DELAY_MS = 250; +/** + * Longest the drawer slides in or out for, in ms. Both run for the theme's + * `--duration-medium`: 410 ms by default, and at most 545 ms on the default + * scale (`--duration-medium-max`). The slide-out keeps playing after the + * dialog closes, while the dialog's `display` transition keeps it rendered. + * The touch hold on the slide-in ends by this time. + */ +export const MAX_EXIT_MS = 550; /** Fraction of the hold to close at, so the close never lands on its boundary. */ const CLOSE_WITHIN_HOLD = 0.6; @@ -504,7 +515,11 @@ export function MobileNav({ ); const dialogRef = useRef(null); + const drawerRef = useRef(null); const closeTimeoutRef = useRef>(null); + // The input hold on the drawer's layer while it slides in under a coarse + // primary pointer. It is null under a fine one and once the slide-in ends. + const releaseHoldRef = useRef<(() => void) | null>(null); // Element that was focused when the drawer opened; focus goes back to it // once the native dialog has closed (see closeAndRestoreFocus). const triggerElementRef = useRef(null); @@ -569,6 +584,8 @@ export function MobileNav({ } if (isOpen) { + releaseHoldRef.current?.(); + releaseHoldRef.current = null; if (!dialog.open) { // Capture the opener before showModal() pulls focus into the top // layer. Only on the transition into open: a reopen while the delayed @@ -578,7 +595,16 @@ export function MobileNav({ document.activeElement as HTMLElement | null; dialog.showModal(); } + // Under a coarse primary pointer, nothing takes a touch until the + // slide-in ends, at most MAX_EXIT_MS in. A close holds nothing, because + // only an entrance is held. Under a fine one, nothing is held. + releaseHoldRef.current = holdEntranceInput(dialog, { + entrance: drawerRef.current, + capMs: MAX_EXIT_MS, + }); } else if (dialog.open) { + releaseHoldRef.current?.(); + releaseHoldRef.current = null; closeTimeoutRef.current = setTimeout(() => { closeAndRestoreFocus(dialog, triggerElementRef); setIsCloseHeld(false); @@ -594,6 +620,10 @@ export function MobileNav({ clearTimeout(closeTimeoutRef.current); closeTimeoutRef.current = null; } + // The hold this run took ends with it: a reopen, a close or an + // unmount mid-slide never leaves input blocked. + releaseHoldRef.current?.(); + releaseHoldRef.current = null; }; }, [isOpen]); @@ -613,6 +643,8 @@ export function MobileNav({ useEffect(() => { const dialog = dialogRef.current; return () => { + releaseHoldRef.current?.(); + releaseHoldRef.current = null; if (dialog?.open) { closeAndRestoreFocus(dialog, triggerElementRef); } @@ -704,6 +736,7 @@ export function MobileNav({ {/* Drawer panel — tabIndex so showModal() focuses the drawer, not the close button */}
+ + + Home + + + ); +} + +// jsdom has no Web Animations, so a case under a finger gives the drawer a +// slide-in (stubSlideIn) that ends when the case says, or at MAX_EXIT_MS. +// jsdom resolves no `var()`, so a close lands MAX_CLOSE_DELAY_MS in. +async function advance(ms: number) { + await act(async () => { + vi.advanceTimersByTime(ms); + }); +} + +beforeAll(() => { + // jsdom has no showModal/close: model the dialog focusing steps + // (showModal() moves focus into the dialog; close() restores nothing). + HTMLDialogElement.prototype.showModal = function (this: HTMLDialogElement) { + this.setAttribute('open', ''); + this.querySelector('[tabindex]')?.focus(); + }; + HTMLDialogElement.prototype.close = function (this: HTMLDialogElement) { + this.removeAttribute('open'); + }; +}); + +class MockResizeObserver { + observe() {} + unobserve() {} + disconnect() {} +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.stubGlobal('ResizeObserver', MockResizeObserver); +}); + +afterEach(() => { + vi.useRealTimers(); + document.documentElement.style.overflow = ''; + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +/** + * Gives the drawer a running slide-in transition (Web Animations' + * `getAnimations()`, which jsdom lacks) whose end the test decides. + */ +function stubSlideIn() { + let end = () => {}; + const finished = new Promise(resolve => { + end = resolve; + }); + const slideIn = { + playState: 'running', + finished, + effect: {getComputedTiming: () => ({endTime: 410})}, + }; + Object.defineProperty(Element.prototype, 'getAnimations', { + configurable: true, + value(this: Element) { + return this.matches('dialog [tabindex="-1"]') ? [slideIn] : []; + }, + }); + return { + async end() { + await act(async () => { + end(); + }); + }, + }; +} + +describe('MobileNav under a finger', () => { + beforeEach(() => { + stubMatchMedia({reduceMotion: false, pointer: 'coarse'}); + }); + + afterEach(() => { + Reflect.deleteProperty(Element.prototype, 'getAnimations'); + }); + + it('takes no touch until the slide-in ends, at most MAX_EXIT_MS in', async () => { + stubSlideIn(); + render(); + const open = screen.getByRole('button', {name: 'Open'}); + open.focus(); + fireEvent.click(open); + const dialog = screen.getByTestId('mobile-nav'); + expect(dialog).toHaveAttribute('open'); + expect(isInHeldLayer(dialog)).toBe(true); + + await advance(MAX_EXIT_MS + 10); + expect(isInHeldLayer(dialog)).toBe(false); + }); + + it('takes touch again when its slide-in transition ends, however soon (FR35)', async () => { + const slideIn = stubSlideIn(); + render(); + fireEvent.click(screen.getByRole('button', {name: 'Open'})); + const dialog = screen.getByTestId('mobile-nav'); + await advance(300); + expect(isInHeldLayer(dialog)).toBe(true); + + await slideIn.end(); + expect(isInHeldLayer(dialog)).toBe(false); + }); + + it('holds until its slide-in transition ends, past a timer of its duration (FR35)', async () => { + // A 410 ms slide-in starts a frame or two after the drawer opens, so it + // ends after a 410 ms timer started on open would. + const slideIn = stubSlideIn(); + render(); + const drawer = screen + .getByTestId('mobile-nav') + .querySelector('[tabindex="-1"]'); + drawer?.style.setProperty('transition-duration', '0.41s'); + fireEvent.click(screen.getByRole('button', {name: 'Open'})); + const dialog = screen.getByTestId('mobile-nav'); + await advance(420); + expect(isInHeldLayer(dialog)).toBe(true); + + await slideIn.end(); + expect(isInHeldLayer(dialog)).toBe(false); + }); + + it('keeps keys and assistive technology live while it slides in (spec:AST-094 FR35)', () => { + stubSlideIn(); + render(); + const open = screen.getByRole('button', {name: 'Open'}); + open.focus(); + fireEvent.click(open); + const dialog = screen.getByTestId('mobile-nav'); + expect(isInHeldLayer(dialog)).toBe(true); + + // Only pointer input is held: the drawer keeps the focus showModal() + // gave it, and its content stays out of any inert or hidden subtree, so + // keys and assistive technology still reach it. + expect(dialog.contains(document.activeElement)).toBe(true); + const home = screen.getByRole('link', {name: 'Home'}); + expect(home.closest('[inert]')).toBeNull(); + expect(home.closest('[aria-hidden="true"]')).toBeNull(); + home.focus(); + expect(document.activeElement).toBe(home); + }); + + it('holds nothing once a close is requested: the leaving drawer stays live until the dialog closes, at most 250 ms in (FR5), then gives focus back (spec:AST-094 FR35 holds entrances only)', async () => { + stubSlideIn(); + render(); + const open = screen.getByRole('button', {name: 'Open'}); + open.focus(); + fireEvent.click(open); + await advance(MAX_EXIT_MS + 10); + const dialog = screen.getByTestId('mobile-nav'); + + fireEvent.click(screen.getByRole('button', {name: /close navigation/i})); + await advance(100); + // Before the close: still open and modal, and nothing is held. + expect(dialog).toHaveAttribute('open'); + expect(isInHeldLayer(dialog)).toBe(false); + expect( + screen.getByRole('link', {name: 'Home', hidden: true}).closest('[inert]'), + ).toBeNull(); + + // The close keeps the mouse's timing, at most MAX_CLOSE_DELAY_MS in. + await advance(MAX_CLOSE_DELAY_MS - 100 + 10); + expect(dialog).not.toHaveAttribute('open'); + expect(document.activeElement).toBe(open); + }); + + it('reopened before the dialog closes, keeps focus in the drawer', async () => { + stubSlideIn(); + render(); + const open = screen.getByRole('button', {name: 'Open'}); + open.focus(); + fireEvent.click(open); + await advance(MAX_EXIT_MS + 10); + const dialog = screen.getByTestId('mobile-nav'); + + fireEvent.click(screen.getByRole('button', {name: /close navigation/i})); + await advance(100); + fireEvent.click(open); + expect(dialog).toHaveAttribute('open'); + expect(dialog.contains(document.activeElement)).toBe(true); + expect( + screen.getByRole('link', {name: 'Home', hidden: true}).closest('[inert]'), + ).toBeNull(); + + await advance(MAX_EXIT_MS + 10); + expect(dialog).toHaveAttribute('open'); + expect(isInHeldLayer(dialog)).toBe(false); + }); + it('holds nothing when the drawer has no slide-in to wait for', () => { + render(); + fireEvent.click(screen.getByRole('button', {name: 'Open'})); + const dialog = screen.getByTestId('mobile-nav'); + expect(dialog).toHaveAttribute('open'); + expect(isInHeldLayer(dialog)).toBe(false); + }); +}); + +describe('MobileNav under a mouse', () => { + beforeEach(() => { + stubMatchMedia({reduceMotion: false, pointer: 'fine'}); + }); + + it('holds nothing, and closes on its own timing as before', async () => { + render(); + const open = screen.getByRole('button', {name: 'Open'}); + open.focus(); + fireEvent.click(open); + const dialog = screen.getByTestId('mobile-nav'); + expect(dialog).toHaveAttribute('open'); + expect(isInHeldLayer(dialog)).toBe(false); + + fireEvent.click(screen.getByRole('button', {name: /close navigation/i})); + expect(isInHeldLayer(dialog)).toBe(false); + expect( + screen.getByRole('link', {name: 'Home', hidden: true}).closest('[inert]'), + ).toBeNull(); + await advance(260); + expect(dialog).not.toHaveAttribute('open'); + expect(document.activeElement).toBe(open); + }); +}); diff --git a/packages/core/src/MobileNav/__tests__/MobileNavTouchPresentation.a11y.chromium.spec.ts b/packages/core/src/MobileNav/__tests__/MobileNavTouchPresentation.a11y.chromium.spec.ts new file mode 100644 index 0000000000000..6aae34b7e795b --- /dev/null +++ b/packages/core/src/MobileNav/__tests__/MobileNavTouchPresentation.a11y.chromium.spec.ts @@ -0,0 +1,520 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file MobileNavTouchPresentation.a11y.chromium.spec.ts + * @input The built MobileNav "Default" story, real Chromium touch input in a + * phone context and a mouse on a fine-pointer page + * @output Browser evidence that under a finger the drawer takes no tap while + * it slides in, while keys and assistive technology stay live; that a close + * holds nothing (spec:AST-094 FR35 holds entrances only): the dialog closes + * on its own timing (at most 250 ms in, FR5), when focus returns to the + * opener and the page takes taps again; the rest of the slide-out after the + * close takes no tap and is hidden from assistive technology (FR5). Under a + * mouse nothing is held and the close keeps its timing. + * @position Chromium proof for MobileNav's touch presentation (MobileNav.tsx); + * the jsdom layer is MobileNavTouchPresentation.test.tsx + * + * A case that must act inside the slide-in or the close stops the page's + * clock first, so the close's own delay and the slide-in's cap wait for it + * however long the runner takes between steps, and + * it runs the clock on by exact amounts. Where the drawer's place or its + * slide-in matters, the slide is slowed to a minute; the close keeps its own + * timing either way. + */ + +import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright'; +import { + DEFAULT_STORYBOOK_DIR, + serveStorybook, + type StaticServer, +} from '@astryxdesign/a11y-spec/storybook'; + +let storybook: StaticServer; +test.beforeAll(async () => { + storybook = await serveStorybook( + process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR, + ); +}); +test.afterAll(async () => { + await storybook?.close(); +}); + +test.use({ + hasTouch: true, + isMobile: true, + viewport: {width: 402, height: 714}, + deviceScaleFactor: 1, +}); + +test.beforeEach(async ({page}) => { + // The page's clock runs with real time until a case stops it (stopClock). + await page.clock.install(); + // Counts the key presses that reach the window (settleInput). + await page.addInitScript(() => { + const counter = window as unknown as {__keydowns: number}; + counter.__keydowns = 0; + window.addEventListener( + 'keydown', + () => { + counter.__keydowns += 1; + }, + true, + ); + }); +}); + +const MOBILE_NAV_STORY = 'core-mobilenav--default'; + +interface LoggedEvent { + type: 'click' | 'focus' | 'open'; + /** performance.now() in the page, ms. */ + t: number; + /** The event's target is inside the dialog (or is the dialog). */ + inDialog?: boolean; + /** The event's target is the dialog itself: its backdrop. */ + onBackdrop?: boolean; + /** The event's target is inside the drawer panel. */ + inDrawer?: boolean; + /** The focused element's accessible name, for focus events. */ + name?: string | null; + /** The dialog's `open` attribute, for open events. */ + open?: boolean; +} + +/** + * Opens the drawer from its button with a tap, waits for the slide-in, and + * starts logging clicks, focus moves and the dialog's `open` attribute. + */ +async function openNav( + page: Page, + { + input = 'touch', + tokenDefault = false, + }: { + input?: 'touch' | 'mouse'; + /** + * Runs the slide at the token default, `--duration-medium: 410ms`, rather + * than the story theme's 300 ms, so a close at the end of the slide-out + * (410 ms) and one on FR5's timing (at most 250 ms) are far apart. + */ + tokenDefault?: boolean; + } = {}, +) { + await page.goto( + `${storybook.origin}/iframe.html?id=${MOBILE_NAV_STORY}&viewMode=story`, + ); + if (tokenDefault) { + await page.addStyleTag({ + content: '* { --duration-medium: 410ms !important; }', + }); + } + const opener = page.getByRole('button', {name: 'Open Navigation'}); + // A tap focuses the button in Chromium; focusing it first makes the opener + // explicit for the focus-return assertions. + await opener.focus(); + if (input === 'mouse') { + await opener.click(); + } else { + await opener.tap(); + } + const nav = page.getByRole('dialog'); + await expect(nav).toBeVisible(); + const drawer = nav.locator('[tabindex="-1"]').first(); + await drawer.evaluate(async element => { + await Promise.all(element.getAnimations().map(async a => a.finished)); + }); + const box = await drawer.boundingBox(); + const viewport = page.viewportSize(); + if (box == null || viewport == null) { + throw new Error('the drawer did not render'); + } + const durationMs = await drawer.evaluate(element => { + const value = getComputedStyle(element).transitionDuration.split(',')[0]; + return value.endsWith('ms') ? parseFloat(value) : parseFloat(value) * 1000; + }); + await page.evaluate(() => { + const events: LoggedEvent[] = []; + (window as unknown as {__events: LoggedEvent[]}).__events = events; + const dialog = document.querySelector('dialog'); + if (dialog == null) { + throw new Error('no dialog'); + } + new MutationObserver(() => { + events.push({ + type: 'open', + t: performance.now(), + open: dialog.hasAttribute('open'), + }); + }).observe(dialog, {attributes: true, attributeFilter: ['open']}); + document.addEventListener( + 'click', + event => { + const target = event.target as Element; + // Keep the story's nav links from navigating the frame. + if (target.closest('a')) { + event.preventDefault(); + } + events.push({ + type: 'click', + t: performance.now(), + inDialog: target.closest('dialog') != null, + onBackdrop: target === dialog, + inDrawer: target.closest('dialog [tabindex="-1"]') != null, + }); + }, + true, + ); + document.addEventListener( + 'focusin', + event => { + const target = event.target as HTMLElement; + events.push({ + type: 'focus', + t: performance.now(), + name: target.getAttribute('aria-label') ?? target.textContent, + }); + }, + true, + ); + }); + // The backdrop is the strip the drawer leaves free. + const strip = + box.x > 0.5 + ? {from: 0, to: box.x} + : {from: box.x + box.width, to: viewport.width}; + const backdrop = {x: (strip.from + strip.to) / 2, y: viewport.height / 2}; + return {nav, drawer, durationMs, backdrop}; +} + +const loggedEvents = async (page: Page) => + page.evaluate( + () => (window as unknown as {__events: LoggedEvent[]}).__events, + ); + +const now = async (page: Page) => page.evaluate(() => performance.now()); + +/** The dialog's state at this instant. */ +const state = async (page: Page) => + page.evaluate(() => { + const dialog = document.querySelector('dialog'); + const drawer = dialog?.querySelector('[tabindex="-1"]'); + return { + modal: dialog?.matches(':modal') ?? false, + drawerInert: drawer?.inert ?? false, + scrim: + dialog == null ? null : +getComputedStyle(dialog, '::backdrop').opacity, + focusInDrawer: drawer != null && drawer.contains(document.activeElement), + focusOnOpener: + document.activeElement?.getAttribute('aria-label') === + 'Open Navigation', + }; + }); + +const middleOf = (box: {x: number; y: number; width: number; height: number}) => + [box.x + box.width / 2, box.y + box.height / 2] as const; + +/** + * Stops the page's clock: no timer fires (the close's own delay, the + * slide-in's cap) until `advance` runs the clock on. + * Until here it runs with real time; the pause is a minute ahead, so always in + * its future. + */ +async function stopClock(page: Page) { + const pageNow = await page.evaluate(() => Date.now()); + await page.clock.pauseAt(pageNow + 60_000); + return { + /** Runs the page's clock `ms` on, firing every timer due by then. */ + advance: async (ms: number) => page.clock.runFor(ms), + }; +} + +/** Slows the drawer's slide to a minute, so it is still moving at each step. */ +const slowSlide = async (page: Page) => + page.addStyleTag({content: '* { --duration-medium: 60s !important; }'}); + +/** + * Waits until every tap sent before has reached the page, clicks and all: a + * Shift press goes through the same input queue after them, and no hold takes + * keys (FR35). + */ +async function settleInput(page: Page) { + const keydowns = async () => + page.evaluate(() => (window as unknown as {__keydowns: number}).__keydowns); + const before = await keydowns(); + await page.keyboard.press('Shift'); + await expect.poll(keydowns).toBe(before + 1); +} + +test('a close holds nothing: the dialog closes at most 250 ms in (FR5), then focus returns', async ({ + page, +}) => { + const {durationMs, backdrop} = await openNav(page, {tokenDefault: true}); + expect(durationMs).toBeGreaterThan(400); + + const clock = await stopClock(page); + await page.touchscreen.tap(backdrop.x, backdrop.y); + const closeTapped = await now(page); + await settleInput(page); + // Inside the close, which cannot end while the page's clock is stopped: + // still the modal dialog with its drawer laid out, and nothing held + // (spec:AST-094 FR35 holds an entrance only): no shield, the leaving + // drawer live. + const early = await state(page); + expect(early.modal).toBe(true); + const drawerBox = await page + .locator('dialog [tabindex="-1"]') + .first() + .boundingBox(); + expect(drawerBox?.width ?? 0).toBeGreaterThan(0); + expect(early.drawerInert).toBe(false); + await expect(page.locator('dialog > [popover]')).toHaveCount(0); + + await clock.advance(1000); + // The dialog closed on its own timing, at most 250 ms in, well before the + // 410 ms slide-out ended... + const events = await loggedEvents(page); + const closed = events.find(e => e.type === 'open' && e.open === false); + expect(closed).toBeDefined(); + const closedIn = (closed?.t ?? Infinity) - closeTapped; + expect(closedIn).toBeGreaterThan(0); + expect(closedIn).toBeLessThanOrEqual(250); + // ...and focus went back to the opener as it did, in the same task. + const returned = events.find( + e => e.type === 'focus' && e.name === 'Open Navigation', + ); + expect(returned?.t).toBe(closed?.t); + const after = await state(page); + expect(after.modal).toBe(false); + expect(after.drawerInert).toBe(false); +}); + +test('the page takes taps again once the dialog has closed', async ({page}) => { + const {backdrop} = await openNav(page, {tokenDefault: true}); + await slowSlide(page); + + const clock = await stopClock(page); + await page.touchscreen.tap(backdrop.x, backdrop.y); + await settleInput(page); + await clock.advance(1000); + expect((await state(page)).modal).toBe(false); + // The dialog has closed while the drawer still slides out (a minute long + // here): the page takes the next tap. + await page.touchscreen.tap(backdrop.x, backdrop.y); + await settleInput(page); + + const events = await loggedEvents(page); + const closed = events.find(e => e.type === 'open' && e.open === false); + expect(closed).toBeDefined(); + const clicks = events.filter(e => e.type === 'click'); + const pageClicks = clicks.filter(e => !e.inDialog); + // Two clicks: the close tap's on the backdrop, and the page's after the + // close. + expect(clicks).toHaveLength(2); + expect(clicks[0].onBackdrop).toBe(true); + expect(clicks[0].t).toBeLessThan(closed?.t ?? -Infinity); + expect(pageClicks).toHaveLength(1); + expect(pageClicks[0]).toBe(clicks[1]); + expect(pageClicks[0].t).toBeGreaterThan(closed?.t ?? Infinity); +}); + +/** + * The roles and names the browser's accessibility tree gives assistive + * technology: its nodes that are not ignored. + */ +async function exposedToAssistiveTech(page: Page): Promise { + const cdp = await page.context().newCDPSession(page); + try { + const {nodes} = (await cdp.send('Accessibility.getFullAXTree')) as { + nodes: { + ignored: boolean; + role?: {value: string}; + name?: {value: string}; + }[]; + }; + return nodes + .filter(node => !node.ignored) + .map(node => + `${node.role?.value ?? ''} ${node.name?.value ?? ''}`.trim(), + ); + } finally { + await cdp.detach(); + } +} + +/** Whether a hit at a point lands inside the drawer panel. */ +const hitsDrawer = async (page: Page, point: readonly [number, number]) => + page.evaluate( + ([x, y]) => + document.elementFromPoint(x, y)?.closest('dialog [tabindex="-1"]') != + null, + point, + ); + +test('after the dialog closes, the rest of the slide-out takes no tap and is hidden from assistive technology (FR5)', async ({ + page, +}) => { + const {backdrop} = await openNav(page, {tokenDefault: true}); + const link = page.locator('dialog a', {hasText: 'Dashboard'}); + const linkBox = async () => { + const box = await link.boundingBox(); + if (box == null) { + throw new Error('no link box'); + } + return box; + }; + // Open, its link takes a hit and assistive technology reads the dialog and + // its links: what the checks below look for is there to find. + expect(await hitsDrawer(page, middleOf(await linkBox()))).toBe(true); + expect(await exposedToAssistiveTech(page)).toEqual( + expect.arrayContaining(['dialog Navigation', 'link Dashboard']), + ); + + await slowSlide(page); + const clock = await stopClock(page); + await page.touchscreen.tap(backdrop.x, backdrop.y); + await settleInput(page); + await clock.advance(1000); + // The dialog has closed while the drawer still slides out (a minute long + // here): the drawer and its link are there, painted on screen. + expect((await state(page)).modal).toBe(false); + expect( + await page.evaluate(() => document.querySelector('dialog')?.open), + ).toBe(false); + const tail = await linkBox(); + const viewport = page.viewportSize(); + expect(tail.width).toBeGreaterThan(0); + expect(tail.x).toBeGreaterThanOrEqual(0); + expect(tail.x + tail.width).toBeLessThanOrEqual(viewport?.width ?? 0); + const onLink = middleOf(tail); + // A tap on the leaving drawer reaches the page, not the drawer... + expect(await hitsDrawer(page, onLink)).toBe(false); + await page.touchscreen.tap(...onLink); + await settleInput(page); + const clicks = (await loggedEvents(page)).filter(e => e.type === 'click'); + // The close tap's click on the backdrop, then the page's. + expect(clicks).toHaveLength(2); + expect(clicks[0].onBackdrop).toBe(true); + expect(clicks[1].inDialog).toBe(false); + // ...and assistive technology reads none of it. + const exposed = await exposedToAssistiveTech(page); + expect(exposed).not.toContain('dialog Navigation'); + expect(exposed).not.toContain('link Dashboard'); + expect(exposed).not.toContain('button Close navigation'); +}); + +/** Opens the drawer with a tap while the page's clock is stopped. */ +async function openInsideSlideIn(page: Page) { + await page.goto( + `${storybook.origin}/iframe.html?id=${MOBILE_NAV_STORY}&viewMode=story`, + ); + await slowSlide(page); + const opener = await page + .getByRole('button', {name: 'Open Navigation'}) + .boundingBox(); + if (opener == null) { + throw new Error('no opener box'); + } + const clock = await stopClock(page); + await page.touchscreen.tap(...middleOf(opener)); + await settleInput(page); + await expect.poll(async () => (await state(page)).modal).toBe(true); + return clock; +} + +test('a tap during the slide-in reaches nothing', async ({page}) => { + const clock = await openInsideSlideIn(page); + const viewport = page.viewportSize(); + if (viewport == null) { + throw new Error('no viewport'); + } + // Early in the slide-in, on the strip the drawer leaves free: under iOS's + // rule the tap is dropped, so it does not close the drawer. The point is + // the backdrop's: inside the dialog, outside the drawer, which is there + // and laid out. + const tap = {x: 8, y: viewport.height / 2}; + const dialogBox = await page.locator('dialog').boundingBox(); + const drawerBox = await page + .locator('dialog [tabindex="-1"]') + .first() + .boundingBox(); + if (dialogBox == null || drawerBox == null) { + throw new Error('no dialog or drawer box'); + } + expect(drawerBox.width).toBeGreaterThan(0); + expect(drawerBox.height).toBeGreaterThan(0); + expect(tap.x).toBeGreaterThan(dialogBox.x); + expect(tap.x).toBeLessThan(dialogBox.x + dialogBox.width); + expect(tap.x < drawerBox.x || tap.x > drawerBox.x + drawerBox.width).toBe( + true, + ); + await page.touchscreen.tap(tap.x, tap.y); + await settleInput(page); + // A close asked for would have closed the dialog by now: the page's clock + // ran past the close's delay and the slide-in's cap. + await clock.advance(1000); + expect( + await page.evaluate(() => document.querySelector('dialog')?.open), + ).toBe(true); +}); + +test('keys and assistive technology stay live during the slide-in (spec:AST-094 FR35)', async ({ + page, +}) => { + await openInsideSlideIn(page); + // Early in the slide-in, while a tap is still held: a key moves focus into + // the drawer, and its links stay in the accessibility tree. + await page.keyboard.press('Tab'); + const live = await page.evaluate(() => { + const dialog = document.querySelector('dialog'); + const drawer = dialog?.querySelector('[tabindex="-1"]'); + const focused = document.activeElement; + return { + sliding: + drawer?.getAnimations().some(a => a.playState === 'running') ?? false, + focusInDialog: dialog?.contains(focused) ?? false, + focusInert: focused?.closest('[inert]') != null, + }; + }); + expect(live.sliding).toBe(true); + expect(live.focusInDialog).toBe(true); + expect(live.focusInert).toBe(false); + await expect(page.getByRole('link', {name: 'Dashboard'})).toHaveCount(1); +}); + +test.describe('under a mouse', () => { + test.use({hasTouch: false, isMobile: false}); + + test('nothing is held, and the dialog closes partway into the slide-out, as before', async ({ + page, + }) => { + const {drawer, durationMs, backdrop} = await openNav(page, { + input: 'mouse', + }); + expect( + await page.evaluate(() => matchMedia('(pointer: fine)').matches), + ).toBe(true); + + const clock = await stopClock(page); + await page.mouse.click(backdrop.x, backdrop.y); + const closeClicked = await now(page); + await settleInput(page); + // No hold: the leaving drawer is not inert. + expect( + await drawer.evaluate(element => (element as HTMLElement).inert), + ).toBe(false); + await clock.advance(1000); + + const events = await loggedEvents(page); + const closed = events.find(e => e.type === 'open' && e.open === false); + expect(closed).toBeDefined(); + // The close's own timing: at most 250 ms in, well before the slide-out + // ends. + const closedIn = (closed?.t ?? Infinity) - closeClicked; + expect(closedIn).toBeGreaterThan(0); + expect(closedIn).toBeLessThan(durationMs); + expect(closedIn).toBeLessThanOrEqual(250); + expect( + events.some(e => e.type === 'focus' && e.name === 'Open Navigation'), + ).toBe(true); + }); +}); diff --git a/packages/core/src/__tests__/stubMatchMedia.test.ts b/packages/core/src/__tests__/stubMatchMedia.test.ts index 01846d67f3c72..4b749123c5b79 100644 --- a/packages/core/src/__tests__/stubMatchMedia.test.ts +++ b/packages/core/src/__tests__/stubMatchMedia.test.ts @@ -55,6 +55,17 @@ describe('stubMatchMedia', () => { expect(matchMedia('(max-width: 768px)').matches).toBe(true); }); + it('answers the pointer queries from their own knob, fine by default', () => { + stubMatchMedia(); + expect(matchMedia('(pointer: coarse)').matches).toBe(false); + expect(matchMedia('(pointer: fine)').matches).toBe(true); + + stubMatchMedia({pointer: 'coarse'}); + expect(matchMedia('(pointer: coarse)').matches).toBe(true); + expect(matchMedia('(pointer: fine)').matches).toBe(false); + expect(matchMedia('(max-width: 768px)').matches).toBe(true); + }); + it('lets a non-motion query be answered false', () => { // Above the breakpoint, motion still reduced — the other axis of the // combination, so neither knob can be quietly driving both. diff --git a/packages/core/src/__tests__/stubMatchMedia.ts b/packages/core/src/__tests__/stubMatchMedia.ts index 5fad7a2030964..5c66262ed49c9 100644 --- a/packages/core/src/__tests__/stubMatchMedia.ts +++ b/packages/core/src/__tests__/stubMatchMedia.ts @@ -19,9 +19,11 @@ * it is exercising the real delay. The failure mode is invisible: every test * still passes. * - * So the two answers are separate knobs here. `reduceMotion` answers - * `prefers-reduced-motion` only; `matches` answers everything else (breakpoint - * width queries, which tests below a breakpoint want to be true). + * So the answers are separate knobs here. `reduceMotion` answers + * `prefers-reduced-motion` only; `pointer` answers the pointer queries (a + * blanket `true` would also make the pointer coarse, rerouting anything that + * behaves differently under a finger); `matches` answers everything else + * (breakpoint width queries, which tests below a breakpoint want to be true). * * SYNC: When modified, update this header. */ @@ -31,10 +33,26 @@ import {vi} from 'vitest'; export interface StubMatchMediaOptions { /** Whether the user prefers reduced motion. */ reduceMotion?: boolean; + /** The primary pointer: `(pointer: coarse)` matches only for `'coarse'`. */ + pointer?: 'fine' | 'coarse'; /** Answer for every other query — width breakpoints, hover, etc. */ matches?: boolean; } +/** Answer a `pointer` query, or null if it isn't one. */ +function answerPointer( + query: string, + pointer: 'fine' | 'coarse', +): boolean | null { + if (query.includes('pointer: coarse')) { + return pointer === 'coarse'; + } + if (query.includes('pointer: fine')) { + return pointer === 'fine'; + } + return null; +} + /** * Answer a `prefers-reduced-motion` query, or null if it isn't one. * @@ -77,12 +95,16 @@ function answerReducedMotion( */ export function stubMatchMedia({ reduceMotion = false, + pointer = 'fine', matches = true, }: StubMatchMediaOptions = {}): void { vi.stubGlobal( 'matchMedia', vi.fn((query: string) => ({ - matches: answerReducedMotion(query, reduceMotion) ?? matches, + matches: + answerReducedMotion(query, reduceMotion) ?? + answerPointer(query, pointer) ?? + matches, media: query, onchange: null, addEventListener: vi.fn(), diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.ts index 712119d4d555a..77c27798ef3e4 100644 --- a/packages/core/src/gestures/GestureHost.ts +++ b/packages/core/src/gestures/GestureHost.ts @@ -3,7 +3,8 @@ /** * @file GestureHost.ts * @input DOM touch, pointer, click, contextmenu, scroll and focus events of - * one document; elements with recognizers and consumers attached + * one document; elements with recognizers and consumers attached; the + * input hold's held layers (Layer/inputHold `holdsTouch`) * @output Exports GestureHost (the DOM side of the gesture system) and * getGestureHost (one host per document) * @position Browser adapter of packages/core/src/gestures: turns real events @@ -149,6 +150,7 @@ import { import {containsAlongFlatTree} from '../utils/flatTree'; import {isIosWebKit} from '../utils/touchQueries'; import {type WheelSegment, WheelSegmenter} from './wheelSegmenter'; +import {holdsTouch} from '../Layer/inputHold'; import { gestureHostStyle, type GestureHostStyle, @@ -2128,9 +2130,12 @@ export class GestureHost { const recognizers: GestureRecognizer[] = []; let consumer: TouchConsumer | null = null; let consumerElement: Element | null = null; + // A layer that the input hold holds takes no touch while it presents. + // The host asks the hold, so the hold needs nothing from gestures/. A + // root-entry component can then use the hold with no gesture code. if ( target instanceof Node && - [...this.touchGates].some(gate => gate(target)) + (holdsTouch(target) || [...this.touchGates].some(gate => gate(target))) ) { return {recognizers, consumer, consumerElement}; } @@ -2870,8 +2875,8 @@ export class GestureHost { /** * Hold touches away from every participant while `gate(target)` answers - * true (a presentation running in a layer: its content takes no touch - * until it settles). Returns the release. + * true. Returns the release. The input hold's held layers need no gate, + * because the host asks `holdsTouch` for every touch. */ addTouchGate(gate: (target: Node) => boolean): () => void { this.touchGates.add(gate); diff --git a/packages/core/src/gestures/README.md b/packages/core/src/gestures/README.md index 18df55bba67c7..83a7159509f43 100644 --- a/packages/core/src/gestures/README.md +++ b/packages/core/src/gestures/README.md @@ -434,11 +434,15 @@ subscriber cancels it: the host cancels `touchend` and `contextmenu` there while a claiming participant is attached, never a `touchstart` or a `touchmove`, and the click guard (`../utils/clickGuard.ts`) keeps a cancelling `click` while it is armed, and from the menu press model's first -arm on. A blocking `touchmove` sits on a claiming +arm on. A layer's input hold (`../Layer/inputHold.ts`) cancels pointer and +mouse events, clicks, `touchmove` and `touchend` there while a layer is held, +never a `touchstart`. A blocking `touchmove` sits on a claiming element and on a claimed touch's target, on the document while an element a claiming recognizer lives in is moving (Touches on moving elements), or on -the window only while a page hold is held, so a page of pressables blocks -no scroll. +the window only while a page hold or a layer's input hold is held, so a page +of pressables blocks no scroll. The stream records the type of the latest +pointer event it delivers (`getLastPointerType`); the input hold reads it as +a layer opens. ### Holding the page still diff --git a/packages/core/src/gestures/__tests__/GestureHost.test.ts b/packages/core/src/gestures/__tests__/GestureHost.test.ts index da5738d2f2f99..decc4be8c2b99 100644 --- a/packages/core/src/gestures/__tests__/GestureHost.test.ts +++ b/packages/core/src/gestures/__tests__/GestureHost.test.ts @@ -29,6 +29,7 @@ import {TapGestureRecognizer} from '../TapGestureRecognizer'; import {createNativeScrollProbe} from '../nativeScroll'; import {gestureHosts} from '../hostRegistry'; import {holdPageScroll, type PageScrollDecision} from '../pageHold'; +import {holdInput} from '../../Layer/inputHold'; import {ManualClock, RecordingConsumer} from './harness'; import {TOUCH_QUERY} from '../../utils/touchQueries'; import {registerPresentedOffset} from '../../motion/presentation'; @@ -3740,6 +3741,26 @@ describe('touch gates and a second finger', () => { touch('touchend', button, [finger], [], 140); }); + it("holds a held layer's targets away from every participant with no gate: the host asks the input hold", () => { + const {layer, button} = mount( + '
', + ); + const tap = new TapGestureRecognizer({name: 'tap'}); + detachers.push(host.attach(button, tap)); + const release = holdInput(layer, { + until: new Promise(() => {}), + scope: 'viewport', + }); + const finger = {id: 1, x: 5, y: 5}; + touch('touchstart', button, [finger], [finger], 0); + expect(tap.numberOfTouches).toBe(0); + touch('touchend', button, [finger], [], 40); + release(); + touch('touchstart', button, [finger], [finger], 100); + expect(tap.numberOfTouches).toBe(1); + touch('touchend', button, [finger], [], 140); + }); + it('fails a one-finger pan that has not claimed when a second finger lands anywhere, so the browser can pinch', () => { const {row, text} = mount('

plain

'); const swipe = new PanGestureRecognizer({ diff --git a/packages/core/src/utils/flatTree.test.ts b/packages/core/src/utils/flatTree.test.ts index 7837af699dbb3..4c12f03770ee4 100644 --- a/packages/core/src/utils/flatTree.test.ts +++ b/packages/core/src/utils/flatTree.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. import {afterEach, describe, expect, it} from 'vitest'; -import {containsAlongFlatTree} from './flatTree'; +import {containsAlongFlatTree, deepActiveElement} from './flatTree'; afterEach(() => { document.body.innerHTML = ''; @@ -40,3 +40,29 @@ describe('containsAlongFlatTree', () => { expect(containsAlongFlatTree(a, document.createElement('i'))).toBe(false); }); }); + +describe('deepActiveElement', () => { + it("is the document's focused element in light DOM, and null without a document", () => { + document.body.innerHTML = ''; + const field = document.getElementById('field') as HTMLInputElement; + field.focus(); + expect(deepActiveElement(document)).toBe(field); + expect(deepActiveElement(null)).toBeNull(); + expect(deepActiveElement(undefined)).toBeNull(); + }); + + it('goes down through open shadow roots to the element that has focus', () => { + const outer = document.createElement('div'); + document.body.append(outer); + const outerRoot = outer.attachShadow({mode: 'open'}); + const inner = document.createElement('span'); + outerRoot.append(inner); + const innerRoot = inner.attachShadow({mode: 'open'}); + const button = document.createElement('button'); + innerRoot.append(button); + button.focus(); + // The document sees only the outermost host. + expect(document.activeElement).toBe(outer); + expect(deepActiveElement(document)).toBe(button); + }); +}); diff --git a/packages/core/src/utils/flatTree.ts b/packages/core/src/utils/flatTree.ts index f43ed609e9e77..de9dcc8f391fb 100644 --- a/packages/core/src/utils/flatTree.ts +++ b/packages/core/src/utils/flatTree.ts @@ -3,11 +3,12 @@ /** * @file flatTree.ts * @input A DOM node - * @output Exports parentAcrossShadow, and containsAlongFlatTree, which walks it + * @output Exports parentAcrossShadow, containsAlongFlatTree, which walks it, + * and deepActiveElement * @position The flat-tree parent the browser scrolls and dispatches - * through, shared by the gesture host's native-scroll probe and the + * through, shared by the gesture host's native-scroll probe, the * selection lock (which the press feedback controller uses without the - * gesture system) + * gesture system) and the Layer module's input hold */ /** The node's parent, crossing out of shadow roots. */ @@ -38,3 +39,14 @@ export function containsAlongFlatTree(ancestor: Node, node: Node): boolean { } return false; } + +/** The focused element of `doc`, inside open shadow roots too. */ +export function deepActiveElement( + doc: Document | null | undefined, +): Element | null { + let active = doc?.activeElement ?? null; + while (active?.shadowRoot?.activeElement != null) { + active = active.shadowRoot.activeElement; + } + return active; +} diff --git a/packages/core/src/utils/inputStream.test.ts b/packages/core/src/utils/inputStream.test.ts index 08201a703387f..7c21056e4d125 100644 --- a/packages/core/src/utils/inputStream.test.ts +++ b/packages/core/src/utils/inputStream.test.ts @@ -10,7 +10,9 @@ * window, stopImmediatePropagation on the document) starves no subscriber; events * fired at the document reach the stream; a page of pressables registers * no non-passive listener, and the gesture host none that holds a scroll; - * the press feedback controller imports nothing from gestures/ + * the press feedback controller imports nothing from gestures/; the + * latest delivered pointer event's type is readable, and none is recorded + * while no subscriber hears pointer events * @position Unit tests of packages/core/src/utils/inputStream.ts */ @@ -19,7 +21,7 @@ import path from 'node:path'; import {afterEach, describe, expect, it, vi} from 'vitest'; import {getGestureHost} from '../gestures/GestureHost'; -import {subscribeInput} from './inputStream'; +import {getLastPointerType, subscribeInput} from './inputStream'; import {installPressFeedback} from './pressFeedback'; type Registration = { @@ -80,6 +82,32 @@ describe('inputStream', () => { expect(removed.map(r => r.type)).toEqual(['pointerdown']); }); + it('runs a first subscriber before the others, even subscribed after them, and its true ends the dispatch', () => { + const calls: string[] = []; + let isHeld = false; + // Only a first subscriber's true ends the dispatch. + subscribe(window, 'pointerdown', () => { + calls.push('press feedback'); + return true; + }); + subscribe( + window, + 'pointerdown', + () => { + calls.push('hold'); + return isHeld; + }, + {first: true}, + ); + subscribe(window, 'pointerdown', () => calls.push('gesture host')); + pointerDown(document.body); + expect(calls).toEqual(['hold', 'press feedback', 'gesture host']); + calls.length = 0; + isHeld = true; + pointerDown(document.body); + expect(calls).toEqual(['hold']); + }); + it('delivers to every subscriber in subscription order, each isolated from another that throws', () => { const reported = vi.fn(); vi.stubGlobal('reportError', reported); @@ -204,6 +232,29 @@ describe('inputStream', () => { detach(); }); + it("records the latest delivered pointer event's type, before its subscribers run, and only while one hears pointer events", () => { + const view = document.defaultView as Window; + const heard: (string | null)[] = []; + const stop = subscribeInput(view, 'pointermove', () => { + heard.push(getLastPointerType(view)); + }); + document.body.dispatchEvent( + new PointerEvent('pointermove', {bubbles: true, pointerType: 'mouse'}), + ); + expect(getLastPointerType(view)).toBe('mouse'); + document.body.dispatchEvent( + new PointerEvent('pointermove', {bubbles: true, pointerType: 'touch'}), + ); + expect(heard).toEqual(['mouse', 'touch']); + stop(); + + // No subscriber, no native listener: the stream hears nothing. + document.body.dispatchEvent( + new PointerEvent('pointermove', {bubbles: true, pointerType: 'pen'}), + ); + expect(getLastPointerType(view)).toBe('touch'); + }); + it('keeps the press feedback controller free of the gesture system', () => { const utils = path.resolve(__dirname); const seen = new Set(); diff --git a/packages/core/src/utils/inputStream.ts b/packages/core/src/utils/inputStream.ts index 663c6bcca6207..1fdcc35f8fb56 100644 --- a/packages/core/src/utils/inputStream.ts +++ b/packages/core/src/utils/inputStream.ts @@ -4,7 +4,8 @@ * @file inputStream.ts * @input A window, and subscribers to its input events (the press feedback * controller, the gesture host) - * @output subscribeInput + * @output subscribeInput, and getLastPointerType: the type of the latest + * pointer event the stream delivered * @position The one entry for document-wide input listeners in core: one * native listener per event type on the window's capture phase, shared by * every subscriber @@ -22,18 +23,21 @@ // `blur` or `focus`. A subscriber for the window's own event checks // `event.target`. // -// Subscribers run in subscription order. One that throws is reported, and -// the rest still run. +// Subscribers run in subscription order, after the ones subscribed `first`. +// A first subscriber that returns `true` ends the dispatch: no later +// subscriber hears the event. One that throws is reported, and the rest still +// run. // // A type's native listener is passive, so it blocks no scroll. It is // non-passive only while a subscriber that cancels the event // (`{cancels: true}`) is subscribed. With no subscriber left, it is removed. -type InputListener = (event: Event) => void; +type InputListener = (event: Event) => unknown; interface Subscriber { readonly listener: InputListener; readonly cancels: boolean; + readonly isFirst: boolean; } interface Channel { @@ -50,12 +54,30 @@ export interface InputSubscriptionOptions { * @default false */ readonly cancels?: boolean; + /** + * The subscriber runs before every subscriber that is not first. When it + * returns `true`, no later subscriber hears the event. + * @default false + */ + readonly first?: boolean; } /** The events a window's capture phase sees: its own, and the document's. */ export type InputEventMap = WindowEventMap & DocumentEventMap; const streams = new WeakMap>(); +/** The type of the latest pointer event each window's stream delivered. */ +const lastPointerTypes = new WeakMap(); + +/** + * The type of the latest pointer event `view`'s stream delivered: `mouse`, + * `pen` or `touch`, or `null` before any. The stream hears a pointer event + * type only while a subscriber listens to it, as press feedback does on any + * page with a pressable. Reading it adds no listener. + */ +export function getLastPointerType(view: Window): string | null { + return lastPointerTypes.get(view) ?? null; +} /** * Listen to `type` on `view`'s capture phase through its shared native @@ -64,8 +86,8 @@ const streams = new WeakMap>(); export function subscribeInput( view: Window, type: K, - listener: (event: InputEventMap[K]) => void, - {cancels = false}: InputSubscriptionOptions = {}, + listener: (event: InputEventMap[K]) => unknown, + {cancels = false, first = false}: InputSubscriptionOptions = {}, ): () => void { let channels = streams.get(view); if (channels == null) { @@ -80,8 +102,16 @@ export function subscribeInput( const subscriber: Subscriber = { listener: listener as InputListener, cancels, + isFirst: first, }; - channel.subscribers.push(subscriber); + const firstLater = first + ? channel.subscribers.findIndex(other => !other.isFirst) + : -1; + if (firstLater === -1) { + channel.subscribers.push(subscriber); + } else { + channel.subscribers.splice(firstLater, 0, subscriber); + } register(view, type, channel); let isSubscribed = true; return () => { @@ -124,12 +154,17 @@ function register(view: Window, type: string, channel: Channel): void { if (wanted == null) { return; } - const listener: InputListener = event => dispatch(channel, event); + const listener: InputListener = event => dispatch(view, channel, event); view.addEventListener(type, listener, {capture: true, passive: !wanted}); channel.native = {listener, cancels: wanted}; } -function dispatch(channel: Channel, event: Event): void { +function dispatch(view: Window, channel: Channel, event: Event): void { + // Recorded before any subscriber runs, so each reads the pointer at hand. + const {pointerType} = event as Partial; + if (typeof pointerType === 'string' && pointerType !== '') { + lastPointerTypes.set(view, pointerType); + } // A subscriber may subscribe or unsubscribe while the event runs; the // event goes to those subscribed when it arrived. for (const subscriber of [...channel.subscribers]) { @@ -137,7 +172,9 @@ function dispatch(channel: Channel, event: Event): void { continue; } try { - subscriber.listener(event); + if (subscriber.listener(event) === true && subscriber.isFirst) { + return; + } } catch (error) { report(error); } diff --git a/packages/core/src/utils/selectionLock.ts b/packages/core/src/utils/selectionLock.ts index 57b783055ed65..60f68b3a07a88 100644 --- a/packages/core/src/utils/selectionLock.ts +++ b/packages/core/src/utils/selectionLock.ts @@ -28,7 +28,11 @@ // // A mouse never takes the lock, so its released behavior stays (AST-017). -import {containsAlongFlatTree, parentAcrossShadow} from './flatTree'; +import { + containsAlongFlatTree, + deepActiveElement, + parentAcrossShadow, +} from './flatTree'; import {subscribeInput} from './inputStream'; import {isIosWebKit} from './touchQueries'; @@ -582,15 +586,6 @@ function openShadowRootsOf(target: EventTarget | null): ShadowRoot[] { return roots; } -/** The focused element, inside open shadow roots too. */ -function deepActiveElement(doc: Document | null): Element | null { - let active = doc?.activeElement ?? null; - while (active?.shadowRoot?.activeElement != null) { - active = active.shadowRoot.activeElement; - } - return active; -} - /** * The selection-lock styles on `set`, refcounted per element; idempotent * release. diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs index af25cc63287ca..2b7504521c4f2 100644 --- a/scripts/touch-support-bundle.test.mjs +++ b/scripts/touch-support-bundle.test.mjs @@ -359,6 +359,22 @@ describe('the touch module in bundles', () => { } }); + it('is absent from a component that holds its layer (Layer/inputHold)', () => { + // A component in the root entry may hold its layer's input statically + // (a popover's presentation): the hold brings no gesture code with it. + const holder = entryWith( + 'Holder.ts', + `import {holdInput} from ${JSON.stringify( + path.join(CORE_SRC, 'Layer/inputHold.ts'), + )}; +export const Holder = holdInput; +`, + ); + for (const bytes of outputsOf([holder])) { + expect(bytesOf(bytes)).toEqual([]); + } + }); + it('is one copy that two components importing it share', () => { const component = name => entryWith( From 288070e3ac0364c515cc5a3823a835e66d94b460 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 4 Nov 2026 00:52:41 -0800 Subject: [PATCH 3/8] feat(Popover): under a finger, it grows out of its trigger and shrinks back into it Under a coarse primary pointer, Popover grows out of its trigger on the theme's entrance duration and easing and shrinks back into it on the theme's exit duration and easing, on the layer runtime's exit copy. A fine primary pointer keeps the layer's own entrance. --- .changeset/popover-uikit-presentation.md | 7 + docs/specs/components/Popover/Popover.spec.md | 2 +- packages/core/src/Layer/useLayer.test.tsx | 38 ++ packages/core/src/Layer/useLayer.tsx | 14 + packages/core/src/Popover/Popover.doc.mjs | 6 +- packages/core/src/Popover/Popover.test.tsx | 116 ++++ packages/core/src/Popover/Popover.tsx | 39 +- packages/core/src/Popover/PopoverTouch.ts | 20 + .../core/src/Popover/popoverSurfaceFrame.ts | 165 +++++ .../src/Popover/popoverSurfaceMotion.test.ts | 602 ++++++++++++++++++ .../core/src/Popover/popoverSurfaceMotion.ts | 268 ++++++++ packages/core/src/Popover/usePopover.tsx | 34 +- .../Popover/usePopoverSurfaceMotion.test.tsx | 110 ++++ .../src/Popover/usePopoverSurfaceMotion.ts | 112 ++++ .../useSegmentedSelectionMotion.ts | 52 +- packages/core/src/motion/MEASUREMENTS.md | 13 + packages/core/src/motion/README.md | 2 + packages/core/src/motion/themeTiming.test.ts | 136 ++++ packages/core/src/motion/themeTiming.ts | 87 +++ packages/core/src/motion/uikit/index.ts | 3 +- packages/core/src/motion/uikit/popover.ts | 51 ++ .../privateAttributes/popoverExit.stylex.ts | 30 + 22 files changed, 1857 insertions(+), 50 deletions(-) create mode 100644 .changeset/popover-uikit-presentation.md create mode 100644 packages/core/src/Popover/PopoverTouch.ts create mode 100644 packages/core/src/Popover/popoverSurfaceFrame.ts create mode 100644 packages/core/src/Popover/popoverSurfaceMotion.test.ts create mode 100644 packages/core/src/Popover/popoverSurfaceMotion.ts create mode 100644 packages/core/src/Popover/usePopoverSurfaceMotion.test.tsx create mode 100644 packages/core/src/Popover/usePopoverSurfaceMotion.ts create mode 100644 packages/core/src/motion/themeTiming.test.ts create mode 100644 packages/core/src/motion/themeTiming.ts create mode 100644 packages/core/src/motion/uikit/popover.ts create mode 100644 packages/core/src/privateAttributes/popoverExit.stylex.ts diff --git a/.changeset/popover-uikit-presentation.md b/.changeset/popover-uikit-presentation.md new file mode 100644 index 0000000000000..ce642a5cd9fd4 --- /dev/null +++ b/.changeset/popover-uikit-presentation.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feature] Under a finger (a coarse primary pointer, on any touch device), Popover grows out of its trigger, wide before tall, with its edge held on the trigger, and shrinks back into the trigger when it closes. The growth plays the theme's entrance duration and easing, and the shrink plays its exit duration and easing, on the compositor. A close during the growth, or an open during the shrink, turns back from where the popover is. With reduced motion it cross-fades in and out, opacity only, in 200 ms or less. A fine primary pointer (a mouse) keeps its entrance. The shrink plays on the layer runtime's exit copy, of which Popover is the first user. + +@vjeux diff --git a/docs/specs/components/Popover/Popover.spec.md b/docs/specs/components/Popover/Popover.spec.md index a4cc71dcbb627..ad76f76b06cc7 100644 --- a/docs/specs/components/Popover/Popover.spec.md +++ b/docs/specs/components/Popover/Popover.spec.md @@ -187,7 +187,7 @@ table owns their semantic effect. | FR6 | Component anatomy contains the caller trigger and content, one painted Popover surface, and the optional fallback close control. Popover owns no Header, Body, or separate shared-hook surface part. | Current source, docs target inventory, and tests | Accepted anatomy; stale consumer anatomy corrected by this contract | | FR7 | The painted surface has one broad canonical target, `popover`; composed components may add one authoritative component-specific refinement target. | Owner direction on 2026-08-31 plus current target inventory | Accepted canonical contract; covered by focused target tests | | FR8 | The surface padding is one spacing-scale rung applied on the painted surface. Popover defaults to step 3 (the released inset); `0` paints a flush surface; a direct `usePopover` composition paints none unless it asks for a rung. The rung sits where a theme's `padding` on the `popover` target replaces it. | PR #6683 and its Popover tests; `architecture:container-padding/INV8` (padding alone does not enroll) | Pending owner review (DEC-4); implemented and covered by the Popover surface-padding suite | -| FR9 | Under a finger, Popover grows out of its trigger on the theme's entrance duration and easing tokens and shrinks back into it on the theme's exit duration and easing, and a touch during its growth is ignored, as `spec:AST-094` FR31, FR35 and FR45 state. Its dismissal is unchanged, and a mouse keeps today's entrance. | `spec:AST-094` FR31, FR35 | Pending implementation; tests land with it | +| FR9 | Under a finger, Popover grows out of its trigger on the theme's `--duration-fast-max` and `--ease-entrance` and shrinks back into it on the theme's exit duration and easing, and a touch during its growth is ignored (`spec:AST-094` FR31, FR35 and FR45). Its dismissal is unchanged, and a mouse keeps today's entrance. | `spec:AST-094` FR31, FR35 | Grow and shrink implemented; a touch during the growth is not yet ignored | ### Allowed variation diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsx index b7d8f1b3bc629..dbef8a6bc7b37 100644 --- a/packages/core/src/Layer/useLayer.test.tsx +++ b/packages/core/src/Layer/useLayer.test.tsx @@ -1497,6 +1497,44 @@ describe('useLayer', () => { expect(onTooltipShow).toHaveBeenCalledTimes(1); }); + it('reports a close start as a hide starts, before its toggle: the browser\u2019s own hide and hide() alike', () => { + const {browserHide, runToggleTasks} = installBrowserHidePopoverApi(); + const events: string[] = []; + function CloseStartHarness() { + const layer = useLayerInternal({ + mode: 'context', + onCloseStart: () => events.push('close-start'), + onHide: () => events.push('hide'), + }); + return ( + <> + + + {layer.render(Content)} + + ); + } + const {getByRole, getByText} = render(); + fireEvent.click(getByRole('button', {name: 'Trigger'})); + act(() => runToggleTasks()); + expect(events).toEqual([]); + // The browser hides the popover itself, as a close watcher's Escape. + const popover = getByText('Content').closest('[popover]')!; + act(() => browserHide(popover)); + expect(events).toEqual(['close-start']); + act(() => runToggleTasks()); + expect(events).toEqual(['close-start', 'hide']); + // The hook's own hide() starts a close the same way, before its hide. + fireEvent.click(getByRole('button', {name: 'Trigger'})); + act(() => runToggleTasks()); + fireEvent.click(getByRole('button', {name: 'Close'})); + expect(events).toEqual(['close-start', 'hide', 'close-start', 'hide']); + }); + it('opens a layer at once when the press that closed another one opens it after the hide has returned', () => { // A light dismiss runs at pointerup and the click that follows opens the // next layer in the same gesture: the browser accepts that show (its diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx index dfaddc14eec21..42e4b0c753015 100644 --- a/packages/core/src/Layer/useLayer.tsx +++ b/packages/core/src/Layer/useLayer.tsx @@ -453,6 +453,12 @@ interface InternalContextLayerOptions extends ContextLayerOptions { * context menu on every table cell). */ keepsMountAfterShow?: boolean; + /** + * Runs as the layer starts to close, while the browser still shows it: in + * its `beforetoggle` to closed. A close that plays out after the layer is + * hidden starts here. + */ + onCloseStart?: () => void; } type InternalContextLayerReturn = ContextLayerReturn & InternalLayerFields; @@ -1045,6 +1051,9 @@ function useLayerImplementation( : false; const keepsAnchorClear = mode === 'context' ? (options.keepsAnchorClear ?? false) : false; + const onCloseStartRef = useRef<(() => void) | undefined>(undefined); + onCloseStartRef.current = + mode === 'context' ? options.onCloseStart : undefined; const id = useId(); const anchorId = `--astryx-layer-${id.replace(/:/g, '')}`; @@ -1326,6 +1335,10 @@ function useLayerImplementation( pendingShowRef.current = false; if (isOpenRef.current) { const el = popoverRef.current; + // A close that plays out after the layer is hidden starts here, while + // the browser still shows it. The `beforetoggle` handler below starts + // the browser's own hides. + onCloseStartRef.current?.(); // Clear the open state BEFORE hiding: hidePopover fires `toggle`, and // the reconciler below reads this ref to tell the browser's own // dismissals from ours. @@ -1470,6 +1483,7 @@ function useLayerImplementation( const el = e.currentTarget as HTMLElement | null; if (toggleEvent.newState === 'closed' && isOpenRef.current && el != null) { observeBrowserHide(el); + onCloseStartRef.current?.(); } }, []); diff --git a/packages/core/src/Popover/Popover.doc.mjs b/packages/core/src/Popover/Popover.doc.mjs index 21e5b5b575acf..38f2e23ceb002 100644 --- a/packages/core/src/Popover/Popover.doc.mjs +++ b/packages/core/src/Popover/Popover.doc.mjs @@ -221,7 +221,7 @@ export const docs = { }, usage: { description: - 'A click-triggered overlay anchored to a button or trigger element. Use it for secondary actions, inline confirmations, or supplementary information that does not warrant a full dialog. For hover previews use HoverCard, for brief helper text use Tooltip.', + 'A click-triggered overlay anchored to a button or trigger element. Use it for secondary actions, inline confirmations, or supplementary information that does not warrant a full dialog. For hover previews use HoverCard, for brief helper text use Tooltip. Under a finger (a coarse primary pointer), it is presented like a native popover: it grows out of its trigger and shrinks back into it on the theme\u2019s motion tokens; with reduced motion it cross-fades, opacity only, in 200 ms or less.', bestPractices: [ { guidance: true, @@ -439,7 +439,7 @@ export const docsZh = { }, usage: { description: - 'A click-triggered overlay anchored to a button or trigger element. Use it for secondary actions, inline confirmations, or supplementary information that does not warrant a full dialog. For hover previews use HoverCard, for brief helper text use Tooltip.', + 'A click-triggered overlay anchored to a button or trigger element. Use it for secondary actions, inline confirmations, or supplementary information that does not warrant a full dialog. For hover previews use HoverCard, for brief helper text use Tooltip. Under a finger (a coarse primary pointer), it is presented like a native popover: it grows out of its trigger and shrinks back into it on the theme\u2019s motion tokens; with reduced motion it cross-fades, opacity only, in 200 ms or less.', bestPractices: [ { guidance: true, @@ -512,7 +512,7 @@ export const docsDense = { 'Click-triggered popover displaying interactive content anchored to trigger element; implements button+dialog ARIA pattern.', usage: { description: - 'A click-triggered overlay anchored to a button or trigger element. Use it for secondary actions, inline confirmations, or supplementary information that does not warrant a full dialog. For hover previews use HoverCard, for brief helper text use Tooltip.', + 'A click-triggered overlay anchored to a button or trigger element. Use it for secondary actions, inline confirmations, or supplementary information that does not warrant a full dialog. For hover previews use HoverCard, for brief helper text use Tooltip. Under a finger (a coarse primary pointer), it is presented like a native popover: it grows out of its trigger and shrinks back into it on the theme\u2019s motion tokens; with reduced motion it cross-fades, opacity only, in 200 ms or less.', bestPractices: [ { guidance: true, diff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsx index ff51e0f451502..44356634051e7 100644 --- a/packages/core/src/Popover/Popover.test.tsx +++ b/packages/core/src/Popover/Popover.test.tsx @@ -1550,6 +1550,122 @@ describe('Popover', () => { }); }); +describe('Popover touch presentation', () => { + interface RecordedAnimation { + target: Element; + keyframes: Keyframe[]; + cancelled: boolean; + } + let recorded: RecordedAnimation[] = []; + let isCoarse = true; + const originalMatchMedia = window.matchMedia; + const originalShow = HTMLElement.prototype.showPopover; + const originalHide = HTMLElement.prototype.hidePopover; + + beforeAll(() => { + // The shared resolver reads the primary pointer (one touch model on every + // touch device); Reduce Motion is off. + window.matchMedia = (query: string) => ({ + matches: query.includes('pointer: coarse') ? isCoarse : false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + }); + // The browser announces a close with `beforetoggle` while the popover is + // still shown, then hides it. + HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) { + const before = new Event('beforetoggle'); + Object.defineProperty(before, 'newState', {value: 'closed'}); + this.dispatchEvent(before); + popoverOpenState.set(this, false); + const event = new Event('toggle'); + Object.defineProperty(event, 'newState', {value: 'closed'}); + this.dispatchEvent(event); + }); + HTMLElement.prototype.animate = function (keyframes) { + const animation = { + target: this, + keyframes: keyframes as Keyframe[], + cancelled: false, + // Started at once, as the browser commits it (the animator holds a + // curve's start until it has one). + startTime: performance.now() as number | null, + finished: new Promise(() => {}), + cancel() { + this.cancelled = true; + }, + }; + recorded.push(animation); + return animation as unknown as Animation; + }; + }); + + afterAll(() => { + window.matchMedia = originalMatchMedia; + HTMLElement.prototype.showPopover = originalShow; + HTMLElement.prototype.hidePopover = originalHide; + Reflect.deleteProperty(HTMLElement.prototype, 'animate'); + }); + + const open = () => { + recorded = []; + render( + Filters} label="Filters"> + + , + ); + fireEvent.click(screen.getByRole('button', {name: 'Filter'})); + const layer = screen + .getByRole('dialog', {name: 'Filters', hidden: true}) + .closest('[popover]'); + expect(layer).not.toBeNull(); + return layer!; + }; + + it('under a finger, grows the popover out of its trigger in place of the layer\u2019s entrance', () => { + isCoarse = true; + const layer = open(); + expect(layer.style.getPropertyValue('animation-name')).toBe('none'); + expect(layer.style.getPropertyValue('transform-origin')).not.toBe(''); + const scale = recorded.find( + animation => + animation.target === layer && 'scale' in animation.keyframes[0], + ); + expect(scale).toBeDefined(); + expect(String(scale!.keyframes[0].scale).split(' ')[0]).toBe('0.01'); + }); + + it('under a finger, shrinks back into its trigger on a copy that outlives the close', () => { + isCoarse = true; + const layer = open(); + fireEvent.click(screen.getByRole('button', {name: 'Filter'})); + const copy = layer.parentElement!.querySelector( + '[data-astryx-popover-exit]', + ); + expect(copy).not.toBeNull(); + expect(copy!.getAttribute('aria-hidden')).toBe('true'); + expect(copy!.hasAttribute('inert')).toBe(true); + }); + + it('under a mouse, keeps the layer\u2019s own entrance, plays nothing and closes at once', () => { + isCoarse = false; + expect(window.matchMedia('(pointer: coarse)').matches).toBe(false); + const layer = open(); + expect(layer.style.getPropertyValue('animation-name')).toBe(''); + expect(recorded.filter(animation => animation.target === layer)).toEqual( + [], + ); + fireEvent.click(screen.getByRole('button', {name: 'Filter'})); + expect( + layer.parentElement!.querySelector('[data-astryx-popover-exit]'), + ).toBeNull(); + }); +}); + describe('Popover focus region (DEC-9)', () => { function Page({isModal}: {isModal: boolean}) { return ( diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsx index 5f02abb63d829..ee7604d96bfc3 100644 --- a/packages/core/src/Popover/Popover.tsx +++ b/packages/core/src/Popover/Popover.tsx @@ -4,10 +4,17 @@ /** * @file Popover.tsx - * @input Uses React layout measurement and the usePopover hook + * @input Uses React layout measurement, the usePopover hook and the touch + * presentation's surface motion * @output Exports Popover with conditional overflow and content-first focus above the layer runtime's viewport fit * @position Layer component; declarative wrapper around usePopover hook * + * Under a finger, the popover grows out of its anchor and shrinks back into + * it, as a UIKit popover does. The shared touch resolver's coarse primary + * pointer decides it, with one touch model on every touch device. The motion + * plays the theme's duration and easing tokens (popoverSurfaceMotion.ts). A + * fine primary pointer keeps the layer's own entrance. + * * For hover-triggered overlays, use HoverCard instead. * * `presentation` chooses the surface, with the vocabulary DropdownMenu and @@ -20,6 +27,8 @@ * * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/Popover/Popover.test.tsx + * - /packages/core/src/Popover/PopoverTouch.ts (its touch layer) + * - /packages/core/src/Popover/usePopoverSurfaceMotion.ts * - /packages/core/src/Popover/index.ts * - /packages/core/src/Popover/PopoverPresentation.test.tsx * - /apps/storybook/stories/Popover.stories.tsx @@ -49,7 +58,8 @@ import {useThemeDefinition} from '../theme/useTheme'; import * as stylex from '@stylexjs/stylex'; import {devWarn} from '../utils/devWarning'; import type {BaseProps} from '../BaseProps'; -import {FALLBACK_CLOSE_SELECTOR, usePopover} from './usePopover'; +import {FALLBACK_CLOSE_SELECTOR, usePopoverInternal} from './usePopover'; +import {usePopoverSurfaceMotion} from './PopoverTouch'; import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector'; import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer'; import {layerAnimations} from '../Layer/layerAnimations.stylex'; @@ -530,12 +540,20 @@ export function Popover({ const measurementFrameRef = useRef<{id: number; view: Window} | null>(null); const [hasOverflow, setHasOverflow] = useState(false); const isControlled = isOpen !== undefined; + // The element the popover is anchored to, whichever way it was attached: + // the touch presentation grows the popover out of it. + const anchorElementRef = useRef(null); + const surfaceMotion = usePopoverSurfaceMotion(); + // Runs as the popover opens, before it paints; set once `usePopover` has + // returned the surface it presents. + const presentSurfaceRef = useRef<() => void>(() => {}); // The bottom-sheet presentation: the surface it resolves to now, and // whether the sheet is the surface that is open. const resolvedPresentation = usePresentationSurface(presentation); const [isSheetOpenState, setIsSheetOpenState] = useState(false); const handlePopoverShow = useCallback(() => { + presentSurfaceRef.current(); onOpenChange?.(true); }, [onOpenChange]); @@ -543,7 +561,7 @@ export function Popover({ onOpenChange?.(false); }, [onOpenChange]); - const popover = usePopover({ + const popover = usePopoverInternal({ dialogLabel: label, role, isModal, @@ -568,8 +586,18 @@ export function Popover({ style, onShow: handlePopoverShow, onHide: handlePopoverHide, + onCloseStart: surfaceMotion.closeStart, }); + const {contentRef: surfaceRef} = popover; + // The layer's show handler calls this as the popover opens. It reads the + // surface and the anchor when it runs, so a render-time store is safe. + presentSurfaceRef.current = () => { + surfaceMotion.present( + surfaceRef.current?.closest('[popover]') ?? null, + anchorElementRef.current, + ); + }; // A controlled popover opens on the surface its presentation resolves to // as it opens, and keeps that surface until it closes: a phone rotated past // the compact width while the sheet is open keeps its sheet. @@ -806,6 +834,7 @@ export function Popover({ const setRenderTrigger = useCallback( (element: HTMLElement | null) => { renderTriggerRef.current = element; + anchorElementRef.current = element; popover.triggerRef(element); }, [popover], @@ -929,12 +958,14 @@ export function Popover({ } // Set up anchor positioning on the anchorRef element itself + anchorElementRef.current = el; popover.triggerRef(el); // Attach handlers + ARIA to the button const detach = attachTrigger(button); return () => { + anchorElementRef.current = null; popover.triggerRef(null); detach(); }; @@ -957,6 +988,7 @@ export function Popover({ // Use the wrapper as the CSS anchor — it doesn't receive pressed-state // transforms, so the anchor position stays stable. + anchorElementRef.current = wrapper; popover.triggerRef(wrapper); // Find the button inside the wrapper @@ -975,6 +1007,7 @@ export function Popover({ const detach = attachTrigger(button); return () => { + anchorElementRef.current = null; popover.triggerRef(null); detach(); }; diff --git a/packages/core/src/Popover/PopoverTouch.ts b/packages/core/src/Popover/PopoverTouch.ts new file mode 100644 index 0000000000000..1ccc20120d677 --- /dev/null +++ b/packages/core/src/Popover/PopoverTouch.ts @@ -0,0 +1,20 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file PopoverTouch.ts + * @input usePopoverSurfaceMotion.ts (the touch presentation's grow and + * shrink) + * @output Popover's touch layer: usePopoverSurfaceMotion + * @position The one module Popover imports touch-only code through, and its + * only import site is Popover.tsx. The mouse paths stay outside it. + * + * A pointer page carries this touch-only code. Components import the shared + * touch modules statically, with no install call, so this module's cost is + * in every Popover import. + * + * SYNC: When modified, keep every touch-only import of Popover.tsx here. + */ + +export {usePopoverSurfaceMotion} from './usePopoverSurfaceMotion'; diff --git a/packages/core/src/Popover/popoverSurfaceFrame.ts b/packages/core/src/Popover/popoverSurfaceFrame.ts new file mode 100644 index 0000000000000..760e473e6ebc4 --- /dev/null +++ b/packages/core/src/Popover/popoverSurfaceFrame.ts @@ -0,0 +1,165 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file popoverSurfaceFrame.ts + * @input The popover's box and its source's, and UIKit's popover values + * @output Exports `popoverCollapsedState`, where the popover grows from and + * the shape it starts as. Exports `popoverFrame`, the surface at a progress + * of the growth. Also exports the theme tokens that time the motion, the + * frame helpers, and their types. + * @position Internal to Popover: the pure geometry of the touch + * presentation, with no DOM and no animator. A browser proof imports it on + * its own, and popoverSurfaceMotion.ts plays it. + * + * SYNC: When modified, update: + * - /packages/core/src/Popover/popoverSurfaceMotion.ts + * - /packages/core/src/Popover/popoverSurfaceMotion.test.ts + */ + +import type {LayerExitBox} from '../Layer/layerExitCopy'; +import type {ThemeTimingTokens} from '../motion/themeTiming'; +import {popover} from '../motion/uikit/popover'; + +/** + * The growth plays the layer entrance's duration and the theme's entrance + * easing. A tap opens the popover, and a tap has no velocity, so no spring + * plays. + */ +export const POPOVER_ENTRANCE_TOKENS: ThemeTimingTokens = { + durations: ['--duration-fast-max'], + easing: '--ease-entrance', +}; + +/** + * The shrink plays the theme's exit duration and easing. A theme that sets + * no exit duration gets the fast duration, which is the exit duration's + * default. + */ +export const POPOVER_EXIT_TOKENS: ThemeTimingTokens = { + durations: ['--duration-exit', '--duration-fast'], + easing: '--ease-exit', +}; + +/** A box in viewport px. */ +export type PopoverSurfaceRect = LayerExitBox; + +/** Where the popover sits and what it hangs off, in viewport px. */ +export interface PopoverSurfaceGeometry { + /** The layer element's border box once positioned, at full size. */ + surface: PopoverSurfaceRect; + /** The box of the source the popover is anchored to. */ + source: PopoverSurfaceRect; +} + +/** Where the popover grows from, and the shape it starts as. */ +export interface PopoverCollapsedState { + /** Transform origin, px from the surface's top-left corner. */ + originX: number; + originY: number; + /** + * The scale axis that also carries the length: the axis pointing away + * from the source (`y` for a popover above or below it). + */ + axis: 'x' | 'y'; + /** The uniform scale it grows from. */ + scale: number; + /** The share of its own length along `axis` it grows from, at most 1. */ + length: number; +} + +/** The transform and opacity of the surface. */ +export interface PopoverFrame { + scaleX: number; + scaleY: number; + opacity: number; +} + +/** How far the edges may sit apart and still count as touching, px. */ +const EDGE_TOLERANCE = 1; + +const clamp = (value: number, min: number, max: number) => + Math.min(Math.max(value, min), max); + +/** + * Where the popover meets its source, and the shape it grows from. The point + * is the middle of the source on the popover's edge facing it (the arrow's + * tip), kept on that edge. + */ +export function popoverCollapsedState({ + surface, + source, +}: PopoverSurfaceGeometry): PopoverCollapsedState { + const gaps = { + below: surface.top - (source.top + source.height), + above: source.top - (surface.top + surface.height), + right: surface.left - (source.left + source.width), + left: source.left - (surface.left + surface.width), + }; + // The side with the widest gap is the one the popover was placed on. A + // popover that overlaps its source grows from below, as the default. + let side: keyof typeof gaps = 'below'; + for (const candidate of ['above', 'right', 'left'] as const) { + if (gaps[candidate] > gaps[side]) { + side = candidate; + } + } + if (gaps[side] < -EDGE_TOLERANCE) { + side = 'below'; + } + const centerX = clamp( + source.left + source.width / 2 - surface.left, + 0, + surface.width, + ); + const centerY = clamp( + source.top + source.height / 2 - surface.top, + 0, + surface.height, + ); + const vertical = side === 'below' || side === 'above'; + const fullLength = vertical ? surface.height : surface.width; + return { + originX: vertical ? centerX : side === 'right' ? 0 : surface.width, + originY: vertical ? (side === 'below' ? 0 : surface.height) : centerY, + axis: vertical ? 'y' : 'x', + scale: popover.collapsedScale, + length: + fullLength > 0 ? Math.min(1, popover.collapsedLengthPx / fullLength) : 1, + }; +} + +export interface SurfaceState { + scale: number; + /** Share of the full length along the axis. */ + length: number; + opacity: number; +} + +export const PRESENTED: SurfaceState = {scale: 1, length: 1, opacity: 1}; + +export function frameOf(state: SurfaceState, axis: 'x' | 'y'): PopoverFrame { + const along = state.scale * state.length; + return { + scaleX: axis === 'x' ? along : state.scale, + scaleY: axis === 'y' ? along : state.scale, + opacity: state.opacity, + }; +} + +/** + * The surface at progress `p` of the growth: the frame UIKit's popover view + * shows on its path at that progress. + */ +export function popoverFrame( + state: PopoverCollapsedState, + p: number, +): PopoverFrame { + return frameOf( + { + scale: state.scale + (1 - state.scale) * p, + length: state.length + (1 - state.length) * p, + opacity: p, + }, + state.axis, + ); +} diff --git a/packages/core/src/Popover/popoverSurfaceMotion.test.ts b/packages/core/src/Popover/popoverSurfaceMotion.test.ts new file mode 100644 index 0000000000000..d21ada538809c --- /dev/null +++ b/packages/core/src/Popover/popoverSurfaceMotion.test.ts @@ -0,0 +1,602 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file popoverSurfaceMotion.test.ts + * @input vitest (jsdom), popoverSurfaceMotion, the theme's duration and + * easing defaults, a recording stand-in for Element.animate + * @output Checks where the popover grows from on each side of its source, + * and that every frame stays on UIKit's measured path. Checks that the + * growth plays the entrance tokens and the shrink the exit tokens. Covers + * present, dismiss, turn-back, reset and Reduce Motion. + * @position Testing; the curves on a real compositor are proven in + * __tests__/PopoverTouchMotion.interaction.browser.spec.ts + */ + +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {cubicBezier} from '../motion/bezier'; +import {parseCssEasing, parseMotionRoleValue} from '../motion/roles'; +import {popover, timing} from '../motion/uikit'; +import {findPopoverExitCopy} from '../privateAttributes/popoverExit.stylex'; +import {durationDefaults, easeDefaults} from '../theme/tokens.stylex'; +import { + createPopoverSurfaceMotion, + popoverCollapsedState, + popoverFrame, + type PopoverSurfaceGeometry, +} from './popoverSurfaceMotion'; + +/** A motion's duration (ms) and eased progress, as CSS gives them. */ +function cssTiming(duration: string, easing: string) { + const ms = parseMotionRoleValue('duration', duration); + const points = parseCssEasing(easing); + if (ms == null || points == null) { + throw new Error(`not a playable timing: ${duration} ${easing}`); + } + const ease = cubicBezier(points); + return {ms, at: (tMs: number) => (tMs >= ms ? 1 : ease(tMs / ms))}; +} + +// The theme's defaults, which a page with no theme scope plays. +const ENTRANCE = cssTiming( + durationDefaults['--duration-fast-max'], + easeDefaults['--ease-entrance'], +); +const EXIT = cssTiming( + durationDefaults['--duration-fast'], + easeDefaults['--ease-exit'], +); + +// UIKit on iOS 26.2 (batch 36): a 120 × 44 button at (141, 160). It presents +// a 320 × 253 popover below it at (41, 204), centred on it. +const GEOMETRY: PopoverSurfaceGeometry = { + surface: {left: 41, top: 204, width: 320, height: 253}, + source: {left: 141, top: 160, width: 120, height: 44}, +}; + +/** The visual box of the surface scaled by (sx, sy) about the origin. */ +function visualBox( + geometry: PopoverSurfaceGeometry, + origin: {x: number; y: number}, + sx: number, + sy: number, +) { + const {left, top, width, height} = geometry.surface; + return { + left: left + origin.x * (1 - sx), + top: top + origin.y * (1 - sy), + width: width * sx, + height: height * sy, + }; +} + +const scaleOf = (frame: Keyframe) => + String(frame.scale) + .split(' ') + .map(value => Number(value)); + +/** + * The person's settings, through `matchMedia` as the animator reads them: no + * option overrides them. + */ +function stubMedia(reduced: boolean, coarse: boolean) { + vi.stubGlobal('matchMedia', (query: string) => ({ + matches: query.includes('prefers-reduced-motion') + ? reduced + : query.includes('pointer: coarse') + ? coarse + : false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + })); +} + +describe('popoverCollapsedState', () => { + it('grows a popover below its source out of the source\u2019s bottom centre', () => { + const state = popoverCollapsedState(GEOMETRY); + expect(state.originX).toBe(160); + expect(state.originY).toBe(0); + expect(state.axis).toBe('y'); + expect(state.scale).toBe(popover.collapsedScale); + expect(state.length).toBeCloseTo(popover.collapsedLengthPx / 253, 12); + }); + + it('turns the same motion toward a source above or beside the popover', () => { + const above = popoverCollapsedState({ + surface: {left: 41, top: 100, width: 320, height: 200}, + source: {left: 141, top: 310, width: 120, height: 44}, + }); + expect([above.originX, above.originY, above.axis]).toEqual([160, 200, 'y']); + const right = popoverCollapsedState({ + surface: {left: 200, top: 100, width: 180, height: 240}, + source: {left: 20, top: 150, width: 160, height: 40}, + }); + expect([right.originX, right.originY, right.axis]).toEqual([0, 70, 'x']); + expect(right.length).toBeCloseTo(popover.collapsedLengthPx / 180, 12); + const left = popoverCollapsedState({ + surface: {left: 10, top: 100, width: 180, height: 240}, + source: {left: 200, top: 150, width: 160, height: 40}, + }); + expect([left.originX, left.originY, left.axis]).toEqual([180, 70, 'x']); + }); + + it('keeps the point on the popover when its source is wider than it, and never grows a short popover', () => { + const state = popoverCollapsedState({ + surface: {left: 300, top: 60, width: 90, height: 80}, + source: {left: 0, top: 10, width: 402, height: 44}, + }); + // The source's centre (201) lies left of the popover: its nearest point. + expect(state.originX).toBe(0); + expect(state.originY).toBe(0); + // Shorter than the 100 pt it would grow from: the length does not move. + expect(state.length).toBe(1); + }); +}); + +describe('popoverFrame', () => { + it('keeps every frame on UIKit\u2019s path: the top on the source, the centre on its line, the length growing from 100 pt', () => { + const state = popoverCollapsedState(GEOMETRY); + // Progress past 1 is an easing's overshoot; the path extends straight. + for (const p of [0, 0.1, 0.3126, 0.5, 0.9, 1, 1.0152]) { + const frame = popoverFrame(state, p); + const box = visualBox( + GEOMETRY, + {x: state.originX, y: state.originY}, + frame.scaleX, + frame.scaleY, + ); + const scale = popover.collapsedScale + (1 - popover.collapsedScale) * p; + expect(box.top).toBeCloseTo(204, 9); + expect(box.left + box.width / 2).toBeCloseTo(201, 9); + expect(box.width).toBeCloseTo(320 * scale, 9); + expect(box.height).toBeCloseTo(scale * (100 + 153 * p), 9); + expect(frame.opacity).toBeCloseTo(p, 12); + } + }); + + it('matches the popover view\u2019s measured frames', () => { + const state = popoverCollapsedState(GEOMETRY); + // Presentation frames of the popover view, iOS 26.2 (batch 36): scale, + // then the visual width and height. + for (const [scale, width, height] of [ + [0.0865, 27.69, 9.68], + [0.3195, 102.25, 47.24], + [0.6664, 213.26, 134.25], + [0.9632, 308.22, 238.2], + [1.015, 324.79, 259.14], + ]) { + const p = (scale - popover.collapsedScale) / (1 - popover.collapsedScale); + const frame = popoverFrame(state, p); + expect(320 * frame.scaleX).toBeCloseTo(width, 1); + expect(253 * frame.scaleY).toBeCloseTo(height, 1); + } + }); +}); + +interface Recorded { + target: Element; + keyframes: Keyframe[]; + options: KeyframeAnimationOptions; + cancelled: boolean; +} + +describe('createPopoverSurfaceMotion', () => { + let clock = 1000; + let recorded: Recorded[] = []; + + beforeEach(() => { + clock = 1000; + recorded = []; + vi.useFakeTimers(); + HTMLElement.prototype.animate = function (keyframes, options) { + const animation = { + target: this, + keyframes: keyframes as Keyframe[], + options: options as KeyframeAnimationOptions, + cancelled: false, + // The browser starts it at once: its first frame is committed at the + // call (the animator holds a curve's start until it has one). + startTime: clock as number | null, + finished: new Promise(() => {}), + cancel() { + this.cancelled = true; + }, + }; + recorded.push(animation); + return animation as unknown as Animation; + }; + }); + + // jsdom has no layout: the dismissal's copy stands where its inline box + // says. + const originalRect = HTMLElement.prototype.getBoundingClientRect; + beforeEach(() => { + HTMLElement.prototype.getBoundingClientRect = function (this: HTMLElement) { + if (findPopoverExitCopy(this.parentElement ?? document) !== this) { + return originalRect.call(this); + } + const left = parseFloat(this.style.left); + const top = parseFloat(this.style.top); + const width = parseFloat(this.style.width); + const height = parseFloat(this.style.height); + return { + left, + top, + width, + height, + x: left, + y: top, + right: left + width, + bottom: top + height, + toJSON: () => ({}), + }; + }; + }); + + afterEach(() => { + Reflect.deleteProperty(HTMLElement.prototype, 'animate'); + HTMLElement.prototype.getBoundingClientRect = originalRect; + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + const create = (reducedMotion = false) => { + const host = document.createElement('section'); + document.body.appendChild(host); + const element = document.createElement('div'); + element.id = 'popover-layer'; + element.setAttribute('popover', 'auto'); + element.innerHTML = + ''; + // jsdom has no layout: the surface stands where the open measured it. + element.getBoundingClientRect = () => ({ + ...GEOMETRY.surface, + x: GEOMETRY.surface.left, + y: GEOMETRY.surface.top, + right: GEOMETRY.surface.left + GEOMETRY.surface.width, + bottom: GEOMETRY.surface.top + GEOMETRY.surface.height, + toJSON: () => ({}), + }); + host.appendChild(element); + // The touch presentation runs under a coarse pointer, where Reduce + // Motion cross-fades. + stubMedia(reducedMotion, true); + const motion = createPopoverSurfaceMotion(element, {now: () => clock}); + return {element, motion}; + }; + + const live = (property: string, target?: Element) => + recorded.filter( + animation => + !animation.cancelled && + (target == null || animation.target === target) && + animation.keyframes.some(frame => property in frame), + ); + const copyOf = (element: HTMLElement) => + findPopoverExitCopy(element.parentElement!); + + /** + * Checks each keyframe of `animation` against the path from collapsed to + * presented at `progress(t ms)`, and returns the time the motion ends. + */ + const expectPath = ( + animation: Recorded, + state: ReturnType, + progress: (tMs: number) => number, + ) => { + const duration = Number(animation.options.duration); + let endMs = 0; + let peak = 0; + let previous: number[] | null = null; + for (const frame of animation.keyframes) { + const tMs = (frame.offset as number) * duration; + const expected = popoverFrame(state, progress(tMs)); + const scale = scaleOf(frame); + expect(scale[0]).toBeCloseTo(expected.scaleX, 2); + expect(scale[1]).toBeCloseTo(expected.scaleY, 2); + peak = Math.max(peak, scale[0]); + if (previous == null || previous.some((v, i) => v !== scale[i])) { + endMs = tMs; + } + previous = scale; + } + return {endMs, peak}; + }; + + it('grows the popover out of its source on the theme\u2019s entrance tokens, without the layer\u2019s CSS entrance', () => { + const {element, motion} = create(); + // The read happens with the CSS entrance already off and no scale left. + const measure = vi.fn(() => { + expect(element.style.getPropertyValue('animation-name')).toBe('none'); + return GEOMETRY; + }); + motion.enter(measure); + expect(measure).toHaveBeenCalledTimes(1); + const state = popoverCollapsedState(GEOMETRY); + expect(element.style.getPropertyValue('animation-name')).toBe('none'); + expect(element.style.getPropertyValue('transform-origin')).toBe( + `${state.originX}px ${state.originY}px`, + ); + const [scaleAnimation] = live('scale'); + const first = scaleOf(scaleAnimation.keyframes[0]); + expect(first[0]).toBeCloseTo(state.scale, 4); + expect(first[1]).toBeCloseTo(state.scale * state.length, 4); + expect(scaleOf(scaleAnimation.keyframes.at(-1)!)).toEqual([1, 1]); + // Every keyframe is the measured path at the entrance easing's progress, + // and the growth ends with the entrance duration: no spring, no bounce. + const {endMs, peak} = expectPath(scaleAnimation, state, ENTRANCE.at); + expect(endMs).toBeLessThanOrEqual(ENTRANCE.ms + 1); + expect(endMs).toBeGreaterThan(ENTRANCE.ms * 0.8); + expect(peak).toBeLessThanOrEqual(1); + const [opacityAnimation] = live('opacity'); + expect(Number(opacityAnimation.keyframes[0].opacity)).toBe(0); + expect(Number(opacityAnimation.keyframes.at(-1)!.opacity)).toBe(1); + }); + + it('plays the dismissal on a static copy of the popover, back into its source on the theme\u2019s exit tokens, removed when it ends', async () => { + const {element, motion} = create(); + motion.enter(() => GEOMETRY); + clock += 1000; + vi.advanceTimersByTime(1000); + motion.exit(); + const copy = copyOf(element); + expect(copy).not.toBeNull(); + // Beside the layer (same inherited theme), where it stands, out of reach. + expect(copy!.previousElementSibling).toBe(element); + expect(copy!.getAttribute('aria-hidden')).toBe('true'); + expect(copy!.hasAttribute('inert')).toBe(true); + // In the top layer, as the popover was (the layer runtime's exit copy). + expect(copy!.getAttribute('popover')).toBe('manual'); + expect(copy!.querySelectorAll('[id]')).toHaveLength(0); + expect(copy!.style.getPropertyValue('left')).toBe('41px'); + expect(copy!.style.getPropertyValue('top')).toBe('204px'); + const state = popoverCollapsedState(GEOMETRY); + expect(copy!.style.getPropertyValue('transform-origin')).toBe( + `${state.originX}px ${state.originY}px`, + ); + // The copy shrinks into the point on the exit easing, in the exit + // duration (the fast duration while the theme sets none), and fades. + const [scaleAnimation] = live('scale', copy!); + const last = scaleOf(scaleAnimation.keyframes.at(-1)!); + expect(last[0]).toBeCloseTo(state.scale, 4); + expect(last[1]).toBeCloseTo(state.scale * state.length, 4); + const {endMs} = expectPath(scaleAnimation, state, t => 1 - EXIT.at(t)); + expect(endMs).toBeLessThanOrEqual(EXIT.ms + 1); + expect(endMs).toBeGreaterThan(EXIT.ms * 0.8); + const [opacityAnimation] = live('opacity', copy!); + expect(Number(opacityAnimation.keyframes[0].opacity)).toBe(1); + expect(Number(opacityAnimation.keyframes.at(-1)!.opacity)).toBe(0); + // The layer itself is left at rest for its next presentation (an + // identity at rest leaves no inline value). + expect(element.style.getPropertyValue('scale')).toMatch(/^(1( 1)?)?$/); + expect(element.style.getPropertyValue('opacity')).toMatch(/^(1)?$/); + // Gone once the shrink ends. + clock += 2000; + vi.advanceTimersByTime(2000); + return Promise.resolve().then(() => { + expect(copyOf(element)).toBeNull(); + }); + }); + + it('reads the theme\u2019s tokens where the popover is: the entrance duration and easing time the growth, the exit duration and easing the shrink', () => { + const {element, motion} = create(); + element.style.setProperty('--duration-fast-max', '400ms'); + element.style.setProperty('--ease-entrance', 'linear'); + element.style.setProperty('--duration-exit', '0.3s'); + element.style.setProperty('--ease-exit', 'ease-in'); + const state = popoverCollapsedState(GEOMETRY); + motion.enter(() => GEOMETRY); + const growth = expectPath( + live('scale', element)[0], + state, + cssTiming('400ms', 'linear').at, + ); + expect(growth.endMs).toBeGreaterThan(320); + expect(growth.endMs).toBeLessThanOrEqual(401); + clock += 1000; + vi.advanceTimersByTime(1000); + motion.exit(); + const shrinkTiming = cssTiming('300ms', 'ease-in'); + const shrink = expectPath( + live('scale', copyOf(element)!)[0], + state, + t => 1 - shrinkTiming.at(t), + ); + expect(shrink.endMs).toBeGreaterThan(240); + expect(shrink.endMs).toBeLessThanOrEqual(301); + }); + + it('a theme that sets no exit duration shrinks the popover in its fast duration', () => { + const {element, motion} = create(); + element.style.setProperty('--duration-fast', '250ms'); + const state = popoverCollapsedState(GEOMETRY); + motion.enter(() => GEOMETRY); + clock += 1000; + vi.advanceTimersByTime(1000); + motion.exit(); + const fast = cssTiming('250ms', easeDefaults['--ease-exit']); + const shrink = expectPath( + live('scale', copyOf(element)!)[0], + state, + t => 1 - fast.at(t), + ); + expect(shrink.endMs).toBeGreaterThan(200); + expect(shrink.endMs).toBeLessThanOrEqual(251); + }); + + it('dismissed during the growth, shrinks from the frame on screen on the exit tokens', () => { + const {element, motion} = create(); + motion.enter(() => GEOMETRY); + clock += ENTRANCE.ms / 2; + vi.advanceTimersByTime(ENTRANCE.ms / 2); + motion.exit(); + const state = popoverCollapsedState(GEOMETRY); + const [scaleAnimation] = live('scale', copyOf(element)!); + const first = scaleOf(scaleAnimation.keyframes[0]); + const onScreen = popoverFrame(state, ENTRANCE.at(ENTRANCE.ms / 2)); + expect(first[0]).toBeCloseTo(onScreen.scaleX, 2); + expect(first[1]).toBeCloseTo(onScreen.scaleY, 2); + expect(first[0]).toBeLessThan(1); + const last = scaleOf(scaleAnimation.keyframes.at(-1)!); + expect(last[0]).toBeCloseTo(state.scale, 4); + }); + + it('lets the hidden layer go of its compositing layer as the dismissal starts, so no style write reaches it during the dismissal', async () => { + const {element, motion} = create(); + motion.enter(() => GEOMETRY); + // Dismissed about 100 ms after the presentation's curve ended, while the + // animator still keeps the element promoted (its PROMOTION_LINGER_MS). + clock += 600; + vi.advanceTimersByTime(600); + motion.exit(); + // The exit's own task. + await Promise.resolve(); + const writes: string[] = []; + const observer = new MutationObserver(records => { + for (const record of records) { + writes.push(record.oldValue ?? ''); + } + }); + observer.observe(element, { + attributes: true, + attributeFilter: ['style'], + attributeOldValue: true, + }); + // The dismissal's whole run, and any linger past it. + for (let ms = 0; ms < 1200; ms += 50) { + clock += 50; + vi.advanceTimersByTime(50); + await Promise.resolve(); + } + writes.push(...observer.takeRecords().map(record => record.oldValue ?? '')); + observer.disconnect(); + expect(writes).toEqual([]); + expect(element.style.getPropertyValue('will-change')).toBe(''); + }); + + it('presented again during the dismissal, grows back from the frame on screen about the same point', () => { + const {element, motion} = create(); + motion.enter(() => GEOMETRY); + clock += 1000; + vi.advanceTimersByTime(1000); + motion.exit(); + const origin = element.style.getPropertyValue('transform-origin'); + clock += 80; + const measure = vi.fn(() => GEOMETRY); + motion.enter(measure); + // No new measurement and no new pivot; the copy is gone. + expect(measure).not.toHaveBeenCalled(); + expect(element.style.getPropertyValue('transform-origin')).toBe(origin); + expect(copyOf(element)).toBeNull(); + const first = scaleOf(live('scale', element).at(-1)!.keyframes[0]); + const state = popoverCollapsedState(GEOMETRY); + // Mid-dismissal: smaller than the presented popover, larger than the + // point, with the length between its two values. + expect(first[0]).toBeLessThan(1); + expect(first[0]).toBeGreaterThan(state.scale); + const length = first[1] / first[0]; + expect(length).toBeLessThan(1); + expect(length).toBeGreaterThan(state.length); + }); + + it('a dismissal with no touch presentation before it does nothing', () => { + const {element, motion} = create(); + motion.exit(); + expect(recorded).toHaveLength(0); + expect(copyOf(element)).toBeNull(); + }); + + it('reset leaves the element as the component styles it', () => { + const {element, motion} = create(); + motion.enter(() => GEOMETRY); + motion.reset(); + for (const property of [ + 'scale', + 'opacity', + 'transform-origin', + 'animation-name', + ]) { + expect(element.style.getPropertyValue(property), property).toBe(''); + } + motion.exit(); + expect(copyOf(element)).toBeNull(); + }); + + it('Reduce Motion: the popover cross-fades in at its size and out where it stands, in 200 ms or less, with no spring', () => { + const {element, motion} = create(true); + motion.enter(() => GEOMETRY); + // No growth: every scale keyframe is the full size. + for (const animation of live('scale', element)) { + for (const frame of animation.keyframes) { + expect(String(frame.scale)).toMatch(/^1( 1)?$/); + } + } + const ease = cubicBezier(timing.curves.move); + // The animator holds a curve's end value to the end of a longer + // animation. The fade ends at the first keyframe after which the opacity + // stays at its target. + const fadeMs = ( + animation: { + options: KeyframeAnimationOptions; + keyframes: Keyframe[]; + }, + target: number, + ) => { + const total = Number(animation.options.duration); + let end = animation.keyframes.length - 1; + while ( + end > 0 && + Number(animation.keyframes[end - 1].opacity) === target + ) { + end -= 1; + } + return (animation.keyframes[end].offset as number) * total; + }; + const [fadeIn] = live('opacity', element); + // design:reduced-motion DR2: opacity only, 200 ms or less. + const fadeInMs = fadeMs(fadeIn, 1); + expect(fadeInMs).toBeGreaterThan(0); + expect(fadeInMs).toBeLessThanOrEqual(timing.reducedMotionCrossFadeMs + 1); + // UIKit's cross-fade curve, not a spring. + const fadeInTotal = Number(fadeIn.options.duration); + for (const frame of fadeIn.keyframes) { + const t = (frame.offset as number) * fadeInTotal; + expect(Number(frame.opacity)).toBeCloseTo( + ease(Math.min(1, t / timing.reducedMotionCrossFadeMs)), + 2, + ); + } + clock += 1000; + vi.advanceTimersByTime(1000); + motion.exit(); + const copy = copyOf(element)!; + const [fadeOut] = live('opacity', copy); + const fadeOutMs = fadeMs(fadeOut, 0); + expect(fadeOutMs).toBeGreaterThan(0); + expect(fadeOutMs).toBeLessThanOrEqual(timing.reducedMotionCrossFadeMs + 1); + expect(Number(fadeOut.keyframes[0].opacity)).toBe(1); + expect(Number(fadeOut.keyframes.at(-1)!.opacity)).toBe(0); + const fadeOutTotal = Number(fadeOut.options.duration); + for (const frame of fadeOut.keyframes) { + const t = (frame.offset as number) * fadeOutTotal; + expect(Number(frame.opacity)).toBeCloseTo( + 1 - ease(Math.min(1, t / timing.reducedMotionCrossFadeMs)), + 2, + ); + } + // The copy keeps its size while it fades (where it lands once it is out + // is the animator's business). + for (const animation of live('scale', copy)) { + const total = Number(animation.options.duration); + for (const frame of animation.keyframes) { + if ((frame.offset as number) * total < fadeOutMs - 1) { + expect(String(frame.scale)).toMatch(/^1( 1)?$/); + } + } + } + }); +}); diff --git a/packages/core/src/Popover/popoverSurfaceMotion.ts b/packages/core/src/Popover/popoverSurfaceMotion.ts new file mode 100644 index 0000000000000..933acbc08a038 --- /dev/null +++ b/packages/core/src/Popover/popoverSurfaceMotion.ts @@ -0,0 +1,268 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file popoverSurfaceMotion.ts + * @input A Popover's layer element, the source it hangs off, the compositor + * animator, the theme's duration and easing tokens, and the layer + * runtime's exit copy + * @output Exports `popoverCollapsedState`, `popoverFrame` and + * `createPopoverSurfaceMotion`, the touch presentation's present and + * dismiss. + * @position Internal to Popover. Under a finger the popover grows out of its + * source and shrinks back into it, as a UIKit popover does. + * + * SYNC: When modified, update: + * - /packages/core/src/Popover/popoverSurfaceFrame.ts + * - /packages/core/src/Popover/popoverSurfaceMotion.test.ts + * - /packages/core/src/Popover/Popover.tsx + */ + +import { + createMotionAnimator, + type Animator, + type AnimatorOptions, + type MotionCurve, + type MotionHandle, +} from '../motion/animator'; +import {mapProgress, mapRange} from '../motion/progress'; +import {readThemeTiming} from '../motion/themeTiming'; +import {placePopoverExitCopy} from '../privateAttributes/popoverExit.stylex'; +import { + frameOf, + popoverCollapsedState, + POPOVER_ENTRANCE_TOKENS, + POPOVER_EXIT_TOKENS, + PRESENTED, + type PopoverCollapsedState, + type PopoverSurfaceGeometry, + type SurfaceState, +} from './popoverSurfaceFrame'; + +export {popoverCollapsedState, popoverFrame} from './popoverSurfaceFrame'; +export type { + PopoverCollapsedState, + PopoverFrame, + PopoverSurfaceGeometry, + PopoverSurfaceRect, +} from './popoverSurfaceFrame'; + +/** + * The curves from `from` to `to` as `progress` moves from 0 to 1. The scale + * and the length move together, so the scale along the axis is their product. + */ +function surfaceCurves( + from: SurfaceState, + to: SurfaceState, + axis: 'x' | 'y', + progress: MotionCurve, +): Record<'scaleX' | 'scaleY' | 'opacity', MotionCurve> { + // Unclamped, so an easing that overshoots carries the channels with it. + const lerp = (a: number, b: number) => + mapRange([0, 1], [a, b], {clamp: false}); + const scale = lerp(from.scale, to.scale); + const length = lerp(from.length, to.length); + const across = mapProgress(progress, scale); + const along = mapProgress(progress, p => scale(p) * length(p)); + return { + scaleX: axis === 'x' ? along : across, + scaleY: axis === 'y' ? along : across, + opacity: mapProgress(progress, lerp(from.opacity, to.opacity)), + }; +} + +/** What `animator` shows now, split back into scale and length. */ +function readState(animator: Animator, axis: 'x' | 'y'): SurfaceState { + const across = animator.get(axis === 'x' ? 'scaleY' : 'scaleX'); + const along = animator.get(axis === 'x' ? 'scaleX' : 'scaleY'); + return { + scale: across, + length: across > 0 ? along / across : 1, + opacity: animator.get('opacity'), + }; +} + +export interface PopoverSurfaceMotion { + /** + * The popover has just been shown in its touch presentation: grow it out + * of its source. `measure` reads the geometry; it runs with the element at + * its full size. During a dismissal, the popover grows back from where the + * dismissal has it, about the same point. + */ + enter(measure: () => PopoverSurfaceGeometry): void; + /** + * The popover is closing (its `beforetoggle` to closed, while it is still + * shown): shrink it back into its source. Does nothing unless the last + * presentation was a touch one. + */ + exit(): void; + /** + * The popover opened in a presentation that does not use this motion: + * leave the element exactly as the component styles it. + */ + reset(): void; + /** Cancels everything and restores the element. */ + dispose(): void; +} + +const MOTION_STYLE_PROPERTIES = [ + 'scale', + 'opacity', + 'transform-origin', + 'animation-name', +] as const; + +/** + * The popover is scaled about the point where it meets its source. Across + * the source's edge its scale is s = s₀ + (1 − s₀)·p. Along the axis away + * from the source it is s·f, with f = f₀ + (1 − f₀)·p, the share of its + * full length. Both follow one eased progress p, so they play as curves on + * the compositor. A dismissal during the growth, or a growth during the + * dismissal, turns back from the frame on screen. + * + * The browser hides a popover as it closes, so the dismissal plays on the + * layer runtime's exit copy, which is removed when its motion ends. + * + * Under Reduce Motion the animator's policy applies. On a coarse pointer the + * popover lands at its full size and cross-fades in, and it cross-fades out + * where it stands. + */ +export function createPopoverSurfaceMotion( + element: HTMLElement, + options: Pick = {}, +): PopoverSurfaceMotion { + const animator = createMotionAnimator(element, options); + // The presentation in progress or last played; null while the popover is + // in a presentation this motion does not drive. + let collapsed: PopoverCollapsedState | null = null; + // The geometry the presentation measured. While the growth runs, the + // element's box includes a scale that only the curve knows. + let measured: PopoverSurfaceGeometry | null = null; + let presentHandle: MotionHandle | null = null; + // The dismissal in progress: its copy and the copy's animator. + let exiting: {copy: HTMLElement; animator: Animator} | null = null; + + const endExit = () => { + if (exiting == null) { + return; + } + exiting.animator.dispose(); + exiting.copy.remove(); + exiting = null; + }; + + const reset = () => { + collapsed = null; + measured = null; + presentHandle = null; + endExit(); + animator.set({scaleX: 1, scaleY: 1, opacity: 1}); + for (const property of MOTION_STYLE_PROPERTIES) { + element.style.removeProperty(property); + } + }; + + const enter = (measure: () => PopoverSurfaceGeometry) => { + // A dismissal let the element go (exit, below). + animator.attach(element); + let from: SurfaceState | null = null; + if (exiting != null && collapsed != null) { + // Shown again during the dismissal: turn back from the frame on + // screen, about the same point. + from = readState(exiting.animator, collapsed.axis); + } + endExit(); + if (from == null) { + // Full size and invisible for the read. The box must not include a + // scale from the last dismissal, nor the first keyframe of the layer's + // CSS entrance. The curves below replace these before anything paints. + element.style.setProperty('animation-name', 'none'); + animator.set({scaleX: 1, scaleY: 1, opacity: 0}); + } + const geometry = from != null && measured != null ? measured : measure(); + const next = + from != null && collapsed != null + ? collapsed + : popoverCollapsedState(geometry); + collapsed = next; + measured = geometry; + // The layer's own CSS entrance belongs to the pointer presentation. + element.style.setProperty('animation-name', 'none'); + element.style.setProperty( + 'transform-origin', + `${next.originX}px ${next.originY}px`, + ); + const start = from ?? {scale: next.scale, length: next.length, opacity: 0}; + animator.set(frameOf(start, next.axis)); + const handle = animator.play( + surfaceCurves( + start, + PRESENTED, + next.axis, + readThemeTiming(element, POPOVER_ENTRANCE_TOKENS), + ), + ); + presentHandle = handle; + void handle.finished.then(() => { + if (presentHandle === handle) { + presentHandle = null; + } + }); + }; + + const exit = () => { + const target = collapsed; + if (target == null || exiting != null) { + return; + } + const from = readState(animator, target.axis); + const timing = readThemeTiming(element, POPOVER_EXIT_TOKENS); + presentHandle = null; + // The copy stands where the surface is drawn, the growth's frame + // included. + const copy = placePopoverExitCopy(element); + if (copy == null) { + // No top layer for a copy: the close is immediate. + animator.set({scaleX: 1, scaleY: 1, opacity: 1}); + return; + } + copy.style.setProperty( + 'transform-origin', + `${target.originX}px ${target.originY}px`, + ); + const closing = createMotionAnimator(copy, options); + closing.set(frameOf(from, target.axis)); + const handle = closing.play( + surfaceCurves( + from, + {scale: target.scale, length: target.length, opacity: 0}, + target.axis, + timing, + ), + ); + exiting = {copy, animator: closing}; + // The browser hides the element now. Leave it at rest, and let go of the + // layer its growth promoted in this task. Kept, the promotion would end + // inside the dismissal, a style write on an element that no longer + // paints (a Layout in the dismissal's frames). The next presentation + // attaches the element again. + animator.set({scaleX: 1, scaleY: 1, opacity: 1}, {promote: false}); + animator.attach(null); + void handle.finished.then(finished => { + if (finished && exiting?.copy === copy) { + endExit(); + } + }); + }; + + return { + enter, + exit, + reset, + dispose() { + reset(); + animator.dispose(); + }, + }; +} diff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsx index 677ec0792112f..094c5bbf57a65 100644 --- a/packages/core/src/Popover/usePopover.tsx +++ b/packages/core/src/Popover/usePopover.tsx @@ -5,8 +5,9 @@ /** * @file usePopover.tsx * @input Uses useLayer, useFocusTrap, React hooks - * @output Exports the public usePopover hook with derived focus and guarded opening, - * and FALLBACK_CLOSE_SELECTOR for Popover.tsx (internal). + * @output Exports the public usePopover hook with derived focus and guarded opening. + * For Popover.tsx (internal), exports usePopoverInternal and + * FALLBACK_CLOSE_SELECTOR. * @position Higher-level layer utility; used by DatePicker, Combobox, etc. * * Combines popover layer behavior with focus trap for dialog-like popovers. @@ -18,7 +19,7 @@ import React, {useCallback, useEffect, useRef, type ReactNode} from 'react'; import * as stylex from '@stylexjs/stylex'; -import {useLayer, type ContextRenderProps} from '../Layer/useLayer'; +import {useLayerInternal, type ContextRenderProps} from '../Layer/useLayer'; import {useFocusTrapInternal} from '../hooks/useFocusTrap'; import {LayerDepthProvider} from '../Layer/LayerDepthContext'; import type {StyleXStyles} from '@stylexjs/stylex'; @@ -392,12 +393,25 @@ export interface UsePopoverReturn { * } * ``` */ +/** + * Options a core component may pass through `usePopoverInternal`; not part + * of the public `usePopover` options. + */ +interface InternalPopoverOptions extends UsePopoverOptions { + /** + * Runs as the popover starts to close, while the browser still shows it. + * A close that plays out after the popover is hidden starts here. + */ + onCloseStart?: () => void; +} + function usePopoverImplementation( - options: UsePopoverOptions = {}, + options: InternalPopoverOptions = {}, ): UsePopoverReturn { const { onShow, onHide, + onCloseStart, xstyle, className, style, @@ -435,11 +449,12 @@ function usePopoverImplementation( }, [onShow]); // Core layer for popover positioning - const layer = useLayer({ + const layer = useLayerInternal({ mode: 'context', lightDismiss: hasLightDismiss, onShow: handleLayerShow, onHide, + onCloseStart, }); // Focus trap for the popover content. Escape stays registered while light @@ -669,3 +684,12 @@ function usePopoverImplementation( export function usePopover(options: UsePopoverOptions = {}): UsePopoverReturn { return usePopoverImplementation(options); } + +/** + * @internal For Popover; not exported from the package barrel. + */ +export function usePopoverInternal( + options: InternalPopoverOptions = {}, +): UsePopoverReturn { + return usePopoverImplementation(options); +} diff --git a/packages/core/src/Popover/usePopoverSurfaceMotion.test.tsx b/packages/core/src/Popover/usePopoverSurfaceMotion.test.tsx new file mode 100644 index 0000000000000..b5ed286b69c82 --- /dev/null +++ b/packages/core/src/Popover/usePopoverSurfaceMotion.test.tsx @@ -0,0 +1,110 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file usePopoverSurfaceMotion.test.tsx + * @input vitest (jsdom), React Testing Library, a stand-in popover layer and + * trigger, a stubbed pointer query and a recording stand-in for the motion + * @output Checks when the hook creates, drives and releases the touch + * presentation. A fine pointer creates and promotes nothing, and its close + * start plays nothing. + * @position Testing; Popover's touch presentation, the hook that drives it + */ + +import {renderHook} from '@testing-library/react'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {TOUCH_QUERY} from '../utils/touchPresentation'; +import {createPopoverSurfaceMotion} from './popoverSurfaceMotion'; +import {usePopoverSurfaceMotion} from './usePopoverSurfaceMotion'; + +vi.mock('./popoverSurfaceMotion', () => ({ + createPopoverSurfaceMotion: vi.fn(() => ({ + enter: vi.fn(), + exit: vi.fn(), + reset: vi.fn(), + dispose: vi.fn(), + })), +})); + +const created = () => + vi + .mocked(createPopoverSurfaceMotion) + .mock.results.map( + result => result.value as ReturnType, + ); + +let isTouch = false; + +beforeEach(() => { + isTouch = false; + vi.mocked(createPopoverSurfaceMotion).mockClear(); + vi.stubGlobal( + 'matchMedia', + vi.fn((query: string) => ({ + matches: query === TOUCH_QUERY ? isTouch : false, + media: query, + addEventListener: () => {}, + removeEventListener: () => {}, + })), + ); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + document.body.innerHTML = ''; +}); + +function layerAndTrigger() { + const layer = document.createElement('div'); + layer.setAttribute('popover', 'auto'); + layer.innerHTML = '
'; + const trigger = document.createElement('button'); + document.body.append(layer, trigger); + return {layer, trigger}; +} + +describe('usePopoverSurfaceMotion', () => { + it('leaves a fine-pointer open untouched: nothing created, nothing promoted, and its close start plays nothing', () => { + const {layer, trigger} = layerAndTrigger(); + const {result} = renderHook(() => usePopoverSurfaceMotion()); + result.current.present(layer, trigger); + result.current.closeStart(); + expect(createPopoverSurfaceMotion).not.toHaveBeenCalled(); + expect(layer.getAttribute('style')).toBeNull(); + }); + + it('under a coarse pointer, grows the popover as it opens and shrinks it as its close starts', () => { + isTouch = true; + const {layer, trigger} = layerAndTrigger(); + const {result} = renderHook(() => usePopoverSurfaceMotion()); + result.current.present(layer, trigger); + const [motion] = created(); + expect(motion.enter).toHaveBeenCalledTimes(1); + expect(motion.exit).not.toHaveBeenCalled(); + result.current.closeStart(); + expect(motion.exit).toHaveBeenCalledTimes(1); + }); + + it('a fine-pointer open after a touch one releases the touch motion, and its close start plays nothing', () => { + isTouch = true; + const {layer, trigger} = layerAndTrigger(); + const {result} = renderHook(() => usePopoverSurfaceMotion()); + result.current.present(layer, trigger); + const [motion] = created(); + // The pointer turns fine (a keyboard attached) for the next open. + isTouch = false; + result.current.present(layer, trigger); + expect(motion.dispose).toHaveBeenCalledTimes(1); + result.current.closeStart(); + expect(motion.exit).not.toHaveBeenCalled(); + }); + + it('releases the motion at unmount', () => { + isTouch = true; + const {layer, trigger} = layerAndTrigger(); + const {result, unmount} = renderHook(() => usePopoverSurfaceMotion()); + result.current.present(layer, trigger); + const [motion] = created(); + unmount(); + expect(motion.dispose).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/core/src/Popover/usePopoverSurfaceMotion.ts b/packages/core/src/Popover/usePopoverSurfaceMotion.ts new file mode 100644 index 0000000000000..623ac9b3ea6e5 --- /dev/null +++ b/packages/core/src/Popover/usePopoverSurfaceMotion.ts @@ -0,0 +1,112 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file usePopoverSurfaceMotion.ts + * @input React, the shared touch resolver and popoverSurfaceMotion + * @output Exports `usePopoverSurfaceMotion`, the calls Popover makes as it + * opens and as it starts to close. Under a finger they present and dismiss + * the popover the UIKit way; a mouse keeps the layer's own entrance. + * @position Internal to Popover; glue between the component and + * popoverSurfaceMotion.ts + * + * The shared touch resolver decides as the popover opens. Under a finger (a + * coarse primary pointer, on any touch device) the popover grows out of its + * source. When the layer runtime reports that it starts to close, it shrinks + * back into it. A fine primary pointer keeps the layer's own entrance. The + * motion is created for the popover element the first time it opens and + * follows it if the element is replaced. + * + * SYNC: When modified, update: + * - /packages/core/src/Popover/Popover.tsx + * - /packages/core/src/Popover/usePopoverSurfaceMotion.test.tsx + */ + +import {useCallback, useEffect, useMemo, useRef} from 'react'; +import {isCoarsePointer} from '../utils/coarsePointer'; +import { + createPopoverSurfaceMotion, + type PopoverSurfaceMotion, + type PopoverSurfaceRect, +} from './popoverSurfaceMotion'; + +function boxOf(element: Element): PopoverSurfaceRect { + const rect = element.getBoundingClientRect(); + return { + left: rect.left, + top: rect.top, + width: rect.width, + height: rect.height, + }; +} + +export interface PopoverSurfaceMotionCalls { + /** + * Call as the popover opens, right after the browser shows it and before + * it paints. + */ + present: (layer: HTMLElement | null, source: HTMLElement | null) => void; + /** Call as the popover starts to close, while the browser still shows it. */ + closeStart: () => void; +} + +export function usePopoverSurfaceMotion(): PopoverSurfaceMotionCalls { + const motionRef = useRef<{ + element: HTMLElement; + motion: PopoverSurfaceMotion; + } | null>(null); + const isTouchPresentationRef = useRef(false); + + const release = useCallback(() => { + motionRef.current?.motion.dispose(); + motionRef.current = null; + }, []); + + const motionFor = useCallback((element: HTMLElement) => { + const current = motionRef.current; + if (current?.element === element) { + return current.motion; + } + current?.motion.dispose(); + const motion = createPopoverSurfaceMotion(element); + motionRef.current = {element, motion}; + return motion; + }, []); + + // Releases the motion's compositor animations, and any exit copy still on + // screen, at unmount. + useEffect(() => release, [release]); + + const present = useCallback( + (layer: HTMLElement | null, source: HTMLElement | null) => { + if (layer == null) { + return; + } + const isTouch = + source != null && isCoarsePointer(layer.ownerDocument.defaultView); + isTouchPresentationRef.current = isTouch; + if (!isTouch || source == null) { + // A fine pointer animates nothing here, so nothing is created for + // it, and nothing is promoted to the compositor. A motion this layer + // already has (the pointer changed, or a touch presentation is on + // screen) is released. + release(); + return; + } + motionFor(layer).enter(() => ({ + surface: boxOf(layer), + source: boxOf(source), + })); + }, + [motionFor, release], + ); + + const closeStart = useCallback(() => { + if (isTouchPresentationRef.current) { + motionRef.current?.motion.exit(); + } + }, []); + + return useMemo(() => ({present, closeStart}), [present, closeStart]); +} diff --git a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts index 69e10fba731b1..96b05777c046d 100644 --- a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts +++ b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts @@ -42,7 +42,9 @@ import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import {observeResize} from '../utils/sharedResizeObserver'; import {titleOfSegment} from '../privateAttributes/segmentTitle.stylex'; import {cubicBezier} from '../motion/bezier'; +import {mapProgress, mapRange} from '../motion/progress'; import {parseCssEasing, parseMotionRoleValue} from '../motion/roles'; +import {easedProgress} from '../motion/themeTiming'; import {useSegmentedTouchTracking} from './useSegmentedTouchTracking'; /** The segments, in DOM order. */ @@ -351,18 +353,12 @@ function isEnabledSegment(segment: HTMLElement): boolean { const titleOf = titleOfSegment; -/** The theme's timing: a duration in seconds and its easing. */ -interface ThemeTiming { - readonly seconds: number; - readonly ease: (progress: number) => number; -} - /** - * The timing of `segment`'s own transition, which reads the theme's duration - * and easing tokens. The values stay readable while a carry turns the - * transition's property off. Null when the theme gives no duration. + * The eased progress of `segment`'s own transition, which reads the theme's + * duration and easing tokens. The values stay readable while a carry turns + * the transition's property off. Null when the theme gives no duration. */ -function themeTimingOf(segment: HTMLElement): ThemeTiming | null { +function themeTimingOf(segment: HTMLElement): MotionCurve | null { const view = segment.ownerDocument.defaultView; if (view == null) { return null; @@ -378,32 +374,11 @@ function themeTimingOf(segment: HTMLElement): ThemeTiming | null { if (ms == null || ms <= 0 || points == null) { return null; } - return {seconds: ms / 1000, ease: cubicBezier(points)}; + return easedProgress(ms / 1000, cubicBezier(points)); } /** A theme that gives the segments no transition: the lens lands at once. */ -const INSTANT: ThemeTiming = {seconds: 0.001, ease: progress => progress}; - -/** A curve from `from` to `to` on `timing`. */ -function timedCurve( - from: number, - to: number, - timing: ThemeTiming, -): MotionCurve { - const {seconds, ease} = timing; - const at = (t: number) => - from + (to - from) * ease(Math.min(1, Math.max(0, t / seconds))); - const step = Math.min(seconds / 100, 0.001); - return { - duration: seconds, - at, - velocity: t => { - const before = Math.max(0, t - step); - const after = Math.min(seconds, t + step); - return (at(after) - at(before)) / (after - before); - }, - }; -} +const INSTANT = easedProgress(0.001, progress => progress); /** What the control reads of its selection motion. */ export interface SegmentedSelection { @@ -1277,14 +1252,17 @@ export class SegmentedSelectionMotion { return; } this.velocity = {}; - const timing = themeTimingOf(segment) ?? INSTANT; + const progress = themeTimingOf(segment) ?? INSTANT; const at = options.at; + // Unclamped, so an easing that overshoots carries the lens with it. + const toward = (from: number, to: number) => + mapProgress(progress, mapRange([0, 1], [from, to], {clamp: false})); this.trackHandle( this.animator.play( { - x: timedCurve(this.animator.get('x', at), 0, timing), - scaleX: timedCurve(this.animator.get('scaleX', at), 1, timing), - scaleY: timedCurve(this.animator.get('scaleY', at), 1, timing), + x: toward(this.animator.get('x', at), 0), + scaleX: toward(this.animator.get('scaleX', at), 1), + scaleY: toward(this.animator.get('scaleY', at), 1), }, options, ), diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.md index aaa6aafd51f35..28823e5f072d7 100644 --- a/packages/core/src/motion/MEASUREMENTS.md +++ b/packages/core/src/motion/MEASUREMENTS.md @@ -314,3 +314,16 @@ scroll view coasts with 0.25 × the pan's velocity plus 0.75 × its value one event earlier (four HID releases; `velocity.scrollReleaseWeight`, which a pan's `scrollVelocity()` reads). On UIKit, Reduce Motion with Prefer Cross-Fade changes nothing on a picker; the Wheel follows design:reduced-motion instead. + +## Popovers (UIPopoverPresentationController) + +Values the popover reads from its own table (`uikit/popover.ts`). Its growth +and shrink play the theme's duration and easing tokens, not UIKit's springs. + +Done (iOS 26.2 simulator, Oct 23 2026; in the popover's table): the scale and +length a popover below its source grows from, and Reduce Motion, with the +`.none` adaptation on iPhone. + +| ID | Scene | Gesture | Extract | Method | +| ----- | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------ | +| M-PO1 | a popover above its source, one to its left and one to its right; a source near a screen edge so the arrow sits off the popover's centre | present, then a tap outside | which edge stays in place, which length grows from 100 pt, and the point the scale grows out of when the arrow is off centre | A, C | diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md index fa0341f398e59..8d17846e23206 100644 --- a/packages/core/src/motion/README.md +++ b/packages/core/src/motion/README.md @@ -22,6 +22,7 @@ roles through `resolveMotion`. | `uikit/alert.ts` | UIAlertController: how a finger is tracked across the actions (highlight onset and bounds). | | `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. | | `uikit/progressBar.ts` | UIProgressView's fill: the whole-track duration and curve, its minimum length and empty alpha; the reduced-motion pulse (three roles). | +| `uikit/popover.ts` | UIPopoverPresentationController: the scale and the length a popover grows out of and shrinks back into. | | `uikit/gestures.ts` | Gesture recognizer thresholds, the velocity filter and haptic stand-ins, as `{value, unit}` entries (sources in JSDoc). | | `uikit/picker.ts` | UIPickerView: row pitch, height and rubber band, velocity floor, the coast's stop speed, snap at rest, tap spin, tick. | | `uikit/segmented.ts` | UISegmentedControl: the selection indicator's spring; under Reduce Motion the animator's cross-fade replaces it. | @@ -39,6 +40,7 @@ roles through `resolveMotion`. | `paging.ts` | Paging: UIKit's paging settle as a playable curve, its velocity floor, the animated page scroll. | | `resolveSnapPoint.ts` | Release policy: the snap point a release lands on (flick, back-out cancel, step limit), on `selectSnapPoint`. Internal. | | `bezier.ts` | Cubic-bézier timing functions (Core Animation's named curves). | +| `themeTiming.ts` | The eased progress, as one timed MotionCurve, from the theme's tokens for a motion that a tap, a key or the program starts. Durations fall back down a chain. | | `animator.ts` | Compositor animator: springs, coasts and any closed-form curve compiled to Web Animations, read back analytically. | | `progress.ts` | A spring's progress, one curve mapped from another (companions, clamped ranges), the velocity that continues a motion. | | `presentation.ts` | Where each moving element is drawn relative to where the engine hit-tests it, reported by the animator while translate runs; read by the gesture host at touch-down. | diff --git a/packages/core/src/motion/themeTiming.test.ts b/packages/core/src/motion/themeTiming.test.ts new file mode 100644 index 0000000000000..980638f5d80aa --- /dev/null +++ b/packages/core/src/motion/themeTiming.test.ts @@ -0,0 +1,136 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file themeTiming.test.ts + * @input vitest (jsdom), readThemeTiming and easedProgress, the theme's + * duration and easing defaults + * @output Checks how a motion reads its theme tokens. Covers a set value, an + * explicit zero, an empty or unparseable value, the fallback chain, the + * progress velocity and easedProgress's curve. + * @position Testing; validates themeTiming.ts + */ + +import {afterEach, describe, expect, it} from 'vitest'; +import {cubicBezier} from './bezier'; +import {parseCssEasing} from './roles'; +import { + easedProgress, + readThemeTiming, + type ThemeTimingTokens, +} from './themeTiming'; +import {easeDefaults} from '../theme/tokens.stylex'; + +const EXIT: ThemeTimingTokens = { + durations: ['--duration-exit', '--duration-fast'], + easing: '--ease-exit', +}; + +const exitEase = cubicBezier(parseCssEasing(easeDefaults['--ease-exit'])!); + +function element(tokens: Record = {}): HTMLElement { + const node = document.createElement('div'); + for (const [name, value] of Object.entries(tokens)) { + node.style.setProperty(name, value); + } + document.body.appendChild(node); + return node; +} + +describe('readThemeTiming', () => { + afterEach(() => { + document.body.replaceChildren(); + }); + + it('plays the last token\u2019s default duration and the easing default when no token is set', () => { + const timing = readThemeTiming(element(), EXIT); + expect(timing.duration).toBeCloseTo(0.175, 6); + expect(timing.at(0.0875)).toBeCloseTo(exitEase(0.5), 6); + expect(timing.at(0.175)).toBe(1); + }); + + it('plays the first set token of the chain, in ms or s, with its easing', () => { + const exit = readThemeTiming( + element({ + '--duration-exit': '0.3s', + '--duration-fast': '100ms', + '--ease-exit': 'linear', + }), + EXIT, + ); + expect(exit.duration).toBeCloseTo(0.3, 6); + expect(exit.at(0.15)).toBeCloseTo(0.5, 6); + const fast = readThemeTiming(element({'--duration-fast': '250ms'}), EXIT); + expect(fast.duration).toBeCloseTo(0.25, 6); + }); + + it('gives the progress velocity per second, and none once the motion ends', () => { + const timing = readThemeTiming( + element({'--duration-exit': '0.3s', '--ease-exit': 'linear'}), + EXIT, + ); + expect(timing.velocity(0)).toBeCloseTo(1 / 0.3, 4); + expect(timing.velocity(0.15)).toBeCloseTo(1 / 0.3, 4); + expect(timing.velocity(0.3)).toBe(0); + const eased = readThemeTiming(element(), EXIT); + const t = 0.05; + const h = 1e-6; + expect(eased.velocity(t)).toBeCloseTo( + (eased.at(t + h) - eased.at(t - h)) / (2 * h), + 3, + ); + }); + + it('an explicit zero duration means no motion', () => { + const timing = readThemeTiming( + element({'--duration-exit': '0ms', '--duration-fast': '250ms'}), + EXIT, + ); + expect(timing.duration).toBe(0); + expect(timing.at(0)).toBe(1); + expect(timing.velocity(0)).toBe(0); + }); + + it('an empty duration falls back down the chain', () => { + const timing = readThemeTiming( + element({'--duration-exit': ' ', '--duration-fast': '250ms'}), + EXIT, + ); + expect(timing.duration).toBeCloseTo(0.25, 6); + }); + + it('an unparseable duration falls back down the chain, and never means no motion', () => { + const next = readThemeTiming( + element({'--duration-exit': 'fast', '--duration-fast': '250ms'}), + EXIT, + ); + expect(next.duration).toBeCloseTo(0.25, 6); + const last = readThemeTiming( + element({'--duration-exit': '-1ms', '--duration-fast': 'calc(1s)'}), + EXIT, + ); + expect(last.duration).toBeCloseTo(0.175, 6); + }); + + it('an unparseable easing gets its default', () => { + const timing = readThemeTiming( + element({'--duration-exit': '200ms', '--ease-exit': 'steps(4)'}), + EXIT, + ); + expect(timing.at(0.1)).toBeCloseTo(exitEase(0.5), 6); + }); +}); + +describe('easedProgress', () => { + it('eases from 0 to 1 over its length, and a zero length means no motion', () => { + const curve = easedProgress(0.2, x => x * x); + expect(curve.duration).toBe(0.2); + expect(curve.at(0)).toBe(0); + expect(curve.at(0.1)).toBeCloseTo(0.25, 6); + expect(curve.at(0.2)).toBe(1); + expect(curve.velocity(0.1)).toBeCloseTo(5, 3); + expect(curve.velocity(0.2)).toBe(0); + const none = easedProgress(0, x => x); + expect(none.at(0)).toBe(1); + expect(none.velocity(0)).toBe(0); + }); +}); diff --git a/packages/core/src/motion/themeTiming.ts b/packages/core/src/motion/themeTiming.ts new file mode 100644 index 0000000000000..971b2bb2d8bcd --- /dev/null +++ b/packages/core/src/motion/themeTiming.ts @@ -0,0 +1,87 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file themeTiming.ts + * @input An element and the theme tokens that time one motion + * @output readThemeTiming: the theme's eased progress from 0 to 1 for those + * tokens where the element is, as one timed MotionCurve. easedProgress: + * that curve for a length and an easing already read. + * @position Motion foundation, internal to core. Motion that a tap, a key or + * the program starts reads its duration and easing from the theme with it. + * + * SYNC: When modified, update /packages/core/src/motion/themeTiming.test.ts + */ + +import type {MotionCurve} from './animator'; +import {cubicBezier} from './bezier'; +import {parseCssEasing, parseMotionRoleValue} from './roles'; +import { + durationDefaults, + easeDefaults, + type DurationVarName, + type EaseVarName, +} from '../theme/tokens.stylex'; + +/** + * The theme tokens that time one motion. The duration tokens are a fallback + * chain, and the last one always has a default. + */ +export interface ThemeTimingTokens { + readonly durations: readonly [...string[], DurationVarName]; + readonly easing: EaseVarName; +} + +/** + * The eased progress from 0 to 1 over `seconds`, as a MotionCurve whose + * velocity is in progress per second. A zero length means no motion. + */ +export function easedProgress( + seconds: number, + ease: (x: number) => number, +): MotionCurve { + const at = (t: number) => + seconds <= 0 || t >= seconds ? 1 : ease(Math.max(0, t) / seconds); + // A central difference, one step inside the curve at either end. + const step = Math.min(1e-3, seconds / 100); + return { + duration: seconds, + at, + velocity: t => { + if (seconds <= 0 || t >= seconds) { + return 0; + } + const before = Math.max(0, t - step); + const after = Math.min(seconds, t + step); + return (at(after) - at(before)) / (after - before); + }, + }; +} + +/** + * The eased progress on the tokens, from 0 to 1, as a MotionCurve whose + * velocity is in progress per second. It reads the tokens where the element + * is, so a theme scope and the theme's tempo apply. An explicit zero duration + * means no motion. An unset, empty or unparseable duration falls back to the + * next token in the chain. The last token falls back to its default, so a bad + * value never means no motion. An unset or unparseable easing gets its + * default. + */ +export function readThemeTiming( + element: Element, + {durations, easing}: ThemeTimingTokens, +): MotionCurve { + const style = element.ownerDocument.defaultView?.getComputedStyle(element); + const read = (name: string) => style?.getPropertyValue(name) ?? ''; + let durationMs: number | null = null; + for (const name of durations) { + durationMs = parseMotionRoleValue('duration', read(name)); + if (durationMs != null) { + break; + } + } + const last = durations[durations.length - 1] as DurationVarName; + durationMs ??= parseMotionRoleValue('duration', durationDefaults[last]) ?? 0; + const points = parseCssEasing(read(easing)) ?? + parseCssEasing(easeDefaults[easing]) ?? [0, 0, 1, 1]; + return easedProgress(durationMs / 1000, cubicBezier(points)); +} diff --git a/packages/core/src/motion/uikit/index.ts b/packages/core/src/motion/uikit/index.ts index f9bbff0054a1f..55fee3e2d2279 100644 --- a/packages/core/src/motion/uikit/index.ts +++ b/packages/core/src/motion/uikit/index.ts @@ -4,7 +4,7 @@ * @file index.ts * @input The domain files of the UIKit constants table * @output Re-exports `springs` and one constant per spring (`SHEET_PRESENT_SPRING`, - * …), `scroll`, `timing`, `navigation`, `picker`, `progressBar`, + * …), `scroll`, `timing`, `navigation`, `picker`, `popover`, `progressBar`, * `segmentedControl`, `datePicker`, `slider` and `switchControl`. It also * re-exports the gesture thresholds: one `UIKIT_*` group per recognizer, * their union `UIKIT_GESTURES`, and the haptic tables @@ -42,6 +42,7 @@ export { export {datePicker} from './datePicker'; export {navigation, registerNavigationTable} from './navigation'; export {picker} from './picker'; +export {popover} from './popover'; export {progressBar, registerProgressBarTable} from './progressBar'; export {registerScrollTable, scroll} from './scroll'; export {segmentedControl} from './segmented'; diff --git a/packages/core/src/motion/uikit/popover.ts b/packages/core/src/motion/uikit/popover.ts new file mode 100644 index 0000000000000..89d5520209f6f --- /dev/null +++ b/packages/core/src/motion/uikit/popover.ts @@ -0,0 +1,51 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file popover.ts + * @input Nothing; data only + * @output Exports `popover`: the shape a popover grows out of and shrinks + * back into as it is presented and dismissed + * @position The popover domain of the UIKit constants table (motion/uikit). + * These are internal constants, not motion roles. + * + * UIPopoverPresentationController with its adaptation turned off (`.none`, + * so it stays a popover on iPhone), read from UIKit on the iOS 26.2 + * simulator. The popover view grows out of the point where it meets its + * source (the bottom centre of the source for a popover below it). Its scale, + * its length away from the source and its opacity move together, with the + * edge that meets the source held in place. Lengths are in pt (CSS px). + * + * Every leaf carries one or more `@source`; GUESS values also carry the + * `@measure` task that will confirm or replace them. uikit.test.ts enforces + * both. + * + * SYNC: When modified, update /packages/core/src/motion/MEASUREMENTS.md + */ + +export const popover = { + /** + * The uniform scale the popover grows from and shrinks back to, about the + * point where it meets its source. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, CASpringAnimation dump on the popover view, Oct 23 + * 2026: an additive `transform` animation from scale 0.01 to identity on + * the present spring, and from identity back to 0.01 on the dismiss + * spring; per-frame presentation frames keep the popover's top edge on + * the source's bottom edge and its centre on the source's centre line + * (scale 0.02, 0.32, 0.67, 0.88, 0.98, 1.01, 1 at 50 ms steps) + */ + collapsedScale: 0.01, + /** + * The popover's length away from its source when it starts to grow and + * when it has shrunk back. For a popover below its source, it is the + * height. The box grows from this length to its own together with the + * scale, whatever its size. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, CASpringAnimation dump on the popover view, Oct 23 + * 2026: an additive `bounds.size` animation from height −153 for a + * 253 pt popover and from −433 for a 533 pt one, both starting at 100 pt, + * with `position` moving by half of it so the top edge stays put; the + * dismiss animates back to the same 100 pt + */ + collapsedLengthPx: 100, +} as const; diff --git a/packages/core/src/privateAttributes/popoverExit.stylex.ts b/packages/core/src/privateAttributes/popoverExit.stylex.ts new file mode 100644 index 0000000000000..2c58c7519e17f --- /dev/null +++ b/packages/core/src/privateAttributes/popoverExit.stylex.ts @@ -0,0 +1,30 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file privateAttributes/popoverExit.stylex.ts + * @input A closing popover's layer element + * @output placePopoverExitCopy, which places the layer runtime's exit copy of + * a closing popover, marked as a popover's, and findPopoverExitCopy, which + * finds that copy + * @position Owner module of the private popover-exit attribute: the only + * file that writes its name. Popover's touch close plays on the copy it + * places. No package entry exports it. + */ + +import {placeLayerExitCopy} from '../Layer/layerExitCopy'; + +const POPOVER_EXIT = 'data-astryx-popover-exit'; + +/** + * Places the layer runtime's exit copy of a closing popover, marked as a + * popover's. Returns null where there is no top layer to show it in: the + * close is then immediate. + */ +export function placePopoverExitCopy(element: HTMLElement): HTMLElement | null { + return placeLayerExitCopy(element, POPOVER_EXIT); +} + +/** The exit copy of a closing popover under `root`, if one is on screen. */ +export function findPopoverExitCopy(root: ParentNode): HTMLElement | null { + return root.querySelector(`[${POPOVER_EXIT}]`); +} From 904c29f46d8d90935fbb6194d1cfee23ad04d8bb Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 4 Nov 2026 00:52:41 -0800 Subject: [PATCH 4/8] test(Popover): browser proofs of the touch presentation's grow and shrink Real-browser proofs, in Chromium and WebKit, that under a finger Popover grows out of its trigger on the theme's entrance tokens and shrinks back on its exit tokens, keeps advancing through a blocked main thread, does no Layout or Paint per frame, and cross-fades under Reduce Motion, with storyboards of both. --- ...verTouchMotion.interaction.browser.spec.ts | 659 ++++++++++++++++++ 1 file changed, 659 insertions(+) create mode 100644 packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts diff --git a/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts b/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts new file mode 100644 index 0000000000000..4f5951b00aab8 --- /dev/null +++ b/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts @@ -0,0 +1,659 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file PopoverTouchMotion.interaction.browser.spec.ts + * @input The built Default Popover story, real touch input (Chromium CDP / + * WebKit's input command), the interaction harness, the popover's + * geometry and the theme tokens that time its motion + * @output Animation proofs for Popover's touch presentation (under a finger, + * one touch model on every touch device): it grows out of its trigger on + * the theme's entrance tokens (the edge on the trigger, the scale and the + * length together) and shrinks back into it on the theme's exit tokens, on + * screen through the light dismiss; the growth keeps advancing through a + * blocked main thread; neither does Layout or Paint per frame; Reduce + * Motion cross-fades, opacity only, in 200 ms or less; a mouse keeps the + * layer's own entrance; storyboards of both + * @position Evidence for Popover's touch presentation; the model itself is + * unit-tested in popoverSurfaceMotion.test.ts + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + animationStoryboard, + blockMainThread, + busyWindowProof, + castStoryboard, + compareCurve, + countBetween, + freezeTimers, + holdAnimations, + installLongTaskLog, + installTimerGate, + markElement, + openStory, + readLongTasks, + releaseAnimations, + startScreencast, + thawTimers, + timeline, + touchDriver, + traceRendering, + trackMarker, + waitForAnimation, + waitForRest, + withStorybook, + writeEvidence, + type TouchDriver, +} from '@astryxdesign/interaction-harness'; +import {timing} from '../../motion/uikit/timing'; +import {cubicBezier} from '../../motion/bezier'; +import {parseCssEasing, parseMotionRoleValue} from '../../motion/roles'; +import type {ThemeTimingTokens} from '../../motion/themeTiming'; +import { + POPOVER_ENTRANCE_TOKENS, + POPOVER_EXIT_TOKENS, + popoverCollapsedState, + popoverFrame, +} from '../popoverSurfaceFrame'; + +const storybook = withStorybook(test); + +/** + * The duration (ms) and the eased progress that the story's theme gives + * `tokens`, read where the popover is. + */ +async function themeTiming(locator: Locator, tokens: ThemeTimingTokens) { + const values = await locator.evaluate( + (element, names) => { + const style = getComputedStyle(element); + return names.map(name => style.getPropertyValue(name).trim()); + }, + [...tokens.durations, tokens.easing], + ); + const easing = values.pop() ?? ''; + const ms = values + .map(value => parseMotionRoleValue('duration', value)) + .find(value => value != null); + const points = parseCssEasing(easing); + if (ms == null || points == null) { + throw new Error( + `the story theme gives no playable timing: ${values.join(', ')}`, + ); + } + const ease = cubicBezier(points); + return {ms, at: (t: number) => (t >= ms ? 1 : ease(Math.max(0, t) / ms))}; +} + +interface Box { + x: number; + y: number; + width: number; + height: number; +} + +interface OpenStory { + driver: TouchDriver; + trigger: Locator; + layer: Locator; + center: {x: number; y: number}; + triggerBox: Box; +} + +async function openDefault(page: Page): Promise { + await installLongTaskLog(page); + await openStory(page, storybook(), 'core-popover--default'); + const driver = await touchDriver(page); + const trigger = page.getByRole('button', {name: 'Settings'}); + const triggerBox = await trigger.boundingBox(); + if (triggerBox == null) { + throw new Error('no trigger'); + } + return { + driver, + trigger, + layer: page.locator('[popover]:has([role="dialog"])').first(), + center: { + x: triggerBox.x + triggerBox.width / 2, + y: triggerBox.y + triggerBox.height / 2, + }, + triggerBox, + }; +} + +/** + * The element's presented box at each time of its held animations: its + * layout box scaled by the presented `scale` about its `transform-origin`. + * Read from the computed style, which follows a seek; a composited animation + * of an individual transform property does not reach getBoundingClientRect + * in Chromium. + */ +async function sampleBoxes( + locator: Locator, + layout: Box, + times: ReadonlyArray, +): Promise<{t: number; box: Box; opacity: number}[]> { + const raw = await locator.evaluate((element, ts) => { + const held = + (window as unknown as {__harnessHeld?: Animation[]}).__harnessHeld ?? []; + if (held.length === 0) { + throw new Error('sampleBoxes: no held animations'); + } + return ts.map(t => { + for (const animation of held) { + const end = Number( + animation.effect?.getComputedTiming().endTime ?? Infinity, + ); + animation.currentTime = Math.min(t, end - 0.5); + } + const style = getComputedStyle(element); + return { + t, + scale: style.scale, + origin: style.transformOrigin, + opacity: Number(style.opacity), + }; + }); + }, times); + return raw.map(({t, scale, origin, opacity}) => { + const [sx, sy = sx] = + scale === 'none' ? [1, 1] : scale.split(' ').map(Number); + const [ox, oy] = origin.split(' ').map(value => parseFloat(value)); + return { + t, + opacity, + box: { + x: layout.x + ox * (1 - sx), + y: layout.y + oy * (1 - sy), + width: layout.width * sx, + height: layout.height * sy, + }, + }; + }); +} + +/** UIKit's popover path at progress p of the growth, as a visual box. */ +function expectedBox(final: Box, trigger: Box, p: number): Box { + const geometry = { + surface: { + left: final.x, + top: final.y, + width: final.width, + height: final.height, + }, + source: { + left: trigger.x, + top: trigger.y, + width: trigger.width, + height: trigger.height, + }, + }; + const state = popoverCollapsedState(geometry); + const frame = popoverFrame(state, p); + return { + x: final.x + state.originX * (1 - frame.scaleX), + y: final.y + state.originY * (1 - frame.scaleY), + width: final.width * frame.scaleX, + height: final.height * frame.scaleY, + }; +} + +/** The layer's own scale animation among those running in it. */ +async function scaleAnimationOf(locator: Locator) { + for (;;) { + const found = await waitForAnimation(locator); + const scale = found.find(a => a.keyframes.some(k => 'scale' in k)); + if (scale != null) { + return scale; + } + } +} + +/** The static copy the dismissal plays on. */ +const exitCopyOf = (page: Page) => + page.locator('[data-astryx-popover-exit]').first(); + +async function openWithTap(story: OpenStory) { + await story.driver.tap(story.center); + await expect(story.trigger).toHaveAttribute('aria-expanded', 'true'); +} + +test.describe('with a mouse (a fine primary pointer)', () => { + test.use({hasTouch: false, isMobile: false}); + + test('the layer keeps its own entrance and the popover closes at once', async ({ + page, + }) => { + await installLongTaskLog(page); + await openStory(page, storybook(), 'core-popover--default'); + const trigger = page.getByRole('button', {name: 'Settings'}); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + await trigger.click(); + await expect(trigger).toHaveAttribute('aria-expanded', 'true'); + const layer = page.locator('[popover]:has([role="dialog"])').first(); + // The layer's own CSS entrance runs; no UIKit scale is set or played. + const entrance = await layer.evaluate(element => ({ + inlineScale: (element as HTMLElement).style.getPropertyValue('scale'), + inlineAnimation: (element as HTMLElement).style.getPropertyValue( + 'animation-name', + ), + animationName: getComputedStyle(element).animationName, + played: element + .getAnimations() + .some( + animation => + !(animation instanceof CSSAnimation) && + (animation.effect as KeyframeEffect | null) + ?.getKeyframes() + .some(frame => 'scale' in frame) === true, + ), + })); + expect(entrance.inlineScale).toBe(''); + expect(entrance.inlineAnimation).toBe(''); + expect(entrance.animationName).not.toBe('none'); + expect(entrance.played).toBe(false); + await waitForRest(layer); + // A click outside closes it at once: no copy shrinks back into the trigger. + const viewport = page.viewportSize(); + if (viewport == null) { + throw new Error('no viewport'); + } + await page.mouse.click(20, viewport.height - 20); + await expect(trigger).toHaveAttribute('aria-expanded', 'false'); + await expect(exitCopyOf(page)).toHaveCount(0); + }); +}); + +test('the presentation grows out of the trigger on the theme\u2019s entrance tokens', async ({ + page, +}, testInfo) => { + const story = await openDefault(page); + // The popover's layout box, from a first presentation run to rest. + await openWithTap(story); + await waitForRest(story.layer); + const final = (await story.layer.boundingBox())!; + const entrance = await themeTiming(story.layer, POPOVER_ENTRANCE_TOKENS); + await page.keyboard.press('Escape'); + await expect(story.trigger).toHaveAttribute('aria-expanded', 'false'); + // Presenting during the dismissal would turn back from the closing frame. + await expect(exitCopyOf(page)).toHaveCount(0); + await openWithTap(story); + await scaleAnimationOf(story.layer); + const held = await holdAnimations(page, story.layer); + const samples = await sampleBoxes( + story.layer, + final, + timeline(entrance.ms + 100), + ); + await releaseAnimations(page, {finish: true}); + const at = (t: number) => + expectedBox(final, story.triggerBox, entrance.at(t)); + const compare = (read: (box: Box) => number) => + compareCurve( + samples.map(sample => ({t: sample.t, value: read(sample.box)})), + t => read(at(t)), + 0.75, + ); + const width = compare(box => box.width); + const height = compare(box => box.height); + const top = compare(box => box.y); + const cx = compare(box => box.x + box.width / 2); + const opacity = compareCurve( + samples.map(sample => ({t: sample.t, value: sample.opacity})), + t => entrance.at(t), + 0.02, + ); + await writeEvidence( + 'curves/popover-touch-present', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {held, final, trigger: story.triggerBox, width, height, top, cx}, + null, + 1, + ), + }, + testInfo, + ); + // The popover's edge stays on the trigger's bottom edge throughout. + for (const sample of samples) { + expect(sample.box.y).toBeCloseTo(final.y, 0); + } + for (const result of [width, height, top, cx, opacity]) { + expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual( + result.tolerance, + ); + } +}); + +test('the dismissal shrinks back into the trigger on the theme\u2019s exit tokens, on screen through the light dismiss', async ({ + page, +}, testInfo) => { + const story = await openDefault(page); + await openWithTap(story); + await waitForRest(story.layer); + const open = (await story.layer.boundingBox())!; + const exit = await themeTiming(story.layer, POPOVER_EXIT_TOKENS); + // Tap outside: the browser's light dismiss closes the popover at once. + const viewport = page.viewportSize()!; + await story.driver.tap({x: 20, y: viewport.height - 20}); + await expect(story.trigger).toHaveAttribute('aria-expanded', 'false'); + const copy = exitCopyOf(page); + await scaleAnimationOf(copy); + const held = await holdAnimations(page, copy); + // The popover is closed and gone; the dismissal plays on a static copy + // where it stood, out of the accessibility tree and out of reach. + const state = await page.evaluate(() => { + const layer = document.querySelector( + '[popover]:has([role="dialog"])', + )!; + const exitCopy = document.querySelector( + '[data-astryx-popover-exit]', + )!; + return { + layerOpen: layer.matches(':popover-open'), + layerDisplay: getComputedStyle(layer).display, + copyHidden: exitCopy.getAttribute('aria-hidden'), + copyInert: exitCopy.hasAttribute('inert'), + copyPointerEvents: getComputedStyle(exitCopy).pointerEvents, + copyIds: exitCopy.querySelectorAll('[id]').length, + }; + }); + expect(state).toEqual({ + layerOpen: false, + layerDisplay: 'none', + copyHidden: 'true', + copyInert: true, + copyPointerEvents: 'none', + copyIds: 0, + }); + const samples = await sampleBoxes(copy, open, timeline(exit.ms + 100)); + await releaseAnimations(page, {finish: true}); + // The dismissal runs the presentation's path backwards. + const at = (t: number) => expectedBox(open, story.triggerBox, 1 - exit.at(t)); + const width = compareCurve( + samples.map(sample => ({t: sample.t, value: sample.box.width})), + t => at(t).width, + 0.75, + ); + const height = compareCurve( + samples.map(sample => ({t: sample.t, value: sample.box.height})), + t => at(t).height, + 0.75, + ); + const opacity = compareCurve( + samples.map(sample => ({t: sample.t, value: sample.opacity})), + t => 1 - exit.at(t), + 0.02, + ); + await writeEvidence( + 'curves/popover-touch-dismiss', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {held, open, trigger: story.triggerBox, state, width, height}, + null, + 1, + ), + }, + testInfo, + ); + for (const result of [width, height, opacity]) { + expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual( + result.tolerance, + ); + } + // Once the dismissal has run, the copy is gone. + await expect(page.locator('[data-astryx-popover-exit]')).toHaveCount(0); +}); + +test('the presentation keeps advancing every frame while the main thread is blocked', async ({ + page, + browserName, +}, testInfo) => { + test.skip( + browserName !== 'chromium', + 'screencast frame evidence is Chromium-only in Playwright (WebKit: the iOS simulator rig)', + ); + const story = await openDefault(page); + // The screencast finds the element by its marker's exact color, which the + // content fade would blend away: hold opacity at 1 for this proof (an + // important declaration outranks the animation); the scale, composited + // the same way, carries the evidence. + await page.addStyleTag({ + content: '[popover]:has([role="dialog"]) { opacity: 1 !important; }', + }); + await markElement(story.layer, {size: 24, inset: 0}); + const entrance = await themeTiming(story.layer, POPOVER_ENTRANCE_TOKENS); + const cast = await startScreencast(page); + await openWithTap(story); + const [present] = await waitForAnimation(story.layer, {minProgressMs: 16}); + const block = await blockMainThread(page, 400); + await page.waitForTimeout(100); + const castFrames = await cast.stop(); + const tracked = await trackMarker(page, castFrames); + // Up to the end of the growth: until then the marker moves one way only. + const window = { + from: block.from, + to: Math.min(block.to, present.from + entrance.ms - 20), + }; + const proof = busyWindowProof(tracked, window, {axis: 'x'}); + await writeEvidence( + 'busy-main-thread/popover-touch-present', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {block, present, proof}, + null, + 1, + ), + }, + testInfo, + ); + const film = await castStoryboard(page, castFrames, { + name: 'popover-touch-present-busy-main-thread', + zero: block.from, + from: block.from - 40, + to: window.to + 40, + columns: 8, + cellScale: 0.35, + data: t => ({x: tracked.find(f => f.t === t)?.box?.x ?? -1}), + }); + await film.write(testInfo, {block, present}); + expect(proof.frames).toBeGreaterThanOrEqual(proof.expectedFrames - 2); + expect(proof.changed).toBeGreaterThanOrEqual(proof.frames - 3); + // A stall is judged in the screencast's own intervals, as the harness's + // verdict judges it: no more than two dropped frames. + expect(proof.longestStallFrames).toBeLessThanOrEqual(3); + expect(proof.monotonic).toBe(true); +}); + +test('the presentation and the dismissal do no Layout or Paint per frame', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only'); + const story = await openDefault(page); + const entrance = await themeTiming(story.layer, POPOVER_ENTRANCE_TOKENS); + const exit = await themeTiming(story.layer, POPOVER_EXIT_TOKENS); + let present = {from: 0, to: 0}; + let dismiss = {from: 0, to: 0}; + const started = Date.now(); + // Opened from the keyboard (the phone's primary pointer is still coarse, + // so the touch presentation runs) to keep the trigger's own press + // feedback out of the measurement. Nothing polls the page inside the + // windows: a style read during an animation forces a style update, and on + // an anchored element a layout. + await story.trigger.focus(); + const trace = await traceRendering(page, async () => { + await page.keyboard.press('Enter'); + present = await scaleAnimationOf(story.layer); + await page.waitForTimeout(present.to - Date.now() + 100); + await page.keyboard.press('Escape'); + dismiss = await scaleAnimationOf(exitCopyOf(page)); + await page.waitForTimeout(dismiss.to - Date.now() + 100); + }); + // The animations hold their end state for a while past the curve; judge + // the curves themselves, less their first and last frames. The growth's + // first 150 ms also carry the focus moving into the popover (its first + // control paints its ring), which is not this motion. + const windows = [ + { + name: 'present', + from: present.from + 150, + to: present.from + entrance.ms - 20, + }, + { + name: 'dismiss', + from: dismiss.from + 30, + to: dismiss.from + exit.ms - 20, + }, + ]; + for (const window of windows) { + const during = countBetween(trace, window.from, window.to); + // On failure, every rendering event of the window, in ms after its + // animation's start. + const base = window.name === 'present' ? present.from : dismiss.from; + const detail = `${window.name} ${JSON.stringify({ + during, + events: trace.events + .filter(e => e.t >= window.from && e.t <= window.to) + .map(e => `${e.name}@${Math.round(e.t - base)}`), + })}`; + expect(during.Layout ?? 0, detail).toBe(0); + expect(during.Paint ?? 0, detail).toBe(0); + } + expect(trace.longTasks).toEqual([]); + expect(await readLongTasks(page, {from: started, to: Date.now()})).toEqual( + [], + ); +}); + +test('Reduce Motion: the popover cross-fades in at its size and out where it stands, in 200 ms or less with no spring', async ({ + page, +}) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + const story = await openDefault(page); + await openWithTap(story); + await waitForAnimation(story.layer); + await holdAnimations(page, story.layer); + const unit = {x: 0, y: 0, width: 100, height: 100}; + // design:reduced-motion DR2: opacity only, 200 ms or less, here on + // UIKit's cross-fade curve. + const ease = cubicBezier(timing.curves.move); + const fade = (t: number) => + ease(Math.min(1, Math.max(0, t / timing.reducedMotionCrossFadeMs))); + const samples = await sampleBoxes(story.layer, unit, timeline(300)); + // Resume rather than finish: the dismissal below starts from what the + // animator presents, which follows the clock. + await releaseAnimations(page); + await page.waitForTimeout(400); + // No growth: every frame is the popover at full size; it only fades in. + for (const sample of samples) { + expect(sample.box.width).toBeCloseTo(100, 3); + expect(sample.box.height).toBeCloseTo(100, 3); + } + const opacity = compareCurve( + samples.map(sample => ({t: sample.t, value: sample.opacity})), + fade, + 0.02, + ); + expect(opacity.maxError, JSON.stringify(opacity.worst)).toBeLessThanOrEqual( + 0.02, + ); + // In by 200 ms. + for (const sample of samples.filter( + s => s.t >= timing.reducedMotionCrossFadeMs, + )) { + expect(sample.opacity).toBeCloseTo(1, 3); + } + // The dismissal fades out where the popover stands, on the same curve. + await page.keyboard.press('Escape'); + const copy = exitCopyOf(page); + await waitForAnimation(copy); + await holdAnimations(page, copy); + const [closing, gone] = await sampleBoxes(copy, unit, [ + 100, + timing.reducedMotionCrossFadeMs, + ]); + await releaseAnimations(page, {finish: true}); + expect(closing.box.width).toBeCloseTo(100, 3); + expect(closing.opacity).toBeCloseTo(1 - fade(100), 2); + expect(gone.opacity).toBeCloseTo(0, 3); +}); + +test( + 'storyboard: tap to present, tap outside to dismiss', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + const story = await openDefault(page); + await installTimerGate(page); + const viewport = page.viewportSize() ?? {width: 402, height: 714}; + const clip = {x: 0, y: 0, width: viewport.width, height: viewport.height}; + // The presented scale and opacity (a composited scale does not reach + // getBoundingClientRect in Chromium), and the layout size they apply to. + const measureOf = (locator: Locator) => async () => + locator.evaluate(node => { + const el = node as HTMLElement; + const style = getComputedStyle(el); + const [sx, sy = sx] = + style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number); + return { + w: el.offsetWidth * sx, + h: el.offsetHeight * sy, + opacity: Number(style.opacity), + }; + }); + await openWithTap(story); + await waitForAnimation(story.layer); + const entrance = await themeTiming(story.layer, POPOVER_ENTRANCE_TOKENS); + const exit = await themeTiming(story.layer, POPOVER_EXIT_TOKENS); + await freezeTimers(page); + const {storyboard: presentBoard} = await animationStoryboard(page, { + name: 'popover-touch-present', + clip, + scope: story.layer, + measure: measureOf(story.layer), + // The growth ends with the entrance duration; the animation holds its + // end state past that. + times: timeline(entrance.ms + 100), + columns: 8, + cellScale: 0.35, + }); + await releaseAnimations(page, {finish: true}); + await thawTimers(page); + await waitForRest(story.layer); + await story.driver.tap({x: 20, y: viewport.height - 20}); + const copy = exitCopyOf(page); + await waitForAnimation(copy); + await freezeTimers(page); + const {storyboard: dismissBoard} = await animationStoryboard(page, { + name: 'popover-touch-dismiss', + clip, + scope: copy, + measure: measureOf(copy), + times: timeline(exit.ms + 100), + columns: 8, + cellScale: 0.35, + }); + await releaseAnimations(page, {finish: true}); + await thawTimers(page); + await presentBoard.write(testInfo); + await dismissBoard.write(testInfo); + // The trace is the assertion: it grows from a point, wide before tall, + // with no overshoot, and shrinks back. + const widths = presentBoard.frames.map(f => f.data.w as number); + const heights = presentBoard.frames.map(f => f.data.h as number); + expect(widths[0]).toBeLessThan(widths.at(-1)! / 10); + expect(Math.max(...widths)).toBeLessThanOrEqual(widths.at(-1)! + 0.5); + const middle = Math.floor(widths.length / 8); + expect(heights[middle] / heights.at(-1)!).toBeLessThan( + widths[middle] / widths.at(-1)!, + ); + const dismissWidths = dismissBoard.frames.map(f => f.data.w as number); + expect(dismissWidths.at(-1)!).toBeLessThan(dismissWidths[0] / 2); + }, +); From e0a9bb5defa429f21c9bf64504786f1ec4920e6f Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 4 Nov 2026 00:52:41 -0800 Subject: [PATCH 5/8] fix(Popover): under a finger, a tap during the presentation is ignored, as on iOS While the popover grows out of its trigger under a coarse primary pointer, the layer runtime's input hold takes every touch. A tap outside neither dismisses it nor reaches what is under it, a pan scrolls nothing, and a pinch still zooms the page. --- .changeset/popover-uikit-presentation.md | 2 +- docs/specs/components/Popover/Popover.spec.md | 2 +- ...verTouchMotion.interaction.browser.spec.ts | 237 +++++++++++++++++- .../src/Popover/popoverSurfaceMotion.test.ts | 59 ++++- .../core/src/Popover/popoverSurfaceMotion.ts | 22 +- 5 files changed, 317 insertions(+), 5 deletions(-) diff --git a/.changeset/popover-uikit-presentation.md b/.changeset/popover-uikit-presentation.md index ce642a5cd9fd4..d388716e8ee6c 100644 --- a/.changeset/popover-uikit-presentation.md +++ b/.changeset/popover-uikit-presentation.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[feature] Under a finger (a coarse primary pointer, on any touch device), Popover grows out of its trigger, wide before tall, with its edge held on the trigger, and shrinks back into the trigger when it closes. The growth plays the theme's entrance duration and easing, and the shrink plays its exit duration and easing, on the compositor. A close during the growth, or an open during the shrink, turns back from where the popover is. With reduced motion it cross-fades in and out, opacity only, in 200 ms or less. A fine primary pointer (a mouse) keeps its entrance. The shrink plays on the layer runtime's exit copy, of which Popover is the first user. +[feature] Under a finger (a coarse primary pointer, on any touch device), Popover grows out of its trigger, wide before tall, with its edge held on the trigger, and shrinks back into the trigger when it closes. The growth plays the theme's entrance duration and easing, and the shrink plays its exit duration and easing, on the compositor. A close during the growth, or an open during the shrink, turns back from where the popover is. With reduced motion it cross-fades in and out, opacity only, in 200 ms or less. A fine primary pointer (a mouse) keeps its entrance. A tap that lands while it grows is ignored, and a pan started then scrolls nothing. The shrink plays on the layer runtime's exit copy, of which Popover is the first user. @vjeux diff --git a/docs/specs/components/Popover/Popover.spec.md b/docs/specs/components/Popover/Popover.spec.md index ad76f76b06cc7..b3bda97e453e4 100644 --- a/docs/specs/components/Popover/Popover.spec.md +++ b/docs/specs/components/Popover/Popover.spec.md @@ -187,7 +187,7 @@ table owns their semantic effect. | FR6 | Component anatomy contains the caller trigger and content, one painted Popover surface, and the optional fallback close control. Popover owns no Header, Body, or separate shared-hook surface part. | Current source, docs target inventory, and tests | Accepted anatomy; stale consumer anatomy corrected by this contract | | FR7 | The painted surface has one broad canonical target, `popover`; composed components may add one authoritative component-specific refinement target. | Owner direction on 2026-08-31 plus current target inventory | Accepted canonical contract; covered by focused target tests | | FR8 | The surface padding is one spacing-scale rung applied on the painted surface. Popover defaults to step 3 (the released inset); `0` paints a flush surface; a direct `usePopover` composition paints none unless it asks for a rung. The rung sits where a theme's `padding` on the `popover` target replaces it. | PR #6683 and its Popover tests; `architecture:container-padding/INV8` (padding alone does not enroll) | Pending owner review (DEC-4); implemented and covered by the Popover surface-padding suite | -| FR9 | Under a finger, Popover grows out of its trigger on the theme's `--duration-fast-max` and `--ease-entrance` and shrinks back into it on the theme's exit duration and easing, and a touch during its growth is ignored (`spec:AST-094` FR31, FR35 and FR45). Its dismissal is unchanged, and a mouse keeps today's entrance. | `spec:AST-094` FR31, FR35 | Grow and shrink implemented; a touch during the growth is not yet ignored | +| FR9 | Under a finger, Popover grows out of its trigger on the theme's `--duration-fast-max` and `--ease-entrance` and shrinks back into it on the theme's exit duration and easing, and a touch during its growth is ignored (`spec:AST-094` FR31, FR35 and FR45). Its dismissal is unchanged, and a mouse keeps today's entrance. | `spec:AST-094` FR31, FR35 | Implemented; gap: the open-to-close latch waits for the shared presentation hold | ### Allowed variation diff --git a/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts b/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts index 4f5951b00aab8..403b808bb845f 100644 --- a/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts +++ b/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts @@ -12,7 +12,8 @@ * screen through the light dismiss; the growth keeps advancing through a * blocked main thread; neither does Layout or Paint per frame; Reduce * Motion cross-fades, opacity only, in 200 ms or less; a mouse keeps the - * layer's own entrance; storyboards of both + * layer's own entrance; a tap, a pan or a pinch while it grows does nothing + * but a pinch's zoom; storyboards * @position Evidence for Popover's touch presentation; the model itself is * unit-tested in popoverSurfaceMotion.test.ts */ @@ -25,17 +26,20 @@ import { } from '@astryxdesign/a11y-spec/playwright'; import { animationStoryboard, + armHold, blockMainThread, busyWindowProof, castStoryboard, compareCurve, countBetween, + drag, freezeTimers, holdAnimations, installLongTaskLog, installTimerGate, markElement, openStory, + pinch, readLongTasks, releaseAnimations, startScreencast, @@ -63,6 +67,10 @@ import { const storybook = withStorybook(test); +// The layer runtime's input hold puts its shield inside the layer. It is a +// manual popover hidden from assistive technology, and not the exit copy. +const SHIELD = '[popover][aria-hidden="true"]:not([data-astryx-popover-exit])'; + /** * The duration (ms) and the eased progress that the story's theme gives * `tokens`, read where the popover is. @@ -657,3 +665,230 @@ test( expect(dismissWidths.at(-1)!).toBeLessThan(dismissWidths[0] / 2); }, ); + +/** + * Logs each close of a popover and each click on an added button outside it. + * The hold takes a held press before any page listener, so the log counts + * what a press did, not the press itself. + */ +async function installPressLog(page: Page) { + await page.evaluate(() => { + const log = {closed: 0, outsideClicks: 0}; + (window as unknown as {__pressLog: typeof log}).__pressLog = log; + document.addEventListener( + 'toggle', + event => { + if (event.newState === 'closed') { + log.closed += 1; + } + }, + true, + ); + const outside = document.createElement('button'); + outside.textContent = 'Outside'; + Object.assign(outside.style, { + position: 'fixed', + right: '20px', + bottom: '20px', + width: '120px', + height: '44px', + }); + outside.addEventListener('click', () => { + log.outsideClicks += 1; + }); + document.body.append(outside); + }); +} + +const readPressLog = async (page: Page) => + page.evaluate( + () => + ( + window as unknown as { + __pressLog: {closed: number; outsideClicks: number}; + } + ).__pressLog, + ); + +/** Whether the hold's shield is up and is what a press at `point` hits. */ +async function shieldTakes(page: Page, point: {x: number; y: number}) { + return page.evaluate( + ({selector, x, y}) => { + const shield = document.querySelector(selector); + return ( + shield?.matches(':popover-open') === true && + document.elementFromPoint(x, y) === shield + ); + }, + {selector: SHIELD, ...point}, + ); +} + +/** The center of the added button outside the popover. */ +function outsidePoint(page: Page) { + const viewport = page.viewportSize(); + if (viewport == null) { + throw new Error('no viewport'); + } + return {x: viewport.width - 80, y: viewport.height - 42}; +} + +/** + * Opens the popover with a tap and holds its growth where it starts, so the + * next press lands while it grows. Returns the held growth; release it with + * `releaseAnimations`. + */ +async function openHeldWhileGrowing(page: Page, story: OpenStory) { + const armed = await armHold(page, story.layer); + await openWithTap(story); + return armed.held(); +} + +const focusedElement = async (page: Page) => + page.evaluate(() => document.activeElement?.outerHTML.slice(0, 120)); + +test('a tap outside while it grows is ignored: the popover stays open and keeps focus, and the tap reaches nothing', async ({ + page, +}) => { + const story = await openDefault(page); + await installPressLog(page); + const outside = outsidePoint(page); + await openHeldWhileGrowing(page, story); + const focusedAtOpen = await focusedElement(page); + // The tap outside lands on the hold's shield. + expect(await shieldTakes(page, outside)).toBe(true); + await story.driver.tap(outside); + await releaseAnimations(page, {finish: true}); + await waitForRest(story.layer); + await expect(story.trigger).toHaveAttribute('aria-expanded', 'true'); + const log = await readPressLog(page); + expect(log.closed).toBe(0); + expect(log.outsideClicks).toBe(0); + // The control the popover focused keeps focus. + expect(focusedAtOpen).toContain('role="switch"'); + expect(await focusedElement(page)).toBe(focusedAtOpen); + // Once it has grown, the hold is gone, and a tap outside dismisses it. + await expect(page.locator(SHIELD)).toHaveCount(0); + await story.driver.tap(outside); + await expect(story.trigger).toHaveAttribute('aria-expanded', 'false'); +}); + +test('a tap on the trigger while it grows does not close the popover', async ({ + page, +}) => { + const story = await openDefault(page); + await installPressLog(page); + await openHeldWhileGrowing(page, story); + expect(await shieldTakes(page, story.center)).toBe(true); + await story.driver.tap(story.center); + await releaseAnimations(page, {finish: true}); + await waitForRest(story.layer); + await expect(story.trigger).toHaveAttribute('aria-expanded', 'true'); + const log = await readPressLog(page); + expect(log.closed).toBe(0); +}); + +test('a pan outside while it grows starts nothing: no scroll, and the popover stays', async ({ + page, +}) => { + const story = await openDefault(page); + test.skip( + !story.driver.drivesNativeGestures, + 'scripted touches do not start native pans in this engine', + ); + await installPressLog(page); + // Room to scroll, so a pan the browser took would scroll the page. + await page.addStyleTag({content: 'body { min-height: 300vh; }'}); + const viewport = page.viewportSize()!; + await openHeldWhileGrowing(page, story); + const focusedAtOpen = await focusedElement(page); + const from = {x: viewport.width - 40, y: viewport.height - 120}; + expect(await shieldTakes(page, from)).toBe(true); + await story.driver.play( + drag(from, {x: from.x, y: from.y - 100}, {durationMs: 150, hz: 60}), + ); + await releaseAnimations(page, {finish: true}); + await waitForRest(story.layer); + await expect(story.trigger).toHaveAttribute('aria-expanded', 'true'); + const log = await readPressLog(page); + expect(log.closed).toBe(0); + expect(await page.evaluate(() => window.scrollY)).toBe(0); + expect(await focusedElement(page)).toBe(focusedAtOpen); +}); + +test('a pinch while it grows zooms the page, and the popover grows and stays', async ({ + page, +}) => { + const story = await openDefault(page); + test.skip( + !story.driver.drivesNativeGestures, + 'scripted touches do not start a native pinch-zoom in this engine', + ); + await installPressLog(page); + const scale = async () => + page.evaluate(() => window.visualViewport?.scale ?? 1); + expect(await scale()).toBe(1); + const viewport = page.viewportSize()!; + await openHeldWhileGrowing(page, story); + const center = {x: viewport.width / 2, y: viewport.height - 160}; + expect(await shieldTakes(page, center)).toBe(true); + await story.driver.play( + pinch({ + center, + fromDistance: 60, + toDistance: 240, + durationMs: 200, + hz: 60, + }), + ); + await releaseAnimations(page, {finish: true}); + await waitForRest(story.layer); + // The fingers landed on the shield, which leaves a pinch to the browser. + await expect.poll(scale).toBeGreaterThan(1.1); + await expect(story.trigger).toHaveAttribute('aria-expanded', 'true'); + const log = await readPressLog(page); + expect(log.closed).toBe(0); +}); + +test( + 'storyboard: a tap outside while it grows, and the growth goes on', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + const story = await openDefault(page); + await installTimerGate(page); + const viewport = page.viewportSize() ?? {width: 402, height: 714}; + const clip = {x: 0, y: 0, width: viewport.width, height: viewport.height}; + const entrance = await themeTiming(story.layer, POPOVER_ENTRANCE_TOKENS); + const held = await openHeldWhileGrowing(page, story); + const outside = outsidePoint(page); + expect(await shieldTakes(page, outside)).toBe(true); + await story.driver.tap(outside); + await freezeTimers(page); + const {storyboard} = await animationStoryboard(page, { + name: 'popover-touch-tap-while-growing', + clip, + held, + measure: async () => + story.layer.evaluate(node => { + const el = node as HTMLElement; + const style = getComputedStyle(el); + const [sx] = + style.scale === 'none' ? [1] : style.scale.split(' ').map(Number); + return {w: el.offsetWidth * sx, open: el.matches(':popover-open')}; + }), + times: timeline(entrance.ms + 100), + columns: 8, + cellScale: 0.35, + }); + await releaseAnimations(page, {finish: true}); + await thawTimers(page); + await storyboard.write(testInfo); + // The trace is the assertion: the popover stays open on every frame and + // grows to its full width, with no exit copy. + const widths = storyboard.frames.map(f => f.data.w as number); + expect(storyboard.frames.every(f => f.data.open === true)).toBe(true); + expect(widths.at(-1)!).toBeGreaterThan(widths[0]); + await expect(exitCopyOf(page)).toHaveCount(0); + await expect(story.trigger).toHaveAttribute('aria-expanded', 'true'); + }, +); diff --git a/packages/core/src/Popover/popoverSurfaceMotion.test.ts b/packages/core/src/Popover/popoverSurfaceMotion.test.ts index d21ada538809c..c1288db85ecf6 100644 --- a/packages/core/src/Popover/popoverSurfaceMotion.test.ts +++ b/packages/core/src/Popover/popoverSurfaceMotion.test.ts @@ -7,12 +7,14 @@ * @output Checks where the popover grows from on each side of its source, * and that every frame stays on UIKit's measured path. Checks that the * growth plays the entrance tokens and the shrink the exit tokens. Covers - * present, dismiss, turn-back, reset and Reduce Motion. + * present, dismiss, turn-back, reset, Reduce Motion and the input hold + * while it grows. * @position Testing; the curves on a real compositor are proven in * __tests__/PopoverTouchMotion.interaction.browser.spec.ts */ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {isInHeldLayer, isInputShield} from '../Layer/inputHold'; import {cubicBezier} from '../motion/bezier'; import {parseCssEasing, parseMotionRoleValue} from '../motion/roles'; import {popover, timing} from '../motion/uikit'; @@ -599,4 +601,59 @@ describe('createPopoverSurfaceMotion', () => { } } }); + describe('the hold while it grows', () => { + const shieldOf = (element: HTMLElement) => + [...element.children].find(node => isInputShield(node)) ?? null; + + it('holds every touch while the popover grows, and lets go when the growth ends', async () => { + const {element, motion} = create(); + motion.enter(() => GEOMETRY); + expect(isInHeldLayer(element)).toBe(true); + expect(shieldOf(element)).not.toBeNull(); + // Still held halfway through the growth. + clock += ENTRANCE.ms / 2; + vi.advanceTimersByTime(ENTRANCE.ms / 2); + await Promise.resolve(); + expect(isInHeldLayer(element)).toBe(true); + // Free once the growth has ended. + const [growth] = live('scale', element); + const duration = Number(growth.options.duration); + clock += duration; + vi.advanceTimersByTime(duration); + await Promise.resolve(); + await Promise.resolve(); + expect(isInHeldLayer(element)).toBe(false); + expect(shieldOf(element)).toBeNull(); + }); + + it('lets go at once when the popover is dismissed or reset during the growth', () => { + const dismissed = create(); + dismissed.motion.enter(() => GEOMETRY); + expect(isInHeldLayer(dismissed.element)).toBe(true); + dismissed.motion.exit(); + expect(isInHeldLayer(dismissed.element)).toBe(false); + expect(shieldOf(dismissed.element)).toBeNull(); + + const reset = create(); + reset.motion.enter(() => GEOMETRY); + reset.motion.reset(); + expect(isInHeldLayer(reset.element)).toBe(false); + expect(shieldOf(reset.element)).toBeNull(); + }); + + it('holds under Reduce Motion too, for the length of the cross-fade', async () => { + const {element, motion} = create(true); + motion.enter(() => GEOMETRY); + expect(isInHeldLayer(element)).toBe(true); + clock += timing.reducedMotionCrossFadeMs / 2; + vi.advanceTimersByTime(timing.reducedMotionCrossFadeMs / 2); + await Promise.resolve(); + expect(isInHeldLayer(element)).toBe(true); + clock += timing.reducedMotionCrossFadeMs; + vi.advanceTimersByTime(timing.reducedMotionCrossFadeMs); + await Promise.resolve(); + await Promise.resolve(); + expect(isInHeldLayer(element)).toBe(false); + }); + }); }); diff --git a/packages/core/src/Popover/popoverSurfaceMotion.ts b/packages/core/src/Popover/popoverSurfaceMotion.ts index 933acbc08a038..4ee2e0c6ef2f5 100644 --- a/packages/core/src/Popover/popoverSurfaceMotion.ts +++ b/packages/core/src/Popover/popoverSurfaceMotion.ts @@ -6,7 +6,7 @@ * @file popoverSurfaceMotion.ts * @input A Popover's layer element, the source it hangs off, the compositor * animator, the theme's duration and easing tokens, and the layer - * runtime's exit copy + * runtime's exit copy and input hold * @output Exports `popoverCollapsedState`, `popoverFrame` and * `createPopoverSurfaceMotion`, the touch presentation's present and * dismiss. @@ -26,6 +26,7 @@ import { type MotionCurve, type MotionHandle, } from '../motion/animator'; +import {holdInput} from '../Layer/inputHold'; import {mapProgress, mapRange} from '../motion/progress'; import {readThemeTiming} from '../motion/themeTiming'; import {placePopoverExitCopy} from '../privateAttributes/popoverExit.stylex'; @@ -124,6 +125,13 @@ const MOTION_STYLE_PROPERTIES = [ * The browser hides a popover as it closes, so the dismissal plays on the * layer runtime's exit copy, which is removed when its motion ends. * + * While the popover grows, the layer runtime's input hold takes every touch, + * as UIKit ignores touches while it presents a popover. A tap outside does + * not dismiss it and reaches nothing under it. A pinch still zooms the page. + * The browser's light dismiss cannot be cancelled from an event, so the + * hold's shield covers the viewport from inside the layer. A tap on the + * shield is then a tap inside the popover, which the browser leaves open. + * * Under Reduce Motion the animator's policy applies. On a coarse pointer the * popover lands at its full size and cross-fades in, and it cross-fades out * where it stands. @@ -142,6 +150,13 @@ export function createPopoverSurfaceMotion( let presentHandle: MotionHandle | null = null; // The dismissal in progress: its copy and the copy's animator. let exiting: {copy: HTMLElement; animator: Animator} | null = null; + // Releases the hold that takes every touch while the popover grows. + let releaseHold: (() => void) | null = null; + + const endHold = () => { + releaseHold?.(); + releaseHold = null; + }; const endExit = () => { if (exiting == null) { @@ -156,6 +171,7 @@ export function createPopoverSurfaceMotion( collapsed = null; measured = null; presentHandle = null; + endHold(); endExit(); animator.set({scaleX: 1, scaleY: 1, opacity: 1}); for (const property of MOTION_STYLE_PROPERTIES) { @@ -204,14 +220,18 @@ export function createPopoverSurfaceMotion( ), ); presentHandle = handle; + endHold(); + releaseHold = holdInput(element, {until: handle, scope: 'viewport'}); void handle.finished.then(() => { if (presentHandle === handle) { presentHandle = null; + endHold(); } }); }; const exit = () => { + endHold(); const target = collapsed; if (target == null || exiting != null) { return; From 1fda0191072c43a1489a5796c1aaab7abc9f67f5 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 4 Nov 2026 15:53:44 -0800 Subject: [PATCH 6/8] 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 415707b000eced7b58a5bde9f92045d31f3cca13 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 5 Nov 2026 07:38:03 -0800 Subject: [PATCH 7/8] feat(Popover): under a finger, it grows out of its trigger and shrinks back into it Under a coarse primary pointer, Popover grows out of its trigger on the theme duration step nearest iOS's growth (`--duration-medium-min`) and the theme's entrance easing, and shrinks back into it on the theme's exit duration and easing, on the layer runtime's exit copy. A fine primary pointer keeps the layer's own entrance. --- .changeset/popover-uikit-presentation.md | 7 + docs/specs/components/Popover/Popover.spec.md | 7 +- packages/core/src/Layer/useLayer.test.tsx | 38 ++ packages/core/src/Layer/useLayer.tsx | 14 + packages/core/src/Popover/Popover.doc.mjs | 6 +- packages/core/src/Popover/Popover.test.tsx | 116 ++++ packages/core/src/Popover/Popover.tsx | 39 +- packages/core/src/Popover/PopoverTouch.ts | 20 + .../src/Popover/popoverSurfaceFrame.test.ts | 70 ++ .../core/src/Popover/popoverSurfaceFrame.ts | 167 +++++ .../src/Popover/popoverSurfaceMotion.test.ts | 602 ++++++++++++++++++ .../core/src/Popover/popoverSurfaceMotion.ts | 276 ++++++++ packages/core/src/Popover/usePopover.tsx | 34 +- .../Popover/usePopoverSurfaceMotion.test.tsx | 110 ++++ .../src/Popover/usePopoverSurfaceMotion.ts | 112 ++++ packages/core/src/motion/MEASUREMENTS.md | 17 + packages/core/src/motion/README.md | 1 + packages/core/src/motion/uikit/index.ts | 3 +- packages/core/src/motion/uikit/popover.ts | 71 +++ .../privateAttributes/popoverExit.stylex.ts | 30 + 20 files changed, 1727 insertions(+), 13 deletions(-) create mode 100644 .changeset/popover-uikit-presentation.md create mode 100644 packages/core/src/Popover/PopoverTouch.ts create mode 100644 packages/core/src/Popover/popoverSurfaceFrame.test.ts create mode 100644 packages/core/src/Popover/popoverSurfaceFrame.ts create mode 100644 packages/core/src/Popover/popoverSurfaceMotion.test.ts create mode 100644 packages/core/src/Popover/popoverSurfaceMotion.ts create mode 100644 packages/core/src/Popover/usePopoverSurfaceMotion.test.tsx create mode 100644 packages/core/src/Popover/usePopoverSurfaceMotion.ts create mode 100644 packages/core/src/motion/uikit/popover.ts create mode 100644 packages/core/src/privateAttributes/popoverExit.stylex.ts diff --git a/.changeset/popover-uikit-presentation.md b/.changeset/popover-uikit-presentation.md new file mode 100644 index 0000000000000..0f80a71b797be --- /dev/null +++ b/.changeset/popover-uikit-presentation.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feature] Under a finger (a coarse primary pointer, on any touch device), Popover grows out of its trigger, wide before tall, with its edge held on the trigger, and shrinks back into the trigger when it closes. The growth plays the theme's `--duration-medium-min` (in the Storybook theme, the step nearest iOS's 206 ms growth) with its entrance easing, and the shrink plays its exit duration and easing, on the compositor. A close during the growth, or an open during the shrink, turns back from where the popover is. With reduced motion it cross-fades in and out, opacity only, in 200 ms or less. A fine primary pointer (a mouse) keeps its entrance. The shrink plays on the layer runtime's exit copy, of which Popover is the first user. + +@vjeux diff --git a/docs/specs/components/Popover/Popover.spec.md b/docs/specs/components/Popover/Popover.spec.md index 82067f19c6e6e..e585afb5e0b54 100644 --- a/docs/specs/components/Popover/Popover.spec.md +++ b/docs/specs/components/Popover/Popover.spec.md @@ -188,7 +188,7 @@ table owns their semantic effect. | FR6 | Component anatomy contains the caller trigger and content, one painted Popover surface, and the optional fallback close control. Popover owns no Header, Body, or separate shared-hook surface part. | Current source, docs target inventory, and tests | Accepted anatomy; stale consumer anatomy corrected by this contract | | FR7 | The painted surface has one broad canonical target, `popover`; composed components may add one authoritative component-specific refinement target. | Owner direction on 2026-08-31 plus current target inventory | Accepted canonical contract; covered by focused target tests | | FR8 | The surface padding is one spacing-scale rung applied on the painted surface. Popover defaults to step 3 (the released inset); `0` paints a flush surface; a direct `usePopover` composition paints none unless it asks for a rung. The rung sits where a theme's `padding` on the `popover` target replaces it. | PR #6683 and its Popover tests; `architecture:container-padding/INV8` (padding alone does not enroll) | Pending owner review (DEC-4); implemented and covered by the Popover surface-padding suite | -| FR9 | Under a finger, Popover grows out of its trigger on the theme's entrance duration and easing tokens and shrinks back into it on the theme's exit duration and easing, and a touch during its growth is ignored, as `spec:AST-094` FR31, FR35 and FR45 state. Its dismissal is unchanged, and a mouse keeps today's entrance. | `spec:AST-094` FR31, FR35 | Pending implementation; tests land with it | +| FR9 | Under a finger, Popover grows from its trigger on `--duration-medium-min`, the Storybook step nearest iOS's 206 ms growth, with `--ease-entrance` (`spec:AST-094` FR45), and shrinks back on the theme's exit duration and easing. A touch while it grows is ignored (FR35). Dismissal and a mouse's entrance are unchanged. | `spec:AST-094` FR31, FR35 | Grow and shrink implemented; a touch during the growth is not yet ignored | ### Allowed variation @@ -252,6 +252,10 @@ table owns their semantic effect. pending coalesce into one animation-frame callback. - **PR3 — Stable state update.** Measurement updates overflow state only when the overflow boolean changes. +- **PR4 — Touch presentation frames.** On a page with no other frame work, the + touch growth and shrink do no Layout or Paint per frame. Known platform cost: + in Chromium, a page with its own `requestAnimationFrame` loop makes an + anchored, animating layer lay out and paint every frame. ## Accessibility contract @@ -357,6 +361,7 @@ consumers that need distinct theme reachability provide and document an owned | ORD2, FR4 | `Popover.test.tsx` sizing/overflow suites; `Popover.stories.tsx` match-trigger and overflow scenarios; geometry under `Core/Layer` viewport-inset stories | Explicit width clamped to the viewport, trigger matching, fitting and overflowing content | Reversing width precedence, capping to the span beside the trigger, or always enabling scroll fails emitted-style or overflow assertions. | `audit:Popover/layout` | | FR8 | `Popover.test.tsx` surface-padding suite | Default rung, `0`, an explicit rung, a direct hook composition with and without a rung | A default other than step 3, a rung landing on a box inside the surface, or the hook painting a rung it was not given fails the suite. | `audit:Popover/theming` | | FR9 | `spec:AST-094` verification for FR31 and FR35 | Under a finger: open, close, a touch during growth; a mouse | A Popover that does not grow from and shrink into its trigger, a changed dismissal, or a changed mouse path fails. | `audit:Popover/behavior` | +| PR4 | `spec:AST-094` verification for FR5 | The touch growth and shrink in a Chromium trace, on a page with no other frame work | A Layout or a Paint during either motion on such a page | `audit:Popover/resources` | | FR5 | `Popover.test.tsx` scheduling and observer-lifecycle suites | Closed, opened, repeated signals, cleanup | Constructing observers while closed or measuring more than once per pending frame fails lifecycle assertions. | `audit:Popover/resources` | | FR6, FR7 and theming anatomy | `Popover.test.tsx`, `Popover.doc.mjs`, `usePopover.doc.mjs`, `astryx theme targets Popover --json`, and `scripts/check-knowledge.mjs` | One real surface with canonical `popover` plus composed-component refinements | A fake anatomy part, missing canonical output, or an active target without a real owner fails review or validation. | `audit:Popover/theming` | | AR5 | `Popover.stories.tsx` manual-AT fixture and PR #5373 test record | Read-only dialog manual-AT fixture; no recorded NVDA/VoiceOver announcement result | A fixture without recorded AT/browser observations cannot be cited as announcement proof. | `audit:Popover/at-evidence` | diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsx index 203e4ebdd73d8..a8458afd43bfa 100644 --- a/packages/core/src/Layer/useLayer.test.tsx +++ b/packages/core/src/Layer/useLayer.test.tsx @@ -1499,6 +1499,44 @@ describe('useLayer', () => { expect(onTooltipShow).toHaveBeenCalledTimes(1); }); + it('reports a close start as a hide starts, before its toggle: the browser\u2019s own hide and hide() alike', () => { + const {browserHide, runToggleTasks} = installBrowserHidePopoverApi(); + const events: string[] = []; + function CloseStartHarness() { + const layer = useLayerInternal({ + mode: 'context', + onCloseStart: () => events.push('close-start'), + onHide: () => events.push('hide'), + }); + return ( + <> + + + {layer.render(Content)} + + ); + } + const {getByRole, getByText} = render(); + fireEvent.click(getByRole('button', {name: 'Trigger'})); + act(() => runToggleTasks()); + expect(events).toEqual([]); + // The browser hides the popover itself, as a close watcher's Escape. + const popover = getByText('Content').closest('[popover]')!; + act(() => browserHide(popover)); + expect(events).toEqual(['close-start']); + act(() => runToggleTasks()); + expect(events).toEqual(['close-start', 'hide']); + // The hook's own hide() starts a close the same way, before its hide. + fireEvent.click(getByRole('button', {name: 'Trigger'})); + act(() => runToggleTasks()); + fireEvent.click(getByRole('button', {name: 'Close'})); + expect(events).toEqual(['close-start', 'hide', 'close-start', 'hide']); + }); + it('opens a layer at once when the press that closed another one opens it after the hide has returned', () => { // A light dismiss runs at pointerup and the click that follows opens the // next layer in the same gesture: the browser accepts that show (its diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx index 23d6423b11b8a..1bc7080e0206a 100644 --- a/packages/core/src/Layer/useLayer.tsx +++ b/packages/core/src/Layer/useLayer.tsx @@ -455,6 +455,12 @@ interface InternalContextLayerOptions extends ContextLayerOptions { * context menu on every table cell). */ keepsMountAfterShow?: boolean; + /** + * Runs as the layer starts to close, while the browser still shows it: in + * its `beforetoggle` to closed. A close that plays out after the layer is + * hidden starts here. + */ + onCloseStart?: () => void; } type InternalContextLayerReturn = ContextLayerReturn & InternalLayerFields; @@ -1065,6 +1071,9 @@ function useLayerImplementation( : false; const keepsAnchorClear = mode === 'context' ? (options.keepsAnchorClear ?? false) : false; + const onCloseStartRef = useRef<(() => void) | undefined>(undefined); + onCloseStartRef.current = + mode === 'context' ? options.onCloseStart : undefined; const id = useId(); const anchorId = `--astryx-layer-${id.replace(/:/g, '')}`; @@ -1393,6 +1402,10 @@ function useLayerImplementation( pendingShowRef.current = false; if (isOpenRef.current) { const el = popoverRef.current; + // A close that plays out after the layer is hidden starts here, while + // the browser still shows it. The `beforetoggle` handler below starts + // the browser's own hides. + onCloseStartRef.current?.(); // Clear the open state BEFORE hiding: hidePopover fires `toggle`, and // the reconciler below reads this ref to tell the browser's own // dismissals from ours. @@ -1542,6 +1555,7 @@ function useLayerImplementation( const el = e.currentTarget as HTMLElement | null; if (toggleEvent.newState === 'closed' && isOpenRef.current && el != null) { observeBrowserHide(el); + onCloseStartRef.current?.(); } }, []); diff --git a/packages/core/src/Popover/Popover.doc.mjs b/packages/core/src/Popover/Popover.doc.mjs index 21e5b5b575acf..38f2e23ceb002 100644 --- a/packages/core/src/Popover/Popover.doc.mjs +++ b/packages/core/src/Popover/Popover.doc.mjs @@ -221,7 +221,7 @@ export const docs = { }, usage: { description: - 'A click-triggered overlay anchored to a button or trigger element. Use it for secondary actions, inline confirmations, or supplementary information that does not warrant a full dialog. For hover previews use HoverCard, for brief helper text use Tooltip.', + 'A click-triggered overlay anchored to a button or trigger element. Use it for secondary actions, inline confirmations, or supplementary information that does not warrant a full dialog. For hover previews use HoverCard, for brief helper text use Tooltip. Under a finger (a coarse primary pointer), it is presented like a native popover: it grows out of its trigger and shrinks back into it on the theme\u2019s motion tokens; with reduced motion it cross-fades, opacity only, in 200 ms or less.', bestPractices: [ { guidance: true, @@ -439,7 +439,7 @@ export const docsZh = { }, usage: { description: - 'A click-triggered overlay anchored to a button or trigger element. Use it for secondary actions, inline confirmations, or supplementary information that does not warrant a full dialog. For hover previews use HoverCard, for brief helper text use Tooltip.', + 'A click-triggered overlay anchored to a button or trigger element. Use it for secondary actions, inline confirmations, or supplementary information that does not warrant a full dialog. For hover previews use HoverCard, for brief helper text use Tooltip. Under a finger (a coarse primary pointer), it is presented like a native popover: it grows out of its trigger and shrinks back into it on the theme\u2019s motion tokens; with reduced motion it cross-fades, opacity only, in 200 ms or less.', bestPractices: [ { guidance: true, @@ -512,7 +512,7 @@ export const docsDense = { 'Click-triggered popover displaying interactive content anchored to trigger element; implements button+dialog ARIA pattern.', usage: { description: - 'A click-triggered overlay anchored to a button or trigger element. Use it for secondary actions, inline confirmations, or supplementary information that does not warrant a full dialog. For hover previews use HoverCard, for brief helper text use Tooltip.', + 'A click-triggered overlay anchored to a button or trigger element. Use it for secondary actions, inline confirmations, or supplementary information that does not warrant a full dialog. For hover previews use HoverCard, for brief helper text use Tooltip. Under a finger (a coarse primary pointer), it is presented like a native popover: it grows out of its trigger and shrinks back into it on the theme\u2019s motion tokens; with reduced motion it cross-fades, opacity only, in 200 ms or less.', bestPractices: [ { guidance: true, diff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsx index 5c3e24039a519..94ae18fa3ebf0 100644 --- a/packages/core/src/Popover/Popover.test.tsx +++ b/packages/core/src/Popover/Popover.test.tsx @@ -1550,6 +1550,122 @@ describe('Popover', () => { }); }); +describe('Popover touch presentation', () => { + interface RecordedAnimation { + target: Element; + keyframes: Keyframe[]; + cancelled: boolean; + } + let recorded: RecordedAnimation[] = []; + let isCoarse = true; + const originalMatchMedia = window.matchMedia; + const originalShow = HTMLElement.prototype.showPopover; + const originalHide = HTMLElement.prototype.hidePopover; + + beforeAll(() => { + // The shared resolver reads the primary pointer (one touch model on every + // touch device); Reduce Motion is off. + window.matchMedia = (query: string) => ({ + matches: query.includes('pointer: coarse') ? isCoarse : false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + }); + // The browser announces a close with `beforetoggle` while the popover is + // still shown, then hides it. + HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) { + const before = new Event('beforetoggle'); + Object.defineProperty(before, 'newState', {value: 'closed'}); + this.dispatchEvent(before); + popoverOpenState.set(this, false); + const event = new Event('toggle'); + Object.defineProperty(event, 'newState', {value: 'closed'}); + this.dispatchEvent(event); + }); + HTMLElement.prototype.animate = function (keyframes) { + const animation = { + target: this, + keyframes: keyframes as Keyframe[], + cancelled: false, + // Started at once, as the browser commits it (the animator holds a + // curve's start until it has one). + startTime: performance.now() as number | null, + finished: new Promise(() => {}), + cancel() { + this.cancelled = true; + }, + }; + recorded.push(animation); + return animation as unknown as Animation; + }; + }); + + afterAll(() => { + window.matchMedia = originalMatchMedia; + HTMLElement.prototype.showPopover = originalShow; + HTMLElement.prototype.hidePopover = originalHide; + Reflect.deleteProperty(HTMLElement.prototype, 'animate'); + }); + + const open = () => { + recorded = []; + render( + Filters} label="Filters"> + + , + ); + fireEvent.click(screen.getByRole('button', {name: 'Filter'})); + const layer = screen + .getByRole('dialog', {name: 'Filters', hidden: true}) + .closest('[popover]'); + expect(layer).not.toBeNull(); + return layer!; + }; + + it('under a finger, grows the popover out of its trigger in place of the layer\u2019s entrance', () => { + isCoarse = true; + const layer = open(); + expect(layer.style.getPropertyValue('animation-name')).toBe('none'); + expect(layer.style.getPropertyValue('transform-origin')).not.toBe(''); + const scale = recorded.find( + animation => + animation.target === layer && 'scale' in animation.keyframes[0], + ); + expect(scale).toBeDefined(); + expect(String(scale!.keyframes[0].scale).split(' ')[0]).toBe('0.01'); + }); + + it('under a finger, shrinks back into its trigger on a copy that outlives the close', () => { + isCoarse = true; + const layer = open(); + fireEvent.click(screen.getByRole('button', {name: 'Filter'})); + const copy = layer.parentElement!.querySelector( + '[data-astryx-popover-exit]', + ); + expect(copy).not.toBeNull(); + expect(copy!.getAttribute('aria-hidden')).toBe('true'); + expect(copy!.hasAttribute('inert')).toBe(true); + }); + + it('under a mouse, keeps the layer\u2019s own entrance, plays nothing and closes at once', () => { + isCoarse = false; + expect(window.matchMedia('(pointer: coarse)').matches).toBe(false); + const layer = open(); + expect(layer.style.getPropertyValue('animation-name')).toBe(''); + expect(recorded.filter(animation => animation.target === layer)).toEqual( + [], + ); + fireEvent.click(screen.getByRole('button', {name: 'Filter'})); + expect( + layer.parentElement!.querySelector('[data-astryx-popover-exit]'), + ).toBeNull(); + }); +}); + describe('Popover focus region (DEC-9)', () => { function Page({isModal}: {isModal: boolean}) { return ( diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsx index 5f02abb63d829..ee7604d96bfc3 100644 --- a/packages/core/src/Popover/Popover.tsx +++ b/packages/core/src/Popover/Popover.tsx @@ -4,10 +4,17 @@ /** * @file Popover.tsx - * @input Uses React layout measurement and the usePopover hook + * @input Uses React layout measurement, the usePopover hook and the touch + * presentation's surface motion * @output Exports Popover with conditional overflow and content-first focus above the layer runtime's viewport fit * @position Layer component; declarative wrapper around usePopover hook * + * Under a finger, the popover grows out of its anchor and shrinks back into + * it, as a UIKit popover does. The shared touch resolver's coarse primary + * pointer decides it, with one touch model on every touch device. The motion + * plays the theme's duration and easing tokens (popoverSurfaceMotion.ts). A + * fine primary pointer keeps the layer's own entrance. + * * For hover-triggered overlays, use HoverCard instead. * * `presentation` chooses the surface, with the vocabulary DropdownMenu and @@ -20,6 +27,8 @@ * * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/Popover/Popover.test.tsx + * - /packages/core/src/Popover/PopoverTouch.ts (its touch layer) + * - /packages/core/src/Popover/usePopoverSurfaceMotion.ts * - /packages/core/src/Popover/index.ts * - /packages/core/src/Popover/PopoverPresentation.test.tsx * - /apps/storybook/stories/Popover.stories.tsx @@ -49,7 +58,8 @@ import {useThemeDefinition} from '../theme/useTheme'; import * as stylex from '@stylexjs/stylex'; import {devWarn} from '../utils/devWarning'; import type {BaseProps} from '../BaseProps'; -import {FALLBACK_CLOSE_SELECTOR, usePopover} from './usePopover'; +import {FALLBACK_CLOSE_SELECTOR, usePopoverInternal} from './usePopover'; +import {usePopoverSurfaceMotion} from './PopoverTouch'; import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector'; import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer'; import {layerAnimations} from '../Layer/layerAnimations.stylex'; @@ -530,12 +540,20 @@ export function Popover({ const measurementFrameRef = useRef<{id: number; view: Window} | null>(null); const [hasOverflow, setHasOverflow] = useState(false); const isControlled = isOpen !== undefined; + // The element the popover is anchored to, whichever way it was attached: + // the touch presentation grows the popover out of it. + const anchorElementRef = useRef(null); + const surfaceMotion = usePopoverSurfaceMotion(); + // Runs as the popover opens, before it paints; set once `usePopover` has + // returned the surface it presents. + const presentSurfaceRef = useRef<() => void>(() => {}); // The bottom-sheet presentation: the surface it resolves to now, and // whether the sheet is the surface that is open. const resolvedPresentation = usePresentationSurface(presentation); const [isSheetOpenState, setIsSheetOpenState] = useState(false); const handlePopoverShow = useCallback(() => { + presentSurfaceRef.current(); onOpenChange?.(true); }, [onOpenChange]); @@ -543,7 +561,7 @@ export function Popover({ onOpenChange?.(false); }, [onOpenChange]); - const popover = usePopover({ + const popover = usePopoverInternal({ dialogLabel: label, role, isModal, @@ -568,8 +586,18 @@ export function Popover({ style, onShow: handlePopoverShow, onHide: handlePopoverHide, + onCloseStart: surfaceMotion.closeStart, }); + const {contentRef: surfaceRef} = popover; + // The layer's show handler calls this as the popover opens. It reads the + // surface and the anchor when it runs, so a render-time store is safe. + presentSurfaceRef.current = () => { + surfaceMotion.present( + surfaceRef.current?.closest('[popover]') ?? null, + anchorElementRef.current, + ); + }; // A controlled popover opens on the surface its presentation resolves to // as it opens, and keeps that surface until it closes: a phone rotated past // the compact width while the sheet is open keeps its sheet. @@ -806,6 +834,7 @@ export function Popover({ const setRenderTrigger = useCallback( (element: HTMLElement | null) => { renderTriggerRef.current = element; + anchorElementRef.current = element; popover.triggerRef(element); }, [popover], @@ -929,12 +958,14 @@ export function Popover({ } // Set up anchor positioning on the anchorRef element itself + anchorElementRef.current = el; popover.triggerRef(el); // Attach handlers + ARIA to the button const detach = attachTrigger(button); return () => { + anchorElementRef.current = null; popover.triggerRef(null); detach(); }; @@ -957,6 +988,7 @@ export function Popover({ // Use the wrapper as the CSS anchor — it doesn't receive pressed-state // transforms, so the anchor position stays stable. + anchorElementRef.current = wrapper; popover.triggerRef(wrapper); // Find the button inside the wrapper @@ -975,6 +1007,7 @@ export function Popover({ const detach = attachTrigger(button); return () => { + anchorElementRef.current = null; popover.triggerRef(null); detach(); }; diff --git a/packages/core/src/Popover/PopoverTouch.ts b/packages/core/src/Popover/PopoverTouch.ts new file mode 100644 index 0000000000000..1ccc20120d677 --- /dev/null +++ b/packages/core/src/Popover/PopoverTouch.ts @@ -0,0 +1,20 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file PopoverTouch.ts + * @input usePopoverSurfaceMotion.ts (the touch presentation's grow and + * shrink) + * @output Popover's touch layer: usePopoverSurfaceMotion + * @position The one module Popover imports touch-only code through, and its + * only import site is Popover.tsx. The mouse paths stay outside it. + * + * A pointer page carries this touch-only code. Components import the shared + * touch modules statically, with no install call, so this module's cost is + * in every Popover import. + * + * SYNC: When modified, keep every touch-only import of Popover.tsx here. + */ + +export {usePopoverSurfaceMotion} from './usePopoverSurfaceMotion'; diff --git a/packages/core/src/Popover/popoverSurfaceFrame.test.ts b/packages/core/src/Popover/popoverSurfaceFrame.test.ts new file mode 100644 index 0000000000000..2ef433d98b64f --- /dev/null +++ b/packages/core/src/Popover/popoverSurfaceFrame.test.ts @@ -0,0 +1,70 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file popoverSurfaceFrame.test.ts + * @input vitest, the popover's timing tokens, its UIKit table and the + * Storybook theme's motion scale + * @output Checks that the growth plays the Storybook theme's duration step + * nearest iOS's measured growth, naming both numbers. It also checks that + * the shrink keeps the exit every overlay shares. + * @position Testing; the motion that plays these tokens is checked in + * popoverSurfaceMotion.test.ts + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import {describe, expect, it} from 'vitest'; +import {popover} from '../motion/uikit'; +import {expandMotionScale} from '../theme/expandMotionScale'; +import { + POPOVER_ENTRANCE_TOKENS, + POPOVER_EXIT_TOKENS, +} from './popoverSurfaceFrame'; + +// The Storybook theme (neutral) declares its motion scale in its own source. +const NEUTRAL_SOURCE = fs.readFileSync( + path.resolve(__dirname, '../../../themes/neutral/src/neutralTheme.ts'), + 'utf8', +); +const SCALE = + /motion: \{fast: (\d+), medium: (\d+), slow: (\d+), ratio: ([\d.]+)\}/.exec( + NEUTRAL_SOURCE, + ); +if (SCALE == null) { + throw new Error('the neutral theme declares no motion scale'); +} +const NEUTRAL = expandMotionScale({ + fast: Number(SCALE[1]), + medium: Number(SCALE[2]), + slow: Number(SCALE[3]), + ratio: Number(SCALE[4]), +}); + +/** The neutral theme's duration token whose value is nearest `ms`. */ +function nearestNeutral(ms: number): string { + const gap = (value: string) => Math.abs(Number.parseFloat(value) - ms); + const [[token]] = Object.entries(NEUTRAL) + .filter(([name]) => name.startsWith('--duration-')) + .sort(([, a], [, b]) => gap(a) - gap(b)); + return token; +} + +describe('popover timing tokens', () => { + it('grows on --duration-medium-min, 225 ms in the Storybook theme, the step nearest iOS\u2019s 206 ms growth', () => { + expect(popover.growMs).toBe(206); + expect(NEUTRAL['--duration-medium-min']).toBe('225ms'); + expect(nearestNeutral(popover.growMs)).toBe('--duration-medium-min'); + expect(POPOVER_ENTRANCE_TOKENS).toEqual({ + duration: '--duration-medium-min', + easing: '--ease-entrance', + }); + }); + + it('shrinks on the theme\u2019s exit duration and easing, which every overlay shares, keeping iOS\u2019s 249 ms shrink as a reference', () => { + expect(popover.shrinkMs).toBe(249); + expect(POPOVER_EXIT_TOKENS).toEqual({ + duration: '--duration-exit', + easing: '--ease-exit', + }); + }); +}); diff --git a/packages/core/src/Popover/popoverSurfaceFrame.ts b/packages/core/src/Popover/popoverSurfaceFrame.ts new file mode 100644 index 0000000000000..a7594e0c79d1a --- /dev/null +++ b/packages/core/src/Popover/popoverSurfaceFrame.ts @@ -0,0 +1,167 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file popoverSurfaceFrame.ts + * @input The popover's box and its source's, and UIKit's popover values + * @output Exports `popoverCollapsedState`, where the popover grows from and + * the shape it starts as. Exports `popoverFrame`, the surface at a progress + * of the growth. Also exports the theme tokens that time the motion, the + * frame helpers, and their types. + * @position Internal to Popover: the pure geometry of the touch + * presentation, with no DOM and no animator. A browser proof imports it on + * its own, and popoverSurfaceMotion.ts plays it. + * + * SYNC: When modified, update: + * - /packages/core/src/Popover/popoverSurfaceMotion.ts + * - /packages/core/src/Popover/popoverSurfaceMotion.test.ts + */ + +import type {LayerExitBox} from '../Layer/layerExitCopy'; +import type {ThemeTimingTokens} from '../motion/themeTiming'; +import {popover} from '../motion/uikit/popover'; + +/** + * The growth plays `--duration-medium-min`, which in the Storybook theme is + * the step nearest iOS's measured growth (`popover.growMs`), with the + * entrance easing. A tap opens the popover, and a tap has no velocity, so no + * spring plays. + */ +export const POPOVER_ENTRANCE_TOKENS: ThemeTimingTokens = { + duration: '--duration-medium-min', + easing: '--ease-entrance', +}; + +/** + * The shrink plays the theme's exit duration and easing, which every overlay + * shares; iOS's measured shrink (`popover.shrinkMs`) is only a reference. A + * theme that sets no exit duration gets the fast duration, which is the exit + * duration's default. + */ +export const POPOVER_EXIT_TOKENS: ThemeTimingTokens = { + duration: '--duration-exit', + easing: '--ease-exit', +}; + +/** A box in viewport px. */ +export type PopoverSurfaceRect = LayerExitBox; + +/** Where the popover sits and what it hangs off, in viewport px. */ +export interface PopoverSurfaceGeometry { + /** The layer element's border box once positioned, at full size. */ + surface: PopoverSurfaceRect; + /** The box of the source the popover is anchored to. */ + source: PopoverSurfaceRect; +} + +/** Where the popover grows from, and the shape it starts as. */ +export interface PopoverCollapsedState { + /** Transform origin, px from the surface's top-left corner. */ + originX: number; + originY: number; + /** + * The scale axis that also carries the length: the axis pointing away + * from the source (`y` for a popover above or below it). + */ + axis: 'x' | 'y'; + /** The uniform scale it grows from. */ + scale: number; + /** The share of its own length along `axis` it grows from, at most 1. */ + length: number; +} + +/** The transform and opacity of the surface. */ +export interface PopoverFrame { + scaleX: number; + scaleY: number; + opacity: number; +} + +/** How far the edges may sit apart and still count as touching, px. */ +const EDGE_TOLERANCE = 1; + +const clamp = (value: number, min: number, max: number) => + Math.min(Math.max(value, min), max); + +/** + * Where the popover meets its source, and the shape it grows from. The point + * is the middle of the source on the popover's edge facing it (the arrow's + * tip), kept on that edge. + */ +export function popoverCollapsedState({ + surface, + source, +}: PopoverSurfaceGeometry): PopoverCollapsedState { + const gaps = { + below: surface.top - (source.top + source.height), + above: source.top - (surface.top + surface.height), + right: surface.left - (source.left + source.width), + left: source.left - (surface.left + surface.width), + }; + // The side with the widest gap is the one the popover was placed on. A + // popover that overlaps its source grows from below, as the default. + let side: keyof typeof gaps = 'below'; + for (const candidate of ['above', 'right', 'left'] as const) { + if (gaps[candidate] > gaps[side]) { + side = candidate; + } + } + if (gaps[side] < -EDGE_TOLERANCE) { + side = 'below'; + } + const centerX = clamp( + source.left + source.width / 2 - surface.left, + 0, + surface.width, + ); + const centerY = clamp( + source.top + source.height / 2 - surface.top, + 0, + surface.height, + ); + const vertical = side === 'below' || side === 'above'; + const fullLength = vertical ? surface.height : surface.width; + return { + originX: vertical ? centerX : side === 'right' ? 0 : surface.width, + originY: vertical ? (side === 'below' ? 0 : surface.height) : centerY, + axis: vertical ? 'y' : 'x', + scale: popover.collapsedScale, + length: + fullLength > 0 ? Math.min(1, popover.collapsedLengthPx / fullLength) : 1, + }; +} + +export interface SurfaceState { + scale: number; + /** Share of the full length along the axis. */ + length: number; + opacity: number; +} + +export const PRESENTED: SurfaceState = {scale: 1, length: 1, opacity: 1}; + +export function frameOf(state: SurfaceState, axis: 'x' | 'y'): PopoverFrame { + const along = state.scale * state.length; + return { + scaleX: axis === 'x' ? along : state.scale, + scaleY: axis === 'y' ? along : state.scale, + opacity: state.opacity, + }; +} + +/** + * The surface at progress `p` of the growth: the frame UIKit's popover view + * shows on its path at that progress. + */ +export function popoverFrame( + state: PopoverCollapsedState, + p: number, +): PopoverFrame { + return frameOf( + { + scale: state.scale + (1 - state.scale) * p, + length: state.length + (1 - state.length) * p, + opacity: p, + }, + state.axis, + ); +} diff --git a/packages/core/src/Popover/popoverSurfaceMotion.test.ts b/packages/core/src/Popover/popoverSurfaceMotion.test.ts new file mode 100644 index 0000000000000..7b6a9a88384b5 --- /dev/null +++ b/packages/core/src/Popover/popoverSurfaceMotion.test.ts @@ -0,0 +1,602 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file popoverSurfaceMotion.test.ts + * @input vitest (jsdom), popoverSurfaceMotion, the theme's duration and + * easing defaults, a recording stand-in for Element.animate + * @output Checks where the popover grows from on each side of its source, + * and that every frame stays on UIKit's measured path. Checks that the + * growth plays the entrance tokens and the shrink the exit tokens. Covers + * present, dismiss, turn-back, reset and Reduce Motion. + * @position Testing; the curves on a real compositor are proven in + * __tests__/PopoverTouchMotion.interaction.browser.spec.ts + */ + +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {cubicBezier} from '../motion/bezier'; +import {parseCssEasing, parseMotionRoleValue} from '../motion/roles'; +import {popover, timing} from '../motion/uikit'; +import {findPopoverExitCopy} from '../privateAttributes/popoverExit.stylex'; +import {durationDefaults, easeDefaults} from '../theme/tokens.stylex'; +import { + createPopoverSurfaceMotion, + popoverCollapsedState, + popoverFrame, + type PopoverSurfaceGeometry, +} from './popoverSurfaceMotion'; + +/** A motion's duration (ms) and eased progress, as CSS gives them. */ +function cssTiming(duration: string, easing: string) { + const ms = parseMotionRoleValue('duration', duration); + const points = parseCssEasing(easing); + if (ms == null || points == null) { + throw new Error(`not a playable timing: ${duration} ${easing}`); + } + const ease = cubicBezier(points); + return {ms, at: (tMs: number) => (tMs >= ms ? 1 : ease(tMs / ms))}; +} + +// The theme's defaults, which a page with no theme scope plays. +const ENTRANCE = cssTiming( + durationDefaults['--duration-medium-min'], + easeDefaults['--ease-entrance'], +); +const EXIT = cssTiming( + durationDefaults['--duration-fast'], + easeDefaults['--ease-exit'], +); + +// UIKit on iOS 26.2 (batch 36): a 120 × 44 button at (141, 160). It presents +// a 320 × 253 popover below it at (41, 204), centred on it. +const GEOMETRY: PopoverSurfaceGeometry = { + surface: {left: 41, top: 204, width: 320, height: 253}, + source: {left: 141, top: 160, width: 120, height: 44}, +}; + +/** The visual box of the surface scaled by (sx, sy) about the origin. */ +function visualBox( + geometry: PopoverSurfaceGeometry, + origin: {x: number; y: number}, + sx: number, + sy: number, +) { + const {left, top, width, height} = geometry.surface; + return { + left: left + origin.x * (1 - sx), + top: top + origin.y * (1 - sy), + width: width * sx, + height: height * sy, + }; +} + +const scaleOf = (frame: Keyframe) => + String(frame.scale) + .split(' ') + .map(value => Number(value)); + +/** + * The person's settings, through `matchMedia` as the animator reads them: no + * option overrides them. + */ +function stubMedia(reduced: boolean, coarse: boolean) { + vi.stubGlobal('matchMedia', (query: string) => ({ + matches: query.includes('prefers-reduced-motion') + ? reduced + : query.includes('pointer: coarse') + ? coarse + : false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + })); +} + +describe('popoverCollapsedState', () => { + it('grows a popover below its source out of the source\u2019s bottom centre', () => { + const state = popoverCollapsedState(GEOMETRY); + expect(state.originX).toBe(160); + expect(state.originY).toBe(0); + expect(state.axis).toBe('y'); + expect(state.scale).toBe(popover.collapsedScale); + expect(state.length).toBeCloseTo(popover.collapsedLengthPx / 253, 12); + }); + + it('turns the same motion toward a source above or beside the popover', () => { + const above = popoverCollapsedState({ + surface: {left: 41, top: 100, width: 320, height: 200}, + source: {left: 141, top: 310, width: 120, height: 44}, + }); + expect([above.originX, above.originY, above.axis]).toEqual([160, 200, 'y']); + const right = popoverCollapsedState({ + surface: {left: 200, top: 100, width: 180, height: 240}, + source: {left: 20, top: 150, width: 160, height: 40}, + }); + expect([right.originX, right.originY, right.axis]).toEqual([0, 70, 'x']); + expect(right.length).toBeCloseTo(popover.collapsedLengthPx / 180, 12); + const left = popoverCollapsedState({ + surface: {left: 10, top: 100, width: 180, height: 240}, + source: {left: 200, top: 150, width: 160, height: 40}, + }); + expect([left.originX, left.originY, left.axis]).toEqual([180, 70, 'x']); + }); + + it('keeps the point on the popover when its source is wider than it, and never grows a short popover', () => { + const state = popoverCollapsedState({ + surface: {left: 300, top: 60, width: 90, height: 80}, + source: {left: 0, top: 10, width: 402, height: 44}, + }); + // The source's centre (201) lies left of the popover: its nearest point. + expect(state.originX).toBe(0); + expect(state.originY).toBe(0); + // Shorter than the 100 pt it would grow from: the length does not move. + expect(state.length).toBe(1); + }); +}); + +describe('popoverFrame', () => { + it('keeps every frame on UIKit\u2019s path: the top on the source, the centre on its line, the length growing from 100 pt', () => { + const state = popoverCollapsedState(GEOMETRY); + // Progress past 1 is an easing's overshoot; the path extends straight. + for (const p of [0, 0.1, 0.3126, 0.5, 0.9, 1, 1.0152]) { + const frame = popoverFrame(state, p); + const box = visualBox( + GEOMETRY, + {x: state.originX, y: state.originY}, + frame.scaleX, + frame.scaleY, + ); + const scale = popover.collapsedScale + (1 - popover.collapsedScale) * p; + expect(box.top).toBeCloseTo(204, 9); + expect(box.left + box.width / 2).toBeCloseTo(201, 9); + expect(box.width).toBeCloseTo(320 * scale, 9); + expect(box.height).toBeCloseTo(scale * (100 + 153 * p), 9); + expect(frame.opacity).toBeCloseTo(p, 12); + } + }); + + it('matches the popover view\u2019s measured frames', () => { + const state = popoverCollapsedState(GEOMETRY); + // Presentation frames of the popover view, iOS 26.2 (batch 36): scale, + // then the visual width and height. + for (const [scale, width, height] of [ + [0.0865, 27.69, 9.68], + [0.3195, 102.25, 47.24], + [0.6664, 213.26, 134.25], + [0.9632, 308.22, 238.2], + [1.015, 324.79, 259.14], + ]) { + const p = (scale - popover.collapsedScale) / (1 - popover.collapsedScale); + const frame = popoverFrame(state, p); + expect(320 * frame.scaleX).toBeCloseTo(width, 1); + expect(253 * frame.scaleY).toBeCloseTo(height, 1); + } + }); +}); + +interface Recorded { + target: Element; + keyframes: Keyframe[]; + options: KeyframeAnimationOptions; + cancelled: boolean; +} + +describe('createPopoverSurfaceMotion', () => { + let clock = 1000; + let recorded: Recorded[] = []; + + beforeEach(() => { + clock = 1000; + recorded = []; + vi.useFakeTimers(); + HTMLElement.prototype.animate = function (keyframes, options) { + const animation = { + target: this, + keyframes: keyframes as Keyframe[], + options: options as KeyframeAnimationOptions, + cancelled: false, + // The browser starts it at once: its first frame is committed at the + // call (the animator holds a curve's start until it has one). + startTime: clock as number | null, + finished: new Promise(() => {}), + cancel() { + this.cancelled = true; + }, + }; + recorded.push(animation); + return animation as unknown as Animation; + }; + }); + + // jsdom has no layout: the dismissal's copy stands where its inline box + // says. + const originalRect = HTMLElement.prototype.getBoundingClientRect; + beforeEach(() => { + HTMLElement.prototype.getBoundingClientRect = function (this: HTMLElement) { + if (findPopoverExitCopy(this.parentElement ?? document) !== this) { + return originalRect.call(this); + } + const left = parseFloat(this.style.left); + const top = parseFloat(this.style.top); + const width = parseFloat(this.style.width); + const height = parseFloat(this.style.height); + return { + left, + top, + width, + height, + x: left, + y: top, + right: left + width, + bottom: top + height, + toJSON: () => ({}), + }; + }; + }); + + afterEach(() => { + Reflect.deleteProperty(HTMLElement.prototype, 'animate'); + HTMLElement.prototype.getBoundingClientRect = originalRect; + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + const create = (reducedMotion = false) => { + const host = document.createElement('section'); + document.body.appendChild(host); + const element = document.createElement('div'); + element.id = 'popover-layer'; + element.setAttribute('popover', 'auto'); + element.innerHTML = + ''; + // jsdom has no layout: the surface stands where the open measured it. + element.getBoundingClientRect = () => ({ + ...GEOMETRY.surface, + x: GEOMETRY.surface.left, + y: GEOMETRY.surface.top, + right: GEOMETRY.surface.left + GEOMETRY.surface.width, + bottom: GEOMETRY.surface.top + GEOMETRY.surface.height, + toJSON: () => ({}), + }); + host.appendChild(element); + // The touch presentation runs under a coarse pointer, where Reduce + // Motion cross-fades. + stubMedia(reducedMotion, true); + const motion = createPopoverSurfaceMotion(element, {now: () => clock}); + return {element, motion}; + }; + + const live = (property: string, target?: Element) => + recorded.filter( + animation => + !animation.cancelled && + (target == null || animation.target === target) && + animation.keyframes.some(frame => property in frame), + ); + const copyOf = (element: HTMLElement) => + findPopoverExitCopy(element.parentElement!); + + /** + * Checks each keyframe of `animation` against the path from collapsed to + * presented at `progress(t ms)`, and returns the time the motion ends. + */ + const expectPath = ( + animation: Recorded, + state: ReturnType, + progress: (tMs: number) => number, + ) => { + const duration = Number(animation.options.duration); + let endMs = 0; + let peak = 0; + let previous: number[] | null = null; + for (const frame of animation.keyframes) { + const tMs = (frame.offset as number) * duration; + const expected = popoverFrame(state, progress(tMs)); + const scale = scaleOf(frame); + expect(scale[0]).toBeCloseTo(expected.scaleX, 2); + expect(scale[1]).toBeCloseTo(expected.scaleY, 2); + peak = Math.max(peak, scale[0]); + if (previous == null || previous.some((v, i) => v !== scale[i])) { + endMs = tMs; + } + previous = scale; + } + return {endMs, peak}; + }; + + it('grows the popover out of its source on the theme\u2019s entrance tokens, without the layer\u2019s CSS entrance', () => { + const {element, motion} = create(); + // The read happens with the CSS entrance already off and no scale left. + const measure = vi.fn(() => { + expect(element.style.getPropertyValue('animation-name')).toBe('none'); + return GEOMETRY; + }); + motion.enter(measure); + expect(measure).toHaveBeenCalledTimes(1); + const state = popoverCollapsedState(GEOMETRY); + expect(element.style.getPropertyValue('animation-name')).toBe('none'); + expect(element.style.getPropertyValue('transform-origin')).toBe( + `${state.originX}px ${state.originY}px`, + ); + const [scaleAnimation] = live('scale'); + const first = scaleOf(scaleAnimation.keyframes[0]); + expect(first[0]).toBeCloseTo(state.scale, 4); + expect(first[1]).toBeCloseTo(state.scale * state.length, 4); + expect(scaleOf(scaleAnimation.keyframes.at(-1)!)).toEqual([1, 1]); + // Every keyframe is the measured path at the entrance easing's progress, + // and the growth ends with the entrance duration: no spring, no bounce. + const {endMs, peak} = expectPath(scaleAnimation, state, ENTRANCE.at); + expect(endMs).toBeLessThanOrEqual(ENTRANCE.ms + 1); + expect(endMs).toBeGreaterThan(ENTRANCE.ms * 0.8); + expect(peak).toBeLessThanOrEqual(1); + const [opacityAnimation] = live('opacity'); + expect(Number(opacityAnimation.keyframes[0].opacity)).toBe(0); + expect(Number(opacityAnimation.keyframes.at(-1)!.opacity)).toBe(1); + }); + + it('plays the dismissal on a static copy of the popover, back into its source on the theme\u2019s exit tokens, removed when it ends', async () => { + const {element, motion} = create(); + motion.enter(() => GEOMETRY); + clock += 1000; + vi.advanceTimersByTime(1000); + motion.exit(); + const copy = copyOf(element); + expect(copy).not.toBeNull(); + // Beside the layer (same inherited theme), where it stands, out of reach. + expect(copy!.previousElementSibling).toBe(element); + expect(copy!.getAttribute('aria-hidden')).toBe('true'); + expect(copy!.hasAttribute('inert')).toBe(true); + // In the top layer, as the popover was (the layer runtime's exit copy). + expect(copy!.getAttribute('popover')).toBe('manual'); + expect(copy!.querySelectorAll('[id]')).toHaveLength(0); + expect(copy!.style.getPropertyValue('left')).toBe('41px'); + expect(copy!.style.getPropertyValue('top')).toBe('204px'); + const state = popoverCollapsedState(GEOMETRY); + expect(copy!.style.getPropertyValue('transform-origin')).toBe( + `${state.originX}px ${state.originY}px`, + ); + // The copy shrinks into the point on the exit easing, in the exit + // duration (the fast duration while the theme sets none), and fades. + const [scaleAnimation] = live('scale', copy!); + const last = scaleOf(scaleAnimation.keyframes.at(-1)!); + expect(last[0]).toBeCloseTo(state.scale, 4); + expect(last[1]).toBeCloseTo(state.scale * state.length, 4); + const {endMs} = expectPath(scaleAnimation, state, t => 1 - EXIT.at(t)); + expect(endMs).toBeLessThanOrEqual(EXIT.ms + 1); + expect(endMs).toBeGreaterThan(EXIT.ms * 0.8); + const [opacityAnimation] = live('opacity', copy!); + expect(Number(opacityAnimation.keyframes[0].opacity)).toBe(1); + expect(Number(opacityAnimation.keyframes.at(-1)!.opacity)).toBe(0); + // The layer itself is left at rest for its next presentation (an + // identity at rest leaves no inline value). + expect(element.style.getPropertyValue('scale')).toMatch(/^(1( 1)?)?$/); + expect(element.style.getPropertyValue('opacity')).toMatch(/^(1)?$/); + // Gone once the shrink ends. + clock += 2000; + vi.advanceTimersByTime(2000); + return Promise.resolve().then(() => { + expect(copyOf(element)).toBeNull(); + }); + }); + + it('reads the theme\u2019s tokens where the popover is: the entrance duration and easing time the growth, the exit duration and easing the shrink', () => { + const {element, motion} = create(); + element.style.setProperty('--duration-medium-min', '400ms'); + element.style.setProperty('--ease-entrance', 'linear'); + element.style.setProperty('--duration-exit', '0.3s'); + element.style.setProperty('--ease-exit', 'ease-in'); + const state = popoverCollapsedState(GEOMETRY); + motion.enter(() => GEOMETRY); + const growth = expectPath( + live('scale', element)[0], + state, + cssTiming('400ms', 'linear').at, + ); + expect(growth.endMs).toBeGreaterThan(320); + expect(growth.endMs).toBeLessThanOrEqual(401); + clock += 1000; + vi.advanceTimersByTime(1000); + motion.exit(); + const shrinkTiming = cssTiming('300ms', 'ease-in'); + const shrink = expectPath( + live('scale', copyOf(element)!)[0], + state, + t => 1 - shrinkTiming.at(t), + ); + expect(shrink.endMs).toBeGreaterThan(240); + expect(shrink.endMs).toBeLessThanOrEqual(301); + }); + + it('a theme that sets no exit duration shrinks the popover in its fast duration', () => { + const {element, motion} = create(); + element.style.setProperty('--duration-fast', '250ms'); + const state = popoverCollapsedState(GEOMETRY); + motion.enter(() => GEOMETRY); + clock += 1000; + vi.advanceTimersByTime(1000); + motion.exit(); + const fast = cssTiming('250ms', easeDefaults['--ease-exit']); + const shrink = expectPath( + live('scale', copyOf(element)!)[0], + state, + t => 1 - fast.at(t), + ); + expect(shrink.endMs).toBeGreaterThan(200); + expect(shrink.endMs).toBeLessThanOrEqual(251); + }); + + it('dismissed during the growth, shrinks from the frame on screen on the exit tokens', () => { + const {element, motion} = create(); + motion.enter(() => GEOMETRY); + clock += ENTRANCE.ms / 2; + vi.advanceTimersByTime(ENTRANCE.ms / 2); + motion.exit(); + const state = popoverCollapsedState(GEOMETRY); + const [scaleAnimation] = live('scale', copyOf(element)!); + const first = scaleOf(scaleAnimation.keyframes[0]); + const onScreen = popoverFrame(state, ENTRANCE.at(ENTRANCE.ms / 2)); + expect(first[0]).toBeCloseTo(onScreen.scaleX, 2); + expect(first[1]).toBeCloseTo(onScreen.scaleY, 2); + expect(first[0]).toBeLessThan(1); + const last = scaleOf(scaleAnimation.keyframes.at(-1)!); + expect(last[0]).toBeCloseTo(state.scale, 4); + }); + + it('lets the hidden layer go of its compositing layer as the dismissal starts, so no style write reaches it during the dismissal', async () => { + const {element, motion} = create(); + motion.enter(() => GEOMETRY); + // Dismissed about 100 ms after the presentation's curve ended, while the + // animator still keeps the element promoted (its PROMOTION_LINGER_MS). + clock += 600; + vi.advanceTimersByTime(600); + motion.exit(); + // The exit's own task. + await Promise.resolve(); + const writes: string[] = []; + const observer = new MutationObserver(records => { + for (const record of records) { + writes.push(record.oldValue ?? ''); + } + }); + observer.observe(element, { + attributes: true, + attributeFilter: ['style'], + attributeOldValue: true, + }); + // The dismissal's whole run, and any linger past it. + for (let ms = 0; ms < 1200; ms += 50) { + clock += 50; + vi.advanceTimersByTime(50); + await Promise.resolve(); + } + writes.push(...observer.takeRecords().map(record => record.oldValue ?? '')); + observer.disconnect(); + expect(writes).toEqual([]); + expect(element.style.getPropertyValue('will-change')).toBe(''); + }); + + it('presented again during the dismissal, grows back from the frame on screen about the same point', () => { + const {element, motion} = create(); + motion.enter(() => GEOMETRY); + clock += 1000; + vi.advanceTimersByTime(1000); + motion.exit(); + const origin = element.style.getPropertyValue('transform-origin'); + clock += 80; + const measure = vi.fn(() => GEOMETRY); + motion.enter(measure); + // No new measurement and no new pivot; the copy is gone. + expect(measure).not.toHaveBeenCalled(); + expect(element.style.getPropertyValue('transform-origin')).toBe(origin); + expect(copyOf(element)).toBeNull(); + const first = scaleOf(live('scale', element).at(-1)!.keyframes[0]); + const state = popoverCollapsedState(GEOMETRY); + // Mid-dismissal: smaller than the presented popover, larger than the + // point, with the length between its two values. + expect(first[0]).toBeLessThan(1); + expect(first[0]).toBeGreaterThan(state.scale); + const length = first[1] / first[0]; + expect(length).toBeLessThan(1); + expect(length).toBeGreaterThan(state.length); + }); + + it('a dismissal with no touch presentation before it does nothing', () => { + const {element, motion} = create(); + motion.exit(); + expect(recorded).toHaveLength(0); + expect(copyOf(element)).toBeNull(); + }); + + it('reset leaves the element as the component styles it', () => { + const {element, motion} = create(); + motion.enter(() => GEOMETRY); + motion.reset(); + for (const property of [ + 'scale', + 'opacity', + 'transform-origin', + 'animation-name', + ]) { + expect(element.style.getPropertyValue(property), property).toBe(''); + } + motion.exit(); + expect(copyOf(element)).toBeNull(); + }); + + it('Reduce Motion: the popover cross-fades in at its size and out where it stands, in 200 ms or less, with no spring', () => { + const {element, motion} = create(true); + motion.enter(() => GEOMETRY); + // No growth: every scale keyframe is the full size. + for (const animation of live('scale', element)) { + for (const frame of animation.keyframes) { + expect(String(frame.scale)).toMatch(/^1( 1)?$/); + } + } + const ease = cubicBezier(timing.curves.move); + // The animator holds a curve's end value to the end of a longer + // animation. The fade ends at the first keyframe after which the opacity + // stays at its target. + const fadeMs = ( + animation: { + options: KeyframeAnimationOptions; + keyframes: Keyframe[]; + }, + target: number, + ) => { + const total = Number(animation.options.duration); + let end = animation.keyframes.length - 1; + while ( + end > 0 && + Number(animation.keyframes[end - 1].opacity) === target + ) { + end -= 1; + } + return (animation.keyframes[end].offset as number) * total; + }; + const [fadeIn] = live('opacity', element); + // design:reduced-motion DR2: opacity only, 200 ms or less. + const fadeInMs = fadeMs(fadeIn, 1); + expect(fadeInMs).toBeGreaterThan(0); + expect(fadeInMs).toBeLessThanOrEqual(timing.reducedMotionCrossFadeMs + 1); + // UIKit's cross-fade curve, not a spring. + const fadeInTotal = Number(fadeIn.options.duration); + for (const frame of fadeIn.keyframes) { + const t = (frame.offset as number) * fadeInTotal; + expect(Number(frame.opacity)).toBeCloseTo( + ease(Math.min(1, t / timing.reducedMotionCrossFadeMs)), + 2, + ); + } + clock += 1000; + vi.advanceTimersByTime(1000); + motion.exit(); + const copy = copyOf(element)!; + const [fadeOut] = live('opacity', copy); + const fadeOutMs = fadeMs(fadeOut, 0); + expect(fadeOutMs).toBeGreaterThan(0); + expect(fadeOutMs).toBeLessThanOrEqual(timing.reducedMotionCrossFadeMs + 1); + expect(Number(fadeOut.keyframes[0].opacity)).toBe(1); + expect(Number(fadeOut.keyframes.at(-1)!.opacity)).toBe(0); + const fadeOutTotal = Number(fadeOut.options.duration); + for (const frame of fadeOut.keyframes) { + const t = (frame.offset as number) * fadeOutTotal; + expect(Number(frame.opacity)).toBeCloseTo( + 1 - ease(Math.min(1, t / timing.reducedMotionCrossFadeMs)), + 2, + ); + } + // The copy keeps its size while it fades (where it lands once it is out + // is the animator's business). + for (const animation of live('scale', copy)) { + const total = Number(animation.options.duration); + for (const frame of animation.keyframes) { + if ((frame.offset as number) * total < fadeOutMs - 1) { + expect(String(frame.scale)).toMatch(/^1( 1)?$/); + } + } + } + }); +}); diff --git a/packages/core/src/Popover/popoverSurfaceMotion.ts b/packages/core/src/Popover/popoverSurfaceMotion.ts new file mode 100644 index 0000000000000..600c26e567526 --- /dev/null +++ b/packages/core/src/Popover/popoverSurfaceMotion.ts @@ -0,0 +1,276 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file popoverSurfaceMotion.ts + * @input A Popover's layer element, the source it hangs off, the compositor + * animator, the theme's duration and easing tokens, and the layer + * runtime's exit copy + * @output Exports `popoverCollapsedState`, `popoverFrame` and + * `createPopoverSurfaceMotion`, the touch presentation's present and + * dismiss. + * @position Internal to Popover. Under a finger the popover grows out of its + * source and shrinks back into it, as a UIKit popover does. + * + * SYNC: When modified, update: + * - /packages/core/src/Popover/popoverSurfaceFrame.ts + * - /packages/core/src/Popover/popoverSurfaceMotion.test.ts + * - /packages/core/src/Popover/Popover.tsx + */ + +import { + createMotionEngine, + type Animator, + type AnimatorOptions, + type MotionCurve, + type MotionHandle, +} from '../motion/animator'; +import {mapProgress, mapRange} from '../motion/progress'; +import { + easedProgress, + readThemeTiming, + type ThemeTimingTokens, +} from '../motion/themeTiming'; +import {placePopoverExitCopy} from '../privateAttributes/popoverExit.stylex'; +import { + frameOf, + popoverCollapsedState, + POPOVER_ENTRANCE_TOKENS, + POPOVER_EXIT_TOKENS, + PRESENTED, + type PopoverCollapsedState, + type PopoverSurfaceGeometry, + type SurfaceState, +} from './popoverSurfaceFrame'; + +export {popoverCollapsedState, popoverFrame} from './popoverSurfaceFrame'; +export type { + PopoverCollapsedState, + PopoverFrame, + PopoverSurfaceGeometry, + PopoverSurfaceRect, +} from './popoverSurfaceFrame'; + +/** + * The curves from `from` to `to` as `progress` moves from 0 to 1. The scale + * and the length move together, so the scale along the axis is their product. + */ +function surfaceCurves( + from: SurfaceState, + to: SurfaceState, + axis: 'x' | 'y', + progress: MotionCurve, +): Record<'scaleX' | 'scaleY' | 'opacity', MotionCurve> { + // Unclamped, so an easing that overshoots carries the channels with it. + const lerp = (a: number, b: number) => + mapRange([0, 1], [a, b], {clamp: false}); + const scale = lerp(from.scale, to.scale); + const length = lerp(from.length, to.length); + const across = mapProgress(progress, scale); + const along = mapProgress(progress, p => scale(p) * length(p)); + return { + scaleX: axis === 'x' ? along : across, + scaleY: axis === 'y' ? along : across, + opacity: mapProgress(progress, lerp(from.opacity, to.opacity)), + }; +} + +/** A theme timing that does not resolve plays no motion. */ +function timingOn(element: Element, tokens: ThemeTimingTokens): MotionCurve { + return readThemeTiming(element, tokens) ?? easedProgress(0, x => x); +} + +/** What `animator` shows now, split back into scale and length. */ +function readState(animator: Animator, axis: 'x' | 'y'): SurfaceState { + const across = animator.get(axis === 'x' ? 'scaleY' : 'scaleX'); + const along = animator.get(axis === 'x' ? 'scaleX' : 'scaleY'); + return { + scale: across, + length: across > 0 ? along / across : 1, + opacity: animator.get('opacity'), + }; +} + +export interface PopoverSurfaceMotion { + /** + * The popover has just been shown in its touch presentation: grow it out + * of its source. `measure` reads the geometry; it runs with the element at + * its full size. During a dismissal, the popover grows back from where the + * dismissal has it, about the same point. + */ + enter(measure: () => PopoverSurfaceGeometry): void; + /** + * The popover is closing (its `beforetoggle` to closed, while it is still + * shown): shrink it back into its source. Does nothing unless the last + * presentation was a touch one. + */ + exit(): void; + /** + * The popover opened in a presentation that does not use this motion: + * leave the element exactly as the component styles it. + */ + reset(): void; + /** Cancels everything and restores the element. */ + dispose(): void; +} + +const MOTION_STYLE_PROPERTIES = [ + 'scale', + 'opacity', + 'transform-origin', + 'animation-name', +] as const; + +/** + * The popover is scaled about the point where it meets its source. Across + * the source's edge its scale is s = s₀ + (1 − s₀)·p. Along the axis away + * from the source it is s·f, with f = f₀ + (1 − f₀)·p, the share of its + * full length. Both follow one eased progress p, so they play as curves on + * the compositor. A dismissal during the growth, or a growth during the + * dismissal, turns back from the frame on screen. + * + * The browser hides a popover as it closes, so the dismissal plays on the + * layer runtime's exit copy, which is removed when its motion ends. + * + * Under Reduce Motion the animator's policy applies. On a coarse pointer the + * popover lands at its full size and cross-fades in, and it cross-fades out + * where it stands. + */ +export function createPopoverSurfaceMotion( + element: HTMLElement, + options: Pick = {}, +): PopoverSurfaceMotion { + const animator = createMotionEngine(element, options); + // The presentation in progress or last played; null while the popover is + // in a presentation this motion does not drive. + let collapsed: PopoverCollapsedState | null = null; + // The geometry the presentation measured. While the growth runs, the + // element's box includes a scale that only the curve knows. + let measured: PopoverSurfaceGeometry | null = null; + let presentHandle: MotionHandle | null = null; + let exiting: {copy: HTMLElement; animator: Animator} | null = null; + + const endExit = () => { + if (exiting == null) { + return; + } + exiting.animator.dispose(); + exiting.copy.remove(); + exiting = null; + }; + + const reset = () => { + collapsed = null; + measured = null; + presentHandle = null; + endExit(); + animator.set({scaleX: 1, scaleY: 1, opacity: 1}); + for (const property of MOTION_STYLE_PROPERTIES) { + element.style.removeProperty(property); + } + }; + + const enter = (measure: () => PopoverSurfaceGeometry) => { + // A dismissal let the element go (exit, below). + animator.attach(element); + let from: SurfaceState | null = null; + if (exiting != null && collapsed != null) { + // Shown again during the dismissal: turn back from the frame on + // screen, about the same point. + from = readState(exiting.animator, collapsed.axis); + } + endExit(); + if (from == null) { + // Full size and invisible for the read. The box must not include a + // scale from the last dismissal, nor the first keyframe of the layer's + // CSS entrance. The curves below replace these before anything paints. + element.style.setProperty('animation-name', 'none'); + animator.set({scaleX: 1, scaleY: 1, opacity: 0}); + } + const geometry = from != null && measured != null ? measured : measure(); + const next = + from != null && collapsed != null + ? collapsed + : popoverCollapsedState(geometry); + collapsed = next; + measured = geometry; + // The layer's own CSS entrance belongs to the pointer presentation. + element.style.setProperty('animation-name', 'none'); + element.style.setProperty( + 'transform-origin', + `${next.originX}px ${next.originY}px`, + ); + const start = from ?? {scale: next.scale, length: next.length, opacity: 0}; + animator.set(frameOf(start, next.axis)); + const handle = animator.play( + surfaceCurves( + start, + PRESENTED, + next.axis, + timingOn(element, POPOVER_ENTRANCE_TOKENS), + ), + ); + presentHandle = handle; + void handle.finished.then(() => { + if (presentHandle === handle) { + presentHandle = null; + } + }); + }; + + const exit = () => { + const target = collapsed; + if (target == null || exiting != null) { + return; + } + const from = readState(animator, target.axis); + const timing = timingOn(element, POPOVER_EXIT_TOKENS); + presentHandle = null; + // The copy stands where the surface is drawn, the growth's frame + // included. + const copy = placePopoverExitCopy(element); + if (copy == null) { + // No top layer for a copy: the close is immediate. + animator.set({scaleX: 1, scaleY: 1, opacity: 1}); + return; + } + copy.style.setProperty( + 'transform-origin', + `${target.originX}px ${target.originY}px`, + ); + const closing = createMotionEngine(copy, options); + closing.set(frameOf(from, target.axis)); + const handle = closing.play( + surfaceCurves( + from, + {scale: target.scale, length: target.length, opacity: 0}, + target.axis, + timing, + ), + ); + exiting = {copy, animator: closing}; + // The browser hides the element now. Leave it at rest, and let go of the + // layer its growth promoted in this task. Kept, the promotion would end + // inside the dismissal, a style write on an element that no longer + // paints (a Layout in the dismissal's frames). The next presentation + // attaches the element again. + animator.set({scaleX: 1, scaleY: 1, opacity: 1}, {promote: false}); + animator.attach(null); + void handle.finished.then(finished => { + if (finished && exiting?.copy === copy) { + endExit(); + } + }); + }; + + return { + enter, + exit, + reset, + dispose() { + reset(); + animator.dispose(); + }, + }; +} diff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsx index 6bf22e828ace7..6462e951fe584 100644 --- a/packages/core/src/Popover/usePopover.tsx +++ b/packages/core/src/Popover/usePopover.tsx @@ -5,8 +5,9 @@ /** * @file usePopover.tsx * @input Uses useLayer, useFocusTrap, React hooks - * @output Exports the public usePopover hook with derived focus and guarded opening, - * and FALLBACK_CLOSE_SELECTOR for Popover.tsx (internal). + * @output Exports the public usePopover hook with derived focus and guarded opening. + * For Popover.tsx (internal), exports usePopoverInternal and + * FALLBACK_CLOSE_SELECTOR. * @position Higher-level layer utility; used by DatePicker, Combobox, etc. * * Combines popover layer behavior with focus trap for dialog-like popovers. @@ -18,7 +19,7 @@ import React, {useCallback, useEffect, useRef, type ReactNode} from 'react'; import * as stylex from '@stylexjs/stylex'; -import {useLayer, type ContextRenderProps} from '../Layer/useLayer'; +import {useLayerInternal, type ContextRenderProps} from '../Layer/useLayer'; import {useFocusTrapInternal} from '../hooks/useFocusTrap'; import {LayerDepthProvider} from '../Layer/LayerDepthContext'; import type {StyleXStyles} from '@stylexjs/stylex'; @@ -353,6 +354,18 @@ export interface UsePopoverReturn { }; } +/** + * Options a core component may pass through `usePopoverInternal`; not part + * of the public `usePopover` options. + */ +interface InternalPopoverOptions extends UsePopoverOptions { + /** + * Runs as the popover starts to close, while the browser still shows it. + * A close that plays out after the popover is hidden starts here. + */ + onCloseStart?: () => void; +} + /** * Hook for creating popover dialogs with focus trapping. * @@ -394,11 +407,12 @@ export interface UsePopoverReturn { * ``` */ function usePopoverImplementation( - options: UsePopoverOptions = {}, + options: InternalPopoverOptions = {}, ): UsePopoverReturn { const { onShow, onHide, + onCloseStart, xstyle, className, style, @@ -436,11 +450,12 @@ function usePopoverImplementation( }, [onShow]); // Core layer for popover positioning - const layer = useLayer({ + const layer = useLayerInternal({ mode: 'context', lightDismiss: hasLightDismiss, onShow: handleLayerShow, onHide, + onCloseStart, }); // Focus trap for the popover content. Escape stays registered while light @@ -670,3 +685,12 @@ function usePopoverImplementation( export function usePopover(options: UsePopoverOptions = {}): UsePopoverReturn { return usePopoverImplementation(options); } + +/** + * @internal For Popover; not exported from the package barrel. + */ +export function usePopoverInternal( + options: InternalPopoverOptions = {}, +): UsePopoverReturn { + return usePopoverImplementation(options); +} diff --git a/packages/core/src/Popover/usePopoverSurfaceMotion.test.tsx b/packages/core/src/Popover/usePopoverSurfaceMotion.test.tsx new file mode 100644 index 0000000000000..b5ed286b69c82 --- /dev/null +++ b/packages/core/src/Popover/usePopoverSurfaceMotion.test.tsx @@ -0,0 +1,110 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file usePopoverSurfaceMotion.test.tsx + * @input vitest (jsdom), React Testing Library, a stand-in popover layer and + * trigger, a stubbed pointer query and a recording stand-in for the motion + * @output Checks when the hook creates, drives and releases the touch + * presentation. A fine pointer creates and promotes nothing, and its close + * start plays nothing. + * @position Testing; Popover's touch presentation, the hook that drives it + */ + +import {renderHook} from '@testing-library/react'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {TOUCH_QUERY} from '../utils/touchPresentation'; +import {createPopoverSurfaceMotion} from './popoverSurfaceMotion'; +import {usePopoverSurfaceMotion} from './usePopoverSurfaceMotion'; + +vi.mock('./popoverSurfaceMotion', () => ({ + createPopoverSurfaceMotion: vi.fn(() => ({ + enter: vi.fn(), + exit: vi.fn(), + reset: vi.fn(), + dispose: vi.fn(), + })), +})); + +const created = () => + vi + .mocked(createPopoverSurfaceMotion) + .mock.results.map( + result => result.value as ReturnType, + ); + +let isTouch = false; + +beforeEach(() => { + isTouch = false; + vi.mocked(createPopoverSurfaceMotion).mockClear(); + vi.stubGlobal( + 'matchMedia', + vi.fn((query: string) => ({ + matches: query === TOUCH_QUERY ? isTouch : false, + media: query, + addEventListener: () => {}, + removeEventListener: () => {}, + })), + ); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + document.body.innerHTML = ''; +}); + +function layerAndTrigger() { + const layer = document.createElement('div'); + layer.setAttribute('popover', 'auto'); + layer.innerHTML = '
'; + const trigger = document.createElement('button'); + document.body.append(layer, trigger); + return {layer, trigger}; +} + +describe('usePopoverSurfaceMotion', () => { + it('leaves a fine-pointer open untouched: nothing created, nothing promoted, and its close start plays nothing', () => { + const {layer, trigger} = layerAndTrigger(); + const {result} = renderHook(() => usePopoverSurfaceMotion()); + result.current.present(layer, trigger); + result.current.closeStart(); + expect(createPopoverSurfaceMotion).not.toHaveBeenCalled(); + expect(layer.getAttribute('style')).toBeNull(); + }); + + it('under a coarse pointer, grows the popover as it opens and shrinks it as its close starts', () => { + isTouch = true; + const {layer, trigger} = layerAndTrigger(); + const {result} = renderHook(() => usePopoverSurfaceMotion()); + result.current.present(layer, trigger); + const [motion] = created(); + expect(motion.enter).toHaveBeenCalledTimes(1); + expect(motion.exit).not.toHaveBeenCalled(); + result.current.closeStart(); + expect(motion.exit).toHaveBeenCalledTimes(1); + }); + + it('a fine-pointer open after a touch one releases the touch motion, and its close start plays nothing', () => { + isTouch = true; + const {layer, trigger} = layerAndTrigger(); + const {result} = renderHook(() => usePopoverSurfaceMotion()); + result.current.present(layer, trigger); + const [motion] = created(); + // The pointer turns fine (a keyboard attached) for the next open. + isTouch = false; + result.current.present(layer, trigger); + expect(motion.dispose).toHaveBeenCalledTimes(1); + result.current.closeStart(); + expect(motion.exit).not.toHaveBeenCalled(); + }); + + it('releases the motion at unmount', () => { + isTouch = true; + const {layer, trigger} = layerAndTrigger(); + const {result, unmount} = renderHook(() => usePopoverSurfaceMotion()); + result.current.present(layer, trigger); + const [motion] = created(); + unmount(); + expect(motion.dispose).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/core/src/Popover/usePopoverSurfaceMotion.ts b/packages/core/src/Popover/usePopoverSurfaceMotion.ts new file mode 100644 index 0000000000000..623ac9b3ea6e5 --- /dev/null +++ b/packages/core/src/Popover/usePopoverSurfaceMotion.ts @@ -0,0 +1,112 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file usePopoverSurfaceMotion.ts + * @input React, the shared touch resolver and popoverSurfaceMotion + * @output Exports `usePopoverSurfaceMotion`, the calls Popover makes as it + * opens and as it starts to close. Under a finger they present and dismiss + * the popover the UIKit way; a mouse keeps the layer's own entrance. + * @position Internal to Popover; glue between the component and + * popoverSurfaceMotion.ts + * + * The shared touch resolver decides as the popover opens. Under a finger (a + * coarse primary pointer, on any touch device) the popover grows out of its + * source. When the layer runtime reports that it starts to close, it shrinks + * back into it. A fine primary pointer keeps the layer's own entrance. The + * motion is created for the popover element the first time it opens and + * follows it if the element is replaced. + * + * SYNC: When modified, update: + * - /packages/core/src/Popover/Popover.tsx + * - /packages/core/src/Popover/usePopoverSurfaceMotion.test.tsx + */ + +import {useCallback, useEffect, useMemo, useRef} from 'react'; +import {isCoarsePointer} from '../utils/coarsePointer'; +import { + createPopoverSurfaceMotion, + type PopoverSurfaceMotion, + type PopoverSurfaceRect, +} from './popoverSurfaceMotion'; + +function boxOf(element: Element): PopoverSurfaceRect { + const rect = element.getBoundingClientRect(); + return { + left: rect.left, + top: rect.top, + width: rect.width, + height: rect.height, + }; +} + +export interface PopoverSurfaceMotionCalls { + /** + * Call as the popover opens, right after the browser shows it and before + * it paints. + */ + present: (layer: HTMLElement | null, source: HTMLElement | null) => void; + /** Call as the popover starts to close, while the browser still shows it. */ + closeStart: () => void; +} + +export function usePopoverSurfaceMotion(): PopoverSurfaceMotionCalls { + const motionRef = useRef<{ + element: HTMLElement; + motion: PopoverSurfaceMotion; + } | null>(null); + const isTouchPresentationRef = useRef(false); + + const release = useCallback(() => { + motionRef.current?.motion.dispose(); + motionRef.current = null; + }, []); + + const motionFor = useCallback((element: HTMLElement) => { + const current = motionRef.current; + if (current?.element === element) { + return current.motion; + } + current?.motion.dispose(); + const motion = createPopoverSurfaceMotion(element); + motionRef.current = {element, motion}; + return motion; + }, []); + + // Releases the motion's compositor animations, and any exit copy still on + // screen, at unmount. + useEffect(() => release, [release]); + + const present = useCallback( + (layer: HTMLElement | null, source: HTMLElement | null) => { + if (layer == null) { + return; + } + const isTouch = + source != null && isCoarsePointer(layer.ownerDocument.defaultView); + isTouchPresentationRef.current = isTouch; + if (!isTouch || source == null) { + // A fine pointer animates nothing here, so nothing is created for + // it, and nothing is promoted to the compositor. A motion this layer + // already has (the pointer changed, or a touch presentation is on + // screen) is released. + release(); + return; + } + motionFor(layer).enter(() => ({ + surface: boxOf(layer), + source: boxOf(source), + })); + }, + [motionFor, release], + ); + + const closeStart = useCallback(() => { + if (isTouchPresentationRef.current) { + motionRef.current?.motion.exit(); + } + }, []); + + return useMemo(() => ({present, closeStart}), [present, closeStart]); +} diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.md index c5a9677b5815c..2643d62d9c8b0 100644 --- a/packages/core/src/motion/MEASUREMENTS.md +++ b/packages/core/src/motion/MEASUREMENTS.md @@ -297,6 +297,23 @@ fades in, with Prefer Cross-Fade Transitions on or off. | M-CM5 | Commit haptic stand-in | An Android device: `navigator.vibrate` patterns against the platform's HapticFeedbackConstants for the context-click moment | the pattern that matches; not a UIKit parity value (as M-G18) | H | | M-CM6 | Press thresholds | Probe app: repeated long presses at random vsync phases | from touch receipt and from the HID timestamp, the tick before and the tick at the press observer's began and at the click commit; the intersection pins the 150 ms and 400 ms thresholds | C | +## Popovers (UIPopoverPresentationController) + +Values the popover reads from its own table (`uikit/popover.ts`). Its growth +and shrink play the theme's duration and easing tokens, not UIKit's springs. +The table keeps how long UIKit's springs take, as references: the growth comes +within 2% of its end in 206 ms and plays `--duration-medium-min`, the nearest +step in the Storybook theme (225 ms); the shrink takes 249 ms and plays the +exit every overlay shares. + +Done (iOS 26.2 simulator, Oct 23 2026; in the popover's table): the scale and +length a popover below its source grows from, how long its growth and shrink +take, and Reduce Motion, with the `.none` adaptation on iPhone. + +| ID | Scene | Gesture | Extract | Method | +| ----- | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------ | +| M-PO1 | a popover above its source, one to its left and one to its right; a source near a screen edge so the arrow sits off the popover's centre | present, then a tap outside | which edge stays in place, which length grows from 100 pt, and the point the scale grows out of when the arrow is off centre | A, C | + ## Picker (UIPickerView) Values the Wheel reads from its own table (`uikit/picker.ts`). diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md index bb8df901afb34..c035a99b2f9b4 100644 --- a/packages/core/src/motion/README.md +++ b/packages/core/src/motion/README.md @@ -22,6 +22,7 @@ roles through `resolveMotion`. | `uikit/alert.ts` | UIAlertController: how a finger is tracked across the actions (highlight onset and bounds). | | `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. | | `uikit/progressBar.ts` | UIProgressView's fill: the whole-track duration and curve, its minimum length and empty alpha; the reduced-motion pulse (three roles). | +| `uikit/popover.ts` | UIPopoverPresentationController: the scale and the length a popover grows out of and shrinks back into. | | `uikit/gestures.ts` | Gesture recognizer thresholds, the velocity filter and haptic stand-ins, as `{value, unit}` entries (sources in JSDoc). | | `uikit/picker.ts` | UIPickerView: row pitch, height and rubber band, velocity floor, the coast's stop speed, snap at rest, tap spin, tick. | | `uikit/segmented.ts` | UISegmentedControl: the selection indicator's spring; under Reduce Motion the animator's cross-fade replaces it. | diff --git a/packages/core/src/motion/uikit/index.ts b/packages/core/src/motion/uikit/index.ts index 0ea81c759fed9..c7169cdefa401 100644 --- a/packages/core/src/motion/uikit/index.ts +++ b/packages/core/src/motion/uikit/index.ts @@ -4,7 +4,7 @@ * @file index.ts * @input The domain files of the UIKit constants table * @output Re-exports `springs` and one constant per spring (`SHEET_PRESENT_SPRING`, - * …), `scroll`, `timing`, `navigation`, `picker`, `progressBar`, + * …), `scroll`, `timing`, `navigation`, `picker`, `popover`, `progressBar`, * `segmentedControl`, `datePicker`, `slider` and `switchControl`. It also * re-exports the gesture thresholds: one `UIKIT_*` group per recognizer, * their union `UIKIT_GESTURES`, and the haptic tables @@ -43,6 +43,7 @@ export { export {datePicker} from './datePicker'; export {navigation, registerNavigationTable} from './navigation'; export {picker} from './picker'; +export {popover} from './popover'; export {progressBar, registerProgressBarTable} from './progressBar'; export {registerScrollTable, scroll} from './scroll'; export {segmentedControl} from './segmented'; diff --git a/packages/core/src/motion/uikit/popover.ts b/packages/core/src/motion/uikit/popover.ts new file mode 100644 index 0000000000000..f8c3111aace59 --- /dev/null +++ b/packages/core/src/motion/uikit/popover.ts @@ -0,0 +1,71 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file popover.ts + * @input Nothing; data only + * @output Exports `popover`: the shape a popover grows out of and shrinks + * back into as it is presented and dismissed, and how long each takes + * @position The popover domain of the UIKit constants table (motion/uikit). + * These are internal constants, not motion roles. + * + * UIPopoverPresentationController with its adaptation turned off (`.none`, + * so it stays a popover on iPhone), read from UIKit on the iOS 26.2 + * simulator. The popover view grows out of the point where it meets its + * source (the bottom centre of the source for a popover below it). Its scale, + * its length away from the source and its opacity move together, with the + * edge that meets the source held in place. Lengths are in pt (CSS px). + * + * Every leaf carries one or more `@source`; GUESS values also carry the + * `@measure` task that will confirm or replace them. uikit.test.ts enforces + * both. + * + * SYNC: When modified, update /packages/core/src/motion/MEASUREMENTS.md + */ + +export const popover = { + /** + * The uniform scale the popover grows from and shrinks back to, about the + * point where it meets its source. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, CASpringAnimation dump on the popover view, Oct 23 + * 2026: an additive `transform` animation from scale 0.01 to identity on + * the present spring, and from identity back to 0.01 on the dismiss + * spring; per-frame presentation frames keep the popover's top edge on + * the source's bottom edge and its centre on the source's centre line + * (scale 0.02, 0.32, 0.67, 0.88, 0.98, 1.01, 1 at 50 ms steps) + */ + collapsedScale: 0.01, + /** + * The popover's length away from its source when it starts to grow and + * when it has shrunk back. For a popover below its source, it is the + * height. The box grows from this length to its own together with the + * scale, whatever its size. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, CASpringAnimation dump on the popover view, Oct 23 + * 2026: an additive `bounds.size` animation from height −153 for a + * 253 pt popover and from −433 for a 533 pt one, both starting at 100 pt, + * with `position` moving by half of it so the top edge stays put; the + * dismiss animates back to the same 100 pt + */ + collapsedLengthPx: 100, + /** + * How long the growth takes to come within 2% of its end: the reference + * the growth's duration token is chosen against. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, CASpringAnimation dump on the popover view, Oct 23 + * 2026: the present spring (mass 1, stiffness 331.901, damping 29.149, + * bounce 0.2, CA duration 0.4937 s) is 98% of the way at 206 ms and stays + * within 2% after it; the frames read scale 0.98 at 200 ms + */ + growMs: 206, + /** + * How long the shrink takes to come within 2% of its end. It is a + * reference only: the shrink plays the exit every overlay shares. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, CASpringAnimation dump on the popover view, Oct 23 + * 2026: the dismiss spring (mass 1, stiffness 283.973, damping 28.648, + * bounce 0.15, CA duration 0.51566 s) is 98% of the way at 249 ms and + * stays within 2% after it + */ + shrinkMs: 249, +} as const; diff --git a/packages/core/src/privateAttributes/popoverExit.stylex.ts b/packages/core/src/privateAttributes/popoverExit.stylex.ts new file mode 100644 index 0000000000000..2c58c7519e17f --- /dev/null +++ b/packages/core/src/privateAttributes/popoverExit.stylex.ts @@ -0,0 +1,30 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file privateAttributes/popoverExit.stylex.ts + * @input A closing popover's layer element + * @output placePopoverExitCopy, which places the layer runtime's exit copy of + * a closing popover, marked as a popover's, and findPopoverExitCopy, which + * finds that copy + * @position Owner module of the private popover-exit attribute: the only + * file that writes its name. Popover's touch close plays on the copy it + * places. No package entry exports it. + */ + +import {placeLayerExitCopy} from '../Layer/layerExitCopy'; + +const POPOVER_EXIT = 'data-astryx-popover-exit'; + +/** + * Places the layer runtime's exit copy of a closing popover, marked as a + * popover's. Returns null where there is no top layer to show it in: the + * close is then immediate. + */ +export function placePopoverExitCopy(element: HTMLElement): HTMLElement | null { + return placeLayerExitCopy(element, POPOVER_EXIT); +} + +/** The exit copy of a closing popover under `root`, if one is on screen. */ +export function findPopoverExitCopy(root: ParentNode): HTMLElement | null { + return root.querySelector(`[${POPOVER_EXIT}]`); +} From 5f98e88d45baa1147a384b522bbeb6f71f930fcf Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 5 Nov 2026 07:38:03 -0800 Subject: [PATCH 8/8] test(Popover): browser proofs of the touch presentation's grow and shrink Real-browser proofs, in Chromium and WebKit, that under a finger Popover grows out of its trigger on the theme's entrance tokens and shrinks back on its exit tokens, keeps advancing through a blocked main thread, does no Layout or Paint per frame, and cross-fades under Reduce Motion, with storyboards of both. --- ...verTouchMotion.interaction.browser.spec.ts | 775 ++++++++++++++++++ 1 file changed, 775 insertions(+) create mode 100644 packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts diff --git a/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts b/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts new file mode 100644 index 0000000000000..d096b9b8e6771 --- /dev/null +++ b/packages/core/src/Popover/__tests__/PopoverTouchMotion.interaction.browser.spec.ts @@ -0,0 +1,775 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file PopoverTouchMotion.interaction.browser.spec.ts + * @input The built Default Popover story, with real touch input (Chromium + * CDP / WebKit's input command) and the interaction harness. The proofs + * also read the popover's geometry and the theme tokens that time its + * motion. + * @output Animation proofs for Popover's touch presentation under a finger, + * one touch model on every touch device. It grows out of its trigger on + * the entrance tokens, edge on the trigger. It shrinks back on the exit + * tokens, on screen through the light dismiss. The growth keeps advancing + * through a blocked main thread. On a page with no other frame work, + * neither motion does Layout or Paint per frame. Reduce Motion + * cross-fades, opacity only, in 200 ms or less. A mouse keeps the layer's + * own entrance. Storyboards of both. + * @position Evidence for Popover's touch presentation; the model itself is + * unit-tested in popoverSurfaceMotion.test.ts + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + animationStoryboard, + blockMainThread, + busyWindowProof, + castStoryboard, + compareCurve, + countBetween, + freezeTimers, + holdAnimations, + installLongTaskLog, + installTimerGate, + markElement, + openStory, + releaseAnimations, + startScreencast, + thawTimers, + timeline, + touchDriver, + traceRendering, + trackMarker, + waitForAnimation, + waitForRest, + withStorybook, + writeEvidence, + type TouchDriver, +} from '@astryxdesign/interaction-harness'; +import {timing} from '../../motion/uikit/timing'; +import {cubicBezier} from '../../motion/bezier'; +import {parseCssEasing, parseMotionRoleValue} from '../../motion/roles'; +import type {ThemeTimingTokens} from '../../motion/themeTiming'; +import { + POPOVER_ENTRANCE_TOKENS, + POPOVER_EXIT_TOKENS, + popoverCollapsedState, + popoverFrame, +} from '../popoverSurfaceFrame'; + +const storybook = withStorybook(test); + +/** + * The duration (ms) and the eased progress that the story's theme gives + * `tokens`, read where the popover is. + */ +async function themeTiming(locator: Locator, tokens: ThemeTimingTokens) { + const [duration, easing] = await locator.evaluate( + (element, names) => { + const style = getComputedStyle(element); + return names.map(name => style.getPropertyValue(name).trim()); + }, + [tokens.duration, tokens.easing], + ); + const ms = parseMotionRoleValue('duration', duration); + const points = parseCssEasing(easing); + if (ms == null || points == null) { + throw new Error( + `the story theme gives no playable timing: ${duration}, ${easing}`, + ); + } + const ease = cubicBezier(points); + return {ms, at: (t: number) => (t >= ms ? 1 : ease(Math.max(0, t) / ms))}; +} + +interface Box { + x: number; + y: number; + width: number; + height: number; +} + +interface OpenStory { + driver: TouchDriver; + trigger: Locator; + layer: Locator; + center: {x: number; y: number}; + triggerBox: Box; +} + +async function openDefault(page: Page): Promise { + await installLongTaskLog(page); + await openStory(page, storybook(), 'core-popover--default'); + const driver = await touchDriver(page); + const trigger = page.getByRole('button', {name: 'Settings'}); + const triggerBox = await trigger.boundingBox(); + if (triggerBox == null) { + throw new Error('no trigger'); + } + return { + driver, + trigger, + layer: page.locator('[popover]:has([role="dialog"])').first(), + center: { + x: triggerBox.x + triggerBox.width / 2, + y: triggerBox.y + triggerBox.height / 2, + }, + triggerBox, + }; +} + +/** + * The element's presented box at each time of its held animations: its + * layout box scaled by the presented `scale` about its `transform-origin`. + * Read from the computed style, which follows a seek; a composited animation + * of an individual transform property does not reach getBoundingClientRect + * in Chromium. + */ +async function sampleBoxes( + locator: Locator, + layout: Box, + times: ReadonlyArray, +): Promise<{t: number; box: Box; opacity: number}[]> { + const raw = await locator.evaluate((element, ts) => { + const held = + (window as unknown as {__harnessHeld?: Animation[]}).__harnessHeld ?? []; + if (held.length === 0) { + throw new Error('sampleBoxes: no held animations'); + } + return ts.map(t => { + for (const animation of held) { + const end = Number( + animation.effect?.getComputedTiming().endTime ?? Infinity, + ); + animation.currentTime = Math.min(t, end - 0.5); + } + const style = getComputedStyle(element); + return { + t, + scale: style.scale, + origin: style.transformOrigin, + opacity: Number(style.opacity), + }; + }); + }, times); + return raw.map(({t, scale, origin, opacity}) => { + const [sx, sy = sx] = + scale === 'none' ? [1, 1] : scale.split(' ').map(Number); + const [ox, oy] = origin.split(' ').map(value => parseFloat(value)); + return { + t, + opacity, + box: { + x: layout.x + ox * (1 - sx), + y: layout.y + oy * (1 - sy), + width: layout.width * sx, + height: layout.height * sy, + }, + }; + }); +} + +/** UIKit's popover path at progress p of the growth, as a visual box. */ +function expectedBox(final: Box, trigger: Box, p: number): Box { + const geometry = { + surface: { + left: final.x, + top: final.y, + width: final.width, + height: final.height, + }, + source: { + left: trigger.x, + top: trigger.y, + width: trigger.width, + height: trigger.height, + }, + }; + const state = popoverCollapsedState(geometry); + const frame = popoverFrame(state, p); + return { + x: final.x + state.originX * (1 - frame.scaleX), + y: final.y + state.originY * (1 - frame.scaleY), + width: final.width * frame.scaleX, + height: final.height * frame.scaleY, + }; +} + +/** The layer's own scale animation among those running in it. */ +async function scaleAnimationOf(locator: Locator) { + for (;;) { + const found = await waitForAnimation(locator); + const scale = found.find(a => a.keyframes.some(k => 'scale' in k)); + if (scale != null) { + return scale; + } + } +} + +/** + * Logs when each `scale` animation starts, epoch ms, from a wrapper on + * `Element.animate`. It runs no frame loop, so it reads nothing between + * frames. + */ +async function logScaleStarts(page: Page) { + await page.addInitScript(() => { + const starts: number[] = []; + Object.defineProperty(window, '__popoverScaleStarts', {value: starts}); + const animate = Element.prototype.animate; + Element.prototype.animate = function (keyframes, options) { + const animation = animate.call(this, keyframes, options); + if ( + Array.isArray(keyframes) && + keyframes.some(frame => frame != null && 'scale' in frame) + ) { + starts.push(performance.timeOrigin + performance.now()); + } + return animation; + }; + }); +} + +/** + * The rendering proof's motions: 1.2 s each, set on the layer and its exit + * copy, which the dismissal clones from it. + */ +const LONG_MOTIONS = + '[popover]:has([role="dialog"]) { --duration-medium-min: 1200ms; --duration-exit: 1200ms; }'; + +/** Where each rendering window starts, ms after its motion starts. */ +const WINDOW_START_MS = 400; + +/** The page's clock, epoch ms. */ +async function pageNow(page: Page): Promise { + return page.evaluate(() => performance.timeOrigin + performance.now()); +} + +/** + * Waits in the page until `ms` after the first logged scale start at or after + * `after`, and returns that start. It reads only the log, never a style, and + * after the start it sets one timer. + */ +async function waitPastScaleStart( + page: Page, + after: number, + ms: number, +): Promise { + return page.evaluate( + async ({after, ms}) => + new Promise((resolve, reject) => { + const starts = (window as unknown as {__popoverScaleStarts: number[]}) + .__popoverScaleStarts; + const deadline = performance.now() + 5_000; + const look = () => { + const start = starts.find(logged => logged >= after); + if (start != null) { + const now = performance.timeOrigin + performance.now(); + setTimeout(() => resolve(start), Math.max(0, start + ms - now)); + } else if (performance.now() > deadline) { + reject(new Error('no scale animation started')); + } else { + setTimeout(look, 10); + } + }; + look(); + }), + {after, ms}, + ); +} + +/** The static copy the dismissal plays on. */ +const exitCopyOf = (page: Page) => + page.locator('[data-astryx-popover-exit]').first(); + +async function openWithTap(story: OpenStory) { + await story.driver.tap(story.center); + await expect(story.trigger).toHaveAttribute('aria-expanded', 'true'); +} + +test.describe('with a mouse (a fine primary pointer)', () => { + test.use({hasTouch: false, isMobile: false}); + + test('the layer keeps its own entrance and the popover closes at once', async ({ + page, + }) => { + await installLongTaskLog(page); + await openStory(page, storybook(), 'core-popover--default'); + const trigger = page.getByRole('button', {name: 'Settings'}); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + await trigger.click(); + await expect(trigger).toHaveAttribute('aria-expanded', 'true'); + const layer = page.locator('[popover]:has([role="dialog"])').first(); + // The layer's own CSS entrance runs; no UIKit scale is set or played. + const entrance = await layer.evaluate(element => ({ + inlineScale: (element as HTMLElement).style.getPropertyValue('scale'), + inlineAnimation: (element as HTMLElement).style.getPropertyValue( + 'animation-name', + ), + animationName: getComputedStyle(element).animationName, + played: element + .getAnimations() + .some( + animation => + !(animation instanceof CSSAnimation) && + (animation.effect as KeyframeEffect | null) + ?.getKeyframes() + .some(frame => 'scale' in frame) === true, + ), + })); + expect(entrance.inlineScale).toBe(''); + expect(entrance.inlineAnimation).toBe(''); + expect(entrance.animationName).not.toBe('none'); + expect(entrance.played).toBe(false); + await waitForRest(layer); + // A click outside closes it at once: no copy shrinks back into the trigger. + const viewport = page.viewportSize(); + if (viewport == null) { + throw new Error('no viewport'); + } + await page.mouse.click(20, viewport.height - 20); + await expect(trigger).toHaveAttribute('aria-expanded', 'false'); + await expect(exitCopyOf(page)).toHaveCount(0); + }); +}); + +test('the presentation grows out of the trigger on the theme\u2019s entrance tokens', async ({ + page, +}, testInfo) => { + const story = await openDefault(page); + // The popover's layout box, from a first presentation run to rest. + await openWithTap(story); + await waitForRest(story.layer); + const final = (await story.layer.boundingBox())!; + const entrance = await themeTiming(story.layer, POPOVER_ENTRANCE_TOKENS); + await page.keyboard.press('Escape'); + await expect(story.trigger).toHaveAttribute('aria-expanded', 'false'); + // Presenting during the dismissal would turn back from the closing frame. + await expect(exitCopyOf(page)).toHaveCount(0); + await openWithTap(story); + await scaleAnimationOf(story.layer); + const held = await holdAnimations(page, story.layer); + const samples = await sampleBoxes( + story.layer, + final, + timeline(entrance.ms + 100), + ); + await releaseAnimations(page, {finish: true}); + const at = (t: number) => + expectedBox(final, story.triggerBox, entrance.at(t)); + const compare = (read: (box: Box) => number) => + compareCurve( + samples.map(sample => ({t: sample.t, value: read(sample.box)})), + t => read(at(t)), + 0.75, + ); + const width = compare(box => box.width); + const height = compare(box => box.height); + const top = compare(box => box.y); + const cx = compare(box => box.x + box.width / 2); + const opacity = compareCurve( + samples.map(sample => ({t: sample.t, value: sample.opacity})), + t => entrance.at(t), + 0.02, + ); + await writeEvidence( + 'curves/popover-touch-present', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {held, final, trigger: story.triggerBox, width, height, top, cx}, + null, + 1, + ), + }, + testInfo, + ); + // The popover's edge stays on the trigger's bottom edge throughout. + for (const sample of samples) { + expect(sample.box.y).toBeCloseTo(final.y, 0); + } + for (const result of [width, height, top, cx, opacity]) { + expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual( + result.tolerance, + ); + } +}); + +test('the dismissal shrinks back into the trigger on the theme\u2019s exit tokens, on screen through the light dismiss', async ({ + page, +}, testInfo) => { + const story = await openDefault(page); + await openWithTap(story); + await waitForRest(story.layer); + const open = (await story.layer.boundingBox())!; + const exit = await themeTiming(story.layer, POPOVER_EXIT_TOKENS); + // Tap outside: the browser's light dismiss closes the popover at once. + const viewport = page.viewportSize()!; + await story.driver.tap({x: 20, y: viewport.height - 20}); + await expect(story.trigger).toHaveAttribute('aria-expanded', 'false'); + const copy = exitCopyOf(page); + await scaleAnimationOf(copy); + const held = await holdAnimations(page, copy); + // The popover is closed and gone; the dismissal plays on a static copy + // where it stood, out of the accessibility tree and out of reach. + const state = await page.evaluate(() => { + const layer = document.querySelector( + '[popover]:has([role="dialog"])', + )!; + const exitCopy = document.querySelector( + '[data-astryx-popover-exit]', + )!; + return { + layerOpen: layer.matches(':popover-open'), + layerDisplay: getComputedStyle(layer).display, + copyHidden: exitCopy.getAttribute('aria-hidden'), + copyInert: exitCopy.hasAttribute('inert'), + copyPointerEvents: getComputedStyle(exitCopy).pointerEvents, + copyIds: exitCopy.querySelectorAll('[id]').length, + }; + }); + expect(state).toEqual({ + layerOpen: false, + layerDisplay: 'none', + copyHidden: 'true', + copyInert: true, + copyPointerEvents: 'none', + copyIds: 0, + }); + const samples = await sampleBoxes(copy, open, timeline(exit.ms + 100)); + await releaseAnimations(page, {finish: true}); + // The dismissal runs the presentation's path backwards. + const at = (t: number) => expectedBox(open, story.triggerBox, 1 - exit.at(t)); + const width = compareCurve( + samples.map(sample => ({t: sample.t, value: sample.box.width})), + t => at(t).width, + 0.75, + ); + const height = compareCurve( + samples.map(sample => ({t: sample.t, value: sample.box.height})), + t => at(t).height, + 0.75, + ); + const opacity = compareCurve( + samples.map(sample => ({t: sample.t, value: sample.opacity})), + t => 1 - exit.at(t), + 0.02, + ); + await writeEvidence( + 'curves/popover-touch-dismiss', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {held, open, trigger: story.triggerBox, state, width, height}, + null, + 1, + ), + }, + testInfo, + ); + for (const result of [width, height, opacity]) { + expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual( + result.tolerance, + ); + } + // Once the dismissal has run, the copy is gone. + await expect(page.locator('[data-astryx-popover-exit]')).toHaveCount(0); +}); + +test('the presentation keeps advancing every frame while the main thread is blocked', async ({ + page, + browserName, +}, testInfo) => { + test.skip( + browserName !== 'chromium', + 'screencast frame evidence is Chromium-only in Playwright (WebKit: the iOS simulator rig)', + ); + const story = await openDefault(page); + // The screencast finds the element by its marker's exact color, which the + // content fade would blend away. So this proof holds opacity at 1, since an + // important declaration outranks the animation. The scale, composited the + // same way, carries the evidence. + await page.addStyleTag({ + content: '[popover]:has([role="dialog"]) { opacity: 1 !important; }', + }); + await markElement(story.layer, {size: 24, inset: 0}); + const entrance = await themeTiming(story.layer, POPOVER_ENTRANCE_TOKENS); + const cast = await startScreencast(page); + await openWithTap(story); + const [present] = await waitForAnimation(story.layer, {minProgressMs: 16}); + const block = await blockMainThread(page, 400); + await page.waitForTimeout(100); + const castFrames = await cast.stop(); + const tracked = await trackMarker(page, castFrames); + // Up to the end of the growth: until then the marker moves one way only. + const window = { + from: block.from, + to: Math.min(block.to, present.from + entrance.ms - 20), + }; + const proof = busyWindowProof(tracked, window, {axis: 'x'}); + await writeEvidence( + 'busy-main-thread/popover-touch-present', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {block, present, proof}, + null, + 1, + ), + }, + testInfo, + ); + const film = await castStoryboard(page, castFrames, { + name: 'popover-touch-present-busy-main-thread', + zero: block.from, + from: block.from - 40, + to: window.to + 40, + columns: 8, + cellScale: 0.35, + data: t => ({x: tracked.find(f => f.t === t)?.box?.x ?? -1}), + }); + await film.write(testInfo, {block, present}); + expect(proof.frames).toBeGreaterThanOrEqual(proof.expectedFrames - 2); + expect(proof.changed).toBeGreaterThanOrEqual(proof.frames - 3); + // A stall is judged in the screencast's own intervals, as the harness's + // verdict judges it: no more than two dropped frames. + expect(proof.longestStallFrames).toBeLessThanOrEqual(3); + expect(proof.monotonic).toBe(true); +}); + +test('the presentation and the dismissal do no Layout or Paint per frame', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only'); + await logScaleStarts(page); + const story = await openDefault(page); + // Both motions run for 1.2 s here. The windows can then start after the + // one-off work as the content appears and still span many frames, even + // on a loaded machine. + await page.addStyleTag({content: LONG_MOTIONS}); + const entrance = await themeTiming(story.layer, POPOVER_ENTRANCE_TOKENS); + const exit = await themeTiming(story.layer, POPOVER_EXIT_TOKENS); + expect(entrance.ms).toBe(1200); + expect(exit.ms).toBe(1200); + // It opens from the keyboard to keep the trigger's own press feedback out + // of the measurement. The phone's primary pointer is still coarse, so the + // touch presentation runs. Nothing reads the page inside the windows: on + // this anchored layer, a style read during an animation is a style update + // and a layout. That rules out the harness's animation recorder, which + // reads every animation each frame, so the windows come from when each + // scale animation starts. + await story.trigger.focus(); + let present = 0; + let dismiss = 0; + const trace = await traceRendering(page, async () => { + const opened = await pageNow(page); + await page.keyboard.press('Enter'); + present = await waitPastScaleStart(page, opened, entrance.ms + 150); + const closed = await pageNow(page); + await page.keyboard.press('Escape'); + dismiss = await waitPastScaleStart(page, closed, exit.ms + 150); + }); + // Each window starts 400 ms in, after the focus ring and the touch hit + // areas' first measurement, and ends one frame before its curve does. A + // page frame callback makes Chromium lay out this anchored layer every + // frame. So these zeros also show that no frame loop runs here, Popover's + // own included. + for (const [name, base, ms] of [ + ['present', present, entrance.ms], + ['dismiss', dismiss, exit.ms], + ] as const) { + const from = base + WINDOW_START_MS; + const end = base + ms - 20; + const during = countBetween(trace, from, end); + // On failure, every rendering event of the window, in ms after its + // animation's start. + const detail = `${name} ${JSON.stringify({ + during, + events: trace.events + .filter(e => e.t >= from && e.t <= end) + .map(e => `${e.name}@${Math.round(e.t - base)}`), + })}`; + expect(during.Layout ?? 0, detail).toBe(0); + expect(during.Paint ?? 0, detail).toBe(0); + } + // A loaded machine stretches a task's wall time, not its thread time. So a + // long task here is one that runs over 50 ms of thread time. + expect(trace.longTasks.filter(task => task.threadMs > 50)).toEqual([]); + // Positive control: the same trace sees per-frame work in such a window. + // A frame loop moves the trigger by a pixel in each frame the page draws. + // Every one of those frames must show work, however few are drawn. + await story.trigger.evaluate(element => { + (element as HTMLElement).style.position = 'relative'; + }); + let loopFrom = 0; + const control = await traceRendering(page, async () => { + loopFrom = await story.trigger.evaluate((element, ms) => { + const style = (element as HTMLElement).style; + const writes: number[] = []; + Object.defineProperty(window, '__popoverLoopWrites', {value: writes}); + const from = performance.now(); + let frame = 0; + const step = () => { + const now = performance.now(); + frame += 1; + style.top = `${frame % 2}px`; + writes.push(performance.timeOrigin + now); + if (now - from < ms) { + requestAnimationFrame(step); + } + }; + requestAnimationFrame(step); + return performance.timeOrigin + from; + }, entrance.ms); + await page.waitForTimeout(entrance.ms + 150); + }); + const from = loopFrom + WINDOW_START_MS; + const end = loopFrom + entrance.ms - 20; + const drawn = ( + await page.evaluate(() => [ + ...(window as unknown as {__popoverLoopWrites: number[]}) + .__popoverLoopWrites, + ]) + ).filter(write => write >= from && write <= end); + expect(drawn.length, 'frames drawn in the window').toBeGreaterThan(1); + for (const write of drawn) { + expect( + control.events.some( + event => + (event.name === 'Layout' || event.name === 'Paint') && + event.t >= write && + event.t < write + 1000 / 60, + ), + `work in the frame drawn ${Math.round(write - loopFrom)} ms in`, + ).toBe(true); + } +}); + +test('Reduce Motion: the popover cross-fades in at its size and out where it stands, in 200 ms or less with no spring', async ({ + page, +}) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + const story = await openDefault(page); + await openWithTap(story); + await waitForAnimation(story.layer); + await holdAnimations(page, story.layer); + const unit = {x: 0, y: 0, width: 100, height: 100}; + // design:reduced-motion DR2: opacity only, 200 ms or less, here on + // UIKit's cross-fade curve. + const ease = cubicBezier(timing.curves.move); + const fade = (t: number) => + ease(Math.min(1, Math.max(0, t / timing.reducedMotionCrossFadeMs))); + const samples = await sampleBoxes(story.layer, unit, timeline(300)); + // Resume rather than finish: the dismissal below starts from what the + // animator presents, which follows the clock. + await releaseAnimations(page); + await page.waitForTimeout(400); + // No growth: every frame is the popover at full size; it only fades in. + for (const sample of samples) { + expect(sample.box.width).toBeCloseTo(100, 3); + expect(sample.box.height).toBeCloseTo(100, 3); + } + const opacity = compareCurve( + samples.map(sample => ({t: sample.t, value: sample.opacity})), + fade, + 0.02, + ); + expect(opacity.maxError, JSON.stringify(opacity.worst)).toBeLessThanOrEqual( + 0.02, + ); + // In by 200 ms. + for (const sample of samples.filter( + s => s.t >= timing.reducedMotionCrossFadeMs, + )) { + expect(sample.opacity).toBeCloseTo(1, 3); + } + // The dismissal fades out where the popover stands, on the same curve. + await page.keyboard.press('Escape'); + const copy = exitCopyOf(page); + await waitForAnimation(copy); + await holdAnimations(page, copy); + const [closing, gone] = await sampleBoxes(copy, unit, [ + 100, + timing.reducedMotionCrossFadeMs, + ]); + await releaseAnimations(page, {finish: true}); + expect(closing.box.width).toBeCloseTo(100, 3); + expect(closing.opacity).toBeCloseTo(1 - fade(100), 2); + expect(gone.opacity).toBeCloseTo(0, 3); +}); + +test( + 'storyboard: tap to present, tap outside to dismiss', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + const story = await openDefault(page); + await installTimerGate(page); + const viewport = page.viewportSize() ?? {width: 402, height: 714}; + const clip = {x: 0, y: 0, width: viewport.width, height: viewport.height}; + // The presented scale and opacity (a composited scale does not reach + // getBoundingClientRect in Chromium), and the layout size they apply to. + const measureOf = (locator: Locator) => async () => + locator.evaluate(node => { + const el = node as HTMLElement; + const style = getComputedStyle(el); + const [sx, sy = sx] = + style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number); + return { + w: el.offsetWidth * sx, + h: el.offsetHeight * sy, + opacity: Number(style.opacity), + }; + }); + await openWithTap(story); + await waitForAnimation(story.layer); + const entrance = await themeTiming(story.layer, POPOVER_ENTRANCE_TOKENS); + const exit = await themeTiming(story.layer, POPOVER_EXIT_TOKENS); + await freezeTimers(page); + const {storyboard: presentBoard} = await animationStoryboard(page, { + name: 'popover-touch-present', + clip, + scope: story.layer, + measure: measureOf(story.layer), + // The growth ends with the entrance duration; the animation holds its + // end state past that. + times: timeline(entrance.ms + 100), + columns: 8, + cellScale: 0.35, + }); + await releaseAnimations(page, {finish: true}); + await thawTimers(page); + await waitForRest(story.layer); + await story.driver.tap({x: 20, y: viewport.height - 20}); + const copy = exitCopyOf(page); + await waitForAnimation(copy); + await freezeTimers(page); + const {storyboard: dismissBoard} = await animationStoryboard(page, { + name: 'popover-touch-dismiss', + clip, + scope: copy, + measure: measureOf(copy), + times: timeline(exit.ms + 100), + columns: 8, + cellScale: 0.35, + }); + await releaseAnimations(page, {finish: true}); + await thawTimers(page); + await presentBoard.write(testInfo); + await dismissBoard.write(testInfo); + // The trace is the assertion: it grows from a point, wide before tall, + // with no overshoot, and shrinks back. + const widths = presentBoard.frames.map(f => f.data.w as number); + const heights = presentBoard.frames.map(f => f.data.h as number); + expect(widths[0]).toBeLessThan(widths.at(-1)! / 10); + expect(Math.max(...widths)).toBeLessThanOrEqual(widths.at(-1)! + 0.5); + const middle = Math.floor(widths.length / 8); + expect(heights[middle] / heights.at(-1)!).toBeLessThan( + widths[middle] / widths.at(-1)!, + ); + const dismissWidths = dismissBoard.frames.map(f => f.data.w as number); + expect(dismissWidths.at(-1)!).toBeLessThan(dismissWidths[0] / 2); + }, +);