fix(core): a sealed move inside a nested composition shows where it was dropped (#8517)

* fix(core): a patched tween on a resting scene timeline is drawn before the frame says patched

* fix(core): the frame says patched only once each patched tween has rendered
This commit is contained in:
Miguel Ángel
2026-11-22 16:17:17 +00:00
committed by GitHub
parent 0bc7963ffd
commit ec9a3a8ef2
5 changed files with 202 additions and 30 deletions
+10 -1
View File
@@ -319,6 +319,16 @@ export function seekGsapTimeline(
const from = landOn(timeline, t, suppressEvents, version);
if (t < from && structure) reapplyStepsInAuthoredOrder(timeline, structure, t);
if (from !== t || !gsapNeverRendered(timeline)) return false;
redrawGsapTimelineAt(timeline, t, structure);
return true;
}
export function redrawGsapTimelineAt(
timeline: RuntimeTimelineLike,
t: number,
structure?: GsapStructureKey,
): void {
if (typeof timeline.totalTime !== "function") return;
rerenderGsapTimelineAt(
{
totalTime: timeline.totalTime.bind(timeline),
@@ -328,7 +338,6 @@ export function seekGsapTimeline(
t,
structure,
);
return true;
}
type GsapParent = {
@@ -0,0 +1,119 @@
import gsap from "gsap";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { initSandboxRuntimeModular } from "../init";
import type { RuntimeTimelineLike } from "../types";
import { resetRuntimeFixtureDom } from "../runtimeSeekFixture.test-helpers";
import { patchTweens } from "./patchTween";
// fails without the fix: the runtime skips a scene resting at the time it would draw, so a patched tween on a
// scene's timeline was never drawn and the frame still answered patched.
describe("patch-tweens on a scene that rests", () => {
beforeEach(() => {
resetRuntimeFixtureDom();
window.gsap = gsap as unknown as typeof window.gsap;
});
afterEach(() => {
window.__hfRuntimeTeardown?.();
vi.restoreAllMocks();
delete window.__player;
delete window.__playerReady;
delete window.__hf;
});
/** `#a` is held at x 40 by a set on scene a's timeline; at depth 2, scene a sits inside scene outer. */
function load(depth: 1 | 2, holdA = (a: gsap.core.Timeline) => a.set("#a", { x: 40 }, 0)) {
const a = `<div class="clip" data-composition-id="a" data-start="0" data-duration="10"><div id="a"></div></div>`;
document.body.innerHTML =
`<div data-composition-id="main" data-root="true" data-duration="10">` +
(depth === 1
? a
: `<div class="clip" data-composition-id="outer" data-start="0" data-duration="10">${a}</div>`) +
`<div class="clip" data-composition-id="b" data-start="0" data-duration="10"><div id="b"></div></div>` +
`</div>`;
const scene = () => gsap.timeline({ paused: true }).to({}, { duration: 5 }, 0);
const b = scene().set("#b", { x: 10 }, 0);
const timelines: Record<string, unknown> = {
main: scene(),
a: holdA(scene()),
b,
};
if (depth === 2) timelines.outer = scene();
window.__timelines = timelines as Record<string, RuntimeTimelineLike>;
initSandboxRuntimeModular();
window.__player?.seek(1);
window.__player?.seek(1);
return { b };
}
const shownX = (selector: string) => Number(gsap.getProperty(selector, "x"));
const patchA = (x: number) =>
patchTweens({
patches: [{ selector: "#a", change: { kind: "set", props: { x } } }],
seek: true,
});
it.each([1, 2] as const)(
"draws the patched set on a scene %i composition deep, and only then answers patched",
(depth) => {
load(depth);
expect(shownX("#a")).toBe(40);
expect(patchA(300)).toEqual({ patched: true });
expect(shownX("#a")).toBe(300);
},
);
it("still skips a scene at rest that no patch touched", () => {
const { b } = load(1);
const drawsB = [vi.spyOn(b, "totalTime"), vi.spyOn(b, "seek"), vi.spyOn(b, "render")];
patchA(300);
expect(drawsB.map((draw) => draw.mock.calls.filter((call) => call.length > 0).length)).toEqual([
0, 0, 0,
]);
});
it("answers not patched when the patched set sits in a child timeline that already ended", () => {
load(1, (a) => a.add(gsap.timeline().set("#a", { x: 40 }, 0), 0));
expect(patchA(300)).toEqual({ patched: false });
expect(shownX("#a")).toBe(40);
});
it("answers patched for a keyframe-step edit once the tween that replaced it renders", () => {
load(1, (a) =>
a.to("#a", { keyframes: { "0%": { x: 40 }, "100%": { x: 40 } }, duration: 2 }, 0),
);
const reply = patchTweens({
patches: [
{ selector: "#a", change: { kind: "keyframe-rebuild", pct: 100, props: { x: 140 } } },
],
seek: true,
});
expect(reply).toEqual({ patched: true });
expect(shownX("#a")).toBe(90);
});
it("answers not patched when nothing draws the scene it changed", () => {
load(1);
delete window.__player;
expect(patchA(300)).toEqual({ patched: false });
});
});
// The reply reads GSAP's internal _initted: an upgrade that changes it fails here, not every reply.
describe("GSAP's init flag, as the patch reply reads it", () => {
it("is cleared by invalidate() and set again by the tween's next render", () => {
document.body.innerHTML = `<div id="a"></div>`;
const timeline = gsap
.timeline({ paused: true })
.set("#a", { x: 40 }, 0)
.to({}, { duration: 2 }, 0);
timeline.totalTime(1);
const set = timeline.getChildren(true)[0] as gsap.core.Tween & { _initted?: unknown };
expect(Boolean(set._initted)).toBe(true);
set.invalidate();
expect(Boolean(set._initted)).toBe(false);
timeline.totalTime(0.5, true);
timeline.totalTime(1, true);
expect(Boolean(set._initted)).toBe(true);
});
});
+44 -13
View File
@@ -4,6 +4,7 @@
import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "../../colorGrading";
import { recordLiveSet, swapWaiting } from "./softReload";
import { drawDrafts } from "../editingDraft";
import { markRestingScenesForRedraw } from "../sceneRest";
import { parseDraftEnd, type EditingDraftEnd } from "../editingDraftEnd";
export interface SetPatchProps {
@@ -281,16 +282,22 @@ function keyframeObject(
const finiteStep = (props: KeyframeStep) =>
Object.values(props).every((v) => typeof v === "number" && Number.isFinite(v));
function rebuildKeyframeTween(tween: PatchableTween, pct: number, props: KeyframeStep): boolean {
if (!replaceable(tween) || !finiteStep(props)) return false;
function rebuildKeyframeTween(
tween: PatchableTween,
pct: number,
props: KeyframeStep,
): PatchableTween | null {
if (!replaceable(tween) || !finiteStep(props)) return null;
const kf = keyframeObject(tween.vars);
const targets = tween.targets?.();
if (!kf || !targets || targets.length === 0) return false;
if (!kf || !targets || targets.length === 0) return null;
const next = mergeKeyframeStep(kf, pct, props);
const position = tween.startTime();
const parent = tween.parent;
tween.kill();
tween.parent.to(targets, { ...tween.vars, keyframes: next }, position);
return true;
const before = new Set(parent.getChildren?.(false));
parent.to(targets, { ...tween.vars, keyframes: next }, position);
return parent.getChildren?.(false).find((child) => !before.has(child)) ?? null;
}
function changeChannels(change: RuntimeTweenChange): string[] | undefined {
@@ -319,12 +326,28 @@ function restoreAuthoredOpacityForCapture(tween: PatchableTween): void {
}
}
function applyChange(tween: PatchableTween, change: RuntimeTweenChange): boolean {
if (change.kind === "set") return patchSet(tween, change.props);
if (change.kind === "keyframes") return patchKeyframes(tween, change.keyframes);
function applyChange(tween: PatchableTween, change: RuntimeTweenChange): PatchableTween | null {
if (change.kind === "set") return patchSet(tween, change.props) ? tween : null;
if (change.kind === "keyframes") return patchKeyframes(tween, change.keyframes) ? tween : null;
if (change.kind === "keyframe-rebuild")
return rebuildKeyframeTween(tween, change.pct, change.props);
return false;
return null;
}
type GsapInitFlag = { _initted?: unknown };
/** Reads GSAP's internal `_initted`: invalidate() clears it and the tween's next render sets it. */
const renderedOnceReached = (tween: PatchableTween): boolean => {
const now = tween.parent?.time?.();
const reached = typeof now === "number" && now >= (tween.startTime?.() ?? 0);
return !reached || Boolean((tween as GsapInitFlag)._initted);
};
function timelinesAbove(tween: PatchableTween): object[] {
const chain: object[] = [];
for (let parent = tween.parent; parent; parent = (parent as PatchableTween).parent)
chain.push(parent);
return chain;
}
function seekToCurrent(target: PatchTarget, timeline: PatchableTimeline): void {
@@ -345,6 +368,7 @@ export function patchTween(
change: Exclude<RuntimeTweenChange, { kind: "global-set" }>,
compositionId?: string,
deferSeek = false,
patchedTweens: PatchableTween[] = [],
): boolean {
try {
const kind = change.kind === "set" ? "set" : "keyframe";
@@ -352,10 +376,13 @@ export function patchTween(
if (!resolved) return false;
const { tween, timeline } = resolved;
if (changeTouchesOpacity(change)) restoreAuthoredOpacityForCapture(tween);
if (!applyChange(tween, change)) return false;
const patched = applyChange(tween, change);
if (!patched) return false;
patchedTweens.push(patched);
// Only the edited tween: a timeline-wide invalidate re-captures every from() against
// the grading engine's opacity-0 hide, and graded elements vanish.
if (change.kind !== "keyframe-rebuild") tween.invalidate?.();
markRestingScenesForRedraw(timelinesAbove(patched));
if (!deferSeek) seekToCurrent(target, timeline);
return true;
} catch {
@@ -473,11 +500,15 @@ export function patchTweens({ patches, seek, endsDrafts }: PatchTweensParams): {
};
if (swapWaiting()) return { patched: false };
const renderAt = lastTweenPatch(patches);
const patchedTweens: PatchableTween[] = [];
const missed = patches.find(({ selector, change }, index) => {
if (change.kind === "global-set")
return applyGlobalSet(target, selector, change.props) === null;
return !patchTween(target, selector, change, undefined, !(seek && index === renderAt));
const defer = !(seek && index === renderAt);
return !patchTween(target, selector, change, undefined, defer, patchedTweens);
});
if (missed === undefined && endsDrafts) drawDrafts(endsDrafts);
return { patched: missed === undefined };
const shown = !seek || patchedTweens.every(renderedOnceReached);
const patched = missed === undefined && shown;
if (patched && endsDrafts) drawDrafts(endsDrafts);
return { patched };
}
+12 -16
View File
@@ -1,5 +1,6 @@
// fallow-ignore-file code-duplication complexity
import { rememberSourceLength, sourceLengthOf } from "./sourceLength";
import { restSceneAt, sceneRestingAt, takeSceneRedrawDue } from "./sceneRest";
import { wallClearTimeout, wallSetTimeout } from "./wallClock";
import { setPreviewRasterScale } from "./previewRasterHints";
import { createFarSceneSkip } from "./farScenes";
@@ -73,7 +74,7 @@ import {
createGsapAdapter,
holdFrameMarks,
muteDiscreteCallbacks,
rerenderGsapTimelineAt,
redrawGsapTimelineAt,
gsapTimelineOf,
seekGsapTimeline,
type GsapStructureKey,
@@ -5707,12 +5708,15 @@ export function initSandboxRuntimeModular(): void {
timeline: RuntimeTimelineLike,
timeSeconds: number,
options?: RuntimeSeekOptions,
redrawDue = false,
) => {
try {
const suppressEvents = options?.suppressEvents === true;
// Guarded: a partial timeline without pause() must still get its seek.
pauseTimelineIfPossible(timeline);
seekGsapTimeline(timeline, timeSeconds, suppressEvents, gsapStructureOf(timeline), renderFps);
const structure = gsapStructureOf(timeline);
const redrawn = seekGsapTimeline(timeline, timeSeconds, suppressEvents, structure, renderFps);
if (redrawDue && !redrawn) redrawGsapTimelineAt(timeline, timeSeconds, structure);
} catch (err) {
// The scene's own callback threw. A warning, not a script error: it must not turn a
// timed-out timeline wait into a script failure.
@@ -5774,9 +5778,8 @@ export function initSandboxRuntimeModular(): void {
sceneClocks.set(timeline, clock);
return clock;
};
const restingAt = new WeakMap<object, number>();
const restsAt = (timeline: RuntimeTimelineLike, time: number): boolean => {
if (restingAt.get(timeline) !== time) return false;
if (sceneRestingAt(timeline) !== time) return false;
try {
return (
(timeline.paused as () => unknown)() === true && Number(timeline.totalTime?.()) === time
@@ -5819,9 +5822,10 @@ export function initSandboxRuntimeModular(): void {
: sourceTime,
);
// A scene before or after its clip rests where the last frame left it: no redraw.
if (!renderCaptureSeekStarted && restsAt(timeline, localTime)) continue;
seekSceneTimeline(compositionId, timeline, localTime, options);
restingAt.set(timeline, localTime);
const redrawDue = takeSceneRedrawDue(timeline);
if (!redrawDue && !renderCaptureSeekStarted && restsAt(timeline, localTime)) continue;
seekSceneTimeline(compositionId, timeline, localTime, options, redrawDue);
restSceneAt(timeline, localTime);
}
};
@@ -5950,15 +5954,7 @@ export function initSandboxRuntimeModular(): void {
const redrawn = seekGsapTimeline(tl, tlSeekTime, suppressEvents, structure, renderFps);
if (!redrawn && !suppressEvents && !hasZeroDurationCallbackTween(tl, structure)) {
// The first seek is the only eventful one; the re-render only refreshes styles.
rerenderGsapTimelineAt(
{
totalTime: tl.totalTime.bind(tl),
totalDuration: tl.totalDuration?.bind(tl),
getChildren: tl.getChildren?.bind(tl),
},
tlSeekTime,
structure,
);
redrawGsapTimelineAt(tl, tlSeekTime, structure);
}
} else {
tl.seek(tlSeekTime, suppressEvents);
+17
View File
@@ -0,0 +1,17 @@
// The local time each scene timeline was last drawn at: a seek that would draw it there again skips it.
const restingAt = new WeakMap<object, number>();
const redrawDue = new WeakSet<object>();
export function restSceneAt(timeline: object, time: number): void {
restingAt.set(timeline, time);
}
export const sceneRestingAt = (timeline: object): number | undefined => restingAt.get(timeline);
export function takeSceneRedrawDue(timeline: object): boolean {
return redrawDue.delete(timeline);
}
export function markRestingScenesForRedraw(timelines: readonly object[]): void {
for (const timeline of timelines) if (restingAt.has(timeline)) redrawDue.add(timeline);
}