feat: Add syntax highlighting to Code Text (#6007)

Closes #4119

Supersedes #5999 after GitHub closed it during the head-branch rename.

## Approach

Code Text uses one optional public highlighting boundary:

- `@webstudio-is/sdk-components-react/code-text` → `src/code-text.tsx`

The ordinary `components` entry remains Shiki-free. Canvas loading,
metadata options, theme variables, and the plain semantic `<code>`
component remain private implementation details.

**Code** uses the code editor. **Language** and **Theme** use normal
bindable selects. Fixed selections generate direct imports for only the
per-page language/theme union; plaintext imports no grammar. Bound
selections generate Shiki's lazy language/theme registries.

SSR and client rendering share the same factory. Missing bound assets
suspend the first render while SSR resolves the selected modules. SSG
now waits for Suspense before serializing HTML. During hydration the
completed server markup stays in place while the browser fetches only
the selected language and theme. Later client-side binding changes load
only the new selections and keep the same `<code>` node and focus.

Highlighted output preserves the semantic root, ref, author
classes/styles, whitespace, escaped source, and legacy children/native
`lang` behavior. Shiki's implicit tab stop is disabled. A color-only
transformer strips theme typography so asynchronous highlighting cannot
change text geometry.

## Bundle impact

Measured from same-commit production React Router + Cloudflare builds
containing one JavaScript / GitHub Light Code Text instance. Sizes are
the sum of emitted JavaScript files; gzip is the sum of each file
compressed independently.

| Worker output | Files | Raw | Sum gzip |
| --- | ---: | ---: | ---: |
| Fixed selections | 3 | 1,341,851 B | 288,342 B |
| Bound selections | 310 | 10,372,112 B | 1,872,273 B |
| Increase | +307 | +9,030,261 B (8.61 MiB) | +1,583,931 B (1.51 MiB) |

The bound browser build also emits the catalog as lazy chunks:
+9,012,594 raw bytes / +1,578,779 sum-gzip bytes across the complete
deployed output. Those chunks are not all delivered on page load. The
production SSG regression verifies 100+ catalog chunks are emitted while
the HTML directly module-preloads only one shared runtime chunk; the
browser fetches the runtime-selected language/theme modules on demand.

## Tradeoffs and compatibility

- Instances with both highlighting properties unset keep the legacy
plain renderer.
- Static highlighting still requires both **Language** and **Theme**.
- Binding either selection includes that catalog in deploy output
because its runtime value is not known at publish time.
- The syntax-highlighting property is `language`; legacy native HTML
`lang` remains preserved.
- Invalid or unavailable runtime selections render as plain code.
- Fixed selections retain the smallest publish output; bound selections
trade deploy/worker size for runtime flexibility.

## Todo

- [x] Restore the specialized Code Text component and semantic plain
fallback
- [x] Use a code editor for Code and bindable selects for Language and
Theme
- [x] Persist JavaScript / GitHub Light template defaults
- [x] Collapse highlighting to one public `./code-text` entry
- [x] Keep canvas loaders and option/theme helpers private
- [x] Generate direct imports for fixed selections and omit plaintext
grammar
- [x] Generate lazy catalogs when Language or Theme is bound
- [x] Preserve highlighted SSR markup during hydration without
node/focus movement
- [x] Support Suspense-aware highlighted SSG output
- [x] Preserve escaping, accessibility, legacy children, and native
`lang`
- [x] Measure fixed versus bound Cloudflare worker output
- [x] Deep-review correctness, DRYness, package surface, and obsolete
binding infrastructure
- [x] Review documentation impact and update Code Text documentation
- [x] Run focused tests, typechecks, production builds, formatting, and
staged diff review
- [ ] Fixture pipeline — blocked during sync because the current API
rejects this local CLI version as incompatible; no fixture output
changed

## Verification

- [x] New/changed regressions were demonstrated failing without their
behavior and passing after restoration
- [x] SDK Code Text metadata, rendering, hydration, and bundle tests: 17
passed
- [x] Component registry tests: 3 passed
- [x] CLI asset collection and full prebuild suite: 59 passed
- [x] SDK components, component registry, SDK, and CLI typechecks
- [x] SDK components declaration and production builds
- [x] Component registry production build
- [x] Production Vite + Vike prerender emits highlighted bound SSG HTML
with one doctype
- [x] Dynamic catalog chunks remain outside the SSG page's direct
preload set
- [x] Documentation reviewed and updated
- [x] Formatting and staged diff checks
This commit is contained in:
Oleg Isonen authored and GitHub committed 2026-08-04 18:25:36 +02:00
1 parent 6b82b413b9
commit 6385e290c6
66 files changed
+2830 -229

No files matched your search

+2 -1
View File
@@ -36,7 +36,7 @@ export const createFramework = async (
await cleanupFrameworkTemplates(options);
const reactRouter = "@webstudio-is/sdk-components-react-router";
const { components, metas } = createFrameworkComponentRegistry({
const { components, metas, buildHooks } = createFrameworkComponentRegistry({
routerComponents: reactRouterComponents,
routerComponentPackage: reactRouter,
});
@@ -44,6 +44,7 @@ export const createFramework = async (
return {
metas,
components,
componentBuildHooks: buildHooks,
tags: {
textarea: `${baseComponentImportSource}:Textarea`,
input: `${baseComponentImportSource}:Input`,
+2 -1
View File
@@ -36,7 +36,7 @@ export const createFramework = async (
await cleanupFrameworkTemplates(options);
const remix = "@webstudio-is/sdk-components-react-remix";
const { components, metas } = createFrameworkComponentRegistry({
const { components, metas, buildHooks } = createFrameworkComponentRegistry({
routerComponents: remixComponents,
routerComponentPackage: remix,
});
@@ -44,6 +44,7 @@ export const createFramework = async (
return {
metas,
components,
componentBuildHooks: buildHooks,
tags: {
textarea: `${baseComponentImportSource}:Textarea`,
input: `${baseComponentImportSource}:Input`,
+2 -1
View File
@@ -47,11 +47,12 @@ export const createFramework = async (
// cleanup route templates after reading to not bloat generated code
await cleanupFrameworkTemplates(options);
const { components, metas } = createFrameworkComponentRegistry();
const { components, metas, buildHooks } = createFrameworkComponentRegistry();
return {
metas,
components,
componentBuildHooks: buildHooks,
tags: {
textarea: `${baseComponentImportSource}:Textarea`,
input: `${baseComponentImportSource}:Input`,
+2 -1
View File
@@ -1,6 +1,6 @@
import { rm } from "node:fs/promises";
import { join } from "node:path";
import type { WsComponentMeta } from "@webstudio-is/sdk";
import type { ComponentBuildHook, WsComponentMeta } from "@webstudio-is/sdk";
export type FrameworkOptions = { preserveTemplates?: boolean };
export const routeTemplatesDirectory = join("app", "route-templates");
@@ -23,6 +23,7 @@ export type Framework = {
metas: Record<string, WsComponentMeta>;
// instance.component: "importSource:importSpecifier"
components: Record<string, string>;
componentBuildHooks: ComponentBuildHook[];
// instance.tag: "importSource:importSpecifier"
tags: Record<string, string>;
html: (params: {
+315 -14
View File
@@ -15,8 +15,14 @@ import { pathToFileURL } from "node:url";
import { tmpdir } from "node:os";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import {
defaultTreeAdapter,
parse as parseHtml,
type DefaultTreeAdapterMap,
} from "parse5";
import { build } from "esbuild";
import { bundleVersion } from "@webstudio-is/protocol";
import type { Asset } from "@webstudio-is/sdk";
import type { Asset, Instance, Prop } from "@webstudio-is/sdk";
import {
createDocumentGraph,
type AssetFileDocument,
@@ -124,6 +130,45 @@ const getFilePaths = async (dir: string): Promise<string[]> => {
return paths.flat();
};
const getImportSources = async (source: string) => {
const result = await build({
stdin: { contents: source, loader: "tsx" },
bundle: false,
format: "esm",
metafile: true,
write: false,
});
return Object.values(result.metafile.outputs).flatMap((output) =>
output.imports.map(({ path }) => path)
);
};
const findElementsByTagName = (
node: DefaultTreeAdapterMap["node"],
tagName: string
): DefaultTreeAdapterMap["element"][] => {
const elements: DefaultTreeAdapterMap["element"][] = [];
if (defaultTreeAdapter.isElementNode(node) && node.tagName === tagName) {
elements.push(node);
}
if ("childNodes" in node) {
for (const child of node.childNodes) {
elements.push(...findElementsByTagName(child, tagName));
}
}
return elements;
};
const getTextContent = (node: DefaultTreeAdapterMap["node"]): string => {
if (defaultTreeAdapter.isTextNode(node)) {
return node.value;
}
if ("childNodes" in node) {
return node.childNodes.map(getTextContent).join("");
}
return "";
};
const createSiteData = (
overrides: {
assets?: Asset[];
@@ -136,18 +181,8 @@ const createSiteData = (
meta: Record<string, unknown>;
isDraft?: boolean;
}>;
instances?: Array<
[
string,
{
type?: "instance";
id: string;
component: string;
tag?: string;
children: Array<{ type: "id"; value: string }>;
},
]
>;
instances?: Array<[string, Omit<Instance, "type">]>;
props?: Array<[string, Prop]>;
pageMeta?: Record<string, unknown>;
redirects?: Redirects;
} = {}
@@ -227,7 +262,7 @@ const createSiteData = (
},
],
},
props: [],
props: overrides.props ?? [],
instances: (
overrides.instances ?? [
[
@@ -250,6 +285,62 @@ const createSiteData = (
};
};
const createCodeTextSiteData = (
selections: Array<{
id: string;
code?: string;
language?: string | { type: "expression"; value: string };
theme?: string | { type: "expression"; value: string };
lang?: string;
children?: Instance["children"];
}>
) => {
const instances: Array<[string, Omit<Instance, "type">]> = [
[
"root",
{
id: "root",
component: "Box",
children: selections.map(({ id }) => ({ type: "id", value: id })),
},
],
];
const props: Array<[string, Prop]> = [];
for (const selection of selections) {
instances.push([
selection.id,
{
id: selection.id,
component: "CodeText",
children: selection.children ?? [],
},
]);
for (const [name, value] of [
["code", selection.code],
["language", selection.language],
["theme", selection.theme],
["lang", selection.lang],
] as const) {
if (value === undefined) {
continue;
}
const id = `${selection.id}-${name}`;
props.push([
id,
{
id,
instanceId: selection.id,
name,
...(typeof value === "string"
? { type: "string" as const, value }
: value),
},
]);
}
}
return createSiteData({ instances, props });
};
const writeSiteData = async (
siteData: ReturnType<typeof createSiteData> = createSiteData()
) => {
@@ -636,6 +727,216 @@ test("hydrates encoded filenames from an embedded SSG database", async () => {
});
describe("prebuild", () => {
test("imports only configured Code Text language and theme assets", async () => {
await writeSiteData(
createCodeTextSiteData([
{
id: "code-1",
code: "const answer = 42;",
language: "javascript",
theme: "github-light",
},
{
id: "code-2",
code: "const answer = 42;",
language: "javascript",
theme: "nord",
},
])
);
await prebuild({ assets: false, template: ["react-router"] });
const generatedPage = await readFile(
"app/__generated__/_index.tsx",
"utf8"
);
const importSources = await getImportSources(generatedPage);
expect(
importSources.filter((source) => source === "@shikijs/langs/javascript")
).toHaveLength(1);
expect(importSources).toEqual(
expect.arrayContaining([
"@shikijs/themes/github-light",
"@shikijs/themes/nord",
"@webstudio-is/sdk-components-react/code-text",
])
);
expect(importSources).not.toContain("@shikijs/langs/css");
expect(importSources).not.toContain("@shikijs/themes/dracula");
});
test("generates lazy loaders for bound selections", async () => {
await writeSiteData(
createCodeTextSiteData([
{
id: "code-1",
code: "const answer = 42;",
language: { type: "expression", value: '"javascript"' },
theme: { type: "expression", value: '"github-light"' },
},
])
);
await prebuild({ assets: false, template: ["react-router"] });
const generatedPage = await readFile(
"app/__generated__/_index.tsx",
"utf8"
);
const importSources = await getImportSources(generatedPage);
expect(importSources).toEqual(
expect.arrayContaining(["shiki/langs", "shiki/themes"])
);
expect(importSources).not.toContain("@shikijs/langs/javascript");
expect(importSources).not.toContain("@shikijs/themes/github-light");
expect(generatedPage).not.toContain("import.meta.env.SSR");
expect(generatedPage).not.toContain("await Promise.all");
expect(generatedPage).toContain("suspense: true");
expect(generatedPage).toContain("loader?.().then");
});
test("prerenders configured and legacy Code Text in SSG output", async () => {
await writeSiteData(
createCodeTextSiteData([
{
id: "code-highlighted",
code: "const answer = 42;",
language: "javascript",
theme: "github-light",
},
{
id: "code-plaintext",
code: "plain <value>",
language: "plaintext",
theme: "nord",
},
{
id: "code-legacy",
lang: "en",
children: [{ type: "text", value: "legacy <code>" }],
},
])
);
await prebuild({ assets: false, template: ["ssg"] });
const generatedPage = await readFile(
"app/__generated__/_index.tsx",
"utf8"
);
const importSources = await getImportSources(generatedPage);
expect(importSources).toEqual(
expect.arrayContaining([
"@shikijs/langs/javascript",
"@shikijs/themes/github-light",
"@shikijs/themes/nord",
])
);
expect(importSources).not.toContain("@shikijs/langs/plaintext");
expect(importSources).not.toContain("@shikijs/langs/css");
expect(importSources).not.toContain("@shikijs/themes/dracula");
expect(
JSON.parse(await readFile("package.json", "utf8")).dependencies
).toMatchObject({
"@shikijs/langs": "4.4.1",
"@shikijs/themes": "4.4.1",
shiki: "4.4.1",
});
await symlink(join(originalCwd, "node_modules"), "node_modules", "dir");
await runGeneratedCommand("vite", ["build"]);
await runGeneratedCommand("vike", ["prerender"]);
const html = parseHtml(await readFile("dist/client/index.html", "utf8"));
const codeElements = findElementsByTagName(html, "code");
const [highlightedCode, plaintextCode, legacyCode] = codeElements;
if (
highlightedCode === undefined ||
plaintextCode === undefined ||
legacyCode === undefined
) {
throw new Error("Expected three prerendered Code Text elements");
}
expect(
Object.fromEntries(
highlightedCode.attrs.map(({ name, value }) => [name, value])
)
).toMatchObject({
class: "w-code-text",
});
expect(
Object.fromEntries(
highlightedCode.attrs.map(({ name, value }) => [name, value])
)
).not.toHaveProperty("tabindex");
expect(
findElementsByTagName(highlightedCode, "span").length
).toBeGreaterThan(0);
expect(getTextContent(highlightedCode)).toBe("const answer = 42;");
expect(
Object.fromEntries(
plaintextCode.attrs.map(({ name, value }) => [name, value])
)
).toMatchObject({
class: "w-code-text",
style: expect.stringContaining(
"--w-code-text-theme-background:#2e3440ff"
),
});
expect(getTextContent(plaintextCode)).toBe("plain <value>");
expect(
Object.fromEntries(
legacyCode.attrs.map(({ name, value }) => [name, value])
)
).toMatchObject({ class: "w-code-text", lang: "en" });
expect(findElementsByTagName(legacyCode, "span")).toHaveLength(0);
expect(getTextContent(legacyCode)).toBe("legacy <code>");
}, 30_000);
test("prerenders bound Code Text while keeping catalog chunks lazy", async () => {
await writeSiteData(
createCodeTextSiteData([
{
id: "code-bound",
code: "const answer = 42;",
language: { type: "expression", value: '"javascript"' },
theme: { type: "expression", value: '"github-light"' },
},
])
);
await prebuild({ assets: false, template: ["ssg"] });
await symlink(join(originalCwd, "node_modules"), "node_modules", "dir");
await runGeneratedCommand("vite", ["build"]);
await runGeneratedCommand("vike", ["prerender"]);
const htmlSource = await readFile("dist/client/index.html", "utf8");
expect(htmlSource).toMatch(/^<!DOCTYPE html><html/);
const html = parseHtml(htmlSource);
const [codeElement] = findElementsByTagName(html, "code");
if (codeElement === undefined) {
throw new Error("Expected a prerendered Code Text element");
}
expect(findElementsByTagName(codeElement, "span").length).toBeGreaterThan(
0
);
expect(getTextContent(codeElement)).toBe("const answer = 42;");
const clientPaths = await getFilePaths("dist/client");
const catalogChunks = clientPaths.filter(
(path) => path.includes("/chunks/") && path.endsWith(".js")
);
expect(catalogChunks.length).toBeGreaterThan(100);
const referencedChunks = catalogChunks.filter((chunk) => {
const filename = chunk.split("/").at(-1);
return filename !== undefined && htmlSource.includes(filename);
});
expect(referencedChunks).toHaveLength(1);
}, 60_000);
test("emits the identity marker only for local previews", async () => {
await prebuild({
assets: false,
+35 -2
View File
@@ -54,6 +54,7 @@ import {
type Resource,
type WsComponentMeta,
type Pages,
type ComponentBuildContribution,
} from "@webstudio-is/sdk";
import { migratePages } from "@webstudio-is/project-migrations/pages";
import { collectFontFamiliesFromStyleDecls } from "@webstudio-is/project-build/runtime";
@@ -1126,10 +1127,30 @@ export const prebuild = async (options: {
}
}
const props = new Map(pageData.build.props);
const componentBuildContributions = new Map<
string,
ComponentBuildContribution
>();
for (const hook of framework.componentBuildHooks) {
const contribution = await hook.build({
instances,
props,
meta: framework.metas[hook.component],
scope,
});
if (contribution !== undefined) {
componentBuildContributions.set(hook.component, contribution);
}
}
// generate component imports
// Map<importSource, Map<id, importSpecifier>>
const imports = new Map<string, Map<string, string>>();
for (const instance of instances.values()) {
if (componentBuildContributions.has(instance.component)) {
continue;
}
let descriptor = framework.components[instance.component];
let id = instance.component;
if (instance.component === elementComponent && instance.tag) {
@@ -1158,10 +1179,22 @@ export const prebuild = async (options: {
importsString += `import { ${specifiersString} } from "${importSource}";\n`;
}
const componentBuildDeclarations: string[] = [];
for (const contribution of componentBuildContributions.values()) {
for (const buildImport of contribution.imports) {
if (buildImport.imported === undefined) {
importsString += `import ${buildImport.local} from ${JSON.stringify(buildImport.source)};\n`;
} else {
importsString += `import { ${buildImport.imported} as ${buildImport.local} } from ${JSON.stringify(buildImport.source)};\n`;
}
}
componentBuildDeclarations.push(...contribution.declarations);
}
const componentBuildSetupString = componentBuildDeclarations.join("\n");
const pageFontAssets = fontAssetsByPage[page.id];
const pageBackgroundImageAssets = backgroundImageAssetsByPage[page.id];
const props = new Map(pageData.build.props);
const dataSources = new Map(pageData.build.dataSources);
const resources = new Map(pageData.build.resources);
replaceFormActionsWithResources({
@@ -1219,7 +1252,7 @@ export const prebuild = async (options: {
import { Fragment, useState } from "react";
import { renderText, useResource, useVariableState } from "@webstudio-is/react-sdk/runtime";
${importsString}
${importsString}${componentBuildSetupString}
export const projectId = "${siteData.build.projectId}";