@bigmistqke/whiteboard 0.7.0 → 0.8.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 (66) hide show
  1. package/README.md +10 -209
  2. package/bin/whiteboard.ts +82 -239
  3. package/dist/bin/whiteboard.js +70 -200
  4. package/dist/client/runtime.js +66 -7
  5. package/dist/plugins/chat/public/style.css +10 -6
  6. package/dist/plugins/code/README.md +10 -0
  7. package/dist/plugins/code/index.js +31 -22
  8. package/dist/plugins/code/public/client.js +1 -0
  9. package/dist/plugins/code/public/style.css +33 -2
  10. package/dist/plugins/comments/public/client.js +1 -1
  11. package/dist/plugins/form/public/style.css +2 -0
  12. package/dist/plugins/iframe/index.js +2 -2
  13. package/dist/plugins/lightbox/public/client.js +1 -1
  14. package/dist/plugins/terminal/index.js +7 -9
  15. package/dist/plugins/terminal/public/client.js +1 -1
  16. package/dist/plugins/terminal/public/style.css +3 -3
  17. package/dist/plugins/toc/index.js +1 -1
  18. package/dist/plugins/toc/public/client.js +1 -1
  19. package/dist/plugins/window/index.js +4 -4
  20. package/dist/src/build.js +159 -0
  21. package/dist/src/client/page/main.js +1 -1
  22. package/dist/src/document.js +93 -0
  23. package/dist/src/events.js +3 -13
  24. package/dist/src/hub.js +47 -35
  25. package/dist/src/listen.js +100 -0
  26. package/dist/src/listeners.js +67 -0
  27. package/dist/src/pages/index.js +1 -1
  28. package/dist/src/pages/markdown.js +23 -11
  29. package/dist/src/pages/render.js +13 -8
  30. package/dist/src/server.js +166 -514
  31. package/dist/src/site.js +173 -0
  32. package/dist/src/status.js +63 -1
  33. package/package.json +1 -1
  34. package/plugins/README.md +258 -0
  35. package/plugins/chat/public/style.css +10 -6
  36. package/plugins/code/README.md +10 -0
  37. package/plugins/code/client.ts +73 -0
  38. package/plugins/code/index.ts +38 -26
  39. package/plugins/code/public/style.css +33 -2
  40. package/plugins/comments/client.ts +8 -1
  41. package/plugins/form/public/style.css +2 -0
  42. package/plugins/iframe/index.ts +2 -2
  43. package/plugins/lightbox/client.ts +13 -3
  44. package/plugins/terminal/client.ts +10 -2
  45. package/plugins/terminal/index.ts +8 -6
  46. package/plugins/terminal/public/style.css +3 -3
  47. package/plugins/toc/client.ts +9 -2
  48. package/plugins/toc/index.ts +1 -1
  49. package/plugins/window/index.ts +4 -4
  50. package/skills/whiteboard/SKILL.md +3 -1
  51. package/src/build.ts +213 -0
  52. package/src/client/page/elsewhere.ts +2 -1
  53. package/src/client/runtime.ts +88 -10
  54. package/src/client/toast.ts +1 -1
  55. package/src/define.ts +34 -18
  56. package/src/document.ts +191 -0
  57. package/src/events.ts +11 -16
  58. package/src/hub.ts +48 -34
  59. package/src/listen.ts +125 -0
  60. package/src/listeners.ts +95 -0
  61. package/src/pages/index.ts +1 -1
  62. package/src/pages/markdown.ts +29 -18
  63. package/src/pages/render.ts +13 -8
  64. package/src/server.ts +165 -609
  65. package/src/site.ts +165 -0
  66. package/src/status.ts +100 -0
@@ -1,13 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { configFileIn, findProjectDir, pageId, project as project$1 } from "../src/config.js";
3
- import { CLAIM, appendEvent, editEvent, follow, forAgent, handOut, matches, pick, pickedUp, prune, read, readEvents } from "../src/events.js";
3
+ import { appendEvent, editEvent, follow, forAgent, handOut, matches, pick, prune, read, readEvents } from "../src/events.js";
4
4
  import { BUILTIN_COMMANDS, createConfigLoader, pluginDir } from "../src/loader.js";
5
5
  import { parseCommandArgs, pluginCommands, usage } from "../src/plugins.js";
6
6
  import { projectToken } from "../src/auth.js";
7
7
  import { PACKAGE_DIR, VERSION, compareVersions, packagePath } from "../src/package.js";
8
8
  import { recordedSharedPort, runningServer, sharedServer } from "../src/running.js";
9
9
  import { machineDir, machineServerFile, matchesEntries, readMachineConfig, serverPaths, stateDir } from "../src/entries.js";
10
- import { statusLines, takenByOther, whose } from "../src/status.js";
10
+ import { CLAIM, pickedUp, statusLines, whose } from "../src/status.js";
11
+ import { fallback, listen } from "../src/listen.js";
11
12
  import fs from "node:fs";
12
13
  import os from "node:os";
13
14
  import path from "node:path";
@@ -249,99 +250,6 @@ async function askInProcess(route) {
249
250
  listener.close();
250
251
  }
251
252
  }
252
- /**
253
- * Tell the project's server that an agent is waiting, for as long as this command runs: pages show
254
- * what is waited for. Holds one connection open, the listener; reconnects when the server restarts.
255
- * Reading the log does not depend on it, so answers are never missed when the server is away.
256
- */
257
- /**
258
- * Tell the server who is listening, for as long as the command runs (again after a restart). The
259
- * fallback is refused when another one runs: it exits, saying so. Resolves once the server took it.
260
- */
261
- function listen(f, command, fallback = false) {
262
- return new Promise((registered) => {
263
- const connect = async () => {
264
- let base;
265
- try {
266
- base = await needServer();
267
- } catch {
268
- return setTimeout(connect, 2e3).unref();
269
- }
270
- const q = new URLSearchParams({
271
- command,
272
- ...f.page ? { page: f.page } : {},
273
- ...f.type ? { type: f.type } : {},
274
- ...fallback ? { fallback: "" } : {}
275
- });
276
- let again = false;
277
- const retry = (ms) => {
278
- if (!again) {
279
- again = true;
280
- setTimeout(connect, ms).unref();
281
- }
282
- };
283
- const req = http.get(`${base}/api/listen?${q}`, (res) => {
284
- if (res.statusCode === 409) {
285
- console.error("whiteboard: another agent already takes what no other listener does (a wait or watch without --page; one per project). Add --page to wait on a page of your own.");
286
- process.exit(1);
287
- }
288
- res.resume();
289
- registered();
290
- res.on("close", () => retry(1e3));
291
- });
292
- req.on("error", () => retry(2e3));
293
- req.on("socket", (socket) => socket.unref());
294
- };
295
- connect();
296
- });
297
- }
298
- /**
299
- * Who else listens, kept current: the fallback leaves to them what they would take. Calls
300
- * `changed` after each change (the server's live channel says when).
301
- */
302
- async function otherListeners(changed, server = needServer) {
303
- let list = [];
304
- const load = async () => {
305
- try {
306
- list = await (await fetch(`${await server()}/api/listeners`)).json();
307
- } catch {}
308
- changed();
309
- };
310
- const follow = async () => {
311
- let again = false;
312
- const retry = () => {
313
- if (!again) {
314
- again = true;
315
- setTimeout(follow, 1e3).unref();
316
- }
317
- };
318
- let base;
319
- try {
320
- base = await server();
321
- } catch {
322
- return retry();
323
- }
324
- const req = http.get(`${base}/api/watch?dir`, (res) => {
325
- let buf = "";
326
- res.setEncoding("utf8");
327
- res.on("data", (chunk) => {
328
- buf += chunk;
329
- if (buf.includes("event: listeners")) {
330
- buf = "";
331
- load();
332
- }
333
- if (buf.length > 4096) buf = buf.slice(-64);
334
- });
335
- res.on("close", retry);
336
- load();
337
- });
338
- req.on("error", retry);
339
- req.on("socket", (socket) => socket.unref());
340
- };
341
- await load();
342
- follow();
343
- return () => list;
344
- }
345
253
  function init(name) {
346
254
  const dir = process.cwd();
347
255
  const wb = path.join(dir, ".whiteboard");
@@ -560,7 +468,7 @@ switch (cmd) {
560
468
  })
561
469
  })).json();
562
470
  if (!tabs) {
563
- console.error(`whiteboard: no browser has ${id} open; \`whiteboard show ${target}\` prints its URL`);
471
+ console.error(`whiteboard: no tab of ${id} is connected now; one that is open scrolls there once it is back (a background tab connects again when it is shown). \`whiteboard show ${target}\` prints its URL`);
564
472
  process.exit(1);
565
473
  }
566
474
  console.log(`scrolled ${tabs} tab${tabs > 1 ? "s" : ""} of ${id} to ${JSON.stringify(to)}`);
@@ -638,39 +546,54 @@ switch (cmd) {
638
546
  break;
639
547
  }
640
548
  const { handedOut } = await projectConfig(proj);
641
- const fallback = !f.page;
642
- let recheck = () => {};
643
- const others = fallback ? (await listen(f, cmd, true), await otherListeners(() => recheck())) : null;
644
- const held = /* @__PURE__ */ new Set();
645
- const skip = (e) => {
646
- if (!held.has(e.id)) {
647
- held.add(e.id);
648
- setTimeout(() => recheck(), 500).unref();
649
- return true;
650
- }
651
- return takenByOther(others(), e);
549
+ const query = {
550
+ command: cmd,
551
+ ...f.page ? { page: f.page } : {},
552
+ ...f.type ? { type: f.type } : {}
553
+ };
554
+ const refused = (reason) => {
555
+ console.error(`whiteboard: ${reason}: another agent already takes what no other listener does (a wait or watch without --page; one per project). Add --page to wait on a page of your own.`);
556
+ process.exit(1);
652
557
  };
653
- handOut(proj.eventsFile, f, (e) => console.log(JSON.stringify(e)), {
558
+ const at = () => needServer().catch(() => null);
559
+ const options = {
654
560
  count: cmd === "wait" ? Number(opts.count ?? 1) : Infinity,
655
- forAgent: forAgent(handedOut),
656
- ...others && {
657
- skip,
658
- recheck: (again) => {
659
- recheck = again;
660
- }
661
- }
662
- }).then(async () => {
663
- if (cmd === "wait" && !fallback) try {
664
- const pages = await api(`/api/status?page=${encodeURIComponent(f.page)}`);
665
- for (const p of pages) if (p.open.length) console.error(`whiteboard: still unanswered on ${p.page}: ${p.open.join(", ")} → run \`whiteboard wait --page ${relFile(p.file)}\` again, in the background, once you've acted on this`);
666
- } catch {}
667
- process.exit(0);
668
- });
669
- if (!fallback) listen(f, cmd);
561
+ forAgent: forAgent(handedOut)
562
+ };
670
563
  if (opts.timeout && cmd === "wait") setTimeout(() => {
671
564
  console.error("timeout");
672
565
  process.exit(2);
673
566
  }, Number(opts.timeout) * 1e3);
567
+ if (!f.page) {
568
+ const update = fallback((_, handing) => {
569
+ handOut(proj.eventsFile, f, (e) => console.log(JSON.stringify(e)), {
570
+ ...options,
571
+ ...handing
572
+ }).then(() => process.exit(0));
573
+ });
574
+ await listen({
575
+ at,
576
+ query: {
577
+ ...query,
578
+ fallback: ""
579
+ },
580
+ onSnapshot: update,
581
+ onRefused: refused
582
+ });
583
+ } else {
584
+ await listen({
585
+ at,
586
+ query,
587
+ onRefused: refused
588
+ }, { orNone: true });
589
+ handOut(proj.eventsFile, f, (e) => console.log(JSON.stringify(e)), options).then(async () => {
590
+ if (cmd === "wait") try {
591
+ const pages = await api(`/api/status?page=${encodeURIComponent(f.page)}`);
592
+ for (const p of pages) if (p.open.length) console.error(`whiteboard: still unanswered on ${p.page}: ${p.open.join(", ")} → run \`whiteboard wait --page ${relFile(p.file)}\` again, in the background, once you've acted on this`);
593
+ } catch {}
594
+ process.exit(0);
595
+ });
596
+ }
674
597
  break;
675
598
  }
676
599
  case "append": {
@@ -791,67 +714,12 @@ async function entryFallback(entry, f, command) {
791
714
  console.error("timeout");
792
715
  process.exit(2);
793
716
  }, Number(opts.timeout) * 1e3);
794
- await new Promise((registered) => {
795
- const connect = async () => {
796
- const shared = await sharedServer(file);
797
- if (!shared) return setTimeout(connect, 2e3).unref();
798
- const q = new URLSearchParams({
799
- entry,
800
- command,
801
- ...f.type ? { type: f.type } : {}
802
- });
803
- let again = false;
804
- const retry = (ms) => {
805
- if (!again) {
806
- again = true;
807
- setTimeout(connect, ms).unref();
808
- }
809
- };
810
- const req = http.get(`${shared.origin}/api/listen?${q}`, (res) => {
811
- if (res.statusCode === 409) {
812
- let body = "";
813
- res.on("data", (d) => body += d);
814
- res.on("end", () => {
815
- console.error(`whiteboard: ${JSON.parse(body || "{}").error ?? "another agent is the fallback"}. Add --page to wait on a page of your own.`);
816
- process.exit(1);
817
- });
818
- return;
819
- }
820
- res.resume();
821
- registered();
822
- res.on("close", () => retry(1e3));
823
- });
824
- req.on("error", () => retry(2e3));
825
- req.on("socket", (socket) => socket.unref());
826
- };
827
- connect();
828
- });
829
- const following = /* @__PURE__ */ new Map();
830
- async function start(p, origin) {
717
+ let origin = "";
718
+ const page = (id) => id.split("/").map(encodeURIComponent).join("/");
719
+ const update = fallback((p, handing) => {
831
720
  const proj = project$1(p.dir);
832
721
  if (!proj) return;
833
- const stop = new AbortController();
834
- following.set(p.dir, stop);
835
- const { handedOut } = await projectConfig(proj);
836
- let recheck = () => {};
837
- const at = async () => {
838
- const shared = await sharedServer(file);
839
- const now = shared?.projects.find((x) => x.dir === p.dir);
840
- if (!shared || !now) throw new Error("not served");
841
- return `${shared.origin}${now.base}`;
842
- };
843
- const others = await otherListeners(() => recheck(), at);
844
- const held = /* @__PURE__ */ new Set();
845
- const skip = (e) => {
846
- if (!held.has(e.id)) {
847
- held.add(e.id);
848
- setTimeout(() => recheck(), 500).unref();
849
- return true;
850
- }
851
- return takenByOther(others(), e);
852
- };
853
- const page = (id) => id.split("/").map(encodeURIComponent).join("/");
854
- await handOut(proj.eventsFile, { type: f.type }, (e) => {
722
+ projectConfig(proj).then(({ handedOut }) => handOut(proj.eventsFile, { type: f.type }, (e) => {
855
723
  console.log(JSON.stringify({
856
724
  ...e,
857
725
  project: p.dir,
@@ -860,25 +728,27 @@ async function entryFallback(entry, f, command) {
860
728
  if (++total >= count) done.abort();
861
729
  }, {
862
730
  forAgent: forAgent(handedOut),
863
- signal: AbortSignal.any([stop.signal, done.signal]),
864
- skip,
865
- recheck: (again) => {
866
- recheck = again;
867
- }
868
- });
869
- }
870
- const sync = async () => {
871
- const shared = await sharedServer(file);
872
- if (!shared) return;
873
- const mine = shared.projects.filter((p) => p.entry === entry);
874
- for (const p of mine) if (!following.has(p.dir)) start(p, shared.origin);
875
- for (const [dir, stop] of following) if (!mine.some((p) => p.dir === dir)) {
876
- stop.abort();
877
- following.delete(dir);
731
+ ...handing,
732
+ signal: AbortSignal.any([handing.signal, done.signal])
733
+ }));
734
+ });
735
+ await listen({
736
+ at: async () => {
737
+ origin = (await sharedServer(file))?.origin ?? "";
738
+ return origin || null;
739
+ },
740
+ query: {
741
+ entry,
742
+ command,
743
+ ...f.type ? { type: f.type } : {}
744
+ },
745
+ onSnapshot: update,
746
+ onRefused: (reason) => {
747
+ console.error(`whiteboard: ${reason}. Add --page to wait on a page of your own.`);
748
+ process.exit(1);
878
749
  }
879
- };
880
- await sync();
881
- setInterval(sync, 2e3);
750
+ });
751
+ setInterval(() => {}, 1 << 30);
882
752
  }
883
753
  /** The commands the project's plugins add: `whiteboard <plugin> [sub]`. */
884
754
  async function projectCommands(proj) {
@@ -620,6 +620,16 @@ async function loadEvents() {
620
620
  const known = new Set(all.map((e) => e.id));
621
621
  for (const [id, e] of sending) if (known.has(id)) sending.delete(id);
622
622
  setEvents([...all, ...[...sending.values()]]);
623
+ scrollFromLog();
624
+ }
625
+ let scrolledTo;
626
+ function scrollFromLog() {
627
+ const last = events.findLast((e) => e.type === "whiteboard:scroll" && !fromReader(e));
628
+ if (scrolledTo === void 0) return void (scrolledTo = last?.id ?? null);
629
+ if (!last || last.id === scrolledTo) return;
630
+ scrolledTo = last.id;
631
+ const to = String(last.data?.to ?? "");
632
+ if (!scrollToTarget(root, to)) console.warn(`whiteboard scroll: nothing on the page matches ${JSON.stringify(to)}`);
623
633
  }
624
634
  /** How long one send may take before it is tried again, in ms; and how many tries in all. */
625
635
  const SEND_TIMEOUT = 8e3;
@@ -695,6 +705,38 @@ function writeTitle() {
695
705
  const list = [...badges.values()].toSorted((a, b) => a.order - b.order || a.since - b.since);
696
706
  document.title = `${list.map((b) => `(${b.text}) `).join("")}${baseTitle}`;
697
707
  }
708
+ /** The plugins in their order, which is the order of their elements in a slot. */
709
+ const pluginOrder = (handoff.plugins ?? []).map((p) => p.name);
710
+ /**
711
+ * Mount `owner`'s element in a slot (Api.slot): the one the server rendered with its markup, or a
712
+ * new one, put among the others in plugin order. What `mount` returns runs when it is taken away.
713
+ */
714
+ function slotFor(owner, name, mount) {
715
+ const holder = name === "corner" ? corner : name === "header" ? root.querySelector("[data-wb-slot=header]") : document.querySelector(`body > [data-wb-slot=${name}]`);
716
+ if (!holder) return () => {};
717
+ let el = [...holder.children].find((c) => c instanceof HTMLElement && c.dataset.plugin === owner);
718
+ if (!el) {
719
+ el = document.createElement("div");
720
+ el.dataset.plugin = owner;
721
+ const at = pluginOrder.indexOf(owner);
722
+ const next = [...holder.children].find((c) => c instanceof HTMLElement && c.dataset.plugin != null && pluginOrder.indexOf(c.dataset.plugin) > at);
723
+ holder.insertBefore(el, next ?? null);
724
+ }
725
+ const unmount = mount(el);
726
+ let gone = false;
727
+ return () => {
728
+ if (gone) return;
729
+ gone = true;
730
+ unmount?.();
731
+ el.remove();
732
+ };
733
+ }
734
+ /** The page's own element in the corner (its toasts), made the first time it is asked for. */
735
+ let pageCorner = null;
736
+ const cornerOfPage = () => {
737
+ if (!pageCorner) slotFor("", "corner", (el) => void (pageCorner = el));
738
+ return pageCorner ?? corner;
739
+ };
698
740
  const api = {
699
741
  page,
700
742
  url,
@@ -721,7 +763,7 @@ const api = {
721
763
  renderedListeners.add(fn);
722
764
  return () => renderedListeners.delete(fn);
723
765
  },
724
- corner: () => corner,
766
+ slot: (name, mount) => slotFor("", name, mount),
725
767
  badge(key, text, order = 0) {
726
768
  if (text == null) badges.delete(key);
727
769
  else badges.set(key, {
@@ -735,7 +777,7 @@ const api = {
735
777
  baseTitle = title;
736
778
  writeTitle();
737
779
  },
738
- toast: createToast(() => corner),
780
+ toast: createToast(cornerOfPage),
739
781
  ...formsApi
740
782
  };
741
783
  const changeListeners = /* @__PURE__ */ new Set();
@@ -799,11 +841,8 @@ const onLive = {
799
841
  listeners: () => loadListeners(),
800
842
  elsewhere: () => document.dispatchEvent(new Event("wb-elsewhere")),
801
843
  reload: () => reloadWhenUp(),
802
- scroll: (data) => {
803
- const { to } = data;
804
- if (!scrollToTarget(root, to)) console.warn(`whiteboard scroll: nothing on the page matches ${JSON.stringify(to)}`);
805
- },
806
844
  style: () => {
845
+ stamps = null;
807
846
  for (const link of document.querySelectorAll("link[rel=stylesheet]")) {
808
847
  const url = new URL(link.href);
809
848
  if (url.origin !== location.origin) continue;
@@ -812,6 +851,22 @@ const onLive = {
812
851
  }
813
852
  }
814
853
  };
854
+ let stamps = handoff.stamps ?? null;
855
+ /**
856
+ * Back on the live channel: what changed while this page wasn't on it, it never heard of. Browser
857
+ * code that changed reloads the page; stylesheets that changed are refreshed in place.
858
+ */
859
+ async function compareStamps() {
860
+ let now;
861
+ try {
862
+ now = await (await fetch(url("/api/stamps"), { cache: "no-store" })).json();
863
+ } catch {
864
+ return;
865
+ }
866
+ if (stamps && now.code !== stamps.code) return reloadWhenUp();
867
+ if (stamps && now.style !== stamps.style) onLive.style(null);
868
+ stamps = now;
869
+ }
815
870
  let socket = null;
816
871
  let retries = 0;
817
872
  let retryTimer;
@@ -826,6 +881,7 @@ function connect() {
826
881
  document.documentElement.dataset.wbLive = "";
827
882
  loadListeners();
828
883
  loadEvents();
884
+ compareStamps();
829
885
  document.dispatchEvent(new Event("wb-elsewhere"));
830
886
  caughtUp();
831
887
  };
@@ -895,7 +951,10 @@ await Promise.all((handoff.plugins ?? []).map(async (ext) => {
895
951
  try {
896
952
  const mount = (await import(moduleUrl(ext.client))).default;
897
953
  if (typeof mount !== "function") throw new Error("the client module must export a mount(root, page, api) function as default");
898
- await mount(root, handleFor(ext.name), api);
954
+ await mount(root, handleFor(ext.name), {
955
+ ...api,
956
+ slot: (name, mount) => slotFor(ext.name, name, mount)
957
+ });
899
958
  } catch (err) {
900
959
  console.error(`plugin ${ext.name}:`, err);
901
960
  root.insertAdjacentHTML("afterbegin", String(html`<pre class="wb-error" role="alert">
@@ -44,6 +44,7 @@
44
44
  }
45
45
  .wb-chat-bubble {
46
46
  max-width: 100%;
47
+ min-width: 0;
47
48
  box-sizing: border-box;
48
49
  white-space: pre-wrap;
49
50
  padding: var(--space-md) var(--space-xl);
@@ -62,18 +63,19 @@
62
63
  .wb-chat-bubble[data-md] > :last-child {
63
64
  margin-bottom: 0;
64
65
  }
65
- .wb-chat-bubble[data-md] :is(p, ul, ol, pre, blockquote) {
66
+ .wb-chat-bubble[data-md] :is(p, ul, ol, pre, blockquote, table) {
66
67
  margin: 0 0 0.5em;
67
68
  }
68
- /* code wraps at the bubble's edge, as the text around it does: a long line would otherwise make the
69
- bubble as wide (it fits its content), and the chat and the page with it; and a scrollbar under it
70
- is drawn over the text below in WebKit (its height left out when the block first lays out) */
69
+ /* a table's cells wrap between words, not inside them (the bubble's own wrapping anywhere would
70
+ squeeze its columns down to a letter); one too wide for the bubble scrolls sideways */
71
+ .wb-chat-bubble[data-md] table {
72
+ overflow-wrap: normal;
73
+ }
74
+ /* code keeps its lines whole and scrolls sideways, as on a page (code/style.css: {wrap} wraps it) */
71
75
  .wb-chat-bubble[data-md] pre {
72
76
  font-size: var(--ui-small);
73
77
  padding: var(--space-md) var(--space-lg);
74
78
  border-radius: var(--radius-sm);
75
- white-space: pre-wrap;
76
- overflow-wrap: anywhere;
77
79
  }
78
80
  .wb-chat-message[data-from='you'] .wb-chat-bubble[data-md] a {
79
81
  color: inherit;
@@ -102,6 +104,8 @@
102
104
  border-top: var(--hairline) solid var(--border);
103
105
  border-bottom: var(--hairline) solid var(--border);
104
106
  display: grid;
107
+ /* one column, as wide as the block: wide content (a code block) scrolls inside it, not past it */
108
+ grid-template-columns: minmax(0, 1fr);
105
109
  gap: var(--space-2xl);
106
110
  }
107
111
  .wb-chat-block > :first-child {
@@ -22,6 +22,16 @@ bare `@@`: its lines show without numbers. `---` and `+++` lines name the file
22
22
  without a `diff --git` above them. Use four backticks around it, since a diff
23
23
  can hold three.
24
24
 
25
+ A line longer than the block scrolls it sideways, on a page and in a chat
26
+ message alike. A fence that says `{wrap}` wraps its long lines at the block's
27
+ edge instead, a diff's rows too:
28
+
29
+ ````markdown
30
+ ```sh {wrap}
31
+ whiteboard append --page plan --type chat:message --data '{"chat":"notes","text":"a long line"}'
32
+ ```
33
+ ````
34
+
25
35
  A missing or unknown language renders as plain text. Fences named after
26
36
  another block, such as `mermaid`, still go to that block.
27
37
 
@@ -23,8 +23,11 @@ function code(options = {}) {
23
23
  let highlighter;
24
24
  let shiki;
25
25
  const loaded = /* @__PURE__ */ new Set();
26
- /** Highlight `code` as `lang`; an unknown or missing language renders as plain text. */
27
- async function highlight(code, lang) {
26
+ /**
27
+ * Highlight `code` as `lang`; an unknown or missing language renders as plain text. A long line
28
+ * scrolls the block sideways; with `wrap` it wraps at the block's edge.
29
+ */
30
+ async function highlight(code, lang, wrap = false) {
28
31
  shiki ??= await import("shiki");
29
32
  highlighter ??= shiki.createHighlighter({
30
33
  themes: Object.values(themes),
@@ -39,38 +42,44 @@ function code(options = {}) {
39
42
  }
40
43
  } else language = "text";
41
44
  const diff = language === "diff" ? diffLines(code) : null;
45
+ const transformers = [];
46
+ if (wrap) transformers.push({ pre(node) {
47
+ node.properties["data-wrap"] = "";
48
+ } });
49
+ if (diff) transformers.push({
50
+ line(node, n) {
51
+ const info = diff[n - 1];
52
+ if (!info) return;
53
+ node.properties["data-diff"] = info.kind;
54
+ if (info.n != null) node.properties["data-n"] = String(info.n);
55
+ if (info.at) node.properties["data-wb-at"] = info.at;
56
+ if (info.label != null) node.children = [{
57
+ type: "text",
58
+ value: info.label
59
+ }];
60
+ },
61
+ code(node) {
62
+ node.children = node.children.filter((child, i, all) => {
63
+ const isMeta = (c) => c?.type === "element" && c.properties["data-diff"] === "meta";
64
+ return !isMeta(child) && !(child.type === "text" && isMeta(all[i - 1]));
65
+ });
66
+ }
67
+ });
42
68
  return h.codeToHtml(code, {
43
69
  lang: language,
44
70
  themes,
45
71
  defaultColor: false,
46
72
  colorReplacements,
47
- transformers: diff ? [{
48
- line(node, n) {
49
- const info = diff[n - 1];
50
- if (!info) return;
51
- node.properties["data-diff"] = info.kind;
52
- if (info.n != null) node.properties["data-n"] = String(info.n);
53
- if (info.at) node.properties["data-wb-at"] = info.at;
54
- if (info.label != null) node.children = [{
55
- type: "text",
56
- value: info.label
57
- }];
58
- },
59
- code(node) {
60
- node.children = node.children.filter((child, i, all) => {
61
- const isMeta = (c) => c?.type === "element" && c.properties["data-diff"] === "meta";
62
- return !isMeta(child) && !(child.type === "text" && isMeta(all[i - 1]));
63
- });
64
- }
65
- }] : []
73
+ transformers
66
74
  });
67
75
  }
68
76
  return definePlugin({
69
77
  name: "code",
70
78
  public: builtinPublic("code"),
79
+ setup: () => ({ client: "client.js" }),
71
80
  blocks: { code: {
72
81
  fence: "any",
73
- html: (ctx) => highlight(ctx.text, ctx.lang),
82
+ html: (ctx) => highlight(ctx.text, ctx.lang, "wrap" in ctx.attrs),
74
83
  style: "style.css"
75
84
  } },
76
85
  docs: () => fs.readFileSync(new URL("./README.md", import.meta.url), "utf8")
@@ -0,0 +1 @@
1
+ const e=`pre.shiki > code`,t=t=>{let n=e=>{let t=String(e.scrollWidth>e.clientWidth);e.dataset.overflow!==t&&(e.dataset.overflow=t)},r=new ResizeObserver(e=>{for(let{target:t}of e)n(t)}),i=/* @__PURE__ */ new WeakSet,a=t=>{let a=t.matches(e)?[t]:t.querySelectorAll(e);for(let e of a)n(e),i.has(e)||(i.add(e),r.observe(e))};a(t),document.fonts?.addEventListener(`loadingdone`,()=>{for(let r of t.querySelectorAll(e))n(r)}),new MutationObserver(t=>{for(let r of t){if(r.type===`characterData`){let t=r.target.parentElement?.closest(e);t&&n(t);continue}for(let e of r.addedNodes)e instanceof Element&&a(e);let t=r.target instanceof Element?r.target.closest(e):null;t&&n(t)}}).observe(t,{childList:!0,characterData:!0,subtree:!0})};export{t as default};
@@ -24,12 +24,39 @@ pre.shiki {
24
24
  text-decoration: var(--shiki-dark-text-decoration);
25
25
  }
26
26
 
27
+ /* a long line scrolls the block sideways, wherever it is; a fence that says {wrap} wraps it. The
28
+ code inside the block scrolls, not the block: WebKit sizes a block that scrolls sideways without
29
+ its scrollbar, so the bar ate into its height (a vertical scrollbar came with it) */
30
+ pre.shiki {
31
+ white-space: pre;
32
+ overflow-wrap: normal;
33
+ overflow: visible;
34
+ }
35
+ pre.shiki > code {
36
+ display: block;
37
+ overflow-x: auto;
38
+ overflow-y: hidden;
39
+ }
40
+ /* the scrollbar chosen in advance, from measured overflow (client.ts): WebKit lays out an `auto`
41
+ scrollbar under a flex or grid ancestor after the ancestors, which keep the height they had
42
+ without it (https://github.com/block/buzz-app/pull/1677,
43
+ https://bugs.webkit.org/show_bug.cgi?id=51148) */
44
+ pre.shiki > code[data-overflow='true'] {
45
+ overflow-x: scroll;
46
+ }
47
+ pre.shiki > code[data-overflow='false'] {
48
+ overflow-x: hidden;
49
+ }
50
+ pre.shiki[data-wrap] {
51
+ white-space: pre-wrap;
52
+ overflow-wrap: anywhere;
53
+ }
54
+
27
55
  /* a diff: one row per line, as wide as the longest (a grid leaves out the line breaks between them,
28
56
  which stay in the text), tinted by what it is, with its number in a gutter */
29
57
  .shiki code:has(> .line[data-diff]) {
30
58
  display: grid;
31
- width: max-content;
32
- min-width: 100%;
59
+ grid-template-columns: minmax(max-content, 1fr);
33
60
  }
34
61
  .shiki .line[data-diff='add'] {
35
62
  background: color-mix(in srgb, #16a34a var(--tint-soft), transparent);
@@ -66,3 +93,7 @@ pre.shiki {
66
93
  .shiki .line[data-diff='file'] + .line[data-diff='hunk'] {
67
94
  margin-top: 0;
68
95
  }
96
+ /* a diff that wraps: its rows fill the block, and a long one wraps inside its row */
97
+ pre.shiki[data-wrap] code:has(> .line[data-diff]) {
98
+ grid-template-columns: minmax(0, 1fr);
99
+ }
@@ -21,4 +21,4 @@ var e=class{value;constructor(e){this.value=e}toString(){return this.value}};con
21
21
  <div class="wb-thread-actions">
22
22
  <button type="submit" class="wb-comment-button wb-comment-primary">Comment</button
23
23
  ><button type="button" class="wb-comment-button" data-cancel>Cancel</button>
24
- </div>`);function H(){if(!j)return;V.querySelector(`blockquote`).textContent=j.at?`${j.at}\n${j.quote}`:j.quote,V.style.top=h.style.top;let e=Math.min(360,document.documentElement.clientWidth-32);V.style.width=`${e}px`,V.style.left=`${Math.max(16+scrollX,Math.min(parseFloat(h.style.left),document.documentElement.clientWidth-e-16+scrollX))}px`,V.hidden=!1,h.hidden=!0,V.querySelector(`textarea`).focus({preventScroll:!0})}const U=(e,t,n)=>{if(t.kind!==`page`&&t.kind!==`file`)return;l=e,d=l.querySelector(`main`)??l,u=n,document.body.append(m,h,P,g,V),document.addEventListener(`mousemove`,B),document.documentElement.addEventListener(`mouseleave`,()=>{I||(P.hidden=!0,F=null)}),P.addEventListener(`mousedown`,e=>{if(!F||e.button!==0)return;e.preventDefault();let t=CSS.highlights,n=window.Highlight;t&&n&&t.set(`wb-comment-active`,new n(R(F,F))),I={pre:F.closest(`pre`),from:F,to:F}}),document.addEventListener(`mouseup`,()=>{if(!I)return;let{from:e,to:t}=I;I=null,P.hidden=!0,N(R(e,t))?H():C()});let r=0;document.addEventListener(`selectionchange`,()=>{clearTimeout(r),r=window.setTimeout(M,150)}),h.addEventListener(`mousedown`,e=>e.preventDefault()),h.addEventListener(`click`,H);for(let e of[V,g])e.addEventListener(`keydown`,e=>{let t=e.target;t.tagName!==`TEXTAREA`||e.key!==`Enter`||e.shiftKey||e.isComposing||(e.preventDefault(),t.closest(`form`)?.requestSubmit())});V.addEventListener(`submit`,async e=>{e.preventDefault();let t=V.querySelector(`textarea`).value.trim();if(!t||!j)return;let n=j,r=u.append(o,{...n,text:t}),i=u.events().findLast(e=>e.type===o&&e.sending&&e.data.text===t);V.querySelector(`textarea`).value=``,V.hidden=!0,j=null,getSelection()?.removeAllRanges(),T(),i&&k(i.id);try{await r}catch(e){if(console.error(`comments:`,e),!V.hidden)return;j=n,V.querySelector(`textarea`).value=t,V.hidden=!1,u.toast(`Couldn't send the comment`,{kind:`alert`,name:`comment-failed`,details:`It's back in the box: send it again.`})}}),V.querySelector(`[data-cancel]`).addEventListener(`click`,()=>{V.hidden=!0,j=null}),m.addEventListener(`click`,e=>{let t=e.target.closest(`[data-thread]`)?.dataset.thread;t&&(p===t?A():k(t))}),g.addEventListener(`submit`,async e=>{e.preventDefault();let t=g.querySelector(`textarea`),n=t.value.trim();if(!n||!p)return;let r=p;t.value=``;let i=u.append(s,{replyTo:r,text:n});T();try{await i}catch(e){console.error(`comments:`,e);let t=g.querySelector(`textarea`);p===r&&t&&!t.value.trim()&&(t.value=n),u.toast(`Couldn't send the reply`,{kind:`alert`,name:`comment-failed`,details:`It's back in the box: send it again.`})}}),g.addEventListener(`click`,async e=>{if(!e.target.closest(`[data-close]`)||!p)return;let t=p;A(),u.markRead(f.find(e=>e.id===t)?.replies.map(e=>e.id)??[]);let n=u.append(c,{replyTo:t});T(),n.catch(e=>{console.error(`comments:`,e),u.toast(`Couldn't close the thread`,{kind:`alert`,name:`comment-failed`,details:`It's open again.`})})}),m.addEventListener(`wb-reveal`,e=>{let t=e.target.closest(`[data-thread]`)?.dataset.thread;t&&p!==t&&k(t)}),document.addEventListener(`dblclick`,e=>{let t=e.target;!p||g.contains(t)||m.contains(t)||A()}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&(V.hidden?p&&A():(V.hidden=!0,j=null))}),u.events.on(T),u.onRendered(T),new ResizeObserver(()=>C()).observe(l),addEventListener(`resize`,()=>C()),T()};export{U as default};
24
+ </div>`);function H(){if(!j)return;V.querySelector(`blockquote`).textContent=j.at?`${j.at}\n${j.quote}`:j.quote,V.style.top=h.style.top;let e=Math.min(360,document.documentElement.clientWidth-32);V.style.width=`${e}px`,V.style.left=`${Math.max(16+scrollX,Math.min(parseFloat(h.style.left),document.documentElement.clientWidth-e-16+scrollX))}px`,V.hidden=!1,h.hidden=!0,V.querySelector(`textarea`).focus({preventScroll:!0})}const U=(e,t,n)=>{if(t.kind!==`page`&&t.kind!==`file`)return;l=e,d=l.querySelector(`main`)??l,u=n,n.slot(`overlay`,e=>(e.append(m,h,P,g,V),()=>{for(let e of[m,h,P,g,V])e.remove()})),document.addEventListener(`mousemove`,B),document.documentElement.addEventListener(`mouseleave`,()=>{I||(P.hidden=!0,F=null)}),P.addEventListener(`mousedown`,e=>{if(!F||e.button!==0)return;e.preventDefault();let t=CSS.highlights,n=window.Highlight;t&&n&&t.set(`wb-comment-active`,new n(R(F,F))),I={pre:F.closest(`pre`),from:F,to:F}}),document.addEventListener(`mouseup`,()=>{if(!I)return;let{from:e,to:t}=I;I=null,P.hidden=!0,N(R(e,t))?H():C()});let r=0;document.addEventListener(`selectionchange`,()=>{clearTimeout(r),r=window.setTimeout(M,150)}),h.addEventListener(`mousedown`,e=>e.preventDefault()),h.addEventListener(`click`,H);for(let e of[V,g])e.addEventListener(`keydown`,e=>{let t=e.target;t.tagName!==`TEXTAREA`||e.key!==`Enter`||e.shiftKey||e.isComposing||(e.preventDefault(),t.closest(`form`)?.requestSubmit())});V.addEventListener(`submit`,async e=>{e.preventDefault();let t=V.querySelector(`textarea`).value.trim();if(!t||!j)return;let n=j,r=u.append(o,{...n,text:t}),i=u.events().findLast(e=>e.type===o&&e.sending&&e.data.text===t);V.querySelector(`textarea`).value=``,V.hidden=!0,j=null,getSelection()?.removeAllRanges(),T(),i&&k(i.id);try{await r}catch(e){if(console.error(`comments:`,e),!V.hidden)return;j=n,V.querySelector(`textarea`).value=t,V.hidden=!1,u.toast(`Couldn't send the comment`,{kind:`alert`,name:`comment-failed`,details:`It's back in the box: send it again.`})}}),V.querySelector(`[data-cancel]`).addEventListener(`click`,()=>{V.hidden=!0,j=null}),m.addEventListener(`click`,e=>{let t=e.target.closest(`[data-thread]`)?.dataset.thread;t&&(p===t?A():k(t))}),g.addEventListener(`submit`,async e=>{e.preventDefault();let t=g.querySelector(`textarea`),n=t.value.trim();if(!n||!p)return;let r=p;t.value=``;let i=u.append(s,{replyTo:r,text:n});T();try{await i}catch(e){console.error(`comments:`,e);let t=g.querySelector(`textarea`);p===r&&t&&!t.value.trim()&&(t.value=n),u.toast(`Couldn't send the reply`,{kind:`alert`,name:`comment-failed`,details:`It's back in the box: send it again.`})}}),g.addEventListener(`click`,async e=>{if(!e.target.closest(`[data-close]`)||!p)return;let t=p;A(),u.markRead(f.find(e=>e.id===t)?.replies.map(e=>e.id)??[]);let n=u.append(c,{replyTo:t});T(),n.catch(e=>{console.error(`comments:`,e),u.toast(`Couldn't close the thread`,{kind:`alert`,name:`comment-failed`,details:`It's open again.`})})}),m.addEventListener(`wb-reveal`,e=>{let t=e.target.closest(`[data-thread]`)?.dataset.thread;t&&p!==t&&k(t)}),document.addEventListener(`dblclick`,e=>{let t=e.target;!p||g.contains(t)||m.contains(t)||A()}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&(V.hidden?p&&A():(V.hidden=!0,j=null))}),u.events.on(T),u.onRendered(T),new ResizeObserver(()=>C()).observe(l),addEventListener(`resize`,()=>C()),T()};export{U as default};
@@ -5,6 +5,8 @@
5
5
  border-top: var(--hairline) solid var(--border);
6
6
  border-bottom: var(--hairline) solid var(--border);
7
7
  display: grid;
8
+ /* one column, as wide as the form: wide content (a code block) scrolls inside it, not past it */
9
+ grid-template-columns: minmax(0, 1fr);
8
10
  gap: var(--space-2xl);
9
11
  }
10
12
  .wb-form-pending {