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
134 changes: 134 additions & 0 deletions packages/core/src/runtime/adapters/gsap.mute.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// @vitest-environment happy-dom
import gsap from "gsap";
import { describe, expect, it, vi } from "vitest";
import { muteDiscreteCallbacks } from "./gsap";
import type { RuntimeTimelineLike } from "../types";

const asRuntime = (tl: gsap.core.Timeline): RuntimeTimelineLike =>
tl as unknown as RuntimeTimelineLike;

function sweep(tl: gsap.core.Timeline, ...times: number[]): void {
for (const t of times) tl.seek(t, false);
}

describe("muteDiscreteCallbacks", () => {
it("quiets onStart, onComplete, onReverseComplete and onRepeat, and leaves onUpdate firing", () => {
const fired = { start: 0, complete: 0, reverse: 0, repeat: 0, update: 0 };
const tl = gsap.timeline({ paused: true });
tl.to(
{ v: 0 },
{
v: 1,
duration: 0.2,
repeat: 1,
onStart: () => void fired.start++,
onComplete: () => void fired.complete++,
onReverseComplete: () => void fired.reverse++,
onRepeat: () => void fired.repeat++,
onUpdate: () => void fired.update++,
},
0.1,
);

const restore = muteDiscreteCallbacks([asRuntime(tl)]);
sweep(tl, 0, 0.2, 0.6, 0);
expect(fired.start + fired.complete + fired.reverse + fired.repeat).toBe(0);
expect(fired.update).toBeGreaterThan(0);

restore();
sweep(tl, 0.2, 0.6, 0);
expect(fired.start).toBeGreaterThan(0);
expect(fired.complete).toBeGreaterThan(0);
expect(fired.reverse).toBeGreaterThan(0);
expect(fired.repeat).toBeGreaterThan(0);
});

it("reaches a stagger's and a keyframes tween's own tweens", () => {
const staggered = vi.fn();
const keyed = vi.fn();
const tl = gsap.timeline({ paused: true });
tl.to(
[{ v: 0 }, { v: 0 }],
{
v: 1,
duration: 0.05,
stagger: { each: 0.05, onComplete: staggered },
},
0.1,
);
tl.to(
{ v: 0 },
{
keyframes: [
{ v: 0.5, duration: 0.05 },
{ v: 1, duration: 0.05, onComplete: keyed },
],
},
0.4,
);

const restore = muteDiscreteCallbacks([asRuntime(tl)]);
sweep(tl, 0, 1);
expect(staggered).not.toHaveBeenCalled();
expect(keyed).not.toHaveBeenCalled();

restore();
sweep(tl, 0, 1);
expect(staggered).toHaveBeenCalled();
expect(keyed).toHaveBeenCalled();
});

it("restores a callback reached through two timelines", () => {
const fn = vi.fn();
const root = gsap.timeline({ paused: true });
const scene = gsap.timeline();
scene.call(fn, [], 0.5);
root.add(scene, 0);

const restore = muteDiscreteCallbacks([asRuntime(scene), asRuntime(root)]);
sweep(root, 0, 1);
expect(fn).not.toHaveBeenCalled();

restore();
sweep(root, 0, 1);
expect(fn).toHaveBeenCalledTimes(1);
});

it("restores the outer mute's callbacks when mutes nest", () => {
const fn = vi.fn();
const tl = gsap.timeline({ paused: true });
tl.call(fn, [], 0.5);

const outer = muteDiscreteCallbacks([asRuntime(tl)]);
const inner = muteDiscreteCallbacks([asRuntime(tl)]);
inner();
sweep(tl, 0, 1);
expect(fn).not.toHaveBeenCalled();

outer();
sweep(tl, 0, 1);
expect(fn).toHaveBeenCalledTimes(1);
});

it("keeps a replaced function's params and scope", () => {
const scope = { name: "scope" };
const seen: Array<{ args: unknown[]; scope: unknown }> = [];
const fn = function (this: unknown, ...args: unknown[]): void {
seen.push({ args, scope: this });
};
const tl = gsap.timeline({ paused: true });
tl.call(fn, ["x"], 0.5);
const call = tl.getChildren(false, true, false)[0] as gsap.core.Tween;
call.vars.callbackScope = scope;

const restore = muteDiscreteCallbacks([asRuntime(tl)]);
sweep(tl, 0, 1);
expect(seen).toEqual([]);

restore();
sweep(tl, 0, 1);
expect(seen).toHaveLength(1);
expect(seen[0]?.args).toEqual(["x"]);
expect(seen[0]?.scope).toBe(scope);
});
});
37 changes: 37 additions & 0 deletions packages/core/src/runtime/adapters/gsap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,43 @@ export function holdFrameMarks({
};
}

type GsapCallbackHolder = {
vars?: Record<string, unknown>;
timeline?: { getChildren?: RuntimeTimelineLike["getChildren"] };
getChildren?: RuntimeTimelineLike["getChildren"];
};

const DISCRETE_CALLBACKS = ["onStart", "onComplete", "onReverseComplete", "onRepeat"] as const;

const noOpInPlaceOfCallback = (): void => {};

function eachAnimationIn(
animation: GsapCallbackHolder,
visit: (a: GsapCallbackHolder) => void,
): void {
visit(animation);
for (const child of (animation.getChildren?.(false, true, true) ?? []) as GsapCallbackHolder[])
eachAnimationIn(child, visit);
if (animation.timeline) eachAnimationIn(animation.timeline as GsapCallbackHolder, visit);
}

export function muteDiscreteCallbacks(timelines: RuntimeTimelineLike[]): () => void {
const held: Array<[Record<string, unknown>, string, unknown]> = [];
for (const timeline of timelines) {
eachAnimationIn(gsapTimelineOf(timeline) as GsapCallbackHolder, ({ vars }) => {
if (!vars) return;
for (const name of DISCRETE_CALLBACKS) {
if (typeof vars[name] !== "function" || vars[name] === noOpInPlaceOfCallback) continue;
held.push([vars, name, vars[name]]);
vars[name] = noOpInPlaceOfCallback;
}
});
}
return () => {
for (const [vars, name, callback] of held) vars[name] = callback;
};
Comment on lines +506 to +519

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

important — If the walk throws partway, the callbacks it has already muted stay no-ops for the rest of the session, and the next mute/restore can't bring them back. On the next pass those no-ops look like an outer mute's, so the skip on L500 passes over them and they never go into held. I reproduced it: muteDiscreteCallbacks([a, objWhoseGetChildrenThrows]) throws, after which a's tl.call fires 0 times, including after a later full mute → restore → seek(0)/seek(1) cycle. whileCallbacksMuted calls muteCallbacks() before its try, and the paint swallows the error (runtime.captureMotionBlur.paint), so the film just loses its calls without any visible failure. The trigger is any window.__timelines entry that isn't a GSAP timeline and whose getChildren throws (or nests deeply enough to overflow the recursion).

The fix is small. The same guard on restore also covers your second limit, a callback reassigned while muted. I ran it with both cases as tests, plus gsap.mute.test.ts and captureMotionBlur/: 220/220 pass.

Suggested change
const held: Array<[Record<string, unknown>, string, unknown]> = [];
for (const timeline of timelines) {
eachAnimationIn(gsapTimelineOf(timeline) as GsapCallbackHolder, ({ vars }) => {
if (!vars) return;
for (const name of DISCRETE_CALLBACKS) {
if (typeof vars[name] !== "function" || vars[name] === noOpInPlaceOfCallback) continue;
held.push([vars, name, vars[name]]);
vars[name] = noOpInPlaceOfCallback;
}
});
}
return () => {
for (const [vars, name, callback] of held) vars[name] = callback;
};
const held: Array<[Record<string, unknown>, string, unknown]> = [];
const restore = (): void => {
for (const [vars, name, callback] of held)
if (vars[name] === noOpInPlaceOfCallback) vars[name] = callback;
};
try {
for (const timeline of timelines) {
eachAnimationIn(gsapTimelineOf(timeline) as GsapCallbackHolder, ({ vars }) => {
if (!vars) return;
for (const name of DISCRETE_CALLBACKS) {
if (typeof vars[name] !== "function" || vars[name] === noOpInPlaceOfCallback) continue;
held.push([vars, name, vars[name]]);
vars[name] = noOpInPlaceOfCallback;
}
});
}
} catch (err) {
restore();
throw err;
}
return restore;

}

function landingMarksOf(
timeline: { getChildren?: RuntimeTimelineLike["getChildren"] },
structure: GsapStructureKey | undefined,
Expand Down
83 changes: 10 additions & 73 deletions packages/core/src/runtime/captureMotionBlur/discover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,80 +292,17 @@ function boxesKey(boxes: ReadonlyArray<DOMRect | undefined>): number {
return h;
}

type FirstValue = [namespace: string | null, name: string, old: string | null];

type DomJournal = { flush: () => void; undo: () => void; stop: () => void };

function journalDom(doc: Document): DomJournal {
const firstValues = new Map<Node, Map<string, FirstValue>>();
const trees: MutationRecord[] = [];
const fold = (records: MutationRecord[]): void => {
for (const r of records) {
if (r.type === "childList") {
trees.push(r);
continue;
}
const own = firstValues.get(r.target) ?? new Map<string, FirstValue>();
firstValues.set(r.target, own);
const key = `${r.attributeNamespace}:${r.attributeName}`;
if (!own.has(key)) own.set(key, [r.attributeNamespace, r.attributeName ?? "", r.oldValue]);
}
};
const observer = new MutationObserver(fold);
observer.observe(doc, {
subtree: true,
childList: true,
attributes: true,
attributeOldValue: true,
characterData: true,
characterDataOldValue: true,
});
return {
flush: () => fold(observer.takeRecords()),
stop: () => observer.disconnect(),
undo: () => {
fold(observer.takeRecords());
observer.disconnect();
for (const r of trees.reverse()) {
r.addedNodes.forEach((n) => n.parentNode === r.target && r.target.removeChild(n));
r.removedNodes.forEach((n) => r.target.insertBefore(n, r.nextSibling));
}
for (const [node, values] of firstValues) {
for (const [ns, name, old] of values.values()) {
putBack(node, ns, name, old);
}
}
},
};
}

const isElement = (node: Node): node is Element => node.nodeType === 1;

function putBack(node: Node, ns: string | null, name: string, old: string | null): void {
if (!isElement(node)) {
const text = old ?? "";
if ((node as CharacterData).data !== text) (node as CharacterData).data = text;
return;
export function whileCallbacksMuted<T>(
host: { muteCallbacks?: () => () => void },
muted: boolean,
run: () => T,
): T {
const unmute = muted ? host.muteCallbacks?.() : undefined;
try {
return run();
} finally {
unmute?.();
}
if (node.getAttributeNS(ns, name) === old) return;
if (old === null) node.removeAttributeNS(ns, name);
else node.setAttributeNS(ns, name, old);
}

// A callback a loud seek fired cannot be un-fired: land with callbacks on, then put the DOM back.
export function landThenUndoDom(
seek: (t: number) => void,
doc: Document,
): Omit<DomJournal, "undo"> & { land: (t: number) => void } {
const journal = journalDom(doc);
return {
flush: journal.flush,
stop: journal.stop,
land: (t) => {
seek(t);
journal.undo();
},
};
}

/** Discovery, and whether pose reads need callbacks: when they change an element's style or box. */
Expand Down
33 changes: 13 additions & 20 deletions packages/core/src/runtime/captureMotionBlur/filterTier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { swallow } from "../diagnostics";
import { landThenUndoDom, scanMovers } from "./discover";
import { scanMovers, whileCallbacksMuted } from "./discover";
import { planFilter, type FilterPlan } from "./filterPlan";
import { readMoverFrames, shutterTimes } from "./frames";
import { createPoseReader } from "./pose";
Expand Down Expand Up @@ -123,21 +123,17 @@ export function createFilterTier(
function discover(restoreTo: number): void {
scanned = host.timeline();
const s0 = performance.now();
const landing = config.events ? landThenUndoDom(seek, document) : null;
let found: ReturnType<typeof scanMovers>;
try {
found = scanMovers({
const found = whileCallbacksMuted(host, config.events, () => {
const scan = scanMovers({
scene: root,
durationSeconds: host.durationSeconds(),
fps: host.fps,
seek: host.seek,
events: config.events,
onStep: landing?.flush,
});
(landing?.land ?? seek)(restoreTo);
} finally {
landing?.stop();
}
seek(restoreTo);
return scan;
});
readEvents = found.readEvents;
movers = found.movers;
pads = found.pads;
Expand Down Expand Up @@ -186,25 +182,22 @@ export function createFilterTier(
function plansAt(t: number, engineMode: boolean): Array<[HTMLElement, FilterPlan]> {
if (!reader || host.timeline() !== scanned) discover(t);
if (!reader) return [];
const landing = readEvents ? landThenUndoDom(readSeek, document) : null;
let read: ReturnType<typeof readMoverFrames>;
try {
read = readMoverFrames({
const poseReader = reader;
const read = whileCallbacksMuted(host, readEvents, () =>
readMoverFrames({
movers,
reader,
reader: poseReader,
seek: readSeek,
restore: landing?.land ?? host.holdFrame?.(),
restore: readEvents ? undefined : host.holdFrame?.(),
t,
reads: engineMode ? RENDER_READS : PREVIEW_READS,
...shutterTimes(config.shutterDeg, config.phaseDeg, host.fps),
taps: COPIES,
frameW: width,
scene: root,
frameH: height,
});
} finally {
landing?.stop();
}
}),
);
const plans: Array<[HTMLElement, FilterPlan]> = [];
read.els.forEach((el, i) => {
const frame = read.frames[i];
Expand Down
Loading
Loading