@bigmistqke/whiteboard 0.6.1 → 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 (101) hide show
  1. package/README.md +23 -216
  2. package/bin/whiteboard.ts +82 -239
  3. package/dist/bin/whiteboard.js +70 -200
  4. package/dist/client/runtime.js +297 -61
  5. package/dist/plugins/badge/README.md +3 -1
  6. package/dist/plugins/badge/public/style.css +17 -0
  7. package/dist/plugins/chat/public/client.js +2 -2
  8. package/dist/plugins/chat/public/style.css +19 -6
  9. package/dist/plugins/code/README.md +10 -0
  10. package/dist/plugins/code/index.js +31 -22
  11. package/dist/plugins/code/public/client.js +1 -0
  12. package/dist/plugins/code/public/style.css +33 -2
  13. package/dist/plugins/comments/public/client.js +7 -2
  14. package/dist/plugins/comments/public/style.css +4 -0
  15. package/dist/plugins/form/public/style.css +2 -0
  16. package/dist/plugins/grid/public/style.css +0 -5
  17. package/dist/plugins/iframe/index.js +2 -2
  18. package/dist/plugins/index.js +5 -1
  19. package/dist/plugins/lightbox/public/client.js +1 -1
  20. package/dist/plugins/terminal/index.js +7 -9
  21. package/dist/plugins/terminal/public/client.js +1 -1
  22. package/dist/plugins/terminal/public/style.css +3 -3
  23. package/dist/plugins/timeline/README.md +40 -0
  24. package/dist/plugins/timeline/index.js +82 -0
  25. package/dist/plugins/timeline/public/style.css +118 -0
  26. package/dist/plugins/toc/README.md +13 -13
  27. package/dist/plugins/toc/index.js +6 -4
  28. package/dist/plugins/toc/public/client.js +1 -1
  29. package/dist/plugins/toc/public/style.css +19 -2
  30. package/dist/plugins/window/index.js +4 -4
  31. package/dist/solid/index.js +2 -1
  32. package/dist/src/auth.js +7 -3
  33. package/dist/src/build.js +159 -0
  34. package/dist/src/client/page/base.css +74 -35
  35. package/dist/src/client/page/main.js +16 -5
  36. package/dist/src/document.js +93 -0
  37. package/dist/src/events.js +7 -15
  38. package/dist/src/hub.js +90 -53
  39. package/dist/src/listen.js +100 -0
  40. package/dist/src/listeners.js +67 -0
  41. package/dist/src/pages/index.js +1 -1
  42. package/dist/src/pages/markdown.js +23 -11
  43. package/dist/src/pages/render.js +13 -8
  44. package/dist/src/serve.js +2 -0
  45. package/dist/src/server.js +204 -514
  46. package/dist/src/site.js +173 -0
  47. package/dist/src/status.js +63 -1
  48. package/dist/src/ws.js +128 -0
  49. package/package.json +1 -1
  50. package/plugins/README.md +258 -0
  51. package/plugins/badge/README.md +3 -1
  52. package/plugins/badge/public/style.css +17 -0
  53. package/plugins/chat/client.tsx +34 -6
  54. package/plugins/chat/public/style.css +19 -6
  55. package/plugins/code/README.md +10 -0
  56. package/plugins/code/client.ts +73 -0
  57. package/plugins/code/index.ts +38 -26
  58. package/plugins/code/public/style.css +33 -2
  59. package/plugins/comments/client.ts +56 -6
  60. package/plugins/comments/public/style.css +4 -0
  61. package/plugins/form/public/style.css +2 -0
  62. package/plugins/grid/public/style.css +0 -5
  63. package/plugins/iframe/index.ts +2 -2
  64. package/plugins/index.ts +6 -1
  65. package/plugins/lightbox/client.ts +13 -3
  66. package/plugins/terminal/client.ts +10 -2
  67. package/plugins/terminal/index.ts +8 -6
  68. package/plugins/terminal/public/style.css +3 -3
  69. package/plugins/timeline/README.md +40 -0
  70. package/plugins/timeline/index.ts +92 -0
  71. package/plugins/timeline/public/style.css +118 -0
  72. package/plugins/toc/README.md +13 -13
  73. package/plugins/toc/client.ts +58 -32
  74. package/plugins/toc/index.ts +13 -13
  75. package/plugins/toc/public/style.css +19 -2
  76. package/plugins/window/index.ts +4 -4
  77. package/skills/whiteboard/SKILL.md +3 -1
  78. package/solid/index.tsx +3 -0
  79. package/src/auth.ts +7 -2
  80. package/src/build.ts +213 -0
  81. package/src/client/forms.ts +102 -5
  82. package/src/client/page/base.css +74 -35
  83. package/src/client/page/elsewhere.ts +14 -4
  84. package/src/client/page/waiting.ts +10 -5
  85. package/src/client/read.ts +16 -3
  86. package/src/client/runtime.ts +219 -52
  87. package/src/client/toast.ts +36 -6
  88. package/src/define.ts +44 -18
  89. package/src/document.ts +191 -0
  90. package/src/events.ts +18 -17
  91. package/src/hub.ts +102 -56
  92. package/src/listen.ts +125 -0
  93. package/src/listeners.ts +95 -0
  94. package/src/pages/index.ts +1 -1
  95. package/src/pages/markdown.ts +29 -18
  96. package/src/pages/render.ts +13 -8
  97. package/src/serve.ts +2 -0
  98. package/src/server.ts +223 -611
  99. package/src/site.ts +165 -0
  100. package/src/status.ts +100 -0
  101. package/src/ws.ts +155 -0
@@ -201,26 +201,96 @@ function restoreLast(prefill) {
201
201
  if (prefill && !keepsOwnFields(form)) writeForm(form, last.data);
202
202
  }
203
203
  }
204
+ /** What each form is sending now, as sent: the same answer again is not sent twice. */
205
+ const inFlight = /* @__PURE__ */ new WeakMap();
206
+ /** A button's own label, while it says how a send goes. */
207
+ const labelOf = (button) => {
208
+ const el = document.createElement("div");
209
+ el.innerHTML = labels.get(button).html;
210
+ return el.textContent?.trim() ?? "";
211
+ };
212
+ const SEND_TEXT = {
213
+ sending: "Sending…",
214
+ sent: "✓ Sent",
215
+ failed: "Try again"
216
+ };
217
+ const labels = /* @__PURE__ */ new WeakMap();
218
+ function sendState(button, state) {
219
+ if (!button) return;
220
+ let saved = labels.get(button);
221
+ clearTimeout(saved?.timer);
222
+ if (!state) {
223
+ if (!saved) return;
224
+ button.innerHTML = saved.html;
225
+ button.style.minWidth = "";
226
+ delete button.dataset.wbSend;
227
+ labels.delete(button);
228
+ return;
229
+ }
230
+ if (!saved) {
231
+ saved = { html: button.innerHTML };
232
+ labels.set(button, saved);
233
+ button.style.minWidth = `${button.getBoundingClientRect().width}px`;
234
+ }
235
+ button.dataset.wbSend = state;
236
+ button.textContent = SEND_TEXT[state];
237
+ if (state === "sent") saved.timer = setTimeout(() => sendState(button, null), 2e3);
238
+ }
204
239
  async function onSubmit(e) {
205
240
  const form = e.target;
206
241
  if (!managed(form) || !root$1.contains(form)) return;
207
242
  e.preventDefault();
208
243
  const button = e.submitter;
209
- const action = button ? button.value || button.textContent?.trim() || null : null;
244
+ const label = button ? labels.get(button) ? labelOf(button) : button.textContent?.trim() : null;
245
+ const action = button ? button.value || label || null : null;
246
+ const data = readForm(form);
247
+ const sent = JSON.stringify([action, data]);
248
+ if (inFlight.get(form) === sent) return;
249
+ inFlight.set(form, sent);
250
+ const before = form.dataset.wbSent;
210
251
  form.dataset.wbState = "sending";
252
+ form.dataset.wbSent = action ?? "";
253
+ form.removeAttribute("data-wb-just-sent");
254
+ sendState(button, "sending");
255
+ showStatus(form);
211
256
  try {
212
- await api$1.append(form.getAttribute("name"), readForm(form), action);
257
+ await api$1.append(form.getAttribute("name"), data, action);
258
+ if (inFlight.get(form) !== sent) return;
213
259
  dropDraft(form);
214
260
  form.dataset.wbState = "sent";
215
- form.dataset.wbSent = action ?? "";
261
+ sendState(button, "sent");
216
262
  form.toggleAttribute("data-wb-just-sent", true);
217
263
  clearTimeout(justSent.get(form));
218
- justSent.set(form, setTimeout(() => form.removeAttribute("data-wb-just-sent"), 3e3));
264
+ justSent.set(form, setTimeout(() => {
265
+ form.removeAttribute("data-wb-just-sent");
266
+ showStatus(form);
267
+ }, 3e3));
268
+ showStatus(form);
219
269
  } catch (err) {
270
+ if (inFlight.get(form) !== sent) return;
220
271
  form.dataset.wbState = "failed";
272
+ sendState(button, "failed");
273
+ if (before == null) delete form.dataset.wbSent;
274
+ else form.dataset.wbSent = before;
275
+ showStatus(form);
221
276
  console.error(err);
277
+ } finally {
278
+ if (inFlight.get(form) === sent) inFlight.delete(form);
222
279
  }
223
280
  }
281
+ const sendButtons = (form) => [...form.querySelectorAll("button, input[type=submit]")].filter((b) => (b instanceof HTMLInputElement || b.type !== "button" && b.type !== "reset") && b.form === form);
282
+ function showStatus(form) {
283
+ const text = form.dataset.wbState === "failed" ? ["couldn't send it", "bad"] : form.dataset.wbState === "sending" || !form.hasAttribute("data-wb-pending") ? null : ["waiting for the agent to pick it up", null];
284
+ let el = form.querySelector(".wb-form-status");
285
+ const last = sendButtons(form).at(-1);
286
+ if (!text || !last) return void el?.remove();
287
+ if (!el) el = Object.assign(document.createElement("span"), { className: "wb-form-status" });
288
+ el.setAttribute("role", "status");
289
+ if (el.previousElementSibling !== last) last.after(el);
290
+ el.textContent = text[0];
291
+ if (text[1]) el.dataset.kind = text[1];
292
+ else delete el.dataset.kind;
293
+ }
224
294
  const ATTR = {
225
295
  open: "data-wb-open",
226
296
  pending: "data-wb-pending",
@@ -263,6 +333,7 @@ function mark() {
263
333
  for (const st of STATES) form.toggleAttribute(ATTR[st], st === state);
264
334
  if (state === "decided") form.dataset.wbOutcome = outcome(last.data, last.action);
265
335
  else delete form.dataset.wbOutcome;
336
+ showStatus(form);
266
337
  return {
267
338
  form,
268
339
  name,
@@ -312,8 +383,13 @@ function place(corner) {
312
383
  return box;
313
384
  }
314
385
  function createToast(corner) {
315
- return function toast(text, { kind = "info", ms = 7e3, onClick, onDismiss, name, order = 0 } = {}) {
386
+ return function toast(text, { kind = "info", ms = 7e3, onClick, onDismiss, name, order = 0, details } = {}) {
316
387
  const el = document.createElement("button");
388
+ let timer;
389
+ const close = () => {
390
+ clearTimeout(timer);
391
+ el.remove();
392
+ };
317
393
  el.type = "button";
318
394
  el.className = "wb-toast";
319
395
  el.dataset.kind = kind;
@@ -323,6 +399,26 @@ function createToast(corner) {
323
399
  label.className = "wb-toast-text";
324
400
  label.textContent = text;
325
401
  el.append(label);
402
+ let more = null;
403
+ let detail = null;
404
+ if (details) {
405
+ more = document.createElement("span");
406
+ more.className = "wb-toast-more";
407
+ detail = document.createElement("span");
408
+ detail.className = "wb-toast-details";
409
+ detail.textContent = details;
410
+ el.setAttribute("aria-description", details);
411
+ el.append(more, detail);
412
+ fold(false);
413
+ }
414
+ function fold(open) {
415
+ el.toggleAttribute("data-open", open);
416
+ detail.hidden = !open;
417
+ more.textContent = open ? "▾" : "▸";
418
+ more.title = open ? "Less" : "More";
419
+ clearTimeout(timer);
420
+ if (!open && ms) timer = setTimeout(close, ms);
421
+ }
326
422
  if (onDismiss) {
327
423
  const x = document.createElement("span");
328
424
  x.className = "wb-toast-dismiss";
@@ -330,17 +426,18 @@ function createToast(corner) {
330
426
  x.title = x.ariaLabel = "Dismiss";
331
427
  el.append(x);
332
428
  }
333
- const close = () => el.remove();
334
429
  el.addEventListener("click", (e) => {
335
- if (onDismiss && e.target.closest(".wb-toast-dismiss")) {
430
+ const target = e.target;
431
+ if (onDismiss && target.closest(".wb-toast-dismiss")) {
336
432
  close();
337
433
  onDismiss();
338
434
  return;
339
435
  }
436
+ if (details && target.closest(".wb-toast-more, .wb-toast-details")) return fold(!el.hasAttribute("data-open"));
340
437
  if (ms) close();
341
438
  onClick?.();
342
439
  });
343
- if (ms) setTimeout(close, ms);
440
+ if (ms && !details) timer = setTimeout(close, ms);
344
441
  place(corner()).append(el);
345
442
  return {
346
443
  close,
@@ -361,8 +458,8 @@ function createToast(corner) {
361
458
  let isMessage = () => false;
362
459
  let getEvents = () => [];
363
460
  let send = () => {};
364
- const sending = /* @__PURE__ */ new Set();
365
- const unread$1 = () => unreadMessages(getEvents(), isMessage).filter((e) => !sending.has(e.id));
461
+ const sending$1 = /* @__PURE__ */ new Set();
462
+ const unread$1 = () => unreadMessages(getEvents(), isMessage).filter((e) => !sending$1.has(e.id));
366
463
  const queued = /* @__PURE__ */ new Set();
367
464
  let timer = 0;
368
465
  function markRead(ids) {
@@ -370,7 +467,7 @@ function markRead(ids) {
370
467
  const fresh = ids.filter((id) => open.has(id));
371
468
  if (!fresh.length) return;
372
469
  for (const id of fresh) {
373
- sending.add(id);
470
+ sending$1.add(id);
374
471
  queued.add(id);
375
472
  }
376
473
  clearTimeout(timer);
@@ -382,17 +479,24 @@ function markRead(ids) {
382
479
  }
383
480
  /** Once the log has the reads, they need no holding. */
384
481
  function readsArrived(events) {
385
- for (const e of events) if (e.type === "whiteboard:read") for (const id of e.data?.ids ?? []) sending.delete(String(id));
482
+ for (const e of events) if (e.type === "whiteboard:read") for (const id of e.data?.ids ?? []) sending$1.delete(String(id));
483
+ }
484
+ const MOSTLY = .6;
485
+ function mostlyInView(entry) {
486
+ if (!entry.isIntersecting) return false;
487
+ if (entry.intersectionRatio >= MOSTLY) return true;
488
+ const viewport = entry.rootBounds?.height ?? window.innerHeight;
489
+ return entry.intersectionRect.height >= MOSTLY * viewport;
386
490
  }
387
491
  const inView = /* @__PURE__ */ new Set();
388
492
  const seen = new IntersectionObserver((entries) => {
389
493
  for (const entry of entries) {
390
494
  const id = entry.target.dataset.wbMessage;
391
- if (entry.isIntersecting) inView.add(id);
495
+ if (mostlyInView(entry)) inView.add(id);
392
496
  else inView.delete(id);
393
497
  }
394
498
  readVisible();
395
- }, { threshold: .6 });
499
+ }, { threshold: Array.from({ length: 21 }, (_, i) => i / 20) });
396
500
  function readVisible() {
397
501
  if (document.visibilityState === "visible" && inView.size) markRead([...inView]);
398
502
  }
@@ -512,25 +616,79 @@ function setEvents(next) {
512
616
  }
513
617
  async function loadEvents() {
514
618
  if (!live) return;
515
- setEvents((await (await fetch(url(`/api/events?page=${encodeURIComponent(page)}`))).json()).filter((e) => e.page === page));
516
- }
619
+ const all = (await (await fetch(url(`/api/events?page=${encodeURIComponent(page)}`))).json()).filter((e) => e.page === page);
620
+ const known = new Set(all.map((e) => e.id));
621
+ for (const [id, e] of sending) if (known.has(id)) sending.delete(id);
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)}`);
633
+ }
634
+ /** How long one send may take before it is tried again, in ms; and how many tries in all. */
635
+ const SEND_TIMEOUT = 8e3;
636
+ const TRIES = 4;
637
+ /** Events appended here that the server hasn't confirmed: kept in the events when they are loaded. */
638
+ const sending = /* @__PURE__ */ new Map();
639
+ /** An id as the server makes them (isEventId): the time in base 36, a dash, random hex. */
640
+ const newId = () => `${Date.now().toString(36)}-${[...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(6))].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
517
641
  async function append(type, data = {}, action = null) {
518
642
  if (!live) throw new Error("a built page is a file: there is no log to append to");
519
- const res = await fetch(url("/api/events"), {
520
- method: "POST",
521
- headers: { "content-type": "application/json" },
522
- body: JSON.stringify({
523
- page,
524
- type,
525
- action,
526
- data
527
- })
643
+ const id = newId();
644
+ const shown = {
645
+ id,
646
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
647
+ page,
648
+ type,
649
+ action,
650
+ data,
651
+ sending: true
652
+ };
653
+ sending.set(id, shown);
654
+ setEvents([...events, shown]);
655
+ const body = JSON.stringify({
656
+ id,
657
+ page,
658
+ type,
659
+ action,
660
+ data
528
661
  });
529
- if (!res.ok) throw new Error(await res.text());
530
- const saved = await res.json();
531
- if (!events.some((e) => e.id === saved.id)) setEvents([...events, saved]);
532
- return saved;
662
+ let failure;
663
+ for (let attempt = 0; attempt < TRIES; attempt++) {
664
+ if (attempt) await new Promise((r) => setTimeout(r, 500 * 2 ** attempt));
665
+ try {
666
+ const res = await fetch(url("/api/events"), {
667
+ method: "POST",
668
+ headers: { "content-type": "application/json" },
669
+ body,
670
+ signal: AbortSignal.timeout(SEND_TIMEOUT)
671
+ });
672
+ if (res.status >= 400 && res.status < 500) {
673
+ failure = new Error(await res.text());
674
+ break;
675
+ }
676
+ if (!res.ok) throw new Error(await res.text());
677
+ const saved = await res.json();
678
+ sending.delete(id);
679
+ setEvents([...events.filter((e) => e.id !== id && e.id !== saved.id), saved].toSorted(byTime));
680
+ return saved;
681
+ } catch (err) {
682
+ failure = err;
683
+ }
684
+ }
685
+ const arrived = !sending.has(id) && events.find((e) => e.id === id && !e.sending);
686
+ if (arrived) return arrived;
687
+ sending.delete(id);
688
+ setEvents(events.filter((e) => e.id !== id));
689
+ throw failure;
533
690
  }
691
+ const byTime = (a, b) => a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0;
534
692
  let listeners = [];
535
693
  const listenersValue = reactive(() => listeners);
536
694
  async function loadListeners() {
@@ -547,6 +705,38 @@ function writeTitle() {
547
705
  const list = [...badges.values()].toSorted((a, b) => a.order - b.order || a.since - b.since);
548
706
  document.title = `${list.map((b) => `(${b.text}) `).join("")}${baseTitle}`;
549
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
+ };
550
740
  const api = {
551
741
  page,
552
742
  url,
@@ -573,7 +763,7 @@ const api = {
573
763
  renderedListeners.add(fn);
574
764
  return () => renderedListeners.delete(fn);
575
765
  },
576
- corner: () => corner,
766
+ slot: (name, mount) => slotFor("", name, mount),
577
767
  badge(key, text, order = 0) {
578
768
  if (text == null) badges.delete(key);
579
769
  else badges.set(key, {
@@ -587,7 +777,7 @@ const api = {
587
777
  baseTitle = title;
588
778
  writeTitle();
589
779
  },
590
- toast: createToast(() => corner),
780
+ toast: createToast(cornerOfPage),
591
781
  ...formsApi
592
782
  };
593
783
  const changeListeners = /* @__PURE__ */ new Set();
@@ -636,44 +826,87 @@ if (!handoff.client) handle.onChange(async () => {
636
826
  root.innerHTML = (await handle.render()).html;
637
827
  api.rendered();
638
828
  });
829
+ const reloadWhenUp = async () => {
830
+ try {
831
+ if ((await fetch(url("/api/health"), { cache: "no-store" })).ok) return location.reload();
832
+ } catch {}
833
+ setTimeout(reloadWhenUp, 500);
834
+ };
835
+ /** What the server says on the live channel, by its name. */
836
+ const onLive = {
837
+ change: () => {
838
+ for (const fn of changeListeners) fn();
839
+ },
840
+ events: () => loadEvents(),
841
+ listeners: () => loadListeners(),
842
+ elsewhere: () => document.dispatchEvent(new Event("wb-elsewhere")),
843
+ reload: () => reloadWhenUp(),
844
+ style: () => {
845
+ stamps = null;
846
+ for (const link of document.querySelectorAll("link[rel=stylesheet]")) {
847
+ const url = new URL(link.href);
848
+ if (url.origin !== location.origin) continue;
849
+ url.searchParams.set("t", String(Date.now()));
850
+ link.href = url.pathname + url.search;
851
+ }
852
+ }
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
+ }
870
+ let socket = null;
871
+ let retries = 0;
872
+ let retryTimer;
639
873
  function connect() {
640
- const es = new EventSource(url(`/api/watch?page=${encodeURIComponent(page)}${isDir ? "&dir" : ""}`));
641
- es.onopen = () => {
874
+ clearTimeout(retryTimer);
875
+ if (socket && socket.readyState <= WebSocket.OPEN) return;
876
+ const at = new URL(url(`/api/live?page=${encodeURIComponent(page)}${isDir ? "&dir" : ""}`), location.href);
877
+ at.protocol = location.protocol === "https:" ? "wss:" : "ws:";
878
+ const ws = socket = new WebSocket(at);
879
+ ws.onopen = () => {
880
+ retries = 0;
642
881
  document.documentElement.dataset.wbLive = "";
643
882
  loadListeners();
644
883
  loadEvents();
884
+ compareStamps();
885
+ document.dispatchEvent(new Event("wb-elsewhere"));
645
886
  caughtUp();
646
887
  };
647
- es.onerror = () => {
888
+ ws.onmessage = (e) => {
889
+ let message;
890
+ try {
891
+ message = JSON.parse(String(e.data));
892
+ } catch {
893
+ return;
894
+ }
895
+ if (message.event) onLive[message.event]?.(message.data);
896
+ };
897
+ ws.onclose = () => {
898
+ if (socket !== ws) return;
899
+ socket = null;
648
900
  delete document.documentElement.dataset.wbLive;
901
+ retryTimer = setTimeout(connect, Math.min(250 * 2 ** retries++, 5e3));
649
902
  };
650
- es.addEventListener("change", () => {
651
- for (const fn of changeListeners) fn();
652
- });
653
- es.addEventListener("events", () => loadEvents());
654
- es.addEventListener("listeners", () => loadListeners());
655
- es.addEventListener("reload", () => {
656
- const go = async () => {
657
- try {
658
- if ((await fetch(url("/api/health"), { cache: "no-store" })).ok) return location.reload();
659
- } catch {}
660
- setTimeout(go, 500);
661
- };
662
- go();
663
- });
664
- es.addEventListener("scroll", (e) => {
665
- const { to } = JSON.parse(e.data);
666
- if (!scrollToTarget(root, to)) console.warn(`whiteboard scroll: nothing on the page matches ${JSON.stringify(to)}`);
667
- });
668
- es.addEventListener("style", () => {
669
- for (const link of document.querySelectorAll("link[rel=stylesheet]")) {
670
- const url = new URL(link.href);
671
- if (url.origin !== location.origin) continue;
672
- url.searchParams.set("t", String(Date.now()));
673
- link.href = url.pathname + url.search;
674
- }
675
- });
676
903
  }
904
+ document.addEventListener("visibilitychange", () => {
905
+ if (document.visibilityState === "visible" && !socket) connect();
906
+ });
907
+ addEventListener("online", () => {
908
+ if (!socket) connect();
909
+ });
677
910
  await Promise.all([loadEvents(), loadListeners()]);
678
911
  if (handoff.client) try {
679
912
  const mount = (await import(moduleUrl(handoff.client))).default;
@@ -718,7 +951,10 @@ await Promise.all((handoff.plugins ?? []).map(async (ext) => {
718
951
  try {
719
952
  const mount = (await import(moduleUrl(ext.client))).default;
720
953
  if (typeof mount !== "function") throw new Error("the client module must export a mount(root, page, api) function as default");
721
- 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
+ });
722
958
  } catch (err) {
723
959
  console.error(`plugin ${ext.name}:`, err);
724
960
  root.insertAdjacentHTML("afterbegin", String(html`<pre class="wb-error" role="alert">
@@ -15,7 +15,9 @@ green, `active new info` blue, `open todo maybe warning` amber,
15
15
  The release is :badge[blocked] on review.
16
16
  ```
17
17
 
18
- A grid card whose heading ends in a badge shows it at the card's right edge.
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-wb-title` attribute on it.
19
21
 
20
22
  ### Parser :badge[done]
21
23
 
@@ -28,3 +28,20 @@
28
28
  .wb-badge:is([data-badge='blocked'], [data-badge='no'], [data-badge='bad'], [data-badge='error']) {
29
29
  --c: var(--bad);
30
30
  }
31
+
32
+ /* a badge that ends a title sits at its right edge, centred on its first line: in any heading,
33
+ and in anything a block marks as a title (data-wb-title: a timeline's step). --wb-title-line is
34
+ the title's line height in px (registered, so 1lh resolves on the title, not on the badge) */
35
+ @property --wb-title-line {
36
+ syntax: '<length>';
37
+ inherits: true;
38
+ initial-value: 0px;
39
+ }
40
+ :is(h1, h2, h3, h4, h5, h6, [data-wb-title]):has(> .wb-badge:last-child) {
41
+ --wb-title-line: 1lh;
42
+ }
43
+ :is(h1, h2, h3, h4, h5, h6, [data-wb-title]) > .wb-badge:last-child {
44
+ float: right;
45
+ margin: calc(var(--wb-title-line) / 2 - 0.5em) 0 0 var(--space-lg);
46
+ vertical-align: baseline;
47
+ }