// Picking a post item's excerpt by selecting its words (excerptPick.mjs): snapped to words, merged, settled // where the build's indexOf will find each span. Run with: pnpm test:scripts import assert from "node:assert/strict"; import test from "node:test"; import { addRange, piecesOf, rangesOf, settleRanges, snapToWords, spansOf } from "./excerptPick.mjs"; import { excerptRanges } from "umtool-report-to-video/post-item"; const T = "The scale said 291. I said the scale was broken. Then the scale said 290."; test("a selection snaps out to whole words, trimmed", () => { const r = snapToWords(T, T.indexOf("cale said 2"), T.indexOf("291") + 2); assert.deepEqual(spansOf(T, [r]), ["scale said 291."]); assert.equal(snapToWords(T, 3, 4), null); assert.deepEqual(snapToWords(T, 0, 1), { start: 0, end: 3 }); }); test("ranges merge in the post's order", () => { let rs = addRange([], { start: 20, end: 30 }); rs = addRange(rs, { start: 0, end: 5 }); rs = addRange(rs, { start: 28, end: 40 }); assert.deepEqual(rs, [{ start: 0, end: 5 }, { start: 20, end: 40 }]); }); test("a span whose words come earlier too is widened until the build finds it where it was picked", () => { const W = "scale said"; const second = T.lastIndexOf(W); assert.ok(T.indexOf(W) < second); const picked = [{ start: second, end: second + W.length }]; const settled = settleRanges(T, picked); const spans = spansOf(T, settled); assert.deepEqual(excerptRanges(T, spans).map((r) => r.end), [second + W.length]); assert.deepEqual(spans, ["the scale said"]); // Two spans: the second found after the first. const two = settleRanges(T, [{ start: 0, end: 9 }, picked[0]]); assert.deepEqual(excerptRanges(T, spansOf(T, two)), two); assert.deepEqual(rangesOf(T, spansOf(T, two)), two); }); test("the pieces cover the text, the picked ones marked", () => { const p = piecesOf(T, [{ start: 4, end: 9 }]); assert.equal(p.map((x) => x.text).join(""), T); assert.deepEqual(p.filter((x) => x.picked).map((x) => x.text), ["scale"]); });