@bigmistqke/whiteboard 0.2.0 → 0.3.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 (45) hide show
  1. package/README.md +16 -10
  2. package/bin/whiteboard.ts +98 -4
  3. package/dist/bin/whiteboard.js +99 -3
  4. package/dist/client/runtime.js +118 -24
  5. package/dist/plugins/claude-code/index.js +14 -3
  6. package/dist/plugins/comments/client.js +3 -3
  7. package/dist/plugins/details/README.md +3 -1
  8. package/dist/plugins/form/README.md +6 -4
  9. package/dist/plugins/form/index.js +9 -1
  10. package/dist/plugins/form/style.css +3 -0
  11. package/dist/plugins/toc/README.md +10 -0
  12. package/dist/plugins/toc/client.js +1 -0
  13. package/dist/plugins/toc/index.js +17 -0
  14. package/dist/plugins/toc/style.css +19 -0
  15. package/dist/src/client/page/base.css +26 -22
  16. package/dist/src/client/page/main.js +231 -56
  17. package/dist/src/events.js +127 -9
  18. package/dist/src/loader.js +4 -0
  19. package/dist/src/server.js +25 -17
  20. package/package.json +6 -1
  21. package/plugins/claude-code/index.ts +16 -7
  22. package/plugins/comments/client.ts +30 -7
  23. package/plugins/details/README.md +3 -1
  24. package/plugins/form/README.md +6 -4
  25. package/plugins/form/index.ts +9 -1
  26. package/plugins/form/style.css +3 -0
  27. package/plugins/toc/README.md +10 -0
  28. package/plugins/toc/client.ts +130 -0
  29. package/plugins/toc/index.ts +25 -0
  30. package/plugins/toc/style.css +19 -0
  31. package/skills/whiteboard/SKILL.md +41 -9
  32. package/src/client/forms.ts +32 -1
  33. package/src/client/page/base.css +26 -22
  34. package/src/client/page/fresh.ts +18 -23
  35. package/src/client/page/hold.ts +37 -0
  36. package/src/client/page/main.ts +87 -10
  37. package/src/client/page/sticky.ts +45 -0
  38. package/src/client/page/waiting.ts +30 -27
  39. package/src/client/runtime.ts +8 -2
  40. package/src/client/scroll.ts +44 -0
  41. package/src/client/toast.ts +51 -21
  42. package/src/define.ts +17 -8
  43. package/src/events.ts +95 -7
  44. package/src/loader.ts +1 -1
  45. package/src/server.ts +28 -7
@@ -481,6 +481,7 @@ function signature(el) {
481
481
  n.removeAttribute("data-wb-island");
482
482
  n.removeAttribute("data-wb-mounted");
483
483
  }
484
+ clone.removeAttribute("data-wb-block");
484
485
  const s = clone.outerHTML;
485
486
  let h = 2166136261;
486
487
  for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);
@@ -559,11 +560,8 @@ function markNew(el) {
559
560
  unseen.add(el);
560
561
  scheduleCheck();
561
562
  }
562
- const nav = document.createElement("div");
563
- nav.className = "wb-fresh";
564
- nav.innerHTML = String(html`${["up", "down"].map((dir) => html`<button type="button" data-dir="${dir}"><span class="wb-fresh-label"></span><span class="wb-fresh-close" title="Mark everything new as seen" aria-label="Mark everything new as seen">✕</span></button>`)}`);
565
- const [upBtn, downBtn] = nav.querySelectorAll("button");
566
- nav.hidden = upBtn.hidden = downBtn.hidden = true;
563
+ let upToast = null;
564
+ let downToast = null;
567
565
  function split() {
568
566
  const above = [], below = [];
569
567
  for (const el of unseen) {
@@ -588,27 +586,34 @@ function update$1() {
588
586
  cancelAnimationFrame(raf);
589
587
  raf = requestAnimationFrame(() => {
590
588
  const { above, below } = split();
591
- upBtn.hidden = !above.length;
592
- downBtn.hidden = !below.length;
593
- upBtn.querySelector(".wb-fresh-label").textContent = `↑ new (${above.length})`;
594
- downBtn.querySelector(".wb-fresh-label").textContent = `↓ new (${below.length})`;
595
- nav.hidden = !above.length && !below.length;
589
+ for (const [toast, list, arrow] of [[
590
+ upToast,
591
+ above,
592
+ "↑"
593
+ ], [
594
+ downToast,
595
+ below,
596
+ "↓"
597
+ ]]) {
598
+ if (!toast) continue;
599
+ if (list.length) {
600
+ toast.update(`${arrow} new (${list.length})`);
601
+ toast.show();
602
+ } else toast.hide();
603
+ }
596
604
  core$1?.badge("new", unseen.size ? String(unseen.size) : null);
597
605
  });
598
606
  }
599
- nav.addEventListener("click", (e) => {
600
- const dir = e.target.closest("button")?.dataset.dir;
601
- if (!dir) return;
602
- if (e.target.closest(".wb-fresh-close")) {
603
- for (const el of [...unseen]) markSeen(el);
604
- return;
605
- }
607
+ function go(dir) {
606
608
  const { above, below } = split();
607
609
  (dir === "up" ? above : below)[0]?.scrollIntoView({
608
610
  behavior: "smooth",
609
611
  block: "start"
610
612
  });
611
- });
613
+ }
614
+ const seeAll = () => {
615
+ for (const el of [...unseen]) markSeen(el);
616
+ };
612
617
  addEventListener("scroll", update$1, { passive: true });
613
618
  addEventListener("resize", update$1);
614
619
  /** Below this share of blocks recognised from the last visit, the page counts as new to the reader. */
@@ -620,7 +625,24 @@ const RECOGNISED_MIN = .25;
620
625
  */
621
626
  function trackInitial(main, page, api) {
622
627
  core$1 = api;
623
- api.corner().append(nav);
628
+ upToast = api.toast("", {
629
+ ms: 0,
630
+ kind: "alert",
631
+ name: "new-up",
632
+ order: 1,
633
+ onClick: () => go("up"),
634
+ onDismiss: seeAll
635
+ });
636
+ downToast = api.toast("", {
637
+ ms: 0,
638
+ kind: "alert",
639
+ name: "new-down",
640
+ order: 2,
641
+ onClick: () => go("down"),
642
+ onDismiss: seeAll
643
+ });
644
+ upToast.hide();
645
+ downToast.hide();
624
646
  mainEl = main;
625
647
  storeKey = `wb-seen:${page}`;
626
648
  const blocks = [...main.children];
@@ -760,7 +782,7 @@ function trackElsewhere(root, handle, core) {
760
782
  // src/client/page/waiting.ts
761
783
  const ORDER = STATES;
762
784
  const LABEL = {
763
- open: (n) => `${n} waiting for you`,
785
+ open: (n) => `${n} unanswered`,
764
786
  pending: (n) => `${n} waiting for the agent`,
765
787
  decided: (n) => `${n} decided`
766
788
  };
@@ -768,10 +790,6 @@ const messagesLabel = (n) => `${n} unread message${n === 1 ? "" : "s"} from the
768
790
  let main$1;
769
791
  let api$1;
770
792
  let forms = [];
771
- const button = document.createElement("button");
772
- button.type = "button";
773
- button.className = "wb-waiting-next";
774
- button.hidden = true;
775
793
  const summary = document.createElement("div");
776
794
  summary.className = "wb-summary";
777
795
  summary.hidden = true;
@@ -789,8 +807,10 @@ function targets(kind = "all") {
789
807
  const top = (el) => el.getBoundingClientRect().top;
790
808
  return list.sort((a, b) => top(a) - top(b));
791
809
  }
792
- let messagesToast = null;
810
+ let waitingToast;
811
+ let unreadToast;
793
812
  let toastTimer = 0;
813
+ let unreadShown = false;
794
814
  function show(list = forms) {
795
815
  forms = list;
796
816
  for (const { form, name, state, last } of forms) {
@@ -809,24 +829,23 @@ function show(list = forms) {
809
829
  return i ? [document.createTextNode(" · "), link] : [link];
810
830
  }));
811
831
  const n = inState("open").length + unread;
812
- button.hidden = n === 0;
813
- button.textContent = `→ waiting for you (${n})`;
832
+ const questions = inState("open").length;
833
+ if (questions) {
834
+ waitingToast.update(`→ unanswered (${questions})`);
835
+ waitingToast.show();
836
+ } else waitingToast.hide();
814
837
  api$1.badge("waiting", n ? `!${n}` : null, -1);
815
- if (!unread) {
816
- messagesToast?.close();
817
- messagesToast = null;
818
- clearTimeout(toastTimer);
819
- } else if (messagesToast) messagesToast.update(messagesLabel(unread));
820
- else {
821
- clearTimeout(toastTimer);
822
- toastTimer = window.setTimeout(() => {
823
- const left = api$1.unread().length;
824
- if (left && !messagesToast) messagesToast = api$1.toast(messagesLabel(left), {
825
- ms: 0,
826
- onClick: () => jump("messages")
827
- });
828
- }, 1e3);
829
- }
838
+ clearTimeout(toastTimer);
839
+ if (!unread) unreadToast.hide();
840
+ else if (unreadShown) unreadToast.update(`→ unread (${unread})`);
841
+ else toastTimer = window.setTimeout(() => {
842
+ const left = api$1.unread().length;
843
+ if (!left) return;
844
+ unreadToast.update(`→ unread (${left})`);
845
+ unreadToast.show();
846
+ unreadShown = true;
847
+ }, 1e3);
848
+ if (!unread) unreadShown = false;
830
849
  if (arriving && n) {
831
850
  arriving = false;
832
851
  history.replaceState(history.state, "", location.pathname + location.search);
@@ -866,8 +885,20 @@ function jumpTo(target) {
866
885
  function trackWaiting(root, core) {
867
886
  main$1 = root;
868
887
  api$1 = core;
869
- api$1.corner().prepend(button);
870
- button.addEventListener("click", () => jump("all"));
888
+ waitingToast = api$1.toast("", {
889
+ ms: 0,
890
+ name: "waiting",
891
+ order: -2,
892
+ onClick: () => jump("open")
893
+ });
894
+ unreadToast = api$1.toast("", {
895
+ ms: 0,
896
+ name: "unread",
897
+ order: -1,
898
+ onClick: () => jump("messages")
899
+ });
900
+ waitingToast.hide();
901
+ unreadToast.hide();
871
902
  main$1.before(summary);
872
903
  summary.addEventListener("click", (e) => {
873
904
  const state = e.target.closest("button[data-state]")?.dataset.state;
@@ -898,8 +929,11 @@ function trackWaiting(root, core) {
898
929
  if (form.dataset.wbState === "sending") return;
899
930
  sent.disconnect();
900
931
  if (form.dataset.wbState !== "sent") return;
901
- if (fallback) api$1.toast("Sent. No agent waits on this page; the fallback agent picks it up.");
902
- else api$1.toast("Sent, but no agent is listening right now. Your answer stays in the log until one checks this page.", { kind: "warn" });
932
+ if (fallback) api$1.toast("Sent. No agent waits on this page; the fallback agent picks it up.", { name: "sent" });
933
+ else api$1.toast("Sent, but no agent is listening right now. Your answer stays in the log until one checks this page.", {
934
+ kind: "warn",
935
+ name: "sent"
936
+ });
903
937
  });
904
938
  sent.observe(form, {
905
939
  attributes: true,
@@ -965,6 +999,74 @@ function trackSorts() {
965
999
  });
966
1000
  applySorts();
967
1001
  }
1002
+ // src/client/page/sticky.ts
1003
+ function place(main) {
1004
+ const nav = document.querySelector(".wb-nav");
1005
+ const base = nav ? nav.getBoundingClientRect().height : 0;
1006
+ for (const summary of main.querySelectorAll("details > summary")) {
1007
+ let top = base, depth = 0;
1008
+ for (let d = summary.parentElement.parentElement?.closest("details"); d && main.contains(d); d = d.parentElement?.closest("details")) {
1009
+ const outer = d.querySelector(":scope > summary");
1010
+ if (outer && d.open) top += outer.getBoundingClientRect().height;
1011
+ depth++;
1012
+ }
1013
+ summary.style.setProperty("--wb-sticky-top", `${top}px`);
1014
+ summary.style.setProperty("--wb-sticky-z", String(Math.max(1, 4 - depth)));
1015
+ }
1016
+ }
1017
+ /** A click on a stuck title: once its details has closed, the title where it was stuck. */
1018
+ function keepTitle(e) {
1019
+ const summary = e.target.closest?.("summary");
1020
+ const details = summary?.parentElement;
1021
+ if (!summary || !(details instanceof HTMLDetailsElement) || !details.open) return;
1022
+ const top = parseFloat(summary.style.getPropertyValue("--wb-sticky-top")) || 0;
1023
+ if (details.getBoundingClientRect().top >= top - 1) return;
1024
+ requestAnimationFrame(() => scrollBy({ top: details.getBoundingClientRect().top - top }));
1025
+ }
1026
+ function trackSticky(main, onRendered) {
1027
+ main.addEventListener("click", keepTitle);
1028
+ let frame = 0;
1029
+ const later = () => {
1030
+ cancelAnimationFrame(frame);
1031
+ frame = requestAnimationFrame(() => place(main));
1032
+ };
1033
+ main.addEventListener("toggle", later, true);
1034
+ addEventListener("resize", later);
1035
+ onRendered(later);
1036
+ place(main);
1037
+ }
1038
+ // src/client/page/hold.ts
1039
+ const typing = (el) => el instanceof HTMLElement && el.matches("input:not([type=radio], [type=checkbox], [type=button], [type=submit]), textarea, select, [contenteditable]");
1040
+ let held = null;
1041
+ let top = 0;
1042
+ let frame = 0;
1043
+ function note() {
1044
+ const el = document.activeElement;
1045
+ held = typing(el) ? el : null;
1046
+ if (held) top = held.getBoundingClientRect().top;
1047
+ }
1048
+ function hold() {
1049
+ cancelAnimationFrame(frame);
1050
+ frame = requestAnimationFrame(() => {
1051
+ if (!held || document.activeElement !== held || !held.isConnected) return note();
1052
+ const moved = held.getBoundingClientRect().top - top;
1053
+ if (Math.abs(moved) >= 1) scrollBy(0, moved);
1054
+ top = held.getBoundingClientRect().top;
1055
+ });
1056
+ }
1057
+ function trackHold() {
1058
+ document.addEventListener("focusin", note);
1059
+ document.addEventListener("focusout", () => queueMicrotask(note));
1060
+ addEventListener("scroll", () => {
1061
+ if (held) top = held.getBoundingClientRect().top;
1062
+ }, { passive: true });
1063
+ new MutationObserver(hold).observe(document.body, {
1064
+ childList: true,
1065
+ subtree: true,
1066
+ characterData: true
1067
+ });
1068
+ addEventListener("resize", note);
1069
+ }
968
1070
  // src/client/page/orphans.ts
969
1071
  /** A message in a chat: the chat block's event. */
970
1072
  const isMessage = (e) => e.type === "chat:message" && typeof e.data.chat === "string";
@@ -1108,14 +1210,65 @@ function detailsKeys(root) {
1108
1210
  }
1109
1211
  return keys;
1110
1212
  }
1111
- function morph(html) {
1213
+ /** Each block's key: its signature, and which of the blocks with that signature it is. */
1214
+ function keyBlocks(parent, sigs) {
1215
+ const seen = /* @__PURE__ */ new Map();
1216
+ [...parent.children].forEach((el, i) => {
1217
+ const sig = sigs[i];
1218
+ if (!sig) return;
1219
+ const nth = seen.get(sig) ?? 0;
1220
+ seen.set(sig, nth + 1);
1221
+ el.dataset.wbBlock = `${sig}#${nth}`;
1222
+ });
1223
+ }
1224
+ /** What has the focus, to give it back if the patch took it: the element, its caret, and how to find it again. */
1225
+ function focusOf() {
1226
+ const el = document.activeElement;
1227
+ if (!el || el === document.body || !main.contains(el)) return null;
1228
+ const form = el.closest("form")?.getAttribute("name");
1229
+ let start = null, end = null;
1230
+ try {
1231
+ start = el.selectionStart;
1232
+ end = el.selectionEnd;
1233
+ } catch {}
1234
+ return {
1235
+ el,
1236
+ form,
1237
+ name: el.getAttribute("name"),
1238
+ start,
1239
+ end
1240
+ };
1241
+ }
1242
+ function giveFocusBack(f) {
1243
+ if (!f || document.activeElement === f.el) return;
1244
+ let el = f.el.isConnected ? f.el : null;
1245
+ if (!el && f.form && f.name) el = main.querySelector(`form[name="${CSS.escape(f.form)}"] [name="${CSS.escape(f.name)}"]`);
1246
+ if (!el) return;
1247
+ el.focus({ preventScroll: true });
1248
+ if (f.start != null && "setSelectionRange" in el) try {
1249
+ el.setSelectionRange(f.start, f.end ?? f.start);
1250
+ } catch {}
1251
+ }
1252
+ /** Are two elements, before and after a patch, the same field of the same form? */
1253
+ function sameField(from, to) {
1254
+ if (from.tagName !== to.tagName || from.getAttribute("name") !== to.getAttribute("name")) return false;
1255
+ const formOf = (el) => el.closest("form")?.getAttribute("name") ?? null;
1256
+ if (formOf(from) !== formOf(to)) return false;
1257
+ const type = from.getAttribute("type");
1258
+ if ((type === "radio" || type === "checkbox") && (to.getAttribute("type") !== type || from.getAttribute("value") !== to.getAttribute("value"))) return false;
1259
+ return true;
1260
+ }
1261
+ function morph(html, sigs) {
1112
1262
  const open = /* @__PURE__ */ new Set();
1113
1263
  for (const [el, key] of detailsKeys(main)) if (el.open) open.add(key);
1264
+ const focus = focusOf();
1114
1265
  const next = main.cloneNode(false);
1115
1266
  next.innerHTML = html;
1267
+ keyBlocks(main, sigs.from);
1268
+ keyBlocks(next, sigs.to);
1116
1269
  for (const [el, key] of detailsKeys(next)) el.open = open.has(key);
1117
1270
  morphdom(main, next, {
1118
- getNodeKey: (n) => n.dataset?.wbKey || n.id || void 0,
1271
+ getNodeKey: (n) => n.dataset?.wbKey || n.dataset?.wbBlock || n.id || void 0,
1119
1272
  onBeforeElUpdated(from, to) {
1120
1273
  if (from.dataset.wbKey) {
1121
1274
  if (from.dataset.wbKey === to.dataset.wbKey && "wbMounted" in from.dataset) {
@@ -1126,18 +1279,21 @@ function morph(html) {
1126
1279
  }
1127
1280
  if (FIELD(from)) {
1128
1281
  if (from === document.activeElement) return false;
1129
- to.value = from.value;
1130
- if (from instanceof HTMLInputElement) to.checked = from.checked;
1282
+ if (sameField(from, to)) {
1283
+ to.value = from.value;
1284
+ if (from instanceof HTMLInputElement) to.checked = from.checked;
1285
+ }
1131
1286
  }
1132
1287
  for (const { name, value } of [...from.attributes]) if (name.startsWith("data-wb-") && name !== "data-wb-mounted" && !to.hasAttribute(name)) to.setAttribute(name, value);
1133
1288
  for (const c of KEEP_CLASSES) if (from.classList.contains(c)) to.classList.add(c);
1134
1289
  return true;
1135
- },
1136
- onBeforeNodeDiscarded(node) {
1137
- disposeWithin(node);
1138
- return true;
1139
1290
  }
1140
1291
  });
1292
+ for (const [el, dispose] of disposers) if (!el.isConnected) {
1293
+ dispose();
1294
+ disposers.delete(el);
1295
+ }
1296
+ giveFocusBack(focus);
1141
1297
  }
1142
1298
  document.documentElement.style.overflowAnchor = "none";
1143
1299
  /**
@@ -1168,14 +1324,26 @@ function keepPlace(place, sigs) {
1168
1324
  }
1169
1325
  /** The new render of the page, patched in. */
1170
1326
  async function refresh() {
1171
- const next = await currentPage.render();
1327
+ let next;
1328
+ try {
1329
+ next = await currentPage.render();
1330
+ } catch (err) {
1331
+ if (/: 404$/.test(err.message)) return location.reload();
1332
+ throw err;
1333
+ }
1172
1334
  const data = next.data;
1173
1335
  islands = data.islands;
1174
1336
  for (const href of data.styles) if (![...document.querySelectorAll("link[rel=stylesheet]")].some((l) => new URL(l.href).pathname === new URL(href, location.href).pathname)) document.head.insertAdjacentHTML("beforeend", String(html`<link rel="stylesheet" href="${href}">`));
1175
1337
  const content = new DOMParser().parseFromString(next.html, "text/html").getElementById("wb-main")?.innerHTML ?? "";
1176
1338
  const nextSigs = signaturesOf(content);
1177
1339
  const place = placeOf(nextSigs);
1178
- morph(content);
1340
+ const focused = document.activeElement instanceof HTMLElement && document.activeElement !== document.body ? document.activeElement : null;
1341
+ const focusedTop = focused?.getBoundingClientRect().top;
1342
+ morph(content, {
1343
+ from: blockSigs,
1344
+ to: nextSigs
1345
+ });
1346
+ applySorts();
1179
1347
  keepPlace(place, nextSigs);
1180
1348
  const updated = document.getElementById("wb-updated");
1181
1349
  if (updated && data.mtime) updated.dataset.ts = String(data.mtime);
@@ -1186,6 +1354,11 @@ async function refresh() {
1186
1354
  keepPlace(place, nextSigs);
1187
1355
  tickTimes();
1188
1356
  api.rendered();
1357
+ const now = document.activeElement;
1358
+ if (focused && focusedTop != null && now instanceof HTMLElement && (now === focused || focused.isConnected === false)) {
1359
+ const moved = now.getBoundingClientRect().top - focusedTop;
1360
+ if (Math.abs(moved) >= 1) scrollBy(0, moved);
1361
+ }
1189
1362
  }
1190
1363
  let currentPage;
1191
1364
  let core;
@@ -1221,6 +1394,8 @@ const mount = async (root, handle, coreApi) => {
1221
1394
  trackSorts();
1222
1395
  core.onRendered(applySorts);
1223
1396
  }
1397
+ trackSticky(main, (fn) => core.onRendered(fn));
1398
+ trackHold();
1224
1399
  if (!isDir) trackOrphanThreads(main, core);
1225
1400
  await mountIslands();
1226
1401
  tickTimes();
@@ -67,35 +67,153 @@ function read(file) {
67
67
  * Call `onEvent` for each event appended to the log from byte `from` on (a line boundary, such as
68
68
  * `read`'s `end`), in order, as whole lines arrive. Checks every `interval` ms (default 200).
69
69
  * Returns a function that stops it.
70
+ *
71
+ * The log can be rewritten under it (`prune`: a page closed, its events gone): a new file, or a
72
+ * shorter one. Then it reads the log again and goes on after the last event it had passed on (by
73
+ * time, and by id among those of the same time), so nothing is passed on twice.
70
74
  */
71
75
  function follow(file, from, onEvent, { interval = 200 } = {}) {
72
76
  let offset = from;
73
77
  let partial = "";
78
+ let inode = null;
79
+ try {
80
+ inode = fs.statSync(file).ino;
81
+ } catch {}
82
+ let lastTs = "";
83
+ let atLastTs = /* @__PURE__ */ new Set();
84
+ if (from > 0) {
85
+ let before = [];
86
+ try {
87
+ before = parseLines(fs.readFileSync(file).subarray(0, from).toString("utf8"));
88
+ } catch {}
89
+ for (const e of before) {
90
+ if (e.ts > lastTs) {
91
+ lastTs = e.ts;
92
+ atLastTs = /* @__PURE__ */ new Set();
93
+ }
94
+ if (e.ts === lastTs) atLastTs.add(e.id);
95
+ }
96
+ }
97
+ const pass = (e) => {
98
+ if (e.ts > lastTs) {
99
+ lastTs = e.ts;
100
+ atLastTs = /* @__PURE__ */ new Set();
101
+ }
102
+ atLastTs.add(e.id);
103
+ onEvent(e);
104
+ };
74
105
  const poll = () => {
75
- let size;
106
+ let stat;
76
107
  try {
77
- size = fs.statSync(file).size;
108
+ stat = fs.statSync(file);
78
109
  } catch {
79
110
  return;
80
111
  }
81
- if (size < offset) {
82
- offset = 0;
112
+ if (inode != null && stat.ino !== inode || stat.size < offset) {
113
+ inode = stat.ino;
114
+ const { events, end } = read(file);
115
+ offset = end;
83
116
  partial = "";
117
+ for (const e of events) if (e.ts > lastTs || e.ts === lastTs && !atLastTs.has(e.id)) pass(e);
118
+ return;
84
119
  }
85
- if (size === offset) return;
120
+ inode = stat.ino;
121
+ if (stat.size === offset) return;
86
122
  const fd = fs.openSync(file, "r");
87
- const buf = Buffer.alloc(size - offset);
123
+ const buf = Buffer.alloc(stat.size - offset);
88
124
  fs.readSync(fd, buf, 0, buf.length, offset);
89
125
  fs.closeSync(fd);
90
- offset = size;
126
+ offset = stat.size;
91
127
  const text = partial + buf.toString("utf8");
92
128
  const cut = text.lastIndexOf("\n");
93
129
  partial = text.slice(cut + 1);
94
- for (const e of parseLines(text.slice(0, cut + 1))) onEvent(e);
130
+ for (const e of parseLines(text.slice(0, cut + 1))) pass(e);
95
131
  };
96
132
  const timer = setInterval(poll, interval);
97
133
  return () => clearInterval(timer);
98
134
  }
135
+ /**
136
+ * Rewrite the log, event by event: `change` returns the event to keep (as it is, or changed) or
137
+ * null to drop it. The log is written anew and put in place in one rename; when an event was
138
+ * appended while it was being written, it starts over, so none is lost. A follow running across it
139
+ * reads it again and goes on after the last event it passed on (see follow). Lines that aren't
140
+ * events are kept as they are. Returns how many were dropped and changed.
141
+ */
142
+ function rewrite(file, change) {
143
+ for (let attempt = 0; attempt < 10; attempt++) {
144
+ let buf;
145
+ try {
146
+ buf = fs.readFileSync(file);
147
+ } catch {
148
+ return {
149
+ removed: 0,
150
+ changed: 0
151
+ };
152
+ }
153
+ const keep = [];
154
+ let removed = 0, changed = 0;
155
+ for (const line of buf.toString("utf8").split("\n")) {
156
+ if (!line.trim()) continue;
157
+ let ev = null;
158
+ try {
159
+ ev = JSON.parse(line);
160
+ } catch {}
161
+ if (!ev) {
162
+ keep.push(line);
163
+ continue;
164
+ }
165
+ const next = change(ev);
166
+ if (!next) {
167
+ removed++;
168
+ continue;
169
+ }
170
+ const text = JSON.stringify(next);
171
+ if (text !== JSON.stringify(ev)) changed++;
172
+ keep.push(next === ev ? line : text);
173
+ }
174
+ if (!removed && !changed) return {
175
+ removed,
176
+ changed
177
+ };
178
+ const tmp = `${file}.${process.pid}.tmp`;
179
+ fs.writeFileSync(tmp, keep.length ? keep.join("\n") + "\n" : "");
180
+ if (fs.statSync(file).size !== buf.length) {
181
+ fs.rmSync(tmp, { force: true });
182
+ continue;
183
+ }
184
+ fs.renameSync(tmp, file);
185
+ return {
186
+ removed,
187
+ changed
188
+ };
189
+ }
190
+ throw new Error("the log kept changing while it was being rewritten; try again");
191
+ }
192
+ /** Remove a page's events from the log (`whiteboard close`, `whiteboard prune`): those of exactly
193
+ * that page, and of them only those `which` says (all by default). Returns how many. */
194
+ function prune(file, page, which = () => true) {
195
+ return rewrite(file, (e) => e.page === page && which(e) ? null : e).removed;
196
+ }
197
+ /**
198
+ * Change an agent's event in place (`whiteboard edit`): `data` is merged into its data; its id, time
199
+ * and everything else stay, so what refers to it (a reply, a pick, a read) still does. Only an
200
+ * agent's own events (`from: cli`): what the reader sent stays as they sent it. Returns the event
201
+ * as it is now.
202
+ */
203
+ function editEvent(file, id, data) {
204
+ const found = readEvents(file).find((e) => e.id === id);
205
+ if (!found) throw new Error(`no event ${id} in the log`);
206
+ if (fromReader(found)) throw new Error(`event ${id} is the reader's (${found.type}): what the reader sent stays as they sent it; an agent edits only its own`);
207
+ let edited = null;
208
+ rewrite(file, (e) => e.id === id ? edited = {
209
+ ...e,
210
+ data: {
211
+ ...e.data,
212
+ ...data
213
+ }
214
+ } : e);
215
+ return edited ?? found;
216
+ }
99
217
  /** `page` matches the page itself and every page below it, unless `exact`. */
100
218
  function matches(event, { page, type, exact } = {}) {
101
219
  if (page && event.page !== page && (exact || !event.page.startsWith(page + "/"))) return false;
@@ -180,4 +298,4 @@ function handOut(file, filter, onEvent, options = {}) {
180
298
  }, { interval });
181
299
  });
182
300
  }
183
- export { CLAIM, PICKED, appendEvent, follow, forAgent, fromReader, handOut, matches, parseLines, pick, pickedUp, read, readEvents };
301
+ export { CLAIM, PICKED, appendEvent, editEvent, follow, forAgent, fromReader, handOut, matches, parseLines, pick, pickedUp, prune, read, readEvents, rewrite };
@@ -21,6 +21,10 @@ const BUILTIN_COMMANDS = /* @__PURE__ */ new Set([
21
21
  "append",
22
22
  "pick",
23
23
  "status",
24
+ "scroll",
25
+ "close",
26
+ "prune",
27
+ "edit",
24
28
  "skill",
25
29
  "help"
26
30
  ]);
@@ -398,7 +398,7 @@ function createServer(project) {
398
398
  };
399
399
  }
400
400
  const json = (s) => JSON.stringify(s).replace(/</g, "\\u003c");
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)}";
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{display:flex;flex-direction:column;align-items:flex-end;gap:6px}.wb-toasts:empty{display:none}.wb-toast{display:inline-flex;align-items:center;gap:8px;cursor:pointer;padding:5px 12px;border-radius:99px;font:600 .8rem/1.4 var(--sans,system-ui,sans-serif);background:var(--accent,#1d5bbf);color:var(--accent-text,#fff);border:1px solid transparent;box-shadow:0 2px 10px rgb(0 0 0/.18)}.wb-toast[hidden]{display:none}.wb-toast[data-kind=warn]{background:var(--warn,#6b4fc0)}.wb-toast[data-kind=alert]{background:var(--bad,#c4352b);color:#fff}@keyframes wb-flash{from{outline-color:var(--accent,#1d5bbf)}to{outline-color:transparent}}.wb-flash{outline:3px solid transparent;outline-offset:6px;border-radius:4px;animation:wb-flash 2s ease-out}.wb-toast-dismiss{margin-right:-4px;padding:0 4px;border-left:1px solid rgb(255 255 255/.35);opacity:.75}.wb-toast-dismiss:hover{opacity:1}";
402
402
  /** `extras`: what plugins add to <head> and <body> (see shellExtras). */
403
403
  function shell(page, { page: rendered, out, notices }, extras = {
404
404
  head: [],
@@ -585,6 +585,17 @@ function createServer(project) {
585
585
  if (!body.type) return sendJson(res, 400, { error: "event type required" });
586
586
  return sendJson(res, 200, appendEvent(project.eventsFile, body));
587
587
  }
588
+ if (p === "/api/scroll" && req.method === "POST") {
589
+ const { page: id, to } = JSON.parse(await readBody(req));
590
+ if (typeof id !== "string" || typeof to !== "string" || !to.trim()) return sendJson(res, 400, { error: "page and to required" });
591
+ let tabs = 0;
592
+ for (const c of clients) {
593
+ if (c.isDir || c.page !== id && c.page + "/index" !== id) continue;
594
+ c.res.write(`event: scroll\ndata: ${JSON.stringify({ to })}\n\n`);
595
+ tabs++;
596
+ }
597
+ return sendJson(res, 200, { tabs });
598
+ }
588
599
  if (p === "/api/markdown" && req.method === "POST") {
589
600
  const { texts } = JSON.parse(await readBody(req));
590
601
  if (!Array.isArray(texts)) return sendJson(res, 400, { error: "texts: an array of strings" });
@@ -688,22 +699,19 @@ function createServer(project) {
688
699
  return;
689
700
  }
690
701
  if ("raw" in r) return sendFile(res, r.raw);
691
- if ("notFound" in r) return send(res, 404, await page(req, {
692
- kind: "page",
693
- id,
694
- file: "",
695
- mtime: null,
696
- source: r.notFound,
697
- body: r.notFound,
698
- frontmatter: {}
699
- }, {
700
- page: false,
701
- out: {
702
- title: "Not found",
703
- html: html`<h1>Not found</h1><p>${r.notFound}</p>`
704
- },
705
- notices: []
706
- }));
702
+ if ("notFound" in r) {
703
+ const md = `# Not found\n\n${r.notFound.replace(/[\\`*_[\]{}()<>#!:|~&-]/g, "\\$&")}\n`;
704
+ const missing = {
705
+ kind: "page",
706
+ id,
707
+ file: "",
708
+ mtime: null,
709
+ source: md,
710
+ body: md,
711
+ frontmatter: {}
712
+ };
713
+ return send(res, 404, await page(req, missing, await render(missing)));
714
+ }
707
715
  return send(res, 200, await page(req, r.page, await render(r.page)));
708
716
  } catch (err) {
709
717
  console.error(err);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bigmistqke/whiteboard",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "A whiteboard for you and your agent: it writes markdown pages you read live in the browser, you answer through forms it waits on",
5
5
  "keywords": [
6
6
  "agent",
@@ -51,6 +51,11 @@
51
51
  "types": "./plugins/comments/index.ts",
52
52
  "default": "./dist/plugins/comments/index.js"
53
53
  },
54
+ "./toc": {
55
+ "source": "./plugins/toc/index.ts",
56
+ "types": "./plugins/toc/index.ts",
57
+ "default": "./dist/plugins/toc/index.js"
58
+ },
54
59
  "./solid": {
55
60
  "types": "./solid/index.tsx",
56
61
  "default": "./dist/solid/index.js"