diff --git a/src/ui/App.tsx b/src/ui/App.tsx
new file mode 100644
index 0000000..c2b9d94
--- /dev/null
+++ b/src/ui/App.tsx
@@ -0,0 +1,641 @@
+import { useEffect, useLayoutEffect, useReducer, useRef, useState } from "preact/hooks";
+import { ancestors, ancestorsInDoc, docOf, label, sections, staleness, type Conflict, type NodeId } from "../core/model";
+import { verifyHistory, type Commit } from "../core/repo";
+import { clip, plain, sentences } from "../core/text";
+import { hostOf } from "../core/ref";
+import { HELP, handleKey } from "./keys";
+import { DocBar, DocsPanel } from "./Menu";
+import { LinkCard, LinkPicker, NodeBacklinks, NodeRelated, TargetRow } from "./Links";
+import { NodeBody, Outline, PendingSections, TopMatter } from "./Node";
+import { Panes } from "./Panes";
+import { PANES_MIN_WIDTH, store, type Aux } from "./store";
+import { WikiPage } from "./Wiki";
+import { Usage } from "./Usage";
+
+function Page() {
+ if (store.colWiki) return ;
+ const kids = sections(store.snap, store.top);
+ const listing = store.snap.library && store.top === store.snap.root;
+ return (
+
+
+ {kids.length > 0 && }
+
+ {!listing && }
+ {!listing && }
+ {!listing && }
+
+ );
+}
+
+// ---- panels ----
+
+const ago = (t: number) => {
+ const s = Math.max(0, Date.now() / 1000 - t);
+ if (s < 60) return "just now";
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
+ return `${Math.floor(s / 86400)}d ago`;
+};
+
+function ConflictCard({ c, selected }: { c: Conflict; selected: boolean }) {
+ const kind = { "edit-edit": "both sides rewrote this", "edit-delete": "edited on one side, deleted on the other", contradiction: "contradicts another node" }[c.type];
+ const other = c.other && store.snap.nodes[c.other] ? label(store.snap, c.other) : null;
+ return (
+
+
+ {c.title || "(untitled)"}
+ {c.status}
+
+
+ {kind}
+ {other ? `: “${other}”` : ""}
+
+ {selected && (
+
+ {c.type !== "contradiction" &&
}
+
+ {c.type === "edit-delete" ?
:
}
+ {c.type === "edit-edit" &&
}
+ {c.status === "resolved" &&
}
+ {c.rationale &&
{c.rationale}
}
+
+ {c.status === "open" ? (
+ <>
+ store.settle(c.id, "a")}>take A
+ {c.type !== "contradiction" && store.settle(c.id, "b")}>{c.type === "edit-delete" ? "keep deleted" : "take B"} }
+ {store.generating && store.resolveAll()}>ask the model }
+ >
+ ) : (
+ store.reopen(c.id)}>reopen (x)
+ )}
+
+
+ )}
+
+ );
+}
+
+function Side({ name, text, strong }: { name: string; text: string; strong?: boolean }) {
+ return (
+
+ {name}
+ {text}
+
+ );
+}
+
+function HistoryPanel({ verdict }: { verdict: string }) {
+ const items = store.panel();
+ const ref = useRef(null);
+ useLayoutEffect(() => {
+ ref.current?.querySelector(".selected")?.scrollIntoView({ block: "nearest" });
+ });
+ const heads = new Set();
+ let lastType = "";
+ return (
+
+
+ History{store.historyFilter && store.currentDoc ? ` · ${clip(store.snap.nodes[store.currentDoc]?.title ?? "", 30)}` : " · the library"}
+ j k · Enter · r revert{store.currentDoc ? " this document" : ""} · n branch · m merge · f {store.historyFilter ? "everything" : "this document"} · v verify · Esc
+
+ {verdict && {verdict}
}
+ {items.map((it, i) => {
+ const selected = i === store.historyIndex;
+ const head = it.type !== lastType && !heads.has(it.type) ? ({ conflict: "Conflicts", branch: "Branches", commit: "Commits" } as const)[it.type] : null;
+ lastType = it.type;
+ heads.add(it.type);
+ const pick = () => {
+ store.historyIndex = i;
+ store.emit();
+ };
+ return (
+
+ {head &&
{head} }
+ {it.type === "conflict" &&
}
+ {it.type === "branch" && (
+
+
+ {it.branch === store.repo.current ? "● " : "○ "}
+ {it.branch}
+
+ {it.branch === store.repo.current ? current : Enter switch · m merge into {store.repo.current} }
+
+ )}
+ {it.type === "commit" &&
}
+
+ );
+ })}
+
+ );
+}
+
+function CommitRow({ c, selected }: { c: Commit; selected: boolean }) {
+ const viewing = store.preview?.commit.id === c.id;
+ const snap = store.doc.snap();
+ const docs = store.touchedDocs(c).map((d) => snap.nodes[d]?.title ?? "");
+ return (
+
+
+ {c.hash ? c.hash.slice(0, 7) : "·······"}
+ {c.message}
+
+
+ {c.by}
+ {c.actor === "llm" ? " (model)" : ""} · {ago(c.time)}
+ {c.parents.length > 1 ? " · merge" : ""}
+ {c.tag ? ` · ${c.tag}` : ""}
+ {viewing ? " · viewing" : ""}
+
+ {docs.length > 0 && (
+
+ {docs.length > 3 ? `${docs.slice(0, 3).map((t) => clip(t, 24)).join(" · ")} · and ${docs.length - 3} more` : docs.map((t) => clip(t, 30)).join(" · ")}
+
+ )}
+
+ );
+}
+
+function Help() {
+ return (
+ store.setMode("normal")}>
+
e.stopPropagation()}>
+
Keys
+
+ Focus is a node and a grain. Start on a section, press i to move by sentence, i again by word, and e on
+ anything to go deeper. Text with a dotted underline already has an expansion; anything else is written on request.
+
+
+ {HELP.map(([head, rows]) => (
+
+ {head}
+
+ {rows.map(([keys, what]) => (
+
+
+ {!keys ? null : keys.length > 1 && keys.startsWith("/") ? {keys} : keys.split(" ").map((k) => {k} )}
+
+ {what}
+
+ ))}
+
+
+ ))}
+
+
+
+ );
+}
+
+function Jump() {
+ const [q, setQ] = useState("");
+ const [i, setI] = useState(0);
+ const hits = store.search(q);
+ const snap = store.snap;
+ const close = () => store.setMode("normal");
+ return (
+
+
e.stopPropagation()}>
+
el?.focus()}
+ placeholder="Jump to a section, in any document…"
+ value={q}
+ onInput={(e) => (setQ((e.target as HTMLInputElement).value), setI(0))}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === "Escape") close();
+ else if (e.key === "ArrowDown" || (e.ctrlKey && e.key === "n")) (e.preventDefault(), setI(Math.min(hits.length - 1, i + 1)));
+ else if (e.key === "ArrowUp" || (e.ctrlKey && e.key === "p")) (e.preventDefault(), setI(Math.max(0, i - 1)));
+ else if (e.key === "Enter" && hits[i]) store.jumpTo(hits[i]);
+ }}
+ />
+
+ {hits.map((id, k) => {
+ const d = docOf(snap, id);
+ const within = ancestorsInDoc(snap, id).reverse().slice(1);
+ return (
+ store.jumpTo(id)}>
+ {label(snap, id)}
+
+ {d && d !== id ? {snap.nodes[d].title} : document }
+ {within.length ? ` › ${within.map((a) => snap.nodes[a].title).join(" › ")}` : ""}
+
+
+ );
+ })}
+ {!hits.length && Nothing matches. }
+
+
+
+ );
+}
+
+function CommandBar({ prefill }: { prefill: string }) {
+ const f = store.focus;
+ const snap = store.snap;
+ const n = snap.nodes[f.node];
+ const about = f.grain !== "node" && f.range ? `ask about “${clip(plain(n.body.slice(f.range[0], f.range[1])), 48)}”` : `tell the editor · ${clip(label(snap, f.node), 40)}`;
+ return (
+
+ {about}
+ {
+ if (el && document.activeElement !== el) {
+ el.focus();
+ el.setSelectionRange(el.value.length, el.value.length);
+ }
+ }}
+ defaultValue={prefill}
+ placeholder={f.grain !== "node" ? "why? · example · how does this fail? …" : "add a section on… · tighten this · /branch name · /merge name"}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === "Escape") {
+ store.branchFrom = null;
+ store.setMode("normal");
+ } else if (e.key === "Enter") {
+ e.preventDefault();
+ store.command((e.target as HTMLInputElement).value);
+ }
+ }}
+ onBlur={() => store.mode === "command" && store.setMode("normal")}
+ />
+
+ );
+}
+
+/** What a popup shows for a note: its text; for a link, its target's card; for a note that links, both. */
+function PopupBody({ note }: { note: NodeId }) {
+ const n = store.snap.nodes[note];
+ return (
+ <>
+ {n.body.trim() && }
+ {n.ref && }
+ >
+ );
+}
+
+const place = (x: number, top: number, bottom: number): Record => ({
+ left: `${Math.max(12, Math.min(window.innerWidth - 452, x - 40))}px`,
+ ...(top < 260 ? { top: `${bottom + 8}px` } : { bottom: `${window.innerHeight - top + 8}px` }),
+});
+
+/** The hover preview: shown after a pause on a marked span, gone when the pointer leaves it or a key is pressed. */
+function Popup() {
+ const p = store.popup;
+ const snap = store.snap;
+ if (!p || !snap.nodes[p.note] || store.open.has(p.note)) return null;
+ return (
+
+ );
+}
+
+/**
+ * The keyboard's preview: while the selection is exactly a link's words, its card shows beside
+ * them. It is drawn from the focus, so it moves and goes with the focus in the same frame and can
+ * never outlive it.
+ */
+function FocusPopup() {
+ const f = store.focus;
+ const note = f.grain !== "node" && store.mode === "normal" && !store.popup && !store.aux ? store.noteAt(f.range) : undefined;
+ const n = note ? store.snap.nodes[note] : undefined;
+ const ref = useRef(null);
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const sel = [...document.querySelectorAll(".sel")].find((x) => x.offsetParent);
+ if (!sel) return void (el.style.visibility = "hidden");
+ const r = sel.getBoundingClientRect();
+ Object.assign(el.style, { left: "", top: "", bottom: "", ...place(r.left + 40, r.top, r.bottom), visibility: "visible" });
+ });
+ if (!note || !n?.ref || store.open.has(note)) return null;
+ return (
+
+ );
+}
+
+/**
+ * A research run of the editor, above the status line: each search, page read and edit as it
+ * happens, then the summary and the sources it linked. Esc stops the run, or puts the panel away.
+ */
+function AgentPanel() {
+ const run = store.agentRun;
+ if (!run?.research) return null;
+ const all = run.steps;
+ const steps = all.slice(-8);
+ return (
+
+
+ editor
+ {run.running ? "researching on the web · Esc stops" : "done · Esc closes"}
+
+
+ {all.length > steps.length && {all.length - steps.length} earlier steps }
+ {steps.map((s, i) => (
+ {s}
+ ))}
+
+ {!run.running && run.summary &&
{run.summary}
}
+ {!run.running && run.sources && (
+
+ {run.sources.length ? "Sources: " : "No sources were linked."}
+ {run.sources.map((s, i) => (
+
+ {i ? " · " : ""}
+
+ {s.title || hostOf(s.url)}
+ {" "}
+ {hostOf(s.url)}
+
+ ))}
+
+ )}
+
+ );
+}
+
+function StatusLine() {
+ const f = store.focus;
+ const snap = store.snap;
+ const n = snap.nodes[f.node];
+ const st = staleness(snap, f.node);
+ const path = [...ancestors(snap, f.node).reverse(), f.node].map((id) => clip(label(snap, id), 28)).join(" › ");
+ const selecting = f.grain !== "node";
+ const hint = store.aux
+ ? store.aux.kind === "wiki"
+ ? `Wikipedia · j k rows · l open · h back · Tab links${store.aux.link !== undefined ? " · Enter opens this link" : ""} · W on wikipedia.org${store.panes ? " · q close" : ""}`
+ : store.aux.kind === "target" ? "Enter opens what this is about"
+ : "Enter goes to the linking note"
+ : store.preview
+ ? "read-only · r revert to this · n branch from this · Esc back to now"
+ : selecting && store.focusedSuggestion()
+ ? `suggested link → ${clip(store.focusedSuggestion()!.title, 40)} · y link · n decline · Tab next · S review all`
+ : selecting
+ ? store.noteAt(f.range)
+ ? store.snap.nodes[store.noteAt(f.range)!].ref
+ ? `Enter open the link · w retarget · D remove${store.snap.nodes[store.noteAt(f.range)!].ref!.kind === "wiki" ? " · W on Wikipedia" : ""}`
+ : "Enter open/enter · e toggle · D delete note · w link it"
+ : `e expand${store.generating ? "" : " (no model)"} · d define · y why · x example · c challenge · : ask · w link`
+ : st.up || st.down
+ ? `stale · ${n.pinned ? "b accept · p unpin" : "R reconcile · b accept"}`
+ : "";
+ return (
+
+ {store.preview ? "history" : store.mode === "review" ? "review" : store.aux ? (store.aux.kind === "wiki" ? "article" : store.aux.kind === "back" ? "linked" : "target") : f.grain}
+ {path}
+ {store.status || hint}
+
+ {store.links.job?.state === "running" && (
+
+ links {store.links.job.done}/{store.links.job.total} · :/linkcancel
+
+ )}
+ {store.busy > 0 && }
+
+ {store.repo.current}
+ {store.llm.kind === "off" ? "no model" : store.llm.model}
+
+ ? keys
+
+
+ );
+}
+
+// ---- the app ----
+
+/** Map a DOM position inside a body to (node, offset). */
+function locate(node: Node | null, offset: number): { id: NodeId; at: number } | null {
+ const el = node instanceof Element ? node : node?.parentElement;
+ const piece = el?.closest("[data-o]");
+ const body = el?.closest("[data-body]");
+ if (!piece || !body) return null;
+ return { id: body.dataset.body as NodeId, at: Number(piece.dataset.o) + (node instanceof Text ? offset : 0) };
+}
+
+let hover: ReturnType | undefined;
+
+export function App() {
+ const [, tick] = useReducer((x: number) => x + 1, 0);
+ const [prefill, setPrefill] = useState("");
+ const [verdict, setVerdict] = useState("");
+ useEffect(() => store.subscribe(() => tick(0)), []);
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ clearTimeout(hover);
+ if (store.popup) {
+ store.popup = null;
+ store.emit(store.top);
+ }
+ handleKey(e, {
+ openCommand(text = "") {
+ setPrefill(text);
+ store.setMode("command");
+ },
+ verify() {
+ const t = performance.now();
+ const v = verifyHistory(store.doc);
+ setVerdict(
+ v.mismatches.length
+ ? `${v.mismatches.length} of ${v.checked} commits do NOT reproduce their recorded hash.`
+ : `Verified: all ${v.checked} hashed commits reproduce byte-for-byte${v.unhashed ? ` (${v.unhashed} undo/redo steps carry no hash)` : ""}. ${Math.round(performance.now() - t)} ms.`,
+ );
+ },
+ });
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, []);
+
+ // `auto` picks the layout from the window's width, so follow the width.
+ useEffect(() => {
+ const onResize = () => {
+ const wide = window.innerWidth >= PANES_MIN_WIDTH;
+ if (wide === store.wide) return;
+ store.wide = wide;
+ if (store.settings.view === "auto") store.emit();
+ };
+ window.addEventListener("resize", onResize);
+ return () => window.removeEventListener("resize", onResize);
+ }, []);
+
+ // Keep the focused thing in view, and time keypress → paint.
+ useLayoutEffect(() => {
+ if (!store.ready) return;
+ const f = store.focus;
+ // The panes keep their own focus in view (Panes.tsx).
+ const el =
+ !store.panes &&
+ ((f.grain !== "node" && document.querySelector(".sel")) ||
+ document.querySelector(`[data-row="${CSS.escape(f.node)}"]`) ||
+ document.querySelector(`[data-node="${CSS.escape(f.node)}"]`));
+ if (el && store.mode !== "edit") el.scrollIntoView({ block: "nearest" });
+ store.clean();
+ const t = store.t0;
+ if (t) {
+ store.t0 = null;
+ requestAnimationFrame(() => {
+ const ch = new MessageChannel();
+ ch.port1.onmessage = () => store.samples.push({ what: t.what, ms: performance.now() - t.at });
+ ch.port2.postMessage(0);
+ });
+ }
+ });
+
+ if (store.fatal) return {store.fatal}
;
+ if (!store.ready) return Loading…
;
+
+ const panes = store.panes;
+ const onClick = (e: MouseEvent) => {
+ if (store.mode === "edit") return;
+ const target = e.target as HTMLElement;
+ const paneEl = target.closest("[data-pane-index]");
+ const paneIndex = paneEl ? Number(paneEl.dataset.paneIndex) : store.paneAt;
+ // A covered pane's spine brings that pane back by focusing it.
+ const spine = target.closest("[data-spine]");
+ if (spine) {
+ const i = Number(spine.dataset.spine);
+ const p = store.trail[i];
+ store.paneAt = i;
+ if (p?.kind === "node") return store.setFocus({ node: p.id, grain: "node" });
+ return store.setFocus(store.focus, { kind: "wiki", host: `p${i}`, row: { t: "head" } });
+ }
+ // Article text: a link to another article opens it next; a link out leaves in a new tab (the HTML says so); nothing else navigates.
+ const host = target.closest("[data-host]")?.dataset.host;
+ const a = target.closest("a");
+ if (a && host) {
+ if (a.dataset.wiki) {
+ e.preventDefault();
+ store.paneAt = paneIndex;
+ const h = store.wikiHost(host);
+ return store.follow({ kind: "wiki", title: a.dataset.wiki, lang: h?.lang ?? store.wiki.lang });
+ }
+ if (!/^https?:/.test(a.getAttribute("href") ?? "")) e.preventDefault();
+ return;
+ }
+ if (a && target.closest(".wattr")) return;
+ const wrow = target.closest("[data-wrow], [data-sense]");
+ if (wrow && host) {
+ store.paneAt = paneIndex;
+ const id = Number(wrow.dataset.wrow);
+ const ss = wrow.dataset.sense;
+ if (ss) return store.follow({ kind: "wiki", title: ss, lang: store.wikiHost(host)?.lang ?? store.wiki.lang });
+ store.setFocus(store.focus, { kind: "wiki", host, row: { t: "sec", id } } as Aux);
+ return store.auxActivate();
+ }
+ const linking = target.closest("[data-linking]");
+ if (linking) {
+ store.paneAt = paneIndex;
+ return store.openLinking(linking.dataset.linking as NodeId);
+ }
+ const targetRow = target.closest("[data-target]");
+ if (targetRow) {
+ store.paneAt = paneIndex;
+ const r = store.snap.nodes[targetRow.dataset.target as NodeId]?.ref;
+ return r && store.follow(r);
+ }
+ if (host && target.closest(".wiki-head")) {
+ store.paneAt = paneIndex;
+ return store.setFocus(store.focus, { kind: "wiki", host, row: { t: "head" } });
+ }
+ const selection = window.getSelection();
+ // A drag selection inside one body becomes the focus range.
+ if (selection && !selection.isCollapsed) {
+ const a = locate(selection.anchorNode, selection.anchorOffset);
+ const b = locate(selection.focusNode, selection.focusOffset);
+ if (a && b && a.id === b.id && a.at !== b.at) {
+ store.go(a.id, "word", [Math.min(a.at, b.at), Math.max(a.at, b.at)]);
+ selection.removeAllRanges();
+ return;
+ }
+ }
+ const anchor = target.closest("[data-note]");
+ if (anchor?.dataset.note) {
+ const id = anchor.dataset.note as NodeId;
+ const n = store.snap.nodes[id];
+ const a = n.anchors[0];
+ store.popup = null;
+ if (n.ref && (store.panes || store.open.has(id)) && !n.body.trim()) {
+ // A link: in panes it opens next to its pane; in the column, once its preview is open.
+ store.paneAt = paneIndex;
+ store.go(n.parent!, "word", [a.start, a.end]);
+ return store.follow(n.ref);
+ }
+ if (store.open.has(id)) store.open.delete(id);
+ else store.open.add(id);
+ store.go(n.parent!, "word", [a.start, a.end]);
+ if (!store.open.has(id)) store.saveView();
+ return;
+ }
+ const row = target.closest("[data-row]");
+ if (row) {
+ const id = row.dataset.row as NodeId;
+ if (panes && id !== store.top) {
+ // In panes a click shows the row's pane: focus it and open it next. On the focused row whose pane is showing, it closes that pane.
+ const next = store.trail[paneIndex + 1];
+ if (store.focus.node === id && store.focus.grain === "node" && next?.kind === "node" && next.id === id) {
+ store.trail = store.trail.slice(0, paneIndex + 1);
+ store.saveView();
+ return store.emit();
+ }
+ store.paneAt = paneIndex;
+ store.go(id);
+ store.open.add(id);
+ const holder = store.trail[paneIndex];
+ if (store.snap.nodes[id]?.kind === "section" && holder?.kind === "node" && store.snap.nodes[id].parent === holder.id) store.openPane(paneIndex, { kind: "node", id });
+ return;
+ }
+ store.go(id);
+ if (id !== store.top) store.toggle(id);
+ return;
+ }
+ const at = selection && locate(selection.anchorNode, selection.anchorOffset);
+ if (at) {
+ const all = sentences(store.snap.nodes[at.id].body);
+ const hit = all.find((r) => at.at >= r[0] && at.at <= r[1]);
+ if (hit) return store.go(at.id, "sentence", hit);
+ }
+ const node = target.closest("[data-node]");
+ if (node) store.go(node.dataset.node as NodeId);
+ };
+
+ const onOver = (e: MouseEvent) => {
+ const anchor = (e.target as HTMLElement).closest("[data-note]");
+ clearTimeout(hover);
+ if (!anchor?.dataset.note || store.open.has(anchor.dataset.note as NodeId)) {
+ if (store.popup) hover = setTimeout(() => ((store.popup = null), store.emit(store.top)), 150);
+ return;
+ }
+ const r = anchor.getBoundingClientRect();
+ const note = anchor.dataset.note as NodeId;
+ hover = setTimeout(() => ((store.popup = { note, x: e.clientX, top: r.top, bottom: r.bottom }), store.emit(store.top)), 450);
+ };
+
+ return (
+
+
+
+ {store.preview && (
+
+ Viewing “{clip(store.preview.commit.message, 70)}” by {store.preview.commit.by}, {ago(store.preview.commit.time)}. Read-only.
+
+ )}
+ {panes ? : }
+
+ {store.mode === "history" &&
}
+ {store.mode === "docs" &&
}
+ {store.mode === "help" &&
}
+ {store.mode === "jump" &&
}
+ {store.mode === "command" &&
}
+ {store.mode === "link" && store.picker &&
}
+
+
+
+
+
+ );
+}
diff --git a/src/ui/Links.tsx b/src/ui/Links.tsx
new file mode 100644
index 0000000..653d53e
--- /dev/null
+++ b/src/ui/Links.tsx
@@ -0,0 +1,349 @@
+/**
+ * Links as the reader sees them: the small mark after linked words (after gwern.net's typed link
+ * icons: W for Wikipedia, § for another note in this library, ↗ for the web), the card a popup or
+ * an inset shows, a node's own target, the "Linked from" list, and the link picker.
+ */
+import { Fragment } from "preact";
+import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
+import { ownerSection, resolveNode } from "../core/links";
+import { docOf, isLink, label, type NodeId } from "../core/model";
+import { describeTarget, hostOf, parseTarget, validateRef, wikiTitle, type Ref } from "../core/ref";
+import { clip, plain } from "../core/text";
+import { sameAux, store, type Aux } from "./store";
+import type { Sugg } from "./linker";
+import { suggest, summary, wikiConfig, type Attribution as Attr, type Suggestion } from "./wiki";
+
+const MARK: Record[ = { wiki: "W", node: "§", url: "↗" };
+
+/** The document a node target is in, for its mark's tooltip. */
+function where(r: Ref): string {
+ if (r.kind === "wiki") return `Wikipedia: ${r.title}`;
+ if (r.kind === "url") return hostOf(r.url);
+ const s = store.snap;
+ const id = resolveNode(store.snap, r);
+ if (!id) return "a note that is gone";
+ const d = docOf(s, id);
+ return `${label(s, id)}${d && d !== id ? ` · in ${s.nodes[d].title}` : ""}`;
+}
+
+/** The mark set after linked words. Not text of the body: it carries no offset and cannot be selected. */
+export function LinkMark({ r, id }: { r: Ref; id?: NodeId }) {
+ const broken = r.kind === "node" && !resolveNode(store.snap, r);
+ return (
+ ]
+ {MARK[r.kind]}
+
+ );
+}
+
+/** The licence line every piece of article text carries: who wrote it, under what terms, and what was changed. */
+export function Attribution({ a }: { a: Attr }) {
+ return (
+
+ {a.text}{" "}
+ article
+ {a.revisionUrl && (
+ <>
+ {" · "}
+ this revision
+ >
+ )}
+ {" · "}
+ {a.license.name}
+
+ );
+}
+
+/** What a target is, briefly: an article's summary, a node's title, document and first lines, a page's host. */
+export function LinkCard({ r, compact }: { r: Ref; compact?: boolean }) {
+ if (r.kind === "url") {
+ return (
+
+
+ ↗ {hostOf(r.url)}
+
+ {r.title &&
{r.title}
}
+
{clip(r.url, 90)}
+
+ );
+ }
+ if (r.kind === "node") {
+ const s = store.snap;
+ const id = resolveNode(store.snap, r);
+ if (!id) {
+ return (
+
+
§ broken link
+
The note this pointed to is gone{r.path?.length ? `: it was “${r.path.join(" › ")}”${r.doc ? ` in ${r.doc}` : ""}` : ""}.
+
+ );
+ }
+ const d = docOf(s, id);
+ const n = s.nodes[id];
+ const sec = ownerSection(s, id);
+ return (
+
+
+ § {d ? s.nodes[d].title : "the library"}
+ {sec !== d && n.kind === "note" ? ` › ${label(s, sec)}` : ""}
+
+
{label(s, id)}
+ {n.body.trim() &&
{clip(plain(n.body), compact ? 160 : 320)}
}
+
+ );
+ }
+ const sum = summary(r.title, r.lang);
+ return (
+
+
+ W Wikipedia
+
+
{sum.state === "ready" ? sum.value.title : r.title}
+ {sum.state === "loading" &&
Loading the summary…
}
+ {sum.state === "failed" &&
{sum.message}
}
+ {sum.state === "ready" && (
+ <>
+ {sum.value.description &&
{sum.value.description}
}
+ {sum.value.disambiguation &&
A disambiguation page: it lists the senses of the word.
}
+
{compact ? clip(sum.value.extract, 240) : sum.value.extract}
+
+ >
+ )}
+
+ );
+}
+
+/** A link opened in the column: its card set under the paragraph, with what Enter does next. */
+export function LinkPreview({ id }: { id: NodeId }) {
+ const n = store.snap.nodes[id];
+ if (!n?.ref) return null;
+ const next = n.ref.kind === "wiki" ? "Enter opens the article · W opens it on Wikipedia" : n.ref.kind === "node" ? "Enter goes there · Back returns" : "Enter opens the page in a new tab";
+ return (
+
+
+ {next}
+
+ );
+}
+
+/** A node's own target, as a row at the foot of its text (the column; in panes a Wikipedia target is the article itself). */
+export function TargetRow({ id }: { id: NodeId }) {
+ const r = store.snap.nodes[id]?.ref;
+ if (!r) return null;
+ const focused = sameAux(store.aux, { kind: "target", of: id });
+ return (
+
+ about
+
+
+ );
+}
+
+/**
+ * "Linked from": the nodes that link here, each as its section's title and its document. Collapsed
+ * to nothing when there are none. The same list, for an article, is "Mentioned in".
+ */
+export function Backlinks({ ids, title, focusedAt }: { ids: NodeId[]; title: string; focusedAt: (i: number) => boolean }) {
+ if (!ids.length) return null;
+ const s = store.snap;
+ return (
+
+ {title}
+
+ {ids.map((id, i) => {
+ const sec = ownerSection(s, id);
+ const d = docOf(s, id);
+ const n = s.nodes[id];
+ return (
+
+ {label(s, sec)}
+ {d && d !== sec ? s.nodes[d].title : "document"}
+ {n.kind === "note" && “{clip(n.anchors[0]?.text ?? "", 60)}” }
+
+ );
+ })}
+
+
+ );
+}
+
+/** A suggested link, while the focus is on its words: the proposed target with its summary, and what the keys do. */
+export function SuggestionCard({ sg }: { sg: Sugg }) {
+ return (
+
+ suggested link{sg.tier === "auto" ? " (sure)" : ""} · y links · n declines{store.review ? " · s skips" : " · S reviews them all"}
+
+ {sg.why}
+
+ );
+}
+
+/**
+ * "Related": sections of other documents close in meaning to this one, derived and never stored.
+ * Numbered: with words of this node selected, the number links them to that section; on the node,
+ * it goes there.
+ */
+export function NodeRelated({ id }: { id: NodeId }) {
+ const rows = store.relatedShown(id) ? store.relatedOf(id) : [];
+ if (!rows.length) return null;
+ return (
+
+ );
+}
+
+export function NodeBacklinks({ id }: { id: NodeId }) {
+ const ids = store.linkedFrom(id);
+ const a = store.aux;
+ return sameAux(a, { kind: "back", of: id, index: i } as Aux)} />;
+}
+
+// ---- choosing a target: the picker (w) and the [[ completer in the body editor ----
+
+export interface Choice {
+ group: "Library" | "Wikipedia" | "Address";
+ label: string;
+ sub: string;
+ ref: Ref;
+}
+
+/** A section of the library as a choice, with the document it is in. */
+export function sectionChoice(id: NodeId): Choice {
+ const s = store.snap;
+ const d = docOf(s, id);
+ return { group: "Library", label: s.nodes[id].title || "(untitled)", sub: d && d !== id ? s.nodes[d].title : "document", ref: { kind: "node", id } };
+}
+
+/** A Wikipedia title suggestion as a choice. */
+export const articleChoice = (w: Suggestion): Choice => ({ group: "Wikipedia", label: w.title, sub: w.description ?? "", ref: { kind: "wiki", title: wikiTitle(w.title), lang: wikiConfig().lang } });
+
+/**
+ * Wikipedia's title suggestions for some text, after a pause in typing. A superseded request is
+ * abandoned, and the server then never sends it. Empty text asks for nothing.
+ */
+export function useWikiSuggest(text: string): { q: string; list: Suggestion[]; problem?: string } | null {
+ const [found, setFound] = useState<{ q: string; list: Suggestion[]; problem?: string } | null>(null);
+ useEffect(() => {
+ if (!text || wikiConfig().mode === "off") return setFound(null);
+ const ac = new AbortController();
+ const timer = setTimeout(() => {
+ suggest(text, ac.signal)
+ .then((r) => !ac.signal.aborted && setFound(Array.isArray(r) ? { q: text, list: r } : { q: text, list: [], problem: r.message }))
+ .catch(() => {});
+ }, 250);
+ return () => (clearTimeout(timer), ac.abort());
+ }, [text]);
+ return found;
+}
+
+/** The rows of a list of choices, under a heading for each group. A row is taken on click, without taking the focus from the input. */
+export function ChoiceRows({ choices, sel, pick }: { choices: Choice[]; sel: number; pick: (c: Choice) => void }) {
+ let group = "";
+ return (
+ <>
+ {choices.map((c, k) => {
+ const head = c.group !== group ? (group = c.group) : null;
+ return (
+
+ {head && {head} }
+ e.preventDefault()} onClick={() => pick(c)}>
+ {MARK[c.ref.kind]}
+ {c.label}
+ {c.sub}
+
+
+ );
+ })}
+ >
+ );
+}
+
+/** Sections and notes whose words match, across the library. */
+function libraryChoices(q: string, spot: NodeId): Choice[] {
+ const s = store.snap;
+ const terms = q.toLowerCase().split(/\s+/).filter(Boolean);
+ if (!terms.length) return [];
+ const out = store.search(q).filter((id) => id !== spot).slice(0, 6).map(sectionChoice);
+ for (const n of Object.values(s.nodes)) {
+ if (out.length >= 9) break;
+ if (n.kind !== "note" || isLink(n) || !n.anchors.length) continue;
+ const text = (n.anchors[0].text || n.anchors[0].quote).toLowerCase();
+ if (!terms.every((t) => text.includes(t))) continue;
+ const d = docOf(s, n.id);
+ out.push({ group: "Library", label: `“${clip(n.anchors[0].text, 50)}”`, sub: `note in ${d ? s.nodes[d].title : "the library"} › ${label(s, ownerSection(s, n.id))}`, ref: { kind: "node", id: n.id } });
+ }
+ return out;
+}
+
+/** w: link the selected words (or the node) to a note in the library, a Wikipedia article or an address. */
+export function LinkPicker() {
+ const spot = store.picker!;
+ const [q, setQ] = useState(spot.text);
+ const [i, setI] = useState(0);
+ const input = useRef(null);
+ useLayoutEffect(() => {
+ input.current?.focus();
+ input.current?.select();
+ }, []);
+ const text = q.trim();
+ const wiki = useWikiSuggest(/^https?:\/\//i.test(text) ? "" : text);
+
+ const choices: Choice[] = [];
+ if (/^https?:\/\/\S+$/i.test(text)) {
+ try {
+ choices.push({ group: "Address", label: hostOf(text), sub: text, ref: validateRef({ kind: "url", url: text }) });
+ } catch {
+ /* not an address after all */
+ }
+ }
+ const typed = /^(w(\.[a-z-]+)?:|\.?\/)/.test(text) ? parseTarget(text) : null;
+ if (typed && typeof typed !== "string") choices.push({ group: typed.kind === "wiki" ? "Wikipedia" : "Library", label: describeTarget(typed), sub: "as typed", ref: typed });
+ choices.push(...libraryChoices(text, spot.node));
+ choices.push(...(wiki?.list ?? []).map(articleChoice));
+ const sel = Math.min(i, choices.length - 1);
+ const apply = (c: Choice | undefined) => {
+ if (!c) return;
+ store.closePicker();
+ store.applyTarget(spot, c.ref);
+ };
+ const existing = spot.existing ? store.snap.nodes[spot.existing]?.ref : spot.range ? undefined : store.snap.nodes[spot.node]?.ref;
+ return (
+ store.closePicker()}>
+
e.stopPropagation()}>
+
+ {existing ? `Retarget (now ${describeTarget(existing)})` : spot.range ? `Link “${clip(spot.text, 50)}” to…` : `What “${clip(spot.text, 40)}” is about…`}
+
+
(setQ((e.target as HTMLInputElement).value), setI(0))}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === "Escape") store.closePicker();
+ else if (e.key === "ArrowDown" || (e.ctrlKey && e.key === "n") || (e.key === "Tab" && !e.shiftKey)) (e.preventDefault(), setI(Math.min(choices.length - 1, sel + 1)));
+ else if (e.key === "ArrowUp" || (e.ctrlKey && e.key === "p") || (e.key === "Tab" && e.shiftKey)) (e.preventDefault(), setI(Math.max(0, sel - 1)));
+ else if (e.key === "Enter") (e.preventDefault(), apply(choices[sel]));
+ }}
+ />
+
+
+ {!choices.length && {text ? "Nothing matches yet." : "Type to search."} }
+ {text && !wiki && wikiConfig().mode !== "off" && !/^https?:/i.test(text) && Asking Wikipedia… }
+ {wiki?.problem && Wikipedia: {wiki.problem} }
+
+
+
+ );
+}
diff --git a/src/ui/Menu.tsx b/src/ui/Menu.tsx
new file mode 100644
index 0000000..a5d3c3c
--- /dev/null
+++ b/src/ui/Menu.tsx
@@ -0,0 +1,192 @@
+/** The top bar (where the reader is, and whether it is saved) and the documents menu it opens (m). */
+import { useLayoutEffect, useRef, useState } from "preact/hooks";
+import { clip } from "../core/text";
+import { store } from "./store";
+
+const SAVE_LABEL = { saved: "saved", saving: "saving…", offline: "offline · kept in this browser", foreign: "not saved · reload the page" };
+const SAVE_TITLE = {
+ saved: "Every edit is saved as you make it. The server has all of them.",
+ saving: "Every edit is saved as you make it. The latest are on their way to the server.",
+ offline: "The server cannot be reached. Edits are kept in this browser and sent when it can.",
+ foreign: "The server now holds a different library than this page.",
+};
+
+export function DocBar() {
+ const state = store.saveState();
+ const here = store.currentDoc;
+ const snap = store.snap;
+ return (
+
+ {
+ e.stopPropagation();
+ if (store.mode === "docs") store.closeMenu();
+ else store.openMenu();
+ }}
+ >
+ {here ? snap.nodes[here]?.title || "Untitled" : snap.nodes[snap.root].title}
+
+
+
+ {SAVE_LABEL[state]}
+
+
+ );
+}
+
+function TitlePrompt() {
+ const p = store.menu.prompt!;
+ const label = { new: "New document, titled", rename: "Rename to", duplicate: "Save a copy as" }[p.kind];
+ return (
+
+ {label}
+ {
+ if (el && document.activeElement !== el) (el.focus(), el.select());
+ }}
+ defaultValue={p.value}
+ placeholder="Title"
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === "Enter") {
+ e.preventDefault();
+ store.menuSubmit((e.target as HTMLInputElement).value);
+ } else if (e.key === "Escape") {
+ e.preventDefault();
+ store.menu.prompt = null;
+ store.menu.focus = "list";
+ store.emit();
+ }
+ }}
+ />
+
+ );
+}
+
+export function DocsPanel() {
+ const m = store.menu;
+ const items = store.menuItems();
+ const sel = store.menuSelected();
+ const current = store.currentDoc;
+ const ref = useRef(null);
+ const [dropping, setDropping] = useState(false);
+ useLayoutEffect(() => {
+ ref.current?.querySelector(".doc.selected")?.scrollIntoView({ block: "nearest" });
+ });
+ const typing = m.focus === "filter" && !m.prompt && !m.confirm;
+ const act = (fn: () => void) => (e: MouseEvent) => {
+ e.stopPropagation();
+ fn();
+ };
+ return (
+ (e.preventDefault(), setDropping(true))}
+ onDragLeave={() => setDropping(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setDropping(false);
+ const file = e.dataTransfer?.files[0];
+ if (file) void store.importFile(file);
+ }}
+ >
+
+ Documents
+
+ {typing ? "type to filter · ↑ ↓ · Enter open · Esc for actions" : "j k · Enter open · n new · r rename · s save as · D delete · x export · i import · / filter · Esc"}
+
+
+ {
+ if (el && typing && document.activeElement !== el) el.focus();
+ }}
+ value={m.filter}
+ placeholder="Filter by title or text…"
+ onFocus={() => m.focus !== "filter" && ((m.focus = "filter"), store.emit())}
+ onInput={(e) => store.menuFilter((e.target as HTMLInputElement).value)}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ const k = e.key;
+ if (k === "ArrowDown" || (e.ctrlKey && (k === "n" || k === "j"))) (e.preventDefault(), store.menuMove(1));
+ else if (k === "ArrowUp" || (e.ctrlKey && (k === "p" || k === "k"))) (e.preventDefault(), store.menuMove(-1));
+ else if (k === "Enter") {
+ e.preventDefault();
+ // The selection as it is now: the filter may have changed since this was drawn.
+ const now = store.menuSelected();
+ if (now) store.openDoc(now.node);
+ } else if (k === "Escape" || k === "Tab") {
+ e.preventDefault();
+ m.focus = "list";
+ (e.target as HTMLInputElement).blur();
+ store.emit();
+ }
+ }}
+ />
+ {m.prompt && }
+ {m.confirm && (
+
+ Delete “{clip(items.find((d) => d.node === m.confirm)?.title ?? "", 60)}” and everything in it? u brings it back.
+
+ store.deleteDocument(m.confirm!))}>delete (y)
+ ((m.confirm = null), store.emit()))}>keep (n)
+
+
+ )}
+ {m.problems && (
+
+
The file was not imported:
+
+ {m.problems.slice(0, 30).map((p, i) => (
+ {p}
+ ))}
+
+
+ )}
+
+ {items.map((d) => {
+ const selected = d.node === sel?.node;
+ return (
+ {
+ // A click in the list hands the keys to the list.
+ m.selected = d.node;
+ m.focus = "list";
+ (document.activeElement as HTMLElement | null)?.blur();
+ store.emit();
+ }}
+ onDblClick={() => store.openDoc(d.node)}
+ >
+
+ {d.title || "Untitled"}
+ {d.node === current ? `open · ${SAVE_LABEL[store.saveState()]}` : `/doc/${d.slug}`}
+
+ {d.excerpt || "No text yet."}
+ {selected && (
+
+ {d.node !== current && store.openDoc(d.node))}>open }
+ store.menuPrompt("rename"))}>rename
+ store.menuPrompt("duplicate"))}>save as
+ store.exportDocument(d.node))}>export .md
+ ((m.confirm = d.node), store.emit()))}>delete
+
+ )}
+
+ );
+ })}
+ {!items.length && No document matches. }
+
+
+
+ );
+}
diff --git a/src/ui/Node.tsx b/src/ui/Node.tsx
new file mode 100644
index 0000000..545a9f2
--- /dev/null
+++ b/src/ui/Node.tsx
@@ -0,0 +1,461 @@
+/** Rendering shared by both page layouts: a node's body with its notes, the outline rows, and the top of the page. */
+import { Component, type ComponentChildren } from "preact";
+import { useLayoutEffect, useRef, useState } from "preact/hooks";
+import { anchorLost, ancestors, descendants, docOf, isLibraryRoot, label, notesOf, sections, staleness, type NodeId, type Snap } from "../core/model";
+import type { Ref } from "../core/ref";
+import { clip, overlaps, paragraphs, plain, type Form, type Range } from "../core/text";
+import { streamView } from "../core/marks";
+import { ChoiceRows, LinkMark, LinkPreview, NodeBacklinks, NodeRelated, SuggestionCard, TargetRow, articleChoice, sectionChoice, useWikiSuggest, type Choice } from "./Links";
+import { store, type Pending } from "./store";
+
+// ---- inline text ----
+
+/** A note as the renderer sees it: one in the document, or one still being written. */
+interface VNote {
+ key: string;
+ id?: NodeId;
+ form: Form;
+ ranges: Range[];
+ open: boolean;
+ pending?: Pending;
+ lens?: string;
+ /** Its target, if it links somewhere. */
+ ref?: Ref;
+ /** A link: a target and no text of its own. */
+ link?: boolean;
+}
+
+function notesFor(snap: Snap, id: NodeId): { placed: VNote[]; orphans: NodeId[] } {
+ const placed: VNote[] = [];
+ const orphans: NodeId[] = [];
+ for (const c of notesOf(snap, id)) {
+ const n = snap.nodes[c];
+ const ranges = n.anchors.filter((a) => a.end > a.start).map((a): Range => [a.start, a.end]);
+ if (!ranges.length || n.anchors.every(anchorLost)) orphans.push(c);
+ else placed.push({ key: c, id: c, form: n.form ?? "note", ranges, open: store.open.has(c), lens: n.lens, ref: n.ref, link: !!n.ref && !n.body.trim() });
+ }
+ for (const p of store.pending.values()) {
+ if (p.node === id && p.kind === "note" && p.range) placed.push({ key: p.key, form: p.form ?? "note", ranges: [p.range], open: true, pending: p, lens: p.lens });
+ }
+ return { placed, orphans };
+}
+
+const MARK = /\*([^*\n]+)\*|`([^`\n]+)`/g;
+
+/** One paragraph (or a whole short body) as spans that know their offsets into the body. */
+function Para(props: { id: NodeId; range: Range; notes: VNote[]; inline: boolean; inNote: boolean; first: boolean }) {
+ const { id, range, notes, inline } = props;
+ const snap = store.snap;
+ const body = snap.nodes[id].body;
+ const [ps, pe] = range;
+ const cuts = new Set([ps, pe]);
+ const clipTo = (r: Range): Range | null => (r[0] < pe && r[1] > ps ? [Math.max(r[0], ps), Math.min(r[1], pe)] : null);
+ const cut = (r: Range | null) => r && (cuts.add(r[0]), cuts.add(r[1]));
+
+ // *emphasis* and `code`: the markers are hidden but still count as characters.
+ const hidden = new Set();
+ const em: Range[] = [];
+ const code: Range[] = [];
+ const text = body.slice(ps, pe);
+ MARK.lastIndex = 0;
+ for (let m; (m = MARK.exec(text)); ) {
+ const a = ps + m.index;
+ const b = a + m[0].length;
+ hidden.add(a).add(b - 1);
+ (m[1] !== undefined ? em : code).push([a + 1, b - 1]);
+ [a, a + 1, b - 1, b].forEach((x) => cuts.add(x));
+ }
+
+ for (const n of notes) n.ranges.forEach((r) => cut(clipTo(r)));
+ // Suggested links: a faint dashed underline where no note or link already is.
+ const suggs = store.preview ? [] : store.links.forNode(id, snap).filter((sg) => !notes.some((n) => n.ranges.some((r) => overlaps(r, sg.range))));
+ for (const sg of suggs) cut(clipTo(sg.range));
+ const focusedSugg = store.focusedSuggestion();
+ // Each linked span gets one mark, after its last character: the first link on it, in library order.
+ const marked = new Set();
+ const f = store.focus;
+ const sel = f.node === id && f.grain !== "node" && f.range ? clipTo(f.range) : null;
+ cut(sel);
+ // On the root, show which sentences of the prompt the focused section grew from.
+ const focusNode = snap.nodes[f.node];
+ const chain = focusNode ? [f.node, ...ancestors(snap, f.node)] : [];
+ const source = chain.map((x) => snap.nodes[x]).find((x) => x.parent === id && x.kind === "section" && x.anchors.length);
+ const srcRanges = source ? source.anchors.map((a): Range => [a.start, a.end]) : [];
+ srcRanges.forEach((r) => cut(clipTo(r)));
+
+ const within = (rs: Range[], a: number, b: number) => rs.some((r) => r[0] <= a && r[1] >= b);
+ const points = [...cuts].sort((x, y) => x - y);
+ const out: ComponentChildren[] = [];
+ const after: ComponentChildren[] = [];
+ for (let i = 0; i + 1 < points.length; i++) {
+ const a = points[i];
+ const b = points[i + 1];
+ if (!(b === a + 1 && hidden.has(a))) {
+ // A note (with text) gets the dotted underline; a link the solid one. A note that also links
+ // keeps its dotted underline and gets the mark, so the two facts stay separately legible.
+ const note = notes.find((n) => !n.link && within(n.ranges, a, b));
+ const link = notes.find((n) => n.ref && within(n.ranges, a, b));
+ const sugg = !note && !link ? suggs.find((sg) => sg.range[0] <= a && sg.range[1] >= b) : undefined;
+ const cls = [
+ within(em, a, b) && "em",
+ within(code, a, b) && "code",
+ note && `anchor a-${note.form}`,
+ note?.open && "on",
+ note?.pending && "writing",
+ link?.link && !note && `lnk l-${link.ref!.kind}${link.open ? " on" : ""}`,
+ sel && sel[0] <= a && sel[1] >= b && `sel ${f.grain}`,
+ within(srcRanges, a, b) && "src",
+ sugg && `sugg${sugg.tier === "auto" ? " sure" : ""}`,
+ ].filter(Boolean).join(" ");
+ out.push(
+
+ {body.slice(a, b)}
+ ,
+ );
+ }
+ for (const n of notes) {
+ const r = n.ranges[0];
+ if (!n.ref || r[1] !== b || b <= ps || b > pe || marked.has(`${r[0]}:${r[1]}`)) continue;
+ marked.add(`${r[0]}:${r[1]}`);
+ out.push( );
+ }
+ if (focusedSugg && focusedSugg.node === id && focusedSugg.range[1] === b && b > ps && b <= pe) after.push( );
+ for (const n of notes) {
+ if (!n.open || n.ranges[0][1] !== b || (b === ps && i === 0)) continue;
+ if (n.link) {
+ // A link opens its target in panes; in the column it shows a preview under the paragraph.
+ if (!store.panes && n.id) after.push( );
+ continue;
+ }
+ const view = ;
+ // A pane has no margin, so there a margin note follows its paragraph instead of splitting it.
+ if (n.form === "passage" || (n.form === "note" && (props.inNote || store.panes))) after.push(view);
+ else out.push(view);
+ }
+ }
+ const Tag = (inline ? "span" : "p") as "p";
+ return (
+ <>
+ {out}
+ {after}
+ >
+ );
+}
+
+function Writing({ text }: { text: string }) {
+ // Link marks ([[…]]) a model writes are never shown, even half-written.
+ return (
+ <>
+ {plain(streamView(text))}
+
+ >
+ );
+}
+
+const LENS_LABEL: Record = { elaborate: "", define: "definition", why: "why", example: "example", challenge: "objection" };
+
+function NoteView({ v, inNote }: { v: VNote; inNote: boolean }) {
+ const snap = store.snap;
+ const focused = !!v.id && store.focus.node === v.id;
+ const st = v.id ? staleness(snap, v.id) : null;
+ const stale = !!st && (st.down || st.up);
+ const cls = `${focused && store.focus.grain === "node" ? " focused" : ""}${v.pending ? " pending" : ""}${stale ? " stale" : ""}`;
+ const lens = v.lens ? (LENS_LABEL[v.lens] ?? v.lens) : "";
+ const content = v.pending ? : ;
+ const meta = (lens || stale || (v.id && snap.nodes[v.id].pinned)) && (
+
+ {lens}
+ {v.id && snap.nodes[v.id].pinned ? " · pinned" : ""}
+ {stale ? " · stale" : ""}
+
+ );
+ if (v.form === "gloss") {
+ return (
+
+ {content}
+
+ );
+ }
+ const kids = v.id ? sections(snap, v.id) : [];
+ return (
+
+ {meta}
+ {content}
+ {kids.length > 0 && }
+ {v.id && }
+
+ );
+}
+
+/** The phrase a choice puts in the text: what was typed, finished from the title where the title continues it. */
+function phraseFor(typed: string, title: string): string {
+ const base = title.replace(/\s*\([^)]*\)\s*$/, "");
+ if (!typed.trim()) return base;
+ return base.toLowerCase().startsWith(typed.toLowerCase()) ? typed + base.slice(typed.length) : typed.trim();
+}
+
+function BodyEditor({ id }: { id: NodeId }) {
+ const ref = useRef(null);
+ // The [[ completer: where the [[ is, what follows it, Wikipedia's answer for it, and the selection.
+ const [comp, setComp] = useState<{ start: number; q: string } | null>(null);
+ const [sel, setSel] = useState(0);
+ const fit = () => {
+ const el = ref.current;
+ if (!el) return;
+ el.style.height = "auto";
+ el.style.height = `${el.scrollHeight + 2}px`;
+ };
+ useLayoutEffect(() => {
+ ref.current?.focus();
+ fit();
+ }, []);
+ const typed = comp?.q.trim() ?? "";
+ const wiki = useWikiSuggest(typed.length >= 2 ? typed : "");
+ const detect = () => {
+ const el = ref.current!;
+ const m = /\[\[([^\[\]\n|]{0,60})$/.exec(el.value.slice(0, el.selectionStart));
+ setComp(m ? { start: el.selectionStart - m[0].length, q: m[1] } : null);
+ setSel(0);
+ };
+ // Library titles are instant and come first.
+ const choices: Choice[] = typed
+ ? [...store.search(comp!.q).filter((x) => x !== id).slice(0, 5).map(sectionChoice), ...(wiki?.list.slice(0, 6) ?? []).map(articleChoice)]
+ : [];
+ const accept = (c: Choice) => {
+ const el = ref.current!;
+ const phrase = phraseFor(comp!.q, c.label);
+ el.setRangeText(phrase, comp!.start, el.selectionStart, "end");
+ (store.edit!.chosen ??= []).push({ phrase, at: comp!.start, target: c.ref });
+ setComp(null);
+ fit();
+ };
+ return (
+ <>
+