fix(studio): address #1607 review — cold-parse vs fetch-error budgets, isZeroDurationSet, array-ease tests

- useGsapAnimationFetchFallback: discriminate resolved/fetch-error/cold; only the cold
  (warm-but-zero) race gets the full ~600ms retry budget — a hard fetch error retries once.
- Extract isZeroDurationSet (was !(duration>0) duplicated); rejects NaN, documents intent.
- parsePercentageKeyframes: cite GSAP even-index spread; tests that a per-entry/interior
  ease is stripped without shifting the other keyframes' percentages.
This commit is contained in:
Miguel Ángel
2026-06-20 16:08:23 -04:00
parent 105c86520d
commit e28b30549c
6 changed files with 118 additions and 34 deletions
@@ -19,6 +19,9 @@ describe("readRuntimeKeyframes — zero-duration set must not shadow the keyfram
const el = { id: "puck-b" };
const holdSet = {
targets: () => [el],
// `data` is the STUDIO_HOLD_MARKER sentinel ("hf-hold") from core's gsapParser.
// TODO(core follow-up): re-export STUDIO_HOLD_MARKER via the @hyperframes/core/
// gsap-parser subpath so this fixture can import the const instead of the literal.
vars: { x: 0, y: 0, data: "hf-hold" },
duration: () => 0,
startTime: () => 0,
@@ -72,6 +72,17 @@ function isXY(p: unknown): p is { x: number; y: number } {
return !!p && typeof (p as any).x === "number" && typeof (p as any).y === "number";
}
/**
* A tween we must skip when reading keyframes: a zero-duration `set`/hold (incl.
* the studio pre-keyframe position hold, tagged `data: STUDIO_HOLD_MARKER`).
* These sit before the real keyframed tween and otherwise shadow it — `readTween`
* would fall back to a degenerate 2-point flat path from the set's values, hiding
* the actual multi-keyframe motion. `!(duration > 0)` also rejects NaN durations.
*/
function isZeroDurationSet(duration: number): boolean {
return !(duration > 0);
}
/** Coordinates + curviness from a live `vars.motionPath` value (object or array form), or null. */
function coordsFromMotionPath(mp: unknown): {
coords: Array<{ x: number; y: number }>;
@@ -186,12 +197,8 @@ export function readRuntimeKeyframes(
let firstRead: ReadTween | null = null;
for (const tween of timeline.getChildren(true)) {
if (!tween.vars || !matchesElement(tween, targetEl)) continue;
// Skip zero-duration tweens (`tl.set(...)`, incl. the studio position-hold
// `data:"hf-hold"`). They sit before the real keyframed tween and otherwise
// shadow it — `readTween` falls back to a degenerate 2-point flat path from
// the set's values, hiding the actual multi-keyframe motion.
const dur = typeof tween.duration === "function" ? tween.duration() : 0;
if (!(dur > 0)) continue;
if (isZeroDurationSet(dur)) continue; // skip hold/set tweens (see isZeroDurationSet)
const read = readTween(tween.vars);
if (!read) continue;
if (firstRead === null) firstRead = read;
@@ -243,9 +250,7 @@ function addScanEntry(
): void {
if (!tween.targets || !tween.vars) return;
const { start, duration } = tweenTiming(tween);
// Skip zero-duration sets/holds — they shadow the real keyframed tween (see
// readRuntimeKeyframes).
if (!(duration > 0)) return;
if (isZeroDurationSet(duration)) return; // skip hold/set tweens (see isZeroDurationSet)
const read = readTween(tween.vars);
if (!read) return;
for (const target of tween.targets()) {
@@ -23,6 +23,34 @@ describe("parsePercentageKeyframes", () => {
expect(out?.keyframes[1]!.properties).toEqual({ x: 520, y: 120 });
});
it("strips a per-entry ease without shifting the even index-spacing of the others", () => {
// GSAP positions array keyframes by array index, so a `{ ease }` carried on an
// entry is a segment ease (skipped as a property) — it must not change where
// the surrounding keyframes land. 3 entries → 0 / 50 / 100, even though the
// middle entry also carries an ease.
const out = parsePercentageKeyframes([
{ x: 0 },
{ x: 100, ease: "power2.in" },
{ x: 200 },
] as unknown as Record<string, unknown>);
expect(out?.keyframes.map((k) => k.percentage)).toEqual([0, 50, 100]);
expect(out?.keyframes.map((k) => k.properties)).toEqual([{ x: 0 }, { x: 100 }, { x: 200 }]);
});
it("keeps even spacing when an interior array slot has no animatable prop", () => {
// A degenerate `{ ease }`-only slot contributes no output keyframe, but it is
// still an array slot GSAP allocates a position to — so the remaining entries
// keep their original i/(n-1) percentages (0 and 100 for a 3-slot array), not
// 0/100 collapsed onto a 2-entry spacing.
const out = parsePercentageKeyframes([
{ x: 0 },
{ ease: "power2.in" },
{ x: 200 },
] as unknown as Record<string, unknown>);
expect(out?.keyframes.map((k) => k.percentage)).toEqual([0, 100]);
expect(out?.keyframes.map((k) => k.properties)).toEqual([{ x: 0 }, { x: 200 }]);
});
it("returns null for keyframes with no positional/animatable props", () => {
expect(parsePercentageKeyframes([] as unknown as Record<string, unknown>)).toBeNull();
expect(parsePercentageKeyframes({})).toBeNull();
+12 -4
View File
@@ -115,10 +115,18 @@ export function parsePercentageKeyframes(
const keyframes: ParsedPercentageKeyframes["keyframes"] = [];
let easeEach: string | undefined;
// GSAP array-form keyframes — `keyframes: [{x,y}, {x,y}, ...]` — are evenly
// distributed across the tween, so step i of n maps to i/(n-1)*100%. (The object
// form below uses explicit "0%" keys.) Without this, array-keyframed tweens (e.g.
// a multi-point shuttle path) read as null → no motion path.
// GSAP array-form keyframes — `keyframes: [{x,y}, {x,y}, ...]` — are spread
// evenly across the tween by default: GSAP gives each entry an equal share of
// the duration unless an entry carries its own `duration`/`delay`, which the
// studio never emits. So entry i of n maps to i/(n-1)*100% (n=4 → 0/33.3/66.7/100).
// Index spacing counts EVERY array slot, including a degenerate entry that
// contributes no animatable prop (it's still a slot GSAP allocates a position
// to), so dropping such an entry from the output below must NOT shift the others.
// A per-entry `ease` is a segment ease, not a keyframe value, so it's skipped as
// a property; there is no array-form `easeEach` (that's an object-form sibling key).
// (The object form further down uses explicit "0%" keys instead.) Without this
// branch, array-keyframed tweens (e.g. a multi-point shuttle) read as null → no
// motion path.
if (Array.isArray(kfObj)) {
const steps = kfObj as unknown[];
steps.forEach((entry, i) => {
@@ -8,20 +8,29 @@ const parsed = (anims: GsapAnimation[]): ParsedGsap => ({ animations: anims }) a
const target = { id: "puck-a", selector: "#puck-a" };
describe("selectElementAnimationsOrRetry", () => {
it("returns null (retry) when the parse is cold — null or zero total animations", () => {
expect(selectElementAnimationsOrRetry(null, target)).toBeNull();
expect(selectElementAnimationsOrRetry(parsed([]), target)).toBeNull();
it("signals fetch-error (short retry) when the fetch itself failed (null)", () => {
// A null parse means fetchParsedAnimations hit a 404/network/JSON failure —
// not a parse-warming race, so it must NOT be conflated with a cold parse.
expect(selectElementAnimationsOrRetry(null, target)).toEqual({ kind: "fetch-error" });
});
it("returns the matching animations from a warm parse", () => {
const result = selectElementAnimationsOrRetry(
it("signals cold (full retry budget) when the parse is reachable but has zero total animations", () => {
expect(selectElementAnimationsOrRetry(parsed([]), target)).toEqual({ kind: "cold" });
});
it("resolves the matching animations from a warm parse", () => {
const outcome = selectElementAnimationsOrRetry(
parsed([anim("#puck-a"), anim("#other")]),
target,
);
expect(result?.map((a) => a.targetSelector)).toEqual(["#puck-a"]);
expect(outcome.kind).toBe("resolved");
expect(outcome.kind === "resolved" && outcome.animations.map((a) => a.targetSelector)).toEqual([
"#puck-a",
]);
});
it("returns [] (no retry) for a warm parse with no match — element genuinely has no animation", () => {
expect(selectElementAnimationsOrRetry(parsed([anim("#other")]), target)).toEqual([]);
it("resolves to [] (no retry) for a warm parse with no match — element genuinely has no animation", () => {
const outcome = selectElementAnimationsOrRetry(parsed([anim("#other")]), target);
expect(outcome).toEqual({ kind: "resolved", animations: [] });
});
});
@@ -3,25 +3,45 @@ import type { GsapAnimation, ParsedGsap } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditing";
import { fetchParsedAnimations, getAnimationsForElement } from "./useGsapTweenCache";
// A cold parse is the initial-load race: the endpoint is reachable but its parse
// isn't warm yet (zero total animations). It's worth waiting out (~600ms).
const COLD_PARSE_RETRIES = 5;
const COLD_PARSE_DELAY_MS = 120;
// A hard fetch error (404/403/network/JSON failure → `fetchParsedAnimations`
// returns null) is NOT a parse-warming race, so it shouldn't burn the full
// cold-parse budget. One short retry covers a transient blip; beyond that the
// endpoint genuinely isn't serving this file, so fall through to "no animation".
const FETCH_ERROR_RETRIES = 1;
const FETCH_ERROR_DELAY_MS = 120;
const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
/**
* Decide an element's animations from a parse result, or signal a retry.
*
* Returns `null` only when the parse is *cold* (missing or zero total animations)
* — the initial-load race where the endpoint isn't ready yet, so the caller should
* retry. A warm parse with no match for this element returns `[]` (the element
* genuinely has no animation — create a new one, don't retry).
* Outcome of resolving an element's animations from a single parse result.
* - `resolved`: a definitive answer (matched animations, or `[]` when the parse
* is warm but this element has no animation — create a new one, don't retry).
* - `fetch-error`: `fetchParsedAnimations` returned null (HTTP/network/JSON
* failure) — retry briefly, not for the full cold-parse budget.
* - `cold`: the parse came back reachable but with zero total animations — the
* initial-load warming race, worth the full cold-parse retry budget.
*/
export type ElementAnimationsOutcome =
| { kind: "resolved"; animations: GsapAnimation[] }
| { kind: "fetch-error" }
| { kind: "cold" };
/**
* Classify a parse result for one element. Differentiates a hard fetch failure
* (`parsed === null`) from a warm-but-empty cold parse (`animations.length === 0`)
* so the caller can apply the right retry budget to each.
*/
export function selectElementAnimationsOrRetry(
parsed: ParsedGsap | null,
target: { id: string | null; selector: string | null },
): GsapAnimation[] | null {
if (!parsed || parsed.animations.length === 0) return null;
return getAnimationsForElement(parsed.animations, target);
): ElementAnimationsOutcome {
if (!parsed) return { kind: "fetch-error" };
if (parsed.animations.length === 0) return { kind: "cold" };
return { kind: "resolved", animations: getAnimationsForElement(parsed.animations, target) };
}
export function useGsapAnimationFetchFallback(projectId: string | null, gsapSourceFile: string) {
@@ -30,12 +50,23 @@ export function useGsapAnimationFetchFallback(projectId: string | null, gsapSour
if (!projectId) return [];
const target = { id: selection.id ?? null, selector: selection.selector ?? null };
// A drag can fire before the async parse is warm; a cold parse must retry
// rather than fall through to the no-animation path (which duplicates the tween).
for (let attempt = 0; ; attempt++) {
// rather than fall through to the no-animation path (which duplicates the
// tween). A hard fetch error is a different failure — retry only briefly.
let coldAttempts = 0;
let errorAttempts = 0;
for (;;) {
const parsed = await fetchParsedAnimations(projectId, gsapSourceFile);
const resolved = selectElementAnimationsOrRetry(parsed, target);
if (resolved !== null) return resolved;
if (attempt >= COLD_PARSE_RETRIES) return [];
const outcome = selectElementAnimationsOrRetry(parsed, target);
if (outcome.kind === "resolved") return outcome.animations;
if (outcome.kind === "fetch-error") {
if (errorAttempts >= FETCH_ERROR_RETRIES) return [];
errorAttempts++;
await delay(FETCH_ERROR_DELAY_MS);
continue;
}
// cold
if (coldAttempts >= COLD_PARSE_RETRIES) return [];
coldAttempts++;
await delay(COLD_PARSE_DELAY_MS);
}
},