Browser UI

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Fable 5.2 committed 2026-11-15 14:30:50 -05:00
1 parent dfa08f6e0c
commit dbd64aa591
17 files changed
+7118

No files matched your search

+641
View File
@@ -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 <WikiPage />;
const kids = sections(store.snap, store.top);
const listing = store.snap.library && store.top === store.snap.root;
return (
<article class={store.preview ? "preview" : ""}>
<TopMatter id={store.top} />
{kids.length > 0 && <Outline ids={kids} />}
<PendingSections id={store.top} />
{!listing && <TargetRow id={store.top} />}
{!listing && <NodeBacklinks id={store.top} />}
{!listing && <NodeRelated id={store.top} />}
</article>
);
}
// ---- 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 (
<div class={`item conflict ${c.status}${selected ? " selected" : ""}`} data-conflict={c.id}>
<div class="line">
<b>{c.title || "(untitled)"}</b>
<span class="chip">{c.status}</span>
</div>
<div class="sub">
{kind}
{other ? `: “${other}”` : ""}
</div>
{selected && (
<div class="sides">
{c.type !== "contradiction" && <Side name="before" text={c.base} />}
<Side name={c.type === "contradiction" ? "the other node says" : "side A (1)"} text={c.a} />
{c.type === "edit-delete" ? <Side name="side B (2)" text="(deleted the node)" /> : <Side name={c.type === "contradiction" ? "this node said" : "side B (2)"} text={c.b} />}
{c.type === "edit-edit" && <Side name="mechanical merge (3)" text={c.merged} />}
{c.status === "resolved" && <Side name={`resolved by ${c.resolvedBy}`} text={c.resolved || "(left deleted)"} strong />}
{c.rationale && <div class="why">{c.rationale}</div>}
<div class="actions">
{c.status === "open" ? (
<>
<button onClick={() => store.settle(c.id, "a")}>take A</button>
{c.type !== "contradiction" && <button onClick={() => store.settle(c.id, "b")}>{c.type === "edit-delete" ? "keep deleted" : "take B"}</button>}
{store.generating && <button onClick={() => store.resolveAll()}>ask the model</button>}
</>
) : (
<button onClick={() => store.reopen(c.id)}>reopen (x)</button>
)}
</div>
</div>
)}
</div>
);
}
function Side({ name, text, strong }: { name: string; text: string; strong?: boolean }) {
return (
<div class={`side${strong ? " strong" : ""}`}>
<span class="name">{name}</span>
<span class="text">{text}</span>
</div>
);
}
function HistoryPanel({ verdict }: { verdict: string }) {
const items = store.panel();
const ref = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
ref.current?.querySelector(".selected")?.scrollIntoView({ block: "nearest" });
});
const heads = new Set<string>();
let lastType = "";
return (
<aside class="panel" ref={ref}>
<div class="panel-head">
<span>History{store.historyFilter && store.currentDoc ? ` · ${clip(store.snap.nodes[store.currentDoc]?.title ?? "", 30)}` : " · the library"}</span>
<span class="keys">j k · Enter · r revert{store.currentDoc ? " this document" : ""} · n branch · m merge · f {store.historyFilter ? "everything" : "this document"} · v verify · Esc</span>
</div>
{verdict && <div class="verdict">{verdict}</div>}
{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 (
<div key={it.type === "commit" ? it.commit.id : it.type === "branch" ? `b:${it.branch}` : `c:${it.conflict.id}`} onClick={pick}>
{head && <h3>{head}</h3>}
{it.type === "conflict" && <ConflictCard c={it.conflict} selected={selected} />}
{it.type === "branch" && (
<div class={`item branch${selected ? " selected" : ""}`}>
<span class="line">
{it.branch === store.repo.current ? "● " : "○ "}
{it.branch}
</span>
{it.branch === store.repo.current ? <span class="sub">current</span> : <span class="sub">Enter switch · m merge into {store.repo.current}</span>}
</div>
)}
{it.type === "commit" && <CommitRow c={it.commit} selected={selected} />}
</div>
);
})}
</aside>
);
}
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 (
<div class={`item commit${selected ? " selected" : ""}${viewing ? " viewing" : ""}`}>
<div class="line">
<code class="hash">{c.hash ? c.hash.slice(0, 7) : "·······"}</code>
<span class="msg">{c.message}</span>
</div>
<div class="sub">
{c.by}
{c.actor === "llm" ? " (model)" : ""} · {ago(c.time)}
{c.parents.length > 1 ? " · merge" : ""}
{c.tag ? ` · ${c.tag}` : ""}
{viewing ? " · viewing" : ""}
</div>
{docs.length > 0 && (
<div class="docs" title={docs.join(", ")}>
{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(" · ")}
</div>
)}
</div>
);
}
function Help() {
return (
<div class="overlay" onClick={() => store.setMode("normal")}>
<div class="help" onClick={(e) => e.stopPropagation()}>
<h2>Keys</h2>
<p class="lede">
Focus is a node and a grain. Start on a section, press <kbd>i</kbd> to move by sentence, <kbd>i</kbd> again by word, and <kbd>e</kbd> on
anything to go deeper. Text with a dotted underline already has an expansion; anything else is written on request.
</p>
<div class="cols">
{HELP.map(([head, rows]) => (
<section key={head}>
<h3>{head}</h3>
<dl>
{rows.map(([keys, what]) => (
<div key={keys}>
<dt>
{!keys ? null : keys.length > 1 && keys.startsWith("/") ? <code>{keys}</code> : keys.split(" ").map((k) => <kbd key={k}>{k}</kbd>)}
</dt>
<dd>{what}</dd>
</div>
))}
</dl>
</section>
))}
</div>
</div>
</div>
);
}
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 (
<div class="overlay" onClick={close}>
<div class="jump" onClick={(e) => e.stopPropagation()}>
<input
autoFocus
ref={(el) => 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]);
}}
/>
<ul>
{hits.map((id, k) => {
const d = docOf(snap, id);
const within = ancestorsInDoc(snap, id).reverse().slice(1);
return (
<li key={id} class={k === i ? "selected" : ""} onClick={() => store.jumpTo(id)}>
<span class="t">{label(snap, id)}</span>
<span class="p">
{d && d !== id ? <b class="in">{snap.nodes[d].title}</b> : <b class="in">document</b>}
{within.length ? ` › ${within.map((a) => snap.nodes[a].title).join(" › ")}` : ""}
</span>
</li>
);
})}
{!hits.length && <li class="none">Nothing matches.</li>}
</ul>
</div>
</div>
);
}
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 (
<div class="command">
<span class="prompt">{about}</span>
<input
ref={(el) => {
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")}
/>
</div>
);
}
/** 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() && <NodeBody id={note} inline inNote />}
{n.ref && <LinkCard r={n.ref} compact />}
</>
);
}
const place = (x: number, top: number, bottom: number): Record<string, string> => ({
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 (
<div class="popup" style={place(p.x, p.top, p.bottom)} data-popup={p.note}>
<PopupBody note={p.note} />
</div>
);
}
/**
* 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<HTMLDivElement>(null);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const sel = [...document.querySelectorAll<HTMLElement>(".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 (
<div class="popup focus-popup" ref={ref} data-popup={note} style={{ visibility: "hidden" }}>
<PopupBody note={note} />
</div>
);
}
/**
* 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 (
<div class="agent-panel" data-agent={run.running ? "running" : "done"}>
<div class="agent-head">
<span class="agent-label">editor</span>
{run.running ? "researching on the web · Esc stops" : "done · Esc closes"}
</div>
<ol class="agent-steps">
{all.length > steps.length && <li class="agent-more">{all.length - steps.length} earlier steps</li>}
{steps.map((s, i) => (
<li key={all.length - steps.length + i}>{s}</li>
))}
</ol>
{!run.running && run.summary && <div class="agent-summary">{run.summary}</div>}
{!run.running && run.sources && (
<div class="agent-sources">
{run.sources.length ? "Sources: " : "No sources were linked."}
{run.sources.map((s, i) => (
<span key={s.url}>
{i ? " · " : ""}
<a href={s.url} target="_blank" rel="noopener noreferrer" data-source={s.url}>
{s.title || hostOf(s.url)}
</a>{" "}
<span class="agent-host">{hostOf(s.url)}</span>
</span>
))}
</div>
)}
</div>
);
}
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 (
<footer class="status">
<span class={`grain ${store.aux ? "aux" : f.grain}`}>{store.preview ? "history" : store.mode === "review" ? "review" : store.aux ? (store.aux.kind === "wiki" ? "article" : store.aux.kind === "back" ? "linked" : "target") : f.grain}</span>
<span class="path">{path}</span>
<span class="message">{store.status || hint}</span>
<span class="right">
{store.links.job?.state === "running" && (
<span class="job" title={store.jobText(store.links.job)}>
links {store.links.job.done}/{store.links.job.total} · :/linkcancel
</span>
)}
{store.busy > 0 && <span class="spin" />}
<Usage />
<span title="branch">{store.repo.current}</span>
<span title="model">{store.llm.kind === "off" ? "no model" : store.llm.model}</span>
<span class={`dot ${store.online ? "on" : "off"}`} title={store.online ? "synced with the local server" : "offline: changes are kept locally"} />
<span class="q">? keys</span>
</span>
</footer>
);
}
// ---- 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<HTMLElement>("[data-o]");
const body = el?.closest<HTMLElement>("[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<typeof setTimeout> | 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 <div class="fatal">{store.fatal}</div>;
if (!store.ready) return <div class="loading">Loading…</div>;
const panes = store.panes;
const onClick = (e: MouseEvent) => {
if (store.mode === "edit") return;
const target = e.target as HTMLElement;
const paneEl = target.closest<HTMLElement>("[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<HTMLElement>("[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<HTMLElement>("[data-host]")?.dataset.host;
const a = target.closest<HTMLAnchorElement>("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<HTMLElement>("[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<HTMLElement>("[data-linking]");
if (linking) {
store.paneAt = paneIndex;
return store.openLinking(linking.dataset.linking as NodeId);
}
const targetRow = target.closest<HTMLElement>("[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<HTMLElement>("[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<HTMLElement>("[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<HTMLElement>("[data-node]");
if (node) store.go(node.dataset.node as NodeId);
};
const onOver = (e: MouseEvent) => {
const anchor = (e.target as HTMLElement).closest<HTMLElement>("[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 (
<div class={`app mode-${store.mode}${store.mode === "history" || store.mode === "docs" ? " with-panel" : ""}${panes ? " view-panes" : ""}`} onMouseOver={onOver}>
<main class="page" onClick={onClick}>
<DocBar />
{store.preview && (
<div class="banner">
Viewing “{clip(store.preview.commit.message, 70)}” by {store.preview.commit.by}, {ago(store.preview.commit.time)}. Read-only.
</div>
)}
{panes ? <Panes /> : <Page />}
</main>
{store.mode === "history" && <HistoryPanel verdict={verdict} />}
{store.mode === "docs" && <DocsPanel />}
{store.mode === "help" && <Help />}
{store.mode === "jump" && <Jump />}
{store.mode === "command" && <CommandBar prefill={prefill} />}
{store.mode === "link" && store.picker && <LinkPicker />}
<Popup />
<FocusPopup />
<AgentPanel />
<StatusLine />
</div>
);
}
+349
View File
@@ -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<Ref["kind"], string> = { 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 (
<span class={`lmark l-${r.kind}${broken ? " broken" : ""}`} data-note={id} title={where(r)} aria-hidden="true">
{MARK[r.kind]}
</span>
);
}
/** 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 (
<p class="wattr">
{a.text}{" "}
<a href={a.url} target="_blank" rel="noopener noreferrer">article</a>
{a.revisionUrl && (
<>
{" · "}
<a href={a.revisionUrl} target="_blank" rel="noopener noreferrer">this revision</a>
</>
)}
{" · "}
<a href={a.license.url} target="_blank" rel="noopener noreferrer">{a.license.name}</a>
</p>
);
}
/** 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 (
<div class="lcard l-url">
<div class="lhead">
<span class="lmark l-url">↗</span> {hostOf(r.url)}
</div>
{r.title && <div class="ltitle">{r.title}</div>}
<div class="lsub">{clip(r.url, 90)}</div>
</div>
);
}
if (r.kind === "node") {
const s = store.snap;
const id = resolveNode(store.snap, r);
if (!id) {
return (
<div class="lcard l-node broken">
<div class="lhead"><span class="lmark l-node">§</span> broken link</div>
<div class="lsub">The note this pointed to is gone{r.path?.length ? `: it was “${r.path.join(" › ")}”${r.doc ? ` in ${r.doc}` : ""}` : ""}.</div>
</div>
);
}
const d = docOf(s, id);
const n = s.nodes[id];
const sec = ownerSection(s, id);
return (
<div class="lcard l-node">
<div class="lhead">
<span class="lmark l-node">§</span> {d ? s.nodes[d].title : "the library"}
{sec !== d && n.kind === "note" ? ` › ${label(s, sec)}` : ""}
</div>
<div class="ltitle">{label(s, id)}</div>
{n.body.trim() && <div class="lbody">{clip(plain(n.body), compact ? 160 : 320)}</div>}
</div>
);
}
const sum = summary(r.title, r.lang);
return (
<div class="lcard l-wiki">
<div class="lhead">
<span class="lmark l-wiki">W</span> Wikipedia
</div>
<div class="ltitle">{sum.state === "ready" ? sum.value.title : r.title}</div>
{sum.state === "loading" && <div class="lsub">Loading the summary…</div>}
{sum.state === "failed" && <div class="lsub problem">{sum.message}</div>}
{sum.state === "ready" && (
<>
{sum.value.description && <div class="lsub">{sum.value.description}</div>}
{sum.value.disambiguation && <div class="lsub">A disambiguation page: it lists the senses of the word.</div>}
<div class="lbody">{compact ? clip(sum.value.extract, 240) : sum.value.extract}</div>
<Attribution a={sum.value.attribution} />
</>
)}
</div>
);
}
/** 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 (
<span class={`inset lpreview l-${n.ref.kind}${store.focus.node === id ? " focused" : ""}`} data-node={id}>
<LinkCard r={n.ref} />
<span class="meta lnext">{next}</span>
</span>
);
}
/** 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 (
<div class={`target-row l-${r.kind}${focused ? " focused" : ""}`} data-target={id}>
<span class="meta">about</span>
<LinkCard r={r} compact />
</div>
);
}
/**
* "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 (
<section class="backlinks">
<h3>{title}</h3>
<ul>
{ids.map((id, i) => {
const sec = ownerSection(s, id);
const d = docOf(s, id);
const n = s.nodes[id];
return (
<li key={id} class={focusedAt(i) ? "focused" : ""} data-linking={id}>
<span class="bl-title">{label(s, sec)}</span>
<span class="bl-doc">{d && d !== sec ? s.nodes[d].title : "document"}</span>
{n.kind === "note" && <span class="bl-quote">“{clip(n.anchors[0]?.text ?? "", 60)}”</span>}
</li>
);
})}
</ul>
</section>
);
}
/** 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 (
<span class={`inset lpreview suggestion l-${sg.target.kind}`} data-suggestion={sg.id}>
<span class="meta">suggested link{sg.tier === "auto" ? " (sure)" : ""} · y links · n declines{store.review ? " · s skips" : " · S reviews them all"}</span>
<LinkCard r={sg.target} compact />
<span class="meta why">{sg.why}</span>
</span>
);
}
/**
* "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 (
<section class="related-list">
<h3>Related</h3>
<ul>
{rows.map((r, i) => (
<li key={r.node} data-related={r.node}>
<span class="bl-key">{i + 1}</span>
<span class="bl-title">{r.title}</span>
<span class="bl-doc">{r.doc}</span>
<span class="bl-quote">{r.why}</span>
</li>
))}
</ul>
</section>
);
}
export function NodeBacklinks({ id }: { id: NodeId }) {
const ids = store.linkedFrom(id);
const a = store.aux;
return <Backlinks ids={ids} title="Linked from" focusedAt={(i) => 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 (
<Fragment key={k}>
{head && <li class="group">{head}</li>}
<li class={`choice${k === sel ? " selected" : ""}`} data-choice={k} onMouseDown={(e) => e.preventDefault()} onClick={() => pick(c)}>
<span class={`lmark l-${c.ref.kind}`}>{MARK[c.ref.kind]}</span>
<span class="t">{c.label}</span>
<span class="p">{c.sub}</span>
</li>
</Fragment>
);
})}
</>
);
}
/** 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<HTMLInputElement>(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 (
<div class="overlay" onClick={() => store.closePicker()}>
<div class="jump picker" onClick={(e) => e.stopPropagation()}>
<div class="picker-head">
{existing ? `Retarget (now ${describeTarget(existing)})` : spot.range ? `Link “${clip(spot.text, 50)}” to…` : `What “${clip(spot.text, 40)}” is about…`}
</div>
<input
ref={input}
value={q}
placeholder="Search the library and Wikipedia, or paste an address"
onInput={(e) => (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]));
}}
/>
<ul>
<ChoiceRows choices={choices} sel={sel} pick={apply} />
{!choices.length && <li class="none">{text ? "Nothing matches yet." : "Type to search."}</li>}
{text && !wiki && wikiConfig().mode !== "off" && !/^https?:/i.test(text) && <li class="none">Asking Wikipedia…</li>}
{wiki?.problem && <li class="none problem">Wikipedia: {wiki.problem}</li>}
</ul>
</div>
</div>
);
}
+192
View File
@@ -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 (
<nav class="docbar">
<button
class="doc-title"
title="Documents (m)"
onClick={(e) => {
e.stopPropagation();
if (store.mode === "docs") store.closeMenu();
else store.openMenu();
}}
>
<span class="name">{here ? snap.nodes[here]?.title || "Untitled" : snap.nodes[snap.root].title}</span>
<span class="chev" />
</button>
<span class={`save-state ${state}`} title={SAVE_TITLE[state]}>
{SAVE_LABEL[state]}
</span>
</nav>
);
}
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 class="prompt">
<span>{label}</span>
<input
ref={(el) => {
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();
}
}}
/>
</label>
);
}
export function DocsPanel() {
const m = store.menu;
const items = store.menuItems();
const sel = store.menuSelected();
const current = store.currentDoc;
const ref = useRef<HTMLElement>(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 (
<aside
class={`panel docs${dropping ? " dropping" : ""}`}
ref={ref}
onDragOver={(e) => (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);
}}
>
<div class="panel-head">
<span>Documents</span>
<span class="keys">
{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"}
</span>
</div>
<input
class="filter"
ref={(el) => {
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 && <TitlePrompt />}
{m.confirm && (
<div class="confirm">
Delete “{clip(items.find((d) => d.node === m.confirm)?.title ?? "", 60)}” and everything in it? u brings it back.
<div class="actions">
<button onClick={act(() => store.deleteDocument(m.confirm!))}>delete (y)</button>
<button onClick={act(() => ((m.confirm = null), store.emit()))}>keep (n)</button>
</div>
</div>
)}
{m.problems && (
<div class="problems">
<b>The file was not imported:</b>
<ul>
{m.problems.slice(0, 30).map((p, i) => (
<li key={i}>{p}</li>
))}
</ul>
</div>
)}
<ul class="doclist">
{items.map((d) => {
const selected = d.node === sel?.node;
return (
<li
key={d.node}
class={`item doc${selected ? " selected" : ""}${d.node === current ? " current" : ""}`}
data-doc={d.slug}
onClick={() => {
// 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)}
>
<div class="line">
<span class="title">{d.title || "Untitled"}</span>
<span class="when">{d.node === current ? `open · ${SAVE_LABEL[store.saveState()]}` : `/doc/${d.slug}`}</span>
</div>
<div class="sub">{d.excerpt || "No text yet."}</div>
{selected && (
<div class="actions">
{d.node !== current && <button onClick={act(() => store.openDoc(d.node))}>open</button>}
<button onClick={act(() => store.menuPrompt("rename"))}>rename</button>
<button onClick={act(() => store.menuPrompt("duplicate"))}>save as</button>
<button onClick={act(() => store.exportDocument(d.node))}>export .md</button>
<button onClick={act(() => ((m.confirm = d.node), store.emit()))}>delete</button>
</div>
)}
</li>
);
})}
{!items.length && <li class="none">No document matches.</li>}
</ul>
<div class="panel-foot">
<button onClick={act(() => store.menuPrompt("new"))}>new document (n)</button>
<button onClick={act(() => store.pickFile())}>import .md (i)</button>
<span>or drop a .md file here</span>
</div>
</aside>
);
}
+461
View File
@@ -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<number>([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<number>();
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<string>();
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(
<span key={a} data-o={a} class={cls || undefined} data-note={(note ?? link)?.id} data-sugg={sugg?.id}>
{body.slice(a, b)}
</span>,
);
}
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(<LinkMark key={`m${n.key}`} r={n.ref} id={n.id} />);
}
if (focusedSugg && focusedSugg.node === id && focusedSugg.range[1] === b && b > ps && b <= pe) after.push(<SuggestionCard key="sugg" sg={focusedSugg} />);
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(<LinkPreview key={`p${n.key}`} id={n.id} />);
continue;
}
const view = <NoteView key={`n${n.key}`} v={n} inNote={props.inNote} />;
// 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 (
<>
<Tag class={`para${props.first ? " first" : ""}`}>{out}</Tag>
{after}
</>
);
}
function Writing({ text }: { text: string }) {
// Link marks ([[…]]) a model writes are never shown, even half-written.
return (
<>
{plain(streamView(text))}
<span class="caret" />
</>
);
}
const LENS_LABEL: Record<string, string> = { 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 ? <Writing text={v.pending.text} /> : <NodeBody id={v.id!} inline inNote />;
const meta = (lens || stale || (v.id && snap.nodes[v.id].pinned)) && (
<span class="meta">
{lens}
{v.id && snap.nodes[v.id].pinned ? " · pinned" : ""}
{stale ? " · stale" : ""}
</span>
);
if (v.form === "gloss") {
return (
<span class={`gloss${cls}`} data-node={v.id}>
{content}
</span>
);
}
const kids = v.id ? sections(snap, v.id) : [];
return (
<span class={`${v.form === "passage" || inNote ? "inset" : "sidenote"}${cls}`} data-node={v.id}>
{meta}
{content}
{kids.length > 0 && <Outline ids={kids} />}
{v.id && <PendingSections id={v.id} />}
</span>
);
}
/** 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<HTMLTextAreaElement>(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 (
<>
<textarea
ref={ref}
class="editor"
data-edit={id}
spellcheck
defaultValue={store.edit!.value}
onInput={() => (fit(), detect())}
onKeyDown={(e) => {
e.stopPropagation();
if (comp) {
const n = choices.length;
if (e.key === "Escape") return e.preventDefault(), setComp(null);
if (n && (e.key === "ArrowDown" || (e.key === "Tab" && !e.shiftKey))) return e.preventDefault(), setSel((sel + 1) % n);
if (n && (e.key === "ArrowUp" || (e.key === "Tab" && e.shiftKey))) return e.preventDefault(), setSel((sel - 1 + n) % n);
if (n && e.key === "Enter") return e.preventDefault(), accept(choices[Math.min(sel, n - 1)]);
}
if (e.key === "Escape" || (e.key === "Enter" && (e.metaKey || e.ctrlKey))) {
e.preventDefault();
store.commitEdit((e.target as HTMLTextAreaElement).value);
}
}}
onKeyUp={(e) => (e.key === "ArrowLeft" || e.key === "ArrowRight") && detect()}
onBlur={(e) => store.edit?.node === id && store.commitEdit((e.target as HTMLTextAreaElement).value)}
/>
{comp && (
<div class="completer" data-completer>
<ul>
<ChoiceRows choices={choices} sel={Math.min(sel, choices.length - 1)} pick={accept} />
{!choices.length && <li class="group">{comp.q.trim() ? "Nothing yet · Esc leaves [[…]] to be looked up on save" : "Type what to link"}</li>}
</ul>
</div>
)}
</>
);
}
/** A node's body: paragraphs, with its notes placed where they are anchored. */
export function NodeBody({ id, inline, inNote }: { id: NodeId; inline?: boolean; inNote?: boolean }) {
const snap = store.snap;
const n = snap.nodes[id];
if (store.edit?.node === id && store.edit.field === "body") return <BodyEditor id={id} />;
const rewrite = [...store.pending.values()].find((p) => p.node === id && p.kind === "rewrite");
const { placed, orphans } = notesFor(snap, id);
const paras = paragraphs(n.body);
return (
<span class={`body${rewrite ? " rewriting" : ""}`} data-body={id}>
{paras.map((r, i) => (
<Para key={i} id={id} range={r} notes={placed} inline={!!inline} inNote={!!inNote} first={i === 0} />
))}
{!paras.length && !inline && (
<p class="para first empty">
{isLibraryRoot(snap, id) ? "Every document is a section of this library. l or Enter opens one, a adds one, m lists them; c writes a note about the library here." : `No text yet. c to write it${store.generating ? ", e to have it written" : ""}.`}
</p>
)}
{orphans.map((o) => (
<span key={o} class={`inset orphan${store.focus.node === o ? " focused" : ""}`} data-node={o}>
<span class="meta">orphaned: its text “{clip(snap.nodes[o].anchors[0]?.quote ?? "", 60)}” was deleted</span>
<NodeBody id={o} inline inNote />
</span>
))}
</span>
);
}
export function PendingSections({ id }: { id: NodeId }) {
const p = [...store.pending.values()].find((x) => x.node === id && x.kind === "sections");
if (!p) return null;
return (
<div class="pending-sections">
{p.text
? p.text.split(/^##\s+/m).filter((c) => c.trim()).map((chunk, i, all) => {
const nl = chunk.indexOf("\n");
const title = nl < 0 ? chunk : chunk.slice(0, nl);
return (
<div key={i} class="pending-section">
<div class="title">{title}</div>
<p class="para first">
{i === all.length - 1 ? <Writing text={nl < 0 ? "" : chunk.slice(nl + 1)} /> : plain(streamView(nl < 0 ? "" : chunk.slice(nl + 1)))}
</p>
</div>
);
})
: <p class="para first"><Writing text="" /></p>}
</div>
);
}
// ---- the outline ----
export function TitleEditor({ id }: { id: NodeId }) {
const ref = useRef<HTMLInputElement>(null);
useLayoutEffect(() => ref.current?.focus(), []);
return (
<input
ref={ref}
class="title-editor"
data-edit={id}
defaultValue={store.edit!.value}
placeholder="Title"
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === "Escape") {
e.preventDefault();
store.commitEdit((e.target as HTMLInputElement).value);
}
e.stopPropagation();
}}
onBlur={(e) => store.edit?.node === id && store.commitEdit((e.target as HTMLInputElement).value)}
/>
);
}
export function Flags({ id }: { id: NodeId }) {
const snap = store.snap;
const n = snap.nodes[id];
const st = staleness(snap, id);
const conflict = store.shown.conflicts().some((c) => c.status === "open" && (c.node === id || c.other === id));
const flags = [
conflict && "conflict",
st.up && "sections changed",
st.down && "parent changed",
n.pinned && n.parent && "pinned",
].filter(Boolean) as string[];
if (!flags.length) return null;
return <span class={`flags${st.up || st.down || conflict ? " attn" : ""}`}>{flags.join(" · ")}</span>;
}
/** Redraws a section only when something in its subtree changed. */
class Section extends Component<{ id: NodeId }> {
shouldComponentUpdate(next: { id: NodeId }) {
return next.id !== this.props.id || store.isDirty(next.id);
}
render() {
return <SectionView id={this.props.id} />;
}
}
/** A section's title line: marker, title (or its editor), flags. Clicking it is handled by the page. */
export function Row({ id, open, leaf, editing }: { id: NodeId; open: boolean; leaf: boolean; editing: boolean }) {
const n = store.snap.nodes[id];
return (
<div class="row" data-row={id}>
<span class="mark">{open ? "▾" : leaf ? "·" : "▸"}</span>
{editing ? <TitleEditor id={id} /> : <span class="title">{n.title || <i class="untitled">untitled</i>}</span>}
<Flags id={id} />
</div>
);
}
function SectionView({ id }: { id: NodeId }) {
const snap = store.snap;
const n = snap.nodes[id];
const open = store.isOpen(id);
const kids = sections(snap, id);
const focused = store.focus.node === id;
const leaf = !kids.length && !n.body.trim();
const editing = store.edit?.node === id && store.edit.field === "title";
const st = staleness(snap, id);
return (
<li class={`node d${Math.min(n.depth - (snap.library ? 1 : 0), 6)}${open ? " open" : ""}${focused ? " focused" : ""}${st.up || st.down ? " stale" : ""}`} data-node={id}>
<Row id={id} open={open} leaf={leaf} editing={editing} />
{open && (
<div class="content">
<NodeBody id={id} />
{kids.length > 0 && <Outline ids={kids} />}
<PendingSections id={id} />
<TargetRow id={id} />
<NodeBacklinks id={id} />
<NodeRelated id={id} />
</div>
)}
</li>
);
}
export function Outline({ ids }: { ids: NodeId[] }) {
return (
<ul class="outline">
{ids.map((id) => (
<Section key={id} id={id} />
))}
</ul>
);
}
/**
* The head of a page or of a pane that is a page of its own: the top node, or a document. Crumbs
* (on the top only), title, byline, and the node's own text, folded if it is a prompt. The
* library's byline counts documents; a document's counts its own sections and nodes.
*/
export function TopMatter({ id }: { id: NodeId }) {
const snap = store.snap;
const n = snap.nodes[id];
const kids = sections(snap, id);
const isTop = id === store.top;
const crumbs = isTop ? ancestors(snap, id).reverse() : [];
const focused = store.focus.node === id;
const editing = store.edit?.node === id && store.edit.field === "title";
const library = isLibraryRoot(snap, id);
// A document whose sections cite its sentences is a prompt (the first document's is): long, and
// the page should open on the outline, so it is folded until asked for. Other text is plain.
const prompt = !library && docOf(snap, id) === id && kids.some((k) => snap.nodes[k].anchors.length > 0);
const folded = prompt && !store.unfolded.has(id) && !(focused && store.focus.grain !== "node") && store.edit?.node !== id;
const count = library ? Object.keys(snap.nodes).length - 1 : descendants(snap, id).length;
return (
<>
{crumbs.length > 0 && (
<nav class="crumbs">
{crumbs.map((c) => (
<span key={c}>
<a onClick={() => (isLibraryRoot(snap, c) ? store.setHoist(null) : store.setHoist(c))}>{label(snap, c)}</a> ›{" "}
</span>
))}
</nav>
)}
<header class={`top${focused ? " focused" : ""}${library ? " library" : ""}`} data-node={id}>
<div data-row={id}>{editing ? <TitleEditor id={id} /> : <h1>{n.title || "Untitled"}</h1>}</div>
<div class="byline">
{library ? `${kids.length} document${kids.length === 1 ? "" : "s"}` : `${kids.length} section${kids.length === 1 ? "" : "s"}`} · {count} nodes · branch {store.repo.current}
<Flags id={id} />
</div>
</header>
<div class={`abstract${prompt ? " seed" : ""}${folded ? " folded" : ""}`} onClick={folded ? () => store.toggleFold(id) : undefined}>
<NodeBody id={id} />
</div>
{folded && <div class="unfold">Enter to read the whole prompt · every sentence of it is traced to a section below</div>}
</>
);
}
+245
View File
@@ -0,0 +1,245 @@
/**
* The panes view: a trail of panes, side by side, in the manner of Andy Matuschak's notes. It
* starts as the path down from the top node; a link followed from a pane opens its target in the
* next pane (another document's node, a Wikipedia article, a section of one), replacing what was
* to the right. Moving back left closes nothing: the trail stays until something else is opened
* from an earlier pane, or q closes panes. Earlier panes stay pinned at the left as narrow spines
* when later ones slide over them.
*
* The trail is `store.trail`; which pane holds the focus is `store.paneAt`. Clicks are handled by
* the page (App.tsx), exactly as in the column view.
*/
import { Component } from "preact";
import { useEffect, useLayoutEffect, useRef } from "preact/hooks";
import { docOf, label, sections, staleness, type NodeId } from "../core/model";
import { NodeBacklinks, NodeRelated, TargetRow } from "./Links";
import { Flags, NodeBody, PendingSections, Row, TitleEditor, TopMatter } from "./Node";
import { store, type Aux, type PaneRef } from "./store";
import { WikiView } from "./Wiki";
import { article } from "./wiki";
interface PaneProps {
p: PaneRef;
index: number;
/** The child whose pane is open to the right of this one, if any. */
showing?: NodeId;
/** The aux focus, when this pane holds it. */
aux: Aux | null;
active: boolean;
}
const key = (p: PaneProps) => `${p.p.kind === "node" ? p.p.id : `${p.p.title}#${p.p.sec ?? ""}`}|${p.index}|${p.showing ?? ""}|${p.active}|${JSON.stringify(p.aux)}`;
/** Redraws a pane only when something drawn in it changed (see `store.paneDirty`). An article pane is cheap to redraw: its HTML is set once. */
class Pane extends Component<PaneProps> {
shouldComponentUpdate(next: PaneProps) {
if (key(next) !== key(this.props)) return true;
if (next.p.kind === "wiki") return true;
return store.paneDirty(next.p.id) || !!store.snap.nodes[next.p.id]?.ref || store.linkedFrom(next.p.id).length > 0;
}
render() {
const p = this.props.p;
return p.kind === "node" ? <NodePane {...this.props} id={p.id} /> : <WikiPane {...this.props} />;
}
}
function NodePane({ id, index, showing, active }: PaneProps & { id: NodeId }) {
const snap = store.snap;
const n = snap.nodes[id];
if (!n) return null;
const top = id === store.top && index === 0;
// A document's pane is a page of its own, headed like one.
const page = top || docOf(snap, id) === id;
const kids = sections(snap, id);
const focused = active && !store.aux && store.focus.node === id;
const editing = store.edit?.node === id && store.edit.field === "title";
const jump = index > 0 && !store.continues(index);
return (
<article
class={`pane${top ? " root" : ""}${page && !top ? " doc" : ""}${jump ? " jumped" : ""}${n.kind === "note" ? " note-pane" : ""}${store.preview ? " preview" : ""}`}
data-pane={id}
data-pane-index={index}
style={{ left: `calc(${index} * var(--spine))` }}
>
<div class="spine" data-spine={index} title={label(snap, id)}>
<span>{label(snap, id)}</span>
</div>
<div class="pane-scroll">
{page ? (
<TopMatter id={id} />
) : (
<>
{jump && <div class="pane-from">{docOf(snap, id) ? snap.nodes[docOf(snap, id)!].title : "the library"}</div>}
<header class={`pane-head${focused ? " focused" : ""}`} data-node={id}>
{editing ? <TitleEditor id={id} /> : <h2>{n.title || (n.kind === "note" ? label(snap, id) : <i class="untitled">untitled</i>)}</h2>}
<Flags id={id} />
</header>
<NodeBody id={id} />
</>
)}
{kids.length > 0 && (
<ul class="outline rows">
{kids.map((k) => (
<PaneRow key={k} id={k} showing={k === showing} active={active} />
))}
</ul>
)}
<PendingSections id={id} />
{n.ref?.kind === "wiki" ? <WikiView host={`n${id}`} /> : <TargetRow id={id} />}
<NodeBacklinks id={id} />
<NodeRelated id={id} />
</div>
</article>
);
}
function WikiPane({ p, index }: PaneProps) {
if (p.kind !== "wiki") return null;
const a = article(p.title, p.lang);
const sec = p.sec && a.state === "ready" ? a.value.sections.find((x) => x.id === p.sec) : undefined;
const title = sec ? `${sec.heading} · ${p.title}` : a.state === "ready" ? a.value.title : p.title;
return (
<article class={`pane wiki-pane${p.from ? " jumped" : ""}`} data-pane={`w:${p.title}${p.sec ? `#${p.sec}` : ""}`} data-pane-index={index} style={{ left: `calc(${index} * var(--spine))` }}>
<div class="spine" data-spine={index} title={`Wikipedia: ${title}`}>
<span>
<b class="wmark">W</b> {title}
</span>
</div>
<div class="pane-scroll">
<WikiView host={`p${index}`} />
</div>
</article>
);
}
function PaneRow({ id, showing, active }: { id: NodeId; showing: boolean; active: boolean }) {
const snap = store.snap;
const n = snap.nodes[id];
const open = store.isOpen(id);
const leaf = !sections(snap, id).length && !n.body.trim();
const focused = active && !store.aux && store.focus.node === id;
const st = staleness(snap, id);
// While its pane is showing, the title is edited at the head of that pane instead.
const editing = !showing && store.edit?.node === id && store.edit.field === "title";
return (
<li class={`node d${Math.min(n.depth - (snap.library ? 1 : 0), 6)}${open ? " open" : ""}${focused ? " focused" : ""}${showing ? " showing" : ""}${st.up || st.down ? " stale" : ""}`} data-node={id}>
<Row id={id} open={open} leaf={leaf} editing={editing} />
</li>
);
}
const reducedMotion = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
/** Scroll a pane vertically, as little as possible, so that an element in it is in view. */
function nearestY(el: Element | null | false) {
const box = el && el.closest<HTMLElement>(".pane-scroll");
if (!el || !box) return;
const r = el.getBoundingClientRect();
const c = box.getBoundingClientRect();
const pad = 28;
if (r.top < c.top + pad) box.scrollTop += r.top - c.top - pad;
else if (r.bottom > c.bottom - pad) box.scrollTop += Math.min(r.bottom - c.bottom + pad, r.top - c.top - pad);
}
const setAttr = (el: HTMLElement | undefined, name: string, on: boolean) => {
if (el && el.hasAttribute(name) !== on) on ? el.setAttribute(name, "") : el.removeAttribute(name);
};
export function Panes() {
store.syncTrail();
const trail = store.trail;
const strip = useRef<HTMLDivElement>(null);
const followed = useRef("");
/**
* Mark how far each pane is covered by the next. Any overlap gives the upper pane a shadow edge
* (data-over); once too little of the pane is left to read its own heading, it shows as a spine
* with its title (data-covered).
*/
const measure = () => {
const el = strip.current;
if (!el) return;
const panes = Array.from(el.children) as HTMLElement[];
if (!panes.length) return;
const w = panes[0].offsetWidth;
const lefts = panes.map((p) => p.getBoundingClientRect().left);
for (let i = 0; i < panes.length; i++) {
const visible = i + 1 < panes.length ? lefts[i + 1] - lefts[i] : w;
setAttr(panes[i], "data-covered", visible < w * 0.4);
setAttr(panes[i + 1], "data-over", visible < w - 1);
}
};
/**
* Keep the focus in view. Vertically, the pane holding the focus scrolls to its focused row,
* selection or link. Horizontally, the strip scrolls as little as it can so that pane is fully
* visible and, when there is room, so is the pane beside it: for a row whose pane is showing,
* that pane; otherwise the pane before.
*/
const follow = () => {
const el = strip.current;
if (!el) return;
const f = store.focus;
const at = store.paneAt;
const key = `${f.node}|${f.grain}|${f.range?.join()}|${JSON.stringify(store.aux)}|${at}|${store.trail.length}|${el.clientWidth}|${store.mode === "edit"}`;
if (key === followed.current) return;
followed.current = key;
const panes = Array.from(el.children) as HTMLElement[];
if (!panes.length) return;
const next = store.trail[at + 1];
const a0 = store.aux;
const showing = store.showingFocus() || (a0?.kind === "wiki" && a0.row.t === "sec" && next?.kind === "wiki" && next.sec === a0.row.id);
if (store.mode !== "edit") {
const pane = panes[at];
nearestY(pane?.querySelector(".sel, .wfocus, .node.focused > .row, .wrow.focused > .row, .backlinks li.focused, .target-row.focused, .wiki-head.focused, .pane-head.focused, .focused"));
}
const w = panes[0].offsetWidth;
const spine = (panes[0].querySelector(".spine") as HTMLElement | null)?.offsetWidth ?? 0;
const view = el.clientWidth;
const b = Math.min(panes.length - 1, showing ? at + 1 : at);
let a = b > 0 && (showing || f.grain === "node") ? b - 1 : b;
// Pane i starts at i·w. It is uncovered while scrollLeft ≤ i·(w − spine), and its right edge is in view while scrollLeft ≥ (i+1)·w − view.
const lo = (b + 1) * w - view;
if (lo > a * (w - spine)) a = b;
const hi = a * (w - spine);
const target = Math.max(0, Math.min(el.scrollWidth - view, Math.min(Math.max(el.scrollLeft, lo), hi)));
if (Math.abs(target - el.scrollLeft) > 1) el.scrollTo({ left: target, behavior: reducedMotion() ? "auto" : "smooth" });
};
useLayoutEffect(() => {
follow();
measure();
});
useEffect(() => {
const el = strip.current!;
let frame = 0;
const onScroll = () => {
if (!frame) frame = requestAnimationFrame(() => ((frame = 0), measure()));
};
const onResize = () => {
followed.current = "";
follow();
measure();
};
el.addEventListener("scroll", onScroll, { passive: true });
// The strip changes width with the window and when the history panel opens or closes.
const sizes = new ResizeObserver(onResize);
sizes.observe(el);
return () => {
cancelAnimationFrame(frame);
el.removeEventListener("scroll", onScroll);
sizes.disconnect();
};
}, []);
return (
<div class="strip" ref={strip}>
{trail.map((p, i) => {
const next = trail[i + 1];
const showing = p.kind === "node" && next?.kind === "node" && store.continues(i + 1) ? next.id : undefined;
return <Pane key={`${i}:${p.kind === "node" ? p.id : `${p.title}#${p.sec ?? ""}`}`} p={p} index={i} showing={showing} active={store.paneAt === i} aux={store.paneAt === i ? store.aux : null} />;
})}
</div>
);
}
+32
View File
@@ -0,0 +1,32 @@
/** The footer's usage figures: what is left of the plan (subscription only) and what this session used. */
import { useEffect, useReducer } from "preact/hooks";
import { onUsage, startUsage, usageNow, view } from "./usage";
export function Usage() {
const [, tick] = useReducer((x: number) => x + 1, 0);
useEffect(() => {
const off = onUsage(() => tick(0));
const stop = startUsage();
return () => {
off();
stop();
};
}, []);
const v = view(usageNow());
if (!v) return null;
return (
<span class="usage">
{v.plan && (
<span class={`usage-plan${v.plan.attn ? " attn" : ""}${v.plan.limited ? " limited" : ""}`} title={v.plan.title}>
{v.plan.text}
</span>
)}
{v.session && (
<span class="usage-session" title={v.session.title} data-calls={v.session.calls}>
{v.session.text}
</span>
)}
</span>
);
}
+194
View File
@@ -0,0 +1,194 @@
/**
* A Wikipedia article shown as a tree, so the keys that move through nodes move through it: the
* lead is its text, its sections are rows (in a pane a section opens as the next pane; on the
* column's article page it opens in place), its links are Tab stops, and a disambiguation page
* lists its senses as rows. It is never stored in the library: it comes from /api/wiki/article,
* one request per article, cached by the server.
*
* Article panes look different on purpose (sans-serif, a tinted ground, a W at the head) so it is
* always clear which text is Wikipedia's and which is the reader's, and every view of article
* text ends with its attribution.
*/
import { useLayoutEffect, useRef } from "preact/hooks";
import { clip } from "../core/text";
import { Attribution, Backlinks } from "./Links";
import { sameAux, store, type WRow } from "./store";
import { article, cleanHtml, known, sectionsUnder, sensesOf, summary, type Article } from "./wiki";
/**
* Article HTML, cleaned twice (server and here) and put into the page. The focused link, when Tab
* has picked one, is marked here rather than in the HTML, which never changes once set.
*/
function WikiText({ html, link }: { html: string; link?: number }) {
const ref = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
el.querySelectorAll("a.wfocus").forEach((a) => a.classList.remove("wfocus"));
if (link === undefined) return;
const a = el.querySelectorAll("a[data-wiki]")[link];
if (a) {
a.classList.add("wfocus");
(a as HTMLElement).scrollIntoView?.({ block: "nearest" });
}
});
return <div class="wiki-text" ref={ref} dangerouslySetInnerHTML={{ __html: cleanHtml(html) }} />;
}
/** The W that marks Wikipedia's text, and the title. */
function Head({ title, sub, focused }: { title: string; sub?: string; focused: boolean }) {
return (
<header class={`wiki-head${focused ? " focused" : ""}`}>
<div class="wiki-brand">
<span class="wmark">W</span> Wikipedia
</div>
<h2>
{title}
{sub && <span class="wsub"> › {sub}</span>}
</h2>
</header>
);
}
function Problem({ message }: { message: string }) {
return <p class="wiki-problem">{message}</p>;
}
/** One article view. `host` says which (see Aux in store.ts); a pane passes its index. */
export function WikiView({ host }: { host: string }) {
const h = store.wikiHost(host);
if (!h) return null;
const a = store.aux;
const at = (row: WRow) => !!a && a.kind === "wiki" && a.host === host && sameAux({ ...a, link: undefined }, { kind: "wiki", host, row });
const linkAt = (row: WRow) => (at(row) && a?.kind === "wiki" ? a.link : undefined);
const embedded = h.embedded;
// Under a node, folded: its summary only, until l unfolds the article.
if (embedded && !store.expanded.has(embedded)) {
const sum = summary(h.title, h.lang);
return (
<section class={`wiki embedded folded${at({ t: "head" }) ? " focused" : ""}`} data-host={host}>
<Head title={sum.state === "ready" ? sum.value.title : h.title} focused={at({ t: "head" })} />
{sum.state === "loading" && <p class="wiki-wait">Loading the summary…</p>}
{sum.state === "failed" && <Problem message={sum.message} />}
{sum.state === "ready" && (
<>
{sum.value.description && <p class="wiki-desc">{sum.value.description}</p>}
<p class="wiki-summary">{sum.value.extract}</p>
<p class="wiki-more">l opens the article here · L opens it in a pane of its own · W on Wikipedia</p>
<Attribution a={sum.value.attribution} />
</>
)}
</section>
);
}
const art = article(h.title, h.lang);
if (art.state !== "ready") {
// While the article loads, a summary already at hand is shown at once.
const have = known(h.title, h.lang).summary;
return (
<section class={`wiki${embedded ? " embedded" : ""}`} data-host={host}>
<Head title={have?.title ?? h.title} focused={at({ t: "head" })} />
{have && <p class="wiki-summary">{have.extract}</p>}
{art.state === "loading" ? <p class="wiki-wait">Loading the article from Wikipedia…</p> : <Problem message={art.message} />}
{have && <Attribution a={have.attribution} />}
<Mentions title={h.title} lang={h.lang} show={!!h.mentions} at={at} />
</section>
);
}
const v = art.value;
const sec = h.sec ? v.sections.find((x) => x.id === h.sec) : undefined;
const showing = (id: number) => {
const i = host.startsWith("p") ? +host.slice(1) : store.paneAt;
const next = store.trail[i + 1];
return !!store.panes && next?.kind === "wiki" && next.title === h.title && next.sec === id;
};
return (
<section class={`wiki${embedded ? " embedded" : ""}`} data-host={host}>
<Head title={v.title} sub={sec?.heading} focused={at({ t: "head" })} />
{art.stale && <p class="wiki-wait">Wikipedia could not be reached; this is the copy kept from before.</p>}
<WikiText html={sec ? sec.html : v.lead} link={linkAt({ t: "head" })} />
{v.disambiguation && !sec && <Senses title={v.title} lang={h.lang} at={at} />}
<Rows article={v} parent={h.sec} nested={!!h.nested} at={at} linkAt={linkAt} showing={showing} />
<Mentions title={v.title} lang={h.lang} show={!!h.mentions} at={at} />
<Attribution a={v.attribution} />
</section>
);
}
function Rows(props: { article: Article; parent: number; nested: boolean; at: (r: WRow) => boolean; linkAt: (r: WRow) => number | undefined; showing: (id: number) => boolean }) {
const { article: v, parent, nested, at, linkAt, showing } = props;
const kids = sectionsUnder(v, parent);
if (!kids.length) return null;
return (
<ul class={`wrows${parent ? " nested" : ""}`}>
{kids.map((x) => {
const row: WRow = { t: "sec", id: x.id };
const open = nested && store.colOpen.has(x.id);
const leaf = !sectionsUnder(v, x.id).length;
return (
<li key={x.id} class={`wrow${at(row) ? " focused" : ""}${open ? " open" : ""}${showing(x.id) ? " showing" : ""}`}>
<div class="row" data-wrow={x.id}>
<span class="mark">{open ? "▾" : leaf && !x.html ? "·" : "▸"}</span>
<span class="title">{x.heading}</span>
{x.number && <span class="wnum">{x.number}</span>}
</div>
{open && (
<div class="content">
<WikiText html={x.html} link={linkAt(row)} />
<Rows {...props} parent={x.id} />
</div>
)}
</li>
);
})}
</ul>
);
}
function Senses({ title, lang, at }: { title: string; lang: string; at: (r: WRow) => boolean }) {
const ss = sensesOf(title, lang);
if (ss.state === "loading") return <p class="wiki-wait">Loading its senses…</p>;
if (ss.state === "failed") return <Problem message={ss.message} />;
return (
<section class="senses">
<h3>“{title}” may refer to</h3>
<ul class="wrows">
{ss.value.map((x, i) => (
<li key={x.title} class={`wrow sense${at({ t: "sense", i }) ? " focused" : ""}`}>
<div class="row" data-sense={x.title}>
<span class="mark">→</span>
<span class="title">{x.title}</span>
{x.description && <span class="wdesc">{clip(x.description, 70)}</span>}
</div>
</li>
))}
</ul>
</section>
);
}
/** "Mentioned in": the library's nodes that link to this article, which is what makes an article a hub between documents. */
function Mentions({ title, lang, show, at }: { title: string; lang: string; show: boolean; at: (r: WRow) => boolean }) {
if (!show) return null;
return <Backlinks ids={store.mentionsOf(lang, title)} title="Mentioned in" focusedAt={(i) => at({ t: "back", i })} />;
}
/** The column's article page: the article on its own, h or Back returns to where it was opened. */
export function WikiPage() {
return (
<article class="wiki-page">
<WikiView host="col" />
<p class="wiki-back">h at the top, or Back, returns to “{clip(backLabel(), 40)}”.</p>
</article>
);
}
function backLabel(): string {
const c = store.colWiki;
if (!c) return "";
if (c.stack.length) return c.stack[c.stack.length - 1].title;
const n = store.snap.nodes[c.back.focus.node];
return n ? n.title || "the text" : "the text";
}
+54
View File
@@ -0,0 +1,54 @@
/** A key-value store on IndexedDB: where the local replica lives between sessions. */
let dbp: Promise<IDBDatabase> | null = null;
function db(): Promise<IDBDatabase> {
return (dbp ??= new Promise((resolve, reject) => {
// The project's former name: kept, so replicas already stored in a browser are found.
const req = indexedDB.open("infinite-expand", 1);
req.onupgradeneeded = () => req.result.createObjectStore("kv");
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
}));
}
export async function idbGet<T>(key: string): Promise<T | undefined> {
try {
const d = await db();
return await new Promise((resolve, reject) => {
const req = d.transaction("kv").objectStore("kv").get(key);
req.onsuccess = () => resolve(req.result as T | undefined);
req.onerror = () => reject(req.error);
});
} catch {
return undefined; // private windows and blocked storage: run from the server copy instead
}
}
/** Every stored key. */
export async function idbKeys(): Promise<string[]> {
try {
const d = await db();
return await new Promise((resolve, reject) => {
const req = d.transaction("kv").objectStore("kv").getAllKeys();
req.onsuccess = () => resolve(req.result.map(String));
req.onerror = () => reject(req.error);
});
} catch {
return [];
}
}
export async function idbSet(key: string, value: unknown): Promise<void> {
try {
const d = await db();
await new Promise<void>((resolve, reject) => {
const tx = d.transaction("kv", "readwrite");
tx.objectStore("kv").put(value, key);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
} catch {
/* see idbGet */
}
}
+550
View File
@@ -0,0 +1,550 @@
/** The keymap. Modal, in the manner of vim: focus is a (node, grain) pair and most keys are one stroke. */
import { store } from "./store";
export const HELP: [string, [string, string][]][] = [
[
"Move",
[
["j k", "next / previous (section, sentence or word, by grain)"],
["l", "open, or step into the first child"],
["h", "close, or step out to the parent"],
["i", "narrow the grain: node → sentence → word"],
["Esc", "widen the grain; leave a note; close a panel; stop the editor while it works"],
["Tab", "jump between spans that carry a note or a link; in an article, between its links"],
["/", "jump to a section by name, in any document"],
["z", "hoist: make this node the whole page (again, or h or Esc at its top, to step out)"],
["v", "view: one column ↔ panes side by side (in panes, j k move among siblings)"],
["q", "in panes: close the panes right of the focus (with none, the focused one); moving left never closes anything"],
],
],
[
"Links",
[
["", "W marks a Wikipedia link, § another note in the library, ↗ a web page; a dotted underline is a note, both together a note that also links"],
["Enter", "on a link: open it (panes: the next pane; column: a preview, Enter again opens it)"],
["w", "on a selection: link it (library, Wikipedia or an address); on a link: retarget it; on a node: give the node a target"],
["L", "on a node: open its own target"],
["W", "open the focused article on wikipedia.org, in a new tab"],
["D", "on a link: remove it (u undoes)"],
["y n", "on a suggested link (a faint dashed underline; Tab reaches it): link it / decline it (a declined phrase is not suggested again in that node)"],
["S", "review the suggested links of this document one by one: y link · n decline · s skip · Y link all the rest · Esc stop"],
["1–5", "the node's Related list (sections of other documents close in meaning, numbered under its text): with words selected, link them to that one; on the node, go there"],
["l h j k", "in an article: sections are rows, as in a node; l opens one, h goes back"],
],
],
[
"Expand",
[
["e", "go deeper: open → open children → generate"],
["Enter", "on a section: toggle. On a selection: open its note, or step into it"],
["H L", "shrink / grow the selection by one unit"],
["d y x c", "on a selection: define · why · example · challenge"],
[":", "on a selection: ask your own question about it"],
["o O", "open everything below / collapse everything"],
],
],
[
"Edit",
[
["c", "edit the body (Esc saves). In it, [[ links a phrase: library titles first, then Wikipedia; a bare [[term]] left in the text is looked up when saved"],
["r", "rename"],
["a A", "add a section inside / after (on the library: a document)"],
["D", "delete (no confirmation; u undoes)"],
["J K", "move down / up among siblings"],
["> <", "indent / outdent (a document's sections can be moved into another this way, or over HTTP)"],
["p", "pin or unpin: pinned nodes are never rewritten by the model"],
["f", "on a note: cycle its form (inline · margin · inset)"],
[":", "on a node: tell the editor agent what to change"],
["u U", "undo / redo: the last edit made in this tab, in whichever document it was"],
],
],
[
"Keep consistent",
[
["R", "reconcile: have the model bring a stale node back in line"],
["b", "bless: accept a stale node as it stands"],
["g", "history: commits, branches, conflicts"],
["?", "this help"],
],
],
[
"Documents (m)",
[
["", "every document is a section of one library: the library is the first page (h or Esc steps out to it), and a document opens in place"],
["m", "the documents menu (or click the title in the top bar). Type to filter; ↑ ↓ select; Enter opens"],
["Esc", "in the filter: go to the list, where single keys act. In the list: close"],
["j k Enter", "in the list: select / open"],
["n", "new blank document (asks for a title)"],
["r", "rename the selected document"],
["s", "duplicate it: save as a copy under a new title, and open the copy"],
["D", "delete it (asks first; u brings it back)"],
["x", "export it: save to a .md file"],
["i", "import a .md file as a new document (or drop the file on the menu)"],
["/", "back to the filter"],
],
],
[
"In history (g)",
[
["j k", "select"],
["Enter", "commit: view it (read-only). Branch: switch. Open conflict: ask the model"],
["r", "revert to the selected commit, as a new commit"],
["n", "new branch from the selected commit"],
["m", "merge the selected branch into this one"],
["1 2 3", "conflict: take side A / side B / the mechanical merge"],
["x", "conflict: reopen a resolution"],
["f", "show only what touched the current document, or everything"],
["v", "verify: check every commit reproduces its recorded hash"],
["", "each commit names the documents it touched; r reverts only the current document, the rest of the library stays as it is"],
],
],
[
"Commands (:)",
[
["/branch name", "create and switch to a branch"],
["/switch name", "switch branch"],
["/merge name", "merge a branch into this one"],
["/resolve", "have the model resolve open conflicts"],
["/auto on|off", "reconcile automatically after edits"],
["/speculate on|off", "start writing the focused sentence's expansion early"],
["/view mode", "page layout: auto, column or panes; auto shows panes on windows 1600 px wide or more"],
["/user name", "set the name on your commits"],
["/new title", "new blank document"],
["/open name", "open a document by title or id"],
["/rename title", "rename this document"],
["/duplicate title", "save this document as a copy, and open the copy"],
["/export", "save this document to a .md file"],
["/import", "open a .md file as a new document"],
["/recover", "save edits this browser made before the library existed, and never sent, as .md files"],
["/link target", "link the selection (or the node): w:Title, /document/Section, an address, or a Wikipedia title"],
["/unlink", "remove the link on the selection, or the node's own target"],
["/autolink suggest|on|off", "after an edit: suggest what was found (suggest, the default), also link the surest at once (on, u undoes), or look for nothing (off)"],
["/linkdoc", "look for links in the whole document, in the background; progress in the status line"],
["/linkall", "look for links in the whole library, in the background"],
["/linkcancel", "stop looking (what was found is kept)"],
["/research question", "the editor searches the web, reads a few pages and writes what it finds into the focused node, each claim linked to its page (within the server's limits, by default 5 searches and 5 pages read per request; Esc stops)"],
["", "an ordinary request to the editor may use the web too when it says so: \"look up…\", \"find sources for…\", \"search the web…\", \"cite sources\", \"fact-check\""],
],
],
];
const isTyping = (e: KeyboardEvent) => {
const t = e.target as HTMLElement | null;
return !!t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.isContentEditable);
};
interface KeyHooks {
openCommand(prefill?: string): void;
verify(): void;
}
export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
if (!store.ready || isTyping(e) || e.metaKey || e.ctrlKey || e.altKey) return;
const k = e.key;
const done = () => {
e.preventDefault();
store.t0 = { what: k, at: e.timeStamp };
};
if (store.mode === "help") {
if (k === "Escape" || k === "?" || k === "q") {
store.setMode("normal");
e.preventDefault();
}
return;
}
if (store.mode === "history") {
const items = store.panel();
const item = items[store.historyIndex];
const select = (i: number) => {
store.historyIndex = Math.max(0, Math.min(items.length - 1, i));
const it = items[store.historyIndex];
if (store.preview && it?.type === "commit") store.setPreview(it.commit);
store.emit();
};
switch (k) {
case "Escape":
if (store.preview) store.setPreview(null);
else store.closeHistory();
break;
case "g":
case "q":
store.closeHistory();
break;
case "j":
case "ArrowDown":
select(store.historyIndex + 1);
break;
case "k":
case "ArrowUp":
select(store.historyIndex - 1);
break;
case "Enter":
if (item?.type === "commit") store.setPreview(store.preview?.commit.id === item.commit.id ? null : item.commit);
else if (item?.type === "branch") store.switchBranch(item.branch);
else if (item?.type === "conflict" && item.conflict.status === "open") store.resolveAll();
break;
case "r":
if (item?.type === "commit") store.revert(item.commit);
break;
case "n":
if (item?.type === "commit") {
store.branchFrom = item.commit;
hooks.openCommand("/branch ");
}
break;
case "m":
if (item?.type === "branch") store.mergeFrom(item.branch);
break;
case "1":
case "2":
case "3":
if (item?.type === "conflict") store.settle(item.conflict.id, (["a", "b", "merged"] as const)[+k - 1]);
break;
case "x":
if (item?.type === "conflict") store.reopen(item.conflict.id);
break;
case "v":
hooks.verify();
break;
case "f":
store.toggleHistoryFilter();
break;
case ":":
hooks.openCommand();
break;
case "?":
store.setMode("help");
break;
default:
return;
}
return done();
}
if (store.mode === "docs") {
// The filter and title boxes take their own keys (Menu.tsx); these are the list's.
const m = store.menu;
const d = store.menuSelected();
if (m.focus === "filter" && !m.prompt && !m.confirm) {
// The filter box is not focused (a key typed before it took focus, or after a click
// elsewhere in the panel): keys still mean what they would there.
if (k === "Escape" || k === "Tab") m.focus = "list";
else if (k === "Enter") return d && (e.preventDefault(), store.openDoc(d.node));
else if (k === "ArrowDown" || k === "ArrowUp") return e.preventDefault(), store.menuMove(k === "ArrowDown" ? 1 : -1);
else if (k.length === 1) return e.preventDefault(), store.menuFilter(m.filter + k);
else return;
store.emit();
return done();
}
if (m.confirm) {
if (k === "y") store.deleteDocument(m.confirm);
else if (k === "n" || k === "Escape" || k === "q") (m.confirm = null), store.emit();
else return;
return done();
}
switch (k) {
case "Escape":
case "q":
case "m":
store.closeMenu();
break;
case "j":
case "ArrowDown":
store.menuMove(1);
break;
case "k":
case "ArrowUp":
store.menuMove(-1);
break;
case "Enter":
if (d) store.openDoc(d.node);
break;
case "/":
m.focus = "filter";
store.emit();
break;
case "n":
store.menuPrompt("new");
break;
case "r":
store.menuPrompt("rename");
break;
case "s":
store.menuPrompt("duplicate");
break;
case "D":
if (d) (m.confirm = d.node), store.emit();
break;
case "x":
if (d) store.exportDocument(d.node);
break;
case "i":
store.pickFile();
break;
case "?":
store.setMode("help");
break;
default:
return;
}
return done();
}
if (store.mode === "review") {
switch (k) {
case "y":
store.acceptSuggestion();
break;
case "n":
store.rejectSuggestion();
break;
case "s":
case "j":
case "Tab":
case " ":
store.reviewStep(e.shiftKey ? -1 : 1);
break;
case "k":
store.reviewStep(-1);
break;
case "Y":
store.reviewAcceptAll();
break;
case "Escape":
case "q":
case "S":
store.endReview("Review stopped.");
break;
case "u":
store.undoLast();
break;
default:
return;
}
return done();
}
if (store.mode !== "normal") return;
// Esc stops the editor while it works, and puts away the panel of a finished research run.
if (k === "Escape" && store.agentRun) {
store.escAgent();
return done();
}
if (store.panes) store.syncTrail();
// On a Wikipedia view, a target or a "Linked from" row, the keys mean what they would on rows.
if (!store.aux && ((store.panes && store.trail[store.paneAt]?.kind === "wiki") || (!store.panes && store.colWiki))) {
store.aux = { kind: "wiki", host: store.panes ? `p${store.paneAt}` : "col", row: { t: "head" } };
}
if (store.aux) {
// An Enter after a Tab that is waiting for its article to arrive waits with it.
if (store.holdKey(k)) return done();
if (auxKey(k, e.shiftKey) || commonKey(k, hooks)) return done();
return;
}
if (commonKey(k, hooks)) return done();
const grain = store.focus.grain;
const selecting = grain !== "node";
switch (k) {
case "j":
case "ArrowDown":
store.move(1);
break;
case "k":
case "ArrowUp":
store.move(-1);
break;
case "l":
case "ArrowRight":
store.into();
break;
case "h":
case "ArrowLeft":
store.out();
break;
case "i":
store.descend();
break;
case "Escape":
store.ascend();
break;
case "Tab":
store.nextAnchor(e.shiftKey ? -1 : 1);
break;
case "e":
store.expand();
break;
case "Enter":
case " ":
if (selecting) store.enterOrExpand();
else if (store.snap.nodes[store.focus.node]?.kind === "note" && store.snap.nodes[store.focus.node].ref) store.followOwn();
else store.toggle();
break;
case "w":
store.openPicker();
break;
case "L":
if (selecting) store.extend(1);
else store.followOwn();
break;
case "H":
store.extend(-1);
break;
case "J":
if (selecting) store.extend(1);
else store.shift(1);
break;
case "K":
if (selecting) store.extend(-1);
else store.shift(-1);
break;
case "d":
if (selecting) store.expand("define");
break;
case "y":
if (store.focusedSuggestion()) store.acceptSuggestion();
else if (selecting) store.expand("why");
break;
case "n":
if (store.focusedSuggestion()) store.rejectSuggestion();
else return;
break;
case "S":
store.startReview();
break;
case "1":
case "2":
case "3":
case "4":
case "5":
store.relatedKey(+k);
break;
case "x":
if (selecting) store.expand("example");
break;
case "c":
if (selecting) store.expand("challenge");
else store.startEdit("body");
break;
case "r":
if (!selecting) store.startEdit("title");
break;
case "a":
if (!selecting) store.add("child");
break;
case "A":
if (!selecting) store.add("after");
break;
case "D":
store.remove();
break;
case ">":
store.indent(1);
break;
case "<":
store.indent(-1);
break;
case "p":
store.togglePin();
break;
case "f":
store.cycleForm();
break;
case "R":
store.reconcileFocus();
break;
case "b":
store.bless();
break;
case "o":
store.expandAll();
break;
case "O":
store.collapseAll();
break;
case "z":
store.setHoist(store.focus.node);
break;
default:
return;
}
done();
}
/** Keys that mean the same on a node and on an aux row. Returns whether the key was taken. */
function commonKey(k: string, hooks: KeyHooks): boolean {
switch (k) {
case "W":
store.openOnWikipedia();
return true;
case "q":
if (store.panes) store.closePane();
return true;
case "v":
store.cycleView();
return true;
case "u":
store.undoLast();
return true;
case "U":
store.undoLast(true);
return true;
case "g":
store.openHistory();
return true;
case "m":
store.openMenu();
return true;
case "/":
store.setMode("jump");
return true;
case "?":
store.setMode("help");
return true;
case ":":
hooks.openCommand();
return true;
default:
return false;
}
}
/** Keys on an aux row. Returns whether the key was taken; keys that only make sense on a node are ignored there. */
function auxKey(k: string, shift: boolean): boolean {
switch (k) {
case "j":
case "ArrowDown":
store.move(1);
return true;
case "k":
case "ArrowUp":
store.move(-1);
return true;
case "l":
case "ArrowRight":
case "Enter":
case " ":
store.auxActivate();
return true;
case "h":
case "ArrowLeft":
case "Escape":
store.auxLeave();
return true;
case "Tab":
store.auxTab(shift ? -1 : 1);
return true;
case "L": {
// Under a node, its article opens in a pane of its own.
const a = store.aux;
const id = a?.kind === "wiki" && a.host.startsWith("n") ? a.host.slice(1) : a?.kind === "target" ? a.of : null;
const r = id ? store.snap.nodes[id as keyof typeof store.snap.nodes]?.ref : undefined;
if (r) store.follow(r);
return true;
}
default:
return false;
}
}
+364
View File
@@ -0,0 +1,364 @@
/**
* Link discovery as the browser sees it: asking the server to scan a node (server/links) after it
* is written, applying the `auto` tier at once as its own commit (so `u` takes it back), keeping
* the rest as suggestions drawn in the text, accepting and declining them, the Related list, the
* background job's progress, and the "nearby" list a model is given before it writes.
*
* Nothing here runs on a keystroke: scans are queued after a write is saved and run one at a time.
*/
import type { JobState } from "../../server/links/jobs";
import type { Related as RelatedRow, Suggestion as Sugg } from "../../server/links/scan";
import { applyLinks, nodeRef } from "../core/links";
import type { Mark } from "../core/marks";
import { ancestors, docOf, notesOf, type Doc, type NodeId, type Snap } from "../core/model";
import { describeTarget, sameTarget } from "../core/ref";
import { clip, overlaps, type Range } from "../core/text";
import type { Nearby } from "../llm/prompts";
export type { JobState, Sugg };
export type AutoMode = "on" | "suggest" | "off";
/** What the linker needs from the page's store. */
interface Host {
doc(): Doc;
user(): string;
mode(): AutoMode;
say(text: string): void;
emit(...ids: NodeId[]): void;
/** Whether a node is drawn now (its Related list is fetched only then). */
rendered(id: NodeId): boolean;
}
/** Who wrote the text being scanned: a person's marks always resolve; a model's follow the mode. */
type Origin = "human" | "model" | "import";
interface Task {
node: NodeId;
origin: Origin;
forced: Mark[];
}
/** Run when the page has nothing better to do (soon, regardless, after a second). */
const idle = (fn: () => void) => (typeof requestIdleCallback === "function" ? requestIdleCallback(fn, { timeout: 1000 }) : setTimeout(fn, 50));
const post = (path: string, body: unknown, signal?: AbortSignal) =>
fetch(`/api/links/${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal });
/** A suggestion as it applies to a node's text now: its words where they are, or null if they are gone or taken. */
function place(snap: Snap, s: Sugg): Sugg | null {
const n = snap.nodes[s.node];
if (!n || n.nolink?.includes(s.key)) return null;
let range = s.range;
if (n.body.slice(range[0], range[1]) !== s.quote) {
const at = n.body.indexOf(s.quote);
if (at < 0) return null;
range = [at, at + s.quote.length];
}
for (const c of notesOf(snap, s.node)) {
const note = snap.nodes[c];
for (const a of note.anchors) {
if (!overlaps([a.start, a.end], range)) continue;
// A plain note on exactly these words may take the target; anything else in the way blocks it.
if (note.ref || a.start !== range[0] || a.end !== range[1]) return null;
}
if (note.ref && sameTarget(note.ref, s.target)) return null;
}
return range === s.range ? s : { ...s, range };
}
export class Linker {
/** Pending suggestions by node, as the scanner gave them (placed again whenever read). */
private byNode = new Map<NodeId, Sugg[]>();
private related = new Map<NodeId, { body: string; rows: RelatedRow[] | null; done: boolean }>();
private queue: Task[] = [];
private running = false;
job: JobState | null = null;
/** Documents whose pending list has been fetched since the page loaded. */
private fetched = new Set<NodeId>();
/** Scans in flight or queued: the page waits on this in tests (`idle`). */
busy = 0;
constructor(private host: Host) {}
// ---- reading ----
/** The suggestions on a node, placed in its current text, in text order. */
forNode(id: NodeId, snap: Snap): Sugg[] {
const list = this.byNode.get(id);
if (!list?.length) return [];
const out: Sugg[] = [];
for (const s of list) {
const p = place(snap, s);
if (p && !out.some((o) => overlaps(o.range, p.range))) out.push(p);
}
return out.sort((a, b) => a.range[0] - b.range[0]);
}
/** The suggestion on exactly these words, if any. */
at(id: NodeId, range: Range | undefined, snap: Snap): Sugg | undefined {
if (!range) return;
return this.forNode(id, snap).find((s) => s.range[0] === range[0] && s.range[1] === range[1]);
}
/** Every pending suggestion under some nodes, in reading order. */
under(ids: NodeId[], snap: Snap): Sugg[] {
return ids.flatMap((id) => this.forNode(id, snap));
}
// ---- scanning ----
/** Queue a scan of a node that was just written. Off the keystroke: it runs after the write is saved. */
scan(node: NodeId, origin: Origin, forced: Mark[] = []) {
if (this.host.mode() === "off" && !(origin === "human" && forced.length)) return;
const had = this.queue.find((t) => t.node === node);
if (had) {
had.forced = forced.length ? forced : had.forced;
return;
}
this.queue.push({ node, origin, forced });
this.busy++;
void this.pump();
}
private async pump() {
if (this.running) return;
this.running = true;
try {
for (let t; (t = this.queue.shift()); ) {
try {
await this.run(t);
} catch (e) {
if (e instanceof TypeError) this.host.say("Could not reach the server to look for links.");
else this.host.say(`Looking for links failed: ${e instanceof Error ? e.message : e}`);
} finally {
this.busy--;
}
}
} finally {
this.running = false;
this.host.emit();
}
}
/** The request a scan sends: the node's own text and context, from this replica, which may be ahead of the server's. */
private request(snap: Snap, id: NodeId, forced: Mark[]) {
const n = snap.nodes[id];
const d = docOf(snap, id);
return {
node: id,
text: n.body,
title: n.title,
doc: d,
docTitle: d ? snap.nodes[d].title : "",
ancestors: ancestors(snap, id),
occupied: notesOf(snap, id).flatMap((c) => snap.nodes[c].anchors.map((a) => [a.start, a.end, !!snap.nodes[c].ref])),
rejected: n.nolink ?? [],
forced,
};
}
private async run(t: Task) {
const doc = this.host.doc();
const snap = doc.snap();
if (!snap.nodes[t.node]) return;
const res = await post("scan", this.request(snap, t.node, t.forced));
if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error ?? `the server answered ${res.status}`);
const r = (await res.json()) as { suggestions: Sugg[]; unresolved: string[]; degraded: string[] };
this.take(doc, t.node, r.suggestions, t.origin, r.unresolved, r.degraded);
}
/**
* What a scan found, applied as the mode says: with `on`, the auto tier (and verified marks) at
* once, as one commit by "linker"; everything else waits, drawn in the text.
*/
private take(doc: Doc, node: NodeId, list: Sugg[], origin: Origin, unresolved: string[], degraded: string[]) {
const mode = this.host.mode();
const snap = doc.snap();
const marked = (s: Sugg) => s.kind === "forced";
const now = list.filter((s) => (marked(s) && (origin === "human" || mode === "on")) || (s.tier === "auto" && mode === "on"));
const later = list.filter((s) => !now.includes(s) && !(marked(s) && mode === "off"));
const placed = this.applyAuto(now, doc);
this.byNode.set(node, later);
if (unresolved.length && origin === "human") this.host.say(`Found nothing to link for ${unresolved.map((u) => `“${clip(u, 40)}”`).join(", ")}; the brackets were taken out.`);
else if (!placed.length && later.length && origin !== "import") this.host.say(`${later.length} link suggestion${later.length > 1 ? "s" : ""}: Tab reaches ${later.length > 1 ? "them" : "it"}, y links, n declines${degraded.length ? ` (${degraded[0]})` : ""}`);
this.host.emit(node);
}
/** Apply suggestions without asking, as one commit by "linker" (an ordinary commit: `u` takes it back). */
applyAuto(list: Sugg[], doc = this.host.doc()): Sugg[] {
const snap = doc.snap();
const placed = list.map((s) => place(snap, s)).filter((s): s is Sugg => !!s);
if (!placed.length) return [];
const r = applyLinks(doc, placed.map((s) => ({ node: s.node, range: s.range, target: s.target })), {
author: "linker",
actor: "llm",
tag: "autolink",
message: `Link ${placed.length === 1 ? `“${clip(placed[0].quote, 40)}”` : `${placed.length} phrases`} automatically`,
});
if (r.created.length + r.merged.length) {
this.host.say(`Linked ${placed.map((s) => `“${clip(s.quote, 30)}” → ${clip(s.title, 40)}`).slice(0, 3).join(", ")}${placed.length > 3 ? ` and ${placed.length - 3} more` : ""} · u undoes`);
}
this.forget(placed);
return placed;
}
/** The pending list of a document from the server (what a background job found), once per page load or on demand. */
async loadDoc(docId: NodeId, force = false): Promise<Sugg[]> {
if (!force && this.fetched.has(docId)) return [];
this.fetched.add(docId);
try {
const res = await fetch(`/api/links/pending?doc=${encodeURIComponent(docId)}`);
if (!res.ok) return [];
const r = (await res.json()) as { suggestions: Sugg[] };
const by = new Map<NodeId, Sugg[]>();
for (const s of r.suggestions) by.set(s.node, [...(by.get(s.node) ?? []), s]);
for (const [id, list] of by) this.byNode.set(id, list);
// Nothing to draw, nothing to redraw: a document opened is not repainted for an empty list.
if (by.size) this.host.emit(...by.keys());
return r.suggestions;
} catch {
return [];
}
}
// ---- the writer's decisions ----
/** y: link these suggestions, as the writer's own commit. */
accept(list: Sugg[]): number {
const doc = this.host.doc();
const snap = doc.snap();
const placed = list.map((s) => place(snap, s)).filter((s): s is Sugg => !!s);
if (!placed.length) return 0;
const r = applyLinks(doc, placed.map((s) => ({ node: s.node, range: s.range, target: s.target })), {
author: this.host.user(),
actor: "human",
message: placed.length === 1 ? `Link “${clip(placed[0].quote, 40)}” to ${clip(describeTarget(placed[0].target), 50)}` : `Link ${placed.length} suggested phrases`,
});
this.forget(placed);
return r.created.length + r.merged.length;
}
/** n: decline these, remembered in each node (so a later scan does not offer them again, here or on another replica). */
reject(list: Sugg[]): number {
const doc = this.host.doc();
const byNode = new Map<NodeId, Set<string>>();
for (const s of list) if (doc.snap().nodes[s.node]) byNode.set(s.node, (byNode.get(s.node) ?? new Set()).add(s.key));
if (!byNode.size) return 0;
const ops = [...byNode].map(([id, keys]) => ({ op: "update" as const, id, nolink: [...keys] }));
doc.as(this.host.user(), () => doc.apply(ops, list.length === 1 ? `Decline linking “${clip(list[0].quote, 40)}”` : `Decline ${list.length} link suggestions`, { tag: "nolink" }));
this.forget(list);
return list.length;
}
private forget(list: Sugg[]) {
const gone = new Set(list.map((s) => s.id));
for (const [id, l] of this.byNode) this.byNode.set(id, l.filter((s) => !gone.has(s.id) && !list.some((x) => x.node === s.node && x.key === s.key)));
this.host.emit(...new Set(list.map((s) => s.node)));
}
// ---- Related ----
/** The Related list of a node: fetched when first drawn and again when its text changes. Null while unknown. */
relatedOf(id: NodeId, snap: Snap): RelatedRow[] | null {
const n = snap.nodes[id];
if (!n) return null;
const cur = this.related.get(id);
if (cur && cur.body === n.body && cur.done) {
// Rows that are now linked from this node drop out.
const linked = new Set(notesOf(snap, id).map((c) => snap.nodes[c].ref).flatMap((r) => (r?.kind === "node" && r.id ? [r.id] : [])));
return cur.rows?.filter((r) => snap.nodes[r.node] && !linked.has(r.node)) ?? null;
}
if (!cur || cur.body !== n.body) this.related.set(id, { body: n.body, rows: cur?.rows ?? null, done: false });
// Fetched a few at a time, newest first, when the page is idle: opening everything must not
// send a request per node at once, nor redraw between the keystrokes that opened them.
this.relatedQueue = [id, ...this.relatedQueue.filter((x) => x !== id)].slice(0, 30);
idle(() => void this.pumpRelated());
return cur?.rows ?? null;
}
private relatedQueue: NodeId[] = [];
private relatedBusy = 0;
private async pumpRelated() {
while (this.relatedBusy < 2 && this.relatedQueue.length) {
const id = this.relatedQueue.shift()!;
const entry = this.related.get(id);
const snap = this.host.doc().snap();
if (!entry || !snap.nodes[id]) continue;
this.relatedBusy++;
const { node, text, title, doc, docTitle, ancestors: up } = this.request(snap, id, []);
void post("related", { node, text, title, doc, docTitle, ancestors: up })
.then(async (res) => {
const r = res.ok ? ((await res.json()) as { related: RelatedRow[] }) : { related: [] };
if (this.related.get(id)?.body === entry.body) {
entry.rows = r.related;
entry.done = true;
if (r.related.length) idle(() => this.host.emit(id));
}
})
.catch(() => (entry.done = true))
.finally(() => {
this.relatedBusy--;
void this.pumpRelated();
});
}
}
/** Turn a Related row into a link on words of the node (the writer's selection there). */
linkRelated(node: NodeId, range: Range, target: NodeId): boolean {
const doc = this.host.doc();
const snap = doc.snap();
if (!snap.nodes[target] || !snap.nodes[node]) return false;
const r = applyLinks(doc, [{ node, range, target: nodeRef(snap, target) }], { author: this.host.user(), actor: "human", message: `Link “${clip(snap.nodes[node].body.slice(range[0], range[1]), 40)}” to ${clip(snap.nodes[target].title, 50)}` });
return r.created.length + r.merged.length > 0;
}
// ---- background jobs ----
async startJob(scope: "doc" | "library", doc?: NodeId): Promise<JobState | string> {
const res = await post("jobs", { scope, doc });
const r = await res.json().catch(() => ({}));
if (!res.ok) return r.error ?? `the server answered ${res.status}`;
this.job = r.job;
return r.job;
}
async cancelJob(): Promise<boolean> {
const res = await fetch("/api/links/jobs", { method: "DELETE" });
const r = await res.json().catch(() => ({}));
if (r.job) this.job = r.job;
return !!r.cancelled;
}
// ---- for the model ----
/** The few library nodes near a node, for a model's prompt. Never waits long: a prompt is not held up for it. */
async nearby(node: NodeId, ms = 400): Promise<Nearby[]> {
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), ms);
try {
const snap = this.host.doc().snap();
if (!snap.nodes[node]) return [];
const { text, title, ancestors: up } = this.request(snap, node, []);
const res = await post("nearby?k=5", { node, text, title, ancestors: up }, ac.signal);
if (!res.ok) return [];
return ((await res.json()) as { nearby: Nearby[] }).nearby;
} catch {
return [];
} finally {
clearTimeout(timer);
}
}
/** What a scan finds for a node of some replica (the editor agent's fork), without recording it as pending. */
async peek(doc: Doc, node: NodeId): Promise<Sugg[] | null> {
const snap = doc.snap();
if (!snap.nodes[node]) return null;
try {
const res = await post("scan", { ...this.request(snap, node, []), save: false });
if (!res.ok) return null;
return ((await res.json()) as { suggestions: Sugg[] }).suggestions;
} catch {
return null;
}
}
}
+11
View File
@@ -0,0 +1,11 @@
import "@fontsource-variable/source-serif-4/opsz.css";
import "@fontsource-variable/source-serif-4/opsz-italic.css";
import "@fontsource-variable/source-sans-3/wght.css";
import "@fontsource/ibm-plex-mono/400.css";
import "./style.css";
import { render } from "preact";
import { App } from "./App";
import { store } from "./store";
render(<App />, document.getElementById("app")!);
void store.boot();
+80
View File
@@ -0,0 +1,80 @@
/** The model, as the browser sees it: the LLM seam (src/llm/types.ts) as fetches to the local server's /api/llm. */
import type { JsonReq, LLM, Req, Turn, TurnReq } from "../llm/types";
import type { WebStep } from "../llm/web";
import { failure } from "./session";
async function fail(res: Response): Promise<never> {
throw await failure(res);
}
export function remoteLLM(kind: LLM["kind"], model?: string): LLM {
const post = (path: string, payload: unknown, signal?: AbortSignal) =>
fetch(`/api/llm/${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload), signal });
return {
kind,
model,
async stream(req: Req, onText, signal) {
const res = await post("stream", req, signal);
if (!res.ok || !res.body) await fail(res);
const reader = res.body!.getReader();
const decoder = new TextDecoder();
let text = "";
let error: string | null = null;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
let chunk = decoder.decode(value, { stream: true });
if (error !== null) {
error += chunk;
continue;
}
// A failure after the stream has started arrives in-band, after a NUL.
const nul = chunk.indexOf("\u0000");
if (nul >= 0) {
error = chunk.slice(nul + 1);
chunk = chunk.slice(0, nul);
}
if (chunk) {
text += chunk;
onText(chunk);
}
}
if (error !== null) throw new Error(error || "generation failed");
return text;
},
async json<T>(req: JsonReq, signal?: AbortSignal) {
const res = await post("json", req, signal);
if (!res.ok) await fail(res);
return (await res.json()) as T;
},
async turn(req: TurnReq, signal?: AbortSignal, onWeb?: (step: WebStep) => void) {
if (!onWeb) {
const res = await post("turn", req, signal);
if (!res.ok) await fail(res);
return (await res.json()) as Turn;
}
// With research, the server sends each search and page read as a line as it happens, then the turn.
const res = await post("turn?steps=1", req, signal);
if (!res.ok || !res.body) await fail(res);
const reader = res.body!.getReader();
const decoder = new TextDecoder();
let buf = "";
for (;;) {
const { done, value } = await reader.read();
buf += decoder.decode(value, { stream: !done });
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line) continue;
const msg = JSON.parse(line) as { step?: WebStep; turn?: Turn; error?: string };
if (msg.step) onWeb(msg.step);
else if (msg.turn) return msg.turn;
else if (msg.error) throw new Error(msg.error);
}
if (done) break;
}
throw new Error("the server ended the turn without a reply");
},
};
}
+225
View File
@@ -0,0 +1,225 @@
/**
* The library in the browser: its branches as local replicas (kept in IndexedDB), the sync loop
* with the server, and the subscription to the server's change notices.
*/
import { VersionVector } from "loro-crdt";
import { Doc } from "../core/model";
import { Repo, decodeVV, encodeVV, mergeUpdate, vvIncludes, type MergeReport } from "../core/repo";
import { idbGet, idbSet } from "./idb";
type VV = Map<`${number}`, number>;
export interface SessionHooks {
/** A replica changed, locally or by sync. */
changed(doc: Doc): void;
/** A sync round ended; `ok` says whether the server answered. */
synced(name: string, ok: boolean, report: MergeReport | null): void;
/** The server's notice stream opened or failed. */
connection(up: boolean): void;
/** The server holds a different library than this page (its data directory was replaced). */
foreign(): void;
/** Any other notice from the server (a link job's progress). */
message?(msg: Record<string, unknown>): void;
}
export async function failure(res: Response): Promise<Error & { body?: Record<string, unknown> }> {
let message = `${res.status} ${res.statusText}`;
let body: Record<string, unknown> | undefined;
try {
body = await res.json();
message = String(body?.error ?? message);
} catch {
/* not JSON */
}
return Object.assign(new Error(message), { body });
}
export class Session {
repo!: Repo;
/** Set once the server turns out to hold another library: nothing more is sent to it. */
foreign = false;
private serverVV = new Map<string, VV>();
private syncing = new Set<string>();
private events: EventSource | null = null;
/** Branches the server listed that are not stored here yet. */
private missing: string[] = [];
constructor(
/** Stored replicas are keyed by the library's id: a replica of another library is never loaded into this one. */
readonly library: string,
private user: string,
private clientId: string,
private hooks: SessionHooks,
) {}
private key(k: string) {
return `lib:${this.library}:${k}`;
}
/**
* Open the replicas stored locally; only if main is not among them, wait for the server.
* Branches the server has and this browser does not arrive by sync afterwards.
*/
async load(serverBranches: string[], online: boolean) {
const names = new Set<string>([...((await idbGet<string[]>(this.key("branches"))) ?? []), ...serverBranches]);
const docs = new Map<string, Doc>();
for (const name of names) {
const local = await idbGet<Uint8Array>(this.key(`branch:${name}`));
if (local) docs.set(name, Doc.load(local, this.user));
}
const fetched = new Set<string>();
if (!docs.has("main") && online) {
const doc = await this.fetchBranch("main");
if (doc) {
docs.set("main", doc);
fetched.add("main");
}
}
if (!docs.has("main")) throw new Error("Could not open the library: the server is not reachable and nothing is stored in this browser.");
this.repo = new Repo(docs.get("main")!);
for (const [name, doc] of docs) {
this.repo.branches.set(name, doc);
this.watch(name, doc, fetched.has(name));
}
this.missing = [...names].filter((n) => !docs.has(n));
}
private async fetchBranch(name: string): Promise<Doc | null> {
const res = await fetch(`/api/branch/${encodeURIComponent(name)}`);
if (!res.ok) return null;
if (res.headers.get("x-library") !== this.library) {
this.lost();
return null;
}
const doc = Doc.load(new Uint8Array(await res.arrayBuffer()), this.user);
this.serverVV.set(name, decodeVV(res.headers.get("x-vv")!));
return doc;
}
/** Persist and sync a replica a moment after each change. `store`: it came from the server, so keep a copy now. */
watch(name: string, doc: Doc, store = false) {
let saveTimer: ReturnType<typeof setTimeout> | undefined;
let syncTimer: ReturnType<typeof setTimeout> | undefined;
doc.onChange(() => {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
void idbSet(this.key(`branch:${name}`), doc.snapshotBytes());
void idbSet(this.key("branches"), [...this.repo.branches.keys()]);
}, 60);
clearTimeout(syncTimer);
syncTimer = setTimeout(() => void this.sync(name), 60);
this.hooks.changed(doc);
});
if (store) void idbSet(this.key(`branch:${name}`), doc.snapshotBytes());
void idbSet(this.key("branches"), [...this.repo.branches.keys()]);
}
/** True when the server has everything these replicas have. */
synced(): boolean {
if (this.foreign) return true;
for (const [name, doc] of this.repo?.branches ?? []) {
const known = this.serverVV.get(name);
if (!known || !vvIncludes(known, doc.loro.version().toJSON())) return false;
}
return true;
}
/** On the way out, hand the server anything it has not seen. A beacon outlives the page, but cannot carry headers, so the library goes in the query. */
flush() {
if (this.foreign) return;
for (const [name, doc] of this.repo?.branches ?? []) {
const known = this.serverVV.get(name);
if (known && vvIncludes(known, doc.loro.version().toJSON())) continue;
const bytes = known ? doc.loro.export({ mode: "update", from: new VersionVector(known) }) : doc.snapshotBytes();
navigator.sendBeacon(`/api/sync/${encodeURIComponent(name)}?library=${encodeURIComponent(this.library)}`, new Blob([bytes as BlobPart], { type: "application/octet-stream" }));
}
}
/** A round for every branch, and fetch the ones only the server has. */
async syncAll() {
const names = [...this.repo.branches.keys(), ...this.missing.splice(0)];
await Promise.all(names.map((n) => this.sync(n)));
}
/** One round with the server: push what it lacks, pull what we lack, then look for semantic conflicts. */
async sync(name: string) {
if (this.foreign || this.syncing.has(name)) return;
if (typeof navigator !== "undefined" && !navigator.onLine) return;
const doc = this.repo.branches.get(name);
if (!doc) {
this.syncing.add(name);
let ok = true;
try {
const fetched = await this.fetchBranch(name);
if (fetched && !this.repo.branches.has(name)) {
this.repo.branches.set(name, fetched);
this.watch(name, fetched, true);
}
} catch {
ok = false; // offline: try again on the next notice
} finally {
this.syncing.delete(name);
}
return this.hooks.synced(name, ok, null);
}
const known = this.serverVV.get(name);
const mine = doc.loro.version().toJSON();
this.syncing.add(name);
let report: MergeReport | null = null;
let ok = false;
try {
const bytes = !known ? doc.snapshotBytes() : vvIncludes(known, mine) ? new Uint8Array() : doc.loro.export({ mode: "update", from: new VersionVector(known) });
const res = await fetch(`/api/sync/${encodeURIComponent(name)}`, {
method: "POST",
headers: { "x-vv": encodeVV(mine), "x-client": this.clientId, "x-library": this.library, "content-type": "application/octet-stream" },
body: bytes as BodyInit,
});
if (!res.ok) {
if (res.status === 409) this.lost();
throw await failure(res);
}
const theirs = decodeVV(res.headers.get("x-vv")!);
report = mergeUpdate(doc, new Uint8Array(await res.arrayBuffer()), theirs);
this.serverVV.set(name, theirs);
ok = true;
} catch {
report = null;
} finally {
this.syncing.delete(name);
this.hooks.synced(name, ok, report);
}
// Anything committed during the round (including a detected conflict) goes out in the next one.
const server = this.serverVV.get(name);
if (ok && server && !vvIncludes(server, this.repo.branches.get(name)!.loro.version().toJSON())) void this.sync(name);
}
private lost() {
if (this.foreign) return;
this.foreign = true;
this.disconnect();
this.hooks.foreign();
}
/** Listen for other writers. */
connect() {
if (this.events || this.foreign) return;
const events = new EventSource("/api/events");
events.onmessage = (e) => {
const msg = JSON.parse(e.data) as { branch?: string; from?: string };
if (msg.branch && msg.from !== this.clientId) void this.sync(msg.branch);
else if (!msg.branch) this.hooks.message?.(msg);
};
events.onopen = () => {
this.hooks.connection(true);
// Back after an outage (or just connected): exchange whatever either side missed.
void this.syncAll();
};
events.onerror = () => this.hooks.connection(false);
this.events = events;
}
disconnect() {
this.events?.close();
this.events = null;
}
}
+2755
View File
File diff suppressed because it is too large. Load diff
+554
View File
@@ -0,0 +1,554 @@
/*
* Typography and palette follow gwern.net (values read from its source): a serif body in
* grayscale, indented justified paragraphs, underlines only on things that respond, and
* visual differences only where there is a difference in meaning.
*/
:root {
--bg: #fff;
--fg: #000;
--soft: #333;
--dim: #666;
--faint: #888;
--rule: #bbb;
--hair: #e4e4e4;
--wash: #f5f5f5;
--sel: #e9e9e9;
--sel-strong: #d6d6d6;
--src: #f1efe6;
--attn: #8a5a00;
/* Links: the one colour on the page, kept to underlines and marks. */
--link: #3d6189;
/* Wikipedia's text sits on its own ground, so it is never mistaken for the reader's. */
--wiki-bg: #f2f5f8;
--wiki-rule: #c9d3dd;
--serif: "Source Serif 4 Variable", "Source Serif 4", "Apple Garamond", "Baskerville", "Libre Baskerville", "Times New Roman", serif;
--sans: "Source Sans 3 Variable", "Source Sans 3", "Lucida Sans Unicode", "Helvetica", sans-serif;
--mono: "IBM Plex Mono", "Liberation Mono", "Consolas", monospace;
--col: 700px;
--margin: 300px;
--gap: 44px;
color-scheme: light dark;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #161616;
--fg: #f1f1f1;
--soft: #dcdcdc;
--dim: #b4b4b4;
--faint: #999;
--rule: #6c6c6c;
--hair: #333;
--wash: #1d1d1d;
--sel: #2e2e2e;
--sel-strong: #444;
--src: #26241c;
--attn: #d9a441;
--link: #8fb1d8;
--wiki-bg: #182029;
--wiki-rule: #34414f;
}
}
* { box-sizing: border-box; }
html { font-size: 19px; }
body {
margin: 0;
background: var(--bg);
color: var(--fg);
font-family: var(--serif);
line-height: 1.55;
font-variant-numeric: oldstyle-nums;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
::selection { background: var(--sel-strong); }
.app { min-height: 100vh; }
.loading, .fatal { max-width: 34em; margin: 20vh auto; padding: 0 20px; font-family: var(--sans); color: var(--dim); }
.page { max-width: calc(var(--col) + var(--gap) + var(--margin) + 40px); margin: 0 auto; padding: 44px 20px 30vh; }
article { width: min(100%, var(--col)); }
/* ---- the top of the page ---- */
.crumbs { font-family: var(--sans); font-size: 0.72rem; color: var(--faint); margin-bottom: 0.5rem; }
.crumbs a { cursor: pointer; border-bottom: 1px dotted var(--faint); }
.top h1 {
margin: 0;
font-weight: 600;
font-size: 2rem;
line-height: 1;
font-variant-caps: small-caps;
letter-spacing: -0.02em;
text-align: right;
padding-bottom: 0.35rem;
border-bottom: 1px solid var(--faint);
}
.top.focused h1 { border-bottom-color: var(--fg); }
.byline { font-family: var(--sans); font-size: 0.68rem; color: var(--faint); text-align: right; margin-top: 0.3rem; letter-spacing: 0.02em; }
.abstract { margin: 1.4rem 0 1.6rem; }
.abstract.seed { border: 1px solid var(--rule); padding: 0.9rem 1.2rem; font-size: 0.86rem; line-height: 1.5; position: relative; }
.abstract.seed::before {
content: "the prompt, verbatim";
position: absolute; top: -0.62em; left: 0.9rem; padding: 0 0.4em;
background: var(--bg); font-family: var(--sans); font-size: 0.62rem; letter-spacing: 0.06em; text-transform: uppercase; color: var(--faint);
}
.abstract.seed.folded { cursor: pointer; border-bottom-style: dashed; margin-bottom: 0.3rem; }
.abstract.seed.folded .body { max-height: 6.1em; overflow: hidden; }
.abstract.seed.folded .body { -webkit-mask-image: linear-gradient(#000 35%, transparent 96%); mask-image: linear-gradient(#000 35%, transparent 96%); }
.unfold { font-family: var(--sans); font-size: 0.64rem; color: var(--faint); margin-bottom: 1.5rem; letter-spacing: 0.02em; }
/* ---- prose ---- */
.body { display: block; }
.para { display: block; margin: 0; text-align: justify; hyphens: auto; text-indent: 1.75em; }
.para.first { text-indent: 0; }
.para.empty { color: var(--faint); font-style: italic; text-align: left; }
.abstract.seed .para { text-indent: 0; margin-top: 0.6em; }
.abstract.seed .para.first { margin-top: 0; }
.em { font-style: italic; }
.code { font-family: var(--mono); font-size: 0.82em; background: var(--wash); padding: 0 0.2em; border-radius: 2px; font-style: normal; }
/* Text that already carries an expansion: a dotted underline, as on gwern's annotated links. */
.anchor {
cursor: pointer;
background-image: linear-gradient(to right, var(--dim) 50%, transparent 50%);
background-size: 3px 1px; background-repeat: repeat-x; background-position: 0 calc(100% - 0.08em);
}
.anchor:hover { background-image: linear-gradient(var(--fg), var(--fg)); background-size: 1px 1px; }
.anchor.on { background-image: linear-gradient(var(--faint), var(--faint)); background-size: 1px 1px; }
.anchor.writing { background-image: none; background-color: var(--sel); }
/* The keyboard selection. */
.sel { background: var(--sel); box-decoration-break: clone; -webkit-box-decoration-break: clone; }
.sel.word { background: var(--sel-strong); }
.src { background-color: var(--src); }
/* ---- expansions, in three sizes ---- */
/* 1. a gloss: a few words, inline, right after the term */
.gloss { color: var(--dim); font-size: 0.9em; text-indent: 0; }
.gloss::before { content: " ["; color: var(--faint); }
.gloss::after { content: "]"; color: var(--faint); }
.gloss .body, .gloss .para { display: inline; text-indent: 0; }
.gloss.focused { background: var(--sel); color: var(--fg); }
/* 2. a note: a sentence or three, in the margin beside its line */
.sidenote {
float: right; clear: right;
width: var(--margin); margin-right: calc(-1 * (var(--margin) + var(--gap))); margin-bottom: 0.9rem;
font-size: 0.8rem; line-height: 1.42; text-indent: 0; text-align: left; hyphens: manual;
color: var(--soft); padding: 0.3rem 0 0.35rem; border-top: 1px dotted var(--rule); border-bottom: 1px dotted var(--rule);
position: relative;
}
.sidenote .para, .inset .para, .popup .para { text-indent: 0; text-align: left; hyphens: manual; }
.sidenote .para + .para, .inset .para + .para, .popup .para + .para { margin-top: 0.5em; }
.sidenote.focused { border-top: 1px solid var(--fg); border-bottom: 1px solid var(--fg); color: var(--fg); }
.inset.focused { border-left-color: var(--fg); color: var(--fg); }
/* 3. a passage: paragraphs, set into the column under the text it expands */
.inset {
display: block; clear: both;
margin: 0.55rem 0 0.75rem 1.75em; padding: 0.45rem 0.9rem 0.5rem;
font-size: 0.88rem; line-height: 1.5; text-indent: 0;
border-left: 2px solid var(--rule); background: var(--wash); color: var(--soft);
}
.sidenote .inset, .inset .inset { margin-left: 0.4rem; font-size: 0.95em; }
.inset.orphan { border-left-style: dashed; }
.meta { display: block; font-family: var(--sans); font-size: 0.62rem; letter-spacing: 0.06em; text-transform: uppercase; color: var(--faint); margin-bottom: 0.15rem; }
.stale > .meta, .orphan > .meta { color: var(--attn); }
/* Below the width where a margin fits, notes fall into the column. */
@media (max-width: 1139px) {
.page { max-width: calc(var(--col) + 40px); }
.sidenote { float: none; display: block; width: auto; margin: 0.5rem 0 0.7rem 1.75em; padding: 0.4rem 0.8rem; border: 0; border-left: 2px dotted var(--rule); }
}
.with-panel .sidenote { float: none; display: block; width: auto; margin: 0.5rem 0 0.7rem 1.75em; padding: 0.4rem 0.8rem; border: 0; border-left: 2px dotted var(--rule); }
/* Text arriving. */
.caret { display: inline-block; width: 0.45em; height: 1em; vertical-align: -0.15em; background: var(--faint); animation: blink 1s steps(2) infinite; }
@keyframes blink { 50% { opacity: 0; } }
.pending { color: var(--dim); }
.pending-sections { margin: 0.4rem 0 0 1.35rem; color: var(--dim); }
.pending-section .title { font-weight: 600; margin-top: 0.4rem; }
/* ---- the outline ---- */
.outline { list-style: none; margin: 0; padding: 0; }
.content > .outline { margin-top: 0.55rem; }
.node { margin: 0; }
.row { display: flex; align-items: baseline; gap: 0.45em; cursor: pointer; padding: 0.08rem 0.3rem 0.08rem 0; margin-left: -0.3rem; padding-left: 0.3rem; border-radius: 2px; }
.row:hover .title { color: var(--dim); }
.mark { flex: none; width: 0.9em; font-family: var(--sans); font-size: 0.7em; color: var(--faint); text-align: center; position: relative; top: -0.1em; }
.title { flex: 0 1 auto; }
.untitled { color: var(--faint); }
/* Depth comes in a cycle of three, as gwern prescribes: bold, italic, small caps. */
.node.open > .row > .title { font-weight: 600; }
.node.open.d2 > .row > .title, .node.open.d5 > .row > .title { font-weight: 400; font-style: italic; }
.node.open.d3 > .row > .title, .node.open.d6 > .row > .title { font-weight: 500; font-variant-caps: small-caps; letter-spacing: 0.02em; }
.node.focused > .row { background: var(--sel); }
.node.focused > .row .mark { color: var(--fg); }
.flags { margin-left: auto; padding-left: 1em; flex: none; font-family: var(--sans); font-size: 0.62rem; letter-spacing: 0.05em; text-transform: uppercase; color: var(--faint); white-space: nowrap; }
.flags.attn { color: var(--attn); }
.byline .flags { margin-left: 0.8em; padding: 0; }
/* An open node's content hangs from a hairline, like gwern's collapse gutter. */
.content { margin: 0.15rem 0 0.7rem 0.42em; padding-left: 0.93em; border-left: 1px solid var(--hair); }
.node.focused > .content { border-left-color: var(--faint); }
article > .outline > .node { margin-top: 0.12rem; }
/* ---- editing ---- */
.editor, .title-editor {
font: inherit; color: inherit; background: var(--wash); border: 1px solid var(--rule); border-radius: 2px; outline: none; width: 100%;
}
.editor { display: block; padding: 0.4rem 0.6rem; resize: none; line-height: 1.5; font-size: 0.95em; text-indent: 0; }
.title-editor { padding: 0 0.3rem; flex: 1; }
.editor:focus, .title-editor:focus { border-color: var(--fg); }
/* ---- history view ---- */
.banner { font-family: var(--sans); font-size: 0.72rem; background: var(--fg); color: var(--bg); padding: 0.35rem 0.7rem; margin: -1rem 0 1.2rem; width: min(100%, var(--col)); }
article.preview { opacity: 0.92; }
.panel {
position: fixed; top: 0; right: 0; bottom: 1.75rem; width: min(440px, 92vw); overflow-y: auto;
background: var(--bg); border-left: 3px double var(--rule); padding: 0 0.9rem 2rem; font-family: var(--sans); font-size: 0.74rem; line-height: 1.4; z-index: 5;
}
.panel-head { position: sticky; top: 0; background: var(--bg); padding: 0.7rem 0 0.45rem; display: flex; justify-content: space-between; align-items: baseline; gap: 1em; border-bottom: 1px solid var(--hair); font-weight: 600; z-index: 1; }
.panel-head .keys { font-weight: 400; font-size: 0.62rem; color: var(--faint); text-align: right; }
.panel h3 { margin: 0.9rem 0 0.25rem; font-size: 0.62rem; letter-spacing: 0.08em; text-transform: uppercase; color: var(--faint); font-weight: 600; }
.verdict { margin-top: 0.6rem; padding: 0.4rem 0.6rem; background: var(--wash); border-left: 2px solid var(--fg); }
.item { padding: 0.28rem 0.45rem; border-radius: 2px; cursor: pointer; border-left: 2px solid transparent; }
.item.selected { background: var(--sel); border-left-color: var(--fg); }
.item.viewing { border-left-color: var(--attn); }
.item .line { display: flex; gap: 0.6em; align-items: baseline; }
.item .msg { flex: 1; }
.item .sub { color: var(--faint); font-size: 0.64rem; }
.hash { font-family: var(--mono); font-size: 0.62rem; color: var(--faint); flex: none; }
/* The documents a commit touched. */
.item .docs { color: var(--dim); font-size: 0.62rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chip { margin-left: auto; font-size: 0.58rem; letter-spacing: 0.06em; text-transform: uppercase; border: 1px solid var(--rule); padding: 0 0.35em; border-radius: 2px; color: var(--dim); }
.conflict.open .chip { color: var(--attn); border-color: var(--attn); }
.sides { margin-top: 0.4rem; display: grid; gap: 0.35rem; font-family: var(--serif); font-size: 0.74rem; line-height: 1.4; cursor: default; }
.side { display: block; border-left: 2px solid var(--hair); padding-left: 0.5rem; }
.side.strong { border-left-color: var(--fg); }
.side .name { display: block; font-family: var(--sans); font-size: 0.58rem; letter-spacing: 0.06em; text-transform: uppercase; color: var(--faint); }
.why { font-style: italic; color: var(--dim); }
.actions { display: flex; gap: 0.4rem; }
button { font: inherit; font-family: var(--sans); font-size: 0.66rem; color: var(--fg); background: var(--bg); border: 1px solid var(--rule); border-radius: 2px; padding: 0.1rem 0.5rem; cursor: pointer; }
button:hover { border-color: var(--fg); }
/* ---- overlays ---- */
.overlay { position: fixed; inset: 0; background: color-mix(in srgb, var(--bg) 82%, transparent); display: flex; justify-content: center; align-items: flex-start; padding: 8vh 20px 4vh; z-index: 20; overflow-y: auto; }
.help, .jump { background: var(--bg); border: 3px double var(--rule); box-shadow: 1px 2px 8px 0 color-mix(in srgb, var(--fg) 14%, transparent); font-family: var(--sans); }
.help { max-width: 980px; padding: 1.1rem 1.5rem 1.4rem; font-size: 0.72rem; line-height: 1.35; }
.help h2 { margin: 0 0 0.3rem; font-family: var(--serif); font-variant-caps: small-caps; font-size: 1.3rem; font-weight: 600; }
.help .lede { margin: 0 0 0.9rem; max-width: 62em; color: var(--dim); font-family: var(--serif); font-size: 0.82rem; }
.help .cols { columns: 2 380px; column-gap: 2.2rem; }
.help section { break-inside: avoid; margin-bottom: 0.8rem; }
.help h3 { margin: 0 0 0.25rem; font-size: 0.62rem; letter-spacing: 0.08em; text-transform: uppercase; color: var(--faint); }
.help dl { margin: 0; }
.help dl > div { display: grid; grid-template-columns: 9.6em 1fr; gap: 0.7em; padding: 0.1rem 0; }
.help dt { white-space: nowrap; }
.help dd { margin: 0; color: var(--soft); }
kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid var(--rule); border-bottom-width: 2px; border-radius: 3px; padding: 0 0.3em; margin-right: 0.25em; background: var(--wash); }
.help code { border: 0; padding: 0; background: none; }
.jump { width: min(560px, 100%); }
.jump input { width: 100%; font: inherit; font-size: 0.9rem; padding: 0.55rem 0.8rem; border: 0; border-bottom: 1px solid var(--hair); outline: none; background: transparent; color: var(--fg); }
.jump ul { list-style: none; margin: 0; padding: 0.25rem 0; }
.jump li { padding: 0.25rem 0.8rem; cursor: pointer; display: flex; gap: 0.8em; align-items: baseline; font-size: 0.8rem; }
.jump li.selected { background: var(--sel); }
.jump li .p { color: var(--faint); font-size: 0.66rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.jump li .p .in { font-weight: 600; color: var(--dim); }
.jump li.none { color: var(--faint); cursor: default; }
.popup {
position: fixed; width: 440px; max-height: 320px; overflow: auto; z-index: 15;
background: var(--bg); border: 3px double var(--rule); box-shadow: 1px 2px 8px 0 color-mix(in srgb, var(--fg) 16%, transparent);
padding: 0.6rem 0.85rem 0.7rem; font-size: 0.82rem; line-height: 1.45; pointer-events: none;
}
/* ---- the command bar and status line ---- */
.command { position: fixed; left: 0; right: 0; bottom: 1.75rem; display: flex; align-items: baseline; gap: 0.7em; background: var(--bg); border-top: 1px solid var(--fg); padding: 0.4rem 0.9rem; font-family: var(--sans); font-size: 0.8rem; z-index: 12; }
.command .prompt { color: var(--faint); font-size: 0.7rem; white-space: nowrap; }
.command .prompt::after { content: " ›"; }
.command input { flex: 1; font: inherit; border: 0; outline: none; background: transparent; color: var(--fg); }
.status {
position: fixed; left: 0; right: 0; bottom: 0; height: 1.75rem; display: flex; align-items: center; gap: 0.9em;
background: var(--wash); border-top: 1px solid var(--hair); padding: 0 0.9rem; font-family: var(--sans); font-size: 0.66rem; color: var(--dim); white-space: nowrap; z-index: 10;
}
.grain { font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; color: var(--bg); background: var(--fg); padding: 0 0.5em; border-radius: 2px; }
.grain.sentence, .grain.word { background: var(--dim); }
.grain.aux { background: var(--link); }
.path { color: var(--faint); overflow: hidden; text-overflow: ellipsis; flex: 0 1 auto; min-width: 0; }
.message { flex: 1 1 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; color: var(--fg); }
.right { display: flex; align-items: center; gap: 0.9em; color: var(--faint); }
.dot { width: 0.5em; height: 0.5em; border-radius: 50%; background: var(--faint); }
.dot.off { background: transparent; border: 1px solid var(--attn); }
.spin { width: 0.7em; height: 0.7em; border: 1.5px solid var(--faint); border-top-color: transparent; border-radius: 50%; animation: spin 0.8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
@media (max-width: 720px) {
html { font-size: 17px; }
.para { text-align: left; }
.status .path, .status .q { display: none; }
}
/* ---- the editor's research run, above the status line (AgentPanel in App.tsx) ---- */
.agent-panel {
position: fixed; left: 0; right: 0; bottom: 1.75rem; max-height: 11rem; overflow: auto; z-index: 11;
background: var(--wash); border-top: 1px solid var(--hair); padding: 0.35rem 0.9rem 0.4rem;
font-family: var(--sans); font-size: 0.7rem; line-height: 1.5; color: var(--dim);
}
.agent-head { color: var(--faint); }
.agent-label { font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; color: var(--fg); margin-right: 0.7em; }
.agent-steps { margin: 0.15rem 0 0; padding: 0; list-style: none; }
.agent-steps li { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.agent-steps li::before { content: "· "; color: var(--faint); }
.agent-steps .agent-more { color: var(--faint); }
.agent-summary { color: var(--fg); margin-top: 0.2rem; }
.agent-sources a { color: var(--link); text-decoration: none; }
.agent-sources a:hover { text-decoration: underline; }
.agent-host { color: var(--faint); }
/* ---- usage in the status line (src/ui/Usage.tsx) ---- */
.usage { display: flex; align-items: center; gap: 0.9em; flex: none; white-space: nowrap; color: var(--faint); font-variant-numeric: tabular-nums; }
.usage > span { cursor: default; }
.usage-plan { color: var(--dim); }
.usage-plan.attn { color: var(--attn); font-weight: 600; }
@media (max-width: 899px) {
.usage-session { display: none; }
}
/* ---- end usage ---- */
/* ---- panes view (src/ui/Panes.tsx) ----
* The path to the focus as a strip of panes, side by side, after notes.andymatuschak.org. Pane i
* sticks i spines from the left edge, so later panes slide over earlier ones and leave each a
* narrow spine that carries its title. Each pane scrolls on its own; only the strip scrolls sideways.
*/
:root {
--pane-text: 34rem;
--spine: 2.1rem;
--pane-pad: 1.8rem;
--pane: calc(var(--spine) + var(--pane-text) + var(--pane-pad));
--shade: rgb(0 0 0 / 0.2);
}
@media (prefers-color-scheme: dark) {
:root { --shade: rgb(0 0 0 / 0.6); }
}
.view-panes .page {
position: fixed; top: 0; left: 0; right: 0; bottom: 1.75rem;
max-width: none; margin: 0; padding: 0; display: flex; flex-direction: column;
}
.view-panes.with-panel .page { right: min(440px, 92vw); }
.view-panes .banner { flex: none; width: auto; margin: 0; }
.strip {
flex: 1; min-height: 0; display: flex; overflow-x: auto; overflow-y: hidden;
overscroll-behavior-x: contain; scrollbar-width: thin; scrollbar-color: var(--rule) transparent;
}
.pane { position: sticky; flex: none; width: var(--pane); width: round(down, var(--pane), 1px); height: 100%; background: var(--bg); border-left: 1px solid var(--hair); }
.pane:first-child { border-left-color: transparent; }
.pane[data-over] { border-left-color: var(--rule); box-shadow: -14px 0 20px -12px var(--shade); }
.pane-scroll {
height: 100%; overflow-x: hidden; overflow-y: auto; padding: 1.9rem var(--pane-pad) 30vh var(--spine);
scrollbar-width: thin; scrollbar-color: var(--hair) transparent;
}
/* The spine: a covered pane's title, set vertically in the left gutter. */
.spine { position: absolute; top: 0; bottom: 0; left: 0; width: var(--spine); z-index: 2; background: var(--bg); opacity: 0; pointer-events: none; cursor: pointer; transition: opacity 0.12s; }
.pane[data-covered] .spine { opacity: 1; pointer-events: auto; }
.spine span {
display: block; max-height: 100%; padding: 1.95rem 0 1.2rem; writing-mode: vertical-rl; line-height: var(--spine);
font-family: var(--sans); font-size: 0.74rem; letter-spacing: 0.03em; color: var(--dim);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.spine:hover span { color: var(--fg); }
@media (prefers-reduced-motion: reduce) {
.spine { transition: none; }
}
/* A pane's head: a section heading, smaller than the page title the first pane keeps. */
.pane-head { display: flex; align-items: baseline; gap: 0.6em; margin: 0 0 0.85rem; padding-bottom: 0.3rem; border-bottom: 1px solid var(--faint); cursor: pointer; }
.pane-head.focused { border-bottom-color: var(--fg); }
.pane-head h2 { margin: 0; font-size: 1.32rem; font-weight: 600; line-height: 1.2; letter-spacing: -0.01em; }
.pane-head .title-editor { font-size: 1.32rem; font-weight: 600; }
/* Its child sections, as outline rows. The one whose pane is open to the right is marked. */
.pane .rows { margin-top: 1.4rem; padding-top: 0.55rem; border-top: 1px solid var(--hair); }
.pane.root .rows { margin-top: 0; padding-top: 0; border-top: 0; }
.pane .rows > .node { margin-top: 0.12rem; }
.node.showing:not(.focused) > .row { background: var(--wash); }
.node.showing > .row .mark { color: var(--fg); }
.node.showing > .row::after { content: "→"; flex: none; margin-left: auto; padding-left: 0.8em; font-family: var(--sans); font-size: 0.72em; color: var(--dim); }
/* The first pane keeps the page title, set from the left so it stays readable when the pane is partly covered. */
.pane.root .top h1, .pane.root .byline, .pane.doc .top h1, .pane.doc .byline { text-align: left; }
.pane.root .rows, .pane.doc .rows { margin-top: 0; padding-top: 0; border-top: 0; }
/* A pane has no margin: notes are set into its column, as on a narrow screen. */
.pane .sidenote { float: none; display: block; width: auto; margin: 0.5rem 0 0.7rem 1.75em; padding: 0.4rem 0.8rem; border: 0; border-left: 2px dotted var(--rule); }
.pane .sidenote.focused { border-left: 2px solid var(--fg); }
/* ---- end panes view ---- */
/* ---- the top bar and the documents menu (src/ui/Menu.tsx) ----
* The bar sits in the page's top margin: the document's title, which opens the menu, and whether
* the server has every edit yet. The menu is a panel like history's.
*/
.docbar { display: flex; align-items: baseline; gap: 0.9em; width: min(100%, var(--col)); margin: -30px 0 16px; min-width: 0; font-family: var(--sans); font-size: 0.66rem; color: var(--faint); letter-spacing: 0.02em; }
.doc-title { display: flex; align-items: baseline; gap: 0.35em; min-width: 0; max-width: 75%; padding: 0; border: 0; background: none; font-size: inherit; color: var(--dim); }
.doc-title .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.doc-title .chev { align-self: center; width: 0; height: 0; border: 0.38em solid transparent; border-top: 0.46em solid var(--faint); border-bottom: 0; margin-left: 0.1em; }
.doc-title:hover .name { color: var(--fg); text-decoration: underline dotted; text-underline-offset: 0.2em; }
.save-state { white-space: nowrap; }
.save-state.offline, .save-state.deleted { color: var(--attn); }
.view-panes .docbar { flex: none; width: auto; margin: 0; padding: 0.3rem 0.9rem 0.25rem; border-bottom: 1px solid var(--hair); }
.panel .filter, .panel .prompt input {
display: block; width: 100%; margin: 0.6rem 0 0.3rem; padding: 0.3rem 0.5rem; font: inherit; font-size: 0.8rem;
color: var(--fg); background: var(--bg); border: 1px solid var(--rule); border-radius: 2px; outline: none;
}
.panel .filter:focus, .panel .prompt input:focus { border-color: var(--fg); }
.panel .prompt { display: block; margin-top: 0.5rem; }
.panel .prompt span { font-size: 0.6rem; letter-spacing: 0.06em; text-transform: uppercase; color: var(--faint); }
.panel .prompt input { margin-top: 0.15rem; }
.doclist { list-style: none; margin: 0.3rem 0 0; padding: 0; }
.doc { margin-bottom: 0.1rem; }
.doc .title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
.doc .when { flex: none; font-size: 0.6rem; color: var(--faint); }
.doc .sub { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.doc.current .title::before { content: "● "; font-size: 0.7em; color: var(--dim); }
.doc .actions { flex-wrap: wrap; margin: 0.3rem 0 0.1rem; }
.doclist .none { padding: 0.3rem 0.45rem; color: var(--faint); }
.confirm, .problems { margin: 0.5rem 0; padding: 0.45rem 0.6rem; background: var(--wash); border-left: 2px solid var(--attn); }
.confirm .actions { margin-top: 0.4rem; }
.problems ul { margin: 0.3rem 0 0; padding-left: 1.1rem; font-family: var(--mono); font-size: 0.6rem; overflow-wrap: anywhere; }
.panel-foot { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.5rem; margin-top: 0.9rem; padding-top: 0.6rem; border-top: 1px solid var(--hair); font-size: 0.62rem; color: var(--faint); }
.panel.docs.dropping { outline: 2px dashed var(--fg); outline-offset: -6px; }
/* ---- end documents ---- */
/* ---- links (src/ui/Links.tsx) ----
* After gwern.net's typed links: the linked words keep the text's colour and get a thin solid
* underline; a small mark after them says where the link goes (W Wikipedia, § another note in this
* library, ↗ the web). A note keeps its dotted underline; a note that also links has both.
*/
.lnk { cursor: pointer; text-decoration: underline 1px solid var(--link); text-underline-offset: 0.18em; text-decoration-skip-ink: auto; }
.lnk:hover, .lnk.on { text-decoration-thickness: 2px; }
.lnk.on { background: var(--wash); }
.lmark {
display: inline-block; margin: 0 0.06em 0 0.08em; font-family: var(--serif); font-size: 0.6em; line-height: 1; font-weight: 600;
vertical-align: 0.55em; color: var(--link); cursor: pointer; user-select: none; -webkit-user-select: none; text-indent: 0; font-style: normal;
}
.lmark.l-wiki { font-family: var(--serif); letter-spacing: -0.04em; }
.lmark.l-node { font-weight: 400; font-size: 0.68em; vertical-align: 0.45em; }
.lmark.l-url { font-family: var(--sans); font-weight: 400; font-size: 0.66em; vertical-align: 0.5em; }
.lmark.broken { color: var(--attn); text-decoration: line-through; }
/* A target's card: in a popup, a column inset, a node's own target row. */
.lcard { font-family: var(--sans); font-size: 0.78rem; line-height: 1.45; color: var(--soft); text-align: left; text-indent: 0; }
.lcard .lhead { font-size: 0.62rem; letter-spacing: 0.07em; text-transform: uppercase; color: var(--faint); }
.lcard .lhead .lmark { vertical-align: 0.1em; font-size: 0.95em; margin: 0 0.15em 0 0; }
.lcard .ltitle { font-weight: 600; color: var(--fg); font-size: 0.92rem; margin-top: 0.05rem; }
.lcard .lsub { color: var(--dim); font-size: 0.72rem; }
.lcard .lsub.problem, .problem { color: var(--attn); }
.lcard .lbody { margin-top: 0.3rem; }
.popup .lcard + .lcard, .popup .body + .lcard { margin-top: 0.5rem; padding-top: 0.45rem; border-top: 1px solid var(--hair); }
.popup:has(.l-wiki) { background: var(--wiki-bg); border-color: var(--wiki-rule); }
.wattr { margin: 0.5rem 0 0; font-family: var(--sans); font-size: 0.6rem; line-height: 1.4; color: var(--faint); text-align: left; text-indent: 0; }
.wattr a { color: inherit; text-decoration: underline 1px dotted; text-underline-offset: 0.15em; }
.lpreview.l-wiki { background: var(--wiki-bg); border-left-color: var(--wiki-rule); }
.lpreview .lnext { margin: 0.35rem 0 0; }
.target-row { margin: 0.9rem 0 0.4rem; padding: 0.45rem 0.7rem; border-left: 2px solid var(--wiki-rule); cursor: pointer; }
.target-row.l-wiki { background: var(--wiki-bg); }
.target-row.focused { border-left-color: var(--fg); background: var(--sel); }
/* "Linked from" and "Mentioned in". */
:is(.backlinks, .related-list) { margin: 1.4rem 0 0.6rem; padding-top: 0.5rem; border-top: 1px solid var(--hair); font-family: var(--sans); font-size: 0.74rem; }
:is(.backlinks, .related-list) h3 { margin: 0 0 0.25rem; font-size: 0.6rem; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; color: var(--faint); }
:is(.backlinks, .related-list) ul { list-style: none; margin: 0; padding: 0; }
:is(.backlinks, .related-list) li { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0 0.6em; padding: 0.12rem 0.35rem; margin-left: -0.35rem; border-radius: 2px; cursor: pointer; }
:is(.backlinks, .related-list) li.focused { background: var(--sel); }
:is(.backlinks, .related-list) .bl-title { color: var(--fg); font-weight: 600; }
:is(.backlinks, .related-list) .bl-doc { color: var(--dim); }
:is(.backlinks, .related-list) .bl-quote { color: var(--faint); font-style: italic; flex-basis: 100%; }
/* The link picker: the jump box, grouped. */
.picker-head { padding: 0.5rem 0.8rem 0; font-size: 0.66rem; letter-spacing: 0.04em; color: var(--faint); }
.picker li.group { cursor: default; padding-top: 0.45rem; font-size: 0.58rem; letter-spacing: 0.08em; text-transform: uppercase; color: var(--faint); }
.picker li .lmark { vertical-align: 0.15em; font-size: 0.85em; width: 0.9em; text-align: center; margin: 0; }
.picker li .t { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 55%; }
/* ---- Wikipedia (src/ui/Wiki.tsx) ----
* Its own ground, its own face (the bundled sans), a W at its head, its licence at its foot.
*/
.wiki { font-family: var(--sans); color: var(--soft); }
.wiki-pane .pane-scroll, .wiki-pane .spine { background: var(--wiki-bg); }
.wiki-pane { border-left-color: var(--wiki-rule); }
.wiki-pane .spine span { color: var(--dim); }
.wiki-pane .spine .wmark { font-weight: 600; }
.wiki-head { margin: 0 0 0.8rem; padding-bottom: 0.35rem; border-bottom: 1px solid var(--wiki-rule); cursor: pointer; }
.wiki-head.focused { border-bottom-color: var(--fg); }
.wiki-head.focused h2 { text-decoration: underline 1px solid var(--faint); text-underline-offset: 0.2em; }
.wiki-brand { font-size: 0.6rem; letter-spacing: 0.08em; text-transform: uppercase; color: var(--faint); display: flex; align-items: center; gap: 0.4em; }
.wmark { font-family: var(--serif); font-weight: 600; font-size: 1.05em; letter-spacing: -0.04em; color: var(--link); text-transform: none; }
.wiki-brand .wmark { display: inline-block; border: 1px solid var(--wiki-rule); border-radius: 2px; padding: 0 0.22em; line-height: 1.25; background: var(--bg); }
.wiki-head h2 { margin: 0.15rem 0 0; font-family: var(--sans); font-size: 1.28rem; font-weight: 600; line-height: 1.2; color: var(--fg); letter-spacing: -0.005em; }
.wiki-head .wsub { font-weight: 400; color: var(--dim); }
.wiki-text { font-size: 0.82rem; line-height: 1.55; }
.wiki-text p { margin: 0 0 0.65em; }
.wiki-text ul, .wiki-text ol { margin: 0 0 0.65em; padding-left: 1.3em; }
.wiki-text dl dd { margin-left: 1.2em; }
.wiki-text a { color: inherit; text-decoration: underline 1px solid var(--link); text-underline-offset: 0.16em; }
.wiki-text a[target]::after { content: "↗"; font-size: 0.7em; vertical-align: 0.45em; color: var(--link); margin-left: 0.05em; }
.wiki-text a.wfocus { background: var(--sel-strong); outline: 1px solid var(--fg); outline-offset: 1px; }
.wiki-text table { border-collapse: collapse; font-size: 0.92em; margin: 0.4em 0 0.8em; }
.wiki-text th, .wiki-text td { border: 1px solid var(--wiki-rule); padding: 0.15em 0.4em; vertical-align: top; }
.wiki-text blockquote { margin: 0.4em 0 0.7em 1em; padding-left: 0.7em; border-left: 2px solid var(--wiki-rule); }
.wiki-text pre, .wiki-text code { font-family: var(--mono); font-size: 0.9em; }
.wiki-text math { font-size: 1.05em; }
.wiki-desc { margin: -0.4rem 0 0.6rem; font-size: 0.74rem; color: var(--dim); font-style: italic; }
.wiki-summary { margin: 0 0 0.5rem; font-size: 0.82rem; line-height: 1.55; }
.wiki-more, .wiki-wait, .wiki-back { margin: 0.3rem 0; font-size: 0.66rem; color: var(--faint); letter-spacing: 0.02em; }
.wiki-problem { margin: 0.4rem 0; padding: 0.4rem 0.6rem; border-left: 2px solid var(--attn); background: var(--bg); font-size: 0.78rem; color: var(--soft); }
.wrows { list-style: none; margin: 0.9rem 0 0; padding: 0.5rem 0 0; border-top: 1px solid var(--wiki-rule); }
.wrows.nested { margin: 0.3rem 0 0; border-top: 0; padding-top: 0; }
.wrow .row { font-size: 0.86rem; }
.wrow.focused > .row { background: var(--sel); }
.wrow.focused > .row .mark { color: var(--fg); }
.wrow.open > .row > .title { font-weight: 600; }
.wrow.showing:not(.focused) > .row { background: color-mix(in srgb, var(--wiki-rule) 40%, transparent); }
.wrow.showing > .row::after { content: "→"; flex: none; margin-left: 0.5em; font-size: 0.72em; color: var(--dim); }
.wrow.showing > .row:not(:has(.wnum))::after { margin-left: auto; }
.wrow .wnum, .wrow .wdesc { margin-left: auto; padding-left: 1em; font-size: 0.66rem; color: var(--faint); white-space: nowrap; }
.wrow .wnum { font-variant-numeric: tabular-nums; }
.wiki .content { border-left-color: var(--wiki-rule); }
.senses h3 { margin: 0.8rem 0 0; font-size: 0.66rem; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--faint); }
.senses .wrows { margin-top: 0.3rem; }
.wiki .backlinks { border-top-color: var(--wiki-rule); }
.wiki > .wattr { margin-top: 1.2rem; padding-top: 0.5rem; border-top: 1px solid var(--wiki-rule); }
/* An article under a node in its pane: clearly divided from the node's own text above it. */
.wiki.embedded { margin: 1.6rem calc(-1 * var(--pane-pad)) 0 0; padding: 0.9rem var(--pane-pad) 0.8rem 1rem; background: var(--wiki-bg); border-top: 3px double var(--wiki-rule); }
.wiki.embedded:has(.wiki-head.focused) { box-shadow: inset 3px 0 0 var(--fg); }
.pane-from { margin: 0 0 0.25rem; font-family: var(--sans); font-size: 0.62rem; letter-spacing: 0.06em; text-transform: uppercase; color: var(--faint); }
.pane.note-pane .pane-head h2 { font-style: italic; font-weight: 500; }
/* The column's article page. */
.wiki-page { background: var(--wiki-bg); padding: 1.2rem 1.4rem 1.4rem; border: 1px solid var(--wiki-rule); }
/* ---- end links and Wikipedia ---- */
/* Suggested links: a faint dashed underline, distinct from a link's solid one and a note's dotted one. */
.sugg { text-decoration: underline 1px dashed color-mix(in srgb, var(--link) 45%, transparent); text-underline-offset: 0.24em; text-decoration-skip-ink: auto; }
.sugg.sel { text-decoration-color: var(--link); }
.lpreview.suggestion { border-left-style: dashed; }
.lpreview.suggestion .why { display: block; margin-top: 0.3rem; }
.related-list { border-top-style: dashed; }
.status .job { color: var(--link); white-space: nowrap; }
/* The [[ completer under the body editor. */
.completer { position: relative; }
.completer ul { position: absolute; z-index: 20; left: 0; top: 0.2rem; min-width: 22rem; max-width: 36rem; margin: 0; padding: 0.25rem 0; list-style: none; background: var(--bg); border: 1px solid var(--hair); box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12); font-family: var(--sans); font-size: 0.8rem; }
.completer li { display: flex; gap: 0.6em; align-items: baseline; padding: 0.2rem 0.6rem; }
.completer li.group { color: var(--faint); font-size: 0.62rem; letter-spacing: 0.08em; text-transform: uppercase; padding-top: 0.35rem; }
.completer li.selected { background: var(--sel); }
.completer .t { color: var(--fg); font-weight: 600; }
.completer .p { color: var(--dim); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
:is(.backlinks, .related-list) .bl-key { color: var(--link); font-family: var(--mono, monospace); font-size: 0.7rem; min-width: 0.8em; }
+191
View File
@@ -0,0 +1,191 @@
/**
* The footer's usage figures, as seen from the browser: fetched from GET /api/usage on load, after
* every model call the page makes, and once a minute while the page is visible. Kept apart from
* the store; the store only wraps its model with `refreshAfterCalls`.
*/
import type { PlanWindow, UsageSummary } from "../../server/usage";
import type { LLM } from "../llm/types";
let current: UsageSummary | null = null;
const listeners = new Set<() => void>();
export const usageNow = () => current;
export function onUsage(fn: () => void): () => void {
listeners.add(fn);
return () => listeners.delete(fn);
}
let inflight = false;
let again = false;
/** Fetch the summary. Calls that arrive while one is in flight fold into one more fetch after it. */
async function refreshUsage(): Promise<void> {
if (inflight) {
again = true;
return;
}
inflight = true;
try {
do {
again = false;
try {
const res = await fetch("/api/usage");
if (res.ok) current = (await res.json()) as UsageSummary;
} catch {
/* offline: keep what we had */
}
for (const fn of listeners) fn();
} while (again);
} finally {
inflight = false;
}
}
const MINUTE = 60_000;
let timer: ReturnType<typeof setInterval> | undefined;
const onVisible = () => {
if (!document.hidden) void refreshUsage();
};
/** Load now, then refresh once a minute while the page is visible. Returns a stop function. */
export function startUsage(): () => void {
void refreshUsage();
if (timer === undefined) {
timer = setInterval(() => !document.hidden && void refreshUsage(), MINUTE);
document.addEventListener("visibilitychange", onVisible);
}
return () => {
clearInterval(timer);
timer = undefined;
document.removeEventListener("visibilitychange", onVisible);
};
}
/** The same model, refreshing the usage figures after each call finishes (or fails). */
export function refreshAfterCalls(llm: LLM): LLM {
const after = <T>(p: Promise<T>): Promise<T> => p.finally(() => void refreshUsage());
return {
...llm,
stream: (req, onText, signal) => after(llm.stream(req, onText, signal)),
json: (req, signal) => after(llm.json(req, signal)),
turn: (req, signal, onWeb) => after(llm.turn(req, signal, onWeb)),
};
}
// ---- words ----
/** 950 → "950", 12_400 → "12k", 1_250_000 → "1.3M". */
function tokens(n: number): string {
if (n < 1000) return String(n);
if (n < 10_000) return `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k`;
if (n < 1_000_000) return `${Math.round(n / 1000)}k`;
return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;
}
const num = (n: number) => n.toLocaleString("en-US");
const plural = (n: number, one: string, many = `${one}s`) => `${num(n)} ${n === 1 ? one : many}`;
/** A reset time, short: "17:00" today, "Sat 14:00" within a week, else "16 Nov". */
function when(iso: string, now: Date): string {
const t = new Date(iso);
const hm = t.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
if (t.toDateString() === now.toDateString()) return hm;
if (t.getTime() - now.getTime() < 6.5 * 86_400_000) return `${t.toLocaleDateString([], { weekday: "short" })} ${hm}`;
return t.toLocaleDateString([], { day: "numeric", month: "short" });
}
/** A reset time, long: "Sat 16 Nov, 14:00 (in 2 days 5 hours)". */
function whenLong(iso: string, now: Date): string {
const t = new Date(iso);
const date = t.toLocaleString([], { weekday: "short", day: "numeric", month: "short", hour: "numeric", minute: "2-digit" });
const mins = Math.max(0, Math.round((t.getTime() - now.getTime()) / 60_000));
const d = Math.floor(mins / 1440);
const h = Math.floor((mins % 1440) / 60);
const m = mins % 60;
const rel = d ? `${plural(d, "day")}${h ? ` ${plural(h, "hour")}` : ""}` : h ? `${plural(h, "hour")}${m ? ` ${plural(m, "minute")}` : ""}` : plural(m, "minute");
return `${date} (in ${rel})`;
}
/** Share left, rounded down so it never overstates: 3.6 → "3%", 0.4 → "<1%". */
function left(usedPercent: number): string {
const r = Math.max(0, 100 - usedPercent);
return r > 0 && r < 1 ? "<1%" : `${Math.floor(r)}%`;
}
const passed = (iso: string | null, now: Date) => iso !== null && Date.parse(iso) <= now.getTime();
function windowLine(w: PlanWindow, now: Date): string {
if (w.id === "overage") {
if (w.usedPercent !== null) return `Extra usage: ${Math.round(w.usedPercent)}% used${w.resetsAt ? `, resets ${whenLong(w.resetsAt, now)}` : ""}`;
return `Extra usage: ${w.status === "rejected" ? "not available" : "available"}`;
}
if (w.reset || passed(w.resetsAt, now)) return `${cap(w.label)} usage: reset since it was reported; the new figure arrives with the next call`;
const pct = w.usedPercent === null ? `${cap(w.label)} usage: not reported` : `${left(w.usedPercent)} of ${w.label} usage left`;
const status = w.status === "rejected" ? " (limit reached)" : w.status === "allowed_warning" ? " (close to the limit)" : "";
return `${pct}${status}${w.resetsAt ? `, resets ${whenLong(w.resetsAt, now)}` : ""}`;
}
const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
export interface UsageView {
plan: { text: string; title: string; attn: boolean; limited: boolean } | null;
session: { text: string; title: string; calls: number } | null;
}
/** What the footer shows, in words. Null when there is no model. */
export function view(u: UsageSummary | null, now: Date = new Date()): UsageView | null {
if (!u || !u.provider) return null;
const s = u.session;
const started = new Date(s.startedAt).toLocaleString([], { weekday: "short", hour: "numeric", minute: "2-digit" });
const lines = [`This session (since the server started, ${started}):`, plural(s.calls, "model call")];
const notes = [s.failed ? `${num(s.failed)} failed` : "", s.unreported ? `${num(s.unreported)} without token counts` : ""].filter(Boolean);
if (notes.length) lines[1] += ` (${notes.join(", ")})`;
const cached = s.input.cacheRead || s.input.cacheWrite;
lines.push(
`${plural(s.input.total, "input token")}${cached ? `: ${num(s.input.fresh)} uncached, ${num(s.input.cacheRead)} read from cache, ${num(s.input.cacheWrite)} written to cache` : ""}`,
plural(s.output, "output token"),
);
const web = s.web ?? { searches: 0, fetches: 0 };
if (web.searches || web.fetches) lines.push(`Web research: ${plural(web.searches, "search", "searches")}, ${plural(web.fetches, "page")} fetched`);
if (s.lastCall) lines.push(`Last call sent ${plural(s.lastCall.input, "input token")} (${new Date(s.lastCall.at).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })})`);
if (s.costUsd !== null) lines.push(`About $${s.costUsd.toFixed(2)} at API prices (Claude Code's estimate; the subscription is not charged per call)`);
if (u.provider === "mock") lines.push("Mock model: token counts are estimates (4 characters per token).");
let plan: UsageView["plan"] = null;
const p = u.plan;
if (p) {
const title: string[] = [];
const limited = p.limited && !passed(p.limitResetsAt, now);
if (limited) {
title.push(`Claude is refusing requests: ${p.limitLabel ? `${p.limitLabel} limit` : "usage limit"} reached.${p.limitResetsAt ? ` It resets ${whenLong(p.limitResetsAt, now)}.` : ""}`);
}
// The most constrained window first: it is the one the footer shows.
const ordered = [...p.windows].sort((a, b) => Number(b.id === p.tightest) - Number(a.id === p.tightest));
for (const w of ordered) title.push(windowLine(w, now));
if (p.overage && !p.windows.some((w) => w.id === "overage") && (p.overage.status || p.overage.inUse !== null)) {
title.push(p.overage.inUse ? "Extra usage: in use" : `Extra usage: ${p.overage.status === "rejected" ? "not available" : "available"}`);
}
if (p.updatedAt) {
const at = new Date(p.updatedAt).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
const from = p.source === "query" ? "looked up when the server started" : "reported with the last call";
title.push(`As of ${at} (${from}). Use elsewhere (Claude Code, claude.ai) counts too and shows here after the next call.`);
}
const tight = p.windows.find((w) => w.id === p.tightest);
if (limited) {
plan = { text: `limit reached${p.limitResetsAt ? `, resets ${when(p.limitResetsAt, now)}` : ""}`, title: title.join("\n"), attn: true, limited: true };
} else if (tight && tight.usedPercent !== null && !passed(tight.resetsAt, now)) {
plan = { text: `${tight.label} ${left(tight.usedPercent)} left`, title: title.join("\n"), attn: p.warning, limited: false };
} else {
lines.push("", "Plan usage: not reported yet. Claude reports it with each call.");
if (title.length) lines.push(...title);
}
}
return {
plan,
session: {
text: `${plural(s.calls, "call")} · ${tokens(s.input.total)} in · ${tokens(s.output)} out${web.searches || web.fetches ? ` · ${plural(web.searches, "search", "searches")}` : ""}`,
title: lines.join("\n"),
calls: s.calls,
},
};
}
+220
View File
@@ -0,0 +1,220 @@
/**
* Wikipedia in the browser: what the server's /api/wiki routes return, kept per title so a pane,
* a popup and an inset showing the same article share one request. Nothing here blocks: a view
* asks for an article and draws whatever state it is in (loading, ready, missing, unreachable…),
* and is told to draw again when that changes.
*
* Article HTML arrives sanitised by the server (server/wiki.ts). It is cleaned again here before it
* is put into the page, because it came from outside: only an allowlist of elements and
* attributes survives, and every link either names an article (data-wiki) or opens a new tab.
*/
import type { Attribution, FullArticle as Article, Sense, Summary, TitleSuggestion as Suggestion } from "../../server/wiki";
import { wikiKey, wikiTitle } from "../core/ref";
export type { Article, Attribution, Suggestion };
type WikiSection = Article["sections"][number];
/** Why something could not be shown, in words a reader can act on. */
type Problem = { reason: "missing" | "offline" | "rate-limited" | "off" | "error"; message: string };
type Loadable<T> = { state: "loading" } | { state: "ready"; value: T; stale?: boolean } | ({ state: "failed"; at: number } & Problem);
/** A failure other than "missing" is asked again after this long, not on every redraw. */
const RETRY_MS = 20_000;
/** What the server said about Wikipedia when the page loaded. */
export interface WikiConfig {
mode: "live" | "mock" | "off";
lang: string;
contact: boolean;
}
let config: WikiConfig = { mode: "live", lang: "en", contact: false };
let onChange: () => void = () => {};
/** Told once, the first time a request is slow or refused, if no contact is configured. */
let onSlow: (() => void) | null = null;
export function configureWiki(c: Partial<WikiConfig> | undefined, changed: () => void, slow: () => void) {
if (c) config = { ...config, ...c };
onChange = changed;
onSlow = slow;
}
export const wikiConfig = () => config;
const summaries = new Map<string, Loadable<Summary>>();
const articles = new Map<string, Loadable<Article>>();
const senses = new Map<string, Loadable<Sense[]>>();
/** How long a request may take before the reader is told why Wikipedia is slow. */
const SLOW_MS = 2000;
async function get<T>(path: string, key: string, signal?: AbortSignal): Promise<{ ok: true; value: T; stale?: boolean } | ({ ok: false } & Problem)> {
if (config.mode === "off") return { ok: false, reason: "off", message: "Wikipedia is turned off on this server (IE_WIKI=off)." };
const slow = setTimeout(() => slowOnce(), SLOW_MS);
try {
const res = await fetch(path, { signal });
const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (res.ok && body.ok) return { ok: true, value: body[key] as T, stale: !!body.stale };
const reason = String(body.reason ?? "");
if (reason === "rate-limited") slowOnce();
if (res.status === 404 || reason === "missing") return { ok: false, reason: "missing", message: String(body.message ?? "There is no such article.") };
if (reason === "off") return { ok: false, reason: "off", message: String(body.message ?? "Wikipedia is turned off on this server.") };
if (reason === "offline") return { ok: false, reason: "offline", message: "Wikipedia could not be reached. It is tried again in a little while." };
if (reason === "rate-limited") return { ok: false, reason: "rate-limited", message: "Wikipedia asked for fewer requests; try again in a minute." };
return { ok: false, reason: "error", message: String(body.message ?? `The server answered ${res.status}.`) };
} catch (err) {
if ((err as Error).name === "AbortError") throw err;
return { ok: false, reason: "offline", message: "The local server could not be reached." };
} finally {
clearTimeout(slow);
}
}
function slowOnce() {
// The mock has no contact either, and a slow fixture, so the hint can be tested without the network.
if (config.contact || config.mode === "off" || !onSlow) return;
const fn = onSlow;
onSlow = null;
fn();
}
function load<T>(cache: Map<string, Loadable<T>>, key: string, path: string, field: string): Loadable<T> {
const have = cache.get(key);
if (have && (have.state !== "failed" || have.reason === "missing" || have.reason === "off" || Date.now() - have.at < RETRY_MS)) return have;
cache.set(key, { state: "loading" });
void get<T>(path, field).then((r) => {
cache.set(key, r.ok ? { state: "ready", value: r.value, stale: r.stale } : { state: "failed", at: Date.now(), reason: r.reason, message: r.message });
onChange();
});
return cache.get(key)!;
}
const q = (title: string, extra = "") => `title=${encodeURIComponent(title)}${extra}`;
/** An article's summary: the extract, its description, whether it is a disambiguation page. */
export function summary(title: string, lang = config.lang): Loadable<Summary> {
return load(summaries, wikiKey(lang, title), `/api/wiki/summary?${q(wikiTitle(title))}`, "summary");
}
/** The whole article in one request: the lead and every section, each sanitised. */
export function article(title: string, lang = config.lang): Loadable<Article> {
return load(articles, wikiKey(lang, title), `/api/wiki/article?${q(wikiTitle(title), "&full=1")}`, "article");
}
/** The articles a disambiguation page lists. */
export function sensesOf(title: string, lang = config.lang): Loadable<Sense[]> {
return load(senses, wikiKey(lang, title), `/api/wiki/senses?${q(wikiTitle(title))}`, "senses");
}
/** What is already known about an article, without asking for anything. */
export function known(title: string, lang = config.lang): { summary?: Summary; article?: Article } {
const s = summaries.get(wikiKey(lang, title));
const a = articles.get(wikiKey(lang, title));
return { summary: s?.state === "ready" ? s.value : undefined, article: a?.state === "ready" ? a.value : undefined };
}
/**
* The summary only if the server has it cached, within a short wait: grounding for a model prompt,
* which must never wait on Wikipedia.
*/
export async function cachedExtract(title: string, ms = 300): Promise<{ title: string; extract: string } | null> {
const have = known(title).summary;
if (have?.extract) return { title: have.title, extract: have.extract };
if (config.mode === "off") return null;
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), ms);
try {
const res = await fetch(`/api/wiki/summary?${q(wikiTitle(title), "&cached=1")}`, { signal: ac.signal });
if (!res.ok) return null;
const body = (await res.json()) as { summary?: Summary };
return body.summary?.extract ? { title: body.summary.title, extract: body.summary.extract } : null;
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
/** Title suggestions for the link picker. The caller aborts a superseded request, which the server then never sends. */
export async function suggest(text: string, signal: AbortSignal): Promise<Suggestion[] | Problem> {
const r = await get<Suggestion[]>(`/api/wiki/suggest?q=${encodeURIComponent(text.slice(0, 200))}&limit=6`, "suggestions", signal);
return r.ok ? r.value : { reason: r.reason, message: r.message };
}
// ---- untrusted HTML ----
const KEEP = new Set([
"p", "br", "hr", "b", "strong", "i", "em", "u", "s", "sub", "sup", "code", "kbd", "var", "samp", "small", "blockquote",
"q", "ul", "ol", "li", "dl", "dt", "dd", "pre", "table", "caption", "thead", "tbody", "tfoot", "tr", "th", "td", "abbr",
"bdi", "mark", "a", "math", "semantics", "mrow", "mi", "mo", "mn", "ms", "mtext", "mspace", "msub", "msup", "msubsup",
"mfrac", "msqrt", "mroot", "mover", "munder", "munderover", "mtable", "mtr", "mtd", "mstyle", "mpadded", "mphantom",
"menclose", "merror", "mmultiscripts", "mprescripts", "none",
]);
const ATTRS = new Set(["colspan", "rowspan", "start", "data-wiki", "data-wiki-fragment", "data-wiki-anchor", "display", "mathvariant", "stretchy", "displaystyle", "scriptlevel", "fence", "separator", "accent", "accentunder", "lspace", "rspace", "linethickness", "columnalign", "rowalign", "notation", "largeop", "movablelimits", "symmetric", "minsize", "maxsize", "width", "height", "depth", "alttext"]);
/** Elements whose content goes with them. */
const DROP = new Set(["script", "style", "iframe", "object", "embed", "svg", "link", "meta", "base", "form", "template", "noscript", "video", "audio", "img", "picture", "figure", "source", "canvas", "title", "head", "input", "button", "select", "textarea"]);
const cleaned = new Map<string, string>();
/**
* Clean article HTML once more, in an inert document (DOMParser runs no script and loads nothing):
* allowlisted elements and attributes only, wiki links kept as data-wiki, other links only if
* http(s) and then in a new tab without an opener. Remembered per string.
*/
export function cleanHtml(html: string): string {
const have = cleaned.get(html);
if (have !== undefined) return have;
const doc = new DOMParser().parseFromString(`<body>${html}</body>`, "text/html");
const walk = (el: Element) => {
for (const child of [...el.children]) {
const tag = child.localName;
if (DROP.has(tag)) {
child.remove();
continue;
}
walk(child);
if (!KEEP.has(tag)) {
child.replaceWith(...child.childNodes);
continue;
}
const href = tag === "a" ? child.getAttribute("href") : null;
for (const a of [...child.attributes]) if (!ATTRS.has(a.name)) child.removeAttribute(a.name);
if (tag === "a") {
if (child.hasAttribute("data-wiki")) child.setAttribute("href", `https://${config.lang}.wikipedia.org/wiki/${encodeURIComponent(child.getAttribute("data-wiki")!.replace(/ /g, "_"))}`);
else if (href && /^https?:\/\//i.test(href)) {
child.setAttribute("href", href);
child.setAttribute("target", "_blank");
child.setAttribute("rel", "noopener noreferrer nofollow");
}
}
}
};
walk(doc.body);
const out = doc.body.innerHTML;
if (cleaned.size > 400) cleaned.delete(cleaned.keys().next().value as string);
cleaned.set(html, out);
return out;
}
/** The article links in a piece of article HTML, in reading order: what Tab cycles through. */
const linkLists = new Map<string, { title: string; text: string }[]>();
export function wikiLinks(html: string): { title: string; text: string }[] {
let out = linkLists.get(html);
if (out) return out;
const doc = new DOMParser().parseFromString(`<body>${cleanHtml(html)}</body>`, "text/html");
out = [...doc.querySelectorAll("a[data-wiki]")].map((a) => ({ title: a.getAttribute("data-wiki")!, text: a.textContent ?? "" }));
if (linkLists.size > 400) linkLists.delete(linkLists.keys().next().value as string);
linkLists.set(html, out);
return out;
}
/**
* The sections under one (0: the top level) that have something to show: the sanitiser empties
* Notes and References, and a row that opens onto nothing is noise.
*/
export function sectionsUnder(a: Article, parent: number): WikiSection[] {
return a.sections.filter((x) => x.parent === parent && (x.html.trim() !== "" || a.sections.some((y) => y.parent === x.id)));
}
/** The address of an article on Wikipedia itself. */
export const wikiUrl = (title: string, lang = config.lang) => `https://${lang}.wikipedia.org/wiki/${encodeURIComponent(wikiTitle(title).replace(/ /g, "_"))}`;