Skip to content

Commit cf43dd1

Browse files
committed
fix(lint): a font the project's root stylesheet declares counts for its sub-compositions
1 parent 01783f3 commit cf43dd1

4 files changed

Lines changed: 87 additions & 22 deletions

File tree

‎packages/lint/src/project.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,6 +541,32 @@ describe("sub-composition stylesheet links", () => {
541541
).toEqual([]);
542542
});
543543

544+
it("counts a font the root's linked stylesheet declares for a sub-composition that only uses it", async () => {
545+
const project = makeProject(
546+
validHtml().replace(
547+
"<body>",
548+
'<head><link rel="stylesheet" href="assets/fonts.css"></head><body>',
549+
),
550+
);
551+
mkdirSync(join(project, "assets"), { recursive: true });
552+
writeFileSync(
553+
join(project, "assets", "fonts.css"),
554+
"@font-face{font-family:'Repro';src:local('Repro')}",
555+
);
556+
mkdirSync(join(project, "compositions"), { recursive: true });
557+
const scene = (family: string) => `<template>
558+
<style>#scene-title{font-family:'${family}'}</style>
559+
<div id="root" data-composition-id="scene" data-width="1920" data-height="1080" data-duration="1">
560+
<h1 id="scene-title">Hello</h1>
561+
</div>
562+
<script>window.__timelines["scene"] = gsap.timeline({ paused: true });</script>
563+
</template>`;
564+
writeFileSync(join(project, "compositions", "scene.html"), scene("Repro"));
565+
expect(await fontFaceFindings(project)).toEqual([]);
566+
writeFileSync(join(project, "compositions", "scene.html"), scene("Nowhere"));
567+
expect(await fontFaceFindings(project)).toHaveLength(1);
568+
});
569+
544570
it("reads the stylesheet next to the sub-composition when both exist", async () => {
545571
const project = projectWithSharedFonts("compositions/frames", "fonts.css");
546572
writeFileSync(join(project, "fonts.css"), "@font-face{font-family:'Other';src:local('Other')}");

‎packages/lint/src/project.ts‎

Lines changed: 50 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import {
4040
lintVideoMediaStartPastEof,
4141
} from "./hevcPreviewLint.js";
4242
import { lintHyperframeHtml } from "./hyperframeLinter.js";
43+
import { extractFontFaceFamilies } from "./rules/fonts.js";
4344
import { lintProjectShaderScripts } from "./projectShaders.js";
4445
import type {
4546
HyperframeLintFinding,
@@ -198,6 +199,41 @@ function resolveCssAssetCandidates(
198199
return resolveLocalAssetCandidates(projectDir, url);
199200
}
200201

202+
function collectHtmlFiles(compositionsDir: string): string[] {
203+
const walk = (dir: string, rel: string): string[] => {
204+
const out: string[] = [];
205+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
206+
const relPath = rel ? `${rel}/${entry.name}` : entry.name;
207+
if (entry.isDirectory()) {
208+
// Registry components are source snippets, not independently mounted
209+
// sub-compositions. Linting every installed template here makes an
210+
// unused component fail the assembled project check.
211+
if (!rel && entry.name === "components") continue;
212+
out.push(...walk(join(dir, entry.name), relPath));
213+
} else if (entry.isFile() && entry.name.endsWith(".html") && !entry.name.startsWith("._")) {
214+
out.push(relPath);
215+
}
216+
}
217+
return out;
218+
};
219+
return walk(compositionsDir, "").sort();
220+
}
221+
222+
function declaredProjectFontFamilies(projectDir: string, sources: HtmlSource[]): string[] {
223+
const families = new Set<string>();
224+
for (const { html, compSrcPath } of sources) {
225+
const { document } = parseHTML(html);
226+
const styles = [
227+
...querySelectorAllIncludingTemplates(document, "style").map((style) => ({
228+
content: style.textContent ?? "",
229+
})),
230+
...collectLocalStylesheets(projectDir, document, compSrcPath),
231+
];
232+
for (const family of extractFontFaceFamilies(styles)) families.add(family);
233+
}
234+
return [...families];
235+
}
236+
201237
export async function lintProject(
202238
projectDir: string,
203239
entryFile?: string,
@@ -215,37 +251,31 @@ export async function lintProject(
215251
let totalInfos = 0;
216252

217253
const rootHtml = readFileSync(indexPath, "utf-8");
254+
const compositionsDir = resolve(projectDir, "compositions");
255+
const compositionFiles =
256+
!entryFile && existsSync(compositionsDir) ? collectHtmlFiles(compositionsDir) : [];
257+
const projectFontFamilies = declaredProjectFontFamilies(projectDir, [
258+
{ html: rootHtml, compSrcPath: rootCompSrcPath },
259+
...compositionFiles.map((file) => ({
260+
html: readFileSync(join(compositionsDir, file), "utf-8"),
261+
compSrcPath: `compositions/${file}`,
262+
})),
263+
]);
218264
const rootResult = await lintHyperframeHtml(rootHtml, {
219265
...hostOptions,
220266
filePath: indexPath,
221267
compSrcPath: rootFile,
222268
externalStyles: collectExternalStyles(projectDir, rootHtml, rootCompSrcPath),
269+
projectFontFamilies,
223270
});
224271
results.push({ file: rootFile, result: rootResult, contentHash: contentDigest(rootHtml) });
225272
totalErrors += rootResult.errorCount;
226273
totalWarnings += rootResult.warningCount;
227274
totalInfos += rootResult.infoCount;
228275

229276
const allHtmlSources: HtmlSource[] = [{ html: rootHtml, compSrcPath: rootCompSrcPath }];
230-
const compositionsDir = resolve(projectDir, "compositions");
231-
if (!entryFile && existsSync(compositionsDir)) {
232-
const collectHtmlFiles = (dir: string, rel: string): string[] => {
233-
const out: string[] = [];
234-
for (const entry of readdirSync(dir, { withFileTypes: true })) {
235-
const relPath = rel ? `${rel}/${entry.name}` : entry.name;
236-
if (entry.isDirectory()) {
237-
// Registry components are source snippets, not independently mounted
238-
// sub-compositions. Linting every installed template here makes an
239-
// unused component fail the assembled project check.
240-
if (!rel && entry.name === "components") continue;
241-
out.push(...collectHtmlFiles(join(dir, entry.name), relPath));
242-
} else if (entry.isFile() && entry.name.endsWith(".html") && !entry.name.startsWith("._")) {
243-
out.push(relPath);
244-
}
245-
}
246-
return out;
247-
};
248-
const files = collectHtmlFiles(compositionsDir, "").sort();
277+
if (compositionFiles.length > 0) {
278+
const files = compositionFiles;
249279
for (const file of files) {
250280
const filePath = join(compositionsDir, file);
251281
const html = readFileSync(filePath, "utf-8");
@@ -262,6 +292,7 @@ export async function lintProject(
262292
isSubComposition: true,
263293
compSrcPath,
264294
externalStyles: collectExternalStyles(projectDir, html, compSrcPath),
295+
projectFontFamilies,
265296
});
266297
results.push({
267298
file: `compositions/${file}`,

‎packages/lint/src/rules/fonts.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ function isFontFaceDeclaration(decl: postcss.Declaration): boolean {
4747
return false;
4848
}
4949

50-
function extractFontFaceFamilies(styles: Array<{ content: string }>): Set<string> {
50+
export function extractFontFaceFamilies(styles: Array<{ content: string }>): Set<string> {
5151
const families = new Set<string>();
5252
for (const style of styles) {
5353
parseFontCss(style.content)?.walkDecls(/^font-family$/i, (decl) => {
@@ -59,6 +59,13 @@ function extractFontFaceFamilies(styles: Array<{ content: string }>): Set<string
5959
return families;
6060
}
6161

62+
function declaredFontFamilies(
63+
styles: Array<{ content: string }>,
64+
options: { projectFontFamilies?: string[] },
65+
): Set<string> {
66+
return new Set([...extractFontFaceFamilies(styles), ...(options.projectFontFamilies ?? [])]);
67+
}
68+
6269
// Function tokens and unresolved var() references are not literal family names.
6370
function normalizeUsedFontName(part: string): string | null {
6471
const name = part
@@ -195,7 +202,7 @@ export const fontRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
195202
// so there is nothing for the author to act on.
196203
({ styles, options }) => {
197204
if (!options.distributed) return [];
198-
const declared = extractFontFaceFamilies(styles);
205+
const declared = declaredFontFamilies(styles, options);
199206
const used = extractUsedFontFamilies(styles);
200207
const aliased = collectAliasedFonts(used, declared);
201208
if (aliased.length === 0) return [];
@@ -215,7 +222,7 @@ export const fontRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
215222
({ styles, source, rawSource, options, locate }) => {
216223
if (isRegistrySourceFile(options.filePath) || isRegistryInstalledFile(rawSource)) return [];
217224
const findings: HyperframeLintFinding[] = [];
218-
const declared = extractFontFaceFamilies(styles);
225+
const declared = declaredFontFamilies(styles, options);
219226
const used = extractUsedFontFamilies(styles);
220227
const googleFonts = collectGoogleFontFamilies(source, styles);
221228

‎packages/lint/src/types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ export type HyperframeLinterOptions = {
5555
* render time — the font will silently fall back to whatever the OS provides.
5656
*/
5757
distributed?: boolean;
58+
projectFontFamilies?: string[];
5859
/** Who is running the lint: Studio raises the structure rules to errors, the CLI keeps them warnings. */
5960
host?: "studio" | "cli";
6061
};

0 commit comments

Comments
 (0)