@bigmistqke/whiteboard 0.0.0-stage → 0.1.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 (138) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +609 -2
  3. package/bin/whiteboard.ts +431 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/whiteboard.js +471 -0
  6. package/dist/client/runtime.js +391 -0
  7. package/dist/define.js +7 -0
  8. package/dist/plugins/callout/README.md +13 -0
  9. package/dist/plugins/callout/index.js +27 -0
  10. package/dist/plugins/callout/style.css +12 -0
  11. package/dist/plugins/chat/README.md +45 -0
  12. package/dist/plugins/chat/client.js +3 -0
  13. package/dist/plugins/chat/index.js +46 -0
  14. package/dist/plugins/chat/style.css +17 -0
  15. package/dist/plugins/claude-code/index.js +120 -0
  16. package/dist/plugins/code/README.md +42 -0
  17. package/dist/plugins/code/diff.js +64 -0
  18. package/dist/plugins/code/index.js +77 -0
  19. package/dist/plugins/code/style.css +29 -0
  20. package/dist/plugins/comments/client.js +10 -0
  21. package/dist/plugins/comments/index.js +51 -0
  22. package/dist/plugins/comments/style.css +32 -0
  23. package/dist/plugins/details/README.md +17 -0
  24. package/dist/plugins/details/index.js +17 -0
  25. package/dist/plugins/details/style.css +3 -0
  26. package/dist/plugins/form/README.md +111 -0
  27. package/dist/plugins/form/index.js +102 -0
  28. package/dist/plugins/form/style.css +41 -0
  29. package/dist/plugins/gallery/README.md +30 -0
  30. package/dist/plugins/gallery/client.js +1 -0
  31. package/dist/plugins/gallery/index.js +74 -0
  32. package/dist/plugins/gallery/style.css +27 -0
  33. package/dist/plugins/grid/README.md +33 -0
  34. package/dist/plugins/grid/index.js +33 -0
  35. package/dist/plugins/grid/style.css +25 -0
  36. package/dist/plugins/index.js +26 -0
  37. package/dist/plugins/mermaid/README.md +21 -0
  38. package/dist/plugins/mermaid/index.js +34 -0
  39. package/dist/plugins/mermaid/style.css +16 -0
  40. package/dist/plugins/quiet/README.md +26 -0
  41. package/dist/plugins/quiet/index.js +17 -0
  42. package/dist/plugins/terminal/client.js +41 -0
  43. package/dist/plugins/terminal/host.js +332 -0
  44. package/dist/plugins/terminal/index.js +171 -0
  45. package/dist/plugins/terminal/modes.js +32 -0
  46. package/dist/plugins/terminal/server.js +256 -0
  47. package/dist/plugins/terminal/sizes.js +57 -0
  48. package/dist/plugins/terminal/style.css +357 -0
  49. package/dist/solid/index.js +35 -0
  50. package/dist/src/auth.js +54 -0
  51. package/dist/src/client/page/base.css +274 -0
  52. package/dist/src/client/page/main.js +1004 -0
  53. package/dist/src/config.js +76 -0
  54. package/dist/src/events.js +162 -0
  55. package/dist/src/html.js +34 -0
  56. package/dist/src/load.js +77 -0
  57. package/dist/src/loader.js +120 -0
  58. package/dist/src/package.js +33 -0
  59. package/dist/src/pages/blocks.js +49 -0
  60. package/dist/src/pages/index.js +14 -0
  61. package/dist/src/pages/markdown.js +307 -0
  62. package/dist/src/pages/render.js +257 -0
  63. package/dist/src/plugins.js +238 -0
  64. package/dist/src/running.js +24 -0
  65. package/dist/src/serve.js +71 -0
  66. package/dist/src/server.js +700 -0
  67. package/dist/src/status.js +43 -0
  68. package/package.json +131 -4
  69. package/plugins/callout/README.md +13 -0
  70. package/plugins/callout/index.ts +25 -0
  71. package/plugins/callout/style.css +12 -0
  72. package/plugins/chat/README.md +45 -0
  73. package/plugins/chat/autosize.ts +101 -0
  74. package/plugins/chat/client.tsx +81 -0
  75. package/plugins/chat/index.ts +61 -0
  76. package/plugins/chat/style.css +17 -0
  77. package/plugins/claude-code/index.ts +136 -0
  78. package/plugins/code/README.md +42 -0
  79. package/plugins/code/diff.ts +58 -0
  80. package/plugins/code/index.ts +94 -0
  81. package/plugins/code/style.css +29 -0
  82. package/plugins/comments/client.ts +448 -0
  83. package/plugins/comments/index.ts +52 -0
  84. package/plugins/comments/style.css +32 -0
  85. package/plugins/details/README.md +17 -0
  86. package/plugins/details/index.ts +21 -0
  87. package/plugins/details/style.css +3 -0
  88. package/plugins/form/README.md +111 -0
  89. package/plugins/form/index.ts +104 -0
  90. package/plugins/form/style.css +41 -0
  91. package/plugins/gallery/README.md +30 -0
  92. package/plugins/gallery/client.tsx +64 -0
  93. package/plugins/gallery/index.ts +67 -0
  94. package/plugins/gallery/style.css +27 -0
  95. package/plugins/grid/README.md +33 -0
  96. package/plugins/grid/index.ts +36 -0
  97. package/plugins/grid/style.css +25 -0
  98. package/plugins/index.ts +19 -0
  99. package/plugins/mermaid/README.md +21 -0
  100. package/plugins/mermaid/index.ts +39 -0
  101. package/plugins/mermaid/style.css +16 -0
  102. package/plugins/quiet/README.md +26 -0
  103. package/plugins/quiet/index.ts +27 -0
  104. package/plugins/terminal/client.ts +317 -0
  105. package/plugins/terminal/host.ts +326 -0
  106. package/plugins/terminal/index.ts +138 -0
  107. package/plugins/terminal/modes.ts +30 -0
  108. package/plugins/terminal/server.ts +215 -0
  109. package/plugins/terminal/sizes.ts +60 -0
  110. package/plugins/terminal/style.css +71 -0
  111. package/skills/whiteboard/SKILL.md +292 -0
  112. package/solid/index.tsx +56 -0
  113. package/src/auth.ts +66 -0
  114. package/src/client/forms.ts +186 -0
  115. package/src/client/page/base.css +274 -0
  116. package/src/client/page/fresh.ts +205 -0
  117. package/src/client/page/main.ts +249 -0
  118. package/src/client/page/orphans.ts +46 -0
  119. package/src/client/page/theme.ts +32 -0
  120. package/src/client/page/view.ts +9 -0
  121. package/src/client/page/waiting.ts +109 -0
  122. package/src/client/runtime.ts +170 -0
  123. package/src/config.ts +96 -0
  124. package/src/define.ts +546 -0
  125. package/src/events.ts +194 -0
  126. package/src/html.ts +40 -0
  127. package/src/load.ts +89 -0
  128. package/src/loader.ts +109 -0
  129. package/src/package.ts +39 -0
  130. package/src/pages/blocks.ts +67 -0
  131. package/src/pages/index.ts +36 -0
  132. package/src/pages/markdown.ts +276 -0
  133. package/src/pages/render.ts +196 -0
  134. package/src/plugins.ts +197 -0
  135. package/src/running.ts +22 -0
  136. package/src/serve.ts +52 -0
  137. package/src/server.ts +644 -0
  138. package/src/status.ts +69 -0
@@ -0,0 +1,276 @@
1
+ // Markdown → HTML, with directives and fences handed to blocks.
2
+ //
3
+ // A block with a component becomes an island:
4
+ // <div class="wb-island" data-wb-island="3">fallback html</div>
5
+ // and its props go into the `islands` map the page embeds for the client to mount.
6
+ // A block with only server.ts html() is inlined as static HTML.
7
+ import path from 'node:path'
8
+ import crypto from 'node:crypto'
9
+ import { unified } from 'unified'
10
+ import remarkParse from 'remark-parse'
11
+ import remarkGfm from 'remark-gfm'
12
+ import remarkDirective from 'remark-directive'
13
+ import remarkRehype from 'remark-rehype'
14
+ import rehypeStringify from 'rehype-stringify'
15
+ import { toString } from 'mdast-util-to-string'
16
+ import { html, raw, type Html } from '../html.ts'
17
+ import { isQuestionName } from '../status.ts'
18
+ import type { ResolvedBlock } from './blocks.ts'
19
+
20
+ /**
21
+ * An mdast node, loosely: the pipeline hands nodes between remark, the directive plugin and
22
+ * blocks, and replaces some in place with `html` nodes.
23
+ */
24
+ export interface MdNode {
25
+ type: string
26
+ children?: MdNode[]
27
+ value?: string
28
+ [key: string]: any
29
+ }
30
+
31
+ type LinkFor = (absolutePath: string) => string | null
32
+
33
+ const parser = unified().use(remarkParse).use(remarkGfm).use(remarkDirective).freeze()
34
+ const toHast = unified().use(remarkRehype, { allowDangerousHtml: true }).use(rehypeStringify, { allowDangerousHtml: true }).freeze()
35
+
36
+ /** `cols=3 open title="a b"` → { cols: '3', open: '', title: 'a b' } (bare words get '' like directive attrs) */
37
+ export function parseAttrs(s: unknown) {
38
+ const out: Record<string, string> = {}
39
+ for (const m of String(s ?? '').matchAll(/([\w-]+)(?:=("[^"]*"|'[^']*'|\S+))?/g))
40
+ out[m[1]] = m[2] ? m[2].replace(/^["']|["']$/g, '') : ''
41
+ return out
42
+ }
43
+
44
+ const DIRECTIVES = new Set(['containerDirective', 'leafDirective', 'textDirective'])
45
+ const PHRASING = new Set(['text', 'emphasis', 'strong', 'delete', 'inlineCode', 'break', 'link', 'linkReference',
46
+ 'image', 'imageReference', 'footnoteReference', 'textDirective'])
47
+
48
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/i
49
+
50
+ /**
51
+ * Point relative links and images at what they name on disk: each is resolved from the markdown
52
+ * file's own folder and handed to `linkFor(absolutePath)`, which returns the URL that serves it
53
+ * (or null to leave the link as written).
54
+ */
55
+ function rewriteLinks(tree: MdNode, file: string, linkFor?: LinkFor) {
56
+ if (!linkFor || !file) return
57
+ const walk = (node: MdNode) => {
58
+ if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && node.url &&
59
+ !SCHEME.test(node.url) && !/^[/#]/.test(node.url)) {
60
+ const [, target, rest] = /^([^?#]*)(.*)$/s.exec(node.url)!
61
+ let decoded = target
62
+ try { decoded = decodeURIComponent(target) } catch { /* keep as written */ }
63
+ const url = decoded && linkFor(path.resolve(path.dirname(file), decoded))
64
+ if (url) node.url = url + rest
65
+ }
66
+ node.children?.forEach(walk)
67
+ }
68
+ walk(tree)
69
+ }
70
+
71
+ /** Separate a directive's `[label]` (remark-directive stores it as a flagged first paragraph). */
72
+ function splitLabel(node: MdNode): { label: MdNode[] | null; children: MdNode[] } {
73
+ const [head, ...rest] = node.children ?? []
74
+ if (node.type === 'containerDirective' && head?.data?.directiveLabel) return { label: head.children ?? null, children: rest }
75
+ if (node.type !== 'containerDirective') return { label: node.children?.length ? node.children : null, children: [] }
76
+ return { label: null, children: node.children ?? [] }
77
+ }
78
+
79
+ const MARKER: Record<string, string> = { textDirective: ':', leafDirective: '::', containerDirective: ':::' }
80
+
81
+ function literalDirective(node: MdNode, label: MdNode[] | null) {
82
+ const marker = MARKER[node.type]
83
+ const attrs = Object.entries(node.attributes ?? {}).map(([k, v]) => (v ? `${k}="${v}"` : k)).join(' ')
84
+ return `${marker}${node.name}${label ? `[${toString({ type: 'root', children: label } as any)}]` : ''}${attrs ? `{${attrs}}` : ''}`
85
+ }
86
+
87
+ /**
88
+ * The forms a page asks the reader to answer, by name: `:::form{name=…}` containers and
89
+ * hand-written <form name="…"> without an action. Parsed, so a form shown as an example inside a
90
+ * code block doesn't count.
91
+ */
92
+ export function formNames(source: string) {
93
+ const tree = parser.parse(String(source ?? '').replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '')) as MdNode
94
+ const names: string[] = []
95
+ const walk = (node: MdNode) => {
96
+ if (node.type === 'containerDirective' && node.name === 'form') {
97
+ const attrs = node.attributes ?? {}
98
+ names.push(attrs.name || attrs.id || 'form')
99
+ } else if (node.type === 'html') {
100
+ for (const m of (node.value ?? '').matchAll(/<form\b([^>]*)>/gi)) {
101
+ if (/\baction\s*=/i.test(m[1])) continue
102
+ const name = /\bname\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(m[1])
103
+ if (name) names.push(name[2] ?? name[3] ?? name[4])
104
+ }
105
+ }
106
+ for (const child of node.children ?? []) walk(child)
107
+ }
108
+ walk(tree)
109
+ return [...new Set(names)].filter(isQuestionName)
110
+ }
111
+
112
+ export interface RenderOptions {
113
+ page: string
114
+ file: string
115
+ /** a block by name, resolved (see blocks.ts) */
116
+ resolve: (name: string) => ResolvedBlock | null
117
+ /** the block for fences no block claims by name; without one they render as plain code */
118
+ code?: ResolvedBlock | null
119
+ /** the URL that serves a file on disk, for relative links */
120
+ linkFor?: LinkFor
121
+ }
122
+
123
+ export interface Island { block: string; client: string; props: unknown }
124
+
125
+ /**
126
+ * Markdown (or an mdast root, rendered as it is) → HTML, with directives and fences handed to
127
+ * blocks. Returns the page's HTML, its first heading, the islands to mount and the blocks'
128
+ * stylesheets.
129
+ */
130
+ export async function renderMarkdown(source: string | MdNode, { page, file, resolve, code = null, linkFor }: RenderOptions) {
131
+ let nextId = 0
132
+ const islands: Record<string, Island> = {}
133
+ const keyCount: Record<string, number> = {}
134
+ const used = new Map<string, ResolvedBlock>()
135
+
136
+ const stringify = (nodes: MdNode[]): string => {
137
+ // inline content (a label, say) is one line: as children of the root, each node would be a block
138
+ // of its own, separated by newlines, which show as spaces
139
+ if (nodes.length && nodes.every(n => PHRASING.has(n.type))) {
140
+ const out = toHast.stringify(toHast.runSync({ type: 'root', children: [{ type: 'paragraph', children: nodes }] } as any))
141
+ return out.replace(/^<p>([\s\S]*)<\/p>$/, '$1')
142
+ }
143
+ return toHast.stringify(toHast.runSync({ type: 'root', children: nodes } as any))
144
+ }
145
+ /** Render mdast nodes to HTML. Transforms nested directives first; safe to call twice on the same nodes. */
146
+ const toHtml = async (nodes: MdNode[]) => { await transform({ type: 'root', children: nodes }); return stringify(nodes) }
147
+
148
+ async function sectionsOf(children: MdNode[]) {
149
+ await transform({ type: 'root', children })
150
+ const heads = children.filter(n => n.type === 'heading')
151
+ if (!heads.length) {
152
+ return {
153
+ intro: '',
154
+ sections: children.map(n => ({ title: null, text: null, html: stringify([n]) })),
155
+ }
156
+ }
157
+ const depth = Math.min(...heads.map(h => h.depth))
158
+ const out: { heading: MdNode; body: MdNode[] }[] = []
159
+ const intro: MdNode[] = []
160
+ let current: { heading: MdNode; body: MdNode[] } | null = null
161
+ for (const n of children) {
162
+ if (n.type === 'heading' && n.depth === depth) {
163
+ current = { heading: n, body: [] }
164
+ out.push(current)
165
+ } else if (current) current.body.push(n)
166
+ else intro.push(n)
167
+ }
168
+ return {
169
+ intro: stringify(intro),
170
+ sections: out.map(s => ({ title: stringify(s.heading.children ?? []), text: toString(s.heading as any), html: stringify(s.body) })),
171
+ }
172
+ }
173
+
174
+ /** HTML into the markdown tree, where the rest of the pipeline takes it as it is: the one place it becomes a string. */
175
+ const htmlNode = (markup: Html | string): MdNode => ({ type: 'html', value: String(markup) })
176
+
177
+ /** A block's output for one directive or fence: static HTML, or an island around it. */
178
+ async function run(block: ResolvedBlock, ctx: any, fallback: () => Promise<Html | string>): Promise<Html> {
179
+ used.set(block.name, block)
180
+ try {
181
+ // a block may return a string or an `html` result: either is HTML
182
+ const own = block.html ? await block.html(ctx) : null
183
+ const body = raw(own ?? (await fallback()))
184
+ // the element is span or div, chosen here, never from input
185
+ const tag = raw(ctx.kind === 'textDirective' ? 'span' : 'div')
186
+ if (!block.client) return own != null ? body : html`<${tag} data-block="${ctx.name}">${body}</${tag}>`
187
+ const props = block.props ? await block.props(ctx) : await ctx.defaults()
188
+ const id = String(++nextId)
189
+ islands[id] = { block: block.name, client: block.client, props }
190
+ // stable across re-renders while block + props are unchanged, so the client keeps the mounted island
191
+ const hash = crypto.createHash('sha1').update(block.name + '\0' + JSON.stringify(props)).digest('hex').slice(0, 12)
192
+ const key = `${hash}-${(keyCount[hash] = (keyCount[hash] ?? 0) + 1)}`
193
+ return html`<${tag} class="wb-island" data-block="${ctx.name}" data-wb-island="${id}" data-wb-key="${key}">${body}</${tag}>`
194
+ } catch (err) {
195
+ console.error(`block ${block.name}:`, err)
196
+ return html`<pre class="wb-error">block "${block.name}" failed: ${(err as Error).message}</pre>`
197
+ }
198
+ }
199
+
200
+ const parse = (src: string) => {
201
+ const tree = parser.parse(String(src ?? '')) as MdNode
202
+ rewriteLinks(tree, file, linkFor)
203
+ return tree
204
+ }
205
+ const markdown = async (src: string) => toHtml(parse(src).children ?? [])
206
+ const inline = async (src: string) => (await markdown(src)).trim().replace(/^<p>([\s\S]*)<\/p>$/, '$1')
207
+ const base = { page, file, dir: path.dirname(file), parseAttrs, toHtml, toString, markdown, inline }
208
+
209
+ async function directive(node: MdNode): Promise<MdNode> {
210
+ const { label, children } = splitLabel(node)
211
+ const block = resolve(node.name)
212
+ if (!block) {
213
+ if (node.type === 'textDirective') return { type: 'text', value: literalDirective(node, label) }
214
+ // an unknown directive still shows its content: a typo never breaks the page
215
+ const labelHtml = label && html`<p class="wb-label"><strong>${raw(await toHtml(label))}</strong></p>`
216
+ return htmlNode(html`<div class="wb-unknown" data-directive="${node.name}">${labelHtml}${raw(await toHtml(children))}</div>`)
217
+ }
218
+ const labelHtml = label ? await toHtml(label) : null
219
+ let defaults: Promise<Record<string, unknown>> | undefined
220
+ const ctx = {
221
+ ...base,
222
+ kind: node.type,
223
+ name: node.name,
224
+ attrs: { ...node.attributes },
225
+ label: labelHtml,
226
+ labelText: label ? toString({ type: 'root', children: label } as any) : null,
227
+ children,
228
+ node,
229
+ sections: () => sectionsOf(children),
230
+ defaults: () => (defaults ??= (async () => {
231
+ const content = await toHtml(children)
232
+ return { name: node.name, attrs: { ...node.attributes }, label: labelHtml, html: content, ...(await sectionsOf(children)) }
233
+ })()),
234
+ }
235
+ return htmlNode(await run(block, ctx, () => toHtml(children)))
236
+ }
237
+
238
+ async function fence(node: MdNode): Promise<MdNode> {
239
+ const lang: string | null = node.lang || null
240
+ const plain = async () => html`<pre><code${lang && html` class="language-${lang}"`}>${node.value}</code></pre>`
241
+ const block = (lang && resolve(lang)) || code
242
+ if (!block) return htmlNode(await plain())
243
+ const name = code && block === code && lang !== code.name ? code.name : lang
244
+ const attrs = parseAttrs(node.meta)
245
+ const ctx = {
246
+ ...base,
247
+ kind: 'fence',
248
+ name,
249
+ lang,
250
+ attrs,
251
+ text: node.value,
252
+ node,
253
+ defaults: async () => ({ name, attrs, text: node.value }),
254
+ }
255
+ return htmlNode(await run(block, ctx, plain))
256
+ }
257
+
258
+ async function transform(parent: MdNode) {
259
+ const kids = parent.children
260
+ if (!kids) return
261
+ for (let i = 0; i < kids.length; i++) {
262
+ const node = kids[i]
263
+ if (DIRECTIVES.has(node.type)) kids[i] = await directive(node)
264
+ else if (node.type === 'code') kids[i] = await fence(node)
265
+ else await transform(node)
266
+ }
267
+ }
268
+
269
+ const tree = typeof source === 'string' ? parse(source) : source
270
+ const h1 = tree.children?.find(n => n.type === 'heading' && n.depth === 1)
271
+ const title = h1 ? toString(h1 as any) : null
272
+ await transform(tree)
273
+ const out = stringify(tree.children ?? [])
274
+ const styles = [...used.values()].map(t => t.style).filter((s): s is string => !!s)
275
+ return { html: out, title, islands, styles }
276
+ }
@@ -0,0 +1,196 @@
1
+ // A page on the server: a stored page → the HTML the reader sees. Markdown goes through remark with
2
+ // directives and fences handed to the plugins' blocks (markdown.ts); repository files show as highlighted
3
+ // code, folders as listings with their README on top; around all of it goes the page's frame.
4
+ // What the page draws itself is built with `html` (../html.ts), which escapes every value.
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { execFileSync } from 'node:child_process'
9
+ import { renderMarkdown, type Island, type MdNode } from './markdown.ts'
10
+ import { html, raw, type Html } from '../html.ts'
11
+ import type { RenderContext, Rendered, StoredPage } from '../define.ts'
12
+ import type { ResolvedBlock, ResolvedBlocks } from './blocks.ts'
13
+
14
+ type PagesPage = Extract<StoredPage, { kind: 'pages' }>
15
+ type FolderPage = Extract<StoredPage, { kind: 'folder' }>
16
+ interface Content { html: string | Html; title?: string | null; islands: Record<string, Island>; styles: string[] }
17
+
18
+ const BASE_CSS = new URL('../client/page/base.css', import.meta.url)
19
+
20
+ // before the stylesheets, so the page never flashes the wrong theme. A plain string, not part of an
21
+ // `html` template: the bundler writes `</script` in strings as `<\/script`, which in a tagged
22
+ // template would change the raw text the tag gets, so it rewrites the template into a helper call
23
+ const THEME_SCRIPT = raw(`<script>try{const t=localStorage.getItem('wb-theme');if(t==='light'||t==='dark')document.documentElement.dataset.theme=t}catch{}</script>`)
24
+
25
+ const CODE_LANG: Record<string, string> = { js: 'javascript', mjs: 'javascript', cjs: 'javascript', ts: 'typescript', tsx: 'tsx', jsx: 'jsx', json: 'json', css: 'css', html: 'html', sh: 'bash', zsh: 'bash', py: 'python', rs: 'rust', go: 'go', toml: 'toml', yml: 'yaml', yaml: 'yaml' }
26
+
27
+ /** Frontmatter is the core's; the page starts after it. */
28
+ const body = (source: string) => source.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '')
29
+
30
+ /** A page's title: its first heading, else its name. */
31
+ function titleOf(file: string, fallback: string) {
32
+ try {
33
+ const h1 = /^#\s+(.+)$/m.exec(body(fs.readFileSync(file, 'utf8')))
34
+ return h1 ? h1[1].replace(/[*_`]/g, '') : fallback
35
+ } catch { return fallback }
36
+ }
37
+
38
+ function crumbs(id: string, name: string) {
39
+ const parts = id ? id.split('/') : []
40
+ return html`<a href="/">${name}</a>${parts.map((p, i) => html` / <a href="/${parts.slice(0, i + 1).join('/')}">${p}</a>`)}`
41
+ }
42
+
43
+ const time = (ts: number) => html`<time data-ts="${ts}"></time>`
44
+
45
+ function pageList(pages: PagesPage['pages']) {
46
+ return html`<ul class="wb-index">${pages.map(p => html`<li><a href="/${p.id}">${titleOf(p.file, path.basename(p.id))}</a> <span class="wb-meta"><code>${p.id}</code> · edited ${time(p.mtime)}${
47
+ p.lastEvent && html` · last submit ${time(Date.parse(p.lastEvent))}`}${
48
+ p.listeners > 0 && html` · <span class="wb-waiting">agent waiting</span>`}</span></li>`)}</ul>`
49
+ }
50
+
51
+ /** The folder's README, when it has one. */
52
+ function readmeOf(page: FolderPage) {
53
+ const name = ['README.md', 'readme.md', 'Readme.md'].find(n => page.entries.some(e => !e.dir && e.name === n))
54
+ if (!name) return null
55
+ const file = path.join(page.file, name)
56
+ return { file, source: fs.readFileSync(file, 'utf8') }
57
+ }
58
+
59
+ /** A stylesheet reference (URL, file: URL string, or absolute path) → absolute path. */
60
+ function stylePath(ref: URL | string | undefined) {
61
+ if (ref == null) return null
62
+ const file = ref instanceof URL || String(ref).startsWith('file:') ? fileURLToPath(ref) : String(ref)
63
+ if (!path.isAbsolute(file)) throw new Error(`style: use a URL, e.g. new URL('./style.css', import.meta.url)`)
64
+ if (!fs.existsSync(file)) throw new Error(`style: file not found: ${file}`)
65
+ return file
66
+ }
67
+
68
+ const SKIP = new Set(['node_modules', '.git', '.whiteboard', 'dist', 'build'])
69
+ const MARKDOWN = /\.(md|markdown)$/i
70
+
71
+ /**
72
+ * Every markdown file in the project, which renders as a page: the top folder's first,
73
+ * then by path. In a git repository, the files git knows (tracked, or new and not ignored), so
74
+ * built copies and dependencies stay out; elsewhere a walk that skips the usual build and
75
+ * dependency folders. The project's own pages (.whiteboard/) are listed apart.
76
+ */
77
+ function documentsIn(dir: string) {
78
+ let files: string[]
79
+ try {
80
+ files = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '--', ':(icase)*.md', ':(icase)*.markdown'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
81
+ .split('\n').filter(f => f && !f.startsWith('.whiteboard/') && fs.existsSync(path.join(dir, f)))
82
+ } catch {
83
+ files = []
84
+ const walk = (rel: string) => {
85
+ let entries: fs.Dirent[] = []
86
+ try { entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true }) } catch { return }
87
+ for (const e of entries) {
88
+ if (e.isDirectory()) { if (!SKIP.has(e.name) && !e.name.startsWith('.')) walk(path.posix.join(rel, e.name)) }
89
+ else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name))
90
+ }
91
+ }
92
+ walk('')
93
+ }
94
+ const depth = (f: string) => f.split('/').length
95
+ return [...new Set(files)].sort((a, b) => depth(a) - depth(b) || a.localeCompare(b))
96
+ }
97
+
98
+ /** The overview's list of the project's documents: each by its title, linked to its rendered page. */
99
+ function documentList(ctx: RenderContext) {
100
+ const files = documentsIn(ctx.project.dir)
101
+ if (!files.length) return ''
102
+ const rows = files.map(f => {
103
+ const abs = path.join(ctx.project.dir, f)
104
+ return html`<li><a href="${ctx.urlFor(abs) ?? `/-/${f}`}">${titleOf(abs, f)}</a> <span class="wb-meta"><code>${f}</code></span></li>`
105
+ })
106
+ // in a section, so the heading isn't numbered like the page's own sections
107
+ return html`<section class="wb-documents"><h2>Documents</h2><ul class="wb-index">${rows}</ul></section>`
108
+ }
109
+
110
+ export function createRender(blocks: () => ResolvedBlocks, style?: URL | string, pluginStyles: (URL | string)[] = []) {
111
+ const STYLE = stylePath(style)
112
+ const PLUGIN_STYLES = pluginStyles.map(stylePath).filter((f): f is string => !!f)
113
+ async function markdown(source: string, page: string, file: string, ctx: RenderContext) {
114
+ const { blocks: set, code } = blocks()
115
+ return renderMarkdown(body(source), { page, file, resolve: name => set.get(name) ?? null, code, linkFor: ctx.urlFor })
116
+ }
117
+
118
+ async function content(page: StoredPage, ctx: RenderContext): Promise<Content> {
119
+ const { project } = ctx
120
+ switch (page.kind) {
121
+ case 'page':
122
+ return markdown(page.source, page.id, page.file, ctx)
123
+ case 'pages': {
124
+ const list = page.pages.length ? pageList(page.pages) : html`<p class="wb-meta">No pages yet.</p>`
125
+ const view = page.id
126
+ ? html`<h1>${page.id}</h1>${list}<p class="wb-meta">${page.file}</p>`
127
+ : html`<h1>${project.name}</h1>${list}${project.files && documentList(ctx)}<p class="wb-meta"><code>${project.dir}</code>${project.files && html` · <a href="/-/">files</a>`} · <a href="/_/docs">how to write pages</a></p>`
128
+ return { html: view, title: page.id || project.name, islands: {}, styles: [] }
129
+ }
130
+ case 'folder': {
131
+ const rel = page.id.slice(2)
132
+ const rows = page.entries.map(e => html`<li><a href="${encodeURIComponent(e.name) + (e.dir ? '/' : '')}">${e.name + (e.dir ? '/' : '')}</a></li>`)
133
+ const listing = html`<h1>${rel || project.name}</h1><ul class="wb-files">${rel && html`<li><a href="../">../</a></li>`}${rows}</ul><p class="wb-meta">${page.file} · <code>${page.id}</code></p>`
134
+ const readme = readmeOf(page)
135
+ if (!readme) return { html: listing, title: rel || project.name, islands: {}, styles: [] }
136
+ // markdown's output is HTML already
137
+ const r = await markdown(readme.source, page.id, readme.file, ctx)
138
+ return { ...r, html: html`${raw(r.html)}<hr>${listing}` }
139
+ }
140
+ case 'file': {
141
+ // the file as one code block, rendered by the code block (or as plain code)
142
+ const { code } = blocks()
143
+ const ext = path.extname(page.file).slice(1).toLowerCase()
144
+ const tree: MdNode = { type: 'root', children: [{ type: 'code', lang: CODE_LANG[ext] ?? (ext || null), meta: null, value: page.source }] }
145
+ const out = await renderMarkdown(tree, { page: page.id, file: page.file, resolve: () => null, code, linkFor: ctx.urlFor })
146
+ const view = html`<h1 class="wb-code-title wb-wide">${page.id.slice(2)}</h1><div class="wb-code wb-wide">${raw(out.html)}</div>`
147
+ return { html: view, title: path.basename(page.file), islands: out.islands, styles: out.styles }
148
+ }
149
+ }
150
+ }
151
+
152
+ return async function render(page: StoredPage, ctx: RenderContext): Promise<Rendered> {
153
+ let out: Content
154
+ try {
155
+ out = await content(page, ctx)
156
+ } catch (err) {
157
+ // blocks that do not resolve (a bad block in a plugin)
158
+ out = { html: html`<pre class="wb-error">${(err as Error).message}</pre>`, islands: {}, styles: [] }
159
+ }
160
+ const islands = Object.fromEntries(Object.entries(out.islands).map(([id, island]) => [id, { ...island, client: ctx.asset(island.client) }]))
161
+ const styles = out.styles.map(s => ctx.asset(s))
162
+ const nav = html`<nav class="wb-nav"><span>${crumbs(page.id, ctx.project.name)}</span>${page.mtime != null && html`<span class="wb-meta">updated <time id="wb-updated" data-ts="${page.mtime}"></time></span>`}<button type="button" class="wb-theme" title="Theme: follow the system, light or dark">auto</button><span class="wb-live" title="live reload"></span></nav>`
163
+ // the page's own, the plugins' (every page), the blocks' on this page, then the project's
164
+ const links = [ctx.asset(BASE_CSS), ...PLUGIN_STYLES.map(f => ctx.asset(f)), ...styles, ...(STYLE ? [ctx.asset(STYLE)] : [])]
165
+ return {
166
+ title: out.title || page.id || ctx.project.name,
167
+ head: html`${THEME_SCRIPT}
168
+ ${links.map(href => html`<link rel="stylesheet" href="${href}">`)}`,
169
+ // the page's content is HTML already: markdown's output, or what was built above
170
+ html: html`${nav}<main id="wb-main">${raw(out.html)}</main>`,
171
+ // the client mounts `islands` and links `styles`
172
+ data: { islands, styles, mtime: page.mtime },
173
+ }
174
+ }
175
+ }
176
+
177
+ /**
178
+ * What `whiteboard docs` prints first: how pages are written, and which blocks the project's plugins
179
+ * bring. Each plugin's own docs, printed after it, say how to write its blocks.
180
+ */
181
+ export function createDocs(blocks: () => ResolvedBlocks) {
182
+ return function docs(_ctx: RenderContext) {
183
+ const byPlugin = new Map<string, string[]>()
184
+ for (const t of blocks().blocks.values()) byPlugin.set(t.source, [...(byPlugin.get(t.source) ?? []), t.code ? `${t.name} (every other code fence)` : t.name])
185
+ const list = [...byPlugin].sort(([a], [b]) => a.localeCompare(b))
186
+ .map(([plugin, blocks]) => `- **${plugin}**: ${blocks.map(b => `\`${b}\``).join(', ')}`)
187
+ return `# Pages
188
+
189
+ A page is markdown: GFM tables, \`<details>\`, raw HTML and a hand-written \`<form name="…">\` work as they are. Plugins add blocks to it: \`:::name\` around content, \`::name\` on a line, \`:name\` inside a line, and code fences (\`\`\`\` \`\`\`name \`\`\`\`). A block nobody brings renders its content, so a typo never breaks a page.
190
+
191
+ The blocks here, by the plugin that brings them (each plugin's section below says how to write them):
192
+
193
+ ${list.join('\n')}
194
+ `
195
+ }
196
+ }