Skip to content

Commit a5f970a

Browse files
committed
fix(studio): undoing a freeze frame removes the still it made
1 parent b7343e3 commit a5f970a

7 files changed

Lines changed: 116 additions & 28 deletions

File tree

‎packages/studio-server/src/routes/freezeFrame.test.ts‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,8 @@ describe("freeze-frame route", () => {
5858
target: { id: "talk" },
5959
playhead: 2.5,
6060
});
61-
const body: { before?: string; after?: string; imageSrc?: string } = await res.json();
61+
const body: { before?: string; after?: string; imageSrc?: string; stillPath?: string } =
62+
await res.json();
6263
expect(res.status).toBe(200);
6364
const output = calls[0]?.at(-1) ?? "";
6465
expect(calls[0]).toEqual([
@@ -74,6 +75,7 @@ describe("freeze-frame route", () => {
7475
expect(dirname(output)).toBe(join(dir, "assets/freeze"));
7576
expect(basename(output)).toMatch(/^talk-[0-9a-f]{10}-2500-[0-9a-f]{8}\.png$/);
7677
expect(body.imageSrc).toBe(`assets/freeze/${basename(output)}`);
78+
expect(body.stillPath).toBe(`assets/freeze/${basename(output)}`);
7779
expect(body.before).toBe(html);
7880
expect(readFileSync(join(dir, "index.html"), "utf-8")).toBe(body.after);
7981
expect(body.after).toContain('id="talk-freeze"');
@@ -107,6 +109,25 @@ describe("freeze-frame route", () => {
107109
expect(readFileSync(join(dir, "index.html"), "utf-8")).toBe(html);
108110
});
109111

112+
it("removes the still it extracted when the page changed before the write", async () => {
113+
let still = "";
114+
const { dir, post } = setup(async (args) => {
115+
still = args.at(-1) ?? "";
116+
writeFileSync(still, "png");
117+
writeFileSync(join(dir, "index.html"), `${html}\n<!-- edited meanwhile -->`);
118+
return { ok: true };
119+
});
120+
const res = await post({
121+
path: "index.html",
122+
expectedVersion: fileContentVersion(html),
123+
target: { id: "talk" },
124+
playhead: 2.5,
125+
});
126+
expect(res.status).toBe(409);
127+
expect(still).not.toBe("");
128+
expect(existsSync(still)).toBe(false);
129+
});
130+
110131
it("keeps a traversal clip id inside assets/freeze, for the ffmpeg output and the still's src", async () => {
111132
const evil = html.replace('id="talk"', 'id="../../../../outside/frame"');
112133
const calls: string[][] = [];
@@ -123,9 +144,11 @@ describe("freeze-frame route", () => {
123144
target: { id: "../../../../outside/frame" },
124145
playhead: 2.5,
125146
});
126-
const body: { imageSrc?: string; after?: string } = await res.json();
147+
const body: { imageSrc?: string; after?: string; stillPath?: string } = await res.json();
127148
expect(res.status).toBe(200);
128149
const output = calls[0]?.at(-1) ?? "";
150+
// The history names project files from the project root, not from the page that shows the still.
151+
expect(body.stillPath).toBe(`assets/freeze/${basename(output)}`);
129152
expect(basename(output)).toMatch(/^____________outside_frame-[0-9a-f]{10}-2500-/);
130153
expect(dirname(output)).toBe(join(dir, "assets/freeze"));
131154
expect(body.imageSrc).toBe(`../assets/freeze/${basename(output)}`);
@@ -199,16 +222,16 @@ describe("freeze-frame route", () => {
199222
expect(readFileSync(outputs[0] ?? "", "utf-8")).toBe(first);
200223
});
201224

202-
it("gives concurrent requests distinct stills", async () => {
225+
it("gives concurrent requests distinct stills and keeps only the one the page uses", async () => {
203226
const outputs: string[] = [];
204227
const { dir, post } = setup(writingExtractor(outputs));
205228
const results = await Promise.all([freeze(post, dir, "talk"), freeze(post, dir, "talk")]);
206229
expect(results.map((res) => res.status).sort()).toEqual([200, 409]);
207230
expect(new Set(outputs).size).toBe(2);
208-
expect(outputs.map((output) => readFileSync(output, "utf-8"))).toEqual([
209-
expect.stringContaining("#"),
210-
expect.stringContaining("#"),
211-
]);
231+
const kept = outputs.filter((output) => existsSync(output));
232+
expect(kept).toHaveLength(1);
233+
expect(readFileSync(kept[0] ?? "", "utf-8")).toContain("#");
234+
expect(readFileSync(join(dir, "index.html"), "utf-8")).toContain(basename(kept[0] ?? ""));
212235
});
213236

214237
it("refuses, without extracting, when the still's name is already taken", async () => {

‎packages/studio-server/src/routes/freezeFrame.ts‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { execFile } from "node:child_process";
2-
import { existsSync, readFileSync, statSync } from "node:fs";
2+
import { existsSync, readFileSync, rmSync, statSync } from "node:fs";
33
import { dirname, join, relative, sep } from "node:path";
44
import type { Hono } from "hono";
55
import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
@@ -86,7 +86,7 @@ async function extractStill(
8686
source: FreezeSource,
8787
playhead: number,
8888
tools: { extract: FrameExtractor; stillToken: () => string },
89-
): Promise<{ imageSrc: string } | Failure> {
89+
): Promise<{ imageSrc: string; stillPath: string; imagePath: string } | Failure> {
9090
const fileDir = dirname(absPath);
9191
const mediaPath = pinWithinProject(projectDir, relative(projectDir, join(fileDir, source.src)));
9292
if (!mediaPath) return { error: `forbidden media path: ${source.src}`, status: 403 };
@@ -107,7 +107,8 @@ async function extractStill(
107107
};
108108
}
109109
const depth = relative(projectDir, fileDir).split(sep).filter(Boolean).length;
110-
return { imageSrc: `${"../".repeat(depth)}${FREEZE_DIR.join("/")}/${fileName}` };
110+
const stillPath = `${FREEZE_DIR.join("/")}/${fileName}`;
111+
return { imageSrc: `${"../".repeat(depth)}${stillPath}`, stillPath, imagePath };
111112
}
112113

113114
function writeFolded(
@@ -160,17 +161,22 @@ export function registerFreezeFrameRoutes(
160161
stillToken,
161162
});
162163
if ("error" in still) return c.json({ error: still.error }, still.status);
163-
const { imageSrc } = still;
164+
const { imageSrc, stillPath } = still;
164165
const folded = applyFreezeFrameToHtml(before, {
165166
target: body.target,
166167
playhead: body.playhead,
167168
imageSrc,
168169
});
169-
if (!folded) return c.json({ error: "Freeze target was not found in the file" }, 400);
170+
// The page never names a still from a freeze that failed past here.
171+
const fail = (error: string, status: 400 | Failure["status"]) => {
172+
rmSync(still.imagePath, { force: true });
173+
return c.json({ error }, status);
174+
};
175+
if (!folded) return fail("Freeze target was not found in the file", 400);
170176
const written = writeFolded(project.dir, absPath, body.path, before, folded.html, {
171177
token: body.transactionToken ?? c.req.header("X-Hyperframes-Write-Token"),
172178
});
173-
if ("error" in written) return c.json({ error: written.error }, written.status);
179+
if ("error" in written) return fail(written.error, written.status);
174180
const { version, writeToken, backupPath } = written;
175181
return c.json({
176182
ok: true,
@@ -182,6 +188,7 @@ export function registerFreezeFrameRoutes(
182188
backupPath,
183189
freezeId: folded.freezeId,
184190
imageSrc,
191+
stillPath,
185192
});
186193
});
187194
}

‎packages/studio/src/hooks/useFreezeFrame.test.ts‎

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
// @vitest-environment happy-dom
2+
import { act, createElement } from "react";
3+
import { createRoot } from "react-dom/client";
14
import { afterEach, describe, expect, it, vi } from "vitest";
25
import type { TimelineElement } from "../player";
3-
import { requestFreezeFrame } from "./useFreezeFrame";
6+
import { requestFreezeFrame, useFreezeFrame } from "./useFreezeFrame";
47

58
afterEach(() => vi.unstubAllGlobals());
69

@@ -29,14 +32,15 @@ function stubFetch(freezeResponse: { status: number; body: unknown }) {
2932

3033
describe("requestFreezeFrame", () => {
3134
it("posts the clip target, file version and an authored-time playhead", async () => {
32-
const calls = stubFetch({ status: 200, body: { before: "a", after: "b", version: "v2" } });
35+
const frozen = { before: "a", after: "b", version: "v2", stillPath: "assets/freeze/t.png" };
36+
const calls = stubFetch({ status: 200, body: frozen });
3337
const result = await requestFreezeFrame({
3438
projectId: "p",
3539
path: "scene.html",
3640
element,
3741
playhead: 7.5,
3842
});
39-
expect(result).toEqual({ before: "a", after: "b", version: "v2" });
43+
expect(result).toEqual(frozen);
4044
const post = calls[1];
4145
expect(post?.url).toContain("/file-mutations/freeze-frame");
4246
expect(post?.body).toMatchObject({
@@ -54,3 +58,35 @@ describe("requestFreezeFrame", () => {
5458
).rejects.toThrow("Move the playhead inside a video clip to freeze");
5559
});
5660
});
61+
62+
describe("useFreezeFrame", () => {
63+
it("records the still it made with the edit, so Undo removes it", async () => {
64+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
65+
stubFetch({
66+
status: 200,
67+
body: { before: "a", after: "b", version: "v2", stillPath: "assets/freeze/talk.png" },
68+
});
69+
const recordEdit = vi.fn(async () => {});
70+
let freeze!: ReturnType<typeof useFreezeFrame>;
71+
function Harness() {
72+
freeze = useFreezeFrame({
73+
projectId: "p",
74+
activeCompPath: "index.html",
75+
showToast: () => {},
76+
writeProjectFile: async () => {},
77+
recordEdit,
78+
reloadPreview: () => {},
79+
});
80+
return null;
81+
}
82+
const root = createRoot(document.createElement("div"));
83+
await act(async () => root.render(createElement(Harness)));
84+
await act(() => freeze({ ...element, sourceFile: "index.html" }, 7.5));
85+
expect(recordEdit).toHaveBeenCalledWith({
86+
label: "Freeze frame",
87+
files: { "index.html": { before: "a", after: "b" } },
88+
created: ["assets/freeze/talk.png"],
89+
});
90+
act(() => root.unmount());
91+
});
92+
});

‎packages/studio/src/hooks/useFreezeFrame.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ interface FreezeFrameResponse {
1313
before: string;
1414
after: string;
1515
version: string;
16+
stillPath: string;
1617
}
1718

1819
function isFreezeFrameResponse(value: unknown): value is FreezeFrameResponse {
@@ -21,7 +22,8 @@ function isFreezeFrameResponse(value: unknown): value is FreezeFrameResponse {
2122
return (
2223
typeof body.before === "string" &&
2324
typeof body.after === "string" &&
24-
typeof body.version === "string"
25+
typeof body.version === "string" &&
26+
typeof body.stillPath === "string"
2527
);
2628
}
2729

@@ -108,6 +110,7 @@ export function useFreezeFrame(options: UseFreezeFrameOptions) {
108110
await opts.recordEdit({
109111
label: "Freeze frame",
110112
files: { [path]: { before: result.before, after: result.after } },
113+
created: [result.stillPath],
111114
});
112115
opts.observeProjectFileVersion?.(path, result.version);
113116
});

‎packages/studio/src/hooks/usePersistentEditHistory.test.ts‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
// fallow-ignore-file code-duplication
33
import { act, createElement } from "react";
44
import { createRoot } from "react-dom/client";
5-
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
66
import { tmpdir } from "node:os";
7-
import { join } from "node:path";
7+
import { dirname, join } from "node:path";
88
import { afterEach, expect, it, vi } from "vitest";
99
import {
1010
createStudioApi,
@@ -88,6 +88,29 @@ it("an edit Studio saved is undone and redone by the project's history, with the
8888
expect(file()).toBe("B");
8989
});
9090

91+
it("a file the edit made (a freeze's still) is deleted by its Undo and put back by its Redo", async () => {
92+
const { dir, hook, save, readFile } = await studio();
93+
const still = join(dir, "assets", "freeze", "talk.png");
94+
mkdirSync(dirname(still), { recursive: true });
95+
writeFileSync(still, "png");
96+
save("B");
97+
await act(() =>
98+
hook().recordEdit({
99+
label: "Freeze frame",
100+
files: { "index.html": { before: "A", after: "B" } },
101+
created: ["assets/freeze/talk.png"],
102+
}),
103+
);
104+
await vi.waitFor(() => expect(hook().undoLabel).toBe("Freeze frame"));
105+
106+
await act(() => hook().undo({ readFile }));
107+
expect(existsSync(still)).toBe(false);
108+
109+
await vi.waitFor(() => expect(hook().canRedo).toBe(true));
110+
await act(() => hook().redo({ readFile }));
111+
expect(readFileSync(still, "utf8")).toBe("png");
112+
});
113+
91114
it("a drag's edits under one key undo as one step, even before the drag goes idle", async () => {
92115
const { hook, file, save, readFile } = await studio();
93116
const writes: Array<[before: string, after: string]> = [

‎packages/studio/src/hooks/usePersistentEditHistory.ts‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
22
import type { HistoryListItem, HistoryResult } from "@hyperframes/studio-server";
33
import { studioFileContentVersion, studioWriteHeaders } from "../utils/studioFileVersion";
44
import type { RestoreFiles } from "../utils/gsapUndoRestore";
5-
6-
interface RecordEditInput {
7-
label: string;
8-
coalesceKey?: string;
9-
coalesceMs?: number;
10-
files: Record<string, { before: string; after: string }>;
11-
}
5+
import type { RecordEditInput } from "../utils/studioFileHistory";
126

137
interface ApplyCallbacks {
148
readFile: (path: string) => Promise<string>;
@@ -210,9 +204,9 @@ export function usePersistentEditHistory({ projectId }: UsePersistentEditHistory
210204
}, [refresh, own]);
211205

212206
const recordEdit = useCallback(
213-
async ({ label, coalesceKey, coalesceMs, files }: RecordEditInput) => {
207+
async ({ label, coalesceKey, coalesceMs, files, created = [] }: RecordEditInput) => {
214208
if (!projectId) return;
215-
const paths = Object.keys(files);
209+
const paths = [...Object.keys(files), ...created];
216210
own.overtake();
217211
const reply = await post(historyUrl(projectId, "/claim"), {
218212
label,

‎packages/studio/src/utils/studioFileHistory.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ export interface RecordEditInput {
88
coalesceKey?: string;
99
coalesceMs?: number;
1010
files: Record<string, { before: string; after: string }>;
11+
/** Files the edit made that are not text (a freeze's still): Undo deletes them, Redo puts them back. */
12+
created?: string[];
1113
}
1214

1315
export interface DomEditCommitBaseParams {

0 commit comments

Comments
 (0)