From 5f024e34e2be4e1ee232ee3361aca6470611ca95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Fri, 20 Nov 2026 21:19:26 +0000 Subject: [PATCH] fix(studio): thumbnails of compositions with no code of their own load in under a second (#8316) * fix(studio): thumbnails of compositions with no code of their own load in under a second Both thumbnail paths (the CLI's preview server and Studio's dev server) waited up to 5 s for a GSAP timeline before shooting a card. A composition with no script never registers one, so each of its cards took the full 5 s, and the route shoots one card at a time, so the third card came at about 16 s. The wait cannot simply go: a composition may register its timeline late, in a timer or a load handler, after the runtime is ready, and shooting it then shows the wrong moment. So the preview route now marks the page a thumbnail loads when nothing on it can register a timeline: no script but Studio's own (the runtime, GSAP core, an import map, the registry line), no inline event handler, frame, template or child composition loaded at run time, and no Studio motion. A marked page is shot once the runtime is ready. Every other page is held for its timeline exactly as before. The rule lives once, in studio-server, and both thumbnail paths wait on it. fails without the fix: "is skipped for a composition with no code of its own" and "holds for a composition whose script registers its timeline late" (packages/studio-server/src/routes/preview.thumbnailMark.test.ts), "thumbnailSeekReadyInBrowser" (packages/studio-server/src/helpers/screenshotClip.test.ts), "hasAuthoredCode" (packages/studio-server/src/helpers/authoredCode.test.ts), and "holds a thumbnail's shot on the thumbnail readiness rule" (packages/cli/src/server/studioServer.test.ts and packages/studio/vite.browser.test.ts). * test(studio-server): the thumbnail mark test builds its page from elements, not parsed text The test read the served page back through DOMParser and innerHTML to hand its metas to the readiness rule, which code scanning reports as DOM text reinterpreted as HTML. It now finds the served page's meta tags with the compiler's own tag scanner and creates each one as an element, so no text is parsed as markup. Also adds a row to the code check's table: a script inside an inline SVG counts as code. fails without the fix: "is skipped for a composition with no code of its own" (packages/studio-server/src/routes/preview.thumbnailMark.test.ts) still fails when the route writes no mark. --- packages/cli/src/server/studioServer.test.ts | 20 +++- packages/cli/src/server/studioServer.ts | 13 +-- .../src/helpers/authoredCode.test.ts | 45 +++++++++ .../studio-server/src/helpers/authoredCode.ts | 25 +++++ .../src/helpers/rootImportMap.ts | 2 +- .../src/helpers/screenshotClip.test.ts | 36 ++++++- .../src/helpers/screenshotClip.ts | 14 +++ .../src/helpers/subComposition.ts | 3 +- packages/studio-server/src/index.ts | 1 + .../src/routes/preview.thumbnailMark.test.ts | 96 +++++++++++++++++++ packages/studio-server/src/routes/preview.ts | 10 +- packages/studio/vite.browser.test.ts | 11 +++ packages/studio/vite.browser.ts | 7 +- 13 files changed, 261 insertions(+), 22 deletions(-) create mode 100644 packages/studio-server/src/helpers/authoredCode.test.ts create mode 100644 packages/studio-server/src/helpers/authoredCode.ts create mode 100644 packages/studio-server/src/routes/preview.thumbnailMark.test.ts diff --git a/packages/cli/src/server/studioServer.test.ts b/packages/cli/src/server/studioServer.test.ts index 57d0c1f3e7..3aee6b9128 100644 --- a/packages/cli/src/server/studioServer.test.ts +++ b/packages/cli/src/server/studioServer.test.ts @@ -23,6 +23,7 @@ import { HistoryBusyError, HistoryClosedError, } from "@hyperframes/studio-server"; +import { thumbnailSeekReadyInBrowser } from "@hyperframes/studio-server/screenshot-clip"; import { loadHyperframeRuntimeSource } from "@hyperframes/core"; import { loadRuntimeSource } from "./runtimeSource.js"; import { findFFmpeg, findFFprobe } from "../browser/ffmpeg.js"; @@ -719,11 +720,14 @@ describe("Studio thumbnail capture", () => { afterEach(async () => { await server?.shutdown(); }); - function fakePageBrowser(onEvaluate = () => {}) { + function fakePageBrowser( + onEvaluate = () => {}, + waitForFunction = async (_ready: () => boolean) => {}, + ) { const screenshot = vi.fn(async () => Buffer.from("jpeg")); const evaluate = vi.fn(async () => onEvaluate()); const page = new Proxy( - { screenshot, evaluate }, + { screenshot, evaluate, waitForFunction }, { get: (target, key) => key === "then" @@ -751,6 +755,18 @@ describe("Studio thumbnail capture", () => { signal, }); + it("holds a thumbnail's shot on the thumbnail readiness rule", async () => { + const waits: unknown[] = []; + const { screenshot } = fakePageBrowser(undefined, async (ready) => { + expect(screenshot).not.toHaveBeenCalled(); + waits.push(ready); + }); + const dir = tmpProject(); + server = createStudioServer({ projectDir: dir }); + await expect(server.adapter.generateThumbnail?.(opts(dir))).resolves.toBeInstanceOf(Buffer); + expect(waits[0]).toBe(thumbnailSeekReadyInBrowser); + }); + it("stops a thumbnail whose request is aborted before its screenshot", async () => { let abortOnEvaluate: AbortController | undefined; const { screenshot } = fakePageBrowser(() => abortOnEvaluate?.abort()); diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts index e173f8f739..73555f0f2a 100644 --- a/packages/cli/src/server/studioServer.ts +++ b/packages/cli/src/server/studioServer.ts @@ -97,8 +97,9 @@ import { resolveAutoProxy } from "../utils/projectConfig.js"; import { clearElementScreenshotIsolation, getElementScreenshotClip, + type ScreenshotClip, + thumbnailSeekReadyInBrowser, } from "@hyperframes/studio-server/screenshot-clip"; -import type { ScreenshotClip } from "@hyperframes/studio-server/screenshot-clip"; import type { RenderJob } from "@hyperframes/producer"; import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution"; import { seekCompositionTimeline } from "../capture/captureCompositionFrame.js"; @@ -890,15 +891,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { requiresWebGpu && session.softwareWebGpu, ); await page - .waitForFunction( - () => { - const w = window as Window & { - __timelines?: Record; - }; - return !!(w.__timelines && Object.keys(w.__timelines).length > 0); - }, - { timeout: 5000 }, - ) + .waitForFunction(thumbnailSeekReadyInBrowser, { timeout: 5000 }) .catch(() => {}); }, async (page) => { diff --git a/packages/studio-server/src/helpers/authoredCode.test.ts b/packages/studio-server/src/helpers/authoredCode.test.ts new file mode 100644 index 0000000000..299327d6ec --- /dev/null +++ b/packages/studio-server/src/helpers/authoredCode.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from "vitest"; +import { hasAuthoredCode, TIMELINE_REGISTRY_SCRIPT } from "./authoredCode"; + +const page = (head: string, body: string) => + `${head}${body}`; +const runtime = ''; +const gsap = ''; +const still = '

Hi

'; + +describe("hasAuthoredCode", () => { + it.each([ + ["a still or CSS-animated composition", page("", still)], + [ + "Studio's runtime, GSAP core and registry line", + page(runtime + gsap, TIMELINE_REGISTRY_SCRIPT + still), + ], + ["an import map", page('', still)], + ])("finds none in %s", (_name, html) => { + expect(hasAuthoredCode(html)).toBe(false); + }); + + it.each([ + ["an inline script", page("", `${still}`)], + ["an upper-case script tag", page("", `${still}`)], + ["a script inside an inline SVG", page("", `${still}`)], + [ + "a script held until fonts load", + page("", `${still}`), + ], + ["a script file of the project", page('', still)], + [ + "a GSAP plugin file", + page('', still), + ], + ["an inline event handler", page("", `${still}`)], + ["a frame", page("", `${still}`)], + ["a template", page("", `${still}`)], + [ + "a child composition loaded at run time", + page("", '
'), + ], + ])("finds %s", (_name, html) => { + expect(hasAuthoredCode(html)).toBe(true); + }); +}); diff --git a/packages/studio-server/src/helpers/authoredCode.ts b/packages/studio-server/src/helpers/authoredCode.ts new file mode 100644 index 0000000000..8278938f86 --- /dev/null +++ b/packages/studio-server/src/helpers/authoredCode.ts @@ -0,0 +1,25 @@ +import { RUNTIME_BOOTSTRAP_ATTR } from "@hyperframes/core/compiler"; +import { findStartTags } from "@hyperframes/core/compiler/html-document"; +import { isGsapCoreUrl } from "./gsapCoreScript.js"; +import { IMPORT_MAP_TYPE } from "./rootImportMap.js"; + +export const TIMELINE_REGISTRY_SCRIPT = + ""; + +const HANDLER_FRAME_TEMPLATE_OR_CHILD_COMPOSITION = + /\son[a-z]+\s*=|<(iframe|frame|object|embed|template)\b|\sdata-composition-src\s*=/i; +const SCRIPT_SRC = /\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i; + +function isStudioOwnScript(html: string, start: number): boolean { + if (html.startsWith(TIMELINE_REGISTRY_SCRIPT, start)) return true; + const tag = html.slice(start, html.indexOf(">", start) + 1); + if (tag.includes(RUNTIME_BOOTSTRAP_ATTR) || IMPORT_MAP_TYPE.test(tag)) return true; + const src = SCRIPT_SRC.exec(tag); + return src !== null && isGsapCoreUrl((src[1] ?? src[2] ?? src[3] ?? "").replace(/&/gi, "&")); +} + +// Code that could still register a timeline. Whatever is not known to be Studio's own counts, so unsure means held. +export function hasAuthoredCode(html: string): boolean { + if (HANDLER_FRAME_TEMPLATE_OR_CHILD_COMPOSITION.test(html)) return true; + return findStartTags(html, "script").some((start) => !isStudioOwnScript(html, start)); +} diff --git a/packages/studio-server/src/helpers/rootImportMap.ts b/packages/studio-server/src/helpers/rootImportMap.ts index 2de60888b0..538cff1543 100644 --- a/packages/studio-server/src/helpers/rootImportMap.ts +++ b/packages/studio-server/src/helpers/rootImportMap.ts @@ -4,7 +4,7 @@ import { underBase } from "./rootPaths.js"; type Entries = Record; type ImportMap = { imports?: Entries; scopes?: Record }; -const IMPORT_MAP_TYPE = /\btype\s*=\s*["']?importmap["']?(?=[\s/>])/i; +export const IMPORT_MAP_TYPE = /\btype\s*=\s*["']?importmap["']?(?=[\s/>])/i; /** The first import map's JSON and where it sits; templates, comments and raw text are skipped. */ function findImportMap(html: string): { start: number; end: number; json: string } | null { diff --git a/packages/studio-server/src/helpers/screenshotClip.test.ts b/packages/studio-server/src/helpers/screenshotClip.test.ts index 6d68ba01b4..d086874cb7 100644 --- a/packages/studio-server/src/helpers/screenshotClip.test.ts +++ b/packages/studio-server/src/helpers/screenshotClip.test.ts @@ -1,5 +1,10 @@ import { afterEach, describe, expect, it } from "vitest"; -import { clearElementScreenshotIsolation, getElementScreenshotClip } from "./screenshotClip"; +import { + clearElementScreenshotIsolation, + getElementScreenshotClip, + THUMBNAIL_NO_AUTHORED_CODE_META, + thumbnailSeekReadyInBrowser, +} from "./screenshotClip"; afterEach(() => { document.body.innerHTML = ""; @@ -83,3 +88,32 @@ describe("getElementScreenshotClip", () => { expect(document.getElementById("outside")!.style.getPropertyValue("opacity")).toBe(outside); }); }); + +describe("thumbnailSeekReadyInBrowser", () => { + const mark = ``; + afterEach(() => { + for (const key of ["__timelines", "__renderReady"]) Reflect.deleteProperty(window, key); + }); + + it.each([ + ["a registered timeline, before the runtime is ready", { __timelines: { main: {} } }, "", true], + [ + "a page marked as having no code, once the runtime is ready", + { __renderReady: true }, + mark, + true, + ], + ["a page whose code may still register a timeline", { __renderReady: true }, "", false], + [ + "an empty timeline registry on such a page", + { __renderReady: true, __timelines: {} }, + "", + false, + ], + ["a marked page whose runtime is not ready yet", {}, mark, false], + ])("%s", (_page, state, head, ready) => { + document.head.innerHTML = head; + for (const [key, value] of Object.entries(state)) Reflect.set(window, key, value); + expect(thumbnailSeekReadyInBrowser()).toBe(ready); + }); +}); diff --git a/packages/studio-server/src/helpers/screenshotClip.ts b/packages/studio-server/src/helpers/screenshotClip.ts index f54c8c1709..314a986a73 100644 --- a/packages/studio-server/src/helpers/screenshotClip.ts +++ b/packages/studio-server/src/helpers/screenshotClip.ts @@ -60,3 +60,17 @@ export function clearElementScreenshotIsolation(): void { } page.__hfThumbnailFaded = []; } + +export const THUMBNAIL_NO_AUTHORED_CODE_META = "hyperframes-thumbnail-no-authored-code"; + +// Serialised into the page, so the meta name is spelled out. A timeline may register late: only a marked page skips it. +export function thumbnailSeekReadyInBrowser(): boolean { + const timelines: unknown = Reflect.get(window, "__timelines"); + if (typeof timelines === "object" && timelines !== null && Object.keys(timelines).length > 0) { + return true; + } + return ( + Boolean(Reflect.get(window, "__renderReady")) && + document.querySelector('meta[name="hyperframes-thumbnail-no-authored-code"]') !== null + ); +} diff --git a/packages/studio-server/src/helpers/subComposition.ts b/packages/studio-server/src/helpers/subComposition.ts index 4dc4cfc4e0..d4029268c2 100644 --- a/packages/studio-server/src/helpers/subComposition.ts +++ b/packages/studio-server/src/helpers/subComposition.ts @@ -15,6 +15,7 @@ import { import { findStartTags, isFullHtmlDocument } from "@hyperframes/core/compiler/html-document"; import { gsapCdnDist } from "@hyperframes/core/gsap-cdn"; import { resolveWithinProject } from "@hyperframes/core/safe-path"; +import { TIMELINE_REGISTRY_SCRIPT } from "./authoredCode.js"; import { htmlHasGsapCore, insertGsapCoreBeforeHeadPlugin } from "./gsapCoreScript.js"; import { withRootPathsRelative } from "./rootPaths.js"; @@ -418,7 +419,7 @@ ${htmlOpen} ${headContent} ${bodyOpen} - +${TIMELINE_REGISTRY_SCRIPT} ${rewrittenContent} `; diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts index 5b4eb85377..1c3724d72d 100644 --- a/packages/studio-server/src/index.ts +++ b/packages/studio-server/src/index.ts @@ -71,6 +71,7 @@ export { clearElementScreenshotIsolation, getElementScreenshotClip, type ScreenshotClip, + thumbnailSeekReadyInBrowser, } from "./helpers/screenshotClip.js"; export { thumbnailDeviceScaleFactor, diff --git a/packages/studio-server/src/routes/preview.thumbnailMark.test.ts b/packages/studio-server/src/routes/preview.thumbnailMark.test.ts new file mode 100644 index 0000000000..9c2bf78dc7 --- /dev/null +++ b/packages/studio-server/src/routes/preview.thumbnailMark.test.ts @@ -0,0 +1,96 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { findStartTags } from "@hyperframes/core/compiler/html-document"; +import { afterEach, describe, expect, it, onTestFinished } from "vitest"; +import { + THUMBNAIL_NO_AUTHORED_CODE_META, + thumbnailSeekReadyInBrowser, +} from "../helpers/screenshotClip"; +import { buildSubCompositionHtml } from "../helpers/subComposition"; +import { injectStudioPreviewAugmentations, withPreviewRuntime } from "./preview"; + +const STILL = '

Hi

'; +const LATE = `${STILL}`; +const MOTION = JSON.stringify({ + version: 1, + motions: [ + { + kind: "gsap-motion", + target: { sourceFile: "card.html", id: "title" }, + start: 0, + duration: 1, + ease: "none", + from: { x: 0 }, + to: { x: 10 }, + }, + ], +}); + +function project(files: Record): string { + const dir = mkdtempSync(join(tmpdir(), "hf-thumbnail-mark-")); + onTestFinished(() => rmSync(dir, { recursive: true, force: true })); + for (const [rel, content] of Object.entries(files)) { + mkdirSync(join(dir, rel, ".."), { recursive: true }); + writeFileSync(join(dir, rel), content, "utf-8"); + } + return dir; +} + +/** The page a thumbnail loads for card.html, as the preview route assembles it. */ +function servedPage(files: Record, capture = true): string { + const dir = project({ + "index.html": "", + ...files, + }); + const built = buildSubCompositionHtml(dir, "card.html", "/api/runtime.js") ?? ""; + return injectStudioPreviewAugmentations( + withPreviewRuntime(built, "/api/runtime.js"), + "/api/runtime.js", + "signature", + dir, + "card.html", + { capture, gsapBaseUrl: "https://cdn.jsdelivr.net/npm", sandboxedCapture: false }, + ); +} + +/** Opens the served page far enough for the rule: its named metas, the runtime ready, no timeline registered. */ +function readyWithoutTimeline(html: string): boolean { + for (const start of findStartTags(html, "meta")) { + const name = /\sname="([^"]*)"/.exec(html.slice(start, html.indexOf(">", start)))?.[1]; + if (name === undefined) continue; + const meta = document.createElement("meta"); + meta.name = name; + document.head.append(meta); + } + Reflect.set(window, "__renderReady", true); + return thumbnailSeekReadyInBrowser(); +} + +afterEach(() => { + document.head.replaceChildren(); + Reflect.deleteProperty(window, "__renderReady"); +}); + +describe("a thumbnail's wait for a timeline", () => { + it("is skipped for a composition with no code of its own", () => { + expect(readyWithoutTimeline(servedPage({ "card.html": STILL }))).toBe(true); + }); + + it("holds for a composition whose script registers its timeline late", () => { + expect(readyWithoutTimeline(servedPage({ "card.html": LATE }))).toBe(false); + }); + + it("holds for a still composition that Studio motion animates", () => { + const files = { "card.html": STILL, ".hyperframes/studio-motion.json": MOTION }; + expect(readyWithoutTimeline(servedPage(files))).toBe(false); + }); + + it("marks only the page a thumbnail loads, not the preview a person sees", () => { + expect(servedPage({ "card.html": STILL }, false)).not.toContain( + THUMBNAIL_NO_AUTHORED_CODE_META, + ); + }); +}); diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.ts index 50808ec7c3..b29a7c8158 100644 --- a/packages/studio-server/src/routes/preview.ts +++ b/packages/studio-server/src/routes/preview.ts @@ -37,6 +37,8 @@ import { normalizeGsapLocalRoot, } from "@hyperframes/core/gsap-cdn"; import { findStartTags, injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document"; +import { hasAuthoredCode } from "../helpers/authoredCode.js"; +import { THUMBNAIL_NO_AUTHORED_CODE_META } from "../helpers/screenshotClip.js"; import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution"; import type { ResolvedProject, StudioApiAdapter } from "../types.js"; import { @@ -386,10 +388,15 @@ export function injectStudioPreviewAugmentations( activeCompositionPath: string, options: { capture: boolean; gsapBaseUrl: string; sandboxedCapture: boolean }, ): string { + const studioMotion = readStudioMotion(projectDir, activeCompositionPath); + const noTimelineToCome = + options.capture && !studioMotion && !hasAuthoredCode(html) + ? `` + : ""; const marked = options.capture ? injectTagsAtHeadStart( options.sandboxedCapture ? corsProjectVideos(html) : html, - ``, + `${noTimelineToCome}`, ) : injectTagsAtHeadStart( lazyPreviewImages(html), @@ -405,7 +412,6 @@ export function injectStudioPreviewAugmentations( ), options.gsapBaseUrl, ); - const studioMotion = readStudioMotion(projectDir, activeCompositionPath); // Studio motion's GSAP core goes in first, so a MotionPathPlugin injected next lands after it. const withMotionDependencies = studioMotion ? injectStudioMotionDependencies( diff --git a/packages/studio/vite.browser.test.ts b/packages/studio/vite.browser.test.ts index ada156227f..c97d3cbd17 100644 --- a/packages/studio/vite.browser.test.ts +++ b/packages/studio/vite.browser.test.ts @@ -26,6 +26,7 @@ vi.mock("node:child_process", async (original) => ({ execFileSync: browserMocks.versionProbe, })); +import { thumbnailSeekReadyInBrowser } from "@hyperframes/studio-server"; import { findSystemChrome, generateThumbnail, type GenerateThumbnailOptions } from "./vite.browser"; const originalBrowserPath = process.env["HYPERFRAMES_BROWSER_PATH"]; @@ -123,6 +124,16 @@ describe("generateThumbnail", () => { expect(browserMocks.page.goto).toHaveBeenCalledWith(previewUrl, expect.anything()); }); + it("holds a thumbnail's shot on the thumbnail readiness rule", async () => { + await expect(generateThumbnail(options())).resolves.toEqual(Buffer.from("thumbnail")); + + const { waitForFunction, screenshot } = browserMocks.page; + expect(waitForFunction).toHaveBeenCalledWith(thumbnailSeekReadyInBrowser, { timeout: 5000 }); + expect(waitForFunction.mock.invocationCallOrder[0]).toBeLessThan( + screenshot.mock.invocationCallOrder[0] ?? 0, + ); + }); + it("captures at the route-provided physical output size", async () => { await expect(generateThumbnail(options())).resolves.toEqual(Buffer.from("thumbnail")); diff --git a/packages/studio/vite.browser.ts b/packages/studio/vite.browser.ts index 6a4ecde9ed..01bb18453d 100644 --- a/packages/studio/vite.browser.ts +++ b/packages/studio/vite.browser.ts @@ -8,6 +8,7 @@ import { getElementScreenshotClip, grantCaptureLoads, thumbnailDeviceScaleFactor, + thumbnailSeekReadyInBrowser, type ScreenshotClip, } from "@hyperframes/studio-server"; import { createStudioDevRenderBodyScripts } from "./vite.studioMotion"; @@ -236,11 +237,7 @@ async function prepareThumbnailPage( document.body.style.margin = "0"; document.body.style.overflow = "hidden"; }); - await page - .waitForFunction(`!!(window.__timelines && Object.keys(window.__timelines).length > 0)`, { - timeout: 5000, - }) - .catch(() => {}); + await page.waitForFunction(thumbnailSeekReadyInBrowser, { timeout: 5000 }).catch(() => {}); await seekThumbnailPreview(page, opts.seekTime); await page.evaluate("window.__hfWaitForSeekCompletion?.()"); await applyStudioRenderBodyScriptsToThumbnailPage(page, opts.project.dir, opts.compPath);