Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions ui-packages/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
109 changes: 109 additions & 0 deletions ui-packages/web/src/core/docx-unconverted.test.ts
Original file line number Diff line number Diff line change
@@ -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) =>
`<Relationship Id="${id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="${target}"/>`

// 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',
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/></Types>',
)
zip.file(
'_rels/.rels',
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${relationship('rId1', 'officeDocument', 'word/document.xml')}</Relationships>`,
)
zip.file(
'word/_rels/document.xml.rels',
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${relationship('rIdS', 'styles', 'styles.xml')}${relationship('rIdC', 'comments', 'comments.xml')}</Relationships>`,
)
zip.file(
'word/styles.xml',
`<w:styles ${namespaces}><w:style w:type="paragraph" w:styleId="BodyText"><w:name w:val="Body Text"/></w:style></w:styles>`,
)
zip.file(
'word/comments.xml',
`<w:comments ${namespaces}><w:comment w:id="0" w:author="Reviewer"><w:p><w:r><w:t>Check this figure</w:t></w:r></w:p></w:comment></w:comments>`,
)
zip.file('word/document.xml', `<w:document ${namespaces}><w:body>${body}</w:body></w:document>`)
return new Blob([await zip.generateAsync({ type: 'arraybuffer' })])
}

const paragraph = (text: string) => `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`
const drawing = (uri: string, data: string) =>
`<w:drawing><wp:inline><wp:docPr id="1" name="Shape"/><a:graphic><a:graphicData uri="${uri}">${data}</a:graphicData></a:graphic></wp:inline></w:drawing>`
const chart = drawing(
'http://schemas.openxmlformats.org/drawingml/2006/chart',
'<c:chart r:id="rIdX"/>',
)
const diagram = drawing(
'http://schemas.openxmlformats.org/drawingml/2006/diagram',
'<dgm:relIds r:dm="rIdX" r:lo="rIdX" r:qs="rIdX" r:cs="rIdX"/>',
)

describe('unconverted Word content', () => {
it('leaves a document whose content all converts exactly as it was', async () => {
const { markdown } = await convertDocxToMarkdown(
await docx(
'<w:p><w:pPr><w:pStyle w:val="BodyText"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>Styled body</w:t></w:r></w:p>',
),
)
expect(markdown).toBe('**Styled body**')
})

it('marks equations, charts and diagrams where they stood', async () => {
const { markdown } = await convertDocxToMarkdown(
await docx(
[
paragraph('Before'),
'<w:p><m:oMathPara><m:oMath><m:r><m:t>E=mc2</m:t></m:r></m:oMath></m:oMathPara></w:p>',
'<w:p><w:r><w:t xml:space="preserve">Inline </w:t></w:r><m:oMath><m:r><m:t>x</m:t></m:r></m:oMath></w:p>',
`<w:p><w:r>${chart}</w:r></w:p>`,
`<w:p><w:r>${diagram}</w:r></w:p>`,
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(
`<w:p><w:r><mc:AlternateContent><mc:Choice Requires="c14">${chart}</mc:Choice><mc:Fallback><w:t>Chart as text</w:t></mc:Fallback></mc:AlternateContent></w:r></w:p>`,
),
)
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(
'<w:p><w:r><w:t>Commented text</w:t></w:r><w:r><w:commentReference w:id="0"/></w:r></w:p>',
),
)
expect(markdown).toBe('Commented text(1)\n\nComment (1)\n\nCheck this figure')
})
})
98 changes: 98 additions & 0 deletions ui-packages/web/src/core/docx-unconverted.ts
Original file line number Diff line number Diff line change
@@ -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<ArrayBuffer> => {
// 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' })
}
33 changes: 25 additions & 8 deletions ui-packages/web/src/core/docx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<DocxConversion> => {
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<string, Blob>()
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)
Expand All @@ -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',
Expand Down