@bigmistqke/whiteboard 0.1.0 → 0.2.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 (73) hide show
  1. package/README.md +31 -12
  2. package/bin/whiteboard.ts +74 -17
  3. package/dist/bin/whiteboard.js +93 -22
  4. package/dist/client/runtime.js +164 -11
  5. package/dist/plugins/chat/README.md +2 -1
  6. package/dist/plugins/chat/client.js +2 -2
  7. package/dist/plugins/chat/index.js +1 -0
  8. package/dist/plugins/chat/style.css +7 -0
  9. package/dist/plugins/code/diff.js +1 -0
  10. package/dist/plugins/comments/client.js +6 -6
  11. package/dist/plugins/comments/index.js +4 -1
  12. package/dist/plugins/comments/style.css +8 -0
  13. package/dist/plugins/forge/README.md +12 -0
  14. package/dist/plugins/forge/index.js +83 -0
  15. package/dist/plugins/gallery/client.js +1 -1
  16. package/dist/plugins/iframe/README.md +18 -0
  17. package/dist/plugins/iframe/client.js +1 -0
  18. package/dist/plugins/iframe/index.js +40 -0
  19. package/dist/plugins/iframe/style.css +29 -0
  20. package/dist/plugins/index.js +4 -0
  21. package/dist/plugins/mermaid/index.js +1 -0
  22. package/dist/solid/index.js +2 -1
  23. package/dist/src/client/page/base.css +33 -12
  24. package/dist/src/client/page/main.js +246 -22
  25. package/dist/src/events.js +24 -3
  26. package/dist/src/icons.js +6 -0
  27. package/dist/src/loader.js +12 -6
  28. package/dist/src/pages/blocks.js +1 -0
  29. package/dist/src/pages/index.js +3 -2
  30. package/dist/src/pages/markdown.js +107 -4
  31. package/dist/src/pages/render.js +63 -9
  32. package/dist/src/server.js +37 -12
  33. package/dist/src/status.js +38 -10
  34. package/package.json +1 -1
  35. package/plugins/chat/README.md +2 -1
  36. package/plugins/chat/client.tsx +15 -3
  37. package/plugins/chat/index.ts +1 -1
  38. package/plugins/chat/style.css +7 -0
  39. package/plugins/code/diff.ts +7 -1
  40. package/plugins/comments/client.ts +50 -6
  41. package/plugins/comments/index.ts +4 -2
  42. package/plugins/comments/style.css +8 -0
  43. package/plugins/forge/README.md +12 -0
  44. package/plugins/forge/index.ts +71 -0
  45. package/plugins/iframe/README.md +18 -0
  46. package/plugins/iframe/client.ts +46 -0
  47. package/plugins/iframe/index.ts +54 -0
  48. package/plugins/iframe/style.css +29 -0
  49. package/plugins/index.ts +3 -1
  50. package/plugins/mermaid/index.ts +1 -0
  51. package/skills/whiteboard/SKILL.md +17 -7
  52. package/solid/index.tsx +3 -0
  53. package/src/client/forms.ts +5 -6
  54. package/src/client/markdown.ts +36 -0
  55. package/src/client/page/base.css +33 -12
  56. package/src/client/page/elsewhere.ts +70 -0
  57. package/src/client/page/live.ts +30 -0
  58. package/src/client/page/main.ts +25 -2
  59. package/src/client/page/sort.ts +38 -0
  60. package/src/client/page/waiting.ts +102 -29
  61. package/src/client/read.ts +73 -0
  62. package/src/client/runtime.ts +13 -0
  63. package/src/client/toast.ts +25 -0
  64. package/src/define.ts +79 -13
  65. package/src/events.ts +27 -3
  66. package/src/icons.ts +8 -0
  67. package/src/loader.ts +7 -4
  68. package/src/pages/blocks.ts +3 -0
  69. package/src/pages/index.ts +8 -2
  70. package/src/pages/markdown.ts +92 -4
  71. package/src/pages/render.ts +49 -12
  72. package/src/server.ts +35 -12
  73. package/src/status.ts +64 -20
@@ -676,19 +676,95 @@ function setThemePreference(pref) {
676
676
  } catch {}
677
677
  update();
678
678
  }
679
- // src/client/page/waiting.ts
680
- const ORDER = [
681
- "waiting",
682
- "unheard",
679
+ // src/status.ts
680
+ /** The states, in the order a reader should see them: what waits on them first. */
681
+ const STATES = [
682
+ "open",
683
683
  "pending",
684
684
  "decided"
685
685
  ];
686
+ /** How many things on a page wait for the reader: its open questions and unread messages. */
687
+ const awaiting = (p) => p.open.length + p.unread.length;
688
+ // src/icons.ts
689
+ /** An inbox: what awaits the reader (the header's menu, the overview). */
690
+ const INBOX_ICON = "<svg viewBox=\"0 0 16 16\" width=\"13\" height=\"13\" aria-hidden=\"true\"><path d=\"M2 9.5 3.8 3.2A1 1 0 0 1 4.8 2.5h6.4a1 1 0 0 1 1 .7L14 9.5V13a.5.5 0 0 1-.5.5h-11A.5.5 0 0 1 2 13Zm0 0h3.5l1 1.5h3l1-1.5H14\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linejoin=\"round\"/></svg>";
691
+ /** "Awaiting you: 2 things", and where: what the inbox says to a reader who hovers it. */
692
+ const awaitingLabel = (n, where = "") => `Awaiting you: ${n === 1 ? "1 question or message" : `${n} questions and messages`}${where}`;
693
+ // src/client/page/elsewhere.ts
694
+ /** A link to a page that scrolls it to its first waiting question. */
695
+ const WAITING_HASH = "#wb-waiting";
696
+ const box = document.createElement("div");
697
+ box.className = "wb-elsewhere";
698
+ box.hidden = true;
699
+ box.innerHTML = "<button type=\"button\" class=\"wb-elsewhere-toggle wb-awaiting\" aria-haspopup=\"true\" aria-expanded=\"false\"></button><ul class=\"wb-elsewhere-list\" hidden></ul>";
700
+ const toggle = box.querySelector("button");
701
+ toggle.innerHTML = `${INBOX_ICON}<span class="wb-elsewhere-count"></span>`;
702
+ const count = toggle.querySelector("span");
703
+ const list = box.querySelector("ul");
704
+ function open(yes) {
705
+ list.hidden = !yes;
706
+ toggle.setAttribute("aria-expanded", String(yes));
707
+ }
708
+ let current$1 = "";
709
+ async function load() {
710
+ let pages;
711
+ try {
712
+ pages = await (await fetch("/api/status", { cache: "no-store" })).json();
713
+ } catch {
714
+ return;
715
+ }
716
+ const waiting = pages.filter((p) => p.page !== current$1).map((p) => ({
717
+ p,
718
+ n: awaiting(p)
719
+ })).filter(({ n }) => n > 0);
720
+ const total = waiting.reduce((sum, { n }) => sum + n, 0);
721
+ box.hidden = total === 0;
722
+ if (!total) open(false);
723
+ count.textContent = String(total);
724
+ toggle.title = awaitingLabel(total, ` on ${waiting.length === 1 ? "another page" : `${waiting.length} other pages`}`);
725
+ toggle.setAttribute("aria-label", toggle.title);
726
+ list.replaceChildren(...waiting.map(({ p, n }) => {
727
+ const li = document.createElement("li");
728
+ const a = document.createElement("a");
729
+ a.href = `/${p.page.split("/").map(encodeURIComponent).join("/")}${WAITING_HASH}`;
730
+ a.textContent = `${p.title} (${n})`;
731
+ li.append(a);
732
+ return li;
733
+ }));
734
+ }
735
+ let timer = 0;
736
+ const reload = () => {
737
+ clearTimeout(timer);
738
+ timer = window.setTimeout(load, 100);
739
+ };
740
+ function trackElsewhere(root, handle, core) {
741
+ current$1 = handle.id;
742
+ const nav = root.querySelector(".wb-nav");
743
+ if (!nav) return;
744
+ nav.querySelector(".wb-theme")?.before(box);
745
+ toggle.addEventListener("click", () => open(!!list.hidden));
746
+ document.addEventListener("click", (e) => {
747
+ if (!box.contains(e.target)) open(false);
748
+ });
749
+ document.addEventListener("keydown", (e) => {
750
+ if (e.key === "Escape" && !list.hidden) {
751
+ open(false);
752
+ toggle.focus();
753
+ }
754
+ });
755
+ core.onEvents(reload);
756
+ core.onListeners(reload);
757
+ handle.onChange(reload);
758
+ load();
759
+ }
760
+ // src/client/page/waiting.ts
761
+ const ORDER = STATES;
686
762
  const LABEL = {
687
- waiting: (n) => `${n} waiting for you`,
688
- unheard: (n) => `${n} nobody listening`,
763
+ open: (n) => `${n} waiting for you`,
689
764
  pending: (n) => `${n} waiting for the agent`,
690
765
  decided: (n) => `${n} decided`
691
766
  };
767
+ const messagesLabel = (n) => `${n} unread message${n === 1 ? "" : "s"} from the agent`;
692
768
  let main$1;
693
769
  let api$1;
694
770
  let forms = [];
@@ -701,51 +777,97 @@ summary.className = "wb-summary";
701
777
  summary.hidden = true;
702
778
  const reopened = /* @__PURE__ */ new Map();
703
779
  const inState = (state) => forms.filter((f) => f.state === state && f.form.isConnected).map((f) => f.form);
704
- function show(list) {
780
+ /** Where an unread message is on the page: its own element, else the one holding it. */
781
+ function messageTarget(id) {
782
+ const own = document.querySelector(`[data-wb-message="${CSS.escape(id)}"]`);
783
+ if (own && own.getClientRects().length) return own;
784
+ return [...document.querySelectorAll("[data-wb-holds]")].find((el) => el.dataset.wbHolds.split(" ").includes(id)) ?? null;
785
+ }
786
+ /** What waits for the reader, top to bottom: open forms and unread messages. */
787
+ function targets(kind = "all") {
788
+ const list = [.../* @__PURE__ */ new Set([...kind === "all" ? inState("open") : [], ...api$1.unread().map((e) => messageTarget(e.id)).filter((el) => !!el)])];
789
+ const top = (el) => el.getBoundingClientRect().top;
790
+ return list.sort((a, b) => top(a) - top(b));
791
+ }
792
+ let messagesToast = null;
793
+ let toastTimer = 0;
794
+ function show(list = forms) {
705
795
  forms = list;
706
796
  for (const { form, name, state, last } of forms) {
707
797
  if (last && reopened.has(name) && reopened.get(name) !== last.id && state === "decided") reopened.delete(name);
708
798
  form.toggleAttribute("data-wb-folded", state === "decided" && !reopened.has(name));
709
799
  }
710
- const parts = ORDER.map((state) => [state, inState(state).length]).filter(([, count]) => count);
800
+ const unread = api$1.unread().length;
801
+ const parts = ORDER.map((state) => [state, inState(state).length]).filter(([, count]) => count).map(([state, count]) => [state, LABEL[state](count)]);
802
+ if (unread) parts.splice(inState("open").length ? 1 : 0, 0, ["messages", messagesLabel(unread)]);
711
803
  summary.hidden = !parts.length;
712
- summary.replaceChildren(...parts.flatMap(([state, count], i) => {
804
+ summary.replaceChildren(...parts.flatMap(([state, text], i) => {
713
805
  const link = document.createElement("button");
714
806
  link.type = "button";
715
807
  link.dataset.state = state;
716
- link.textContent = LABEL[state](count);
808
+ link.textContent = text;
717
809
  return i ? [document.createTextNode(" · "), link] : [link];
718
810
  }));
719
- const n = inState("waiting").length;
811
+ const n = inState("open").length + unread;
720
812
  button.hidden = n === 0;
721
813
  button.textContent = `→ waiting for you (${n})`;
722
814
  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
+ }
830
+ if (arriving && n) {
831
+ arriving = false;
832
+ history.replaceState(history.state, "", location.pathname + location.search);
833
+ requestAnimationFrame(() => {
834
+ const first = targets()[0];
835
+ if (first) jumpTo(first);
836
+ });
837
+ }
723
838
  }
839
+ let arriving = location.hash === WAITING_HASH;
840
+ setTimeout(() => {
841
+ arriving = false;
842
+ }, 5e3);
724
843
  let current = null;
725
844
  let scrolledTo = 0;
726
- function next(state) {
727
- const list = inState(state);
845
+ function next(list) {
728
846
  const i = current ? list.indexOf(current) : -1;
729
847
  if (i >= 0 && Math.abs(scrollY - scrolledTo) < 40) return list[(i + 1) % list.length];
730
848
  return list.find((f) => f.getBoundingClientRect().top > viewBottom() / 2) ?? list[0];
731
849
  }
732
- function jump(state) {
733
- const form = next(state);
734
- if (!form) return;
735
- current = form;
736
- const r = form.getBoundingClientRect();
850
+ function jump(what) {
851
+ const target = next(what === "all" ? targets() : what === "messages" ? targets("messages") : inState(what));
852
+ if (target) jumpTo(target);
853
+ }
854
+ function jumpTo(target) {
855
+ current = target;
856
+ const r = target.getBoundingClientRect();
737
857
  scrolledTo = Math.max(0, Math.min(scrollY + r.top + r.height / 2 - viewBottom() / 2, document.documentElement.scrollHeight - innerHeight));
738
858
  scrollTo({
739
859
  top: scrolledTo,
740
860
  behavior: "smooth"
741
861
  });
742
- if (state === "waiting") form.querySelector("input:not([type=hidden]), textarea, select, button")?.focus({ preventScroll: true });
862
+ if (target instanceof HTMLFormElement) {
863
+ if (target.hasAttribute("data-wb-open")) target.querySelector("input:not([type=hidden]), textarea, select, button")?.focus({ preventScroll: true });
864
+ } else target.dispatchEvent(new CustomEvent("wb-reveal", { bubbles: true }));
743
865
  }
744
866
  function trackWaiting(root, core) {
745
867
  main$1 = root;
746
868
  api$1 = core;
747
869
  api$1.corner().prepend(button);
748
- button.addEventListener("click", () => jump("waiting"));
870
+ button.addEventListener("click", () => jump("all"));
749
871
  main$1.before(summary);
750
872
  summary.addEventListener("click", (e) => {
751
873
  const state = e.target.closest("button[data-state]")?.dataset.state;
@@ -763,7 +885,85 @@ function trackWaiting(root, core) {
763
885
  form.querySelector("input:not([type=hidden]), textarea, select")?.focus({ preventScroll: true });
764
886
  });
765
887
  api$1.onForms(show);
888
+ api$1.onEvents(() => show());
766
889
  show(api$1.forms());
890
+ document.addEventListener("submit", (e) => {
891
+ const form = e.target;
892
+ const name = form.getAttribute("name");
893
+ if (!name || !main$1.contains(form) || !forms.some((f) => f.form === form)) return;
894
+ const takes = (fallback) => api$1.listeners().some((l) => !!l.fallback === fallback && (l.type === name || l.type === null));
895
+ if (takes(false)) return;
896
+ const fallback = takes(true);
897
+ const sent = new MutationObserver(() => {
898
+ if (form.dataset.wbState === "sending") return;
899
+ sent.disconnect();
900
+ 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" });
903
+ });
904
+ sent.observe(form, {
905
+ attributes: true,
906
+ attributeFilter: ["data-wb-state"]
907
+ });
908
+ });
909
+ }
910
+ // src/client/page/live.ts
911
+ function trackLive(root, handle, api) {
912
+ const dot = root.querySelector(".wb-live");
913
+ if (!dot) return;
914
+ const hasAnswers = handle.kind === "page" || handle.kind === "file";
915
+ const show = () => {
916
+ const live = document.documentElement.hasAttribute("data-wb-live");
917
+ const listeners = hasAnswers ? api.listeners() : [];
918
+ const own = listeners.some((l) => !l.fallback);
919
+ const anyPage = listeners.some((l) => l.fallback);
920
+ const agent = live && (own || anyPage);
921
+ dot.toggleAttribute("data-agent", agent);
922
+ dot.title = !live ? "Reconnecting… the page may be out of date" : !hasAnswers ? "Live" : own ? "Live · an agent is listening on this page" : anyPage ? "Live · an agent is listening on every page" : "Live · no agent is listening right now; answers wait in the log";
923
+ dot.setAttribute("aria-label", dot.title);
924
+ };
925
+ api.onListeners(show);
926
+ new MutationObserver(show).observe(document.documentElement, {
927
+ attributes: true,
928
+ attributeFilter: ["data-wb-live"]
929
+ });
930
+ show();
931
+ }
932
+ // src/client/page/sort.ts
933
+ const KEY = (name) => `wb-sort:${name}`;
934
+ function sortList(select) {
935
+ const list = select.closest("section")?.querySelector("ul");
936
+ if (!list) return;
937
+ const by = select.value;
938
+ const value = (li) => by === "title" ? li.dataset.title ?? "" : Number(by === "updated" ? li.dataset.updated : li.dataset.order);
939
+ const rows = [...list.children];
940
+ rows.sort((a, b) => {
941
+ const x = value(a), y = value(b);
942
+ if (by === "updated") return y - x;
943
+ return typeof x === "string" ? x.localeCompare(y) : x - y;
944
+ });
945
+ list.append(...rows);
946
+ }
947
+ function applySorts() {
948
+ for (const select of document.querySelectorAll("select[data-wb-sort]")) {
949
+ let kept = null;
950
+ try {
951
+ kept = localStorage.getItem(KEY(select.dataset.wbSort));
952
+ } catch {}
953
+ if (kept && [...select.options].some((o) => o.value === kept)) select.value = kept;
954
+ sortList(select);
955
+ }
956
+ }
957
+ function trackSorts() {
958
+ document.addEventListener("change", (e) => {
959
+ const select = e.target;
960
+ if (!select.matches?.("select[data-wb-sort]")) return;
961
+ try {
962
+ localStorage.setItem(KEY(select.dataset.wbSort), select.value);
963
+ } catch {}
964
+ sortList(select);
965
+ });
966
+ applySorts();
767
967
  }
768
968
  // src/client/page/orphans.ts
769
969
  /** A message in a chat: the chat block's event. */
@@ -838,13 +1038,31 @@ const NEXT = {
838
1038
  light: "dark",
839
1039
  dark: "auto"
840
1040
  };
1041
+ const svg = (d) => `<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">${d}</svg>`;
1042
+ const THEME_ICON = {
1043
+ auto: svg("<circle cx=\"8\" cy=\"8\" r=\"5.5\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"/><path d=\"M8 2.5a5.5 5.5 0 0 1 0 11Z\" fill=\"currentColor\"/>"),
1044
+ light: svg("<circle cx=\"8\" cy=\"8\" r=\"2.8\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"/><path d=\"M8 1.2v1.8M8 13v1.8M1.2 8H3M13 8h1.8M3.2 3.2l1.3 1.3M11.5 11.5l1.3 1.3M3.2 12.8l1.3-1.3M11.5 4.5l1.3-1.3\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linecap=\"round\"/>"),
1045
+ dark: svg("<path d=\"M13.5 9.6A5.8 5.8 0 0 1 6.4 2.5a5.8 5.8 0 1 0 7.1 7.1Z\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linejoin=\"round\"/>")
1046
+ };
1047
+ const THEME_LABEL = {
1048
+ auto: "Theme: follows the system",
1049
+ light: "Theme: light",
1050
+ dark: "Theme: dark"
1051
+ };
841
1052
  function themeToggle(root) {
842
1053
  const button = root.querySelector(".wb-theme");
843
1054
  if (!button) return;
844
- button.textContent = themePreference();
1055
+ const show = () => {
1056
+ const pref = themePreference();
1057
+ button.innerHTML = THEME_ICON[pref];
1058
+ button.dataset.pref = pref;
1059
+ button.title = `${THEME_LABEL[pref]} (click for ${NEXT[pref]})`;
1060
+ button.setAttribute("aria-label", button.title);
1061
+ };
1062
+ show();
845
1063
  button.addEventListener("click", () => {
846
1064
  setThemePreference(NEXT[themePreference()]);
847
- button.textContent = themePreference();
1065
+ show();
848
1066
  });
849
1067
  }
850
1068
  function ago(ts) {
@@ -997,6 +1215,12 @@ const mount = async (root, handle, coreApi) => {
997
1215
  blockSigs = [...main.children].map(signature);
998
1216
  if (!isDir) trackInitial(main, page, core);
999
1217
  if (!isDir) trackWaiting(main, core);
1218
+ trackElsewhere(root, handle, core);
1219
+ trackLive(root, handle, core);
1220
+ if (isDir) {
1221
+ trackSorts();
1222
+ core.onRendered(applySorts);
1223
+ }
1000
1224
  if (!isDir) trackOrphanThreads(main, core);
1001
1225
  await mountIslands();
1002
1226
  tickTimes();
@@ -133,7 +133,7 @@ const forAgent = (handedOut = /* @__PURE__ */ new Set()) => (type) => !type.incl
133
133
  * `follow`, or when `signal` aborts.
134
134
  */
135
135
  function handOut(file, filter, onEvent, options = {}) {
136
- const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent() } = options;
136
+ const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent(), skip, recheck } = options;
137
137
  return new Promise((resolve) => {
138
138
  let got = 0;
139
139
  let stop = () => {};
@@ -148,14 +148,35 @@ function handOut(file, filter, onEvent, options = {}) {
148
148
  pick(file, e);
149
149
  return ++got < count;
150
150
  };
151
+ const left = /* @__PURE__ */ new Map();
152
+ const offer = (e) => {
153
+ if (skip?.(e)) {
154
+ left.set(e.id, e);
155
+ return true;
156
+ }
157
+ return hand(e);
158
+ };
151
159
  if (count <= 0 || signal?.aborted) return finish();
152
160
  const { events, end } = read(file);
153
161
  const picked = pickedUp(events);
154
- for (const e of events) if (wanted(e) && !picked.has(e.id) && !hand(e)) return finish();
162
+ for (const e of events) if (wanted(e) && !picked.has(e.id) && !offer(e)) return finish();
155
163
  if (!following) return finish();
156
164
  signal?.addEventListener("abort", finish);
165
+ recheck?.(() => {
166
+ if (!left.size || got >= count) return;
167
+ const picked = pickedUp(read(file).events);
168
+ for (const [id, e] of left) {
169
+ if (picked.has(id)) {
170
+ left.delete(id);
171
+ continue;
172
+ }
173
+ if (skip?.(e)) continue;
174
+ left.delete(id);
175
+ if (!hand(e)) return finish();
176
+ }
177
+ });
157
178
  stop = follow(file, end, (e) => {
158
- if (got < count && wanted(e) && !hand(e)) finish();
179
+ if (got < count && wanted(e) && !offer(e)) finish();
159
180
  }, { interval });
160
181
  });
161
182
  }
@@ -0,0 +1,6 @@
1
+ // src/icons.ts
2
+ /** An inbox: what awaits the reader (the header's menu, the overview). */
3
+ const INBOX_ICON = "<svg viewBox=\"0 0 16 16\" width=\"13\" height=\"13\" aria-hidden=\"true\"><path d=\"M2 9.5 3.8 3.2A1 1 0 0 1 4.8 2.5h6.4a1 1 0 0 1 1 .7L14 9.5V13a.5.5 0 0 1-.5.5h-11A.5.5 0 0 1 2 13Zm0 0h3.5l1 1.5h3l1-1.5H14\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linejoin=\"round\"/></svg>";
4
+ /** "Awaiting you: 2 things", and where: what the inbox says to a reader who hovers it. */
5
+ const awaitingLabel = (n, where = "") => `Awaiting you: ${n === 1 ? "1 question or message" : `${n} questions and messages`}${where}`;
6
+ export { INBOX_ICON, awaitingLabel };
@@ -86,14 +86,19 @@ function createConfigLoader(proj, { pages: withPages = true } = {}) {
86
86
  plugin: p.name
87
87
  })));
88
88
  const styles = plugins.map((p) => p.style).filter((s) => !!s);
89
+ const links = plugins.flatMap((p) => p.links ? [p.links.bind(p)] : []);
90
+ const pages = withPages ? createPages({
91
+ blocks,
92
+ style: config?.style,
93
+ styles,
94
+ links
95
+ }) : null;
96
+ const declared = (flag) => new Set(plugins.flatMap((p) => Object.entries(p.events ?? {}).filter(([, spec]) => spec?.[flag]).map(([type]) => type)));
89
97
  return {
90
- pages: withPages ? createPages({
91
- blocks,
92
- style: config?.style,
93
- styles
94
- }) : null,
98
+ pages,
95
99
  plugins,
96
- handedOut: new Set(plugins.flatMap((p) => Object.entries(p.events ?? {}).filter(([, spec]) => spec?.handOut).map(([type]) => type))),
100
+ handedOut: declared("handOut"),
101
+ forReader: declared("forReader"),
97
102
  files: config?.files !== false
98
103
  };
99
104
  }
@@ -105,6 +110,7 @@ function createConfigLoader(proj, { pages: withPages = true } = {}) {
105
110
  pages: null,
106
111
  plugins: [],
107
112
  handedOut: /* @__PURE__ */ new Set(),
113
+ forReader: /* @__PURE__ */ new Set(),
108
114
  files: false,
109
115
  errors: [error]
110
116
  }));
@@ -22,6 +22,7 @@ function normalize({ name, block: b, plugin }) {
22
22
  return {
23
23
  name,
24
24
  code: b.fence === "any",
25
+ fences: b.fence === true || b.fence === "any",
25
26
  props: typeof b.props === "function" ? b.props.bind(b) : null,
26
27
  html: typeof b.html === "function" ? b.html.bind(b) : null,
27
28
  ...files,
@@ -1,12 +1,13 @@
1
1
  import { resolveBlocks } from "./blocks.js";
2
- import { createDocs, createRender } from "./render.js";
2
+ import { createDocs, createMessageRender, createRender } from "./render.js";
3
3
  import { formNames } from "./markdown.js";
4
4
  // src/pages/index.ts
5
5
  function createPages(options) {
6
6
  const resolved = resolveBlocks(options.blocks);
7
7
  const blocks = () => resolved;
8
8
  return {
9
- render: createRender(blocks, options.style, options.styles ?? []),
9
+ render: createRender(blocks, options.style, options.styles ?? [], options.links ?? []),
10
+ message: createMessageRender(blocks, options.links ?? []),
10
11
  docs: createDocs(blocks),
11
12
  questions: (page) => formNames(page.source)
12
13
  };
@@ -11,6 +11,44 @@ import rehypeStringify from "rehype-stringify";
11
11
  import { toString } from "mdast-util-to-string";
12
12
  // src/pages/markdown.ts
13
13
  const parser = unified().use(remarkParse).use(remarkGfm).use(remarkDirective).freeze();
14
+ const HIDDEN_COLON = "";
15
+ const FENCE = /^(\s*)(`{3,}|~{3,})/;
16
+ function hideColonsInFences(source) {
17
+ let open = null;
18
+ return source.split("\n").map((line) => {
19
+ const fence = FENCE.exec(line);
20
+ if (!open) {
21
+ if (fence) open = {
22
+ char: fence[2][0],
23
+ length: fence[2].length
24
+ };
25
+ return line;
26
+ }
27
+ if (fence && fence[2][0] === open.char && fence[2].length >= open.length && !line.slice(fence[0].length).trim()) {
28
+ open = null;
29
+ return line;
30
+ }
31
+ return line.replace(/^(\s*)(:+)/, (_, space, colons) => space + HIDDEN_COLON.repeat(colons.length));
32
+ }).join("\n");
33
+ }
34
+ function showColons(node) {
35
+ if (typeof node.value === "string" && node.value.includes(HIDDEN_COLON)) node.value = node.value.replaceAll(HIDDEN_COLON, ":");
36
+ node.children?.forEach(showColons);
37
+ }
38
+ /** A message's raw HTML, as text: it shows as written, and runs nothing. */
39
+ function asText(node) {
40
+ if (node.type === "html") {
41
+ node.type = "text";
42
+ return;
43
+ }
44
+ node.children?.forEach(asText);
45
+ }
46
+ /** Markdown → mdast: GFM and directives, with code fences safe inside containers. */
47
+ function parseMarkdown(source) {
48
+ const tree = parser.parse(hideColonsInFences(source));
49
+ showColons(tree);
50
+ return tree;
51
+ }
14
52
  const toHast = unified().use(remarkRehype, { allowDangerousHtml: true }).use(rehypeStringify, { allowDangerousHtml: true }).freeze();
15
53
  /** `cols=3 open title="a b"` → { cols: '3', open: '', title: 'a b' } (bare words get '' like directive attrs) */
16
54
  function parseAttrs(s) {
@@ -43,6 +81,68 @@ const SCHEME = /^[a-z][a-z0-9+.-]*:/i;
43
81
  * file's own folder and handed to `linkFor(absolutePath)`, which returns the URL that serves it
44
82
  * (or null to leave the link as written).
45
83
  */
84
+ const NO_TEXT_LINKS = /* @__PURE__ */ new Set([
85
+ "link",
86
+ "linkReference",
87
+ "inlineCode",
88
+ "code",
89
+ "html",
90
+ "textDirective",
91
+ "definition"
92
+ ]);
93
+ /** Turn the plugins' text links (`#12`) into links, in plain text only. */
94
+ function linkText(tree, links) {
95
+ if (!links.length) return;
96
+ const split = (text) => {
97
+ let parts = [{
98
+ type: "text",
99
+ value: text
100
+ }];
101
+ for (const link of links) {
102
+ const flags = link.pattern.flags.includes("g") ? link.pattern.flags : link.pattern.flags + "g";
103
+ parts = parts.flatMap((part) => {
104
+ if (part.type !== "text") return [part];
105
+ const out = [];
106
+ const value = part.value;
107
+ const re = new RegExp(link.pattern.source, flags);
108
+ let at = 0;
109
+ for (let m = re.exec(value); m; m = re.exec(value)) {
110
+ if (!m[0]) {
111
+ re.lastIndex++;
112
+ continue;
113
+ }
114
+ const href = link.href(m);
115
+ if (!href) continue;
116
+ if (m.index > at) out.push({
117
+ type: "text",
118
+ value: value.slice(at, m.index)
119
+ });
120
+ out.push({
121
+ type: "link",
122
+ url: href,
123
+ title: link.title?.(m) ?? null,
124
+ children: [{
125
+ type: "text",
126
+ value: m[0]
127
+ }]
128
+ });
129
+ at = m.index + m[0].length;
130
+ }
131
+ if (at < value.length) out.push({
132
+ type: "text",
133
+ value: value.slice(at)
134
+ });
135
+ return out;
136
+ });
137
+ }
138
+ return parts;
139
+ };
140
+ const walk = (node) => {
141
+ if (!node.children || NO_TEXT_LINKS.has(node.type)) return;
142
+ node.children = node.children.flatMap((child) => child.type === "text" ? split(child.value) : (walk(child), [child]));
143
+ };
144
+ walk(tree);
145
+ }
46
146
  function rewriteLinks(tree, file, linkFor) {
47
147
  if (!linkFor || !file) return;
48
148
  const walk = (node) => {
@@ -94,7 +194,7 @@ function literalDirective(node, label) {
94
194
  * code block doesn't count.
95
195
  */
96
196
  function formNames(source) {
97
- const tree = parser.parse(String(source ?? "").replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, ""));
197
+ const tree = parseMarkdown(String(source ?? "").replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, ""));
98
198
  const names = [];
99
199
  const walk = (node) => {
100
200
  if (node.type === "containerDirective" && node.name === "form") {
@@ -115,7 +215,7 @@ function formNames(source) {
115
215
  * blocks. Returns the page's HTML, its first heading, the islands to mount and the blocks'
116
216
  * stylesheets.
117
217
  */
118
- async function renderMarkdown(source, { page, file, resolve, code = null, linkFor }) {
218
+ async function renderMarkdown(source, { page, file, resolve, code = null, linkFor, textLinks = [], message = false }) {
119
219
  let nextId = 0;
120
220
  const islands = {};
121
221
  const keyCount = {};
@@ -205,8 +305,10 @@ async function renderMarkdown(source, { page, file, resolve, code = null, linkFo
205
305
  }
206
306
  }
207
307
  const parse = (src) => {
208
- const tree = parser.parse(String(src ?? ""));
308
+ const tree = parseMarkdown(String(src ?? ""));
309
+ if (message) asText(tree);
209
310
  rewriteLinks(tree, file, linkFor);
311
+ linkText(tree, textLinks);
210
312
  return tree;
211
313
  };
212
314
  const markdown = async (src) => toHtml(parse(src).children ?? []);
@@ -263,7 +365,8 @@ async function renderMarkdown(source, { page, file, resolve, code = null, linkFo
263
365
  async function fence(node) {
264
366
  const lang = node.lang || null;
265
367
  const plain = async () => html`<pre><code${lang && html` class="language-${lang}"`}>${node.value}</code></pre>`;
266
- const block = lang && resolve(lang) || code;
368
+ const named = lang ? resolve(lang) : null;
369
+ const block = (named?.fences ? named : null) || code;
267
370
  if (!block) return htmlNode(await plain());
268
371
  const name = code && block === code && lang !== code.name ? code.name : lang;
269
372
  const attrs = parseAttrs(node.meta);