@bigmistqke/whiteboard 0.2.1 → 0.3.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 (45) hide show
  1. package/README.md +16 -10
  2. package/bin/whiteboard.ts +98 -4
  3. package/dist/bin/whiteboard.js +99 -3
  4. package/dist/client/runtime.js +118 -24
  5. package/dist/plugins/claude-code/index.js +14 -3
  6. package/dist/plugins/comments/client.js +3 -3
  7. package/dist/plugins/details/README.md +3 -1
  8. package/dist/plugins/form/README.md +6 -4
  9. package/dist/plugins/form/index.js +9 -1
  10. package/dist/plugins/form/style.css +3 -0
  11. package/dist/plugins/toc/README.md +10 -0
  12. package/dist/plugins/toc/client.js +1 -0
  13. package/dist/plugins/toc/index.js +17 -0
  14. package/dist/plugins/toc/style.css +19 -0
  15. package/dist/src/client/page/base.css +26 -22
  16. package/dist/src/client/page/main.js +227 -52
  17. package/dist/src/events.js +127 -9
  18. package/dist/src/loader.js +4 -0
  19. package/dist/src/server.js +25 -17
  20. package/package.json +6 -1
  21. package/plugins/claude-code/index.ts +16 -7
  22. package/plugins/comments/client.ts +30 -7
  23. package/plugins/details/README.md +3 -1
  24. package/plugins/form/README.md +6 -4
  25. package/plugins/form/index.ts +9 -1
  26. package/plugins/form/style.css +3 -0
  27. package/plugins/toc/README.md +10 -0
  28. package/plugins/toc/client.ts +130 -0
  29. package/plugins/toc/index.ts +25 -0
  30. package/plugins/toc/style.css +19 -0
  31. package/skills/whiteboard/SKILL.md +41 -9
  32. package/src/client/forms.ts +32 -1
  33. package/src/client/page/base.css +26 -22
  34. package/src/client/page/fresh.ts +18 -23
  35. package/src/client/page/hold.ts +37 -0
  36. package/src/client/page/main.ts +81 -6
  37. package/src/client/page/sticky.ts +45 -0
  38. package/src/client/page/waiting.ts +30 -27
  39. package/src/client/runtime.ts +8 -2
  40. package/src/client/scroll.ts +44 -0
  41. package/src/client/toast.ts +51 -21
  42. package/src/define.ts +17 -8
  43. package/src/events.ts +95 -7
  44. package/src/loader.ts +1 -1
  45. package/src/server.ts +28 -7
@@ -114,7 +114,7 @@ hr::after { content: "⁂"; font-size: 1.1em; color: var(--muted); letter-spacin
114
114
  details { margin: 3.2em 0; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); }
115
115
  details + details { margin-top: -3.2em; border-top: 0; }
116
116
  details > summary {
117
- cursor: pointer; list-style: none; padding: .95em 0; font: 500 .95rem/1.4 var(--sans); color: var(--text);
117
+ cursor: pointer; list-style: none; padding: .5em 0; font: 500 .95rem/1.4 var(--sans); color: var(--text);
118
118
  display: flex; gap: .6em; align-items: baseline;
119
119
  }
120
120
  details > summary::-webkit-details-marker { display: none; }
@@ -123,6 +123,9 @@ details[open] > summary::before { content: "−"; }
123
123
  details > summary:hover { color: var(--accent); }
124
124
  details > :not(summary) { margin-left: 1.4em; }
125
125
  details[open] > :last-child { margin-bottom: 2em; }
126
+ /* an open details' summary stays at the top while its content is read, under the header and the
127
+ summaries of the details around it (sticky.ts says how far down) */
128
+ #wb-main details[open] > summary { position: sticky; top: var(--wb-sticky-top, 0px); z-index: var(--wb-sticky-z, 3); background: var(--bg); }
126
129
 
127
130
  /* figures: an image alone in its paragraph, an HTML <figure>, or anything with .wb-figure (blocks
128
131
  opt in) may run wider than the text, up to --figure, centred on the column. Images keep their
@@ -197,17 +200,12 @@ button:hover { border-color: var(--muted); }
197
200
 
198
201
  /* new content since the reader last saw the page */
199
202
  #wb-main > * { scroll-margin-top: 72px; }
200
- .wb-new { position: relative; }
201
- .wb-new::after {
202
- content: ""; position: absolute; left: -14px; top: 3px; bottom: 3px; width: 3px; border-radius: 2px;
203
- background: var(--bad); transition: opacity 1.2s ease;
204
- }
205
- .wb-wide.wb-new::after { left: -10px; }
206
- .wb-new.wb-new-seen::after { opacity: 0; transition-delay: 1s; }
207
- .wb-fresh button { display: inline-flex; align-items: center; gap: 8px; }
208
- .wb-fresh-close { display: inline-block; margin-right: -4px; padding: 0 4px; border-left: 1px solid rgb(255 255 255 / .35); opacity: .75; }
209
- .wb-fresh-close:hover { opacity: 1; }
210
- .wb-fresh { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; }
203
+ /* a 3px bar left of the block, drawn as two shadows (red, with the page's colour over all but its
204
+ last 3px), not as ::before or ::after: blocks use those themselves (a heading's number, a folded
205
+ form's lines), and a bar laid over them squeezed their text into its width */
206
+ .wb-new { --wb-new-at: 14px; box-shadow: calc(3px - var(--wb-new-at)) 0 0 var(--bg), calc(0px - var(--wb-new-at)) 0 0 var(--bad); transition: box-shadow 1.2s ease; }
207
+ .wb-wide.wb-new { --wb-new-at: 10px; }
208
+ .wb-new.wb-new-seen { box-shadow: calc(3px - var(--wb-new-at)) 0 0 var(--bg), calc(0px - var(--wb-new-at)) 0 0 transparent; transition-delay: 1s; }
211
209
 
212
210
  form.wb-form[data-wb-folded] { padding: 1em 0; gap: 0; }
213
211
  /* named forms: the core marks where each stands (data-wb-open, -pending, -decided); this is how that looks */
@@ -221,13 +219,13 @@ form.wb-form[data-wb-state=failed]::before { content: "couldn't send it: try aga
221
219
  form[data-wb-sent]:not(.wb-form)::after { content: "✓ sent " attr(data-wb-sent); display: block; margin-top: 6px; color: var(--ok); font: .8rem var(--sans); }
222
220
  form[data-wb-state=failed]:not(.wb-form)::after { content: "failed to send"; color: var(--bad); }
223
221
 
224
- /* the button in the page's corner that goes to the next thing waiting for the reader */
225
- .wb-waiting-next { background: var(--accent); color: var(--accent-text); border-color: var(--accent); border-radius: 99px; font-size: .8rem; }
226
- .wb-waiting-next[hidden] { display: none; }
227
222
 
228
- /* a question the reader hasn't answered, or one the agent asks again */
223
+ /* a question the reader hasn't answered, or one the agent asks again: outlined, without a label of
224
+ its own (one laid into the form landed on its content in some layouts; the corner counts them) */
229
225
  form[data-wb-open] { outline: 2px solid var(--accent); outline-offset: 10px; border-radius: 2px; }
230
- form[data-wb-open]::before { content: "waiting for you"; display: block; margin-bottom: 8px; color: var(--accent); font: 600 .75rem/1.4 var(--sans); letter-spacing: .04em; text-transform: uppercase; }
226
+ /* the outline sets it off: the form's rules above and below (its borders, which the outline would
227
+ enclose) step aside meanwhile */
228
+ form.wb-form[data-wb-open] { border-top-color: transparent; border-bottom-color: transparent; }
231
229
  form[data-wb-pending]::before { content: "sent · waiting for the agent to pick it up"; display: block; margin-bottom: 8px; color: var(--muted); font: .75rem/1.4 var(--sans); }
232
230
  form[data-wb-pending][data-wb-just-sent]::before { content: "✓ sent · waiting for the agent to pick it up"; color: var(--ok); font-weight: 600; }
233
231
 
@@ -249,14 +247,12 @@ form[data-wb-folded]:hover::after { color: var(--accent); }
249
247
  .wb-summary { max-width: calc(var(--measure) + var(--indent, 34px) + 32px); margin: 0 auto; padding: 96px 16px 0; box-sizing: border-box; color: var(--muted); font: .8rem/1.5 var(--sans); }
250
248
  /* the summary takes the space above the title that the page would otherwise start with */
251
249
  .wb-summary:not([hidden]) + main { padding-top: 20px; }
252
- .wb-fresh[hidden], .wb-fresh button[hidden] { display: none; }
253
- .wb-fresh button { background: var(--bad); color: #fff; border-color: var(--bad); border-radius: 99px; font-size: .8rem; }
254
250
 
255
251
  @media (max-width: 600px) {
256
252
  body { font-size: 18px; }
257
253
  main { padding-top: 32px; }
258
254
  h1 { font-size: 2.2rem; }
259
- .wb-new::after { left: -9px; }
255
+ .wb-new { --wb-new-at: 9px; }
260
256
  }
261
257
 
262
258
  /* repository views: folder listings and code */
@@ -274,8 +270,16 @@ form[data-wb-folded]:hover::after { color: var(--accent); }
274
270
  .wb-documents h2 { font-size: 1.1rem; margin: 0; }
275
271
  /* a list's heading with its sort control at the right (sort.ts) */
276
272
  .wb-list-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-bottom: .4em; }
277
- .wb-sort { font: .8rem/1.4 var(--sans); color: var(--muted); display: inline-flex; align-items: baseline; gap: 6px; }
278
- .wb-sort select { font: inherit; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 2px 6px; }
273
+ .wb-sort { font: .8rem/1.4 var(--sans); color: var(--muted); display: inline-flex; align-items: center; gap: 6px; }
274
+ /* in the look of the header's buttons: a rounded outline, its own arrow */
275
+ .wb-sort select {
276
+ appearance: none; -webkit-appearance: none; font: inherit; color: var(--muted); cursor: pointer;
277
+ height: 24px; box-sizing: border-box; padding: 0 24px 0 10px; border: 1px solid var(--border); border-radius: 99px;
278
+ background: var(--bg) no-repeat right 9px center / 8px 5px;
279
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 5'%3E%3Cpath d='M.5.5 4 4 7.5.5' fill='none' stroke='%23888' stroke-width='1.2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
280
+ }
281
+ .wb-sort select:hover { color: var(--text); border-color: var(--muted); }
282
+ .wb-sort select:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
279
283
 
280
284
  /* threads whose form is no longer on the page (orphans.ts): read-only, after the content */
281
285
  .wb-orphans { --indent: 34px; max-width: calc(var(--measure) + var(--indent) + 32px); margin: 0 auto; padding: 0 16px 220px; box-sizing: border-box; font: .92rem/1.45 var(--sans); }
@@ -4,7 +4,7 @@
4
4
  // have been in view for a moment with the tab visible. Floating buttons jump to unseen blocks.
5
5
 
6
6
  import { html } from '../../html.ts'
7
- import type { Api } from '../../define.ts'
7
+ import type { Api, Toast } from '../../define.ts'
8
8
  import { viewBottom } from './view'
9
9
 
10
10
  const DWELL_MS = 600
@@ -28,6 +28,8 @@ export function signature(el: Element): string {
28
28
  n.removeAttribute('data-wb-island')
29
29
  n.removeAttribute('data-wb-mounted')
30
30
  }
31
+ // the page's key for the block (main.ts), not its content
32
+ clone.removeAttribute('data-wb-block')
31
33
  const s = clone.outerHTML
32
34
  let h = 0x811c9dc5
33
35
  for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193)
@@ -111,16 +113,10 @@ function markNew(el: Element) {
111
113
 
112
114
  // ---- navigator ---------------------------------------------------------------------------------
113
115
 
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
116
+ // the "new" toasts, in the page's corner (api.toast): one for what is new above, one for below,
117
+ // each going to the nearest; their ✕ counts everything new as seen. Their count is in the tab title.
118
+ let upToast: Toast | null = null
119
+ let downToast: Toast | null = null
124
120
 
125
121
  function split() {
126
122
  const above: Element[] = [], below: Element[] = []
@@ -141,23 +137,19 @@ function update() {
141
137
  cancelAnimationFrame(raf)
142
138
  raf = requestAnimationFrame(() => {
143
139
  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
140
+ for (const [toast, list, arrow] of [[upToast, above, '↑'], [downToast, below, '↓']] as const) {
141
+ if (!toast) continue
142
+ if (list.length) { toast.update(`${arrow} new (${list.length})`); toast.show() } else toast.hide()
143
+ }
149
144
  core?.badge('new', unseen.size ? String(unseen.size) : null)
150
145
  })
151
146
  }
152
147
 
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 }
148
+ function go(dir: 'up' | 'down') {
158
149
  const { above, below } = split()
159
150
  ;(dir === 'up' ? above : below)[0]?.scrollIntoView({ behavior: 'smooth', block: 'start' })
160
- })
151
+ }
152
+ const seeAll = () => { for (const el of [...unseen]) markSeen(el) }
161
153
  addEventListener('scroll', update, { passive: true })
162
154
  addEventListener('resize', update)
163
155
 
@@ -173,7 +165,10 @@ const RECOGNISED_MIN = 0.25
173
165
  */
174
166
  export function trackInitial(main: HTMLElement, page: string, api: Api) {
175
167
  core = api
176
- api.corner().append(nav)
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 })
170
+ upToast.hide()
171
+ downToast.hide()
177
172
  mainEl = main
178
173
  storeKey = `wb-seen:${page}`
179
174
  const blocks = [...main.children]
@@ -0,0 +1,37 @@
1
+ // What the reader is typing in stays where it is on screen. While a field on the page has the focus,
2
+ // its place is noted; when anything on the page changes around it (a message arrives above a chat's
3
+ // box, a block comes in above a form, a thread grows) and it moved without the reader scrolling,
4
+ // the page scrolls by as much, so the box doesn't slide away mid-word. The reader's own scrolling
5
+ // sets the new place.
6
+
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]'))
9
+
10
+ let held: HTMLElement | null = null
11
+ let top = 0
12
+ let frame = 0
13
+
14
+ function note() {
15
+ const el = document.activeElement
16
+ held = typing(el) ? el : null
17
+ if (held) top = held.getBoundingClientRect().top
18
+ }
19
+
20
+ function hold() {
21
+ cancelAnimationFrame(frame)
22
+ frame = requestAnimationFrame(() => {
23
+ if (!held || document.activeElement !== held || !held.isConnected) return note()
24
+ const moved = held.getBoundingClientRect().top - top
25
+ if (Math.abs(moved) >= 1) scrollBy(0, moved)
26
+ top = held.getBoundingClientRect().top
27
+ })
28
+ }
29
+
30
+ export function trackHold() {
31
+ document.addEventListener('focusin', note)
32
+ document.addEventListener('focusout', () => queueMicrotask(note))
33
+ // 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 })
35
+ new MutationObserver(hold).observe(document.body, { childList: true, subtree: true, characterData: true })
36
+ addEventListener('resize', note)
37
+ }
@@ -11,6 +11,8 @@ import { trackWaiting } from './waiting'
11
11
  import { trackElsewhere } from './elsewhere'
12
12
  import { trackLive } from './live'
13
13
  import { applySorts, trackSorts } from './sort'
14
+ import { trackSticky } from './sticky'
15
+ import { trackHold } from './hold'
14
16
  import { trackOrphanThreads } from './orphans'
15
17
  import { html } from '../../html.ts'
16
18
 
@@ -141,14 +143,61 @@ function detailsKeys(root: HTMLElement): Map<HTMLDetailsElement, string> {
141
143
  return keys
142
144
  }
143
145
 
144
- function morph(html: string) {
146
+ /** Each block's key: its signature, and which of the blocks with that signature it is. */
147
+ function keyBlocks(parent: HTMLElement, sigs: string[]) {
148
+ const seen = new Map<string, number>()
149
+ ;[...parent.children].forEach((el, i) => {
150
+ const sig = sigs[i]
151
+ if (!sig) return
152
+ const nth = seen.get(sig) ?? 0
153
+ seen.set(sig, nth + 1)
154
+ ;(el as HTMLElement).dataset.wbBlock = `${sig}#${nth}`
155
+ })
156
+ }
157
+
158
+ /** What has the focus, to give it back if the patch took it: the element, its caret, and how to find it again. */
159
+ function focusOf() {
160
+ const el = document.activeElement as HTMLInputElement | HTMLTextAreaElement | null
161
+ if (!el || el === document.body || !main.contains(el)) return null
162
+ 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 */ }
165
+ return { el, form, name: el.getAttribute('name'), start, end }
166
+ }
167
+
168
+ function giveFocusBack(f: ReturnType<typeof focusOf>) {
169
+ if (!f || document.activeElement === f.el) return
170
+ let el: HTMLElement | null = f.el.isConnected ? f.el : null
171
+ // 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)}"]`)
173
+ if (!el) return
174
+ 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 */ }
176
+ }
177
+
178
+ /** Are two elements, before and after a patch, the same field of the same form? */
179
+ function sameField(from: Element, to: Element) {
180
+ if (from.tagName !== to.tagName || from.getAttribute('name') !== to.getAttribute('name')) return false
181
+ const formOf = (el: Element) => el.closest('form')?.getAttribute('name') ?? null
182
+ if (formOf(from) !== formOf(to)) return false
183
+ const type = from.getAttribute('type')
184
+ if ((type === 'radio' || type === 'checkbox') && (to.getAttribute('type') !== type || from.getAttribute('value') !== to.getAttribute('value'))) return false
185
+ return true
186
+ }
187
+
188
+ function morph(html: string, sigs: { from: string[]; to: string[] }) {
145
189
  const open = new Set<string>()
146
190
  for (const [el, key] of detailsKeys(main)) if (el.open) open.add(key)
191
+ const focus = focusOf()
147
192
  const next = main.cloneNode(false) as HTMLElement
148
193
  next.innerHTML = html
194
+ // blocks keyed by their content: an update that puts something new above a block leaves it be
195
+ // (and the field being typed in, in it), instead of patching each block into the next one
196
+ keyBlocks(main, sigs.from)
197
+ keyBlocks(next, sigs.to)
149
198
  for (const [el, key] of detailsKeys(next)) el.open = open.has(key)
150
199
  morphdom(main, next, {
151
- getNodeKey: n => (n as HTMLElement).dataset?.wbKey || (n as HTMLElement).id || undefined,
200
+ getNodeKey: n => (n as HTMLElement).dataset?.wbKey || (n as HTMLElement).dataset?.wbBlock || (n as HTMLElement).id || undefined,
152
201
  onBeforeElUpdated(from, to) {
153
202
  if (from.dataset.wbKey) {
154
203
  if (from.dataset.wbKey === to.dataset.wbKey && 'wbMounted' in from.dataset) {
@@ -159,8 +208,13 @@ function morph(html: string) {
159
208
  }
160
209
  if (FIELD(from)) {
161
210
  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
211
+ // what the reader typed or picked goes over only to the same field: the same form, name and
212
+ // (for a radio or checkbox) value. Patched into another field (a block moved), it would
213
+ // answer another question.
214
+ if (sameField(from, to)) {
215
+ ;(to as typeof from).value = from.value
216
+ if (from instanceof HTMLInputElement) (to as HTMLInputElement).checked = from.checked
217
+ }
164
218
  }
165
219
  // <details> open state was set on the new tree by detailsKeys(), matched by identity, not position
166
220
  // what a plugin marked on an element (`data-wb-*`) stays, unless the new render sets it;
@@ -177,6 +231,7 @@ function morph(html: string) {
177
231
  for (const [el, dispose] of disposers) {
178
232
  if (!el.isConnected) { dispose(); disposers.delete(el) }
179
233
  }
234
+ giveFocusBack(focus)
180
235
  }
181
236
 
182
237
  // The page keeps the reader's place itself: the browser's own scroll anchoring loses its anchor
@@ -210,7 +265,13 @@ function keepPlace(place: ReturnType<typeof placeOf>, sigs: string[]) {
210
265
 
211
266
  /** The new render of the page, patched in. */
212
267
  async function refresh() {
213
- const next = await currentPage.render()
268
+ let next: Awaited<ReturnType<PageHandle['render']>>
269
+ try { next = await currentPage.render() } catch (err) {
270
+ // 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()
273
+ throw err
274
+ }
214
275
  const data = next.data as Data
215
276
  islands = data.islands
216
277
  for (const href of data.styles) {
@@ -220,7 +281,14 @@ async function refresh() {
220
281
  const content = new DOMParser().parseFromString(next.html, 'text/html').getElementById('wb-main')?.innerHTML ?? ''
221
282
  const nextSigs = signaturesOf(content)
222
283
  const place = placeOf(nextSigs)
223
- morph(content)
284
+ // what the reader is typing in stays where it is on screen, wherever the change is: measured now,
285
+ // 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
287
+ const focusedTop = focused?.getBoundingClientRect().top
288
+ morph(content, { from: blockSigs, to: nextSigs })
289
+ // a list the reader sorted comes back in the server's order: sorted again at once, before the
290
+ // rest of the update, so it never shows unsorted
291
+ applySorts()
224
292
  keepPlace(place, nextSigs)
225
293
  const updated = document.getElementById('wb-updated')
226
294
  if (updated && data.mtime) updated.dataset.ts = String(data.mtime)
@@ -233,6 +301,11 @@ async function refresh() {
233
301
  tickTimes()
234
302
  // plugins put back what they add to the content
235
303
  api.rendered()
304
+ const now = document.activeElement
305
+ if (focused && focusedTop != null && now instanceof HTMLElement && (now === focused || focused.isConnected === false)) {
306
+ const moved = now.getBoundingClientRect().top - focusedTop
307
+ if (Math.abs(moved) >= 1) scrollBy(0, moved)
308
+ }
236
309
  }
237
310
 
238
311
  let currentPage: PageHandle
@@ -266,6 +339,8 @@ const mount: PluginMount = async (root: HTMLElement, handle: PageHandle, coreApi
266
339
  trackElsewhere(root, handle, core)
267
340
  trackLive(root, handle, core)
268
341
  if (isDir) { trackSorts(); core.onRendered(applySorts) }
342
+ trackSticky(main, fn => core.onRendered(fn))
343
+ trackHold()
269
344
  if (!isDir) trackOrphanThreads(main, core)
270
345
  await mountIslands()
271
346
  tickTimes()
@@ -0,0 +1,45 @@
1
+ // An open <details>'s summary stays at the top while its content is read, below the page's header;
2
+ // a summary of details inside details stacks below the summaries of the details around it. CSS
3
+ // makes them sticky (base.css); this says how far from the top each sticks: the header's height,
4
+ // then each open summary around it, measured, as a summary can take more than one line. Measured
5
+ // again when a details opens or closes, the window resizes, or the page updates. Closing a details by
6
+ // its title while the title is stuck (its start is above the view) scrolls back to it, so the
7
+ // reader lands at the title, not somewhere far below where the content was.
8
+
9
+ function place(main: HTMLElement) {
10
+ const nav = document.querySelector<HTMLElement>('.wb-nav')
11
+ const base = nav ? nav.getBoundingClientRect().height : 0
12
+ for (const summary of main.querySelectorAll<HTMLElement>('details > summary')) {
13
+ let top = base, depth = 0
14
+ for (let d = summary.parentElement!.parentElement?.closest('details'); d && main.contains(d); d = d.parentElement?.closest('details')) {
15
+ const outer = d.querySelector<HTMLElement>(':scope > summary')
16
+ if (outer && d.open) top += outer.getBoundingClientRect().height
17
+ depth++
18
+ }
19
+ summary.style.setProperty('--wb-sticky-top', `${top}px`)
20
+ // an inner summary that scrolls away goes under the ones around it, all under the header
21
+ summary.style.setProperty('--wb-sticky-z', String(Math.max(1, 4 - depth)))
22
+ }
23
+ }
24
+
25
+ /** A click on a stuck title: once its details has closed, the title where it was stuck. */
26
+ function keepTitle(e: MouseEvent) {
27
+ const summary = (e.target as HTMLElement).closest?.('summary')
28
+ const details = summary?.parentElement
29
+ if (!summary || !(details instanceof HTMLDetailsElement) || !details.open) return
30
+ const top = parseFloat(summary.style.getPropertyValue('--wb-sticky-top')) || 0
31
+ // stuck: the details starts above where its title is held
32
+ if (details.getBoundingClientRect().top >= top - 1) return
33
+ requestAnimationFrame(() => scrollBy({ top: details.getBoundingClientRect().top - top }))
34
+ }
35
+
36
+ export function trackSticky(main: HTMLElement, onRendered: (fn: () => void) => void) {
37
+ main.addEventListener('click', keepTitle)
38
+ let frame = 0
39
+ const later = () => { cancelAnimationFrame(frame); frame = requestAnimationFrame(() => place(main)) }
40
+ // toggle doesn't bubble: listened for on the way down
41
+ main.addEventListener('toggle', later, true)
42
+ addEventListener('resize', later)
43
+ onRendered(later)
44
+ place(main)
45
+ }
@@ -1,10 +1,10 @@
1
1
  // How the page shows what waits for the reader: its open questions and the agent's messages they
2
2
  // haven't read (status.ts). The core marks each named form with where it stands (open, pending,
3
3
  // decided; see `api.onForms`); the page styles those marks (base.css), folds a decided form into
4
- // one line quoting its answer, sums them up in a line above the page, puts a button in the page's
5
- // corner that goes from one thing waiting for the reader to the next, and counts them in the tab
6
- // title. Unread messages also get a toast that stays while there are any. A message is found on the
7
- // page by its element (`data-wb-message`), or, when it isn't shown, by the element that holds it
4
+ // one line quoting its answer, sums them up in a line above the page, counts them in the tab title,
5
+ // and puts two toasts in the page's corner, "→ unanswered (n)" for the questions and "→ unread
6
+ // (n)" for the messages, each going from one to the next. A message is found on the page by its
7
+ // element (`data-wb-message`), or, when it isn't shown, by the element that holds it
8
8
  // (`data-wb-holds`: a comment's badge), which is sent `wb-reveal` to show it. Arriving by a link that
9
9
  // ends in `#wb-waiting` (the header's menu, the overview), the page goes to the first. An answer no
10
10
  // agent is listening for says so once it is sent, in a toast: the form's own mark may be out of view.
@@ -15,7 +15,7 @@ import { WAITING_HASH } from './elsewhere'
15
15
 
16
16
  const ORDER = STATES
17
17
  const LABEL: Record<FormState, (n: number) => string> = {
18
- open: n => `${n} waiting for you`,
18
+ open: n => `${n} unanswered`,
19
19
  pending: n => `${n} waiting for the agent`,
20
20
  decided: n => `${n} decided`,
21
21
  }
@@ -25,10 +25,6 @@ let main: HTMLElement
25
25
  let api: Api
26
26
  let forms: FormStatus[] = []
27
27
 
28
- const button = document.createElement('button')
29
- button.type = 'button'
30
- button.className = 'wb-waiting-next'
31
- button.hidden = true
32
28
 
33
29
  // above the page's content, not in it: #wb-main is compared block by block on every update
34
30
  const summary = document.createElement('div')
@@ -58,8 +54,11 @@ function targets(kind: 'all' | 'messages' = 'all'): HTMLElement[] {
58
54
  return list.sort((a, b) => top(a) - top(b))
59
55
  }
60
56
 
61
- let messagesToast: Toast | null = null
57
+ // the corner's toasts: the questions waiting, and the agent's messages unread; each goes to the next
58
+ let waitingToast: Toast
59
+ let unreadToast: Toast
62
60
  let toastTimer = 0
61
+ let unreadShown = false
63
62
 
64
63
  function show(list: FormStatus[] = forms) {
65
64
  forms = list
@@ -79,20 +78,22 @@ function show(list: FormStatus[] = forms) {
79
78
  return i ? [document.createTextNode(' · '), link] : [link]
80
79
  }))
81
80
  const n = inState('open').length + unread
82
- button.hidden = n === 0
83
- button.textContent = `→ waiting for you (${n})`
81
+ const questions = inState('open').length
82
+ if (questions) { waitingToast.update(`→ unanswered (${questions})`); waitingToast.show() } else waitingToast.hide()
84
83
  api.badge('waiting', n ? `!${n}` : null, -1)
85
- // the agent's messages, wherever the reader is scrolled: a toast while there are any. It comes a
86
- // moment late: a message that arrives in view (an open thread) is read before it would show.
87
- if (!unread) { messagesToast?.close(); messagesToast = null; clearTimeout(toastTimer) }
88
- else if (messagesToast) messagesToast.update(messagesLabel(unread))
89
- else {
90
- clearTimeout(toastTimer)
91
- toastTimer = window.setTimeout(() => {
92
- const left = api.unread().length
93
- if (left && !messagesToast) messagesToast = api.toast(messagesLabel(left), { ms: 0, onClick: () => jump('messages') })
94
- }, 1000)
95
- }
84
+ // the agent's messages: a toast while there are any. It comes a moment late: a message that
85
+ // arrives in view (an open thread) is read before it would show.
86
+ clearTimeout(toastTimer)
87
+ if (!unread) unreadToast.hide()
88
+ else if (unreadShown) unreadToast.update(`→ unread (${unread})`)
89
+ else toastTimer = window.setTimeout(() => {
90
+ const left = api.unread().length
91
+ if (!left) return
92
+ unreadToast.update(`→ unread (${left})`)
93
+ unreadToast.show()
94
+ unreadShown = true
95
+ }, 1000)
96
+ if (!unread) unreadShown = false
96
97
  // arrived to answer: the first thing waiting, once the page knows (the log loads after the page)
97
98
  if (arriving && n) {
98
99
  arriving = false
@@ -138,8 +139,10 @@ function jumpTo(target: HTMLElement) {
138
139
  export function trackWaiting(root: HTMLElement, core: Api) {
139
140
  main = root
140
141
  api = core
141
- api.corner().prepend(button)
142
- button.addEventListener('click', () => jump('all'))
142
+ waitingToast = api.toast('', { ms: 0, name: 'waiting', order: -2, onClick: () => jump('open') })
143
+ unreadToast = api.toast('', { ms: 0, name: 'unread', order: -1, onClick: () => jump('messages') })
144
+ waitingToast.hide()
145
+ unreadToast.hide()
143
146
  main.before(summary)
144
147
  summary.addEventListener('click', e => {
145
148
  const state = (e.target as HTMLElement).closest<HTMLElement>('button[data-state]')?.dataset.state as FormState | 'messages' | undefined
@@ -174,8 +177,8 @@ export function trackWaiting(root: HTMLElement, core: Api) {
174
177
  if (form.dataset.wbState === 'sending') return
175
178
  sent.disconnect()
176
179
  if (form.dataset.wbState !== 'sent') return
177
- if (fallback) api.toast('Sent. No agent waits on this page; the fallback agent picks it up.')
178
- else api.toast('Sent, but no agent is listening right now. Your answer stays in the log until one checks this page.', { kind: 'warn' })
180
+ if (fallback) api.toast('Sent. No agent waits on this page; the fallback agent picks it up.', { name: 'sent' })
181
+ else api.toast('Sent, but no agent is listening right now. Your answer stays in the log until one checks this page.', { kind: 'warn', name: 'sent' })
179
182
  })
180
183
  sent.observe(form, { attributes: true, attributeFilter: ['data-wb-state'] })
181
184
  })
@@ -4,10 +4,11 @@
4
4
  import type { Api, PluginMount, Listener, PageHandle, RenderedPage, StoredPage, WbEvent } from '../define'
5
5
  import { html } from '../html.ts'
6
6
  import { formsApi, trackForms } from './forms'
7
- import { toast } from './toast'
7
+ import { createToast } from './toast'
8
8
  import { markRead, messagesChanged, readsArrived, trackReading, unread } from './read'
9
9
  import { READ } from '../status.ts'
10
10
  import { markdown } from './markdown'
11
+ import { scrollToTarget } from './scroll'
11
12
 
12
13
  interface Handoff {
13
14
  id: string; kind: StoredPage['kind']; data: unknown
@@ -96,7 +97,7 @@ const api: Api = {
96
97
  writeTitle()
97
98
  },
98
99
  title(title) { baseTitle = title; writeTitle() },
99
- toast,
100
+ toast: createToast(() => corner),
100
101
  ...formsApi,
101
102
  }
102
103
 
@@ -146,6 +147,11 @@ function connect() {
146
147
  }
147
148
  go()
148
149
  })
150
+ // an agent shows the reader a place on the page
151
+ es.addEventListener('scroll', e => {
152
+ const { to } = JSON.parse((e as MessageEvent).data) as { to: string }
153
+ if (!scrollToTarget(root, to)) console.warn(`whiteboard scroll: nothing on the page matches ${JSON.stringify(to)}`)
154
+ })
149
155
  es.addEventListener('style', () => {
150
156
  for (const link of document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')) {
151
157
  const url = new URL(link.href)
@@ -0,0 +1,44 @@
1
+ // An agent shows the reader a place on the page (`whiteboard scroll <page> <where>`): the live
2
+ // channel says where, and the page goes there. `where` is, in this order: a heading whose text it
3
+ // is (or, failing that, contains), a form of that name, an element with that id, or the first text
4
+ // that contains it. A <details> around it opens; it is scrolled to just below the header and the
5
+ // titles of open details that stick above it, and lit up a moment, so the eye finds it.
6
+
7
+ const norm = (s: string) => s.replace(/\s+/g, ' ').trim().toLowerCase()
8
+
9
+ export function findTarget(root: ParentNode, where: string): HTMLElement | null {
10
+ const want = norm(where)
11
+ const headings = [...root.querySelectorAll<HTMLElement>('h1, h2, h3, h4, h5, h6, summary')]
12
+ const heading = headings.find(h => norm(h.textContent ?? '') === want) ?? headings.find(h => norm(h.textContent ?? '').includes(want))
13
+ if (heading) return heading
14
+ const byName = [...root.querySelectorAll<HTMLElement>('form[name]')].find(f => f.getAttribute('name') === where.trim())
15
+ if (byName) return byName
16
+ const byId = root.querySelector<HTMLElement>(`#${CSS.escape(where.trim())}`)
17
+ if (byId) return byId
18
+ const walker = document.createTreeWalker(root as Node, NodeFilter.SHOW_TEXT)
19
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
20
+ if (norm(n.textContent ?? '').includes(want) && n.parentElement && !n.parentElement.closest('script, style')) return n.parentElement
21
+ }
22
+ return null
23
+ }
24
+
25
+ export function scrollToTarget(root: ParentNode, where: string): boolean {
26
+ const target = findTarget(root, where)
27
+ if (!target) return false
28
+ // a <details> around it opens (a summary's own details stays as it is)
29
+ for (let d = (target.tagName === 'SUMMARY' ? target.parentElement?.parentElement : target)?.closest('details'); d; d = d.parentElement?.closest('details')) d.open = true
30
+ requestAnimationFrame(() => {
31
+ // below the header, and below the titles of the open details around it, which stick
32
+ let offset = (document.querySelector<HTMLElement>('.wb-nav')?.getBoundingClientRect().height ?? 0) + 12
33
+ for (let d = target.parentElement?.closest('details'); d; d = d.parentElement?.closest('details')) {
34
+ const summary = d.querySelector<HTMLElement>(':scope > summary')
35
+ if (summary && summary !== target) offset += summary.getBoundingClientRect().height
36
+ }
37
+ scrollTo({ top: Math.max(0, scrollY + target.getBoundingClientRect().top - offset), behavior: 'smooth' })
38
+ target.classList.remove('wb-flash')
39
+ void target.offsetWidth
40
+ target.classList.add('wb-flash')
41
+ setTimeout(() => target.classList.remove('wb-flash'), 2000)
42
+ })
43
+ return true
44
+ }