From e1a2e8eb892da018f1fd5c88503f42e9ca42bbc9 Mon Sep 17 00:00:00 2001 From: Qijun Date: Fri, 2 Oct 2026 00:17:18 -0700 Subject: [PATCH] feat: mark Word content that does not convert where it stood Mammoth drops equations, charts, SmartArt and bare embedded objects, often without a warning, so readers and the assistant took the converted text for the whole document. Before conversion, those elements are now replaced in document.xml with an italic marker such as (Equation not converted). Comments are kept and listed at the end. Documents with none of these pass through unchanged. --- pnpm-lock.yaml | 3 + ui-packages/web/package.json | 1 + .../web/src/core/docx-unconverted.test.ts | 109 ++++++++++++++++++ ui-packages/web/src/core/docx-unconverted.ts | 98 ++++++++++++++++ ui-packages/web/src/core/docx.ts | 33 ++++-- 5 files changed, 236 insertions(+), 8 deletions(-) create mode 100644 ui-packages/web/src/core/docx-unconverted.test.ts create mode 100644 ui-packages/web/src/core/docx-unconverted.ts diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 204454c..b6d2d7e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -166,6 +166,9 @@ importers: idb: specifier: ^8.0.3 version: 8.0.3 + jszip: + specifier: ^3.10.2 + version: 3.10.2 katex: specifier: ^0.18.7 version: 0.18.7 diff --git a/ui-packages/web/package.json b/ui-packages/web/package.json index d2eb619..acba874 100644 --- a/ui-packages/web/package.json +++ b/ui-packages/web/package.json @@ -26,6 +26,7 @@ "codemirror": "^6.0.2", "highlight.js": "^11.12.0", "idb": "^8.0.3", + "jszip": "^3.10.2", "katex": "^0.18.7", "lowlight": "^3.3.0", "lucide-react": "^1.46.0", diff --git a/ui-packages/web/src/core/docx-unconverted.test.ts b/ui-packages/web/src/core/docx-unconverted.test.ts new file mode 100644 index 0000000..0e1a502 --- /dev/null +++ b/ui-packages/web/src/core/docx-unconverted.test.ts @@ -0,0 +1,109 @@ +import JSZip from 'jszip' +import { describe, expect, it } from 'vitest' +import { convertDocxToMarkdown } from './docx' + +const namespaces = [ + 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"', + 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"', + 'xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"', + 'xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"', + 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"', + 'xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"', + 'xmlns:dgm="http://schemas.openxmlformats.org/drawingml/2006/diagram"', + 'xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"', + 'xmlns:v="urn:schemas-microsoft-com:vml"', +].join(' ') + +const relationship = (id: string, type: string, target: string) => + `` + +// A minimal package Mammoth accepts: the body, its styles, and the comments it may cite. +const docx = async (body: string) => { + const zip = new JSZip() + zip.file( + '[Content_Types].xml', + '', + ) + zip.file( + '_rels/.rels', + `${relationship('rId1', 'officeDocument', 'word/document.xml')}`, + ) + zip.file( + 'word/_rels/document.xml.rels', + `${relationship('rIdS', 'styles', 'styles.xml')}${relationship('rIdC', 'comments', 'comments.xml')}`, + ) + zip.file( + 'word/styles.xml', + ``, + ) + zip.file( + 'word/comments.xml', + `Check this figure`, + ) + zip.file('word/document.xml', `${body}`) + return new Blob([await zip.generateAsync({ type: 'arraybuffer' })]) +} + +const paragraph = (text: string) => `${text}` +const drawing = (uri: string, data: string) => + `${data}` +const chart = drawing( + 'http://schemas.openxmlformats.org/drawingml/2006/chart', + '', +) +const diagram = drawing( + 'http://schemas.openxmlformats.org/drawingml/2006/diagram', + '', +) + +describe('unconverted Word content', () => { + it('leaves a document whose content all converts exactly as it was', async () => { + const { markdown } = await convertDocxToMarkdown( + await docx( + 'Styled body', + ), + ) + expect(markdown).toBe('**Styled body**') + }) + + it('marks equations, charts and diagrams where they stood', async () => { + const { markdown } = await convertDocxToMarkdown( + await docx( + [ + paragraph('Before'), + 'E=mc2', + 'Inline x', + `${chart}`, + `${diagram}`, + paragraph('After'), + ].join(''), + ), + ) + expect(markdown.split('\n\n')).toEqual([ + 'Before', + '*(Equation not converted)*', + 'Inline *(Equation not converted)*', + '*(Chart not converted)*', + '*(Diagram not converted)*', + 'After', + ]) + }) + + it('trusts the fallback Word shows instead of marking the alternative it skips', async () => { + const { markdown } = await convertDocxToMarkdown( + await docx( + `${chart}Chart as text`, + ), + ) + expect(markdown).toBe('Chart as text') + }) + + it('keeps comments, listed after the text they annotate, without dead links', async () => { + const { markdown } = await convertDocxToMarkdown( + await docx( + 'Commented text', + ), + ) + expect(markdown).toBe('Commented text(1)\n\nComment (1)\n\nCheck this figure') + }) +}) diff --git a/ui-packages/web/src/core/docx-unconverted.ts b/ui-packages/web/src/core/docx-unconverted.ts new file mode 100644 index 0000000..34203c9 --- /dev/null +++ b/ui-packages/web/src/core/docx-unconverted.ts @@ -0,0 +1,98 @@ +import JSZip from 'jszip' + +const namespaces = { + w: 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', + m: 'http://schemas.openxmlformats.org/officeDocument/2006/math', + c: 'http://schemas.openxmlformats.org/drawingml/2006/chart', + dgm: 'http://schemas.openxmlformats.org/drawingml/2006/diagram', + mc: 'http://schemas.openxmlformats.org/markup-compatibility/2006', + v: 'urn:schemas-microsoft-com:vml', +} +const documentPath = 'word/document.xml' + +const elements = (root: Document | Element, namespace: string, name: string) => + Array.from(root.getElementsByTagNameNS(namespace, name)) + +const contains = (element: Element, namespace: string, name: string) => + element.getElementsByTagNameNS(namespace, name).length > 0 + +// Mammoth reads only mc:Fallback, so nothing under mc:Choice is shown to begin with. +const insideChoice = (element: Element) => { + for (let parent = element.parentElement; parent; parent = parent.parentElement) + if (parent.namespaceURI === namespaces.mc && parent.localName === 'Choice') return true + return false +} + +// Italic and in parentheses: square brackets would come out of Markdown escaping as \[…\], +// which the reader renders as display math. +const marker = (document: Document, label: string) => { + const run = document.createElementNS(namespaces.w, 'w:r') + const properties = document.createElementNS(namespaces.w, 'w:rPr') + properties.append(document.createElementNS(namespaces.w, 'w:i')) + const text = document.createElementNS(namespaces.w, 'w:t') + text.textContent = `(${label} not converted)` + run.append(properties, text) + return run +} + +// Drawings and objects sit inside a run, which cannot hold another run, so the marker follows it. +const markInPlace = (target: Element, label: string) => { + const run = target.parentElement + const document = target.ownerDocument + if (run?.namespaceURI === namespaces.w && run.localName === 'r') { + run.after(marker(document, label)) + target.remove() + } else target.replaceWith(marker(document, label)) +} + +// Each rule names content Mammoth drops without trace; styles and anything it keeps stay out. +const markEquations = (document: Document) => { + const paragraphs = elements(document, namespaces.m, 'oMathPara').filter( + math => !insideChoice(math), + ) + for (const math of paragraphs) markInPlace(math, 'Equation') + const inline = elements(document, namespaces.m, 'oMath').filter(math => !insideChoice(math)) + for (const math of inline) markInPlace(math, 'Equation') + return paragraphs.length + inline.length +} + +const drawingLabel = (drawing: Element) => { + if (contains(drawing, namespaces.c, 'chart')) return 'Chart' + if (contains(drawing, namespaces.dgm, 'relIds')) return 'Diagram' + return null +} + +const markDrawings = (document: Document) => { + const lost = elements(document, namespaces.w, 'drawing') + .filter(drawing => !insideChoice(drawing)) + .flatMap(drawing => { + const label = drawingLabel(drawing) + return label ? [{ drawing, label }] : [] + }) + for (const { drawing, label } of lost) markInPlace(drawing, label) + return lost.length +} + +// An embedded object with a preview image is shown as that image, so only bare ones are lost. +const markObjects = (document: Document) => { + const bare = elements(document, namespaces.w, 'object').filter( + object => !insideChoice(object) && !contains(object, namespaces.v, 'imagedata'), + ) + for (const object of bare) markInPlace(object, 'Embedded object') + return bare.length +} + +/** Puts a visible marker where Mammoth would silently drop content; other documents pass through untouched. */ +export const markUnconvertedContent = async (docx: ArrayBuffer): Promise => { + // Anything that is not a zip package has nothing to mark; Mammoth reports it as it always has. + const [first, second] = new Uint8Array(docx, 0, Math.min(2, docx.byteLength)) + if (first !== 0x50 || second !== 0x4b) return docx + const zip = await JSZip.loadAsync(docx) + const entry = zip.file(documentPath) + if (!entry) return docx + const document = new DOMParser().parseFromString(await entry.async('string'), 'application/xml') + const marked = markEquations(document) + markDrawings(document) + markObjects(document) + if (marked === 0) return docx + zip.file(documentPath, new XMLSerializer().serializeToString(document)) + return zip.generateAsync({ type: 'arraybuffer', compression: 'STORE' }) +} diff --git a/ui-packages/web/src/core/docx.ts b/ui-packages/web/src/core/docx.ts index 8efa1aa..e942651 100644 --- a/ui-packages/web/src/core/docx.ts +++ b/ui-packages/web/src/core/docx.ts @@ -60,23 +60,39 @@ const promoteHeaderRow = (root: Document) => { } } +// Turndown drops the ids these anchors point at, which would leave links that go nowhere: +// a reference keeps its number as text, and the back link to it has nothing left to say. +// Numbers move from [1] to (1) because escaped square brackets render as display math. +const commentNumber = (text: string) => text.replace(/\[(\d+)\]/, '($1)') + +const unlinkComments = (root: Document) => { + for (const back of root.querySelectorAll('a[href^="#comment-ref-"]')) back.remove() + for (const link of root.querySelectorAll('a[href^="#comment-"]')) + link.replaceWith(commentNumber(link.textContent ?? '')) + for (const term of root.querySelectorAll('dt[id^="comment-"]')) + term.textContent = commentNumber(term.textContent ?? '') +} + export const convertDocxToMarkdown = async ( blob: Blob, { images: withImages = true }: DocxConversionOptions = {}, ): Promise => { - const [{ default: mammoth }, { default: TurndownService }, { gfm }] = await Promise.all([ - import('mammoth'), - import('turndown'), - import('turndown-plugin-gfm'), - ]) + const [{ default: mammoth }, { default: TurndownService }, { gfm }, { markUnconvertedContent }] = + await Promise.all([ + import('mammoth'), + import('turndown'), + import('turndown-plugin-gfm'), + import('./docx-unconverted'), + ]) const images = new Map() const { value, messages } = await mammoth.convertToHtml( - { arrayBuffer: await blob.arrayBuffer() }, + { arrayBuffer: await markUnconvertedContent(await blob.arrayBuffer()) }, { // A manual page break is the author separating sections; Mammoth drops it otherwise. - // This is added to the default style map, not a replacement for it. - styleMap: ["br[type='page'] => hr"], + // Comments are dropped unless their references are mapped; Mammoth then lists them at the end. + // These are added to the default style map, not a replacement for it. + styleMap: ["br[type='page'] => hr", 'comment-reference => sup'], convertImage: mammoth.images.imgElement(async image => { if (!withImages) return { src: '' } const reference = imageReference(images.size + 1) @@ -92,6 +108,7 @@ export const convertDocxToMarkdown = async ( const parsed = new DOMParser().parseFromString(value, 'text/html') flattenTableCells(parsed) promoteHeaderRow(parsed) + unlinkComments(parsed) const turndown = new TurndownService({ headingStyle: 'atx',