@bigmistqke/whiteboard 0.7.0 → 0.8.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 (66) hide show
  1. package/README.md +10 -209
  2. package/bin/whiteboard.ts +82 -239
  3. package/dist/bin/whiteboard.js +70 -200
  4. package/dist/client/runtime.js +66 -7
  5. package/dist/plugins/chat/public/style.css +10 -6
  6. package/dist/plugins/code/README.md +10 -0
  7. package/dist/plugins/code/index.js +31 -22
  8. package/dist/plugins/code/public/client.js +1 -0
  9. package/dist/plugins/code/public/style.css +33 -2
  10. package/dist/plugins/comments/public/client.js +1 -1
  11. package/dist/plugins/form/public/style.css +2 -0
  12. package/dist/plugins/iframe/index.js +2 -2
  13. package/dist/plugins/lightbox/public/client.js +1 -1
  14. package/dist/plugins/terminal/index.js +7 -9
  15. package/dist/plugins/terminal/public/client.js +1 -1
  16. package/dist/plugins/terminal/public/style.css +3 -3
  17. package/dist/plugins/toc/index.js +1 -1
  18. package/dist/plugins/toc/public/client.js +1 -1
  19. package/dist/plugins/window/index.js +4 -4
  20. package/dist/src/build.js +159 -0
  21. package/dist/src/client/page/main.js +1 -1
  22. package/dist/src/document.js +93 -0
  23. package/dist/src/events.js +3 -13
  24. package/dist/src/hub.js +47 -35
  25. package/dist/src/listen.js +100 -0
  26. package/dist/src/listeners.js +67 -0
  27. package/dist/src/pages/index.js +1 -1
  28. package/dist/src/pages/markdown.js +23 -11
  29. package/dist/src/pages/render.js +13 -8
  30. package/dist/src/server.js +166 -514
  31. package/dist/src/site.js +173 -0
  32. package/dist/src/status.js +63 -1
  33. package/package.json +1 -1
  34. package/plugins/README.md +258 -0
  35. package/plugins/chat/public/style.css +10 -6
  36. package/plugins/code/README.md +10 -0
  37. package/plugins/code/client.ts +73 -0
  38. package/plugins/code/index.ts +38 -26
  39. package/plugins/code/public/style.css +33 -2
  40. package/plugins/comments/client.ts +8 -1
  41. package/plugins/form/public/style.css +2 -0
  42. package/plugins/iframe/index.ts +2 -2
  43. package/plugins/lightbox/client.ts +13 -3
  44. package/plugins/terminal/client.ts +10 -2
  45. package/plugins/terminal/index.ts +8 -6
  46. package/plugins/terminal/public/style.css +3 -3
  47. package/plugins/toc/client.ts +9 -2
  48. package/plugins/toc/index.ts +1 -1
  49. package/plugins/window/index.ts +4 -4
  50. package/skills/whiteboard/SKILL.md +3 -1
  51. package/src/build.ts +213 -0
  52. package/src/client/page/elsewhere.ts +2 -1
  53. package/src/client/runtime.ts +88 -10
  54. package/src/client/toast.ts +1 -1
  55. package/src/define.ts +34 -18
  56. package/src/document.ts +191 -0
  57. package/src/events.ts +11 -16
  58. package/src/hub.ts +48 -34
  59. package/src/listen.ts +125 -0
  60. package/src/listeners.ts +95 -0
  61. package/src/pages/index.ts +1 -1
  62. package/src/pages/markdown.ts +29 -18
  63. package/src/pages/render.ts +13 -8
  64. package/src/server.ts +165 -609
  65. package/src/site.ts +165 -0
  66. package/src/status.ts +100 -0
@@ -1,12 +1,12 @@
1
1
  // The core in the browser: the page's events, the live channel, and handing the page to the page
2
2
  // module (./page: markdown live, the blocks' islands) and the plugins' modules. When the config failed
3
3
  // to load, the page is its raw text: the server's HTML, replaced when it changes.
4
- import type { Api, PluginMount, Listener, PageHandle, RenderedPage, StoredPage, WbEvent } from '../define'
4
+ import type { Api, PluginMount, Listener, PageHandle, RenderedPage, SlotName, StoredPage, WbEvent } from '../define'
5
5
  import { html } from '../html.ts'
6
6
  import { formsApi, trackForms } from './forms'
7
7
  import { createToast } from './toast'
8
8
  import { markRead, messagesChanged, readsArrived, trackReading, unread as unreadNow } from './read'
9
- import { READ } from '../status.ts'
9
+ import { READ, SCROLL, fromReader } from '../status.ts'
10
10
  import { markdown } from './markdown'
11
11
  import { scrollToTarget } from './scroll'
12
12
  import { reactive } from './reactive'
@@ -26,6 +26,8 @@ interface Handoff {
26
26
  frontmatter: Record<string, unknown>
27
27
  /** false on a built page (`whiteboard build`): a file, no server behind it */
28
28
  live?: boolean
29
+ /** what the browser runs and how it looks, as the server served them (see /api/stamps) */
30
+ stamps?: { code: string; style: string }
29
31
  }
30
32
 
31
33
  const handoff: Handoff = JSON.parse(document.getElementById('wb-page')!.textContent!)
@@ -60,6 +62,20 @@ async function loadEvents() {
60
62
  const known = new Set(all.map(e => e.id))
61
63
  for (const [id, e] of sending) if (known.has(id)) sending.delete(id)
62
64
  setEvents([...all, ...[...sending.values()]])
65
+ scrollFromLog()
66
+ }
67
+
68
+ // `whiteboard scroll` is an event in the log (SCROLL), so a scroll sent while this page wasn't
69
+ // connected still happens once it is. The latest one counts; the first load only notes which that
70
+ // is, so a page loaded later doesn't jump to a place shown before it.
71
+ let scrolledTo: string | null | undefined
72
+ function scrollFromLog() {
73
+ const last = events.findLast(e => e.type === SCROLL && !fromReader(e))
74
+ if (scrolledTo === undefined) return void (scrolledTo = last?.id ?? null)
75
+ if (!last || last.id === scrolledTo) return
76
+ scrolledTo = last.id
77
+ const to = String(last.data?.to ?? '')
78
+ if (!scrollToTarget(root, to)) console.warn(`whiteboard scroll: nothing on the page matches ${JSON.stringify(to)}`)
63
79
  }
64
80
 
65
81
  // Appending is optimistic: the event is in the page's events at once, marked `sending`, so the page
@@ -151,6 +167,50 @@ function writeTitle() {
151
167
  document.title = `${list.map(b => `(${b.text}) `).join('')}${baseTitle}`
152
168
  }
153
169
 
170
+ // ---- slots -------------------------------------------------------------------------------------
171
+
172
+ /** The plugins in their order, which is the order of their elements in a slot. */
173
+ const pluginOrder = (handoff.plugins ?? []).map(p => p.name)
174
+
175
+ /**
176
+ * Mount `owner`'s element in a slot (Api.slot): the one the server rendered with its markup, or a
177
+ * new one, put among the others in plugin order. What `mount` returns runs when it is taken away.
178
+ */
179
+ function slotFor(owner: string, name: SlotName, mount: (el: HTMLElement) => void | (() => void)): () => void {
180
+ const holder =
181
+ name === 'corner'
182
+ ? corner
183
+ : name === 'header'
184
+ ? root.querySelector<HTMLElement>('[data-wb-slot=header]')
185
+ : document.querySelector<HTMLElement>(`body > [data-wb-slot=${name}]`)
186
+ if (!holder) return () => {}
187
+ let el = [...holder.children].find((c): c is HTMLElement => c instanceof HTMLElement && c.dataset.plugin === owner)
188
+ if (!el) {
189
+ el = document.createElement('div')
190
+ el.dataset.plugin = owner
191
+ const at = pluginOrder.indexOf(owner)
192
+ const next = [...holder.children].find(
193
+ c => c instanceof HTMLElement && c.dataset.plugin != null && pluginOrder.indexOf(c.dataset.plugin) > at,
194
+ )
195
+ holder.insertBefore(el, next ?? null)
196
+ }
197
+ const unmount = mount(el)
198
+ let gone = false
199
+ return () => {
200
+ if (gone) return
201
+ gone = true
202
+ unmount?.()
203
+ el.remove()
204
+ }
205
+ }
206
+
207
+ /** The page's own element in the corner (its toasts), made the first time it is asked for. */
208
+ let pageCorner: HTMLElement | null = null
209
+ const cornerOfPage = (): HTMLElement => {
210
+ if (!pageCorner) slotFor('', 'corner', el => void (pageCorner = el))
211
+ return pageCorner ?? corner
212
+ }
213
+
154
214
  const api: Api = {
155
215
  page,
156
216
  url,
@@ -179,7 +239,8 @@ const api: Api = {
179
239
  renderedListeners.add(fn)
180
240
  return () => renderedListeners.delete(fn)
181
241
  },
182
- corner: () => corner,
242
+ // the page's own (not a plugin's): before the plugins' in a slot
243
+ slot: (name, mount) => slotFor('', name, mount),
183
244
  badge(key, text, order = 0) {
184
245
  if (text == null) badges.delete(key)
185
246
  else badges.set(key, { text, order, since: badges.get(key)?.since ?? badgeCount++ })
@@ -189,7 +250,7 @@ const api: Api = {
189
250
  baseTitle = title
190
251
  writeTitle()
191
252
  },
192
- toast: createToast(() => corner),
253
+ toast: createToast(cornerOfPage),
193
254
  ...formsApi,
194
255
  }
195
256
 
@@ -281,12 +342,8 @@ const onLive: Record<string, (data: unknown) => void> = {
281
342
  // the server answers: reloading while it restarts would leave the browser's error page, which
282
343
  // has nothing left in it to recover with.
283
344
  reload: () => reloadWhenUp(),
284
- // an agent shows the reader a place on the page
285
- scroll: data => {
286
- const { to } = data as { to: string }
287
- if (!scrollToTarget(root, to)) console.warn(`whiteboard scroll: nothing on the page matches ${JSON.stringify(to)}`)
288
- },
289
345
  style: () => {
346
+ stamps = null
290
347
  for (const link of document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')) {
291
348
  const url = new URL(link.href)
292
349
  if (url.origin !== location.origin) continue
@@ -296,6 +353,26 @@ const onLive: Record<string, (data: unknown) => void> = {
296
353
  },
297
354
  }
298
355
 
356
+ // What the browser runs and how it looks, as this page has them; null once a style message refreshed
357
+ // the stylesheets without a stamp to go with it (the next comparison takes the server's then).
358
+ let stamps: { code: string; style: string } | null = handoff.stamps ?? null
359
+
360
+ /**
361
+ * Back on the live channel: what changed while this page wasn't on it, it never heard of. Browser
362
+ * code that changed reloads the page; stylesheets that changed are refreshed in place.
363
+ */
364
+ async function compareStamps() {
365
+ let now: { code: string; style: string }
366
+ try {
367
+ now = await (await fetch(url('/api/stamps'), { cache: 'no-store' })).json()
368
+ } catch {
369
+ return
370
+ }
371
+ if (stamps && now.code !== stamps.code) return reloadWhenUp()
372
+ if (stamps && now.style !== stamps.style) onLive.style!(null)
373
+ stamps = now
374
+ }
375
+
299
376
  let socket: WebSocket | null = null
300
377
  let retries = 0
301
378
  let retryTimer: ReturnType<typeof setTimeout> | undefined
@@ -313,6 +390,7 @@ function connect() {
313
390
  // elsewhere
314
391
  loadListeners()
315
392
  loadEvents()
393
+ void compareStamps()
316
394
  document.dispatchEvent(new Event('wb-elsewhere'))
317
395
  // and the page, if it changed while the channel wasn't open yet (just after loading, or while
318
396
  // the server restarted): that change was never announced. Only then: an update that changes
@@ -394,7 +472,7 @@ await Promise.all(
394
472
  const mount: PluginMount = (await import(moduleUrl(ext.client))).default
395
473
  if (typeof mount !== 'function')
396
474
  throw new Error('the client module must export a mount(root, page, api) function as default')
397
- await mount(root, handleFor(ext.name), api)
475
+ await mount(root, handleFor(ext.name), { ...api, slot: (name, mount) => slotFor(ext.name, name, mount) })
398
476
  } catch (err) {
399
477
  console.error(`plugin ${ext.name}:`, err)
400
478
  root.insertAdjacentHTML(
@@ -1,4 +1,4 @@
1
- // Toasts (api.toast): short labels in the page's corner (api.corner(), above what covers the bottom
1
+ // Toasts (api.toast): short labels in the page's corner (its element in the corner slot, above what covers the bottom
2
2
  // of the window) that say what is going on and take the reader there: "→ unanswered (2)",
3
3
  // "↓ new (3)", "Sent, but no agent is listening". One goes after a few seconds, or on a click; one
4
4
  // with `ms: 0` stays until closed, and changes its text, or hides and shows again, through what
package/src/define.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  import type { IncomingMessage, ServerResponse } from 'node:http'
10
10
  import type { Html } from './html.ts'
11
11
 
12
- // HTML from a template literal, escaped by default: for a block, a plugin's `shell`
12
+ // HTML from a template literal, escaped by default: for a block, a plugin's `slots`
13
13
  export { html, raw, escape, Html } from './html.ts'
14
14
  export { windowFrame, type WindowOptions } from './pages/window.ts'
15
15
 
@@ -185,11 +185,9 @@ export interface PluginContext {
185
185
  dataDir: string
186
186
  /**
187
187
  * whether a request carries the project's token: for a check of its own, beyond a route's `auth`.
188
- * No request (`shell` for a page being built) has none.
188
+ * No request (`slots` for a page being built) has none.
189
189
  */
190
190
  authorized(req: IncomingMessage | null): boolean
191
- /** the URL that serves a file of the plugin (its browser module, a stylesheet) */
192
- asset(file: URL | string): string
193
191
  }
194
192
 
195
193
  /**
@@ -198,13 +196,29 @@ export interface PluginContext {
198
196
  */
199
197
  export type FieldType = 'string' | 'number' | 'boolean' | 'string[]' | 'string?' | 'number?' | 'boolean?' | 'string[]?'
200
198
 
199
+ /**
200
+ * The places on a page the core owns, for what a plugin puts there (each plugin its own element in
201
+ * each, in plugin order; see Api.slot): `header`, in the page's header bar before the theme button;
202
+ * `aside`, `bottom` and `overlay`, at the end of <body>, laid out as their content says (a panel
203
+ * beside the text, a drawer, something over the page); `corner`, the column of floating labels at
204
+ * the bottom right.
205
+ */
206
+ export type SlotName = 'header' | 'aside' | 'bottom' | 'overlay' | 'corner'
207
+
208
+ /**
209
+ * What a plugin's `slots` gives a page on the server: `head` at the end of <head>, and markup for
210
+ * its element in each slot but `header` (the header bar is the page's own render; a plugin adds to
211
+ * it in the browser).
212
+ */
213
+ export type SlotMarkup = { [K in 'head' | Exclude<SlotName, 'header'>]?: string | Html }
214
+
201
215
  export interface PluginHooks {
202
216
  /** by method and path, `'POST /start'`: mounted at `/api/<name>/start` */
203
217
  routes?: Record<string, Route>
204
218
  /**
205
- * Markup for the page shell, outside the page's root: `head` at the end of <head>, `body` at
206
- * the end of <body>. Called for every page; null adds nothing. The body is there for the first
207
- * render, so an element in it can take part in the view transition between two pages.
219
+ * Markup for the page's slots (SlotMarkup), on the server: there on the first render, so an
220
+ * element in it can take part in the view transition between two pages. The browser module then
221
+ * mounts on its element in each slot (Api.slot). Called for every page; null adds nothing.
208
222
  *
209
223
  * Something that covers an edge of the window (a drawer at the bottom) says how much of it, as a
210
224
  * length in `--wb-inset-bottom` on :root, registered with `@property` so that it computes to
@@ -215,17 +229,12 @@ export interface PluginHooks {
215
229
  * browser asked for: what is only for the project's own browser (the terminal's drawer, behind
216
230
  * `authorized`) has nothing to add there.
217
231
  */
218
- shell?(
219
- req: IncomingMessage | null,
220
- ):
221
- | { head?: string | Html; body?: string | Html }
222
- | null
223
- | Promise<{ head?: string | Html; body?: string | Html } | null>
232
+ slots?(req: IncomingMessage | null): SlotMarkup | null | Promise<SlotMarkup | null>
224
233
  /**
225
234
  * A browser module whose default export is an `PluginMount`: on every page, the core imports
226
235
  * it once the page has mounted, and hands it the page and its api. For
227
236
  * behaviour on the page's own content (its forms, say); markup of the plugin's own can come
228
- * from `shell` instead. A file in the plugin's public folder: `'client.js'`.
237
+ * from `slots` instead. A file in the plugin's public folder: `'client.js'`.
229
238
  */
230
239
  client?: URL | string
231
240
  }
@@ -582,11 +591,12 @@ export interface Api {
582
591
  /** called after each `rendered()`; returns an unsubscribe */
583
592
  onRendered(fn: () => void): () => void
584
593
  /**
585
- * The page's corner: a column at the bottom right, above whatever covers the bottom of the
586
- * window (`--wb-inset-bottom`), for floating buttons. The page and the plugins each add
587
- * their own; the core draws nothing in it.
594
+ * Mount on this plugin's own element in a slot (SlotName): `mount` is called with it, holding
595
+ * what the plugin's `slots` rendered there on the server, or empty, and what it returns is called
596
+ * when the element is taken away. The plugin never makes or looks up the element. Returns what
597
+ * takes it away. A page without the slot (raw text has no header bar) mounts nothing.
588
598
  */
589
- corner(): HTMLElement
599
+ slot(name: SlotName, mount: (el: HTMLElement) => void | (() => void)): () => void
590
600
  /**
591
601
  * A count in the tab title, under `key`: `(text)` in front of the page's title; null removes it.
592
602
  * Lower `order` comes first (default 0), so what waits for the reader can lead.
@@ -704,6 +714,12 @@ interface BaseContext {
704
714
  /** absolute path of the markdown file, and its folder (resolve files next to the page with it) */
705
715
  file: string
706
716
  dir: string
717
+ /**
718
+ * The address of a file named relative to the page (an image's `src`): served, the server's; in a
719
+ * build, of a copy beside the built page. A URL, an address from the root, or a file that isn't
720
+ * there comes back as written.
721
+ */
722
+ fileUrl(src: string): string
707
723
  name: string
708
724
  attrs: Record<string, string>
709
725
  parseAttrs(s: string): Record<string, string>
@@ -0,0 +1,191 @@
1
+ // A page as the browser gets it: the page's render, the plugins' parts (markup for <head> and
2
+ // <body>, their browser modules, notices of those that failed), and the handoff the browser runtime
3
+ // starts from. Put together here once, for a page the server serves and for one `whiteboard build`
4
+ // writes; what differs is told: how a file is addressed, whether the page is live, which plugins
5
+ // are left out, where a failing plugin is said.
6
+ import path from 'node:path'
7
+ import type { IncomingMessage } from 'node:http'
8
+ import { html, raw, type Html } from './html.ts'
9
+ import { PACKAGE_DIR } from './package.ts'
10
+ import type { MountedRoute } from './plugins.ts'
11
+ import type { Plugin, PluginHooks, Rendered, SlotName, StoredPage } from './define.ts'
12
+
13
+ /** The browser runtime, built by build.ts. */
14
+ export const RUNTIME = path.join(PACKAGE_DIR, 'dist', 'client', 'runtime.js')
15
+ /** The page in the browser (markdown live: morphing, blocks' islands, forms' marks), built by build.ts. */
16
+ export const PAGE_CLIENT = path.join(PACKAGE_DIR, 'dist', 'src', 'client', 'page', 'main.js')
17
+
18
+ /** A plugin once set up: what its setup returned, its mounted routes, or why it failed. */
19
+ export interface SetUp extends PluginHooks {
20
+ name: string
21
+ table: MountedRoute[]
22
+ plugin: Plugin
23
+ error?: Error
24
+ }
25
+
26
+ /** A render as the document takes it. `page`: whether the page's browser part runs (not on raw text). */
27
+ export interface Render {
28
+ page: boolean
29
+ out: Rendered
30
+ notices: string[]
31
+ }
32
+
33
+ /** The slots at the end of <body>, in the order they are there; `corner` is the page's dock. */
34
+ const BODY_SLOTS = ['aside', 'bottom', 'overlay'] as const
35
+
36
+ /** A plugin's markup in a slot. */
37
+ type Slotted = { name: string; html: Html }
38
+
39
+ /** What the plugins add to a page. */
40
+ export interface PageParts {
41
+ head: Html[]
42
+ /** each plugin's markup in each slot, in plugin order */
43
+ slots: { [K in Exclude<SlotName, 'header'>]: Slotted[] }
44
+ /** their browser modules, which the runtime imports after the page's */
45
+ clients: { name: string; client: string }[]
46
+ /** the event types that, from the agent, are messages for the reader (EventSpec.forReader) */
47
+ messages: string[]
48
+ }
49
+
50
+ /**
51
+ * What the plugins add to a page: each one's markup for the slots (`slots`, asked with the browser's request, or
52
+ * null for a page no browser asked for), and its browser module. One that failed to start or fails
53
+ * here is left out and told to `failed`; so are those in `leaveOut` (a build's skip), silently.
54
+ */
55
+ export async function pluginParts(
56
+ hooks: SetUp[],
57
+ req: IncomingMessage | null,
58
+ {
59
+ asset,
60
+ messages,
61
+ leaveOut = new Set(),
62
+ failed,
63
+ }: {
64
+ asset(ref: string | URL): string
65
+ messages: string[]
66
+ leaveOut?: ReadonlySet<string>
67
+ failed(message: string): void
68
+ },
69
+ ): Promise<PageParts> {
70
+ const included = hooks.filter(h => !leaveOut.has(h.name))
71
+ for (const h of included) if (h.error) failed(`plugin "${h.name}" failed to start: ${h.error.message}`)
72
+ const working = included.filter(h => !h.error)
73
+ const parts = await Promise.all(
74
+ working.map(async h => {
75
+ try {
76
+ return (await h.slots?.(req)) ?? null
77
+ } catch (err) {
78
+ failed(`plugin "${h.name}" failed on this page: ${(err as Error).message}`)
79
+ return null
80
+ }
81
+ }),
82
+ )
83
+ const slotted = (slot: Exclude<SlotName, 'header'>): Slotted[] =>
84
+ working.flatMap((h, i) => {
85
+ const markup = parts[i]?.[slot]
86
+ return markup == null ? [] : [{ name: h.name, html: raw(String(markup)) }]
87
+ })
88
+ return {
89
+ head: parts.map(x => raw(String(x?.head ?? ''))),
90
+ slots: {
91
+ aside: slotted('aside'),
92
+ bottom: slotted('bottom'),
93
+ overlay: slotted('overlay'),
94
+ corner: slotted('corner'),
95
+ },
96
+ clients: working.filter(h => h.client).map(h => ({ name: h.name, client: asset(h.client!) })),
97
+ messages,
98
+ }
99
+ }
100
+
101
+ /** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
102
+ export const frontmatterOf = (page: StoredPage): Record<string, unknown> =>
103
+ page.kind === 'page' ? page.frontmatter : {}
104
+
105
+ /** JSON made safe inside a <script>. */
106
+ const json = (s: unknown) => JSON.stringify(s).replace(/</g, '\\u003c')
107
+
108
+ // the page's corner (the corner slot): the one thing the core puts on every page, empty, for the
109
+ // page's and the plugins' floating buttons and toasts; above what covers the bottom of the window.
110
+ // Above the page and what floats on it (comment threads: 20), under what fills the window (a
111
+ // maximized frame: 40, a lightbox or the terminal drawer: 50)
112
+ const DOCK_STYLE =
113
+ '#wb-dock{position:fixed;right:16px;bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:30;display:flex;flex-direction:column;align-items:flex-end;gap:6px}#wb-dock:not(:has(> :not(:empty))){display:none}' +
114
+ // the slots (SlotName) and each plugin's element in one: laid out as what is in them says, as if
115
+ // that were where the slot is (a fixed drawer, a panel, a button in the header bar)
116
+ '[data-wb-slot]:not(#wb-dock),[data-wb-slot]>[data-plugin]{display:contents}' +
117
+ // toasts (api.toast): labels in the corner, in the page's theme colours where it has them
118
+ '.wb-toasts{display:flex;flex-direction:column;align-items:flex-end;gap:6px}.wb-toasts:empty{display:none}' +
119
+ '.wb-toast{display:inline-flex;align-items:center;gap:8px;cursor:pointer;padding:5px 12px;border-radius:99px;font:600 .8rem/1.4 var(--sans,system-ui,sans-serif);background:var(--accent,#1d5bbf);color:var(--accent-text,#fff);border:1px solid transparent;box-shadow:0 2px 10px rgb(0 0 0/.18)}' +
120
+ '.wb-toast[hidden]{display:none}.wb-toast[data-kind=warn]{background:var(--warn,#6b4fc0)}.wb-toast[data-kind=alert]{background:var(--bad,#c4352b);color:#fff}' +
121
+ // where an agent scrolled the page to, lit up a moment
122
+ '@keyframes wb-flash{from{outline-color:var(--accent,#1d5bbf)}to{outline-color:transparent}}.wb-flash{outline:3px solid transparent;outline-offset:6px;border-radius:4px;animation:wb-flash 2s ease-out}' +
123
+ '.wb-toast-dismiss{margin-right:-4px;padding:0 4px;border-left:1px solid rgb(255 255 255/.35);opacity:.75}.wb-toast-dismiss:hover{opacity:1}' +
124
+ // a toast's details (ToastOptions.details): a ▸ on its line, unfolding them under it
125
+ '.wb-toast{max-width:min(24rem,calc(100vw - 32px));text-align:left}.wb-toast-more{margin:0 -4px 0 -2px;padding:0 4px;opacity:.75}.wb-toast-more:hover{opacity:1}' +
126
+ '.wb-toast[data-open]{flex-wrap:wrap;border-radius:12px}.wb-toast-details{flex-basis:100%;padding:2px 0 3px;font-weight:400;cursor:text}.wb-toast-details[hidden]{display:none}'
127
+
128
+ /** How a page is put out: by the server (live) or by a build (a file with no server behind it). */
129
+ export interface Output {
130
+ /** a page the server serves: events, listeners and updates; false for a built page */
131
+ live: boolean
132
+ /** what the page's own requests start with (ServerOptions.base); '' for a built page */
133
+ base: string
134
+ /** the address of a file the page loads */
135
+ asset(ref: string | URL): string
136
+ /** the address of the browser runtime */
137
+ runtime: string
138
+ /** the title when the render has none and the page no id: the project's name */
139
+ title: string
140
+ /** what the browser runs and how it looks, compared again when the live channel is back */
141
+ stamps?: { code: string; style: string }
142
+ }
143
+
144
+ /** Each plugin's own element in a slot, with what it rendered there. */
145
+ const slotted = (list: Slotted[]) => list.map(x => html`<div data-plugin="${x.name}">${x.html}</div>`)
146
+
147
+ /** A page as a document: the render, the plugins' parts, and the handoff for the browser runtime. */
148
+ export function pageDocument(
149
+ page: StoredPage,
150
+ { page: rendered, out, notices }: Render,
151
+ parts: PageParts,
152
+ o: Output,
153
+ ): string {
154
+ const handoff = {
155
+ id: page.id,
156
+ kind: page.kind,
157
+ live: o.live,
158
+ base: o.base,
159
+ client: rendered ? o.asset(PAGE_CLIENT) : null,
160
+ data: out.data ?? null,
161
+ frontmatter: frontmatterOf(page),
162
+ plugins: parts.clients,
163
+ messages: parts.messages,
164
+ ...(o.stamps && { stamps: o.stamps }),
165
+ }
166
+ // the page's head and html are HTML already; the handoff is JSON made safe for a script tag
167
+ return String(
168
+ html`<!doctype html>
169
+ <html lang="en">
170
+ <head>
171
+ <meta charset="utf-8" />
172
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
173
+ <title>${out.title || page.id || o.title}</title>
174
+ <style>
175
+ ${DOCK_STYLE}
176
+ </style>
177
+ ${raw(String(out.head ?? ''))}${parts.head}
178
+ </head>
179
+ <body data-page="${page.id}" data-kind="${page.kind}">
180
+ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
181
+ <div id="wb-root">${raw(String(out.html))}</div>
182
+ <div id="wb-dock" data-wb-slot="corner">${slotted(parts.slots.corner)}</div>
183
+ <script type="application/json" id="wb-page">
184
+ ${raw(json(handoff))}
185
+ </script>
186
+ <script type="module" src="${o.runtime}"></script>
187
+ ${BODY_SLOTS.map(name => html`<div data-wb-slot="${name}">${slotted(parts.slots[name])}</div>`)}
188
+ </body>
189
+ </html>`,
190
+ )
191
+ }
package/src/events.ts CHANGED
@@ -9,9 +9,9 @@
9
9
  import fs from 'node:fs'
10
10
  import crypto from 'node:crypto'
11
11
  import type { WbEvent } from './define.ts'
12
- import { fromReader } from './status.ts'
12
+ import { CLAIM, PICKED, fromReader, pickedUp } from './status.ts'
13
13
 
14
- export { fromReader }
14
+ export { CLAIM, PICKED, fromReader, pickedUp }
15
15
 
16
16
  /** What is appended: the id and time are added. */
17
17
  export interface EventInput {
@@ -31,12 +31,6 @@ export interface EventFilter {
31
31
  exact?: boolean
32
32
  }
33
33
 
34
- /**
35
- * The type of the event `whiteboard new` appends when an agent session creates a page:
36
- * `{ session }`. The colon keeps it apart from form names, which are event types too.
37
- */
38
- export const CLAIM = 'whiteboard:claim'
39
-
40
34
  // ---- primitives ----------------------------------------------------------------------------------
41
35
 
42
36
  /** An event id as the log has them: the time in base 36, a dash, random hex. */
@@ -270,14 +264,6 @@ export function matches(event: WbEvent, { page, type, exact }: EventFilter = {})
270
264
  // is the only record: a wait that starts hands out the matching events nobody picked up yet,
271
265
  // whatever its filter, and pages show the same events as picked up.
272
266
 
273
- /** The type of the event that says another event was handed to an agent: `{ event: <its id> }`. */
274
- export const PICKED = 'whiteboard:picked'
275
-
276
- /** The ids of the events that were picked up. Only the command line's picks count. */
277
- export function pickedUp(events: WbEvent[]): Set<string> {
278
- return new Set(events.filter(e => e.type === PICKED && !fromReader(e)).map(e => String(e.data?.event)))
279
- }
280
-
281
267
  /** Record that `event` was handed to an agent: from then on it counts as picked up. */
282
268
  export function pick(file: string, event: WbEvent): WbEvent {
283
269
  return appendEvent(file, { page: event.page, type: PICKED, data: { event: event.id } }, 'cli')
@@ -312,6 +298,12 @@ export interface HandOutOptions {
312
298
  */
313
299
  skip?: (event: WbEvent) => boolean
314
300
  recheck?: (again: () => void) => void
301
+ /**
302
+ * Hand out only what nobody picked up by the time it is offered (the fallback: an answer another
303
+ * listener took is not its, even when it sees it only after that one stopped listening). Without
304
+ * it, a new event is handed out also when another running hand-out got it too.
305
+ */
306
+ unpicked?: boolean
315
307
  }
316
308
 
317
309
  /**
@@ -339,6 +331,7 @@ export function handOut(
339
331
  forAgent: isForAgent = forAgent(),
340
332
  skip,
341
333
  recheck,
334
+ unpicked = false,
342
335
  } = options
343
336
  return new Promise(resolve => {
344
337
  let got = 0
@@ -361,6 +354,8 @@ export function handOut(
361
354
  const left = new Map<string, WbEvent>()
362
355
  // false once enough were handed out; a left event is kept to look at again
363
356
  const offer = (e: WbEvent) => {
357
+ // the log as it is now: a pick is appended right after the event it names
358
+ if (unpicked && pickedUp(read(file).events).has(e.id)) return true
364
359
  if (skip?.(e)) {
365
360
  left.set(e.id, e)
366
361
  return true