Skip to content
Merged
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
118 changes: 118 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -784,9 +784,124 @@ function cleanUp(el: Element, styles?: Partial<CSSStyleDeclaration>) {
;(el.style as any)[style as any] = ""
}
}
unpinCells(el)
}, 0)
}

/**
* Table cells whose width was pinned while their row animates out:
* [cell, original width, original box-sizing, pinned width]. Restored on
* cleanup (only if still ours) so a re-inserted row lays out normally.
*/
const pinnedCells = new WeakMap<
Element,
Array<[HTMLElement, string, string, string]>
>()

/**
* Where the first cell of a leaving row should be (page coordinates), used to
* put the row back exactly.
*/
const rowAnchors = new WeakMap<Element, { left: number; top: number }>()

/**
* A table row taken out of flow (position: absolute) loses its table layout:
* its cells collapse to their content. Render the leaving row as its own
* fixed-layout table with each cell pinned to its width instead.
* @param el - The row being removed.
* @param oldCoords - The row's coordinates before it was removed.
* @param styleReset - The removal styles, extended in place.
*/
function preserveRowLayout(
el: Element,
oldCoords: Coordinates,
styleReset: Partial<CSSStyleDeclaration>,
) {
if (!(el instanceof HTMLElement) || getComputedStyle(el).display !== "table-row")
return
const table = el.closest("table")
const tableStyles = table ? getComputedStyle(table) : null
const cells = Array.from(el.children).filter(
(cell): cell is HTMLElement => cell instanceof HTMLElement,
)
// Layout sizes (not getBoundingClientRect) so transformed tables aren't scaled twice.
const widths = cells.map((cell) => cell.offsetWidth)
if (cells[0]) {
// The first cell's offset inside the row, applied to the row's pre-removal
// position (the layout may already have shifted by now).
const row = getCoords(el)
const cell = getCoords(cells[0])
rowAnchors.set(el, {
left: oldCoords.left + cell.left - row.left,
top: oldCoords.top + cell.top - row.top,
})
}
pinnedCells.set(
el,
cells.map((cell, i) => {
const entry: [HTMLElement, string, string, string] = [
cell,
cell.style.width,
cell.style.boxSizing,
`${widths[i]}px`,
]
cell.style.boxSizing = "border-box"
cell.style.width = `${widths[i]}px`
return entry
}),
)
styleReset.display = "table"
styleReset.tableLayout = "fixed"
if (tableStyles) {
styleReset.borderCollapse = tableStyles.borderCollapse
styleReset.borderSpacing = tableStyles.borderSpacing
if (tableStyles.borderCollapse !== "collapse") {
// The row is now its own table, so border-spacing also wraps its outer
// edges: pull it back by that much and make room for the gaps.
const [h, v = h] = tableStyles.borderSpacing.split(" ").map(raw)
if (h || v) {
styleReset.margin = `${-v}px ${-h}px`
styleReset.width = `${
widths.reduce((sum, w) => sum + w, 0) + h * (cells.length + 1)
}px`
styleReset.height = `${el.offsetHeight + 2 * v}px`
}
}
}
}

/**
* Restore pinned cell styles, leaving any the app changed in the meantime.
*/
function unpinCells(el: Element) {
pinnedCells.get(el)?.forEach(([cell, width, boxSizing, pinned]) => {
if (cell.style.width === pinned) {
cell.style.width = width
if (cell.style.boxSizing === "border-box") cell.style.boxSizing = boxSizing
}
})
pinnedCells.delete(el)
}

/**
* Browsers disagree on where an absolutely positioned table row lands relative
* to its computed top/left (Firefox and border-spacing especially). For rows
* (only), line the first cell back up with where it was.
*/
function correctDeletePosition(el: Element) {
const anchor = rowAnchors.get(el)
const firstCell = el.firstElementChild
rowAnchors.delete(el)
if (!(el instanceof HTMLElement) || !anchor || !firstCell) return
const now = getCoords(firstCell)
// Page pixels → CSS pixels inside a transformed (scaled) table.
const scale = el.offsetWidth ? el.getBoundingClientRect().width / el.offsetWidth : 1
const dx = Math.round((anchor.left - now.left) / (scale || 1))
const dy = Math.round((anchor.top - now.top) / (scale || 1))
if (dx) el.style.left = `${raw(el.style.left) + dx}px`
if (dy) el.style.top = `${raw(el.style.top) + dy}px`
}

/**
* Animates the removal of an element.
* @param el - Element to remove
Expand Down Expand Up @@ -833,7 +948,10 @@ function remove(el: Element) {
}

if (!isPlugin(optionsOrPlugin)) {
// Plugins own their removal styles, so rows are only adjusted here.
preserveRowLayout(el, oldCoords, styleReset)
Object.assign((el as HTMLElement).style, styleReset)
correctDeletePosition(el)
animation = (el as HTMLElement).animate(
[
{
Expand Down
100 changes: 100 additions & 0 deletions tests/e2e/table-row-layout.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
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))}`

// #7: a removed <tr> lost its table layout while animating out (cells
// collapsed to their content and the row floated outside the table).
for (const tableStyle of ['border-collapse:separate;border-spacing:4px', 'border-collapse:collapse', 'border-collapse:separate;border-spacing:10px 2px'])
test(`a removed table row keeps its cell layout while it animates out (${tableStyle})`, async ({ page }) => {
await page.emulateMedia({ reducedMotion: 'no-preference' })
await page.goto(fixtureUrl)
const r = await page.evaluate(async ({ moduleUrl, tableStyle }) => {
const { default: autoAnimate } = (await import(moduleUrl)) as typeof import('../../src/index')
document.body.innerHTML = `
<table id="t" style="width:600px;${tableStyle}">
<thead><tr><th>Drink</th><th>Takes</th><th>Time</th><th>Status</th></tr></thead>
<tbody>
${['Latte', 'Mocha', 'Flat white'].map((d, i) => `<tr id="r${i}"><td>${d}</td><td>${i + 1}</td><td>10:0${i}</td><td>Queued</td></tr>`).join('')}
</tbody>
</table>`
const tbody = document.querySelector('tbody')!
autoAnimate(tbody, { duration: 1000 })
await new Promise((res) => setTimeout(res, 100))
const row = document.getElementById('r1')!
const box = (el: Element) => { const b = el.getBoundingClientRect(); return [Math.round(b.left), Math.round(b.top), Math.round(b.width), Math.round(b.height)] }
const before = { row: box(row), cells: [...row.children].map(box) }
row.remove()
await new Promise((res) => setTimeout(res, 60))
const during = { inDom: row.isConnected, row: box(row), cells: [...row.children].map(box) }
await new Promise((res) => setTimeout(res, 1300))
const afterStyles = { cell: (row.children[0] as HTMLElement).style.cssText, row: row.style.cssText }
return { before, during, afterStyles, gone: !row.isConnected }
}, { moduleUrl, tableStyle })
expect(r.during.inDom).toBe(true)
// the leaving row stays where it was, with the same cell geometry (±2px for the scale)
for (let i = 0; i < 4; i++) {
expect(Math.abs(r.during.cells[i][0] - r.before.cells[i][0])).toBeLessThanOrEqual(2)
expect(Math.abs(r.during.cells[i][1] - r.before.cells[i][1])).toBeLessThanOrEqual(2)
expect(Math.abs(r.during.cells[i][2] - r.before.cells[i][2])).toBeLessThanOrEqual(4)
}
expect(r.gone).toBe(true)
// nothing left behind on the element for re-insertion
expect(r.afterStyles.cell).toBe('')
})

/** Remove a row and report cell boxes before/during, plus inline styles after. */
async function probe(page: import('@playwright/test').Page, html: string, rowSel: string, opts: { plugin?: boolean; tweak?: boolean } = {}) {
await page.emulateMedia({ reducedMotion: 'no-preference' })
await page.goto(fixtureUrl)
return page.evaluate(async ({ moduleUrl, html, rowSel, opts }) => {
const { default: autoAnimate } = (await import(moduleUrl)) as typeof import('../../src/index')
document.body.innerHTML = html
const row = document.querySelector(rowSel) as HTMLElement
const parent = row.parentElement!
const plugin: any = (el: Element, action: string) =>
action === 'remove'
? [new KeyframeEffect(el, [{ opacity: 1 }, { opacity: 0 }], 600), { styleReset: { position: 'absolute', top: '0px', left: '0px' } }]
: new KeyframeEffect(el, [{ opacity: 1 }, { opacity: 1 }], 10)
autoAnimate(parent, opts.plugin ? plugin : { duration: 600 })
await new Promise((r) => setTimeout(r, 100))
const box = (el: Element) => { const b = el.getBoundingClientRect(); return [Math.round(b.left), Math.round(b.top), Math.round(b.width)] }
const before = [...row.children].map(box)
row.remove()
await new Promise((r) => setTimeout(r, 60))
if (opts.tweak) (row.children[0] as HTMLElement).style.color = 'red'
const during = [...row.children].map(box)
const rowStyle = { top: row.style.top, left: row.style.left }
await new Promise((r) => setTimeout(r, 900))
return { before, during, rowStyle, cellStyle: (row.children[0] as HTMLElement).style.cssText }
}, { moduleUrl, html, rowSel, opts })
}

const close = (a: number[][], b: number[][], tol = 2) =>
a.every((c, i) => c.every((v, j) => Math.abs(v - b[i][j]) <= tol))

test('works inside a transformed (scaled) table', async ({ page }) => {
const r = await probe(page, `<div style="transform:scale(2);transform-origin:0 0"><table style="width:300px;border-spacing:4px"><tbody>
<tr><td>a</td><td>b</td></tr><tr id="x"><td>c</td><td>d</td></tr><tr><td>e</td><td>f</td></tr></tbody></table></div>`, '#x')
expect(close(r.during, r.before, 3)).toBe(true)
})

test('removing the only header row keeps it in place', async ({ page }) => {
const r = await probe(page, `<table style="width:400px;border-spacing:4px"><thead><tr id="h"><th>A</th><th>B</th></tr></thead>
<tbody><tr><td>1</td><td>2</td></tr></tbody></table>`, '#h')
expect(close(r.during, r.before)).toBe(true)
})

test('plugins keep full control of removal positioning', async ({ page }) => {
const r = await probe(page, `<table style="width:400px;border-spacing:4px"><tbody>
<tr><td>a</td><td>b</td></tr><tr id="x"><td>c</td><td>d</td></tr></tbody></table>`, '#x', { plugin: true })
expect(r.rowStyle).toEqual({ top: '0px', left: '0px' })
expect(r.cellStyle).toBe('')
})

test('cleanup keeps cell styles the app changed meanwhile', async ({ page }) => {
const r = await probe(page, `<table style="width:400px;border-spacing:4px"><tbody>
<tr><td>a</td><td>b</td></tr><tr id="x"><td>c</td><td>d</td></tr></tbody></table>`, '#x', { tweak: true })
expect(r.cellStyle).toBe('color: red;')
})
Loading