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

+27 -15
View File
@@ -1,7 +1,7 @@
/** What the mouse offers (src/ui/actions.ts): every item does what its key does, and the bar, the ⋯ menus and the right-click menu are built from one place. */
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { articleRowEntries, barItems, nodeEntries, pageEntries, paneEntries, selectionEntries, tidy, topEntries, type Act, type Entry, type Item, type NodeCtx, type SelCtx, type TopCtx } from "../src/ui/actions";
import { articleRowEntries, barItems, nodeEntries, paneEntries, selectionEntries, tidy, topEntries, type Act, type Entry, type Item, type NodeCtx, type SelCtx, type TopCtx } from "../src/ui/actions";
/** An Act that records what was asked of it. */
function recorder() {
@@ -19,9 +19,9 @@ const items = (es: Entry[]): Item[] => es.filter((e): e is Item => e.t === "item
const labels = (es: Entry[]) => es.map((e) => (e.t === "item" ? e.label : e.t === "head" ? `# ${e.text}` : e.t === "choices" ? `[${e.label}: ${e.options.map((o) => o.label).join(" ")}]` : "--"));
const find = (es: Entry[], label: string) => items(es).find((i) => i.label === label)!;
const node = (more: Partial<NodeCtx> = {}): NodeCtx => ({ title: "Training", text: "Training\n\nIt is trained.", note: false, locked: false, target: false, library: false, doc: false, generating: true, ...more });
const node = (more: Partial<NodeCtx> = {}): NodeCtx => ({ title: "Training", text: "Training\n\nIt is trained.", note: false, locked: false, target: false, library: false, generating: true, ...more });
const sel = (more: Partial<SelCtx> = {}): SelCtx => ({ text: "a probability for each possible next piece", article: false, panes: false, ...more });
const top = (more: Partial<TopCtx> = {}): TopCtx => ({ view: "auto", autolink: "suggest", auto: true, speculate: false, curves: true, colors: "line", panes: false, doc: true, canRedo: false, ...more });
const top = (more: Partial<TopCtx> = {}): TopCtx => ({ view: "auto", autolink: "suggest", auto: true, speculate: false, curves: true, colors: "line", panes: false, canRedo: false, ...more });
/** Every key the page's handler takes, read from keys.ts: an item's key must be one of them. */
const handled = new Set([...readFileSync(new URL("../src/ui/keys.ts", import.meta.url), "utf8").matchAll(/case "([^"]+)":/g)].map((m) => m[1]));
@@ -33,7 +33,7 @@ describe("actions", () => {
...barItems(sel(), act).flat(),
...items(selectionEntries(sel({ link: "wiki", note: true, suggestion: "Hoyle state", related: [{ title: "Nodes" }], panes: true }), act)),
...items(nodeEntries(node({ stale: "parent", target: true, note: true }), act)),
...items(pageEntries(node({ doc: true }), act)),
...items(nodeEntries(node({ library: true }), act)),
...items(paneEntries({ node: node(), pinned: false }, act)),
...items(paneEntries({ article: "Octopus", pinned: true }, act)),
...items(articleRowEntries("Octopus", true, act)),
@@ -57,7 +57,7 @@ describe("actions", () => {
it("the selection menu puts Copy first, then what the words carry, then the lenses, linking and Related", () => {
const { act, calls } = recorder();
const plain = selectionEntries(sel({ related: [{ title: "Expansion by depth", doc: "Infinispand" }, { title: "Nodes" }] }), act);
const plain = selectionEntries(sel({ related: [{ title: "Expansion by depth", where: "Infinispand" }, { title: "Nodes" }] }), act);
expect(labels(plain)).toEqual([
"# “a probability for each possible next piece”",
"Copy",
@@ -108,20 +108,28 @@ describe("actions", () => {
expect(find(nodeEntries(node(), act), "Lock").checked).toBe(false);
expect(labels(nodeEntries(node(), act)).join("|")).not.toMatch(/pin/i);
const lib = labels(nodeEntries(node({ library: true }), act));
for (const l of ["Delete", "Lock", "Add a section after", "[Move: up down in out]", "Show only this"]) expect(lib).not.toContain(l);
expect(lib).toContain("Add a document");
for (const l of ["Delete", "Lock", "Add a section after", "[Move: up down in out]", "Move under…", "Show only this", "Save a copy"]) expect(lib).not.toContain(l);
// The library root is a node like any other: it takes a section, and is exported, imported into and scanned like one.
for (const l of ["Add a section inside", "Export as .md", "Import a .md file into it…", "Find links here"]) expect(lib).toContain(l);
expect(labels(nodeEntries(node({ note: true }), act))).toContain("Change its form");
find(nodeEntries(node(), act), "Research on the web…").run();
expect(calls).toEqual(["prompt /research "]);
expect(labels(nodeEntries(node({ generating: false }), act))).not.toContain("Research on the web…");
});
it("a page adds the document's own items; a pane adds pin, close and the column", () => {
it("every node offers what acts on it and everything under it, a note none of it; a pane adds pin, close and the column", () => {
const { act, calls } = recorder();
const page = pageEntries(node({ doc: true }), act);
expect(labels(page).slice(-2)).toEqual(["Save a copy", "Export as .md"]);
find(page, "Export as .md").run();
expect(calls).toEqual(["command /export"]);
const any = nodeEntries(node(), act);
expect(labels(any).slice(-7)).toEqual(["--", "Find links here", "Save a copy", "Export as .md", "Import a .md file into it…", "--", "Delete"]);
expect(find(any, "Move under…")).toMatchObject({ key: "M" });
for (const [label, cmd] of [["Find links here", "/linkhere"], ["Save a copy", "/duplicate"], ["Export as .md", "/export"], ["Import a .md file into it…", "/import"]]) {
calls.length = 0;
find(any, label).run();
expect(calls).toEqual([`command ${cmd}`]);
}
const note = labels(nodeEntries(node({ note: true }), act));
for (const l of ["Move under…", "Save a copy", "Export as .md", "Import a .md file into it…", "Find links here"]) expect(note).not.toContain(l);
calls.length = 0;
const pane = paneEntries({ node: node(), pinned: true }, act);
expect(labels(pane).slice(-3)).toEqual(["Pin this pane", "Close this pane", "Show as one column"]);
expect(find(pane, "Pin this pane").checked).toBe(true);
@@ -131,7 +139,7 @@ describe("actions", () => {
expect(go.options.map((o) => `${o.label} ${o.key}`)).toEqual(["left A-h", "right A-l", "above A-k", "below A-j"]);
});
it("the top menu: documents, history, undo and redo, links, the layout and settings as commands", () => {
it("the top menu: jump, history, undo and redo, links, the layout and settings as commands", () => {
const { act, calls } = recorder();
const es = topEntries(top(), act);
expect(find(es, "Redo").disabled).toBe(true);
@@ -148,8 +156,12 @@ describe("actions", () => {
expect(colors.options.map((o) => `${o.label}${o.on ? "*" : ""}`)).toEqual(["line*", "top", "edge", "off"]);
colors.options[3].run();
expect(calls.at(-1)).toBe("command /colors off");
expect(labels(topEntries(top({ doc: false }), act))).not.toContain("Links found: review and reverse");
expect(labels(topEntries(top(), act))).toContain("Links found: review and reverse");
expect(labels(es)).not.toContain("Documents…");
expect(find(es, "Links found: review and reverse")).toMatchObject({ key: "S" });
calls.length = 0;
find(es, "Find links in the whole library").run();
find(es, "Find links here").run();
expect(calls).toEqual(["command /linkall", "command /linkhere"]);
});
it("tidy leaves no separator at an end or next to another", () => {
+3 -4
View File
@@ -4,7 +4,6 @@ import { describe, expect, it } from "vitest";
import { annotationsOf, articleNodes, articleParent, containers, fold, inArticles, makeAnchor, reanchor, type ArticleKey, type SectionText } from "../src/core/article";
import { Doc, isStale, staleness, tops, type NodeId, type Op } from "../src/core/model";
import { mergeUpdate, verifyHistory } from "../src/core/repo";
import { listDocs } from "../src/core/library";
import type { Range } from "../src/core/text";
// ---- re-anchoring ----
@@ -138,9 +137,9 @@ const sync = (a: Doc, b: Doc) => {
};
describe("article nodes", () => {
it("are made on the first annotation, once; the container is not a document and nothing in it goes stale", () => {
it("are made on the first annotation, once; the container is not one of the root's sections and nothing in it goes stale", () => {
const doc = library();
const before = listDocs(doc.snap());
const before = tops(doc.snap());
expect(containers(doc.snap())).toEqual([]);
const first = annotate(doc, OCTOPUS, "arms");
const second = annotate(doc, { lang: "en", title: "octopus" }, "suckers");
@@ -152,7 +151,7 @@ describe("article nodes", () => {
expect(articleNodes(snap, { lang: "en", title: "Octopodes", pageId: 1200106 })).toHaveLength(1);
expect(articleNodes(snap, { lang: "fr", title: "Octopus" })).toHaveLength(0);
// Not one of the root's sections: not listed, no count.
expect(listDocs(snap)).toEqual(before);
expect(tops(snap)).toEqual(before);
expect(tops(snap)).toHaveLength(1);
const box = containers(snap)[0];
expect(inArticles(snap, first) && inArticles(snap, box) && !inArticles(snap, tops(snap)[0])).toBe(true);
+2 -2
View File
@@ -1,7 +1,7 @@
import { UndoManager } from "loro-crdt";
import { describe, expect, it } from "vitest";
import { Doc, SYSTEM_ORIGIN, ancestorsBelowRoot, isStale, retitleOps, staleness, sections, notesOf, topOf, tops, type NodeId } from "../src/core/model";
import { healAnchors, history, verifyHistory, revertTo, revertDocTo, mergeBranch, mergeUpdate, resolveConflict, reopenConflict, at, touched, Repo } from "../src/core/repo";
import { healAnchors, history, verifyHistory, revertTo, revertSubtreeTo, mergeBranch, mergeUpdate, resolveConflict, reopenConflict, at, touched, Repo } from "../src/core/repo";
import { formFor, paragraphs, sentences, sha256, words } from "../src/core/text";
function fixture() {
@@ -375,7 +375,7 @@ describe("library", () => {
doc.apply([{ op: "create", parent: a, title: "Added later" }], "Add a section");
doc.apply([{ op: "update", id: bLeaf, body: "Beta changed later too." }], "Change the other document");
const beta = doc.shape(doc.snap(), b);
revertDocTo(doc, mark, a);
revertSubtreeTo(doc, mark, a);
const snap = doc.snap();
expect(doc.shape(snap, a)).toBe(doc.shape(at(doc, mark).snap(), a));
expect(doc.shape(snap, b)).toBe(beta);
+5 -5
View File
@@ -10,7 +10,7 @@ import { join, relative } from "node:path";
import { describe, expect, it } from "vitest";
import { LibraryStore } from "../server/library";
import { Doc, descendants, isStale, tops, type NodeId } from "../src/core/model";
import { at, history, mergeBranch, revertDocTo, revertTo, verifyHistory } from "../src/core/repo";
import { at, history, mergeBranch, revertSubtreeTo, revertTo, verifyHistory } from "../src/core/repo";
const temp = () => mkdtempSync(join(tmpdir(), "ie-migrate-"));
@@ -88,7 +88,7 @@ describe("migration from the per-document layout", () => {
// One library: the first document first, then most recently changed first.
expect(snap.library).toBe(true);
expect(store.list().map((d) => d.title)).toEqual(["Infinite Expand", "The tides", "The tides (copy)"]);
expect(store.titles()).toEqual(["Infinite Expand", "The tides", "The tides (copy)"]);
const [nFirst, nTides, nCopy] = tops(snap);
for (const [node, old] of [[nFirst, first], [nTides, tides], [nCopy, copy]] as const) {
expect(lib.shape(snap, node)).toBe(old.shape());
@@ -117,7 +117,7 @@ describe("migration from the per-document layout", () => {
// Reverting the whole library to before it existed is refused; reverting the document to then works.
const humanEdit = h.find((c) => c.message === "Human edit")!;
expect(() => revertTo(lib, humanEdit)).toThrow(/before the library existed/);
revertDocTo(lib, humanEdit, first.snap().root);
revertSubtreeTo(lib, humanEdit, first.snap().root);
expect(lib.snap().nodes[one].title).toBe("One");
expect(lib.shape(lib.snap(), nTides)).toBe(tides.shape());
expect(verifyHistory(lib).mismatches).toEqual([]);
@@ -155,7 +155,7 @@ describe("migration from the per-document layout", () => {
const logs: string[] = [];
const store = new LibraryStore(data, (m) => logs.push(m)).open();
const snap = store.main.snap();
expect(store.list().map((d) => d.title)).toEqual(["Infinite Expand"]);
expect(store.titles()).toEqual(["Infinite Expand"]);
expect(store.main.shape(snap, tops(snap)[0])).toBe(main.shape());
expect(readdirSync(data).filter((f) => f.endsWith(".loro"))).toEqual([]);
expect(existsSync(join(data, "notes.txt"))).toBe(true); // anything else is left alone
@@ -169,7 +169,7 @@ describe("migration from the per-document layout", () => {
const data = temp();
const store = new LibraryStore(data, () => {}).open();
expect(store.main.snap().library).toBe(true);
expect(store.list()).toEqual([]);
expect(store.titles()).toEqual([]);
expect(readdirSync(data)).toEqual(["library"]);
});
});
+32
View File
@@ -332,6 +332,38 @@ describe("the scan route in review mode", () => {
expect(marked.suggestions.find((s: Suggestion) => s.kind === "forced")).toBeTruthy();
expect(marked.entries.find((s: Suggestion) => s.kind === "forced").review).toBeUndefined();
});
it("scopes by node: a node and everything under it (/linkhere), or on the library root the whole library (/linkall); pending lists a subtree", async () => {
const snap = ids.doc.snap();
expect(scopeNodes(snap, ids.minds)).toEqual([ids.minds, ids.arms]);
expect(scopeNodes(snap, ids.arms)).toEqual([ids.arms]);
expect(scopeNodes(snap, null)).toEqual([ids.minds, ids.arms, ids.stars]);
expect(scopeNodes(snap, ids.lib)).toEqual(scopeNodes(snap, null));
const done = async () => {
for (let i = 0; i < 200; i++) {
const { job } = await (await fetch(`${base}/api/links/jobs`)).json();
if (job.state !== "running") return job as JobState;
await new Promise((r) => setTimeout(r, 20));
}
throw new Error("the job did not finish");
};
expect((await post("jobs", { scope: "node", node: ids.minds })).job).toMatchObject({ scope: "node", node: ids.minds, title: "Octopus minds", total: 2 });
expect(await done()).toMatchObject({ state: "done", done: 2 });
expect((await post("jobs", { scope: "node", node: ids.lib })).job).toMatchObject({ scope: "library", title: "the library", total: 3 });
await done();
const lib = (await post("jobs", { scope: "library" })).job;
expect(lib).toMatchObject({ scope: "library", total: 3 });
expect(lib.node).toBeUndefined();
await done();
expect((await post("jobs", { scope: "doc", doc: "octopus-minds" })).error).toMatch(/scope is "node" or "library"/);
expect((await post("jobs", { scope: "node", node: "999@999" })).error).toMatch(/no node/);
// Pending: a node alone, or with everything under it.
const sub = await (await fetch(`${base}/api/links/pending?node=${encodeURIComponent(ids.minds)}&subtree=1&all=1`)).json();
expect(sub.suggestions.length).toBeGreaterThan(0);
expect(new Set(sub.suggestions.map((s: Suggestion) => s.node))).toEqual(new Set([ids.arms]));
const alone = await (await fetch(`${base}/api/links/pending?node=${encodeURIComponent(ids.minds)}&all=1`)).json();
expect(alone.suggestions.every((s: Suggestion) => s.node === ids.minds)).toBe(true);
});
});
describe("the links list in the page", () => {
+1 -1
View File
@@ -86,7 +86,7 @@ describe("a large library", () => {
writeFileSync(join(data, "library", "main.loro"), bytes);
t = performance.now();
const store = new LibraryStore(data, () => {}).open();
expect(store.list()).toHaveLength(100);
expect(store.titles()).toHaveLength(100);
const serverStart = performance.now() - t;
// The backlinks index follows every edit below; it is built once, here.
+75 -70
View File
@@ -1,14 +1,14 @@
/** The library on disk: seeding and starter files; and (until step 2 removes them) the UI's document features: the root's children made, listed and addressed. */
/** The library on disk (seeding and starter files), and a node with everything under it: imported, exported, copied, moved and addressed wherever it is. */
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { UndoManager } from "loro-crdt";
import { describe, expect, it } from "vitest";
import { LibraryStore } from "../server/library";
import { FormatError, serializeDoc } from "../src/core/format";
import { address, createDoc, deleteDoc, duplicateDoc, findTop, importDoc, listDocs, renameDoc, resolve } from "../src/core/library";
import { Doc, SYSTEM_ORIGIN, descendants, sections } from "../src/core/model";
import { SEED_TITLE, writeSeed } from "../src/core/seed";
import { address, resolve } from "../src/core/address";
import { resolveNode } from "../src/core/links";
import { Doc, descendants, isStale, sections, staleness, tops } from "../src/core/model";
import { SEED_TITLE, importTree, writeSeed } from "../src/core/seed";
import { seed } from "../src/seed/tree";
const prompt = readFileSync(new URL("../src/seed/prompt.txt", import.meta.url), "utf8");
@@ -21,7 +21,7 @@ describe("the library on disk", () => {
const data = temp();
const store = new LibraryStore(data, quiet).open();
store.seedFirst((doc) => writeSeed(doc, prompt, seed));
expect(store.list().map((d) => d.title)).toEqual([SEED_TITLE]);
expect(store.titles()).toEqual([SEED_TITLE]);
expect(store.main.snap().library).toBe(true);
expect(JSON.parse(readFileSync(join(data, "library.json"), "utf8")).imported).toEqual(["infinite-expand"]);
store.flush();
@@ -43,92 +43,97 @@ describe("the library on disk", () => {
const logs: string[] = [];
const store = new LibraryStore(data, (m) => logs.push(m)).open();
store.importLibrary(lib);
expect(store.list().map((d) => d.title)).toEqual(["Second", "Good one"]); // file-name order: "S" sorts before "g"
expect(store.titles()).toEqual(["Second", "Good one"]); // file-name order: "S" sorts before "g"
expect(logs.join("\n")).toMatch(/skipped broken\.md:\n {2}library\/broken\.md:9: in “One”: quote not found: "Missing"/);
deleteDoc(store.main, findTop(store.main.snap(), "good-one")!, "alice");
const good = tops(store.main.snap()).find((id) => store.main.snap().nodes[id].title === "Good one")!;
store.main.apply([{ op: "delete", id: good }], "Delete “Good one”");
store.save("main");
const again = new LibraryStore(data, quiet).open();
again.importLibrary(lib);
expect(again.list().map((d) => d.title)).toEqual(["Second"]);
expect(again.titles()).toEqual(["Second"]);
// Once fixed, the broken file is picked up.
writeFileSync(join(lib, "broken.md"), MD("Broken"));
again.importLibrary(lib);
expect(again.list().map((d) => d.title)).toEqual(["Second", "Broken"]);
expect(again.titles()).toEqual(["Second", "Broken"]);
});
});
describe("the root's children (the UI's documents, until step 2)", () => {
it("are created, renamed, duplicated and deleted as ordinary commits, with names made from their titles", () => {
describe("a node and everything under it, wherever it is", () => {
const LINKED = `# Imported\n\nA root body with a phrase.\n\n## One\n\nSection text.\n\n^ "Section" gloss: a note\n^ "text" link -> ./One\n`;
it("is imported under any node, its paths below the file's top stored from the library root, and exported back the same", () => {
const lib = Doc.library("alice");
const a = createDoc(lib, "My notes", "alice");
const snap = () => lib.snap();
expect(snap().nodes[a]).toMatchObject({ parent: snap().root, title: "My notes", by: "human" });
const nameOf = (title: string) => {
const id = createDoc(lib, title, "alice");
return listDocs(snap()).find((d) => d.node === id)!.slug;
};
expect(nameOf("My notes")).toBe("my-notes");
expect(nameOf("../../etc/passwd")).toBe("etc-passwd");
// A name another child has too finds the first; the id finds each.
expect(findTop(snap(), "my-notes")).toBe(a);
expect(findTop(snap(), a)).toBe(a);
const [inner] = lib.apply([{ op: "create", parent: a, title: "Inside" }], "add").created;
expect(findTop(snap(), "inside")).toBeUndefined();
renameDoc(lib, a, "Renamed", "alice");
expect(listDocs(snap()).find((d) => d.node === a)).toMatchObject({ title: "Renamed", slug: "renamed" });
const copy = duplicateDoc(lib, a, "Renamed (copy)", "alice");
expect(listDocs(snap()).find((d) => d.node === copy)).toMatchObject({ title: "Renamed (copy)", slug: "renamed-copy" });
expect(snap().nodes[snap().root].children.indexOf(copy)).toBe(snap().nodes[snap().root].children.indexOf(a) + 1);
expect(sections(snap(), copy).map((id) => snap().nodes[id].title)).toEqual(["Inside"]);
expect(sections(snap(), copy)[0]).not.toBe(inner); // a copy, not the same nodes
// Delete is an ordinary delete: undo brings it back, content and all.
const undo = new UndoManager(lib.loro, { mergeInterval: 0, excludeOriginPrefixes: [SYSTEM_ORIGIN] });
lib.group = { start: () => undo.groupStart(), end: () => undo.groupEnd() };
deleteDoc(lib, copy, "alice");
expect(findTop(snap(), "renamed-copy")).toBeUndefined();
expect(undo.undo()).toBe(true);
lib.touch();
const back = findTop(snap(), "renamed-copy")!;
expect(snap().nodes[back].title).toBe("Renamed (copy)");
expect(sections(snap(), back).map((id) => snap().nodes[id].title)).toEqual(["Inside"]);
});
it("import and export one tree in the text format; a file with a bad quote writes nothing", () => {
const lib = Doc.library("alice");
createDoc(lib, "Something else", "alice");
const id = importDoc(lib, MD("Imported thing"), "thing.md");
const snap = lib.snap();
const tides = importTree(lib, MD("Tides"), "tides.md");
const one = sections(lib.snap(), tides)[0];
// Under a section two levels down, at the end of its children.
const id = importTree(lib, LINKED, "linked.md", { parent: one });
let snap = lib.snap();
expect(snap.nodes[id].parent).toBe(one);
expect(snap.nodes[one].children.at(-1)).toBe(id);
expect([id, ...descendants(snap, id)].every((n) => snap.nodes[n].by === "llm")).toBe(true);
expect(serializeDoc(snap, id).text).toBe(MD("Imported thing"));
const inner = sections(snap, id)[0];
const link = snap.nodes[inner].children.map((c) => snap.nodes[c]).find((c) => c.ref)!;
expect(link.ref).toMatchObject({ kind: "node", id: inner, path: ["Tides", "One", "Imported", "One"] });
expect(resolveNode(snap, { kind: "node", path: ["Tides", "One", "Imported", "One"] })).toBe(inner);
// Nothing starts out stale under it; only the node it went under has a new section to summarise.
for (const n of [id, ...descendants(snap, id)]) expect(isStale(snap, n)).toBe(false);
expect(staleness(snap, one).up).toBe(true);
// Exported from where it is, its own paths are written relative to it again.
expect(serializeDoc(snap, id).text).toBe(LINKED);
// At a place among the children, when asked.
const first = importTree(lib, MD("First"), "first.md", { parent: tides, index: 0 });
snap = lib.snap();
expect(snap.nodes[tides].children[0]).toBe(first);
// A file with a bad quote writes nothing, wherever it was to go.
const before = lib.stateHash();
expect(() => importDoc(lib, MD("Bad").replace('"Section"', '"Nowhere"'), "bad.md")).toThrow(FormatError);
expect(() => importTree(lib, MD("Bad").replace('"Section"', '"Nowhere"'), "bad.md", { parent: inner })).toThrow(FormatError);
expect(lib.stateHash()).toBe(before);
expect(listDocs(lib.snap()).map((d) => d.slug)).toEqual(["something-else", "imported-thing"]);
});
it("have addresses: /doc/<name> for one, /doc/<name>/<node> for a node under it, / for the library", () => {
it("is copied just after itself with everything under it, and the copy's links inside it still point into the original", () => {
const lib = Doc.library("alice");
const a = importDoc(lib, MD("Tides"), "tides.md");
const b = importDoc(lib, MD("Codes"), "codes.md");
const tides = importTree(lib, MD("Tides"), "tides.md");
const id = importTree(lib, LINKED, "linked.md", { parent: sections(lib.snap(), tides)[0] });
const parent = lib.snap().nodes[id].parent!;
const [copy] = lib.apply([{ op: "copy", id, parent, index: lib.snap().nodes[parent].children.indexOf(id) + 1, title: "Imported (copy)" }], "Duplicate").created;
const snap = lib.snap();
expect(snap.nodes[parent].children.indexOf(copy)).toBe(snap.nodes[parent].children.indexOf(id) + 1);
expect(sections(snap, copy).map((c) => snap.nodes[c].title)).toEqual(["One"]);
expect(sections(snap, copy)[0]).not.toBe(sections(snap, id)[0]);
for (const n of [copy, ...descendants(snap, copy)]) expect(isStale(snap, n)).toBe(false);
});
it("is moved under any other node, never under itself", () => {
const lib = Doc.library("alice");
const a = importTree(lib, MD("Alpha"), "a.md");
const b = importTree(lib, MD("Beta"), "b.md");
const deep = sections(lib.snap(), b)[0];
lib.apply([{ op: "move", id: a, parent: deep }], "Move under");
expect(lib.snap().nodes[a].parent).toBe(deep);
expect(() => lib.apply([{ op: "move", id: b, parent: sections(lib.snap(), a)[0] }], "Move under itself")).toThrow(/inside itself/);
// And back to the top of the library.
lib.apply([{ op: "move", id: a, parent: lib.snap().root }], "Move to the top");
expect(tops(lib.snap())).toEqual([b, a]);
});
it("has an address made of its id alone: /n/<id>, and / for the library root", () => {
const lib = Doc.library("alice");
const a = importTree(lib, MD("Tides"), "tides.md");
const b = importTree(lib, MD("Codes"), "codes.md");
const snap = lib.snap();
const one = sections(snap, a)[0];
expect(address(snap, snap.root)).toBe("/");
expect(address(snap, a)).toBe("/doc/tides");
expect(address(snap, one)).toBe(`/doc/tides/${encodeURIComponent(one)}`);
expect(address(snap, a)).toBe(`/n/${encodeURIComponent(a)}`);
expect(address(snap, one)).toBe(`/n/${encodeURIComponent(one)}`);
for (const id of [snap.root, a, one]) expect(resolve(snap, address(snap, id))).toEqual({ node: id });
// The node id is what counts: a link whose node has moved to another document still finds it.
lib.apply([{ op: "move", id: one, parent: b }], "move");
expect(resolve(lib.snap(), `/doc/tides/${encodeURIComponent(one)}`)).toEqual({ node: one });
expect(address(lib.snap(), one)).toBe(`/doc/codes/${encodeURIComponent(one)}`);
// A moved node keeps its address; a renamed one too.
lib.apply([{ op: "move", id: one, parent: b }, { op: "update", id: one, title: "Renamed" }], "move and rename");
expect(address(lib.snap(), one)).toBe(`/n/${encodeURIComponent(one)}`);
expect(resolve(lib.snap(), `/n/${encodeURIComponent(one)}`)).toEqual({ node: one });
expect(resolve(lib.snap(), "/doc/nothing")).toEqual({ missing: "nothing called “nothing”" });
// A child of the root whose name another has too is addressed by its id as well.
const twin = importDoc(lib, MD("Tides"), "tides-2.md");
expect(address(lib.snap(), twin)).toBe(`/doc/tides/${encodeURIComponent(twin)}`);
expect(resolve(lib.snap(), address(lib.snap(), twin))).toEqual({ node: twin });
expect(address(lib.snap(), a)).toBe("/doc/tides");
// What names nothing says so (the page then shows the library): a gone node, an old document address, anything else.
expect(resolve(lib.snap(), "/n/999%40999")).toEqual({ missing: "no node 999@999" });
expect(resolve(lib.snap(), "/doc/tides")).toEqual({ missing: "no page /doc/tides" });
expect(resolve(lib.snap(), "/n/%E0%A4%A")).toMatchObject({ missing: expect.any(String) });
});
});