refactor(site): make every page static and stop shipping the app's JavaScript (#63067)

This commit is contained in:
Adam
2026-11-10 03:34:19 -06:00
committed by GitHub
Unverified
parent 3b04ec6f59
commit 57719d7fd4
29 changed files with 373 additions and 626 deletions
+2 -2
View File
@@ -21,11 +21,11 @@ Read the design-system rules in `DESIGN.md` (also shown at `/dev/components#rule
## Static pages
- The pages in `staticPaths` (`src/static/routes.ts`: home, the product pages, legal, Brand, Press, the changelog and Browse) render in production as plain HTML from the same components, without hydration (`src/static/render.tsx`). They load one small script, `src/client/entry.ts`, which reads the markup the components render and loads each island in `src/client/islands/` only when the page has it.
- Production hydrates no page. The pages in `staticPaths` (`src/static/routes.ts`: home, the product pages, legal, Brand, Press, the changelog, Browse and the font page) render as plain HTML from the same components, without hydration (`src/static/render.tsx`), and so does the not-found page, for every address no route answers. They load one small script, `src/client/entry.ts`, which reads the markup the components render and loads each island in `src/client/islands/` only when the page has it. The app's browser build only provides the stylesheets.
- Between the home page, /product and the product pages, a card grows into its product's hero and back with a cross-document view transition (`card-morph.ts`); every other page change is a plain page load.
- Behaviour both renderings need lives in framework-free modules in `src/component/site/` that the component and the script both call, such as `contents-spy.ts`, `changelog-motion.ts`, `tooltips.ts`, `site-frame.ts`, `theme-switch.ts` and `sheet-motion.ts`. Put new behaviour there. Where a component renders its state from signals and the script keeps its own copy, each names the other in a comment: change both.
- `vite dev` renders these pages hydrated, because Design mode and Settings need the app, so a change that only works hydrated looks right there. Check them in a production build served by `perf/serve.ts`: `bun run build`, then `bun perf/serve.ts --port 4300`, and open the page on that port.
- To serve a page hydrated again, remove its path from `staticPaths`.
- A new page route needs its path in `staticPaths`, or production answers it with the not-found page (`test/static-routes.test.ts` lists the ones that may be missing: the development tools).
## Funnel
+33 -59
View File
@@ -5,14 +5,11 @@
// Also fails when server-only code reaches it: the Worker's cache, GitHub calls and the build-time
// GitHub snapshot. Pages may import their modules for the queries, whose "use server" bodies the
// browser build drops along with everything only those bodies read.
// Last, it fails when a page's initial JavaScript (the entry and every chunk the page's route imports
// statically, which the server modulepreloads) passes its budget below, gzipped. A static page
// (src/static/routes.ts) loads the static pages' one script (src/client/entry.ts) instead, and has
// its budget. Code a page needs only later belongs behind a dynamic import.
// Last, it fails when the app's own scripts ship, or the one script every page loads passes its budget
// below. Code a page needs only later belongs behind a dynamic import.
// Run after `vite build`, optionally with the output directory: `bun script/check-client-bundle.ts .output`.
import path from "node:path"
import { Glob } from "bun"
import { staticPath } from "../src/static/routes"
const root = path.resolve(process.argv[2] ?? path.join(import.meta.dir, "..", ".output"), "public")
// Strings only the tools' own code contains, as they survive minification.
@@ -63,68 +60,45 @@ console.log(
`check-client-bundle: ${files.length} client files, no Settings, Design mode, device preview or server-only code`,
)
// 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<string, number> = {
"static pages": 11.3,
"[...404].tsx": 104.3,
"devices.tsx": 57.1,
"font/index.tsx": 119,
"video-editor/index.tsx": 55.5,
}
// Production hydrates no page (src/static/render.tsx): every page loads the static pages' one script
// (src/client/entry.ts, script/static-client.ts), whose islands and overlays load later. The app's
// browser build is there for its stylesheets only, so none of its scripts may ship, and the script
// may bring no router, no serialized data (seroval) and no hydration. Its budget in kB, gzipped, is
// what it was when last measured, plus a kB of room; lower it when the script gets lighter.
const budget = 11.6
type Chunk = { file: string; imports?: string[] }
const manifest: Record<string, Chunk> = await Bun.file(path.join(root, ".vite/manifest.json")).json()
const sizes = new Map<string, number>()
const gzipped = async (file: string) => {
const known = sizes.get(file)
if (known !== undefined) return known
const size = Bun.gzipSync(await Bun.file(path.join(root, file)).bytes(), { level: 9 }).length
sizes.set(file, size)
return size
}
const closure = (key: string, seen = new Set<string>()): Set<string> => {
if (seen.has(key)) return seen
seen.add(key)
manifest[key].imports?.forEach((next) => closure(next, seen))
return seen
}
const entry = closure("src/entry-client.tsx")
const kB = async (keys: Iterable<string>) =>
Math.round(
(await Promise.all([...keys].map((key) => gzipped(manifest[key].file)))).reduce((a, b) => a + b, 0) / 100,
) / 10
// The static pages' script, from its own build (script/static-client.ts): one file, whose islands and
// overlays load later.
const app: Record<string, Chunk> = await Bun.file(path.join(root, ".vite/manifest.json")).json()
const statics: Record<string, Chunk> = await Bun.file(path.join(root, ".vite/static-manifest.json")).json()
const own = new Set(Object.values(statics).map((chunk) => chunk.file))
const shipped = (
await Promise.all(
Object.values(app)
.filter((chunk) => /\.m?js$/.test(chunk.file) && !own.has(chunk.file))
.map(async (chunk) => ((await Bun.file(path.join(root, chunk.file)).exists()) ? [chunk.file] : [])),
)
).flat()
if (shipped.length) {
console.error(`check-client-bundle: the app's scripts ship, though no page loads them:\n ${shipped.join("\n ")}`)
process.exit(1)
}
const script = statics["src/client/entry.ts"]
if (script.imports?.length) {
console.error(`check-client-bundle: the static pages' script imports ${script.imports.join(", ")}; keep it one file`)
process.exit(1)
}
const staticScript = Math.round((await gzipped(script.file)) / 100) / 10
const pages = await Promise.all(
Object.keys(manifest)
.filter((key) => key.startsWith("src/routes/") && key.includes("?pick=default"))
.map(async (key) => {
const route = key.slice("src/routes/".length).split("?")[0]
// The route file's address: brand/index.tsx is /brand, changelog/[tag].tsx is /changelog/:tag.
const address = `/${route.replace(/(^|\/)index\.tsx$|\.tsx$/, "").replace(/\[([^\]]+)\]/g, ":$1")}`
if (staticPath(address) === address) return { route, kB: staticScript, budget: budgets["static pages"] }
return { route, kB: await kB(new Set([...entry, ...closure(key)])), budget: budgets[route] }
}),
)
const over = pages.filter((page) => !(page.kB <= page.budget))
if (over.length) {
console.error(
"check-client-bundle: initial JavaScript (gzipped) over its page's budget:\n " +
over.map((page) => `${page.route}: ${page.kB} kB, budget ${page.budget ?? "none"}`).join("\n "),
)
const bytes = await Bun.file(path.join(root, script.file)).bytes()
const text = new TextDecoder().decode(bytes)
// As they survive minification: the router's scroll key, seroval's errors, hydration's global.
const brought = ["solid-router", "Seroval", "_$HY"].filter((marker) => text.includes(marker))
if (brought.length) {
console.error(`check-client-bundle: the static pages' script brings ${brought.join(", ")}`)
process.exit(1)
}
const kB = Math.round(Bun.gzipSync(bytes, { level: 9 }).length / 100) / 10
if (!(kB <= budget)) {
console.error(`check-client-bundle: the static pages' script is ${kB} kB gzipped, over its budget of ${budget} kB`)
process.exit(1)
}
console.log(
"check-client-bundle: initial JavaScript within budget (kB gzipped): " +
pages
.toSorted((a, b) => b.kB - a.kB)
.map((page) => `${page.route} ${page.kB}`)
.join(", "),
`check-client-bundle: the app ships no scripts; the static pages' script is ${kB} kB gzipped (budget ${budget})`,
)
+12 -6
View File
@@ -21,8 +21,9 @@ const root = path.resolve(import.meta.dir, "..")
// Markdown twin, src/docs/middleware.ts). The docs' old /v2 address and a V1 docs path redirect. The
// last three are files the Worker serves, or the assets layer before it (_headers). Every answer
// carries the stage's headers (src/lib/noindex.ts): dev's noindex, none in production. The V1 docs'
// pages are noindex in both. The static pages (src/static/routes.ts) must come back as plain HTML: no
// hydration keys, no serialized data, and their own script rather than the app's.
// pages are noindex in both. Every page must come back as plain HTML (src/static/render.tsx): no
// hydration keys or markers, no serialized data, and one module script, the static pages' own; the
// not-found page too, in any language, and for the development tools' addresses (/devices).
const pages: {
path: string
status?: number
@@ -40,7 +41,10 @@ const pages: {
{ path: "/ja", status: 200, static: true },
{ path: "/desktop", status: 200, static: true },
{ path: "/ar/product", status: 200, static: true },
{ path: "/check-worker-start-404", status: 404 },
{ path: "/font", status: 200, static: true },
{ path: "/check-worker-start-404", status: 404, static: true },
{ path: "/ja/check-worker-start-404", status: 404, static: true },
{ path: "/devices", status: 404, static: true },
{ path: "/docs/", status: 200 },
{ path: "/docs/config/", status: 200, accept: "text/markdown" },
{ path: "/v2/docs/config/", status: 301, location: "/docs/config/" },
@@ -125,8 +129,10 @@ const results = await Promise.resolve()
status: response.status,
location: response.headers.get("location") ?? undefined,
robots: response.headers.get("x-robots-tag") ?? undefined,
hydrated: /data-hk=|_\$HY|\$R\[|entry-client-/.test(body),
scripted: /<script type="module" src="\/_build\/assets\/entry-[\w-]+\.js">/.test(body),
hydrated: /data-hk=|_\$HY|\$R\[|entry-client-|<!--\$-->|<!--\/-->/.test(body),
scripted:
body.split('<script type="module"').length === 2 &&
/<script type="module" src="\/_build\/assets\/entry-[\w-]+\.js">/.test(body),
}
})
.catch(() => ({ status: 0, location: undefined, robots: undefined, hydrated: false, scripted: false }))
@@ -165,7 +171,7 @@ const failures = results
? ` with X-Robots-Tag ${result.actualRobots ?? "absent"} in ${stage}`
: "") +
(result.static && result.hydrated ? " with the hydrated app's markup, not as a static page" : "") +
(result.static && !result.scripted ? " without the static pages' script" : ""),
(result.static && !result.scripted ? " without the static pages' script as its only module script" : ""),
)
if (failures.length || errors.length) {
console.error(`check-worker-start: FAILED\n${[...errors, ...failures].map((line) => ` ${line}`).join("\n")}`)
+11 -66
View File
@@ -1,15 +1,15 @@
// The translation slices in the client build (script/i18n-slices.ts works out what goes in each):
// The translation slices in the static pages' script (script/static-client.ts; script/i18n-slices.ts
// works out what goes in each):
//
// - each locale gets a table module (virtual:i18n/<locale>) holding the shell's strings and where each
// other slice is, each slice a module of its own (virtual:i18n/<locale>/<slice>), and
// src/i18n/tables.ts becomes the 18 tables;
// - src/i18n/english.ts keeps only the English the browser reads in every language;
// - every import() of a lazy boundary (a page route, a module only ever loaded with import())
// loads the boundary's slice alongside it and resolves once both have arrived, so the boundary's
// code never runs before its strings (a top-level await in the boundary would do the same, but
// makes Rolldown split the shared chunks differently);
// - the server reads where the files went (virtual:i18n-preload) to preload a page's own
// (src/i18n/preload.ts), so no string costs a round trip before hydration.
// - every import() of a lazy boundary (a module only ever loaded with import()) loads the boundary's
// slice alongside it and resolves once both have arrived, so the boundary's code never runs before
// its strings (a top-level await in the boundary would do the same, but makes Rolldown split the
// shared chunks differently). The script's first file must not bring the runtime, so that import()
// loads the runtime with import() too.
//
// The development server and the Worker keep the source files whole.
import path from "node:path"
@@ -29,16 +29,9 @@ const englishFile = path.posix.join(root, "src/i18n/english.ts")
// An import() of a module, with any spaces or comments (such as /* @vite-ignore */) inside.
const dynamicImport = /\bimport\(\s*(?:\/\*[\s\S]*?\*\/\s*)*(["'])([^"'`]+)\1\s*\)/g
/**
* `app: false` for the static pages' script (script/static-client.ts): no route list to check, and
* its first file must not bring the runtime, so a boundary's import() loads the runtime with import()
* too. The app loads the runtime up front anyway.
*/
export function i18nSlices(options: { app?: boolean } = {}): Plugin {
export function i18nSlices(): Plugin {
let build = false
let slices: Slices | undefined
// Output file of each virtual module in the client build, by its id.
const files = new Map<string, string>()
const client = (environment: { name: string }) => build && environment.name === "client"
const analyze = () => {
if (slices) return slices
@@ -54,9 +47,6 @@ export function i18nSlices(options: { app?: boolean } = {}): Plugin {
const payload = locale.slices[analyze().shared[slice]]
return !Object.keys(payload.dict).length && !Object.keys(payload.content).length
})
const routes = () => Object.keys(analyze().boundaries).filter((file) => file.startsWith(`${root}src/routes/`))
// The page routes whose import() in SolidStart's route list loads their slice (checked in generateBundle).
const routed = new Set<string>()
return {
name: "i18n-slices",
@@ -68,9 +58,6 @@ export function i18nSlices(options: { app?: boolean } = {}): Plugin {
if (id.startsWith("virtual:i18n")) return `\0${id}`
},
load(id) {
// Read by the server only; the browser's copy is empty.
if (id === "\0virtual:i18n-preload")
return `export default ${JSON.stringify(build && this.environment.name !== "client" ? preloads() : null)}`
if (!client(this.environment)) return
const data = analyze()
if (id === englishFile) return `export const english = ${json(data.english)}`
@@ -99,61 +86,19 @@ export function i18nSlices(options: { app?: boolean } = {}): Plugin {
for (const match of code.matchAll(dynamicImport)) {
const target = await this.resolve(match[2], id)
const slice = target && boundary(target.id)
// A boundary without strings (the funnel's config) has nothing to wait for, but SolidStart's
// route list is checked below.
if (!target || !slice || (id !== "solid-start:routes" && empty(slice))) continue
// A boundary without strings (the funnel's config) has nothing to wait for.
if (!target || !slice || empty(slice)) continue
slices.set(match[0], slice)
if (id === "solid-start:routes") routed.add(slashes(target.id).split("?")[0])
}
if (!slices.size) return
return {
code: [
...(options.app === false
? [
`const __i18nWith = (module, slice) => Promise.all([module, import(${JSON.stringify(runtime)}).then((i18n) => i18n.loadSlice(slice)).catch(() => {})]).then((loaded) => loaded[0]);`,
]
: [
`import { loadSlice as __i18nSlice } from ${JSON.stringify(runtime)};`,
"const __i18nWith = (module, slice) => Promise.all([module, __i18nSlice(slice).catch(() => {})]).then((loaded) => loaded[0]);",
]),
`const __i18nWith = (module, slice) => Promise.all([module, import(${JSON.stringify(runtime)}).then((i18n) => i18n.loadSlice(slice)).catch(() => {})]).then((loaded) => loaded[0]);`,
code.replace(dynamicImport, (text) => (slices.has(text) ? `__i18nWith(${text}, ${JSON.stringify(slices.get(text))})` : text)),
].join("\n"),
map: null,
}
},
generateBundle(_, bundle) {
if (!client(this.environment)) return
// A page route whose import() wasn't rewritten would run before its strings arrive: fail the
// build instead (a change in how SolidStart writes its route list, for example).
const missed = options.app === false ? [] : routes().filter((file) => !routed.has(file))
if (missed.length)
throw new Error(`i18n-slices: SolidStart's route list doesn't load the strings of ${missed.join(", ")}`)
for (const chunk of Object.values(bundle))
if (chunk.type === "chunk" && chunk.facadeModuleId?.startsWith("\0virtual:i18n/"))
files.set(chunk.facadeModuleId.slice(1), `/${chunk.fileName}`)
},
}
/**
* For each locale, the files a page in it loads before hydration: its table (with the shell's
* strings) and its route's slice. `boundaries` has the other lazy boundaries' slices, for a page
* that knows before hydration it will load one (the Markdown view on a reload in it).
*/
function preloads() {
const data = analyze()
const src = `${root}src/`
const sliceFiles = (locale: string, routes: boolean) =>
Object.fromEntries(
Object.entries(data.boundaries)
.filter(([file]) => file.startsWith(`${src}routes/`) === routes)
.map(([file, slice]) => [file.slice(src.length), files.get(`virtual:i18n/${locale}/${data.shared[slice]}`) ?? null]),
)
return Object.fromEntries(
Object.keys(data.locales).map((locale) => [
locale,
{ table: files.get(`virtual:i18n/${locale}`), routes: sliceFiles(locale, true), boundaries: sliceFiles(locale, false) },
]),
)
}
}
+12 -11
View File
@@ -1,10 +1,11 @@
// Splits the translations by where the browser needs them, for the client build (vite.config.ts,
// i18nSlices). The source files stay as they are (src/i18n/<locale>.ts, src/i18n/content/<locale>.ts);
// this reads them and the app's import graph and works out, for each locale:
// Splits the translations by where the browser needs them, for the static pages' script
// (script/static-client.ts, i18nSlices). The source files stay as they are (src/i18n/<locale>.ts,
// src/i18n/content/<locale>.ts); this reads them and the app's import graph and works out, for each
// locale:
//
// - the shell slice: the dictionary keys and page copy the code every page loads can show
// (entry-client.tsx and app.tsx with their static imports), and what most page routes show;
// - one slice per lazy boundary, a module the browser loads on demand (each page route, and each
// - one slice per lazy boundary, a module the browser loads on demand (each island and overlay, any
// module only ever loaded with import()): what its static imports can show, minus the shell;
// - the full file: everything any client code can show, for switching to the language in place.
//
@@ -119,14 +120,14 @@ const routes = [...new Bun.Glob("routes/**/*.tsx").scanSync(src)]
.filter((file) => /export default/.test(readFileSync(file, "utf8")))
// The static pages' script (src/client/entry.ts) too, so what its islands and overlays load is a boundary.
const client = closure([...shellRoots, ...routes, path.join(src, "client/entry.ts")], true)
// Lazy boundaries: the page routes and every module the client loads with import(), even one that is
// also imported statically elsewhere (an import() can still be the first to load it). The development
// loader's imports of the source files, in src/i18n, don't count.
// Lazy boundaries: every module the static pages' script loads with import(), even one that is also
// imported statically elsewhere (an import() can still be the first to load it). The development
// loader's imports of the source files, in src/i18n, don't count, and nothing loads a page route in
// the browser in production (the development server keeps the source files whole).
const boundaries = [
...new Set([
...routes,
...[...client].flatMap((file) => scan(file).dynamic).filter((file) => !file.startsWith(path.join(src, "i18n"))),
]),
...new Set(
[...client].flatMap((file) => scan(file).dynamic).filter((file) => !file.startsWith(path.join(src, "i18n"))),
),
].toSorted()
// The shell: what the code every page loads can show, plus what most page routes show (the site's
+18 -9
View File
@@ -1,4 +1,4 @@
import { readFile } from "node:fs/promises"
import { readFile, rm } from "node:fs/promises"
import path from "node:path"
import { fileURLToPath } from "node:url"
import { build, type Plugin } from "vite"
@@ -15,12 +15,14 @@ const virtual = "virtual:static-client"
/**
* The static pages' script (src/client/entry.ts, with the islands and overlays it loads) in a build
* of its own, as the docs build theirs (src/docs/script/build.ts), so it never changes how the app's
* code is split: the two share source, never output files. It runs once the app's browser build is
* written, beside its files, and the Worker's build after it reads the script's file name from
* `virtual:static-client` (src/static/render.tsx). A stylesheet the app's build puts in the shell's
* or a group's file (script/stylesheet-groups.ts) is already on the page, so this build leaves it
* empty; the ones the app loads on demand (search, the Markdown view) come with their code.
* of its own, as the docs build theirs (src/docs/script/build.ts): the only JavaScript production
* serves, since every page is static there (src/static/render.tsx). The app's browser build still
* runs, for the stylesheets every page links (the shell's and each group's, script/stylesheet-groups.ts)
* and the manifest the Worker finds them in, but its scripts, which only hydration would load, are
* deleted once it is written. Then this runs, beside its files, and the Worker's build after it reads
* the script's file name from `virtual:static-client`. A stylesheet already in the shell's or a
* group's file is on the page, so this build leaves it empty; the ones loaded on demand (search, the
* Markdown view) come with their code.
*/
export function staticClient(): Plugin {
let script: string | undefined
@@ -29,8 +31,15 @@ export function staticClient(): Plugin {
resolveId: (id) => (id === virtual ? `\0${virtual}` : undefined),
// Development renders no static pages (src/static/routes.ts), so it has no script.
load: (id) => (id === `\0${virtual}` ? `export default ${JSON.stringify(script ?? null)}` : undefined),
async writeBundle(options) {
async writeBundle(options, bundle) {
if (this.environment.name !== "client" || !options.dir) return
// The app's own scripts: no production page loads them.
const dir = options.dir
await Promise.all(
Object.values(bundle)
.filter((file) => /\.m?js(\.map)?$/.test(file.fileName))
.map((file) => rm(path.join(dir, file.fileName))),
)
const shown = new Set(
[...this.getModuleIds()].filter(
(id) =>
@@ -61,7 +70,7 @@ export function staticClient(): Plugin {
solid({ solid: { hydratable: false } }),
devOnlyCss(),
cssVariantsForProduction(),
i18nSlices({ app: false }),
i18nSlices(),
],
build: {
outDir: options.dir,
+2 -6
View File
@@ -12,9 +12,8 @@ const shell = /[\\/]src[\\/](app|component[\\/]site[\\/]site)\.tsx$/
* 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.
* (search, the Markdown view, the Hex pop-up), which stay with their own code (script/static-client.ts).
* Chunks of stylesheets alone leave no JavaScript (Vite's pure CSS chunks).
*/
export function stylesheetGroups(): PluginOption {
return {
@@ -31,9 +30,6 @@ export function stylesheetGroups(): PluginOption {
{
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,
},
],
},
+3 -20
View File
@@ -1,7 +1,7 @@
import { Link, Title, Meta } from "@solidjs/meta"
import { Router, useBeforeLeave, useCurrentMatches, useIsRouting, useLocation } from "@solidjs/router"
import { Router, useCurrentMatches, useLocation } from "@solidjs/router"
import { FileRoutes } from "@solidjs/start/router"
import { createEffect, type JSX, Show, Suspense } from "solid-js"
import { type JSX, Show, Suspense } from "solid-js"
import { isServer } from "solid-js/web"
import { Favicon } from "@opencode/ui/favicon"
import { Font } from "@opencode/ui/font"
@@ -10,13 +10,11 @@ import "./style/fonts.css"
import "./app.css"
import { LanguageProvider } from "~/context/language"
import { I18nProvider, useI18n } from "~/context/i18n"
import { preloadStrings } from "~/i18n/preload"
import { config } from "~/config"
import { ogImage } from "~/lib/og"
import { strip } from "~/lib/language"
import { HeadMetaProvider, LiveMeta } from "~/component/head-meta"
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"
@@ -49,17 +47,6 @@ function AppMeta() {
const matches = useCurrentMatches()
// The 404 route and its /dev/404 previews (the dev server shows one for bad URLs).
const notFound = () => matches().some((match) => match.route.pattern.includes("404"))
preloadStrings()
// Preloaded pages' stylesheets wait for a navigation (lib/route-preloads.ts).
if (!isServer) {
const routing = useIsRouting()
// A leave that another listener blocked, or that stays on this page, never starts routing.
useBeforeLeave(() => {
setNavigating(true)
queueMicrotask(() => routing() || setNavigating(false))
})
createEffect(() => setNavigating(routing()))
}
return (
<>
<Title>opencode</Title>
@@ -93,10 +80,6 @@ if (!isServer) {
})
}
// The file routes, with preloads that leave the page alone when they fail (lib/route-preloads.ts). A
// component on both sides, as <FileRoutes /> was, so hydration counts it the same.
const Routes = () => (isServer ? FileRoutes() : quietPreloads(FileRoutes()))
export default function App() {
return (
<Router
@@ -108,7 +91,7 @@ export default function App() {
scrollRestoration
root={AppRoot}
>
<Routes />
<FileRoutes />
</Router>
)
}
+107 -101
View File
@@ -1,7 +1,9 @@
// The static pages' only script (src/static/render.tsx). The pages are plain HTML rendered from the
// site's components, with no hydration; this drives them with listeners delegated from the document,
// keyed on the attributes those components render, and loads the rest on intent: search, the Markdown
// view, the orb's pop-up, the logo menu, and each island's code (islands.ts).
// view, the orb's pop-up, the logo menu, and each island's code (islands.ts). The not-found page has
// none of the site's frame (Site): its arcade island brings its own, search and tooltips included
// (arcade/chrome.tsx), so it gets the islands only.
import { Funnel } from "~/lib/funnel"
import { installConsoleStub } from "~/lib/console-stub"
import type { SearchVia } from "~/component/site/search"
@@ -21,109 +23,113 @@ import { startTheme } from "./theme"
// The page reports to the Console's funnel from its markup, as every page does (lib/funnel.ts).
Funnel.start(() => import("~/lib/funnel-config").then((module) => module.funnelConfig()))
startTheme()
startMenus()
startCopy()
startFaq()
startContents()
startFrame()
const tip = $('[data-component="tooltip"]')
if (tip) startTooltips(tip)
if ($("[data-site][data-page]")) startShell()
startIslands()
revealHandedOff()
const idle = window.requestIdleCallback ?? ((run: () => void) => setTimeout(run, 1500))
// window.opencode and its hint for developers who open DevTools (lib/console-stub.ts).
idle(() => installConsoleStub())
// The corner orb, after the page.
addEventListener("load", () => idle(() => void import("./overlays/orb").then((module) => module.default())), {
once: true,
})
function startShell() {
startTheme()
startMenus()
startCopy()
startFaq()
startContents()
startFrame()
const tip = $('[data-component="tooltip"]')
if (tip) startTooltips(tip)
revealHandedOff()
// Search: ⌘K, Ctrl+K or "/" (when not typing). ⌘ or Ctrl on its own starts loading the palette, so a
// fast ⌘K finds results; once it is in the page it handles the shortcut itself, and a shortcut pressed
// while it loads opens it as it arrives.
const pending: { via?: SearchVia } = {}
let search: Promise<unknown> | undefined
let searching = false
const loadSearch = () =>
(search ??= import("./overlays/search").then((module) => module.default(pending)).then(() => (searching = true)))
on("keydown", (event) => {
if (searching) return
if (event.key === "Meta" || event.key === "Control") return void loadSearch()
if (event.defaultPrevented || event.altKey || event.repeat || target(event).closest("[contenteditable]")) return
const command = (event.metaKey || event.ctrlKey) && !event.shiftKey && event.key.toLowerCase() === "k"
const slash =
event.key === "/" && !event.metaKey && !event.ctrlKey && !target(event).closest("input, textarea, select")
if (!command && !slash) return
event.preventDefault()
pending.via = slash ? "slash" : "shortcut"
void loadSearch()
})
const idle = window.requestIdleCallback ?? ((run: () => void) => setTimeout(run, 1500))
// window.opencode and its hint for developers who open DevTools (lib/console-stub.ts).
idle(() => installConsoleStub())
// The corner orb, after the page.
addEventListener("load", () => idle(() => void import("./overlays/orb").then((module) => module.default())), {
once: true,
})
// The Markdown view: the footer's switch (a link to the page's .md, so a new tab still works), or "m"
// then "d". Its code and the page's Markdown load as the pointer reaches the switch, or on "m".
let markdown: typeof import("./overlays/markdown") | undefined
const loadMarkdown = () => import("./overlays/markdown").then((module) => (markdown = module))
const prefetchMarkdown = () => void loadMarkdown().then((module) => module.prefetch())
const markdownSwitch = '[data-funnel^="markdown-view:"]'
for (const type of ["pointerover", "focusin"] as const)
on(type, (event) => target(event).closest(markdownSwitch) && prefetchMarkdown())
on("click", (event) => {
const button = target(event).closest(markdownSwitch)
if (button) {
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
// Search: ⌘K, Ctrl+K or "/" (when not typing). ⌘ or Ctrl on its own starts loading the palette, so a
// fast ⌘K finds results; once it is in the page it handles the shortcut itself, and a shortcut pressed
// while it loads opens it as it arrives.
const pending: { via?: SearchVia } = {}
let search: Promise<unknown> | undefined
let searching = false
const loadSearch = () =>
(search ??= import("./overlays/search").then((module) => module.default(pending)).then(() => (searching = true)))
on("keydown", (event) => {
if (searching) return
if (event.key === "Meta" || event.key === "Control") return void loadSearch()
if (event.defaultPrevented || event.altKey || event.repeat || target(event).closest("[contenteditable]")) return
const command = (event.metaKey || event.ctrlKey) && !event.shiftKey && event.key.toLowerCase() === "k"
const slash =
event.key === "/" && !event.metaKey && !event.ctrlKey && !target(event).closest("input, textarea, select")
if (!command && !slash) return
event.preventDefault()
return void loadMarkdown().then((module) =>
module.toggle(undefined, !!button.closest('[data-component="site-footer"]')),
)
}
// The logo always leads to the real home page, so it leaves the Markdown view.
if (target(event).closest('[data-slot="logo"]')) markdown?.leave()
})
if (site.hasAttribute("data-markdown-boot")) void loadMarkdown().then((module) => module.toggle(true))
on(
"keydown",
markdownShortcut({
prefetch: prefetchMarkdown,
toggle: () => void loadMarkdown().then((module) => module.toggle()),
shown: () => site.hasAttribute("data-markdown"),
}),
)
pending.via = slash ? "slash" : "shortcut"
void loadSearch()
})
// Number keys open the matching nav item and 0 the home page, unless the reader is typing or using a
// shortcut (as Site does from its nav data); Escape closes what's open.
on("keydown", (event) => {
if (event.metaKey || event.ctrlKey || event.altKey || event.repeat) return
if (target(event).closest("input, textarea, select, [contenteditable]")) return
const link =
event.key === "0"
? $<HTMLAnchorElement>('[data-slot="logo"]')
: $$<HTMLAnchorElement>('[data-component="nav"] li[data-nav-id] > a').find((item) =>
$(`[data-slot="number"][data-n="${event.key}"]`, item),
)
if (!link) return
event.preventDefault()
// A shortcut is not keyboard navigation through the page: no focus ring is left behind.
;(document.activeElement as HTMLElement | null)?.blur()
if (link.target === "_blank") return void open(link.href, "_blank", "noopener")
location.assign(link.href)
})
on("keydown", (event) => event.key === "Escape" && !event.defaultPrevented && closeMenus())
// A product page's previous and next links (product-page.tsx): the left and right arrow keys follow
// them, unless focus is somewhere that uses those keys itself, or a menu, sheet or dialog is open.
on("keydown", (event) => {
if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return
if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey || event.defaultPrevented) return
const busy =
'input, textarea, select, [contenteditable], [role="tablist"], [data-slot="track"], [data-slot="menu"], [popover], dialog'
if (target(event).closest(busy) || $(":popover-open, dialog[open]")) return
const link = $$<HTMLAnchorElement>('[data-component="product-cycle"] a')[inlineKey(event) === "ArrowLeft" ? 0 : 1]
if (link) location.assign(link.href)
})
// The skip link moves focus to the content, leaving the address as it is.
on("click", (event) => {
if (!target(event).closest('[data-component="skip-link"]')) return
event.preventDefault()
$("#content")?.focus()
})
// The Markdown view: the footer's switch (a link to the page's .md, so a new tab still works), or "m"
// then "d". Its code and the page's Markdown load as the pointer reaches the switch, or on "m".
let markdown: typeof import("./overlays/markdown") | undefined
const loadMarkdown = () => import("./overlays/markdown").then((module) => (markdown = module))
const prefetchMarkdown = () => void loadMarkdown().then((module) => module.prefetch())
const markdownSwitch = '[data-funnel^="markdown-view:"]'
for (const type of ["pointerover", "focusin"] as const)
on(type, (event) => target(event).closest(markdownSwitch) && prefetchMarkdown())
on("click", (event) => {
const button = target(event).closest(markdownSwitch)
if (button) {
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
event.preventDefault()
return void loadMarkdown().then((module) =>
module.toggle(undefined, !!button.closest('[data-component="site-footer"]')),
)
}
// The logo always leads to the real home page, so it leaves the Markdown view.
if (target(event).closest('[data-slot="logo"]')) markdown?.leave()
})
if (site.hasAttribute("data-markdown-boot")) void loadMarkdown().then((module) => module.toggle(true))
on(
"keydown",
markdownShortcut({
prefetch: prefetchMarkdown,
toggle: () => void loadMarkdown().then((module) => module.toggle()),
shown: () => site.hasAttribute("data-markdown"),
}),
)
// Number keys open the matching nav item and 0 the home page, unless the reader is typing or using a
// shortcut (as Site does from its nav data); Escape closes what's open.
on("keydown", (event) => {
if (event.metaKey || event.ctrlKey || event.altKey || event.repeat) return
if (target(event).closest("input, textarea, select, [contenteditable]")) return
const link =
event.key === "0"
? $<HTMLAnchorElement>('[data-slot="logo"]')
: $$<HTMLAnchorElement>('[data-component="nav"] li[data-nav-id] > a').find((item) =>
$(`[data-slot="number"][data-n="${event.key}"]`, item),
)
if (!link) return
event.preventDefault()
// A shortcut is not keyboard navigation through the page: no focus ring is left behind.
;(document.activeElement as HTMLElement | null)?.blur()
if (link.target === "_blank") return void open(link.href, "_blank", "noopener")
location.assign(link.href)
})
on("keydown", (event) => event.key === "Escape" && !event.defaultPrevented && closeMenus())
// A product page's previous and next links (product-page.tsx): the left and right arrow keys follow
// them, unless focus is somewhere that uses those keys itself, or a menu, sheet or dialog is open.
on("keydown", (event) => {
if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return
if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey || event.defaultPrevented) return
const busy =
'input, textarea, select, [contenteditable], [role="tablist"], [data-slot="track"], [data-slot="menu"], [popover], dialog'
if (target(event).closest(busy) || $(":popover-open, dialog[open]")) return
const link = $$<HTMLAnchorElement>('[data-component="product-cycle"] a')[inlineKey(event) === "ArrowLeft" ? 0 : 1]
if (link) location.assign(link.href)
})
// The skip link moves focus to the content, leaving the address as it is.
on("click", (event) => {
if (!target(event).closest('[data-component="skip-link"]')) return
event.preventDefault()
$("#content")?.focus()
})
}
+8
View File
@@ -47,6 +47,14 @@ const islands: {
when: "near",
load: () => import("./islands/download-list"),
},
// The font page's typewriter, then its plates as they come near (one module, islands/font.tsx).
{ selector: '[data-component="font-hero"]', when: "idle", load: () => import("./islands/font") },
{
selector: '[data-component="specimen"] > *, [data-plate="film"]',
when: "near",
load: () => import("./islands/font"),
},
{ selector: '[data-component="arcade-404"]', when: "idle", load: () => import("./islands/arcade") },
]
export function startIslands() {
@@ -0,0 +1,33 @@
import { MetaProvider } from "@solidjs/meta"
import { Router } from "@solidjs/router"
import { Arcade404 } from "~/component/site/arcade/arcade"
import { I18nProvider } from "~/context/i18n"
import { LanguageProvider } from "~/context/language"
import { swap } from "../solid"
/**
* The not-found page's arcade (arcade.tsx, in production's mode, not-found-page.tsx), with its own
* frame, search and tooltips (chrome.tsx): rendered again in the browser in place of the server's
* copy, whose screen the first-paint script already pinned in place, so the token can be dragged
* into the slot. Its frame reads the language and adds head tags, so it gets the app's providers, as
* search does (overlays/search.tsx); the router has no routes.
*/
export default function arcade(root: HTMLElement) {
void swap(
() => (
<Router
explicitLinks={true}
root={() => (
<LanguageProvider>
<I18nProvider>
<MetaProvider>
<Arcade404 mode="layers" />
</MetaProvider>
</I18nProvider>
</LanguageProvider>
)}
/>
),
root,
)
}
+38
View File
@@ -0,0 +1,38 @@
import type { Component } from "solid-js"
import { Analysis, Kerning, Performance } from "~/component/font/analysis"
import { Construction, Timeline } from "~/component/font/construction"
import { Anagrams, Colophon, Cover, Tester } from "~/component/font/display"
import { Exploded } from "~/component/font/exploded"
import { Field } from "~/component/font/field"
import { Loupe } from "~/component/font/loupe"
import { Typewriter } from "~/component/font/typewriter"
import { Universe } from "~/component/font/universe"
import { FilmPlate } from "~/component/font-film/section"
import { swap } from "../solid"
// The parts of the font page (routes/font) that move or answer the reader: the hero's typewriter, and
// the plates, by id (Exploded's by the scroll track around it). The other plates (Passports, Poster,
// Waterfall) are still pictures and stay as the server rendered them.
const views: Record<string, Component> = {
"font-hero": Typewriter,
film: FilmPlate,
cover: Cover,
construction: Construction,
timeline: Timeline,
"exploded-scroll": Exploded,
analysis: Analysis,
kerning: Kerning,
performance: Performance,
anagrams: Anagrams,
field: Field,
loupe: Loupe,
tester: Tester,
universe: Universe,
colophon: Colophon,
}
/** Renders one of them again in the browser, in place of the server's copy, in the same task. */
export default function font(root: HTMLElement) {
const View = views[root.dataset.plate ?? root.dataset.slot ?? root.dataset.component ?? ""]
if (View) void swap(() => <View />, root)
}
@@ -7,7 +7,11 @@ import { Exploded } from "./exploded"
import { Passports } from "./passports"
import { Universe } from "./universe"
/** Everything below the hero: a type specimen in sixteen plates, in its own layout system. */
/**
* Everything below the hero: a type specimen in sixteen plates, in its own layout system. Production
* serves them as plain HTML, and client/islands/font.tsx renders each plate that moves or answers
* the reader again in the browser: a new one of those goes there too.
*/
export function Specimen() {
return (
<div data-component="specimen">
@@ -16,6 +16,8 @@ import { ogImage } from "~/lib/og"
* hydration, so the server's layers markup always hydrates). Phones get the layers stack with its
* still light and the hybrid's phone flow (arcade/phone.ts), which loads no WebGL there. Each mode's
* setting comes first in its `when`, so production folds the modes it never shows out of the bundle.
* Production's page is plain HTML, and its script renders production's mode again in the browser
* (client/islands/arcade.tsx): change both.
*/
export function NotFoundPage(props: { title: string; status: number }) {
const [phone, setPhone] = createSignal(false)
@@ -1,29 +0,0 @@
type Connection = { saveData?: boolean; effectiveType?: string }
// Pages already preloaded in this visit, so each destination loads once.
const preloaded = new Set<string>()
/**
* Touch screens have no hover to tell where the reader is heading, and the router's own touchstart
* preload never runs (it waits for a mouse button), so the page a link leads to (`accepts` picks
* which) has its code and strings loaded as soon as a finger lands on the link, each page once.
* Scrolling past links loads nothing. Not with Save-Data or on a connection slower than 4G, never for
* the current page, a new-tab, download or language link. Returns a cleanup.
*/
export function preloadTouchedLinks(accepts: (link: HTMLAnchorElement) => boolean, preload: (path: string) => void) {
const connection = (navigator as Navigator & { connection?: Connection }).connection
if (connection?.saveData || (connection?.effectiveType && connection.effectiveType !== "4g")) return () => {}
const touched = (event: PointerEvent) => {
if (event.pointerType !== "touch") return
const anchor = (event.target as Element | null)?.closest?.("a[href]")
if (!(anchor instanceof HTMLAnchorElement) || anchor.target) return
if (anchor.hasAttribute("download") || anchor.hasAttribute("hreflang")) return
const url = new URL(anchor.href)
if (url.origin !== location.origin || url.pathname === location.pathname || preloaded.has(url.pathname)) return
if (!accepts(anchor)) return
preloaded.add(url.pathname)
preload(url.pathname)
}
document.addEventListener("pointerdown", touched, { passive: true })
return () => document.removeEventListener("pointerdown", touched)
}
+7 -16
View File
@@ -6,7 +6,7 @@ import "./github-link.css"
import "./tap-targets.css"
import "./asset-buttons.css"
import { Link, Meta } from "@solidjs/meta"
import { A, useLocation, useNavigate, usePreloadRoute } from "@solidjs/router"
import { A, useLocation, useNavigate } from "@solidjs/router"
import {
createEffect,
createMemo,
@@ -38,7 +38,7 @@ import { installConsoleStub } from "~/lib/console-stub"
import { status, type ServiceStatus } from "~/lib/status"
import { pageData } from "~/lib/page-data"
import { staticRender } from "~/lib/static-render"
import { staticPath, staticPaths } from "~/static/routes"
import { staticPaths } from "~/static/routes"
import { clientStrings } from "~/client/strings"
import { useViewportCover } from "~/lib/viewport"
import { markdownShortcut } from "./markdown-key"
@@ -71,7 +71,6 @@ import { bannerDismissScript, bannerThemeColorScript, bannerTopColor, bannerVisi
import { Tooltips } from "./tooltip"
import { SiteSearch } from "./search"
import { navMenusOnIntent } from "./nav-intent"
import { preloadTouchedLinks } from "./preload-touched"
import { adoptVoice, dropVoice } from "./voice/host"
// The shared nav menus in the site's colours.
import "./nav-menus.css"
@@ -119,13 +118,12 @@ const SiteBanner =
// A nav item as the nav renders it: a known one (links.ts) or a custom link (nav-order.tsx).
type NavItemView = { id: string; label: string; href: string; arrow: boolean; external: boolean; company: boolean }
// Pages of this site that render client-side; everything else keeps a full page load. The docs
// (/docs) are served separately, /download redirects on the server, and the static pages
// (static/routes.ts) never hydrate in production.
// Pages of this site that render client-side on the development server (production hydrates none,
// static/routes.ts); everything else keeps a full page load. The docs (/docs) are served separately,
// and /download redirects on the server.
const clientPages = /^\/(?:desktop|mobile|terminal|sdk|changelog(?:\/v\d[\w.+-]*)?|brand|press|legal(?:\/.*)?)?\/?$/
function clientPage(pathname: string) {
const path = strip(pathname)
return clientPages.test(path) && (import.meta.env.DEV || !staticPath(path))
return clientPages.test(strip(pathname))
}
// The full page loads a link here can lead to on this domain (this site's other pages, in any
// language, the static ones among them, the docs and Stats), fetched once the pointer rests on the
@@ -228,7 +226,6 @@ export function Site(props: {
const enter = !isServer && navigated && !document.documentElement.hasAttribute("data-card-grow")
const routed = !isServer && navigated
onMount(() => (navigated = true))
const preloadRoute = usePreloadRoute()
// The page runs under the notch and home indicator; edge elements pad by the safe-area insets.
useViewportCover()
// Read the saved theme before the first client render so hydration doesn't flip it back to
@@ -673,8 +670,7 @@ export function Site(props: {
// The app's router only handles links marked with a `link` attribute (explicitLinks), so the
// older console pages and proxied paths like /docs keep full page loads. Links between pages
// of this site get the attribute as soon as a pointer, focus or click reaches them, so the
// router swaps the page in place and preloads it on intent: hover or focus, and on touch screens,
// which have no hover, a finger landing on the link.
// router swaps the page in place and preloads it on intent (hover or focus).
const markLink = (event: Event) => {
const anchor = (event.target as Element | null)?.closest?.("a[href]")
if (!(anchor instanceof HTMLAnchorElement) || anchor.hasAttribute("link") || anchor.target) return
@@ -683,10 +679,6 @@ export function Site(props: {
}
for (const type of ["pointerover", "focusin", "touchstart", "click"])
document.addEventListener(type, markLink, true)
const stopPreloads = preloadTouchedLinks(
(link) => link.hasAttribute("link") || clientPage(new URL(link.href).pathname),
(path) => preloadRoute(path, { preloadData: false }),
)
const idle = window.requestIdleCallback ?? ((run: () => void) => setTimeout(run, 1500))
// window.opencode and its hint for developers who open DevTools (Settings › Other › Console API).
@@ -780,7 +772,6 @@ export function Site(props: {
navMenus = undefined
document.removeEventListener("opencode-nav-menu-open", closeSiteMenus)
stopMenuLinks()
stopPreloads()
for (const type of ["pointerover", "focusin", "touchstart", "click"])
document.removeEventListener(type, markLink, true)
media.removeEventListener("change", syncDark)
+3 -2
View File
@@ -6,8 +6,9 @@ import { Funnel } from "~/lib/funnel"
// Every page, the not-found page too, reports to the Console's funnel from its markup (lib/funnel.ts).
Funnel.start(() => import("~/lib/funnel-config").then((module) => module.funnelConfig()))
// The strings every page shows arrive before hydration (the server preloads them, i18n/preload.ts),
// so the first client render matches the server's. Each page route loads its own before it runs.
// The development server's app: production hydrates no page (src/static/render.tsx), and its pages
// load the static pages' script instead (src/client/entry.ts). The strings every page shows load
// before hydration, so the first client render matches the server's.
void loadSlice("shell")
.catch(() => undefined)
.then(() => mount(() => <StartClient />, document.getElementById("app")!))
+4 -41
View File
@@ -1,49 +1,16 @@
// @refresh reload
import { createHandler, StartServer } from "@solidjs/start/server"
import { getRequestEvent, ssr } from "solid-js/web"
import { dir, pageLocale, tag, type Locale } from "~/lib/language"
import { dir, pageLocale, tag } from "~/lib/language"
import { sourceLogo } from "~/lib/source-logo"
import { freezeScript } from "~/lib/freeze"
import { clientViteManifest } from "solid-start:client-vite-manifest"
import { markdownKey } from "~/component/site/use-markdown"
import preloads from "virtual:i18n-preload"
// Every language, before any page renders.
import "~/i18n/server"
const criticalCSS = `[data-component="top"]{min-height:80px;display:flex;align-items:center}html[data-scroll-restore] #app{opacity:0}`
// A reload, or a return from another site, lands on a history entry the router left a scroll position
// for (createScrollRestoration in @solidjs/router keeps them in sessionStorage by the entry's depth).
// WebKit paints the top of the page while it's still parsing and restores only once the page has
// loaded, so the reader saw the top and then a jump. When there's a position to go back to, the page
// stays hidden (its background still paints) until the document has been parsed, and the script after
// #app scrolls there before anything paints; the timer shows it anyway if that never runs.
const scrollHoldScript = `try{const n=performance.getEntriesByType("navigation")[0],d=history.state&&history.state._depth,y=n&&n.type!=="navigate"&&d!=null&&JSON.parse(sessionStorage.getItem("solid-router:scroll")||"{}")[d];if(y>0){const r=document.documentElement;r.dataset.scrollRestore=y;setTimeout(()=>delete r.dataset.scrollRestore,2000)}}catch{}`
const scrollRestoreScript = `{const r=document.documentElement,y=+r.dataset.scrollRestore;if(y){scrollTo(0,y);delete r.dataset.scrollRestore}}`
// A reload in the Markdown view keeps the page hidden until the view shows (site.tsx), so the view's
// code (markdown-pages.ts, loaded on first use) and its strings in the page's language are fetched
// alongside the page's own code. The development server has no manifest, so it fetches them once
// the page runs.
const markdownChunks = (() => {
const closure = (key: string, seen = new Set<string>()): Set<string> => {
if (seen.has(key) || !clientViteManifest[key]) return seen
seen.add(key)
clientViteManifest[key].imports?.forEach((next) => closure(next, seen))
return seen
}
const entry = closure("src/entry-client.tsx")
return [...closure("src/component/site/markdown-pages.ts")]
.filter((key) => !entry.has(key))
.map((key) => `${import.meta.env.BASE_URL.replace(/\/+$/, "")}/${clientViteManifest[key].file}`)
})()
const markdownPreload = (locale: Locale) => {
const strings = preloads?.[locale].boundaries["component/site/markdown-pages.ts"]
const files = strings ? [...markdownChunks, strings] : markdownChunks
if (!files.length) return undefined
return `try{if(sessionStorage.getItem(${JSON.stringify(markdownKey)})==="1")for(const href of ${JSON.stringify(files)}){const link=document.createElement("link");link.rel="modulepreload";link.href=href;document.head.append(link)}}catch{}`
}
const criticalCSS = `[data-component="top"]{min-height:80px;display:flex;align-items:center}`
// The hydrated app's document: the development server's (production renders every page as plain HTML,
// src/static/render.tsx).
export default createHandler(
() => (
<StartServer
@@ -51,7 +18,6 @@ export default createHandler(
const evt = getRequestEvent()
// The language comes from the URL only (dev #56564), never the cookie, so / is always English.
const locale = evt ? pageLocale(evt.request) : "en"
const restoreMarkdown = markdownPreload(locale)
return (
<html lang={tag(locale)} dir={dir(locale)} data-locale={locale}>
@@ -60,15 +26,12 @@ export default createHandler(
{/* After the charset meta: the art is over 1 KB, and the meta must come in the first 1024 bytes. */}
{ssr([`\n${sourceLogo}\n`]) as unknown as Element}
<style>{criticalCSS}</style>
<script innerHTML={scrollHoldScript} />
{/* Development only, before Vite's client loads: the device preview's Freeze (lib/freeze.ts). */}
{import.meta.env.DEV && <script innerHTML={freezeScript} />}
{assets}
{restoreMarkdown && <script innerHTML={restoreMarkdown} />}
</head>
<body>
<div id="app">{children}</div>
<script innerHTML={scrollRestoreScript} />
{scripts}
</body>
</html>
-9
View File
@@ -1,14 +1,5 @@
/// <reference types="@solidjs/start/env" />
// Where the client build put each locale's translation slices (script/i18n-plugin.ts); null in development.
declare module "virtual:i18n-preload" {
const preloads: Record<
import("~/lib/language").Locale,
{ table?: string; routes: Record<string, string | null>; boundaries: Record<string, string | null> }
> | null
export default preloads
}
// The static pages' script, from its own build (script/static-client.ts); null in development.
declare module "virtual:static-client" {
const script: string | null
-26
View File
@@ -1,26 +0,0 @@
import { useCurrentMatches } from "@solidjs/router"
import { isServer, ssr, useAssets } from "solid-js/web"
import { staticRender } from "~/lib/static-render"
import preloads from "virtual:i18n-preload"
import { useLanguage } from "~/context/language"
/**
* Server only: preloads the page's strings in its language (the locale's table, which holds the
* shell's, and the page route's slice), so they arrive with the page's scripts rather than after
* them. Written like Vite's own preloads, so lib/head-links.ts gives them the same priority. The
* client build writes where each file went (script/i18n-plugin.ts); the development server has none.
* Called inside a component (AppMeta) rather than rendered as one, so the component tree, and the ids
* Solid derives from it, stay as they were. The static pages (src/static/render.tsx) load no strings.
*/
export function preloadStrings() {
if (!isServer || !preloads || staticRender()) return
const language = useLanguage()
const matches = useCurrentMatches()
const files = preloads[language.locale()]
const routes = matches().flatMap((match) => {
const src = (match.route.key as { $component?: { src?: string } }).$component?.src
return src ? [files.routes[src.replaceAll("\\", "/").replace(/^src\//, "").replace(/\?.*$/, "")]] : []
})
const hrefs = [files.table, ...routes].filter((href) => typeof href === "string")
useAssets(() => ssr(hrefs.map((href) => `<link href="${href}" rel="modulepreload" />`).join("")) as unknown as Element)
}
+13 -22
View File
@@ -1,36 +1,27 @@
import type { createMiddleware } from "@solidjs/start/middleware"
import { getRequestEvent } from "solid-js/web"
// A page's head links, in production. Its stylesheets (the shell's and its group's,
// script/stylesheet-groups.ts) are also named in a Link header, so the browser, and Cloudflare's Early
// Hints before the page is ready, can start them sooner. Its module preloads get fetchpriority="low":
// they still start with the page, but the stylesheets, the fonts and the largest image go first on a
// slow connection, and the page's script (the same files, the same order) hydrates once they have
// arrived. Inside the HTML cache (middleware.ts), so cached pages carry both.
// In production, a page's stylesheets (the shell's and its group's, script/stylesheet-groups.ts) are
// also named in a Link header, so the browser, and Cloudflare's Early Hints before the page is ready,
// can start them sooner. Inside the HTML cache (middleware.ts), so cached pages carry it.
type Middleware = ReturnType<typeof createMiddleware>[number]
export const headLinks: Middleware = async (_event, next) => {
const value = await next()
if (import.meta.env.DEV || typeof value !== "string") return value
const page = pageHead(value)
const link = stylesheetLinks(value)
// On the request's response headers, which the HTML cache keeps with the page (lib/html-cache.ts).
if (page.link) getRequestEvent()?.response.headers.set("Link", page.link)
return page.html
if (link) getRequestEvent()?.response.headers.set("Link", link)
return value
}
/** The page with its module preloads at low priority, and the Link header for its stylesheets. */
export function pageHead(html: string) {
/** The Link header for the stylesheets in a page's head, if it has any. */
export function stylesheetLinks(html: string) {
const end = html.indexOf("</head>")
if (end < 0) return { html }
const head = html.slice(0, end)
const stylesheets = [...head.matchAll(/<link href="(\/_build\/assets\/[\w-]+\.css)" rel="stylesheet" ?\/?>/g)]
return {
html:
head.replace(
/(<link href="\/_build\/assets\/[\w-]+\.js" rel="modulepreload")( ?\/?>)/g,
'$1 fetchpriority="low"$2',
) + html.slice(end),
link: stylesheets.map((match) => `<${match[1]}>; rel=preload; as=style`).join(", ") || undefined,
}
if (end < 0) return
const stylesheets = [
...html.slice(0, end).matchAll(/<link href="(\/_build\/assets\/[\w-]+\.css)" rel="stylesheet" ?\/?>/g),
]
return stylesheets.map((match) => `<${match[1]}>; rel=preload; as=style`).join(", ") || undefined
}
-65
View File
@@ -1,65 +0,0 @@
// The parts of SolidStart's file routes (FileRoutes) that preloading uses.
type Route = {
component?: { preload?: () => unknown }
$component?: { import: () => Promise<unknown> }
children?: Route[]
}
const quiet = new WeakSet<object>()
// Stylesheets that preloads added between navigations, held off until the next navigation starts.
const held = new Set<HTMLLinkElement>()
// True until the first page has rendered, and from the start of each navigation until it settles.
let navigating = true
/**
* SolidStart reloads the page when a route's code fails to load (reloadOnRouteChunkError), so a page
* left open across a deploy picks up the new build. The router's preloads (a link hovered, focused or
* touched) run the same loader, so one that failed on a flaky connection reloaded the page under the
* reader, and one that Safari or Firefox cancelled as the reader followed a link to another page
* reloaded the page they were leaving instead. Here a
* route's preload loads its code without that reload and hands it to the route once it has loaded;
* one that fails leaves the route as it was, to load (and recover) when it's opened.
*
* Loading a route's code also adds its stylesheets (Vite's preload helper does, and never again for
* the same file). Added between navigations, they would restyle the page being read with another
* page's rules, at once and again whenever it changes, so they're held off (media "not all": fetched
* and parsed, never applied) until a navigation starts (setNavigating).
*/
export function quietPreloads<T extends Route>(routes: T[]) {
routes.forEach((route) => {
if (route.children) quietPreloads(route.children)
const component = route.component
const load = route.$component?.import
const preload = component?.preload
if (!component || !load || !preload || quiet.has(component)) return
quiet.add(component)
component.preload = () => {
const before = navigating ? undefined : new Set(document.querySelectorAll('link[rel="stylesheet"]'))
const loading = load()
// The helper adds the stylesheets synchronously, before any of them has loaded or applied.
if (before)
document.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]').forEach((link) => {
if (before.has(link)) return
link.media = "not all"
held.add(link)
})
return loading.then(
() => preload(),
() => undefined,
)
}
})
return routes
}
/**
* Whether a navigation is under way (from the router's beforeLeave until it settles). The page being
* opened needs its stylesheets, so a navigation's start applies every held one, before the router
* renders the page, and preloads add theirs as before until it settles.
*/
export function setNavigating(on: boolean) {
navigating = on
if (!on) return
held.forEach((link) => link.removeAttribute("media"))
held.clear()
}
+22 -6
View File
@@ -9,7 +9,7 @@ import { AppRoot } from "~/app"
import { dir, pageLocale, strip, tag } from "~/lib/language"
import type { StaticPass } from "~/lib/page-data"
import { sourceLogo } from "~/lib/source-logo"
import { staticPath } from "./routes"
import { matches, staticPath } from "./routes"
import {
cardMorphKey,
clearCardMorph,
@@ -24,12 +24,27 @@ import { cardTiming } from "~/component/site/products"
type Middleware = ReturnType<typeof createMiddleware>[number]
type PageModule = { default: Component; id$$?: string }
// The page routes' modules, by path (`/changelog/:tag`; an index route's ends in a slash, `/brand/`), as
// SolidStart's router loads them.
const pages = fileRoutes as { path: string; page?: boolean; $component?: { import: () => Promise<PageModule> } }[]
// The file routes, by path (`/changelog/:tag`; an index route's ends in a slash, `/brand/`), as
// SolidStart's router loads them: the pages' modules, and the API routes' handlers by method (`$GET`).
const pages = fileRoutes as {
path: string
page?: boolean
$component?: { import: () => Promise<PageModule> }
[handler: string]: unknown
}[]
/** Whether an API route or a server function (SolidStart's /_server) answers a request, not a page. A HEAD
* request is answered by the route's GET handler. */
const answered = (path: string, method: string) =>
path.startsWith("/_server") ||
pages.some(
(route) =>
!route.page && (route[`$${method}`] || (method === "HEAD" && route.$GET)) && matches(route.path, path),
)
/**
* Production only: the static routes (routes.ts) as plain HTML with no hydration. The page renders
* Production only: the static routes (routes.ts) as plain HTML with no hydration, and the not-found
* page (`[...404].tsx`, with its 404 status) for every address no route answers. The page renders
* with the same components, providers and head tags as the hydrated app, inside NoHydration and
* synchronously (renderToString), so the HTML has no hydration keys and no serialized data, and the
* page loads one script of its own (src/client/entry.ts) instead of the app. Its data (the status
@@ -41,7 +56,8 @@ export const staticPages: Middleware = async (_event, next) => {
if (import.meta.env.DEV || !event || (event.request.method !== "GET" && event.request.method !== "HEAD"))
return next()
const url = new URL(event.request.url)
const pattern = staticPath(strip(url.pathname))
const path = strip(url.pathname)
const pattern = staticPath(path) ?? (answered(path, event.request.method) ? undefined : "/*404")
const load =
pattern && pages.find((route) => route.page && route.path.replace(/(.)\/$/, "$1") === pattern)?.$component?.import
if (!load) return next()
+11 -4
View File
@@ -1,9 +1,10 @@
/**
* The pages the Worker renders as plain HTML, without hydration (src/static/render.tsx): their own
* small script drives them (src/client/entry.ts), and links to them load the whole page. Each is a
* page route's path in SolidStart's form (`:tag` for a parameter). Take one out and it is the hydrated
* app's again, on the server and in the browser. The development server keeps them all hydrated:
* Design mode and Settings need the app. perf/serve.ts serves a production build to try them.
* page route's path in SolidStart's form (`:tag` for a parameter). Any other address that no API
* route answers gets the not-found page, rendered the same way, so production serves no hydrated
* page at all. The development server keeps them all hydrated: Design mode and Settings need the
* app. perf/serve.ts serves a production build to try them.
*/
export const staticPaths = [
"/",
@@ -22,9 +23,15 @@ export const staticPaths = [
"/changelog",
"/changelog/:tag",
"/product/browse",
"/font",
]
/** The static route a path (without its locale) is, if any. No imports, so the browser can use it too. */
export function staticPath(path: string) {
return staticPaths.find((pattern) => new RegExp(`^${pattern.replace(/:\w+/g, "[^/]+")}/?$`).test(path))
return staticPaths.find((pattern) => matches(pattern, path))
}
/** Whether a path is one a route's pattern (`:tag` a segment, a trailing `*rest` the rest) matches. */
export function matches(pattern: string, path: string) {
return new RegExp(`^${pattern.replace(/\*\w*$/, ".*").replace(/:\w+/g, "[^/]+")}/?$`).test(path)
}
+7 -15
View File
@@ -1,22 +1,14 @@
import { expect, test } from "bun:test"
import { pageHead } from "~/lib/head-links"
import { stylesheetLinks } from "~/lib/head-links"
const css = (name: string) => `<link href="/_build/assets/${name}.css" rel="stylesheet" />`
const js = (name: string) => `<link href="/_build/assets/${name}.js" rel="modulepreload" />`
test("a page's stylesheets stay as they are and are named in its Link header", () => {
const html = `<html><head>${css("shell-a")}${css("home-b")}${js("entry")}</head><body>${css("late")}</body></html>`
const page = pageHead(html)
expect(page.html).toContain(`${css("shell-a")}${css("home-b")}`)
expect(page.link).toBe(
"</_build/assets/shell-a.css>; rel=preload; as=style, </_build/assets/home-b.css>; rel=preload; as=style",
)
test("a page's stylesheets in its head are named in its Link header", () => {
expect(
stylesheetLinks(`<html><head>${css("shell-a")}${css("home-b")}</head><body>${css("late")}</body></html>`),
).toBe("</_build/assets/shell-a.css>; rel=preload; as=style, </_build/assets/home-b.css>; rel=preload; as=style")
})
test("module preloads in the head start at low priority", () => {
const page = pageHead(`<head>${js("entry")}</head><body>${js("body")}</body>`)
expect(page.html).toBe(
`<head><link href="/_build/assets/entry.js" rel="modulepreload" fetchpriority="low" /></head><body>${js("body")}</body>`,
)
expect(page.link).toBeUndefined()
test("a page without stylesheets in its head gets no Link header", () => {
expect(stylesheetLinks(`<head></head><body>${css("body")}</body>`)).toBeUndefined()
})
+7 -6
View File
@@ -7,12 +7,13 @@ import { LOCALES } from "~/lib/language"
const src = path.join(import.meta.dir, "../src")
test("every page route is a boundary with its own slice", () => {
const routes = [...new Bun.Glob("routes/**/*.tsx").scanSync(src)]
.map((file) => path.join(src, file))
.filter((file) => readFileSync(file, "utf8").includes("export default"))
expect(routes.length).toBeGreaterThan(10)
expect(routes.filter((file) => !result.boundaries[file.replaceAll("\\", "/")])).toEqual([])
test("every island and overlay is a boundary with its own slice, and no page route is", () => {
const files = (glob: string) =>
[...new Bun.Glob(glob).scanSync(src)].map((file) => path.join(src, file).replaceAll("\\", "/"))
const lazy = files("client/{islands,overlays}/*.{ts,tsx}")
expect(lazy.length).toBeGreaterThan(10)
expect(lazy.filter((file) => !result.boundaries[file])).toEqual([])
expect(files("routes/**/*.tsx").filter((file) => result.boundaries[file])).toEqual([])
})
test("every locale has a value for every key its slices name", () => {
-73
View File
@@ -1,73 +0,0 @@
import { describe, expect, test } from "bun:test"
import { quietPreloads } from "~/lib/route-preloads"
// A file route as SolidStart builds it: a lazy component whose preload is the reloading loader, and
// the route's own import of its code.
function route(code: () => Promise<unknown>) {
const calls = { preload: 0, import: 0 }
return {
calls,
route: {
component: { preload: () => void calls.preload++ },
$component: {
import: () => {
calls.import++
return code()
},
},
},
}
}
describe("quietPreloads", () => {
test("hands a route its code once the code has loaded", async () => {
const page = route(() => Promise.resolve({}))
quietPreloads([page.route])
await page.route.component.preload()
expect(page.calls).toEqual({ preload: 1, import: 1 })
})
test("leaves the route as it was when its code fails to load", async () => {
const page = route(() => Promise.reject(new TypeError("Failed to fetch dynamically imported module")))
quietPreloads([page.route])
expect(await page.route.component.preload()).toBeUndefined()
expect(page.calls).toEqual({ preload: 0, import: 1 })
})
// quietPreloads relies on the shape SolidStart gives each file route, and skips any route without
// it, so a SolidStart or Solid upgrade that changes it would turn the fix off without a sound. If
// one of these fails, check that preloads still can't reload the page (src/lib/route-preloads.ts),
// then update the expectations.
test("SolidStart's file routes still have the shape it relies on", async () => {
const start = (file: string) =>
Bun.file(new URL(`../node_modules/@solidjs/start/dist/${file}`, import.meta.url)).text()
// The route's own import of its code, unwrapped: `$component: { src, build, import }`.
expect(await start("config/fs-routes/index.js")).toContain("import: `_$() => import('${buildId}')$_`")
const router = await start("router.jsx")
// Each route keeps its `$component`, and its component is a lazy one over the reloading loader.
expect(router).toContain("...route,")
expect(router).toContain("lazy(loadComponent(route))")
expect(router).toContain("withRouteChunkReload(route.$component.import)")
// The router preloads a route through its component's `preload`, which a lazy component has.
expect(await Bun.file(new URL("../node_modules/@solidjs/router/dist/index.js", import.meta.url)).text()).toContain(
"route.component && route.component.preload && route.component.preload()",
)
expect(await Bun.file(new URL("../node_modules/solid-js/dist/solid.js", import.meta.url)).text()).toContain(
"wrap.preload = () =>",
)
})
test("reaches nested routes and wraps each preload once", async () => {
const page = route(() => Promise.resolve({}))
const routes = [{ children: [page.route] }]
quietPreloads(routes)
quietPreloads(routes)
await page.route.component.preload()
expect(page.calls).toEqual({ preload: 1, import: 1 })
})
})
+13 -2
View File
@@ -3,7 +3,7 @@ import { fileURLToPath } from "node:url"
// SolidStart's own file router, which builds the route manifest the static renderer finds pages in.
import { DEFAULT_EXTENSIONS } from "../node_modules/@solidjs/start/dist/config/constants.js"
import { SolidStartServerFileRouter } from "../node_modules/@solidjs/start/dist/config/fs-router.js"
import { staticPath, staticPaths } from "~/static/routes"
import { matches, staticPath, staticPaths } from "~/static/routes"
const router = new SolidStartServerFileRouter({
dir: fileURLToPath(new URL("../src/routes", import.meta.url)),
@@ -18,6 +18,10 @@ describe("static routes", () => {
expect(staticPaths.filter((path) => !pages.includes(path))).toEqual([])
})
test("cover every page route but the development tools, which production answers with the not-found page", () => {
expect(pages.filter((path) => !staticPath(path)).toSorted()).toEqual(["/*404", "/devices", "/video-editor"])
})
test("match their pages' addresses and nothing else", () => {
expect(staticPath("/brand")).toBe("/brand")
expect(staticPath("/legal")).toBe("/legal")
@@ -26,8 +30,15 @@ describe("static routes", () => {
expect(staticPath("/changelog")).toBe("/changelog")
expect(staticPath("/")).toBe("/")
expect(staticPath("/desktop")).toBe("/desktop")
expect(staticPath("/font")).toBeUndefined()
expect(staticPath("/font")).toBe("/font")
expect(staticPath("/nope")).toBeUndefined()
expect(staticPath("/legal/nope/deeper")).toBeUndefined()
expect(staticPath("/brand/extra")).toBeUndefined()
})
test("a trailing *rest matches the rest of the path, as the API routes' patterns do", () => {
expect(matches("/video-editor/api/*path", "/video-editor/api/a/b")).toBe(true)
expect(matches("/stylesheet/:file", "/stylesheet/a.css")).toBe(true)
expect(matches("/stylesheet/:file", "/stylesheet/a/b.css")).toBe(false)
})
})
-29
View File
@@ -3,7 +3,6 @@ import { solidStart } from "@solidjs/start/config"
import { nitro } from "nitro/vite"
import { fromPathname } from "./src/lib/language"
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"
@@ -67,7 +66,6 @@ export default defineConfig({
stylesheetGroups(),
staticClient(),
docs(),
i18nSlices(),
],
server: {
allowedHosts: true,
@@ -104,38 +102,11 @@ export default defineConfig({
cssTarget: ["chrome123", "edge123", "firefox120", "safari17.5"],
},
environments: {
// The browser bundles are minified; the Worker keeps readable code for its stack traces.
client: {
build: {
// Nitro copies public/ with fs.cp, which keeps the symlinks into packages/ui as links.
// Letting Vite copy it first writes real files.
copyPublicDir: true,
// Oxc, Vite 8's own minifier. "esbuild" here left the bundles unminified: Vite only adds its
// esbuild minifier when the top-level build.minify asks for it, and that stays off for the Worker.
minify: "oxc",
// strobe builds with STROBE_SOURCEMAP=hidden: maps beside the scripts without a
// sourceMappingURL comment, so the scripts stay byte for byte and profiles name source lines.
sourcemap: process.env.STROBE_SOURCEMAP === "hidden" ? "hidden" : undefined,
rolldownOptions: {
output: {
// Rolldown gives the code that pages share one chunk per set of pages sharing it, which
// had the home page preload 29 files, most under 3 kB. Plain modules (not components,
// which may bring their stylesheet to every page that loads the chunk) of up to 4 kB
// that 12 or more of the bundle's entries (page routes and lazily loaded modules)
// import go in one chunk instead: fewer requests and a little less code on most pages.
// Each language's strings keep their own files (script/i18n-plugin.ts).
codeSplitting: {
groups: [
{
name: "common",
test: (id) => !/\.(tsx|jsx|css)(\?|$)/.test(id) && !id.startsWith("\0virtual:i18n"),
minShareCount: 12,
maxModuleSize: 4000,
},
],
},
},
},
},
},
},