Files
explicata/tests/articleText.test.ts
T
thalladaandClaude Opus 5.5 2c1ee048a4 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
2026-11-15 21:53:00 -05:00

79 lines
5.0 KiB
TypeScript

/**
* 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 });
}
}
}
});
});