@bigmistqke/whiteboard 0.6.1 → 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 (101) hide show
  1. package/README.md +23 -216
  2. package/bin/whiteboard.ts +82 -239
  3. package/dist/bin/whiteboard.js +70 -200
  4. package/dist/client/runtime.js +297 -61
  5. package/dist/plugins/badge/README.md +3 -1
  6. package/dist/plugins/badge/public/style.css +17 -0
  7. package/dist/plugins/chat/public/client.js +2 -2
  8. package/dist/plugins/chat/public/style.css +19 -6
  9. package/dist/plugins/code/README.md +10 -0
  10. package/dist/plugins/code/index.js +31 -22
  11. package/dist/plugins/code/public/client.js +1 -0
  12. package/dist/plugins/code/public/style.css +33 -2
  13. package/dist/plugins/comments/public/client.js +7 -2
  14. package/dist/plugins/comments/public/style.css +4 -0
  15. package/dist/plugins/form/public/style.css +2 -0
  16. package/dist/plugins/grid/public/style.css +0 -5
  17. package/dist/plugins/iframe/index.js +2 -2
  18. package/dist/plugins/index.js +5 -1
  19. package/dist/plugins/lightbox/public/client.js +1 -1
  20. package/dist/plugins/terminal/index.js +7 -9
  21. package/dist/plugins/terminal/public/client.js +1 -1
  22. package/dist/plugins/terminal/public/style.css +3 -3
  23. package/dist/plugins/timeline/README.md +40 -0
  24. package/dist/plugins/timeline/index.js +82 -0
  25. package/dist/plugins/timeline/public/style.css +118 -0
  26. package/dist/plugins/toc/README.md +13 -13
  27. package/dist/plugins/toc/index.js +6 -4
  28. package/dist/plugins/toc/public/client.js +1 -1
  29. package/dist/plugins/toc/public/style.css +19 -2
  30. package/dist/plugins/window/index.js +4 -4
  31. package/dist/solid/index.js +2 -1
  32. package/dist/src/auth.js +7 -3
  33. package/dist/src/build.js +159 -0
  34. package/dist/src/client/page/base.css +74 -35
  35. package/dist/src/client/page/main.js +16 -5
  36. package/dist/src/document.js +93 -0
  37. package/dist/src/events.js +7 -15
  38. package/dist/src/hub.js +90 -53
  39. package/dist/src/listen.js +100 -0
  40. package/dist/src/listeners.js +67 -0
  41. package/dist/src/pages/index.js +1 -1
  42. package/dist/src/pages/markdown.js +23 -11
  43. package/dist/src/pages/render.js +13 -8
  44. package/dist/src/serve.js +2 -0
  45. package/dist/src/server.js +204 -514
  46. package/dist/src/site.js +173 -0
  47. package/dist/src/status.js +63 -1
  48. package/dist/src/ws.js +128 -0
  49. package/package.json +1 -1
  50. package/plugins/README.md +258 -0
  51. package/plugins/badge/README.md +3 -1
  52. package/plugins/badge/public/style.css +17 -0
  53. package/plugins/chat/client.tsx +34 -6
  54. package/plugins/chat/public/style.css +19 -6
  55. package/plugins/code/README.md +10 -0
  56. package/plugins/code/client.ts +73 -0
  57. package/plugins/code/index.ts +38 -26
  58. package/plugins/code/public/style.css +33 -2
  59. package/plugins/comments/client.ts +56 -6
  60. package/plugins/comments/public/style.css +4 -0
  61. package/plugins/form/public/style.css +2 -0
  62. package/plugins/grid/public/style.css +0 -5
  63. package/plugins/iframe/index.ts +2 -2
  64. package/plugins/index.ts +6 -1
  65. package/plugins/lightbox/client.ts +13 -3
  66. package/plugins/terminal/client.ts +10 -2
  67. package/plugins/terminal/index.ts +8 -6
  68. package/plugins/terminal/public/style.css +3 -3
  69. package/plugins/timeline/README.md +40 -0
  70. package/plugins/timeline/index.ts +92 -0
  71. package/plugins/timeline/public/style.css +118 -0
  72. package/plugins/toc/README.md +13 -13
  73. package/plugins/toc/client.ts +58 -32
  74. package/plugins/toc/index.ts +13 -13
  75. package/plugins/toc/public/style.css +19 -2
  76. package/plugins/window/index.ts +4 -4
  77. package/skills/whiteboard/SKILL.md +3 -1
  78. package/solid/index.tsx +3 -0
  79. package/src/auth.ts +7 -2
  80. package/src/build.ts +213 -0
  81. package/src/client/forms.ts +102 -5
  82. package/src/client/page/base.css +74 -35
  83. package/src/client/page/elsewhere.ts +14 -4
  84. package/src/client/page/waiting.ts +10 -5
  85. package/src/client/read.ts +16 -3
  86. package/src/client/runtime.ts +219 -52
  87. package/src/client/toast.ts +36 -6
  88. package/src/define.ts +44 -18
  89. package/src/document.ts +191 -0
  90. package/src/events.ts +18 -17
  91. package/src/hub.ts +102 -56
  92. package/src/listen.ts +125 -0
  93. package/src/listeners.ts +95 -0
  94. package/src/pages/index.ts +1 -1
  95. package/src/pages/markdown.ts +29 -18
  96. package/src/pages/render.ts +13 -8
  97. package/src/serve.ts +2 -0
  98. package/src/server.ts +223 -611
  99. package/src/site.ts +165 -0
  100. package/src/status.ts +100 -0
  101. package/src/ws.ts +155 -0
package/src/build.ts ADDED
@@ -0,0 +1,213 @@
1
+ // Pages rendered once (`whiteboard build`), as files: each page's HTML with its links relative, and
2
+ // what it loads copied beside it, under its own ids and addresses (a site of its own: the server's is
3
+ // site.ts's servedSite). The page around a render is document.ts's, as for a page the server serves.
4
+ // See BuildConfig.
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { stripTypeScriptTypes } from 'node:module'
8
+ import type { Project } from './config.ts'
9
+ import type { BuildConfig } from './define.ts'
10
+ import { RUNTIME, pageDocument, pluginParts, type SetUp } from './document.ts'
11
+ import { toPath, type LoadedConfig } from './loader.ts'
12
+ import { PACKAGE_DIR } from './package.ts'
13
+ import { pageSource, within } from './site.ts'
14
+
15
+ const ENGINE_DIR = PACKAGE_DIR
16
+ const TYPESCRIPT = /\.m?ts$/i
17
+ const typeScriptModule = (file: string): string => stripTypeScriptTypes(fs.readFileSync(file, 'utf8'))
18
+
19
+ /** What a build made. */
20
+ export interface BuildResult {
21
+ /** the folder the site is in */
22
+ out: string
23
+ /** each page, and the file it became */
24
+ pages: { file: string; to: string }[]
25
+ /** what didn't fit: a link to a page outside the build, no index.html */
26
+ warnings: string[]
27
+ }
28
+
29
+ /** What a build takes from the project's server: its config, its plugins set up, whether it serves the project's files. */
30
+ export interface BuildFrom {
31
+ project: Project
32
+ config(): Promise<LoadedConfig>
33
+ hooks(): Promise<SetUp[]>
34
+ files(): boolean
35
+ }
36
+
37
+ /** What a build leaves out unless told otherwise: what is for writing a page, not for reading it. */
38
+ const BUILD_SKIP = ['form', 'chat', 'comments', 'draft']
39
+ /** In the folder a build writes, so that a next build knows it may replace it. */
40
+ const BUILD_MARK = '.whiteboard-build'
41
+
42
+ export async function build(
43
+ { project, config, hooks: setUp, files: served }: BuildFrom,
44
+ options: BuildConfig = {},
45
+ ): Promise<BuildResult> {
46
+ const cfg = await config()
47
+ if (cfg.errors.length) throw new Error(`the config failed to load: ${(cfg.errors[0] as Error).message}`)
48
+ if (!cfg.pages) throw new Error('the config has no pages renderer')
49
+ const pages = cfg.pages
50
+ const defined = <T>(...xs: (T | undefined)[]) => xs.find(x => x !== undefined)
51
+ const patterns = defined(options.pages, cfg.build.pages) ?? []
52
+ const skip = new Set(defined(options.skip, cfg.build.skip) ?? BUILD_SKIP)
53
+ const outDir = path.resolve(project.dir, defined(options.out, cfg.build.out) ?? 'site')
54
+ if (!patterns.length)
55
+ throw new Error(
56
+ "nothing to build: name the pages, as globs from the project's folder (whiteboard build 'docs/**/*.md'), or set build.pages in the config",
57
+ )
58
+ const warnings: string[] = []
59
+
60
+ // the pages: markdown files the globs match, but those a `!` glob leaves out
61
+ const include = patterns.filter(p => !p.startsWith('!'))
62
+ const exclude = patterns.filter(p => p.startsWith('!')).map(p => p.slice(1))
63
+ const files = [
64
+ ...new Set(include.flatMap(p => fs.globSync(p, { cwd: project.dir }).map(f => path.resolve(project.dir, f)))),
65
+ ]
66
+ .filter(f => /\.(md|markdown)$/i.test(f) && fs.statSync(f).isFile())
67
+ .filter(f => !exclude.some(g => path.matchesGlob(path.relative(project.dir, f), g)))
68
+ .sort()
69
+ if (!files.length) throw new Error(`no markdown files match ${patterns.join(' ')}`)
70
+ // each at its place below the folder they share; a README or index is its folder's index.html
71
+ const base = files.map(path.dirname).reduce((a, b) => {
72
+ while (!within(b, a)) a = path.dirname(a)
73
+ return a
74
+ })
75
+ const outOf = (file: string) => {
76
+ const rel = path.relative(base, file)
77
+ return path.join(
78
+ outDir,
79
+ /^(readme|index)\.(md|markdown)$/i.test(path.basename(rel))
80
+ ? path.join(path.dirname(rel), 'index.html')
81
+ : rel.replace(/\.(md|markdown)$/i, '.html'),
82
+ )
83
+ }
84
+ const built = new Map(files.map(f => [f, outOf(f)]))
85
+
86
+ // the folder it writes: new, empty, or what an earlier build wrote
87
+ if (fs.existsSync(outDir)) {
88
+ if (fs.readdirSync(outDir).length && !fs.existsSync(path.join(outDir, BUILD_MARK)))
89
+ throw new Error(`${outDir} has files a build didn't write: give another folder (--out), or empty it`)
90
+ fs.rmSync(outDir, { recursive: true })
91
+ }
92
+ fs.mkdirSync(outDir, { recursive: true })
93
+ fs.writeFileSync(path.join(outDir, BUILD_MARK), 'written by whiteboard build; the next build replaces this folder\n')
94
+
95
+ // what a page loads, copied once: the package's files under _/whiteboard/, the project's under
96
+ // _/project/, at their places there (so a stylesheet's url()s still hold); TypeScript as JavaScript
97
+ const copied = new Map<string, string>()
98
+ function copyAsset(file: string): string {
99
+ const known = copied.get(file)
100
+ if (known) return known
101
+ const rel = within(file, ENGINE_DIR)
102
+ ? path.join('_', 'whiteboard', path.relative(ENGINE_DIR, file))
103
+ : within(file, project.dir)
104
+ ? path.join('_', 'project', path.relative(project.dir, file))
105
+ : path.join('_', 'files', path.basename(path.dirname(file)), path.basename(file))
106
+ const dest = path.join(outDir, TYPESCRIPT.test(rel) ? rel.replace(/\.m?ts$/i, '.js') : rel)
107
+ copied.set(file, dest)
108
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
109
+ if (TYPESCRIPT.test(file)) fs.writeFileSync(dest, typeScriptModule(file))
110
+ else fs.copyFileSync(file, dest)
111
+ // a stylesheet's own files (fonts, images), at the same places beside it
112
+ if (/\.css$/i.test(file)) {
113
+ for (const m of fs.readFileSync(file, 'utf8').matchAll(/url\(\s*['"]?([^'")]+)['"]?\s*\)/g)) {
114
+ const ref = m[1]!
115
+ if (/^(data:|[a-z][a-z0-9+.-]*:|\/|#)/i.test(ref)) continue
116
+ const target = path.resolve(path.dirname(file), ref.replace(/[?#].*$/, ''))
117
+ if (fs.existsSync(target) && fs.statSync(target).isFile()) copyAsset(target)
118
+ }
119
+ }
120
+ return dest
121
+ }
122
+ /** a file beside the pages (an image), copied to its place below the site */
123
+ function copyBeside(file: string): string | null {
124
+ if (!within(file, base)) return null
125
+ const dest = path.join(outDir, path.relative(base, file))
126
+ if (!fs.existsSync(dest)) {
127
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
128
+ fs.copyFileSync(file, dest)
129
+ }
130
+ return dest
131
+ }
132
+
133
+ const hooks = await setUp()
134
+ const result: BuildResult = { out: outDir, pages: [], warnings }
135
+ for (const [file, dest] of built) {
136
+ const here = path.dirname(dest)
137
+ const relTo = (target: string) =>
138
+ path.relative(here, target).split(path.sep).map(encodeURIComponent).join('/') || '.'
139
+ const assetHere = (ref: string | URL) => relTo(copyAsset(toPath(ref)))
140
+ const urlFor = (abs: string): string | null => {
141
+ for (const candidate of [abs, abs + '.md']) {
142
+ if (!fs.existsSync(candidate)) continue
143
+ if (fs.statSync(candidate).isDirectory()) {
144
+ const index = [...built.keys()].find(
145
+ f => path.dirname(f) === candidate && /^(readme|index)\.(md|markdown)$/i.test(path.basename(f)),
146
+ )
147
+ if (index) return relTo(built.get(index)!)
148
+ continue
149
+ }
150
+ if (built.has(candidate)) return relTo(built.get(candidate)!)
151
+ if (/\.(md|markdown)$/i.test(candidate)) {
152
+ warnings.push(
153
+ `${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, which is not in the build`,
154
+ )
155
+ return null
156
+ }
157
+ const copy = copyBeside(candidate)
158
+ if (copy) return relTo(copy)
159
+ warnings.push(
160
+ `${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, outside the built pages' folder`,
161
+ )
162
+ return null
163
+ }
164
+ return null
165
+ }
166
+ const id = within(file, project.pagesDir)
167
+ ? path
168
+ .relative(project.pagesDir, file)
169
+ .split(path.sep)
170
+ .join('/')
171
+ .replace(/\.(md|markdown)$/i, '')
172
+ : '-/' + path.relative(project.dir, file).split(path.sep).join('/')
173
+ const stored = pageSource(id, file)
174
+ if (stored.frontmatterError)
175
+ warnings.push(`${path.relative(project.dir, file)}: frontmatter: ${stored.frontmatterError}`)
176
+ const context = {
177
+ project: { name: project.name, dir: project.dir, files: served() },
178
+ asset: assetHere,
179
+ urlFor,
180
+ live: false,
181
+ skip,
182
+ }
183
+ const rendered = await pages.render(stored, context)
184
+ // a page without a heading of its own is named by its file (a README by its folder), not by
185
+ // the id the server knows it by
186
+ const named = /^(readme|index)\.(md|markdown)$/i.test(path.basename(file))
187
+ ? path.basename(path.dirname(file))
188
+ : path.basename(file).replace(/\.(md|markdown)$/i, '')
189
+ const title = !rendered.title || rendered.title === id ? named : rendered.title
190
+ const out = { ...rendered, title, html: String(rendered.html ?? ''), head: String(rendered.head ?? '') }
191
+ // what the plugins add, but those the build leaves out, asked with no request: no browser
192
+ // asked for this page (what is only for the project's own browser has nothing to add here)
193
+ const parts = await pluginParts(hooks, null, {
194
+ asset: assetHere,
195
+ messages: [],
196
+ leaveOut: skip,
197
+ failed: message => warnings.push(`${path.relative(project.dir, file)}: ${message}`),
198
+ })
199
+ const doc = pageDocument(stored, { page: true, out, notices: [] }, parts, {
200
+ live: false,
201
+ base: '',
202
+ asset: assetHere,
203
+ runtime: assetHere(RUNTIME),
204
+ title: project.name,
205
+ })
206
+ fs.mkdirSync(here, { recursive: true })
207
+ fs.writeFileSync(dest, doc)
208
+ result.pages.push({ file, to: dest })
209
+ }
210
+ if (![...built.values()].includes(path.join(outDir, 'index.html')))
211
+ warnings.push('no README.md or index.md in the top folder: the site has no index.html')
212
+ return result
213
+ }
@@ -4,7 +4,8 @@
4
4
  // every page.
5
5
  //
6
6
  // What the core does with such a form, without drawing anything:
7
- // - sends a submit as an event, and says how that went: `data-wb-state` is sending, sent or failed;
7
+ // - sends a submit as an event, shown at once (optimistic), and says how that went: `data-wb-state`
8
+ // is sending (shown, not yet confirmed), sent or failed (taken back);
8
9
  // - keeps what the reader typed until it is sent (localStorage, per page and form), across
9
10
  // re-renders and reloads;
10
11
  // - puts the last answer back into the form, and its button in `data-wb-sent`;
@@ -152,34 +153,129 @@ function restoreLast(prefill: boolean) {
152
153
  }
153
154
  }
154
155
 
156
+ /** What each form is sending now, as sent: the same answer again is not sent twice. */
157
+ const inFlight = new WeakMap<HTMLFormElement, string>()
158
+
159
+ // The button that sent it says how that goes, in its own text and colour (`data-wb-send` on it):
160
+ // "Sending…" (grey) while on its way, "✓ Sent" (green) a moment once the server has it, then its own
161
+ // label again; "Try again" (red) when no try got through, until it is pressed. It keeps its width
162
+ // meanwhile.
163
+ type Send = 'sending' | 'sent' | 'failed'
164
+ /** A button's own label, while it says how a send goes. */
165
+ const labelOf = (button: HTMLButtonElement) => {
166
+ const el = document.createElement('div')
167
+ el.innerHTML = labels.get(button)!.html
168
+ return el.textContent?.trim() ?? ''
169
+ }
170
+ const SEND_TEXT: Record<Send, string> = { sending: 'Sending…', sent: '✓ Sent', failed: 'Try again' }
171
+ const labels = new WeakMap<HTMLButtonElement, { html: string; timer?: ReturnType<typeof setTimeout> }>()
172
+
173
+ function sendState(button: HTMLButtonElement | null, state: Send | null) {
174
+ if (!button) return
175
+ let saved = labels.get(button)
176
+ clearTimeout(saved?.timer)
177
+ if (!state) {
178
+ if (!saved) return
179
+ button.innerHTML = saved.html
180
+ button.style.minWidth = ''
181
+ delete button.dataset.wbSend
182
+ labels.delete(button)
183
+ return
184
+ }
185
+ if (!saved) {
186
+ saved = { html: button.innerHTML }
187
+ labels.set(button, saved)
188
+ button.style.minWidth = `${button.getBoundingClientRect().width}px`
189
+ }
190
+ button.dataset.wbSend = state
191
+ button.textContent = SEND_TEXT[state]
192
+ // confirmed: said for a moment, then the button is itself again
193
+ if (state === 'sent') saved.timer = setTimeout(() => sendState(button, null), 2000)
194
+ }
195
+
196
+ // Optimistic: the answer is the form's at once (api.append puts it in the events, so the form is
197
+ // marked pending), with `data-wb-state="sending"` saying it is still on its way, and its button
198
+ // saying so (sendState); `sent` once the server has it, with the short `data-wb-just-sent` to
199
+ // confirm it. Should it not get through, the answer leaves the form again: `failed`, the button
200
+ // the form had before, the draft kept.
155
201
  async function onSubmit(e: SubmitEvent) {
156
202
  const form = e.target as HTMLFormElement
157
203
  if (!managed(form) || !root.contains(form)) return
158
204
  e.preventDefault()
159
205
  const button = e.submitter as HTMLButtonElement | null
160
- const action = button ? button.value || button.textContent?.trim() || null : null
206
+ // its label as it is, not as it says how a send goes
207
+ const label = button ? (labels.get(button) ? labelOf(button) : button.textContent?.trim()) : null
208
+ const action = button ? button.value || label || null : null
209
+ const data = readForm(form)
210
+ const sent = JSON.stringify([action, data])
211
+ if (inFlight.get(form) === sent) return
212
+ inFlight.set(form, sent)
213
+ const before = form.dataset.wbSent
161
214
  form.dataset.wbState = 'sending'
215
+ form.dataset.wbSent = action ?? ''
216
+ form.removeAttribute('data-wb-just-sent')
217
+ sendState(button, 'sending')
218
+ showStatus(form)
162
219
  try {
163
- await api.append(form.getAttribute('name')!, readForm(form), action)
220
+ await api.append(form.getAttribute('name')!, data, action)
221
+ if (inFlight.get(form) !== sent) return // a newer answer took its place
164
222
  dropDraft(form)
165
223
  form.dataset.wbState = 'sent'
166
- form.dataset.wbSent = action ?? ''
224
+ sendState(button, 'sent')
167
225
  // for the page to confirm the send: set for a few seconds after it, also once the form
168
226
  // folds because an agent picked the answer up at once
169
227
  form.toggleAttribute('data-wb-just-sent', true)
170
228
  clearTimeout(justSent.get(form))
171
229
  justSent.set(
172
230
  form,
173
- setTimeout(() => form.removeAttribute('data-wb-just-sent'), 3000),
231
+ setTimeout(() => {
232
+ form.removeAttribute('data-wb-just-sent')
233
+ showStatus(form)
234
+ }, 3000),
174
235
  )
236
+ showStatus(form)
175
237
  } catch (err) {
238
+ if (inFlight.get(form) !== sent) return
176
239
  form.dataset.wbState = 'failed'
240
+ sendState(button, 'failed')
241
+ if (before == null) delete form.dataset.wbSent
242
+ else form.dataset.wbSent = before
243
+ showStatus(form)
177
244
  console.error(err)
245
+ } finally {
246
+ if (inFlight.get(form) === sent) inFlight.delete(form)
178
247
  }
179
248
  }
180
249
 
181
250
  // ---- where each form stands --------------------------------------------------------------------
182
251
 
252
+ // What a sent answer came to, said beside the form's last send button, where the eye is when it is
253
+ // pressed (a line over the form was out of view below a long list of options): `.wb-form-status`,
254
+ // "waiting for the agent to pick it up", or `data-kind="bad"` "couldn't send it". Never what the
255
+ // button says already (sendState): nothing while sending, no "sent".
256
+ const sendButtons = (form: HTMLFormElement) =>
257
+ [...form.querySelectorAll<HTMLButtonElement | HTMLInputElement>('button, input[type=submit]')].filter(
258
+ b => (b instanceof HTMLInputElement || (b.type !== 'button' && b.type !== 'reset')) && b.form === form,
259
+ )
260
+
261
+ function showStatus(form: HTMLFormElement) {
262
+ const text =
263
+ form.dataset.wbState === 'failed'
264
+ ? (["couldn't send it", 'bad'] as const)
265
+ : form.dataset.wbState === 'sending' || !form.hasAttribute('data-wb-pending')
266
+ ? null
267
+ : (['waiting for the agent to pick it up', null] as const)
268
+ let el = form.querySelector<HTMLElement>('.wb-form-status')
269
+ const last = sendButtons(form).at(-1)
270
+ if (!text || !last) return void el?.remove()
271
+ if (!el) el = Object.assign(document.createElement('span'), { className: 'wb-form-status' })
272
+ el.setAttribute('role', 'status')
273
+ if (el.previousElementSibling !== last) last.after(el)
274
+ el.textContent = text[0]
275
+ if (text[1]) el.dataset.kind = text[1]
276
+ else delete el.dataset.kind
277
+ }
278
+
183
279
  const ATTR: Record<FormState, string> = { open: 'data-wb-open', pending: 'data-wb-pending', decided: 'data-wb-decided' }
184
280
 
185
281
  /** One line quoting an answer: what was chosen, then what was written. */
@@ -225,6 +321,7 @@ function mark() {
225
321
  for (const st of STATES) form.toggleAttribute(ATTR[st], st === state)
226
322
  if (state === 'decided') form.dataset.wbOutcome = outcome(last!.data, last!.action)
227
323
  else delete form.dataset.wbOutcome
324
+ showStatus(form)
228
325
  return { form, name, state, last }
229
326
  })
230
327
  forms_.notify()
@@ -19,6 +19,10 @@
19
19
  --warn: light-dark(#6b4fc0, #b4a0ff);
20
20
  --bad: light-dark(#c4352b, #ff6f66);
21
21
  --info: light-dark(#1d5bbf, #82aaff);
22
+ /* what the reader sent, shown at once but not yet confirmed by the server (an event with
23
+ `sending`): grey, in whatever carries it (a button, a bubble, a comment's text). Confirmed, it
24
+ takes its usual colour (a button flashes --ok first); never got there, --bad */
25
+ --wb-sending: light-dark(#9a9fa7, #6c717a);
22
26
  --shadow: none;
23
27
 
24
28
  /* Type. The article is set in --serif at --text-size; everything in it (its margins, its
@@ -302,7 +306,7 @@ hr::after {
302
306
  letter-spacing: 0.3em;
303
307
  }
304
308
 
305
- /* section numbers hanging in the margin: 1, 1.1, 1.1.1, in italic oldstyle figures. Only the
309
+ /* section numbers hanging in the margin: 1, 1.1, 1.1.1, down to h6, in italic oldstyle figures. Only the
306
310
  page's own headings (direct children of main), so headings inside cards stay unnumbered. The
307
311
  number is an inline-block pulled into the margin, so it shares the heading's baseline. */
308
312
  #wb-main {
@@ -318,8 +322,16 @@ hr::after {
318
322
  }
319
323
  #wb-main > h4 {
320
324
  counter-increment: h4;
325
+ counter-reset: h5;
321
326
  }
322
- #wb-main > :is(h2, h3, h4)::before {
327
+ #wb-main > h5 {
328
+ counter-increment: h5;
329
+ counter-reset: h6;
330
+ }
331
+ #wb-main > h6 {
332
+ counter-increment: h6;
333
+ }
334
+ #wb-main > :is(h2, h3, h4, h5, h6)::before {
323
335
  display: inline-block;
324
336
  box-sizing: content-box;
325
337
  width: 64px;
@@ -347,12 +359,18 @@ hr::after {
347
359
  content: counter(h2) '.' counter(h3) '.' counter(h4);
348
360
  font-size: 1.3em;
349
361
  }
362
+ #wb-main > h5::before {
363
+ content: counter(h2) '.' counter(h3) '.' counter(h4) '.' counter(h5);
364
+ }
365
+ #wb-main > h6::before {
366
+ content: counter(h2) '.' counter(h3) '.' counter(h4) '.' counter(h5) '.' counter(h6);
367
+ }
350
368
  /* no margin to hang them in: set the number in front of the heading, and indent less */
351
369
  @media (max-width: 860px) {
352
370
  main {
353
371
  --indent: 0px;
354
372
  }
355
- #wb-main > :is(h2, h3, h4)::before {
373
+ #wb-main > :is(h2, h3, h4, h5, h6)::before {
356
374
  width: auto;
357
375
  margin-left: 0;
358
376
  margin-right: 0.6em;
@@ -682,14 +700,32 @@ form.wb-form[data-wb-folded] {
682
700
  gap: 0;
683
701
  }
684
702
  /* named forms: the core marks where each stands (data-wb-open, -pending, -decided); this is how that looks */
685
- form[data-wb-state='sending'] {
686
- opacity: 0.7;
687
- }
688
- /* sending: the form's buttons can't send twice */
689
- form[data-wb-state='sending'] button {
690
- pointer-events: none;
703
+ /* the button a form was sent with says how that goes (forms.ts): the answer is the form's already
704
+ (optimistic), the button grey while the server hasn't confirmed it, green a moment once it has,
705
+ red ("Try again") when it never got there. The form stays usable: the same answer isn't sent twice. !important: a send's
706
+ state outranks however a plugin or the project styles its buttons (.wb-primary) */
707
+ form button[data-wb-send] {
708
+ transition:
709
+ background-color 0.2s,
710
+ border-color 0.2s,
711
+ color 0.2s;
712
+ }
713
+ form button[data-wb-send='sending'] {
714
+ background: var(--wb-sending) !important;
715
+ border-color: var(--wb-sending) !important;
716
+ color: var(--bg) !important;
691
717
  cursor: progress;
692
718
  }
719
+ form button[data-wb-send='sent'] {
720
+ background: var(--ok) !important;
721
+ border-color: var(--ok) !important;
722
+ color: var(--bg) !important;
723
+ }
724
+ form button[data-wb-send='failed'] {
725
+ background: var(--bad) !important;
726
+ border-color: var(--bad) !important;
727
+ color: var(--bg) !important;
728
+ }
693
729
  /* just sent: a short green flash, and a line saying what happened, for a few seconds */
694
730
  @keyframes wb-sent {
695
731
  from {
@@ -702,23 +738,16 @@ form[data-wb-state='sending'] button {
702
738
  form[data-wb-just-sent] {
703
739
  animation: wb-sent 1.4s ease-out;
704
740
  }
705
- form.wb-form[data-wb-state='failed']::before {
706
- content: "couldn't send it: try again";
707
- display: block;
708
- margin-bottom: var(--space-md);
709
- color: var(--bad);
710
- font: var(--weight-strong) var(--ui-tiny)/var(--ui-line-height) var(--sans);
711
- }
712
- form[data-wb-sent]:not(.wb-form)::after {
713
- content: '✓ sent ' attr(data-wb-sent);
714
- display: block;
715
- margin-top: var(--space-sm);
716
- color: var(--ok);
717
- font: var(--ui-small) var(--sans);
741
+ /* what a sent answer came to, beside the form's last send button (forms.ts): waiting for the agent
742
+ (muted), couldn't send (red) */
743
+ .wb-form-status {
744
+ margin-left: var(--space-md);
745
+ color: var(--muted);
746
+ font: var(--ui-tiny)/var(--ui-line-height) var(--sans);
718
747
  }
719
- form[data-wb-state='failed']:not(.wb-form)::after {
720
- content: 'failed to send';
748
+ .wb-form-status[data-kind='bad'] {
721
749
  color: var(--bad);
750
+ font-weight: var(--weight-strong);
722
751
  }
723
752
 
724
753
  /* a question the reader hasn't answered, or one the agent asks again: outlined, without a label of
@@ -730,21 +759,25 @@ form[data-wb-open] {
730
759
  }
731
760
  /* the outline sets it off: the form's rules above and below (its borders, which the outline would
732
761
  enclose) step aside meanwhile */
733
- form.wb-form[data-wb-open] {
762
+ form.wb-form:is([data-wb-open], [data-wb-pending], [data-wb-state='sending'], [data-wb-state='failed']) {
734
763
  border-top-color: transparent;
735
764
  border-bottom-color: transparent;
736
765
  }
737
- form[data-wb-pending]::before {
738
- content: 'sent · waiting for the agent to pick it up';
739
- display: block;
740
- margin-bottom: var(--space-md);
741
- color: var(--muted);
742
- font: var(--ui-tiny)/var(--ui-line-height) var(--sans);
766
+ /* the outline speaks the language of a send too: grey while the answer is on its way (it is the
767
+ form's already, so no longer outlined as unanswered) and while it waits for the agent to pick it
768
+ up, red when it never got there; gone once the agent took it (decided) */
769
+ form:is([data-wb-open], [data-wb-pending], [data-wb-state='sending'], [data-wb-state='failed']) {
770
+ transition: outline-color 0.2s;
743
771
  }
744
- form[data-wb-pending][data-wb-just-sent]::before {
745
- content: '✓ sent · waiting for the agent to pick it up';
746
- color: var(--ok);
747
- font-weight: var(--weight-strong);
772
+ form:is([data-wb-state='sending'], [data-wb-pending]) {
773
+ outline: 2px solid var(--wb-sending);
774
+ outline-offset: 10px;
775
+ border-radius: var(--radius-sm);
776
+ }
777
+ form[data-wb-state='failed'] {
778
+ outline: 2px solid var(--bad);
779
+ outline-offset: 10px;
780
+ border-radius: var(--radius-sm);
748
781
  }
749
782
 
750
783
  /* decided: the agent picked up the latest answer; the form folds into one line quoting it */
@@ -1236,3 +1269,9 @@ main:has(+ .wb-orphans:not([hidden])) {
1236
1269
  :root[data-wb-window-maximized] {
1237
1270
  overflow: hidden;
1238
1271
  }
1272
+ @media (prefers-reduced-motion: reduce) {
1273
+ form button[data-wb-send],
1274
+ form:is([data-wb-open], [data-wb-pending], [data-wb-state='sending'], [data-wb-state='failed']) {
1275
+ transition: none;
1276
+ }
1277
+ }
@@ -110,18 +110,27 @@ async function load() {
110
110
  )
111
111
  }
112
112
 
113
- // several changes at once (an answer is an event and a listener less) load once
113
+ // several changes at once (an answer is an event and a listener less) load once; a hidden tab
114
+ // loads once it is shown, and not before (the index asks every project of the server)
114
115
  let timer = 0
116
+ let stale = false
115
117
  const reload = () => {
116
118
  clearTimeout(timer)
119
+ if (document.hidden) return void (stale = true)
117
120
  timer = window.setTimeout(load, 100)
118
121
  }
122
+ document.addEventListener('visibilitychange', () => {
123
+ if (document.hidden || !stale) return
124
+ stale = false
125
+ reload()
126
+ })
119
127
 
120
128
  export function trackElsewhere(root: HTMLElement, handle: PageHandle, core: Api) {
121
129
  current = handle.id
122
130
  const nav = root.querySelector('.wb-nav')
123
131
  if (!nav) return
124
- nav.querySelector('.wb-theme')?.before(box)
132
+ // before the plugins' place in the header bar (its header slot), and the theme button after it
133
+ ;(nav.querySelector('[data-wb-slot=header]') ?? nav.querySelector('.wb-theme'))?.before(box)
125
134
  toggle.addEventListener('click', () => open(!!list.hidden))
126
135
  document.addEventListener('click', e => {
127
136
  if (!box.contains(e.target as Node)) open(false)
@@ -138,6 +147,7 @@ export function trackElsewhere(root: HTMLElement, handle: PageHandle, core: Api)
138
147
  core.listeners.on(reload)
139
148
  handle.onChange(reload)
140
149
  load()
141
- // other projects' pages change without this page hearing of it: look again now and then
142
- if (base) setInterval(reload, 5000)
150
+ // another project's pages, log or listeners changed: the shared server says so on the live
151
+ // channel (and the channel opening again may have missed some)
152
+ if (base) document.addEventListener('wb-elsewhere', reload)
143
153
  }
@@ -280,12 +280,17 @@ export function trackWaiting(root: HTMLElement, core: Api) {
280
280
  if (form.dataset.wbState === 'sending') return
281
281
  sent.disconnect()
282
282
  if (form.dataset.wbState !== 'sent') return
283
- if (fallback) api.toast('Sent. No agent waits on this page; the fallback agent picks it up.', { name: 'sent' })
283
+ if (fallback)
284
+ api.toast('Sent · to the fallback agent', {
285
+ name: 'sent',
286
+ details: 'No agent waits on this page, so the fallback agent picks it up.',
287
+ })
284
288
  else
285
- api.toast(
286
- 'Sent, but no agent is listening right now. Your answer stays in the log until one checks this page.',
287
- { kind: 'warn', name: 'sent' },
288
- )
289
+ api.toast('Sent · no agent listening', {
290
+ kind: 'warn',
291
+ name: 'sent',
292
+ details: 'Your answer stays in the log until an agent checks this page.',
293
+ })
289
294
  })
290
295
  sent.observe(form, { attributes: true, attributeFilter: ['data-wb-state'] })
291
296
  })
@@ -1,6 +1,7 @@
1
1
  // The agent's messages the reader hasn't read (status.ts: unreadMessages), and reading them: an
2
2
  // element marked `data-wb-message="<event id>"` (a reply in an open thread, a chat bubble) reads
3
- // its message once it has been mostly in view while the tab is visible. Reads are sent together, a
3
+ // its message once it has been mostly in view (most of it on screen, or filling most of the window)
4
+ // while the tab is visible. Reads are sent together, a
4
5
  // moment later, as one `whiteboard:read` event.
5
6
  import type { WbEvent } from '../define.ts'
6
7
  import { READ, unreadMessages } from '../status.ts'
@@ -38,18 +39,30 @@ export function readsArrived(events: WbEvent[]) {
38
39
  if (e.type === READ) for (const id of (e.data?.ids as unknown[] | undefined) ?? []) sending.delete(String(id))
39
40
  }
40
41
 
42
+ // Mostly in view: most of the message is on screen, or, for one taller than the window, it fills
43
+ // most of the window.
44
+ const MOSTLY = 0.6
45
+ function mostlyInView(entry: IntersectionObserverEntry) {
46
+ if (!entry.isIntersecting) return false
47
+ if (entry.intersectionRatio >= MOSTLY) return true
48
+ const viewport = entry.rootBounds?.height ?? window.innerHeight
49
+ return entry.intersectionRect.height >= MOSTLY * viewport
50
+ }
51
+
41
52
  // what is in view now, read once the tab is visible too
42
53
  const inView = new Set<string>()
43
54
  const seen = new IntersectionObserver(
44
55
  entries => {
45
56
  for (const entry of entries) {
46
57
  const id = (entry.target as HTMLElement).dataset.wbMessage!
47
- if (entry.isIntersecting) inView.add(id)
58
+ if (mostlyInView(entry)) inView.add(id)
48
59
  else inView.delete(id)
49
60
  }
50
61
  readVisible()
51
62
  },
52
- { threshold: 0.6 },
63
+ // steps: a message taller than the window never reaches 0.6 of itself in view, so its share is
64
+ // reported as it scrolls by
65
+ { threshold: Array.from({ length: 21 }, (_, i) => i / 20) },
53
66
  )
54
67
 
55
68
  function readVisible() {