Focus is a node and a grain. Start on a section, press i to move by sentence, i again by word, and e on
anything to go deeper. Text with a dotted underline already has an expansion; anything else is written on request.
);
}
function CommandBar({ prefill }: { prefill: string }) {
const f = store.focus;
const snap = store.snap;
const n = snap.nodes[f.node];
const words = store.selectedText();
const about = words !== null ? `ask about “${clip(plain(words), 48)}”` : `tell the editor · ${clip(label(snap, f.node), 40)}`;
return (
{about}
{
if (el && document.activeElement !== el) {
el.focus();
el.setSelectionRange(el.value.length, el.value.length);
}
}}
defaultValue={prefill}
placeholder={words !== null ? "why? · example · how does this fail? …" : "add a section on… · tighten this · /branch name · /merge name"}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Escape") {
store.branchFrom = null;
store.setMode("normal");
} else if (e.key === "Enter") {
e.preventDefault();
store.command((e.target as HTMLInputElement).value);
}
}}
onBlur={() => store.mode === "command" && store.setMode("normal")}
/>
);
}
/** What a popup shows for a note: its text; for a link, its target's card; for a note that links, both. */
function PopupBody({ note }: { note: NodeId }) {
const n = store.snap.nodes[note];
return (
<>
{n.body.trim() && }
{n.ref && }
>
);
}
const place = (x: number, top: number, bottom: number): Record => ({
left: `${Math.max(12, Math.min(window.innerWidth - 452, x - 40))}px`,
...(top < 260 ? { top: `${bottom + 8}px` } : { bottom: `${window.innerHeight - top + 8}px` }),
});
/** The hover preview: shown after a pause on a marked span, gone when the pointer leaves it or a key is pressed. */
function Popup() {
const p = store.popup;
const snap = store.snap;
if (!p || !snap.nodes[p.note] || store.open.has(p.note)) return null;
return (
);
}
/**
* The keyboard's preview: while the selection is exactly a link's words, its card shows beside
* them. It is drawn from the focus, so it moves and goes with the focus in the same frame and can
* never outlive it.
*/
function FocusPopup() {
const f = store.focus;
const note = f.grain !== "node" && store.mode === "normal" && !store.popup && !store.aux ? store.noteAt(f.range) : undefined;
const n = note ? store.snap.nodes[note] : undefined;
const ref = useRef(null);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const sel = [...document.querySelectorAll(".sel")].find((x) => x.offsetParent);
if (!sel) return void (el.style.visibility = "hidden");
const r = sel.getBoundingClientRect();
Object.assign(el.style, { left: "", top: "", bottom: "", ...place(r.left + 40, r.top, r.bottom), visibility: "visible" });
});
if (!note || !n?.ref || store.open.has(note)) return null;
return (
);
}
/**
* A research run of the editor, above the status line: each search, page read and edit as it
* happens, then the summary and the sources it linked. Esc stops the run, or puts the panel away.
*/
function AgentPanel() {
const run = store.agentRun;
if (!run?.research) return null;
const all = run.steps;
const steps = all.slice(-8);
return (
editor
{run.running ? "researching on the web · Esc stops" : "done · Esc closes"}
);
}
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"
? store.inArticleText
? store.articleNoteHere()
? "Enter open/enter the note · e toggle · D delete note · Tab next"
: store.auxLink(store.aux)
? `Enter opens “${clip(store.auxLink(store.aux)!.title, 40)}” · e d y x c annotate · W on wikipedia.org`
: `e expand${store.generating ? "" : " (no model)"} · d define · y why · x example · c challenge · : ask · Esc widen`
: `Wikipedia · j k rows · l open · h back · i select words · Tab links and notes · 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.commentaryAt(f.range)
? `Enter opens the note with ${store.targetOf(store.commentaryAt(f.range)!)!.kind === "wiki" ? "its article" : "what it links to"} · e shows the note here · D delete note · w retarget`
: 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 (
);
}
// ---- the app ----
/** The offset in its text of a DOM position inside a piece marked with data-o. */
function locateIn(node: Node, offset: number): number | null {
const el = node instanceof Element ? node : node.parentElement;
const piece = el?.closest("[data-o]");
return piece ? Number(piece.dataset.o) + (node instanceof Text ? offset : 0) : null;
}
/** Map a DOM position inside a body to (node, offset). */
function locate(node: Node | null, offset: number): { id: NodeId; at: number } | null {
const el = node instanceof Element ? node : node?.parentElement;
const piece = el?.closest("[data-o]");
const body = el?.closest("[data-body]");
if (!piece || !body) return null;
return { id: body.dataset.body as NodeId, at: Number(piece.dataset.o) + (node instanceof Text ? offset : 0) };
}
let hover: ReturnType | undefined;
export function App() {
const [, tick] = useReducer((x: number) => x + 1, 0);
const [prefill, setPrefill] = useState("");
const [verdict, setVerdict] = useState("");
useEffect(() => store.subscribe(() => tick(0)), []);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
clearTimeout(hover);
if (store.popup) {
store.popup = null;
store.emit(store.top);
}
handleKey(e, {
openCommand(text = "") {
setPrefill(text);
store.setMode("command");
},
verify() {
const t = performance.now();
const v = verifyHistory(store.doc);
setVerdict(
v.mismatches.length
? `${v.mismatches.length} of ${v.checked} commits do NOT reproduce their recorded hash.`
: `Verified: all ${v.checked} hashed commits reproduce byte-for-byte${v.unhashed ? ` (${v.unhashed} undo/redo steps carry no hash)` : ""}. ${Math.round(performance.now() - t)} ms.`,
);
},
});
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, []);
// `auto` picks the layout from the window's width, so follow the width.
useEffect(() => {
const onResize = () => {
const wide = window.innerWidth >= PANES_MIN_WIDTH;
if (wide === store.wide) return;
store.wide = wide;
if (store.settings.view === "auto") store.emit();
};
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, []);
// Keep the focused thing in view, and time keypress → paint.
useLayoutEffect(() => {
if (!store.ready) return;
const f = store.focus;
// The panes keep their own focus in view (Panes.tsx).
const el =
!store.panes &&
((f.grain !== "node" && document.querySelector(".sel")) ||
document.querySelector(`[data-row="${CSS.escape(f.node)}"]`) ||
document.querySelector(`[data-node="${CSS.escape(f.node)}"]`));
if (el && store.mode !== "edit") el.scrollIntoView({ block: "nearest" });
store.clean();
const t = store.t0;
if (t) {
store.t0 = null;
requestAnimationFrame(() => {
const ch = new MessageChannel();
ch.port1.onmessage = () => store.addSample(t, performance.now() - t.at);
ch.port2.postMessage(0);
});
}
});
if (store.fatal) return
{store.fatal}
;
if (!store.ready) return
Loading…
;
const panes = store.panes;
// A click opens beside what is open (so do Ctrl-, Cmd- and middle clicks); a Shift-click in its place.
const onClick = (e: MouseEvent) => store.withReplace(e.shiftKey, () => click(e));
const click = (e: MouseEvent) => {
if (store.mode === "edit") return;
const target = e.target as HTMLElement;
// A pane's × and pin act on that pane, wherever the focus is.
const ctl = target.closest("[data-close], [data-pin]");
if (ctl) return ctl.dataset.close ? store.closePane(Number(ctl.dataset.close)) : store.togglePanePin(Number(ctl.dataset.pin));
const paneEl = target.closest("[data-pane-index]");
const paneIndex = paneEl ? Number(paneEl.dataset.paneIndex) : store.paneAt;
// A pane in another fork: that fork becomes the focused branch first, then the click does what it would there.
const tid = paneEl ? Number(paneEl.dataset.tid) : undefined;
if (tid !== undefined && store.branchNodes[paneIndex]?.id !== tid) store.enterFork(tid);
// A covered pane's spine brings that pane back by focusing it.
const spine = target.closest("[data-spine]");
if (spine) return store.land(Number(spine.dataset.spine));
// 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 named = target.closest("[data-host]")?.dataset.host;
// An article pane off the branch is named by its place in the tree; on the branch, by its column.
const host = named?.startsWith("f") ? `p${paneIndex}` : named;
const a = target.closest("a");
if (a && host) {
if (a.dataset.wiki) {
e.preventDefault();
store.paneAt = paneIndex;
const h = store.wikiHost(host);
return store.follow({ kind: "wiki", title: a.dataset.wiki, lang: h?.lang ?? store.wiki.lang });
}
if (!/^https?:/.test(a.getAttribute("href") ?? "")) e.preventDefault();
return;
}
if (a && target.closest(".wattr")) return;
const wrow = target.closest("[data-wrow], [data-sense]");
if (wrow && host) {
store.paneAt = paneIndex;
const id = Number(wrow.dataset.wrow);
const ss = wrow.dataset.sense;
if (ss) return store.follow({ kind: "wiki", title: ss, lang: store.wikiHost(host)?.lang ?? store.wiki.lang });
store.setFocus(store.focus, { kind: "wiki", host, row: { t: "sec", id } } as Aux);
return store.auxActivate();
}
const linking = target.closest("[data-linking]");
if (linking) {
store.paneAt = paneIndex;
return store.openLinking(linking.dataset.linking as NodeId);
}
const related = target.closest("[data-related]");
if (related) {
store.paneAt = paneIndex;
return store.follow(nodeRef(store.snap, related.dataset.related as NodeId));
}
const targetRow = target.closest("[data-target]");
if (targetRow) {
store.paneAt = paneIndex;
const r = store.targetOf(targetRow.dataset.target as NodeId);
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();
// In an article's text: a drag selects words, an annotation's words open it, a click selects the sentence.
const wtext = target.closest("[data-wtext]");
if (host && wtext && !target.closest("[data-node]")) {
store.paneAt = paneIndex;
const row = (wtext.dataset.wtext === "head" ? { t: "head" } : { t: "sec", id: Number(wtext.dataset.wtext) }) as WRow;
const at = (n: Node | null, o: number) => (n && wtext.contains(n) ? locateIn(n, o) : null);
const a = selection && !selection.isCollapsed ? at(selection.anchorNode, selection.anchorOffset) : null;
const b = selection && !selection.isCollapsed ? at(selection.focusNode, selection.focusOffset) : null;
if (a !== null && b !== null && a !== b) {
selection!.removeAllRanges();
return store.selectInArticle(host, row, [Math.min(a, b), Math.max(a, b)], "word");
}
const note = target.closest("[data-note]")?.dataset.note as NodeId | undefined;
if (note) return store.toggleAnnotation(host, row, note);
const o = selection ? at(selection.anchorNode, selection.anchorOffset) : null;
if (o !== null) return store.selectInArticle(host, row, [o, o], "sentence");
return;
}
// A drag selection inside one body becomes the focus range.
if (selection && !selection.isCollapsed && !store.replacing) {
const a = locate(selection.anchorNode, selection.anchorOffset);
const b = locate(selection.focusNode, selection.focusOffset);
if (a && b && a.id === b.id && a.at !== b.at) {
store.go(a.id, "word", [Math.min(a.at, b.at), Math.max(a.at, b.at)]);
selection.removeAllRanges();
return;
}
}
const anchor = target.closest("[data-note]");
if (anchor?.dataset.note) {
const id = anchor.dataset.note as NodeId;
const n = store.snap.nodes[id];
const a = n.anchors[0];
store.popup = null;
// Words with a note and a target open as one page: the note's text, then the article.
const both = store.commentaryAt([a.start, a.end], n.parent!);
if (both) {
store.paneAt = paneIndex;
store.go(n.parent!, "word", [a.start, a.end]);
return store.openCommentary(both);
}
if (n.ref && (store.panes || store.open.has(id)) && !n.body.trim()) {
// A link: in panes it opens next to its pane; in the column, once its preview is open.
store.paneAt = paneIndex;
store.go(n.parent!, "word", [a.start, a.end]);
return store.follow(n.ref);
}
if (store.open.has(id)) store.open.delete(id);
else store.open.add(id);
store.go(n.parent!, "word", [a.start, a.end]);
if (!store.open.has(id)) store.saveView();
return;
}
const row = target.closest("[data-row]");
if (row) {
const id = row.dataset.row as NodeId;
if (panes && id !== store.top) {
// In panes a click shows the row's pane: focus it and open it next (or focus it where it is open).
store.paneAt = paneIndex;
store.go(id);
store.open.add(id);
const holder = store.trail[paneIndex];
if (store.snap.nodes[id]?.kind === "section" && holder?.kind === "node" && store.snap.nodes[id].parent === holder.id) store.openPane(paneIndex, { kind: "node", id });
return;
}
store.go(id);
if (id !== store.top) store.toggle(id);
return;
}
const at = selection && locate(selection.anchorNode, selection.anchorOffset);
if (at) {
const all = sentences(store.snap.nodes[at.id].body);
const hit = all.find((r) => at.at >= r[0] && at.at <= r[1]);
if (hit) return store.go(at.id, "sentence", hit);
}
const node = target.closest("[data-node]");
if (!node) return;
// A pane's head makes that pane the active one.
if (panes && paneEl && node.matches(".pane-head, .top")) store.paneAt = paneIndex;
store.go(node.dataset.node as NodeId);
};
const onOver = (e: MouseEvent) => {
const anchor = (e.target as HTMLElement).closest("[data-note]");
clearTimeout(hover);
if (!anchor?.dataset.note || store.open.has(anchor.dataset.note as NodeId)) {
if (store.popup) hover = setTimeout(() => ((store.popup = null), store.emit(store.top)), 150);
return;
}
const r = anchor.getBoundingClientRect();
const note = anchor.dataset.note as NodeId;
hover = setTimeout(() => ((store.popup = { note, x: e.clientX, top: r.top, bottom: r.bottom }), store.emit(store.top)), 450);
};
return (
e.button === 1 && (e.preventDefault(), onClick(e))}
// A Shift-click would extend the text selection, and a middle press scrolls or pastes: neither, when they open a fork.
onMouseDown={(e) => (e.shiftKey || e.button === 1) && !(e.target as HTMLElement).closest("input, textarea") && e.preventDefault()}
>
{store.preview && (
Viewing “{clip(store.preview.commit.message, 70)}” by {store.preview.commit.by}, {ago(store.preview.commit.time)}. Read-only.