diff --git a/packages/docs-next/src/openapi/api-page-samples.test.tsx b/packages/docs-next/src/openapi/api-page-samples.test.tsx index 3018b394..0fe47320 100644 --- a/packages/docs-next/src/openapi/api-page-samples.test.tsx +++ b/packages/docs-next/src/openapi/api-page-samples.test.tsx @@ -2,7 +2,9 @@ import assert from "node:assert/strict"; import test, { type TestContext } from "node:test"; import { FrameworkProvider } from "fumadocs-core/framework"; import type { Document } from "fumadocs-openapi"; -import { act } from "react"; +import { act, type ReactElement } from "react"; +import { createRoot } from "react-dom/client"; +import { renderToString } from "react-dom/server"; import { mountClient } from "../../test/dom.js"; import { ApiPage } from "./api-page.js"; import { withCodeSamples } from "./code-samples.js"; @@ -32,13 +34,8 @@ async function renderSamples(t: TestContext): Promise { return mountSamples(t); } -async function mountSamples(t: TestContext): Promise { - t.after(() => { - localStorage.clear(); - sessionStorage.clear(); - }); - const container = await mountClient( - t, +function samplesPage(): ReactElement { + return ( "/"} useParams={() => ({})} @@ -50,8 +47,16 @@ async function mountSamples(t: TestContext): Promise { operations={[{ path: "/api/v2/buildinfo", method: "get" }]} payload={{ bundled: operation as Document }} /> - , + ); +} + +async function mountSamples(t: TestContext): Promise { + t.after(() => { + localStorage.clear(); + sessionStorage.clear(); + }); + const container = await mountClient(t, samplesPage()); await settle(); return container; } @@ -86,6 +91,46 @@ function highlightedTokens(panel: HTMLElement): string { return String(panel.querySelectorAll(".line span[style]").length > 0); } +// These run first: the highlighter is module-level, so later tests would find it already warm. +test("the first synchronous render highlights the visible cURL sample", (t) => { + localStorage.clear(); + sessionStorage.clear(); + const container = document.body.appendChild(document.createElement("div")); + const root = createRoot(container); + t.after(() => { + act(() => root.unmount()); + container.remove(); + localStorage.clear(); + sessionStorage.clear(); + }); + act(() => root.render(samplesPage())); + const shown = shownRegion(container); + assert.equal( + shown.getAttribute("aria-label") ?? + shown.querySelector("[aria-label]")?.getAttribute("aria-label"), + "cURL sample", + ); + assert.equal(highlightedTokens(shown), "true"); +}); + +test("the server renders the samples highlighted, with no suspended placeholder", () => { + const doc = new DOMParser().parseFromString(renderToString(samplesPage()), "text/html"); + assert.equal( + String(doc.querySelectorAll('template[id^="B:"]').length), + "0", + "pending boundaries", + ); + const markers = []; + const walker = doc.createTreeWalker(doc, NodeFilter.SHOW_COMMENT); + for (let node = walker.nextNode(); node; node = walker.nextNode()) markers.push(node.nodeValue); + assert.equal(markers.includes("$?"), false, "no pending Suspense marker"); + const panels = [...doc.querySelectorAll('.coder-sample-tabs [role="tabpanel"]')].filter( + (panel) => !panel.hasAttribute("hidden"), + ); + assert.equal(String(panels.length), "1", "one shown panel"); + assert.equal(String((panels[0]?.querySelectorAll(".line span[style]").length ?? 0) > 0), "true"); +}); + test("a sample tab revisited after it was highlighted is highlighted at the first render", async (t) => { const container = await renderSamples(t); assert.equal(highlightedTokens(shownRegion(container)), "true", "cURL, the first tab"); diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index 3a23c3dd..8f8d5911 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -1,6 +1,7 @@ "use client"; -import { createShikiFactory, createShikiHighlighter } from "fumadocs-core/highlight/shiki"; +import type { Highlighter } from "fumadocs-core/highlight"; +import { createShikiFactory } from "fumadocs-core/highlight/shiki"; import type { CodeBlockProps } from "fumadocs-openapi"; import { useOperation } from "fumadocs-openapi/operation"; import { createCodeUsageGeneratorRegistry } from "fumadocs-openapi/requests/generators"; @@ -11,48 +12,43 @@ import { TabsContent, TabsList, TabsTrigger } from "fumadocs-ui/components/tabs" import { Tabs as TabsRoot } from "fumadocs-ui/components/tabs.unstyled"; import { escapeTabValue } from "@coder/docs-ui"; import { type ComponentProps, useState } from "react"; +import { createHighlighterCoreSync } from "shiki/core"; +import { createJavaScriptRegexEngine } from "shiki/engine/javascript"; +import go from "shiki/langs/go.mjs"; +import javascript from "shiki/langs/javascript.mjs"; +import json from "shiki/langs/json.mjs"; +import python from "shiki/langs/python.mjs"; +import shellscript from "shiki/langs/shellscript.mjs"; +import typescript from "shiki/langs/typescript.mjs"; +import githubDarkDefault from "shiki/themes/github-dark-default.mjs"; +import githubLightHighContrast from "shiki/themes/github-light-high-contrast.mjs"; import { SamplesNote } from "./samples-note.js"; // Only the grammars and themes an API page uses (JSON, the code samples, TypeScript definitions), on the JavaScript regex engine (no WASM, no eval). -const shiki = createShikiFactory({ - async init() { - const [{ createHighlighterCore }, { createJavaScriptRegexEngine }] = await Promise.all([ - import("shiki/core"), - import("shiki/engine/javascript"), - ]); - return createHighlighterCore({ - engine: createJavaScriptRegexEngine(), - langs: [ - import("shiki/langs/json.mjs"), - import("shiki/langs/shellscript.mjs"), - import("shiki/langs/typescript.mjs"), - import("shiki/langs/javascript.mjs"), - import("shiki/langs/python.mjs"), - import("shiki/langs/go.mjs"), - ], - themes: [ - import("shiki/themes/github-light-high-contrast.mjs"), - import("shiki/themes/github-dark-default.mjs"), - ], - }); - }, +// Built synchronously so the server renders highlighted markup inline instead of suspending. +const core = createHighlighterCoreSync({ + engine: createJavaScriptRegexEngine(), + langs: [json, shellscript, typescript, javascript, python, go], + themes: [githubLightHighContrast, githubDarkDefault], }); +const shiki = createShikiFactory({ init: () => core }); const shikiOptions = { themes: { light: "github-light-high-contrast", dark: "github-dark-default" }, } as const; -// One highlighter for every block, so a language loads once and a remounted block highlights on its first render. -const SAMPLE_LANGS = ["shellscript", "javascript", "python", "go", "json", "typescript"]; -const highlighter = createShikiHighlighter(() => shiki.getOrInit(), { - defaultColor: false, - ...shikiOptions, -}); +// No `loadLanguage`, so the code block never suspends; a language outside the bundle renders as plain text. +const highlighter: Highlighter = { + codeToHast: (code, { lang, structure, meta }) => + core.codeToHast(code, { + ...shikiOptions, + defaultColor: false, + lang: core.getLoadedLanguages().includes(lang) ? lang : "text", + structure, + meta, + }), +}; const DynamicCodeBlock = createDynamicCodeBlock({ highlighter }); -void highlighter.loadLanguage(...SAMPLE_LANGS).catch((error: unknown) => { - if (process.env.NODE_ENV !== "production") - console.warn("sample languages failed to preload", error); -}); // fumadocs-openapi's default code block leaves its scroll region unnamed, so every block on a page is the same landmark. function CodeBlock({ name, ...props }: CodeBlockProps & { name?: string }) {