@bigmistqke/workpad 0.18.1 → 0.19.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 (55) hide show
  1. package/bin/workpad.ts +225 -21
  2. package/dist/bin/workpad.js +181 -15
  3. package/dist/plugins/badge/README.md +59 -10
  4. package/dist/plugins/badge/index.js +130 -8
  5. package/dist/plugins/badge/public/style.css +132 -12
  6. package/dist/plugins/chat/index.js +7 -1
  7. package/dist/plugins/claude/README.md +13 -5
  8. package/dist/plugins/claude/channel.js +25 -2
  9. package/dist/plugins/claude/doctor.js +43 -47
  10. package/dist/plugins/claude/index.js +24 -8
  11. package/dist/plugins/claude/session.js +46 -1
  12. package/dist/plugins/opencode/channel.js +42 -7
  13. package/dist/plugins/opencode/index.js +2 -0
  14. package/dist/src/agents.js +6 -1
  15. package/dist/src/events.js +6 -5
  16. package/dist/src/help.js +16 -4
  17. package/dist/src/hub.js +55 -2
  18. package/dist/src/listen.js +36 -4
  19. package/dist/src/listeners.js +14 -4
  20. package/dist/src/pages/board.js +9 -4
  21. package/dist/src/pages/index.js +2 -4
  22. package/dist/src/pages/markdown.js +47 -16
  23. package/dist/src/pages/render.js +1 -1
  24. package/dist/src/server.js +69 -6
  25. package/dist/src/state.js +2 -1
  26. package/dist/src/status.js +11 -2
  27. package/dist/src/turns.js +41 -0
  28. package/package.json +6 -1
  29. package/plugins/badge/README.md +59 -10
  30. package/plugins/badge/index.ts +141 -8
  31. package/plugins/badge/public/style.css +132 -12
  32. package/plugins/chat/index.ts +9 -1
  33. package/plugins/claude/README.md +13 -5
  34. package/plugins/claude/channel.ts +26 -2
  35. package/plugins/claude/doctor.ts +58 -39
  36. package/plugins/claude/index.ts +30 -8
  37. package/plugins/claude/session.ts +32 -0
  38. package/plugins/opencode/channel.ts +42 -7
  39. package/plugins/opencode/index.ts +4 -0
  40. package/skills/workpad/SKILL.md +23 -3
  41. package/src/agents.ts +7 -0
  42. package/src/define.ts +28 -1
  43. package/src/events.ts +23 -2
  44. package/src/help.ts +16 -4
  45. package/src/hub.ts +71 -2
  46. package/src/listen.ts +47 -4
  47. package/src/listeners.ts +22 -1
  48. package/src/pages/board.ts +10 -3
  49. package/src/pages/index.ts +8 -10
  50. package/src/pages/markdown.ts +55 -8
  51. package/src/pages/render.ts +1 -1
  52. package/src/server.ts +84 -6
  53. package/src/state.ts +3 -0
  54. package/src/status.ts +15 -1
  55. package/src/turns.ts +56 -0
@@ -295,13 +295,8 @@ function titleWords(nodes, resolve) {
295
295
  };
296
296
  return nodes.map(words).join("").replace(/\s*\u0000[\s\u0000]*/g, " ").trim();
297
297
  }
298
- /**
299
- * The forms a page asks the reader to answer, by name: `:::form{name=…}` containers and
300
- * hand-written <form name="…"> without an action. Parsed, so a form shown as an example inside a
301
- * code block doesn't count.
302
- */
303
- function formNames(source) {
304
- const tree = parseMarkdown(String(source ?? ""));
298
+ /** formNames of a source parsed already. */
299
+ function formNamesIn(tree) {
305
300
  const names = [];
306
301
  const walk = (node) => {
307
302
  if (node.type === "containerDirective" && node.name === "form") {
@@ -319,10 +314,10 @@ function formNames(source) {
319
314
  }
320
315
  /**
321
316
  * The `:::form`s in a source by the name they are written with, null for one without; in order, and
322
- * not those shown in a code fence. For a message's forms, which are named in their chat.
317
+ * not those shown in a code fence. For a message's forms, which are named in their chat. Kept: a
318
+ * status asks it of every agent message in every chat, and a message's text never changes.
323
319
  */
324
- function formsIn(source) {
325
- const text = String(source ?? "");
320
+ const formsIn = byText(5e3, (text) => {
326
321
  const out = [];
327
322
  const walk = (node) => {
328
323
  if (node.type === "containerDirective" && node.name === "form") {
@@ -337,7 +332,7 @@ function formsIn(source) {
337
332
  };
338
333
  walk(parseMarkdown(text));
339
334
  return out;
340
- }
335
+ });
341
336
  /** The text of nodes without the inline blocks in them (a form's inputs). */
342
337
  const plainText = (nodes) => nodes.map((n) => n.type === "textDirective" || n.type === "leafDirective" ? " " : n.children ? plainText(n.children) : n.value ?? "").join("").replace(/\s+/g, " ").trim();
343
338
  /** What one `:::form` node asks (FormDetail). */
@@ -375,15 +370,47 @@ function describeForm(node) {
375
370
  }
376
371
  /** What each `:::form` in a source asks, in order (not those shown in a code fence). */
377
372
  function formDetails(source) {
373
+ return formDetailsIn(parseMarkdown(String(source ?? "")));
374
+ }
375
+ /** formDetails of a source parsed already. */
376
+ function formDetailsIn(tree) {
378
377
  const out = [];
379
378
  const walk = (node) => {
380
379
  if (node.type === "containerDirective" && node.name === "form") out.push(describeForm(node));
381
380
  for (const child of node.children ?? []) walk(child);
382
381
  };
383
- walk(parseMarkdown(String(source ?? "")));
382
+ walk(tree);
384
383
  return out;
385
384
  }
386
385
  /**
386
+ * A page's questions, chats and forms, from one parse of its source. The same source is asked again
387
+ * after the config reloads, which a change to a plugin does: its answer is kept.
388
+ */
389
+ const pageAsks = byText(1e3, (source) => {
390
+ const tree = parseMarkdown(source);
391
+ return {
392
+ questions: formNamesIn(tree),
393
+ chats: chatNamesIn(tree),
394
+ forms: formDetailsIn(tree)
395
+ };
396
+ });
397
+ /**
398
+ * `fn` with its answers kept by the text it was asked about, the oldest dropped past `limit`: for
399
+ * what is read from a parse, asked again and again of the same pages and messages. What it answers
400
+ * is shared, never to be changed.
401
+ */
402
+ function byText(limit, fn) {
403
+ const kept = /* @__PURE__ */ new Map();
404
+ return (source) => {
405
+ const text = String(source ?? "");
406
+ if (kept.has(text)) return kept.get(text);
407
+ const value = fn(text);
408
+ if (kept.size >= limit) kept.delete(kept.keys().next().value);
409
+ kept.set(text, value);
410
+ return value;
411
+ };
412
+ }
413
+ /**
387
414
  * The forms in the agent's messages in `chats` (a page's chats, chatNames), by their names there:
388
415
  * `<chat>/<name>`, an unnamed one numbered in its chat (Api.message). They are questions of the
389
416
  * page as much as its own forms are.
@@ -414,8 +441,11 @@ function chatForms(events, page, chat) {
414
441
  * on the page.
415
442
  */
416
443
  function chatNames(source) {
417
- const tree = parseMarkdown(String(source ?? ""));
418
- const names = formNames(source);
444
+ return chatNamesIn(parseMarkdown(String(source ?? "")));
445
+ }
446
+ /** chatNames of a source parsed already. */
447
+ function chatNamesIn(tree) {
448
+ const names = formNamesIn(tree);
419
449
  const without = /* @__PURE__ */ new Set();
420
450
  const walk = (node) => {
421
451
  if (node.type === "containerDirective" && node.name === "form" && node.attributes?.chat === "false") without.add(node.attributes.name ?? "");
@@ -715,7 +745,8 @@ plugin "${name}" failed to compose around block "${block.name}": ${err.message}<
715
745
  inline,
716
746
  fileUrl,
717
747
  anchor,
718
- chat: inChat
748
+ chat: inChat,
749
+ problem
719
750
  };
720
751
  /**
721
752
  * Attributes a block doesn't read (Block.attrs), when it says which it does: a typo, or one from
@@ -860,4 +891,4 @@ plugin "${name}" failed to compose around block "${block.name}": ${err.message}<
860
891
  problems
861
892
  };
862
893
  }
863
- export { chatForms, chatNames, formDetails, formNames, formSource, formsIn, messageForms, parseAttrs, parseMarkdown, renderMarkdown, slug, titleWords };
894
+ export { chatForms, chatNames, formDetails, formSource, formsIn, messageForms, pageAsks, parseAttrs, parseMarkdown, renderMarkdown, slug, titleWords };
@@ -362,7 +362,7 @@ function card(c, withProject) {
362
362
  <a class="wp-board-title" href="${c.page.url}">${c.page.title}</a>
363
363
  ${counts(c.waiting, `${c.page.url}#wp-waiting`)}
364
364
  ${withProject && html`<span class="wp-board-project">${c.project.label}</span>`}
365
- <span class="wp-meta wp-board-when">edited ${time(c.page.mtime)}</span>
365
+ <span class="wp-meta wp-board-when">updated ${time(c.page.updated)}</span>
366
366
  </li>`;
367
367
  }
368
368
  function cards(list, withProject) {
@@ -12,7 +12,7 @@ import { SCROLL, SUBSCRIBE, agentMessagesIn, awaiting, handledIds, isAgentMessag
12
12
  import { formsIn, messageForms } from "./pages/markdown.js";
13
13
  import { fileFilter } from "./files.js";
14
14
  import { titleOf } from "./pages/render.js";
15
- import { createRegistry, holdStream, listenerOf } from "./listeners.js";
15
+ import { createRegistry, follows, holdStream, listenerOf } from "./listeners.js";
16
16
  import { inPublic } from "./public.js";
17
17
  import { build } from "./build.js";
18
18
  import { PAGE_CLIENT, RUNTIME, frontmatterOf, pageDocument, pluginParts } from "./document.js";
@@ -243,10 +243,8 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
243
243
  let chats;
244
244
  let details = [];
245
245
  try {
246
- const source = pageSource(id, file);
247
- asks = renderer?.questions(source) ?? [];
248
- chats = renderer?.chats(source);
249
- details = renderer?.forms(source) ?? [];
246
+ const said = renderer?.asks(pageSource(id, file));
247
+ if (said) ({questions: asks, chats, forms: details} = said);
250
248
  } catch (err) {
251
249
  console.error("questions:", err);
252
250
  }
@@ -267,15 +265,23 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
267
265
  async function snapshot(listed) {
268
266
  const { pages: renderer, handedOut, forReader } = await config();
269
267
  const events = readEvents(project.eventsFile);
268
+ const messages = /* @__PURE__ */ new Map();
269
+ for (const e of events) {
270
+ if (!isAgentMessage(e)) continue;
271
+ const own = messages.get(e.page);
272
+ if (own) own.push(e);
273
+ else messages.set(e.page, [e]);
274
+ }
270
275
  const pages = listed.map((p) => {
271
276
  const page = {
272
277
  id: p.id,
273
278
  file: p.file,
274
279
  ...questionsOf(renderer, p.id, p.file)
275
280
  };
281
+ const forms = messageForms(messages.get(p.id) ?? [], p.id, page.chats ?? []);
276
282
  return {
277
283
  ...page,
278
- asks: [...page.asks, ...messageForms(events, p.id, page.chats ?? [])]
284
+ asks: [...page.asks, ...forms]
279
285
  };
280
286
  });
281
287
  return projectStatus({
@@ -537,6 +543,48 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
537
543
  /** the codes of pings sent and not confirmed yet: the channel each went to */
538
544
  const pings = /* @__PURE__ */ new Map();
539
545
  const pingCode = () => crypto.randomBytes(3).toString("hex");
546
+ const unfollowing = /* @__PURE__ */ new Set();
547
+ let looking = false;
548
+ function lookAgain() {
549
+ if (looking || !unfollowing.size) return;
550
+ looking = true;
551
+ setImmediate(() => {
552
+ looking = false;
553
+ const pages = pagesIn(project.pagesDir).map((p) => p.id).filter((id) => !registry.list(id).some((l) => follows(l, id)));
554
+ for (const u of unfollowing) {
555
+ for (const [page, release] of u.held) if (!pages.includes(page)) {
556
+ release();
557
+ u.held.delete(page);
558
+ }
559
+ for (const page of pages) if (!u.held.has(page)) u.held.set(page, registry.add({
560
+ ...u.listener,
561
+ page,
562
+ unfollowed: true
563
+ }));
564
+ const now = JSON.stringify(pages);
565
+ if (now !== u.told) {
566
+ u.told = now;
567
+ u.onPages(pages);
568
+ }
569
+ }
570
+ });
571
+ }
572
+ registry.onChange(lookAgain);
573
+ function unfollowed(listener, onPages) {
574
+ const u = {
575
+ listener,
576
+ onPages,
577
+ held: /* @__PURE__ */ new Map(),
578
+ told: null
579
+ };
580
+ unfollowing.add(u);
581
+ lookAgain();
582
+ return () => {
583
+ if (!unfollowing.delete(u)) return;
584
+ for (const release of u.held.values()) release();
585
+ u.held.clear();
586
+ };
587
+ }
540
588
  const clients = /* @__PURE__ */ new Set();
541
589
  /** what the browser appended lately, by id: a send it retries is answered with what it got */
542
590
  const appended = /* @__PURE__ */ new Map();
@@ -557,6 +605,7 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
557
605
  });
558
606
  function pageChanged(id) {
559
607
  onChange?.();
608
+ lookAgain();
560
609
  for (const c of clients) if (c.isDir ? !c.page || id.startsWith(c.page + "/") : c.page === id || c.page + "/index" === id) notify(c, "change");
561
610
  for (const c of clients) if (c.isDir && !c.page) notify(c, "change");
562
611
  }
@@ -929,6 +978,19 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
929
978
  if (p === "/api/status") return sendJson(res, 200, await status(q.page || null));
930
979
  if (p === "/api/listeners") return sendJson(res, 200, listenersFor(q.page ?? null));
931
980
  if (p === "/api/stamps") return sendJson(res, 200, stamps());
981
+ if (p === "/api/listen" && url.searchParams.has("unfollowed")) {
982
+ const stop = unfollowed(listenerOf(url.searchParams), (pages) => stream.send("pages", { projects: pages.length ? [{
983
+ dir: project.dir,
984
+ base,
985
+ pages
986
+ }] : [] }));
987
+ const stream = holdStream(req, res, () => {
988
+ stop();
989
+ streams.delete(stream.end);
990
+ });
991
+ streams.add(stream.end);
992
+ return;
993
+ }
932
994
  if (p === "/api/listen") {
933
995
  const remove = registry.add(listenerOf(url.searchParams));
934
996
  const stream = holdStream(req, res, () => {
@@ -1084,6 +1146,7 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
1084
1146
  elsewhere: () => notifyAll("elsewhere"),
1085
1147
  addListener: (l) => registry.add(l),
1086
1148
  onListeners: (fn) => registry.onChange(fn),
1149
+ unfollowed,
1087
1150
  status: (page = null) => status(page),
1088
1151
  read: readList,
1089
1152
  stream,
package/dist/src/state.js CHANGED
@@ -128,7 +128,8 @@ function subscriptionsOf(s) {
128
128
  agent: e.by,
129
129
  page: e.page,
130
130
  since: e.ts,
131
- channel: !!e.data?.channel
131
+ channel: !!e.data?.channel,
132
+ ...e.data?.unfollowed ? { unfollowed: true } : {}
132
133
  }));
133
134
  }
134
135
  /** Everyone the board knows, in the order the log first names them, then those only listening. */
@@ -163,7 +163,7 @@ function receivedIds(events) {
163
163
  function channelSince(events, agent, page) {
164
164
  let since = null;
165
165
  for (const e of subscriptions(events)) {
166
- if (e.by !== agent) continue;
166
+ if (e.by !== agent || e.data?.unfollowed) continue;
167
167
  if (!(e.page === "" || e.page === page || page.startsWith(`${e.page}/`))) continue;
168
168
  if (!e.data?.channel) return null;
169
169
  since ??= e.id;
@@ -171,6 +171,13 @@ function channelSince(events, agent, page) {
171
171
  return since;
172
172
  }
173
173
  /**
174
+ * Does `agent` take the pages no one follows through its channel (`workpad listen --unfollowed
175
+ * --channel`)? Said by a subscription on every page (`''`) with data `{ channel: true, unfollowed:
176
+ * true }`; it makes no page the agent's (no subscriber of any), and `workpad agent unsubscribe`
177
+ * takes it off with the rest.
178
+ */
179
+ const takesUnfollowed = (events, agent) => subscriptions(events).some((e) => e.by === agent && !!e.data?.unfollowed);
180
+ /**
174
181
  * The ids of the reader's events the agent handled: acknowledged (`workpad:handled`), or replied
175
182
  * to after them (see the top of this file). The log is gone through once: each of the reader's
176
183
  * events is filed under what a reply would name (its id, its thread, its chat, its form), and an
@@ -244,6 +251,7 @@ function projectStatus({ pages, events, listeners, forAgent, forReader }) {
244
251
  if (fromReader(e)) last.set(e.page, e.ts);
245
252
  }
246
253
  for (const e of subscriptions(events)) {
254
+ if (e.data?.unfollowed) continue;
247
255
  const now = subscribers.get(e.page) ?? [];
248
256
  if (!now.includes(e.by)) subscribers.set(e.page, [...now, e.by]);
249
257
  }
@@ -281,6 +289,7 @@ function projectStatus({ pages, events, listeners, forAgent, forReader }) {
281
289
  unreceived: own.filter((e) => fromReader(e) && forAgent(e.type) && !received.has(e.id) && !handled.has(e.id)),
282
290
  unhandled: own.filter((e) => fromReader(e) && forAgent(e.type) && received.has(e.id) && !handled.has(e.id)),
283
291
  awaitingReply: awaitingReply(own),
292
+ updated: own.findLast((e) => !fromReader(e) && !e.type.startsWith("workpad:"))?.ts ?? null,
284
293
  listeners: listening
285
294
  };
286
295
  })
@@ -320,4 +329,4 @@ function agentMessagesIn(events, page, chat) {
320
329
  const replaced = new Set(own.map((e) => e.data.replaces).filter(Boolean).map(String));
321
330
  return own.filter((e) => !replaced.has(e.id));
322
331
  }
323
- export { CHAT_MESSAGE, HANDLED, HOLD, NAME, READ, RECEIVED, RELEASE, SCROLL, SETTLE, SUBSCRIBE, UNSUBSCRIBE, agentMessagesIn, awaiting, awaitingReply, channelSince, covers, fromReader, handledIds, heard, holdOf, isAgentMessage, isQuestionName, namesOf, projectStatus, questionState, receivedIds, settleNested, statusLines, subscriptions, unreadMessages, whose };
332
+ export { CHAT_MESSAGE, HANDLED, HOLD, NAME, READ, RECEIVED, RELEASE, SCROLL, SETTLE, SUBSCRIBE, UNSUBSCRIBE, agentMessagesIn, awaiting, awaitingReply, channelSince, covers, fromReader, handledIds, heard, holdOf, isAgentMessage, isQuestionName, namesOf, projectStatus, questionState, receivedIds, settleNested, statusLines, subscriptions, takesUnfollowed, unreadMessages, whose };
@@ -0,0 +1,41 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ // src/turns.ts
4
+ const dirOf = (wp) => path.join(wp, "turns");
5
+ const fileOf = (wp, session) => path.join(dirOf(wp), encodeURIComponent(session));
6
+ /** Records older than this go when a turn end is written: their sessions are long over. */
7
+ const KEEP = 6048e5;
8
+ /**
9
+ * Record for `session` that its turn ended now (`ended`), or only that its turn ends are recorded
10
+ * (a mark: an end recorded before stays).
11
+ */
12
+ function recordTurn(wp, session, ended) {
13
+ if (!session) return;
14
+ const dir = dirOf(wp);
15
+ const file = fileOf(wp, session);
16
+ if (!ended && fs.existsSync(file)) return;
17
+ if (!fs.existsSync(dir)) {
18
+ fs.mkdirSync(dir, { recursive: true });
19
+ fs.writeFileSync(path.join(dir, ".gitignore"), "# when each agent session's turn last ended; not for git\n*\n");
20
+ }
21
+ if (ended) {
22
+ for (const name of fs.readdirSync(dir)) if (name !== ".gitignore" && Date.now() - fs.statSync(path.join(dir, name)).mtimeMs > KEEP) fs.rmSync(path.join(dir, name), { force: true });
23
+ }
24
+ fs.writeFileSync(`${file}.tmp`, ended ? String(Date.now()) : "");
25
+ fs.renameSync(`${file}.tmp`, file);
26
+ }
27
+ /**
28
+ * What is recorded of `session`'s turns: null when nothing is (its turn ends aren't recorded);
29
+ * else when its last turn ended, null when none has since it was marked.
30
+ */
31
+ function lastTurnEnd(wp, session) {
32
+ let text;
33
+ try {
34
+ text = fs.readFileSync(fileOf(wp, session), "utf8");
35
+ } catch {
36
+ return null;
37
+ }
38
+ const ended = Number(text);
39
+ return { ended: text && Number.isFinite(ended) ? ended : null };
40
+ }
41
+ export { lastTurnEnd, recordTurn };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bigmistqke/workpad",
3
- "version": "0.18.1",
3
+ "version": "0.19.0",
4
4
  "description": "A workpad 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",
@@ -84,6 +84,11 @@
84
84
  "source": "./plugins/code/index.ts",
85
85
  "types": "./plugins/code/index.ts",
86
86
  "default": "./dist/plugins/code/index.js"
87
+ },
88
+ "./badge": {
89
+ "source": "./plugins/badge/index.ts",
90
+ "types": "./plugins/badge/index.ts",
91
+ "default": "./dist/plugins/badge/index.js"
87
92
  }
88
93
  },
89
94
  "files": [
@@ -1,7 +1,6 @@
1
- A status as a coloured dot and a word, inline wherever text goes: in a
2
- heading, a table cell, a list item, a sentence. `done ok yes good` are
3
- green, `active new info` blue, `open todo maybe warning` amber,
4
- `blocked no bad error` red; any other word is grey.
1
+ A status as a word, small and inline wherever text goes: in a heading, a
2
+ table cell, a list item, a sentence. A grey dot before it, unless it says
3
+ otherwise.
5
4
 
6
5
  ```markdown
7
6
  ### Parser :badge[done]
@@ -15,12 +14,6 @@ green, `active new info` blue, `open todo maybe warning` amber,
15
14
  The release is :badge[blocked] on review.
16
15
  ```
17
16
 
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-wp-title` attribute on it. A badge is not
21
- in a heading's anchor, nor in an item's: `### Parser :badge[done]` is
22
- `#parser`, so a link to it holds while the badge changes.
23
-
24
17
  ### Parser :badge[done]
25
18
 
26
19
  | step | state |
@@ -30,3 +23,59 @@ in a heading's anchor, nor in an item's: `### Parser :badge[done]` is
30
23
  | docs | :badge[todo] |
31
24
 
32
25
  The release is :badge[blocked] on review.
26
+
27
+ Its look, each attribute off unless set, each colour a name from the
28
+ palette `red orange yellow green blue violet pink grey` (tuned per theme, so
29
+ the text reads on the page and on a fill):
30
+
31
+ - `color`: the dot and the text.
32
+ - `background`: a fill behind them; the text takes the palette's readable
33
+ shade for it, so `{background=red}` alone is a red pill.
34
+ - `border`: an outline.
35
+ - `live`: the dot pulses (still for a reader who asks for less motion).
36
+
37
+ A fill or an outline stands without the dot, unless it is `live`.
38
+
39
+ ```markdown
40
+ :badge[busy]{color=green live} :badge[you]{background=red} :badge[on hold]{color=orange border=orange}
41
+ ```
42
+
43
+ :badge[busy]{color=green live} :badge[you]{background=red} :badge[on hold]{color=orange border=orange}
44
+
45
+ **Presets** name looks, in the config: a badge whose word is the name takes
46
+ its preset (`:badge[you]`, the word as its text lowercased, other characters
47
+ a `-`), and so does one that names it (`:badge[Jonathan]{preset=person}`). A
48
+ preset sets any of the badge's own attributes, and nothing else.
49
+
50
+ ```ts
51
+ // .workpad/config.ts
52
+ import badge from '@bigmistqke/workpad/badge'
53
+
54
+ export default defineConfig({
55
+ plugins: [
56
+ badge({
57
+ presets: {
58
+ you: { background: 'red' },
59
+ 'on hold': { color: 'orange', border: 'orange' },
60
+ busy: { color: 'green', live: true },
61
+ person: { color: 'violet' },
62
+ },
63
+ }),
64
+ ],
65
+ })
66
+ ```
67
+
68
+ The built-in words are presets too: `done ok yes good` green,
69
+ `active new info` blue, `open todo maybe warning` orange,
70
+ `blocked no bad error` red. A project's preset of the same word replaces one.
71
+
72
+ Most specific wins, attribute by attribute: the badge's own attributes, then
73
+ its `preset=`, then its word's preset. An unknown colour, preset or attribute
74
+ is listed by `workpad check` and shown above the page; a bad preset stops the
75
+ config from loading, saying which.
76
+
77
+ A badge that ends a heading sits at its right edge: a page's heading, a grid
78
+ card's, a timeline step's. A block of your own can have the same for a title
79
+ that isn't a heading, with a `data-wp-title` attribute on it. A badge is not
80
+ in a heading's anchor, nor in an item's: `### Parser :badge[done]` is
81
+ `#parser`, so a link to it holds while the badge changes.
@@ -4,7 +4,43 @@ import { definePlugin, type Plugin } from '@bigmistqke/workpad'
4
4
  import { html, raw, type DirectiveContext } from '@bigmistqke/workpad'
5
5
  import { builtinPublic } from '../../src/package.ts'
6
6
 
7
- /** The word a badge's colour is chosen by: its text, lowercased, runs of other characters a `-`. */
7
+ /** The colours a badge takes, by name; each tuned per theme for readable text (style.css). */
8
+ export const PALETTE = ['red', 'orange', 'yellow', 'green', 'blue', 'violet', 'pink', 'grey'] as const
9
+ export type Colour = (typeof PALETTE)[number]
10
+
11
+ /**
12
+ * How a badge looks, each part off unless set: `color` the dot and the text, `background` a fill
13
+ * (its text then the palette's readable shade for it), `border` an outline, `live` a pulsing dot.
14
+ * What a badge's attributes say, and what a preset sets.
15
+ */
16
+ export interface Look {
17
+ color?: Colour
18
+ background?: Colour
19
+ border?: Colour
20
+ live?: boolean
21
+ }
22
+
23
+ export interface BadgeOptions {
24
+ /**
25
+ * Looks by name: a badge whose word is the name takes it (`:badge[you]`), and so does one that
26
+ * names it (`:badge[Jonathan]{preset=person}`). They replace the built-in words of the same name.
27
+ */
28
+ presets?: Record<string, Look>
29
+ }
30
+
31
+ const COLOURED = ['color', 'background', 'border'] as const
32
+ const KEYS = [...COLOURED, 'live']
33
+ const palette = PALETTE.join(', ')
34
+
35
+ /** The built-in words: default presets, which a project's presets replace word by word. */
36
+ export const BUILTIN_PRESETS: Record<string, Look> = Object.fromEntries([
37
+ ...['done', 'ok', 'yes', 'good'].map(w => [w, { color: 'green' }]),
38
+ ...['active', 'new', 'info'].map(w => [w, { color: 'blue' }]),
39
+ ...['open', 'todo', 'maybe', 'warning'].map(w => [w, { color: 'orange' }]),
40
+ ...['blocked', 'no', 'bad', 'error'].map(w => [w, { color: 'red' }]),
41
+ ])
42
+
43
+ /** The word a badge's preset is found by: its text, lowercased, runs of other characters a `-`. */
8
44
  export const tone = (s: string) =>
9
45
  s
10
46
  .toLowerCase()
@@ -12,25 +48,122 @@ export const tone = (s: string) =>
12
48
  .replace(/[^a-z0-9]+/g, '-')
13
49
  .replace(/^-|-$/g, '')
14
50
 
15
- /** `:badge[done]`: a coloured dot and a word, inline wherever text goes. */
16
- export function render(ctx: DirectiveContext) {
51
+ const isColour = (v: unknown): v is Colour => typeof v === 'string' && (PALETTE as readonly string[]).includes(v)
52
+
53
+ /**
54
+ * A config's presets, checked, by their words (tone()), over the built-in words: what is wrong
55
+ * throws, so the config fails to load and says why.
56
+ */
57
+ export function presetsOf(given: Record<string, Look> = {}): Record<string, Look> {
58
+ if (typeof given !== 'object' || given === null || Array.isArray(given))
59
+ throw new Error('badge: `presets` is an object of looks by name: `{ you: { background: "red" } }`')
60
+ const own: Record<string, Look> = {}
61
+ const named: Record<string, string> = {}
62
+ for (const [name, look] of Object.entries(given)) {
63
+ const word = tone(name)
64
+ const where = `badge: preset "${name}"`
65
+ if (!word) throw new Error(`${where} has no letter or digit: a badge's word couldn't reach it`)
66
+ if (word in named) throw new Error(`${where} is the same word as "${named[word]}" (${word})`)
67
+ named[word] = name
68
+ if (typeof look !== 'object' || look === null || Array.isArray(look))
69
+ throw new Error(`${where} is a look: an object such as \`{ color: 'green' }\``)
70
+ for (const [k, v] of Object.entries(look)) {
71
+ if (!KEYS.includes(k))
72
+ throw new Error(`${where} sets \`${k}\`, which a badge hasn't: a preset sets ${KEYS.join(', ')}`)
73
+ if (k === 'live' ? typeof v !== 'boolean' : !isColour(v))
74
+ throw new Error(
75
+ k === 'live'
76
+ ? `${where} has \`live: ${JSON.stringify(v)}\`: it is true or false`
77
+ : `${where} has no colour ${JSON.stringify(v)} for \`${k}\`: the palette is ${palette}`,
78
+ )
79
+ }
80
+ own[word] = { ...look }
81
+ }
82
+ return { ...BUILTIN_PRESETS, ...own }
83
+ }
84
+
85
+ /**
86
+ * The look of a badge of `text` with `attrs`, attribute by attribute the most specific: its own
87
+ * attributes, then the preset it names (`preset=`), then its word's preset (the built-in words
88
+ * among them). A value it doesn't know is reported, and the next one down holds.
89
+ */
90
+ export function lookOf(
91
+ text: string,
92
+ attrs: Record<string, string>,
93
+ presets: Record<string, Look>,
94
+ report: (problem: string) => void = () => {},
95
+ ): Look {
96
+ const written = `\`:badge[${text}]\``
97
+ const own: Look = {}
98
+ for (const k of COLOURED) {
99
+ const v = attrs[k]
100
+ if (v === undefined) continue
101
+ if (isColour(v)) own[k] = v
102
+ else report(`${written} has no colour \`${v}\` for \`${k}\`: the palette is ${palette}`)
103
+ }
104
+ if (attrs.live !== undefined) {
105
+ if (attrs.live === '' || attrs.live === 'true') own.live = true
106
+ else if (attrs.live === 'false') own.live = false
107
+ else report(`${written} has \`live=${attrs.live}\`: it is \`{live}\` or \`{live=false}\``)
108
+ }
109
+ let named: Look = {}
110
+ if (attrs.preset !== undefined) {
111
+ const found = presets[tone(attrs.preset)]
112
+ if (found) named = found
113
+ else
114
+ report(
115
+ `${written} names no preset \`${attrs.preset}\`: there are ${Object.keys(presets)
116
+ .map(p => `\`${p}\``)
117
+ .join(', ')}`,
118
+ )
119
+ }
120
+ const look: Look = {}
121
+ for (const layer of [presets[tone(text)] ?? {}, named, own])
122
+ for (const [k, v] of Object.entries(layer)) if (v !== undefined) (look as any)[k] = v
123
+ return look
124
+ }
125
+
126
+ /** `:badge[done]`: a word, with a coloured dot, a fill or an outline, inline wherever text goes. */
127
+ export function render(ctx: DirectiveContext, presets: Record<string, Look> = BUILTIN_PRESETS) {
17
128
  const text = ctx.labelText?.trim()
18
129
  if (!text) return html``
19
- // the label is HTML already; its plain text picks the colour
20
- return html`<span class="wp-badge" data-badge="${tone(text)}">${raw(ctx.label ?? '')}</span>`
130
+ const look = lookOf(text, ctx.attrs, presets, p => ctx.problem(p))
131
+ // a built-in word's colour is its dot's only, its text stays grey; a colour written on the
132
+ // badge, or by a preset of the project's, colours the text too
133
+ const word = tone(text)
134
+ const builtin =
135
+ presets[word] !== undefined &&
136
+ presets[word] === BUILTIN_PRESETS[word] &&
137
+ ctx.attrs.color === undefined &&
138
+ (ctx.attrs.preset === undefined || presets[tone(ctx.attrs.preset)]?.color === undefined)
139
+ // what it shows, as data-* the stylesheet reads: only what is set
140
+ const shows = html`${COLOURED.map(k => look[k] && html` data-${k}="${look[k]}"`)}${look.live && html` data-live`}${builtin && look.color && html` data-dot`}`
141
+ // the label is HTML already; its plain text picks the preset
142
+ const label = raw(ctx.label ?? '')
143
+ // unformatted: prettier would put a space before ${shows}, which brings its own
144
+ // prettier-ignore
145
+ return html`<span class="wp-badge" data-badge="${tone(text)}"${shows}>${label}</span>`
21
146
  }
22
147
 
23
- export default function badge(): Plugin {
148
+ export default function badge(options: BadgeOptions = {}): Plugin {
149
+ const presets = presetsOf(options.presets)
150
+ const own = Object.keys(options.presets ?? {})
24
151
  return definePlugin({
25
152
  name: 'badge',
26
153
  public: builtinPublic('badge'),
27
154
  blocks: {
28
155
  badge: {
29
156
  menu: { group: 'mark', summary: 'a status in a word: done, todo, waiting' },
30
- html: render,
157
+ attrs: ['color', 'background', 'border', 'live', 'preset'],
158
+ html: ctx => render(ctx as DirectiveContext, presets),
31
159
  style: 'style.css',
32
160
  },
33
161
  },
34
- docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
162
+ docs: () => {
163
+ const readme = fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8')
164
+ if (!own.length) return readme
165
+ const list = own.map(name => `- \`${name}\`: ${JSON.stringify(options.presets![name])}`).join('\n')
166
+ return `${readme}\nThis project's presets:\n\n${list}\n`
167
+ },
35
168
  })
36
169
  }