@bigmistqke/whiteboard 0.3.0 → 0.4.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 (155) hide show
  1. package/README.md +67 -17
  2. package/bin/whiteboard.ts +268 -71
  3. package/dist/client/runtime.js +88 -41
  4. package/dist/define.js +21 -2
  5. package/dist/plugins/callout/index.js +3 -1
  6. package/dist/plugins/callout/public/style.css +30 -0
  7. package/dist/plugins/chat/index.js +7 -4
  8. package/dist/plugins/chat/{client.js → public/client.js} +1 -1
  9. package/dist/plugins/chat/public/style.css +98 -0
  10. package/dist/plugins/code/index.js +3 -1
  11. package/dist/plugins/code/public/style.css +68 -0
  12. package/dist/plugins/comments/index.js +4 -5
  13. package/dist/plugins/comments/public/client.js +19 -0
  14. package/dist/plugins/comments/public/style.css +185 -0
  15. package/dist/plugins/details/index.js +7 -2
  16. package/dist/plugins/details/public/style.css +7 -0
  17. package/dist/plugins/form/index.js +37 -8
  18. package/dist/plugins/form/public/style.css +126 -0
  19. package/dist/plugins/gallery/index.js +4 -3
  20. package/dist/plugins/gallery/public/client.js +1 -0
  21. package/dist/plugins/gallery/public/style.css +90 -0
  22. package/dist/plugins/grid/index.js +9 -3
  23. package/dist/plugins/grid/public/style.css +71 -0
  24. package/dist/plugins/iframe/index.js +13 -14
  25. package/dist/plugins/iframe/public/style.css +13 -0
  26. package/dist/plugins/index.js +3 -1
  27. package/dist/plugins/mermaid/index.js +3 -1
  28. package/dist/plugins/mermaid/{style.css → public/style.css} +7 -2
  29. package/dist/plugins/terminal/index.js +10 -9
  30. package/dist/plugins/terminal/{style.css → public/style.css} +199 -45
  31. package/dist/plugins/toc/README.md +12 -0
  32. package/dist/plugins/toc/index.js +9 -5
  33. package/dist/plugins/toc/public/client.js +1 -0
  34. package/dist/plugins/toc/public/style.css +93 -0
  35. package/dist/plugins/window/README.md +29 -0
  36. package/dist/plugins/window/index.js +64 -0
  37. package/dist/solid/index.js +14 -11
  38. package/dist/src/client/page/base.css +1078 -199
  39. package/dist/src/client/page/main.js +174 -32
  40. package/dist/src/loader.js +7 -2
  41. package/dist/src/package.js +3 -6
  42. package/dist/src/pages/blocks.js +8 -13
  43. package/dist/src/pages/markdown.js +1 -1
  44. package/dist/src/pages/render.js +73 -13
  45. package/dist/src/pages/window.js +30 -0
  46. package/dist/src/public.js +24 -0
  47. package/dist/src/server.js +37 -15
  48. package/package.json +3 -1
  49. package/plugins/callout/index.ts +3 -1
  50. package/plugins/callout/public/style.css +30 -0
  51. package/plugins/chat/autosize.ts +43 -9
  52. package/plugins/chat/client.tsx +22 -5
  53. package/plugins/chat/index.ts +22 -8
  54. package/plugins/chat/public/style.css +98 -0
  55. package/plugins/claude-code/index.ts +49 -14
  56. package/plugins/code/diff.ts +28 -8
  57. package/plugins/code/index.ts +30 -20
  58. package/plugins/code/public/style.css +68 -0
  59. package/plugins/comments/client.ts +139 -71
  60. package/plugins/comments/index.ts +9 -7
  61. package/plugins/comments/public/style.css +185 -0
  62. package/plugins/details/index.ts +7 -2
  63. package/plugins/details/public/style.css +7 -0
  64. package/plugins/forge/index.ts +16 -3
  65. package/plugins/form/index.ts +75 -27
  66. package/plugins/form/public/style.css +126 -0
  67. package/plugins/gallery/client.tsx +9 -3
  68. package/plugins/gallery/index.ts +31 -9
  69. package/plugins/gallery/public/style.css +90 -0
  70. package/plugins/grid/index.ts +19 -5
  71. package/plugins/grid/public/style.css +71 -0
  72. package/plugins/iframe/index.ts +20 -23
  73. package/plugins/iframe/public/style.css +13 -0
  74. package/plugins/index.ts +16 -1
  75. package/plugins/mermaid/index.ts +3 -1
  76. package/plugins/mermaid/{style.css → public/style.css} +7 -2
  77. package/plugins/terminal/client.ts +105 -48
  78. package/plugins/terminal/host.ts +131 -29
  79. package/plugins/terminal/index.ts +84 -25
  80. package/plugins/terminal/public/style.css +225 -0
  81. package/plugins/terminal/server.ts +64 -13
  82. package/plugins/terminal/sizes.ts +13 -3
  83. package/plugins/toc/README.md +12 -0
  84. package/plugins/toc/client.ts +58 -29
  85. package/plugins/toc/index.ts +22 -5
  86. package/plugins/toc/public/style.css +93 -0
  87. package/plugins/window/README.md +29 -0
  88. package/plugins/window/index.ts +85 -0
  89. package/skills/whiteboard/SKILL.md +3 -1
  90. package/solid/index.tsx +24 -9
  91. package/src/auth.ts +25 -7
  92. package/src/client/forms.ts +74 -28
  93. package/src/client/markdown.ts +15 -4
  94. package/src/client/page/base.css +1078 -199
  95. package/src/client/page/elsewhere.ts +32 -15
  96. package/src/client/page/fresh.ts +91 -23
  97. package/src/client/page/hold.ts +11 -2
  98. package/src/client/page/live.ts +10 -6
  99. package/src/client/page/main.ts +106 -34
  100. package/src/client/page/orphans.ts +25 -10
  101. package/src/client/page/sort.ts +14 -4
  102. package/src/client/page/sticky.ts +11 -3
  103. package/src/client/page/theme.ts +11 -7
  104. package/src/client/page/waiting.ts +141 -34
  105. package/src/client/page/window.ts +40 -0
  106. package/src/client/reactive.ts +19 -0
  107. package/src/client/read.ts +17 -10
  108. package/src/client/runtime.ts +130 -35
  109. package/src/client/scroll.ts +14 -4
  110. package/src/client/toast.ts +19 -5
  111. package/src/config.ts +20 -5
  112. package/src/define.ts +67 -23
  113. package/src/events.ts +111 -24
  114. package/src/html.ts +6 -2
  115. package/src/icons.ts +4 -2
  116. package/src/load.ts +10 -2
  117. package/src/loader.ts +75 -11
  118. package/src/package.ts +9 -8
  119. package/src/pages/blocks.ts +20 -14
  120. package/src/pages/markdown.ts +113 -34
  121. package/src/pages/render.ts +198 -37
  122. package/src/pages/window.ts +71 -0
  123. package/src/plugins.ts +90 -24
  124. package/src/public.ts +39 -0
  125. package/src/running.ts +8 -2
  126. package/src/serve.ts +29 -7
  127. package/src/server.ts +351 -108
  128. package/src/status.ts +15 -9
  129. package/dist/plugins/callout/style.css +0 -12
  130. package/dist/plugins/chat/style.css +0 -24
  131. package/dist/plugins/code/style.css +0 -29
  132. package/dist/plugins/comments/client.js +0 -10
  133. package/dist/plugins/comments/style.css +0 -40
  134. package/dist/plugins/details/style.css +0 -3
  135. package/dist/plugins/form/style.css +0 -44
  136. package/dist/plugins/gallery/client.js +0 -1
  137. package/dist/plugins/gallery/style.css +0 -27
  138. package/dist/plugins/grid/style.css +0 -25
  139. package/dist/plugins/iframe/client.js +0 -1
  140. package/dist/plugins/iframe/style.css +0 -29
  141. package/dist/plugins/toc/client.js +0 -1
  142. package/dist/plugins/toc/style.css +0 -19
  143. package/plugins/callout/style.css +0 -12
  144. package/plugins/chat/style.css +0 -24
  145. package/plugins/code/style.css +0 -29
  146. package/plugins/comments/style.css +0 -40
  147. package/plugins/details/style.css +0 -3
  148. package/plugins/form/style.css +0 -44
  149. package/plugins/gallery/style.css +0 -27
  150. package/plugins/grid/style.css +0 -25
  151. package/plugins/iframe/client.ts +0 -46
  152. package/plugins/iframe/style.css +0 -29
  153. package/plugins/terminal/style.css +0 -71
  154. package/plugins/toc/style.css +0 -19
  155. /package/dist/plugins/terminal/{client.js → public/client.js} +0 -0
@@ -12,7 +12,8 @@ export const WAITING_HASH = '#wb-waiting'
12
12
  const box = document.createElement('div')
13
13
  box.className = 'wb-elsewhere'
14
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>'
15
+ box.innerHTML =
16
+ '<button type="button" class="wb-elsewhere-toggle wb-awaiting" aria-haspopup="true" aria-expanded="false"></button><ul class="wb-elsewhere-list" hidden></ul>'
16
17
  const toggle = box.querySelector('button')!
17
18
  // an inbox, and how many questions wait in it
18
19
  toggle.innerHTML = `${INBOX_ICON}<span class="wb-elsewhere-count"></span>`
@@ -28,7 +29,11 @@ let current = ''
28
29
 
29
30
  async function load() {
30
31
  let pages: PageStatus[]
31
- try { pages = await (await fetch('/api/status', { cache: 'no-store' })).json() } catch { return }
32
+ try {
33
+ pages = await (await fetch('/api/status', { cache: 'no-store' })).json()
34
+ } catch {
35
+ return
36
+ }
32
37
  const waiting = pages
33
38
  .filter(p => p.page !== current)
34
39
  .map(p => ({ p, n: awaiting(p) }))
@@ -39,19 +44,24 @@ async function load() {
39
44
  count.textContent = String(total)
40
45
  toggle.title = awaitingLabel(total, ` on ${waiting.length === 1 ? 'another page' : `${waiting.length} other pages`}`)
41
46
  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
- }))
47
+ list.replaceChildren(
48
+ ...waiting.map(({ p, n }) => {
49
+ const li = document.createElement('li')
50
+ const a = document.createElement('a')
51
+ a.href = `/${p.page.split('/').map(encodeURIComponent).join('/')}${WAITING_HASH}`
52
+ a.textContent = `${p.title} (${n})`
53
+ li.append(a)
54
+ return li
55
+ }),
56
+ )
50
57
  }
51
58
 
52
59
  // several changes at once (an answer is an event and a listener less) load once
53
60
  let timer = 0
54
- const reload = () => { clearTimeout(timer); timer = window.setTimeout(load, 100) }
61
+ const reload = () => {
62
+ clearTimeout(timer)
63
+ timer = window.setTimeout(load, 100)
64
+ }
55
65
 
56
66
  export function trackElsewhere(root: HTMLElement, handle: PageHandle, core: Api) {
57
67
  current = handle.id
@@ -59,12 +69,19 @@ export function trackElsewhere(root: HTMLElement, handle: PageHandle, core: Api)
59
69
  if (!nav) return
60
70
  nav.querySelector('.wb-theme')?.before(box)
61
71
  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() } })
72
+ document.addEventListener('click', e => {
73
+ if (!box.contains(e.target as Node)) open(false)
74
+ })
75
+ document.addEventListener('keydown', e => {
76
+ if (e.key === 'Escape' && !list.hidden) {
77
+ open(false)
78
+ toggle.focus()
79
+ }
80
+ })
64
81
  // what waits changes with an answer (events), a wait starting or ending (listeners), and a page's
65
82
  // forms (a page changed)
66
- core.onEvents(reload)
67
- core.onListeners(reload)
83
+ core.events.on(reload)
84
+ core.listeners.on(reload)
68
85
  handle.onChange(reload)
69
86
  load()
70
87
  }
@@ -17,19 +17,37 @@ let storeKey = ''
17
17
  // set by trackInitial: a page that tracks nothing (the overview) has no bubbles
18
18
  let core: Api | undefined
19
19
 
20
+ // the data-wb-* attributes the server writes into a page; every other one is the browser's (a
21
+ // form's state, a mark, a key), and not part of what the server sent
22
+ const SERVER_MARKS = new Set([
23
+ 'data-wb-at',
24
+ 'data-wb-key',
25
+ 'data-wb-maximize',
26
+ 'data-wb-other',
27
+ 'data-wb-other-text',
28
+ 'data-wb-quiet',
29
+ 'data-wb-self',
30
+ 'data-wb-sort',
31
+ ])
32
+
20
33
  /**
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.
34
+ * FNV-1a over the block's HTML as the server sent it, ignoring anything quiet: content inside
35
+ * [data-wb-quiet] can appear, change or go without the block counting as changed. What the browser
36
+ * added is left out, so a block in the page and the same block in a new render have one signature:
37
+ * an island's content (it draws itself; its props are in its key), the page's own elements (a folded
38
+ * form's card), its marks (data-wb-* the server doesn't write: a form's state) and its classes for
39
+ * new content.
23
40
  */
24
41
  export function signature(el: Element): string {
25
42
  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')
43
+ for (const q of clone.querySelectorAll('[data-wb-quiet], .wb-folded')) q.remove()
44
+ for (const n of [clone, ...clone.querySelectorAll('*')]) {
45
+ for (const { name } of [...n.attributes])
46
+ if (name.startsWith('data-wb-') && !SERVER_MARKS.has(name)) n.removeAttribute(name)
47
+ n.classList.remove('wb-new', 'wb-new-seen')
48
+ if (!n.classList.length) n.removeAttribute('class')
30
49
  }
31
- // the page's key for the block (main.ts), not its content
32
- clone.removeAttribute('data-wb-block')
50
+ for (const island of clone.querySelectorAll('[data-wb-key]')) island.replaceChildren()
33
51
  const s = clone.outerHTML
34
52
  let h = 0x811c9dc5
35
53
  for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193)
@@ -47,14 +65,21 @@ function loadSeen(): Set<string> | null {
47
65
  try {
48
66
  const raw = localStorage.getItem(storeKey)
49
67
  return raw ? new Set(JSON.parse(raw)) : null
50
- } catch { return null }
68
+ } catch {
69
+ return null
70
+ }
51
71
  }
52
72
 
53
73
  function saveSeen(main: HTMLElement) {
54
74
  try {
55
- const seen = [...main.children].filter(el => !unseen.has(el)).map(el => sigOf.get(el)).filter(Boolean)
75
+ const seen = [...main.children]
76
+ .filter(el => !unseen.has(el))
77
+ .map(el => sigOf.get(el))
78
+ .filter(Boolean)
56
79
  localStorage.setItem(storeKey, JSON.stringify(seen))
57
- } catch { /* storage unavailable: tracking still works for this visit */ }
80
+ } catch {
81
+ /* storage unavailable: tracking still works for this visit */
82
+ }
58
83
  }
59
84
 
60
85
  // ---- seen detection ----------------------------------------------------------------------------
@@ -76,10 +101,20 @@ function inView(el: Element) {
76
101
  function check() {
77
102
  const active = document.visibilityState === 'visible'
78
103
  for (const el of unseen) {
79
- if (!el.isConnected) { unseen.delete(el); continue }
104
+ if (!el.isConnected) {
105
+ unseen.delete(el)
106
+ continue
107
+ }
80
108
  const pending = timers.has(el)
81
109
  if (active && inView(el)) {
82
- if (!pending) timers.set(el, window.setTimeout(() => { timers.delete(el); markSeen(el) }, DWELL_MS))
110
+ if (!pending)
111
+ timers.set(
112
+ el,
113
+ window.setTimeout(() => {
114
+ timers.delete(el)
115
+ markSeen(el)
116
+ }, DWELL_MS),
117
+ )
83
118
  } else if (pending) {
84
119
  clearTimeout(timers.get(el))
85
120
  timers.delete(el)
@@ -88,11 +123,16 @@ function check() {
88
123
  }
89
124
 
90
125
  let checkFrame = 0
91
- const scheduleCheck = () => { cancelAnimationFrame(checkFrame); checkFrame = requestAnimationFrame(check) }
126
+ const scheduleCheck = () => {
127
+ cancelAnimationFrame(checkFrame)
128
+ checkFrame = requestAnimationFrame(check)
129
+ }
92
130
  addEventListener('scroll', scheduleCheck, { passive: true })
93
131
  addEventListener('resize', scheduleCheck)
94
132
  document.addEventListener('visibilitychange', scheduleCheck)
95
- setInterval(() => { if (unseen.size) check() }, 500)
133
+ setInterval(() => {
134
+ if (unseen.size) check()
135
+ }, 500)
96
136
 
97
137
  function markSeen(el: Element) {
98
138
  if (!unseen.delete(el)) return
@@ -119,9 +159,13 @@ let upToast: Toast | null = null
119
159
  let downToast: Toast | null = null
120
160
 
121
161
  function split() {
122
- const above: Element[] = [], below: Element[] = []
162
+ const above: Element[] = [],
163
+ below: Element[] = []
123
164
  for (const el of unseen) {
124
- if (!el.isConnected) { unseen.delete(el); continue }
165
+ if (!el.isConnected) {
166
+ unseen.delete(el)
167
+ continue
168
+ }
125
169
  const r = el.getBoundingClientRect()
126
170
  if (r.bottom < 60) above.push(el)
127
171
  else if (r.top > viewBottom()) below.push(el)
@@ -137,9 +181,15 @@ function update() {
137
181
  cancelAnimationFrame(raf)
138
182
  raf = requestAnimationFrame(() => {
139
183
  const { above, below } = split()
140
- for (const [toast, list, arrow] of [[upToast, above, '↑'], [downToast, below, '↓']] as const) {
184
+ for (const [toast, list, arrow] of [
185
+ [upToast, above, '↑'],
186
+ [downToast, below, '↓'],
187
+ ] as const) {
141
188
  if (!toast) continue
142
- if (list.length) { toast.update(`${arrow} new (${list.length})`); toast.show() } else toast.hide()
189
+ if (list.length) {
190
+ toast.update(`${arrow} new (${list.length})`)
191
+ toast.show()
192
+ } else toast.hide()
143
193
  }
144
194
  core?.badge('new', unseen.size ? String(unseen.size) : null)
145
195
  })
@@ -149,7 +199,9 @@ function go(dir: 'up' | 'down') {
149
199
  const { above, below } = split()
150
200
  ;(dir === 'up' ? above : below)[0]?.scrollIntoView({ behavior: 'smooth', block: 'start' })
151
201
  }
152
- const seeAll = () => { for (const el of [...unseen]) markSeen(el) }
202
+ const seeAll = () => {
203
+ for (const el of [...unseen]) markSeen(el)
204
+ }
153
205
  addEventListener('scroll', update, { passive: true })
154
206
  addEventListener('resize', update)
155
207
 
@@ -165,8 +217,22 @@ const RECOGNISED_MIN = 0.25
165
217
  */
166
218
  export function trackInitial(main: HTMLElement, page: string, api: Api) {
167
219
  core = api
168
- upToast = api.toast('', { ms: 0, kind: 'alert', name: 'new-up', order: 1, onClick: () => go('up'), onDismiss: seeAll })
169
- downToast = api.toast('', { ms: 0, kind: 'alert', name: 'new-down', order: 2, onClick: () => go('down'), onDismiss: seeAll })
220
+ upToast = api.toast('', {
221
+ ms: 0,
222
+ kind: 'alert',
223
+ name: 'new-up',
224
+ order: 1,
225
+ onClick: () => go('up'),
226
+ onDismiss: seeAll,
227
+ })
228
+ downToast = api.toast('', {
229
+ ms: 0,
230
+ kind: 'alert',
231
+ name: 'new-down',
232
+ order: 2,
233
+ onClick: () => go('down'),
234
+ onDismiss: seeAll,
235
+ })
170
236
  upToast.hide()
171
237
  downToast.hide()
172
238
  mainEl = main
@@ -177,7 +243,9 @@ export function trackInitial(main: HTMLElement, page: string, api: Api) {
177
243
  const seen = loadSeen()
178
244
  const recognised = seen ? sigs.filter(s => seen.has(s)).length : 0
179
245
  if (seen && recognised >= blocks.length * RECOGNISED_MIN)
180
- blocks.forEach((el, i) => { if (!seen.has(sigs[i])) markNew(el) })
246
+ blocks.forEach((el, i) => {
247
+ if (!seen.has(sigs[i])) markNew(el)
248
+ })
181
249
  saveSeen(main)
182
250
  update()
183
251
  }
@@ -5,7 +5,10 @@
5
5
  // sets the new place.
6
6
 
7
7
  const typing = (el: Element | null): el is HTMLElement =>
8
- el instanceof HTMLElement && (el.matches('input:not([type=radio], [type=checkbox], [type=button], [type=submit]), textarea, select, [contenteditable]'))
8
+ el instanceof HTMLElement &&
9
+ el.matches(
10
+ 'input:not([type=radio], [type=checkbox], [type=button], [type=submit]), textarea, select, [contenteditable]',
11
+ )
9
12
 
10
13
  let held: HTMLElement | null = null
11
14
  let top = 0
@@ -31,7 +34,13 @@ export function trackHold() {
31
34
  document.addEventListener('focusin', note)
32
35
  document.addEventListener('focusout', () => queueMicrotask(note))
33
36
  // the reader scrolled (or the page did, to keep it): that is the place now
34
- addEventListener('scroll', () => { if (held) top = held.getBoundingClientRect().top }, { passive: true })
37
+ addEventListener(
38
+ 'scroll',
39
+ () => {
40
+ if (held) top = held.getBoundingClientRect().top
41
+ },
42
+ { passive: true },
43
+ )
35
44
  new MutationObserver(hold).observe(document.body, { childList: true, subtree: true, characterData: true })
36
45
  addEventListener('resize', note)
37
46
  }
@@ -17,14 +17,18 @@ export function trackLive(root: HTMLElement, handle: PageHandle, api: Api) {
17
17
  const anyPage = listeners.some(l => l.fallback)
18
18
  const agent = live && (own || anyPage)
19
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'
20
+ dot.title = !live
21
+ ? 'Reconnecting… the page may be out of date'
22
+ : !hasAnswers
23
+ ? 'Live'
24
+ : own
25
+ ? 'Live · an agent is listening on this page'
26
+ : anyPage
27
+ ? 'Live · an agent is listening on every page'
28
+ : 'Live · no agent is listening right now; answers wait in the log'
25
29
  dot.setAttribute('aria-label', dot.title)
26
30
  }
27
- api.onListeners(show)
31
+ api.listeners.on(show)
28
32
  new MutationObserver(show).observe(document.documentElement, { attributes: true, attributeFilter: ['data-wb-live'] })
29
33
  show()
30
34
  }
@@ -6,18 +6,27 @@ import morphdom from 'morphdom'
6
6
  import type { Api, PageHandle, PluginMount } from '../../define.ts'
7
7
  import type { ClientApi, Mount } from '../../define.ts'
8
8
  import { signature, signaturesOf, trackInitial, trackUpdate } from './fresh'
9
- import { currentTheme, onTheme, setThemePreference, themePreference, type ThemePreference } from './theme'
9
+ import { currentTheme, setThemePreference, themePreference, type ThemePreference } from './theme'
10
10
  import { trackWaiting } from './waiting'
11
11
  import { trackElsewhere } from './elsewhere'
12
12
  import { trackLive } from './live'
13
13
  import { applySorts, trackSorts } from './sort'
14
14
  import { trackSticky } from './sticky'
15
15
  import { trackHold } from './hold'
16
+ import { trackWindows } from './window'
16
17
  import { trackOrphanThreads } from './orphans'
17
18
  import { html } from '../../html.ts'
18
19
 
19
- interface Island { block: string; client: string; props: unknown }
20
- interface Data { islands: Record<string, Island>; styles: string[]; mtime: number | null }
20
+ interface Island {
21
+ block: string
22
+ client: string
23
+ props: unknown
24
+ }
25
+ interface Data {
26
+ islands: Record<string, Island>
27
+ styles: string[]
28
+ mtime: number | null
29
+ }
21
30
 
22
31
  let main: HTMLElement
23
32
  let page = ''
@@ -35,21 +44,26 @@ async function mountOne(el: HTMLElement) {
35
44
  const mod = await import(island.client)
36
45
  if (!el.isConnected) return
37
46
  const mount: Mount = mod.default
38
- if (typeof mount !== 'function') throw new Error('the client module must export a mount(element, props, api) function as default')
47
+ if (typeof mount !== 'function')
48
+ throw new Error('the client module must export a mount(element, props, api) function as default')
39
49
  el.replaceChildren()
40
50
  const dispose = await mount(el, island.props, api)
41
51
  if (typeof dispose === 'function') disposers.set(el, dispose)
42
52
  } catch (err) {
43
53
  console.error(`island ${island.block}:`, err)
44
- el.insertAdjacentHTML('afterbegin', String(html`<pre class="wb-error">block "${island.block}" failed to mount: ${(err as Error).message}</pre>`))
54
+ el.insertAdjacentHTML(
55
+ 'afterbegin',
56
+ String(html`<pre class="wb-error">block "${island.block}" failed to mount: ${(err as Error).message}</pre>`),
57
+ )
45
58
  }
46
59
  }
47
60
 
48
61
  /** Mount islands outermost first; nested islands show up once their parent has rendered. */
49
62
  async function mountIslands(root: ParentNode = main): Promise<void> {
50
63
  for (;;) {
51
- const pending = [...root.querySelectorAll<HTMLElement>('[data-wb-island]:not([data-wb-mounted])')]
52
- .filter(el => !el.parentElement?.closest('[data-wb-island]:not([data-wb-mounted])'))
64
+ const pending = [...root.querySelectorAll<HTMLElement>('[data-wb-island]:not([data-wb-mounted])')].filter(
65
+ el => !el.parentElement?.closest('[data-wb-island]:not([data-wb-mounted])'),
66
+ )
53
67
  if (!pending.length) return
54
68
  await Promise.all(pending.map(mountOne))
55
69
  }
@@ -57,22 +71,34 @@ async function mountIslands(root: ParentNode = main): Promise<void> {
57
71
 
58
72
  function disposeWithin(node: Node) {
59
73
  for (const [el, dispose] of disposers) {
60
- if (node === el || node.contains(el)) { dispose(); disposers.delete(el) }
74
+ if (node === el || node.contains(el)) {
75
+ dispose()
76
+ disposers.delete(el)
77
+ }
61
78
  }
62
79
  }
63
80
 
64
-
65
81
  // ---- theme -------------------------------------------------------------------------------------
66
82
 
67
83
  const NEXT: Record<ThemePreference, ThemePreference> = { auto: 'light', light: 'dark', dark: 'auto' }
68
84
  // the preference as an icon: half a circle for following the system, a sun, a moon
69
85
  const svg = (d: string) => `<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">${d}</svg>`
70
86
  const THEME_ICON: Record<ThemePreference, string> = {
71
- 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"/>'),
72
- 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"/>'),
73
- 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"/>'),
87
+ auto: svg(
88
+ '<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"/>',
89
+ ),
90
+ light: svg(
91
+ '<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"/>',
92
+ ),
93
+ dark: svg(
94
+ '<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"/>',
95
+ ),
96
+ }
97
+ const THEME_LABEL: Record<ThemePreference, string> = {
98
+ auto: 'Theme: follows the system',
99
+ light: 'Theme: light',
100
+ dark: 'Theme: dark',
74
101
  }
75
- const THEME_LABEL: Record<ThemePreference, string> = { auto: 'Theme: follows the system', light: 'Theme: light', dark: 'Theme: dark' }
76
102
 
77
103
  function themeToggle(root: HTMLElement) {
78
104
  const button = root.querySelector<HTMLButtonElement>('.wb-theme')
@@ -133,7 +159,10 @@ function detailsKeys(root: HTMLElement): Map<HTMLDetailsElement, string> {
133
159
  while (block.parentElement && block.parentElement !== root) block = block.parentElement
134
160
  let heading = ''
135
161
  for (let b: Element | null = block; b; b = b.previousElementSibling) {
136
- if (/^H[1-6]$/.test(b.tagName)) { heading = b.textContent?.trim() ?? ''; break }
162
+ if (/^H[1-6]$/.test(b.tagName)) {
163
+ heading = b.textContent?.trim() ?? ''
164
+ break
165
+ }
137
166
  }
138
167
  const base = `${heading}\u0000${el.querySelector(':scope > summary')?.textContent?.trim() ?? ''}`
139
168
  const n = seen.get(base) ?? 0
@@ -160,8 +189,14 @@ function focusOf() {
160
189
  const el = document.activeElement as HTMLInputElement | HTMLTextAreaElement | null
161
190
  if (!el || el === document.body || !main.contains(el)) return null
162
191
  const form = el.closest('form')?.getAttribute('name')
163
- let start: number | null = null, end: number | null = null
164
- try { start = el.selectionStart; end = el.selectionEnd } catch { /* not a text field */ }
192
+ let start: number | null = null,
193
+ end: number | null = null
194
+ try {
195
+ start = el.selectionStart
196
+ end = el.selectionEnd
197
+ } catch {
198
+ /* not a text field */
199
+ }
165
200
  return { el, form, name: el.getAttribute('name'), start, end }
166
201
  }
167
202
 
@@ -169,10 +204,16 @@ function giveFocusBack(f: ReturnType<typeof focusOf>) {
169
204
  if (!f || document.activeElement === f.el) return
170
205
  let el: HTMLElement | null = f.el.isConnected ? f.el : null
171
206
  // replaced: the field of the same name in the form of the same name
172
- if (!el && f.form && f.name) el = main.querySelector<HTMLElement>(`form[name="${CSS.escape(f.form)}"] [name="${CSS.escape(f.name)}"]`)
207
+ if (!el && f.form && f.name)
208
+ el = main.querySelector<HTMLElement>(`form[name="${CSS.escape(f.form)}"] [name="${CSS.escape(f.name)}"]`)
173
209
  if (!el) return
174
210
  el.focus({ preventScroll: true })
175
- if (f.start != null && 'setSelectionRange' in el) try { (el as HTMLInputElement).setSelectionRange(f.start, f.end ?? f.start) } catch { /* not a text field */ }
211
+ if (f.start != null && 'setSelectionRange' in el)
212
+ try {
213
+ ;(el as HTMLInputElement).setSelectionRange(f.start, f.end ?? f.start)
214
+ } catch {
215
+ /* not a text field */
216
+ }
176
217
  }
177
218
 
178
219
  /** Are two elements, before and after a patch, the same field of the same form? */
@@ -181,7 +222,11 @@ function sameField(from: Element, to: Element) {
181
222
  const formOf = (el: Element) => el.closest('form')?.getAttribute('name') ?? null
182
223
  if (formOf(from) !== formOf(to)) return false
183
224
  const type = from.getAttribute('type')
184
- if ((type === 'radio' || type === 'checkbox') && (to.getAttribute('type') !== type || from.getAttribute('value') !== to.getAttribute('value'))) return false
225
+ if (
226
+ (type === 'radio' || type === 'checkbox') &&
227
+ (to.getAttribute('type') !== type || from.getAttribute('value') !== to.getAttribute('value'))
228
+ )
229
+ return false
185
230
  return true
186
231
  }
187
232
 
@@ -197,7 +242,8 @@ function morph(html: string, sigs: { from: string[]; to: string[] }) {
197
242
  keyBlocks(next, sigs.to)
198
243
  for (const [el, key] of detailsKeys(next)) el.open = open.has(key)
199
244
  morphdom(main, next, {
200
- getNodeKey: n => (n as HTMLElement).dataset?.wbKey || (n as HTMLElement).dataset?.wbBlock || (n as HTMLElement).id || undefined,
245
+ getNodeKey: n =>
246
+ (n as HTMLElement).dataset?.wbKey || (n as HTMLElement).dataset?.wbBlock || (n as HTMLElement).id || undefined,
201
247
  onBeforeElUpdated(from, to) {
202
248
  if (from.dataset.wbKey) {
203
249
  if (from.dataset.wbKey === to.dataset.wbKey && 'wbMounted' in from.dataset) {
@@ -220,7 +266,8 @@ function morph(html: string, sigs: { from: string[]; to: string[] }) {
220
266
  // what a plugin marked on an element (`data-wb-*`) stays, unless the new render sets it;
221
267
  // data-wb-mounted is the page's own, and a replaced island must mount afresh
222
268
  for (const { name, value } of [...from.attributes])
223
- if (name.startsWith('data-wb-') && name !== 'data-wb-mounted' && !to.hasAttribute(name)) to.setAttribute(name, value)
269
+ if (name.startsWith('data-wb-') && name !== 'data-wb-mounted' && !to.hasAttribute(name))
270
+ to.setAttribute(name, value)
224
271
  for (const c of KEEP_CLASSES) if (from.classList.contains(c)) to.classList.add(c)
225
272
  return true
226
273
  },
@@ -229,7 +276,10 @@ function morph(html: string, sigs: { from: string[]; to: string[] }) {
229
276
  // form's new place). So islands are not disposed here, but after the patch, if gone.
230
277
  })
231
278
  for (const [el, dispose] of disposers) {
232
- if (!el.isConnected) { dispose(); disposers.delete(el) }
279
+ if (!el.isConnected) {
280
+ dispose()
281
+ disposers.delete(el)
282
+ }
233
283
  }
234
284
  giveFocusBack(focus)
235
285
  }
@@ -266,24 +316,37 @@ function keepPlace(place: ReturnType<typeof placeOf>, sigs: string[]) {
266
316
  /** The new render of the page, patched in. */
267
317
  async function refresh() {
268
318
  let next: Awaited<ReturnType<PageHandle['render']>>
269
- try { next = await currentPage.render() } catch (err) {
319
+ try {
320
+ next = await currentPage.render()
321
+ } catch (err) {
270
322
  // the page is gone (closed, deleted): load what its address shows now, the "Not found" page,
271
- // which turns into the page again if it is written back
272
- if (/: 404$/.test((err as Error).message)) return location.reload()
323
+ // which turns into the page again if it is written back. Already that page (it has no file, so
324
+ // no time it was edited): still not there, nothing to do
325
+ if (/: 404$/.test((err as Error).message)) {
326
+ if ((currentPage.data() as Data | null)?.mtime == null) return
327
+ return location.reload()
328
+ }
273
329
  throw err
274
330
  }
275
331
  const data = next.data as Data
276
332
  islands = data.islands
277
333
  for (const href of data.styles) {
278
- if (![...document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')].some(l => new URL(l.href).pathname === new URL(href, location.href).pathname))
279
- document.head.insertAdjacentHTML('beforeend', String(html`<link rel="stylesheet" href="${href}">`))
334
+ if (
335
+ ![...document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')].some(
336
+ l => new URL(l.href).pathname === new URL(href, location.href).pathname,
337
+ )
338
+ )
339
+ document.head.insertAdjacentHTML('beforeend', String(html`<link rel="stylesheet" href="${href}" />`))
280
340
  }
281
341
  const content = new DOMParser().parseFromString(next.html, 'text/html').getElementById('wb-main')?.innerHTML ?? ''
282
342
  const nextSigs = signaturesOf(content)
283
343
  const place = placeOf(nextSigs)
284
344
  // what the reader is typing in stays where it is on screen, wherever the change is: measured now,
285
345
  // and held once the update and what the plugins redraw on it are done
286
- const focused = document.activeElement instanceof HTMLElement && document.activeElement !== document.body ? document.activeElement : null
346
+ const focused =
347
+ document.activeElement instanceof HTMLElement && document.activeElement !== document.body
348
+ ? document.activeElement
349
+ : null
287
350
  const focusedTop = focused?.getBoundingClientRect().top
288
351
  morph(content, { from: blockSigs, to: nextSigs })
289
352
  // a list the reader sorted comes back in the server's order: sorted again at once, before the
@@ -302,7 +365,12 @@ async function refresh() {
302
365
  // plugins put back what they add to the content
303
366
  api.rendered()
304
367
  const now = document.activeElement
305
- if (focused && focusedTop != null && now instanceof HTMLElement && (now === focused || focused.isConnected === false)) {
368
+ if (
369
+ focused &&
370
+ focusedTop != null &&
371
+ now instanceof HTMLElement &&
372
+ (now === focused || focused.isConnected === false)
373
+ ) {
306
374
  const moved = now.getBoundingClientRect().top - focusedTop
307
375
  if (Math.abs(moved) >= 1) scrollBy(0, moved)
308
376
  }
@@ -316,8 +384,8 @@ const mount: PluginMount = async (root: HTMLElement, handle: PageHandle, coreApi
316
384
  core = coreApi
317
385
  page = handle.id
318
386
  main = root.querySelector<HTMLElement>('#wb-main')!
319
- islands = (handle.data as Data).islands
320
- api = { ...core, theme: currentTheme, onTheme }
387
+ islands = (handle.data() as Data).islands
388
+ api = { ...core, theme: currentTheme }
321
389
  const isDir = handle.kind === 'pages' || handle.kind === 'folder'
322
390
 
323
391
  themeToggle(root)
@@ -329,18 +397,22 @@ const mount: PluginMount = async (root: HTMLElement, handle: PageHandle, coreApi
329
397
 
330
398
  handle.onChange(() => refresh())
331
399
  // the overview shows when pages were last answered
332
- if (isDir) core.onEvents(() => refresh())
400
+ if (isDir) core.events.on(() => refresh())
333
401
  // the overview shows which pages an agent is waiting on
334
- if (isDir) core.onListeners(() => refresh())
402
+ if (isDir) core.listeners.on(() => refresh())
335
403
 
336
404
  blockSigs = [...main.children].map(signature)
337
405
  if (!isDir) trackInitial(main, page, core)
338
406
  if (!isDir) trackWaiting(main, core)
339
407
  trackElsewhere(root, handle, core)
340
408
  trackLive(root, handle, core)
341
- if (isDir) { trackSorts(); core.onRendered(applySorts) }
409
+ if (isDir) {
410
+ trackSorts()
411
+ core.onRendered(applySorts)
412
+ }
342
413
  trackSticky(main, fn => core.onRendered(fn))
343
414
  trackHold()
415
+ trackWindows(core)
344
416
  if (!isDir) trackOrphanThreads(main, core)
345
417
  await mountIslands()
346
418
  tickTimes()
@@ -29,18 +29,33 @@ export function trackOrphanThreads(main: HTMLElement, api: Api) {
29
29
  }
30
30
  box.hidden = threads.size === 0
31
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
- })}`)
32
+ box.innerHTML = String(
33
+ html`<h2>Chats no longer on this page</h2>
34
+ ${[...threads].map(([chat, messages]) => {
35
+ // a message can take the place of an earlier one (`replaces`), to correct it
36
+ const replaced = new Set(
37
+ messages
38
+ .map(m => m.data.replaces)
39
+ .filter(Boolean)
40
+ .map(String),
41
+ )
42
+ return html`<div class="wb-orphan" data-chat="${chat}">
43
+ <h3>${chat}</h3>
44
+ ${messages
45
+ .filter(m => !replaced.has(m.id))
46
+ .map(m => {
47
+ const who = m.from === 'cli' ? 'agent' : 'you'
48
+ return html`<div class="wb-orphan-message" data-from="${who}">
49
+ <span class="wb-orphan-who">${who}</span
50
+ ><span class="wb-orphan-text">${String(m.data.text ?? '')}</span>
51
+ </div>`
52
+ })}
53
+ </div>`
54
+ })}`,
55
+ )
41
56
  }
42
57
 
43
- api.onEvents(draw)
58
+ api.events.on(draw)
44
59
  api.onRendered(draw)
45
60
  draw()
46
61
  }