mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-16 14:27:26 +00:00
* fix(studio): undo waits for in-flight hand edits before consuming history * docs(studio): trim comments to the 3-line house rule * feat(studio): export timeline editing, undo/redo, conflict banner and TimelinePane for a host * docs(studio): trim comments to the 3-line house rule * refactor(studio): simplify exports pass * docs(studio): trim comments to the 3-line house rule * fix(studio): resolve canEdit targets against expanded timeline rows * docs(studio): trim comment to the 3-line house rule * fix(studio): guard razor-split-all and the audio-group attribute write * fix(studio): gate the audio-group attribute for sub-composition-only members * fix(studio): keep blocked timeline edits truthful Refresh cached permission checks from the current host policy, gate auto-grouping before live patches, and restore optimistic attribute previews when a guarded commit is refused. * fix(studio): publish desktop compatibility exports Expose range selection and the canonical loader from the built Studio package while retaining timeline editing seams. * fix(studio): gate timeline drop writes Route asset, file, and composition drops through the shared edit permission gate before any side effect. * fix(studio): preserve release-owned style exports * fix(studio): clear file and Fallow gates * fix(studio): keep the carve gate and range slice under the size budgets * style(studio): format playerStore
223 lines
8.2 KiB
TypeScript
223 lines
8.2 KiB
TypeScript
// @vitest-environment happy-dom
|
|
|
|
// Proves the package's public exports, not internal hook paths, are enough
|
|
// for a host to mount hand editing outside EditorShell: an edit writes
|
|
// through the history path, Undo restores it, and a 409 shows the banner.
|
|
import { act, createElement, useRef } from "react";
|
|
import { createRoot, type Root } from "react-dom/client";
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
// Backend/storage mocking only, standing in for a host's own server and
|
|
// persistence — not part of the host's integration code under test.
|
|
import { studioFileContentVersion } from "./utils/studioFileVersion";
|
|
import { createMemoryEditHistoryStorage } from "./utils/editHistoryStorage";
|
|
import {
|
|
flushStudioPendingEdits,
|
|
useTimelineEditing,
|
|
useProjectFileWriter,
|
|
usePersistentEditHistory,
|
|
useEditHistoryActions,
|
|
ExternalFileConflictBanner,
|
|
StudioFileConflictError,
|
|
type ExternalFileChangeCoordinatorHandle,
|
|
type TimelineElement,
|
|
} from "./index";
|
|
|
|
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
|
|
|
const ORIGINAL_HTML = '<div id="clip" data-start="0" data-track-index="0"></div>';
|
|
|
|
let root: Root | null = null;
|
|
afterEach(() => {
|
|
act(() => root?.unmount());
|
|
document.body.innerHTML = "";
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
/** A minimal disk with etag-guarded PUT, faithful enough to exercise a real
|
|
* conflict: a stale If-Match gets a 409 with the current version + content. */
|
|
function stubHostProjectDisk(
|
|
initial: Record<string, string>,
|
|
options?: { editElsewhereAfterFirstRead?: boolean },
|
|
) {
|
|
const content = { ...initial };
|
|
const readsSeen = new Set<string>();
|
|
// The real backend's etag is a content hash (useProjectFileWriter derives
|
|
// If-Match the same way) — an arbitrary counter here would make every
|
|
// write from a host that hasn't just read the file look stale.
|
|
const versionOf = (path: string) => studioFileContentVersion(content[path]);
|
|
|
|
async function handlePut(path: string, init: RequestInit | undefined) {
|
|
const ifMatch = new Headers(init?.headers).get("If-Match");
|
|
const currentVersion = await versionOf(path);
|
|
if (ifMatch && ifMatch !== currentVersion) {
|
|
return new Response(JSON.stringify({ currentVersion, currentContent: content[path] }), {
|
|
status: 409,
|
|
});
|
|
}
|
|
content[path] = String(init?.body ?? "");
|
|
return new Response(JSON.stringify({ version: await versionOf(path) }), { status: 200 });
|
|
}
|
|
|
|
async function handleGet(path: string) {
|
|
const served = content[path];
|
|
// Simulates another writer landing between this read and the caller's
|
|
// own write: content moves on right after being served once, so the
|
|
// caller's hash of what it just read no longer matches disk.
|
|
if (options?.editElsewhereAfterFirstRead && !readsSeen.has(path)) {
|
|
readsSeen.add(path);
|
|
content[path] = `${served} <!--edited elsewhere-->`;
|
|
}
|
|
return new Response(
|
|
JSON.stringify({ content: served, version: await studioFileContentVersion(served) }),
|
|
{ status: 200 },
|
|
);
|
|
}
|
|
|
|
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const match = String(input).match(/\/files\/([^?]+)/);
|
|
const path = match ? decodeURIComponent(match[1]) : "";
|
|
return (init?.method ?? "GET") === "PUT" ? handlePut(path, init) : handleGet(path);
|
|
});
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
return { content, fetchMock };
|
|
}
|
|
|
|
type TimelineEditingHandle = {
|
|
handleTimelineElementMove: (
|
|
element: TimelineElement,
|
|
updates: { start: number; track: number },
|
|
) => Promise<void>;
|
|
};
|
|
|
|
function mountHost(
|
|
clip: TimelineElement,
|
|
iframe: HTMLIFrameElement,
|
|
): {
|
|
timelineEditing: TimelineEditingHandle;
|
|
undo: () => Promise<void>;
|
|
bannerHost: HTMLDivElement;
|
|
} {
|
|
let timelineEditing: TimelineEditingHandle | null = null;
|
|
let undo: (() => Promise<void>) | null = null;
|
|
let conflict: ExternalFileChangeCoordinatorHandle = {
|
|
blocked: null,
|
|
retry: async () => {},
|
|
useExternalFile: async () => {},
|
|
keepStudioFile: async () => {},
|
|
};
|
|
const bannerHost = document.createElement("div");
|
|
document.body.append(bannerHost);
|
|
const bannerRoot = createRoot(bannerHost);
|
|
// Created once: a fresh storage object on every render would change
|
|
// usePersistentEditHistory's effect deps each time and loop forever.
|
|
const storage = createMemoryEditHistoryStorage();
|
|
|
|
function Harness() {
|
|
const writer = useProjectFileWriter({ projectId: "p1" });
|
|
const editHistory = usePersistentEditHistory({ projectId: "p1", storage });
|
|
const historyActions = useEditHistoryActions({
|
|
editHistory,
|
|
readOptionalProjectFile: writer.readOptionalProjectFile,
|
|
readProjectFile: writer.readProjectFile,
|
|
writeProjectFile: writer.writeProjectFile,
|
|
showToast: () => {},
|
|
syncHistoryPreviewAfterApply: async () => {},
|
|
// The pattern a host's own dom-edit queue would also drain through —
|
|
// this is the one gate that closes the undo/delete race (#4194).
|
|
waitForPendingDomEditSaves: async () => {
|
|
const result = await flushStudioPendingEdits();
|
|
if (result.status !== "clean") throw result.error;
|
|
},
|
|
});
|
|
undo = historyActions.undo;
|
|
const commitRef = useRef(null);
|
|
timelineEditing = useTimelineEditing({
|
|
projectId: "p1",
|
|
activeCompPath: "index.html",
|
|
timelineElements: [clip],
|
|
showToast: () => {},
|
|
writeProjectFile: async (path, content, expectedContent) => {
|
|
try {
|
|
await writer.writeProjectFile(path, content, expectedContent);
|
|
} catch (error) {
|
|
if (error instanceof StudioFileConflictError) {
|
|
conflict = {
|
|
...conflict,
|
|
blocked: { status: "conflict", generation: 0, error, payload: null },
|
|
};
|
|
bannerRoot.render(createElement(ExternalFileConflictBanner, { coordinator: conflict }));
|
|
}
|
|
throw error;
|
|
}
|
|
},
|
|
observeProjectFileVersion: writer.observeProjectFileVersion,
|
|
recordEdit: editHistory.recordEdit,
|
|
reloadPreview: () => {},
|
|
previewIframeRef: { current: iframe },
|
|
pendingTimelineEditPathRef: { current: new Set<string>() },
|
|
uploadProjectFiles: async () => [],
|
|
handleDomZIndexReorderCommitRef: commitRef,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
root = createRoot(document.createElement("div"));
|
|
act(() => root!.render(createElement(Harness)));
|
|
if (!timelineEditing) throw new Error("Expected hook to mount");
|
|
if (!undo) throw new Error("Expected undo to be exposed");
|
|
return { timelineEditing, undo, bannerHost };
|
|
}
|
|
|
|
describe("public export surface: a host mounting hand editing outside EditorShell", () => {
|
|
it("writes a move through the history path and undo restores it", async () => {
|
|
const disk = stubHostProjectDisk({ "index.html": ORIGINAL_HTML });
|
|
const iframe = document.createElement("iframe");
|
|
document.body.append(iframe);
|
|
iframe.contentDocument!.body.innerHTML = ORIGINAL_HTML;
|
|
const clip: TimelineElement = {
|
|
id: "clip",
|
|
domId: "clip",
|
|
tag: "div",
|
|
start: 0,
|
|
duration: 2,
|
|
track: 0,
|
|
};
|
|
|
|
const { timelineEditing, undo } = mountHost(clip, iframe);
|
|
await act(async () => {
|
|
await timelineEditing.handleTimelineElementMove(clip, { start: 5, track: 0 });
|
|
});
|
|
expect(disk.content["index.html"]).toContain('data-start="5"');
|
|
|
|
await act(async () => {
|
|
await undo();
|
|
});
|
|
expect(disk.content["index.html"]).toContain('data-start="0"');
|
|
});
|
|
|
|
it("surfaces the conflict banner on a 409", async () => {
|
|
stubHostProjectDisk({ "index.html": ORIGINAL_HTML }, { editElsewhereAfterFirstRead: true });
|
|
const iframe = document.createElement("iframe");
|
|
document.body.append(iframe);
|
|
iframe.contentDocument!.body.innerHTML = ORIGINAL_HTML;
|
|
const clip: TimelineElement = {
|
|
id: "clip",
|
|
domId: "clip",
|
|
tag: "div",
|
|
start: 0,
|
|
duration: 2,
|
|
track: 0,
|
|
};
|
|
|
|
const { timelineEditing, bannerHost } = mountHost(clip, iframe);
|
|
|
|
await act(async () => {
|
|
await expect(
|
|
timelineEditing.handleTimelineElementMove(clip, { start: 5, track: 0 }),
|
|
).rejects.toBeInstanceOf(StudioFileConflictError);
|
|
});
|
|
|
|
expect(bannerHost.textContent).toContain("changed outside Studio");
|
|
});
|
|
});
|