UI without documents: every page a node, the library root the first; moving, copying, exporting and importing any node

The page has one head for whatever node is the page (crumbs from the library's title, a byline of
sections and nodes, its flags and ⋯); in panes the first pane is the page and every other pane has
a section's head, whatever node it shows. A prompt (a node whose sections cite its sentences) is
folded wherever it shows. The library root's sections open in place like any others; an address
outside the hoisted node un-hoists to the library, and Esc at a hoisted page's top steps out to its
parent's.

What acts on a node and everything under it acts on the node the reader is on (the focused
section, or the one a focused note or selection is in): M moves it under any node (the jump box as
a picker, the root offered too), /duplicate copies it just after itself, /export saves it, /import
reads a file in as its last child (place() prefixes the titles down to the parent), /linkhere scans
it, S lists its links (on the root, the whole library's), history's f filters to it and r reverts
it. Every node's ⋯ offers them.

The documents menu, its mode and keys, /new, /open, /rename and /linkdoc are gone; m is free and
the top bar's left is a plain label with the library's name. Addresses are /n/<node id>, and / the
root; an old /doc/ address shows the library.

Server: /api/docs gives way to /api/nodes/<id>/{tree,export,import}; link jobs take scope "node" or
"library" and pending lists ?node=<id>&subtree=1. Step-1 shims removed: docOf/documents, all of
core/library.ts (IMPORT_MAX and importTree move to seed.ts, address and resolve to address.ts),
docArg, and the old single-document replica check. revertDocTo is revertSubtreeTo.

The page scrolls the focus into view only when the focus, the page or the mode changed, not on a
render for something that arrived in the background; row flags give way on a narrow screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Opus 5.5 committed 2026-11-17 01:49:12 -05:00
1 parent e6e4ad8d26
commit bed47c0c7a
31 files changed
+789 -1153

No files matched your search

+51 -26
View File
@@ -1,11 +1,11 @@
import { useEffect, useLayoutEffect, useReducer, useRef, useState } from "preact/hooks";
import { ancestors, ancestorsBelowRoot, docOf, label, sections, staleness, type Conflict, type NodeId } from "../core/model";
import { ancestors, isLibraryRoot, label, sections, staleness, type Conflict, type NodeId } from "../core/model";
import { verifyHistory, type Commit } from "../core/repo";
import { clip, plain } from "../core/text";
import { hostOf } from "../core/ref";
import { nodeRef } from "../core/links";
import { HELP, handleKey } from "./keys";
import { DocBar, DocsPanel } from "./Menu";
import { DocBar } from "./Menu";
import { LinkCard, LinkPicker, LinksPanel, NodeBacklinks, NodeRelated, TargetRow } from "./Links";
import { NodeBody, Outline, PendingSections, TopMatter } from "./Node";
import { Panes } from "./Panes";
@@ -18,15 +18,14 @@ import { press } from "./press";
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 && (store.articleUnder(store.top) ? <WikiView host={`n${store.top}`} /> : <TargetRow id={store.top} />)}
{!listing && <NodeBacklinks id={store.top} />}
{!listing && <NodeRelated id={store.top} />}
{store.articleUnder(store.top) ? <WikiView host={`n${store.top}`} /> : <TargetRow id={store.top} />}
<NodeBacklinks id={store.top} />
<NodeRelated id={store.top} />
</article>
);
}
@@ -96,12 +95,15 @@ function HistoryPanel({ verdict }: { verdict: string }) {
});
const heads = new Set<string>();
let lastType = "";
const live = store.doc.snap();
const filter = store.historyFilter && live.nodes[store.historyFilter] ? store.historyFilter : null;
const onRoot = isLibraryRoot(live, store.activeNode);
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>History{filter ? ` · ${clip(label(store.doc.snap(), filter), 30)}` : " · the library"}</span>
<span class="keys">
<Hints hint={["j k", ["Enter", "view"], ["r", `revert${store.currentDoc ? " this document" : ""}`], ["n", "branch"], ["m", "merge"], ["f", store.historyFilter ? "everything" : "this document"], ["v", "verify"], ["Escape", "close"]]} />
<Hints hint={["j k", ["Enter", "view"], ["r", `revert ${onRoot ? "the library" : "this node"}`], ["n", "branch"], ["m", "merge"], ["f", filter ? "everything" : "this node"], ["v", "verify"], ["Escape", "close"]]} />
</span>
</div>
{verdict && <div class="verdict">{verdict}</div>}
@@ -138,7 +140,7 @@ function HistoryPanel({ verdict }: { verdict: string }) {
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 ?? "");
const under = store.touchedTops(c).map((d) => snap.nodes[d]?.title ?? "");
return (
<div class={`item commit${selected ? " selected" : ""}${viewing ? " viewing" : ""}`}>
<div class="line">
@@ -152,9 +154,9 @@ function CommitRow({ c, selected }: { c: Commit; selected: boolean }) {
{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(" · ")}
{under.length > 0 && (
<div class="under" title={under.join(", ")}>
under: {under.length > 3 ? `${under.slice(0, 3).map((t) => clip(t, 24)).join(" · ")} · and ${under.length - 3} more` : under.map((t) => clip(t, 30)).join(" · ")}
</div>
)}
</div>
@@ -193,19 +195,26 @@ function Help() {
);
}
function Jump() {
/**
* The jump box (/): sections anywhere in the library, by title and text. The same box is the
* picker of Move under… (M), where it offers the library root too and never the node being moved.
*/
function Jump({ move }: { move?: boolean }) {
const [q, setQ] = useState("");
const [i, setI] = useState(0);
const hits = store.search(q);
const hits = move ? store.moveTargets(q) : store.search(q);
const snap = store.snap;
const close = () => store.setMode("normal");
const close = () => (move ? store.cancelMove() : store.setMode("normal"));
const pick = (id: NodeId) => (move ? store.moveUnder(id) : store.jumpTo(id));
const moving = move && store.moving && snap.nodes[store.moving] ? label(snap, store.moving) : "";
return (
<div class="overlay" onClick={close}>
<div class="jump" onClick={(e) => e.stopPropagation()}>
<div class={`jump${move ? " move" : ""}`} onClick={(e) => e.stopPropagation()}>
{move && <div class="jump-head">Move “{clip(moving, 50)}” and everything under it under…</div>}
<input
autoFocus
ref={(el) => el?.focus()}
placeholder="Jump to a section, in any document…"
placeholder={move ? "The node to move it under…" : "Jump to a section, anywhere in the library…"}
value={q}
onInput={(e) => (setQ((e.target as HTMLInputElement).value), setI(0))}
onKeyDown={(e) => {
@@ -213,19 +222,27 @@ function Jump() {
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]);
else if (e.key === "Enter" && hits[i]) pick(hits[i]);
}}
/>
<ul>
{hits.map((id, k) => {
const d = docOf(snap, id);
const within = ancestorsBelowRoot(snap, id).reverse().slice(1);
// Where it is: the titles down to it from the library root, the first of them bold.
const path = ancestors(snap, id).reverse().slice(1);
return (
<li key={id} class={k === i ? "selected" : ""} onClick={() => store.jumpTo(id)}>
<li key={id} class={k === i ? "selected" : ""} data-hit={id} onClick={() => pick(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(" › ")}` : ""}
{isLibraryRoot(snap, id) ? (
<b class="in">the library root</b>
) : path.length ? (
<>
<b class="in">{snap.nodes[path[0]].title}</b>
{path.length > 1 ? ` › ${path.slice(1).map((a) => snap.nodes[a].title).join(" › ")}` : ""}
</>
) : (
<b class="in">{label(snap, snap.root)}</b>
)}
</span>
</li>
);
@@ -438,6 +455,8 @@ function StatusLine() {
// ---- the app ----
let hover: ReturnType<typeof setTimeout> | undefined;
/** The focus last scrolled into view (App's layout effect). */
let shownFocus = "";
export function App() {
const [, tick] = useReducer((x: number) => x + 1, 0);
@@ -508,8 +527,14 @@ export function App() {
useLayoutEffect(() => {
if (!store.ready) return;
const f = store.focus;
// The panes keep their own focus in view (Panes.tsx).
// Only when the focus, the page or the mode has changed: a render for something that arrived
// in the background (a list fetched, a scan's suggestions) leaves the page where the reader
// scrolled it. The panes keep their own focus in view (Panes.tsx).
const key = JSON.stringify([f, store.aux, store.mode, store.panes, store.top, store.colWiki?.title]);
const moved = key !== shownFocus;
shownFocus = key;
const el =
moved &&
!store.panes &&
((f.grain !== "node" && document.querySelector(".sel")) ||
document.querySelector(`[data-row="${CSS.escape(f.node)}"]`) ||
@@ -705,7 +730,7 @@ export function App() {
};
return (
<div class={`app mode-${store.mode}${store.mode === "history" || store.mode === "docs" || store.mode === "review" ? " with-panel" : ""}${panes ? " view-panes" : ""}`} onMouseOver={onOver} onContextMenu={onContext}>
<div class={`app mode-${store.mode}${store.mode === "history" || store.mode === "review" ? " with-panel" : ""}${panes ? " view-panes" : ""}`} onMouseOver={onOver} onContextMenu={onContext}>
<main
class="page"
onClick={onClick}
@@ -722,10 +747,10 @@ export function App() {
{panes ? <Panes /> : <Page />}
</main>
{store.mode === "history" && <HistoryPanel verdict={verdict} />}
{store.mode === "docs" && <DocsPanel />}
{store.mode === "review" && <LinksPanel />}
{store.mode === "help" && <Help />}
{store.mode === "jump" && <Jump />}
{store.mode === "move" && <Jump move />}
{store.mode === "command" && <CommandBar prefill={prefill} />}
{store.mode === "link" && store.picker && <LinkPicker />}
<Popup />
+34 -21
View File
@@ -6,7 +6,7 @@
import { Fragment, createContext } from "preact";
import { useContext, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
import { ownerSection, resolveNode } from "../core/links";
import { docOf, isLink, label, type NodeId } from "../core/model";
import { isLibraryRoot, isLink, label, topOf, type NodeId, type Snap } from "../core/model";
import { describeTarget, hostOf, parseTarget, validateRef, wikiTitle, type Ref } from "../core/ref";
import { clip, plain } from "../core/text";
import { kidClass, sameAux, store, type Aux } from "./store";
@@ -17,15 +17,21 @@ import { suggest, summary, wikiConfig, type Attribution as Attr, type Suggestion
const MARK: Record<Ref["kind"], string> = { wiki: "W", node: "§", url: "↗" };
/** The document a node target is in, for its mark's tooltip. */
/** Where a node is, in a word: the title of the top-level node it is under, or for a top-level node itself, the library's. */
export function whereIs(s: Snap, id: NodeId): string {
const t = topOf(s, id);
return t && t !== id ? s.nodes[t].title : label(s, s.root);
}
/** Where a node target is, 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}` : ""}`;
const t = topOf(s, id);
return `${label(s, id)}${t && t !== id ? ` · in ${s.nodes[t].title}` : ""}`;
}
/** The mark set after linked words. Not text of the body: it carries no offset and cannot be selected. */
@@ -56,7 +62,7 @@ export function Attribution({ a }: { a: Attr }) {
);
}
/** What a target is, briefly: an article's summary, a node's title, document and first lines, a page's host. */
/** What a target is, briefly: an article's summary, a node's title, where it is and first lines, a page's host. */
export function LinkCard({ r, compact }: { r: Ref; compact?: boolean }) {
if (r.kind === "url") {
return (
@@ -80,13 +86,13 @@ export function LinkCard({ r, compact }: { r: Ref; compact?: boolean }) {
</div>
);
}
const d = docOf(s, id);
const d = topOf(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"}
<span class="lmark l-node">§</span> {d ? s.nodes[d].title : label(s, s.root)}
{sec !== d && n.kind === "note" ? ` › ${label(s, sec)}` : ""}
</div>
<div class="ltitle">{label(s, id)}</div>
@@ -163,7 +169,7 @@ export function useForkMark(): ((...keys: (string | undefined)[]) => string) | n
}
/**
* "Linked from": the nodes that link here, each as its section's title and its document. Collapsed
* "Linked from": the nodes that link here, each as its section's title and where it is. 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 }) {
@@ -176,12 +182,11 @@ export function Backlinks({ ids, title, focusedAt }: { ids: NodeId[]; title: str
<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", forkMark?.(`n:${sec}`)].filter(Boolean).join(" ")} data-linking={id}>
<span class="bl-title">{label(s, sec)}</span>
<span class="bl-doc">{d && d !== sec ? s.nodes[d].title : "document"}</span>
<span class="bl-doc">{whereIs(s, sec)}</span>
{n.kind === "note" && <span class="bl-quote">“{clip(n.anchors[0]?.text ?? "", 60)}”</span>}
</li>
);
@@ -205,7 +210,7 @@ export function SuggestionCard({ sg }: { sg: Sugg }) {
}
/**
* "Related": sections of other documents close in meaning to this one, derived and never stored.
* "Related": sections elsewhere in the library 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.
*/
@@ -245,11 +250,10 @@ export interface Choice {
ref: Ref;
}
/** A section of the library as a choice, with the document it is in. */
/** A section of the library as a choice, with where it is. */
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 } };
return { group: "Library", label: s.nodes[id].title || "(untitled)", sub: whereIs(s, id), ref: { kind: "node", id } };
}
/** A Wikipedia title suggestion as a choice. */
@@ -307,8 +311,8 @@ function libraryChoices(q: string, spot: NodeId): Choice[] {
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 } });
const d = topOf(s, n.id);
out.push({ group: "Library", label: `“${clip(n.anchors[0].text, 50)}”`, sub: `note in ${d ? s.nodes[d].title : label(s, s.root)} › ${label(s, ownerSection(s, n.id))}`, ref: { kind: "node", id: n.id } });
}
return out;
}
@@ -377,6 +381,9 @@ export function LinkPicker() {
// ---- the links list (S) ----
/** Rows of the links list drawn at once, around the selected one. */
const WINDOW = 200;
const FILTERS: [key: string, status: Status, label: string][] = [
["1", "linked", "linked"],
["2", "rejected", "rejected"],
@@ -397,7 +404,8 @@ function verdictLine(r: LinkRow): string {
}
/**
* The links list (S): every link found or made in the current document, as it stands, with who
* The links list (S): every link found or made in a node and everything under it (on the library
* root, the whole library), as it stands, with who
* decided and the reviewer's reason. Quiet toggles filter it by status; the selected row's words
* are selected in the text, and every key it takes is a button in its head.
*/
@@ -412,12 +420,15 @@ export function LinksPanel() {
const rows = all.filter((x) => r.show[x.status]);
const sel = store.reviewRow();
const s = store.snap;
const doc = store.currentDoc;
const count = (st: Status) => all.filter((x) => x.status === st).length;
// A whole library's list can be long: the rows around the selected one are drawn, the rest counted.
const at = Math.max(0, rows.findIndex((x) => x.key === sel?.key));
const from = Math.max(0, Math.min(at - WINDOW / 2, rows.length - WINDOW));
const shown = rows.slice(from, from + WINDOW);
return (
<aside class="panel links" ref={ref} data-links-panel>
<div class="panel-head">
<span>Links{doc ? ` · ${clip(s.nodes[doc]?.title ?? "", 30)}` : ""}</span>
<span>Links · {isLibraryRoot(s, r.node) ? "the library" : clip(label(s, r.node), 30)}</span>
<span class="keys">
<Hints hint={["j k", ...(sel?.status !== "linked" ? [["y", "link"] as [string, string]] : []), ...(sel?.status !== "rejected" ? [["n", sel?.status === "linked" ? "remove" : "decline"] as [string, string]] : []), ["Y", "link all"], ["Enter", "go"], ["Escape", "close"]]} />
</span>
@@ -432,8 +443,9 @@ export function LinksPanel() {
</Fragment>
))}
</div>
{!rows.length && <p class="lempty">{all.length ? "Nothing shown: 1 2 3 show more." : "Nothing linked or found here yet. :/linkdoc looks for links in this document."}</p>}
{rows.map((x) => (
{!rows.length && <p class="lempty">{all.length ? "Nothing shown: 1 2 3 show more." : "Nothing linked or found yet. :/linkall looks for links in the whole library, :/linkhere in the node you are on."}</p>}
{from > 0 && <p class="lmore">{from} more above</p>}
{shown.map((x) => (
<div key={x.key} class={`item lrow ${x.status}${x.key === sel?.key ? " selected" : ""}`} data-row={x.status} onClick={() => store.reviewSelect(x.key)}>
<div class="line">
<span class="lq">“{clip(x.quote, 48)}”</span>
@@ -449,6 +461,7 @@ export function LinksPanel() {
</div>
</div>
))}
{from + shown.length < rows.length && <p class="lmore">{rows.length - from - shown.length} more below</p>}
</aside>
);
}
+7 -174
View File
@@ -1,8 +1,6 @@
/** 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";
/** The top bar: where the reader is (the library's name) and whether it is saved, with undo and the menu. */
import { topEntries } from "./actions";
import { Hints, act, showMenu } from "./Mouse";
import { act, showMenu } from "./Mouse";
import { press } from "./press";
import { store } from "./store";
@@ -19,22 +17,12 @@ const SAVE_TITLE = {
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="lib-name" title="The library">
{snap.nodes[snap.root].title || "Library"}
</span>
<span class={`save-state ${state}`} title={SAVE_TITLE[state]}>
{SAVE_LABEL[state]}
</span>
@@ -51,12 +39,12 @@ export function DocBar() {
type="button"
class="tool"
aria-haspopup="menu"
title="Documents, history, layout and settings"
title="Jump, history, links, layout and settings"
onMouseDown={keep}
onClick={(e) => {
e.stopPropagation();
const s = store.settings;
showMenu(topEntries({ view: s.view, autolink: s.autolink, auto: s.auto, speculate: s.speculate, curves: s.curves, colors: s.colors, panes: store.panes, doc: !!store.currentDoc, canRedo: store.canRedo() }, act), e.currentTarget as HTMLElement);
showMenu(topEntries({ view: s.view, autolink: s.autolink, auto: s.auto, speculate: s.speculate, curves: s.curves, colors: s.colors, panes: store.panes, canRedo: store.canRedo() }, act), e.currentTarget as HTMLElement);
}}
>
menu<span class="chev" />
@@ -65,158 +53,3 @@ export function DocBar() {
</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">
<Hints hint={typing ? ["type to filter · ↑ ↓", ["Enter", "open"], ["Escape", "for actions"]] : ["j k", ["Enter", "open"], ["n", "new"], ["r", "rename"], ["s", "save as"], ["D", "delete"], ["x", "export"], ["i", "import"], ["/", "filter"], ["Escape", "close"]]} />
</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, true);
} 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, true)}
>
<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, true))}>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>
);
}
+7 -6
View File
@@ -10,9 +10,9 @@
import { Fragment, type ComponentChildren } from "preact";
import { createPortal } from "preact/compat";
import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
import { docOf, isLibraryRoot, label, staleness, type NodeId } from "../core/model";
import { isLibraryRoot, label, staleness, topOf, type NodeId } from "../core/model";
import { plain } from "../core/text";
import { articleRowEntries, barItems, nodeEntries, pageAct, pageEntries, paneEntries, selectionEntries, topEntries, type Entry, type Item, type NodeCtx, type SelCtx } from "./actions";
import { articleRowEntries, barItems, nodeEntries, pageAct, paneEntries, selectionEntries, topEntries, type Entry, type Item, type NodeCtx, type SelCtx } from "./actions";
import { press } from "./press";
import { store, type WRow } from "./store";
@@ -69,7 +69,6 @@ function nodeCtx(id: NodeId): NodeCtx {
locked: n.pinned,
target: !!store.targetOf(id),
library: isLibraryRoot(s, id),
doc: docOf(s, id) === id,
generating: store.generating,
};
}
@@ -88,7 +87,10 @@ function selCtx(): SelCtx {
link: r?.kind,
note: !!id && !!s.nodes[id].body.trim(),
suggestion: store.focusedSuggestion()?.title,
related: store.relatedOf(f.node).map((x) => ({ title: x.title, doc: s.nodes[docOf(s, x.node) ?? x.node]?.title })),
related: store.relatedOf(f.node).map((x) => {
const t = s.nodes[x.node] ? topOf(s, x.node) : null;
return { title: x.title, where: t && t !== x.node ? s.nodes[t].title : undefined };
}),
panes: store.panes,
};
}
@@ -112,7 +114,6 @@ export function menuHere(where: Where): Entry[] {
const id = store.focus.node;
if (!store.snap.nodes[id]) return [];
if (where === "pane" && store.panes) return paneEntries({ node: nodeCtx(id), pinned }, act);
if (where === "page") return pageEntries(nodeCtx(id), act);
return nodeEntries(nodeCtx(id), act);
}
@@ -524,7 +525,7 @@ export function Key({ k, what, shift }: { k: string; what: ComponentChildren; sh
return (
<button type="button" class="key" data-key={k} title={`${keyText(k)}`} onMouseDown={(e) => e.preventDefault()} onClick={(e) => {
e.stopPropagation();
// A box being typed in (the documents filter) gives the key back to the page.
// A box being typed in (the jump box, the command line) gives the key back to the page.
if ((document.activeElement as HTMLElement | null)?.matches?.("input, textarea")) (document.activeElement as HTMLElement).blur();
press(k, shift);
}}
+32 -16
View File
@@ -1,7 +1,7 @@
/** 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 { anchorLost, ancestors, descendants, 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";
@@ -11,7 +11,7 @@ import { store, type Pending } from "./store";
// ---- inline text ----
/** A note as the renderer sees it: one in the document, or one still being written. */
/** A note as the renderer sees it: one in the library, or one still being written. */
export interface VNote {
key: string;
id?: NodeId;
@@ -286,7 +286,7 @@ export function NodeBody({ id, inline, inNote }: { id: NodeId; inline?: boolean;
))}
{!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" : ""}.`}
{isLibraryRoot(snap, id) ? "This is the library, the root of everything in it. a adds a section, / jumps anywhere, :/import reads a .md file into it; 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) => (
@@ -403,7 +403,7 @@ function SectionView({ id }: { id: NodeId }) {
<Row id={id} open={open} leaf={leaf} editing={editing} />
{open && (
<div class="content">
<NodeBody id={id} />
{isPrompt(snap, id) ? <Abstract id={id} /> : <NodeBody id={id} />}
{kids.length > 0 && <Outline ids={kids} />}
<PendingSections id={id} />
<TargetRow id={id} />
@@ -426,9 +426,31 @@ export function Outline({ ids }: { ids: NodeId[] }) {
}
/**
* 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.
* Whether a node's text is a prompt: its sections cite its sentences (the first tree's top is one).
* A prompt is long, and the page should open on the outline, so it is folded until asked for.
*/
export function isPrompt(snap: Snap, id: NodeId): boolean {
return !isLibraryRoot(snap, id) && sections(snap, id).some((k) => snap.nodes[k].anchors.length > 0);
}
/** A node's own text under its head: plain, or a prompt, set apart and folded until asked for. */
export function Abstract({ id }: { id: NodeId }) {
const snap = store.snap;
const prompt = isPrompt(snap, id);
const folded = prompt && !store.unfolded.has(id) && !(store.focus.node === id && store.focus.grain !== "node") && store.edit?.node !== id;
return (
<>
<div class={`abstract${prompt ? " seed" : ""}${folded ? " folded" : ""}`} onClick={folded ? () => store.toggleFold(id) : undefined}>
<NodeBody id={id} />
</div>
{folded && <div class="unfold">{id === store.top ? "Enter" : "A click"} to read the whole prompt · every sentence of it is traced to a section below</div>}
</>
);
}
/**
* The head of a page, the same for every node: crumbs (the titles above it, from the library's
* own), title, byline (its sections and nodes, the branch, its flags and its ⋯), and its own text.
*/
export function TopMatter({ id }: { id: NodeId }) {
const snap = store.snap;
@@ -439,10 +461,7 @@ export function TopMatter({ id }: { id: NodeId }) {
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;
// The library root's count leaves out the Wikipedia container, which is nobody's section.
const count = library ? kids.reduce((n, d) => n + 1 + descendants(snap, d).length, 0) : descendants(snap, id).length;
return (
<>
@@ -460,16 +479,13 @@ export function TopMatter({ id }: { id: NodeId }) {
<div class="byline">
{n.kind === "note"
? `a note in ${clip(label(snap, ownerSection(snap, id)), 40)}${n.by === "llm" ? ", written by the model" : ""}`
: `${library ? `${kids.length} document${kids.length === 1 ? "" : "s"}` : `${kids.length} section${kids.length === 1 ? "" : "s"}`} · ${count} nodes`}{" "}
: `${library ? "library · " : ""}${kids.length} section${kids.length === 1 ? "" : "s"} · ${count} nodes`}{" "}
· branch {store.repo.current}
<Flags id={id} />
<button type="button" class="more" data-more="page" tabIndex={-1} aria-haspopup="menu" title="More for this page (right-click works too)">⋯</button>
</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>}
<Abstract id={id} />
</>
);
}
+10 -9
View File
@@ -1,7 +1,7 @@
/**
* The panes view: 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
* (a node from anywhere in the library, a Wikipedia article, a section of one), replacing what was to the
* right. Moving back left closes nothing: the panes stay until something else is opened from an
* earlier pane, or q or a pane's × closes them. Earlier columns stay at the left as narrow spines
* when later ones slide over them.
@@ -17,11 +17,11 @@
*/
import { Component, type ComponentChildren } from "preact";
import { useEffect, useLayoutEffect, useRef } from "preact/hooks";
import { docOf, label, sections, staleness, type NodeId } from "../core/model";
import { ancestors, label, sections, staleness, type NodeId } from "../core/model";
import { LANES, LANE_FIRST, LANE_LAST, LANE_PITCH, laneOrder } from "./lanes";
import { ACROSS, DOWN, mark, offsets, reveal, starts, stick, unmark, whole } from "./stack";
import { NodeBacklinks, NodeRelated, PaneCtx, TargetRow } from "./Links";
import { Flags, NodeBody, PendingSections, Row, TitleEditor, TopMatter } from "./Node";
import { Abstract, Flags, NodeBody, PendingSections, Row, TitleEditor, TopMatter, isPrompt } from "./Node";
import { kidClass, refKey, store, type Aux, type Pane as PaneNode, type PaneRef } from "./store";
import { WikiView } from "./Wiki";
import { article } from "./wiki";
@@ -170,9 +170,9 @@ function NodePane(props: PaneProps & { id: NodeId }) {
const snap = store.snap;
const n = snap.nodes[id];
if (!n) return null;
// The first pane is the page, headed like the column's page (crumbs, byline, its ⋯); every other
// pane has a section's head, whatever node it shows.
const top = props.root && id === store.top;
// 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";
@@ -183,23 +183,24 @@ function NodePane(props: PaneProps & { id: NodeId }) {
const forked = new Set(t.kids.flatMap((k, j) => (j !== t.pick && k.ref.kind === "node" && store.continuesFrom(k.ref, props.p) ? [k.ref.id] : [])));
return (
<article
class={`pane${top ? " root" : ""}${page && !top ? " doc" : ""}${jump ? " jumped" : ""}${n.kind === "note" ? " note-pane" : ""}${store.preview ? " preview" : ""}${paneClass(props)}`}
class={`pane${top ? " root" : ""}${jump ? " jumped" : ""}${n.kind === "note" ? " note-pane" : ""}${store.preview ? " preview" : ""}${paneClass(props)}`}
{...paneAttrs(props, id)}
>
<Chrome props={props} title={label(snap, id)} />
<div class="pane-scroll">
<div class="pane-body">
<Orphaned on={props.orphan} />
{page ? (
{top ? (
<TopMatter id={id} />
) : (
<>
{jump && <div class="pane-from">{docOf(snap, id) ? snap.nodes[docOf(snap, id)!].title : "the library"}</div>}
{/* A pane opened by a jump (a link, a search) says where its node is: the titles above it. */}
{jump && <div class="pane-from">{ancestors(snap, id).reverse().map((a) => label(snap, a)).join(" › ")}</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} />
{isPrompt(snap, id) ? <Abstract id={id} /> : <NodeBody id={id} />}
</>
)}
{kids.length > 0 && (
+1 -1
View File
@@ -282,7 +282,7 @@ function Senses({ title, lang, at }: { title: string; lang: string; at: (r: WRow
);
}
/** "Mentioned in": the library's nodes that link to this article, which is what makes an article a hub between documents. */
/** "Mentioned in": the library's nodes that link to this article, which is what makes an article a hub between places in the library. */
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 })} />;
+22 -24
View File
@@ -81,8 +81,8 @@ export interface SelCtx {
note?: boolean;
/** A suggested link on these words: what it would link to. */
suggestion?: string;
/** The node's Related list, numbered 1–5. */
related?: { title: string; doc?: string }[];
/** The node's Related list, numbered 1–5, each with where it is. */
related?: { title: string; where?: string }[];
panes: boolean;
}
@@ -125,7 +125,7 @@ export function selectionEntries(c: SelCtx, act: Act): Entry[] {
SEP,
!c.article && !c.link && !c.note && key(act, "Link to…", "w"),
related.length > 0 && head("Link to a related section"),
...related.map((r, i) => key(act, r.title, String(i + 1), { sub: r.doc })),
...related.map((r, i) => key(act, r.title, String(i + 1), { sub: r.where })),
SEP,
{ t: "choices", label: "Select", options: [{ label: "less", key: "H", run: () => act.press("H") }, { label: "more", key: "L", run: () => act.press("L") }] },
]);
@@ -143,15 +143,19 @@ export interface NodeCtx {
locked: boolean;
/** It has a target of its own (L opens it). */
target: boolean;
/** The library itself: nothing around it to add after, move among or delete it from. */
/** The library itself: nothing around it to add after, move among, copy or delete it from. */
library: boolean;
/** A document's top. */
doc: boolean;
generating: boolean;
}
/**
* A node's menu, the same for a row, a pane's head and a page's head. What acts on the node and
* everything under it (move under, copy, export, import under it, find links) acts on the
* section, so a note's menu leaves it out.
*/
export function nodeEntries(c: NodeCtx, act: Act): Entry[] {
const fixed = c.library;
const tree = !c.note;
return tidy([
head(c.stale ? `${c.title} · ${c.stale === "parent" ? "its parent changed" : "its sections changed"}` : c.title),
c.stale && key(act, "Bring it in line", "R", { sub: c.locked ? "locked: the model will not rewrite it" : "the model rewrites it to match", disabled: c.locked || !c.generating }),
@@ -162,8 +166,8 @@ export function nodeEntries(c: NodeCtx, act: Act): Entry[] {
key(act, "Write more", "e"),
key(act, "Edit text", "c"),
key(act, "Rename", "r"),
key(act, c.library ? "Add a document" : "Add a section inside", "a"),
!fixed && !c.note && key(act, c.doc ? "Add a document after" : "Add a section after", "A"),
key(act, "Add a section inside", "a"),
!fixed && !c.note && key(act, "Add a section after", "A"),
SEP,
key(act, "Ask the editor…", ":"),
c.generating && { t: "item", label: "Research on the web…", keyText: "/research", run: () => act.prompt("/research ") },
@@ -171,23 +175,19 @@ export function nodeEntries(c: NodeCtx, act: Act): Entry[] {
c.target && key(act, "Open its target", "L"),
SEP,
!fixed && { t: "choices", label: "Move", options: [{ label: "up", key: "K", run: () => act.press("K") }, { label: "down", key: "J", run: () => act.press("J") }, { label: "in", key: ">", run: () => act.press(">") }, { label: "out", key: "<", run: () => act.press("<") }] },
!fixed && tree && key(act, "Move under…", "M", { sub: "any node in the library, with all under it" }),
c.note && key(act, "Change its form", "f", { sub: "inline · margin · inset" }),
key(act, "Open everything below", "o"),
key(act, "Collapse everything", "O"),
!fixed && key(act, "Lock", "p", { checked: c.locked, sub: "the model will not rewrite it" }),
!c.library && key(act, "Show only this", "z", { sub: "hoist it: h or Esc at its top steps out" }),
SEP,
!fixed && key(act, "Delete", "D", { sub: "u undoes" }),
]);
}
/** A document's own head: the node's items, and the document's. */
export function pageEntries(c: NodeCtx, act: Act): Entry[] {
return tidy([
...nodeEntries(c, act),
tree && { t: "item", label: "Find links here", keyText: "/linkhere", sub: "in it and everything under it", run: () => act.command("/linkhere") },
tree && !fixed && { t: "item", label: "Save a copy", keyText: "/duplicate", sub: "just after it", run: () => act.command("/duplicate") },
tree && { t: "item", label: "Export as .md", keyText: "/export", run: () => act.command("/export") },
tree && { t: "item", label: "Import a .md file into it…", keyText: "/import", run: () => act.command("/import") },
SEP,
c.doc && { t: "item", label: "Save a copy", keyText: "/duplicate", run: () => act.command("/duplicate") },
c.doc && { t: "item", label: "Export as .md", keyText: "/export", run: () => act.command("/export") },
!fixed && key(act, "Delete", "D", { sub: "u undoes" }),
]);
}
@@ -202,7 +202,7 @@ export interface PaneCtx {
}
export function paneEntries(c: PaneCtx, act: Act): Entry[] {
const own = c.node ? (c.node.doc || c.node.library ? pageEntries(c.node, act) : nodeEntries(c.node, act)) : [head(c.article ?? "Wikipedia"), key(act, "Open on wikipedia.org", "W")];
const own = c.node ? nodeEntries(c.node, act) : [head(c.article ?? "Wikipedia"), key(act, "Open on wikipedia.org", "W")];
return tidy([
...own,
SEP,
@@ -243,8 +243,6 @@ export interface TopCtx {
/** Where each fork's colour shows in the panes view (`/colors`). */
colors: "line" | "top" | "edge" | "off";
panes: boolean;
/** A document is open (its links can be looked for and reviewed). */
doc: boolean;
canRedo: boolean;
}
@@ -253,15 +251,15 @@ export function topEntries(c: TopCtx, act: Act): Entry[] {
const auto = (v: TopCtx["autolink"], label: string): Choice => ({ label, on: c.autolink === v, run: () => act.command(`/autolink ${v}`) });
const setting = (label: string, name: string, on: boolean, sub?: string): Item => ({ t: "item", label, sub, keyText: `/${name}`, checked: on, run: () => act.command(`/${name} ${on ? "off" : "on"}`) });
return tidy([
key(act, "Documents…", "m"),
key(act, "Jump to a section…", "/"),
key(act, "History and branches", "g"),
SEP,
key(act, "Undo", "u"),
key(act, "Redo", "U", { disabled: !c.canRedo }),
SEP,
c.doc && key(act, "Links found: review and reverse", "S"),
c.doc && { t: "item", label: "Find links in this document", keyText: "/linkdoc", run: () => act.command("/linkdoc") },
key(act, "Links found: review and reverse", "S", { sub: "in the node you are on and under it; on the root, the library" }),
{ t: "item", label: "Find links in the whole library", keyText: "/linkall", run: () => act.command("/linkall") },
{ t: "item", label: "Find links here", keyText: "/linkhere", sub: "in the node you are on and everything under it", run: () => act.command("/linkhere") },
SEP,
{ t: "choices", label: "Layout", options: [view("auto"), view("column"), view("panes")] },
{ t: "choices", label: "Links found", options: [auto("review", "review"), auto("suggest", "suggest"), auto("on", "link sure"), auto("off", "off")] },
+22 -103
View File
@@ -12,8 +12,8 @@ export const HELP: [string, [string, string][]][] = [
["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 and the notes on it"],
["/", "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)"],
["/", "jump to a section by name, anywhere in the library"],
["z", "hoist: make this node the whole page (again, or h or Esc at its top, to step out to its parent's page)"],
["v", "view: one column ↔ panes side by side (in panes, j k move among siblings)"],
["q", "in panes: close the active pane (the one under the heavy rule, whatever it shows) and every pane opened from it, except pinned ones; the focus goes back to where it was opened from. A pane's x does the same. Moving left never closes anything"],
["P", "in panes: pin or unpin the active pane (or its pin, top right). A pinned pane stays where it is when a pane it came from closes, is never replaced by a Shift open, and is never covered, in its column or along the strip"],
@@ -29,7 +29,7 @@ export const HELP: [string, [string, string][]][] = [
["", "a click on a sentence selects it, and a bar over it offers expand · define · why · example · challenge · ask · link, each with its key (on a phone, at the foot of the screen, × puts it away); a drag selects words, a double click a word"],
["", "right-click (a long press on a phone) on words, a row, a link, a note or a pane: what can be done with it, Copy first. Shift+right-click is the browser's own menu"],
["", "⋯ by a row, a pane's pin, a page's byline or a note (shown when pointed at): the same menu. A stale flag, clicked, offers what to do about it"],
["", "the top bar: undo, redo, and menu: documents, jump, history, links, layout and settings. A key named in the status line or a panel's head is a button that presses it"],
["", "the top bar: the library's name, undo, redo, and menu: jump, history, links, layout and settings. A key named in the status line or a panel's head is a button that presses it"],
],
],
[
@@ -42,8 +42,8 @@ export const HELP: [string, [string, string][]][] = [
["W", "open the focused article on wikipedia.org, in a new tab"],
["D", "on a link: remove it, and decline its words in that node so it is not made again (u undoes). Also in the right-click menu: Remove the link"],
["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", "the links list of this document: every link found or made, with who decided and the reviewer's reason. 1 2 3 show or hide linked · rejected · pending (rejected is hidden at first); j k move (the words are selected in the text); y links (also a rejected one: you overrule); n declines, or on a link removes it for good; Y links all the pending shown; Enter goes to the words; Esc closes"],
["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"],
["S", "the links list of the node you are on and everything under it (on the library root, the whole library): every link found or made, with who decided and the reviewer's reason. 1 2 3 show or hide linked · rejected · pending (rejected is hidden at first); j k move (the words are selected in the text); y links (also a rejected one: you overrule); n declines, or on a link removes it for good; Y links all the pending shown; Enter goes to the words; Esc closes"],
["1–5", "the node's Related list (sections elsewhere in the library 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"],
["i e d y x c :", "in an article: select words of its text as in a node, and write a note on them; the note belongs to the article and shows wherever it is opened (one whose words are gone from a newer revision is listed as detached)"],
],
@@ -64,14 +64,15 @@ export const HELP: [string, [string, string][]][] = [
[
["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)"],
["a A", "add a section inside / after (on the library root: a new top-level node)"],
["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)"],
["> <", "indent / outdent"],
["M", "move under…: pick any node in the library (or the library root) and this node, with everything under it, becomes its last child (u undoes)"],
["p", "lock or unlock: a locked node is never rewritten by the model (your own edits lock it). Not the same as P, which pins a pane"],
["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"],
["u U", "undo / redo: the last edit made in this tab, wherever in the library it was"],
],
],
[
@@ -84,19 +85,9 @@ export const HELP: [string, [string, string][]][] = [
],
],
[
"Documents (m)",
"The library",
[
["", "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"],
["", "everything is a node of one tree, whose root is the library: the first page. Any node can be moved under any other (M, > <), copied (/duplicate), saved to a file (/export) or given a file's tree under it (/import); each acts on the node you are on, with everything under it. The ⋯ menu of any node offers the same"],
],
],
[
@@ -109,9 +100,9 @@ export const HELP: [string, [string, string][]][] = [
["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"],
["f", "show only what touched the node you are on and what is under it, 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"],
["", "each commit names the top-level nodes it touched. r reverts only the node you are on and what is under it, the rest of the library stays as it is; on the library root, the whole library"],
],
],
[
@@ -127,18 +118,15 @@ export const HELP: [string, [string, string][]][] = [
["/curves on|off", "in panes: the faint curves from where each pane was opened to it"],
["/colors line|top|edge|off", "in panes: each fork's own colour, on its curves and the rule under its panes' titles (line, the default), across their tops, down their left edges, or none"],
["/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"],
["/duplicate title", "save the node you are on, with everything under it, as a copy just after it (titled \"… (copy)\" unless given one); the copy has the focus"],
["/export", "save the node you are on, with everything under it, to a .md file (on the library root, the whole library)"],
["/import", "read a .md file into the node you are on, as its last child (on the library root, a new top-level node)"],
["/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"],
["/link target", "link the selection (or the node): w:Title, /Top title/Section (titles from the library root), an address, or a Wikipedia title"],
["/unlink", "remove the link on the selection (for good: its words are declined; a note that also links keeps its text), or the node's own target"],
["/autolink review|suggest|on|off", "after an edit: the model reviews what was found and links what it approves (review, the default with a model; u undoes, S lists every decision), suggest everything for you to decide (suggest; what review does without a model, or when the model fails or its limit is reached), link the scanner's sure ones unreviewed (on), or look for nothing (off)"],
["/linkdoc", "look for links in the whole document, in the background (reviewed, in review mode); progress and the reviewer's model calls in the status line"],
["/linkall", "look for links in the whole library, in the background"],
["/linkhere", "look for links in the node you are on and everything under it, in the background (reviewed, in review mode); progress and the reviewer's model calls in the status line"],
["/linkall", "look for links in the whole library, in the background (so does /linkhere on the library root)"],
["/linkcancel", "stop looking (what was found and reviewed is kept, and what was approved is linked)"],
["/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\""],
@@ -261,75 +249,6 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
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, true));
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, true);
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":
@@ -528,6 +447,9 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
case "z":
store.setHoist(store.focus.node);
break;
case "M":
if (!selecting) store.startMove();
break;
default:
return;
}
@@ -562,9 +484,6 @@ function commonKey(k: string, hooks: KeyHooks): boolean {
case "g":
store.openHistory();
return true;
case "m":
store.openMenu();
return true;
case "/":
store.setMode("jump");
return true;
+19 -13
View File
@@ -15,7 +15,7 @@ import type { Related as RelatedRow, Suggestion as Sugg } from "../../server/lin
import { inArticles } from "../core/article";
import { applyLinks, nodeRef, phraseKey } from "../core/links";
import type { Mark } from "../core/marks";
import { ancestors, isLink, topOf, label, notesOf, type Doc, type NodeId, type Op, type Snap } from "../core/model";
import { ancestors, isLibraryRoot, isLink, label, notesOf, topOf, tops, type Doc, type NodeId, type Op, type Snap } from "../core/model";
import { describeTarget, sameTarget, type Ref } from "../core/ref";
import { clip, overlaps, type Range } from "../core/text";
import type { Nearby } from "../llm/prompts";
@@ -145,7 +145,7 @@ export class Linker {
private queue: Task[] = [];
private running = false;
job: JobState | null = null;
/** Documents whose pending list has been fetched since the page loaded. */
/** Subtrees whose pending list has been fetched since the page loaded (by the node at their top). */
private fetched = new Set<NodeId>();
/** Scans in flight or queued: the page waits on this in tests (`idle`). */
busy = 0;
@@ -219,7 +219,7 @@ export class Linker {
/** 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;
// Annotations on Wikipedia articles are not a document's text: nothing in them is linked.
// Annotations on Wikipedia articles are not the library's own text: nothing in them is linked.
const snap = this.host.doc().snap();
if (snap.nodes[node] && inArticles(snap, node)) return;
const had = this.queue.find((t) => t.node === node);
@@ -342,21 +342,27 @@ export class Linker {
}
/**
* A document's stored suggestions from the server, with what was decided about each (what a
* background job found, and the reviewer's verdicts), once per page load or on demand. With
* `claim`, also the links the reviewer approved that no page has made yet, handed to this one.
* The stored suggestions of a node and everything under it, from the server, with what was
* decided about each (what a background job found, and the reviewer's verdicts), once per page
* load or on demand. On the library root, each top-level tree's, side by side. With `claim`, also
* the links the reviewer approved that no page has made yet, handed to this one.
*/
async loadDoc(docId: NodeId, force = false, claim = false): Promise<{ found: Sugg[]; apply: Sugg[] }> {
if (!force && this.fetched.has(docId)) return { found: [], apply: [] };
this.fetched.add(docId);
async loadSubtree(id: NodeId, force = false, claim = false): Promise<{ found: Sugg[]; apply: Sugg[] }> {
const snap = this.host.doc().snap();
if (isLibraryRoot(snap, id)) {
const got = await Promise.all(tops(snap).map((t) => this.loadSubtree(t, force, claim)));
return { found: got.flatMap((g) => g.found), apply: got.flatMap((g) => g.apply) };
}
if (!force && this.fetched.has(id)) return { found: [], apply: [] };
this.fetched.add(id);
try {
const res = await fetch(`/api/links/pending?doc=${encodeURIComponent(docId)}&all=1${claim ? "&claim=1" : ""}`);
const res = await fetch(`/api/links/pending?node=${encodeURIComponent(id)}&subtree=1&all=1${claim ? "&claim=1" : ""}`);
if (!res.ok) return { found: [], apply: [] };
const r = (await res.json()) as { suggestions: Sugg[]; apply?: 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.
// Nothing to draw, nothing to redraw: a tree reached is not repainted for an empty list.
if (by.size) this.host.emit(...by.keys());
return { found: r.suggestions, apply: r.apply ?? [] };
} catch {
@@ -484,8 +490,8 @@ export class Linker {
// ---- background jobs ----
async startJob(scope: "doc" | "library", doc?: NodeId): Promise<JobState | string> {
const res = await post("jobs", { scope, doc, review: this.effective() === "review" });
async startJob(scope: "node" | "library", node?: NodeId): Promise<JobState | string> {
const res = await post("jobs", { scope, node: scope === "node" ? node : undefined, review: this.effective() === "review" });
const r = await res.json().catch(() => ({}));
if (!res.ok) return r.error ?? `the server answered ${res.status}`;
// A short job's end can be announced before this answer arrives: keep the later news.
+226 -320
View File
@@ -2,20 +2,21 @@
* Application state for the browser: the library's replicas, sync with the server, the focus
* model, and every action the keyboard, the mouse or the command bar can take.
*
* There is one library and everything in it is reachable from anywhere: a document is a section
* of the library root, opened by hoisting to it (the column) or by showing it in the next pane.
* Nothing is closed to open something else, so model work carries on wherever the reader goes,
* and writes into the node it was asked about.
* There is one library, a tree of nodes, and every node in it is reachable from anywhere: the
* library root is the first page, and any node can be made the whole page (hoisted, in the column)
* or shown in the next pane. Nothing is closed to open something else, so model work carries on
* wherever the reader goes, and writes into the node it was asked about.
*/
import { UndoManager } from "loro-crdt";
import {
Doc, OpError, SYSTEM_ORIGIN, ancestors, descendants, docOf, documents, isLibraryRoot, isLink, isStale, label, notesOf, sections,
staleness, type NodeId, type Op, type Snap,
Doc, OpError, SYSTEM_ORIGIN, ancestors, descendants, isLibraryRoot, isLink, isStale, label, notesOf, sections,
staleness, topOf, tops, type NodeId, type Op, type Snap,
} from "../core/model";
import { FormatError, serializeDoc } from "../core/format";
import { IMPORT_MAX, address, createDoc, deleteDoc, duplicateDoc, importDoc, listDocs, renameDoc, resolve, type DocInfo } from "../core/library";
import { address, resolve } from "../core/address";
import { IMPORT_MAX, importTree } from "../core/seed";
import {
Repo, at, decodeVV, healAnchors, history, reopenConflict, resolveConflict, revertDocTo, revertTo, touched, vvIncludes, type Commit,
Repo, at, decodeVV, healAnchors, history, reopenConflict, resolveConflict, revertSubtreeTo, revertTo, touched, vvIncludes, type Commit,
type MergeReport,
} from "../core/repo";
import { clip, formFor, plain, rangeAt, sentences, slugify, words, type Form, type Range } from "../core/text";
@@ -45,12 +46,12 @@ export interface Focus {
grain: Grain;
range?: Range;
}
export type Mode = "normal" | "edit" | "command" | "history" | "help" | "jump" | "docs" | "link" | "review";
export type Mode = "normal" | "edit" | "command" | "history" | "help" | "jump" | "move" | "link" | "review";
/**
* A pane of the panes view. The panes are a tree of forks (forks.ts) whose focused branch is the
* trail: it starts with the path down from the top node, and a link followed from a pane opens its
* target in the next pane, so it may hold another document's node, a Wikipedia article or a section
* target in the next pane, so it may hold a node from anywhere in the library, a Wikipedia article or a section
* of one. `from` is where a jump was made from, which h returns to.
*/
export type PaneRef =
@@ -111,18 +112,6 @@ export interface Picker {
}
export const sameAux = (a: Aux | null, b: Aux | null): boolean => JSON.stringify(a) === JSON.stringify(b);
/** The documents menu: its filter, selection, and any title being typed or deletion being confirmed. */
export interface Menu {
filter: string;
/** The selected document's node (kept by id, so a changed list does not move the selection). */
selected: NodeId | null;
/** Where the keys go: the filter box, or the list (single-key actions). */
focus: "filter" | "list";
prompt: { kind: "new" | "rename" | "duplicate"; id?: NodeId; value: string } | null;
confirm: NodeId | null;
/** Problems from the last import, shown until the menu closes. */
problems: string[] | null;
}
/** Page layout: one column with a margin, or panes side by side. Auto picks panes on wide windows. */
export type View = "auto" | "column" | "panes";
/** Where a fork's colour shows in the panes view: along its curves and title rules, across its panes' tops, down their left edges, or nowhere. */
@@ -131,7 +120,7 @@ const COLORS: Colors[] = ["line", "top", "edge", "off"];
/** The narrowest window, in CSS px, on which `auto` chooses panes. */
export const PANES_MIN_WIDTH = 900;
/** Text being generated that is not in the document yet. */
/** Text being generated that is not in the library yet. */
export interface Pending {
key: string;
node: NodeId;
@@ -217,7 +206,6 @@ class Store {
fatal: string | null = null;
/** The library's replicas and their sync. */
session!: Session;
menu: Menu = { filter: "", selected: null, focus: "filter", prompt: null, confirm: null, problems: null };
user = "you";
llm: LLM = remoteLLM("off");
online = false;
@@ -226,7 +214,7 @@ class Store {
focus!: Focus;
open = new Set<NodeId>();
hoist: NodeId | null = null;
/** Documents whose own text is unfolded, where it is a prompt that is folded by default. */
/** Nodes whose own text is unfolded, where it is a prompt that is folded by default. */
unfolded = new Set<NodeId>();
/** A past commit being looked at, read-only. */
preview: { commit: Commit; doc: Doc } | null = null;
@@ -236,10 +224,12 @@ class Store {
busy = 0;
log: { at: number; text: string }[] = [];
historyIndex = 0;
/** The history panel shows only what touched the current document. */
historyFilter = false;
/** The commit before the editor agent's last run, while `u` can still take it back. */
agentUndo: { commit: Commit; doc: NodeId | null } | null = null;
/** The history panel shows only what touched this node and what is under it (f). */
historyFilter: NodeId | null = null;
/** The commit before the editor agent's last run, while `u` can still take it back, and the top of the tree it worked in. */
agentUndo: { commit: Commit; top: NodeId | null } | null = null;
/** The node being moved while the reader picks where it goes (M). */
moving: NodeId | null = null;
/** Set by "new branch from this commit" until the name has been typed. */
branchFrom: Commit | null = null;
/** A note being previewed on hover, and where to draw it. */
@@ -256,10 +246,11 @@ class Store {
rendered: (id) => this.rendered(id),
});
/**
* The links list (S): every link found or made in the current document, as it stands, under
* The links list (S): every link found or made in a node and everything under it (on the library
* root, the whole library), as it stands, under
* filters by status; the selected row's words are focused in the text.
*/
review: { ids: NodeId[]; show: Record<Status, boolean>; key: string | null } | null = null;
review: { node: NodeId; ids: NodeId[]; show: Record<Status, boolean>; key: string | null } | null = null;
/** Whether the window is wide enough for `auto` to mean panes. Kept current by the page. */
wide = typeof window !== "undefined" && window.innerWidth >= PANES_MIN_WIDTH;
@@ -455,19 +446,16 @@ class Store {
}
/**
* The document the reader is in: the one the focus is in. On the column's library page, where
* documents are rows to be opened, none.
* The node the reader is on, for what acts on a node and everything under it (export, duplicate,
* import under it, move under, /linkhere, history's f and r): the focused section, or the section
* a focused note or selection is in. From an annotation (its article is not in the outline), the
* page's top.
*/
get currentDoc(): NodeId | null {
get activeNode(): NodeId {
const s = this.snap;
if (!this.panes && isLibraryRoot(s, this.top)) return null;
return docOf(s, this.focus.node);
}
/** The library page in the column: documents are opened by hoisting to them, never unfolded in the list. */
private listing(id: NodeId): boolean {
const s = this.snap;
return !this.panes && isLibraryRoot(s, this.top) && s.nodes[id]?.parent === s.root;
const f = this.focus.node;
if (!s.nodes[f] || inArticles(s, f)) return this.top;
return ownerSection(s, f);
}
/**
@@ -847,7 +835,7 @@ class Store {
return id === this.focus.node || id === this.top;
}
/** A node's Related list: sections of other documents close in meaning (fetched when it is drawn). */
/** A node's Related list: sections elsewhere in the library close in meaning (fetched when it is drawn). */
relatedOf(id: NodeId) {
if (this.preview || !this.snap.nodes[id] || isLibraryRoot(this.snap, id)) return [];
return this.links.relatedOf(id, this.snap) ?? [];
@@ -858,12 +846,11 @@ class Store {
if (this.colWiki) return this.wikiRows("col").map((row) => ({ aux: { kind: "wiki", host: "col", row } }));
const s = this.snap;
const out: Row[] = [];
const listing = isLibraryRoot(s, this.top);
const visit = (id: NodeId) => {
out.push({ node: id });
if (!this.isOpen(id)) return;
sections(s, id).forEach(visit);
if (!(listing && id === this.top)) out.push(...this.auxRows(id));
out.push(...this.auxRows(id));
};
visit(this.top);
return out;
@@ -1003,8 +990,8 @@ class Store {
private inOrder(ids: NodeId[]): NodeId[] {
if (ids.length < 2) return ids;
const s = this.snap;
const docs = documents(s);
const key = (id: NodeId) => [docs.indexOf(docOf(s, id) ?? s.root), label(s, ownerSection(s, id))] as const;
const order = tops(s);
const key = (id: NodeId) => [order.indexOf(topOf(s, id) ?? s.root), label(s, ownerSection(s, id))] as const;
return [...ids].sort((a, b) => {
const [da, la] = key(a);
const [db, lb] = key(b);
@@ -1082,7 +1069,7 @@ class Store {
}
isOpen(id: NodeId) {
return id === this.top || (this.open.has(id) && !this.listing(id));
return id === this.top || this.open.has(id);
}
/** On screen right now: every ancestor up to the top is open. */
@@ -1175,6 +1162,7 @@ class Store {
this.undoManager();
this.navigate(location.pathname, "replace");
this.ready = true;
this.prefetchLinks(this.focus.node);
this.emit();
// The first commit hashes the whole library once (later ones only the path to what they
// changed); do that while the page is idle rather than on the reader's first edit.
@@ -1198,10 +1186,10 @@ class Store {
}
/**
* The version that kept each document separately stored its replicas under `doc:<uid>:…` (and
* the single-document version under bare `branch:<name>` keys). They are never loaded into the
* library, but one may hold edits made offline that never reached the server: compare each with
* what the server had when it built the library, and say so if it is ahead.
* The version that kept each document separately stored its replicas under `doc:<uid>:…`. They
* are never loaded into the library, but one may hold edits made offline that never reached the
* server: compare each with what the server had when it built the library, and say so if it is
* ahead.
*/
private async checkOldReplicas(migrated: Migrated) {
const flag = `lib:${this.session.library}:old-checked`;
@@ -1219,12 +1207,6 @@ class Store {
const m = /^doc:([0-9a-f]+):branch:(.+)$/.exec(key);
if (m) await check(key, migrated.docs.find((d) => d.uid === m[1]), m[2]);
}
if (!(await idbGet("adopted"))) {
for (const key of keys) {
const m = /^branch:(.+)$/.exec(key);
if (m) await check(key, migrated.docs.find((d) => d.slug === "infinite-expand"), m[1]);
}
}
this.oldReplicas = found;
if (!found.length) return void idbSet(flag, true);
const names = found.map((r) => `“${clip(r.title, 30)}”${r.branch === "main" ? "" : ` (${r.branch})`}`).join(", ");
@@ -1238,21 +1220,14 @@ class Store {
const { text } = serializeDoc(Doc.load(r.bytes, this.user).snap());
download(`${r.slug}${r.branch === "main" ? "" : `-${r.branch.replace(/[^\w-]+/g, "-")}`}-unsent.md`, text);
}
this.say(`Saved ${this.oldReplicas.length} file${this.oldReplicas.length > 1 ? "s" : ""}; m then i imports one as a document.`);
this.say(`Saved ${this.oldReplicas.length} file${this.oldReplicas.length > 1 ? "s" : ""}; :/import brings one in under the node you are on.`);
this.oldReplicas = [];
void idbSet(`lib:${this.session.library}:old-checked`, true);
}
/** The current document's title, or the library's. */
docTitle(): string {
const s = this.snap;
const d = this.currentDoc;
return d ? s.nodes[d].title : s.nodes[s.root].title;
}
/** The window's title: the article on the column's article page, else the document. */
/** The window's title: the article on the column's article page, else the node the reader is on. */
private setTitle() {
document.title = this.colWiki ? `${this.colWiki.title} · Wikipedia` : this.docTitle() || "Infinispand";
document.title = this.colWiki ? `${this.colWiki.title} · Wikipedia` : label(this.snap, this.activeNode) || "Infinispand";
}
/** Every edit is saved as it is made; this says whether the server has it yet. */
@@ -1303,14 +1278,10 @@ class Store {
// ---- addresses ----
/**
* The address of what is on screen. On the column's library page it is the library; otherwise
* it is the focused node, so a reload, a link or Back lands on it again.
*/
/** The address of what is on screen: the focused node, so a reload, a link or Back lands on it again. */
here(): string {
if (!this.panes && this.colWiki) return `/w/${this.colWiki.lang}/${encodeURIComponent(this.colWiki.title.replace(/ /g, "_"))}`;
const s = this.snap;
if (!this.panes && isLibraryRoot(s, this.top)) return "/";
// An annotation has no address of its own: the address stays on what shows its article.
if (inArticles(s, this.focus.node)) return location.pathname;
return address(s, this.focus.node);
@@ -1318,8 +1289,8 @@ class Store {
/**
* Put the address in the bar. Moving the focus replaces the entry (after a pause: browsers
* throttle a page that rewrites its address on every keystroke); opening a document or
* jumping makes a new one, so Back returns to where the reader was.
* throttle a page that rewrites its address on every keystroke); changing the page (hoisting,
* stepping out) or jumping makes a new one, so Back returns to where the reader was.
*/
private remember(push = false) {
clearTimeout(this.addressTimer);
@@ -1363,13 +1334,9 @@ class Store {
this.hoist = null;
this.focus = { node: s.root, grain: "node" };
} else if (isLibraryRoot(s, found.node)) {
// The library page: in the column, on the row of the document the reader was in; in
// panes, the library alone.
const from = docOf(s, this.focus.node);
this.hoist = null;
this.focus = { node: (!this.panes && from) || s.root, grain: "node" };
this.focus = { node: s.root, grain: "node" };
} else {
if (!this.panes && found.node === docOf(s, found.node)) this.hoist = found.node;
this.reveal(found.node);
// In panes, the node an address names is shown in its own pane: the trail keeps it if it
// already shows it (Back to a pane of the trail), and is made again as the path to it if not.
@@ -1387,17 +1354,31 @@ class Store {
}
this.repairView();
this.saveView();
this.prefetchLinks(this.focus.node);
if (history === "replace") window.history.replaceState(null, "", this.here());
this.setTitle();
this.emit();
}
/**
* What the server stored about links in the top-level tree the reader has reached (what a
* background job found, the reviewer's verdicts), fetched once a page load, so its suggestions
* show in the text.
*/
private prefetchLinks(id: NodeId) {
if (this.preview || !this.ready) return;
const s = this.doc.snap();
const t = s.nodes[id] ? topOf(s, id) : null;
if (t) void this.links.loadSubtree(t);
}
// ---- navigation ----
setFocus(f: Focus, aux: Aux | null = null) {
const was = this.focus.node;
this.focus = f;
this.aux = aux;
this.prefetchLinks(f.node);
this.syncTrail();
this.saveView();
this.scheduleSpeculation();
@@ -1407,20 +1388,15 @@ class Store {
}
/**
* Open whatever needs opening for a node to be on screen. The column shows one document at a
* time, so a node in another one is shown by hoisting to its document; a document itself is a
* row of the library page until it is opened.
* Open whatever needs opening for a node to be on screen: everything above it, and the page
* itself if the node is not on it (outside the hoisted node, the page goes back to the library).
*/
reveal(id: NodeId) {
const s = this.snap;
// An annotation is shown with its article, wherever that is; the Wikipedia container is never a page.
if (!s.nodes[id] || inArticles(s, id)) return;
const chain = ancestors(s, id);
const under = this.hoist && (id === this.hoist || chain.includes(this.hoist));
if (!this.panes) {
if (isLibraryRoot(s, id)) this.hoist = null;
else if (!under && !(this.hoist === null && s.nodes[id].parent === s.root)) this.hoist = s.library ? docOf(s, id) : null;
} else if (this.hoist && !under) this.hoist = null;
if (this.hoist && id !== this.hoist && !chain.includes(this.hoist)) this.hoist = null;
for (const a of chain) this.open.add(a);
if (s.nodes[id].kind === "note") this.open.add(id);
}
@@ -1432,40 +1408,17 @@ class Store {
if (this.hoist !== hoist) this.remember(true);
}
/** Open a document: hoist to it in the column, show it in the next pane in panes. */
/** Open a document: from its row in the library, beside what is open; from the menu, a command or an address (`nav`), in place of it. */
openDoc(id: NodeId, nav = false) {
const s = this.doc.snap();
if (!s.nodes[id]) return;
void this.links.loadDoc(id);
this.preview = null;
this.mode = "normal";
this.aux = null;
this.colWiki = null;
if (this.panes) {
if (this.hoist && this.hoist !== id && !ancestors(s, this.hoist).includes(id)) this.hoist = null;
this.open.add(id);
this.focus = { node: id, grain: "node" };
this.syncTrail();
if (s.nodes[id].parent === this.top) this.withReplace(nav || this.replacing, () => this.openPane(this.paneAt, { kind: "node", id }));
} else this.hoist = id;
this.focus = { node: id, grain: "node" };
this.saveView();
this.remember(true);
this.emit();
}
/**
* Step out of the hoisted node: to its document if it is deeper, else to the library. The
* focus stays on what was the top, now a row of the page it opened from.
* Step out of the hoisted node, to its parent's page (from a child of the root, the library).
* The focus stays on what was the top, now a row of the page it opened from.
*/
stepOut() {
this.aux = null;
const s = this.snap;
const was = this.hoist;
if (!was) return;
const d = docOf(s, was);
this.hoist = d && d !== was ? d : null;
const p = s.nodes[was].parent;
this.hoist = p && !isLibraryRoot(s, p) ? p : null;
// A note opened as a page steps back out to its words.
const a = s.nodes[was].kind === "note" ? s.nodes[was].anchors[0] : undefined;
this.focus = a ? { node: s.nodes[was].parent!, grain: "word", range: [a.start, a.end] } : { node: was, grain: "node" };
@@ -1526,7 +1479,6 @@ class Store {
const s = this.snap;
const f = this.focus;
if (f.grain !== "node" || this.inArticleText) return this.move(1);
if (this.listing(f.node)) return this.openDoc(f.node);
if (this.panes && (s.nodes[f.node].kind === "section" || this.paneHead(f.node))) {
this.syncTrail();
const i = this.paneAt;
@@ -1631,7 +1583,6 @@ class Store {
toggle(id = this.focus.node) {
if (id === this.top) return this.toggleFold(id);
if (this.listing(id)) return this.openDoc(id);
// The head of a pane other than the first: Enter steps into its rows, as l does.
if (this.panes && this.paneAt > 0 && this.paneHead(id)) return this.into();
// In panes a row opens its pane, or focuses it where it is open already: closing is q's, or the pane's x.
@@ -1642,7 +1593,7 @@ class Store {
this.setOpen(id, !this.isOpen(id));
}
/** Unfold or fold a document's own text where it is a prompt. */
/** Unfold or fold a node's own text where it is a prompt. */
toggleFold(id: NodeId) {
if (this.unfolded.has(id)) this.unfolded.delete(id);
else this.unfolded.add(id);
@@ -1683,7 +1634,7 @@ class Store {
return;
}
if (f.grain === "node") {
if (!this.isOpen(f.node) && n.kind === "section" && !this.listing(f.node)) this.open.add(f.node);
if (!this.isOpen(f.node) && n.kind === "section") this.open.add(f.node);
if (n.kind === "section") this.rowPane(f.node, true);
const first = sentences(n.body)[0];
if (first) this.setFocus({ node: f.node, grain: "sentence", range: first });
@@ -1746,8 +1697,8 @@ class Store {
expandAll(id = this.focus.node) {
const s = this.snap;
// On the library, opening everything would mean every document; open the documents only.
const under = isLibraryRoot(s, id) ? documents(s) : descendants(s, id);
// On the library root, opening everything would open the whole library: its top-level nodes only.
const under = isLibraryRoot(s, id) ? tops(s) : descendants(s, id);
this.open.add(id);
for (const d of under) if (s.nodes[d].kind === "section") this.open.add(d);
this.saveView();
@@ -1842,7 +1793,7 @@ class Store {
startEdit(field: "title" | "body", fresh = false) {
if (!this.writable()) return;
const n = this.snap.nodes[this.focus.node];
if (field === "body" && !this.isOpen(n.id) && !this.listing(n.id)) this.open.add(n.id);
if (field === "body" && !this.isOpen(n.id)) this.open.add(n.id);
if (field === "body") this.rowPane(n.id, true);
this.edit = { node: n.id, field, value: n[field], fresh };
this.mode = "edit";
@@ -1899,7 +1850,7 @@ class Store {
return ops;
}
/** a: a new section inside the focused node. A: a new section after it. On the library, a section is a document. */
/** a: a new section inside the focused node. A: a new section after it. */
add(where: "child" | "after") {
if (!this.writable()) return;
const s = this.snap;
@@ -1907,9 +1858,9 @@ class Store {
const asChild = where === "child" || !n.parent || n.id === this.top || n.kind === "note";
const parent = asChild ? n.id : n.parent!;
const index = asChild ? undefined : s.nodes[parent].children.indexOf(n.id) + 1;
const [id] = this.apply([{ op: "create", parent, index, kind: "section", title: "", body: "" }], isLibraryRoot(s, parent) ? "Add document" : "Add section");
const [id] = this.apply([{ op: "create", parent, index, kind: "section", title: "", body: "" }], "Add section");
if (!id) return;
if (!this.listing(id)) this.open.add(parent);
this.open.add(parent);
this.focus = { node: id, grain: "node" };
this.startEdit("title", true);
}
@@ -1951,7 +1902,7 @@ class Store {
: this.panes ? sibs[j + 1] ?? sibs[j - 1] ?? n.parent
: order[i + 1 + descendants(s, n.id).filter((d) => order.includes(d)).length] ?? order[i - 1] ?? n.parent;
this.apply([{ op: "delete", id: n.id }], `Delete “${clip(label(s, n.id), 40)}”`);
if (this.hoist === n.id || (this.hoist && ancestors(s, this.hoist).includes(n.id))) this.hoist = docOf(s, n.parent) === n.parent ? n.parent : null;
if (this.hoist === n.id || (this.hoist && ancestors(s, this.hoist).includes(n.id))) this.hoist = isLibraryRoot(s, n.parent) ? null : n.parent;
this.focus = { node: this.snap.nodes[next] ? next : n.parent, grain: "node" };
this.remember();
this.say(`Deleted “${clip(label(s, n.id), 40)}”. u to undo.`);
@@ -1971,7 +1922,7 @@ class Store {
this.afterEdit(n.parent, `the subsections were reordered`);
}
/** >: make it a child of the section above. <: lift it out beside its parent. Either may carry it into another document. */
/** >: make it a child of the section above. <: lift it out beside its parent. M moves it under any node. */
indent(delta: number) {
if (!this.writable()) return;
const s = this.snap;
@@ -2054,9 +2005,9 @@ class Store {
// The agent's work arrives by merge, which the undo stack does not see. If it was the last
// thing to happen, undo means going back to the commit before it.
if (!redo && this.agentUndo) {
const { commit, doc } = this.agentUndo;
const { commit, top } = this.agentUndo;
this.agentUndo = null;
this.attempt(() => (doc ? revertDocTo(this.doc, commit, doc) : revertTo(this.doc, commit)));
this.attempt(() => (top ? revertSubtreeTo(this.doc, commit, top) : revertTo(this.doc, commit)));
this.repairView();
return this.say("Undid the editor's changes (as a revert commit).");
}
@@ -2080,11 +2031,10 @@ class Store {
const f = this.focus;
const n = s.nodes[f.node];
if (f.grain === "node") {
if (this.listing(n.id)) return this.openDoc(n.id);
if (!this.isOpen(n.id)) return this.setOpen(n.id, true);
const kids = sections(s, n.id);
const closed = kids.filter((k) => !this.open.has(k));
if (closed.length && !isLibraryRoot(s, n.id)) {
if (closed.length) {
closed.forEach((k) => this.open.add(k));
this.saveView();
// In panes a child's pane only shows once it is focused, so say what changed.
@@ -2225,8 +2175,6 @@ class Store {
if (!text) return;
const [verb, ...rest] = text.split(/\s+/);
const arg = rest.join(" ");
const here = this.currentDoc;
const needDoc = (fn: (id: NodeId) => void) => () => (here ? fn(here) : this.say("Open a document first (m), or name it in the menu."));
const builtin: Record<string, () => void> = {
branch: () => {
this.newBranch(arg, this.branchFrom ?? undefined);
@@ -2245,18 +2193,15 @@ class Store {
colors: () => this.setColors(arg),
view: () => (["auto", "column", "panes"].includes(arg) ? this.setView(arg as View) : this.say(`/view auto, column or panes (now ${this.settings.view}, showing ${this.panes ? "panes" : "column"})`)),
resolve: () => this.resolveAll(),
new: () => (arg ? this.newDoc(arg) : this.openMenu("new")),
open: () => this.openByName(arg),
rename: needDoc((id) => (arg ? this.renameDocument(id, arg) : this.say("Give the new title: /rename <title>"))),
duplicate: needDoc((id) => this.duplicateDocument(id, arg || `${this.snap.nodes[id].title} (copy)`)),
export: needDoc((id) => this.exportDocument(id)),
duplicate: () => this.duplicateNode(arg),
export: () => this.exportNode(),
import: () => this.pickFile(),
recover: () => this.recover(),
link: () => this.linkTo(arg),
unlink: () => this.unlink(),
autolink: () => this.setAutolink(arg),
linkdoc: needDoc((id) => void this.linkJob("doc", id)),
linkall: () => void this.linkJob("library"),
linkhere: () => void this.linkJob(this.activeNode),
linkall: () => void this.linkJob(this.snap.root),
linkcancel: () => void this.cancelLinkJob(),
research: () => this.agent(arg, { research: true }),
};
@@ -2800,7 +2745,7 @@ class Store {
if (typeof parsed === "string") return this.say(parsed);
let ref: Ref = parsed;
if (ref.kind === "node") {
const id = resolveNode(this.snap, ref, docOf(this.snap, spot.node) ?? undefined);
const id = resolveNode(this.snap, ref, spot.node);
if (!id) return this.say(`No node at ${text}.`);
ref = nodeRef(this.snap, id);
}
@@ -2898,7 +2843,7 @@ class Store {
const sources = result.sources.length ? ` · sources: ${result.sources.map((s) => (s.title ? `${clip(s.title, 40)} (${hostOf(s.url)})` : hostOf(s.url))).join(", ")}` : "";
this.say(`editor: ${clip(run.summary, 160)}${result.commits ? ` (${result.commits} change${result.commits > 1 ? "s" : ""}; u undoes, g reviews)` : ""}${sources}`);
if (result.commits) {
this.agentUndo = { commit: before, doc: docOf(doc.snap(), focus) };
this.agentUndo = { commit: before, top: topOf(doc.snap(), focus) };
await this.afterMerge(result.report);
}
} catch (err) {
@@ -2962,16 +2907,19 @@ class Store {
this.say(`Removed the link on “${clip(quote, 40)}”; it will not be made again here · u undoes`);
}
/** S: the links list of the current document (or, on the library, of the focused node). It opens at once; what the server has is fetched fresh behind it. */
/**
* S: the links list of the node the reader is on and everything under it; on the library root,
* of the whole library. It opens at once, on the first row waiting for a decision, else the
* first shown; what the server has is fetched fresh behind it.
*/
startReview() {
if (!this.writable()) return;
const s = this.snap;
const d = this.currentDoc;
const ids = d ? [d, ...descendants(s, d)] : [this.focus.node];
const review = { ids, show: { linked: true, pending: true, rejected: false } as Record<Status, boolean>, key: null as string | null };
const node = this.activeNode;
const ids = isLibraryRoot(s, node) ? [s.root, ...tops(s).flatMap((t) => [t, ...descendants(s, t)])] : [node, ...descendants(s, node)];
const review = { node, ids, show: { linked: true, pending: true, rejected: false } as Record<Status, boolean>, key: null as string | null };
this.review = review;
this.mode = "review";
// The first row waiting for a decision, else the first shown.
const first = () => {
if (this.review !== review || review.key) return;
const rows = this.reviewRows();
@@ -2980,7 +2928,7 @@ class Store {
};
first();
this.emit();
if (d) void this.links.loadDoc(d, true).then(() => (first(), this.emit()));
void this.links.loadSubtree(node, true).then(() => (first(), this.emit()));
}
/** Every row of the links list, whatever the filters. */
@@ -3145,9 +3093,12 @@ class Store {
this.say(c === "off" ? "colors off: forks in plain ink" : `colors ${c}`);
}
/** /linkdoc, /linkall: scan in the background on the server; progress shows in the status line. */
async linkJob(scope: "doc" | "library", doc?: NodeId, quiet = false) {
const r = await this.links.startJob(scope, doc);
/**
* /linkhere, /linkall: scan a node and everything under it (on the library root, the whole
* library) in the background on the server; progress shows in the status line.
*/
async linkJob(node: NodeId, quiet = false) {
const r = await this.links.startJob(isLibraryRoot(this.doc.snap(), node) ? "library" : "node", node);
if (typeof r === "string") return this.say(`Could not start looking for links: ${r}`);
// Already over (a short job announced its end first): that has been said.
if (r.state === "running" && (!quiet || r.slow)) this.say(this.jobText(r));
@@ -3188,9 +3139,9 @@ class Store {
}
if (before?.id === j.id && before.state !== "running") return;
void (async () => {
const docs = j.doc ? [j.doc] : documents(this.doc.snap());
const scope = j.node ? [j.node] : tops(this.doc.snap());
const claim = !!j.review && this.links.effective() === "review";
const got = await Promise.all(docs.map((d) => this.links.loadDoc(d, true, claim)));
const got = await Promise.all(scope.map((id) => this.links.loadSubtree(id, true, claim)));
let made: number | undefined;
if (claim) made = this.links.applyAuto(got.flatMap((g) => g.apply), this.doc, "reviewer").length;
else if (j.state === "done" && this.settings.autolink === "on") {
@@ -3208,127 +3159,33 @@ class Store {
while (!this.session.synced() && Date.now() < until) await new Promise((r) => setTimeout(r, 100));
}
// ---- documents: the menu (m) and what it does ----
// ---- a node and everything under it: copy, export, import, move ----
openMenu(prompt?: "new") {
const items = this.menuItems("");
const here = this.currentDoc;
this.menu = { filter: "", selected: items.find((d) => d.node === here)?.node ?? items[0]?.node ?? null, focus: "filter", prompt: null, confirm: null, problems: null };
this.mode = "docs";
if (prompt) this.menuPrompt(prompt);
this.emit();
}
closeMenu() {
this.mode = "normal";
this.emit();
}
/** The menu's rows: the documents matching the filter, in library order. */
menuItems(filter = this.menu.filter): DocInfo[] {
const terms = filter.toLowerCase().split(/\s+/).filter(Boolean);
const rows = listDocs(this.doc.snap());
return terms.length ? rows.filter((d) => terms.every((t) => `${d.title} ${d.slug} ${d.excerpt}`.toLowerCase().includes(t))) : rows;
}
menuSelected(): DocInfo | undefined {
const items = this.menuItems();
return items.find((d) => d.node === this.menu.selected) ?? items[0];
}
menuMove(delta: number) {
const items = this.menuItems();
if (!items.length) return;
const i = items.findIndex((d) => d.node === this.menuSelected()?.node);
this.menu.selected = items[Math.max(0, Math.min(items.length - 1, i + delta))].node;
this.emit();
}
menuFilter(text: string) {
this.menu.filter = text;
this.menu.selected = this.menuItems()[0]?.node ?? null;
this.emit();
}
/** Ask for a title in the menu: for a new document, or to rename or duplicate the selected one. */
menuPrompt(kind: "new" | "rename" | "duplicate") {
const d = this.menuSelected();
if (kind !== "new" && !d) return;
this.menu.prompt = { kind, id: d?.node, value: kind === "new" ? "" : kind === "rename" ? d!.title : `${d!.title} (copy)` };
this.menu.confirm = null;
this.emit();
}
menuSubmit(value: string) {
const p = this.menu.prompt;
this.menu.prompt = null;
this.menu.focus = "list";
this.emit();
if (!p) return;
if (p.kind === "new") this.newDoc(value);
else if (p.kind === "rename") this.renameDocument(p.id!, value);
else this.duplicateDocument(p.id!, value);
}
/** A document command on the replica on screen: refused while viewing history, reported if refused. */
private docWrite(fn: () => void) {
/** A write on the replica on screen: refused while viewing history, reported if refused. */
private nodeWrite(fn: () => void) {
if (!this.writable()) return;
this.agentUndo = null;
this.attempt(fn);
}
newDoc(title: string) {
title = title.replace(/\s+/g, " ").trim();
if (!title) return this.say("A new document needs a title: /new <title>");
this.docWrite(() => {
const id = createDoc(this.doc, title, this.user);
this.openDoc(id, true);
this.say(`Created “${clip(title, 60)}”: c writes its opening text, a adds a section.`);
/** /duplicate [title]: a copy of the active node and everything under it, placed just after it, which then has the focus. */
duplicateNode(title = "") {
const s = this.snap;
const id = this.activeNode;
if (isLibraryRoot(s, id)) return this.say("The library itself is not copied: /export saves it to a file.");
const name = title.replace(/\s+/g, " ").trim() || `${s.nodes[id].title} (copy)`;
this.nodeWrite(() => {
const parent = s.nodes[id].parent!;
const index = s.nodes[parent].children.indexOf(id) + 1;
const [copy] = this.doc.as(this.user, () => this.doc.apply([{ op: "copy", id, parent, index, title: name }], `Duplicate “${clip(s.nodes[id].title, 40)}” as “${clip(name, 40)}”`).created);
this.go(copy);
this.remember(true);
this.say(`Saved a copy as “${clip(name, 60)}”, just after the original; this is the copy.`);
});
}
/** Links keep working (they go by node id); on this branch, and u undoes it. */
renameDocument(id: NodeId, title: string) {
title = title.replace(/\s+/g, " ").trim();
if (!title) return this.say("A document needs a title.");
this.docWrite(() => {
renameDoc(this.doc, id, title, this.user);
this.remember();
this.say(`Renamed to “${clip(title, 60)}”.`);
});
}
/** Save as: a copy of the whole document, placed after it, which then opens. */
duplicateDocument(id: NodeId, title: string) {
title = title.replace(/\s+/g, " ").trim();
if (!title) return this.say("The copy needs a title.");
this.docWrite(() => {
const copy = duplicateDoc(this.doc, id, title, this.user);
this.openDoc(copy, true);
this.say(`Saved a copy as “${clip(title, 60)}”; this is the copy.`);
});
}
/** Delete (after the menu has asked): an ordinary delete, which u undoes. */
deleteDocument(id: NodeId) {
this.menu.confirm = null;
const s = this.doc.snap();
const title = s.nodes[id]?.title ?? "";
this.docWrite(() => {
const leaving = this.currentDoc === id || (this.hoist && docOf(s, this.hoist) === id);
deleteDoc(this.doc, id, this.user);
if (leaving) {
this.hoist = null;
this.focus = { node: s.root, grain: "node" };
this.remember(true);
}
this.repairView();
this.say(`Deleted “${clip(title, 50)}”. u brings it back.`);
});
}
/** Save to a file: the text format, written from this replica, so unsynced edits are included. */
exportDocument(id: NodeId) {
/** /export: the active node and everything under it, to a file in the text format, written from this replica, so unsynced edits are included. */
exportNode(id = this.activeNode) {
const s = this.doc.snap();
const n = s.nodes[id];
if (!n) return;
@@ -3337,11 +3194,13 @@ class Store {
const name = this.repo.current === "main" ? `${base}.md` : `${base}-${this.repo.current.replace(/[^\w-]+/g, "-")}.md`;
download(name, text);
const left = [skipped.orphans && `${skipped.orphans} orphaned note${skipped.orphans > 1 ? "s" : ""}`, skipped.inNotes && `${skipped.inNotes} section${skipped.inNotes > 1 ? "s" : ""} inside notes`].filter(Boolean);
this.say(`Saved “${clip(n.title, 50)}” to ${name}${left.length ? `. Left out: ${left.join(" and ")} (the format has no place for them)` : ""}.`);
this.say(`Saved “${clip(label(s, id), 50)}” to ${name}${left.length ? `. Left out: ${left.join(" and ")} (the format has no place for them)` : ""}.`);
}
/** Open a file: a file picker, whose choice is imported. */
/** /import: a file picker, whose choice is imported under the active node. */
pickFile() {
if (!this.writable()) return;
const parent = this.activeNode;
const input = document.createElement("input");
input.type = "file";
input.accept = ".md,.markdown,.txt,text/markdown,text/plain";
@@ -3349,42 +3208,81 @@ class Store {
input.onchange = () => {
const file = input.files?.[0];
input.remove();
if (file) void this.importFile(file);
if (file) void this.importFile(file, parent);
};
document.body.append(input);
input.click();
}
/** A .md file as a new document at the end of the library. */
async importFile(file: File) {
/** A .md file as a new last child of a node (the active one by default; on the library root, a new top-level node). */
async importFile(file: File, parent = this.activeNode) {
if (file.size > IMPORT_MAX) return this.say(`${file.name} is too large to import (the limit is ${IMPORT_MAX / 1024 / 1024} MB).`);
if (!this.writable()) return;
const text = await file.text();
if (!this.doc.snap().nodes[parent]) return this.say(`Could not import ${file.name}: the node it was to go under is gone.`);
try {
const id = importDoc(this.doc, text, file.name, { creator: this.user });
this.openDoc(id, true);
this.say(`Imported ${file.name} as “${clip(this.doc.snap().nodes[id].title, 60)}”.`);
const id = importTree(this.doc, text, file.name, { creator: this.user, parent });
this.agentUndo = null;
this.go(id);
this.remember(true);
const s = this.doc.snap();
this.say(`Imported ${file.name} as “${clip(s.nodes[id].title, 60)}”${isLibraryRoot(s, parent) ? "" : `, under “${clip(label(s, parent), 40)}”`}.`);
// Imported text is scanned like any other writing: by a background job, once the server has it.
if (this.settings.autolink !== "off") void this.whenSynced().then(() => this.linkJob("doc", id, true));
if (this.settings.autolink !== "off") void this.whenSynced().then(() => this.linkJob(id, true));
} catch (err) {
if (!(err instanceof FormatError)) return this.say(`Could not import ${file.name}: ${err instanceof Error ? err.message : err}`);
if (this.mode !== "docs") this.openMenu();
this.menu.problems = err.problems;
this.say(`Could not import ${file.name}: ${err.problems.length} problem${err.problems.length > 1 ? "s" : ""}, listed in the menu.`);
const n = err.problems.length;
this.say(`Could not import ${file.name}: ${err.problems[0]}${n > 1 ? ` (and ${n - 1} more problem${n > 2 ? "s" : ""})` : ""}`);
}
}
/** /open name: by slug, then by title (exact, then its start, then anywhere). */
openByName(name: string) {
const q = name.trim().toLowerCase();
if (!q) return this.openMenu();
const all = this.menuItems("");
const d =
all.find((x) => x.slug === q) ?? all.find((x) => x.title.toLowerCase() === q) ?? all.find((x) => x.title.toLowerCase().startsWith(q)) ??
all.find((x) => `${x.title} ${x.slug}`.toLowerCase().includes(q));
if (!d) return this.say(`No document matches “${name}”. m lists them.`);
this.openDoc(d.node, true);
this.say(`Opened “${clip(d.title, 60)}”.`);
/** M: pick a node to move the active node (and everything under it) under. The jump box is the picker. */
startMove() {
if (!this.writable()) return;
const id = this.activeNode;
if (isLibraryRoot(this.snap, id)) return this.say("The library root stays where it is: M moves a node under another.");
this.moving = id;
this.mode = "move";
this.emit();
}
/** What the move picker offers for a query: the library root and its sections, never the node being moved or anything under it. */
moveTargets(q: string): NodeId[] {
const s = this.snap;
const id = this.moving;
const away = new Set(id && s.nodes[id] ? [id, ...descendants(s, id)] : []);
const terms = q.toLowerCase().split(/\s+/).filter(Boolean);
const root = !terms.length || terms.every((t) => s.nodes[s.root].title.toLowerCase().includes(t)) ? [s.root] : [];
const found = terms.length ? this.search(q, away) : tops(s).filter((t) => !away.has(t));
return [...root, ...found].slice(0, 12);
}
/** Enter in the move picker: the node goes under the one chosen, as its last child, in one commit (u undoes). */
moveUnder(target: NodeId) {
const id = this.moving;
this.moving = null;
this.mode = "normal";
const s = this.snap;
if (!id || !s.nodes[id] || !s.nodes[target]) return this.emit();
if (target === id || ancestors(s, target).includes(id)) return this.say("A node cannot go under itself or anything under it.");
const n = s.nodes[id];
if (n.parent === target) return this.say(`“${clip(label(s, id), 40)}” is under “${clip(label(s, target), 40)}” already.`);
const from = n.parent!;
this.nodeWrite(() => {
this.doc.as(this.user, () => this.doc.apply([{ op: "move", id, parent: target }], `Move “${clip(label(s, id), 40)}” under “${clip(label(s, target), 40)}”`));
this.open.add(target);
this.go(id);
this.remember(true);
this.say(`Moved “${clip(label(s, id), 40)}” under “${clip(label(s, target), 40)}”. u undoes.`);
if (!isLibraryRoot(s, target)) this.afterEdit(target, `the subsection “${n.title}” was moved in`);
if (!isLibraryRoot(s, from)) this.afterEdit(from, `the subsection “${n.title}” was moved out`);
});
}
/** Esc in the move picker. */
cancelMove() {
this.moving = null;
this.setMode("normal");
}
// ---- history, branches, merge ----
@@ -3398,33 +3296,37 @@ class Store {
}
/**
* The documents a commit wrote to, derived from the containers its ops changed (the commit
* itself does not record them), placed by where those nodes are now. A node deleted since
* cannot be placed without checking out the past, which costs the size of the library, so a
* commit that only deleted names no document.
* The nodes a commit wrote to, derived from the containers its ops changed (the commit itself
* does not record them), that are still in the library.
*/
touchedDocs(c: Commit): NodeId[] {
touchedNodes(c: Commit): NodeId[] {
const key = `${this.repo.current}:${c.id}`;
let out = this.touchedCache.get(key);
if (out) return out;
const s = this.doc.snap();
const docs = new Set<NodeId>();
for (const id of touched(this.doc, c.spans).nodes) {
const d = s.nodes[id] ? docOf(s, id) : null;
if (d) docs.add(d);
}
out = [...docs];
out = [...touched(this.doc, c.spans).nodes].filter((id) => s.nodes[id]);
this.touchedCache.set(key, out);
return out;
}
/**
* Where a commit wrote, for its line in history: the top-level nodes its nodes are under, placed
* by where those nodes are now. A node deleted since cannot be placed without checking out the
* past, which costs the size of the library, so a commit that only deleted names nothing.
*/
touchedTops(c: Commit): NodeId[] {
const s = this.doc.snap();
return [...new Set(this.touchedNodes(c).map((id) => topOf(s, id)).filter((t): t is NodeId => !!t))];
}
/** Items of the history panel, in the order j and k walk them. */
panel() {
const here = this.historyFilter ? this.currentDoc : null;
const s = this.doc.snap();
const conflicts = this.doc.conflicts().filter((c) => !here || [c.node, c.parent].some((x) => x && s.nodes[x] && docOf(s, x) === here));
const here = this.historyFilter && s.nodes[this.historyFilter] ? this.historyFilter : null;
const under = here ? new Set([here, ...descendants(s, here)]) : null;
const conflicts = this.doc.conflicts().filter((c) => !under || [c.node, c.parent].some((x) => x && under.has(x)));
const branches = [...this.repo.branches.keys()];
const commits = here ? this.commits().filter((c) => this.touchedDocs(c).includes(here)) : this.commits();
const commits = under ? this.commits().filter((c) => this.touchedNodes(c).some((id) => under.has(id))) : this.commits();
return [
...conflicts.map((c) => ({ type: "conflict" as const, conflict: c })),
...branches.map((b) => ({ type: "branch" as const, branch: b })),
@@ -3432,16 +3334,19 @@ class Store {
];
}
/** f in history: show only what touched the current document, or everything. */
/** f in history: show only what touched the active node and what is under it, or everything. */
toggleHistoryFilter() {
if (!this.historyFilter && !this.currentDoc) return this.say("Open a document first: the filter shows what touched the current one.");
this.historyFilter = !this.historyFilter;
const id = this.activeNode;
if (!this.historyFilter && isLibraryRoot(this.doc.snap(), id)) return this.say("On the library root history shows everything: focus a node first, and f shows only what touched it and what is under it.");
this.historyFilter = this.historyFilter ? null : id;
this.historyIndex = 0;
this.emit();
}
openHistory() {
this.mode = "history";
// The filter follows the reader: on another node it is that node's.
if (this.historyFilter) this.historyFilter = isLibraryRoot(this.doc.snap(), this.activeNode) ? null : this.activeNode;
this.historyIndex = Math.min(this.historyIndex, this.panel().length - 1);
const firstCommit = this.panel().findIndex((i) => i.type === "commit");
if (!this.doc.conflicts().some((c) => c.status === "open")) this.historyIndex = Math.max(this.historyIndex, firstCommit);
@@ -3476,17 +3381,19 @@ class Store {
}
/**
* r in history: roll the current document back to the commit, leaving the rest of the library
* as it is. On the library itself, the whole library goes back.
* r in history: roll the active node and everything under it back to the commit, leaving the
* rest of the library as it is. On the library root, the whole library goes back.
*/
revert(commit: Commit) {
this.preview = null;
const here = this.currentDoc;
const s = this.doc.snap();
if (!s.nodes[this.focus.node]) return this.repairView(), this.say("The node you were on is gone now: pick one, then r reverts it.");
const here = isLibraryRoot(s, this.activeNode) ? null : this.activeNode;
this.attempt(() => {
if (here) revertDocTo(this.doc, commit, here);
if (here) revertSubtreeTo(this.doc, commit, here);
else revertTo(this.doc, commit);
this.repairView();
this.say(here ? `Reverted “${clip(this.snap.nodes[here]?.title ?? "", 40)}” to “${clip(commit.message, 50)}” as a new commit; the rest of the library is unchanged.` : `Reverted the library to “${clip(commit.message, 50)}” as a new commit.`);
this.say(here ? `Reverted “${clip(label(this.snap, here), 40)}” and what is under it to “${clip(commit.message, 50)}” as a new commit; the rest of the library is unchanged.` : `Reverted the library to “${clip(commit.message, 50)}” as a new commit.`);
});
this.repairView();
this.emit();
@@ -3568,12 +3475,12 @@ class Store {
this.repairView();
}
/** Sections matching a query, across the whole library, for the jump box. */
search(q: string): NodeId[] {
/** Sections matching a query, across the whole library, for the jump box (and the move picker, leaving out `skip`). */
search(q: string, skip?: Set<NodeId>): NodeId[] {
const s = this.snap;
const terms = q.toLowerCase().split(/\s+/).filter(Boolean);
const all = Object.values(s.nodes).filter((n) => n.kind === "section" && n.id !== s.root && !inArticles(s, n.id));
if (!terms.length) return documents(s).slice(0, 12);
const all = Object.values(s.nodes).filter((n) => n.kind === "section" && n.id !== s.root && !inArticles(s, n.id) && !skip?.has(n.id));
if (!terms.length) return tops(s).slice(0, 12);
const low = (n: (typeof all)[number]) => {
let l = lowered.get(n);
if (!l) lowered.set(n, (l = [n.title.toLowerCase(), n.body.toLowerCase()]));
@@ -3590,19 +3497,18 @@ class Store {
}
return total;
};
// Between equally good matches, the document the reader is in comes first.
const here = this.currentDoc;
const near = (id: NodeId) => (here && docOf(s, id) === here ? 0.5 : 0);
// Between equally good matches, those in the same top-level tree as the reader come first.
const here = s.nodes[this.focus.node] ? topOf(s, this.focus.node) : null;
const near = (id: NodeId) => (here && topOf(s, id) === here ? 0.5 : 0);
return all.map((n) => [n.id, score(n)] as const).filter(([, sc]) => sc > 0).map(([id, sc]) => [id, sc + near(id)] as const).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([id]) => id);
}
/** Enter in the jump box: a document opens; anything else is gone to, in whichever document it is. */
/** Enter in the jump box: the node is gone to, wherever it is (outside the hoisted node, the page goes back to the library). */
jumpTo(id: NodeId) {
this.mode = "normal";
this.aux = null;
this.colWiki = null;
const s = this.snap;
if (s.library && s.nodes[id]?.parent === s.root) return this.openDoc(id, true);
if (!this.snap.nodes[id]) return this.emit();
this.reveal(id);
this.focus = { node: id, grain: "node" };
this.saveView();
+12 -36
View File
@@ -187,7 +187,8 @@ article { width: min(100%, var(--col)); }
.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 give way (cut short) before a cramped row runs off a narrow screen. */
.flags { margin-left: auto; padding-left: 1em; flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; 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; }
@@ -234,10 +235,10 @@ article.preview { opacity: 0.92; }
.lrow.rejected .lq, .lrow.rejected .lt { color: var(--faint); }
.lrow .sub { overflow-wrap: anywhere; }
.lrow .lwhere { color: var(--dim); }
.lempty { color: var(--faint); margin: 0.8rem 0.45rem; }
.lempty, .lmore { color: var(--faint); margin: 0.8rem 0.45rem; }
.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; }
/* The top-level nodes a commit touched. */
.item .under { 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; }
@@ -273,6 +274,7 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.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; }
.jump-head { padding: 0.45rem 0.8rem 0; font-size: 0.62rem; letter-spacing: 0.06em; text-transform: uppercase; color: var(--faint); }
.popup {
position: fixed; width: 440px; max-height: 320px; overflow: auto; z-index: 15;
@@ -581,49 +583,23 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.orphan-note { text-transform: none; letter-spacing: 0.02em; font-style: italic; }
/* 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; }
.pane.root .top h1, .pane.root .byline { text-align: left; }
/* 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.
/* ---- the top bar (src/ui/Menu.tsx) ----
* The bar sits in the page's top margin: the library's name, and whether the server has every
* edit yet; undo, redo and the menu on the right.
*/
.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; }
.lib-name { min-width: 0; max-width: 75%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dim); }
.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 ---- */
/* ---- end top bar ---- */
/* ---- links (src/ui/Links.tsx) ----
* After gwern.net's typed links: the linked words keep the text's colour and get a thin solid