@clarusjs/theme-docs 0.2.0 → 0.4.0

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.
package/src/vite.d.ts CHANGED
@@ -11,7 +11,13 @@ export type Options = {
11
11
  * write llms.txt and llms-full.txt to the client output after the build (llmstxt.org)
12
12
  */
13
13
  llms?: LlmsOptions;
14
+ /**
15
+ * parts of the layout replaced by files of the site's own, from
16
+ * the Vite root: `{ header: '/src/theme/header.tscl' }`. Each gets the inputs and slots the theme's part gets.
17
+ */
18
+ components?: Partial<Record<PartName, string>>;
14
19
  };
20
+ export type PartName = 'header' | 'sidebar' | 'contents' | 'pageFooter' | 'footer';
15
21
  export type LlmsOptions = {
16
22
  /**
17
23
  * the site's name, the file's heading
@@ -26,18 +32,6 @@ export type LlmsOptions = {
26
32
  */
27
33
  site?: string;
28
34
  };
29
- /**
30
- * @typedef {object} Options
31
- * @property {string} [pages] the pages folder, from the Vite root (default src/pages)
32
- * @property {boolean} [search] false: no search index (it's written to the client output's search/ after the build)
33
- * @property {LlmsOptions} [llms] write llms.txt and llms-full.txt to the client output after the build (llmstxt.org)
34
- */
35
- /**
36
- * @typedef {object} LlmsOptions
37
- * @property {string} title the site's name, the file's heading
38
- * @property {string} [summary] one or two sentences about the site
39
- * @property {string} [site] the public address (https://example.com): links are absolute with it, root-relative without
40
- */
41
35
  /**
42
36
  * Reads the pages for the sidebar (served as `virtual:theme-docs/pages`) and writes the search index after the build.
43
37
  * @param {Options} [options]
package/src/vite.js CHANGED
@@ -2,8 +2,10 @@
2
2
  // `virtual:theme-docs/pages`, so the sidebar data (not the files) reaches pages rendered in the browser too.
3
3
  // Plain JavaScript: vite.config loads it from node_modules, where Node doesn't strip types. Types are the JSDoc here;
4
4
  // vite.d.ts is generated from it (pnpm types; typecheck and prepack run it).
5
- import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
6
- import { join, resolve } from 'node:path'
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
6
+ import { dirname, join, resolve } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { parse } from 'clarusjs/compiler'
7
9
  import { gitDates } from 'clarusjs/vite'
8
10
  import { CHUNK, termFile, tokens } from './search.js'
9
11
 
@@ -14,8 +16,12 @@ const ID = 'virtual:theme-docs/pages'
14
16
  * @property {string} [pages] the pages folder, from the Vite root (default src/pages)
15
17
  * @property {boolean} [search] false: no search index (it's written to the client output's search/ after the build)
16
18
  * @property {LlmsOptions} [llms] write llms.txt and llms-full.txt to the client output after the build (llmstxt.org)
19
+ * @property {Partial<Record<PartName, string>>} [components] parts of the layout replaced by files of the site's own, from
20
+ * the Vite root: `{ header: '/src/theme/header.tscl' }`. Each gets the inputs and slots the theme's part gets.
17
21
  */
18
22
 
23
+ /** @typedef {'header' | 'sidebar' | 'contents' | 'pageFooter' | 'footer'} PartName */
24
+
19
25
  /**
20
26
  * @typedef {object} LlmsOptions
21
27
  * @property {string} title the site's name, the file's heading
@@ -23,6 +29,65 @@ const ID = 'virtual:theme-docs/pages'
23
29
  * @property {string} [site] the public address (https://example.com): links are absolute with it, root-relative without
24
30
  */
25
31
 
32
+ /** The layout's replaceable parts (#361) and their files in src/parts/. */
33
+ const PARTS = { header: 'header.tscl', sidebar: 'sidebar.tscl', contents: 'contents.tscl', pageFooter: 'page-footer.tscl', footer: 'footer.tscl' }
34
+ const PARTS_DIR = fileURLToPath(new URL('./parts/', import.meta.url))
35
+ const real = (/** @type {string} */ p) => { try { return realpathSync(p) } catch { return p } }
36
+
37
+ /**
38
+ * A .tscl file's inputs (name, and whether it has a default) and slot names ('default' for the unnamed one).
39
+ * @param {string} file
40
+ */
41
+ function contractOf(file) {
42
+ const parsed = parse(readFileSync(file, 'utf8'), file)
43
+ /** @type {Set<string>} */
44
+ const slots = new Set()
45
+ /** @param {any[]} nodes */
46
+ const walk = (nodes) => {
47
+ for (const n of nodes) {
48
+ if (n.type === 'element' && n.tag === 'slot') {
49
+ const name = n.attrs.find((/** @type {any} */ a) => a.name === 'name' && a.kind === 'static')
50
+ slots.add(name ? String(name.value) : 'default')
51
+ }
52
+ for (const key of ['children', 'empty']) if (Array.isArray(n[key])) walk(n[key])
53
+ if (n.type === 'if') for (const b of n.branches) walk(b.children)
54
+ }
55
+ }
56
+ walk(parsed.nodes)
57
+ return { inputs: parsed.inputs.map((i) => ({ name: i.name, required: i.default === undefined })), slots }
58
+ }
59
+
60
+ /**
61
+ * The site's replacements for the layout's parts, as absolute paths by part file, checked against the parts they
62
+ * replace: every part named exists, every file exists, a replacement needs no input the layout doesn't pass, and has
63
+ * every slot the layout fills.
64
+ * @param {Partial<Record<string, string>>} components
65
+ * @param {string} root
66
+ * @returns {Map<string, string>}
67
+ */
68
+ function overridesOf(components, root) {
69
+ /** @type {Map<string, string>} */
70
+ const out = new Map()
71
+ for (const [key, path] of Object.entries(components)) {
72
+ const part = /** @type {Record<string, string>} */ (PARTS)[key]
73
+ if (!part) throw new Error(`themeDocs: components.${key} isn't a part of the theme; the parts are ${Object.keys(PARTS).join(', ')}`)
74
+ if (!path) continue
75
+ const file = resolve(root, path.startsWith('/') ? '.' + path : path)
76
+ if (!existsSync(file)) throw new Error(`themeDocs: components.${key}: no file at ${path}`)
77
+ const theirs = contractOf(join(PARTS_DIR, part))
78
+ const mine = contractOf(file)
79
+ const passed = new Set(theirs.inputs.map((i) => i.name))
80
+ for (const i of mine.inputs) {
81
+ if (i.required && !passed.has(i.name)) throw new Error(`themeDocs: components.${key} (${path}) requires @input ${i.name}, which the layout never passes: give it a default, or remove it`)
82
+ }
83
+ for (const slot of theirs.slots) {
84
+ if (!mine.slots.has(slot)) throw new Error(`themeDocs: components.${key} (${path}) has no ${slot === 'default' ? '<slot />' : `<slot name="${slot}">`}, which the layout fills`)
85
+ }
86
+ out.set(real(join(PARTS_DIR, part)), file)
87
+ }
88
+ return out
89
+ }
90
+
26
91
  /**
27
92
  * Reads the pages for the sidebar (served as `virtual:theme-docs/pages`) and writes the search index after the build.
28
93
  * @param {Options} [options]
@@ -30,15 +95,37 @@ const ID = 'virtual:theme-docs/pages'
30
95
  */
31
96
  export function themeDocs(options = {}) {
32
97
  let dir = resolve(options.pages ?? 'src/pages')
98
+ /** @type {Map<string, string>} */
99
+ let overrides = new Map()
33
100
  return {
34
101
  name: 'clarusjs:theme-docs',
102
+ // Before Vite resolves the layout's relative import of a part itself.
103
+ enforce: 'pre',
104
+ // The replacements, for clarusjs to find like its own components (their styles and islands): no page imports
105
+ // them by path, and they may be outside src/.
106
+ api: {
107
+ /** @param {string} root */
108
+ clarusComponents: (root) => [...overridesOf(options.components ?? {}, root).values()],
109
+ },
35
110
  /** @param {{ root: string }} config */
36
111
  configResolved(config) {
37
112
  dir = resolve(config.root, options.pages ?? 'src/pages')
113
+ overrides = overridesOf(options.components ?? {}, config.root)
38
114
  },
39
- /** @param {string} id */
40
- resolveId(id) {
41
- return id === ID ? '\0' + ID : undefined
115
+ /**
116
+ * @param {string} id
117
+ * @param {string} [importer]
118
+ */
119
+ resolveId(id, importer) {
120
+ if (id === ID) return '\0' + ID
121
+ // The layout's import of a part the site replaced (./parts/x.tscl from the theme): the site's file.
122
+ // The query (?render: the layout rendered in the browser) stays on the site's file.
123
+ if (overrides.size && importer && id.startsWith('./parts/')) {
124
+ const [path, query] = id.split('?', 2)
125
+ const file = overrides.get(real(resolve(dirname(importer.replace(/\?.*$/, '')), /** @type {string} */ (path))))
126
+ if (file) return query === undefined ? file : `${file}?${query}`
127
+ }
128
+ return undefined
42
129
  },
43
130
  /** @param {string} id */
44
131
  load(id) {
@@ -122,6 +209,13 @@ export function readPages(dir) {
122
209
  const group = data.group ?? (parts.length > 2 ? words(parts[1]) : undefined)
123
210
  if (group) page.group = group
124
211
  if (data.order !== undefined && Number.isFinite(Number(data.order))) page.order = Number(data.order)
212
+ if (typeof data.badge === 'string' && data.badge) page.badge = data.badge
213
+ if (data.minutes !== undefined && Number(data.minutes) > 0) page.minutes = Number(data.minutes)
214
+ // A lesson: the XP it can earn, as progress.ts counts it (a step 10, the lesson 50, a quiz right 20).
215
+ if (String(data.steps) === 'true') {
216
+ const body = text.replace(/^```[\s\S]*?^```/gm, '') // not the headings inside code samples
217
+ page.xp = 50 + 10 * (body.match(/^## /gm)?.length ?? 0) + 20 * (body.match(/^:::+ *quiz\b/gm)?.length ?? 0)
218
+ }
125
219
  const updated = dates.get(resolve(dir, file))
126
220
  if (updated !== undefined) page.updated = updated
127
221
  if (data.sidebar === 'false' || parts.some((part) => part.startsWith('['))) page.hidden = true
@@ -137,6 +231,13 @@ const plain = (html) => html.replace(/<[^>]*>/g, (tag) => (BLOCK.test(tag) ? ' '
137
231
  .replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (all, e) => e[0] !== '#' ? ENTITIES[e.toLowerCase()] ?? all : String.fromCodePoint(e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : Number(e.slice(1))))
138
232
  .replace(/\s+/g, ' ').trim()
139
233
 
234
+ /**
235
+ * An element (its tag, through its closing tag) whose class attribute has `name` as a whole token.
236
+ * @param {string} tag
237
+ * @param {string} name
238
+ */
239
+ const withClass = (tag, name) => new RegExp(`<${tag}\\b[^>]*\\bclass="(?:[^"]*\\s)?${name}(?:\\s[^"]*)?"[^>]*>[\\s\\S]*?<\\/${tag}>`)
240
+
140
241
  /**
141
242
  * A built page's search sections: its main content (main#content, without the theme's crumb, inline contents and
142
243
  * footer) split at each h1-h3 with an id. None for pages without one, noindex pages and pages with
@@ -152,9 +253,11 @@ export function sectionsOf(html, url) {
152
253
  if (main === undefined || /\bdata-search="false"/.test(main)) return []
153
254
  const body = main.replace(/<!--[\s\S]*?-->/g, '')
154
255
  .replace(/<(script|style|template)\b[\s\S]*?<\/\1>/gi, '')
155
- .replace(/<p class="crumb">[\s\S]*?<\/p>/, '')
156
- .replace(/<details class="toc-inline">[\s\S]*?<\/details>/, '')
157
- .replace(/<footer class="page-footer">[\s\S]*?<\/footer>/, '')
256
+ // By whole class token: the layout's parts carry their scope class too (class="page-footer cl-c-…"), and a class
257
+ // that only starts the same (crumb-note) isn't one of them.
258
+ .replace(withClass('p', 'crumb'), '')
259
+ .replace(withClass('details', 'toc-inline'), '')
260
+ .replace(withClass('footer', 'page-footer'), '')
158
261
  .replace(/<a class="header-anchor"[\s\S]*?<\/a>/g, '')
159
262
  const parts = body.split(/(<h[1-3]\b[^>]*\bid="[^"]*"[^>]*>[\s\S]*?<\/h[1-3]>)/i)
160
263
  const page = plain(/<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(body)?.[1] ?? /<title>([\s\S]*?)<\/title>/i.exec(html)?.[1] ?? '')