@bigmistqke/whiteboard 0.4.0 → 0.6.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 (128) hide show
  1. package/README.md +177 -26
  2. package/bin/whiteboard.ts +331 -16
  3. package/dist/bin/whiteboard.js +268 -17
  4. package/dist/client/runtime.js +66 -23
  5. package/dist/plugins/ansi/README.md +36 -0
  6. package/dist/plugins/ansi/index.js +64 -0
  7. package/dist/plugins/ansi/public/style.css +28 -0
  8. package/dist/plugins/badge/README.md +28 -0
  9. package/dist/plugins/badge/index.js +24 -0
  10. package/dist/plugins/badge/public/style.css +30 -0
  11. package/dist/plugins/chat/public/style.css +7 -2
  12. package/dist/plugins/code/README.md +4 -2
  13. package/dist/plugins/code/diff.js +12 -2
  14. package/dist/plugins/draft/README.md +14 -0
  15. package/dist/plugins/draft/index.js +21 -0
  16. package/dist/plugins/draft/public/style.css +21 -0
  17. package/dist/plugins/grid/README.md +12 -12
  18. package/dist/plugins/grid/index.js +7 -19
  19. package/dist/plugins/grid/public/style.css +4 -33
  20. package/dist/plugins/iframe/README.md +7 -7
  21. package/dist/plugins/iframe/index.js +11 -11
  22. package/dist/plugins/iframe/public/style.css +15 -0
  23. package/dist/plugins/index.js +11 -3
  24. package/dist/plugins/lightbox/README.md +22 -0
  25. package/dist/plugins/lightbox/index.js +20 -0
  26. package/dist/plugins/lightbox/public/client.js +4 -0
  27. package/dist/plugins/lightbox/public/style.css +66 -0
  28. package/dist/plugins/steps/README.md +42 -0
  29. package/dist/plugins/steps/index.js +60 -0
  30. package/dist/plugins/steps/public/client.js +1 -0
  31. package/dist/plugins/steps/public/style.css +77 -0
  32. package/dist/plugins/terminal/host.js +9 -3
  33. package/dist/plugins/terminal/public/client.js +1 -1
  34. package/dist/plugins/terminal/sizes.js +2 -1
  35. package/dist/plugins/toc/README.md +21 -3
  36. package/dist/plugins/toc/index.js +8 -2
  37. package/dist/plugins/toc/public/client.js +1 -1
  38. package/dist/plugins/toc/public/style.css +10 -4
  39. package/dist/plugins/window/README.md +34 -14
  40. package/dist/plugins/window/index.js +21 -13
  41. package/dist/src/auth.js +6 -4
  42. package/dist/src/client/page/base.css +61 -1
  43. package/dist/src/client/page/main.js +74 -20
  44. package/dist/src/entries.js +211 -0
  45. package/dist/src/events.js +1 -1
  46. package/dist/src/hub.js +272 -0
  47. package/dist/src/loader.js +12 -3
  48. package/dist/src/package.js +23 -1
  49. package/dist/src/pages/blocks.js +1 -0
  50. package/dist/src/pages/index.js +1 -1
  51. package/dist/src/pages/markdown.js +87 -33
  52. package/dist/src/pages/render.js +157 -28
  53. package/dist/src/pages/window.js +17 -18
  54. package/dist/src/running.js +37 -2
  55. package/dist/src/serve.js +111 -2
  56. package/dist/src/server.js +264 -23
  57. package/package.json +3 -2
  58. package/plugins/ansi/README.md +36 -0
  59. package/plugins/ansi/index.ts +95 -0
  60. package/plugins/ansi/public/style.css +28 -0
  61. package/plugins/badge/README.md +28 -0
  62. package/plugins/badge/index.ts +35 -0
  63. package/plugins/badge/public/style.css +30 -0
  64. package/plugins/chat/public/style.css +7 -2
  65. package/plugins/code/README.md +4 -2
  66. package/plugins/code/diff.ts +14 -2
  67. package/plugins/code/index.ts +3 -1
  68. package/plugins/draft/README.md +14 -0
  69. package/plugins/draft/index.ts +23 -0
  70. package/plugins/draft/public/style.css +21 -0
  71. package/plugins/grid/README.md +12 -12
  72. package/plugins/grid/index.ts +11 -26
  73. package/plugins/grid/public/style.css +4 -33
  74. package/plugins/iframe/README.md +7 -7
  75. package/plugins/iframe/index.ts +15 -15
  76. package/plugins/iframe/public/style.css +15 -0
  77. package/plugins/index.ts +10 -2
  78. package/plugins/lightbox/README.md +22 -0
  79. package/plugins/lightbox/client.ts +99 -0
  80. package/plugins/lightbox/index.ts +25 -0
  81. package/plugins/lightbox/public/style.css +66 -0
  82. package/plugins/mermaid/index.ts +4 -2
  83. package/plugins/steps/README.md +42 -0
  84. package/plugins/steps/client.ts +75 -0
  85. package/plugins/steps/index.ts +84 -0
  86. package/plugins/steps/public/style.css +77 -0
  87. package/plugins/terminal/client.ts +16 -7
  88. package/plugins/terminal/host.ts +12 -6
  89. package/plugins/terminal/sizes.ts +3 -1
  90. package/plugins/toc/README.md +21 -3
  91. package/plugins/toc/client.ts +47 -6
  92. package/plugins/toc/index.ts +19 -6
  93. package/plugins/toc/public/style.css +10 -4
  94. package/plugins/window/README.md +34 -14
  95. package/plugins/window/index.ts +20 -13
  96. package/skills/whiteboard/SKILL.md +18 -10
  97. package/src/auth.ts +8 -5
  98. package/src/client/base.ts +19 -0
  99. package/src/client/forms.ts +2 -1
  100. package/src/client/markdown.ts +2 -1
  101. package/src/client/page/base.css +61 -1
  102. package/src/client/page/elsewhere.ts +72 -16
  103. package/src/client/page/fresh.ts +2 -1
  104. package/src/client/page/main.ts +18 -6
  105. package/src/client/page/sort.ts +2 -1
  106. package/src/client/runtime.ts +62 -25
  107. package/src/define.ts +126 -19
  108. package/src/entries.ts +258 -0
  109. package/src/events.ts +2 -1
  110. package/src/hub.ts +355 -0
  111. package/src/loader.ts +14 -3
  112. package/src/package.ts +22 -0
  113. package/src/pages/blocks.ts +3 -0
  114. package/src/pages/index.ts +6 -4
  115. package/src/pages/markdown.ts +89 -32
  116. package/src/pages/render.ts +181 -28
  117. package/src/pages/window.ts +23 -25
  118. package/src/running.ts +47 -1
  119. package/src/serve.ts +114 -1
  120. package/src/server.ts +332 -26
  121. package/dist/plugins/gallery/README.md +0 -30
  122. package/dist/plugins/gallery/index.js +0 -75
  123. package/dist/plugins/gallery/public/client.js +0 -1
  124. package/dist/plugins/gallery/public/style.css +0 -90
  125. package/plugins/gallery/README.md +0 -30
  126. package/plugins/gallery/client.tsx +0 -70
  127. package/plugins/gallery/index.ts +0 -89
  128. package/plugins/gallery/public/style.css +0 -90
package/src/server.ts CHANGED
@@ -17,6 +17,7 @@
17
17
  // text.
18
18
  import type { IncomingMessage, ServerResponse } from 'node:http'
19
19
  import fs from 'node:fs'
20
+ import { parse as parseYaml } from 'yaml'
20
21
  import { stripTypeScriptTypes } from 'node:module'
21
22
  import path from 'node:path'
22
23
  import type { Project } from './config.ts'
@@ -25,7 +26,7 @@ import { html, raw, type Html } from './html.ts'
25
26
  import { createConfigLoader, pluginDir, toPath, type LoadedConfig } from './loader.ts'
26
27
  import { describeRoutes, dispatch, pluginCommands, mountRoutes, usage, type MountedRoute } from './plugins.ts'
27
28
  import { createAuth } from './auth.ts'
28
- import { FROM_SOURCE, PACKAGE_DIR } from './package.ts'
29
+ import { FROM_SOURCE, PACKAGE_DIR, VERSION } from './package.ts'
29
30
  import { awaiting, covers, heard, questionState, unreadMessages } from './status.ts'
30
31
  import { titleOf } from './pages/render.ts'
31
32
  import { inPublic } from './public.ts'
@@ -38,6 +39,7 @@ import type {
38
39
  Rendered,
39
40
  StoredPage,
40
41
  PagesSource,
42
+ BuildConfig,
41
43
  } from './define.ts'
42
44
 
43
45
  const ENGINE_DIR = PACKAGE_DIR
@@ -70,7 +72,7 @@ const MIME: Record<string, string> = {
70
72
  // files in .whiteboard/ that are the server's own bookkeeping, not content
71
73
  const OWN_FILES = new Set(['events.ndjson', 'server.json', 'server.log', 'server.lock', 'token'])
72
74
  const SKIP_DIRS = new Set(['node_modules', '.git'])
73
- // a page's frontmatter: `---` lines around `key: value` lines, at the very start
75
+ // a page's frontmatter: YAML between `---` lines, at the very start
74
76
  const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/
75
77
 
76
78
  /** A project's server: its request handler, and what it knows. */
@@ -81,13 +83,58 @@ export interface WhiteboardServer {
81
83
  status(page?: string | null): Promise<PageStatus[]>
82
84
  /** the project's config, loaded */
83
85
  config(): Promise<LoadedConfig>
86
+ /** a static site of some pages (`whiteboard build`); options over the config's `build` */
87
+ build(options?: BuildConfig): Promise<BuildResult>
88
+ /**
89
+ * Hold a listener that is not a connection to this server: the shared server's fallback for a
90
+ * whole entry, which covers every page of each of its projects. Pages are told, as for any
91
+ * listener. @returns what removes it
92
+ */
93
+ addListener(l: Listener): () => void
94
+ /** who listens now: the running waits and watches, and a fallback held for it */
95
+ listeners(): Listener[]
96
+ /** the project's pages as its overview lists them, newest first, with what waits on each; whether it serves its files */
97
+ overview(): Promise<{ pages: PagesSource['pages']; files: boolean }>
98
+ /** tell the open overviews (`/`) that what they list changed */
99
+ touch(): void
84
100
  /** stop watching and end the live connections; the server answers nothing after */
85
101
  close(): void
86
102
  }
87
103
 
88
- export function createServer(project: Project): WhiteboardServer {
104
+ export interface BuildResult {
105
+ /** the folder the site is in */
106
+ out: string
107
+ /** each page, and the file it became */
108
+ pages: { file: string; to: string }[]
109
+ /** what didn't fit: a link to a page outside the build, no index.html */
110
+ warnings: string[]
111
+ }
112
+
113
+ /** How a server is mounted: on a port of its own (the default), or under a path of a shared server. */
114
+ export interface ServerOptions {
115
+ /** the path every URL it makes starts with, without a trailing slash: '' (its own port) or `/rg/develop` */
116
+ base?: string
117
+ /** the entry of a shared server the project is in */
118
+ entry?: string
119
+ /** how the project is known in its entry: `worktrees › cmux` (default: its name) */
120
+ label?: string
121
+ /** what the project is called, over its folder's or config's name (the shared server's own: whiteboard) */
122
+ name?: string
123
+ /** serve and watch the project's files, over the config's `files` */
124
+ files?: boolean
125
+ /** the overview at / lists these instead of the project's pages (the shared server's own project) */
126
+ overview?: () => Promise<Pick<PagesSource, 'groups' | 'empty' | 'note'>>
127
+ /** a page of the project changed, or its log grew: the shared server's overview follows it */
128
+ onChange?: () => void
129
+ }
130
+
131
+ export function createServer(
132
+ project: Project,
133
+ { base = '', entry, label, name, files: filesOption, overview, onChange }: ServerOptions = {},
134
+ ): WhiteboardServer {
135
+ const projectName = () => name ?? project.name
89
136
  const loader = createConfigLoader(project)
90
- const auth = createAuth(project.wb)
137
+ const auth = createAuth(project.wb, base)
91
138
  // what close() stops: watchers, and the live connections' pings and responses
92
139
  const watchers = new Set<fs.FSWatcher>()
93
140
  const streams = new Set<() => void>()
@@ -202,7 +249,7 @@ export function createServer(project: Project): WhiteboardServer {
202
249
  /** The loaded config. Also applies its `files` setting to what is served and watched. */
203
250
  async function config(): Promise<LoadedConfig> {
204
251
  const c = await loader.config()
205
- setFiles(c.files)
252
+ setFiles(filesOption ?? c.files)
206
253
  publicDirs = [...c.publicDirs.values()]
207
254
  return c
208
255
  }
@@ -236,7 +283,7 @@ export function createServer(project: Project): WhiteboardServer {
236
283
  }
237
284
  }
238
285
  }
239
- return `/_/file${file.split(path.sep).map(encodeURIComponent).join('/')}`
286
+ return `${base}/_/file${file.split(path.sep).map(encodeURIComponent).join('/')}`
240
287
  }
241
288
 
242
289
  const within = (file: string, dir: string) => file === dir || file.startsWith(dir + path.sep)
@@ -251,15 +298,20 @@ export function createServer(project: Project): WhiteboardServer {
251
298
 
252
299
  const isRepoId = (id: string) => id === '-' || id.startsWith('-/')
253
300
 
254
- function frontmatter(source: string): Record<string, string> {
301
+ /** A page's frontmatter, parsed as YAML; empty, with the reason, when it isn't fields. */
302
+ function frontmatter(source: string): { data: Record<string, unknown>; error: string | null } {
255
303
  const m = FRONTMATTER.exec(source)
256
- const out: Record<string, string> = {}
257
- if (m)
258
- for (const line of m[1]!.split(/\r?\n/)) {
259
- const kv = /^([\w-]+)\s*:\s*(.*)$/.exec(line)
260
- if (kv) out[kv[1]!] = kv[2]!.trim().replace(/^["']|["']$/g, '')
261
- }
262
- return out
304
+ if (!m) return { data: {}, error: null }
305
+ let data: unknown
306
+ try {
307
+ data = parseYaml(m[1]!)
308
+ } catch (err) {
309
+ return { data: {}, error: (err as Error).message }
310
+ }
311
+ if (data == null) return { data: {}, error: null }
312
+ if (typeof data !== 'object' || Array.isArray(data))
313
+ return { data: {}, error: 'it must be fields (`key: value` lines), not a single value or a list' }
314
+ return { data: data as Record<string, unknown>, error: null }
263
315
  }
264
316
 
265
317
  function pageSource(id: string, file: string): PageSource {
@@ -271,7 +323,7 @@ export function createServer(project: Project): WhiteboardServer {
271
323
  mtime: fs.statSync(file).mtimeMs,
272
324
  source,
273
325
  body: source.replace(FRONTMATTER, ''),
274
- frontmatter: frontmatter(source),
326
+ ...(({ data, error }) => ({ frontmatter: data, frontmatterError: error }))(frontmatter(source)),
275
327
  }
276
328
  }
277
329
 
@@ -345,7 +397,7 @@ export function createServer(project: Project): WhiteboardServer {
345
397
  /** The URL that serves a file or folder on disk, or null when nothing here serves it. */
346
398
  function urlOf(abs: string): string | null {
347
399
  const rel = (dir: string) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join('/')
348
- if (within(abs, project.pagesDir)) return `/${rel(project.pagesDir).replace(/\.md$/, '')}`
400
+ if (within(abs, project.pagesDir)) return `${base}/${rel(project.pagesDir).replace(/\.md$/, '')}`
349
401
  if (FILES && within(abs, project.dir)) {
350
402
  if (
351
403
  rel(project.dir)
@@ -353,7 +405,7 @@ export function createServer(project: Project): WhiteboardServer {
353
405
  .some(part => SKIP_DIRS.has(part))
354
406
  )
355
407
  return null
356
- return `/-/${rel(project.dir)}`
408
+ return `${base}/-/${rel(project.dir)}`
357
409
  }
358
410
  return null
359
411
  }
@@ -377,7 +429,7 @@ export function createServer(project: Project): WhiteboardServer {
377
429
  html`<ul>
378
430
  ${items.map(([href, text]) => html`<li><a href="${href}">${text}</a></li>`)}
379
431
  </ul>`
380
- if (page.kind === 'pages') return { html: list(page.pages.map(p => [`/${p.id}`, p.id])) }
432
+ if (page.kind === 'pages') return { html: list(page.pages.map(p => [`${base}/${p.id}`, p.id])) }
381
433
  if (page.kind === 'folder') {
382
434
  return {
383
435
  html: list(
@@ -390,7 +442,13 @@ export function createServer(project: Project): WhiteboardServer {
390
442
  return { html: html`<pre>${page.source}</pre>` }
391
443
  }
392
444
 
393
- const context = () => ({ project: { name: project.name, dir: project.dir, files: !!FILES }, asset, urlFor })
445
+ const context = () => ({
446
+ project: { name: projectName(), dir: project.dir, files: !!FILES },
447
+ asset,
448
+ urlFor,
449
+ base,
450
+ ...(entry && { entry: { name: entry, label } }),
451
+ })
394
452
 
395
453
  /** A render as the shell takes it. `page`: whether the page's browser part runs (not on raw text). */
396
454
  interface Render {
@@ -400,12 +458,13 @@ export function createServer(project: Project): WhiteboardServer {
400
458
  }
401
459
 
402
460
  /** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
403
- const frontmatterOf = (page: StoredPage): Record<string, string> => (page.kind === 'page' ? page.frontmatter : {})
461
+ const frontmatterOf = (page: StoredPage): Record<string, unknown> => (page.kind === 'page' ? page.frontmatter : {})
404
462
 
405
463
  /** Render a stored page as markdown, with the plugins' blocks, and anything the reader should be told. */
406
464
  async function render(page: StoredPage): Promise<Render> {
407
465
  const { pages, errors } = await config()
408
466
  const notices = errors.map(e => `config: ${(e as Error).message}`)
467
+ if (page.kind === 'page' && page.frontmatterError) notices.push(`frontmatter: ${page.frontmatterError}`)
409
468
  let out: Rendered
410
469
  let rendered = !!pages
411
470
  try {
@@ -516,11 +575,16 @@ export function createServer(project: Project): WhiteboardServer {
516
575
  page: StoredPage,
517
576
  { page: rendered, out, notices }: Render,
518
577
  extras: Extras = { head: [], body: [], clients: [] },
578
+ /** a built page (`whiteboard build`): its files as the build names them, and no server behind it */
579
+ built?: { asset(ref: string | URL): string },
519
580
  ): string {
520
581
  const handoff = {
521
582
  id: page.id,
522
583
  kind: page.kind,
523
- client: rendered ? asset(PAGE_CLIENT) : null,
584
+ live: !built,
585
+ // what the page's own requests start with (see ServerOptions.base)
586
+ base: built ? '' : base,
587
+ client: rendered ? (built ?? { asset }).asset(PAGE_CLIENT) : null,
524
588
  data: out.data ?? null,
525
589
  frontmatter: frontmatterOf(page),
526
590
  plugins: extras.clients,
@@ -533,7 +597,7 @@ export function createServer(project: Project): WhiteboardServer {
533
597
  <head>
534
598
  <meta charset="utf-8" />
535
599
  <meta name="viewport" content="width=device-width,initial-scale=1" />
536
- <title>${out.title || page.id || project.name}</title>
600
+ <title>${out.title || page.id || projectName()}</title>
537
601
  <style>
538
602
  ${DOCK_STYLE}
539
603
  </style>
@@ -546,7 +610,7 @@ export function createServer(project: Project): WhiteboardServer {
546
610
  <script type="application/json" id="wb-page">
547
611
  ${raw(json(handoff))}
548
612
  </script>
549
- <script type="module" src="/_/runtime.js"></script>
613
+ <script type="module" src="${built ? built.asset(RUNTIME) : `${base}/_/runtime.js`}"></script>
550
614
  ${extras.body}
551
615
  </body>
552
616
  </html>`,
@@ -594,6 +658,7 @@ export function createServer(project: Project): WhiteboardServer {
594
658
  }
595
659
 
596
660
  function pageChanged(id: string) {
661
+ onChange?.()
597
662
  for (const c of clients) {
598
663
  if (c.isDir ? !c.page || id.startsWith(c.page + '/') : c.page === id || c.page + '/index' === id)
599
664
  notify(c, 'change')
@@ -607,7 +672,10 @@ export function createServer(project: Project): WhiteboardServer {
607
672
  if (f.split('/').some(part => SKIP_DIRS.has(part))) return
608
673
  if (f.startsWith('.whiteboard/')) {
609
674
  const inner = f.slice('.whiteboard/'.length)
610
- if (inner === 'events.ndjson') return notifyAll('events')
675
+ if (inner === 'events.ndjson') {
676
+ onChange?.()
677
+ return notifyAll('events')
678
+ }
611
679
  if (inner.startsWith('pages/')) {
612
680
  if (inner.endsWith('.md')) pageChanged(inner.slice('pages/'.length).replace(/\.md$/, ''))
613
681
  return
@@ -728,11 +796,12 @@ export function createServer(project: Project): WhiteboardServer {
728
796
  if ('raw' in found) return found
729
797
  // a folder is served at /dir/, so relative links resolve inside it
730
798
  if ((found.kind === 'folder' || (found.kind === 'pages' && id)) && !requested.endsWith('/'))
731
- return { redirect: `/${id}/` }
799
+ return { redirect: `${base}/${id}/` }
732
800
  // a list of pages says which await the reader: where their questions stand takes the config
733
801
  if (found.kind === 'pages') {
734
802
  const counts = new Map((await status(found.id || null)).map(s => [s.page, awaiting(s)]))
735
803
  for (const p of found.pages) p.awaiting = counts.get(p.id) ?? 0
804
+ if (!found.id && overview) Object.assign(found, await overview())
736
805
  }
737
806
  return { page: found }
738
807
  }
@@ -780,7 +849,8 @@ export function createServer(project: Project): WhiteboardServer {
780
849
  }
781
850
  return sendFile(res, file)
782
851
  }
783
- if (p === '/api/health') return sendJson(res, 200, { ok: true, dir: project.dir, pid: process.pid })
852
+ if (p === '/api/health')
853
+ return sendJson(res, 200, { ok: true, dir: project.dir, pid: process.pid, version: VERSION, base })
784
854
  if (p === '/api/events' && req.method === 'POST') {
785
855
  const body = JSON.parse(await readBody(req))
786
856
  if (!body.type) return sendJson(res, 400, { error: 'event type required' })
@@ -917,10 +987,246 @@ export function createServer(project: Project): WhiteboardServer {
917
987
  }
918
988
  }
919
989
 
990
+ // ---- build: a static site ---------------------------------------------------------------------
991
+ // Pages rendered once (`whiteboard build`), as files: each page's HTML with its links relative, and
992
+ // what it loads copied beside it. See BuildConfig.
993
+
994
+ /** What a build leaves out unless told otherwise: what is for writing a page, not for reading it. */
995
+ const BUILD_SKIP = ['form', 'chat', 'comments', 'draft']
996
+ /** In the folder a build writes, so that a next build knows it may replace it. */
997
+ const BUILD_MARK = '.whiteboard-build'
998
+
999
+ async function build(options: BuildConfig = {}): Promise<BuildResult> {
1000
+ const cfg = await config()
1001
+ if (cfg.errors.length) throw new Error(`the config failed to load: ${(cfg.errors[0] as Error).message}`)
1002
+ if (!cfg.pages) throw new Error('the config has no pages renderer')
1003
+ const pages = cfg.pages
1004
+ const defined = <T>(...xs: (T | undefined)[]) => xs.find(x => x !== undefined)
1005
+ const patterns = defined(options.pages, cfg.build.pages) ?? []
1006
+ const skip = new Set(defined(options.skip, cfg.build.skip) ?? BUILD_SKIP)
1007
+ const outDir = path.resolve(project.dir, defined(options.out, cfg.build.out) ?? 'site')
1008
+ if (!patterns.length)
1009
+ throw new Error(
1010
+ "nothing to build: name the pages, as globs from the project's folder (whiteboard build 'docs/**/*.md'), or set build.pages in the config",
1011
+ )
1012
+ const warnings: string[] = []
1013
+
1014
+ // the pages: markdown files the globs match, but those a `!` glob leaves out
1015
+ const include = patterns.filter(p => !p.startsWith('!'))
1016
+ const exclude = patterns.filter(p => p.startsWith('!')).map(p => p.slice(1))
1017
+ const files = [
1018
+ ...new Set(include.flatMap(p => fs.globSync(p, { cwd: project.dir }).map(f => path.resolve(project.dir, f)))),
1019
+ ]
1020
+ .filter(f => /\.(md|markdown)$/i.test(f) && fs.statSync(f).isFile())
1021
+ .filter(f => !exclude.some(g => path.matchesGlob(path.relative(project.dir, f), g)))
1022
+ .sort()
1023
+ if (!files.length) throw new Error(`no markdown files match ${patterns.join(' ')}`)
1024
+ // each at its place below the folder they share; a README or index is its folder's index.html
1025
+ const base = files.map(path.dirname).reduce((a, b) => {
1026
+ while (!within(b, a)) a = path.dirname(a)
1027
+ return a
1028
+ })
1029
+ const outOf = (file: string) => {
1030
+ const rel = path.relative(base, file)
1031
+ return path.join(
1032
+ outDir,
1033
+ /^(readme|index)\.(md|markdown)$/i.test(path.basename(rel))
1034
+ ? path.join(path.dirname(rel), 'index.html')
1035
+ : rel.replace(/\.(md|markdown)$/i, '.html'),
1036
+ )
1037
+ }
1038
+ const built = new Map(files.map(f => [f, outOf(f)]))
1039
+
1040
+ // the folder it writes: new, empty, or what an earlier build wrote
1041
+ if (fs.existsSync(outDir)) {
1042
+ if (fs.readdirSync(outDir).length && !fs.existsSync(path.join(outDir, BUILD_MARK)))
1043
+ throw new Error(`${outDir} has files a build didn't write: give another folder (--out), or empty it`)
1044
+ fs.rmSync(outDir, { recursive: true })
1045
+ }
1046
+ fs.mkdirSync(outDir, { recursive: true })
1047
+ fs.writeFileSync(
1048
+ path.join(outDir, BUILD_MARK),
1049
+ 'written by whiteboard build; the next build replaces this folder\n',
1050
+ )
1051
+
1052
+ // what a page loads, copied once: the package's files under _/whiteboard/, the project's under
1053
+ // _/project/, at their places there (so a stylesheet's url()s still hold); TypeScript as JavaScript
1054
+ const copied = new Map<string, string>()
1055
+ function copyAsset(file: string): string {
1056
+ const known = copied.get(file)
1057
+ if (known) return known
1058
+ const rel = within(file, ENGINE_DIR)
1059
+ ? path.join('_', 'whiteboard', path.relative(ENGINE_DIR, file))
1060
+ : within(file, project.dir)
1061
+ ? path.join('_', 'project', path.relative(project.dir, file))
1062
+ : path.join('_', 'files', path.basename(path.dirname(file)), path.basename(file))
1063
+ const dest = path.join(outDir, TYPESCRIPT.test(rel) ? rel.replace(/\.m?ts$/i, '.js') : rel)
1064
+ copied.set(file, dest)
1065
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
1066
+ if (TYPESCRIPT.test(file)) fs.writeFileSync(dest, typeScriptModule(file))
1067
+ else fs.copyFileSync(file, dest)
1068
+ // a stylesheet's own files (fonts, images), at the same places beside it
1069
+ if (/\.css$/i.test(file)) {
1070
+ for (const m of fs.readFileSync(file, 'utf8').matchAll(/url\(\s*['"]?([^'")]+)['"]?\s*\)/g)) {
1071
+ const ref = m[1]!
1072
+ if (/^(data:|[a-z][a-z0-9+.-]*:|\/|#)/i.test(ref)) continue
1073
+ const target = path.resolve(path.dirname(file), ref.replace(/[?#].*$/, ''))
1074
+ if (fs.existsSync(target) && fs.statSync(target).isFile()) copyAsset(target)
1075
+ }
1076
+ }
1077
+ return dest
1078
+ }
1079
+ /** a file beside the pages (an image), copied to its place below the site */
1080
+ function copyBeside(file: string): string | null {
1081
+ if (!within(file, base)) return null
1082
+ const dest = path.join(outDir, path.relative(base, file))
1083
+ if (!fs.existsSync(dest)) {
1084
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
1085
+ fs.copyFileSync(file, dest)
1086
+ }
1087
+ return dest
1088
+ }
1089
+
1090
+ const hooks = await pluginHooks()
1091
+ const result: BuildResult = { out: outDir, pages: [], warnings }
1092
+ for (const [file, dest] of built) {
1093
+ const here = path.dirname(dest)
1094
+ const relTo = (target: string) =>
1095
+ path.relative(here, target).split(path.sep).map(encodeURIComponent).join('/') || '.'
1096
+ const assetHere = (ref: string | URL) => relTo(copyAsset(toPath(ref)))
1097
+ const urlFor = (abs: string): string | null => {
1098
+ for (const candidate of [abs, abs + '.md']) {
1099
+ if (!fs.existsSync(candidate)) continue
1100
+ if (fs.statSync(candidate).isDirectory()) {
1101
+ const index = [...built.keys()].find(
1102
+ f => path.dirname(f) === candidate && /^(readme|index)\.(md|markdown)$/i.test(path.basename(f)),
1103
+ )
1104
+ if (index) return relTo(built.get(index)!)
1105
+ continue
1106
+ }
1107
+ if (built.has(candidate)) return relTo(built.get(candidate)!)
1108
+ if (/\.(md|markdown)$/i.test(candidate)) {
1109
+ warnings.push(
1110
+ `${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, which is not in the build`,
1111
+ )
1112
+ return null
1113
+ }
1114
+ const copy = copyBeside(candidate)
1115
+ if (copy) return relTo(copy)
1116
+ warnings.push(
1117
+ `${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, outside the built pages' folder`,
1118
+ )
1119
+ return null
1120
+ }
1121
+ return null
1122
+ }
1123
+ const id = within(file, project.pagesDir)
1124
+ ? path
1125
+ .relative(project.pagesDir, file)
1126
+ .split(path.sep)
1127
+ .join('/')
1128
+ .replace(/\.(md|markdown)$/i, '')
1129
+ : '-/' + path.relative(project.dir, file).split(path.sep).join('/')
1130
+ const stored = pageSource(id, file)
1131
+ if (stored.frontmatterError)
1132
+ warnings.push(`${path.relative(project.dir, file)}: frontmatter: ${stored.frontmatterError}`)
1133
+ const context = {
1134
+ project: { name: project.name, dir: project.dir, files: !!FILES },
1135
+ asset: assetHere,
1136
+ urlFor,
1137
+ live: false,
1138
+ skip,
1139
+ }
1140
+ const rendered = await pages.render(stored, context)
1141
+ // a page without a heading of its own is named by its file (a README by its folder), not by
1142
+ // the id the server knows it by
1143
+ const named = /^(readme|index)\.(md|markdown)$/i.test(path.basename(file))
1144
+ ? path.basename(path.dirname(file))
1145
+ : path.basename(file).replace(/\.(md|markdown)$/i, '')
1146
+ const title = !rendered.title || rendered.title === id ? named : rendered.title
1147
+ const out = { ...rendered, title, html: String(rendered.html ?? ''), head: String(rendered.head ?? '') }
1148
+ // the plugins' browser modules, but those the build leaves out; not what they add to a live
1149
+ // page's shell (the terminal's drawer): that is the server's
1150
+ const included = hooks.filter(h => !h.error && !skip.has(h.name))
1151
+ const clients = included.filter(h => h.client).map(h => ({ name: h.name, client: assetHere(h.client!) }))
1152
+ // what the plugins add to the shell, asked with no request: no browser asked for this page
1153
+ const parts = await Promise.all(
1154
+ included.map(async h => {
1155
+ try {
1156
+ return (await h.shell?.(null)) ?? null
1157
+ } catch (err) {
1158
+ warnings.push(`plugin ${h.name} failed on ${path.relative(project.dir, file)}: ${(err as Error).message}`)
1159
+ return null
1160
+ }
1161
+ }),
1162
+ )
1163
+ const extras = {
1164
+ head: parts.map(x => raw(String(x?.head ?? ''))),
1165
+ body: parts.map(x => raw(String(x?.body ?? ''))),
1166
+ clients,
1167
+ }
1168
+ let doc = shell(stored, { page: true, out, notices: [] }, extras, { asset: assetHere })
1169
+ // a file a plugin named the server's way (its asset URL, /_/file/<path>): its copy
1170
+ doc = doc.replace(/\/_\/file(\/[^"'\s)<>]+)/g, (all, served: string) => {
1171
+ let file: string
1172
+ try {
1173
+ file = path.resolve(served.split('/').map(decodeURIComponent).join(path.sep))
1174
+ } catch {
1175
+ return all
1176
+ }
1177
+ return fs.existsSync(file) && fs.statSync(file).isFile() ? assetHere(file) : all
1178
+ })
1179
+ // what the blocks name relative to the page (an ::image's src, an iframe's page): copied too
1180
+ doc = doc.replace(/\b(src|href|poster)="([^"#?:]+)([^"]*)"/g, (all, _attr, ref: string) => {
1181
+ if (ref.startsWith('/') || ref.startsWith('_/') || ref.startsWith('../')) return all
1182
+ let decoded = ref
1183
+ try {
1184
+ decoded = decodeURIComponent(ref)
1185
+ } catch {
1186
+ /* as written */
1187
+ }
1188
+ const source = path.resolve(path.dirname(file), decoded)
1189
+ if (fs.existsSync(source) && fs.statSync(source).isFile() && !/\.(md|markdown)$/i.test(source)) {
1190
+ const target = path.resolve(here, decoded)
1191
+ if (within(target, outDir) && !fs.existsSync(target)) {
1192
+ fs.mkdirSync(path.dirname(target), { recursive: true })
1193
+ fs.copyFileSync(source, target)
1194
+ }
1195
+ }
1196
+ return all
1197
+ })
1198
+ fs.mkdirSync(here, { recursive: true })
1199
+ fs.writeFileSync(dest, doc)
1200
+ result.pages.push({ file, to: dest })
1201
+ }
1202
+ if (![...built.values()].includes(path.join(outDir, 'index.html')))
1203
+ warnings.push('no README.md or index.md in the top folder: the site has no index.html')
1204
+ return result
1205
+ }
1206
+
920
1207
  return {
921
1208
  handle,
1209
+ listeners: () => listenersFor(null),
1210
+ async overview() {
1211
+ await config()
1212
+ const pages = pagesIn(project.pagesDir)
1213
+ const counts = new Map((await status(null)).map(s => [s.page, awaiting(s)]))
1214
+ for (const p of pages) p.awaiting = counts.get(p.id) ?? 0
1215
+ return { pages, files: !!FILES }
1216
+ },
1217
+ touch() {
1218
+ for (const c of clients) if (c.isDir && !c.page) notify(c, 'change')
1219
+ },
1220
+ addListener(l) {
1221
+ listeners.add(l)
1222
+ notifyAll('listeners')
1223
+ return () => {
1224
+ if (listeners.delete(l)) notifyAll('listeners')
1225
+ }
1226
+ },
922
1227
  status: (page = null) => status(page),
923
1228
  config,
1229
+ build,
924
1230
  close() {
925
1231
  for (const w of watchers) w.close()
926
1232
  watchers.clear()
@@ -1,30 +0,0 @@
1
- Image cards; clicking one opens a lightbox (arrow keys to step, Esc to close).
2
-
3
- Each heading at the shallowest level starts an item: the first image under it
4
- is the picture, the heading is the title and the rest is the caption. Without
5
- headings, every image in the block is an item and its alt text the title.
6
- Relative image paths resolve next to the page file.
7
-
8
- Attributes: `min` (smallest card width, default `240px`).
9
-
10
- ```markdown
11
- :::gallery{min=200px}
12
- ### Dunes
13
- ![dunes](https://picsum.photos/id/1016/800/600)
14
- Option A: warm, quiet.
15
-
16
- ### Coast
17
- ![coast](https://picsum.photos/id/1015/800/600)
18
- Option B: more contrast.
19
- :::
20
- ```
21
-
22
- :::gallery{min=200px}
23
- ### Dunes
24
- ![dunes](https://picsum.photos/id/1016/800/600)
25
- Option A: warm, quiet.
26
-
27
- ### Coast
28
- ![coast](https://picsum.photos/id/1015/800/600)
29
- Option B: more contrast.
30
- :::
@@ -1,75 +0,0 @@
1
- import { builtinPublic } from "../../src/package.js";
2
- import fs from "node:fs";
3
- import { definePlugin, escape } from "@bigmistqke/whiteboard";
4
- // plugins/gallery/index.ts
5
- /** Remove and return the first image in a list of nodes (searching inside paragraphs). */
6
- function takeImage(nodes) {
7
- for (let i = 0; i < nodes.length; i++) {
8
- const n = nodes[i];
9
- if (n.type === "image") {
10
- nodes.splice(i, 1);
11
- return n;
12
- }
13
- if (n.children) {
14
- const found = takeImage(n.children);
15
- if (found) {
16
- if (n.type === "paragraph" && n.children.every((c) => c.type === "text" && !String(c.value).trim())) nodes.splice(i, 1);
17
- return found;
18
- }
19
- }
20
- }
21
- return null;
22
- }
23
- async function props(ctx) {
24
- const children = ctx.children;
25
- const heads = children.filter((n) => n.type === "heading");
26
- const items = [];
27
- if (heads.length) {
28
- const depth = Math.min(...heads.map((h) => h.depth));
29
- let current = null;
30
- const groups = [];
31
- for (const n of children) if (n.type === "heading" && n.depth === depth) groups.push(current = {
32
- heading: n,
33
- body: []
34
- });
35
- else current?.body.push(n);
36
- for (const g of groups) {
37
- const img = takeImage(g.body);
38
- items.push({
39
- src: img?.url ?? null,
40
- alt: img?.alt ?? "",
41
- title: await ctx.toHtml(g.heading.children ?? []),
42
- html: await ctx.toHtml(g.body)
43
- });
44
- }
45
- } else {
46
- const walk = (nodes) => {
47
- for (const n of nodes) if (n.type === "image") items.push({
48
- src: n.url,
49
- alt: n.alt ?? "",
50
- title: n.alt ? escape(n.alt) : null,
51
- html: ""
52
- });
53
- else if (n.children) walk(n.children);
54
- };
55
- walk(children);
56
- }
57
- return {
58
- items,
59
- min: ctx.attrs.min ?? null,
60
- narrow: "narrow" in ctx.attrs
61
- };
62
- }
63
- function gallery() {
64
- return definePlugin({
65
- name: "gallery",
66
- public: builtinPublic("gallery"),
67
- blocks: { gallery: {
68
- props,
69
- client: "client.js",
70
- style: "style.css"
71
- } },
72
- docs: () => fs.readFileSync(new URL("./README.md", import.meta.url), "utf8")
73
- });
74
- }
75
- export { gallery as default, props };