Annotate Wikipedia articles with the same keys as nodes

An article's text is drawn from its sanitised HTML as selectable text
(articleText.ts): paragraphs, list items and quotes with their inline
elements; a formula is one unit; tables and preformatted blocks are shown
but carry no offsets. The selection ladder, Tab, Enter, e d y x c :, D and
the rest go through the same store paths as on a node; a note on article
words is a note (Enter steps into it; c, f, u, the editor and history work
on it as on any other) and shows wherever the article is opened, in the
library's own note style. Detached annotations are listed at the top of
their section with a link to the old revision. Keys that only make sense on
a node say why in the status line. Tab on a link now selects its words, so
Esc widens before h leaves, as in a node.

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-15 21:53:00 -05:00
1 parent f63fc10dc0
commit 2c1ee048a4
18 files changed
+1132 -124

No files matched your search

+13
View File
@@ -96,6 +96,17 @@ Press `?` for every key. The short version:
line.
- Under an open node, **Linked from** lists what links to it; under an article, **Mentioned in**
lists the library's nodes that link to it.
- **Notes on an article.** In an article's text the keys are a node's: `i` selects a sentence, then
a word, `j` `k` `H` `L` move and widen, `Tab` walks links and notes, and `e` `d` `y` `x` `c` `:`
write a note on the words, which is a note like any other (`Enter` steps into it; `c`, `D`, `f`,
`u`, `:` the editor). Wikipedia's text itself cannot be edited: keys that would edit it say why not. The notes
belong to the article, so they show wherever it is opened. The library keeps a node per annotated
article in a container that is not a document (not listed, never scanned for links, never
reconciled); the article text stays in the server's cache. Each note records its section, its
words, a little text either side and the revision; in a later revision it is found again (its
section first, then anywhere, then ignoring case and punctuation), and if its words are gone it
is listed at the top of its section as detached, with a link to the old revision. Tables and
preformatted blocks are shown but cannot be selected; a formula is selected whole.
- To link by hand, select words (`i`, widen with `H` `L`) and press `w`: the picker offers library
sections and notes, Wikipedia articles and, for a pasted address, the web page. `w` on a link
retargets it, `D` removes it; `:/link target` and `:/unlink` do the same.
@@ -170,6 +181,8 @@ What is sent where:
works on a fork and merges back. A prompt carries the focused node's document only.
- **`src/core/ref.ts`, `src/core/links.ts`** Targets, the backlinks index, finding a node target
again, and `applyLinks`, which links a batch of spans in one commit.
- **`src/core/article.ts`, `src/ui/articleText.ts`** Notes on Wikipedia articles: the article
nodes, anchors and finding them again in a new revision; an article's HTML as text to select in.
- **`src/core/format.ts`, `seed.ts`, `library.ts`** The text format, writing a parsed tree into the
library, and the document operations and addresses.
- **`server/`** Relays updates between replicas and persists them (`library.ts`), proxies model
+7
View File
@@ -218,6 +218,13 @@ senses 14 d, suggest and search 1 d), `articles/` (7 d). Vectors: `<IE_DATA>/vec
and `.f32`. An expired entry is still served, marked `stale`, when the network is down. The
variables that configure all this are in the README.
Notes on articles (src/core/article.ts) rely on this cache and add nothing to it: an article is
re-read through `article?full=1`, whose answer always carries `revisionId` (and `pageId`), as
every `section` answer does (a `summary` may not). A note records the revision it was made
against; when the cached copy expires (7 d) and Wikipedia has a newer revision, the note is found
again in it, or shown as detached with a link to the old revision. The browser keeps articles in
memory for the page's life only, never in IndexedDB.
## 8. Link discovery as built
`server/links/` (README "Links found for you" says what the writer sees). A scan of one node:
+215
View File
@@ -0,0 +1,215 @@
/**
* Annotating Wikipedia articles, keyboard first, against the mock Wikipedia and the mock model:
* words of an article are selected with the same keys as words of a node, a lens writes a note on
* them, the note belongs to the article (it shows wherever the article is opened), and it is found
* again in a later revision, or listed as detached when its words are gone.
*/
import { expect, test, type Page } from "@playwright/test";
import { command, idle, jump, keys, seedLinks, selected, settle, state } from "./helpers";
const panes = (page: Page) => page.locator(".strip > .pane");
async function wide(page: Page, path = "/doc/fixed-points") {
await page.setViewportSize({ width: 1920, height: 1080 });
await page.goto(path);
await page.waitForSelector(".strip > .pane");
await page.evaluate(() => document.fonts.ready);
}
async function column(page: Page, path: string) {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto(path);
await page.waitForFunction(() => (globalThis as any).__ie?.ready);
}
async function tabTo(page: Page, words: string) {
for (let i = 0; i < 16; i++) {
await page.keyboard.press("Tab");
if ((await selected(page)) === words || (await articleSelection(page)) === words) return;
}
throw new Error(`Tab never reached “${words}”`);
}
/** The words selected in an article's text. */
const articleSelection = (page: Page) => state(page, (s) => s.selectedText() as string | null);
/** The library's annotations: their words and text. */
const annotations = (page: Page) => state(page, (s) => Object.values(s.snap.nodes).filter((n: any) => n.wanchor).map((n: any) => `${n.wanchor.q} | ${n.body}`));
test.describe.configure({ mode: "serial" });
test.beforeAll(async ({ request }) => {
await seedLinks(request);
});
test.beforeEach(async ({ context }) => {
await context.route(/wikipedia\.org|wikimedia\.org/, (r) => r.abort());
});
test.afterEach(({ page }) => settle(page));
test("words of an article are selected with the node keys, and a lens writes a note on them that the library keeps", async ({ page }) => {
await wide(page);
const docs = await state(page, (s) => s.menuItems("").length);
await jump(page, "Recursion without names");
await tabTo(page, "fixed-point combinator");
await keys(page, "Enter");
const art = page.locator(".wiki-pane").last();
await expect(art.locator(".wiki-head h2")).toHaveText("Fixed-point combinator");
// i: the first sentence; i again: its first word; j moves by word, Esc widens back.
// (Pressed while the article is still arriving, i waits for it.)
await keys(page, "i");
await expect.poll(() => articleSelection(page)).toMatch(/^In mathematics and computer science, a fixed-point combinator .* of f: a value x with f\(x\) = x\.$/);
await expect(art.locator(".wiki-text .sel")).not.toHaveCount(0);
await keys(page, "i");
expect(await articleSelection(page)).toBe("In");
await keys(page, "j L");
expect(await articleSelection(page)).toBe("mathematics and");
await keys(page, "Escape");
// A sentence: y asks why, as a margin note set after its paragraph.
await keys(page, "j");
const sentence = await articleSelection(page);
expect(sentence).toMatch(/^In the untyped lambda calculus/);
await keys(page, "y");
await idle(page);
const note = art.locator(".wiki-text .inset");
await expect(note).toContainText("through the why lens");
expect(await note.evaluate((el) => getComputedStyle(el).fontFamily)).toContain("Serif");
// Tab reaches links and the note's words; d on a link's words writes a gloss.
await keys(page, "Escape");
await tabTo(page, "Haskell Curry");
await expect(art.locator("a.wfocus")).toHaveText("Haskell Curry");
await keys(page, "d");
await idle(page);
await expect(art.locator(".wiki-text .gloss")).toContainText("mock gloss of Haskell Curry");
await expect(art.locator(".wiki-text .anchor.a-gloss")).toHaveText("Haskell Curry");
expect((await annotations(page)).sort()).toEqual([`Haskell Curry | mock gloss of Haskell Curry`, `${sentence} | Mock note on “${sentence!.slice(0, 47)}…” through the why lens. It is two sentences long.`].sort());
// The article's node is in the library's Wikipedia container, which is not a document.
expect(await state(page, (s) => s.menuItems("").length)).toBe(docs);
expect(await state(page, (s) => s.menuItems("").some((d: any) => d.title === "Wikipedia"))).toBe(false);
// Keys that only make sense on a node say why not.
await keys(page, "Escape Escape");
await keys(page, "c");
await expect(page.locator(".status .message")).toContainText("cannot be edited");
await keys(page, "r");
await expect(page.locator(".status .message")).toContainText("shown as it is");
});
test("an annotation is a note: Enter steps into it, and it is edited, undone, deleted and given to the editor like any other", async ({ page }) => {
await wide(page);
await jump(page, "Recursion without names");
await tabTo(page, "fixed-point combinator");
await keys(page, "Enter");
await keys(page, "i");
await tabTo(page, "Haskell Curry");
const art = page.locator(".wiki-pane").last();
// Its words carry the dotted underline; e opens and closes it, as on a node; Enter opens it, and Enter again steps into it.
await expect(art.locator(".wiki-text .anchor.a-gloss")).toHaveText("Haskell Curry");
await expect(art.locator(".wiki-text .gloss")).toHaveCount(0);
await keys(page, "e");
await expect(art.locator(".wiki-text .gloss")).toHaveCount(1);
await keys(page, "e");
await expect(art.locator(".wiki-text .gloss")).toHaveCount(0);
await keys(page, "Enter Enter");
const id = await state(page, (s) => s.focus.node);
expect(await state(page, (s) => !!s.snap.nodes[s.focus.node].wanchor && s.aux === null)).toBe(true);
await expect(art.locator(".wiki-text .gloss.focused")).toHaveCount(1);
// c edits it in place.
await keys(page, "c");
await page.keyboard.press("Control+a");
await page.keyboard.type("the logician the Y combinator is named after");
await keys(page, "Escape");
await expect(art.locator(".wiki-text .gloss")).toContainText("the logician the Y combinator is named after");
await keys(page, "u");
await expect(art.locator(".wiki-text .gloss")).toContainText("mock gloss of Haskell Curry");
// The editor agent works on it like on any node.
await command(page, 'rename to "Curry"');
await idle(page);
expect(await state(page, (s) => s.snap.nodes[s.focus.node]?.title)).toBe("Curry");
// h returns to its words; D there deletes it, u brings it back.
await keys(page, "h");
expect(await articleSelection(page)).toBe("Haskell Curry");
await keys(page, "D");
expect(await page.evaluate((x) => !!(globalThis as any).__ie.snap.nodes[x], id)).toBe(false);
await expect(art.locator(".wiki-text .gloss")).toHaveCount(0);
await expect(art.locator(".wiki-text .anchor.a-gloss")).toHaveCount(0);
await keys(page, "u");
await expect(art.locator(".wiki-text .anchor.a-gloss")).toHaveText("Haskell Curry");
});
test("an article's annotations show wherever it is opened: from another link, from another article, by its address", async ({ page }) => {
// Annotate Lambda calculus under the note that links to it (the article in full beneath the note).
await wide(page);
await jump(page, "Recursion without names");
await tabTo(page, "lambda calculus");
await keys(page, "Enter j");
const under = panes(page).last().locator(".wiki.embedded");
await expect(under.locator(".wiki-head h2")).toHaveText("Lambda calculus");
await keys(page, "i");
await expect.poll(() => articleSelection(page)).toMatch(/^Lambda calculus \(also written λ-calculus\) is a formal system/);
await keys(page, "x");
await idle(page);
await expect(under.locator(".wiki-text .inset")).toContainText("through the example lens");
// From another document's link to it.
await settle(page);
await wide(page, "/doc/what-a-proof-is");
await jump(page, "Proofs as programs");
await tabTo(page, "a function turning proofs");
await keys(page, "Enter");
await expect(page.locator(".wiki-pane").last().locator(".wiki-head h2")).toHaveText("Lambda calculus");
await expect(page.locator(".wiki-pane").last().locator(".wiki-text .inset")).toContainText("through the example lens");
// From another article's link to it.
await jump(page, "Recursion without names");
await tabTo(page, "fixed-point combinator");
await keys(page, "Enter");
await tabTo(page, "lambda calculus");
await keys(page, "Enter");
await expect(page.locator(".wiki-pane").last().locator(".wiki-head h2")).toHaveText("Lambda calculus");
await expect(page.locator(".wiki-pane").last().locator(".wiki-text .inset")).toContainText("through the example lens");
// By its address, as the column's article page.
await settle(page);
await column(page, "/w/en/Lambda_calculus");
await expect(page.locator(".wiki-page .wiki-text .inset")).toContainText("through the example lens");
});
test("in a new revision an annotation is found where its words moved; one whose words are gone is kept as detached", async ({ page }) => {
await column(page, "/w/en/Octopus");
const pageEl = page.locator(".wiki-page");
const openSection = async (title: string) => {
const focused = () => page.evaluate(() => document.querySelector(".wiki-page .wrow.focused > .row .title")?.textContent ?? "");
await expect(pageEl.locator(".wrow").first()).toBeVisible();
for (let i = 0; i < 12 && (await focused()) !== title; i++) await keys(page, "j");
await keys(page, "l");
};
// A note on a sentence of Description, and one on a sentence of Intelligence.
await openSection("Description");
await keys(page, "i j");
expect(await articleSelection(page)).toBe("Its skin contains specialised cells that let it change colour and texture within a fraction of a second.");
await keys(page, "y");
await idle(page);
await keys(page, "Escape Escape");
await openSection("Intelligence");
await keys(page, "i j");
expect(await articleSelection(page)).toBe("In laboratory studies they have solved mazes, unscrewed jar lids and learned by watching other octopuses.");
await keys(page, "x");
await idle(page);
await expect(pageEl.locator(".wiki-text .inset")).toHaveCount(2);
const rev = await state(page, (s) => (Object.values(s.snap.nodes) as any[]).find((n) => n.wanchor?.q.startsWith("Its skin")).wanchor.rev as number);
await settle(page);
// The next revision: the Intelligence paragraph moved into Description and edited around the
// annotated sentence, and the skin sentence rewritten away.
await page.route(/\/api\/wiki\/article\?title=Octopus/, async (route) => {
const res = await route.fetch();
const body = await res.json();
const a = body.article;
a.revisionId += 1;
const desc = a.sections.find((x: any) => x.heading === "Description");
const intel = a.sections.find((x: any) => x.heading === "Intelligence");
desc.html = desc.html.replace(/Its skin contains specialised cells[^.]*\./, "Its skin can change colour in an instant.") + intel.html.replace("Some have been seen carrying coconut shells to use later as shelter.", "Some carry coconut shells about.").replace("widely regarded as", "often called");
intel.html = "<p>See above.</p>";
await route.fulfill({ response: res, json: body });
});
await page.reload();
await page.waitForFunction(() => (globalThis as any).__ie?.ready);
await openSection("Description");
const desc = pageEl.locator(".wrow.open").first();
await expect(desc.locator(".wdetached .inset")).toContainText("Its skin contains specialised cells");
await expect(desc.locator(".wdetached a")).toHaveAttribute("href", new RegExp(`oldid=${rev}$`));
await expect(desc.locator(".wiki-text .anchor")).toHaveText("In laboratory studies they have solved mazes, unscrewed jar lids and learned by watching other octopuses.");
await expect(desc.locator(".wiki-text .inset")).toContainText("through the example lens");
// Nothing was lost or rewritten: both annotations are still in the library as they were.
expect((await annotations(page)).filter((a) => /^(Its skin|In laboratory)/.test(a))).toHaveLength(2);
});
+1 -1
View File
@@ -103,7 +103,7 @@ test("past the pre-generated text, a selection is expanded by the model, in a fo
await expect(page.locator(".inset").last()).toContainText("through the how does this fail? lens");
const notes = await state(page, (s) =>
Object.values(s.snap.nodes).filter((c: any) => c.kind === "note" && /^[Mm]ock/.test(c.body)).map((c: any) => c.form).sort(),
Object.values(s.snap.nodes).filter((c: any) => c.kind === "note" && !c.wanchor && /^[Mm]ock/.test(c.body)).map((c: any) => c.form).sort(),
);
expect(notes).toEqual(["gloss", "note", "passage"]);
+11 -5
View File
@@ -139,17 +139,19 @@ test("panes: Tab and Enter open an article in the next pane; its sections open a
await expect(sec.locator(".wattr")).toBeVisible();
await keys(page, "l");
expect(await state(page, (s) => s.aux)).toMatchObject({ kind: "wiki", host: "p4", row: { t: "head" } });
// Tab reaches the section's link to Lambda calculus; Enter opens it as a further pane.
// Tab selects the section's link to Lambda calculus, as words of a node; Enter opens it as a further pane.
await keys(page, "Tab");
await expect(sec.locator("a.wfocus")).toHaveText("lambda calculus");
expect(await state(page, (s) => s.selectedText())).toBe("lambda calculus");
await keys(page, "Enter");
await expect(panes(page)).toHaveCount(6);
await expect(panes(page).last().locator(".wiki-head h2")).toHaveText("Lambda calculus");
// Back left, step by step, to the words the trail started from; nothing to the right closes.
await keys(page, "h");
expect(await state(page, (s) => s.paneAt)).toBe(4);
// From the link it was opened from: off the link, up to the section's row, the article's head, the words.
await keys(page, "h h h h");
// From the link it was opened from: Esc widens the selection to its sentence, then to the text's
// head; h goes up to the section's row in the pane before, its head, the words.
await keys(page, "Escape Escape h h h");
expect(await selected(page)).toBe("fixed-point combinator");
expect(await trail(page)).toEqual(["Library", "Fixed points", "Recursion without names", "W:Fixed-point combinator", "W:Fixed-point combinator#2", "W:Lambda calculus"]);
await expect(panes(page)).toHaveCount(6);
@@ -167,7 +169,10 @@ test("panes: Tab and Enter open an article in the next pane; its sections open a
// Spines of covered article panes carry the W and the tint.
await keys(page, "j j l l Tab Enter");
await expect(panes(page).last().locator(".wiki-head h2")).toHaveText("Lambda calculus");
await keys(page, "Tab Enter");
// (Tab also stops on notes the library keeps on the article, if an earlier test wrote one.)
await expect(panes(page).last().locator(".wiki-text a[data-wiki]").first()).toBeVisible();
for (let i = 0; i < 4 && (await state(page, (s) => s.selectedText())) !== "Alonzo Church"; i++) await keys(page, "Tab");
await keys(page, "Enter");
await expect(panes(page).last().locator(".wiki-head h2")).toHaveText("Alonzo Church");
const spine = page.locator(".wiki-pane[data-covered] .spine").first();
await expect(spine.locator(".wmark")).toHaveText("W");
@@ -437,7 +442,8 @@ test("column: Enter on a link shows a preview, Enter again opens the article as
await expect(pageEl.locator(".wiki-head h2")).toHaveText("Lambda calculus");
await keys(page, "h");
await expect(pageEl.locator(".wiki-head h2")).toHaveText("Fixed-point combinator");
await keys(page, "h h h");
// Back on the link's words: Esc widens to the sentence, then to the section's row; h to the head, then out.
await keys(page, "Escape Escape h h");
await expect(page.locator(".wiki-page")).toHaveCount(0);
expect(await selected(page)).toBe("fixed-point combinator");
// Back works too.
+3 -3
View File
@@ -56,7 +56,7 @@ test.afterEach(({ page }) => settle(page));
test("the library is the first page: its documents are its sections, and opening one needs no closing step", async ({ page }) => {
await open(page, "/");
await expect(page.locator(".top h1")).toHaveText("Library");
const docs = await state(page, (s) => s.snap.nodes[s.snap.root].children.length);
const docs = await state(page, (s) => s.snap.nodes[s.snap.root].children.filter((c: string) => !s.snap.nodes[c].articles).length);
await expect(page.locator("article > .outline > .node")).toHaveCount(docs);
await expect(page.locator("article > .outline > .node.open")).toHaveCount(0);
await keys(page, "j Enter"); // the first document's row: it opens in place of the list
@@ -81,7 +81,7 @@ test("m opens the menu, in library order, and the title in the top bar opens it
await expect(panel.locator(".doc.current")).toContainText("Infinispand");
await expect(panel.locator(".doc.current")).toContainText(/open · (saved|saving…)/);
const listed = await panel.locator(".doc .title").allTextContents();
expect(listed).toEqual(await state(page, (s) => s.snap.nodes[s.snap.root].children.map((c: string) => s.snap.nodes[c].title)));
expect(listed).toEqual(await state(page, (s) => s.snap.nodes[s.snap.root].children.filter((c: string) => !s.snap.nodes[c].articles).map((c: string) => s.snap.nodes[c].title)));
await keys(page, "Escape Escape");
await expect(panel).toHaveCount(0);
await page.locator(".docbar .doc-title").click();
@@ -234,7 +234,7 @@ test("create, rename and duplicate from the menu", async ({ page }) => {
await expect(page).toHaveURL(/\/doc\/scratch-copy$/);
// The copy sits after the original in the library, and is one commit in its history.
expect(await state(page, (s) => s.commits()[0].message)).toBe("Duplicate “Scratch pad, renamed” as “Scratch copy”");
const order = await state(page, (s) => s.snap.nodes[s.snap.root].children.map((c: string) => s.snap.nodes[c].slug));
const order = await state(page, (s) => s.snap.nodes[s.snap.root].children.filter((c: string) => !s.snap.nodes[c].articles).map((c: string) => s.snap.nodes[c].slug));
expect(order.indexOf("scratch-copy")).toBe(order.indexOf("scratch-pad") + 1);
});
+1 -1
View File
@@ -33,7 +33,7 @@ test("everything is reachable with the mouse: titles, marked spans, and a dragge
expect(focus.text.length).toBeGreaterThan(3);
await page.keyboard.press("e");
await idle(page);
const made = await state(page, (s) => Object.values(s.snap.nodes).filter((n: any) => n.kind === "note" && /^[Mm]ock/.test(n.body)).map((n: any) => n.anchors[0].text));
const made = await state(page, (s) => Object.values(s.snap.nodes).filter((n: any) => n.kind === "note" && !n.wanchor && /^[Mm]ock/.test(n.body)).map((n: any) => n.anchors[0].text));
expect(made).toContain(focus.text);
});
+1 -1
View File
@@ -37,7 +37,7 @@ test("the library is the first pane, and a document opens in the next; reload an
await page.goto("/");
await page.waitForSelector(".strip > .pane");
expect(await paneTitles(page)).toEqual(["Library"]);
await expect(page.locator(".pane.root .rows > .node")).toHaveCount(await state(page, (s) => s.snap.nodes[s.snap.root].children.length));
await expect(page.locator(".pane.root .rows > .node")).toHaveCount(await state(page, (s) => s.snap.nodes[s.snap.root].children.filter((c: string) => !s.snap.nodes[c].articles).length));
await keys(page, "j l"); // the first document's row, then open it
expect(await paneTitles(page)).toEqual(["Library", "Infinispand"]);
await expect(page.locator(".pane.doc .abstract.seed.folded")).toBeVisible();
+36 -4
View File
@@ -8,7 +8,7 @@ import { DocBar, DocsPanel } from "./Menu";
import { LinkCard, LinkPicker, NodeBacklinks, NodeRelated, TargetRow } from "./Links";
import { NodeBody, Outline, PendingSections, TopMatter } from "./Node";
import { Panes } from "./Panes";
import { PANES_MIN_WIDTH, store, type Aux } from "./store";
import { PANES_MIN_WIDTH, store, type Aux, type WRow } from "./store";
import { WikiPage, WikiView } from "./Wiki";
import { Usage } from "./Usage";
@@ -235,7 +235,8 @@ function CommandBar({ prefill }: { prefill: string }) {
const f = store.focus;
const snap = store.snap;
const n = snap.nodes[f.node];
const about = f.grain !== "node" && f.range ? `ask about “${clip(plain(n.body.slice(f.range[0], f.range[1])), 48)}”` : `tell the editor · ${clip(label(snap, f.node), 40)}`;
const words = store.selectedText();
const about = words !== null ? `ask about “${clip(plain(words), 48)}”` : `tell the editor · ${clip(label(snap, f.node), 40)}`;
return (
<div class="command">
<span class="prompt">{about}</span>
@@ -247,7 +248,7 @@ function CommandBar({ prefill }: { prefill: string }) {
}
}}
defaultValue={prefill}
placeholder={f.grain !== "node" ? "why? · example · how does this fail? …" : "add a section on… · tighten this · /branch name · /merge name"}
placeholder={words !== null ? "why? · example · how does this fail? …" : "add a section on… · tighten this · /branch name · /merge name"}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Escape") {
@@ -367,7 +368,13 @@ function StatusLine() {
const selecting = f.grain !== "node";
const hint = store.aux
? store.aux.kind === "wiki"
? `Wikipedia · j k rows · l open · h back · Tab links${store.aux.link !== undefined ? " · Enter opens this link" : ""} · W on wikipedia.org${store.panes ? " · q close" : ""}`
? store.inArticleText
? store.articleNoteHere()
? "Enter open/enter the note · e toggle · D delete note · Tab next"
: store.auxLink(store.aux)
? `Enter opens “${clip(store.auxLink(store.aux)!.title, 40)}” · e d y x c annotate · W on wikipedia.org`
: `e expand${store.generating ? "" : " (no model)"} · d define · y why · x example · c challenge · : ask · Esc widen`
: `Wikipedia · j k rows · l open · h back · i select words · Tab links and notes · W on wikipedia.org${store.panes ? " · q close" : ""}`
: store.aux.kind === "target" ? "Enter opens what this is about"
: "Enter goes to the linking note"
: store.preview
@@ -409,6 +416,13 @@ function StatusLine() {
// ---- the app ----
/** The offset in its text of a DOM position inside a piece marked with data-o. */
function locateIn(node: Node, offset: number): number | null {
const el = node instanceof Element ? node : node.parentElement;
const piece = el?.closest<HTMLElement>("[data-o]");
return piece ? Number(piece.dataset.o) + (node instanceof Text ? offset : 0) : null;
}
/** Map a DOM position inside a body to (node, offset). */
function locate(node: Node | null, offset: number): { id: NodeId; at: number } | null {
const el = node instanceof Element ? node : node?.parentElement;
@@ -545,6 +559,24 @@ export function App() {
return store.setFocus(store.focus, { kind: "wiki", host, row: { t: "head" } });
}
const selection = window.getSelection();
// In an article's text: a drag selects words, an annotation's words open it, a click selects the sentence.
const wtext = target.closest<HTMLElement>("[data-wtext]");
if (host && wtext && !target.closest("[data-node]")) {
store.paneAt = paneIndex;
const row = (wtext.dataset.wtext === "head" ? { t: "head" } : { t: "sec", id: Number(wtext.dataset.wtext) }) as WRow;
const at = (n: Node | null, o: number) => (n && wtext.contains(n) ? locateIn(n, o) : null);
const a = selection && !selection.isCollapsed ? at(selection.anchorNode, selection.anchorOffset) : null;
const b = selection && !selection.isCollapsed ? at(selection.focusNode, selection.focusOffset) : null;
if (a !== null && b !== null && a !== b) {
selection!.removeAllRanges();
return store.selectInArticle(host, row, [Math.min(a, b), Math.max(a, b)], "word");
}
const note = target.closest<HTMLElement>("[data-note]")?.dataset.note as NodeId | undefined;
if (note) return store.toggleAnnotation(host, row, note);
const o = selection ? at(selection.anchorNode, selection.anchorOffset) : null;
if (o !== null) return store.selectInArticle(host, row, [o, o], "sentence");
return;
}
// A drag selection inside one body becomes the focus range.
if (selection && !selection.isCollapsed) {
const a = locate(selection.anchorNode, selection.anchorOffset);
+3 -3
View File
@@ -12,7 +12,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. */
interface VNote {
export interface VNote {
key: string;
id?: NodeId;
form: Form;
@@ -155,7 +155,7 @@ function Writing({ text }: { text: string }) {
const LENS_LABEL: Record<string, string> = { elaborate: "", define: "definition", why: "why", example: "example", challenge: "objection" };
function NoteView({ v, inNote }: { v: VNote; inNote: boolean }) {
export function NoteView({ v, inNote }: { v: VNote; inNote: boolean }) {
const snap = store.snap;
const focused = !!v.id && store.focus.node === v.id;
const st = v.id ? staleness(snap, v.id) : null;
@@ -434,7 +434,7 @@ export function TopMatter({ id }: { id: NodeId }) {
// the page should open on the outline, so it is folded until asked for. Other text is plain.
const prompt = !library && docOf(snap, id) === id && kids.some((k) => snap.nodes[k].anchors.length > 0);
const folded = prompt && !store.unfolded.has(id) && !(focused && store.focus.grain !== "node") && store.edit?.node !== id;
const count = library ? Object.keys(snap.nodes).length - 1 : descendants(snap, id).length;
const count = library ? kids.reduce((n, d) => n + 1 + descendants(snap, d).length, 0) : descendants(snap, id).length;
return (
<>
{crumbs.length > 0 && (
+132 -25
View File
@@ -9,32 +9,138 @@
* always clear which text is Wikipedia's and which is the reader's, and every view of article
* text ends with its attribution.
*/
import { useLayoutEffect, useRef } from "preact/hooks";
import { clip } from "../core/text";
import { h, type ComponentChildren } from "preact";
import type { NodeId } from "../core/model";
import { wikiKey } from "../core/ref";
import { clip, type Range } from "../core/text";
import type { Block } from "./articleText";
import { Attribution, Backlinks } from "./Links";
import { NodeBody, NoteView, type VNote } from "./Node";
import { sameAux, store, type WRow } from "./store";
import { article, cleanHtml, known, sectionsUnder, sensesOf, summary, type Article } from "./wiki";
import { article, articleText, known, revisionUrl, sectionsUnder, sensesOf, summary, type Article } from "./wiki";
type Para = Extract<Block, { k: "para" }>;
interface Ctx {
text: string;
notes: VNote[];
sel: { grain: string; range: Range } | null;
/** The focused link's words, when the selection is exactly a link. */
link: Range | null;
}
/**
* Article HTML, cleaned twice (server and here) and put into the page. The focused link, when Tab
* has picked one, is marked here rather than in the HTML, which never changes once set.
* A piece of article text (the lead or a section) as text the keys select in: every paragraph is
* drawn from the same characters sentences() and words() count (articleText.ts), so a selection,
* an annotation's words and a link are ranges into it, as in a node's body. Annotations are drawn
* as the library's notes are (a dotted underline; the note inline, or after its paragraph), in the
* library's own face. Tables and preformatted blocks are shown as they came.
*/
function WikiText({ html, link }: { html: string; link?: number }) {
const ref = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
el.querySelectorAll("a.wfocus").forEach((a) => a.classList.remove("wfocus"));
if (link === undefined) return;
const a = el.querySelectorAll("a[data-wiki]")[link];
if (a) {
a.classList.add("wfocus");
(a as HTMLElement).scrollIntoView?.({ block: "nearest" });
function ArticleTextView({ host, row, sec, html, article, lang }: { host: string; row: WRow; sec: number; html: string; article: Article; lang: string }) {
const at = articleText(html);
const a = store.aux;
const here = a?.kind === "wiki" && a.host === host && sameAux({ ...a, grain: undefined, range: undefined }, { kind: "wiki", host, row });
const sel = here && a.grain && a.range ? { grain: a.grain, range: a.range } : null;
const link = sel && at.links.some((l) => l.range[0] === sel.range[0] && l.range[1] === sel.range[1]) ? sel.range : null;
const snap = store.snap;
const notes: VNote[] = [];
for (const [id, p] of store.annotations(article, lang).at) {
const n = snap.nodes[id];
if (p.sec === sec) notes.push({ key: id, id, form: n.form ?? "note", ranges: [p.range], open: store.open.has(id), lens: n.lens });
}
});
return <div class="wiki-text" ref={ref} dangerouslySetInnerHTML={{ __html: cleanHtml(html) }} />;
const key = wikiKey(lang, article.title);
for (const p of store.pending.values()) if (p.art?.key === key && p.art.sec === sec && p.range) notes.push({ key: p.key, form: p.form ?? "note", ranges: [p.range], open: true, pending: p, lens: p.lens });
return (
<div class="wiki-text" data-wtext={row.t === "sec" ? row.id : "head"}>
<Blocks bs={at.blocks} c={{ text: at.text, notes, sel, link }} />
</div>
);
}
function Blocks({ bs, c }: { bs: Block[]; c: Ctx }) {
return (
<>
{bs.map((b, i) =>
b.k === "para" ? <APara key={i} b={b} c={c} /> : b.k === "raw" ? <div key={i} class="wraw" dangerouslySetInnerHTML={{ __html: b.html }} /> : h(b.tag, { key: i, ...Object.fromEntries(b.attrs) }, <Blocks bs={b.kids} c={c} />),
)}
</>
);
}
/** One paragraph, cut where its inline elements, annotations, the selection and the focused link begin and end; a formula is never cut. */
function APara({ b, c }: { b: Para; c: Ctx }) {
const clipTo = (r: Range): Range | null => (r[0] < b.e && r[1] > b.s ? [Math.max(r[0], b.s), Math.min(r[1], b.e)] : null);
const cuts = new Set<number>([b.s, b.e]);
for (const r of b.runs) cuts.add(r.s).add(r.e);
const notes = c.notes.filter((n) => n.ranges.some((r) => clipTo(r)));
for (const n of notes) for (const r of n.ranges.map(clipTo)) if (r) cuts.add(r[0]).add(r[1]);
const sel = c.sel && clipTo(c.sel.range);
if (sel) cuts.add(sel[0]).add(sel[1]);
const maths = b.runs.filter((r) => r.math);
const points = [...cuts].filter((x) => !maths.some((m) => x > m.s && x < m.e)).sort((x, y) => x - y);
const meets = (r: Range, x: number, y: number, whole: boolean) => (whole ? r[0] < y && r[1] > x : r[0] <= x && r[1] >= y);
const out: ComponentChildren[] = [];
const after: ComponentChildren[] = [];
for (let i = 0; i + 1 < points.length; i++) {
const [x, y] = [points[i], points[i + 1]];
const run = b.runs.find((r) => r.s <= x && x < r.e);
if (run) {
const whole = !!run.math;
// Where notes overlap, the narrowest is the one these words open.
const note = notes.filter((n) => n.ranges.some((r) => meets(r, x, y, whole))).sort((m, n) => m.ranges[0][1] - m.ranges[0][0] - (n.ranges[0][1] - n.ranges[0][0]))[0];
const cls = [note && `anchor a-${note.form}`, note?.open && "on", note?.pending && "writing", sel && meets(sel, x, y, whole) && `sel ${c.sel!.grain}`].filter(Boolean).join(" ") || undefined;
let el = run.math ? (
<span key={x} class={cls ? `wmath ${cls}` : "wmath"} data-o={x} data-note={note?.id} dangerouslySetInnerHTML={{ __html: run.math }} />
) : (
<span key={x} class={cls} data-o={x} data-note={note?.id}>
{c.text.slice(x, y)}
</span>
);
for (const m of [...run.marks].reverse()) el = h(m.tag, { key: x, ...Object.fromEntries(m.attrs), class: m.tag === "a" && c.link && meets(c.link, x, y, false) ? "wfocus" : undefined }, el);
out.push(el);
}
for (const n of notes) {
if (!n.open || n.ranges[0][1] !== y) continue;
const view = <NoteView key={`n${n.key}`} v={n} inNote />;
if (n.form === "gloss") out.push(view);
else after.push(view);
}
}
return (
<>
{b.p ? <p class="wpara">{out}</p> : <span class="wpara loose">{out}</span>}
{after}
</>
);
}
/** Annotations whose words are not in this revision: kept, shown at the top of their section (or of the article), with the words and the revision they were made on. */
function Detached({ ids, article, lang }: { ids: NodeId[]; article: Article; lang: string }) {
if (!ids.length) return null;
const snap = store.snap;
return (
<div class="wdetached">
{ids.map((id) => {
const w = snap.nodes[id].wanchor!;
return (
<span key={id} class={`inset detached${store.focus.node === id && !store.aux ? " focused" : ""}`} data-node={id}>
<span class="meta">
detached: “{clip(w.q, 90)}” is not in this revision ·{" "}
<a href={revisionUrl(article.title, w.rev, lang)} target="_blank" rel="noopener noreferrer">
the words in revision {w.rev}
</a>
</span>
<NodeBody id={id} inline inNote />
</span>
);
})}
</div>
);
}
/** The detached annotations of a section (0: the lead, which also takes those whose section is gone). */
const detachedIn = (article: Article, lang: string, sec: number) =>
store.annotations(article, lang).detached.filter((d) => d.sec === sec || (sec === 0 && d.sec === null)).map((d) => d.id);
/** The W that marks Wikipedia's text, and the title. */
function Head({ title, sub, focused }: { title: string; sub?: string; focused: boolean }) {
return (
@@ -59,8 +165,7 @@ export function WikiView({ host }: { host: string }) {
const h = store.wikiHost(host);
if (!h) return null;
const a = store.aux;
const at = (row: WRow) => !!a && a.kind === "wiki" && a.host === host && sameAux({ ...a, link: undefined }, { kind: "wiki", host, row });
const linkAt = (row: WRow) => (at(row) && a?.kind === "wiki" ? a.link : undefined);
const at = (row: WRow) => !!a && a.kind === "wiki" && a.host === host && !a.grain && sameAux(a, { kind: "wiki", host, row });
const embedded = h.embedded;
// Under a node, folded: its summary only, until l unfolds the article.
@@ -108,17 +213,18 @@ export function WikiView({ host }: { host: string }) {
<section class={`wiki${embedded ? " embedded" : ""}`} data-host={host}>
<Head title={v.title} sub={sec?.heading} focused={at({ t: "head" })} />
{art.stale && <p class="wiki-wait">Wikipedia could not be reached; this is the copy kept from before.</p>}
<WikiText html={sec ? sec.html : v.lead} link={linkAt({ t: "head" })} />
<Detached ids={detachedIn(v, h.lang, h.sec)} article={v} lang={h.lang} />
<ArticleTextView host={host} row={{ t: "head" }} sec={h.sec} html={sec ? sec.html : v.lead} article={v} lang={h.lang} />
{v.disambiguation && !sec && <Senses title={v.title} lang={h.lang} at={at} />}
<Rows article={v} parent={h.sec} nested={!!h.nested} at={at} linkAt={linkAt} showing={showing} />
<Rows article={v} host={host} lang={h.lang} parent={h.sec} nested={!!h.nested} at={at} showing={showing} />
<Mentions title={v.title} lang={h.lang} show={!!h.mentions} at={at} />
<Attribution a={v.attribution} />
</section>
);
}
function Rows(props: { article: Article; parent: number; nested: boolean; at: (r: WRow) => boolean; linkAt: (r: WRow) => number | undefined; showing: (id: number) => boolean }) {
const { article: v, parent, nested, at, linkAt, showing } = props;
function Rows(props: { article: Article; host: string; lang: string; parent: number; nested: boolean; at: (r: WRow) => boolean; showing: (id: number) => boolean }) {
const { article: v, host, lang, parent, nested, at, showing } = props;
const kids = sectionsUnder(v, parent);
if (!kids.length) return null;
return (
@@ -136,7 +242,8 @@ function Rows(props: { article: Article; parent: number; nested: boolean; at: (r
</div>
{open && (
<div class="content">
<WikiText html={x.html} link={linkAt(row)} />
<Detached ids={detachedIn(v, lang, x.id)} article={v} lang={lang} />
<ArticleTextView host={host} row={row} sec={x.id} html={x.html} article={v} lang={lang} />
<Rows {...props} parent={x.id} />
</div>
)}
+162
View File
@@ -0,0 +1,162 @@
/**
* An article's sanitised HTML as text the keys can select in, the same way they select in a node's
* body: one string per section, paragraphs separated by a blank line, so sentences(), words(),
* ranges, anchors and the renderer all count the same characters.
*
* What is text (selectable, and where an anchor can attach): paragraphs, list items, definition
* list entries and block quotes, with everything inline in them (links, italics, bold, sub- and
* superscripts, code). An inline formula counts as its glyphs' text and is selected and drawn
* whole: a selection that touches it highlights all of it. What is not: tables and preformatted
* blocks, which are shown as they are but carry no offsets. Whitespace is collapsed as the browser
* collapses it. Citation markers and the rest are gone already (server/wikiHtml.ts). A section's
* text is its own: nothing spans two sections.
*/
import type { Range } from "../core/text";
/** What the walk needs of a DOM node: the browser's, or a stand-in in the tests. */
export interface DomLike {
nodeType: number;
localName?: string;
data?: string;
textContent: string | null;
childNodes: ArrayLike<DomLike>;
attributes?: ArrayLike<{ name: string; value: string }>;
outerHTML?: string;
}
/** An inline element around some text. */
export interface Mark {
tag: string;
attrs: [string, string][];
}
/** A stretch of a paragraph with the same inline elements around it; a formula is a run of its own. */
export interface Run {
s: number;
e: number;
marks: Mark[];
math?: string;
}
export type Block =
/** A paragraph: `p` when it was one in the HTML, else loose text in a list item and the like. */
| { k: "para"; p: boolean; s: number; e: number; runs: Run[] }
| { k: "el"; tag: string; attrs: [string, string][]; kids: Block[] }
| { k: "raw"; html: string };
export interface ArticleText {
text: string;
blocks: Block[];
/** The links to other articles, in reading order. */
links: { range: Range; title: string }[];
}
const STRUCT = new Set(["ul", "ol", "li", "dl", "dt", "dd", "blockquote"]);
const OPAQUE = new Set(["table", "pre", "hr"]);
const attrsOf = (n: DomLike): [string, string][] => Array.from(n.attributes ?? [], (a) => [a.name, a.value]);
const same = (a: Mark[], b: Mark[]) => a.length === b.length && a.every((m, i) => m === b[i]);
export function buildText(root: DomLike): ArticleText {
let text = "";
let out: Block[] = [];
const blocks = out;
let para: { p: boolean; s: number; runs: Run[] } | null = null;
let inP = false;
/** A space is owed before the next text, in the marks it was written in. */
let space: Mark[] | null = null;
const marks: Mark[] = [];
const push = (str: string, m: Mark[], math?: string) => {
if (!para) {
if (text) text += "\n\n";
para = { p: inP, s: text.length, runs: [] };
}
if (space) {
const sp = space;
space = null;
push(" ", sp);
}
const last = para.runs[para.runs.length - 1];
const s = text.length;
text += str;
if (!math && last && !last.math && same(last.marks, m)) last.e = text.length;
else para.runs.push(math ? { s, e: text.length, marks: m, math } : { s, e: text.length, marks: m });
};
const add = (raw: string) => {
const t = raw.replace(/\s+/g, " ");
const m = marks.slice();
for (let i = 0; i < t.length; ) {
if (t[i] === " ") {
if (para) space ??= m;
i++;
continue;
}
let j = t.indexOf(" ", i);
if (j < 0) j = t.length;
push(t.slice(i, j), m);
i = j;
}
};
const flush = () => {
if (para) out.push({ k: "para", ...para, e: text.length });
para = null;
space = null;
};
const visit = (n: DomLike) => {
for (const c of Array.from(n.childNodes)) {
if (c.nodeType === 3) add(c.data ?? "");
if (c.nodeType !== 1) continue;
const tag = c.localName ?? "";
if (tag === "math") {
const t = (c.textContent ?? "").replace(/\s+/g, " ").trim();
if (t) push(t, marks.slice(), c.outerHTML ?? "");
} else if (OPAQUE.has(tag)) {
flush();
out.push({ k: "raw", html: c.outerHTML ?? "" });
} else if (tag === "p") {
flush();
inP = true;
visit(c);
flush();
inP = false;
} else if (STRUCT.has(tag)) {
flush();
const el: Block = { k: "el", tag, attrs: attrsOf(c), kids: [] };
out.push(el);
const was = out;
out = el.kids;
visit(c);
flush();
out = was;
} else if (tag === "br") add(" ");
else {
marks.push({ tag, attrs: attrsOf(c) });
visit(c);
marks.pop();
}
}
};
visit(root);
flush();
// A link is the runs inside one <a data-wiki>.
const links: ArticleText["links"] = [];
const seen = new Map<Mark, number>();
const walk = (bs: Block[]) => {
for (const b of bs) {
if (b.k === "el") walk(b.kids);
if (b.k !== "para") continue;
for (const r of b.runs) {
const a = r.marks.find((m) => m.tag === "a" && m.attrs.some(([k]) => k === "data-wiki"));
if (!a) continue;
const i = seen.get(a);
if (i !== undefined) links[i].range[1] = r.e;
else {
seen.set(a, links.length);
links.push({ range: [r.s, r.e], title: a.attrs.find(([k]) => k === "data-wiki")![1] });
}
}
}
};
walk(blocks);
return { text, blocks, links };
}
+20 -7
View File
@@ -1,4 +1,5 @@
/** The keymap. Modal, in the manner of vim: focus is a (node, grain) pair and most keys are one stroke. */
import { inArticles } from "../core/article";
import { store } from "./store";
export const HELP: [string, [string, string][]][] = [
@@ -10,7 +11,7 @@ export const HELP: [string, [string, string][]][] = [
["h", "close, or step out to the parent"],
["i", "narrow the grain: node → sentence → word"],
["Esc", "widen the grain; leave a note; close a panel; stop the editor while it works"],
["Tab", "jump between spans that carry a note or a link; in an article, between its links"],
["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)"],
["v", "view: one column ↔ panes side by side (in panes, j k move among siblings)"],
@@ -30,6 +31,7 @@ export const HELP: [string, [string, string][]][] = [
["S", "review the suggested links of this document one by one: y link · n decline · s skip · Y link all the rest · Esc stop"],
["1–5", "the node's Related list (sections of other documents close in meaning, numbered under its text): with words selected, link them to that one; on the node, go there"],
["l h j k", "in an article: sections are rows, as in a node; l opens one, h goes back"],
["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)"],
],
],
[
@@ -333,19 +335,27 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
return done();
}
if (store.panes) store.syncTrail();
// On a Wikipedia view, a target or a "Linked from" row, the keys mean what they would on rows.
if (!store.aux && ((store.panes && store.trail[store.paneAt]?.kind === "wiki") || (!store.panes && store.colWiki))) {
// On a Wikipedia view, a target or a "Linked from" row, the keys mean what they would on rows
// (unless the focus is an annotation shown in it, which is a node like any other).
const onAnnotation = !!store.snap.nodes[store.focus.node]?.wanchor || inArticles(store.snap, store.focus.node);
if (!store.aux && !onAnnotation && ((store.panes && store.trail[store.paneAt]?.kind === "wiki") || (!store.panes && store.colWiki))) {
store.aux = { kind: "wiki", host: store.panes ? `p${store.paneAt}` : "col", row: { t: "head" } };
}
if (store.aux) {
// An Enter after a Tab that is waiting for its article to arrive waits with it.
if (store.holdKey(k)) return done();
if (store.aux && store.holdKey(k)) return done();
// Words selected in an article's text take the same keys as words of a node.
if (store.aux && !store.inArticleText) {
if (auxKey(k, e.shiftKey) || commonKey(k, hooks)) return done();
const why = store.aux.kind === "wiki" ? store.articleRefuses(k, false) : null;
if (why) (store.say(why), done());
return;
}
if (commonKey(k, hooks)) return done();
const grain = store.focus.grain;
const selecting = grain !== "node";
const selecting = store.focus.grain !== "node" || store.inArticleText;
if (store.inArticleText) {
const why = store.articleRefuses(k, true);
if (why) return store.say(why), done();
}
switch (k) {
case "j":
@@ -536,6 +546,9 @@ function auxKey(k: string, shift: boolean): boolean {
case "Tab":
store.auxTab(shift ? -1 : 1);
return true;
case "i":
store.descend();
return true;
case "L": {
// Under a node, its article opens in a pane of its own.
const a = store.aux;
+4
View File
@@ -8,6 +8,7 @@
*/
import type { JobState } from "../../server/links/jobs";
import type { Related as RelatedRow, Suggestion as Sugg } from "../../server/links/scan";
import { inArticles } from "../core/article";
import { applyLinks, nodeRef } from "../core/links";
import type { Mark } from "../core/marks";
import { ancestors, docOf, notesOf, type Doc, type NodeId, type Snap } from "../core/model";
@@ -110,6 +111,9 @@ 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.
const snap = this.host.doc().snap();
if (snap.nodes[node] && inArticles(snap, node)) return;
const had = this.queue.find((t) => t.node === node);
if (had) {
had.forced = forced.length ? forced : had.forced;
+404 -66
View File
@@ -20,11 +20,13 @@ import {
} from "../core/repo";
import { clip, formFor, plain, rangeAt, sentences, slugify, words, type Form, type Range } from "../core/text";
import { applyLinks, linkIndex, nodeRef, ownerSection, resolveNode } from "../core/links";
import { describeTarget, formatTarget, hostOf, parseTargetLoose, type Ref } from "../core/ref";
import { article as wikiArticle, cachedExtract, sectionsUnder, configureWiki, sensesOf as wikiSenses, wikiLinks, wikiUrl, type WikiConfig } from "./wiki";
import { annotationsOf, articleNodes, inArticles, makeAnchor, reanchor, type ArticleKey } from "../core/article";
import { describeTarget, formatTarget, hostOf, parseTargetLoose, wikiKey, type Ref } from "../core/ref";
import { article as wikiArticle, articleText, cachedExtract, sectionPath, sectionsUnder, sectionTexts, configureWiki, revisionUrl, sensesOf as wikiSenses, wikiUrl, type Article, type WikiConfig } from "./wiki";
import type { ArticleText } from "./articleText";
import { LENSES } from "../llm/prompts";
import {
cascade, commitExpansion, deepen, reconcile, resolveConflicts, runAgent, scanContradictions, streamExpansion,
cascade, commitArticleNote, commitExpansion, deepen, reconcile, resolveConflicts, runAgent, scanContradictions, streamArticleNote, streamExpansion,
type AgentEvent, type ExpansionRequest, type WriteHooks,
} from "../llm/tasks";
import type { LLM } from "../llm/types";
@@ -62,13 +64,14 @@ export interface Back {
/** A row of a Wikipedia view: its head (the lead), a section, a sense of a disambiguation page, a "Mentioned in" entry. */
export type WRow = { t: "head" } | { t: "sec"; id: number } | { t: "sense"; i: number } | { t: "back"; i: number };
/**
* Focus on something that is not a library node: a row or a link in a Wikipedia view (`host` says
* which: `p<i>` the article in pane i, `n<id>` the article under a node in its pane, `col` the
* article page of the column), a node's target, or a "Linked from" row. The node focus stays
* where it was, so leaving the aux focus returns to it.
* Focus on something that is not a library node: a row of a Wikipedia view (`host` says which:
* `p<i>` the article in pane i, `n<id>` the article under a node, `col` the article page of the
* column), or words in the text that row shows (a grain and a range, as in a node's body: a
* sentence, words, a link or an annotation's words), a node's target, or a "Linked from" row. The
* node focus stays where it was, so leaving the aux focus returns to it.
*/
export type Aux =
| { kind: "wiki"; host: string; row: WRow; link?: number }
| { kind: "wiki"; host: string; row: WRow; grain?: "sentence" | "word"; range?: Range }
| { kind: "target"; of: NodeId }
| { kind: "back"; of: NodeId; index: number };
/** A row in a pane or in the column: a section, or an aux row. */
@@ -114,6 +117,8 @@ export interface Pending {
node: NodeId;
kind: "note" | "sections" | "rewrite";
range?: Range;
/** A note being written on words of an article: which article (its key) and section. */
art?: { key: string; sec: number };
form?: Form;
lens?: string;
text: string;
@@ -156,6 +161,21 @@ const lsSet = (k: string, v: unknown) => {
}
};
/** Article text an aux focus is in (Store.auxSpot). */
export interface Spot {
at: ArticleText;
/** The section's id; 0 the lead. */
sec: number;
article: Article;
lang: string;
host: string;
}
/** An article's annotations found again in the revision at hand (Store.annotations). */
export interface Placements {
at: Map<NodeId, { sec: number; range: Range }>;
detached: { id: NodeId; sec: number | null }[];
}
/** Lower-cased title and body, remembered per node entry, for searching a large library on every keystroke. */
const lowered = new WeakMap<object, [string, string]>();
@@ -394,6 +414,8 @@ class Store {
const p = this.trail[i];
const s = this.snap;
const n = s.nodes[f.node];
// An annotation is held by the pane showing its article.
if (p && n && inArticles(s, f.node)) return this.shows(p.kind === "wiki" ? `p${i}` : `n${p.id}`, f.node);
if (!p || p.kind !== "node" || !n) return false;
if (f.grain !== "node" || n.kind === "note") return ownerSection(s, f.node) === p.id || f.node === p.id;
if (f.node === p.id) return i === 0 || !this.continues(i);
@@ -943,9 +965,11 @@ class Store {
const s = this.snap;
if (this.hoist && !s.nodes[this.hoist]) this.hoist = null;
if (!s.nodes[this.focus.node]) this.focus = { node: this.top, grain: "node" };
// An annotation is on screen only with its article; with none showing it, back to the top.
if (inArticles(s, this.focus.node) && !this.hostOf(this.focus.node)) this.focus = { node: this.top, grain: "node" };
const n = s.nodes[this.focus.node];
if (this.focus.range && this.focus.range[1] > n.body.length) this.focus = { node: n.id, grain: "node" };
if (!this.rendered(this.focus.node)) this.reveal(this.focus.node);
if (!this.rendered(this.focus.node) && !inArticles(s, n.id)) this.reveal(this.focus.node);
if (this.aux && !this.auxValid(this.aux)) this.aux = null;
this.syncTrail();
}
@@ -960,6 +984,8 @@ class Store {
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);
}
@@ -1003,7 +1029,8 @@ class Store {
this.colWiki = null;
this.aux = null;
}
const found = w ? ({ node: s.root } as const) : resolve(s, path);
const named = w ? ({ node: s.root } as const) : resolve(s, path);
const found = "node" in named && inArticles(s, named.node) ? ({ node: s.root } as const) : named;
if ("missing" in found) {
this.say(`There is no ${found.missing.replace(/^no /, "")} here. Showing the library.`);
this.hoist = null;
@@ -1054,7 +1081,8 @@ class Store {
*/
reveal(id: NodeId) {
const s = this.snap;
if (!s.nodes[id]) return;
// 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) {
@@ -1118,12 +1146,14 @@ class Store {
const s = this.snap;
const f = this.focus;
const n = s.nodes[f.node];
if (!this.aux && (f.grain === "sentence" || f.grain === "word")) {
const units = f.grain === "sentence" ? sentences(n.body) : words(n.body);
const sel = this.selecting();
if (sel && sel.grain !== "node") {
const units = sel.grain === "sentence" ? sentences(sel.text) : words(sel.text);
if (!units.length) return;
const i = Math.max(0, Math.min(units.length - 1, rangeAt(units, f.range?.[0] ?? 0) + delta));
return this.setFocus({ ...f, range: units[i] });
const i = Math.max(0, Math.min(units.length - 1, rangeAt(units, sel.range?.[0] ?? 0) + delta));
return sel.set(sel.grain, units[i]);
}
if (n.wanchor && !this.aux) return this.moveAnnotation(n.id, delta);
if (n.kind === "note" && !this.aux && !this.paneHead(n.id) && n.id !== this.top) {
// Among the open notes of the same parent, in the order their anchors appear.
const sibs = notesOf(s, n.parent!).filter((id) => this.open.has(id)).sort((a, b) => (s.nodes[a].anchors[0]?.start ?? 0) - (s.nodes[b].anchors[0]?.start ?? 0));
@@ -1149,21 +1179,20 @@ class Store {
/** Grow or shrink the selection by one unit at its far end. */
extend(delta: number) {
const f = this.focus;
if (f.grain === "node" || !f.range) return;
const body = this.snap.nodes[f.node].body;
const units = f.grain === "sentence" ? sentences(body) : words(body);
const last = rangeAt(units, f.range[1] - 1);
const first = rangeAt(units, f.range[0]);
const sel = this.selecting();
if (!sel || sel.grain === "node" || !sel.range) return;
const units = sel.grain === "sentence" ? sentences(sel.text) : words(sel.text);
const last = rangeAt(units, sel.range[1] - 1);
const first = rangeAt(units, sel.range[0]);
const target = Math.max(first, Math.min(units.length - 1, last + delta));
this.setFocus({ ...f, range: [f.range[0], units[target][1]] });
sel.set(sel.grain, [sel.range[0], units[target][1]]);
}
/** l: open, or step into the first child. On a selection: step into the note anchored there. */
into() {
const s = this.snap;
const f = this.focus;
if (f.grain !== "node") return this.move(1);
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();
@@ -1194,6 +1223,7 @@ class Store {
/** Enter on a selection: open the note anchored there, step into it if it is open, or ask for one. */
enterOrExpand() {
if (this.inArticleText) return this.enterArticle();
// Words with a note and a target (the note's own, or a link's on the same words) open as one
// page: the note's text above, the article (or target) beneath.
const both = this.commentaryAt(this.focus.range);
@@ -1214,7 +1244,8 @@ class Store {
const s = this.snap;
const f = this.focus;
const n = s.nodes[f.node];
if (f.grain !== "node") return this.move(-1);
if (f.grain !== "node" || this.inArticleText) return this.move(-1);
if (n.wanchor) return this.leaveAnnotation(n.id);
if (n.kind === "note" && !this.paneHead(n.id) && n.id !== this.top) {
const a = n.anchors[0];
return this.setFocus({ node: n.parent!, grain: a ? "word" : "node", range: a ? [a.start, a.end] : undefined });
@@ -1291,6 +1322,21 @@ class Store {
const s = this.snap;
const f = this.focus;
const n = s.nodes[f.node];
const a = this.aux;
if (a?.kind === "wiki") {
// In an article: into its text, as in a node's body.
if (a.row.t === "sec" && this.wikiHost(a.host)?.nested && !this.colOpen.has(a.row.id)) this.colOpen.add(a.row.id);
const sel = this.selecting();
if (!sel && a.row.t === "head" && this.auxArticle(a)?.state === "loading") {
this.held = { aux: a, keys: [...(this.held && sameAux(this.held.aux, a) ? this.held.keys : []), "i"] };
return this.say("The article is still loading; i selects in it when it arrives.");
}
if (!sel) return this.say(a.row.t === "sec" ? "l opens the section; i then selects in its text." : a.row.t !== "head" ? "Nothing to select here." : this.folded(this.wikiHost(a.host)?.embedded) ? "l unfolds the article; i then selects in it." : "The article is still loading.");
const unit = sel.grain === "node" ? sentences(sel.text)[0] : sel.grain === "sentence" ? words(sel.text, sel.range)[0] : undefined;
if (unit) sel.set(sel.grain === "node" ? "sentence" : "word", unit);
else if (sel.grain === "node") this.say("This part of the article has no text to select.");
return;
}
if (f.grain === "node") {
if (!this.isOpen(f.node) && n.kind === "section" && !this.listing(f.node)) this.open.add(f.node);
if (n.kind === "section") this.rowPane(f.node, true);
@@ -1305,16 +1351,17 @@ class Store {
/** Esc: widen the grain. Word → sentence → node; at the top of a hoisted page, step out of it. */
ascend() {
const f = this.focus;
const body = this.snap.nodes[f.node].body;
if (f.grain === "word") {
const all = sentences(body);
this.setFocus({ node: f.node, grain: "sentence", range: all[rangeAt(all, f.range?.[0] ?? 0)] });
} else if (f.grain === "sentence") this.setFocus({ node: f.node, grain: "node" });
else if (this.hoist && f.node === this.hoist) this.stepOut();
const sel = this.selecting();
if (sel?.grain === "word") {
const all = sentences(sel.text);
sel.set("sentence", all[rangeAt(all, sel.range?.[0] ?? 0)]);
} else if (sel?.grain === "sentence") sel.set("node");
else if (this.hoist && f.node === this.hoist && !this.aux) this.stepOut();
}
/** Tab: jump between the spans that already carry a note. */
nextAnchor(delta: number) {
if (this.aux?.kind === "wiki") return this.auxTab(delta);
const s = this.snap;
const f = this.focus;
const spans = notesOf(s, f.node)
@@ -1523,6 +1570,14 @@ class Store {
remove() {
if (!this.writable()) return;
const s = this.snap;
const sel = this.articleSelection();
if (sel) {
const note = this.annotationAt(sel.spot, sel.range);
if (!note) return this.say("No annotation on these words to delete; Wikipedia's text itself cannot be deleted.");
this.apply([{ op: "delete", id: note }], `Delete note on “${clip(s.nodes[note].wanchor!.q, 40)}”`);
this.open.delete(note);
return this.say("Note deleted. u to undo.");
}
if (this.focus.grain !== "node") {
// On a selection, D removes the note anchored there.
const note = this.noteAt(this.focus.range);
@@ -1533,6 +1588,12 @@ class Store {
}
const n = s.nodes[this.focus.node];
if (!n.parent) return this.say("The library itself cannot be deleted.");
if (n.wanchor) {
// An annotation: back to its words in the article, then away with it.
this.leaveAnnotation(n.id);
this.apply([{ op: "delete", id: n.id }], `Delete note on “${clip(n.wanchor.q, 40)}”`);
return this.say("Note deleted. u to undo.");
}
const order = this.visible();
const i = order.indexOf(n.id);
const sibs = sections(s, n.parent);
@@ -1661,6 +1722,7 @@ class Store {
* otherwise). On a node: open it, then open its sections, then generate sections it lacks.
*/
expand(lens = "elaborate", question?: string) {
if (this.aux?.kind === "wiki") return this.expandArticle(lens, question);
const s = this.snap;
const f = this.focus;
const n = s.nodes[f.node];
@@ -1844,6 +1906,11 @@ class Store {
research: () => this.agent(arg, { research: true }),
};
if (verb.startsWith("/") && builtin[verb.slice(1)]) return builtin[verb.slice(1)]();
if (this.inArticleText) {
const lens = LENSES.find((l) => l === text.toLowerCase());
return this.expandArticle(lens ?? "elaborate", lens ? undefined : text);
}
if (this.aux?.kind === "wiki") return this.say("Select words of the article first (i), then : asks about them. The editor works on your own nodes.");
if (this.focus.grain !== "node") {
// A question about the selection becomes a note answering it.
const lens = LENSES.find((l) => l === text.toLowerCase());
@@ -1854,23 +1921,18 @@ class Store {
// ---- keys on aux rows: Wikipedia views, targets, "Linked from" ----
/** The article HTML whose links Tab walks from this aux focus, if any. */
auxText(a: Aux): string | null {
if (a.kind !== "wiki") return null;
/** The article text an aux focus is in: the lead or the section its row shows, with the article. None while it loads, or on a row that shows no text. */
auxSpot(a: Aux | null = this.aux): Spot | null {
if (a?.kind !== "wiki") return null;
const h = this.wikiHost(a.host);
if (!h) return null;
const art = wikiArticle(h.title, h.lang);
if (art.state !== "ready") return null;
if (a.row.t === "head") {
if (this.folded(h.embedded)) return null;
if (h.sec) return art.value.sections.find((x) => x.id === h.sec)?.html ?? null;
return art.value.lead;
}
if (a.row.t === "sec" && h.nested && this.colOpen.has(a.row.id)) return art.value.sections.find((x) => x.id === (a.row as { id: number }).id)?.html ?? null;
return null;
const art = h ? wikiArticle(h.title, h.lang) : null;
if (!h || art?.state !== "ready") return null;
const sec = a.row.t === "head" ? (this.folded(h.embedded) ? -1 : h.sec) : a.row.t === "sec" && h.nested && this.colOpen.has(a.row.id) ? a.row.id : -1;
const html = sec === 0 ? art.value.lead : art.value.sections.find((x) => x.id === sec)?.html;
return sec < 0 || html === undefined ? null : { at: articleText(html), sec, article: art.value, lang: h.lang, host: a.host };
}
/** Tab on a Wikipedia view: the next (or previous) article link in the text the focus is on. */
/** Tab on a Wikipedia view: the next (or previous) annotation or link in the text the focus is on, selected as words. */
auxTab(delta: number) {
const a = this.aux;
if (!a || a.kind !== "wiki") return;
@@ -1882,14 +1944,301 @@ class Store {
return this.say("The article is still loading; Tab goes to its first link when it arrives.");
}
if (art?.state === "failed") return this.say(`The article could not be loaded: ${art.message}`);
const html = this.auxText(a);
const links = html ? wikiLinks(html) : [];
if (!links.length) return this.say(a.row.t === "head" || a.row.t === "sec" ? "No links to other articles here." : "");
const at = a.link ?? (delta > 0 ? -1 : links.length);
this.aux = { ...a, link: (at + delta + links.length) % links.length };
const spot = this.auxSpot(a);
const spans = spot ? this.spansIn(spot) : [];
if (!spans.length) return this.say(a.row.t === "head" || a.row.t === "sec" ? "No links to other articles or notes here." : "");
const at = a.range?.[0] ?? (delta > 0 ? -1 : Infinity);
const next = delta > 0 ? spans.find((r) => r[0] > at) ?? spans[0] : [...spans].reverse().find((r) => r[0] < at) ?? spans[spans.length - 1];
this.setFocus(this.focus, { ...a, grain: "word", range: next });
}
/** The article a focused link inside an article names: the link whose words are exactly the selection. */
auxLink(a: Aux): { title: string; lang: string } | null {
if (a.kind !== "wiki" || !a.range) return null;
const spot = this.auxSpot(a);
const l = spot?.at.links.find((x) => x.range[0] === a.range![0] && x.range[1] === a.range![1]);
return l && spot ? { title: l.title, lang: spot.lang } : null;
}
// ---- annotating articles (src/core/article.ts) ----
private placed = new WeakMap<Article, { entries: unknown[]; value: Placements }>();
/**
* An article's annotations, found again in the revision at hand: where each is (a section's id
* and a range in its text), and those whose words are gone. Worked out again only when the
* article or one of its annotations changes.
*/
annotations(article: Article, lang: string): Placements {
const s = this.snap;
const ids = annotationsOf(s, { lang, title: article.title, pageId: article.pageId });
const entries = ids.map((id) => s.nodes[id]);
const had = this.placed.get(article);
if (had && had.entries.length === entries.length && had.entries.every((e, i) => e === entries[i])) return had.value;
const value: Placements = { at: new Map(), detached: [] };
if (ids.length) {
const { ids: secIds, secs } = sectionTexts(article);
for (const id of ids) {
const p = reanchor(s.nodes[id].wanchor!, secs);
if ("detached" in p) value.detached.push({ id, sec: p.sec === null ? null : secIds[p.sec] });
else value.at.set(id, { sec: secIds[p.sec], range: p.range });
}
}
this.placed.set(article, { entries, value });
return value;
}
/** What Tab stops at in a piece of article text: its annotations' words and its links, in reading order. */
private spansIn(spot: Spot): Range[] {
const notes = [...this.annotations(spot.article, spot.lang).at.values()].filter((p) => p.sec === spot.sec).map((p) => p.range);
const seen = new Set<string>();
return [...notes, ...spot.at.links.map((l) => l.range)].sort((a, b) => a[0] - b[0] || a[1] - b[1]).filter((r) => !seen.has(r.join()) && !!seen.add(r.join()));
}
/** The annotation on exactly these words of a piece of article text. */
private annotationAt(spot: Spot, range: Range | undefined): NodeId | undefined {
if (!range) return;
for (const [id, p] of this.annotations(spot.article, spot.lang).at) if (p.sec === spot.sec && p.range[0] === range[0] && p.range[1] === range[1]) return id;
}
/** The selection in article text, when the focus is one: where it is, and its range. */
private articleSelection(): { a: Aux & { kind: "wiki" }; spot: Spot; range: Range; grain: "sentence" | "word" } | null {
const a = this.aux;
if (a?.kind !== "wiki" || !a.grain || !a.range) return null;
const spot = this.auxSpot(a);
return spot ? { a, spot, range: a.range, grain: a.grain } : null;
}
/** Whether the focus is a selection in an article's text. */
get inArticleText(): boolean {
return this.aux?.kind === "wiki" && !!this.aux.grain;
}
/** The text the focus selects in and how to move the selection: a node's body, or an article's text under the aux focus. */
private selecting(): { text: string; grain: Grain; range?: Range; set: (grain: Grain, range?: Range) => void } | null {
const a = this.aux;
if (a?.kind === "wiki") {
const spot = this.auxSpot(a);
if (!spot) return null;
return {
text: spot.at.text,
grain: a.grain ?? "node",
range: a.range,
set: (grain, range) => this.setFocus(this.focus, grain === "node" ? { kind: "wiki", host: a.host, row: a.row } : { kind: "wiki", host: a.host, row: a.row, grain, range }),
};
}
if (a) return null;
const f = this.focus;
return { text: this.snap.nodes[f.node].body, grain: f.grain, range: f.range, set: (grain, range) => this.setFocus({ node: f.node, grain, range }) };
}
/** e d y x c and : on words of an article: open the annotation already there, or have one written. */
private expandArticle(lens: string, question?: string) {
const sel = this.articleSelection();
if (!sel) return this.say("Select words first: i, then e d y x c or :. An article itself is never deepened or rewritten.");
const existing = this.annotationAt(sel.spot, sel.range);
if (existing && lens === "elaborate" && !question) {
if (this.open.has(existing)) this.open.delete(existing);
else this.open.add(existing);
this.saveView();
return this.emit();
}
this.generateArticleNote(sel.spot, sel.range, lens, question);
}
/** Enter on words of an article: an annotation opens, and Enter again steps into it; a link opens its article; anything else is expanded. */
private enterArticle() {
const sel = this.articleSelection()!;
const note = this.annotationAt(sel.spot, sel.range);
if (!note) {
const link = this.auxLink(sel.a);
return link ? this.follow({ kind: "wiki", title: link.title, lang: link.lang }) : this.expandArticle("elaborate");
}
if (this.open.has(note)) return this.setFocus({ node: note, grain: "node" });
this.open.add(note);
this.saveView();
this.emit();
}
private generateArticleNote(spot: Spot, range: Range, lens: string, question?: string) {
if (!this.writable()) return;
if (!this.generating) return this.say("No model is configured to write a note. Start the server with ANTHROPIC_API_KEY set.");
const quote = spot.at.text.slice(range[0], range[1]);
if (!quote.trim()) return;
const a = spot.article;
const form = formFor(quote);
const req = {
article: { lang: spot.lang, title: a.title, pageId: a.pageId },
anchor: makeAnchor(spot.at.text, range, sectionPath(a, spot.sec), a.revisionId),
form,
lens,
question,
context: this.articleContext(spot, range),
};
const p: Pending = { key: `p${++this.seq}`, node: "" as NodeId, kind: "note", range, form, lens: question ?? lens, text: "", art: { key: wikiKey(spot.lang, a.title), sec: spot.sec } };
const doc = this.doc;
this.pending.set(p.key, p);
this.busy++;
this.emit();
streamArticleNote(this.llm, req, (d) => ((p.text += d), this.emit()))
.then((text) => {
this.open.add(commitArticleNote(doc, req, text));
this.saveView();
})
.catch((err) => this.say(err instanceof Error ? err.message : String(err)))
.finally(() => {
this.pending.delete(p.key);
this.busy--;
this.emit();
});
}
/** What a note on words of an article is written from: the lead, the section around the words (trimmed), and the reader's own sentence if the article was opened from one. */
private articleContext(spot: Spot, range: Range) {
const a = spot.article;
const text = spot.at.text;
const from = Math.max(0, range[0] - 3000);
return {
title: a.title,
lead: clip(articleText(a.lead).text, spot.sec ? 2000 : 6000),
heading: spot.sec ? sectionPath(a, spot.sec).join(" › ") : null,
section: spot.sec ? `${from ? "… " : ""}${text.slice(from, range[1] + 3000)}${range[1] + 3000 < text.length ? " …" : ""}` : "",
selection: text.slice(range[0], range[1]),
from: this.fromSentence(spot.host),
};
}
/** The sentence of the reader's own text an article view was opened from, if it was opened from words. */
private fromSentence(host: string): string | undefined {
const s = this.snap;
let f: Focus | undefined;
const n = host.startsWith("n") ? s.nodes[host.slice(1) as NodeId] : undefined;
if (n?.kind === "note" && n.parent && n.anchors[0]) f = { node: n.parent, grain: "word", range: [n.anchors[0].start, n.anchors[0].end] };
else if (host.startsWith("p")) {
const b = this.trail[+host.slice(1)]?.from;
if (b && !b.aux) f = b.focus;
} else if (host === "col" && this.colWiki && !this.colWiki.stack.length && !this.colWiki.back.aux) f = this.colWiki.back.focus;
const body = f?.range ? s.nodes[f.node]?.body : undefined;
const sent = body ? sentences(body).find(([x, y]) => f!.range![0] >= x && f!.range![0] < y) : undefined;
return sent ? plain(body!.slice(sent[0], sent[1])) : undefined;
}
/** The node of the article an annotation (or a note inside one) belongs to. */
private articleOf(id: NodeId): NodeId | undefined {
const s = this.snap;
for (let x: NodeId | null = id; x && s.nodes[x]; x = s.nodes[x].parent) if (s.nodes[x].parent && s.nodes[s.nodes[x].parent!].articles) return x;
}
/** The article a host shows, keyed as the library files it: by its loaded title and page id when it has arrived. */
private hostArticle(host: string): ArticleKey | null {
const h = this.wikiHost(host);
if (!h) return null;
const art = wikiArticle(h.title, h.lang);
return art.state === "ready" ? { lang: h.lang, title: art.value.title, pageId: art.value.pageId } : { lang: h.lang, title: h.title };
}
/** The views that could show an annotation: the article page, a pane's article, the article under a pane's node or the column's top. */
private hosts(): string[] {
if (!this.panes) return this.colWiki ? ["col"] : this.articleUnder(this.top) ? [`n${this.top}`] : [];
return this.trail.flatMap((p, i) => (p.kind === "wiki" ? [`p${i}`] : this.articleUnder(p.id) ? [`n${p.id}`] : []));
}
/** Whether a view shows the article an annotation (or a note inside one) is on. */
private shows(host: string, id: NodeId): boolean {
const art = this.articleOf(id);
const k = art && this.hostArticle(host);
return !!k && articleNodes(this.snap, k).includes(art!);
}
/** The view showing the article an annotation is on, the focused pane's first. */
private hostOf(id: NodeId): string | undefined {
const p = this.panes ? this.trail[this.paneAt] : undefined;
const mine = p ? (p.kind === "wiki" ? `p${this.paneAt}` : `n${p.id}`) : undefined;
return mine && this.shows(mine, id) ? mine : this.hosts().find((h) => this.shows(h, id));
}
/** h on an annotation: back to its words in the article. */
private leaveAnnotation(id: NodeId) {
const host = this.hostOf(id);
const k = host ? this.hostArticle(host) : null;
const art = k ? wikiArticle(k.title, k.lang) : null;
const p = k && art?.state === "ready" ? this.annotations(art.value, k.lang).at.get(id) : undefined;
if (!host) return this.say("Its article is not on screen.");
if (host.startsWith("p")) this.paneAt = +host.slice(1);
const node = this.focusFor(host);
// A detached annotation has no words to return to: back to the article.
if (!p) return this.setFocus(node, { kind: "wiki", host, row: { t: "head" } });
const h = this.wikiHost(host)!;
const row: WRow = p.sec === h.sec ? { t: "head" } : { t: "sec", id: p.sec };
if (row.t === "sec") this.colOpen.add(p.sec);
this.setFocus(node, { kind: "wiki", host, row, grain: "word", range: p.range });
}
/** j k on an annotation: the next or previous open annotation of the same article, in reading order. */
private moveAnnotation(id: NodeId, delta: number) {
const host = this.hostOf(id);
const k = host ? this.hostArticle(host) : null;
const art = k ? wikiArticle(k.title, k.lang) : null;
if (!k || art?.state !== "ready") return;
const order = sectionTexts(art.value).ids;
const list = [...this.annotations(art.value, k.lang).at].filter(([x]) => this.open.has(x)).sort(([, a], [, b]) => order.indexOf(a.sec) - order.indexOf(b.sec) || a.range[0] - b.range[0]);
const next = list[list.findIndex(([x]) => x === id) + delta];
if (next) this.setFocus({ node: next[0], grain: "node" });
}
/** The selected words, in a node's body or an article's text; null when nothing smaller than a node is selected. */
selectedText(): string | null {
const sel = this.selecting();
return sel && sel.grain !== "node" && sel.range ? sel.text.slice(sel.range[0], sel.range[1]) : null;
}
/** The annotation on exactly the selected words of an article, if any. */
articleNoteHere(): NodeId | undefined {
const sel = this.articleSelection();
return sel ? this.annotationAt(sel.spot, sel.range) : undefined;
}
/** The node focus to keep under an aux focus on an article view: the node it is under, else where it was, if that is not an annotation. */
private focusFor(host: string): Focus {
if (host.startsWith("n")) return { node: host.slice(1) as NodeId, grain: "node" };
return inArticles(this.snap, this.focus.node) ? { node: this.top, grain: "node" } : this.focus;
}
/** A click or a drag in an article's text: the sentence at a point, or the words dragged over. */
selectInArticle(host: string, row: WRow, range: Range, grain: "sentence" | "word") {
const a: Aux = { kind: "wiki", host, row };
const spot = this.auxSpot(a);
if (!spot) return this.setFocus(this.focus, a);
const all = sentences(spot.at.text);
const r: Range = grain === "sentence" ? all.find((x) => range[0] >= x[0] && range[0] <= x[1]) ?? all[rangeAt(all, range[0])] : range;
if (r) this.setFocus(this.focusFor(host), { ...a, grain, range: r });
}
/** A click on an annotation's words: it opens or closes, and the words are selected. */
toggleAnnotation(host: string, row: WRow, id: NodeId) {
const k = this.hostArticle(host);
const art = k ? wikiArticle(k.title, k.lang) : null;
const p = k && art?.state === "ready" ? this.annotations(art.value, k.lang).at.get(id) : undefined;
if (this.open.has(id)) this.open.delete(id);
else this.open.add(id);
this.saveView();
if (p) this.selectInArticle(host, row, p.range, "word");
else this.emit();
}
/** Why a key that works on a node does nothing on Wikipedia's text, for the status line; null for a key that does work there. */
articleRefuses(k: string, selecting: boolean): string | null {
const own = "Wikipedia's text is shown as it is: it cannot be edited, renamed, moved, pinned, reconciled or rewritten here. Annotations on it can: i selects words, e d y x c writes one.";
if (["r", "a", "A", "J", "K", ">", "<", "p", "R", "b", "o", "O", "z"].includes(k) && !(selecting && (k === "J" || k === "K"))) return own;
if (k === "c" && !selecting) return "Wikipedia's text cannot be edited here. Select words (i) and press c to challenge them, or e d y x to annotate them.";
if (["e", "d", "y", "x"].includes(k) && !selecting) return "Select words first: i, then e d y x c or :. An article itself is never deepened or rewritten.";
if (k === "D" && !selecting) return "An article cannot be deleted. D on an annotation's words deletes the annotation.";
if (k === "w") return "Words of an article cannot be linked from here; W opens it on wikipedia.org.";
if (k === "f") return "f changes an annotation's form: Enter on its words, Enter again, then f.";
if (k === "S" || k === "n") return "Link suggestions are for your own text, not Wikipedia's.";
if (/^[1-5]$/.test(k)) return "Related is listed under your own nodes, not under an article.";
return null;
}
/** The article an aux focus shows, as loaded so far. */
private auxArticle(a: Aux) {
if (a.kind !== "wiki") return null;
@@ -1904,8 +2253,8 @@ class Store {
holdKey(k: string): boolean {
const h = this.held;
if (!h) return false;
if (k === "Enter" && sameAux(h.aux, this.aux)) {
h.keys.push("Enter");
if ((k === "Enter" || k === "i") && sameAux(h.aux, this.aux)) {
h.keys.push(k);
return true;
}
if (k !== "Tab") this.held = null;
@@ -1922,20 +2271,12 @@ class Store {
this.held = null;
if (art?.state !== "ready") return;
for (const k of h.keys) {
if (k === "Enter") this.auxActivate();
if (k === "Enter") this.inArticleText ? this.enterArticle() : this.auxActivate();
else if (k === "i") this.descend();
else this.auxTab(k === "Tab" ? 1 : -1);
}
}
/** The article a focused link inside an article names. */
auxLink(a: Aux): { title: string; lang: string } | null {
if (a.kind !== "wiki" || a.link === undefined) return null;
const html = this.auxText(a);
const l = html ? wikiLinks(html)[a.link] : undefined;
const h = this.wikiHost(a.host);
return l && h ? { title: l.title, lang: h.lang } : null;
}
/** l, Enter: open what an aux row is: a section (as a pane, or in place on the column's page), a sense, a link, a target, a linking node. */
auxActivate() {
const a = this.aux;
@@ -1986,10 +2327,6 @@ class Store {
const a = this.aux;
if (!a) return;
if (a.kind !== "wiki") return this.setFocus({ node: a.of, grain: "node" });
if (a.link !== undefined) {
this.aux = { ...a, link: undefined };
return this.emit();
}
const h = this.wikiHost(a.host);
if (a.row.t !== "head") {
// On the column's page an open section's subsection steps out to the section first.
@@ -2068,6 +2405,7 @@ class Store {
/** w: the link picker, filled in with the selected words. On words that already link somewhere, it retargets them. */
openPicker() {
if (!this.writable()) return;
if (this.aux?.kind === "wiki") return this.say(this.articleRefuses("w", true)!);
const spot = this.linkSpot();
if (!spot) return this.say("Select words to link (i, then H L to widen), or press w on a node to give the node itself a target.");
if (isLibraryRoot(this.snap, spot.node) && !spot.range) return this.say("The library itself has no target.");
@@ -2751,7 +3089,7 @@ class Store {
search(q: string): 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);
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 low = (n: (typeof all)[number]) => {
let l = lowered.get(n);
+11
View File
@@ -505,6 +505,17 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.wiki-text blockquote { margin: 0.4em 0 0.7em 1em; padding-left: 0.7em; border-left: 2px solid var(--wiki-rule); }
.wiki-text pre, .wiki-text code { font-family: var(--mono); font-size: 0.9em; }
.wiki-text math { font-size: 1.05em; }
/* Annotations in an article are the library's own notes: its dotted underline, its serif face, set off from Wikipedia's text. */
.wiki-text .gloss, .wiki-text .inset, .wdetached .inset { font-family: var(--serif); text-align: left; }
.wiki-text .gloss { color: var(--fg); font-size: 0.98em; }
.wiki-text .inset, .wdetached .inset { display: block; margin: 0.35rem 0 0.75rem 1.2em; padding: 0.35rem 0.75rem; font-size: 0.86rem; line-height: 1.45; background: var(--bg); color: var(--fg); border-left: 2px dotted var(--faint); }
.wiki-text .inset.focused, .wdetached .inset.focused { border-left: 2px solid var(--fg); }
.wiki-text .gloss.focused { background: var(--sel); }
.wdetached { margin: 0 0 0.6rem; }
.wdetached .inset { margin-left: 0; border-left: 2px dashed var(--attn); }
.wdetached .meta { color: var(--attn); text-transform: none; letter-spacing: 0.02em; font-size: 0.66rem; }
.wdetached .meta a { color: inherit; text-decoration: underline 1px dotted; text-underline-offset: 0.15em; }
.wiki-text .wmath.sel { outline: 1px solid var(--sel-strong); }
.wiki-desc { margin: -0.4rem 0 0.6rem; font-size: 0.74rem; color: var(--dim); font-style: italic; }
.wiki-summary { margin: 0 0 0.5rem; font-size: 0.82rem; line-height: 1.55; }
.wiki-more, .wiki-wait, .wiki-back { margin: 0.3rem 0; font-size: 0.66rem; color: var(--faint); letter-spacing: 0.02em; }
+30 -8
View File
@@ -9,7 +9,9 @@
* attributes survives, and every link either names an article (data-wiki) or opens a new tab.
*/
import type { Attribution, FullArticle as Article, Sense, Summary, TitleSuggestion as Suggestion } from "../../server/wiki";
import type { SectionText } from "../core/article";
import { wikiKey, wikiTitle } from "../core/ref";
import { buildText, type ArticleText } from "./articleText";
export type { Article, Attribution, Suggestion };
type WikiSection = Article["sections"][number];
@@ -196,18 +198,38 @@ export function cleanHtml(html: string): string {
return out;
}
/** The article links in a piece of article HTML, in reading order: what Tab cycles through. */
const linkLists = new Map<string, { title: string; text: string }[]>();
export function wikiLinks(html: string): { title: string; text: string }[] {
let out = linkLists.get(html);
/** A piece of article HTML as text to select in (articleText.ts). Remembered per string. */
const texts = new Map<string, ArticleText>();
export function articleText(html: string): ArticleText {
let out = texts.get(html);
if (out) return out;
const doc = new DOMParser().parseFromString(`<body>${cleanHtml(html)}</body>`, "text/html");
out = [...doc.querySelectorAll("a[data-wiki]")].map((a) => ({ title: a.getAttribute("data-wiki")!, text: a.textContent ?? "" }));
if (linkLists.size > 400) linkLists.delete(linkLists.keys().next().value as string);
linkLists.set(html, out);
out = buildText(new DOMParser().parseFromString(`<body>${cleanHtml(html)}</body>`, "text/html").body);
if (texts.size > 400) texts.delete(texts.keys().next().value as string);
texts.set(html, out);
return out;
}
/** The headings down to a section (0: the lead, []): how an annotation names where it is. */
export function sectionPath(a: Article, id: number): string[] {
const out: string[] = [];
for (let s = a.sections.find((x) => x.id === id); s; s = a.sections.find((x) => x.id === s!.parent)) out.unshift(s.heading);
return out;
}
/** Every section's text with its headings, the lead first: what annotations are found again in. Remembered per article. */
const sectionLists = new WeakMap<Article, { ids: number[]; secs: SectionText[] }>();
export function sectionTexts(a: Article): { ids: number[]; secs: SectionText[] } {
let out = sectionLists.get(a);
if (!out) {
out = { ids: [0, ...a.sections.map((s) => s.id)], secs: [{ path: [], text: articleText(a.lead).text }, ...a.sections.map((s) => ({ path: sectionPath(a, s.id), text: articleText(s.html).text }))] };
sectionLists.set(a, out);
}
return out;
}
/** The address of a past revision of an article. */
export const revisionUrl = (title: string, rev: number, lang = config.lang) => `https://${lang}.wikipedia.org/w/index.php?title=${encodeURIComponent(wikiTitle(title).replace(/ /g, "_"))}&oldid=${rev}`;
/**
* The sections under one (0: the top level) that have something to show: the sanitiser empties
* Notes and References, and a row that opens onto nothing is noise.
+78
View File
@@ -0,0 +1,78 @@
/**
* Article HTML as selectable text (src/ui/articleText.ts), on the mock articles as the server
* sanitises them, parsed with parse5 in place of the browser's DOMParser: what is text, what is
* not, links and formulas, and that every sentence anchors and re-anchors to itself.
*/
import { parseFragment, serializeOuter, type DefaultTreeAdapterTypes as T } from "parse5";
import { describe, expect, it } from "vitest";
import { makeAnchor, reanchor } from "../src/core/article";
import { sentences } from "../src/core/text";
import { buildText, type Block, type DomLike } from "../src/ui/articleText";
import { WikiClient } from "../server/wiki";
import { mockWikiFetch } from "../server/wikiMock";
/** A parse5 node as the little of the DOM the walk uses. */
function adapt(n: T.Node): DomLike {
if (n.nodeName === "#text") return { nodeType: 3, data: (n as T.TextNode).value, textContent: (n as T.TextNode).value, childNodes: [] };
if (!("tagName" in n)) return { nodeType: 8, textContent: "", childNodes: "childNodes" in n ? (n as T.ParentNode).childNodes.map(adapt) : [] };
const el = n as T.Element;
const text = (x: T.Node): string => (x.nodeName === "#text" ? (x as T.TextNode).value : "childNodes" in x ? (x as T.Element).childNodes.map(text).join("") : "");
return { nodeType: 1, localName: el.tagName, textContent: text(el), childNodes: el.childNodes.map(adapt), attributes: el.attrs, outerHTML: serializeOuter(el) };
}
const build = (html: string) => buildText({ nodeType: 11, textContent: "", childNodes: parseFragment(html).childNodes.map(adapt) });
async function article(title: string) {
const r = await new WikiClient({ fetch: mockWikiFetch, spacingMs: 0, persist: false, offlineHoldMs: 0 }).article(title, { sections: true });
if (!r.ok) throw new Error(r.message);
return r.value;
}
const kinds = (bs: Block[]): string[] => bs.flatMap((b) => (b.k === "el" ? [b.tag, ...kinds(b.kids)] : [b.k]));
describe("article text", () => {
it("is the paragraphs' visible text, links as ranges of it, a formula as one run", async () => {
const a = await article("Fixed-point combinator");
const lead = build(a.lead);
expect(lead.text).toMatch(/^In mathematics and computer science, a fixed-point combinator \(or fixpoint combinator\) is a higher-order function that, given a function f, returns a fixed point of f: a value x with f\(x\) = x\. In the untyped lambda calculus/);
expect(lead.text).not.toMatch(/ {2}|\n(?!\n)|\[1\]/);
expect(lead.links.map((l) => [lead.text.slice(...l.range), l.title])).toEqual([
["lambda calculus", "Lambda calculus"],
["Haskell Curry", "Haskell Curry"],
["recursion", "Recursion (computer science)"],
]);
const y = build(a.sections.find((s) => s.heading === "Y combinator")!.html);
const runs = y.blocks.flatMap((b) => (b.k === "para" ? b.runs : []));
const math = runs.filter((r) => r.math);
expect(math).toHaveLength(1);
expect(y.text.slice(math[0].s, math[0].e)).toBe("Y=λf.(λx.f(xx))(λx.f(xx))");
expect(math[0].math).toMatch(/^<math/);
// Code and italics are inline runs of the same text.
expect(runs.some((r) => r.marks.some((m) => m.tag === "code") && y.text.slice(r.s, r.e) === "(λx.x x)(λx.x x)")).toBe(true);
});
it("makes a paragraph of each list item; a table is shown but carries no text", async () => {
const m = build((await article("Mercury")).lead);
expect(kinds(m.blocks)).toEqual(["para", "ul", "li", "para", "li", "para", "li", "para"]);
expect(m.text.split("\n\n")).toEqual(["Mercury commonly refers to:", "Mercury (planet), the planet closest to the Sun", "Mercury (element), a metallic chemical element with the symbol Hg", "Mercury (mythology), a Roman god"]);
const t = build(`<p>Before.</p><table><tbody><tr><td>cell text</td></tr></tbody></table><p>After <i>it</i>.</p><pre>code block</pre>`);
expect(t.text).toBe("Before.\n\nAfter it.");
expect(kinds(t.blocks)).toEqual(["para", "raw", "para", "raw"]);
});
it("keeps every paragraph's offsets in its runs, and every sentence of every section anchors back to itself", async () => {
for (const title of ["Fixed-point combinator", "Octopus", "Hoyle state", "Mercury", "Carbon-12"]) {
const a = await article(title);
const secs = [{ path: [] as string[], html: a.lead }, ...a.sections.map((s) => ({ path: [s.heading], html: s.html }))].map((s) => ({ path: s.path, t: build(s.html) }));
for (const [i, s] of secs.entries()) {
const paras = s.t.blocks.flatMap(function all(b: Block): Block[] {
return b.k === "el" ? b.kids.flatMap(all) : [b];
}).filter((b) => b.k === "para");
for (const p of paras) if (p.k === "para") expect(p.runs.map((r) => s.t.text.slice(r.s, r.e)).join("")).toBe(s.t.text.slice(p.s, p.e));
for (const r of sentences(s.t.text)) {
const got = reanchor(makeAnchor(s.t.text, r, s.path, a.revisionId), secs.map((x) => ({ path: x.path, text: x.t.text })));
expect(got).toEqual({ sec: i, range: r });
}
}
}
});
});