Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 69 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,8 @@ if (supportedBrowser) {
root = document.documentElement
mutations = new MutationObserver(handleMutations)
resize = new ResizeObserver(handleResizes)
scrollY = window.scrollY
scrollX = window.scrollX
window.addEventListener("scroll", () => {
scrollY = window.scrollY
scrollX = window.scrollX
Expand Down Expand Up @@ -643,13 +645,50 @@ function ended(el: Element, action: AutoAnimateAction, opts = getOptions(el)) {
if (!isPlugin(opts)) opts.onAnimationEnd?.(el, action)
}

/**
* How far the page was scrolled by the browser itself since the last scroll
* event, which is what CSS scroll anchoring does when content is inserted or
* removed above the viewport (Chrome, Firefox). Scroll events are dispatched a
* frame later, so at mutation time the event-tracked position still reflects
* where the user had scrolled. Only for elements scrolled by the page itself
* (nested scroll containers are measured relative to themselves).
*/
function anchorShift(el: Element): { x: number; y: number } {
return anchorShiftFrom(el.parentElement)
}

/**
* anchorShift, starting from a given parent (for detached elements).
*/
function anchorShiftFrom(parent: Element | null): { x: number; y: number } {
let p = parent
while (p && p !== root) {
if (p.scrollTop || p.scrollLeft) return { x: 0, y: 0 }
p = p.parentElement
}
return { x: window.scrollX - scrollX, y: window.scrollY - scrollY }
}

/**
* Putting a removed element back (to animate it out) can make some browsers
* re-scroll after they already scroll-anchored the removal. Return the page to
* the anchored position so visible content keeps its spot.
*/
function keepAnchoredScroll(x: number, y: number) {
if (window.scrollX === x && window.scrollY === y) return
const before = root.style.scrollBehavior
root.style.scrollBehavior = "auto"
window.scrollTo(x, y)
root.style.scrollBehavior = before
}

/**
* The element in question is remaining in the DOM.
* @param el - Element to flip
* @returns
*/
function remain(el: Element) {
const oldCoords = coords.get(el)
let oldCoords = coords.get(el)
const newCoords = getCoords(el)
if (!isEnabled(el) || !allowed(el, "remain")) return coords.set(el, newCoords)
if (isOffscreen(el)) {
Expand All @@ -660,6 +699,16 @@ function remain(el: Element) {
}
let animation: Animation
if (!oldCoords) return
// If scroll anchoring moved the page, items that kept their on-screen spot
// didn't visually move: compare against where they were on screen (#222).
const shift = anchorShift(el)
if (shift.x || shift.y) {
oldCoords = {
...oldCoords,
top: oldCoords.top + shift.y,
left: oldCoords.left + shift.x,
}
}
const pluginOrOptions = getOptions(el)
if (typeof pluginOrOptions !== "function") {
let deltaLeft = oldCoords.left - newCoords.left
Expand Down Expand Up @@ -913,6 +962,17 @@ function remove(el: Element) {
Object.defineProperty(el, DEL, { value: true, configurable: true })
const finalX = window.scrollX
const finalY = window.scrollY
// Measured before the element is put back (which can re-trigger anchoring).
const removalShift = anchorShiftFrom(
(next?.parentNode as Element | null) ??
(prev?.parentNode as Element | null) ??
getTarget(el) ??
null,
)
// Never let the leaving element serve as a scroll anchor: putting it back
// (briefly in flow, then absolute) would make the browser re-scroll (#222).
if (el instanceof HTMLElement || el instanceof SVGElement)
el.style.overflowAnchor = "none"

if (
next &&
Expand All @@ -930,7 +990,12 @@ function remove(el: Element) {
const [top, left, width, height] = deletePosition(el)
const optionsOrPlugin = getOptions(el)
const oldCoords = coords.get(el)!
if (finalX !== scrollX || finalY !== scrollY) {
// An element that was entirely above the viewport moved the page through
// CSS scroll anchoring (visible content kept its spot): don't undo that
// (#222). adjustScroll is for removals that made the page shorter.
const wasAboveViewport =
removalShift.y !== 0 && oldCoords.top + oldCoords.height <= scrollY
if ((finalX !== scrollX || finalY !== scrollY) && !wasAboveViewport) {
adjustScroll(el, finalX, finalY, optionsOrPlugin)
}

Expand All @@ -945,6 +1010,7 @@ function remove(el: Element) {
pointerEvents: "none",
transformOrigin: "center",
zIndex: "100",
overflowAnchor: "none",
}

if (!isPlugin(optionsOrPlugin)) {
Expand Down Expand Up @@ -983,6 +1049,7 @@ function remove(el: Element) {
animation = new Animation(keyframes)
animation.play()
}
if (wasAboveViewport) keepAnchoredScroll(finalX, finalY)
animations.set(el, animation)
animation.addEventListener(
"finish",
Expand Down
73 changes: 73 additions & 0 deletions tests/e2e/scroll-anchoring-regressions.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { test, expect } from '@playwright/test'
import { fileURLToPath } from 'node:url'

const fixture = `/@fs${fileURLToPath(new URL('../fixtures/removal.html', import.meta.url))}`
const moduleUrl = process.env.AA_MASTER_MODULE || `/@fs${fileURLToPath(new URL('../../src/index.ts', import.meta.url))}`

type Scenario = 'bottom' | 'partial-remove' | 'pending-scroll' | 'partial-insert' | 'nested' | 'initial-scroll' | 'smooth'

for (const scenario of ['bottom', 'partial-remove', 'pending-scroll', 'partial-insert', 'nested', 'initial-scroll', 'smooth'] as Scenario[]) {
test(`scroll anchoring regression: ${scenario}`, async ({ page }, info) => {
await page.emulateMedia({ reducedMotion: 'no-preference' })
await page.goto(fixture)
const result = await page.evaluate(async ({ moduleUrl, scenario }) => {
const rows = Array.from({ length: 12 }, (_, i) => `<li id="r${i}" style="height:100px;list-style:none">${i}</li>`).join('')
const list = `<ul id="list" style="margin:0;padding:0">${rows}</ul>`
document.body.style.margin = '0'
document.body.innerHTML = scenario === 'bottom' ? list : scenario === 'nested'
? `<div id="scroller" style="height:400px;overflow:auto">${list}</div>`
: `<div style="height:400px"></div>${list}<div style="height:2000px"></div>`
const ul = document.getElementById('list')!
const scroller = document.getElementById('scroller')
if (scenario === 'smooth') document.documentElement.style.scrollBehavior = 'smooth'
const instantScroll = (y: number) => window.scrollTo({ top: y, behavior: 'instant' })
if (scenario === 'initial-scroll') instantScroll(700)
const { default: autoAnimate } = (await import(moduleUrl)) as typeof import('../../src/index')
autoAnimate(ul, { duration: 600 })
if (scenario === 'nested') scroller!.scrollTop = 250
else if (scenario === 'bottom') instantScroll(document.documentElement.scrollHeight)
else if (scenario !== 'initial-scroll') instantScroll(scenario.startsWith('partial') ? 450 : 700)
await new Promise((resolve) => setTimeout(resolve, 400))
const watched = document.getElementById(scenario === 'bottom' ? 'r5' : scenario === 'nested' ? 'r5' : 'r6')!
if (scenario === 'pending-scroll') instantScroll(750)
const before = watched.getBoundingClientRect().top
if (scenario === 'bottom') document.getElementById('r11')!.remove()
else if (scenario === 'partial-remove' || scenario === 'nested') document.getElementById('r0')!.remove()
else {
const row = document.createElement('li')
row.style.cssText = 'height:100px;list-style:none'
ul.prepend(row)
}
const tops: number[] = []
const until = performance.now() + 800
while (performance.now() < until) {
await new Promise((resolve) => requestAnimationFrame(resolve))
tops.push(watched.getBoundingClientRect().top)
}
return { before, tops, scroll: window.scrollY }
}, { moduleUrl, scenario })
const { before, tops } = result
// A clamp and partial removal may move the row during the animation,
// but must start from its previous viewport position (as master does).
if (scenario === 'bottom' || scenario === 'partial-remove') {
expect(Math.abs(tops[0] - before), JSON.stringify(result)).toBeLessThanOrEqual(2)
if (info.project.name === 'webkit') {
const direction = scenario === 'bottom' ? 1 : -1
for (let i = 1; i < tops.length; i++)
expect(direction * (tops[i] - tops[i - 1]), JSON.stringify(result)).toBeGreaterThanOrEqual(-2)
}
} else if (scenario === 'nested' && info.project.name === 'webkit') {
expect(Math.abs(tops[0] - before), JSON.stringify(result)).toBeLessThanOrEqual(2)
for (let i = 1; i < tops.length; i++)
expect(tops[i], JSON.stringify(result)).toBeLessThanOrEqual(tops[i - 1] + 2)
} else if (info.project.name !== 'webkit') {
for (const top of tops) expect(Math.abs(top - before), JSON.stringify(result)).toBeLessThanOrEqual(2)
} else {
// Without scroll anchoring, insertion moves the row down monotonically.
for (let i = 0; i < tops.length; i++) {
expect(tops[i], JSON.stringify(result)).toBeGreaterThanOrEqual(before - 2)
if (i) expect(tops[i], JSON.stringify(result)).toBeGreaterThanOrEqual(tops[i - 1] - 2)
}
}
})
}
71 changes: 71 additions & 0 deletions tests/e2e/scroll-anchoring.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { test, expect } from '@playwright/test'
import { fileURLToPath } from 'node:url'

const fixtureUrl = `/@fs${fileURLToPath(new URL('../fixtures/removal.html', import.meta.url))}`
const moduleUrl = `/@fs${fileURLToPath(new URL('../../src/index.ts', import.meta.url))}`

// #222: inserting above the viewport makes Chrome/Firefox scroll-anchor the
// page so visible items keep their on-screen spot. They must not then animate
// from "above" (jump up and slide back down).
test('visible items stay put when content is inserted above the viewport', async ({ page }) => {
await page.emulateMedia({ reducedMotion: 'no-preference' })
await page.goto(fixtureUrl)
const r = await page.evaluate(async (moduleUrl) => {
const { default: autoAnimate } = (await import(moduleUrl)) as typeof import('../../src/index')
document.body.innerHTML = `<div style="height:400px"></div><ul id="l" style="margin:0;padding:0">${'abcdefgh'
.split('')
.map((c) => `<li id="${c}" style="height:40px;list-style:none">${c}</li>`)
.join('')}</ul><div style="height:2000px"></div>`
const ul = document.getElementById('l')!
autoAnimate(ul, { duration: 600 })
window.scrollTo(0, 500) // a, b, c are above the viewport; the rest visible
await new Promise((res) => setTimeout(res, 300)) // let scroll events + measurements settle
const watched = document.getElementById('f')!
const before = watched.getBoundingClientRect().top
const li = document.createElement('li')
li.id = 'new'
li.style.cssText = 'height:40px;list-style:none'
ul.prepend(li)
const tops: number[] = []
for (let i = 0; i < 8; i++) {
await new Promise((res) => requestAnimationFrame(res))
tops.push(Math.round(watched.getBoundingClientRect().top))
}
return { before: Math.round(before), tops, scrolled: Math.round(window.scrollY) }
}, moduleUrl)
const anchored = test.info().project.name !== 'webkit' // WebKit has no scroll anchoring
for (const top of r.tops) {
if (anchored) expect(Math.abs(top - r.before)).toBeLessThanOrEqual(1)
else expect(top).toBeGreaterThanOrEqual(r.before - 1) // only ever moves down toward its new spot
}
})

test('visible items stay put when content is removed above the viewport', async ({ page }) => {
await page.emulateMedia({ reducedMotion: 'no-preference' })
await page.goto(fixtureUrl)
const r = await page.evaluate(async (moduleUrl) => {
const { default: autoAnimate } = (await import(moduleUrl)) as typeof import('../../src/index')
document.body.innerHTML = `<div style="height:400px"></div><ul id="l" style="margin:0;padding:0">${'abcdefgh'
.split('')
.map((c) => `<li id="${c}" style="height:40px;list-style:none">${c}</li>`)
.join('')}</ul><div style="height:2000px"></div>`
const ul = document.getElementById('l')!
autoAnimate(ul, { duration: 600 })
window.scrollTo(0, 500) // a, b, c are above the viewport; the rest visible
await new Promise((res) => setTimeout(res, 300)) // let scroll events + measurements settle
const watched = document.getElementById('f')!
const before = watched.getBoundingClientRect().top
document.getElementById('a')!.remove()
const tops: number[] = []
for (let i = 0; i < 8; i++) {
await new Promise((res) => requestAnimationFrame(res))
tops.push(Math.round(watched.getBoundingClientRect().top))
}
return { before: Math.round(before), tops, scrolled: Math.round(window.scrollY) }
}, moduleUrl)
const anchored = test.info().project.name !== 'webkit' // WebKit has no scroll anchoring
for (const top of r.tops) {
if (anchored) expect(Math.abs(top - r.before)).toBeLessThanOrEqual(1)
else expect(top).toBeLessThanOrEqual(r.before + 1) // only ever moves up toward its new spot
}
})
Loading