Skip to content

Commit c89724b

Browse files
committed
fix(studio): resolve sibling asset paths in sub-composition previews
A composition in a subdirectory that references a sibling file (`<link href="_shared.css">`, not `../_shared.css`) was served unrewritten under the preview's project-root `<base>`, so the browser requested `/preview/_shared.css` and got a 404. The frame rendered unstyled, and the thumbnailer's transparent-body fallback painted it dark navy with unreadable text — every styleframe thumbnail in the Board view illegible. Resolve relative refs against the composition's own directory when that sibling file exists on disk. Registry blocks that reference project-root assets (`assets/logo.png`) have no such sibling, so they stay untouched. Applies to `src`/`href`, inline `style` urls, and `<style>` blocks through the one rewrite pass all three dispatch branches share.
1 parent 7e95630 commit c89724b

2 files changed

Lines changed: 122 additions & 24 deletions

File tree

‎packages/studio-server/src/helpers/subComposition.test.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,4 +359,60 @@ describe("buildSubCompositionHtml", () => {
359359
// The <style> sibling was not tagged.
360360
expect(html).not.toMatch(/<style[^>]*data-composition-id/i);
361361
});
362+
363+
// Regression guard for the dark/illegible styleframe thumbnail: a composition
364+
// in a subdirectory that references a SIBLING file (`_shared.css`, not
365+
// `../_shared.css`) used to be served unrewritten under the project-root
366+
// <base>, so the browser requested /preview/_shared.css → 404. The frame then
367+
// rendered unstyled, and the thumbnailer's transparent-body fallback painted
368+
// it dark navy with unreadable text.
369+
it("resolves same-directory asset refs against the composition's own directory", () => {
370+
const dir = makeTempProject({
371+
"index.html": `<!doctype html><html><head></head><body></body></html>`,
372+
"design/styleframes/_shared.css": `.stage { background: #fff; }`,
373+
"design/styleframes/frame-01.png": `png`,
374+
"design/styleframes/frame-01.html": `<!doctype html>
375+
<html lang="en">
376+
<head>
377+
<meta charset="UTF-8" />
378+
<link rel="stylesheet" href="_shared.css" />
379+
<style>.stage { background-image: url("frame-01.png"); }</style>
380+
</head>
381+
<body><div class="stage"><img src="frame-01.png" alt="" /></div></body>
382+
</html>`,
383+
});
384+
385+
const html = buildSubCompositionHtml(
386+
dir,
387+
"design/styleframes/frame-01.html",
388+
"/api/runtime.js",
389+
"/api/projects/demo/preview/",
390+
);
391+
392+
expect(html).not.toBeNull();
393+
expect(html).toContain('href="design/styleframes/_shared.css"');
394+
expect(html).toContain('src="design/styleframes/frame-01.png"');
395+
expect(html).toContain('url("design/styleframes/frame-01.png")');
396+
expect(html).not.toContain('href="_shared.css"');
397+
});
398+
399+
it("leaves project-root-relative asset refs alone when no sibling file exists", () => {
400+
// Registry blocks are installed into a subdirectory but reference assets at
401+
// the project root (`assets/logo.png`). Those already resolve correctly
402+
// under the project-root <base> and must not be re-pointed at the block dir.
403+
const dir = makeTempProject({
404+
"index.html": `<!doctype html><html><head></head><body></body></html>`,
405+
"assets/logo.png": `png`,
406+
"blocks/hero.html": `<div data-composition-id="hero"><img src="assets/logo.png" alt="" /></div>`,
407+
});
408+
409+
const html = buildSubCompositionHtml(
410+
dir,
411+
"blocks/hero.html",
412+
"/api/runtime.js",
413+
"/api/projects/demo/preview/",
414+
);
415+
416+
expect(html).toContain('src="assets/logo.png"');
417+
});
362418
});

‎packages/studio-server/src/helpers/subComposition.ts‎

Lines changed: 66 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
import { existsSync, readFileSync } from "node:fs";
2-
import { join } from "node:path";
2+
import { join, posix } from "node:path";
33
import { parseHTML } from "linkedom";
4-
import {
5-
rewriteAssetPaths,
6-
rewriteCssAssetUrls,
7-
rewriteInlineStyleAssetUrls,
8-
} from "@hyperframes/core";
4+
import { CSS_URL_RE, isNonRelativeUrl, rewriteAssetPath } from "@hyperframes/core";
95
import { stripEmbeddedRuntimeScripts } from "@hyperframes/core/compiler";
106

117
/**
@@ -18,25 +14,70 @@ function isFullHtmlDocument(html: string): boolean {
1814
return /^\s*(?:<!doctype\s|<html[\s>])/i.test(html);
1915
}
2016

17+
/**
18+
* Resolve one relative asset reference authored inside a sub-composition into a
19+
* path that is correct under the preview's project-root `<base>`.
20+
*
21+
* The browser resolves a relative URL against the document the markup came
22+
* from, but this page borrows the project-root base — so a composition at
23+
* `design/styleframes/frame-01.html` referencing its sibling `_shared.css` used
24+
* to be served as-is and requested as `/preview/_shared.css` (404). The frame
25+
* then rendered unstyled, which the thumbnailer's transparent-body fallback
26+
* painted dark navy — the "illegible styleframe thumbnail" bug.
27+
*
28+
* Two rules, in order:
29+
* 1. `../` paths resolve against the composition dir (shared with the
30+
* producer's inliner, so preview and render agree).
31+
* 2. Any other relative path is re-pointed at the composition's own directory
32+
* ONLY when that sibling file actually exists. Registry blocks installed
33+
* into a subdirectory reference project-root assets (`assets/logo.png`)
34+
* that are already correct under the root base — those must stay put, and
35+
* a disk check is what tells the two conventions apart.
36+
*/
37+
function resolvePreviewAssetPath(projectDir: string, compPath: string, rawValue: string): string {
38+
const value = rawValue.trim();
39+
if (isNonRelativeUrl(value)) return value;
40+
if (value.startsWith("../") || value === "..") return rewriteAssetPath(compPath, value);
41+
const compDir = posix.dirname(compPath);
42+
if (!compDir || compDir === ".") return value;
43+
const filePart = value.split(/[?#]/)[0] ?? "";
44+
if (!filePart) return value;
45+
const sibling = posix.join(compDir, filePart);
46+
if (!existsSync(join(projectDir, sibling))) return value;
47+
return posix.join(compDir, value);
48+
}
49+
50+
function rewriteCssUrls(cssText: string, resolvePath: (value: string) => string): string {
51+
if (!cssText) return cssText;
52+
return cssText.replace(CSS_URL_RE, (full: string, quote: string, rawUrl: string) => {
53+
const url = (rawUrl || "").trim();
54+
const resolved = resolvePath(url);
55+
return resolved === url ? full : `url(${quote || ""}${resolved}${quote || ""})`;
56+
});
57+
}
58+
2159
/**
2260
* Rewrite relative asset paths in a parsed DOM tree. Shared across all
2361
* three dispatch branches (template, full-doc, fragment) to avoid drift.
2462
*/
25-
function rewriteRelativePaths(root: ParentNode, compPath: string): void {
26-
rewriteAssetPaths(
27-
root.querySelectorAll("[src], [href]"),
28-
compPath,
29-
(el: Element, attr: string) => el.getAttribute(attr),
30-
(el: Element, attr: string, value: string) => el.setAttribute(attr, value),
31-
);
32-
rewriteInlineStyleAssetUrls(
33-
root.querySelectorAll("[style]"),
34-
compPath,
35-
(el: Element) => el.getAttribute("style"),
36-
(el: Element, value: string) => el.setAttribute("style", value),
37-
);
63+
function rewriteRelativePaths(root: ParentNode, compPath: string, projectDir: string): void {
64+
const resolvePath = (value: string) => resolvePreviewAssetPath(projectDir, compPath, value);
65+
for (const el of root.querySelectorAll("[src], [href]")) {
66+
for (const attr of ["src", "href"]) {
67+
const value = (el.getAttribute(attr) || "").trim();
68+
if (!value) continue;
69+
const resolved = resolvePath(value);
70+
if (resolved !== value) el.setAttribute(attr, resolved);
71+
}
72+
}
73+
for (const el of root.querySelectorAll("[style]")) {
74+
const style = el.getAttribute("style");
75+
if (!style) continue;
76+
const resolved = rewriteCssUrls(style, resolvePath);
77+
if (resolved !== style) el.setAttribute("style", resolved);
78+
}
3879
for (const styleEl of root.querySelectorAll("style")) {
39-
styleEl.textContent = rewriteCssAssetUrls(styleEl.textContent || "", compPath);
80+
styleEl.textContent = rewriteCssUrls(styleEl.textContent || "", resolvePath);
4081
}
4182
}
4283

@@ -110,6 +151,7 @@ function fixDigitLeadingIdSelectors(root: ParentNode): void {
110151
function extractFullDocumentParts(
111152
rawHtml: string,
112153
compPath: string,
154+
projectDir: string,
113155
): {
114156
headContent: string;
115157
bodyContent: string;
@@ -120,7 +162,7 @@ function extractFullDocumentParts(
120162

121163
const rewriteTargets = [doc.head, doc.body].filter(Boolean);
122164
for (const target of rewriteTargets) {
123-
rewriteRelativePaths(target, compPath);
165+
rewriteRelativePaths(target, compPath, projectDir);
124166
}
125167
// Run on the whole document: ids live in <body> but their rules may live in
126168
// a <head> <style>, so the scope must span both.
@@ -278,12 +320,12 @@ export function buildSubCompositionHtml(
278320
const { document: contentDoc } = parseHTML(
279321
`<!DOCTYPE html><html><head></head><body>${templateInner}</body></html>`,
280322
);
281-
rewriteRelativePaths(contentDoc, compPath);
323+
rewriteRelativePaths(contentDoc, compPath, projectDir);
282324
fixDigitLeadingIdSelectors(contentDoc);
283325
promoteTemplateCompositionId(rawComp, contentDoc.body);
284326
rewrittenContent = contentDoc.body.innerHTML || templateInner;
285327
} else if (isFullHtmlDocument(rawComp)) {
286-
const parts = extractFullDocumentParts(rawComp, compPath);
328+
const parts = extractFullDocumentParts(rawComp, compPath, projectDir);
287329
compHeadContent = parts.headContent;
288330
rewrittenContent = parts.bodyContent;
289331
htmlAttrs = parts.htmlAttrs;
@@ -292,7 +334,7 @@ export function buildSubCompositionHtml(
292334
const { document: contentDoc } = parseHTML(
293335
`<!DOCTYPE html><html><head></head><body>${rawComp}</body></html>`,
294336
);
295-
rewriteRelativePaths(contentDoc, compPath);
337+
rewriteRelativePaths(contentDoc, compPath, projectDir);
296338
fixDigitLeadingIdSelectors(contentDoc);
297339
rewrittenContent = contentDoc.body.innerHTML || rawComp;
298340
}

0 commit comments

Comments
 (0)