@bigmistqke/whiteboard 0.3.1 → 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 (153) 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/index.js +4 -3
  32. package/dist/plugins/toc/public/client.js +1 -0
  33. package/dist/plugins/toc/public/style.css +93 -0
  34. package/dist/plugins/window/README.md +29 -0
  35. package/dist/plugins/window/index.js +64 -0
  36. package/dist/solid/index.js +14 -11
  37. package/dist/src/client/page/base.css +1078 -199
  38. package/dist/src/client/page/main.js +174 -33
  39. package/dist/src/loader.js +7 -2
  40. package/dist/src/package.js +3 -6
  41. package/dist/src/pages/blocks.js +8 -13
  42. package/dist/src/pages/markdown.js +1 -1
  43. package/dist/src/pages/render.js +74 -15
  44. package/dist/src/pages/window.js +30 -0
  45. package/dist/src/public.js +24 -0
  46. package/dist/src/server.js +36 -14
  47. package/package.json +3 -1
  48. package/plugins/callout/index.ts +3 -1
  49. package/plugins/callout/public/style.css +30 -0
  50. package/plugins/chat/autosize.ts +43 -9
  51. package/plugins/chat/client.tsx +22 -5
  52. package/plugins/chat/index.ts +22 -8
  53. package/plugins/chat/public/style.css +98 -0
  54. package/plugins/claude-code/index.ts +49 -14
  55. package/plugins/code/diff.ts +28 -8
  56. package/plugins/code/index.ts +30 -20
  57. package/plugins/code/public/style.css +68 -0
  58. package/plugins/comments/client.ts +139 -71
  59. package/plugins/comments/index.ts +9 -7
  60. package/plugins/comments/public/style.css +185 -0
  61. package/plugins/details/index.ts +7 -2
  62. package/plugins/details/public/style.css +7 -0
  63. package/plugins/forge/index.ts +16 -3
  64. package/plugins/form/index.ts +75 -27
  65. package/plugins/form/public/style.css +126 -0
  66. package/plugins/gallery/client.tsx +9 -3
  67. package/plugins/gallery/index.ts +31 -9
  68. package/plugins/gallery/public/style.css +90 -0
  69. package/plugins/grid/index.ts +19 -5
  70. package/plugins/grid/public/style.css +71 -0
  71. package/plugins/iframe/index.ts +20 -23
  72. package/plugins/iframe/public/style.css +13 -0
  73. package/plugins/index.ts +16 -1
  74. package/plugins/mermaid/index.ts +3 -1
  75. package/plugins/mermaid/{style.css → public/style.css} +7 -2
  76. package/plugins/terminal/client.ts +105 -48
  77. package/plugins/terminal/host.ts +131 -29
  78. package/plugins/terminal/index.ts +84 -25
  79. package/plugins/terminal/public/style.css +225 -0
  80. package/plugins/terminal/server.ts +64 -13
  81. package/plugins/terminal/sizes.ts +13 -3
  82. package/plugins/toc/client.ts +45 -26
  83. package/plugins/toc/index.ts +9 -6
  84. package/plugins/toc/public/style.css +93 -0
  85. package/plugins/window/README.md +29 -0
  86. package/plugins/window/index.ts +85 -0
  87. package/skills/whiteboard/SKILL.md +3 -1
  88. package/solid/index.tsx +24 -9
  89. package/src/auth.ts +25 -7
  90. package/src/client/forms.ts +74 -28
  91. package/src/client/markdown.ts +15 -4
  92. package/src/client/page/base.css +1078 -199
  93. package/src/client/page/elsewhere.ts +32 -15
  94. package/src/client/page/fresh.ts +91 -23
  95. package/src/client/page/hold.ts +11 -2
  96. package/src/client/page/live.ts +10 -6
  97. package/src/client/page/main.ts +106 -36
  98. package/src/client/page/orphans.ts +25 -10
  99. package/src/client/page/sort.ts +14 -4
  100. package/src/client/page/sticky.ts +11 -3
  101. package/src/client/page/theme.ts +11 -7
  102. package/src/client/page/waiting.ts +141 -34
  103. package/src/client/page/window.ts +40 -0
  104. package/src/client/reactive.ts +19 -0
  105. package/src/client/read.ts +17 -10
  106. package/src/client/runtime.ts +130 -35
  107. package/src/client/scroll.ts +14 -4
  108. package/src/client/toast.ts +19 -5
  109. package/src/config.ts +20 -5
  110. package/src/define.ts +65 -25
  111. package/src/events.ts +111 -24
  112. package/src/html.ts +6 -2
  113. package/src/icons.ts +4 -2
  114. package/src/load.ts +10 -2
  115. package/src/loader.ts +75 -11
  116. package/src/package.ts +9 -8
  117. package/src/pages/blocks.ts +20 -14
  118. package/src/pages/markdown.ts +113 -34
  119. package/src/pages/render.ts +199 -39
  120. package/src/pages/window.ts +71 -0
  121. package/src/plugins.ts +90 -24
  122. package/src/public.ts +39 -0
  123. package/src/running.ts +8 -2
  124. package/src/serve.ts +29 -7
  125. package/src/server.ts +348 -107
  126. package/src/status.ts +15 -9
  127. package/dist/plugins/callout/style.css +0 -12
  128. package/dist/plugins/chat/style.css +0 -24
  129. package/dist/plugins/code/style.css +0 -29
  130. package/dist/plugins/comments/client.js +0 -10
  131. package/dist/plugins/comments/style.css +0 -40
  132. package/dist/plugins/details/style.css +0 -3
  133. package/dist/plugins/form/style.css +0 -44
  134. package/dist/plugins/gallery/client.js +0 -1
  135. package/dist/plugins/gallery/style.css +0 -27
  136. package/dist/plugins/grid/style.css +0 -25
  137. package/dist/plugins/iframe/client.js +0 -1
  138. package/dist/plugins/iframe/style.css +0 -29
  139. package/dist/plugins/toc/client.js +0 -1
  140. package/dist/plugins/toc/style.css +0 -19
  141. package/plugins/callout/style.css +0 -12
  142. package/plugins/chat/style.css +0 -24
  143. package/plugins/code/style.css +0 -29
  144. package/plugins/comments/style.css +0 -40
  145. package/plugins/details/style.css +0 -3
  146. package/plugins/form/style.css +0 -44
  147. package/plugins/gallery/style.css +0 -27
  148. package/plugins/grid/style.css +0 -25
  149. package/plugins/iframe/client.ts +0 -46
  150. package/plugins/iframe/style.css +0 -29
  151. package/plugins/terminal/style.css +0 -71
  152. package/plugins/toc/style.css +0 -19
  153. /package/dist/plugins/terminal/{client.js → public/client.js} +0 -0
@@ -48,13 +48,23 @@ import { handOver, lastUsed, leave, report, type Sizes } from './sizes.ts'
48
48
 
49
49
  const require = createRequire(import.meta.url)
50
50
  const [dir, socket] = process.argv.slice(2)
51
- if (!dir || !socket) { console.error('usage: host <project dir> <socket path>'); process.exit(2) }
51
+ if (!dir || !socket) {
52
+ console.error('usage: host <project dir> <socket path>')
53
+ process.exit(2)
54
+ }
52
55
 
53
56
  /** node-pty. Its prebuilt helper ships without execute permission (1.1.0): add it. */
54
57
  function loadPty(): typeof import('node-pty') {
55
58
  const pty = require('node-pty')
56
- const helper = path.join(path.dirname(require.resolve('node-pty/package.json')), 'prebuilds', `${process.platform}-${process.arch}`, 'spawn-helper')
57
- try { if (fs.existsSync(helper) && !(fs.statSync(helper).mode & 0o111)) fs.chmodSync(helper, 0o755) } catch {}
59
+ const helper = path.join(
60
+ path.dirname(require.resolve('node-pty/package.json')),
61
+ 'prebuilds',
62
+ `${process.platform}-${process.arch}`,
63
+ 'spawn-helper',
64
+ )
65
+ try {
66
+ if (fs.existsSync(helper) && !(fs.statSync(helper).mode & 0o111)) fs.chmodSync(helper, 0o755)
67
+ } catch {}
58
68
  return pty
59
69
  }
60
70
 
@@ -99,16 +109,27 @@ const watchers = new Set<Conn>()
99
109
  let idle: ReturnType<typeof setTimeout> | undefined
100
110
  function checkIdle() {
101
111
  clearTimeout(idle)
102
- if (![...sessions.values()].some(s => s.exited == null)) idle = setTimeout(() => quit('no program ran for ten minutes'), 10 * 60 * 1000)
112
+ if (![...sessions.values()].some(s => s.exited == null))
113
+ idle = setTimeout(() => quit('no program ran for ten minutes'), 10 * 60 * 1000)
103
114
  }
104
115
 
105
- const list = () => [...sessions.values()].map(s => ({ id: s.id, label: s.label, running: s.exited == null, exited: s.exited, started: s.started }))
106
- function announce() { for (const c of watchers) send(c, { t: 'sessions', sessions: list() }) }
116
+ const list = () =>
117
+ [...sessions.values()].map(s => ({
118
+ id: s.id,
119
+ label: s.label,
120
+ running: s.exited == null,
121
+ exited: s.exited,
122
+ started: s.started,
123
+ }))
124
+ function announce() {
125
+ for (const c of watchers) send(c, { t: 'sessions', sessions: list() })
126
+ }
107
127
 
108
128
  function start(id: string, command: string, args: string[], label: string): Session {
109
129
  const pty = loadPty()
110
130
  const before = sessions.get(id)
111
- const cols = before?.cols ?? 100, rows = before?.rows ?? 30
131
+ const cols = before?.cols ?? 100,
132
+ rows = before?.rows ?? 30
112
133
  const attached = before?.attached ?? new Set<Conn>()
113
134
  const viewers = before?.viewers ?? new Map()
114
135
  const active = before?.active ?? null
@@ -118,11 +139,30 @@ function start(id: string, command: string, args: string[], label: string): Sess
118
139
  screen.loadAddon(serializer)
119
140
  const mouseEncoding = followMouseEncoding(screen)
120
141
  const proc = pty.spawn(command, args, {
121
- name: 'xterm-256color', cols, rows, cwd: dir,
142
+ name: 'xterm-256color',
143
+ cols,
144
+ rows,
145
+ cwd: dir,
122
146
  // WHITEBOARD_TERMINAL: which tab a program runs in, so it can show a page where its drawer is (`open`)
123
147
  env: { ...process.env, TERM: 'xterm-256color', COLORTERM: 'truecolor', WHITEBOARD_TERMINAL: id },
124
148
  })
125
- const s: Session = { id, label, command, args, proc, screen, serializer, mouseEncoding, cols, rows, attached, viewers, active, exited: null, started: new Date().toISOString() }
149
+ const s: Session = {
150
+ id,
151
+ label,
152
+ command,
153
+ args,
154
+ proc,
155
+ screen,
156
+ serializer,
157
+ mouseEncoding,
158
+ cols,
159
+ rows,
160
+ attached,
161
+ viewers,
162
+ active,
163
+ exited: null,
164
+ started: new Date().toISOString(),
165
+ }
126
166
  proc.onData(d => {
127
167
  screen.write(d)
128
168
  for (const c of s.attached) send(c, { t: 'data', d })
@@ -143,7 +183,9 @@ function start(id: string, command: string, args: string[], label: string): Sess
143
183
  }
144
184
 
145
185
  function endProcess(s: Session) {
146
- try { if (s.exited == null) s.proc.kill() } catch {}
186
+ try {
187
+ if (s.exited == null) s.proc.kill()
188
+ } catch {}
147
189
  s.screen.dispose()
148
190
  }
149
191
 
@@ -167,7 +209,9 @@ function quit(reason: string) {
167
209
  const running = [...sessions.values()].filter(s => s.exited == null).length
168
210
  log(`leaves: ${reason}${running ? `, ending ${running} running tab${running > 1 ? 's' : ''}` : ''}`)
169
211
  for (const id of [...sessions.keys()]) close(id)
170
- try { fs.unlinkSync(socket) } catch {}
212
+ try {
213
+ fs.unlinkSync(socket)
214
+ } catch {}
171
215
  process.exit(0)
172
216
  }
173
217
 
@@ -176,7 +220,8 @@ function quit(reason: string) {
176
220
  /** Give a session a size, and tell the drawers showing it. */
177
221
  function resize(s: Session, cols: number, rows: number) {
178
222
  if (cols !== s.cols || rows !== s.rows) {
179
- s.cols = cols; s.rows = rows
223
+ s.cols = cols
224
+ s.rows = rows
180
225
  s.screen.resize(cols, rows)
181
226
  if (s.exited == null) s.proc.resize(cols, rows)
182
227
  }
@@ -209,7 +254,16 @@ function send(conn: Conn, msg: unknown) {
209
254
  function sendScreen(conn: Conn, s: Session) {
210
255
  conn.queue = []
211
256
  s.screen.write('', () => {
212
- conn.socket.write(JSON.stringify({ t: 'screen', d: s.serializer.serialize() + s.mouseEncoding(), cols: s.cols, rows: s.rows, active: s.active, exited: s.exited }) + '\n')
257
+ conn.socket.write(
258
+ JSON.stringify({
259
+ t: 'screen',
260
+ d: s.serializer.serialize() + s.mouseEncoding(),
261
+ cols: s.cols,
262
+ rows: s.rows,
263
+ active: s.active,
264
+ exited: s.exited,
265
+ }) + '\n',
266
+ )
213
267
  const queued = conn.queue ?? []
214
268
  conn.queue = null
215
269
  for (const msg of queued) send(conn, msg)
@@ -222,14 +276,19 @@ function html(s: Session | undefined): string {
222
276
  // the rows, without the wrapper that sets the serializer's own colors and font; text is escaped
223
277
  const m = /<pre><div style='[^']*'>([\s\S]*)<\/div><\/pre>/.exec(s.serializer.serializeAsHTML())
224
278
  return m ? m[1] : ''
225
- } catch { return '' }
279
+ } catch {
280
+ return ''
281
+ }
226
282
  }
227
283
 
228
284
  function handle(conn: Conn, req: Record<string, any>) {
229
- const reply = (msg: unknown) => { conn.socket.end(JSON.stringify(msg) + '\n') }
285
+ const reply = (msg: unknown) => {
286
+ conn.socket.end(JSON.stringify(msg) + '\n')
287
+ }
230
288
  const s = req.id != null ? sessions.get(String(req.id)) : undefined
231
289
  switch (req.t) {
232
- case 'list': return reply({ sessions: list() })
290
+ case 'list':
291
+ return reply({ sessions: list() })
233
292
  case 'start': {
234
293
  const id = req.id != null ? String(req.id) : String(nextId)
235
294
  const running = sessions.get(id)
@@ -237,9 +296,18 @@ function handle(conn: Conn, req: Record<string, any>) {
237
296
  // without a command: start it again as it was (restarting a tab)
238
297
  const command = typeof req.command === 'string' && req.command ? req.command : running?.command
239
298
  if (!command) return reply({ error: 'start needs a command' })
240
- const args = typeof req.command === 'string' && req.command ? (Array.isArray(req.args) ? req.args.map(String) : []) : running!.args
299
+ const args =
300
+ typeof req.command === 'string' && req.command
301
+ ? Array.isArray(req.args)
302
+ ? req.args.map(String)
303
+ : []
304
+ : running!.args
241
305
  const label = String(req.label ?? (req.command ? path.basename(req.command) : running!.label))
242
- try { start(id, command, args, label) } catch (e) { return reply({ error: (e as Error).message }) }
306
+ try {
307
+ start(id, command, args, label)
308
+ } catch (e) {
309
+ return reply({ error: (e as Error).message })
310
+ }
243
311
  log(`tab ${id} (${label}) ${running ? 'restarted' : 'started'}`)
244
312
  // ids are never reused while the host runs, so a closed tab's id can't come back as another
245
313
  if (Number(id) >= nextId) nextId = Number(id) + 1
@@ -251,19 +319,36 @@ function handle(conn: Conn, req: Record<string, any>) {
251
319
  case 'resize': {
252
320
  const { cols, rows } = req
253
321
  const viewer = String(req.viewer ?? '')
254
- if (s && viewer && Number.isInteger(cols) && Number.isInteger(rows) && cols > 1 && rows > 1 && cols < 1000 && rows < 500) {
322
+ if (
323
+ s &&
324
+ viewer &&
325
+ Number.isInteger(cols) &&
326
+ Number.isInteger(rows) &&
327
+ cols > 1 &&
328
+ rows > 1 &&
329
+ cols < 1000 &&
330
+ rows < 500
331
+ ) {
255
332
  const size = report(s, viewer, cols, rows, !!req.active)
256
333
  resize(s, size.cols, size.rows)
257
334
  }
258
335
  return reply({ ok: true })
259
336
  }
260
- case 'html': return reply({ html: html(s ?? sessions.values().next().value) })
261
- case 'close': close(String(req.id)); return reply({ ok: true })
337
+ case 'html':
338
+ return reply({ html: html(s ?? sessions.values().next().value) })
339
+ case 'close':
340
+ close(String(req.id))
341
+ return reply({ ok: true })
262
342
  case 'open': {
263
343
  // show a page in the browser tab whose drawer the reader used last: for session `id`, or
264
344
  // without one, across all of them (where the reader is). With none active, in every drawer
265
345
  // that shows the session.
266
- const target = s ?? (req.id == null ? lastUsed([...sessions.values()].filter(x => x.attached.size)) ?? [...sessions.values()].find(x => x.attached.size) : undefined)
346
+ const target =
347
+ s ??
348
+ (req.id == null
349
+ ? (lastUsed([...sessions.values()].filter(x => x.attached.size)) ??
350
+ [...sessions.values()].find(x => x.attached.size))
351
+ : undefined)
267
352
  if (!target || typeof req.path !== 'string') return reply({ shown: 0 })
268
353
  const mine = [...target.attached].filter(c => c.viewer && c.viewer === target.active)
269
354
  const to = mine.length ? mine : [...target.attached]
@@ -271,7 +356,9 @@ function handle(conn: Conn, req: Record<string, any>) {
271
356
  for (const c of to) send(c, { t: 'navigate', path: req.path })
272
357
  return reply({ shown: to.length })
273
358
  }
274
- case 'stop': reply({ ok: true }); return void setTimeout(() => quit('asked to stop (whiteboard terminal stop)'), 50)
359
+ case 'stop':
360
+ reply({ ok: true })
361
+ return void setTimeout(() => quit('asked to stop (whiteboard terminal stop)'), 50)
275
362
  case 'attach': {
276
363
  watchers.add(conn)
277
364
  if (req.viewer) conn.viewer = String(req.viewer)
@@ -285,7 +372,8 @@ function handle(conn: Conn, req: Record<string, any>) {
285
372
  sendScreen(conn, s)
286
373
  return
287
374
  }
288
- default: return reply({ error: `unknown request ${req.t}` })
375
+ default:
376
+ return reply({ error: `unknown request ${req.t}` })
289
377
  }
290
378
  }
291
379
 
@@ -302,7 +390,11 @@ const server = net.createServer(socketConn => {
302
390
  buf = ''
303
391
  socketConn.removeAllListeners('data')
304
392
  let req
305
- try { req = JSON.parse(line) } catch { return socketConn.end(JSON.stringify({ error: 'not JSON' }) + '\n') }
393
+ try {
394
+ req = JSON.parse(line)
395
+ } catch {
396
+ return socketConn.end(JSON.stringify({ error: 'not JSON' }) + '\n')
397
+ }
306
398
  handle(conn, req)
307
399
  })
308
400
  })
@@ -311,15 +403,25 @@ const server = net.createServer(socketConn => {
311
403
  try {
312
404
  await new Promise<void>((resolve, reject) => {
313
405
  const probe = net.connect(socket)
314
- probe.on('connect', () => { probe.destroy(); reject(new Error('running')) })
406
+ probe.on('connect', () => {
407
+ probe.destroy()
408
+ reject(new Error('running'))
409
+ })
315
410
  probe.on('error', () => resolve())
316
411
  })
317
- try { fs.unlinkSync(socket) } catch {}
318
- } catch { console.error('terminal host: another host answers on', socket); process.exit(0) }
412
+ try {
413
+ fs.unlinkSync(socket)
414
+ } catch {}
415
+ } catch {
416
+ console.error('terminal host: another host answers on', socket)
417
+ process.exit(0)
418
+ }
319
419
 
320
420
  server.listen(socket, () => {
321
421
  // only its owner may talk to it: the socket runs code
322
- try { fs.chmodSync(socket, 0o600) } catch {}
422
+ try {
423
+ fs.chmodSync(socket, 0o600)
424
+ } catch {}
323
425
  log(`listening on ${socket}`)
324
426
  checkIdle()
325
427
  })
@@ -15,12 +15,12 @@
15
15
  // The parts are whiteboard-free: server.ts is a request handler, host.ts the process that runs the
16
16
  // sessions, client.ts the drawer in the browser. This file wires them in.
17
17
  import { html, raw } from '../../src/html.ts'
18
- import { packagePath } from '../../src/package.ts'
18
+ import { builtinPublic } from '../../src/package.ts'
19
19
  import { createTerminal, type Sessions, type StartOptions } from './server.ts'
20
20
  import type { CommandContext, Plugin } from '../../src/define.ts'
21
21
 
22
- const CLIENT = packagePath('dist/plugins/terminal/client.js')
23
- const STYLE = packagePath('dist/plugins/terminal/style.css')
22
+ const CLIENT = 'client.js'
23
+ const STYLE = 'style.css'
24
24
 
25
25
  /**
26
26
  * The drawer's markup, written by the server so that it is there when the page first renders and
@@ -29,17 +29,45 @@ const STYLE = packagePath('dist/plugins/terminal/style.css')
29
29
  * render, and each session's screen is in it as HTML, so a page shows it from its first render on;
30
30
  * client.js puts the live terminal in its place.
31
31
  */
32
- const drawer = (state: Sessions, screens: Record<string, string>, client: string) => html`<aside id="wb-terminal" aria-label="Terminal" data-sessions="${JSON.stringify(state)}">
33
- <div class="wb-term-grip" title="drag to resize"></div>
34
- <div class="wb-term-bar"><button type="button" class="wb-term-toggle" title="Toggle the terminal (Ctrl+\`)"><span class="wb-term-chevron"></span>terminal</button><span class="wb-term-status"></span><span class="wb-term-actions"></span><span class="wb-term-tabs">${state.sessions.map(s => html`<button type="button" class="wb-term-tab" data-id="${s.id}">${s.label}</button>`)}</span></div>
35
- <div class="wb-term-screen">${state.sessions.map(s => screens[s.id] && html`<div class="wb-term-placeholder" data-id="${s.id}" aria-hidden="true">${raw(screens[s.id])}</div>`)}</div>
36
- </aside>
37
- <script>try{const t=document.getElementById('wb-terminal'),s=sessionStorage,o=new URLSearchParams(location.search).get('terminal')==='open'||s.getItem('wb-terminal-open')==='1';t.dataset.state=o?'open':'collapsed';const h=+s.getItem('wb-terminal-height');if(h)document.documentElement.style.setProperty('--wb-term-h',h+'px');const tabs=[...t.querySelectorAll('.wb-term-tab')],k=s.getItem('wb-terminal-tab'),a=tabs.find(b=>b.dataset.id===k)??tabs[0];if(a){t.dataset.tab=a.dataset.id;a.classList.add('wb-current');t.querySelector('.wb-term-placeholder[data-id="'+a.dataset.id+'"]')?.classList.add('wb-current')}}catch{}</script>
38
- <script type="module" src="${client}"></script>`
32
+ const drawer = (state: Sessions, screens: Record<string, string>, client: string) =>
33
+ html`<aside id="wb-terminal" aria-label="Terminal" data-sessions="${JSON.stringify(state)}">
34
+ <div class="wb-term-grip" title="drag to resize"></div>
35
+ <div class="wb-term-bar">
36
+ <button type="button" class="wb-term-toggle" title="Toggle the terminal (Ctrl+\`)">
37
+ <span class="wb-term-chevron"></span>terminal</button
38
+ ><span class="wb-term-status"></span><span class="wb-term-actions"></span
39
+ ><span class="wb-term-tabs"
40
+ >${state.sessions.map(s => html`<button type="button" class="wb-term-tab" data-id="${s.id}">${s.label}</button>`)}</span
41
+ >
42
+ </div>
43
+ <div class="wb-term-screen">
44
+ ${state.sessions.map(s => screens[s.id] && html`<div class="wb-term-placeholder" data-id="${s.id}" aria-hidden="true">${raw(screens[s.id])}</div>`)}
45
+ </div>
46
+ </aside>
47
+ <script>
48
+ try {
49
+ const t = document.getElementById('wb-terminal'),
50
+ s = sessionStorage,
51
+ o = new URLSearchParams(location.search).get('terminal') === 'open' || s.getItem('wb-terminal-open') === '1'
52
+ t.dataset.state = o ? 'open' : 'collapsed'
53
+ const h = +s.getItem('wb-terminal-height')
54
+ if (h) document.documentElement.style.setProperty('--wb-term-h', h + 'px')
55
+ const tabs = [...t.querySelectorAll('.wb-term-tab')],
56
+ k = s.getItem('wb-terminal-tab'),
57
+ a = tabs.find(b => b.dataset.id === k) ?? tabs[0]
58
+ if (a) {
59
+ t.dataset.tab = a.dataset.id
60
+ a.classList.add('wb-current')
61
+ t.querySelector('.wb-term-placeholder[data-id="' + a.dataset.id + '"]')?.classList.add('wb-current')
62
+ }
63
+ } catch {}
64
+ </script>
65
+ <script type="module" src="${client}"></script>`
39
66
 
40
67
  export default function terminal(): Plugin {
41
68
  return {
42
69
  name: 'terminal',
70
+ public: builtinPublic('terminal'),
43
71
  // the drawer's look: on every page, since every page can have the drawer
44
72
  style: STYLE,
45
73
  setup(ctx) {
@@ -48,31 +76,57 @@ export default function terminal(): Plugin {
48
76
  return {
49
77
  // all of them run code or show what runs, so all need the project's token
50
78
  routes: {
51
- 'GET /sessions': { description: 'the sessions (the drawer\'s tabs): id, label, whether each runs', auth: true, run: () => term.sessions() },
79
+ 'GET /sessions': {
80
+ description: "the sessions (the drawer's tabs): id, label, whether each runs",
81
+ auth: true,
82
+ run: () => term.sessions(),
83
+ },
52
84
  'POST /start': {
53
- description: 'start a tab: the shell, or program (with its arguments) in it; in session id, a new tab without one; with restart, start it again as it was',
85
+ description:
86
+ 'start a tab: the shell, or program (with its arguments) in it; in session id, a new tab without one; with restart, start it again as it was',
54
87
  auth: true,
55
88
  body: { id: 'string?', program: 'string[]?', restart: 'boolean?' },
56
89
  run: ({ body }) => term.start(body as StartOptions),
57
90
  },
58
- 'POST /input': { description: 'keystrokes for a session, as the terminal sends them', auth: true, body: { id: 'string', data: 'string' }, run: ({ body }) => term.input(body.id as string, body.data as string) },
91
+ 'POST /input': {
92
+ description: 'keystrokes for a session, as the terminal sends them',
93
+ auth: true,
94
+ body: { id: 'string', data: 'string' },
95
+ run: ({ body }) => term.input(body.id as string, body.data as string),
96
+ },
59
97
  'POST /resize': {
60
- description: 'the size that fits the terminal in a page (`viewer`: that drawer); `active`: the reader uses this drawer now, so the session takes its size',
98
+ description:
99
+ 'the size that fits the terminal in a page (`viewer`: that drawer); `active`: the reader uses this drawer now, so the session takes its size',
61
100
  auth: true,
62
101
  body: { id: 'string', viewer: 'string', cols: 'number', rows: 'number', active: 'boolean?' },
63
- run: ({ body }) => term.resize(body.id as string, body.viewer as string, body.cols as number, body.rows as number, !!body.active),
102
+ run: ({ body }) =>
103
+ term.resize(
104
+ body.id as string,
105
+ body.viewer as string,
106
+ body.cols as number,
107
+ body.rows as number,
108
+ !!body.active,
109
+ ),
64
110
  },
65
111
  'GET /stream': {
66
- description: 'the tabs and a session\'s whole screen, then its output as it comes (events sessions, screen, data, size, navigate, exit; none without that session)',
112
+ description:
113
+ "the tabs and a session's whole screen, then its output as it comes (events sessions, screen, data, size, navigate, exit; none without that session)",
67
114
  auth: true,
68
115
  stream: true,
69
116
  query: { id: 'string?', viewer: 'string?' },
70
- run: ({ req, res, query }) => term.stream(req, res!, query.id as string | undefined, query.viewer as string | undefined),
117
+ run: ({ req, res, query }) =>
118
+ term.stream(req, res!, query.id as string | undefined, query.viewer as string | undefined),
119
+ },
120
+ 'POST /close': {
121
+ description: 'end a session and drop its tab',
122
+ auth: true,
123
+ body: { id: 'string' },
124
+ run: ({ body }) => term.close(body.id as string),
71
125
  },
72
- 'POST /close': { description: 'end a session and drop its tab', auth: true, body: { id: 'string' }, run: ({ body }) => term.close(body.id as string) },
73
126
  'POST /stop': { description: 'end every session and their host', auth: true, run: () => term.stop() },
74
127
  'POST /open': {
75
- description: 'show the page at path in the browser tab whose drawer the reader used last, for session id or, without one, of all; how many were shown',
128
+ description:
129
+ 'show the page at path in the browser tab whose drawer the reader used last, for session id or, without one, of all; how many were shown',
76
130
  auth: true,
77
131
  body: { id: 'string?', path: 'string' },
78
132
  run: ({ body }) => term.open(body.id as string | undefined, body.path as string),
@@ -87,7 +141,8 @@ export default function terminal(): Plugin {
87
141
  },
88
142
  commands: {
89
143
  '': {
90
- description: 'print a link that opens the terminal drawer in this browser (it gives the browser the project\'s token); with --new, open a tab with the shell; with a program after --, run it in a new tab',
144
+ description:
145
+ "print a link that opens the terminal drawer in this browser (it gives the browser the project's token); with --new, open a tab with the shell; with a program after --, run it in a new tab",
91
146
  args: '[page]',
92
147
  options: {
93
148
  new: { type: 'boolean?', description: 'open a new tab with the shell' },
@@ -95,29 +150,33 @@ export default function terminal(): Plugin {
95
150
  rest: '<program> [arguments]',
96
151
  async run(ctx) {
97
152
  if (ctx.options.new || ctx.rest.length) {
98
- const body = await call(ctx, 'POST', '/start', { program: ctx.rest }) as { session: string }
153
+ const body = (await call(ctx, 'POST', '/start', { program: ctx.rest })) as { session: string }
99
154
  console.error(`whiteboard: started in tab ${body.session}`)
100
155
  }
101
156
  console.log(await ctx.authLink(`${ctx.pagePath(ctx.positionals[0])}?terminal=open`))
102
157
  },
103
158
  },
104
159
  open: {
105
- description: 'show a page in the browser tab whose drawer the reader used last (from a program in a terminal tab: that tab\'s drawer)',
160
+ description:
161
+ "show a page in the browser tab whose drawer the reader used last (from a program in a terminal tab: that tab's drawer)",
106
162
  args: '<page|file>',
107
163
  async run(ctx) {
108
164
  if (!ctx.positionals[0]) throw new Error('usage: whiteboard terminal open <page|file>')
109
165
  // a program in a tab knows its tab; anything else gets the drawer the reader used last
110
166
  const id = process.env.WHITEBOARD_TERMINAL || undefined
111
167
  const path = ctx.pagePath(ctx.positionals[0])
112
- const { shown } = await call(ctx, 'POST', '/open', { id, path }) as { shown: number }
113
- if (!shown) throw new Error(`no browser shows ${id ? `terminal tab ${id}` : 'the terminal drawer'} right now; the page is at ${await ctx.server()}${path}`)
168
+ const { shown } = (await call(ctx, 'POST', '/open', { id, path })) as { shown: number }
169
+ if (!shown)
170
+ throw new Error(
171
+ `no browser shows ${id ? `terminal tab ${id}` : 'the terminal drawer'} right now; the page is at ${await ctx.server()}${path}`,
172
+ )
114
173
  console.log(`opened ${path} ${id ? `where tab ${id}'s drawer is` : 'where the drawer you used last is'}`)
115
174
  },
116
175
  },
117
176
  stop: {
118
177
  description: 'end every session and their host',
119
178
  async run(ctx) {
120
- const { stopped } = await call(ctx, 'POST', '/stop') as { stopped: boolean }
179
+ const { stopped } = (await call(ctx, 'POST', '/stop')) as { stopped: boolean }
121
180
  console.log(stopped ? 'stopped' : 'no session ran')
122
181
  },
123
182
  },