Skip to content

Commit 9e1dbca

Browse files
fix(studio): undo and redo update the preview in place instead of reloading it (#4718)
* fix(studio): undo and redo swap the restored scene in place instead of reloading * fix(studio-server): a preview asked for right after an undo shows the undone state * fix(studio): an undo that restores a page outside every scene still reloads in full * fix(studio-server): a preview built across a write is not cached under the old signature * test(studio): a soft undo keeps the scene hashes so the next edit still swaps
1 parent ea48936 commit 9e1dbca

10 files changed

Lines changed: 169 additions & 5 deletions

File tree

‎packages/cli/src/server/studioServer.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -518,6 +518,9 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
518518
},
519519

520520
getProjectSignature: projectSignature,
521+
invalidateProjectSignature: (dir: string) => {
522+
if (resolve(dir) === resolve(projectDir)) cachedProjectSignature = null;
523+
},
521524

522525
async lint(html: string, opts?: { filePath?: string; isSubComposition?: boolean }) {
523526
const { lintHyperframeHtml } = await import("@hyperframes/lint");

‎packages/studio-server/src/createStudioApi.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,14 @@ export function createStudioApi(adapter: StudioApiAdapter): Hono {
4242
if (c.res.status >= 403 && dirBeforeRoute && folderGone(dirBeforeRoute))
4343
replaceWithProjectDirMissing(c, hostHeaders);
4444
});
45+
api.use("/projects/:id/*", async function forgetSignatureAfterWrite(c, next) {
46+
await next();
47+
if (c.req.method === "GET" || c.req.method === "HEAD") return;
48+
const project = await Promise.resolve()
49+
.then(() => adapter.resolveProject(c.req.param("id")))
50+
.catch(() => null);
51+
if (project) adapter.invalidateProjectSignature?.(project.dir);
52+
});
4553

4654
registerProjectRoutes(api, adapter);
4755
registerFileRoutes(api, adapter);

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
77
import { createStudioApi } from "../createStudioApi";
88
import { DELETED_VERSION, fileContentVersion, identifyFileWrite } from "../helpers/fileVersion";
99
import { openProjectHistory, type ProjectHistory } from "../history/projectHistory";
10+
import { createProjectSignature, resolveProjectSignature } from "../helpers/projectSignature";
1011
import type { StudioApiAdapter } from "../types";
1112

1213
const cleanup: Array<() => unknown> = [];
@@ -103,6 +104,30 @@ describe("history routes", () => {
103104
},
104105
);
105106

107+
it("drop the host's cached signature before an undo answers, so the next preview is the restored build", async () => {
108+
const { projectDir, history } = await demoProject();
109+
let cached: string | null = null;
110+
const adapter = {
111+
listProjects: () => [],
112+
resolveProject: (id: string) => (id === "demo" ? { id, dir: projectDir } : null),
113+
history: () => history,
114+
getProjectSignature: (dir: string) => (cached ??= createProjectSignature(dir)),
115+
invalidateProjectSignature: () => (cached = null),
116+
} as unknown as StudioApiAdapter;
117+
const api = createStudioApi(adapter);
118+
const call = (path: string, body: object) =>
119+
api.request(`/projects/demo/history${path}`, { method: "POST", body: JSON.stringify(body) });
120+
const { windowId } = await (await call("/window", { label: "Retitle" })).json();
121+
writeFileSync(join(projectDir, "index.html"), "Bee");
122+
await call(`/window/${windowId}/close`, {});
123+
// A thumbnail request caches the edited build's signature; the watcher that clears it lags the undo.
124+
const edited = resolveProjectSignature(adapter, projectDir);
125+
126+
expect(await (await call("/step", { direction: "back" })).json()).toMatchObject({ ok: true });
127+
expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toBe("A");
128+
expect(resolveProjectSignature(adapter, projectDir)).not.toBe(edited);
129+
});
130+
106131
it("record a Studio edit window as the person's entry, and step back undoes it", async () => {
107132
const { projectDir, call } = await demoProject();
108133

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,37 @@ describe("registerPreviewRoutes", () => {
435435
expect(html).toContain("Preview");
436436
});
437437

438+
it("does not keep a build under the signature a write replaced while it built", async () => {
439+
const projectDir = createProjectDir();
440+
const file = join(projectDir, "index.html");
441+
const edited = "<html><head></head><body>Edited</body></html>";
442+
writeFileSync(file, edited);
443+
let release = () => {};
444+
let gate: Promise<void> | null = new Promise<void>((resolve) => (release = resolve));
445+
const app = new Hono();
446+
registerPreviewRoutes(
447+
app,
448+
createAdapter(projectDir, {
449+
bundle: async () => {
450+
const wait = gate;
451+
gate = null;
452+
await wait;
453+
return readFileSync(file, "utf-8");
454+
},
455+
}),
456+
);
457+
458+
const inFlight = app.request("http://localhost/projects/demo/preview");
459+
await vi.waitFor(() => expect(gate).toBeNull());
460+
writeFileSync(file, "<html><head></head><body>Undone!</body></html>");
461+
release();
462+
expect(await (await inFlight).text()).toContain("Undone!");
463+
writeFileSync(file, edited);
464+
465+
const redo = await app.request("http://localhost/projects/demo/preview?_t=2");
466+
expect(await redo.text()).toContain("Edited");
467+
});
468+
438469
it("uses the adapter project signature when available", async () => {
439470
const projectDir = createProjectDir();
440471
const getProjectSignature = vi.fn(() => "cached-signature");

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

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { isProjectRootMissing, resolveWithinProject } from "../helpers/safePath.
1818
import { getMimeType } from "../helpers/mime.js";
1919
import { buildSubCompositionHtml, hasBaseElement } from "../helpers/subComposition.js";
2020
import {
21+
createProjectSignature,
2122
resolveProjectAndSignature,
2223
resolveProjectSignature,
2324
} from "../helpers/projectSignature.js";
@@ -372,6 +373,7 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): vo
372373
previewVariables: Record<string, unknown> | null,
373374
builtKey: string,
374375
capture: boolean,
376+
signature: string,
375377
): Promise<string | null> {
376378
const diskMain = resolveProjectMainHtml(project.dir, project.id);
377379
const normalizedDisk = diskMain ? ensureHfIds(diskMain.html) : null;
@@ -426,8 +428,10 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): vo
426428
mediaCodecProbeCache,
427429
);
428430
bundled = addScenePartsManifest(bundled, [`meta[name="${PROJECT_SIGNATURE_META}"]`]);
429-
rememberPreview(builtKey, bundled);
430-
if (!capture) adapter.previewDocuments?.write(builtKey, bundled);
431+
if (createProjectSignature(project.dir) === signature) {
432+
rememberPreview(builtKey, bundled);
433+
if (!capture) adapter.previewDocuments?.write(builtKey, bundled);
434+
}
431435
return bundled;
432436
} catch {
433437
// Re-read disk on bundle failure so we serve the latest file content,
@@ -487,7 +491,7 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): vo
487491
}
488492
let pending = previewBuilds.get(builtKey);
489493
if (!pending) {
490-
pending = buildPreview(project, previewVariables, builtKey, capture).finally(() =>
494+
pending = buildPreview(project, previewVariables, builtKey, capture, signature).finally(() =>
491495
previewBuilds.delete(builtKey),
492496
);
493497
previewBuilds.set(builtKey, pending);

‎packages/studio-server/src/types.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,9 @@ export interface StudioApiAdapter {
120120
options?: Pick<BundleOptions, "stampHfIds" | "onRead">,
121121
): Promise<string | null>;
122122

123-
/** Optional: cached signature for project files that should invalidate preview frame caches. */
123+
/** Optional: a cached `createProjectSignature(dir)`; preview caching checks builds against it. */
124124
getProjectSignature?: (projectDir: string) => string;
125+
invalidateProjectSignature?: (projectDir: string) => void;
125126

126127
/** Lint a single HTML string. */
127128
lint(

‎packages/studio/src/player/sceneSwap.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,27 @@ export function onPreviewContentReplaced(
1717
};
1818
}
1919

20+
export function markScenesStale(iframe: HTMLIFrameElement | null, files: readonly string[]): void {
21+
const doc = iframe?.contentDocument;
22+
const meta = doc?.querySelector<HTMLMetaElement>('meta[name="hf-scene-parts"]');
23+
if (!doc || !meta) return;
24+
let parts: { shared: string; scenes: Record<string, string> };
25+
try {
26+
parts = JSON.parse(meta.content);
27+
} catch {
28+
return;
29+
}
30+
for (const file of files) {
31+
const hosts = doc.querySelectorAll(`[data-composition-file="${CSS.escape(file)}"]`);
32+
if (hosts.length === 0 && file.endsWith(".html")) parts.shared = "";
33+
for (const host of hosts) {
34+
const scene = host.closest("[data-hf-scene]")?.getAttribute("data-hf-scene");
35+
if (scene && scene in parts.scenes) parts.scenes[scene] = "";
36+
}
37+
}
38+
meta.content = JSON.stringify(parts);
39+
}
40+
2041
/** Null when the preview cannot swap; rejects when superseded, cancelled or a full reload is needed. */
2142
export function sceneSwapFor(
2243
iframe: HTMLIFrameElement,

‎packages/studio/src/utils/gsapUndoRestore.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,64 @@ describe("applyUndoRestoreToPreview", () => {
259259
expect(reloadPreview).toHaveBeenCalledTimes(1);
260260
});
261261

262+
it("blanks a restored scene's live hash before reloading, so the scene swap takes it", () => {
263+
const { iframe, doc } = buildLiveIframe(
264+
`<div data-hf-scene="scene0" data-composition-file="scenes/intro.html"><h1>Rep0</h1></div>` +
265+
`<div data-hf-scene="scene1" data-composition-file="scenes/outro.html"></div>`,
266+
);
267+
const meta = doc.createElement("meta");
268+
meta.name = "hf-scene-parts";
269+
meta.content = JSON.stringify({ shared: "s", scenes: { scene0: "h0", scene1: "h1" } });
270+
doc.head.append(meta);
271+
let partsAtReload: unknown;
272+
const reloadPreview = vi.fn(() => (partsAtReload = JSON.parse(meta.content)));
273+
const files = {
274+
"scenes/intro.html": { previous: "<h1>Rep0</h1>", restored: "<h1>Alpha</h1>" },
275+
};
276+
expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("full");
277+
expect(partsAtReload).toEqual({ shared: "s", scenes: { scene0: "", scene1: "h1" } });
278+
279+
const withRoot = {
280+
...files,
281+
[ROOT]: { previous: wrap("<p>b</p>"), restored: wrap("<p>a</p>") },
282+
};
283+
applyUndoRestoreToPreview(iframe, ROOT, withRoot, 3, reloadPreview);
284+
// A restored page outside every scene forces the full reload, never a partial swap.
285+
expect(partsAtReload).toEqual({ shared: "", scenes: { scene0: "", scene1: "h1" } });
286+
});
287+
288+
it("leaves the scene hashes alone on a soft restore, so the next edit can still swap", () => {
289+
const { iframe, doc } = buildLiveIframe(`<div id="a" style="color: red">t</div>`);
290+
const meta = doc.createElement("meta");
291+
meta.name = "hf-scene-parts";
292+
meta.content = JSON.stringify({ shared: "s", scenes: { scene0: "h0" } });
293+
doc.head.append(meta);
294+
const files = {
295+
[ROOT]: {
296+
previous: wrap(`<div id="a" style="color: red">t</div>`),
297+
restored: wrap(`<div id="a" style="color: blue">t</div>`),
298+
},
299+
};
300+
expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, vi.fn())).toBe("soft");
301+
expect(JSON.parse(meta.content)).toEqual({ shared: "s", scenes: { scene0: "h0" } });
302+
});
303+
304+
it.each([
305+
["a restored stylesheet leaves the shared hash", "styles.css", '{"shared":"s","scenes":{}}'],
306+
["an unreadable manifest still reloads", "scenes/intro.html", "not json"],
307+
])("%s", (_name, path, content) => {
308+
const { iframe, doc } = buildLiveIframe(`<div id="a">t</div>`);
309+
const meta = doc.createElement("meta");
310+
meta.name = "hf-scene-parts";
311+
meta.content = content;
312+
doc.head.append(meta);
313+
const reloadPreview = vi.fn();
314+
const files = { [path]: { previous: "a", restored: "b" } };
315+
expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("full");
316+
expect(reloadPreview).toHaveBeenCalledTimes(1);
317+
expect(meta.content).toBe(content);
318+
});
319+
262320
it("full-reloads when the restore touches a sub-comp, not the active comp", () => {
263321
const { iframe } = buildLiveIframe(`<div id="a">t</div>`);
264322
const reloadPreview = vi.fn();

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
extractGsapScriptText,
99
findGsapScriptElements,
1010
} from "./gsapSoftReload";
11+
import { markScenesStale } from "../player/sceneSwap";
1112

1213
type PreviewWindow = Window & {
1314
__player?: { seek?: (t: number) => void };
@@ -184,14 +185,18 @@ export function applyUndoRestoreToPreview(
184185
activeCompPath: string | null,
185186
files: Record<string, UndoRestoreFile> | undefined,
186187
currentTime: number,
187-
reloadPreview: () => void,
188+
reload: () => void,
188189
): "soft" | "full" {
189190
// The master view carries a NULL activeCompPath but the root iframe shows
190191
// index.html — the codebase-wide convention (`activeCompPath || "index.html"`).
191192
// Without this normalization every master-view undo failed the path gate and
192193
// full-reloaded: the original "undo always blinks".
193194
const activeDocPath = activeCompPath ?? "index.html";
194195
const paths = files ? Object.keys(files) : [];
196+
const reloadPreview = () => {
197+
markScenesStale(iframe, paths);
198+
reload();
199+
};
195200
// Soft path only covers the single active-comp document in the root iframe.
196201
if (!iframe || !files || paths.length !== 1 || paths[0] !== activeDocPath) {
197202
reloadPreview();

‎packages/studio/vite.adapter.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ export interface ProjectSignatureCache {
6464
get(projectDir: string): string;
6565
/** Drop the signature of whichever project contains `changedPath`. */
6666
invalidate(changedPath: string): void;
67+
forget(projectDir: string): void;
6768
}
6869

6970
export function createProjectSignatureCache({
@@ -95,6 +96,9 @@ export function createProjectSignatureCache({
9596
if (affectsProjectSignature(projectDir, changedPath)) signatures.delete(projectDir);
9697
}
9798
},
99+
forget(projectDir) {
100+
signatures.delete(resolve(projectDir));
101+
},
98102
};
99103
}
100104

@@ -283,6 +287,10 @@ export function createViteAdapter(
283287
return signatureCache.get(projectDir);
284288
},
285289

290+
invalidateProjectSignature(projectDir: string): void {
291+
signatureCache.forget(projectDir);
292+
},
293+
286294
async lint(html: string, opts?: { filePath?: string; isSubComposition?: boolean }) {
287295
const mod = await server.ssrLoadModule("@hyperframes/core/lint");
288296
return await mod.lintHyperframeHtml(html, { ...opts, host: "studio" });

0 commit comments

Comments
 (0)