Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/studio/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ npx hyperframes preview

Panels can be dragged anywhere; **Window** reopens a closed one or resets the layout.

Select a composition in **Compositions**, then open **Code** to edit its source.
While the source loads, Code shows a loading message. If you select another
composition before it finishes, Code follows your latest selection.

## Edit what you see

Pause where the problem is, click the element (or pick it in **Layers** when things overlap), and change only that.
Expand Down
159 changes: 159 additions & 0 deletions packages/studio/src/hooks/useCompositionContentLoader.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// @vitest-environment happy-dom

import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import { studioApiFetch } from "../utils/studioApiFetch";
import { useCompositionContentLoader } from "./useCompositionContentLoader";

vi.mock("../utils/studioApiFetch", () => ({ studioApiFetch: vi.fn() }));

let root: Root | null = null;

afterEach(() => {
act(() => root?.unmount());
root = null;
vi.resetAllMocks();
vi.unstubAllGlobals();
});

function pendingResponse() {
let resolve: (response: Response) => void = () => {};
let reject: (error: Error) => void = () => {};
const promise = new Promise<Response>((resolveResponse, rejectResponse) => {
resolve = resolveResponse;
reject = rejectResponse;
});
vi.mocked(studioApiFetch).mockReturnValueOnce(promise);
return { resolve, reject };
}

function mountLoader() {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
const setEditingFile = vi.fn();
const setActiveCompPath = vi.fn();
const showToast = vi.fn();
let select: ReturnType<typeof useCompositionContentLoader> | undefined;
function Harness({ projectId }: { projectId: string | null }) {
select = useCompositionContentLoader({
projectId,
setEditingFile,
setActiveCompPath,
showToast,
});
return null;
}
root = createRoot(document.createElement("div"));
const render = (projectId: string | null) => {
act(() => root?.render(<Harness projectId={projectId} />));
};
render("project-a");
return {
setEditingFile,
setActiveCompPath,
showToast,
render,
select(path: string) {
if (!select) throw new Error("Loader did not mount");
act(() => select?.(path));
},
};
}

describe("composition source loading", () => {
it("keeps the latest composition's source when responses arrive in reverse order", async () => {
const first = pendingResponse();
const second = pendingResponse();
const loader = mountLoader();
loader.select("first.html");
loader.select("second.html");
expect(loader.setEditingFile).toHaveBeenLastCalledWith({ path: "second.html", content: null });

await act(async () => second.resolve(Response.json({ content: "SECOND" })));
await act(async () => first.resolve(Response.json({ content: "FIRST" })));

expect(loader.setActiveCompPath).toHaveBeenLastCalledWith("second.html");
expect(loader.setEditingFile).toHaveBeenLastCalledWith({
path: "second.html",
content: "SECOND",
});
});

it("ignores failures from a composition that is no longer selected", async () => {
const first = pendingResponse();
const second = pendingResponse();
const loader = mountLoader();
loader.select("first.html");
loader.select("second.html");
await act(async () => second.resolve(Response.json({ content: "SECOND" })));
await act(async () => first.reject(new Error("first file unavailable")));

expect(loader.showToast).not.toHaveBeenCalled();
});

it("ignores source whose response body finishes after another composition is selected", async () => {
const first = pendingResponse();
const second = pendingResponse();
let resolveBody: (value: { content: string }) => void = () => {};
const body = new Promise<{ content: string }>((resolve) => (resolveBody = resolve));
const firstResponse = Response.json({ content: "FIRST" });
vi.spyOn(firstResponse, "json").mockReturnValue(body);
const loader = mountLoader();
loader.select("first.html");
await act(async () => first.resolve(firstResponse));
loader.select("second.html");
await act(async () => second.resolve(Response.json({ content: "SECOND" })));
await act(async () => resolveBody({ content: "FIRST" }));

expect(loader.setEditingFile).toHaveBeenLastCalledWith({
path: "second.html",
content: "SECOND",
});
});

it("does not accept an old response after leaving and returning to the same project", async () => {
const response = pendingResponse();
const loader = mountLoader();
loader.select("index.html");
loader.render("project-b");
loader.render("project-a");
loader.setEditingFile.mockClear();

await act(async () => response.resolve(Response.json({ content: "OLD PROJECT A" })));

expect(loader.setEditingFile).not.toHaveBeenCalled();
});

it.each(["success", "failure"])("ignores pending %s after unmount", async (outcome) => {
const response = pendingResponse();
const loader = mountLoader();
loader.select("index.html");
act(() => root?.unmount());
root = null;
loader.setEditingFile.mockClear();

await act(async () => {
if (outcome === "success") response.resolve(Response.json({ content: "UNMOUNTED" }));
else response.reject(new Error("request failed"));
});

expect(loader.setEditingFile).not.toHaveBeenCalled();
expect(loader.showToast).not.toHaveBeenCalled();
});

it("reports a current load failure without supplying empty source content", async () => {
const response = pendingResponse();
const loader = mountLoader();
loader.select("index.html");
await act(async () => response.resolve(new Response("unavailable", { status: 500 })));

expect(loader.showToast).toHaveBeenCalledExactlyOnceWith(
"Failed to load index.html (500)",
"error",
);
expect(loader.setEditingFile).toHaveBeenCalledExactlyOnceWith({
path: "index.html",
content: null,
});
});
});
13 changes: 12 additions & 1 deletion packages/studio/src/hooks/useCompositionContentLoader.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { buildProjectApiPath } from "../utils/projectRouting";
import { useCallback } from "react";
import { useCallback, useEffect, useRef } from "react";
import { studioApiFetch } from "../utils/studioApiFetch";

/**
Expand All @@ -20,9 +20,18 @@ export function useCompositionContentLoader({
setActiveCompPath: (path: string | null) => void;
showToast: (message: string, tone?: "error" | "info") => void;
}) {
const loadIdRef = useRef(0);
useEffect(
() => () => {
loadIdRef.current += 1;
},
[projectId],
);

return useCallback(
(comp: string) => {
if (!projectId) return;
const loadId = ++loadIdRef.current;
setActiveCompPath(comp.endsWith(".html") ? comp : null);
setEditingFile({ path: comp, content: null });
studioApiFetch(buildProjectApiPath(projectId, `/files/${encodeURIComponent(comp)}`))
Expand All @@ -31,10 +40,12 @@ export function useCompositionContentLoader({
return r.json();
})
.then((data: { content?: string }) => {
if (loadId !== loadIdRef.current) return;
if (typeof data.content !== "string") throw new Error(`No content returned for ${comp}`);
setEditingFile({ path: comp, content: data.content });
})
.catch((err) => {
if (loadId !== loadIdRef.current) return;
showToast(err instanceof Error ? err.message : `Failed to load ${comp}`, "error");
});
},
Expand Down
Loading