@bigmistqke/whiteboard 0.2.1 → 0.3.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 (45) hide show
  1. package/README.md +16 -10
  2. package/bin/whiteboard.ts +98 -4
  3. package/dist/bin/whiteboard.js +99 -3
  4. package/dist/client/runtime.js +118 -24
  5. package/dist/plugins/claude-code/index.js +14 -3
  6. package/dist/plugins/comments/client.js +3 -3
  7. package/dist/plugins/details/README.md +3 -1
  8. package/dist/plugins/form/README.md +6 -4
  9. package/dist/plugins/form/index.js +9 -1
  10. package/dist/plugins/form/style.css +3 -0
  11. package/dist/plugins/toc/README.md +10 -0
  12. package/dist/plugins/toc/client.js +1 -0
  13. package/dist/plugins/toc/index.js +17 -0
  14. package/dist/plugins/toc/style.css +19 -0
  15. package/dist/src/client/page/base.css +26 -22
  16. package/dist/src/client/page/main.js +227 -52
  17. package/dist/src/events.js +127 -9
  18. package/dist/src/loader.js +4 -0
  19. package/dist/src/server.js +25 -17
  20. package/package.json +6 -1
  21. package/plugins/claude-code/index.ts +16 -7
  22. package/plugins/comments/client.ts +30 -7
  23. package/plugins/details/README.md +3 -1
  24. package/plugins/form/README.md +6 -4
  25. package/plugins/form/index.ts +9 -1
  26. package/plugins/form/style.css +3 -0
  27. package/plugins/toc/README.md +10 -0
  28. package/plugins/toc/client.ts +130 -0
  29. package/plugins/toc/index.ts +25 -0
  30. package/plugins/toc/style.css +19 -0
  31. package/skills/whiteboard/SKILL.md +41 -9
  32. package/src/client/forms.ts +32 -1
  33. package/src/client/page/base.css +26 -22
  34. package/src/client/page/fresh.ts +18 -23
  35. package/src/client/page/hold.ts +37 -0
  36. package/src/client/page/main.ts +81 -6
  37. package/src/client/page/sticky.ts +45 -0
  38. package/src/client/page/waiting.ts +30 -27
  39. package/src/client/runtime.ts +8 -2
  40. package/src/client/scroll.ts +44 -0
  41. package/src/client/toast.ts +51 -21
  42. package/src/define.ts +17 -8
  43. package/src/events.ts +95 -7
  44. package/src/loader.ts +1 -1
  45. package/src/server.ts +28 -7
@@ -1,25 +1,55 @@
1
- // Toasts (api.toast): a short message at the bottom of the window, above what covers its bottom
2
- // (--wb-inset-bottom), for what the reader should know when it happens, wherever they are scrolled.
3
- // One goes after a few seconds, or on a click (a click runs `onClick` first). One with `ms: 0`
4
- // stays: a click only runs `onClick`, and whoever made it closes it, or changes its text, through
5
- // what toast() returns. Its look is the core's (server.ts), with the page's theme colours.
1
+ // Toasts (api.toast): short labels in the page's corner (api.corner(), above what covers the bottom
2
+ // of the window) that say what is going on and take the reader there: "→ unanswered (2)",
3
+ // "↓ new (3)", "Sent, but no agent is listening". One goes after a few seconds, or on a click; one
4
+ // with `ms: 0` stays until closed, and changes its text, or hides and shows again, through what
5
+ // toast() returns. A click runs `onClick` (and closes a toast that goes by itself); `onDismiss`
6
+ // adds a ✕ that runs it and closes the toast. Their look is the core's (server.ts), in the page's
7
+ // theme colours.
6
8
  import type { Toast, ToastOptions } from '../define.ts'
7
9
 
8
- const box = document.createElement('div')
9
- box.id = 'wb-toasts'
10
- box.setAttribute('role', 'status')
11
- box.setAttribute('aria-live', 'polite')
10
+ let box: HTMLElement | null = null
11
+ function place(corner: HTMLElement) {
12
+ if (box?.isConnected) return box
13
+ box = document.createElement('div')
14
+ box.className = 'wb-toasts'
15
+ box.setAttribute('role', 'status')
16
+ box.setAttribute('aria-live', 'polite')
17
+ corner.append(box)
18
+ return box
19
+ }
12
20
 
13
- export function toast(text: string, { kind = 'info', ms = 7000, onClick }: ToastOptions = {}): Toast {
14
- if (!box.isConnected) document.body.append(box)
15
- const el = document.createElement('div')
16
- el.className = 'wb-toast'
17
- el.dataset.kind = kind
18
- if (onClick) el.dataset.action = ''
19
- el.textContent = text
20
- const close = () => el.remove()
21
- el.addEventListener('click', () => { if (ms) close(); onClick?.() })
22
- if (ms) setTimeout(close, ms)
23
- box.append(el)
24
- return { close, update: next => { el.textContent = next } }
21
+ export function createToast(corner: () => HTMLElement) {
22
+ return function toast(text: string, { kind = 'info', ms = 7000, onClick, onDismiss, name, order = 0 }: ToastOptions = {}): Toast {
23
+ const el = document.createElement('button')
24
+ el.type = 'button'
25
+ el.className = 'wb-toast'
26
+ el.dataset.kind = kind
27
+ if (name) el.dataset.toast = name
28
+ el.style.order = String(order)
29
+ const label = document.createElement('span')
30
+ label.className = 'wb-toast-text'
31
+ label.textContent = text
32
+ el.append(label)
33
+ if (onDismiss) {
34
+ const x = document.createElement('span')
35
+ x.className = 'wb-toast-dismiss'
36
+ x.textContent = '✕'
37
+ x.title = x.ariaLabel = 'Dismiss'
38
+ el.append(x)
39
+ }
40
+ const close = () => el.remove()
41
+ el.addEventListener('click', e => {
42
+ if (onDismiss && (e.target as HTMLElement).closest('.wb-toast-dismiss')) { close(); onDismiss(); return }
43
+ if (ms) close()
44
+ onClick?.()
45
+ })
46
+ if (ms) setTimeout(close, ms)
47
+ place(corner()).append(el)
48
+ return {
49
+ close,
50
+ update: next => { label.textContent = next },
51
+ hide: () => { el.hidden = true },
52
+ show: () => { if (!el.isConnected) place(corner()).append(el); el.hidden = false },
53
+ }
54
+ }
25
55
  }
package/src/define.ts CHANGED
@@ -386,19 +386,28 @@ export interface Listener {
386
386
  fallback?: boolean
387
387
  }
388
388
 
389
- /** How a toast looks and acts: `warn` for something that may need the reader, how long it stays. */
389
+ /** How a toast looks and acts (Api.toast). */
390
390
  export interface ToastOptions {
391
- kind?: 'info' | 'warn'
391
+ /** its colour: `info` (the accent, the default), `warn`, or `alert` (as for what is new) */
392
+ kind?: 'info' | 'warn' | 'alert'
392
393
  /** milliseconds before it goes, 7000 by default; 0: it stays until closed through its `Toast` */
393
394
  ms?: number
394
- /** what a click on it does, besides closing it (a toast that stays, stays) */
395
+ /** what a click on it does (go to what it is about); a toast that goes by itself also closes */
395
396
  onClick?: () => void
397
+ /** gives it a ✕, which runs this and closes it */
398
+ onDismiss?: () => void
399
+ /** a name to find it by (`data-toast`), for its styles and for tests */
400
+ name?: string
401
+ /** where it is among the corner's toasts: lower first (default 0) */
402
+ order?: number
396
403
  }
397
404
 
398
- /** A toast on the screen: close it, or change what it says (a count that goes down). */
405
+ /** A toast on the screen: change what it says (a count), hide it and show it again, or close it. */
399
406
  export interface Toast {
400
407
  close(): void
401
408
  update(text: string): void
409
+ hide(): void
410
+ show(): void
402
411
  }
403
412
 
404
413
  /** What the core gives the page and every plugin in the browser. Framework-free: getters and subscriptions. */
@@ -452,10 +461,10 @@ export interface Api {
452
461
  /** the page's own title, behind the badges */
453
462
  title(title: string): void
454
463
  /**
455
- * A short message at the bottom of the window, for what the reader should know when it happens,
456
- * wherever they are scrolled: an answer nobody listens for, a reply in a thread. It goes after a
457
- * few seconds, or on a click, which runs `onClick` first (go to what it is about); with `ms: 0`
458
- * it stays until closed through what this returns.
464
+ * A short label in the page's corner that says what is going on and takes the reader there:
465
+ * what waits for them, what is new, an answer nobody listens for. It goes after a few seconds,
466
+ * or on a click, which runs `onClick` (go to what it is about); with `ms: 0` it stays, and what
467
+ * this returns changes its text, hides and shows it, or closes it.
459
468
  */
460
469
  toast(text: string, options?: ToastOptions): Toast
461
470
  /**
package/src/events.ts CHANGED
@@ -87,29 +87,117 @@ export function read(file: string): { events: WbEvent[]; end: number } {
87
87
  * Call `onEvent` for each event appended to the log from byte `from` on (a line boundary, such as
88
88
  * `read`'s `end`), in order, as whole lines arrive. Checks every `interval` ms (default 200).
89
89
  * Returns a function that stops it.
90
+ *
91
+ * The log can be rewritten under it (`prune`: a page closed, its events gone): a new file, or a
92
+ * shorter one. Then it reads the log again and goes on after the last event it had passed on (by
93
+ * time, and by id among those of the same time), so nothing is passed on twice.
90
94
  */
91
95
  export function follow(file: string, from: number, onEvent: (event: WbEvent) => void, { interval = 200 } = {}): () => void {
92
96
  let offset = from
93
97
  let partial = ''
98
+ let inode: number | null = null
99
+ try { inode = fs.statSync(file).ino } catch { /* not there yet */ }
100
+ // where it is in the log, to find its place again after a rewrite
101
+ let lastTs = ''
102
+ let atLastTs = new Set<string>()
103
+ // the events before `from` count as passed on: the place starts after the last of them
104
+ if (from > 0) {
105
+ let before: WbEvent[] = []
106
+ try { before = parseLines(fs.readFileSync(file).subarray(0, from).toString('utf8')) } catch { /* not there */ }
107
+ for (const e of before) {
108
+ if (e.ts > lastTs) { lastTs = e.ts; atLastTs = new Set() }
109
+ if (e.ts === lastTs) atLastTs.add(e.id)
110
+ }
111
+ }
112
+ const pass = (e: WbEvent) => {
113
+ if (e.ts > lastTs) { lastTs = e.ts; atLastTs = new Set() }
114
+ atLastTs.add(e.id)
115
+ onEvent(e)
116
+ }
94
117
  const poll = () => {
95
- let size: number
96
- try { size = fs.statSync(file).size } catch { return }
97
- if (size < offset) { offset = 0; partial = '' } // truncated
98
- if (size === offset) return
118
+ let stat: fs.Stats
119
+ try { stat = fs.statSync(file) } catch { return }
120
+ if ((inode != null && stat.ino !== inode) || stat.size < offset) {
121
+ // rewritten: read it again, and go on after the place reached
122
+ inode = stat.ino
123
+ const { events, end } = read(file)
124
+ offset = end
125
+ partial = ''
126
+ for (const e of events) if (e.ts > lastTs || (e.ts === lastTs && !atLastTs.has(e.id))) pass(e)
127
+ return
128
+ }
129
+ inode = stat.ino
130
+ if (stat.size === offset) return
99
131
  const fd = fs.openSync(file, 'r')
100
- const buf = Buffer.alloc(size - offset)
132
+ const buf = Buffer.alloc(stat.size - offset)
101
133
  fs.readSync(fd, buf, 0, buf.length, offset)
102
134
  fs.closeSync(fd)
103
- offset = size
135
+ offset = stat.size
104
136
  const text = partial + buf.toString('utf8')
105
137
  const cut = text.lastIndexOf('\n')
106
138
  partial = text.slice(cut + 1)
107
- for (const e of parseLines(text.slice(0, cut + 1))) onEvent(e)
139
+ for (const e of parseLines(text.slice(0, cut + 1))) pass(e)
108
140
  }
109
141
  const timer = setInterval(poll, interval)
110
142
  return () => clearInterval(timer)
111
143
  }
112
144
 
145
+ /**
146
+ * Rewrite the log, event by event: `change` returns the event to keep (as it is, or changed) or
147
+ * null to drop it. The log is written anew and put in place in one rename; when an event was
148
+ * appended while it was being written, it starts over, so none is lost. A follow running across it
149
+ * reads it again and goes on after the last event it passed on (see follow). Lines that aren't
150
+ * events are kept as they are. Returns how many were dropped and changed.
151
+ */
152
+ export function rewrite(file: string, change: (event: WbEvent) => WbEvent | null): { removed: number; changed: number } {
153
+ for (let attempt = 0; attempt < 10; attempt++) {
154
+ let buf: Buffer
155
+ try { buf = fs.readFileSync(file) } catch { return { removed: 0, changed: 0 } }
156
+ const keep: string[] = []
157
+ let removed = 0, changed = 0
158
+ for (const line of buf.toString('utf8').split('\n')) {
159
+ if (!line.trim()) continue
160
+ let ev: WbEvent | null = null
161
+ try { ev = JSON.parse(line) } catch { /* not an event: kept */ }
162
+ if (!ev) { keep.push(line); continue }
163
+ const next = change(ev)
164
+ if (!next) { removed++; continue }
165
+ const text = JSON.stringify(next)
166
+ if (text !== JSON.stringify(ev)) changed++
167
+ keep.push(next === ev ? line : text)
168
+ }
169
+ if (!removed && !changed) return { removed, changed }
170
+ const tmp = `${file}.${process.pid}.tmp`
171
+ fs.writeFileSync(tmp, keep.length ? keep.join('\n') + '\n' : '')
172
+ // appended to meanwhile: that event would be lost with the old file
173
+ if (fs.statSync(file).size !== buf.length) { fs.rmSync(tmp, { force: true }); continue }
174
+ fs.renameSync(tmp, file)
175
+ return { removed, changed }
176
+ }
177
+ throw new Error('the log kept changing while it was being rewritten; try again')
178
+ }
179
+
180
+ /** Remove a page's events from the log (`whiteboard close`, `whiteboard prune`): those of exactly
181
+ * that page, and of them only those `which` says (all by default). Returns how many. */
182
+ export function prune(file: string, page: string, which: (event: WbEvent) => boolean = () => true): number {
183
+ return rewrite(file, e => (e.page === page && which(e) ? null : e)).removed
184
+ }
185
+
186
+ /**
187
+ * Change an agent's event in place (`whiteboard edit`): `data` is merged into its data; its id, time
188
+ * and everything else stay, so what refers to it (a reply, a pick, a read) still does. Only an
189
+ * agent's own events (`from: cli`): what the reader sent stays as they sent it. Returns the event
190
+ * as it is now.
191
+ */
192
+ export function editEvent(file: string, id: string, data: Record<string, unknown>): WbEvent {
193
+ const found = readEvents(file).find(e => e.id === id)
194
+ if (!found) throw new Error(`no event ${id} in the log`)
195
+ if (fromReader(found)) throw new Error(`event ${id} is the reader's (${found.type}): what the reader sent stays as they sent it; an agent edits only its own`)
196
+ let edited: WbEvent | null = null
197
+ rewrite(file, e => (e.id === id ? (edited = { ...e, data: { ...e.data, ...data } }) : e))
198
+ return edited ?? found
199
+ }
200
+
113
201
  /** `page` matches the page itself and every page below it, unless `exact`. */
114
202
  export function matches(event: WbEvent, { page, type, exact }: EventFilter = {}): boolean {
115
203
  if (page && event.page !== page && (exact || !event.page.startsWith(page + '/'))) return false
package/src/loader.ts CHANGED
@@ -26,7 +26,7 @@ export interface LoadedConfig {
26
26
 
27
27
  const NAME = /^[\w-]+$/
28
28
  /** The command line's own commands: a plugin can't be named like one, since its commands are `whiteboard <name>`. */
29
- export const BUILTIN_COMMANDS = new Set(['serve', 'init', 'root', 'new', 'show', 'url', 'docs', 'events', 'wait', 'watch', 'append', 'pick', 'status', 'skill', 'help'])
29
+ export const BUILTIN_COMMANDS = new Set(['serve', 'init', 'root', 'new', 'show', 'url', 'docs', 'events', 'wait', 'watch', 'append', 'pick', 'status', 'scroll', 'close', 'prune', 'edit', 'skill', 'help'])
30
30
  // folders in .whiteboard/ that are the core's or meant for the project's own plugins (a plugin's own
31
31
  // folder holds its data, ignored by git), and the built-in commands
32
32
  const RESERVED = new Set(['pages', 'plugins', ...BUILTIN_COMMANDS])
package/src/server.ts CHANGED
@@ -385,10 +385,13 @@ export function createServer(project: Project): WhiteboardServer {
385
385
  // the page's corner (api.corner()): the one thing the core puts on every page, empty, for the
386
386
  // page's and the plugins' floating buttons; above what covers the bottom of the window
387
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)}'
388
+ // toasts (api.toast): labels in the corner, in the page's theme colours where it has them
389
+ + '.wb-toasts{display:flex;flex-direction:column;align-items:flex-end;gap:6px}.wb-toasts:empty{display:none}'
390
+ + '.wb-toast{display:inline-flex;align-items:center;gap:8px;cursor:pointer;padding:5px 12px;border-radius:99px;font:600 .8rem/1.4 var(--sans,system-ui,sans-serif);background:var(--accent,#1d5bbf);color:var(--accent-text,#fff);border:1px solid transparent;box-shadow:0 2px 10px rgb(0 0 0/.18)}'
391
+ + '.wb-toast[hidden]{display:none}.wb-toast[data-kind=warn]{background:var(--warn,#6b4fc0)}.wb-toast[data-kind=alert]{background:var(--bad,#c4352b);color:#fff}'
392
+ // where an agent scrolled the page to, lit up a moment
393
+ + '@keyframes wb-flash{from{outline-color:var(--accent,#1d5bbf)}to{outline-color:transparent}}.wb-flash{outline:3px solid transparent;outline-offset:6px;border-radius:4px;animation:wb-flash 2s ease-out}'
394
+ + '.wb-toast-dismiss{margin-right:-4px;padding:0 4px;border-left:1px solid rgb(255 255 255/.35);opacity:.75}.wb-toast-dismiss:hover{opacity:1}'
392
395
 
393
396
  /** `extras`: what plugins add to <head> and <body> (see shellExtras). */
394
397
  function shell(page: StoredPage, { page: rendered, out, notices }: Render, extras: Extras = { head: [], body: [], clients: [] }): string {
@@ -420,7 +423,7 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
420
423
  // ---- live changes ------------------------------------------------------------------------------
421
424
  // The browser listens at /api/watch. `change`: its page changed; `events`: the log grew;
422
425
  // `listeners`: an agent started or stopped waiting; `style`: a stylesheet changed; `reload`:
423
- // browser code changed.
426
+ // browser code changed; `scroll`: an agent shows the reader a place on the page ({ to }).
424
427
 
425
428
  /** A browser following its page at /api/watch; `pending`: what it will be told in a moment. */
426
429
  interface WatchClient {
@@ -586,6 +589,19 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
586
589
  if (!body.type) return sendJson(res, 400, { error: 'event type required' })
587
590
  return sendJson(res, 200, appendEvent(project.eventsFile, body))
588
591
  }
592
+ // an agent shows the reader a place on a page: every tab with it open scrolls there
593
+ // ({ page, to }: a heading's text, a form's name or any text) → { tabs }
594
+ if (p === '/api/scroll' && req.method === 'POST') {
595
+ const { page: id, to } = JSON.parse(await readBody(req)) as { page?: unknown; to?: unknown }
596
+ if (typeof id !== 'string' || typeof to !== 'string' || !to.trim()) return sendJson(res, 400, { error: 'page and to required' })
597
+ let tabs = 0
598
+ for (const c of clients) {
599
+ if (c.isDir || (c.page !== id && c.page + '/index' !== id)) continue
600
+ c.res.write(`event: scroll\ndata: ${JSON.stringify({ to })}\n\n`)
601
+ tabs++
602
+ }
603
+ return sendJson(res, 200, { tabs })
604
+ }
589
605
  // messages (comments, chat) written in markdown, as HTML: { texts } → { html, styles }
590
606
  if (p === '/api/markdown' && req.method === 'POST') {
591
607
  const { texts } = JSON.parse(await readBody(req)) as { texts?: unknown }
@@ -643,8 +659,13 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
643
659
  if ('redirect' in r) { res.writeHead(302, { location: r.redirect + url.search }); res.end(); return }
644
660
  if ('raw' in r) return sendFile(res, r.raw)
645
661
  if ('notFound' in r) {
646
- const missing: PageSource = { kind: 'page', id, file: '', mtime: null, source: r.notFound, body: r.notFound, frontmatter: {} }
647
- return send(res, 404, await page(req, missing, { page: false, out: { title: 'Not found', html: html`<h1>Not found</h1><p>${r.notFound}</p>` }, notices: [] }))
662
+ // rendered as a page, with the page's styles and the plugins', and live: it becomes the page
663
+ // once the page is there. The message holds the path from the URL: escaped, so it shows as
664
+ // written and makes no markup or block
665
+ const said = r.notFound.replace(/[\\`*_[\]{}()<>#!:|~&-]/g, '\\$&')
666
+ const md = `# Not found\n\n${said}\n`
667
+ const missing: PageSource = { kind: 'page', id, file: '', mtime: null, source: md, body: md, frontmatter: {} }
668
+ return send(res, 404, await page(req, missing, await render(missing)))
648
669
  }
649
670
  return send(res, 200, await page(req, r.page, await render(r.page)))
650
671
  } catch (err) {