@bigmistqke/workpad 0.18.1 → 0.20.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 (109) hide show
  1. package/README.md +18 -9
  2. package/bin/workpad.ts +412 -58
  3. package/dist/bin/workpad.js +336 -46
  4. package/dist/client/runtime.js +141 -18
  5. package/dist/plugins/badge/README.md +59 -10
  6. package/dist/plugins/badge/index.js +130 -8
  7. package/dist/plugins/badge/public/style.css +132 -12
  8. package/dist/plugins/chat/README.md +7 -3
  9. package/dist/plugins/chat/index.js +8 -1
  10. package/dist/plugins/chat/public/client.js +2 -2
  11. package/dist/plugins/chat/public/style.css +10 -0
  12. package/dist/plugins/claude/README.md +13 -5
  13. package/dist/plugins/claude/channel.js +47 -6
  14. package/dist/plugins/claude/doctor.js +43 -47
  15. package/dist/plugins/claude/index.js +24 -8
  16. package/dist/plugins/claude/session.js +46 -1
  17. package/dist/plugins/comments/README.md +2 -1
  18. package/dist/plugins/comments/index.js +2 -0
  19. package/dist/plugins/comments/public/client.js +6 -5
  20. package/dist/plugins/comments/public/style.css +9 -0
  21. package/dist/plugins/form/README.md +1 -1
  22. package/dist/plugins/index.js +3 -1
  23. package/dist/plugins/opencode/channel.js +43 -7
  24. package/dist/plugins/opencode/index.js +2 -0
  25. package/dist/plugins/progress/README.md +41 -0
  26. package/dist/plugins/progress/index.js +117 -0
  27. package/dist/plugins/progress/public/client.js +1 -0
  28. package/dist/plugins/progress/public/style.css +85 -0
  29. package/dist/plugins/progress/state.js +210 -0
  30. package/dist/solid/index.js +3 -1
  31. package/dist/src/agents.js +13 -4
  32. package/dist/src/anchors.js +25 -1
  33. package/dist/src/build.js +1 -1
  34. package/dist/src/client/page/base.css +48 -2
  35. package/dist/src/client/page/main.js +58 -30
  36. package/dist/src/document.js +6 -4
  37. package/dist/src/events.js +22 -11
  38. package/dist/src/help.js +59 -12
  39. package/dist/src/hub.js +69 -3
  40. package/dist/src/listen.js +36 -4
  41. package/dist/src/listeners.js +14 -4
  42. package/dist/src/loader.js +7 -2
  43. package/dist/src/migrate.js +1 -1
  44. package/dist/src/pages/board.js +9 -4
  45. package/dist/src/pages/index.js +2 -4
  46. package/dist/src/pages/markdown.js +50 -19
  47. package/dist/src/pages/render.js +17 -1
  48. package/dist/src/server.js +94 -18
  49. package/dist/src/set.js +99 -0
  50. package/dist/src/state.js +2 -1
  51. package/dist/src/status.js +57 -9
  52. package/dist/src/turns.js +41 -0
  53. package/package.json +11 -1
  54. package/plugins/README.md +3 -1
  55. package/plugins/badge/README.md +59 -10
  56. package/plugins/badge/index.ts +141 -8
  57. package/plugins/badge/public/style.css +132 -12
  58. package/plugins/chat/README.md +7 -3
  59. package/plugins/chat/client.tsx +20 -3
  60. package/plugins/chat/index.ts +10 -1
  61. package/plugins/chat/public/style.css +10 -0
  62. package/plugins/claude/README.md +13 -5
  63. package/plugins/claude/channel.ts +45 -7
  64. package/plugins/claude/doctor.ts +58 -39
  65. package/plugins/claude/index.ts +30 -8
  66. package/plugins/claude/session.ts +32 -0
  67. package/plugins/comments/README.md +2 -1
  68. package/plugins/comments/client.ts +19 -0
  69. package/plugins/comments/index.ts +7 -1
  70. package/plugins/comments/public/style.css +9 -0
  71. package/plugins/form/README.md +1 -1
  72. package/plugins/index.ts +2 -0
  73. package/plugins/opencode/channel.ts +44 -8
  74. package/plugins/opencode/index.ts +4 -0
  75. package/plugins/progress/README.md +41 -0
  76. package/plugins/progress/client.ts +172 -0
  77. package/plugins/progress/index.ts +166 -0
  78. package/plugins/progress/public/style.css +85 -0
  79. package/plugins/progress/state.ts +278 -0
  80. package/skills/workpad/SKILL.md +149 -18
  81. package/solid/index.tsx +6 -2
  82. package/src/agents.ts +24 -2
  83. package/src/anchors.ts +32 -0
  84. package/src/build.ts +1 -1
  85. package/src/client/delivery.ts +49 -0
  86. package/src/client/forms.ts +18 -11
  87. package/src/client/page/base.css +48 -2
  88. package/src/client/page/waiting.ts +45 -25
  89. package/src/client/read.ts +9 -5
  90. package/src/client/runtime.ts +7 -3
  91. package/src/client/toast.ts +27 -3
  92. package/src/define.ts +120 -9
  93. package/src/document.ts +19 -5
  94. package/src/events.ts +47 -6
  95. package/src/help.ts +58 -11
  96. package/src/hub.ts +80 -2
  97. package/src/listen.ts +47 -4
  98. package/src/listeners.ts +22 -1
  99. package/src/loader.ts +14 -4
  100. package/src/migrate.ts +1 -1
  101. package/src/pages/board.ts +12 -3
  102. package/src/pages/index.ts +8 -10
  103. package/src/pages/markdown.ts +59 -12
  104. package/src/pages/render.ts +20 -2
  105. package/src/server.ts +127 -19
  106. package/src/set.ts +118 -0
  107. package/src/state.ts +3 -0
  108. package/src/status.ts +115 -14
  109. package/src/turns.ts +56 -0
@@ -102,23 +102,82 @@ function questionState(name, events, listeners, marks) {
102
102
  hold
103
103
  };
104
104
  }
105
+ /** Does anyone listen for the answer to question `name`? Not: it is unheard. */
106
+ const heard = (name, listeners) => listeners.some((l) => l.type === null || l.type === name);
107
+ /**
108
+ * After how long an answer no agent received is late, in ms: the page flags it ("not received after
109
+ * 10 min") and counts it, as something went wrong on the agent's side (a session gone, a channel
110
+ * down, a server under load).
111
+ */
112
+ const NOT_RECEIVED_AFTER = 6e5;
113
+ /**
114
+ * Where one of the reader's events for an agent went (Delivery), at time `now` (ms): from its marks
115
+ * (received, handled; `receivedBy`), whether it is still on its way (`sending`), and who listens on
116
+ * its page (`listeners`, those covering it). Someone takes it when a listener hears its type
117
+ * (heard): a listen on the page, a confirmed channel, also a coordinator's listen on the unfollowed
118
+ * pages, which follows the page for no one but does receive what is sent there.
119
+ */
120
+ function deliveryOf(e, listeners, now, after = NOT_RECEIVED_AFTER) {
121
+ if (e.sending) return {
122
+ state: "sending",
123
+ text: "sending…"
124
+ };
125
+ if (e.handled) return {
126
+ state: "handled",
127
+ text: "handled"
128
+ };
129
+ if (e.received) return e.receivedBy ? {
130
+ state: "received",
131
+ text: `received by ${e.receivedBy}`,
132
+ by: e.receivedBy
133
+ } : {
134
+ state: "received",
135
+ text: "received"
136
+ };
137
+ const nobody = !heard(e.type, listeners);
138
+ if (now - Date.parse(e.ts) >= after) return {
139
+ state: "late",
140
+ text: `not received after ${Math.round(after / 6e4)} min${nobody ? " · no one follows this page" : ""}`,
141
+ nobody
142
+ };
143
+ return nobody ? {
144
+ state: "unfollowed",
145
+ text: "no one follows this page — it waits until an agent listens"
146
+ } : {
147
+ state: "waiting",
148
+ text: "waiting for an agent to receive it"
149
+ };
150
+ }
105
151
  /** The type of the event the page appends once messages were in view: `{ ids }`. */
106
152
  const READ = "workpad:read";
107
153
  /**
108
- * The agent's messages on a page the reader hasn't read: events from the agent of a type
109
- * `isMessage` says is for the reader, not named by a `workpad:read` from the reader, not
110
- * replaced by a later one (`replaces`), and, given the page's `chats`, not in a chat (`data.chat`)
111
- * that is no longer among them.
154
+ * The fields of an event's `data` its type requires (EventSpec.requires) that it lacks: each must
155
+ * be a non-empty string.
156
+ */
157
+ const missingData = (data, requires) => requires.filter((field) => {
158
+ const value = data?.[field];
159
+ return typeof value !== "string" || !value.trim();
160
+ });
161
+ /**
162
+ * The agent's messages on a page the reader hasn't read: events from the agent of a type in
163
+ * `messages` (the types for the reader, each with the `data` fields it requires), not named by a
164
+ * `workpad:read` from the reader, not replaced by a later one (`replaces`), with the data their
165
+ * type requires (one without it shows nowhere on the page, so it waits for nobody), and, given the
166
+ * page's `chats`, not in a chat (`data.chat`) that is no longer among them.
112
167
  */
113
- function unreadMessages(events, isMessage, chats) {
168
+ function unreadMessages(events, messages, chats) {
114
169
  const read = /* @__PURE__ */ new Set();
115
170
  const replaced = /* @__PURE__ */ new Set();
116
171
  for (const e of events) {
117
172
  if (e.type === "workpad:read" && fromReader(e)) for (const id of e.data?.ids ?? []) read.add(String(id));
118
173
  if (e.data?.replaces) replaced.add(String(e.data.replaces));
119
174
  }
175
+ const shown = (e) => {
176
+ const requires = messages.get(e.type);
177
+ return !!requires && !missingData(e.data, requires).length;
178
+ };
120
179
  const offPage = (e) => !!chats && typeof e.data?.chat === "string" && !chats.has(e.data.chat);
121
- return events.filter((e) => !fromReader(e) && isMessage(e.type) && !read.has(e.id) && !replaced.has(e.id) && !offPage(e));
180
+ return events.filter((e) => !fromReader(e) && shown(e) && !read.has(e.id) && !replaced.has(e.id) && !offPage(e));
122
181
  }
123
182
  /**
124
183
  * The type of the event that settles questions (`workpad settle`): `{ forms: [<name>…] }`. An
@@ -329,16 +388,21 @@ async function onSubmit(e) {
329
388
  }
330
389
  const sendButtons = (form) => [...form.querySelectorAll("button, input[type=submit]")].filter((b) => (b instanceof HTMLInputElement || b.type !== "button" && b.type !== "reset") && b.form === form);
331
390
  function showStatus(form) {
332
- const text = form.dataset.wpState === "failed" ? ["couldn't send it", "bad"] : form.dataset.wpState === "sending" ? null : form.hasAttribute("data-wp-pending") ? ["waiting for an agent to receive it", null] : form.hasAttribute("data-wp-received") ? ["the agent has it", null] : null;
391
+ const last = api$1.last(form.getAttribute("name"));
392
+ const delivery = last ? api$1.delivery().get(last.id) : void 0;
393
+ const answered = form.hasAttribute("data-wp-pending") || form.hasAttribute("data-wp-received");
394
+ const text = form.dataset.wpState === "failed" ? ["couldn't send it", "bad"] : form.dataset.wpState === "sending" || !answered || !delivery || delivery.state === "sending" ? null : [delivery.text, delivery.state === "late" ? "warn" : null];
333
395
  let el = form.querySelector(".wp-form-status");
334
- const last = sendButtons(form).at(-1);
335
- if (!text || !last) return void el?.remove();
396
+ const button = sendButtons(form).at(-1);
397
+ if (!text || !button) return void el?.remove();
336
398
  if (!el) el = Object.assign(document.createElement("span"), { className: "wp-form-status" });
337
399
  el.setAttribute("role", "status");
338
- if (el.previousElementSibling !== last) last.after(el);
400
+ if (el.previousElementSibling !== button) button.after(el);
339
401
  el.textContent = text[0];
340
402
  if (text[1]) el.dataset.kind = text[1];
341
403
  else delete el.dataset.kind;
404
+ if (text[1] === "bad") delete el.dataset.wpDelivery;
405
+ else el.dataset.wpDelivery = delivery.state;
342
406
  }
343
407
  const ATTR = {
344
408
  open: "data-wp-open",
@@ -439,6 +503,9 @@ function trackForms(el, pageId, core) {
439
503
  document.addEventListener("submit", onSubmit, { capture: true });
440
504
  api$1.onRendered(refresh);
441
505
  api$1.listeners.on(mark);
506
+ api$1.delivery.on(() => {
507
+ for (const form of forms()) showStatus(form);
508
+ });
442
509
  api$1.events.on(() => {
443
510
  restoreLast(false);
444
511
  mark();
@@ -468,6 +535,39 @@ function trackForms(el, pageId, core) {
468
535
  /** For the api: every named form and where it stands, as it changes. */
469
536
  const forms_ = reactive(() => current);
470
537
  const formsApi = { forms: forms_ };
538
+ // src/client/delivery.ts
539
+ const same = (a, b) => a.size === b.size && [...a].every(([id, d]) => b.get(id)?.text === d.text);
540
+ /**
541
+ * The delivery of each of the reader's events for an agent among `events`: a form's answer (a type
542
+ * without a colon) and the plugins' types in `handedOut`.
543
+ */
544
+ function trackDelivery(events, listeners, handedOut) {
545
+ const forAgent = (e) => fromReader(e) && (isQuestionName(e.type) || handedOut.has(e.type));
546
+ let current = /* @__PURE__ */ new Map();
547
+ let timer;
548
+ const value = reactive(() => current);
549
+ const update = () => {
550
+ const now = Date.now();
551
+ const listening = listeners();
552
+ const next = /* @__PURE__ */ new Map();
553
+ let soonest = Infinity;
554
+ for (const e of events()) {
555
+ if (!forAgent(e)) continue;
556
+ const d = deliveryOf(e, listening, now);
557
+ next.set(e.id, d);
558
+ if (d.state === "waiting" || d.state === "unfollowed") soonest = Math.min(soonest, Date.parse(e.ts) + NOT_RECEIVED_AFTER - now);
559
+ }
560
+ clearTimeout(timer);
561
+ if (soonest < Infinity) timer = setTimeout(update, Math.max(0, soonest) + 50);
562
+ if (same(current, next)) return;
563
+ current = next;
564
+ value.notify();
565
+ };
566
+ events.on(update);
567
+ listeners.on(update);
568
+ update();
569
+ return value;
570
+ }
471
571
  // src/client/toast.ts
472
572
  let box = null;
473
573
  function place(corner) {
@@ -480,7 +580,7 @@ function place(corner) {
480
580
  return box;
481
581
  }
482
582
  function createToast(corner) {
483
- return function toast(text, { kind = "info", ms = 7e3, onClick, onDismiss, name, order = 0, details } = {}) {
583
+ return function toast(text, { kind = "info", ms = 7e3, onClick, onDismiss, name, order = 0, details, meta, bar } = {}) {
484
584
  const el = document.createElement("button");
485
585
  let timer;
486
586
  const close = () => {
@@ -496,6 +596,27 @@ function createToast(corner) {
496
596
  label.className = "wp-toast-text";
497
597
  label.textContent = text;
498
598
  el.append(label);
599
+ let metaEl = null;
600
+ let barEl = null;
601
+ const setMeta = (text) => {
602
+ if (!text) return void metaEl?.remove();
603
+ metaEl ??= Object.assign(document.createElement("span"), { className: "wp-toast-meta" });
604
+ metaEl.textContent = text;
605
+ if (!metaEl.isConnected) label.after(metaEl);
606
+ };
607
+ const setBar = (to) => {
608
+ if (!to) return void barEl?.remove();
609
+ if (!barEl) {
610
+ barEl = Object.assign(document.createElement("span"), { className: "wp-toast-bar" });
611
+ barEl.append(document.createElement("span"));
612
+ }
613
+ barEl.dataset.tone = to.tone ?? "accent";
614
+ barEl.toggleAttribute("data-indeterminate", to.value == null);
615
+ barEl.style.setProperty("--wp-toast-bar", to.value == null ? "" : `${Math.max(0, Math.min(1, to.value)) * 100}%`);
616
+ if (!barEl.isConnected) el.append(barEl);
617
+ };
618
+ setMeta(meta);
619
+ setBar(bar);
499
620
  let more = null;
500
621
  let detail = null;
501
622
  if (details) {
@@ -538,8 +659,10 @@ function createToast(corner) {
538
659
  place(corner()).append(el);
539
660
  return {
540
661
  close,
541
- update: (next) => {
662
+ update: (next, more) => {
542
663
  label.textContent = next;
664
+ if (more && "meta" in more) setMeta(more.meta);
665
+ if (more && "bar" in more) setBar(more.bar);
543
666
  },
544
667
  hide: () => {
545
668
  el.hidden = true;
@@ -552,12 +675,12 @@ function createToast(corner) {
552
675
  };
553
676
  }
554
677
  // src/client/read.ts
555
- let isMessage = () => false;
678
+ let messages$1 = /* @__PURE__ */ new Map();
556
679
  let getEvents = () => [];
557
680
  let send = () => {};
558
681
  let chats = () => null;
559
682
  const sending$1 = /* @__PURE__ */ new Set();
560
- const unread$1 = () => unreadMessages(getEvents(), isMessage, chats()).filter((e) => !sending$1.has(e.id));
683
+ const unread$1 = () => unreadMessages(getEvents(), messages$1, chats()).filter((e) => !sending$1.has(e.id));
561
684
  /**
562
685
  * The chats the page's content shows, by name: the one under every form and each chat block; null
563
686
  * while there is no page content (a folder, raw text), when every chat's messages count.
@@ -617,8 +740,7 @@ function observeMessages() {
617
740
  }
618
741
  }
619
742
  function trackReading(options) {
620
- const types = new Set(options.messages);
621
- isMessage = (type) => types.has(type);
743
+ messages$1 = new Map(Object.entries(options.messages));
622
744
  getEvents = options.events;
623
745
  send = options.send;
624
746
  chats = chatsShown;
@@ -1006,7 +1128,8 @@ const api = {
1006
1128
  writeTitle();
1007
1129
  },
1008
1130
  toast: createToast(cornerOfPage),
1009
- ...formsApi
1131
+ ...formsApi,
1132
+ delivery: trackDelivery(eventsValue, listenersValue, new Set(handoff.handedOut ?? []))
1010
1133
  };
1011
1134
  const changeListeners = /* @__PURE__ */ new Set();
1012
1135
  async function getJson(url) {
@@ -1146,7 +1269,7 @@ if (handoff.client) try {
1146
1269
  if (live) {
1147
1270
  trackForms(root, page, api);
1148
1271
  trackReading({
1149
- messages: handoff.messages ?? [],
1272
+ messages: handoff.messages ?? {},
1150
1273
  events: () => events,
1151
1274
  send: (ids) => {
1152
1275
  append(READ, { ids }).catch((err) => console.error("marking read:", err));
@@ -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.
@@ -2,15 +2,126 @@ import { builtinPublic } from "../../src/package.js";
2
2
  import fs from "node:fs";
3
3
  import { definePlugin, html, raw } from "@bigmistqke/workpad";
4
4
  // plugins/badge/index.ts
5
- /** The word a badge's colour is chosen by: its text, lowercased, runs of other characters a `-`. */
5
+ /** The colours a badge takes, by name; each tuned per theme for readable text (style.css). */
6
+ const PALETTE = [
7
+ "red",
8
+ "orange",
9
+ "yellow",
10
+ "green",
11
+ "blue",
12
+ "violet",
13
+ "pink",
14
+ "grey"
15
+ ];
16
+ const COLOURED = [
17
+ "color",
18
+ "background",
19
+ "border"
20
+ ];
21
+ const KEYS = [...COLOURED, "live"];
22
+ const palette = PALETTE.join(", ");
23
+ /** The built-in words: default presets, which a project's presets replace word by word. */
24
+ const BUILTIN_PRESETS = Object.fromEntries([
25
+ ...[
26
+ "done",
27
+ "ok",
28
+ "yes",
29
+ "good"
30
+ ].map((w) => [w, { color: "green" }]),
31
+ ...[
32
+ "active",
33
+ "new",
34
+ "info"
35
+ ].map((w) => [w, { color: "blue" }]),
36
+ ...[
37
+ "open",
38
+ "todo",
39
+ "maybe",
40
+ "warning"
41
+ ].map((w) => [w, { color: "orange" }]),
42
+ ...[
43
+ "blocked",
44
+ "no",
45
+ "bad",
46
+ "error"
47
+ ].map((w) => [w, { color: "red" }])
48
+ ]);
49
+ /** The word a badge's preset is found by: its text, lowercased, runs of other characters a `-`. */
6
50
  const tone = (s) => s.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
7
- /** `:badge[done]`: a coloured dot and a word, inline wherever text goes. */
8
- function render(ctx) {
51
+ const isColour = (v) => typeof v === "string" && PALETTE.includes(v);
52
+ /**
53
+ * A config's presets, checked, by their words (tone()), over the built-in words: what is wrong
54
+ * throws, so the config fails to load and says why.
55
+ */
56
+ function presetsOf(given = {}) {
57
+ if (typeof given !== "object" || given === null || Array.isArray(given)) throw new Error("badge: `presets` is an object of looks by name: `{ you: { background: \"red\" } }`");
58
+ const own = {};
59
+ const named = {};
60
+ for (const [name, look] of Object.entries(given)) {
61
+ const word = tone(name);
62
+ const where = `badge: preset "${name}"`;
63
+ if (!word) throw new Error(`${where} has no letter or digit: a badge's word couldn't reach it`);
64
+ if (word in named) throw new Error(`${where} is the same word as "${named[word]}" (${word})`);
65
+ named[word] = name;
66
+ if (typeof look !== "object" || look === null || Array.isArray(look)) throw new Error(`${where} is a look: an object such as \`{ color: 'green' }\``);
67
+ for (const [k, v] of Object.entries(look)) {
68
+ if (!KEYS.includes(k)) throw new Error(`${where} sets \`${k}\`, which a badge hasn't: a preset sets ${KEYS.join(", ")}`);
69
+ if (k === "live" ? typeof v !== "boolean" : !isColour(v)) throw new Error(k === "live" ? `${where} has \`live: ${JSON.stringify(v)}\`: it is true or false` : `${where} has no colour ${JSON.stringify(v)} for \`${k}\`: the palette is ${palette}`);
70
+ }
71
+ own[word] = { ...look };
72
+ }
73
+ return {
74
+ ...BUILTIN_PRESETS,
75
+ ...own
76
+ };
77
+ }
78
+ /**
79
+ * The look of a badge of `text` with `attrs`, attribute by attribute the most specific: its own
80
+ * attributes, then the preset it names (`preset=`), then its word's preset (the built-in words
81
+ * among them). A value it doesn't know is reported, and the next one down holds.
82
+ */
83
+ function lookOf(text, attrs, presets, report = () => {}) {
84
+ const written = `\`:badge[${text}]\``;
85
+ const own = {};
86
+ for (const k of COLOURED) {
87
+ const v = attrs[k];
88
+ if (v === void 0) continue;
89
+ if (isColour(v)) own[k] = v;
90
+ else report(`${written} has no colour \`${v}\` for \`${k}\`: the palette is ${palette}`);
91
+ }
92
+ if (attrs.live !== void 0) {
93
+ if (attrs.live === "" || attrs.live === "true") own.live = true;
94
+ else if (attrs.live === "false") own.live = false;
95
+ else report(`${written} has \`live=${attrs.live}\`: it is \`{live}\` or \`{live=false}\``);
96
+ }
97
+ let named = {};
98
+ if (attrs.preset !== void 0) {
99
+ const found = presets[tone(attrs.preset)];
100
+ if (found) named = found;
101
+ else report(`${written} names no preset \`${attrs.preset}\`: there are ${Object.keys(presets).map((p) => `\`${p}\``).join(", ")}`);
102
+ }
103
+ const look = {};
104
+ for (const layer of [
105
+ presets[tone(text)] ?? {},
106
+ named,
107
+ own
108
+ ]) for (const [k, v] of Object.entries(layer)) if (v !== void 0) look[k] = v;
109
+ return look;
110
+ }
111
+ /** `:badge[done]`: a word, with a coloured dot, a fill or an outline, inline wherever text goes. */
112
+ function render(ctx, presets = BUILTIN_PRESETS) {
9
113
  const text = ctx.labelText?.trim();
10
114
  if (!text) return html``;
11
- return html`<span class="wp-badge" data-badge="${tone(text)}">${raw(ctx.label ?? "")}</span>`;
115
+ const look = lookOf(text, ctx.attrs, presets, (p) => ctx.problem(p));
116
+ const word = tone(text);
117
+ const builtin = presets[word] !== void 0 && presets[word] === BUILTIN_PRESETS[word] && ctx.attrs.color === void 0 && (ctx.attrs.preset === void 0 || presets[tone(ctx.attrs.preset)]?.color === void 0);
118
+ const shows = html`${COLOURED.map((k) => look[k] && html` data-${k}="${look[k]}"`)}${look.live && html` data-live`}${builtin && look.color && html` data-dot`}`;
119
+ const label = raw(ctx.label ?? "");
120
+ return html`<span class="wp-badge" data-badge="${tone(text)}"${shows}>${label}</span>`;
12
121
  }
13
- function badge() {
122
+ function badge(options = {}) {
123
+ const presets = presetsOf(options.presets);
124
+ const own = Object.keys(options.presets ?? {});
14
125
  return definePlugin({
15
126
  name: "badge",
16
127
  public: builtinPublic("badge"),
@@ -19,10 +130,21 @@ function badge() {
19
130
  group: "mark",
20
131
  summary: "a status in a word: done, todo, waiting"
21
132
  },
22
- html: render,
133
+ attrs: [
134
+ "color",
135
+ "background",
136
+ "border",
137
+ "live",
138
+ "preset"
139
+ ],
140
+ html: (ctx) => render(ctx, presets),
23
141
  style: "style.css"
24
142
  } },
25
- docs: () => fs.readFileSync(new URL("./README.md", import.meta.url), "utf8")
143
+ docs: () => {
144
+ const readme = fs.readFileSync(new URL("./README.md", import.meta.url), "utf8");
145
+ if (!own.length) return readme;
146
+ return `${readme}\nThis project's presets:\n\n${own.map((name) => `- \`${name}\`: ${JSON.stringify(options.presets[name])}`).join("\n")}\n`;
147
+ }
26
148
  });
27
149
  }
28
- export { badge as default, render, tone };
150
+ export { BUILTIN_PRESETS, PALETTE, badge as default, lookOf, presetsOf, render, tone };
@@ -1,30 +1,150 @@
1
- /* a coloured dot and a word, not a pill */
1
+ /* A word, small, with a dot before it; a colour, a fill, an outline and a pulse when it says so
2
+ (data-color, data-background, data-border, data-live, from its attributes and presets).
3
+
4
+ The palette, per theme: each colour (--wp-badge-<name>) as text and dot at least 4.5:1 on the
5
+ page and the surfaces a badge sits on (cards, tables, code), and as a fill under its readable
6
+ text (--wp-badge-ink) at least 4.5:1 (test/browser/badge.test.ts measures both). A project can
7
+ retune one in its own stylesheet, both themes at once: `--wp-badge-orange: light-dark(#9a4a06, #ffa462)`. */
8
+ :root {
9
+ --wp-badge-red: light-dark(#c4352b, #ff6f66);
10
+ --wp-badge-orange: light-dark(#a84d08, #ff9a4d);
11
+ --wp-badge-yellow: light-dark(#8a6500, #e8c547);
12
+ --wp-badge-green: light-dark(#1a7a49, #57c48c);
13
+ --wp-badge-blue: light-dark(#1d5bbf, #82aaff);
14
+ --wp-badge-violet: light-dark(#6b4fc0, #b4a0ff);
15
+ --wp-badge-pink: light-dark(#be185d, #f78fc0);
16
+ --wp-badge-grey: light-dark(#696e76, #979ca5);
17
+ /* a fill is the colour itself; the text on it this: white on the light theme's dark shades,
18
+ near-black on the dark theme's light ones */
19
+ --wp-badge-ink: light-dark(#ffffff, #131417);
20
+ }
21
+
2
22
  .wp-badge {
3
- --c: var(--muted);
4
23
  display: inline-flex;
5
24
  align-items: center;
6
25
  gap: var(--space-sm);
7
26
  font: 500 var(--ui-tiny)/1 var(--sans);
8
- color: var(--muted);
27
+ /* on a fill, its ink; else the colour; else as text beside the page's */
28
+ color: var(--wp-badge-on, var(--wp-badge-c, var(--muted)));
29
+ background: var(--wp-badge-fill, none);
9
30
  white-space: nowrap;
10
31
  vertical-align: 0.1em;
11
32
  }
12
33
  .wp-badge::before {
13
34
  content: '';
35
+ flex: none;
14
36
  width: 7px;
15
37
  height: 7px;
16
38
  border-radius: 50%;
17
- background: var(--c);
39
+ --wp-badge-dot: var(--wp-badge-c, var(--wp-badge-on, var(--muted)));
40
+ background: var(--wp-badge-dot);
41
+ }
42
+ /* a built-in word (done, todo, …): the colour is its dot's, the text stays grey */
43
+ .wp-badge[data-dot]:not([data-background]) {
44
+ color: var(--muted);
45
+ }
46
+ /* a fill or an outline makes it a pill, which stands without a dot, unless the dot is live */
47
+ .wp-badge:is([data-background], [data-border]) {
48
+ padding: 2px 7px;
49
+ border: var(--hairline) solid var(--wp-badge-line, transparent);
50
+ border-radius: var(--radius-pill);
51
+ }
52
+ .wp-badge:is([data-background], [data-border]):not([data-live])::before {
53
+ display: none;
54
+ }
55
+
56
+ .wp-badge[data-color='red'] {
57
+ --wp-badge-c: var(--wp-badge-red);
58
+ }
59
+ .wp-badge[data-color='orange'] {
60
+ --wp-badge-c: var(--wp-badge-orange);
61
+ }
62
+ .wp-badge[data-color='yellow'] {
63
+ --wp-badge-c: var(--wp-badge-yellow);
64
+ }
65
+ .wp-badge[data-color='green'] {
66
+ --wp-badge-c: var(--wp-badge-green);
67
+ }
68
+ .wp-badge[data-color='blue'] {
69
+ --wp-badge-c: var(--wp-badge-blue);
70
+ }
71
+ .wp-badge[data-color='violet'] {
72
+ --wp-badge-c: var(--wp-badge-violet);
73
+ }
74
+ .wp-badge[data-color='pink'] {
75
+ --wp-badge-c: var(--wp-badge-pink);
76
+ }
77
+ .wp-badge[data-color='grey'] {
78
+ --wp-badge-c: var(--wp-badge-grey);
79
+ }
80
+
81
+ .wp-badge[data-background] {
82
+ --wp-badge-on: var(--wp-badge-ink);
83
+ }
84
+ .wp-badge[data-background='red'] {
85
+ --wp-badge-fill: var(--wp-badge-red);
86
+ }
87
+ .wp-badge[data-background='orange'] {
88
+ --wp-badge-fill: var(--wp-badge-orange);
89
+ }
90
+ .wp-badge[data-background='yellow'] {
91
+ --wp-badge-fill: var(--wp-badge-yellow);
92
+ }
93
+ .wp-badge[data-background='green'] {
94
+ --wp-badge-fill: var(--wp-badge-green);
95
+ }
96
+ .wp-badge[data-background='blue'] {
97
+ --wp-badge-fill: var(--wp-badge-blue);
98
+ }
99
+ .wp-badge[data-background='violet'] {
100
+ --wp-badge-fill: var(--wp-badge-violet);
101
+ }
102
+ .wp-badge[data-background='pink'] {
103
+ --wp-badge-fill: var(--wp-badge-pink);
104
+ }
105
+ .wp-badge[data-background='grey'] {
106
+ --wp-badge-fill: var(--wp-badge-grey);
107
+ }
108
+
109
+ .wp-badge[data-border='red'] {
110
+ --wp-badge-line: var(--wp-badge-red);
111
+ }
112
+ .wp-badge[data-border='orange'] {
113
+ --wp-badge-line: var(--wp-badge-orange);
114
+ }
115
+ .wp-badge[data-border='yellow'] {
116
+ --wp-badge-line: var(--wp-badge-yellow);
117
+ }
118
+ .wp-badge[data-border='green'] {
119
+ --wp-badge-line: var(--wp-badge-green);
120
+ }
121
+ .wp-badge[data-border='blue'] {
122
+ --wp-badge-line: var(--wp-badge-blue);
123
+ }
124
+ .wp-badge[data-border='violet'] {
125
+ --wp-badge-line: var(--wp-badge-violet);
126
+ }
127
+ .wp-badge[data-border='pink'] {
128
+ --wp-badge-line: var(--wp-badge-pink);
18
129
  }
19
- .wp-badge:is([data-badge='done'], [data-badge='ok'], [data-badge='yes'], [data-badge='good']) {
20
- --c: var(--ok);
130
+ .wp-badge[data-border='grey'] {
131
+ --wp-badge-line: var(--wp-badge-grey);
21
132
  }
22
- .wp-badge:is([data-badge='active'], [data-badge='new'], [data-badge='info']) {
23
- --c: var(--info);
133
+
134
+ /* live: the dot pulses, a ring growing out of it and fading; still under reduced motion */
135
+ .wp-badge[data-live]::before {
136
+ animation: wp-badge-pulse 1.6s ease-out infinite;
24
137
  }
25
- .wp-badge:is([data-badge='open'], [data-badge='todo'], [data-badge='maybe'], [data-badge='warning']) {
26
- --c: var(--warn);
138
+ @keyframes wp-badge-pulse {
139
+ 0% {
140
+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--wp-badge-dot) 55%, transparent);
141
+ }
142
+ 100% {
143
+ box-shadow: 0 0 0 5px transparent;
144
+ }
27
145
  }
28
- .wp-badge:is([data-badge='blocked'], [data-badge='no'], [data-badge='bad'], [data-badge='error']) {
29
- --c: var(--bad);
146
+ @media (prefers-reduced-motion: reduce) {
147
+ .wp-badge[data-live]::before {
148
+ animation: none;
149
+ }
30
150
  }