Skip to content

Commit 55c78ba

Browse files
committed
chore: more customizing
1 parent a793466 commit 55c78ba

9 files changed

Lines changed: 291 additions & 7 deletions

File tree

‎src/generators/web/README.md‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,86 @@ The `web` generator accepts the following configuration options:
1515
| `useAbsoluteURLs` | `boolean` | `false` | When `true`, all internal links use absolute URLs based on `baseURL` |
1616
| `editURL` | `string` | `'${GITHUB_EDIT_URL}/doc/api{path}.md'` | URL template for "edit this page" links |
1717
| `pageURL` | `string` | `'{baseURL}/latest-{version}/api{path}.html'` | URL template for documentation page links |
18+
| `head` | `object` | See below | Configurable `<meta>`, `<link>`, and raw markup for the document head |
19+
| `lightningcss` | `object` | `{}` | Options spread into LightningCSS while bundling CSS (see below) |
1820
| `imports` | `object` | See below | Object mapping `#theme/` aliases to component paths for customization |
1921
| `virtualImports` | `object` | `{}` | Additional virtual module mappings merged into the build |
2022

23+
#### `head`
24+
25+
The `head` object controls the project-specific markup injected into the
26+
document `<head>` (rendered into the template's `${head}` placeholder). It has
27+
three keys:
28+
29+
| Key | Type | Description |
30+
| ------- | ------- | ------------------------------------------------------------------------------------------- |
31+
| `meta` | `array` | `<meta>` tags. Each entry is an attribute bag, e.g. `{ name: 'description', content: '…' }` |
32+
| `links` | `array` | `<link>` tags. Each entry is an attribute bag, e.g. `{ rel: 'icon', href: '…' }` |
33+
| `html` | `array` | Raw HTML strings appended verbatim — an escape hatch for anything not expressible above |
34+
35+
Each attribute bag is rendered as a tag: a boolean `true` becomes a valueless
36+
attribute (e.g. `crossorigin`), and `false`/`null`/`undefined` attributes are
37+
omitted. Using arrays of attribute bags (rather than `name → value` maps) means
38+
you can emit repeated tags (e.g. two `preconnect` links) and pick the right
39+
attribute (`name` vs `property`) per tag.
40+
41+
The defaults are Node.js-branded — override `head` entirely to brand the output
42+
for any project:
43+
44+
```js
45+
// doc-kit.config.mjs
46+
export default {
47+
web: {
48+
head: {
49+
meta: [
50+
{ name: 'description', content: 'My project documentation' },
51+
{ property: 'og:image', content: 'https://example.com/og.png' },
52+
],
53+
links: [
54+
{ rel: 'icon', href: 'https://example.com/favicon.ico' },
55+
{ rel: 'stylesheet', href: 'https://example.com/fonts.css' },
56+
],
57+
html: ['<meta name="theme-color" content="#000" />'],
58+
},
59+
},
60+
};
61+
```
62+
63+
> Structural and theme-bound tags are emitted by the template itself rather than
64+
> via `head`: `og:title` (mirrors the per-page title), `og:type`, and the font
65+
> preconnects/stylesheet the bundled UI components rely on.
66+
67+
#### Custom LightningCSS options
68+
69+
The `lightningcss` object is spread directly into [LightningCSS][lightningcss]
70+
while CSS is bundled, so any of its options — `visitor` (custom plugins),
71+
`customAtRules`, `targets`, `drafts`, and so on — are supported. The generator
72+
manages `filename`, `code`, `cssModules`, and `resolver`, so those are ignored.
73+
74+
```js
75+
// doc-kit.config.mjs
76+
export default {
77+
web: {
78+
lightningcss: {
79+
customAtRules: {
80+
mixin: { prelude: '<custom-ident>', body: 'style-block' },
81+
},
82+
visitor: {
83+
Color(color) {
84+
// e.g. transform every color through a design-token map
85+
return color;
86+
},
87+
},
88+
},
89+
},
90+
};
91+
```
92+
93+
To apply more than one visitor, compose them with LightningCSS's
94+
`composeVisitors` helper and pass the result as `visitor`.
95+
96+
[lightningcss]: https://lightningcss.dev/transforms.html
97+
2198
#### Default `imports`
2299

23100
| Alias | Default | Description |
@@ -118,6 +195,7 @@ The HTML template file (set via `templatePath`) uses JavaScript template literal
118195
| `root` | `string` | Relative or absolute path to the site root |
119196
| `metadata` | `object` | Full page metadata (frontmatter, path, heading, etc.) |
120197
| `config` | `object` | The resolved web generator configuration |
198+
| `head` | `string` | Pre-rendered `<meta>`/`<link>`/raw markup from the `head` config |
121199

122200
Since the template supports arbitrary JS expressions, you can use conditionals and method calls:
123201

‎src/generators/web/__tests__/generate.test.mjs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,33 @@ describe('web generate', () => {
5454
assert.doesNotMatch(notFoundResult.html, /href=404\.json/);
5555
assert.doesNotMatch(notFoundResult.html, /href=404\.md/);
5656
});
57+
58+
it('renders the configurable head without hardcoded defaults', async () => {
59+
// `setConfig` resolves generator defaults; mutate the live config to apply
60+
// per-generator overrides (the same object `getConfig('web')` returns).
61+
const config = await setConfig({});
62+
config.web.head = {
63+
meta: [
64+
{ name: 'description', content: 'Custom project docs' },
65+
{ property: 'og:image', content: 'https://example.com/og.png' },
66+
],
67+
links: [{ rel: 'icon', href: 'https://example.com/favicon.ico' }],
68+
html: ['<meta name="theme-color" content="#abcdef" />'],
69+
};
70+
71+
const fs = createEntry('fs', 'File system');
72+
const [fsPage] = await generate([await buildContent([fs], fs)]);
73+
74+
assert.match(fsPage.html, /Custom project docs/);
75+
assert.match(fsPage.html, /https:\/\/example\.com\/og\.png/);
76+
assert.match(fsPage.html, /href=https:\/\/example\.com\/favicon\.ico/);
77+
assert.match(fsPage.html, /content=#abcdef/);
78+
79+
// Project-branding `head` config no longer leaks Node.js defaults.
80+
assert.doesNotMatch(fsPage.html, /nodejs\.org/);
81+
82+
// Structural/theme tags stay hardcoded in the template regardless.
83+
assert.match(fsPage.html, /property=og:type content=website/);
84+
assert.match(fsPage.html, /href=https:\/\/fonts\.googleapis\.com/);
85+
});
5786
});

‎src/generators/web/index.mjs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,48 @@ export default createLazyGenerator({
3535
editURL: `${GITHUB_EDIT_URL}/doc/api{path}.md`,
3636
pageURL: '{baseURL}/latest-{version}/api{path}.html',
3737
remoteConfigUrl: 'https://nodejs.org/site.json',
38+
39+
// Project-specific document `<head>` contents. `meta` and `links` are
40+
// arrays of attribute bags (boolean `true` renders a valueless attribute,
41+
// e.g. `crossorigin`); `html` holds arbitrary raw markup as an escape
42+
// hatch. Structural/theme tags (`og:type`, font preconnects/stylesheets)
43+
// are hardcoded in the template instead.
44+
head: {
45+
meta: [
46+
{
47+
name: 'description',
48+
content:
49+
'Node.js® is a free, open-source, cross-platform JavaScript ' +
50+
'runtime environment that lets developers create servers, web ' +
51+
'apps, command line tools and scripts.',
52+
},
53+
{
54+
property: 'og:description',
55+
content:
56+
'Node.js® is a free, open-source, cross-platform JavaScript ' +
57+
'runtime environment that lets developers create servers, web ' +
58+
'apps, command line tools and scripts.',
59+
},
60+
{
61+
property: 'og:image',
62+
content:
63+
'https://nodejs.org/en/next-data/og/announcement/Node.js%20%E2%80%94%20Run%20JavaScript%20Everywhere',
64+
},
65+
],
66+
links: [
67+
{
68+
rel: 'icon',
69+
href: 'https://nodejs.org/static/images/favicons/favicon.png',
70+
},
71+
],
72+
html: [],
73+
},
74+
75+
// Options spread directly into LightningCSS when bundling CSS, e.g.
76+
// `visitor`, `customAtRules`, `targets`, or `drafts`. See
77+
// https://lightningcss.dev/transforms.html for the full set.
78+
lightningcss: {},
79+
3880
imports: {
3981
'#theme/Logo': '@node-core/ui-components/Common/NodejsLogo',
4082
'#theme/Navigation': join(import.meta.dirname, './ui/components/NavBar'),

‎src/generators/web/template.html‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,13 @@
44
<head>
55
<meta charset="UTF-8" />
66
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
7-
<link rel="icon" href="https://nodejs.org/static/images/favicons/favicon.png"/>
87
<title>${title}</title>
9-
<meta name="description" content="Node.js® is a free, open-source, cross-platform JavaScript runtime environment that lets developers create servers, web apps, command line tools and scripts.">
108
<link rel="stylesheet" href="${root}styles.css" />
119
<meta property="og:title" content="${title}">
12-
<meta property="og:description" content="Node.js® is a free, open-source, cross-platform JavaScript runtime environment that lets developers create servers, web apps, command line tools and scripts.">
13-
<meta property="og:image" content="https://nodejs.org/en/next-data/og/announcement/Node.js%20%E2%80%94%20Run%20JavaScript%20Everywhere" />
1410
<meta property="og:type" content="website">
1511

12+
${head}
13+
1614
<link rel="preconnect" href="https://fonts.googleapis.com" />
1715
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
1816
<link rel="stylesheet"

‎src/generators/web/types.d.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,36 @@
1+
import type { BundleAsyncOptions, CustomAtRules } from 'lightningcss-wasm';
2+
13
import type { JSXContent } from '../jsx-ast/utils/buildContent.mjs';
24

5+
// An attribute bag rendered into an HTML tag. `true` becomes a valueless
6+
// attribute (e.g. `crossorigin`); `false`/`null`/`undefined` are omitted.
7+
export type TagAttributes = Record<
8+
string,
9+
string | number | boolean | null | undefined
10+
>;
11+
12+
export type HeadConfig = {
13+
// `<meta>` tags, each an attribute bag (e.g. `{ name, content }`).
14+
meta: Array<TagAttributes>;
15+
// `<link>` tags, each an attribute bag (e.g. `{ rel, href, crossorigin }`).
16+
links: Array<TagAttributes>;
17+
// Arbitrary raw HTML appended to the document head.
18+
html: Array<string>;
19+
};
20+
321
export type Configuration = {
422
templatePath: string;
523
title: string;
624
useAbsoluteURLs: boolean;
25+
head: HeadConfig;
26+
// Options spread into LightningCSS while bundling CSS. `filename`, `code`,
27+
// `cssModules`, and `resolver` are managed by the generator and ignored here.
28+
lightningcss: Partial<
29+
Omit<
30+
BundleAsyncOptions<CustomAtRules>,
31+
'filename' | 'code' | 'cssModules' | 'resolver'
32+
>
33+
>;
734
imports: Record<string, string>;
835
virtualImports: Record<string, string>;
936
};

‎src/generators/web/utils/__tests__/processing.test.mjs‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import assert from 'node:assert/strict';
22
import { describe, it } from 'node:test';
33

4-
import { populateWithEvaluation } from '../processing.mjs';
4+
import { buildHead, populateWithEvaluation } from '../processing.mjs';
55

66
describe('populateWithEvaluation', () => {
77
it('substitutes simple ${variable} placeholders', () => {
@@ -61,3 +61,57 @@ describe('populateWithEvaluation', () => {
6161
assert.strictEqual(result, 'count: 42');
6262
});
6363
});
64+
65+
describe('buildHead', () => {
66+
it('renders meta tags from attribute bags', () => {
67+
const result = buildHead({
68+
meta: [
69+
{ name: 'description', content: 'Docs' },
70+
{ property: 'og:type', content: 'website' },
71+
],
72+
links: [],
73+
html: [],
74+
});
75+
76+
assert.match(result, /<meta name="description" content="Docs" \/>/);
77+
assert.match(result, /<meta property="og:type" content="website" \/>/);
78+
});
79+
80+
it('renders boolean attributes as valueless and omits nullish ones', () => {
81+
const result = buildHead({
82+
meta: [],
83+
links: [
84+
{ rel: 'preconnect', href: 'https://a.example' },
85+
{ rel: 'preconnect', href: 'https://b.example', crossorigin: true },
86+
{ rel: 'icon', href: 'https://c.example', integrity: null },
87+
],
88+
html: [],
89+
});
90+
91+
// Two distinct preconnect tags prove arrays beat a `rel → href` map.
92+
assert.match(
93+
result,
94+
/<link rel="preconnect" href="https:\/\/a\.example" \/>/
95+
);
96+
assert.match(
97+
result,
98+
/<link rel="preconnect" href="https:\/\/b\.example" crossorigin \/>/
99+
);
100+
// `integrity: null` is dropped entirely.
101+
assert.match(result, /<link rel="icon" href="https:\/\/c\.example" \/>/);
102+
});
103+
104+
it('appends raw HTML strings verbatim', () => {
105+
const result = buildHead({
106+
meta: [],
107+
links: [],
108+
html: ['<meta name="theme-color" content="#000" />'],
109+
});
110+
111+
assert.match(result, /<meta name="theme-color" content="#000" \/>/);
112+
});
113+
114+
it('returns an empty string when nothing is configured', () => {
115+
assert.strictEqual(buildHead({ meta: [], links: [], html: [] }), '');
116+
});
117+
});

‎src/generators/web/utils/config.mjs‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,17 @@ export default function createConfigSource(input) {
8484
const exports = {
8585
...omitKeys(
8686
config,
87-
// These are keys that are large, and not needed by components, so we ignore them
88-
['changelog', 'index', 'imports', 'virtualImports']
87+
// These are keys that are large, build-time only (e.g. the document head
88+
// and CSS options), or not serializable (e.g. `lightningcss` visitor
89+
// functions), so they are never exposed to client components.
90+
[
91+
'changelog',
92+
'index',
93+
'imports',
94+
'virtualImports',
95+
'head',
96+
'lightningcss',
97+
]
8998
),
9099
version: configVersion,
91100
versions: buildVersionEntries(config.changelog, pageURL),

‎src/generators/web/utils/css.mjs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { readFile } from 'node:fs/promises';
22

33
import { bundleAsync } from 'lightningcss-wasm';
44

5+
import getConfig from '../../../utils/configuration/index.mjs';
6+
57
// Since we use rolldown to bundle multiple times,
68
// we re-use a lot of CSS files, so there is no
79
// need to re-transpile.
@@ -21,6 +23,10 @@ const fileCache = new Map();
2123
export default () => {
2224
const cssChunks = new Set();
2325

26+
// User-supplied LightningCSS options (e.g. `visitor`, `customAtRules`),
27+
// spread into every bundle call below.
28+
const { lightningcss = {} } = getConfig('web');
29+
2430
return {
2531
name: 'css-loader', // Required plugin name for debugging
2632

@@ -57,6 +63,7 @@ export default () => {
5763

5864
// Use Lightning CSS to compile the file with CSS Modules enabled
5965
const { code, exports } = await bundleAsync({
66+
...lightningcss,
6067
filename: id,
6168
code: Buffer.from(source),
6269
cssModules: id.endsWith('module.css'),

0 commit comments

Comments
 (0)