Repository navigation
perf(docs-next): highlight API samples synchronously so the server renders them highlighted - #422
nickvigilante wants to merge 2 commits into
Conversation
…nders them highlighted The sample highlighter loaded its grammars through an async call, so fumadocs' code block suspended and the server emitted a plain placeholder for each sample, with the highlighted markup arriving later in hidden templates swapped in by inline scripts. Build the highlighter with createHighlighterCoreSync and static grammar and theme imports, and expose only codeToHast so nothing suspends. A language outside the bundle renders as plain text. Assisted-by: AI
|
The latest updates on your projects. Learn more about Vercel for GitHub. 1 Skipped Deployment
|
DOCS-1916 Highlight the first REST API code sample on the server, with no flash on first load
On the first load of a REST API operation page, the default cURL sample shows unstyled for a moment before it is highlighted. This is separate from DOCS-1907, which fixed the flash when switching tabs. The tab fix (#413) is merged and works. Cause. The sample highlighter loads its languages through an async call. Fumadocs' In the fixture export of I could not confirm how long the flash is in a browser. Whether the browser paints the plain version first depends on chunking, CSS and CPU. Hydration may add a second flash. Both are unverified. Proposed fix. Build the highlighter synchronously with Trade-off. The operation-page chunk gets larger, because the grammars (TypeScript is the largest) are bundled statically. They are already fetched for these pages today. The cost is that they now load before the page renders. Decision. Nick prefers the synchronous approach if page timing is acceptable. A benchmark of sync against async (bundle size, first-load check, highlighter cost, build time) is in progress. Paint timing needs a browser, so the issue stays open until someone measures FCP, LCP and CLS on a preview. Done when.
Alternative. Highlight the samples in a server component and pass the result to the client Upstream. The tab-switch cause (a new highlighter for every mount of the plain +++ Agent notes
+++ |
…test The shown panel lookup could be undefined, which failed the typecheck. Assisted-by: AI
Jesswinters
left a comment
There was a problem hiding this comment.
Clean, small change. Removing the Suspense fallback and the $RC swaps by dropping loadLanguage is a neat fix, the comments explain the why, and the two new tests pin the behaviour on both the client and the server. CI is green. I found no blocking issues.
Approving the code. Your own merge gate still applies: please do the browser timing check in QA before merging. The preview deploy is still waiting for approval, so nobody can run that check yet.
Suggestions (P2)
-
The chunk numbers don't agree. The PR body gives three sets of figures for the operation-page chunk:
- Merge order: about 111 KB gzipped moved into the chunk.
- QA step 3: about 107 KB to 183 KB gzipped.
- Benchmark: about 108 KB moved, and the chunk grows from 152 KB to 263 KB gzipped.
Please pick one set (or say which build each comes from). Otherwise whoever runs the QA check won't know what result to expect.
-
Hydration cost is the main risk. The client now tokenizes all five samples synchronously during hydration. In Node, a cold run took about 180 ms in total, and a throttled mobile CPU will be slower than that. Lighthouse showed no change in mobile TBT, which is reassuring. During the QA check, look for a long task around hydration on the larger real operation pages, not only the fixture. If one shows up, the server-component approach you described is the fix.
Nits (P3, optional)
core.getLoadedLanguages()runs on every highlight. You could compute it once into aSetat module level. The cost is tiny either way.- An unknown language now quietly renders as plain text. A
console.warnin development would make a future new sample language easy to spot. The old preload code had a similar warning. - The two new tests only work if they run first in the file. The comment explains this, which is good. Moving them into their own test file would make that guarantee structural, so a test added above them later can't break it.
Coder Agents generated this review for @Jesswinters.
Merge order
Do not merge until the timing check in QA shows no LCP, TBT or INP regression. This change moves about 111 KB gzipped of grammars and themes into the REST API operation page's chunk, so that cost has to be measured in a browser before it lands. It is independent of the other open PRs.
Summary
On the first load of a REST API operation page, the default cURL sample can show unstyled for a moment before it is highlighted. This builds the sample highlighter synchronously, so the server renders every sample (the four sample panels and the response example) already highlighted, with no suspended placeholder and no swap script.
Design
The highlighter was created through an async call that loaded its languages. Fumadocs'
Highlightedcomponent suspends on that call, so the server rendered each sample as a plain<pre>fallback and the highlighted markup arrived later in hidden templates that inline$RCscripts swapped in. In the fixture export of/reference/api/workspaces/list-workspaces/that was five swaps, each starting with no styled spans.The fix in
packages/docs-next/src/openapi/api-page.tsxusescreateHighlighterCoreSyncfromshiki/corewith the JavaScript regex engine and static imports of the same six grammars and two themes. The highlighter handed tocreateDynamicCodeBlockexposes onlycodeToHastand has noloadLanguage, and upstreamHighlightedonly suspends whenloadLanguageexists, so nothing suspends. A language outside the bundle falls back to plain text.createShikiFactory({ init: () => core })stays forcreateOpenAPIPageBase. No casts are needed, and the async factory and the preload call are gone.Why synchronous: it is about 30 lines, keeps
ApiPageandSampleTabsas they are, and makes the server HTML correct without depending on inline scripts, which matters with JavaScript off and for crawlers. The alternative is to highlight the samples in a server component and pass the result to the clientApiPage. That would avoid shipping Shiki for the samples at all, but it means restructuringindex.tsxandSampleTabsand splitting the sample tabs across the server and client boundary. Not worth that for now; it stays open if the chunk cost turns out to matter.The trade-off is bundle shape. The grammars (TypeScript is the largest) are already fetched for these pages today, but lazily after hydration; now they are in the operation page's preloaded chunk and load before it renders. Only operation pages are affected, and first-load JS is unchanged.
QA
Compare production (or a build of
main) against this preview. Timing needs a browser, so these are browser-only steps.about:config, setjavascript.enabledto false, then reload), open each page. Production shows plain uncoloured code in the samples; this branch shows highlighted code.Pages to compare
Note the preview needs a Vercel login. The
docs previewstatus link on this PR is authoritative; the preview URL is that link plus the path below.docs previewstatus link on this PR, then open/reference/api/workspaces/list-workspaces/docs previewstatus link on this PR, then open/reference/api/workspaces/list-workspaces/Testing
Two tests in
packages/docs-next/src/openapi/api-page-samples.test.tsxpin this: the first synchronous render of the samples has styled.line span[style]in the shown cURL panel, andrenderToStringoutput parsed withDOMParserhas no pending Suspense marker orB:template and a highlighted shown panel. Both fail on the currentmaincode and pass with this change (they run first in the file because the highlighter is module-level and would otherwise already be warm). The existing tab-switching andpersisttests still pass.Ran:
pnpm --filter @coder/docs-next test(493 of 493 pass),tsc --noEmitfor@coder/docs-next(clean),oxfmtandoxlinton the touched files (clean), the fixture docs site build, andpnpm --filter @coder/docs-site first-load:check(passes: 68 pages, no forbidden libraries). The axe pass could not run here because headless Chromium is missing system libraries, so CI'sa11yjob is the check. No new UI is added.Benchmark from DOCS-1916, build output and Node timings only, on the fixture page
/reference/api/workspaces/list-workspaces/. Pending markers, templates and$RCswap scripts go from 5 each to 0, and the five code blocks are highlighted inline. Page HTML is 8.2% smaller raw (130,428 to 119,681 bytes) and 5.2% smaller gzipped. Total shiki bytes barely change across the export (+2.3 KB gzipped); about 108 KB gzipped of grammars and themes move from lazy chunks into the operation page's preloaded chunk, which grows from about 152 KB to 263 KB gzipped (470 KB to 1.18 MB raw). Highlighter creation and per-sample highlight times in Node are indistinguishable (cold runs about 45, 85, 20, 30 and 1 ms; warm runs under 1 ms), and build time is the same (about 67 s). FCP, LCP, CLS, TBT, INP and hydration time were not measured. With JavaScript on, the highlighted markup was already in the old page bytes inside hidden templates, so the visible gain may be robustness (no-JS, crawlers, no reliance on inline scripts) rather than a faster paint.Local audit: Lighthouse, Unlighthouse and SiteOne
I built the fixture site from this branch's parent (async) and from this branch (sync), served both exports from localhost, and audited each. The browser steps in QA are still the check that matters for real-world timing, since these runs used software rendering, an uncompressed static server and a small corpus (8 API pages).
Lighthouse, 3 runs per page on 4 operation pages with the variants alternated, medians:
Unlighthouse over 23 routes (coder.com's settings: desktop, no throttling, one sample each) averaged 57.9 for async and 56.6 for sync. The eight REST API routes scored the same on both builds except the API landing page, which has no code samples and scored 57 against 43, so I read that as noise. Accessibility, best practices and SEO were identical.
SiteOne's performance category scored 10 of 10 on both. The crawled total rose from 4.05 MB to 4.72 MB uncompressed, with JavaScript going from 18 files to 19, which is the chunk move described under Design. HTML sizes and the 404 list were the same.
So load metrics are indistinguishable here, sync is marginally better on blocking time and layout shift on desktop, Speed Index reads slightly worse for sync but within the noise of three runs, and the one visible cost is the larger preloaded chunk. INP was not measured, and the real corpus has larger operation pages that this fixture does not reproduce.
Upstream
No. This is our own highlighter setup. The separate cause of the tab-switch flash, a new highlighter for every mount of the plain
DynamicCodeBlock, is a Fumadocs bug whose report is drafted and not filed.https://linear.app/codercom/issue/DOCS-1916
🤖 Built with AI assistance.