@bigmistqke/workpad 0.0.0-stage → 0.18.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 (277) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +781 -2
  3. package/bin/workpad.ts +1526 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/workpad.js +1202 -0
  6. package/dist/client/runtime.js +1194 -0
  7. package/dist/define.js +27 -0
  8. package/dist/plugins/alert/README.md +18 -0
  9. package/dist/plugins/alert/index.js +40 -0
  10. package/dist/plugins/alert/public/style.css +40 -0
  11. package/dist/plugins/ansi/README.md +36 -0
  12. package/dist/plugins/ansi/index.js +63 -0
  13. package/dist/plugins/ansi/public/style.css +28 -0
  14. package/dist/plugins/badge/README.md +32 -0
  15. package/dist/plugins/badge/index.js +28 -0
  16. package/dist/plugins/badge/public/style.css +30 -0
  17. package/dist/plugins/chat/README.md +81 -0
  18. package/dist/plugins/chat/index.js +96 -0
  19. package/dist/plugins/chat/public/client.js +3 -0
  20. package/dist/plugins/chat/public/style.css +143 -0
  21. package/dist/plugins/claude/README.md +116 -0
  22. package/dist/plugins/claude/channel.js +130 -0
  23. package/dist/plugins/claude/doctor.js +316 -0
  24. package/dist/plugins/claude/index.js +199 -0
  25. package/dist/plugins/claude/session.js +68 -0
  26. package/dist/plugins/code/README.md +54 -0
  27. package/dist/plugins/code/diff.js +75 -0
  28. package/dist/plugins/code/index.js +105 -0
  29. package/dist/plugins/code/public/client.js +1 -0
  30. package/dist/plugins/code/public/style.css +99 -0
  31. package/dist/plugins/comments/README.md +30 -0
  32. package/dist/plugins/comments/index.js +39 -0
  33. package/dist/plugins/comments/public/client.js +24 -0
  34. package/dist/plugins/comments/public/style.css +224 -0
  35. package/dist/plugins/details/README.md +24 -0
  36. package/dist/plugins/details/index.js +28 -0
  37. package/dist/plugins/details/public/style.css +7 -0
  38. package/dist/plugins/draft/README.md +14 -0
  39. package/dist/plugins/draft/index.js +27 -0
  40. package/dist/plugins/draft/public/style.css +21 -0
  41. package/dist/plugins/forge/README.md +22 -0
  42. package/dist/plugins/forge/index.js +83 -0
  43. package/dist/plugins/form/README.md +126 -0
  44. package/dist/plugins/form/index.js +179 -0
  45. package/dist/plugins/form/public/style.css +172 -0
  46. package/dist/plugins/grid/README.md +45 -0
  47. package/dist/plugins/grid/index.js +35 -0
  48. package/dist/plugins/grid/public/style.css +98 -0
  49. package/dist/plugins/iframe/README.md +18 -0
  50. package/dist/plugins/iframe/index.js +49 -0
  51. package/dist/plugins/iframe/public/style.css +28 -0
  52. package/dist/plugins/index.js +44 -0
  53. package/dist/plugins/lightbox/README.md +24 -0
  54. package/dist/plugins/lightbox/index.js +20 -0
  55. package/dist/plugins/lightbox/public/client.js +4 -0
  56. package/dist/plugins/lightbox/public/style.css +66 -0
  57. package/dist/plugins/mermaid/README.md +21 -0
  58. package/dist/plugins/mermaid/index.js +42 -0
  59. package/dist/plugins/mermaid/public/style.css +21 -0
  60. package/dist/plugins/opencode/README.md +48 -0
  61. package/dist/plugins/opencode/channel.js +92 -0
  62. package/dist/plugins/opencode/index.js +64 -0
  63. package/dist/plugins/opencode/shim.js +150 -0
  64. package/dist/plugins/quiet/README.md +26 -0
  65. package/dist/plugins/quiet/index.js +23 -0
  66. package/dist/plugins/tabs/README.md +44 -0
  67. package/dist/plugins/tabs/index.js +75 -0
  68. package/dist/plugins/tabs/public/client.js +1 -0
  69. package/dist/plugins/tabs/public/style.css +98 -0
  70. package/dist/plugins/terminal/README.md +63 -0
  71. package/dist/plugins/terminal/host.js +338 -0
  72. package/dist/plugins/terminal/index.js +170 -0
  73. package/dist/plugins/terminal/modes.js +32 -0
  74. package/dist/plugins/terminal/public/client.js +41 -0
  75. package/dist/plugins/terminal/public/style.css +511 -0
  76. package/dist/plugins/terminal/server.js +256 -0
  77. package/dist/plugins/terminal/sizes.js +58 -0
  78. package/dist/plugins/timeline/README.md +48 -0
  79. package/dist/plugins/timeline/index.js +83 -0
  80. package/dist/plugins/timeline/public/style.css +138 -0
  81. package/dist/plugins/toc/README.md +40 -0
  82. package/dist/plugins/toc/index.js +29 -0
  83. package/dist/plugins/toc/public/client.js +1 -0
  84. package/dist/plugins/toc/public/style.css +117 -0
  85. package/dist/plugins/window/README.md +51 -0
  86. package/dist/plugins/window/index.js +91 -0
  87. package/dist/solid/index.js +41 -0
  88. package/dist/src/agents.js +81 -0
  89. package/dist/src/anchors.js +52 -0
  90. package/dist/src/api.js +282 -0
  91. package/dist/src/archive.js +49 -0
  92. package/dist/src/auth.js +67 -0
  93. package/dist/src/build.js +159 -0
  94. package/dist/src/client/page/base.css +1762 -0
  95. package/dist/src/client/page/main.js +2121 -0
  96. package/dist/src/config.js +76 -0
  97. package/dist/src/document.js +93 -0
  98. package/dist/src/entries.js +264 -0
  99. package/dist/src/events.js +322 -0
  100. package/dist/src/files.js +47 -0
  101. package/dist/src/formstate.js +65 -0
  102. package/dist/src/help.js +213 -0
  103. package/dist/src/html.js +34 -0
  104. package/dist/src/hub.js +348 -0
  105. package/dist/src/icons.js +6 -0
  106. package/dist/src/listen.js +132 -0
  107. package/dist/src/listeners.js +64 -0
  108. package/dist/src/load.js +81 -0
  109. package/dist/src/loader.js +179 -0
  110. package/dist/src/migrate.js +314 -0
  111. package/dist/src/package.js +52 -0
  112. package/dist/src/pages/blocks.js +67 -0
  113. package/dist/src/pages/board.js +59 -0
  114. package/dist/src/pages/index.js +27 -0
  115. package/dist/src/pages/markdown.js +863 -0
  116. package/dist/src/pages/render.js +761 -0
  117. package/dist/src/pages/window.js +29 -0
  118. package/dist/src/plugins.js +283 -0
  119. package/dist/src/public.js +24 -0
  120. package/dist/src/rename.js +130 -0
  121. package/dist/src/running.js +146 -0
  122. package/dist/src/serve.js +188 -0
  123. package/dist/src/server.js +1105 -0
  124. package/dist/src/site.js +179 -0
  125. package/dist/src/state.js +155 -0
  126. package/dist/src/status.js +323 -0
  127. package/dist/src/thread.js +68 -0
  128. package/dist/src/watchdog.js +38 -0
  129. package/dist/src/ws.js +128 -0
  130. package/package.json +154 -4
  131. package/plugins/README.md +304 -0
  132. package/plugins/alert/README.md +18 -0
  133. package/plugins/alert/index.ts +50 -0
  134. package/plugins/alert/public/style.css +40 -0
  135. package/plugins/ansi/README.md +36 -0
  136. package/plugins/ansi/index.ts +95 -0
  137. package/plugins/ansi/public/style.css +28 -0
  138. package/plugins/badge/README.md +32 -0
  139. package/plugins/badge/index.ts +36 -0
  140. package/plugins/badge/public/style.css +30 -0
  141. package/plugins/chat/README.md +81 -0
  142. package/plugins/chat/autosize.ts +139 -0
  143. package/plugins/chat/client.tsx +187 -0
  144. package/plugins/chat/index.ts +146 -0
  145. package/plugins/chat/public/style.css +143 -0
  146. package/plugins/claude/README.md +116 -0
  147. package/plugins/claude/channel.ts +136 -0
  148. package/plugins/claude/doctor.ts +274 -0
  149. package/plugins/claude/index.ts +248 -0
  150. package/plugins/claude/session.ts +70 -0
  151. package/plugins/code/README.md +54 -0
  152. package/plugins/code/client.ts +73 -0
  153. package/plugins/code/diff.ts +96 -0
  154. package/plugins/code/index.ts +136 -0
  155. package/plugins/code/public/style.css +99 -0
  156. package/plugins/comments/README.md +30 -0
  157. package/plugins/comments/client.ts +723 -0
  158. package/plugins/comments/index.ts +48 -0
  159. package/plugins/comments/public/style.css +224 -0
  160. package/plugins/details/README.md +24 -0
  161. package/plugins/details/index.ts +30 -0
  162. package/plugins/details/public/style.css +7 -0
  163. package/plugins/draft/README.md +14 -0
  164. package/plugins/draft/index.ts +23 -0
  165. package/plugins/draft/public/style.css +21 -0
  166. package/plugins/forge/README.md +22 -0
  167. package/plugins/forge/index.ts +84 -0
  168. package/plugins/form/README.md +126 -0
  169. package/plugins/form/index.ts +199 -0
  170. package/plugins/form/public/style.css +172 -0
  171. package/plugins/grid/README.md +45 -0
  172. package/plugins/grid/index.ts +41 -0
  173. package/plugins/grid/public/style.css +98 -0
  174. package/plugins/iframe/README.md +18 -0
  175. package/plugins/iframe/index.ts +53 -0
  176. package/plugins/iframe/public/style.css +28 -0
  177. package/plugins/index.ts +49 -0
  178. package/plugins/lightbox/README.md +24 -0
  179. package/plugins/lightbox/client.ts +109 -0
  180. package/plugins/lightbox/index.ts +25 -0
  181. package/plugins/lightbox/public/style.css +66 -0
  182. package/plugins/mermaid/README.md +21 -0
  183. package/plugins/mermaid/index.ts +46 -0
  184. package/plugins/mermaid/public/style.css +21 -0
  185. package/plugins/opencode/README.md +48 -0
  186. package/plugins/opencode/channel.ts +112 -0
  187. package/plugins/opencode/index.ts +91 -0
  188. package/plugins/opencode/shim.ts +166 -0
  189. package/plugins/quiet/README.md +26 -0
  190. package/plugins/quiet/index.ts +28 -0
  191. package/plugins/tabs/README.md +44 -0
  192. package/plugins/tabs/client.ts +96 -0
  193. package/plugins/tabs/index.ts +103 -0
  194. package/plugins/tabs/public/style.css +98 -0
  195. package/plugins/terminal/README.md +63 -0
  196. package/plugins/terminal/client.ts +391 -0
  197. package/plugins/terminal/host.ts +434 -0
  198. package/plugins/terminal/index.ts +199 -0
  199. package/plugins/terminal/modes.ts +30 -0
  200. package/plugins/terminal/public/style.css +225 -0
  201. package/plugins/terminal/server.ts +266 -0
  202. package/plugins/terminal/sizes.ts +72 -0
  203. package/plugins/timeline/README.md +48 -0
  204. package/plugins/timeline/index.ts +82 -0
  205. package/plugins/timeline/public/style.css +138 -0
  206. package/plugins/toc/README.md +40 -0
  207. package/plugins/toc/client.ts +236 -0
  208. package/plugins/toc/index.ts +55 -0
  209. package/plugins/toc/public/style.css +117 -0
  210. package/plugins/window/README.md +51 -0
  211. package/plugins/window/index.ts +92 -0
  212. package/skills/workpad/SKILL.md +592 -0
  213. package/solid/index.tsx +80 -0
  214. package/src/agents.ts +134 -0
  215. package/src/anchors.ts +85 -0
  216. package/src/api.ts +444 -0
  217. package/src/archive.ts +75 -0
  218. package/src/auth.ts +99 -0
  219. package/src/build.ts +213 -0
  220. package/src/client/base.ts +19 -0
  221. package/src/client/forms.ts +420 -0
  222. package/src/client/markdown.ts +147 -0
  223. package/src/client/page/base.css +1762 -0
  224. package/src/client/page/board.ts +166 -0
  225. package/src/client/page/elsewhere.ts +153 -0
  226. package/src/client/page/fresh.ts +343 -0
  227. package/src/client/page/heading-link.ts +32 -0
  228. package/src/client/page/live.ts +134 -0
  229. package/src/client/page/main.ts +398 -0
  230. package/src/client/page/orphans.ts +64 -0
  231. package/src/client/page/place.ts +260 -0
  232. package/src/client/page/sort.ts +49 -0
  233. package/src/client/page/sticky.ts +58 -0
  234. package/src/client/page/theme.ts +36 -0
  235. package/src/client/page/view.ts +9 -0
  236. package/src/client/page/waiting.ts +278 -0
  237. package/src/client/page/window.ts +40 -0
  238. package/src/client/reactive.ts +19 -0
  239. package/src/client/read.ts +111 -0
  240. package/src/client/runtime.ts +499 -0
  241. package/src/client/scroll.ts +90 -0
  242. package/src/client/toast.ts +99 -0
  243. package/src/config.ts +111 -0
  244. package/src/define.ts +997 -0
  245. package/src/document.ts +191 -0
  246. package/src/entries.ts +352 -0
  247. package/src/events.ts +463 -0
  248. package/src/files.ts +74 -0
  249. package/src/formstate.ts +72 -0
  250. package/src/help.ts +240 -0
  251. package/src/html.ts +44 -0
  252. package/src/hub.ts +435 -0
  253. package/src/icons.ts +18 -0
  254. package/src/listen.ts +171 -0
  255. package/src/listeners.ts +89 -0
  256. package/src/load.ts +113 -0
  257. package/src/loader.ts +227 -0
  258. package/src/migrate.ts +352 -0
  259. package/src/package.ts +62 -0
  260. package/src/pages/blocks.ts +106 -0
  261. package/src/pages/board.ts +89 -0
  262. package/src/pages/index.ts +79 -0
  263. package/src/pages/markdown.ts +976 -0
  264. package/src/pages/render.ts +845 -0
  265. package/src/pages/window.ts +69 -0
  266. package/src/plugins.ts +319 -0
  267. package/src/public.ts +39 -0
  268. package/src/rename.ts +147 -0
  269. package/src/running.ts +171 -0
  270. package/src/serve.ts +221 -0
  271. package/src/server.ts +1385 -0
  272. package/src/site.ts +170 -0
  273. package/src/state.ts +327 -0
  274. package/src/status.ts +466 -0
  275. package/src/thread.ts +98 -0
  276. package/src/watchdog.ts +53 -0
  277. package/src/ws.ts +155 -0
@@ -0,0 +1,723 @@
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 (`workpad 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-wp-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, WpEvent } from '../../src/define'
20
+ import { html, raw } from '../../src/html.ts'
21
+
22
+ const NEW = 'comments:new',
23
+ REPLY = 'comments:reply',
24
+ RESOLVE = 'comments:resolve'
25
+
26
+ interface Thread {
27
+ id: string
28
+ comment: WpEvent
29
+ replies: WpEvent[]
30
+ range: Range | null
31
+ /** its passage gone: the data it was found by, to place its badge where the passage was */
32
+ index?: ReturnType<typeof textIndex>
33
+ }
34
+
35
+ const CONTEXT = 32
36
+
37
+ let root: HTMLElement
38
+ let api: Api
39
+ // the page's content: its <main> when it has one. Looked up afresh, since a live update may replace it
40
+ let main: HTMLElement
41
+ let threads: Thread[] = []
42
+ let openThread: string | null = null
43
+
44
+ const layer = document.createElement('div')
45
+ layer.className = 'wp-comments'
46
+
47
+ const startButton = document.createElement('button')
48
+ startButton.type = 'button'
49
+ startButton.className = 'wp-comment-start'
50
+ startButton.textContent = 'Comment'
51
+ startButton.hidden = true
52
+
53
+ const popover = document.createElement('div')
54
+ popover.className = 'wp-thread'
55
+ popover.hidden = true
56
+
57
+ // Comments on text no longer on the page, with nothing of where it was left to place them by: listed
58
+ // after the page's content, each with its quote, its badge beside it (as chats no longer on the
59
+ // page are, by the page)
60
+ const gone = document.createElement('section')
61
+ gone.className = 'wp-orphan-comments'
62
+ gone.hidden = true
63
+ let goneKey = ''
64
+
65
+ // ---- the page's text ---------------------------------------------------------------------------
66
+
67
+ /** The text of the page's content as one string, with where each text node starts in it. */
68
+ function textIndex() {
69
+ const nodes: { node: Text; start: number }[] = []
70
+ let text = ''
71
+ const walker = document.createTreeWalker(main, NodeFilter.SHOW_TEXT, {
72
+ acceptNode: n =>
73
+ n.parentElement?.closest('script, style, textarea') ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT,
74
+ })
75
+ for (let n = walker.nextNode() as Text | null; n; n = walker.nextNode() as Text | null) {
76
+ nodes.push({ node: n, start: text.length })
77
+ text += n.data
78
+ }
79
+ return { text, nodes }
80
+ }
81
+
82
+ /** A position in the index → the text node and offset in it. */
83
+ function point(index: ReturnType<typeof textIndex>, at: number, end: boolean) {
84
+ for (let i = 0; i < index.nodes.length; i++) {
85
+ const { node, start } = index.nodes[i]
86
+ const stop = start + node.data.length
87
+ if (at < stop || (end && at === stop) || i === index.nodes.length - 1)
88
+ return { node, offset: Math.min(Math.max(at - start, 0), node.data.length) }
89
+ }
90
+ return null
91
+ }
92
+
93
+ /** Where a range starts and ends in the index. */
94
+ function offsetsOf(index: ReturnType<typeof textIndex>, range: Range) {
95
+ const find = (container: Node, offset: number) => {
96
+ if (container.nodeType === Node.TEXT_NODE) {
97
+ const hit = index.nodes.find(n => n.node === container)
98
+ return hit ? hit.start + offset : null
99
+ }
100
+ // an element boundary: the end of the last text node before it
101
+ const prefix = document.createRange()
102
+ prefix.setStart(main, 0)
103
+ prefix.setEnd(container, offset)
104
+ let at = 0
105
+ for (const { node, start } of index.nodes) if (prefix.intersectsNode(node)) at = start + node.data.length
106
+ return at
107
+ }
108
+ const start = find(range.startContainer, range.startOffset)
109
+ const end = find(range.endContainer, range.endOffset)
110
+ return start == null || end == null ? null : { start, end }
111
+ }
112
+
113
+ /** The passage of a comment on the page as it is now: its quote, the occurrence whose surroundings match best. */
114
+ function locate(index: ReturnType<typeof textIndex>, data: Record<string, unknown>): Range | null {
115
+ const quote = String(data.quote ?? '')
116
+ if (!quote) return null
117
+ const before = String(data.before ?? ''),
118
+ after = String(data.after ?? '')
119
+ let best = -1,
120
+ bestScore = -1
121
+ for (let at = index.text.indexOf(quote); at >= 0; at = index.text.indexOf(quote, at + 1)) {
122
+ const b = index.text.slice(Math.max(0, at - before.length), at)
123
+ const a = index.text.slice(at + quote.length, at + quote.length + after.length)
124
+ let score = 0
125
+ while (score < b.length && b[b.length - 1 - score] === before[before.length - 1 - score]) score++
126
+ let s2 = 0
127
+ while (s2 < a.length && a[s2] === after[s2]) s2++
128
+ if (score + s2 > bestScore) {
129
+ best = at
130
+ bestScore = score + s2
131
+ }
132
+ }
133
+ if (best < 0) return null
134
+ const s = point(index, best, false),
135
+ e = point(index, best + quote.length, true)
136
+ if (!s || !e) return null
137
+ const range = document.createRange()
138
+ range.setStart(s.node, s.offset)
139
+ range.setEnd(e.node, e.offset)
140
+ return range
141
+ }
142
+
143
+ /**
144
+ * Where a passage that is gone from the page was: right after the text that came before it, else
145
+ * right before the text that came after it (each found again only if long enough to tell apart),
146
+ * else the top of the block it was in. Where on screen, or null when nothing of there is left.
147
+ */
148
+ function whereItWas(index: ReturnType<typeof textIndex>, data: Record<string, unknown>): number | null {
149
+ const at = (from: number, to: number, end: boolean) => {
150
+ const s = point(index, from, false),
151
+ e = point(index, to, true)
152
+ if (!s || !e) return null
153
+ const range = document.createRange()
154
+ range.setStart(s.node, s.offset)
155
+ range.setEnd(e.node, e.offset)
156
+ const rects = range.getClientRects()
157
+ const rect = end ? rects[rects.length - 1] : rects[0]
158
+ return rect ? rect.top : null
159
+ }
160
+ const before = String(data.before ?? '').trim(),
161
+ after = String(data.after ?? '').trim()
162
+ if (before.length >= 8) {
163
+ const i = index.text.indexOf(before)
164
+ if (i >= 0 && index.text.indexOf(before, i + 1) < 0) {
165
+ const top = at(i, i + before.length, true)
166
+ if (top != null) return top
167
+ }
168
+ }
169
+ if (after.length >= 8) {
170
+ const i = index.text.indexOf(after)
171
+ if (i >= 0 && index.text.indexOf(after, i + 1) < 0) {
172
+ const top = at(i, i + after.length, false)
173
+ if (top != null) return top
174
+ }
175
+ }
176
+ const block = typeof data.block === 'number' && data.block >= 0 ? main.children[data.block] : null
177
+ return block ? block.getBoundingClientRect().top : null
178
+ }
179
+
180
+ // ---- threads -----------------------------------------------------------------------------------
181
+
182
+ function collect(): Thread[] {
183
+ const events = api.events()
184
+ const resolved = new Set(events.filter(e => e.type === RESOLVE).map(e => String(e.data.replyTo)))
185
+ const index = textIndex()
186
+ return events
187
+ .filter(e => e.type === NEW && !resolved.has(e.id))
188
+ .map(comment => ({
189
+ id: comment.id,
190
+ comment,
191
+ replies: events.filter(e => e.type === REPLY && e.data.replyTo === comment.id),
192
+ range: locate(index, comment.data),
193
+ index,
194
+ }))
195
+ }
196
+
197
+ const lastFromAgent = (t: Thread) => t.replies.at(-1)?.from === 'cli'
198
+
199
+ /** Highlight every open thread's passage, and put its badge in the margin beside it. */
200
+ function draw() {
201
+ const highlights = (CSS as unknown as { highlights?: Map<string, unknown> }).highlights
202
+ const HighlightCtor = (window as unknown as { Highlight?: new (...r: Range[]) => unknown }).Highlight
203
+ if (highlights && HighlightCtor) {
204
+ highlights.set(
205
+ 'wp-comment',
206
+ new HighlightCtor(...threads.filter(t => t.range && t.id !== openThread).map(t => t.range!)),
207
+ )
208
+ const active = threads.find(t => t.id === openThread)?.range
209
+ if (active) highlights.set('wp-comment-active', new HighlightCtor(active))
210
+ else highlights.delete('wp-comment-active')
211
+ }
212
+ // where each passage gone from the page was, or nowhere left: those go in the list
213
+ const was = new Map<string, number | null>()
214
+ for (const t of threads)
215
+ if (!t.range?.getClientRects().length) was.set(t.id, t.index ? whereItWas(t.index, t.comment.data) : null)
216
+ listGone(threads.filter(t => was.has(t.id) && was.get(t.id) == null))
217
+ const column = main.getBoundingClientRect()
218
+ const unreadIds = new Set(api.unread().map(e => e.id))
219
+ // badges of passages gone from the page, by where they were: a second one at a place goes below
220
+ const detachedAt = new Map<number, number>()
221
+ layer.replaceChildren(
222
+ ...threads.map(t => {
223
+ const badge = document.createElement('button')
224
+ badge.type = 'button'
225
+ badge.className = 'wp-comment-badge'
226
+ badge.dataset.thread = t.id
227
+ badge.toggleAttribute('data-agent', lastFromAgent(t))
228
+ // the replies it holds, for the page to find an unread one here (data-wp-holds, see the page)
229
+ badge.dataset.wpHolds = t.replies.map(r => r.id).join(' ')
230
+ const unread = t.replies.some(r => unreadIds.has(r.id))
231
+ badge.toggleAttribute('data-unread', unread)
232
+ badge.title = unread ? 'the agent replied: unread' : lastFromAgent(t) ? 'the agent replied' : 'comment'
233
+ badge.textContent = String(1 + t.replies.length)
234
+ const rect = t.range?.getClientRects()[0]
235
+ // a passage that is gone from the page: its badge stays where the passage was (at the top, if
236
+ // nothing of there is left), still open until closed
237
+ let top: number
238
+ const row = gone.querySelector<HTMLElement>(`[data-row="${CSS.escape(t.id)}"]`)
239
+ if (rect) top = rect.top + scrollY
240
+ else if (row) top = row.getBoundingClientRect().top + scrollY
241
+ else {
242
+ const at = Math.round(was.get(t.id) ?? column.top)
243
+ const n = detachedAt.get(at) ?? 0
244
+ detachedAt.set(at, n + 1)
245
+ top = at + n * 30 + scrollY
246
+ }
247
+ const left = Math.min(column.right + 8 + scrollX, document.documentElement.clientWidth - 36 + scrollX)
248
+ badge.style.top = `${top}px`
249
+ badge.style.left = `${left}px`
250
+ if (!rect) badge.dataset.detached = ''
251
+ return badge
252
+ }),
253
+ )
254
+ if (openThread) placePopover()
255
+ }
256
+
257
+ /** The list of comments with nowhere on the page left: drawn again only when they change. */
258
+ function listGone(list: Thread[]) {
259
+ if (!gone.isConnected || gone.previousElementSibling !== main) main.after(gone)
260
+ const key = list.map(t => t.id).join(' ')
261
+ if (key === goneKey) return
262
+ goneKey = key
263
+ gone.hidden = !list.length
264
+ // built as elements: a quote keeps its whitespace (its style), so none may come from markup
265
+ const title = document.createElement('p')
266
+ title.className = 'wp-orphan-comments-title'
267
+ title.textContent = `${list.length} comment${list.length === 1 ? '' : 's'} on text no longer on this page`
268
+ const quotes = list.map(t => {
269
+ const quote = document.createElement('blockquote')
270
+ quote.className = 'wp-thread-quote'
271
+ quote.dataset.row = quote.dataset.thread = t.id
272
+ quote.textContent = String(t.comment.data.quote ?? '')
273
+ return quote
274
+ })
275
+ gone.replaceChildren(...(list.length ? [title, ...quotes] : []))
276
+ }
277
+
278
+ /** Called after the page re-rendered, and whenever the log changed. */
279
+ /**
280
+ * Change the thread around a reply being typed, and keep that box where it is on screen: a new
281
+ * message above it, or one shown as markdown, would push it down.
282
+ */
283
+ function holdTyping(change: () => void) {
284
+ const box = popover.querySelector('textarea')
285
+ const typing = !!box && document.activeElement === box
286
+ const top = typing ? box!.getBoundingClientRect().top : 0
287
+ change()
288
+ const now = popover.querySelector('textarea')
289
+ if (!typing || !now || document.activeElement !== now) return
290
+ const moved = now.getBoundingClientRect().top - top
291
+ if (Math.abs(moved) >= 1) scrollBy(0, moved)
292
+ }
293
+
294
+ function refreshComments() {
295
+ if (!root) return
296
+ main = root.querySelector('main') ?? root
297
+ holdTyping(() => {
298
+ threads = collect()
299
+ if (openThread && !threads.some(t => t.id === openThread)) closePopover()
300
+ else if (openThread) renderPopover()
301
+ draw()
302
+ })
303
+ }
304
+
305
+ // ---- the thread popover ------------------------------------------------------------------------
306
+
307
+ // messages as markdown, rendered by the server, by their text
308
+ const rendered = new Map<string, string>()
309
+
310
+ function renderPopover() {
311
+ const t = threads.find(x => x.id === openThread)
312
+ if (!t) return
313
+ const who = (e: WpEvent) => (e.from === 'cli' ? 'agent' : 'you')
314
+ // the quote and every message are text from the reader or the agent: `html` escapes them
315
+ // a message is markdown: as rendered, once the server has (api.markdown), as plain text till then
316
+ const message = (e: WpEvent) => {
317
+ const text = String(e.data.text ?? '')
318
+ const md = rendered.get(text)
319
+ // shown at once, not yet confirmed by the server
320
+ return html`<div
321
+ class="wp-thread-message"
322
+ data-from="${who(e)}"
323
+ data-wp-message="${e.id}"
324
+ ${e.sending ? raw(' data-sending') : ''}
325
+ >
326
+ <span class="wp-thread-who">${who(e)}</span>
327
+ <div class="wp-thread-text" ${md != null ? raw(' data-md') : ''}>${md != null ? raw(md) : text}</div>
328
+ </div>`
329
+ }
330
+ // the reply being typed: its text, and its focus and caret, which a redraw would take
331
+ const box = popover.querySelector('textarea')
332
+ const draft = box?.value ?? ''
333
+ const typing = !!box && document.activeElement === box
334
+ const caret = box ? ([box.selectionStart, box.selectionEnd] as const) : null
335
+ popover.innerHTML = String(
336
+ html` <blockquote class="wp-thread-quote">${t.comment.data.quote ?? ''}</blockquote>
337
+ ${t.comment.data.at && html`<p class="wp-thread-at">${t.comment.data.at}</p>`}
338
+ ${!t.range && html`<p class="wp-thread-detached">This passage is no longer on the page.</p>`}
339
+ ${[t.comment, ...t.replies].map(message)}
340
+ <form class="wp-thread-reply">
341
+ <textarea rows="2" placeholder="Reply (Shift+Enter for a new line)"></textarea>
342
+ <div class="wp-thread-actions">
343
+ <button type="submit" class="wp-comment-button wp-comment-primary">Reply</button
344
+ ><button type="button" class="wp-comment-button" data-close>Close thread</button>
345
+ </div>
346
+ </form>`,
347
+ )
348
+ const again = popover.querySelector('textarea')!
349
+ again.value = draft
350
+ if (typing) {
351
+ again.focus({ preventScroll: true })
352
+ if (caret) again.setSelectionRange(caret[0], caret[1])
353
+ }
354
+ // the messages not rendered yet: their text only, put in place as each arrives (the rest of the
355
+ // thread, the reply being typed among it, stays as it is)
356
+ for (const e of [t.comment, ...t.replies]) {
357
+ const text = String(e.data.text ?? '')
358
+ if (rendered.has(text)) continue
359
+ api.markdown(text).then(
360
+ md => {
361
+ rendered.set(text, md)
362
+ const el = popover.querySelector<HTMLElement>(`[data-wp-message="${CSS.escape(e.id)}"] .wp-thread-text`)
363
+ if (el && !el.hasAttribute('data-md'))
364
+ holdTyping(() => {
365
+ el.innerHTML = md
366
+ el.setAttribute('data-md', '')
367
+ })
368
+ },
369
+ err => console.error('comments:', err),
370
+ )
371
+ }
372
+ }
373
+
374
+ function placePopover() {
375
+ const badge = layer.querySelector<HTMLElement>(`[data-thread="${openThread}"]`)
376
+ if (!badge) return
377
+ const top = parseFloat(badge.style.top) + 28
378
+ const width = Math.min(360, document.documentElement.clientWidth - 32)
379
+ const left = Math.max(
380
+ 16 + scrollX,
381
+ Math.min(parseFloat(badge.style.left) + 28 - width, document.documentElement.clientWidth - width - 16 + scrollX),
382
+ )
383
+ popover.style.top = `${top}px`
384
+ popover.style.left = `${left}px`
385
+ popover.style.width = `${width}px`
386
+ }
387
+
388
+ function openPopover(id: string) {
389
+ openThread = id
390
+ popover.hidden = false
391
+ popover.querySelector('textarea')?.replaceWith(document.createElement('textarea'))
392
+ renderPopover()
393
+ draw()
394
+ popover.querySelector('textarea')?.focus({ preventScroll: true })
395
+ }
396
+
397
+ function closePopover() {
398
+ openThread = null
399
+ popover.hidden = true
400
+ draw()
401
+ }
402
+
403
+ // ---- starting a comment ------------------------------------------------------------------------
404
+
405
+ let pending: { quote: string; before: string; after: string; block: number; at?: string } | null = null
406
+
407
+ /** A selection inside the page's text (not in a form) → where the Comment button goes. */
408
+ function onSelection() {
409
+ main = root.querySelector('main') ?? root
410
+ const sel = getSelection()
411
+ if (!sel || sel.isCollapsed || !sel.rangeCount) {
412
+ if (!startButton.matches(':focus')) startButton.hidden = true
413
+ return
414
+ }
415
+ const range = sel.getRangeAt(0)
416
+ const inPage = (n: Node) =>
417
+ main.contains(n) && !(n instanceof Element ? n : n.parentElement)?.closest('form, input, textarea, select, button')
418
+ if (!inPage(range.startContainer) || !inPage(range.endContainer)) {
419
+ startButton.hidden = true
420
+ return
421
+ }
422
+ startButton.hidden = !prepare(range)
423
+ }
424
+
425
+ /**
426
+ * What a comment on `range` records (`pending`), and the Comment button put under its end. False
427
+ * when there is nothing to comment on.
428
+ */
429
+ function prepare(range: Range): boolean {
430
+ const quote = range.toString().trim()
431
+ if (!quote) return false
432
+ const index = textIndex()
433
+ const at = offsetsOf(index, range)
434
+ if (!at) return false
435
+ // the quote as it appears in the page's text, trimmed of the whitespace the selection had around it
436
+ const start = index.text.indexOf(quote, at.start)
437
+ const s = start >= 0 && start <= at.end ? start : at.start
438
+ let block: Element | null =
439
+ range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement
440
+ while (block && block.parentElement !== main) block = block.parentElement
441
+ pending = {
442
+ quote,
443
+ before: index.text.slice(Math.max(0, s - CONTEXT), s),
444
+ after: index.text.slice(s + quote.length, s + quote.length + CONTEXT),
445
+ block: block ? [...main.children].indexOf(block) : -1,
446
+ }
447
+ // where the passage is from, when its block says (see the top of this file)
448
+ const places = [...main.querySelectorAll<HTMLElement>('[data-wp-at]')]
449
+ .filter(el => range.intersectsNode(el) && el.textContent)
450
+ .map(el => el.dataset.wpAt!)
451
+ if (places.length)
452
+ pending.at = places.length > 1 && places.at(-1) !== places[0] ? `${places[0]} – ${places.at(-1)}` : places[0]
453
+ const rects = range.getClientRects()
454
+ const last = rects[rects.length - 1] ?? range.getBoundingClientRect()
455
+ startButton.style.top = `${last.bottom + scrollY + 6}px`
456
+ startButton.style.left = `${Math.min(last.right + scrollX - 40, document.documentElement.clientWidth - 110 + scrollX)}px`
457
+ return true
458
+ }
459
+
460
+ // ---- comments on lines of code -----------------------------------------------------------------
461
+
462
+ // A code block's lines (Shiki writes each as a .line): hovering one shows "+" at its left; pressing
463
+ // it comments on the line, dragging it down or up takes the lines it passes over.
464
+ const lineButton = document.createElement('button')
465
+ lineButton.type = 'button'
466
+ lineButton.className = 'wp-line-comment'
467
+ lineButton.textContent = '+'
468
+ lineButton.title = 'Comment on this line (drag for several)'
469
+ lineButton.hidden = true
470
+
471
+ let hovered: HTMLElement | null = null
472
+ let drag: { pre: HTMLElement; from: HTMLElement; to: HTMLElement } | null = null
473
+
474
+ const codeLine = (el: EventTarget | null) => {
475
+ const line = el instanceof Element ? el.closest<HTMLElement>('pre .line') : null
476
+ return line && main.contains(line) && !line.closest('form') ? line : null
477
+ }
478
+
479
+ /** The lines from `a` to `b`, either way round, as one range. */
480
+ function linesRange(a: HTMLElement, b: HTMLElement): Range {
481
+ const [first, last] = a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_PRECEDING ? [b, a] : [a, b]
482
+ const range = document.createRange()
483
+ range.setStart(first, 0)
484
+ range.setEnd(last, last.childNodes.length)
485
+ return range
486
+ }
487
+
488
+ function showLineButton(line: HTMLElement) {
489
+ hovered = line
490
+ const rect = line.getBoundingClientRect()
491
+ const pre = line.closest('pre')!.getBoundingClientRect()
492
+ lineButton.style.top = `${rect.top + scrollY + rect.height / 2 - 10}px`
493
+ lineButton.style.left = `${Math.max(scrollX + 2, pre.left + scrollX - 24)}px`
494
+ lineButton.hidden = false
495
+ }
496
+
497
+ function onLinePointer(e: MouseEvent) {
498
+ if (drag) {
499
+ // the line at the pointer's height, inside the block the drag started in
500
+ const pre = drag.pre.getBoundingClientRect()
501
+ const x = drag.from.getBoundingClientRect().left + 4
502
+ const line = codeLine(document.elementFromPoint(x, Math.min(Math.max(e.clientY, pre.top + 1), pre.bottom - 1)))
503
+ if (line && drag.pre.contains(line) && line !== drag.to) {
504
+ drag.to = line
505
+ const highlights = (CSS as unknown as { highlights?: Map<string, unknown> }).highlights
506
+ const HighlightCtor = (window as unknown as { Highlight?: new (...r: Range[]) => unknown }).Highlight
507
+ if (highlights && HighlightCtor)
508
+ highlights.set('wp-comment-active', new HighlightCtor(linesRange(drag.from, drag.to)))
509
+ }
510
+ return
511
+ }
512
+ if (e.target === lineButton) return
513
+ const line = codeLine(e.target)
514
+ if (line) return showLineButton(line)
515
+ if (lineButton.hidden || !hovered) return
516
+ // on the way to the "+" (through the block's padding, or diagonally across other lines): the "+"
517
+ // is for the line at the pointer's height, as long as the pointer is between the "+" and the
518
+ // block's right edge
519
+ const pre = hovered.closest('pre')!
520
+ const box = pre.getBoundingClientRect()
521
+ const plus = lineButton.getBoundingClientRect()
522
+ const inside = e.clientX >= plus.left - 4 && e.clientX <= box.right && e.clientY >= box.top && e.clientY <= box.bottom
523
+ const atHeight = inside
524
+ ? codeLine(document.elementFromPoint(hovered.getBoundingClientRect().left + 4, e.clientY))
525
+ : null
526
+ if (atHeight && pre.contains(atHeight)) showLineButton(atHeight)
527
+ else if (!inside || !(e.clientY >= plus.top - 4 && e.clientY <= plus.bottom + 4)) {
528
+ lineButton.hidden = true
529
+ hovered = null
530
+ }
531
+ }
532
+
533
+ const composer = document.createElement('form')
534
+ composer.className = 'wp-thread wp-comment-new'
535
+ composer.hidden = true
536
+ composer.innerHTML = String(
537
+ html`<blockquote class="wp-thread-quote"></blockquote>
538
+ <textarea rows="3" placeholder="Your comment (Shift+Enter for a new line)"></textarea>
539
+ <div class="wp-thread-actions">
540
+ <button type="submit" class="wp-comment-button wp-comment-primary">Comment</button
541
+ ><button type="button" class="wp-comment-button" data-cancel>Cancel</button>
542
+ </div>`,
543
+ )
544
+
545
+ function startComment() {
546
+ if (!pending) return
547
+ composer.querySelector('blockquote')!.textContent = pending.at ? `${pending.at}\n${pending.quote}` : pending.quote
548
+ composer.style.top = startButton.style.top
549
+ const width = Math.min(360, document.documentElement.clientWidth - 32)
550
+ composer.style.width = `${width}px`
551
+ composer.style.left = `${Math.max(16 + scrollX, Math.min(parseFloat(startButton.style.left), document.documentElement.clientWidth - width - 16 + scrollX))}px`
552
+ composer.hidden = false
553
+ startButton.hidden = true
554
+ composer.querySelector('textarea')!.focus({ preventScroll: true })
555
+ }
556
+
557
+ // ---- entry -------------------------------------------------------------------------------------
558
+
559
+ const mount: PluginMount = (el: HTMLElement, handle: PageHandle, core: Api) => {
560
+ // the overview and folders are lists, not text to comment on
561
+ if (handle.kind !== 'page' && handle.kind !== 'file') return
562
+ root = el
563
+ main = root.querySelector('main') ?? root
564
+ api = core
565
+ // over the page, in document coordinates: its element in the overlay slot is laid out as if these
566
+ // were at the end of <body>
567
+ core.slot('overlay', place => {
568
+ place.append(layer, startButton, lineButton, popover, composer)
569
+ return () => {
570
+ for (const part of [layer, startButton, lineButton, popover, composer]) part.remove()
571
+ }
572
+ })
573
+
574
+ document.addEventListener('mousemove', onLinePointer)
575
+ // the pointer left the page: no line is hovered any more (a drag keeps its lines until mouseup)
576
+ document.documentElement.addEventListener('mouseleave', () => {
577
+ if (drag) return
578
+ lineButton.hidden = true
579
+ hovered = null
580
+ })
581
+ lineButton.addEventListener('mousedown', e => {
582
+ if (!hovered || e.button !== 0) return
583
+ e.preventDefault()
584
+ const highlights = (CSS as unknown as { highlights?: Map<string, unknown> }).highlights
585
+ const HighlightCtor = (window as unknown as { Highlight?: new (...r: Range[]) => unknown }).Highlight
586
+ if (highlights && HighlightCtor)
587
+ highlights.set('wp-comment-active', new HighlightCtor(linesRange(hovered, hovered)))
588
+ drag = { pre: hovered.closest('pre')!, from: hovered, to: hovered }
589
+ })
590
+ document.addEventListener('mouseup', () => {
591
+ if (!drag) return
592
+ const { from, to } = drag
593
+ drag = null
594
+ lineButton.hidden = true
595
+ if (prepare(linesRange(from, to))) startComment()
596
+ else draw()
597
+ })
598
+
599
+ let selTimer = 0
600
+ document.addEventListener('selectionchange', () => {
601
+ clearTimeout(selTimer)
602
+ selTimer = window.setTimeout(onSelection, 150)
603
+ })
604
+ // keep the selection when the button is pressed
605
+ startButton.addEventListener('mousedown', e => e.preventDefault())
606
+ startButton.addEventListener('click', startComment)
607
+
608
+ // as in a chat: Enter sends the comment or reply, Shift+Enter starts a new line; not while an
609
+ // input method is composing
610
+ for (const form of [composer, popover] as HTMLElement[])
611
+ form.addEventListener('keydown', e => {
612
+ const box = e.target as HTMLElement
613
+ if (box.tagName !== 'TEXTAREA' || e.key !== 'Enter' || e.shiftKey || e.isComposing) return
614
+ e.preventDefault()
615
+ box.closest('form')?.requestSubmit()
616
+ })
617
+ composer.addEventListener('submit', async e => {
618
+ e.preventDefault()
619
+ const text = composer.querySelector('textarea')!.value.trim()
620
+ if (!text || !pending) return
621
+ // optimistic: the thread is on the page at once (append puts the comment in the events), open
622
+ const where = pending
623
+ const sent = api.append(NEW, { ...where, text })
624
+ const shown = api.events().findLast(e => e.type === NEW && e.sending && e.data.text === text)
625
+ composer.querySelector('textarea')!.value = ''
626
+ composer.hidden = true
627
+ pending = null
628
+ getSelection()?.removeAllRanges()
629
+ refreshComments()
630
+ if (shown) openPopover(shown.id)
631
+ try {
632
+ await sent
633
+ } catch (err) {
634
+ console.error('comments:', err)
635
+ // it never got there: the composer again, with the passage and the text
636
+ if (!composer.hidden) return
637
+ pending = where
638
+ composer.querySelector('textarea')!.value = text
639
+ composer.hidden = false
640
+ api.toast("Couldn't send the comment", {
641
+ kind: 'alert',
642
+ name: 'comment-failed',
643
+ details: "It's back in the box: send it again.",
644
+ })
645
+ }
646
+ })
647
+ composer.querySelector('[data-cancel]')!.addEventListener('click', () => {
648
+ composer.hidden = true
649
+ pending = null
650
+ })
651
+
652
+ gone.addEventListener('click', e => {
653
+ const id = (e.target as HTMLElement).closest<HTMLElement>('[data-thread]')?.dataset.thread
654
+ if (id) openThread === id ? closePopover() : openPopover(id)
655
+ })
656
+ layer.addEventListener('click', e => {
657
+ const id = (e.target as HTMLElement).closest<HTMLElement>('[data-thread]')?.dataset.thread
658
+ if (id) openThread === id ? closePopover() : openPopover(id)
659
+ })
660
+ popover.addEventListener('submit', async e => {
661
+ e.preventDefault()
662
+ const box = popover.querySelector('textarea')!
663
+ const text = box.value.trim()
664
+ if (!text || !openThread) return
665
+ // optimistic: the reply is in the thread at once, marked sending, and the box is free
666
+ const thread = openThread
667
+ box.value = ''
668
+ const sent = api.append(REPLY, { replyTo: thread, text })
669
+ refreshComments()
670
+ try {
671
+ await sent
672
+ } catch (err) {
673
+ console.error('comments:', err)
674
+ const again = popover.querySelector('textarea')
675
+ if (openThread === thread && again && !again.value.trim()) again.value = text
676
+ api.toast("Couldn't send the reply", {
677
+ kind: 'alert',
678
+ name: 'comment-failed',
679
+ details: "It's back in the box: send it again.",
680
+ })
681
+ }
682
+ })
683
+ popover.addEventListener('click', async e => {
684
+ if (!(e.target as HTMLElement).closest('[data-close]') || !openThread) return
685
+ const id = openThread
686
+ closePopover()
687
+ // closed, the thread's replies ask nothing of the reader any more
688
+ api.markRead(threads.find(t => t.id === id)?.replies.map(r => r.id) ?? [])
689
+ // optimistic: the thread leaves the page at once; should that not get through, it comes back
690
+ const sent = api.append(RESOLVE, { replyTo: id })
691
+ refreshComments()
692
+ sent.catch(err => {
693
+ console.error('comments:', err)
694
+ api.toast("Couldn't close the thread", { kind: 'alert', name: 'comment-failed', details: "It's open again." })
695
+ })
696
+ })
697
+ // the page goes to an unread reply here: open its thread
698
+ layer.addEventListener('wp-reveal', e => {
699
+ const id = (e.target as HTMLElement).closest<HTMLElement>('[data-thread]')?.dataset.thread
700
+ if (id && openThread !== id) openPopover(id)
701
+ })
702
+ // a double-click outside the open thread closes it (a single click selects, to comment)
703
+ document.addEventListener('dblclick', e => {
704
+ const target = e.target as Node
705
+ if (!openThread || popover.contains(target) || layer.contains(target)) return
706
+ closePopover()
707
+ })
708
+ document.addEventListener('keydown', e => {
709
+ if (e.key !== 'Escape') return
710
+ if (!composer.hidden) {
711
+ composer.hidden = true
712
+ pending = null
713
+ } else if (openThread) closePopover()
714
+ })
715
+
716
+ api.events.on(refreshComments)
717
+ api.onRendered(refreshComments)
718
+ new ResizeObserver(() => draw()).observe(root)
719
+ addEventListener('resize', () => draw())
720
+ refreshComments()
721
+ }
722
+
723
+ export default mount