Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(core): a glide retargeted by a second layout change starts where it is drawn (#9327)

Christopher Chedeau1ee5e4069d1e
diff --git a/.changeset/animated-layout-retarget-drawn-place.md b/.changeset/animated-layout-retarget-drawn-place.md
new file mode 100644
index 0000000000..6fa3a737a6
--- /dev/null
+++ b/.changeset/animated-layout-retarget-drawn-place.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] In Safari, content already gliding after a layout change no longer jumps ahead when a second change retargets it, such as a row that moves again while it is still moving, or a row inside a card that is itself gliding: the new glide started up to about 3 px ahead of where the row was drawn, more the later in its frame the change was made. A gliding element's place before a change is now read on the clock of every glide that carries it, its own and its gliding containers', so the new glide starts where the old one is drawn.
+
+@vjeux
diff --git a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts
index 9802791837..2a62e97e6c 100644
--- a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts
+++ b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts
@@ -572,9 +572,16 @@ test.describe('spec:AST-105 Coverage', () => {
expect(await page.evaluate(() => window.motionOf('#pop'))).toEqual([]);
});
- test('an element already moving keeps its motion and adds the new move: no jump, no lost speed', async ({
- page,
- }) => {
+ /**
+ * Opens a row gliding after #grow's change, then retargets its glide with
+ * a second change (#second) made `lateMs` into a frame, as a change in a
+ * slow frame is. Reads the row on the glides' own clock (`glideBoxOf`, at
+ * each frame's time): WebKit evaluates a running transform for
+ * `getBoundingClientRect` at the moment of the read, so a box read late in
+ * its frame places the row further on, and over one short frame read up to
+ * 1.8 times its speed.
+ */
+ async function retarget(page: Page, lateMs: number) {
await open(
page,
`<div id="area" class="area"><div id="grow" class="grow"></div>
@@ -583,32 +590,50 @@ test.describe('spec:AST-105 Coverage', () => {
await change(page);
await page.waitForTimeout(100);
const [first] = await page.evaluate(() => window.motionOf('#after'));
- // The row's on-screen speed over the frame before the second change and
- // the frame after it, and its place either side of the change.
- const run = await page.evaluate(async mutate => {
- const row = document.querySelector('#after') as HTMLElement;
- const frame = async () =>
- new Promise<number>(resolve => requestAnimationFrame(resolve));
- const t0 = await frame();
- const y0 = row.getBoundingClientRect().top;
- const t1 = await frame();
- const y1 = row.getBoundingClientRect().top;
- await window.change({changed: '#second', mutate});
- const y1After = row.getBoundingClientRect().top;
- const t2 = await frame();
- const y2 = row.getBoundingClientRect().top;
- return {
- before: (y1 - y0) / (t1 - t0),
- after: (y2 - y1After) / (t2 - t1),
- y1,
- y1After,
- };
- }, `document.querySelector('#second').classList.add('open')`);
+ // The row's speed over the frame before the second change and the frame
+ // after it, and its place either side of the change.
+ const run = await page.evaluate(
+ async ({mutate, late}) => {
+ const row = document.querySelector('#after') as HTMLElement;
+ const frame = async () =>
+ new Promise<number>(resolve => requestAnimationFrame(resolve));
+ const t0 = await frame();
+ const y0 = window.glideBoxOf(row).top;
+ const t1 = await frame();
+ const y1 = window.glideBoxOf(row).top;
+ const until = performance.now() + late;
+ while (performance.now() < until) {
+ // The change comes `late` ms into the frame.
+ }
+ await window.change({changed: '#second', mutate});
+ const y1After = window.glideBoxOf(row).top;
+ const t2 = await frame();
+ const y2 = window.glideBoxOf(row).top;
+ return {
+ before: (y1 - y0) / (t1 - t0),
+ after: (y2 - y1After) / (t2 - t1),
+ y1,
+ y1After,
+ };
+ },
+ {
+ mutate: `document.querySelector('#second').classList.add('open')`,
+ late: lateMs,
+ },
+ );
+ return {first, run};
+ }
+
+ test('an element already moving keeps its motion and adds the new move: no jump, no lost speed', async ({
+ page,
+ }) => {
+ const {first, run} = await retarget(page, 0);
const motions = await page.evaluate(() => window.motionOf('#after'));
expect(motions).toHaveLength(1);
expect(motions[0].composite).toBe('replace');
expect(motions[0].startTime).not.toBe(first.startTime);
- expect(run.y1After).toBeCloseTo(run.y1, 0);
+ // No jump: the new glide starts where the old one is drawn.
+ expect(Math.abs(run.y1After - run.y1)).toBeLessThan(0.1);
// Still gliding down at least as fast: the new move adds to the motion.
expect(run.before).toBeGreaterThan(0);
expect(run.after).toBeGreaterThan(run.before * 0.9);
@@ -622,6 +647,129 @@ test.describe('spec:AST-105 Coverage', () => {
expect(landed).toBeCloseTo(160, 0);
});
+ for (const lateMs of [1, 9]) {
+ test(`a change made ${lateMs} ms into its frame retargets a glide where it is drawn`, async ({
+ page,
+ }) => {
+ // In WebKit the box read before the change sampled the old glide at
+ // that moment, while the new glide ran on the frame's time, so it
+ // started that many ms of motion ahead (0.3 px at 1 ms, about 3 px at
+ // 9 ms).
+ const {run} = await retarget(page, lateMs);
+ expect(Math.abs(run.y1After - run.y1)).toBeLessThan(0.1);
+ expect(run.after).toBeGreaterThan(run.before * 0.9);
+ });
+ }
+
+ /**
+ * As `retarget`, for a row inside a card that the first change sets
+ * gliding: the second change, inside the card and `lateMs` ms into a frame,
+ * moves the row within the card while the card's glide is retargeted. The
+ * row is read where it is drawn: its layout place plus every glide on it
+ * and on its ancestors, each from its keyframes at its current time.
+ */
+ async function nestedRetarget(
+ page: Page,
+ lateMs: number,
+ body = `<div id="area" class="area"><div id="grow" class="grow"></div>
+ <div id="card"><div id="inner" class="grow"></div><div id="row" class="row"></div></div></div>`,
+ ) {
+ await open(page, body);
+ await change(page);
+ await page.waitForTimeout(100);
+ return page.evaluate(
+ async ({mutate, late}) => {
+ const card = document.querySelector('#card') as HTMLElement;
+ const row = document.querySelector('#row') as HTMLElement;
+ const layoutTop = (element: HTMLElement) => {
+ let y = 0;
+ for (
+ let node: HTMLElement | null = element;
+ node != null;
+ node = node.offsetParent as HTMLElement | null
+ ) {
+ y += node.offsetTop + (node === element ? 0 : node.clientTop);
+ }
+ return y - window.scrollY;
+ };
+ const drawnTop = (element: HTMLElement) => {
+ let y = window.glideBoxOf(element).top;
+ for (
+ let node = element.parentElement;
+ node != null && node !== document.body;
+ node = node.parentElement
+ ) {
+ y += window.glideBoxOf(node).top - layoutTop(node);
+ }
+ return y;
+ };
+ const frame = async () =>
+ new Promise<number>(resolve => requestAnimationFrame(resolve));
+ await frame();
+ await frame();
+ const cardGlidingBefore = card.getAnimations().length > 0;
+ const cardGlide = card.getAnimations().at(-1) ?? null;
+ const y1 = drawnTop(row);
+ const until = performance.now() + late;
+ while (performance.now() < until) {
+ // The change comes `late` ms into the frame.
+ }
+ await window.change({changed: '#inner', mutate});
+ const y1After = drawnTop(row);
+ return {
+ cardGlidingBefore,
+ cardGlidingAfter: card.getAnimations().length > 0,
+ cardRetargeted: card.getAnimations().at(-1) !== cardGlide,
+ rowGlidingAfter: row.getAnimations().length > 0,
+ y1,
+ y1After,
+ };
+ },
+ {
+ mutate: `document.querySelector('#inner').classList.add('open')`,
+ late: lateMs,
+ },
+ );
+ }
+
+ for (const lateMs of [0, 1, 9]) {
+ test(`a row inside a gliding card, moved by a change in the card ${lateMs} ms into its frame, starts where it is drawn`, async ({
+ page,
+ }) => {
+ // The row's recorded place carried the card's glide as WebKit sampled
+ // it at the read, while the card's own place is on its glide's clock:
+ // the row's new glide took up the difference (about 2.3 px at 9 ms).
+ const run = await nestedRetarget(page, lateMs);
+ expect(run.cardGlidingBefore).toBe(true);
+ expect(run.cardGlidingAfter).toBe(true);
+ expect(run.cardRetargeted).toBe(true);
+ expect(run.rowGlidingAfter).toBe(true);
+ expect(Math.abs(run.y1After - run.y1)).toBeLessThan(0.1);
+ });
+ }
+
+ for (const lateMs of [0, 1, 9]) {
+ test(`a row inside a gliding card that keeps its glide (an absolutely positioned panel), moved by a change in the card ${lateMs} ms into its frame, starts where it is drawn`, async ({
+ page,
+ }) => {
+ // Inside an absolutely positioned panel the change takes no ancestors,
+ // so the card keeps its glide through the change while the row moves:
+ // the row's places before and after the change both carry the card's
+ // glide, and both must read it on the same clock.
+ const run = await nestedRetarget(
+ page,
+ lateMs,
+ `<div id="area" class="area"><div id="panel" style="position: absolute; inset: 0 0 auto 0"><div id="grow" class="grow"></div>
+ <div id="card"><div id="inner" class="grow"></div><div id="row" class="row"></div></div></div></div>`,
+ );
+ expect(run.cardGlidingBefore).toBe(true);
+ expect(run.cardGlidingAfter).toBe(true);
+ expect(run.cardRetargeted).toBe(false);
+ expect(run.rowGlidingAfter).toBe(true);
+ expect(Math.abs(run.y1After - run.y1)).toBeLessThan(0.1);
+ });
+ }
+
test('nested areas: motion stops at the inner area; an inner area moves as one unit', async ({
page,
}) => {
diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.ts
index da0a84a017..9d744f917f 100644
--- a/packages/core/src/motion/animatedLayout.ts
+++ b/packages/core/src/motion/animatedLayout.ts
@@ -39,7 +39,13 @@
* old place to the new one, sampled from `springs.settle` into linear
* keyframes and corrected for a scaled ancestor. An element already gliding
* keeps that motion and adds the new move: the rest of its curve and the
- * new move are summed into one new glide, velocity included. Nothing
+ * new move are summed into one new glide, velocity included. Its place
+ * before the change is read on the clock of every glide that carries it,
+ * its own and its gliding ancestors' in the area (the box with each applied
+ * `translate` taken out, plus each glide's offset at its current time), and
+ * so is its place after the change, where only the glides the change leaves
+ * running remain: the new glide starts where the old one is drawn, and a
+ * glide the change leaves running cancels out of the move. Nothing
* animates height, and nothing scrolls the area.
* - A measurement no commit claims by the next frame is dropped.
* - The changed element plays its own entrance on the same spring, started in
@@ -563,6 +569,91 @@ function isStuck(element: Element, cache: WalkCache): boolean {
);
}
+/**
+ * `rect`, a box read before a change or after it (in the flush, once the
+ * glides the change retargets have stopped), with every running glide that
+ * carries the element put back on its glide's own clock: its own and those of
+ * its ancestors inside `area`. A glide the change retargets is read on its
+ * clock before the change and is gone after it; one the change leaves running
+ * (a card inside an absolutely positioned panel, which the change takes no
+ * ancestors from) is read on the same clock in both places, so it cancels out
+ * of the move. A box read samples a running `translate`
+ * wherever the engine evaluates it, and WebKit evaluates it at the moment of
+ * the read, while a glide's offset, and the glide a change retargets it into,
+ * run on the timeline's frame time: from the box alone, a change made `n` ms
+ * into a frame started the new glide `n` ms of motion ahead of the one drawn
+ * (up to about 3 px on a slow frame), and a row inside a gliding card took up
+ * the card's difference. The box is read between two readings of every
+ * carrier's applied `translate` that agree: WebKit samples a running
+ * animation at the moment of each read, in steps of about a millisecond, so
+ * a box read between two equal readings is of that same sample, while the
+ * walk's earlier box read, or one read across a step, is of another. Taken
+ * out of that
+ * box (each scaled by its node's ancestors, as its glide is), the `translate`s
+ * leave the element's place with no glide, and each glide's offset at its
+ * current time goes back in. A glide replaces any `translate` of the app's
+ * own while it runs, so each applied value is the glide's alone. Where the
+ * engine reports no applied `translate` at all (an environment without
+ * individual transform properties), the box is taken as it is.
+ */
+/**
+ * How many times `onGlideClock` reads a box and the applied translates around
+ * it to take all of them from one sample: it bounds the reads for one
+ * consistent snapshot (WebKit's samples step about once a millisecond, and a
+ * second reading lands inside one step), not a retry around a result.
+ */
+const SAMPLE_READS = 3;
+
+function onGlideClock(element: Element, rect: DOMRect, area: Element): DOMRect {
+ const carriers: {node: Element; glide: Glide; time: number}[] = [];
+ for (
+ let node: Element | null = element;
+ node != null && node !== area;
+ node = node.parentElement
+ ) {
+ const glide = glides.get(node);
+ const time = Number(glide?.animation.currentTime);
+ if (glide != null && Number.isFinite(time)) {
+ carriers.push({node, glide, time});
+ }
+ }
+ if (carriers.length === 0) {
+ return rect;
+ }
+ const view = element.ownerDocument.defaultView;
+ const appliedNow = () =>
+ carriers.map(({node}) => view?.getComputedStyle(node).translate);
+ let applied = appliedNow();
+ if (applied.some(translate => translate == null || translate === '')) {
+ return rect;
+ }
+ let box = element.getBoundingClientRect();
+ for (let read = 0; read < SAMPLE_READS; read++) {
+ const again = appliedNow();
+ if (again.every((translate, index) => translate === applied[index])) {
+ break;
+ }
+ applied = again;
+ box = element.getBoundingClientRect();
+ }
+ let dx = 0;
+ let dy = 0;
+ carriers.forEach(({node, glide, time}, index) => {
+ const [appliedX = 0, appliedY = 0] = numbersIn(applied[index] as string);
+ const offset = glide.offsetAt(
+ Math.min(Math.max(0, time), glide.durationMs),
+ );
+ const scale = scaleOf(
+ node,
+ node === element ? box : node.getBoundingClientRect(),
+ ownScaleOf(node),
+ );
+ dx += (offset.x - appliedX) * scale.x;
+ dy += (offset.y - appliedY) * scale.y;
+ });
+ return new DOMRect(box.x + dx, box.y + dy, box.width, box.height);
+}
+
function rectOf(element: Element, cache: WalkCache): DOMRect {
let rect = cache.rects.get(element);
if (rect === undefined) {
@@ -947,7 +1038,15 @@ function flush(batch: Batch): void {
const nearer = (raw: number, shift: number) =>
Math.abs(raw + shift) < Math.abs(raw) ? raw + shift : raw;
for (const entry of entries) {
- entry.after = entry.element.getBoundingClientRect();
+ // On the same clocks as the place before the change: only the glides this
+ // change does not retarget still run here (a card inside an absolutely
+ // positioned panel keeps its glide while the row in it moves), so each
+ // reads the same in both places and cancels out of the move.
+ entry.after = onGlideClock(
+ entry.element,
+ entry.element.getBoundingClientRect(),
+ batch.area,
+ );
// The move is the inline-start edge's, by the container's direction (it
// decides where the element sits): in a right-to-left container an
// element that narrows keeps its left edge and moves its right one.
@@ -1127,7 +1226,7 @@ export function reportLayoutChange(
);
for (const [candidate, rect] of candidates) {
if (!batch.before.has(candidate)) {
- batch.before.set(candidate, rect);
+ batch.before.set(candidate, onGlideClock(candidate, rect, area));
}
}
batch.candidates.set(changed, [...candidates.keys()]);