Skip to content

Commit 29ee7a9

Browse files
fix: re-measure after a parent's CSS transition ends (#227) (#250)
* fix: account for a parent moved by a CSS transform Children's cached positions went stale when their parent moved without them reflowing (e.g. a menu sliding in with transform/translate), so the next mutation animated siblings — and the parent itself — from where they used to be, and removed children faded out at their old on-screen spot. Each child now remembers where its parent was when it was measured; on a mutation the cached coordinates are shifted by however far the parent moved since. The parent's own cached position is updated too (keeping its size), unless it's nested inside another animated parent. Closes #227 * fix: only realign for transform movement (review of #250) Measuring the parent after a change couldn't tell a transform move from a move caused by the change itself, so bottom-anchored (toast) and centered (modal) parents made existing children jump, and a same-render reflow snapped instead of sliding. Now only the parent's transform displacement counts: its on-screen position minus its layout position and ancestor scroll offsets (scroll above a fixed ancestor ignored). Reflow, anchoring and resizing change both equally, so they no longer shift anything. The parent's own cached position is shifted by the same transform delta instead of being overwritten. Nothing is recorded or realigned while auto-animate itself animates the parent or an ancestor, so its own FLIP transforms aren't mistaken for user transforms. The parent's displacement is cached per task (one measurement for many children). Adds regression tests for bottom-anchored and centered parents. * fix: re-measure after a parent's CSS transition instead of realigning Replaces the mutation-time realignment (two reviews found it regressed percentage transforms, centered/anchored parents, bordered nested parents and re-parenting) with a much smaller fix for #227: when a CSS transition or animation ends on an animated parent or one of its ancestors, re-measure the parent and its children. Mutation handling is back to exactly master's. Also ignore GitHub API rate-limit errors in the e2e console checks (the docs fetch the star count). Closes #227 * perf: coalesce post-transition re-measures; ignore paint-only transitions Review of #250: a dark-mode toggle with `* { transition: color, ... }` fired ~80k transitionend events, each re-arming updatePos for every child. Skip paint-only properties (they can't move anything) and flush queued parents once per frame. Also read the target via composedPath() so it works inside shadow roots.
1 parent 0d4fa52 commit 29ee7a9

4 files changed

Lines changed: 181 additions & 3 deletions

File tree

‎src/index.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,61 @@ if (supportedBrowser) {
285285
scrollX = window.scrollX
286286
})
287287
resize.observe(root)
288+
// A CSS transition/animation on an animated parent (or an ancestor) can move
289+
// its children without any reflow or resize — e.g. a menu sliding in with
290+
// `transform`. Re-measure once it ends, so the next change doesn't animate
291+
// children from where they used to be (formkit/auto-animate#227). These
292+
// events only fire for CSS transitions/animations, never for our own WAAPI
293+
// animations.
294+
document.addEventListener("transitionend", remeasureAfterMove, true)
295+
document.addEventListener("animationend", remeasureAfterMove, true)
288296
}
297+
298+
/**
299+
* Transitions of these properties only repaint, so they can't move anything.
300+
*/
301+
const paintOnly =
302+
/^(color|background|opacity|box-shadow|text-shadow|outline|filter|backdrop-filter|fill|stroke|border-color|caret-color|text-decoration|visibility)/
303+
304+
/**
305+
* Animated parents waiting to be re-measured after a CSS transition/animation.
306+
*/
307+
const pendingRemeasure = new Set<Element>()
308+
309+
/**
310+
* Queue a re-measure of every animated parent that is (or is inside) the
311+
* element whose CSS transition or animation just ended. Re-measuring is
312+
* coalesced into one pass per frame, so event storms (e.g. a dark-mode toggle
313+
* with `* { transition: ... }`) stay cheap.
314+
* @param e - The transitionend/animationend event.
315+
*/
316+
function remeasureAfterMove(e: Event) {
317+
if (
318+
e.type === "transitionend" &&
319+
paintOnly.test((e as TransitionEvent).propertyName)
320+
)
321+
return
322+
// composedPath() sees through shadow roots (e.target is retargeted).
323+
const target = (e.composedPath?.()[0] ?? e.target) as unknown
324+
if (!(target instanceof Element)) return
325+
const wasEmpty = !pendingRemeasure.size
326+
parents.forEach((parent) => {
327+
if (target === parent || target.contains(parent)) pendingRemeasure.add(parent)
328+
})
329+
if (wasEmpty && pendingRemeasure.size) {
330+
requestAnimationFrame(() => {
331+
const queued = [...pendingRemeasure]
332+
pendingRemeasure.clear()
333+
queued.forEach((parent) => {
334+
if (!parents.has(parent)) return
335+
forEach(parent, (el) => {
336+
if (coords.has(el)) updatePos(el, false)
337+
})
338+
})
339+
})
340+
}
341+
}
342+
289343
/**
290344
* Retrieves all the elements that may have been affected by the last mutation
291345
* including ones that have been removed and are no longer in the DOM.

‎tests/e2e/moved-parent.spec.ts‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import { test, expect } from '@playwright/test'
2+
import { fileURLToPath } from 'node:url'
3+
4+
const fixtureUrl = `/@fs${fileURLToPath(new URL('../fixtures/moved-parent.html', import.meta.url))}`
5+
const moduleUrl = `/@fs${fileURLToPath(new URL('../../src/index.ts', import.meta.url))}`
6+
7+
// formkit/auto-animate#227: children's cached positions went stale when the
8+
// parent moved via a CSS transform, so the next mutation animated siblings
9+
// from where they *used* to be on screen.
10+
test('siblings animate only their own movement after the parent was moved by a transform', async ({ page }) => {
11+
await page.goto(fixtureUrl)
12+
const start = await page.evaluate(async (moduleUrl) => {
13+
const { default: autoAnimate } = await import(moduleUrl)
14+
const list = document.getElementById('list')!
15+
autoAnimate(list, { duration: 1000 })
16+
// Let auto-animate take its (debounced) initial measurements.
17+
await new Promise((r) => setTimeout(r, 1300))
18+
// Slide the parent back into place (like a menu opening).
19+
// Slide the parent into place with a CSS transition (like a menu
20+
// opening) and let it finish.
21+
list.style.transition = 'transform 150ms'
22+
list.style.transform = 'translateX(0px)'
23+
await new Promise((r) => list.addEventListener('transitionend', r, { once: true }))
24+
await new Promise((r) => setTimeout(r, 30))
25+
// Remove the first item: B and C should only move up by 40px.
26+
document.getElementById('a')!.remove()
27+
await new Promise(requestAnimationFrame)
28+
await new Promise(requestAnimationFrame)
29+
const anim = document.getElementById('c')!.getAnimations()[0] as Animation
30+
const frames = (anim.effect as KeyframeEffect).getKeyframes()
31+
return String(frames[0].transform)
32+
}, moduleUrl)
33+
// translate(dx, dy) at the start of C's move animation
34+
const m = start.match(/translate\((-?[\d.]+)px,\s*(-?[\d.]+)px\)/)
35+
expect(m, start).not.toBeNull()
36+
const [dx, dy] = [Number(m![1]), Number(m![2])]
37+
expect(Math.abs(dx)).toBeLessThan(2) // was ~300 (the parent's old offset)
38+
expect(dy).toBeGreaterThan(30) // it really moved up ~40px
39+
})
40+
41+
test('a removed child fades out in place after the parent was moved by a transform', async ({ page }) => {
42+
await page.goto(fixtureUrl)
43+
const result = await page.evaluate(async (moduleUrl) => {
44+
const { default: autoAnimate } = await import(moduleUrl)
45+
const list = document.getElementById('list')!
46+
autoAnimate(list, { duration: 1000 })
47+
await new Promise((r) => setTimeout(r, 1300))
48+
// Slide the parent into place with a CSS transition (like a menu
49+
// opening) and let it finish.
50+
list.style.transition = 'transform 150ms'
51+
list.style.transform = 'translateX(0px)'
52+
await new Promise((r) => list.addEventListener('transitionend', r, { once: true }))
53+
await new Promise((r) => setTimeout(r, 30))
54+
const before = document.getElementById('b')!.getBoundingClientRect()
55+
document.getElementById('b')!.remove()
56+
await new Promise(requestAnimationFrame)
57+
await new Promise(requestAnimationFrame)
58+
// auto-animate re-inserts the removed node while it animates out
59+
const ghost = document.getElementById('b')
60+
const during = ghost?.getBoundingClientRect()
61+
// Compare centers: the exit animation scales around the center.
62+
const center = (r: DOMRect) => ({ x: r.x + r.width / 2, y: r.y + r.height / 2 })
63+
return { before: center(before), during: during && center(during) }
64+
}, moduleUrl)
65+
expect(result.during).toBeTruthy()
66+
expect(Math.abs(result.during!.x - result.before.x)).toBeLessThan(2)
67+
expect(Math.abs(result.during!.y - result.before.y)).toBeLessThan(2)
68+
})
69+
70+
// Parents that move *because of* the change itself (anchored to the bottom, or
71+
// centered) must not be mistaken for a transform move (review of #250).
72+
for (const [name, html] of [
73+
[
74+
'bottom-anchored (toast stack)',
75+
'<ul id="p" style="position:fixed;bottom:0;right:0;margin:0;padding:0;list-style:none;width:200px"><li id="a" style="height:40px">A</li><li id="b" style="height:40px">B</li></ul>',
76+
],
77+
[
78+
'vertically centered (modal)',
79+
'<div style="height:900px;display:flex;align-items:center;justify-content:center"><ul id="p" style="margin:0;padding:0;list-style:none;width:200px"><li id="a" style="height:40px">A</li><li id="b" style="height:40px">B</li></ul></div>',
80+
],
81+
] as const) {
82+
test(`existing children don't jump when appending to a ${name} parent`, async ({ page }) => {
83+
await page.goto(fixtureUrl)
84+
const offsets = await page.evaluate(
85+
async ({ moduleUrl, html }) => {
86+
const { default: autoAnimate } = await import(moduleUrl)
87+
document.body.innerHTML = html
88+
const parent = document.getElementById('p')!
89+
autoAnimate(parent, { duration: 1000 })
90+
await new Promise((r) => setTimeout(r, 1300))
91+
const before = ['a', 'b'].map((id) => document.getElementById(id)!.getBoundingClientRect().top)
92+
const li = document.createElement('li')
93+
li.style.height = '100px'
94+
parent.append(li)
95+
await new Promise(requestAnimationFrame)
96+
await new Promise(requestAnimationFrame)
97+
document.getAnimations().forEach((a) => {
98+
a.pause()
99+
a.currentTime = 0
100+
})
101+
return ['a', 'b'].map((id, i) => document.getElementById(id)!.getBoundingClientRect().top - before[i])
102+
},
103+
{ moduleUrl, html }
104+
)
105+
for (const offset of offsets) expect(Math.abs(offset)).toBeLessThan(2)
106+
})
107+
}

‎tests/e2e/utils.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,15 @@ import { expect, Page } from '@playwright/test'
33
export async function assertNoConsoleErrors(page: Page) {
44
const errors: string[] = []
55
page.on('console', (msg) => {
6-
if (msg.type() === 'error') {
7-
errors.push(msg.text())
8-
}
6+
if (msg.type() !== 'error') return
7+
// The docs fetch the repo's star count from the GitHub API; a rate limit
8+
// (403) there is unrelated to auto-animate.
9+
if (
10+
msg.text().startsWith('Failed to load resource') &&
11+
msg.location().url.startsWith('https://api.github.com/')
12+
)
13+
return
14+
errors.push(msg.text())
915
})
1016
// Give tests time to run interactions before asserting later
1117
return () => expect(errors, `Console errors: \n${errors.join('\n')}`).toEqual([])

‎tests/fixtures/moved-parent.html‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head><meta charset="utf-8"><title>Moved parent</title></head>
4+
<body style="margin: 0">
5+
<ul id="list" style="margin: 0; padding: 0; list-style: none; transform: translateX(300px)">
6+
<li id="a" style="height: 40px">A</li>
7+
<li id="b" style="height: 40px">B</li>
8+
<li id="c" style="height: 40px">C</li>
9+
</ul>
10+
</body>
11+
</html>

0 commit comments

Comments
 (0)