/**
* 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(/^