diff --git a/packages/cli/src/capture/postExtractionPhase.test.ts b/packages/cli/src/capture/postExtractionPhase.test.ts index 24f2de6984..ad36b53a8f 100644 --- a/packages/cli/src/capture/postExtractionPhase.test.ts +++ b/packages/cli/src/capture/postExtractionPhase.test.ts @@ -1,4 +1,12 @@ -import { mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest"; @@ -72,7 +80,10 @@ describe("runPostExtraction", () => { }, ); - async function runWithFonts(read: () => unknown): Promise { + async function runWithFonts( + read: () => unknown, + bodyHtml?: string, + ): Promise<{ outputDir: string }> { const root = mkdtempSync(join(tmpdir(), "hyperframes-post-extraction-")); onTestFinished(() => rmSync(root, { recursive: true, force: true })); const outputDir = join(root, "capture"); @@ -80,6 +91,7 @@ describe("runPostExtraction", () => { mkdirSync(join(outputDir, dir), { recursive: true }); } const state = createPartialCaptureState({ url: "https://example.com", outputDir }); + if (bodyHtml !== undefined) state.extracted.bodyHtml = bodyHtml; fonts.read = read; await runPostExtraction({ state, @@ -102,8 +114,23 @@ describe("runPostExtraction", () => { fontDrops: noDrops(), canWrite: () => true, }); + return { outputDir }; } + // fails without the fix: a captured site that carries the composition marker was saved with it, so Studio listed + // extracted/page.html as a composition and ran its scripts on its own origin + it("saves the captured page without the composition marker", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const { outputDir } = await runWithFonts( + () => ({ files: [], families: [], unidentified: [] }), + `
`, + ); + + const saved = readFileSync(join(outputDir, "extracted", "page.html"), "utf-8"); + expect(saved).toContain(``); + expect(saved).not.toMatch(/data-composition-id/i); + }); + const printed = (spy: { mock: { calls: unknown[][] } }): string => spy.mock.calls.map((call) => call.map(String).join(" ")).join("\n"); diff --git a/packages/cli/src/capture/postExtractionPhase.ts b/packages/cli/src/capture/postExtractionPhase.ts index d5d72162e0..36a9c52c17 100644 --- a/packages/cli/src/capture/postExtractionPhase.ts +++ b/packages/cli/src/capture/postExtractionPhase.ts @@ -87,6 +87,9 @@ export interface PostExtractionResult { animationCatalog: CaptureResult["animationCatalog"]; } +const withoutCompositionMarker = (capturedHtml: string): string => + capturedHtml.replace(/data-composition-id/gi, "data-captured-composition-id"); + export async function runPostExtraction(input: PostExtractionInput): Promise { let { state, @@ -289,7 +292,9 @@ export async function runPostExtraction(input: PostExtractionInput): Promise\n\n\n${extracted.headHtml}\n\n\n${extracted.bodyHtml}\n\n\n`; + const pageHtml = withoutCompositionMarker( + `\n\n\n${extracted.headHtml}\n\n\n${extracted.bodyHtml}\n\n\n`, + ); state.pageHtml = pageHtml; if (canWrite()) writeCaptureFileSync(join(outputDir, "extracted", "page.html"), pageHtml, "utf-8"); diff --git a/packages/cli/src/server/studioServer.staticAssets.test.ts b/packages/cli/src/server/studioServer.staticAssets.test.ts index 6246da826a..a1f1f3286b 100644 --- a/packages/cli/src/server/studioServer.staticAssets.test.ts +++ b/packages/cli/src/server/studioServer.staticAssets.test.ts @@ -125,7 +125,10 @@ describe("a project page opened by direct navigation", () => { it("is answered sandboxed by this server", async () => { const project = path.join(root, "project"); fs.writeFileSync(path.join(project, "index.html"), '
'); - fs.writeFileSync(path.join(project, "page.html"), ""); + fs.writeFileSync( + path.join(project, "page.html"), + '
', + ); const id = encodeURIComponent(path.basename(project)); for (const file of ["page.html", "comp/page.html"]) { const response = await server.app.request(`/api/projects/${id}/preview/${file}`, { diff --git a/packages/studio-server/src/helpers/hfIdPersist.ts b/packages/studio-server/src/helpers/hfIdPersist.ts index 6c80e32078..65c5866e17 100644 --- a/packages/studio-server/src/helpers/hfIdPersist.ts +++ b/packages/studio-server/src/helpers/hfIdPersist.ts @@ -7,6 +7,9 @@ import { isInHiddenOrVendorDir, mkdirOwnedWithinProject, walkDir } from "./safeP export const isCompositionSource = (html: string): boolean => /data-composition-id\s*=/.test(html); +export const isCompositionPath = (relPath: string): boolean => + /\.html?$/i.test(relPath) && !isInHiddenOrVendorDir(relPath); + const STAMP_RECORD = join(".hyperframes", "hf-ids-stamped.json"); const contentHash = (text: string): string => createHash("sha1").update(text).digest("base64url"); diff --git a/packages/studio-server/src/helpers/subComposition.test.ts b/packages/studio-server/src/helpers/subComposition.test.ts index df056a2c6a..706f89ed44 100644 --- a/packages/studio-server/src/helpers/subComposition.test.ts +++ b/packages/studio-server/src/helpers/subComposition.test.ts @@ -58,7 +58,8 @@ describe("buildSubCompositionHtml", () => { '', }); const dir = makeTempProject({ - "scenes/scene.html": '', + "scenes/scene.html": + '', }); symlinkSync(join(outside, "index.html"), join(dir, "index.html")); const html = buildSubCompositionHtml(dir, "scenes/scene.html", "/runtime.js"); @@ -570,7 +571,7 @@ describe("buildSubCompositionHtml", () => { -
+
`, }); diff --git a/packages/studio-server/src/helpers/subComposition.ts b/packages/studio-server/src/helpers/subComposition.ts index 2964039257..00a37dac6c 100644 --- a/packages/studio-server/src/helpers/subComposition.ts +++ b/packages/studio-server/src/helpers/subComposition.ts @@ -23,6 +23,7 @@ import { import { TIMELINE_REGISTRY_SCRIPT } from "./authoredCode.js"; import { htmlHasGsapCore, insertGsapCoreBeforeHeadPlugin } from "./gsapCoreScript.js"; import { withRootPathsRelative } from "./rootPaths.js"; +import { isCompositionPath, isCompositionSource } from "./hfIdPersist.js"; /** * Rewrite relative asset paths in a parsed DOM tree. Shared across all @@ -323,6 +324,7 @@ export function buildSubCompositionHtml( rawOverride?: string, gsapBaseUrl?: string, ): string | null { + if (!isCompositionPath(compPath)) return null; const compFile = resolveWithinProject(projectDir, compPath); if (!compFile || !existsSync(compFile)) return null; @@ -330,6 +332,7 @@ export function buildSubCompositionHtml( // directly, so the build uses ids minted from the raw file, which is never // written by serving. const rawComp = rawOverride ?? readFileSync(compFile, "utf-8"); + if (!isCompositionSource(rawComp)) return null; let compHeadContent = ""; let rewrittenContent: string; diff --git a/packages/studio-server/src/routes/preview.compositionsOnly.test.ts b/packages/studio-server/src/routes/preview.compositionsOnly.test.ts new file mode 100644 index 0000000000..02865ab3be --- /dev/null +++ b/packages/studio-server/src/routes/preview.compositionsOnly.test.ts @@ -0,0 +1,77 @@ +// @vitest-environment node +import { afterAll, describe, expect, it } from "vitest"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createStudioApi } from "../createStudioApi"; +import type { StudioApiAdapter } from "../types"; + +const SCRIPT = ``; +const projectDir = mkdtempSync(join(tmpdir(), "hf-preview-compositions-only-")); +for (const dir of ["scenes", "extracted", ".hyperframes"]) mkdirSync(join(projectDir, dir)); +writeFileSync(join(projectDir, "index.html"), '
'); +writeFileSync(join(projectDir, "scenes", "intro.html"), '
'); +writeFileSync(join(projectDir, "scenes", "outro.htm"), '
'); +writeFileSync(join(projectDir, "extracted", "page.html"), `${SCRIPT}`); +writeFileSync(join(projectDir, "extracted", "visible-text.txt"), SCRIPT); +writeFileSync(join(projectDir, "data.json"), JSON.stringify({ html: SCRIPT })); +writeFileSync(join(projectDir, "subs.vtt"), `WEBVTT\n\n00:00.000 --> 00:01.000\n${SCRIPT}`); +writeFileSync(join(projectDir, "clip.mp4"), `
${SCRIPT}
`); +writeFileSync( + join(projectDir, ".hyperframes", "preset.html"), + `
${SCRIPT}
`, +); +afterAll(() => rmSync(projectDir, { recursive: true, force: true })); + +const adapter: StudioApiAdapter = { + listProjects: () => [], + resolveProject: async (id: string) => ({ id, dir: projectDir }), + bundle: async () => null, + lint: async () => ({ findings: [] }), + runtimeUrl: "/api/runtime.js", + rendersDir: () => join(projectDir, "renders"), + startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/out.mp4" }), +}; +const api = createStudioApi(adapter); + +const comp = (path: string, site?: string) => + api.request(`http://localhost/projects/demo/preview/comp/${path}`, { + headers: site === undefined ? {} : { "sec-fetch-site": site }, + }); + +// fails without the fix: the comp route built a page from any project file, so its scripts ran on Studio's origin +describe("the sub-composition preview", () => { + const notCompositions = [ + "extracted/page.html", + "extracted/visible-text.txt", + "data.json", + "subs.vtt", + "clip.mp4", + ".hyperframes/preset.html", + ]; + const sites = [undefined, "same-origin", "none", "cross-site"]; + + it.each(notCompositions)("answers no page for %s, however the request is made", async (path) => { + for (const site of sites) { + const res = await comp(path, site); + expect(res.status).toBe(404); + expect(res.headers.get("content-type") ?? "").not.toContain("text/html"); + expect(await res.text()).not.toContain("fetch("); + } + }); + + it.each(["scenes/intro.html", "scenes/outro.htm"])("still builds %s", async (path) => { + const res = await comp(path, "same-origin"); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toContain("text/html"); + }); + + it("answers only for what the project listing reports as compositions", async () => { + const listing = await (await api.request("http://localhost/projects/demo")).json(); + expect([...listing.compositions].sort()).toEqual([ + "index.html", + "scenes/intro.html", + "scenes/outro.htm", + ]); + }); +}); diff --git a/packages/studio-server/src/routes/preview.opaqueFrameLoads.test.ts b/packages/studio-server/src/routes/preview.opaqueFrameLoads.test.ts index d462b095a6..3d8fe18aad 100644 --- a/packages/studio-server/src/routes/preview.opaqueFrameLoads.test.ts +++ b/packages/studio-server/src/routes/preview.opaqueFrameLoads.test.ts @@ -160,16 +160,12 @@ describe("an opaque preview frame's loads under its token", () => { ["video", "music.mp3"], ["video", "logo.png"], ["audio", "clip.mp4"], - ["audio", "comp/music.mp3"], ["font", "data.json"], ["font", "scene.js"], ["script", "data.json"], ["script", "fonts/Brand.woff2"], ["script", "scene.html"], ["script", "comp/scene.html"], - // The sub-composition route answers any project file with an HTML page. - ["script", "comp/scene.js"], - ["font", "comp/fonts/Brand.woff2"], ["toString", "scene.js"], ["constructor", "fonts/Brand.woff2"], ])("refuses a %s load of %s", async (dest, path) => { @@ -178,6 +174,17 @@ describe("an opaque preview frame's loads under its token", () => { expectNotGranted(res); }); + // The sub-composition route answers only for compositions, so these never reach a page or a grant. + it.each([ + ["audio", "comp/music.mp3"], + ["script", "comp/scene.js"], + ["font", "comp/fonts/Brand.woff2"], + ])("refuses a %s load of %s with no page", async (dest, path) => { + const res = await load(path, { origin: "null", "sec-fetch-dest": dest }); + expect(res.status).toBe(404); + expectNotGranted(res); + }); + it("refuses a load that names no Sec-Fetch-Dest", async () => { expectNotGranted(await load("fonts/Brand.woff2", { origin: "null" })); }); diff --git a/packages/studio-server/src/routes/preview.sandbox.test.ts b/packages/studio-server/src/routes/preview.sandbox.test.ts index 593ec509ac..01544236af 100644 --- a/packages/studio-server/src/routes/preview.sandbox.test.ts +++ b/packages/studio-server/src/routes/preview.sandbox.test.ts @@ -11,14 +11,17 @@ writeFileSync( join(projectDir, "index.html"), '
', ); -writeFileSync(join(projectDir, "page.html"), ""); +writeFileSync( + join(projectDir, "page.html"), + `
`, +); writeFileSync( join(projectDir, "icon.svg"), '', ); writeFileSync( join(projectDir, "clip.html"), - '', + '
', ); afterAll(() => rmSync(projectDir, { recursive: true, force: true })); diff --git a/packages/studio-server/src/routes/preview.serviceWorker.test.ts b/packages/studio-server/src/routes/preview.serviceWorker.test.ts index d6e394fa69..e267d604f5 100644 --- a/packages/studio-server/src/routes/preview.serviceWorker.test.ts +++ b/packages/studio-server/src/routes/preview.serviceWorker.test.ts @@ -36,11 +36,15 @@ describe("a project file asked for as a service worker's script", () => { for (const headers of workerFetches) expect((await get(path, headers)).status).toBe(403); }); - it.each(paths)("still loads at %s as a page script, module or dedicated worker", async (path) => { - for (const dest of ["script", "worker", "empty"]) { - const res = await get(path, { "sec-fetch-dest": dest }); - expect(res.status).toBe(200); - expect(await res.text()).toContain("onfetch"); - } - }); + // Only the asset route: the sub-composition route builds pages from compositions, and answers nothing for a script. + it.each(paths.slice(0, 1))( + "still loads at %s as a page script, module or dedicated worker", + async (path) => { + for (const dest of ["script", "worker", "empty"]) { + const res = await get(path, { "sec-fetch-dest": dest }); + expect(res.status).toBe(200); + expect(await res.text()).toContain("onfetch"); + } + }, + ); }); diff --git a/packages/studio-server/src/routes/preview.test.ts b/packages/studio-server/src/routes/preview.test.ts index 65a3bf69c3..b43e742921 100644 --- a/packages/studio-server/src/routes/preview.test.ts +++ b/packages/studio-server/src/routes/preview.test.ts @@ -227,7 +227,10 @@ describe("registerPreviewRoutes", () => { it("encodes the project name in , so a '#' or '\"' in it keeps assets in its own folder", async () => { const projectDir = createProjectDir(); - writeFileSync(join(projectDir, "scene.html"), ""); + writeFileSync( + join(projectDir, "scene.html"), + '', + ); const app = new Hono(); registerPreviewRoutes(app, createAdapter(projectDir)); const baseOf = async (path: string) => @@ -495,7 +498,7 @@ describe("registerPreviewRoutes", () => { it("serves a later scene's image lazy, and captures every image eager under a capture-mode mark", async () => { const projectDir = createProjectDir(); const later = - '
'; + '
'; writeFileSync(join(projectDir, "index.html"), later); writeFileSync(join(projectDir, "scene.html"), later); const app = new Hono(); @@ -1374,7 +1377,7 @@ describe("hf-id surfacing in preview route", () => { ); writeFileSync( files[1]!, - `
`, + `
`, ); const snapshot = () => files.map((f) => [readFileSync(f, "utf-8"), statSync(f).mtimeMs]); const before = snapshot(); @@ -1393,7 +1396,7 @@ describe("hf-id surfacing in preview route", () => { const compPath = join(projectDir, "scene.html"); writeFileSync( compPath, - `
`, + `
`, ); const app = new Hono(); const adapter = createAdapter(projectDir); @@ -1476,8 +1479,14 @@ describe("hf-id surfacing in preview route", () => { it("returns ByteString-safe stable and distinct ETags for percent-encoded CJK sub-comp paths", async () => { const projectDir = createProjectDir(); mkdirSync(join(projectDir, "compositions")); - writeFileSync(join(projectDir, "compositions/測試.html"), "
First
"); - writeFileSync(join(projectDir, "compositions/別頁.html"), "
Second
"); + writeFileSync( + join(projectDir, "compositions/測試.html"), + '
First
', + ); + writeFileSync( + join(projectDir, "compositions/別頁.html"), + '
Second
', + ); const app = new Hono(); registerPreviewRoutes( app, @@ -1505,7 +1514,7 @@ describe("hf-id surfacing in preview route", () => { it("sub-comp served ids equal the source's ids even when relative asset paths are rewritten", async () => { // Guards setTiming element_not_found: minting after the route rewrites src gives ids the source lacks. const projectDir = createProjectDir(); - const raw = `
`; + const raw = `
`; writeFileSync(join(projectDir, "scene.html"), raw); const app = new Hono(); registerPreviewRoutes(app, createAdapter(projectDir)); @@ -1688,7 +1697,7 @@ describe("preview ?variables= injection", () => { const projectDir = createProjectDir(); writeFileSync( join(projectDir, "scene.html"), - "
Scene
", + "
Scene
", ); const app = new Hono(); registerPreviewRoutes(app, createAdapter(projectDir)); @@ -1710,7 +1719,7 @@ describe("sub-composition preview attribute integrity", () => { ]); writeFileSync( join(projectDir, "card.html"), - `
x
`, + `
x
`, ); const app = new Hono(); registerPreviewRoutes(app, createAdapter(projectDir)); @@ -3354,7 +3363,7 @@ describe("GSAP mirror configuration", () => { async (mode) => { const projectDir = createProjectDir(); const authored = "https://authored.example/gsap@3.14.2/dist/gsap.min.js"; - const source = ``; + const source = `
`; writeFileSync(join(projectDir, "index.html"), source); writeFileSync(join(projectDir, "scene.html"), source); const app = appForMirror(projectDir, mirror, { @@ -3398,7 +3407,10 @@ describe("GSAP mirror configuration", () => { ], }), ); - writeFileSync(join(projectDir, "scene.html"), ""); + writeFileSync( + join(projectDir, "scene.html"), + '', + ); const app = appForMirror(projectDir, mirror); const root = parseHTML(await (await app.request(previewUrl)).text()).document; const urls = [...root.querySelectorAll("script[src]")].map((script) => @@ -3420,7 +3432,7 @@ describe("GSAP mirror configuration", () => { "revalidates %s when the mirror setting changes", async (suffix) => { const projectDir = createProjectDir(); - const source = ``; + const source = `
`; writeFileSync(join(projectDir, "index.html"), source); writeFileSync(join(projectDir, "scene.html"), source); const url = previewUrl + suffix; @@ -3443,7 +3455,7 @@ describe("GSAP mirror configuration", () => { const plugin = "https://authored.example/MotionPathPlugin.min.js"; writeFileSync( join(projectDir, "index.html"), - ``, + `
`, ); const configured = await (await appForMirror(projectDir, mirror).request(previewUrl)).text(); expect( @@ -3471,7 +3483,10 @@ describe("GSAP mirror configuration", () => { it("invalidates root, subcomposition, and persistent preview caches when the mirror changes", async () => { const projectDir = createProjectDir(); - writeFileSync(join(projectDir, "scene.html"), ""); + writeFileSync( + join(projectDir, "scene.html"), + '', + ); const bundle = vi.fn( async () => '
Cached preview
', @@ -3580,7 +3595,10 @@ describe("bundled GSAP local root", () => { ], }), ); - writeFileSync(join(projectDir, "scene.html"), ""); + writeFileSync( + join(projectDir, "scene.html"), + '', + ); } it("loads every GSAP dependency Studio adds from the host's bundled copy", async () => { @@ -3604,7 +3622,7 @@ describe("bundled GSAP local root", () => { writeFileSync( join(projectDir, "index.html"), - ``, + `
`, ); const withPath = await (await app.request(previewUrl)).text(); expect( @@ -3620,7 +3638,7 @@ describe("bundled GSAP local root", () => { const projectDir = createProjectDir(); writeFileSync( join(projectDir, "index.html"), - ``, + `
`, ); const html = await (await appForHost(projectDir).request(previewUrl)).text(); expect( diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.ts index d65754bfd6..906b5af0d5 100644 --- a/packages/studio-server/src/routes/preview.ts +++ b/packages/studio-server/src/routes/preview.ts @@ -68,6 +68,7 @@ import { getMimeType } from "../helpers/mime.js"; import { serveWhileOpen } from "../helpers/servedFiles.js"; import { openRangeEnd } from "../helpers/mediaRange.js"; import { hasBaseElement } from "../helpers/subComposition.js"; +import { isCompositionPath } from "../helpers/hfIdPersist.js"; import { runOffThread, ROOT_PREVIEW_DEADLINE_MS, @@ -886,6 +887,7 @@ export function registerPreviewRoutes( return c.text("not found", 404); } const compPath = projectRelativePath(project.dir, compFile); + if (!isCompositionPath(compPath)) return c.text("not found", 404); // "v2" salts the etag for the hf-id-pinning change below: a client holding // a pre-pin cached response (preview-only ids, unstamped disk file) must diff --git a/packages/studio-server/src/routes/projectIdEncoding.test.ts b/packages/studio-server/src/routes/projectIdEncoding.test.ts index 64fdfac920..87527af0ef 100644 --- a/packages/studio-server/src/routes/projectIdEncoding.test.ts +++ b/packages/studio-server/src/routes/projectIdEncoding.test.ts @@ -32,7 +32,10 @@ function projectWithComposition(): { dir: string; cleanup: () => void } { const dir = mkdtempSync(join(tmpdir(), "hf-projectid-")); writeFileSync(join(dir, "index.html"), "COMPOSITION"); mkdirSync(join(dir, "scenes"), { recursive: true }); - writeFileSync(join(dir, "scenes", "scene-1.html"), "SCENE ONE"); + writeFileSync( + join(dir, "scenes", "scene-1.html"), + '
SCENE ONE
', + ); return { dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) }; } diff --git a/packages/studio-server/src/routes/projects.ts b/packages/studio-server/src/routes/projects.ts index 291c1e2b95..d26ccd3340 100644 --- a/packages/studio-server/src/routes/projects.ts +++ b/packages/studio-server/src/routes/projects.ts @@ -2,12 +2,12 @@ import { readFile } from "node:fs/promises"; import { join } from "node:path"; import type { Hono } from "hono"; import type { StudioApiAdapter } from "../types.js"; -import { isInHiddenOrVendorDir, isPrivateProjectPath, walkDir } from "../helpers/safePath.js"; -import { isCompositionSource } from "../helpers/hfIdPersist.js"; +import { isPrivateProjectPath, walkDir } from "../helpers/safePath.js"; +import { isCompositionPath, isCompositionSource } from "../helpers/hfIdPersist.js"; import { resolveProjectSignature } from "../helpers/projectSignature.js"; async function filterCompositionFiles(projectDir: string, files: string[]): Promise { - const htmlFiles = files.filter((f) => f.endsWith(".html") && !isInHiddenOrVendorDir(f)); + const htmlFiles = files.filter(isCompositionPath); const checks = await Promise.all( htmlFiles.map(async (f) => { try { diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx index 64262873d4..76194eaa13 100644 --- a/packages/studio/src/App.tsx +++ b/packages/studio/src/App.tsx @@ -123,7 +123,7 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: St useActiveComposition({ projectId, initialUrlStateRef, - fileTree: fileManager.fileTree, + compositions: fileManager.compositions, fileTreeLoaded: fileManager.fileTreeLoaded, masterCompPath, setEditingFile: fileManager.setEditingFile, diff --git a/packages/studio/src/hooks/useActiveComposition.ts b/packages/studio/src/hooks/useActiveComposition.ts index da3d64d622..e071458fad 100644 --- a/packages/studio/src/hooks/useActiveComposition.ts +++ b/packages/studio/src/hooks/useActiveComposition.ts @@ -10,7 +10,7 @@ import type { AppToast, EditingFile } from "../utils/studioHelpers"; export function useActiveComposition({ projectId, initialUrlStateRef, - fileTree, + compositions, fileTreeLoaded, masterCompPath, setEditingFile, @@ -18,7 +18,7 @@ export function useActiveComposition({ }: { projectId: string | null; initialUrlStateRef: MutableRefObject; - fileTree: string[]; + compositions: string[]; fileTreeLoaded: boolean; masterCompPath: string | null; setEditingFile: (file: EditingFile) => void; @@ -44,7 +44,7 @@ export function useActiveComposition({ useHydrateActiveCompPathFromUrl({ hydrated: activeCompPathHydrated, fileTreeLoaded, - fileTree, + compositions, initialUrlStateRef, setActiveCompPath, setHydrated: setActiveCompPathHydrated, diff --git a/packages/studio/src/hooks/useHydrateActiveCompPathFromUrl.ts b/packages/studio/src/hooks/useHydrateActiveCompPathFromUrl.ts index f52963dcdd..e9a60e6204 100644 --- a/packages/studio/src/hooks/useHydrateActiveCompPathFromUrl.ts +++ b/packages/studio/src/hooks/useHydrateActiveCompPathFromUrl.ts @@ -4,21 +4,21 @@ import { normalizeStudioCompositionPath, type StudioUrlState } from "../utils/st /** * One-time hydration of `activeCompPath` from the initial URL state, once the - * file tree has loaded (a path that isn't in the tree yet can't be - * validated). Runs exactly once — `hydrated` flips true whether or not the + * file tree has loaded (a path that isn't in the server's compositions yet can't + * be validated). Runs exactly once — `hydrated` flips true whether or not the * URL named a valid path, so a later file-tree change never re-fires it. */ export function useHydrateActiveCompPathFromUrl({ hydrated, fileTreeLoaded, - fileTree, + compositions, initialUrlStateRef, setActiveCompPath, setHydrated, }: { hydrated: boolean; fileTreeLoaded: boolean; - fileTree: string[]; + compositions: string[]; initialUrlStateRef: MutableRefObject; setActiveCompPath: (updater: (current: string | null) => string | null) => void; setHydrated: (value: boolean) => void; @@ -28,9 +28,9 @@ export function useHydrateActiveCompPathFromUrl({ if (!fileTreeLoaded) return; const nextCompPath = normalizeStudioCompositionPath( initialUrlStateRef.current.activeCompPath, - fileTree, + compositions, ); setActiveCompPath((current) => (current === nextCompPath ? current : nextCompPath)); setHydrated(true); - }, [hydrated, fileTree, fileTreeLoaded, initialUrlStateRef, setActiveCompPath, setHydrated]); + }, [hydrated, compositions, fileTreeLoaded, initialUrlStateRef, setActiveCompPath, setHydrated]); } diff --git a/packages/studio/src/hooks/useResetSelectionOnProjectSwitch.test.tsx b/packages/studio/src/hooks/useResetSelectionOnProjectSwitch.test.tsx index 2649039dcb..7732cc1d73 100644 --- a/packages/studio/src/hooks/useResetSelectionOnProjectSwitch.test.tsx +++ b/packages/studio/src/hooks/useResetSelectionOnProjectSwitch.test.tsx @@ -170,7 +170,7 @@ describe("full stack: useFileTree -> useActiveComposition (masterCompPath stalen const initialUrlStateRef = useRef(readStudioUrlStateFromWindow()); const projectIdRef = useRef(projectId); projectIdRef.current = projectId; - const { fileTree, fileTreeLoaded, compositions } = useFileTree({ projectId, projectIdRef }); + const { fileTreeLoaded, compositions } = useFileTree({ projectId, projectIdRef }); const masterCompPath = useMemo( () => resolveMasterCompositionPath(compositions), [compositions], @@ -178,7 +178,7 @@ describe("full stack: useFileTree -> useActiveComposition (masterCompPath stalen const { activeCompPath } = useActiveComposition({ projectId, initialUrlStateRef, - fileTree, + compositions, fileTreeLoaded, masterCompPath, setEditingFile: vi.fn(), @@ -231,4 +231,29 @@ describe("full stack: useFileTree -> useActiveComposition (masterCompPath stalen fetchSpy.mockRestore(); }); + + // fails without the fix: a link from any site picked which project file the same-origin player frame loads + it.each([ + ["extracted/page.html", "index.html"], + ["scenes/intro.html", "scenes/intro.html"], + ])("opens the URL's comp %s as %s", async (comp, opened) => { + PROJECT_DATA["project-d"] = { + files: ["index.html", "extracted/page.html", "scenes/intro.html"], + compositions: ["index.html", "scenes/intro.html"], + }; + window.location.hash = `#project/project-d?comp=${encodeURIComponent(comp)}`; + const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(mockFetch as typeof fetch); + const host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); + + await act(async () => { + root?.render(); + await Promise.resolve(); + await Promise.resolve(); + }); + expect((host.firstElementChild as HTMLElement).dataset.activeCompPath).toBe(opened); + + fetchSpy.mockRestore(); + }); }); diff --git a/packages/studio/src/utils/studioUrlState.ts b/packages/studio/src/utils/studioUrlState.ts index e4b5b3ab6e..a991aa8ecf 100644 --- a/packages/studio/src/utils/studioUrlState.ts +++ b/packages/studio/src/utils/studioUrlState.ts @@ -66,10 +66,10 @@ export function normalizeStudioUrlPanelTab(tab: RightPanelTab | null): RightPane export function normalizeStudioCompositionPath( activeCompPath: string | null, - fileTree: string[], + compositions: string[], ): string | null { if (!activeCompPath || activeCompPath === "index.html") return null; - return fileTree.includes(activeCompPath) ? activeCompPath : null; + return compositions.includes(activeCompPath) ? activeCompPath : null; } function parseBoolean(value: string | null): boolean | null {