@bigmistqke/whiteboard 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +23 -216
  2. package/bin/whiteboard.ts +82 -239
  3. package/dist/bin/whiteboard.js +70 -200
  4. package/dist/client/runtime.js +297 -61
  5. package/dist/plugins/badge/README.md +3 -1
  6. package/dist/plugins/badge/public/style.css +17 -0
  7. package/dist/plugins/chat/public/client.js +2 -2
  8. package/dist/plugins/chat/public/style.css +19 -6
  9. package/dist/plugins/code/README.md +10 -0
  10. package/dist/plugins/code/index.js +31 -22
  11. package/dist/plugins/code/public/client.js +1 -0
  12. package/dist/plugins/code/public/style.css +33 -2
  13. package/dist/plugins/comments/public/client.js +7 -2
  14. package/dist/plugins/comments/public/style.css +4 -0
  15. package/dist/plugins/form/public/style.css +2 -0
  16. package/dist/plugins/grid/public/style.css +0 -5
  17. package/dist/plugins/iframe/index.js +2 -2
  18. package/dist/plugins/index.js +5 -1
  19. package/dist/plugins/lightbox/public/client.js +1 -1
  20. package/dist/plugins/terminal/index.js +7 -9
  21. package/dist/plugins/terminal/public/client.js +1 -1
  22. package/dist/plugins/terminal/public/style.css +3 -3
  23. package/dist/plugins/timeline/README.md +40 -0
  24. package/dist/plugins/timeline/index.js +82 -0
  25. package/dist/plugins/timeline/public/style.css +118 -0
  26. package/dist/plugins/toc/README.md +13 -13
  27. package/dist/plugins/toc/index.js +6 -4
  28. package/dist/plugins/toc/public/client.js +1 -1
  29. package/dist/plugins/toc/public/style.css +19 -2
  30. package/dist/plugins/window/index.js +4 -4
  31. package/dist/solid/index.js +2 -1
  32. package/dist/src/auth.js +7 -3
  33. package/dist/src/build.js +159 -0
  34. package/dist/src/client/page/base.css +74 -35
  35. package/dist/src/client/page/main.js +16 -5
  36. package/dist/src/document.js +93 -0
  37. package/dist/src/events.js +7 -15
  38. package/dist/src/hub.js +90 -53
  39. package/dist/src/listen.js +100 -0
  40. package/dist/src/listeners.js +67 -0
  41. package/dist/src/pages/index.js +1 -1
  42. package/dist/src/pages/markdown.js +23 -11
  43. package/dist/src/pages/render.js +13 -8
  44. package/dist/src/serve.js +2 -0
  45. package/dist/src/server.js +204 -514
  46. package/dist/src/site.js +173 -0
  47. package/dist/src/status.js +63 -1
  48. package/dist/src/ws.js +128 -0
  49. package/package.json +1 -1
  50. package/plugins/README.md +258 -0
  51. package/plugins/badge/README.md +3 -1
  52. package/plugins/badge/public/style.css +17 -0
  53. package/plugins/chat/client.tsx +34 -6
  54. package/plugins/chat/public/style.css +19 -6
  55. package/plugins/code/README.md +10 -0
  56. package/plugins/code/client.ts +73 -0
  57. package/plugins/code/index.ts +38 -26
  58. package/plugins/code/public/style.css +33 -2
  59. package/plugins/comments/client.ts +56 -6
  60. package/plugins/comments/public/style.css +4 -0
  61. package/plugins/form/public/style.css +2 -0
  62. package/plugins/grid/public/style.css +0 -5
  63. package/plugins/iframe/index.ts +2 -2
  64. package/plugins/index.ts +6 -1
  65. package/plugins/lightbox/client.ts +13 -3
  66. package/plugins/terminal/client.ts +10 -2
  67. package/plugins/terminal/index.ts +8 -6
  68. package/plugins/terminal/public/style.css +3 -3
  69. package/plugins/timeline/README.md +40 -0
  70. package/plugins/timeline/index.ts +92 -0
  71. package/plugins/timeline/public/style.css +118 -0
  72. package/plugins/toc/README.md +13 -13
  73. package/plugins/toc/client.ts +58 -32
  74. package/plugins/toc/index.ts +13 -13
  75. package/plugins/toc/public/style.css +19 -2
  76. package/plugins/window/index.ts +4 -4
  77. package/skills/whiteboard/SKILL.md +3 -1
  78. package/solid/index.tsx +3 -0
  79. package/src/auth.ts +7 -2
  80. package/src/build.ts +213 -0
  81. package/src/client/forms.ts +102 -5
  82. package/src/client/page/base.css +74 -35
  83. package/src/client/page/elsewhere.ts +14 -4
  84. package/src/client/page/waiting.ts +10 -5
  85. package/src/client/read.ts +16 -3
  86. package/src/client/runtime.ts +219 -52
  87. package/src/client/toast.ts +36 -6
  88. package/src/define.ts +44 -18
  89. package/src/document.ts +191 -0
  90. package/src/events.ts +18 -17
  91. package/src/hub.ts +102 -56
  92. package/src/listen.ts +125 -0
  93. package/src/listeners.ts +95 -0
  94. package/src/pages/index.ts +1 -1
  95. package/src/pages/markdown.ts +29 -18
  96. package/src/pages/render.ts +13 -8
  97. package/src/serve.ts +2 -0
  98. package/src/server.ts +223 -611
  99. package/src/site.ts +165 -0
  100. package/src/status.ts +100 -0
  101. package/src/ws.ts +155 -0
@@ -0,0 +1,173 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { parse } from "yaml";
4
+ // src/site.ts
5
+ /** Folders never shown or served: what a repository keeps for its tools. */
6
+ const SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
7
+ /** A page's frontmatter: YAML between `---` lines, at the very start. */
8
+ const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/;
9
+ /** Is `file` the folder `dir` or inside it? */
10
+ const within = (file, dir) => file === dir || file.startsWith(dir + path.sep);
11
+ /** Resolve a path inside a base folder, refusing anything that escapes it. */
12
+ function inside(base, rel) {
13
+ const p = path.resolve(base, "." + path.posix.normalize("/" + rel));
14
+ return within(p, base) ? p : null;
15
+ }
16
+ /** A page's frontmatter, parsed as YAML; empty, with the reason, when it isn't fields. */
17
+ function parseFrontmatter(source) {
18
+ const m = FRONTMATTER.exec(source);
19
+ if (!m) return {
20
+ data: {},
21
+ error: null
22
+ };
23
+ let data;
24
+ try {
25
+ data = parse(m[1]);
26
+ } catch (err) {
27
+ return {
28
+ data: {},
29
+ error: err.message
30
+ };
31
+ }
32
+ if (data == null) return {
33
+ data: {},
34
+ error: null
35
+ };
36
+ if (typeof data !== "object" || Array.isArray(data)) return {
37
+ data: {},
38
+ error: "it must be fields (`key: value` lines), not a single value or a list"
39
+ };
40
+ return {
41
+ data,
42
+ error: null
43
+ };
44
+ }
45
+ /** A markdown file as a page: its source, the body after its frontmatter, and the frontmatter parsed. */
46
+ function pageSource(id, file) {
47
+ const source = fs.readFileSync(file, "utf8");
48
+ const { data, error } = parseFrontmatter(source);
49
+ return {
50
+ kind: "page",
51
+ id,
52
+ file,
53
+ mtime: fs.statSync(file).mtimeMs,
54
+ source,
55
+ body: source.replace(FRONTMATTER, ""),
56
+ frontmatter: data,
57
+ frontmatterError: error
58
+ };
59
+ }
60
+ /** Text files show as files; anything with a NUL byte near the start is binary. */
61
+ function isText(file) {
62
+ const fd = fs.openSync(file, "r");
63
+ const buf = Buffer.alloc(8192);
64
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
65
+ fs.closeSync(fd);
66
+ return !buf.subarray(0, n).includes(0);
67
+ }
68
+ /** A repository file's id: `-/` and its path in the project (`-` for the project's folder). */
69
+ const isRepoId = (id) => id === "-" || id.startsWith("-/");
70
+ /**
71
+ * The project as its server serves it, below `base`. `files()` says whether it serves the project's
72
+ * own files (`-/…`), which the config can change while it runs.
73
+ */
74
+ function servedSite(project, { base, files }) {
75
+ function pagesIn(dir) {
76
+ const out = [];
77
+ const walk = (d) => {
78
+ if (!fs.existsSync(d)) return;
79
+ for (const ent of fs.readdirSync(d, { withFileTypes: true })) {
80
+ if (ent.name.startsWith(".") || ent.name === "node_modules") continue;
81
+ const full = path.join(d, ent.name);
82
+ if (ent.isDirectory()) walk(full);
83
+ else if (ent.name.endsWith(".md")) {
84
+ const id = path.relative(project.pagesDir, full).split(path.sep).join("/").replace(/\.md$/, "");
85
+ out.push({
86
+ id,
87
+ file: full,
88
+ mtime: fs.statSync(full).mtimeMs,
89
+ lastEvent: null,
90
+ awaiting: 0
91
+ });
92
+ }
93
+ }
94
+ };
95
+ walk(dir);
96
+ return out.sort((a, b) => b.mtime - a.mtime);
97
+ }
98
+ function page(id) {
99
+ if (!id) return {
100
+ kind: "pages",
101
+ id: "",
102
+ file: project.pagesDir,
103
+ mtime: null,
104
+ pages: pagesIn(project.pagesDir)
105
+ };
106
+ if (isRepoId(id)) {
107
+ const target = inside(project.dir, id.slice(2));
108
+ if (!target || path.relative(project.dir, target).split(path.sep).includes(".git") || !fs.existsSync(target)) return null;
109
+ const stat = fs.statSync(target);
110
+ if (stat.isDirectory()) {
111
+ const entries = fs.readdirSync(target, { withFileTypes: true }).filter((e) => !SKIP_DIRS.has(e.name) && e.name !== ".DS_Store").map((e) => ({
112
+ name: e.name,
113
+ dir: e.isDirectory()
114
+ })).sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name));
115
+ return {
116
+ kind: "folder",
117
+ id,
118
+ file: target,
119
+ mtime: stat.mtimeMs,
120
+ entries
121
+ };
122
+ }
123
+ if (/\.(md|markdown)$/i.test(target)) return pageSource(id, target);
124
+ if (stat.size > 1e6 || !isText(target)) return { raw: target };
125
+ return {
126
+ kind: "file",
127
+ id,
128
+ file: target,
129
+ mtime: stat.mtimeMs,
130
+ source: fs.readFileSync(target, "utf8")
131
+ };
132
+ }
133
+ const target = inside(project.pagesDir, id);
134
+ if (!target) return null;
135
+ if (path.extname(id) && fs.existsSync(target) && fs.statSync(target).isFile()) return { raw: target };
136
+ if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
137
+ const index = path.join(target, "index.md");
138
+ if (fs.existsSync(index)) return pageSource(id, index);
139
+ return {
140
+ kind: "pages",
141
+ id,
142
+ file: target,
143
+ mtime: null,
144
+ pages: pagesIn(target)
145
+ };
146
+ }
147
+ const file = target + ".md";
148
+ return fs.existsSync(file) ? pageSource(id, file) : null;
149
+ }
150
+ function urlOf(abs) {
151
+ const rel = (dir) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join("/");
152
+ if (within(abs, project.pagesDir)) return `${base}/${rel(project.pagesDir).replace(/\.md$/, "")}`;
153
+ if (files() && within(abs, project.dir)) {
154
+ if (rel(project.dir).split("/").some((part) => SKIP_DIRS.has(part))) return null;
155
+ return `${base}/-/${rel(project.dir)}`;
156
+ }
157
+ return null;
158
+ }
159
+ function urlFor(abs) {
160
+ for (const candidate of [abs, abs + ".md"]) if (fs.existsSync(candidate)) {
161
+ const url = urlOf(candidate);
162
+ if (url) return url + (fs.statSync(candidate).isDirectory() && !url.endsWith("/") ? "/" : "");
163
+ }
164
+ return null;
165
+ }
166
+ return {
167
+ page,
168
+ pagesIn,
169
+ urlOf,
170
+ urlFor
171
+ };
172
+ }
173
+ export { FRONTMATTER, SKIP_DIRS, inside, isRepoId, pageSource, parseFrontmatter, servedSite, within };
@@ -36,6 +36,12 @@ const heard = (name, listeners) => listeners.some((l) => !l.fallback && (l.type
36
36
  /** The type of the event the page appends once messages were in view: `{ ids }`. */
37
37
  const READ = "whiteboard:read";
38
38
  /**
39
+ * The type of the event `whiteboard scroll` appends: show the reader a place on a page, `{ to }`. A
40
+ * page applies the latest one that came after it loaded, as it comes or once its live channel is
41
+ * back.
42
+ */
43
+ const SCROLL = "whiteboard:scroll";
44
+ /**
39
45
  * The agent's messages on a page the reader hasn't read: events from the agent of a type
40
46
  * `isMessage` says is for the reader, not named by a `whiteboard:read` from the reader, and not
41
47
  * replaced by a later one (`replaces`).
@@ -51,6 +57,62 @@ function unreadMessages(events, isMessage) {
51
57
  }
52
58
  /** How many things on a page wait for the reader: its open questions and unread messages. */
53
59
  const awaiting = (p) => p.open.length + p.unread.length;
60
+ /** The type of the event that says another event was handed to an agent: `{ event: <its id> }`. */
61
+ const PICKED = "whiteboard:picked";
62
+ /**
63
+ * The type of the event `whiteboard new` appends when an agent session creates a page:
64
+ * `{ session }`. The colon keeps it apart from form names, which are event types too.
65
+ */
66
+ const CLAIM = "whiteboard:claim";
67
+ /** The ids of the events that were picked up. Only the command line's picks count. */
68
+ function pickedUp(events) {
69
+ return new Set(events.filter((e) => e.type === "whiteboard:picked" && !fromReader(e)).map((e) => String(e.data?.event)));
70
+ }
71
+ /**
72
+ * A project's status from its pages, its log and who listens: per page its questions and where each
73
+ * stands, what is open and unheard, the agent's messages unread, the reader's events not picked up,
74
+ * and who listens; which events were picked up; when each page was last answered. The log is
75
+ * gone through once.
76
+ */
77
+ function projectStatus({ pages, events, listeners, forAgent, forReader }) {
78
+ const picked = pickedUp(events);
79
+ const byPage = /* @__PURE__ */ new Map();
80
+ const owner = /* @__PURE__ */ new Map();
81
+ const last = /* @__PURE__ */ new Map();
82
+ for (const e of events) {
83
+ let list = byPage.get(e.page);
84
+ if (!list) byPage.set(e.page, list = []);
85
+ list.push(e);
86
+ if (fromReader(e)) last.set(e.page, e.ts);
87
+ else if (e.type === "whiteboard:claim") owner.set(e.page, e.data?.session ?? null);
88
+ }
89
+ return {
90
+ picked,
91
+ lastAnswered: (page) => last.get(page) ?? null,
92
+ pages: pages.map((p) => {
93
+ const own = byPage.get(p.id) ?? [];
94
+ const listening = listeners(p.id);
95
+ const questions = p.asks.map((name) => ({
96
+ name,
97
+ state: questionState(name, own, listening, (id) => picked.has(id)).state
98
+ }));
99
+ const open = questions.filter((q) => q.state === "open").map((q) => q.name);
100
+ return {
101
+ page: p.id,
102
+ title: p.title,
103
+ file: p.file,
104
+ owner: owner.get(p.id) ?? null,
105
+ asks: p.asks,
106
+ questions,
107
+ open,
108
+ unheard: open.filter((name) => !heard(name, listening)),
109
+ unread: unreadMessages(own, forReader),
110
+ unpicked: own.filter((e) => fromReader(e) && forAgent(e.type) && !picked.has(e.id)),
111
+ listeners: listening
112
+ };
113
+ })
114
+ };
115
+ }
54
116
  /**
55
117
  * What is open on a page, one short line each; the command that picks it up comes last, once.
56
118
  * `file` is how to name the page's file to the reader (relative to where they are). Without
@@ -68,4 +130,4 @@ function statusLines(p, file, { waiting = true } = {}) {
68
130
  }
69
131
  /** Whose a page is, said to `session`: yours, another session's, or nobody's. */
70
132
  const whose = (p, session) => p.owner && p.owner === session ? "yours" : p.owner ? `session ${p.owner.slice(0, 8)}` : "no session";
71
- export { READ, awaiting, covers, fromReader, heard, isQuestionName, questionState, statusLines, takenByOther, unreadMessages, whose };
133
+ export { CLAIM, PICKED, READ, SCROLL, awaiting, covers, fromReader, heard, isQuestionName, pickedUp, projectStatus, questionState, statusLines, takenByOther, unreadMessages, whose };
package/dist/src/ws.js ADDED
@@ -0,0 +1,128 @@
1
+ import crypto from "node:crypto";
2
+ // src/ws.ts
3
+ const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
4
+ const PING_EVERY = 25e3;
5
+ /** Is this request asking to become a WebSocket? */
6
+ const isUpgrade = (req) => (req.headers.upgrade ?? "").toLowerCase() === "websocket" && !!req.headers["sec-websocket-key"];
7
+ /** Answer the handshake and give the socket; null (and the connection refused) if it isn't one. */
8
+ function accept(req, conn) {
9
+ const key = req.headers["sec-websocket-key"];
10
+ if (!isUpgrade(req) || typeof key !== "string" || req.headers["sec-websocket-version"] !== "13") {
11
+ refuse(conn, 400, "Bad Request");
12
+ return null;
13
+ }
14
+ const hash = crypto.createHash("sha1").update(key + GUID).digest("base64");
15
+ conn.write(`HTTP/1.1 101 Switching Protocols\r
16
+ Upgrade: websocket\r
17
+ Connection: Upgrade\r
18
+ Sec-WebSocket-Accept: ${hash}\r\n\r\n`);
19
+ if ("setNoDelay" in conn && typeof conn.setNoDelay === "function") conn.setNoDelay(true);
20
+ let open = true;
21
+ const closers = [];
22
+ const ended = () => {
23
+ if (!open) return;
24
+ open = false;
25
+ clearInterval(ping);
26
+ for (const fn of closers.splice(0)) fn();
27
+ };
28
+ const write = (opcode, payload) => {
29
+ if (!open || conn.destroyed) return;
30
+ conn.write(Buffer.concat([header(opcode, payload.length), payload]));
31
+ };
32
+ let alive = true;
33
+ const ping = setInterval(() => {
34
+ if (!alive) return void conn.destroy();
35
+ alive = false;
36
+ write(9, Buffer.alloc(0));
37
+ }, PING_EVERY);
38
+ ping.unref?.();
39
+ let buf = Buffer.alloc(0);
40
+ conn.on("data", (chunk) => {
41
+ buf = Buffer.concat([buf, chunk]);
42
+ for (;;) {
43
+ const frame = parse(buf);
44
+ if (!frame) break;
45
+ buf = buf.subarray(frame.size);
46
+ alive = true;
47
+ if (frame.opcode === 8) {
48
+ write(8, frame.payload.subarray(0, 2));
49
+ ended();
50
+ conn.end();
51
+ return;
52
+ }
53
+ if (frame.opcode === 9) write(10, frame.payload);
54
+ }
55
+ if (buf.length > 1 << 20) conn.destroy();
56
+ });
57
+ conn.on("close", ended);
58
+ conn.on("error", () => conn.destroy());
59
+ return {
60
+ send: (text) => write(1, Buffer.from(text, "utf8")),
61
+ close() {
62
+ if (!open) return;
63
+ write(8, Buffer.from([3, 232]));
64
+ ended();
65
+ conn.end();
66
+ setTimeout(() => conn.destroy(), 1e3).unref?.();
67
+ },
68
+ onClose(fn) {
69
+ if (open) closers.push(fn);
70
+ else fn();
71
+ }
72
+ };
73
+ }
74
+ /** Turn an upgrade down with a plain HTTP response. */
75
+ function refuse(conn, status, text) {
76
+ if (conn.destroyed) return;
77
+ conn.end(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
78
+ }
79
+ /** A frame's header, unmasked as the server sends them, FIN set. */
80
+ function header(opcode, length) {
81
+ if (length < 126) return Buffer.from([128 | opcode, length]);
82
+ if (length < 65536) {
83
+ const h = Buffer.alloc(4);
84
+ h[0] = 128 | opcode;
85
+ h[1] = 126;
86
+ h.writeUInt16BE(length, 2);
87
+ return h;
88
+ }
89
+ const h = Buffer.alloc(10);
90
+ h[0] = 128 | opcode;
91
+ h[1] = 127;
92
+ h.writeBigUInt64BE(BigInt(length), 2);
93
+ return h;
94
+ }
95
+ /** One whole frame at the start of `buf` (unmasked), or null while it hasn't all arrived. */
96
+ function parse(buf) {
97
+ if (buf.length < 2) return null;
98
+ const opcode = buf[0] & 15;
99
+ const masked = (buf[1] & 128) !== 0;
100
+ let length = buf[1] & 127;
101
+ let at = 2;
102
+ if (length === 126) {
103
+ if (buf.length < 4) return null;
104
+ length = buf.readUInt16BE(2);
105
+ at = 4;
106
+ } else if (length === 127) {
107
+ if (buf.length < 10) return null;
108
+ const big = buf.readBigUInt64BE(2);
109
+ if (big > BigInt(1 << 20)) return {
110
+ opcode: 8,
111
+ payload: Buffer.alloc(0),
112
+ size: buf.length
113
+ };
114
+ length = Number(big);
115
+ at = 10;
116
+ }
117
+ const mask = masked ? buf.subarray(at, at + 4) : null;
118
+ if (masked) at += 4;
119
+ if (buf.length < at + length) return null;
120
+ const payload = Buffer.from(buf.subarray(at, at + length));
121
+ if (mask) for (let i = 0; i < payload.length; i++) payload[i] = payload[i] ^ mask[i % 4];
122
+ return {
123
+ opcode,
124
+ payload,
125
+ size: at + length
126
+ };
127
+ }
128
+ export { accept, isUpgrade, refuse };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bigmistqke/whiteboard",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
4
4
  "description": "A whiteboard for you and your agent: it writes markdown pages you read live in the browser, you answer through forms it waits on",
5
5
  "keywords": [
6
6
  "agent",
@@ -0,0 +1,258 @@
1
+ # Writing a plugin
2
+
3
+ How to extend whiteboard. The plugins in this folder are the built-in ones,
4
+ and the best examples: each one's `README.md` is what `whiteboard docs` tells
5
+ an agent writing pages; this file is for writing a plugin of your own.
6
+
7
+ Everything that extends whiteboard is a plugin: syntax for pages,
8
+ behaviour on every page, commands, events. A plugin is an object with a
9
+ name, and everything it adds lives under that name, so two plugins can't
10
+ collide: its block `:::name`, its events `name:…`, its command
11
+ `whiteboard name`, its routes `/api/name/…` and its data folder
12
+ `.whiteboard/name/`. Local plugins go in `.whiteboard/plugins/`.
13
+
14
+ ## A block: a checklist the reader ticks
15
+
16
+ A block is syntax: `:::name` around content, `::name` on a line, `:name`
17
+ inside a line, or a code fence of that name. It renders on the server, and
18
+ with a `client` it is mounted in the browser too.
19
+
20
+ ```ts
21
+ // .whiteboard/plugins/checklist/index.ts
22
+ import { definePlugin, html, type DirectiveContext } from '@bigmistqke/whiteboard'
23
+
24
+ const toText = (node: any): string => node.value ?? (node.children ?? []).map(toText).join('')
25
+
26
+ export default function checklist() {
27
+ return definePlugin({
28
+ name: 'checklist',
29
+ blocks: {
30
+ checklist: {
31
+ // what the browser part gets: the block's list items as text
32
+ props: ctx => {
33
+ const c = ctx as DirectiveContext // a block (`:::checklist`), not a code fence
34
+ return {
35
+ name: c.attrs.name ?? 'checklist',
36
+ items: (c.children as any[]).filter(n => n.type === 'list')
37
+ .flatMap(list => list.children.map((item: any) => toText(item))),
38
+ }
39
+ },
40
+ // shown until the client mounts, then replaced
41
+ html: () => html`<ul class="checklist"></ul>`,
42
+ client: 'client.js', // in its public/ folder
43
+ },
44
+ },
45
+ // its events, and whether a `wait` on the page hands them out (a tick is information: no)
46
+ events: { 'checklist:tick': { description: '`{ checklist, item, checked }`' } },
47
+ // for `whiteboard docs`, under a `# Plugin: checklist` heading the core adds
48
+ docs: () => 'A list the reader ticks:\n\n :::checklist{name=launch}\n - Write the changelog\n :::\n',
49
+ })
50
+ }
51
+ ```
52
+
53
+ ```js
54
+ // .whiteboard/plugins/checklist/public/client.js: its public/ folder is served, nothing else of it
55
+ export default function mount(el, { name, items }, api) {
56
+ const ticked = () => {
57
+ const state = new Map()
58
+ for (const e of api.events()) if (e.type === 'checklist:tick' && e.data.checklist === name) state.set(e.data.item, e.data.checked)
59
+ return state
60
+ }
61
+ const draw = () => {
62
+ const state = ticked()
63
+ el.replaceChildren(...items.map(item => {
64
+ const box = Object.assign(document.createElement('input'), { type: 'checkbox', checked: !!state.get(item) })
65
+ box.addEventListener('change', () => api.append('checklist:tick', { checklist: name, item, checked: box.checked }))
66
+ const label = document.createElement('label')
67
+ label.append(box, ' ', item)
68
+ return label
69
+ }))
70
+ }
71
+ draw()
72
+ // the page's events, also the ones it appends itself, come back here
73
+ return api.events.on(draw)
74
+ }
75
+ ```
76
+
77
+ ```ts
78
+ // .whiteboard/config.ts
79
+ import { defineConfig } from '@bigmistqke/whiteboard'
80
+ import checklist from './plugins/checklist/index.ts'
81
+
82
+ export default defineConfig({ plugins: [checklist()] })
83
+ ```
84
+
85
+ An agent can wait for a tick by asking for it: `whiteboard wait --page
86
+ <file> --type checklist:tick`.
87
+
88
+ ## Behaviour on every page: votes
89
+
90
+ A plugin can also put something on every page, and add commands:
91
+
92
+ ```ts
93
+ // .whiteboard/plugins/votes/index.ts
94
+ import { definePlugin } from '@bigmistqke/whiteboard'
95
+ import { read } from '@bigmistqke/whiteboard/log'
96
+
97
+ export default function votes() {
98
+ return definePlugin({
99
+ name: 'votes',
100
+ events: { 'votes:up': { description: 'the reader voted the page up' } },
101
+ commands: {
102
+ '': {
103
+ description: 'print the votes per page',
104
+ run(ctx) {
105
+ const counts = new Map<string, number>()
106
+ for (const e of read(ctx.eventsFile).events) if (e.type === 'votes:up') counts.set(e.page, (counts.get(e.page) ?? 0) + 1)
107
+ for (const [page, n] of counts) console.log(`${page}: ${n}`)
108
+ },
109
+ },
110
+ },
111
+ docs: () => 'The reader can vote a page up: a `votes:up` event. `whiteboard votes` counts them.',
112
+ // from setup: what the running server adds (routes, what it puts in its slots, the browser module)
113
+ setup: () => ({ client: 'client.js' }),
114
+ })
115
+ }
116
+ ```
117
+
118
+ ```js
119
+ // .whiteboard/plugins/votes/public/client.js
120
+ export default function mount(root, page, api) {
121
+ const button = document.createElement('button')
122
+ const draw = () => { button.textContent = `👍 ${api.events().filter(e => e.type === 'votes:up').length}` }
123
+ button.addEventListener('click', () => api.append('votes:up'))
124
+ api.slot('corner', el => { // its own element in the page's corner, for floating buttons
125
+ el.append(button)
126
+ return () => button.remove()
127
+ })
128
+ api.events.on(draw)
129
+ draw()
130
+ }
131
+ ```
132
+
133
+ ## What a plugin can have
134
+
135
+ - **`blocks`**, by name. A block has `html(ctx)` (the server's HTML; `ctx`
136
+ has the block's attributes, label, content as mdast nodes, `toHtml`,
137
+ `items()`, `fileUrl(src)` for the address of a file beside the page, and
138
+ more), `props(ctx)` (JSON for its client), `client` (a
139
+ browser module, mounted per block), `style` (linked on pages that use it),
140
+ `fence: true` to also take the code fences of its name (```` ```mermaid ````),
141
+ `fence: 'any'` for the block that takes every code fence nobody else
142
+ claims, and `open(ctx)`: what it shows on its own, for a window around it.
143
+ Block names are unique across a project's plugins.
144
+ - **`compose(ctx)`**: itself around any block that names the plugin in its
145
+ `compose` attribute, that block's HTML as `ctx.children` (see below).
146
+ - **`events`**, by type (`<plugin>:<what>`): a description each, and
147
+ `handOut: true` for those an agent should get unasked, like a chat
148
+ message. `whiteboard docs` lists them.
149
+ - **`style`**: a stylesheet on every page.
150
+ - **`docs`**: markdown for agents: how to write its blocks, what its events
151
+ mean, how to answer.
152
+ - **`commands`**: `whiteboard <name>` and `whiteboard <name> <sub>`, with
153
+ declared options that the core parses and checks. A command gets the
154
+ project, its event log (`ctx.eventsFile`, for
155
+ `@bigmistqke/whiteboard/log`), its token and server, what is open on each
156
+ page (`ctx.status`), and handing out (`ctx.handOut`, what `wait` does).
157
+ - **`session()`**: the agent session a command runs in, for a plugin that
158
+ knows how its agent says so.
159
+ - **`setup(ctx)`**, which runs once per loaded config on the server and
160
+ returns:
161
+ - `routes`, by method and path (`'POST /start'` is mounted at
162
+ `/api/<name>/start`), each with what it does, whether it needs the
163
+ project's token (`auth`), and the types of its body and query; the core
164
+ checks all of that before the route's code runs;
165
+ - `slots`, markup for its element in the page's slots, there on the first
166
+ render (see below), and `head` for `<head>`;
167
+ - `client`, a module on every page, run once per page load.
168
+
169
+ **A plugin puts what it adds to the page in slots**, places the core owns:
170
+ `header` (the header bar, before the theme button), `aside` (a panel beside
171
+ the text), `bottom` (a drawer the page makes room for), `overlay` (over the
172
+ page) and `corner` (floating buttons and toasts). Each plugin has its own
173
+ element in each. Its `slots(req)` can render markup into them on the server,
174
+ so it is there on the first paint; its browser module mounts on its element
175
+ with `api.slot('bottom', el => unmount)`, handed to it whether the server
176
+ filled it or not, and what the mount returns runs when the element is taken
177
+ away. A plugin never looks the element up, and its markup names no
178
+ addresses: it names its files (`client`, `style`) and the core makes them.
179
+
180
+ ```ts
181
+ // server: the drawer, there on the first render
182
+ setup: () => ({
183
+ client: 'client.js',
184
+ slots: () => ({ bottom: html`<aside class="drawer">…</aside>` }),
185
+ }),
186
+
187
+ // browser (client.js): mounts on it
188
+ export default (root, page, api) =>
189
+ api.slot('bottom', el => {
190
+ const drawer = open(el.firstElementChild)
191
+ return () => drawer.close()
192
+ })
193
+ ```
194
+
195
+ **A plugin can compose itself around other blocks.** With `compose`, a
196
+ block whose `compose` attribute names the plugin is put in what it returns,
197
+ the block's HTML as `children`, as a component gets what it wraps. The
198
+ window plugin is one: `::image{src compose=window}`, ```` ```mermaid {compose=window} ````
199
+ and `:::grid{compose=window}` all go in a window, and none of those blocks
200
+ knows of windows. A block says what it shows on its own with `open` (an
201
+ image's file), which a window's ↗ opens. Several named compose in the order
202
+ written, the first innermost: `compose=lightbox,window`. A name no plugin
203
+ composes is said in place.
204
+
205
+ ```ts
206
+ definePlugin({
207
+ name: 'window',
208
+ compose: ({ children, label, open }) => windowFrame({ label, open, body: children }),
209
+ })
210
+ ```
211
+
212
+ **A plugin's browser files live in its `public/` folder**, and only that
213
+ folder is served: its client modules, styles, images and fonts, never its
214
+ server code or the project's files beside it. `client` and `style` (a
215
+ plugin's and a block's) name files in it: `'client.js'`. `definePlugin` puts
216
+ it next to the module that calls it (`plugins/checklist/public/` for
217
+ `plugins/checklist/index.ts`); say another with `public: new URL('./assets/',
218
+ import.meta.url)`; a plain object plugin, or one written in the config, has
219
+ `.whiteboard/public/`. A file named outside it is a config error. Browser
220
+ code is JavaScript or TypeScript: a `.ts` file is served with its types
221
+ stripped (Node's type stripping, as for server code: types only, so no
222
+ `enum` or `namespace`, and imports name their `.ts` files). JSX still needs
223
+ building first. A block's `client` gets
224
+ `mount(element, props, api)` and may return a cleanup, run when the block
225
+ is replaced on a live update; it replaces the server's HTML when it mounts.
226
+ A page module (`setup`'s `client`) gets `mount(root, page, api)`. Both get
227
+ the page's `api`: its `events` and `append` (which comes back through
228
+ `events.on`), the `listeners`, `forms` and `unread` messages, `onRendered`
229
+ (after a live update, to put back what it adds), the page's `frontmatter`
230
+ on the page handle (YAML, as parsed) and the plugin's own `settings` in it
231
+ (under `plugins:` by its name: `plugins: { toc: true }` is `true` for toc), `slot()` for its elements in the page's slots, `toast()` for a label in
232
+ the corner that says what is going on and goes there (one that hides after a
233
+ few seconds, or one that stays with a count), `badge()` for counts in the
234
+ tab title, the `theme`, and `url(path)`: the address of one of the
235
+ project's server routes as this page requests it (`api.url('/api/votes/count')`).
236
+ Ask for the plugin's routes through it rather than writing `/api/…`: under a
237
+ shared server a project is served below a path (`/rg/develop`). Every value
238
+ that changes is called for what it
239
+ is now and has `.on(fn)` for each change: `api.events()`,
240
+ `api.events.on(draw)`, `page.frontmatter.on(…)`. Files beside a browser module that are browser
241
+ assets (scripts, styles, images, fonts) are served too.
242
+
243
+ Something that covers the bottom of the window says how much in
244
+ `--wb-inset-bottom`, and the page keeps clear of it. A plugin can't be
245
+ named like a built-in command or a folder of the core.
246
+
247
+ ## Patterns in the built-in plugins
248
+
249
+ | want | look at |
250
+ | --- | --- |
251
+ | a block with a browser part | `checklist` above; `steps/` |
252
+ | a block around other blocks (`compose`) | `window/`, `lightbox/` |
253
+ | markup there on the first paint, a drawer the page makes room for (`bottom`) | `terminal/` |
254
+ | a button in the header bar and a panel beside the text (`header`, `aside`) | `toc/` |
255
+ | things over the page, placed in document coordinates (`overlay`) | `comments/` |
256
+ | a browser module that works on every page's content | `code/` (measures code blocks), `lightbox/` |
257
+ | events an agent gets, answered in place | `chat/`, `comments/` |
258
+ | commands and routes | `terminal/` (both), `claude-code/` (commands) |
@@ -15,7 +15,9 @@ green, `active new info` blue, `open todo maybe warning` amber,
15
15
  The release is :badge[blocked] on review.
16
16
  ```
17
17
 
18
- A grid card whose heading ends in a badge shows it at the card's right edge.
18
+ A badge that ends a heading sits at its right edge: a page's heading, a grid
19
+ card's, a timeline step's. A block of your own can have the same for a title
20
+ that isn't a heading, with a `data-wb-title` attribute on it.
19
21
 
20
22
  ### Parser :badge[done]
21
23
 
@@ -28,3 +28,20 @@
28
28
  .wb-badge:is([data-badge='blocked'], [data-badge='no'], [data-badge='bad'], [data-badge='error']) {
29
29
  --c: var(--bad);
30
30
  }
31
+
32
+ /* a badge that ends a title sits at its right edge, centred on its first line: in any heading,
33
+ and in anything a block marks as a title (data-wb-title: a timeline's step). --wb-title-line is
34
+ the title's line height in px (registered, so 1lh resolves on the title, not on the badge) */
35
+ @property --wb-title-line {
36
+ syntax: '<length>';
37
+ inherits: true;
38
+ initial-value: 0px;
39
+ }
40
+ :is(h1, h2, h3, h4, h5, h6, [data-wb-title]):has(> .wb-badge:last-child) {
41
+ --wb-title-line: 1lh;
42
+ }
43
+ :is(h1, h2, h3, h4, h5, h6, [data-wb-title]) > .wb-badge:last-child {
44
+ float: right;
45
+ margin: calc(var(--wb-title-line) / 2 - 0.5em) 0 0 var(--space-lg);
46
+ vertical-align: baseline;
47
+ }