@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,70 @@
1
+ // What waits for the reader on other pages: a menu in the page's header, there only while another
2
+ // page has a question they haven't answered or a message from the agent they haven't read. It
3
+ // lists those pages, each with how many; a click goes to the page, which goes to the first of them
4
+ // (`#wb-waiting`, see waiting.ts). This page's own are in its corner, not here.
5
+ import type { Api, PageHandle, PageStatus } from '../../define.ts'
6
+ import { INBOX_ICON, awaitingLabel } from '../../icons.ts'
7
+ import { awaiting } from '../../status.ts'
8
+
9
+ /** A link to a page that scrolls it to its first waiting question. */
10
+ export const WAITING_HASH = '#wb-waiting'
11
+
12
+ const box = document.createElement('div')
13
+ box.className = 'wb-elsewhere'
14
+ box.hidden = true
15
+ box.innerHTML = '<button type="button" class="wb-elsewhere-toggle wb-awaiting" aria-haspopup="true" aria-expanded="false"></button><ul class="wb-elsewhere-list" hidden></ul>'
16
+ const toggle = box.querySelector('button')!
17
+ // an inbox, and how many questions wait in it
18
+ toggle.innerHTML = `${INBOX_ICON}<span class="wb-elsewhere-count"></span>`
19
+ const count = toggle.querySelector('span')!
20
+ const list = box.querySelector('ul')!
21
+
22
+ function open(yes: boolean) {
23
+ list.hidden = !yes
24
+ toggle.setAttribute('aria-expanded', String(yes))
25
+ }
26
+
27
+ let current = ''
28
+
29
+ async function load() {
30
+ let pages: PageStatus[]
31
+ try { pages = await (await fetch('/api/status', { cache: 'no-store' })).json() } catch { return }
32
+ const waiting = pages
33
+ .filter(p => p.page !== current)
34
+ .map(p => ({ p, n: awaiting(p) }))
35
+ .filter(({ n }) => n > 0)
36
+ const total = waiting.reduce((sum, { n }) => sum + n, 0)
37
+ box.hidden = total === 0
38
+ if (!total) open(false)
39
+ count.textContent = String(total)
40
+ toggle.title = awaitingLabel(total, ` on ${waiting.length === 1 ? 'another page' : `${waiting.length} other pages`}`)
41
+ toggle.setAttribute('aria-label', toggle.title)
42
+ list.replaceChildren(...waiting.map(({ p, n }) => {
43
+ const li = document.createElement('li')
44
+ const a = document.createElement('a')
45
+ a.href = `/${p.page.split('/').map(encodeURIComponent).join('/')}${WAITING_HASH}`
46
+ a.textContent = `${p.title} (${n})`
47
+ li.append(a)
48
+ return li
49
+ }))
50
+ }
51
+
52
+ // several changes at once (an answer is an event and a listener less) load once
53
+ let timer = 0
54
+ const reload = () => { clearTimeout(timer); timer = window.setTimeout(load, 100) }
55
+
56
+ export function trackElsewhere(root: HTMLElement, handle: PageHandle, core: Api) {
57
+ current = handle.id
58
+ const nav = root.querySelector('.wb-nav')
59
+ if (!nav) return
60
+ nav.querySelector('.wb-theme')?.before(box)
61
+ toggle.addEventListener('click', () => open(!!list.hidden))
62
+ document.addEventListener('click', e => { if (!box.contains(e.target as Node)) open(false) })
63
+ document.addEventListener('keydown', e => { if (e.key === 'Escape' && !list.hidden) { open(false); toggle.focus() } })
64
+ // what waits changes with an answer (events), a wait starting or ending (listeners), and a page's
65
+ // forms (a page changed)
66
+ core.onEvents(reload)
67
+ core.onListeners(reload)
68
+ handle.onChange(reload)
69
+ load()
70
+ }
@@ -0,0 +1,205 @@
1
+ // New-content tracking. A top-level block of the page is "new" when its content was not on the
2
+ // page last time the reader saw it: since the previous live update, or since their previous
3
+ // visit (remembered per page in localStorage). New blocks get .wb-new (a left border) until they
4
+ // have been in view for a moment with the tab visible. Floating buttons jump to unseen blocks.
5
+
6
+ import { html } from '../../html.ts'
7
+ import type { Api } from '../../define.ts'
8
+ import { viewBottom } from './view'
9
+
10
+ const DWELL_MS = 600
11
+ const FADE_MS = 2500
12
+
13
+ const sigOf = new WeakMap<Element, string>()
14
+ const unseen = new Set<Element>()
15
+ const timers = new WeakMap<Element, number>()
16
+ let storeKey = ''
17
+ // set by trackInitial: a page that tracks nothing (the overview) has no bubbles
18
+ let core: Api | undefined
19
+
20
+ /**
21
+ * FNV-1a over the block's HTML, ignoring per-render attributes and anything quiet: content inside
22
+ * [data-wb-quiet] can appear, change or go without the block counting as changed.
23
+ */
24
+ export function signature(el: Element): string {
25
+ const clone = el.cloneNode(true) as Element
26
+ for (const q of clone.querySelectorAll('[data-wb-quiet]')) q.remove()
27
+ for (const n of [clone, ...clone.querySelectorAll('[data-wb-island],[data-wb-mounted]')]) {
28
+ n.removeAttribute('data-wb-island')
29
+ n.removeAttribute('data-wb-mounted')
30
+ }
31
+ const s = clone.outerHTML
32
+ let h = 0x811c9dc5
33
+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193)
34
+ return (h >>> 0).toString(36)
35
+ }
36
+
37
+ /** Signatures of the top-level blocks in an HTML string, in order. */
38
+ export function signaturesOf(html: string): string[] {
39
+ const t = document.createElement('template')
40
+ t.innerHTML = html
41
+ return [...t.content.children].map(signature)
42
+ }
43
+
44
+ function loadSeen(): Set<string> | null {
45
+ try {
46
+ const raw = localStorage.getItem(storeKey)
47
+ return raw ? new Set(JSON.parse(raw)) : null
48
+ } catch { return null }
49
+ }
50
+
51
+ function saveSeen(main: HTMLElement) {
52
+ try {
53
+ const seen = [...main.children].filter(el => !unseen.has(el)).map(el => sigOf.get(el)).filter(Boolean)
54
+ localStorage.setItem(storeKey, JSON.stringify(seen))
55
+ } catch { /* storage unavailable: tracking still works for this visit */ }
56
+ }
57
+
58
+ // ---- seen detection ----------------------------------------------------------------------------
59
+ // Measured directly on scroll, resize and tab switches (and every half second while anything is
60
+ // unseen, since layout also moves without scrolling). An IntersectionObserver only reports at fixed
61
+ // fractions of a block's own height, which a block taller than twice the screen never reaches.
62
+
63
+ let mainEl: HTMLElement
64
+
65
+ /** In view enough to count as read: half the block, or half the screen for blocks taller than that. */
66
+ function inView(el: Element) {
67
+ const r = el.getBoundingClientRect()
68
+ const bottom = viewBottom()
69
+ const overlap = Math.min(r.bottom, bottom) - Math.max(r.top, 0)
70
+ return overlap > 0 && overlap >= Math.min(r.height, bottom) * 0.5
71
+ }
72
+
73
+ /** Start the dwell timer of unseen blocks in view; stop it for blocks that left the view. */
74
+ function check() {
75
+ const active = document.visibilityState === 'visible'
76
+ for (const el of unseen) {
77
+ if (!el.isConnected) { unseen.delete(el); continue }
78
+ const pending = timers.has(el)
79
+ if (active && inView(el)) {
80
+ if (!pending) timers.set(el, window.setTimeout(() => { timers.delete(el); markSeen(el) }, DWELL_MS))
81
+ } else if (pending) {
82
+ clearTimeout(timers.get(el))
83
+ timers.delete(el)
84
+ }
85
+ }
86
+ }
87
+
88
+ let checkFrame = 0
89
+ const scheduleCheck = () => { cancelAnimationFrame(checkFrame); checkFrame = requestAnimationFrame(check) }
90
+ addEventListener('scroll', scheduleCheck, { passive: true })
91
+ addEventListener('resize', scheduleCheck)
92
+ document.addEventListener('visibilitychange', scheduleCheck)
93
+ setInterval(() => { if (unseen.size) check() }, 500)
94
+
95
+ function markSeen(el: Element) {
96
+ if (!unseen.delete(el)) return
97
+ el.classList.add('wb-new-seen')
98
+ setTimeout(() => el.classList.remove('wb-new', 'wb-new-seen'), FADE_MS)
99
+ saveSeen(mainEl)
100
+ update()
101
+ }
102
+
103
+ function markNew(el: Element) {
104
+ // a block that is quiet as a whole is never news
105
+ if (el.matches('[data-wb-quiet]')) return
106
+ el.classList.remove('wb-new-seen')
107
+ el.classList.add('wb-new')
108
+ unseen.add(el)
109
+ scheduleCheck()
110
+ }
111
+
112
+ // ---- navigator ---------------------------------------------------------------------------------
113
+
114
+ // the "new" bubbles, in the page's corner (the core's), and their count in the tab title
115
+ const nav = document.createElement('div')
116
+ nav.className = 'wb-fresh'
117
+
118
+ nav.innerHTML = String(html`${['up', 'down'].map(dir =>
119
+ html`<button type="button" data-dir="${dir}"><span class="wb-fresh-label"></span><span class="wb-fresh-close" title="Mark everything new as seen" aria-label="Mark everything new as seen">✕</span></button>`)}`)
120
+ const [upBtn, downBtn] = nav.querySelectorAll('button')
121
+ // hidden until the first update has counted: it runs in an animation frame, which a hidden tab
122
+ // does not get, so until then the bubbles would show without their labels
123
+ nav.hidden = upBtn.hidden = downBtn.hidden = true
124
+
125
+ function split() {
126
+ const above: Element[] = [], below: Element[] = []
127
+ for (const el of unseen) {
128
+ if (!el.isConnected) { unseen.delete(el); continue }
129
+ const r = el.getBoundingClientRect()
130
+ if (r.bottom < 60) above.push(el)
131
+ else if (r.top > viewBottom()) below.push(el)
132
+ }
133
+ const top = (el: Element) => el.getBoundingClientRect().top
134
+ above.sort((a, b) => top(b) - top(a)) // nearest first
135
+ below.sort((a, b) => top(a) - top(b))
136
+ return { above, below }
137
+ }
138
+
139
+ let raf = 0
140
+ function update() {
141
+ cancelAnimationFrame(raf)
142
+ raf = requestAnimationFrame(() => {
143
+ const { above, below } = split()
144
+ upBtn.hidden = !above.length
145
+ downBtn.hidden = !below.length
146
+ upBtn.querySelector('.wb-fresh-label')!.textContent = `↑ new (${above.length})`
147
+ downBtn.querySelector('.wb-fresh-label')!.textContent = `↓ new (${below.length})`
148
+ nav.hidden = !above.length && !below.length
149
+ core?.badge('new', unseen.size ? String(unseen.size) : null)
150
+ })
151
+ }
152
+
153
+ nav.addEventListener('click', e => {
154
+ const dir = (e.target as HTMLElement).closest('button')?.dataset.dir
155
+ if (!dir) return
156
+ // the ✕ in a bubble clicks the marks away: everything new counts as seen
157
+ if ((e.target as HTMLElement).closest('.wb-fresh-close')) { for (const el of [...unseen]) markSeen(el); return }
158
+ const { above, below } = split()
159
+ ;(dir === 'up' ? above : below)[0]?.scrollIntoView({ behavior: 'smooth', block: 'start' })
160
+ })
161
+ addEventListener('scroll', update, { passive: true })
162
+ addEventListener('resize', update)
163
+
164
+ // ---- entry points ------------------------------------------------------------------------------
165
+
166
+ /** Below this share of blocks recognised from the last visit, the page counts as new to the reader. */
167
+ const RECOGNISED_MIN = 0.25
168
+
169
+ /**
170
+ * First render: blocks the reader has not seen on a previous visit are new. On a first visit, or
171
+ * when so little is recognised that the page is effectively a different one (a rewrite, say),
172
+ * nothing is marked: marking every block tells the reader nothing.
173
+ */
174
+ export function trackInitial(main: HTMLElement, page: string, api: Api) {
175
+ core = api
176
+ api.corner().append(nav)
177
+ mainEl = main
178
+ storeKey = `wb-seen:${page}`
179
+ const blocks = [...main.children]
180
+ const sigs = blocks.map(signature)
181
+ blocks.forEach((el, i) => sigOf.set(el, sigs[i]))
182
+ const seen = loadSeen()
183
+ const recognised = seen ? sigs.filter(s => seen.has(s)).length : 0
184
+ if (seen && recognised >= blocks.length * RECOGNISED_MIN)
185
+ blocks.forEach((el, i) => { if (!seen.has(sigs[i])) markNew(el) })
186
+ saveSeen(main)
187
+ update()
188
+ }
189
+
190
+ /** After a live update: blocks whose content was not on the page before are new. */
191
+ export function trackUpdate(main: HTMLElement, previous: string[], next: string[]) {
192
+ const before = new Map<string, number>()
193
+ for (const s of previous) before.set(s, (before.get(s) ?? 0) + 1)
194
+ const blocks = [...main.children]
195
+ blocks.forEach((el, i) => {
196
+ const sig = next[i]
197
+ sigOf.set(el, sig)
198
+ const left = before.get(sig) ?? 0
199
+ if (left > 0) before.set(sig, left - 1)
200
+ else markNew(el)
201
+ })
202
+ for (const el of [...unseen]) if (!el.isConnected) unseen.delete(el)
203
+ saveSeen(main)
204
+ update()
205
+ }
@@ -0,0 +1,30 @@
1
+ // The dot at the end of the header: is the page live, and does an agent take its answers? Green: the
2
+ // live channel is open and a wait or watch covers the page (one with --page on it or above it, or
3
+ // the project-wide one without --page). Grey: live, but no agent listens, so answers wait in the
4
+ // log. A ring: not connected, the page may be out of date (the core reconnects and catches up).
5
+ // What it says on hover tells them apart. Only the overview and folders have no answers: there it
6
+ // says only whether the page is live.
7
+ import type { Api, PageHandle } from '../../define.ts'
8
+
9
+ export function trackLive(root: HTMLElement, handle: PageHandle, api: Api) {
10
+ const dot = root.querySelector<HTMLElement>('.wb-live')
11
+ if (!dot) return
12
+ const hasAnswers = handle.kind === 'page' || handle.kind === 'file'
13
+ const show = () => {
14
+ const live = document.documentElement.hasAttribute('data-wb-live')
15
+ const listeners = hasAnswers ? api.listeners() : []
16
+ const own = listeners.some(l => !l.fallback)
17
+ const anyPage = listeners.some(l => l.fallback)
18
+ const agent = live && (own || anyPage)
19
+ dot.toggleAttribute('data-agent', agent)
20
+ dot.title = !live ? 'Reconnecting… the page may be out of date'
21
+ : !hasAnswers ? 'Live'
22
+ : own ? 'Live · an agent is listening on this page'
23
+ : anyPage ? 'Live · an agent is listening on every page'
24
+ : 'Live · no agent is listening right now; answers wait in the log'
25
+ dot.setAttribute('aria-label', dot.title)
26
+ }
27
+ api.onListeners(show)
28
+ new MutationObserver(show).observe(document.documentElement, { attributes: true, attributeFilter: ['data-wb-live'] })
29
+ show()
30
+ }
@@ -0,0 +1,272 @@
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 { signature, signaturesOf, trackInitial, trackUpdate } from './fresh'
9
+ import { currentTheme, onTheme, 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 { trackOrphanThreads } from './orphans'
15
+ import { html } from '../../html.ts'
16
+
17
+ interface Island { block: string; client: string; props: unknown }
18
+ interface Data { islands: Record<string, Island>; styles: string[]; mtime: number | null }
19
+
20
+ let main: HTMLElement
21
+ let page = ''
22
+ let api: ClientApi
23
+ let islands: Record<string, Island> = {}
24
+ const disposers = new Map<Element, () => void>()
25
+
26
+ // ---- islands -----------------------------------------------------------------------------------
27
+
28
+ async function mountOne(el: HTMLElement) {
29
+ const island = islands[el.dataset.wbIsland!]
30
+ el.dataset.wbMounted = ''
31
+ if (!island) return
32
+ try {
33
+ const mod = await import(island.client)
34
+ if (!el.isConnected) return
35
+ const mount: Mount = mod.default
36
+ if (typeof mount !== 'function') throw new Error('the client module must export a mount(element, props, api) function as default')
37
+ el.replaceChildren()
38
+ const dispose = await mount(el, island.props, api)
39
+ if (typeof dispose === 'function') disposers.set(el, dispose)
40
+ } catch (err) {
41
+ console.error(`island ${island.block}:`, err)
42
+ el.insertAdjacentHTML('afterbegin', String(html`<pre class="wb-error">block "${island.block}" failed to mount: ${(err as Error).message}</pre>`))
43
+ }
44
+ }
45
+
46
+ /** Mount islands outermost first; nested islands show up once their parent has rendered. */
47
+ async function mountIslands(root: ParentNode = main): Promise<void> {
48
+ for (;;) {
49
+ const pending = [...root.querySelectorAll<HTMLElement>('[data-wb-island]:not([data-wb-mounted])')]
50
+ .filter(el => !el.parentElement?.closest('[data-wb-island]:not([data-wb-mounted])'))
51
+ if (!pending.length) return
52
+ await Promise.all(pending.map(mountOne))
53
+ }
54
+ }
55
+
56
+ function disposeWithin(node: Node) {
57
+ for (const [el, dispose] of disposers) {
58
+ if (node === el || node.contains(el)) { dispose(); disposers.delete(el) }
59
+ }
60
+ }
61
+
62
+
63
+ // ---- theme -------------------------------------------------------------------------------------
64
+
65
+ const NEXT: Record<ThemePreference, ThemePreference> = { auto: 'light', light: 'dark', dark: 'auto' }
66
+ // the preference as an icon: half a circle for following the system, a sun, a moon
67
+ const svg = (d: string) => `<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">${d}</svg>`
68
+ const THEME_ICON: Record<ThemePreference, string> = {
69
+ auto: svg('<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"/>'),
70
+ light: svg('<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"/>'),
71
+ dark: svg('<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"/>'),
72
+ }
73
+ const THEME_LABEL: Record<ThemePreference, string> = { auto: 'Theme: follows the system', light: 'Theme: light', dark: 'Theme: dark' }
74
+
75
+ function themeToggle(root: HTMLElement) {
76
+ const button = root.querySelector<HTMLButtonElement>('.wb-theme')
77
+ if (!button) return
78
+ const show = () => {
79
+ const pref = themePreference()
80
+ button.innerHTML = THEME_ICON[pref]
81
+ button.dataset.pref = pref
82
+ // what it is now, and that a click changes it
83
+ button.title = `${THEME_LABEL[pref]} (click for ${NEXT[pref]})`
84
+ button.setAttribute('aria-label', button.title)
85
+ }
86
+ show()
87
+ button.addEventListener('click', () => {
88
+ setThemePreference(NEXT[themePreference()])
89
+ show()
90
+ })
91
+ }
92
+
93
+ // ---- time --------------------------------------------------------------------------------------
94
+
95
+ function ago(ts: number) {
96
+ const s = Math.round((Date.now() - ts) / 1000)
97
+ if (s < 10) return 'just now'
98
+ if (s < 60) return `${s}s ago`
99
+ if (s < 3600) return `${Math.round(s / 60)}m ago`
100
+ if (s < 86400) return `${Math.round(s / 3600)}h ago`
101
+ return new Date(ts).toLocaleDateString()
102
+ }
103
+ function tickTimes() {
104
+ for (const t of document.querySelectorAll<HTMLTimeElement>('time[data-ts]')) {
105
+ const ts = Number(t.dataset.ts)
106
+ t.textContent = ago(ts)
107
+ t.title = new Date(ts).toLocaleString()
108
+ }
109
+ }
110
+
111
+ // ---- live reload -------------------------------------------------------------------------------
112
+
113
+ let blockSigs: string[] = []
114
+
115
+ const FIELD = (n: Element): n is HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement =>
116
+ n instanceof HTMLInputElement || n instanceof HTMLTextAreaElement || n instanceof HTMLSelectElement
117
+ const KEEP_CLASSES = ['wb-new', 'wb-new-seen']
118
+
119
+ /** Patch the page in place: focus, caret, typed values, open <details> and unchanged islands survive. */
120
+ /**
121
+ * A <details> element's identity across renders: its summary, the nearest heading above its
122
+ * top-level block, and how many before it share both. Blocks are matched by position when the page
123
+ * updates, so a block inserted above an open section would otherwise pair it with a different
124
+ * element and close it; this finds the same section wherever it moved.
125
+ */
126
+ function detailsKeys(root: HTMLElement): Map<HTMLDetailsElement, string> {
127
+ const keys = new Map<HTMLDetailsElement, string>()
128
+ const seen = new Map<string, number>()
129
+ for (const el of root.querySelectorAll('details')) {
130
+ let block: Element = el
131
+ while (block.parentElement && block.parentElement !== root) block = block.parentElement
132
+ let heading = ''
133
+ for (let b: Element | null = block; b; b = b.previousElementSibling) {
134
+ if (/^H[1-6]$/.test(b.tagName)) { heading = b.textContent?.trim() ?? ''; break }
135
+ }
136
+ const base = `${heading}\u0000${el.querySelector(':scope > summary')?.textContent?.trim() ?? ''}`
137
+ const n = seen.get(base) ?? 0
138
+ seen.set(base, n + 1)
139
+ keys.set(el, `${base}\u0000${n}`)
140
+ }
141
+ return keys
142
+ }
143
+
144
+ function morph(html: string) {
145
+ const open = new Set<string>()
146
+ for (const [el, key] of detailsKeys(main)) if (el.open) open.add(key)
147
+ const next = main.cloneNode(false) as HTMLElement
148
+ next.innerHTML = html
149
+ for (const [el, key] of detailsKeys(next)) el.open = open.has(key)
150
+ morphdom(main, next, {
151
+ getNodeKey: n => (n as HTMLElement).dataset?.wbKey || (n as HTMLElement).id || undefined,
152
+ onBeforeElUpdated(from, to) {
153
+ if (from.dataset.wbKey) {
154
+ if (from.dataset.wbKey === to.dataset.wbKey && 'wbMounted' in from.dataset) {
155
+ from.dataset.wbIsland = to.dataset.wbIsland // ids are per render; the key is what's stable
156
+ return false
157
+ }
158
+ disposeWithin(from)
159
+ }
160
+ if (FIELD(from)) {
161
+ if (from === document.activeElement) return false
162
+ ;(to as typeof from).value = from.value
163
+ if (from instanceof HTMLInputElement) (to as HTMLInputElement).checked = from.checked
164
+ }
165
+ // <details> open state was set on the new tree by detailsKeys(), matched by identity, not position
166
+ // what a plugin marked on an element (`data-wb-*`) stays, unless the new render sets it;
167
+ // data-wb-mounted is the page's own, and a replaced island must mount afresh
168
+ for (const { name, value } of [...from.attributes])
169
+ if (name.startsWith('data-wb-') && name !== 'data-wb-mounted' && !to.hasAttribute(name)) to.setAttribute(name, value)
170
+ for (const c of KEEP_CLASSES) if (from.classList.contains(c)) to.classList.add(c)
171
+ return true
172
+ },
173
+ onBeforeNodeDiscarded(node) {
174
+ disposeWithin(node)
175
+ return true
176
+ },
177
+ })
178
+ }
179
+
180
+ // The page keeps the reader's place itself: the browser's own scroll anchoring loses its anchor
181
+ // when an update replaces elements, so it is turned off to keep the two from both correcting.
182
+ document.documentElement.style.overflowAnchor = 'none'
183
+
184
+ /**
185
+ * The reader's place before an update: the first block in view that the update keeps (by
186
+ * signature, and which of the blocks with that signature it is), and where it is on screen.
187
+ */
188
+ function placeOf(nextSigs: string[]) {
189
+ const keep = new Set(nextSigs)
190
+ const blocks = [...main.children]
191
+ for (let i = 0; i < blocks.length; i++) {
192
+ const sig = blockSigs[i]
193
+ if (!keep.has(sig) || blocks[i].getBoundingClientRect().bottom <= 0) continue
194
+ const nth = blockSigs.slice(0, i).filter(s => s === sig).length
195
+ return { sig, nth, top: blocks[i].getBoundingClientRect().top }
196
+ }
197
+ return null
198
+ }
199
+
200
+ /** Scroll so the block of `place` is where it was on screen. */
201
+ function keepPlace(place: ReturnType<typeof placeOf>, sigs: string[]) {
202
+ if (!place) return
203
+ let seen = 0
204
+ const i = sigs.findIndex(s => s === place.sig && seen++ === place.nth)
205
+ const el = main.children[i]
206
+ if (el) window.scrollBy(0, el.getBoundingClientRect().top - place.top)
207
+ }
208
+
209
+ /** The new render of the page, patched in. */
210
+ async function refresh() {
211
+ const next = await currentPage.render()
212
+ const data = next.data as Data
213
+ islands = data.islands
214
+ for (const href of data.styles) {
215
+ if (![...document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')].some(l => new URL(l.href).pathname === new URL(href, location.href).pathname))
216
+ document.head.insertAdjacentHTML('beforeend', String(html`<link rel="stylesheet" href="${href}">`))
217
+ }
218
+ const content = new DOMParser().parseFromString(next.html, 'text/html').getElementById('wb-main')?.innerHTML ?? ''
219
+ const nextSigs = signaturesOf(content)
220
+ const place = placeOf(nextSigs)
221
+ morph(content)
222
+ keepPlace(place, nextSigs)
223
+ const updated = document.getElementById('wb-updated')
224
+ if (updated && data.mtime) updated.dataset.ts = String(data.mtime)
225
+ if (next.title) core.title(next.title)
226
+ trackUpdate(main, blockSigs, nextSigs)
227
+ blockSigs = nextSigs
228
+ await mountIslands()
229
+ // islands that mounted just now can change the height of what is above the reader
230
+ keepPlace(place, nextSigs)
231
+ tickTimes()
232
+ // plugins put back what they add to the content
233
+ api.rendered()
234
+ }
235
+
236
+ let currentPage: PageHandle
237
+ let core: Api
238
+
239
+ const mount: PluginMount = async (root: HTMLElement, handle: PageHandle, coreApi: Api) => {
240
+ currentPage = handle
241
+ core = coreApi
242
+ page = handle.id
243
+ main = root.querySelector<HTMLElement>('#wb-main')!
244
+ islands = (handle.data as Data).islands
245
+ api = { ...core, theme: currentTheme, onTheme }
246
+ const isDir = handle.kind === 'pages' || handle.kind === 'folder'
247
+
248
+ themeToggle(root)
249
+ setInterval(tickTimes, 15000)
250
+ // islands rendered later (after async loading inside a component) still get mounted
251
+ new MutationObserver(() => {
252
+ if (main.querySelector('[data-wb-island]:not([data-wb-mounted])')) mountIslands()
253
+ }).observe(main, { childList: true, subtree: true })
254
+
255
+ handle.onChange(() => refresh())
256
+ // the overview shows when pages were last answered
257
+ if (isDir) core.onEvents(() => refresh())
258
+ // the overview shows which pages an agent is waiting on
259
+ if (isDir) core.onListeners(() => refresh())
260
+
261
+ blockSigs = [...main.children].map(signature)
262
+ if (!isDir) trackInitial(main, page, core)
263
+ if (!isDir) trackWaiting(main, core)
264
+ trackElsewhere(root, handle, core)
265
+ trackLive(root, handle, core)
266
+ if (isDir) { trackSorts(); core.onRendered(applySorts) }
267
+ if (!isDir) trackOrphanThreads(main, core)
268
+ await mountIslands()
269
+ tickTimes()
270
+ }
271
+
272
+ export default mount
@@ -0,0 +1,46 @@
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: the agent can still answer in one (`whiteboard append --type chat:message`).
5
+ import type { Api, WbEvent } from '../../define.ts'
6
+ import { html } from '../../html.ts'
7
+
8
+ /** A message in a chat: the chat block's event. */
9
+ const isMessage = (e: WbEvent) => e.type === 'chat:message' && typeof e.data.chat === 'string'
10
+
11
+ export function trackOrphanThreads(main: HTMLElement, api: Api) {
12
+ // after the page's content, not in it: #wb-main is compared block by block on every update
13
+ const box = document.createElement('section')
14
+ box.className = 'wb-orphans'
15
+ box.hidden = true
16
+ main.after(box)
17
+
18
+ function draw() {
19
+ // the chats on the page: one under every form, and the chat blocks
20
+ const onPage = new Set([
21
+ ...[...main.querySelectorAll('form[name]')].map(f => f.getAttribute('name')),
22
+ ...[...main.querySelectorAll('[data-chat]')].map(c => c.getAttribute('data-chat')),
23
+ ])
24
+ const threads = new Map<string, WbEvent[]>()
25
+ for (const e of api.events()) {
26
+ const chat = String(e.data.chat)
27
+ if (!isMessage(e) || onPage.has(chat)) continue
28
+ threads.set(chat, [...(threads.get(chat) ?? []), e])
29
+ }
30
+ box.hidden = threads.size === 0
31
+ if (box.hidden) return box.replaceChildren()
32
+ box.innerHTML = String(html`<h2>Chats no longer on this page</h2>
33
+ ${[...threads].map(([chat, messages]) => {
34
+ // a message can take the place of an earlier one (`replaces`), to correct it
35
+ const replaced = new Set(messages.map(m => m.data.replaces).filter(Boolean).map(String))
36
+ return html`<div class="wb-orphan" data-chat="${chat}"><h3>${chat}</h3>${messages.filter(m => !replaced.has(m.id)).map(m => {
37
+ const who = m.from === 'cli' ? 'agent' : 'you'
38
+ return html`<div class="wb-orphan-message" data-from="${who}"><span class="wb-orphan-who">${who}</span><span class="wb-orphan-text">${String(m.data.text ?? '')}</span></div>`
39
+ })}</div>`
40
+ })}`)
41
+ }
42
+
43
+ api.onEvents(draw)
44
+ api.onRendered(draw)
45
+ draw()
46
+ }
@@ -0,0 +1,38 @@
1
+ // A list the reader can sort: a `<select data-wb-sort="<name>">` sorts the `ul` after its heading
2
+ // by what each `li` carries (`data-order`, `data-updated`, `data-title`: the overview's documents).
3
+ // The choice is kept per list in this browser, and put back after a live update, which writes the
4
+ // list again in the server's order.
5
+ const KEY = (name: string) => `wb-sort:${name}`
6
+
7
+ function sortList(select: HTMLSelectElement) {
8
+ const list = select.closest('section')?.querySelector('ul')
9
+ if (!list) return
10
+ const by = select.value
11
+ const value = (li: HTMLElement) => by === 'title' ? li.dataset.title ?? '' : Number(by === 'updated' ? li.dataset.updated : li.dataset.order)
12
+ const rows = [...list.children] as HTMLElement[]
13
+ rows.sort((a, b) => {
14
+ const x = value(a), y = value(b)
15
+ if (by === 'updated') return (y as number) - (x as number)
16
+ return typeof x === 'string' ? x.localeCompare(y as string) : (x as number) - (y as number)
17
+ })
18
+ list.append(...rows)
19
+ }
20
+
21
+ export function applySorts() {
22
+ for (const select of document.querySelectorAll<HTMLSelectElement>('select[data-wb-sort]')) {
23
+ let kept: string | null = null
24
+ try { kept = localStorage.getItem(KEY(select.dataset.wbSort!)) } catch { /* private window */ }
25
+ if (kept && [...select.options].some(o => o.value === kept)) select.value = kept
26
+ sortList(select)
27
+ }
28
+ }
29
+
30
+ export function trackSorts() {
31
+ document.addEventListener('change', e => {
32
+ const select = e.target as HTMLSelectElement
33
+ if (!select.matches?.('select[data-wb-sort]')) return
34
+ try { localStorage.setItem(KEY(select.dataset.wbSort!), select.value) } catch { /* private window */ }
35
+ sortList(select)
36
+ })
37
+ applySorts()
38
+ }