diff --git a/apps/writer/package.json b/apps/writer/package.json index 4d689784..5e2263d2 100644 --- a/apps/writer/package.json +++ b/apps/writer/package.json @@ -32,8 +32,8 @@ "typecheck": "pnpm manifest && tsc -p tsconfig.json", "deploy:lab": "MDBASE_ENV=lab node scripts/deploy-pages.mjs", "upload:compiler": "node scripts/upload-compiler.mjs", - "test:perf-fixture": "PERF_RUNS=1 PERF_LATENCY_MS=0 vitest run --config scripts/perf/vitest.config.ts", - "typecheck:perf": "tsc -p scripts/perf/tsconfig.json" + "test:perf-fixture": "pnpm manifest && PERF_RUNS=1 PERF_LATENCY_MS=0 vitest run --config scripts/perf/vitest.config.ts", + "typecheck:perf": "pnpm manifest && tsc -p scripts/perf/tsconfig.json" }, "dependencies": { "@codemirror/autocomplete": "^6.20.3", diff --git a/apps/writer/scripts/perf/README.md b/apps/writer/scripts/perf/README.md index 63291878..103a890d 100644 --- a/apps/writer/scripts/perf/README.md +++ b/apps/writer/scripts/perf/README.md @@ -8,7 +8,28 @@ rpnpm --filter @mdbase-writer/app typecheck:perf pnpm -C apps/writer typecheck ``` -The registered smoke check runs one zero-latency fixture with `rpnpm --filter @mdbase-writer/app test:perf-fixture`. +Run both benchmarks with `rpnpm --filter @mdbase-writer/app test:perf-fixture`. This uses one zero-latency run of the collection fixture. + +Run just the mounted outline benchmark from the repository root: + +```sh +rpnpm --filter @mdbase-writer/app run test:perf-fixture scripts/perf/outline.bench.tsx +``` + +It renders all 120 chapter rows through the normal outline pagination, edits one chapter, and switches among four loaded chapters. It checks section words and searches for one sparse term and one broad term across the same manuscript. Each phase has 5 warmups and 20 measurements. The fixture has 24 headings and three comment offsets per chapter. Outline timings include React commits in jsdom. + +For a control at `ba47bda`, create a detached worktree and copy these files from the performance branch before running the same commands. Start the dev server from that worktree for the Chromium comparison. + +```text +apps/writer/package.json +apps/writer/scripts/perf/browser-profile.mjs +apps/writer/scripts/perf/generator.ts +apps/writer/scripts/perf/outline.bench.tsx +apps/writer/scripts/perf/tsconfig.json +apps/writer/scripts/perf/vitest.config.ts +apps/writer/src/backend/large-demo.ts +apps/writer/src/ui/DemoRoot.tsx +``` Capture JSON (output path is relative to `apps/writer`): @@ -37,6 +58,17 @@ Result JSON is generated evidence: the default is `out/perf/large-collection.jso ## Recorded outcomes +Outline comparison on the remote builder (AMD EPYC 9B14, Node 22.22.0). The two revisions ran the same outline benchmark three times each, with Writer at `ba47bda` for the control. The p50 columns are medians of the three runs. The p95 columns show the spread across runs. + +| Operation | Before p50 | After p50 | Before p95 range | After p95 range | +|---|---:|---:|---:|---:| +| Typing in one chapter | 19.97 ms | 16.76 ms | 21.66–49.75 ms | 19.00–47.49 ms | +| Switching chapters | 21.98 ms | 18.57 ms | 20.45–60.42 ms | 18.89–19.30 ms | +| Sparse manuscript search (1 hit) | 1.31 ms | 1.31 ms | 1.32–1.40 ms | 1.32–1.33 ms | +| Broad manuscript search (34,560 hits) | 2.46 ms | 2.38 ms | 2.87–4.62 ms | 2.68–2.77 ms | + +In one zero-latency collection run, warm search over 5,000 sources took 0.73 ms median, and resolving paths for 100 chapter embeds took 0.25 ms median. Cached placement of 300 comments took 0.03 ms, cold placement across 3,000 comments took 10.06 ms, and server rendering the Comments panel took 24.78 ms. Scanning 100 records from scratch for words, labels, and citations took 21.85 ms. Writer already tracks those manuscript totals by changed body. The outline change reuses heading parses and section counts across edits and chapter switches. + Round 3, three-run 20 ms medians (before → after): | Metric | Before | After | @@ -57,14 +89,16 @@ Round 5 keeps the incremental traffic totals above, selected-body batching and w ## Chromium responsiveness profile (Round 4) -Start the normal development server, then visit `http://127.0.0.1:5320/?demo=large&manuscript=manuscripts/main.md`. This mode shares `generator.ts` with the Node benchmark; it adds 100 labelled headings, 300 highlights on one source and one 149-reply thread. It uses NativeWriterBackend, SDK sessions, compiler and renderer over an in-memory SDK fixture. It is DEV-only, even for a production demo build. +Start the normal development server, then visit `http://127.0.0.1:5320/?demo=large&largeManuscript=1&manuscript=manuscripts/main.md`. This mode shares `generator.ts` with the Node benchmark. The Chromium fixture adds 60 embedded chapters, 100 labelled main-record headings, 300 highlights on one source and one 149-reply thread. It uses NativeWriterBackend, SDK sessions, compiler and renderer over an in-memory SDK fixture. It is DEV-only, even for a production demo build. + +A 120-chapter attempt with SDK 0.2.58 opened the main record and 63 chapters. The SDK refused the other 57 with `record_session_budget` because Writer retains a session for each embedded chapter. The browser fixture uses 60 chapters so it can exercise the complete manuscript. The 120-chapter outline benchmark supplies record views directly. ```sh PROFILE_NAME=after PROFILE_OUTPUT=out/perf/browser-after.json pnpm -C apps/writer exec node scripts/perf/browser-profile.mjs pnpm -C apps/writer test:browser ``` -`BASE`, `CHROME`, `PROFILE_NAME`, `PROFILE_OUTPUT` are configurable. +`BASE`, `CHROME`, `PROFILE_NAME`, and `PROFILE_OUTPUT` are configurable. Set `PROFILE_EDITOR_ONLY=1` to measure editing with the preview pane hidden. HTTP cache is explicitly disabled and service workers bypassed on every profile. The profiler now also captures startup tasks, first drawn-revision time, worker messages/resource timings, main heap after forced GC/full discovery and worker @@ -78,9 +112,28 @@ pnpm -C apps/writer exec node scripts/perf/heap-summary.mjs out/perf/main.heapsn COLD_CACHE=1 pnpm -C apps/writer test:browser ``` +### 60-chapter Chromium comparison + +Both runs used `PROFILE_EDITOR_ONLY=1` on an AMD Ryzen 9 7940HS with Node 22.22.0 and Playwright's Chromium. The split-view attempts timed out while returning to the main record. The editor-only pair edited a chapter and used the export controls for the full workspace. Each run loaded 60 chapters, 300 comment records, and 5,000 sources. Comments showed 50 threads and 50 replies in both runs. + +| Action | Before | After | +|---|---:|---:| +| Switch through four chapters | 4.17 s | 2.46 s | +| Type with Outline open | 1.81 s | 1.19 s | +| Type with Comments open | 2.41 s | 1.68 s | +| Type with Sources open | 1.01 s | 1.22 s | +| Filter sources | 288 ms | 98 ms | +| Sparse outline search (1 result) | 272 ms | 730 ms | +| Broad outline search (480 results) | 761 ms | 461 ms | +| Download Word document | 43.15 s | 44.39 s | + +Both exports produced a 27,086-byte DOCX containing the Word document part. The two browser runs had long tasks above 20 seconds around export and source interactions. The browser measurements are single observations. The repeated Vitest runs establish the outline comparison. + +### Earlier browser measurements + On the fixture-corrected product comparison, cold preview went from 3,426 to 2,134 ms and the GC-controlled main heap from 60.91 to 58.28 MiB. Uncollected heap is still recorded for historical comparisons, not treated as a retention measurement. -The script also captures editor/preview visible geometry at animation frames, CDP main-isolate JS heap, >50 ms main-thread long tasks during two ~10 s typing phases, source paging (historically Show all), 300-highlight expansion, citation/embed completion, page errors and `out/large-{sources,comments}-{before,after}.png`. One run is observational, not a statistical timing assertion; the main heap field excludes workers/native backing storage, and visible canvas is not pixel verification. The original Round 4 heap field was not GC-controlled. The default JSON output is `out/perf/browser-profile.json`. Historical before was captured before Round 4 UI changes; after uses a corrected reply counter. Interpretation and deferred work are in `docs/perf-review.md`. +The script captures editor and preview geometry at animation frames, CDP main-isolate JS heap, and main-thread tasks over 50 ms. It measures chapter switching, typing the same text with Outline, Sources and Comments open, sparse and broad outline search, source filtering and paging, highlight expansion, citation and embed completion, and Word export. It checks the finished edits, search result counts, and the presence of a Word document part in the downloaded DOCX. Browser action timings include Playwright round trips. Each typing phase uses 12 text inputs with no added delay. One Chromium run per revision is observational. The main heap excludes workers and native backing storage. The default JSON output is `out/perf/browser-profile.json`. The original Round 4 heap field was not GC-controlled. Interpretation of the earlier runs is in `docs/perf-review.md`. diff --git a/apps/writer/scripts/perf/browser-profile.mjs b/apps/writer/scripts/perf/browser-profile.mjs index e6031bcc..336490fe 100644 --- a/apps/writer/scripts/perf/browser-profile.mjs +++ b/apps/writer/scripts/perf/browser-profile.mjs @@ -1,9 +1,15 @@ // Opt-in Chromium UI profile against DEV ?demo=large; never a real collection. import { chromium } from "playwright"; -import { writeFileSync, mkdirSync } from "node:fs"; +import { readFileSync, writeFileSync, mkdirSync } from "node:fs"; import { dirname } from "node:path"; +import assert from "node:assert/strict"; const browser = await chromium.launch({ executablePath: process.env.CHROME }); const page = await browser.newPage({ viewport: { width: 1500, height: 950 } }); +page.setDefaultTimeout(60_000); +const editorOnly = process.env.PROFILE_EDITOR_ONLY === "1"; +if (editorOnly) { + await page.addInitScript(() => localStorage.setItem("mdbase-writer:layout", JSON.stringify({ view: "write" }))); +} const errors = []; page.on("pageerror", (e) => errors.push(e.message)); const workers = []; page.on("worker", (worker) => workers.push(worker)); const cdp = await page.context().newCDPSession(page); @@ -40,21 +46,38 @@ await page.addInitScript(() => { }; requestAnimationFrame(watch); }); const base = process.env.BASE ?? "http://127.0.0.1:5320/"; -const report = { boundary: "Cold browser cache; Chromium main-thread long tasks; editor/canvas geometry and rendered-revision marker at animation frame (not pixel verification); main CDP JS heap excludes worker heaps and native/WASM backing storage; heap sampled after complete metadata; synthetic transport 20ms pages", phases: {} }; +const report = { boundary: "Cold browser cache, in-memory SDK, Chromium main-thread long tasks. Editor and preview markers describe geometry and rendered revisions. Main CDP heap excludes workers and native/WASM backing storage.", editorOnly, phases: {} }; +let phase = "startup"; const measure = async (name, run) => { - const start = await page.evaluate(() => performance.now()); await run(); await page.waitForTimeout(100); - report.phases[name] = await page.evaluate((start) => { + phase = name; + const start = await page.evaluate(() => performance.now()); + await run(); + const actionMs = await page.evaluate(start => performance.now() - start, start); + await page.waitForTimeout(100); + report.phases[name] = await page.evaluate(({ start, actionMs }) => { const tasks = window.uiTasks.filter((e) => e.start >= start); - return { elapsedMs: performance.now() - start, longTasks: tasks.length, totalLongTaskMs: tasks.reduce((n, e) => n + e.duration, 0), maxLongTaskMs: Math.max(0, ...tasks.map((e) => e.duration)), sourceRows: document.querySelectorAll(".source-row").length, highlights: document.querySelectorAll(".annotations > li").length, threads: document.querySelectorAll(".threads > .thread").length, replies: document.querySelectorAll(".comment.is-reply").length, headings: document.querySelectorAll(".heading-row").length }; - }, start); + return { actionMs, elapsedMs: performance.now() - start, longTasks: tasks.length, totalLongTaskMs: tasks.reduce((n, e) => n + e.duration, 0), maxLongTaskMs: Math.max(0, ...tasks.map((e) => e.duration)), sourceRows: document.querySelectorAll(".source-row").length, highlights: document.querySelectorAll(".annotations > li").length, threads: document.querySelectorAll(".mdbase-threads > .mdbase-thread").length, replies: document.querySelectorAll(".mdbase-comment.is-reply").length, headings: document.querySelectorAll(".heading-row").length }; + }, { start, actionMs }); }; try { - await page.goto(`${base}?demo=large&manuscript=manuscripts/main.md`); - await page.waitForFunction(() => window.previewRendered && window.writer.workspace.getSnapshot().commentsLoad.phase === "ready", null, { timeout: 120000 }); + await page.goto(`${base}?demo=large&largeManuscript=1&manuscript=manuscripts/main.md`); + await page.waitForFunction(() => { + const workspace = window.writer?.workspace; + if (!workspace || !window.editorPaint) return false; + const snapshot = workspace.getSnapshot(); + const order = workspace.readingOrder(); + return order.length === 61 && order.every(path => snapshot.records.has(path)) && snapshot.commentsLoad.phase === "ready"; + }, null, { timeout: 120000 }); report.paint = await page.evaluate(() => ({ editorMs: window.editorPaint, previewMs: window.previewPaint, renderedMs: window.previewRendered })); // An early self-contained preview can precede discovery. Compare retained heap // only after the same complete metadata workload, never a partial collection. await page.waitForFunction(() => ["indexLoad", "libraryLoad", "annotationsLoad", "commentsLoad"].every((key) => window.writer.workspace.getSnapshot()[key].phase === "ready"), null, { timeout: 120000 }); + report.fixture = await page.evaluate(() => { + const workspace = window.writer.workspace; + const snapshot = workspace.getSnapshot(); + return { chapters: workspace.readingOrder().length - 1, comments: snapshot.comments.length, sources: snapshot.library.length }; + }); + assert.deepEqual(report.fixture, { chapters: 60, comments: 300, sources: 5_000 }); report.metadataReadyMs = await page.evaluate(() => performance.now()); await page.waitForTimeout(100); report.heapAfterLoadBytes = (await cdp.send("Performance.getMetrics")).metrics.find((m) => m.name === "JSHeapUsedSize").value; @@ -117,31 +140,97 @@ try { mkdirSync(dirname(process.env.PROFILE_HEAP), { recursive: true }); writeFileSync(process.env.PROFILE_HEAP, chunks.join("")); } - await page.getByRole("tab", { name: /Sources/ }).click(); - const type = async () => { - await page.locator(".cm-content").click(); await page.keyboard.press("ControlOrMeta+End"); - const until = Date.now() + 10000; - while (Date.now() < until) { await page.keyboard.type(" ordinary typing", { delay: 25 }); await page.waitForTimeout(75); } + const editor = page.locator(".cm-content"); + const editorEnd = async () => { + await editor.focus(); + await page.keyboard.press("ControlOrMeta+End"); + }; + const type = async (path) => { + const original = await page.evaluate(path => window.writer.workspace.getSnapshot().records.get(path).snapshot.body, path); + await editorEnd(); + for (let i = 0; i < 12; i++) await page.keyboard.insertText(" ordinary typing"); + await page.waitForFunction(({ path, original }) => window.writer.workspace.getSnapshot().records.get(path).snapshot.body === original + " ordinary typing".repeat(12), { path, original }); }; - await measure("typingSources10s", type); + const chapter = index => `chapters/chapter-${String(index).padStart(5, "0")}.md`; + await page.getByRole("tab", { name: "Outline", exact: true }).click(); + await measure("switchChapters", async () => { + for (const index of [1, 7, 22, 0]) { + const path = chapter(index); + await page.locator(`.record-row[data-path="${path}"]`).click(); + await page.locator(".pane-path", { hasText: path }).waitFor(); + } + }); + await measure("typingOutline", () => type(chapter(0))); + phase = "openComments"; + await page.getByRole("tab", { name: /Comments/ }).click(); + await page.locator(".mdbase-threads > .mdbase-thread").first().waitFor(); + await measure("typingComments", () => type(chapter(0))); + mkdirSync("out", { recursive: true }); + await page.screenshot({ path: "out/large-comments-" + (process.env.PROFILE_NAME ?? "profile") + ".png" }); + await measure("docxExport", async () => { + const download = page.waitForEvent("download", { timeout: 120000 }); + await page.getByRole("button", { name: "Export formats" }).click(); + await page.getByRole("menuitem").filter({ has: page.getByText("Word (DOCX)", { exact: true }) }).click(); + const review = page.getByRole("button", { name: "Export anyway", exact: true }); + if (await Promise.race([download.then(() => false), review.waitFor({ timeout: 120000 }).then(() => true)])) await review.click(); + const bytes = readFileSync(await (await download).path()); + assert.equal(bytes.subarray(0, 4).toString("hex"), "504b0304"); + assert.ok(bytes.includes(Buffer.from("word/document.xml")), "DOCX is missing its document part"); + report.docxBytes = bytes.length; + }); + await page.getByRole("tab", { name: /Sources/ }).click(); + await measure("typingSources", () => type(chapter(0))); await measure("showAllSources", async () => { const all = page.getByRole("button", { name: /^Show all/ }); if (await all.count()) await all.click(); else await page.getByRole("button", { name: /^Show 50 more sources/ }).click(); }); - await page.locator(".sources input[type=search]").fill("source00000"); - await measure("expand300Highlights", async () => { await page.locator('.source-row[data-key="source00000"]').click(); await page.locator(".annotations > li").first().waitFor(); }); - for (const [name, text] of [["citeCompletion", " [@"], ["embedCompletion", "\n![["]]) { - await measure(name, async () => { await page.locator(".cm-content").click(); await page.keyboard.press("ControlOrMeta+End"); await page.keyboard.type(text); await page.locator(".cm-tooltip-autocomplete").waitFor(); }); - await page.keyboard.press("Escape"); await page.keyboard.press("ControlOrMeta+z"); + await measure("filterSources", async () => { + await page.getByRole("searchbox", { name: "Find a source" }).fill("source00000"); + await page.getByRole("list", { name: "Matching sources" }).locator('[data-key="source00000"]').waitFor(); + }); + await measure("expand300Highlights", async () => { + await page.locator('.source-row[data-key="source00000"]').click(); + await page.locator(".annotations > li").first().waitFor(); + }); + await page.screenshot({ path: "out/large-sources-" + (process.env.PROFILE_NAME ?? "profile") + ".png" }); + await page.getByRole("tab", { name: "Outline", exact: true }).click(); + const outlineSearch = page.getByRole("searchbox", { name: "Search outline" }); + const results = page.locator(".search-hit"); + await measure("searchOutlineSparse", async () => { + await outlineSearch.fill("Evidence in chapter 60, section 8"); + await results.first().waitFor(); + assert.equal(await results.count(), 1); + }); + await measure("searchOutlineBroad", async () => { + await outlineSearch.fill("supports the manuscript"); + await page.waitForFunction(() => document.querySelectorAll(".search-hit").length === 480, null, { timeout: 60_000 }); + }); + // Use concrete prefixes so completion waits for results from the large index. + for (const [name, input] of [["citeCompletion", " [@source000"], ["embedCompletion", "\n![[chapters/chapter-000"]]) { + await measure(name, async () => { + await editorEnd(); + await page.keyboard.type(input, { delay: 20 }); + await page.locator(".cm-tooltip-autocomplete li").first().waitFor({ timeout: 10_000 }); + }); + await page.keyboard.press("Escape"); + await page.keyboard.press("ControlOrMeta+z"); } - await page.getByRole("tab", { name: /Comments/ }).click(); - await measure("typingComments10s", type); - mkdirSync("out", { recursive: true }); await page.screenshot({ path: "out/large-comments-" + (process.env.PROFILE_NAME ?? "profile") + ".png" }); - await page.getByRole("tab", { name: /Sources/ }).click(); await page.screenshot({ path: "out/large-sources-" + (process.env.PROFILE_NAME ?? "profile") + ".png" }); +} catch (error) { + report.failure = { + phase, message: String(error), + ...(await page.evaluate(() => ({ + search: document.querySelector(".manuscript-search input")?.value, + summary: document.querySelector(".search-summary")?.textContent, + hits: document.querySelectorAll(".search-hit").length, + })).catch(() => ({}))), + }; + throw error; +} finally { report.errors = errors; const output = process.env.PROFILE_OUTPUT ?? "out/perf/browser-profile.json"; mkdirSync(dirname(output), { recursive: true }); writeFileSync(output, JSON.stringify(report, null, 2) + "\n"); console.log(JSON.stringify(report, null, 2)); if (errors.length) process.exitCode = 1; -} finally { await browser.close(); } + await browser.close(); +} diff --git a/apps/writer/scripts/perf/generator.ts b/apps/writer/scripts/perf/generator.ts index db9d533b..98d0cf13 100644 --- a/apps/writer/scripts/perf/generator.ts +++ b/apps/writer/scripts/perf/generator.ts @@ -3,7 +3,8 @@ import type { JsonObject } from "@mdbase-dev/sdk"; export const counts = { sources: 5_000, annotations: 30_000, comments: 3_000, notes: 20_000, manuscripts: 100, files: 5_000 }; export const main = "manuscripts/main.md"; const pad = (n: number) => String(n).padStart(5, "0"); -export function generateCollection(seed: (path: string, type: string, fm: JsonObject, body: string) => void, highlightsPerBook?: number, browser = false): string { +export function generateCollection(seed: (path: string, type: string, fm: JsonObject, body: string) => void, highlightsPerBook?: number, browser = false, chapterCount = 0): string { + const browserChapters = Array.from({ length: chapterCount }, (_, i) => `chapters/chapter-${pad(i)}.md`); const body = "# Main {#sec-main}\n\n" + Array.from({ length: 100 }, (_, i) => `${browser ? `## Section ${i} {#sec-${i}}\n\n` : ""}Paragraph ${i}: quoted passage ${i}. A sustained cited argument [@source${pad(i)}].\n\n`).join(""); // Share the fixture's intentionally identical text instead of retaining one // flattened copy per seeded record. Cardinality/logical payloads are unchanged. @@ -13,7 +14,12 @@ export function generateCollection(seed: (path: string, type: string, fm: JsonOb const noteBody = "Ordinary collection note.\n".repeat(80); const commentBody = "A comment discussing the passage. ".repeat(16); const abstract = "Source metadata. ".repeat(40); - for (let i = 0; i < counts.manuscripts; i++) seed(i === 0 ? main : `manuscripts/paper-${pad(i)}.md`, "writer-manuscript", { title: `Paper ${pad(i)}`, csl: "apa", template: "article" }, body); + const mainBody = browserChapters.length ? `${body}${browserChapters.map(path => `![[${path}]]`).join("\n\n")}\n` : body; + for (let i = 0; i < counts.manuscripts; i++) seed(i === 0 ? main : `manuscripts/paper-${pad(i)}.md`, "writer-manuscript", { title: `Paper ${pad(i)}`, csl: "apa", template: "article" }, i === 0 ? mainBody : body); + for (const [i, path] of browserChapters.entries()) { + const sections = Array.from({ length: 8 }, (_, section) => `### Section ${section + 1}\n\nEvidence in chapter ${i + 1}, section ${section + 1}, supports the manuscript's argument. Further analysis puts the result in context.`); + seed(path, "note", { title: `Chapter ${i + 1}` }, `## Chapter ${i + 1}\n\n${sections.join("\n\n")}\n`); + } for (let i = 0; i < counts.sources; i++) seed(`sources/source${pad(i)}.md`, "reader-source", { title: `Synthetic source ${pad(i)}`, csl: { id: `source${pad(i)}`, type: "article-journal", title: `Synthetic research ${pad(i)}: evidence and collection performance`, author: [{ family: `Author${pad(i % 997)}`, given: "Alex" }], issued: { "date-parts": [[2000 + i % 25]] }, "container-title": "Journal of Synthetic Data", DOI: `10.0000/${i}`, abstract }, diff --git a/apps/writer/scripts/perf/outline.bench.tsx b/apps/writer/scripts/perf/outline.bench.tsx new file mode 100644 index 00000000..9869f218 --- /dev/null +++ b/apps/writer/scripts/perf/outline.bench.tsx @@ -0,0 +1,70 @@ +// @vitest-environment jsdom +import { performance } from "node:perf_hooks"; +import { expect, it, vi } from "vitest"; +import { fireEvent } from "@testing-library/react"; +import { render } from "../../src/test/render.js"; +import { OutlinePanel } from "../../src/ui/OutlinePanel.js"; +import { searchManuscript } from "../../src/ui/search.js"; +import type { RecordView } from "../../src/workspace/workspace.js"; + +it("updates the open outline across a 120-chapter manuscript", () => { + const main = "main.md"; + const chapters = Array.from({ length: 120 }, (_, i) => `chapters/chapter-${i}.md`); + const order = [main, ...chapters]; + const chapterBody = Array.from({ length: 24 }, (_, i) => `## Section ${i}\n\n${"Evidence from the collection supports this passage [@source]. ".repeat(12)}\n\n`).join(""); + const view = (path: string, body: string): RecordView => { + const frontmatter = { title: path }; + return { + path, + snapshot: { + body, frontmatter, state: "saved", dirty: false, + remote: null, problem: null, recovery: null, lastReceipt: null, + record: { id: path, path, body, frontmatter, revision: "fixture", types: [], state: { state: "confirmed", confirmedSeq: 1 } }, + }, + }; + }; + const mainView = view(main, chapters.map(path => `![[${path}]]\n`).join("")); + const records = new Map([[main, mainView], ...chapters.map(path => [path, view(path, chapterBody)] as const)]); + const commentOffsets = new Map(chapters.map(path => [path, [100, 900, 1700]])); + const props = { main, order, chapters, words: 350_000, byRecord: new Map(), commentOffsets, onOpen: vi.fn(), onJump: vi.fn(), onMove: vi.fn(), onAdd: vi.fn() }; + const edited = chapters[0]!; + const panel = (active: string, current = records, offset = 0) => ; + const scroll = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "scrollIntoView"); + Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { configurable: true, value() {} }); + try { + const rendered = render(panel(edited)); + try { + fireEvent.click(rendered.getByRole("button", { name: /Show 50 more chapters/ })); + fireEvent.click(rendered.getByRole("button", { name: /Show 50 more chapters/ })); + expect(rendered.container.querySelectorAll(".record-row")).toHaveLength(chapters.length); + const measure = (label: string, operation: (i: number) => void) => { + const samples: number[] = []; + for (let i = 0; i < 25; i++) { + const start = performance.now(); + operation(i); + if (i >= 5) samples.push(performance.now() - start); + } + samples.sort((a, b) => a - b); + console.log(`${label}: p50 ${samples[10]!.toFixed(2)} ms, p95 ${samples[18]!.toFixed(2)} ms (${samples.length} samples)`); + }; + measure("Typing in one chapter", i => { + const next = new Map(records).set(edited, view(edited, chapterBody.replace("Evidence", `New word ${i} Evidence`))); + rendered.rerender(panel(edited, next, 20 + i)); + }); + expect(rendered.container.querySelector(".heading-words")?.textContent).toBe("87"); + const revisit = [chapters[4]!, chapters[18]!, chapters[39]!, chapters[57]!]; + measure("Switching chapters", i => rendered.rerender(panel(revisit[i % revisit.length]!))); + const bodyOf = (path: string) => records.get(path)?.snapshot.body; + const results = searchManuscript("Chapter-119", order, bodyOf); + expect(results.total).toBe(1); + expect(searchManuscript("Evidence", order, bodyOf)).toMatchObject({ total: 34_560, truncated: true }); + measure("Sparse manuscript search", () => searchManuscript("Chapter-119", order, bodyOf)); + measure("Broad manuscript search", () => searchManuscript("Evidence", order, bodyOf)); + expect(rendered.container.querySelector('[aria-current="true"]')?.getAttribute("data-path")).toBe(revisit[0]); + expect(rendered.container.querySelectorAll(".heading-row")).toHaveLength(24); + } finally { rendered.unmount(); } + } finally { + if (scroll) Object.defineProperty(HTMLElement.prototype, "scrollIntoView", scroll); + else Reflect.deleteProperty(HTMLElement.prototype, "scrollIntoView"); + } +}); diff --git a/apps/writer/scripts/perf/tsconfig.json b/apps/writer/scripts/perf/tsconfig.json index 5ae87e45..5ab219a9 100644 --- a/apps/writer/scripts/perf/tsconfig.json +++ b/apps/writer/scripts/perf/tsconfig.json @@ -1,5 +1,5 @@ { "extends": "../../tsconfig.json", "compilerOptions": { "types": ["vite/client", "node"] }, - "include": ["*.ts", "../../src/env.d.ts"] + "include": ["*.ts", "*.tsx", "../../src/env.d.ts"] } diff --git a/apps/writer/scripts/perf/vitest.config.ts b/apps/writer/scripts/perf/vitest.config.ts index ec9adbc9..6c24cb04 100644 --- a/apps/writer/scripts/perf/vitest.config.ts +++ b/apps/writer/scripts/perf/vitest.config.ts @@ -4,5 +4,5 @@ import appConfig from "../../vitest.config.js"; // Opt-in only: never matched by the app's normal test or production build. export default defineConfig({ ...appConfig, - test: { ...appConfig.test, include: ["scripts/perf/*.bench.ts"], testTimeout: 180_000, fileParallelism: false }, + test: { ...appConfig.test, include: ["scripts/perf/*.bench.{ts,tsx}"], testTimeout: 180_000, fileParallelism: false }, }); diff --git a/apps/writer/src/backend/large-demo.ts b/apps/writer/src/backend/large-demo.ts index e1e1bba0..450f44ba 100644 --- a/apps/writer/src/backend/large-demo.ts +++ b/apps/writer/src/backend/large-demo.ts @@ -2,9 +2,11 @@ import { counts, generateCollection } from "../../scripts/perf/generator.js"; import { createDemoApp, DemoWriterBackend, demoRecord } from "./demo-fixture.js"; -export async function createLargeDemoBackend() { +export async function createLargeDemoBackend(largeManuscript = false) { const records: ReturnType[] = []; - generateCollection((path, type, fields, body) => records.push(demoRecord(path, { type, ...fields }, body)), 300, true); + // The SDK retains a session per opened record. Leave room for the main record. + const chapters = largeManuscript ? 60 : 0; + generateCollection((path, type, fields, body) => records.push(demoRecord(path, { type, ...fields }, body)), 300, true, chapters); const image = "data:image/svg+xml," + encodeURIComponent(''); const assets = new Map(Array.from({ length: counts.files }, (_, i) => [`files/image-${i}.png`, image])); return new DemoWriterBackend(await createDemoApp({ name: "Large demo", records }), assets, "large-demo"); diff --git a/apps/writer/src/i18n/locales/de/messages.po b/apps/writer/src/i18n/locales/de/messages.po index 2d946b18..5b3fe834 100644 --- a/apps/writer/src/i18n/locales/de/messages.po +++ b/apps/writer/src/i18n/locales/de/messages.po @@ -44,7 +44,7 @@ msgstr "{0, plural, one {# Kapitel} other {# Kapitel}}" msgid "{0, plural, one {# person record claims your account, so Writer will not guess which is you.} other {# person records claim your account, so Writer will not guess which is you.}}" msgstr "{0, plural, one {# Personendatensatz beansprucht Ihr Konto. Writer kann nicht erraten, welcher Datensatz Sie repräsentiert.} other {# Personendatensätze beanspruchen Ihr Konto. Writer kann nicht erraten, welcher Datensatz Sie repräsentiert.}}" -#. placeholder {0}: words[ranks.get(h)!] ?? 0 +#. placeholder {0}: words?.[ranks.get(h)!] ?? 0 #: src/ui/OutlinePanel.tsx msgid "{0, plural, one {# word in this section} other {# words in this section}}" msgstr "{0, plural, one {# Wort in diesem Abschnitt} other {# Wörter in diesem Abschnitt}}" diff --git a/apps/writer/src/i18n/locales/en/messages.po b/apps/writer/src/i18n/locales/en/messages.po index cddd4967..fa2715b8 100644 --- a/apps/writer/src/i18n/locales/en/messages.po +++ b/apps/writer/src/i18n/locales/en/messages.po @@ -44,7 +44,7 @@ msgstr "{0, plural, one {# chapter} other {# chapters}}" msgid "{0, plural, one {# person record claims your account, so Writer will not guess which is you.} other {# person records claim your account, so Writer will not guess which is you.}}" msgstr "{0, plural, one {# person record claims your account, so Writer will not guess which is you.} other {# person records claim your account, so Writer will not guess which is you.}}" -#. placeholder {0}: words[ranks.get(h)!] ?? 0 +#. placeholder {0}: words?.[ranks.get(h)!] ?? 0 #: src/ui/OutlinePanel.tsx msgid "{0, plural, one {# word in this section} other {# words in this section}}" msgstr "{0, plural, one {# word in this section} other {# words in this section}}" diff --git a/apps/writer/src/i18n/locales/es/messages.po b/apps/writer/src/i18n/locales/es/messages.po index 1aa8b43a..84bea720 100644 --- a/apps/writer/src/i18n/locales/es/messages.po +++ b/apps/writer/src/i18n/locales/es/messages.po @@ -44,7 +44,7 @@ msgstr "{0, plural, one {# capítulo} other {# capítulos}}" msgid "{0, plural, one {# person record claims your account, so Writer will not guess which is you.} other {# person records claim your account, so Writer will not guess which is you.}}" msgstr "{0, plural, one {# registro de persona está asociado a tu cuenta; Writer no decidirá cuál te corresponde.} other {# registros de persona están asociados a tu cuenta; Writer no decidirá cuáles te corresponden.}}" -#. placeholder {0}: words[ranks.get(h)!] ?? 0 +#. placeholder {0}: words?.[ranks.get(h)!] ?? 0 #: src/ui/OutlinePanel.tsx msgid "{0, plural, one {# word in this section} other {# words in this section}}" msgstr "{0, plural, one {# palabra en esta sección} other {# palabras en esta sección}}" diff --git a/apps/writer/src/i18n/locales/fr/messages.po b/apps/writer/src/i18n/locales/fr/messages.po index 9e204d20..0351f33c 100644 --- a/apps/writer/src/i18n/locales/fr/messages.po +++ b/apps/writer/src/i18n/locales/fr/messages.po @@ -44,7 +44,7 @@ msgstr "{0, plural, one {# chapitre} other {# chapitres}}" msgid "{0, plural, one {# person record claims your account, so Writer will not guess which is you.} other {# person records claim your account, so Writer will not guess which is you.}}" msgstr "{0, plural, one {# document de personne revendique votre compte : Writer ne devinera donc pas lequel est le vôtre.} other {# documents de personne revendiquent votre compte : Writer ne devinera donc pas lequel est le vôtre.}}" -#. placeholder {0}: words[ranks.get(h)!] ?? 0 +#. placeholder {0}: words?.[ranks.get(h)!] ?? 0 #: src/ui/OutlinePanel.tsx msgid "{0, plural, one {# word in this section} other {# words in this section}}" msgstr "{0, plural, one {# mot dans cette section} other {# mots dans cette section}}" diff --git a/apps/writer/src/i18n/locales/it/messages.po b/apps/writer/src/i18n/locales/it/messages.po index 097b4215..d7b181b9 100644 --- a/apps/writer/src/i18n/locales/it/messages.po +++ b/apps/writer/src/i18n/locales/it/messages.po @@ -44,7 +44,7 @@ msgstr "{0, plural, one {# capitolo} other {# capitoli}}" msgid "{0, plural, one {# person record claims your account, so Writer will not guess which is you.} other {# person records claim your account, so Writer will not guess which is you.}}" msgstr "{0, plural, one {# record persona rivendica questo account, quindi Writer non può stabilire a chi appartiene.} other {# record persona rivendicano questo account, quindi Writer non può stabilire a chi appartiene.}}" -#. placeholder {0}: words[ranks.get(h)!] ?? 0 +#. placeholder {0}: words?.[ranks.get(h)!] ?? 0 #: src/ui/OutlinePanel.tsx msgid "{0, plural, one {# word in this section} other {# words in this section}}" msgstr "{0, plural, one {# parola in questa sezione} other {# parole in questa sezione}}" diff --git a/apps/writer/src/i18n/locales/ja/messages.po b/apps/writer/src/i18n/locales/ja/messages.po index cf929a08..f7553d4f 100644 --- a/apps/writer/src/i18n/locales/ja/messages.po +++ b/apps/writer/src/i18n/locales/ja/messages.po @@ -44,7 +44,7 @@ msgstr "{0, plural, other {#章}}" msgid "{0, plural, one {# person record claims your account, so Writer will not guess which is you.} other {# person records claim your account, so Writer will not guess which is you.}}" msgstr "{0, plural, other {アカウントに紐づく人物レコードが#件あります。どれが本人かWriterが推測することはありません。}}" -#. placeholder {0}: words[ranks.get(h)!] ?? 0 +#. placeholder {0}: words?.[ranks.get(h)!] ?? 0 #: src/ui/OutlinePanel.tsx msgid "{0, plural, one {# word in this section} other {# words in this section}}" msgstr "{0, plural, other {このセクションの単語数:#語}}" diff --git a/apps/writer/src/i18n/locales/ko/messages.po b/apps/writer/src/i18n/locales/ko/messages.po index fbdc0668..75eafe35 100644 --- a/apps/writer/src/i18n/locales/ko/messages.po +++ b/apps/writer/src/i18n/locales/ko/messages.po @@ -44,7 +44,7 @@ msgstr "{0, plural, other {#장}}" msgid "{0, plural, one {# person record claims your account, so Writer will not guess which is you.} other {# person records claim your account, so Writer will not guess which is you.}}" msgstr "{0, plural, other {계정 사용자로 주장하는 사람 레코드가 #개여서 Writer는 어느 사람이 사용자인지 임의로 판단하지 않습니다.}}" -#. placeholder {0}: words[ranks.get(h)!] ?? 0 +#. placeholder {0}: words?.[ranks.get(h)!] ?? 0 #: src/ui/OutlinePanel.tsx msgid "{0, plural, one {# word in this section} other {# words in this section}}" msgstr "{0, plural, other {이 절의 단어 #개}}" diff --git a/apps/writer/src/i18n/locales/pt/messages.po b/apps/writer/src/i18n/locales/pt/messages.po index 7abf6bfb..28193942 100644 --- a/apps/writer/src/i18n/locales/pt/messages.po +++ b/apps/writer/src/i18n/locales/pt/messages.po @@ -44,7 +44,7 @@ msgstr "{0, plural, one {# capítulo} other {# capítulos}}" msgid "{0, plural, one {# person record claims your account, so Writer will not guess which is you.} other {# person records claim your account, so Writer will not guess which is you.}}" msgstr "{0, plural, one {# registro de pessoa reivindica sua conta, então o Writer não vai presumir qual é você.} other {# registros de pessoa reivindicam sua conta, então o Writer não vai presumir qual é você.}}" -#. placeholder {0}: words[ranks.get(h)!] ?? 0 +#. placeholder {0}: words?.[ranks.get(h)!] ?? 0 #: src/ui/OutlinePanel.tsx msgid "{0, plural, one {# word in this section} other {# words in this section}}" msgstr "{0, plural, one {# palavra nesta seção} other {# palavras nesta seção}}" diff --git a/apps/writer/src/i18n/locales/ru/messages.po b/apps/writer/src/i18n/locales/ru/messages.po index 1c273739..b2eefc54 100644 --- a/apps/writer/src/i18n/locales/ru/messages.po +++ b/apps/writer/src/i18n/locales/ru/messages.po @@ -44,7 +44,7 @@ msgstr "{0, plural, one {# глава} few {# главы} many {# глав} othe msgid "{0, plural, one {# person record claims your account, so Writer will not guess which is you.} other {# person records claim your account, so Writer will not guess which is you.}}" msgstr "{0, plural, one {# запись о пользователе связана с вашей учётной записью, поэтому mdbase writer не будет угадывать, какая из них ваша.} few {# записи о пользователях связаны с вашей учётной записью, поэтому mdbase writer не будет угадывать, какая из них ваша.} many {# записей о пользователях связаны с вашей учётной записью, поэтому mdbase writer не будет угадывать, какая из них ваша.} other {# записи о пользователях связаны с вашей учётной записью, поэтому mdbase writer не будет угадывать, какая из них ваша.}}" -#. placeholder {0}: words[ranks.get(h)!] ?? 0 +#. placeholder {0}: words?.[ranks.get(h)!] ?? 0 #: src/ui/OutlinePanel.tsx msgid "{0, plural, one {# word in this section} other {# words in this section}}" msgstr "{0, plural, one {# слово в этом разделе} few {# слова в этом разделе} many {# слов в этом разделе} other {# слова в этом разделе}}" diff --git a/apps/writer/src/i18n/locales/zh/messages.po b/apps/writer/src/i18n/locales/zh/messages.po index 900081b2..bf15533c 100644 --- a/apps/writer/src/i18n/locales/zh/messages.po +++ b/apps/writer/src/i18n/locales/zh/messages.po @@ -44,7 +44,7 @@ msgstr "{0, plural, other {# 章}}" msgid "{0, plural, one {# person record claims your account, so Writer will not guess which is you.} other {# person records claim your account, so Writer will not guess which is you.}}" msgstr "{0, plural, other {有 # 条人员记录关联到你的账户,因此 Writer 不会擅自猜测哪条记录是你本人。}}" -#. placeholder {0}: words[ranks.get(h)!] ?? 0 +#. placeholder {0}: words?.[ranks.get(h)!] ?? 0 #: src/ui/OutlinePanel.tsx msgid "{0, plural, one {# word in this section} other {# words in this section}}" msgstr "{0, plural, other {本节 # 个字}}" diff --git a/apps/writer/src/ui/DemoRoot.tsx b/apps/writer/src/ui/DemoRoot.tsx index 7830fc7e..47850222 100644 --- a/apps/writer/src/ui/DemoRoot.tsx +++ b/apps/writer/src/ui/DemoRoot.tsx @@ -49,8 +49,9 @@ function DemoCollection() { void import("../backend/demo.js").then(async ({ createDemoBackend }) => { // StrictMode may have disposed this effect while the module was loading. if (!live) return; - const b = import.meta.env.DEV && new URL(location.href).searchParams.get("demo") === "large" - ? await (await import("../backend/large-demo.js")).createLargeDemoBackend() + const params = new URL(location.href).searchParams; + const b = import.meta.env.DEV && params.get("demo") === "large" + ? await (await import("../backend/large-demo.js")).createLargeDemoBackend(params.has("largeManuscript")) : await createDemoBackend(); if (live) { owned = b; setBackend(b); } else b.dispose(); diff --git a/apps/writer/src/ui/OutlinePanel.test.tsx b/apps/writer/src/ui/OutlinePanel.test.tsx index 01159013..0a6656ff 100644 --- a/apps/writer/src/ui/OutlinePanel.test.tsx +++ b/apps/writer/src/ui/OutlinePanel.test.tsx @@ -1,5 +1,5 @@ // @vitest-environment jsdom -import { act, cleanup } from "@testing-library/react"; +import { act, cleanup, fireEvent, screen } from "@testing-library/react"; import { render } from "../test/render.js"; import { useCallback } from "react"; import { MemoryReplica } from "@mdbase-dev/sdk/testing"; @@ -65,6 +65,27 @@ it("still reveals a different logical heading beyond the first page", async () = } finally { h.release(); } }); +it("updates a folded chapter's headings when its body or title changes", async () => { + const h = await fixture("# Main\n"); + const chapter = "chapter.md"; + const props = { main: "main.md", order: ["main.md", chapter], chapters: [chapter], words: 10, byRecord: new Map(), active: "main.md", cursor: null, onOpen: vi.fn(), onJump: vi.fn(), onMove: vi.fn(), onAdd: vi.fn() }; + const panel = (title: string, body: string) => { + const snapshot = { ...h.session.getSnapshot(), body, frontmatter: { title } }; + return ; + }; + try { + const rendered = render(panel("Chapter", "# Chapter\n")); + expect(screen.queryByRole("button", { name: "Show the headings of Chapter" })).toBeNull(); + rendered.rerender(panel("Renamed", "# Chapter\n")); + fireEvent.click(screen.getByRole("button", { name: "Show the headings of Renamed" })); + expect(screen.getByRole("button", { name: /Chapter.*0/ })).toBeTruthy(); + rendered.rerender(panel("Renamed", "# Chapter\n\n## Section\n\nSome words.\n")); + expect(screen.getByRole("button", { name: /Section.*2/ })).toBeTruthy(); + rendered.rerender(panel("Renamed", "# Chapter\n\n## Section\n\nSome more words.\n")); + expect(screen.getByRole("button", { name: /Section.*3/ })).toBeTruthy(); + } finally { h.release(); } +}); + afterEach(() => { if (scrollIntoView) Object.defineProperty(HTMLElement.prototype, "scrollIntoView", scrollIntoView); else Reflect.deleteProperty(HTMLElement.prototype, "scrollIntoView"); diff --git a/apps/writer/src/ui/OutlinePanel.tsx b/apps/writer/src/ui/OutlinePanel.tsx index 2d5ed70c..68fda6f3 100644 --- a/apps/writer/src/ui/OutlinePanel.tsx +++ b/apps/writer/src/ui/OutlinePanel.tsx @@ -14,9 +14,32 @@ import { wordCount } from "../words.js"; import type { RecordView } from "../workspace/workspace.js"; import { useRowWindow } from "./paging.js"; import { ChatIcon, ChevronRight, GripIcon, PlusIcon } from "./icons.js"; -import { headingAt, headings, sectionWords, withoutTitle } from "./outline.js"; +import { headingAt, headings, sectionWords, withoutTitle, type OutlineHeading } from "./outline.js"; import { formatCount, plural as countLabel, recordTitle, STATE_LABEL, STATE_TONE } from "./records.js"; +// Workspace preserves each unchanged chapter's view across edits to other records. +// A folded row and its expanded headings share the same parse of that view. +interface RecordOutline { + readonly title: string; + readonly all: readonly OutlineHeading[]; + readonly visible: readonly OutlineHeading[]; + sectionWords?: readonly number[]; +} + +const outlines = new WeakMap(); +function outlineFor(view: RecordView) { + let outline = outlines.get(view); + if (!outline) { + const title = recordTitle(view, view.path); + const all = headings(view.snapshot.body); + outline = { title, all, visible: withoutTitle(all, title) }; + outlines.set(view, outline); + } + return outline; +} + +const NO_HEADINGS: readonly OutlineHeading[] = []; + export function OutlinePanel({ main, order, @@ -142,7 +165,9 @@ export function OutlinePanel({ if (drop?.index !== index || drop.after !== after) setDrop({ index, after }); }; const dropClass = drop?.index === index && dragging !== null ? (drop.after ? "drop-after" : "drop-before") : ""; - const hasHeadings = view ? withoutTitle(headings(view.snapshot.body), recordTitle(view, path)).length > 0 : false; + const outline = view && outlineFor(view); + const title = outline?.title ?? recordTitle(undefined, path); + const hasHeadings = Boolean(outline?.visible.length); const comments = commentOffsets?.get(path)?.length ?? 0; const openRename = () => { if (onRename && view) setRenaming(path); }; return ( @@ -164,7 +189,7 @@ export function OutlinePanel({ > {renaming === path && view ? ( { setRenaming(null); if (title !== null && onRename) { const done = await onRename(path, title); if (!done.ok) setAnnouncement(done.message); } @@ -187,7 +212,7 @@ export function OutlinePanel({ {direct ? index + 1 : ""} {direct && } - {recordTitle(view, path)} + {title} {view ? : ""} @@ -264,17 +289,19 @@ const Words = memo(function Words({ body }: { body: string }) { */ const RecordHeadings = memo(function RecordHeadings({ view, path, cursor, onJump, comments, problems }: { view: RecordView | undefined; path: string; cursor: number | null; onJump(path: string, offset: number): void; comments?: readonly number[] | undefined; problems?: readonly WriterDiagnostic[] | undefined }) { useLingui(); - const body = view?.snapshot.body; - const title = recordTitle(view, path); - const all = useMemo(() => (body ? headings(body) : []), [body]); - const words = useMemo(() => (body ? sectionWords(body, all) : []), [body, all]); + const outline = view && outlineFor(view); + const all = outline?.all ?? NO_HEADINGS; + const list = outline?.visible ?? NO_HEADINGS; + // Folded rows never need section counts. Keep them for later expansions of + // the same view once an expanded row has computed them. + if (outline && view) outline.sectionWords ??= sectionWords(view.snapshot.body, all); + const words = outline?.sectionWords; // What each section holds: the comments and problems anchored between its heading and the next of its level or higher. const counts = useMemo(() => all.map((h, i) => { const end = all.slice(i + 1).find((n) => n.level <= h.level)?.offset ?? Number.MAX_SAFE_INTEGER; const within = (offset: number) => offset >= h.offset && offset < end; return { comments: comments?.filter(within).length ?? 0, problems: problems?.filter((d) => !d.field && within(d.from)).length ?? 0 }; }), [all, comments, problems]); - const list = useMemo(() => withoutTitle(all, title), [all, title]); const window = useRowWindow(); const ranks = useMemo(() => new Map(all.map((h, i) => [h, i])), [all]); const here = cursor !== null ? headingAt(all, cursor) : undefined; @@ -313,7 +340,7 @@ const RecordHeadings = memo(function RecordHeadings({ view, path, cursor, onJump {h.text} {(counts[ranks.get(h)!]?.comments ?? 0) > 0 && } {(counts[ranks.get(h)!]?.problems ?? 0) > 0 && } - {formatCount(words[ranks.get(h)!] ?? 0)} + {formatCount(words?.[ranks.get(h)!] ?? 0)} ))}