From 6b3701084070ed04452149de895341e8d142a65c Mon Sep 17 00:00:00 2001 From: Adam <2363879+adamdotdevin@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:50:44 -0600 Subject: [PATCH] refactor(site): prune component CSS variants and split shell from route stylesheets (#62990) --- services/site/script/check-client-bundle.ts | 40 +- services/site/script/check-css-output.ts | 26 +- services/site/script/css-variants-plugin.ts | 257 +++++-- services/site/script/css-variants.ts | 18 +- services/site/script/stylesheet-groups.ts | 72 ++ services/site/src/app.tsx | 5 +- .../src/component/site/changelog-entry.css | 3 +- .../site/src/component/site/css-variants.json | 102 ++- .../site/src/component/site/css-variants.ts | 36 +- .../site/src/component/site/docs-lockup.css | 4 +- .../site/src/component/site/inter-fonts.ts | 3 +- .../site/src/component/site/legal-print.css | 14 +- .../site/src/component/site/legal-print.tsx | 1 - services/site/src/component/site/legal.tsx | 3 + services/site/src/component/site/logo-fan.css | 626 ------------------ .../site/src/component/site/markdown-view.css | 11 +- .../site/src/component/site/markdown-view.tsx | 1 + .../site/src/component/site/mono-fonts.ts | 3 +- .../src/component/site/preload-settings.ts | 35 + services/site/src/component/site/site.css | 22 + services/site/src/component/site/site.tsx | 11 +- services/site/src/docs/layouts/DocsLayout.tsx | 5 +- services/site/src/docs/script/build.ts | 2 +- services/site/src/docs/styles/docs.css | 1 + services/site/src/i18n/preload.ts | 2 +- services/site/src/lib/head-links.ts | 36 + services/site/src/lib/one-stylesheet.ts | 59 -- services/site/src/middleware.ts | 8 +- services/site/src/routes/legal/legal.css | 15 +- .../src/routes/legal/privacy-policy/index.css | 4 - services/site/src/routes/press/index.css | 9 - services/site/src/routes/stylesheet/[file].ts | 8 +- services/site/src/style/fonts.css | 203 ++++++ services/site/test/css-variants.test.ts | 41 +- services/site/test/fonts.test.ts | 17 + services/site/test/head-links.test.ts | 22 + services/site/test/one-stylesheet.test.ts | 35 - services/site/vite.config.ts | 2 + 38 files changed, 867 insertions(+), 895 deletions(-) create mode 100644 services/site/script/stylesheet-groups.ts delete mode 100644 services/site/src/component/site/logo-fan.css create mode 100644 services/site/src/lib/head-links.ts delete mode 100644 services/site/src/lib/one-stylesheet.ts create mode 100644 services/site/src/style/fonts.css create mode 100644 services/site/test/head-links.test.ts delete mode 100644 services/site/test/one-stylesheet.test.ts diff --git a/services/site/script/check-client-bundle.ts b/services/site/script/check-client-bundle.ts index f7fc1277aba..b465c47b89d 100644 --- a/services/site/script/check-client-bundle.ts +++ b/services/site/script/check-client-bundle.ts @@ -64,26 +64,26 @@ console.log( // Each page's budget in kB, gzipped: what it was when last measured, plus a kB of room. Lower a // budget when a page gets lighter; a page without one fails until it has one. const budgets: Record = { - "[...404].tsx": 104.1, - "brand/index.tsx": 104.5, - "changelog/[tag].tsx": 99.2, - "changelog/index.tsx": 98.4, - "desktop.tsx": 127.9, - "devices.tsx": 56.8, - "product/browse.tsx": 104.2, - "font/index.tsx": 120.1, - "ide.tsx": 127.9, - "index.tsx": 114.9, - "legal/index.tsx": 148.3, - "legal/privacy-policy/index.tsx": 137.8, - "legal/terms-of-service/index.tsx": 133.2, - "mini.tsx": 127.9, - "mobile.tsx": 127.9, - "press/index.tsx": 113.2, - "product/index.tsx": 112.7, - "sdk.tsx": 127.9, - "terminal.tsx": 127.9, - "video-editor/index.tsx": 55.2, + "[...404].tsx": 103.8, + "brand/index.tsx": 104.4, + "changelog/[tag].tsx": 99, + "changelog/index.tsx": 98.2, + "desktop.tsx": 127.5, + "devices.tsx": 56.6, + "product/browse.tsx": 104, + "font/index.tsx": 119.9, + "ide.tsx": 127.5, + "index.tsx": 114.7, + "legal/index.tsx": 148.1, + "legal/privacy-policy/index.tsx": 137.7, + "legal/terms-of-service/index.tsx": 133, + "mini.tsx": 127.5, + "mobile.tsx": 127.5, + "press/index.tsx": 113, + "product/index.tsx": 112.5, + "sdk.tsx": 127.5, + "terminal.tsx": 127.5, + "video-editor/index.tsx": 55, } type Chunk = { file: string; imports?: string[] } const manifest: Record = await Bun.file(path.join(root, ".vite/manifest.json")).json() diff --git a/services/site/script/check-css-output.ts b/services/site/script/check-css-output.ts index d7b39b27aa8..acf5757c6dd 100644 --- a/services/site/script/check-css-output.ts +++ b/services/site/script/check-css-output.ts @@ -4,17 +4,39 @@ // (--lightningcss-light/--lightningcss-dark variables) freezes every token at the root's theme, so // the production page silently differs from the development server. vite.config.ts's cssTarget // keeps light-dark() native; this guards against that target being lowered again. +// +// It also fails when a stylesheet outgrows its budget (gzipped): the shell's, which every page links +// and holds up its first paint for, and each of the others, a group of pages' or one that loads on +// demand (script/stylesheet-groups.ts). // Run after `vite build`, optionally with the output directory: `bun script/check-css-output.ts .output`. import path from "node:path" import { Glob } from "bun" const root = path.resolve(process.argv[2] ?? path.join(import.meta.dir, "..", ".output"), "public") +const budgets = { shell: 27.5 * 1024, other: 10.5 * 1024 } const lowered: string[] = [] +const over: string[] = [] +const shells: string[] = [] for await (const file of new Glob("**/*.css").scan(root)) { - if ((await Bun.file(path.join(root, file)).text()).includes("--lightningcss-")) lowered.push(file) + const css = await Bun.file(path.join(root, file)).text() + if (css.includes("--lightningcss-")) lowered.push(file) + if (!file.startsWith("_build/assets/")) continue + const shell = path.basename(file).startsWith("shell-") + if (shell) shells.push(file) + const size = Bun.gzipSync(css, { level: 9 }).length + const budget = shell ? budgets.shell : budgets.other + if (size > budget) over.push(`${file} ${(size / 1024).toFixed(1)} kB (budget ${(budget / 1024).toFixed(1)} kB)`) } if (lowered.length > 0) { console.error(`light-dark() was lowered (--lightningcss-* variables) in:\n${lowered.join("\n")}`) process.exit(1) } -console.log("Production CSS keeps light-dark() native.") +if (shells.length !== 1) { + console.error(`expected one shell stylesheet, found ${shells.length}: ${shells.join(", ")}`) + process.exit(1) +} +if (over.length > 0) { + console.error(`stylesheets over budget (gzipped):\n${over.join("\n")}`) + process.exit(1) +} +console.log("Production CSS keeps light-dark() native, and each stylesheet is within its budget.") diff --git a/services/site/script/css-variants-plugin.ts b/services/site/script/css-variants-plugin.ts index 8696b26e78c..772788c5eb2 100644 --- a/services/site/script/css-variants-plugin.ts +++ b/services/site/script/css-variants-plugin.ts @@ -1,5 +1,7 @@ // Production CSS plugins shared by the site's build (vite.config.ts) and the docs' own build // (src/docs/script/build.ts), so both ship the same stylesheets for the same settings. +import { readdirSync, readFileSync } from "node:fs" +import path from "node:path" import type { PluginOption } from "vite" import variants from "../src/component/site/css-variants.json" @@ -17,50 +19,38 @@ export function devOnlyCss(): PluginOption { } /** - * Production only: Settings and Design mode are development tools, so the site root's settings - * attributes always carry the default settings' values (src/component/site/css-variants.json). This - * drops, from the production CSS, each selector that needs another value of one of them, and each - * rule left with none; the development server keeps every variant for Design mode. Only attributes - * outside parentheses count (an attribute inside :not(), :is() or :has() keeps its selector). + * Production only: Settings and Design mode are development tools, so the settings attributes + * always carry the default settings' values (src/component/site/css-variants.json): on the site root, + * and on the elements the pre-paint rules name (`scoped`, matched by their attribute values, such as + * `[data-component="products"]`). This drops, from the production CSS, each selector that needs + * another value of one of them, nested selectors included (read with their parents'), each rule left + * with none, and then the at-rules left empty and the @keyframes nothing names any more; the + * development server keeps every variant for Design mode. Only attributes outside parentheses count, + * and an :is() or :where() none of whose selectors can match (an attribute inside :not() or :has() + * keeps its selector). */ export function cssVariantsForProduction(): PluginOption { - const fixed = variants as Record - const impossible = (selector: string) => { - let depth = 0 - let top = "" - for (const char of selector) { - if (char === "(") depth++ - if (depth === 0) top += char - if (char === ")") depth-- - } - return [...top.matchAll(/\[(data-[\w-]+)(~?=)["']?([^"'\]]*)["']?\]/g)].some((match) => { - if (!(match[1] in fixed)) return false - const value = fixed[match[1]] - if (value === null) return true - return match[2] === "~=" ? !value.split(" ").includes(match[3]) : value !== match[3] + const root = variants.root as Record + const scoped = (variants.scoped as [string, string, string | null][]).map(([element, name, value]) => ({ + element: attributes(element).map((attribute) => attribute.join("")), + name, + value, + })) + const impossible = (selector: string): boolean => + alternatives(selector).some((list) => split(list).every((each) => impossible(each))) || + compounds(selector).some((compound) => { + const found = attributes(compound) + const keys = new Set(found.map((attribute) => attribute.join(""))) + return found.some(([name, operator, value]) => { + if (name in root) return !matches(root[name], operator, value) + return scoped.some( + (entry) => + entry.name === name && + entry.element.every((key) => keys.has(key)) && + !matches(entry.value, operator, value), + ) + }) }) - } - const split = (selector: string) => { - const parts: string[] = [] - let depth = 0 - let quote = "" - let start = 0 - for (let i = 0; i < selector.length; i++) { - const char = selector[i] - if (quote) { - if (char === quote) quote = "" - continue - } - if (char === '"' || char === "'") quote = char - else if (char === "(" || char === "[") depth++ - else if (char === ")" || char === "]") depth-- - else if (char === "," && depth === 0) { - parts.push(selector.slice(start, i)) - start = i + 1 - } - } - return [...parts, selector.slice(start)] - } return { name: "css-variants-for-production", apply: "build", @@ -70,12 +60,37 @@ export function cssVariantsForProduction(): PluginOption { plugins: [ { postcssPlugin: "css-variants-for-production", - Rule(rule: { selector: string; remove(): void }) { - const selectors = split(rule.selector) - const kept = selectors.filter((selector) => !impossible(selector)) - if (kept.length === selectors.length) return - if (!kept.length) return rule.remove() - rule.selector = kept.join(",") + OnceExit(css: Root) { + // Each rule's selectors as written out in full, so a nested one is read with its parents'. + const full = new WeakMap() + css.walkRules((rule) => { + if (/keyframes$/i.test(rule.parent?.name ?? "")) return + const parent = parentRule(rule) + const parents = (parent && full.get(parent)) ?? [""] + const selectors = split(rule.selector ?? "").map((selector) => ({ + selector, + full: parents.map((parent) => nest(parent, selector.trim())).filter((each) => !impossible(each)), + })) + const kept = selectors.filter((selector) => selector.full.length) + full.set( + rule, + kept.flatMap((selector) => selector.full), + ) + if (!kept.length) return rule.remove() + if (kept.length < selectors.length) + rule.selector = kept.map((selector) => selector.selector).join(",") + }) + removeEmpty(css) + // A @keyframes no declaration names any more (an animation, or a custom property one + // reads), unless another file names it: a stylesheet built on its own, or a script. + const named = new Set() + css.walkDecls((decl) => decl.value?.match(/[\w-]+/g)?.forEach((name) => named.add(name))) + css.walkAtRules(/^(-webkit-)?keyframes$/i, (rule) => { + const name = (rule.params ?? "").trim().replace(/^["']|["']$/g, "") + if (named.has(name) || namedElsewhere(name, rule.source?.input?.file)) return + rule.remove() + }) + removeEmpty(css) }, }, ], @@ -84,3 +99,151 @@ export function cssVariantsForProduction(): PluginOption { }), } } + +// The PostCSS nodes this reads (the site doesn't depend on PostCSS itself; Vite runs it). +type Node = { + type: string + name?: string + params?: string + selector?: string + value?: string + nodes?: Node[] + parent?: Node + source?: { input?: { file?: string } } + remove(): void +} +type Root = Node & { + walk(callback: (node: Node) => void): void + walkRules(callback: (rule: Node) => void): void + walkDecls(callback: (decl: Node) => void): void + walkAtRules(filter: RegExp, callback: (rule: Node) => void): void +} + +/** The nearest rule a rule is nested in (through at-rules such as @media), if any. */ +function parentRule(rule: Node) { + let node = rule.parent + while (node && node.type === "atrule") node = node.parent + return node?.type === "rule" ? node : undefined +} + +/** A nested selector written out against one of its parent's (CSS nesting: `&`, or a descendant). */ +function nest(parent: string, selector: string) { + if (!parent) return selector + return selector.includes("&") ? selector.replaceAll("&", parent) : `${parent} ${selector}` +} + +/** Removes the rules and at-rules (other than @font-face and the like, which hold declarations) left empty. */ +function removeEmpty(css: Root) { + const empty: Node[] = [] + css.walk((node) => { + if ((node.type === "rule" || node.type === "atrule") && node.nodes && node.nodes.length === 0) empty.push(node) + }) + if (!empty.length) return + empty.forEach((node) => node.remove()) + removeEmpty(css) +} + +/** A selector list's selectors. */ +function split(selector: string) { + const parts: string[] = [] + let depth = 0 + let quote = "" + let start = 0 + for (let i = 0; i < selector.length; i++) { + const char = selector[i] + if (quote) { + if (char === quote) quote = "" + continue + } + if (char === '"' || char === "'") quote = char + else if (char === "(" || char === "[") depth++ + else if (char === ")" || char === "]") depth-- + else if (char === "," && depth === 0) { + parts.push(selector.slice(start, i)) + start = i + 1 + } + } + return [...parts, selector.slice(start)] +} + +/** A selector's compound selectors (between its combinators), without what's inside parentheses. */ +function compounds(selector: string) { + const list = [""] + let depth = 0 + let bracket = false + let quote = "" + for (const char of selector) { + if (quote) { + if (char === quote) quote = "" + if (!depth) list[list.length - 1] += char + continue + } + if (char === "(") depth++ + if (char === ")") depth-- + if (depth || char === ")") continue + if (char === '"' || char === "'") quote = char + if (char === "[") bracket = true + if (char === "]") bracket = false + if (!bracket && /[\s>+~]/.test(char)) { + if (list.at(-1)) list.push("") + continue + } + list[list.length - 1] += char + } + return list.filter(Boolean) +} + +/** The selector lists of a selector's own :is() and :where(), which match when one of theirs does. */ +function alternatives(selector: string) { + const depth = (text: string) => [...text].reduce((open, char) => open + (char === "(" ? 1 : char === ")" ? -1 : 0), 0) + return [...selector.matchAll(/:(?:is|where)\(/g)] + .filter((match) => depth(selector.slice(0, match.index)) === 0) + .map((match) => { + let open = 1 + let end = match.index + match[0].length + for (; end < selector.length && open; end++) { + if (selector[end] === "(") open++ + if (selector[end] === ")") open-- + } + return selector.slice(match.index + match[0].length, end - 1) + }) +} + +/** A compound selector's attribute selectors, as name, operator and value (a case-insensitive one is left out). */ +function attributes(compound: string) { + return [...compound.matchAll(/\[\s*([\w-]+)\s*(?:([~|^$*]?=)\s*(?:"([^"]*)"|'([^']*)'|([^\s\]]*)))?\s*([is])?\s*\]/g)] + .filter((match) => match[6] !== "i") + .map((match) => [match[1], match[2] ?? "", match[3] ?? match[4] ?? match[5] ?? ""] as const) +} + +/** Whether an attribute with this production value (null: absent) matches an attribute selector. */ +function matches(fixed: string | null, operator: string, value: string) { + if (fixed === null) return false + if (operator === "") return true + if (operator === "=") return fixed === value + if (operator === "~=") return fixed.split(" ").includes(value) + if (operator === "|=") return fixed === value || fixed.startsWith(`${value}-`) + if (operator === "^=") return fixed.startsWith(value) + if (operator === "$=") return fixed.endsWith(value) + return fixed.includes(value) +} + +// The site's and its packages' sources, each file's words, read once: a @keyframes one of them names +// stays, as a stylesheet built on its own or a script may use it. +const sources = ["../src", "../../../packages/ui/src", "../../../packages/nav-menus/src"].map((dir) => + path.resolve(import.meta.dirname, dir), +) +let words: Map> | undefined +function namedElsewhere(name: string, file: string | undefined) { + words ??= new Map( + sources.flatMap((dir) => + readdirSync(dir, { recursive: true, encoding: "utf8" }) + .filter((entry) => /\.(css|tsx?|mdx)$/.test(entry)) + .map((entry) => { + const text = readFileSync(path.join(dir, entry), "utf8") + return [path.join(dir, entry), new Set(text.match(/[\w-]+/g))] as const + }), + ), + ) + return [...words].some(([source, names]) => source !== file && names.has(name)) +} diff --git a/services/site/script/css-variants.ts b/services/site/script/css-variants.ts index bb9188d7563..833352b7ff7 100644 --- a/services/site/script/css-variants.ts +++ b/services/site/script/css-variants.ts @@ -1,10 +1,18 @@ // Writes src/component/site/css-variants.json: each settings attribute and the one value production -// renders for it (the default settings; null when it is left off). script/css-variants-plugin.ts drops, from the -// production CSS only, every rule that needs another value. Run after changing a setting's default -// or adding a settings attribute; test/css-variants.test.ts fails while the file is out of date. +// renders for it (the default settings; null when it is left off), on the site root and on the +// elements the pre-paint rules name. script/css-variants-plugin.ts drops, from the production CSS +// only, every rule that needs another value. Run after changing a setting's default or adding a +// settings attribute; test/css-variants.test.ts fails while the file is out of date. import path from "node:path" import { cssVariants } from "../src/component/site/css-variants" const file = path.join(import.meta.dir, "../src/component/site/css-variants.json") -await Bun.write(file, JSON.stringify(cssVariants(), null, 2) + "\n") -console.log(`css-variants.json: ${Object.keys(cssVariants()).length} attributes`) +const variants = cssVariants() +// One element's attribute a line. +await Bun.write( + file, + JSON.stringify(variants, null, 2).replace(/\[\n\s+(.+),\n\s+(.+),\n\s+(.+)\n\s+\]/g, "[$1, $2, $3]") + "\n", +) +console.log( + `css-variants.json: ${Object.keys(variants.root).length} root attributes, ${variants.scoped.length} on other elements`, +) diff --git a/services/site/script/stylesheet-groups.ts b/services/site/script/stylesheet-groups.ts new file mode 100644 index 00000000000..ed7f1a2926a --- /dev/null +++ b/services/site/script/stylesheet-groups.ts @@ -0,0 +1,72 @@ +import type { PluginOption } from "vite" + +// Pages that share a layout share a stylesheet: the product pages with the changelog (both show +// release notes), and otherwise each section of the site (the route's first path segment). +const productPages = /^(product|desktop|terminal|mobile|sdk|ide|mini|changelog)(\/|$)/ +const shell = /[\\/]src[\\/](app|component[\\/]site[\\/]site)\.tsx$/ + +/** + * Production only: every page links two stylesheets, the shell's (`shell-.css`: the site's + * frame, its fonts and every stylesheet more than one group of pages uses) and its own group's + * (`home-`, `product-`, `legal-.css`, …). Both are content-hashed files that browsers keep for + * a year, so a visitor downloads the shell once and each group the first time they open one of its + * pages, whichever page that is. Vite splits stylesheets by JavaScript chunk, so this names a chunk + * of stylesheets for each: the stylesheets a page's code imports, and none that load on demand + * (search, the Markdown view, the Hex pop-up), which stay with their own code. Chunks of stylesheets + * alone leave no JavaScript (Vite's pure CSS chunks), and Vite's loader adds a group's stylesheet the + * first time the app moves to one of its pages. + */ +export function stylesheetGroups(): PluginOption { + return { + name: "stylesheet-groups", + apply: "build", + configEnvironment: (name) => { + if (name !== "client") return + return { + build: { + rolldownOptions: { + output: { + codeSplitting: { + groups: [ + { + name: (id, context) => group(id, (module) => context.getModuleInfo(module)), + test: /\.css$/, + // Ahead of vite.config.ts's "common" group, which takes along the modules its small + // shared ones import, so it would otherwise take stylesheets too (the orb's, the sheet's). + priority: 1, + }, + ], + }, + }, + }, + }, + } + }, + } +} + +/** The group a stylesheet goes in: the shell's, a group of pages', or none (it loads on demand). */ +function group(id: string, info: (id: string) => { importers: string[] } | null) { + const groups = new Set() + const seen = new Set() + // Up the static imports only, to the shell and the page routes. + const visit = (module: string) => { + if (seen.has(module)) return + seen.add(module) + const file = module.split("?")[0] + if (shell.test(file)) return groups.add("shell") + const route = file.match(/[\\/]src[\\/]routes[\\/](.+)\.tsx$/)?.[1] + if (route) return groups.add(routeGroup(route.replaceAll("\\", "/"))) + info(module)?.importers.forEach(visit) + } + visit(id) + if (groups.size === 0) return null + return groups.size === 1 ? [...groups][0] : "shell" +} + +function routeGroup(route: string) { + if (productPages.test(route)) return "product" + if (route === "index") return "home" + if (route === "[...404]") return "not-found" + return route.split("/")[0] +} diff --git a/services/site/src/app.tsx b/services/site/src/app.tsx index 484b58e7449..c84467ed3ca 100644 --- a/services/site/src/app.tsx +++ b/services/site/src/app.tsx @@ -6,6 +6,7 @@ import { isServer } from "solid-js/web" import { Favicon } from "@opencode/ui/favicon" import { Font } from "@opencode/ui/font" import "./style/ibm-plex-mono.dev.css" +import "./style/fonts.css" import "./app.css" import { LanguageProvider } from "~/context/language" import { I18nProvider, useI18n } from "~/context/i18n" @@ -18,7 +19,6 @@ import { viewportContent } from "~/lib/viewport" import { quietPreloads, setNavigating } from "~/lib/route-preloads" // Before the router, so its popstate listener comes first. import "~/component/site/popstate" -import { monoFontFaces } from "~/component/site/mono-fonts" // Pages that set their own og:image. const shareImagePages = [ @@ -111,9 +111,6 @@ export default function App() { - {/* OpenTUI Mono for every page, with or without the site shell (--font-mono and the - token stack name it). A plain style element, which hydration keeps. */} - ${css("b")}` - expect(combineStylesheets(html)).toBe(html) -}) diff --git a/services/site/vite.config.ts b/services/site/vite.config.ts index 425cc64066d..b3584fd1b2c 100644 --- a/services/site/vite.config.ts +++ b/services/site/vite.config.ts @@ -6,6 +6,7 @@ import { docs } from "./src/docs/vite" import { i18nSlices } from "./script/i18n-plugin" import { foldSettingsForProduction } from "./script/fold-settings" import { cssVariantsForProduction, devOnlyCss } from "./script/css-variants-plugin" +import { stylesheetGroups } from "./script/stylesheet-groups" // Nitro's dev server drops any page the app renders with a 404 status and falls through to a bare // "Cannot GET". In development only, serve the not-found page's preview (/dev/404, which follows @@ -56,6 +57,7 @@ export default defineConfig({ notFoundInDev(), devOnlyCss(), cssVariantsForProduction(), + stylesheetGroups(), docs(), i18nSlices(), ],