@bigmistqke/whiteboard 0.1.0 → 0.2.1

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 (73) hide show
  1. package/README.md +31 -12
  2. package/bin/whiteboard.ts +74 -17
  3. package/dist/bin/whiteboard.js +93 -22
  4. package/dist/client/runtime.js +164 -11
  5. package/dist/plugins/chat/README.md +2 -1
  6. package/dist/plugins/chat/client.js +2 -2
  7. package/dist/plugins/chat/index.js +1 -0
  8. package/dist/plugins/chat/style.css +7 -0
  9. package/dist/plugins/code/diff.js +1 -0
  10. package/dist/plugins/comments/client.js +6 -6
  11. package/dist/plugins/comments/index.js +4 -1
  12. package/dist/plugins/comments/style.css +8 -0
  13. package/dist/plugins/forge/README.md +12 -0
  14. package/dist/plugins/forge/index.js +83 -0
  15. package/dist/plugins/gallery/client.js +1 -1
  16. package/dist/plugins/iframe/README.md +18 -0
  17. package/dist/plugins/iframe/client.js +1 -0
  18. package/dist/plugins/iframe/index.js +40 -0
  19. package/dist/plugins/iframe/style.css +29 -0
  20. package/dist/plugins/index.js +4 -0
  21. package/dist/plugins/mermaid/index.js +1 -0
  22. package/dist/solid/index.js +2 -1
  23. package/dist/src/client/page/base.css +33 -12
  24. package/dist/src/client/page/main.js +250 -26
  25. package/dist/src/events.js +24 -3
  26. package/dist/src/icons.js +6 -0
  27. package/dist/src/loader.js +12 -6
  28. package/dist/src/pages/blocks.js +1 -0
  29. package/dist/src/pages/index.js +3 -2
  30. package/dist/src/pages/markdown.js +107 -4
  31. package/dist/src/pages/render.js +63 -9
  32. package/dist/src/server.js +37 -12
  33. package/dist/src/status.js +38 -10
  34. package/package.json +1 -1
  35. package/plugins/chat/README.md +2 -1
  36. package/plugins/chat/client.tsx +15 -3
  37. package/plugins/chat/index.ts +1 -1
  38. package/plugins/chat/style.css +7 -0
  39. package/plugins/code/diff.ts +7 -1
  40. package/plugins/comments/client.ts +50 -6
  41. package/plugins/comments/index.ts +4 -2
  42. package/plugins/comments/style.css +8 -0
  43. package/plugins/forge/README.md +12 -0
  44. package/plugins/forge/index.ts +71 -0
  45. package/plugins/iframe/README.md +18 -0
  46. package/plugins/iframe/client.ts +46 -0
  47. package/plugins/iframe/index.ts +54 -0
  48. package/plugins/iframe/style.css +29 -0
  49. package/plugins/index.ts +3 -1
  50. package/plugins/mermaid/index.ts +1 -0
  51. package/skills/whiteboard/SKILL.md +17 -7
  52. package/solid/index.tsx +3 -0
  53. package/src/client/forms.ts +5 -6
  54. package/src/client/markdown.ts +36 -0
  55. package/src/client/page/base.css +33 -12
  56. package/src/client/page/elsewhere.ts +70 -0
  57. package/src/client/page/live.ts +30 -0
  58. package/src/client/page/main.ts +31 -6
  59. package/src/client/page/sort.ts +38 -0
  60. package/src/client/page/waiting.ts +102 -29
  61. package/src/client/read.ts +73 -0
  62. package/src/client/runtime.ts +13 -0
  63. package/src/client/toast.ts +25 -0
  64. package/src/define.ts +79 -13
  65. package/src/events.ts +27 -3
  66. package/src/icons.ts +8 -0
  67. package/src/loader.ts +7 -4
  68. package/src/pages/blocks.ts +3 -0
  69. package/src/pages/index.ts +8 -2
  70. package/src/pages/markdown.ts +92 -4
  71. package/src/pages/render.ts +49 -12
  72. package/src/server.ts +35 -12
  73. package/src/status.ts +64 -20
@@ -1,5 +1,6 @@
1
1
  import { renderMarkdown } from "./markdown.js";
2
2
  import { html, raw } from "../html.js";
3
+ import { awaitingLabel } from "../icons.js";
3
4
  import fs from "node:fs";
4
5
  import path from "node:path";
5
6
  import { execFileSync } from "node:child_process";
@@ -43,7 +44,7 @@ function crumbs(id, name) {
43
44
  }
44
45
  const time = (ts) => html`<time data-ts="${ts}"></time>`;
45
46
  function pageList(pages) {
46
- return html`<ul class="wb-index">${pages.map((p) => html`<li><a href="/${p.id}">${titleOf(p.file, path.basename(p.id))}</a> <span class="wb-meta"><code>${p.id}</code> · edited ${time(p.mtime)}${p.lastEvent && html` · last submit ${time(Date.parse(p.lastEvent))}`}${p.listeners > 0 && html` · <span class="wb-waiting">agent waiting</span>`}</span></li>`)}</ul>`;
47
+ return html`<ul class="wb-index">${pages.map((p) => html`<li><a href="/${p.id}">${titleOf(p.file, path.basename(p.id))}</a>${p.awaiting > 0 && html` <a class="wb-awaiting" href="/${p.id}#wb-waiting" title="${awaitingLabel(p.awaiting)}" aria-label="${awaitingLabel(p.awaiting)}">${raw("<svg viewBox=\"0 0 16 16\" width=\"13\" height=\"13\" aria-hidden=\"true\"><path d=\"M2 9.5 3.8 3.2A1 1 0 0 1 4.8 2.5h6.4a1 1 0 0 1 1 .7L14 9.5V13a.5.5 0 0 1-.5.5h-11A.5.5 0 0 1 2 13Zm0 0h3.5l1 1.5h3l1-1.5H14\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linejoin=\"round\"/></svg>")}${p.awaiting}</a>`} <span class="wb-meta"><code>${p.id}</code> · edited ${time(p.mtime)}${p.lastEvent && html` · last submit ${time(Date.parse(p.lastEvent))}`}</span></li>`)}</ul>`;
47
48
  }
48
49
  /** The folder's README, when it has one. */
49
50
  function readmeOf(page) {
@@ -119,17 +120,69 @@ function documentsIn(dir) {
119
120
  const depth = (f) => f.split("/").length;
120
121
  return [...new Set(files)].sort((a, b) => depth(a) - depth(b) || a.localeCompare(b));
121
122
  }
122
- /** The overview's list of the project's documents: each by its title, linked to its rendered page. */
123
+ /**
124
+ * The overview's list of the project's documents: each by its title, linked to its rendered page,
125
+ * with when its file last changed. The list can be sorted in the browser (sort.ts): by folder (as
126
+ * written here), by when last updated, or by title; each row carries what it is sorted by.
127
+ */
123
128
  function documentList(ctx) {
124
129
  const files = documentsIn(ctx.project.dir);
125
130
  if (!files.length) return "";
126
- const rows = files.map((f) => {
131
+ const rows = files.map((f, i) => {
127
132
  const abs = path.join(ctx.project.dir, f);
128
- return html`<li><a href="${ctx.urlFor(abs) ?? `/-/${f}`}">${titleOf(abs, f)}</a> <span class="wb-meta"><code>${f}</code></span></li>`;
133
+ const name = path.posix.basename(f);
134
+ const title = titleOf(abs, name);
135
+ const where = title === name ? path.posix.dirname(f) : f;
136
+ let mtime = 0;
137
+ try {
138
+ mtime = fs.statSync(abs).mtimeMs;
139
+ } catch {}
140
+ return html`<li data-order="${i}" data-updated="${mtime}" data-title="${title.toLowerCase()}"><a href="${ctx.urlFor(abs) ?? `/-/${f}`}">${title}</a> <span class="wb-meta">${where !== "." && html`<code>${where === f ? f : `${where}/`}</code> · `}edited ${time(mtime)}</span></li>`;
129
141
  });
130
- return html`<section class="wb-documents"><h2>Documents</h2><ul class="wb-index">${rows}</ul></section>`;
142
+ return html`<section class="wb-documents"><div class="wb-list-head"><h2>Documents</h2><label class="wb-sort">sort <select data-wb-sort="documents" aria-label="Sort the documents"><option value="order">by folder</option><option value="updated">last updated</option><option value="title">by title</option></select></label></div><ul class="wb-index">${rows}</ul></section>`;
143
+ }
144
+ /** The plugins' text links for a project folder, asked once per folder. */
145
+ function textLinksOf(links) {
146
+ const linksFor = /* @__PURE__ */ new Map();
147
+ return (dir) => {
148
+ let got = linksFor.get(dir);
149
+ if (!got) {
150
+ got = links.flatMap((fn) => {
151
+ try {
152
+ return fn({ dir });
153
+ } catch (err) {
154
+ console.error("links:", err);
155
+ return [];
156
+ }
157
+ });
158
+ linksFor.set(dir, got);
159
+ }
160
+ return got;
161
+ };
162
+ }
163
+ /**
164
+ * A message (a comment, a chat message) as HTML: markdown as on a page, but its raw HTML as text and
165
+ * its directives as written. Code fences go to the code block, so `styles` are what it needs linked.
166
+ */
167
+ function createMessageRender(blocks, links = []) {
168
+ const textLinks = textLinksOf(links);
169
+ return async (text, ctx) => {
170
+ const out = await renderMarkdown(String(text ?? ""), {
171
+ page: "",
172
+ file: "",
173
+ resolve: () => null,
174
+ code: blocks().code,
175
+ textLinks: textLinks(ctx.project.dir),
176
+ message: true
177
+ });
178
+ return {
179
+ html: out.html,
180
+ styles: out.styles.map((s) => ctx.asset(s))
181
+ };
182
+ };
131
183
  }
132
- function createRender(blocks, style, pluginStyles = []) {
184
+ function createRender(blocks, style, pluginStyles = [], links = []) {
185
+ const textLinks = textLinksOf(links);
133
186
  const STYLE = stylePath(style);
134
187
  const PLUGIN_STYLES = pluginStyles.map(stylePath).filter((f) => !!f);
135
188
  async function markdown(source, page, file, ctx) {
@@ -139,7 +192,8 @@ function createRender(blocks, style, pluginStyles = []) {
139
192
  file,
140
193
  resolve: (name) => set.get(name) ?? null,
141
194
  code,
142
- linkFor: ctx.urlFor
195
+ linkFor: ctx.urlFor,
196
+ textLinks: textLinks(ctx.project.dir)
143
197
  });
144
198
  }
145
199
  async function content(page, ctx) {
@@ -216,7 +270,7 @@ function createRender(blocks, style, pluginStyles = []) {
216
270
  client: ctx.asset(island.client)
217
271
  }]));
218
272
  const styles = out.styles.map((s) => ctx.asset(s));
219
- const nav = html`<nav class="wb-nav"><span>${crumbs(page.id, ctx.project.name)}</span>${page.mtime != null && html`<span class="wb-meta">updated <time id="wb-updated" data-ts="${page.mtime}"></time></span>`}<button type="button" class="wb-theme" title="Theme: follow the system, light or dark">auto</button><span class="wb-live" title="live reload"></span></nav>`;
273
+ const nav = html`<nav class="wb-nav"><span>${crumbs(page.id, ctx.project.name)}</span>${page.mtime != null && html`<span class="wb-meta">updated <time id="wb-updated" data-ts="${page.mtime}"></time></span>`}<button type="button" class="wb-theme" title="Theme: follow the system, light or dark" aria-label="Theme"></button><span class="wb-live" role="img" title="Connecting…" aria-label="Connecting…"></span></nav>`;
220
274
  const links = [
221
275
  ctx.asset(BASE_CSS),
222
276
  ...PLUGIN_STYLES.map((f) => ctx.asset(f)),
@@ -254,4 +308,4 @@ ${[...byPlugin].sort(([a], [b]) => a.localeCompare(b)).map(([plugin, blocks]) =>
254
308
  `;
255
309
  };
256
310
  }
257
- export { createDocs, createRender };
311
+ export { createDocs, createMessageRender, createRender, titleOf };
@@ -4,7 +4,8 @@ import { createConfigLoader, pluginDir, toPath } from "./loader.js";
4
4
  import { describeRoutes, dispatch, mountRoutes, pluginCommands, usage } from "./plugins.js";
5
5
  import { createAuth } from "./auth.js";
6
6
  import { FROM_SOURCE, PACKAGE_DIR } from "./package.js";
7
- import { fromReader, questionState } from "./status.js";
7
+ import { awaiting, covers, fromReader, heard, questionState, unreadMessages } from "./status.js";
8
+ import { titleOf } from "./pages/render.js";
8
9
  import _taggedTemplateLiteral from "../_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js";
9
10
  import fs from "node:fs";
10
11
  import path from "node:path";
@@ -109,10 +110,12 @@ function createServer(project) {
109
110
  name: h.name,
110
111
  client: asset(h.client)
111
112
  }));
113
+ const messages = [...(await config()).forReader];
112
114
  return {
113
115
  head: parts.map((x) => raw(String(x?.head ?? ""))),
114
116
  body: parts.map((x) => raw(String(x?.body ?? ""))),
115
117
  clients,
118
+ messages,
116
119
  notices
117
120
  };
118
121
  }
@@ -192,7 +195,7 @@ function createServer(project) {
192
195
  file: full,
193
196
  mtime: fs.statSync(full).mtimeMs,
194
197
  lastEvent: last.get(id) ?? null,
195
- listeners: listenersFor(id).length
198
+ awaiting: 0
196
199
  });
197
200
  }
198
201
  }
@@ -330,7 +333,7 @@ function createServer(project) {
330
333
  * hooks report. The questions are a page's named forms.
331
334
  */
332
335
  async function status(only) {
333
- const { pages, handedOut } = await config();
336
+ const { pages, handedOut, forReader } = await config();
334
337
  const isForAgent = forAgent(handedOut);
335
338
  const all = readEvents(project.eventsFile);
336
339
  const picked = pickedUp(all);
@@ -355,12 +358,14 @@ function createServer(project) {
355
358
  const named = (...states) => questions.filter((q) => states.includes(q.state)).map((q) => q.name);
356
359
  out.push({
357
360
  page: p.id,
361
+ title: titleOf(p.file, path.basename(p.id)),
358
362
  file: p.file,
359
363
  owner: owner.get(p.id) ?? null,
360
364
  asks,
361
365
  questions,
362
- open: named("waiting", "unheard"),
363
- unheard: named("unheard"),
366
+ open: named("open"),
367
+ unheard: named("open").filter((name) => !heard(name, listening)),
368
+ unread: unreadMessages(events, (type) => forReader.has(type)),
364
369
  unpicked: events.filter((e) => fromReader(e) && isForAgent(e.type) && !picked.has(e.id)),
365
370
  listeners: listening
366
371
  });
@@ -393,7 +398,7 @@ function createServer(project) {
393
398
  };
394
399
  }
395
400
  const json = (s) => JSON.stringify(s).replace(/</g, "\\u003c");
396
- const DOCK_STYLE = "#wb-dock{position:fixed;right:16px;bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:10;display:flex;flex-direction:column;align-items:flex-end;gap:6px}#wb-dock:empty{display:none}";
401
+ const DOCK_STYLE = "#wb-dock{position:fixed;right:16px;bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:10;display:flex;flex-direction:column;align-items:flex-end;gap:6px}#wb-dock:empty{display:none}#wb-toasts{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:30;display:grid;gap:8px;width:min(440px,100vw - 32px);pointer-events:none}.wb-toast{pointer-events:auto;cursor:pointer;padding:10px 14px;border-radius:8px;font:.85rem/1.45 var(--sans,system-ui,sans-serif);background:var(--bg,Canvas);color:var(--text,CanvasText);border:1px solid var(--border,#8884);box-shadow:0 8px 28px rgb(0 0 0/.18)}.wb-toast[data-kind=warn]{border-left:4px solid var(--warn,#c98a00)}.wb-toast[data-action]{border-left:4px solid var(--accent,#1d5bbf)}";
397
402
  /** `extras`: what plugins add to <head> and <body> (see shellExtras). */
398
403
  function shell(page, { page: rendered, out, notices }, extras = {
399
404
  head: [],
@@ -405,7 +410,8 @@ function createServer(project) {
405
410
  kind: page.kind,
406
411
  client: rendered ? asset(PAGE_CLIENT) : null,
407
412
  data: out.data ?? null,
408
- plugins: extras.clients
413
+ plugins: extras.clients,
414
+ messages: extras.messages ?? []
409
415
  };
410
416
  return String(html(_templateObject || (_templateObject = _taggedTemplateLiteral([
411
417
  "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>",
@@ -423,12 +429,11 @@ function createServer(project) {
423
429
  }
424
430
  /** A listener as the server holds it. */
425
431
  const listeners = /* @__PURE__ */ new Set();
426
- /** Does a listener's page filter cover `page`? An empty filter covers every page. */
427
- const covers = (l, page) => !l.page || page === l.page || page.startsWith(l.page + "/");
428
- const listenersFor = (page) => [...listeners].filter((l) => page == null || covers(l, page)).map(({ page, type, command }) => ({
432
+ const listenersFor = (page) => [...listeners].filter((l) => page == null || covers(l, page)).map(({ page, type, command, fallback }) => ({
429
433
  page,
430
434
  type,
431
- command
435
+ command,
436
+ ...fallback && { fallback }
432
437
  }));
433
438
  const clients = /* @__PURE__ */ new Set();
434
439
  function notify(client, kind) {
@@ -541,6 +546,10 @@ function createServer(project) {
541
546
  if (!found) return { notFound: `${isRepoId(id) ? id.slice(2) : id} does not exist${isRepoId(id) ? "" : " yet. This page loads as soon as it does"}.` };
542
547
  if ("raw" in found) return found;
543
548
  if ((found.kind === "folder" || found.kind === "pages" && id) && !requested.endsWith("/")) return { redirect: `/${id}/` };
549
+ if (found.kind === "pages") {
550
+ const counts = new Map((await status(found.id || null)).map((s) => [s.page, awaiting(s)]));
551
+ for (const p of found.pages) p.awaiting = counts.get(p.id) ?? 0;
552
+ }
544
553
  return { page: found };
545
554
  }
546
555
  async function handle(req, res) {
@@ -576,6 +585,19 @@ function createServer(project) {
576
585
  if (!body.type) return sendJson(res, 400, { error: "event type required" });
577
586
  return sendJson(res, 200, appendEvent(project.eventsFile, body));
578
587
  }
588
+ if (p === "/api/markdown" && req.method === "POST") {
589
+ const { texts } = JSON.parse(await readBody(req));
590
+ if (!Array.isArray(texts)) return sendJson(res, 400, { error: "texts: an array of strings" });
591
+ const { pages } = await config();
592
+ const out = await Promise.all(texts.map((t) => pages ? pages.message(String(t ?? ""), context()) : Promise.resolve({
593
+ html: String(html`${String(t ?? "")}`),
594
+ styles: []
595
+ })));
596
+ return sendJson(res, 200, {
597
+ html: out.map((o) => o.html),
598
+ styles: [...new Set(out.flatMap((o) => o.styles))]
599
+ });
600
+ }
579
601
  if (p === "/api/events") {
580
602
  const all = readEvents(project.eventsFile);
581
603
  const picked = pickedUp(all);
@@ -588,6 +610,8 @@ function createServer(project) {
588
610
  if (p === "/api/status") return sendJson(res, 200, await status(q.page || null));
589
611
  if (p === "/api/listeners") return sendJson(res, 200, listenersFor(q.page ?? null));
590
612
  if (p === "/api/listen") {
613
+ const fallback = "fallback" in q;
614
+ if (fallback && [...listeners].some((l) => l.fallback)) return sendJson(res, 409, { error: "another agent is the fallback already" });
591
615
  res.writeHead(200, {
592
616
  "content-type": "text/event-stream",
593
617
  "cache-control": "no-store",
@@ -597,7 +621,8 @@ function createServer(project) {
597
621
  const l = {
598
622
  page: q.page || "",
599
623
  type: q.type || null,
600
- command: q.command === "wait" ? "wait" : "watch"
624
+ command: q.command === "wait" ? "wait" : "watch",
625
+ ...fallback && { fallback }
601
626
  };
602
627
  listeners.add(l);
603
628
  notifyAll("listeners");
@@ -10,20 +10,47 @@ const isQuestionName = (name) => !!name && !name.includes(":");
10
10
  * through the command line, which marks its events `from: 'cli'`: an agent's reply, a claim, a pick.
11
11
  */
12
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));
13
20
  /**
14
21
  * Where the question `name` stands. `events` are the page's, `listeners` the running waits and
15
- * watches that cover the page, `pickedUp` whether an event was handed to an agent. `last` is its
16
- * latest answer: the reader's latest event of its name.
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.
17
25
  */
18
26
  function questionState(name, events, listeners, pickedUp) {
19
27
  const last = events.findLast((e) => e.type === name && fromReader(e));
20
- const asked = listeners.some((l) => l.type === name);
21
- const any = listeners.some((l) => l.type === null);
28
+ const askedAgain = listeners.some((l) => !l.fallback && l.type === name);
22
29
  return {
23
- state: asked || any && !last ? "waiting" : !last ? "unheard" : pickedUp(last.id) ? "decided" : "pending",
30
+ state: !last ? "open" : !pickedUp(last.id) ? "pending" : askedAgain ? "open" : "decided",
24
31
  last
25
32
  };
26
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;
27
54
  /**
28
55
  * What is open on a page, one short line each; the command that picks it up comes last, once.
29
56
  * `file` is how to name the page's file to the reader (relative to where they are). Without
@@ -32,12 +59,13 @@ function questionState(name, events, listeners, pickedUp) {
32
59
  function statusLines(p, file, { waiting = true } = {}) {
33
60
  const lines = [];
34
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(", ")})`);
35
- if (p.unheard.length) lines.push(`nobody listens for ${p.unheard.join(", ")}`);
36
- if (lines.length) lines.push(`→ whiteboard wait --page ${file}`);
37
- const heard = p.open.filter((t) => !p.unheard.includes(t));
38
- if (waiting && heard.length) lines.push(`waiting for the reader: ${heard.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(", ")}`);
39
67
  return lines;
40
68
  }
41
69
  /** Whose a page is, said to `session`: yours, another session's, or nobody's. */
42
70
  const whose = (p, session) => p.owner && p.owner === session ? "yours" : p.owner ? `session ${p.owner.slice(0, 8)}` : "no session";
43
- export { fromReader, isQuestionName, questionState, statusLines, whose };
71
+ export { READ, awaiting, covers, fromReader, heard, isQuestionName, questionState, statusLines, takenByOther, unreadMessages, whose };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bigmistqke/whiteboard",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
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",
@@ -1,6 +1,7 @@
1
1
  A chat between the reader and you: the reader types (Enter sends,
2
2
  Shift+Enter starts a new line), you answer, the reader's messages on one side
3
- and yours on the other. Every form has one under it, for questions about the
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
4
5
  question; a `chat` block puts one anywhere, for talk that isn't about a form.
5
6
 
6
7
  ```markdown
@@ -1,7 +1,7 @@
1
1
  // A chat (rendered by the chat block, on its own or under a form): the reader writes, the agent
2
2
  // answers (`whiteboard append --type chat:message --data '{"chat":"<name>","text":"…"}'`). A message
3
3
  // is a `chat:message` event, never an answer, so talking about a form's choice never makes it.
4
- import { createMemo, For } from 'solid-js'
4
+ import { createMemo, For, Loading } from 'solid-js'
5
5
  import { solid, useWhiteboard } from '@bigmistqke/whiteboard/solid'
6
6
  import type { ChatProps } from './index'
7
7
  import type { WbEvent } from '@bigmistqke/whiteboard'
@@ -58,9 +58,10 @@ function Chat(props: ChatProps) {
58
58
  <For each={messages()}>
59
59
  {m => (
60
60
  // the reader's messages on the right, the agent's on the left
61
- <div class="wb-chat-message" data-from={m.from}>
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}>
62
63
  <span class="wb-chat-who">{m.from}</span>
63
- <div class="wb-chat-bubble">{m.text}</div>
64
+ <Bubble text={m.text} />
64
65
  </div>
65
66
  )}
66
67
  </For>
@@ -78,4 +79,15 @@ function Chat(props: ChatProps) {
78
79
  )
79
80
  }
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
+
81
93
  export default solid(Chat)
@@ -54,7 +54,7 @@ export default function chatPlugin(): Plugin {
54
54
  name: 'chat',
55
55
  blocks: { chat, 'chat-thread': thread },
56
56
  events: {
57
- 'chat:message': { handOut: true, description: 'a message in a chat: `{ chat, text }`, and `replaces` or `replyTo` (see below)' },
57
+ 'chat:message': { handOut: true, forReader: true, description: 'a message in a chat: `{ chat, text }`, and `replaces` or `replyTo` (see below)' },
58
58
  },
59
59
  docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
60
60
  })
@@ -7,6 +7,13 @@
7
7
  .wb-chat-who { font: 600 .68rem/1.3 var(--sans); letter-spacing: .04em; text-transform: uppercase; color: var(--muted); padding: 0 4px; }
8
8
  .wb-chat-message[data-from=agent] .wb-chat-who { color: var(--accent); }
9
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; }
10
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); }
11
18
  .wb-chat-new { display: flex; gap: 8px; align-items: flex-start; }
12
19
  .wb-chat-new textarea { flex: 1; resize: none; font: inherit; }
@@ -2,7 +2,8 @@
2
2
  // unchanged, a gap between hunks, a file's name, or a header line nobody needs to read (`diff --git`,
3
3
  // `index`, `---`, modes), which the block leaves out. A line in a hunk has its number (`n`) and
4
4
  // where it is (`at`: `file:line` in the new file; a removed line counts in the old one,
5
- // `file (old):line`). Reads unified diffs, as `git diff` and `diff -u` print them.
5
+ // `file (old):line`). Reads unified diffs, as `git diff` and `diff -u` print them, and snippets of
6
+ // only +, - and unchanged lines.
6
7
 
7
8
  export type DiffKind = 'add' | 'del' | 'context' | 'hunk' | 'file' | 'meta'
8
9
 
@@ -19,6 +20,11 @@ export interface DiffLineInfo {
19
20
  const unprefix = (p: string) => p.replace(/\t.*$/, '').replace(/^"|"$/g, '').replace(/^[ab]\//, '')
20
21
 
21
22
  export function diffLines(text: string): DiffLineInfo[] {
23
+ // a snippet without hunks or file headers (only +, - and unchanged lines, as people paste them):
24
+ // every line is one of those, without numbers, as no header says where it is
25
+ if (!/^(@@ -\d|diff --git )/m.test(text)) {
26
+ return text.split('\n').map((line): DiffLineInfo => ({ kind: line[0] === '+' ? 'add' : line[0] === '-' ? 'del' : 'context' }))
27
+ }
22
28
  let file = '', oldFile = '', oldN = 0, newN = 0, inHunk = false
23
29
  let status = '', renamedFrom = ''
24
30
  return text.split('\n').map((line): DiffLineInfo => {
@@ -17,7 +17,7 @@
17
17
  // on the page, and highlighted with the CSS Highlight API: the page's own markup is never touched,
18
18
  // so updates and new-content marks don't see comments at all.
19
19
  import type { Api, PluginMount, PageHandle, WbEvent } from '../../src/define'
20
- import { html } from '../../src/html.ts'
20
+ import { html, raw } from '../../src/html.ts'
21
21
 
22
22
  const NEW = 'comments:new', REPLY = 'comments:reply', RESOLVE = 'comments:resolve'
23
23
 
@@ -149,13 +149,18 @@ function draw() {
149
149
  else highlights.delete('wb-comment-active')
150
150
  }
151
151
  const column = main.getBoundingClientRect()
152
+ const unreadIds = new Set(api.unread().map(e => e.id))
152
153
  layer.replaceChildren(...threads.map((t, i) => {
153
154
  const badge = document.createElement('button')
154
155
  badge.type = 'button'
155
156
  badge.className = 'wb-comment-badge'
156
157
  badge.dataset.thread = t.id
157
158
  badge.toggleAttribute('data-agent', lastFromAgent(t))
158
- badge.title = lastFromAgent(t) ? 'the agent replied' : 'comment'
159
+ // the replies it holds, for the page to find an unread one here (data-wb-holds, see the page)
160
+ badge.dataset.wbHolds = t.replies.map(r => r.id).join(' ')
161
+ const unread = t.replies.some(r => unreadIds.has(r.id))
162
+ badge.toggleAttribute('data-unread', unread)
163
+ badge.title = unread ? 'the agent replied: unread' : lastFromAgent(t) ? 'the agent replied' : 'comment'
159
164
  badge.textContent = String(1 + t.replies.length)
160
165
  const rect = t.range?.getClientRects()[0]
161
166
  // a passage that is gone from the page: its badge waits at the top, still open until closed
@@ -181,13 +186,20 @@ function refreshComments() {
181
186
 
182
187
  // ---- the thread popover ------------------------------------------------------------------------
183
188
 
189
+ // messages as markdown, rendered by the server, by their text
190
+ const rendered = new Map<string, string>()
191
+
184
192
  function renderPopover() {
185
193
  const t = threads.find(x => x.id === openThread)
186
194
  if (!t) return
187
195
  const who = (e: WbEvent) => (e.from === 'cli' ? 'agent' : 'you')
188
196
  // the quote and every message are text from the reader or the agent: `html` escapes them
189
- const message = (e: WbEvent) =>
190
- html`<div class="wb-thread-message" data-from="${who(e)}"><span class="wb-thread-who">${who(e)}</span><div class="wb-thread-text">${e.data.text ?? ''}</div></div>`
197
+ // a message is markdown: as rendered, once the server has (api.markdown), as plain text till then
198
+ const message = (e: WbEvent) => {
199
+ const text = String(e.data.text ?? '')
200
+ const md = rendered.get(text)
201
+ return html`<div class="wb-thread-message" data-from="${who(e)}" data-wb-message="${e.id}"><span class="wb-thread-who">${who(e)}</span><div class="wb-thread-text"${md != null ? raw(' data-md') : ''}>${md != null ? raw(md) : text}</div></div>`
202
+ }
191
203
  const draft = popover.querySelector('textarea')?.value ?? ''
192
204
  popover.innerHTML = String(html`
193
205
  <blockquote class="wb-thread-quote">${t.comment.data.quote ?? ''}</blockquote>
@@ -195,10 +207,21 @@ function renderPopover() {
195
207
  ${!t.range && html`<p class="wb-thread-detached">This passage is no longer on the page.</p>`}
196
208
  ${[t.comment, ...t.replies].map(message)}
197
209
  <form class="wb-thread-reply">
198
- <textarea rows="2" placeholder="Reply"></textarea>
210
+ <textarea rows="2" placeholder="Reply (Shift+Enter for a new line)"></textarea>
199
211
  <div class="wb-thread-actions"><button type="submit" class="wb-comment-button wb-comment-primary">Reply</button><button type="button" class="wb-comment-button" data-close>Close thread</button></div>
200
212
  </form>`)
201
213
  popover.querySelector('textarea')!.value = draft
214
+ // the messages not rendered yet: their text only, put in place as each arrives (the rest of the
215
+ // thread, the reply being typed among it, stays as it is)
216
+ for (const e of [t.comment, ...t.replies]) {
217
+ const text = String(e.data.text ?? '')
218
+ if (rendered.has(text)) continue
219
+ api.markdown(text).then(md => {
220
+ rendered.set(text, md)
221
+ const el = popover.querySelector<HTMLElement>(`[data-wb-message="${CSS.escape(e.id)}"] .wb-thread-text`)
222
+ if (el && !el.hasAttribute('data-md')) { el.innerHTML = md; el.setAttribute('data-md', '') }
223
+ }, err => console.error('comments:', err))
224
+ }
202
225
  }
203
226
 
204
227
  function placePopover() {
@@ -343,7 +366,7 @@ function onLinePointer(e: MouseEvent) {
343
366
  const composer = document.createElement('form')
344
367
  composer.className = 'wb-thread wb-comment-new'
345
368
  composer.hidden = true
346
- composer.innerHTML = String(html`<blockquote class="wb-thread-quote"></blockquote><textarea rows="3" placeholder="Your comment"></textarea>
369
+ composer.innerHTML = String(html`<blockquote class="wb-thread-quote"></blockquote><textarea rows="3" placeholder="Your comment (Shift+Enter for a new line)"></textarea>
347
370
  <div class="wb-thread-actions"><button type="submit" class="wb-comment-button wb-comment-primary">Comment</button><button type="button" class="wb-comment-button" data-cancel>Cancel</button></div>`)
348
371
 
349
372
  function startComment() {
@@ -398,6 +421,14 @@ const mount: PluginMount = (el: HTMLElement, handle: PageHandle, core: Api) => {
398
421
  startButton.addEventListener('mousedown', e => e.preventDefault())
399
422
  startButton.addEventListener('click', startComment)
400
423
 
424
+ // as in a chat: Enter sends the comment or reply, Shift+Enter starts a new line; not while an
425
+ // input method is composing
426
+ for (const form of [composer, popover] as HTMLElement[]) form.addEventListener('keydown', e => {
427
+ const box = e.target as HTMLElement
428
+ if (box.tagName !== 'TEXTAREA' || e.key !== 'Enter' || e.shiftKey || e.isComposing) return
429
+ e.preventDefault()
430
+ box.closest('form')?.requestSubmit()
431
+ })
401
432
  composer.addEventListener('submit', async e => {
402
433
  e.preventDefault()
403
434
  const text = composer.querySelector('textarea')!.value.trim()
@@ -429,9 +460,22 @@ const mount: PluginMount = (el: HTMLElement, handle: PageHandle, core: Api) => {
429
460
  if (!(e.target as HTMLElement).closest('[data-close]') || !openThread) return
430
461
  const id = openThread
431
462
  closePopover()
463
+ // closed, the thread's replies ask nothing of the reader any more
464
+ api.markRead(threads.find(t => t.id === id)?.replies.map(r => r.id) ?? [])
432
465
  await api.append(RESOLVE, { replyTo: id })
433
466
  refreshComments()
434
467
  })
468
+ // the page goes to an unread reply here: open its thread
469
+ layer.addEventListener('wb-reveal', e => {
470
+ const id = (e.target as HTMLElement).closest<HTMLElement>('[data-thread]')?.dataset.thread
471
+ if (id && openThread !== id) openPopover(id)
472
+ })
473
+ // a double-click outside the open thread closes it (a single click selects, to comment)
474
+ document.addEventListener('dblclick', e => {
475
+ const target = e.target as Node
476
+ if (!openThread || popover.contains(target) || layer.contains(target)) return
477
+ closePopover()
478
+ })
435
479
  document.addEventListener('keydown', e => {
436
480
  if (e.key !== 'Escape') return
437
481
  if (!composer.hidden) { composer.hidden = true; pending = null }
@@ -35,7 +35,9 @@ page until the reader closes it. Answer a comment the way it asks:
35
35
  \`whiteboard append --page <file> --type comments:reply --data '{"replyTo":"<comment id>","text":"…"}'\`
36
36
 
37
37
  Your replies show as the agent's, and \`wait\` and \`watch\` skip what you
38
- append, so you don't hear your own replies.`
38
+ append, so you don't hear your own replies. Comments and replies are
39
+ markdown: code in backticks or fences, lists, links, \`#12\`; raw HTML and
40
+ blocks (\`:::…\`, \`:button\`) show as written.`
39
41
 
40
42
  export default function comments(): Plugin {
41
43
  return {
@@ -43,7 +45,7 @@ export default function comments(): Plugin {
43
45
  docs: () => DOCS,
44
46
  events: {
45
47
  'comments:new': { handOut: true, description: 'a comment on a passage or lines of code: `{ quote, before, after, block, at?, text }`; its id is the thread\'s' },
46
- 'comments:reply': { handOut: true, description: 'a reply in a thread: `{ replyTo, text }`' },
48
+ 'comments:reply': { handOut: true, forReader: true, description: 'a reply in a thread: `{ replyTo, text }`' },
47
49
  'comments:resolve': { description: 'the reader closed a thread: `{ replyTo }`' },
48
50
  },
49
51
  style: STYLE,
@@ -11,6 +11,8 @@
11
11
  .wb-comment-badge { min-width: 24px; height: 24px; padding: 0 6px; border-radius: 12px 12px 12px 3px; font-size: .72rem; font-weight: 600; background: var(--bg, Canvas); color: var(--accent, #1d5bbf); border: 1px solid color-mix(in srgb, var(--accent, #1d5bbf) 50%, transparent); }
12
12
  .wb-comment-badge[data-agent] { background: var(--accent, #1d5bbf); color: var(--accent-text, #fff); }
13
13
  .wb-comment-badge[data-detached] { border-style: dashed; }
14
+ /* a reply the reader hasn't read: a dot on the badge until its thread is open and it is in view */
15
+ .wb-comment-badge[data-unread]::after { content: ''; position: absolute; top: -3px; right: -3px; width: 9px; height: 9px; border-radius: 50%; background: var(--bad, #c4352b); border: 2px solid var(--bg, Canvas); }
14
16
  .wb-thread { background: var(--bg, Canvas); border: 1px solid var(--border, #e3e5e9); border-radius: 8px; padding: 12px 14px; box-shadow: 0 8px 28px rgb(0 0 0 / .16); display: grid; gap: 10px; font-size: .9rem; }
15
17
  .wb-thread-quote { margin: 0; padding-left: 10px; border-left: 3px solid color-mix(in srgb, var(--accent, #1d5bbf) 50%, transparent); color: var(--muted, #696e76); font-size: .85rem; max-height: 6.5em; overflow: auto; white-space: pre-wrap; }
16
18
  .wb-thread-detached { margin: 0; color: var(--muted, #696e76); font-size: .8rem; }
@@ -18,6 +20,12 @@
18
20
  .wb-thread-who { font-size: .7rem; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--muted, #696e76); }
19
21
  .wb-thread-message[data-from=agent] .wb-thread-who { color: var(--accent, #1d5bbf); }
20
22
  .wb-thread-text { white-space: pre-wrap; line-height: 1.45; }
23
+ /* rendered from markdown: its paragraphs and code carry the spacing */
24
+ .wb-thread-text[data-md] { white-space: normal; overflow-wrap: anywhere; }
25
+ .wb-thread-text[data-md] > :first-child { margin-top: 0; }
26
+ .wb-thread-text[data-md] > :last-child { margin-bottom: 0; }
27
+ .wb-thread-text[data-md] :is(p, ul, ol, pre, blockquote) { margin: 0 0 .5em; }
28
+ .wb-thread-text[data-md] pre { font-size: .8rem; padding: 8px 10px; border-radius: 6px; overflow-x: auto; max-width: 100%; }
21
29
  .wb-thread textarea { width: 100%; resize: vertical; font: inherit; }
22
30
  .wb-thread-reply { display: grid; gap: 8px; margin: 0; }
23
31
  .wb-thread-actions { display: flex; gap: 8px; }
@@ -0,0 +1,12 @@
1
+ Issues and pull/merge requests of the project's GitHub or GitLab repository
2
+ link themselves: write `#12` for issue 12 and `!34` for pull or merge request
3
+ 34, as plain text. `owner/repo#12` and `group/project!34` point into another
4
+ repository on the same host. Inside code (`` `#12` ``) they stay text.
5
+
6
+ The repository is read from the project's `origin` remote, so a self-hosted
7
+ GitLab works too. Without such a remote they stay text; a config can say
8
+ which: `forge({ repo: 'group/project', host: 'gitlab.example.com', kind: 'gitlab' })`.
9
+
10
+ ```markdown
11
+ Fixed in !34, which closes #12 (see also bigmistqke/other#3).
12
+ ```