@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,492 @@
1
+ // Comments on a page's text, on every page. The reader selects a passage
2
+ // of the page's content (its <main>, else all of it), a "Comment" button appears next to it,
3
+ // and what they write goes into the page's log; the agent replies there too (`whiteboard append`),
4
+ // or edits the page. Threads stay until the reader closes them. In a code block, the reader can
5
+ // also comment on whole lines: a "+" beside the line, pressed, or dragged over several.
6
+ //
7
+ // Everything is an event on the page, its type named after the plugin:
8
+ // comments:new { quote, before, after, block, at?, text } the event's id is the thread's id
9
+ // comments:reply { replyTo, text } from the reader, or from the command line
10
+ // comments:resolve { replyTo } the reader closed the thread
11
+ //
12
+ // A block can say where its parts are from with `data-wb-at` (a diff's lines: `src/a.ts:12`); a
13
+ // comment records those of the passage as `at` (the first, and the last when it differs), so the
14
+ // agent knows what it is about.
15
+ //
16
+ // Passages are found again by their quote and the text around it, so they survive edits elsewhere
17
+ // on the page, and highlighted with the CSS Highlight API: the page's own markup is never touched,
18
+ // so updates and new-content marks don't see comments at all.
19
+ import type { Api, PluginMount, PageHandle, WbEvent } from '../../src/define'
20
+ import { html, raw } from '../../src/html.ts'
21
+
22
+ const NEW = 'comments:new', REPLY = 'comments:reply', RESOLVE = 'comments:resolve'
23
+
24
+ interface Thread {
25
+ id: string
26
+ comment: WbEvent
27
+ replies: WbEvent[]
28
+ range: Range | null
29
+ }
30
+
31
+ const CONTEXT = 32
32
+
33
+ let root: HTMLElement
34
+ let api: Api
35
+ // the page's content: its <main> when it has one. Looked up afresh, since a live update may replace it
36
+ let main: HTMLElement
37
+ let threads: Thread[] = []
38
+ let openThread: string | null = null
39
+
40
+ const layer = document.createElement('div')
41
+ layer.className = 'wb-comments'
42
+
43
+ const startButton = document.createElement('button')
44
+ startButton.type = 'button'
45
+ startButton.className = 'wb-comment-start'
46
+ startButton.textContent = 'Comment'
47
+ startButton.hidden = true
48
+
49
+ const popover = document.createElement('div')
50
+ popover.className = 'wb-thread'
51
+ popover.hidden = true
52
+
53
+ // ---- the page's text ---------------------------------------------------------------------------
54
+
55
+ /** The text of the page's content as one string, with where each text node starts in it. */
56
+ function textIndex() {
57
+ const nodes: { node: Text; start: number }[] = []
58
+ let text = ''
59
+ const walker = document.createTreeWalker(main, NodeFilter.SHOW_TEXT, {
60
+ acceptNode: n => (n.parentElement?.closest('script, style, textarea') ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT),
61
+ })
62
+ for (let n = walker.nextNode() as Text | null; n; n = walker.nextNode() as Text | null) {
63
+ nodes.push({ node: n, start: text.length })
64
+ text += n.data
65
+ }
66
+ return { text, nodes }
67
+ }
68
+
69
+ /** A position in the index → the text node and offset in it. */
70
+ function point(index: ReturnType<typeof textIndex>, at: number, end: boolean) {
71
+ for (let i = 0; i < index.nodes.length; i++) {
72
+ const { node, start } = index.nodes[i]
73
+ const stop = start + node.data.length
74
+ if (at < stop || (end && at === stop) || i === index.nodes.length - 1) return { node, offset: Math.min(Math.max(at - start, 0), node.data.length) }
75
+ }
76
+ return null
77
+ }
78
+
79
+ /** Where a range starts and ends in the index. */
80
+ function offsetsOf(index: ReturnType<typeof textIndex>, range: Range) {
81
+ const find = (container: Node, offset: number) => {
82
+ if (container.nodeType === Node.TEXT_NODE) {
83
+ const hit = index.nodes.find(n => n.node === container)
84
+ return hit ? hit.start + offset : null
85
+ }
86
+ // an element boundary: the end of the last text node before it
87
+ const prefix = document.createRange()
88
+ prefix.setStart(main, 0)
89
+ prefix.setEnd(container, offset)
90
+ let at = 0
91
+ for (const { node, start } of index.nodes) if (prefix.intersectsNode(node)) at = start + node.data.length
92
+ return at
93
+ }
94
+ const start = find(range.startContainer, range.startOffset)
95
+ const end = find(range.endContainer, range.endOffset)
96
+ return start == null || end == null ? null : { start, end }
97
+ }
98
+
99
+ /** The passage of a comment on the page as it is now: its quote, the occurrence whose surroundings match best. */
100
+ function locate(index: ReturnType<typeof textIndex>, data: Record<string, unknown>): Range | null {
101
+ const quote = String(data.quote ?? '')
102
+ if (!quote) return null
103
+ const before = String(data.before ?? ''), after = String(data.after ?? '')
104
+ let best = -1, bestScore = -1
105
+ for (let at = index.text.indexOf(quote); at >= 0; at = index.text.indexOf(quote, at + 1)) {
106
+ const b = index.text.slice(Math.max(0, at - before.length), at)
107
+ const a = index.text.slice(at + quote.length, at + quote.length + after.length)
108
+ let score = 0
109
+ while (score < b.length && b[b.length - 1 - score] === before[before.length - 1 - score]) score++
110
+ let s2 = 0
111
+ while (s2 < a.length && a[s2] === after[s2]) s2++
112
+ if (score + s2 > bestScore) { best = at; bestScore = score + s2 }
113
+ }
114
+ if (best < 0) return null
115
+ const s = point(index, best, false), e = point(index, best + quote.length, true)
116
+ if (!s || !e) return null
117
+ const range = document.createRange()
118
+ range.setStart(s.node, s.offset)
119
+ range.setEnd(e.node, e.offset)
120
+ return range
121
+ }
122
+
123
+ // ---- threads -----------------------------------------------------------------------------------
124
+
125
+ function collect(): Thread[] {
126
+ const events = api.events()
127
+ const resolved = new Set(events.filter(e => e.type === RESOLVE).map(e => String(e.data.replyTo)))
128
+ const index = textIndex()
129
+ return events
130
+ .filter(e => e.type === NEW && !resolved.has(e.id))
131
+ .map(comment => ({
132
+ id: comment.id,
133
+ comment,
134
+ replies: events.filter(e => e.type === REPLY && e.data.replyTo === comment.id),
135
+ range: locate(index, comment.data),
136
+ }))
137
+ }
138
+
139
+ const lastFromAgent = (t: Thread) => t.replies.at(-1)?.from === 'cli'
140
+
141
+ /** Highlight every open thread's passage, and put its badge in the margin beside it. */
142
+ function draw() {
143
+ const highlights = (CSS as unknown as { highlights?: Map<string, unknown> }).highlights
144
+ const HighlightCtor = (window as unknown as { Highlight?: new (...r: Range[]) => unknown }).Highlight
145
+ if (highlights && HighlightCtor) {
146
+ highlights.set('wb-comment', new HighlightCtor(...threads.filter(t => t.range && t.id !== openThread).map(t => t.range!)))
147
+ const active = threads.find(t => t.id === openThread)?.range
148
+ if (active) highlights.set('wb-comment-active', new HighlightCtor(active))
149
+ else highlights.delete('wb-comment-active')
150
+ }
151
+ const column = main.getBoundingClientRect()
152
+ const unreadIds = new Set(api.unread().map(e => e.id))
153
+ layer.replaceChildren(...threads.map((t, i) => {
154
+ const badge = document.createElement('button')
155
+ badge.type = 'button'
156
+ badge.className = 'wb-comment-badge'
157
+ badge.dataset.thread = t.id
158
+ badge.toggleAttribute('data-agent', lastFromAgent(t))
159
+ // the replies it holds, for the page to find an unread one here (data-wb-holds, see the page)
160
+ badge.dataset.wbHolds = t.replies.map(r => r.id).join(' ')
161
+ const unread = t.replies.some(r => unreadIds.has(r.id))
162
+ badge.toggleAttribute('data-unread', unread)
163
+ badge.title = unread ? 'the agent replied: unread' : lastFromAgent(t) ? 'the agent replied' : 'comment'
164
+ badge.textContent = String(1 + t.replies.length)
165
+ const rect = t.range?.getClientRects()[0]
166
+ // a passage that is gone from the page: its badge waits at the top, still open until closed
167
+ const top = rect ? rect.top + scrollY : column.top + scrollY + i * 30
168
+ const left = Math.min(column.right + 8 + scrollX, document.documentElement.clientWidth - 36 + scrollX)
169
+ badge.style.top = `${top}px`
170
+ badge.style.left = `${left}px`
171
+ if (!rect) badge.dataset.detached = ''
172
+ return badge
173
+ }))
174
+ if (openThread) placePopover()
175
+ }
176
+
177
+ /** Called after the page re-rendered, and whenever the log changed. */
178
+ function refreshComments() {
179
+ if (!root) return
180
+ main = root.querySelector('main') ?? root
181
+ threads = collect()
182
+ if (openThread && !threads.some(t => t.id === openThread)) closePopover()
183
+ else if (openThread) renderPopover()
184
+ draw()
185
+ }
186
+
187
+ // ---- the thread popover ------------------------------------------------------------------------
188
+
189
+ // messages as markdown, rendered by the server, by their text
190
+ const rendered = new Map<string, string>()
191
+
192
+ function renderPopover() {
193
+ const t = threads.find(x => x.id === openThread)
194
+ if (!t) return
195
+ const who = (e: WbEvent) => (e.from === 'cli' ? 'agent' : 'you')
196
+ // the quote and every message are text from the reader or the agent: `html` escapes them
197
+ // a message is markdown: as rendered, once the server has (api.markdown), as plain text till then
198
+ const message = (e: WbEvent) => {
199
+ const text = String(e.data.text ?? '')
200
+ const md = rendered.get(text)
201
+ return html`<div class="wb-thread-message" data-from="${who(e)}" data-wb-message="${e.id}"><span class="wb-thread-who">${who(e)}</span><div class="wb-thread-text"${md != null ? raw(' data-md') : ''}>${md != null ? raw(md) : text}</div></div>`
202
+ }
203
+ const draft = popover.querySelector('textarea')?.value ?? ''
204
+ popover.innerHTML = String(html`
205
+ <blockquote class="wb-thread-quote">${t.comment.data.quote ?? ''}</blockquote>
206
+ ${t.comment.data.at && html`<p class="wb-thread-at">${t.comment.data.at}</p>`}
207
+ ${!t.range && html`<p class="wb-thread-detached">This passage is no longer on the page.</p>`}
208
+ ${[t.comment, ...t.replies].map(message)}
209
+ <form class="wb-thread-reply">
210
+ <textarea rows="2" placeholder="Reply (Shift+Enter for a new line)"></textarea>
211
+ <div class="wb-thread-actions"><button type="submit" class="wb-comment-button wb-comment-primary">Reply</button><button type="button" class="wb-comment-button" data-close>Close thread</button></div>
212
+ </form>`)
213
+ popover.querySelector('textarea')!.value = draft
214
+ // the messages not rendered yet: their text only, put in place as each arrives (the rest of the
215
+ // thread, the reply being typed among it, stays as it is)
216
+ for (const e of [t.comment, ...t.replies]) {
217
+ const text = String(e.data.text ?? '')
218
+ if (rendered.has(text)) continue
219
+ api.markdown(text).then(md => {
220
+ rendered.set(text, md)
221
+ const el = popover.querySelector<HTMLElement>(`[data-wb-message="${CSS.escape(e.id)}"] .wb-thread-text`)
222
+ if (el && !el.hasAttribute('data-md')) { el.innerHTML = md; el.setAttribute('data-md', '') }
223
+ }, err => console.error('comments:', err))
224
+ }
225
+ }
226
+
227
+ function placePopover() {
228
+ const badge = layer.querySelector<HTMLElement>(`[data-thread="${openThread}"]`)
229
+ if (!badge) return
230
+ const top = parseFloat(badge.style.top) + 28
231
+ const width = Math.min(360, document.documentElement.clientWidth - 32)
232
+ const left = Math.max(16 + scrollX, Math.min(parseFloat(badge.style.left) + 28 - width, document.documentElement.clientWidth - width - 16 + scrollX))
233
+ popover.style.top = `${top}px`
234
+ popover.style.left = `${left}px`
235
+ popover.style.width = `${width}px`
236
+ }
237
+
238
+ function openPopover(id: string) {
239
+ openThread = id
240
+ popover.hidden = false
241
+ popover.querySelector('textarea')?.replaceWith(document.createElement('textarea'))
242
+ renderPopover()
243
+ draw()
244
+ popover.querySelector('textarea')?.focus({ preventScroll: true })
245
+ }
246
+
247
+ function closePopover() {
248
+ openThread = null
249
+ popover.hidden = true
250
+ draw()
251
+ }
252
+
253
+ // ---- starting a comment ------------------------------------------------------------------------
254
+
255
+ let pending: { quote: string; before: string; after: string; block: number; at?: string } | null = null
256
+
257
+ /** A selection inside the page's text (not in a form) → where the Comment button goes. */
258
+ function onSelection() {
259
+ main = root.querySelector('main') ?? root
260
+ const sel = getSelection()
261
+ if (!sel || sel.isCollapsed || !sel.rangeCount) { if (!startButton.matches(':focus')) startButton.hidden = true; return }
262
+ const range = sel.getRangeAt(0)
263
+ const inPage = (n: Node) => main.contains(n) && !(n instanceof Element ? n : n.parentElement)?.closest('form, input, textarea, select, button')
264
+ if (!inPage(range.startContainer) || !inPage(range.endContainer)) { startButton.hidden = true; return }
265
+ startButton.hidden = !prepare(range)
266
+ }
267
+
268
+ /**
269
+ * What a comment on `range` records (`pending`), and the Comment button put under its end. False
270
+ * when there is nothing to comment on.
271
+ */
272
+ function prepare(range: Range): boolean {
273
+ const quote = range.toString().trim()
274
+ if (!quote) return false
275
+ const index = textIndex()
276
+ const at = offsetsOf(index, range)
277
+ if (!at) return false
278
+ // the quote as it appears in the page's text, trimmed of the whitespace the selection had around it
279
+ const start = index.text.indexOf(quote, at.start)
280
+ const s = start >= 0 && start <= at.end ? start : at.start
281
+ let block: Element | null = (range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement)
282
+ while (block && block.parentElement !== main) block = block.parentElement
283
+ pending = {
284
+ quote,
285
+ before: index.text.slice(Math.max(0, s - CONTEXT), s),
286
+ after: index.text.slice(s + quote.length, s + quote.length + CONTEXT),
287
+ block: block ? [...main.children].indexOf(block) : -1,
288
+ }
289
+ // where the passage is from, when its block says (see the top of this file)
290
+ const places = [...main.querySelectorAll<HTMLElement>('[data-wb-at]')].filter(el => range.intersectsNode(el) && el.textContent).map(el => el.dataset.wbAt!)
291
+ if (places.length) pending.at = places.length > 1 && places.at(-1) !== places[0] ? `${places[0]} – ${places.at(-1)}` : places[0]
292
+ const rects = range.getClientRects()
293
+ const last = rects[rects.length - 1] ?? range.getBoundingClientRect()
294
+ startButton.style.top = `${last.bottom + scrollY + 6}px`
295
+ startButton.style.left = `${Math.min(last.right + scrollX - 40, document.documentElement.clientWidth - 110 + scrollX)}px`
296
+ return true
297
+ }
298
+
299
+ // ---- comments on lines of code -----------------------------------------------------------------
300
+
301
+ // A code block's lines (Shiki writes each as a .line): hovering one shows "+" at its left; pressing
302
+ // it comments on the line, dragging it down or up takes the lines it passes over.
303
+ const lineButton = document.createElement('button')
304
+ lineButton.type = 'button'
305
+ lineButton.className = 'wb-line-comment'
306
+ lineButton.textContent = '+'
307
+ lineButton.title = 'Comment on this line (drag for several)'
308
+ lineButton.hidden = true
309
+
310
+ let hovered: HTMLElement | null = null
311
+ let drag: { pre: HTMLElement; from: HTMLElement; to: HTMLElement } | null = null
312
+
313
+ const codeLine = (el: EventTarget | null) => {
314
+ const line = el instanceof Element ? el.closest<HTMLElement>('pre .line') : null
315
+ return line && main.contains(line) && !line.closest('form') ? line : null
316
+ }
317
+
318
+ /** The lines from `a` to `b`, either way round, as one range. */
319
+ function linesRange(a: HTMLElement, b: HTMLElement): Range {
320
+ const [first, last] = a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_PRECEDING ? [b, a] : [a, b]
321
+ const range = document.createRange()
322
+ range.setStart(first, 0)
323
+ range.setEnd(last, last.childNodes.length)
324
+ return range
325
+ }
326
+
327
+ function showLineButton(line: HTMLElement) {
328
+ hovered = line
329
+ const rect = line.getBoundingClientRect()
330
+ const pre = line.closest('pre')!.getBoundingClientRect()
331
+ lineButton.style.top = `${rect.top + scrollY + rect.height / 2 - 10}px`
332
+ lineButton.style.left = `${Math.max(scrollX + 2, pre.left + scrollX - 24)}px`
333
+ lineButton.hidden = false
334
+ }
335
+
336
+ function onLinePointer(e: MouseEvent) {
337
+ if (drag) {
338
+ // the line at the pointer's height, inside the block the drag started in
339
+ const pre = drag.pre.getBoundingClientRect()
340
+ const x = drag.from.getBoundingClientRect().left + 4
341
+ const line = codeLine(document.elementFromPoint(x, Math.min(Math.max(e.clientY, pre.top + 1), pre.bottom - 1)))
342
+ if (line && drag.pre.contains(line) && line !== drag.to) {
343
+ drag.to = line
344
+ const highlights = (CSS as unknown as { highlights?: Map<string, unknown> }).highlights
345
+ const HighlightCtor = (window as unknown as { Highlight?: new (...r: Range[]) => unknown }).Highlight
346
+ if (highlights && HighlightCtor) highlights.set('wb-comment-active', new HighlightCtor(linesRange(drag.from, drag.to)))
347
+ }
348
+ return
349
+ }
350
+ if (e.target === lineButton) return
351
+ const line = codeLine(e.target)
352
+ if (line) return showLineButton(line)
353
+ if (lineButton.hidden || !hovered) return
354
+ // on the way to the "+" (through the block's padding, or diagonally across other lines): the "+"
355
+ // is for the line at the pointer's height, as long as the pointer is between the "+" and the
356
+ // block's right edge
357
+ const pre = hovered.closest('pre')!
358
+ const box = pre.getBoundingClientRect()
359
+ const plus = lineButton.getBoundingClientRect()
360
+ const inside = e.clientX >= plus.left - 4 && e.clientX <= box.right && e.clientY >= box.top && e.clientY <= box.bottom
361
+ const atHeight = inside ? codeLine(document.elementFromPoint(hovered.getBoundingClientRect().left + 4, e.clientY)) : null
362
+ if (atHeight && pre.contains(atHeight)) showLineButton(atHeight)
363
+ else if (!inside || !(e.clientY >= plus.top - 4 && e.clientY <= plus.bottom + 4)) { lineButton.hidden = true; hovered = null }
364
+ }
365
+
366
+ const composer = document.createElement('form')
367
+ composer.className = 'wb-thread wb-comment-new'
368
+ composer.hidden = true
369
+ composer.innerHTML = String(html`<blockquote class="wb-thread-quote"></blockquote><textarea rows="3" placeholder="Your comment (Shift+Enter for a new line)"></textarea>
370
+ <div class="wb-thread-actions"><button type="submit" class="wb-comment-button wb-comment-primary">Comment</button><button type="button" class="wb-comment-button" data-cancel>Cancel</button></div>`)
371
+
372
+ function startComment() {
373
+ if (!pending) return
374
+ composer.querySelector('blockquote')!.textContent = pending.at ? `${pending.at}\n${pending.quote}` : pending.quote
375
+ composer.style.top = startButton.style.top
376
+ const width = Math.min(360, document.documentElement.clientWidth - 32)
377
+ composer.style.width = `${width}px`
378
+ composer.style.left = `${Math.max(16 + scrollX, Math.min(parseFloat(startButton.style.left), document.documentElement.clientWidth - width - 16 + scrollX))}px`
379
+ composer.hidden = false
380
+ startButton.hidden = true
381
+ composer.querySelector('textarea')!.focus({ preventScroll: true })
382
+ }
383
+
384
+ // ---- entry -------------------------------------------------------------------------------------
385
+
386
+ const mount: PluginMount = (el: HTMLElement, handle: PageHandle, core: Api) => {
387
+ // the overview and folders are lists, not text to comment on
388
+ if (handle.kind !== 'page' && handle.kind !== 'file') return
389
+ root = el
390
+ main = root.querySelector('main') ?? root
391
+ api = core
392
+ document.body.append(layer, startButton, lineButton, popover, composer)
393
+
394
+ document.addEventListener('mousemove', onLinePointer)
395
+ // the pointer left the page: no line is hovered any more (a drag keeps its lines until mouseup)
396
+ document.documentElement.addEventListener('mouseleave', () => {
397
+ if (drag) return
398
+ lineButton.hidden = true
399
+ hovered = null
400
+ })
401
+ lineButton.addEventListener('mousedown', e => {
402
+ if (!hovered || e.button !== 0) return
403
+ e.preventDefault()
404
+ const highlights = (CSS as unknown as { highlights?: Map<string, unknown> }).highlights
405
+ const HighlightCtor = (window as unknown as { Highlight?: new (...r: Range[]) => unknown }).Highlight
406
+ if (highlights && HighlightCtor) highlights.set('wb-comment-active', new HighlightCtor(linesRange(hovered, hovered)))
407
+ drag = { pre: hovered.closest('pre')!, from: hovered, to: hovered }
408
+ })
409
+ document.addEventListener('mouseup', () => {
410
+ if (!drag) return
411
+ const { from, to } = drag
412
+ drag = null
413
+ lineButton.hidden = true
414
+ if (prepare(linesRange(from, to))) startComment()
415
+ else draw()
416
+ })
417
+
418
+ let selTimer = 0
419
+ document.addEventListener('selectionchange', () => { clearTimeout(selTimer); selTimer = window.setTimeout(onSelection, 150) })
420
+ // keep the selection when the button is pressed
421
+ startButton.addEventListener('mousedown', e => e.preventDefault())
422
+ startButton.addEventListener('click', startComment)
423
+
424
+ // as in a chat: Enter sends the comment or reply, Shift+Enter starts a new line; not while an
425
+ // input method is composing
426
+ for (const form of [composer, popover] as HTMLElement[]) form.addEventListener('keydown', e => {
427
+ const box = e.target as HTMLElement
428
+ if (box.tagName !== 'TEXTAREA' || e.key !== 'Enter' || e.shiftKey || e.isComposing) return
429
+ e.preventDefault()
430
+ box.closest('form')?.requestSubmit()
431
+ })
432
+ composer.addEventListener('submit', async e => {
433
+ e.preventDefault()
434
+ const text = composer.querySelector('textarea')!.value.trim()
435
+ if (!text || !pending) return
436
+ const saved = await api.append(NEW, { ...pending, text })
437
+ composer.querySelector('textarea')!.value = ''
438
+ composer.hidden = true
439
+ pending = null
440
+ getSelection()?.removeAllRanges()
441
+ refreshComments()
442
+ openPopover(saved.id)
443
+ })
444
+ composer.querySelector('[data-cancel]')!.addEventListener('click', () => { composer.hidden = true; pending = null })
445
+
446
+ layer.addEventListener('click', e => {
447
+ const id = (e.target as HTMLElement).closest<HTMLElement>('[data-thread]')?.dataset.thread
448
+ if (id) (openThread === id ? closePopover() : openPopover(id))
449
+ })
450
+ popover.addEventListener('submit', async e => {
451
+ e.preventDefault()
452
+ const box = popover.querySelector('textarea')!
453
+ const text = box.value.trim()
454
+ if (!text || !openThread) return
455
+ await api.append(REPLY, { replyTo: openThread, text })
456
+ box.value = ''
457
+ refreshComments()
458
+ })
459
+ popover.addEventListener('click', async e => {
460
+ if (!(e.target as HTMLElement).closest('[data-close]') || !openThread) return
461
+ const id = openThread
462
+ closePopover()
463
+ // closed, the thread's replies ask nothing of the reader any more
464
+ api.markRead(threads.find(t => t.id === id)?.replies.map(r => r.id) ?? [])
465
+ await api.append(RESOLVE, { replyTo: id })
466
+ refreshComments()
467
+ })
468
+ // the page goes to an unread reply here: open its thread
469
+ layer.addEventListener('wb-reveal', e => {
470
+ const id = (e.target as HTMLElement).closest<HTMLElement>('[data-thread]')?.dataset.thread
471
+ if (id && openThread !== id) openPopover(id)
472
+ })
473
+ // a double-click outside the open thread closes it (a single click selects, to comment)
474
+ document.addEventListener('dblclick', e => {
475
+ const target = e.target as Node
476
+ if (!openThread || popover.contains(target) || layer.contains(target)) return
477
+ closePopover()
478
+ })
479
+ document.addEventListener('keydown', e => {
480
+ if (e.key !== 'Escape') return
481
+ if (!composer.hidden) { composer.hidden = true; pending = null }
482
+ else if (openThread) closePopover()
483
+ })
484
+
485
+ api.onEvents(refreshComments)
486
+ api.onRendered(refreshComments)
487
+ new ResizeObserver(() => draw()).observe(root)
488
+ addEventListener('resize', () => draw())
489
+ refreshComments()
490
+ }
491
+
492
+ export default mount
@@ -0,0 +1,54 @@
1
+ // Comments, as a whiteboard plugin: on every page the reader selects a passage and comments on it,
2
+ // and the agent replies in the thread or edits the page. Built in: every project has it.
3
+ //
4
+ // A thread is events on the page (see client.ts), so the server has nothing to do but serve the
5
+ // browser module and the styles, and tell agents how to answer (`whiteboard docs`).
6
+ import { packagePath } from '../../src/package.ts'
7
+ import type { Plugin } from '../../src/define.ts'
8
+
9
+ const CLIENT = packagePath('dist/plugins/comments/client.js')
10
+ const STYLE = packagePath('dist/plugins/comments/style.css')
11
+
12
+ const DOCS = `## Comments
13
+
14
+ The reader can select text on any page and comment on it, or comment on
15
+ whole lines of a code block (a "+" beside each line; dragging it takes
16
+ several). Each comment comes to you as an event on the page, like a form
17
+ answer:
18
+
19
+ \`\`\`json
20
+ {"id":"…","page":"plan","type":"comments:new","data":{"quote":"the selected text","before":"…","after":"…","block":3,"text":"their comment"}}
21
+ \`\`\`
22
+
23
+ On lines that say where they are from, \`data.at\` says it too: in a
24
+ \`diff\` fence, \`"src/a.ts:12"\` (a line of the new file), \`"src/a.ts (old):9"\`
25
+ (a removed line), or \`"src/a.ts:12 – src/a.ts:15"\` for several. Any block
26
+ can say where its parts are from with a \`data-wb-at\` attribute.
27
+
28
+ Replies to a thread come as \`comments:reply\` (\`data.replyTo\` is the comment's
29
+ id), and \`comments:resolve\` when the reader closed it. A thread stays on the
30
+ page until the reader closes it. Answer a comment the way it asks:
31
+
32
+ - **It asks for a change:** edit the page. The thread stays, so say what you
33
+ changed in a reply if it is not obvious.
34
+ - **It asks a question:** reply in the thread:
35
+ \`whiteboard append --page <file> --type comments:reply --data '{"replyTo":"<comment id>","text":"…"}'\`
36
+
37
+ Your replies show as the agent's, and \`wait\` and \`watch\` skip what you
38
+ append, so you don't hear your own replies. Comments and replies are
39
+ markdown: code in backticks or fences, lists, links, \`#12\`; raw HTML and
40
+ blocks (\`:::…\`, \`:button\`) show as written.`
41
+
42
+ export default function comments(): Plugin {
43
+ return {
44
+ name: 'comments',
45
+ docs: () => DOCS,
46
+ events: {
47
+ 'comments:new': { handOut: true, description: 'a comment on a passage or lines of code: `{ quote, before, after, block, at?, text }`; its id is the thread\'s' },
48
+ 'comments:reply': { handOut: true, forReader: true, description: 'a reply in a thread: `{ replyTo, text }`' },
49
+ 'comments:resolve': { description: 'the reader closed a thread: `{ replyTo }`' },
50
+ },
51
+ style: STYLE,
52
+ setup: () => ({ client: CLIENT }),
53
+ }
54
+ }
@@ -0,0 +1,40 @@
1
+ /*
2
+ * Comments: highlights through the CSS Highlight API, badges and threads above the page. Colors
3
+ * and fonts come from the page's theme variables, else from
4
+ * the fallbacks here.
5
+ */
6
+ ::highlight(wb-comment) { background-color: color-mix(in srgb, var(--accent, #1d5bbf) 18%, transparent); }
7
+ ::highlight(wb-comment-active) { background-color: color-mix(in srgb, var(--accent, #1d5bbf) 34%, transparent); }
8
+ .wb-comment-start, .wb-comment-badge, .wb-thread { position: absolute; z-index: 20; font-family: var(--sans, sans-serif); }
9
+ .wb-comment-start[hidden], .wb-thread[hidden], .wb-line-comment[hidden] { display: none; }
10
+ .wb-comment-start { background: var(--accent, #1d5bbf); color: var(--accent-text, #fff); border-color: var(--accent, #1d5bbf); border-radius: 99px; font-size: .78rem; padding: 3px 10px; box-shadow: 0 2px 8px rgb(0 0 0 / .15); }
11
+ .wb-comment-badge { min-width: 24px; height: 24px; padding: 0 6px; border-radius: 12px 12px 12px 3px; font-size: .72rem; font-weight: 600; background: var(--bg, Canvas); color: var(--accent, #1d5bbf); border: 1px solid color-mix(in srgb, var(--accent, #1d5bbf) 50%, transparent); }
12
+ .wb-comment-badge[data-agent] { background: var(--accent, #1d5bbf); color: var(--accent-text, #fff); }
13
+ .wb-comment-badge[data-detached] { border-style: dashed; }
14
+ /* a reply the reader hasn't read: a dot on the badge until its thread is open and it is in view */
15
+ .wb-comment-badge[data-unread]::after { content: ''; position: absolute; top: -3px; right: -3px; width: 9px; height: 9px; border-radius: 50%; background: var(--bad, #c4352b); border: 2px solid var(--bg, Canvas); }
16
+ .wb-thread { background: var(--bg, Canvas); border: 1px solid var(--border, #e3e5e9); border-radius: 8px; padding: 12px 14px; box-shadow: 0 8px 28px rgb(0 0 0 / .16); display: grid; gap: 10px; font-size: .9rem; }
17
+ .wb-thread-quote { margin: 0; padding-left: 10px; border-left: 3px solid color-mix(in srgb, var(--accent, #1d5bbf) 50%, transparent); color: var(--muted, #696e76); font-size: .85rem; max-height: 6.5em; overflow: auto; white-space: pre-wrap; }
18
+ .wb-thread-detached { margin: 0; color: var(--muted, #696e76); font-size: .8rem; }
19
+ .wb-thread-message { display: grid; gap: 2px; }
20
+ .wb-thread-who { font-size: .7rem; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--muted, #696e76); }
21
+ .wb-thread-message[data-from=agent] .wb-thread-who { color: var(--accent, #1d5bbf); }
22
+ .wb-thread-text { white-space: pre-wrap; line-height: 1.45; }
23
+ /* rendered from markdown: its paragraphs and code carry the spacing */
24
+ .wb-thread-text[data-md] { white-space: normal; overflow-wrap: anywhere; }
25
+ .wb-thread-text[data-md] > :first-child { margin-top: 0; }
26
+ .wb-thread-text[data-md] > :last-child { margin-bottom: 0; }
27
+ .wb-thread-text[data-md] :is(p, ul, ol, pre, blockquote) { margin: 0 0 .5em; }
28
+ .wb-thread-text[data-md] pre { font-size: .8rem; padding: 8px 10px; border-radius: 6px; overflow-x: auto; max-width: 100%; }
29
+ .wb-thread textarea { width: 100%; resize: vertical; font: inherit; }
30
+ .wb-thread-reply { display: grid; gap: 8px; margin: 0; }
31
+ .wb-thread-actions { display: flex; gap: 8px; }
32
+ /* its own buttons, styled here rather than borrowed from the page */
33
+ .wb-comment-button { font: 500 .85rem/1.3 var(--sans, sans-serif); padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid var(--border, #e3e5e9); background: var(--surface, Canvas); color: var(--text, CanvasText); }
34
+ .wb-comment-button:hover { border-color: var(--muted, #696e76); }
35
+ .wb-comment-primary { background: var(--accent, #1d5bbf); color: var(--accent-text, #fff); border-color: var(--accent, #1d5bbf); }
36
+ .wb-comment-start, .wb-comment-badge { cursor: pointer; border-style: solid; border-width: 1px; }
37
+
38
+ /* "+" beside a line of code: comment on it, or drag over several */
39
+ .wb-line-comment { position: absolute; z-index: 20; width: 20px; height: 20px; padding: 0; border-radius: 4px; cursor: pointer; font: 600 14px/1 var(--sans, sans-serif); background: var(--accent, #1d5bbf); color: var(--accent-text, #fff); border: none; box-shadow: 0 1px 4px rgb(0 0 0 / .2); }
40
+ .wb-thread-at { margin: -4px 0 0; font: .78rem var(--mono, monospace); color: var(--muted, #696e76); }
@@ -0,0 +1,17 @@
1
+ A collapsible section. The label is the summary line; the body is any
2
+ markdown. Use it to keep in-depth explanation out of the way of the main read.
3
+ Unlike a raw `<details>` tag, the body needs no blank-line care.
4
+
5
+ Attributes: `open` (start expanded).
6
+
7
+ ```markdown
8
+ :::details[Why remark-directive instead of MDX?]
9
+ MDX fails the **whole page** on one stray `<` or `{`. Directives that no
10
+ block handles still render as plain markdown.
11
+ :::
12
+ ```
13
+
14
+ :::details[Why remark-directive instead of MDX?]
15
+ MDX fails the **whole page** on one stray `<` or `{`. Directives that no
16
+ block handles still render as plain markdown.
17
+ :::
@@ -0,0 +1,21 @@
1
+ import fs from 'node:fs'
2
+ import { definePlugin, type Plugin } from '@bigmistqke/whiteboard'
3
+ import { html, raw, type DirectiveContext } from '@bigmistqke/whiteboard'
4
+
5
+ export async function render(ctx: DirectiveContext) {
6
+ // the label and content are HTML already
7
+ return html`<details class="wb-details"${'open' in ctx.attrs && raw(' open')}><summary>${ctx.label ? raw(ctx.label) : 'Details'}</summary><div class="wb-details-body">${raw(await ctx.toHtml(ctx.children))}</div></details>`
8
+ }
9
+
10
+ export default function details(): Plugin {
11
+ return definePlugin({
12
+ name: 'details',
13
+ blocks: {
14
+ details: {
15
+ html: render,
16
+ style: new URL('./style.css', import.meta.url),
17
+ },
18
+ },
19
+ docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
20
+ })
21
+ }
@@ -0,0 +1,3 @@
1
+ /* the base <details> style does the work; the body wrapper only needs spacing */
2
+ .wb-details > .wb-details-body > :first-child { margin-top: .2em; }
3
+ .wb-details > .wb-details-body > :last-child { margin-bottom: 0; }
@@ -0,0 +1,12 @@
1
+ Issues and pull/merge requests of the project's GitHub or GitLab repository
2
+ link themselves: write `#12` for issue 12 and `!34` for pull or merge request
3
+ 34, as plain text. `owner/repo#12` and `group/project!34` point into another
4
+ repository on the same host. Inside code (`` `#12` ``) they stay text.
5
+
6
+ The repository is read from the project's `origin` remote, so a self-hosted
7
+ GitLab works too. Without such a remote they stay text; a config can say
8
+ which: `forge({ repo: 'group/project', host: 'gitlab.example.com', kind: 'gitlab' })`.
9
+
10
+ ```markdown
11
+ Fixed in !34, which closes #12 (see also bigmistqke/other#3).
12
+ ```