@bigmistqke/whiteboard 0.1.0 → 0.2.1

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 (73) hide show
  1. package/README.md +31 -12
  2. package/bin/whiteboard.ts +74 -17
  3. package/dist/bin/whiteboard.js +93 -22
  4. package/dist/client/runtime.js +164 -11
  5. package/dist/plugins/chat/README.md +2 -1
  6. package/dist/plugins/chat/client.js +2 -2
  7. package/dist/plugins/chat/index.js +1 -0
  8. package/dist/plugins/chat/style.css +7 -0
  9. package/dist/plugins/code/diff.js +1 -0
  10. package/dist/plugins/comments/client.js +6 -6
  11. package/dist/plugins/comments/index.js +4 -1
  12. package/dist/plugins/comments/style.css +8 -0
  13. package/dist/plugins/forge/README.md +12 -0
  14. package/dist/plugins/forge/index.js +83 -0
  15. package/dist/plugins/gallery/client.js +1 -1
  16. package/dist/plugins/iframe/README.md +18 -0
  17. package/dist/plugins/iframe/client.js +1 -0
  18. package/dist/plugins/iframe/index.js +40 -0
  19. package/dist/plugins/iframe/style.css +29 -0
  20. package/dist/plugins/index.js +4 -0
  21. package/dist/plugins/mermaid/index.js +1 -0
  22. package/dist/solid/index.js +2 -1
  23. package/dist/src/client/page/base.css +33 -12
  24. package/dist/src/client/page/main.js +250 -26
  25. package/dist/src/events.js +24 -3
  26. package/dist/src/icons.js +6 -0
  27. package/dist/src/loader.js +12 -6
  28. package/dist/src/pages/blocks.js +1 -0
  29. package/dist/src/pages/index.js +3 -2
  30. package/dist/src/pages/markdown.js +107 -4
  31. package/dist/src/pages/render.js +63 -9
  32. package/dist/src/server.js +37 -12
  33. package/dist/src/status.js +38 -10
  34. package/package.json +1 -1
  35. package/plugins/chat/README.md +2 -1
  36. package/plugins/chat/client.tsx +15 -3
  37. package/plugins/chat/index.ts +1 -1
  38. package/plugins/chat/style.css +7 -0
  39. package/plugins/code/diff.ts +7 -1
  40. package/plugins/comments/client.ts +50 -6
  41. package/plugins/comments/index.ts +4 -2
  42. package/plugins/comments/style.css +8 -0
  43. package/plugins/forge/README.md +12 -0
  44. package/plugins/forge/index.ts +71 -0
  45. package/plugins/iframe/README.md +18 -0
  46. package/plugins/iframe/client.ts +46 -0
  47. package/plugins/iframe/index.ts +54 -0
  48. package/plugins/iframe/style.css +29 -0
  49. package/plugins/index.ts +3 -1
  50. package/plugins/mermaid/index.ts +1 -0
  51. package/skills/whiteboard/SKILL.md +17 -7
  52. package/solid/index.tsx +3 -0
  53. package/src/client/forms.ts +5 -6
  54. package/src/client/markdown.ts +36 -0
  55. package/src/client/page/base.css +33 -12
  56. package/src/client/page/elsewhere.ts +70 -0
  57. package/src/client/page/live.ts +30 -0
  58. package/src/client/page/main.ts +31 -6
  59. package/src/client/page/sort.ts +38 -0
  60. package/src/client/page/waiting.ts +102 -29
  61. package/src/client/read.ts +73 -0
  62. package/src/client/runtime.ts +13 -0
  63. package/src/client/toast.ts +25 -0
  64. package/src/define.ts +79 -13
  65. package/src/events.ts +27 -3
  66. package/src/icons.ts +8 -0
  67. package/src/loader.ts +7 -4
  68. package/src/pages/blocks.ts +3 -0
  69. package/src/pages/index.ts +8 -2
  70. package/src/pages/markdown.ts +92 -4
  71. package/src/pages/render.ts +49 -12
  72. package/src/server.ts +35 -12
  73. package/src/status.ts +64 -20
package/src/events.ts CHANGED
@@ -154,6 +154,13 @@ export interface HandOutOptions {
154
154
  interval?: number
155
155
  /** stops following */
156
156
  signal?: AbortSignal
157
+ /**
158
+ * Leave an event for now (the fallback: another listener would take it). A left event is looked
159
+ * at again each time `recheck` calls back, and handed out then if nobody picked it up meanwhile
160
+ * and it is no longer left.
161
+ */
162
+ skip?: (event: WbEvent) => boolean
163
+ recheck?: (again: () => void) => void
157
164
  }
158
165
 
159
166
  /**
@@ -168,7 +175,7 @@ export interface HandOutOptions {
168
175
  * `follow`, or when `signal` aborts.
169
176
  */
170
177
  export function handOut(file: string, filter: EventFilter, onEvent: (event: WbEvent) => void, options: HandOutOptions = {}): Promise<number> {
171
- const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent() } = options
178
+ const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent(), skip, recheck } = options
172
179
  return new Promise(resolve => {
173
180
  let got = 0
174
181
  let stop = () => {}
@@ -181,14 +188,31 @@ export function handOut(file: string, filter: EventFilter, onEvent: (event: WbEv
181
188
  pick(file, e)
182
189
  return ++got < count
183
190
  }
191
+ // the events left for now (skip), by id
192
+ const left = new Map<string, WbEvent>()
193
+ // false once enough were handed out; a left event is kept to look at again
194
+ const offer = (e: WbEvent) => {
195
+ if (skip?.(e)) { left.set(e.id, e); return true }
196
+ return hand(e)
197
+ }
184
198
  if (count <= 0 || signal?.aborted) return finish()
185
199
  const { events, end } = read(file)
186
200
  const picked = pickedUp(events)
187
201
  for (const e of events) {
188
- if (wanted(e) && !picked.has(e.id) && !hand(e)) return finish()
202
+ if (wanted(e) && !picked.has(e.id) && !offer(e)) return finish()
189
203
  }
190
204
  if (!following) return finish()
191
205
  signal?.addEventListener('abort', finish)
192
- stop = follow(file, end, e => { if (got < count && wanted(e) && !hand(e)) finish() }, { interval })
206
+ recheck?.(() => {
207
+ if (!left.size || got >= count) return
208
+ const picked = pickedUp(read(file).events)
209
+ for (const [id, e] of left) {
210
+ if (picked.has(id)) { left.delete(id); continue }
211
+ if (skip?.(e)) continue
212
+ left.delete(id)
213
+ if (!hand(e)) return finish()
214
+ }
215
+ })
216
+ stop = follow(file, end, e => { if (got < count && wanted(e) && !offer(e)) finish() }, { interval })
193
217
  })
194
218
  }
package/src/icons.ts ADDED
@@ -0,0 +1,8 @@
1
+ // Icons the page and the server both draw, as SVG markup. No Node in it: the browser runtime
2
+ // imports it too.
3
+
4
+ /** An inbox: what awaits the reader (the header's menu, the overview). */
5
+ export const INBOX_ICON = '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path d="M2 9.5 3.8 3.2A1 1 0 0 1 4.8 2.5h6.4a1 1 0 0 1 1 .7L14 9.5V13a.5.5 0 0 1-.5.5h-11A.5.5 0 0 1 2 13Zm0 0h3.5l1 1.5h3l1-1.5H14" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/></svg>'
6
+
7
+ /** "Awaiting you: 2 things", and where: what the inbox says to a reader who hovers it. */
8
+ export const awaitingLabel = (n: number, where = '') => `Awaiting you: ${n === 1 ? '1 question or message' : `${n} questions and messages`}${where}`
package/src/loader.ts CHANGED
@@ -18,6 +18,8 @@ export interface LoadedConfig {
18
18
  plugins: Plugin[]
19
19
  /** the plugins' event types declared `handOut: true`: those that reach an agent unasked */
20
20
  handedOut: Set<string>
21
+ /** the plugins' event types declared `forReader: true`: from the agent, a message for the reader */
22
+ forReader: Set<string>
21
23
  files: boolean
22
24
  errors: unknown[]
23
25
  }
@@ -92,15 +94,16 @@ export function createConfigLoader(proj: Project, { pages: withPages = true } =
92
94
  }
93
95
  const blocks = plugins.flatMap(p => Object.entries(p.blocks ?? {}).map(([name, block]) => ({ name, block, plugin: p.name })))
94
96
  const styles = plugins.map(p => p.style).filter((s): s is URL | string => !!s)
95
- const pages = withPages ? createPages({ blocks, style: config?.style, styles }) : null
96
- const handedOut = new Set(plugins.flatMap(p => Object.entries(p.events ?? {}).filter(([, spec]) => spec?.handOut).map(([type]) => type)))
97
- return { pages, plugins, handedOut, files: config?.files !== false }
97
+ const links = plugins.flatMap(p => p.links ? [p.links.bind(p)] : [])
98
+ const pages = withPages ? createPages({ blocks, style: config?.style, styles, links }) : null
99
+ const declared = (flag: 'handOut' | 'forReader') => new Set(plugins.flatMap(p => Object.entries(p.events ?? {}).filter(([, spec]) => spec?.[flag]).map(([type]) => type)))
100
+ return { pages, plugins, handedOut: declared('handOut'), forReader: declared('forReader'), files: config?.files !== false }
98
101
  }
99
102
 
100
103
  function config(): Promise<LoadedConfig> {
101
104
  cached ??= load().then(
102
105
  value => ({ ...value, errors: [] }),
103
- error => ({ pages: null, plugins: [], handedOut: new Set<string>(), files: false, errors: [error] }),
106
+ error => ({ pages: null, plugins: [], handedOut: new Set<string>(), forReader: new Set<string>(), files: false, errors: [error] }),
104
107
  )
105
108
  return cached
106
109
  }
@@ -15,6 +15,8 @@ export interface ResolvedBlock {
15
15
  name: string
16
16
  /** the block for code in general (`fence: 'any'`) */
17
17
  code: boolean
18
+ /** it renders the code fences of its name (`fence: true` or `'any'`) */
19
+ fences: boolean
18
20
  props: ((ctx: any) => unknown) | null
19
21
  html: ((ctx: any) => string | Html | null | Promise<string | Html | null>) | null
20
22
  client: string | null
@@ -43,6 +45,7 @@ function normalize({ name, block: b, plugin }: BlockEntry): ResolvedBlock {
43
45
  return {
44
46
  name,
45
47
  code: b.fence === 'any',
48
+ fences: b.fence === true || b.fence === 'any',
46
49
  props: typeof b.props === 'function' ? b.props.bind(b) : null,
47
50
  html: typeof b.html === 'function' ? b.html.bind(b) : null,
48
51
  ...files,
@@ -2,9 +2,10 @@
2
2
  // project's plugins bring (`:::name`, `::name`, `:name`, ```` ```name ````). The loader makes one per
3
3
  // loaded config (see loader.ts); the server renders with it.
4
4
  import { resolveBlocks, type BlockEntry } from './blocks.ts'
5
- import { createDocs, createRender } from './render.ts'
5
+ import { createDocs, createMessageRender, createRender } from './render.ts'
6
6
  import { formNames } from './markdown.ts'
7
7
  import type { PageSource, RenderContext, Rendered, StoredPage } from '../define.ts'
8
+ import type { TextLink } from '../define.ts'
8
9
 
9
10
  export interface PagesOptions {
10
11
  /** the blocks of the project's plugins, in plugin order */
@@ -13,6 +14,8 @@ export interface PagesOptions {
13
14
  style?: URL | string
14
15
  /** the plugins' stylesheets, linked on every page */
15
16
  styles?: (URL | string)[]
17
+ /** the plugins' text links (Plugin.links), each asked once per project folder */
18
+ links?: ((ctx: { dir: string }) => TextLink[])[]
16
19
  }
17
20
 
18
21
  /** How the core renders pages for one loaded config. */
@@ -23,13 +26,16 @@ export interface Pages {
23
26
  docs(ctx: RenderContext): string
24
27
  /** the questions a page asks: its named forms, whose answers are events of their name */
25
28
  questions(page: PageSource): string[]
29
+ /** a message's markdown (a comment, a chat message) as HTML, and the stylesheets it needs */
30
+ message(text: string, ctx: RenderContext): Promise<{ html: string; styles: string[] }>
26
31
  }
27
32
 
28
33
  export function createPages(options: PagesOptions): Pages {
29
34
  const resolved = resolveBlocks(options.blocks)
30
35
  const blocks = () => resolved
31
36
  return {
32
- render: createRender(blocks, options.style, options.styles ?? []),
37
+ render: createRender(blocks, options.style, options.styles ?? [], options.links ?? []),
38
+ message: createMessageRender(blocks, options.links ?? []),
33
39
  docs: createDocs(blocks),
34
40
  questions: page => formNames(page.source),
35
41
  }
@@ -16,6 +16,7 @@ import { toString } from 'mdast-util-to-string'
16
16
  import { html, raw, type Html } from '../html.ts'
17
17
  import { isQuestionName } from '../status.ts'
18
18
  import type { ResolvedBlock } from './blocks.ts'
19
+ import type { TextLink } from '../define.ts'
19
20
 
20
21
  /**
21
22
  * An mdast node, loosely: the pipeline hands nodes between remark, the directive plugin and
@@ -31,6 +32,44 @@ export interface MdNode {
31
32
  type LinkFor = (absolutePath: string) => string | null
32
33
 
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
+ }
34
73
  const toHast = unified().use(remarkRehype, { allowDangerousHtml: true }).use(rehypeStringify, { allowDangerousHtml: true }).freeze()
35
74
 
36
75
  /** `cols=3 open title="a b"` → { cols: '3', open: '', title: 'a b' } (bare words get '' like directive attrs) */
@@ -52,6 +91,43 @@ const SCHEME = /^[a-z][a-z0-9+.-]*:/i
52
91
  * file's own folder and handed to `linkFor(absolutePath)`, which returns the URL that serves it
53
92
  * (or null to leave the link as written).
54
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
+
55
131
  function rewriteLinks(tree: MdNode, file: string, linkFor?: LinkFor) {
56
132
  if (!linkFor || !file) return
57
133
  const walk = (node: MdNode) => {
@@ -90,7 +166,7 @@ function literalDirective(node: MdNode, label: MdNode[] | null) {
90
166
  * code block doesn't count.
91
167
  */
92
168
  export function formNames(source: string) {
93
- const tree = parser.parse(String(source ?? '').replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '')) as MdNode
169
+ const tree = parseMarkdown(String(source ?? '').replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, ''))
94
170
  const names: string[] = []
95
171
  const walk = (node: MdNode) => {
96
172
  if (node.type === 'containerDirective' && node.name === 'form') {
@@ -118,6 +194,13 @@ export interface RenderOptions {
118
194
  code?: ResolvedBlock | null
119
195
  /** the URL that serves a file on disk, for relative links */
120
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
121
204
  }
122
205
 
123
206
  export interface Island { block: string; client: string; props: unknown }
@@ -127,7 +210,7 @@ export interface Island { block: string; client: string; props: unknown }
127
210
  * blocks. Returns the page's HTML, its first heading, the islands to mount and the blocks'
128
211
  * stylesheets.
129
212
  */
130
- export async function renderMarkdown(source: string | MdNode, { page, file, resolve, code = null, linkFor }: RenderOptions) {
213
+ export async function renderMarkdown(source: string | MdNode, { page, file, resolve, code = null, linkFor, textLinks = [], message = false }: RenderOptions) {
131
214
  let nextId = 0
132
215
  const islands: Record<string, Island> = {}
133
216
  const keyCount: Record<string, number> = {}
@@ -198,8 +281,10 @@ export async function renderMarkdown(source: string | MdNode, { page, file, reso
198
281
  }
199
282
 
200
283
  const parse = (src: string) => {
201
- const tree = parser.parse(String(src ?? '')) as MdNode
284
+ const tree = parseMarkdown(String(src ?? ''))
285
+ if (message) asText(tree)
202
286
  rewriteLinks(tree, file, linkFor)
287
+ linkText(tree, textLinks)
203
288
  return tree
204
289
  }
205
290
  const markdown = async (src: string) => toHtml(parse(src).children ?? [])
@@ -238,7 +323,10 @@ export async function renderMarkdown(source: string | MdNode, { page, file, reso
238
323
  async function fence(node: MdNode): Promise<MdNode> {
239
324
  const lang: string | null = node.lang || null
240
325
  const plain = async () => html`<pre><code${lang && html` class="language-${lang}"`}>${node.value}</code></pre>`
241
- const block = (lang && resolve(lang)) || code
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
242
330
  if (!block) return htmlNode(await plain())
243
331
  const name = code && block === code && lang !== code.name ? code.name : lang
244
332
  const attrs = parseAttrs(node.meta)
@@ -8,7 +8,8 @@ import { fileURLToPath } from 'node:url'
8
8
  import { execFileSync } from 'node:child_process'
9
9
  import { renderMarkdown, type Island, type MdNode } from './markdown.ts'
10
10
  import { html, raw, type Html } from '../html.ts'
11
- import type { RenderContext, Rendered, StoredPage } from '../define.ts'
11
+ import { INBOX_ICON, awaitingLabel } from '../icons.ts'
12
+ import type { RenderContext, Rendered, StoredPage, TextLink } from '../define.ts'
12
13
  import type { ResolvedBlock, ResolvedBlocks } from './blocks.ts'
13
14
 
14
15
  type PagesPage = Extract<StoredPage, { kind: 'pages' }>
@@ -28,7 +29,7 @@ const CODE_LANG: Record<string, string> = { js: 'javascript', mjs: 'javascript',
28
29
  const body = (source: string) => source.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '')
29
30
 
30
31
  /** A page's title: its first heading, else its name. */
31
- function titleOf(file: string, fallback: string) {
32
+ export function titleOf(file: string, fallback: string) {
32
33
  try {
33
34
  const h1 = /^#\s+(.+)$/m.exec(body(fs.readFileSync(file, 'utf8')))
34
35
  return h1 ? h1[1].replace(/[*_`]/g, '') : fallback
@@ -43,9 +44,9 @@ function crumbs(id: string, name: string) {
43
44
  const time = (ts: number) => html`<time data-ts="${ts}"></time>`
44
45
 
45
46
  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>`
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>`
49
50
  }
50
51
 
51
52
  /** The folder's README, when it has one. */
@@ -95,24 +96,60 @@ function documentsIn(dir: string) {
95
96
  return [...new Set(files)].sort((a, b) => depth(a) - depth(b) || a.localeCompare(b))
96
97
  }
97
98
 
98
- /** The overview's list of the project's documents: each by its title, linked to its rendered page. */
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
+ */
99
104
  function documentList(ctx: RenderContext) {
100
105
  const files = documentsIn(ctx.project.dir)
101
106
  if (!files.length) return ''
102
- const rows = files.map(f => {
107
+ const rows = files.map((f, i) => {
103
108
  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>`
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>`
105
116
  })
106
117
  // 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>`
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
+ }
108
144
  }
109
145
 
110
- export function createRender(blocks: () => ResolvedBlocks, style?: URL | string, pluginStyles: (URL | string)[] = []) {
146
+ export function createRender(blocks: () => ResolvedBlocks, style?: URL | string, pluginStyles: (URL | string)[] = [], links: ((ctx: { dir: string }) => TextLink[])[] = []) {
147
+ const textLinks = textLinksOf(links)
111
148
  const STYLE = stylePath(style)
112
149
  const PLUGIN_STYLES = pluginStyles.map(stylePath).filter((f): f is string => !!f)
113
150
  async function markdown(source: string, page: string, file: string, ctx: RenderContext) {
114
151
  const { blocks: set, code } = blocks()
115
- return renderMarkdown(body(source), { page, file, resolve: name => set.get(name) ?? null, code, linkFor: ctx.urlFor })
152
+ return renderMarkdown(body(source), { page, file, resolve: name => set.get(name) ?? null, code, linkFor: ctx.urlFor, textLinks: textLinks(ctx.project.dir) })
116
153
  }
117
154
 
118
155
  async function content(page: StoredPage, ctx: RenderContext): Promise<Content> {
@@ -159,7 +196,7 @@ export function createRender(blocks: () => ResolvedBlocks, style?: URL | string,
159
196
  }
160
197
  const islands = Object.fromEntries(Object.entries(out.islands).map(([id, island]) => [id, { ...island, client: ctx.asset(island.client) }]))
161
198
  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>`
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>`
163
200
  // the page's own, the plugins' (every page), the blocks' on this page, then the project's
164
201
  const links = [ctx.asset(BASE_CSS), ...PLUGIN_STYLES.map(f => ctx.asset(f)), ...styles, ...(STYLE ? [ctx.asset(STYLE)] : [])]
165
202
  return {
package/src/server.ts CHANGED
@@ -25,7 +25,8 @@ import { createConfigLoader, pluginDir, toPath, type LoadedConfig } from './load
25
25
  import { describeRoutes, dispatch, pluginCommands, mountRoutes, usage, type MountedRoute } from './plugins.ts'
26
26
  import { createAuth } from './auth.ts'
27
27
  import { FROM_SOURCE, PACKAGE_DIR } from './package.ts'
28
- import { questionState } from './status.ts'
28
+ import { awaiting, covers, heard, questionState, unreadMessages } from './status.ts'
29
+ import { titleOf } from './pages/render.ts'
29
30
  import type { Listener, PageSource, PageStatus, Plugin, PluginHooks, Rendered, StoredPage, PagesSource } from './define.ts'
30
31
 
31
32
  const ENGINE_DIR = PACKAGE_DIR
@@ -113,6 +114,8 @@ export function createServer(project: Project): WhiteboardServer {
113
114
  head: Html[]
114
115
  body: Html[]
115
116
  clients: { name: string; client: string }[]
117
+ /** the event types that, from the agent, are messages for the reader (EventSpec.forReader) */
118
+ messages?: string[]
116
119
  notices?: string[]
117
120
  }
118
121
 
@@ -128,7 +131,8 @@ export function createServer(project: Project): WhiteboardServer {
128
131
  }))
129
132
  // their browser modules, which the runtime imports after the page's
130
133
  const clients = hooks.filter(h => h.client && !h.error).map(h => ({ name: h.name, client: asset(h.client!) }))
131
- return { head: parts.map(x => raw(String(x?.head ?? ''))), body: parts.map(x => raw(String(x?.body ?? ''))), clients, notices }
134
+ const messages = [...(await config()).forReader]
135
+ return { head: parts.map(x => raw(String(x?.head ?? ''))), body: parts.map(x => raw(String(x?.body ?? ''))), clients, messages, notices }
132
136
  }
133
137
 
134
138
  /** A page with what the plugins add, their notices among the page's. */
@@ -212,7 +216,7 @@ export function createServer(project: Project): WhiteboardServer {
212
216
  if (ent.isDirectory()) walk(full)
213
217
  else if (ent.name.endsWith('.md')) {
214
218
  const id = path.relative(project.pagesDir, full).split(path.sep).join('/').replace(/\.md$/, '')
215
- out.push({ id, file: full, mtime: fs.statSync(full).mtimeMs, lastEvent: last.get(id) ?? null, listeners: listenersFor(id).length })
219
+ out.push({ id, file: full, mtime: fs.statSync(full).mtimeMs, lastEvent: last.get(id) ?? null, awaiting: 0 })
216
220
  }
217
221
  }
218
222
  }
@@ -331,7 +335,7 @@ export function createServer(project: Project): WhiteboardServer {
331
335
  * hooks report. The questions are a page's named forms.
332
336
  */
333
337
  async function status(only: string | null): Promise<PageStatus[]> {
334
- const { pages, handedOut } = await config()
338
+ const { pages, handedOut, forReader } = await config()
335
339
  const isForAgent = forAgent(handedOut)
336
340
  const all = readEvents(project.eventsFile)
337
341
  const picked = pickedUp(all)
@@ -349,9 +353,10 @@ export function createServer(project: Project): WhiteboardServer {
349
353
  const questions = asks.map(name => ({ name, state: questionState(name, events, listening, id => picked.has(id)).state }))
350
354
  const named = (...states: string[]) => questions.filter(q => states.includes(q.state)).map(q => q.name)
351
355
  out.push({
352
- page: p.id, file: p.file, owner: owner.get(p.id) ?? null, asks, questions,
353
- open: named('waiting', 'unheard'),
354
- unheard: named('unheard'),
356
+ page: p.id, title: titleOf(p.file, path.basename(p.id)), file: p.file, owner: owner.get(p.id) ?? null, asks, questions,
357
+ open: named('open'),
358
+ unheard: named('open').filter(name => !heard(name, listening)),
359
+ unread: unreadMessages(events, type => forReader.has(type)),
355
360
  // the reader's events for an agent: a form's answers, and plugin events declared handOut
356
361
  unpicked: events.filter(e => fromReader(e) && isForAgent(e.type) && !picked.has(e.id)),
357
362
  listeners: listening,
@@ -380,10 +385,14 @@ export function createServer(project: Project): WhiteboardServer {
380
385
  // the page's corner (api.corner()): the one thing the core puts on every page, empty, for the
381
386
  // page's and the plugins' floating buttons; above what covers the bottom of the window
382
387
  const DOCK_STYLE = '#wb-dock{position:fixed;right:16px;bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:10;display:flex;flex-direction:column;align-items:flex-end;gap:6px}#wb-dock:empty{display:none}'
388
+ // toasts (api.toast), centred above the same edge; in the page's theme colours where it has them
389
+ + '#wb-toasts{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:30;display:grid;gap:8px;width:min(440px,100vw - 32px);pointer-events:none}'
390
+ + '.wb-toast{pointer-events:auto;cursor:pointer;padding:10px 14px;border-radius:8px;font:.85rem/1.45 var(--sans,system-ui,sans-serif);background:var(--bg,Canvas);color:var(--text,CanvasText);border:1px solid var(--border,#8884);box-shadow:0 8px 28px rgb(0 0 0/.18)}'
391
+ + '.wb-toast[data-kind=warn]{border-left:4px solid var(--warn,#c98a00)}.wb-toast[data-action]{border-left:4px solid var(--accent,#1d5bbf)}'
383
392
 
384
393
  /** `extras`: what plugins add to <head> and <body> (see shellExtras). */
385
394
  function shell(page: StoredPage, { page: rendered, out, notices }: Render, extras: Extras = { head: [], body: [], clients: [] }): string {
386
- const handoff = { id: page.id, kind: page.kind, client: rendered ? asset(PAGE_CLIENT) : null, data: out.data ?? null, plugins: extras.clients }
395
+ const handoff = { id: page.id, kind: page.kind, client: rendered ? asset(PAGE_CLIENT) : null, data: out.data ?? null, plugins: extras.clients, messages: extras.messages ?? [] }
387
396
  // the page's head and html are HTML already; the handoff is JSON made safe for a script tag
388
397
  return String(html`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
389
398
  <title>${out.title || page.id || project.name}</title>
@@ -405,10 +414,8 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
405
414
  /** A listener as the server holds it. */
406
415
  const listeners = new Set<Listener>()
407
416
 
408
- /** Does a listener's page filter cover `page`? An empty filter covers every page. */
409
- const covers = (l: Listener, page: string) => !l.page || page === l.page || page.startsWith(l.page + '/')
410
417
 
411
- const listenersFor = (page: string | null): Listener[] => [...listeners].filter(l => page == null || covers(l, page)).map(({ page, type, command }) => ({ page, type, command }))
418
+ const listenersFor = (page: string | null): Listener[] => [...listeners].filter(l => page == null || covers(l, page)).map(({ page, type, command, fallback }) => ({ page, type, command, ...(fallback && { fallback }) }))
412
419
 
413
420
  // ---- live changes ------------------------------------------------------------------------------
414
421
  // The browser listens at /api/watch. `change`: its page changed; `events`: the log grew;
@@ -543,6 +550,11 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
543
550
  if ('raw' in found) return found
544
551
  // a folder is served at /dir/, so relative links resolve inside it
545
552
  if ((found.kind === 'folder' || (found.kind === 'pages' && id)) && !requested.endsWith('/')) return { redirect: `/${id}/` }
553
+ // a list of pages says which await the reader: where their questions stand takes the config
554
+ if (found.kind === 'pages') {
555
+ const counts = new Map((await status(found.id || null)).map(s => [s.page, awaiting(s)]))
556
+ for (const p of found.pages) p.awaiting = counts.get(p.id) ?? 0
557
+ }
546
558
  return { page: found }
547
559
  }
548
560
 
@@ -574,6 +586,14 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
574
586
  if (!body.type) return sendJson(res, 400, { error: 'event type required' })
575
587
  return sendJson(res, 200, appendEvent(project.eventsFile, body))
576
588
  }
589
+ // messages (comments, chat) written in markdown, as HTML: { texts } → { html, styles }
590
+ if (p === '/api/markdown' && req.method === 'POST') {
591
+ const { texts } = JSON.parse(await readBody(req)) as { texts?: unknown }
592
+ if (!Array.isArray(texts)) return sendJson(res, 400, { error: 'texts: an array of strings' })
593
+ const { pages } = await config()
594
+ const out = await Promise.all(texts.map(t => pages ? pages.message(String(t ?? ''), context()) : Promise.resolve({ html: String(html`${String(t ?? '')}`), styles: [] })))
595
+ return sendJson(res, 200, { html: out.map(o => o.html), styles: [...new Set(out.flatMap(o => o.styles))] })
596
+ }
577
597
  if (p === '/api/events') {
578
598
  const all = readEvents(project.eventsFile)
579
599
  const picked = pickedUp(all)
@@ -583,9 +603,12 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
583
603
  if (p === '/api/status') return sendJson(res, 200, await status(q.page || null))
584
604
  if (p === '/api/listeners') return sendJson(res, 200, listenersFor(q.page ?? null))
585
605
  if (p === '/api/listen') {
606
+ const fallback = 'fallback' in q
607
+ // one fallback per project: two would split what nobody else takes between them
608
+ if (fallback && [...listeners].some(l => l.fallback)) return sendJson(res, 409, { error: 'another agent is the fallback already' })
586
609
  res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
587
610
  res.write(': listening\n\n')
588
- const l: Listener = { page: q.page || '', type: q.type || null, command: q.command === 'wait' ? 'wait' : 'watch' }
611
+ const l: Listener = { page: q.page || '', type: q.type || null, command: q.command === 'wait' ? 'wait' : 'watch', ...(fallback && { fallback }) }
589
612
  listeners.add(l)
590
613
  notifyAll('listeners')
591
614
  const ping = setInterval(() => res.write(': ping\n\n'), 25000)