@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,134 @@
1
+ // The dot at the end of the header: is the page live, and does anyone listen for its answers? Green:
2
+ // the live channel is open and a listen covers the page (one on it or above it, or one on every
3
+ // page). Grey: live, but nobody listens, so answers wait in the log. A ring: not connected, the
4
+ // page may be out of date (the core reconnects and catches up). What it says on hover tells them
5
+ // apart. Only the overview and folders have no answers: there it says only whether the page is live.
6
+ // On a page, a click on the dot lists who listens: each by its name, else its id (`--agent`,
7
+ // `WORKPAD_AGENT`, a plugin's session), with a button that copies the id (what reopens its
8
+ // session: `claude --resume <id>`).
9
+ import type { Api, Listener, PageHandle } from '../../define.ts'
10
+ import { CHECK_ICON, COPY_ICON } from '../../icons.ts'
11
+
12
+ /** A button that copies an agent's id, a check for a moment once it did. */
13
+ function copyButton(id: string): HTMLButtonElement {
14
+ const button = document.createElement('button')
15
+ button.type = 'button'
16
+ button.className = 'wp-listeners-copy'
17
+ button.title = 'copy id'
18
+ button.setAttribute('aria-label', `copy id ${id}`)
19
+ button.innerHTML = COPY_ICON
20
+ button.addEventListener('click', async e => {
21
+ e.stopPropagation()
22
+ try {
23
+ await navigator.clipboard.writeText(id)
24
+ button.innerHTML = CHECK_ICON
25
+ button.dataset.copied = ''
26
+ setTimeout(() => {
27
+ button.innerHTML = COPY_ICON
28
+ delete button.dataset.copied
29
+ }, 1200)
30
+ } catch {
31
+ button.title = 'could not copy'
32
+ }
33
+ })
34
+ return button
35
+ }
36
+
37
+ export function trackLive(root: HTMLElement, handle: PageHandle, api: Api) {
38
+ const dot = root.querySelector<HTMLElement>('.wp-live')
39
+ if (!dot) return
40
+ const hasAnswers = handle.kind === 'page' || handle.kind === 'file'
41
+ const show = () => {
42
+ const live = document.documentElement.hasAttribute('data-wp-live')
43
+ const listeners = hasAnswers ? whoListens(api.listeners()) : []
44
+ const agent = live && listeners.length > 0
45
+ dot.toggleAttribute('data-agent', agent)
46
+ dot.title = !live
47
+ ? 'Reconnecting… the page may be out of date'
48
+ : !hasAnswers
49
+ ? 'Live'
50
+ : listeners.length
51
+ ? `Live · ${listeners.length === 1 ? 'one listens' : `${listeners.length} listen`} on this page`
52
+ : 'Live · nobody is listening right now; answers wait in the log'
53
+ dot.setAttribute('aria-label', dot.title)
54
+ }
55
+ api.listeners.on(show)
56
+ new MutationObserver(show).observe(document.documentElement, { attributes: true, attributeFilter: ['data-wp-live'] })
57
+ show()
58
+ if (hasAnswers) listenersPopup(dot, api)
59
+ }
60
+
61
+ /**
62
+ * Who listens, one each: an agent listening several ways (its channel, a `listen` it ran besides)
63
+ * is one agent; an unnamed process is one of its own.
64
+ */
65
+ const whoListens = (listeners: Listener[]): Listener[] => {
66
+ const seen = new Set<string>()
67
+ return listeners.filter(l => !l.agent || (!seen.has(l.agent) && !!seen.add(l.agent)))
68
+ }
69
+
70
+ /** The dot as a button: a click opens the list of who listens on the page, kept up to date while open. */
71
+ function listenersPopup(dot: HTMLElement, api: Api) {
72
+ dot.setAttribute('role', 'button')
73
+ dot.tabIndex = 0
74
+ const box = document.createElement('div')
75
+ box.className = 'wp-listeners'
76
+ box.popover = 'auto'
77
+ document.body.append(box)
78
+ const render = () => {
79
+ const listeners = whoListens(api.listeners())
80
+ box.replaceChildren()
81
+ const title = document.createElement('div')
82
+ title.className = 'wp-listeners-title'
83
+ title.textContent = listeners.length ? 'Listening on this page' : 'Nobody is listening'
84
+ box.append(title)
85
+ if (!listeners.length) {
86
+ const p = document.createElement('p')
87
+ p.textContent = 'Answers wait in the log for whoever listens next.'
88
+ box.append(p)
89
+ return
90
+ }
91
+ const list = document.createElement('ul')
92
+ for (const l of listeners) {
93
+ const li = document.createElement('li')
94
+ const name = document.createElement('span')
95
+ name.className = 'wp-listeners-who'
96
+ name.textContent = l.name ?? l.agent ?? 'unnamed'
97
+ // its id on hover (whole, also one cut short); one that said nothing about itself: how it would
98
+ li.title = l.agent ?? 'listening without --agent, WORKPAD_AGENT or an agent plugin naming it'
99
+ li.append(name)
100
+ if (l.agent) {
101
+ // the whole row copies it; the button shows that it does, and is the keyboard's way
102
+ const button = copyButton(l.agent)
103
+ li.append(button)
104
+ li.dataset.copy = ''
105
+ li.addEventListener('click', () => button.click())
106
+ }
107
+ list.append(li)
108
+ }
109
+ box.append(list)
110
+ }
111
+ // under the header with room to spare, and clear of the window's edge (and its scrollbar)
112
+ const place = () => {
113
+ const r = dot.getBoundingClientRect()
114
+ const edge = 16 + (innerWidth - document.documentElement.clientWidth)
115
+ box.style.top = `${r.bottom + 14}px`
116
+ box.style.left = `${Math.max(edge, Math.min(r.right - box.offsetWidth + 12, innerWidth - box.offsetWidth - edge))}px`
117
+ }
118
+ const toggle = () => {
119
+ if (box.matches(':popover-open')) return box.hidePopover()
120
+ render()
121
+ box.showPopover()
122
+ place()
123
+ }
124
+ dot.addEventListener('click', toggle)
125
+ dot.addEventListener('keydown', e => {
126
+ if (e.key === 'Enter' || e.key === ' ') {
127
+ e.preventDefault()
128
+ toggle()
129
+ }
130
+ })
131
+ api.listeners.on(() => {
132
+ if (box.matches(':popover-open')) render()
133
+ })
134
+ }
@@ -0,0 +1,398 @@
1
+ // The page in the browser: mounts blocks' islands, patches the page in place when it changes, and
2
+ // shows what an agent waits for on the page's named forms (the core sends them and marks their
3
+ // state). Comments are a plugin of their own. Framework-free: an island's client module exports
4
+ // mount(element, props, api) (see types.ts).
5
+ import morphdom from 'morphdom'
6
+ import type { Api, PageHandle, PluginMount } from '../../define.ts'
7
+ import type { ClientApi, Mount } from '../../define.ts'
8
+ import { countItems, markChanged, signature, signaturesOf, trackInitial, trackUpdate } from './fresh'
9
+ import { currentTheme, setThemePreference, themePreference, type ThemePreference } from './theme'
10
+ import { trackWaiting } from './waiting'
11
+ import { trackElsewhere } from './elsewhere'
12
+ import { trackLive } from './live'
13
+ import { applySorts, trackSorts } from './sort'
14
+ import { applyBoard, applySearch, trackBoard } from './board'
15
+ import { trackSticky } from './sticky'
16
+ import { beforeUpdate, trackPlace } from './place'
17
+ import { trackWindows } from './window'
18
+ import { trackHeadingLinks } from './heading-link'
19
+ import { trackOrphanThreads } from './orphans'
20
+ import { html } from '../../html.ts'
21
+
22
+ interface Island {
23
+ block: string
24
+ client: string
25
+ props: unknown
26
+ }
27
+ interface Data {
28
+ islands: Record<string, Island>
29
+ styles: string[]
30
+ mtime: number | null
31
+ }
32
+
33
+ let main: HTMLElement
34
+ let page = ''
35
+ let api: ClientApi
36
+ let islands: Record<string, Island> = {}
37
+ const disposers = new Map<Element, () => void>()
38
+
39
+ // ---- islands -----------------------------------------------------------------------------------
40
+
41
+ async function mountOne(el: HTMLElement) {
42
+ const island = islands[el.dataset.wpIsland!]
43
+ el.dataset.wpMounted = ''
44
+ if (!island) return
45
+ try {
46
+ const mod = await import(new URL(island.client, document.baseURI).href)
47
+ if (!el.isConnected) return
48
+ const mount: Mount = mod.default
49
+ if (typeof mount !== 'function')
50
+ throw new Error('the client module must export a mount(element, props, api) function as default')
51
+ el.replaceChildren()
52
+ const dispose = await mount(el, island.props, api)
53
+ if (typeof dispose === 'function') disposers.set(el, dispose)
54
+ } catch (err) {
55
+ console.error(`island ${island.block}:`, err)
56
+ el.insertAdjacentHTML(
57
+ 'afterbegin',
58
+ String(html`<pre class="wp-error">block "${island.block}" failed to mount: ${(err as Error).message}</pre>`),
59
+ )
60
+ }
61
+ }
62
+
63
+ /** Mount islands outermost first; nested islands show up once their parent has rendered. */
64
+ async function mountIslands(root: ParentNode = main): Promise<void> {
65
+ for (;;) {
66
+ const pending = [...root.querySelectorAll<HTMLElement>('[data-wp-island]:not([data-wp-mounted])')].filter(
67
+ el => !el.parentElement?.closest('[data-wp-island]:not([data-wp-mounted])'),
68
+ )
69
+ if (!pending.length) return
70
+ await Promise.all(pending.map(mountOne))
71
+ }
72
+ }
73
+
74
+ function disposeWithin(node: Node) {
75
+ for (const [el, dispose] of disposers) {
76
+ if (node === el || node.contains(el)) {
77
+ dispose()
78
+ disposers.delete(el)
79
+ }
80
+ }
81
+ }
82
+
83
+ // ---- theme -------------------------------------------------------------------------------------
84
+
85
+ const NEXT: Record<ThemePreference, ThemePreference> = { auto: 'light', light: 'dark', dark: 'auto' }
86
+ // the preference as an icon: half a circle for following the system, a sun, a moon
87
+ const svg = (d: string) => `<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">${d}</svg>`
88
+ const THEME_ICON: Record<ThemePreference, string> = {
89
+ auto: svg(
90
+ '<circle cx="8" cy="8" r="5.5" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M8 2.5a5.5 5.5 0 0 1 0 11Z" fill="currentColor"/>',
91
+ ),
92
+ light: svg(
93
+ '<circle cx="8" cy="8" r="2.8" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M8 1.2v1.8M8 13v1.8M1.2 8H3M13 8h1.8M3.2 3.2l1.3 1.3M11.5 11.5l1.3 1.3M3.2 12.8l1.3-1.3M11.5 4.5l1.3-1.3" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/>',
94
+ ),
95
+ dark: svg(
96
+ '<path d="M13.5 9.6A5.8 5.8 0 0 1 6.4 2.5a5.8 5.8 0 1 0 7.1 7.1Z" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/>',
97
+ ),
98
+ }
99
+ const THEME_LABEL: Record<ThemePreference, string> = {
100
+ auto: 'Theme: follows the system',
101
+ light: 'Theme: light',
102
+ dark: 'Theme: dark',
103
+ }
104
+
105
+ function themeToggle(root: HTMLElement) {
106
+ const button = root.querySelector<HTMLButtonElement>('.wp-theme')
107
+ if (!button) return
108
+ const show = () => {
109
+ const pref = themePreference()
110
+ button.innerHTML = THEME_ICON[pref]
111
+ button.dataset.pref = pref
112
+ // what it is now, and that a click changes it
113
+ button.title = `${THEME_LABEL[pref]} (click for ${NEXT[pref]})`
114
+ button.setAttribute('aria-label', button.title)
115
+ }
116
+ show()
117
+ button.addEventListener('click', () => {
118
+ setThemePreference(NEXT[themePreference()])
119
+ show()
120
+ })
121
+ }
122
+
123
+ // ---- time --------------------------------------------------------------------------------------
124
+
125
+ function ago(ts: number) {
126
+ const s = Math.round((Date.now() - ts) / 1000)
127
+ if (s < 10) return 'just now'
128
+ if (s < 60) return `${s}s ago`
129
+ if (s < 3600) return `${Math.round(s / 60)}m ago`
130
+ if (s < 86400) return `${Math.round(s / 3600)}h ago`
131
+ return new Date(ts).toLocaleDateString()
132
+ }
133
+ function tickTimes() {
134
+ for (const t of document.querySelectorAll<HTMLTimeElement>('time[data-ts]')) {
135
+ const ts = Number(t.dataset.ts)
136
+ t.textContent = ago(ts)
137
+ t.title = new Date(ts).toLocaleString()
138
+ }
139
+ }
140
+
141
+ // ---- live reload -------------------------------------------------------------------------------
142
+
143
+ let blockSigs: string[] = []
144
+
145
+ const FIELD = (n: Element): n is HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement =>
146
+ n instanceof HTMLInputElement || n instanceof HTMLTextAreaElement || n instanceof HTMLSelectElement
147
+ const KEEP_CLASSES = ['wp-new', 'wp-new-seen']
148
+
149
+ /** Patch the page in place: focus, caret, typed values, open <details> and unchanged islands survive. */
150
+ /**
151
+ * A <details> element's identity across renders: its summary, the nearest heading above its
152
+ * top-level block, and how many before it share both. Blocks are matched by position when the page
153
+ * updates, so a block inserted above an open section would otherwise pair it with a different
154
+ * element and close it; this finds the same section wherever it moved.
155
+ */
156
+ function detailsKeys(root: HTMLElement): Map<HTMLDetailsElement, string> {
157
+ const keys = new Map<HTMLDetailsElement, string>()
158
+ const seen = new Map<string, number>()
159
+ for (const el of root.querySelectorAll('details')) {
160
+ let block: Element = el
161
+ while (block.parentElement && block.parentElement !== root) block = block.parentElement
162
+ let heading = ''
163
+ for (let b: Element | null = block; b; b = b.previousElementSibling) {
164
+ if (/^H[1-6]$/.test(b.tagName)) {
165
+ heading = b.textContent?.trim() ?? ''
166
+ break
167
+ }
168
+ }
169
+ const base = `${heading}\u0000${el.querySelector(':scope > summary')?.textContent?.trim() ?? ''}`
170
+ const n = seen.get(base) ?? 0
171
+ seen.set(base, n + 1)
172
+ keys.set(el, `${base}\u0000${n}`)
173
+ }
174
+ return keys
175
+ }
176
+
177
+ /** Each block's key: its signature, and which of the blocks with that signature it is. */
178
+ function keyBlocks(parent: HTMLElement, sigs: string[]) {
179
+ const seen = new Map<string, number>()
180
+ ;[...parent.children].forEach((el, i) => {
181
+ const sig = sigs[i]
182
+ if (!sig) return
183
+ const nth = seen.get(sig) ?? 0
184
+ seen.set(sig, nth + 1)
185
+ ;(el as HTMLElement).dataset.wpBlock = `${sig}#${nth}`
186
+ })
187
+ }
188
+
189
+ /** What has the focus, to give it back if the patch took it: the element, its caret, and how to find it again. */
190
+ function focusOf() {
191
+ const el = document.activeElement as HTMLInputElement | HTMLTextAreaElement | null
192
+ if (!el || el === document.body || !main.contains(el)) return null
193
+ const form = el.closest('form')?.getAttribute('name')
194
+ let start: number | null = null,
195
+ end: number | null = null
196
+ try {
197
+ start = el.selectionStart
198
+ end = el.selectionEnd
199
+ } catch {
200
+ /* not a text field */
201
+ }
202
+ return { el, form, name: el.getAttribute('name'), start, end }
203
+ }
204
+
205
+ function giveFocusBack(f: ReturnType<typeof focusOf>) {
206
+ if (!f || document.activeElement === f.el) return
207
+ let el: HTMLElement | null = f.el.isConnected ? f.el : null
208
+ // replaced: the field of the same name in the form of the same name
209
+ if (!el && f.form && f.name)
210
+ el = main.querySelector<HTMLElement>(`form[name="${CSS.escape(f.form)}"] [name="${CSS.escape(f.name)}"]`)
211
+ if (!el) return
212
+ el.focus({ preventScroll: true })
213
+ if (f.start != null && 'setSelectionRange' in el)
214
+ try {
215
+ ;(el as HTMLInputElement).setSelectionRange(f.start, f.end ?? f.start)
216
+ } catch {
217
+ /* not a text field */
218
+ }
219
+ }
220
+
221
+ /** Are two elements, before and after a patch, the same field of the same form? */
222
+ function sameField(from: Element, to: Element) {
223
+ if (from.tagName !== to.tagName || from.getAttribute('name') !== to.getAttribute('name')) return false
224
+ const formOf = (el: Element) => el.closest('form')?.getAttribute('name') ?? null
225
+ if (formOf(from) !== formOf(to)) return false
226
+ const type = from.getAttribute('type')
227
+ if (
228
+ (type === 'radio' || type === 'checkbox') &&
229
+ (to.getAttribute('type') !== type || from.getAttribute('value') !== to.getAttribute('value'))
230
+ )
231
+ return false
232
+ return true
233
+ }
234
+
235
+ function morph(html: string, sigs: { from: string[]; to: string[] }) {
236
+ const open = new Set<string>()
237
+ for (const [el, key] of detailsKeys(main)) if (el.open) open.add(key)
238
+ const focus = focusOf()
239
+ const next = main.cloneNode(false) as HTMLElement
240
+ next.innerHTML = html
241
+ // blocks keyed by their content: an update that puts something new above a block leaves it be
242
+ // (and the field being typed in, in it), instead of patching each block into the next one
243
+ keyBlocks(main, sigs.from)
244
+ keyBlocks(next, sigs.to)
245
+ for (const [el, key] of detailsKeys(next)) el.open = open.has(key)
246
+ morphdom(main, next, {
247
+ getNodeKey: n =>
248
+ (n as HTMLElement).dataset?.wpKey || (n as HTMLElement).dataset?.wpBlock || (n as HTMLElement).id || undefined,
249
+ onBeforeElUpdated(from, to) {
250
+ if (from.dataset.wpKey) {
251
+ if (from.dataset.wpKey === to.dataset.wpKey && 'wpMounted' in from.dataset) {
252
+ from.dataset.wpIsland = to.dataset.wpIsland // ids are per render; the key is what's stable
253
+ return false
254
+ }
255
+ disposeWithin(from)
256
+ }
257
+ if (FIELD(from)) {
258
+ if (from === document.activeElement) return false
259
+ // what the reader typed or picked goes over only to the same field: the same form, name and
260
+ // (for a radio or checkbox) value. Patched into another field (a block moved), it would
261
+ // answer another question.
262
+ if (sameField(from, to)) {
263
+ ;(to as typeof from).value = from.value
264
+ if (from instanceof HTMLInputElement) (to as HTMLInputElement).checked = from.checked
265
+ }
266
+ }
267
+ // <details> open state was set on the new tree by detailsKeys(), matched by identity, not position
268
+ // what a plugin marked on an element (`data-wp-*`) stays, unless the new render sets it;
269
+ // data-wp-mounted is the page's own, and a replaced island must mount afresh
270
+ for (const { name, value } of [...from.attributes])
271
+ if (name.startsWith('data-wp-') && name !== 'data-wp-mounted' && !to.hasAttribute(name))
272
+ to.setAttribute(name, value)
273
+ for (const c of KEEP_CLASSES) if (from.classList.contains(c)) to.classList.add(c)
274
+ return true
275
+ },
276
+ // An element morphdom discards can hold an island it is about to move elsewhere (a form that
277
+ // moved down: its old place became the new paragraph, and the chat in it, keyed, goes into the
278
+ // form's new place). So islands are not disposed here, but after the patch, if gone.
279
+ })
280
+ for (const [el, dispose] of disposers) {
281
+ if (!el.isConnected) {
282
+ dispose()
283
+ disposers.delete(el)
284
+ }
285
+ }
286
+ giveFocusBack(focus)
287
+ }
288
+
289
+ /** The new render of the page, patched in. */
290
+ // the page is going (its own reload below, or the reader went elsewhere): a render still in flight is
291
+ // cut off then, and its failure is not the page's
292
+ let leaving = false
293
+ addEventListener('pagehide', () => {
294
+ leaving = true
295
+ })
296
+
297
+ async function refresh() {
298
+ let next: Awaited<ReturnType<PageHandle['render']>>
299
+ try {
300
+ next = await currentPage.render()
301
+ } catch (err) {
302
+ if (leaving) return
303
+ // the page is gone (closed, deleted): load what its address shows now, the "Not found" page,
304
+ // which turns into the page again if it is written back. Already that page (it has no file, so
305
+ // no time it was edited): still not there, nothing to do
306
+ if (/: 404$/.test((err as Error).message)) {
307
+ if ((currentPage.data() as Data | null)?.mtime == null) return
308
+ leaving = true
309
+ return location.reload()
310
+ }
311
+ throw err
312
+ }
313
+ const data = next.data as Data
314
+ islands = data.islands
315
+ for (const href of data.styles) {
316
+ if (
317
+ ![...document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')].some(
318
+ l => new URL(l.href).pathname === new URL(href, location.href).pathname,
319
+ )
320
+ )
321
+ document.head.insertAdjacentHTML('beforeend', String(html`<link rel="stylesheet" href="${href}" />`))
322
+ }
323
+ const content = new DOMParser().parseFromString(next.html, 'text/html').getElementById('wp-main')?.innerHTML ?? ''
324
+ const nextSigs = signaturesOf(content)
325
+ // the reader's place, found again if the update replaces it (what moves it later, as islands
326
+ // mount and plugins redraw, place.ts puts back as it happens)
327
+ const restorePlace = beforeUpdate(blockSigs, nextSigs)
328
+ morph(content, { from: blockSigs, to: nextSigs })
329
+ // a list the reader sorted comes back in the server's order: sorted again at once, before the
330
+ // rest of the update, so it never shows unsorted
331
+ applySorts()
332
+ applyBoard()
333
+ applySearch()
334
+ restorePlace()
335
+ const updated = document.getElementById('wp-updated')
336
+ if (updated && data.mtime) updated.dataset.ts = String(data.mtime)
337
+ if (next.title) core.title(next.title)
338
+ trackUpdate(main, blockSigs, nextSigs)
339
+ blockSigs = nextSigs
340
+ await mountIslands()
341
+ tickTimes()
342
+ // plugins put back what they add to the content
343
+ api.rendered()
344
+ }
345
+
346
+ let currentPage: PageHandle
347
+ let core: Api
348
+
349
+ const mount: PluginMount = async (root: HTMLElement, handle: PageHandle, coreApi: Api) => {
350
+ currentPage = handle
351
+ core = coreApi
352
+ page = handle.id
353
+ main = root.querySelector<HTMLElement>('#wp-main')!
354
+ islands = (handle.data() as Data).islands
355
+ // the islands of an agent's chat message (Api.message): mounted like the page's own once it is in
356
+ document.addEventListener('wp-islands', e => Object.assign(islands, (e as CustomEvent).detail))
357
+ // what changed in place (an agent's message, edited): new until seen, as a changed block is
358
+ main.addEventListener('wp-changed', e => markChanged(e.target as Element))
359
+ api = { ...core, theme: currentTheme }
360
+ const isDir = handle.kind === 'pages' || handle.kind === 'folder'
361
+
362
+ themeToggle(root)
363
+ setInterval(tickTimes, 15000)
364
+ // islands rendered later (after async loading inside a component) still get mounted
365
+ new MutationObserver(() => {
366
+ if (main.querySelector('[data-wp-island]:not([data-wp-mounted])')) mountIslands()
367
+ }).observe(main, { childList: true, subtree: true })
368
+
369
+ handle.onChange(() => refresh())
370
+ // the overview shows when pages were last answered
371
+ if (isDir) core.events.on(() => refresh())
372
+ // the overview shows which pages an agent is waiting on
373
+ if (isDir) core.listeners.on(() => refresh())
374
+
375
+ blockSigs = [...main.children].map(signature)
376
+ countItems(main)
377
+ // what is new, what waits, what is elsewhere, whether it's live: the server's, not a built page's
378
+ if (handle.live) {
379
+ if (!isDir) trackInitial(main, page, core)
380
+ if (!isDir) trackWaiting(main, core)
381
+ trackElsewhere(root, handle, core)
382
+ trackLive(root, handle, core)
383
+ }
384
+ if (isDir) {
385
+ trackSorts()
386
+ core.onRendered(applySorts)
387
+ trackBoard()
388
+ }
389
+ trackSticky(main, fn => core.onRendered(fn))
390
+ trackPlace(main)
391
+ trackHeadingLinks(main)
392
+ trackWindows(core)
393
+ if (!isDir && handle.live) trackOrphanThreads(main, core)
394
+ await mountIslands()
395
+ tickTimes()
396
+ }
397
+
398
+ export default mount
@@ -0,0 +1,64 @@
1
+ // Chats no longer on the page. A chat is found by its name: a form's chat by the form's, a chat
2
+ // block by its own. So when the writer removes or renames one, what the reader and the agent said in
3
+ // it would vanish from the page without a trace. The page lists those chats after its
4
+ // content instead, read-only and folded: the agent can still answer in one (`workpad append --type
5
+ // chat:message`), and prunes one it is done with (`workpad chat prune <page> <name>`). What the
6
+ // agent wrote in one is not unread (read.ts): the list is a record, nothing waits for the reader there.
7
+ import type { Api, WpEvent } from '../../define.ts'
8
+ import { html, raw } from '../../html.ts'
9
+ import { chatsShown } from '../read.ts'
10
+
11
+ /** A message in a chat: the chat block's event. */
12
+ const isMessage = (e: WpEvent) => e.type === 'chat:message' && typeof e.data.chat === 'string'
13
+
14
+ export function trackOrphanThreads(main: HTMLElement, api: Api) {
15
+ // after the page's content, not in it: #wp-main is compared block by block on every update
16
+ const box = document.createElement('section')
17
+ box.className = 'wp-orphans'
18
+ box.hidden = true
19
+ main.after(box)
20
+
21
+ function draw() {
22
+ const onPage = chatsShown() ?? new Set()
23
+ const threads = new Map<string, WpEvent[]>()
24
+ for (const e of api.events()) {
25
+ const chat = String(e.data.chat)
26
+ if (!isMessage(e) || onPage.has(chat)) continue
27
+ threads.set(chat, [...(threads.get(chat) ?? []), e])
28
+ }
29
+ box.hidden = threads.size === 0
30
+ if (box.hidden) return box.replaceChildren()
31
+ // folded: talk left over from questions taken off the page, kept for whoever wants it
32
+ const open = box.querySelector('details')?.open ?? false
33
+ box.innerHTML = String(
34
+ html`<details ${open ? raw('open') : ''}>
35
+ <summary>${threads.size} chat${threads.size === 1 ? '' : 's'} no longer on this page</summary>
36
+ ${[...threads].map(([chat, messages]) => {
37
+ // a message can take the place of an earlier one (`replaces`), to correct it
38
+ const replaced = new Set(
39
+ messages
40
+ .map(m => m.data.replaces)
41
+ .filter(Boolean)
42
+ .map(String),
43
+ )
44
+ return html`<div class="wp-orphan" data-chat="${chat}">
45
+ <h3>${chat}</h3>
46
+ ${messages
47
+ .filter(m => !replaced.has(m.id))
48
+ .map(m => {
49
+ const who = m.from === 'cli' ? 'agent' : 'you'
50
+ return html`<div class="wp-orphan-message" data-from="${who}">
51
+ <span class="wp-orphan-who">${who}</span
52
+ ><span class="wp-orphan-text">${String(m.data.text ?? '')}</span>
53
+ </div>`
54
+ })}
55
+ </div>`
56
+ })}
57
+ </details>`,
58
+ )
59
+ }
60
+
61
+ api.events.on(draw)
62
+ api.onRendered(draw)
63
+ draw()
64
+ }