@bigmistqke/whiteboard 0.4.0 → 0.5.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 (50) hide show
  1. package/README.md +55 -4
  2. package/bin/whiteboard.ts +32 -0
  3. package/dist/bin/whiteboard.js +21 -0
  4. package/dist/client/runtime.js +44 -13
  5. package/dist/plugins/draft/README.md +14 -0
  6. package/dist/plugins/draft/index.js +21 -0
  7. package/dist/plugins/draft/public/style.css +21 -0
  8. package/dist/plugins/index.js +5 -1
  9. package/dist/plugins/steps/README.md +42 -0
  10. package/dist/plugins/steps/index.js +99 -0
  11. package/dist/plugins/steps/public/client.js +1 -0
  12. package/dist/plugins/steps/public/style.css +77 -0
  13. package/dist/plugins/terminal/host.js +9 -3
  14. package/dist/plugins/terminal/sizes.js +2 -1
  15. package/dist/plugins/toc/README.md +21 -3
  16. package/dist/plugins/toc/index.js +8 -2
  17. package/dist/plugins/toc/public/client.js +1 -1
  18. package/dist/plugins/toc/public/style.css +10 -4
  19. package/dist/src/auth.js +2 -1
  20. package/dist/src/client/page/main.js +14 -6
  21. package/dist/src/loader.js +8 -2
  22. package/dist/src/pages/render.js +42 -15
  23. package/dist/src/pages/window.js +3 -2
  24. package/dist/src/server.js +216 -10
  25. package/package.json +3 -2
  26. package/plugins/code/index.ts +3 -1
  27. package/plugins/draft/README.md +14 -0
  28. package/plugins/draft/index.ts +23 -0
  29. package/plugins/draft/public/style.css +21 -0
  30. package/plugins/index.ts +4 -0
  31. package/plugins/mermaid/index.ts +4 -2
  32. package/plugins/steps/README.md +42 -0
  33. package/plugins/steps/client.ts +66 -0
  34. package/plugins/steps/index.ts +127 -0
  35. package/plugins/steps/public/style.css +77 -0
  36. package/plugins/terminal/host.ts +12 -6
  37. package/plugins/terminal/sizes.ts +3 -1
  38. package/plugins/toc/README.md +21 -3
  39. package/plugins/toc/client.ts +47 -6
  40. package/plugins/toc/index.ts +19 -6
  41. package/plugins/toc/public/style.css +10 -4
  42. package/src/auth.ts +3 -2
  43. package/src/client/page/main.ts +18 -6
  44. package/src/client/runtime.ts +51 -16
  45. package/src/define.ts +60 -12
  46. package/src/loader.ts +7 -2
  47. package/src/pages/index.ts +2 -2
  48. package/src/pages/render.ts +48 -16
  49. package/src/pages/window.ts +8 -1
  50. package/src/server.ts +253 -13
@@ -17,6 +17,7 @@ import { definePlugin, type Plugin } from '@bigmistqke/whiteboard'
17
17
  // of the text) and where it is (`data-wb-at="file:line"`), which comments on the line record.
18
18
  // shiki loads the first time a page has code, not with the plugin: the command line loads the
19
19
  // built-in plugins too, for their declarations
20
+ import type * as Shiki from 'shiki'
20
21
  import type { BundledTheme, Highlighter } from 'shiki'
21
22
  import type { FenceContext } from '@bigmistqke/whiteboard'
22
23
  import { diffLines } from './diff.ts'
@@ -41,7 +42,8 @@ export default function code(options: Options = {}): Plugin {
41
42
  const themes = options.themes ?? DEFAULT_THEMES
42
43
  const colorReplacements = options.colorReplacements ?? (options.themes ? {} : DEFAULT_REPLACEMENTS)
43
44
  let highlighter: Promise<Highlighter> | undefined
44
- let shiki: typeof import('shiki') | undefined
45
+ // loaded the first time a page has code, not with the plugin: the command line loads plugins too
46
+ let shiki: typeof Shiki | undefined
45
47
  const loaded = new Set<string>()
46
48
 
47
49
  /** Highlight `code` as `lang`; an unknown or missing language renders as plain text. */
@@ -0,0 +1,14 @@
1
+ What is there while a page is written, and not once it is built: a note to
2
+ check something, two versions of a paragraph, a question for later. It shows
3
+ set apart, marked as a draft; `whiteboard build` leaves it out (it is in the
4
+ build's `skip` by default). The label is optional.
5
+
6
+ ```markdown
7
+ :::draft[Check with the API]
8
+ Is `wait` really the only way to get answers?
9
+ :::
10
+ ```
11
+
12
+ :::draft[Check with the API]
13
+ Is `wait` really the only way to get answers?
14
+ :::
@@ -0,0 +1,23 @@
1
+ // Draft: what is there while a page is written, and not once it is built (`whiteboard build` leaves
2
+ // it out by default): a note to check something, two versions of a paragraph, a question for later.
3
+ import fs from 'node:fs'
4
+ import { definePlugin, html, raw, type DirectiveContext, type Plugin } from '@bigmistqke/whiteboard'
5
+ import { builtinPublic } from '../../src/package.ts'
6
+
7
+ export async function render(ctx: DirectiveContext) {
8
+ const label = ctx.label != null && String(ctx.label) !== '' ? ctx.label : 'draft'
9
+ return html`<aside class="wb-draft">
10
+ <div class="wb-draft-label">${raw(String(label))}</div>
11
+ ${raw(await ctx.toHtml(ctx.children))}
12
+ </aside>`
13
+ }
14
+
15
+ export default function draft(): Plugin {
16
+ return definePlugin({
17
+ name: 'draft',
18
+ public: builtinPublic('draft'),
19
+ style: 'style.css',
20
+ blocks: { draft: { html: render } },
21
+ docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
22
+ })
23
+ }
@@ -0,0 +1,21 @@
1
+ /* A draft (index.ts): set apart, plainly not final */
2
+ .wb-draft {
3
+ margin: calc(var(--rhythm) * 2) 0;
4
+ padding: var(--space-md) var(--space-xl) var(--space-xl);
5
+ border: var(--hairline) dashed color-mix(in srgb, var(--warn) var(--tint-strong), transparent);
6
+ border-radius: var(--radius);
7
+ background: color-mix(in srgb, var(--warn) var(--tint-faint), transparent);
8
+ }
9
+ .wb-draft-label {
10
+ font: var(--weight-strong) var(--ui-tiny) / var(--ui-line-height) var(--sans);
11
+ letter-spacing: var(--caps-spacing);
12
+ text-transform: uppercase;
13
+ color: var(--warn);
14
+ margin-bottom: var(--space-xs);
15
+ }
16
+ .wb-draft-label > * {
17
+ margin: 0;
18
+ }
19
+ .wb-draft > :last-child {
20
+ margin-bottom: 0;
21
+ }
package/plugins/index.ts CHANGED
@@ -16,6 +16,8 @@ import iframe from './iframe/index.ts'
16
16
  import mermaid from './mermaid/index.ts'
17
17
  import quiet from './quiet/index.ts'
18
18
  import windows from './window/index.ts'
19
+ import steps from './steps/index.ts'
20
+ import draft from './draft/index.ts'
19
21
 
20
22
  export function builtins(): Plugin[] {
21
23
  return [
@@ -32,5 +34,7 @@ export function builtins(): Plugin[] {
32
34
  mermaid(),
33
35
  quiet(),
34
36
  windows(),
37
+ steps(),
38
+ draft(),
35
39
  ]
36
40
  }
@@ -3,11 +3,13 @@ import { definePlugin, type Plugin } from '@bigmistqke/whiteboard'
3
3
  // Mermaid diagrams rendered to SVG on the server with Pele (https://pele.run): no JavaScript on
4
4
  // the page, and colours come from CSS variables, so diagrams follow the light/dark theme.
5
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
6
+ import type * as Pele from 'pele'
8
7
  import { html, raw, type FenceContext } from '@bigmistqke/whiteboard'
9
8
  import { builtinPublic } from '../../src/package.ts'
10
9
 
10
+ // loaded the first time a page has a diagram, not with the plugin: the command line loads plugins too
11
+ let pele: typeof Pele | undefined
12
+
11
13
  const FONT = 'ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'
12
14
 
13
15
  export async function render(ctx: FenceContext) {
@@ -0,0 +1,42 @@
1
+ One pane, one item at a time, with ‹ › between them: an A/B, the steps of a
2
+ procedure, versions of a design. It is a window, so ⤢ fills the browser
3
+ window with it (for going through steps, large).
4
+
5
+ Each heading at the shallowest level starts an item; without headings, `---`
6
+ separates them. With up to four items, all titled, the header shows the
7
+ titles as tabs; else it counts (`2 / 5`) and each item shows its title.
8
+
9
+ The items are laid over each other, so the pane is as tall as the tallest
10
+ and flipping doesn't move the page. ← and → step when it has the focus (a
11
+ click in it) or fills the window. Which item shows stays when the page
12
+ updates.
13
+
14
+ Attributes: `count` (count, never tabs), `wide`, `height`.
15
+
16
+ ```markdown
17
+ :::steps[Two headers]
18
+ ### A
19
+ The label on the left, the buttons on the right.
20
+
21
+ ### B
22
+ Everything centred.
23
+ :::
24
+ ```
25
+
26
+ :::steps[Two headers]
27
+ ### A
28
+ The label on the left, the buttons on the right.
29
+
30
+ ### B
31
+ Everything centred.
32
+ :::
33
+
34
+ ```markdown
35
+ :::steps[The migration]
36
+ ### Copy the table
37
+ `migrate --dry-run` on staging first.
38
+
39
+ ### Switch the reads
40
+ …
41
+ :::
42
+ ```
@@ -0,0 +1,66 @@
1
+ // Steps in the browser: which item shows, by the ‹ › buttons, the tabs and ← →, and kept across
2
+ // the page's updates (which write the block anew) by the block's place among the page's steps. It
3
+ // marks only data-wb-* attributes, which a block's signature leaves out: flipping through items is
4
+ // not a change to the page.
5
+ import type { Api, PageHandle, PluginMount } from '../../src/define'
6
+
7
+ const windows = () => [...document.querySelectorAll<HTMLElement>('#wb-main .wb-steps-window')]
8
+ const items = (win: HTMLElement) => [
9
+ ...win.querySelectorAll<HTMLElement>(':scope > .wb-window-body > .wb-steps > .wb-steps-item'),
10
+ ]
11
+ const marks = (win: HTMLElement) => [...win.querySelectorAll<HTMLElement>(':scope > .wb-window-bar .wb-steps-mark')]
12
+
13
+ /** which item shows, by the block's place */
14
+ const at = new Map<number, number>()
15
+
16
+ function show(win: HTMLElement, place: number, i: number) {
17
+ const all = items(win)
18
+ const n = Math.max(all.length, 1)
19
+ i = Math.min(Math.max(i, 0), n - 1)
20
+ at.set(place, i)
21
+ win.setAttribute('data-wb-step', String(i))
22
+ all.forEach((item, k) => item.toggleAttribute('data-wb-current', k === i))
23
+ marks(win).forEach((mark, k) => mark.toggleAttribute('data-wb-current', k === i))
24
+ win.toggleAttribute('data-wb-first', i === 0)
25
+ win.toggleAttribute('data-wb-last', i === n - 1)
26
+ }
27
+
28
+ const apply = () => windows().forEach((win, place) => show(win, place, at.get(place) ?? 0))
29
+
30
+ function step(win: HTMLElement, to: 'prev' | 'next' | number) {
31
+ const place = windows().indexOf(win)
32
+ if (place < 0) return
33
+ const now = at.get(place) ?? 0
34
+ show(win, place, to === 'prev' ? now - 1 : to === 'next' ? now + 1 : to)
35
+ }
36
+
37
+ const typing = (el: Element | null) =>
38
+ !!el?.closest?.('input, textarea, select, [contenteditable]:not([contenteditable="false"])')
39
+
40
+ let listening = false
41
+ const mount: PluginMount = (_el: HTMLElement, _handle: PageHandle, core: Api) => {
42
+ apply()
43
+ core.onRendered(apply)
44
+ if (listening) return
45
+ listening = true
46
+ document.addEventListener('click', e => {
47
+ const button = (e.target as Element).closest?.<HTMLElement>('[data-steps]')
48
+ const win = button?.closest<HTMLElement>('.wb-steps-window')
49
+ if (!button || !win) return
50
+ const to = button.dataset.steps!
51
+ step(win, to === 'prev' || to === 'next' ? to : Number(to))
52
+ })
53
+ document.addEventListener('keydown', e => {
54
+ if ((e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') || e.metaKey || e.ctrlKey || e.altKey) return
55
+ const target = e.target as Element
56
+ if (typing(target)) return
57
+ // the steps that have the focus, or the one filling the window
58
+ const win =
59
+ target.closest?.<HTMLElement>('.wb-steps-window') ??
60
+ document.querySelector<HTMLElement>('#wb-main .wb-steps-window[data-wb-maximized]')
61
+ if (!win) return
62
+ e.preventDefault()
63
+ step(win, e.key === 'ArrowLeft' ? 'prev' : 'next')
64
+ })
65
+ }
66
+ export default mount
@@ -0,0 +1,127 @@
1
+ // Steps: one pane, one item at a time, ‹ › between them: an A/B, a sequence of steps, versions of a
2
+ // design. In a window (src/pages/window.ts), so it fills the browser window too. The items are laid
3
+ // over each other, so the pane is as tall as the tallest and flipping doesn't move the page; which
4
+ // one shows is the browser's (client.ts), kept across the page's updates.
5
+ import fs from 'node:fs'
6
+ import { definePlugin, html, raw, windowFrame, type DirectiveContext, type Plugin } from '@bigmistqke/whiteboard'
7
+ import { builtinPublic } from '../../src/package.ts'
8
+
9
+ interface Node {
10
+ type: string
11
+ depth?: number
12
+ value?: string
13
+ children?: Node[]
14
+ }
15
+
16
+ export interface Part {
17
+ /** the heading's content, or none */
18
+ title: Node[] | null
19
+ body: Node[]
20
+ }
21
+
22
+ /**
23
+ * The items of a block: one per heading at its shallowest level (what comes before the first is an
24
+ * item of its own); without headings, `---` separates them; else it is one item.
25
+ */
26
+ export function split(children: Node[]): Part[] {
27
+ const content = children.filter(n => !(n.type === 'text' && !n.value?.trim()))
28
+ const heads = content.filter(n => n.type === 'heading')
29
+ const parts: Part[] = []
30
+ if (heads.length) {
31
+ const depth = Math.min(...heads.map(h => h.depth!))
32
+ for (const n of content) {
33
+ if (n.type === 'heading' && n.depth === depth) parts.push({ title: n.children ?? [], body: [] })
34
+ else if (parts.length) parts.at(-1)!.body.push(n)
35
+ else parts.push({ title: null, body: [n] })
36
+ }
37
+ return parts
38
+ }
39
+ let current: Part = { title: null, body: [] }
40
+ for (const n of content) {
41
+ if (n.type === 'thematicBreak') {
42
+ if (current.body.length) parts.push(current)
43
+ current = { title: null, body: [] }
44
+ } else current.body.push(n)
45
+ }
46
+ if (current.body.length || !parts.length) parts.push(current)
47
+ return parts
48
+ }
49
+
50
+ /** A height in px (a bare number) or a CSS length; else none. */
51
+ const height = (value: string | undefined) =>
52
+ value && /^\d+(\.\d+)?$/.test(value)
53
+ ? `${value}px`
54
+ : value && /^\d+(\.\d+)?(px|em|rem|vh|svh|dvh)$/.test(value)
55
+ ? value
56
+ : undefined
57
+
58
+ const svg = (d: string) =>
59
+ raw(
60
+ `<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="${d}"/></svg>`,
61
+ )
62
+ const PREV = svg('M10 3.5 5.5 8l4.5 4.5')
63
+ const NEXT = svg('M6 3.5 10.5 8 6 12.5')
64
+
65
+ /** With this many items or fewer, all titled, the header shows their titles as tabs. */
66
+ const TABS = 4
67
+
68
+ export async function render(ctx: DirectiveContext) {
69
+ const parts = split(ctx.children as Node[])
70
+ const items = await Promise.all(
71
+ parts.map(async p => ({ title: p.title ? await ctx.toHtml(p.title) : null, html: await ctx.toHtml(p.body) })),
72
+ )
73
+ const tabs = !('count' in ctx.attrs) && items.length <= TABS && items.every(i => i.title)
74
+ const n = items.length
75
+ const marks = tabs
76
+ ? items.map(
77
+ (item, i) =>
78
+ html`<button type="button" class="wb-steps-tab wb-steps-mark" data-steps="${String(i)}">
79
+ ${raw(item.title!)}
80
+ </button>`,
81
+ )
82
+ : html`<span class="wb-steps-count">
83
+ ${items.map((_, i) => html`<span class="wb-steps-mark">${String(i + 1)} / ${String(n)}</span>`)}
84
+ </span>`
85
+ const controls = html`<span class="wb-steps-nav">
86
+ <button
87
+ type="button"
88
+ class="wb-window-button wb-steps-prev"
89
+ data-steps="prev"
90
+ title="Previous (←)"
91
+ aria-label="Previous"
92
+ >
93
+ ${PREV}
94
+ </button>
95
+ ${marks}
96
+ <button type="button" class="wb-window-button wb-steps-next" data-steps="next" title="Next (→)" aria-label="Next">
97
+ ${NEXT}
98
+ </button>
99
+ </span>`
100
+ const body = html`<div class="wb-steps" tabindex="0">
101
+ ${items.map(
102
+ item =>
103
+ html`<section class="wb-steps-item">
104
+ ${!tabs && item.title ? html`<div class="wb-steps-title">${raw(item.title)}</div>` : ''} ${raw(item.html)}
105
+ </section>`,
106
+ )}
107
+ </div>`
108
+ return windowFrame({
109
+ label: ctx.label,
110
+ className: 'wb-steps-window',
111
+ controls,
112
+ wide: 'wide' in ctx.attrs,
113
+ height: height(ctx.attrs.height),
114
+ body,
115
+ })
116
+ }
117
+
118
+ export default function steps(): Plugin {
119
+ return definePlugin({
120
+ name: 'steps',
121
+ public: builtinPublic('steps'),
122
+ style: 'style.css',
123
+ setup: () => ({ client: 'client.js' }),
124
+ blocks: { steps: { html: render } },
125
+ docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
126
+ })
127
+ }
@@ -0,0 +1,77 @@
1
+ /* Steps (index.ts): the items over each other in one grid cell, so the pane is as tall as the
2
+ tallest; one shows. Before the browser marks one (data-wb-step), the first. */
3
+ .wb-steps {
4
+ display: grid;
5
+ outline: none;
6
+ }
7
+ .wb-steps:focus-visible {
8
+ box-shadow: inset 0 0 0 2px color-mix(in srgb, var(--accent) var(--tint-strong), transparent);
9
+ }
10
+ .wb-steps > .wb-steps-item {
11
+ grid-area: 1 / 1;
12
+ min-width: 0;
13
+ }
14
+ .wb-steps > .wb-steps-item > :first-child {
15
+ margin-top: 0;
16
+ }
17
+ .wb-steps > .wb-steps-item > :last-child {
18
+ margin-bottom: 0;
19
+ }
20
+ .wb-steps-window:not([data-wb-step]) > .wb-window-body > .wb-steps > .wb-steps-item:not(:first-child),
21
+ .wb-steps-window[data-wb-step] > .wb-window-body > .wb-steps > .wb-steps-item:not([data-wb-current]) {
22
+ visibility: hidden;
23
+ }
24
+ .wb-steps-title {
25
+ font: var(--weight-strong) var(--ui-small) / var(--ui-line-height) var(--sans);
26
+ color: var(--muted);
27
+ letter-spacing: var(--caps-spacing);
28
+ text-transform: uppercase;
29
+ margin-bottom: var(--space-md);
30
+ }
31
+
32
+ /* the header: ‹ 2 / 5 › or ‹ A B › */
33
+ .wb-steps-nav {
34
+ display: flex;
35
+ align-items: center;
36
+ gap: var(--space-2xs);
37
+ flex: none;
38
+ }
39
+ .wb-steps-count {
40
+ font: var(--ui-tiny) / 1 var(--sans);
41
+ font-variant-numeric: tabular-nums;
42
+ color: var(--muted);
43
+ padding: 0 var(--space-2xs);
44
+ }
45
+ .wb-steps-window:not([data-wb-step]) > .wb-window-bar .wb-steps-count > .wb-steps-mark:not(:first-child),
46
+ .wb-steps-window[data-wb-step] > .wb-window-bar .wb-steps-count > .wb-steps-mark:not([data-wb-current]) {
47
+ display: none;
48
+ }
49
+ .wb-steps-tab {
50
+ font: var(--ui-tiny) / 1 var(--sans);
51
+ color: var(--muted);
52
+ background: none;
53
+ border: var(--hairline) solid transparent;
54
+ border-radius: var(--radius-pill);
55
+ padding: var(--space-xs) var(--space-md);
56
+ cursor: pointer;
57
+ white-space: nowrap;
58
+ }
59
+ .wb-steps-tab > * {
60
+ margin: 0;
61
+ }
62
+ .wb-steps-tab:hover {
63
+ color: var(--text);
64
+ background: color-mix(in srgb, var(--text) var(--tint-faint), transparent);
65
+ }
66
+ .wb-steps-window:not([data-wb-step]) > .wb-window-bar .wb-steps-tab:first-of-type,
67
+ .wb-steps-window > .wb-window-bar .wb-steps-tab[data-wb-current] {
68
+ color: var(--accent);
69
+ border-color: color-mix(in srgb, var(--accent) var(--tint-strong), transparent);
70
+ background: color-mix(in srgb, var(--accent) var(--tint-faint), transparent);
71
+ }
72
+ .wb-steps-window:not([data-wb-step]) > .wb-window-bar .wb-steps-prev,
73
+ .wb-steps-window[data-wb-first] > .wb-window-bar .wb-steps-prev,
74
+ .wb-steps-window[data-wb-last] > .wb-window-bar .wb-steps-next {
75
+ opacity: 0.35;
76
+ pointer-events: none;
77
+ }
@@ -40,9 +40,10 @@ import fs from 'node:fs'
40
40
  import net from 'node:net'
41
41
  import path from 'node:path'
42
42
  import { createRequire } from 'node:module'
43
+ import type * as NodePty from 'node-pty'
43
44
  import type { IPty } from 'node-pty'
44
- import type { Terminal as HeadlessTerminal } from '@xterm/headless'
45
- import type { SerializeAddon as Serializer } from '@xterm/addon-serialize'
45
+ import xtermHeadless, { type Terminal as HeadlessTerminal } from '@xterm/headless'
46
+ import xtermSerialize, { type SerializeAddon as Serializer } from '@xterm/addon-serialize'
46
47
  import { followMouseEncoding } from './modes.ts'
47
48
  import { handOver, lastUsed, leave, report, type Sizes } from './sizes.ts'
48
49
 
@@ -53,8 +54,12 @@ if (!dir || !socket) {
53
54
  process.exit(2)
54
55
  }
55
56
 
56
- /** node-pty. Its prebuilt helper ships without execute permission (1.1.0): add it. */
57
- function loadPty(): typeof import('node-pty') {
57
+ /**
58
+ * node-pty, loaded when a session starts rather than imported: a native module that may not load on
59
+ * this machine, which then is an error to report, not a host that fails to start. Its prebuilt
60
+ * helper ships without execute permission (1.1.0): add it.
61
+ */
62
+ function loadPty(): typeof NodePty {
58
63
  const pty = require('node-pty')
59
64
  const helper = path.join(
60
65
  path.dirname(require.resolve('node-pty/package.json')),
@@ -68,8 +73,9 @@ function loadPty(): typeof import('node-pty') {
68
73
  return pty
69
74
  }
70
75
 
71
- const { Terminal } = (await import('@xterm/headless')).default
72
- const { SerializeAddon } = (await import('@xterm/addon-serialize')).default
76
+ // CommonJS packages: their exports are the default's
77
+ const { Terminal } = xtermHeadless
78
+ const { SerializeAddon } = xtermSerialize
73
79
 
74
80
  /** A program in a pseudo-terminal, and the headless terminal that keeps its screen. */
75
81
  interface Session extends Sizes {
@@ -47,7 +47,9 @@ export function leave(s: Sizes, viewer: string): boolean {
47
47
  */
48
48
  export function handOver(s: Sizes, viewer: string): { cols: number; rows: number } | null {
49
49
  if (s.active !== viewer || s.viewers.has(viewer)) return null
50
- const next = [...s.viewers].sort((a, b) => b[1].used - a[1].used)[0]
50
+ // the one used last: the first of them, as a stable sort by `used` would give
51
+ let next: [string, { cols: number; rows: number; used: number }] | undefined
52
+ for (const viewer of s.viewers) if (!next || viewer[1].used > next[1].used) next = viewer
51
53
  s.active = next?.[0] ?? null
52
54
  return next ? { cols: next[1].cols, rows: next[1].rows } : null
53
55
  }
@@ -9,14 +9,32 @@ import toc from '@bigmistqke/whiteboard/toc'
9
9
  export default defineConfig({ plugins: [toc()] })
10
10
  ```
11
11
 
12
- A page has it when its frontmatter says `toc: true`:
12
+ A page has it when its frontmatter asks, under `plugins:` (where every
13
+ plugin's settings for a page go, by the plugin's name):
13
14
 
14
15
  ```markdown
15
16
  ---
16
- toc: true
17
+ plugins:
18
+ toc: true
17
19
  ---
18
20
  # A long page
19
21
  ```
20
22
 
21
23
  To have it on every page, `toc({ always: true })`; a page then goes without
22
- with `toc: false`.
24
+ with `toc: false` there.
25
+
26
+ The panel fits its items, between a minimum and a maximum width (160px and
27
+ 320px by default). A project sets its own in the options, and a page in its
28
+ frontmatter, which is then also how it asks for the contents:
29
+
30
+ ```ts
31
+ toc({ minWidth: 180, maxWidth: '24rem' }) // pixels, or a CSS length
32
+ ```
33
+
34
+ ```markdown
35
+ ---
36
+ plugins:
37
+ toc:
38
+ maxWidth: 240px
39
+ ---
40
+ ```
@@ -23,19 +23,58 @@ let headings: HTMLElement[] = []
23
23
 
24
24
  const navHeight = () => document.querySelector<HTMLElement>('.wb-nav')?.getBoundingClientRect().height ?? 0
25
25
 
26
- /** Is there room left of the text for the panel? Else it opens from the header. */
26
+ /** The gap between the panel and the text, and between the panel and the window's edge. */
27
+ const GAP = 40
28
+ const EDGE = 16
29
+
30
+ /** Is there room left of the text for the panel at its narrowest? Else it opens from the header. */
27
31
  function fits() {
32
+ const narrowest = parseFloat(getComputedStyle(panel).minWidth) || 0
33
+ return main.getBoundingClientRect().left >= narrowest + GAP + EDGE
34
+ }
35
+
36
+ /** A width as the settings or the options give it: a CSS length, or a number of pixels. */
37
+ const length = (value: unknown): string | null => {
38
+ const m = /^(\d+(?:\.\d+)?)(px|em|rem|ch|vw)?$/.exec(String(value ?? '').trim())
39
+ return m && Number(m[1]) > 0 ? m[1] + (m[2] ?? 'px') : null
40
+ }
41
+
42
+ /**
43
+ * How wide the panel may be: it fits its items, between a minimum and a maximum, which the page's
44
+ * settings can set (`plugins: { toc: { minWidth: 160px, maxWidth: 320px } }`), else the project's options.
45
+ */
46
+ function bounds() {
47
+ const meta = document.querySelector<HTMLMetaElement>('meta[name=wb-toc]')
48
+ const said = handle.settings()
49
+ const own = said && typeof said === 'object' ? (said as Record<string, unknown>) : {}
50
+ for (const [name, prop] of [
51
+ ['minWidth', '--wb-toc-min-width'],
52
+ ['maxWidth', '--wb-toc-max-width'],
53
+ ] as const) {
54
+ const value = length(own[name]) ?? length(meta?.dataset[name])
55
+ if (value) panel.style.setProperty(prop, value)
56
+ else panel.style.removeProperty(prop)
57
+ }
58
+ }
59
+
60
+ /** Docked: its right edge a gap left of the text, so a wider panel grows away from it. */
61
+ function place() {
28
62
  const left = main.getBoundingClientRect().left
29
- return left >= 230
63
+ panel.style.setProperty('--wb-toc-right', `${document.documentElement.clientWidth - left + GAP}px`)
64
+ panel.style.setProperty('--wb-toc-room', `${left - GAP - EDGE}px`)
30
65
  }
31
66
 
32
67
  let handle: PageHandle
33
68
 
34
- /** Does this page have it: what its frontmatter says (`toc:`), and whether it is on everywhere. */
69
+ /** Does this page have it: what its settings say, and whether it is on everywhere. */
35
70
  function wanted() {
36
- const said = handle.frontmatter().toc?.trim().toLowerCase()
71
+ // its settings (`plugins: { toc: … }`): true, or { minWidth, maxWidth }: on; false: off; else as
72
+ // the project says
73
+ const said = handle.settings()
37
74
  const always = document.querySelector('meta[name=wb-toc]')?.getAttribute('content') === 'always'
38
- return always ? said !== 'false' : said === 'true'
75
+ if (said === false) return false
76
+ if (said === true || (said && typeof said === 'object')) return true
77
+ return always
39
78
  }
40
79
 
41
80
  function build() {
@@ -60,6 +99,8 @@ function build() {
60
99
  }),
61
100
  )
62
101
  const any = headings.length > 1
102
+ bounds()
103
+ place()
63
104
  toggle.hidden = !any || fits()
64
105
  panel.hidden = !any || (!fits() && !panel.classList.contains('wb-toc-open'))
65
106
  panel.classList.toggle('wb-toc-docked', fits())
@@ -150,7 +191,7 @@ const mount: PluginMount = (root, page, core) => {
150
191
  addEventListener('scroll', soon(current), { passive: true })
151
192
  addEventListener('resize', soon(build))
152
193
  api.onRendered(build)
153
- page.frontmatter.on(build)
194
+ page.settings.on(build)
154
195
  api.forms.on(() => mark())
155
196
  api.events.on(() => requestAnimationFrame(mark))
156
197
  build()
@@ -6,9 +6,10 @@
6
6
  // import toc from '@bigmistqke/whiteboard/toc'
7
7
  // export default defineConfig({ plugins: [toc()] })
8
8
  //
9
- // A page has it when its frontmatter says `toc: true`. With `toc({ always: true })`, every page has
10
- // it, unless its frontmatter says `toc: false`.
9
+ // A page has it when its frontmatter says so, under `plugins:` (`plugins: { toc: true }`). With
10
+ // `toc({ always: true })`, every page has it, unless its frontmatter says `toc: false` there.
11
11
  import { builtinPublic } from '../../src/package.ts'
12
+ import { html } from '../../src/html.ts'
12
13
  import type { Plugin } from '../../src/define.ts'
13
14
 
14
15
  const DOCS = `## Table of contents
@@ -19,8 +20,12 @@ in it. A section with an unanswered question or an unread message has a dot.
19
20
  `
20
21
 
21
22
  export interface TocOptions {
22
- /** on every page, not only the ones whose frontmatter says `toc: true` (`toc: false` still goes without) */
23
+ /** on every page, not only the ones that ask (`plugins: { toc: true }`); `toc: false` there still goes without */
23
24
  always?: boolean
25
+ /** the panel fits its items, but never narrower than this: a CSS length, or pixels (default 160px) */
26
+ minWidth?: string | number
27
+ /** nor wider than this (default 320px); a page can say otherwise: `plugins: { toc: { maxWidth: 280px } }` */
28
+ maxWidth?: string | number
24
29
  }
25
30
 
26
31
  export default function toc(options: TocOptions = {}): Plugin {
@@ -28,15 +33,23 @@ export default function toc(options: TocOptions = {}): Plugin {
28
33
  name: 'toc',
29
34
  docs: () =>
30
35
  options.always
31
- ? DOCS + '\nIn this project every page has it; a page without it says `toc: false` in its frontmatter.\n'
36
+ ? DOCS +
37
+ '\nIn this project every page has it; a page goes without with `toc: false` under `plugins:` in its frontmatter:\n\n```markdown\n---\nplugins:\n toc: false\n---\n```\n'
32
38
  : DOCS +
33
- '\nA page has it when its frontmatter says `toc: true`:\n\n```markdown\n---\ntoc: true\n---\n# A long page\n```\n',
39
+ '\nA page has it when its frontmatter asks, under `plugins:`:\n\n```markdown\n---\nplugins:\n toc: true\n---\n# A long page\n```\n',
34
40
  public: builtinPublic('toc'),
35
41
  style: 'style.css',
36
42
  setup: () => ({
37
43
  client: 'client.js',
38
44
  // how the browser part knows: on every page, or only where the frontmatter asks
39
- shell: () => ({ head: `<meta name="wb-toc" content="${options.always ? 'always' : 'opt-in'}">` }),
45
+ shell: () => ({
46
+ head: html`<meta
47
+ name="wb-toc"
48
+ content="${options.always ? 'always' : 'opt-in'}"
49
+ ${options.minWidth != null ? html` data-min-width="${String(options.minWidth)}"` : ''}
50
+ ${options.maxWidth != null ? html` data-max-width="${String(options.maxWidth)}"` : ''}
51
+ />`,
52
+ }),
40
53
  }),
41
54
  }
42
55
  }