diff --git a/apps/writer/scripts/browser-a11y-test.mjs b/apps/writer/scripts/browser-a11y-test.mjs index cf29707d..3d01e19e 100644 --- a/apps/writer/scripts/browser-a11y-test.mjs +++ b/apps/writer/scripts/browser-a11y-test.mjs @@ -10,6 +10,8 @@ assert.ok(["127.0.0.1", "localhost", "[::1]"].includes(new URL(base).hostname)); await mkdir("out", { recursive: true }); const browser = await chromium.launch({ executablePath: process.env.CHROME }); let failures = 0; +let audits = 0; +const wcag = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22a", "wcag22aa"]; async function audit(page, name) { await page.evaluate(async () => { @@ -19,17 +21,27 @@ async function audit(page, name) { ).map(animation => animation.finished.catch(() => {}))); }); await page.evaluate(axe.source); - const results = await page.evaluate(() => window.axe.run(document, { + const results = await page.evaluate(tags => window.axe.run(document, { + runOnly: { type: "tag", values: tags }, // This speech-input rule is opt-in in axe, including the production sweep. rules: { "label-content-name-mismatch": { enabled: true } }, - })); - await writeFile(`out/a11y-${name}.json`, JSON.stringify(results.violations, null, 2)); - const serious = results.violations.filter(({ impact }) => impact === "serious" || impact === "critical"); - if (serious.length) { + }), wcag); + audits++; + const contrastNeedsReview = results.incomplete.filter(({ id }) => id === "color-contrast"); + // Axe leaves single characters (including real numeric badges) undecided. + // Use its measured ratio when it can identify both colors. + const shortText = contrastNeedsReview.flatMap(({ nodes }) => nodes.filter(node => + node.any.some(({ data }) => data?.messageKey === "shortTextContent" && + data.fgColor && data.bgColor && data.contrastRatio < Number.parseFloat(data.expectedContrastRatio)) + )); + await writeFile(`out/a11y-${name}.json`, JSON.stringify({ violations: results.violations, shortText, contrastNeedsReview }, null, 2)); + const violations = results.violations.map(({ id, nodes }) => ({ id, targets: nodes.map(n => n.target) })); + if (shortText.length) violations.push({ id: "color-contrast (short text)", targets: shortText.map(n => n.target) }); + if (violations.length) { failures++; await page.screenshot({ path: `out/a11y-${name}.png`, fullPage: true }); - console.error(`FAIL ${name}: ${JSON.stringify(serious.map(v => ({ id: v.id, nodes: v.nodes.map(n => n.target) })))}`); - } else console.log(`PASS ${name}: no serious or critical axe violations`); + console.error(`FAIL ${name}: ${JSON.stringify(violations)}`); + } else console.log(`PASS ${name}: no WCAG AA axe violations`); } async function escapeTo(page, dialog, opener) { @@ -41,8 +53,13 @@ async function escapeTo(page, dialog, opener) { } try { - for (const width of [375, 1280]) { - const context = await browser.newContext({ viewport: { width, height: 812 }, colorScheme: "light" }); + for (const [width, colorScheme] of [390, 1280].flatMap(width => ["light", "dark"].map(theme => [width, theme]))) { + const scenario = `${width}-${colorScheme}`; + const context = await browser.newContext({ + viewport: { width, height: width === 390 ? 844 : 900 }, + colorScheme, + hasTouch: width === 390, + }); await context.route("**/*", route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort()); const page = await context.newPage(); page.setDefaultTimeout(15_000); @@ -51,14 +68,20 @@ try { await page.getByRole("heading", { name: "Manuscripts", exact: true }).waitFor(); await page.evaluate(async () => (await import("/scripts/browser-a11y-fixture.tsx")).mountSignIn()); await page.getByRole("button", { name: "Sign in", exact: true }).waitFor(); - await audit(page, `signin-${width}`); + await audit(page, `signin-${scenario}`); await page.goto(`${base}?demo`); await page.getByRole("heading", { name: "Manuscripts", exact: true }).waitFor(); - await audit(page, `home-${width}`); + await audit(page, `home-${scenario}`); const create = page.getByRole("button", { name: "New manuscript", exact: true }); await create.click(); - await audit(page, `new-manuscript-${width}`); + await audit(page, `new-manuscript-${scenario}`); + await page.getByRole("button", { name: "Use a note you already have…" }).click(); + const note = page.locator(".note-option").first(); + await note.focus(); + await page.keyboard.press("Enter"); + assert.equal(await note.getAttribute("aria-pressed"), "true"); + await audit(page, `adopt-note-${scenario}`); await escapeTo(page, page.getByRole("dialog", { name: "New manuscript", exact: true }), create); await page.locator(".manuscripts > li", { hasText: "Small Agents, Large Effects" }).locator("[data-path]").click(); @@ -68,7 +91,7 @@ try { }, null, { timeout: 60_000 }); if (width < 900) { assert.equal(await page.locator(".preview").evaluate(element => element.checkVisibility({ visibilityProperty: true })), false); - await audit(page, `editor-${width}`); + await audit(page, `editor-${scenario}`); await page.getByRole("navigation", { name: "View", exact: true }).getByRole("button", { name: /Preview/ }).click(); } await page.waitForFunction(() => { @@ -77,16 +100,32 @@ try { return snap?.artifact && !snap.compiling && Number(document.querySelector(".preview-pages")?.dataset.renderedRevision) === snap.artifactRevision && canvas?.checkVisibility({ visibilityProperty: true }); }, null, { timeout: 60_000 }); if (width < 900) { - await audit(page, `preview-${width}`); + await audit(page, `preview-${scenario}`); await page.getByRole("navigation", { name: "View", exact: true }).getByRole("button", { name: /Sidebar/ }).click(); - } else await audit(page, `editor-${width}`); - for (const name of ["Sources", "Comments"]) { + } else await audit(page, `editor-${scenario}`); + for (const name of ["Outline", "Sources", "Comments"]) { await page.getByRole("tab", { name: new RegExp(name) }).click(); + if (name === "Sources") await page.locator(".source-row").first().waitFor(); if (name === "Comments") await page.waitForFunction(() => window.writer.workspace.getSnapshot().commentsLoad.phase === "ready"); - await audit(page, `${name.toLowerCase()}-${width}`); + await audit(page, `${name.toLowerCase()}-${scenario}`); } + const outlineSearch = page.getByRole("searchbox", { name: "Search outline", exact: true }); + await page.getByRole("tab", { name: "Outline", exact: true }).click(); + await outlineSearch.fill("Darwin"); + await page.locator(".search-hit").first().waitFor(); + await audit(page, `outline-search-${scenario}`); + await outlineSearch.clear(); + await page.getByRole("tab", { name: /Sources/ }).click(); + const sourceSearch = page.locator(".sources input[type=search]"); + await sourceSearch.fill("darwinFormation81"); + await page.locator('.source-row[data-key="darwinFormation81"]').click(); + await page.getByRole("textbox", { name: /^Page or locator for / }).waitFor(); + await audit(page, `citation-details-${scenario}`); + await sourceSearch.clear(); + await page.getByRole("tab", { name: /Comments/ }).click(); + await page.getByRole("button", { name: "Split sidebar", exact: true }).click(); - await audit(page, `split-sidebar-${width}`); + await audit(page, `split-sidebar-${scenario}`); await page.getByRole("button", { name: "Close the lower panel", exact: true }).click(); if (width < 900) await page.getByRole("navigation", { name: "View", exact: true }).getByRole("button", { name: /Write/ }).click(); const settings = page.getByRole("button", { name: "Settings", exact: true }); @@ -94,10 +133,19 @@ try { await page.getByRole("button", { name: "More", exact: true }).click(); await page.getByRole("menuitem", { name: "Settings", exact: true }).click(); } else await settings.click(); - await audit(page, `settings-${width}`); + await audit(page, `settings-${scenario}`); await escapeTo(page, page.getByRole("dialog", { name: "Manuscript settings", exact: true }), page.locator(".cm-content")); const more = page.getByRole("button", { name: "More", exact: true }); + await page.locator(".cm-content").focus(); + await page.keyboard.press("Control+End"); + await page.keyboard.press("Enter"); + await page.keyboard.insertText("[@darwin"); + const completion = page.locator(".cm-tooltip-autocomplete [role=option]").first(); + await completion.waitFor(); + await audit(page, `citation-completion-${scenario}`); + await page.keyboard.press("Escape"); + await completion.waitFor({ state: "hidden" }); for (const name of ["Keyboard shortcuts", "Commands"]) { if (width < 900) await page.keyboard.press(name === "Commands" ? "Control+k" : "Control+/"); else { @@ -106,26 +154,23 @@ try { } const dialog = page.getByRole("dialog", { name: name === "Commands" ? "Writer commands" : name, exact: true }); await dialog.waitFor(); - await audit(page, `${name.toLowerCase().replaceAll(" ", "-")}-${width}`); + await audit(page, `${name.toLowerCase().replaceAll(" ", "-")}-${scenario}`); await escapeTo(page, dialog, width < 900 ? page.locator(".cm-content") : more); } await page.evaluate(() => { const { workspace } = window.writer; workspace.setBody(workspace.main, "# Export check\n\nMissing citation [@a11y-missing].\n"); }); - let exportOpener; - if (width < 900) { - await more.click(); - await page.getByRole("menuitem", { name: "PDF", exact: true }).click(); - exportOpener = more; - } else { - exportOpener = page.getByRole("button", { name: "Export PDF", exact: true }); - await exportOpener.click(); - } + const exportMenu = width < 900 ? more : page.getByRole("button", { name: "Export formats" }); + await exportMenu.click(); + const word = page.getByRole("menuitem").filter({ has: page.getByText("Word (DOCX)", { exact: true }) }); + await word.waitFor(); + await audit(page, `export-menu-${scenario}`); + await word.click(); const exportReview = page.getByRole("dialog", { name: "Review export problems", exact: true }); await exportReview.waitFor({ timeout: 60_000 }); - await audit(page, `export-review-${width}`); - await escapeTo(page, exportReview, exportOpener); + await audit(page, `export-review-${scenario}`); + await escapeTo(page, exportReview, exportMenu); await page.evaluate(() => { const { workspace, backend } = window.writer; const snapshot = workspace.getSnapshot().records.get(workspace.main).snapshot; @@ -134,11 +179,11 @@ try { }); const compare = page.getByRole("button", { name: "Compare versions", exact: true }); await compare.click(); - await audit(page, `compare-${width}`); + await audit(page, `compare-${scenario}`); await escapeTo(page, page.getByRole("dialog", { name: "Compare conflicting versions", exact: true }), compare); const home = page.getByRole("button", { name: "Manuscripts", exact: true }); await home.click(); - await audit(page, `unsaved-changes-${width}`); + await audit(page, `unsaved-changes-${scenario}`); await page.evaluate(() => { const { workspace } = window.writer; const retry = workspace.retrySave.bind(workspace); @@ -152,12 +197,39 @@ try { await page.waitForFunction(() => !document.querySelector('.compare-actions [aria-disabled="true"]')); assert.ok(await retry.evaluate(el => el === document.activeElement), "A failed retry keeps focus"); await escapeTo(page, page.getByRole("dialog", { name: "Some changes are not saved", exact: true }), home); - console.log(`PASS ${width}px: dialogs close with Escape and restore focus`); + // The browser-local checkpoint survives a reload. Audit its home row, + // the editor banner, and the comparison before choosing a version. + await page.goto(`${base}?demo`); + await page.locator(".manuscripts > li", { hasText: "Patient Observation" }).locator("[data-path]").click(); + await page.waitForFunction(() => window.writer?.workspace?.getSnapshot().phase === "ready"); + await page.evaluate(async () => { + const { workspace } = window.writer; + const snap = workspace.getSnapshot().records.get(workspace.main).snapshot; + const { DraftStore } = await import("/src/workspace/drafts.ts"); + new DraftStore("demo").write(workspace.main, { + version: 1, body: "# Recovered local draft\n", frontmatter: snap.frontmatter, + baseBody: snap.body, baseFrontmatter: snap.record.frontmatter, + revision: snap.record.revision, updated: new Date().toISOString(), + }); + }); + await page.goto(`${base}?demo`); + const drafts = page.getByRole("region", { name: "Unsaved drafts" }); + await drafts.waitFor(); + await audit(page, `offline-drafts-${scenario}`); + await drafts.getByRole("listitem").filter({ hasText: "Patient Observation" }).getByRole("button", { name: "Review", exact: true }).click(); + const reviewDraft = page.getByRole("button", { name: "Review Patient Observation", exact: true }); + await reviewDraft.waitFor(); + await audit(page, `recovery-banner-${scenario}`); + await reviewDraft.click(); + await page.getByRole("button", { name: "Restore local draft", exact: true }).waitFor(); + await audit(page, `recovery-dialog-${scenario}`); + console.log(`PASS ${scenario}: dialogs close with Escape and restore focus`); } catch (error) { failures++; - await page.screenshot({ path: `out/a11y-failure-${width}.png`, fullPage: true }); - console.error(`FAIL ${width}px: ${error.stack}`); + await page.screenshot({ path: `out/a11y-failure-${scenario}.png`, fullPage: true }); + console.error(`FAIL ${scenario}: ${error.stack}`); } finally { await context.close(); } } } finally { await browser.close(); } +console.log(`Audited ${audits} Writer surfaces across viewport and theme combinations`); assert.equal(failures, 0, `${failures} accessibility checks failed`); diff --git a/apps/writer/scripts/browser-reliability-test.mjs b/apps/writer/scripts/browser-reliability-test.mjs index 65349604..b750757a 100644 --- a/apps/writer/scripts/browser-reliability-test.mjs +++ b/apps/writer/scripts/browser-reliability-test.mjs @@ -2,6 +2,7 @@ // Run with the development server: node scripts/browser-reliability-test.mjs [base URL] import assert from "node:assert/strict"; import { mkdirSync } from "node:fs"; +import { execFileSync } from "node:child_process"; import { chromium } from "playwright"; const base = process.argv[2] ?? process.env.BASE ?? "http://127.0.0.1:5320/"; @@ -479,7 +480,7 @@ try { assert.equal(await page.locator(".toast.tone-busy").count(), 0); }); - await scenario("new manuscripts can include an actionable worked example", async (page) => { + await scenario("the worked example exports its collection image and cited footnote to Word", async (page) => { await page.goto(`${base}?demo`); await page.getByRole("button", { name: "New manuscript" }).click(); await page.getByRole("textbox", { name: "Title", exact: true }).fill("[test] Worked example"); @@ -488,6 +489,45 @@ try { await page.waitForFunction(() => window.writer?.workspace?.getSnapshot().phase === "ready"); const text = await page.evaluate(() => { const workspace = window.writer.workspace; return workspace.getSnapshot().records.get(workspace.main).snapshot.body; }); assert.match(text, /fig-example/); assert.match(text, /Add chapter/); assert.match(text, /A cited claim \[@/); + + const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==", "base64"); + await page.evaluate(async bytes => { + const { backend, workspace } = window.writer; + // A collection client models the peer that adds the file. Export reads + // it through Writer's native descriptor and download checks. + const uploaded = await backend.fixture.client().files.upload("figures/example.png", new Uint8Array(bytes)); + await uploaded.confirmed; + const snapshot = workspace.getSnapshot().records.get(workspace.main).snapshot; + const citekey = /A cited claim \[@([^,]+),/.exec(snapshot.body)[1]; + workspace.setBody(workspace.main, `${snapshot.body}\nA worked note.[^example]\n\n[^example]: Footnote evidence [@${citekey}, p. 21].\n`); + }, [...png]); + + const [outcome] = await Promise.all([ + Promise.race([ + page.waitForEvent("download", { timeout: 120_000 }).then(download => ({ download })), + page.getByRole("dialog", { name: "Review export problems", exact: true }).waitFor({ timeout: 120_000 }) + .then(async () => ({ problems: await page.getByRole("dialog", { name: "Review export problems", exact: true }).innerText() })), + ]), + format(page, "Word (DOCX)"), + ]); + assert.ok(outcome.download, outcome.problems); + const path = "out/worked-example.docx"; + await outcome.download.saveAs(path); + const part = name => execFileSync("unzip", ["-p", path, name]); + const relationships = part("word/_rels/document.xml.rels").toString(); + const image = /relationships\/image" Id="([^"]+)" Target="(media\/[^"]+\.png)"/.exec(relationships); + assert.ok(image, "document contains an image relationship"); + const doc = part("word/document.xml").toString(); + assert.ok(doc.includes(`r:embed="${image[1]}"`)); + assert.deepEqual(part(`word/${image[2]}`), png); + assert.match(doc, /w:footnoteReference/); + assert.match(doc, /Bibliography/); + const footnotes = part("word/footnotes.xml").toString(); + assert.match(footnotes, /Footnote evidence/); + assert.match(footnotes, /21/); + assert.match(footnotes, / { + const records = new Map(); + const library = new Map(); + const main = "manuscripts/main.md"; + const filePaths = new Set(); + for (let i = 0; i < 5_000; i++) { + const id = `source${i}`; + library.set(id, { id, type: "book", title: `Source ${i}` }); + } + const chapters = Array.from({ length: 120 }, (_, chapter) => { + const path = `chapters/chapter-${chapter}.md`; + const sections = Array.from({ length: 24 }, (_, section) => { + const id = `${chapter}-${section}`; + const source = chapter * 24 + section; + return `### Section ${id} {#sec-${id}}\n\n` + + `Evidence [@source${source}] supports the account in [@sec-${id}]. Compare @fig-${chapter}.\n\n` + + `An example remains literal in code: \`@sec-${id}\`.\n`; + }); + const figure = `figure-${chapter}.png`; + filePaths.add(`chapters/figures/${figure}`); + records.set(path, { + path, frontmatter: {}, + body: `## Chapter ${chapter}\n\n![Evidence from chapter ${chapter}](figures/${figure}){#fig-${chapter}}\n\n` + + sections.join("\n"), + }); + return path; + }); + records.set(main, { path: main, frontmatter: { title: "Large manuscript" }, body: "# Introduction\n\n" + chapters.map(path => `![[${path}]]`).join("\n\n") }); + const input = { main, records, filePaths, recordPaths: new Set(records.keys()), library, styles: new Map(), crossReferences: "resolved" as const }; + const samples: number[] = []; + for (let run = 0; run < 24; run++) { + const start = performance.now(); + const output = materialize(input); + const elapsed = performance.now() - start; + if (run >= 4) samples.push(elapsed); + expect(output.problems).toEqual([]); + expect(output.references).toHaveLength(2_880); + expect(output.media.size).toBe(120); + expect(output.markdown).toContain("## 1.120 Chapter 119"); + expect(output.markdown).toContain("[Section 1.120.24](#sec-119-23)"); + expect(output.markdown).toContain("[Figure 120](#fig-119)"); + expect(output.markdown).toContain("`@sec-119-23`"); + } + samples.sort((a, b) => a - b); + const median = (samples[9]! + samples[10]!) / 2; + const p95 = samples[Math.ceil(0.95 * samples.length) - 1]!; + console.log(`Word Markdown assembly: median ${median.toFixed(2)} ms, p95 ${p95.toFixed(2)} ms (${samples.length} samples)`); +}); diff --git a/apps/writer/src/editor/Editor.tsx b/apps/writer/src/editor/Editor.tsx index 37f71ac0..96b66b3a 100644 --- a/apps/writer/src/editor/Editor.tsx +++ b/apps/writer/src/editor/Editor.tsx @@ -113,7 +113,7 @@ export const Editor = memo(function Editor({ states, position, onPosition, path, const translatedExtensions = () => [ EditorState.phrases.of(phrases.current), placeholder(t`Start writing. Type / to insert or @ to cite.`), - EditorView.contentAttributes.of({ "aria-label": t`Markdown for ${path}`, spellcheck: "true", autocapitalize: "sentences" }), + EditorView.contentAttributes.of({ "aria-label": t`Markdown for ${path}`, tabindex: "0", spellcheck: "true", autocapitalize: "sentences" }), ]; const host = useRef(null); const view = useRef(null); diff --git a/apps/writer/src/editor/language.ts b/apps/writer/src/editor/language.ts index 9392577d..89a47405 100644 --- a/apps/writer/src/editor/language.ts +++ b/apps/writer/src/editor/language.ts @@ -38,7 +38,7 @@ const style = HighlightStyle.define([ { tag: t.emphasis, fontStyle: "italic" }, { tag: t.strong, fontWeight: "700" }, { tag: t.strikethrough, textDecoration: "line-through" }, - { tag: [t.processingInstruction, t.meta, t.contentSeparator], color: "var(--faint)" }, + { tag: [t.processingInstruction, t.meta, t.contentSeparator], color: "var(--muted)" }, { tag: [t.link, t.url], color: "var(--accent)" }, { tag: t.monospace, fontFamily: "var(--mono)", fontSize: "0.9em" }, { tag: t.quote, color: "var(--ink-soft)" }, diff --git a/apps/writer/src/export/pandoc.node.test.ts b/apps/writer/src/export/pandoc.node.test.ts index 7a2182c4..37015ef3 100644 --- a/apps/writer/src/export/pandoc.node.test.ts +++ b/apps/writer/src/export/pandoc.node.test.ts @@ -6,6 +6,7 @@ import { resolve } from "node:path"; import { materialize, splitFrontmatter, type CslItem, type WriterRecord } from "@mdbase-writer/core"; import { STYLES } from "@mdbase-writer/core/styles"; import { describe, expect, it } from "vitest"; +import { pandocWarnings } from "./warnings.js"; const root = resolve(import.meta.dirname, "../.."); const csl = resolve(root, "../../packages/core/assets/csl"); @@ -16,13 +17,24 @@ describe("Word export", () => { const pandoc = await createPandocInstance(readFileSync(resolve(root, "node_modules/pandoc-wasm/src/pandoc.wasm")).buffer as ArrayBuffer); const text = readFileSync(resolve(root, "demo/manuscripts/slow-change.md"), "utf8"); const record: WriterRecord = { path: "manuscripts/slow-change.md", ...splitFrontmatter(text) }; + const chapter: WriterRecord = { + path: "chapters/evidence.md", + frontmatter: {}, + body: "# An inserted chapter\n\n![Site photo](){#fig-site}\n", + }; + const photoPath = "chapters/figures/à reef (west).png"; + const photo = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==", "base64"); + const records = new Map([ + [record.path, { ...record, body: `${record.body}\n\n![[${chapter.path}]]\n` }], + [chapter.path, chapter], + ]); const library = new Map((JSON.parse(readFileSync(resolve(root, "demo/library.json"), "utf8")) as CslItem[]).map((i) => [i.id, i])); const styles = new Map(STYLES.map((s) => [s.id, readFileSync(resolve(csl, `${s.id}.csl`), "utf8")])); const out = materialize({ main: record.path, - records: new Map([[record.path, record]]), - recordPaths: new Set([record.path]), - filePaths: new Set(["manuscripts/figures/reef-stages.svg"]), + records, + recordPaths: new Set(records.keys()), + filePaths: new Set(["manuscripts/figures/reef-stages.svg", photoPath]), library, styles, crossReferences: "resolved", @@ -32,7 +44,10 @@ describe("Word export", () => { "style.csl": out.styleXml, "reference.docx": new Blob([readFileSync(resolve(root, "public/docx/article.docx"))]), }; - for (const [from, to] of out.media) files[to] = new Blob([readFileSync(resolve(root, "demo", from))]); + expect(out.problems).toEqual([]); + for (const [from, to] of out.media) { + files[to] = new Blob([from === photoPath ? photo : readFileSync(resolve(root, "demo", from))]); + } const result = await pandoc.convert( { from: "markdown", to: "docx", "output-file": "m.docx", standalone: true, citeproc: true, "reference-doc": "reference.docx", "resource-path": ["."] }, out.markdown, @@ -41,8 +56,19 @@ describe("Word export", () => { const docx = result.files["m.docx"]; expect(result.stderr).toBe(""); expect(docx).toBeDefined(); - // Read it back to plain text with the same Pandoc. - const plain = await pandoc.convert({ from: "docx", to: "plain", standalone: true, "input-files": ["m.docx"] }, null, { "m.docx": docx as Blob }); + // Pandoc embeds the SVG but cannot invoke the external fallback rasterizer + // in WASM. PNG must embed without warnings. + expect(pandocWarnings(result.warnings)).toEqual([expect.stringMatching(/^Could not convert image .*reef-stages\.svg:/)]); + const plain = await pandoc.convert( + { from: "docx", to: "plain", standalone: true, "input-files": ["m.docx"], "extract-media": "extracted" }, + null, + { "m.docx": docx as Blob }, + ); + const extracted = Object.entries(plain.files).filter(([path]) => path.startsWith("extracted/media/")); + const png = extracted.find(([path]) => path.endsWith(".png"))?.[1]; + expect(png).toBeDefined(); + expect(Buffer.from(await png!.arrayBuffer())).toEqual(photo); + expect(extracted.some(([path]) => path.endsWith(".svg"))).toBe(true); expect(plain.stdout).toContain("Small Agents, Large Effects"); expect(plain.stdout).toMatch(/Section \d/); expect(plain.stdout).not.toMatch(/\(sec-[\w-]+\?\)/); diff --git a/apps/writer/src/styles.css b/apps/writer/src/styles.css index 89019742..9bd3abe8 100644 --- a/apps/writer/src/styles.css +++ b/apps/writer/src/styles.css @@ -272,9 +272,9 @@ kbd { font-family: var(--mono); font-size: 11.5px; padding: 1px 5px; border: 1px .note-list > li.muted { padding: 0.35rem 0.55rem; } .note-option { display: flex; align-items: baseline; gap: 0.6rem; width: 100%; text-align: left; padding: 0.35rem 0.55rem; border: 0; border-radius: 4px; background: none; cursor: pointer; } .note-option:hover { background: var(--subtle); } -[aria-selected="true"] > .note-option { background: var(--selected); font-weight: 700; } +.note-option[aria-pressed="true"] { background: var(--selected); font-weight: 700; } .note-name { font-size: 13px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.note-folder { margin-left: auto; flex: none; font-family: var(--mono); font-size: 11px; color: var(--faint); } +.note-folder { margin-left: auto; flex: none; font-family: var(--mono); font-size: 11px; color: var(--muted); } .new-dialog .mdbase-dialog-body > p { margin: -0.5rem 0 0; } .new-dialog .mdbase-dialog-body > p.adopt-offer { margin: 0; } .new-manuscript .field-problem { display: block; margin-top: 0.3rem; } @@ -315,6 +315,12 @@ kbd { font-family: var(--mono); font-size: 11.5px; padding: 1px 5px; border: 1px .sidebar-tabs button:focus-visible { outline-offset: -2px; } .tab-count { font-size: 11px; font-weight: 400; color: var(--muted); font-variant-numeric: tabular-nums; } .sidebar-panel { min-height: 0; overflow: auto; padding: 0.5rem 0.5rem 1.5rem; scrollbar-gutter: stable; } +/* Keep the active heading and keyboard-focused rows clear of the sticky search. */ +.sidebar-panel:has(> .manuscript-search) { scroll-padding-top: 3rem; } +@media (pointer: coarse) { + .sidebar-panel:has(> .manuscript-search) { scroll-padding-top: 3.75rem; } + .outline button.heading-row { align-items: center; min-height: 44px; } +} /* A second panel beneath the first, with its own small tabs. */ .outline.has-lower { --lower-duration: 160ms; grid-template-rows: auto minmax(0, var(--sidebar-split, .5fr)) 7px minmax(0, var(--sidebar-lower, .5fr)); } .lower-resizer { grid-row: 3; cursor: row-resize; touch-action: none; border-block: 1px solid var(--line); } @@ -405,7 +411,7 @@ kbd { font-family: var(--mono); font-size: 11.5px; padding: 1px 5px; border: 1px .heading-problem { flex: none; width: 6px; height: 6px; border-radius: 50%; background: var(--danger); opacity: 0.8; } .record-line { display: flex; align-items: stretch; } .record-line > .record-row { flex: 1; min-width: 0; } -.record-fold { flex: none; width: 22px; border: 0; background: none; color: var(--faint); cursor: pointer; border-radius: 4px; } +.record-fold { flex: none; width: 22px; border: 0; background: none; color: var(--muted); cursor: pointer; border-radius: 4px; } .record-fold .icon { width: 12px; height: 12px; transition: transform var(--motion-quick) ease; } .record-fold[aria-expanded="true"] .icon { transform: rotate(90deg); } .record-fold:hover { color: var(--ink); background: var(--subtle); } @@ -582,7 +588,7 @@ kbd { font-family: var(--mono); font-size: 11.5px; padding: 1px 5px; border: 1px .editor .cm-chapter-card { display: flex; align-items: center; gap: 0.75rem; margin: 0.25rem 0; padding: 0.6rem 0.6rem 0.6rem 0.8rem; border: 1px solid var(--line); border-radius: var(--control-radius); background: var(--surface); font-family: var(--sans); cursor: text; } .editor .cm-chapter-card:hover { border-color: var(--line-strong); } .editor .cm-chapter-card.is-missing { border-color: var(--color-warning-border); background: var(--color-warning-surface); } -.cm-chapter-number { flex: none; min-width: 1.4rem; font-size: 12px; color: var(--faint); font-variant-numeric: tabular-nums; } +.cm-chapter-number { flex: none; min-width: 1.4rem; font-size: 12px; color: var(--muted); font-variant-numeric: tabular-nums; } .cm-chapter-text { flex: 1; min-width: 0; display: grid; } .cm-chapter-title { font-size: 15px; font-weight: 700; line-height: 1.35; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .cm-chapter-meta { font-size: 12px; line-height: 1.4; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } @@ -610,7 +616,7 @@ kbd { font-family: var(--mono); font-size: 11.5px; padding: 1px 5px; border: 1px .cm-ref-tip { max-width: 26rem; padding: 0.5rem 0.7rem; display: grid; gap: 0.25rem; font-family: var(--sans); font-size: 13px; line-height: 1.45; } .cm-ref-kind { font-size: 10.5px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; color: var(--muted); } .cm-ref-body { color: var(--ink); } -.cm-ref-hint { font-size: 11px; color: var(--faint); } +.cm-ref-hint { font-size: 11px; color: var(--muted); } /* Live preview: the editor reads like the manuscript until the cursor is on a line (live-preview.ts). */ .cm-lp-chip { display: inline-block; max-width: 24em; margin: 0; padding: 0 0.2em; border-radius: 4px; vertical-align: -0.2em; font-size: 0.88em; line-height: 1.35; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: text; } @@ -620,7 +626,7 @@ kbd { font-family: var(--mono); font-size: 11.5px; padding: 1px 5px; border: 1px .cm-lp-chip.is-ref { color: var(--ink-soft); background: var(--subtle); padding-inline: 0.12em; } .cm-lp-chip.is-label { color: var(--muted); background: var(--subtle); font-family: var(--mono); font-size: 0.72em; letter-spacing: -0.01em; vertical-align: 0.1em; } .cm-lp-link { color: var(--accent); text-decoration: underline; text-decoration-color: color-mix(in oklch, var(--accent) 45%, transparent); text-underline-offset: 2px; } -.cm-lp-quiet { color: var(--faint); } +.cm-lp-quiet { color: var(--muted); } .cm-lp-fn-ref { color: var(--accent); font-size: 0.72em; font-weight: 700; line-height: 0; cursor: text; } .cm-lp-fn-number { color: var(--muted); font-size: 0.85em; font-variant-numeric: tabular-nums; margin-right: 0.35em; } /* Muted falls under 4.5:1 on a comment's highlight; match the footnote's own text there. */ @@ -735,7 +741,7 @@ fieldset.settings { margin: 0; padding: 0; border: 0; min-width: 0; } .pane-tabs button[aria-pressed="true"] { color: var(--ink); font-weight: 700; } .pane-tabs button[aria-pressed="true"] .icon { color: var(--app-writer); } .pane-tab-icon { position: relative; display: inline-grid; } - .tab-badge { position: absolute; top: -5px; left: 13px; min-width: 16px; height: 16px; padding: 0 4px; border-radius: 8px; font-size: 10px; font-weight: 700; line-height: 16px; text-align: center; color: #fff; background: var(--warning); } + .tab-badge { position: absolute; top: -5px; left: 13px; min-width: 16px; height: 16px; padding: 0 4px; border-radius: 8px; font-size: 10px; font-weight: 700; line-height: 16px; text-align: center; color: var(--color-on-accent); background: var(--color-warning-strong); } .tab-badge.tone-danger { background: var(--danger); } .tab-badge.tone-comments { background: var(--accent); } .sidebar-rail { display: none; } diff --git a/apps/writer/src/ui/Home.tsx b/apps/writer/src/ui/Home.tsx index d0f333cc..1b7a966c 100644 --- a/apps/writer/src/ui/Home.tsx +++ b/apps/writer/src/ui/Home.tsx @@ -641,17 +641,17 @@ function NotePicker({ notes, value, onChange }: { notes: readonly string[]; valu
{notes.length === 0 ? (

No other notes in this collection.

) : ( -
    +
      {matches.map((p) => { const folder = p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : ""; return ( -
    • - diff --git a/apps/writer/src/ui/WorkspaceView.tsx b/apps/writer/src/ui/WorkspaceView.tsx index 01f414ee..e6b24265 100644 --- a/apps/writer/src/ui/WorkspaceView.tsx +++ b/apps/writer/src/ui/WorkspaceView.tsx @@ -1609,6 +1609,7 @@ function ExportMenu(props: { open: boolean; setOpen(open: boolean): void; busy: disabled={!can[value] || busy} onClick={() => { setOpen(false); + trigger.current?.focus(); onExport(value); }} > diff --git a/packages/core/src/crossref.ts b/packages/core/src/crossref.ts index bc9426e1..41ac77af 100644 --- a/packages/core/src/crossref.ts +++ b/packages/core/src/crossref.ts @@ -10,6 +10,7 @@ import type { SyntaxNode } from "@lezer/common"; import { parseCluster } from "./cite-items.js"; import { CITEKEY, markdownParser } from "./markdown.js"; +import { applyTextEdits, type TextEdit } from "./text-edits.js"; export type CrossRefKind = "section" | "figure" | "table" | "equation"; @@ -38,10 +39,21 @@ export function supplement(kind: CrossRefKind, lang: string): string { const ATTRS = /\{([^{}]*)\}\s*$/; const idOf = (attrs: string | undefined) => (attrs ? /(?:^|\s)#([\p{L}\p{N}_:.-]+)/u.exec(attrs)?.[1] : undefined); +/** Call with match offsets in document order, as produced by matchAll. */ +function overlapScan(ranges: [number, number][]) { + ranges.sort(([a], [b]) => a - b); + let index = 0; + return (from: number, to: number) => { + let next = ranges[index]; + while (next && next[1] <= from) next = ranges[++index]; + return next !== undefined && next[0] < to; + }; +} + /** Numbers every labelled target, and rewrites captions and equations to show their numbers. */ export function resolveCrossReferences(markdown: string, lang: string): { markdown: string; targets: Map } { const targets = new Map(); - const edits: { from: number; to: number; text: string }[] = []; + const edits: TextEdit[] = []; const skip: [number, number][] = []; const sections: number[] = []; let figures = 0; @@ -119,36 +131,37 @@ export function resolveCrossReferences(markdown: string, lang: string): { markdo return t ? `[${supplement(t.kind, lang)} ${t.number}](#${key})` : undefined; }; // References: bracketed clusters made only of labels, then bare @label. - // Footnote definitions keep their inline text unparsed, so this works on - // the text, skipping code and math. - const skipped = (from: number, to: number) => skip.some(([a, b]) => from < b && to > a) || edits.some((e) => e.to > e.from && from < e.to && to > e.from); + // Scan the text so references inside footnotes are included. Protected + // ranges keep code, math and content already being rewritten intact. + for (const { from, to } of edits) if (to > from) skip.push([from, to]); + const overlapsBlock = overlapScan(skip); + const clusters: [number, number][] = []; const cluster = new RegExp(`\\[([^\\[\\]]*?@${CITEKEY.source}[^\\[\\]]*)\\](?![({])`, "gu"); for (const m of markdown.matchAll(cluster)) { const from = m.index ?? 0; const to = from + m[0].length; - if (skipped(from, to)) continue; + if (overlapsBlock(from, to)) continue; const items = parseCluster(m[1] ?? ""); - if (!items.length || !items.every((i) => targets.has(i.key))) { - skip.push([from, to]); // a citation (or a mixed cluster, an error the preview reports): leave it whole - continue; - } + // Keep a citation (or mixed cluster) whole and avoid rewriting a resolved + // cluster again in the bare-reference pass. + clusters.push([from, to]); + if (!items.length || !items.every((i) => targets.has(i.key))) continue; edits.push({ from, to, text: items.map((i) => `${i.prefix ? `${i.prefix} ` : ""}${reference(i.key)}${i.suffix}`).join(", "), }); } + const overlapsProtected = overlapScan([...skip, ...clusters]); const bare = new RegExp(`(^|[^\\p{L}\\p{N}_@\\[-])@(${CITEKEY.source})`, "gu"); for (const m of markdown.matchAll(bare)) { const from = (m.index ?? 0) + (m[1]?.length ?? 0); const key = m[2] ?? ""; const to = from + 1 + key.length; const link = reference(key); - if (!link || skipped(from, to)) continue; + if (!link || overlapsProtected(from, to)) continue; edits.push({ from, to, text: link }); } - let out = markdown; - for (const e of edits.sort((a, b) => b.from - a.from)) out = out.slice(0, e.from) + e.text + out.slice(e.to); - return { markdown: out, targets }; + return { markdown: applyTextEdits(markdown, edits), targets }; } diff --git a/packages/core/src/materialize.ts b/packages/core/src/materialize.ts index 4bca24bf..48760473 100644 --- a/packages/core/src/materialize.ts +++ b/packages/core/src/materialize.ts @@ -12,6 +12,7 @@ import { resolveCrossReferences } from "./crossref.js"; import { manuscriptMeta } from "./meta.js"; import type { CslItem } from "./citeproc.js"; import { CITEKEY, markdownParser } from "./markdown.js"; +import { applyTextEdits, type TextEdit } from "./text-edits.js"; import { IMAGE_EXTENSION, missingImageMessage, resolveLinkTarget, type WriterRecord } from "./records.js"; export interface MaterializeInput { @@ -64,7 +65,9 @@ export function materialize(input: MaterializeInput): MaterializedManuscript { const mediaPath = (collectionPath: string) => { const bundled = `${BUNDLE_MEDIA}/${collectionPath}`; media.set(collectionPath, bundled); - return bundled; + // Markdown destinations need URL escaping; the bundle retains the actual + // collection filename so Pandoc can open the decoded path. + return encodeURI(bundled).replace(/[()#?]/g, char => `%${char.charCodeAt(0).toString(16)}`); }; const expand = (path: string, stack: readonly string[]): string => { @@ -74,7 +77,7 @@ export function materialize(input: MaterializeInput): MaterializedManuscript { return ""; } const body = record.body; - const edits: { from: number; to: number; text: string }[] = []; + const edits: TextEdit[] = []; const visit = (node: SyntaxNode) => { switch (node.name) { case "EmbedBlock": { @@ -125,9 +128,7 @@ export function materialize(input: MaterializeInput): MaterializedManuscript { // inline content the block parser leaves unparsed). A stray match only // adds an unused entry to the bibliography file. for (const m of body.matchAll(CITED_KEY)) if (m[1] && input.library.has(m[1])) cited.add(m[1]); - let out = body; - for (const e of edits.sort((a, b) => b.from - a.from)) out = out.slice(0, e.from) + e.text + out.slice(e.to); - return out; + return applyTextEdits(body, edits); }; const main = input.records.get(input.main); diff --git a/packages/core/src/text-edits.ts b/packages/core/src/text-edits.ts new file mode 100644 index 00000000..9a02ff94 --- /dev/null +++ b/packages/core/src/text-edits.ts @@ -0,0 +1,19 @@ +export interface TextEdit { + readonly from: number; + readonly to: number; + readonly text: string; +} + +/** Assemble disjoint replacements and insertions without recopying the document for each edit. */ +export function applyTextEdits(text: string, edits: TextEdit[]): string { + if (!edits.length) return text; + const parts: string[] = []; + let cursor = 0; + // A heading number and a reference can start at the same offset. + for (const edit of edits.sort((a, b) => a.from - b.from || a.to - b.to)) { + parts.push(text.slice(cursor, edit.from), edit.text); + cursor = edit.to; + } + parts.push(text.slice(cursor)); + return parts.join(""); +} diff --git a/packages/core/test/crossref.test.ts b/packages/core/test/crossref.test.ts index 9cd6e601..037927c1 100644 --- a/packages/core/test/crossref.test.ts +++ b/packages/core/test/crossref.test.ts @@ -65,3 +65,13 @@ describe("resolveCrossReferences", () => { expect(resolveCrossReferences(doc, "de-DE").markdown).toContain("See [Abbildung 1](#fig-site)"); }); }); + +it("numbers headings that begin with a reference and preserves mixed citations and code", () => { + const { markdown } = resolveCrossReferences( + "# First {#sec-first}\n\n## [@sec-first]\n\n\`[@sec-first]\` and [@sec-first; @writer2020]. Then @sec-first.\n", + "en", + ); + expect(markdown).toBe( + "# 1 First {#sec-first}\n\n## 1.1 [Section 1](#sec-first)\n\n\`[@sec-first]\` and [@sec-first; @writer2020]. Then [Section 1](#sec-first).\n", + ); +}); diff --git a/patches/pandoc-wasm@1.1.0.patch b/patches/pandoc-wasm@1.1.0.patch new file mode 100644 index 00000000..7c9c8d53 --- /dev/null +++ b/patches/pandoc-wasm@1.1.0.patch @@ -0,0 +1,27 @@ +diff --git a/src/core.js b/src/core.js +index 23e0eaee4522fe7f6650e4b8399e69f85383a266..d0856636f5f338e23ba456cfc9072079b33cae97 100644 +--- a/src/core.js ++++ b/src/core.js +@@ -74,7 +74,21 @@ export function createPandocInstance(wasmBinary) { + uint8Array = new Uint8Array(buffer) + } + const file = new File(uint8Array, {readonly: readonly}) +- fileSystem.set(filename, file) ++ // WASI resolves path components by walking Directory entries. ++ const parts = filename.split("/") ++ const basename = parts.pop() ++ let directory = fileSystem ++ for (const part of parts) { ++ if (!part || part === ".") continue ++ let child = directory.get(part) ++ if (!child) { ++ child = new Directory(new Map()) ++ directory.set(part, child) ++ } ++ if (!(child instanceof Directory)) throw new Error(`Invalid file path: ${filename}`) ++ directory = child.contents ++ } ++ directory.set(basename, file) + } + + // Main API: query function diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e85f3897..4fbb5420 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,6 +6,7 @@ settings: patchedDependencies: citeproc: f7e3d4ceb169ed26f620629251d1c4f625551c8e9355526267e43a91fc27a73e + pandoc-wasm@1.1.0: 1ba3916b68987e69c14b1c65ba8d94079ad9da27f633d26e79b132c59f222b87 importers: @@ -94,7 +95,7 @@ importers: version: 2.1.10(react-dom@19.3.0(react@19.3.0))(react@19.3.0) pandoc-wasm: specifier: 1.1.0 - version: 1.1.0 + version: 1.1.0(patch_hash=1ba3916b68987e69c14b1c65ba8d94079ad9da27f633d26e79b132c59f222b87) react: specifier: ^19.2.8 version: 19.3.0 @@ -2837,7 +2838,7 @@ snapshots: stdin-discarder: 0.3.2 string-width: 8.3.0 - pandoc-wasm@1.1.0: + pandoc-wasm@1.1.0(patch_hash=1ba3916b68987e69c14b1c65ba8d94079ad9da27f633d26e79b132c59f222b87): dependencies: '@bjorn3/browser_wasi_shim': 0.4.2 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index d24f152f..03fe07cd 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -13,3 +13,4 @@ onlyBuiltDependencies: patchedDependencies: citeproc: patches/citeproc.patch + pandoc-wasm@1.1.0: patches/pandoc-wasm@1.1.0.patch