mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
fix(studio): a sealed undo or redo of a keyframe edit re-runs in place instead of reloading (#8272)
This commit is contained in:
@@ -80,16 +80,21 @@ function scope(value: unknown): RestoreScope | null {
|
||||
return parsed.every(Boolean) ? { file, elements: parsed as RestoreScope["elements"] } : null;
|
||||
}
|
||||
|
||||
export function parseRestoreAttributes(params: unknown): RestoreAttributesParams | null {
|
||||
if (!isRecord(params) || !keysAre(params, "scopes,scripted,time")) return null;
|
||||
const { scopes, scripted, time } = params;
|
||||
if (typeof scripted !== "boolean") return null;
|
||||
if (typeof time !== "number" || !Number.isFinite(time) || time < 0) return null;
|
||||
if (!Array.isArray(scopes) || !scopes.length || scopes.length > MAX_SCOPES) return null;
|
||||
export function parseRestoreScopes(scopes: unknown): RestoreScope[] | null {
|
||||
if (!Array.isArray(scopes) || scopes.length > MAX_SCOPES) return null;
|
||||
const parsed = scopes.map(scope);
|
||||
if (!parsed.every(Boolean)) return null;
|
||||
const count = (parsed as RestoreScope[]).reduce((n, s) => n + s.elements.length, 0);
|
||||
return count <= MAX_ELEMENTS ? { scopes: parsed as RestoreScope[], scripted, time } : null;
|
||||
return count <= MAX_ELEMENTS ? (parsed as RestoreScope[]) : null;
|
||||
}
|
||||
|
||||
export function parseRestoreAttributes(params: unknown): RestoreAttributesParams | null {
|
||||
if (!isRecord(params) || !keysAre(params, "scopes,scripted,time")) return null;
|
||||
const { scripted, time } = params;
|
||||
if (typeof scripted !== "boolean") return null;
|
||||
if (typeof time !== "number" || !Number.isFinite(time) || time < 0) return null;
|
||||
const scopes = parseRestoreScopes(params.scopes);
|
||||
return scopes?.length ? { scopes, scripted, time } : null;
|
||||
}
|
||||
|
||||
function identityKey(el: Element): RestoreElementKey | null {
|
||||
@@ -119,7 +124,7 @@ function scopeRoots(file: string | null): ParentNode[] {
|
||||
);
|
||||
}
|
||||
|
||||
type RestorePlan = [Element, drop: string[], set: RestoreAttribute[]][];
|
||||
export type RestorePlan = [Element, drop: string[], set: RestoreAttribute[]][];
|
||||
|
||||
/** Adds `root`'s live elements to `plan`; false when any is missing, not the file's own, or unsafe to change. */
|
||||
function planRoot(
|
||||
@@ -143,7 +148,7 @@ function planRoot(
|
||||
}
|
||||
|
||||
/** Each live element with the attributes it drops and sets, or null when the restore cannot apply in place. */
|
||||
function planRestore(scopes: RestoreScope[]): RestorePlan | null {
|
||||
export function planRestore(scopes: RestoreScope[]): RestorePlan | null {
|
||||
const plan: RestorePlan = [];
|
||||
for (const { file, elements } of scopes) {
|
||||
const roots = scopeRoots(file);
|
||||
@@ -152,6 +157,13 @@ function planRestore(scopes: RestoreScope[]): RestorePlan | null {
|
||||
return plan;
|
||||
}
|
||||
|
||||
export function applyRestorePlan(plan: RestorePlan): void {
|
||||
for (const [el, drop, set] of plan) {
|
||||
for (const name of drop) el.removeAttribute(name);
|
||||
for (const [name, value] of set) el.setAttribute(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
type RestoreWindow = Window & {
|
||||
__player?: { seek?: (t: number) => void; isPlaying?: () => boolean; play?: () => void };
|
||||
__hfForceTimelineRebind?: () => void;
|
||||
@@ -180,10 +192,7 @@ export function restoreAttributes({ scopes, scripted, time }: RestoreAttributesP
|
||||
const plan = planRestore(scopes);
|
||||
if (!plan || typeof win.__player?.seek !== "function") return { applied: false };
|
||||
if (scripted && plan.some(([el]) => "_gsap" in el)) return { applied: false };
|
||||
for (const [el, drop, set] of plan) {
|
||||
for (const name of drop) el.removeAttribute(name);
|
||||
for (const [name, value] of set) el.setAttribute(name, value);
|
||||
}
|
||||
applyRestorePlan(plan);
|
||||
rebindAt(win, time);
|
||||
return { applied: true };
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ const params = (over: Partial<SoftReloadParams> = {}): SoftReloadParams => ({
|
||||
sets: [],
|
||||
authored: [],
|
||||
timing: [],
|
||||
restore: [],
|
||||
...over,
|
||||
});
|
||||
|
||||
@@ -100,6 +101,47 @@ describe("soft-reload", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const restoreOf = (key: string, attributes: Array<[string, string]>) => ({
|
||||
file: null,
|
||||
elements: [{ key, attributes }],
|
||||
});
|
||||
|
||||
// fails without the fix: a sealed undo of a keyframe edit could not re-run in place, so the preview reloaded.
|
||||
describe("soft-reload of an undo", () => {
|
||||
const MARKUP = `<div data-composition-id="main"><div id="a" data-hf-id="h1" style="left: 90px" data-hf-studio-path-offset="1"></div></div>`;
|
||||
const KEPT: Array<[string, string]> = [
|
||||
["id", "a"],
|
||||
["data-hf-id", "h1"],
|
||||
];
|
||||
|
||||
it("sets the restored attributes before the re-run, as restore-attributes would", async () => {
|
||||
preview(MARKUP);
|
||||
const el = document.getElementById("a")!;
|
||||
const seen: Array<string | null> = [];
|
||||
win.__hfForceTimelineRebind = () => seen.push(el.getAttribute("style"));
|
||||
|
||||
const restore = [restoreOf("hf:h1", [...KEPT, ["style", "left: 0px"]])];
|
||||
expect(await softReload(params({ restore }))).toEqual({ result: "applied" });
|
||||
|
||||
expect(seen).toEqual(["left: 0px"]);
|
||||
expect(el.hasAttribute("data-hf-studio-path-offset")).toBe(false);
|
||||
expect(killed).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("refuses the whole request and changes nothing when the restore carries an attribute it may not set", async () => {
|
||||
preview(MARKUP);
|
||||
const el = document.getElementById("a")!;
|
||||
const restore = [restoreOf("hf:h1", [...KEPT, ["style", "left: 0px"], ["onclick", "x()"]])];
|
||||
|
||||
expect(await softReload(params({ restore }))).toEqual({ result: "cannot-soft-reload" });
|
||||
|
||||
expect(el.getAttribute("style")).toBe("left: 90px");
|
||||
expect(el.hasAttribute("onclick")).toBe(false);
|
||||
expect(killed).not.toHaveBeenCalled();
|
||||
expect(document.querySelector("script")?.textContent).toBe(SCRIPT);
|
||||
});
|
||||
});
|
||||
|
||||
describe("soft-reload of a timing edit", () => {
|
||||
const MARKUP = `<div data-composition-id="main" data-hf-id="root" data-duration="5"><div id="clip" data-start="1" data-duration="2" data-hf-autostamped></div></div>`;
|
||||
|
||||
@@ -172,6 +214,8 @@ describe("parseSoftReload", () => {
|
||||
["an authored entry with three parts", params({ authored: [["#a", "", ""] as never] })],
|
||||
["a timing attribute that is not timing", params({ timing: [["#a", [["style", "x"]]]] })],
|
||||
["no timing field", { ...params(), timing: undefined }],
|
||||
["no restore field", { ...params(), restore: undefined }],
|
||||
["a restore element keyed by neither id", params({ restore: [restoreOf("a", [])] })],
|
||||
])("refuses %s", (_label, request) => {
|
||||
expect(parseSoftReload(request)).toBeNull();
|
||||
});
|
||||
|
||||
@@ -5,6 +5,13 @@ import { GSAP_BASE_URL_META, motionPathPluginUrl } from "../../gsapCdn";
|
||||
import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "../../colorGrading";
|
||||
import { escapeCssString } from "../editingElement";
|
||||
import { applyAuthoredTiming } from "../../studioPreviewMark";
|
||||
import {
|
||||
applyRestorePlan,
|
||||
parseRestoreScopes,
|
||||
planRestore,
|
||||
type RestorePlan,
|
||||
type RestoreScope,
|
||||
} from "./restoreAttributes";
|
||||
|
||||
type TweenLike = {
|
||||
targets?: () => unknown[];
|
||||
@@ -54,6 +61,7 @@ export interface SoftReloadInput {
|
||||
) => string | null | undefined;
|
||||
/** A sealed timing edit's saved timing, which a reachable preview's commit already patched live. */
|
||||
timing?: SavedTiming;
|
||||
restorePlan?: RestorePlan;
|
||||
}
|
||||
|
||||
/** The attributes the runtime derives clip windows and the film's length from. */
|
||||
@@ -488,6 +496,7 @@ export function softReloadFrame(
|
||||
};
|
||||
|
||||
const doReload = () => {
|
||||
if (input.restorePlan) applyRestorePlan(input.restorePlan);
|
||||
applyTimingPlan(timing);
|
||||
killTimelines(win, targetKeys);
|
||||
resetTargetStyles(win, targets, authored);
|
||||
@@ -522,6 +531,8 @@ export type SoftReloadParams = {
|
||||
authored: Array<[string, string]>;
|
||||
/** Empty unless a timing edit: the saved file's timing, applied before the re-run's rebind. */
|
||||
timing: SavedTiming;
|
||||
/** An undo's or redo's restored attributes, set as `restore-attributes` would before the re-run. */
|
||||
restore: RestoreScope[];
|
||||
};
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
@@ -566,18 +577,19 @@ export function parseSavedTiming(value: unknown): SavedTiming | null {
|
||||
}
|
||||
|
||||
export function parseSoftReload(params: unknown): SoftReloadParams | null {
|
||||
const fields = "authored,script,sets,time,timing";
|
||||
const fields = "authored,restore,script,sets,time,timing";
|
||||
if (!isRecord(params) || Object.keys(params).sort().join() !== fields) return null;
|
||||
const { script, time, sets, authored } = params;
|
||||
const timing = parseSavedTiming(params.timing);
|
||||
if (!timing) return null;
|
||||
const restore = parseRestoreScopes(params.restore);
|
||||
if (!timing || !restore) return null;
|
||||
if (!boundedString(script, MAX_SOFT_RELOAD_SCRIPT) || script.length === 0) return null;
|
||||
if (typeof time !== "number" || !Number.isFinite(time) || time < 0) return null;
|
||||
if (!Array.isArray(sets) || sets.length > MAX_SETS) return null;
|
||||
if (!Array.isArray(authored) || authored.length > MAX_AUTHORED) return null;
|
||||
const parsedSets = sets.map(parseSet);
|
||||
if (!parsedSets.every(Boolean) || !authored.every(isAuthoredEntry)) return null;
|
||||
return { script, time, sets: parsedSets as StandaloneSet[], authored, timing };
|
||||
return { script, time, sets: parsedSets as StandaloneSet[], authored, timing, restore };
|
||||
}
|
||||
|
||||
/** The key Studio files an element's authored style under: its hf-id, else its id. */
|
||||
@@ -590,11 +602,14 @@ export function authoredKey(el: Element): string | null {
|
||||
/** The frame re-running its own script: only elements of the saved file have authored styles to use. */
|
||||
export async function softReload(params: SoftReloadParams): Promise<{ result: SoftReloadResult }> {
|
||||
const styles = new Map(params.authored);
|
||||
const restorePlan = planRestore(params.restore);
|
||||
if (!restorePlan) return { result: "cannot-soft-reload" };
|
||||
const result = await softReloadFrame(window as SoftReloadWindow, document, {
|
||||
script: params.script,
|
||||
time: params.time,
|
||||
sets: params.sets,
|
||||
timing: params.timing,
|
||||
restorePlan,
|
||||
authoredStyle: (el, file, ownFile) => {
|
||||
if (file !== ownFile) return undefined;
|
||||
const key = authoredKey(el);
|
||||
|
||||
@@ -540,7 +540,7 @@ describe("installEditingAgent", () => {
|
||||
Object.assign(frame, { gsap: { set: () => {} }, __timelines: { main: {} } });
|
||||
frame.__hfForceTimelineRebind = () => {};
|
||||
const port = connectedPort();
|
||||
const params = { script, time: 0, sets: [], authored: [], timing: [] };
|
||||
const params = { script, time: 0, sets: [], authored: [], timing: [], restore: [] };
|
||||
|
||||
const extra = { ...params, keys: ["main"] };
|
||||
expect(await ask(port, { v: 1, id: 1, kind: "soft-reload", params: extra })).toMatchObject({
|
||||
|
||||
@@ -48,8 +48,15 @@ it("sends one request built only from the saved files: the saved script, its aut
|
||||
["#b", ""],
|
||||
]),
|
||||
);
|
||||
expect(Object.keys(params).sort()).toEqual(["authored", "script", "sets", "time", "timing"]);
|
||||
expect(params.timing).toEqual([]);
|
||||
expect(Object.keys(params).sort()).toEqual([
|
||||
"authored",
|
||||
"restore",
|
||||
"script",
|
||||
"sets",
|
||||
"time",
|
||||
"timing",
|
||||
]);
|
||||
expect([params.timing, params.restore]).toEqual([[], []]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
} from "@hyperframes/core/runtime/soft-reload";
|
||||
import { authoredStyles, findAuthoredElement, savedTiming } from "./authoredSource";
|
||||
import { fileDocs, standaloneSets } from "./softReloadTargets";
|
||||
import type { EditingParams } from "@hyperframes/core/runtime/editing-port";
|
||||
import { previewFrameOpaque, previewRequest } from "../player/lib/previewChannel";
|
||||
|
||||
export {
|
||||
@@ -112,6 +113,7 @@ export interface SoftReloadOptions {
|
||||
timingEdit?: boolean;
|
||||
/** Other composition files a reset element is written in, by path; null when one could not be read. */
|
||||
nestedFiles?: Map<string, string> | null;
|
||||
restore?: EditingParams<"soft-reload">["restore"];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -197,6 +199,7 @@ function softReloadSealed(
|
||||
currentTimeOverride,
|
||||
onAsyncFailure,
|
||||
timingEdit,
|
||||
restore = [],
|
||||
}: SoftReloadOptions,
|
||||
): SoftReloadResult {
|
||||
if (authoredHtml === undefined || previousHtml === undefined || currentTimeOverride === undefined)
|
||||
@@ -208,6 +211,7 @@ function softReloadSealed(
|
||||
sets: standaloneSets(outgoingScripts(previous, scriptText)),
|
||||
authored: authoredStyles(authoredHtml),
|
||||
timing: timingEdit ? savedTiming(authoredHtml) : [],
|
||||
restore,
|
||||
}).then((reply) => {
|
||||
if (sealedSoftReloadResult(reply) === "cannot-soft-reload") onAsyncFailure?.();
|
||||
});
|
||||
|
||||
@@ -20,6 +20,14 @@ function undo(previous: string, restored: string) {
|
||||
return { reload, strategy: applyUndoRestoreToPreview(iframe, null, files, 2, reload), iframe };
|
||||
}
|
||||
|
||||
const BOX_AT_0 = {
|
||||
key: "hf:box",
|
||||
attributes: [
|
||||
["data-hf-id", "box"],
|
||||
["style", "left: 0px"],
|
||||
],
|
||||
};
|
||||
|
||||
const settled = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
beforeEach(() => channel.request.mockReset());
|
||||
@@ -60,19 +68,36 @@ describe("undo on a sealed preview", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("says the files keep a GSAP script, and reloads at once when the script itself changed", () => {
|
||||
it("says the files keep a GSAP script when they do", () => {
|
||||
channel.request.mockResolvedValue({ applied: true });
|
||||
undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 1 }"));
|
||||
expect(channel.request.mock.calls[0]![2]).toMatchObject({ scripted: true });
|
||||
channel.request.mockReset();
|
||||
});
|
||||
|
||||
// fails without the fix: a sealed undo of a keyframe edit reloaded the whole preview.
|
||||
it.each([
|
||||
["and the attributes it changed", box(90), [{ file: null, elements: [BOX_AT_0] }]],
|
||||
["alone", box(0), []],
|
||||
])("re-runs a changed script in the frame %s, in one request", async (_name, before, restore) => {
|
||||
channel.request.mockResolvedValue({ result: "applied" });
|
||||
const { reload, strategy, iframe } = undo(
|
||||
box(90) + script("{ x: 1 }"),
|
||||
before + script("{ x: 1 }"),
|
||||
box(0) + script("{ x: 2 }"),
|
||||
);
|
||||
expect(strategy).toBe("full");
|
||||
expect(strategy).toBe("soft");
|
||||
expect(channel.request).toHaveBeenCalledExactlyOnceWith(
|
||||
iframe,
|
||||
"soft-reload",
|
||||
expect.objectContaining({ script: expect.stringContaining("{ x: 2 }"), time: 2, restore }),
|
||||
);
|
||||
await settled();
|
||||
expect(reload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reloads when the frame cannot re-run the changed script", async () => {
|
||||
channel.request.mockResolvedValue({ result: "cannot-soft-reload" });
|
||||
const { reload } = undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 2 }"));
|
||||
await settled();
|
||||
expect(reload).toHaveBeenCalledOnce();
|
||||
expect(channel.request).toHaveBeenCalledExactlyOnceWith(iframe, "mark-scenes-stale", {
|
||||
files: ["index.html"],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -372,8 +372,6 @@ type SealedFile = { scripted: boolean; elements: SealedRestore["scopes"][number]
|
||||
|
||||
/** One file's changed elements with their restored attributes, or null when it needs a reload. */
|
||||
function sealedFile(file: UndoRestoreFile, isActive: boolean): SealedFile | null {
|
||||
// A changed script is re-run in the frame, which a sealed preview cannot be asked to do yet.
|
||||
if (extractGsapScriptText(file.restored) !== extractGsapScriptText(file.previous)) return null;
|
||||
const prevDoc = parseRestoreSource(stamped(file.previous));
|
||||
const nextDoc = parseRestoreSource(stamped(file.restored));
|
||||
const scripted = restoreScripted(prevDoc, nextDoc, isActive);
|
||||
@@ -398,7 +396,7 @@ function sealedRestore(activeDocPath: string, files: RestoreFiles): SealedRestor
|
||||
if (found.elements.length)
|
||||
restore.scopes.push({ file: isActive ? null : path, elements: found.elements });
|
||||
}
|
||||
return restore.scopes.length ? restore : null;
|
||||
return restore;
|
||||
}
|
||||
|
||||
/** Sends the restore to a sealed preview; a refusal, or no answer, reloads it. */
|
||||
@@ -410,16 +408,38 @@ function applySealedRestore(
|
||||
reloadPreview: () => void,
|
||||
): "soft" | "full" {
|
||||
const restore = sealedRestore(activeDocPath, files);
|
||||
if (!restore) {
|
||||
reloadPreview();
|
||||
return "full";
|
||||
const active = files[activeDocPath];
|
||||
const script = active ? extractGsapScriptText(active.restored) : null;
|
||||
if (restore && active && script !== extractGsapScriptText(active.previous)) {
|
||||
const rerun =
|
||||
script &&
|
||||
applySoftReload(iframe, script, {
|
||||
onAsyncFailure: reloadPreview,
|
||||
currentTimeOverride: currentTime,
|
||||
authoredHtml: active.restored,
|
||||
previousHtml: active.previous,
|
||||
restore: restore.scopes,
|
||||
});
|
||||
if (rerun === "applied") return "soft";
|
||||
} else if (restore?.scopes.length) {
|
||||
sendSealedRestore(iframe, restore, currentTime, reloadPreview);
|
||||
return "soft";
|
||||
}
|
||||
reloadPreview();
|
||||
return "full";
|
||||
}
|
||||
|
||||
function sendSealedRestore(
|
||||
iframe: HTMLIFrameElement,
|
||||
restore: SealedRestore,
|
||||
currentTime: number,
|
||||
reloadPreview: () => void,
|
||||
): void {
|
||||
void previewRequest(iframe, "restore-attributes", { ...restore, time: currentTime }).then(
|
||||
(reply) => {
|
||||
if (!reply?.applied) reloadPreview();
|
||||
},
|
||||
);
|
||||
return "soft";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user