mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-16 06:19:21 +00:00
fix(sdk,studio): 14 code-review correctness fixes from stage 7 review
- http adapter: throw on 5xx instead of silently returning undefined - fs adapter: serialize appendVersion to prevent concurrent pruning race - mutate: GSAP handlers throw (not silent EMPTY) when no GSAP script block - mutate: selectorMatchesId supports scoped hf-HOST/hf-LEAF ids - sdkShadow: fix double data- prefix on attribute patch ops - sdkShadow: call onDomEditPersisted on SDK cutover success path - useSdkSession: fix compRef closure race on dispose; suppress self-write echo - App.tsx: pass domEditSaveTimestampRef to useSdkSession for echo suppression - examples: fix dead !comp.can(op) guard (needs .ok); remove stale id field Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
3f742d9745
commit
e33dd14026
@@ -121,10 +121,7 @@ export async function addStaggeredEntrance(html: string, staggerDelay = 0.15): P
|
||||
fromProperties: { opacity: 0, y: 30 },
|
||||
} as const;
|
||||
const first = textEls[0];
|
||||
if (
|
||||
!first ||
|
||||
!comp.can({ type: "addGsapTween", target: first, id: "preflight", tween: probeTween })
|
||||
) {
|
||||
if (!first || !comp.can({ type: "addGsapTween", target: first, tween: probeTween }).ok) {
|
||||
return comp.serialize();
|
||||
}
|
||||
|
||||
|
||||
@@ -98,12 +98,12 @@ export function addBounceIn(comp: Composition, targetId: string): string | null
|
||||
ease: "bounce.out",
|
||||
fromProperties: { y: 40, opacity: 0 },
|
||||
} as const;
|
||||
if (!comp.can({ type: "addGsapTween", target: targetId, id: "preflight", tween })) return null;
|
||||
if (!comp.can({ type: "addGsapTween", target: targetId, tween }).ok) return null;
|
||||
return comp.addGsapTween(targetId, tween);
|
||||
}
|
||||
|
||||
export function updateEase(comp: Composition, animationId: string, ease: string): void {
|
||||
if (!comp.can({ type: "setGsapTween", animationId, properties: { ease } })) return;
|
||||
if (!comp.can({ type: "setGsapTween", animationId, properties: { ease } }).ok) return;
|
||||
comp.setGsapTween(animationId, { ease });
|
||||
}
|
||||
|
||||
|
||||
@@ -113,7 +113,7 @@ export function addFadeIn(comp: Composition, targetId: string, delay = 0): strin
|
||||
ease: "power2.out",
|
||||
fromProperties: { opacity: 0 },
|
||||
};
|
||||
if (!comp.can({ type: "addGsapTween", target: targetId, id: "preflight", tween })) return null;
|
||||
if (!comp.can({ type: "addGsapTween", target: targetId, tween }).ok) return null;
|
||||
return comp.addGsapTween(targetId, tween);
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ export function addBounce(
|
||||
fromProperties: { y: 60, opacity: 0 },
|
||||
...overrides,
|
||||
};
|
||||
if (!comp.can({ type: "addGsapTween", target: targetId, id: "preflight", tween })) return null;
|
||||
if (!comp.can({ type: "addGsapTween", target: targetId, tween }).ok) return null;
|
||||
return comp.addGsapTween(targetId, tween);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ class FsAdapter implements PersistAdapter {
|
||||
private errorHandlers: Array<(e: PersistErrorEvent) => void> = [];
|
||||
private readonly inflightWrites = new Set<Promise<void>>();
|
||||
private versionCounter = 0;
|
||||
private appendVersionQueue = Promise.resolve();
|
||||
|
||||
constructor(opts: FsAdapterOptions) {
|
||||
this.root = opts.root;
|
||||
@@ -109,7 +110,14 @@ class FsAdapter implements PersistAdapter {
|
||||
return join(this.root, ".hf-versions", path);
|
||||
}
|
||||
|
||||
private async appendVersion(path: string, content: string): Promise<void> {
|
||||
private appendVersion(path: string, content: string): Promise<void> {
|
||||
this.appendVersionQueue = this.appendVersionQueue.then(() =>
|
||||
this.doAppendVersion(path, content),
|
||||
);
|
||||
return this.appendVersionQueue;
|
||||
}
|
||||
|
||||
private async doAppendVersion(path: string, content: string): Promise<void> {
|
||||
const dir = this.versionsDir(path);
|
||||
await mkdir(dir, { recursive: true });
|
||||
// Pad counter to 6 digits so lexicographic sort = insertion order within same ms.
|
||||
|
||||
@@ -59,11 +59,17 @@ describe("read()", () => {
|
||||
expect(await adapter.read("missing.html")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns undefined on non-ok response", async () => {
|
||||
it("returns undefined on 404 response", async () => {
|
||||
stubFetch(() => ({ ok: false, status: 404 }));
|
||||
const adapter = createHttpAdapter({ projectFilesUrl: BASE });
|
||||
expect(await adapter.read("gone.html")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("throws on 5xx server error", async () => {
|
||||
stubFetch(() => ({ ok: false, status: 503 }));
|
||||
const adapter = createHttpAdapter({ projectFilesUrl: BASE });
|
||||
await expect(adapter.read("comp.html")).rejects.toThrow("HTTP 503");
|
||||
});
|
||||
});
|
||||
|
||||
// ── write() ───────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -30,7 +30,8 @@ class HttpAdapter implements PersistAdapter {
|
||||
async read(path: string): Promise<string | undefined> {
|
||||
const url = `${this.baseUrl}/files/${encodeURIComponent(path)}?optional=1`;
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) return undefined;
|
||||
if (res.status === 404) return undefined;
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = (await res.json()) as { content?: string };
|
||||
return typeof data.content === "string" ? data.content : undefined;
|
||||
}
|
||||
|
||||
@@ -177,16 +177,17 @@ describe("addGsapTween", () => {
|
||||
expect(newScript).toContain("opacity: 1");
|
||||
});
|
||||
|
||||
it("returns EMPTY when no GSAP script", () => {
|
||||
it("throws when no GSAP script block exists in composition", () => {
|
||||
const noScript = parseMutable(
|
||||
`<div data-hf-id="hf-stage" data-hf-root><div data-hf-id="hf-box"></div></div>`,
|
||||
);
|
||||
const result = applyOp(noScript, {
|
||||
type: "addGsapTween",
|
||||
target: "hf-box",
|
||||
tween: { method: "to", properties: { x: 1 } },
|
||||
});
|
||||
expect(result.forward).toHaveLength(0);
|
||||
expect(() =>
|
||||
applyOp(noScript, {
|
||||
type: "addGsapTween",
|
||||
target: "hf-box",
|
||||
tween: { method: "to", properties: { x: 1 } },
|
||||
}),
|
||||
).toThrow("No GSAP script block found");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -477,3 +478,41 @@ window.__timelines["t"] = tl;`;
|
||||
expect(newScript).toContain("hf-stage");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── GSAP ops on composition with no script block ────────────────────────────
|
||||
|
||||
const NO_SCRIPT_HTML = `<div data-hf-id="hf-stage" data-hf-root style="width:1280px;height:720px">
|
||||
<div data-hf-id="hf-box" style="opacity:0"></div>
|
||||
</div>`.trim();
|
||||
|
||||
describe("GSAP ops on composition with no GSAP script block", () => {
|
||||
function freshNoScript() {
|
||||
return parseMutable(NO_SCRIPT_HTML);
|
||||
}
|
||||
|
||||
it("addGsapTween throws instead of silent no-op", () => {
|
||||
expect(() =>
|
||||
applyOp(freshNoScript(), {
|
||||
type: "addGsapTween",
|
||||
target: "hf-box",
|
||||
tween: { method: "to", properties: { x: 100 } },
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("setGsapTween throws instead of silent no-op", () => {
|
||||
expect(() =>
|
||||
applyOp(freshNoScript(), {
|
||||
type: "setGsapTween",
|
||||
animationId: "anim-1",
|
||||
properties: { ease: "power2.out" },
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("removeGsapTween throws instead of silent no-op", () => {
|
||||
expect(() =>
|
||||
applyOp(freshNoScript(), { type: "removeGsapTween", animationId: "anim-1" }),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -389,14 +389,14 @@ describe("validateOp", () => {
|
||||
// ─── Phase 3b ops — graceful when no GSAP script, feature-detectable ────────
|
||||
|
||||
describe("Phase 3b ops", () => {
|
||||
it("applyOp returns EMPTY when no GSAP script is present", () => {
|
||||
const result = applyOp(fresh(), {
|
||||
type: "addGsapTween",
|
||||
target: "hf-title",
|
||||
tween: { method: "from", properties: { opacity: 0 } },
|
||||
});
|
||||
expect(result.forward).toHaveLength(0);
|
||||
expect(result.inverse).toHaveLength(0);
|
||||
it("applyOp throws when no GSAP script block is present", () => {
|
||||
expect(() =>
|
||||
applyOp(fresh(), {
|
||||
type: "addGsapTween",
|
||||
target: "hf-title",
|
||||
tween: { method: "from", properties: { opacity: 0 } },
|
||||
}),
|
||||
).toThrow("No GSAP script block found");
|
||||
});
|
||||
|
||||
it("validateOp returns ok:false / E_NO_GSAP_SCRIPT when no GSAP script present", () => {
|
||||
|
||||
@@ -509,10 +509,15 @@ function handleSetVariableValue(
|
||||
// ─── GSAP selector helpers ───────────────────────────────────────────────────
|
||||
|
||||
function selectorMatchesId(selector: string, id: HfId): boolean {
|
||||
const bareId = id.includes("/") ? id.split("/").pop()! : id;
|
||||
return (
|
||||
selector === `[data-hf-id="${id}"]` ||
|
||||
selector === `[data-hf-id='${id}']` ||
|
||||
selector === `#${id}`
|
||||
selector === `#${id}` ||
|
||||
(bareId !== id &&
|
||||
(selector === `[data-hf-id="${bareId}"]` ||
|
||||
selector === `[data-hf-id='${bareId}']` ||
|
||||
selector === `#${bareId}`))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -585,6 +590,8 @@ function handleAddGsapTween(
|
||||
tween: GsapTweenSpec,
|
||||
): MutationResult {
|
||||
const script = getGsapScript(parsed.document);
|
||||
if (script === null)
|
||||
throw new Error("No GSAP script block found. Use comp.can(op) to check first.");
|
||||
if (!script) return EMPTY;
|
||||
|
||||
const extras: Record<string, unknown> = {};
|
||||
@@ -623,6 +630,8 @@ function handleSetGsapTween(
|
||||
properties: Partial<GsapTweenSpec>,
|
||||
): MutationResult {
|
||||
const script = getGsapScript(parsed.document);
|
||||
if (script === null)
|
||||
throw new Error("No GSAP script block found. Use comp.can(op) to check first.");
|
||||
if (!script) return EMPTY;
|
||||
|
||||
const updates: Partial<GsapAnimation> = {};
|
||||
@@ -649,6 +658,8 @@ function handleSetGsapTween(
|
||||
|
||||
function handleRemoveGsapTween(parsed: ParsedDocument, animationId: string): MutationResult {
|
||||
const script = getGsapScript(parsed.document);
|
||||
if (script === null)
|
||||
throw new Error("No GSAP script block found. Use comp.can(op) to check first.");
|
||||
if (!script) return EMPTY;
|
||||
const newScript = removeAnimationFromScript(script, animationId);
|
||||
if (newScript === script) return EMPTY;
|
||||
|
||||
@@ -152,6 +152,9 @@ export function StudioApp() {
|
||||
domEditSaveTimestampRef,
|
||||
setRefreshKey,
|
||||
});
|
||||
|
||||
const sdkSession = useSdkSession(projectId, activeCompPath, domEditSaveTimestampRef);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeCompPathHydrated) return;
|
||||
if (!fileManager.fileTreeLoaded) return;
|
||||
|
||||
@@ -134,7 +134,6 @@ export function useDomEditCommits({
|
||||
if (options?.shouldSave && !options.shouldSave()) return;
|
||||
|
||||
const targetPath = selection.sourceFile || activeCompPath || "index.html";
|
||||
|
||||
const readResponse = await fetch(
|
||||
`/api/projects/${pid}/files/${encodeURIComponent(targetPath)}`,
|
||||
);
|
||||
@@ -146,9 +145,14 @@ export function useDomEditCommits({
|
||||
if (typeof originalContent !== "string") {
|
||||
throw new Error(`Missing file contents for ${targetPath}`);
|
||||
}
|
||||
|
||||
if (options?.shouldSave && !options.shouldSave()) return;
|
||||
|
||||
if (
|
||||
onTrySdkPersist &&
|
||||
(await onTrySdkPersist(selection, operations, originalContent, targetPath))
|
||||
) {
|
||||
onDomEditPersisted?.(selection, operations);
|
||||
return;
|
||||
}
|
||||
const patchTarget = buildDomEditPatchTarget(selection);
|
||||
const patchBody = { target: patchTarget, operations };
|
||||
const unsafeFields = findUnsafeDomPatchValues(patchBody);
|
||||
@@ -162,7 +166,6 @@ export function useDomEditCommits({
|
||||
// handler suppresses the reload even if the event arrives before the
|
||||
// response (the server writes the file and emits SSE during the fetch).
|
||||
domEditSaveTimestampRef.current = Date.now();
|
||||
|
||||
const patchResponse = await fetch(
|
||||
`/api/projects/${pid}/file-mutations/patch-element/${encodeURIComponent(targetPath)}`,
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import type { MutableRefObject } from "react";
|
||||
import { openComposition } from "@hyperframes/sdk";
|
||||
import { createHttpAdapter } from "@hyperframes/sdk/adapters/http";
|
||||
import type { Composition } from "@hyperframes/sdk";
|
||||
@@ -27,9 +28,12 @@ export function shouldReloadSdkSession(payload: unknown, activeCompPath: string
|
||||
* is therefore purely additive — no SDK self-write exists yet, so there is no
|
||||
* persist echo. Step 3c must add self-write suppression once dispatch writes.
|
||||
*/
|
||||
const SELF_WRITE_SUPPRESS_MS = 2000;
|
||||
|
||||
export function useSdkSession(
|
||||
projectId: string | null,
|
||||
activeCompPath: string | null,
|
||||
domEditSaveTimestampRef?: MutableRefObject<number>,
|
||||
): Composition | null {
|
||||
const [session, setSession] = useState<Composition | null>(null);
|
||||
const [reloadToken, setReloadToken] = useState(0);
|
||||
@@ -38,9 +42,14 @@ export function useSdkSession(
|
||||
useEffect(() => {
|
||||
if (!activeCompPath) return;
|
||||
const handler = (payload?: unknown) => {
|
||||
if (shouldReloadSdkSession(payload, activeCompPath)) {
|
||||
setReloadToken((t) => t + 1);
|
||||
}
|
||||
if (!shouldReloadSdkSession(payload, activeCompPath)) return;
|
||||
// Suppress reload triggered by our own SDK cutover write.
|
||||
if (
|
||||
domEditSaveTimestampRef &&
|
||||
Date.now() - domEditSaveTimestampRef.current < SELF_WRITE_SUPPRESS_MS
|
||||
)
|
||||
return;
|
||||
setReloadToken((t) => t + 1);
|
||||
};
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.on("hf:file-change", handler);
|
||||
@@ -50,6 +59,7 @@ export function useSdkSession(
|
||||
const es = new EventSource("/api/events");
|
||||
es.addEventListener("file-change", handler);
|
||||
return () => es.close();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [activeCompPath]);
|
||||
|
||||
// ── Open / re-open the session ──
|
||||
@@ -60,7 +70,7 @@ export function useSdkSession(
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
let comp: Composition | null = null;
|
||||
const compRef = { current: null as Composition | null };
|
||||
|
||||
const adapter = createHttpAdapter({
|
||||
projectFilesUrl: `/api/projects/${projectId}`,
|
||||
@@ -69,7 +79,7 @@ export function useSdkSession(
|
||||
.read(activeCompPath)
|
||||
.then(async (content) => {
|
||||
if (cancelled || typeof content !== "string") return;
|
||||
comp = await openComposition(content, {
|
||||
const comp = await openComposition(content, {
|
||||
persist: adapter,
|
||||
persistPath: activeCompPath,
|
||||
});
|
||||
@@ -81,6 +91,7 @@ export function useSdkSession(
|
||||
comp.dispose();
|
||||
return;
|
||||
}
|
||||
compRef.current = comp;
|
||||
setSession(comp);
|
||||
})
|
||||
.catch(() => {
|
||||
@@ -89,7 +100,7 @@ export function useSdkSession(
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
const c = comp;
|
||||
const c = compRef.current;
|
||||
if (c) void c.flush().finally(() => c.dispose());
|
||||
};
|
||||
}, [projectId, activeCompPath, reloadToken]);
|
||||
|
||||
@@ -42,6 +42,20 @@ describe("patchOpsToSdkEditOps", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not double-prefix attribute op whose property already starts with data-", () => {
|
||||
const ops: PatchOperation[] = [
|
||||
{ type: "attribute", property: "data-hf-studio-path-offset", value: "true" },
|
||||
];
|
||||
const result = patchOpsToSdkEditOps("hf-box", ops);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual({
|
||||
type: "setAttribute",
|
||||
target: "hf-box",
|
||||
name: "data-hf-studio-path-offset",
|
||||
value: "true",
|
||||
});
|
||||
});
|
||||
|
||||
it("maps html-attribute op to setAttribute without prefix", () => {
|
||||
const ops: PatchOperation[] = [
|
||||
{ type: "html-attribute", property: "contenteditable", value: "true" },
|
||||
|
||||
@@ -38,7 +38,7 @@ export function patchOpsToSdkEditOps(hfId: string, ops: PatchOperation[]): EditO
|
||||
result.push({
|
||||
type: "setAttribute",
|
||||
target: hfId,
|
||||
name: `data-${op.property}`,
|
||||
name: op.property.startsWith("data-") ? op.property : `data-${op.property}`,
|
||||
value: op.value,
|
||||
});
|
||||
} else if (op.type === "html-attribute") {
|
||||
@@ -105,11 +105,14 @@ const OP_FIELD_RESOLVERS: Record<string, OpFieldResolver> = {
|
||||
actual: flat.styles[op.property] ?? null,
|
||||
}),
|
||||
"text-content": (op, flat) => ({ property: "text", expected: op.value ?? "", actual: flat.text }),
|
||||
attribute: (op, flat) => ({
|
||||
property: `data-${op.property}`,
|
||||
expected: op.value ?? null,
|
||||
actual: flat.attrs[`data-${op.property}`] ?? null,
|
||||
}),
|
||||
attribute: (op, flat) => {
|
||||
const attrName = op.property.startsWith("data-") ? op.property : `data-${op.property}`;
|
||||
return {
|
||||
property: attrName,
|
||||
expected: op.value ?? null,
|
||||
actual: flat.attrs[attrName] ?? null,
|
||||
};
|
||||
},
|
||||
"html-attribute": (op, flat) => ({
|
||||
property: op.property,
|
||||
expected: op.value ?? null,
|
||||
|
||||
Reference in New Issue
Block a user