@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,71 @@
1
+ // src/status.ts
2
+ /**
3
+ * Can this be a question's name, the type of its answers? Not with a colon: types with one belong
4
+ * to whiteboard (`whiteboard:picked`) or a plugin (`comments:reply`, `chat:message`),
5
+ * named after its owner, so a form's answers never mix with their events.
6
+ */
7
+ const isQuestionName = (name) => !!name && !name.includes(":");
8
+ /**
9
+ * Was this event written by the reader (a form submit, a comment), not by an agent? Agents write
10
+ * through the command line, which marks its events `from: 'cli'`: an agent's reply, a claim, a pick.
11
+ */
12
+ const fromReader = (event) => event.from !== "cli";
13
+ /** Does a listener's page filter cover `page`? An empty filter covers every page. */
14
+ const covers = (l, page) => !l.page || page === l.page || page.startsWith(l.page + "/");
15
+ /**
16
+ * Would a listener other than the fallback take this event, by its page and type? What the
17
+ * fallback leaves to it.
18
+ */
19
+ const takenByOther = (listeners, event) => listeners.some((l) => !l.fallback && covers(l, event.page) && (l.type === null || l.type === event.type));
20
+ /**
21
+ * Where the question `name` stands. `events` are the page's, `listeners` the running waits and
22
+ * watches that cover the page (only one asking for it by name counts: it asks again),
23
+ * `pickedUp` whether an event was handed to an agent. `last` is its latest answer: the reader's
24
+ * latest event of its name.
25
+ */
26
+ function questionState(name, events, listeners, pickedUp) {
27
+ const last = events.findLast((e) => e.type === name && fromReader(e));
28
+ const askedAgain = listeners.some((l) => !l.fallback && l.type === name);
29
+ return {
30
+ state: !last ? "open" : !pickedUp(last.id) ? "pending" : askedAgain ? "open" : "decided",
31
+ last
32
+ };
33
+ }
34
+ /** Does a wait or watch take the answer to question `name`? Not: it is unheard. */
35
+ const heard = (name, listeners) => listeners.some((l) => !l.fallback && (l.type === null || l.type === name));
36
+ /** The type of the event the page appends once messages were in view: `{ ids }`. */
37
+ const READ = "whiteboard:read";
38
+ /**
39
+ * The agent's messages on a page the reader hasn't read: events from the agent of a type
40
+ * `isMessage` says is for the reader, not named by a `whiteboard:read` from the reader, and not
41
+ * replaced by a later one (`replaces`).
42
+ */
43
+ function unreadMessages(events, isMessage) {
44
+ const read = /* @__PURE__ */ new Set();
45
+ const replaced = /* @__PURE__ */ new Set();
46
+ for (const e of events) {
47
+ if (e.type === "whiteboard:read" && fromReader(e)) for (const id of e.data?.ids ?? []) read.add(String(id));
48
+ if (e.data?.replaces) replaced.add(String(e.data.replaces));
49
+ }
50
+ return events.filter((e) => !fromReader(e) && isMessage(e.type) && !read.has(e.id) && !replaced.has(e.id));
51
+ }
52
+ /** How many things on a page wait for the reader: its open questions and unread messages. */
53
+ const awaiting = (p) => p.open.length + p.unread.length;
54
+ /**
55
+ * What is open on a page, one short line each; the command that picks it up comes last, once.
56
+ * `file` is how to name the page's file to the reader (relative to where they are). Without
57
+ * `waiting`, the questions an agent is already waiting on are left out.
58
+ */
59
+ function statusLines(p, file, { waiting = true } = {}) {
60
+ const lines = [];
61
+ if (p.unpicked.length) lines.push(`${p.unpicked.length} answer${p.unpicked.length > 1 ? "s" : ""} no agent picked up (${[...new Set(p.unpicked.map((e) => e.type))].join(", ")})`);
62
+ const fallback = p.listeners.some((l) => l.fallback);
63
+ if (p.unheard.length) lines.push(fallback ? `no agent waits for ${p.unheard.join(", ")}; the fallback picks the answers up` : `nobody listens for ${p.unheard.join(", ")}`);
64
+ if (lines.length && !(fallback && !p.unpicked.length)) lines.push(`→ whiteboard wait --page ${file}`);
65
+ const listened = p.open.filter((t) => !p.unheard.includes(t));
66
+ if (waiting && listened.length) lines.push(`waiting for the reader: ${listened.join(", ")}`);
67
+ return lines;
68
+ }
69
+ /** Whose a page is, said to `session`: yours, another session's, or nobody's. */
70
+ 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 };
package/package.json CHANGED
@@ -1,6 +1,133 @@
1
1
  {
2
2
  "name": "@bigmistqke/whiteboard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
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
+ "keywords": [
6
+ "agent",
7
+ "ai",
8
+ "markdown",
9
+ "live-reload",
10
+ "forms",
11
+ "whiteboard",
12
+ "agent-skills",
13
+ "skill",
14
+ "cli"
15
+ ],
16
+ "license": "MIT",
17
+ "author": "bigmistqke",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/bigmistqke/whiteboard.git"
21
+ },
22
+ "homepage": "https://github.com/bigmistqke/whiteboard#readme",
23
+ "bugs": "https://github.com/bigmistqke/whiteboard/issues",
24
+ "type": "module",
25
+ "bin": {
26
+ "whiteboard": "dist/bin/whiteboard.js"
27
+ },
28
+ "exports": {
29
+ ".": {
30
+ "source": "./src/define.ts",
31
+ "types": "./src/define.ts",
32
+ "default": "./dist/define.js"
33
+ },
34
+ "./log": {
35
+ "source": "./src/events.ts",
36
+ "types": "./src/events.ts",
37
+ "default": "./dist/src/events.js"
38
+ },
39
+ "./terminal": {
40
+ "source": "./plugins/terminal/index.ts",
41
+ "types": "./plugins/terminal/index.ts",
42
+ "default": "./dist/plugins/terminal/index.js"
43
+ },
44
+ "./claude-code": {
45
+ "source": "./plugins/claude-code/index.ts",
46
+ "types": "./plugins/claude-code/index.ts",
47
+ "default": "./dist/plugins/claude-code/index.js"
48
+ },
49
+ "./comments": {
50
+ "source": "./plugins/comments/index.ts",
51
+ "types": "./plugins/comments/index.ts",
52
+ "default": "./dist/plugins/comments/index.js"
53
+ },
54
+ "./solid": {
55
+ "types": "./solid/index.tsx",
56
+ "default": "./dist/solid/index.js"
57
+ },
58
+ "./plugins": {
59
+ "source": "./plugins/index.ts",
60
+ "types": "./plugins/index.ts",
61
+ "default": "./dist/plugins/index.js"
62
+ },
63
+ "./code": {
64
+ "source": "./plugins/code/index.ts",
65
+ "types": "./plugins/code/index.ts",
66
+ "default": "./dist/plugins/code/index.js"
67
+ }
68
+ },
69
+ "files": [
70
+ "bin",
71
+ "src",
72
+ "dist",
73
+ "plugins",
74
+ "solid",
75
+ "skills",
76
+ "!**/*.test.ts"
77
+ ],
78
+ "scripts": {
79
+ "build": "node build.ts",
80
+ "dev": "node build.ts --watch",
81
+ "prepare": "node build.ts",
82
+ "prepublishOnly": "npm run check && npm test",
83
+ "release": "npm run check && npm test && bumpp --commit 'Release v%s' && npm publish --access public",
84
+ "start": "node bin/whiteboard.ts serve",
85
+ "check": "tsc -p tsconfig.json",
86
+ "test": "node --test --test-force-exit 'src/**/*.test.ts' 'plugins/**/*.test.ts'",
87
+ "test:browser": "node --test --test-force-exit --test-concurrency=1 'test/browser/*.test.ts'"
88
+ },
89
+ "engines": {
90
+ "node": ">=22.18"
91
+ },
92
+ "dependencies": {
93
+ "@xterm/addon-serialize": "^0.14.0",
94
+ "@xterm/headless": "^6.0.0",
95
+ "mdast-util-to-string": "^4.0.0",
96
+ "pele": "^1.13.0",
97
+ "rehype-stringify": "^10.0.1",
98
+ "remark-directive": "^4.0.0",
99
+ "remark-gfm": "^4.0.1",
100
+ "remark-parse": "^11.0.0",
101
+ "remark-rehype": "^11.1.2",
102
+ "shiki": "^4.6.0",
103
+ "unified": "^11.0.5"
104
+ },
105
+ "peerDependencies": {
106
+ "@solidjs/web": "^2.0.0-rc.21",
107
+ "solid-js": "^2.0.0-rc.21"
108
+ },
109
+ "peerDependenciesMeta": {
110
+ "solid-js": {
111
+ "optional": true
112
+ },
113
+ "@solidjs/web": {
114
+ "optional": true
115
+ }
116
+ },
117
+ "devDependencies": {
118
+ "@solidjs/compiler": "^2.0.0-rc.21",
119
+ "@solidjs/web": "^2.0.0-rc.21",
120
+ "@types/node": "^26.6.6",
121
+ "@xterm/addon-fit": "^0.11.0",
122
+ "@xterm/xterm": "^6.0.0",
123
+ "bumpp": "^12.3.0",
124
+ "morphdom": "^2.7.7",
125
+ "playwright": "^1.60.0",
126
+ "rolldown": "^1.2.19",
127
+ "solid-js": "^2.0.0-rc.21",
128
+ "typescript": "^7.0.2"
129
+ },
130
+ "optionalDependencies": {
131
+ "node-pty": "^1.1.0"
132
+ }
133
+ }
@@ -0,0 +1,13 @@
1
+ A highlighted box with an optional title. Pick the type with `{type=…}` or the
2
+ class shorthand `{.warning}`: `note` (default), `tip`, `success`, `warning`,
3
+ `danger`, `question`.
4
+
5
+ ```markdown
6
+ :::callout[Heads up]{.warning}
7
+ Solid 2 is a release candidate; APIs can still move.
8
+ :::
9
+ ```
10
+
11
+ :::callout[Heads up]{.warning}
12
+ Solid 2 is a release candidate; APIs can still move.
13
+ :::
@@ -0,0 +1,25 @@
1
+ import fs from 'node:fs'
2
+ import { definePlugin, type Plugin } from '@bigmistqke/whiteboard'
3
+ import { html, raw, type DirectiveContext } from '@bigmistqke/whiteboard'
4
+
5
+ const TYPES = new Set(['note', 'tip', 'success', 'warning', 'danger', 'question'])
6
+
7
+ export async function render(ctx: DirectiveContext) {
8
+ const type = [ctx.attrs.type, ...(ctx.attrs.class ?? '').split(/\s+/)].find(t => t && TYPES.has(t)) ?? 'note'
9
+ // the label and content are HTML already
10
+ const title = ctx.label && html`<div class="wb-callout-title">${raw(ctx.label)}</div>`
11
+ return html`<aside class="wb-callout" data-type="${type}">${title}${raw(await ctx.toHtml(ctx.children))}</aside>`
12
+ }
13
+
14
+ export default function callout(): Plugin {
15
+ return definePlugin({
16
+ name: 'callout',
17
+ blocks: {
18
+ callout: {
19
+ html: render,
20
+ style: new URL('./style.css', import.meta.url),
21
+ },
22
+ },
23
+ docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
24
+ })
25
+ }
@@ -0,0 +1,12 @@
1
+ /* a margin note: a coloured rule and a light tint, set in the body face */
2
+ .wb-callout {
3
+ --c: var(--info);
4
+ margin: 3.4em 0; padding: 1em 1.3em; border-left: 3px solid var(--c);
5
+ background: color-mix(in srgb, var(--c) 6%, var(--bg)); border-radius: 0 var(--radius) var(--radius) 0;
6
+ }
7
+ .wb-callout > :first-child { margin-top: 0; }
8
+ .wb-callout > :last-child { margin-bottom: 0; }
9
+ .wb-callout-title { font: 600 .8rem/1.4 var(--sans); color: var(--c); margin-bottom: .5em; letter-spacing: .01em; }
10
+ .wb-callout:is([data-type=tip], [data-type=success]) { --c: var(--ok); }
11
+ .wb-callout:is([data-type=warning], [data-type=question]) { --c: var(--warn); }
12
+ .wb-callout[data-type=danger] { --c: var(--bad); }
@@ -0,0 +1,46 @@
1
+ A chat between the reader and you: the reader types (Enter sends,
2
+ Shift+Enter starts a new line), you answer, the reader's messages on one side
3
+ and yours on the other. Messages are markdown (code, lists, links, `#12`);
4
+ raw HTML and blocks show as written. Every form has one under it, for questions about the
5
+ question; a `chat` block puts one anywhere, for talk that isn't about a form.
6
+
7
+ ```markdown
8
+ :::chat{name=notes}
9
+ Anything about the plan that isn't a decision: write it here.
10
+ :::
11
+ ```
12
+
13
+ :::chat{name=notes}
14
+ Anything about the plan that isn't a decision: write it here.
15
+ :::
16
+
17
+ What the block says above the chat is ordinary markdown, and optional:
18
+ `::chat{name=page}` alone is a bare chat. Give each chat on a page its own
19
+ name, other than the page's forms' names: a form's chat has the form's name.
20
+
21
+ A message is a `chat:message` event, `{ "chat": "<name>", "text": "…" }`,
22
+ never an answer: under a form it never makes a choice. Answer in the same chat:
23
+
24
+ ```sh
25
+ whiteboard append --page <file> --type chat:message --data '{"chat":"<name>","text":"your answer"}'
26
+ ```
27
+
28
+ Two more fields, both optional:
29
+
30
+ - `replaces`: the id of an earlier message of yours. Yours takes its place,
31
+ to correct it; the log itself only grows.
32
+ - `replyTo` (in a form's chat): the id of a submit of the form whose written
33
+ text you answer (a remark typed into one of its text fields). That text
34
+ shows as the reader's message, right before yours.
35
+
36
+ Your messages show as the agent's, and `wait` and `watch` skip what you
37
+ append. A wait on the whole page (no `--type`) hands out chat messages too;
38
+ a wait with `--type <form name>` does not. So don't add a free-text field
39
+ for questions or remarks to a decision form: its chat is for that, and a
40
+ submit stays a choice.
41
+
42
+ A chat is found by its name. Remove or rename a form or a chat block and its
43
+ chat moves to the end of the page, read-only, under "Chats no longer on this
44
+ page" (you can still answer there); bring it back under its name and the chat
45
+ is in its place again. So rework a question in its form rather than
46
+ replacing the form.
@@ -0,0 +1,101 @@
1
+ // A textarea that grows with its text, between a minimum and a maximum number of rows. Inlined
2
+ // from solid-textarea-autosize (MIT, © 2022 bigmistqke), itself a port of react-textarea-autosize,
3
+ // and updated for Solid 2: a ref directive, set up in `onSettled` with its cleanup returned.
4
+ //
5
+ // <textarea ref={autosize({ maxRows: 8 })} />
6
+ //
7
+ // The height is measured on a hidden textarea with the same sizing styles. It is measured again on
8
+ // every input, and whenever the textarea's own box changes (a narrower pane wraps more lines).
9
+ // After changing the value from code, dispatch an `input` event to measure again.
10
+ import { onSettled } from 'solid-js'
11
+
12
+ export interface AutosizeOptions {
13
+ /** rows shown at the least (default 1) */
14
+ minRows?: number
15
+ /** rows it grows to at the most, then it scrolls (default: no limit) */
16
+ maxRows?: number
17
+ }
18
+
19
+ const SIZING_STYLE = [
20
+ 'border-bottom-width', 'border-left-width', 'border-right-width', 'border-top-width', 'box-sizing',
21
+ 'font-family', 'font-size', 'font-style', 'font-weight', 'letter-spacing', 'line-height',
22
+ 'padding-bottom', 'padding-left', 'padding-right', 'padding-top', 'tab-size', 'text-indent',
23
+ 'text-rendering', 'text-transform', 'width', 'word-break',
24
+ ] as const
25
+
26
+ // forced on the measuring textarea, over anything a page's stylesheet gives textareas (a page's
27
+ // `max-width: 100%` resolves against the body here, and would squeeze it to nothing)
28
+ const HIDDEN_STYLE: Record<string, string> = {
29
+ 'min-height': '0', 'max-height': 'none', 'min-width': '0', 'max-width': 'none', height: '0',
30
+ visibility: 'hidden', overflow: 'hidden',
31
+ position: 'absolute', 'z-index': '-1000', top: '0', right: '0',
32
+ }
33
+
34
+ interface Sizing { style: Record<string, string>; padding: number; border: number }
35
+
36
+ function sizingOf(node: HTMLElement): Sizing | null {
37
+ const computed = getComputedStyle(node)
38
+ const style: Record<string, string> = {}
39
+ for (const key of SIZING_STYLE) style[key] = computed.getPropertyValue(key)
40
+ // a node that is not in the document has no computed box
41
+ if (!style['box-sizing']) return null
42
+ return {
43
+ style,
44
+ padding: parseFloat(style['padding-bottom']) + parseFloat(style['padding-top']),
45
+ border: parseFloat(style['border-bottom-width']) + parseFloat(style['border-top-width']),
46
+ }
47
+ }
48
+
49
+ let hidden: HTMLTextAreaElement | null = null
50
+
51
+ /** The height the textarea needs for `value`, within the rows allowed. */
52
+ function heightFor(sizing: Sizing, value: string, minRows: number, maxRows: number) {
53
+ if (!hidden) {
54
+ hidden = document.createElement('textarea')
55
+ hidden.setAttribute('tabindex', '-1')
56
+ hidden.setAttribute('aria-hidden', 'true')
57
+ }
58
+ if (!hidden.isConnected) document.body.append(hidden)
59
+ for (const [key, value] of Object.entries(sizing.style)) hidden.style.setProperty(key, value)
60
+ for (const [key, value] of Object.entries(HIDDEN_STYLE)) hidden.style.setProperty(key, value, 'important')
61
+
62
+ const borderBox = sizing.style['box-sizing'] === 'border-box'
63
+ // border-box: the height includes padding and border; content-box: only the content
64
+ const outer = (content: number) => (borderBox ? content + sizing.padding + sizing.border : content)
65
+ hidden.value = value
66
+ const height = borderBox ? hidden.scrollHeight + sizing.border : hidden.scrollHeight - sizing.padding
67
+ hidden.value = 'x'
68
+ const row = hidden.scrollHeight - sizing.padding
69
+ return Math.min(outer(row * maxRows), Math.max(outer(row * minRows), height))
70
+ }
71
+
72
+ /** A ref directive that keeps a textarea as tall as its text. */
73
+ export function autosize(options: AutosizeOptions = {}) {
74
+ let node: HTMLTextAreaElement | undefined
75
+ let last = 0
76
+ const resize = () => {
77
+ if (!node) return
78
+ const sizing = sizingOf(node)
79
+ if (!sizing) return
80
+ const height = heightFor(sizing, node.value || node.placeholder || 'x', options.minRows ?? 1, options.maxRows ?? Infinity)
81
+ if (height === last) return
82
+ last = height
83
+ node.style.setProperty('height', `${height}px`, 'important')
84
+ }
85
+ // the ref runs before the element is in the document: measure once it is
86
+ onSettled(() => {
87
+ const el = node
88
+ if (!el) return
89
+ resize()
90
+ el.addEventListener('input', resize)
91
+ const observer = new ResizeObserver(() => resize())
92
+ observer.observe(el)
93
+ return () => {
94
+ el.removeEventListener('input', resize)
95
+ observer.disconnect()
96
+ }
97
+ })
98
+ return (el: HTMLTextAreaElement) => {
99
+ node = el
100
+ }
101
+ }
@@ -0,0 +1,93 @@
1
+ // A chat (rendered by the chat block, on its own or under a form): the reader writes, the agent
2
+ // answers (`whiteboard append --type chat:message --data '{"chat":"<name>","text":"…"}'`). A message
3
+ // is a `chat:message` event, never an answer, so talking about a form's choice never makes it.
4
+ import { createMemo, For, Loading } from 'solid-js'
5
+ import { solid, useWhiteboard } from '@bigmistqke/whiteboard/solid'
6
+ import type { ChatProps } from './index'
7
+ import type { WbEvent } from '@bigmistqke/whiteboard'
8
+ import { autosize } from './autosize'
9
+
10
+ /** A message in a chat: the chat block's own event type. */
11
+ const MESSAGE = 'chat:message'
12
+
13
+ interface Message { id: string; from: 'you' | 'agent'; text: string }
14
+
15
+ /**
16
+ * What the reader wrote in a submit of a form: every text in it that is not one of the form's
17
+ * choices (also from a field the form no longer has).
18
+ */
19
+ function written(submit: WbEvent, choiceNames: string[]) {
20
+ const choices = new Set(choiceNames)
21
+ return Object.entries(submit.data)
22
+ .filter(([k, v]) => !choices.has(k) && typeof v === 'string' && v.trim())
23
+ .map(([, v]) => String(v).trim())
24
+ .join('\n\n')
25
+ }
26
+
27
+ function Chat(props: ChatProps) {
28
+ const wb = useWhiteboard()
29
+ // The chat's messages in order. A message can take the place of an earlier one (`replaces` its
30
+ // id), to correct it. Under a form, a message can answer something the reader wrote in a submit
31
+ // of the form (`replyTo` its id): that text shows as theirs, right before the answer.
32
+ const messages = createMemo((): Message[] => {
33
+ const events = wb.events()
34
+ const own = events.filter(e => e.type === MESSAGE && e.data.chat === props.chat)
35
+ const replaced = new Set(own.map(e => e.data.replaces).filter(Boolean).map(String))
36
+ const out: Message[] = []
37
+ for (const e of own) {
38
+ if (replaced.has(e.id)) continue
39
+ const to = props.form && e.data.replyTo ? events.find(x => x.id === e.data.replyTo && x.type === props.form) : undefined
40
+ const asked = to ? written(to, props.choices) : ''
41
+ if (to && asked && !out.some(m => m.id === to.id)) out.push({ id: to.id, from: 'you', text: asked })
42
+ out.push({ id: e.id, from: e.from === 'cli' ? 'agent' : 'you', text: String(e.data.text ?? '') })
43
+ }
44
+ return out
45
+ })
46
+ let box: HTMLTextAreaElement | undefined
47
+ const post = async () => {
48
+ const text = box?.value.trim()
49
+ if (!text) return
50
+ await wb.append(MESSAGE, { chat: props.chat, text })
51
+ box!.value = ''
52
+ // measure again: a value set from code fires no input event
53
+ box!.dispatchEvent(new Event('input'))
54
+ }
55
+ return (
56
+ // a div, not a form: forms don't nest, and the box has no name, so it is never part of an answer
57
+ <div class="wb-chat" data-under-form={props.form ? '' : undefined}>
58
+ <For each={messages()}>
59
+ {m => (
60
+ // the reader's messages on the right, the agent's on the left
61
+ // the agent's: read once in view (the core marks it, see EventSpec.forReader)
62
+ <div class="wb-chat-message" data-from={m.from} data-wb-message={m.from === 'agent' ? m.id : undefined}>
63
+ <span class="wb-chat-who">{m.from}</span>
64
+ <Bubble text={m.text} />
65
+ </div>
66
+ )}
67
+ </For>
68
+ <div class="wb-chat-new">
69
+ <textarea
70
+ ref={[el => (box = el), autosize({ maxRows: 10 })]}
71
+ rows={1}
72
+ placeholder={props.form ? "Ask about this question (doesn't choose anything)" : 'Write a message'}
73
+ // Enter sends, Shift+Enter starts a new line; not while an input method is composing
74
+ onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); post() } }}
75
+ />
76
+ <button type="button" onClick={post}>{props.form ? 'Ask' : 'Send'}</button>
77
+ </div>
78
+ </div>
79
+ )
80
+ }
81
+
82
+ /** A message as markdown, rendered by the server; its plain text until then. */
83
+ function Bubble(props: { text: string }) {
84
+ const wb = useWhiteboard()
85
+ const md = createMemo(() => wb.markdown(props.text))
86
+ return (
87
+ <Loading fallback={<div class="wb-chat-bubble">{props.text}</div>}>
88
+ <div class="wb-chat-bubble" data-md="" innerHTML={md()} />
89
+ </Loading>
90
+ )
91
+ }
92
+
93
+ export default solid(Chat)
@@ -0,0 +1,61 @@
1
+ // :::chat{name=…} — a chat between the reader and the agent, anywhere on a page; and the chat under
2
+ // every form, which the form plugin places with the form's name. See README.md.
3
+ //
4
+ // A message is a `chat:message` event, `{ chat, text }`, from the reader (the page) or the agent
5
+ // (`whiteboard append`); the chat's name says which chat it belongs to. Messages are never answers:
6
+ // a form's chat is talk about the question, never a choice.
7
+ import fs from 'node:fs'
8
+ import { definePlugin, type Plugin } from '@bigmistqke/whiteboard'
9
+ import { html, raw, type Block, type DirectiveContext } from '@bigmistqke/whiteboard'
10
+ import { builtFile } from '../../src/package.ts'
11
+ import { isQuestionName } from '../../src/status.ts'
12
+
13
+ const style = new URL('./style.css', import.meta.url)
14
+
15
+ /**
16
+ * What the chat needs to know. `form`: the form it sits under, if any, with the names of its choices,
17
+ * whose values are never a remark (a message can answer text the reader typed into a submit).
18
+ */
19
+ export interface ChatProps { chat: string; form: string | null; choices: string[] }
20
+
21
+ /** The chat itself: a client island, so the server renders nothing for it. */
22
+ const thread: Block<ChatProps> = {
23
+ style,
24
+ props: ctx => ({
25
+ chat: (ctx as DirectiveContext).attrs.chat ?? '',
26
+ form: (ctx as DirectiveContext).attrs.form || null,
27
+ choices: ((ctx as DirectiveContext).attrs.choices ?? '').split(' ').filter(Boolean),
28
+ }),
29
+ html: () => '',
30
+ client: builtFile(import.meta.url, 'client.js'),
31
+ }
32
+
33
+ const quote = (s: string) => s.replace(/"/g, '&quot;')
34
+
35
+ /** The chat thread for `chat`, as markup: for the chat block, and for the form plugin under a form. */
36
+ export const chatThread = (c: DirectiveContext, chat: string, form?: { choices: string[] }) =>
37
+ c.markdown(`::chat-thread{chat="${quote(chat)}"${form ? ` form="${quote(chat)}" choices="${form.choices.join(' ')}"` : ''}}`)
38
+
39
+ /** `:::chat{name=…}`: a chat on its own, after whatever the block says above it. */
40
+ const chat: Block = {
41
+ style,
42
+ async html(ctx) {
43
+ const c = ctx as DirectiveContext
44
+ const name = c.attrs.name || c.attrs.id || 'chat'
45
+ // a chat's name shares the forms' names: a colon marks events, never a chat
46
+ if (!isQuestionName(name)) throw new Error(`chat name "${name}" has a colon: those names are reserved for events of whiteboard and plugins`)
47
+ const body = c.children.length ? await c.toHtml(c.children) : ''
48
+ return html`<section class="wb-chat-block" data-chat="${name}">${raw(body)}${raw(await chatThread(c, name))}</section>`
49
+ },
50
+ }
51
+
52
+ export default function chatPlugin(): Plugin {
53
+ return definePlugin({
54
+ name: 'chat',
55
+ blocks: { chat, 'chat-thread': thread },
56
+ events: {
57
+ 'chat:message': { handOut: true, forReader: true, description: 'a message in a chat: `{ chat, text }`, and `replaces` or `replyTo` (see below)' },
58
+ },
59
+ docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
60
+ })
61
+ }
@@ -0,0 +1,24 @@
1
+ /* A chat: the reader's messages on the right, the agent's on the left; never part of an answer. */
2
+ .wb-chat { display: flex; flex-direction: column; gap: 10px; font: .92rem/1.45 var(--sans); }
3
+ /* under a form: set off from the question by a dashed rule */
4
+ .wb-chat[data-under-form] { margin-top: 4px; padding-top: 12px; border-top: 1px dashed var(--border); }
5
+ .wb-chat-message { display: flex; flex-direction: column; gap: 3px; max-width: 85%; align-self: flex-start; align-items: flex-start; }
6
+ .wb-chat-message[data-from=you] { align-self: flex-end; align-items: flex-end; }
7
+ .wb-chat-who { font: 600 .68rem/1.3 var(--sans); letter-spacing: .04em; text-transform: uppercase; color: var(--muted); padding: 0 4px; }
8
+ .wb-chat-message[data-from=agent] .wb-chat-who { color: var(--accent); }
9
+ .wb-chat-bubble { white-space: pre-wrap; padding: 8px 12px; border-radius: 14px 14px 14px 4px; background: var(--tint); border: 1px solid var(--border); }
10
+ /* rendered from markdown: its paragraphs and code carry the spacing */
11
+ .wb-chat-bubble[data-md] { white-space: normal; overflow-wrap: anywhere; }
12
+ .wb-chat-bubble[data-md] > :first-child { margin-top: 0; }
13
+ .wb-chat-bubble[data-md] > :last-child { margin-bottom: 0; }
14
+ .wb-chat-bubble[data-md] :is(p, ul, ol, pre, blockquote) { margin: 0 0 .5em; }
15
+ .wb-chat-bubble[data-md] pre { font-size: .8rem; padding: 8px 10px; border-radius: 6px; overflow-x: auto; max-width: 100%; }
16
+ .wb-chat-message[data-from=you] .wb-chat-bubble[data-md] a { color: inherit; }
17
+ .wb-chat-message[data-from=you] .wb-chat-bubble { border-radius: 14px 14px 4px 14px; background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
18
+ .wb-chat-new { display: flex; gap: 8px; align-items: flex-start; }
19
+ .wb-chat-new textarea { flex: 1; resize: none; font: inherit; }
20
+
21
+ /* :::chat on its own: set off from the article like a form, hairlines above and below */
22
+ .wb-chat-block { margin: 3.6em 0; padding: 1.6em 0 1.7em; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); display: grid; gap: 16px; }
23
+ .wb-chat-block > :first-child { margin-top: 0; }
24
+ .wb-chat-block > :is(p, ul, ol) { margin: 0; }