Initial public release

This commit is contained in:
GenOffice
2026-08-02 19:52:16 +08:00
commit d2fe8ddaae
994 changed files with 348937 additions and 0 deletions
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@genoffice/docx-engine",
"version": "0.1.0",
"license": "Apache-2.0",
"private": true,
"type": "module",
"description": "docx parsing (Block tree with docxIndex anchors), OOXML fragment generation, paragraph-patch save",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"fixtures": "tsx scripts/generate-fixtures.ts"
},
"dependencies": {
"fast-xml-parser": "^5.3.4",
"jszip": "^3.10.1"
},
"devDependencies": {
"@types/node": "^24.10.1",
"tsx": "^4.21.0",
"typescript": "^5.9.3",
"vitest": "^4.1.0"
}
}
@@ -0,0 +1,28 @@
import { mkdirSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { buildDocx, buildKitchenSinkDocx } from '../tests/helpers/build-docx'
const outDir = join(dirname(fileURLToPath(import.meta.url)), '../../../fixtures/generated')
async function main() {
mkdirSync(outDir, { recursive: true })
const kitchenSink = await buildKitchenSinkDocx()
writeFileSync(join(outDir, 'kitchen-sink.docx'), kitchenSink)
const simple = await buildDocx({
bodyXml:
'<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>标题</w:t></w:r></w:p>' +
'<w:p><w:r><w:t>第一段。</w:t></w:r></w:p>' +
'<w:p><w:r><w:t>第二段。</w:t></w:r></w:p>',
})
writeFileSync(join(outDir, 'simple.docx'), simple)
console.log(`fixtures written to ${outDir}`)
}
main().catch((err) => {
console.error(err)
process.exit(1)
})
@@ -0,0 +1,55 @@
/** throwaway: build /tmp/revdemo.docx + /tmp/revdemo-v2.docx for manual review-mode verification */
import { writeFileSync } from 'node:fs'
import { buildDocx } from '../tests/helpers/build-docx'
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const COMMENTS_XML =
XML_DECL +
'<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:comment w:id="1" w:author="Alice" w:initials="A" w:date="2026-07-01T10:00:00Z">' +
'<w:p><w:r><w:t>这个数据需要再核对一下</w:t></w:r></w:p></w:comment>' +
'</w:comments>'
const body = [
'<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>市场调研报告(修订演示)</w:t></w:r></w:p>',
'<w:p><w:r><w:t xml:space="preserve">本季度销量同比增长 </w:t></w:r>' +
'<w:commentRangeStart w:id="1"/><w:r><w:t>23%</w:t></w:r><w:commentRangeEnd w:id="1"/>' +
'<w:r><w:commentReference w:id="1"/></w:r>' +
'<w:r><w:t xml:space="preserve">,超出预期。</w:t></w:r></w:p>',
'<w:p><w:r><w:t xml:space="preserve">市场规模预计达到 </w:t></w:r>' +
'<w:del w:id="12" w:author="Bob" w:date="2026-07-02T08:30:00Z">' +
'<w:r><w:delText>五千亿</w:delText></w:r></w:del>' +
'<w:ins w:id="11" w:author="Alice" w:date="2026-07-01T10:00:00Z">' +
'<w:r><w:t>六千亿</w:t></w:r></w:ins>' +
'<w:r><w:t xml:space="preserve"> 元,竞争格局趋于集中。</w:t></w:r></w:p>',
'<w:p><w:r><w:t>结论:建议加大渠道投入,关注头部厂商动态。</w:t></w:r></w:p>',
].join('')
const bodyV2 = [
'<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>市场调研报告(修订演示)</w:t></w:r></w:p>',
'<w:p><w:r><w:t>本季度销量同比增长 23%,超出预期。</w:t></w:r></w:p>',
'<w:p><w:r><w:t>新增:海外市场开始放量,值得关注。</w:t></w:r></w:p>',
'<w:p><w:r><w:t>结论:建议聚焦高端产品线。</w:t></w:r></w:p>',
].join('')
const main = async () => {
writeFileSync(
'/tmp/revdemo.docx',
await buildDocx({
bodyXml: body,
extraParts: [
{
path: 'word/comments.xml',
xml: COMMENTS_XML,
contentType:
'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml',
},
],
}),
)
writeFileSync('/tmp/revdemo-v2.docx', await buildDocx({ bodyXml: bodyV2 }))
console.log('wrote /tmp/revdemo.docx and /tmp/revdemo-v2.docx')
}
void main()
+196
View File
@@ -0,0 +1,196 @@
import JSZip from 'jszip'
/**
* Blank document template for "new document" and AI from-scratch generation.
*
* The generate layer only references styles / numbering that already exist in
* the package, so a fresh document must ship with the standard set: Normal,
* Heading1-6, ListParagraph, Hyperlink, TOC1-9 (for generated TOC fields),
* plus bullet (numId 1) and decimal (numId 2) numbering definitions.
*/
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const DOC_NS =
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
'xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ' +
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
'xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" ' +
'xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"'
/** numId of the template's bullet list definition */
export const BLANK_BULLET_NUM_ID = '1'
/** numId of the template's ordered (decimal) list definition */
export const BLANK_ORDERED_NUM_ID = '2'
/** TOC entry styles referenced by generateTocFieldXml (indent grows per level) */
function tocStyle(level: number): string {
const ind = level > 1 ? `<w:ind w:left="${220 * (level - 1)}"/>` : ''
return (
`<w:style w:type="paragraph" w:styleId="TOC${level}"><w:name w:val="toc ${level}"/>` +
'<w:basedOn w:val="Normal"/><w:next w:val="Normal"/>' +
`<w:pPr><w:spacing w:after="100"/>${ind}</w:pPr></w:style>`
)
}
function headingStyle(level: number, sizeHalfPoints: number): string {
return (
`<w:style w:type="paragraph" w:styleId="Heading${level}"><w:name w:val="heading ${level}"/>` +
'<w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/>' +
`<w:pPr><w:keepNext/><w:spacing w:before="${level <= 2 ? 240 : 160}" w:after="120"/><w:outlineLvl w:val="${level - 1}"/></w:pPr>` +
`<w:rPr><w:b/><w:sz w:val="${sizeHalfPoints}"/><w:szCs w:val="${sizeHalfPoints}"/></w:rPr></w:style>`
)
}
const stylesXml = (eastAsiaFont?: string): string =>
XML_DECL +
'<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:docDefaults><w:rPrDefault><w:rPr>' +
`<w:rFonts w:ascii="Calibri"${eastAsiaFont ? ` w:eastAsia="${eastAsiaFont}"` : ''} w:hAnsi="Calibri"/><w:sz w:val="22"/><w:szCs w:val="22"/>` +
'</w:rPr></w:rPrDefault>' +
'<w:pPrDefault><w:pPr><w:spacing w:after="120" w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>' +
'<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>' +
headingStyle(1, 32) +
headingStyle(2, 28) +
headingStyle(3, 26) +
headingStyle(4, 24) +
headingStyle(5, 22) +
headingStyle(6, 22) +
'<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/>' +
'<w:pPr><w:ind w:left="720"/><w:contextualSpacing/></w:pPr></w:style>' +
'<w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/>' +
'<w:rPr><w:color w:val="0563C1"/><w:u w:val="single"/></w:rPr></w:style>' +
Array.from({ length: 9 }, (_, i) => tocStyle(i + 1)).join('') +
'</w:styles>'
function bulletLevels(): string {
let xml = ''
for (let ilvl = 0; ilvl < 5; ilvl++) {
xml +=
`<w:lvl w:ilvl="${ilvl}"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="&#61623;"/>` +
`<w:lvlJc w:val="left"/><w:pPr><w:ind w:left="${720 * (ilvl + 1)}" w:hanging="360"/></w:pPr>` +
'<w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol" w:hint="default"/></w:rPr></w:lvl>'
}
return xml
}
function decimalLevels(): string {
let xml = ''
for (let ilvl = 0; ilvl < 5; ilvl++) {
xml +=
`<w:lvl w:ilvl="${ilvl}"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%${ilvl + 1}."/>` +
`<w:lvlJc w:val="left"/><w:pPr><w:ind w:left="${720 * (ilvl + 1)}" w:hanging="360"/></w:pPr></w:lvl>`
}
return xml
}
/** Custom numbering level (one level of a multilevel list / bullet library / numbering library definition) */
export interface CustomNumberingLevel {
/** w:numFmt:decimal/bullet/lowerLetter/upperRoman/chineseCountingThousand… */
numFmt: string
/** w:lvlText: a pattern like "%1." or a literal bullet symbol */
lvlText: string
/** w:ind w:left(twips) */
indentLeft: number
/** w:ind w:hanging (twips, default 360) */
hanging?: number
/** w:start (default 1) */
start?: number
}
const escAttr = (s: string): string =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
function customLevels(levels: CustomNumberingLevel[]): string {
return levels
.map(
(l, ilvl) =>
`<w:lvl w:ilvl="${ilvl}"><w:start w:val="${l.start ?? 1}"/><w:numFmt w:val="${escAttr(l.numFmt)}"/>` +
`<w:lvlText w:val="${escAttr(l.lvlText)}"/><w:lvlJc w:val="left"/>` +
`<w:pPr><w:ind w:left="${Math.round(l.indentLeft)}" w:hanging="${Math.round(l.hanging ?? 360)}"/></w:pPr></w:lvl>`,
)
.join('')
}
/** One abstractNum definition; uses custom levels when provided, otherwise the blank-template style (5 levels) */
export function abstractNumXml(
abstractNumId: string,
kind: 'bullet' | 'ordered',
levels?: CustomNumberingLevel[],
): string {
const body = levels?.length
? customLevels(levels)
: kind === 'bullet'
? bulletLevels()
: decimalLevels()
return `<w:abstractNum w:abstractNumId="${abstractNumId}">${body}</w:abstractNum>`
}
/** The blank template's numbering.xml (bullet numId 1 / decimal numId 2);
* base content used when the document has no such part */
export const BLANK_NUMBERING_XML =
XML_DECL +
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
`<w:abstractNum w:abstractNumId="0">${bulletLevels()}</w:abstractNum>` +
`<w:abstractNum w:abstractNumId="1">${decimalLevels()}</w:abstractNum>` +
`<w:num w:numId="${BLANK_BULLET_NUM_ID}"><w:abstractNumId w:val="0"/></w:num>` +
`<w:num w:numId="${BLANK_ORDERED_NUM_ID}"><w:abstractNumId w:val="1"/></w:num>` +
'</w:numbering>'
const NUMBERING_XML = BLANK_NUMBERING_XML
export interface BlankDocxOptions {
/**
* docDefaults East Asian font (w:eastAsia); pick per UI language so e.g.
* Japanese/Korean users don't start with a Simplified-Chinese face.
* When omitted no w:eastAsia is written — like an en-US Word document,
* Word/our renderer then substitute per script when CJK text appears.
*/
eastAsiaFont?: string
}
/** Build a minimal valid .docx: one empty paragraph, A4 portrait, standard styles. */
export async function buildBlankDocx(options?: BlankDocxOptions): Promise<Uint8Array> {
const zip = new JSZip()
zip.file(
'[Content_Types].xml',
`${XML_DECL}<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"/>' +
'<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>' +
'<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>' +
'<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>' +
'</Types>',
)
zip.file(
'_rels/.rels',
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>' +
'</Relationships>',
)
zip.file(
'word/_rels/document.xml.rels',
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>' +
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>' +
'</Relationships>',
)
zip.file('word/styles.xml', stylesXml(options?.eastAsiaFont))
zip.file('word/numbering.xml', NUMBERING_XML)
const sectPr =
'<w:sectPr><w:pgSz w:w="11906" w:h="16838"/>' +
'<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>' +
'</w:sectPr>'
zip.file(
'word/document.xml',
`${XML_DECL}<w:document ${DOC_NS}><w:body><w:p/>${sectPr}</w:body></w:document>`,
)
return zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' })
}
+519
View File
@@ -0,0 +1,519 @@
import JSZip from 'jszip'
import type { ChartDisplay, ChartSeries, NewChart } from './types'
import {
attrsOf,
childrenOf,
escapeXmlText,
findChild,
findChildren,
nameOf,
textOf,
xmlParser,
type XNode,
} from './xml-utils'
const CHART_KINDS: Record<string, ChartDisplay['kind']> = {
'c:barChart': 'bar',
'c:bar3DChart': 'bar',
'c:lineChart': 'line',
'c:line3DChart': 'line',
'c:pieChart': 'pie',
'c:pie3DChart': 'pie',
'c:doughnutChart': 'pie',
'c:areaChart': 'area',
'c:area3DChart': 'area',
}
/**
* Read the display model of a chart part (word/charts/chartN.xml). Only the
* caches Word writes next to the data references (c:strCache / c:numCache)
* are read — the embedded workbook is never opened. Returns null when the
* part has no series with cached values (e.g. scatter charts).
*/
export function parseChartPartXml(xml: string, partPath: string): ChartDisplay | null {
const parsed = xmlParser.parse(xml) as XNode[]
const space = parsed.find((n) => nameOf(n) === 'c:chartSpace')
const chart = space ? findChild(space, 'c:chart') : undefined
const plotArea = chart ? findChild(chart, 'c:plotArea') : undefined
if (!chart || !plotArea) return null
// first plotted chart type wins (combo charts render their primary series)
const plot = childrenOf(plotArea).find((c) => (nameOf(c) ?? '').endsWith('Chart'))
if (!plot) return null
const kind = CHART_KINDS[nameOf(plot) ?? ''] ?? 'other'
let categories: string[] = []
const series: ChartSeries[] = []
for (const ser of findChildren(plot, 'c:ser')) {
const val = findChild(ser, 'c:val')
const rawValues = val ? cachePoints(val) : []
const values = rawValues.map((v) => {
if (v === null || v.trim() === '') return null
const n = Number(v)
return Number.isFinite(n) ? n : null
})
if (values.length === 0) continue
const cat = findChild(ser, 'c:cat')
if (cat && categories.length === 0) {
categories = cachePoints(cat).map((v) => v ?? '')
}
const name = seriesName(ser)
series.push({ ...(name !== undefined ? { name } : {}), values })
}
if (series.length === 0) return null
const title = chartTitle(chart)
return {
partPath,
kind,
...(title !== undefined ? { title } : {}),
categories,
series,
}
}
/** cached point texts of a c:cat / c:val / c:tx container, in idx order */
function cachePoints(container: XNode): (string | null)[] {
const ref = findChild(container, 'c:strRef') ?? findChild(container, 'c:numRef')
const cache = ref
? (findChild(ref, 'c:strCache') ?? findChild(ref, 'c:numCache'))
: (findChild(container, 'c:strLit') ?? findChild(container, 'c:numLit'))
if (!cache) return []
const count = parseInt(attrsOf(findChild(cache, 'c:ptCount') ?? {})['val'] ?? '', 10)
const points: (string | null)[] = []
for (const pt of findChildren(cache, 'c:pt')) {
const idx = parseInt(attrsOf(pt)['idx'] ?? '', 10)
if (!Number.isFinite(idx) || idx < 0) continue
points[idx] = textOf(findChild(pt, 'c:v') ?? {})
}
const length = Number.isFinite(count) ? Math.max(count, points.length) : points.length
const out: (string | null)[] = []
for (let i = 0; i < length; i++) out.push(points[i] ?? null)
return out
}
function seriesName(ser: XNode): string | undefined {
const tx = findChild(ser, 'c:tx')
if (!tx) return undefined
const literal = findChild(tx, 'c:v')
if (literal) return textOf(literal)
const cached = cachePoints(tx)
return cached[0] ?? undefined
}
function chartTitle(chart: XNode): string | undefined {
const title = findChild(chart, 'c:title')
if (!title) return undefined
const texts: string[] = []
const walk = (node: XNode) => {
for (const child of childrenOf(node)) {
if (nameOf(child) === 'a:t') texts.push(textOf(child))
else walk(child)
}
}
walk(title)
return texts.join('')
}
const _XLSX_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
export const CHART_WORKBOOK_REL_TYPE =
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/package'
const colLetter = (i: number) => String.fromCharCode(66 + i) // B, C, D...
function strCacheXml(values: string[], f: string): string {
return (
`<c:strRef><c:f>${escapeXmlText(f)}</c:f><c:strCache><c:ptCount val="${values.length}"/>` +
values.map((v, i) => `<c:pt idx="${i}"><c:v>${escapeXmlText(v)}</c:v></c:pt>`).join('') +
'</c:strCache></c:strRef>'
)
}
function numCacheXml(values: (number | null)[], f: string): string {
return (
`<c:numRef><c:f>${escapeXmlText(f)}</c:f><c:numCache><c:formatCode>General</c:formatCode>` +
`<c:ptCount val="${values.length}"/>` +
values.map((v, i) => (v === null ? '' : `<c:pt idx="${i}"><c:v>${v}</c:v></c:pt>`)).join('') +
'</c:numCache></c:numRef>'
)
}
/**
* Build a complete chart part (word/charts/chartN.xml) from data. The chart
* references an embedded workbook via c:externalData so Word's "Edit Data" works.
* Pass `externalDataRId` to wire the c:externalData relationship; omit it when
* the workbook will be added in a separate step.
*/
export function buildChartPartXml(chart: NewChart, externalDataRId?: string): string {
const rows = chart.categories.length
const sers = chart.series
.map((ser, i) => {
const col = colLetter(i)
return (
`<c:ser><c:idx val="${i}"/><c:order val="${i}"/>` +
`<c:tx>${strCacheXml([ser.name], `Sheet1!$${col}$1`)}</c:tx>` +
`<c:cat>${strCacheXml(chart.categories, `Sheet1!$A$2:$A$${rows + 1}`)}</c:cat>` +
`<c:val>${numCacheXml(ser.values.slice(0, rows), `Sheet1!$${col}$2:$${col}$${rows + 1}`)}</c:val>` +
'</c:ser>'
)
})
.join('')
let plot: string
if (chart.kind === 'pie') {
plot = `<c:pieChart><c:varyColors val="1"/>${sers}<c:firstSliceAng val="0"/></c:pieChart>`
} else {
const axes =
'<c:catAx><c:axId val="111111111"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
'<c:delete val="0"/><c:axPos val="b"/><c:crossAx val="222222222"/></c:catAx>' +
'<c:valAx><c:axId val="222222222"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
'<c:delete val="0"/><c:axPos val="l"/><c:crossAx val="111111111"/></c:valAx>'
const inner =
chart.kind === 'bar'
? `<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:varyColors val="0"/>${sers}` +
'<c:axId val="111111111"/><c:axId val="222222222"/></c:barChart>'
: `<c:lineChart><c:grouping val="standard"/><c:varyColors val="0"/>${sers}<c:marker val="1"/>` +
'<c:axId val="111111111"/><c:axId val="222222222"/></c:lineChart>'
plot = inner + axes
}
const title = chart.title
? '<c:title><c:tx><c:rich><a:bodyPr/><a:lstStyle/><a:p><a:r>' +
`<a:t>${escapeXmlText(chart.title)}</a:t></a:r></a:p></c:rich></c:tx>` +
'<c:overlay val="0"/></c:title><c:autoTitleDeleted val="0"/>'
: ''
return (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
'<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" ' +
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
`<c:chart>${title}<c:plotArea><c:layout/>${plot}</c:plotArea>` +
'<c:plotVisOnly val="1"/><c:dispBlanksAs val="gap"/></c:chart>' +
(externalDataRId
? `<c:externalData r:id="${externalDataRId}"><c:autoUpdate val="0"/></c:externalData>`
: '') +
'</c:chartSpace>'
)
}
export interface ChartSeriesPatch {
name?: string
/** aligned with ChartSeries.values; null = keep the original value */
values?: (number | null)[]
}
export interface ChartPatch {
title?: string
/** aligned with ChartDisplay.categories; null = keep */
categories?: (string | null)[]
/** aligned with ChartDisplay.series; null = keep that series untouched */
series?: (ChartSeriesPatch | null)[]
}
/**
* Patch cached texts/numbers of a chart part while keeping the structure —
* data references (c:f), styling, layout — byte-identical. Anything the
* patch cannot anchor (missing title, missing cache point) is left as-is.
* The embedded workbook is intentionally not touched: Word renders from
* these caches, but "Edit Data" will show the original sheet numbers.
*/
export function patchChartPartXml(xml: string, patch: ChartPatch): string {
const edits: Array<{ start: number; end: number; text: string }> = []
if (patch.title !== undefined) {
const title = tagRange(xml, 'c:title')
if (title) {
const texts = innerTextRanges(xml, 'a:t', title.start, title.end)
// whole title into the first run, remaining runs blanked
texts.forEach((range, i) => {
edits.push({ ...range, text: i === 0 ? patch.title! : '' })
})
}
}
const serRanges = tagRanges(xml, 'c:ser')
serRanges.forEach((ser, i) => {
const serPatch = patch.series?.[i]
if (serPatch?.name !== undefined) {
const tx = tagRange(xml, 'c:tx', ser.start, ser.end)
if (tx) {
const texts = innerTextRanges(xml, 'c:v', tx.start, tx.end)
if (texts.length > 0) edits.push({ ...texts[0], text: serPatch.name })
}
}
if (serPatch?.values) {
const val = tagRange(xml, 'c:val', ser.start, ser.end)
if (val)
pushPointEdits(
xml,
val,
serPatch.values.map((v) => (v === null ? null : String(v))),
edits,
)
}
// categories are cached per series; every copy must agree
if (patch.categories) {
const cat = tagRange(xml, 'c:cat', ser.start, ser.end)
if (cat) pushPointEdits(xml, cat, patch.categories, edits)
}
})
if (edits.length === 0) return xml
let out = xml
for (const edit of edits.sort((a, b) => b.start - a.start)) {
out = out.slice(0, edit.start) + escapeXmlText(edit.text) + out.slice(edit.end)
}
return out
}
/** queue edits for the c:v of each indexed cache point present in [range] */
function pushPointEdits(
xml: string,
range: { start: number; end: number },
texts: (string | null)[],
edits: Array<{ start: number; end: number; text: string }>,
): void {
const re = /<c:pt idx="(\d+)"[^>]*>([\s\S]*?)<\/c:pt>/g
re.lastIndex = range.start
let m: RegExpExecArray | null
while ((m = re.exec(xml)) !== null && m.index < range.end) {
const idx = parseInt(m[1], 10)
const text = texts[idx]
if (text === null || text === undefined) continue
const inner = innerTextRanges(xml, 'c:v', m.index, m.index + m[0].length)
if (inner.length > 0) edits.push({ ...inner[0], text })
}
}
/** first depth-0 range of `tag` in [from, to); charts never nest these tags */
function tagRange(
xml: string,
tag: string,
from = 0,
to = xml.length,
): { start: number; end: number } | null {
const openPrefix = '<' + tag
let i = from
while (i < to) {
const o = xml.indexOf(openPrefix, i)
if (o === -1 || o >= to) return null
const after = xml.charAt(o + openPrefix.length)
if (after !== '>' && after !== ' ' && after !== '/') {
i = o + openPrefix.length // prefix of a longer tag (c:tx vs c:txPr)
continue
}
const close = xml.indexOf('</' + tag + '>', o)
if (close === -1 || close >= to) return null
return { start: o, end: close + tag.length + 3 }
}
return null
}
/** all depth-0 ranges of `tag` (used for c:ser, which never nests) */
function tagRanges(xml: string, tag: string): Array<{ start: number; end: number }> {
const out: Array<{ start: number; end: number }> = []
let from = 0
let range: { start: number; end: number } | null
while ((range = tagRange(xml, tag, from)) !== null) {
out.push(range)
from = range.end
}
return out
}
/** inner-text ranges (between open and close tag) of every `tag` in [from, to) */
function innerTextRanges(
xml: string,
tag: string,
from: number,
to: number,
): Array<{ start: number; end: number }> {
const out: Array<{ start: number; end: number }> = []
const re = new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, 'g')
re.lastIndex = from
let m: RegExpExecArray | null
while ((m = re.exec(xml)) !== null && m.index < to) {
const openEnd = m.index + m[0].indexOf('>') + 1
out.push({ start: openEnd, end: openEnd + m[1].length })
}
return out
}
// ---- embedded xlsx workbook ----
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
/** Excel column letter: A, B, C... */
const xlsxColLetter = (i: number) => String.fromCharCode(65 + i)
/**
* Build a minimal but valid xlsx file containing one Sheet1 with the chart
* data (header row + data rows). Returns base64-encoded bytes.
*
* Layout:
* A1 | B1 (ser 0 name) | C1 (ser 1 name) ...
* A2 (cat0) | B2 (val 0,0) | C2 (val 1,0) ...
* A3 (cat1) | B3 (val 0,1) | C3 (val 1,1) ...
*/
export async function buildChartWorkbookXlsxBase64(
categories: string[],
series: Array<{ name: string; values: (number | null)[] }>,
): Promise<string> {
const rows = categories.length
const serCount = series.length
// shared strings: all text cells collected in order
const strings: string[] = []
const si = (s: string): number => {
const idx = strings.indexOf(s)
if (idx !== -1) return idx
strings.push(s)
return strings.length - 1
}
// Build sheetData rows
const headerCells: string[] = []
// A1: empty label cell
headerCells.push(`<c r="A1" t="s"><v>${si('')}</v></c>`)
for (let j = 0; j < serCount; j++) {
headerCells.push(`<c r="${xlsxColLetter(j + 1)}1" t="s"><v>${si(series[j].name)}</v></c>`)
}
const dataRows: string[] = []
for (let i = 0; i < rows; i++) {
const rowNum = i + 2
const cells: string[] = []
cells.push(`<c r="A${rowNum}" t="s"><v>${si(categories[i])}</v></c>`)
for (let j = 0; j < serCount; j++) {
const val = series[j].values[i]
if (val !== null && val !== undefined) {
cells.push(`<c r="${xlsxColLetter(j + 1)}${rowNum}"><v>${val}</v></c>`)
}
}
dataRows.push(`<row r="${rowNum}">${cells.join('')}</row>`)
}
const sheetXml =
XML_DECL +
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
'<sheetData>' +
`<row r="1">${headerCells.join('')}</row>` +
dataRows.join('') +
'</sheetData>' +
'</worksheet>'
const sharedStringsXml =
XML_DECL +
`<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="${strings.length}" uniqueCount="${strings.length}">` +
strings.map((s) => `<si><t>${escapeXmlText(s)}</t></si>`).join('') +
'</sst>'
const workbookXml =
XML_DECL +
'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ' +
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
'<sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets>' +
'</workbook>'
const workbookRels =
XML_DECL +
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>' +
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>' +
'</Relationships>'
const topRels =
XML_DECL +
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>' +
'</Relationships>'
const contentTypes =
XML_DECL +
'<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"/>' +
'<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' +
'<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>' +
'<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>' +
'</Types>'
const zip = new JSZip()
zip.file('[Content_Types].xml', contentTypes)
zip.file('_rels/.rels', topRels)
zip.file('xl/workbook.xml', workbookXml)
zip.file('xl/_rels/workbook.xml.rels', workbookRels)
zip.file('xl/worksheets/sheet1.xml', sheetXml)
zip.file('xl/sharedStrings.xml', sharedStringsXml)
return zipToBase64(zip)
}
async function zipToBase64(zip: JSZip): Promise<string> {
const bytes = await zip.generateAsync({
type: 'uint8array',
compression: 'DEFLATE',
compressionOptions: { level: 6 },
})
let binary = ''
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i])
return btoa(binary)
}
/**
* Patch the Sheet1 sheetData inside an embedded xlsx file (base64).
* Rewrites category column A and each series column with the provided values.
* Returns the updated base64, or null on failure.
*/
export async function patchChartWorkbookXlsxBase64(
base64: string,
categories: string[],
series: Array<{ name: string; values: (number | null)[] }>,
): Promise<string | null> {
try {
const binaryStr = atob(base64)
const bytes = new Uint8Array(binaryStr.length)
for (let i = 0; i < binaryStr.length; i++) bytes[i] = binaryStr.charCodeAt(i)
const zip = await JSZip.loadAsync(bytes)
const sheetFile = zip.file('xl/worksheets/sheet1.xml')
if (!sheetFile) return null
// Replace only Sheet1's sheetData in place, using inline strings so
// sharedStrings.xml (and every other part: styles, extra sheets, defined
// names) survives untouched.
const inlineStr = (ref: string, text: string) =>
`<c r="${ref}" t="inlineStr"><is><t xml:space="preserve">${escapeXmlText(text)}</t></is></c>`
const headerCells = [inlineStr('A1', '')]
for (let j = 0; j < series.length; j++) {
headerCells.push(inlineStr(`${xlsxColLetter(j + 1)}1`, series[j].name))
}
const dataRows: string[] = []
for (let i = 0; i < categories.length; i++) {
const rowNum = i + 2
const cells = [inlineStr(`A${rowNum}`, categories[i])]
for (let j = 0; j < series.length; j++) {
const val = series[j].values[i]
if (val !== null && val !== undefined) {
cells.push(`<c r="${xlsxColLetter(j + 1)}${rowNum}"><v>${val}</v></c>`)
}
}
dataRows.push(`<row r="${rowNum}">${cells.join('')}</row>`)
}
const newSheetData = `<sheetData><row r="1">${headerCells.join('')}</row>${dataRows.join('')}</sheetData>`
const sheetXml = await sheetFile.async('string')
if (!/<sheetData\/>|<sheetData[\s>]/.test(sheetXml)) return null
let updatedSheet = sheetXml.replace(
/<sheetData\/>|<sheetData[^>]*>[\s\S]*?<\/sheetData>/,
newSheetData,
)
const lastRef = `${xlsxColLetter(series.length)}${categories.length + 1}`
updatedSheet = updatedSheet.replace(/<dimension[^>]*\/>/, `<dimension ref="A1:${lastRef}"/>`)
zip.file('xl/worksheets/sheet1.xml', updatedSheet)
return await zipToBase64(zip)
} catch {
return null
}
}
File diff suppressed because it is too large Load Diff
+90
View File
@@ -0,0 +1,90 @@
export * from './types'
export { parseDocx, type ParseExtras } from './parse'
export {
saveDocx,
findChartWorkbookPath,
readDocxPartBase64,
type SaveBlock,
type SaveOptions,
type StyleUpsert,
type ParsedDocFull,
} from './patch'
export {
TABLE_HEADER_FILL,
WORDART_PRESETS,
applyImageWrap,
buildShapeParagraphXml,
buildTextboxParagraphXml,
buildWordArtParagraphXml,
generateCaptionXml,
generateIndexFieldXml,
generateParagraphXml,
generateTableModelXml,
generateTableXml,
generateTocFieldXml,
mergePPrFormat,
setPPrChange,
stripPPrChange,
patchFieldParagraphXml,
patchImageParagraphXml,
patchMathTokens,
patchTableCellTexts,
patchTextboxHeights,
patchTextboxParas,
type CellTextsPatch,
type FieldTextPatch,
type GenerateContext,
type ImagePatch,
type TextboxParaPatch,
type TableGenOptions,
type TocEntry,
} from './generate'
export {
buildChartPartXml,
buildChartWorkbookXlsxBase64,
patchChartWorkbookXlsxBase64,
parseChartPartXml,
patchChartPartXml,
CHART_WORKBOOK_REL_TYPE,
type ChartPatch,
type ChartSeriesPatch,
} from './chart'
export {
latexToOmml,
mathParagraphXml,
mathTokensOf,
ommlFragmentsOf,
ommlToLatex,
ommlToMathML,
} from './math'
export { scanBody, type BodyElement, type BodyScan } from './scan'
export {
BLANK_BULLET_NUM_ID,
BLANK_ORDERED_NUM_ID,
buildBlankDocx,
type BlankDocxOptions,
type CustomNumberingLevel,
} from './blank'
export {
DEFAULT_SECTION,
applySectionSettings,
applyPageNumType,
applySectionStartType,
readPageColor,
readSections,
readSectionSettings,
sectionSettingsFromXml,
} from './section'
export { nextNoteId, parseNotesXml, type NoteKind } from './notes'
export { readWatermarkText } from './watermark'
export {
INK_NAME_PREFIX,
anchoredInkRunXml,
findInkRuns,
injectInkRunsIntoParagraph,
stripInkRuns,
} from './ink'
export { bibliographyLine, citationText, parseSourcesXml } from './sources'
export { readThemeColors, readThemeFonts } from './theme'
export { hashProtectionPassword, verifyProtectionPassword } from './protection'
export { decodeSymbolChar, decodeSymbolText, isSymbolFont } from './symbol-fonts'
+146
View File
@@ -0,0 +1,146 @@
import type { NewInkImage } from './types'
import { escapeXmlAttr } from './xml-utils'
/**
* Ink annotations (freehand strokes). Each saved annotation is a floating picture —
* a run-level <w:drawing><wp:anchor> injected into its anchor paragraph:
*
* - wp:positionV relativeFrom="paragraph": the drawing moves with the
* paragraph when content above it reflows.
* - wp:positionH relativeFrom="column": offsets are measured from the text
* column edge, independent of the paragraph's own indentation.
* - behindDoc="0" + wp:wrapNone: floats in front of the text without
* affecting layout.
* - wp:docPr name starts with "aidocs-ink" so we can recognize our own
* annotations when the file is reopened; descr carries the editor's
* stroke vectors (opaque payload) so the layer stays re-editable.
*
* Word renders these as ordinary floating pictures; only our editor restores
* them into live strokes.
*/
export const INK_NAME_PREFIX = 'aidocs-ink'
/** media filename prefix for ink PNGs (distinct from inline-image aidocsN) */
export const INK_MEDIA_PREFIX = 'aidocsink'
/** matches a document.xml.rels entry that targets an ink media part */
export const INK_REL_RE = new RegExp(
`<Relationship [^>]*Target="media/${INK_MEDIA_PREFIX}\\d+\\.png"[^>]*/>`,
'g',
)
/** matches an ink media part's zip path */
export const INK_MEDIA_PATH_RE = new RegExp(`^word/media/${INK_MEDIA_PREFIX}\\d+\\.png$`)
const EMU_PER_PX = 9525
const A_NS = 'http://schemas.openxmlformats.org/drawingml/2006/main'
const PIC_NS = 'http://schemas.openxmlformats.org/drawingml/2006/picture'
const WP_NS = 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'
const R_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
/**
* The anchored-picture run for one ink annotation. Namespaces are declared
* inline so the fragment is valid regardless of what the document root
* declares (w: is always present).
*/
export function anchoredInkRunXml(
ink: Pick<NewInkImage, 'widthPx' | 'heightPx' | 'offsetXPx' | 'offsetYPx' | 'payload'>,
rId: string,
docPrId: number,
): string {
const cx = Math.max(1, Math.round(ink.widthPx * EMU_PER_PX))
const cy = Math.max(1, Math.round(ink.heightPx * EMU_PER_PX))
const x = Math.round(ink.offsetXPx * EMU_PER_PX)
const y = Math.round(ink.offsetYPx * EMU_PER_PX)
const name = `${INK_NAME_PREFIX} ${docPrId}`
const descr = ink.payload ? ` descr="${escapeXmlAttr(ink.payload)}"` : ''
return (
'<w:r><w:drawing>' +
`<wp:anchor xmlns:wp="${WP_NS}" distT="0" distB="0" distL="0" distR="0" simplePos="0"` +
` relativeHeight="${251658240 + docPrId}" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">` +
'<wp:simplePos x="0" y="0"/>' +
`<wp:positionH relativeFrom="column"><wp:posOffset>${x}</wp:posOffset></wp:positionH>` +
`<wp:positionV relativeFrom="paragraph"><wp:posOffset>${y}</wp:posOffset></wp:positionV>` +
`<wp:extent cx="${cx}" cy="${cy}"/>` +
'<wp:effectExtent l="0" t="0" r="0" b="0"/>' +
'<wp:wrapNone/>' +
`<wp:docPr id="${docPrId}" name="${name}"${descr}/>` +
'<wp:cNvGraphicFramePr/>' +
`<a:graphic xmlns:a="${A_NS}">` +
`<a:graphicData uri="${PIC_NS}">` +
`<pic:pic xmlns:pic="${PIC_NS}">` +
`<pic:nvPicPr><pic:cNvPr id="${docPrId}" name="${name}"/><pic:cNvPicPr/></pic:nvPicPr>` +
`<pic:blipFill><a:blip xmlns:r="${R_NS}" r:embed="${rId}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>` +
`<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm>` +
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr>' +
'</pic:pic></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>'
)
}
const ANCHOR_RUN_RE = /<w:r><w:drawing><wp:anchor[\s\S]*?<\/wp:anchor><\/w:drawing><\/w:r>/g
const isInkRun = (run: string) => run.includes(`name="${INK_NAME_PREFIX}`)
/** Remove every aidocs-ink run from a body-element XML slice. */
export function stripInkRuns(xml: string): string {
if (!xml.includes(INK_NAME_PREFIX)) return xml
return xml.replace(ANCHOR_RUN_RE, (run) => (isInkRun(run) ? '' : run))
}
/** One raw ink run found in a paragraph's XML. */
export interface InkRunMatch {
/** the exact <w:r>...</w:r> slice, for stripping */
xml: string
offsetXPx: number
offsetYPx: number
widthPx: number
heightPx: number
payload: string | null
/** relationship id of the embedded PNG */
embedRId: string | null
}
/** Find aidocs-ink anchored runs inside one paragraph's XML. */
export function findInkRuns(paragraphXml: string): InkRunMatch[] {
if (!paragraphXml.includes(INK_NAME_PREFIX)) return []
const out: InkRunMatch[] = []
for (const run of paragraphXml.match(ANCHOR_RUN_RE) ?? []) {
if (!isInkRun(run)) continue
const emu = (re: RegExp) => parseInt(re.exec(run)?.[1] ?? '0', 10) || 0
const descr = /<wp:docPr [^>]*descr="([^"]*)"/.exec(run)?.[1]
out.push({
xml: run,
offsetXPx: emu(/<wp:positionH[^>]*><wp:posOffset>(-?\d+)/) / EMU_PER_PX,
offsetYPx: emu(/<wp:positionV[^>]*><wp:posOffset>(-?\d+)/) / EMU_PER_PX,
widthPx: emu(/<wp:extent cx="(\d+)"/) / EMU_PER_PX,
heightPx: emu(/<wp:extent cx="\d+" cy="(\d+)"/) / EMU_PER_PX,
payload: descr ? decodeXmlEntities(descr) : null,
embedRId: /r:embed="([^"]+)"/.exec(run)?.[1] ?? null,
})
}
return out
}
/**
* Insert ink runs at the end of a paragraph fragment (after all content
* runs). Returns null when the fragment's root is not a w:p — floating ink
* can only anchor to paragraphs.
*/
export function injectInkRunsIntoParagraph(xml: string, runsXml: string): string | null {
if (!/^<w:p[\s/>]/.test(xml)) return null
if (xml.endsWith('/>')) return `${xml.slice(0, -2)}>${runsXml}</w:p>`
const close = xml.lastIndexOf('</w:p>')
if (close === -1) return null
return xml.slice(0, close) + runsXml + xml.slice(close)
}
function decodeXmlEntities(text: string): string {
return text
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&amp;/g, '&')
}
File diff suppressed because it is too large Load Diff
+200
View File
@@ -0,0 +1,200 @@
import { patchParagraphTexts } from './text-patch'
import type { NoteInfo, NoteRun } from './types'
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
/**
* Footnotes / endnotes part handling (word/footnotes.xml, word/endnotes.xml).
*
* Both parts share one schema: a list of w:footnote / w:endnote elements.
* Entries carrying a w:type attribute (separator, continuationSeparator, ...)
* are structural and must be preserved; only typeless entries are real notes.
*/
export type NoteKind = 'footnote' | 'endnote'
const ROOT: Record<NoteKind, string> = { footnote: 'w:footnotes', endnote: 'w:endnotes' }
const ENTRY: Record<NoteKind, string> = { footnote: 'w:footnote', endnote: 'w:endnote' }
export const NOTE_PART_PATH: Record<NoteKind, string> = {
footnote: 'word/footnotes.xml',
endnote: 'word/endnotes.xml',
}
export const NOTE_REL_TYPE: Record<NoteKind, string> = {
footnote: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes',
endnote: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes',
}
export const NOTE_CONTENT_TYPE: Record<NoteKind, string> = {
footnote: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml',
endnote: 'application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml',
}
const NOTE_NS =
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'
/** real notes (separator entries excluded), in file order */
export function parseNotesXml(xml: string, kind: NoteKind): NoteInfo[] {
return noteEntriesOf(xml, kind).map(({ id, text, xml: entryXml }) => {
const richParas = noteRichParas(entryXml)
const hasFormat = richParas.some((paras) =>
paras.some(
(r) => r.bold || r.italic || r.underline || r.strike || r.color || r.sizeHalfPoints,
),
)
return { id, text, ...(hasFormat ? { richParas } : {}) }
})
}
/** Display runs per paragraph (bold/italic/underline/strike, color, size); the footnote self-reference mark run is skipped */
function noteRichParas(entryXml: string): NoteRun[][] {
const out: NoteRun[][] = []
const pRe = /<w:p[\s>][\s\S]*?<\/w:p>|<w:p\/>/g
let p: RegExpExecArray | null
const flag = (rPr: string, tag: string) =>
new RegExp(`<w:${tag}(?:\\s*/>|\\s(?![^>]*w:val="(?:0|false|none)")[^>]*/>)`).test(rPr)
while ((p = pRe.exec(entryXml)) !== null) {
const runs: NoteRun[] = []
const rRe = /<w:r(?:\s[^>]*)?>([\s\S]*?)<\/w:r>/g
let r: RegExpExecArray | null
while ((r = rRe.exec(p[0])) !== null) {
const inner = r[1]
if (/<w:footnoteRef\/>|<w:endnoteRef\/>/.test(inner)) continue
const text = notePlainText(inner)
if (!text) continue
const rPr = /<w:rPr>[\s\S]*?<\/w:rPr>/.exec(inner)?.[0] ?? ''
const run: NoteRun = { text }
if (flag(rPr, 'b')) run.bold = true
if (flag(rPr, 'i')) run.italic = true
// w:u is not a boolean prop: underline needs an explicit non-"none" w:val
const uVal = /<w:u\s[^>]*w:val="([^"]*)"/.exec(rPr)?.[1]
if (uVal && uVal !== 'none') run.underline = true
if (flag(rPr, 'strike')) run.strike = true
const color = /<w:color [^>]*w:val="([0-9A-Fa-f]{6})"/.exec(rPr)?.[1]
if (color) run.color = color.toUpperCase()
const sz = /<w:sz [^>]*w:val="(\d+)"/.exec(rPr)?.[1]
if (sz) run.sizeHalfPoints = parseInt(sz, 10)
runs.push(run)
}
out.push(runs)
}
// Strip the first paragraph's leading space (spacer after the self-reference mark)
if (out[0]?.[0]) out[0][0].text = out[0][0].text.replace(/^\s+/, '')
return out
}
/** typeless (real) note entries with their exact XML slice + plain text */
function noteEntriesOf(
xml: string,
kind: NoteKind,
): Array<{ id: string; text: string; xml: string }> {
const out: Array<{ id: string; text: string; xml: string }> = []
const entry = ENTRY[kind]
const re = new RegExp(`<${entry}(\\s[^>]*)?>([\\s\\S]*?)</${entry}>`, 'g')
let m: RegExpExecArray | null
while ((m = re.exec(xml)) !== null) {
const attrs = m[1] ?? ''
if (/w:type="/.test(attrs)) continue // separator / continuation entries
const id = /w:id="([^"]+)"/.exec(attrs)?.[1]
if (!id) continue
const paras: string[] = []
const pRe = /<w:p[\s>][\s\S]*?<\/w:p>|<w:p\/>/g
let p: RegExpExecArray | null
while ((p = pRe.exec(m[2])) !== null) paras.push(notePlainText(p[0]))
// the first paragraph starts with the self-reference mark + a spacer
if (paras.length > 0) paras[0] = paras[0].replace(/^\s+/, '')
out.push({ id, text: paras.join('\n'), xml: m[0] })
}
return out
}
function notePlainText(xml: string): string {
const texts: string[] = []
const re = /<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>/g
let m: RegExpExecArray | null
while ((m = re.exec(xml)) !== null) texts.push(m[1])
return texts
.join('')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&amp;/g, '&')
}
/** default separator entries required by Word when the part is created fresh */
function separatorEntries(kind: NoteKind): string {
const entry = ENTRY[kind]
return (
`<${entry} w:type="separator" w:id="-1"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:separator/></w:r></w:p></${entry}>` +
`<${entry} w:type="continuationSeparator" w:id="0"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></${entry}>`
)
}
function noteEntryXml(kind: NoteKind, note: NoteInfo): string {
const entry = ENTRY[kind]
const refTag = kind === 'footnote' ? 'w:footnoteRef' : 'w:endnoteRef'
const paras = note.text.split('\n').map((line, i) => {
// OOXML convention: the note body starts with the self-reference mark
const refRun =
i === 0
? `<w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><${refTag}/></w:r>` +
'<w:r><w:t xml:space="preserve"> </w:t></w:r>'
: ''
const textRun =
line === '' ? '' : `<w:r><w:t xml:space="preserve">${escapeXmlText(line)}</w:t></w:r>`
return `<w:p>${refRun}${textRun}</w:p>`
})
return `<${entry} w:id="${escapeXmlAttr(note.id)}">${paras.join('')}</${entry}>`
}
/**
* Regenerate the notes part from the full desired list. Structural entries
* (separator/continuation) from the original part are kept byte-identical;
* when there is no original part, standard separators are created.
* Surgical: existing entries whose text is unchanged keep their original bytes (inline
* formatting, images, and hyperlinks are preserved); entries with changed text first try
* an in-paragraph w:t-level patch (formatting still preserved), and only fall back to a
* plain-text rebuild when patching fails (paragraph count changed, etc.).
*/
export function buildNotesXml(
kind: NoteKind,
notes: NoteInfo[],
originalXml: string | null,
): string {
const entry = ENTRY[kind]
let structural = ''
const originals = new Map<string, { text: string; xml: string }>()
if (originalXml) {
const re = new RegExp(`<${entry}\\s[^>]*w:type="[^"]*"[^>]*>[\\s\\S]*?</${entry}>`, 'g')
structural = (originalXml.match(re) ?? []).join('')
for (const e of noteEntriesOf(originalXml, kind)) originals.set(e.id, e)
}
if (!structural) structural = separatorEntries(kind)
const body = notes
.map((n) => {
const orig = originals.get(n.id)
if (!orig) return noteEntryXml(kind, n)
if (orig.text === n.text) return orig.xml
const patched = patchParagraphTexts(orig.xml, n.text, {
stripFirstParaLeadingSpace: true,
})
return patched ?? noteEntryXml(kind, n)
})
.join('')
return (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
`<${ROOT[kind]} ${NOTE_NS}>${structural}${body}</${ROOT[kind]}>`
)
}
/** next free numeric note id (separator ids -1/0 and existing notes considered) */
export function nextNoteId(notes: NoteInfo[]): string {
let max = 0
for (const note of notes) {
const n = parseInt(note.id, 10)
if (Number.isFinite(n)) max = Math.max(max, n)
}
return String(max + 1)
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+79
View File
@@ -0,0 +1,79 @@
import type { DocProtection } from './types'
/**
* w:documentProtection password hash (Word 2013+ scheme, ECMA-376 iterated hash):
* h0 = H(salt || UTF-16LE(password))
* hi = H(h(i-1) || LE32(i)) i = 0..spinCount-1
* sid 14 = SHA-512 (the only implemented algorithm). Uses WebCrypto, so it works in
* both the renderer process and Node 20+.
*/
function toBase64(bytes: Uint8Array): string {
let bin = ''
for (const b of bytes) bin += String.fromCharCode(b)
return btoa(bin)
}
function fromBase64(b64: string): Uint8Array {
const bin = atob(b64)
const out = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
return out
}
function utf16le(text: string): Uint8Array {
const out = new Uint8Array(text.length * 2)
for (let i = 0; i < text.length; i++) {
const code = text.charCodeAt(i)
out[i * 2] = code & 0xff
out[i * 2 + 1] = code >> 8
}
return out
}
function concat(a: Uint8Array, b: Uint8Array): Uint8Array {
const out = new Uint8Array(a.length + b.length)
out.set(a, 0)
out.set(b, a.length)
return out
}
async function iteratedSha512(
password: string,
salt: Uint8Array,
spinCount: number,
): Promise<Uint8Array> {
const subtle = globalThis.crypto.subtle
const digest = async (bytes: Uint8Array) =>
new Uint8Array(await subtle.digest('SHA-512', bytes as unknown as ArrayBuffer))
let hash = await digest(concat(salt, utf16le(password)))
const iter = new Uint8Array(4)
const view = new DataView(iter.buffer)
for (let i = 0; i < spinCount; i++) {
view.setUint32(0, i, true)
hash = await digest(concat(hash, iter))
}
return hash
}
/** Generate the protection password hash (random 16-byte salt, 100000 iterations by default) */
export async function hashProtectionPassword(
password: string,
spinCount = 100000,
): Promise<{ hash: string; salt: string; spinCount: number; algorithmSid: number }> {
const salt = globalThis.crypto.getRandomValues(new Uint8Array(16))
const hash = await iteratedSha512(password, salt, spinCount)
return { hash: toBase64(hash), salt: toBase64(salt), spinCount, algorithmSid: 14 }
}
/** Check whether the password matches the hash in documentProtection (no hash = no password, always true) */
export async function verifyProtectionPassword(
password: string,
protection: Pick<DocProtection, 'hash' | 'salt' | 'spinCount' | 'algorithmSid'>,
): Promise<boolean> {
if (!protection.hash) return true
if ((protection.algorithmSid ?? 14) !== 14) return false // only SHA-512 is supported
const salt = protection.salt ? fromBase64(protection.salt) : new Uint8Array(0)
const hash = await iteratedSha512(password, salt, protection.spinCount ?? 100000)
return toBase64(hash) === protection.hash
}
+82
View File
@@ -0,0 +1,82 @@
/**
* Byte-exact scanner for word/document.xml.
*
* We never re-serialize the whole XML (parse->serialize would silently change
* untouched bytes: attribute order, self-closing forms, entity forms...).
* Instead we locate the exact character range of every top-level element in
* <w:body> so that patch-save can splice new fragments while copying untouched
* elements as raw original substrings.
*/
export interface BodyElement {
/** tag name, e.g. "w:p", "w:tbl", "w:sectPr" */
name: string
/** range [start, end) in the document.xml string */
start: number
end: number
}
export interface BodyScan {
elements: BodyElement[]
/** range [innerStart, innerEnd) spanning from the first top-level element start to the last element end */
innerStart: number
innerEnd: number
}
// Matches one XML tag, tolerating '>' inside quoted attribute values.
const TAG_RE = /<\/?(?:[^<>"']|"[^"]*"|'[^']*')*>/g
const NAME_RE = /^<\/?\s*([A-Za-z_][\w:.-]*)/
export function scanBody(documentXml: string): BodyScan {
const bodyOpenMatch = /<w:body(?:\s(?:[^<>"']|"[^"]*"|'[^']*')*)?>/.exec(documentXml)
if (!bodyOpenMatch) {
throw new Error('document.xml has no <w:body> element')
}
const scanFrom = bodyOpenMatch.index + bodyOpenMatch[0].length
const elements: BodyElement[] = []
TAG_RE.lastIndex = scanFrom
let depth = 0
let currentStart = -1
let currentName = ''
let match: RegExpExecArray | null
while ((match = TAG_RE.exec(documentXml)) !== null) {
const tag = match[0]
// Skip comments / CDATA / processing instructions (rare in Word output).
if (tag.startsWith('<!--') || tag.startsWith('<![') || tag.startsWith('<?')) continue
const isClosing = tag.startsWith('</')
const isSelfClosing = !isClosing && tag.endsWith('/>')
const name = NAME_RE.exec(tag)?.[1] ?? ''
if (isClosing) {
if (depth === 0) {
if (name === 'w:body') break
throw new Error(`unexpected closing tag </${name}> at body level`)
}
depth--
if (depth === 0) {
elements.push({ name: currentName, start: currentStart, end: match.index + tag.length })
}
} else if (isSelfClosing) {
if (depth === 0) {
elements.push({ name, start: match.index, end: match.index + tag.length })
}
} else {
if (depth === 0) {
currentStart = match.index
currentName = name
}
depth++
}
}
if (elements.length === 0) {
return { elements, innerStart: scanFrom, innerEnd: scanFrom }
}
return {
elements,
innerStart: elements[0].start,
innerEnd: elements[elements.length - 1].end,
}
}
+267
View File
@@ -0,0 +1,267 @@
import type { ParsedDoc, SectionInfo, SectionSettings, DocGrid } from './types'
/** US Letter, portrait, 1-inch margins */
export const DEFAULT_SECTION: SectionSettings = {
pageWidth: 12240,
pageHeight: 15840,
orientation: 'portrait',
marginTop: 1440,
marginRight: 1440,
marginBottom: 1440,
marginLeft: 1440,
pageBorder: false,
columns: 1,
headerDist: 720,
footerDist: 720,
}
/** Vertical alignment of page content (sectPr w:vAlign); top/default returns undefined */
function vAlignOf(xml: string): 'center' | 'both' | 'bottom' | undefined {
const v = /<w:vAlign w:val="(center|both|bottom)"\s*\/>/.exec(xml)?.[1]
return v as 'center' | 'both' | 'bottom' | undefined
}
function intAttr(tag: string, name: string, fallback: number): number {
const m = new RegExp(`${name}="(-?\\d+)"`).exec(tag)
const v = m ? parseInt(m[1], 10) : NaN
return Number.isFinite(v) ? v : fallback
}
/**
* True when w:pgBorders declares at least one visible side. Word writes explicit
* "no border" as side elements with w:val="none" (or "nil"), so the mere presence
* of w:pgBorders must not be treated as a drawn border.
*/
function hasVisiblePageBorder(xml: string): boolean {
const pgBorders = /<w:pgBorders[^>]*\/>|<w:pgBorders[\s\S]*?<\/w:pgBorders>/.exec(xml)?.[0]
if (!pgBorders) return false
const sides = pgBorders.match(/<w:(?:top|left|bottom|right)\b[^>]*\/?>/g) ?? []
return sides.some((side) => {
const val = /w:val="([^"]*)"/.exec(side)?.[1]
return val !== undefined && val !== 'none' && val !== 'nil'
})
}
/** Page setup from one w:sectPr XML slice. */
export function sectionSettingsFromXml(xml: string): SectionSettings {
const pgSz = /<w:pgSz[^>]*\/?>/.exec(xml)?.[0] ?? ''
const pgMar = /<w:pgMar[^>]*\/?>/.exec(xml)?.[0] ?? ''
// Parse docGrid (w:docGrid)
let docGrid: DocGrid | undefined
const docGridTag = /<w:docGrid[^>]*\/?>/.exec(xml)?.[0]
if (docGridTag) {
const typeMatch = /w:type="([^"]+)"/.exec(docGridTag)
const linePitchMatch = /w:linePitch="(\d+)"/.exec(docGridTag)
const charSpaceMatch = /w:charSpace="(-?\d+)"/.exec(docGridTag)
const gridType = (typeMatch?.[1] ?? 'default') as DocGrid['type']
const validTypes: DocGrid['type'][] = ['default', 'lines', 'linesAndChars', 'snapToChars']
docGrid = {
type: validTypes.includes(gridType) ? gridType : 'default',
...(linePitchMatch ? { linePitch: parseInt(linePitchMatch[1], 10) } : {}),
...(charSpaceMatch ? { charSpace: parseInt(charSpaceMatch[1], 10) } : {}),
}
}
return {
pageWidth: intAttr(pgSz, 'w:w', DEFAULT_SECTION.pageWidth),
pageHeight: intAttr(pgSz, 'w:h', DEFAULT_SECTION.pageHeight),
orientation: pgSz.includes('w:orient="landscape"') ? 'landscape' : 'portrait',
marginTop: intAttr(pgMar, 'w:top', DEFAULT_SECTION.marginTop),
marginRight: intAttr(pgMar, 'w:right', DEFAULT_SECTION.marginRight),
marginBottom: intAttr(pgMar, 'w:bottom', DEFAULT_SECTION.marginBottom),
marginLeft: intAttr(pgMar, 'w:left', DEFAULT_SECTION.marginLeft),
headerDist: intAttr(pgMar, 'w:header', 720),
footerDist: intAttr(pgMar, 'w:footer', 720),
...(vAlignOf(xml) ? { vAlign: vAlignOf(xml) } : {}),
pageBorder: hasVisiblePageBorder(xml),
columns: intAttr(/<w:cols[^>]*\/?>/.exec(xml)?.[0] ?? '', 'w:num', 1),
colSpace: intAttr(/<w:cols[^>]*\/?>/.exec(xml)?.[0] ?? '', 'w:space', 720),
...(docGrid ? { docGrid } : {}),
...(textDirectionOf(xml) ? { textDirection: textDirectionOf(xml) } : {}),
}
}
function textDirectionOf(xml: string): string | undefined {
const val = /<w:textDirection[^>]*w:val="([^"]+)"/.exec(xml)?.[1]
return val && val !== 'lrTb' ? val : undefined
}
/** Read page setup from the trailing (hidden) w:sectPr. */
export function readSectionSettings(parsed: ParsedDoc): SectionSettings {
const sectBlock = parsed.blocks.find((b) => b.hidden && b.originalXml?.includes('<w:sectPr'))
return sectionSettingsFromXml(sectBlock?.originalXml ?? '')
}
const SECT_PR_RE = /<w:sectPr[^>]*\/>|<w:sectPr[\s\S]*?<\/w:sectPr>/
function hfRefs(
xml: string,
kind: 'header' | 'footer',
): Partial<Record<'default' | 'first' | 'even', string>> {
const refs: Partial<Record<'default' | 'first' | 'even', string>> = {}
for (const ref of xml.match(new RegExp(`<w:${kind}Reference[^>]*/>`, 'g')) ?? []) {
const type = /w:type="(default|first|even)"/.exec(ref)?.[1] ?? 'default'
const rId = /r:id="([^"]+)"/.exec(ref)?.[1]
if (rId) refs[type as 'default' | 'first' | 'even'] = rId
}
return refs
}
function sectionFromSectPr(
sectPrXml: string,
firstBlockIndex: number,
lastBlockIndex: number,
): SectionInfo {
const type = /<w:type[^>]*w:val="(nextPage|continuous|evenPage|oddPage|nextColumn)"/.exec(
sectPrXml,
)?.[1]
const pgNumStart = /<w:pgNumType[^>]*w:start="(\d+)"/.exec(sectPrXml)?.[1]
const pgNumFmt = /<w:pgNumType[^>]*w:fmt="([^"]+)"/.exec(sectPrXml)?.[1]
return {
settings: sectionSettingsFromXml(sectPrXml),
// nextColumn is rare; treat it as continuous (no forced page break)
startType:
type === 'nextColumn' ? 'continuous' : ((type as SectionInfo['startType']) ?? 'nextPage'),
firstBlockIndex,
lastBlockIndex,
sectPrXml,
titlePg: /<w:titlePg\s*\/>/.test(sectPrXml),
...(pgNumStart !== undefined ? { pageNumberStart: parseInt(pgNumStart, 10) } : {}),
...(pgNumFmt !== undefined ? { pageNumberFmt: pgNumFmt } : {}),
headerRefs: hfRefs(sectPrXml, 'header'),
footerRefs: hfRefs(sectPrXml, 'footer'),
}
}
/**
* Rewrite the sectPr page numbering w:pgNumType (fmt = number format, start = starting
* page number; undefined fields are omitted, and the tag is removed when both are unset).
* Schema order: pgNumType comes after pgMar/pgBorders and before cols/docGrid.
*/
export function applyPageNumType(
sectPrXml: string,
fmt: string | undefined,
start: number | undefined,
): string {
let xml = sectPrXml.replace(/<w:pgNumType[^>]*\/>/, '')
if (fmt === undefined && start === undefined) return xml
const tag = `<w:pgNumType${fmt !== undefined ? ` w:fmt="${fmt}"` : ''}${start !== undefined ? ` w:start="${start}"` : ''}/>`
if (/<w:cols[\s/>]/.test(xml)) xml = xml.replace(/(<w:cols[\s/>])/, `${tag}$1`)
else if (/<w:docGrid/.test(xml)) xml = xml.replace(/(<w:docGrid)/, `${tag}$1`)
else xml = xml.replace(/<\/w:sectPr>/, `${tag}</w:sectPr>`)
return xml
}
/**
* Enumerate every section in document order. A paragraph-level w:sectPr
* (section-break paragraph) closes its section; the trailing hidden sectPr closes the last.
* Block ranges use docxIndex (body child order), boundaries inclusive.
*/
export function readSections(parsed: ParsedDoc): SectionInfo[] {
const sections: SectionInfo[] = []
let first = 0
for (const block of parsed.blocks) {
const xml = block.originalXml ?? ''
if (block.docxIndex == null || !xml.includes('<w:sectPr')) continue
const sectPrXml = SECT_PR_RE.exec(xml)?.[0]
if (!sectPrXml) continue
sections.push(sectionFromSectPr(sectPrXml, first, block.docxIndex))
first = block.docxIndex + 1
}
if (sections.length === 0) {
const last = parsed.blocks[parsed.blocks.length - 1]?.docxIndex ?? 0
sections.push(sectionFromSectPr('', 0, last))
}
return sections
}
/** Rewrite pgSz / pgMar inside a w:sectPr XML slice, preserving everything else. */
export function applySectionSettings(sectPrXml: string, settings: SectionSettings): string {
const orient = settings.orientation === 'landscape' ? ' w:orient="landscape"' : ''
const pgSz = `<w:pgSz w:w="${settings.pageWidth}" w:h="${settings.pageHeight}"${orient}/>`
let xml = sectPrXml
if (/<w:pgSz[^>]*\/?>/.test(xml)) {
xml = xml.replace(/<w:pgSz[^>]*\/?>/, pgSz)
} else {
xml = xml.replace(/(<w:sectPr[^>]*>)/, `$1${pgSz}`)
}
const replaceMarAttr = (tag: string, name: string, value: number): string => {
if (new RegExp(`${name}="`).test(tag)) {
return tag.replace(new RegExp(`${name}="-?\\d+"`), `${name}="${value}"`)
}
return tag.replace(/\/>$/, ` ${name}="${value}"/>`)
}
const marMatch = /<w:pgMar[^>]*\/>/.exec(xml)
if (marMatch) {
let tag = marMatch[0]
tag = replaceMarAttr(tag, 'w:top', settings.marginTop)
tag = replaceMarAttr(tag, 'w:right', settings.marginRight)
tag = replaceMarAttr(tag, 'w:bottom', settings.marginBottom)
tag = replaceMarAttr(tag, 'w:left', settings.marginLeft)
xml = xml.replace(marMatch[0], tag)
} else {
const pgMar =
`<w:pgMar w:top="${settings.marginTop}" w:right="${settings.marginRight}"` +
` w:bottom="${settings.marginBottom}" w:left="${settings.marginLeft}"` +
' w:header="708" w:footer="708" w:gutter="0"/>'
xml = xml.replace(/<\/w:sectPr>/, `${pgMar}</w:sectPr>`)
}
// page border: single-line box measured from the page edge (pgBorders sits
// between pgMar and cols in CT_SectPr)
xml = xml.replace(/<w:pgBorders[^>]*\/>|<w:pgBorders[\s\S]*?<\/w:pgBorders>/, '')
if (settings.pageBorder) {
const side = (name: string) =>
`<w:${name} w:val="single" w:sz="4" w:space="24" w:color="auto"/>`
const pgBorders =
'<w:pgBorders w:offsetFrom="page">' +
`${side('top')}${side('left')}${side('bottom')}${side('right')}` +
'</w:pgBorders>'
xml = xml.replace(/(<w:pgMar[^>]*\/>)/, `$1${pgBorders}`)
}
// columns (w:cols may be self-closing or carry explicit <w:col> children)
const colsMatch = /<w:cols[^>]*\/>|<w:cols[^>]*>[\s\S]*?<\/w:cols>/.exec(xml)
const numAttr = settings.columns > 1 ? ` w:num="${settings.columns}"` : ''
if (colsMatch) {
const openTag = /^<w:cols[^>]*>/.exec(colsMatch[0])?.[0] ?? colsMatch[0]
const selfClosing = colsMatch[0].endsWith('/>')
const currentNum = / w:num="(\d+)"/.exec(openTag)?.[1] ?? '1'
if (selfClosing || currentNum !== String(settings.columns)) {
// explicit per-column widths only stay valid while the count is unchanged
let tag = openTag.replace(/ w:num="\d+"/, '').replace(/\/?>$/, '/>')
if (numAttr) tag = tag.replace(/^<w:cols/, `<w:cols${numAttr}`)
xml = xml.replace(colsMatch[0], tag)
}
} else if (numAttr) {
const anchor = /(<w:pgBorders[\s\S]*?<\/w:pgBorders>|<w:pgMar[^>]*\/>)/.exec(xml)
const cols = `<w:cols${numAttr} w:space="425"/>`
if (anchor) xml = xml.replace(anchor[0], `${anchor[0]}${cols}`)
else xml = xml.replace(/<\/w:sectPr>/, `${cols}</w:sectPr>`)
}
return xml
}
/**
* Rewrite the sectPr start type w:type (how this section starts relative to the previous
* one). nextPage is the default and is written by removing the tag; w:type comes before
* pgSz in CT_SectPr.
*/
export function applySectionStartType(
sectPrXml: string,
type: 'nextPage' | 'continuous' | 'evenPage' | 'oddPage',
): string {
let xml = sectPrXml.replace(/<w:type[^>]*\/>/, '')
if (type === 'nextPage') return xml
const tag = `<w:type w:val="${type}"/>`
if (/<w:pgSz/.test(xml)) xml = xml.replace(/(<w:pgSz)/, `${tag}$1`)
else xml = xml.replace(/(<w:sectPr[^>]*>)/, `$1${tag}`)
return xml
}
/** Read the page color (w:background) from document.xml; null when unset. */
export function readPageColor(parsed: ParsedDoc): string | null {
const m = /<w:background[^>]*w:color="([0-9A-Fa-f]{6})"/.exec(parsed.internal.documentXml)
return m ? m[1].toUpperCase() : null
}
+153
View File
@@ -0,0 +1,153 @@
import type JSZip from 'jszip'
import type { SourceInfo } from './types'
import { escapeXmlText } from './xml-utils'
/**
* Bibliography sources live in a customXml part using the Word b:Sources
* schema, so sources added here appear in Word's own citation manager.
*/
export const SOURCES_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/bibliography'
export const CUSTOM_XML_REL_TYPE =
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml'
/** find the zip path of the existing b:Sources custom xml part, if any */
export async function findSourcesPart(zip: JSZip): Promise<string | null> {
for (const name of Object.keys(zip.files)) {
if (!/^customXml\/item\d+\.xml$/.test(name)) continue
const xml = await zip.file(name)!.async('string')
if (xml.includes('Sources') && xml.includes(SOURCES_NS)) return name
}
return null
}
export function parseSourcesXml(xml: string): SourceInfo[] {
const out: SourceInfo[] = []
const re = /<b:Source>([\s\S]*?)<\/b:Source>/g
let m: RegExpExecArray | null
while ((m = re.exec(xml)) !== null) {
const body = m[1]
const field = (tag: string) => {
const f = new RegExp(`<b:${tag}>([\\s\\S]*?)</b:${tag}>`).exec(body)?.[1]
return f ? decodeEntities(f.trim()) : undefined
}
const tag = field('Tag')
if (!tag) continue
// author: person name list (Last, First) or corporate name
let author = field('Corporate') ?? ''
if (!author) {
const last = field('Last') ?? ''
const first = field('First') ?? ''
author = [last, first].filter(Boolean).join(', ')
}
out.push({
tag,
type: field('SourceType') ?? 'Misc',
author,
title: field('Title') ?? '',
year: field('Year') ?? '',
publisher: field('Publisher') ?? field('JournalName') ?? field('InternetSiteTitle'),
url: field('URL'),
})
}
return out
}
function decodeEntities(text: string): string {
return text
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&amp;/g, '&')
}
function sourceEntryXml(source: SourceInfo): string {
const t = (tag: string, value: string | undefined) =>
value ? `<b:${tag}>${escapeXmlText(value)}</b:${tag}>` : ''
// "Last, First" splits into Last/First; anything else is stored as Last
const comma = source.author.indexOf(',')
const last = comma === -1 ? source.author : source.author.slice(0, comma).trim()
const first = comma === -1 ? '' : source.author.slice(comma + 1).trim()
const authorXml = source.author
? '<b:Author><b:Author><b:NameList><b:Person>' +
t('Last', last) +
t('First', first) +
'</b:Person></b:NameList></b:Author></b:Author>'
: ''
const publisherTag =
source.type === 'JournalArticle'
? 'JournalName'
: source.type === 'InternetSite'
? 'InternetSiteTitle'
: 'Publisher'
return (
'<b:Source>' +
t('Tag', source.tag) +
t('SourceType', source.type) +
authorXml +
t('Title', source.title) +
t('Year', source.year) +
t(publisherTag, source.publisher) +
t('URL', source.url) +
'</b:Source>'
)
}
/**
* Surgical rebuild of b:Sources: unchanged b:Source entries keep their original bytes
* (unmodeled fields like Editor/Volume/Pages/DOI/multi-author lists are preserved), the
* root element attributes (SelectedStyle citation style) come from the original document,
* and only new/edited entries are rebuilt from the modeled fields.
*/
export function buildSourcesXml(sources: SourceInfo[], originalXml: string | null = null): string {
const originals = new Map<string, { xml: string; parsed: SourceInfo }>()
let rootOpen =
`<b:Sources SelectedStyle="\\APASixthEditionOfficeOnline.xsl" StyleName="APA" Version="6" xmlns:b="${SOURCES_NS}" xmlns="${SOURCES_NS}">`
if (originalXml) {
const open = /<b:Sources(?:\s[^>]*)?>/.exec(originalXml)?.[0]
if (open) rootOpen = open
for (const m of originalXml.match(/<b:Source>[\s\S]*?<\/b:Source>/g) ?? []) {
const parsed = parseSourcesXml(m)[0]
if (parsed) originals.set(parsed.tag, { xml: m, parsed })
}
}
const unchanged = (a: SourceInfo, b: SourceInfo) =>
a.type === b.type && a.author === b.author && a.title === b.title && a.year === b.year &&
(a.publisher ?? '') === (b.publisher ?? '') && (a.url ?? '') === (b.url ?? '')
const body = sources
.map((s) => {
const orig = originals.get(s.tag)
return orig && unchanged(orig.parsed, s) ? orig.xml : sourceEntryXml(s)
})
.join('')
return rootOpen + body + '</b:Sources>'
}
export function buildSourcesItemPropsXml(): string {
return (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
'<ds:datastoreItem ds:itemID="{4A8D2934-D5B1-4C15-A6F4-7A1B2C3D4E5F}"' +
' xmlns:ds="http://schemas.openxmlformats.org/officeDocument/2006/customXml">' +
`<ds:schemaRefs><ds:schemaRef ds:uri="${SOURCES_NS}"/></ds:schemaRefs>` +
'</ds:datastoreItem>'
)
}
/** in-text citation, e.g. "(Smith, 2024)" */
export function citationText(source: SourceInfo): string {
const author = source.author || source.title
return source.year ? `(${author}, ${source.year})` : `(${author})`
}
/** one bibliography line in a simple APA-like format */
export function bibliographyLine(source: SourceInfo): string {
const parts: string[] = []
if (source.author) parts.push(source.author + '.')
if (source.year) parts.push(`(${source.year}).`)
if (source.title) parts.push(source.title + '.')
if (source.publisher) parts.push(source.publisher + '.')
if (source.url) parts.push(source.url)
return parts.join(' ')
}
+164
View File
@@ -0,0 +1,164 @@
/**
* Symbol-encoded legacy fonts (Symbol / Wingdings / Webdings) carry glyphs at
* arbitrary byte positions, stored either as that byte or as U+F0xx (private
* use). Without the font installed they render as the raw letter or tofu, so
* map the common glyphs to their Unicode equivalents for display.
*/
const SYMBOL: Record<number, string> = {
// Greek (Adobe Symbol layout: Latin letter position -> Greek letter)
0x41: 'Α',
0x42: 'Β',
0x43: 'Χ',
0x44: 'Δ',
0x45: 'Ε',
0x46: 'Φ',
0x47: 'Γ',
0x48: 'Η',
0x49: 'Ι',
0x4b: 'Κ',
0x4c: 'Λ',
0x4d: 'Μ',
0x4e: 'Ν',
0x4f: 'Ο',
0x50: 'Π',
0x51: 'Θ',
0x52: 'Ρ',
0x53: 'Σ',
0x54: 'Τ',
0x55: 'Υ',
0x57: 'Ω',
0x58: 'Ξ',
0x59: 'Ψ',
0x5a: 'Ζ',
0x61: 'α',
0x62: 'β',
0x63: 'χ',
0x64: 'δ',
0x65: 'ε',
0x66: 'φ',
0x67: 'γ',
0x68: 'η',
0x69: 'ι',
0x6b: 'κ',
0x6c: 'λ',
0x6d: 'μ',
0x6e: 'ν',
0x6f: 'ο',
0x70: 'π',
0x71: 'θ',
0x72: 'ρ',
0x73: 'σ',
0x74: 'τ',
0x75: 'υ',
0x77: 'ω',
0x78: 'ξ',
0x79: 'ψ',
0x7a: 'ζ',
// math / arrows
0x22: '∀',
0x24: '∃',
0xa3: '≤',
0xa5: '∞',
0xab: '↔',
0xac: '←',
0xad: '↑',
0xae: '→',
0xaf: '↓',
0xb0: '°',
0xb1: '±',
0xb3: '≥',
0xb4: '×',
0xb6: '∂',
0xb7: '•',
0xb8: '÷',
0xb9: '≠',
0xba: '≡',
0xbb: '≈',
0xbc: '…',
0xc4: '⊗',
0xc5: '⊕',
0xc6: '∅',
0xc7: '∩',
0xc8: '∪',
0xc9: '⊃',
0xcc: '⊂',
0xce: '∈',
0xd1: '∇',
0xd5: '∏',
0xd6: '√',
0xd7: '⋅',
0xd8: '¬',
0xd9: '∧',
0xda: '∨',
0xe5: '∑',
0xf2: '∫',
}
const WINGDINGS: Record<number, string> = {
0x21: '✏',
0x22: '✂',
0x28: '☎',
0x2a: '✉',
0x45: '☜',
0x46: '☞',
0x47: '☝',
0x48: '☟',
0x4a: '☺',
0x4b: '😐',
0x4c: '☹',
0x6c: '●',
0x6d: '❍',
0x6e: '■',
0x6f: '❑',
0x70: '❒',
0x75: '◆',
0x76: '❖',
0x78: '⌧',
0xa7: '▪',
0xa8: '□',
0xab: '★',
0xd8: '➢',
0xfb: '✗',
0xfc: '✓',
0xfd: '☒',
0xfe: '☑',
}
const SYMBOL_FONT_MAPS: Record<string, Record<number, string>> = {
symbol: SYMBOL,
wingdings: WINGDINGS,
// recognized as symbol-encoded so unmapped glyphs get sane fallbacks, but no table yet
'wingdings 2': {},
'wingdings 3': {},
webdings: {},
}
export function isSymbolFont(font: string | null | undefined): boolean {
return !!font && font.trim().toLowerCase() in SYMBOL_FONT_MAPS
}
/** glyph code (raw byte or its U+F0xx private-use form) → Unicode equivalent, null when unknown */
export function decodeSymbolChar(font: string, code: number): string | null {
const map = SYMBOL_FONT_MAPS[font.trim().toLowerCase()]
if (!map) return null
const low = code >= 0xf000 && code <= 0xf0ff ? code - 0xf000 : code
return map[low] ?? null
}
/** whole string decode; null unless every non-whitespace char maps */
export function decodeSymbolText(font: string, text: string): string | null {
if (!isSymbolFont(font)) return null
let out = ''
for (const ch of text) {
const code = ch.codePointAt(0) as number
if (code <= 0x20 || code === 0xa0) {
out += ch
continue
}
const mapped = decodeSymbolChar(font, code)
if (mapped === null) return null
out += mapped
}
return out
}
+213
View File
@@ -0,0 +1,213 @@
import { escapeXmlText } from './xml-utils'
/**
* Paragraph-level surgical text patch (saving edits to rich-text entries such as
* comments/footnotes).
*
* Maps the edited plain text ('\n' between paragraphs, each paragraph = concatenated w:t)
* back onto the original entry XML:
* - Paragraphs whose text is unchanged keep their original bytes (inline formatting,
* hyperlinks, images, and fields are all preserved)
* - Changed paragraphs get a minimal w:t replacement: only the w:t outside the common
* prefix/suffix are rewritten, other run bytes stay untouched
* - If the paragraph count changed, or a changed paragraph has no w:t to anchor to,
* returns null and the caller falls back to rebuilding the whole entry
*
* stripFirstParaLeadingSpace: footnote/endnote first paragraphs start with a
* self-reference mark + space run, which the plain-text model drops; when enabled,
* that leading whitespace is treated as an immutable prefix.
*/
export function patchParagraphTexts(
entryXml: string,
newText: string,
opts: { stripFirstParaLeadingSpace?: boolean } = {},
): string | null {
const paras = paragraphSlices(entryXml)
if (paras.length === 0) return null
const oldParaTexts = paras.map((p, i) =>
i === 0 && opts.stripFirstParaLeadingSpace
? decodedTextOf(p.xml).replace(/^\s+/, '')
: decodedTextOf(p.xml),
)
if (oldParaTexts.join('\n') === newText) return entryXml
const newParaTexts = newText.split('\n')
if (newParaTexts.length !== paras.length) return null
let out = ''
let cursor = 0
for (let i = 0; i < paras.length; i++) {
const para = paras[i]
out += entryXml.slice(cursor, para.start)
if (oldParaTexts[i] === newParaTexts[i]) {
out += para.xml
} else {
const skipLeading = i === 0 && opts.stripFirstParaLeadingSpace === true
const patched = patchOneParagraph(para.xml, newParaTexts[i], skipLeading)
if (patched === null) return null
out += patched
}
cursor = para.end
}
out += entryXml.slice(cursor)
// Self-check: re-extracted text must match the target, otherwise abandon the surgical patch
const check = paragraphSlices(out).map((p, i) =>
i === 0 && opts.stripFirstParaLeadingSpace
? decodedTextOf(p.xml).replace(/^\s+/, '')
: decodedTextOf(p.xml),
)
return check.join('\n') === newText ? out : null
}
interface ParaSlice {
start: number
end: number
xml: string
}
function paragraphSlices(xml: string): ParaSlice[] {
// depth-aware scan: a paragraph may legally nest more <w:p> inside embedded
// textbox content (w:txbxContent), so a lazy open-to-first-close match would
// truncate the outer paragraph
const out: ParaSlice[] = []
const re = /<w:p(?:\s[^>]*)?\/>|<w:p(?:\s[^>]*)?>|<\/w:p>/g
let m: RegExpExecArray | null
let depth = 0
let start = -1
while ((m = re.exec(xml)) !== null) {
const token = m[0]
if (token === '</w:p>') {
if (depth === 0) continue
depth--
if (depth === 0 && start !== -1) {
const end = m.index + token.length
out.push({ start, end, xml: xml.slice(start, end) })
start = -1
}
} else if (token.endsWith('/>')) {
if (depth === 0) out.push({ start: m.index, end: m.index + token.length, xml: token })
} else {
if (depth === 0) start = m.index
depth++
}
}
return out
}
interface TSlice {
/** offsets of the inner content within the paragraph XML */
innerStart: number
innerEnd: number
/** offset of the opening <w:t ...> tag */
tagStart: number
text: string
}
function tSlices(paraXml: string): TSlice[] {
const out: TSlice[] = []
const re = /<w:t(\s[^>]*)?>([\s\S]*?)<\/w:t>/g
let m: RegExpExecArray | null
while ((m = re.exec(paraXml)) !== null) {
const inner = m[2]
const innerStart = m.index + m[0].length - inner.length - '</w:t>'.length
out.push({
tagStart: m.index,
innerStart,
innerEnd: innerStart + inner.length,
text: decodeEntities(inner),
})
}
return out
}
function decodedTextOf(paraXml: string): string {
return tSlices(paraXml)
.map((t) => t.text)
.join('')
}
function decodeEntities(s: string): string {
return s
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&amp;/g, '&')
}
function patchOneParagraph(paraXml: string, newText: string, skipLeading: boolean): string | null {
const slices = tSlices(paraXml)
if (slices.length === 0) return null
const raw = slices.map((t) => t.text).join('')
// First paragraph's leading whitespace (spacer run after the self-reference mark) is
// excluded from the diff and treated as an immutable prefix
const lead = skipLeading ? raw.length - raw.replace(/^\s+/, '').length : 0
const oldText = raw.slice(lead)
if (oldText === newText) return paraXml
let prefix = 0
const maxCommon = Math.min(oldText.length, newText.length)
while (prefix < maxCommon && oldText[prefix] === newText[prefix]) prefix++
let suffix = 0
while (
suffix < maxCommon - prefix &&
oldText[oldText.length - 1 - suffix] === newText[newText.length - 1 - suffix]
) {
suffix++
}
// Changed range (relative to the full raw text)
const changeStart = lead + prefix
const changeEnd = lead + oldText.length - suffix
const replacement = newText.slice(prefix, newText.length - suffix)
// Find the w:t intersecting the changed range; for pure insertion (changeStart ===
// changeEnd), take the slice covering that point
let acc = 0
let first = -1
let last = -1
const bounds: Array<{ start: number; end: number }> = []
for (let i = 0; i < slices.length; i++) {
const start = acc
const end = acc + slices[i].text.length
bounds.push({ start, end })
const touches =
changeStart === changeEnd
? start <= changeStart && changeStart <= end
: start < changeEnd && end > changeStart
if (touches) {
if (first === -1) first = i
last = i
}
acc = end
}
if (first === -1) {
// Insertion point falls outside every w:t (in theory only an empty paragraph) —
// no anchor, give up
return null
}
// Rewrite [first..last]: first takes the prefix remainder + replacement text + last's
// suffix remainder; the rest are emptied
const newInner: string[] = []
for (let i = first; i <= last; i++) {
if (i === first) {
const head = slices[i].text.slice(0, changeStart - bounds[i].start)
const tail = slices[last].text.slice(changeEnd - bounds[last].start)
newInner.push(escapeXmlText(head + replacement + tail))
} else {
newInner.push('')
}
}
// Replace back-to-front so offsets stay valid; changed w:t all get xml:space="preserve"
let out = paraXml
for (let i = last; i >= first; i--) {
const s = slices[i]
const closeEnd = s.innerEnd + '</w:t>'.length
out =
out.slice(0, s.tagStart) +
`<w:t xml:space="preserve">${newInner[i - first]}</w:t>` +
out.slice(closeEnd)
}
return out
}
+193
View File
@@ -0,0 +1,193 @@
import type { ThemeColors, ThemeFonts } from './types'
import { escapeXmlAttr } from './xml-utils'
/**
* Theme part support (word/theme/theme1.xml). Theme fonts rewrite the
* major/minor font pair; theme colors rewrite the a:clrScheme entries. Documents
* whose styles reference theme fonts/colors re-render in Word accordingly.
*/
export const THEME_PART_PATH = 'word/theme/theme1.xml'
export const THEME_REL_TYPE =
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme'
export const THEME_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.theme+xml'
/** read the latin major/minor typefaces (+major east-asian) from theme1.xml */
export function readThemeFonts(themeXml: string): ThemeFonts | null {
const major = fontOf(themeXml, 'a:majorFont')
const minor = fontOf(themeXml, 'a:minorFont')
if (!major && !minor) return null
const eaMatch = sectionOf(themeXml, 'a:minorFont')?.match(/<a:ea typeface="([^"]*)"/)
return {
major: major ?? '',
minor: minor ?? '',
...(eaMatch?.[1] ? { eastAsia: eaMatch[1] } : {}),
}
}
function sectionOf(xml: string, tag: string): string | null {
return new RegExp(`<${tag}(?:\\s[^>]*)?>[\\s\\S]*?</${tag}>`).exec(xml)?.[0] ?? null
}
function fontOf(xml: string, tag: string): string | null {
const section = sectionOf(xml, tag)
return section ? (/<a:latin typeface="([^"]*)"/.exec(section)?.[1] ?? null) : null
}
/** rewrite the latin (and optional east-asian) typefaces of one font group */
function applyFontGroup(xml: string, tag: string, typeface: string, eastAsia?: string): string {
const section = sectionOf(xml, tag)
if (!section) return xml
let next = section.replace(/(<a:latin typeface=")[^"]*(")/, `$1${escapeXmlAttr(typeface)}$2`)
if (eastAsia !== undefined) {
next = next.replace(/(<a:ea typeface=")[^"]*(")/, `$1${escapeXmlAttr(eastAsia)}$2`)
}
return xml.replace(section, next)
}
export function applyThemeFonts(themeXml: string, fonts: ThemeFonts): string {
let xml = applyFontGroup(themeXml, 'a:majorFont', fonts.major, fonts.eastAsia)
xml = applyFontGroup(xml, 'a:minorFont', fonts.minor, fonts.eastAsia)
return xml
}
const COLOR_TAGS = ['dk2', 'lt2', 'accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6'] as const
/** all clrScheme slots, including read-only ones (dk1/lt1 may be sysClr) */
const READ_TAGS = ['dk1', 'lt1', ...COLOR_TAGS, 'hlink', 'folHlink'] as const
export function readThemeColors(themeXml: string): ThemeColors | null {
const scheme = sectionOf(themeXml, 'a:clrScheme')
if (!scheme) return null
const out: ThemeColors = {}
const name = /<a:clrScheme name="([^"]*)"/.exec(themeXml)?.[1]
if (name) out.name = name
for (const tag of READ_TAGS) {
const m = new RegExp(
`<a:${tag}>\\s*<a:(?:srgbClr val|sysClr[^>]*? lastClr)="([0-9A-Fa-f]{6})"`,
).exec(scheme)
if (m) out[tag] = m[1].toUpperCase()
}
return Object.keys(out).length > 0 ? out : null
}
/** w:themeColor attribute value -> clrScheme slot (default clrSchemeMapping) */
const THEME_COLOR_SLOTS: Record<string, keyof ThemeColors> = {
dark1: 'dk1',
text1: 'dk1',
light1: 'lt1',
background1: 'lt1',
dark2: 'dk2',
text2: 'dk2',
light2: 'lt2',
background2: 'lt2',
accent1: 'accent1',
accent2: 'accent2',
accent3: 'accent3',
accent4: 'accent4',
accent5: 'accent5',
accent6: 'accent6',
hyperlink: 'hlink',
followedHyperlink: 'folHlink',
}
const SLOT_FALLBACK: Partial<Record<keyof ThemeColors, string>> = { dk1: '000000', lt1: 'FFFFFF' }
/**
* Resolve a w:themeColor reference (+ optional w:themeTint / w:themeShade,
* hex 00-FF) against the palette. sRGB per-channel approximation of Word's
* tint/shade math — close enough for display; w:val stays authoritative on save.
*/
export function resolveThemeColor(
themeColor: string,
colors: ThemeColors,
tint?: string,
shade?: string,
): string | null {
const slot = THEME_COLOR_SLOTS[themeColor]
if (!slot) return null
const base = (colors[slot] as string | undefined) ?? SLOT_FALLBACK[slot]
if (!base || !/^[0-9A-Fa-f]{6}$/.test(base)) return null
let rgb = [0, 2, 4].map((i) => parseInt(base.slice(i, i + 2), 16))
const factorOf = (hex?: string) => {
const v = hex ? parseInt(hex, 16) : NaN
return Number.isFinite(v) ? Math.max(0, Math.min(255, v)) / 255 : null
}
const s = factorOf(shade)
if (s !== null) rgb = rgb.map((c) => c * s)
const t = factorOf(tint)
if (t !== null) rgb = rgb.map((c) => c * t + 255 * (1 - t))
return rgb.map((c) => Math.round(c).toString(16).padStart(2, '0').toUpperCase()).join('')
}
export function applyThemeColors(themeXml: string, colors: ThemeColors): string {
let scheme = sectionOf(themeXml, 'a:clrScheme')
if (!scheme) return themeXml
const original = scheme
for (const tag of COLOR_TAGS) {
const value = colors[tag]
if (!value) continue
scheme = scheme.replace(
new RegExp(`(<a:${tag}>\\s*<a:srgbClr val=")[0-9A-Fa-f]{6}(")`),
`$1${value}$2`,
)
// sysClr entries (windowText etc.) are left alone; dk2/lt2 are usually srgbClr
}
let xml = themeXml.replace(original, scheme)
if (colors.name) {
xml = xml.replace(/(<a:clrScheme name=")[^"]*(")/, `$1${escapeXmlAttr(colors.name)}$2`)
}
return xml
}
/**
* Minimal but complete theme part for documents that have none (e.g. the
* blank template). Word requires fmtScheme; this ships the standard Office
* format scheme skeleton.
*/
export function buildThemeXml(fonts: ThemeFonts, colors: ThemeColors): string {
const c = (tag: (typeof COLOR_TAGS)[number], fallback: string) =>
`<a:${tag}><a:srgbClr val="${colors[tag] ?? fallback}"/></a:${tag}>`
const font = (tag: string, typeface: string) =>
`<${tag}><a:latin typeface="${escapeXmlAttr(typeface)}"/>` +
`<a:ea typeface="${escapeXmlAttr(fonts.eastAsia ?? '')}"/><a:cs typeface=""/></${tag}>`
return (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
'<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office">' +
'<a:themeElements>' +
`<a:clrScheme name="${escapeXmlAttr(colors.name ?? 'Office')}">` +
'<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>' +
'<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>' +
c('dk2', '44546A') +
c('lt2', 'E7E6E6') +
c('accent1', '4472C4') +
c('accent2', 'ED7D31') +
c('accent3', 'A5A5A5') +
c('accent4', 'FFC000') +
c('accent5', '5B9BD5') +
c('accent6', '70AD47') +
'<a:hlink><a:srgbClr val="0563C1"/></a:hlink>' +
'<a:folHlink><a:srgbClr val="954F72"/></a:folHlink>' +
'</a:clrScheme>' +
`<a:fontScheme name="Office">${font('a:majorFont', fonts.major)}${font('a:minorFont', fonts.minor)}</a:fontScheme>` +
'<a:fmtScheme name="Office">' +
'<a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:fillStyleLst>' +
'<a:lnStyleLst>' +
'<a:ln w="6350"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>' +
'<a:ln w="12700"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>' +
'<a:ln w="19050"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>' +
'</a:lnStyleLst>' +
'<a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle>' +
'<a:effectStyle><a:effectLst/></a:effectStyle>' +
'<a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst>' +
'<a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:bgFillStyleLst>' +
'</a:fmtScheme>' +
'</a:themeElements></a:theme>'
)
}
File diff suppressed because it is too large Load Diff
+61
View File
@@ -0,0 +1,61 @@
import { escapeXmlAttr } from './xml-utils'
/**
* Text watermark support. Word implements watermarks as a VML shape with a
* v:textpath inside the page header; the shape floats behind the body text
* on every page that uses that header.
*/
/** namespaces the header part root needs when it carries a VML watermark */
export const WATERMARK_NS =
' xmlns:v="urn:schemas-microsoft-com:vml"' +
' xmlns:o="urn:schemas-microsoft-com:office:office"' +
' xmlns:w10="urn:schemas-microsoft-com:office:word"'
/** read the watermark text from a header part; null when it has none */
export function readWatermarkText(headerXml: string): string | null {
if (!headerXml.includes('<v:textpath')) return null
const m = /<v:textpath[^>]*\bstring="([^"]*)"/.exec(headerXml)
if (!m) return null
const text = m[1]
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&amp;/g, '&')
return text || null
}
/**
* The diagonal gray text watermark paragraph Word generates (shapetype 136 =
* text-on-path). Lives as the first paragraph of the header part.
*/
export function watermarkParagraphXml(text: string): string {
const shape =
'<v:shape id="PowerPlusWaterMarkObject1" o:spid="_x0000_s2049" type="#_x0000_t136"' +
' style="position:absolute;left:0;text-align:left;margin-left:0;margin-top:0;' +
'width:412.4pt;height:247.45pt;rotation:315;z-index:-251656192;' +
'mso-position-horizontal:center;mso-position-horizontal-relative:margin;' +
'mso-position-vertical:center;mso-position-vertical-relative:margin"' +
' o:allowincell="f" fillcolor="silver" stroked="f">' +
'<v:fill opacity=".5"/>' +
`<v:textpath style="font-family:&quot;DengXian&quot;;font-size:1pt" string="${escapeXmlAttr(text)}"/>` +
'</v:shape>'
const shapetype =
'<v:shapetype id="_x0000_t136" coordsize="21600,21600" o:spt="136" adj="10800"' +
' path="m@7,l@8,m@5,21600l@6,21600e">' +
'<v:formulas>' +
'<v:f eqn="sum #0 0 10800"/><v:f eqn="prod #0 2 1"/><v:f eqn="sum 21600 0 @1"/>' +
'<v:f eqn="sum 0 0 @2"/><v:f eqn="sum 21600 0 @3"/><v:f eqn="if @0 @3 0"/>' +
'<v:f eqn="if @0 21600 @1"/><v:f eqn="if @0 0 @2"/><v:f eqn="if @0 @4 21600"/>' +
'<v:f eqn="mid @5 @6"/><v:f eqn="mid @8 @5"/><v:f eqn="mid @7 @8"/>' +
'<v:f eqn="mid @6 @7"/><v:f eqn="sum @6 0 @5"/>' +
'</v:formulas>' +
'<v:path textpathok="t" o:connecttype="custom" o:connectlocs="@9,0;@10,10800;@11,21600;@12,10800"' +
' o:connectangles="270,180,90,0"/>' +
'<v:textpath on="t" fitshape="t"/>' +
'<v:handles><v:h position="#0,bottomRight" xrange="6629,14971"/></v:handles>' +
'<o:lock v:ext="edit" text="t" shapetype="t"/>' +
'</v:shapetype>'
return `<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:pict>${shapetype}${shape}</w:pict></w:r></w:p>`
}
+121
View File
@@ -0,0 +1,121 @@
import { XMLParser } from 'fast-xml-parser'
/** preserveOrder node shape from fast-xml-parser */
export type XNode = Record<string, unknown>
export const xmlParser = new XMLParser({
preserveOrder: true,
ignoreAttributes: false,
attributeNamePrefix: '',
trimValues: false,
parseTagValue: false,
parseAttributeValue: false,
})
export function nameOf(node: XNode): string | undefined {
return Object.keys(node).find((k) => k !== ':@' && k !== '#text')
}
export function childrenOf(node: XNode): XNode[] {
const name = nameOf(node)
if (!name) return []
const value = node[name]
return Array.isArray(value) ? (value as XNode[]) : []
}
export function attrsOf(node: XNode): Record<string, string> {
return (node[':@'] as Record<string, string>) ?? {}
}
export function textOf(node: XNode): string {
let out = ''
for (const child of childrenOf(node)) {
if ('#text' in child) out += String(child['#text'])
else out += textOf(child)
}
return out
}
export function findChild(node: XNode, name: string): XNode | undefined {
return childrenOf(node).find((c) => nameOf(c) === name)
}
export function findChildren(node: XNode, name: string): XNode[] {
return childrenOf(node).filter((c) => nameOf(c) === name)
}
/**
* Direct children with `name`, looking through w:sdt → w:sdtContent wrappers
* (nested sdt included). Structured document tags may wrap table rows, cells
* or paragraphs at any level; for display purposes the wrapper is transparent
* (research-report templates wrap every field in an sdt).
*/
export function childrenThroughSdt(node: XNode, name: string): XNode[] {
const out: XNode[] = []
const visit = (n: XNode): void => {
for (const child of childrenOf(n)) {
const cn = nameOf(child)
if (cn === name) out.push(child)
else if (cn === 'w:sdt') {
const content = findChild(child, 'w:sdtContent')
if (content) visit(content)
}
}
}
visit(node)
return out
}
/** OOXML boolean property: present => true unless w:val says otherwise */
export function boolProp(parent: XNode, name: string): boolean {
const child = findChild(parent, name)
if (!child) return false
const val = attrsOf(child)['w:val']
if (val === undefined) return true
return !['0', 'false', 'none', 'off'].includes(val.toLowerCase())
}
/**
* w:u is NOT an OOXML boolean (CT_OnOff) — it is CT_Underline, where the
* underline pattern lives entirely in w:val. A <w:u> with no w:val (e.g.
* `<w:u w:color="415461"/>` as emitted by Pages/LibreOffice) means no
* underline, matching how Word renders it.
*/
export function underlineProp(parent: XNode): boolean {
const child = findChild(parent, 'w:u')
if (!child) return false
const val = attrsOf(child)['w:val']
return val !== undefined && val !== 'none'
}
/**
* XNode → XML text (attribute order = parse order, empty elements self-close). Semantic
* fidelity, not byte fidelity: used to store parse-tree fragments (e.g. a run's rPr) as
* writable source slices.
*/
export function serializeXNode(node: XNode): string {
if ('#text' in node) return escapeXmlText(String(node['#text']))
const name = nameOf(node)
if (!name) return ''
const attrs = Object.entries(attrsOf(node))
.map(([k, v]) => ` ${k}="${escapeXmlAttr(String(v))}"`)
.join('')
const inner = childrenOf(node).map(serializeXNode).join('')
return inner === '' ? `<${name}${attrs}/>` : `<${name}${attrs}>${inner}</${name}>`
}
// Control characters outside \t \n \r are illegal in XML 1.0 even when escaped
// eslint-disable-next-line no-control-regex
const ILLEGAL_XML_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g
export function escapeXmlText(text: string): string {
return text
.replace(ILLEGAL_XML_CHARS, '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
}
export function escapeXmlAttr(text: string): string {
return escapeXmlText(text).replace(/"/g, '&quot;')
}
+57
View File
@@ -0,0 +1,57 @@
import { describe, expect, it } from 'vitest'
import { mergePPrFormat, parseDocx, saveDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const BIDI_BODY =
'<w:p><w:pPr><w:bidi/><w:jc w:val="right"/></w:pPr><w:r><w:t>כותרת</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:bidi/><w:jc w:val="left"/></w:pPr><w:r><w:t>שמאל</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:bidi/></w:pPr><w:r><w:t>ברירת מחדל</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:t>LTR right</w:t></w:r></w:p>'
describe('RTL paragraphs (w:bidi + Word jc left/right swap)', () => {
it('parses bidi and stores the visual alignment (jc left/right swapped)', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BIDI_BODY }))
expect(doc.blocks[0].format).toMatchObject({ bidi: true, align: 'left' })
expect(doc.blocks[1].format).toMatchObject({ bidi: true, align: 'right' })
expect(doc.blocks[2].format?.bidi).toBe(true)
expect(doc.blocks[2].format?.align).toBeUndefined()
// non-bidi paragraphs are not swapped
expect(doc.blocks[3].format?.bidi).toBeUndefined()
expect(doc.blocks[3].format?.align).toBe('right')
})
it('keeps untouched bidi paragraphs byte-identical', async () => {
const bytes = await buildDocx({ bodyXml: BIDI_BODY })
const doc = await parseDocx(bytes)
const blocks = doc.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
expect(await saveDocx(doc, blocks)).toEqual(bytes)
})
it('mergePPrFormat writes the logical jc back and keeps a single w:bidi', () => {
const out = mergePPrFormat('<w:pPr><w:bidi/><w:jc w:val="right"/></w:pPr>', {
bidi: true,
align: 'left',
})
expect(out.match(/<w:bidi\/>/g)).toHaveLength(1)
expect(out).toContain('<w:jc w:val="right"/>')
// visual right maps back to logical left
const out2 = mergePPrFormat('<w:pPr><w:bidi/><w:jc w:val="left"/></w:pPr>', {
bidi: true,
align: 'right',
})
expect(out2).toContain('<w:jc w:val="left"/>')
})
})
describe('RTL tables (tblPr w:bidiVisual)', () => {
it('parses bidiVisual into the table model', async () => {
const xml =
'<w:tbl><w:tblPr><w:bidiVisual/><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
'<w:tr><w:tc><w:p><w:r><w:t>א</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
expect(doc.blocks[0].table?.bidiVisual).toBe(true)
})
})
@@ -0,0 +1,58 @@
import { describe, expect, it } from 'vitest'
import {
BLANK_BULLET_NUM_ID,
BLANK_ORDERED_NUM_ID,
buildBlankDocx,
parseDocx,
saveDocx,
type SaveBlock,
} from '../src/index'
describe('blank document template (new-document / AI generation base)', () => {
it('parses to a single empty paragraph with standard heading styles available', async () => {
const bytes = await buildBlankDocx()
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden)
expect(visible).toHaveLength(1)
expect(visible[0].type).toBe('paragraph')
for (const styleId of ['Heading1', 'Heading2', 'Heading3', 'Heading6']) {
expect(doc.styles.has(styleId), styleId).toBe(true)
}
})
it('AI-generated content (headings, paragraphs, lists) saves and reparses correctly', async () => {
const bytes = await buildBlankDocx()
const doc = await parseDocx(bytes)
const generated: SaveBlock[] = [
{ kind: 'generated', block: { type: 'heading', level: 1, runs: [{ text: '生成的标题' }] } },
{ kind: 'generated', block: { type: 'paragraph', runs: [{ text: '正文段落,', bold: false }, { text: '重点', bold: true }] } },
{
kind: 'generated',
block: {
type: 'listItem',
list: { kind: 'bullet', numId: BLANK_BULLET_NUM_ID, ilvl: 0 },
runs: [{ text: '无序项' }],
},
},
{
kind: 'generated',
block: {
type: 'listItem',
list: { kind: 'ordered', numId: BLANK_ORDERED_NUM_ID, ilvl: 0 },
runs: [{ text: '有序项' }],
},
},
]
const saved = await saveDocx(doc, generated)
const reparsed = await parseDocx(saved)
const visible = reparsed.blocks.filter((b) => !b.hidden)
expect(visible.map((b) => b.type)).toEqual(['heading', 'paragraph', 'listItem', 'listItem'])
expect(visible[0].level).toBe(1)
expect(visible[0].runs?.map((r) => r.text).join('')).toBe('生成的标题')
expect(visible[1].runs?.some((r) => r.bold && r.text === '重点')).toBe(true)
expect(visible[2].list?.kind).toBe('bullet')
expect(visible[3].list?.kind).toBe('ordered')
})
})
@@ -0,0 +1,120 @@
import { describe, expect, it } from 'vitest'
import { generateParagraphXml, parseDocx, saveDocx, type GenerateContext } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const GEN_CTX: GenerateContext = {
headingStyleIds: new Map([[1, 'Heading1']]),
allocateHyperlinkRel: () => 'rId999',
}
const BOOKMARKED_PARA =
'<w:p><w:bookmarkStart w:id="3" w:name="市场规模"/><w:bookmarkEnd w:id="3"/>' +
'<w:bookmarkStart w:id="4" w:name="_GoBack"/><w:bookmarkEnd w:id="4"/>' +
'<w:r><w:t>2025 年市场规模达到 1200 亿。</w:t></w:r></w:p>'
const REF_PARA =
'<w:p><w:r><w:t xml:space="preserve">详见</w:t></w:r>' +
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:instrText xml:space="preserve"> REF 市场规模 \\h </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:r><w:t>2025 年市场规模达到 1200 亿。</w:t></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
'<w:r><w:t xml:space="preserve">一节。</w:t></w:r></w:p>'
describe('bookmarks', () => {
it('parses user bookmarks and splits Word internals into hiddenBookmarks', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BOOKMARKED_PARA }))
expect(doc.blocks[0].type).toBe('paragraph')
expect(doc.blocks[0].bookmarks).toEqual(['市场规模'])
expect(doc.blocks[0].hiddenBookmarks).toEqual(['_GoBack'])
})
it('re-emits hidden (_Ref/_Toc) bookmarks on regeneration so REF anchors survive editing', async () => {
const body =
'<w:p><w:bookmarkStart w:id="7" w:name="_Ref12345"/><w:bookmarkEnd w:id="7"/>' +
'<w:r><w:t>被引用的段落。</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: body }))
const block = doc.blocks[0]
expect(block.hiddenBookmarks).toEqual(['_Ref12345'])
// Rebuild after editing the paragraph text → the _Ref bookmark survives (lost here
// before the broken-link fix)
const saved = await saveDocx(doc, [
{
kind: 'generated',
block: {
type: 'paragraph',
hiddenBookmarks: block.hiddenBookmarks,
runs: [{ text: '改过的段落。' }],
},
},
])
const reparsed = await parseDocx(saved)
expect(reparsed.blocks[0].hiddenBookmarks).toEqual(['_Ref12345'])
})
it('re-emits bookmarkStart/End pairs on regeneration', () => {
const xml = generateParagraphXml(
{ type: 'paragraph', bookmarks: ['目标位置'], runs: [{ text: '正文' }] },
GEN_CTX,
)
const id = /<w:bookmarkStart w:id="(\d+)" w:name="目标位置"\/>/.exec(xml)?.[1]
expect(id).toBeTruthy()
expect(xml).toContain(`<w:bookmarkEnd w:id="${id}"/>`)
expect(xml.indexOf('<w:bookmarkStart')).toBeLessThan(xml.indexOf('<w:r>'))
})
it('round-trips bookmarks through generate -> parse', async () => {
const para = generateParagraphXml(
{ type: 'paragraph', bookmarks: ['章节A'], runs: [{ text: 'x' }] },
GEN_CTX,
)
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
expect(doc.blocks[0].bookmarks).toEqual(['章节A'])
})
})
describe('cross-references (REF fields)', () => {
it('keeps REF paragraphs editable and folds the field into Run.refField', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: REF_PARA }))
const block = doc.blocks[0]
expect(block.type).toBe('paragraph')
const runs = block.runs!
expect(runs.map((r) => r.text)).toEqual(['详见', '2025 年市场规模达到 1200 亿。', '一节。'])
expect(runs[1].refField).toBe('市场规模')
expect(runs[0].refField).toBeUndefined()
})
it('regenerates the full REF field with cached display text', () => {
const xml = generateParagraphXml(
{
type: 'paragraph',
runs: [{ text: '见' }, { text: '第一章', refField: 'chap1' }, { text: '。' }],
},
GEN_CTX,
)
expect(xml).toContain('<w:instrText xml:space="preserve"> REF chap1 \\h </w:instrText>')
expect(xml).toContain('<w:fldChar w:fldCharType="separate"/>')
expect(xml).toContain('<w:t xml:space="preserve">第一章</w:t>')
expect(xml.indexOf('fldCharType="begin"')).toBeLessThan(xml.indexOf('第一章'))
expect(xml.indexOf('第一章')).toBeLessThan(xml.indexOf('fldCharType="end"'))
})
it('round-trips a REF run through generate -> parse', async () => {
const para = generateParagraphXml(
{ type: 'paragraph', runs: [{ text: '目标内容', refField: 'target' }] },
GEN_CTX,
)
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
expect(doc.blocks[0].runs![0]).toMatchObject({ text: '目标内容', refField: 'target' })
})
it('keeps untouched bookmark/REF paragraphs byte-identical on save', async () => {
const source = await buildDocx({ bodyXml: BOOKMARKED_PARA + REF_PARA })
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [
{ kind: 'original', docxIndex: 0 },
{ kind: 'original', docxIndex: 1 },
])
expect(saved).toEqual(source)
})
})
@@ -0,0 +1,127 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import {
applySectionSettings,
buildChartWorkbookXlsxBase64,
latexToOmml,
nextNoteId,
ommlToLatex,
parseDocx,
patchChartWorkbookXlsxBase64,
readSections,
saveDocx,
sectionSettingsFromXml,
type SaveBlock,
} from '../src/index'
import { patchParagraphTexts } from '../src/text-patch'
import { escapeXmlText } from '../src/xml-utils'
import { buildDocx } from './helpers/build-docx'
const P = (text: string) => `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`
describe('saveDocx isUnchanged short-circuit', () => {
it('a sectionStartType-only edit is not silently dropped', async () => {
const bytes = await buildDocx({ bodyXml: P('a') + P('b') })
const parsed = await parseDocx(bytes)
const visible: SaveBlock[] = parsed.blocks
.filter((b) => !b.hidden)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
const saved = await saveDocx(parsed, visible, { sectionStartType: 'continuous' })
expect(saved).not.toBe(bytes)
const sections = readSections(await parseDocx(saved))
expect(sections[0].startType).toBe('continuous')
})
})
describe('applySectionSettings w:cols', () => {
const SECT_PR =
'<w:sectPr><w:pgSz w:w="11906" w:h="16838"/>' +
'<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>' +
'<w:cols w:num="3" w:space="720">' +
'<w:col w:w="3000" w:space="720"/><w:col w:w="3600" w:space="720"/><w:col w:w="2000"/>' +
'</w:cols></w:sectPr>'
it('keeps explicit column widths when the count is unchanged', () => {
const settings = sectionSettingsFromXml(SECT_PR)
expect(settings.columns).toBe(3)
const out = applySectionSettings(SECT_PR, settings)
expect(out.match(/<w:cols[\s>]/g)?.length).toBe(1)
expect(out).toContain('<w:col w:w="3000"')
})
it('replaces the open-form element without duplicating it when the count changes', () => {
const settings = sectionSettingsFromXml(SECT_PR)
const out = applySectionSettings(SECT_PR, { ...settings, columns: 2 })
expect(out.match(/<w:cols[\s>]/g)?.length).toBe(1)
expect(out).toContain('w:num="2"')
expect(out).not.toContain('<w:col w:w=')
})
})
describe('patchParagraphTexts with nested textbox paragraphs', () => {
const ENTRY =
'<w:comment w:id="1">' +
'<w:p><w:r><w:t xml:space="preserve">outer </w:t></w:r>' +
'<w:r><w:drawing><wps:txbx><w:txbxContent>' +
'<w:p><w:r><w:t>inside box</w:t></w:r></w:p>' +
'</w:txbxContent></wps:txbx></w:drawing></w:r>' +
'<w:r><w:t>tail</w:t></w:r></w:p>' +
'<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>second</w:t></w:r></w:p>' +
'</w:comment>'
it('slices the outer paragraph past the embedded w:p and patches surgically', () => {
const out = patchParagraphTexts(ENTRY, 'outer inside boxtail\nsecond edited')
expect(out).not.toBeNull()
// the textbox structure of the untouched paragraph survives byte-for-byte
expect(out).toContain(
'<w:txbxContent><w:p><w:r><w:t>inside box</w:t></w:r></w:p></w:txbxContent>',
)
expect(out).toContain('second edited')
expect(out).toContain('<w:rPr><w:b/></w:rPr>')
})
})
describe('escapeXmlText', () => {
it('strips control characters that are illegal in XML 1.0 but keeps tab/newline', () => {
expect(escapeXmlText('a\u0000b\u000Bc\td\ne')).toBe('abc\td\ne')
expect(escapeXmlText('<a & b>')).toBe('&lt;a &amp; b&gt;')
})
})
describe('nextNoteId', () => {
it('starts at 1 for a document with no existing notes', () => {
expect(nextNoteId([])).toBe('1')
})
})
describe('ommlToLatex matrix environments', () => {
it('recovers the named pmatrix environment instead of generic delimiters', () => {
const omml = `<m:oMath>${latexToOmml('\\begin{pmatrix} 1 & 0 \\\\ 0 & 1 \\end{pmatrix}')}</m:oMath>`
expect(ommlToLatex(omml)).toContain('\\begin{pmatrix}')
})
})
describe('patchChartWorkbookXlsxBase64', () => {
it('preserves unrelated workbook parts and updates Sheet1 in place', async () => {
const base = await buildChartWorkbookXlsxBase64(['a', 'b'], [{ name: 'S1', values: [1, 2] }])
const zip = await JSZip.loadAsync(Buffer.from(base, 'base64'))
zip.file('xl/styles.xml', '<styleSheet/>')
zip.file('xl/worksheets/sheet2.xml', '<worksheet><sheetData/></worksheet>')
const withExtras = Buffer.from(await zip.generateAsync({ type: 'uint8array' })).toString(
'base64',
)
const patched = await patchChartWorkbookXlsxBase64(
withExtras,
['x', 'y'],
[{ name: 'S1', values: [9, 8] }],
)
expect(patched).not.toBeNull()
const outZip = await JSZip.loadAsync(Buffer.from(patched!, 'base64'))
expect(outZip.file('xl/styles.xml')).toBeTruthy()
expect(outZip.file('xl/worksheets/sheet2.xml')).toBeTruthy()
const sheet = await outZip.file('xl/worksheets/sheet1.xml')!.async('string')
expect(sheet).toContain('<v>9</v>')
expect(sheet).toContain('>x</t>')
})
})
@@ -0,0 +1,198 @@
import { describe, expect, it } from 'vitest'
import { generateParagraphXml, parseDocx, type GenerateContext } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const GEN_CTX: GenerateContext = {
headingStyleIds: new Map([[1, 'Heading1']]),
allocateHyperlinkRel: () => 'rId999',
}
const EMPHASIS_STYLES =
'<w:style w:type="character" w:styleId="Strong"><w:name w:val="Strong"/>' +
'<w:rPr><w:b/><w:color w:val="C00000"/></w:rPr></w:style>' +
'<w:style w:type="character" w:styleId="Emphasis"><w:name w:val="Emphasis"/><w:basedOn w:val="Strong"/>' +
'<w:rPr><w:i/><w:u w:val="single"/></w:rPr></w:style>'
describe('character styles (w:rStyle)', () => {
it('parses character styles into the styles map with resolved basedOn display', async () => {
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
extraStylesXml: EMPHASIS_STYLES,
})
const doc = await parseDocx(bytes)
const strong = doc.styles.get('Strong')!
expect(strong.type).toBe('character')
expect(strong.display).toMatchObject({ bold: true, color: 'C00000' })
const emphasis = doc.styles.get('Emphasis')!
// inherits bold/color from Strong, adds its own italic/underline
expect(emphasis.display).toMatchObject({
bold: true,
color: 'C00000',
italic: true,
underline: true,
})
expect(doc.styles.get('Hyperlink')!.display).toMatchObject({ underline: true, color: '0563C1' })
})
it('captures w:rStyle on runs, except the implied Hyperlink style', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:r><w:rPr><w:rStyle w:val="Emphasis"/></w:rPr><w:t>styled</w:t></w:r>' +
'<w:r><w:t>plain</w:t></w:r>' +
'<w:hyperlink r:id="rId20"><w:r><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t>link</w:t></w:r></w:hyperlink></w:p>',
extraStylesXml: EMPHASIS_STYLES,
extraRels:
'<Relationship Id="rId20" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/" TargetMode="External"/>',
})
const doc = await parseDocx(bytes)
const runs = doc.blocks[0].runs!
expect(runs[0].styleId).toBe('Emphasis')
expect(runs[1].styleId).toBeUndefined()
expect(runs[2].link?.href).toBe('https://example.com/')
expect(runs[2].styleId).toBeUndefined()
})
it('does not merge adjacent runs with different character styles', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:r><w:rPr><w:rStyle w:val="Strong"/></w:rPr><w:t>a</w:t></w:r>' +
'<w:r><w:rPr><w:rStyle w:val="Emphasis"/></w:rPr><w:t>b</w:t></w:r></w:p>',
extraStylesXml: EMPHASIS_STYLES,
})
const doc = await parseDocx(bytes)
expect(doc.blocks[0].runs!.map((r) => r.styleId)).toEqual(['Strong', 'Emphasis'])
})
it('regenerates w:rStyle first in rPr schema order', () => {
const xml = generateParagraphXml(
{ type: 'paragraph', runs: [{ text: 'x', styleId: 'Emphasis', bold: true, font: '宋体' }] },
GEN_CTX,
)
expect(xml).toContain('<w:rStyle w:val="Emphasis"/>')
expect(xml.indexOf('<w:rStyle')).toBeLessThan(xml.indexOf('<w:rFonts'))
})
it('round-trips styleId through generate -> parse', async () => {
const para = generateParagraphXml(
{ type: 'paragraph', runs: [{ text: '强调', styleId: 'Emphasis' }] },
GEN_CTX,
)
const bytes = await buildDocx({ bodyXml: para, extraStylesXml: EMPHASIS_STYLES })
const doc = await parseDocx(bytes)
expect(doc.blocks[0].runs![0].styleId).toBe('Emphasis')
})
it('resolves paragraph style basedOn chains and survives cycles', async () => {
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
extraStylesXml:
'<w:style w:type="paragraph" w:styleId="Base"><w:name w:val="Base"/>' +
'<w:rPr><w:rFonts w:ascii="Georgia"/><w:sz w:val="20"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Base"/>' +
'<w:rPr><w:i/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="CycA"><w:name w:val="CycA"/><w:basedOn w:val="CycB"/></w:style>' +
'<w:style w:type="paragraph" w:styleId="CycB"><w:name w:val="CycB"/><w:basedOn w:val="CycA"/></w:style>',
})
const doc = await parseDocx(bytes)
expect(doc.styles.get('Quote')!.display).toMatchObject({
italic: true,
font: 'Georgia',
sizeHalfPoints: 20,
})
expect(doc.styles.get('CycA')).toBeDefined()
expect(doc.styles.get('CycB')).toBeDefined()
})
})
describe('linkedStyle (w:link) and docDefaults backfill', () => {
it('when a character-style shell has no rPr, run-level display attributes come from the linked paragraph style', async () => {
const styles =
'<w:style w:type="paragraph" w:styleId="Heading9"><w:name w:val="heading 9"/>' +
'<w:link w:val="Heading9Char"/>' +
'<w:rPr><w:b/><w:color w:val="2F5496"/><w:sz w:val="24"/></w:rPr></w:style>' +
'<w:style w:type="character" w:styleId="Heading9Char"><w:name w:val="标题 9 字符"/>' +
'<w:link w:val="Heading9"/></w:style>'
const doc = await parseDocx(
await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>', extraStylesXml: styles }),
)
expect(doc.styles.get('Heading9Char')!.display).toMatchObject({
bold: true,
color: '2F5496',
sizeHalfPoints: 24,
})
// A style's own properties are not overridden by the link
const styles2 =
'<w:style w:type="paragraph" w:styleId="Quote2"><w:name w:val="Quote2"/>' +
'<w:link w:val="Quote2Char"/><w:rPr><w:i/><w:color w:val="404040"/></w:rPr></w:style>' +
'<w:style w:type="character" w:styleId="Quote2Char"><w:name w:val="Quote2 Char"/>' +
'<w:link w:val="Quote2"/><w:rPr><w:color w:val="FF0000"/></w:rPr></w:style>'
const doc2 = await parseDocx(
await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>', extraStylesXml: styles2 }),
)
expect(doc2.styles.get('Quote2Char')!.display).toMatchObject({ italic: true, color: 'FF0000' })
})
it('docDefaults parses bold/italic/color from rPrDefault', async () => {
const zipBytes = await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' })
// buildDocx's styles.xml has no docDefaults: inject it manually
const JSZip = (await import('jszip')).default
const zip = await JSZip.loadAsync(zipBytes)
const stylesXml = await zip.file('word/styles.xml')!.async('string')
zip.file(
'word/styles.xml',
stylesXml.replace(
/(<w:styles[^>]*>)/,
'$1<w:docDefaults><w:rPrDefault><w:rPr>' +
'<w:b/><w:i w:val="0"/><w:color w:val="333333"/><w:sz w:val="21"/>' +
'</w:rPr></w:rPrDefault></w:docDefaults>',
),
)
const doc = await parseDocx(await zip.generateAsync({ type: 'uint8array' }))
expect(doc.docDefaults).toMatchObject({ bold: true, color: '333333', sizeHalfPoints: 21 })
expect(doc.docDefaults?.italic).toBeUndefined()
})
})
describe('styleUpserts style write-back', () => {
it('new styles are appended, modified styles are replaced in place', async () => {
const { saveDocx } = await import('../src/index')
const parsed = await parseDocx(
await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }),
)
const blocks = parsed.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
const saved = await saveDocx(parsed, blocks, {
styleUpserts: [
{
styleId: 'MyQuote',
type: 'paragraph',
name: '我的引用',
basedOn: 'Normal',
rPr: { italic: true, color: '595959', sizeHalfPoints: 20 },
pPr: { align: 'center', spaceBeforeTwips: 120, spaceAfterTwips: 120 },
},
],
})
const reparsed = await parseDocx(saved)
const st = reparsed.styles.get('MyQuote')!
expect(st.name).toBe('我的引用')
expect(st.display).toMatchObject({ italic: true, color: '595959', sizeHalfPoints: 20 })
// Modify: upsert the same styleId again — replaces instead of duplicating
const parsed2 = await parseDocx(saved)
const blocks2 = parsed2.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
const saved2 = await saveDocx(parsed2, blocks2, {
styleUpserts: [
{ styleId: 'MyQuote', type: 'paragraph', name: '我的引用', rPr: { bold: true } },
],
})
const zip = await (await import('jszip')).default.loadAsync(saved2)
const stylesXml = await zip.file('word/styles.xml')!.async('string')
expect(stylesXml.match(/w:styleId="MyQuote"/g)).toHaveLength(1)
const reparsed2 = await parseDocx(saved2)
expect(reparsed2.styles.get('MyQuote')!.display).toMatchObject({ bold: true })
expect(reparsed2.styles.get('MyQuote')!.display?.italic).toBeUndefined()
})
})
@@ -0,0 +1,120 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import { parseChartPartXml, parseDocx, patchChartPartXml, saveDocx } from '../src/index'
import { CHART_PART_XML, buildChartDocx } from './helpers/build-docx'
describe('chart part parsing', () => {
it('reads kind, title, categories and cached series values', () => {
const display = parseChartPartXml(CHART_PART_XML, 'word/charts/chart1.xml')
expect(display).toMatchObject({
partPath: 'word/charts/chart1.xml',
kind: 'bar',
title: '销售统计',
categories: ['一月', '二月', '三月'],
})
expect(display?.series).toEqual([
{ name: '华东', values: [120, 88.5, 96] },
{ name: '华南', values: [70, null, 110] },
])
})
it('surfaces the chart model on the protected block and keeps the part XML', async () => {
const parsed = await parseDocx(await buildChartDocx())
const block = parsed.blocks.find((b) => b.label === 'Chart')
expect(block?.type).toBe('passthrough')
expect(block?.chartDisplay?.title).toBe('销售统计')
expect(block?.chartDisplay?.series[0].values).toEqual([120, 88.5, 96])
expect(parsed.extras.chartParts['word/charts/chart1.xml']).toBe(CHART_PART_XML)
})
it('returns null for parts without cached series', () => {
const empty =
'<c:chartSpace xmlns:c="x"><c:chart><c:plotArea><c:scatterChart>' +
'<c:ser><c:idx val="0"/></c:ser></c:scatterChart></c:plotArea></c:chart></c:chartSpace>'
expect(parseChartPartXml(empty, 'word/charts/chart2.xml')).toBeNull()
})
})
describe('patchChartPartXml', () => {
it('patches title, series name, values and categories; keeps refs and structure', () => {
const patched = patchChartPartXml(CHART_PART_XML, {
title: '2026 营收 & 目标',
categories: [null, '2月', null],
series: [{ name: '华东大区', values: [null, 99, null] }, null],
})
// structure and data references stay byte-identical
expect(patched).toContain('<c:f>Sheet1!$B$2:$B$4</c:f>')
expect(patched).toContain('<c:formatCode>General</c:formatCode>')
expect(patched).toContain('<c:barDir val="col"/>')
// title collapses into the first run, second run blanked, entities escaped
expect(patched).toContain('<a:t>2026 营收 &amp; 目标</a:t>')
expect(patched).toContain('<a:t></a:t>')
// targeted cache edits only
expect(patched).toContain('<c:v>华东大区</c:v>')
expect(patched).toContain('<c:v>华南</c:v>')
expect(patched).toContain('<c:v>99</c:v>')
expect(patched).toContain('<c:v>120</c:v>')
expect(patched).toContain('<c:v>2月</c:v>')
expect(patched).not.toContain('<c:v>88.5</c:v>')
const reparsed = parseChartPartXml(patched, 'word/charts/chart1.xml')
expect(reparsed?.title).toBe('2026 营收 & 目标')
expect(reparsed?.categories).toEqual(['一月', '2月', '三月'])
expect(reparsed?.series).toEqual([
{ name: '华东大区', values: [120, 99, 96] },
{ name: '华南', values: [70, null, 110] },
])
})
it('ignores edits it cannot anchor (gap points, missing title) and empty patches', () => {
// idx 1 of series 2 has no cached pt: the edit is skipped, not invented
const gap = patchChartPartXml(CHART_PART_XML, { series: [null, { values: [null, 42, null] }] })
expect(gap).toBe(CHART_PART_XML)
const noTitle = CHART_PART_XML.replace(/<c:title>[\s\S]*?<\/c:title>/, '')
expect(patchChartPartXml(noTitle, { title: '新标题' })).toBe(noTitle)
expect(patchChartPartXml(CHART_PART_XML, {})).toBe(CHART_PART_XML)
})
})
describe('chart save round-trip', () => {
it('saves a patched chart part via partXml and leaves everything else untouched', async () => {
const source = await buildChartDocx()
const parsed = await parseDocx(source)
const originalPart = parsed.extras.chartParts['word/charts/chart1.xml']
const patchedPart = patchChartPartXml(originalPart, {
title: '更新后的标题',
series: [{ values: [200, null, null] }, null],
})
const visible = parsed.blocks.filter((b) => !b.hidden)
const saved = await saveDocx(
parsed,
visible.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
{ partXml: { 'word/charts/chart1.xml': patchedPart } },
)
const reparsed = await parseDocx(saved)
const block = reparsed.blocks.find((b) => b.label === 'Chart')
expect(block?.chartDisplay?.title).toBe('更新后的标题')
expect(block?.chartDisplay?.series[0].values).toEqual([200, 88.5, 96])
// the body paragraph is byte-identical; only the chart part changed
const [oldZip, newZip] = await Promise.all([JSZip.loadAsync(source), JSZip.loadAsync(saved)])
expect(await newZip.file('word/document.xml')!.async('string')).toBe(
await oldZip.file('word/document.xml')!.async('string'),
)
expect(await newZip.file('word/styles.xml')!.async('string')).toBe(
await oldZip.file('word/styles.xml')!.async('string'),
)
})
it('stays byte-stable when no chart edit is made', async () => {
const source = await buildChartDocx()
const parsed = await parseDocx(source)
const visible = parsed.blocks.filter((b) => !b.hidden)
const saved = await saveDocx(
parsed,
visible.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
)
expect(saved).toEqual(source)
})
})
@@ -0,0 +1,151 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import {
buildChartPartXml,
buildChartWorkbookXlsxBase64,
parseChartPartXml,
parseDocx,
patchChartWorkbookXlsxBase64,
saveDocx,
} from '../src/index'
import { buildDocx } from './helpers/build-docx'
const SPEC = {
kind: 'bar' as const,
title: '季度销售',
categories: ['Q1', 'Q2', 'Q3'],
series: [
{ name: '华东', values: [120, 88.5, 96] },
{ name: '华南', values: [70, null, 110] },
],
}
describe('buildChartPartXml', () => {
it('produces a part our own parser reads back', () => {
const xml = buildChartPartXml(SPEC)
const display = parseChartPartXml(xml, 'word/charts/chart1.xml')!
expect(display.kind).toBe('bar')
expect(display.title).toBe('季度销售')
expect(display.categories).toEqual(['Q1', 'Q2', 'Q3'])
expect(display.series).toEqual([
{ name: '华东', values: [120, 88.5, 96] },
{ name: '华南', values: [70, null, 110] },
])
})
it('emits axes for bar/line and none for pie', () => {
expect(buildChartPartXml(SPEC)).toContain('<c:catAx>')
expect(buildChartPartXml({ ...SPEC, kind: 'line' })).toContain('<c:lineChart>')
const pie = buildChartPartXml({ ...SPEC, kind: 'pie', series: [SPEC.series[0]] })
expect(pie).toContain('<c:pieChart>')
expect(pie).not.toContain('<c:catAx>')
})
})
describe('saveDocx kind:chart', () => {
it('creates the part, relationship, content type and drawing paragraph', async () => {
const source = await buildDocx({ bodyXml: '<w:p><w:r><w:t>前文</w:t></w:r></w:p>' })
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [
{ kind: 'original', docxIndex: 0 },
{ kind: 'chart', chart: SPEC },
])
const zip = await JSZip.loadAsync(saved)
expect(zip.file('word/charts/chart1.xml')).toBeTruthy()
const contentTypes = await zip.file('[Content_Types].xml')!.async('string')
expect(contentTypes).toContain('/word/charts/chart1.xml')
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
expect(rels).toContain('charts/chart1.xml')
const reparsed = await parseDocx(saved)
const chartBlock = reparsed.blocks.find((b) => b.chartDisplay)
expect(chartBlock?.chartDisplay?.title).toBe('季度销售')
expect(chartBlock?.chartDisplay?.series[1].values).toEqual([70, null, 110])
})
it('allocates distinct part names for multiple charts in one save', async () => {
const source = await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' })
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [
{ kind: 'original', docxIndex: 0 },
{ kind: 'chart', chart: SPEC },
{ kind: 'chart', chart: { ...SPEC, kind: 'pie', title: '占比' } },
])
const zip = await JSZip.loadAsync(saved)
expect(zip.file('word/charts/chart1.xml')).toBeTruthy()
expect(zip.file('word/charts/chart2.xml')).toBeTruthy()
const reparsed = await parseDocx(saved)
const charts = reparsed.blocks.filter((b) => b.chartDisplay)
expect(charts).toHaveLength(2)
expect(charts[1].chartDisplay?.kind).toBe('pie')
})
})
describe('chart embedded workbook', () => {
it('buildChartWorkbookXlsxBase64 produces a valid xlsx with correct sheet data', async () => {
const base64 = await buildChartWorkbookXlsxBase64(
['Q1', 'Q2', 'Q3'],
[
{ name: '华东', values: [120, 88, 96] },
{ name: '华南', values: [70, 80, 110] },
],
)
expect(typeof base64).toBe('string')
expect(base64.length).toBeGreaterThan(0)
// Decode and verify it's a valid zip with the expected parts
const binaryStr = atob(base64)
const bytes = new Uint8Array(binaryStr.length)
for (let i = 0; i < binaryStr.length; i++) bytes[i] = binaryStr.charCodeAt(i)
const xlsx = await JSZip.loadAsync(bytes)
expect(xlsx.file('xl/workbook.xml')).toBeTruthy()
expect(xlsx.file('xl/worksheets/sheet1.xml')).toBeTruthy()
expect(xlsx.file('xl/sharedStrings.xml')).toBeTruthy()
const sheet = await xlsx.file('xl/worksheets/sheet1.xml')!.async('string')
// Sheet uses shared string indices (t="s"), numeric values are inline
expect(sheet).toContain('<v>120</v>')
const ss = await xlsx.file('xl/sharedStrings.xml')!.async('string')
// Category labels Q1/Q2/Q3 live in the shared strings table
expect(ss).toContain('Q1')
expect(ss).toContain('华东')
expect(ss).toContain('华南')
})
it('saveDocx kind:chart embeds the workbook file and chart rels', async () => {
const source = await buildDocx({ bodyXml: '<w:p><w:r><w:t>前文</w:t></w:r></w:p>' })
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [
{ kind: 'original', docxIndex: 0 },
{ kind: 'chart', chart: SPEC },
])
const zip = await JSZip.loadAsync(saved)
// Workbook file must exist
expect(zip.file('word/charts/embeddings/workbook1.xlsx')).toBeTruthy()
// Chart rels must reference it
const relsXml = await zip.file('word/charts/_rels/chart1.xml.rels')!.async('string')
expect(relsXml).toContain('embeddings/workbook1.xlsx')
// Chart XML must have c:externalData reference
const chartXml = await zip.file('word/charts/chart1.xml')!.async('string')
expect(chartXml).toContain('c:externalData')
// Content types must register the workbook
const ct = await zip.file('[Content_Types].xml')!.async('string')
expect(ct).toContain('spreadsheetml.sheet')
})
it('patchChartWorkbookXlsxBase64 updates cell values', async () => {
const original = await buildChartWorkbookXlsxBase64(
['Q1', 'Q2'],
[{ name: '华东', values: [100, 200] }],
)
const patched = await patchChartWorkbookXlsxBase64(original, ['A', 'B'], [
{ name: '华东', values: [999, 888] },
])
expect(patched).toBeTruthy()
const binaryStr = atob(patched!)
const bytes = new Uint8Array(binaryStr.length)
for (let i = 0; i < binaryStr.length; i++) bytes[i] = binaryStr.charCodeAt(i)
const xlsx = await JSZip.loadAsync(bytes)
const sheet = await xlsx.file('xl/worksheets/sheet1.xml')!.async('string')
expect(sheet).toContain('999')
expect(sheet).toContain('888')
})
})
@@ -0,0 +1,51 @@
import { describe, expect, it } from 'vitest'
import { parseDocx, readSections, sectionSettingsFromXml } from '../src/index'
import { buildDocx } from './helpers/build-docx'
describe('emphasis marks (w:em)', () => {
it('parses dot/circle emphasis onto runs and skips none', async () => {
const p =
'<w:p><w:r><w:rPr><w:em w:val="dot"/></w:rPr><w:t>重点</w:t></w:r>' +
'<w:r><w:rPr><w:em w:val="circle"/></w:rPr><w:t>圈点</w:t></w:r>' +
'<w:r><w:rPr><w:em w:val="none"/></w:rPr><w:t>普通</w:t></w:r></w:p>'
const parsed = await parseDocx(await buildDocx({ bodyXml: p }))
const runs = parsed.blocks[0].runs!
expect(runs[0].em).toBe('dot')
expect(runs[1].em).toBe('circle')
expect(runs[2].em).toBeUndefined()
})
it('keeps the w:em bytes via rawRPr for untouched-style saves', async () => {
const p = '<w:p><w:r><w:rPr><w:em w:val="dot"/></w:rPr><w:t>重点</w:t></w:r></w:p>'
const parsed = await parseDocx(await buildDocx({ bodyXml: p }))
expect(parsed.blocks[0].runs![0].rawRPr).toContain('<w:em w:val="dot"/>')
})
})
describe('section textDirection (w:textDirection)', () => {
it('reads vertical tbRl from sectPr and omits horizontal lrTb', () => {
expect(
sectionSettingsFromXml('<w:sectPr><w:textDirection w:val="tbRl"/></w:sectPr>').textDirection,
).toBe('tbRl')
expect(
sectionSettingsFromXml('<w:sectPr><w:textDirection w:val="lrTb"/></w:sectPr>').textDirection,
).toBeUndefined()
expect(sectionSettingsFromXml('<w:sectPr/>').textDirection).toBeUndefined()
})
it('readSections surfaces per-section columns and direction from a real doc', async () => {
const body =
'<w:p><w:r><w:t>one</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:sectPr><w:type w:val="continuous"/><w:pgSz w:w="11906" w:h="16838"/>' +
'<w:cols w:num="2" w:space="425"/></w:sectPr></w:pPr></w:p>' +
'<w:p><w:r><w:t>two</w:t></w:r></w:p>'
const parsed = await parseDocx(
await buildDocx({ bodyXml: body, sectPrExtra: '<w:textDirection w:val="tbRl"/>' }),
)
const sections = readSections(parsed)
expect(sections).toHaveLength(2)
expect(sections[0].settings.columns).toBe(2)
expect(sections[0].startType).toBe('continuous')
expect(sections[1].settings.textDirection).toBe('tbRl')
})
})
+276
View File
@@ -0,0 +1,276 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx, type SaveBlock } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const COMMENTS_XML =
XML_DECL +
'<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:comment w:id="1" w:author="Alice" w:initials="A" w:date="2026-07-01T10:00:00Z">' +
'<w:p><w:r><w:t>第一条批注</w:t></w:r></w:p>' +
'<w:p><w:r><w:t>第二段</w:t></w:r></w:p>' +
'</w:comment>' +
'<w:comment w:id="2" w:author="Bob">' +
'<w:p><w:r><w:t>cross-para note</w:t></w:r></w:p>' +
'</w:comment>' +
'</w:comments>'
/** paragraph with an in-paragraph comment range over its middle run */
const COMMENTED_P =
'<w:p><w:r><w:t>before </w:t></w:r>' +
'<w:commentRangeStart w:id="1"/>' +
'<w:r><w:t>marked</w:t></w:r>' +
'<w:commentRangeEnd w:id="1"/>' +
'<w:r><w:commentReference w:id="1"/></w:r>' +
'<w:r><w:t> after</w:t></w:r></w:p>'
/** comment 2 spans two paragraphs: start in one, end in the next */
const CROSS_P_A = '<w:p><w:commentRangeStart w:id="2"/><w:r><w:t>range opens here</w:t></w:r></w:p>'
const CROSS_P_B =
'<w:p><w:r><w:t>range closes here</w:t></w:r><w:commentRangeEnd w:id="2"/>' +
'<w:r><w:commentReference w:id="2"/></w:r></w:p>'
async function buildCommentedDocx(): Promise<Uint8Array> {
return buildDocx({
bodyXml: COMMENTED_P + CROSS_P_A + CROSS_P_B,
extraParts: [
{
path: 'word/comments.xml',
xml: COMMENTS_XML,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml',
},
],
})
}
describe('comment parsing', () => {
it('reads word/comments.xml into the display list', async () => {
const doc = await parseDocx(await buildCommentedDocx())
expect(doc.comments).toEqual([
{
id: '1',
author: 'Alice',
initials: 'A',
date: '2026-07-01T10:00:00Z',
text: '第一条批注\n第二段',
},
{ id: '2', author: 'Bob', initials: undefined, date: undefined, text: 'cross-para note' },
])
})
it('has no comments array entries for documents without comments.xml', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }))
expect(doc.comments).toEqual([])
})
it('keeps commented paragraphs editable and marks covered runs', async () => {
const doc = await parseDocx(await buildCommentedDocx())
const p = doc.blocks[0]
expect(p.type).toBe('paragraph')
expect(p.runs).toEqual([
{ text: 'before ' },
{ text: 'marked', commentIds: ['1'] },
{ text: ' after' },
])
})
it('leaves runs of a cross-paragraph range unmarked (markers preserved by passthrough)', async () => {
const doc = await parseDocx(await buildCommentedDocx())
expect(doc.blocks[1].type).toBe('paragraph')
expect(doc.blocks[1].runs).toEqual([{ text: 'range opens here' }])
expect(doc.blocks[2].runs).toEqual([{ text: 'range closes here' }])
// Cross-paragraph endpoints go into the block-level passthrough fields
expect(doc.blocks[1].commentStarts).toEqual(['2'])
expect(doc.blocks[1].commentEnds).toBeUndefined()
expect(doc.blocks[2].commentEnds).toEqual(['2'])
// A range fully inside one paragraph stays out of the cross-paragraph fields
// (handled by run.commentIds)
expect(doc.blocks[0].commentStarts).toBeUndefined()
expect(doc.blocks[0].commentEnds).toBeUndefined()
})
it('editing a paragraph inside a cross-paragraph range re-emits its marker (no orphan end)', async () => {
const bytes = await buildCommentedDocx()
const doc = await parseDocx(bytes)
const finalBlocks: SaveBlock[] = doc.blocks
.filter((b) => !b.hidden)
.map((b) =>
b.docxIndex === 1
? {
kind: 'generated',
block: {
type: 'paragraph',
commentStarts: b.commentStarts,
commentEnds: b.commentEnds,
runs: [{ text: 'range opens here (edited)' }],
},
}
: { kind: 'original', docxIndex: b.docxIndex! },
)
const saved = await saveDocx(doc, finalBlocks)
const docXml = await (await JSZip.loadAsync(saved)).file('word/document.xml')!.async('string')
// Before the fix: the edited paragraph lost its commentRangeStart, leaving an
// orphaned commentRangeEnd in the later paragraph
expect(docXml).toContain('<w:commentRangeStart w:id="2"/>')
expect(docXml).toContain('range opens here (edited)')
expect(docXml).toContain('<w:commentRangeEnd w:id="2"/>')
// Editing the closing paragraph → end + reference are written back together
const doc2 = await parseDocx(saved)
const finalBlocks2: SaveBlock[] = doc2.blocks
.filter((b) => !b.hidden)
.map((b) =>
b.runs?.some((r) => r.text.includes('range closes here'))
? {
kind: 'generated',
block: {
type: 'paragraph',
commentStarts: b.commentStarts,
commentEnds: b.commentEnds,
runs: [{ text: 'closes edited' }],
},
}
: { kind: 'original', docxIndex: b.docxIndex! },
)
const saved2 = await saveDocx(doc2, finalBlocks2)
const docXml2 = await (await JSZip.loadAsync(saved2)).file('word/document.xml')!.async('string')
expect(docXml2).toContain('closes edited')
expect(docXml2).toContain(
'<w:commentRangeEnd w:id="2"/><w:r><w:commentReference w:id="2"/></w:r>',
)
})
})
describe('comment save fidelity', () => {
it('no edits -> byte-identical output including comments.xml', async () => {
const bytes = await buildCommentedDocx()
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
const saved = await saveDocx(
doc,
visible.map((docxIndex): SaveBlock => ({ kind: 'original', docxIndex })),
)
expect(saved).toBe(bytes)
})
it('editing a commented paragraph re-emits its range markers and reference', async () => {
const bytes = await buildCommentedDocx()
const doc = await parseDocx(bytes)
const finalBlocks: SaveBlock[] = doc.blocks
.filter((b) => !b.hidden)
.map((b) =>
b.docxIndex === 0
? {
kind: 'generated',
block: {
type: 'paragraph',
runs: [
{ text: 'BEFORE ' },
{ text: 'marked edited', commentIds: ['1'] },
{ text: ' AFTER' },
],
},
}
: { kind: 'original', docxIndex: b.docxIndex! },
)
const saved = await saveDocx(doc, finalBlocks)
const zip = await JSZip.loadAsync(saved)
const docXml = await zip.file('word/document.xml')!.async('string')
expect(docXml).toContain(
'<w:commentRangeStart w:id="1"/><w:r><w:t xml:space="preserve">marked edited</w:t></w:r>' +
'<w:commentRangeEnd w:id="1"/><w:r><w:commentReference w:id="1"/></w:r>',
)
// comments.xml itself is untouched
expect(await zip.file('word/comments.xml')!.async('string')).toBe(COMMENTS_XML)
})
it('editing one comment keeps the other rich comment entry byte-identical (surgical rebuild)', async () => {
const RICH_COMMENTS =
XML_DECL +
'<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:comment w:id="1" w:author="Alice" w:initials="A">' +
'<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>加粗观点</w:t></w:r>' +
'<w:r><w:t>与普通文字</w:t></w:r></w:p>' +
'<w:p><w:r><w:rPr><w:i/><w:highlight w:val="yellow"/></w:rPr><w:t>第二段斜体高亮</w:t></w:r></w:p>' +
'</w:comment>' +
'<w:comment w:id="2" w:author="Bob"><w:p><w:r><w:t>待编辑的批注</w:t></w:r></w:p></w:comment>' +
'</w:comments>'
const bytes = await buildDocx({
bodyXml: COMMENTED_P + CROSS_P_A + CROSS_P_B,
extraParts: [
{
path: 'word/comments.xml',
xml: RICH_COMMENTS,
contentType:
'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml',
},
],
extraRels:
'<Relationship Id="rId50" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>',
})
const doc = await parseDocx(bytes)
// Only comment 2's text changes; comment 1 (rich formatting) stays untouched
const edited = doc.comments.map((c) => (c.id === '2' ? { ...c, text: '已改写的批注' } : c))
const saved = await saveDocx(
doc,
doc.blocks
.filter((b) => !b.hidden)
.map((b): SaveBlock => ({ kind: 'original', docxIndex: b.docxIndex! })),
{ comments: edited },
)
const commentsXml = await (
await JSZip.loadAsync(saved)
)
.file('word/comments.xml')!
.async('string')
// Before the surgical fix: comment 1 was rebuilt as plain text, losing its
// bold/italic/highlight
expect(commentsXml).toContain(
'<w:comment w:id="1" w:author="Alice" w:initials="A">' +
'<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>加粗观点</w:t></w:r>' +
'<w:r><w:t>与普通文字</w:t></w:r></w:p>' +
'<w:p><w:r><w:rPr><w:i/><w:highlight w:val="yellow"/></w:rPr><w:t>第二段斜体高亮</w:t></w:r></w:p>' +
'</w:comment>',
)
expect(commentsXml).toContain('已改写的批注')
expect(commentsXml).not.toContain('待编辑的批注')
})
})
describe('comment replies/resolution (commentsExtended)', () => {
it('round-trips new replies and the resolved state', async () => {
const parsed = await parseDocx(
await buildDocx({
bodyXml:
'<w:p><w:commentRangeStart w:id="1"/><w:r><w:t>被批注文字</w:t></w:r>' +
'<w:commentRangeEnd w:id="1"/><w:r><w:commentReference w:id="1"/></w:r></w:p>',
}),
)
const blocks = parsed.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
const comments = [
{ id: '1', author: '甲', text: '主批注' },
{ id: '2', author: '乙', text: '回复一下', parentId: '1' },
]
const saved = await saveDocx(parsed, blocks, { comments })
const reparsed = await parseDocx(saved)
expect(reparsed.comments).toHaveLength(2)
const reply = reparsed.comments.find((c) => c.id === '2')!
expect(reply.parentId).toBe('1')
expect(reply.paraId).toBeTruthy()
// Resolve the main comment → done round-trips
const resolved = reparsed.comments.map((c) => ({ ...c, done: true }))
const saved2 = await saveDocx(await parseDocx(saved), blocks, { comments: resolved })
const reparsed2 = await parseDocx(saved2)
expect(reparsed2.comments.every((c) => c.done)).toBe(true)
// Part/relationship/ContentType wired together
const zip = await (await import('jszip')).default.loadAsync(saved2)
expect(zip.file('word/commentsExtended.xml')).toBeTruthy()
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
expect(rels).toContain('commentsExtended.xml')
const ct = await zip.file('[Content_Types].xml')!.async('string')
expect(ct).toContain('commentsExtended+xml')
})
})
@@ -0,0 +1,122 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/parse'
import { buildDocx } from './helpers/build-docx'
/**
* Documents produced by design tools (and Word itself) pair every DrawingML
* shape with a legacy VML fallback:
* <mc:AlternateContent><mc:Choice><w:drawing>…</mc:Choice>
* <mc:Fallback><w:pict>…</mc:Fallback></mc:AlternateContent>
* The raw bytes therefore contain <w:pict> even for a plain decorated text
* paragraph — classification must ignore fallback content or whole documents
* degrade into embedded-object chips.
*/
const THIN_RULE_DRAWING =
'<w:r><mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">' +
'<mc:Choice Requires="wps"><w:drawing>' +
'<wp:anchor behindDoc="1" distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="2" locked="0" layoutInCell="1" allowOverlap="1">' +
'<wp:simplePos x="0" y="0"/><wp:extent cx="6048375" cy="9525"/>' +
'<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
'<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
'<wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="6048375" cy="9525"/></a:xfrm></wps:spPr>' +
'</wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></mc:Choice>' +
'<mc:Fallback><w:pict>' +
'<v:rect xmlns:v="urn:schemas-microsoft-com:vml" style="position:absolute" id="rule1" filled="true"/>' +
'</w:pict></mc:Fallback></mc:AlternateContent></w:r>'
describe('paragraphs with decorative shapes + VML fallbacks', () => {
it('keeps text of a decorated heading editable (fallback w:pict must not trigger Embedded object)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
`<w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr>${THIN_RULE_DRAWING}` +
'<w:r><w:t>Mandatory Story Header Format</w:t></w:r></w:p>',
}),
)
const block = doc.blocks[0]
expect(block.type).toBe('heading')
expect(block.level).toBe(2)
expect(block.runs?.map((r) => r.text).join('')).toBe('Mandatory Story Header Format')
})
it('keeps decorated list items as listItem', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
'<w:p><w:pPr><w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr>' +
`${THIN_RULE_DRAWING}<w:r><w:t>Include new date only on a time skip</w:t></w:r></w:p>`,
withNumbering: true,
}),
)
const block = doc.blocks[0]
expect(block.type).toBe('listItem')
expect(block.runs?.map((r) => r.text).join('')).toBe('Include new date only on a time skip')
})
it('marks a text-less thin shape as a decorative rule', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: `<w:p>${THIN_RULE_DRAWING}</w:p>` }))
const block = doc.blocks[0]
expect(block.type).toBe('passthrough')
expect(block.label).toBe('Drawing object')
expect(block.decorative).toBe(true)
})
it('still protects real VML embedded objects (w:pict outside mc:Fallback)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
'<w:p><w:r><w:pict>' +
'<v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="ole1" style="width:100pt;height:100pt"/>' +
'</w:pict></w:r></w:p>',
}),
)
const block = doc.blocks[0]
expect(block.type).toBe('passthrough')
expect(block.label).toBe('Embedded object')
})
it('extracts anchored textbox content as a display-only model (code box)', async () => {
const textboxDrawing =
'<w:r><w:drawing><wp:anchor behindDoc="1" simplePos="0" locked="0" layoutInCell="1" allowOverlap="1">' +
'<wp:simplePos x="0" y="0"/><wp:extent cx="6038850" cy="1704975"/>' +
'<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
'<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
'<wps:spPr><a:prstGeom prst="rect"><a:avLst/></a:prstGeom>' +
'<a:solidFill><a:srgbClr val="F5F5F5"/></a:solidFill>' +
'<a:ln w="9524"><a:solidFill><a:srgbClr val="CCCCCC"/></a:solidFill></a:ln></wps:spPr>' +
'<wps:txbx><w:txbxContent>' +
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Courier New"/><w:color w:val="415461"/><w:sz w:val="22"/></w:rPr>' +
'<w:t>**Current date:** {Month}</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>CRITICAL</w:t></w:r></w:p>' +
'</w:txbxContent></wps:txbx></wps:wsp>' +
'</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>'
const doc = await parseDocx(await buildDocx({ bodyXml: `<w:p>${textboxDrawing}</w:p>` }))
const block = doc.blocks[0]
expect(block.type).toBe('passthrough')
expect(block.label).toBe('Text box')
const box = block.textboxes?.[0]
expect(box?.fill).toBe('F5F5F5')
expect(box?.borderColor).toBe('CCCCCC')
expect(box?.paras).toHaveLength(2)
expect(box?.paras[0].runs[0]).toMatchObject({
text: '**Current date:** {Month}',
color: '415461',
font: 'Courier New',
})
expect(box?.paras[1].align).toBe('center')
expect(box?.paras[1].runs[0]).toMatchObject({ text: 'CRITICAL', bold: true })
})
it('preserves the original XML slice for decorated paragraphs (byte-level patch anchor)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: `<w:p>${THIN_RULE_DRAWING}<w:r><w:t>text</w:t></w:r></w:p>`,
}),
)
const block = doc.blocks[0]
expect(block.type).toBe('paragraph')
expect(block.originalXml).toContain('<mc:Fallback>')
expect(block.originalXml).toContain('<w:pict>')
})
})
@@ -0,0 +1,64 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx, type SaveBlock } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const CORE_XML =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" ' +
'xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" ' +
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
'<dc:title>测试文档</dc:title><dc:creator>作者甲</dc:creator>' +
'<cp:lastModifiedBy>作者甲</cp:lastModifiedBy><cp:revision>3</cp:revision>' +
'<dcterms:created xsi:type="dcterms:W3CDTF">2020-01-01T00:00:00Z</dcterms:created>' +
'<dcterms:modified xsi:type="dcterms:W3CDTF">2020-01-02T00:00:00Z</dcterms:modified>' +
'</cp:coreProperties>'
const BODY = '<w:p><w:r><w:t>正文</w:t></w:r></w:p>'
const docxWithCore = () =>
buildDocx({
bodyXml: BODY,
extraParts: [
{
path: 'docProps/core.xml',
xml: CORE_XML,
contentType: 'application/vnd.openxmlformats-package.core-properties+xml',
},
],
})
const originalOrder = (doc: Awaited<ReturnType<typeof parseDocx>>): SaveBlock[] =>
doc.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
describe('docProps/core.xml on save', () => {
it('a real save updates dcterms:modified and bumps cp:revision, keeping other fields', async () => {
const doc = await parseDocx(await docxWithCore())
const out = await saveDocx(doc, originalOrder(doc), {
watermark: '草稿',
savedAt: '2026-07-28T08:30:00Z',
})
const core = await (await JSZip.loadAsync(out)).file('docProps/core.xml')!.async('string')
expect(core).toContain(
'<dcterms:modified xsi:type="dcterms:W3CDTF">2026-07-28T08:30:00Z</dcterms:modified>',
)
expect(core).toContain('<cp:revision>4</cp:revision>')
expect(core).toContain('<dc:title>测试文档</dc:title>')
expect(core).toContain('<dcterms:created xsi:type="dcterms:W3CDTF">2020-01-01T00:00:00Z</dcterms:created>')
})
it('an unedited save still returns the original bytes untouched', async () => {
const bytes = await docxWithCore()
const doc = await parseDocx(bytes)
const out = await saveDocx(doc, originalOrder(doc), { savedAt: '2026-07-28T08:30:00Z' })
expect(out).toEqual(bytes)
})
it('a document without docProps saves fine (nothing injected)', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BODY }))
const out = await saveDocx(doc, originalOrder(doc), { watermark: '草稿' })
expect((await JSZip.loadAsync(out)).file('docProps/core.xml')).toBeNull()
})
})
@@ -0,0 +1,94 @@
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
// ---- fixture XML fragments ----
/** Paragraph with a drop cap (Word OOXML: framePr dropCap="drop") */
const DROP_CAP_P =
'<w:p>' +
'<w:pPr>' +
'<w:framePr w:dropCap="drop" w:lines="3" w:wrap="around" w:vAnchor="text" w:hAnchor="text"/>' +
'</w:pPr>' +
'<w:r><w:t xml:space="preserve">Lorem ipsum dolor sit amet.</w:t></w:r>' +
'</w:p>'
/** Paragraph with margin drop cap */
const MARGIN_CAP_P =
'<w:p>' +
'<w:pPr>' +
'<w:framePr w:dropCap="margin" w:lines="4" w:wrap="around" w:vAnchor="text" w:hAnchor="text"/>' +
'</w:pPr>' +
'<w:r><w:t xml:space="preserve">Dropped margin cap text here.</w:t></w:r>' +
'</w:p>'
const PLAIN_P = '<w:p><w:r><w:t>plain paragraph no dropcap</w:t></w:r></w:p>'
describe('drop cap parsing', () => {
it('parses w:framePr dropCap="drop" into block.format.dropCap', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: DROP_CAP_P }))
const block = doc.blocks[0]
expect(block.format?.dropCap).toBeDefined()
expect(block.format!.dropCap!.type).toBe('drop')
expect(block.format!.dropCap!.lines).toBe(3)
})
it('parses w:framePr dropCap="margin" correctly', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: MARGIN_CAP_P }))
const block = doc.blocks[0]
expect(block.format?.dropCap).toBeDefined()
expect(block.format!.dropCap!.type).toBe('margin')
expect(block.format!.dropCap!.lines).toBe(4)
})
it('plain paragraph has no dropCap', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: PLAIN_P }))
expect(doc.blocks[0].format?.dropCap).toBeUndefined()
})
})
describe('drop cap roundtrip', () => {
it('untouched drop-cap paragraph saves byte-identical', async () => {
const bytes = await buildDocx({ bodyXml: DROP_CAP_P })
const doc = await parseDocx(bytes)
const saved = await saveDocx(doc, [{ kind: 'original', docxIndex: 0 }])
const reparsed = await parseDocx(saved)
expect(reparsed.blocks[0].format?.dropCap?.type).toBe('drop')
expect(reparsed.internal.documentXml).toContain('w:dropCap="drop"')
expect(reparsed.internal.documentXml).toContain('w:lines="3"')
})
it('setting dropCap via format regenerates correct pPr with framePr', async () => {
const { generateParagraphXml } = await import('../src/generate')
const block = {
type: 'paragraph' as const,
runs: [{ text: 'Hello world' }],
format: { dropCap: { type: 'drop' as const, lines: 3 } },
}
const xml = generateParagraphXml(block, {
headingStyleIds: new Map(),
allocateHyperlinkRel: () => 'rId1',
})
expect(xml).toContain('w:framePr')
expect(xml).toContain('w:dropCap="drop"')
expect(xml).toContain('w:lines="3"')
})
it('clearing dropCap removes framePr from rawPPr', async () => {
const { mergePPrFormat } = await import('../src/generate')
const rawPPr =
'<w:pPr><w:framePr w:dropCap="drop" w:lines="3" w:wrap="around" w:vAnchor="text" w:hAnchor="text"/></w:pPr>'
// format with dropCap=undefined → should remove framePr
const merged = mergePPrFormat(rawPPr, { dropCap: undefined })
// dropCap undefined means it's not managed; framePr is preserved
expect(merged).toContain('w:framePr')
// explicitly set dropCap: undefined won't remove because undefined fields skip the managed set
// To actually clear it, you'd set dropCap to a falsy value; test that null clears it:
// NOTE: the format type has dropCap?: {...}, so passing null would need to be cast.
// Instead test that passing a new dropCap replaces the old framePr:
const replaced = mergePPrFormat(rawPPr, { dropCap: { type: 'margin', lines: 2 } })
expect(replaced).toContain('w:dropCap="margin"')
expect(replaced).toContain('w:lines="2"')
expect(replaced).not.toContain('w:dropCap="drop"')
})
})
@@ -0,0 +1,97 @@
import { describe, expect, it } from 'vitest'
import { generateTocFieldXml, parseDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
// TOC entry paragraph as Word writes it: TOC field begin + hyperlink entry
// with a dot-leader tab and a nested PAGEREF field for the page number.
const TOC_ENTRY_PARAGRAPH =
'<w:p><w:pPr><w:pStyle w:val="TOC1"/>' +
'<w:tabs><w:tab w:val="right" w:leader="dot" w:pos="9350"/></w:tabs></w:pPr>' +
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:instrText xml:space="preserve"> TOC \\o "1-3" \\h </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:hyperlink w:anchor="_Toc1" w:history="1">' +
'<w:r><w:t>第一章 概述</w:t></w:r>' +
'<w:r><w:tab/></w:r>' +
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:instrText xml:space="preserve"> PAGEREF _Toc1 \\h </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:r><w:t>2</w:t></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
'</w:hyperlink></w:p>'
const FIELD_END_PAGEBREAK_PARAGRAPH =
'<w:p><w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:br w:type="page"/></w:r></w:p>'
const PAGE_FIELD_PARAGRAPH =
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:r><w:t>- 8 -</w:t></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
describe('field paragraph display model', () => {
it('TOC entry becomes a tocLine with title, page number and level', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: TOC_ENTRY_PARAGRAPH }))
const block = doc.blocks[0]
expect(block.type).toBe('passthrough')
expect(block.fieldDisplay).toEqual({
kind: 'tocLine',
left: '第一章 概述',
right: '2',
level: 1,
anchor: '_Toc1',
})
})
it('field-end + page break paragraph shows as a pageBreak marker', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: FIELD_END_PAGEBREAK_PARAGRAPH }))
expect(doc.blocks[0].fieldDisplay).toEqual({ kind: 'pageBreak' })
})
it('PAGE field paragraphs collapse into an editable inline field run (cached result as display text)', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: PAGE_FIELD_PARAGRAPH }))
expect(doc.blocks[0].type).toBe('paragraph')
expect(doc.blocks[0].runs?.[0]).toMatchObject({ text: '- 8 -', instrField: 'PAGE' })
})
it('TOC entry carries its hyperlink anchor for click-to-jump', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: TOC_ENTRY_PARAGRAPH }))
expect(doc.blocks[0].fieldDisplay?.anchor).toBe('_Toc1')
})
})
describe('generateTocFieldXml', () => {
const entries = [
{ level: 1, text: '第一章 概述' },
{ level: 2, text: '1.1 背景 <特殊&字符>' },
{ level: 1, text: '第二章 分析' },
]
it('emits a dirty TOC field spanning one paragraph per entry', () => {
const frags = generateTocFieldXml(entries)
expect(frags).toHaveLength(3)
// field structure: dirty begin + instruction in the first, single end in the last
expect(frags[0]).toContain('w:fldCharType="begin" w:dirty="true"')
expect(frags[0]).toContain(' TOC \\o "1-2" \\h \\z \\u ')
expect(frags[0]).toContain('<w:pStyle w:val="TOC1"/>')
expect(frags[1]).toContain('<w:pStyle w:val="TOC2"/>')
expect(frags[1]).toContain('&lt;特殊&amp;字符&gt;')
expect(frags[2]).toContain('w:fldCharType="end"')
const joined = frags.join('')
expect(joined.match(/w:fldCharType="end"/g)).toHaveLength(1)
expect(joined.match(/w:fldCharType="begin"/g)).toHaveLength(1)
})
it('round-trips through the parser as tocLine display blocks', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: generateTocFieldXml(entries).join('') }))
const visible = doc.blocks.filter((b) => !b.hidden)
expect(visible).toHaveLength(3)
for (const [i, block] of visible.entries()) {
expect(block.type).toBe('passthrough')
expect(block.fieldDisplay?.kind).toBe('tocLine')
expect(block.fieldDisplay?.left).toBe(entries[i].text)
expect(block.fieldDisplay?.level).toBe(entries[i].level)
}
})
})
@@ -0,0 +1,182 @@
import { describe, expect, it } from 'vitest'
import { generateParagraphXml, parseDocx, type GenerateContext } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const GEN_CTX: GenerateContext = {
headingStyleIds: new Map([[1, 'Heading1']]),
allocateHyperlinkRel: () => 'rId999',
}
describe('run-level formatting (font / highlight / vertAlign)', () => {
it('parses rFonts, highlight and vertAlign from runs', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Georgia" w:hAnsi="Georgia"/></w:rPr><w:t>font</w:t></w:r>' +
'<w:r><w:rPr><w:highlight w:val="yellow"/></w:rPr><w:t>hl</w:t></w:r>' +
'<w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><w:t>sup</w:t></w:r>' +
'<w:r><w:rPr><w:vertAlign w:val="subscript"/></w:rPr><w:t>sub</w:t></w:r></w:p>',
})
const doc = await parseDocx(bytes)
const runs = doc.blocks[0].runs!
expect(runs[0].font).toBe('Georgia')
expect(runs[1].highlight).toBe('yellow')
expect(runs[2].vertAlign).toBe('superscript')
expect(runs[3].vertAlign).toBe('subscript')
})
it('prefers eastAsia font name when present', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Calibri" w:eastAsia="宋体"/></w:rPr><w:t>文字</w:t></w:r></w:p>',
})
const doc = await parseDocx(bytes)
expect(doc.blocks[0].runs![0].font).toBe('宋体')
})
it('generates rPr children for the new run props', () => {
const xml = generateParagraphXml(
{
type: 'paragraph',
runs: [
{ text: 'x', font: '宋体', highlight: 'yellow', vertAlign: 'superscript', bold: true },
],
},
GEN_CTX,
)
expect(xml).toContain('<w:rFonts w:ascii="宋体" w:eastAsia="宋体" w:hAnsi="宋体" w:cs="宋体"/>')
expect(xml).toContain('<w:highlight w:val="yellow"/>')
expect(xml).toContain('<w:vertAlign w:val="superscript"/>')
// schema order: rFonts before b, highlight after sz-position, vertAlign last
expect(xml.indexOf('<w:rFonts')).toBeLessThan(xml.indexOf('<w:b/>'))
expect(xml.indexOf('<w:highlight')).toBeLessThan(xml.indexOf('<w:vertAlign'))
})
it('round-trips run formatting through generate -> parse', async () => {
const para = generateParagraphXml(
{
type: 'paragraph',
runs: [{ text: '重点', font: '黑体', highlight: 'green', vertAlign: 'subscript' }],
},
GEN_CTX,
)
const bytes = await buildDocx({ bodyXml: para })
const doc = await parseDocx(bytes)
const run = doc.blocks[0].runs![0]
expect(run).toMatchObject({
text: '重点',
font: '黑体',
highlight: 'green',
vertAlign: 'subscript',
})
})
})
describe('paragraph-level formatting (align / line spacing / indent)', () => {
it('parses w:jc, w:spacing line and w:ind left', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>centered</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:spacing w:line="360" w:lineRule="auto"/></w:pPr><w:r><w:t>1.5x</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:ind w:left="720"/><w:jc w:val="both"/></w:pPr><w:r><w:t>indented justify</w:t></w:r></w:p>' +
'<w:p><w:r><w:t>plain</w:t></w:r></w:p>',
})
const doc = await parseDocx(bytes)
expect(doc.blocks[0].format).toEqual({ align: 'center' })
// F1: parser now exposes lineRawTwips + lineRule + lineSpacing for auto-mode spacing
expect(doc.blocks[1].format).toMatchObject({
lineSpacing: 1.5,
lineRawTwips: 360,
lineRule: 'auto',
})
expect(doc.blocks[2].format).toEqual({ align: 'justify', indentLeft: 720 })
expect(doc.blocks[3].format).toBeUndefined()
})
it('parses and generates first-line and hanging indents', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:pPr><w:ind w:firstLine="440"/></w:pPr><w:r><w:t>首行缩进</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr><w:r><w:t>悬挂缩进</w:t></w:r></w:p>',
})
const doc = await parseDocx(bytes)
expect(doc.blocks[0].format).toEqual({ indentFirstLine: 440 })
expect(doc.blocks[1].format).toEqual({ indentLeft: 720, indentFirstLine: -360 })
const firstLineXml = generateParagraphXml(
{ type: 'paragraph', format: { indentFirstLine: 440 }, runs: [{ text: 'a' }] },
GEN_CTX,
)
expect(firstLineXml).toContain('<w:ind w:firstLine="440"/>')
const hangingXml = generateParagraphXml(
{
type: 'paragraph',
format: { indentLeft: 720, indentFirstLine: -360 },
runs: [{ text: 'a' }],
},
GEN_CTX,
)
expect(hangingXml).toContain('<w:ind w:left="720" w:hanging="360"/>')
})
it('exposes exact/atLeast spacing as lineRawTwips+lineRule (F1)', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:pPr><w:spacing w:line="360" w:lineRule="exact"/></w:pPr><w:r><w:t>x</w:t></w:r></w:p>',
})
const doc = await parseDocx(bytes)
// F1: exact/atLeast spacing is now exposed via lineRawTwips+lineRule instead of being ignored
expect(doc.blocks[0].format).toMatchObject({ lineRawTwips: 360, lineRule: 'exact' })
})
it('generates pPr with schema-ordered children', () => {
const xml = generateParagraphXml(
{
type: 'heading',
level: 1,
format: { align: 'justify', lineSpacing: 1.15, indentLeft: 360 },
runs: [{ text: 'title' }],
},
GEN_CTX,
)
expect(xml).toContain('<w:pStyle w:val="Heading1"/>')
expect(xml).toContain('<w:spacing w:line="276" w:lineRule="auto"/>')
expect(xml).toContain('<w:ind w:left="360"/>')
expect(xml).toContain('<w:jc w:val="both"/>')
expect(xml.indexOf('<w:pStyle')).toBeLessThan(xml.indexOf('<w:spacing'))
expect(xml.indexOf('<w:spacing')).toBeLessThan(xml.indexOf('<w:ind'))
expect(xml.indexOf('<w:ind')).toBeLessThan(xml.indexOf('<w:jc'))
})
it('round-trips paragraph formatting through generate -> parse', async () => {
const para = generateParagraphXml(
{
type: 'paragraph',
format: { align: 'right', lineSpacing: 2, indentLeft: 720 },
runs: [{ text: 'formatted' }],
},
GEN_CTX,
)
const bytes = await buildDocx({ bodyXml: para })
const doc = await parseDocx(bytes)
// F1: parser now exposes lineRawTwips+lineRule+lineSpacing for full accuracy
expect(doc.blocks[0].format).toMatchObject({
align: 'right',
lineSpacing: 2,
lineRawTwips: 480,
lineRule: 'auto',
indentLeft: 720,
})
})
it('round-trips exact/atLeast line rule (previously only auto was recognized, so edits lost line spacing)', async () => {
for (const lineRule of ['exact', 'atLeast'] as const) {
const para = generateParagraphXml(
{ type: 'paragraph', format: { lineRule, lineRawTwips: 216 }, runs: [{ text: 'x' }] },
GEN_CTX,
)
expect(para).toContain(`<w:spacing w:line="216" w:lineRule="${lineRule}"/>`)
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
expect(doc.blocks[0].format).toMatchObject({ lineRule, lineRawTwips: 216 })
}
})
})
@@ -0,0 +1,212 @@
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx, TOTAL_PAGES_MARK, type SaveBlock } from '../src/index'
import { buildDocx } from './helpers/build-docx'
/** rich header/footer paragraphs: save (paras) -> reparse (headerParas) round trip */
async function base() {
const bytes = await buildDocx({ bodyXml: '<w:p><w:r><w:t>正文</w:t></w:r></w:p>' })
const parsed = await parseDocx(bytes)
const saveBlocks: SaveBlock[] = [{ kind: 'original', docxIndex: parsed.blocks[0].docxIndex! }]
return { parsed, saveBlocks }
}
describe('rich header / footer', () => {
it('saves multi-paragraph styled header and reparses it as headerParas', async () => {
const { parsed, saveBlocks } = await base()
const saved = await saveDocx(parsed, saveBlocks, {
header: {
text: '',
paras: [
{ align: 'right', runs: [{ text: '机密', bold: true, color: 'FF0000' }] },
{ runs: [{ text: '年度报告 ' }, { text: '2026', italic: true }] },
],
},
})
const reparsed = await parseDocx(saved)
expect(reparsed.headerParas).toHaveLength(2)
expect(reparsed.headerParas![0].align).toBe('right')
expect(reparsed.headerParas![0].runs[0]).toMatchObject({
text: '机密',
bold: true,
color: 'FF0000',
})
expect(reparsed.headerParas![1].runs.map((r) => r.text).join('')).toBe('年度报告 2026')
expect(reparsed.headerText).toBe('机密年度报告 2026')
})
it('footer paras with # keep a real PAGE field', async () => {
const { parsed, saveBlocks } = await base()
const saved = await saveDocx(parsed, saveBlocks, {
footer: {
text: '',
pageNumber: true,
paras: [{ align: 'center', runs: [{ text: '第 # 页' }] }],
},
})
const reparsed = await parseDocx(saved)
expect(reparsed.footerHasPageNumber).toBe(true)
expect(reparsed.footerParas![0].runs.map((r) => r.text).join('')).toBe('第 # 页')
const zip = await (await import('jszip')).default.loadAsync(saved)
const names = Object.keys(zip.files).filter((n) => /word\/footer\d+\.xml/.test(n))
const xml = await zip.file(names[0])!.async('string')
expect(xml).toContain('<w:instrText xml:space="preserve"> PAGE </w:instrText>')
})
it('footer NUMPAGES field parses to TOTAL_PAGES_MARK and saves back as a field', async () => {
const { parsed, saveBlocks } = await base()
const saved = await saveDocx(parsed, saveBlocks, {
footer: {
text: '',
pageNumber: true,
paras: [{ align: 'center', runs: [{ text: `Seite # von ${TOTAL_PAGES_MARK}` }] }],
},
})
const zip = await (await import('jszip')).default.loadAsync(saved)
const names = Object.keys(zip.files).filter((n) => /word\/footer\d+\.xml/.test(n))
const xml = await zip.file(names[0])!.async('string')
expect(xml).toContain('<w:instrText xml:space="preserve"> NUMPAGES </w:instrText>')
expect(xml).not.toContain(TOTAL_PAGES_MARK)
// Re-parse: the NUMPAGES field returns to the placeholder (no cached result lingers)
const reparsed = await parseDocx(saved)
expect(reparsed.footerParas!.flatMap((p) => p.runs.map((r) => r.text)).join('')).toBe(
`Seite # von ${TOTAL_PAGES_MARK}`,
)
})
it('rich header edit keeps the watermark paragraph', async () => {
const { parsed, saveBlocks } = await base()
const withWm = await saveDocx(parsed, saveBlocks, {
header: { text: '旧页眉' },
watermark: '草稿',
})
const reparsed = await parseDocx(withWm)
expect(reparsed.watermarkText).toBe('草稿')
// rich rewrite carries the watermark through (options.watermark undefined)
const again = await saveDocx(
reparsed,
reparsed.blocks
.filter((b) => !b.hidden)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! })),
{ header: { text: '', paras: [{ runs: [{ text: '新页眉', bold: true }] }] } },
)
const final = await parseDocx(again)
expect(final.watermarkText).toBe('草稿')
expect(final.headerParas![0].runs[0]).toMatchObject({ text: '新页眉', bold: true })
// the watermark paragraph is not part of the text paras
expect(final.headerText).toBe('新页眉')
})
})
describe('surgical header rewrite (real Word headers carry tables/logos)', () => {
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const HEADER_TBL =
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="4000"/><w:gridCol w:w="4000"/></w:tblGrid>' +
'<w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr>' +
'<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>ACME 公司</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr>' +
'<w:p><w:r><w:t>Logo 占位</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
const RICH_HEADER =
XML_DECL +
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
HEADER_TBL +
'<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>公司内部资料</w:t></w:r></w:p>' +
'</w:hdr>'
async function richHeaderDocx() {
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>正文</w:t></w:r></w:p>',
extraRels:
'<Relationship Id="rId60" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
extraParts: [
{
path: 'word/header1.xml',
xml: RICH_HEADER,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
},
],
sectPrExtra: '<w:headerReference w:type="default" r:id="rId60"/>',
})
const parsed = await parseDocx(bytes)
const saveBlocks: SaveBlock[] = parsed.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
return { parsed, saveBlocks }
}
it('watermark-only change keeps the header table and paragraphs byte-identical', async () => {
const { parsed, saveBlocks } = await richHeaderDocx()
const saved = await saveDocx(parsed, saveBlocks, { watermark: '机密' })
const zip = await (await import('jszip')).default.loadAsync(saved)
const hdr = await zip.file('word/header1.xml')!.async('string')
// Before the surgical fix: the whole part was rebuilt, losing the table and the
// right-aligned italic paragraph
expect(hdr).toContain(HEADER_TBL)
expect(hdr).toContain(
'<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>公司内部资料</w:t></w:r></w:p>',
)
expect(hdr).toContain('v:textpath')
expect(hdr).toContain('string="机密"')
// Then remove the watermark: the table remains, the watermark paragraph is gone
const removed = await saveDocx(await parseDocx(saved), saveBlocks, { watermark: null })
const hdr2 = await (
await (await import('jszip')).default.loadAsync(removed)
)
.file('word/header1.xml')!
.async('string')
expect(hdr2).toContain(HEADER_TBL)
expect(hdr2).not.toContain('v:textpath')
})
it('header text edit replaces paragraphs but keeps the table', async () => {
const { parsed, saveBlocks } = await richHeaderDocx()
const saved = await saveDocx(parsed, saveBlocks, { header: { text: '新版页眉' } })
const hdr = await (
await (await import('jszip')).default.loadAsync(saved)
)
.file('word/header1.xml')!
.async('string')
expect(hdr).toContain(HEADER_TBL) // the table (invisible in the user's model) is kept
expect(hdr).toContain('新版页眉')
expect(hdr).not.toContain('公司内部资料') // the text-paragraph set was replaced
})
})
describe('header edits keep image paragraphs', () => {
it('the logo paragraph with w:drawing keeps its original bytes; text paragraphs are replaced', async () => {
const LOGO_P =
'<w:p><w:pPr><w:jc w:val="left"/></w:pPr><w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="914400"/></wp:inline></w:drawing></w:r></w:p>'
const HDR =
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
' xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"' +
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
LOGO_P +
'<w:p><w:r><w:t>旧页眉文字</w:t></w:r></w:p>' +
'</w:hdr>'
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>正文</w:t></w:r></w:p>',
extraRels:
'<Relationship Id="rId61" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
extraParts: [
{
path: 'word/header1.xml',
xml: HDR,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
},
],
sectPrExtra: '<w:headerReference w:type="default" r:id="rId61"/>',
})
const parsed = await parseDocx(bytes)
const saveBlocks: SaveBlock[] = parsed.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
const saved = await saveDocx(parsed, saveBlocks, { header: { text: '新页眉文字' } })
const zip = await (await import('jszip')).default.loadAsync(saved)
const hdr = await zip.file('word/header1.xml')!.async('string')
expect(hdr).toContain(LOGO_P) // the logo paragraph keeps its original bytes
expect(hdr).toContain('新页眉文字')
expect(hdr).not.toContain('旧页眉文字')
})
})
@@ -0,0 +1,117 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
/**
* Chinese government documents (repro) place the footer page number
* inside a VML textbox: w:p > w:r > w:pict > v:shape > v:textbox > w:txbxContent,
* with a complex PAGE field ("— PAGE —") whose cached result is a literal digit.
* The parser must surface the textbox paragraphs instead of dropping the footer.
*/
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const FTR_NS =
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
'xmlns:v="urn:schemas-microsoft-com:vml" ' +
'xmlns:o="urn:schemas-microsoft-com:office:office" ' +
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'
const RPR =
'<w:rPr><w:rFonts w:ascii="SimSun" w:hAnsi="SimSun" w:cs="SimSun"/><w:sz w:val="28"/><w:szCs w:val="28"/></w:rPr>'
/** structure copied from the repro document's word/footer1.xml (fonts renamed, ids shortened) */
const GOV_TEXTBOX_FOOTER =
XML_DECL +
`<w:ftr ${FTR_NS}><w:p><w:pPr><w:pStyle w:val="6"/></w:pPr><w:r><w:pict>` +
'<v:shape id="Text Box 8" o:spid="_x0000_s4096" o:spt="202" type="#_x0000_t202" ' +
'style="position:absolute;left:0pt;margin-top:0pt;height:144pt;width:144pt;mso-position-horizontal:outside;mso-position-horizontal-relative:margin;mso-wrap-style:none;z-index:251659264;" ' +
'filled="f" stroked="f" coordsize="21600,21600">' +
'<v:path/><v:fill on="f" focussize="0,0"/><v:stroke on="f"/><v:imagedata o:title=""/>' +
'<o:lock v:ext="edit" aspectratio="f"/>' +
'<v:textbox inset="0mm,0mm,0mm,0mm" style="mso-fit-shape-to-text:t;"><w:txbxContent>' +
'<w:p><w:pPr><w:pStyle w:val="6"/><w:ind w:left="315" w:leftChars="150" w:right="315" w:rightChars="150"/>' +
`${RPR}</w:pPr>` +
`<w:r>${RPR}<w:t xml:space="preserve">\u2014 </w:t></w:r>` +
`<w:r>${RPR}<w:fldChar w:fldCharType="begin"/></w:r>` +
`<w:r>${RPR}<w:instrText xml:space="preserve"> PAGE \\* MERGEFORMAT </w:instrText></w:r>` +
`<w:r>${RPR}<w:fldChar w:fldCharType="separate"/></w:r>` +
`<w:r>${RPR}<w:t>1</w:t></w:r>` +
`<w:r>${RPR}<w:fldChar w:fldCharType="end"/></w:r>` +
`<w:r>${RPR}<w:t xml:space="preserve"> \u2014</w:t></w:r>` +
'</w:p></w:txbxContent></v:textbox></v:shape></w:pict></w:r></w:p></w:ftr>'
async function parseWithFooter(footerXml: string) {
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>body</w:t></w:r></w:p>',
extraRels:
'<Relationship Id="rId70" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/>',
extraParts: [
{
path: 'word/footer1.xml',
xml: footerXml,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml',
},
],
sectPrExtra: '<w:footerReference w:type="default" r:id="rId70"/>',
})
return parseDocx(bytes)
}
describe('footer content inside a VML textbox', () => {
it('parses the textbox paragraph into non-empty footer content with the PAGE marker', async () => {
const parsed = await parseWithFooter(GOV_TEXTBOX_FOOTER)
expect(parsed.footerHasPageNumber).toBe(true)
// the "\u2014 N \u2014" literal runs survive; the PAGE field becomes the '#' marker
expect(parsed.footerText).toBe('\u2014 # \u2014')
expect(parsed.footerParas).not.toBeNull()
expect(parsed.footerParas!.length).toBeGreaterThan(0)
const line = parsed.footerParas!.flatMap((p) => p.runs.map((r) => r.text)).join('')
expect(line).toBe('\u2014 # \u2014')
// run formatting from inside the textbox is preserved
const firstRun = parsed.footerParas![0].runs[0]
expect(firstRun.font).toBe('SimSun')
expect(firstRun.sizeHalfPoints).toBe(28)
})
it('hfParts (multi-section lookup path) also carries the textbox paragraphs', async () => {
const parsed = await parseWithFooter(GOV_TEXTBOX_FOOTER)
const part = parsed.hfParts?.rId70
expect(part).toBeDefined()
expect(part!.hasPageNumber).toBe(true)
expect(part!.paras.length).toBeGreaterThan(0)
expect(part!.paras.flatMap((p) => p.runs.map((r) => r.text)).join('')).toBe('\u2014 # \u2014')
})
it('footer PAGE field with a cached result drops the stale number and keeps literal runs', async () => {
// same field structure but as a plain paragraph (no textbox): cached "7" must
// not leak into the display text; the marker takes its place
const plainFooter =
XML_DECL +
`<w:ftr ${FTR_NS}><w:p>` +
'<w:r><w:t xml:space="preserve">\u2014 </w:t></w:r>' +
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:instrText xml:space="preserve"> PAGE \\* MERGEFORMAT </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:r><w:t>7</w:t></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
'<w:r><w:t xml:space="preserve"> \u2014</w:t></w:r>' +
'</w:p></w:ftr>'
const parsed = await parseWithFooter(plainFooter)
expect(parsed.footerHasPageNumber).toBe(true)
expect(parsed.footerText).toBe('\u2014 # \u2014')
expect(parsed.footerParas!.flatMap((p) => p.runs.map((r) => r.text)).join('')).toBe(
'\u2014 # \u2014',
)
})
it('an empty decorative textbox still contributes no footer paragraphs', async () => {
const emptyTextboxFooter =
XML_DECL +
`<w:ftr ${FTR_NS}><w:p><w:r><w:pict>` +
'<v:shape id="s1" o:spt="202" type="#_x0000_t202" style="position:absolute;" filled="t" stroked="f">' +
'<v:textbox><w:txbxContent><w:p/></w:txbxContent></v:textbox>' +
'</v:shape></w:pict></w:r></w:p></w:ftr>'
const parsed = await parseWithFooter(emptyTextboxFooter)
expect(parsed.footerParas ?? []).toHaveLength(0)
})
})
@@ -0,0 +1,245 @@
import JSZip from 'jszip'
/** 1x1 red PNG */
export const TINY_PNG_BASE64 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='
export interface BuildDocxOptions {
/** raw XML of <w:body> children (without w:sectPr; one is appended automatically) */
bodyXml: string
/** extra <w:style> entries appended to the default styles.xml */
extraStylesXml?: string
withNumbering?: boolean
/** full word/numbering.xml content (implies withNumbering) */
numberingXml?: string
withImage?: boolean
/** extra Relationship entries for word/_rels/document.xml.rels */
extraRels?: string
/** extra zip parts (charts etc.) with their [Content_Types].xml override */
extraParts?: Array<{ path: string; xml: string; contentType: string }>
/** extra sectPr children inserted first (headerReference/footerReference…) */
sectPrExtra?: string
}
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const DOC_NS =
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
'xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ' +
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
'xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" ' +
'xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"'
const STYLES_XML_OPEN =
XML_DECL +
'<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>' +
'<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/>' +
'<w:pPr><w:outlineLvl w:val="0"/></w:pPr><w:rPr><w:b/><w:sz w:val="32"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/>' +
'<w:pPr><w:outlineLvl w:val="1"/></w:pPr><w:rPr><w:b/><w:sz w:val="28"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/></w:style>' +
'<w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/>' +
'<w:rPr><w:color w:val="0563C1"/><w:u w:val="single"/></w:rPr></w:style>'
const NUMBERING_XML =
XML_DECL +
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/><w:lvlText w:val="&#61623;"/></w:lvl></w:abstractNum>' +
'<w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum>' +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
'<w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num>' +
'</w:numbering>'
export async function buildDocx(options: BuildDocxOptions): Promise<Uint8Array> {
const zip = new JSZip()
const withNumbering = options.withNumbering || options.numberingXml !== undefined
const contentTypes = [
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>',
'<Default Extension="xml" ContentType="application/xml"/>',
options.withImage ? '<Default Extension="png" ContentType="image/png"/>' : '',
'<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>',
'<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>',
withNumbering
? '<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>'
: '',
...(options.extraParts ?? []).map(
(p) => `<Override PartName="/${p.path}" ContentType="${p.contentType}"/>`,
),
].join('')
zip.file(
'[Content_Types].xml',
`${XML_DECL}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">${contentTypes}</Types>`,
)
zip.file(
'_rels/.rels',
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>' +
'</Relationships>',
)
const docRels = [
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>',
withNumbering
? '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>'
: '',
options.withImage
? '<Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.png"/>'
: '',
options.extraRels ?? '',
].join('')
zip.file(
'word/_rels/document.xml.rels',
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${docRels}</Relationships>`,
)
zip.file('word/styles.xml', `${STYLES_XML_OPEN}${options.extraStylesXml ?? ''}</w:styles>`)
if (withNumbering) zip.file('word/numbering.xml', options.numberingXml ?? NUMBERING_XML)
if (options.withImage) zip.file('word/media/image1.png', TINY_PNG_BASE64, { base64: true })
for (const part of options.extraParts ?? []) zip.file(part.path, part.xml)
const sectPr =
`<w:sectPr>${options.sectPrExtra ?? ''}<w:pgSz w:w="11906" w:h="16838"/>` +
'<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>' +
'</w:sectPr>'
zip.file(
'word/document.xml',
`${XML_DECL}<w:document ${DOC_NS}><w:body>${options.bodyXml}${sectPr}</w:body></w:document>`,
)
return zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' })
}
export const IMAGE_PARAGRAPH_XML =
'<w:p><w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="914400"/>' +
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>'
export const MATH_PARAGRAPH_XML =
'<w:p><m:oMath><m:r><m:t>E=mc^2</m:t></m:r></m:oMath></w:p>'
export const CHART_PARAGRAPH_XML =
'<w:p><w:r><w:drawing><wp:inline><wp:extent cx="5486400" cy="3200400"/>' +
'<wp:docPr id="1" name="图表 1"/>' +
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/chart">' +
'<c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" r:id="rId30"/>' +
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>'
const chartStrCache = (values: string[], f: string) =>
`<c:strRef><c:f>${f}</c:f><c:strCache><c:ptCount val="${values.length}"/>` +
values.map((v, i) => `<c:pt idx="${i}"><c:v>${v}</c:v></c:pt>`).join('') +
'</c:strCache></c:strRef>'
const chartNumCache = (values: (number | null)[], f: string) =>
`<c:numRef><c:f>${f}</c:f><c:numCache><c:formatCode>General</c:formatCode>` +
`<c:ptCount val="${values.length}"/>` +
values
.map((v, i) => (v === null ? '' : `<c:pt idx="${i}"><c:v>${v}</c:v></c:pt>`))
.join('') +
'</c:numCache></c:numRef>'
/** bar chart part: title, 2 series over 3 categories, with a gap in series 2 */
export const CHART_PART_XML =
XML_DECL +
'<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" ' +
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
'<c:chart><c:title><c:tx><c:rich><a:bodyPr/><a:p><a:r><a:t>销售</a:t></a:r><a:r><a:t>统计</a:t></a:r></a:p></c:rich></c:tx><c:overlay val="0"/></c:title>' +
'<c:plotArea><c:layout/><c:barChart><c:barDir val="col"/><c:grouping val="clustered"/>' +
'<c:ser><c:idx val="0"/><c:order val="0"/>' +
`<c:tx>${chartStrCache(['华东'], 'Sheet1!$B$1')}</c:tx>` +
`<c:cat>${chartStrCache(['一月', '二月', '三月'], 'Sheet1!$A$2:$A$4')}</c:cat>` +
`<c:val>${chartNumCache([120, 88.5, 96], 'Sheet1!$B$2:$B$4')}</c:val>` +
'</c:ser>' +
'<c:ser><c:idx val="1"/><c:order val="1"/>' +
`<c:tx>${chartStrCache(['华南'], 'Sheet1!$C$1')}</c:tx>` +
`<c:cat>${chartStrCache(['一月', '二月', '三月'], 'Sheet1!$A$2:$A$4')}</c:cat>` +
`<c:val>${chartNumCache([70, null, 110], 'Sheet1!$C$2:$C$4')}</c:val>` +
'</c:ser>' +
'<c:axId val="111"/><c:axId val="222"/></c:barChart></c:plotArea></c:chart></c:chartSpace>'
export const CHART_RELS =
'<Relationship Id="rId30" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart" Target="charts/chart1.xml"/>'
/** a document whose only body content is one embedded bar chart */
export async function buildChartDocx(bodyPrefixXml = ''): Promise<Uint8Array> {
return buildDocx({
bodyXml: bodyPrefixXml + CHART_PARAGRAPH_XML,
extraRels: CHART_RELS,
extraParts: [
{
path: 'word/charts/chart1.xml',
xml: CHART_PART_XML,
contentType: 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml',
},
],
})
}
export const TABLE_XML =
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/></w:tblPr>' +
'<w:tr><w:tc><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>B1</w:t></w:r></w:p></w:tc></w:tr>' +
'<w:tr><w:tc><w:p><w:r><w:t>A2</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>B2</w:t></w:r></w:p></w:tc></w:tr>' +
'</w:tbl>'
/** A representative document exercising every block type the engine supports. */
export function kitchenSinkBody(): string {
return [
'<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>第一章 概述</w:t></w:r></w:p>',
'<w:p><w:r><w:t xml:space="preserve">普通段落,包含</w:t></w:r>' +
'<w:r><w:rPr><w:b/></w:rPr><w:t>加粗</w:t></w:r>' +
'<w:r><w:rPr><w:i/></w:rPr><w:t>斜体</w:t></w:r>' +
'<w:r><w:rPr><w:u w:val="single"/></w:rPr><w:t>下划线</w:t></w:r>' +
'<w:r><w:rPr><w:strike/></w:rPr><w:t>删除线</w:t></w:r>' +
'<w:r><w:rPr><w:color w:val="FF0000"/><w:sz w:val="28"/></w:rPr><w:t>红色14号</w:t></w:r>' +
'<w:r><w:t xml:space="preserve">与特殊字符 &amp; &lt; &gt; 结束。</w:t></w:r></w:p>',
'<w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr><w:r><w:t>1.1 列表</w:t></w:r></w:p>',
'<w:p><w:pPr><w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>无序项一</w:t></w:r></w:p>',
'<w:p><w:pPr><w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>无序项二</w:t></w:r></w:p>',
'<w:p><w:pPr><w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr><w:r><w:t>有序项一</w:t></w:r></w:p>',
'<w:p><w:r><w:t xml:space="preserve">链接示例:</w:t></w:r>' +
'<w:hyperlink r:id="rId20"><w:r><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t>示例网站</w:t></w:r></w:hyperlink></w:p>',
TABLE_XML,
IMAGE_PARAGRAPH_XML,
MATH_PARAGRAPH_XML,
'<w:p><w:r><w:t>尾段。</w:t></w:r></w:p>',
].join('')
}
export async function buildKitchenSinkDocx(): Promise<Uint8Array> {
return buildDocx({
bodyXml: kitchenSinkBody(),
withNumbering: true,
withImage: true,
extraRels:
'<Relationship Id="rId20" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/" TargetMode="External"/>',
})
}
/** 2x3 table: row 2 has a whole-row delete revision (trPr w:del + delText), row 3 cell A has cellIns */
export const REVISION_TABLE_XML =
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="4000"/><w:gridCol w:w="4000"/></w:tblGrid>' +
'<w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>B1</w:t></w:r></w:p></w:tc></w:tr>' +
'<w:tr><w:trPr><w:del w:id="11" w:author="Alice" w:date="2026-01-01T00:00:00Z"/></w:trPr>' +
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:del w:id="13" w:author="Alice" w:date="2026-01-01T00:00:00Z"><w:r><w:delText>A2del</w:delText></w:r></w:del></w:p></w:tc>' +
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:del w:id="14" w:author="Alice" w:date="2026-01-01T00:00:00Z"><w:r><w:delText>B2del</w:delText></w:r></w:del></w:p></w:tc></w:tr>' +
'<w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/><w:cellIns w:id="15" w:author="Alice" w:date="2026-01-01T00:00:00Z"/></w:tcPr><w:p><w:r><w:t>A3</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>B3</w:t></w:r></w:p></w:tc></w:tr>' +
'</w:tbl>'
/** outer 1x2 table, cell A contains a 2x1 nested table (InnerA/InnerB) + trailing empty paragraph */
export const NESTED_TABLE_XML =
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="3000"/><w:gridCol w:w="3000"/></w:tblGrid>' +
'<w:tr><w:tc><w:p><w:r><w:t>Outer</w:t></w:r></w:p>' +
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr><w:tblGrid><w:gridCol w:w="1000"/><w:gridCol w:w="1000"/></w:tblGrid>' +
'<w:tr><w:tc><w:p><w:r><w:t>InnerA</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>InnerB</w:t></w:r></w:p></w:tc></w:tr>' +
'</w:tbl><w:p/></w:tc>' +
'<w:tc><w:p><w:r><w:t>RightCell</w:t></w:r></w:p></w:tc></w:tr>' +
'</w:tbl>'
@@ -0,0 +1,72 @@
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const HEADER_XML =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"' +
' xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"' +
' xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"' +
' xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
'<w:p><w:r><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0">' +
'<wp:extent cx="381000" cy="190500"/><wp:docPr id="1" name="Logo"/>' +
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
'<pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic>' +
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>' +
'<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:t>Confidential</w:t></w:r></w:p>' +
'</w:hdr>'
const HEADER_RELS =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.png"/>' +
'</Relationships>'
async function buildHeaderLogoDocx(): Promise<Uint8Array> {
return buildDocx({
bodyXml: '<w:p><w:r><w:t>Body</w:t></w:r></w:p>',
withImage: true,
extraRels:
'<Relationship Id="rId20" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
sectPrExtra: '<w:headerReference w:type="default" r:id="rId20"/>',
extraParts: [
{
path: 'word/header1.xml',
xml: HEADER_XML,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
},
{
path: 'word/_rels/header1.xml.rels',
xml: HEADER_RELS,
contentType: 'application/vnd.openxmlformats-package.relationships+xml',
},
],
})
}
describe('header/footer images (display-only Logo)', () => {
it('parses header images with size, text paragraphs unaffected', async () => {
const doc = await parseDocx(await buildHeaderLogoDocx())
expect(doc.headerImages).toHaveLength(1)
const img = doc.headerImages![0]
expect(img.dataUrl.startsWith('data:image/png;base64,')).toBe(true)
expect(img.widthPx).toBe(40)
expect(img.heightPx).toBe(20)
expect(img.floating).toBeUndefined()
// text paragraphs enter the model as usual; image paragraphs produce no empty text paragraph
expect(doc.headerText).toBe('Confidential')
// hfParts (multi-section path) carries images too
const part = Object.values(doc.hfParts ?? {}).find((p) => p.text === 'Confidential')
expect(part?.images).toHaveLength(1)
})
it('untouched round-trip stays byte-identical', async () => {
const bytes = await buildHeaderLogoDocx()
const doc = await parseDocx(bytes)
const blocks = doc.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
expect(await saveDocx(doc, blocks)).toEqual(bytes)
})
})
@@ -0,0 +1,116 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const BODY = '<w:p><w:r><w:t>正文</w:t></w:r></w:p>'
async function zipText(bytes: Uint8Array, path: string): Promise<string | null> {
const zip = await JSZip.loadAsync(bytes)
const file = zip.file(path)
return file ? file.async('string') : null
}
describe('first-page / even-page headers & footers', () => {
it('creates typed parts, references and flags; round-trips through parse', async () => {
const source = await buildDocx({ bodyXml: BODY })
const parsed = await parseDocx(source)
expect(parsed.titlePg).toBe(false)
expect(parsed.evenAndOddHeaders).toBe(false)
expect(parsed.headerFirst).toBeNull()
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }], {
header: { text: '默认页眉' },
headerFirst: { text: '首页页眉' },
headerEven: { text: '偶数页页眉' },
footerEven: { text: '偶 #', pageNumber: true },
titlePg: true,
evenAndOddHeaders: true,
})
const docXml = (await zipText(saved, 'word/document.xml'))!
expect(docXml).toContain('<w:titlePg/>')
expect(docXml).toMatch(/<w:headerReference w:type="first"/)
expect(docXml).toMatch(/<w:headerReference w:type="even"/)
expect(docXml).toMatch(/<w:footerReference w:type="even"/)
const settingsXml = (await zipText(saved, 'word/settings.xml'))!
expect(settingsXml).toContain('<w:evenAndOddHeaders/>')
const reparsed = await parseDocx(saved)
expect(reparsed.titlePg).toBe(true)
expect(reparsed.evenAndOddHeaders).toBe(true)
expect(reparsed.headerText).toBe('默认页眉')
expect(reparsed.headerFirst?.text).toBe('首页页眉')
expect(reparsed.headerEven?.text).toBe('偶数页页眉')
expect(reparsed.footerEven?.text).toBe('偶 #')
expect(reparsed.footerEven?.hasPageNumber).toBe(true)
expect(reparsed.footerFirst).toBeNull()
})
it('gives each new part a distinct filename in a single save', async () => {
const source = await buildDocx({ bodyXml: BODY })
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }], {
header: { text: 'a' },
headerFirst: { text: 'b' },
headerEven: { text: 'c' },
})
const zip = await JSZip.loadAsync(saved)
const headers = Object.keys(zip.files).filter((n) => /^word\/header\d+\.xml$/.test(n))
expect(headers.sort()).toEqual(['word/header1.xml', 'word/header2.xml', 'word/header3.xml'])
})
it('rewrites only the edited variant; the others stay byte-identical', async () => {
const source = await buildDocx({ bodyXml: BODY })
const parsed = await parseDocx(source)
const withBoth = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }], {
header: { text: '默认' },
headerFirst: { text: '首页' },
titlePg: true,
})
const p2 = await parseDocx(withBoth)
const firstPartBefore = await zipText(withBoth, 'word/header2.xml')
const edited = await saveDocx(p2, [{ kind: 'original', docxIndex: 0 }], {
header: { text: '默认已改' },
})
expect(await zipText(edited, 'word/header2.xml')).toBe(firstPartBefore)
const p3 = await parseDocx(edited)
expect(p3.headerText).toBe('默认已改')
expect(p3.headerFirst?.text).toBe('首页')
expect(p3.titlePg).toBe(true)
})
it('removes titlePg and evenAndOddHeaders when toggled off', async () => {
const source = await buildDocx({ bodyXml: BODY })
const parsed = await parseDocx(source)
const on = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }], {
titlePg: true,
evenAndOddHeaders: true,
})
const p2 = await parseDocx(on)
const off = await saveDocx(p2, [{ kind: 'original', docxIndex: 0 }], {
titlePg: false,
evenAndOddHeaders: false,
})
const p3 = await parseDocx(off)
expect(p3.titlePg).toBe(false)
expect(p3.evenAndOddHeaders).toBe(false)
expect(await zipText(off, 'word/document.xml')).not.toContain('<w:titlePg/>')
})
it('keeps titlePg before w:docGrid in schema order', async () => {
const source = await buildDocx({ bodyXml: BODY })
// inject a docGrid into the trailing sectPr
const zip = await JSZip.loadAsync(source)
const docXml = (await zip.file('word/document.xml')!.async('string')).replace(
'</w:sectPr>',
'<w:docGrid w:linePitch="360"/></w:sectPr>',
)
zip.file('word/document.xml', docXml)
const parsed = await parseDocx(await zip.generateAsync({ type: 'uint8array' }))
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }], { titlePg: true })
const out = (await zipText(saved, 'word/document.xml'))!
expect(out.indexOf('<w:titlePg/>')).toBeGreaterThan(-1)
expect(out.indexOf('<w:titlePg/>')).toBeLessThan(out.indexOf('<w:docGrid'))
})
})
@@ -0,0 +1,139 @@
import { describe, expect, it } from 'vitest'
import { applyImageWrap, parseDocx, patchImageParagraphXml } from '../src/index'
import { buildDocx, IMAGE_PARAGRAPH_XML } from './helpers/build-docx'
/** A minimal floating image paragraph with numeric posOffset */
const ANCHOR_IMAGE_XML =
'<w:p><w:r><w:drawing>' +
'<wp:anchor distT="0" distB="0" distL="114300" distR="114300" simplePos="0" relativeHeight="251658240" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">' +
'<wp:simplePos x="0" y="0"/>' +
'<wp:positionH relativeFrom="column"><wp:posOffset>914400</wp:posOffset></wp:positionH>' +
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>457200</wp:posOffset></wp:positionV>' +
'<wp:extent cx="914400" cy="914400"/>' +
'<wp:wrapSquare wrapText="bothSides"/>' +
'<wp:docPr id="1" name="图片 1"/>' +
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
'</a:graphicData></a:graphic>' +
'</wp:anchor>' +
'</w:drawing></w:r></w:p>'
describe('image metadata parsing', () => {
it('exposes display size from wp:extent', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true }))
const img = doc.blocks[0]
expect(img.type).toBe('image')
// 914400 EMU = 96 px
expect(img.imageWidthPx).toBe(96)
expect(img.imageHeightPx).toBe(96)
expect(img.imageAlign).toBeUndefined()
})
it('exposes centered alignment', async () => {
const centered = IMAGE_PARAGRAPH_XML.replace(
'<w:p>',
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr>',
)
const doc = await parseDocx(await buildDocx({ bodyXml: centered, withImage: true }))
expect(doc.blocks[0].imageAlign).toBe('center')
})
})
describe('patchImageParagraphXml', () => {
it('rewrites wp:extent and a:ext size', () => {
const xml =
'<w:p><w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="457200"/>' +
'<a:graphic><pic:pic><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="457200"/></a:xfrm></pic:spPr></pic:pic></a:graphic>' +
'</wp:inline></w:drawing></w:r></w:p>'
const out = patchImageParagraphXml(xml, { widthPx: 192, heightPx: 96 })
expect(out).toContain('<wp:extent cx="1828800" cy="914400"/>')
expect(out).toContain('<a:ext cx="1828800" cy="914400"/>')
})
it('adds, replaces and removes w:jc', () => {
const xml = '<w:p><w:r><w:t>x</w:t></w:r></w:p>'
const centered = patchImageParagraphXml(xml, { align: 'center' })
expect(centered).toContain('<w:pPr><w:jc w:val="center"/></w:pPr>')
const right = patchImageParagraphXml(centered, { align: 'right' })
expect(right).toContain('<w:jc w:val="right"/>')
expect(right).not.toContain('w:val="center"')
const cleared = patchImageParagraphXml(right, { align: null })
expect(cleared).not.toContain('<w:jc')
})
it('inserts w:jc before the paragraph-mark rPr', () => {
const xml = '<w:p><w:pPr><w:rPr><w:b/></w:rPr></w:pPr><w:r><w:t>x</w:t></w:r></w:p>'
const out = patchImageParagraphXml(xml, { align: 'center' })
expect(out).toContain('<w:pPr><w:jc w:val="center"/><w:rPr><w:b/></w:rPr></w:pPr>')
})
it('round-trips size + align through the parser', async () => {
const patched = patchImageParagraphXml(IMAGE_PARAGRAPH_XML, {
widthPx: 200,
heightPx: 150,
align: 'center',
})
const doc = await parseDocx(await buildDocx({ bodyXml: patched, withImage: true }))
expect(doc.blocks[0].imageWidthPx).toBe(200)
expect(doc.blocks[0].imageHeightPx).toBe(150)
expect(doc.blocks[0].imageAlign).toBe('center')
})
})
describe('image posOffset (free-position drag)', () => {
it('parses posOffset from anchor images', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: ANCHOR_IMAGE_XML, withImage: true }))
const img = doc.blocks[0]
expect(img.type).toBe('image')
expect(img.imageOffsetXEmu).toBe(914400)
expect(img.imageOffsetYEmu).toBe(457200)
expect(img.imageWrap).toBe('square-left')
})
it('patchImageParagraphXml rewrites posOffset values', () => {
const out = patchImageParagraphXml(ANCHOR_IMAGE_XML, {
posOffsetX: 1828800,
posOffsetY: 914400,
})
expect(out).toContain('<wp:positionH relativeFrom="column"><wp:posOffset>1828800</wp:posOffset></wp:positionH>')
expect(out).toContain('<wp:positionV relativeFrom="paragraph"><wp:posOffset>914400</wp:posOffset></wp:positionV>')
// Original structure untouched
expect(out).toContain('relativeHeight="251658240"')
})
it('patchImageParagraphXml leaves images without posOffset unchanged', () => {
// IMAGE_PARAGRAPH_XML is inline (no posOffset) — no rewrite should happen
const unchanged = patchImageParagraphXml(IMAGE_PARAGRAPH_XML, {
posOffsetX: 100000,
})
expect(unchanged).toBe(IMAGE_PARAGRAPH_XML)
})
it('applyImageWrap with posOffset uses numeric posOffset instead of align', () => {
const out = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-left', { x: 914400, y: 457200 })
expect(out).toContain('<wp:positionH relativeFrom="column"><wp:posOffset>914400</wp:posOffset></wp:positionH>')
expect(out).toContain('<wp:positionV relativeFrom="paragraph"><wp:posOffset>457200</wp:posOffset></wp:positionV>')
expect(out).not.toContain('<wp:align>')
})
it('applyImageWrap without posOffset uses named alignment', () => {
const out = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-left')
expect(out).toContain('<wp:align>left</wp:align>')
// V position uses posOffset(0) when no numeric offset provided (existing behavior)
expect(out).toContain('<wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV>')
// H position uses named align, not posOffset
expect(out).not.toContain('<wp:positionH relativeFrom="column"><wp:posOffset>')
})
it('round-trips posOffset through the parser', async () => {
// Apply wrap with posOffset, then parse back
const wrapped = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-left', { x: 1828800, y: 914400 })
const doc = await parseDocx(await buildDocx({ bodyXml: wrapped, withImage: true }))
const img = doc.blocks[0]
expect(img.imageWrap).toBe('square-left')
expect(img.imageOffsetXEmu).toBe(1828800)
expect(img.imageOffsetYEmu).toBe(914400)
})
})
@@ -0,0 +1,207 @@
import { describe, expect, it } from 'vitest'
import { applyImageWrap, parseDocx, saveDocx } from '../src/index'
import { buildDocx, IMAGE_PARAGRAPH_XML } from './helpers/build-docx'
const ANCHOR_SQUARE_RIGHT_XML =
'<w:p><w:r><w:drawing>' +
'<wp:anchor distT="0" distB="0" distL="114300" distR="114300" simplePos="0" relativeHeight="1" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">' +
'<wp:simplePos x="0" y="0"/>' +
'<wp:positionH relativeFrom="column"><wp:align>right</wp:align></wp:positionH>' +
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV>' +
'<wp:extent cx="914400" cy="914400"/>' +
'<wp:wrapSquare wrapText="bothSides"/>' +
'<wp:docPr id="1" name="图片 1"/>' +
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
'</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>'
describe('image text wrap (wp:anchor)', () => {
it('parses wrap mode from anchored images', async () => {
const bytes = await buildDocx({ bodyXml: ANCHOR_SQUARE_RIGHT_XML, withImage: true })
const doc = await parseDocx(bytes)
expect(doc.blocks[0].type).toBe('image')
expect(doc.blocks[0].imageWrap).toBe('square-right')
})
it('parses behind / topAndBottom / front variants', async () => {
const behind = ANCHOR_SQUARE_RIGHT_XML.replace('behindDoc="0"', 'behindDoc="1"')
const topBottom = ANCHOR_SQUARE_RIGHT_XML.replace(
'<wp:wrapSquare wrapText="bothSides"/>',
'<wp:wrapTopAndBottom/>',
)
const front = ANCHOR_SQUARE_RIGHT_XML.replace(
'<wp:wrapSquare wrapText="bothSides"/>',
'<wp:wrapNone/>',
)
for (const [xml, expected] of [
[behind, 'behind'],
[topBottom, 'topBottom'],
[front, 'front'],
] as const) {
const doc = await parseDocx(await buildDocx({ bodyXml: xml, withImage: true }))
expect(doc.blocks[0].imageWrap).toBe(expected)
}
const inline = await parseDocx(
await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true }),
)
expect(inline.blocks[0].imageWrap).toBeUndefined()
})
it('converts inline -> square anchor with position and wrap elements', () => {
const out = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-left')
expect(out).toContain('<wp:anchor')
expect(out).not.toContain('<wp:inline')
expect(out).toContain('behindDoc="0"')
expect(out).toContain('<wp:align>left</wp:align>')
expect(out).toContain('<wp:wrapSquare wrapText="bothSides"/>')
// schema order: positionH before extent, wrap after extent and before the graphic
expect(out.indexOf('<wp:positionH')).toBeLessThan(out.indexOf('<wp:extent'))
expect(out.indexOf('<wp:wrapSquare')).toBeGreaterThan(out.indexOf('<wp:extent'))
expect(out.indexOf('<wp:wrapSquare')).toBeLessThan(out.indexOf('<a:graphic'))
})
it('converts anchor -> inline', () => {
const out = applyImageWrap(ANCHOR_SQUARE_RIGHT_XML, null)
expect(out).toContain('<wp:inline')
expect(out).not.toContain('<wp:anchor')
expect(out).not.toContain('wp:positionH')
expect(out).not.toContain('wp:wrapSquare')
expect(out).toContain('<wp:extent cx="914400"')
})
it('changes wrap on an existing anchor', () => {
const out = applyImageWrap(ANCHOR_SQUARE_RIGHT_XML, 'behind')
expect(out).toContain('behindDoc="1"')
expect(out).toContain('<wp:wrapNone/>')
expect(out).not.toContain('wp:wrapSquare')
})
it('applies margin-relative position presets (Word position gallery)', () => {
const out = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-right', undefined, {
h: 'center',
v: 'bottom',
})
expect(out).toContain(
'<wp:positionH relativeFrom="margin"><wp:align>center</wp:align></wp:positionH>',
)
expect(out).toContain(
'<wp:positionV relativeFrom="margin"><wp:align>bottom</wp:align></wp:positionV>',
)
expect(out).toContain('<wp:wrapSquare wrapText="bothSides"/>')
})
it('round-trips a position preset through saveDocx + reparse', async () => {
const bytes = await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true })
const parsed = await parseDocx(bytes)
const saved = await saveDocx(parsed, [
{
kind: 'xml',
xml: applyImageWrap(parsed.blocks[0].originalXml!, 'square-left', undefined, {
h: 'left',
v: 'top',
}),
},
])
const p2 = await parseDocx(saved)
expect(p2.blocks[0].imageWrap).toBe('square-left')
expect(p2.blocks[0].imagePosH).toBe('left')
expect(p2.blocks[0].imagePosV).toBe('top')
// numeric posOffset must not leak in from the align-based position
expect(p2.blocks[0].imageOffsetXEmu).toBeUndefined()
})
it('round-trips wrap changes through saveDocx', async () => {
const bytes = await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true })
const parsed = await parseDocx(bytes)
const floated = await saveDocx(parsed, [
{ kind: 'xml', xml: applyImageWrap(parsed.blocks[0].originalXml!, 'square-right') },
])
const p2 = await parseDocx(floated)
expect(p2.blocks[0].imageWrap).toBe('square-right')
const backInline = await saveDocx(p2, [
{ kind: 'xml', xml: applyImageWrap(p2.blocks[0].originalXml!, null) },
])
const p3 = await parseDocx(backInline)
expect(p3.blocks[0].imageWrap).toBeUndefined()
expect(p3.blocks[0].imageDataUrl).toBeTruthy()
})
it('embeds new images as anchors when NewImage.wrap is set', async () => {
const bytes = await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' })
const parsed = await parseDocx(bytes)
const saved = await saveDocx(parsed, [
{ kind: 'original', docxIndex: 0 },
{
kind: 'image',
image: {
base64:
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
mime: 'image/png',
widthPx: 100,
heightPx: 80,
wrap: 'square-left',
},
},
])
const p2 = await parseDocx(saved)
const img = p2.blocks.find((b) => b.type === 'image')!
expect(img.imageWrap).toBe('square-left')
expect(img.imageWidthPx).toBe(100)
})
})
const WRAP_TIGHT_POLYGON =
'<wp:wrapTight wrapText="bothSides"><wp:wrapPolygon edited="0">' +
'<wp:start x="0" y="0"/><wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/>' +
'<wp:lineTo x="21600" y="0"/><wp:lineTo x="0" y="0"/></wp:wrapPolygon></wp:wrapTight>'
describe('tight / through wrap (wrapPolygon fidelity)', () => {
const tightXml = ANCHOR_SQUARE_RIGHT_XML.replace(
'<wp:wrapSquare wrapText="bothSides"/>',
WRAP_TIGHT_POLYGON,
)
const throughXml = ANCHOR_SQUARE_RIGHT_XML.replace(
'<wp:wrapSquare wrapText="bothSides"/>',
'<wp:wrapThrough wrapText="bothSides"><wp:wrapPolygon><wp:start x="1" y="2"/></wp:wrapPolygon></wp:wrapThrough>',
)
it('parses tight / through as their own modes (no square downgrade)', async () => {
const tight = await parseDocx(await buildDocx({ bodyXml: tightXml, withImage: true }))
expect(tight.blocks[0].imageWrap).toBe('tight-right')
const through = await parseDocx(await buildDocx({ bodyXml: throughXml, withImage: true }))
expect(through.blocks[0].imageWrap).toBe('through-right')
})
it('re-applying the same tight wrap keeps the original wrapPolygon bytes', () => {
const out = applyImageWrap(tightXml, 'tight-right')
expect(out).toContain(WRAP_TIGHT_POLYGON)
expect(out).not.toContain('wp:wrapSquare')
})
it('free-position drag (posOffset) on a tight image keeps the polygon', () => {
const out = applyImageWrap(tightXml, 'tight-right', { x: 12345, y: 67890 })
expect(out).toContain('<wp:posOffset>12345</wp:posOffset>')
expect(out).toContain(WRAP_TIGHT_POLYGON)
})
it('explicitly switching a tight image to square rebuilds as wrapSquare', () => {
const out = applyImageWrap(tightXml, 'square-left')
expect(out).toContain('<wp:wrapSquare wrapText="bothSides"/>')
expect(out).not.toContain('wp:wrapTight')
})
it('tight wrap round-trips through save + reparse', async () => {
const bytes = await buildDocx({ bodyXml: tightXml, withImage: true })
const parsed = await parseDocx(bytes)
const saved = await saveDocx(parsed, [
{
kind: 'xml',
xml: applyImageWrap(parsed.blocks[0].originalXml!, 'tight-right', { x: 100, y: 200 }),
},
])
const p2 = await parseDocx(saved)
expect(p2.blocks[0].imageWrap).toBe('tight-left')
expect(p2.blocks[0].imageOffsetXEmu).toBe(100)
expect(p2.blocks[0].originalXml).toContain('<wp:wrapPolygon')
})
})
+191
View File
@@ -0,0 +1,191 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import {
INK_NAME_PREFIX,
injectInkRunsIntoParagraph,
parseDocx,
saveDocx,
stripInkRuns,
type NewInkImage,
type SaveBlock,
} from '../src/index'
import { buildDocx, TINY_PNG_BASE64 } from './helpers/build-docx'
const TWO_PARAS = '<w:p><w:r><w:t>第一段</w:t></w:r></w:p><w:p><w:r><w:t>第二段</w:t></w:r></w:p>'
function asOriginal(doc: Awaited<ReturnType<typeof parseDocx>>): SaveBlock[] {
return doc.blocks
.filter((b) => !b.hidden)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
}
function makeInk(blockIndex: number, extra: Partial<NewInkImage> = {}): NewInkImage {
return {
blockIndex,
base64: TINY_PNG_BASE64,
widthPx: 200,
heightPx: 80,
offsetXPx: 40,
offsetYPx: -10,
payload: '{"strokes":[{"tool":"pen","color":"C00000"}]}',
...extra,
}
}
async function docXmlOf(bytes: Uint8Array): Promise<string> {
const zip = await JSZip.loadAsync(bytes)
return zip.file('word/document.xml')!.async('string')
}
describe('ink save (wp:anchor floating picture)', () => {
it('writes an anchored in-front-of-text picture into the anchor paragraph', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: TWO_PARAS }))
const saved = await saveDocx(doc, asOriginal(doc), { inks: [makeInk(1)] })
const xml = await docXmlOf(saved)
// second paragraph carries the anchored run; the first is untouched
expect(xml).toContain('<w:p><w:r><w:t>第一段</w:t></w:r></w:p>')
const second = /<w:p><w:r><w:t>第二段[\s\S]*?<\/wp:anchor><\/w:drawing><\/w:r><\/w:p>/.exec(xml)
expect(second).not.toBeNull()
expect(second![0]).toContain('behindDoc="0"')
expect(second![0]).toContain('<wp:wrapNone/>')
expect(second![0]).toContain('<wp:positionH relativeFrom="column"><wp:posOffset>381000</wp:posOffset>')
expect(second![0]).toContain('<wp:positionV relativeFrom="paragraph"><wp:posOffset>-95250</wp:posOffset>')
expect(second![0]).toContain(`name="${INK_NAME_PREFIX} `)
expect(second![0]).toContain('descr="{&quot;strokes&quot;')
// media part + relationship + png content type all present
const zip = await JSZip.loadAsync(saved)
expect(zip.file('word/media/aidocsink1.png')).not.toBeNull()
expect(await zip.file('word/_rels/document.xml.rels')!.async('string')).toContain(
'Target="media/aidocsink1.png"',
)
expect(await zip.file('[Content_Types].xml')!.async('string')).toContain('Extension="png"')
})
it('anchors into a self-closing empty paragraph', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: '<w:p/>' }))
const saved = await saveDocx(doc, asOriginal(doc), { inks: [makeInk(0)] })
const xml = await docXmlOf(saved)
expect(xml).toContain(`name="${INK_NAME_PREFIX} `)
expect(xml).not.toContain('<w:p/><w:r>')
})
it('skips a non-paragraph anchor without leaving orphan media/relationships', async () => {
const table =
'<w:tbl><w:tblGrid><w:gridCol w:w="5000"/></w:tblGrid>' +
'<w:tr><w:tc><w:p><w:r><w:t>cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
const doc = await parseDocx(await buildDocx({ bodyXml: table }))
const saved = await saveDocx(doc, asOriginal(doc), { inks: [makeInk(0)] })
const zip = await JSZip.loadAsync(saved)
expect(zip.file('word/media/aidocsink1.png')).toBeNull()
expect(await zip.file('word/_rels/document.xml.rels')!.async('string')).not.toContain('aidocsink')
expect(await docXmlOf(saved)).not.toContain(INK_NAME_PREFIX)
})
it('inks undefined keeps the file byte-identical (no-op save)', async () => {
const bytes = await buildDocx({ bodyXml: TWO_PARAS })
const doc = await parseDocx(bytes)
expect(await saveDocx(doc, asOriginal(doc))).toBe(bytes)
})
})
describe('ink reopen (ParsedDoc.inks)', () => {
async function savedWithInk(): Promise<Uint8Array> {
const doc = await parseDocx(await buildDocx({ bodyXml: TWO_PARAS }))
return saveDocx(doc, asOriginal(doc), { inks: [makeInk(1)] })
}
it('round-trips placement, payload and image bytes', async () => {
const reopened = await parseDocx(await savedWithInk())
expect(reopened.inks).toHaveLength(1)
const ink = reopened.inks[0]
expect(ink.anchorIndex).toBe(1)
expect(ink.offsetXPx).toBeCloseTo(40, 1)
expect(ink.offsetYPx).toBeCloseTo(-10, 1)
expect(ink.widthPx).toBeCloseTo(200, 1)
expect(ink.heightPx).toBeCloseTo(80, 1)
expect(ink.payload).toBe('{"strokes":[{"tool":"pen","color":"C00000"}]}')
expect(ink.dataUrl).toContain('data:image/png;base64,')
})
it('the annotated paragraph stays an editable text paragraph', async () => {
const reopened = await parseDocx(await savedWithInk())
const para = reopened.blocks[1]
expect(para.type).toBe('paragraph')
expect(para.runs?.map((r) => r.text).join('')).toBe('第二段')
})
it('saving with inks: [] removes the annotation, its media part and its relationship', async () => {
const reopened = await parseDocx(await savedWithInk())
const cleared = await saveDocx(reopened, asOriginal(reopened), { inks: [] })
const xml = await docXmlOf(cleared)
expect(xml).not.toContain(INK_NAME_PREFIX)
expect(xml).toContain('第二段')
expect((await parseDocx(cleared)).inks).toHaveLength(0)
const zip = await JSZip.loadAsync(cleared)
expect(zip.file('word/media/aidocsink1.png')).toBeNull()
expect(await zip.file('word/_rels/document.xml.rels')!.async('string')).not.toContain('aidocsink')
})
it('re-saving does not accumulate media parts or relationships', async () => {
const reopened = await parseDocx(await savedWithInk())
const ink = reopened.inks[0]
const resaved = await saveDocx(reopened, asOriginal(reopened), {
inks: [
{
blockIndex: 1,
base64: TINY_PNG_BASE64,
widthPx: ink.widthPx,
heightPx: ink.heightPx,
offsetXPx: ink.offsetXPx,
offsetYPx: ink.offsetYPx,
payload: ink.payload ?? undefined,
},
],
})
const zip = await JSZip.loadAsync(resaved)
const inkMedia = Object.keys(zip.files).filter((n) => n.includes('aidocsink'))
expect(inkMedia).toEqual(['word/media/aidocsink1.png'])
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
expect(rels.match(/aidocsink/g)).toHaveLength(1)
expect((await parseDocx(resaved)).inks).toHaveLength(1)
})
it('re-saving moves the annotation to a new anchor without duplicating runs', async () => {
const reopened = await parseDocx(await savedWithInk())
const ink = reopened.inks[0]
const moved = await saveDocx(reopened, asOriginal(reopened), {
inks: [
{
blockIndex: 0,
base64: TINY_PNG_BASE64,
widthPx: ink.widthPx,
heightPx: ink.heightPx,
offsetXPx: ink.offsetXPx,
offsetYPx: ink.offsetYPx,
payload: ink.payload ?? undefined,
},
],
})
const again = await parseDocx(moved)
expect(again.inks).toHaveLength(1)
expect(again.inks[0].anchorIndex).toBe(0)
})
})
describe('ink XML helpers', () => {
it('stripInkRuns leaves foreign anchored drawings alone', () => {
const foreign =
'<w:p><w:r><w:drawing><wp:anchor behindDoc="1"><wp:docPr id="5" name="图片 5"/>' +
'</wp:anchor></w:drawing></w:r><w:r><w:t>x</w:t></w:r></w:p>'
expect(stripInkRuns(foreign)).toBe(foreign)
})
it('injectInkRunsIntoParagraph rejects non-paragraph roots', () => {
expect(injectInkRunsIntoParagraph('<w:tbl></w:tbl>', '<w:r/>')).toBeNull()
expect(injectInkRunsIntoParagraph('<w:p><w:r><w:t>a</w:t></w:r></w:p>', '<w:r/>')).toBe(
'<w:p><w:r><w:t>a</w:t></w:r><w:r/></w:p>',
)
})
})
@@ -0,0 +1,192 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import {
generateParagraphXml,
generateTableXml,
parseDocx,
readPageColor,
readSectionSettings,
saveDocx,
type GenerateContext,
type SaveBlock,
} from '../src/index'
import { TINY_PNG_BASE64, buildKitchenSinkDocx } from './helpers/build-docx'
const GEN_CTX: GenerateContext = {
headingStyleIds: new Map(),
allocateHyperlinkRel: () => 'rId999',
}
async function docXmlOf(bytes: Uint8Array): Promise<string> {
const zip = await JSZip.loadAsync(bytes)
return zip.file('word/document.xml')!.async('string')
}
function originals(indexes: number[]): SaveBlock[] {
return indexes.map((docxIndex) => ({ kind: 'original', docxIndex }))
}
describe('new paragraph format props', () => {
it('round-trips spaceBefore/spaceAfter/indentRight/pageBreakBefore', async () => {
const para = generateParagraphXml(
{
type: 'paragraph',
format: { spaceBefore: 240, spaceAfter: 120, indentRight: 360, pageBreakBefore: true },
runs: [{ text: 'x' }],
},
GEN_CTX,
)
expect(para).toContain('<w:pageBreakBefore/>')
expect(para).toContain('<w:spacing w:before="240" w:after="120"/>')
expect(para).toContain('<w:ind w:right="360"/>')
const bytes = await buildKitchenSinkDocx()
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
const saved = await saveDocx(doc, [...originals(visible), { kind: 'xml', xml: para }])
const reparsed = await parseDocx(saved)
const last = reparsed.blocks.filter((b) => !b.hidden).at(-1)!
expect(last.format).toEqual({
spaceBefore: 240,
spaceAfter: 120,
indentRight: 360,
pageBreakBefore: true,
})
})
})
describe('inserting new tables (xml save blocks)', () => {
it('generates a bordered fixed table and reparses it as a table block', async () => {
const bytes = await buildKitchenSinkDocx()
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
const saved = await saveDocx(doc, [
{ kind: 'xml', xml: generateTableXml(3, 4) },
...originals(visible),
])
const xml = await docXmlOf(saved)
expect(xml).toContain('<w:tblBorders>')
const reparsed = await parseDocx(saved)
const first = reparsed.blocks.filter((b) => !b.hidden)[0]
expect(first.type).toBe('table')
expect(first.label).toBe('Table 3×4')
})
})
describe('inserting new images', () => {
it('adds media, relationship and content-type default', async () => {
const bytes = await buildKitchenSinkDocx()
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
const saved = await saveDocx(doc, [
...originals(visible),
{
kind: 'image',
image: { base64: TINY_PNG_BASE64, mime: 'image/png', widthPx: 100, heightPx: 60 },
},
])
const zip = await JSZip.loadAsync(saved)
const media = Object.keys(zip.files).filter((n) => n.startsWith('word/media/aidocs'))
expect(media).toHaveLength(1)
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
expect(rels).toContain(`Target="${media[0].replace('word/', '')}"`)
const xml = await docXmlOf(saved)
expect(xml).toContain(`<wp:extent cx="${100 * 9525}" cy="${60 * 9525}"/>`)
const reparsed = await parseDocx(saved)
const last = reparsed.blocks.filter((b) => !b.hidden).at(-1)!
expect(last.type).toBe('image')
expect(last.imageDataUrl).toMatch(/^data:image\/png;base64,/)
})
})
describe('section settings (page setup)', () => {
it('parses sectPr vAlign and in-paragraph page breaks / hyperlink tooltip', async () => {
const { sectionSettingsFromXml } = await import('../src/section')
expect(sectionSettingsFromXml('<w:sectPr><w:vAlign w:val="center"/></w:sectPr>').vAlign).toBe(
'center',
)
expect(sectionSettingsFromXml('<w:sectPr/>').vAlign).toBeUndefined()
const { buildDocx } = await import('./helpers/build-docx')
const bodyXml =
'<w:p><w:r><w:t>上半</w:t><w:br w:type="page"/><w:t>下半</w:t></w:r></w:p>' +
'<w:p><w:hyperlink r:id="rIdLink" w:tooltip="提示语"><w:r><w:t>链</w:t></w:r></w:hyperlink></w:p>'
const doc = await parseDocx(
await buildDocx({
bodyXml,
extraRels:
'<Relationship Id="rIdLink" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://a.cn" TargetMode="External"/>',
}),
)
expect(doc.blocks[0].runs?.[0].text).toBe('上半\f下半')
const linkRun = doc.blocks[1].runs?.find((r) => r.link)
expect(linkRun?.link?.tooltip).toBe('提示语')
})
it('reads defaults from the kitchen sink sectPr (A4 portrait)', async () => {
const doc = await parseDocx(await buildKitchenSinkDocx())
const section = readSectionSettings(doc)
expect(section).toEqual({
pageWidth: 11906,
pageHeight: 16838,
orientation: 'portrait',
marginTop: 1440,
marginRight: 1440,
marginBottom: 1440,
marginLeft: 1440,
headerDist: 708,
footerDist: 708,
pageBorder: false,
columns: 1,
colSpace: 720,
})
})
it('rewrites pgSz and pgMar while keeping header/footer attrs', async () => {
const doc = await parseDocx(await buildKitchenSinkDocx())
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
const saved = await saveDocx(doc, originals(visible), {
section: {
pageWidth: 16838,
pageHeight: 11906,
orientation: 'landscape',
marginTop: 720,
marginRight: 720,
marginBottom: 720,
marginLeft: 720,
pageBorder: false,
columns: 1,
},
})
const xml = await docXmlOf(saved)
expect(xml).toContain('<w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/>')
expect(xml).toMatch(
/<w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720" w:header="708"/,
)
const reparsed = await parseDocx(saved)
expect(readSectionSettings(reparsed).orientation).toBe('landscape')
expect(readSectionSettings(reparsed).marginLeft).toBe(720)
})
})
describe('page color', () => {
it('sets, reads back and removes w:background', async () => {
const doc = await parseDocx(await buildKitchenSinkDocx())
expect(readPageColor(doc)).toBeNull()
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
const colored = await saveDocx(doc, originals(visible), { pageColor: 'FFF2CC' })
const coloredXml = await docXmlOf(colored)
expect(coloredXml).toMatch(/<w:document[^>]*><w:background w:color="FFF2CC"\/>/)
const reparsedColored = await parseDocx(colored)
expect(readPageColor(reparsedColored)).toBe('FFF2CC')
const cleared = await saveDocx(
reparsedColored,
reparsedColored.blocks
.filter((b) => !b.hidden)
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
{ pageColor: null },
)
expect(readPageColor(await parseDocx(cleared))).toBeNull()
})
})
@@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const LINKED_IMAGE_URL = 'https://example.com/cfimages?u1=abc&width=2560'
const LINKED_IMAGE_PARAGRAPH =
'<w:p><w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="914400"/>' +
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
'<pic:pic><pic:blipFill><a:blip r:link="rId30"/></pic:blipFill></pic:pic>' +
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>'
const IMAGE_REL = `<Relationship Id="rId30" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="${LINKED_IMAGE_URL.replace(/&/g, '&amp;')}" TargetMode="External"/>`
/** INCLUDEPICTURE field whose cached result is the linked drawing (as produced by some converters) */
const INCLUDEPICTURE_PARAGRAPH =
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
`<w:r><w:instrText xml:space="preserve"> INCLUDEPICTURE \\d "${LINKED_IMAGE_URL.replace(/&/g, '&amp;')}" \\y </w:instrText></w:r>` +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="914400"/>' +
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
'<pic:pic><pic:blipFill><a:blip r:link="rId30"/></pic:blipFill></pic:pic>' +
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
describe('linked (external) pictures', () => {
it('exposes the external URL as imageDataUrl instead of degrading to Drawing object', async () => {
const bytes = await buildDocx({ bodyXml: LINKED_IMAGE_PARAGRAPH, extraRels: IMAGE_REL })
const doc = await parseDocx(bytes)
const block = doc.blocks[0]
expect(block.type).toBe('image')
expect(block.imageDataUrl).toBe(LINKED_IMAGE_URL)
})
it('shows the picture for INCLUDEPICTURE field paragraphs instead of a field chip', async () => {
const bytes = await buildDocx({ bodyXml: INCLUDEPICTURE_PARAGRAPH, extraRels: IMAGE_REL })
const doc = await parseDocx(bytes)
const block = doc.blocks[0]
expect(block.type).toBe('image')
expect(block.imageDataUrl).toBe(LINKED_IMAGE_URL)
// still protected: saving must keep the original field XML byte-identical
expect(block.originalXml).toContain('INCLUDEPICTURE')
})
})
+285
View File
@@ -0,0 +1,285 @@
import { describe, expect, it } from 'vitest'
import {
latexToOmml,
mathParagraphXml,
mathTokensOf,
ommlFragmentsOf,
ommlToLatex,
ommlToMathML,
parseDocx,
patchMathTokens,
saveDocx,
} from '../src/index'
import { buildDocx } from './helpers/build-docx'
const FRACTION_OMATH =
'<m:oMath><m:f><m:num><m:r><m:t>a</m:t></m:r></m:num>' +
'<m:den><m:r><m:t>b</m:t></m:r></m:den></m:f></m:oMath>'
describe('ommlToMathML', () => {
it('converts fractions', () => {
const mathml = ommlToMathML(FRACTION_OMATH)
expect(mathml).toContain('<mfrac>')
expect(mathml).toContain('<mi>a</mi>')
expect(mathml).toContain('<mi>b</mi>')
})
it('converts scripts, radicals and delimiters', () => {
const omml =
'<m:oMath>' +
'<m:sSup><m:e><m:r><m:t>x</m:t></m:r></m:e><m:sup><m:r><m:t>2</m:t></m:r></m:sup></m:sSup>' +
'<m:rad><m:radPr><m:degHide m:val="1"/></m:radPr><m:deg/><m:e><m:r><m:t>y</m:t></m:r></m:e></m:rad>' +
'<m:d><m:e><m:r><m:t>z</m:t></m:r></m:e></m:d>' +
'</m:oMath>'
const mathml = ommlToMathML(omml)
expect(mathml).toContain('<msup>')
expect(mathml).toContain('<mn>2</mn>')
expect(mathml).toContain('<msqrt>')
expect(mathml).toContain('<mo stretchy="true">(</mo>')
})
it('converts n-ary operators with under/over limits', () => {
const omml =
'<m:oMath><m:nary><m:naryPr><m:chr m:val="∑"/><m:limLoc m:val="undOvr"/></m:naryPr>' +
'<m:sub><m:r><m:t>k=0</m:t></m:r></m:sub><m:sup><m:r><m:t>n</m:t></m:r></m:sup>' +
'<m:e><m:r><m:t>k</m:t></m:r></m:e></m:nary></m:oMath>'
const mathml = ommlToMathML(omml)
expect(mathml).toContain('<munderover>')
expect(mathml).toContain('∑')
})
it('converts matrices', () => {
const omml =
'<m:oMath><m:m>' +
'<m:mr><m:e><m:r><m:t>1</m:t></m:r></m:e><m:e><m:r><m:t>0</m:t></m:r></m:e></m:mr>' +
'<m:mr><m:e><m:r><m:t>0</m:t></m:r></m:e><m:e><m:r><m:t>1</m:t></m:r></m:e></m:mr>' +
'</m:m></m:oMath>'
const mathml = ommlToMathML(omml)
expect(mathml.match(/<mtr>/g)).toHaveLength(2)
expect(mathml.match(/<mtd>/g)).toHaveLength(4)
})
it('classifies run text into mn / mi / mo tokens', () => {
const omml = '<m:oMath><m:r><m:t>2x+1</m:t></m:r></m:oMath>'
const mathml = ommlToMathML(omml)
expect(mathml).toContain('<mn>2</mn>')
expect(mathml).toContain('<mi>x</mi>')
expect(mathml).toContain('<mo>+</mo>')
expect(mathml).toContain('<mn>1</mn>')
})
it('handles multiple oMath fragments in one paragraph', () => {
const xml = `<w:p>${FRACTION_OMATH}${FRACTION_OMATH}</w:p>`
expect(ommlFragmentsOf(xml)).toHaveLength(2)
expect(ommlToMathML(xml).match(/<math /g)).toHaveLength(2)
})
it('unwraps oMathPara', () => {
const xml = `<w:p><m:oMathPara>${FRACTION_OMATH}</m:oMathPara></w:p>`
expect(ommlFragmentsOf(xml)).toHaveLength(1)
expect(ommlToMathML(xml)).toContain('<mfrac>')
})
})
describe('latexToOmml', () => {
it('builds fractions, scripts and radicals', () => {
const omml = latexToOmml('x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}')
expect(omml).toContain('<m:f><m:num>')
expect(omml).toContain('<m:rad>')
expect(omml).toContain('±')
const mathml = ommlToMathML(`<m:oMath>${omml}</m:oMath>`)
expect(mathml).toContain('<mfrac>')
expect(mathml).toContain('<msqrt>')
expect(mathml).toContain('<msup>')
})
it('builds n-ary sums with limits and binomials', () => {
const omml = latexToOmml('\\sum_{k=0}^{n} \\binom{n}{k} x^k')
expect(omml).toContain('<m:nary>')
expect(omml).toContain('m:val="∑"')
expect(omml).toContain('m:val="noBar"')
})
it('builds matrices with delimiters', () => {
const omml = latexToOmml('\\begin{pmatrix} 1 & 0 \\\\ 0 & 1 \\end{pmatrix}')
expect(omml).toContain('<m:m>')
expect(omml.match(/<m:mr>/g)).toHaveLength(2)
expect(omml).toContain('m:begChr m:val="("')
})
it('maps greek letters and functions', () => {
const omml = latexToOmml('A = \\pi r^2, \\sin \\alpha')
expect(omml).toContain('π')
expect(omml).toContain('α')
expect(omml).toContain('<m:sty m:val="p"/>')
expect(omml).toContain('sin')
})
it('binds a script to the last character of a text run', () => {
const omml = latexToOmml('ab^2')
// the base of the superscript must be "b", not "ab"
expect(omml).toContain('<m:t xml:space="preserve">a</m:t>')
expect(omml).toMatch(/<m:sSup><m:e><m:r><m:t[^>]*>b<\/m:t>/)
})
it('supports \\left \\right stretchy delimiters', () => {
const omml = latexToOmml('\\left( \\frac{a}{b} \\right)')
expect(omml).toContain('<m:d>')
expect(omml).toContain('<m:f>')
})
it('rejects unsupported commands with a helpful error', () => {
expect(() => latexToOmml('\\unknowncmd{x}')).toThrow(/Unsupported command/)
expect(() => latexToOmml('{unclosed')).toThrow(/Missing matching/)
})
it('token edits round-trip through patchMathTokens', () => {
const omml = `<m:oMath>${latexToOmml('\\frac{a}{b}')}</m:oMath>`
const tokens = mathTokensOf(omml)
expect(tokens).toEqual(['a', 'b'])
const patched = patchMathTokens(omml, ['x', 'y'])
expect(mathTokensOf(patched)).toEqual(['x', 'y'])
expect(ommlToMathML(patched)).toContain('<mi>x</mi>')
})
})
describe('ommlToLatex', () => {
const CASES = [
'x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}',
'(x+a)^n = \\sum_{k=0}^{n} \\binom{n}{k} x^k a^{n-k}',
'f(x) = a_0 + \\sum_{n=1}^{\\infty} \\left( a_n \\cos \\frac{n\\pi x}{L} + b_n \\sin \\frac{n\\pi x}{L} \\right)',
'a^2 + b^2 = c^2',
'e^x = 1 + \\frac{x}{1!} + \\frac{x^2}{2!} + \\cdots',
'\\begin{pmatrix} 1 & 0 \\\\ 0 & 1 \\end{pmatrix}',
'\\begin{cases} x & x > 0 \\\\ -x & x \\le 0 \\end{cases}',
'\\lim_{x \\to 0} \\frac{\\sin x}{x} = 1',
'\\sqrt[3]{x} + \\hat{y} + \\overline{z}',
'\\int_{0}^{1} x^2 dx',
'\\underbrace{a + b}',
'\\text{速度} = \\frac{s}{t}',
]
it.each(CASES)('round-trips through latexToOmml: %s', (latex) => {
const omml = `<m:oMath>${latexToOmml(latex)}</m:oMath>`
const decompiled = ommlToLatex(omml)
expect(decompiled).toBeTruthy()
// semantic equivalence: recompiling the decompiled LaTeX renders the same
const omml2 = `<m:oMath>${latexToOmml(decompiled!)}</m:oMath>`
expect(ommlToMathML(omml2)).toBe(ommlToMathML(omml))
// and the visible tokens survive
expect(mathTokensOf(omml2).join('')).toBe(mathTokensOf(omml).join(''))
})
it('decompiles Word-authored OMML (attrs and property bags present)', () => {
const omml =
'<m:oMath xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math">' +
'<m:sSup><m:sSupPr><m:ctrlPr/></m:sSupPr>' +
'<m:e><m:r><m:rPr><m:sty m:val="i"/></m:rPr><m:t>x</m:t></m:r></m:e>' +
'<m:sup><m:r><m:t>2</m:t></m:r></m:sup></m:sSup>' +
'<m:r><m:t>+1=0</m:t></m:r></m:oMath>'
expect(ommlToLatex(omml)).toBe('{x}^{2}+1=0')
})
it('returns null for structures outside the subset', () => {
expect(
ommlToLatex('<m:oMath><m:sPre><m:sub><m:r><m:t>a</m:t></m:r></m:sub><m:e><m:r><m:t>X</m:t></m:r></m:e></m:sPre></m:oMath>'),
).toBeNull()
expect(ommlToLatex(`<m:oMath>${latexToOmml('a')}</m:oMath><m:oMath>${latexToOmml('b')}</m:oMath>`)).toBeNull()
})
it('escapes parser-special characters', () => {
const omml = '<m:oMath><m:r><m:t>100%_x</m:t></m:r></m:oMath>'
const latex = ommlToLatex(omml)
expect(latex).toBeTruthy()
const round = `<m:oMath>${latexToOmml(latex!)}</m:oMath>`
expect(mathTokensOf(round).join('')).toBe('100%_x')
})
})
describe('formula parse + save integration', () => {
it('parseDocx fills mathml and omml for display equations', async () => {
const parsed = await parseDocx(await buildDocx({ bodyXml: `<w:p>${FRACTION_OMATH}</w:p>` }))
const formula = parsed.blocks[0].formulaDisplay
expect(formula?.tokens).toEqual(['a', 'b'])
expect(formula?.mathml).toContain('<mfrac>')
expect(formula?.omml).toContain('<m:oMath>')
})
it('parses paragraphs mixing math and text into editable runs with math runs', async () => {
const mixed = `<w:p><w:r><w:t>see </w:t></w:r>${FRACTION_OMATH}<w:r><w:t> here</w:t></w:r></w:p>`
const parsed = await parseDocx(await buildDocx({ bodyXml: mixed }))
const block = parsed.blocks[0]
expect(block.type).toBe('paragraph')
expect(block.runs?.map((r) => r.text)).toEqual(['see ', 'ab', ' here'])
expect(block.runs?.[1].math?.omml).toBe(FRACTION_OMATH)
})
it('a mixed paragraph regenerates with the math run emitted verbatim', async () => {
const mixed = `<w:p><w:r><w:t>see </w:t></w:r>${FRACTION_OMATH}</w:p>`
const parsed = await parseDocx(await buildDocx({ bodyXml: mixed }))
const block = parsed.blocks[0]
const bytes = await saveDocx(parsed, [
{
kind: 'generated',
block: {
type: 'paragraph',
runs: [{ text: 'edited ' }, ...block.runs!.filter((r) => r.math)],
},
},
])
const reparsed = await parseDocx(bytes)
const rb = reparsed.blocks[0]
expect(rb.type).toBe('paragraph')
expect(rb.runs?.map((r) => r.text)).toEqual(['edited ', 'ab'])
expect(rb.runs?.[1].math?.omml).toBe(FRACTION_OMATH)
})
it('display equations (oMathPara) still parse as protected formula blocks', async () => {
const display = `<w:p><m:oMathPara>${FRACTION_OMATH}</m:oMathPara></w:p>`
const parsed = await parseDocx(await buildDocx({ bodyXml: display }))
expect(parsed.blocks[0].type).toBe('passthrough')
expect(parsed.blocks[0].formulaDisplay?.mathml).toContain('<mfrac>')
})
it('an inserted equation paragraph survives save and reparse', async () => {
const parsed = await parseDocx(await buildDocx({ bodyXml: '<w:p><w:r><w:t>hi</w:t></w:r></w:p>' }))
const omml = latexToOmml('a^2 + b^2 = c^2')
const bytes = await saveDocx(parsed, [
{ kind: 'original', docxIndex: parsed.blocks[0].docxIndex! },
{ kind: 'xml', xml: mathParagraphXml(omml) },
])
const reparsed = await parseDocx(bytes)
const formula = reparsed.blocks[1].formulaDisplay
expect(formula?.mathml).toContain('<msup>')
expect(formula?.tokens.join('')).toContain('=')
})
it('declares xmlns:m when the original document root lacks it', async () => {
const JSZip = (await import('jszip')).default
// rebuild a docx whose document.xml root omits xmlns:m (non-Word generators)
const base = await buildDocx({ bodyXml: '<w:p><w:r><w:t>hi</w:t></w:r></w:p>' })
const baseZip = await JSZip.loadAsync(base)
const baseDocXml = await baseZip.file('word/document.xml')!.async('string')
expect(baseDocXml).toContain('xmlns:m=')
baseZip.file(
'word/document.xml',
baseDocXml.replace(
' xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"',
'',
),
)
const stripped = await parseDocx(await baseZip.generateAsync({ type: 'uint8array' }))
const omml = latexToOmml('E = mc^2')
const bytes = await saveDocx(stripped, [
{ kind: 'original', docxIndex: stripped.blocks[0].docxIndex! },
{ kind: 'xml', xml: mathParagraphXml(omml) },
])
const outZip = await JSZip.loadAsync(bytes)
const docXml = await outZip.file('word/document.xml')!.async('string')
expect(/<w:document[^>]*xmlns:m=/.test(docXml)).toBe(true)
// reparse must still see the formula
const reparsed = await parseDocx(bytes)
expect(reparsed.blocks[1].formulaDisplay?.tokens.join('')).toContain('=')
})
})
@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest'
import {
buildShapeParagraphXml,
buildTextboxParagraphXml,
buildWordArtParagraphXml,
} from '../src/generate'
/**
* ECMA-376 Part 3 (MCE): every prefix named in mc:Choice Requires must be
* resolvable at the AlternateContent scope. Word treats an unresolvable
* prefix as file corruption ("unreadable content", issue #155), so the
* builders must declare the wps namespace on mc:AlternateContent itself.
*/
const BUILDERS: Array<[string, string]> = [
['wordart', buildWordArtParagraphXml({ text: 'Hi' })],
['textbox', buildTextboxParagraphXml()],
['shape', buildShapeParagraphXml({ prst: 'ellipse' })],
]
describe('MCE Requires prefixes resolve at AlternateContent scope', () => {
for (const [name, xml] of BUILDERS) {
it(`${name} declares every Requires prefix on mc:AlternateContent`, () => {
const acTag = /<mc:AlternateContent[^>]*>/.exec(xml)?.[0]
expect(acTag).toBeDefined()
for (const m of xml.matchAll(/Requires="([^"]+)"/g)) {
for (const prefix of m[1].split(/\s+/)) {
expect(acTag, `prefix ${prefix} in ${name}`).toContain(`xmlns:${prefix}=`)
}
}
})
}
for (const [name, xml] of BUILDERS) {
it(`${name} emits the required wps:cNvSpPr child`, () => {
const wsp = /<wps:wsp[^>]*>([\s\S]*?)<wps:spPr>/.exec(xml)?.[1] ?? ''
expect(wsp, name).toContain('<wps:cNvSpPr')
})
}
it('VML fallback sizes are points, not pixels', () => {
const xml = buildWordArtParagraphXml({ widthEmu: 2700000, heightEmu: 720000 })
const style = /<v:rect[^>]*style="([^"]*)"/.exec(xml)?.[1] ?? ''
expect(style).toContain(`width:${2700000 / 12700}pt`)
expect(style).toContain(`height:${720000 / 12700}pt`)
})
})
@@ -0,0 +1,37 @@
import { describe, expect, it } from 'vitest'
import { generateTableModelXml, parseDocx, patchTableCellTexts, saveDocx } from '../src/index'
import { buildDocx, NESTED_TABLE_XML } from './helpers/build-docx'
describe('nested table editing (surgical text patch + regeneration)', () => {
it('patches nested cell texts and keeps the outer cell bytes', () => {
const out = patchTableCellTexts(NESTED_TABLE_XML, [
[{ nested: [[[['EditedInnerA'], null]]] }, null],
])
expect(out).toContain('EditedInnerA')
expect(out).toContain('<w:t>InnerB</w:t>')
expect(out).toContain('<w:t>Outer</w:t>')
expect(out).toContain('<w:t>RightCell</w:t>')
// outer structure is not rearranged
expect(out.indexOf('<w:tbl>')).toBe(0)
})
it('plain-array cell patches still skip cells containing nested tables', () => {
const out = patchTableCellTexts(NESTED_TABLE_XML, [[['ShouldNotApply'], null]])
expect(out).toBe(NESTED_TABLE_XML)
})
it('regenerating a table model keeps nested tables (structure edits no longer drop them)', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: NESTED_TABLE_XML }))
const model = doc.blocks[0].table!
const xml = generateTableModelXml(model, doc.blocks[0].originalXml ?? undefined)
expect(xml).toContain('InnerA')
expect(xml).toContain('InnerB')
// nested table is followed by an empty paragraph (OOXML: tc must end with w:p)
expect(/<\/w:tbl><w:p\/><\/w:tc>/.test(xml)).toBe(true)
// reparsing still yields the nested structure
const saved = await saveDocx(doc, [{ kind: 'xml', xml }])
const reparsed = await parseDocx(saved)
const nested = reparsed.blocks[0].table!.rows[0][0].nestedTables
expect(nested?.[0]?.rows[0].map((c) => c.paras[0])).toEqual(['InnerA', 'InnerB'])
})
})
+281
View File
@@ -0,0 +1,281 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import {
generateCaptionXml,
generateIndexFieldXml,
nextNoteId,
parseDocx,
saveDocx,
type SaveBlock,
} from '../src/index'
import { buildDocx } from './helpers/build-docx'
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const FOOTNOTES_XML =
XML_DECL +
'<w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:footnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:footnote>' +
'<w:footnote w:type="continuationSeparator" w:id="0"><w:p><w:r><w:continuationSeparator/></w:r></w:p></w:footnote>' +
'<w:footnote w:id="2"><w:p><w:r><w:footnoteRef/></w:r><w:r><w:t>这是脚注正文</w:t></w:r></w:p></w:footnote>' +
'</w:footnotes>'
const FOOTNOTE_P =
'<w:p><w:r><w:t>正文</w:t></w:r>' +
'<w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><w:footnoteReference w:id="2"/></w:r>' +
'<w:r><w:t>继续</w:t></w:r></w:p>'
const FOOTNOTES_REL =
'<Relationship Id="rId40" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" Target="footnotes.xml"/>'
async function buildFootnoteDocx(): Promise<Uint8Array> {
return buildDocx({
bodyXml: FOOTNOTE_P,
extraRels: FOOTNOTES_REL,
extraParts: [
{
path: 'word/footnotes.xml',
xml: FOOTNOTES_XML,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml',
},
],
})
}
const originalOrder = (doc: Awaited<ReturnType<typeof parseDocx>>): SaveBlock[] =>
doc.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
describe('footnotes / endnotes', () => {
it('parses word/footnotes.xml and keeps the reference paragraph editable', async () => {
const doc = await parseDocx(await buildFootnoteDocx())
expect(doc.footnotes).toEqual([{ id: '2', text: '这是脚注正文' }])
expect(doc.endnotes).toEqual([])
const p = doc.blocks[0]
expect(p.type).toBe('paragraph')
expect(p.runs).toEqual([
{ text: '正文' },
{ text: '1', noteRef: { kind: 'footnote', id: '2' } },
{ text: '继续' },
])
})
it('adding a note keeps the untouched rich footnote entry byte-identical (surgical rebuild)', async () => {
// Existing footnote with rich formatting (bold run): after adding a new footnote and
// regenerating the part, the original entry keeps its bytes
const RICH_FOOTNOTES =
XML_DECL +
'<w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:footnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:footnote>' +
'<w:footnote w:id="2"><w:p><w:r><w:footnoteRef/></w:r>' +
'<w:r><w:rPr><w:b/><w:color w:val="C00000"/></w:rPr><w:t>加粗红字脚注</w:t></w:r></w:p></w:footnote>' +
'</w:footnotes>'
const bytes = await buildDocx({
bodyXml: FOOTNOTE_P,
extraRels: FOOTNOTES_REL,
extraParts: [
{
path: 'word/footnotes.xml',
xml: RICH_FOOTNOTES,
contentType:
'application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml',
},
],
})
const doc = await parseDocx(bytes)
const out = await saveDocx(doc, originalOrder(doc), {
footnotes: [...doc.footnotes, { id: '3', text: '新脚注' }],
})
const fnXml = await (await JSZip.loadAsync(out)).file('word/footnotes.xml')!.async('string')
// Before the surgical fix: the original entry was rebuilt as plain text, losing
// <w:b/> and the color
expect(fnXml).toContain(
'<w:footnote w:id="2"><w:p><w:r><w:footnoteRef/></w:r>' +
'<w:r><w:rPr><w:b/><w:color w:val="C00000"/></w:rPr><w:t>加粗红字脚注</w:t></w:r></w:p></w:footnote>',
)
expect(fnXml).toContain('新脚注')
})
it('untouched footnote paragraphs still save byte-identical', async () => {
const bytes = await buildFootnoteDocx()
const doc = await parseDocx(bytes)
const out = await saveDocx(doc, originalOrder(doc))
expect(out).toBe(doc.internal.originalBytes)
})
it('regenerates footnotes.xml preserving separators, and round-trips a new note', async () => {
const doc = await parseDocx(await buildFootnoteDocx())
const newId = nextNoteId(doc.footnotes)
expect(newId).toBe('3')
const notes = [...doc.footnotes, { id: newId, text: '新脚注' }]
const out = await saveDocx(
doc,
[
...originalOrder(doc),
{
kind: 'generated',
block: {
type: 'paragraph',
runs: [{ text: '新段落' }, { text: '2', noteRef: { kind: 'footnote', id: newId } }],
},
},
],
{ footnotes: notes },
)
const zip = await JSZip.loadAsync(out)
const fnXml = await zip.file('word/footnotes.xml')!.async('string')
expect(fnXml).toContain('w:type="separator"')
expect(fnXml).toContain('新脚注')
const reparsed = await parseDocx(out)
expect(reparsed.footnotes).toEqual([
{ id: '2', text: '这是脚注正文' },
{ id: '3', text: '新脚注' },
])
const last = reparsed.blocks.filter((b) => !b.hidden).at(-1)!
expect(last.runs).toEqual([
{ text: '新段落' },
{ text: '2', noteRef: { kind: 'footnote', id: '3' } },
])
})
it('creates word/endnotes.xml with rel + content type when the part is missing', async () => {
const bytes = await buildDocx({ bodyXml: '<w:p><w:r><w:t>正文</w:t></w:r></w:p>' })
const doc = await parseDocx(bytes)
const out = await saveDocx(
doc,
[
{
kind: 'generated',
block: {
type: 'paragraph',
runs: [{ text: '正文' }, { text: '1', noteRef: { kind: 'endnote', id: '2' } }],
},
},
],
{ endnotes: [{ id: '2', text: '尾注内容' }] },
)
const zip = await JSZip.loadAsync(out)
const enXml = await zip.file('word/endnotes.xml')!.async('string')
expect(enXml).toContain('尾注内容')
expect(enXml).toContain('w:type="separator"')
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
expect(rels).toContain('endnotes.xml')
const ct = await zip.file('[Content_Types].xml')!.async('string')
expect(ct).toContain('/word/endnotes.xml')
const reparsed = await parseDocx(out)
expect(reparsed.endnotes).toEqual([{ id: '2', text: '尾注内容' }])
expect(reparsed.blocks[0].runs).toEqual([
{ text: '正文' },
{ text: '1', noteRef: { kind: 'endnote', id: '2' } },
])
})
})
describe('index entries (XE)', () => {
const XE_P =
'<w:p><w:r><w:t>人工智能是研究热点</w:t></w:r>' +
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:instrText xml:space="preserve"> XE "人工智能" </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
'<w:r><w:t>,继续。</w:t></w:r></w:p>'
it('keeps XE-only field paragraphs editable and parses the term', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: XE_P }))
const p = doc.blocks[0]
expect(p.type).toBe('paragraph')
expect(p.runs).toEqual([
{ text: '人工智能是研究热点' },
{ text: '', xeTerm: '人工智能' },
{ text: ',继续。' },
])
})
it('regenerates the XE field when the paragraph is edited', async () => {
const bytes = await buildDocx({ bodyXml: XE_P })
const doc = await parseDocx(bytes)
const out = await saveDocx(doc, [
{
kind: 'generated',
block: {
type: 'paragraph',
runs: [{ text: '改过的文本' }, { text: '', xeTerm: '人工智能' }],
},
},
])
const reparsed = await parseDocx(out)
expect(reparsed.blocks[0].runs).toEqual([
{ text: '改过的文本' },
{ text: '', xeTerm: '人工智能' },
])
})
it('PAGE field paragraphs collapse into an editable inline field (no longer whole-paragraph protected)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> PAGE </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>',
}),
)
expect(doc.blocks[0].type).toBe('paragraph')
expect(doc.blocks[0].runs?.[0]?.instrField).toBe('PAGE')
})
it('generateIndexFieldXml sorts, dedupes and wraps in one dirty INDEX field', () => {
const paras = generateIndexFieldXml(['术语B', '术语A', '术语A'])
expect(paras).toHaveLength(2)
expect(paras[0]).toContain('fldCharType="begin" w:dirty="true"')
expect(paras[0]).toContain('INDEX')
expect(paras[0]).toContain('术语A')
expect(paras[1]).toContain('术语B')
expect(paras[1]).toContain('fldCharType="end"')
})
})
describe('captions', () => {
it('generateCaptionXml emits a dirty SEQ field with the static number', () => {
const xml = generateCaptionXml('图', 3, '系统架构')
expect(xml).toContain(' SEQ 图 \\* ARABIC ')
expect(xml).toContain('w:dirty="true"')
expect(xml).toContain('<w:t>3</w:t>')
expect(xml).toContain('系统架构')
})
it('caption paragraphs parse as protected SEQ field blocks with visible text', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: generateCaptionXml('图', 1, '测试') }))
const p = doc.blocks[0]
expect(p.type).toBe('passthrough')
expect(p.fieldDisplay).toEqual({ kind: 'text', left: '图 1 测试' })
})
})
describe('rich-text footnote display runs', () => {
it('parses bold/italic/color/size runs; plain-text footnotes carry no richParas', async () => {
const footnotesXml =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:footnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:footnote>' +
'<w:footnote w:id="1"><w:p>' +
'<w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><w:footnoteRef/></w:r>' +
'<w:r><w:t xml:space="preserve"> 见</w:t></w:r>' +
'<w:r><w:rPr><w:b/><w:color w:val="c00000"/></w:rPr><w:t>重要文献</w:t></w:r>' +
'<w:r><w:rPr><w:i/><w:sz w:val="16"/></w:rPr><w:t>(斜体小字)</w:t></w:r>' +
'</w:p></w:footnote>' +
'<w:footnote w:id="2"><w:p><w:r><w:footnoteRef/></w:r><w:r><w:t>纯文本</w:t></w:r></w:p></w:footnote>' +
'</w:footnotes>'
const { parseNotesXml } = await import('../src/notes')
const notes = parseNotesXml(footnotesXml, 'footnote')
expect(notes).toHaveLength(2)
const rich = notes[0]
expect(rich.richParas?.[0]).toEqual([
{ text: '见' },
{ text: '重要文献', bold: true, color: 'C00000' },
{ text: '(斜体小字)', italic: true, sizeHalfPoints: 16 },
])
expect(notes[1].richParas).toBeUndefined()
expect(notes[1].text).toBe('纯文本')
})
})
@@ -0,0 +1,57 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const MULTILEVEL_NUMBERING =
XML_DECL +
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:abstractNum w:abstractNumId="0">' +
'<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl>' +
'<w:lvl w:ilvl="1"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2"/></w:lvl>' +
'<w:lvl w:ilvl="2"><w:start w:val="3"/><w:numFmt w:val="lowerLetter"/><w:lvlText w:val="%3)"/></w:lvl>' +
'</w:abstractNum>' +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
'<w:num w:numId="2"><w:abstractNumId w:val="0"/>' +
'<w:lvlOverride w:ilvl="0"><w:startOverride w:val="1"/></w:lvlOverride>' +
'<w:lvlOverride w:ilvl="1"><w:lvl w:ilvl="1"><w:start w:val="5"/><w:numFmt w:val="upperRoman"/><w:lvlText w:val="%2:"/></w:lvl></w:lvlOverride>' +
'</w:num>' +
'</w:numbering>'
describe('numbering definitions (word/numbering.xml)', () => {
it('parses per-level numFmt / lvlText / start and lvlOverrides', async () => {
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
numberingXml: MULTILEVEL_NUMBERING,
})
const doc = await parseDocx(bytes)
const num1 = doc.numbering.get('1')!
expect(num1.abstractNumId).toBe('0')
expect(num1.levels[0]).toEqual({ numFmt: 'decimal', lvlText: '%1.', start: 1 })
expect(num1.levels[1]).toEqual({ numFmt: 'decimal', lvlText: '%1.%2', start: 1 })
expect(num1.levels[2]).toEqual({ numFmt: 'lowerLetter', lvlText: '%3)', start: 3 })
expect(num1.startOverrides).toEqual({})
const num2 = doc.numbering.get('2')!
expect(num2.startOverrides).toEqual({ 0: 1 })
// A full w:lvl inside lvlOverride replaces that level's definition; other levels
// follow the abstractNum
expect(num2.levels[1]).toEqual({ numFmt: 'upperRoman', lvlText: '%2:', start: 5 })
expect(num2.levels[0]).toEqual({ numFmt: 'decimal', lvlText: '%1.', start: 1 })
})
it('keeps the bullet/ordered classification for list blocks', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>a</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr><w:r><w:t>b</w:t></w:r></w:p>',
withNumbering: true,
})
const doc = await parseDocx(bytes)
expect(doc.blocks[0].list?.kind).toBe('bullet')
expect(doc.blocks[1].list?.kind).toBe('ordered')
expect(doc.numbering.get('2')?.levels[0]?.lvlText).toBe('%1.')
})
})
+112
View File
@@ -0,0 +1,112 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/index'
import { buildKitchenSinkDocx } from './helpers/build-docx'
describe('parseDocx', () => {
it('parses the kitchen-sink document into anchored blocks', async () => {
const bytes = await buildKitchenSinkDocx()
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden)
expect(visible.map((b) => b.type)).toEqual([
'heading',
'paragraph',
'heading',
'listItem',
'listItem',
'listItem',
'paragraph',
'table',
'image',
'passthrough',
'paragraph',
])
// every block anchored to its top-level element index with exact XML slice
doc.blocks.forEach((block, i) => {
expect(block.docxIndex).toBe(i)
expect(block.originalXml).toBeTruthy()
expect(doc.internal.documentXml).toContain(block.originalXml!)
})
const h1 = visible[0]
expect(h1.level).toBe(1)
expect(h1.runs?.[0].text).toBe('第一章 概述')
const rich = visible[1]
const runs = rich.runs!
expect(runs.find((r) => r.bold)?.text).toBe('加粗')
expect(runs.find((r) => r.italic)?.text).toBe('斜体')
expect(runs.find((r) => r.underline)?.text).toBe('下划线')
expect(runs.find((r) => r.strike)?.text).toBe('删除线')
const colored = runs.find((r) => r.color === 'FF0000')
expect(colored?.text).toBe('红色14号')
expect(colored?.sizeHalfPoints).toBe(28)
// XML entities decoded
expect(runs[runs.length - 1].text).toContain('& < >')
const bullets = visible.filter((b) => b.type === 'listItem')
expect(bullets[0].list).toEqual({ kind: 'bullet', numId: '1', ilvl: 0 })
expect(bullets[2].list).toEqual({ kind: 'ordered', numId: '2', ilvl: 0 })
const linkPara = visible[6]
const linkRun = linkPara.runs!.find((r) => r.link)
expect(linkRun?.link?.href).toBe('https://example.com/')
expect(linkRun?.link?.rId).toBe('rId20')
const table = visible[7]
expect(table.label).toBe('Table 2×2')
expect(table.previewText).toContain('A1')
const image = visible[8]
expect(image.imageDataUrl).toMatch(/^data:image\/png;base64,/)
const math = visible[9]
expect(math.label).toBe('Equation')
// trailing sectPr is hidden
const hidden = doc.blocks.filter((b) => b.hidden)
expect(hidden).toHaveLength(1)
expect(hidden[0].originalXml).toContain('<w:sectPr>')
// style metadata for generation
expect(doc.headingStyleIds.get(1)).toBe('Heading1')
expect(doc.headingStyleIds.get(2)).toBe('Heading2')
expect(doc.listParagraphStyleId).toBe('ListParagraph')
})
it('protects structural paragraphs (section break / fields) as passthrough', async () => {
const { buildDocx } = await import('./helpers/build-docx')
const bytes = await buildDocx({
bodyXml: [
// mid-document section break lives inside w:pPr
'<w:p><w:pPr><w:sectPr><w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/></w:sectPr></w:pPr></w:p>',
// TOC field (complex fields still protect the whole paragraph; simple inline
// fields PAGE/DATE are already editable)
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> TOC \\o "1-3" </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>',
'<w:p><w:r><w:t>带脚注的段落</w:t></w:r><w:r><w:footnoteReference w:id="2"/></w:r></w:p>',
// comments stay editable: they are tracked at run level, not as passthrough
'<w:p><w:commentRangeStart w:id="0"/><w:r><w:t>有批注</w:t></w:r><w:commentRangeEnd w:id="0"/></w:p>',
'<w:p><w:r><w:t>普通可编辑段落</w:t></w:r></w:p>',
].join(''),
})
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden)
expect(visible.map((b) => b.type)).toEqual([
'passthrough',
'passthrough',
'paragraph',
'paragraph',
'paragraph',
])
expect(visible[0].label).toBe('Section break paragraph')
expect(visible[1].label).toBe('Auto TOC (updates when opened in Word)')
// footnote references stay editable as atomic noteRef runs
expect(visible[2].runs).toEqual([
{ text: '带脚注的段落' },
{ text: '*', noteRef: { kind: 'footnote', id: '2' } },
])
expect(visible[3].runs).toEqual([{ text: '有批注', commentIds: ['0'] }])
})
})
@@ -0,0 +1,57 @@
import { describe, expect, it } from 'vitest'
import {
parseDocx,
patchFieldParagraphXml,
patchMathTokens,
} from '../src/index'
import { buildDocx } from './helpers/build-docx'
const TOC_ENTRY =
'<w:p><w:pPr><w:pStyle w:val="TOC1"/></w:pPr>' +
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:instrText xml:space="preserve"> TOC \\o "1-3" \\h </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:hyperlink w:anchor="_Toc1"><w:r><w:rPr><w:b/></w:rPr><w:t>First </w:t></w:r>' +
'<w:r><w:t>chapter</w:t></w:r><w:r><w:tab/></w:r>' +
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:instrText> PAGEREF _Toc1 \\h </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>3</w:t></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:hyperlink></w:p>'
const FORMULA =
'<w:p><m:oMath><m:f><m:num><m:r><m:t>a</m:t></m:r></m:num>' +
'<m:den><m:r><m:t>b</m:t></m:r></m:den></m:f></m:oMath></w:p>'
describe('protected visible-text patching', () => {
it('edits TOC title and page while preserving field structure and run formatting', async () => {
const patched = patchFieldParagraphXml(TOC_ENTRY, {
left: 'Updated & chapter',
right: '12',
})
expect(patched).toContain('<w:instrText xml:space="preserve"> TOC \\o "1-3" \\h </w:instrText>')
expect(patched).toContain('<w:instrText> PAGEREF _Toc1 \\h </w:instrText>')
expect(patched).toContain('<w:rPr><w:b/></w:rPr>')
expect(patched).toContain('&amp; chapter')
const parsed = await parseDocx(await buildDocx({ bodyXml: patched }))
expect(parsed.blocks[0].fieldDisplay?.left).toBe('Updated & chapter')
expect(parsed.blocks[0].fieldDisplay?.right).toBe('12')
})
it('edits OMML tokens while preserving the formula tree', async () => {
const patched = patchMathTokens(FORMULA, ['x & 1', 'y'])
expect(patched).toContain('<m:f><m:num>')
expect(patched).toContain('<m:t>x &amp; 1</m:t>')
expect(patched).toContain('<m:den><m:r><m:t>y</m:t>')
const parsed = await parseDocx(await buildDocx({ bodyXml: patched }))
expect(parsed.blocks[0].formulaDisplay?.tokens).toEqual(['x & 1', 'y'])
expect(parsed.blocks[0].formulaDisplay?.mathml).toContain('<mfrac>')
expect(parsed.blocks[0].previewText).toBe('x & 1y')
})
it('refuses a formula patch when token count changes', () => {
expect(patchMathTokens(FORMULA, ['only-one'])).toBe(FORMULA)
})
})
+190
View File
@@ -0,0 +1,190 @@
/**
* rawRPr passthrough: run-level unmodeled properties (caps/vanish/dstrike/bdr/double
* underline/themeColor/character spacing/all four rFonts slots…) survive paragraph
* rebuilds; editing a modeled field rebuilds only its group.
*/
import { describe, expect, it } from 'vitest'
import { generateParagraphXml, parseDocx, saveDocx, type GenerateContext, type SaveBlock } from '../src/index'
import { buildDocx } from './helpers/build-docx'
import { existsSync, readFileSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
const GEN_CTX: GenerateContext = {
headingStyleIds: new Map([[1, 'Heading1']]),
allocateHyperlinkRel: () => 'rId999',
}
// A run packed with unmodeled properties: double underline, caps, hidden text, double
// strikethrough, character border, run-level shading, character spacing, horizontal
// scale, position, kern, lang, themeColor, szCs≠sz, all four rFonts slots
const RICH_RPR =
'<w:rPr>' +
'<w:rFonts w:ascii="Georgia" w:eastAsia="宋体" w:hAnsi="Georgia" w:cs="Arial"/>' +
'<w:caps/><w:dstrike/><w:vanish/>' +
'<w:color w:val="4472C4" w:themeColor="accent1"/>' +
'<w:spacing w:val="20"/><w:w w:val="90"/><w:kern w:val="24"/><w:position w:val="6"/>' +
'<w:sz w:val="28"/><w:szCs w:val="32"/>' +
'<w:u w:val="double"/>' +
'<w:bdr w:val="single" w:sz="4" w:space="1" w:color="auto"/>' +
'<w:shd w:val="clear" w:color="auto" w:fill="FFF2CC"/>' +
'<w:lang w:val="en-US" w:eastAsia="zh-CN"/>' +
'</w:rPr>'
const RICH_PARA = `<w:p><w:r>${RICH_RPR}<w:t>富格式文本</w:t></w:r></w:p>`
const UNMODELED_TAGS = [
'<w:caps/>', '<w:dstrike/>', '<w:vanish/>',
'w:themeColor="accent1"',
'<w:spacing w:val="20"/>', '<w:w w:val="90"/>', '<w:kern w:val="24"/>', '<w:position w:val="6"/>',
'<w:szCs w:val="32"/>',
'<w:u w:val="double"/>',
'<w:bdr w:val="single" w:sz="4" w:space="1" w:color="auto"/>',
'<w:shd w:val="clear" w:color="auto" w:fill="FFF2CC"/>',
'<w:lang w:val="en-US" w:eastAsia="zh-CN"/>',
'w:cs="Arial"',
]
describe('rawRPr passthrough', () => {
it('text-only edit keeps every unmodeled rPr property', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: RICH_PARA }))
const run = doc.blocks[0].runs![0]
expect(run.rawRPr).toBeTruthy()
// Text-only edit: formatting fields carry over verbatim
const xml = generateParagraphXml(
{ type: 'paragraph', runs: [{ ...run, text: '改过的文字' }] },
GEN_CTX,
)
for (const tag of UNMODELED_TAGS) expect(xml, tag).toContain(tag)
expect(xml).toContain('<w:t xml:space="preserve">改过的文字</w:t>')
})
it('editing a modeled field rebuilds only that group, keeps the rest', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: RICH_PARA }))
const run = doc.blocks[0].runs![0]
// Add bold (not there originally): w:b is inserted at its schema position, the other
// groups keep their original bytes
const xml = generateParagraphXml(
{ type: 'paragraph', runs: [{ ...run, bold: true }] },
GEN_CTX,
)
expect(xml).toContain('<w:b/>')
// schema order: rFonts < b < caps
expect(xml.indexOf('<w:rFonts')).toBeLessThan(xml.indexOf('<w:b/>'))
expect(xml.indexOf('<w:b/>')).toBeLessThan(xml.indexOf('<w:caps/>'))
for (const tag of UNMODELED_TAGS) expect(xml, tag).toContain(tag)
})
it('double underline survives while modeled underline stays true, drops when cleared', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: RICH_PARA }))
const run = doc.blocks[0].runs![0]
expect(run.underline).toBe(true) // the parse side counts double as underline
const kept = generateParagraphXml({ type: 'paragraph', runs: [{ ...run }] }, GEN_CTX)
expect(kept).toContain('<w:u w:val="double"/>') // not edited → double is kept
const cleared = generateParagraphXml(
{ type: 'paragraph', runs: [{ ...run, underline: false }] },
GEN_CTX,
)
expect(cleared).not.toContain('<w:u') // underline cleared → whole group removed
})
it('changing size rebuilds sz+szCs together; changing color drops stale themeColor', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: RICH_PARA }))
const run = doc.blocks[0].runs![0]
const resized = generateParagraphXml(
{ type: 'paragraph', runs: [{ ...run, sizeHalfPoints: 36 }] },
GEN_CTX,
)
expect(resized).toContain('<w:sz w:val="36"/>')
expect(resized).toContain('<w:szCs w:val="36"/>')
expect(resized).not.toContain('w:val="32"')
const recolored = generateParagraphXml(
{ type: 'paragraph', runs: [{ ...run, color: 'FF0000' }] },
GEN_CTX,
)
expect(recolored).toContain('<w:color w:val="FF0000"/>')
expect(recolored).not.toContain('themeColor') // after an explicit recolor the theme-color reference no longer holds
})
it('adjacent runs with different unmodeled props are not merged at parse', async () => {
const body =
'<w:p><w:r><w:rPr><w:caps/></w:rPr><w:t>大写</w:t></w:r>' +
'<w:r><w:t>普通</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: body }))
expect(doc.blocks[0].runs).toHaveLength(2) // modeled fields all equal, but rawRPr differs → no merge
})
})
const here = dirname(fileURLToPath(import.meta.url))
const REAL = join(here, '..', '..', '..', 'example', 'docx', 'OpenClaw开源项目调研分析报告文档.docx')
// Runs only when the local (gitignored) sample document is present.
describe.skipIf(!existsSync(REAL))('real document invariant (example/docx)', () => {
it('edit one paragraph: all other zip entries and w:p slices stay byte-identical, edited one keeps char spacing', async () => {
const bytes = new Uint8Array(readFileSync(REAL))
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden)
// Pick the first editable paragraph with a run-level w:spacing (character spacing, unmodeled)
const target = visible.find(
(b) =>
(b.type === 'paragraph' || b.type === 'heading') &&
b.runs?.length &&
b.runs.some((r) => r.rawRPr?.includes('<w:spacing')),
)!
expect(target).toBeTruthy()
const finalBlocks: SaveBlock[] = visible.map((b) =>
b === target
? {
kind: 'generated',
block: {
type: b.type as 'paragraph' | 'heading',
...(b.level ? { level: b.level } : {}),
...(b.styleId ? { styleId: b.styleId } : {}),
...(b.rawPPr !== undefined ? { rawPPr: b.rawPPr } : {}),
...(b.bookmarks ? { bookmarks: b.bookmarks } : {}),
...(b.hiddenBookmarks ? { hiddenBookmarks: b.hiddenBookmarks } : {}),
runs: b.runs!.map((r, i) => (i === 0 ? { ...r, text: '【已编辑】' + r.text } : r)),
},
}
: { kind: 'original', docxIndex: b.docxIndex! },
)
const saved = await saveDocx(doc, finalBlocks)
// Other zip entries stay byte-identical
const JSZip = (await import('jszip')).default
const [zBefore, zAfter] = await Promise.all([JSZip.loadAsync(bytes), JSZip.loadAsync(saved)])
const fileNames = (z: InstanceType<typeof JSZip>) =>
Object.keys(z.files).filter((n) => !z.files[n].dir).sort()
expect(fileNames(zAfter)).toEqual(fileNames(zBefore))
for (const name of fileNames(zBefore)) {
// core.xml is the exception: a real save updates dcterms:modified / cp:revision
if (name === 'word/document.xml' || name === 'docProps/core.xml') continue
const [a, b] = await Promise.all([
zBefore.files[name].async('uint8array'),
zAfter.files[name].async('uint8array'),
])
expect(b, name).toEqual(a)
}
// Untouched paragraphs' original slices remain; the edited one keeps its character spacing
const newXml = new TextDecoder().decode(await zAfter.files['word/document.xml'].async('uint8array'))
let checked = 0
for (const b of visible) {
if (b === target || !b.originalXml || b.originalXml.length < 40) continue
expect(newXml.includes(b.originalXml), `block docxIndex=${b.docxIndex}`).toBe(true)
checked++
}
expect(checked).toBeGreaterThan(10)
expect(newXml).toContain('【已编辑】')
const spacingVal = /<w:spacing w:val="[^"]+"\/>/.exec(target.runs![0].rawRPr!)?.[0]
expect(spacingVal).toBeTruthy()
// Character spacing is still in the edited paragraph (lost here before the rawRPr fix)
const editedPara = /<w:p>(?:(?!<\/w:p>).)*【已编辑】(?:(?!<\/w:p>).)*<\/w:p>/s.exec(newXml)?.[0]
expect(editedPara).toBeTruthy()
expect(editedPara!).toContain(spacingVal!)
// The saved output can be re-parsed
const reparsed = await parseDocx(saved)
expect(reparsed.blocks.length).toBe(doc.blocks.length)
})
})
@@ -0,0 +1,436 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import { mergePPrFormat, parseDocx, saveDocx, setPPrChange, type SaveBlock } from '../src/index'
import { buildDocx, TABLE_XML } from './helpers/build-docx'
/** paragraph with a tracked insertion and a tracked deletion */
const REVISED_P =
'<w:p><w:r><w:t xml:space="preserve">保留 </w:t></w:r>' +
'<w:ins w:id="11" w:author="Alice" w:date="2026-07-01T10:00:00Z">' +
'<w:r><w:t>新增文字</w:t></w:r>' +
'</w:ins>' +
'<w:del w:id="12" w:author="Bob" w:date="2026-07-02T08:30:00Z">' +
'<w:r><w:delText xml:space="preserve">被删文字</w:delText></w:r>' +
'</w:del>' +
'<w:r><w:t xml:space="preserve"> 结尾</w:t></w:r></w:p>'
/** an insertion that was later deleted: w:del nested in w:ins */
const NESTED_P =
'<w:p><w:ins w:id="21" w:author="Alice">' +
'<w:del w:id="22" w:author="Bob">' +
'<w:r><w:delText>插了又删</w:delText></w:r>' +
'</w:del></w:ins></w:p>'
/** paragraph-mark revision lives in pPr — editable via rawPPr passthrough */
const PARA_MARK_P =
'<w:p><w:pPr><w:rPr><w:del w:id="31" w:author="Alice"/></w:rPr></w:pPr>' +
'<w:r><w:t>段落标记被删</w:t></w:r></w:p>'
/** tracked paragraph-property change (pPrChange nests the old pPr) */
const PPR_CHANGE_P =
'<w:p><w:pPr><w:jc w:val="center"/><w:keepNext/>' +
'<w:pPrChange w:id="51" w:author="Alice" w:date="2026-07-01T10:00:00Z">' +
'<w:pPr><w:jc w:val="left"/></w:pPr></w:pPrChange></w:pPr>' +
'<w:r><w:t>对齐方式被改过</w:t></w:r></w:p>'
/** move-from revision: content was moved away (shown with del marks) */
const MOVE_P =
'<w:p><w:moveFrom w:id="41" w:author="Alice" w:name="move1">' +
'<w:r><w:delText>moved away</w:delText></w:r></w:moveFrom></w:p>'
/** move-to revision: content was moved here (shown with ins marks) */
const MOVE_TO_P =
'<w:p><w:moveTo w:id="42" w:author="Bob" w:name="move2">' +
'<w:r><w:t>moved here</w:t></w:r></w:moveTo></w:p>'
describe('tracked change parsing', () => {
it('parses run-level w:ins / w:del into editable runs', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: REVISED_P }))
const p = doc.blocks[0]
expect(p.type).toBe('paragraph')
expect(p.runs).toEqual([
{ text: '保留 ' },
{
text: '新增文字',
ins: { author: 'Alice', date: '2026-07-01T10:00:00Z', id: '11' },
},
{
text: '被删文字',
del: { author: 'Bob', date: '2026-07-02T08:30:00Z', id: '12' },
},
{ text: ' 结尾' },
])
})
it('parses an insertion later deleted with both markers', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: NESTED_P }))
const p = doc.blocks[0]
expect(p.type).toBe('paragraph')
expect(p.runs).toEqual([
{
text: '插了又删',
ins: { author: 'Alice', id: '21' },
del: { author: 'Bob', id: '22' },
},
])
})
it('paragraph-mark / pPrChange revisions parse as editable paragraphs with rawPPr', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: PARA_MARK_P + PPR_CHANGE_P }))
expect(doc.blocks[0].type).toBe('paragraph')
expect(doc.blocks[0].rawPPr).toContain('<w:del w:id="31"')
expect(doc.blocks[1].type).toBe('paragraph')
expect(doc.blocks[1].rawPPr).toContain('<w:pPrChange')
expect(doc.blocks[1].format?.align).toBe('center')
// pPrChangeInfo is extracted from pPrChange for UI badge/navigation
expect(doc.blocks[1].pPrChangeInfo).toBeDefined()
expect(doc.blocks[1].pPrChangeInfo!.author).toBe('Alice')
expect(doc.blocks[1].pPrChangeInfo!.id).toBe('51')
})
it('move revisions parse as editable paragraphs with moveRevision marker', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: MOVE_P }))
expect(doc.blocks[0].type).toBe('paragraph')
expect(doc.blocks[0].moveRevision).toBe('from')
// The run text is extracted from w:delText inside w:moveFrom with del mark
const delRun = doc.blocks[0].runs?.find((r) => r.del !== undefined)
expect(delRun).toBeDefined()
})
it('moveTo revision parses as editable with moveRevision "to" and ins mark', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: MOVE_TO_P }))
expect(doc.blocks[0].type).toBe('paragraph')
expect(doc.blocks[0].moveRevision).toBe('to')
const insRun = doc.blocks[0].runs?.find((r) => r.ins !== undefined)
expect(insRun).toBeDefined()
expect(insRun!.text).toBe('moved here')
})
it('a text edit regenerates with the pPr (incl. pPrChange) byte-identical', async () => {
const parsed = await parseDocx(await buildDocx({ bodyXml: PPR_CHANGE_P }))
const block = parsed.blocks[0]
expect(block.rawPPr).toBeDefined()
const out = await saveDocx(parsed, [
{
kind: 'generated',
block: { type: 'paragraph', rawPPr: block.rawPPr, runs: [{ text: '改过的文字' }] },
},
])
const zip = await JSZip.loadAsync(out)
const xml = await zip.file('word/document.xml')!.async('string')
expect(xml).toContain('改过的文字')
expect(xml).toContain(block.rawPPr!)
expect(xml).toContain('<w:keepNext/>')
expect(xml).toContain('<w:pPrChange w:id="51"')
})
})
describe('tracked change save fidelity', () => {
it('writes and reopens top-level paragraph and table revision wrappers', async () => {
const parsed = await parseDocx(
await buildDocx({ bodyXml: '<w:p><w:r><w:t>base</w:t></w:r></w:p>' }),
)
const revision = {
kind: 'ins' as const,
author: 'Structural Reviewer',
date: '2026-07-30T10:00:00Z',
}
const paragraph = await saveDocx(parsed, [
{
kind: 'generated',
block: { type: 'paragraph', runs: [{ text: 'inserted paragraph' }] },
revision,
},
])
const reopenedParagraph = await parseDocx(paragraph)
expect(reopenedParagraph.blocks[0].blockRevision).toMatchObject(revision)
expect(reopenedParagraph.blocks[0].runs?.[0].text).toBe('inserted paragraph')
const table = await saveDocx(parsed, [{ kind: 'xml', xml: TABLE_XML, revision }])
const reopenedTable = await parseDocx(table)
expect(reopenedTable.blocks[0].type).toBe('table')
expect(reopenedTable.blocks[0].blockRevision).toMatchObject(revision)
})
it('re-emits w:ins / w:del wrappers when the paragraph is regenerated', async () => {
const parsed = await parseDocx(await buildDocx({ bodyXml: REVISED_P }))
const block = parsed.blocks[0]
if (block.type !== 'paragraph') throw new Error('expected paragraph')
// edit the plain leading run, keep the revised runs untouched
const runs = block.runs!.map((r, i) => (i === 0 ? { ...r, text: '改过 ' } : r))
const saveBlocks: SaveBlock[] = [{ kind: 'generated', block: { type: 'paragraph', runs } }]
const out = await saveDocx(parsed, saveBlocks)
const zip = await JSZip.loadAsync(out)
const xml = await zip.file('word/document.xml')!.async('string')
expect(xml).toContain('改过 ')
expect(xml).toContain('<w:ins w:id="11" w:author="Alice" w:date="2026-07-01T10:00:00Z">')
expect(xml).toContain('<w:del w:id="12" w:author="Bob" w:date="2026-07-02T08:30:00Z">')
expect(xml).toContain('<w:delText xml:space="preserve">被删文字</w:delText>')
// round-trip: parse the saved file again
const again = await parseDocx(out)
expect(again.blocks[0].runs).toEqual([
{ text: '改过 ' },
{ text: '新增文字', ins: { author: 'Alice', date: '2026-07-01T10:00:00Z', id: '11' } },
{ text: '被删文字', del: { author: 'Bob', date: '2026-07-02T08:30:00Z', id: '12' } },
{ text: ' 结尾' },
])
})
it('mints ids for new revisions without one', async () => {
const parsed = await parseDocx(
await buildDocx({ bodyXml: '<w:p><w:r><w:t>base</w:t></w:r></w:p>' }),
)
const saveBlocks: SaveBlock[] = [
{
kind: 'generated',
block: {
type: 'paragraph',
runs: [
{ text: 'base' },
{ text: '新输入', ins: { author: '用户', date: '2026-07-22T04:00:00Z' } },
{ text: '被删掉', del: { author: '用户', date: '2026-07-22T04:00:00Z' } },
],
},
},
]
const out = await saveDocx(parsed, saveBlocks)
const zip = await JSZip.loadAsync(out)
const xml = await zip.file('word/document.xml')!.async('string')
expect(xml).toMatch(/<w:ins w:id="\d+" w:author="用户" w:date="2026-07-22T04:00:00Z">/)
expect(xml).toMatch(/<w:del w:id="\d+" w:author="用户" w:date="2026-07-22T04:00:00Z">/)
expect(xml).toContain('<w:delText xml:space="preserve">被删掉</w:delText>')
})
it('leaves untouched revised paragraphs byte-identical', async () => {
const bytes = await buildDocx({ bodyXml: REVISED_P })
const parsed = await parseDocx(bytes)
const saveBlocks: SaveBlock[] = parsed.blocks
.filter((b) => !b.hidden)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
const out = await saveDocx(parsed, saveBlocks)
expect(out).toBe(bytes)
})
})
describe('comment writing', () => {
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const COMMENTS_XML =
XML_DECL +
'<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:comment w:id="1" w:author="Alice"><w:p><w:r><w:t>已有批注</w:t></w:r></w:p></w:comment>' +
'</w:comments>'
it('creates word/comments.xml with rel + content type when absent', async () => {
const parsed = await parseDocx(
await buildDocx({ bodyXml: '<w:p><w:r><w:t>hello</w:t></w:r></w:p>' }),
)
const block = parsed.blocks[0]
if (block.type !== 'paragraph') throw new Error('expected paragraph')
const runs = [{ ...block.runs![0], commentIds: ['1'] }]
const out = await saveDocx(
parsed,
[{ kind: 'generated', block: { type: 'paragraph', runs } }],
{
comments: [
{ id: '1', author: '用户', date: '2026-07-22T04:00:00Z', text: '第一条\n第二行' },
],
},
)
const zip = await JSZip.loadAsync(out)
const comments = await zip.file('word/comments.xml')!.async('string')
expect(comments).toContain('w:id="1"')
expect(comments).toContain('w:author="用户"')
expect(comments).toContain('<w:t xml:space="preserve">第一条</w:t>')
expect(comments).toContain('<w:t xml:space="preserve">第二行</w:t>')
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
expect(rels).toContain('relationships/comments')
expect(rels).toContain('Target="comments.xml"')
const types = await zip.file('[Content_Types].xml')!.async('string')
expect(types).toContain('PartName="/word/comments.xml"')
const docXml = await zip.file('word/document.xml')!.async('string')
expect(docXml).toContain('<w:commentRangeStart w:id="1"/>')
expect(docXml).toContain('<w:commentReference w:id="1"/>')
// the saved file parses back with the comment attached
const again = await parseDocx(out)
expect(again.comments).toHaveLength(1)
expect(again.comments[0].text).toBe('第一条\n第二行')
expect(again.blocks[0].runs![0].commentIds).toEqual(['1'])
})
it('rewrites an existing comments.xml from the full list', async () => {
const parsed = await parseDocx(
await buildDocx({
bodyXml: '<w:p><w:r><w:t>hello</w:t></w:r></w:p>',
extraParts: [
{
path: 'word/comments.xml',
xml: COMMENTS_XML,
contentType:
'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml',
},
],
}),
)
const out = await saveDocx(
parsed,
parsed.blocks
.filter((b) => !b.hidden)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! })),
{
comments: [
{ id: '1', author: 'Alice', text: '已有批注' },
{ id: '2', author: '用户', text: '新加的' },
],
},
)
const zip = await JSZip.loadAsync(out)
const comments = await zip.file('word/comments.xml')!.async('string')
expect(comments).toContain('w:id="1"')
expect(comments).toContain('w:id="2"')
expect(comments).toContain('新加的')
})
})
describe('document protection', () => {
const SETTINGS_XML =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
'<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:zoom w:percent="100"/></w:settings>'
const withSettings = () =>
buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
extraParts: [
{
path: 'word/settings.xml',
xml: SETTINGS_XML,
contentType:
'application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml',
},
],
})
it('reports no protection for an unprotected document', async () => {
const doc = await parseDocx(await withSettings())
expect(doc.protection).toBeNull()
})
it('writes and re-reads w:documentProtection', async () => {
const parsed = await parseDocx(await withSettings())
const blocks: SaveBlock[] = parsed.blocks
.filter((b) => !b.hidden)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
const out = await saveDocx(parsed, blocks, {
protection: { edit: 'readOnly', enforced: true },
})
const again = await parseDocx(out)
expect(again.protection).toEqual({ edit: 'readOnly', enforced: true })
// removing it round-trips too
const cleared = await saveDocx(again, blocks, { protection: null })
expect((await parseDocx(cleared)).protection).toBeNull()
})
})
describe('mergePPrFormat', () => {
const RAW =
'<w:pPr><w:pStyle w:val="Body"/><w:keepNext/><w:tabs><w:tab w:val="left" w:pos="420"/></w:tabs>' +
'<w:spacing w:before="120" w:beforeAutospacing="1"/><w:jc w:val="left"/>' +
'<w:rPr><w:del w:id="31" w:author="Alice"/></w:rPr>' +
'<w:pPrChange w:id="51" w:author="Alice"><w:pPr><w:jc w:val="left"/></w:pPr></w:pPrChange></w:pPr>'
it('replaces managed children in place, keeps everything else byte-identical', () => {
const merged = mergePPrFormat(RAW, { align: 'center', spaceBefore: 240 })
expect(merged).toContain('<w:pStyle w:val="Body"/>')
expect(merged).toContain('<w:keepNext/>')
expect(merged).toContain('<w:tabs><w:tab w:val="left" w:pos="420"/></w:tabs>')
expect(merged).toContain('<w:rPr><w:del w:id="31" w:author="Alice"/></w:rPr>')
expect(merged).toContain('<w:pPrChange w:id="51"')
// rebuilt from the format model (old spacing/jc replaced)
expect(merged).toContain('<w:spacing w:before="240"/>')
expect(merged).toContain('<w:jc w:val="center"/>')
expect(merged).not.toContain('beforeAutospacing')
// schema order: tabs < spacing < jc < rPr
const order = [
'<w:keepNext/>',
'<w:tabs>',
'<w:spacing',
'<w:jc',
'<w:rPr>',
'<w:pPrChange',
].map((t) => merged.indexOf(t))
expect([...order].sort((a, b) => a - b)).toEqual(order)
})
it('clearing all format keeps only unmanaged children', () => {
const merged = mergePPrFormat(RAW, undefined)
expect(merged).toContain('<w:keepNext/>')
expect(merged).not.toContain('<w:spacing')
// the only remaining jc is the old value recorded inside pPrChange
expect(merged.indexOf('<w:jc')).toBeGreaterThan(merged.indexOf('<w:pPrChange'))
})
})
describe('stripPPrChange', () => {
it('removes pPrChange from a raw pPr slice', async () => {
const { stripPPrChange } = await import('../src/generate')
const raw =
'<w:pPr><w:jc w:val="center"/>' +
'<w:pPrChange w:id="51" w:author="Alice">' +
'<w:pPr><w:jc w:val="left"/></w:pPr>' +
'</w:pPrChange></w:pPr>'
const result = stripPPrChange(raw)
expect(result).toContain('<w:jc w:val="center"/>')
expect(result).not.toContain('<w:pPrChange')
expect(result).not.toContain('Alice')
})
it('returns unchanged string if no pPrChange', async () => {
const { stripPPrChange } = await import('../src/generate')
const raw = '<w:pPr><w:jc w:val="left"/></w:pPr>'
expect(stripPPrChange(raw)).toBe(raw)
})
})
describe('setPPrChange', () => {
it('writes a schema-ordered paragraph revision that parses after reopen', async () => {
const raw = '<w:pPr><w:spacing w:after="240"/><w:jc w:val="center"/></w:pPr>'
const revised = setPPrChange(
raw,
JSON.stringify({
author: 'Paragraph Reviewer',
date: '2026-07-30T09:00:00Z',
old: {
type: 'docParagraph',
styleId: 'BodyText',
format: {
align: 'left',
indentLeft: 120,
lineSpacing: 1,
spaceAfter: 80,
},
},
}),
)
expect(revised.indexOf('<w:pPrChange')).toBeGreaterThan(revised.indexOf('<w:jc'))
const parsed = await parseDocx(
await buildDocx({ bodyXml: `<w:p>${revised}<w:r><w:t>paragraph</w:t></w:r></w:p>` }),
)
expect(parsed.blocks[0].pPrChangeInfo).toMatchObject({
author: 'Paragraph Reviewer',
old: {
align: 'left',
indentLeft: 120,
lineSpacing: 1,
spaceAfter: 80,
},
})
})
})
@@ -0,0 +1,159 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx, type SaveBlock } from '../src/index'
import { buildKitchenSinkDocx } from './helpers/build-docx'
async function entryBytes(bytes: Uint8Array): Promise<Map<string, Uint8Array>> {
const zip = await JSZip.loadAsync(bytes)
const out = new Map<string, Uint8Array>()
for (const [name, entry] of Object.entries(zip.files)) {
if (!entry.dir) out.set(name, await entry.async('uint8array'))
}
return out
}
function asOriginal(indexes: number[]): SaveBlock[] {
return indexes.map((docxIndex) => ({ kind: 'original', docxIndex }))
}
describe('paragraph-patch save fidelity', () => {
it('no edits -> output is the exact original file (byte identical)', async () => {
const bytes = await buildKitchenSinkDocx()
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
const saved = await saveDocx(doc, asOriginal(visible))
expect(saved).toBe(bytes)
})
it('editing one paragraph leaves every other entry and every other w:p byte-identical', async () => {
const bytes = await buildKitchenSinkDocx()
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden)
// replace paragraph at docxIndex 1 (the rich text paragraph)
const finalBlocks: SaveBlock[] = visible.map((b) =>
b.docxIndex === 1
? {
kind: 'generated',
block: {
type: 'paragraph',
runs: [{ text: 'AI 重写后的段落。', bold: false }],
},
}
: { kind: 'original', docxIndex: b.docxIndex! },
)
const saved = await saveDocx(doc, finalBlocks)
const before = await entryBytes(bytes)
const after = await entryBytes(saved)
expect([...after.keys()].sort()).toEqual([...before.keys()].sort())
for (const [name, content] of before) {
if (name === 'word/document.xml') continue
expect(after.get(name), name).toEqual(content)
}
// untouched top-level elements keep their exact original XML slices
const newDocXml = new TextDecoder().decode(after.get('word/document.xml')!)
for (const block of doc.blocks) {
if (block.docxIndex === 1) continue
expect(newDocXml).toContain(block.originalXml!)
}
expect(newDocXml).toContain('AI 重写后的段落。')
expect(newDocXml).not.toContain('红色14号')
// and the patched file still parses
const reparsed = await parseDocx(saved)
expect(reparsed.blocks.filter((b) => !b.hidden)).toHaveLength(visible.length)
})
it('supports insert / delete / heading generation with existing styles', async () => {
const bytes = await buildKitchenSinkDocx()
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden)
const finalBlocks: SaveBlock[] = []
for (const b of visible) {
if (b.docxIndex === 10) continue // delete the trailing paragraph
finalBlocks.push({ kind: 'original', docxIndex: b.docxIndex! })
if (b.docxIndex === 0) {
finalBlocks.push({
kind: 'generated',
block: { type: 'heading', level: 2, runs: [{ text: '新增小节', bold: true }] },
})
finalBlocks.push({
kind: 'generated',
block: {
type: 'listItem',
list: { kind: 'bullet', numId: '1', ilvl: 0 },
runs: [{ text: '新增列表项' }],
},
})
}
}
const saved = await saveDocx(doc, finalBlocks)
const newDocXml = new TextDecoder().decode(
(await entryBytes(saved)).get('word/document.xml')!,
)
expect(newDocXml).toContain('<w:pStyle w:val="Heading2"/>')
expect(newDocXml).toContain('<w:pStyle w:val="ListParagraph"/>')
expect(newDocXml).toContain('<w:numId w:val="1"/>')
expect(newDocXml).not.toContain('尾段。')
// sectPr survives exactly once, at the end of the body
expect(newDocXml.match(/<w:sectPr>/g)).toHaveLength(1)
expect(newDocXml).toMatch(/<w:sectPr>[\s\S]*<\/w:sectPr><\/w:body>/)
const reparsed = await parseDocx(saved)
const types = reparsed.blocks.filter((b) => !b.hidden).map((b) => b.type)
expect(types[1]).toBe('heading')
expect(types[2]).toBe('listItem')
})
it('new hyperlinks get relationships appended to document.xml.rels', async () => {
const bytes = await buildKitchenSinkDocx()
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden)
const finalBlocks: SaveBlock[] = visible.map((b) =>
b.docxIndex === 10
? {
kind: 'generated',
block: {
type: 'paragraph',
runs: [
{ text: '访问 ' },
{ text: '新链接', link: { href: 'https://new.example.org/' } },
],
},
}
: { kind: 'original', docxIndex: b.docxIndex! },
)
const saved = await saveDocx(doc, finalBlocks)
const entries = await entryBytes(saved)
const rels = new TextDecoder().decode(entries.get('word/_rels/document.xml.rels')!)
expect(rels).toContain('Target="https://new.example.org/"')
expect(rels).toContain('TargetMode="External"')
const relId = /<Relationship Id="(rId\d+)"[^>]*new\.example\.org/.exec(rels)![1]
const docXml = new TextDecoder().decode(entries.get('word/document.xml')!)
expect(docXml).toContain(`<w:hyperlink r:id="${relId}">`)
const reparsed = await parseDocx(saved)
const lastPara = reparsed.blocks.filter((b) => !b.hidden).at(-1)!
expect(lastPara.runs?.find((r) => r.link)?.link?.href).toBe('https://new.example.org/')
})
it('passthrough blocks (table / image / math) can be moved as whole units', async () => {
const bytes = await buildKitchenSinkDocx()
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden)
const tableIdx = visible.find((b) => b.type === 'table')!.docxIndex!
const order = visible.map((b) => b.docxIndex!).filter((i) => i !== tableIdx)
order.unshift(tableIdx) // move table to the top
const saved = await saveDocx(doc, asOriginal(order))
const reparsed = await parseDocx(saved)
const newVisible = reparsed.blocks.filter((b) => !b.hidden)
expect(newVisible[0].type).toBe('table')
expect(newVisible[0].originalXml).toBe(doc.blocks[tableIdx].originalXml)
})
})
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
function rubyXml(base: string, rt: string): string {
return (
'<w:ruby><w:rubyPr><w:rubyAlign w:val="distributeSpace"/><w:hps w:val="12"/>' +
'<w:hpsRaise w:val="22"/><w:hpsBaseText w:val="24"/><w:lid w:val="zh-CN"/></w:rubyPr>' +
`<w:rt><w:r><w:rPr><w:sz w:val="12"/></w:rPr><w:t>${rt}</w:t></w:r></w:rt>` +
`<w:rubyBase><w:r><w:t>${base}</w:t></w:r></w:rubyBase></w:ruby>`
)
}
describe('phonetic guide (w:ruby)', () => {
it('parses ruby runs keeping the base characters and phonetic text', async () => {
const p =
`<w:p><w:r>${rubyXml('床', 'chuáng')}</w:r><w:r>${rubyXml('前', 'qián')}</w:r>` +
'<w:r><w:t>,</w:t></w:r></w:p>'
const parsed = await parseDocx(await buildDocx({ bodyXml: p }))
const block = parsed.blocks[0]
expect(block.type).toBe('paragraph')
expect(block.runs?.map((r) => r.text)).toEqual(['床', '前', ','])
expect(block.runs?.[0].ruby).toEqual({ rt: 'chuáng', xml: rubyXml('床', 'chuáng') })
expect(block.runs?.[1].ruby?.rt).toBe('qián')
expect(block.runs?.[2].ruby).toBeUndefined()
})
it('an edited paragraph re-emits ruby fragments verbatim', async () => {
const p = `<w:p><w:r>${rubyXml('月', 'yuè')}</w:r><w:r><w:t>。</w:t></w:r></w:p>`
const parsed = await parseDocx(await buildDocx({ bodyXml: p }))
const block = parsed.blocks[0]
const bytes = await saveDocx(parsed, [
{
kind: 'generated',
block: { type: 'paragraph', runs: [{ text: 'edited ' }, ...block.runs!.filter((r) => r.ruby)] },
},
])
const reparsed = await parseDocx(bytes)
const rb = reparsed.blocks[0]
expect(rb.runs?.map((r) => r.text)).toEqual(['edited ', '月'])
expect(rb.runs?.[1].ruby).toEqual({ rt: 'yuè', xml: rubyXml('月', 'yuè') })
})
it('an untouched ruby paragraph round-trips byte-preserving', async () => {
const p = `<w:p><w:r>${rubyXml('霜', 'shuāng')}</w:r></w:p>`
const parsed = await parseDocx(await buildDocx({ bodyXml: p }))
const bytes = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }])
const reparsed = await parseDocx(bytes)
expect(reparsed.blocks[0].runs?.[0].text).toBe('霜')
expect(reparsed.blocks[0].runs?.[0].ruby?.xml).toBe(rubyXml('霜', 'shuāng'))
})
it('multi-run ruby base and rt concatenate', async () => {
const ruby =
'<w:ruby><w:rubyPr/><w:rt><w:r><w:t>gù</w:t></w:r><w:r><w:t>xiāng</w:t></w:r></w:rt>' +
'<w:rubyBase><w:r><w:t>故</w:t></w:r><w:r><w:t>乡</w:t></w:r></w:rubyBase></w:ruby>'
const parsed = await parseDocx(await buildDocx({ bodyXml: `<w:p><w:r>${ruby}</w:r></w:p>` }))
const run = parsed.blocks[0].runs?.[0]
expect(run?.text).toBe('故乡')
expect(run?.ruby?.rt).toBe('gùxiāng')
})
})
@@ -0,0 +1,80 @@
/**
* OOXML schema-order gatekeeper: in the output of mergeRPrModel/mergePPrFormat, known
* children must appear in CT_RPr/CT_PPr sequence — wrong order makes Word show the
* "repair" dialog.
*/
import { describe, expect, it } from 'vitest'
import {
mergePPrFormat,
mergeRPrModel,
PPR_CHILD_ORDER,
RPR_CHILD_ORDER,
splitXmlChildren,
} from '../src/generate'
/** Assert the ranks of known children inside the fragment are non-decreasing (unknown elements skipped) */
function assertSchemaOrder(fragment: string, rootTag: string, order: readonly string[]) {
const open = new RegExp(`^<${rootTag}(?: [^>]*)?>`).exec(fragment)?.[0]
if (!open) return // empty or self-closing: no children to verify
const inner = fragment.slice(open.length, fragment.length - `</${rootTag}>`.length)
let prev = -1
let prevName = ''
for (const child of splitXmlChildren(inner)) {
const rank = order.indexOf(child.name)
if (rank === -1) continue
expect(rank, `${child.name} appears after ${prevName}, violating the ${rootTag} schema order`).toBeGreaterThanOrEqual(prev)
prev = rank
prevName = child.name
}
}
describe('rPr schema order (mergeRPrModel)', () => {
const RAW =
'<w:rPr><w:rFonts w:ascii="Georgia"/><w:caps/><w:strike/><w:color w:val="112233"/>' +
'<w:sz w:val="24"/><w:u w:val="double"/><w:bdr w:val="single"/><w:lang w:val="en-US"/></w:rPr>'
it.each([
['add bold', { text: 'x', bold: true }],
['add italic + highlight', { text: 'x', italic: true, highlight: 'yellow' }],
['change color + size', { text: 'x', color: 'FF0000', sizeHalfPoints: 36 }],
['add style + vertAlign', { text: 'x', styleId: 'Emphasis', vertAlign: 'superscript' as const }],
['clear underline + add font', { text: 'x', underline: false, font: '微软雅黑' }],
])('%s keeps CT_RPr child order', (_label, run) => {
const out = mergeRPrModel(RAW, { ...run }, false)
assertSchemaOrder(out, 'w:rPr', RPR_CHILD_ORDER)
})
it('hyperlink rStyle lands first even with raw children present', () => {
// font matches raw (a parsed run always carries font) → the rFonts group keeps its
// original bytes
const out = mergeRPrModel(RAW, { text: 'x', bold: true, font: 'Georgia' }, true)
assertSchemaOrder(out, 'w:rPr', RPR_CHILD_ORDER)
expect(out.indexOf('<w:rStyle')).toBeLessThan(out.indexOf('<w:rFonts'))
})
it('raw children in unusual-but-valid subsets still merge in order', () => {
const sparse = '<w:rPr><w:vanish/><w:vertAlign w:val="subscript"/></w:rPr>'
const out = mergeRPrModel(sparse, { text: 'x', bold: true, color: 'AA0000' }, false)
assertSchemaOrder(out, 'w:rPr', RPR_CHILD_ORDER)
expect(out.indexOf('<w:b/>')).toBeLessThan(out.indexOf('<w:vanish/>'))
expect(out.indexOf('<w:vanish/>')).toBeLessThan(out.indexOf('<w:color'))
})
})
describe('pPr schema order (mergePPrFormat)', () => {
const RAW =
'<w:pPr><w:pStyle w:val="Heading1"/><w:keepNext/><w:tabs><w:tab w:val="left" w:pos="420"/></w:tabs>' +
'<w:rPr><w:b/></w:rPr></w:pPr>'
it.each([
['spacing + align', { spaceBefore: 120, align: 'center' as const }],
['borders + shading', { borders: 'tb', shadingFill: 'EEEEEE' }],
['indent + pageBreak', { indentLeft: 720, pageBreakBefore: true }],
])('%s keeps CT_PPr child order', (_label, format) => {
const out = mergePPrFormat(RAW, format)
assertSchemaOrder(out, 'w:pPr', PPR_CHILD_ORDER)
// The paragraph-mark rPr must still sit at the end (one of the highest-ranked known
// elements inside pPr)
expect(out).toContain('<w:rPr><w:b/></w:rPr>')
})
})
+257
View File
@@ -0,0 +1,257 @@
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
// ---- SDT fixture XML fragments ----
/** Block-level SDT wrapping a text paragraph with alias "Author" */
const BLOCK_SDT_P =
'<w:sdt>' +
'<w:sdtPr>' +
'<w:alias w:val="Author Name"/>' +
'<w:tag w:val="author"/>' +
'<w:text/>' +
'</w:sdtPr>' +
'<w:sdtEndPr/>' +
'<w:sdtContent>' +
'<w:p><w:r><w:t>Jane Doe</w:t></w:r></w:p>' +
'</w:sdtContent>' +
'</w:sdt>'
/** Block-level SDT with date picker */
const DATE_SDT_P =
'<w:sdt>' +
'<w:sdtPr>' +
'<w:alias w:val="Date"/>' +
'<w:date>' +
'<w:dateFormat w:val="yyyy-MM-dd"/>' +
'</w:date>' +
'</w:sdtPr>' +
'<w:sdtContent>' +
'<w:p><w:r><w:t>2026-07-26</w:t></w:r></w:p>' +
'</w:sdtContent>' +
'</w:sdt>'
/** Block-level SDT with dropdown */
const DROPDOWN_SDT_P =
'<w:sdt>' +
'<w:sdtPr>' +
'<w:alias w:val="Status"/>' +
'<w:dropDownList>' +
'<w:listItem w:value="Draft" w:displayText="Draft"/>' +
'<w:listItem w:value="Final" w:displayText="Final"/>' +
'</w:dropDownList>' +
'</w:sdtPr>' +
'<w:sdtContent>' +
'<w:p><w:r><w:t>Draft</w:t></w:r></w:p>' +
'</w:sdtContent>' +
'</w:sdt>'
/** Plain paragraph (no SDT) */
const PLAIN_P = '<w:p><w:r><w:t>plain text no sdt</w:t></w:r></w:p>'
describe('SDT parsing', () => {
it('parses block-level w:sdt and exposes alias/tag/controlType', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BLOCK_SDT_P }))
const block = doc.blocks[0]
expect(block.sdtShell).toBeDefined()
expect(block.sdtShell!.alias).toBe('Author Name')
expect(block.sdtShell!.tag).toBe('author')
expect(block.sdtShell!.controlType).toBe('text')
})
it('parses date SDT as controlType "date"', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: DATE_SDT_P }))
expect(doc.blocks[0].sdtShell?.controlType).toBe('date')
expect(doc.blocks[0].sdtShell?.alias).toBe('Date')
})
it('parses dropdown SDT as controlType "dropdown"', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: DROPDOWN_SDT_P }))
expect(doc.blocks[0].sdtShell?.controlType).toBe('dropdown')
})
it('extracts the sdtContent paragraph runs as editable block runs', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BLOCK_SDT_P }))
const block = doc.blocks[0]
expect(block.runs?.some((r) => r.text.includes('Jane Doe'))).toBe(true)
})
it('plain paragraph has no sdtShell', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: PLAIN_P }))
expect(doc.blocks[0].sdtShell).toBeUndefined()
})
})
describe('SDT roundtrip', () => {
it('untouched SDT block saves byte-identical (sdt shell preserved)', async () => {
const bytes = await buildDocx({ bodyXml: BLOCK_SDT_P })
const doc = await parseDocx(bytes)
const saved = await saveDocx(doc, [{ kind: 'original', docxIndex: 0 }])
const reparsed = await parseDocx(saved)
// The shell must be preserved
expect(reparsed.blocks[0].sdtShell?.alias).toBe('Author Name')
// sdtContent text must be preserved
expect(reparsed.blocks[0].runs?.some((r) => r.text.includes('Jane Doe'))).toBe(true)
// Re-saved XML must contain the sdt shell elements
expect(reparsed.internal.documentXml).toContain('<w:sdt>')
expect(reparsed.internal.documentXml).toContain('w:val="Author Name"')
expect(reparsed.internal.documentXml).toContain('Jane Doe')
})
it('sdt shell openXml contains original sdtPr bytes', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BLOCK_SDT_P }))
const shell = doc.blocks[0].sdtShell!
expect(shell.openXml).toContain('<w:sdt>')
expect(shell.openXml).toContain('<w:sdtPr>')
expect(shell.openXml).toContain('Author Name')
expect(shell.openXml).toContain('<w:sdtContent>')
expect(shell.closeXml).toBe('</w:sdtContent></w:sdt>')
})
})
// ---- Multi-paragraph SDT (Word automatic TOC) ----
const TOC_ENTRY = (n: number) =>
'<w:p><w:pPr><w:pStyle w:val="TOC1"/></w:pPr>' +
`<w:r><w:t>Chapter ${n}</w:t></w:r>` +
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
`<w:r><w:instrText xml:space="preserve"> PAGEREF _Toc${n} \\h </w:instrText></w:r>` +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
`<w:r><w:t>${n}</w:t></w:r>` +
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
'</w:p>'
const TOC_SDT =
'<w:sdt>' +
'<w:sdtPr><w:id w:val="-1"/>' +
'<w:docPartObj><w:docPartGallery w:val="Table of Contents"/><w:docPartUnique/></w:docPartObj>' +
'</w:sdtPr>' +
'<w:sdtEndPr/>' +
'<w:sdtContent>' +
'<w:p><w:pPr><w:pStyle w:val="TOCHeading"/></w:pPr><w:r><w:t>Contents</w:t></w:r></w:p>' +
Array.from({ length: 13 }, (_, i) => TOC_ENTRY(i + 1)).join('') +
'<w:p><w:r><w:t>tail</w:t></w:r></w:p>' +
'</w:sdtContent>' +
'</w:sdt>'
const sdtOpenCount = (xml: string) => (xml.match(/<w:sdt>/g) ?? []).length
const sdtCloseCount = (xml: string) => (xml.match(/<\/w:sdt>/g) ?? []).length
describe('multi-paragraph SDT (TOC)', () => {
it('yields one block per sdtContent child paragraph', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: TOC_SDT }))
const visible = doc.blocks.filter((b) => !b.hidden)
expect(visible.length).toBe(15)
expect(visible[0].runs?.some((r) => r.text.includes('Contents'))).toBe(true)
for (let n = 1; n <= 13; n++) {
expect(visible[n].type).toBe('passthrough')
expect(visible[n].previewText).toContain(`Chapter ${n}`)
}
expect(visible.map((b) => b.docxIndex)).toEqual(visible.map((_, i) => i))
})
it('splits the shell: first block opens, last block closes, middles carry none', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: TOC_SDT }))
const visible = doc.blocks.filter((b) => !b.hidden)
const shells = visible.map((b) => b.sdtShell!)
expect(shells.every((s) => s !== undefined)).toBe(true)
expect(new Set(shells.map((s) => s.group)).size).toBe(1)
expect(shells[0].group).not.toBeUndefined()
expect(shells[0].openXml).toContain('<w:sdt>')
expect(shells[0].openXml).toContain('Table of Contents')
expect(shells[0].openXml).toContain('<w:sdtContent>')
expect(shells[0].closeXml).toBe('')
for (const s of shells.slice(1, -1)) {
expect(s.openXml).toBe('')
expect(s.closeXml).toBe('')
}
expect(shells[14].openXml).toBe('')
expect(shells[14].closeXml).toBe('</w:sdtContent></w:sdt>')
})
it('untouched multi-paragraph sdt saves byte-identical', async () => {
const bytes = await buildDocx({ bodyXml: TOC_SDT })
const doc = await parseDocx(bytes)
const saved = await saveDocx(
doc,
doc.blocks
.filter((b) => !b.hidden)
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
)
expect(Buffer.from(saved).equals(Buffer.from(bytes))).toBe(true)
})
it('regenerating a middle paragraph keeps a single balanced sdt', async () => {
const bytes = await buildDocx({ bodyXml: TOC_SDT })
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden)
const finalBlocks = visible.map((b, i) =>
i === 7
? {
kind: 'generated' as const,
block: {
type: 'paragraph' as const,
runs: [{ text: 'edited entry' }],
sdtShell: b.sdtShell,
},
}
: { kind: 'original' as const, docxIndex: b.docxIndex! },
)
const saved = await saveDocx(doc, finalBlocks)
const reparsed = await parseDocx(saved)
const xml = reparsed.internal.documentXml
expect(sdtOpenCount(xml)).toBe(1)
expect(sdtCloseCount(xml)).toBe(1)
const contentOpen = xml.indexOf('<w:sdtContent>')
const contentClose = xml.indexOf('</w:sdtContent>')
const edited = xml.indexOf('edited entry')
expect(edited).toBeGreaterThan(contentOpen)
expect(edited).toBeLessThan(contentClose)
expect(reparsed.blocks.filter((b) => !b.hidden).length).toBe(15)
})
it('regenerating the first and last paragraphs re-emits their shell halves', async () => {
const bytes = await buildDocx({ bodyXml: TOC_SDT })
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden)
const finalBlocks = visible.map((b, i) =>
i === 0 || i === visible.length - 1
? {
kind: 'generated' as const,
block: {
type: 'paragraph' as const,
runs: [{ text: i === 0 ? 'New Title' : 'new tail' }],
sdtShell: b.sdtShell,
},
}
: { kind: 'original' as const, docxIndex: b.docxIndex! },
)
const saved = await saveDocx(doc, finalBlocks)
const xml = (await parseDocx(saved)).internal.documentXml
expect(sdtOpenCount(xml)).toBe(1)
expect(sdtCloseCount(xml)).toBe(1)
expect(xml.indexOf('New Title')).toBeGreaterThan(xml.indexOf('<w:sdtContent>'))
expect(xml.indexOf('new tail')).toBeLessThan(xml.indexOf('</w:sdtContent>'))
})
it('sdt wrapping a table plus a paragraph yields a table block and a paragraph block', async () => {
const MIXED_SDT =
'<w:sdt><w:sdtPr><w:alias w:val="Report"/></w:sdtPr><w:sdtContent>' +
'<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
'<w:tr><w:tc><w:tcPr/><w:p><w:r><w:t>cell A</w:t></w:r></w:p></w:tc></w:tr></w:tbl>' +
'<w:p><w:r><w:t>after table</w:t></w:r></w:p>' +
'</w:sdtContent></w:sdt>'
const bytes = await buildDocx({ bodyXml: MIXED_SDT })
const doc = await parseDocx(bytes)
const visible = doc.blocks.filter((b) => !b.hidden)
expect(visible.length).toBe(2)
expect(visible[0].type).toBe('table')
expect(visible[1].runs?.some((r) => r.text.includes('after table'))).toBe(true)
const saved = await saveDocx(
doc,
visible.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
)
expect(Buffer.from(saved).equals(Buffer.from(bytes))).toBe(true)
})
})
+431
View File
@@ -0,0 +1,431 @@
import { describe, expect, it } from 'vitest'
import {
applySectionSettings,
applySectionStartType,
parseDocx,
readSections,
readSectionSettings,
saveDocx,
type SaveBlock,
} from '../src/index'
import { buildDocx } from './helpers/build-docx'
const P = (text: string) => `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`
/** Paragraph-level sectPr (section break): landscape A4 + narrow margins + optional continuous */
const sectBreakPara = (
opts: { landscape?: boolean; continuous?: boolean; extra?: string } = {},
) => {
const size = opts.landscape
? '<w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/>'
: '<w:pgSz w:w="11906" w:h="16838"/>'
return (
'<w:p><w:pPr><w:sectPr>' +
(opts.continuous ? '<w:type w:val="continuous"/>' : '') +
size +
'<w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720" w:header="708" w:footer="708" w:gutter="0"/>' +
(opts.extra ?? '') +
'</w:sectPr></w:pPr></w:p>'
)
}
describe('readSections enumerates all sections', () => {
it('single-section document: one section covers all blocks, trailing sectPr provides settings', async () => {
const parsed = await parseDocx(await buildDocx({ bodyXml: P('a') + P('b') }))
const sections = readSections(parsed)
expect(sections.length).toBe(1)
expect(sections[0].firstBlockIndex).toBe(0)
expect(sections[0].settings.pageWidth).toBe(11906)
expect(sections[0].startType).toBe('nextPage')
expect(sections[0].settings).toEqual(readSectionSettings(parsed))
})
it('two sections: paragraph-level sectPr ends section 1 with correct block ranges', async () => {
const bodyXml = P('第一节') + sectBreakPara({ landscape: true }) + P('第二节') + P('尾段')
const parsed = await parseDocx(await buildDocx({ bodyXml }))
const sections = readSections(parsed)
expect(sections.length).toBe(2)
// Section 1: block 0 (paragraph) + block 1 (section-break paragraph), landscape narrow margins
expect(sections[0].firstBlockIndex).toBe(0)
expect(sections[0].lastBlockIndex).toBe(1)
expect(sections[0].settings.orientation).toBe('landscape')
expect(sections[0].settings.pageWidth).toBe(16838)
expect(sections[0].settings.marginTop).toBe(720)
// Section 2: blocks 2..3 + the trailing hidden section-properties block, portrait A4 default margins
expect(sections[1].firstBlockIndex).toBe(2)
expect(sections[1].settings.orientation).toBe('portrait')
expect(sections[1].settings.pageWidth).toBe(11906)
expect(sections[1].settings.marginTop).toBe(1440)
expect(sections[1].firstBlockIndex).toBe(sections[0].lastBlockIndex + 1)
})
it('parses startType/titlePg/pgNumType/header-footer references per section', async () => {
const extra =
'<w:headerReference w:type="default" r:id="rId7"/>' +
'<w:footerReference w:type="first" r:id="rId8"/>' +
'<w:titlePg/><w:pgNumType w:start="5"/>'
const bodyXml = P('a') + sectBreakPara({ continuous: true, extra }) + P('b')
const parsed = await parseDocx(await buildDocx({ bodyXml }))
const sections = readSections(parsed)
expect(sections[0].startType).toBe('continuous')
expect(sections[0].titlePg).toBe(true)
expect(sections[0].pageNumberStart).toBe(5)
expect(sections[0].headerRefs.default).toBe('rId7')
expect(sections[0].footerRefs.first).toBe('rId8')
expect(sections[1].startType).toBe('nextPage')
expect(sections[1].titlePg).toBe(false)
expect(sections[1].pageNumberStart).toBeUndefined()
})
it('three sections with mixed portrait/landscape', async () => {
const bodyXml =
P('纵向一') + sectBreakPara() + P('横向二') + sectBreakPara({ landscape: true }) + P('纵向三')
const parsed = await parseDocx(await buildDocx({ bodyXml }))
const sections = readSections(parsed)
expect(sections.map((s) => s.settings.orientation)).toEqual([
'portrait',
'landscape',
'portrait',
])
expect(sections.map((s) => s.firstBlockIndex)).toEqual([0, 2, 4])
})
it('hfParts: parses all header/footer parts by rId (PAGE field displayed as #)', async () => {
const XML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'
const headerXml = `${XML}<w:hdr ${W}><w:p><w:r><w:t>第一节页眉</w:t></w:r></w:p></w:hdr>`
const footerXml =
`${XML}<w:ftr ${W}><w:p><w:r><w:t>第 </w:t></w:r>` +
'<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> PAGE </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t> 页</w:t></w:r></w:p></w:ftr>'
const REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
const bytes = await buildDocx({
bodyXml:
P('a') +
sectBreakPara({
extra:
'<w:headerReference w:type="default" r:id="rId20"/><w:footerReference w:type="default" r:id="rId21"/>',
}) +
P('b'),
extraRels:
`<Relationship Id="rId20" Type="${REL}/header" Target="header1.xml"/>` +
`<Relationship Id="rId21" Type="${REL}/footer" Target="footer1.xml"/>`,
extraParts: [
{
path: 'word/header1.xml',
xml: headerXml,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
},
{
path: 'word/footer1.xml',
xml: footerXml,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml',
},
],
})
const parsed = await parseDocx(bytes)
expect(parsed.hfParts?.rId20?.text).toBe('第一节页眉')
expect(parsed.hfParts?.rId21?.hasPageNumber).toBe(true)
expect(parsed.hfParts?.rId21?.text).toContain('#')
const sections = readSections(parsed)
expect(sections[0].headerRefs.default).toBe('rId20')
expect(sections[0].footerRefs.default).toBe('rId21')
expect(sections[1].headerRefs.default).toBeUndefined()
})
it('applySectionStartType: inserts/replaces/removes w:type', () => {
const base = '<w:sectPr><w:pgSz w:w="1" w:h="2"/></w:sectPr>'
expect(applySectionStartType(base, 'continuous')).toBe(
'<w:sectPr><w:type w:val="continuous"/><w:pgSz w:w="1" w:h="2"/></w:sectPr>',
)
const cont = '<w:sectPr><w:type w:val="continuous"/><w:pgSz w:w="1" w:h="2"/></w:sectPr>'
expect(applySectionStartType(cont, 'evenPage')).toContain('<w:type w:val="evenPage"/>')
expect(applySectionStartType(cont, 'nextPage')).toBe(base)
// Without pgSz, insert at the start of sectPr
expect(applySectionStartType('<w:sectPr></w:sectPr>', 'oddPage')).toBe(
'<w:sectPr><w:type w:val="oddPage"/></w:sectPr>',
)
})
it('section edit round-trip: non-final sectPr rewritten via kind:xml, final section via options.section', async () => {
const bytes = await buildDocx({
bodyXml: P('第一节') + sectBreakPara({ landscape: true }) + P('第二节'),
})
const parsed = await parseDocx(bytes)
const sections = readSections(parsed)
// Section 1: landscape → change to portrait narrow margins (simulating layout applied
// to the section under the cursor)
const edited = {
...sections[0].settings,
orientation: 'portrait' as const,
pageWidth: sections[0].settings.pageHeight,
pageHeight: sections[0].settings.pageWidth,
marginTop: 567,
}
const breakBlock = parsed.blocks.find((b) => b.docxIndex === sections[0].lastBlockIndex)!
const newXml = breakBlock.originalXml!.replace(
sections[0].sectPrXml,
applySectionStartType(applySectionSettings(sections[0].sectPrXml, edited), 'continuous'),
)
const finalBlocks: SaveBlock[] = parsed.blocks
.filter((b) => !b.hidden)
.map((b) =>
b.docxIndex === sections[0].lastBlockIndex
? { kind: 'xml', xml: newXml }
: { kind: 'original', docxIndex: b.docxIndex! },
)
const saved = await saveDocx(parsed, finalBlocks, {
section: { ...sections[1].settings, marginLeft: 999 },
})
const reparsed = readSections(await parseDocx(saved))
expect(reparsed[0].settings.orientation).toBe('portrait')
expect(reparsed[0].settings.marginTop).toBe(567)
expect(reparsed[0].startType).toBe('continuous')
expect(reparsed[1].settings.marginLeft).toBe(999)
})
it('insert section break: new break paragraph via kind:xml + trailing sectPr gets w:type', async () => {
const bytes = await buildDocx({ bodyXml: P('a') + P('b') })
const parsed = await parseDocx(bytes)
const sections = readSections(parsed)
expect(sections.length).toBe(1)
const breakXml = `<w:p><w:pPr>${'<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/></w:sectPr>'}</w:pPr></w:p>`
const visible = parsed.blocks.filter((b) => !b.hidden)
const finalBlocks: SaveBlock[] = [
{ kind: 'original', docxIndex: visible[0].docxIndex! },
{ kind: 'xml', xml: breakXml },
{ kind: 'original', docxIndex: visible[1].docxIndex! },
]
const saved = await saveDocx(parsed, finalBlocks, { sectionStartType: 'continuous' })
const reparsed = readSections(await parseDocx(saved))
expect(reparsed.length).toBe(2)
expect(reparsed[0].lastBlockIndex).toBe(1)
expect(reparsed[1].startType).toBe('continuous')
expect(reparsed[1].firstBlockIndex).toBe(2)
})
it('unedited multi-section document saves byte-identical', async () => {
const bytes = await buildDocx({
bodyXml: P('第一节') + sectBreakPara({ landscape: true }) + P('第二节'),
})
const parsed = await parseDocx(bytes)
readSections(parsed)
const visible: SaveBlock[] = parsed.blocks
.filter((b) => !b.hidden)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
expect(await saveDocx(parsed, visible)).toBe(bytes)
})
})
describe('sectionHf per-section headers/footers', () => {
const visibleBlocks = (parsed: Awaited<ReturnType<typeof parseDocx>>): SaveBlock[] =>
parsed.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
it('section without references: new part + reference injected into that sectPr, neighbors unaffected', async () => {
const bodyXml = P('第一节') + sectBreakPara() + P('第二节')
const parsed = await parseDocx(await buildDocx({ bodyXml }))
const sections = readSections(parsed)
expect(sections[0].headerRefs.default).toBeUndefined()
const saved = await saveDocx(parsed, visibleBlocks(parsed), {
sectionHf: [
{ lastBlockIndex: sections[0].lastBlockIndex, kind: 'header', hf: { text: '第一节页眉' } },
],
})
const reparsed = await parseDocx(saved)
const secs = readSections(reparsed)
const rId = secs[0].headerRefs.default
expect(rId).toBeDefined()
expect(reparsed.hfParts?.[rId!]?.text).toContain('第一节页眉')
// The last section did not get a reference stuffed in
expect(secs[1].headerRefs.default).toBeUndefined()
// The reference is the first child of that section's sectPr
const zip = await (await import('jszip')).default.loadAsync(saved)
const docXml = await zip.file('word/document.xml')!.async('string')
expect(docXml).toMatch(/<w:sectPr[^>]*><w:headerReference w:type="default"/)
})
it('section with an existing reference: rewrites the referenced part instead of creating one', async () => {
const HDR =
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:p><w:r><w:t>旧页眉</w:t></w:r></w:p></w:hdr>'
const bodyXml =
P('第一节') +
sectBreakPara({ extra: '<w:headerReference w:type="default" r:id="rId60"/>' }) +
P('第二节')
const bytes = await buildDocx({
bodyXml,
extraRels:
'<Relationship Id="rId60" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
extraParts: [
{
path: 'word/header1.xml',
xml: HDR,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
},
],
})
const parsed = await parseDocx(bytes)
const sections = readSections(parsed)
expect(sections[0].headerRefs.default).toBe('rId60')
const saved = await saveDocx(parsed, visibleBlocks(parsed), {
sectionHf: [
{ lastBlockIndex: sections[0].lastBlockIndex, kind: 'header', hf: { text: '新页眉' } },
],
})
const zip = await (await import('jszip')).default.loadAsync(saved)
const hdr = await zip.file('word/header1.xml')!.async('string')
expect(hdr).toContain('新页眉')
expect(zip.file('word/header2.xml')).toBeNull()
// Reference count unchanged (no duplicate injection)
const docXml = await zip.file('word/document.xml')!.async('string')
expect(docXml.match(/<w:headerReference/g)).toHaveLength(1)
})
it('kind:xml section-break block (layout rewritten in the same pass) can also receive references', async () => {
const bodyXml = P('第一节') + sectBreakPara({ landscape: true }) + P('第二节')
const parsed = await parseDocx(await buildDocx({ bodyXml }))
const sections = readSections(parsed)
const breakBlock = parsed.blocks.find((b) => b.docxIndex === sections[0].lastBlockIndex)!
const rewritten = applySectionSettings(sections[0].sectPrXml, {
...sections[0].settings,
marginTop: 720,
})
const finalBlocks: SaveBlock[] = parsed.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) =>
b.docxIndex === sections[0].lastBlockIndex
? {
kind: 'xml' as const,
xml: breakBlock.originalXml!.replace(sections[0].sectPrXml, rewritten),
docxIndex: b.docxIndex!,
}
: { kind: 'original' as const, docxIndex: b.docxIndex! },
)
const saved = await saveDocx(parsed, finalBlocks, {
sectionHf: [
{ lastBlockIndex: sections[0].lastBlockIndex, kind: 'footer', hf: { text: '第一节页脚' } },
],
})
const reparsed = await parseDocx(saved)
const secs = readSections(reparsed)
expect(secs[0].settings.marginTop).toBe(720)
const rId = secs[0].footerRefs.default
expect(rId).toBeDefined()
expect(reparsed.hfParts?.[rId!]?.text).toContain('第一节页脚')
})
})
describe('pgNumType page numbering', () => {
it('applyPageNumType inserts/replaces/removes', async () => {
const { applyPageNumType } = await import('../src/index')
const base =
'<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/><w:cols w:space="425"/></w:sectPr>'
const withFmt = applyPageNumType(base, 'lowerRoman', 3)
expect(withFmt).toContain('<w:pgNumType w:fmt="lowerRoman" w:start="3"/><w:cols')
// Replacement does not duplicate
const replaced = applyPageNumType(withFmt, 'upperLetter', undefined)
expect(replaced.match(/<w:pgNumType/g)).toHaveLength(1)
expect(replaced).toContain('w:fmt="upperLetter"')
expect(replaced).not.toContain('w:start=')
// All-unset removes the tag
expect(applyPageNumType(withFmt, undefined, undefined)).not.toContain('pgNumType')
// Without cols it lands right before </w:sectPr>
const noCols = base.replace('<w:cols w:space="425"/>', '')
expect(applyPageNumType(noCols, 'decimal', undefined)).toContain(
'<w:pgNumType w:fmt="decimal"/></w:sectPr>',
)
})
it('SaveOptions.pgNumType writes the final section and round-trips', async () => {
const parsed = await parseDocx(await buildDocx({ bodyXml: P('正文') }))
const blocks: SaveBlock[] = parsed.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
const saved = await saveDocx(parsed, blocks, { pgNumType: { fmt: 'upperRoman', start: 5 } })
const secs = readSections(await parseDocx(saved))
expect(secs[0].pageNumberFmt).toBe('upperRoman')
expect(secs[0].pageNumberStart).toBe(5)
})
})
describe('SaveOptions.numbering write-back', () => {
const P2 = (text: string) => `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`
const LI = (numId: number, text: string) =>
`<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="${numId}"/></w:numPr></w:pPr><w:r><w:t>${text}</w:t></w:r></w:p>`
const NUMBERING =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:abstractNum w:abstractNumId="3"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum>' +
'<w:num w:numId="5"><w:abstractNumId w:val="3"/></w:num>' +
'</w:numbering>'
it('restartNums: appends a w:num pointing at an existing abstractNum + startOverride', async () => {
const bytes = await buildDocx({
bodyXml: LI(5, '一') + LI(5, '二'),
numberingXml: NUMBERING,
})
const parsed = await parseDocx(bytes)
const blocks: SaveBlock[] = parsed.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
const saved = await saveDocx(parsed, blocks, {
numbering: { restartNums: [{ numId: '6', abstractNumId: '3', startOverrides: { 0: 1 } }] },
})
const reparsed = await parseDocx(saved)
const def = reparsed.numbering.get('6')
expect(def).toBeDefined()
expect(def!.abstractNumId).toBe('3')
expect(def!.startOverrides[0]).toBe(1)
// Existing entries keep their original bytes
const zip = await (await import('jszip')).default.loadAsync(saved)
const numXml = await zip.file('word/numbering.xml')!.async('string')
expect(numXml).toContain('<w:num w:numId="5"><w:abstractNumId w:val="3"/></w:num>')
})
it('newDefs: allocates a new abstractNum; creates part/rel/ContentType when numbering.xml is missing', async () => {
const bytes = await buildDocx({ bodyXml: P2('正文') })
const parsed = await parseDocx(bytes)
const blocks: SaveBlock[] = parsed.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
const saved = await saveDocx(parsed, blocks, {
numbering: { newDefs: [{ numId: '10', kind: 'ordered' }] },
})
const reparsed = await parseDocx(saved)
const def = reparsed.numbering.get('10')
expect(def).toBeDefined()
expect(def!.levels[0].numFmt).toBe('decimal')
// numIds 1/2 from the blank-template base are also present
expect(reparsed.numbering.get('1')!.levels[0].numFmt).toBe('bullet')
const zip = await (await import('jszip')).default.loadAsync(saved)
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
expect(rels).toContain('Target="numbering.xml"')
const ct = await zip.file('[Content_Types].xml')!.async('string')
expect(ct).toContain('PartName="/word/numbering.xml"')
// The abstract id does not clash with the template's 0/1
const numXml = await zip.file('word/numbering.xml')!.async('string')
expect(numXml).toContain('<w:num w:numId="10"><w:abstractNumId w:val="2"/></w:num>')
})
it('with an existing numbering.xml, newDefs abstracts are inserted before w:num entries', async () => {
const bytes = await buildDocx({ bodyXml: LI(5, '一'), numberingXml: NUMBERING })
const parsed = await parseDocx(bytes)
const blocks: SaveBlock[] = parsed.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
const saved = await saveDocx(parsed, blocks, {
numbering: { newDefs: [{ numId: '9', kind: 'bullet' }] },
})
const zip = await (await import('jszip')).default.loadAsync(saved)
const numXml = await zip.file('word/numbering.xml')!.async('string')
// The new abstract (id=4) comes before the first w:num; the new num goes at the end
expect(numXml.indexOf('w:abstractNumId="4"')).toBeLessThan(numXml.indexOf('<w:num '))
expect(numXml).toContain('<w:num w:numId="9"><w:abstractNumId w:val="4"/></w:num>')
const reparsed = await parseDocx(saved)
expect(reparsed.numbering.get('9')!.levels[0].numFmt).toBe('bullet')
})
})
@@ -0,0 +1,71 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const DIAGRAM_DATA_XML =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<dgm:dataModel xmlns:dgm="http://schemas.openxmlformats.org/drawingml/2006/diagram" ' +
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><dgm:ptLst>' +
['总经理办', '研发部', '产品部', '销售部', '运营部']
.map(
(t, i) =>
`<dgm:pt modelId="{${i}}"><dgm:t><a:bodyPr/><a:p><a:r><a:t>${t}</a:t></a:r></a:p></dgm:t></dgm:pt>`,
)
.join('') +
'</dgm:ptLst></dgm:dataModel>'
const SMARTART_P =
'<w:p><w:r><w:drawing><wp:inline><wp:extent cx="5486400" cy="419100"/>' +
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/diagram">' +
'<dgm:relIds xmlns:dgm="http://schemas.openxmlformats.org/drawingml/2006/diagram" ' +
'r:dm="rId40" r:lo="rId41" r:qs="rId42" r:cs="rId43"/>' +
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>'
const OLE_P =
'<w:p><w:r><w:object><v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="_x0000_i1025" ' +
'style="width:32pt;height:32pt"><v:imagedata r:id="rId10" o:title=""/></v:shape>' +
'<o:OLEObject xmlns:o="urn:schemas-microsoft-com:office:office" Type="Embed" ' +
'ProgID="Excel.Sheet.12" ShapeID="_x0000_i1025" DrawAspect="Icon" ObjectID="_1"/>' +
'</w:object></w:r></w:p>'
async function buildFixture(): Promise<Uint8Array> {
return buildDocx({
bodyXml: SMARTART_P + OLE_P,
withImage: true,
extraRels:
'<Relationship Id="rId40" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramData" Target="diagrams/data1.xml"/>',
extraParts: [
{
path: 'word/diagrams/data1.xml',
xml: DIAGRAM_DATA_XML,
contentType: 'application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml',
},
],
})
}
describe('SmartArt / OLE visible degrade (#220)', () => {
it('SmartArt preview lists the diagram node texts', async () => {
const parsed = await parseDocx(await buildFixture())
const block = parsed.blocks[0]
expect(block.type).toBe('passthrough')
expect(block.label).toBe('SmartArt')
expect(block.previewText).toBe('总经理办\n研发部\n产品部\n销售部\n运营部')
})
it('OLE embed surfaces the packaged preview picture and ProgID', async () => {
const parsed = await parseDocx(await buildFixture())
const block = parsed.blocks[1]
expect(block.type).toBe('passthrough')
expect(block.label).toBe('Embedded object')
expect(block.oleProgId).toBe('Excel.Sheet.12')
expect(block.imageDataUrl).toMatch(/^data:image\/png;base64,/)
})
it('a missing diagram part degrades to the bare label, not an error', async () => {
const parsed = await parseDocx(await buildDocx({ bodyXml: SMARTART_P }))
const block = parsed.blocks[0]
expect(block.label).toBe('SmartArt')
expect(block.previewText ?? '').toBe('')
})
})
@@ -0,0 +1,101 @@
import { describe, expect, it } from 'vitest'
import { decodeSymbolChar, decodeSymbolText, isSymbolFont, parseDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
describe('symbol font decoding helpers', () => {
it('recognizes symbol-encoded fonts case-insensitively', () => {
expect(isSymbolFont('Wingdings')).toBe(true)
expect(isSymbolFont('symbol')).toBe(true)
expect(isSymbolFont('Webdings')).toBe(true)
expect(isSymbolFont('Calibri')).toBe(false)
expect(isSymbolFont(null)).toBe(false)
})
it('maps raw bytes and their U+F0xx private-use forms alike', () => {
expect(decodeSymbolChar('Wingdings', 0x6c)).toBe('●')
expect(decodeSymbolChar('Wingdings', 0xf06c)).toBe('●')
expect(decodeSymbolChar('Symbol', 0xf0b7)).toBe('•')
expect(decodeSymbolChar('Wingdings', 0xf000)).toBeNull()
})
it('decodes whole strings only when every glyph maps', () => {
expect(decodeSymbolText('Symbol', 'abg')).toBe('αβγ')
expect(decodeSymbolText('Wingdings', 'l e')).toBeNull()
expect(decodeSymbolText('Calibri', 'abc')).toBeNull()
})
})
describe('symbol runs in document.xml', () => {
it('converts w:sym to the Unicode equivalent', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:r><w:t>勾:</w:t></w:r><w:r><w:sym w:font="Wingdings" w:char="F0FC"/></w:r>' +
'<w:r><w:sym w:font="Wingdings" w:char="6C"/></w:r></w:p>',
})
const doc = await parseDocx(bytes)
expect(doc.blocks[0].runs!.map((r) => r.text).join('')).toBe('勾:✓●')
})
it('keeps unknown w:sym glyphs as private-use characters', async () => {
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:sym w:font="Wingdings 2" w:char="F045"/></w:r></w:p>',
})
const doc = await parseDocx(bytes)
expect(doc.blocks[0].runs!.map((r) => r.text).join('')).toBe('\uF045')
})
it('decodes text runs carrying a symbol font and drops the font', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol"/></w:rPr><w:t>&#xF0B7;</w:t></w:r>' +
'<w:r><w:t> 后文</w:t></w:r></w:p>',
})
const doc = await parseDocx(bytes)
const run = doc.blocks[0].runs![0]
expect(doc.blocks[0].runs!.map((r) => r.text).join('')).toBe('• 后文')
expect(run.font).toBeUndefined()
expect(run.rawRPr ?? '').not.toContain('w:rFonts')
})
it('leaves undecodable symbol-font runs untouched', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Wingdings" w:hAnsi="Wingdings"/></w:rPr><w:t>le</w:t></w:r></w:p>',
})
const doc = await parseDocx(bytes)
const run = doc.blocks[0].runs![0]
expect(run.text).toBe('le')
expect(run.font).toBe('Wingdings')
})
it('decodes numeric character references in w:t', async () => {
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>&#x2713;&#65;</w:t></w:r></w:p>',
})
const doc = await parseDocx(bytes)
expect(doc.blocks[0].runs!.map((r) => r.text).join('')).toBe('✓A')
})
})
describe('numbering level marker font', () => {
it('parses w:rPr/w:rFonts of a bullet level', async () => {
const numberingXml =
XML_DECL +
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:abstractNum w:abstractNumId="0">' +
'<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="l"/>' +
'<w:rPr><w:rFonts w:ascii="Wingdings" w:hAnsi="Wingdings"/></w:rPr></w:lvl>' +
'</w:abstractNum>' +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
'</w:numbering>'
const bytes = await buildDocx({
bodyXml:
'<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>项</w:t></w:r></w:p>',
numberingXml,
})
const doc = await parseDocx(bytes)
expect(doc.numbering.get('1')!.levels[0].font).toBe('Wingdings')
})
})
@@ -0,0 +1,145 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const STYLED_TABLE_XML =
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="4000"/><w:gridCol w:w="2000"/></w:tblGrid>' +
// header row: shaded cells, bold white text, centered
'<w:tr>' +
'<w:tc><w:tcPr><w:shd w:val="clear" w:fill="1F3864"/></w:tcPr>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/><w:color w:val="FFFFFF"/></w:rPr><w:t>排名</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:tcPr><w:shd w:val="clear" w:fill="1F3864"/></w:tcPr>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/><w:color w:val="FFFFFF"/></w:rPr><w:t>品牌</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:tcPr><w:shd w:val="clear" w:fill="1F3864"/></w:tcPr>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/><w:color w:val="FFFFFF"/></w:rPr><w:t>份额</w:t></w:r></w:p></w:tc>' +
'</w:tr>' +
// data row with colSpan
'<w:tr>' +
'<w:tc><w:p><w:r><w:t>1</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:tcPr><w:gridSpan w:val="2"/></w:tcPr><w:p><w:r><w:t>比亚迪</w:t></w:r></w:p><w:p><w:r><w:t>第二段</w:t></w:r></w:p></w:tc>' +
'</w:tr>' +
// vertical merge pair
'<w:tr>' +
'<w:tc><w:tcPr><w:vMerge w:val="restart"/></w:tcPr><w:p><w:r><w:t>竖排</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:p><w:r><w:t>a</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:p><w:r><w:t>b</w:t></w:r></w:p></w:tc>' +
'</w:tr>' +
'<w:tr>' +
'<w:tc><w:tcPr><w:vMerge/></w:tcPr><w:p/></w:tc>' +
'<w:tc><w:p><w:r><w:t>c</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:p><w:r><w:t>d</w:t></w:r></w:p></w:tc>' +
'</w:tr>' +
'</w:tbl>'
describe('table display model', () => {
it('extracts rows, shading, bold, alignment, spans and column widths', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: STYLED_TABLE_XML }))
const block = doc.blocks[0]
expect(block.type).toBe('table')
const table = block.table!
expect(table.rows).toHaveLength(4)
const header = table.rows[0]
expect(header.map((c) => c.paras[0])).toEqual(['排名', '品牌', '份额'])
expect(header[0]).toMatchObject({ fill: '1F3864', color: 'FFFFFF', bold: true, align: 'center' })
const dataRow = table.rows[1]
expect(dataRow[1].colSpan).toBe(2)
expect(dataRow[1].paras).toEqual(['比亚迪', '第二段'])
expect(dataRow[0].bold).toBeUndefined()
expect(table.rows[2][0].vMerge).toBe('restart')
expect(table.rows[3][0].vMerge).toBe('continue')
expect(table.colWidthsPct).toHaveLength(3)
expect(Math.round(table.colWidthsPct![0])).toBe(25)
expect(Math.round(table.colWidthsPct![1])).toBe(50)
})
it('original table XML is still saved byte-identical (display model is read-only)', async () => {
const bytes = await buildDocx({ bodyXml: STYLED_TABLE_XML })
const doc = await parseDocx(bytes)
expect(doc.blocks[0].originalXml).toContain('<w:tbl>')
})
it('parses table-level borders / alignment / cell margins / nested tables', async () => {
const xml =
'<w:tbl><w:tblPr>' +
'<w:tblW w:w="0" w:type="auto"/><w:jc w:val="center"/><w:tblInd w:w="120" w:type="dxa"/>' +
'<w:tblBorders><w:top w:val="single" w:sz="12" w:space="0" w:color="FF0000"/>' +
'<w:insideH w:val="none"/><w:insideV w:val="single" w:sz="4"/></w:tblBorders>' +
'<w:tblCellMar><w:top w:w="0" w:type="dxa"/><w:left w:w="0" w:type="dxa"/></w:tblCellMar>' +
'</w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="3000"/><w:gridCol w:w="3000"/></w:tblGrid>' +
'<w:tr><w:tc><w:p><w:r><w:t>外层</w:t></w:r></w:p>' +
'<w:tbl><w:tblGrid><w:gridCol w:w="1000"/><w:gridCol w:w="1000"/></w:tblGrid>' +
'<w:tr><w:tc><w:p><w:r><w:t>内A</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>内B</w:t></w:r></w:p></w:tc></w:tr>' +
'</w:tbl><w:p/></w:tc>' +
'<w:tc><w:p><w:r><w:t>右格</w:t></w:r></w:p></w:tc></w:tr>' +
'</w:tbl>'
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
const table = doc.blocks[0].table!
expect(table.align).toBe('center')
// tblInd is still parsed with jc=center (the renderer only applies it for left alignment)
expect(table.indentTwips).toBe(120)
expect(table.borders?.top).toMatchObject({ style: 'single', szEighths: 12, color: 'FF0000' })
expect(table.borders?.insideH).toMatchObject({ style: 'none' })
expect(table.borders?.insideV).toMatchObject({ style: 'single', szEighths: 4 })
expect(table.cellMarTwips).toEqual({ top: 0, left: 0 })
expect(table.colWidthsTwips).toEqual([3000, 3000])
const outerCell = table.rows[0][0]
expect(outerCell.paras[0]).toBe('外层')
const nested = outerCell.nestedTables![0]
expect(nested.rows[0].map((c) => c.paras[0])).toEqual(['内A', '内B'])
expect(nested.colWidthsTwips).toEqual([1000, 1000])
})
it('parses cell textDirection and falls back to tcW when tblGrid is unusable', async () => {
const xml =
'<w:tbl><w:tblGrid><w:gridCol w:w="0"/><w:gridCol w:w="0"/></w:tblGrid>' +
'<w:tr>' +
'<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:textDirection w:val="tbRlV"/></w:tcPr><w:p><w:r><w:t>竖</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:tcPr><w:tcW w:w="6000" w:type="dxa"/><w:textDirection w:val="btLr"/></w:tcPr><w:p><w:r><w:t>横转</w:t></w:r></w:p></w:tc>' +
'</w:tr></w:tbl>'
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
const table = doc.blocks[0].table!
expect(table.colWidthsTwips).toEqual([2000, 6000])
expect(Math.round(table.colWidthsPct![0])).toBe(25)
expect(table.rows[0][0].textDirection).toBe('tbRl')
expect(table.rows[0][1].textDirection).toBe('btLr')
})
it('merges legacy w:hMerge continue cells into the restart cell', async () => {
const xml =
'<w:tbl><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid>' +
'<w:tr>' +
'<w:tc><w:tcPr><w:hMerge w:val="restart"/></w:tcPr><w:p><w:r><w:t>合并头</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:tcPr><w:hMerge/></w:tcPr><w:p/></w:tc>' +
'<w:tc><w:p><w:r><w:t>右</w:t></w:r></w:p></w:tc>' +
'</w:tr></w:tbl>'
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
const row = doc.blocks[0].table!.rows[0]
expect(row).toHaveLength(2)
expect(row[0].colSpan).toBe(2)
expect(row[0].paras[0]).toBe('合并头')
expect(row[1].paras[0]).toBe('右')
})
it('inherits tblBorders / tblCellMar from the referenced table style', async () => {
const styleXml =
'<w:style w:type="table" w:styleId="GridStyled"><w:name w:val="Grid Styled"/>' +
'<w:tblPr><w:tblBorders><w:top w:val="single" w:sz="16" w:color="00FF00"/>' +
'<w:insideH w:val="dashed" w:sz="4"/></w:tblBorders>' +
'<w:tblCellMar><w:left w:w="200" w:type="dxa"/><w:right w:w="200" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style>'
const xml =
'<w:tbl><w:tblPr><w:tblStyle w:val="GridStyled"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="3000"/></w:tblGrid>' +
'<w:tr><w:tc><w:p><w:r><w:t>甲</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
const doc = await parseDocx(await buildDocx({ bodyXml: xml, extraStylesXml: styleXml }))
const table = doc.blocks[0].table!
expect(table.borders?.top).toMatchObject({ style: 'single', szEighths: 16, color: '00FF00' })
expect(table.borders?.insideH).toMatchObject({ style: 'dashed' })
expect(table.cellMarTwips).toEqual({ left: 200, right: 200 })
})
})
@@ -0,0 +1,245 @@
import { describe, expect, it } from 'vitest'
import { generateTableModelXml, parseDocx, patchTableCellTexts } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const TABLE_XML =
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="4000"/><w:gridCol w:w="4000"/></w:tblGrid>' +
'<w:tr>' +
'<w:tc><w:tcPr><w:shd w:val="clear" w:fill="1F3864"/></w:tcPr>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/><w:color w:val="FFFFFF"/></w:rPr><w:t>标题A</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:tcPr><w:shd w:val="clear" w:fill="1F3864"/></w:tcPr>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/><w:color w:val="FFFFFF"/></w:rPr><w:t>标题B</w:t></w:r></w:p></w:tc>' +
'</w:tr>' +
'<w:tr>' +
'<w:tc><w:p><w:r><w:t>甲</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:p><w:r><w:t>乙</w:t></w:r></w:p><w:p><w:r><w:t>第二段</w:t></w:r></w:p></w:tc>' +
'</w:tr>' +
'</w:tbl>'
describe('patchTableCellTexts', () => {
it('replaces a single cell text and keeps the rest byte-identical', () => {
const out = patchTableCellTexts(TABLE_XML, [null, [['已修改'], null]])
expect(out).toContain('<w:t xml:space="preserve">已修改</w:t>')
expect(out).not.toContain('<w:t>甲</w:t>')
// untouched cells keep exact original bytes
expect(out).toContain('<w:t>标题A</w:t>')
expect(out).toContain('<w:t>标题B</w:t>')
expect(out).toContain('<w:t>乙</w:t>')
})
it('preserves tcPr, first-paragraph pPr and first-run rPr of the edited cell', () => {
const out = patchTableCellTexts(TABLE_XML, [[['新标题'], null], null])
const cell = /<w:tc>[\s\S]*?<\/w:tc>/.exec(out)![0]
expect(cell).toContain('<w:shd w:val="clear" w:fill="1F3864"/>')
expect(cell).toContain('<w:jc w:val="center"/>')
expect(cell).toContain('<w:b/>')
expect(cell).toContain('<w:color w:val="FFFFFF"/>')
expect(cell).toContain('<w:t xml:space="preserve">新标题</w:t>')
})
it('writes multiple paragraphs per cell and escapes XML entities', () => {
const out = patchTableCellTexts(TABLE_XML, [null, [null, ['A<B', '&C']]])
expect(out).toContain('<w:t xml:space="preserve">A&lt;B</w:t>')
expect(out).toContain('<w:t xml:space="preserve">&amp;C</w:t>')
})
it('round-trips through the parser with the new text', async () => {
const patched = patchTableCellTexts(TABLE_XML, [null, [['改甲'], ['改乙一', '改乙二']]])
const doc = await parseDocx(await buildDocx({ bodyXml: patched }))
const table = doc.blocks[0].table!
expect(table.rows[1][0].paras).toEqual(['改甲'])
expect(table.rows[1][1].paras).toEqual(['改乙一', '改乙二'])
// header styles survived
expect(table.rows[0][0]).toMatchObject({ fill: '1F3864', bold: true, align: 'center' })
})
it('skips cells containing nested tables', () => {
const nested =
'<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
'<w:tr><w:tc><w:p><w:r><w:t>外层</w:t></w:r></w:p>' +
'<w:tbl><w:tr><w:tc><w:p><w:r><w:t>内层</w:t></w:r></w:p></w:tc></w:tr></w:tbl>' +
'<w:p/></w:tc></w:tr></w:tbl>'
const out = patchTableCellTexts(nested, [[['不应生效']]])
expect(out).toBe(nested)
})
it('handles vertical merges: continue cells stay untouched', () => {
const merged =
'<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
'<w:tr><w:tc><w:tcPr><w:vMerge w:val="restart"/></w:tcPr><w:p><w:r><w:t>合并首</w:t></w:r></w:p></w:tc></w:tr>' +
'<w:tr><w:tc><w:tcPr><w:vMerge/></w:tcPr><w:p/></w:tc></w:tr>' +
'</w:tbl>'
const out = patchTableCellTexts(merged, [[['新合并首']], null])
expect(out).toContain('<w:t xml:space="preserve">新合并首</w:t>')
expect(out).toContain('<w:vMerge w:val="restart"/>')
expect(out).toContain('<w:vMerge/>')
})
})
describe('generateTableModelXml', () => {
it('round-trips structural rows, columns, styling, and merged cells', async () => {
const xml = generateTableModelXml({
colWidthsPct: [25, 35, 40],
rows: [
[
{
paras: ['Merged header'],
colSpan: 2,
vMerge: 'restart',
fill: '1F3864',
color: 'FFFFFF',
bold: true,
align: 'center',
},
{ paras: ['C'] },
],
[{ paras: [''], colSpan: 2, vMerge: 'continue', fill: '1F3864' }, { paras: ['D'] }],
[{ paras: ['A'] }, { paras: ['B'] }, { paras: ['C'] }],
],
})
const parsed = await parseDocx(await buildDocx({ bodyXml: xml }))
const model = parsed.blocks[0].table!
expect(model.rows).toHaveLength(3)
expect(model.rows[0][0]).toMatchObject({
paras: ['Merged header'],
colSpan: 2,
vMerge: 'restart',
fill: '1F3864',
color: 'FFFFFF',
bold: true,
align: 'center',
})
expect(model.rows[1][0]).toMatchObject({ colSpan: 2, vMerge: 'continue' })
expect(model.rows[2].map((cell) => cell.paras[0])).toEqual(['A', 'B', 'C'])
expect(model.colWidthsPct?.map(Math.round)).toEqual([25, 35, 40])
})
it('reuses the imported tblPr while regenerating rows and rich runs', async () => {
const template =
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/>' +
'<w:tblCellMar><w:left w:w="120" w:type="dxa"/></w:tblCellMar></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="8000"/></w:tblGrid>' +
'<w:tr><w:tc><w:p><w:r><w:t>Old</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
const xml = generateTableModelXml(
{
rows: [
[
{
paras: ['Rich'],
richParas: [
{
runs: [
{
text: 'Rich',
bold: true,
color: 'C00000',
font: 'Arial',
sizeHalfPoints: 30,
},
],
},
],
},
{ paras: ['New'] },
],
],
},
template,
)
const parsed = await parseDocx(await buildDocx({ bodyXml: xml }))
const run = parsed.blocks[0].table?.rows[0][0].richParas?.[0].runs[0]
expect(xml).toContain('<w:tblStyle w:val="TableGrid"/>')
expect(xml).toContain('<w:tblCellMar><w:left w:w="120" w:type="dxa"/></w:tblCellMar>')
expect(run).toMatchObject({
text: 'Rich',
bold: true,
color: 'C00000',
font: 'Arial',
sizeHalfPoints: 30,
})
})
})
describe('tcPr/trPr fidelity and new attributes', () => {
it('generateTableModelXml: unmodeled rawTcPr attributes are kept; vAlign/borders are written from the model', async () => {
const { generateTableModelXml } = await import('../src/index')
const model = {
rows: [
[
{
paras: ['a'],
vAlign: 'center' as const,
borders: {
top: { style: 'single', szEighths: 8, color: 'FF0000' },
bottom: { style: 'none' },
},
rawTcPr:
'<w:tcPr><w:tcW w:w="4000" w:type="dxa"/><w:tcMar><w:left w:w="200" w:type="dxa"/></w:tcMar><w:textDirection w:val="btLr"/></w:tcPr>',
},
{ paras: ['b'] },
],
],
rowHeightsTwips: [600],
rawTrPrs: ['<w:trPr><w:cantSplit/></w:trPr>'],
}
const xml = generateTableModelXml(model)
// Unmodeled properties are kept
expect(xml).toContain('<w:tcMar><w:left w:w="200" w:type="dxa"/></w:tcMar>')
expect(xml).toContain('<w:textDirection w:val="btLr"/>')
// vAlign comes after textDirection (schema order); borders sit in the shd position range
expect(xml).toContain('<w:vAlign w:val="center"/>')
expect(xml.indexOf('<w:tcBorders>')).toBeLessThan(xml.indexOf('<w:tcMar>'))
expect(xml).toContain('<w:top w:val="single" w:sz="8" w:space="0" w:color="FF0000"/>')
expect(xml).toContain('<w:bottom w:val="none"/>')
// trPr: cantSplit kept + trHeight injected
expect(xml).toContain(
'<w:trPr><w:cantSplit/><w:trHeight w:val="600" w:hRule="atLeast"/></w:trPr>',
)
})
it('parse read-back: vAlign/tcBorders/trHeight/rawTcPr/rawTrPr', async () => {
const { parseDocx } = await import('../src/index')
const { buildDocx } = await import('./helpers/build-docx')
const tbl =
'<w:tbl><w:tblPr><w:tblW w:w="8000" w:type="dxa"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="4000"/><w:gridCol w:w="4000"/></w:tblGrid>' +
'<w:tr><w:trPr><w:trHeight w:val="500"/><w:cantSplit/></w:trPr>' +
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/><w:vAlign w:val="bottom"/>' +
'<w:tcBorders><w:top w:val="dashed" w:sz="12" w:color="00FF00"/></w:tcBorders>' +
'<w:tcMar><w:left w:w="100" w:type="dxa"/></w:tcMar></w:tcPr>' +
'<w:p><w:r><w:t>x</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>y</w:t></w:r></w:p></w:tc>' +
'</w:tr></w:tbl>'
const parsed = await parseDocx(await buildDocx({ bodyXml: tbl }))
const table = parsed.blocks.find((b) => b.type === 'table')!
const model = table.table!
const cell = model.rows[0][0]
expect(cell.vAlign).toBe('bottom')
expect(cell.borders?.top).toEqual({ style: 'dashed', szEighths: 12, color: '00FF00' })
expect(cell.rawTcPr).toContain('<w:tcMar>')
expect(model.rowHeightsTwips).toEqual([500])
expect(model.rawTrPrs?.[0]).toContain('<w:cantSplit/>')
})
})
describe('tblStyleId table style reference', () => {
it('replaces/inserts/removes w:tblStyle, adding a default tblLook when missing', async () => {
const { generateTableModelXml } = await import('../src/index')
const model = { rows: [[{ paras: ['x'] }]], tblStyleId: 'FancyTable' }
const orig =
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="8000" w:type="dxa"/></w:tblPr><w:tblGrid><w:gridCol w:w="8000"/></w:tblGrid><w:tr><w:tc><w:p/></w:tc></w:tr></w:tbl>'
const xml = generateTableModelXml(model, orig)
expect(xml).toContain('<w:tblPr><w:tblStyle w:val="FancyTable"/><w:tblW')
expect(xml.match(/<w:tblStyle/g)).toHaveLength(1)
expect(xml).toContain('<w:tblLook w:val="04A0"')
// Removal
const removed = generateTableModelXml({ rows: [[{ paras: ['x'] }]], tblStyleId: '' }, orig)
expect(removed).not.toContain('<w:tblStyle')
// undefined leaves it untouched
const kept = generateTableModelXml({ rows: [[{ paras: ['x'] }]] }, orig)
expect(kept).toContain('<w:tblStyle w:val="TableGrid"/>')
})
})
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx } from '../src/index'
import { buildDocx, REVISION_TABLE_XML } from './helpers/build-docx'
describe('table row / cell revisions (trPr w:ins/w:del, tcPr w:cellIns/w:cellDel)', () => {
it('parses row and cell revisions into the table model', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: REVISION_TABLE_XML }))
const model = doc.blocks[0].table!
expect(doc.blocks[0].type).toBe('table')
expect(model.rowRevisions).toEqual([
null,
{ kind: 'del', author: 'Alice', date: '2026-01-01T00:00:00Z', id: '11' },
null,
])
expect(model.rows[2][0].cellRevision).toEqual({
kind: 'ins',
author: 'Alice',
date: '2026-01-01T00:00:00Z',
id: '15',
})
// deleted-row text arrives as del-marked runs, still part of the editable model
expect(model.rows[1][0].richParas?.[0]?.runs?.[0]?.del?.author).toBe('Alice')
})
it('keeps an untouched revision table byte-identical', async () => {
const bytes = await buildDocx({ bodyXml: REVISION_TABLE_XML })
const doc = await parseDocx(bytes)
expect(await saveDocx(doc, [{ kind: 'original', docxIndex: 0 }])).toEqual(bytes)
})
it('parses row insertion (trPr w:ins)', async () => {
const xml = REVISION_TABLE_XML.replace('<w:del w:id="11"', '<w:ins w:id="11"')
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
expect(doc.blocks[0].table!.rowRevisions?.[1]?.kind).toBe('ins')
})
})
@@ -0,0 +1,102 @@
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const GRID_STYLE =
'<w:style w:type="table" w:styleId="GridBlue"><w:name w:val="Grid Table Blue"/>' +
'<w:tblStylePr w:type="firstRow"><w:rPr><w:b/><w:color w:val="FFFFFF"/></w:rPr>' +
'<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="4472C4"/></w:tcPr></w:tblStylePr>' +
'<w:tblStylePr w:type="band1Horz"><w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="D9E2F3"/></w:tcPr></w:tblStylePr>' +
'</w:style>' +
'<w:style w:type="table" w:styleId="GridBlueChild"><w:name w:val="Child"/><w:basedOn w:val="GridBlue"/>' +
'<w:tblStylePr w:type="band1Horz"><w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="EEEEEE"/></w:tcPr></w:tblStylePr>' +
'</w:style>'
const row = (a: string, b: string, shd = '') =>
`<w:tr><w:tc>${shd ? `<w:tcPr>${shd}</w:tcPr>` : ''}<w:p><w:r><w:t>${a}</w:t></w:r></w:p></w:tc>` +
`<w:tc><w:p><w:r><w:t>${b}</w:t></w:r></w:p></w:tc></w:tr>`
function styledTable(look: string, extra = ''): string {
return (
`<w:tbl><w:tblPr><w:tblStyle w:val="GridBlue"/>${look}</w:tblPr>` +
row('表头A', '表头B') +
row('一1', '一2', extra) +
row('二1', '二2') +
row('三1', '三2') +
'</w:tbl>'
)
}
describe('table styles (tblStyle display)', () => {
it('parses table styles with firstRow / banding and applies them per tblLook', async () => {
const bytes = await buildDocx({
bodyXml: styledTable('<w:tblLook w:firstRow="1" w:noHBand="0"/>'),
extraStylesXml: GRID_STYLE,
})
const doc = await parseDocx(bytes)
const info = doc.styles.get('GridBlue')!
expect(info.type).toBe('table')
expect(info.tableDisplay).toMatchObject({
firstRow: { fill: '4472C4', bold: true, color: 'FFFFFF' },
band1Fill: 'D9E2F3',
})
const rows = doc.blocks[0].table!.rows
expect(rows[0][0]).toMatchObject({ fill: '4472C4', bold: true, color: 'FFFFFF' })
// body rows: band1 / none / band1
expect(rows[1][0].fill).toBe('D9E2F3')
expect(rows[2][0].fill).toBeUndefined()
expect(rows[3][0].fill).toBe('D9E2F3')
})
it('honors noHBand and firstRow=0 flags', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: styledTable('<w:tblLook w:firstRow="0" w:noHBand="1"/>'),
extraStylesXml: GRID_STYLE,
}),
)
const rows = doc.blocks[0].table!.rows
expect(rows[0][0].fill).toBeUndefined()
expect(rows[0][0].bold).toBeUndefined()
expect(rows[1][0].fill).toBeUndefined()
})
it('explicit cell shading beats the style', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: styledTable(
'<w:tblLook w:firstRow="1" w:noHBand="0"/>',
'<w:shd w:val="clear" w:color="auto" w:fill="FF0000"/>',
),
extraStylesXml: GRID_STYLE,
}),
)
expect(doc.blocks[0].table!.rows[1][0].fill).toBe('FF0000')
expect(doc.blocks[0].table!.rows[1][1].fill).toBe('D9E2F3')
})
it('resolves basedOn chains between table styles', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
extraStylesXml: GRID_STYLE,
}),
)
const child = doc.styles.get('GridBlueChild')!
expect(child.tableDisplay).toMatchObject({
firstRow: { fill: '4472C4', bold: true },
band1Fill: 'EEEEEE',
})
})
it('style-derived display keeps untouched tables byte-identical', async () => {
const source = await buildDocx({
bodyXml: styledTable('<w:tblLook w:firstRow="1" w:noHBand="0"/>'),
extraStylesXml: GRID_STYLE,
})
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }])
expect(saved).toEqual(source)
})
})
+75
View File
@@ -0,0 +1,75 @@
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx, type TabStop } from '../src/index'
import { buildDocx } from './helpers/build-docx'
// ---- fixture XML fragments ----
/** paragraph with left + center tab stops and dot leader */
const TABS_P =
'<w:p>' +
'<w:pPr><w:tabs>' +
'<w:tab w:val="left" w:pos="720"/>' +
'<w:tab w:val="center" w:pos="2160" w:leader="dot"/>' +
'<w:tab w:val="right" w:pos="4320"/>' +
'<w:tab w:val="decimal" w:pos="5040"/>' +
'</w:tabs></w:pPr>' +
'<w:r><w:t xml:space="preserve">A\tB\tC</w:t></w:r>' +
'</w:p>'
/** paragraph with NO tabs (control) */
const PLAIN_P = '<w:p><w:r><w:t>plain</w:t></w:r></w:p>'
describe('tab stops parsing', () => {
it('parses w:tabs into block.format.tabStops', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: TABS_P }))
const block = doc.blocks[0]
expect(block.format?.tabStops).toBeDefined()
const stops = block.format!.tabStops!
expect(stops).toHaveLength(4)
expect(stops[0]).toMatchObject({ pos: 720, val: 'left' })
expect(stops[1]).toMatchObject({ pos: 2160, val: 'center', leader: 'dot' })
expect(stops[2]).toMatchObject({ pos: 4320, val: 'right' })
expect(stops[3]).toMatchObject({ pos: 5040, val: 'decimal' })
})
it('plain paragraph has no tabStops', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: PLAIN_P }))
expect(doc.blocks[0].format?.tabStops).toBeUndefined()
})
})
describe('tab stops roundtrip', () => {
it('untouched tabs paragraph saves byte-identical', async () => {
const bytes = await buildDocx({ bodyXml: TABS_P })
const doc = await parseDocx(bytes)
const saved = await saveDocx(doc, [{ kind: 'original', docxIndex: 0 }])
const reparsed = await parseDocx(saved)
expect(reparsed.blocks[0].format?.tabStops).toEqual(doc.blocks[0].format?.tabStops)
expect(reparsed.internal.documentXml).toContain('<w:tabs>')
expect(reparsed.internal.documentXml).toContain('w:val="center"')
expect(reparsed.internal.documentXml).toContain('w:leader="dot"')
})
it('writing new tabStops via format regenerates correct pPr', async () => {
const { generateParagraphXml } = await import('../src/generate')
const newStops: TabStop[] = [
{ pos: 1440, val: 'right', leader: 'dot' },
{ pos: 2880, val: 'left' },
]
const block = {
type: 'paragraph' as const,
runs: [{ text: 'test' }],
format: { tabStops: newStops },
}
const xml = generateParagraphXml(block, {
headingStyleIds: new Map(),
allocateHyperlinkRel: () => 'rId1',
})
expect(xml).toContain('<w:tabs>')
expect(xml).toContain('w:val="right"')
expect(xml).toContain('w:pos="1440"')
expect(xml).toContain('w:leader="dot"')
expect(xml).toContain('w:val="left"')
expect(xml).toContain('w:pos="2880"')
})
})
@@ -0,0 +1,144 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx, type SaveBlock } from '../src/index'
import { patchParagraphTexts } from '../src/text-patch'
import { buildDocx } from './helpers/build-docx'
describe('patchParagraphTexts', () => {
const COMMENT =
'<w:comment w:id="1" w:author="甲">' +
'<w:p><w:r><w:t xml:space="preserve">前缀</w:t></w:r>' +
'<w:r><w:rPr><w:b/><w:color w:val="FF0000"/></w:rPr><w:t>红色加粗</w:t></w:r>' +
'<w:r><w:t xml:space="preserve">后缀</w:t></w:r></w:p>' +
'<w:p w14:paraId="AA00"><w:hyperlink r:id="rId9"><w:r><w:rPr><w:u w:val="single"/></w:rPr><w:t>链接</w:t></w:r></w:hyperlink></w:p>' +
'</w:comment>'
it('editing one paragraph keeps the other paragraph and untouched runs byte-identical', () => {
const out = patchParagraphTexts(COMMENT, '前缀红色加粗改后缀\n链接')
expect(out).not.toBeNull()
// Untouched paragraph keeps its original bytes
expect(out).toContain('<w:p w14:paraId="AA00"><w:hyperlink r:id="rId9">')
// The touched run keeps its rPr
expect(out).toContain('<w:rPr><w:b/><w:color w:val="FF0000"/></w:rPr>')
expect(out).toContain('红色加粗改')
})
it('inserting text mid-paragraph preserves the runs on both sides', () => {
const out = patchParagraphTexts(COMMENT, '前缀X红色加粗后缀\n链接')
expect(out).not.toBeNull()
expect(out).toContain('前缀X')
expect(out).toContain('<w:rPr><w:b/><w:color w:val="FF0000"/></w:rPr>')
})
it('cross-run deletion empties the middle run but keeps its formatting shell', () => {
const out = patchParagraphTexts(COMMENT, '前后缀\n链接')
expect(out).not.toBeNull()
const decoded = out!
expect(decoded).toContain('<w:t xml:space="preserve">前</w:t>')
// Full re-extracted text matches (guaranteed by the self-check); the red run's
// content is emptied but its structure remains
expect(decoded).toContain('<w:rPr><w:b/><w:color w:val="FF0000"/></w:rPr>')
})
it('escapes XML special characters in text correctly', () => {
const out = patchParagraphTexts(COMMENT, '前缀<A&B>后缀\n链接')
expect(out).not.toBeNull()
expect(out).toContain('&lt;A&amp;B&gt;')
})
it('returns null when the paragraph count changes (caller falls back to a rebuild)', () => {
expect(patchParagraphTexts(COMMENT, '只剩一段')).toBeNull()
expect(patchParagraphTexts(COMMENT, '一\n二\n三')).toBeNull()
})
it('treats the footnote first-paragraph self-reference space as an immutable prefix', () => {
const NOTE =
'<w:footnote w:id="2">' +
'<w:p><w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><w:footnoteRef/></w:r>' +
'<w:r><w:t xml:space="preserve"> </w:t></w:r>' +
'<w:r><w:rPr><w:i/></w:rPr><w:t>斜体脚注</w:t></w:r></w:p>' +
'</w:footnote>'
const out = patchParagraphTexts(NOTE, '斜体脚注改', { stripFirstParaLeadingSpace: true })
expect(out).not.toBeNull()
expect(out).toContain('<w:footnoteRef/>')
expect(out).toContain('<w:t xml:space="preserve"> </w:t>')
expect(out).toContain('<w:rPr><w:i/></w:rPr>')
expect(out).toContain('斜体脚注改')
})
})
describe('rich-text comment/footnote edits use the surgical patch', () => {
const originalOrder = (doc: Awaited<ReturnType<typeof parseDocx>>): SaveBlock[] =>
doc.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
it('editing comment text keeps the bold run and hyperlink structure inside the comment', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:commentRangeStart w:id="1"/><w:r><w:t>正文</w:t></w:r>' +
'<w:commentRangeEnd w:id="1"/><w:r><w:commentReference w:id="1"/></w:r></w:p>',
extraRels:
'<Relationship Id="rId31" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>',
extraParts: [
{
path: 'word/comments.xml',
xml:
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml">' +
'<w:comment w:id="1" w:author="甲"><w:p w14:paraId="11112222">' +
'<w:r><w:rPr><w:b/></w:rPr><w:t>加粗</w:t></w:r>' +
'<w:r><w:t xml:space="preserve">批注</w:t></w:r>' +
'</w:p></w:comment></w:comments>',
contentType:
'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml',
},
],
})
const doc = await parseDocx(bytes)
expect(doc.comments[0].text).toBe('加粗批注')
const edited = [{ ...doc.comments[0], text: '加粗的批注' }]
const out = await saveDocx(doc, originalOrder(doc), { comments: edited })
const xml = await (await JSZip.loadAsync(out)).file('word/comments.xml')!.async('string')
expect(xml).toContain('<w:rPr><w:b/></w:rPr>')
expect(xml).toContain('w14:paraId="11112222"')
const reparsed = await parseDocx(out)
expect(reparsed.comments[0].text).toBe('加粗的批注')
})
it('editing footnote text keeps the italic formatting inside the footnote', async () => {
const bytes = await buildDocx({
bodyXml:
'<w:p><w:r><w:t>正文</w:t></w:r>' +
'<w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><w:footnoteReference w:id="2"/></w:r></w:p>',
extraRels:
'<Relationship Id="rId32" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" Target="footnotes.xml"/>',
extraParts: [
{
path: 'word/footnotes.xml',
xml:
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:footnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:footnote>' +
'<w:footnote w:id="2"><w:p>' +
'<w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><w:footnoteRef/></w:r>' +
'<w:r><w:t xml:space="preserve"> </w:t></w:r>' +
'<w:r><w:rPr><w:i/></w:rPr><w:t>斜体脚注</w:t></w:r>' +
'</w:p></w:footnote></w:footnotes>',
contentType:
'application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml',
},
],
})
const doc = await parseDocx(bytes)
expect(doc.footnotes[0].text).toBe('斜体脚注')
const edited = [{ ...doc.footnotes[0], text: '斜体脚注(改)' }]
const out = await saveDocx(doc, originalOrder(doc), { footnotes: edited })
const xml = await (await JSZip.loadAsync(out)).file('word/footnotes.xml')!.async('string')
expect(xml).toContain('<w:rPr><w:i/></w:rPr>')
expect(xml).toContain('<w:footnoteRef/>')
const reparsed = await parseDocx(out)
expect(reparsed.footnotes[0].text).toBe('斜体脚注(改)')
expect(reparsed.footnotes[0].richParas?.[0]?.some((r) => r.italic)).toBe(true)
})
})
@@ -0,0 +1,218 @@
import { describe, expect, it } from 'vitest'
import { patchTextboxHeights, patchTextboxParas, type TextboxParaPatch } from '../src/generate'
import { parseDocx } from '../src/parse'
import { buildDocx } from './helpers/build-docx'
const TXBX_CONTENT =
'<w:txbxContent>' +
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Courier New"/><w:color w:val="415461"/><w:sz w:val="22"/></w:rPr>' +
'<w:t>**Current date:** {Month}</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>CRITICAL</w:t></w:r></w:p>' +
'</w:txbxContent>'
/** anchored DrawingML code box with the VML fallback twin Word always writes */
const TEXTBOX_PARAGRAPH =
'<w:p><w:r><mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">' +
'<mc:Choice Requires="wps"><w:drawing>' +
'<wp:anchor behindDoc="1" simplePos="0" locked="0" layoutInCell="1" allowOverlap="1">' +
'<wp:simplePos x="0" y="0"/><wp:extent cx="6038850" cy="1704975"/>' +
'<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
'<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
'<wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="6038850" cy="1704975"/></a:xfrm>' +
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>' +
'<a:solidFill><a:srgbClr val="F5F5F5"/></a:solidFill>' +
'<a:ln w="9524"><a:solidFill><a:srgbClr val="CCCCCC"/></a:solidFill></a:ln></wps:spPr>' +
`<wps:txbx>${TXBX_CONTENT}</wps:txbx></wps:wsp>` +
'</a:graphicData></a:graphic></wp:anchor></w:drawing></mc:Choice>' +
'<mc:Fallback><w:pict>' +
'<v:rect xmlns:v="urn:schemas-microsoft-com:vml" id="box1" style="position:absolute">' +
`<v:textbox>${TXBX_CONTENT}</v:textbox></v:rect>` +
'</w:pict></mc:Fallback></mc:AlternateContent></w:r></w:p>'
const para = (patch: TextboxParaPatch): TextboxParaPatch => patch
describe('textbox editing', () => {
it('extracts the box size from the shape extent', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: TEXTBOX_PARAGRAPH }))
const box = doc.blocks[0].textboxes?.[0]
expect(box?.widthPx).toBe(634) // 6038850 EMU / 9525
// no spAutoFit -> fixed height, Word clips overflow
expect(box?.heightPx).toBe(179) // 1704975 EMU / 9525
})
it('skips the fixed height when the shape auto-fits its text', async () => {
const autoFitXml = TEXTBOX_PARAGRAPH.replace(
'<wps:txbx>',
'<wps:bodyPr><a:spAutoFit/></wps:bodyPr><wps:txbx>',
)
const doc = await parseDocx(await buildDocx({ bodyXml: autoFitXml }))
const box = doc.blocks[0].textboxes?.[0]
expect(box?.widthPx).toBe(634)
expect(box?.heightPx).toBeUndefined()
})
it('extracts text insets and paragraph geometry used by Word', async () => {
const formatted = TEXTBOX_PARAGRAPH
.replace(
'<wps:txbx>',
'<wps:bodyPr lIns="0" tIns="47625" rIns="95250" bIns="0"/><wps:txbx>',
)
.replace(
'<w:p><w:r><w:rPr><w:rFonts',
'<w:p><w:pPr><w:spacing w:line="312" w:lineRule="auto" w:before="211" w:after="40"/>' +
'<w:ind w:left="180" w:right="90" w:firstLine="60"/></w:pPr><w:r><w:rPr><w:rFonts',
)
const doc = await parseDocx(await buildDocx({ bodyXml: formatted }))
const box = doc.blocks[0].textboxes?.[0]
expect(box).toMatchObject({
insetLeftPx: 0,
insetTopPx: 5,
insetRightPx: 10,
insetBottomPx: 0,
})
expect(box?.paras[0]).toMatchObject({
lineSpacing: 1.3,
spaceBefore: 211,
spaceAfter: 40,
indentLeft: 180,
indentRight: 90,
indentFirstLine: 60,
})
})
it('updates DrawingML and VML fallback heights without changing box styling', () => {
const withFallbackHeight = TEXTBOX_PARAGRAPH.replace(
'style="position:absolute"',
'style="position:absolute;width:475.5pt;height:134.25pt"',
)
const out = patchTextboxHeights(withFallbackHeight, [240])
expect(out).toContain('<wp:extent cx="6038850" cy="2286000"/>')
expect(out).toContain('<a:ext cx="6038850" cy="2286000"/>')
expect(out).toContain('width:475.5pt;height:180pt')
expect(out).toContain('<a:srgbClr val="F5F5F5"/>')
})
it('regenerates changed paragraphs from rich runs and keeps unchanged bytes', () => {
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[
para({
runs: [
{ text: '**Current date:** July 21', font: 'Courier New', color: '415461', sizeHalfPoints: 22 },
],
}),
null, // untouched
],
])
expect(out).toContain('<w:t xml:space="preserve">**Current date:** July 21</w:t>')
expect(out).not.toContain('{Month}')
// rich run styles regenerated from the Run model
expect(out).toContain('w:ascii="Courier New"')
expect(out).toContain('<w:color w:val="415461"/>')
expect(out).toContain('<w:sz w:val="22"/>')
// untouched paragraph keeps its original bytes
expect(out).toContain(
'<w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>CRITICAL</w:t></w:r>',
)
// box shape untouched
expect(out).toContain('<a:srgbClr val="F5F5F5"/>')
expect(out).toContain('<a:srgbClr val="CCCCCC"/>')
})
it('applies new run formatting (color, bold) to edited paragraphs', () => {
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[
para({
runs: [
{ text: 'red part', color: 'FF0000' },
{ text: ' bold part', bold: true, sizeHalfPoints: 28 },
],
}),
null,
],
])
expect(out).toContain(
'<w:r><w:rPr><w:color w:val="FF0000"/></w:rPr><w:t xml:space="preserve">red part</w:t></w:r>',
)
expect(out).toContain(
'<w:r><w:rPr><w:b/><w:sz w:val="28"/><w:szCs w:val="28"/></w:rPr><w:t xml:space="preserve"> bold part</w:t></w:r>',
)
})
it('rewrites, keeps, or removes w:jc according to align', () => {
const centered = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[para({ runs: [{ text: 'Hi' }], align: 'center' }), null],
])
expect(centered).toContain('<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t xml:space="preserve">Hi</w:t></w:r></w:p>')
// align undefined keeps the template pPr (second para is centered)
const kept = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[null, para({ runs: [{ text: 'STILL', bold: true }] })],
])
expect(kept).toContain('<w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t xml:space="preserve">STILL</w:t></w:r>')
// align null strips the centered jc from the second paragraph
const removed = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[null, para({ runs: [{ text: 'LEFT', bold: true }], align: null })],
])
expect(removed).toContain('<w:p><w:r><w:rPr><w:b/></w:rPr><w:t xml:space="preserve">LEFT</w:t></w:r></w:p>')
})
it('patches the VML fallback twin with the same paragraphs', () => {
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, [[para({ runs: [{ text: 'NEW' }] }), null]])
const hits = out.match(/<w:t xml:space="preserve">NEW<\/w:t>/g) ?? []
expect(hits).toHaveLength(2) // mc:Choice + mc:Fallback
expect(out).not.toContain('{Month}')
})
it('added paragraphs inherit the last original pPr; removed ones drop', () => {
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[null, null, para({ runs: [{ text: 'line3', bold: true }] }), para({ runs: [] })],
])
// new paragraph reuses the centered pPr of the last original
expect(out).toContain(
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t xml:space="preserve">line3</w:t></w:r></w:p>',
)
// empty paragraph keeps pPr only
expect(out).toContain('<w:p><w:pPr><w:jc w:val="center"/></w:pPr></w:p>')
const fewer = patchTextboxParas(TEXTBOX_PARAGRAPH, [[para({ runs: [{ text: 'only line' }] })]])
expect(fewer).not.toContain('CRITICAL')
})
it('escapes special characters and converts tabs/newlines to OOXML elements', () => {
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[para({ runs: [{ text: 'a < b & c\tD\nE' }] }), null],
])
expect(out).toContain(
'<w:t xml:space="preserve">a &lt; b &amp; c</w:t><w:tab/><w:t xml:space="preserve">D</w:t><w:br/><w:t xml:space="preserve">E</w:t>',
)
})
it('round-trips: patched XML re-parses with the new rich formatting', async () => {
const patched = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[
para({ runs: [{ text: '**Current date:** July 21', font: 'Courier New', color: 'FF0000' }] }),
para({ runs: [{ text: 'IMPORTANT', bold: true, color: '0070C0' }], align: 'center' }),
],
])
const doc = await parseDocx(await buildDocx({ bodyXml: patched }))
const box = doc.blocks[0].textboxes?.[0]
expect(box?.fill).toBe('F5F5F5')
expect(box?.borderColor).toBe('CCCCCC')
expect(box?.paras.map((p) => p.runs.map((r) => r.text).join(''))).toEqual([
'**Current date:** July 21',
'IMPORTANT',
])
expect(box?.paras[0].runs[0]).toMatchObject({ font: 'Courier New', color: 'FF0000' })
expect(box?.paras[1].runs[0]).toMatchObject({ bold: true, color: '0070C0' })
expect(box?.paras[1].align).toBe('center')
})
it('leaves the paragraph untouched when every box is null', () => {
expect(patchTextboxParas(TEXTBOX_PARAGRAPH, [null])).toBe(TEXTBOX_PARAGRAPH)
expect(patchTextboxParas('<w:p><w:r><w:t>plain</w:t></w:r></w:p>', [])).toBe(
'<w:p><w:r><w:t>plain</w:t></w:r></w:p>',
)
})
})
@@ -0,0 +1,444 @@
/**
* verify16-p1p2.test.ts
* P1+P2 end-to-end verification (pure engine layer, no Electron)
* Covers: chart workbook / character styles / image posOffset / tab stops / drop caps /
* SDT / full revision semantics
* Run: cd packages/docx-engine && npx vitest run tests/verify16-p1p2.test.ts
*/
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import {
buildChartWorkbookXlsxBase64,
patchChartWorkbookXlsxBase64,
parseDocx,
saveDocx,
stripPPrChange,
} from '../src/index'
import type { GeneratedBlock } from '../src/types'
import { buildDocx } from './helpers/build-docx'
// ═══════════════════════════════════════════════════════════════════════════
// T1 – chart embedded workbook (embeddings/*.xlsx + sheetData consistent)
// ═══════════════════════════════════════════════════════════════════════════
const CHART_CATEGORIES = ['A', 'B', 'C']
const CHART_SERIES = [{ name: 'S1', values: [10, 20, 30] as (number | null)[] }]
const CHART_SPEC = {
kind: 'bar' as const,
title: '验证图表',
categories: CHART_CATEGORIES,
series: CHART_SERIES,
}
describe('T1: chart embedded workbook', () => {
it('buildChartWorkbookXlsxBase64 produces a valid xlsx whose sheetData contains the chart data', async () => {
// buildChartWorkbookXlsxBase64 takes (categories, series) separately
const b64 = await buildChartWorkbookXlsxBase64(CHART_CATEGORIES, CHART_SERIES)
expect(b64.length).toBeGreaterThan(100)
const buf = Buffer.from(b64, 'base64')
const zip = await JSZip.loadAsync(buf)
// xl/workbook.xml exists
expect(zip.file('xl/workbook.xml')).toBeTruthy()
// xl/worksheets/sheet1.xml contains sheetData
const sheet = await zip.file('xl/worksheets/sheet1.xml')!.async('string')
expect(sheet).toContain('<sheetData')
// contains categories and values (via sharedStrings)
const ss = zip.file('xl/sharedStrings.xml')
if (ss) {
const ssXml = await ss.async('string')
expect(ssXml).toContain('>A<')
}
// numeric values appear inline in sheet
expect(sheet).toContain('>10<')
expect(sheet).toContain('>20<')
})
it('saveDocx kind:chart creates the chart part + ContentType + rels', async () => {
const source = await buildDocx({ bodyXml: '<w:p><w:r><w:t>前</w:t></w:r></w:p>' })
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [
{ kind: 'original', docxIndex: 0 },
{ kind: 'chart', chart: CHART_SPEC },
])
const zip = await JSZip.loadAsync(saved)
// chart part exists
expect(zip.file('word/charts/chart1.xml')).toBeTruthy()
const chartXml = await zip.file('word/charts/chart1.xml')!.async('string')
expect(chartXml).toContain('验证图表')
// ContentTypes includes the chart
const ct = await zip.file('[Content_Types].xml')!.async('string')
expect(ct).toContain('/word/charts/chart1.xml')
// document rels include the chart
const docRels = await zip.file('word/_rels/document.xml.rels')!.async('string')
expect(docRels).toContain('charts/chart1.xml')
})
it('saveDocx kind:chart generates the embeddings xlsx + c:externalData', async () => {
const source = await buildDocx({ bodyXml: '<w:p><w:r><w:t>前</w:t></w:r></w:p>' })
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [
{ kind: 'original', docxIndex: 0 },
{ kind: 'chart', chart: CHART_SPEC },
])
const zip = await JSZip.loadAsync(saved)
const chartXml = await zip.file('word/charts/chart1.xml')!.async('string')
// c:externalData is written (workbook rel)
expect(chartXml).toContain('externalData')
// workbook xlsx exists in the zip (path: word/charts/embeddings/workbook1.xlsx)
const wb = zip.file(/word\/charts\/embeddings\/.*\.xlsx/)
expect(wb.length).toBeGreaterThan(0)
// chart rels include the workbook
const chartRels = await zip.file('word/charts/_rels/chart1.xml.rels')!.async('string')
expect(chartRels).toContain('embeddings/')
// the workbook xlsx contains sheetData
const wbBytes = await wb[0].async('uint8array')
const wbZip = await JSZip.loadAsync(wbBytes)
const sheet = await wbZip.file('xl/worksheets/sheet1.xml')!.async('string')
expect(sheet).toContain('<sheetData')
expect(sheet).toContain('>10<')
})
it('patchChartWorkbookXlsxBase64 updates the values', async () => {
const b64 = await buildChartWorkbookXlsxBase64(CHART_CATEGORIES, CHART_SERIES)
const newSeries = [{ name: 'S1', values: [99, 88, 77] as (number | null)[] }]
const patched = await patchChartWorkbookXlsxBase64(b64, CHART_CATEGORIES, newSeries)
expect(patched).not.toBeNull()
const zip = await JSZip.loadAsync(Buffer.from(patched!, 'base64'))
const sheet = await zip.file('xl/worksheets/sheet1.xml')!.async('string')
expect(sheet).toContain('>99<')
expect(sheet).toContain('>88<')
expect(sheet).not.toContain('>10<') // old value gone
})
})
// ═══════════════════════════════════════════════════════════════════════════
// T2 – character style rStyle preservation
// ═══════════════════════════════════════════════════════════════════════════
const CHAR_STYLE_P =
'<w:p>' +
'<w:r>' +
'<w:rPr><w:rStyle w:val="Emphasis"/></w:rPr>' +
'<w:t>emphasized text</w:t>' +
'</w:r>' +
'</w:p>'
describe('T2: character style rStyle preservation', () => {
it('parsing yields runs[0] with styleId=Emphasis', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: CHAR_STYLE_P,
extraStylesXml:
'<w:style w:type="character" w:styleId="Emphasis">' +
'<w:name w:val="Emphasis"/>' +
'<w:rPr><w:i/></w:rPr>' +
'</w:style>',
}),
)
const run = doc.blocks[0].runs?.[0]
expect(run?.styleId).toBe('Emphasis')
})
it('rStyle survives saveDocx and reparse', async () => {
const source = await buildDocx({
bodyXml: CHAR_STYLE_P,
extraStylesXml:
'<w:style w:type="character" w:styleId="Emphasis">' +
'<w:name w:val="Emphasis"/>' +
'<w:rPr><w:i/></w:rPr>' +
'</w:style>',
})
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }])
const zip = await JSZip.loadAsync(saved)
const docXml = await zip.file('word/document.xml')!.async('string')
expect(docXml).toContain('w:val="Emphasis"')
})
it('character-type styles from the style sheet are parsed into the styles Map', async () => {
const source = await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
extraStylesXml:
'<w:style w:type="character" w:styleId="StrongEmph">' +
'<w:name w:val="Strong Emphasis"/>' +
'<w:rPr><w:b/><w:i/></w:rPr>' +
'</w:style>',
})
const parsed = await parseDocx(source)
expect(parsed.styles).toBeDefined()
const style = parsed.styles?.get('StrongEmph')
expect(style?.type).toBe('character')
expect(style?.display?.bold).toBe(true)
})
})
// ═══════════════════════════════════════════════════════════════════════════
// T3 – image posOffset write
// ═══════════════════════════════════════════════════════════════════════════
/** Floating image XML with posOffset */
const FLOAT_IMG_P =
'<w:p><w:r><w:rPr/><w:drawing>' +
'<wp:anchor distT="0" distB="0" distL="114300" distR="114300" ' +
'simplePos="0" relativeHeight="251658240" behindDoc="0" ' +
'locked="0" layoutInCell="1" allowOverlap="1">' +
'<wp:simplePos x="0" y="0"/>' +
'<wp:positionH relativeFrom="column"><wp:posOffset>457200</wp:posOffset></wp:positionH>' +
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>914400</wp:posOffset></wp:positionV>' +
'<wp:extent cx="1905000" cy="1905000"/>' +
'<wp:effectExtent l="0" t="0" r="0" b="0"/>' +
'<wp:wrapSquare wrapText="bothSides"/>' +
'<wp:docPr id="1" name="Image1"/>' +
'<wp:cNvGraphicFramePr/>' +
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">' +
'<a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
'<pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
'<pic:nvPicPr><pic:cNvPr id="1" name="Image1"/><pic:cNvPicPr/></pic:nvPicPr>' +
'<pic:blipFill>' +
'<a:blip r:embed="rId10"/>' +
'<a:stretch><a:fillRect/></a:stretch>' +
'</pic:blipFill>' +
'<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1905000" cy="1905000"/></a:xfrm>' +
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr>' +
'</pic:pic>' +
'</a:graphicData>' +
'</a:graphic>' +
'</wp:anchor>' +
'</w:drawing></w:r></w:p>'
describe('T3: image posOffset read/write', () => {
it('parsing a floating image reads imageOffsetXEmu / imageOffsetYEmu', async () => {
const doc = await parseDocx(
// withImage:true adds rId10 rel + word/media/image1.png so extractImage succeeds
await buildDocx({ bodyXml: FLOAT_IMG_P, withImage: true }),
)
const block = doc.blocks.find((b) => b.imageOffsetXEmu !== undefined)
expect(block).toBeDefined()
expect(block!.imageOffsetXEmu).toBe(457200)
expect(block!.imageOffsetYEmu).toBe(914400)
})
it('wp:posOffset values are preserved after saveDocx', async () => {
const source = await buildDocx({ bodyXml: FLOAT_IMG_P, withImage: true })
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }])
const zip = await JSZip.loadAsync(saved)
const xml = await zip.file('word/document.xml')!.async('string')
expect(xml).toContain('<wp:posOffset>457200</wp:posOffset>')
expect(xml).toContain('<wp:posOffset>914400</wp:posOffset>')
})
})
// ═══════════════════════════════════════════════════════════════════════════
// T4 – tab stops w:tabs save
// ═══════════════════════════════════════════════════════════════════════════
const TABS_P =
'<w:p>' +
'<w:pPr>' +
'<w:tabs>' +
'<w:tab w:val="left" w:pos="1440"/>' +
'<w:tab w:val="center" w:pos="2880"/>' +
'</w:tabs>' +
'</w:pPr>' +
'<w:r><w:t>a\tb\tc</w:t></w:r>' +
'</w:p>'
describe('T4: tab stops w:tabs', () => {
it('parses the tabStops array', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: TABS_P }))
const block = doc.blocks[0]
expect(block.format?.tabStops).toBeDefined()
expect(block.format!.tabStops!.length).toBe(2)
expect(block.format!.tabStops![0]).toEqual({ pos: 1440, val: 'left' })
expect(block.format!.tabStops![1]).toEqual({ pos: 2880, val: 'center' })
})
it('w:tabs is written back correctly after saveDocx', async () => {
const source = await buildDocx({ bodyXml: TABS_P })
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }])
const zip = await JSZip.loadAsync(saved)
const xml = await zip.file('word/document.xml')!.async('string')
expect(xml).toContain('<w:tabs>')
expect(xml).toContain('w:val="left"')
expect(xml).toContain('w:pos="1440"')
expect(xml).toContain('w:val="center"')
expect(xml).toContain('w:pos="2880"')
})
})
// ═══════════════════════════════════════════════════════════════════════════
// T5 – drop cap w:framePr dropCap
// ═══════════════════════════════════════════════════════════════════════════
const DROPCAP_P =
'<w:p>' +
'<w:pPr>' +
'<w:framePr w:dropCap="drop" w:lines="3" w:wrap="around" w:vAnchor="text" w:hAnchor="text"/>' +
'</w:pPr>' +
'<w:r><w:t>T</w:t></w:r>' +
'</w:p>'
describe('T5: drop cap w:framePr dropCap', () => {
it('parses dropCap attributes', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: DROPCAP_P }))
const block = doc.blocks[0]
expect(block.format?.dropCap).toBeDefined()
expect(block.format!.dropCap!.type).toBe('drop')
expect(block.format!.dropCap!.lines).toBe(3)
})
it('w:framePr dropCap is written back after saveDocx', async () => {
const source = await buildDocx({ bodyXml: DROPCAP_P })
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }])
const zip = await JSZip.loadAsync(saved)
const xml = await zip.file('word/document.xml')!.async('string')
expect(xml).toContain('w:dropCap="drop"')
expect(xml).toContain('w:lines="3"')
})
it('margin dropCap parses as type=margin', async () => {
const p =
'<w:p><w:pPr>' +
'<w:framePr w:dropCap="margin" w:lines="2" w:wrap="around" w:vAnchor="text" w:hAnchor="text"/>' +
'</w:pPr><w:r><w:t>M</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: p }))
expect(doc.blocks[0].format?.dropCap?.type).toBe('margin')
})
})
// ═══════════════════════════════════════════════════════════════════════════
// T6 – SDT content-control shell preservation
// ═══════════════════════════════════════════════════════════════════════════
const SDT_P =
'<w:sdt>' +
'<w:sdtPr>' +
'<w:alias w:val="AuthorField"/>' +
'<w:tag w:val="author_tag"/>' +
'<w:text/>' +
'</w:sdtPr>' +
'<w:sdtEndPr/>' +
'<w:sdtContent>' +
'<w:p><w:r><w:t>Initial Value</w:t></w:r></w:p>' +
'</w:sdtContent>' +
'</w:sdt>'
describe('T6: SDT content controls', () => {
it('parses the sdt block and exposes sdtShell', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: SDT_P }))
const block = doc.blocks[0]
expect(block.sdtShell).toBeDefined()
expect(block.sdtShell!.alias).toBe('AuthorField')
expect(block.sdtShell!.tag).toBe('author_tag')
expect(block.sdtShell!.controlType).toBe('text')
expect(block.runs?.[0].text).toBe('Initial Value')
})
it('passthrough: the w:sdt shell is kept when saveDocx does not touch the sdt content', async () => {
const source = await buildDocx({ bodyXml: SDT_P })
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }])
const zip = await JSZip.loadAsync(saved)
const xml = await zip.file('word/document.xml')!.async('string')
expect(xml).toContain('<w:sdt>')
expect(xml).toContain('w:val="AuthorField"')
expect(xml).toContain('Initial Value')
})
it('save after editing: sdt shell kept, sdtContent updated', async () => {
const source = await buildDocx({ bodyXml: SDT_P })
const parsed = await parseDocx(source)
const block = parsed.blocks[0]
expect(block.sdtShell).toBeDefined()
// Build a generated SaveBlock that edits the text but preserves the sdtShell
const genBlock: GeneratedBlock = {
type: 'paragraph',
runs: [{ text: 'Updated Value' }],
sdtShell: block.sdtShell,
}
const saved = await saveDocx(parsed, [{ kind: 'generated', block: genBlock }])
const zip = await JSZip.loadAsync(saved)
const xml = await zip.file('word/document.xml')!.async('string')
// SDT shell preserved
expect(xml).toContain('<w:sdt>')
expect(xml).toContain('w:val="AuthorField"')
// content updated
expect(xml).toContain('Updated Value')
expect(xml).not.toContain('Initial Value')
})
})
// ═══════════════════════════════════════════════════════════════════════════
// T7 – full revision semantics (pPrChange / move revisions)
// ═══════════════════════════════════════════════════════════════════════════
const PPRCHANGE_P =
'<w:p><w:pPr>' +
'<w:jc w:val="center"/>' +
'<w:pPrChange w:id="51" w:author="Alice" w:date="2026-07-01T10:00:00Z">' +
'<w:pPr><w:jc w:val="left"/></w:pPr>' +
'</w:pPrChange>' +
'</w:pPr>' +
'<w:r><w:t>段落修订文字</w:t></w:r>' +
'</w:p>'
const MOVEFROM_P =
'<w:p><w:moveFrom w:id="41" w:author="Alice" w:name="move1">' +
'<w:r><w:delText>moved away text</w:delText></w:r>' +
'</w:moveFrom></w:p>'
const MOVETO_P =
'<w:p><w:moveTo w:id="42" w:author="Bob" w:name="move2">' +
'<w:r><w:t>moved here text</w:t></w:r>' +
'</w:moveTo></w:p>'
describe('T7: full tracked-revision semantics', () => {
it('pPrChange: parses pPrChangeInfo.author and keeps rawPPr', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: PPRCHANGE_P }))
const block = doc.blocks[0]
expect(block.pPrChangeInfo).toBeDefined()
expect(block.pPrChangeInfo!.author).toBe('Alice')
expect(block.pPrChangeInfo!.id).toBe('51')
expect(block.rawPPr).toContain('<w:pPrChange')
})
it('pPrChange: still present after saveDocx passthrough', async () => {
const source = await buildDocx({ bodyXml: PPRCHANGE_P })
const parsed = await parseDocx(source)
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }])
const zip = await JSZip.loadAsync(saved)
const xml = await zip.file('word/document.xml')!.async('string')
expect(xml).toContain('<w:pPrChange')
expect(xml).toContain('w:author="Alice"')
})
it('stripPPrChange removes the pPrChange tag', () => {
const rawPPr =
'<w:pPr><w:jc w:val="center"/><w:pPrChange w:id="51" w:author="Alice"><w:pPr><w:jc w:val="left"/></w:pPr></w:pPrChange></w:pPr>'
const stripped = stripPPrChange(rawPPr)
expect(stripped).not.toContain('<w:pPrChange')
expect(stripped).toContain('<w:jc w:val="center"')
})
it('moveFrom: parses as del marks + moveRevision=from', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: MOVEFROM_P }))
const block = doc.blocks[0]
expect(block.moveRevision).toBe('from')
const delRun = block.runs?.find((r) => r.del)
expect(delRun).toBeDefined()
expect(delRun?.text).toContain('moved away text')
})
it('moveTo: parses as ins marks + moveRevision=to', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: MOVETO_P }))
const block = doc.blocks[0]
expect(block.moveRevision).toBe('to')
const insRun = block.runs?.find((r) => r.ins)
expect(insRun).toBeDefined()
expect(insRun?.text).toContain('moved here text')
})
})
@@ -0,0 +1,167 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/parse'
import { buildDocx } from './helpers/build-docx'
/**
* Legacy VML textboxes and content-control (w:sdt) wrappers, as produced by
* broker research-report templates: every field lives in an sdt,
* sidebars are v:shape textboxes full of tables, and whole tables are wrapped
* in content controls. Display must look through all of it.
*/
const V_NS = 'xmlns:v="urn:schemas-microsoft-com:vml"'
function vmlTextboxParagraph(txbxContent: string, shapeAttrs = ''): string {
return (
'<w:p><w:r><w:pict>' +
`<v:shape ${V_NS} id="s1" type="#_x0000_t202" ` +
`style="position:absolute;margin-left:380.75pt;margin-top:103.2pt;width:207pt;height:54pt" ${shapeAttrs}>` +
`<v:textbox><w:txbxContent>${txbxContent}</w:txbxContent></v:textbox>` +
'</v:shape></w:pict></w:r></w:p>'
)
}
describe('VML textbox display extraction', () => {
it('extracts a v:shape textbox as a Text box block with pt→px geometry', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: vmlTextboxParagraph('<w:p><w:r><w:t>Sidebar title</w:t></w:r></w:p>'),
}),
)
const block = doc.blocks[0]
expect(block.type).toBe('passthrough')
expect(block.label).toBe('Text box')
const box = block.textboxes?.[0]
expect(box?.widthPx).toBe(276) // 207pt
expect(box?.heightPx).toBe(72) // 54pt
expect(box?.minHeightPx).toBe(72)
expect(box?.paras[0].runs[0].text).toBe('Sidebar title')
})
it('reads fillcolor / strokecolor, honoring filled="f" / stroked="f"', async () => {
const parse = async (attrs: string) => {
const doc = await parseDocx(
await buildDocx({
bodyXml: vmlTextboxParagraph('<w:p><w:r><w:t>x</w:t></w:r></w:p>', attrs),
}),
)
return doc.blocks[0].textboxes?.[0]
}
const painted = await parse('fillcolor="#dbe5f1" strokecolor="#4472c4"')
expect(painted?.fill).toBe('dbe5f1')
expect(painted?.borderColor).toBe('4472c4')
const bare = await parse('fillcolor="#dbe5f1" strokecolor="#4472c4" filled="f" stroked="f"')
expect(bare?.fill).toBeUndefined()
expect(bare?.borderColor).toBeUndefined()
})
it('renders tables inside the textbox as one line per row, recursing into sdt-wrapped nested tables', async () => {
const nested =
'<w:sdt><w:sdtPr><w:alias w:val="analyst"/></w:sdtPr><w:sdtContent>' +
'<w:tbl><w:tr><w:tc><w:p><w:r><w:t>Alice</w:t></w:r></w:p>' +
'<w:p><w:r><w:t>alice@example.com</w:t></w:r></w:p></w:tc></w:tr></w:tbl>' +
'</w:sdtContent></w:sdt>'
const tbl =
'<w:tbl>' +
'<w:tr><w:tc><w:p><w:r><w:t>Rating</w:t></w:r></w:p></w:tc>' +
`<w:tc><w:p><w:r><w:t>Buy</w:t></w:r></w:p></w:tc></w:tr>` +
`<w:tr><w:tc>${nested}<w:p/></w:tc></w:tr>` +
'</w:tbl>'
const doc = await parseDocx(await buildDocx({ bodyXml: vmlTextboxParagraph(tbl) }))
const box = doc.blocks[0].textboxes?.[0]
const lines = box?.paras.map((p) => p.runs.map((r) => r.text).join('')) ?? []
expect(lines[0]).toBe('Rating\u2002\u2002Buy')
// nested table row becomes its own line; multiple cell paragraphs joined with a space
expect(lines).toContain('Alice alice@example.com')
// flattened rows don't map 1:1 to w:p children — the box must not be editable,
// or a sub-editor commit through patchTxbxContent would drop the table
expect(box?.readOnly).toBe(true)
})
it('keeps plain-paragraph textboxes editable (no readOnly flag)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: vmlTextboxParagraph('<w:p><w:r><w:t>Editable</w:t></w:r></w:p>'),
}),
)
expect(doc.blocks[0].textboxes?.[0].readOnly).toBeUndefined()
})
it('marks boxes whose content is sdt-wrapped as read-only (shells would be lost on rewrite)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: vmlTextboxParagraph(
'<w:sdt><w:sdtPr/><w:sdtContent><w:p><w:r><w:t>Wrapped</w:t></w:r></w:p></w:sdtContent></w:sdt>',
),
}),
)
const box = doc.blocks[0].textboxes?.[0]
expect(box?.paras[0].runs[0].text).toBe('Wrapped')
expect(box?.readOnly).toBe(true)
})
it('keeps textboxes whose content holds field codes on the Text box path (not Field passthrough)', async () => {
const fieldPara =
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:instrText xml:space="preserve"> DATE </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:r><w:t>2022-04-29</w:t></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: vmlTextboxParagraph(fieldPara) }))
const block = doc.blocks[0]
expect(block.label).toBe('Text box')
expect(block.textboxes?.[0].paras[0].runs.map((r) => r.text).join('')).toContain('2022-04-29')
})
it('still protects paragraphs whose own runs carry field codes', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: '<w:p><w:fldSimple w:instr=" PAGE "><w:r><w:t>1</w:t></w:r></w:fldSimple></w:p>',
}),
)
expect(doc.blocks[0].type).toBe('passthrough')
expect(doc.blocks[0].label).not.toBe('Text box')
})
})
describe('sdt-wrapped tables and rows', () => {
it('a body-level sdt whose content is a table displays as a table block', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
'<w:sdt><w:sdtPr><w:alias w:val="report"/></w:sdtPr><w:sdtContent>' +
'<w:tbl><w:tr><w:tc><w:p><w:r><w:t>H1</w:t></w:r></w:p></w:tc></w:tr>' +
'<w:tr><w:tc><w:p><w:r><w:t>Body</w:t></w:r></w:p></w:tc></w:tr></w:tbl>' +
'</w:sdtContent></w:sdt>',
}),
)
const block = doc.blocks[0]
expect(block.type).toBe('table')
expect(block.table?.rows).toHaveLength(2)
expect(block.table?.rows[0][0].paras[0]).toBe('H1')
expect(block.table?.rows[1][0].paras[0]).toBe('Body')
})
it('finds rows, cells and cell paragraphs through sdt wrappers inside a table', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
'<w:tbl>' +
'<w:sdt><w:sdtPr/><w:sdtContent>' +
'<w:tr><w:tc><w:sdt><w:sdtPr/><w:sdtContent>' +
'<w:p><w:r><w:t>Wrapped</w:t></w:r></w:p>' +
'</w:sdtContent></w:sdt></w:tc>' +
'<w:sdt><w:sdtPr/><w:sdtContent><w:tc><w:p><w:r><w:t>Cell2</w:t></w:r></w:p></w:tc></w:sdtContent></w:sdt>' +
'</w:tr>' +
'</w:sdtContent></w:sdt>' +
'<w:tr><w:tc><w:p><w:r><w:t>Plain</w:t></w:r></w:p></w:tc>' +
'<w:tc><w:p><w:r><w:t>Row</w:t></w:r></w:p></w:tc></w:tr>' +
'</w:tbl>',
}),
)
const table = doc.blocks[0].table
expect(table?.rows).toHaveLength(2)
expect(table?.rows[0].map((c) => c.paras[0])).toEqual(['Wrapped', 'Cell2'])
expect(table?.rows[1].map((c) => c.paras[0])).toEqual(['Plain', 'Row'])
})
})
@@ -0,0 +1,265 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import {
bibliographyLine,
citationText,
parseDocx,
readThemeColors,
readThemeFonts,
saveDocx,
type SaveBlock,
} from '../src/index'
import { buildDocx } from './helpers/build-docx'
const BODY = '<w:p><w:r><w:t>正文</w:t></w:r></w:p>'
const originalOrder = (doc: Awaited<ReturnType<typeof parseDocx>>): SaveBlock[] =>
doc.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original', docxIndex: b.docxIndex! }))
describe('watermark', () => {
it('writes a VML text watermark into the header and reads it back', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BODY }))
const out = await saveDocx(doc, originalOrder(doc), { watermark: '机密' })
const zip = await JSZip.loadAsync(out)
const header = await zip.file('word/header1.xml')!.async('string')
expect(header).toContain('<v:textpath')
expect(header).toContain('string="机密"')
const reparsed = await parseDocx(out)
expect(reparsed.watermarkText).toBe('机密')
})
it('a header text rewrite carries the existing watermark through', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BODY }))
const withWm = await parseDocx(
await saveDocx(doc, originalOrder(doc), { watermark: '草稿' }),
)
const out = await parseDocx(
await saveDocx(withWm, originalOrder(withWm), { header: { text: '公司内部' } }),
)
expect(out.headerText).toBe('公司内部')
expect(out.watermarkText).toBe('草稿')
})
it('watermark: null removes it but keeps the header text', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BODY }))
const withBoth = await parseDocx(
await saveDocx(doc, originalOrder(doc), { watermark: '草稿', header: { text: '页眉' } }),
)
const cleared = await parseDocx(
await saveDocx(withBoth, originalOrder(withBoth), { watermark: null }),
)
expect(cleared.watermarkText).toBeNull()
expect(cleared.headerText).toBe('页眉')
})
})
describe('theme fonts / colors', () => {
it('creates word/theme/theme1.xml when the document has none', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BODY }))
expect(doc.themeFonts).toBeNull()
const out = await saveDocx(doc, originalOrder(doc), {
themeFonts: { major: '微软雅黑', minor: '宋体', eastAsia: '宋体' },
themeColors: { accent1: '1F4E79' },
})
const zip = await JSZip.loadAsync(out)
const theme = await zip.file('word/theme/theme1.xml')!.async('string')
expect(readThemeFonts(theme)).toEqual({ major: '微软雅黑', minor: '宋体', eastAsia: '宋体' })
expect(readThemeColors(theme)?.accent1).toBe('1F4E79')
const ct = await zip.file('[Content_Types].xml')!.async('string')
expect(ct).toContain('/word/theme/theme1.xml')
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
expect(rels).toContain('theme/theme1.xml')
const reparsed = await parseDocx(out)
expect(reparsed.themeFonts).toEqual({ major: '微软雅黑', minor: '宋体', eastAsia: '宋体' })
})
it('patches an existing theme part in place', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BODY }))
const first = await parseDocx(
await saveDocx(doc, originalOrder(doc), {
themeFonts: { major: 'Calibri Light', minor: 'Calibri' },
}),
)
const out = await saveDocx(first, originalOrder(first), {
themeFonts: { major: 'Georgia', minor: 'Georgia' },
themeColors: { accent1: '70AD47', name: '绿色' },
})
const zip = await JSZip.loadAsync(out)
const theme = await zip.file('word/theme/theme1.xml')!.async('string')
expect(readThemeFonts(theme)?.major).toBe('Georgia')
expect(readThemeColors(theme)).toMatchObject({ accent1: '70AD47', name: '绿色' })
})
})
describe('bibliography sources', () => {
const source = {
tag: 'Wang2024',
type: 'Book',
author: '王明',
title: '深度学习实践',
year: '2024',
publisher: '清华出版社',
}
it('creates the b:Sources customXml part with rels + content type', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BODY }))
expect(doc.sources).toEqual([])
const out = await saveDocx(doc, originalOrder(doc), { sources: [source] })
const zip = await JSZip.loadAsync(out)
const item = await zip.file('customXml/item1.xml')!.async('string')
expect(item).toContain('b:Sources')
expect(item).toContain('深度学习实践')
expect(zip.file('customXml/itemProps1.xml')).toBeTruthy()
expect(zip.file('customXml/_rels/item1.xml.rels')).toBeTruthy()
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
expect(rels).toContain('../customXml/item1.xml')
const reparsed = await parseDocx(out)
expect(reparsed.sources).toEqual([source])
})
it('rewrites the existing sources part on later saves', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: BODY }))
const first = await parseDocx(await saveDocx(doc, originalOrder(doc), { sources: [source] }))
const second = await parseDocx(
await saveDocx(first, originalOrder(first), {
sources: [...first.sources, { tag: 'Li2023', type: 'JournalArticle', author: '李强', title: 'LLM 综述', year: '2023', publisher: '计算机学报' }],
}),
)
expect(second.sources).toHaveLength(2)
expect(second.sources[1].publisher).toBe('计算机学报')
})
it('citation and bibliography text formatting', () => {
expect(citationText(source)).toBe('(王明, 2024)')
expect(bibliographyLine(source)).toBe('王明. (2024). 深度学习实践. 清华出版社.')
})
it('adding a source keeps unmodeled fields and citation style of existing entries (surgical rebuild)', async () => {
// Original document: GB citation style + a journal entry with Volume/Pages/DOI/
// multiple authors (all fields the engine does not model)
const RICH_SOURCES =
'<b:Sources SelectedStyle="\\GB7714.xsl" StyleName="GB7714" Version="2005"' +
' xmlns:b="http://schemas.openxmlformats.org/officeDocument/2006/bibliography"' +
' xmlns="http://schemas.openxmlformats.org/officeDocument/2006/bibliography">' +
'<b:Source><b:Tag>Zhao2022</b:Tag><b:SourceType>JournalArticle</b:SourceType>' +
'<b:Author><b:Author><b:NameList>' +
'<b:Person><b:Last>赵</b:Last><b:First>一</b:First></b:Person>' +
'<b:Person><b:Last>钱</b:Last><b:First>二</b:First></b:Person>' +
'</b:NameList></b:Author></b:Author>' +
'<b:Title>大模型对齐</b:Title><b:Year>2022</b:Year>' +
'<b:JournalName>软件学报</b:JournalName>' +
'<b:Volume>33</b:Volume><b:Issue>4</b:Issue><b:Pages>1-20</b:Pages>' +
'<b:StandardNumber>doi:10.1000/xyz</b:StandardNumber>' +
'</b:Source></b:Sources>'
const bytes = await buildDocx({
bodyXml: BODY,
extraParts: [
{ path: 'customXml/item1.xml', xml: RICH_SOURCES, contentType: 'application/xml' },
],
})
const doc = await parseDocx(bytes)
expect(doc.sources).toHaveLength(1)
const out = await saveDocx(doc, originalOrder(doc), {
sources: [...doc.sources, source],
})
const item = await (await JSZip.loadAsync(out)).file('customXml/item1.xml')!.async('string')
// Before the surgical fix: the root element was rewritten to APA6 and Volume/Pages/
// DOI/the second author were all lost
expect(item).toContain('SelectedStyle="\\GB7714.xsl"')
expect(item).toContain('<b:Volume>33</b:Volume>')
expect(item).toContain('<b:Pages>1-20</b:Pages>')
expect(item).toContain('doi:10.1000/xyz')
expect(item).toContain('<b:Last>钱</b:Last>')
expect(item).toContain('深度学习实践') // the new entry is there too
})
})
describe('w:themeColor resolution', () => {
const THEME_XML =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office">' +
'<a:themeElements><a:clrScheme name="Office">' +
'<a:dk1><a:sysClr val="windowText" lastClr="1A1A1A"/></a:dk1>' +
'<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>' +
'<a:dk2><a:srgbClr val="44546A"/></a:dk2><a:lt2><a:srgbClr val="E7E6E6"/></a:lt2>' +
'<a:accent1><a:srgbClr val="4472C4"/></a:accent1><a:accent2><a:srgbClr val="ED7D31"/></a:accent2>' +
'<a:accent3><a:srgbClr val="A5A5A5"/></a:accent3><a:accent4><a:srgbClr val="FFC000"/></a:accent4>' +
'<a:accent5><a:srgbClr val="5B9BD5"/></a:accent5><a:accent6><a:srgbClr val="70AD47"/></a:accent6>' +
'<a:hlink><a:srgbClr val="0563C1"/></a:hlink><a:folHlink><a:srgbClr val="954F72"/></a:folHlink>' +
'</a:clrScheme><a:fontScheme name="Office">' +
'<a:majorFont><a:latin typeface="Calibri Light"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont>' +
'<a:minorFont><a:latin typeface="Calibri"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont>' +
'</a:fontScheme><a:fmtScheme name="Office"><a:fillStyleLst/><a:lnStyleLst/><a:effectStyleLst/><a:bgFillStyleLst/></a:fmtScheme>' +
'</a:themeElements></a:theme>'
const themedDocx = (bodyXml: string) =>
buildDocx({
bodyXml,
extraRels:
'<Relationship Id="rId40" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/>',
extraParts: [
{
path: 'word/theme/theme1.xml',
xml: THEME_XML,
contentType: 'application/vnd.openxmlformats-officedocument.theme+xml',
},
],
})
it('parseDocx returns the palette, including sysClr dk1/lt1 and hlink', async () => {
const doc = await parseDocx(await themedDocx(BODY))
expect(doc.themeColors).toMatchObject({
dk1: '1A1A1A',
lt1: 'FFFFFF',
accent1: '4472C4',
hlink: '0563C1',
})
})
it('run color resolves w:themeColor against the palette, beating a stale w:val', async () => {
const doc = await parseDocx(
await themedDocx(
'<w:p><w:r><w:rPr><w:color w:val="DEAD00" w:themeColor="accent1"/></w:rPr><w:t>主题色</w:t></w:r></w:p>',
),
)
expect(doc.blocks[0].runs?.[0].color).toBe('4472C4')
})
it('applies themeTint / themeShade (sRGB approximation)', async () => {
const doc = await parseDocx(
await themedDocx(
'<w:p><w:r><w:rPr><w:color w:val="8EAADB" w:themeColor="accent1" w:themeTint="99"/></w:rPr><w:t>浅</w:t></w:r>' +
'<w:r><w:rPr><w:color w:val="2F5496" w:themeColor="accent1" w:themeShade="BF"/></w:rPr><w:t>深</w:t></w:r></w:p>',
),
)
// tint 0x99: c*0.6 + 255*0.4 -> 8FAADC (Word writes 8EAADB; rounding differs by at most 1)
expect(doc.blocks[0].runs?.[0].color).toBe('8FAADC')
// shade 0xBF: c*0.75 -> 335593 (Word writes 2F5496 — linear-space difference; visually close enough)
expect(doc.blocks[0].runs?.[1].color).toBe('335593')
})
it('w:val alone still wins when the doc has no theme part', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
'<w:p><w:r><w:rPr><w:color w:val="FF0000" w:themeColor="accent1"/></w:rPr><w:t>x</w:t></w:r></w:p>',
}),
)
expect(doc.themeColors).toBeNull()
expect(doc.blocks[0].runs?.[0].color).toBe('FF0000')
})
it('an untouched themed document still saves byte-identical', async () => {
const bytes = await themedDocx(
'<w:p><w:r><w:rPr><w:color w:val="DEAD00" w:themeColor="accent1"/></w:rPr><w:t>主题色</w:t></w:r></w:p>',
)
const doc = await parseDocx(bytes)
const out = await saveDocx(doc, originalOrder(doc), {})
expect(out).toEqual(bytes)
})
})
@@ -0,0 +1,207 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import {
DEFAULT_SECTION,
generateParagraphXml,
parseDocx,
readSections,
readSectionSettings,
saveDocx,
sectionSettingsFromXml,
type GenerateContext,
type SaveBlock,
} from '../src/index'
import { buildDocx } from './helpers/build-docx'
const CTX: GenerateContext = {
headingStyleIds: new Map(),
allocateHyperlinkRel: () => 'rId999',
}
function originals(indexes: number[]): SaveBlock[] {
return indexes.map((docxIndex) => ({ kind: 'original', docxIndex }))
}
describe('paragraph shading and borders', () => {
it('round-trips shading fill and border sides through generate + parse', async () => {
const xml = generateParagraphXml(
{
type: 'paragraph',
format: { shadingFill: 'FFF2CC', borders: 'tb' },
runs: [{ text: '底纹段落' }],
},
CTX,
)
expect(xml).toContain('<w:shd w:val="clear" w:color="auto" w:fill="FFF2CC"/>')
expect(xml).toContain('<w:pBdr><w:top')
expect(xml).toContain('<w:bottom')
expect(xml).not.toContain('<w:left')
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
expect(doc.blocks[0].format?.shadingFill).toBe('FFF2CC')
expect(doc.blocks[0].format?.borders).toBe('tb')
})
})
describe('page border and columns (sectPr)', () => {
it('adds and reads a page border box', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }))
const saved = await saveDocx(doc, originals([0]), {
section: { ...readSectionSettings(doc), pageBorder: true },
})
const reparsed = await parseDocx(saved)
expect(readSectionSettings(reparsed).pageBorder).toBe(true)
expect(reparsed.internal.documentXml).toContain('<w:pgBorders w:offsetFrom="page">')
// and removing it again
const cleared = await saveDocx(reparsed, originals([0]), {
section: { ...readSectionSettings(reparsed), pageBorder: false },
})
expect(readSectionSettings(await parseDocx(cleared)).pageBorder).toBe(false)
})
it('sets and clears column count', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }))
const saved = await saveDocx(doc, originals([0]), {
section: { ...readSectionSettings(doc), columns: 2 },
})
const reparsed = await parseDocx(saved)
expect(readSectionSettings(reparsed).columns).toBe(2)
const back = await saveDocx(reparsed, originals([0]), {
section: { ...readSectionSettings(reparsed), columns: 1 },
})
expect(readSectionSettings(await parseDocx(back)).columns).toBe(1)
})
it('DEFAULT_SECTION carries the new fields', () => {
expect(DEFAULT_SECTION.pageBorder).toBe(false)
expect(DEFAULT_SECTION.columns).toBe(1)
})
// Government documents write explicit "no border" as pgBorders with all sides
// val="none"; the presence of the element alone must not draw a border
const NONE_PG_BORDERS =
'<w:pgBorders>' +
'<w:top w:val="none" w:sz="0" w:space="0"/>' +
'<w:left w:val="none" w:sz="0" w:space="0"/>' +
'<w:bottom w:val="none" w:sz="0" w:space="0"/>' +
'<w:right w:val="none" w:sz="0" w:space="0"/>' +
'</w:pgBorders>'
it('pgBorders with all sides val="none" yields pageBorder=false', () => {
const sectPr = `<w:sectPr><w:pgSz w:w="11906" w:h="16838"/>${NONE_PG_BORDERS}</w:sectPr>`
expect(sectionSettingsFromXml(sectPr).pageBorder).toBe(false)
})
it('pgBorders side values nil / missing are not visible; any drawn side is', () => {
const wrap = (sides: string) => `<w:sectPr><w:pgBorders>${sides}</w:pgBorders></w:sectPr>`
expect(sectionSettingsFromXml(wrap('<w:top w:val="nil"/>')).pageBorder).toBe(false)
expect(sectionSettingsFromXml(wrap('')).pageBorder).toBe(false)
expect(
sectionSettingsFromXml(wrap('<w:top w:val="none"/><w:left w:val="single" w:sz="4"/>'))
.pageBorder,
).toBe(true)
expect(
sectionSettingsFromXml(
wrap(
'<w:top w:val="single" w:sz="4" w:space="24" w:color="auto"/>' +
'<w:left w:val="single" w:sz="4" w:space="24" w:color="auto"/>' +
'<w:bottom w:val="single" w:sz="4" w:space="24" w:color="auto"/>' +
'<w:right w:val="single" w:sz="4" w:space="24" w:color="auto"/>',
),
).pageBorder,
).toBe(true)
})
it('sections whose pgBorders declare all sides none parse without a page border', async () => {
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
sectPrExtra: NONE_PG_BORDERS,
})
const parsed = await parseDocx(bytes)
expect(readSectionSettings(parsed).pageBorder).toBe(false)
const sections = readSections(parsed)
expect(sections).toHaveLength(1)
expect(sections[0].settings.pageBorder).toBe(false)
})
})
describe('header / footer', () => {
it('creates default header and footer parts with references and content types', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }))
expect(doc.headerText).toBeNull()
const saved = await saveDocx(doc, originals([0]), {
header: { text: '机密文件' },
footer: { text: '第', pageNumber: true },
})
const zip = await JSZip.loadAsync(saved)
const headerXml = await zip.file('word/header1.xml')!.async('string')
const footerXml = await zip.file('word/footer1.xml')!.async('string')
expect(headerXml).toContain('机密文件')
expect(footerXml).toContain(' PAGE ')
const docXml = await zip.file('word/document.xml')!.async('string')
expect(docXml).toMatch(
/<w:sectPr[^>]*><w:headerReference w:type="default" r:id="rId\d+"\/><w:footerReference/,
)
const ct = await zip.file('[Content_Types].xml')!.async('string')
expect(ct).toContain('/word/header1.xml')
expect(ct).toContain('header+xml')
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
expect(rels).toContain('Target="header1.xml"')
// reparse exposes the text for display
const reparsed = await parseDocx(saved)
expect(reparsed.headerText).toBe('机密文件')
expect(reparsed.footerHasPageNumber).toBe(true)
})
it('overwrites an existing default header instead of adding a second one', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }))
const first = await saveDocx(doc, originals([0]), { header: { text: '版本一' } })
const second = await saveDocx(await parseDocx(first), originals([0]), {
header: { text: '版本二' },
})
const zip = await JSZip.loadAsync(second)
expect(zip.file('word/header2.xml')).toBeNull()
expect(await zip.file('word/header1.xml')!.async('string')).toContain('版本二')
const docXml = await zip.file('word/document.xml')!.async('string')
expect(docXml.match(/<w:headerReference/g)).toHaveLength(1)
})
})
describe('protection password hash', () => {
it('round-trips after setting a password: the correct password verifies, a wrong one does not', async () => {
const { hashProtectionPassword, verifyProtectionPassword, parseDocx, saveDocx } =
await import('../src/index')
const { buildDocx } = await import('./helpers/build-docx')
const creds = await hashProtectionPassword('s3cret', 1000) // lower iterations for the test
const parsed = await parseDocx(
await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }),
)
const blocks = parsed.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
const saved = await saveDocx(parsed, blocks, {
protection: { edit: 'readOnly', enforced: true, ...creds },
})
const reparsed = await parseDocx(saved)
expect(reparsed.protection).toMatchObject({
edit: 'readOnly',
enforced: true,
spinCount: 1000,
algorithmSid: 14,
})
expect(reparsed.protection?.hash).toBe(creds.hash)
expect(await verifyProtectionPassword('s3cret', reparsed.protection!)).toBe(true)
expect(await verifyProtectionPassword('wrong', reparsed.protection!)).toBe(false)
// settings.xml carries the full field set
const zip = await (await import('jszip')).default.loadAsync(saved)
const settings = await zip.file('word/settings.xml')!.async('string')
expect(settings).toContain('w:cryptAlgorithmSid="14"')
expect(settings).toContain('w:cryptSpinCount="1000"')
})
})
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["src", "tests", "scripts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
testTimeout: 20000,
},
})