@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
@@ -5,19 +5,24 @@ import type { Api, PluginMount, Listener, PageHandle, RenderedPage, StoredPage,
5
5
  import { html } from '../html.ts'
6
6
  import { formsApi, trackForms } from './forms'
7
7
  import { createToast } from './toast'
8
- import { markRead, messagesChanged, readsArrived, trackReading, unread } from './read'
8
+ import { markRead, messagesChanged, readsArrived, trackReading, unread as unreadNow } from './read'
9
9
  import { READ } from '../status.ts'
10
10
  import { markdown } from './markdown'
11
11
  import { scrollToTarget } from './scroll'
12
+ import { reactive } from './reactive'
12
13
 
13
14
  interface Handoff {
14
- id: string; kind: StoredPage['kind']; data: unknown
15
+ id: string
16
+ kind: StoredPage['kind']
17
+ data: unknown
15
18
  /** the page module; null for raw text */
16
19
  client: string | null
17
20
  /** the plugins' browser modules */
18
21
  plugins: { name: string; client: string }[]
19
22
  /** the event types that, from the agent, are messages for the reader */
20
23
  messages: string[]
24
+ /** the page's frontmatter (PageHandle.frontmatter) */
25
+ frontmatter: Record<string, string>
21
26
  }
22
27
 
23
28
  const handoff: Handoff = JSON.parse(document.getElementById('wb-page')!.textContent!)
@@ -28,11 +33,14 @@ const isDir = handoff.kind === 'pages' || handoff.kind === 'folder'
28
33
  // ---- events ------------------------------------------------------------------------------------
29
34
 
30
35
  let events: WbEvent[] = []
31
- const eventListeners = new Set<(events: WbEvent[]) => void>()
36
+ const eventsValue = reactive(() => events)
37
+ // what is unread changes with the events, and with a message read here before the log has it
38
+ const unread = reactive(unreadNow)
32
39
  function setEvents(next: WbEvent[]) {
33
40
  events = next
34
41
  readsArrived(events)
35
- for (const fn of eventListeners) fn(events)
42
+ eventsValue.notify()
43
+ unread.notify()
36
44
  messagesChanged()
37
45
  }
38
46
 
@@ -42,7 +50,11 @@ async function loadEvents() {
42
50
  setEvents(all.filter(e => e.page === page))
43
51
  }
44
52
 
45
- async function append(type: string, data: Record<string, unknown> = {}, action: string | null = null): Promise<WbEvent> {
53
+ async function append(
54
+ type: string,
55
+ data: Record<string, unknown> = {},
56
+ action: string | null = null,
57
+ ): Promise<WbEvent> {
46
58
  const res = await fetch('/api/events', {
47
59
  method: 'POST',
48
60
  headers: { 'content-type': 'application/json' },
@@ -55,11 +67,11 @@ async function append(type: string, data: Record<string, unknown> = {}, action:
55
67
  }
56
68
 
57
69
  let listeners: Listener[] = []
58
- const listenerListeners = new Set<(listeners: Listener[]) => void>()
70
+ const listenersValue = reactive(() => listeners)
59
71
 
60
72
  async function loadListeners() {
61
73
  listeners = await (await fetch(`/api/listeners?page=${encodeURIComponent(page)}`)).json()
62
- for (const fn of listenerListeners) fn(listeners)
74
+ listenersValue.notify()
63
75
  }
64
76
 
65
77
  const renderedListeners = new Set<() => void>()
@@ -67,7 +79,9 @@ const renderedListeners = new Set<() => void>()
67
79
  // ---- the corner and the title ------------------------------------------------------------------
68
80
 
69
81
  // the server puts it in the page; a page from a server older than this runtime has none
70
- const corner = document.getElementById('wb-dock') ?? document.body.appendChild(Object.assign(document.createElement('div'), { id: 'wb-dock' }))
82
+ const corner =
83
+ document.getElementById('wb-dock') ??
84
+ document.body.appendChild(Object.assign(document.createElement('div'), { id: 'wb-dock' }))
71
85
  let baseTitle = document.title
72
86
  const badges = new Map<string, { text: string; order: number; since: number }>()
73
87
  let badgeCount = 0
@@ -78,25 +92,41 @@ function writeTitle() {
78
92
 
79
93
  const api: Api = {
80
94
  page,
81
- events: () => events,
82
- onEvents(fn) { eventListeners.add(fn); return () => eventListeners.delete(fn) },
95
+ events: eventsValue,
83
96
  last: type => events.findLast(e => e.type === type),
84
97
  pickedUp: id => !!events.find(e => e.id === id)?.pickedUp,
85
98
  unread,
86
- markRead,
99
+ markRead: ids => {
100
+ markRead(ids)
101
+ unread.notify()
102
+ },
87
103
  markdown,
88
104
  append,
89
- listeners: () => listeners,
90
- onListeners(fn) { listenerListeners.add(fn); return () => listenerListeners.delete(fn) },
91
- rendered() { for (const fn of renderedListeners) fn() },
92
- onRendered(fn) { renderedListeners.add(fn); return () => renderedListeners.delete(fn) },
105
+ listeners: listenersValue,
106
+ rendered() {
107
+ // the new page is in place: what came with its render is the page's now, before anyone hears
108
+ // of the update, so a listener reads the new values
109
+ const frontmatterChanged = JSON.stringify(nextFrontmatter) !== JSON.stringify(frontmatter)
110
+ data = nextData
111
+ frontmatter = nextFrontmatter
112
+ for (const fn of renderedListeners) fn()
113
+ dataValue.notify()
114
+ if (frontmatterChanged) frontmatterValue.notify()
115
+ },
116
+ onRendered(fn) {
117
+ renderedListeners.add(fn)
118
+ return () => renderedListeners.delete(fn)
119
+ },
93
120
  corner: () => corner,
94
121
  badge(key, text, order = 0) {
95
122
  if (text == null) badges.delete(key)
96
123
  else badges.set(key, { text, order, since: badges.get(key)?.since ?? badgeCount++ })
97
124
  writeTitle()
98
125
  },
99
- title(title) { baseTitle = title; writeTitle() },
126
+ title(title) {
127
+ baseTitle = title
128
+ writeTitle()
129
+ },
100
130
  toast: createToast(() => corner),
101
131
  ...formsApi,
102
132
  }
@@ -111,17 +141,52 @@ async function getJson<T>(url: string): Promise<T> {
111
141
  return res.json()
112
142
  }
113
143
 
144
+ // what came with the page, and what came with its last render: the page's once the new page is in
145
+ // place (api.rendered), so a listener never sees new values over the old page
146
+ let data: unknown = handoff.data
147
+ let nextData: unknown = data
148
+ let frontmatter: Record<string, string> = handoff.frontmatter ?? {}
149
+ let nextFrontmatter = frontmatter
150
+ const dataValue = reactive(() => data)
151
+ const frontmatterValue = reactive(() => frontmatter)
114
152
  const handle: PageHandle = {
115
153
  id: page,
116
154
  kind: handoff.kind,
117
- data: handoff.data,
118
- onChange(fn) { changeListeners.add(fn); return () => changeListeners.delete(fn) },
119
- render: () => getJson<RenderedPage>(`/api/render?page=${encodeURIComponent(page)}`),
155
+ data: dataValue,
156
+ frontmatter: frontmatterValue,
157
+ onChange(fn) {
158
+ changeListeners.add(fn)
159
+ return () => changeListeners.delete(fn)
160
+ },
161
+ render: async () => {
162
+ const next = await getJson<RenderedPage>(`/api/render?page=${encodeURIComponent(page)}`)
163
+ nextData = next.data ?? null
164
+ nextFrontmatter = next.frontmatter ?? {}
165
+ return next
166
+ },
120
167
  stored: () => getJson<StoredPage>(`/api/page?page=${encodeURIComponent(page)}`),
121
168
  }
122
169
 
170
+ /** Did the page change since it was rendered here (its file's time, or it came to be)? Then say so. */
171
+ async function caughtUp() {
172
+ let now: number | null
173
+ try {
174
+ now =
175
+ (await getJson<RenderedPage & { mtime: number | null }>(`/api/render?page=${encodeURIComponent(page)}`)).mtime ??
176
+ null
177
+ } catch {
178
+ now = null
179
+ }
180
+ const shown = (data as { mtime?: number | null } | null)?.mtime ?? null
181
+ if (now !== shown) for (const fn of changeListeners) fn()
182
+ }
183
+
123
184
  // raw text: the server's HTML is the page, replaced when the page changes
124
- if (!handoff.client) handle.onChange(async () => { root.innerHTML = (await handle.render()).html; api.rendered() })
185
+ if (!handoff.client)
186
+ handle.onChange(async () => {
187
+ root.innerHTML = (await handle.render()).html
188
+ api.rendered()
189
+ })
125
190
 
126
191
  // ---- live channel ------------------------------------------------------------------------------
127
192
 
@@ -132,9 +197,17 @@ function connect() {
132
197
  // after a server restart: who is listening now, and what was answered meanwhile
133
198
  loadListeners()
134
199
  loadEvents()
200
+ // and the page, if it changed while the channel wasn't open yet (just after loading, or while
201
+ // the server restarted): that change was never announced. Only then: an update that changes
202
+ // nothing still redraws, sorts and scrolls, under the reader's hands
203
+ caughtUp()
204
+ }
205
+ es.onerror = () => {
206
+ delete document.documentElement.dataset.wbLive
135
207
  }
136
- es.onerror = () => { delete document.documentElement.dataset.wbLive }
137
- es.addEventListener('change', () => { for (const fn of changeListeners) fn() })
208
+ es.addEventListener('change', () => {
209
+ for (const fn of changeListeners) fn()
210
+ })
138
211
  es.addEventListener('events', () => loadEvents())
139
212
  es.addEventListener('listeners', () => loadListeners())
140
213
  // browser code changed; the page keeps what matters across a reload itself. Reload only once
@@ -142,7 +215,11 @@ function connect() {
142
215
  // has nothing left in it to recover with.
143
216
  es.addEventListener('reload', () => {
144
217
  const go = async () => {
145
- try { if ((await fetch('/api/health', { cache: 'no-store' })).ok) return location.reload() } catch { /* not up yet */ }
218
+ try {
219
+ if ((await fetch('/api/health', { cache: 'no-store' })).ok) return location.reload()
220
+ } catch {
221
+ /* not up yet */
222
+ }
146
223
  setTimeout(go, 500)
147
224
  }
148
225
  go()
@@ -169,21 +246,39 @@ if (handoff.client) {
169
246
  await mount(root, handle, api)
170
247
  } catch (err) {
171
248
  console.error('page:', err)
172
- root.insertAdjacentHTML('afterbegin', String(html`<pre class="wb-error" role="alert">the page failed to start: ${(err as Error).message}</pre>`))
249
+ root.insertAdjacentHTML(
250
+ 'afterbegin',
251
+ String(html`<pre class="wb-error" role="alert">the page failed to start: ${(err as Error).message}</pre>`),
252
+ )
173
253
  }
174
254
  }
175
255
  // named forms, once the page is on the page
176
256
  trackForms(root, page, api)
177
- trackReading({ messages: handoff.messages ?? [], events: () => events, send: ids => { append(READ, { ids }).catch(err => console.error('marking read:', err)) } })
257
+ trackReading({
258
+ messages: handoff.messages ?? [],
259
+ events: () => events,
260
+ send: ids => {
261
+ append(READ, { ids }).catch(err => console.error('marking read:', err))
262
+ },
263
+ })
178
264
  // the plugins' modules after the page, so that what they work on is there; one failing leaves the others
179
- await Promise.all((handoff.plugins ?? []).map(async ext => {
180
- try {
181
- const mount: PluginMount = (await import(ext.client)).default
182
- if (typeof mount !== 'function') throw new Error('the client module must export a mount(root, page, api) function as default')
183
- await mount(root, handle, api)
184
- } catch (err) {
185
- console.error(`plugin ${ext.name}:`, err)
186
- root.insertAdjacentHTML('afterbegin', String(html`<pre class="wb-error" role="alert">plugin "${ext.name}" failed in the browser: ${(err as Error).message}</pre>`))
187
- }
188
- }))
265
+ await Promise.all(
266
+ (handoff.plugins ?? []).map(async ext => {
267
+ try {
268
+ const mount: PluginMount = (await import(ext.client)).default
269
+ if (typeof mount !== 'function')
270
+ throw new Error('the client module must export a mount(root, page, api) function as default')
271
+ await mount(root, handle, api)
272
+ } catch (err) {
273
+ console.error(`plugin ${ext.name}:`, err)
274
+ root.insertAdjacentHTML(
275
+ 'afterbegin',
276
+ String(
277
+ html`<pre class="wb-error" role="alert">
278
+ plugin "${ext.name}" failed in the browser: ${(err as Error).message}</pre>`,
279
+ ),
280
+ )
281
+ }
282
+ }),
283
+ )
189
284
  connect()
@@ -9,15 +9,20 @@ const norm = (s: string) => s.replace(/\s+/g, ' ').trim().toLowerCase()
9
9
  export function findTarget(root: ParentNode, where: string): HTMLElement | null {
10
10
  const want = norm(where)
11
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))
12
+ const heading =
13
+ headings.find(h => norm(h.textContent ?? '') === want) ??
14
+ headings.find(h => norm(h.textContent ?? '').includes(want))
13
15
  if (heading) return heading
14
- const byName = [...root.querySelectorAll<HTMLElement>('form[name]')].find(f => f.getAttribute('name') === where.trim())
16
+ const byName = [...root.querySelectorAll<HTMLElement>('form[name]')].find(
17
+ f => f.getAttribute('name') === where.trim(),
18
+ )
15
19
  if (byName) return byName
16
20
  const byId = root.querySelector<HTMLElement>(`#${CSS.escape(where.trim())}`)
17
21
  if (byId) return byId
18
22
  const walker = document.createTreeWalker(root as Node, NodeFilter.SHOW_TEXT)
19
23
  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
24
+ if (norm(n.textContent ?? '').includes(want) && n.parentElement && !n.parentElement.closest('script, style'))
25
+ return n.parentElement
21
26
  }
22
27
  return null
23
28
  }
@@ -26,7 +31,12 @@ export function scrollToTarget(root: ParentNode, where: string): boolean {
26
31
  const target = findTarget(root, where)
27
32
  if (!target) return false
28
33
  // 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
34
+ for (
35
+ let d = (target.tagName === 'SUMMARY' ? target.parentElement?.parentElement : target)?.closest('details');
36
+ d;
37
+ d = d.parentElement?.closest('details')
38
+ )
39
+ d.open = true
30
40
  requestAnimationFrame(() => {
31
41
  // below the header, and below the titles of the open details around it, which stick
32
42
  let offset = (document.querySelector<HTMLElement>('.wb-nav')?.getBoundingClientRect().height ?? 0) + 12
@@ -19,7 +19,10 @@ function place(corner: HTMLElement) {
19
19
  }
20
20
 
21
21
  export function createToast(corner: () => HTMLElement) {
22
- return function toast(text: string, { kind = 'info', ms = 7000, onClick, onDismiss, name, order = 0 }: ToastOptions = {}): Toast {
22
+ return function toast(
23
+ text: string,
24
+ { kind = 'info', ms = 7000, onClick, onDismiss, name, order = 0 }: ToastOptions = {},
25
+ ): Toast {
23
26
  const el = document.createElement('button')
24
27
  el.type = 'button'
25
28
  el.className = 'wb-toast'
@@ -39,7 +42,11 @@ export function createToast(corner: () => HTMLElement) {
39
42
  }
40
43
  const close = () => el.remove()
41
44
  el.addEventListener('click', e => {
42
- if (onDismiss && (e.target as HTMLElement).closest('.wb-toast-dismiss')) { close(); onDismiss(); return }
45
+ if (onDismiss && (e.target as HTMLElement).closest('.wb-toast-dismiss')) {
46
+ close()
47
+ onDismiss()
48
+ return
49
+ }
43
50
  if (ms) close()
44
51
  onClick?.()
45
52
  })
@@ -47,9 +54,16 @@ export function createToast(corner: () => HTMLElement) {
47
54
  place(corner()).append(el)
48
55
  return {
49
56
  close,
50
- update: next => { label.textContent = next },
51
- hide: () => { el.hidden = true },
52
- show: () => { if (!el.isConnected) place(corner()).append(el); el.hidden = false },
57
+ update: next => {
58
+ label.textContent = next
59
+ },
60
+ hide: () => {
61
+ el.hidden = true
62
+ },
63
+ show: () => {
64
+ if (!el.isConnected) place(corner()).append(el)
65
+ el.hidden = false
66
+ },
53
67
  }
54
68
  }
55
69
  }
package/src/config.ts CHANGED
@@ -39,7 +39,13 @@ export function configFileIn(whiteboardDir: string): string | null {
39
39
  return null
40
40
  }
41
41
 
42
- const isDir = (p: string) => { try { return fs.statSync(p).isDirectory() } catch { return false } }
42
+ const isDir = (p: string) => {
43
+ try {
44
+ return fs.statSync(p).isDirectory()
45
+ } catch {
46
+ return false
47
+ }
48
+ }
43
49
 
44
50
  /** The project folder a path is in: the nearest folder upward with a `.whiteboard/` folder. */
45
51
  export function findProjectDir(from: string = process.cwd()): string | null {
@@ -61,7 +67,9 @@ export function project(dir: string | null | undefined): Project | null {
61
67
  dir,
62
68
  wb,
63
69
  /** the config file, or null: looked up each time, since one can be added or removed while a server runs */
64
- get configFile() { return configFileIn(wb) },
70
+ get configFile() {
71
+ return configFileIn(wb)
72
+ },
65
73
  pagesDir: path.join(wb, 'pages'),
66
74
  eventsFile: path.join(wb, 'events.ndjson'),
67
75
  serverFile: path.join(wb, 'server.json'),
@@ -69,14 +77,20 @@ export function project(dir: string | null | undefined): Project | null {
69
77
  /** shown in titles and the overview: `name` in the config if it is a plain literal, else the folder name */
70
78
  get name() {
71
79
  const file = configFileIn(wb)
72
- return (file && (/\bname\s*:\s*['"]([^'"]+)['"]/.exec(fs.readFileSync(file, 'utf8')) ?? [])[1]) || path.basename(dir)
80
+ return (
81
+ (file && (/\bname\s*:\s*['"]([^'"]+)['"]/.exec(fs.readFileSync(file, 'utf8')) ?? [])[1]) || path.basename(dir)
82
+ )
73
83
  },
74
84
  }
75
85
  }
76
86
 
77
87
  // ---- page ids ----------------------------------------------------------------------------------
78
88
 
79
- const strip = (p: string) => p.replace(/\\/g, '/').replace(/\.md$/, '').replace(/^\/+|\/+$/g, '')
89
+ const strip = (p: string) =>
90
+ p
91
+ .replace(/\\/g, '/')
92
+ .replace(/\.md$/, '')
93
+ .replace(/^\/+|\/+$/g, '')
80
94
 
81
95
  /**
82
96
  * A file path or page name → the page id used in URLs and events.
@@ -91,6 +105,7 @@ export function pageId(proj: Project | null, input: unknown, cwd: string = proce
91
105
  if (!looksLikeFile || !proj) return strip(s)
92
106
  const abs = path.resolve(cwd, s)
93
107
  if (abs.startsWith(proj.pagesDir + path.sep)) return strip(path.relative(proj.pagesDir, abs))
94
- if (abs === proj.dir || abs.startsWith(proj.dir + path.sep)) return `-/${path.relative(proj.dir, abs).replace(/\\/g, '/')}`.replace(/\/$/, '')
108
+ if (abs === proj.dir || abs.startsWith(proj.dir + path.sep))
109
+ return `-/${path.relative(proj.dir, abs).replace(/\\/g, '/')}`.replace(/\/$/, '')
95
110
  return strip(s)
96
111
  }
package/src/define.ts CHANGED
@@ -10,6 +10,7 @@ import type { Html } from './html.ts'
10
10
 
11
11
  // HTML from a template literal, escaped by default: for a block, a plugin's `shell`
12
12
  export { html, raw, escape, Html } from './html.ts'
13
+ export { windowFrame, type WindowOptions } from './pages/window.ts'
13
14
 
14
15
  // ---- config ------------------------------------------------------------------------------------
15
16
 
@@ -56,7 +57,14 @@ export interface Plugin {
56
57
  * go to the block of that name. Block names are unique across a project's plugins.
57
58
  */
58
59
  blocks?: Record<string, Block<any>>
59
- /** a stylesheet linked on every page (for blocks, their own `style` links it only where they're used) */
60
+ /**
61
+ * The folder its browser files are served from, and nothing else of it: its client modules,
62
+ * stylesheets, images, fonts (TypeScript there is served with its types stripped). `client` and
63
+ * `style` here and in its blocks name files in it. definePlugin defaults it to `public/` next to
64
+ * the module that calls it; a plain object plugin has the project's `.whiteboard/public/`.
65
+ */
66
+ public?: URL | string
67
+ /** a stylesheet linked on every page, in its public folder (a block's `style` links only where it is used) */
60
68
  style?: URL | string
61
69
  /**
62
70
  * Text that links somewhere, as written in plain text (`#12` → an issue): the core turns each
@@ -89,7 +97,25 @@ export interface Plugin {
89
97
  session?(): string | null | undefined | Promise<string | null | undefined>
90
98
  }
91
99
 
92
- export const definePlugin = (plugin: Plugin): Plugin => plugin
100
+ /**
101
+ * A plugin, with its public folder defaulted to `public/` next to the module that calls this
102
+ * (found from the call stack), when it doesn't say one.
103
+ */
104
+ export const definePlugin = (plugin: Plugin): Plugin =>
105
+ plugin.public != null ? plugin : { ...plugin, public: callerPublic() }
106
+
107
+ /** `public/` next to the module that called definePlugin: the first frame of the stack in another file. */
108
+ function callerPublic(): URL | undefined {
109
+ const own = import.meta.url
110
+ for (const line of (new Error().stack ?? '').split('\n').slice(1)) {
111
+ const m = /(file:\/\/[^\s)]+?|\/[^\s():]+?):\d+:\d+/.exec(line)
112
+ if (!m) continue
113
+ const url = m[1].startsWith('file:') ? m[1] : `file://${m[1]}`
114
+ if (url === own) continue
115
+ return new URL('./public/', url)
116
+ }
117
+ return undefined
118
+ }
93
119
 
94
120
  /** A pattern in a page's text that links somewhere (Plugin.links). */
95
121
  export interface TextLink {
@@ -152,12 +178,17 @@ export interface PluginHooks {
152
178
  * pixels. The page keeps its own fixed elements clear of it and counts what is behind it as out
153
179
  * of view.
154
180
  */
155
- shell?(req: import('node:http').IncomingMessage): { head?: string | Html; body?: string | Html } | null | Promise<{ head?: string | Html; body?: string | Html } | null>
181
+ shell?(
182
+ req: import('node:http').IncomingMessage,
183
+ ):
184
+ | { head?: string | Html; body?: string | Html }
185
+ | null
186
+ | Promise<{ head?: string | Html; body?: string | Html } | null>
156
187
  /**
157
188
  * A browser module whose default export is an `PluginMount`: on every page, the core imports
158
189
  * it once the page has mounted, and hands it the page and its api. For
159
190
  * behaviour on the page's own content (its forms, say); markup of the plugin's own can come
160
- * from `shell` instead. Serve it with `ctx.asset`.
191
+ * from `shell` instead. A file in the plugin's public folder: `'client.js'`.
161
192
  */
162
193
  client?: URL | string
163
194
  }
@@ -274,6 +305,8 @@ export interface Rendered {
274
305
  export interface RenderedPage extends Rendered {
275
306
  html: string
276
307
  head?: string
308
+ /** the page's frontmatter (see PageHandle.frontmatter) */
309
+ frontmatter: Record<string, string>
277
310
  }
278
311
 
279
312
  /** A page as the core stores it: what is in the file, read as is. */
@@ -343,8 +376,14 @@ export type PluginMount = (root: HTMLElement, page: PageHandle, api: Api) => voi
343
376
  export interface PageHandle {
344
377
  id: string
345
378
  kind: StoredPage['kind']
346
- /** what the server render returned with the HTML now in the root */
347
- data: unknown
379
+ /** what the server render returned with the HTML now in the root; it changes with each live update */
380
+ data: Reactive<unknown>
381
+ /**
382
+ * The page's frontmatter: its fields as written, as strings (`toc: true` is `'true'`); empty for a
383
+ * page without one, and for the overview, folders and code. It changes with a live update that
384
+ * changed it, once the new page is in place (`onChange` comes before, with the old one still here).
385
+ */
386
+ frontmatter: Reactive<Record<string, string>>
348
387
  /** called when the stored page changed; returns an unsubscribe */
349
388
  onChange(fn: () => void): () => void
350
389
  /** the server render, afresh */
@@ -410,14 +449,22 @@ export interface Toast {
410
449
  show(): void
411
450
  }
412
451
 
413
- /** What the core gives the page and every plugin in the browser. Framework-free: getters and subscriptions. */
452
+ /**
453
+ * A value that changes: call it for what it is now, and `.on(fn)` to hear each change, with the
454
+ * new value (it returns an unsubscribe). Every changing value of the api is one, so a framework
455
+ * can turn any of them into its own reactive value with one helper (the Solid one does).
456
+ */
457
+ export interface Reactive<T> {
458
+ (): T
459
+ on(fn: (value: T) => void): () => void
460
+ }
461
+
462
+ /** What the core gives the page and every plugin in the browser. Framework-free: its changing values are Reactive. */
414
463
  export interface Api {
415
464
  /** this page's id */
416
465
  page: string
417
466
  /** every event recorded for this page, oldest first */
418
- events(): WbEvent[]
419
- /** called with the new list whenever it changes; returns an unsubscribe */
420
- onEvents(fn: (events: WbEvent[]) => void): () => void
467
+ events: Reactive<WbEvent[]>
421
468
  /** the latest event of a type, e.g. the last submit of a form */
422
469
  last(type: string): WbEvent | undefined
423
470
  /** record an event for this page: it lands in the log, where the agent reads it */
@@ -429,7 +476,7 @@ export interface Api {
429
476
  * EventSpec.forReader). An element marked `data-wb-message="<event id>"` reads its message once
430
477
  * it has been in view; `markRead` does so for messages read otherwise (a thread closed).
431
478
  */
432
- unread(): WbEvent[]
479
+ unread: Reactive<WbEvent[]>
433
480
  markRead(ids: string[]): void
434
481
  /**
435
482
  * A message's markdown (a comment, a chat message) as HTML, rendered by the server like a page:
@@ -437,8 +484,7 @@ export interface Api {
437
484
  */
438
485
  markdown(text: string): Promise<string>
439
486
  /** the agents waiting for answers on this page right now */
440
- listeners(): Listener[]
441
- onListeners(fn: (listeners: Listener[]) => void): () => void
487
+ listeners: Reactive<Listener[]>
442
488
  /**
443
489
  * Say that the page's content changed in place: the page module calls it after each patch on an update
444
490
  * (it morphs it) calls this after each patch, so that plugins working on the content
@@ -471,11 +517,10 @@ export interface Api {
471
517
  * The page's named forms and where each stands. The core looks after every `<form name>` without
472
518
  * an `action`: it sends a submit as an event, keeps drafts, puts the last answer back, and marks
473
519
  * each form with its state (`data-wb-open`, `-pending`, `-decided`). How that
474
- * looks is the page's styles'; this is for drawing more than the attributes allow (a summary, a count)
520
+ * looks is the page's styles'; this is for drawing more than the attributes allow (a summary, a
521
+ * count). It changes when the forms are marked again: the log, the listeners or the page changed.
475
522
  */
476
- forms(): FormStatus[]
477
- /** called after the forms were marked again: the log, the listeners or the page changed */
478
- onForms(fn: (forms: FormStatus[]) => void): () => void
523
+ forms: Reactive<FormStatus[]>
479
524
  }
480
525
 
481
526
  /**
@@ -503,8 +548,8 @@ export interface FormStatus {
503
548
  * `::name` and `:name`; and, when it says so (`fence`), the code fences of that language,
504
549
  * ```` ```name ````. Server functions run while the page renders; `client` runs in the browser.
505
550
  *
506
- * File references are URLs relative to the plugin's module, so they work wherever it is installed:
507
- * client: new URL('./client.js', import.meta.url)
551
+ * Its files are in its plugin's public folder, named within it, so they work wherever it is
552
+ * installed: `client: 'chart.js'`, `style: 'chart.css'`.
508
553
  */
509
554
  export interface Block<Props = unknown> {
510
555
  /**
@@ -521,9 +566,9 @@ export interface Block<Props = unknown> {
521
566
  * output; with it, what shows until it mounts.
522
567
  */
523
568
  html?(ctx: ServerContext): string | Html | null | Promise<string | Html | null>
524
- /** a browser module whose default export is a `Mount` */
569
+ /** a browser module whose default export is a `Mount`, in its plugin's public folder: `'chart.js'` */
525
570
  client?: URL | string
526
- /** a stylesheet linked on every page that uses the block */
571
+ /** a stylesheet linked on every page that uses the block, in its plugin's public folder: `'chart.css'` */
527
572
  style?: URL | string
528
573
  }
529
574
 
@@ -616,6 +661,5 @@ export type Theme = 'light' | 'dark'
616
661
  /** Passed to every Mount: the core's api, and the page's theme. */
617
662
  export interface ClientApi extends Api {
618
663
  /** the theme in effect (the reader's choice, else the system's) */
619
- theme(): Theme
620
- onTheme(fn: (theme: Theme) => void): () => void
664
+ theme: Reactive<Theme>
621
665
  }