@writedocs/generator 0.10.14 → 0.10.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,831 +1,877 @@
1
- ---
2
- // The site's root HTML shell: <head> meta/SEO tags, the writedocs.json
3
- // `integrations`/`scripts` passthrough, the color-theme flash-
4
- // prevention script, the dismissible `banner`, and the three-column
5
- // .wd-shell (sidebar/main/toc) that every page's own content lands in.
6
- // Everything else that used to live directly in this file - the topbar,
7
- // the mobile hamburger drawer, the search modal, the footer, and the
8
- // analytics/AI-chat integration scripts - is now its own component,
9
- // composed below. This file had grown to ~2200 lines covering all of
10
- // those unrelated concerns in one place before that split; each piece is
11
- // small enough on its own now to read start-to-finish without losing the
12
- // thread, and a change to (say) the mobile menu no longer means scrolling
13
- // past a thousand lines of unrelated topbar/search/footer code to find
14
- // the right spot. This file is the only .astro file that stays directly
15
- // in src/layout/ - every other component lives in src/layout/components/,
16
- // and every plain .css file (base.css, banner.css, and the rest each
17
- // component below imports for itself) lives in src/layout/styles/ - this
18
- // file is the layout's single entry point/orchestrator, everything else
19
- // is a piece it composes.
20
- import fs from "node:fs";
21
- // Named `nodePath`, not the more natural `path` - this component already
22
- // destructures a prop called `path` (the current page's own URL path,
23
- // see Props below) from Astro.props, which would otherwise shadow a
24
- // module-level `path` import inside this component's own scope, silently
25
- // turning every `path.join(...)` call into a TypeError at render time
26
- // ("path.join is not a function") rather than a compile-time error, since
27
- // both are just plain identifiers to the bundler. Hit and fixed while
28
- // wiring up findRootAssets() below - real bug, not a hypothetical.
29
- import nodePath from "node:path";
30
- import {
31
- resolveSiteUrl,
32
- resolveAbsoluteUrl,
33
- findRootAssets,
34
- resolveNavbarColor,
35
- contrastTextColor,
36
- resolveFonts,
37
- googleFontsHref,
38
- fontFaceRule,
39
- type DocsConfig,
40
- type Selector,
41
- type GlobalDropdownView,
42
- type SeoFields,
43
- } from "../lib/config";
44
- import "../styles/global.css";
45
- // rehypeKatex (astro.config.mjs) renders every $inline$/$$block$$ math
46
- // span into real KaTeX markup at build time - this is the one runtime
47
- // dependency that output needs: layout/glyph CSS for the .katex class
48
- // tree, self-hosted (bundled by Vite, fonts included via its own url()
49
- // asset resolution) rather than a KaTeX CDN link. Loaded site-wide, same
50
- // as global.css above - a page with no math in it pays for one small,
51
- // cached stylesheet and nothing else (no fonts are actually fetched
52
- // unless a page's rendered KaTeX markup uses their glyphs). KaTeX's own
53
- // output deliberately sets no explicit text color, inheriting `color`
54
- // from whatever wraps it - so it already follows this site's light/dark
55
- // theme with no extra CSS needed here.
56
- import "katex/dist/katex.min.css";
57
- import "./styles/base.css";
58
- import "./styles/banner.css";
59
- // Astro's client-side router - swaps <body> content between same-origin
60
- // navigations via the native View Transition API instead of a hard
61
- // browser reload, so the topbar/sidebar/footer don't visibly flash/
62
- // "twitch" on every click the way a full document reload does. Every
63
- // interactive component's own <script> (TopBar's dropdowns, search,
64
- // TableOfContents, Mermaid, the copy-page menu, ...) already calls its
65
- // init function once directly *and* re-registers it on the
66
- // `astro:page-load` event (see e.g. TableOfContents.astro's own
67
- // `initToc(document); document.addEventListener('astro:page-load', ...)`
68
- // pair) - that event only ever fires when this router is active, so this
69
- // was already the intended architecture, just missing this one piece
70
- // that actually turns it on.
71
- import { ClientRouter } from "astro:transitions";
72
- import TopBar from "./components/TopBar.astro";
73
- import MobileMenu from "./components/MobileMenu.astro";
74
- import SearchModal from "./components/SearchModal.astro";
75
- import ImageZoom from "./components/ImageZoom.astro";
76
- import SiteFooter from "./components/SiteFooter.astro";
77
- import AnalyticsScripts from "./components/AnalyticsScripts.astro";
78
- import AskAiWidget from "./components/AskAiWidget.astro";
79
-
80
- interface Props {
81
- config: DocsConfig;
82
- title: string;
83
- // Falls back to config.description when a page has none of its own -
84
- // see [...slug].astro, which passes entry.data.description straight
85
- // through without resolving the fallback itself.
86
- description?: string;
87
- // The current page's own path (e.g. "/" or "/guides/foo/"), used to
88
- // build the canonical <link> and og:url/twitter:url - [...slug].astro
89
- // already computes this via hrefForSlug(currentFileId) for its own
90
- // prev/next links, so it's passed through rather than recomputed here.
91
- path: string;
92
- // Site-wide seo (writedocs.json) merged with this page's own frontmatter
93
- // seo override - see mergeSeo() in lib/config.ts. [...slug].astro does
94
- // the merging; this component just renders the result.
95
- seo?: SeoFields;
96
- // One Selector per level of the active page's navigation path (tabs,
97
- // versions, languages, products, or a dropdown used as a nested level)
98
- // - see resolveSections()/buildSelectors() in lib/config.ts for how
99
- // this is computed from however the site's writedocs.json nests things.
100
- // Passed straight through to TopBar.astro and MobileMenu.astro, which
101
- // each derive their own view of it (TopBar's switcherSelectors/
102
- // tabSelectors vs. MobileMenu's per-level accordion rows).
103
- selectors?: Selector[];
104
- // The always-visible topbar dropdown list from navigation.global.dropdowns
105
- // - independent of the active selectors, shown on every page. Also
106
- // passed straight through to TopBar.astro and MobileMenu.astro.
107
- globalDropdowns?: GlobalDropdownView[];
108
- // Per-page frontmatter `mode` (content.config.ts) - controls how much
109
- // site chrome wraps this page. 'blank' drops the topbar and the whole
110
- // .wd-shell (sidebar/toc columns) entirely, rendering only <slot />
111
- // directly in <body> - see the template below. Every other mode
112
- // (including 'custom') still gets the topbar; [...slug].astro is what
113
- // decides whether to actually pass sidebar/toc slot content for
114
- // 'wide'/'frame'/'custom' (BaseLayout has no sidebar/toc content of its
115
- // own to conditionally omit - an unfilled named slot in Astro already
116
- // renders nothing, so this component only needs to know whether to
117
- // render the *column wrapper divs* at all).
118
- mode?: "default" | "wide" | "frame" | "custom" | "blank";
119
- // The page's language, for <html lang> - the `language` of the
120
- // navigation level it belongs to (see [...slug].astro), or 'en'.
121
- lang?: string;
122
- }
123
- const {
124
- config,
125
- title,
126
- description,
127
- path,
128
- seo = {},
129
- selectors = [],
130
- globalDropdowns = [],
131
- mode = "default",
132
- lang = "en",
133
- } = Astro.props as Props;
134
- const showSidebarCol = mode === "default" || mode === "wide";
135
- const showTocCol = mode === "default";
136
- // Meta tag resolution - all derived once here rather than inline in the
137
- // template below, so the JSX stays a straight list of conditional <meta>
138
- // tags instead of repeating this logic at each call site.
139
- const siteUrl = resolveSiteUrl(config);
140
- const effectiveDescription = description ?? config.description;
141
- const canonicalUrl = siteUrl ? `${siteUrl}${path}` : null;
142
- const ogType = seo.ogType ?? "website";
143
- const absoluteOgImage = seo.ogImage ? resolveAbsoluteUrl(siteUrl, seo.ogImage) : undefined;
144
- // summary_large_image needs a real image to make sense as a card size;
145
- // falls back to the smaller "summary" card when no image is set, rather
146
- // than always defaulting to the large-image card regardless.
147
- const twitterCard = seo.twitterCard ?? (absoluteOgImage ? "summary_large_image" : "summary");
148
- // Light-mode values come straight from styles.colors/styles.background
149
- // (with defaults); dark-mode values fall back to their light counterpart
150
- // when the site's own dark override doesn't set them, so a site only has
151
- // to specify what actually changes for dark mode. Both sets are always
152
- // computed and handed to the CSS below (light-mode ones as sensible
153
- // starting defaults, but the .wd-* class hides/shows appropriately) - see
154
- // the `[data-theme="dark"]` override rule below, which is what actually
155
- // switches which set is live. Unlike every other bit of CSS this file
156
- // used to own directly, this specific pair of rules can't move into a
157
- // plain external .css file the way base.css/banner.css did - `define:vars`
158
- // (right below) is what lets these raw hex/URL values get interpolated
159
- // into custom-property assignments at all, and that directive only works
160
- // on a <style> tag physically inside an .astro file's own template.
161
- const lightPrimary = config.styles.colors.primary;
162
- const lightText = config.styles.colors.text ?? "#404045";
163
- const darkPrimary = config.styles.colors.dark?.primary ?? lightPrimary;
164
- // Body text - also the sidebar's and table of contents' links. Headings,
165
- // bold text and group titles use the stronger --wd-heading (below).
166
- const darkText = config.styles.colors.dark?.text ?? "#a0a0a5";
167
- // Text drawn on the primary color (step numbers, the info banner, the API
168
- // playground's buttons) - white, or black on a clearly light primary
169
- // (contrastTextColor(), lib/config.ts). It used to be white everywhere,
170
- // unreadable on a light primary - and a light dark-mode primary is exactly
171
- // what dark-mode links need.
172
- const lightOnPrimary = contrastTextColor(lightPrimary);
173
- const darkOnPrimary = contrastTextColor(darkPrimary);
174
- // styles.background.colors is now the single source for any background
175
- // color - both the flat --wd-background surface (dropdowns/modals/kbd
176
- // chips/footer/topbar-fallback/etc., every other `var(--wd-background)`
177
- // call site) and the <body> canvas paint below. There used to be a
178
- // separate styles.colors.background/colors.dark.background pair driving
179
- // just the --wd-background half, independent of this - see config.ts's
180
- // own comment on why that split was removed; `lightBackground`/
181
- // `darkBackground` here is what used to read that other field.
182
- const lightBackground = config.styles.background?.colors?.light ?? "#ffffff";
183
- const darkBackground = config.styles.background?.colors?.dark ?? "#0b1120";
184
- // The topbar/mobile-menu-panel background - falls back to the page's own
185
- // background (above) when a site doesn't set it, so an unconfigured navbar
186
- // keeps blending into the page exactly as it always has; only sites that
187
- // explicitly set `styles.navbar.light`/`.dark` get a topbar that looks
188
- // different from the page behind it. resolveNavbarColor() (lib/config.ts)
189
- // is what splits the string-or-{background,accent} union `navbar.light`/
190
- // `.dark` can now be into its two parts - see its own comment.
191
- const navLight = resolveNavbarColor(config.styles.navbar?.light, lightBackground);
192
- const navDark = resolveNavbarColor(config.styles.navbar?.dark, darkBackground);
193
- const lightNavbarBg = navLight.background;
194
- const darkNavbarBg = navDark.background;
195
- // Whether this side of `styles.navbar` was configured at all - string or
196
- // object form, doesn't matter, just "is there a writedocs.json value here" -
197
- // not merely "does lightNavbarBg differ from the page background", since
198
- // a site could deliberately set navbar to the *same* color as the page
199
- // background and this should still count as configured. What this gates:
200
- // once true, the navbar's own text/icon color stops assuming it's sitting
201
- // on something close to the page background (--wd-text's own tuning
202
- // target) and switches to being computed fresh against whatever
203
- // `background` actually resolved to.
204
- const lightNavbarConfigured = config.styles.navbar?.light !== undefined;
205
- const darkNavbarConfigured = config.styles.navbar?.dark !== undefined;
206
- // --wd-navbar-foreground/-muted: the topbar's own text/icon color, plain
207
- // (resting) state. Never a writedocs.json value, even indirectly - always
208
- // contrastTextColor(lightNavbarBg) (lib/config.ts, picks black or white by
209
- // luminance) the moment this side of `navbar` is configured at all, or the
210
- // literal --wd-text/--wd-text-muted var references when it isn't, so an
211
- // unconfigured navbar renders pixel-identical to before this feature
212
- // existed. An earlier version of this let an object-form field double as
213
- // both "the navbar's accent color" and "the navbar's text color" - real
214
- // bug, caught immediately: a site picking a light accent (to stay legible
215
- // against a dark/saturated background, the whole point of setting it) got
216
- // that same light color as its *text*, which is exactly backwards. Text
217
- // legibility isn't a design choice worth exposing at all here - it's
218
- // always computed, correctly, every time. The muted variant mixes that
219
- // same resolved color toward transparent (not toward lightNavbarBg, which
220
- // would drag it back toward the background's own hue and undo the
221
- // contrast fix) - a plain opacity reduction, so it stays legible
222
- // regardless of what hue the navbar itself happens to be.
223
- const lightNavbarFg = lightNavbarConfigured ? contrastTextColor(lightNavbarBg) : "var(--wd-text)";
224
- const darkNavbarFg = darkNavbarConfigured ? contrastTextColor(darkNavbarBg) : "var(--wd-text)";
225
- // The current tab (and a hovered one) stands out: the heading color on the
226
- // page's own background, or the same computed black/white on a configured
227
- // navbar - which is already the strongest color there.
228
- const lightNavbarFgStrong = lightNavbarConfigured ? lightNavbarFg : "var(--wd-heading)";
229
- const darkNavbarFgStrong = darkNavbarConfigured ? darkNavbarFg : "var(--wd-heading)";
230
- const lightNavbarFgMuted = lightNavbarConfigured
231
- ? `color-mix(in srgb, ${lightNavbarFg} 70%, transparent)`
232
- : "var(--wd-text-muted)";
233
- const darkNavbarFgMuted = darkNavbarConfigured
234
- ? `color-mix(in srgb, ${darkNavbarFg} 70%, transparent)`
235
- : "var(--wd-text-muted)";
236
- // --wd-navbar-accent: the tab-hover-underline/active-tab-fill color inside
237
- // the topbar specifically - `accent` on the object form (a real, legitimate
238
- // design choice, unlike text color above), falling back to the sitewide
239
- // --wd-primary (today's exact behavior) when unset - a site that sets a
240
- // navbar background but no accent keeps its ordinary brand-colored
241
- // active-tab underline.
242
- const lightNavbarAccent = navLight.accent ?? lightPrimary;
243
- const darkNavbarAccent = navDark.accent ?? darkPrimary;
244
- // --wd-navbar-border: the switcher pills' (version/language/product) own
245
- // border. Never the flat --wd-border (a fixed neutral gray/slate tuned for
246
- // sitting on the page background) once navbar is configured - that reads
247
- // as a harsh, near-white outline against a saturated/colored navbar
248
- // background, since it's not picked with that background in mind at all.
249
- // Same mix-toward-transparent technique as the muted foreground above: a
250
- // low-opacity tint of the already-contrast-correct navbarFg, so it stays
251
- // soft and legible against any navbar hue instead of a flat, unrelated
252
- // gray. Unconfigured navbar keeps the literal var(--wd-border) reference,
253
- // pixel-identical to before this existed.
254
- const lightNavbarBorder = lightNavbarConfigured
255
- ? `color-mix(in srgb, ${lightNavbarFg} 25%, transparent)`
256
- : "var(--wd-border)";
257
- const darkNavbarBorder = darkNavbarConfigured
258
- ? `color-mix(in srgb, ${darkNavbarFg} 25%, transparent)`
259
- : "var(--wd-border)";
260
- // --wd-navbar-hover: a topbar tab's background on hover. On a navbar with
261
- // the page's own background, the sidebar's hover tint (NavTree.astro) -
262
- // the same 6% of --wd-primary. A configured navbar can *be* the primary
263
- // color, where that tint would vanish, so there it's a light tint of the
264
- // navbar's own contrast-correct text color instead, like --wd-navbar-border.
265
- const sidebarHover = "color-mix(in srgb, var(--wd-primary) 6%, transparent)";
266
- const lightNavbarHover = lightNavbarConfigured ? `color-mix(in srgb, ${lightNavbarFg} 12%, transparent)` : sidebarHover;
267
- const darkNavbarHover = darkNavbarConfigured ? `color-mix(in srgb, ${darkNavbarFg} 12%, transparent)` : sidebarHover;
268
- // The <body> canvas's own paint - same color as --wd-background above
269
- // (there's only one background color to configure now), plus an optional
270
- // image layered on top. `images.light`/`.dark` are plain public/-relative
271
- // paths (same convention as styles.logo/favicon) - wrapped in url(...) here
272
- // (or 'none' when unset) since CSS custom properties can't have url()
273
- // applied to them after the fact (`url(var(--x))` isn't valid CSS - the
274
- // value itself has to already be a full `url(...)` token, which is what
275
- // these two variables hold).
276
- const lightPageBgColor = lightBackground;
277
- const darkPageBgColor = darkBackground;
278
- const lightPageBgImage = config.styles.background?.images?.light
279
- ? `url('${config.styles.background.images.light}')`
280
- : "none";
281
- const darkPageBgImage = config.styles.background?.images?.dark
282
- ? `url('${config.styles.background.images.dark}')`
283
- : "none";
284
- // A logo is either one path used for both modes, or a {light, dark,
285
- // label} object - normalized to a single light/dark pair here (the one
286
- // place that needs to know which form writedocs.json used) so TopBar.astro,
287
- // MobileMenu.astro, and SiteFooter.astro - each of which render their own
288
- // copy of the brand link - never need to branch on it themselves. The
289
- // brand link shows the image(s) alone by default - no site name text next
290
- // to it, since a real logo asset is usually already a wordmark. `label`
291
- // (only settable on the object form - see config.ts) opts back into
292
- // showing text next to the image - or, since `light`/`dark` are
293
- // themselves optional on that form, stands entirely on its own:
294
- // `styles.logo: { label: "..." }` with no images at all overrides just the
295
- // brand text without adding any logo image. A site with neither a logo
296
- // image nor a label falls back to plain config.name text, so the brand
297
- // link is never left empty.
298
- const logo = config.styles.logo;
299
- const logoLight = typeof logo === "string" ? logo : logo?.light;
300
- const logoDark = typeof logo === "string" ? logo : logo?.dark;
301
- const logoLabel = typeof logo === "string" ? undefined : logo?.label;
302
- const hasLogoImage = Boolean(logoLight || logoDark);
303
- const brandLabel = logoLabel ?? (hasLogoImage ? undefined : config.name);
304
-
305
- // writedocs.json's `footer.logo` (same {light, dark, label} shape as
306
- // `styles.logo` above, via config.ts's shared logoSchema) - unset by
307
- // default, in which case SiteFooter.astro just gets the same
308
- // logoLight/logoDark/logoLabel as the topbar/mobile menu above. Set, it
309
- // replaces those entirely (not just fills in whichever side is missing)
310
- // before ever reaching SiteFooter - a footer wanting a different mark
311
- // than the topbar (or none at all - `styles.logo` set, `footer.logo`
312
- // deliberately absent-of-images-but-present, e.g. `{ label: "" }`, isn't
313
- // a real use case worth solving here) shouldn't still show the sitewide
314
- // one alongside or underneath it.
315
- const footerLogoConfig = config.footer.logo;
316
- const footerLogoLight = footerLogoConfig
317
- ? typeof footerLogoConfig === "string"
318
- ? footerLogoConfig
319
- : footerLogoConfig.light
320
- : logoLight;
321
- const footerLogoDark = footerLogoConfig
322
- ? typeof footerLogoConfig === "string"
323
- ? footerLogoConfig
324
- : footerLogoConfig.dark
325
- : logoDark;
326
-
327
- // Zero-config custom CSS/JS - any `.css`/`.js` file anywhere in the
328
- // project (root, `docs/`, `snippets/`, `public/`, any subfolder -
329
- // `dist/`/`node_modules/`/etc. excluded, see findRootAssets() in
330
- // lib/pages.js) is auto-loaded on every page, no writedocs.json entry
331
- // needed. Read fresh on every render (not cached at module scope) so an
332
- // edit to one of these files shows up on the next `writedocs dev` page
333
- // load without a server restart - same freshness `loadDocsConfig(contentDir)`
334
- // itself already gives writedocs.json edits in [...slug].astro/404.astro.
335
- // Rendered in addition to, not instead of, writedocs.json's own explicit
336
- // `scripts` field - that still exists for external/CDN script URLs
337
- // (`src`) and inline content that should only load under deliberate
338
- // config, and renders before these so a file living in the project (the
339
- // more locally-owned override) wins over a URL possibly pointing at
340
- // someone else's asset.
341
- const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
342
- const rootAssets = findRootAssets(contentDir);
343
- // `name` is a POSIX-separated path relative to contentDir (e.g.
344
- // "docs/theme.css") - split and rejoin with nodePath.join rather than
345
- // handing the raw string straight to it, so a nested asset resolves
346
- // correctly on every OS this might run on, not just POSIX ones.
347
- const rootCssContents = rootAssets.css.map((name) =>
348
- fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8"),
349
- );
350
- const rootJsContents = rootAssets.js.map((name) =>
351
- fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8"),
352
- );
353
- // public/*.css and public/*.js auto-load too, but as <link>/<script src>
354
- // pointing at their already-public URL (see findRootAssets()'s own
355
- // comment for why - no point inlining a file that's also independently
356
- // fetchable at that exact URL). publicJsHrefs is filtered against
357
- // writedocs.json's own `scripts.head` so a site that hasn't yet removed an
358
- // explicit `src` entry for the same public/ file doesn't get that href
359
- // rendered twice - the explicit entry still works, it's just redundant
360
- // with this now. publicCssHrefs has no equivalent filter to apply -
361
- // there's no explicit stylesheet-URL config field anymore.
362
- const explicitScriptSrcs = new Set(config.scripts.head.map((s) => s.src).filter((src): src is string => Boolean(src)));
363
- const publicCssHrefs = rootAssets.publicCss;
364
- const publicJsHrefs = rootAssets.publicJs.filter((href) => !explicitScriptSrcs.has(href));
365
-
366
- // styles.fonts (see fontsSchema/resolveFonts() in lib/config.ts) - resolves
367
- // to plain Inter, genuinely loaded via Google Fonts (not just named in a
368
- // fallback stack the way base.css used to), when a site sets no `fonts`
369
- // field at all. `fontStack()` quotes the family name (safe even for a
370
- // single-word name, and required for one with spaces like "Playfair
371
- // Display") and appends the same system-font fallback chain base.css
372
- // always used, so a reader who somehow loads the page before the web font
373
- // finishes fetching still sees a reasonable font rather than the browser
374
- // default serif. `heading`/`body` are left `null` (not defaulted to the
375
- // same value as `base`) whenever a site hasn't overridden them - base.css
376
- // falls back to `--wd-font-family` itself via CSS var(), so a `null` here
377
- // deliberately never gets its own CSS var written into the style block
378
- // below.
379
- const resolvedFonts = resolveFonts(config);
380
- const fontsGoogleHref = googleFontsHref(resolvedFonts);
381
- function fontStack(family: string): string {
382
- return `'${family}', -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;
383
- }
384
- // heading/body already fall back to `resolvedFonts.base` right here (not
385
- // left as a CSS var() fallback chain for :root below to resolve) - same
386
- // "fully resolve in JS, plain values into define:vars" approach every
387
- // other themeable value in this file already uses (see lightPrimary/
388
- // darkPrimary etc. above), rather than introducing a different pattern
389
- // just for fonts.
390
- const wdFontFamily = fontStack(resolvedFonts.base.family);
391
- const wdFontFamilyHeading = resolvedFonts.heading ? fontStack(resolvedFonts.heading.family) : wdFontFamily;
392
- const wdFontFamilyBody = resolvedFonts.body ? fontStack(resolvedFonts.body.family) : wdFontFamily;
393
- // One @font-face rule per source-based font actually configured (Google
394
- // Fonts, covered by fontsGoogleHref above instead, never reach here) - this
395
- // only ever gets the right *file* loaded (the @font-face `font-weight`
396
- // descriptor, or the Google Fonts URL's `:wght@` axis inside
397
- // googleFontsHref() above), not the actual rendered boldness of any
398
- // element - see wdFontWeightCss right below for that other half.
399
- const fontFaceCss = [
400
- fontFaceRule(resolvedFonts.base),
401
- fontFaceRule(resolvedFonts.heading),
402
- fontFaceRule(resolvedFonts.body),
403
- ]
404
- .filter(Boolean)
405
- .join("\n");
406
- // Without this, a configured `weight` only ever changed which font *file*
407
- // loaded - h1-h6 still rendered at the browser's own default `font-weight:
408
- // bold` (a user-agent-stylesheet rule, present regardless of which file
409
- // actually loaded), so a heading weight of e.g. 400 was silently faux-
410
- // bolded back to looking bold anyway, with no visible effect from
411
- // changing the config at all. `resolvedFonts.heading?.weight ?? base.weight`
412
- // falls back the same way family already does (an override with no
413
- // weight of its own still inherits the top-level one); `undefined` when
414
- // nothing at any level configured a weight, which deliberately renders no
415
- // rule at all here - an unconfigured site keeps today's plain browser-
416
- // default bold headings/normal body text exactly as before this feature
417
- // existed, not a forced 400/700 nobody asked for.
418
- const wdFontWeightHeading = resolvedFonts.heading?.weight ?? resolvedFonts.base.weight;
419
- const wdFontWeightBody = resolvedFonts.body?.weight ?? resolvedFonts.base.weight;
420
- const fontWeightCss = [
421
- wdFontWeightHeading !== undefined ? `h1, h2, h3, h4, h5, h6 { font-weight: ${wdFontWeightHeading}; }` : "",
422
- wdFontWeightBody !== undefined ? `body { font-weight: ${wdFontWeightBody}; }` : "",
423
- ]
424
- .filter(Boolean)
425
- .join("\n");
426
- const fontExtraCss = [fontFaceCss, fontWeightCss].filter(Boolean).join("\n");
427
- ---
428
-
429
- <!doctype html>
430
- <html lang={lang}>
431
- <head>
432
- <meta charset="UTF-8" />
433
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
434
- {/* Marks the pages writedocs renders - the build checks each has the site's styles (cli/check-built-styles.js). */}
435
- <meta name="generator" content="writedocs" />
436
- <title>{title} · {config.name}</title>
437
- <ClientRouter />
438
- {effectiveDescription && <meta name="description" content={effectiveDescription} />}
439
- {seo.keywords && seo.keywords.length > 0 && <meta name="keywords" content={seo.keywords.join(", ")} />}
440
- {seo.noindex && <meta name="robots" content="noindex, nofollow" />}
441
- {canonicalUrl && <link rel="canonical" href={canonicalUrl} />}
442
- {config.styles.favicon && <link rel="icon" href={config.styles.favicon} />}
443
- {
444
- /* styles.fonts - see resolveFonts()/googleFontsHref() in lib/config.ts.
445
- Present (non-null) whenever at least one configured font (or the
446
- Inter default, when styles.fonts is unset entirely) has no `source`
447
- - i.e. is a Google Font, auto-loaded by family name. The two
448
- preconnect hints warm up the connections googleapis.com's own CSS
449
- response will immediately need (its @font-face rules point at
450
- gstatic.com for the actual font files) before the browser has even
451
- parsed that response - Google's own recommended pattern for using
452
- their fonts. Rendered this early in <head> (right after favicon,
453
- before Open Graph/Twitter meta) so the font starts loading as soon
454
- as possible rather than competing with less render-critical tags
455
- for bandwidth/priority. */
456
- }
457
- {
458
- fontsGoogleHref && (
459
- <>
460
- <link rel="preconnect" href="https://fonts.googleapis.com" />
461
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
462
- <link rel="stylesheet" href={fontsGoogleHref} />
463
- </>
464
- )
465
- }
466
- <!-- Open Graph -->
467
- <meta property="og:title" content={title} />
468
- {effectiveDescription && <meta property="og:description" content={effectiveDescription} />}
469
- <meta property="og:type" content={ogType} />
470
- <meta property="og:site_name" content={config.name} />
471
- {canonicalUrl && <meta property="og:url" content={canonicalUrl} />}
472
- {absoluteOgImage && <meta property="og:image" content={absoluteOgImage} />}
473
- <!-- Twitter card -->
474
- <meta name="twitter:card" content={twitterCard} />
475
- <meta name="twitter:title" content={title} />
476
- {effectiveDescription && <meta name="twitter:description" content={effectiveDescription} />}
477
- {absoluteOgImage && <meta name="twitter:image" content={absoluteOgImage} />}
478
- {
479
- /* writedocs.json's `integrations` (the six analytics providers) - see
480
- AnalyticsScripts.astro. Rendered as early in <head> as reasonably
481
- possible (right after the meta tags, before even the theme-
482
- detection script below) - the usual placement every one of these
483
- providers' own install instructions ask for, so pageview timing is
484
- captured as close to actual page load as it can be. */
485
- }
486
- <AnalyticsScripts config={config} />
487
- <script is:inline>
488
- // Sets [data-theme] and [data-banner-dismissed] on <html> before
489
- // first paint, so the page never flashes the wrong mode or an
490
- // already-dismissed banner. Preference order for theme: an explicit
491
- // prior choice (localStorage), then the OS-level preference,
492
- // defaulting to light. The click handlers that update both live in
493
- // src/scripts/theme-toggle.ts and src/scripts/banner.ts.
494
- //
495
- // Also re-run on `astro:after-swap` (ClientRouter, see BaseLayout's
496
- // own import of it below), not just the initial load - Astro's
497
- // client-side navigation swaps <html>'s attributes wholesale to
498
- // match the newly-fetched page's raw server-rendered markup (see
499
- // swapRootAttributes() in astro/dist/transitions/swap-functions.js),
500
- // which has neither of these dataset attributes baked in since
501
- // they're pure client-side runtime state, not something the server
502
- // ever renders. Without re-running this after every swap, a
503
- // dismissed banner (or a chosen dark theme) would silently come
504
- // back on the very next navigation - both attributes get wiped, not
505
- // just reset to their default, so this has to unconditionally
506
- // reapply them from localStorage every time, exactly as it does on
507
- // first load. `astro:after-swap` fires synchronously right after
508
- // that swap and before the browser's next paint, so this still
509
- // prevents any visible flash on client-side navigations too.
510
- function wdApplyStoredPreferences() {
511
- try {
512
- var stored = localStorage.getItem("wd-theme");
513
- var theme =
514
- stored === "light" || stored === "dark"
515
- ? stored
516
- : window.matchMedia("(prefers-color-scheme: dark)").matches
517
- ? "dark"
518
- : "light";
519
- document.documentElement.dataset.theme = theme;
520
- } catch (e) {
521
- document.documentElement.dataset.theme = "light";
522
- }
523
- try {
524
- document.documentElement.dataset.bannerDismissed =
525
- localStorage.getItem("wd-banner-dismissed") === "true" ? "true" : "false";
526
- } catch (e) {
527
- document.documentElement.dataset.bannerDismissed = "false";
528
- }
529
- }
530
- wdApplyStoredPreferences();
531
- document.addEventListener("astro:after-swap", wdApplyStoredPreferences);
532
- </script>
533
- <script>
534
- // Preserves the sidebar's own scroll position across a ClientRouter
535
- // navigation - see src/scripts/sidebar-scroll.ts for why this is
536
- // needed at all (the sidebar is re-rendered fresh, server-side, on
537
- // every page, so it's a brand-new DOM node each time, reset to
538
- // scrollTop 0 like a real page reload would be). Same before-swap/
539
- // after-swap pairing as wdApplyStoredPreferences above, and for the
540
- // same reason: after-swap fires before the next paint, so there's no
541
- // visible flash of the sidebar sitting at the top before jumping
542
- // back to where the reader had it scrolled.
543
- import { saveSidebarScroll, restoreSidebarScroll } from "../scripts/sidebar-scroll";
544
-
545
- document.addEventListener("astro:before-swap", saveSidebarScroll);
546
- document.addEventListener("astro:after-swap", restoreSidebarScroll);
547
- </script>
548
- <style
549
- define:vars={{
550
- wdPrimaryLight: lightPrimary,
551
- wdOnPrimaryLight: lightOnPrimary,
552
- wdBackgroundLight: lightBackground,
553
- wdTextLight: lightText,
554
- wdNavbarLight: lightNavbarBg,
555
- wdNavbarFgLight: lightNavbarFg,
556
- wdNavbarFgStrongLight: lightNavbarFgStrong,
557
- wdNavbarFgMutedLight: lightNavbarFgMuted,
558
- wdNavbarAccentLight: lightNavbarAccent,
559
- wdNavbarBorderLight: lightNavbarBorder,
560
- wdNavbarHoverLight: lightNavbarHover,
561
- wdPageBgColorLight: lightPageBgColor,
562
- wdPageBgImageLight: lightPageBgImage,
563
- wdFontFamily,
564
- wdFontFamilyHeading,
565
- wdFontFamilyBody,
566
- wdPrimaryDark: darkPrimary,
567
- wdOnPrimaryDark: darkOnPrimary,
568
- wdBackgroundDark: darkBackground,
569
- wdTextDark: darkText,
570
- wdNavbarDark: darkNavbarBg,
571
- wdNavbarFgDark: darkNavbarFg,
572
- wdNavbarFgStrongDark: darkNavbarFgStrong,
573
- wdNavbarFgMutedDark: darkNavbarFgMuted,
574
- wdNavbarAccentDark: darkNavbarAccent,
575
- wdNavbarBorderDark: darkNavbarBorder,
576
- wdNavbarHoverDark: darkNavbarHover,
577
- wdPageBgColorDark: darkPageBgColor,
578
- wdPageBgImageDark: darkPageBgImage,
579
- }}
580
- >
581
- :root {
582
- --wd-primary: var(--wdPrimaryLight);
583
- --wd-on-primary: var(--wdOnPrimaryLight);
584
- --wd-background: var(--wdBackgroundLight);
585
- --wd-text: var(--wdTextLight);
586
- --wd-navbar-background: var(--wdNavbarLight);
587
- --wd-navbar-foreground: var(--wdNavbarFgLight);
588
- --wd-navbar-foreground-strong: var(--wdNavbarFgStrongLight);
589
- --wd-navbar-foreground-muted: var(--wdNavbarFgMutedLight);
590
- --wd-navbar-accent: var(--wdNavbarAccentLight);
591
- --wd-navbar-border: var(--wdNavbarBorderLight);
592
- --wd-navbar-hover: var(--wdNavbarHoverLight);
593
- --wd-page-bg-color: var(--wdPageBgColorLight);
594
- --wd-page-bg-image: var(--wdPageBgImageLight);
595
- --wd-text-muted: #64748b;
596
- /* Headings, bold text, card titles, and the sidebar's group titles -
597
- a stronger color than body text (--wd-text), which the sidebar's
598
- and table of contents' links use (--wd-nav-text). */
599
- --wd-heading: #18191d;
600
- --wd-nav-title: var(--wd-heading);
601
- --wd-nav-text: var(--wd-text);
602
- --wd-border: #e2e8f0;
603
- --wd-surface: #f8fafc;
604
- /* The browser's own controls - the page's scrollbar, a code block's -
605
- drawn for the theme on screen. Without it they stayed light in dark
606
- mode. */
607
- color-scheme: light;
608
- /* Not mode-dependent (a site's chosen font doesn't change between
609
- light/dark) - set once here rather than duplicated in the
610
- :root[data-theme='dark'] block below. */
611
- --wd-font-family: var(--wdFontFamily);
612
- --wd-font-family-heading: var(--wdFontFamilyHeading);
613
- --wd-font-family-body: var(--wdFontFamilyBody);
614
- }
615
- /* Higher specificity than the plain :root rule above (an attribute
616
- selector on :root beats an unqualified one), so this wins
617
- regardless of source order once data-theme is set to "dark" by
618
- the inline script above or the toggle button's click handler
619
- (src/scripts/theme-toggle.ts). */
620
- :root[data-theme="dark"] {
621
- --wd-primary: var(--wdPrimaryDark);
622
- --wd-on-primary: var(--wdOnPrimaryDark);
623
- --wd-background: var(--wdBackgroundDark);
624
- --wd-text: var(--wdTextDark);
625
- --wd-navbar-background: var(--wdNavbarDark);
626
- --wd-navbar-foreground: var(--wdNavbarFgDark);
627
- --wd-navbar-foreground-strong: var(--wdNavbarFgStrongDark);
628
- --wd-navbar-foreground-muted: var(--wdNavbarFgMutedDark);
629
- --wd-navbar-accent: var(--wdNavbarAccentDark);
630
- --wd-navbar-border: var(--wdNavbarBorderDark);
631
- --wd-navbar-hover: var(--wdNavbarHoverDark);
632
- --wd-page-bg-color: var(--wdPageBgColorDark);
633
- --wd-page-bg-image: var(--wdPageBgImageDark);
634
- --wd-text-muted: #94a3b8;
635
- --wd-heading: #e0e0e5;
636
- --wd-border: #1e293b;
637
- --wd-surface: #131a2b;
638
- color-scheme: dark;
639
- }
640
- </style>
641
- {
642
- /* styles.fonts: local/externally-hosted font(s) (fontFaceRule() in
643
- lib/config.ts - a local `source` path resolves the same way
644
- styles.favicon/styles.logo/styles.background.images already do, see
645
- collectConfiguredAssetPaths() + styles-asset-integration.js, no
646
- extra wiring needed here beyond listing it there), plus a
647
- font-weight override for h1-h6/body whenever `weight` was actually
648
- configured somewhere (fontWeightCss above) - both concatenated
649
- into one block since both need the same raw-CSS-text treatment.
650
- set:html (not a plain <style>{fontExtraCss}</style>) because this
651
- needs to render already-built CSS text as-is, not have Astro's own
652
- CSS parser/scoper attempt to process an `@font-face` block or a
653
- bare `h1, h2, ...` selector list assembled as a runtime string -
654
- empty string renders nothing when neither piece has anything to
655
- contribute (every configured font is a Google Font, and no
656
- `weight` was set anywhere in `styles.fonts`). */
657
- }
658
- {fontExtraCss && <style set:html={fontExtraCss} />}
659
- {
660
- /* writedocs.json's `scripts.head` - see scriptEntrySchema in lib/config.ts.
661
- Each entry is exactly one of an external/local `src` or inline
662
- `content` (enforced by the schema's own .refine()), rendered right
663
- before </head> so it runs before body content paints - the usual
664
- spot a third-party script's own install instructions ask for. */
665
- }
666
- {
667
- config.scripts.head.map((s) =>
668
- s.src ? <script is:inline src={s.src} /> : <script is:inline set:html={s.content} />,
669
- )
670
- }
671
- {
672
- /* Zero-config custom CSS - see findRootAssets() in lib/pages.js and
673
- rootCssContents above. Rendered last in <head>, so a project-owned
674
- file - anywhere in the project, not just the root - wins over
675
- everything else writedocs generates itself. Inlined as raw <style>
676
- content rather than a <link> - these files aren't necessarily under
677
- `public/`, so there's no guaranteed build-time copy step making them
678
- independently fetchable as a URL; inlining sidesteps needing one.
679
- One <style> tag per file (not concatenated) so each is independently
680
- visible/attributable
681
- in devtools. */
682
- }
683
- {rootCssContents.map((content) => <style is:inline set:html={content} />)}
684
- {
685
- /* Zero-config custom CSS living in public/ - see findRootAssets()'s
686
- own comment in lib/pages.js for why these render as <link> tags
687
- pointing at their already-public URL instead of joining
688
- rootCssContents above as inlined content. */
689
- }
690
- {publicCssHrefs.map((href) => <link rel="stylesheet" href={href} />)}
691
- </head>
692
- <body>
693
- {
694
- mode === "blank" ? (
695
- // No site chrome at all - no topbar, no sidebar/toc columns, not
696
- // even the .wd-shell wrapper's own max-width - the page's own
697
- // MDX/components control 100% of the layout, including whether
698
- // there's any nav/branding at all. SearchModal.astro's own overlay
699
- // markup and its ⌘K listener still work even with no visible
700
- // trigger button to click (it's rendered unconditionally below,
701
- // outside this mode === 'blank' branch), so that's left in rather
702
- // than also gated on mode.
703
- <slot />
704
- ) : (
705
- <Fragment>
706
- {/* Everything above the footer, in one wrapper - see .wd-page/body in
707
- base.css: body is a flex column, this is its flex: 1 0 auto item,
708
- and the footer (a plain sibling below, not inside this wrapper) is
709
- what that pushes down to the viewport's bottom edge on a page
710
- short enough not to need scrolling - the "sticky footer" pattern,
711
- not position: sticky/fixed (either of which would cover page
712
- content instead of just trailing it once actually reached). */}
713
- <div class="wd-page">
714
- {config.banner && (
715
- <div class={`wd-banner wd-banner-${config.banner.type}`} id="wd-banner">
716
- <div class="wd-banner-inner">
717
- <span class="wd-banner-content">{config.banner.content}</span>
718
- {config.banner.dismissible && (
719
- <button type="button" class="wd-banner-dismiss" aria-label="Dismiss banner" data-banner-dismiss>
720
- &times;
721
- </button>
722
- )}
723
- </div>
724
- </div>
725
- )}
726
- <TopBar
727
- config={config}
728
- selectors={selectors}
729
- globalDropdowns={globalDropdowns}
730
- showSidebarCol={showSidebarCol}
731
- logoLight={logoLight}
732
- logoDark={logoDark}
733
- brandLabel={brandLabel}
734
- />
735
- <MobileMenu
736
- config={config}
737
- selectors={selectors}
738
- globalDropdowns={globalDropdowns}
739
- showSidebarCol={showSidebarCol}
740
- logoLight={logoLight}
741
- logoDark={logoDark}
742
- brandLabel={brandLabel}
743
- >
744
- <slot name="sidebar" slot="sidebar" />
745
- </MobileMenu>
746
- <div class="wd-shell">
747
- {showSidebarCol && (
748
- <div class="wd-sidebar-col">
749
- <slot name="sidebar" />
750
- </div>
751
- )}
752
- <div class="wd-main-col">
753
- <slot />
754
- </div>
755
- {showTocCol && (
756
- <div class="wd-toc-col">
757
- <slot name="toc" />
758
- </div>
759
- )}
760
- </div>
761
- </div>
762
- <SiteFooter config={config} logoLight={footerLogoLight} logoDark={footerLogoDark} />
763
- </Fragment>
764
- )
765
- }
766
-
767
- <SearchModal />
768
- <ImageZoom />
769
-
770
- <script>
771
- import { initBanner } from "../scripts/banner";
772
- import { initTopbarOffset } from "../scripts/topbar-offset";
773
-
774
- initBanner(document);
775
- document.addEventListener("astro:page-load", () => initBanner(document));
776
-
777
- // No ordering dependency on initBanner above - see topbar-offset.ts
778
- // for why it measures only the topbar itself (not the banner) and
779
- // why that's live-measured rather than a fixed CSS value.
780
- initTopbarOffset();
781
- document.addEventListener("astro:page-load", () => initTopbarOffset());
782
- </script>
783
- {
784
- /* writedocs.json's `scripts.body` - see scriptEntrySchema in lib/config.ts.
785
- Rendered after everything above (including every component's own
786
- <script> tags, which Astro/Vite already bundles to run in document
787
- order) so it runs after every other script on the page has already
788
- loaded/hydrated - matching where a third-party script's own install
789
- instructions usually ask for a "body end" placement. */
790
- }
791
- {
792
- config.scripts.body.map((s) =>
793
- s.src ? <script is:inline src={s.src} /> : <script is:inline set:html={s.content} />,
794
- )
795
- }
796
- {
797
- /* Zero-config custom JS - see findRootAssets() in lib/pages.js and
798
- rootJsContents above. Rendered last, after writedocs.json's own
799
- `scripts.body`, same "most locally-owned override runs last"
800
- reasoning as the root CSS above. `is:inline` here isn't optional -
801
- without it, Astro tries to process/bundle the tag as a module and
802
- the build fails outright ("Cannot find the built path for ...
803
- type=script&index=N") the same way a dynamic-`src` script did
804
- while this file's own writedocs.json `scripts` support was first being
805
- built - see that feature's own commit for the full story. */
806
- }
807
- {rootJsContents.map((content) => <script is:inline set:html={content} />)}
808
- {
809
- /* Zero-config custom JS living in public/ - see this file's own CSS
810
- equivalent above and findRootAssets()'s comment in lib/pages.js.
811
- `<script src>`, not `is:inline set:html` - the file's already a
812
- fetchable URL, no reason to inline its content. Filtered against
813
- config.scripts.head's own `src` entries (publicJsHrefs) for the
814
- same duplicate-tag reason as the CSS <link>s above - note this
815
- only dedupes against `scripts.head`, not `scripts.body` (a public/
816
- file explicitly listed there instead would still also render here
817
- as a second tag; `scripts.head` vs `scripts.body` placement is a
818
- deliberate choice this can't second-guess, but `head` is by far
819
- the more common spot for a plain local script and this hasn't come
820
- up in practice). */
821
- }
822
- {publicJsHrefs.map((href) => <script is:inline src={href} />)}
823
- {
824
- /* writedocs.json's `integrations.askAi` - see AskAiWidget.astro. Rendered
825
- last of all - it's a floating chat widget, not something anything
826
- else on the page depends on running before, so there's no reason
827
- to load it any earlier than absolutely last. */
828
- }
829
- <AskAiWidget config={config} />
830
- </body>
831
- </html>
1
+ ---
2
+ // The site's root HTML shell: <head> meta/SEO tags, the writedocs.json
3
+ // `integrations`/`scripts` passthrough, the color-theme flash-
4
+ // prevention script, the dismissible `banner`, and the three-column
5
+ // .wd-shell (sidebar/main/toc) that every page's own content lands in.
6
+ // Everything else that used to live directly in this file - the topbar,
7
+ // the mobile hamburger drawer, the search modal, the footer, and the
8
+ // analytics/AI-chat integration scripts - is now its own component,
9
+ // composed below. This file had grown to ~2200 lines covering all of
10
+ // those unrelated concerns in one place before that split; each piece is
11
+ // small enough on its own now to read start-to-finish without losing the
12
+ // thread, and a change to (say) the mobile menu no longer means scrolling
13
+ // past a thousand lines of unrelated topbar/search/footer code to find
14
+ // the right spot. This file is the only .astro file that stays directly
15
+ // in src/layout/ - every other component lives in src/layout/components/,
16
+ // and every plain .css file (base.css, banner.css, and the rest each
17
+ // component below imports for itself) lives in src/layout/styles/ - this
18
+ // file is the layout's single entry point/orchestrator, everything else
19
+ // is a piece it composes.
20
+ import fs from "node:fs";
21
+ // Named `nodePath`, not the more natural `path` - this component already
22
+ // destructures a prop called `path` (the current page's own URL path,
23
+ // see Props below) from Astro.props, which would otherwise shadow a
24
+ // module-level `path` import inside this component's own scope, silently
25
+ // turning every `path.join(...)` call into a TypeError at render time
26
+ // ("path.join is not a function") rather than a compile-time error, since
27
+ // both are just plain identifiers to the bundler. Hit and fixed while
28
+ // wiring up findRootAssets() below - real bug, not a hypothetical.
29
+ import nodePath from "node:path";
30
+ import {
31
+ resolveSiteUrl,
32
+ findRootAssets,
33
+ resolveNavbarColor,
34
+ contrastTextColor,
35
+ resolveFonts,
36
+ googleFontsHref,
37
+ fontFaceRule,
38
+ type DocsConfig,
39
+ type Selector,
40
+ type GlobalDropdownView,
41
+ type SeoFields,
42
+ } from "../lib/config";
43
+ import "../styles/global.css";
44
+ // rehypeKatex (astro.config.mjs) renders every $inline$/$$block$$ math
45
+ // span into real KaTeX markup at build time - this is the one runtime
46
+ // dependency that output needs: layout/glyph CSS for the .katex class
47
+ // tree, self-hosted (bundled by Vite, fonts included via its own url()
48
+ // asset resolution) rather than a KaTeX CDN link. Loaded site-wide, same
49
+ // as global.css above - a page with no math in it pays for one small,
50
+ // cached stylesheet and nothing else (no fonts are actually fetched
51
+ // unless a page's rendered KaTeX markup uses their glyphs). KaTeX's own
52
+ // output deliberately sets no explicit text color, inheriting `color`
53
+ // from whatever wraps it - so it already follows this site's light/dark
54
+ // theme with no extra CSS needed here.
55
+ import "katex/dist/katex.min.css";
56
+ import "./styles/base.css";
57
+ import "./styles/banner.css";
58
+ // Astro's client-side router - swaps <body> content between same-origin
59
+ // navigations via the native View Transition API instead of a hard
60
+ // browser reload, so the topbar/sidebar/footer don't visibly flash/
61
+ // "twitch" on every click the way a full document reload does. Every
62
+ // interactive component's own <script> (TopBar's dropdowns, search,
63
+ // TableOfContents, Mermaid, the copy-page menu, ...) already calls its
64
+ // init function once directly *and* re-registers it on the
65
+ // `astro:page-load` event (see e.g. TableOfContents.astro's own
66
+ // `initToc(document); document.addEventListener('astro:page-load', ...)`
67
+ // pair) - that event only ever fires when this router is active, so this
68
+ // was already the intended architecture, just missing this one piece
69
+ // that actually turns it on.
70
+ import { ClientRouter } from "astro:transitions";
71
+ import TopBar from "./components/TopBar.astro";
72
+ import MobileMenu from "./components/MobileMenu.astro";
73
+ import SearchModal from "./components/SearchModal.astro";
74
+ import ImageZoom from "./components/ImageZoom.astro";
75
+ import SiteFooter from "./components/SiteFooter.astro";
76
+ import AnalyticsScripts from "./components/AnalyticsScripts.astro";
77
+ import AskAiWidget from "./components/AskAiWidget.astro";
78
+ import ConsentBanner from "./components/ConsentBanner.astro";
79
+ import { seoHead, hreflangLinks } from "../lib/seo-tags.js";
80
+ import { jsonLd, serializeJsonLd } from "../lib/json-ld.js";
81
+ import { consentOptions } from "../lib/consent.js";
82
+
83
+ interface Props {
84
+ config: DocsConfig;
85
+ title: string;
86
+ // Falls back to config.description when a page has none of its own -
87
+ // see [...slug].astro, which passes entry.data.description straight
88
+ // through without resolving the fallback itself.
89
+ description?: string;
90
+ // The current page's own path (e.g. "/" or "/guides/foo/"), used to
91
+ // build the canonical <link> and og:url/twitter:url - [...slug].astro
92
+ // already computes this via hrefForSlug(currentFileId) for its own
93
+ // prev/next links, so it's passed through rather than recomputed here.
94
+ path: string;
95
+ // Site-wide seo (writedocs.json) merged with this page's own frontmatter
96
+ // seo override - see mergeSeo() in lib/config.ts. [...slug].astro does
97
+ // the merging; this component just renders the result.
98
+ seo?: SeoFields;
99
+ // One Selector per level of the active page's navigation path (tabs,
100
+ // versions, languages, products, or a dropdown used as a nested level)
101
+ // - see resolveSections()/buildSelectors() in lib/config.ts for how
102
+ // this is computed from however the site's writedocs.json nests things.
103
+ // Passed straight through to TopBar.astro and MobileMenu.astro, which
104
+ // each derive their own view of it (TopBar's switcherSelectors/
105
+ // tabSelectors vs. MobileMenu's per-level accordion rows).
106
+ selectors?: Selector[];
107
+ // The always-visible topbar dropdown list from navigation.global.dropdowns
108
+ // - independent of the active selectors, shown on every page. Also
109
+ // passed straight through to TopBar.astro and MobileMenu.astro.
110
+ globalDropdowns?: GlobalDropdownView[];
111
+ // Per-page frontmatter `mode` (content.config.ts) - controls how much
112
+ // site chrome wraps this page. 'blank' drops the topbar and the whole
113
+ // .wd-shell (sidebar/toc columns) entirely, rendering only <slot />
114
+ // directly in <body> - see the template below. Every other mode
115
+ // (including 'custom') still gets the topbar; [...slug].astro is what
116
+ // decides whether to actually pass sidebar/toc slot content for
117
+ // 'wide'/'frame'/'custom' (BaseLayout has no sidebar/toc content of its
118
+ // own to conditionally omit - an unfilled named slot in Astro already
119
+ // renders nothing, so this component only needs to know whether to
120
+ // render the *column wrapper divs* at all).
121
+ mode?: "default" | "wide" | "frame" | "custom" | "blank";
122
+ // The page's language, for <html lang> - the `language` of the
123
+ // navigation level it belongs to (see [...slug].astro), or 'en'.
124
+ lang?: string;
125
+ // This page in each language - `{ lang, href }`, its own included - for
126
+ // the hreflang links (languageAlternates() in lib/item-pages.js). Empty for
127
+ // a page with no counterpart in another language.
128
+ alternates?: { lang: string; href: string }[];
129
+ // Home, the linked groups above the page, the page - for the page's
130
+ // structured data (lib/json-ld.js).
131
+ breadcrumbs?: { name: string; href: string }[];
132
+ // An OpenAPI page: its structured data says APIReference.
133
+ isApi?: boolean;
134
+ }
135
+ const {
136
+ config,
137
+ title,
138
+ description,
139
+ path,
140
+ seo = {},
141
+ selectors = [],
142
+ globalDropdowns = [],
143
+ mode = "default",
144
+ lang = "en",
145
+ alternates = [],
146
+ breadcrumbs = [],
147
+ isApi = false,
148
+ } = Astro.props as Props;
149
+ const showSidebarCol = mode === "default" || mode === "wide";
150
+ const showTocCol = mode === "default";
151
+ // Meta tag resolution - all derived once here rather than inline in the
152
+ // template below, so the JSX stays a straight list of conditional <meta>
153
+ // tags instead of repeating this logic at each call site.
154
+ // seoHead() (lib/seo-tags.js) decides every tag - the <title>, the canonical
155
+ // link, and the description, robots, Open Graph and Twitter metas, with
156
+ // `seo.metatags` replacing or adding to them.
157
+ const siteUrl = resolveSiteUrl(config);
158
+ const head = seoHead({
159
+ title,
160
+ siteName: config.name,
161
+ description,
162
+ siteDescription: config.description,
163
+ seo,
164
+ siteUrl,
165
+ path,
166
+ });
167
+ // hreflang: only on a page search engines index, and only with full URLs.
168
+ const languageLinks = seo.noindex ? [] : hreflangLinks(siteUrl, alternates);
169
+ // Structured data - see lib/json-ld.js for what a page gets.
170
+ const siteLogo = typeof config.styles.logo === "string" ? config.styles.logo : config.styles.logo?.light;
171
+ const structuredData = jsonLd({
172
+ siteUrl,
173
+ siteName: config.name,
174
+ siteDescription: config.description,
175
+ title,
176
+ description: seo.description ?? description ?? config.description,
177
+ path,
178
+ canonical: head.canonical,
179
+ lang,
180
+ mode,
181
+ isApi,
182
+ noindex: Boolean(seo.noindex),
183
+ breadcrumbs,
184
+ organization: config.seo.organization,
185
+ logo: siteLogo,
186
+ socials: config.socials,
187
+ custom: seo.jsonLd,
188
+ });
189
+ // Analytics wait for the reader's answer when the consent banner is on -
190
+ // see lib/consent.js.
191
+ const consent = consentOptions(config.integrations.consent);
192
+ const gated = (s: { consent?: boolean }) => Boolean(consent && s.consent);
193
+ // Light-mode values come straight from styles.colors/styles.background
194
+ // (with defaults); dark-mode values fall back to their light counterpart
195
+ // when the site's own dark override doesn't set them, so a site only has
196
+ // to specify what actually changes for dark mode. Both sets are always
197
+ // computed and handed to the CSS below (light-mode ones as sensible
198
+ // starting defaults, but the .wd-* class hides/shows appropriately) - see
199
+ // the `[data-theme="dark"]` override rule below, which is what actually
200
+ // switches which set is live. Unlike every other bit of CSS this file
201
+ // used to own directly, this specific pair of rules can't move into a
202
+ // plain external .css file the way base.css/banner.css did - `define:vars`
203
+ // (right below) is what lets these raw hex/URL values get interpolated
204
+ // into custom-property assignments at all, and that directive only works
205
+ // on a <style> tag physically inside an .astro file's own template.
206
+ const lightPrimary = config.styles.colors.primary;
207
+ const lightText = config.styles.colors.text ?? "#404045";
208
+ const darkPrimary = config.styles.colors.dark?.primary ?? lightPrimary;
209
+ // Body text - also the sidebar's and table of contents' links. Headings,
210
+ // bold text and group titles use the stronger --wd-heading (below).
211
+ const darkText = config.styles.colors.dark?.text ?? "#a0a0a5";
212
+ // Text drawn on the primary color (step numbers, the info banner, the API
213
+ // playground's buttons) - white, or black on a clearly light primary
214
+ // (contrastTextColor(), lib/config.ts). It used to be white everywhere,
215
+ // unreadable on a light primary - and a light dark-mode primary is exactly
216
+ // what dark-mode links need.
217
+ const lightOnPrimary = contrastTextColor(lightPrimary);
218
+ const darkOnPrimary = contrastTextColor(darkPrimary);
219
+ // styles.background.colors is now the single source for any background
220
+ // color - both the flat --wd-background surface (dropdowns/modals/kbd
221
+ // chips/footer/topbar-fallback/etc., every other `var(--wd-background)`
222
+ // call site) and the <body> canvas paint below. There used to be a
223
+ // separate styles.colors.background/colors.dark.background pair driving
224
+ // just the --wd-background half, independent of this - see config.ts's
225
+ // own comment on why that split was removed; `lightBackground`/
226
+ // `darkBackground` here is what used to read that other field.
227
+ const lightBackground = config.styles.background?.colors?.light ?? "#ffffff";
228
+ const darkBackground = config.styles.background?.colors?.dark ?? "#0b1120";
229
+ // The topbar/mobile-menu-panel background - falls back to the page's own
230
+ // background (above) when a site doesn't set it, so an unconfigured navbar
231
+ // keeps blending into the page exactly as it always has; only sites that
232
+ // explicitly set `styles.navbar.light`/`.dark` get a topbar that looks
233
+ // different from the page behind it. resolveNavbarColor() (lib/config.ts)
234
+ // is what splits the string-or-{background,accent} union `navbar.light`/
235
+ // `.dark` can now be into its two parts - see its own comment.
236
+ const navLight = resolveNavbarColor(config.styles.navbar?.light, lightBackground);
237
+ const navDark = resolveNavbarColor(config.styles.navbar?.dark, darkBackground);
238
+ const lightNavbarBg = navLight.background;
239
+ const darkNavbarBg = navDark.background;
240
+ // Whether this side of `styles.navbar` was configured at all - string or
241
+ // object form, doesn't matter, just "is there a writedocs.json value here" -
242
+ // not merely "does lightNavbarBg differ from the page background", since
243
+ // a site could deliberately set navbar to the *same* color as the page
244
+ // background and this should still count as configured. What this gates:
245
+ // once true, the navbar's own text/icon color stops assuming it's sitting
246
+ // on something close to the page background (--wd-text's own tuning
247
+ // target) and switches to being computed fresh against whatever
248
+ // `background` actually resolved to.
249
+ const lightNavbarConfigured = config.styles.navbar?.light !== undefined;
250
+ const darkNavbarConfigured = config.styles.navbar?.dark !== undefined;
251
+ // --wd-navbar-foreground/-muted: the topbar's own text/icon color, plain
252
+ // (resting) state. Never a writedocs.json value, even indirectly - always
253
+ // contrastTextColor(lightNavbarBg) (lib/config.ts, picks black or white by
254
+ // luminance) the moment this side of `navbar` is configured at all, or the
255
+ // literal --wd-text/--wd-text-muted var references when it isn't, so an
256
+ // unconfigured navbar renders pixel-identical to before this feature
257
+ // existed. An earlier version of this let an object-form field double as
258
+ // both "the navbar's accent color" and "the navbar's text color" - real
259
+ // bug, caught immediately: a site picking a light accent (to stay legible
260
+ // against a dark/saturated background, the whole point of setting it) got
261
+ // that same light color as its *text*, which is exactly backwards. Text
262
+ // legibility isn't a design choice worth exposing at all here - it's
263
+ // always computed, correctly, every time. The muted variant mixes that
264
+ // same resolved color toward transparent (not toward lightNavbarBg, which
265
+ // would drag it back toward the background's own hue and undo the
266
+ // contrast fix) - a plain opacity reduction, so it stays legible
267
+ // regardless of what hue the navbar itself happens to be.
268
+ const lightNavbarFg = lightNavbarConfigured ? contrastTextColor(lightNavbarBg) : "var(--wd-text)";
269
+ const darkNavbarFg = darkNavbarConfigured ? contrastTextColor(darkNavbarBg) : "var(--wd-text)";
270
+ // The current tab (and a hovered one) stands out: the heading color on the
271
+ // page's own background, or the same computed black/white on a configured
272
+ // navbar - which is already the strongest color there.
273
+ const lightNavbarFgStrong = lightNavbarConfigured ? lightNavbarFg : "var(--wd-heading)";
274
+ const darkNavbarFgStrong = darkNavbarConfigured ? darkNavbarFg : "var(--wd-heading)";
275
+ const lightNavbarFgMuted = lightNavbarConfigured
276
+ ? `color-mix(in srgb, ${lightNavbarFg} 70%, transparent)`
277
+ : "var(--wd-text-muted)";
278
+ const darkNavbarFgMuted = darkNavbarConfigured
279
+ ? `color-mix(in srgb, ${darkNavbarFg} 70%, transparent)`
280
+ : "var(--wd-text-muted)";
281
+ // --wd-navbar-accent: the tab-hover-underline/active-tab-fill color inside
282
+ // the topbar specifically - `accent` on the object form (a real, legitimate
283
+ // design choice, unlike text color above), falling back to the sitewide
284
+ // --wd-primary (today's exact behavior) when unset - a site that sets a
285
+ // navbar background but no accent keeps its ordinary brand-colored
286
+ // active-tab underline.
287
+ const lightNavbarAccent = navLight.accent ?? lightPrimary;
288
+ const darkNavbarAccent = navDark.accent ?? darkPrimary;
289
+ // --wd-navbar-border: the switcher pills' (version/language/product) own
290
+ // border. Never the flat --wd-border (a fixed neutral gray/slate tuned for
291
+ // sitting on the page background) once navbar is configured - that reads
292
+ // as a harsh, near-white outline against a saturated/colored navbar
293
+ // background, since it's not picked with that background in mind at all.
294
+ // Same mix-toward-transparent technique as the muted foreground above: a
295
+ // low-opacity tint of the already-contrast-correct navbarFg, so it stays
296
+ // soft and legible against any navbar hue instead of a flat, unrelated
297
+ // gray. Unconfigured navbar keeps the literal var(--wd-border) reference,
298
+ // pixel-identical to before this existed.
299
+ const lightNavbarBorder = lightNavbarConfigured
300
+ ? `color-mix(in srgb, ${lightNavbarFg} 25%, transparent)`
301
+ : "var(--wd-border)";
302
+ const darkNavbarBorder = darkNavbarConfigured
303
+ ? `color-mix(in srgb, ${darkNavbarFg} 25%, transparent)`
304
+ : "var(--wd-border)";
305
+ // --wd-navbar-hover: a topbar tab's background on hover. On a navbar with
306
+ // the page's own background, the sidebar's hover tint (NavTree.astro) -
307
+ // the same 6% of --wd-primary. A configured navbar can *be* the primary
308
+ // color, where that tint would vanish, so there it's a light tint of the
309
+ // navbar's own contrast-correct text color instead, like --wd-navbar-border.
310
+ const sidebarHover = "color-mix(in srgb, var(--wd-primary) 6%, transparent)";
311
+ const lightNavbarHover = lightNavbarConfigured ? `color-mix(in srgb, ${lightNavbarFg} 12%, transparent)` : sidebarHover;
312
+ const darkNavbarHover = darkNavbarConfigured ? `color-mix(in srgb, ${darkNavbarFg} 12%, transparent)` : sidebarHover;
313
+ // The <body> canvas's own paint - same color as --wd-background above
314
+ // (there's only one background color to configure now), plus an optional
315
+ // image layered on top. `images.light`/`.dark` are plain public/-relative
316
+ // paths (same convention as styles.logo/favicon) - wrapped in url(...) here
317
+ // (or 'none' when unset) since CSS custom properties can't have url()
318
+ // applied to them after the fact (`url(var(--x))` isn't valid CSS - the
319
+ // value itself has to already be a full `url(...)` token, which is what
320
+ // these two variables hold).
321
+ const lightPageBgColor = lightBackground;
322
+ const darkPageBgColor = darkBackground;
323
+ const lightPageBgImage = config.styles.background?.images?.light
324
+ ? `url('${config.styles.background.images.light}')`
325
+ : "none";
326
+ const darkPageBgImage = config.styles.background?.images?.dark
327
+ ? `url('${config.styles.background.images.dark}')`
328
+ : "none";
329
+ // A logo is either one path used for both modes, or a {light, dark,
330
+ // label} object - normalized to a single light/dark pair here (the one
331
+ // place that needs to know which form writedocs.json used) so TopBar.astro,
332
+ // MobileMenu.astro, and SiteFooter.astro - each of which render their own
333
+ // copy of the brand link - never need to branch on it themselves. The
334
+ // brand link shows the image(s) alone by default - no site name text next
335
+ // to it, since a real logo asset is usually already a wordmark. `label`
336
+ // (only settable on the object form - see config.ts) opts back into
337
+ // showing text next to the image - or, since `light`/`dark` are
338
+ // themselves optional on that form, stands entirely on its own:
339
+ // `styles.logo: { label: "..." }` with no images at all overrides just the
340
+ // brand text without adding any logo image. A site with neither a logo
341
+ // image nor a label falls back to plain config.name text, so the brand
342
+ // link is never left empty.
343
+ const logo = config.styles.logo;
344
+ const logoLight = typeof logo === "string" ? logo : logo?.light;
345
+ const logoDark = typeof logo === "string" ? logo : logo?.dark;
346
+ const logoLabel = typeof logo === "string" ? undefined : logo?.label;
347
+ const hasLogoImage = Boolean(logoLight || logoDark);
348
+ const brandLabel = logoLabel ?? (hasLogoImage ? undefined : config.name);
349
+
350
+ // writedocs.json's `footer.logo` (same {light, dark, label} shape as
351
+ // `styles.logo` above, via config.ts's shared logoSchema) - unset by
352
+ // default, in which case SiteFooter.astro just gets the same
353
+ // logoLight/logoDark/logoLabel as the topbar/mobile menu above. Set, it
354
+ // replaces those entirely (not just fills in whichever side is missing)
355
+ // before ever reaching SiteFooter - a footer wanting a different mark
356
+ // than the topbar (or none at all - `styles.logo` set, `footer.logo`
357
+ // deliberately absent-of-images-but-present, e.g. `{ label: "" }`, isn't
358
+ // a real use case worth solving here) shouldn't still show the sitewide
359
+ // one alongside or underneath it.
360
+ const footerLogoConfig = config.footer.logo;
361
+ const footerLogoLight = footerLogoConfig
362
+ ? typeof footerLogoConfig === "string"
363
+ ? footerLogoConfig
364
+ : footerLogoConfig.light
365
+ : logoLight;
366
+ const footerLogoDark = footerLogoConfig
367
+ ? typeof footerLogoConfig === "string"
368
+ ? footerLogoConfig
369
+ : footerLogoConfig.dark
370
+ : logoDark;
371
+
372
+ // Zero-config custom CSS/JS - any `.css`/`.js` file anywhere in the
373
+ // project (root, `docs/`, `snippets/`, `public/`, any subfolder -
374
+ // `dist/`/`node_modules/`/etc. excluded, see findRootAssets() in
375
+ // lib/pages.js) is auto-loaded on every page, no writedocs.json entry
376
+ // needed. Read fresh on every render (not cached at module scope) so an
377
+ // edit to one of these files shows up on the next `writedocs dev` page
378
+ // load without a server restart - same freshness `loadDocsConfig(contentDir)`
379
+ // itself already gives writedocs.json edits in [...slug].astro/404.astro.
380
+ // Rendered in addition to, not instead of, writedocs.json's own explicit
381
+ // `scripts` field - that still exists for external/CDN script URLs
382
+ // (`src`) and inline content that should only load under deliberate
383
+ // config, and renders before these so a file living in the project (the
384
+ // more locally-owned override) wins over a URL possibly pointing at
385
+ // someone else's asset.
386
+ const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
387
+ const rootAssets = findRootAssets(contentDir);
388
+ // `name` is a POSIX-separated path relative to contentDir (e.g.
389
+ // "docs/theme.css") - split and rejoin with nodePath.join rather than
390
+ // handing the raw string straight to it, so a nested asset resolves
391
+ // correctly on every OS this might run on, not just POSIX ones.
392
+ const rootCssContents = rootAssets.css.map((name) =>
393
+ fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8"),
394
+ );
395
+ const rootJsContents = rootAssets.js.map((name) =>
396
+ fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8"),
397
+ );
398
+ // public/*.css and public/*.js auto-load too, but as <link>/<script src>
399
+ // pointing at their already-public URL (see findRootAssets()'s own
400
+ // comment for why - no point inlining a file that's also independently
401
+ // fetchable at that exact URL). publicJsHrefs is filtered against
402
+ // writedocs.json's own `scripts.head` so a site that hasn't yet removed an
403
+ // explicit `src` entry for the same public/ file doesn't get that href
404
+ // rendered twice - the explicit entry still works, it's just redundant
405
+ // with this now. publicCssHrefs has no equivalent filter to apply -
406
+ // there's no explicit stylesheet-URL config field anymore.
407
+ const explicitScriptSrcs = new Set(config.scripts.head.map((s) => s.src).filter((src): src is string => Boolean(src)));
408
+ const publicCssHrefs = rootAssets.publicCss;
409
+ const publicJsHrefs = rootAssets.publicJs.filter((href) => !explicitScriptSrcs.has(href));
410
+
411
+ // styles.fonts (see fontsSchema/resolveFonts() in lib/config.ts) - resolves
412
+ // to plain Inter, genuinely loaded via Google Fonts (not just named in a
413
+ // fallback stack the way base.css used to), when a site sets no `fonts`
414
+ // field at all. `fontStack()` quotes the family name (safe even for a
415
+ // single-word name, and required for one with spaces like "Playfair
416
+ // Display") and appends the same system-font fallback chain base.css
417
+ // always used, so a reader who somehow loads the page before the web font
418
+ // finishes fetching still sees a reasonable font rather than the browser
419
+ // default serif. `heading`/`body` are left `null` (not defaulted to the
420
+ // same value as `base`) whenever a site hasn't overridden them - base.css
421
+ // falls back to `--wd-font-family` itself via CSS var(), so a `null` here
422
+ // deliberately never gets its own CSS var written into the style block
423
+ // below.
424
+ const resolvedFonts = resolveFonts(config);
425
+ const fontsGoogleHref = googleFontsHref(resolvedFonts);
426
+ function fontStack(family: string): string {
427
+ return `'${family}', -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;
428
+ }
429
+ // heading/body already fall back to `resolvedFonts.base` right here (not
430
+ // left as a CSS var() fallback chain for :root below to resolve) - same
431
+ // "fully resolve in JS, plain values into define:vars" approach every
432
+ // other themeable value in this file already uses (see lightPrimary/
433
+ // darkPrimary etc. above), rather than introducing a different pattern
434
+ // just for fonts.
435
+ const wdFontFamily = fontStack(resolvedFonts.base.family);
436
+ const wdFontFamilyHeading = resolvedFonts.heading ? fontStack(resolvedFonts.heading.family) : wdFontFamily;
437
+ const wdFontFamilyBody = resolvedFonts.body ? fontStack(resolvedFonts.body.family) : wdFontFamily;
438
+ // One @font-face rule per source-based font actually configured (Google
439
+ // Fonts, covered by fontsGoogleHref above instead, never reach here) - this
440
+ // only ever gets the right *file* loaded (the @font-face `font-weight`
441
+ // descriptor, or the Google Fonts URL's `:wght@` axis inside
442
+ // googleFontsHref() above), not the actual rendered boldness of any
443
+ // element - see wdFontWeightCss right below for that other half.
444
+ const fontFaceCss = [
445
+ fontFaceRule(resolvedFonts.base),
446
+ fontFaceRule(resolvedFonts.heading),
447
+ fontFaceRule(resolvedFonts.body),
448
+ ]
449
+ .filter(Boolean)
450
+ .join("\n");
451
+ // Without this, a configured `weight` only ever changed which font *file*
452
+ // loaded - h1-h6 still rendered at the browser's own default `font-weight:
453
+ // bold` (a user-agent-stylesheet rule, present regardless of which file
454
+ // actually loaded), so a heading weight of e.g. 400 was silently faux-
455
+ // bolded back to looking bold anyway, with no visible effect from
456
+ // changing the config at all. `resolvedFonts.heading?.weight ?? base.weight`
457
+ // falls back the same way family already does (an override with no
458
+ // weight of its own still inherits the top-level one); `undefined` when
459
+ // nothing at any level configured a weight, which deliberately renders no
460
+ // rule at all here - an unconfigured site keeps today's plain browser-
461
+ // default bold headings/normal body text exactly as before this feature
462
+ // existed, not a forced 400/700 nobody asked for.
463
+ const wdFontWeightHeading = resolvedFonts.heading?.weight ?? resolvedFonts.base.weight;
464
+ const wdFontWeightBody = resolvedFonts.body?.weight ?? resolvedFonts.base.weight;
465
+ const fontWeightCss = [
466
+ wdFontWeightHeading !== undefined ? `h1, h2, h3, h4, h5, h6 { font-weight: ${wdFontWeightHeading}; }` : "",
467
+ wdFontWeightBody !== undefined ? `body { font-weight: ${wdFontWeightBody}; }` : "",
468
+ ]
469
+ .filter(Boolean)
470
+ .join("\n");
471
+ const fontExtraCss = [fontFaceCss, fontWeightCss].filter(Boolean).join("\n");
472
+ ---
473
+
474
+ <!doctype html>
475
+ <html lang={lang}>
476
+ <head>
477
+ <meta charset="UTF-8" />
478
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
479
+ {/* Marks the pages writedocs renders - the build checks each has the site's styles (cli/check-built-styles.js). */}
480
+ <meta name="generator" content="writedocs" />
481
+ <title>{head.title}</title>
482
+ <ClientRouter />
483
+ {head.canonical && <link rel="canonical" href={head.canonical} />}
484
+ {languageLinks.map((link) => <link rel="alternate" hreflang={link.hreflang} href={link.href} />)}
485
+ {
486
+ head.metas.map((meta) =>
487
+ meta.attr === "property" ? (
488
+ <meta property={meta.key} content={meta.content} />
489
+ ) : (
490
+ <meta name={meta.key} content={meta.content} />
491
+ ),
492
+ )
493
+ }
494
+ {config.styles.favicon && <link rel="icon" href={config.styles.favicon} />}
495
+ {
496
+ /* styles.fonts - see resolveFonts()/googleFontsHref() in lib/config.ts.
497
+ Present (non-null) whenever at least one configured font (or the
498
+ Inter default, when styles.fonts is unset entirely) has no `source`
499
+ - i.e. is a Google Font, auto-loaded by family name. The two
500
+ preconnect hints warm up the connections googleapis.com's own CSS
501
+ response will immediately need (its @font-face rules point at
502
+ gstatic.com for the actual font files) before the browser has even
503
+ parsed that response - Google's own recommended pattern for using
504
+ their fonts. Rendered this early in <head> (right after favicon,
505
+ before Open Graph/Twitter meta) so the font starts loading as soon
506
+ as possible rather than competing with less render-critical tags
507
+ for bandwidth/priority. */
508
+ }
509
+ {
510
+ fontsGoogleHref && (
511
+ <>
512
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
513
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
514
+ <link rel="stylesheet" href={fontsGoogleHref} />
515
+ </>
516
+ )
517
+ }
518
+ {
519
+ /* writedocs.json's `integrations` (the six analytics providers) - see
520
+ AnalyticsScripts.astro. Rendered as early in <head> as reasonably
521
+ possible (right after the meta tags, before even the theme-
522
+ detection script below) - the usual placement every one of these
523
+ providers' own install instructions ask for, so pageview timing is
524
+ captured as close to actual page load as it can be. */
525
+ }
526
+ {structuredData.map((block) => <script is:inline type="application/ld+json" set:html={serializeJsonLd(block)} />)}
527
+ <AnalyticsScripts
528
+ config={config}
529
+ consent={consent}
530
+ gatedScripts={[...config.scripts.head, ...config.scripts.body].filter(gated)}
531
+ />
532
+ <script is:inline>
533
+ // Sets [data-theme] and [data-banner-dismissed] on <html> before
534
+ // first paint, so the page never flashes the wrong mode or an
535
+ // already-dismissed banner. Preference order for theme: an explicit
536
+ // prior choice (localStorage), then the OS-level preference,
537
+ // defaulting to light. The click handlers that update both live in
538
+ // src/scripts/theme-toggle.ts and src/scripts/banner.ts.
539
+ //
540
+ // Also re-run on `astro:after-swap` (ClientRouter, see BaseLayout's
541
+ // own import of it below), not just the initial load - Astro's
542
+ // client-side navigation swaps <html>'s attributes wholesale to
543
+ // match the newly-fetched page's raw server-rendered markup (see
544
+ // swapRootAttributes() in astro/dist/transitions/swap-functions.js),
545
+ // which has neither of these dataset attributes baked in since
546
+ // they're pure client-side runtime state, not something the server
547
+ // ever renders. Without re-running this after every swap, a
548
+ // dismissed banner (or a chosen dark theme) would silently come
549
+ // back on the very next navigation - both attributes get wiped, not
550
+ // just reset to their default, so this has to unconditionally
551
+ // reapply them from localStorage every time, exactly as it does on
552
+ // first load. `astro:after-swap` fires synchronously right after
553
+ // that swap and before the browser's next paint, so this still
554
+ // prevents any visible flash on client-side navigations too.
555
+ function wdApplyStoredPreferences() {
556
+ try {
557
+ var stored = localStorage.getItem("wd-theme");
558
+ var theme =
559
+ stored === "light" || stored === "dark"
560
+ ? stored
561
+ : window.matchMedia("(prefers-color-scheme: dark)").matches
562
+ ? "dark"
563
+ : "light";
564
+ document.documentElement.dataset.theme = theme;
565
+ } catch (e) {
566
+ document.documentElement.dataset.theme = "light";
567
+ }
568
+ try {
569
+ document.documentElement.dataset.bannerDismissed =
570
+ localStorage.getItem("wd-banner-dismissed") === "true" ? "true" : "false";
571
+ } catch (e) {
572
+ document.documentElement.dataset.bannerDismissed = "false";
573
+ }
574
+ }
575
+ wdApplyStoredPreferences();
576
+ document.addEventListener("astro:after-swap", wdApplyStoredPreferences);
577
+ </script>
578
+ <script>
579
+ // Preserves the sidebar's own scroll position across a ClientRouter
580
+ // navigation - see src/scripts/sidebar-scroll.ts for why this is
581
+ // needed at all (the sidebar is re-rendered fresh, server-side, on
582
+ // every page, so it's a brand-new DOM node each time, reset to
583
+ // scrollTop 0 like a real page reload would be). Same before-swap/
584
+ // after-swap pairing as wdApplyStoredPreferences above, and for the
585
+ // same reason: after-swap fires before the next paint, so there's no
586
+ // visible flash of the sidebar sitting at the top before jumping
587
+ // back to where the reader had it scrolled.
588
+ import { saveSidebarScroll, restoreSidebarScroll } from "../scripts/sidebar-scroll";
589
+
590
+ document.addEventListener("astro:before-swap", saveSidebarScroll);
591
+ document.addEventListener("astro:after-swap", restoreSidebarScroll);
592
+ </script>
593
+ <style
594
+ define:vars={{
595
+ wdPrimaryLight: lightPrimary,
596
+ wdOnPrimaryLight: lightOnPrimary,
597
+ wdBackgroundLight: lightBackground,
598
+ wdTextLight: lightText,
599
+ wdNavbarLight: lightNavbarBg,
600
+ wdNavbarFgLight: lightNavbarFg,
601
+ wdNavbarFgStrongLight: lightNavbarFgStrong,
602
+ wdNavbarFgMutedLight: lightNavbarFgMuted,
603
+ wdNavbarAccentLight: lightNavbarAccent,
604
+ wdNavbarBorderLight: lightNavbarBorder,
605
+ wdNavbarHoverLight: lightNavbarHover,
606
+ wdPageBgColorLight: lightPageBgColor,
607
+ wdPageBgImageLight: lightPageBgImage,
608
+ wdFontFamily,
609
+ wdFontFamilyHeading,
610
+ wdFontFamilyBody,
611
+ wdPrimaryDark: darkPrimary,
612
+ wdOnPrimaryDark: darkOnPrimary,
613
+ wdBackgroundDark: darkBackground,
614
+ wdTextDark: darkText,
615
+ wdNavbarDark: darkNavbarBg,
616
+ wdNavbarFgDark: darkNavbarFg,
617
+ wdNavbarFgStrongDark: darkNavbarFgStrong,
618
+ wdNavbarFgMutedDark: darkNavbarFgMuted,
619
+ wdNavbarAccentDark: darkNavbarAccent,
620
+ wdNavbarBorderDark: darkNavbarBorder,
621
+ wdNavbarHoverDark: darkNavbarHover,
622
+ wdPageBgColorDark: darkPageBgColor,
623
+ wdPageBgImageDark: darkPageBgImage,
624
+ }}
625
+ >
626
+ :root {
627
+ --wd-primary: var(--wdPrimaryLight);
628
+ --wd-on-primary: var(--wdOnPrimaryLight);
629
+ --wd-background: var(--wdBackgroundLight);
630
+ --wd-text: var(--wdTextLight);
631
+ --wd-navbar-background: var(--wdNavbarLight);
632
+ --wd-navbar-foreground: var(--wdNavbarFgLight);
633
+ --wd-navbar-foreground-strong: var(--wdNavbarFgStrongLight);
634
+ --wd-navbar-foreground-muted: var(--wdNavbarFgMutedLight);
635
+ --wd-navbar-accent: var(--wdNavbarAccentLight);
636
+ --wd-navbar-border: var(--wdNavbarBorderLight);
637
+ --wd-navbar-hover: var(--wdNavbarHoverLight);
638
+ --wd-page-bg-color: var(--wdPageBgColorLight);
639
+ --wd-page-bg-image: var(--wdPageBgImageLight);
640
+ --wd-text-muted: #64748b;
641
+ /* Headings, bold text, card titles, and the sidebar's group titles -
642
+ a stronger color than body text (--wd-text), which the sidebar's
643
+ and table of contents' links use (--wd-nav-text). */
644
+ --wd-heading: #18191d;
645
+ --wd-nav-title: var(--wd-heading);
646
+ --wd-nav-text: var(--wd-text);
647
+ --wd-border: #e2e8f0;
648
+ --wd-surface: #f8fafc;
649
+ /* The browser's own controls - the page's scrollbar, a code block's -
650
+ drawn for the theme on screen. Without it they stayed light in dark
651
+ mode. */
652
+ color-scheme: light;
653
+ /* Not mode-dependent (a site's chosen font doesn't change between
654
+ light/dark) - set once here rather than duplicated in the
655
+ :root[data-theme='dark'] block below. */
656
+ --wd-font-family: var(--wdFontFamily);
657
+ --wd-font-family-heading: var(--wdFontFamilyHeading);
658
+ --wd-font-family-body: var(--wdFontFamilyBody);
659
+ }
660
+ /* Higher specificity than the plain :root rule above (an attribute
661
+ selector on :root beats an unqualified one), so this wins
662
+ regardless of source order once data-theme is set to "dark" by
663
+ the inline script above or the toggle button's click handler
664
+ (src/scripts/theme-toggle.ts). */
665
+ :root[data-theme="dark"] {
666
+ --wd-primary: var(--wdPrimaryDark);
667
+ --wd-on-primary: var(--wdOnPrimaryDark);
668
+ --wd-background: var(--wdBackgroundDark);
669
+ --wd-text: var(--wdTextDark);
670
+ --wd-navbar-background: var(--wdNavbarDark);
671
+ --wd-navbar-foreground: var(--wdNavbarFgDark);
672
+ --wd-navbar-foreground-strong: var(--wdNavbarFgStrongDark);
673
+ --wd-navbar-foreground-muted: var(--wdNavbarFgMutedDark);
674
+ --wd-navbar-accent: var(--wdNavbarAccentDark);
675
+ --wd-navbar-border: var(--wdNavbarBorderDark);
676
+ --wd-navbar-hover: var(--wdNavbarHoverDark);
677
+ --wd-page-bg-color: var(--wdPageBgColorDark);
678
+ --wd-page-bg-image: var(--wdPageBgImageDark);
679
+ --wd-text-muted: #94a3b8;
680
+ --wd-heading: #e0e0e5;
681
+ --wd-border: #1e293b;
682
+ --wd-surface: #131a2b;
683
+ color-scheme: dark;
684
+ }
685
+ </style>
686
+ {
687
+ /* styles.fonts: local/externally-hosted font(s) (fontFaceRule() in
688
+ lib/config.ts - a local `source` path resolves the same way
689
+ styles.favicon/styles.logo/styles.background.images already do, see
690
+ collectConfiguredAssetPaths() + styles-asset-integration.js, no
691
+ extra wiring needed here beyond listing it there), plus a
692
+ font-weight override for h1-h6/body whenever `weight` was actually
693
+ configured somewhere (fontWeightCss above) - both concatenated
694
+ into one block since both need the same raw-CSS-text treatment.
695
+ set:html (not a plain <style>{fontExtraCss}</style>) because this
696
+ needs to render already-built CSS text as-is, not have Astro's own
697
+ CSS parser/scoper attempt to process an `@font-face` block or a
698
+ bare `h1, h2, ...` selector list assembled as a runtime string -
699
+ empty string renders nothing when neither piece has anything to
700
+ contribute (every configured font is a Google Font, and no
701
+ `weight` was set anywhere in `styles.fonts`). */
702
+ }
703
+ {fontExtraCss && <style set:html={fontExtraCss} />}
704
+ {
705
+ /* writedocs.json's `scripts.head` - see scriptEntrySchema in lib/config.ts.
706
+ Each entry is exactly one of an external/local `src` or inline
707
+ `content` (enforced by the schema's own .refine()), rendered right
708
+ before </head> so it runs before body content paints - the usual
709
+ spot a third-party script's own install instructions ask for. */
710
+ }
711
+ {
712
+ config.scripts.head
713
+ .filter((s) => !gated(s))
714
+ .map((s) => (s.src ? <script is:inline src={s.src} /> : <script is:inline set:html={s.content} />))
715
+ }
716
+ {
717
+ /* Zero-config custom CSS - see findRootAssets() in lib/pages.js and
718
+ rootCssContents above. Rendered last in <head>, so a project-owned
719
+ file - anywhere in the project, not just the root - wins over
720
+ everything else writedocs generates itself. Inlined as raw <style>
721
+ content rather than a <link> - these files aren't necessarily under
722
+ `public/`, so there's no guaranteed build-time copy step making them
723
+ independently fetchable as a URL; inlining sidesteps needing one.
724
+ One <style> tag per file (not concatenated) so each is independently
725
+ visible/attributable
726
+ in devtools. */
727
+ }
728
+ {rootCssContents.map((content) => <style is:inline set:html={content} />)}
729
+ {
730
+ /* Zero-config custom CSS living in public/ - see findRootAssets()'s
731
+ own comment in lib/pages.js for why these render as <link> tags
732
+ pointing at their already-public URL instead of joining
733
+ rootCssContents above as inlined content. */
734
+ }
735
+ {publicCssHrefs.map((href) => <link rel="stylesheet" href={href} />)}
736
+ </head>
737
+ <body>
738
+ {
739
+ mode === "blank" ? (
740
+ // No site chrome at all - no topbar, no sidebar/toc columns, not
741
+ // even the .wd-shell wrapper's own max-width - the page's own
742
+ // MDX/components control 100% of the layout, including whether
743
+ // there's any nav/branding at all. SearchModal.astro's own overlay
744
+ // markup and its ⌘K listener still work even with no visible
745
+ // trigger button to click (it's rendered unconditionally below,
746
+ // outside this mode === 'blank' branch), so that's left in rather
747
+ // than also gated on mode.
748
+ <slot />
749
+ ) : (
750
+ <Fragment>
751
+ {/* Everything above the footer, in one wrapper - see .wd-page/body in
752
+ base.css: body is a flex column, this is its flex: 1 0 auto item,
753
+ and the footer (a plain sibling below, not inside this wrapper) is
754
+ what that pushes down to the viewport's bottom edge on a page
755
+ short enough not to need scrolling - the "sticky footer" pattern,
756
+ not position: sticky/fixed (either of which would cover page
757
+ content instead of just trailing it once actually reached). */}
758
+ <div class="wd-page">
759
+ {config.banner && (
760
+ <div class={`wd-banner wd-banner-${config.banner.type}`} id="wd-banner">
761
+ <div class="wd-banner-inner">
762
+ <span class="wd-banner-content">{config.banner.content}</span>
763
+ {config.banner.dismissible && (
764
+ <button type="button" class="wd-banner-dismiss" aria-label="Dismiss banner" data-banner-dismiss>
765
+ &times;
766
+ </button>
767
+ )}
768
+ </div>
769
+ </div>
770
+ )}
771
+ <TopBar
772
+ config={config}
773
+ selectors={selectors}
774
+ globalDropdowns={globalDropdowns}
775
+ showSidebarCol={showSidebarCol}
776
+ logoLight={logoLight}
777
+ logoDark={logoDark}
778
+ brandLabel={brandLabel}
779
+ />
780
+ <MobileMenu
781
+ config={config}
782
+ selectors={selectors}
783
+ globalDropdowns={globalDropdowns}
784
+ showSidebarCol={showSidebarCol}
785
+ logoLight={logoLight}
786
+ logoDark={logoDark}
787
+ brandLabel={brandLabel}
788
+ >
789
+ <slot name="sidebar" slot="sidebar" />
790
+ </MobileMenu>
791
+ <div class="wd-shell">
792
+ {showSidebarCol && (
793
+ <div class="wd-sidebar-col">
794
+ <slot name="sidebar" />
795
+ </div>
796
+ )}
797
+ <div class="wd-main-col">
798
+ <slot />
799
+ </div>
800
+ {showTocCol && (
801
+ <div class="wd-toc-col">
802
+ <slot name="toc" />
803
+ </div>
804
+ )}
805
+ </div>
806
+ </div>
807
+ <SiteFooter config={config} logoLight={footerLogoLight} logoDark={footerLogoDark} />
808
+ </Fragment>
809
+ )
810
+ }
811
+
812
+ <SearchModal />
813
+ <ImageZoom />
814
+ {consent && <ConsentBanner consent={consent} />}
815
+
816
+ <script>
817
+ import { initBanner } from "../scripts/banner";
818
+ import { initTopbarOffset } from "../scripts/topbar-offset";
819
+
820
+ initBanner(document);
821
+ document.addEventListener("astro:page-load", () => initBanner(document));
822
+
823
+ // No ordering dependency on initBanner above - see topbar-offset.ts
824
+ // for why it measures only the topbar itself (not the banner) and
825
+ // why that's live-measured rather than a fixed CSS value.
826
+ initTopbarOffset();
827
+ document.addEventListener("astro:page-load", () => initTopbarOffset());
828
+ </script>
829
+ {
830
+ /* writedocs.json's `scripts.body` - see scriptEntrySchema in lib/config.ts.
831
+ Rendered after everything above (including every component's own
832
+ <script> tags, which Astro/Vite already bundles to run in document
833
+ order) so it runs after every other script on the page has already
834
+ loaded/hydrated - matching where a third-party script's own install
835
+ instructions usually ask for a "body end" placement. */
836
+ }
837
+ {
838
+ config.scripts.body
839
+ .filter((s) => !gated(s))
840
+ .map((s) => (s.src ? <script is:inline src={s.src} /> : <script is:inline set:html={s.content} />))
841
+ }
842
+ {
843
+ /* Zero-config custom JS - see findRootAssets() in lib/pages.js and
844
+ rootJsContents above. Rendered last, after writedocs.json's own
845
+ `scripts.body`, same "most locally-owned override runs last"
846
+ reasoning as the root CSS above. `is:inline` here isn't optional -
847
+ without it, Astro tries to process/bundle the tag as a module and
848
+ the build fails outright ("Cannot find the built path for ...
849
+ type=script&index=N") the same way a dynamic-`src` script did
850
+ while this file's own writedocs.json `scripts` support was first being
851
+ built - see that feature's own commit for the full story. */
852
+ }
853
+ {rootJsContents.map((content) => <script is:inline set:html={content} />)}
854
+ {
855
+ /* Zero-config custom JS living in public/ - see this file's own CSS
856
+ equivalent above and findRootAssets()'s comment in lib/pages.js.
857
+ `<script src>`, not `is:inline set:html` - the file's already a
858
+ fetchable URL, no reason to inline its content. Filtered against
859
+ config.scripts.head's own `src` entries (publicJsHrefs) for the
860
+ same duplicate-tag reason as the CSS <link>s above - note this
861
+ only dedupes against `scripts.head`, not `scripts.body` (a public/
862
+ file explicitly listed there instead would still also render here
863
+ as a second tag; `scripts.head` vs `scripts.body` placement is a
864
+ deliberate choice this can't second-guess, but `head` is by far
865
+ the more common spot for a plain local script and this hasn't come
866
+ up in practice). */
867
+ }
868
+ {publicJsHrefs.map((href) => <script is:inline src={href} />)}
869
+ {
870
+ /* writedocs.json's `integrations.askAi` - see AskAiWidget.astro. Rendered
871
+ last of all - it's a floating chat widget, not something anything
872
+ else on the page depends on running before, so there's no reason
873
+ to load it any earlier than absolutely last. */
874
+ }
875
+ <AskAiWidget config={config} />
876
+ </body>
877
+ </html>