@bigmistqke/whiteboard 0.0.0-stage → 0.2.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 (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +628 -2
  3. package/bin/whiteboard.ts +488 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/whiteboard.js +542 -0
  6. package/dist/client/runtime.js +544 -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 +46 -0
  12. package/dist/plugins/chat/client.js +3 -0
  13. package/dist/plugins/chat/index.js +47 -0
  14. package/dist/plugins/chat/style.css +24 -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 +65 -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 +54 -0
  22. package/dist/plugins/comments/style.css +40 -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/forge/README.md +12 -0
  27. package/dist/plugins/forge/index.js +83 -0
  28. package/dist/plugins/form/README.md +111 -0
  29. package/dist/plugins/form/index.js +102 -0
  30. package/dist/plugins/form/style.css +41 -0
  31. package/dist/plugins/gallery/README.md +30 -0
  32. package/dist/plugins/gallery/client.js +1 -0
  33. package/dist/plugins/gallery/index.js +74 -0
  34. package/dist/plugins/gallery/style.css +27 -0
  35. package/dist/plugins/grid/README.md +33 -0
  36. package/dist/plugins/grid/index.js +33 -0
  37. package/dist/plugins/grid/style.css +25 -0
  38. package/dist/plugins/iframe/README.md +18 -0
  39. package/dist/plugins/iframe/client.js +1 -0
  40. package/dist/plugins/iframe/index.js +40 -0
  41. package/dist/plugins/iframe/style.css +29 -0
  42. package/dist/plugins/index.js +30 -0
  43. package/dist/plugins/mermaid/README.md +21 -0
  44. package/dist/plugins/mermaid/index.js +35 -0
  45. package/dist/plugins/mermaid/style.css +16 -0
  46. package/dist/plugins/quiet/README.md +26 -0
  47. package/dist/plugins/quiet/index.js +17 -0
  48. package/dist/plugins/terminal/client.js +41 -0
  49. package/dist/plugins/terminal/host.js +332 -0
  50. package/dist/plugins/terminal/index.js +171 -0
  51. package/dist/plugins/terminal/modes.js +32 -0
  52. package/dist/plugins/terminal/server.js +256 -0
  53. package/dist/plugins/terminal/sizes.js +57 -0
  54. package/dist/plugins/terminal/style.css +357 -0
  55. package/dist/solid/index.js +36 -0
  56. package/dist/src/auth.js +54 -0
  57. package/dist/src/client/page/base.css +295 -0
  58. package/dist/src/client/page/main.js +1228 -0
  59. package/dist/src/config.js +76 -0
  60. package/dist/src/events.js +183 -0
  61. package/dist/src/html.js +34 -0
  62. package/dist/src/icons.js +6 -0
  63. package/dist/src/load.js +77 -0
  64. package/dist/src/loader.js +126 -0
  65. package/dist/src/package.js +33 -0
  66. package/dist/src/pages/blocks.js +50 -0
  67. package/dist/src/pages/index.js +15 -0
  68. package/dist/src/pages/markdown.js +410 -0
  69. package/dist/src/pages/render.js +311 -0
  70. package/dist/src/plugins.js +238 -0
  71. package/dist/src/running.js +24 -0
  72. package/dist/src/serve.js +71 -0
  73. package/dist/src/server.js +725 -0
  74. package/dist/src/status.js +71 -0
  75. package/package.json +131 -4
  76. package/plugins/callout/README.md +13 -0
  77. package/plugins/callout/index.ts +25 -0
  78. package/plugins/callout/style.css +12 -0
  79. package/plugins/chat/README.md +46 -0
  80. package/plugins/chat/autosize.ts +101 -0
  81. package/plugins/chat/client.tsx +93 -0
  82. package/plugins/chat/index.ts +61 -0
  83. package/plugins/chat/style.css +24 -0
  84. package/plugins/claude-code/index.ts +136 -0
  85. package/plugins/code/README.md +42 -0
  86. package/plugins/code/diff.ts +64 -0
  87. package/plugins/code/index.ts +94 -0
  88. package/plugins/code/style.css +29 -0
  89. package/plugins/comments/client.ts +492 -0
  90. package/plugins/comments/index.ts +54 -0
  91. package/plugins/comments/style.css +40 -0
  92. package/plugins/details/README.md +17 -0
  93. package/plugins/details/index.ts +21 -0
  94. package/plugins/details/style.css +3 -0
  95. package/plugins/forge/README.md +12 -0
  96. package/plugins/forge/index.ts +71 -0
  97. package/plugins/form/README.md +111 -0
  98. package/plugins/form/index.ts +104 -0
  99. package/plugins/form/style.css +41 -0
  100. package/plugins/gallery/README.md +30 -0
  101. package/plugins/gallery/client.tsx +64 -0
  102. package/plugins/gallery/index.ts +67 -0
  103. package/plugins/gallery/style.css +27 -0
  104. package/plugins/grid/README.md +33 -0
  105. package/plugins/grid/index.ts +36 -0
  106. package/plugins/grid/style.css +25 -0
  107. package/plugins/iframe/README.md +18 -0
  108. package/plugins/iframe/client.ts +46 -0
  109. package/plugins/iframe/index.ts +54 -0
  110. package/plugins/iframe/style.css +29 -0
  111. package/plugins/index.ts +21 -0
  112. package/plugins/mermaid/README.md +21 -0
  113. package/plugins/mermaid/index.ts +40 -0
  114. package/plugins/mermaid/style.css +16 -0
  115. package/plugins/quiet/README.md +26 -0
  116. package/plugins/quiet/index.ts +27 -0
  117. package/plugins/terminal/client.ts +317 -0
  118. package/plugins/terminal/host.ts +326 -0
  119. package/plugins/terminal/index.ts +138 -0
  120. package/plugins/terminal/modes.ts +30 -0
  121. package/plugins/terminal/server.ts +215 -0
  122. package/plugins/terminal/sizes.ts +60 -0
  123. package/plugins/terminal/style.css +71 -0
  124. package/skills/whiteboard/SKILL.md +302 -0
  125. package/solid/index.tsx +59 -0
  126. package/src/auth.ts +66 -0
  127. package/src/client/forms.ts +185 -0
  128. package/src/client/markdown.ts +36 -0
  129. package/src/client/page/base.css +295 -0
  130. package/src/client/page/elsewhere.ts +70 -0
  131. package/src/client/page/fresh.ts +205 -0
  132. package/src/client/page/live.ts +30 -0
  133. package/src/client/page/main.ts +272 -0
  134. package/src/client/page/orphans.ts +46 -0
  135. package/src/client/page/sort.ts +38 -0
  136. package/src/client/page/theme.ts +32 -0
  137. package/src/client/page/view.ts +9 -0
  138. package/src/client/page/waiting.ts +182 -0
  139. package/src/client/read.ts +73 -0
  140. package/src/client/runtime.ts +183 -0
  141. package/src/client/toast.ts +25 -0
  142. package/src/config.ts +96 -0
  143. package/src/define.ts +612 -0
  144. package/src/events.ts +218 -0
  145. package/src/html.ts +40 -0
  146. package/src/icons.ts +8 -0
  147. package/src/load.ts +89 -0
  148. package/src/loader.ts +112 -0
  149. package/src/package.ts +39 -0
  150. package/src/pages/blocks.ts +70 -0
  151. package/src/pages/index.ts +42 -0
  152. package/src/pages/markdown.ts +364 -0
  153. package/src/pages/render.ts +233 -0
  154. package/src/plugins.ts +197 -0
  155. package/src/running.ts +22 -0
  156. package/src/serve.ts +52 -0
  157. package/src/server.ts +667 -0
  158. package/src/status.ts +113 -0
@@ -0,0 +1,364 @@
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
+ import type { TextLink } from '../define.ts'
20
+
21
+ /**
22
+ * An mdast node, loosely: the pipeline hands nodes between remark, the directive plugin and
23
+ * blocks, and replaces some in place with `html` nodes.
24
+ */
25
+ export interface MdNode {
26
+ type: string
27
+ children?: MdNode[]
28
+ value?: string
29
+ [key: string]: any
30
+ }
31
+
32
+ type LinkFor = (absolutePath: string) => string | null
33
+
34
+ const parser = unified().use(remarkParse).use(remarkGfm).use(remarkDirective).freeze()
35
+
36
+ // A line starting with `:::` inside a code fence would close the container directive around the
37
+ // fence: the directive parser looks for its closing fence on every line before the code fence's
38
+ // content. So inside code fences, a line's leading colons are hidden from it (as a character no
39
+ // page uses), and put back in the parsed tree.
40
+ const HIDDEN_COLON = '\uE000'
41
+ const FENCE = /^(\s*)(`{3,}|~{3,})/
42
+
43
+ function hideColonsInFences(source: string): string {
44
+ let open: { char: string; length: number } | null = null
45
+ return source.split('\n').map(line => {
46
+ const fence = FENCE.exec(line)
47
+ if (!open) {
48
+ if (fence) open = { char: fence[2][0], length: fence[2].length }
49
+ return line
50
+ }
51
+ if (fence && fence[2][0] === open.char && fence[2].length >= open.length && !line.slice(fence[0].length).trim()) { open = null; return line }
52
+ return line.replace(/^(\s*)(:+)/, (_, space: string, colons: string) => space + HIDDEN_COLON.repeat(colons.length))
53
+ }).join('\n')
54
+ }
55
+
56
+ function showColons(node: MdNode) {
57
+ if (typeof node.value === 'string' && node.value.includes(HIDDEN_COLON)) node.value = node.value.replaceAll(HIDDEN_COLON, ':')
58
+ node.children?.forEach(showColons)
59
+ }
60
+
61
+ /** A message's raw HTML, as text: it shows as written, and runs nothing. */
62
+ function asText(node: MdNode) {
63
+ if (node.type === 'html') { node.type = 'text'; return }
64
+ node.children?.forEach(asText)
65
+ }
66
+
67
+ /** Markdown → mdast: GFM and directives, with code fences safe inside containers. */
68
+ function parseMarkdown(source: string): MdNode {
69
+ const tree = parser.parse(hideColonsInFences(source)) as MdNode
70
+ showColons(tree)
71
+ return tree
72
+ }
73
+ const toHast = unified().use(remarkRehype, { allowDangerousHtml: true }).use(rehypeStringify, { allowDangerousHtml: true }).freeze()
74
+
75
+ /** `cols=3 open title="a b"` → { cols: '3', open: '', title: 'a b' } (bare words get '' like directive attrs) */
76
+ export function parseAttrs(s: unknown) {
77
+ const out: Record<string, string> = {}
78
+ for (const m of String(s ?? '').matchAll(/([\w-]+)(?:=("[^"]*"|'[^']*'|\S+))?/g))
79
+ out[m[1]] = m[2] ? m[2].replace(/^["']|["']$/g, '') : ''
80
+ return out
81
+ }
82
+
83
+ const DIRECTIVES = new Set(['containerDirective', 'leafDirective', 'textDirective'])
84
+ const PHRASING = new Set(['text', 'emphasis', 'strong', 'delete', 'inlineCode', 'break', 'link', 'linkReference',
85
+ 'image', 'imageReference', 'footnoteReference', 'textDirective'])
86
+
87
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/i
88
+
89
+ /**
90
+ * Point relative links and images at what they name on disk: each is resolved from the markdown
91
+ * file's own folder and handed to `linkFor(absolutePath)`, which returns the URL that serves it
92
+ * (or null to leave the link as written).
93
+ */
94
+ // where text is not linked: it is code, a link already, or an inline directive (a button, a field)
95
+ const NO_TEXT_LINKS = new Set(['link', 'linkReference', 'inlineCode', 'code', 'html', 'textDirective', 'definition'])
96
+
97
+ /** Turn the plugins' text links (`#12`) into links, in plain text only. */
98
+ function linkText(tree: MdNode, links: TextLink[]) {
99
+ if (!links.length) return
100
+ const split = (text: string): MdNode[] => {
101
+ let parts: MdNode[] = [{ type: 'text', value: text }]
102
+ for (const link of links) {
103
+ const flags = link.pattern.flags.includes('g') ? link.pattern.flags : link.pattern.flags + 'g'
104
+ parts = parts.flatMap(part => {
105
+ if (part.type !== 'text') return [part]
106
+ const out: MdNode[] = []
107
+ const value = part.value as string
108
+ const re = new RegExp(link.pattern.source, flags)
109
+ let at = 0
110
+ for (let m = re.exec(value); m; m = re.exec(value)) {
111
+ if (!m[0]) { re.lastIndex++; continue }
112
+ const href = link.href(m)
113
+ if (!href) continue
114
+ if (m.index > at) out.push({ type: 'text', value: value.slice(at, m.index) })
115
+ out.push({ type: 'link', url: href, title: link.title?.(m) ?? null, children: [{ type: 'text', value: m[0] }] })
116
+ at = m.index + m[0].length
117
+ }
118
+ if (at < value.length) out.push({ type: 'text', value: value.slice(at) })
119
+ return out
120
+ })
121
+ }
122
+ return parts
123
+ }
124
+ const walk = (node: MdNode) => {
125
+ if (!node.children || NO_TEXT_LINKS.has(node.type)) return
126
+ node.children = node.children.flatMap(child => child.type === 'text' ? split(child.value as string) : (walk(child), [child]))
127
+ }
128
+ walk(tree)
129
+ }
130
+
131
+ function rewriteLinks(tree: MdNode, file: string, linkFor?: LinkFor) {
132
+ if (!linkFor || !file) return
133
+ const walk = (node: MdNode) => {
134
+ if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && node.url &&
135
+ !SCHEME.test(node.url) && !/^[/#]/.test(node.url)) {
136
+ const [, target, rest] = /^([^?#]*)(.*)$/s.exec(node.url)!
137
+ let decoded = target
138
+ try { decoded = decodeURIComponent(target) } catch { /* keep as written */ }
139
+ const url = decoded && linkFor(path.resolve(path.dirname(file), decoded))
140
+ if (url) node.url = url + rest
141
+ }
142
+ node.children?.forEach(walk)
143
+ }
144
+ walk(tree)
145
+ }
146
+
147
+ /** Separate a directive's `[label]` (remark-directive stores it as a flagged first paragraph). */
148
+ function splitLabel(node: MdNode): { label: MdNode[] | null; children: MdNode[] } {
149
+ const [head, ...rest] = node.children ?? []
150
+ if (node.type === 'containerDirective' && head?.data?.directiveLabel) return { label: head.children ?? null, children: rest }
151
+ if (node.type !== 'containerDirective') return { label: node.children?.length ? node.children : null, children: [] }
152
+ return { label: null, children: node.children ?? [] }
153
+ }
154
+
155
+ const MARKER: Record<string, string> = { textDirective: ':', leafDirective: '::', containerDirective: ':::' }
156
+
157
+ function literalDirective(node: MdNode, label: MdNode[] | null) {
158
+ const marker = MARKER[node.type]
159
+ const attrs = Object.entries(node.attributes ?? {}).map(([k, v]) => (v ? `${k}="${v}"` : k)).join(' ')
160
+ return `${marker}${node.name}${label ? `[${toString({ type: 'root', children: label } as any)}]` : ''}${attrs ? `{${attrs}}` : ''}`
161
+ }
162
+
163
+ /**
164
+ * The forms a page asks the reader to answer, by name: `:::form{name=…}` containers and
165
+ * hand-written <form name="…"> without an action. Parsed, so a form shown as an example inside a
166
+ * code block doesn't count.
167
+ */
168
+ export function formNames(source: string) {
169
+ const tree = parseMarkdown(String(source ?? '').replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, ''))
170
+ const names: string[] = []
171
+ const walk = (node: MdNode) => {
172
+ if (node.type === 'containerDirective' && node.name === 'form') {
173
+ const attrs = node.attributes ?? {}
174
+ names.push(attrs.name || attrs.id || 'form')
175
+ } else if (node.type === 'html') {
176
+ for (const m of (node.value ?? '').matchAll(/<form\b([^>]*)>/gi)) {
177
+ if (/\baction\s*=/i.test(m[1])) continue
178
+ const name = /\bname\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(m[1])
179
+ if (name) names.push(name[2] ?? name[3] ?? name[4])
180
+ }
181
+ }
182
+ for (const child of node.children ?? []) walk(child)
183
+ }
184
+ walk(tree)
185
+ return [...new Set(names)].filter(isQuestionName)
186
+ }
187
+
188
+ export interface RenderOptions {
189
+ page: string
190
+ file: string
191
+ /** a block by name, resolved (see blocks.ts) */
192
+ resolve: (name: string) => ResolvedBlock | null
193
+ /** the block for fences no block claims by name; without one they render as plain code */
194
+ code?: ResolvedBlock | null
195
+ /** the URL that serves a file on disk, for relative links */
196
+ linkFor?: LinkFor
197
+ /** the plugins' text links (`#12` → an issue), applied to plain text */
198
+ textLinks?: TextLink[]
199
+ /**
200
+ * a message (a comment, a chat message), not a page: raw HTML shows as text, and directives as
201
+ * written (no buttons or forms in a message); code fences and text links work as on a page
202
+ */
203
+ message?: boolean
204
+ }
205
+
206
+ export interface Island { block: string; client: string; props: unknown }
207
+
208
+ /**
209
+ * Markdown (or an mdast root, rendered as it is) → HTML, with directives and fences handed to
210
+ * blocks. Returns the page's HTML, its first heading, the islands to mount and the blocks'
211
+ * stylesheets.
212
+ */
213
+ export async function renderMarkdown(source: string | MdNode, { page, file, resolve, code = null, linkFor, textLinks = [], message = false }: RenderOptions) {
214
+ let nextId = 0
215
+ const islands: Record<string, Island> = {}
216
+ const keyCount: Record<string, number> = {}
217
+ const used = new Map<string, ResolvedBlock>()
218
+
219
+ const stringify = (nodes: MdNode[]): string => {
220
+ // inline content (a label, say) is one line: as children of the root, each node would be a block
221
+ // of its own, separated by newlines, which show as spaces
222
+ if (nodes.length && nodes.every(n => PHRASING.has(n.type))) {
223
+ const out = toHast.stringify(toHast.runSync({ type: 'root', children: [{ type: 'paragraph', children: nodes }] } as any))
224
+ return out.replace(/^<p>([\s\S]*)<\/p>$/, '$1')
225
+ }
226
+ return toHast.stringify(toHast.runSync({ type: 'root', children: nodes } as any))
227
+ }
228
+ /** Render mdast nodes to HTML. Transforms nested directives first; safe to call twice on the same nodes. */
229
+ const toHtml = async (nodes: MdNode[]) => { await transform({ type: 'root', children: nodes }); return stringify(nodes) }
230
+
231
+ async function sectionsOf(children: MdNode[]) {
232
+ await transform({ type: 'root', children })
233
+ const heads = children.filter(n => n.type === 'heading')
234
+ if (!heads.length) {
235
+ return {
236
+ intro: '',
237
+ sections: children.map(n => ({ title: null, text: null, html: stringify([n]) })),
238
+ }
239
+ }
240
+ const depth = Math.min(...heads.map(h => h.depth))
241
+ const out: { heading: MdNode; body: MdNode[] }[] = []
242
+ const intro: MdNode[] = []
243
+ let current: { heading: MdNode; body: MdNode[] } | null = null
244
+ for (const n of children) {
245
+ if (n.type === 'heading' && n.depth === depth) {
246
+ current = { heading: n, body: [] }
247
+ out.push(current)
248
+ } else if (current) current.body.push(n)
249
+ else intro.push(n)
250
+ }
251
+ return {
252
+ intro: stringify(intro),
253
+ sections: out.map(s => ({ title: stringify(s.heading.children ?? []), text: toString(s.heading as any), html: stringify(s.body) })),
254
+ }
255
+ }
256
+
257
+ /** HTML into the markdown tree, where the rest of the pipeline takes it as it is: the one place it becomes a string. */
258
+ const htmlNode = (markup: Html | string): MdNode => ({ type: 'html', value: String(markup) })
259
+
260
+ /** A block's output for one directive or fence: static HTML, or an island around it. */
261
+ async function run(block: ResolvedBlock, ctx: any, fallback: () => Promise<Html | string>): Promise<Html> {
262
+ used.set(block.name, block)
263
+ try {
264
+ // a block may return a string or an `html` result: either is HTML
265
+ const own = block.html ? await block.html(ctx) : null
266
+ const body = raw(own ?? (await fallback()))
267
+ // the element is span or div, chosen here, never from input
268
+ const tag = raw(ctx.kind === 'textDirective' ? 'span' : 'div')
269
+ if (!block.client) return own != null ? body : html`<${tag} data-block="${ctx.name}">${body}</${tag}>`
270
+ const props = block.props ? await block.props(ctx) : await ctx.defaults()
271
+ const id = String(++nextId)
272
+ islands[id] = { block: block.name, client: block.client, props }
273
+ // stable across re-renders while block + props are unchanged, so the client keeps the mounted island
274
+ const hash = crypto.createHash('sha1').update(block.name + '\0' + JSON.stringify(props)).digest('hex').slice(0, 12)
275
+ const key = `${hash}-${(keyCount[hash] = (keyCount[hash] ?? 0) + 1)}`
276
+ return html`<${tag} class="wb-island" data-block="${ctx.name}" data-wb-island="${id}" data-wb-key="${key}">${body}</${tag}>`
277
+ } catch (err) {
278
+ console.error(`block ${block.name}:`, err)
279
+ return html`<pre class="wb-error">block "${block.name}" failed: ${(err as Error).message}</pre>`
280
+ }
281
+ }
282
+
283
+ const parse = (src: string) => {
284
+ const tree = parseMarkdown(String(src ?? ''))
285
+ if (message) asText(tree)
286
+ rewriteLinks(tree, file, linkFor)
287
+ linkText(tree, textLinks)
288
+ return tree
289
+ }
290
+ const markdown = async (src: string) => toHtml(parse(src).children ?? [])
291
+ const inline = async (src: string) => (await markdown(src)).trim().replace(/^<p>([\s\S]*)<\/p>$/, '$1')
292
+ const base = { page, file, dir: path.dirname(file), parseAttrs, toHtml, toString, markdown, inline }
293
+
294
+ async function directive(node: MdNode): Promise<MdNode> {
295
+ const { label, children } = splitLabel(node)
296
+ const block = resolve(node.name)
297
+ if (!block) {
298
+ if (node.type === 'textDirective') return { type: 'text', value: literalDirective(node, label) }
299
+ // an unknown directive still shows its content: a typo never breaks the page
300
+ const labelHtml = label && html`<p class="wb-label"><strong>${raw(await toHtml(label))}</strong></p>`
301
+ return htmlNode(html`<div class="wb-unknown" data-directive="${node.name}">${labelHtml}${raw(await toHtml(children))}</div>`)
302
+ }
303
+ const labelHtml = label ? await toHtml(label) : null
304
+ let defaults: Promise<Record<string, unknown>> | undefined
305
+ const ctx = {
306
+ ...base,
307
+ kind: node.type,
308
+ name: node.name,
309
+ attrs: { ...node.attributes },
310
+ label: labelHtml,
311
+ labelText: label ? toString({ type: 'root', children: label } as any) : null,
312
+ children,
313
+ node,
314
+ sections: () => sectionsOf(children),
315
+ defaults: () => (defaults ??= (async () => {
316
+ const content = await toHtml(children)
317
+ return { name: node.name, attrs: { ...node.attributes }, label: labelHtml, html: content, ...(await sectionsOf(children)) }
318
+ })()),
319
+ }
320
+ return htmlNode(await run(block, ctx, () => toHtml(children)))
321
+ }
322
+
323
+ async function fence(node: MdNode): Promise<MdNode> {
324
+ const lang: string | null = node.lang || null
325
+ const plain = async () => html`<pre><code${lang && html` class="language-${lang}"`}>${node.value}</code></pre>`
326
+ // a fence goes to the block of its language only if that block takes fences: ```text is code,
327
+ // not the text field of the same name
328
+ const named = lang ? resolve(lang) : null
329
+ const block = (named?.fences ? named : null) || code
330
+ if (!block) return htmlNode(await plain())
331
+ const name = code && block === code && lang !== code.name ? code.name : lang
332
+ const attrs = parseAttrs(node.meta)
333
+ const ctx = {
334
+ ...base,
335
+ kind: 'fence',
336
+ name,
337
+ lang,
338
+ attrs,
339
+ text: node.value,
340
+ node,
341
+ defaults: async () => ({ name, attrs, text: node.value }),
342
+ }
343
+ return htmlNode(await run(block, ctx, plain))
344
+ }
345
+
346
+ async function transform(parent: MdNode) {
347
+ const kids = parent.children
348
+ if (!kids) return
349
+ for (let i = 0; i < kids.length; i++) {
350
+ const node = kids[i]
351
+ if (DIRECTIVES.has(node.type)) kids[i] = await directive(node)
352
+ else if (node.type === 'code') kids[i] = await fence(node)
353
+ else await transform(node)
354
+ }
355
+ }
356
+
357
+ const tree = typeof source === 'string' ? parse(source) : source
358
+ const h1 = tree.children?.find(n => n.type === 'heading' && n.depth === 1)
359
+ const title = h1 ? toString(h1 as any) : null
360
+ await transform(tree)
361
+ const out = stringify(tree.children ?? [])
362
+ const styles = [...used.values()].map(t => t.style).filter((s): s is string => !!s)
363
+ return { html: out, title, islands, styles }
364
+ }
@@ -0,0 +1,233 @@
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 { INBOX_ICON, awaitingLabel } from '../icons.ts'
12
+ import type { RenderContext, Rendered, StoredPage, TextLink } from '../define.ts'
13
+ import type { ResolvedBlock, ResolvedBlocks } from './blocks.ts'
14
+
15
+ type PagesPage = Extract<StoredPage, { kind: 'pages' }>
16
+ type FolderPage = Extract<StoredPage, { kind: 'folder' }>
17
+ interface Content { html: string | Html; title?: string | null; islands: Record<string, Island>; styles: string[] }
18
+
19
+ const BASE_CSS = new URL('../client/page/base.css', import.meta.url)
20
+
21
+ // before the stylesheets, so the page never flashes the wrong theme. A plain string, not part of an
22
+ // `html` template: the bundler writes `</script` in strings as `<\/script`, which in a tagged
23
+ // template would change the raw text the tag gets, so it rewrites the template into a helper call
24
+ const THEME_SCRIPT = raw(`<script>try{const t=localStorage.getItem('wb-theme');if(t==='light'||t==='dark')document.documentElement.dataset.theme=t}catch{}</script>`)
25
+
26
+ 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' }
27
+
28
+ /** Frontmatter is the core's; the page starts after it. */
29
+ const body = (source: string) => source.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '')
30
+
31
+ /** A page's title: its first heading, else its name. */
32
+ export function titleOf(file: string, fallback: string) {
33
+ try {
34
+ const h1 = /^#\s+(.+)$/m.exec(body(fs.readFileSync(file, 'utf8')))
35
+ return h1 ? h1[1].replace(/[*_`]/g, '') : fallback
36
+ } catch { return fallback }
37
+ }
38
+
39
+ function crumbs(id: string, name: string) {
40
+ const parts = id ? id.split('/') : []
41
+ return html`<a href="/">${name}</a>${parts.map((p, i) => html` / <a href="/${parts.slice(0, i + 1).join('/')}">${p}</a>`)}`
42
+ }
43
+
44
+ const time = (ts: number) => html`<time data-ts="${ts}"></time>`
45
+
46
+ function pageList(pages: PagesPage['pages']) {
47
+ return html`<ul class="wb-index">${pages.map(p => html`<li><a href="/${p.id}">${titleOf(p.file, path.basename(p.id))}</a>${
48
+ p.awaiting > 0 && html` <a class="wb-awaiting" href="/${p.id}#wb-waiting" title="${awaitingLabel(p.awaiting)}" aria-label="${awaitingLabel(p.awaiting)}">${raw(INBOX_ICON)}${p.awaiting}</a>`} <span class="wb-meta"><code>${p.id}</code> · edited ${time(p.mtime)}${
49
+ p.lastEvent && html` · last submit ${time(Date.parse(p.lastEvent))}`}</span></li>`)}</ul>`
50
+ }
51
+
52
+ /** The folder's README, when it has one. */
53
+ function readmeOf(page: FolderPage) {
54
+ const name = ['README.md', 'readme.md', 'Readme.md'].find(n => page.entries.some(e => !e.dir && e.name === n))
55
+ if (!name) return null
56
+ const file = path.join(page.file, name)
57
+ return { file, source: fs.readFileSync(file, 'utf8') }
58
+ }
59
+
60
+ /** A stylesheet reference (URL, file: URL string, or absolute path) → absolute path. */
61
+ function stylePath(ref: URL | string | undefined) {
62
+ if (ref == null) return null
63
+ const file = ref instanceof URL || String(ref).startsWith('file:') ? fileURLToPath(ref) : String(ref)
64
+ if (!path.isAbsolute(file)) throw new Error(`style: use a URL, e.g. new URL('./style.css', import.meta.url)`)
65
+ if (!fs.existsSync(file)) throw new Error(`style: file not found: ${file}`)
66
+ return file
67
+ }
68
+
69
+ const SKIP = new Set(['node_modules', '.git', '.whiteboard', 'dist', 'build'])
70
+ const MARKDOWN = /\.(md|markdown)$/i
71
+
72
+ /**
73
+ * Every markdown file in the project, which renders as a page: the top folder's first,
74
+ * then by path. In a git repository, the files git knows (tracked, or new and not ignored), so
75
+ * built copies and dependencies stay out; elsewhere a walk that skips the usual build and
76
+ * dependency folders. The project's own pages (.whiteboard/) are listed apart.
77
+ */
78
+ function documentsIn(dir: string) {
79
+ let files: string[]
80
+ try {
81
+ files = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '--', ':(icase)*.md', ':(icase)*.markdown'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
82
+ .split('\n').filter(f => f && !f.startsWith('.whiteboard/') && fs.existsSync(path.join(dir, f)))
83
+ } catch {
84
+ files = []
85
+ const walk = (rel: string) => {
86
+ let entries: fs.Dirent[] = []
87
+ try { entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true }) } catch { return }
88
+ for (const e of entries) {
89
+ if (e.isDirectory()) { if (!SKIP.has(e.name) && !e.name.startsWith('.')) walk(path.posix.join(rel, e.name)) }
90
+ else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name))
91
+ }
92
+ }
93
+ walk('')
94
+ }
95
+ const depth = (f: string) => f.split('/').length
96
+ return [...new Set(files)].sort((a, b) => depth(a) - depth(b) || a.localeCompare(b))
97
+ }
98
+
99
+ /**
100
+ * The overview's list of the project's documents: each by its title, linked to its rendered page,
101
+ * with when its file last changed. The list can be sorted in the browser (sort.ts): by folder (as
102
+ * written here), by when last updated, or by title; each row carries what it is sorted by.
103
+ */
104
+ function documentList(ctx: RenderContext) {
105
+ const files = documentsIn(ctx.project.dir)
106
+ if (!files.length) return ''
107
+ const rows = files.map((f, i) => {
108
+ const abs = path.join(ctx.project.dir, f)
109
+ // a file without a heading goes by its name, and the line under it says the folder it is in
110
+ const name = path.posix.basename(f)
111
+ const title = titleOf(abs, name)
112
+ const where = title === name ? path.posix.dirname(f) : f
113
+ let mtime = 0
114
+ try { mtime = fs.statSync(abs).mtimeMs } catch { /* gone meanwhile */ }
115
+ return html`<li data-order="${i}" data-updated="${mtime}" data-title="${title.toLowerCase()}"><a href="${ctx.urlFor(abs) ?? `/-/${f}`}">${title}</a> <span class="wb-meta">${where !== '.' && html`<code>${where === f ? f : `${where}/`}</code> · `}edited ${time(mtime)}</span></li>`
116
+ })
117
+ // in a section, so the heading isn't numbered like the page's own sections
118
+ return html`<section class="wb-documents"><div class="wb-list-head"><h2>Documents</h2><label class="wb-sort">sort <select data-wb-sort="documents" aria-label="Sort the documents"><option value="order">by folder</option><option value="updated">last updated</option><option value="title">by title</option></select></label></div><ul class="wb-index">${rows}</ul></section>`
119
+ }
120
+
121
+ /** The plugins' text links for a project folder, asked once per folder. */
122
+ function textLinksOf(links: ((ctx: { dir: string }) => TextLink[])[]) {
123
+ const linksFor = new Map<string, TextLink[]>()
124
+ return (dir: string) => {
125
+ let got = linksFor.get(dir)
126
+ if (!got) {
127
+ got = links.flatMap(fn => { try { return fn({ dir }) } catch (err) { console.error('links:', err); return [] } })
128
+ linksFor.set(dir, got)
129
+ }
130
+ return got
131
+ }
132
+ }
133
+
134
+ /**
135
+ * A message (a comment, a chat message) as HTML: markdown as on a page, but its raw HTML as text and
136
+ * its directives as written. Code fences go to the code block, so `styles` are what it needs linked.
137
+ */
138
+ export function createMessageRender(blocks: () => ResolvedBlocks, links: ((ctx: { dir: string }) => TextLink[])[] = []) {
139
+ const textLinks = textLinksOf(links)
140
+ return async (text: string, ctx: RenderContext) => {
141
+ const out = await renderMarkdown(String(text ?? ''), { page: '', file: '', resolve: () => null, code: blocks().code, textLinks: textLinks(ctx.project.dir), message: true })
142
+ return { html: out.html, styles: out.styles.map(s => ctx.asset(s)) }
143
+ }
144
+ }
145
+
146
+ export function createRender(blocks: () => ResolvedBlocks, style?: URL | string, pluginStyles: (URL | string)[] = [], links: ((ctx: { dir: string }) => TextLink[])[] = []) {
147
+ const textLinks = textLinksOf(links)
148
+ const STYLE = stylePath(style)
149
+ const PLUGIN_STYLES = pluginStyles.map(stylePath).filter((f): f is string => !!f)
150
+ async function markdown(source: string, page: string, file: string, ctx: RenderContext) {
151
+ const { blocks: set, code } = blocks()
152
+ return renderMarkdown(body(source), { page, file, resolve: name => set.get(name) ?? null, code, linkFor: ctx.urlFor, textLinks: textLinks(ctx.project.dir) })
153
+ }
154
+
155
+ async function content(page: StoredPage, ctx: RenderContext): Promise<Content> {
156
+ const { project } = ctx
157
+ switch (page.kind) {
158
+ case 'page':
159
+ return markdown(page.source, page.id, page.file, ctx)
160
+ case 'pages': {
161
+ const list = page.pages.length ? pageList(page.pages) : html`<p class="wb-meta">No pages yet.</p>`
162
+ const view = page.id
163
+ ? html`<h1>${page.id}</h1>${list}<p class="wb-meta">${page.file}</p>`
164
+ : 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>`
165
+ return { html: view, title: page.id || project.name, islands: {}, styles: [] }
166
+ }
167
+ case 'folder': {
168
+ const rel = page.id.slice(2)
169
+ const rows = page.entries.map(e => html`<li><a href="${encodeURIComponent(e.name) + (e.dir ? '/' : '')}">${e.name + (e.dir ? '/' : '')}</a></li>`)
170
+ 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>`
171
+ const readme = readmeOf(page)
172
+ if (!readme) return { html: listing, title: rel || project.name, islands: {}, styles: [] }
173
+ // markdown's output is HTML already
174
+ const r = await markdown(readme.source, page.id, readme.file, ctx)
175
+ return { ...r, html: html`${raw(r.html)}<hr>${listing}` }
176
+ }
177
+ case 'file': {
178
+ // the file as one code block, rendered by the code block (or as plain code)
179
+ const { code } = blocks()
180
+ const ext = path.extname(page.file).slice(1).toLowerCase()
181
+ const tree: MdNode = { type: 'root', children: [{ type: 'code', lang: CODE_LANG[ext] ?? (ext || null), meta: null, value: page.source }] }
182
+ const out = await renderMarkdown(tree, { page: page.id, file: page.file, resolve: () => null, code, linkFor: ctx.urlFor })
183
+ 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>`
184
+ return { html: view, title: path.basename(page.file), islands: out.islands, styles: out.styles }
185
+ }
186
+ }
187
+ }
188
+
189
+ return async function render(page: StoredPage, ctx: RenderContext): Promise<Rendered> {
190
+ let out: Content
191
+ try {
192
+ out = await content(page, ctx)
193
+ } catch (err) {
194
+ // blocks that do not resolve (a bad block in a plugin)
195
+ out = { html: html`<pre class="wb-error">${(err as Error).message}</pre>`, islands: {}, styles: [] }
196
+ }
197
+ const islands = Object.fromEntries(Object.entries(out.islands).map(([id, island]) => [id, { ...island, client: ctx.asset(island.client) }]))
198
+ const styles = out.styles.map(s => ctx.asset(s))
199
+ 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" aria-label="Theme"></button><span class="wb-live" role="img" title="Connecting…" aria-label="Connecting…"></span></nav>`
200
+ // the page's own, the plugins' (every page), the blocks' on this page, then the project's
201
+ const links = [ctx.asset(BASE_CSS), ...PLUGIN_STYLES.map(f => ctx.asset(f)), ...styles, ...(STYLE ? [ctx.asset(STYLE)] : [])]
202
+ return {
203
+ title: out.title || page.id || ctx.project.name,
204
+ head: html`${THEME_SCRIPT}
205
+ ${links.map(href => html`<link rel="stylesheet" href="${href}">`)}`,
206
+ // the page's content is HTML already: markdown's output, or what was built above
207
+ html: html`${nav}<main id="wb-main">${raw(out.html)}</main>`,
208
+ // the client mounts `islands` and links `styles`
209
+ data: { islands, styles, mtime: page.mtime },
210
+ }
211
+ }
212
+ }
213
+
214
+ /**
215
+ * What `whiteboard docs` prints first: how pages are written, and which blocks the project's plugins
216
+ * bring. Each plugin's own docs, printed after it, say how to write its blocks.
217
+ */
218
+ export function createDocs(blocks: () => ResolvedBlocks) {
219
+ return function docs(_ctx: RenderContext) {
220
+ const byPlugin = new Map<string, string[]>()
221
+ 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])
222
+ const list = [...byPlugin].sort(([a], [b]) => a.localeCompare(b))
223
+ .map(([plugin, blocks]) => `- **${plugin}**: ${blocks.map(b => `\`${b}\``).join(', ')}`)
224
+ return `# Pages
225
+
226
+ 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.
227
+
228
+ The blocks here, by the plugin that brings them (each plugin's section below says how to write them):
229
+
230
+ ${list.join('\n')}
231
+ `
232
+ }
233
+ }