mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-09-10 22:20:14 +00:00
feat: Persist Studio manual edits via manifest (#593)
## Summary Studio manual geometry edits now persist as a project-local manifest instead of being baked into composition source on each gesture. The manifest lives at: ```text .hyperframes/studio-manual-edits.json ``` It is the source of truth for manual drag, resize, rotation, inspector geometry edits, group moves, and selected-layer reset. ## Architecture - **Manifest-backed edits**: each edit stores a kind (`path-offset`, `box-size`, `rotation`), a source-scoped target, and the edit values. - **Source-scoped resolution**: targets include `sourceFile`, `id`, `selector`, and `selectorIndex`, so duplicate selectors in nested compositions resolve against the owning source file. - **Additive CSS layer**: move uses CSS `translate`, resize writes stable dimensions/flex sizing, and rotation uses CSS `rotate` over the authored base. - **Shared replay runtime**: Studio preview, thumbnails, frame capture, producer renders, and CLI Studio renders/thumbnails all use the same core manual-edit render script. - **Animation-safe replay**: Studio reapplies the manual layer after load, refresh, timeline seeks, player operations, playback frames, thumbnail seeks, and render seeks instead of rewriting GSAP timelines. - **History and handoff**: the manifest is a normal project file, so undo/redo and agent edits can preserve, modify, or remove manual visual edits explicitly. ## User Impact Users can move, resize, rotate, group-move, and reset supported layers from the canvas or inspector, then refresh, capture thumbnails/screenshots, play animated compositions, and render videos without manual edits drifting away from the edited state. ## Main Files - `packages/studio/src/components/editor/manualEdits.ts` - `packages/studio/src/components/editor/DomEditOverlay.tsx` - `packages/studio/src/components/editor/PropertyPanel.tsx` - `packages/studio/src/App.tsx` - `packages/core/src/studio-api/helpers/manualEditsRenderScript.ts` - `packages/studio/vite.config.ts` - `packages/cli/src/server/studioServer.ts` - `packages/core/src/compiler/htmlBundler.ts` - `packages/producer/src/services/htmlCompiler.ts` - `packages/core/src/studio-api/routes/thumbnail.ts` - `packages/producer/src/services/fileServer.ts` - `packages/producer/src/services/renderOrchestrator.ts` ## Test Plan ```bash volta run --node 22.20.0 bun run build volta run --node 22.20.0 bun run --filter @hyperframes/core test -- src/studio-api/helpers/manualEditsRenderScript.test.ts volta run --node 22.20.0 bun run --filter @hyperframes/core typecheck volta run --node 22.20.0 bun run --filter @hyperframes/studio typecheck volta run --node 22.20.0 bun run --filter @hyperframes/cli typecheck volta run --node 22.20.0 bunx oxlint <changed files> volta run --node 22.20.0 bunx oxfmt --check <changed files> git diff --check ```
This commit is contained in:
@@ -0,0 +1,382 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Window } from "happy-dom";
|
||||
import { createStudioManualEditsRenderBodyScript } from "./manualEditsRenderScript";
|
||||
|
||||
function runScript(
|
||||
window: Window,
|
||||
script: string,
|
||||
getComputedStyle: typeof window.getComputedStyle = window.getComputedStyle.bind(window),
|
||||
timers: {
|
||||
setInterval?: typeof globalThis.setInterval;
|
||||
clearInterval?: typeof globalThis.clearInterval;
|
||||
} = {},
|
||||
): void {
|
||||
const execute = new Function(
|
||||
"window",
|
||||
"document",
|
||||
"HTMLElement",
|
||||
"getComputedStyle",
|
||||
"setInterval",
|
||||
"clearInterval",
|
||||
script,
|
||||
);
|
||||
execute(
|
||||
window,
|
||||
window.document,
|
||||
window.HTMLElement,
|
||||
getComputedStyle,
|
||||
timers.setInterval ??
|
||||
(((callback: TimerHandler) => {
|
||||
void callback;
|
||||
return 0 as never;
|
||||
}) as typeof globalThis.setInterval),
|
||||
timers.clearInterval ?? globalThis.clearInterval,
|
||||
);
|
||||
}
|
||||
|
||||
describe("createStudioManualEditsRenderBodyScript", () => {
|
||||
it("returns null for an empty manifest", () => {
|
||||
expect(createStudioManualEditsRenderBodyScript("")).toBeNull();
|
||||
});
|
||||
|
||||
it("applies manual edits and reapplies them after render seeks", () => {
|
||||
const window = new Window();
|
||||
window.document.body.innerHTML = '<div id="card" style="width: 20px; height: 20px"></div>';
|
||||
const card = window.document.getElementById("card");
|
||||
if (!(card instanceof window.HTMLElement)) {
|
||||
throw new Error("card fixture missing");
|
||||
}
|
||||
|
||||
let seekCalls = 0;
|
||||
(
|
||||
window as unknown as {
|
||||
__hf: { seek: (time: number) => void };
|
||||
}
|
||||
).__hf = {
|
||||
seek: () => {
|
||||
seekCalls += 1;
|
||||
card.style.removeProperty("translate");
|
||||
},
|
||||
};
|
||||
|
||||
const script = createStudioManualEditsRenderBodyScript(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
edits: [
|
||||
{
|
||||
kind: "path-offset",
|
||||
target: { sourceFile: "index.html", id: "card" },
|
||||
x: 12,
|
||||
y: 24,
|
||||
},
|
||||
{
|
||||
kind: "box-size",
|
||||
target: { sourceFile: "index.html", id: "card" },
|
||||
width: 120,
|
||||
height: 64,
|
||||
},
|
||||
{
|
||||
kind: "rotation",
|
||||
target: { sourceFile: "index.html", id: "card" },
|
||||
angle: 15,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
if (!script) throw new Error("script fixture missing");
|
||||
|
||||
const computedStyle = (element: Element) =>
|
||||
({
|
||||
display: element === card ? "block" : "block",
|
||||
flexDirection: "row",
|
||||
}) as CSSStyleDeclaration;
|
||||
|
||||
const intervalCallbacks: Array<() => void> = [];
|
||||
runScript(window, script, computedStyle, {
|
||||
setInterval: ((callback: TimerHandler) => {
|
||||
if (typeof callback === "function") intervalCallbacks.push(callback as () => void);
|
||||
return 0 as never;
|
||||
}) as typeof globalThis.setInterval,
|
||||
});
|
||||
|
||||
expect(card.style.getPropertyValue("translate")).toContain("--hf-studio-offset-x");
|
||||
expect(card.style.getPropertyValue("width")).toBe("120px");
|
||||
expect(card.style.getPropertyValue("height")).toBe("64px");
|
||||
expect(card.style.getPropertyValue("rotate")).toContain("--hf-studio-rotation");
|
||||
expect(card.style.getPropertyValue("transform-origin")).toBe("center center");
|
||||
|
||||
(
|
||||
window as unknown as {
|
||||
__hf: { seek: (time: number) => void };
|
||||
}
|
||||
).__hf.seek(1);
|
||||
|
||||
expect(seekCalls).toBe(1);
|
||||
expect(card.style.getPropertyValue("translate")).toContain("--hf-studio-offset-x");
|
||||
|
||||
(
|
||||
window as unknown as {
|
||||
__hf: { seek: (time: number) => void };
|
||||
}
|
||||
).__hf.seek = () => {
|
||||
card.style.removeProperty("rotate");
|
||||
};
|
||||
intervalCallbacks.forEach((callback) => callback());
|
||||
(
|
||||
window as unknown as {
|
||||
__hf: { seek: (time: number) => void };
|
||||
}
|
||||
).__hf.seek(2);
|
||||
expect(card.style.getPropertyValue("rotate")).toContain("--hf-studio-rotation");
|
||||
|
||||
(
|
||||
window as unknown as {
|
||||
__player: { renderSeek: (time: number) => void };
|
||||
}
|
||||
).__player = {
|
||||
renderSeek: () => {
|
||||
card.style.removeProperty("rotate");
|
||||
},
|
||||
};
|
||||
intervalCallbacks.forEach((callback) => callback());
|
||||
(
|
||||
window as unknown as {
|
||||
__player: { renderSeek: (time: number) => void };
|
||||
}
|
||||
).__player.renderSeek(3);
|
||||
expect(card.style.getPropertyValue("rotate")).toContain("--hf-studio-rotation");
|
||||
});
|
||||
|
||||
it("applies render edits to the matching source file target", () => {
|
||||
const window = new Window();
|
||||
window.document.body.innerHTML = `
|
||||
<div data-composition-id="root">
|
||||
<div id="card"></div>
|
||||
<div data-composition-id="nested" data-composition-file="scenes/nested.html">
|
||||
<div id="card"></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
const cards = Array.from(window.document.getElementsByTagName("*")).filter(
|
||||
(element): element is HTMLElement =>
|
||||
element instanceof window.HTMLElement && element.id === "card",
|
||||
);
|
||||
const rootCard = cards[0];
|
||||
const nestedCard = cards[1];
|
||||
if (!rootCard || !nestedCard) {
|
||||
throw new Error("source-scoped render fixture missing");
|
||||
}
|
||||
|
||||
const script = createStudioManualEditsRenderBodyScript(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
edits: [
|
||||
{
|
||||
kind: "rotation",
|
||||
target: { sourceFile: "scenes/nested.html", id: "card" },
|
||||
angle: 21,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
if (!script) throw new Error("script fixture missing");
|
||||
|
||||
runScript(window, script);
|
||||
|
||||
expect(rootCard.style.getPropertyValue("rotate")).toBe("");
|
||||
expect(nestedCard.style.getPropertyValue("rotate")).toContain("--hf-studio-rotation");
|
||||
});
|
||||
|
||||
it("applies render edits inside composition-file hosts without composition ids", () => {
|
||||
const window = new Window();
|
||||
window.document.body.innerHTML = `
|
||||
<div data-composition-id="root">
|
||||
<div id="card"></div>
|
||||
<div data-composition-file="scenes/anonymous.html">
|
||||
<div id="card"></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
const cards = Array.from(window.document.getElementsByTagName("*")).filter(
|
||||
(element): element is HTMLElement =>
|
||||
element instanceof window.HTMLElement && element.id === "card",
|
||||
);
|
||||
const rootCard = cards[0];
|
||||
const nestedCard = cards[1];
|
||||
if (!rootCard || !nestedCard) {
|
||||
throw new Error("anonymous composition render fixture missing");
|
||||
}
|
||||
|
||||
const script = createStudioManualEditsRenderBodyScript(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
edits: [
|
||||
{
|
||||
kind: "path-offset",
|
||||
target: { sourceFile: "scenes/anonymous.html", id: "card" },
|
||||
x: 12,
|
||||
y: 24,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
if (!script) throw new Error("script fixture missing");
|
||||
|
||||
runScript(window, script);
|
||||
|
||||
expect(rootCard.style.getPropertyValue("translate")).toBe("");
|
||||
expect(nestedCard.style.getPropertyValue("translate")).toContain("--hf-studio-offset-x");
|
||||
});
|
||||
|
||||
it("uses the active composition path as the unscoped document fallback", () => {
|
||||
const window = new Window();
|
||||
window.document.body.innerHTML = `<div id="card"></div>`;
|
||||
const card = window.document.getElementById("card");
|
||||
if (!(card instanceof window.HTMLElement)) {
|
||||
throw new Error("card fixture missing");
|
||||
}
|
||||
|
||||
const script = createStudioManualEditsRenderBodyScript(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
edits: [
|
||||
{
|
||||
kind: "path-offset",
|
||||
target: { sourceFile: "compositions/scene-2.html", id: "card" },
|
||||
x: 12,
|
||||
y: 24,
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ activeCompositionPath: "compositions/scene-2.html" },
|
||||
);
|
||||
if (!script) throw new Error("script fixture missing");
|
||||
|
||||
runScript(window, script);
|
||||
|
||||
expect(card.style.getPropertyValue("translate")).toContain("--hf-studio-offset-x");
|
||||
});
|
||||
|
||||
it("preserves computed transform longhands as render edit bases", () => {
|
||||
const window = new Window();
|
||||
window.document.body.innerHTML = `<div id="card"></div>`;
|
||||
const card = window.document.getElementById("card");
|
||||
if (!(card instanceof window.HTMLElement)) {
|
||||
throw new Error("card fixture missing");
|
||||
}
|
||||
|
||||
const script = createStudioManualEditsRenderBodyScript(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
edits: [
|
||||
{
|
||||
kind: "path-offset",
|
||||
target: { sourceFile: "index.html", id: "card" },
|
||||
x: 12,
|
||||
y: 24,
|
||||
},
|
||||
{
|
||||
kind: "rotation",
|
||||
target: { sourceFile: "index.html", id: "card" },
|
||||
angle: 15,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
if (!script) throw new Error("script fixture missing");
|
||||
|
||||
const computedStyle = (element: Element) =>
|
||||
({
|
||||
getPropertyValue: (property: string) => {
|
||||
if (element !== card) return "";
|
||||
if (property === "translate") return "10px 20px";
|
||||
if (property === "rotate") return "8deg";
|
||||
return "";
|
||||
},
|
||||
}) as CSSStyleDeclaration;
|
||||
|
||||
runScript(window, script, computedStyle);
|
||||
|
||||
expect(card.style.getPropertyValue("translate")).toContain("calc(10px +");
|
||||
expect(card.style.getPropertyValue("translate")).toContain("calc(20px +");
|
||||
expect(card.style.getPropertyValue("rotate")).toContain("8deg");
|
||||
expect(card.style.getPropertyValue("rotate")).toContain("--hf-studio-rotation");
|
||||
expect(card.style.getPropertyValue("transform-origin")).toBe("center center");
|
||||
});
|
||||
|
||||
it("does not compound stale studio variables during render reapply", () => {
|
||||
const window = new Window();
|
||||
window.document.body.innerHTML = `
|
||||
<div id="card" style="
|
||||
translate: var(--hf-studio-offset-x, 0px) var(--hf-studio-offset-y, 0px);
|
||||
rotate: var(--hf-studio-rotation, 0deg);
|
||||
"></div>
|
||||
`;
|
||||
const card = window.document.getElementById("card");
|
||||
if (!(card instanceof window.HTMLElement)) {
|
||||
throw new Error("card fixture missing");
|
||||
}
|
||||
|
||||
const script = createStudioManualEditsRenderBodyScript(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
edits: [
|
||||
{
|
||||
kind: "path-offset",
|
||||
target: { sourceFile: "index.html", id: "card" },
|
||||
x: 12,
|
||||
y: 24,
|
||||
},
|
||||
{
|
||||
kind: "rotation",
|
||||
target: { sourceFile: "index.html", id: "card" },
|
||||
angle: 15,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
if (!script) throw new Error("script fixture missing");
|
||||
|
||||
runScript(window, script);
|
||||
|
||||
expect(card.style.getPropertyValue("translate")).toBe(
|
||||
"var(--hf-studio-offset-x, 0px) var(--hf-studio-offset-y, 0px)",
|
||||
);
|
||||
expect(card.style.getPropertyValue("rotate")).toBe("var(--hf-studio-rotation, 0deg)");
|
||||
});
|
||||
|
||||
it("exposes a render reapply hook for thumbnails after layout settles", () => {
|
||||
const window = new Window();
|
||||
window.document.body.innerHTML = `<div id="card"></div>`;
|
||||
const card = window.document.getElementById("card");
|
||||
if (!(card instanceof window.HTMLElement)) {
|
||||
throw new Error("card fixture missing");
|
||||
}
|
||||
|
||||
const script = createStudioManualEditsRenderBodyScript(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
edits: [
|
||||
{
|
||||
kind: "path-offset",
|
||||
target: { sourceFile: "index.html", id: "card" },
|
||||
x: 12,
|
||||
y: 24,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
if (!script) throw new Error("script fixture missing");
|
||||
|
||||
runScript(window, script);
|
||||
card.style.removeProperty("translate");
|
||||
|
||||
(
|
||||
window as unknown as {
|
||||
__hfStudioManualEditsApply?: () => number;
|
||||
}
|
||||
).__hfStudioManualEditsApply?.();
|
||||
|
||||
expect(card.style.getPropertyValue("translate")).toContain("--hf-studio-offset-x");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,369 @@
|
||||
export interface StudioManualEditsRenderScriptOptions {
|
||||
activeCompositionPath?: string | null;
|
||||
}
|
||||
|
||||
export function createStudioManualEditsRenderBodyScript(
|
||||
manifestContent: string,
|
||||
options: StudioManualEditsRenderScriptOptions = {},
|
||||
): string | null {
|
||||
if (!manifestContent.trim()) return null;
|
||||
return `(${studioManualEditsRenderRuntime.toString()})(${JSON.stringify(manifestContent)}, ${JSON.stringify(options.activeCompositionPath ?? null)});`;
|
||||
}
|
||||
|
||||
function studioManualEditsRenderRuntime(
|
||||
manifestContent: string,
|
||||
activeCompositionPath: string | null,
|
||||
): void {
|
||||
const OFFSET_X_PROP = "--hf-studio-offset-x";
|
||||
const OFFSET_Y_PROP = "--hf-studio-offset-y";
|
||||
const WIDTH_PROP = "--hf-studio-width";
|
||||
const HEIGHT_PROP = "--hf-studio-height";
|
||||
const ROTATION_PROP = "--hf-studio-rotation";
|
||||
const PATH_OFFSET_ATTR = "data-hf-studio-path-offset";
|
||||
const BOX_SIZE_ATTR = "data-hf-studio-box-size";
|
||||
const ROTATION_ATTR = "data-hf-studio-rotation";
|
||||
const ORIGINAL_TRANSLATE_ATTR = "data-hf-studio-original-translate";
|
||||
const ORIGINAL_ROTATE_ATTR = "data-hf-studio-original-rotate";
|
||||
const WRAPPED_SEEK_PROP = "__hfStudioManualEditsWrapped";
|
||||
const ROTATION_TRANSFORM_ORIGIN = "center center";
|
||||
|
||||
const finiteNumber = (value: unknown): number | null =>
|
||||
typeof value === "number" && Number.isFinite(value) ? value : null;
|
||||
|
||||
const objectRecord = (value: unknown): Record<string, unknown> | null =>
|
||||
value && typeof value === "object" ? (value as Record<string, unknown>) : null;
|
||||
|
||||
const runtimeWindow = window as Window & {
|
||||
__hf?: { seek?: (time: number) => unknown };
|
||||
__hfStudioManualEditsApply?: () => number;
|
||||
__player?: { renderSeek?: (time: number) => unknown };
|
||||
};
|
||||
|
||||
const parsedManifest = (() => {
|
||||
try {
|
||||
return objectRecord(JSON.parse(manifestContent));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
const manifestEdits = Array.isArray(parsedManifest?.edits) ? parsedManifest.edits : [];
|
||||
if (manifestEdits.length === 0) return;
|
||||
|
||||
const sourceFileForElement = (element: HTMLElement): string => {
|
||||
let current: HTMLElement | null = element;
|
||||
while (current) {
|
||||
const sourceFile =
|
||||
current.getAttribute("data-composition-file") ??
|
||||
current.getAttribute("data-composition-src");
|
||||
if (sourceFile) return sourceFile;
|
||||
current = current.parentElement;
|
||||
}
|
||||
return activeCompositionPath ?? "index.html";
|
||||
};
|
||||
|
||||
const elementMatchesSourceFile = (element: HTMLElement, sourceFile: string): boolean =>
|
||||
sourceFileForElement(element) === sourceFile;
|
||||
|
||||
const styleUsesStudioOffset = (value: string): boolean =>
|
||||
value.includes(OFFSET_X_PROP) || value.includes(OFFSET_Y_PROP);
|
||||
|
||||
const styleUsesStudioRotation = (value: string): boolean => value.includes(ROTATION_PROP);
|
||||
|
||||
const splitTopLevelWhitespace = (value: string): string[] => {
|
||||
const parts: string[] = [];
|
||||
let depth = 0;
|
||||
let current = "";
|
||||
for (const char of value.trim()) {
|
||||
if (char === "(") depth += 1;
|
||||
if (char === ")") depth = Math.max(0, depth - 1);
|
||||
if (/\s/.test(char) && depth === 0) {
|
||||
if (current) parts.push(current);
|
||||
current = "";
|
||||
} else {
|
||||
current += char;
|
||||
}
|
||||
}
|
||||
if (current) parts.push(current);
|
||||
return parts;
|
||||
};
|
||||
|
||||
const composeTranslate = (element: HTMLElement, x: string, y: string): string => {
|
||||
const original = element.getAttribute(ORIGINAL_TRANSLATE_ATTR)?.trim();
|
||||
if (!original || original === "none") return `${x} ${y}`;
|
||||
|
||||
const parts = splitTopLevelWhitespace(original);
|
||||
if (parts.length === 1) return `calc(${parts[0]} + ${x}) ${y}`;
|
||||
if (parts.length === 2) return `calc(${parts[0]} + ${x}) calc(${parts[1]} + ${y})`;
|
||||
if (parts.length === 3) {
|
||||
return `calc(${parts[0]} + ${x}) calc(${parts[1]} + ${y}) ${parts[2]}`;
|
||||
}
|
||||
return `${x} ${y}`;
|
||||
};
|
||||
|
||||
const readStyleOrComputed = (element: HTMLElement, property: string): string => {
|
||||
try {
|
||||
return (
|
||||
element.style.getPropertyValue(property) ||
|
||||
getComputedStyle(element).getPropertyValue(property)
|
||||
);
|
||||
} catch {
|
||||
return element.style.getPropertyValue(property);
|
||||
}
|
||||
};
|
||||
|
||||
const readTransformLonghandBase = (
|
||||
element: HTMLElement,
|
||||
property: "translate" | "rotate",
|
||||
): string => {
|
||||
const value = readStyleOrComputed(element, property).trim();
|
||||
return value === "none" ? "" : value;
|
||||
};
|
||||
|
||||
const preparePathOffsetBase = (element: HTMLElement): void => {
|
||||
const currentTranslate = readTransformLonghandBase(element, "translate");
|
||||
const hasMarker = element.hasAttribute(PATH_OFFSET_ATTR);
|
||||
const wasResetByAnimation = !styleUsesStudioOffset(currentTranslate);
|
||||
if (!hasMarker) {
|
||||
element.setAttribute(ORIGINAL_TRANSLATE_ATTR, wasResetByAnimation ? currentTranslate : "");
|
||||
} else if (wasResetByAnimation) {
|
||||
element.setAttribute(ORIGINAL_TRANSLATE_ATTR, currentTranslate);
|
||||
}
|
||||
};
|
||||
|
||||
const prepareRotationBase = (element: HTMLElement): void => {
|
||||
const currentRotate = readTransformLonghandBase(element, "rotate");
|
||||
const hasMarker = element.hasAttribute(ROTATION_ATTR);
|
||||
const wasResetByAnimation = !styleUsesStudioRotation(currentRotate);
|
||||
if (!hasMarker) {
|
||||
element.setAttribute(ORIGINAL_ROTATE_ATTR, wasResetByAnimation ? currentRotate : "");
|
||||
} else if (wasResetByAnimation) {
|
||||
element.setAttribute(ORIGINAL_ROTATE_ATTR, currentRotate);
|
||||
}
|
||||
};
|
||||
|
||||
const querySelectorCandidates = (selector: string): HTMLElement[] => {
|
||||
const isCandidate = (element: Element): element is HTMLElement =>
|
||||
element instanceof HTMLElement;
|
||||
|
||||
const className = selector.match(/^\.([A-Za-z0-9_-]+)$/)?.[1];
|
||||
if (className) {
|
||||
return Array.from(document.getElementsByTagName("*")).filter(
|
||||
(element): element is HTMLElement =>
|
||||
isCandidate(element) && element.classList.contains(className),
|
||||
);
|
||||
}
|
||||
|
||||
if (/^[A-Za-z][A-Za-z0-9-]*$/.test(selector)) {
|
||||
return Array.from(document.getElementsByTagName(selector)).filter(isCandidate);
|
||||
}
|
||||
|
||||
return Array.from(document.querySelectorAll(selector)).filter(isCandidate);
|
||||
};
|
||||
|
||||
const resolveTarget = (edit: Record<string, unknown>): HTMLElement | null => {
|
||||
const targetRecord = objectRecord(edit.target);
|
||||
if (!targetRecord) return null;
|
||||
|
||||
const sourceFile = typeof targetRecord.sourceFile === "string" ? targetRecord.sourceFile : "";
|
||||
if (!sourceFile) return null;
|
||||
|
||||
const id = typeof targetRecord.id === "string" ? targetRecord.id : "";
|
||||
if (id) {
|
||||
const byId = document.getElementById(id);
|
||||
if (byId instanceof HTMLElement && elementMatchesSourceFile(byId, sourceFile)) return byId;
|
||||
|
||||
const matchesById = [
|
||||
document.documentElement,
|
||||
...Array.from(document.getElementsByTagName("*")),
|
||||
].filter(
|
||||
(element): element is HTMLElement =>
|
||||
element instanceof HTMLElement &&
|
||||
element.id === id &&
|
||||
elementMatchesSourceFile(element, sourceFile),
|
||||
);
|
||||
if (matchesById[0]) return matchesById[0];
|
||||
}
|
||||
|
||||
const selector = typeof targetRecord.selector === "string" ? targetRecord.selector : "";
|
||||
if (!selector) return null;
|
||||
|
||||
try {
|
||||
const matches = querySelectorCandidates(selector).filter((element) =>
|
||||
elementMatchesSourceFile(element, sourceFile),
|
||||
);
|
||||
const selectorIndex = finiteNumber(targetRecord.selectorIndex) ?? 0;
|
||||
return matches[Math.max(0, Math.floor(selectorIndex))] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const roundRotationAngle = (angle: number): number => Math.round(angle * 10) / 10;
|
||||
|
||||
const isSimpleRotateAngle = (value: string): boolean =>
|
||||
/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:deg|rad|turn|grad)$/.test(value.trim());
|
||||
|
||||
const composeRotation = (element: HTMLElement, rotationValue: string): string => {
|
||||
const original = element.getAttribute(ORIGINAL_ROTATE_ATTR)?.trim();
|
||||
if (!original || original === "none" || !isSimpleRotateAngle(original)) {
|
||||
return rotationValue;
|
||||
}
|
||||
return `calc(${original} + ${rotationValue})`;
|
||||
};
|
||||
|
||||
const applyPathOffset = (element: HTMLElement, edit: Record<string, unknown>): void => {
|
||||
const x = finiteNumber(edit.x);
|
||||
const y = finiteNumber(edit.y);
|
||||
if (x == null || y == null) return;
|
||||
preparePathOffsetBase(element);
|
||||
element.setAttribute(PATH_OFFSET_ATTR, "true");
|
||||
element.style.setProperty(OFFSET_X_PROP, `${Math.round(x)}px`);
|
||||
element.style.setProperty(OFFSET_Y_PROP, `${Math.round(y)}px`);
|
||||
element.style.setProperty(
|
||||
"translate",
|
||||
composeTranslate(element, `var(${OFFSET_X_PROP}, 0px)`, `var(${OFFSET_Y_PROP}, 0px)`),
|
||||
);
|
||||
};
|
||||
|
||||
const readParentFlexBasisPixels = (
|
||||
element: HTMLElement,
|
||||
size: { width: number; height: number },
|
||||
): number | null => {
|
||||
const parent = element.parentElement;
|
||||
if (!parent) return null;
|
||||
const styles = getComputedStyle(parent);
|
||||
if (styles.display !== "flex" && styles.display !== "inline-flex") return null;
|
||||
return Math.round(
|
||||
Math.max(1, styles.flexDirection.startsWith("column") ? size.height : size.width),
|
||||
);
|
||||
};
|
||||
|
||||
const applyBoxSize = (element: HTMLElement, edit: Record<string, unknown>): void => {
|
||||
const width = finiteNumber(edit.width);
|
||||
const height = finiteNumber(edit.height);
|
||||
if (width == null || height == null || width <= 0 || height <= 0) return;
|
||||
|
||||
const rounded = {
|
||||
width: Math.round(Math.max(1, width)),
|
||||
height: Math.round(Math.max(1, height)),
|
||||
};
|
||||
element.setAttribute(BOX_SIZE_ATTR, "true");
|
||||
element.style.setProperty(WIDTH_PROP, `${rounded.width}px`);
|
||||
element.style.setProperty(HEIGHT_PROP, `${rounded.height}px`);
|
||||
element.style.setProperty("box-sizing", "border-box");
|
||||
element.style.setProperty("width", `${rounded.width}px`);
|
||||
element.style.setProperty("height", `${rounded.height}px`);
|
||||
element.style.setProperty("min-width", "0px");
|
||||
element.style.setProperty("min-height", "0px");
|
||||
element.style.setProperty("max-width", "none");
|
||||
element.style.setProperty("max-height", "none");
|
||||
|
||||
const flexBasis = readParentFlexBasisPixels(element, rounded);
|
||||
if (flexBasis != null) {
|
||||
element.style.setProperty("flex-basis", `${flexBasis}px`);
|
||||
element.style.setProperty("flex-grow", "0");
|
||||
element.style.setProperty("flex-shrink", "0");
|
||||
}
|
||||
if (getComputedStyle(element).display === "inline") {
|
||||
element.style.setProperty("display", "inline-block");
|
||||
}
|
||||
};
|
||||
|
||||
const applyRotation = (element: HTMLElement, edit: Record<string, unknown>): void => {
|
||||
const angle = finiteNumber(edit.angle);
|
||||
if (angle == null) return;
|
||||
prepareRotationBase(element);
|
||||
element.setAttribute(ROTATION_ATTR, "true");
|
||||
element.style.setProperty(ROTATION_PROP, `${roundRotationAngle(angle)}deg`);
|
||||
element.style.setProperty("transform-origin", ROTATION_TRANSFORM_ORIGIN);
|
||||
element.style.setProperty("rotate", composeRotation(element, `var(${ROTATION_PROP}, 0deg)`));
|
||||
};
|
||||
|
||||
const applyManifest = (): number => {
|
||||
let applied = 0;
|
||||
for (const edit of manifestEdits) {
|
||||
const editRecord = objectRecord(edit);
|
||||
if (!editRecord) continue;
|
||||
const element = resolveTarget(editRecord);
|
||||
if (!element) continue;
|
||||
if (editRecord.kind === "path-offset") applyPathOffset(element, editRecord);
|
||||
if (editRecord.kind === "box-size") applyBoxSize(element, editRecord);
|
||||
if (editRecord.kind === "rotation") applyRotation(element, editRecord);
|
||||
applied += 1;
|
||||
}
|
||||
return applied;
|
||||
};
|
||||
runtimeWindow.__hfStudioManualEditsApply = applyManifest;
|
||||
|
||||
const markWrapped = (fn: (time: number) => unknown): void => {
|
||||
try {
|
||||
Object.defineProperty(fn, WRAPPED_SEEK_PROP, {
|
||||
configurable: false,
|
||||
enumerable: false,
|
||||
value: true,
|
||||
});
|
||||
} catch {
|
||||
try {
|
||||
(fn as unknown as Record<string, unknown>)[WRAPPED_SEEK_PROP] = true;
|
||||
} catch {
|
||||
// Ignore non-extensible functions.
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const isWrapped = (fn: (time: number) => unknown): boolean =>
|
||||
Boolean((fn as unknown as Record<string, unknown>)[WRAPPED_SEEK_PROP]);
|
||||
|
||||
const wrapFunction = (
|
||||
get: () => ((time: number) => unknown) | undefined,
|
||||
set: (fn: (time: number) => unknown) => void,
|
||||
): boolean => {
|
||||
const fn = get();
|
||||
if (!fn) return false;
|
||||
const seek = fn as (time: number) => unknown;
|
||||
if (isWrapped(seek)) {
|
||||
applyManifest();
|
||||
return true;
|
||||
}
|
||||
|
||||
const wrappedSeek = function (this: unknown, time: number): unknown {
|
||||
const result = seek.call(this, time);
|
||||
applyManifest();
|
||||
return result;
|
||||
};
|
||||
markWrapped(wrappedSeek);
|
||||
set(wrappedSeek);
|
||||
applyManifest();
|
||||
return true;
|
||||
};
|
||||
|
||||
const wrapSeekFunctions = (): boolean => {
|
||||
const wrappedHfSeek = wrapFunction(
|
||||
() => runtimeWindow.__hf?.seek,
|
||||
(fn) => {
|
||||
if (runtimeWindow.__hf) runtimeWindow.__hf.seek = fn;
|
||||
},
|
||||
);
|
||||
const wrappedPlayerRenderSeek = wrapFunction(
|
||||
() => runtimeWindow.__player?.renderSeek,
|
||||
(fn) => {
|
||||
if (runtimeWindow.__player) runtimeWindow.__player.renderSeek = fn;
|
||||
},
|
||||
);
|
||||
return wrappedHfSeek || wrappedPlayerRenderSeek;
|
||||
};
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", () => applyManifest(), { once: true });
|
||||
} else {
|
||||
applyManifest();
|
||||
}
|
||||
|
||||
wrapSeekFunctions();
|
||||
let remainingSeekWrapAttempts = 120;
|
||||
const seekWrapInterval = setInterval(() => {
|
||||
wrapSeekFunctions();
|
||||
remainingSeekWrapAttempts -= 1;
|
||||
if (remainingSeekWrapAttempts <= 0) clearInterval(seekWrapInterval);
|
||||
}, 50);
|
||||
}
|
||||
@@ -5,8 +5,15 @@ export interface ScreenshotClip {
|
||||
height: number;
|
||||
}
|
||||
|
||||
export function getElementScreenshotClip(selector: string): ScreenshotClip | undefined {
|
||||
const el = document.querySelector(selector);
|
||||
export function getElementScreenshotClip(
|
||||
selector: string,
|
||||
selectorIndex?: number,
|
||||
): ScreenshotClip | undefined {
|
||||
const matches = Array.from(document.querySelectorAll(selector)).filter(
|
||||
(el): el is HTMLElement => el instanceof HTMLElement,
|
||||
);
|
||||
const safeIndex = Math.max(0, Math.min(matches.length - 1, Math.floor(selectorIndex ?? 0)));
|
||||
const el = matches[safeIndex] ?? null;
|
||||
if (!(el instanceof HTMLElement)) return undefined;
|
||||
const rect = el.getBoundingClientRect();
|
||||
if (rect.width < 4 || rect.height < 4) return undefined;
|
||||
|
||||
@@ -23,6 +23,7 @@ describe("buildSubCompositionHtml", () => {
|
||||
"compositions/hero.html": `<template id="hero-template">
|
||||
<div data-composition-id="hero" data-width="1920" data-height="1080">
|
||||
<img src="../logo.png" alt="Logo" />
|
||||
<div style="background-image: url('../poster.png')"></div>
|
||||
<style>
|
||||
@font-face {
|
||||
font-family: "Brand Sans";
|
||||
@@ -42,8 +43,10 @@ describe("buildSubCompositionHtml", () => {
|
||||
|
||||
expect(html).toContain('<base href="/api/projects/demo/preview/">');
|
||||
expect(html).toContain('src="logo.png"');
|
||||
expect(html).toContain("background-image: url('poster.png')");
|
||||
expect(html).toContain('url("fonts/brand.woff2")');
|
||||
expect(html).not.toContain('src="../logo.png"');
|
||||
expect(html).not.toContain("url('../poster.png')");
|
||||
expect(html).not.toContain('url("../fonts/brand.woff2")');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { parseHTML } from "linkedom";
|
||||
import { rewriteAssetPaths, rewriteCssAssetUrls } from "../../compiler/rewriteSubCompPaths.js";
|
||||
import {
|
||||
rewriteAssetPaths,
|
||||
rewriteCssAssetUrls,
|
||||
rewriteInlineStyleAssetUrls,
|
||||
} from "../../compiler/rewriteSubCompPaths.js";
|
||||
|
||||
/**
|
||||
* Build a standalone HTML page for a sub-composition.
|
||||
@@ -36,6 +40,14 @@ export function buildSubCompositionHtml(
|
||||
el.setAttribute(attr, value);
|
||||
},
|
||||
);
|
||||
rewriteInlineStyleAssetUrls(
|
||||
contentDoc.querySelectorAll("[style]"),
|
||||
compPath,
|
||||
(el: Element) => el.getAttribute("style"),
|
||||
(el: Element, value: string) => {
|
||||
el.setAttribute("style", value);
|
||||
},
|
||||
);
|
||||
for (const styleEl of contentDoc.querySelectorAll("style")) {
|
||||
styleEl.textContent = rewriteCssAssetUrls(styleEl.textContent || "", compPath);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user