@bigmistqke/whiteboard 0.7.0 → 0.8.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.
Files changed (66) hide show
  1. package/README.md +10 -209
  2. package/bin/whiteboard.ts +82 -239
  3. package/dist/bin/whiteboard.js +70 -200
  4. package/dist/client/runtime.js +66 -7
  5. package/dist/plugins/chat/public/style.css +10 -6
  6. package/dist/plugins/code/README.md +10 -0
  7. package/dist/plugins/code/index.js +31 -22
  8. package/dist/plugins/code/public/client.js +1 -0
  9. package/dist/plugins/code/public/style.css +33 -2
  10. package/dist/plugins/comments/public/client.js +1 -1
  11. package/dist/plugins/form/public/style.css +2 -0
  12. package/dist/plugins/iframe/index.js +2 -2
  13. package/dist/plugins/lightbox/public/client.js +1 -1
  14. package/dist/plugins/terminal/index.js +7 -9
  15. package/dist/plugins/terminal/public/client.js +1 -1
  16. package/dist/plugins/terminal/public/style.css +3 -3
  17. package/dist/plugins/toc/index.js +1 -1
  18. package/dist/plugins/toc/public/client.js +1 -1
  19. package/dist/plugins/window/index.js +4 -4
  20. package/dist/src/build.js +159 -0
  21. package/dist/src/client/page/main.js +1 -1
  22. package/dist/src/document.js +93 -0
  23. package/dist/src/events.js +3 -13
  24. package/dist/src/hub.js +47 -35
  25. package/dist/src/listen.js +100 -0
  26. package/dist/src/listeners.js +67 -0
  27. package/dist/src/pages/index.js +1 -1
  28. package/dist/src/pages/markdown.js +23 -11
  29. package/dist/src/pages/render.js +13 -8
  30. package/dist/src/server.js +166 -514
  31. package/dist/src/site.js +173 -0
  32. package/dist/src/status.js +63 -1
  33. package/package.json +1 -1
  34. package/plugins/README.md +258 -0
  35. package/plugins/chat/public/style.css +10 -6
  36. package/plugins/code/README.md +10 -0
  37. package/plugins/code/client.ts +73 -0
  38. package/plugins/code/index.ts +38 -26
  39. package/plugins/code/public/style.css +33 -2
  40. package/plugins/comments/client.ts +8 -1
  41. package/plugins/form/public/style.css +2 -0
  42. package/plugins/iframe/index.ts +2 -2
  43. package/plugins/lightbox/client.ts +13 -3
  44. package/plugins/terminal/client.ts +10 -2
  45. package/plugins/terminal/index.ts +8 -6
  46. package/plugins/terminal/public/style.css +3 -3
  47. package/plugins/toc/client.ts +9 -2
  48. package/plugins/toc/index.ts +1 -1
  49. package/plugins/window/index.ts +4 -4
  50. package/skills/whiteboard/SKILL.md +3 -1
  51. package/src/build.ts +213 -0
  52. package/src/client/page/elsewhere.ts +2 -1
  53. package/src/client/runtime.ts +88 -10
  54. package/src/client/toast.ts +1 -1
  55. package/src/define.ts +34 -18
  56. package/src/document.ts +191 -0
  57. package/src/events.ts +11 -16
  58. package/src/hub.ts +48 -34
  59. package/src/listen.ts +125 -0
  60. package/src/listeners.ts +95 -0
  61. package/src/pages/index.ts +1 -1
  62. package/src/pages/markdown.ts +29 -18
  63. package/src/pages/render.ts +13 -8
  64. package/src/server.ts +165 -609
  65. package/src/site.ts +165 -0
  66. package/src/status.ts +100 -0
@@ -46,8 +46,11 @@ export default function code(options: Options = {}): Plugin {
46
46
  let shiki: typeof Shiki | undefined
47
47
  const loaded = new Set<string>()
48
48
 
49
- /** Highlight `code` as `lang`; an unknown or missing language renders as plain text. */
50
- async function highlight(code: string, lang: string | null) {
49
+ /**
50
+ * Highlight `code` as `lang`; an unknown or missing language renders as plain text. A long line
51
+ * scrolls the block sideways; with `wrap` it wraps at the block's edge.
52
+ */
53
+ async function highlight(code: string, lang: string | null, wrap = false) {
51
54
  shiki ??= await import('shiki')
52
55
  highlighter ??= shiki.createHighlighter({ themes: Object.values(themes), langs: [] })
53
56
  const h = await highlighter
@@ -59,45 +62,54 @@ export default function code(options: Options = {}): Plugin {
59
62
  }
60
63
  } else language = 'text'
61
64
  const diff = language === 'diff' ? diffLines(code) : null
65
+ const transformers: Shiki.ShikiTransformer[] = []
66
+ // a fence that says {wrap}: its long lines wrap (style.css)
67
+ if (wrap)
68
+ transformers.push({
69
+ pre(node) {
70
+ node.properties['data-wrap'] = ''
71
+ },
72
+ })
73
+ if (diff)
74
+ transformers.push({
75
+ line(node, n) {
76
+ const info = diff[n - 1]
77
+ if (!info) return
78
+ node.properties['data-diff'] = info.kind
79
+ if (info.n != null) node.properties['data-n'] = String(info.n)
80
+ if (info.at) node.properties['data-wb-at'] = info.at
81
+ // a file's headers read as its name; a hunk's header as nothing but the gutter's `⋯`
82
+ if (info.label != null) node.children = [{ type: 'text', value: info.label }]
83
+ },
84
+ // the headers nobody reads go, with the line break after each
85
+ code(node) {
86
+ node.children = node.children.filter((child, i, all) => {
87
+ const isMeta = (c: typeof child | undefined) =>
88
+ c?.type === 'element' && c.properties['data-diff'] === 'meta'
89
+ return !isMeta(child) && !(child.type === 'text' && isMeta(all[i - 1]))
90
+ })
91
+ },
92
+ })
62
93
  return h.codeToHtml(code, {
63
94
  lang: language,
64
95
  themes,
65
96
  defaultColor: false,
66
97
  colorReplacements,
67
- transformers: diff
68
- ? [
69
- {
70
- line(node, n) {
71
- const info = diff[n - 1]
72
- if (!info) return
73
- node.properties['data-diff'] = info.kind
74
- if (info.n != null) node.properties['data-n'] = String(info.n)
75
- if (info.at) node.properties['data-wb-at'] = info.at
76
- // a file's headers read as its name; a hunk's header as nothing but the gutter's `⋯`
77
- if (info.label != null) node.children = [{ type: 'text', value: info.label }]
78
- },
79
- // the headers nobody reads go, with the line break after each
80
- code(node) {
81
- node.children = node.children.filter((child, i, all) => {
82
- const isMeta = (c: typeof child | undefined) =>
83
- c?.type === 'element' && c.properties['data-diff'] === 'meta'
84
- return !isMeta(child) && !(child.type === 'text' && isMeta(all[i - 1]))
85
- })
86
- },
87
- },
88
- ]
89
- : [],
98
+ transformers,
90
99
  })
91
100
  }
92
101
 
93
102
  return definePlugin({
94
103
  name: 'code',
95
104
  public: builtinPublic('code'),
105
+ // measures whether each code block overflows, so its scrollbar is chosen in advance (client.ts:
106
+ // a WebKit layout bug)
107
+ setup: () => ({ client: 'client.js' }),
96
108
  blocks: {
97
109
  code: {
98
110
  // every code fence no other block claims by name, and the code view of repository files
99
111
  fence: 'any',
100
- html: ctx => highlight((ctx as FenceContext).text, (ctx as FenceContext).lang),
112
+ html: ctx => highlight((ctx as FenceContext).text, (ctx as FenceContext).lang, 'wrap' in ctx.attrs),
101
113
  style: 'style.css',
102
114
  },
103
115
  },
@@ -24,12 +24,39 @@ pre.shiki {
24
24
  text-decoration: var(--shiki-dark-text-decoration);
25
25
  }
26
26
 
27
+ /* a long line scrolls the block sideways, wherever it is; a fence that says {wrap} wraps it. The
28
+ code inside the block scrolls, not the block: WebKit sizes a block that scrolls sideways without
29
+ its scrollbar, so the bar ate into its height (a vertical scrollbar came with it) */
30
+ pre.shiki {
31
+ white-space: pre;
32
+ overflow-wrap: normal;
33
+ overflow: visible;
34
+ }
35
+ pre.shiki > code {
36
+ display: block;
37
+ overflow-x: auto;
38
+ overflow-y: hidden;
39
+ }
40
+ /* the scrollbar chosen in advance, from measured overflow (client.ts): WebKit lays out an `auto`
41
+ scrollbar under a flex or grid ancestor after the ancestors, which keep the height they had
42
+ without it (https://github.com/block/buzz-app/pull/1677,
43
+ https://bugs.webkit.org/show_bug.cgi?id=51148) */
44
+ pre.shiki > code[data-overflow='true'] {
45
+ overflow-x: scroll;
46
+ }
47
+ pre.shiki > code[data-overflow='false'] {
48
+ overflow-x: hidden;
49
+ }
50
+ pre.shiki[data-wrap] {
51
+ white-space: pre-wrap;
52
+ overflow-wrap: anywhere;
53
+ }
54
+
27
55
  /* a diff: one row per line, as wide as the longest (a grid leaves out the line breaks between them,
28
56
  which stay in the text), tinted by what it is, with its number in a gutter */
29
57
  .shiki code:has(> .line[data-diff]) {
30
58
  display: grid;
31
- width: max-content;
32
- min-width: 100%;
59
+ grid-template-columns: minmax(max-content, 1fr);
33
60
  }
34
61
  .shiki .line[data-diff='add'] {
35
62
  background: color-mix(in srgb, #16a34a var(--tint-soft), transparent);
@@ -66,3 +93,7 @@ pre.shiki {
66
93
  .shiki .line[data-diff='file'] + .line[data-diff='hunk'] {
67
94
  margin-top: 0;
68
95
  }
96
+ /* a diff that wraps: its rows fill the block, and a long one wraps inside its row */
97
+ pre.shiki[data-wrap] code:has(> .line[data-diff]) {
98
+ grid-template-columns: minmax(0, 1fr);
99
+ }
@@ -476,7 +476,14 @@ const mount: PluginMount = (el: HTMLElement, handle: PageHandle, core: Api) => {
476
476
  root = el
477
477
  main = root.querySelector('main') ?? root
478
478
  api = core
479
- document.body.append(layer, startButton, lineButton, popover, composer)
479
+ // over the page, in document coordinates: its element in the overlay slot is laid out as if these
480
+ // were at the end of <body>
481
+ core.slot('overlay', place => {
482
+ place.append(layer, startButton, lineButton, popover, composer)
483
+ return () => {
484
+ for (const part of [layer, startButton, lineButton, popover, composer]) part.remove()
485
+ }
486
+ })
480
487
 
481
488
  document.addEventListener('mousemove', onLinePointer)
482
489
  // the pointer left the page: no line is hovered any more (a drag keeps its lines until mouseup)
@@ -5,6 +5,8 @@
5
5
  border-top: var(--hairline) solid var(--border);
6
6
  border-bottom: var(--hairline) solid var(--border);
7
7
  display: grid;
8
+ /* one column, as wide as the form: wide content (a code block) scrolls inside it, not past it */
9
+ grid-template-columns: minmax(0, 1fr);
8
10
  gap: var(--space-2xl);
9
11
  }
10
12
  .wb-form-pending {
@@ -25,14 +25,14 @@ export async function render(ctx: DirectiveContext) {
25
25
  const title = ctx.labelText ?? ctx.attrs.title ?? src
26
26
  // the frame, which the reader can drag taller
27
27
  return html`<div class="wb-iframe-frame" style="height: ${height(ctx.attrs.height)}">
28
- <iframe src="${src}" title="${title}" loading="lazy" referrerpolicy="no-referrer"></iframe>
28
+ <iframe src="${ctx.fileUrl(src)}" title="${title}" loading="lazy" referrerpolicy="no-referrer"></iframe>
29
29
  </div>`
30
30
  }
31
31
 
32
32
  /** What it shows on its own, for the ↗ of a window around it: its address. */
33
33
  export function open(ctx: DirectiveContext) {
34
34
  const src = (ctx.attrs.src ?? '').trim()
35
- return src && safeSrc(src) ? src : null
35
+ return src && safeSrc(src) ? ctx.fileUrl(src) : null
36
36
  }
37
37
 
38
38
  export default function iframe(): Plugin {
@@ -61,7 +61,7 @@ function open(scope: Element, picture: HTMLImageElement) {
61
61
  else if (target.closest('.wb-lightbox-next')) step(1)
62
62
  else if (target.closest('.wb-lightbox-close') || target === overlay || target.matches('.wb-lightbox-stage')) close()
63
63
  })
64
- document.body.append(overlay)
64
+ place?.append(overlay)
65
65
  show()
66
66
  }
67
67
 
@@ -76,14 +76,24 @@ function close() {
76
76
  overlay = null
77
77
  }
78
78
 
79
+ /** Where an open lightbox goes: this plugin's element in the overlay slot. */
80
+ let place: HTMLElement | null = null
81
+
79
82
  let listening = false
80
- const mount: PluginMount = () => {
83
+ const mount: PluginMount = (_root, _page, api) => {
84
+ api.slot('overlay', el => {
85
+ place = el
86
+ return () => {
87
+ close()
88
+ place = null
89
+ }
90
+ })
81
91
  if (listening) return
82
92
  listening = true
83
93
  document.addEventListener('click', e => {
84
94
  const picture = (e.target as Element).closest?.('img')
85
95
  const scope = picture?.closest('[data-lightbox]')
86
- if (!picture || !scope || picture.closest('a, .wb-lightbox')) return
96
+ if (!picture || !scope || !place || picture.closest('a, .wb-lightbox')) return
87
97
  e.preventDefault()
88
98
  open(scope, picture)
89
99
  })
@@ -8,6 +8,7 @@
8
8
  // its tab, so switching pages loses nothing.
9
9
  import { Terminal } from '@xterm/xterm'
10
10
  import { FitAddon } from '@xterm/addon-fit'
11
+ import type { PluginMount } from '../../src/define.ts'
11
12
 
12
13
  const store = {
13
14
  get: (k: string) => {
@@ -379,5 +380,12 @@ function post(url: string, body: unknown) {
379
380
  return fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
380
381
  }
381
382
 
382
- const drawer = document.getElementById('wb-terminal')
383
- if (drawer) init(drawer)
383
+ /** Mounts on the drawer the server rendered into this plugin's element in the bottom slot. */
384
+ const mount: PluginMount = (_root, _page, api) => {
385
+ api.slot('bottom', el => {
386
+ const drawer = el.querySelector<HTMLElement>('#wb-terminal')
387
+ if (drawer) init(drawer)
388
+ })
389
+ }
390
+
391
+ export default mount
@@ -29,7 +29,7 @@ const STYLE = 'style.css'
29
29
  * render, and each session's screen is in it as HTML, so a page shows it from its first render on;
30
30
  * client.js puts the live terminal in its place.
31
31
  */
32
- const drawer = (state: Sessions, screens: Record<string, string>, client: string) =>
32
+ const drawer = (state: Sessions, screens: Record<string, string>) =>
33
33
  html`<aside id="wb-terminal" aria-label="Terminal" data-sessions="${JSON.stringify(state)}">
34
34
  <div class="wb-term-grip" title="drag to resize"></div>
35
35
  <div class="wb-term-bar">
@@ -61,8 +61,7 @@ const drawer = (state: Sessions, screens: Record<string, string>, client: string
61
61
  t.querySelector('.wb-term-placeholder[data-id="' + a.dataset.id + '"]')?.classList.add('wb-current')
62
62
  }
63
63
  } catch {}
64
- </script>
65
- <script type="module" src="${client}"></script>`
64
+ </script>`
66
65
 
67
66
  export default function terminal(): Plugin {
68
67
  return {
@@ -72,8 +71,9 @@ export default function terminal(): Plugin {
72
71
  style: STYLE,
73
72
  setup(ctx) {
74
73
  const term = createTerminal({ dir: ctx.project.dir, home: ctx.dataDir })
75
- const client = ctx.asset(CLIENT)
76
74
  return {
75
+ // the drawer comes alive: client.js mounts on it in its slot
76
+ client: CLIENT,
77
77
  // all of them run code or show what runs, so all need the project's token
78
78
  routes: {
79
79
  'GET /sessions': {
@@ -132,10 +132,12 @@ export default function terminal(): Plugin {
132
132
  run: ({ body }) => term.open(body.id as string | undefined, body.path as string),
133
133
  },
134
134
  },
135
- async shell(req) {
135
+ // the drawer, in the bottom slot, there on the first render: the view transition between two
136
+ // pages morphs it, and the page leaves room for it from the first paint
137
+ async slots(req) {
136
138
  if (!ctx.authorized(req)) return null
137
139
  const state = await term.sessions()
138
- return { body: drawer(state, await term.screens(state.sessions), client) }
140
+ return { bottom: drawer(state, await term.screens(state.sessions)) }
139
141
  },
140
142
  }
141
143
  },
@@ -17,10 +17,10 @@
17
17
  --wb-term-h: 320px;
18
18
  --wb-term-bar: 34px;
19
19
  }
20
- :root:has(body > #wb-terminal) {
20
+ :root:has(#wb-terminal) {
21
21
  --wb-inset-bottom: var(--wb-term-bar);
22
22
  }
23
- :root:has(body > #wb-terminal[data-state='open']) {
23
+ :root:has(#wb-terminal[data-state='open']) {
24
24
  --wb-inset-bottom: calc(var(--wb-term-bar) + var(--wb-term-h));
25
25
  }
26
26
 
@@ -42,7 +42,7 @@
42
42
  system-ui,
43
43
  sans-serif;
44
44
  }
45
- body:has(> #wb-terminal) {
45
+ body:has(#wb-terminal) {
46
46
  padding-bottom: var(--wb-inset-bottom);
47
47
  }
48
48
 
@@ -190,8 +190,15 @@ const mount: PluginMount = (root, page, core) => {
190
190
  handle = page
191
191
  main = root.querySelector<HTMLElement>('#wb-main') ?? root
192
192
  api = core
193
- document.body.append(panel)
194
- root.querySelector('.wb-nav .wb-theme')?.before(toggle)
193
+ // the panel beside the text, its button in the header bar
194
+ core.slot('aside', place => {
195
+ place.append(panel)
196
+ return () => panel.remove()
197
+ })
198
+ core.slot('header', place => {
199
+ place.append(toggle)
200
+ return () => toggle.remove()
201
+ })
195
202
  list.addEventListener('click', e => {
196
203
  const a = (e.target as HTMLElement).closest<HTMLElement>('a[data-index]')
197
204
  if (!a) return
@@ -42,7 +42,7 @@ export default function toc(options: TocOptions = {}): Plugin {
42
42
  setup: () => ({
43
43
  client: 'client.js',
44
44
  // how the browser part knows: on every page, or only where the frontmatter asks
45
- shell: () => ({
45
+ slots: () => ({
46
46
  head: html`<meta
47
47
  name="wb-toc"
48
48
  content="${options.always ? 'always' : 'opt-in'}"
@@ -45,12 +45,12 @@ ${kind}: needs a src, like ::${kind}[a label]{src="${kind === 'image' ? 'shot.pn
45
45
  return html`<pre class="wb-error">${kind}: src must be an http(s) URL or a path, not ${src.split(':')[0]}:</pre>`
46
46
  const alt = ctx.labelText ?? ctx.attrs.alt ?? ''
47
47
  const flag = (name: string) => name in ctx.attrs && raw(` ${name}`)
48
- const poster = ctx.attrs.poster && safeSrc(ctx.attrs.poster) ? html` poster="${ctx.attrs.poster}"` : ''
48
+ const poster = ctx.attrs.poster && safeSrc(ctx.attrs.poster) ? html` poster="${ctx.fileUrl(ctx.attrs.poster)}"` : ''
49
49
  const body =
50
50
  kind === 'image'
51
- ? html`<img src="${src}" alt="${alt}" loading="lazy" />`
51
+ ? html`<img src="${ctx.fileUrl(src)}" alt="${alt}" loading="lazy" />`
52
52
  : html`<video
53
- src="${src}"
53
+ src="${ctx.fileUrl(src)}"
54
54
  controls${flag('loop')}${flag('autoplay')}${'autoplay' in ctx.attrs || 'muted' in ctx.attrs ? raw(' muted') : ''}
55
55
  playsinline
56
56
  preload="metadata"
@@ -62,7 +62,7 @@ ${kind}: needs a src, like ::${kind}[a label]{src="${kind === 'image' ? 'shot.pn
62
62
  /** What an image or video shows on its own, for the ↗ of a window around it: its file. */
63
63
  const mediaOpen = (ctx: DirectiveContext) => {
64
64
  const src = (ctx.attrs.src ?? '').trim()
65
- return src && safeSrc(src) ? src : null
65
+ return src && safeSrc(src) ? ctx.fileUrl(src) : null
66
66
  }
67
67
 
68
68
  export async function render(ctx: DirectiveContext) {
@@ -206,7 +206,9 @@ to a heading (by its text), a form (by its name) or any text on it, opens a
206
206
  details around it, and lights it up a moment. Use it when you talk about a
207
207
  part of a long page ("see the risks section"), or to bring the user to a
208
208
  question you just added. It exits 1 when nothing on the page matches, or when
209
- no browser has the page open (then `show` it first).
209
+ no tab of the page is connected now: then a tab that is open still scrolls
210
+ there once it is back (a background tab connects again when it is shown);
211
+ else `show` the page first.
210
212
 
211
213
  ## Getting answers
212
214
 
package/src/build.ts ADDED
@@ -0,0 +1,213 @@
1
+ // Pages rendered once (`whiteboard build`), as files: each page's HTML with its links relative, and
2
+ // what it loads copied beside it, under its own ids and addresses (a site of its own: the server's is
3
+ // site.ts's servedSite). The page around a render is document.ts's, as for a page the server serves.
4
+ // See BuildConfig.
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { stripTypeScriptTypes } from 'node:module'
8
+ import type { Project } from './config.ts'
9
+ import type { BuildConfig } from './define.ts'
10
+ import { RUNTIME, pageDocument, pluginParts, type SetUp } from './document.ts'
11
+ import { toPath, type LoadedConfig } from './loader.ts'
12
+ import { PACKAGE_DIR } from './package.ts'
13
+ import { pageSource, within } from './site.ts'
14
+
15
+ const ENGINE_DIR = PACKAGE_DIR
16
+ const TYPESCRIPT = /\.m?ts$/i
17
+ const typeScriptModule = (file: string): string => stripTypeScriptTypes(fs.readFileSync(file, 'utf8'))
18
+
19
+ /** What a build made. */
20
+ export interface BuildResult {
21
+ /** the folder the site is in */
22
+ out: string
23
+ /** each page, and the file it became */
24
+ pages: { file: string; to: string }[]
25
+ /** what didn't fit: a link to a page outside the build, no index.html */
26
+ warnings: string[]
27
+ }
28
+
29
+ /** What a build takes from the project's server: its config, its plugins set up, whether it serves the project's files. */
30
+ export interface BuildFrom {
31
+ project: Project
32
+ config(): Promise<LoadedConfig>
33
+ hooks(): Promise<SetUp[]>
34
+ files(): boolean
35
+ }
36
+
37
+ /** What a build leaves out unless told otherwise: what is for writing a page, not for reading it. */
38
+ const BUILD_SKIP = ['form', 'chat', 'comments', 'draft']
39
+ /** In the folder a build writes, so that a next build knows it may replace it. */
40
+ const BUILD_MARK = '.whiteboard-build'
41
+
42
+ export async function build(
43
+ { project, config, hooks: setUp, files: served }: BuildFrom,
44
+ options: BuildConfig = {},
45
+ ): Promise<BuildResult> {
46
+ const cfg = await config()
47
+ if (cfg.errors.length) throw new Error(`the config failed to load: ${(cfg.errors[0] as Error).message}`)
48
+ if (!cfg.pages) throw new Error('the config has no pages renderer')
49
+ const pages = cfg.pages
50
+ const defined = <T>(...xs: (T | undefined)[]) => xs.find(x => x !== undefined)
51
+ const patterns = defined(options.pages, cfg.build.pages) ?? []
52
+ const skip = new Set(defined(options.skip, cfg.build.skip) ?? BUILD_SKIP)
53
+ const outDir = path.resolve(project.dir, defined(options.out, cfg.build.out) ?? 'site')
54
+ if (!patterns.length)
55
+ throw new Error(
56
+ "nothing to build: name the pages, as globs from the project's folder (whiteboard build 'docs/**/*.md'), or set build.pages in the config",
57
+ )
58
+ const warnings: string[] = []
59
+
60
+ // the pages: markdown files the globs match, but those a `!` glob leaves out
61
+ const include = patterns.filter(p => !p.startsWith('!'))
62
+ const exclude = patterns.filter(p => p.startsWith('!')).map(p => p.slice(1))
63
+ const files = [
64
+ ...new Set(include.flatMap(p => fs.globSync(p, { cwd: project.dir }).map(f => path.resolve(project.dir, f)))),
65
+ ]
66
+ .filter(f => /\.(md|markdown)$/i.test(f) && fs.statSync(f).isFile())
67
+ .filter(f => !exclude.some(g => path.matchesGlob(path.relative(project.dir, f), g)))
68
+ .sort()
69
+ if (!files.length) throw new Error(`no markdown files match ${patterns.join(' ')}`)
70
+ // each at its place below the folder they share; a README or index is its folder's index.html
71
+ const base = files.map(path.dirname).reduce((a, b) => {
72
+ while (!within(b, a)) a = path.dirname(a)
73
+ return a
74
+ })
75
+ const outOf = (file: string) => {
76
+ const rel = path.relative(base, file)
77
+ return path.join(
78
+ outDir,
79
+ /^(readme|index)\.(md|markdown)$/i.test(path.basename(rel))
80
+ ? path.join(path.dirname(rel), 'index.html')
81
+ : rel.replace(/\.(md|markdown)$/i, '.html'),
82
+ )
83
+ }
84
+ const built = new Map(files.map(f => [f, outOf(f)]))
85
+
86
+ // the folder it writes: new, empty, or what an earlier build wrote
87
+ if (fs.existsSync(outDir)) {
88
+ if (fs.readdirSync(outDir).length && !fs.existsSync(path.join(outDir, BUILD_MARK)))
89
+ throw new Error(`${outDir} has files a build didn't write: give another folder (--out), or empty it`)
90
+ fs.rmSync(outDir, { recursive: true })
91
+ }
92
+ fs.mkdirSync(outDir, { recursive: true })
93
+ fs.writeFileSync(path.join(outDir, BUILD_MARK), 'written by whiteboard build; the next build replaces this folder\n')
94
+
95
+ // what a page loads, copied once: the package's files under _/whiteboard/, the project's under
96
+ // _/project/, at their places there (so a stylesheet's url()s still hold); TypeScript as JavaScript
97
+ const copied = new Map<string, string>()
98
+ function copyAsset(file: string): string {
99
+ const known = copied.get(file)
100
+ if (known) return known
101
+ const rel = within(file, ENGINE_DIR)
102
+ ? path.join('_', 'whiteboard', path.relative(ENGINE_DIR, file))
103
+ : within(file, project.dir)
104
+ ? path.join('_', 'project', path.relative(project.dir, file))
105
+ : path.join('_', 'files', path.basename(path.dirname(file)), path.basename(file))
106
+ const dest = path.join(outDir, TYPESCRIPT.test(rel) ? rel.replace(/\.m?ts$/i, '.js') : rel)
107
+ copied.set(file, dest)
108
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
109
+ if (TYPESCRIPT.test(file)) fs.writeFileSync(dest, typeScriptModule(file))
110
+ else fs.copyFileSync(file, dest)
111
+ // a stylesheet's own files (fonts, images), at the same places beside it
112
+ if (/\.css$/i.test(file)) {
113
+ for (const m of fs.readFileSync(file, 'utf8').matchAll(/url\(\s*['"]?([^'")]+)['"]?\s*\)/g)) {
114
+ const ref = m[1]!
115
+ if (/^(data:|[a-z][a-z0-9+.-]*:|\/|#)/i.test(ref)) continue
116
+ const target = path.resolve(path.dirname(file), ref.replace(/[?#].*$/, ''))
117
+ if (fs.existsSync(target) && fs.statSync(target).isFile()) copyAsset(target)
118
+ }
119
+ }
120
+ return dest
121
+ }
122
+ /** a file beside the pages (an image), copied to its place below the site */
123
+ function copyBeside(file: string): string | null {
124
+ if (!within(file, base)) return null
125
+ const dest = path.join(outDir, path.relative(base, file))
126
+ if (!fs.existsSync(dest)) {
127
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
128
+ fs.copyFileSync(file, dest)
129
+ }
130
+ return dest
131
+ }
132
+
133
+ const hooks = await setUp()
134
+ const result: BuildResult = { out: outDir, pages: [], warnings }
135
+ for (const [file, dest] of built) {
136
+ const here = path.dirname(dest)
137
+ const relTo = (target: string) =>
138
+ path.relative(here, target).split(path.sep).map(encodeURIComponent).join('/') || '.'
139
+ const assetHere = (ref: string | URL) => relTo(copyAsset(toPath(ref)))
140
+ const urlFor = (abs: string): string | null => {
141
+ for (const candidate of [abs, abs + '.md']) {
142
+ if (!fs.existsSync(candidate)) continue
143
+ if (fs.statSync(candidate).isDirectory()) {
144
+ const index = [...built.keys()].find(
145
+ f => path.dirname(f) === candidate && /^(readme|index)\.(md|markdown)$/i.test(path.basename(f)),
146
+ )
147
+ if (index) return relTo(built.get(index)!)
148
+ continue
149
+ }
150
+ if (built.has(candidate)) return relTo(built.get(candidate)!)
151
+ if (/\.(md|markdown)$/i.test(candidate)) {
152
+ warnings.push(
153
+ `${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, which is not in the build`,
154
+ )
155
+ return null
156
+ }
157
+ const copy = copyBeside(candidate)
158
+ if (copy) return relTo(copy)
159
+ warnings.push(
160
+ `${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, outside the built pages' folder`,
161
+ )
162
+ return null
163
+ }
164
+ return null
165
+ }
166
+ const id = within(file, project.pagesDir)
167
+ ? path
168
+ .relative(project.pagesDir, file)
169
+ .split(path.sep)
170
+ .join('/')
171
+ .replace(/\.(md|markdown)$/i, '')
172
+ : '-/' + path.relative(project.dir, file).split(path.sep).join('/')
173
+ const stored = pageSource(id, file)
174
+ if (stored.frontmatterError)
175
+ warnings.push(`${path.relative(project.dir, file)}: frontmatter: ${stored.frontmatterError}`)
176
+ const context = {
177
+ project: { name: project.name, dir: project.dir, files: served() },
178
+ asset: assetHere,
179
+ urlFor,
180
+ live: false,
181
+ skip,
182
+ }
183
+ const rendered = await pages.render(stored, context)
184
+ // a page without a heading of its own is named by its file (a README by its folder), not by
185
+ // the id the server knows it by
186
+ const named = /^(readme|index)\.(md|markdown)$/i.test(path.basename(file))
187
+ ? path.basename(path.dirname(file))
188
+ : path.basename(file).replace(/\.(md|markdown)$/i, '')
189
+ const title = !rendered.title || rendered.title === id ? named : rendered.title
190
+ const out = { ...rendered, title, html: String(rendered.html ?? ''), head: String(rendered.head ?? '') }
191
+ // what the plugins add, but those the build leaves out, asked with no request: no browser
192
+ // asked for this page (what is only for the project's own browser has nothing to add here)
193
+ const parts = await pluginParts(hooks, null, {
194
+ asset: assetHere,
195
+ messages: [],
196
+ leaveOut: skip,
197
+ failed: message => warnings.push(`${path.relative(project.dir, file)}: ${message}`),
198
+ })
199
+ const doc = pageDocument(stored, { page: true, out, notices: [] }, parts, {
200
+ live: false,
201
+ base: '',
202
+ asset: assetHere,
203
+ runtime: assetHere(RUNTIME),
204
+ title: project.name,
205
+ })
206
+ fs.mkdirSync(here, { recursive: true })
207
+ fs.writeFileSync(dest, doc)
208
+ result.pages.push({ file, to: dest })
209
+ }
210
+ if (![...built.values()].includes(path.join(outDir, 'index.html')))
211
+ warnings.push('no README.md or index.md in the top folder: the site has no index.html')
212
+ return result
213
+ }
@@ -129,7 +129,8 @@ export function trackElsewhere(root: HTMLElement, handle: PageHandle, core: Api)
129
129
  current = handle.id
130
130
  const nav = root.querySelector('.wb-nav')
131
131
  if (!nav) return
132
- nav.querySelector('.wb-theme')?.before(box)
132
+ // before the plugins' place in the header bar (its header slot), and the theme button after it
133
+ ;(nav.querySelector('[data-wb-slot=header]') ?? nav.querySelector('.wb-theme'))?.before(box)
133
134
  toggle.addEventListener('click', () => open(!!list.hidden))
134
135
  document.addEventListener('click', e => {
135
136
  if (!box.contains(e.target as Node)) open(false)