From 2d35912ca2f7688f39f74372c167056002111128 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Sat, 28 Nov 2026 21:00:06 +1100 Subject: [PATCH 1/2] Speed up Writer lookup, typing and export while preserving offline drafts --- apps/writer/scripts/perf/README.md | 48 +++- .../scripts/perf/citation-typing-profile.mjs | 86 ++++++ apps/writer/scripts/perf/citations.bench.ts | 66 +++++ apps/writer/scripts/perf/docx-profile.mjs | 14 + apps/writer/scripts/perf/generator.ts | 5 +- apps/writer/src/backend/large-demo.ts | 4 +- apps/writer/src/editor/insight.ts | 2 + apps/writer/src/editor/library-search.ts | 69 +++-- apps/writer/src/i18n/locales/de/messages.po | 2 +- apps/writer/src/i18n/locales/en/messages.po | 2 +- apps/writer/src/i18n/locales/es/messages.po | 2 +- apps/writer/src/i18n/locales/fr/messages.po | 2 +- apps/writer/src/i18n/locales/it/messages.po | 2 +- apps/writer/src/i18n/locales/ja/messages.po | 2 +- apps/writer/src/i18n/locales/ko/messages.po | 2 +- apps/writer/src/i18n/locales/pt/messages.po | 2 +- apps/writer/src/i18n/locales/ru/messages.po | 2 +- apps/writer/src/i18n/locales/zh/messages.po | 2 +- apps/writer/src/ui/DemoRoot.tsx | 2 +- apps/writer/src/ui/OutlinePanel.tsx | 258 +++++++++++------- apps/writer/src/ui/WorkspaceView.tsx | 40 +-- apps/writer/src/words.ts | 9 +- apps/writer/src/workspace/workspace.test.ts | 115 +++++++- apps/writer/src/workspace/workspace.ts | 95 +++++-- packages/core/src/assemble.ts | 74 +++-- packages/core/test/assemble.test.ts | 14 + 26 files changed, 723 insertions(+), 198 deletions(-) create mode 100644 apps/writer/scripts/perf/citation-typing-profile.mjs create mode 100644 apps/writer/scripts/perf/citations.bench.ts diff --git a/apps/writer/scripts/perf/README.md b/apps/writer/scripts/perf/README.md index 10ad27f4..853a970f 100644 --- a/apps/writer/scripts/perf/README.md +++ b/apps/writer/scripts/perf/README.md @@ -1,4 +1,4 @@ -# Large collection benchmark (opt-in, local only) +# Large collection benchmarks (opt-in) From the repository root: @@ -8,7 +8,7 @@ rpnpm --filter @mdbase-writer/app typecheck:perf pnpm -C apps/writer typecheck ``` -Run both benchmarks with `rpnpm --filter @mdbase-writer/app test:perf-fixture`. This uses one zero-latency run of the collection fixture. +Run all Vitest 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: @@ -58,6 +58,50 @@ Result JSON is generated evidence: the default is `out/perf/large-collection.jso ## Recorded outcomes +### Source lookup, long-chapter typing and Word export + +The baseline is `d10c4ef` (#246). Copy `citations.bench.ts`, `citation-typing-profile.mjs`, `docx-profile.mjs` and `generator.ts` from this revision into the matching `apps/writer/scripts/perf` directory of a baseline checkout. Also copy `apps/writer/src/backend/large-demo.ts` and `apps/writer/src/ui/DemoRoot.tsx` to enable the long chapter in the baseline demo. + +```sh +rpnpm --filter @mdbase-writer/app test:perf-fixture scripts/perf/citations.bench.ts +pnpm dev +``` + +Run the Chromium profiles in a separate shell. Set `BASE` if the development server uses a different port. Use separate output directories on each revision and point the second DOCX run at the first revision's `run-1.docx`. + +```sh +pnpm -C apps/writer exec node scripts/perf/citation-typing-profile.mjs +PROFILE_OUTPUT=/tmp/writer-docx-before pnpm -C apps/writer exec node scripts/perf/docx-profile.mjs +PROFILE_OUTPUT=/tmp/writer-docx-after PROFILE_REFERENCE=/tmp/writer-docx-before/run-1.docx \ + pnpm -C apps/writer exec node scripts/perf/docx-profile.mjs +``` + +Vitest used Node 22.22.0 on the remote builder (AMD EPYC 9B14) and took seven measurements after two warmups. It loads 5,000 sources and builds the real APA preview bibliography for 100 cited entries. Warm lookup timings average 100 calls per sample. + +| Vitest median | Before | After | +|---|---:|---:| +| Cold source index and broad lookup | 8.82 ms | 6.74 ms | +| Warm broad source lookup | 0.399 ms | 0.114 ms | +| Warm precise citekey lookup | 0.508 ms | 0.521 ms | +| Cold APA bibliography | 390.0 ms | 413.4 ms | +| Cached APA bibliography | 0.066 ms | 0.066 ms | + +Chromium 149.0.7827.55 ran on an AMD Ryzen 9 7940HS with Node 22.22.0. Each sample uses a fresh context and waits for the collection and preview assembly. The typing run clears source search, opens the Outline and inserts 22 characters into a 78,762-byte chapter. Picker timing includes Playwright round trips and React rendering. Typing timing measures from `beforeinput` to the next animation-frame callback. CDP reports renderer main-thread CPU time for the typing phase. `PROFILE_CPU` can capture a DevTools profile for each run. + +| Chromium median | Before | After | +|---|---:|---:| +| Sources query to matching row, 5 contexts | 29.6 ms | 26.3 ms | +| Typing input to animation frame, 5 contexts | 23.2 ms | 14.5 ms | +| Typing p90 input to animation frame, 5 contexts | 37.0 ms | 24.4 ms | +| Renderer main-thread CPU for 22 inputs, 5 contexts | 1,139 ms | 516 ms | +| Word export preflight, 3 contexts | 371 ms | 81 ms | +| Inside Word export handler, 3 contexts | 2,008 ms | 1,789 ms | +| Chapter save to Word download, 3 contexts | 3,518 ms | 3,236 ms | + +The Word run uses 60 chapters, 480 chapter passages, 100 cited sources and 5,000 available sources. All three DOCX files match the baseline package parts after timestamp normalization. Warm broad lookup benefits from stopping after the top metadata matches are known. Word preflight now reuses dependency and diagnostic analysis while Pandoc formats the citations and bibliography. Fetching and converting with Pandoc accounts for 1.67 seconds of the after median. These are development fixture timings using the SDK's in-memory replica on a shared host. + +### Earlier collection and outline measurements + 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 | diff --git a/apps/writer/scripts/perf/citation-typing-profile.mjs b/apps/writer/scripts/perf/citation-typing-profile.mjs new file mode 100644 index 00000000..766c4282 --- /dev/null +++ b/apps/writer/scripts/perf/citation-typing-profile.mjs @@ -0,0 +1,86 @@ +import assert from "node:assert/strict"; +import { writeFile } from "node:fs/promises"; +import { chromium } from "playwright"; + +const fixture = new URL(process.env.BASE ?? "http://127.0.0.1:5320/"); +const main = "manuscripts/main.md"; +const chapter = "chapters/chapter-00000.md"; +fixture.search = new URLSearchParams({ demo: "large", largeManuscript: "1", longChapter: "1", manuscript: main }).toString(); +const runs = Number(process.env.PROFILE_RUNS ?? 5); +assert.ok(Number.isInteger(runs) && runs > 0, "PROFILE_RUNS must be a positive integer"); +const median = values => { + const sorted = [...values].sort((a, b) => a - b); + const mid = Math.floor(sorted.length / 2); + return (sorted[mid] + sorted[Math.ceil(sorted.length / 2) - 1]) / 2; +}; +const browser = await chromium.launch({ executablePath: process.env.CHROME }); +console.log(JSON.stringify({ chromium: browser.version(), node: process.version })); +try { + for (let run = 1; run <= runs; run++) { + const page = await browser.newPage({ viewport: { width: 1500, height: 950 }, serviceWorkers: "block" }); + try { + const errors = []; + page.on("pageerror", error => errors.push(error.message)); + await page.addInitScript(() => localStorage.setItem("mdbase-writer:layout", JSON.stringify({ view: "write" }))); + await page.goto(fixture.href); + await page.waitForFunction(() => { + const workspace = window.writer?.workspace; + if (!workspace) return false; + const snap = workspace.getSnapshot(); + return snap.library.length === 5000 && snap.records.size === 61 && !snap.compiling + && [snap.indexLoad, snap.annotationsLoad, snap.commentsLoad].every(load => load.phase === "ready"); + }, undefined, { timeout: 60_000 }); + await page.getByRole("tab", { name: /Sources/ }).click(); + const search = page.locator(".sources input[type=search]"); + const timings = []; + for (const [query, key] of [["source", "source00000"], ["synthetic research", "source00000"], ["source04999", "source04999"], ["author00124 2024", "source00124"]]) { + const start = await page.evaluate(() => performance.now()); + await search.fill(query); + await page.getByRole("list", { name: "Matching sources" }).locator(`.source-row[data-key="${key}"]`).first().waitFor(); + timings.push(await page.evaluate(start => performance.now() - start, start)); + } + await search.fill(""); + await page.getByRole("tab", { name: "Outline", exact: true }).click(); + await page.locator(`.record-row[data-path="${chapter}"]`).click(); + const editor = page.getByRole("textbox", { name: `Markdown for ${chapter}`, exact: true }); + const original = await page.evaluate(path => window.writer.workspace.getSnapshot().records.get(path).snapshot.body, chapter); + const chapterBytes = Buffer.byteLength(original); + assert.ok(chapterBytes >= 50_000 && chapterBytes <= 100_000); + await editor.focus(); + await page.keyboard.press("ControlOrMeta+End"); + await editor.evaluate(el => { + window.inputFrames = []; + el.addEventListener("beforeinput", () => { + const start = performance.now(); + requestAnimationFrame(() => window.inputFrames.push(performance.now() - start)); + }, { capture: true }); + }); + const cdp = await page.context().newCDPSession(page); + await cdp.send("Performance.enable", { timeDomain: "threadTicks" }); + const taskTime = async () => (await cdp.send("Performance.getMetrics")).metrics.find(metric => metric.name === "TaskDuration").value * 1000; + if (process.env.PROFILE_CPU) { + await cdp.send("Profiler.enable"); + await cdp.send("Profiler.start"); + } + const phrase = "The archives show that"; + const taskStart = await taskTime(); + for (const [index, char] of [...phrase].entries()) { + await page.keyboard.insertText(char); + await page.waitForFunction(count => window.inputFrames.length === count, index + 1); + } + assert.equal(await page.evaluate(path => window.writer.workspace.getSnapshot().records.get(path).snapshot.body, chapter), original + phrase); + const typingMainCpuMs = await taskTime() - taskStart; + if (process.env.PROFILE_CPU) { + const { profile: samples } = await cdp.send("Profiler.stop"); + await writeFile(`${process.env.PROFILE_CPU}-${run}.cpuprofile`, JSON.stringify(samples)); + } + const frames = await page.evaluate(() => window.inputFrames); + console.log(JSON.stringify({ run, chapterBytes, pickerMs: median(timings), pickerSamplesMs: timings, typingFrameMs: median(frames), typingP90Ms: [...frames].sort((a, b) => a - b)[Math.ceil(frames.length * .9) - 1], typingMainCpuMs })); + assert.deepEqual(errors, []); + } finally { + await page.context().close(); + } + } +} finally { + await browser.close(); +} diff --git a/apps/writer/scripts/perf/citations.bench.ts b/apps/writer/scripts/perf/citations.bench.ts new file mode 100644 index 00000000..ffadea24 --- /dev/null +++ b/apps/writer/scripts/perf/citations.bench.ts @@ -0,0 +1,66 @@ +// Deterministic Node proxy for the source picker and preview bibliography. +import { readFileSync } from "node:fs"; +import { cpus } from "node:os"; +import { Citeproc, type CslItem } from "@mdbase-writer/core/citeproc"; +import { expect, it } from "vitest"; +import type { LibraryEntry } from "../../src/backend/types.js"; +import { searchLibrary } from "../../src/editor/library-search.js"; +import { counts, generateCollection } from "./generator.js"; + +const asset = (name: string) => readFileSync(new URL(`../../../../packages/core/assets/csl/${name}`, import.meta.url), "utf8"); +const median = (values: number[]) => values.sort((a, b) => a - b)[Math.floor(values.length / 2)]; +const measure = (run: () => T) => { + const start = performance.now(); + const result = run(); + return { ms: performance.now() - start, result }; +}; + +it("profiles 5,000 sources with 100 cited entries", () => { + const library: LibraryEntry[] = []; + generateCollection((path, type, fields) => { + if (type !== "reader-source") return; + const item = fields["csl"] as CslItem; + library.push({ path, key: item.id, title: String(item["title"]), item }); + }); + expect(library).toHaveLength(counts.sources); + const items = new Map(library.map(entry => [entry.key, entry.item])); + const cited = new Set(library.slice(0, 100).map(entry => entry.key)); + const requests = [...cited].map(key => ({ items: [{ key, prefix: "", suffix: "", suppressAuthor: false }], noteIndex: 0 })); + const locales = new Map(["en-US", "en-GB"].map(locale => [locale, asset(`locales-${locale}.xml`)])); + const style = asset("apa.csl"); + const samples = []; + for (let run = 0; run < 9; run++) { + const sources = [...library]; + const cold = measure(() => searchLibrary(sources, "research", 60, cited)); + expect(cold.result.at(0)?.key).toBe("source00000"); + expect(cold.result).toHaveLength(60); + const broad = measure(() => { + for (let i = 0; i < 100; i++) searchLibrary(sources, "research", 60, cited); + }); + const exact = measure(() => { + for (let i = 0; i < 100; i++) searchLibrary(sources, "source04999", 60, cited); + }); + expect(searchLibrary(sources, "source04999", 60, cited).at(0)?.key).toBe("source04999"); + const fresh = measure(() => { + const engine = new Citeproc(style, locales, items); + return { engine, formatted: engine.process(requests) }; + }); + const { engine, formatted } = fresh.result; + expect(formatted.bibliography.entries).toHaveLength(cited.size); + expect(new Set(formatted.bibliography.entries.map(entry => entry.key))).toEqual(cited); + const warm = measure(() => engine.process(requests)); + expect(warm.result.mode).toBe("cached"); + expect(warm.result.bibliography).toBe(formatted.bibliography); + if (run > 1) samples.push({ cold: cold.ms, broad: broad.ms / 100, exact: exact.ms / 100, bibliography: fresh.ms, cached: warm.ms }); + } + console.log(JSON.stringify({ + node: process.version, cpu: cpus()[0]?.model, samples, + medians: { + coldSearchMs: median(samples.map(row => row.cold)), + broadSearchMs: median(samples.map(row => row.broad)), + exactSearchMs: median(samples.map(row => row.exact)), + bibliographyMs: median(samples.map(row => row.bibliography)), + cachedBibliographyMs: median(samples.map(row => row.cached)), + }, + })); +}); diff --git a/apps/writer/scripts/perf/docx-profile.mjs b/apps/writer/scripts/perf/docx-profile.mjs index 9d5c4eca..a2f3c8db 100644 --- a/apps/writer/scripts/perf/docx-profile.mjs +++ b/apps/writer/scripts/perf/docx-profile.mjs @@ -112,6 +112,14 @@ try { // Both paths use the ordinary SDK record session and collection watch. const start = await page.evaluate(chapter => { const workspace = window.writer.workspace; + for (const stage of ["preflight", "materialize"]) { + const method = workspace[stage].bind(workspace); + workspace[stage] = async (...args) => { + performance.mark(`${stage}:start`); + try { return await method(...args); } + finally { performance.mark(`${stage}:end`); } + }; + } const exportDocx = workspace.exportDocx.bind(workspace); workspace.exportDocx = async (...args) => { performance.mark("export:start"); @@ -133,10 +141,16 @@ try { const timing = await page.evaluate(start => { const exportStart = performance.getEntriesByName("export:start")[0].startTime; const exportEnd = performance.getEntriesByName("export:end")[0].startTime; + const elapsed = (stage) => performance.measure(stage, `${stage}:start`, `${stage}:end`).duration; + const preflight = elapsed("preflight"); + const materialize = elapsed("materialize"); return { saveToDownloadMs: Math.round(performance.now() - start), beforeExportMs: Math.round(exportStart - start), exportMs: Math.round(exportEnd - exportStart), + preflightMs: Math.round(preflight), + materializeMs: Math.round(materialize - preflight), + convertAndFetchMs: Math.round(exportEnd - exportStart - materialize), mainLongTaskMs: Math.round(window.tasks.filter(([at]) => at >= start).reduce((sum, [, duration]) => sum + duration, 0)), }; }, start); diff --git a/apps/writer/scripts/perf/generator.ts b/apps/writer/scripts/perf/generator.ts index 69186585..33f5b0d4 100644 --- a/apps/writer/scripts/perf/generator.ts +++ b/apps/writer/scripts/perf/generator.ts @@ -3,7 +3,7 @@ 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, chapterCount = 0): string { +export function generateCollection(seed: (path: string, type: string, fm: JsonObject, body: string) => void, highlightsPerBook?: number, browser = false, chapterCount = 0, longChapter = false): 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 @@ -20,7 +20,8 @@ export function generateCollection(seed: (path: string, type: string, fm: JsonOb 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`); + const prose = longChapter && i === 0 ? `\n${"The chapter assembles evidence from several archives and follows the argument through its historical context.\n\n".repeat(700)}` : ""; + seed(path, "note", { title: `Chapter ${i + 1}` }, `## Chapter ${i + 1}\n\n${sections.join("\n\n")}\n${prose}`); } for (let i = 0; i < counts.sources; i++) seed(`sources/source${pad(i)}.md`, "reader-source", { title: `Synthetic source ${pad(i)}`, diff --git a/apps/writer/src/backend/large-demo.ts b/apps/writer/src/backend/large-demo.ts index 450f44ba..fa7529a2 100644 --- a/apps/writer/src/backend/large-demo.ts +++ b/apps/writer/src/backend/large-demo.ts @@ -2,11 +2,11 @@ import { counts, generateCollection } from "../../scripts/perf/generator.js"; import { createDemoApp, DemoWriterBackend, demoRecord } from "./demo-fixture.js"; -export async function createLargeDemoBackend(largeManuscript = false) { +export async function createLargeDemoBackend(largeManuscript = false, longChapter = false) { const records: ReturnType[] = []; // 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); + generateCollection((path, type, fields, body) => records.push(demoRecord(path, { type, ...fields }, body)), 300, true, chapters, longChapter); 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/editor/insight.ts b/apps/writer/src/editor/insight.ts index 4cc86abe..f30a7474 100644 --- a/apps/writer/src/editor/insight.ts +++ b/apps/writer/src/editor/insight.ts @@ -63,6 +63,7 @@ export function referenceNear(state: EditorState, pos: number): { key: string; f /** Every `@key` in a text, citations and cross-references alike. */ export function referenceKeys(text: string): string[] { + if (!text.includes("@")) return []; return [...text.matchAll(KEY)].map((m) => (m[3] ?? "").replace(/[.:,;?~/#$%&+<>-]+$/u, "")).filter(Boolean); } @@ -86,6 +87,7 @@ export function referenceAtOffset(text: string, offset: number): string | null { /** Labels (`{#sec-intro}`) defined in a record body, with the text they label. */ export function labelTargets(record: string, body: string): [string, LabelTarget][] { const out: [string, LabelTarget][] = []; + if (!body.includes("{#")) return out; let offset = 0; for (const line of body.split("\n")) { for (const m of line.matchAll(/\{#([\p{L}\p{N}_][\p{L}\p{N}_:.-]*)[^}]*\}/gu)) { diff --git a/apps/writer/src/editor/library-search.ts b/apps/writer/src/editor/library-search.ts index 3eaea4cf..de6e1a65 100644 --- a/apps/writer/src/editor/library-search.ts +++ b/apps/writer/src/editor/library-search.ts @@ -9,22 +9,30 @@ interface Indexed { readonly key: string; readonly haystack: string; readonly sortKey: string; - readonly rank: number; } const indexes = new WeakMap(); +const collator = new Intl.Collator(); +const nameRoles = ["author", "editor", "translator"] as const; function index(library: readonly LibraryEntry[]): Indexed[] { let found = indexes.get(library); if (!found) { - found = library.map((entry, rank) => { - const names = (["author", "editor", "translator"] as const).flatMap((role) => { + found = library.map((entry) => { + const fields = [entry.key]; + for (const role of nameRoles) { const list = entry.item[role]; - return Array.isArray(list) ? list.map((n: { family?: string; given?: string; literal?: string }) => [n.family, n.given, n.literal].filter(Boolean).join(" ")) : []; - }); + if (!Array.isArray(list)) continue; + for (const name of list) fields.push([name.family, name.given, name.literal].filter(Boolean).join(" ")); + } const container = typeof entry.item["container-title"] === "string" ? entry.item["container-title"] : ""; - return { entry, rank, sortKey: authorYear(entry), key: fold(entry.key), haystack: fold([entry.key, ...names, entry.title, container, yearOf(entry) ?? ""].join(" ")) }; + const year = yearOf(entry); + fields.push(entry.title, container, year ?? ""); + return { entry, sortKey: formatAuthorYear(entry, year), key: fold(entry.key), haystack: fold(fields.join(" ")) }; }); + // Stable author/year ordering is shared by every query. Equal keys retain + // their original library order, including the tie at the result limit. + found.sort((a, b) => collator.compare(a.sortKey, b.sortKey)); indexes.set(library, found); } return found; @@ -46,10 +54,14 @@ export function shortTitle(title: string, max = 40): string { /** "Darwin, 1881" or "Darwin et al., 1881". */ export function authorYear(entry: LibraryEntry): string { + return formatAuthorYear(entry, yearOf(entry)); +} + +function formatAuthorYear(entry: LibraryEntry, year: string | undefined): string { const author = (entry.item["author"] ?? entry.item["editor"]) as { family?: string; literal?: string }[] | undefined; const first = author?.[0]; const name = first?.family ?? first?.literal ?? ""; - return [name + (author && author.length > 1 ? " et al." : ""), yearOf(entry)].filter(Boolean).join(", "); + return [name + (author && author.length > 1 ? " et al." : ""), year].filter(Boolean).join(", "); } /** @@ -58,7 +70,6 @@ export function authorYear(entry: LibraryEntry): string { * "darwinFo" all work. Among equally good matches, `preferred` keys (the * sources a manuscript already cites) come first. */ -const collator = new Intl.Collator(); const sorted = new WeakMap(); /** The library as it is listed: most recently written first; sources the collection has no date for follow, by author and title. */ export function sortedLibrary(library: readonly LibraryEntry[]): readonly LibraryEntry[] { @@ -73,12 +84,11 @@ export function sortedLibrary(library: readonly LibraryEntry[]): readonly Librar } export function searchLibrary(library: readonly LibraryEntry[], query: string, limit = 50, preferred?: { has(key: string): boolean }): LibraryEntry[] { - const prefer = (e: LibraryEntry) => (preferred?.has(e.key) ? 1 : 0); // A citekey-shaped query also splits where letters meet digits ("darwin81"). - const words = fold(query) - .split(/[\s,;]+|(?<=\p{L})(?=\p{N})|(?<=\p{N})(?=\p{L})/u) - .filter(Boolean); const q = fold(query.trim()); + const words = q + .split(/[\s,;]+|(?<=\p{L})(?=\p{N})|(?<=\p{N})(?=\p{L})/u) + .filter(Boolean).reverse(); if (limit <= 0) return []; if (!words.length) { if (!preferred) return library.slice(0, limit); @@ -86,17 +96,28 @@ export function searchLibrary(library: readonly LibraryEntry[], query: string, l for (const entry of library) { const into = preferred.has(entry.key) ? first : rest; if (into.length < limit) into.push(entry); } return [...first, ...rest].slice(0, limit); } - const scored: { indexed: Indexed; score: number; preferred: number }[] = []; - const compare = (a: typeof scored[number], b: typeof scored[number]) => b.score - a.score || b.preferred - a.preferred || collator.compare(a.indexed.sortKey, b.indexed.sortKey) || a.indexed.rank - b.indexed.rank; - for (const i of index(library)) { - const score = i.key.startsWith(q) ? 3 : i.key.includes(q) ? 2 : words.every((w) => i.haystack.includes(w)) ? 1 : 0; - if (!score) continue; - const candidate = { indexed: i, score, preferred: prefer(i.entry) }; - if (scored.length === limit && compare(candidate, scored[limit - 1]!) >= 0) continue; - let low = 0, high = scored.length; - while (low < high) { const mid = (low + high) >>> 1; if (compare(candidate, scored[mid]!) < 0) high = mid; else low = mid + 1; } - scored.splice(low, 0, candidate); - if (scored.length > limit) scored.pop(); + // Key matches outrank metadata matches. Collect them first, then stop the + // broader metadata scan once it has filled the remaining places in rank order. + const rows = index(library); + const keyBuckets: LibraryEntry[][] = [[], [], [], []]; + for (const row of rows) { + const match = row.key.startsWith(q) ? 0 : row.key.includes(q) ? 2 : -1; + if (match < 0) continue; + const bucket = keyBuckets[match + (preferred?.has(row.entry.key) ? 0 : 1)]!; + if (bucket.length < limit) bucket.push(row.entry); + if (match === 0 && bucket.length === limit && (!preferred || bucket === keyBuckets[0])) return bucket; + } + const keys = keyBuckets.flat(); + if (keys.length >= limit) return keys.slice(0, limit); + const keyMatches = new Set(keys); + const remaining = limit - keys.length; + const first: LibraryEntry[] = [], rest: LibraryEntry[] = []; + const [word, ...otherWords] = words; + for (const row of rows) { + if (!row.haystack.includes(word!) || !otherWords.every(value => row.haystack.includes(value)) || keyMatches.has(row.entry)) continue; + const bucket = preferred?.has(row.entry.key) ? first : rest; + if (bucket.length < remaining) bucket.push(row.entry); + if (first.length === remaining || !preferred && rest.length === remaining) break; } - return scored.map((s) => s.indexed.entry); + return keys.concat(first, rest).slice(0, limit); } diff --git a/apps/writer/src/i18n/locales/de/messages.po b/apps/writer/src/i18n/locales/de/messages.po index 103d7de2..8e6af85a 100644 --- a/apps/writer/src/i18n/locales/de/messages.po +++ b/apps/writer/src/i18n/locales/de/messages.po @@ -1291,7 +1291,7 @@ msgstr "Zum nächsten Steuerelement wechseln" msgid "Move up" msgstr "Nach oben verschieben" -#. placeholder {0}: recordTitle(records.get(path), path) +#. placeholder {0}: recordTitle(view, path) #. placeholder {1}: to + 1 #. placeholder {2}: chapters.length #: src/ui/OutlinePanel.tsx diff --git a/apps/writer/src/i18n/locales/en/messages.po b/apps/writer/src/i18n/locales/en/messages.po index ebe0661b..47b4864b 100644 --- a/apps/writer/src/i18n/locales/en/messages.po +++ b/apps/writer/src/i18n/locales/en/messages.po @@ -1291,7 +1291,7 @@ msgstr "Move to the next control" msgid "Move up" msgstr "Move up" -#. placeholder {0}: recordTitle(records.get(path), path) +#. placeholder {0}: recordTitle(view, path) #. placeholder {1}: to + 1 #. placeholder {2}: chapters.length #: src/ui/OutlinePanel.tsx diff --git a/apps/writer/src/i18n/locales/es/messages.po b/apps/writer/src/i18n/locales/es/messages.po index 35e2fa51..773960f1 100644 --- a/apps/writer/src/i18n/locales/es/messages.po +++ b/apps/writer/src/i18n/locales/es/messages.po @@ -1291,7 +1291,7 @@ msgstr "Ir al siguiente control" msgid "Move up" msgstr "Subir" -#. placeholder {0}: recordTitle(records.get(path), path) +#. placeholder {0}: recordTitle(view, path) #. placeholder {1}: to + 1 #. placeholder {2}: chapters.length #: src/ui/OutlinePanel.tsx diff --git a/apps/writer/src/i18n/locales/fr/messages.po b/apps/writer/src/i18n/locales/fr/messages.po index c392b81f..3103517a 100644 --- a/apps/writer/src/i18n/locales/fr/messages.po +++ b/apps/writer/src/i18n/locales/fr/messages.po @@ -1291,7 +1291,7 @@ msgstr "Passer au contrôle suivant" msgid "Move up" msgstr "Monter" -#. placeholder {0}: recordTitle(records.get(path), path) +#. placeholder {0}: recordTitle(view, path) #. placeholder {1}: to + 1 #. placeholder {2}: chapters.length #: src/ui/OutlinePanel.tsx diff --git a/apps/writer/src/i18n/locales/it/messages.po b/apps/writer/src/i18n/locales/it/messages.po index c52bac0b..da1e36bb 100644 --- a/apps/writer/src/i18n/locales/it/messages.po +++ b/apps/writer/src/i18n/locales/it/messages.po @@ -1291,7 +1291,7 @@ msgstr "Passa al controllo successivo" msgid "Move up" msgstr "Sposta in alto" -#. placeholder {0}: recordTitle(records.get(path), path) +#. placeholder {0}: recordTitle(view, path) #. placeholder {1}: to + 1 #. placeholder {2}: chapters.length #: src/ui/OutlinePanel.tsx diff --git a/apps/writer/src/i18n/locales/ja/messages.po b/apps/writer/src/i18n/locales/ja/messages.po index 53c313f1..90a5b805 100644 --- a/apps/writer/src/i18n/locales/ja/messages.po +++ b/apps/writer/src/i18n/locales/ja/messages.po @@ -1291,7 +1291,7 @@ msgstr "次の操作項目へ移動" msgid "Move up" msgstr "上へ移動" -#. placeholder {0}: recordTitle(records.get(path), path) +#. placeholder {0}: recordTitle(view, path) #. placeholder {1}: to + 1 #. placeholder {2}: chapters.length #: src/ui/OutlinePanel.tsx diff --git a/apps/writer/src/i18n/locales/ko/messages.po b/apps/writer/src/i18n/locales/ko/messages.po index 9f9b08c6..8e1f4a88 100644 --- a/apps/writer/src/i18n/locales/ko/messages.po +++ b/apps/writer/src/i18n/locales/ko/messages.po @@ -1291,7 +1291,7 @@ msgstr "다음 컨트롤로 이동" msgid "Move up" msgstr "위로 이동" -#. placeholder {0}: recordTitle(records.get(path), path) +#. placeholder {0}: recordTitle(view, path) #. placeholder {1}: to + 1 #. placeholder {2}: chapters.length #: src/ui/OutlinePanel.tsx diff --git a/apps/writer/src/i18n/locales/pt/messages.po b/apps/writer/src/i18n/locales/pt/messages.po index 10b7987e..4b17fd86 100644 --- a/apps/writer/src/i18n/locales/pt/messages.po +++ b/apps/writer/src/i18n/locales/pt/messages.po @@ -1291,7 +1291,7 @@ msgstr "Ir para o próximo controlo" msgid "Move up" msgstr "Mover para cima" -#. placeholder {0}: recordTitle(records.get(path), path) +#. placeholder {0}: recordTitle(view, path) #. placeholder {1}: to + 1 #. placeholder {2}: chapters.length #: src/ui/OutlinePanel.tsx diff --git a/apps/writer/src/i18n/locales/ru/messages.po b/apps/writer/src/i18n/locales/ru/messages.po index caef4cb4..5704dceb 100644 --- a/apps/writer/src/i18n/locales/ru/messages.po +++ b/apps/writer/src/i18n/locales/ru/messages.po @@ -1291,7 +1291,7 @@ msgstr "Перейти к следующему элементу" msgid "Move up" msgstr "Переместить вверх" -#. placeholder {0}: recordTitle(records.get(path), path) +#. placeholder {0}: recordTitle(view, path) #. placeholder {1}: to + 1 #. placeholder {2}: chapters.length #: src/ui/OutlinePanel.tsx diff --git a/apps/writer/src/i18n/locales/zh/messages.po b/apps/writer/src/i18n/locales/zh/messages.po index 3776be39..e70d3be1 100644 --- a/apps/writer/src/i18n/locales/zh/messages.po +++ b/apps/writer/src/i18n/locales/zh/messages.po @@ -1291,7 +1291,7 @@ msgstr "移到下一个控件" msgid "Move up" msgstr "上移" -#. placeholder {0}: recordTitle(records.get(path), path) +#. placeholder {0}: recordTitle(view, path) #. placeholder {1}: to + 1 #. placeholder {2}: chapters.length #: src/ui/OutlinePanel.tsx diff --git a/apps/writer/src/ui/DemoRoot.tsx b/apps/writer/src/ui/DemoRoot.tsx index 47850222..c6940f99 100644 --- a/apps/writer/src/ui/DemoRoot.tsx +++ b/apps/writer/src/ui/DemoRoot.tsx @@ -51,7 +51,7 @@ function DemoCollection() { if (!live) return; 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 (await import("../backend/large-demo.js")).createLargeDemoBackend(params.has("largeManuscript"), params.has("longChapter")) : await createDemoBackend(); if (live) { owned = b; setBackend(b); } else b.dispose(); diff --git a/apps/writer/src/ui/OutlinePanel.tsx b/apps/writer/src/ui/OutlinePanel.tsx index 68fda6f3..d67d78da 100644 --- a/apps/writer/src/ui/OutlinePanel.tsx +++ b/apps/writer/src/ui/OutlinePanel.tsx @@ -6,7 +6,7 @@ import { shortcutLabel } from "@mdbase-dev/ui/command-palette"; // chapters (records embedded on lines of their own) in reading order, each // with its headings. Chapters are dragged, or moved with Alt-↑/↓, to reorder // them; a new chapter is added at the end. -import { memo, useEffect, useMemo, useRef, useState, type DragEvent, type KeyboardEvent } from "react"; +import { memo, useCallback, useEffect, useMemo, useRef, useState, type DragEvent, type KeyboardEvent } from "react"; import type { Result } from "../backend/types.js"; import type { WriterDiagnostic } from "../compile/protocol.js"; @@ -84,13 +84,6 @@ export function OutlinePanel({ // A book's chapters fold their headings away, except the one being written. const [expanded, setExpanded] = useState>(() => new Set()); const [renaming, setRenaming] = useState(null); - const isExpanded = (path: string) => expanded.has(path) || path === active; - const toggleExpanded = (path: string) => setExpanded((set) => { - const next = new Set(set); - if (isExpanded(path)) { next.delete(path); if (path === active) next.add(`!${path}`); } - else { next.add(path); next.delete(`!${path}`); } - return next; - }); const shows = (path: string) => (path === active ? !expanded.has(`!${path}`) : expanded.has(path)); const refocus = useRef(null); const list = useRef(null); @@ -109,19 +102,57 @@ export function OutlinePanel({ refocus.current = null; }, [order]); - const move = (from: number, to: number) => { + const move = useCallback((from: number, to: number, view: RecordView | undefined) => { const path = chapters[from]; if (to < 0 || to >= chapters.length || !path) return; refocus.current = path; onMove(from, to); - setAnnouncement(t`Moved ${recordTitle(records.get(path), path)} to chapter ${to + 1} of ${chapters.length}.`); - }; + setAnnouncement(t`Moved ${recordTitle(view, path)} to chapter ${to + 1} of ${chapters.length}.`); + }, [chapters, onMove]); + + const reveal = window.reveal; + const navigate = useCallback((event: KeyboardEvent, path: string, index: number, view: RecordView | undefined) => { + const direction = event.key === "ArrowDown" || event.key === "j" ? 1 : event.key === "ArrowUp" || event.key === "k" ? -1 : 0; + if (!direction) return; + if (event.altKey) { + if (index >= 0) { event.preventDefault(); move(index, index + direction, view); } + return; + } + const rank = (recordRanks.get(path) ?? -1) + direction; + const next = rest[rank]; + if (!next) return; + event.preventDefault(); + reveal(rank); + requestAnimationFrame(() => list.current?.querySelector(`.record-row[data-path="${CSS.escape(next)}"]`)?.focus()); + }, [move, recordRanks, rest, reveal]); + const finishRename = useCallback((path: string) => { + requestAnimationFrame(() => list.current?.querySelector(`.record-row[data-path="${CSS.escape(path)}"]`)?.focus()); + }, []); + const startDrag = useCallback((index: number) => setDragging(index), []); + const endDrag = useCallback(() => { setDragging(null); setDrop(null); }, []); + const markDrop = useCallback((index: number, after: boolean) => { + setDrop(current => current?.index === index && current.after === after ? current : { index, after }); + }, []); + const toggle = useCallback((path: string, wasExpanded: boolean) => { + setExpanded(set => { + const next = new Set(set); + if (wasExpanded) { + next.delete(path); + if (path === active) next.add(`!${path}`); + } else { + next.add(path); + next.delete(`!${path}`); + } + return next; + }); + }, [active]); const onDrop = (e: DragEvent) => { e.preventDefault(); if (dragging !== null && drop) { const at = drop.index + (drop.after ? 1 : 0); - move(dragging, at > dragging ? at - 1 : at); + const path = chapters[dragging]; + if (path) move(dragging, at > dragging ? at - 1 : at, records.get(path)); } setDragging(null); setDrop(null); @@ -144,88 +175,34 @@ export function OutlinePanel({ )} {rest.length > 0 && (
    dragging !== null && e.preventDefault()} onDrop={onDrop}> - {rest.slice(window.from, window.from + window.size).map((path) => { - const view = records.get(path); + {rest.slice(window.from, window.from + window.size).map(path => { const index = ranks.get(path) ?? -1; - const direct = index >= 0; - const onKeyDown = (e: KeyboardEvent) => { - const direction = e.key === "ArrowDown" || e.key === "j" ? 1 : e.key === "ArrowUp" || e.key === "k" ? -1 : 0; - if (!direction) return; - if (e.altKey) { if (direct) { e.preventDefault(); move(index, index + direction); } return; } - const rank = (recordRanks.get(path) ?? -1) + direction, next = rest[rank]; - if (!next) return; - e.preventDefault(); window.reveal(rank); - requestAnimationFrame(() => list.current?.querySelector(`.record-row[data-path="${CSS.escape(next)}"]`)?.focus()); - }; - const onDragOver = (e: DragEvent) => { - if (dragging === null || !direct) return; - e.preventDefault(); - const box = e.currentTarget.getBoundingClientRect(); - const after = e.clientY > box.top + Math.min(box.height, 40) / 2; - if (drop?.index !== index || drop.after !== after) setDrop({ index, after }); - }; - const dropClass = drop?.index === index && dragging !== null ? (drop.after ? "drop-after" : "drop-before") : ""; - 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 ( -
  1. { - if (!direct) return; - e.dataTransfer.effectAllowed = "move"; - e.dataTransfer.setData("text/plain", path); - setDragging(index); - }} - onDragEnd={() => { - setDragging(null); - setDrop(null); - }} - onDragOver={onDragOver} - > - {renaming === path && view ? ( - { - setRenaming(null); - if (title !== null && onRename) { const done = await onRename(path, title); if (!done.ok) setAnnouncement(done.message); } - requestAnimationFrame(() => list.current?.querySelector(`.record-row[data-path="${CSS.escape(path)}"]`)?.focus()); - }} - /> - ) : ( -
    - - {hasHeadings && ( - - )} -
    - )} - {shows(path) && } -
  2. - ); + return = 0} + dropClass={dragging !== null && drop?.index === index ? (drop.after ? "drop-after" : "drop-before") : ""} + canDrop={dragging !== null && index >= 0} + onOpen={onOpen} + onJump={onJump} + onNavigate={navigate} + onToggle={toggle} + onRename={onRename} + onStartRename={setRenaming} + onFinishRename={finishRename} + onRenameFailure={setAnnouncement} + onStartDrag={startDrag} + onEndDrag={endDrag} + onMarkDrop={markDrop} + />; })}
)} @@ -238,6 +215,101 @@ export function OutlinePanel({ ); } +const ChapterRow = memo(function ChapterRow({ + path, view, index, active, expanded, cursor, comments, problems, renaming, dragging, dropClass, canDrop, + onOpen, onJump, onNavigate, onToggle, onRename, onStartRename, onFinishRename, onRenameFailure, onStartDrag, onEndDrag, onMarkDrop, +}: { + path: string; + view: RecordView | undefined; + index: number; + active: boolean; + expanded: boolean; + cursor: number | null; + comments: readonly number[] | undefined; + problems: readonly WriterDiagnostic[] | undefined; + renaming: boolean; + dragging: boolean; + dropClass: string; + canDrop: boolean; + onOpen(path: string): void; + onJump(path: string, offset: number): void; + onNavigate(event: KeyboardEvent, path: string, index: number, view: RecordView | undefined): void; + onToggle(path: string, expanded: boolean): void; + onRename: ((path: string, title: string) => Promise> | Result) | undefined; + onStartRename(path: string | null): void; + onFinishRename(path: string): void; + onRenameFailure(message: string): void; + onStartDrag(index: number): void; + onEndDrag(): void; + onMarkDrop(index: number, after: boolean): void; +}) { + useLingui(); + const direct = index >= 0; + const outline = view && outlineFor(view); + const title = outline?.title ?? recordTitle(undefined, path); + const openRename = () => { if (onRename && view) onStartRename(path); }; + return ( +
  • { + if (!direct) return; + event.dataTransfer.effectAllowed = "move"; + event.dataTransfer.setData("text/plain", path); + onStartDrag(index); + }} + onDragEnd={onEndDrag} + onDragOver={event => { + if (!canDrop) return; + event.preventDefault(); + const box = event.currentTarget.getBoundingClientRect(); + onMarkDrop(index, event.clientY > box.top + Math.min(box.height, 40) / 2); + }} + > + {renaming && view ? ( + { + onStartRename(null); + if (name !== null && onRename) { const done = await onRename(path, name); if (!done.ok) onRenameFailure(done.message); } + onFinishRename(path); + }} + /> + ) : ( +
    + + {!!outline?.visible.length && ( + + )} +
    + )} + {expanded && } +
  • + ); +}); + function RecordState({ view, problems, comments = 0 }: { view: RecordView | undefined; problems: number; comments?: number }) { useLingui(); const state = view?.snapshot.state; diff --git a/apps/writer/src/ui/WorkspaceView.tsx b/apps/writer/src/ui/WorkspaceView.tsx index 459f9335..e8d43c68 100644 --- a/apps/writer/src/ui/WorkspaceView.tsx +++ b/apps/writer/src/ui/WorkspaceView.tsx @@ -325,9 +325,12 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc useLayoutEffect(() => { if (narrow && pane === "write") editor.current?.focus(); }, [pane, narrow]); - const dependencyDiagnostics = workspace.dependencyDiagnostics(); - const allDiagnostics = useMemo(() => [...discoveredDiagnostics(snap.result?.diagnostics ?? NO_DIAGNOSTICS, snap), ...dependencyDiagnostics] - .map(d => ({ ...d, message: diagnosticMessage(d.message, d.copy) })), [snap, dependencyDiagnostics, interfaceLocale]); + const { indexLoad, libraryLoad, annotationsLoad, assetProblems, recordProblems } = snap; + const compileDiagnostics = snap.result?.diagnostics ?? NO_DIAGNOSTICS; + const dependencyDiagnostics = useMemo(() => assetProblems.size || recordProblems.size ? workspace.dependencyDiagnostics() : NO_DIAGNOSTICS, + [workspace, indexLoad, assetProblems, recordProblems, snap.records, snap.recordIndex, snap.fileIndex, interfaceLocale]); + const allDiagnostics = useMemo(() => [...discoveredDiagnostics(compileDiagnostics, { indexLoad, libraryLoad, annotationsLoad }), ...dependencyDiagnostics] + .map(d => ({ ...d, message: diagnosticMessage(d.message, d.copy) })), [compileDiagnostics, indexLoad, libraryLoad, annotationsLoad, dependencyDiagnostics, interfaceLocale]); // A citation or label half typed is not a problem yet: problems on the line // being typed wait until typing pauses or the cursor leaves the line. const diagnostics = useMemo(() => { @@ -354,19 +357,20 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc const records = useDeferredValue(snap.records); const [statsCache] = useState(() => new ManuscriptStats()); const stats = useMemo(() => statsCache.derive(order, records, snap.library), [statsCache, records, snap.library, order]); + const libraryByKey = useMemo(() => new Map(snap.library.map(entry => [entry.key, entry])), [snap.library]); const completion = useMemo( () => ({ library: snap.library, labels: snap.result?.labels ?? [], recordPaths: snap.recordPaths, cited: stats.cited }), [snap.library, snap.result?.labels, snap.recordPaths, stats.cited], ); const insight = useMemo( () => ({ - library: new Map(snap.library.map((e) => [e.key, e])), + library: libraryByKey, references: new Map((snap.result?.references ?? []).map((r) => [r.key, r.text])), labels: stats.labels, image: (target) => workspace.imageUrl(target, active), }), // eslint-disable-next-line react-hooks/exhaustive-deps -- images redraw as their bytes load (assetVersion) and resolve from the active record - [workspace, snap.library, snap.result?.references, stats.labels, snap.assetVersion, snap.fileIndex, active], + [workspace, libraryByKey, snap.result?.references, stats.labels, snap.assetVersion, snap.fileIndex, active], ); // Threads on the manuscript's records, placed in their (slightly deferred) text. @@ -499,6 +503,13 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc showComments(); }, [showComments]); const onPreviewJump = useCallback((p: BlockPosition) => jump(p.record, p.offset), [jump]); + const openChapter = useCallback((path: string) => { + revealRequest.current = null; + setActive(path); + setPane("write"); + }, []); + const moveChapter = useCallback((from: number, to: number) => workspace.moveChapter(from, to), [workspace]); + const renameChapter = useCallback((path: string, title: string) => signalFailure(workspace.renameChapter(path, title)), [workspace]); const openSettings = useCallback(() => setSettingsOpen(true), []); const retryPreview = useCallback(() => { void workspace.retryPreview(); }, [workspace]); const closeShortcuts = useCallback(() => setShortcutsOpen(false), []); @@ -610,7 +621,6 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc const recordSet = snap.recordIndex; const cards = useMemo(() => { const keys = sourceKeys(snap.library); - const entries = new Map(snap.library.map((e) => [e.key, e])); return { card(target) { const path = resolveLinkTarget(target, active, recordSet); @@ -621,7 +631,7 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc if (annotation?.quote) { const sourcePath = annotationSourcePath(annotation, keys); const key = sourcePath ? (keys.get(sourcePath) ?? null) : null; - const entry = key ? entries.get(key) : undefined; + const entry = key ? libraryByKey.get(key) : undefined; const cite = entry ? [authorYear(entry) || entry.key, annotation.locator].filter(Boolean).join(", ") : ""; const href = sourcePath && workspace.kind === "connect" ? readerSourceHref(sourcePath, path) : undefined; return { quotation: true, path, quote: annotation.quote, cite, detached: blockQuotation(key, annotation), ...(href ? { href } : {}) }; @@ -634,7 +644,7 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc }, }; // eslint-disable-next-line react-hooks/exhaustive-deps -- isQuotation reads the annotations the snapshot holds - }, [active, recordSet, records, byRecord, snap.library, snap.annotationPaths]); + }, [active, recordSet, records, byRecord, snap.library, libraryByKey, snap.annotationPaths]); const insertSource = useCallback((text: string) => { setPane("write"); const at = editor.current?.selection(); @@ -915,15 +925,11 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc byRecord={byRecord} active={active} cursor={cursor} - onOpen={(path) => { - revealRequest.current = null; - setActive(path); - setPane("write"); - }} + onOpen={openChapter} onJump={jump} - onMove={(from, to) => workspace.moveChapter(from, to)} + onMove={moveChapter} onAdd={async (title, intent) => signalFailure(await workspace.addChapter(title, intent))} - onRename={(path, title) => signalFailure(workspace.renameChapter(path, title))} + onRename={renameChapter} commentOffsets={commentOffsets} /> )} @@ -978,7 +984,7 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc const errors = diagnostics.filter((d) => d.severity === "error").length; const timings = snap.result?.timings; const { columns, areas } = gridFor(layout); - const commands: Command[] = [ + const commands: Command[] = paletteOpen || shortcutsOpen ? [ ...order.map(path => ({ id: `chapter-${path}`, group: translate`Chapters`, label: recordTitle(snap.records.get(path), path), keywords: path, run: () => { setActive(path); setPane("write"); } })), { id: "find-chapter", group: translate`Manuscript`, label: translate`Find in chapter`, shortcut: "mod+f", run: findInChapter }, { id: "save", group: translate`Manuscript`, label: translate`Save now`, shortcut: "mod+s", run: () => { void workspace.retrySave().then(signalResult); } }, @@ -1022,7 +1028,7 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc { id: "export-bundle", group: translate`Export`, label: translate`Export Pandoc bundle (zip)`, run: () => runExport("bundle") }, { id: "export-menu", group: translate`Export`, label: translate`Choose export format`, shortcut: "mod+shift+s", run: () => setExportOpen(true) }, { id: "shortcuts", group: translate`Help`, label: translate`Keyboard shortcuts`, shortcut: "mod+/", run: () => setShortcutsOpen(true) }, - ]; + ] : []; return ( diff --git a/apps/writer/src/words.ts b/apps/writer/src/words.ts index 48b7d107..cba36568 100644 --- a/apps/writer/src/words.ts +++ b/apps/writer/src/words.ts @@ -6,7 +6,9 @@ * link targets are left out. */ export function wordCount(markdown: string): number { - const prose = markdown + // Most chapter prose has none of the markers stripped below. Avoid running + // each replacement over the whole chapter in that case. + const prose = /[`~$[\]@{<]/.test(markdown) ? markdown .replace(/^ {0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:\n {0,3}\1[^\n]*|$)/gm, " ") .replace(/\$\$[\s\S]*?\$\$|\$[^$\n]+\$/g, " ") .replace(/`[^`\n]*`/g, " ") @@ -17,8 +19,9 @@ export function wordCount(markdown: string): number { .replace(/\{[#.][^}\n]*\}/g, " ") .replace(/\[\^[^\]\n]+\]:?/g, " ") .replace(/\]\([^)\n]*\)/g, "]") - .replace(/<[^>\n]+>/g, " "); - return prose.match(/[\p{L}\p{N}]+(?:['’.-][\p{L}\p{N}]+)*/gu)?.length ?? 0; + .replace(/<[^>\n]+>/g, " ") : markdown; + const words = /[^\x00-\x7f]/.test(prose) ? /[\p{L}\p{N}]+(?:['’.-][\p{L}\p{N}]+)*/gu : /[a-zA-Z0-9]+(?:['.-][a-zA-Z0-9]+)*/g; + return prose.match(words)?.length ?? 0; } /** Records embedded on a line of their own (`![[chapters/one]]`). */ diff --git a/apps/writer/src/workspace/workspace.test.ts b/apps/writer/src/workspace/workspace.test.ts index 91649c47..eed7d796 100644 --- a/apps/writer/src/workspace/workspace.test.ts +++ b/apps/writer/src/workspace/workspace.test.ts @@ -1,6 +1,6 @@ import { readFileSync } from "node:fs"; import { MemoryReplica } from "@mdbase-dev/sdk/testing"; -import { MdbaseError, type MdbaseClient } from "@mdbase-dev/sdk"; +import { MdbaseClient, MdbaseError } from "@mdbase-dev/sdk"; import { NextWriterRecords } from "../backend/next-records.js"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { fail, ok, type CollectionDelta, type WriterBackend } from "../backend/types.js"; @@ -38,9 +38,20 @@ afterEach(async () => { for (const client of clients.splice(0)) client.close(); vi.unstubAllGlobals(); }); -async function fixture() { +async function fixture(reconnect?: Promise) { const replica = new MemoryReplica({ confirmDelayMs: 0 }); - const client = await replica.client(); clients.push(client); + const connector = replica.connector(); + let connected = false; + const client = reconnect ? await MdbaseClient.connect({ + app: { name: "writer-offline-test", version: "test" }, + connector: { ...connector, async open(hello, signal) { + if (connected) await reconnect; + const result = await connector.open(hello, signal); + connected = true; + return result; + } }, + }) : await replica.client(); + clients.push(client); const scope = new AbortController(); recordScopes.push(scope); // Use a small real CSL style for workspace-state tests. Repeatedly parsing // the much larger Chicago style dominates their CI budget; core tests cover it. @@ -63,6 +74,104 @@ async function fixture() { } const ready = async (workspace: ManuscriptWorkspace) => vi.waitFor(() => expect(workspace.getSnapshot().phase).toBe("ready")); +it("keeps both chapter versions when a remote edit arrives after offline typing", async () => { + const events = new EventTarget(); + vi.stubGlobal("window", events); + let allowReconnect!: () => void; + const reconnect = new Promise(resolve => { allowReconnect = resolve; }); + const { backend, replica, client, open } = await fixture(reconnect); + const workspace = open(); + const path = "chapters/one.md"; + const chapter = () => workspace.getSnapshot().records.get(path); + const store = new DraftStore(backend.draftNamespace!); + await vi.waitFor(() => expect(chapter()?.snapshot.state).toBe("saved")); + const baseBody = chapter()!.snapshot.body; + const local = `${baseBody}\nDraft typed offline.\n`; + const remote = `${baseBody}\nAn edit from another device.\n`; + + try { + replica.dropConnections(); + await vi.waitFor(() => expect(client.link).toBe("reconnecting")); + workspace.setBody(path, local); + expect(chapter()).toMatchObject({ localSaved: true, snapshot: { body: local, dirty: true } }); + expect(store.read(path)).toMatchObject({ body: local, baseBody }); + replica.editElsewhere(path, { body: remote }); + expect(chapter()?.snapshot.body).toBe(local); + } finally { + allowReconnect(); + } + + await vi.waitFor(() => expect(client.link).toBe("open")); + events.dispatchEvent(new Event("online")); + await vi.waitFor(() => expect(chapter()).toMatchObject({ localSaved: true, snapshot: { state: "conflict", body: local, remote: { body: remote } } })); + expect(workspace.hasUnsavedChanges()).toBe(true); + expect(store.read(path)).toMatchObject({ body: local, baseBody }); + expect(workspace.localDrafts().find(([at]) => at === path)?.[1]).toContain(local); + expect((await workspace.retrySave(path)).ok).toBe(false); + expect((await client.get({ path }, { include: { body: true } })).body).toBe(remote); + + const merged = `${local}\nAn edit from another device.\n`; + workspace.resolveConflict(path, { body: merged }); + expect((await workspace.retrySave(path)).ok).toBe(true); + expect((await client.get({ path }, { include: { body: true } })).body).toBe(merged); + expect(store.read(path)).toBeNull(); +}); + +it.each(["confirmed", "superseded", "rejected"] as const)("keeps an offline device save until it is %s", async outcome => { + const { backend, replica, client, open } = await fixture(); + const path = "chapters/one.md"; + const store = new DraftStore(backend.draftNamespace!); + const local = "# Local chapter\n\nThis text was edited offline.\n"; + const latest = `${local}\nMore local typing after the device save.\n`; + const remote = "# Collection chapter\n\nThis text arrived from another device.\n"; + const workspace = open(); + await vi.waitFor(() => expect(workspace.getSnapshot().records.get(path)?.snapshot.state).toBe("saved")); + const lease = await backend.records.open(path, { autosave: { idleMs: 1_000 }, timeoutMs: 15_000 }); + if (!lease.ok) throw new Error(lease.problem.code); + try { + replica.setOnline(false); + workspace.setBody(path, local); + expect((await lease.value.session.flush({ timeoutMs: 100 })).ok).toBe(true); + expect(workspace.getSnapshot().records.get(path)?.snapshot).toMatchObject({ state: "saved_on_device", body: local }); + expect(store.read(path)?.body).toBe(local); + const pending = await client.pendingWrites(); + expect(pending).toHaveLength(1); + + // The next workspace opens the same pending record before the log comes back. + await workspace.dispose(); + const reopened = open(); + await vi.waitFor(() => expect(reopened.getSnapshot().records.get(path)?.snapshot.state).toBe("saved_on_device")); + expect(reopened.getSnapshot().recoveredDrafts.size).toBe(0); + expect(store.read(path)?.body).toBe(local); + + if (outcome === "rejected") { + replica.reject(pending[0]!.receipt.mutation); + replica.editElsewhere(path, { body: remote }); + } + if (outcome === "superseded") reopened.setBody(path, latest); + replica.setOnline(true); + if (outcome === "superseded") await reopened.retrySave(path); + const expected = outcome === "rejected" ? remote : outcome === "superseded" ? latest : local; + await vi.waitFor(() => expect(reopened.getSnapshot().records.get(path)?.snapshot).toMatchObject({ state: "saved", body: expected })); + if (outcome !== "rejected") { + expect(store.read(path)).toBeNull(); + expect(reopened.hasUnsavedChanges()).toBe(false); + } else { + expect(reopened.getSnapshot().recoveredDrafts.get(path)?.body).toBe(local); + expect(reopened.localDrafts().find(([at]) => at === path)?.[1]).toContain(local); + expect(store.read(path)?.body).toBe(local); + expect(reopened.hasUnsavedChanges()).toBe(true); + expect((await client.get({ path }, { include: { body: true } })).body).toBe(remote); + reopened.restoreDraft(path); + expect((await reopened.retrySave(path)).ok).toBe(true); + expect((await client.get({ path }, { include: { body: true } })).body).toBe(local); + } + } finally { + replica.setOnline(true); + lease.value.release(); + } +}); + it("retries unsettled saves on focus as well as reconnect and removes both listeners on disposal", async () => { const events = new EventTarget(); vi.stubGlobal("window", events); diff --git a/apps/writer/src/workspace/workspace.ts b/apps/writer/src/workspace/workspace.ts index 092c108e..ba0193ea 100644 --- a/apps/writer/src/workspace/workspace.ts +++ b/apps/writer/src/workspace/workspace.ts @@ -9,7 +9,7 @@ import { applySuggestion, bodyHash, linkPath, targetFor, type CommentChange, typ // content change is forwarded to the worker, which assembles and typesets // the whole manuscript and reports which embedded records it still needs. import type { JsonObject } from "@mdbase-dev/sdk"; -import { ManuscriptAssembler, translateRecord, type WriterRecord, type AssemblyInput } from "@mdbase-writer/core"; +import { ManuscriptAssembler, translateRecord, type WriterRecord, type AssemblyInput, type AssemblyInspection } from "@mdbase-writer/core"; import { BUNDLE_README, materialize } from "@mdbase-writer/core/materialize"; import { isAnnotation } from "@mdbase-writer/core/annotations"; import { IMAGE_EXTENSION, PathIndex, pathIndex, resolveLinkTarget } from "@mdbase-writer/core/records"; @@ -123,6 +123,7 @@ export class ManuscriptWorkspace { private compileCleanups: (() => void)[] = []; private bindings: readonly ManuscriptBinding[] = []; private readonly drafts: DraftStore; + private readonly deviceDrafts = new Map(); private readonly stagedSettings = new Map(); private readonly assetBytes = new Map(); /** Object URLs of images shown in the editor, revoked when the manuscript closes. */ @@ -137,6 +138,7 @@ export class ManuscriptWorkspace { private readonly commentIntents = new Map(); private readonly translations = new Map }>(); private lastOrder: readonly string[] = []; + private lastChapters: readonly (string | null)[] = []; private readonly requestedAssets = new Set(); /** Collection text files loaded for the settings (a .csl style, a .typ template). */ private readonly texts = new Map(); @@ -495,7 +497,13 @@ export class ManuscriptWorkspace { const { session } = opened.value; if (recovered) { const saved = session.getSnapshot(); - if (saved.body === recovered.body && JSON.stringify(saved.frontmatter) === JSON.stringify(recovered.frontmatter)) this.discardDraft(path); + if (saved.body === recovered.body && JSON.stringify(saved.frontmatter) === JSON.stringify(recovered.frontmatter)) { + if (saved.state === "saved") this.discardDraft(path); + else if (saved.state === "saved_on_device") { + this.deviceDrafts.set(path, recovered); + this.clearRecoveredDraft(path); + } + } } const unsubscribe = session.subscribe(() => this.onSession(path, session.getSnapshot())); this.leases.set(path, { lease: opened.value, unsubscribe }); @@ -589,14 +597,57 @@ export class ManuscriptWorkspace { private persistDraft(path: string, raw: SessionSnapshot): boolean { if (this.current.recoveredDrafts.has(path)) return false; const staged = this.stagedSettings.get(path); + let onDevice = this.deviceDrafts.get(path); + if (raw.state === "saved_on_device") { + const prior = this.current.records.get(path)?.snapshot; + if (!onDevice && !prior?.dirty) return false; + const base = onDevice ?? this.drafts.read(path); + const previousRecord = prior?.record ?? raw.record; + const draft: LocalDraft = { + version: 1, body: raw.body, frontmatter: { ...raw.frontmatter, ...staged }, + baseBody: base?.baseBody ?? previousRecord.body ?? "", baseFrontmatter: base?.baseFrontmatter ?? previousRecord.frontmatter, + revision: base?.revision ?? previousRecord.revision, updated: new Date().toISOString(), + }; + this.deviceDrafts.set(path, draft); + return this.storeDraft(path, draft); + } + if (onDevice && raw.state === "saved") { + this.deviceDrafts.delete(path); + // The SDK can adopt a new confirmed body after a pending write rolls + // back. Give the writer both versions before clearing the local backup. + const localBodyChanged = onDevice.body !== onDevice.baseBody; + const fieldsChangedElsewhere = Object.entries(draftPatch(onDevice)).some(([key, value]) => JSON.stringify(value) !== JSON.stringify(raw.frontmatter[key])); + if ((localBodyChanged && onDevice.body !== raw.body) || fieldsChangedElsewhere) { + const recovered = { ...onDevice, body: localBodyChanged ? onDevice.body : raw.body }; + const stored = this.storeDraft(path, recovered); + this.update({ recoveredDrafts: new Map(this.current.recoveredDrafts).set(path, recovered) }); + return stored; + } + } + if (raw.state === "conflict" && raw.dirty) { + this.deviceDrafts.delete(path); + onDevice = undefined; + } + if (onDevice && !raw.dirty && raw.state !== "saved") return this.storeDraft(path, onDevice); if (staged || raw.dirty || raw.state === "conflict" || raw.state === "error" || raw.state === "deleted" && raw.body !== raw.record.body) { - const stored = this.drafts.write(path, { version: 1, body: raw.body, frontmatter: { ...raw.frontmatter, ...staged }, baseBody: raw.record.body ?? "", baseFrontmatter: raw.record.frontmatter, revision: raw.record.revision, updated: new Date().toISOString() }); - if (!stored) this.update({ draftProblem: t`Local draft backup is unavailable (browser storage may be full or blocked). Download your draft before leaving if saving fails.` }); - return stored; - } else this.drafts.remove(path); + const draft: LocalDraft = { + version: 1, body: raw.body, frontmatter: { ...raw.frontmatter, ...staged }, + baseBody: onDevice?.baseBody ?? raw.record.body ?? "", baseFrontmatter: onDevice?.baseFrontmatter ?? raw.record.frontmatter, + revision: onDevice?.revision ?? raw.record.revision, updated: new Date().toISOString(), + }; + if (onDevice && raw.state !== "saved") this.deviceDrafts.set(path, draft); + return this.storeDraft(path, draft); + } + this.drafts.remove(path); return false; } + private storeDraft(path: string, draft: LocalDraft): boolean { + const stored = this.drafts.write(path, draft); + if (!stored) this.update({ draftProblem: t`Local draft backup is unavailable (browser storage may be full or blocked). Download your draft before leaving if saving fails.` }); + return stored; + } + private onResult(result: CompileResult): void { this.update({ result, compiling: false, ...(result.artifact ? { artifact: result.artifact, artifactRevision: result.revision } : {}) }); for (const path of result.unloaded) if (!this.current.recordProblems.has(path)) void this.open(path); @@ -761,10 +812,15 @@ export class ManuscriptWorkspace { }; /** The record each of the manuscript's chapter embeds resolves to (null when none does), in order. */ - chapterPaths(): (string | null)[] { + chapterPaths(): readonly (string | null)[] { const body = this.current.records.get(this.main)?.snapshot.body ?? ""; const candidates = this.current.recordIndex; - return chapterEmbeds(body, this.isChapter).map((e) => resolveLinkTarget(e.target, this.main, candidates)); + const chapters = chapterEmbeds(body).flatMap(({ target }) => { + const path = resolveLinkTarget(target, this.main, candidates); + return path && this.isQuotation(path) ? [] : [path]; + }); + if (chapters.length !== this.lastChapters.length || chapters.some((path, index) => path !== this.lastChapters[index])) this.lastChapters = chapters; + return this.lastChapters; } /** Moves the manuscript's chapter embed at index `from` to index `to`. */ @@ -996,7 +1052,12 @@ export class ManuscriptWorkspace { } discardDraft(path: string): void { + this.deviceDrafts.delete(path); this.drafts.remove(path); + this.clearRecoveredDraft(path); + } + + private clearRecoveredDraft(path: string): void { const recoveredDrafts = new Map(this.current.recoveredDrafts); recoveredDrafts.delete(path); this.update({ recoveredDrafts }); @@ -1006,6 +1067,7 @@ export class ManuscriptWorkspace { const result = await this.backend.deleteDocument(this.main); if (result.ok) { this.stagedSettings.delete(this.main); + this.deviceDrafts.delete(this.main); this.drafts.remove(this.main); } return result; @@ -1015,17 +1077,17 @@ export class ManuscriptWorkspace { const paths = new Set([...this.current.records.keys(), ...this.current.recoveredDrafts.keys()]); return [...paths].map((path) => { const view = this.current.records.get(path); - const recovered = this.current.recoveredDrafts.get(path); const raw = this.leases.get(path)?.lease.session.getSnapshot(); - const frontmatter = recovered?.frontmatter ?? { ...(raw?.frontmatter ?? view?.snapshot.frontmatter ?? {}), ...this.stagedSettings.get(path) }; - return [path, `---\n${JSON.stringify(frontmatter, null, 2)}\n---\n\n${recovered?.body ?? view?.snapshot.body ?? ""}`]; + const draft = this.current.recoveredDrafts.get(path) ?? (raw?.dirty ? undefined : this.deviceDrafts.get(path)); + const frontmatter = draft?.frontmatter ?? { ...(raw?.frontmatter ?? view?.snapshot.frontmatter ?? {}), ...this.stagedSettings.get(path) }; + return [path, `---\n${JSON.stringify(frontmatter, null, 2)}\n---\n\n${draft?.body ?? view?.snapshot.body ?? ""}`]; }); } annotationsForSource = (path: string): ReturnType => this.backend.annotationsForSource(path); /** Independent of preview timing: discover and await all embeds, styles and images. */ - private async preflight(signal?: AbortSignal) { + private async preflight(inspect: (input: AssemblyInput) => T, signal?: AbortSignal) { const check = () => { signal?.throwIfAborted(); if (this.disposed) throw new Error(t`The manuscript was closed.`); @@ -1038,7 +1100,6 @@ export class ManuscriptWorkspace { await this.metadata(); check(); const { styles, locales } = await loadStyles(); - const assembler = new ManuscriptAssembler(); const attemptedRecords = new Set(); const attemptedAssets = new Set(); for (let pass = 0; pass < 100; pass++) { @@ -1050,7 +1111,7 @@ export class ManuscriptWorkspace { library: new Map(snap.library.map((entry) => [entry.key, entry.item])), styles, locales, texts: new Map(this.texts), annotationPaths: snap.annotationPaths, sourceKeys: sourceKeys(snap.library), }; - const assembly = assembler.assemble(input); + const assembly = inspect(input); const records = assembly.unloaded.filter((path) => !attemptedRecords.has(path)); const assets = assembly.assets.filter((path) => !attemptedAssets.has(path)); if (!records.length && !assets.length) { @@ -1074,7 +1135,8 @@ export class ManuscriptWorkspace { } async exportPdf(signal?: AbortSignal): Promise<{ bytes?: Uint8Array; error?: string; problems: readonly string[] }> { - const { assembly, problems } = await this.preflight(signal); + const assembler = new ManuscriptAssembler(); + const { assembly, problems } = await this.preflight(input => assembler.assemble(input), signal); if (this.current.previewProblem) await this.retryPreview(); await this.compile.ready; signal?.throwIfAborted(); @@ -1083,7 +1145,8 @@ export class ManuscriptWorkspace { } private async materialize(crossReferences: "quarto" | "resolved", signal?: AbortSignal) { - const prepared = await this.preflight(signal); + const assembler = new ManuscriptAssembler(); + const prepared = await this.preflight(input => assembler.inspect(input), signal); const out = materialize({ ...prepared.input, crossReferences, formatProblem: diagnosticMessage }); const problems = [...new Set([...prepared.problems, ...out.problems])]; const media: [string, Uint8Array][] = []; diff --git a/packages/core/src/assemble.ts b/packages/core/src/assemble.ts index f403261b..e75b0ade 100644 --- a/packages/core/src/assemble.ts +++ b/packages/core/src/assemble.ts @@ -81,6 +81,8 @@ export interface Assembly { readonly debug: { readonly citations: readonly string[]; readonly bibliography: readonly { key: string; text: string }[] }; } +export type AssemblyInspection = Pick; + type Plan = | { kind: "text"; text: string } | { @@ -128,6 +130,17 @@ export class ManuscriptAssembler { } assemble(input: AssemblyInput): Assembly { + return this.build(input, true); + } + + /** Discover and validate dependencies for a Markdown export that renders its own citations. */ + inspect(input: AssemblyInput): AssemblyInspection { + return this.build(input, false); + } + + private build(input: AssemblyInput, renderTypst: true): Assembly; + private build(input: AssemblyInput, renderTypst: false): AssemblyInspection; + private build(input: AssemblyInput, renderTypst: boolean): AssemblyInspection | Assembly { const diagnostics: AssemblyDiagnostic[] = []; const mainRecord = input.records.get(input.main); const { meta, problems, needs } = manuscriptMeta(mainRecord?.frontmatter ?? {}, { @@ -197,7 +210,7 @@ export class ManuscriptAssembler { } // Citations: walk every record's events in document order. - const cp = this.engine(input, meta); + const cp = renderTypst ? this.engine(input, meta) : undefined; const plans = new Map(); const requests: CitationRequest[] = []; let note = 0; @@ -221,7 +234,7 @@ export class ManuscriptAssembler { if (!cl) continue; const refs = cl.items.filter((i) => labels.has(i.key)); if (refs.length && refs.length === cl.items.length) { - plan[ev.index] = { + if (cp) plan[ev.index] = { kind: "text", text: cl.items .map((i) => `${i.prefix ? `${looseEscape(i.prefix)} ` : ""}#ref(<${typstLabel(i.key)}>);${i.suffix ? looseEscape(i.suffix) : ""}`) @@ -229,7 +242,7 @@ export class ManuscriptAssembler { }; continue; } - for (const m of cl.items.filter((i) => !labels.has(i.key) && !cp.has(i.key))) { + for (const m of cl.items.filter((i) => !labels.has(i.key) && !input.library.has(i.key))) { const looksLikeXref = /^(sec|fig|tbl|eq|lst|thm|lem|def)-/.test(m.key); diagnostics.push({ record: recordOf(path), @@ -242,14 +255,15 @@ export class ManuscriptAssembler { ...(looksLikeXref ? {} : { metadata: "library" as const }), }); } - const items = cl.items.filter((i) => cp.has(i.key)); + const items = cl.items.filter((i) => input.library.has(i.key)); if (!items.length || refs.length) { if (refs.length && items.length) { diagnostics.push({ record: recordOf(path), from: cl.from, to: cl.to, severity: "error", message: "A citation cannot mix cross-references and citekeys.", copy: { code: "citation-mixed" } }); } - plan[ev.index] = { kind: "text", text: cl.items.map((i) => `#missing(${typstString(i.key)});`).join(", ") }; + if (cp) plan[ev.index] = { kind: "text", text: cl.items.map((i) => `#missing(${typstString(i.key)});`).join(", ") }; continue; } + if (!cp) continue; const inNote = inFootnote !== null; const footnote = cp.isNoteStyle && !inNote; if (footnote) note++; @@ -276,26 +290,6 @@ export class ManuscriptAssembler { }; } } - const result = cp.process(requests); - - // `marked` puts source markers in a generated note, so a click on it in the preview finds its sources. - const render = (p: Plan | undefined, marked = false): Rendered => { - if (!p) return { text: "" }; - if (p.kind === "text") return { text: p.text }; - const note = (body: string) => (marked ? `${noteMarker(p.keys, p.from)}${body}${END_MARKER}` : body); - let s = result.strings[p.request] ?? ""; - // Inside a note the surrounding sentence supplies punctuation. - if (p.inNote) s = s.replace(/\.$/, ""); - if (p.narrative) { - const author = cp.authorOnly(p.narrative.key, p.first ?? false); - if (cp.isNoteStyle) return { text: `${author}#footnote[${note(s)}];` }; - return { text: author ? `${author} ${s}` : s }; - } - if (p.inNote && p.bracketed) return { text: `(${s})` }; - if (p.footnote) return { text: `#footnote[${note(s.replace(/^[a-z]/, (c) => c.toUpperCase()))}];`, note: true }; - return { text: s }; - }; - // Images: resolve against the collection's files. const assets = new Set(needs); if (meta.customTemplate) assets.add(meta.template); @@ -320,6 +314,36 @@ export class ManuscriptAssembler { return `image(${typstString(`/${resolved}`)}${ref.width ? `, width: ${ref.width}` : ""})`; }; + if (!cp) { + for (const [path, tr] of translated) { + if (!tr.images.length) continue; + for (const token of tr.typst.matchAll(PLACEHOLDERS)) { + if (token[1] === PLACEHOLDER.image[0]) imageExpression(path, Number(token[2])); + } + } + return { meta, order, unloaded, assets: [...assets], diagnostics }; + } + + const result = cp.process(requests); + + // `marked` puts source markers in a generated note, so a click on it in the preview finds its sources. + const render = (p: Plan | undefined, marked = false): Rendered => { + if (!p) return { text: "" }; + if (p.kind === "text") return { text: p.text }; + const note = (body: string) => (marked ? `${noteMarker(p.keys, p.from)}${body}${END_MARKER}` : body); + let s = result.strings[p.request] ?? ""; + // Inside a note the surrounding sentence supplies punctuation. + if (p.inNote) s = s.replace(/\.$/, ""); + if (p.narrative) { + const author = cp.authorOnly(p.narrative.key, p.first ?? false); + if (cp.isNoteStyle) return { text: `${author}#footnote[${note(s)}];` }; + return { text: author ? `${author} ${s}` : s }; + } + if (p.inNote && p.bracketed) return { text: `(${s})` }; + if (p.footnote) return { text: `#footnote[${note(s.replace(/^[a-z]/, (c) => c.toUpperCase()))}];`, note: true }; + return { text: s }; + }; + const sources = new Map(); const maps = new Map(); const rawBlocks = new Map(); diff --git a/packages/core/test/assemble.test.ts b/packages/core/test/assemble.test.ts index bd2539cb..7bd9d93d 100644 --- a/packages/core/test/assemble.test.ts +++ b/packages/core/test/assemble.test.ts @@ -89,6 +89,20 @@ describe("ManuscriptAssembler", () => { ]); }); + it("inspects export dependencies and warnings without rendering Typst", () => { + const records = new Map([ + ["book.md", record("book.md", "# Book {#sec-book}\n\n![[chapter]]\n\n![[unloaded]]\n\nSee [@sec-book; @badiouBeing07] and [@unknown].\n")], + ["chapter.md", record("chapter.md", "![Available](a.png)\n\nFootnote.[^note]\n\n[^note]: ![Missing](b.png)\n")], + ]); + const project = { ...input(records, "book.md", new Set(["a.png"])), recordPaths: new Set([...records.keys(), "unloaded.md"]) }; + const assembler = new ManuscriptAssembler(); + const { meta, order, unloaded, assets, diagnostics } = assembler.assemble(project); + expect(assembler.inspect(project)).toEqual({ meta, order, unloaded, assets, diagnostics }); + expect(unloaded).toEqual(["unloaded.md"]); + expect(assets).toEqual(["a.png"]); + expect(diagnostics.map(d => d.copy?.code)).toEqual(["citation-mixed", "citekey-missing", "image-missing"]); + }); + it("falls back from unknown styles and templates with a warning", () => { const records = new Map([["m.md", record("m.md", "---\ncsl: made-up\ntemplate: poster\n---\nText.\n")]]); const a = new ManuscriptAssembler().assemble(input(records, "m.md")); From 4a98585b088a8b92389bdf84497aea2016aaedd6 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Sat, 28 Nov 2026 22:37:42 +1100 Subject: [PATCH 2/2] Preserve Writer selection and viewport through overlays and sidebar changes Refs #248 --- .../writer/scripts/browser-polish-r4-test.mjs | 26 +++++++++++-- apps/writer/src/editor/Editor.tsx | 26 ++++++++++++- apps/writer/src/ui/WorkspaceView.tsx | 37 +++++++++++++++---- 3 files changed, 77 insertions(+), 12 deletions(-) diff --git a/apps/writer/scripts/browser-polish-r4-test.mjs b/apps/writer/scripts/browser-polish-r4-test.mjs index 6aa38c6c..12343fcc 100644 --- a/apps/writer/scripts/browser-polish-r4-test.mjs +++ b/apps/writer/scripts/browser-polish-r4-test.mjs @@ -30,6 +30,15 @@ async function typeInEditor(page, text) { assert.ok(await page.evaluate(text => [...window.writer.workspace.getSnapshot().records.values()].some(record => record.snapshot.body.includes(text)), text), `Typing after handoff lost ${text}`); } +const editorState = page => page.evaluate(async () => (await import("/scripts/browser-a11y-fixture.tsx")).editorSnapshot()); + +async function assertInsertion(page, before, text) { + const expected = before.text.slice(0, before.from) + text + before.text.slice(before.to); + assert.equal((await editorState(page)).text, expected, `Editor lost or misplaced ${text.trim()}`); + const saved = await page.evaluate(() => window.writer.workspace.getSnapshot().records.get("chapters/reefs.md").snapshot.body); + assert.equal(saved, expected, `Workspace did not receive ${text.trim()}`); +} + async function command(page, query) { await page.keyboard.press("Control+k"); await page.locator(".mdbase-command-palette input").waitFor(); @@ -155,6 +164,9 @@ async function continuePosition(page, width, reduced) { // Logged on success too, so CI shows how close the hide runs to its budget. console.log(`sidebar hide longest tasks ${reduced ? "reduce" : "no-preference"}: median ${median}ms of ${JSON.stringify(longestTasks)}`); assert.ok(median < 50, `Sidebar long-task budget exceeded: median of the longest task per hide is ${median}ms (${JSON.stringify(longestTasks)})`); + const afterSidebar = await visible(); + assert.equal(afterSidebar.text, anchor.text, "Toggling the sidebar changed the first visible line"); + assert.ok(Math.abs(afterSidebar.y - anchor.y) < 2, `Toggling the sidebar moved the viewport: ${JSON.stringify({ anchor, afterSidebar })}`); } await page.getByRole("button", { name: "Manuscripts", exact: true }).click(); await page.locator(".continue-card").waitFor(); @@ -165,7 +177,7 @@ async function continuePosition(page, width, reduced) { await editor.waitFor(); await page.waitForTimeout(220); const restored = await visible(); - assert.equal(restored.text, anchor.text); + assert.equal(restored.text, anchor.text, `Continue moved to another line: ${JSON.stringify({ anchor, restored, position })}`); assert.ok(Math.abs(restored.y - anchor.y) < 2, `Continue moved visible text: ${JSON.stringify({ anchor, restored, position })}`); const before = await page.evaluate(() => { const workspace = window.writer.workspace; return workspace.getSnapshot().records.get(workspace.main).snapshot.body; }); await page.keyboard.type("RESUMED"); @@ -193,6 +205,7 @@ async function continuePosition(page, width, reduced) { async function immediateResume(page, shortcut, overlay, text, reduced) { await page.locator(".cm-content").focus(); + const before = await editorState(page); await page.keyboard.press(shortcut); await page.locator(overlay).waitFor(); await page.locator(overlay).evaluate(element => Promise.all(element.getAnimations().map(animation => animation.finished))); @@ -218,7 +231,7 @@ async function immediateResume(page, shortcut, overlay, text, reduced) { }, { overlay }); await page.keyboard.press("Escape"); await page.keyboard.type(text, { delay: 3 }); - assert.ok(await page.evaluate(text => [...window.writer.workspace.getSnapshot().records.values()].some(record => record.snapshot.body.includes(text)), text), `Immediate Escape resume lost ${text}`); + await assertInsertion(page, before, text); const [first] = await page.evaluate(() => window.resumeKeys); assert.equal(first.editor, true, JSON.stringify(first)); if (!reduced) assert.deepEqual({ attached: first.attached, inert: first.inert }, { attached: true, inert: true }); @@ -228,11 +241,12 @@ async function immediateResume(page, shortcut, overlay, text, reduced) { async function roundFive(page, width, reduced) { for (const [shortcut, selector, text] of [["Control+k", ".mdbase-command-palette", " PALETTE_POINTER "], ["Control+/", ".shortcuts-dialog", " HELP_POINTER "]]) { await page.locator(".cm-content").focus(); + const before = await editorState(page); await page.keyboard.press(shortcut); await page.locator(selector).waitFor(); await page.mouse.click(4, 10); await page.keyboard.type(text, { delay: 3 }); - assert.ok(await page.evaluate(text => [...window.writer.workspace.getSnapshot().records.values()].some(record => record.snapshot.body.includes(text)), text), `Pointer dismissal lost ${text}`); + await assertInsertion(page, before, text); assert.equal(await page.evaluate(() => document.activeElement?.matches(".cm-content")), true); await page.locator(selector).waitFor({ state: "hidden" }); } @@ -246,11 +260,14 @@ async function roundFive(page, width, reduced) { await page.keyboard.press("Escape"); await page.locator(".mdbase-command-palette").waitFor({ state: "hidden" }); await immediateResume(page, "Control+/", ".shortcuts-dialog", " HELP_ESCAPE ", reduced); + await page.keyboard.press("Shift+ArrowLeft"); + const beforeHelp = await editorState(page); + assert.ok(beforeHelp.from < beforeHelp.to, "Select text before opening the palette"); await command(page, "Keyboard shortcuts"); await page.locator(".shortcuts-dialog").waitFor(); await page.keyboard.press("Escape"); await page.keyboard.type(" PALETTE_HELP ", { delay: 3 }); - assert.ok(await page.evaluate(() => [...window.writer.workspace.getSnapshot().records.values()].some(record => record.snapshot.body.includes(" PALETTE_HELP ")))); + await assertInsertion(page, beforeHelp, " PALETTE_HELP "); await page.locator(".shortcuts-dialog").waitFor({ state: "hidden" }); await command(page, "Settings"); await page.locator(".settings-sheet").waitFor(); @@ -385,6 +402,7 @@ try { await context.route("**/*", route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort()); const page = await context.newPage(); page.setDefaultTimeout(7000); + page.setDefaultNavigationTimeout(30_000); const errors = []; page.on("pageerror", error => errors.push(error.message)); try { diff --git a/apps/writer/src/editor/Editor.tsx b/apps/writer/src/editor/Editor.tsx index df9e11cb..37f71ac0 100644 --- a/apps/writer/src/editor/Editor.tsx +++ b/apps/writer/src/editor/Editor.tsx @@ -55,6 +55,8 @@ export interface EditorHandle { coords(offset: number): { left: number; top: number; bottom: number } | null; /** The editor's scrolling element, to follow while something is placed beside the text. */ scroller(): HTMLElement; + /** Capture the viewport before a layout change and restore it on the same document. */ + captureScroll(): () => void; } export interface RetainedEditor { @@ -201,6 +203,8 @@ export const Editor = memo(function Editor({ states, position, onPosition, path, // an animation frame is clamped while long documents are still virtualised. const restored = position?.path === path ? position : undefined; const v = new EditorView({ parent: host.current, state, ...(retained ? { scrollTo: retained.scroll } : restored ? { scrollTo: EditorView.scrollIntoView(Math.min(doc.length, restored.top), { y: "start", yMargin: restored.offset }) } : {}) }); + let layoutScroll: { doc: Text; selection: EditorSelection; scroll: RetainedEditor["scroll"]; top: number; left: number } | undefined; + let scrollFrame = 0; let measured = false; v.requestMeasure({ read: () => { measured = true; } }); view.current = v; @@ -232,6 +236,23 @@ export const Editor = memo(function Editor({ states, position, onPosition, path, scroller() { return v.scrollDOM; }, + captureScroll() { + const { doc, selection } = v.state; + const { scrollTop, scrollLeft } = v.scrollDOM; + // A wrapped line can become shorter than its captured offset. Reuse + // the original anchor on the next resize until the writer moves away. + const scroll = layoutScroll?.doc === doc && layoutScroll.selection.eq(selection) + && layoutScroll.top === scrollTop && layoutScroll.left === scrollLeft ? layoutScroll.scroll : v.scrollSnapshot(); + return () => { + if (view.current !== v || v.state.doc !== doc || !v.state.selection.eq(selection)) return; + v.dispatch({ effects: scroll }); + cancelAnimationFrame(scrollFrame); + // CodeMirror applies its scroll target during the next measurement. + scrollFrame = requestAnimationFrame(() => { + layoutScroll = { doc, selection, scroll, top: v.scrollDOM.scrollTop, left: v.scrollDOM.scrollLeft }; + }); + }; + }, insert(insertion, options) { if (v.state.readOnly) return; v.dispatch(v.state.replaceSelection(insertion), { scrollIntoView: true, userEvent: "input" }); @@ -276,7 +297,9 @@ export const Editor = memo(function Editor({ states, position, onPosition, path, const savePosition = () => { if (!measured) return; const edge = v.scrollDOM.getBoundingClientRect(); - const top = v.posAtCoords({ x: edge.left, y: edge.top + v.defaultLineHeight / 2 }); + if (!edge.height) return; + // Sample the very top, so a partially visible wrapped row is retained. + const top = v.posAtCoords({ x: edge.left, y: edge.top }); if (top === null) return; const coordinates = v.coordsAtPos(top); if (!coordinates) return; @@ -287,6 +310,7 @@ export const Editor = memo(function Editor({ states, position, onPosition, path, // React's development setup/cleanup/setup must not replace the retained // scroll target with zero before CodeMirror has had a layout pass. if (measured || retained) states?.set(path, { state: v.state, scroll: retained && !measured ? retained.scroll : v.scrollSnapshot() }); + cancelAnimationFrame(scrollFrame); window.removeEventListener("pagehide", savePosition); v.destroy(); view.current = null; diff --git a/apps/writer/src/ui/WorkspaceView.tsx b/apps/writer/src/ui/WorkspaceView.tsx index e8d43c68..01f414ee 100644 --- a/apps/writer/src/ui/WorkspaceView.tsx +++ b/apps/writer/src/ui/WorkspaceView.tsx @@ -289,6 +289,15 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc }); }, []); const toggleLivePreview = useCallback(() => setLayout((l) => ({ ...l, livePreview: !l.livePreview })), [setLayout]); + const restoreEditorScroll = useRef<(() => void) | undefined>(undefined); + const toggleSidebar = useCallback(() => { + restoreEditorScroll.current = editor.current?.captureScroll(); + setLayout(current => ({ ...current, sidebar: !current.sidebar })); + }, [setLayout]); + useLayoutEffect(() => { + restoreEditorScroll.current?.(); + restoreEditorScroll.current = undefined; + }, [layout.sidebar]); const setView = useCallback((view: View) => { setLayout(current => ({ ...current, view })); requestAnimationFrame(() => { if (view === "preview") grid.current?.querySelector(".preview")?.focus(); else editor.current?.focus(); }); @@ -512,7 +521,17 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc const renameChapter = useCallback((path: string, title: string) => signalFailure(workspace.renameChapter(path, title)), [workspace]); const openSettings = useCallback(() => setSettingsOpen(true), []); const retryPreview = useCallback(() => { void workspace.retryPreview(); }, [workspace]); - const closeShortcuts = useCallback(() => setShortcutsOpen(false), []); + const closeWritingDialog = useCallback((close: () => void) => { + flushSync(close); + // Native dialog focus restoration can leave the DOM selection in the + // dismissed dialog. Synchronize it before the next keystroke, while + // respecting other openers such as the More menu button. + const handle = editor.current; + const focused = document.activeElement; + if (focused?.matches(".cm-content") && handle?.scroller().contains(focused)) handle.focus(); + }, []); + const closePalette = useCallback(() => closeWritingDialog(() => setPaletteOpen(false)), [closeWritingDialog]); + const closeShortcuts = useCallback(() => closeWritingDialog(() => setShortcutsOpen(false)), [closeWritingDialog]); const onEditorReady = useCallback((handle: EditorHandle) => { editor.current = handle; @@ -842,15 +861,19 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc const mod = isMod(e); const blockingDialog = document.querySelector("dialog[open]:not([inert]):not(.settings-sheet), .settings-sheet:modal"); if (mod && !e.shiftKey && e.key.toLowerCase() === "k" && (paletteOpen || !blockingDialog)) { - e.preventDefault(); e.stopPropagation(); setPaletteOpen(open => !open); return; + e.preventDefault(); e.stopPropagation(); + if (paletteOpen) closePalette(); else setPaletteOpen(true); + return; } if (mod && e.key === "/" && (shortcutsOpen || !blockingDialog)) { - e.preventDefault(); e.stopPropagation(); setShortcutsOpen(open => !open); return; + e.preventDefault(); e.stopPropagation(); + if (shortcutsOpen) closeShortcuts(); else setShortcutsOpen(true); + return; } if (e.target instanceof Element && e.target.closest("dialog[open]:not(.settings-sheet), .settings-sheet:modal")) return; if (blockingDialog && e.key !== "F8") return; let handled = true; - if (mod && !e.shiftKey && e.code === "Backslash") setLayout((l) => ({ ...l, sidebar: !l.sidebar })); + if (mod && !e.shiftKey && e.code === "Backslash") toggleSidebar(); else if (mod && e.shiftKey && e.code === "Backslash") setView(VIEW_ORDER[(VIEW_ORDER.indexOf(layout.view) + 1) % VIEW_ORDER.length] as View); else if (mod && e.shiftKey && e.code === "KeyF") showSearch(); else if (mod && e.shiftKey && e.code === "KeyE") showSources(); @@ -1016,7 +1039,7 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc { id: "zoom-in", group: translate`View`, label: translate`Zoom in`, run: () => setLayout(current => ({ ...current, zoom: nextZoom(previewView?.scale ?? 1, 1) })) }, { id: "zoom-out", group: translate`View`, label: translate`Zoom out`, run: () => setLayout(current => ({ ...current, zoom: nextZoom(previewView?.scale ?? 1, -1) })) }, { id: "lower-panel", group: translate`View`, label: layout.lowerTab ? translate`Close the lower panel` : translate`Split sidebar`, keywords: translate`split stack outline comments sources`, run: toggleLower }, - { id: "sidebar", group: translate`View`, label: layout.sidebar ? translate`Hide the sidebar` : translate`Show the sidebar`, shortcut: "mod+\\", run: () => setLayout((l) => ({ ...l, sidebar: !l.sidebar })) }, + { id: "sidebar", group: translate`View`, label: layout.sidebar ? translate`Hide the sidebar` : translate`Show the sidebar`, shortcut: "mod+\\", run: toggleSidebar }, { id: "live-preview", group: translate`View`, label: layout.livePreview ? translate`Show Markdown as written` : translate`Read as the manuscript`, keywords: translate`source markup raw live preview chips`, run: toggleLivePreview }, { id: "cycle-view", group: translate`View`, label: translate`Cycle editor and preview`, shortcut: "mod+shift+\\", run: () => setView(VIEW_ORDER[(VIEW_ORDER.indexOf(layout.view) + 1) % VIEW_ORDER.length]!) }, ...VIEW_ORDER.filter((view) => view !== layout.view).map((view) => ({ id: `view-${view}`, group: translate`View`, label: VIEW_NAME[view], run: () => setView(view) })), @@ -1070,7 +1093,7 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc type="button" className="mdbase-icon-button" aria-pressed={layout.sidebar} - onClick={() => setLayout((l) => ({ ...l, sidebar: !l.sidebar }))} + onClick={toggleSidebar} title={layout.sidebar ? translate`Hide the sidebar (${shortcutLabel("mod+\\")})` : translate`Show the sidebar (${shortcutLabel("mod+\\")})`} aria-label={translate`Sidebar`} > @@ -1380,7 +1403,7 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc setPaletteOpen(false)} + onClose={closePalette} label={translate`Writer commands`} commands={commands} />