@bigmistqke/whiteboard 0.0.0-stage → 0.2.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 (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +628 -2
  3. package/bin/whiteboard.ts +488 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/whiteboard.js +542 -0
  6. package/dist/client/runtime.js +544 -0
  7. package/dist/define.js +7 -0
  8. package/dist/plugins/callout/README.md +13 -0
  9. package/dist/plugins/callout/index.js +27 -0
  10. package/dist/plugins/callout/style.css +12 -0
  11. package/dist/plugins/chat/README.md +46 -0
  12. package/dist/plugins/chat/client.js +3 -0
  13. package/dist/plugins/chat/index.js +47 -0
  14. package/dist/plugins/chat/style.css +24 -0
  15. package/dist/plugins/claude-code/index.js +120 -0
  16. package/dist/plugins/code/README.md +42 -0
  17. package/dist/plugins/code/diff.js +65 -0
  18. package/dist/plugins/code/index.js +77 -0
  19. package/dist/plugins/code/style.css +29 -0
  20. package/dist/plugins/comments/client.js +10 -0
  21. package/dist/plugins/comments/index.js +54 -0
  22. package/dist/plugins/comments/style.css +40 -0
  23. package/dist/plugins/details/README.md +17 -0
  24. package/dist/plugins/details/index.js +17 -0
  25. package/dist/plugins/details/style.css +3 -0
  26. package/dist/plugins/forge/README.md +12 -0
  27. package/dist/plugins/forge/index.js +83 -0
  28. package/dist/plugins/form/README.md +111 -0
  29. package/dist/plugins/form/index.js +102 -0
  30. package/dist/plugins/form/style.css +41 -0
  31. package/dist/plugins/gallery/README.md +30 -0
  32. package/dist/plugins/gallery/client.js +1 -0
  33. package/dist/plugins/gallery/index.js +74 -0
  34. package/dist/plugins/gallery/style.css +27 -0
  35. package/dist/plugins/grid/README.md +33 -0
  36. package/dist/plugins/grid/index.js +33 -0
  37. package/dist/plugins/grid/style.css +25 -0
  38. package/dist/plugins/iframe/README.md +18 -0
  39. package/dist/plugins/iframe/client.js +1 -0
  40. package/dist/plugins/iframe/index.js +40 -0
  41. package/dist/plugins/iframe/style.css +29 -0
  42. package/dist/plugins/index.js +30 -0
  43. package/dist/plugins/mermaid/README.md +21 -0
  44. package/dist/plugins/mermaid/index.js +35 -0
  45. package/dist/plugins/mermaid/style.css +16 -0
  46. package/dist/plugins/quiet/README.md +26 -0
  47. package/dist/plugins/quiet/index.js +17 -0
  48. package/dist/plugins/terminal/client.js +41 -0
  49. package/dist/plugins/terminal/host.js +332 -0
  50. package/dist/plugins/terminal/index.js +171 -0
  51. package/dist/plugins/terminal/modes.js +32 -0
  52. package/dist/plugins/terminal/server.js +256 -0
  53. package/dist/plugins/terminal/sizes.js +57 -0
  54. package/dist/plugins/terminal/style.css +357 -0
  55. package/dist/solid/index.js +36 -0
  56. package/dist/src/auth.js +54 -0
  57. package/dist/src/client/page/base.css +295 -0
  58. package/dist/src/client/page/main.js +1228 -0
  59. package/dist/src/config.js +76 -0
  60. package/dist/src/events.js +183 -0
  61. package/dist/src/html.js +34 -0
  62. package/dist/src/icons.js +6 -0
  63. package/dist/src/load.js +77 -0
  64. package/dist/src/loader.js +126 -0
  65. package/dist/src/package.js +33 -0
  66. package/dist/src/pages/blocks.js +50 -0
  67. package/dist/src/pages/index.js +15 -0
  68. package/dist/src/pages/markdown.js +410 -0
  69. package/dist/src/pages/render.js +311 -0
  70. package/dist/src/plugins.js +238 -0
  71. package/dist/src/running.js +24 -0
  72. package/dist/src/serve.js +71 -0
  73. package/dist/src/server.js +725 -0
  74. package/dist/src/status.js +71 -0
  75. package/package.json +131 -4
  76. package/plugins/callout/README.md +13 -0
  77. package/plugins/callout/index.ts +25 -0
  78. package/plugins/callout/style.css +12 -0
  79. package/plugins/chat/README.md +46 -0
  80. package/plugins/chat/autosize.ts +101 -0
  81. package/plugins/chat/client.tsx +93 -0
  82. package/plugins/chat/index.ts +61 -0
  83. package/plugins/chat/style.css +24 -0
  84. package/plugins/claude-code/index.ts +136 -0
  85. package/plugins/code/README.md +42 -0
  86. package/plugins/code/diff.ts +64 -0
  87. package/plugins/code/index.ts +94 -0
  88. package/plugins/code/style.css +29 -0
  89. package/plugins/comments/client.ts +492 -0
  90. package/plugins/comments/index.ts +54 -0
  91. package/plugins/comments/style.css +40 -0
  92. package/plugins/details/README.md +17 -0
  93. package/plugins/details/index.ts +21 -0
  94. package/plugins/details/style.css +3 -0
  95. package/plugins/forge/README.md +12 -0
  96. package/plugins/forge/index.ts +71 -0
  97. package/plugins/form/README.md +111 -0
  98. package/plugins/form/index.ts +104 -0
  99. package/plugins/form/style.css +41 -0
  100. package/plugins/gallery/README.md +30 -0
  101. package/plugins/gallery/client.tsx +64 -0
  102. package/plugins/gallery/index.ts +67 -0
  103. package/plugins/gallery/style.css +27 -0
  104. package/plugins/grid/README.md +33 -0
  105. package/plugins/grid/index.ts +36 -0
  106. package/plugins/grid/style.css +25 -0
  107. package/plugins/iframe/README.md +18 -0
  108. package/plugins/iframe/client.ts +46 -0
  109. package/plugins/iframe/index.ts +54 -0
  110. package/plugins/iframe/style.css +29 -0
  111. package/plugins/index.ts +21 -0
  112. package/plugins/mermaid/README.md +21 -0
  113. package/plugins/mermaid/index.ts +40 -0
  114. package/plugins/mermaid/style.css +16 -0
  115. package/plugins/quiet/README.md +26 -0
  116. package/plugins/quiet/index.ts +27 -0
  117. package/plugins/terminal/client.ts +317 -0
  118. package/plugins/terminal/host.ts +326 -0
  119. package/plugins/terminal/index.ts +138 -0
  120. package/plugins/terminal/modes.ts +30 -0
  121. package/plugins/terminal/server.ts +215 -0
  122. package/plugins/terminal/sizes.ts +60 -0
  123. package/plugins/terminal/style.css +71 -0
  124. package/skills/whiteboard/SKILL.md +302 -0
  125. package/solid/index.tsx +59 -0
  126. package/src/auth.ts +66 -0
  127. package/src/client/forms.ts +185 -0
  128. package/src/client/markdown.ts +36 -0
  129. package/src/client/page/base.css +295 -0
  130. package/src/client/page/elsewhere.ts +70 -0
  131. package/src/client/page/fresh.ts +205 -0
  132. package/src/client/page/live.ts +30 -0
  133. package/src/client/page/main.ts +272 -0
  134. package/src/client/page/orphans.ts +46 -0
  135. package/src/client/page/sort.ts +38 -0
  136. package/src/client/page/theme.ts +32 -0
  137. package/src/client/page/view.ts +9 -0
  138. package/src/client/page/waiting.ts +182 -0
  139. package/src/client/read.ts +73 -0
  140. package/src/client/runtime.ts +183 -0
  141. package/src/client/toast.ts +25 -0
  142. package/src/config.ts +96 -0
  143. package/src/define.ts +612 -0
  144. package/src/events.ts +218 -0
  145. package/src/html.ts +40 -0
  146. package/src/icons.ts +8 -0
  147. package/src/load.ts +89 -0
  148. package/src/loader.ts +112 -0
  149. package/src/package.ts +39 -0
  150. package/src/pages/blocks.ts +70 -0
  151. package/src/pages/index.ts +42 -0
  152. package/src/pages/markdown.ts +364 -0
  153. package/src/pages/render.ts +233 -0
  154. package/src/plugins.ts +197 -0
  155. package/src/running.ts +22 -0
  156. package/src/serve.ts +52 -0
  157. package/src/server.ts +667 -0
  158. package/src/status.ts +113 -0
@@ -0,0 +1,46 @@
1
+ // An iframe block filling the window, and back: its header's button, or Escape. Which one is
2
+ // maximized is kept across the page's updates, which put back the block as the server wrote it.
3
+ import type { PluginMount } from '../../src/define.ts'
4
+
5
+ const figures = () => [...document.querySelectorAll<HTMLElement>('#wb-main div.wb-iframe')]
6
+ // the maximized block, by its place among the page's iframe blocks and its address
7
+ let maximized: { index: number; src: string } | null = null
8
+
9
+ function apply() {
10
+ const all = figures()
11
+ let found: HTMLElement | null = null
12
+ all.forEach((fig, i) => {
13
+ const on = !!maximized && i === maximized.index && fig.querySelector('iframe')?.getAttribute('src') === maximized.src
14
+ fig.toggleAttribute('data-maximized', on)
15
+ const button = fig.querySelector<HTMLButtonElement>('[data-wb-maximize]')
16
+ if (button) {
17
+ button.title = on ? 'Back into the page (Esc)' : 'Fill the window'
18
+ button.setAttribute('aria-label', button.title)
19
+ button.setAttribute('aria-pressed', String(on))
20
+ }
21
+ if (on) found = fig
22
+ })
23
+ if (maximized && !found) maximized = null
24
+ document.documentElement.toggleAttribute('data-wb-iframe-maximized', !!found)
25
+ }
26
+
27
+ function toggle(fig: HTMLElement) {
28
+ const index = figures().indexOf(fig)
29
+ const src = fig.querySelector('iframe')?.getAttribute('src') ?? ''
30
+ maximized = maximized && maximized.index === index ? null : { index, src }
31
+ apply()
32
+ }
33
+
34
+ const mount: PluginMount = (_root, _handle, api) => {
35
+ document.addEventListener('click', e => {
36
+ const button = (e.target as Element).closest?.('[data-wb-maximize]')
37
+ const fig = button?.closest<HTMLElement>('div.wb-iframe')
38
+ if (fig) toggle(fig)
39
+ })
40
+ document.addEventListener('keydown', e => {
41
+ if (e.key === 'Escape' && maximized) { maximized = null; apply() }
42
+ })
43
+ api.onRendered(apply)
44
+ }
45
+
46
+ export default mount
@@ -0,0 +1,54 @@
1
+ // Another page inside this one: a URL (a dev server, a deployed site) or an HTML file next to the
2
+ // pages (`demo.html` in .whiteboard/pages/ is served as it is). A header shows its label and address,
3
+ // opens it on its own, and fills the window with it; the frame can be made taller by dragging its
4
+ // bottom edge.
5
+ import fs from 'node:fs'
6
+ import { packagePath } from '../../src/package.ts'
7
+ import { definePlugin, type Plugin } from '@bigmistqke/whiteboard'
8
+ import { html, raw, type DirectiveContext } from '@bigmistqke/whiteboard'
9
+
10
+ /** http(s), protocol-relative, or a path on this server; never `javascript:` or `data:`. */
11
+ export const safeSrc = (src: string) => /^(https?:)?\/\//i.test(src) || !/^[a-z][a-z0-9+.-]*:/i.test(src)
12
+
13
+ /** A height in px (a bare number) or a CSS length; else the default. */
14
+ export function height(value: string | undefined): string {
15
+ if (value && /^\d+(\.\d+)?$/.test(value)) return `${value}px`
16
+ if (value && /^\d+(\.\d+)?(px|em|rem|vh|svh|dvh)$/.test(value)) return value
17
+ return '480px'
18
+ }
19
+
20
+ // the header's buttons, as icons
21
+ const svg = (d: string) => raw(`<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${d}</svg>`)
22
+ const OPEN = svg('<path d="M9 2.5h4.5V7M13.5 2.5 7.5 8.5M11.5 9.5v3a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1h3"/>')
23
+ const MAXIMIZE = svg('<path d="M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10"/>')
24
+ const RESTORE = svg('<path d="M6 2.5V6H2.5M13.5 6H10V2.5M10 13.5V10h3.5M2.5 10H6v3.5"/>')
25
+
26
+ export async function render(ctx: DirectiveContext) {
27
+ const src = (ctx.attrs.src ?? '').trim()
28
+ if (!src) return html`<pre class="wb-error">iframe: needs a src, like ::iframe{src="http://localhost:5173"}</pre>`
29
+ if (!safeSrc(src)) return html`<pre class="wb-error">iframe: src must be an http(s) URL or a path, not ${src.split(':')[0]}:</pre>`
30
+ const title = ctx.labelText ?? ctx.attrs.title ?? src
31
+ // a header like a browser window's: the label, or the address without one (hovering the label
32
+ // shows the address), opening it on its own, and filling the window with it (client.ts).
33
+ // `bare`: the frame alone.
34
+ const header = !('bare' in ctx.attrs) && html`<div class="wb-iframe-bar">
35
+ <span class="wb-iframe-name" title="${src}">${ctx.label ? html`<span class="wb-iframe-title">${raw(ctx.label)}</span>` : html`<span class="wb-iframe-url">${src}</span>`}</span>
36
+ <a class="wb-iframe-button" href="${src}" target="_blank" rel="noopener" title="Open on its own" aria-label="Open on its own">${OPEN}</a>
37
+ <button type="button" class="wb-iframe-button" data-wb-maximize title="Fill the window" aria-label="Fill the window"><span class="wb-iframe-max">${MAXIMIZE}</span><span class="wb-iframe-restore">${RESTORE}</span></button>
38
+ </div>`
39
+ return html`<div class="wb-iframe${'wide' in ctx.attrs && raw(' wb-wide')}">${header}<div class="wb-iframe-frame" style="height: ${height(ctx.attrs.height)}"><iframe src="${src}" title="${title}" loading="lazy" referrerpolicy="no-referrer"></iframe></div></div>`
40
+ }
41
+
42
+ export default function iframe(): Plugin {
43
+ return definePlugin({
44
+ name: 'iframe',
45
+ blocks: {
46
+ iframe: {
47
+ html: render,
48
+ style: new URL('./style.css', import.meta.url),
49
+ },
50
+ },
51
+ setup: () => ({ client: packagePath('dist/plugins/iframe/client.js') }),
52
+ docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
53
+ })
54
+ }
@@ -0,0 +1,29 @@
1
+ /* a page inside the page, framed like a browser window; its bottom edge drags it taller */
2
+ .wb-iframe { margin: 1.6em 0; border: 1px solid var(--border); border-radius: var(--radius, 6px); overflow: hidden; background: var(--bg); }
3
+ .wb-iframe-frame { resize: vertical; overflow: hidden; min-height: 120px; background: #fff; }
4
+ .wb-iframe iframe { display: block; width: 100%; height: 100%; border: 0; }
5
+
6
+ .wb-iframe-bar {
7
+ display: flex; align-items: center; gap: 4px; padding: 4px 4px 4px 12px; min-height: 32px; box-sizing: border-box;
8
+ border-bottom: 1px solid var(--border); background: var(--tint, var(--bg)); font: .8rem/1.4 var(--sans); color: var(--muted);
9
+ }
10
+ .wb-iframe-name { flex: 1; min-width: 0; display: flex; gap: 8px; align-items: baseline; overflow: hidden; white-space: nowrap; }
11
+ .wb-iframe-title { color: var(--text); font-weight: 600; overflow: hidden; text-overflow: ellipsis; }
12
+ .wb-iframe-url { font-family: var(--mono, monospace); font-size: .75rem; overflow: hidden; text-overflow: ellipsis; }
13
+ .wb-iframe-button {
14
+ flex: none; display: inline-grid; place-items: center; width: 26px; height: 24px; padding: 0; border: 0; border-radius: 5px;
15
+ background: none; color: var(--muted); cursor: pointer;
16
+ }
17
+ .wb-iframe-button:hover { background: color-mix(in srgb, var(--text) 8%, transparent); color: var(--text); }
18
+ .wb-iframe-restore, .wb-iframe[data-maximized] .wb-iframe-max { display: none; }
19
+ .wb-iframe[data-maximized] .wb-iframe-restore { display: contents; }
20
+ .wb-iframe-max { display: contents; }
21
+
22
+ /* filling the window, above the page and its header; the terminal drawer stays below it. The
23
+ margin is !important: the page indents its blocks with a rule more specific than any here */
24
+ .wb-iframe[data-maximized] {
25
+ position: fixed; inset: 0 0 var(--wb-inset-bottom, 0px) 0; z-index: 40; margin: 0 !important; border-radius: 0; border: 0;
26
+ display: flex; flex-direction: column; width: auto; left: 0; transform: none;
27
+ }
28
+ .wb-iframe[data-maximized] .wb-iframe-frame { flex: 1; height: auto !important; resize: none; }
29
+ :root[data-wb-iframe-maximized] { overflow: hidden; }
@@ -0,0 +1,21 @@
1
+ // The built-in plugins: what every project has, before its config's `plugins` (which add to them,
2
+ // and replace one of the same name: `code({ themes })` for the default `code`). The terminal and the
3
+ // Claude Code plugin are not among them: they run code, or are about one agent, so a project adds
4
+ // them itself.
5
+ import type { Plugin } from '../src/define.ts'
6
+ import callout from './callout/index.ts'
7
+ import chat from './chat/index.ts'
8
+ import code from './code/index.ts'
9
+ import comments from './comments/index.ts'
10
+ import details from './details/index.ts'
11
+ import forge from './forge/index.ts'
12
+ import form from './form/index.ts'
13
+ import gallery from './gallery/index.ts'
14
+ import grid from './grid/index.ts'
15
+ import iframe from './iframe/index.ts'
16
+ import mermaid from './mermaid/index.ts'
17
+ import quiet from './quiet/index.ts'
18
+
19
+ export function builtins(): Plugin[] {
20
+ return [callout(), chat(), code(), comments(), details(), forge(), form(), gallery(), grid(), iframe(), mermaid(), quiet()]
21
+ }
@@ -0,0 +1,21 @@
1
+ A [Mermaid](https://mermaid.js.org) diagram from a fence: flowcharts,
2
+ sequence, state, class, ER, gantt, pie and the other Mermaid types. Rendered
3
+ to SVG on the server by [Pele](https://pele.run), so no script runs on the
4
+ page; colours follow the page theme. A syntax error shows the line and
5
+ column in place of the diagram.
6
+
7
+ ````markdown
8
+ ```mermaid
9
+ flowchart LR
10
+ agent[agent writes .md] --> page[page in browser]
11
+ page -- form submit --> log[(events.ndjson)]
12
+ log -- whiteboard wait --> agent
13
+ ```
14
+ ````
15
+
16
+ ```mermaid
17
+ flowchart LR
18
+ agent[agent writes .md] --> page[page in browser]
19
+ page -- form submit --> log[(events.ndjson)]
20
+ log -- whiteboard wait --> agent
21
+ ```
@@ -0,0 +1,40 @@
1
+ import fs from 'node:fs'
2
+ import { definePlugin, type Plugin } from '@bigmistqke/whiteboard'
3
+ // Mermaid diagrams rendered to SVG on the server with Pele (https://pele.run): no JavaScript on
4
+ // the page, and colours come from CSS variables, so diagrams follow the light/dark theme.
5
+ import crypto from 'node:crypto'
6
+ // pele loads the first time a page has a diagram, not with the plugin
7
+ let pele: typeof import('pele') | undefined
8
+ import { html, raw, type FenceContext } from '@bigmistqke/whiteboard'
9
+
10
+ const FONT = 'ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'
11
+
12
+ export async function render(ctx: FenceContext) {
13
+ pele ??= await import('pele')
14
+ // ids derive from the source, so an unchanged diagram renders the same markup every time
15
+ const idPrefix = `wbm-${crypto.createHash('sha1').update(ctx.text).digest('hex').slice(0, 8)}-`
16
+ try {
17
+ const { svg } = pele.render(ctx.text, { idPrefix, fontFamily: FONT, responsive: true })
18
+ // the SVG is Pele's markup
19
+ return html`<figure class="wb-diagram wb-figure">${raw(svg)}</figure>`
20
+ } catch (err) {
21
+ if (!(err instanceof pele.PeleError)) throw err
22
+ const where = err.line ? ` (line ${err.line}${err.column ? `, column ${err.column}` : ''})` : ''
23
+ const snippet = err.snippet ? `\n\n${err.snippet}` : ''
24
+ return html`<pre class="wb-error">mermaid: ${err.message}${where}${snippet}</pre>`
25
+ }
26
+ }
27
+
28
+ export default function mermaid(): Plugin {
29
+ return definePlugin({
30
+ name: 'mermaid',
31
+ blocks: {
32
+ mermaid: {
33
+ fence: true,
34
+ html: render,
35
+ style: new URL('./style.css', import.meta.url),
36
+ },
37
+ },
38
+ docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
39
+ })
40
+ }
@@ -0,0 +1,16 @@
1
+ /* Pele reads its colours from --pele-* variables; map them onto the page's tokens so diagrams
2
+ follow the theme without being re-rendered. */
3
+ .wb-diagram {
4
+ margin: 4em 0; overflow-x: auto; text-align: center;
5
+ --pele-bg: transparent;
6
+ --pele-fg: var(--text);
7
+ --pele-muted: var(--muted);
8
+ --pele-line: var(--muted);
9
+ --pele-surface: var(--surface);
10
+ --pele-surface-alt: var(--code-bg);
11
+ --pele-border: var(--border);
12
+ --pele-accent: var(--accent);
13
+ --pele-font: var(--sans);
14
+ --pele-radius: 6px;
15
+ }
16
+ .wb-diagram svg { max-width: 100%; height: auto; }
@@ -0,0 +1,26 @@
1
+ Content that is never marked as new. Changed blocks get a red bar until the
2
+ reader has seen them; what is inside `quiet` does not count as a change. Use
3
+ it for what changes without being news to the reader: repeating back what
4
+ they answered, a status line, a timestamp. Anything with substance (an
5
+ explanation, a question back, a different reading of their answer) belongs
6
+ outside it, so it is marked.
7
+
8
+ A whole block, a line, or a few words:
9
+
10
+ ```markdown
11
+ :::quiet
12
+ Decided: **this week**, as you answered.
13
+ :::
14
+
15
+ ::quiet[Last checked 12:04]
16
+
17
+ The build is green :quiet[(as of 12:04)].
18
+ ```
19
+
20
+ Inside a larger block, such as a card, only the quiet part is ignored: other
21
+ changes in the block still mark it. Hand-written HTML can do the same with a
22
+ `data-wb-quiet` attribute.
23
+
24
+ :::quiet
25
+ This block is quiet: editing it never marks it as new.
26
+ :::
@@ -0,0 +1,27 @@
1
+ import fs from 'node:fs'
2
+ import { definePlugin, type Plugin } from '@bigmistqke/whiteboard'
3
+ // Content the new-content marking leaves alone: whatever is inside a quiet wrapper never marks its
4
+ // block as new, and a block that is quiet as a whole is never marked. For what changes without
5
+ // being news to the reader: an echo of their answer, a status line, a timestamp. The mechanism is
6
+ // the data-wb-quiet attribute, which any block or hand-written HTML can use as well.
7
+ import { html, raw, type DirectiveContext } from '@bigmistqke/whiteboard'
8
+
9
+ export async function render(ctx: DirectiveContext) {
10
+ // the label and content are HTML already
11
+ const label = ctx.label && raw(ctx.label)
12
+ if (ctx.kind === 'textDirective') return html`<span data-wb-quiet>${label}</span>`
13
+ if (ctx.kind === 'leafDirective') return html`<div data-wb-quiet>${label && html`<p>${label}</p>`}</div>`
14
+ return html`<div data-wb-quiet>${raw(await ctx.toHtml(ctx.children))}</div>`
15
+ }
16
+
17
+ export default function quiet(): Plugin {
18
+ return definePlugin({
19
+ name: 'quiet',
20
+ blocks: {
21
+ quiet: {
22
+ html: render,
23
+ },
24
+ },
25
+ docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
26
+ })
27
+ }
@@ -0,0 +1,317 @@
1
+ // The terminal drawer at the bottom of every page (for a browser with the project's token; see
2
+ // server.ts). The server writes its markup and sets its open state before the first render, so
3
+ // the browser can morph it from the page before (a view transition across the page load). This module
4
+ // connects it: an xterm that shows the session of the current tab, keystrokes and size sent back,
5
+ // and a tab per session, with "+" for a shell next to them.
6
+ //
7
+ // The sessions live on the server. Each page load connects again and first gets the whole screen of
8
+ // its tab, so switching pages loses nothing.
9
+ import { Terminal } from '@xterm/xterm'
10
+ import { FitAddon } from '@xterm/addon-fit'
11
+
12
+ const store = {
13
+ get: (k: string) => { try { return sessionStorage.getItem(k) } catch { return null } },
14
+ set: (k: string, v: string) => { try { sessionStorage.setItem(k, v) } catch { /* storage unavailable */ } },
15
+ }
16
+
17
+ interface Session { id: string; label: string; running: boolean; exited: number | null }
18
+
19
+ function init(drawer: HTMLElement) {
20
+ const screen = drawer.querySelector<HTMLElement>('.wb-term-screen')!
21
+ const tabs = drawer.querySelector<HTMLElement>('.wb-term-tabs')!
22
+ const status = drawer.querySelector<HTMLElement>('.wb-term-status')!
23
+ const actions = drawer.querySelector<HTMLElement>('.wb-term-actions')!
24
+ const toggle = drawer.querySelector<HTMLButtonElement>('.wb-term-toggle')!
25
+ const grip = drawer.querySelector<HTMLElement>('.wb-term-grip')!
26
+ // the sessions as the server wrote them into the page, and the tab this browser tab shows
27
+ let sessions: Session[] = []
28
+ try { ({ sessions } = JSON.parse(drawer.dataset.sessions ?? '{}')); sessions ??= [] } catch { /* none */ }
29
+ let current: string | null = drawer.dataset.tab ?? sessions[0]?.id ?? null
30
+
31
+ const term = new Terminal({
32
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
33
+ fontSize: 13,
34
+ cursorBlink: true,
35
+ scrollback: 5000,
36
+ // xterm scales every wheel event smaller than 50 pixels down to 0.3 of its lines, and a trackpad
37
+ // sends almost only those: a swipe moved a program that handles the mouse itself (scrolling its
38
+ // own view) at a third of the speed of a native terminal. This undoes that factor.
39
+ scrollSensitivity: 3,
40
+ allowProposedApi: true,
41
+ theme: { background: '#0f1115', foreground: '#d7dae0', cursor: '#d7dae0', selectionBackground: '#3a4150' },
42
+ })
43
+ const fit = new FitAddon()
44
+ term.loadAddon(fit)
45
+ term.open(screen)
46
+
47
+ const isOpen = () => drawer.dataset.state === 'open'
48
+ // drop the ?terminal=open the auth link adds, now that the state is in this tab
49
+ if (new URLSearchParams(location.search).get('terminal') === 'open') {
50
+ store.set('wb-terminal-open', '1')
51
+ const url = new URL(location.href)
52
+ url.searchParams.delete('terminal')
53
+ history.replaceState(history.state, '', url)
54
+ }
55
+
56
+ // ---- size ----------------------------------------------------------------------------------
57
+ // A session has one size for every drawer showing it (every browser window): the size of the
58
+ // drawer the reader used last, its active viewer (see host.ts). This drawer reports the size that
59
+ // fits it, claims the session when the reader uses it (opening it, focus, a keystroke), and
60
+ // otherwise shows the session at the session's size: with a margin, or cut off at the right.
61
+ const viewer = crypto.randomUUID()
62
+ // the session's active viewer and size, as the host last said
63
+ let active: string | null = null
64
+ let session: { cols: number; rows: number } | null = null
65
+ // this browser tab was the one in use: its next page claims the session again
66
+ let claim = store.get('wb-terminal-active') === '1'
67
+ let sent = ''
68
+ const mine = () => active === viewer
69
+
70
+ /** Tell the host the size that fits this drawer, and whether the reader uses it now. */
71
+ function refit() {
72
+ if (!isOpen() || !current) return
73
+ const dims = fit.proposeDimensions()
74
+ if (!dims?.cols || !dims?.rows) return
75
+ const key = `${current} ${dims.cols}x${dims.rows} ${claim}`
76
+ if (key !== sent) {
77
+ sent = key
78
+ post('/api/terminal/resize', { id: current, viewer, cols: dims.cols, rows: dims.rows, active: claim })
79
+ // it is ours from now on; the host confirms with a `size`
80
+ if (claim) { active = viewer; claim = false }
81
+ }
82
+ show()
83
+ }
84
+
85
+ /** The terminal at the size it has here: its own when this drawer is the active one, else the session's. */
86
+ function show() {
87
+ const dims = fit.proposeDimensions()
88
+ const size = mine() || !session ? dims : session
89
+ if (size?.cols && size?.rows && (size.cols !== term.cols || size.rows !== term.rows)) term.resize(size.cols, size.rows)
90
+ }
91
+
92
+ /** The reader uses this drawer: the session takes its size. */
93
+ function use() {
94
+ if (mine() || !current) return
95
+ claim = true
96
+ refit()
97
+ }
98
+
99
+ new ResizeObserver(() => refit()).observe(screen)
100
+ term.textarea?.addEventListener('focus', use)
101
+
102
+ // ---- open and closed -----------------------------------------------------------------------
103
+ function setOpen(open: boolean) {
104
+ const apply = () => {
105
+ drawer.dataset.state = open ? 'open' : 'collapsed'
106
+ store.set('wb-terminal-open', open ? '1' : '0')
107
+ }
108
+ // the drawer morphs between its two states, as between pages
109
+ const vt = (document as any).startViewTransition
110
+ if (vt && !matchMedia('(prefers-reduced-motion: reduce)').matches) vt.call(document, apply)
111
+ else apply()
112
+ requestAnimationFrame(() => { if (open) use(); refit(); if (open) term.focus() })
113
+ }
114
+ toggle.addEventListener('click', () => setOpen(!isOpen()))
115
+ addEventListener('keydown', e => {
116
+ if (e.ctrlKey && e.key === '`') { e.preventDefault(); setOpen(!isOpen()) }
117
+ })
118
+
119
+ // ---- height --------------------------------------------------------------------------------
120
+ grip.addEventListener('pointerdown', e => {
121
+ e.preventDefault()
122
+ grip.setPointerCapture(e.pointerId)
123
+ if (!isOpen()) setOpen(true)
124
+ const bar = drawer.querySelector<HTMLElement>('.wb-term-bar')!.offsetHeight
125
+ const move = (ev: PointerEvent) => {
126
+ const h = Math.max(120, Math.min(innerHeight - 80, innerHeight - ev.clientY - bar))
127
+ document.documentElement.style.setProperty('--wb-term-h', `${Math.round(h)}px`)
128
+ }
129
+ const up = () => {
130
+ grip.removeEventListener('pointermove', move)
131
+ grip.removeEventListener('pointerup', up)
132
+ const h = getComputedStyle(document.documentElement).getPropertyValue('--wb-term-h')
133
+ store.set('wb-terminal-height', String(parseInt(h) || ''))
134
+ refit()
135
+ }
136
+ grip.addEventListener('pointermove', move)
137
+ grip.addEventListener('pointerup', up)
138
+ })
139
+
140
+ // ---- input ---------------------------------------------------------------------------------
141
+ // keystrokes in order, several typed at once in one request
142
+ let pending = ''
143
+ let chain = Promise.resolve()
144
+ term.onData(d => {
145
+ if (!current) return
146
+ use()
147
+ const id = current
148
+ if (!pending) queueMicrotask(() => {
149
+ const data = pending
150
+ pending = ''
151
+ chain = chain.then(() => post('/api/terminal/input', { id, data })).then(() => {}, () => {})
152
+ })
153
+ pending += d
154
+ })
155
+
156
+ // ---- the session ---------------------------------------------------------------------------
157
+ function setStatus(text: string, buttons: [string, () => void][] = []) {
158
+ status.textContent = text
159
+ actions.replaceChildren(...buttons.map(([label, run]) => {
160
+ const b = document.createElement('button')
161
+ b.type = 'button'
162
+ b.textContent = label
163
+ b.addEventListener('click', run)
164
+ return b
165
+ }))
166
+ }
167
+
168
+ // ---- tabs ----------------------------------------------------------------------------------
169
+ function drawTabs() {
170
+ tabs.replaceChildren(...sessions.map(x => {
171
+ const tab = document.createElement('span')
172
+ tab.className = 'wb-term-tab'
173
+ tab.dataset.id = x.id
174
+ tab.classList.toggle('wb-current', x.id === current)
175
+ tab.toggleAttribute('data-exited', !x.running)
176
+ const name = document.createElement('button')
177
+ name.type = 'button'
178
+ name.className = 'wb-term-tab-name'
179
+ name.textContent = x.label
180
+ name.title = x.running ? x.label : `${x.label}: exited (${x.exited})`
181
+ name.addEventListener('click', () => select(x.id))
182
+ tab.append(name)
183
+ const close = document.createElement('button')
184
+ close.type = 'button'
185
+ close.className = 'wb-term-tab-close'
186
+ close.title = 'Close this tab (ends its program)'
187
+ close.textContent = '×'
188
+ close.addEventListener('click', () => closeTab(x.id))
189
+ tab.append(close)
190
+ return tab
191
+ }))
192
+ showStatus()
193
+ }
194
+
195
+ // "+" at the bar's right end, after the tabs, outside them so it stays in view when they scroll
196
+ const add = document.createElement('button')
197
+ add.type = 'button'
198
+ add.className = 'wb-term-add'
199
+ add.title = 'A new tab with a shell'
200
+ add.textContent = '+'
201
+ add.addEventListener('click', () => start({}))
202
+ tabs.after(add)
203
+
204
+ function showStatus() {
205
+ const x = sessions.find(y => y.id === current)
206
+ // no tab yet: "+" opens one
207
+ if (!x) return setStatus('', [])
208
+ if (x.running) return setStatus('', [])
209
+ setStatus(x.exited == null ? 'stopped' : `exited (${x.exited})`, [['Start again', () => start({ id: x.id, restart: true })]])
210
+ }
211
+
212
+ function select(id: string | null) {
213
+ // the tab that shows already: just give it the keyboard back
214
+ if (id === current && stream) { if (isOpen()) term.focus(); return }
215
+ current = id
216
+ if (id) store.set('wb-terminal-tab', id)
217
+ drawTabs()
218
+ connect()
219
+ if (isOpen()) term.focus()
220
+ }
221
+
222
+ async function closeTab(id: string) {
223
+ await post('/api/terminal/close', { id })
224
+ sessions = sessions.filter(x => x.id !== id)
225
+ if (current === id) select(sessions.at(-1)?.id ?? null)
226
+ else drawTabs()
227
+ }
228
+
229
+ /** Open a tab with the shell, or start tab `id` again as it was. */
230
+ async function start(body: { id?: string; restart?: boolean }) {
231
+ setStatus('starting…')
232
+ const res = await post('/api/terminal/start', body)
233
+ const reply = await res.json().catch(() => ({}))
234
+ if (!res.ok) return setStatus(reply.error ?? 'could not start', [['Try again', () => start(body)]])
235
+ await loadSessions()
236
+ if (!isOpen()) setOpen(true)
237
+ select(reply.session)
238
+ term.focus()
239
+ }
240
+
241
+ async function loadSessions() {
242
+ try {
243
+ const res = await fetch('/api/terminal/sessions')
244
+ if (res.ok) ({ sessions } = await res.json())
245
+ } catch { /* the server is away: the stream reconnects */ }
246
+ drawTabs()
247
+ }
248
+
249
+ let stream: EventSource | null = null
250
+ function connect() {
251
+ stream?.close()
252
+ term.reset()
253
+ sent = ''
254
+ if (!current) showStatus()
255
+ // without a tab too: the host tells it when one appears (started from the command line, say)
256
+ stream = new EventSource(`/api/terminal/stream?${current ? `id=${encodeURIComponent(current)}&` : ''}viewer=${viewer}`)
257
+ stream.addEventListener('sessions', e => {
258
+ sessions = JSON.parse((e as MessageEvent).data).sessions
259
+ // the current tab is gone, or there was none and one appeared: show the last
260
+ if (current ? !sessions.some(x => x.id === current) : sessions.length) return select(sessions.at(-1)?.id ?? null)
261
+ drawTabs()
262
+ })
263
+ stream.addEventListener('none', () => {
264
+ term.reset()
265
+ screen.querySelectorAll('.wb-term-placeholder').forEach(p => p.remove())
266
+ showStatus()
267
+ })
268
+ stream.addEventListener('screen', e => {
269
+ const { d, cols, rows, active: a } = JSON.parse((e as MessageEvent).data)
270
+ term.reset()
271
+ // the screen as the host has it, at the session's size; then the size this drawer shows it at
272
+ session = cols && rows ? { cols, rows } : null
273
+ active = a ?? null
274
+ if (session) term.resize(session.cols, session.rows)
275
+ term.write(d, () => {
276
+ refit()
277
+ // the live terminal takes over from the screens the server wrote into the page
278
+ screen.querySelectorAll('.wb-term-placeholder').forEach(p => p.remove())
279
+ })
280
+ showStatus()
281
+ if (isOpen() && store.get('wb-terminal-focus') === '1') term.focus()
282
+ })
283
+ stream.addEventListener('data', e => term.write(JSON.parse((e as MessageEvent).data).d))
284
+ // a program in this tab asked to show a page here (`whiteboard terminal open`): the drawer comes along
285
+ stream.addEventListener('navigate', e => {
286
+ const { path } = JSON.parse((e as MessageEvent).data)
287
+ if (typeof path === 'string' && path.startsWith('/') && !path.startsWith('//')) location.assign(path)
288
+ })
289
+ // the session's size changed, or another drawer became the active one
290
+ stream.addEventListener('size', e => {
291
+ const { cols, rows, active: a } = JSON.parse((e as MessageEvent).data)
292
+ session = { cols, rows }
293
+ active = a ?? null
294
+ store.set('wb-terminal-active', mine() ? '1' : '0')
295
+ show()
296
+ })
297
+ stream.addEventListener('exit', e => {
298
+ const code = JSON.parse((e as MessageEvent).data).code
299
+ const x = sessions.find(y => y.id === current)
300
+ if (x) { x.running = false; x.exited = code }
301
+ drawTabs()
302
+ })
303
+ }
304
+
305
+ // whether the terminal had the keyboard, for the next page
306
+ addEventListener('pagehide', () => store.set('wb-terminal-focus', drawer.contains(document.activeElement) ? '1' : '0'))
307
+
308
+ drawTabs()
309
+ connect()
310
+ }
311
+
312
+ function post(url: string, body: unknown) {
313
+ return fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
314
+ }
315
+
316
+ const drawer = document.getElementById('wb-terminal')
317
+ if (drawer) init(drawer)