Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): soft-reload GSAP property edits, preserve shader cache (#1129)
Miguel Ángelae717331ce19
diff --git a/packages/core/src/studio-api/routes/files.ts b/packages/core/src/studio-api/routes/files.tsindex 596d79ba84..5b0bdcc689 100644--- a/packages/core/src/studio-api/routes/files.ts+++ b/packages/core/src/studio-api/routes/files.ts@@ -713,6 +713,12 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {// Re-parse the mutated script so the UI gets fresh stateconst freshParsed = parseGsapScript(newScript);- return c.json({ ok: true, parsed: freshParsed, before: html, after: newHtml });+ return c.json({+ ok: true,+ parsed: freshParsed,+ before: html,+ after: newHtml,+ scriptText: newScript,+ });});}diff --git a/packages/shader-transitions/src/hyper-shader.ts b/packages/shader-transitions/src/hyper-shader.tsindex 1b17c00c32..3223edb745 100644--- a/packages/shader-transitions/src/hyper-shader.ts+++ b/packages/shader-transitions/src/hyper-shader.ts@@ -245,6 +245,19 @@ function getDocumentStyleSignature(doc: Document): string {return stableHash(`${styleText}\n${linkedStyles}`);}+// fallow-ignore-next-line complexity+function isGsapAnimationOnlyScript(text: string): boolean {+ const hasGsap =+ text.includes("gsap.timeline") ||+ text.includes("__timelines") ||+ text.includes(".to(") ||+ text.includes(".set(");+ if (!hasGsap) return false;+ return (+ !text.includes("HyperShader") && !text.includes("hyper-shader") && !text.includes("hyperShader")+ );+}+function getDocumentScriptSignature(doc: Document): string {const projectSignature = Array.from(doc.querySelectorAll<HTMLMetaElement>('meta[name="hyperframes-project-signature"]'),@@ -252,6 +265,12 @@ function getDocumentScriptSignature(doc: Document): string {.map((meta) => meta.getAttribute("content") || "").join("\n");const scriptText = Array.from(doc.querySelectorAll<HTMLScriptElement>("script"))+ .filter((script) => {+ if (script.src) return true;+ const text = script.textContent || "";+ if (!text.trim()) return false;+ return !isGsapAnimationOnlyScript(text);+ }).map((script) => {const attrs = [script.type,@@ -2192,6 +2211,10 @@ export function init(config: HyperShaderConfig): GsapTimeline {hfWin.__hf = hfWin.__hf || {};hfWin.__hf.shaderTransitionsReady = prewarmPromise;+ (+ window as Window & { __hfSuppressSceneMutations?: <T>(fn: () => T) => T }+ ).__hfSuppressSceneMutations = <T>(fn: () => T): T => suppressSceneMutationTracking(fn);+registerTimeline(compId, tl, config.timeline);return tl;}diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.tsindex 5df74874c7..5942d8f300 100644--- a/packages/studio/src/hooks/useDomEditSession.ts+++ b/packages/studio/src/hooks/useDomEditSession.ts@@ -224,6 +224,7 @@ export function useDomEditSession({} = useGsapScriptCommits({projectIdRef,activeCompPath,+ previewIframeRef,editHistory,domEditSaveTimestampRef,reloadPreview,diff --git a/packages/studio/src/hooks/useGsapScriptCommits.ts b/packages/studio/src/hooks/useGsapScriptCommits.tsindex b8db3ed78e..a453333881 100644--- a/packages/studio/src/hooks/useGsapScriptCommits.ts+++ b/packages/studio/src/hooks/useGsapScriptCommits.ts@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef } from "react";import type { ParsedGsap } from "@hyperframes/core/gsap-parser";import type { DomEditSelection } from "../components/editor/domEditingTypes";import type { EditHistoryKind } from "../utils/editHistory";+import { applySoftReload } from "../utils/gsapSoftReload";const PROPERTY_DEFAULTS: Record<string, number> = {opacity: 1,@@ -45,6 +46,7 @@ interface MutationResult {parsed?: ParsedGsap;before?: string;after?: string;+ scriptText?: string;}async function mutateGsapScript(@@ -71,6 +73,7 @@ async function mutateGsapScript(interface GsapScriptCommitsParams {projectIdRef: React.MutableRefObject<string | null>;activeCompPath: string | null;+ previewIframeRef: React.RefObject<HTMLIFrameElement | null>;editHistory: {recordEdit: (entry: {label: string;@@ -90,6 +93,7 @@ const DEBOUNCE_MS = 150;export function useGsapScriptCommits({projectIdRef,activeCompPath,+ previewIframeRef,editHistory,domEditSaveTimestampRef,reloadPreview,@@ -131,13 +135,18 @@ export function useGsapScriptCommits({onCacheInvalidate();- if (!options.softReload) {+ if (options.softReload && result.scriptText) {+ if (!applySoftReload(previewIframeRef.current, result.scriptText)) {+ reloadPreview();+ }+ } else {reloadPreview();}},[projectIdRef,activeCompPath,+ previewIframeRef,editHistory,domEditSaveTimestampRef,reloadPreview,@@ -156,6 +165,7 @@ export function useGsapScriptCommits({{label: `Edit GSAP ${property}`,coalesceKey: `gsap:${animationId}:${property}`,+ softReload: true,},);}, [commitMutation]);diff --git a/packages/studio/src/utils/gsapSoftReload.test.ts b/packages/studio/src/utils/gsapSoftReload.test.tsnew file mode 100644index 0000000000..a2adb196d9--- /dev/null+++ b/packages/studio/src/utils/gsapSoftReload.test.ts@@ -0,0 +1,104 @@+// @vitest-environment happy-dom++import { describe, it, expect, vi } from "vitest";+import { applySoftReload } from "./gsapSoftReload";++const SCRIPT_TEXT = `+window.__timelines = window.__timelines || {};+const tl = gsap.timeline({ paused: true });+tl.to("#box", { opacity: 0.8 });+window.__timelines["root"] = tl;+`;++function buildMockIframe(overrides: Record<string, unknown> = {}) {+ const scriptEl = document.createElement("script");+ scriptEl.textContent =+ 'const tl = gsap.timeline({ paused: true }); tl.to("#box", { opacity: 0.5 });';+ const container = document.createElement("div");+ container.appendChild(scriptEl);++ const mockTimeline = { kill: vi.fn(), pause: vi.fn() };+ const contentWindow = {+ gsap: { timeline: vi.fn() },+ __hfForceTimelineRebind: vi.fn(),+ __timelines: { root: mockTimeline } as Record<string, typeof mockTimeline>,+ __player: { getTime: () => 2.0, seek: vi.fn() },+ __hfStudioManualEditsApply: vi.fn(),+ __hfSuppressSceneMutations: undefined as undefined | (<T>(fn: () => T) => T),+ ...overrides,+ };++ const contentDocument = {+ querySelectorAll: (sel: string) => (sel === "script:not([src])" ? [scriptEl] : []),+ createElement: (tag: string) => document.createElement(tag),+ body: container,+ };++ return {+ iframe: { contentWindow, contentDocument } as unknown as HTMLIFrameElement,+ contentWindow,+ mockTimeline,+ };+}++describe("applySoftReload", () => {+ it("returns false when iframe is null", () => {+ expect(applySoftReload(null, SCRIPT_TEXT)).toBe(false);+ });++ it("returns false when scriptText is empty", () => {+ const { iframe } = buildMockIframe();+ expect(applySoftReload(iframe, "")).toBe(false);+ });++ it("returns false when gsap is not on iframe window", () => {+ const { iframe } = buildMockIframe({ gsap: undefined });+ expect(applySoftReload(iframe, SCRIPT_TEXT)).toBe(false);+ });++ it("returns false when __hfForceTimelineRebind is missing", () => {+ const { iframe } = buildMockIframe({ __hfForceTimelineRebind: undefined });+ expect(applySoftReload(iframe, SCRIPT_TEXT)).toBe(false);+ });++ it("kills existing timelines, rebinds, and re-seeks on success", () => {+ const { iframe, contentWindow, mockTimeline } = buildMockIframe();+ const result = applySoftReload(iframe, SCRIPT_TEXT);+ expect(result).toBe(true);+ expect(mockTimeline.kill).toHaveBeenCalled();+ expect(contentWindow.__hfForceTimelineRebind).toHaveBeenCalled();+ expect(contentWindow.__player.seek).toHaveBeenCalledWith(2.0);+ expect(contentWindow.__hfStudioManualEditsApply).toHaveBeenCalled();+ });++ it("wraps execution in __hfSuppressSceneMutations when available", () => {+ let suppressionCalled = false;+ const { iframe } = buildMockIframe({+ __hfSuppressSceneMutations: <T>(fn: () => T): T => {+ suppressionCalled = true;+ return fn();+ },+ });+ const result = applySoftReload(iframe, SCRIPT_TEXT);+ expect(result).toBe(true);+ expect(suppressionCalled).toBe(true);+ });++ it("returns false when multiple GSAP scripts exist (ambiguous)", () => {+ const script1 = document.createElement("script");+ script1.textContent = "const tl = gsap.timeline({ paused: true });";+ const script2 = document.createElement("script");+ script2.textContent = 'tl.to("#other", { x: 10 });';+ const container = document.createElement("div");+ container.appendChild(script1);+ container.appendChild(script2);++ const { iframe } = buildMockIframe();+ (iframe as unknown as { contentDocument: unknown }).contentDocument = {+ querySelectorAll: (sel: string) => (sel === "script:not([src])" ? [script1, script2] : []),+ createElement: (tag: string) => document.createElement(tag),+ body: container,+ };+ expect(applySoftReload(iframe, SCRIPT_TEXT)).toBe(false);+ });+});diff --git a/packages/studio/src/utils/gsapSoftReload.ts b/packages/studio/src/utils/gsapSoftReload.tsnew file mode 100644index 0000000000..b27d404e1c--- /dev/null+++ b/packages/studio/src/utils/gsapSoftReload.ts@@ -0,0 +1,89 @@+type IframeWindow = Window & {+ __timelines?: Record<string, { kill?: () => void; pause?: () => void }>;+ __player?: { getTime?: () => number; seek?: (t: number) => void };+ __hfForceTimelineRebind?: () => void;+ __hfSuppressSceneMutations?: <T>(fn: () => T) => T;+ __hfStudioManualEditsApply?: () => void;+ gsap?: { timeline?: (...args: unknown[]) => unknown };+};++function isGsapScript(text: string): boolean {+ return (+ text.includes("gsap.timeline") ||+ text.includes("__timelines") ||+ text.includes(".to(") ||+ text.includes(".set(")+ );+}++function findGsapScriptElements(doc: Document): HTMLScriptElement[] {+ const results: HTMLScriptElement[] = [];+ const scripts = doc.querySelectorAll<HTMLScriptElement>("script:not([src])");+ for (const script of scripts) {+ if (isGsapScript(script.textContent || "")) results.push(script);+ }+ return results;+}++/**+ * Replace the GSAP script in the live iframe without reloading. This preserves+ * the WebGL context and shader transition cache.+ *+ * Scoped to root-document GSAP scripts only — scripts inside `<template>`+ * elements (sub-compositions) are not visible to `querySelectorAll` and will+ * fall back to a full iframe reload.+ *+ * Returns false (triggering a full reload fallback) when:+ * - The iframe or GSAP runtime isn't available+ * - Multiple GSAP scripts are found (ambiguous which to replace)+ * - No matching GSAP script element exists in the live DOM+ */+export function applySoftReload(iframe: HTMLIFrameElement | null, scriptText: string): boolean {+ if (!iframe || !scriptText) return false;++ const win = iframe.contentWindow as IframeWindow | null;+ const doc = iframe.contentDocument;+ if (!win || !doc) return false;+ if (!win.gsap || !win.__hfForceTimelineRebind) return false;++ const gsapScripts = findGsapScriptElements(doc);+ if (gsapScripts.length !== 1) return false;+ const oldScriptEl = gsapScripts[0]!;++ const currentTime = win.__player?.getTime?.() ?? 0;++ const doReload = () => {+ const timelines = win.__timelines;+ if (timelines) {+ for (const key of Object.keys(timelines)) {+ try {+ timelines[key]?.kill?.();+ } catch {}+ delete timelines[key];+ }+ }++ oldScriptEl.remove();+ const newScript = doc.createElement("script");+ // IIFE prevents const/let redeclaration errors across consecutive edits.+ // Top-level declarations are scoped to the IIFE; window.* assignments+ // (e.g. window.__timelines["root"] = tl) still reach the global scope.+ newScript.textContent = `(function(){${scriptText}\n})();`;+ doc.body.appendChild(newScript);++ win.__hfForceTimelineRebind?.();+ win.__player?.seek?.(currentTime);+ win.__hfStudioManualEditsApply?.();+ };++ try {+ if (win.__hfSuppressSceneMutations) {+ win.__hfSuppressSceneMutations(doReload);+ } else {+ doReload();+ }+ return true;+ } catch {+ return false;+ }+}