diff --git a/packages/studio/src/main.tsx b/packages/studio/src/main.tsx index 9f46b23fd4..17d97def97 100644 --- a/packages/studio/src/main.tsx +++ b/packages/studio/src/main.tsx @@ -5,8 +5,11 @@ import { StudioApp } from "./App"; import { StudioErrorBoundary } from "./components/StudioErrorBoundary"; import { readIconTokens } from "./styles/iconTokens"; import { trackStudioEvent } from "./utils/studioTelemetry"; +import { prefetchPreviewForHash } from "./utils/previewPrefetch"; import "./styles/studio.css"; +prefetchPreviewForHash(window.location.hash); +window.addEventListener("hashchange", () => prefetchPreviewForHash(window.location.hash)); trackStudioEvent("session_start"); function errorProps(value: unknown): { diff --git a/packages/studio/src/utils/previewPrefetch.test.ts b/packages/studio/src/utils/previewPrefetch.test.ts new file mode 100644 index 0000000000..5698d2ec9d --- /dev/null +++ b/packages/studio/src/utils/previewPrefetch.test.ts @@ -0,0 +1,22 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it, vi } from "vitest"; +import { prefetchPreviewForHash } from "./previewPrefetch"; + +describe("prefetchPreviewForHash", () => { + afterEach(() => vi.unstubAllGlobals()); + + it("requests the opening project's preview once, not on every hash update", () => { + const fetchStub = vi.fn(() => Promise.resolve(new Response(""))); + vi.stubGlobal("fetch", fetchStub); + + prefetchPreviewForHash("#project/demo"); + prefetchPreviewForHash("#project/demo?t=2&tab=design"); + prefetchPreviewForHash("#project/other"); + prefetchPreviewForHash("#settings"); + + expect(fetchStub.mock.calls.map(([url]) => new URL(String(url)).pathname)).toEqual([ + "/api/projects/demo/preview", + "/api/projects/other/preview", + ]); + }); +}); diff --git a/packages/studio/src/utils/previewPrefetch.ts b/packages/studio/src/utils/previewPrefetch.ts new file mode 100644 index 0000000000..09854e4734 --- /dev/null +++ b/packages/studio/src/utils/previewPrefetch.ts @@ -0,0 +1,16 @@ +import { applyPreviewVariablesToUrl } from "../hooks/previewVariablesStore"; +import { buildProjectApiPath, parseProjectIdFromHash } from "./projectRouting"; + +let prefetched: string | null = null; + +/** Asks the server for the preview document of the project in the URL while Studio boots, so + * the build runs in parallel with the app instead of after the player mounts. */ +export function prefetchPreviewForHash(hash: string): void { + const projectId = parseProjectIdFromHash(hash); + if (!projectId || projectId === prefetched) return; + prefetched = projectId; + const url = new URL(buildProjectApiPath(projectId, "/preview"), window.location.origin); + applyPreviewVariablesToUrl(url); + // ponytail: the response is dropped; the server keeps the built document for the player's request. + fetch(url).catch(() => undefined); +}