An open source design system that's fully customizable and agent ready
TypeScript
fix(core): a gesture on a gliding element lands where it is drawn (#10239)
Christopher Chedeau79cc4ac77849
diff --git a/.changeset/glide-touch-lands-where-drawn.md b/.changeset/glide-touch-lands-where-drawn.mdnew file mode 100644index 0000000000..4dcb591f7f--- /dev/null+++ b/.changeset/glide-touch-lands-where-drawn.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Animated layout: on iOS Safari, an Astryx gesture on gliding content goes to what is drawn under the finger. Gestures here are gesture recognizers, long presses, and Switch, Slider and SegmentedControl presses. Before, such a touch went to the element that sat under the finger when the glide started. A plain tap that no Astryx gesture handles still goes to that element until the glide ends, at most the theme's move duration.++@vjeuxdiff --git a/docs/specs/AST-105-animated-layout/spec.md b/docs/specs/AST-105-animated-layout/spec.mdindex 4ecfa07194..4df4750ba7 100644--- a/docs/specs/AST-105-animated-layout/spec.md+++ b/docs/specs/AST-105-animated-layout/spec.md@@ -219,6 +219,14 @@ Out of coverage, each taking its final place at once:- INV12 also produces the edge reveal (FR9). SideNav's rail clip and ride moveinto it from SideNav's own code, and a resizable LayoutPanel's collapse andopen, which today jump, adopt it; LayoutPanel's docs say a collapse slides.+- Each running glide that moves a hit-testable element's `translate` reports+ it to `motion/presentation.ts`, as the animator's moves do. An inert copy or+ closing element is not reported. So on iOS WebKit, a touch that the gesture+ host handles goes to what is drawn under the finger (`spec:AST-094` FR11,+ FR19). Implementation gap: on iOS WebKit, a plain tap that no gesture+ handles, on an element mid-glide, still goes to what was at that spot before+ the glide, until the glide ends (glides last at most the theme's move+ duration).## Verificationdiff --git a/packages/core/src/gestures/__tests__/presentedGlide.test.ts b/packages/core/src/gestures/__tests__/presentedGlide.test.tsnew file mode 100644index 0000000000..91eec47e64--- /dev/null+++ b/packages/core/src/gestures/__tests__/presentedGlide.test.ts@@ -0,0 +1,216 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file presentedGlide.test.ts+ * @input GestureHost on jsdom, the animated-layout module and a recording+ * stand-in for Element.animate. The test mimics iOS WebKit's hit testing:+ * `elementFromPoint` answers where each row's glide started. A style write+ * on the row moves that answer to where the row is drawn+ * @output A tap on a row that a glide moves away from its start reaches that+ * row's recognizer, not the row that started under the finger. With the+ * correction off, the row that started there takes it+ * @position Unit tests of animatedLayout's glides in the presented hit+ * testing of GestureHost.ts (motion/presentation.ts); the iOS Simulator+ * proves the real engine+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {+ createAnimatedLayout,+ reportLayoutChange,+} from '../../motion/animatedLayout';+import {GestureHost} from '../GestureHost';+import {TapGestureRecognizer} from '../TapGestureRecognizer';+import {ManualClock} from './harness';+import {coarsePrimaryPointer} from './pointerQuery';++interface Played {+ element: Element;+ keyframes: Keyframe[];+ options: KeyframeAnimationOptions;+ animation: {startTime: number | null};+}++const originalAnimate = Element.prototype.animate;+let played: Played[];+let cleanups: (() => void)[];++beforeEach(() => {+ played = [];+ cleanups = [coarsePrimaryPointer()];+ Element.prototype.animate = function (+ this: Element,+ keyframes: Keyframe[] | PropertyIndexedKeyframes | null,+ options?: number | KeyframeAnimationOptions,+ ) {+ const animation = {+ startTime: null as number | null,+ cancel: vi.fn(),+ addEventListener() {},+ };+ played.push({+ element: this,+ keyframes: keyframes as Keyframe[],+ options: options as KeyframeAnimationOptions,+ animation,+ });+ return animation as unknown as Animation;+ };+});++afterEach(() => {+ Element.prototype.animate = originalAnimate;+ for (const cleanup of cleanups) {+ cleanup();+ }+ vi.restoreAllMocks();+ Reflect.deleteProperty(document, 'elementFromPoint');+ Reflect.deleteProperty(document, 'elementsFromPoint');+ document.body.innerHTML = '';+});++/** The y of a `translate` keyframe, in px. */+const yOf = (frame: Keyframe | undefined) =>+ Number(/(-?[\d.e+-]+)px$/.exec(String(frame?.translate ?? ''))?.[1] ?? 0);++function touch(+ type: 'touchstart' | 'touchend',+ target: EventTarget,+ at: {x: number; y: number},+ time: number,+): void {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const contact = {identifier: 1, clientX: at.x, clientY: at.y, target};+ Object.defineProperty(event, 'changedTouches', {value: [contact]});+ Object.defineProperty(event, 'touches', {+ value: type === 'touchend' ? [] : [contact],+ });+ Object.defineProperty(event, 'timeStamp', {value: time});+ target.dispatchEvent(event);+}++/**+ * Three 60 px rows under an element that opens 120 px, so the rows glide+ * down two rows. Each row has a tap recognizer. Hit tests answer as iOS+ * WebKit does: at each row's glide start, until a style write on the row.+ */+async function mount(presentedHitTesting: 'always' | 'never') {+ document.body.innerHTML =+ '<div id="area"><div id="changed"></div><div id="a"></div><div id="b"></div><div id="c"></div></div>';+ const area = document.getElementById('area') as HTMLElement;+ const changed = document.getElementById('changed') as HTMLElement;+ const rows = ['a', 'b', 'c'].map(+ id => document.getElementById(id) as HTMLElement,+ );+ let opened = 0;+ vi.spyOn(area, 'getBoundingClientRect').mockImplementation(+ () => new DOMRect(0, 0, 400, 600),+ );+ vi.spyOn(changed, 'getBoundingClientRect').mockImplementation(+ () => new DOMRect(0, 0, 400, opened),+ );+ rows.forEach((row, index) =>+ vi+ .spyOn(row, 'getBoundingClientRect')+ .mockImplementation(() => new DOMRect(0, opened + index * 60, 400, 60)),+ );+ const host = new GestureHost(document, {+ clock: new ManualClock(),+ presentedHitTesting,+ });+ const taps: string[] = [];+ for (const row of rows) {+ const tap = new TapGestureRecognizer({name: row.id});+ tap.addTransitionListener((current, _from, to) => {+ if (to === 'ended') {+ taps.push(current.name ?? '');+ }+ });+ cleanups.push(host.attach(row, tap));+ }+ const report = reportLayoutChange(+ createAnimatedLayout(() => area),+ () => changed,+ );+ report.measureBefore();+ opened = 120;+ report.animate();+ await Promise.resolve();+ await Promise.resolve();+ // Each glide at the frame where half of its way is left: row b is drawn+ // over the box where row c started.+ const glides = rows.map(row => {+ const glide = played.find(p => p.element === row) as Played;+ const last = glide.keyframes.length - 1;+ const half = glide.keyframes.findIndex(frame => yOf(frame) >= -60);+ glide.animation.startTime =+ performance.now() - (Number(glide.options.duration) * half) / last;+ return glide;+ });+ const drawnY = (glide: Played, time = performance.now()) => {+ const progress =+ (time - Number(glide.animation.startTime)) /+ Number(glide.options.duration);+ return yOf(+ glide.keyframes[Math.round(progress * (glide.keyframes.length - 1))],+ );+ };+ // Where the engine hit-tests each row: its glide's start until a style+ // write on it, then where it was drawn at that write.+ const resolved = new Map<Element, {write: string; y: number}>();+ const hitY = (index: number) => {+ const row = rows[index];+ const write = row.style.getPropertyValue('--astryx-presented');+ if (write !== '' && resolved.get(row)?.write !== write) {+ resolved.set(row, {write, y: drawnY(glides[index])});+ }+ return resolved.get(row)?.y ?? yOf(glides[index].keyframes[0]);+ };+ const stack = (x: number, y: number): Element[] => [+ ...rows.filter((_, index) => {+ const top = 120 + index * 60 + hitY(index);+ return y >= top && y < top + 60;+ }),+ area,+ document.body,+ ];+ Object.defineProperty(document, 'elementsFromPoint', {+ configurable: true,+ value: stack,+ });+ Object.defineProperty(document, 'elementFromPoint', {+ configurable: true,+ value: (x: number, y: number) => stack(x, y)[0],+ });+ // A row's centre where its glide draws it at `time`.+ const rowCentre = (index: number, time: number) => ({+ x: 200,+ y: 120 + index * 60 + drawnY(glides[index], time) + 30,+ });+ return {rows, taps, rowCentre, stack};+}++describe('a tap on a row an animatedLayout glide moves (iOS WebKit hit-tests it at the glide start)', () => {+ it('reaches the row drawn under the finger', async () => {+ const {taps, rowCentre, stack} = await mount('always');+ // The touch lands now, on the clock the host reads, where row b is drawn.+ const at = performance.now();+ const onB = rowCentre(1, at);+ // The engine sends the touch to the row that started under the finger.+ const native = stack(onB.x, onB.y)[0];+ expect((native as HTMLElement).id).toBe('c');+ touch('touchstart', native, onB, at);+ touch('touchend', native, onB, at + 80);+ expect(taps).toEqual(['b']);+ });++ it('goes to the row that started there with the correction off', async () => {+ const {taps, rowCentre, stack} = await mount('never');+ const at = performance.now();+ const onB = rowCentre(1, at);+ const native = stack(onB.x, onB.y)[0];+ touch('touchstart', native, onB, at);+ touch('touchend', native, onB, at + 80);+ expect(taps).toEqual(['c']);+ });+});diff --git a/packages/core/src/motion/animatedLayout.presented.test.ts b/packages/core/src/motion/animatedLayout.presented.test.tsnew file mode 100644index 0000000000..2c603638d9--- /dev/null+++ b/packages/core/src/motion/animatedLayout.presented.test.ts@@ -0,0 +1,378 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file animatedLayout.presented.test.ts+ * @input vitest (jsdom), the animated-layout module, a recording stand-in for+ * Element.animate and stubbed layout rectangles (jsdom lays nothing out)+ * @output Checks that a running translate glide reports its element to the+ * presented hit-test registry. The cases cover its offset from where iOS+ * WebKit hit-tests it, a touch-down's resolve and its end. A change's+ * glides cost one notice as they start and one as they end, even after a+ * glide in a removed frame ended. A fade or an inert element reports+ * nothing, and a glide whose element left its document loses its report+ * @position Testing; GestureHost's use of the registry is proven in+ * gestures/__tests__/presentedGlide.test.ts+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {+ createAnimatedLayout,+ playLayoutChange,+ reportLayoutChange,+} from './animatedLayout';+import {+ presentedElements,+ presentedOffsetOf,+ resolvePresented,+ watchPresentedElements,+} from './presentation';++interface Played {+ element: Element;+ keyframes: Keyframe[];+ options: KeyframeAnimationOptions;+ cancel: ReturnType<typeof vi.fn>;+ /** Fires the animation's `finish` listeners. */+ finish?: () => void;+ /** Fires the animation's `cancel` listeners. */+ cancelled?: () => void;+ animation?: object;+}++let played: Played[] = [];+let media: Record<string, boolean> = {};+const originalAnimate = Element.prototype.animate;+const originalMatchMedia = window.matchMedia;++beforeEach(() => {+ played = [];+ media = {};+ Element.prototype.animate = function (+ this: Element,+ keyframes: Keyframe[] | PropertyIndexedKeyframes | null,+ options?: number | KeyframeAnimationOptions,+ ) {+ const cancel = vi.fn();+ const listeners: Record<string, (() => void)[]> = {};+ const animation = {+ cancel,+ addEventListener(type: string, listener: () => void) {+ (listeners[type] ??= []).push(listener);+ },+ currentTime: 100,+ };+ played.push({+ element: this,+ keyframes: keyframes as Keyframe[],+ options: options as KeyframeAnimationOptions,+ cancel,+ finish: () => listeners.finish?.forEach(listener => listener()),+ cancelled: () => listeners.cancel?.forEach(listener => listener()),+ animation,+ });+ return animation as unknown as Animation;+ };+ window.matchMedia = (query: string) =>+ ({+ matches: media[query] === true,+ media: query,+ addEventListener() {},+ removeEventListener() {},+ }) as unknown as MediaQueryList;+});++afterEach(async () => {+ // Every glide ends, so no report outlives its test.+ for (const entry of played) {+ entry.finish?.();+ }+ await new Promise(resolve => setTimeout(resolve, 0));+ Element.prototype.animate = originalAnimate;+ window.matchMedia = originalMatchMedia;+ document.body.innerHTML = '';+});++/** Gives `element` a rectangle that follows `phase` (before or after). */+function placeAt(+ element: Element,+ rects: {+ before: [number, number, number, number];+ after?: [number, number, number, number];+ },+ phase: {current: 'before' | 'after'},+) {+ vi.spyOn(element, 'getBoundingClientRect').mockImplementation(() => {+ const [x, y, w, h] =+ phase.current === 'before' || rects.after == null+ ? rects.before+ : rects.after;+ return new DOMRect(x, y, w, h);+ });+}++const flushMicrotasks = async () => {+ await Promise.resolve();+ await Promise.resolve();+};++/** Runs the task that removes the reports of ended glides. */+const nextTask = async () =>+ new Promise(resolve => {+ setTimeout(resolve, 0);+ });++/** An area with a changed element that opens 80 px, and the given HTML. */+function setUp(html: string) {+ document.body.innerHTML = html;+ const area = document.getElementById('area') as HTMLElement;+ const changed = document.getElementById('changed') as HTMLElement;+ const phase: {current: 'before' | 'after'} = {current: 'before'};+ placeAt(area, {before: [0, 0, 400, 600]}, phase);+ placeAt(changed, {before: [0, 0, 400, 0], after: [0, 0, 400, 80]}, phase);+ return {area, changed, phase};+}++function translateOf(entry: Played): {x: number; y: number} {+ const first = String(entry.keyframes[0].translate ?? '');+ const match = /^(-?[\d.e+-]+)px\s+(-?[\d.e+-]+)px/.exec(first);+ return match == null+ ? {x: 0, y: 0}+ : {x: Number(match[1]), y: Number(match[2])};+}++async function runChange(+ layout: ReturnType<typeof createAnimatedLayout> | null,+ changed: Element,+ phase: {current: 'before' | 'after'},+) {+ const report = reportLayoutChange(layout, () => changed);+ report.measureBefore();+ phase.current = 'after';+ report.animate();+ playLayoutChange(layout, changed);+ await flushMicrotasks();+}++describe('a glide in the presented hit-test registry (motion/presentation.ts)', () => {+ /** The translate of keyframe `index` of `entry`, in px. */+ const translateAt = (entry: Played, index: number) =>+ translateOf({...entry, keyframes: entry.keyframes.slice(index)});++ it('reports the element while its translate glides: how far it is drawn from where iOS WebKit hit-tests it', async () => {+ const {area, changed, phase} = setUp(+ '<div id="area"><div id="changed"></div><div id="a"></div></div>',+ );+ const a = document.getElementById('a') as HTMLElement;+ placeAt(a, {before: [0, 0, 400, 40], after: [0, 80, 400, 40]}, phase);+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ const glide = played.find(p => p.element === a) as Played;+ // Hit-tested where the glide starts, which is where it is drawn.+ expect(presentedElements()).toContain(a);+ expect(presentedOffsetOf(a)).toEqual({x: 0, y: 0});+ // Some way into the glide it is drawn that far from its start. The clock+ // stands still, so no time passes between the reads.+ const now = window.performance.now();+ const clock = vi.spyOn(window.performance, 'now').mockReturnValue(now);+ try {+ const index = Math.floor((glide.keyframes.length - 1) / 2);+ const at = index / (glide.keyframes.length - 1);+ (glide.animation as {startTime: number}).startTime =+ now - Number(glide.options.duration) * at;+ const moved = translateAt(glide, index).y - translateOf(glide).y;+ expect(moved).toBeGreaterThan(10);+ expect(presentedOffsetOf(a).y).toBeCloseTo(moved, 6);+ // A touch-down resolves it: one style write, and it is hit-tested there.+ resolvePresented([a]);+ expect(a.style.getPropertyValue('--astryx-presented')).not.toBe('');+ expect(presentedOffsetOf(a).y).toBeCloseTo(0, 6);+ } finally {+ clock.mockRestore();+ }+ // At its end it is hit-tested at its layout again, and a task later its+ // report and the write go.+ glide.finish?.();+ expect(presentedOffsetOf(a)).toEqual({x: 0, y: 0});+ await nextTask();+ expect(presentedElements()).not.toContain(a);+ expect(a.style.getPropertyValue('--astryx-presented')).toBe('');+ });++ it('keeps reporting a retargeted glide: the cancel of the glide it replaced clears nothing', async () => {+ const {area, changed} = setUp(+ '<div id="area"><div id="changed"></div><div id="a"></div></div>',+ );+ const a = document.getElementById('a') as HTMLElement;+ let top = 0;+ vi.spyOn(a, 'getBoundingClientRect').mockImplementation(+ () => new DOMRect(0, top, 400, 40),+ );+ const layout = createAnimatedLayout(() => area);+ let report = reportLayoutChange(layout, () => changed);+ report.measureBefore();+ top = 80;+ report.animate();+ await flushMicrotasks();+ const first = played.find(p => p.element === a) as Played;+ resolvePresented([a]);+ played = [];+ top = 50;+ report = reportLayoutChange(layout, () => changed);+ report.measureBefore();+ top = 120;+ report.animate();+ await flushMicrotasks();+ expect(played.filter(p => p.element === a)).toHaveLength(1);+ first.cancelled?.();+ await nextTask();+ expect(presentedElements()).toContain(a);+ expect(a.style.getPropertyValue('--astryx-presented')).not.toBe('');+ });++ it("tells the registry's watchers once as a change's glides start, and once as they end", async () => {+ const {area, changed, phase} = setUp(+ '<div id="area"><div id="changed"></div><div id="a"></div><div id="b"></div><div id="c"></div></div>',+ );+ for (const [id, y] of [+ ['a', 0],+ ['b', 50],+ ['c', 100],+ ] as const) {+ placeAt(+ document.getElementById(id) as HTMLElement,+ {before: [0, y, 400, 40], after: [0, y + 80, 400, 40]},+ phase,+ );+ }+ let notices = 0;+ const stop = watchPresentedElements(() => {+ notices += 1;+ });+ try {+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ const moving = played.filter(p => p.keyframes[0].translate != null);+ expect(moving).toHaveLength(3);+ expect(notices).toBe(1);+ for (const glide of moving) {+ glide.finish?.();+ }+ await nextTask();+ expect(notices).toBe(2);+ for (const glide of moving) {+ expect(presentedElements()).not.toContain(glide.element);+ }+ } finally {+ stop();+ }+ });++ it('reports no inert element: a closing element or a copy takes no touch', async () => {+ const {area, changed, phase} = setUp(+ '<div id="area"><div id="changed"></div><div id="a" inert></div></div>',+ );+ const a = document.getElementById('a') as HTMLElement;+ placeAt(a, {before: [0, 0, 400, 40], after: [0, 80, 400, 40]}, phase);+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ expect(played.some(p => p.element === a)).toBe(true);+ expect(presentedElements()).not.toContain(a);+ });++ it('reports no element for a motion without travel (a Reduce Motion fade)', async () => {+ media['(prefers-reduced-motion: reduce)'] = true;+ media['(pointer: coarse)'] = true;+ const {area, changed, phase} = setUp(+ '<div id="area"><div id="changed"></div><div id="a"></div></div>',+ );+ const a = document.getElementById('a') as HTMLElement;+ placeAt(a, {before: [0, 0, 400, 40], after: [0, 80, 400, 40]}, phase);+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ expect(played.some(p => p.element === a)).toBe(true);+ expect(played.every(p => p.keyframes[0].translate == null)).toBe(true);+ expect(presentedElements()).not.toContain(a);+ });+ it("removes a later glide's report after a glide in a removed frame ended", async () => {+ const {area, changed, phase} = setUp(+ '<div id="area"><div id="changed"></div><div id="a"></div></div>',+ );+ const a = document.getElementById('a') as HTMLElement;+ placeAt(a, {before: [0, 0, 400, 40], after: [0, 80, 400, 40]}, phase);+ // A glide in a frame ends, and the frame goes before any later task.+ const frame = document.createElement('iframe');+ document.body.append(frame);+ const frameWindow = frame.contentWindow as Window & typeof globalThis;+ frameWindow.Element.prototype.animate = Element.prototype.animate;+ const frameDocument = frame.contentDocument as Document;+ frameDocument.body.innerHTML =+ '<div id="area"><div id="changed"></div><div id="b"></div></div>';+ const frameArea = frameDocument.getElementById('area') as HTMLElement;+ const frameChanged = frameDocument.getElementById('changed') as HTMLElement;+ const b = frameDocument.getElementById('b') as HTMLElement;+ const framePhase: {current: 'before' | 'after'} = {current: 'before'};+ placeAt(frameArea, {before: [0, 0, 400, 600]}, framePhase);+ placeAt(+ frameChanged,+ {before: [0, 0, 400, 0], after: [0, 0, 400, 80]},+ framePhase,+ );+ placeAt(b, {before: [0, 0, 400, 40], after: [0, 80, 400, 40]}, framePhase);+ await runChange(+ createAnimatedLayout(() => frameArea),+ frameChanged,+ framePhase,+ );+ expect(presentedElements()).toContain(b);+ played.find(p => p.element === b)?.finish?.();+ frame.remove();+ // A glide on the page then ends.+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ expect(presentedElements()).toContain(a);+ played.find(p => p.element === a)?.finish?.();+ await nextTask();+ await nextTask();+ // Booleans: a matcher would print the closed frame's element.+ expect(presentedElements().includes(a)).toBe(false);+ expect(presentedElements().includes(b)).toBe(false);+ });++ it('removes the report of a glide whose element left the document before it ended', async () => {+ const {area, changed, phase} = setUp(+ '<div id="area"><div id="changed"></div><div id="a"></div><div id="b"></div></div>',+ );+ const a = document.getElementById('a') as HTMLElement;+ const b = document.getElementById('b') as HTMLElement;+ placeAt(a, {before: [0, 0, 400, 40], after: [0, 80, 400, 40]}, phase);+ placeAt(b, {before: [0, 50, 400, 40], after: [0, 130, 400, 40]}, phase);+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ expect(presentedElements().includes(a)).toBe(true);+ expect(presentedElements().includes(b)).toBe(true);+ // Row a leaves the document mid-glide; row b's glide then ends.+ a.remove();+ played.find(p => p.element === b)?.finish?.();+ await nextTask();+ expect(presentedElements().includes(a)).toBe(false);+ expect(presentedElements().includes(b)).toBe(false);+ });+});diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.tsindex 3364d7157e..e6b682ae59 100644--- a/packages/core/src/motion/animatedLayout.ts+++ b/packages/core/src/motion/animatedLayout.ts@@ -92,6 +92,12 @@ import {import {readThemeTiming, readThemeTokenText} from './themeTiming';import {themeReducesMotion} from '../privateAttributes/reducedMotion.stylex';import {reducedMotionCrossFade} from './uikit/timing';+import {+ batchPresented,+ clearPresentedResolve,+ registerPresentedOffset,+ writePresentedResolve,+} from './presentation';/** Below this many pixels a shift is not worth a move. */const MIN_SHIFT_PX = 0.5;@@ -210,16 +216,179 @@ function round(value: number): number {// Playing// ---------------------------------------------------------------------------+/** The glide each element reports now, so that only its end clears it. */+const presentedGlides = new WeakMap<Element, object>();++/** A glide's report in the presented hit-test registry. */+interface GlideReport {+ readonly element: Element;+ /** Removes the report. A second call does nothing. */+ readonly remove: () => void;+}++const glideReports = new Set<GlideReport>();++/** The reports of ended glides, removed together in a later task. */+const endedReports: GlideReport[] = [];++/**+ * Removes the reports of ended glides with one notice to the registry's+ * watchers. A glide in a closed window or out of its document never ends, so+ * its report goes here too.+ */+function removeEndedReports(): void {+ if (endedReports.length === 0) {+ return;+ }+ batchPresented(() => {+ for (const report of endedReports.splice(0)) {+ report.remove();+ }+ for (const report of [...glideReports]) {+ const {element} = report;+ if (!element.isConnected || element.ownerDocument.defaultView == null) {+ report.remove();+ }+ }+ });+}++/** Each keyframe's `translate` in px at its offset, or null if one has none. */+function translatesOf(+ keyframes: Keyframe[],+): {at: number; x: number; y: number}[] | null {+ const points: {at: number; x: number; y: number}[] = [];+ for (const [index, frame] of keyframes.entries()) {+ const match = /^(-?[\d.e+-]+)px (-?[\d.e+-]+)px$/.exec(+ String(frame.translate ?? ''),+ );+ if (match == null) {+ return null;+ }+ points.push({+ at: frame.offset ?? index / Math.max(1, keyframes.length - 1),+ x: Number(match[1]),+ y: Number(match[2]),+ });+ }+ return points.length > 0 ? points : null;+}++/**+ * Reports `element` to the presented hit-test registry while its `translate`+ * glide runs. iOS WebKit hit-tests the element where the glide started. So+ * the gesture host resolves it at touch-down and lands the touch on what is+ * drawn. `scale` is its ancestors' scale. An inert element, such as a swap's+ * copy or a closing element, takes no touch, so it is not reported.+ */+function presentGlide(+ element: Element,+ animation: Animation,+ keyframes: Keyframe[],+ options: KeyframeAnimationOptions,+ scale: {readonly x: number; readonly y: number},+): void {+ const view = element.ownerDocument.defaultView;+ const durationMs = Number(options.duration);+ const points =+ (options.easing ?? 'linear') === 'linear' && options.delay == null+ ? translatesOf(keyframes)+ : null;+ if (+ view == null ||+ points == null ||+ !(durationMs > 0) ||+ !('style' in element) ||+ element.closest('[inert]') != null+ ) {+ return;+ }+ const styled = element as Element & ElementCSSInlineStyle;+ const now = () => view.performance.now();+ // The translate drawn at `time`: the keyframes are linear between samples.+ const drawnAt = (time: number) => {+ const start = animation.startTime;+ const progress =+ start == null+ ? 0+ : Math.min(1, Math.max(0, (time - Number(start)) / durationMs));+ let next = 1;+ while (next < points.length - 1 && points[next].at < progress) {+ next += 1;+ }+ const from = points[next - 1] ?? points[0];+ const to = points[next] ?? from;+ const span = to.at - from.at;+ const part =+ span > 0 ? Math.min(1, Math.max(0, (progress - from.at) / span)) : 1;+ return {+ x: (from.x + (to.x - from.x) * part) * scale.x,+ y: (from.y + (to.y - from.y) * part) * scale.y,+ };+ };+ let hitTested = drawnAt(now());+ let isEnded = false;+ let isRemoved = false;+ const glide = {};+ presentedGlides.set(element, glide);+ const unregister = registerPresentedOffset(element, {+ // At its end the engine hit-tests the element at its layout again.+ offset: (time = now()) => {+ if (isEnded) {+ return {x: 0, y: 0};+ }+ const drawn = drawnAt(time);+ return {x: drawn.x - hitTested.x, y: drawn.y - hitTested.y};+ },+ resolve: () => {+ if (!isEnded) {+ writePresentedResolve(styled);+ hitTested = drawnAt(now());+ }+ },+ });+ const report: GlideReport = {+ element,+ remove: () => {+ if (isRemoved) {+ return;+ }+ isRemoved = true;+ glideReports.delete(report);+ unregister();+ if (presentedGlides.get(element) === glide) {+ presentedGlides.delete(element);+ clearPresentedResolve(styled);+ }+ },+ };+ glideReports.add(report);+ const end = () => {+ if (isEnded) {+ return;+ }+ isEnded = true;+ endedReports.push(report);+ // This module's own timer: a closed frame's timer never fires. The glides+ // of one change end in one frame, so the first task removes them all.+ setTimeout(removeEndedReports, 0);+ };+ animation.addEventListener?.('finish', end);+ animation.addEventListener?.('cancel', end);+}+/*** Play `keyframes` on `element`. Every option here (linear easing over sampled* keyframes, replace composition) is one any Web Animations engine takes, so* a failure means no Web Animations at all: the change then lands at once.+ * `scale` is the element's ancestors' scale, for a `translate` glide.*/function safeAnimate(element: Element,keyframes: Keyframe[],options: KeyframeAnimationOptions,change?: ChangeStart,+ scale: {readonly x: number; readonly y: number} = {x: 1, y: 1},): Animation | null {if (typeof (element as HTMLElement).animate !== 'function') {return null;@@ -259,6 +428,9 @@ function safeAnimate(});}}+ if (options.pseudoElement == null) {+ presentGlide(element, animation, keyframes, options, scale);+ }return animation;}@@ -1352,6 +1524,7 @@ function flush(batch: Batch): void {}),{duration: durationMs, easing: 'linear'},change,+ scale,);if (animation != null) {const glide: Glide = {@@ -1471,8 +1644,9 @@ export function reportLayoutChange(}if (!batch.scheduled) {batch.scheduled = true;- // After every layout effect of this commit, before paint.- queueMicrotask(() => flush(batch));+ // After every layout effect of this commit, before paint, with one+ // registry notice for all the glides it starts.+ queueMicrotask(() => batchPresented(() => flush(batch)));}return true;},diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.tsindex 2f46072797..2a7aaa49ce 100644--- a/packages/core/src/motion/animator.ts+++ b/packages/core/src/motion/animator.ts@@ -184,7 +184,12 @@import {cubicBezier} from './bezier';import {LATE_START_MS} from './frameBlock';import {solveSpring, toSpring, type SpringDescription} from './spring';-import {registerPresentedOffset, type PresentedSource} from './presentation';+import {+ clearPresentedResolve,+ registerPresentedOffset,+ type PresentedSource,+ writePresentedResolve,+} from './presentation';import {resolveMotion} from './resolveMotion';import {reducedMotionCrossFade,@@ -750,9 +755,6 @@ export const PROMOTION_LINGER_MS = 500;type Channel = 'translate' | 'rotate' | 'scale' | 'opacity';-/** The custom property whose writes make WebKit resolve a moving element. */-const RESOLVE_PROPERTY = '--astryx-presented';-const CHANNELS: Record<Channel, ReadonlyArray<MotionProperty>> = {translate: ['x', 'y'],rotate: ['rotate'],@@ -1026,8 +1028,6 @@ export function createMotionEngine(* moves it: where the animation started, or where a `resolve` left it.*/let hitTested = {x: 0, y: 0};- /** Counts the style writes that make WebKit resolve the element again. */- let resolutions = 0;let unpresent: (() => void) | null = null;/** Channels promoted to the element's compositing layer (will-change). */const promoted = new Set<Channel>();@@ -1261,8 +1261,7 @@ export function createMotionEngine(// Any style write makes WebKit resolve the element's transform again,// to the value drawn now, where it then stays (iOS 26.2: in the same// task); a custom property changes nothing else.- resolutions += 1;- target.style.setProperty(RESOLVE_PROPERTY, String(resolutions));+ writePresentedResolve(target);hitTested = {x: drawnTranslate('x', time), y: drawnTranslate('y', time)};},};@@ -1276,7 +1275,7 @@ export function createMotionEngine(unpresent?.();unpresent = null;if (presented instanceof HTMLElement) {- presented.style.removeProperty(RESOLVE_PROPERTY);+ clearPresentedResolve(presented);}presented = element;if (element != null) {diff --git a/packages/core/src/motion/presentation.ts b/packages/core/src/motion/presentation.tsindex a443cf99cf..8edca42f5f 100644--- a/packages/core/src/motion/presentation.ts+++ b/packages/core/src/motion/presentation.ts@@ -5,12 +5,13 @@* @input Animators reporting, while a translate runs on the compositor, how* far their element is drawn from where the engine hit-tests it, and how* to make the engine hit-test it where it is drawn- * @output Exports registerPresentedOffset, presentedElements,- * presentedOffsetOf, resolvePresented and watchPresentedElements: the- * registry the gesture host reads at touch-down to send a touch to what is- * drawn, and follows to keep a drag on a moving element blocking- * @position Motion foundation (DOM, no React). Written by animator.ts, read- * by gestures/GestureHost.ts; internal to core+ * @output The registry that the gesture host reads at touch-down, to send a+ * touch to what is drawn. The host also follows it to keep a drag on a+ * moving element blocking. Exports: registerPresentedOffset,+ * batchPresented, presentedElements, presentedOffsetOf, resolvePresented,+ * watchPresentedElements and the resolve write+ * @position Motion foundation (DOM, no React). Written by animator.ts and+ * animatedLayout.ts, read by gestures/GestureHost.ts; internal to core** iOS WebKit hit-tests an element that a Web Animations transform moves on* the compositor where the animation STARTED: it keeps the transform it@@ -61,9 +62,16 @@ const ZERO: PresentedOffset = {x: 0, y: 0};const sources = new Map<Element, PresentedSource>();const watchers = new Set<() => void>();+// Inside batchPresented, a change waits for the batch's end.+let batchDepth = 0;+let isChanged = false;/** Tell every watcher the reported elements changed; one's throw stops none. */function notifyWatchers(): void {+ if (batchDepth > 0) {+ isChanged = true;+ return;+ }for (const watcher of [...watchers]) {try {watcher();@@ -75,6 +83,24 @@ function notifyWatchers(): void {}}+/**+ * Runs `apply`, which reports elements or removes reports, and tells the+ * watchers once, at its end, when the reported elements changed. So the+ * moves of one layout change cost one notice.+ */+export function batchPresented(apply: () => void): void {+ batchDepth += 1;+ try {+ apply();+ } finally {+ batchDepth -= 1;+ if (batchDepth === 0 && isChanged) {+ isChanged = false;+ notifyWatchers();+ }+ }+}+/*** Call `listener` each time an element starts or stops being reported.* Returns the function that stops it.@@ -139,6 +165,25 @@ export function presentedOffsetOf(return {x, y};}+/** The custom property whose writes make WebKit resolve a moving element. */+const RESOLVE_PROPERTY = '--astryx-presented';++/**+ * Makes iOS WebKit resolve `element`'s transform again, to the value drawn+ * now: one write of a value the property does not have yet. The animator and+ * the animated layout both write it, so it counts up from the element's own+ * last value.+ */+export function writePresentedResolve(element: ElementCSSInlineStyle): void {+ const last = Number(element.style.getPropertyValue(RESOLVE_PROPERTY)) || 0;+ element.style.setProperty(RESOLVE_PROPERTY, String(last + 1));+}++/** Removes the resolve write from `element`. */+export function clearPresentedResolve(element: ElementCSSInlineStyle): void {+ element.style.removeProperty(RESOLVE_PROPERTY);+}+/*** Makes the engine hit-test each of `elements` where it is drawn now; the* next hit test (an `elementFromPoint`) flushes the writes.