@bigmistqke/whiteboard 0.0.0-stage → 0.1.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 (138) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +609 -2
  3. package/bin/whiteboard.ts +431 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/whiteboard.js +471 -0
  6. package/dist/client/runtime.js +391 -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 +45 -0
  12. package/dist/plugins/chat/client.js +3 -0
  13. package/dist/plugins/chat/index.js +46 -0
  14. package/dist/plugins/chat/style.css +17 -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 +64 -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 +51 -0
  22. package/dist/plugins/comments/style.css +32 -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/form/README.md +111 -0
  27. package/dist/plugins/form/index.js +102 -0
  28. package/dist/plugins/form/style.css +41 -0
  29. package/dist/plugins/gallery/README.md +30 -0
  30. package/dist/plugins/gallery/client.js +1 -0
  31. package/dist/plugins/gallery/index.js +74 -0
  32. package/dist/plugins/gallery/style.css +27 -0
  33. package/dist/plugins/grid/README.md +33 -0
  34. package/dist/plugins/grid/index.js +33 -0
  35. package/dist/plugins/grid/style.css +25 -0
  36. package/dist/plugins/index.js +26 -0
  37. package/dist/plugins/mermaid/README.md +21 -0
  38. package/dist/plugins/mermaid/index.js +34 -0
  39. package/dist/plugins/mermaid/style.css +16 -0
  40. package/dist/plugins/quiet/README.md +26 -0
  41. package/dist/plugins/quiet/index.js +17 -0
  42. package/dist/plugins/terminal/client.js +41 -0
  43. package/dist/plugins/terminal/host.js +332 -0
  44. package/dist/plugins/terminal/index.js +171 -0
  45. package/dist/plugins/terminal/modes.js +32 -0
  46. package/dist/plugins/terminal/server.js +256 -0
  47. package/dist/plugins/terminal/sizes.js +57 -0
  48. package/dist/plugins/terminal/style.css +357 -0
  49. package/dist/solid/index.js +35 -0
  50. package/dist/src/auth.js +54 -0
  51. package/dist/src/client/page/base.css +274 -0
  52. package/dist/src/client/page/main.js +1004 -0
  53. package/dist/src/config.js +76 -0
  54. package/dist/src/events.js +162 -0
  55. package/dist/src/html.js +34 -0
  56. package/dist/src/load.js +77 -0
  57. package/dist/src/loader.js +120 -0
  58. package/dist/src/package.js +33 -0
  59. package/dist/src/pages/blocks.js +49 -0
  60. package/dist/src/pages/index.js +14 -0
  61. package/dist/src/pages/markdown.js +307 -0
  62. package/dist/src/pages/render.js +257 -0
  63. package/dist/src/plugins.js +238 -0
  64. package/dist/src/running.js +24 -0
  65. package/dist/src/serve.js +71 -0
  66. package/dist/src/server.js +700 -0
  67. package/dist/src/status.js +43 -0
  68. package/package.json +131 -4
  69. package/plugins/callout/README.md +13 -0
  70. package/plugins/callout/index.ts +25 -0
  71. package/plugins/callout/style.css +12 -0
  72. package/plugins/chat/README.md +45 -0
  73. package/plugins/chat/autosize.ts +101 -0
  74. package/plugins/chat/client.tsx +81 -0
  75. package/plugins/chat/index.ts +61 -0
  76. package/plugins/chat/style.css +17 -0
  77. package/plugins/claude-code/index.ts +136 -0
  78. package/plugins/code/README.md +42 -0
  79. package/plugins/code/diff.ts +58 -0
  80. package/plugins/code/index.ts +94 -0
  81. package/plugins/code/style.css +29 -0
  82. package/plugins/comments/client.ts +448 -0
  83. package/plugins/comments/index.ts +52 -0
  84. package/plugins/comments/style.css +32 -0
  85. package/plugins/details/README.md +17 -0
  86. package/plugins/details/index.ts +21 -0
  87. package/plugins/details/style.css +3 -0
  88. package/plugins/form/README.md +111 -0
  89. package/plugins/form/index.ts +104 -0
  90. package/plugins/form/style.css +41 -0
  91. package/plugins/gallery/README.md +30 -0
  92. package/plugins/gallery/client.tsx +64 -0
  93. package/plugins/gallery/index.ts +67 -0
  94. package/plugins/gallery/style.css +27 -0
  95. package/plugins/grid/README.md +33 -0
  96. package/plugins/grid/index.ts +36 -0
  97. package/plugins/grid/style.css +25 -0
  98. package/plugins/index.ts +19 -0
  99. package/plugins/mermaid/README.md +21 -0
  100. package/plugins/mermaid/index.ts +39 -0
  101. package/plugins/mermaid/style.css +16 -0
  102. package/plugins/quiet/README.md +26 -0
  103. package/plugins/quiet/index.ts +27 -0
  104. package/plugins/terminal/client.ts +317 -0
  105. package/plugins/terminal/host.ts +326 -0
  106. package/plugins/terminal/index.ts +138 -0
  107. package/plugins/terminal/modes.ts +30 -0
  108. package/plugins/terminal/server.ts +215 -0
  109. package/plugins/terminal/sizes.ts +60 -0
  110. package/plugins/terminal/style.css +71 -0
  111. package/skills/whiteboard/SKILL.md +292 -0
  112. package/solid/index.tsx +56 -0
  113. package/src/auth.ts +66 -0
  114. package/src/client/forms.ts +186 -0
  115. package/src/client/page/base.css +274 -0
  116. package/src/client/page/fresh.ts +205 -0
  117. package/src/client/page/main.ts +249 -0
  118. package/src/client/page/orphans.ts +46 -0
  119. package/src/client/page/theme.ts +32 -0
  120. package/src/client/page/view.ts +9 -0
  121. package/src/client/page/waiting.ts +109 -0
  122. package/src/client/runtime.ts +170 -0
  123. package/src/config.ts +96 -0
  124. package/src/define.ts +546 -0
  125. package/src/events.ts +194 -0
  126. package/src/html.ts +40 -0
  127. package/src/load.ts +89 -0
  128. package/src/loader.ts +109 -0
  129. package/src/package.ts +39 -0
  130. package/src/pages/blocks.ts +67 -0
  131. package/src/pages/index.ts +36 -0
  132. package/src/pages/markdown.ts +276 -0
  133. package/src/pages/render.ts +196 -0
  134. package/src/plugins.ts +197 -0
  135. package/src/running.ts +22 -0
  136. package/src/serve.ts +52 -0
  137. package/src/server.ts +644 -0
  138. package/src/status.ts +69 -0
@@ -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,249 @@
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 { trackOrphanThreads } from './orphans'
12
+ import { html } from '../../html.ts'
13
+
14
+ interface Island { block: string; client: string; props: unknown }
15
+ interface Data { islands: Record<string, Island>; styles: string[]; mtime: number | null }
16
+
17
+ let main: HTMLElement
18
+ let page = ''
19
+ let api: ClientApi
20
+ let islands: Record<string, Island> = {}
21
+ const disposers = new Map<Element, () => void>()
22
+
23
+ // ---- islands -----------------------------------------------------------------------------------
24
+
25
+ async function mountOne(el: HTMLElement) {
26
+ const island = islands[el.dataset.wbIsland!]
27
+ el.dataset.wbMounted = ''
28
+ if (!island) return
29
+ try {
30
+ const mod = await import(island.client)
31
+ if (!el.isConnected) return
32
+ const mount: Mount = mod.default
33
+ if (typeof mount !== 'function') throw new Error('the client module must export a mount(element, props, api) function as default')
34
+ el.replaceChildren()
35
+ const dispose = await mount(el, island.props, api)
36
+ if (typeof dispose === 'function') disposers.set(el, dispose)
37
+ } catch (err) {
38
+ console.error(`island ${island.block}:`, err)
39
+ el.insertAdjacentHTML('afterbegin', String(html`<pre class="wb-error">block "${island.block}" failed to mount: ${(err as Error).message}</pre>`))
40
+ }
41
+ }
42
+
43
+ /** Mount islands outermost first; nested islands show up once their parent has rendered. */
44
+ async function mountIslands(root: ParentNode = main): Promise<void> {
45
+ for (;;) {
46
+ const pending = [...root.querySelectorAll<HTMLElement>('[data-wb-island]:not([data-wb-mounted])')]
47
+ .filter(el => !el.parentElement?.closest('[data-wb-island]:not([data-wb-mounted])'))
48
+ if (!pending.length) return
49
+ await Promise.all(pending.map(mountOne))
50
+ }
51
+ }
52
+
53
+ function disposeWithin(node: Node) {
54
+ for (const [el, dispose] of disposers) {
55
+ if (node === el || node.contains(el)) { dispose(); disposers.delete(el) }
56
+ }
57
+ }
58
+
59
+
60
+ // ---- theme -------------------------------------------------------------------------------------
61
+
62
+ const NEXT: Record<ThemePreference, ThemePreference> = { auto: 'light', light: 'dark', dark: 'auto' }
63
+ function themeToggle(root: HTMLElement) {
64
+ const button = root.querySelector<HTMLButtonElement>('.wb-theme')
65
+ if (!button) return
66
+ button.textContent = themePreference()
67
+ button.addEventListener('click', () => {
68
+ setThemePreference(NEXT[themePreference()])
69
+ button.textContent = themePreference()
70
+ })
71
+ }
72
+
73
+ // ---- time --------------------------------------------------------------------------------------
74
+
75
+ function ago(ts: number) {
76
+ const s = Math.round((Date.now() - ts) / 1000)
77
+ if (s < 10) return 'just now'
78
+ if (s < 60) return `${s}s ago`
79
+ if (s < 3600) return `${Math.round(s / 60)}m ago`
80
+ if (s < 86400) return `${Math.round(s / 3600)}h ago`
81
+ return new Date(ts).toLocaleDateString()
82
+ }
83
+ function tickTimes() {
84
+ for (const t of document.querySelectorAll<HTMLTimeElement>('time[data-ts]')) {
85
+ const ts = Number(t.dataset.ts)
86
+ t.textContent = ago(ts)
87
+ t.title = new Date(ts).toLocaleString()
88
+ }
89
+ }
90
+
91
+ // ---- live reload -------------------------------------------------------------------------------
92
+
93
+ let blockSigs: string[] = []
94
+
95
+ const FIELD = (n: Element): n is HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement =>
96
+ n instanceof HTMLInputElement || n instanceof HTMLTextAreaElement || n instanceof HTMLSelectElement
97
+ const KEEP_CLASSES = ['wb-new', 'wb-new-seen']
98
+
99
+ /** Patch the page in place: focus, caret, typed values, open <details> and unchanged islands survive. */
100
+ /**
101
+ * A <details> element's identity across renders: its summary, the nearest heading above its
102
+ * top-level block, and how many before it share both. Blocks are matched by position when the page
103
+ * updates, so a block inserted above an open section would otherwise pair it with a different
104
+ * element and close it; this finds the same section wherever it moved.
105
+ */
106
+ function detailsKeys(root: HTMLElement): Map<HTMLDetailsElement, string> {
107
+ const keys = new Map<HTMLDetailsElement, string>()
108
+ const seen = new Map<string, number>()
109
+ for (const el of root.querySelectorAll('details')) {
110
+ let block: Element = el
111
+ while (block.parentElement && block.parentElement !== root) block = block.parentElement
112
+ let heading = ''
113
+ for (let b: Element | null = block; b; b = b.previousElementSibling) {
114
+ if (/^H[1-6]$/.test(b.tagName)) { heading = b.textContent?.trim() ?? ''; break }
115
+ }
116
+ const base = `${heading}\u0000${el.querySelector(':scope > summary')?.textContent?.trim() ?? ''}`
117
+ const n = seen.get(base) ?? 0
118
+ seen.set(base, n + 1)
119
+ keys.set(el, `${base}\u0000${n}`)
120
+ }
121
+ return keys
122
+ }
123
+
124
+ function morph(html: string) {
125
+ const open = new Set<string>()
126
+ for (const [el, key] of detailsKeys(main)) if (el.open) open.add(key)
127
+ const next = main.cloneNode(false) as HTMLElement
128
+ next.innerHTML = html
129
+ for (const [el, key] of detailsKeys(next)) el.open = open.has(key)
130
+ morphdom(main, next, {
131
+ getNodeKey: n => (n as HTMLElement).dataset?.wbKey || (n as HTMLElement).id || undefined,
132
+ onBeforeElUpdated(from, to) {
133
+ if (from.dataset.wbKey) {
134
+ if (from.dataset.wbKey === to.dataset.wbKey && 'wbMounted' in from.dataset) {
135
+ from.dataset.wbIsland = to.dataset.wbIsland // ids are per render; the key is what's stable
136
+ return false
137
+ }
138
+ disposeWithin(from)
139
+ }
140
+ if (FIELD(from)) {
141
+ if (from === document.activeElement) return false
142
+ ;(to as typeof from).value = from.value
143
+ if (from instanceof HTMLInputElement) (to as HTMLInputElement).checked = from.checked
144
+ }
145
+ // <details> open state was set on the new tree by detailsKeys(), matched by identity, not position
146
+ // what a plugin marked on an element (`data-wb-*`) stays, unless the new render sets it;
147
+ // data-wb-mounted is the page's own, and a replaced island must mount afresh
148
+ for (const { name, value } of [...from.attributes])
149
+ if (name.startsWith('data-wb-') && name !== 'data-wb-mounted' && !to.hasAttribute(name)) to.setAttribute(name, value)
150
+ for (const c of KEEP_CLASSES) if (from.classList.contains(c)) to.classList.add(c)
151
+ return true
152
+ },
153
+ onBeforeNodeDiscarded(node) {
154
+ disposeWithin(node)
155
+ return true
156
+ },
157
+ })
158
+ }
159
+
160
+ // The page keeps the reader's place itself: the browser's own scroll anchoring loses its anchor
161
+ // when an update replaces elements, so it is turned off to keep the two from both correcting.
162
+ document.documentElement.style.overflowAnchor = 'none'
163
+
164
+ /**
165
+ * The reader's place before an update: the first block in view that the update keeps (by
166
+ * signature, and which of the blocks with that signature it is), and where it is on screen.
167
+ */
168
+ function placeOf(nextSigs: string[]) {
169
+ const keep = new Set(nextSigs)
170
+ const blocks = [...main.children]
171
+ for (let i = 0; i < blocks.length; i++) {
172
+ const sig = blockSigs[i]
173
+ if (!keep.has(sig) || blocks[i].getBoundingClientRect().bottom <= 0) continue
174
+ const nth = blockSigs.slice(0, i).filter(s => s === sig).length
175
+ return { sig, nth, top: blocks[i].getBoundingClientRect().top }
176
+ }
177
+ return null
178
+ }
179
+
180
+ /** Scroll so the block of `place` is where it was on screen. */
181
+ function keepPlace(place: ReturnType<typeof placeOf>, sigs: string[]) {
182
+ if (!place) return
183
+ let seen = 0
184
+ const i = sigs.findIndex(s => s === place.sig && seen++ === place.nth)
185
+ const el = main.children[i]
186
+ if (el) window.scrollBy(0, el.getBoundingClientRect().top - place.top)
187
+ }
188
+
189
+ /** The new render of the page, patched in. */
190
+ async function refresh() {
191
+ const next = await currentPage.render()
192
+ const data = next.data as Data
193
+ islands = data.islands
194
+ for (const href of data.styles) {
195
+ if (![...document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')].some(l => new URL(l.href).pathname === new URL(href, location.href).pathname))
196
+ document.head.insertAdjacentHTML('beforeend', String(html`<link rel="stylesheet" href="${href}">`))
197
+ }
198
+ const content = new DOMParser().parseFromString(next.html, 'text/html').getElementById('wb-main')?.innerHTML ?? ''
199
+ const nextSigs = signaturesOf(content)
200
+ const place = placeOf(nextSigs)
201
+ morph(content)
202
+ keepPlace(place, nextSigs)
203
+ const updated = document.getElementById('wb-updated')
204
+ if (updated && data.mtime) updated.dataset.ts = String(data.mtime)
205
+ if (next.title) core.title(next.title)
206
+ trackUpdate(main, blockSigs, nextSigs)
207
+ blockSigs = nextSigs
208
+ await mountIslands()
209
+ // islands that mounted just now can change the height of what is above the reader
210
+ keepPlace(place, nextSigs)
211
+ tickTimes()
212
+ // plugins put back what they add to the content
213
+ api.rendered()
214
+ }
215
+
216
+ let currentPage: PageHandle
217
+ let core: Api
218
+
219
+ const mount: PluginMount = async (root: HTMLElement, handle: PageHandle, coreApi: Api) => {
220
+ currentPage = handle
221
+ core = coreApi
222
+ page = handle.id
223
+ main = root.querySelector<HTMLElement>('#wb-main')!
224
+ islands = (handle.data as Data).islands
225
+ api = { ...core, theme: currentTheme, onTheme }
226
+ const isDir = handle.kind === 'pages' || handle.kind === 'folder'
227
+
228
+ themeToggle(root)
229
+ setInterval(tickTimes, 15000)
230
+ // islands rendered later (after async loading inside a component) still get mounted
231
+ new MutationObserver(() => {
232
+ if (main.querySelector('[data-wb-island]:not([data-wb-mounted])')) mountIslands()
233
+ }).observe(main, { childList: true, subtree: true })
234
+
235
+ handle.onChange(() => refresh())
236
+ // the overview shows when pages were last answered
237
+ if (isDir) core.onEvents(() => refresh())
238
+ // the overview shows which pages an agent is waiting on
239
+ if (isDir) core.onListeners(() => refresh())
240
+
241
+ blockSigs = [...main.children].map(signature)
242
+ if (!isDir) trackInitial(main, page, core)
243
+ if (!isDir) trackWaiting(main, core)
244
+ if (!isDir) trackOrphanThreads(main, core)
245
+ await mountIslands()
246
+ tickTimes()
247
+ }
248
+
249
+ 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,32 @@
1
+ // The page's light and dark theme: the reader's choice (kept in localStorage), else the system's.
2
+ import type { Theme } from '../../define.ts'
3
+
4
+ export type ThemePreference = Theme | 'auto'
5
+
6
+ const media = matchMedia('(prefers-color-scheme: dark)')
7
+ const listeners = new Set<(theme: Theme) => void>()
8
+ const resolve = (): Theme => (document.documentElement.dataset.theme as Theme | undefined) ?? (media.matches ? 'dark' : 'light')
9
+ let theme = resolve()
10
+
11
+ function update() {
12
+ const next = resolve()
13
+ if (next === theme) return
14
+ theme = next
15
+ for (const fn of listeners) fn(theme)
16
+ }
17
+ media.addEventListener('change', update)
18
+
19
+ export const currentTheme = () => theme
20
+ export function onTheme(fn: (theme: Theme) => void) { listeners.add(fn); return () => listeners.delete(fn) }
21
+
22
+ export const themePreference = (): ThemePreference => (document.documentElement.dataset.theme as Theme | undefined) ?? 'auto'
23
+
24
+ export function setThemePreference(pref: ThemePreference) {
25
+ if (pref === 'auto') delete document.documentElement.dataset.theme
26
+ else document.documentElement.dataset.theme = pref
27
+ try {
28
+ if (pref === 'auto') localStorage.removeItem('wb-theme')
29
+ else localStorage.setItem('wb-theme', pref)
30
+ } catch { /* the choice still applies to this visit */ }
31
+ update()
32
+ }
@@ -0,0 +1,9 @@
1
+ // The part of the window the page is seen in. The core may put something at the bottom of the
2
+ // window (the terminal drawer) and says how tall it is in `--wb-inset-bottom`; what is behind it is
3
+ // not in view, so measurements of what the reader sees stop above it.
4
+
5
+ /** The bottom of the visible part of the page, in window coordinates. */
6
+ export function viewBottom(): number {
7
+ const inset = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--wb-inset-bottom')) || 0
8
+ return Math.max(0, innerHeight - inset)
9
+ }
@@ -0,0 +1,109 @@
1
+ // How the page shows what an agent waits for. The core marks each named form with where it stands
2
+ // (waiting, unheard, pending, decided; see `api.onForms`); the page styles those marks (base.css),
3
+ // folds a decided form into one line quoting its answer, sums the states up in a line above the
4
+ // page, puts a button in the page's corner that jumps from one waiting form to the next, and counts
5
+ // the waiting ones in the tab title.
6
+ import type { Api, FormState, FormStatus } from '../../define.ts'
7
+ import { viewBottom } from './view'
8
+ import { STATES } from '../../status.ts'
9
+
10
+ const ORDER = STATES
11
+ const LABEL: Record<FormState, (n: number) => string> = {
12
+ waiting: n => `${n} waiting for you`,
13
+ unheard: n => `${n} nobody listening`,
14
+ pending: n => `${n} waiting for the agent`,
15
+ decided: n => `${n} decided`,
16
+ }
17
+
18
+ let main: HTMLElement
19
+ let api: Api
20
+ let forms: FormStatus[] = []
21
+
22
+ const button = document.createElement('button')
23
+ button.type = 'button'
24
+ button.className = 'wb-waiting-next'
25
+ button.hidden = true
26
+
27
+ // above the page's content, not in it: #wb-main is compared block by block on every update
28
+ const summary = document.createElement('div')
29
+ summary.className = 'wb-summary'
30
+ summary.hidden = true
31
+
32
+ // forms the reader opened again to change their answer, by name, with the answer they opened:
33
+ // they stay open until a newer answer is decided
34
+ const reopened = new Map<string, string>()
35
+
36
+ const inState = (state: FormState) => forms.filter(f => f.state === state && f.form.isConnected).map(f => f.form)
37
+
38
+ function show(list: FormStatus[]) {
39
+ forms = list
40
+ for (const { form, name, state, last } of forms) {
41
+ if (last && reopened.has(name) && reopened.get(name) !== last.id && state === 'decided') reopened.delete(name)
42
+ form.toggleAttribute('data-wb-folded', state === 'decided' && !reopened.has(name))
43
+ }
44
+ const parts = ORDER.map(state => [state, inState(state).length] as const).filter(([, count]) => count)
45
+ summary.hidden = !parts.length
46
+ summary.replaceChildren(...parts.flatMap(([state, count], i) => {
47
+ const link = document.createElement('button')
48
+ link.type = 'button'
49
+ link.dataset.state = state
50
+ link.textContent = LABEL[state](count)
51
+ return i ? [document.createTextNode(' · '), link] : [link]
52
+ }))
53
+ const n = inState('waiting').length
54
+ button.hidden = n === 0
55
+ button.textContent = `→ waiting for you (${n})`
56
+ api.badge('waiting', n ? `!${n}` : null, -1)
57
+ }
58
+
59
+ // The form a jump went to last, and where the page was scrolled then: jumping again in the same
60
+ // state goes to the one after it, round to the first. Once the reader scrolled themselves, the
61
+ // next one is the first below where they are.
62
+ let current: HTMLFormElement | null = null
63
+ let scrolledTo = 0
64
+
65
+ function next(state: FormState) {
66
+ const list = inState(state)
67
+ const i = current ? list.indexOf(current) : -1
68
+ if (i >= 0 && Math.abs(scrollY - scrolledTo) < 40) return list[(i + 1) % list.length]
69
+ return list.find(f => f.getBoundingClientRect().top > viewBottom() / 2) ?? list[0]
70
+ }
71
+
72
+ function jump(state: FormState) {
73
+ const form = next(state)
74
+ if (!form) return
75
+ current = form
76
+ // the form centred in the part of the window the page is seen in (above the terminal drawer),
77
+ // as far as the page allows
78
+ const r = form.getBoundingClientRect()
79
+ scrolledTo = Math.max(0, Math.min(scrollY + r.top + r.height / 2 - viewBottom() / 2, document.documentElement.scrollHeight - innerHeight))
80
+ scrollTo({ top: scrolledTo, behavior: 'smooth' })
81
+ if (state === 'waiting') form.querySelector<HTMLElement>('input:not([type=hidden]), textarea, select, button')?.focus({ preventScroll: true })
82
+ }
83
+
84
+ export function trackWaiting(root: HTMLElement, core: Api) {
85
+ main = root
86
+ api = core
87
+ api.corner().prepend(button)
88
+ button.addEventListener('click', () => jump('waiting'))
89
+ main.before(summary)
90
+ summary.addEventListener('click', e => {
91
+ const state = (e.target as HTMLElement).closest<HTMLElement>('button[data-state]')?.dataset.state as FormState | undefined
92
+ if (state) jump(state)
93
+ })
94
+ // a folded form opens again on a click, to change the answer; not on one in its thread, which
95
+ // stays open under it
96
+ main.addEventListener('click', e => {
97
+ const target = e.target as HTMLElement
98
+ const form = target.closest<HTMLFormElement>('form[data-wb-folded]')
99
+ if (!form || target.closest('[data-block=chat-thread]')) return
100
+ e.preventDefault()
101
+ const name = form.getAttribute('name')!
102
+ const last = api.last(name)
103
+ if (last) reopened.set(name, last.id)
104
+ show(forms)
105
+ form.querySelector<HTMLElement>('input:not([type=hidden]), textarea, select')?.focus({ preventScroll: true })
106
+ })
107
+ api.onForms(show)
108
+ show(api.forms())
109
+ }