Sync snapshot (2026-08-16) (#99)

- Docs: print dialog with live preview, EMF/WMF rendering, nested tables, margin comments, Word-style table UX
- Slides: chart and SmartArt fidelity overhaul, Format Background pane, Shape Tools tab, PowerPoint line-spacing model
- Sheets: ribbon batches (themes, page breaks, protection, goal seek), AI formula audit and workbook search, import fidelity fixes
- PDF: comments margin with in-place note editing
- UI: unified color pickers and save icon across apps (icon by @ulangmeier in #96)

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-08-17 00:09:18 +08:00
committed by GitHub
co-authored by GenOffice
parent e4d9d407c1
commit 04a994b9e9
312 changed files with 36032 additions and 4115 deletions
+2 -1
View File
@@ -7,7 +7,8 @@
"description": "docx parsing (Block tree with docxIndex anchors), OOXML fragment generation, paragraph-patch save",
"exports": {
".": "./src/index.ts",
"./math": "./src/math.ts"
"./math": "./src/math.ts",
"./metafile": "./src/metafile.ts"
},
"scripts": {
"typecheck": "tsc --noEmit",
+57 -2
View File
@@ -42,6 +42,7 @@ export function parseChartPartXml(xml: string, partPath: string): ChartDisplay |
const plot = childrenOf(plotArea).find((c) => (nameOf(c) ?? '').endsWith('Chart'))
if (!plot) return null
const kind = CHART_KINDS[nameOf(plot) ?? ''] ?? 'other'
const horizontal = kind === 'bar' && attrsOf(findChild(plot, 'c:barDir') ?? {})['val'] === 'bar'
let categories: string[] = []
const series: ChartSeries[] = []
@@ -72,6 +73,7 @@ export function parseChartPartXml(xml: string, partPath: string): ChartDisplay |
return {
partPath,
kind,
...(horizontal ? { horizontal } : {}),
...(title !== undefined ? { title } : {}),
categories,
series,
@@ -231,7 +233,25 @@ function chartTitle(chart: XNode): string | undefined {
}
}
walk(title)
return texts.join('')
let joined = texts.join('')
if (joined) return joined
// strRef titles carry the cached text in c:strCache c:v, not a:t
const walkV = (node: XNode) => {
for (const child of childrenOf(node)) {
if (nameOf(child) === 'c:v') texts.push(textOf(child))
else walkV(child)
}
}
walkV(title)
joined = texts.join('')
if (joined) return joined
// text-less c:title = auto title; Word renders the "Chart Title" placeholder
// unless the auto title was explicitly deleted (CT_Boolean: a val-less
// element and val="true" both mean true)
const del = findChild(chart, 'c:autoTitleDeleted')
const delVal = del ? attrsOf(del)['val'] : undefined
const deleted = del !== undefined && (delVal === undefined || delVal === '1' || delVal === 'true')
return deleted ? undefined : 'Chart Title'
}
const _XLSX_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
@@ -338,12 +358,47 @@ export interface ChartPatch {
* these caches, but "Edit Data" will show the original sheet numbers.
*/
export function patchChartPartXml(xml: string, patch: ChartPatch): string {
// a text-less title (auto title / strRef with no rich body) has no a:t to
// rewrite: give it one first, then patch it like any other title
if (patch.title !== undefined) {
const t = tagRange(xml, 'c:title')
if (
t &&
innerTextRanges(xml, 'a:t', t.start, t.end).length === 0 &&
innerTextRanges(xml, 'c:v', t.start, t.end).length === 0
) {
const runXml = `<a:r><a:t>${escapeXmlText(patch.title)}</a:t></a:r>`
const tx = tagRange(xml, 'c:tx', t.start, t.end)
const p = tx ? tagRange(xml, 'a:p', tx.start, tx.end) : null
if (p) {
// Word auto titles carry an empty c:tx/c:rich paragraph (only
// a:endParaRPr); CT_Title allows one c:tx, so inject the run there,
// before a:endParaRPr per schema order
const endPr = xml.indexOf('<a:endParaRPr', p.start)
const at = endPr !== -1 && endPr < p.end ? endPr : p.end - '</a:p>'.length
xml = xml.slice(0, at) + runXml + xml.slice(at)
} else {
const rich = `<c:tx><c:rich><a:bodyPr/><a:lstStyle/><a:p>${runXml}</a:p></c:rich></c:tx>`
if (tx) {
// cache-less strRef tx (no a:p, no c:v): nothing to inject into —
// replace the whole c:tx with a rich body (CT_Tx is a choice)
xml = xml.slice(0, tx.start) + rich + xml.slice(tx.end)
} else {
const openEnd = xml.indexOf('>', t.start) + 1
xml = xml.slice(0, openEnd) + rich + xml.slice(openEnd)
}
}
}
}
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)
let texts = innerTextRanges(xml, 'a:t', title.start, title.end)
// strRef titles keep the text in the c:strCache c:v cache instead
if (texts.length === 0) texts = innerTextRanges(xml, 'c:v', 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! : '' })
+66 -8
View File
@@ -7,7 +7,7 @@ import type {
TableCell,
TableModel,
} from './types'
import { escapeXmlAttr, escapeXmlText, textHasComplexScript } from './xml-utils'
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
export interface GenerateContext {
/** heading level -> styleId existing in the original styles.xml */
@@ -1630,6 +1630,21 @@ export function generateTableModelXml(model: TableModel, originalTableXml?: stri
}
}
}
// Table alignment (w:jc): explicit align replaces/removes the original;
// undefined keeps whatever the original tblPr carried
if (model.align) {
tblPr = tblPr.replace(/<w:jc[^>]*\/>/, '')
if (model.align !== 'left') {
const tag = `<w:jc w:val="${model.align}"/>`
// schema order puts w:jc right after w:tblW (after w:tblStyle when there is no tblW)
if (/<w:tblW[^>]*\/>/.test(tblPr)) tblPr = tblPr.replace(/(<w:tblW[^>]*\/>)/, `$1${tag}`)
else if (/<w:tblStyle[^>]*\/>/.test(tblPr))
tblPr = tblPr.replace(/(<w:tblStyle[^>]*\/>)/, `$1${tag}`)
else if (/<w:tblPr\/>/.test(tblPr))
tblPr = tblPr.replace('<w:tblPr/>', `<w:tblPr>${tag}</w:tblPr>`)
else tblPr = tblPr.replace(/(<w:tblPr(?:\s[^>]*)?>)/, `$1${tag}`)
}
}
return `<w:tbl>${tblPr}${grid}${rows}</w:tbl>`
}
@@ -1918,13 +1933,54 @@ function runFragmentXml(run: Run, insideLink: boolean): string {
)
}
if (run.instrField !== undefined) {
// Generic inline field: run text is the cached result; the instruction is written back verbatim
// Generic inline field: run text is the cached result; the instruction is written back verbatim.
// A preserved begin run (form fields: w:ffData) replaces the bare begin, and the run text is a
// synthesized glyph Word must not see as a cached result — Word draws the box from ffData.
const instrXml =
`<w:r><w:instrText xml:space="preserve"> ${escapeXmlText(run.instrField)} </w:instrText></w:r>` +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>'
const endXml = '<w:r><w:fldChar w:fldCharType="end"/></w:r>'
if (run.fldBeginXml) {
// Adjacent identical checkboxes merge into one text node in the editor
// (equal marks), so each ☐/☒ glyph in the run is one field sharing the
// same ffData; characters typed beside them survive as plain text runs.
// The glyph is the source of truth for the checked state: an in-editor
// ☐↔☒ edit must land in w:checked or Word keeps the old state.
const syncedField = (checked: boolean): string => {
const val = `<w:checked w:val="${checked ? '1' : '0'}"/>`
let begin = run.fldBeginXml!.replace(/<w:checked(?:\s[^>]*)?\/>/g, '')
if (begin.includes('</w:checkBox>'))
begin = begin.replace('</w:checkBox>', `${val}</w:checkBox>`)
else
begin = begin.replace(/<w:checkBox((?:\s[^>]*)?)\/>/, `<w:checkBox$1>${val}</w:checkBox>`)
return begin + instrXml + endXml
}
let out = ''
let plain = ''
const flush = () => {
if (!plain) return
out += generateRunXml(
{ ...run, text: plain, instrField: undefined, fldBeginXml: undefined },
insideLink,
)
plain = ''
}
for (const ch of run.text) {
if (ch === '☐' || ch === '☒') {
flush()
out += syncedField(ch === '☒')
} else plain += ch
}
flush()
// no glyph left = the user typed over / deleted the checkbox; Word also
// removes the form field then, so only the replacement text survives
return out
}
return (
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
`<w:r><w:instrText xml:space="preserve"> ${escapeXmlText(run.instrField)} </w:instrText></w:r>` +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
instrXml +
generateRunXml({ ...run, instrField: undefined }, insideLink) +
'<w:r><w:fldChar w:fldCharType="end"/></w:r>'
endXml
)
}
let xml = run.text === '' ? '' : generateRunXml(run, insideLink)
@@ -2132,9 +2188,11 @@ export function mergeRPrModel(rawRPr: string, run: Run, insideLink: boolean): st
const inner = rawRPr.slice(open.length, rawRPr.length - '</w:rPr>'.length)
const rawChildren = splitXmlChildren(inner)
const rawOf = (tag: string) => rawChildren.find((c) => c.name === tag)?.xml
// complex-script runs decode bold/italic/size from the Cs twins on the parse side;
// compare against the same elements or every untouched cs run would get "rebuilt"
const cs = run.cs ?? textHasComplexScript(run.text)
// rtl runs decode bold/italic/size from the Cs twins on the parse side;
// compare against the same elements or every untouched rtl run would get "rebuilt".
// run.cs can be dropped by round-trips that rebuild the Run (editor marks), so an
// explicit raw w:rtl re-selects the Cs set on its own.
const cs = !!run.cs || rawBool(rawOf('w:rtl'))
// Compare model vs raw-encoded values group by group; equal → keep the original bytes
// (drop the group from fresh)
+3 -1
View File
@@ -1,5 +1,5 @@
export * from './types'
export { parseDocx, type ParseExtras } from './parse'
export { parseDocx, styleRunFormat, type ParseExtras } from './parse'
export {
saveDocx,
findChartWorkbookPath,
@@ -98,7 +98,9 @@ export {
bulletMarkerScale,
computeListMarkerInfos,
computeListMarkers,
customEnumItems,
formatNumber,
markerTabAdvance,
type ListItemRef,
type ListMarkerInfo,
} from './list-markers'
+50 -3
View File
@@ -20,6 +20,15 @@ function toLetters(value: number): string {
return String.fromCharCode(64 + n).repeat(repeat)
}
function toGreek(value: number, base: number): string {
if (value < 1) return String(value)
// 24-letter alphabet (no final sigma); 25 -> αα, repeated like toLetters
const n = ((value - 1) % 24) + 1
const repeat = Math.floor((value - 1) / 24) + 1
// skip the final-sigma slot (ς / unassigned) between the 17th and 18th letters
return String.fromCharCode(base + n - 1 + (n >= 18 ? 1 : 0)).repeat(repeat)
}
const ROMAN: Array<[number, string]> = [
[1000, 'M'],
[900, 'CM'],
@@ -70,7 +79,19 @@ function toChinese(value: number): string {
return out.replace(/^一十/, '十')
}
export function formatNumber(value: number, numFmt: string): string {
/** w14 custom numFmt enumeration ("α, β, γ, ..."): comma-separated items, a trailing "..." marks continuation */
export function customEnumItems(format: string): string[] | null {
const items = format.split(',').map((s) => s.trim())
while (items.length > 0 && /^(\.{3}|…)?$/.test(items[items.length - 1])) items.pop()
return items.length >= 2 && items.every(Boolean) ? items : null
}
export function formatNumber(value: number, numFmt: string, customFormat?: string): string {
if (numFmt === 'custom') {
const items = customFormat ? customEnumItems(customFormat) : null
// enumeration exhausted: cycle (best-effort; Word's continuation rules are undocumented)
return items && value >= 1 ? items[(value - 1) % items.length] : String(value)
}
switch (numFmt) {
case 'decimalZero':
return value < 10 && value >= 0 ? `0${value}` : String(value)
@@ -82,6 +103,10 @@ export function formatNumber(value: number, numFmt: string): string {
return toRoman(value).toLowerCase()
case 'upperRoman':
return toRoman(value)
case 'lowerGreek':
return toGreek(value, 0x3b1)
case 'upperGreek':
return toGreek(value, 0x391)
case 'chineseCounting':
case 'chineseCountingThousand':
case 'japaneseCounting':
@@ -167,9 +192,12 @@ export function computeListMarkerInfos(
const refLvl = Number(d) - 1
const refDef = def.levels[refLvl]
const value = c[refLvl] ?? refDef?.start ?? 1
return formatNumber(value, refDef?.numFmt ?? 'decimal')
return formatNumber(value, refDef?.numFmt ?? 'decimal', refDef?.customFormat)
})
return marker ? { text: marker } : null
// numFmt "none": an explicit empty marker (Word shows nothing) so renderer
// counter fallbacks don't kick in on the null
if (!marker && level.numFmt !== 'none') return null
return { text: marker }
})
}
@@ -179,3 +207,22 @@ export function computeListMarkers(
): (string | null)[] {
return computeListMarkerInfos(items, defs).map((m) => m?.text ?? null)
}
/**
* Word's default tab after a numbering marker: when the marker fits the hanging
* area the text starts at the text indent; otherwise it jumps to the next
* default-tab-grid stop past the marker end. All positions are twips relative
* to the text column edge. Returns the marker-box width (marker start -> text
* start), or null when the hanging area already fits.
*/
export function markerTabAdvance(
markerStart: number,
markerWidth: number,
textIndent: number,
defaultTab = 720,
): number | null {
const end = markerStart + markerWidth
if (markerStart < textIndent && end <= textIndent) return null
const stop = (Math.floor(end / defaultTab) + 1) * defaultTab
return stop - markerStart
}
+47 -9
View File
@@ -2,26 +2,64 @@ import { convertEmfToDataUrl, convertWmfToDataUrl } from './vendor/emf-converter
const EMF_MIMES = new Set(['image/emf', 'image/x-emf'])
const WMF_MIMES = new Set(['image/wmf', 'image/x-wmf'])
// gzip-compressed metafiles (.emz/.wmz)
const EMZ_MIMES = new Set(['image/emz', 'image/x-emz'])
const WMZ_MIMES = new Set(['image/wmz', 'image/x-wmz'])
export function isMetafileMime(mime: string | undefined): mime is string {
return mime !== undefined && (EMF_MIMES.has(mime) || WMF_MIMES.has(mime))
return (
mime !== undefined &&
(EMF_MIMES.has(mime) || WMF_MIMES.has(mime) || EMZ_MIMES.has(mime) || WMZ_MIMES.has(mime))
)
}
function isGzip(bytes: Uint8Array): boolean {
return bytes.length > 2 && bytes[0] === 0x1f && bytes[1] === 0x8b
}
async function gunzip(bytes: Uint8Array): Promise<Uint8Array> {
// copy to a fresh ArrayBuffer-backed view (BlobPart rejects ArrayBufferLike)
const stream = new Blob([new Uint8Array(bytes)])
.stream()
.pipeThrough(new DecompressionStream('gzip'))
return new Uint8Array(await new Response(stream).arrayBuffer())
}
/** EMR_HEADER iType plus the ' EMF' signature at offset 40 */
function looksLikeEmf(bytes: Uint8Array): boolean {
if (bytes.length < 44) return false
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
return dv.getUint32(0, true) === 1 && dv.getUint32(40, true) === 0x464d4520
}
/**
* Render EMF/WMF bytes to a PNG data URL via the vendored emf-converter.
* Returns null on parse failure or when no canvas API exists (non-renderer
* environments), so callers keep their existing empty-frame degrade.
* Render EMF/WMF (or gzipped EMZ/WMZ) bytes to a PNG data URL via the vendored
* emf-converter. Returns null on parse failure or when no canvas API exists
* (non-renderer environments), so callers keep their existing empty-frame
* degrade. Failures are logged instead of silently swallowed.
*/
export async function metafileToDataUrl(
bytes: ArrayBuffer | Uint8Array,
mime: string,
): Promise<string | null> {
const buffer = bytes instanceof Uint8Array ? bytes.slice().buffer : bytes
try {
if (EMF_MIMES.has(mime)) return await convertEmfToDataUrl(buffer, { dpiScale: 2 })
if (WMF_MIMES.has(mime)) return await convertWmfToDataUrl(buffer, { dpiScale: 2 })
return null
} catch {
let u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
if (isGzip(u8)) u8 = await gunzip(u8)
const buffer = u8.slice().buffer
let isEmf: boolean
if (EMF_MIMES.has(mime)) isEmf = true
else if (WMF_MIMES.has(mime)) isEmf = false
else if (EMZ_MIMES.has(mime) || WMZ_MIMES.has(mime)) isEmf = looksLikeEmf(u8)
else return null
const result = isEmf
? await convertEmfToDataUrl(buffer, { dpiScale: 2 })
: await convertWmfToDataUrl(buffer, { dpiScale: 2 })
if (result === null) {
console.warn(`metafileToDataUrl: converter returned null (${mime}, ${u8.byteLength} bytes)`)
}
return result
} catch (err) {
console.warn(`metafileToDataUrl: conversion failed (${mime}):`, err)
return null
}
}
File diff suppressed because it is too large Load Diff
+12 -6
View File
@@ -23,6 +23,7 @@ import {
stripInkRuns,
} from './ink'
import { assertZipWithinLimits, type ParseExtras } from './parse'
import { loadDocxZip } from './zip-load'
import { BLANK_NUMBERING_XML, abstractNumXml, type CustomNumberingLevel } from './blank'
import { applyPageNumType, applySectionSettings, applySectionStartType } from './section'
import {
@@ -290,7 +291,7 @@ export async function findChartWorkbookPath(
chartPath: string,
): Promise<string | null> {
try {
const zip = await JSZip.loadAsync(docxBytes)
const zip = await loadDocxZip(docxBytes)
// chart path: word/charts/chart1.xml → rels: word/charts/_rels/chart1.xml.rels
const dir = chartPath.substring(0, chartPath.lastIndexOf('/'))
const file = chartPath.substring(chartPath.lastIndexOf('/') + 1)
@@ -319,7 +320,7 @@ export async function readDocxPartBase64(
path: string,
): Promise<string | null> {
try {
const zip = await JSZip.loadAsync(docxBytes)
const zip = await loadDocxZip(docxBytes)
const file = zip.file(path)
if (!file) return null
const bytes = await file.async('uint8array')
@@ -405,7 +406,7 @@ export async function saveDocx(
(options.partBinary === undefined || Object.keys(options.partBinary).length === 0)
if (isUnchanged) return originalBytes
const zip = await JSZip.loadAsync(originalBytes)
const zip = await loadDocxZip(originalBytes)
assertZipWithinLimits(zip)
// Relationship allocation for newly created hyperlinks and images.
@@ -586,9 +587,12 @@ export async function saveDocx(
) => {
if (hf === undefined) return
const refs = trailingSectPr.match(new RegExp(`<w:${kind}Reference[^>]*/>`, 'g')) ?? []
// non-schema w:type="odd" and untyped references count as default (mirrors parse)
const existing =
refs.find((r) => r.includes(`w:type="${hfType}"`)) ??
(hfType === 'default' ? refs.find((r) => !/w:type="/.test(r)) : undefined)
(hfType === 'default'
? (refs.find((r) => r.includes('w:type="odd"')) ?? refs.find((r) => !/w:type="/.test(r)))
: undefined)
const rId = existing ? /r:id="([^"]+)"/.exec(existing)?.[1] : undefined
const target = rId ? relTargets.get(rId) : undefined
if (target) {
@@ -652,7 +656,9 @@ export async function saveDocx(
block?.originalXml?.match(/<w:sectPr[^>]*\/>|<w:sectPr[\s\S]*?<\/w:sectPr>/)?.[0] ?? ''
const refs = sectPr.match(new RegExp(`<w:${edit.kind}Reference[^>]*/>`, 'g')) ?? []
const existing =
refs.find((r) => r.includes('w:type="default"')) ?? refs.find((r) => !/w:type="/.test(r))
refs.find((r) => r.includes('w:type="default"')) ??
refs.find((r) => r.includes('w:type="odd"')) ??
refs.find((r) => !/w:type="/.test(r))
const rId = existing ? /r:id="([^"]+)"/.exec(existing)?.[1] : undefined
const target = rId ? relTargets.get(rId) : undefined
if (target) {
@@ -1292,7 +1298,7 @@ function headerFooterPartXml(
// user-typed '#' stand in (first occurrence only — literal '#' text in a
// part that has real marks must stay literal).
const hasPageMark = hf.paras.some((p) =>
[p.runs, ...(p.cells?.map((c) => c.runs) ?? [])].some((rs) =>
[p.runs, ...(p.cells?.flatMap((c) => c.paras) ?? [])].some((rs) =>
rs.some((r) => r.text.includes(PAGE_MARK)),
),
)
+12 -1
View File
@@ -51,7 +51,18 @@ export function scanBody(documentXml: string): BodyScan {
if (isClosing) {
if (depth === 0) {
if (name === 'w:body') break
if (name === 'w:body') {
// Word tolerates multiple sibling <w:body> elements (POI
// MultipleBodyBug.docx) and renders their contents concatenated;
// keep scanning any later body. Patch-save splices all elements
// back into the first body, which matches Word's own normalization.
const nextBody = /<w:body(?:\s(?:[^<>"']|"[^"]*"|'[^']*')*)?>/g
nextBody.lastIndex = match.index + tag.length
const nb = nextBody.exec(documentXml)
if (!nb) break
TAG_RE.lastIndex = nb.index + nb[0].length
continue
}
throw new Error(`unexpected closing tag </${name}> at body level`)
}
depth--
+11 -1
View File
@@ -95,6 +95,16 @@ export function readSectionSettings(parsed: ParsedDoc): SectionSettings {
const SECT_PR_RE = /<w:sectPr[^>]*\/>|<w:sectPr[\s\S]*?<\/w:sectPr>/
/** On/off flag element (w:titlePg, w:evenAndOddHeaders, …) present and not switched
* off: matches self-closing and paired forms, w:val="0|false|off" counts as off. */
export function xmlFlagOn(xml: string, tag: string): boolean {
for (const m of xml.matchAll(new RegExp(`<${tag}(?=[\\s/>])[^>]*>`, 'g'))) {
const val = /w:val="([^"]*)"/.exec(m[0])?.[1]
if (val === undefined || !/^(?:0|false|off)$/.test(val)) return true
}
return false
}
function hfRefs(
xml: string,
kind: 'header' | 'footer',
@@ -126,7 +136,7 @@ function sectionFromSectPr(
firstBlockIndex,
lastBlockIndex,
sectPrXml,
titlePg: /<w:titlePg\s*\/>/.test(sectPrXml),
titlePg: xmlFlagOn(sectPrXml, 'w:titlePg'),
...(pgNumStart !== undefined ? { pageNumberStart: parseInt(pgNumStart, 10) } : {}),
...(pgNumFmt !== undefined ? { pageNumberFmt: pgNumFmt } : {}),
headerRefs: hfRefs(sectPrXml, 'header'),
+79 -11
View File
@@ -47,7 +47,8 @@ export interface Run {
highlight?: string
/** character shading fill, hex without '#' (w:shd w:fill, non-auto); highlight wins when both are set */
shading?: string
/** bold/italic/size were read from the Cs twins (w:bCs/w:iCs/w:szCs): w:rtl run or complex-script text */
/** rtl run (explicit w:rtl, or inherited from its style chain): bold/italic/size
* were read from the Cs twins (w:bCs/w:iCs/w:szCs) */
cs?: boolean
/** superscript / subscript (w:vertAlign) */
vertAlign?: 'superscript' | 'subscript'
@@ -85,6 +86,9 @@ export interface Run {
refInstr?: string
/** Generic inline field (DATE/TIME/NUMPAGES/FILENAME etc.): full instruction text; run text is the cached result */
instrField?: string
/** Original field-begin run XML (w:fldChar + w:ffData), written back verbatim so form-field
* definitions survive; when set, the run text is a synthesized glyph (☐/☒), not a cached result */
fldBeginXml?: string
/**
* Run-level formatting revision (w:rPrChange): records the review info and the modeled
* subset of the pre-revision formatting. Accept = keep the current formatting and clear
@@ -120,11 +124,21 @@ export interface Run {
*/
ruby?: { rt: string; xml: string }
/**
* Inline picture in a table cell. `dataUrl` is for display; `xml` is the
* exact <w:drawing> fragment, re-wrapped in a w:r and emitted verbatim
* when the cell regenerates.
* Picture carried by this run (table cell, or a paragraph mixing text and
* pictures). `dataUrl` is for display; `xml` is the exact <w:drawing>
* fragment, re-wrapped in a w:r and emitted verbatim on regeneration.
* `wrap`/offsets are display-only anchor geometry of a floating picture
* (wp:anchor); absent = inline.
*/
image?: { dataUrl: string; widthPx?: number; heightPx?: number; xml: string }
image?: {
dataUrl: string
widthPx?: number
heightPx?: number
xml: string
wrap?: ImageWrap
offsetXEmu?: number
offsetYEmu?: number
}
}
/** One comment from word/comments.xml (read-only display model). */
@@ -326,6 +340,9 @@ export interface SectionInfo {
/** one rich paragraph of a header / footer part */
export interface HfParagraph extends ParaFormat {
/** w:framePr w:xAlign — text frame floated at the margin edge; the line
* overlays the following paragraph's flow line instead of stacking (Word) */
frameXAlign?: 'left' | 'center' | 'right'
/** w:ptab alignments indexed by overall tab order (regular w:tab slots are undefined); margin-relative, ignores tab stops */
ptabAligns?: Array<'left' | 'center' | 'right' | undefined>
runs: Run[]
@@ -336,7 +353,8 @@ export interface HfParagraph extends ParaFormat {
/** one cell of a header/footer layout-table row */
export interface HfTableCell {
runs: Run[]
/** cell paragraphs, each rendered as its own block line (Word stacks them) */
paras: Run[][]
align?: ParaAlign
/** column width as % of the row (w:tcW, falling back to tblGrid) */
widthPct?: number
@@ -348,14 +366,20 @@ export interface HfTableCell {
export interface NumberingLevel {
/** w:numFmt, e.g. "decimal" | "bullet" | "lowerLetter" | "upperRoman" | "chineseCountingThousand" */
numFmt: string
/** w14 custom numFmt enumeration (numFmt "custom"), e.g. "α, β, γ, ..." */
customFormat?: string
/** w:lvlText, e.g. "%1." or "%1.%2" (placeholders %n = counter of level n-1) or a bullet glyph */
lvlText: string
/** w:start, default 1 */
start: number
/** w:suff — what follows the marker (Word default: tab up to the hanging edge) */
suff?: 'tab' | 'space' | 'nothing'
/** w:pPr/w:ind left (twips); fallback geometry for items without their own w:ind */
indentLeft?: number
/** w:pPr/w:ind hanging (twips): width reserved for the number/bullet marker */
hanging?: number
/** w:pPr/w:ind positive firstLine (twips): the marker starts right of the text indent */
firstLine?: number
/** w:rPr/w:sz of the marker itself (half-points) */
szHalfPoints?: number
/** w:rPr/w:rFonts of the marker (bullet glyphs in Symbol/Wingdings need decoding) */
@@ -399,12 +423,20 @@ export interface HfImage {
heightPx?: number
/** wp:anchor floating / VML position:absolute (otherwise inline) */
floating?: boolean
/** behind body text (negative VML z-index): picture watermarks */
/** behind body text (negative VML z-index / wp:anchor behindDoc): picture watermarks */
behind?: boolean
/** VML mso-position-horizontal (margin/page relative) */
/** VML mso-position-horizontal / wp:positionH wp:align */
posH?: 'left' | 'center' | 'right'
/** VML mso-position-vertical (margin/page relative) */
/** VML mso-position-vertical / wp:positionV wp:align */
posV?: 'top' | 'center' | 'bottom'
/** wp:positionH wp:posOffset (px); origin per posHRel */
posXPx?: number
/** wp:positionV wp:posOffset (px); origin per posVRel */
posYPx?: number
/** wp:positionH relativeFrom: offsets measure from the page edge or the margin box */
posHRel?: 'page' | 'margin'
/** wp:positionV relativeFrom */
posVRel?: 'page' | 'margin'
/** v:imagedata gain/blacklevel present (Word watermark washout preset) */
washout?: boolean
/** w:jc of the containing paragraph (inline images follow paragraph alignment) */
@@ -489,6 +521,8 @@ export interface ChartDisplay {
/** zip path of the chart part this model was read from */
partPath: string
kind: 'bar' | 'line' | 'pie' | 'area' | 'other'
/** bar charts: c:barDir="bar" (horizontal bars); default is column direction */
horizontal?: boolean
/** chart title; undefined when the chart has no title part (then not editable) */
title?: string
categories: string[]
@@ -546,6 +580,8 @@ export interface NewChart {
/** Editable interchange model of one table cell (type === 'table' blocks). */
export interface TableParagraph extends ParaFormat {
runs: Run[]
/** w:pStyle of the cell paragraph (style CSS: fonts/spacing reach cell content) */
styleId?: string
/** list paragraph inside the cell (w:numPr) */
list?: { kind: 'bullet' | 'ordered'; numId: string; ilvl: number }
}
@@ -590,6 +626,8 @@ export interface TableCell {
cellMarTwips?: CellMargins
/** nested tables inside this cell (shown as read-only sub-tables; bytes kept faithful by the outer table) */
nestedTables?: TableModel[]
/** anchored shapes/textboxes inside cell paragraphs (display-only; Word grows the row to hold them) */
anchoredBoxes?: TextboxDisplay[]
/** per nested table: how many cell paragraphs precede it (reading-order anchor); absent = after all paragraphs */
nestedTableAnchors?: number[]
colSpan?: number
@@ -818,6 +856,10 @@ export interface Block {
invisibleMarker?: boolean
/** display-only content of anchored textboxes (code boxes, callouts) */
textboxes?: TextboxDisplay[]
/** the anchor paragraph's own text runs next to content textboxes (display-only) */
strayRuns?: Run[]
/** w:pStyle of the anchor paragraph; styles strayRuns via data-style */
strayStyleId?: string
/** text tokens of an OMML formula, in document order */
formulaDisplay?: FormulaDisplay
/** display/edit model of an embedded chart (set on chart-labeled blocks) */
@@ -860,6 +902,8 @@ export interface Block {
/** one paragraph inside an anchored textbox */
export interface TextboxParaDisplay extends ParaFormat {
/** w:pStyle id, rendered as data-style so the document style CSS applies */
styleId?: string
runs: Run[]
}
@@ -897,6 +941,12 @@ export interface TextboxDisplay {
* This field is display-only; it is never written to OOXML.
*/
wordArtId?: string
/** text outline of imported VML WordArt (v:textpath strokecolor), display-only */
textOutline?: { colorHex: string; widthPx: number }
/** single-line content (WordArt strings never wrap) */
nowrap?: boolean
/** vertical anchoring of the text body (wps:bodyPr anchor="ctr|b"), display-only */
vAlign?: 'center' | 'bottom'
/**
* Content holds tables / content controls flattened into display lines, so
* paras do not map 1:1 onto the w:txbxContent w:p children the patch-save
@@ -924,6 +974,12 @@ export interface TextboxDisplay {
fillImageDataUrl?: string
/** tile the picture fill (a:tile) instead of stretching it */
fillTile?: boolean
/** straight connector with a real vertical extent: drawn corner-to-corner
* instead of as a level rule (flips pick the diagonal) */
lineDiag?: boolean
/** a:xfrm flipH/flipV (connector direction) */
flipH?: boolean
flipV?: boolean
}
/** Final body content decided by the editor at save time. */
@@ -970,6 +1026,13 @@ export interface StyleDisplay {
color?: string
bold?: boolean
italic?: boolean
/** Cs twins (w:bCs/w:iCs/w:szCs): the set rtl runs read instead of bold/italic/
* sizeHalfPoints (probed, no cross-fallback) — select via styleRunFormat */
boldCs?: boolean
italicCs?: boolean
sizeCsHalfPoints?: number
/** style rPr w:rtl: inherited rtl for runs without their own flag */
rtl?: boolean
underline?: boolean
strike?: boolean
font?: string
@@ -1009,6 +1072,8 @@ export interface StyleDisplay {
align?: 'left' | 'center' | 'right' | 'justify'
/** CJK-Latin/digit auto spacing from the style pPr (w:autoSpaceDE/DN) */
autoSpace?: boolean
/** style-level w:vanish (hidden text, e.g. z-TopofForm/z-BottomofForm HTML form markers) */
vanish?: boolean
}
/** display-only formatting a table style contributes (fills applied per tblLook flags) */
@@ -1057,8 +1122,9 @@ export interface StyleInfo {
display?: StyleDisplay
/** table-style rendering hints (type === 'table') */
tableDisplay?: TableStyleDisplay
/** w:pPr/w:numPr on the style — list numbering referenced via pStyle (ListBullet/ListNumber) */
numPr?: { numId: string; ilvl: number }
/** w:pPr/w:numPr on the style — list numbering referenced via pStyle (ListBullet/ListNumber);
* 'none' = explicit w:numId 0 (cancels numbering inherited via basedOn) */
numPr?: { numId: string; ilvl: number } | 'none'
/** w:default="1" — Word applies this style to every paragraph without a w:pStyle */
isDefault?: boolean
}
@@ -1194,6 +1260,8 @@ export interface ParsedDoc {
titlePg?: boolean
/** "different odd & even pages" (settings.xml w:evenAndOddHeaders) */
evenAndOddHeaders?: boolean
/** settings.xml compatSetting compatibilityMode (0 when absent; >=15 = Word 2013+ layout) */
compatibilityMode?: number
/** first-page header/footer parts (w:type="first"), null when absent */
headerFirst?: HfPartInfo | null
footerFirst?: HfPartInfo | null
+35 -2
View File
@@ -2,5 +2,38 @@
Upstream: emf-converter 2.0.2 (Apache-2.0) — https://github.com/ChristopherVR/emf-converter
`index.mjs` / `index.d.mts` are the published npm dist files, unmodified.
Local changes go in `src/metafile.ts`, never here.
`index.mjs` / `index.d.mts` are the published npm dist files, plus local WMF fixes
(marked below); wrapper-level changes still go in `src/metafile.ts`.
Local modifications to `index.mjs` (2026-08, GenOffice):
- LOGFONT16 FaceName read at offset +18 (upstream read +14, landing in the
precision/quality bytes, so every WMF font family came out empty)
- Font escapement parsed and applied (rotated text), TA_* text alignment honored
- Symbol fonts (Wingdings/Webdings/Symbol/…) remap chars to the U+F0xx PUA
- META_PATBLT filled with the current brush (PATCOPY/BLACKNESS/WHITENESS)
- META_DIBCREATEPATTERNBRUSH approximated as a solid brush (DIB average color)
- Unhandled object-creating records still claim a WMF object-table slot, keeping
SELECTOBJECT indices aligned
- EMF window→viewport mapping normalized back into canvas space: gmx/gmy/gmw/gmh
now offset by rclBounds and scale by canvas/bounds (files with
SETVIEWPORTEXTEX drew at reference-device scale — ignoring dpiScale — and
files with a non-zero bounds origin drew fully off-canvas); viewport defaults
changed to an identity window→viewport mapping to match
- META_DIBBITBLT / META_DIBSTRETCHBLT / META_STRETCHDIB implemented (upstream
dropped every WMF-embedded DIB, e.g. OLE preview icons); SRCAND/SRCPAINT/
SRCINVERT approximated with multiply/lighter/difference composites; the
bitmap-less variant is detected per MS-WMF 2.3.1.2/2.3.1.3
(RecordSize words == (RecordFunction >> 8) + 3 — an earlier local version
added the 6-byte header on top and never matched)
- WMF without a placeable header derives logical bounds from the leading
SETWINDOWORG/SETWINDOWEXT records instead of assuming 800×600
- EMR_ALPHABLEND implemented (Word 2007-era OLE icon previews draw the icon
bitmap with it): 32bpp DIB decoded with its real alpha channel (AC_SRC_ALPHA
premultiplied colors un-premultiplied), SrcConstantAlpha applied via
globalAlpha, source sub-rect scaled onto the destination
- EMF canvases replay in rclFrame space (converted to device units via
szlDevice/szlMillimeters) when rclBounds clearly disagree with the frame
(>5% per edge). Word maps the frame onto the picture extent, so a
bounds-tight canvas got stretched to the frame's aspect by the display box
(e.g. OLE preview text filling a third of a page-wide frame drew giant and
deformed); matching frames keep the established bounds mapping
+414 -19
View File
@@ -129,6 +129,7 @@ var EMR_BITBLT = 76;
var EMR_STRETCHDIBITS = 81;
var EMR_EXTCREATEFONTINDIRECTW = 82;
var EMR_EXTTEXTOUTW = 84;
var EMR_ALPHABLEND = 114;
var EMR_POLYBEZIER16 = 85;
var EMR_POLYGON16 = 86;
var EMR_POLYLINE16 = 87;
@@ -222,6 +223,14 @@ var META_EXTTEXTOUT = 2610;
var META_SAVEDC = 30;
var META_RESTOREDC = 295;
var META_POLYPOLYGON = 1336;
var META_PATBLT = 1565;
var META_DIBBITBLT = 2368;
var META_DIBSTRETCHBLT = 2881;
var META_STRETCHDIB = 3907;
var META_DIBCREATEPATTERNBRUSH = 322;
var META_CREATEPATTERNBRUSH = 505;
var META_CREATEPALETTE = 247;
var META_CREATEREGION = 1791;
var emfLog = (...args) => {
};
var emfWarn = (...args) => {
@@ -432,6 +441,69 @@ function applyFont(ctx, state, scale = 1) {
const family = mapFontFamily(state.fontFamily, state.fontFamilyMap);
ctx.font = `${italic}${weightPart}${size}px ${family}`;
}
var SYMBOL_FONT_RE = /^(wingdings|webdings|symbol$|monotype sorts|zapf ?dingbats|marlett)/i;
function mapSymbolText(family, text) {
if (!SYMBOL_FONT_RE.test((family || "").trim())) {
return text;
}
let out = "";
for (let i = 0; i < text.length; i++) {
const c = text.charCodeAt(i);
out += c >= 32 && c <= 255 ? String.fromCharCode(61440 + c) : text[i];
}
return out;
}
function dibAverageColor(view, off, end) {
try {
const hdrSize = view.getUint32(off, true);
const bitCount = view.getUint16(off + 14, true);
let r = 0, g = 0, b = 0, n = 0;
if (bitCount <= 8) {
const clrUsed = view.getUint32(off + 32, true) || 1 << bitCount;
let p = off + hdrSize;
for (let i = 0; i < clrUsed && p + 4 <= end; i++, p += 4) {
b += view.getUint8(p);
g += view.getUint8(p + 1);
r += view.getUint8(p + 2);
n++;
}
} else {
for (let p = off + hdrSize; p + 3 <= end && n < 1024; p += 3) {
b += view.getUint8(p);
g += view.getUint8(p + 1);
r += view.getUint8(p + 2);
n++;
}
}
if (!n) {
return "#c0c0c0";
}
const h = (v) => Math.round(v / n).toString(16).padStart(2, "0");
return `#${h(r)}${h(g)}${h(b)}`;
} catch {
return "#c0c0c0";
}
}
function drawWmfText(ctx, state, text, x, y) {
const mapped = mapSymbolText(state.fontFamily, text);
const align = state.textAlign || 0;
const prevAlign = ctx.textAlign;
const prevBaseline = ctx.textBaseline;
ctx.textAlign = (align & 6) === 6 ? "center" : align & 2 ? "right" : "left";
ctx.textBaseline = (align & 24) === 24 ? "alphabetic" : align & 8 ? "bottom" : "top";
const esc = state.fontEscapement || 0;
if (esc) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(-esc / 10 * Math.PI / 180);
ctx.fillText(mapped, 0, 0);
ctx.restore();
} else {
ctx.fillText(mapped, x, y);
}
ctx.textAlign = prevAlign;
ctx.textBaseline = prevBaseline;
}
function drawTextDecorations(ctx, state, x, y, width, scale = 1) {
if (!state.fontUnderline && !state.fontStrikeOut) {
return;
@@ -572,6 +644,10 @@ function parseEmfHeader(view) {
const frameBottom = view.getInt32(36, true);
const frameW = frameRight - frameLeft;
const frameH = frameBottom - frameTop;
const deviceCx = view.getInt32(72, true);
const deviceCy = view.getInt32(76, true);
const mmCx = view.getInt32(80, true);
const mmCy = view.getInt32(84, true);
return {
bounds: {
left: boundsLeft,
@@ -579,10 +655,48 @@ function parseEmfHeader(view) {
right: boundsRight,
bottom: boundsBottom
},
frameLeft,
frameTop,
frameW,
frameH
frameH,
deviceCx,
deviceCy,
mmCx,
mmCy
};
}
// Word maps rclFrame (0.01 mm) onto the declared picture extent; rclBounds is
// just the drawn area. When the two clearly disagree (e.g. text in the left
// third of a page-wide frame), a bounds-sized canvas is a tight crop that the
// display box then stretches to the frame's aspect ratio — giant deformed
// text. Convert the frame into the records' device space (szlDevice /
// szlMillimeters) and replay against it instead.
function emfFrameDeviceBounds(header) {
const { frameLeft, frameTop, frameW, frameH, deviceCx, deviceCy, mmCx, mmCy } = header;
if (!(frameW > 0 && frameH > 0 && deviceCx > 0 && deviceCy > 0 && mmCx > 0 && mmCy > 0)) {
return null;
}
const unitsPerDevX = mmCx * 100 / deviceCx;
const unitsPerDevY = mmCy * 100 / deviceCy;
return {
deviceRect: {
left: frameLeft / unitsPerDevX,
top: frameTop / unitsPerDevY,
right: (frameLeft + frameW) / unitsPerDevX,
bottom: (frameTop + frameH) / unitsPerDevY
},
// canvas size at 96 dpi (createCanvas applies dpiScale on top)
pxW: Math.max(1, Math.round(frameW / 2540 * 96)),
pxH: Math.max(1, Math.round(frameH / 2540 * 96))
};
}
// bounds match the frame within 5% per edge: keep the established bounds
// mapping (identical result, no pixel churn on well-formed files)
function emfBoundsCoverFrame(bounds, frameRect) {
const tolX = (frameRect.right - frameRect.left) * 0.05;
const tolY = (frameRect.bottom - frameRect.top) * 0.05;
return Math.abs(bounds.left - frameRect.left) <= tolX && Math.abs(bounds.right - frameRect.right) <= tolX && Math.abs(bounds.top - frameRect.top) <= tolY && Math.abs(bounds.bottom - frameRect.bottom) <= tolY;
}
function getRenderableEmfBounds(header) {
const boundsW = header.bounds.right - header.bounds.left;
const boundsH = header.bounds.bottom - header.bounds.top;
@@ -625,6 +739,34 @@ function parseWmfHeader(view) {
}
const headerSize = view.getUint16(headerOffset + 2, true) * 2;
const maxRecordSize = view.getUint32(headerOffset + 8, true) * 2;
if (headerOffset === 0) {
// No placeable header: derive the logical bounds from the leading
// SETWINDOWORG/SETWINDOWEXT records instead of a fixed 800\xD7600 guess
// (which distorted aspect ratio and size for every such file).
let off = headerSize;
let org = null;
let ext = null;
for (let i = 0; i < 64 && off + 6 <= view.byteLength && (!org || !ext); i++) {
const sizeWords = view.getUint32(off, true);
const fn = view.getUint16(off + 4, true);
if (fn === META_EOF || sizeWords < 3 || off + sizeWords * 2 > view.byteLength) {
break;
}
if (fn === META_SETWINDOWORG && !org && sizeWords >= 5) {
org = { y: view.getInt16(off + 6, true), x: view.getInt16(off + 8, true) };
}
if (fn === META_SETWINDOWEXT && !ext && sizeWords >= 5) {
ext = { cy: view.getInt16(off + 6, true), cx: view.getInt16(off + 8, true) };
}
off += sizeWords * 2;
}
if (ext && ext.cx && ext.cy) {
boundsLeft = org ? org.x : 0;
boundsTop = org ? org.y : 0;
boundsRight = boundsLeft + Math.abs(ext.cx);
boundsBottom = boundsTop + Math.abs(ext.cy);
}
}
return {
headerSize: headerOffset + headerSize,
maxRecordSize,
@@ -637,11 +779,18 @@ function parseWmfHeader(view) {
}
// src/emf-gdi-coord.ts
// Window->viewport mapping yields coordinates in the file's reference-device
// space; rclBounds is in that same device space, so the result must still be
// normalized into canvas space ((dev - bounds) * s), exactly like the
// non-mapping branch. Without this, files that SETVIEWPORTEXTEX draw at
// device scale into a dpiScale-sized canvas (or fully off-canvas when the
// bounds origin is non-zero).
function gmx(r, x) {
const wt = r.state.worldTransform;
const px = wt[0] * x + wt[4];
if (r.useMappingMode) {
return (px - r.windowOrg.x) / (r.windowExt.cx || 1) * (r.viewportExt.cx || 1) + r.viewportOrg.x;
const dev = (px - r.windowOrg.x) / (r.windowExt.cx || 1) * (r.viewportExt.cx || 1) + r.viewportOrg.x;
return (dev - r.bounds.left) * r.sx;
}
return (px - r.bounds.left) * r.sx;
}
@@ -649,21 +798,22 @@ function gmy(r, y) {
const wt = r.state.worldTransform;
const py = wt[3] * y + wt[5];
if (r.useMappingMode) {
return (py - r.windowOrg.y) / (r.windowExt.cy || 1) * (r.viewportExt.cy || 1) + r.viewportOrg.y;
const dev = (py - r.windowOrg.y) / (r.windowExt.cy || 1) * (r.viewportExt.cy || 1) + r.viewportOrg.y;
return (dev - r.bounds.top) * r.sy;
}
return (py - r.bounds.top) * r.sy;
}
function gmw(r, w) {
const pw = r.state.worldTransform[0] * w;
if (r.useMappingMode) {
return pw / (r.windowExt.cx || 1) * (r.viewportExt.cx || 1);
return pw / (r.windowExt.cx || 1) * (r.viewportExt.cx || 1) * r.sx;
}
return pw * r.sx;
}
function gmh(r, h) {
const ph = r.state.worldTransform[3] * h;
if (r.useMappingMode) {
return ph / (r.windowExt.cy || 1) * (r.viewportExt.cy || 1);
return ph / (r.windowExt.cy || 1) * (r.viewportExt.cy || 1) * r.sy;
}
return ph * r.sy;
}
@@ -1228,7 +1378,7 @@ function parseBitfieldMasks(view, bmiOffset, headerSize, compression, bitCount)
}
return { rMask, gMask, bMask, rShift, gShift, bShift, rMax, gMax, bMax };
}
function decodeUncompressedRows(view, bitsOffset, width, height, topDown, bitCount, colorTable, masks, out) {
function decodeUncompressedRows(view, bitsOffset, width, height, topDown, bitCount, colorTable, masks, out, preserveAlpha = false) {
const rowStride = Math.floor((bitCount * width + 31) / 32) * 4;
const { rMask, gMask, bMask, rShift, gShift, bShift, rMax, gMax, bMax } = masks;
for (let y = 0; y < height; y++) {
@@ -1286,14 +1436,14 @@ function decodeUncompressedRows(view, bitsOffset, width, height, topDown, bitCou
out[dstPx] = rr;
out[dstPx + 1] = gg;
out[dstPx + 2] = bb;
out[dstPx + 3] = aa === 0 ? 255 : aa;
out[dstPx + 3] = preserveAlpha ? aa : aa === 0 ? 255 : aa;
}
}
}
}
// src/emf-dib-decoder.ts
function decodeDibToImageData(view, bmiOffset, bitsOffset, bitsSize) {
function decodeDibToImageData(view, bmiOffset, bitsOffset, bitsSize, preserveAlpha = false) {
if (bmiOffset < 0 || bitsOffset < 0 || bmiOffset + 40 > view.byteLength || bitsOffset + bitsSize > view.byteLength) {
return null;
}
@@ -1384,7 +1534,8 @@ function decodeDibToImageData(view, bmiOffset, bitsOffset, bitsSize) {
bitCount,
colorTable,
masks,
out
out,
preserveAlpha
);
return new ImageData(out, width, height);
}
@@ -1516,6 +1667,81 @@ function handleStretchDibits(rCtx, offset, dataOff, recSize) {
}
return true;
}
var AC_SRC_ALPHA = 1;
function handleAlphaBlend(rCtx, offset, dataOff, recSize) {
const { ctx, view } = rCtx;
if (recSize < 108) {
return true;
}
const dstX = view.getInt32(dataOff + 16, true);
const dstY = view.getInt32(dataOff + 20, true);
const dstW = view.getInt32(dataOff + 24, true);
const dstH = view.getInt32(dataOff + 28, true);
const srcConstantAlpha = view.getUint8(dataOff + 34);
const alphaFormat = view.getUint8(dataOff + 35);
const srcX = view.getInt32(dataOff + 36, true);
const srcY = view.getInt32(dataOff + 40, true);
const offBmiSrc = view.getUint32(dataOff + 76, true);
const cbBmiSrc = view.getUint32(dataOff + 80, true);
const offBitsSrc = view.getUint32(dataOff + 84, true);
const cbBitsSrc = view.getUint32(dataOff + 88, true);
const srcW = view.getInt32(dataOff + 92, true);
const srcH = view.getInt32(dataOff + 96, true);
if (offBmiSrc <= 0 || cbBmiSrc <= 0 || offBitsSrc <= 0 || cbBitsSrc <= 0 || srcW <= 0 || srcH <= 0) {
return true;
}
const imageData = decodeDibToImageData(
view,
offset + offBmiSrc,
offset + offBitsSrc,
cbBitsSrc,
(alphaFormat & AC_SRC_ALPHA) !== 0
);
if (!imageData) {
return true;
}
if (alphaFormat & AC_SRC_ALPHA) {
const px = imageData.data;
for (let i = 0; i < px.length; i += 4) {
const a = px[i + 3];
if (a === 255) {
continue;
}
if (a === 0) {
px[i] = px[i + 1] = px[i + 2] = 0;
continue;
}
px[i] = Math.min(255, Math.round(px[i] * 255 / a));
px[i + 1] = Math.min(255, Math.round(px[i + 1] * 255 / a));
px[i + 2] = Math.min(255, Math.round(px[i + 2] * 255 / a));
}
}
const temp = createTempCanvas(imageData.width, imageData.height);
if (!temp) {
return true;
}
temp.ctx.putImageData(imageData, 0, 0);
const constAlpha = srcConstantAlpha / 255;
const prevAlpha = constAlpha < 1 ? ctx.globalAlpha : 1;
if (constAlpha < 1) {
ctx.globalAlpha = prevAlpha * constAlpha;
}
ctx.drawImage(
temp.canvas,
srcX,
srcY,
srcW,
srcH,
gmx(rCtx, dstX),
gmy(rCtx, dstY),
gmw(rCtx, dstW),
gmh(rCtx, dstH)
);
if (constAlpha < 1) {
ctx.globalAlpha = prevAlpha;
}
return true;
}
function gdiCombineClip(rCtx, shape, op) {
const { ctx } = rCtx;
if (rCtx.clipUntracked && op !== "replace") {
@@ -1655,6 +1881,8 @@ function handleEmfGdiTextBitmapRecord(rCtx, recType, offset, dataOff, recSize) {
return handleBitBlt(rCtx, offset, dataOff, recSize);
case EMR_STRETCHDIBITS:
return handleStretchDibits(rCtx, offset, dataOff, recSize);
case EMR_ALPHABLEND:
return handleAlphaBlend(rCtx, offset, dataOff, recSize);
case EMR_INTERSECTCLIPRECT:
return handleIntersectClipRect(rCtx, dataOff, recSize);
case EMR_EXTSELECTCLIPRGN:
@@ -2248,6 +2476,7 @@ function defaultState() {
fontFamily: "sans-serif",
fontUnderline: false,
fontStrikeOut: false,
fontEscapement: 0,
rop2: 13,
curX: 0,
curY: 0,
@@ -4282,7 +4511,8 @@ var GDI_NAMES = {
86: "EMR_POLYGON16",
87: "EMR_POLYLINE16",
88: "EMR_POLYBEZIERTO16",
91: "EMR_POLYPOLYGON16"
91: "EMR_POLYPOLYGON16",
114: "EMR_ALPHABLEND"
};
function replayEmfRecords(view, ctx, bounds, canvasW, canvasH, dpiScale = 1, replayOptions = {}) {
emfLog(
@@ -4306,10 +4536,12 @@ function replayEmfRecords(view, ctx, bounds, canvasW, canvasH, dpiScale = 1, rep
state: { ...defaultState(), fontFamilyMap: replayOptions.fontFamilyMap },
stateStack: [],
inPath: false,
// Defaults form an identity window->viewport mapping in device space, so
// a file that only sets some of the four keeps the non-mapping behavior.
windowOrg: { x: bounds.left, y: bounds.top },
windowExt: { cx: logicalW, cy: logicalH },
viewportOrg: { x: 0, y: 0 },
viewportExt: { cx: canvasW, cy: canvasH },
viewportOrg: { x: bounds.left, y: bounds.top },
viewportExt: { cx: logicalW, cy: logicalH },
useMappingMode: false,
clipSaveDepth: 0,
bounds,
@@ -4399,10 +4631,121 @@ function replayEmfRecords(view, ctx, bounds, canvasW, canvasH, dpiScale = 1, rep
}
// src/wmf-draw-handlers.ts
// GDI ternary raster ops approximated with canvas composites; SRCAND/SRCPAINT/
// SRCINVERT are the classic icon mask+image pairs and map well for the
// black-outside / white-outside operands they are used with.
function wmfRopComposite(rop) {
switch (rop) {
case 8913094:
return "multiply";
case 15597702:
return "lighter";
case 6684742:
return "difference";
default:
return "source-over";
}
}
function drawWmfDib(wCtx, rop, dibOff, dibEnd, xSrc, ySrc, srcW, srcH, xDst, yDst, dstW, dstH) {
const { view, ctx, coord } = wCtx;
if (dibOff + 40 > dibEnd || dibEnd > view.byteLength) {
return;
}
const hdrSize = view.getUint32(dibOff, true);
const bitCount = view.getUint16(dibOff + 14, true);
const compression = view.getUint32(dibOff + 16, true);
let paletteBytes = 0;
if (bitCount <= 8) {
const maxColors = 1 << bitCount;
paletteBytes = Math.min(view.getUint32(dibOff + 32, true) || maxColors, maxColors) * 4;
} else if (compression === 3 && hdrSize === 40) {
paletteBytes = 12;
}
const bitsOff = dibOff + hdrSize + paletteBytes;
if (bitsOff >= dibEnd) {
return;
}
const imageData = decodeDibToImageData(view, dibOff, bitsOff, dibEnd - bitsOff);
if (!imageData) {
return;
}
const temp = createTempCanvas(imageData.width, imageData.height);
if (!temp) {
return;
}
temp.ctx.putImageData(imageData, 0, 0);
// Icon DIBs may be double-height (stacked mask); the src rect crops the half
const sw = srcW > 0 ? srcW : imageData.width;
const sh = srcH > 0 ? srcH : imageData.height;
const prevGco = ctx.globalCompositeOperation;
ctx.globalCompositeOperation = wmfRopComposite(rop);
ctx.drawImage(
temp.canvas,
xSrc,
ySrc,
sw,
sh,
coord.mx(xDst),
coord.my(yDst),
coord.mw(dstW || sw),
coord.mh(dstH || sh)
);
ctx.globalCompositeOperation = prevGco;
}
function handleWmfDrawRecord(wCtx, recType, offset, dataOff, recSize) {
const { ctx, view, state, coord } = wCtx;
const { mx, my, mw, mh } = coord;
switch (recType) {
case META_DIBBITBLT:
case META_DIBSTRETCHBLT:
case META_STRETCHDIB: {
// Bitmap-less variant carries one reserved word instead of the DIB.
// MS-WMF 2.3.1.2/2.3.1.3: RecordSize (words, incl. the 3-word header)
// == (RecordFunction >> 8) + 3; recSize here is that value in bytes.
if (recSize === ((recType >> 8) + 3) * 2) {
return true;
}
const rop = view.getUint32(dataOff, true);
if (recType === META_DIBBITBLT) {
if (recSize >= 22) {
const ySrc = view.getInt16(dataOff + 4, true);
const xSrc = view.getInt16(dataOff + 6, true);
const h = view.getInt16(dataOff + 8, true);
const w = view.getInt16(dataOff + 10, true);
const yDst = view.getInt16(dataOff + 12, true);
const xDst = view.getInt16(dataOff + 14, true);
drawWmfDib(wCtx, rop, dataOff + 16, offset + recSize, xSrc, ySrc, w, h, xDst, yDst, w, h);
}
return true;
}
// META_DIBSTRETCHBLT / META_STRETCHDIB (extra ColorUsage word first)
const base = recType === META_STRETCHDIB ? dataOff + 6 : dataOff + 4;
if (base + 16 <= offset + recSize) {
const srcH = view.getInt16(base, true);
const srcW = view.getInt16(base + 2, true);
const ySrc = view.getInt16(base + 4, true);
const xSrc = view.getInt16(base + 6, true);
const dstH = view.getInt16(base + 8, true);
const dstW = view.getInt16(base + 10, true);
const yDst = view.getInt16(base + 12, true);
const xDst = view.getInt16(base + 14, true);
drawWmfDib(
wCtx,
rop,
base + 16,
offset + recSize,
xSrc,
ySrc,
srcW,
srcH,
xDst,
yDst,
dstW,
dstH
);
}
return true;
}
case META_MOVETO:
if (recSize >= 10) {
state.curY = view.getInt16(dataOff, true);
@@ -4620,7 +4963,7 @@ function handleWmfDrawRecord(wCtx, recType, offset, dataOff, recSize) {
const txCoord = view.getInt16(txOff + 2, true);
applyFont(ctx, state, Math.abs(mh(1)));
ctx.fillStyle = state.textColor;
ctx.fillText(text, mx(txCoord), my(ty2));
drawWmfText(ctx, state, text, mx(txCoord), my(ty2));
}
}
}
@@ -4643,10 +4986,31 @@ function handleWmfDrawRecord(wCtx, recType, offset, dataOff, recSize) {
}
applyFont(ctx, state, Math.abs(mh(1)));
ctx.fillStyle = state.textColor;
ctx.fillText(text, mx(txCoord), my(ty2));
drawWmfText(ctx, state, text, mx(txCoord), my(ty2));
}
}
return true;
case META_PATBLT:
if (recSize >= 18) {
// RasterOp(4) Height(2) Width(2) YLeft(2) XLeft(2)
const rop = view.getUint32(dataOff, true);
const rh2 = view.getInt16(dataOff + 4, true);
const rw2 = view.getInt16(dataOff + 6, true);
const ry = view.getInt16(dataOff + 8, true);
const rx = view.getInt16(dataOff + 10, true);
if (rop === 66) {
ctx.fillStyle = "#000000";
} else if (rop === 16711778) {
ctx.fillStyle = "#ffffff";
} else {
if (state.brushStyle === 1) {
return true;
}
applyBrush(ctx, state);
}
ctx.fillRect(mx(rx), my(ry), mw(rw2), mh(rh2));
}
return true;
default:
return false;
}
@@ -4772,11 +5136,30 @@ function replayWmfRecords(view, ctx, header, canvasW, canvasH, replayOptions = {
});
}
break;
case META_DIBCREATEPATTERNBRUSH:
// Pattern brush approximated by the DIB's average color (solid); it must still
// claim an object slot so later SELECTOBJECT indices keep lining up
objectTable.set(allocObjectSlot(), {
kind: "brush",
style: 0,
color: recSize >= 14 ? dibAverageColor(view, dataOff + 4, offset + recSize) : "#c0c0c0"
});
break;
case META_CREATEPATTERNBRUSH:
case META_CREATEPALETTE:
case META_CREATEREGION:
// Unhandled object-creating records: hold the slot or every later
// SELECTOBJECT picks the wrong pen/brush/font
objectTable.set(allocObjectSlot(), { kind: "unsupported" });
break;
case META_CREATEFONTINDIRECT:
if (recSize >= 24) {
// LOGFONT16: Height(2) Width(2) Escapement(2) Orientation(2) Weight(2)
// Italic/Underline/StrikeOut/CharSet/OutPrec/ClipPrec/Quality/PitchAndFamily(1 each)
// FaceName at +18 (not +14, which lands in the precision/quality bytes)
let family = "";
for (let i = 0; i < 32 && dataOff + 14 + i < offset + recSize; i++) {
const ch = view.getUint8(dataOff + 14 + i);
for (let i = 0; i < 32 && dataOff + 18 + i < offset + recSize; i++) {
const ch = view.getUint8(dataOff + 18 + i);
if (ch === 0) {
break;
}
@@ -4786,6 +5169,7 @@ function replayWmfRecords(view, ctx, header, canvasW, canvasH, replayOptions = {
objectTable.set(slot, {
kind: "font",
height: Math.abs(view.getInt16(dataOff, true)),
escapement: view.getInt16(dataOff + 4, true),
weight: view.getInt16(dataOff + 8, true),
italic: view.getUint8(dataOff + 10) !== 0,
underline: view.getUint8(dataOff + 11) !== 0,
@@ -4815,6 +5199,7 @@ function replayWmfRecords(view, ctx, header, canvasW, canvasH, replayOptions = {
state.fontUnderline = obj.underline;
state.fontStrikeOut = obj.strikeOut;
state.fontFamily = obj.family;
state.fontEscapement = obj.escapement || 0;
break;
}
}
@@ -4941,13 +5326,23 @@ async function convertEmfToDataUrl(buffer, options, recursionDepth = 0) {
emfLog("convertEmfToDataUrl: parseEmfHeader returned null \u2014 returning null");
return null;
}
const renderBounds = getRenderableEmfBounds(header);
let renderBounds = getRenderableEmfBounds(header);
if (!renderBounds) {
emfLog("convertEmfToDataUrl: getRenderableEmfBounds returned null \u2014 returning null");
return null;
}
const logicalW = renderBounds.right - renderBounds.left;
const logicalH = renderBounds.bottom - renderBounds.top;
let logicalW = renderBounds.right - renderBounds.left;
let logicalH = renderBounds.bottom - renderBounds.top;
const boundsW = header.bounds.right - header.bounds.left;
const frameBounds = boundsW > 0 ? emfFrameDeviceBounds(header) : null;
if (frameBounds && !emfBoundsCoverFrame(renderBounds, frameBounds.deviceRect)) {
emfLog(
`convertEmfToDataUrl: bounds disagree with frame \u2014 replaying in frame space (${frameBounds.pxW}\xD7${frameBounds.pxH}px)`
);
renderBounds = frameBounds.deviceRect;
logicalW = frameBounds.pxW;
logicalH = frameBounds.pxH;
}
emfLog(`convertEmfToDataUrl: logicalSize=${logicalW}\xD7${logicalH}`);
const setup = createCanvas(
logicalW,
+11 -2
View File
@@ -3,14 +3,23 @@ import { XMLParser } from 'fast-xml-parser'
/** preserveOrder node shape from fast-xml-parser */
export type XNode = Record<string, unknown>
export const xmlParser = new XMLParser({
const parserOptions = {
preserveOrder: true,
ignoreAttributes: false,
attributeNamePrefix: '',
trimValues: false,
parseTagValue: false,
parseAttributeValue: false,
})
} as const
export const xmlParser = new XMLParser(parserOptions)
/**
* Table XML only: deep nesting is legitimate there (POI stress files nest 5000 table
* levels, far past the default 100-tag cap). fxp parses iteratively, but callers must
* cap their own recursion when walking the result.
*/
export const deepXmlParser = new XMLParser({ ...parserOptions, maxNestedTags: 100_000 })
export function nameOf(node: XNode): string | undefined {
return Object.keys(node).find((k) => k !== ':@' && k !== '#text')
+55
View File
@@ -0,0 +1,55 @@
import JSZip from 'jszip'
const EOCD_SIG = 0x06054b50
const CENTRAL_SIG = 0x02014b50
const UNICODE_PATH_ID = 0x7075
/**
* Word resolves docx parts by the zip header file names and ignores Info-ZIP
* Unicode Path (0x7075) extra fields; JSZip honors them, so a crc-valid but
* conflicting field can shadow word/document.xml with another entry's bytes
* (POI's unicode-path corpus). Blank the field id in the central directory so
* JSZip falls back to the header names. Returns the input when nothing to do.
*/
function neutralizeUnicodePathFields(bytes: Uint8Array): Uint8Array {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
let eocd = -1
const stop = Math.max(0, bytes.length - 22 - 0xffff)
for (let i = bytes.length - 22; i >= stop; i--) {
if (view.getUint32(i, true) === EOCD_SIG) {
eocd = i
break
}
}
if (eocd < 0) return bytes
const count = view.getUint16(eocd + 10, true)
const cdOffset = view.getUint32(eocd + 16, true)
if (count === 0xffff || cdOffset === 0xffffffff) return bytes // zip64: leave as-is
let out: Uint8Array | null = null
let p = cdOffset
for (let i = 0; i < count; i++) {
if (p + 46 > bytes.length || view.getUint32(p, true) !== CENTRAL_SIG) return out ?? bytes
const nameLen = view.getUint16(p + 28, true)
const extraLen = view.getUint16(p + 30, true)
const commentLen = view.getUint16(p + 32, true)
let q = p + 46 + nameLen
const extraEnd = Math.min(q + extraLen, bytes.length)
while (q + 4 <= extraEnd) {
const fieldId = view.getUint16(q, true)
const fieldLen = view.getUint16(q + 2, true)
if (fieldId === UNICODE_PATH_ID) {
out ??= new Uint8Array(bytes)
out[q] = 0xff
out[q + 1] = 0xff
}
q += 4 + fieldLen
}
p += 46 + nameLen + extraLen + commentLen
}
return out ?? bytes
}
/** Load a docx/zip resolving part names the way Word does. */
export async function loadDocxZip(bytes: Uint8Array): Promise<JSZip> {
return JSZip.loadAsync(neutralizeUnicodePathFields(bytes))
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const TRIANGLE_ANCHOR =
'<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:posOffset>2505075</wp:posOffset></wp:positionH>' +
'<wp:positionV relativeFrom="line"><wp:posOffset>40640</wp:posOffset></wp:positionV>' +
'<wp:extent cx="589915" cy="533400"/><wp:wrapNone/>' +
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">' +
'<a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
'<wps:wsp><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="589915" cy="533400"/></a:xfrm>' +
'<a:prstGeom prst="triangle"><a:avLst/></a:prstGeom><a:solidFill><a:srgbClr val="4472C4"/></a:solidFill></wps:spPr>' +
'<wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>'
function tableXml(cellExtra: string): string {
return (
'<w:tbl><w:tblPr><w:tblW w:w="9000" w:type="dxa"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="9000"/></w:tblGrid>' +
'<w:tr><w:tc><w:tcPr/><w:p><w:r><w:t>cell text</w:t></w:r>' +
`<w:r>${cellExtra}</w:r></w:p></w:tc></w:tr></w:tbl>`
)
}
describe('anchored shapes inside table cells (tdf134277)', () => {
it('extracts the shape as a cell display box and keeps the cell text', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: tableXml(TRIANGLE_ANCHOR) }))
const cell = doc.blocks[0].table!.rows[0][0]
expect(cell.anchoredBoxes).toHaveLength(1)
expect(cell.anchoredBoxes![0].prst).toBe('triangle')
expect(cell.paras[0]).toBe('cell text')
})
it('does not duplicate a shape paired with an mc:Fallback VML twin', async () => {
const wrapped =
'<mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">' +
`<mc:Choice Requires="wps">${TRIANGLE_ANCHOR}</mc:Choice>` +
'<mc:Fallback><w:pict><v:rect xmlns:v="urn:schemas-microsoft-com:vml" style="position:absolute;width:46pt;height:42pt">' +
'<v:textbox><w:txbxContent><w:p><w:r><w:t>box text</w:t></w:r></w:p></w:txbxContent></v:textbox>' +
'</v:rect></w:pict></mc:Fallback></mc:AlternateContent>'
const doc = await parseDocx(await buildDocx({ bodyXml: tableXml(wrapped) }))
const cell = doc.blocks[0].table!.rows[0][0]
expect(cell.anchoredBoxes).toHaveLength(1)
// the fallback's txbxContent text must not leak into the cell's plain text
expect(cell.paras[0]).not.toContain('box text')
})
})
@@ -5,6 +5,7 @@ import {
buildChartWorkbookXlsxBase64,
parseChartPartXml,
parseDocx,
patchChartPartXml,
patchChartWorkbookXlsxBase64,
saveDocx,
} from '../src/index'
@@ -136,9 +137,11 @@ describe('chart embedded workbook', () => {
['Q1', 'Q2'],
[{ name: '华东', values: [100, 200] }],
)
const patched = await patchChartWorkbookXlsxBase64(original, ['A', 'B'], [
{ name: '华东', values: [999, 888] },
])
const patched = await patchChartWorkbookXlsxBase64(
original,
['A', 'B'],
[{ name: '华东', values: [999, 888] }],
)
expect(patched).toBeTruthy()
const binaryStr = atob(patched!)
const bytes = new Uint8Array(binaryStr.length)
@@ -149,3 +152,82 @@ describe('chart embedded workbook', () => {
expect(sheet).toContain('888')
})
})
describe('parseChartPartXml direction and auto title', () => {
const chartSpace = (inner: string) =>
'<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" ' +
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">' +
`<c:chart>${inner}</c:chart></c:chartSpace>`
const barPlot = (dir: string) =>
`<c:plotArea><c:barChart><c:barDir val="${dir}"/><c:ser><c:idx val="0"/>` +
'<c:val><c:numRef><c:numCache><c:pt idx="0"><c:v>3</c:v></c:pt></c:numCache></c:numRef></c:val>' +
'</c:ser></c:barChart></c:plotArea>'
it('c:barDir="bar" marks the chart as horizontal', () => {
const display = parseChartPartXml(chartSpace(barPlot('bar')), 'word/charts/chart1.xml')!
expect(display.kind).toBe('bar')
expect(display.horizontal).toBe(true)
expect(parseChartPartXml(chartSpace(barPlot('col')), 'p')!.horizontal).toBeUndefined()
})
it('text-less c:title renders the Word auto-title placeholder unless deleted', () => {
const title = '<c:title><c:overlay val="0"/></c:title>'
const kept = parseChartPartXml(
chartSpace(`${title}<c:autoTitleDeleted val="0"/>${barPlot('col')}`),
'p',
)!
expect(kept.title).toBe('Chart Title')
const deleted = parseChartPartXml(
chartSpace(`${title}<c:autoTitleDeleted val="1"/>${barPlot('col')}`),
'p',
)!
expect(deleted.title).toBeUndefined()
// CT_Boolean: a val-less element and val="true" also mean deleted
for (const form of ['<c:autoTitleDeleted/>', '<c:autoTitleDeleted val="true"/>']) {
const d = parseChartPartXml(chartSpace(`${title}${form}${barPlot('col')}`), 'p')!
expect(d.title).toBeUndefined()
}
})
it('title patches reach strRef caches and synthesize rich bodies for auto titles', () => {
const strRefTitle =
'<c:title><c:tx><c:strRef><c:f>Sheet1!$A$1</c:f>' +
'<c:strCache><c:pt idx="0"><c:v>old</c:v></c:pt></c:strCache></c:strRef></c:tx></c:title>'
const strRefXml = chartSpace(`${strRefTitle}${barPlot('col')}`)
const patchedStrRef = patchChartPartXml(strRefXml, { title: 'new title' })
expect(patchedStrRef).toContain('<c:v>new title</c:v>')
const autoXml = chartSpace(`<c:title><c:overlay val="0"/></c:title>${barPlot('col')}`)
const patchedAuto = patchChartPartXml(autoXml, { title: 'typed title' })
expect(patchedAuto).toContain('<a:t>typed title</a:t>')
expect(parseChartPartXml(patchedAuto, 'p')!.title).toBe('typed title')
// Word auto titles already carry an empty c:tx/c:rich paragraph — the run
// must land in it (CT_Title allows a single c:tx)
const emptyTx =
'<c:title><c:tx><c:rich><a:bodyPr/><a:lstStyle/><a:p>' +
'<a:endParaRPr lang="en-US"/></a:p></c:rich></c:tx></c:title>'
const patchedEmptyTx = patchChartPartXml(chartSpace(`${emptyTx}${barPlot('col')}`), {
title: 'kept single tx',
})
expect(patchedEmptyTx.match(/<c:tx>/g)).toHaveLength(1)
// cache-less strRef tx: replaced wholesale by a rich body (CT_Tx choice)
const bareStrRef = '<c:title><c:tx><c:strRef><c:f>Sheet1!$A$1</c:f></c:strRef></c:tx></c:title>'
const patchedBare = patchChartPartXml(chartSpace(`${bareStrRef}${barPlot('col')}`), {
title: 'from bare strRef',
})
expect(patchedBare.match(/<c:tx>/g)).toHaveLength(1)
expect(patchedBare).not.toContain('<c:strRef>')
expect(parseChartPartXml(patchedBare, 'p')!.title).toBe('from bare strRef')
expect(/<a:r><a:t>kept single tx<\/a:t><\/a:r><a:endParaRPr/.test(patchedEmptyTx)).toBe(true)
})
it('strRef titles read the cached c:v text, not the placeholder', () => {
const title =
'<c:title><c:tx><c:strRef><c:f>Sheet1!$A$1</c:f>' +
'<c:strCache><c:pt idx="0"><c:v>销售汇总</c:v></c:pt></c:strCache></c:strRef></c:tx></c:title>'
const display = parseChartPartXml(
chartSpace(`${title}<c:autoTitleDeleted val="0"/>${barPlot('col')}`),
'p',
)!
expect(display.title).toBe('销售汇总')
})
})
@@ -274,3 +274,50 @@ describe('comment replies/resolution (commentsExtended)', () => {
expect(ct).toContain('commentsExtended+xml')
})
})
describe('reference-only comments (bare w:commentReference, no range markers)', () => {
const refDocx = (bodyXml: string) =>
buildDocx({
bodyXml,
extraParts: [
{
path: 'word/comments.xml',
xml: COMMENTS_XML,
contentType:
'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml',
},
],
})
it('anchors on the preceding run', async () => {
const doc = await parseDocx(
await refDocx(
'<w:p><w:r><w:t>hello</w:t></w:r><w:r><w:commentReference w:id="1"/></w:r></w:p>',
),
)
expect(doc.blocks[0].runs).toEqual([{ text: 'hello', commentIds: ['1'] }])
})
it('anchors a leading reference on the following run', async () => {
const doc = await parseDocx(
await refDocx(
'<w:p><w:r><w:commentReference w:id="1"/></w:r><w:r><w:t>after</w:t></w:r></w:p>',
),
)
expect(doc.blocks[0].runs).toEqual([{ text: 'after', commentIds: ['1'] }])
})
it('keeps an empty paragraph with only a reference parseable (comment stays in the list)', async () => {
const doc = await parseDocx(
await refDocx('<w:p><w:r><w:commentReference w:id="1"/></w:r></w:p>'),
)
expect(doc.blocks[0].type).toBe('paragraph')
expect(doc.blocks[0].runs).toEqual([])
expect(doc.comments.map((c) => c.id)).toContain('1')
})
it('does not anchor a reference whose id has range markers elsewhere', async () => {
const doc = await parseDocx(await refDocx(CROSS_P_A + CROSS_P_B))
expect(doc.blocks[1].runs).toEqual([{ text: 'range closes here' }])
})
})
@@ -0,0 +1,68 @@
import { describe, expect, it } from 'vitest'
import { parseDocx, saveDocx } from '../src/index'
import type { TableModel } from '../src/types'
import { buildDocx } from './helpers/build-docx'
/** levels-deep nested table; each level holds one "Level i" paragraph (built iteratively) */
function deepTableXml(levels: number): string {
let xml = ''
for (let i = levels - 1; i >= 0; i--) {
xml =
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="3000"/></w:tblGrid>' +
`<w:tr><w:tc><w:p><w:r><w:t>Level ${i}</w:t></w:r></w:p>` +
xml +
(xml ? '<w:p/>' : '') +
'</w:tc></w:tr></w:tbl>'
}
return xml
}
function collectTexts(model: TableModel): { texts: string[]; maxDepth: number } {
const texts: string[] = []
let maxDepth = 0
const stack: Array<{ model: TableModel; depth: number }> = [{ model, depth: 1 }]
while (stack.length > 0) {
const { model: m, depth } = stack.pop()!
if (depth > maxDepth) maxDepth = depth
for (const row of m.rows)
for (const cell of row) {
for (const p of cell.paras) if (p !== '') texts.push(p)
for (let i = (cell.nestedTables ?? []).length - 1; i >= 0; i--)
stack.push({ model: cell.nestedTables![i], depth: depth + 1 })
}
}
return { texts, maxDepth }
}
describe('deeply nested tables keep their content', () => {
it('caps the modeled depth but keeps every paragraph of a 2000-level table', async () => {
const source = await buildDocx({ bodyXml: deepTableXml(2000) })
const doc = await parseDocx(source)
expect(doc.blocks[0].type).toBe('table')
const model = doc.blocks[0].table
expect(model).toBeDefined()
const { texts, maxDepth } = collectTexts(model!)
expect(texts).toEqual(Array.from({ length: 2000 }, (_, i) => `Level ${i}`))
// 8 modeled levels + 1 flattened sub-table holding everything below the cap
expect(maxDepth).toBe(9)
// beyond-cap cells are read-only remnants: the flattened sub-table has no further nesting
expect(texts.length).toBeGreaterThan(0)
// untouched deep tables still save byte-identically
const saved = await saveDocx(doc, [{ kind: 'original', docxIndex: 0 }])
expect(saved).toEqual(source)
})
it('does not flatten tables nested within the cap', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: deepTableXml(4) }))
const model = doc.blocks[0].table
expect(model).toBeDefined()
const { texts, maxDepth } = collectTexts(model!)
expect(texts).toEqual(['Level 0', 'Level 1', 'Level 2', 'Level 3'])
expect(maxDepth).toBe(4)
// true nested structure, one paragraph per level (nothing merged)
const level1 = model!.rows[0][0].nestedTables![0]
expect(model!.rows[0][0].paras).toEqual(['Level 0', ''])
expect(level1.rows[0][0].paras[0]).toBe('Level 1')
})
})
@@ -65,6 +65,27 @@ describe('parseDocx with emf media', () => {
expect(block.imageHeightPx).toBe(48)
})
it('resolves an opaque .bin part via the [Content_Types].xml fallback', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: `<w:p><w:r>${DRAWING_XML}</w:r></w:p>`,
extraRels:
'<Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.bin"/>',
binaryParts: [
{
path: 'word/media/image1.bin',
base64: EMF_BASE64,
extension: 'bin',
contentType: 'image/x-emf',
},
],
}),
)
const block = doc.blocks[0]
expect(block.type).toBe('image')
expect(block.imageDataUrl).toBe('data:image/png;base64,EMFPNG')
})
it('converts an emf picture inside a table cell', async () => {
const doc = await parseDocx(
await buildDocx({
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import { generateParagraphXml, generateTocFieldXml, parseDocx } from '../src/index'
import type { GenerateContext } from '../src/index'
import { buildDocx } from './helpers/build-docx'
// TOC entry paragraph as Word writes it: TOC field begin + hyperlink entry
@@ -150,3 +151,108 @@ describe('HYPERLINK field folding', () => {
expect(doc.blocks[0].type).toBe('passthrough')
})
})
// Legacy FORMCHECKBOX form field as Word writes it (POI checkboxes.docx):
// ffData on the begin fldChar defines the box; there is no cached result.
const checkboxParagraph = (state: string) =>
'<w:p><w:r><w:t xml:space="preserve">item: </w:t></w:r>' +
`<w:r><w:fldChar w:fldCharType="begin"><w:ffData><w:name w:val="Check1"/><w:enabled/><w:checkBox><w:sizeAuto/>${state}</w:checkBox></w:ffData></w:fldChar></w:r>` +
'<w:r><w:instrText xml:space="preserve"> FORMCHECKBOX </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
describe('FORMCHECKBOX form fields', () => {
it('unchecked box folds into an editable run with the empty-box glyph', async () => {
const doc = await parseDocx(
await buildDocx({ bodyXml: checkboxParagraph('<w:default w:val="0"/>') }),
)
expect(doc.blocks[0].type).toBe('paragraph')
expect(doc.blocks[0].runs?.map((r) => r.text)).toEqual(['item: ', '☐'])
})
it('checked state comes from w:checked (wins over w:default)', async () => {
const doc = await parseDocx(
await buildDocx({ bodyXml: checkboxParagraph('<w:default w:val="0"/><w:checked/>') }),
)
expect(doc.blocks[0].runs?.[1]).toMatchObject({ text: '☒', instrField: 'FORMCHECKBOX' })
})
it('regeneration writes the ffData begin run back verbatim with no cached glyph', async () => {
const doc = await parseDocx(
await buildDocx({ bodyXml: checkboxParagraph('<w:checked w:val="1"/>') }),
)
const run = doc.blocks[0].runs![1]
const ctx: GenerateContext = {
headingStyleIds: new Map(),
allocateHyperlinkRel: () => 'rId1',
}
const xml = generateParagraphXml({ type: 'paragraph', runs: doc.blocks[0].runs! }, ctx)
expect(xml).toContain('<w:ffData>')
expect(xml).toContain('FORMCHECKBOX')
expect(xml).not.toContain('☒')
expect(run.fldBeginXml).toContain('<w:checkBox>')
})
it('text typed beside the glyph survives as a plain run after the field', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: checkboxParagraph('<w:checked/>') }))
const run = { ...doc.blocks[0].runs![1], text: '\u2612yes' }
const ctx: GenerateContext = {
headingStyleIds: new Map(),
allocateHyperlinkRel: () => 'rId1',
}
const xml = generateParagraphXml({ type: 'paragraph', runs: [run] }, ctx)
expect(xml).toContain('<w:ffData>')
expect(xml).not.toContain('\u2612')
expect(/<w:fldChar w:fldCharType="end"\/><\/w:r>.*<w:t[^>]*>yes<\/w:t>/s.test(xml)).toBe(true)
})
it('editor-merged identical checkboxes regenerate one field per glyph', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: checkboxParagraph('<w:checked/>') }))
const run = { ...doc.blocks[0].runs![1], text: '\u2612\u2612' }
const ctx: GenerateContext = {
headingStyleIds: new Map(),
allocateHyperlinkRel: () => 'rId1',
}
const xml = generateParagraphXml({ type: 'paragraph', runs: [run] }, ctx)
expect(xml.match(/<w:ffData>/g)).toHaveLength(2)
expect(xml.match(/FORMCHECKBOX/g)).toHaveLength(2)
expect(xml).not.toContain('\u2612')
})
it('an in-editor glyph flip lands in w:checked on save', async () => {
const doc = await parseDocx(
await buildDocx({ bodyXml: checkboxParagraph('<w:checked w:val="1"/>') }),
)
const run = { ...doc.blocks[0].runs![1], text: '\u2610' }
const ctx: GenerateContext = {
headingStyleIds: new Map(),
allocateHyperlinkRel: () => 'rId1',
}
const xml = generateParagraphXml({ type: 'paragraph', runs: [run] }, ctx)
expect(xml).toContain('<w:checked w:val="0"/>')
expect(xml).not.toContain('<w:checked w:val="1"/>')
})
it('replacing the glyph with text deletes the form field, like Word', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: checkboxParagraph('<w:checked/>') }))
const run = { ...doc.blocks[0].runs![1], text: 'replaced' }
const ctx: GenerateContext = {
headingStyleIds: new Map(),
allocateHyperlinkRel: () => 'rId1',
}
const xml = generateParagraphXml({ type: 'paragraph', runs: [run] }, ctx)
expect(xml).not.toContain('<w:ffData>')
expect(xml).not.toContain('FORMCHECKBOX')
expect(xml).toContain('>replaced<')
})
it('FORMCHECKBOX without a w:checkBox definition stays on the passthrough path', async () => {
const bodyXml =
'<w:p><w:r><w:fldChar w:fldCharType="begin"><w:ffData><w:name w:val="X"/></w:ffData></w:fldChar></w:r>' +
'<w:r><w:instrText xml:space="preserve"> FORMCHECKBOX </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
expect(doc.blocks[0].type).toBe('passthrough')
})
})
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -164,6 +164,35 @@ describe('rich header / footer', () => {
])
})
it('w:framePr xAlign surfaces as frameXAlign (POI WordWithAttachments page number frame)', async () => {
const HEADER =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:p><w:pPr><w:framePr w:wrap="around" w:vAnchor="text" w:hAnchor="margin" w:xAlign="right" w:y="1"/></w:pPr>' +
'<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="end"/></w:r></w:p>' +
'<w:p><w:r><w:t>Страница 1</w:t></w:r></w:p>' +
'</w:hdr>'
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>body</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: HEADER,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
},
],
sectPrExtra: '<w:headerReference w:type="default" r:id="rId61"/>',
})
const parsed = await parseDocx(bytes)
expect(parsed.headerParas![0].frameXAlign).toBe('right')
expect(parsed.headerParas![0].runs.map((r) => r.text).join('')).toBe(PAGE_MARK)
expect(parsed.headerParas![1].frameXAlign).toBeUndefined()
})
it('w:ptab absolute tabs surface as \\t runs with their alignments (POI ThreeColHead)', async () => {
const HEADER =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
@@ -376,8 +405,9 @@ describe('surgical header rewrite (real Word headers carry tables/logos)', () =>
expect(paras).toHaveLength(2)
const row = paras[0]
expect(row.cells).toHaveLength(2)
expect(row.cells![0].runs[0]).toMatchObject({ text: 'ACME 公司', bold: true })
expect(row.cells![1].runs[0]).toMatchObject({ text: 'Logo 占位' })
expect(row.cells![0].paras).toHaveLength(1)
expect(row.cells![0].paras[0][0]).toMatchObject({ text: 'ACME 公司', bold: true })
expect(row.cells![1].paras[0][0]).toMatchObject({ text: 'Logo 占位' })
expect(row.cells!.map((c) => Math.round(c.widthPct!))).toEqual([50, 50])
expect(row.cells![0].fill).toBe('1F3864')
expect(row.cells![1].fill).toBeUndefined()
@@ -386,6 +416,39 @@ describe('surgical header rewrite (real Word headers carry tables/logos)', () =>
expect(parsed.headerText).toBe('ACME 公司 Logo 占位 公司内部资料')
})
it('keeps every cell paragraph as its own line (two-paragraph title cell, empty shaded cell)', async () => {
const twoParaTbl = HEADER_TBL.replace(
'<w:p><w:r><w:t>Logo 占位</w:t></w:r></w:p>',
'<w:p><w:r><w:t>Title line 1</w:t></w:r></w:p><w:p><w:r><w:t>Title line 2</w:t></w:r></w:p>',
).replace('<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>ACME 公司</w:t></w:r></w:p>', '<w:p/>')
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:
XML_DECL +
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
twoParaTbl +
'</w:hdr>',
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
},
],
sectPrExtra: '<w:headerReference w:type="default" r:id="rId60"/>',
})
const row = (await parseDocx(bytes)).headerParas![0]
// the shaded cell keeps its empty paragraph (it must still reserve a line/fill)
expect(row.cells![0].paras).toEqual([[]])
expect(row.cells![0].fill).toBe('1F3864')
expect(row.cells![1].paras.map((rs) => rs.map((r) => r.text).join(''))).toEqual([
'Title line 1',
'Title line 2',
])
})
it('saving paras that include a cells paragraph keeps the table bytes and never duplicates them', async () => {
const { parsed, saveBlocks } = await richHeaderDocx()
const saved = await saveDocx(parsed, saveBlocks, {
@@ -79,6 +79,46 @@ describe('header/footer images (display-only Logo)', () => {
expect(doc.headerImages![0].align).toBe('right')
})
it('anchored image reads behindDoc and page-relative posOffsets (picture watermark)', async () => {
const headerXml = HEADER_XML.replace(
'<wp:inline distT="0" distB="0" distL="0" distR="0">' +
'<wp:extent cx="381000" cy="190500"/>',
'<wp:anchor behindDoc="1" locked="0" layoutInCell="1" allowOverlap="1">' +
'<wp:positionH relativeFrom="page"><wp:posOffset>190500</wp:posOffset></wp:positionH>' +
'<wp:positionV relativeFrom="page"><wp:posOffset>-95250</wp:posOffset></wp:positionV>' +
'<wp:extent cx="381000" cy="190500"/>',
).replace('</wp:inline>', '</wp:anchor>')
const doc = await parseDocx(await buildHeaderLogoDocx(headerXml))
expect(doc.headerImages).toHaveLength(1)
const img = doc.headerImages![0]
expect(img.floating).toBe(true)
expect(img.behind).toBe(true)
expect(img.posXPx).toBe(20)
expect(img.posYPx).toBe(-10)
expect(img.posHRel).toBe('page')
expect(img.posVRel).toBe('page')
expect(img.posH).toBeUndefined()
expect(img.posV).toBeUndefined()
})
it('anchored image maps wp:align to the alignment fields (margin-relative)', async () => {
const headerXml = HEADER_XML.replace(
'<wp:inline distT="0" distB="0" distL="0" distR="0">' +
'<wp:extent cx="381000" cy="190500"/>',
'<wp:anchor behindDoc="0">' +
'<wp:positionH relativeFrom="margin"><wp:align>center</wp:align></wp:positionH>' +
'<wp:positionV relativeFrom="margin"><wp:align>bottom</wp:align></wp:positionV>' +
'<wp:extent cx="381000" cy="190500"/>',
).replace('</wp:inline>', '</wp:anchor>')
const img = (await parseDocx(await buildHeaderLogoDocx(headerXml))).headerImages![0]
expect(img.floating).toBe(true)
expect(img.behind).toBeUndefined()
expect(img.posH).toBe('center')
expect(img.posV).toBe('bottom')
expect(img.posXPx).toBeUndefined()
expect(img.posYPx).toBeUndefined()
})
it('AlternateContent picks the first blip whose media resolves (mac PDF Choice → PNG Fallback)', async () => {
// rId9 is unresolvable (missing media part); the PNG fallback must be used
const headerXml = HEADER_XML.replace(
@@ -93,3 +133,97 @@ describe('header/footer images (display-only Logo)', () => {
expect(doc.headerImages![0].dataUrl.startsWith('data:image/png;base64,')).toBe(true)
})
})
describe('layout-table cell images (header logo in a w:tbl cell)', () => {
const INLINE_LOGO =
'<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>'
const tableHeaderXml = (cell1Extra = '') =>
'<?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:tbl><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="6000"/></w:tblGrid><w:tr>' +
`<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr><w:p>${INLINE_LOGO}${cell1Extra}</w:p></w:tc>` +
'<w:tc><w:tcPr><w:tcW w:w="6000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>Title</w:t></w:r></w:p></w:tc>' +
'</w:tr></w:tbl></w:hdr>'
it('inline cell picture becomes a cell run image, not a part-level strip image', async () => {
const doc = await parseDocx(await buildHeaderLogoDocx(tableHeaderXml()))
expect(doc.headerImages ?? []).toHaveLength(0)
const row = doc.headerParas!.find((p) => p.cells)
expect(row).toBeDefined()
const img = row!.cells![0].paras[0][0].image
expect(img?.dataUrl.startsWith('data:image/png;base64,')).toBe(true)
expect(img?.widthPx).toBe(40)
expect(img?.heightPx).toBe(20)
// an image-only row still enters the model
expect(row!.cells![1].paras[0][0].text).toBe('Title')
})
it('anchored picture in a cell stays part-level (floating), not a cell run', async () => {
const anchored = INLINE_LOGO.replace(
'<wp:inline distT="0" distB="0" distL="0" distR="0">',
'<wp:anchor behindDoc="1">' +
'<wp:positionH relativeFrom="page"><wp:posOffset>190500</wp:posOffset></wp:positionH>' +
'<wp:positionV relativeFrom="page"><wp:posOffset>190500</wp:posOffset></wp:positionV>',
).replace('</wp:inline>', '</wp:anchor>')
const doc = await parseDocx(await buildHeaderLogoDocx(tableHeaderXml(anchored)))
expect(doc.headerImages).toHaveLength(1)
expect(doc.headerImages![0].floating).toBe(true)
const row = doc.headerParas!.find((p) => p.cells)!
// only the inline logo remains a cell run
const cellImages = row.cells![0].paras.flat().filter((r) => r.image)
expect(cellImages).toHaveLength(1)
expect(cellImages[0].image!.xml.includes('<wp:inline')).toBe(true)
})
it('inline picture in a nested table rides its cell run (not duplicated part-level)', async () => {
const headerXml = tableHeaderXml().replace(
`<w:p>${INLINE_LOGO}</w:p>`,
'<w:tbl><w:tblGrid><w:gridCol w:w="1500"/></w:tblGrid><w:tr>' +
`<w:tc><w:tcPr><w:tcW w:w="1500" w:type="dxa"/></w:tcPr><w:p>${INLINE_LOGO}</w:p></w:tc>` +
'</w:tr></w:tbl><w:p/>',
)
const doc = await parseDocx(await buildHeaderLogoDocx(headerXml))
expect(doc.headerImages ?? []).toHaveLength(0)
const row = doc.headerParas!.find((p) => p.cells)!
const cellImages = row.cells![0].paras.flat().filter((r) => r.image)
expect(cellImages).toHaveLength(1)
expect(cellImages[0].image!.xml.includes('<wp:inline')).toBe(true)
})
it('run with both text and an anchored drawing keeps its text as a cell run', async () => {
const anchored = INLINE_LOGO.replace('<w:r><w:drawing>', '<w:r><w:t>Ref</w:t><w:drawing>')
.replace(
'<wp:inline distT="0" distB="0" distL="0" distR="0">',
'<wp:anchor behindDoc="0">' +
'<wp:positionH relativeFrom="page"><wp:posOffset>190500</wp:posOffset></wp:positionH>' +
'<wp:positionV relativeFrom="page"><wp:posOffset>190500</wp:posOffset></wp:positionV>',
)
.replace('</wp:inline>', '</wp:anchor>')
const doc = await parseDocx(
await buildHeaderLogoDocx(tableHeaderXml().replace(INLINE_LOGO, anchored)),
)
expect(doc.headerImages).toHaveLength(1)
const row = doc.headerParas!.find((p) => p.cells)!
const runs = row.cells![0].paras.flat()
expect(runs.map((r) => r.text).join('')).toBe('Ref')
expect(runs.some((r) => r.image)).toBe(false)
})
it('untouched round-trip of a table header stays byte-identical', async () => {
const bytes = await buildHeaderLogoDocx(tableHeaderXml())
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)
})
})
+200 -1
View File
@@ -1,6 +1,6 @@
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import { PAGE_MARK, parseDocx, saveDocx } from '../src/index'
import { PAGE_MARK, parseDocx, saveDocx, type HfParagraph } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const BODY = '<w:p><w:r><w:t>正文</w:t></w:r></w:p>'
@@ -98,6 +98,49 @@ describe('first-page / even-page headers & footers', () => {
expect(await zipText(off, 'word/document.xml')).not.toContain('<w:titlePg/>')
})
it('parses even-header table cells with one line per cell paragraph (same as default)', async () => {
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const hdrXml = (tblCells: string) =>
XML_DECL +
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="500"/><w:gridCol w:w="7500"/></w:tblGrid>' +
`<w:tr>${tblCells}</w:tr></w:tbl></w:hdr>`
const cells =
'<w:tc><w:tcPr><w:tcW w:w="500" w:type="dxa"/><w:shd w:val="clear" w:fill="C00000"/></w:tcPr><w:p/></w:tc>' +
'<w:tc><w:tcPr><w:tcW w:w="7500" w:type="dxa"/></w:tcPr>' +
'<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>Title line</w:t></w:r></w:p>' +
'<w:p><w:r><w:t>Subtitle line</w:t></w:r></w:p></w:tc>'
const headerType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml'
const bytes = await buildDocx({
bodyXml: BODY,
extraRels:
'<Relationship Id="rId60" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>' +
'<Relationship Id="rId61" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header2.xml"/>',
extraParts: [
{ path: 'word/header1.xml', xml: hdrXml(cells), contentType: headerType },
{ path: 'word/header2.xml', xml: hdrXml(cells), contentType: headerType },
],
sectPrExtra:
'<w:headerReference w:type="default" r:id="rId60"/>' +
'<w:headerReference w:type="even" r:id="rId61"/>',
})
const parsed = await parseDocx(bytes)
const cellShape = (row: HfParagraph) =>
row.cells!.map((c) => ({
fill: c.fill,
texts: c.paras.map((rs) => rs.map((r) => r.text).join('')),
}))
const evenRow = parsed.headerEven!.paras[0]
expect(cellShape(evenRow)).toEqual([
{ fill: 'C00000', texts: [''] },
{ fill: undefined, texts: ['Title line', 'Subtitle line'] },
])
expect(cellShape(evenRow)).toEqual(cellShape(parsed.headerParas![0]))
expect(evenRow.cells![1].paras[0][0]).toMatchObject({ text: 'Title line', bold: true })
})
it('keeps titlePg before w:docGrid in schema order', async () => {
const source = await buildDocx({ bodyXml: BODY })
// inject a docGrid into the trailing sectPr
@@ -114,3 +157,159 @@ describe('first-page / even-page headers & footers', () => {
expect(out.indexOf('<w:titlePg/>')).toBeLessThan(out.indexOf('<w:docGrid'))
})
})
const HEADER_TYPE = 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml'
const FOOTER_TYPE = 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml'
const SETTINGS_TYPE = 'application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml'
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
const W_NS = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'
const hdrPart = (inner: string) => `${XML_DECL}<w:hdr ${W_NS}>${inner}</w:hdr>`
const ftrPart = (inner: string) => `${XML_DECL}<w:ftr ${W_NS}>${inner}</w:ftr>`
const settingsPart = (inner: string) => `${XML_DECL}<w:settings ${W_NS}>${inner}</w:settings>`
describe('non-schema and non-self-closing variants (POI corpus)', () => {
it('treats w:type="odd" header/footer references as the default part', async () => {
const bytes = await buildDocx({
bodyXml: BODY,
extraRels:
'<Relationship Id="rId70" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>' +
'<Relationship Id="rId71" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header2.xml"/>',
extraParts: [
{
path: 'word/header1.xml',
xml: hdrPart('<w:p><w:r><w:t>EVEN_PAGE_HEADER</w:t></w:r></w:p>'),
contentType: HEADER_TYPE,
},
{
path: 'word/header2.xml',
xml: hdrPart('<w:p><w:r><w:t>ODD_PAGE_HEADER</w:t></w:r></w:p>'),
contentType: HEADER_TYPE,
},
],
sectPrExtra:
'<w:headerReference w:type="even" r:id="rId70"/>' +
'<w:headerReference w:type="odd" r:id="rId71"/>',
})
const parsed = await parseDocx(bytes)
expect(parsed.headerText).toBe('ODD_PAGE_HEADER')
expect(parsed.headerEven?.text).toBe('EVEN_PAGE_HEADER')
// editing the default header rewrites the odd part instead of adding a duplicate reference
const saved = await saveDocx(parsed, [{ kind: 'original', docxIndex: 0 }], {
header: { text: 'EDITED_DEFAULT' },
})
expect((await zipText(saved, 'word/document.xml'))!.match(/<w:headerReference/g)).toHaveLength(
2,
)
expect(await zipText(saved, 'word/header2.xml')).toContain('EDITED_DEFAULT')
expect((await parseDocx(saved)).headerText).toBe('EDITED_DEFAULT')
})
it('reads evenAndOddHeaders and titlePg written as paired tags or with w:val', async () => {
const build = (settingsXml: string, titlePgTag: string) =>
buildDocx({
bodyXml: BODY,
sectPrExtra: titlePgTag,
extraParts: [
{ path: 'word/settings.xml', xml: settingsPart(settingsXml), contentType: SETTINGS_TYPE },
],
})
const on = await parseDocx(
await build(
'<w:evenAndOddHeaders></w:evenAndOddHeaders>',
'<w:titlePg w:val="true"></w:titlePg>',
),
)
expect(on.evenAndOddHeaders).toBe(true)
expect(on.titlePg).toBe(true)
const off = await parseDocx(
await build('<w:evenAndOddHeaders w:val="false"/>', '<w:titlePg w:val="0"/>'),
)
expect(off.evenAndOddHeaders).toBe(false)
expect(off.titlePg).toBe(false)
})
it('flattens nested layout tables into their cell (banner shading and text kept)', async () => {
// banner header: outer cell holds a nested single-cell table carrying the
// fill and the centered title, followed by the mandatory empty paragraph
const footerXml = ftrPart(
'<w:tbl><w:tblGrid><w:gridCol w:w="8000"/><w:gridCol w:w="2000"/></w:tblGrid><w:tr>' +
'<w:tc><w:tcPr><w:tcW w:w="8000" w:type="dxa"/></w:tcPr>' +
'<w:tbl><w:tblGrid><w:gridCol w:w="8000"/></w:tblGrid><w:tr>' +
'<w:tc><w:tcPr><w:tcW w:w="8000" w:type="dxa"/><w:shd w:val="clear" w:fill="000066"/></w:tcPr>' +
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>Banner title</w:t></w:r></w:p>' +
'</w:tc></w:tr></w:tbl><w:p/></w:tc>' +
'<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr><w:p/></w:tc>' +
'</w:tr></w:tbl>',
)
const bytes = await buildDocx({
bodyXml: BODY,
extraRels:
'<Relationship Id="rId72" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/>',
extraParts: [{ path: 'word/footer1.xml', xml: footerXml, contentType: FOOTER_TYPE }],
sectPrExtra: '<w:footerReference w:type="default" r:id="rId72"/>',
})
const parsed = await parseDocx(bytes)
const row = parsed.footerParas![0]
expect(row.cells![0]).toMatchObject({ fill: '000066', align: 'center' })
// nested cell text kept; the trailing empty paragraph after the nested table is trimmed
expect(row.cells![0].paras.map((rs) => rs.map((r) => r.text).join(''))).toEqual([
'Banner title',
])
expect(parsed.footerText).toBe('Banner title')
})
it('emits a floating table (w:tblpPr) after its anchor paragraph, matching Word order', async () => {
const footerXml = ftrPart(
'<w:tbl><w:tblPr><w:tblpPr w:vertAnchor="text" w:tblpY="1"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="9000"/></w:tblGrid><w:tr>' +
'<w:tc><w:tcPr><w:tcW w:w="9000" w:type="dxa"/></w:tcPr>' +
'<w:p><w:r><w:t>Page band</w:t></w:r></w:p></w:tc>' +
'</w:tr></w:tbl>' +
'<w:p><w:r><w:t>Simple footer text</w:t></w:r></w:p>',
)
const bytes = await buildDocx({
bodyXml: BODY,
extraRels:
'<Relationship Id="rId73" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/>',
extraParts: [{ path: 'word/footer1.xml', xml: footerXml, contentType: FOOTER_TYPE }],
sectPrExtra: '<w:footerReference w:type="default" r:id="rId73"/>',
})
const parsed = await parseDocx(bytes)
const paras = parsed.footerParas!
expect(paras[0].runs.map((r) => r.text).join('')).toBe('Simple footer text')
expect(paras[1].cells![0].paras[0][0].text).toBe('Page band')
})
})
describe('header style-inherited rtl', () => {
it('hf runs pick the Cs property set when their paragraph style sets w:rtl', async () => {
const headerXml =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:p><w:pPr><w:pStyle w:val="HeaderAr"/></w:pPr>' +
'<w:r><w:rPr><w:bCs/><w:szCs w:val="36"/><w:sz w:val="20"/></w:rPr><w:t>مرحبا</w:t></w:r>' +
'</w:p></w:hdr>'
const source = await buildDocx({
bodyXml: BODY,
extraStylesXml:
'<w:style w:type="paragraph" w:styleId="HeaderAr"><w:name w:val="Header Ar"/>' +
'<w:basedOn w:val="Normal"/><w:rPr><w:rtl/></w:rPr></w:style>',
extraRels:
'<Relationship Id="rId21" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
sectPrExtra: '<w:headerReference w:type="default" r:id="rId21"/>',
extraParts: [
{
path: 'word/header1.xml',
xml: headerXml,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
},
],
})
const parsed = await parseDocx(source)
const run = parsed.headerParas![0].runs[0]
// style rtl reaches hf runs: szCs/bCs win over sz (cs property set)
expect(run).toMatchObject({ text: 'مرحبا', cs: true, bold: true, sizeHalfPoints: 36 })
})
})
@@ -36,9 +36,36 @@ describe('text + inline image mixed paragraphs', () => {
expect(doc.blocks[0].imageDataUrl).toMatch(/^data:image\/png;base64,/)
})
it('an anchored picture with stray text keeps the image-block treatment', async () => {
const bodyXml = `<w:p><w:r><w:t>caption</w:t></w:r>${ANCHORED_IMAGE_RUN}</w:p>`
it('an anchored picture sharing the paragraph with text keeps the text', async () => {
const bodyXml = `<w:p>${ANCHORED_IMAGE_RUN}<w:r><w:t>Lorem ipsum body text</w:t></w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
const block = doc.blocks[0]
expect(block.type).toBe('paragraph')
expect(block.runs!.map((r) => r.text).join('')).toBe('Lorem ipsum body text')
const imageRun = block.runs!.find((r) => r.image)
expect(imageRun?.image?.dataUrl).toMatch(/^data:image\/png;base64,/)
// no wrap element on the anchor = in front of text
expect(imageRun?.image?.wrap).toBe('front')
})
it('carries the anchor posOffset on the run image', async () => {
const anchored = ANCHORED_IMAGE_RUN.replace(
'<wp:extent',
'<wp:positionH relativeFrom="column"><wp:posOffset>1882747</wp:posOffset></wp:positionH>' +
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>-104609</wp:posOffset></wp:positionV>' +
'<wp:extent',
)
const bodyXml = `<w:p>${anchored}<w:r><w:t>wrapped text</w:t></w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
const imageRun = doc.blocks[0].runs!.find((r) => r.image)
expect(imageRun?.image?.offsetXEmu).toBe(1882747)
expect(imageRun?.image?.offsetYEmu).toBe(-104609)
})
it('an anchored picture without text is still an image block', async () => {
const bodyXml = `<w:p>${ANCHORED_IMAGE_RUN}</w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
expect(doc.blocks[0].type).toBe('image')
expect(doc.blocks[0].imageDataUrl).toMatch(/^data:image\/png;base64,/)
})
})
@@ -41,4 +41,17 @@ describe('linked (external) pictures', () => {
// still protected: saving must keep the original field XML byte-identical
expect(block.originalXml).toContain('INCLUDEPICTURE')
})
it('keeps the text visible when INCLUDEPICTURE shares the paragraph with text', async () => {
const bodyXml = INCLUDEPICTURE_PARAGRAPH.replace(
'<w:p>',
'<w:p><w:r><w:t>Company logo: </w:t></w:r>',
)
const doc = await parseDocx(await buildDocx({ bodyXml, extraRels: IMAGE_REL }))
const block = doc.blocks[0]
// the field passthrough keeps the text instead of an image block dropping it
expect(block.type).toBe('passthrough')
expect(block.previewText).toContain('Company logo:')
expect(block.originalXml).toContain('INCLUDEPICTURE')
})
})
@@ -0,0 +1,300 @@
/**
* Replay-level regression tests for the vendored emf-converter, driven by real
* metafile bytes from the POI corpus:
* - wrench.emf (61_VariousPictures): SETWINDOWEXTEX/SETVIEWPORTEXTEX mapping
* with a non-zero, negative-Y rclBounds origin — used to draw fully
* off-canvas (blank image).
* - ole-icon.wmf (91_drawing): OLE preview icon drawn with two
* META_DIBSTRETCHBLT records (AND mask + XOR color) — used to be dropped.
* Node has no canvas, so OffscreenCanvas/ImageData/FileReader are stubbed with
* a recording 2D context and the draw calls are asserted geometrically.
*/
import { readFileSync } from 'node:fs'
import { gzipSync } from 'node:zlib'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { convertEmfToDataUrl, convertWmfToDataUrl } from '../src/vendor/emf-converter/index.mjs'
import { isMetafileMime, metafileToDataUrl } from '../src/metafile'
interface Call {
method: string
args: unknown[]
}
const canvases: FakeOffscreenCanvas[] = []
let calls: Call[] = []
function makeRecordingCtx(canvas: FakeOffscreenCanvas) {
const props: Record<string | symbol, unknown> = {
canvas,
globalCompositeOperation: 'source-over',
}
const fns = new Map<string, (...args: unknown[]) => unknown>()
return new Proxy(props, {
get(target, prop) {
if (prop in target) return target[prop]
const name = String(prop)
let fn = fns.get(name)
if (!fn) {
fn = (...args: unknown[]) => {
calls.push({ method: name, args })
if (name === 'measureText') return { width: 10 }
return undefined
}
fns.set(name, fn)
}
return fn
},
set(target, prop, value) {
target[prop] = value
if (prop === 'globalCompositeOperation') {
calls.push({ method: 'set:globalCompositeOperation', args: [value] })
}
return true
},
})
}
class FakeOffscreenCanvas {
width: number
height: number
private ctx: ReturnType<typeof makeRecordingCtx> | null = null
constructor(width: number, height: number) {
this.width = width
this.height = height
canvases.push(this)
}
getContext(type: string) {
if (type !== '2d') return null
return (this.ctx ??= makeRecordingCtx(this))
}
convertToBlob() {
return Promise.resolve(
new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: 'image/png' }),
)
}
}
class FakeImageData {
data: Uint8ClampedArray
width: number
height: number
constructor(data: Uint8ClampedArray, width: number, height: number) {
this.data = data
this.width = width
this.height = height
}
}
class FakeFileReader {
result: string | null = null
onload: (() => void) | null = null
onerror: (() => void) | null = null
error: Error | null = null
readAsDataURL(blob: Blob) {
void blob.arrayBuffer().then((buf) => {
this.result = `data:${blob.type};base64,${Buffer.from(buf).toString('base64')}`
this.onload?.()
})
}
}
const globals = globalThis as Record<string, unknown>
const saved: Record<string, unknown> = {}
beforeAll(() => {
for (const [key, value] of Object.entries({
OffscreenCanvas: FakeOffscreenCanvas,
ImageData: FakeImageData,
FileReader: FakeFileReader,
})) {
saved[key] = globals[key]
globals[key] = value
}
})
afterAll(() => {
for (const [key, value] of Object.entries(saved)) {
if (value === undefined) delete globals[key]
else globals[key] = value
}
})
function reset() {
canvases.length = 0
calls = []
}
function loadFixture(name: string): ArrayBuffer {
const bytes = readFileSync(new URL(`./fixtures/${name}`, import.meta.url))
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
}
function pathPoints(): Array<{ x: number; y: number }> {
return calls
.filter((c) => c.method === 'moveTo' || c.method === 'lineTo')
.map((c) => ({ x: c.args[0] as number, y: c.args[1] as number }))
}
describe('EMF window/viewport mapping (wrench.emf)', () => {
it('draws the full figure inside the canvas at dpiScale', async () => {
reset()
const result = await convertEmfToDataUrl(loadFixture('wrench.emf'), { dpiScale: 2 })
expect(result).toMatch(/^data:image\/png;base64,/)
// bounds (300,-616)→(490,-501): logical 190×115, canvas 380×230
expect(canvases[0]?.width).toBe(380)
expect(canvases[0]?.height).toBe(230)
const pts = pathPoints()
expect(pts.length).toBeGreaterThan(100)
for (const { x, y } of pts) {
expect(x).toBeGreaterThanOrEqual(-1)
expect(x).toBeLessThanOrEqual(381)
expect(y).toBeGreaterThanOrEqual(-1)
expect(y).toBeLessThanOrEqual(231)
}
const xs = pts.map((p) => p.x)
const ys = pts.map((p) => p.y)
// regression: pre-fix everything landed off-canvas (blank white image)
expect(Math.max(...xs) - Math.min(...xs)).toBeGreaterThan(300)
expect(Math.max(...ys) - Math.min(...ys)).toBeGreaterThan(180)
})
})
describe('WMF DIB blts (ole-icon.wmf)', () => {
it('renders the icon via two DIBSTRETCHBLT records with mask/xor composites', async () => {
reset()
const result = await convertWmfToDataUrl(loadFixture('ole-icon.wmf'), { dpiScale: 2 })
expect(result).toMatch(/^data:image\/png;base64,/)
// placeable bounds 90×50 at dpiScale 2
expect(canvases[0]?.width).toBe(180)
expect(canvases[0]?.height).toBe(100)
const draws = calls.filter((c) => c.method === 'drawImage')
expect(draws).toHaveLength(2)
for (const draw of draws) {
// 9-arg form: src rect crops the (double-height) icon DIB
expect(draw.args).toHaveLength(9)
const [, sx, sy, sw, sh, dx, dy, dw, dh] = draw.args as [unknown, ...number[]]
expect([sx, sy, sw, sh]).toEqual([0, 0, 32, 32])
// dest (29,0,32,32) logical → ×2 device
expect(dx).toBeCloseTo(58)
expect(dy).toBeCloseTo(0)
expect(dw).toBeCloseTo(64)
expect(dh).toBeCloseTo(64)
}
const gcos = calls
.filter((c) => c.method === 'set:globalCompositeOperation')
.map((c) => c.args[0])
expect(gcos).toContain('multiply') // SRCAND mask
expect(gcos).toContain('difference') // SRCINVERT color
})
it('skips a bitmap-less DIBSTRETCHBLT and keeps replaying (MS-WMF 2.3.1.3)', async () => {
reset()
// header + SETWINDOWORG(0,0) + SETWINDOWEXT(50,90) + bitmap-less
// META_DIBSTRETCHBLT (RecordSize == (0x0B41 >> 8) + 3 = 14 words, one
// reserved word in place of the DIB) + RECTANGLE + EOF
const rec = (type: number, params: number[]) => {
const bytes = new Uint8Array(6 + params.length * 2)
const v = new DataView(bytes.buffer)
v.setUint32(0, 3 + params.length, true)
v.setUint16(4, type, true)
params.forEach((p, i) => v.setInt16(6 + i * 2, p, true))
return bytes
}
const records = [
rec(0x020b, [0, 0]), // SETWINDOWORG (y, x)
rec(0x020c, [50, 90]), // SETWINDOWEXT (cy, cx)
rec(0x0b41, [0x20, 0xcc, 0, 32, 32, 0, 0, 32, 32, 0, 0]), // rop lo/hi, reserved, params
rec(0x041b, [40, 80, 10, 10]), // RECTANGLE (b, r, t, l)
rec(0, []), // EOF
]
const body = records.reduce((n, r) => n + r.length, 0)
const wmf = new Uint8Array(18 + body)
const hv = new DataView(wmf.buffer)
hv.setUint16(0, 1, true) // mtType
hv.setUint16(2, 9, true) // mtHeaderSize (words)
hv.setUint16(4, 0x0300, true) // mtVersion
hv.setUint32(6, wmf.length / 2, true) // mtSize (words)
let at = 18
for (const r of records) {
wmf.set(r, at)
at += r.length
}
const result = await convertWmfToDataUrl(wmf.buffer, { dpiScale: 1 })
expect(result).toMatch(/^data:image\/png;base64,/)
// the bitmap-less blt draws nothing, and the record after it still renders
expect(calls.filter((c) => c.method === 'drawImage')).toHaveLength(0)
expect(calls.some((c) => c.method === 'strokeRect')).toBe(true)
})
it('derives bounds from SETWINDOWORG/EXT when the placeable header is missing', async () => {
reset()
const withHeader = new Uint8Array(loadFixture('ole-icon.wmf'))
const stripped = withHeader.slice(22) // drop the 22-byte placeable header
const result = await convertWmfToDataUrl(
stripped.buffer.slice(stripped.byteOffset, stripped.byteOffset + stripped.byteLength),
{ dpiScale: 2 },
)
expect(result).toMatch(/^data:image\/png;base64,/)
// pre-fix fallback was a fixed 800×600 guess (1600×1200 canvas)
expect(canvases[0]?.width).toBe(180)
expect(canvases[0]?.height).toBe(100)
})
})
describe('EMR_ALPHABLEND (w-icon.emf)', () => {
it('draws the OLE icon bitmap with its real alpha channel', async () => {
reset()
const result = await convertEmfToDataUrl(loadFixture('w-icon.emf'), { dpiScale: 2 })
expect(result).toMatch(/^data:image\/png;base64,/)
// regression: the record was unhandled — only the caption text rendered
const draws = calls.filter((c) => c.method === 'drawImage')
expect(draws).toHaveLength(1)
expect(draws[0].args).toHaveLength(9)
const [, sx, sy, sw, sh, , , dw, dh] = draws[0].args as [unknown, ...number[]]
expect([sx, sy, sw, sh]).toEqual([0, 0, 32, 32])
expect(dw).toBeGreaterThan(0)
expect(dh).toBeGreaterThan(0)
// AC_SRC_ALPHA source: the pixels around the icon stay transparent
// (the shared decoder's zero-alpha-means-opaque heuristic must not apply)
const put = calls.find((c) => c.method === 'putImageData')
const img = put?.args[0] as { data: Uint8ClampedArray; width: number; height: number }
expect(img.width).toBe(32)
expect(img.height).toBe(32)
let transparent = 0
let opaque = 0
for (let i = 3; i < img.data.length; i += 4) {
if (img.data[i] === 0) transparent++
else if (img.data[i] === 255) opaque++
}
expect(transparent).toBe(240)
expect(opaque).toBe(784)
// the caption text still replays after the blend
const texts = calls.filter((c) => c.method === 'fillText').map((c) => c.args[0])
expect(texts).toContain('Документ-в-докуме')
expect(texts).toContain('нте')
})
})
describe('gzipped metafiles (.emz/.wmz)', () => {
it('accepts emz/wmz mimes', () => {
for (const m of ['image/emz', 'image/x-emz', 'image/wmz', 'image/x-wmz']) {
expect(isMetafileMime(m)).toBe(true)
}
})
it('gunzips and converts a wmz payload', async () => {
reset()
const gz = gzipSync(Buffer.from(loadFixture('ole-icon.wmf')))
const result = await metafileToDataUrl(new Uint8Array(gz), 'image/x-wmz')
expect(result).toMatch(/^data:image\/png;base64,/)
expect(canvases[0]?.width).toBe(180)
})
it('gunzips gzip-compressed bytes even under a plain emf/wmf mime', async () => {
reset()
const gz = gzipSync(Buffer.from(loadFixture('wrench.emf')))
const result = await metafileToDataUrl(new Uint8Array(gz), 'image/x-emf')
expect(result).toMatch(/^data:image\/png;base64,/)
expect(canvases[0]?.width).toBe(380)
})
})
@@ -1,5 +1,11 @@
import { describe, expect, it } from 'vitest'
import { computeListMarkers, parseDocx } from '../src/index'
import {
computeListMarkers,
customEnumItems,
formatNumber,
markerTabAdvance,
parseDocx,
} from '../src/index'
import { buildDocx } from './helpers/build-docx'
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
@@ -119,3 +125,272 @@ describe('missing w:start default', () => {
expect(markers).toEqual(['0.', '1.'])
})
})
describe('greek letter formats', () => {
it('lowerGreek walks the 24-letter alphabet without final sigma', () => {
expect(formatNumber(1, 'lowerGreek')).toBe('α')
expect(formatNumber(17, 'lowerGreek')).toBe('ρ')
expect(formatNumber(18, 'lowerGreek')).toBe('σ')
expect(formatNumber(24, 'lowerGreek')).toBe('ω')
expect(formatNumber(25, 'lowerGreek')).toBe('αα')
expect(formatNumber(49, 'lowerGreek')).toBe('ααα')
})
it('upperGreek skips the unassigned U+03A2 slot', () => {
expect(formatNumber(1, 'upperGreek')).toBe('Α')
expect(formatNumber(17, 'upperGreek')).toBe('Ρ')
expect(formatNumber(18, 'upperGreek')).toBe('Σ')
expect(formatNumber(24, 'upperGreek')).toBe('Ω')
expect(formatNumber(25, 'upperGreek')).toBe('ΑΑ')
})
it('renders greek markers through lvlText', async () => {
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="0">' +
'<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="lowerGreek"/><w:lvlText w:val="%1."/></w:lvl>' +
'</w:abstractNum>' +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
'</w:numbering>'
const doc = await parseDocx(
await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>', numberingXml: numbering }),
)
const markers = computeListMarkers(
[
{ numId: '1', ilvl: 0 },
{ numId: '1', ilvl: 0 },
],
doc.numbering,
)
expect(markers).toEqual(['α.', 'β.'])
})
})
describe('w:suff', () => {
const SUFF_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="0">' +
'<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:suff w:val="space"/><w:lvlText w:val="%1."/></w:lvl>' +
'<w:lvl w:ilvl="1"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:suff w:val="nothing"/><w:lvlText w:val="%2."/></w:lvl>' +
'<w:lvl w:ilvl="2"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%3."/></w:lvl>' +
'</w:abstractNum>' +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
'</w:numbering>'
it('parses the marker suffix kind, leaving the tab default unset', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
numberingXml: SUFF_NUMBERING,
}),
)
const levels = doc.numbering.get('1')!.levels
expect(levels[0].suff).toBe('space')
expect(levels[1].suff).toBe('nothing')
expect(levels[2].suff).toBeUndefined()
})
})
describe('style-level numId="0" cancels inherited numbering', () => {
const STYLES =
'<w:style w:type="paragraph" w:styleId="NumberedBase"><w:name w:val="Numbered Base"/>' +
'<w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="NoNumChild"><w:name w:val="No Num Child"/>' +
'<w:basedOn w:val="NumberedBase"/>' +
'<w:pPr><w:numPr><w:numId w:val="0"/></w:numPr></w:pPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="PlainChild"><w:name w:val="Plain Child"/>' +
'<w:basedOn w:val="NumberedBase"/></w:style>'
it('blocks basedOn numPr inheritance for the cancelling style only', async () => {
const p = (style: string, text: string) =>
`<w:p><w:pPr><w:pStyle w:val="${style}"/></w:pPr><w:r><w:t>${text}</w:t></w:r></w:p>`
const doc = await parseDocx(
await buildDocx({
bodyXml: p('NumberedBase', 'a') + p('NoNumChild', 'b') + p('PlainChild', 'c'),
extraStylesXml: STYLES,
withNumbering: true,
}),
)
expect(doc.blocks[0].list).toMatchObject({ numId: '2', ilvl: 0 })
expect(doc.blocks[1].list).toBeUndefined()
expect(doc.blocks[2].list).toMatchObject({ numId: '2', ilvl: 0 })
})
})
describe('w:numStyleLink indirection', () => {
const LINKED_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="0"><w:numStyleLink w:val="ListNumberStyle"/></w:abstractNum>' +
'<w:abstractNum w:abstractNumId="1"><w:styleLink w:val="ListNumberStyle"/>' +
'<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="bullet"/><w:lvlText w:val="&#61623;"/></w:lvl>' +
'</w:abstractNum>' +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
'</w:numbering>'
it('resolves levels through numStyleLink -> styleLink', async () => {
const li = (ilvl: number, text: string) =>
`<w:p><w:pPr><w:numPr><w:ilvl w:val="${ilvl}"/><w:numId w:val="1"/></w:numPr></w:pPr>` +
`<w:r><w:t>${text}</w:t></w:r></w:p>`
const doc = await parseDocx(
await buildDocx({ bodyXml: li(0, 'a') + li(1, 'b'), numberingXml: LINKED_NUMBERING }),
)
expect(doc.numbering.get('1')!.levels[0]).toMatchObject({ numFmt: 'decimal', lvlText: '%1)' })
expect(doc.blocks[0].list?.kind).toBe('ordered')
expect(doc.blocks[1].list?.kind).toBe('bullet')
expect(computeListMarkers([{ numId: '1', ilvl: 0 }], doc.numbering)).toEqual(['1)'])
})
it('survives a numStyleLink cycle', async () => {
const cyclic =
'<?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="0"><w:numStyleLink w:val="A"/><w:styleLink w:val="B"/></w:abstractNum>' +
'<w:abstractNum w:abstractNumId="1"><w:numStyleLink w:val="B"/><w:styleLink w:val="A"/></w:abstractNum>' +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
'</w:numbering>'
const doc = await parseDocx(
await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>', numberingXml: cyclic }),
)
expect(doc.numbering.get('1')!.levels).toEqual({})
})
})
describe('numFmt "none" with empty lvlText', () => {
const NONE_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="none"/><w:suff w:val="nothing"/><w:lvlText w:val=""/></w:lvl>' +
'</w:abstractNum>' +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
'</w:numbering>'
it('emits an explicit empty marker, not null (null re-enables counter fallbacks)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
numberingXml: NONE_NUMBERING,
}),
)
expect(doc.numbering.get('1')!.levels[0].numFmt).toBe('none')
const markers = computeListMarkers(
[
{ numId: '1', ilvl: 0 },
{ numId: '1', ilvl: 0 },
],
doc.numbering,
)
expect(markers).toEqual(['', ''])
})
})
describe('w14 custom numFmt (mc:AlternateContent)', () => {
const alternate = (choiceFmt: string, format: string) =>
XML_DECL +
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
' xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">' +
'<w:abstractNum w:abstractNumId="0">' +
'<w:lvl w:ilvl="0"><w:start w:val="1"/>' +
'<mc:AlternateContent><mc:Choice Requires="w14">' +
`<w:numFmt w:val="${choiceFmt}" w:format="${format}"/>` +
'</mc:Choice><mc:Fallback><w:numFmt w:val="decimal"/></mc:Fallback></mc:AlternateContent>' +
'<w:lvlText w:val="%1."/></w:lvl>' +
'</w:abstractNum>' +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
'</w:numbering>'
it('parses the enumerated custom format from mc:Choice and cycles it', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
numberingXml: alternate('custom', 'α, β, γ, ...'),
}),
)
const level = doc.numbering.get('1')!.levels[0]
expect(level.numFmt).toBe('custom')
expect(level.customFormat).toBe('α, β, γ, ...')
const ref = { numId: '1', ilvl: 0 }
expect(computeListMarkers([ref, ref, ref, ref], doc.numbering)).toEqual([
'α.',
'β.',
'γ.',
'α.',
])
})
it('falls back to mc:Fallback when the custom format is not an enumeration', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
numberingXml: alternate('custom', 'mystery'),
}),
)
expect(doc.numbering.get('1')!.levels[0].numFmt).toBe('decimal')
expect(computeListMarkers([{ numId: '1', ilvl: 0 }], doc.numbering)).toEqual(['1.'])
})
it('customEnumItems accepts comma enumerations and rejects everything else', () => {
expect(customEnumItems('α, β, γ, ...')).toEqual(['α', 'β', 'γ'])
expect(customEnumItems('01, 02, 03')).toEqual(['01', '02', '03'])
expect(customEnumItems('mystery')).toBeNull()
expect(customEnumItems('a, ')).toBeNull()
})
it('formatNumber cycles custom enumerations', () => {
expect(formatNumber(2, 'custom', 'α, β, γ, ...')).toBe('β')
expect(formatNumber(5, 'custom', 'α, β, γ, ...')).toBe('β')
expect(formatNumber(3, 'custom')).toBe('3')
})
})
describe('numbering level positive w:firstLine', () => {
const FIRSTLINE_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="upperLetter"/><w:lvlText w:val="%1"/>' +
'<w:pPr><w:ind w:left="432" w:firstLine="135"/></w:pPr></w:lvl>' +
'</w:abstractNum>' +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
'</w:numbering>'
it('keeps the positive first-line indent (marker sits right of the text indent)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
numberingXml: FIRSTLINE_NUMBERING,
}),
)
expect(doc.numbering.get('1')!.levels[0]).toMatchObject({
indentLeft: 432,
firstLine: 135,
})
expect(doc.numbering.get('1')!.levels[0].hanging).toBeUndefined()
})
})
describe('markerTabAdvance (default tab after the marker)', () => {
it('returns null when the marker fits the hanging area', () => {
expect(markerTabAdvance(0, 300, 360)).toBeNull()
expect(markerTabAdvance(0, 360, 360)).toBeNull()
})
it('jumps to the next default-tab-grid stop when the marker overflows', () => {
// "NEW-1-FORMAT" at ind left=360 hanging=360: marker 0..~1476 -> stop at 2160
expect(markerTabAdvance(0, 1476, 360)).toBe(2160)
expect(markerTabAdvance(0, 400, 360)).toBe(720)
})
it('handles markers starting past the text indent (positive firstLine)', () => {
// 47_NumberingWOverrides "B": marker at 567, width ~160 -> stop at 1440
expect(markerTabAdvance(567, 160, 432)).toBe(1440 - 567)
})
it('honors a custom default tab interval', () => {
expect(markerTabAdvance(0, 400, 360, 708)).toBe(708)
})
})
@@ -0,0 +1,56 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
describe('w:br outside a w:r (Word honors these; tdf108714 family)', () => {
it('body-level <w:br w:type="page"/> becomes a page-break block', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
'<w:p><w:r><w:t>Paragraph 1</w:t></w:r></w:p>' +
'<w:br w:type="page"/>' +
'<w:p><w:r><w:t>Paragraph 2</w:t></w:r></w:p>',
}),
)
const br = doc.blocks[1]
expect(br.type).toBe('passthrough')
expect(br.fieldDisplay?.kind).toBe('pageBreak')
expect(br.invisibleMarker).toBeUndefined()
})
it('body-level <w:br w:type="textWrapping"/> stays invisible (no placeholder chip)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p><w:br w:type="textWrapping"/>',
}),
)
expect(doc.blocks[1].invisibleMarker).toBe(true)
})
it('<w:br> as a direct child of w:p becomes a break run', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: '<w:p><w:br w:type="page"/><w:r><w:t>after</w:t></w:r></w:p>',
}),
)
const text = (doc.blocks[0].runs ?? []).map((r) => r.text).join('')
expect(text).toBe('\fafter')
})
it('page-type w:br next to an anchored VML textbox marks the block (tdf141220)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
'<w:p><w:r><w:pict>' +
'<v:rect style="position:absolute;width:100pt;height:50pt">' +
'<v:textbox><w:txbxContent><w:p><w:r><w:t>box text</w:t></w:r></w:p></w:txbxContent></v:textbox>' +
'</v:rect><w10:wrap type="none"/></w:pict></w:r>' +
'<w:r><w:br w:type="page"/></w:r></w:p>' +
'<w:p><w:r><w:t>next page</w:t></w:r></w:p>',
}),
)
const box = doc.blocks[0]
expect(box.label).toBe('Text box')
expect(box.fieldDisplay?.kind).toBe('pageBreak')
})
})
@@ -0,0 +1,162 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/parse'
import { buildDocx } from './helpers/build-docx'
const WPS_NS = 'xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"'
const WPG_NS = 'xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"'
const MC_NS = 'xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"'
const WP14_NS = 'xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing"'
// build-docx sectPr: A4 (11906x16838 twips), 1440-twip margins
const PAGE_W = 11906 * 635
const PAGE_H = 16838 * 635
const MARGIN = 1440 * 635
function textWsp(opts: {
offX: number
offY: number
cx: number
cy: number
text: string
bodyPrAttrs?: string
}): string {
return (
`<wps:wsp ${WPS_NS}><wps:cNvSpPr txBox="1"/><wps:spPr>` +
`<a:xfrm><a:off x="${opts.offX}" y="${opts.offY}"/><a:ext cx="${opts.cx}" cy="${opts.cy}"/></a:xfrm>` +
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/>` +
`</wps:spPr><wps:txbx><w:txbxContent><w:p><w:r><w:t>${opts.text}</w:t></w:r></w:p></w:txbxContent></wps:txbx>` +
`<wps:bodyPr${opts.bodyPrAttrs ?? ''}/></wps:wsp>`
)
}
function anchorPara(
positionHXml: string,
positionVXml: string,
inner: string,
ext: string,
): string {
return (
`<w:p><w:r><w:drawing><wp:anchor behindDoc="0" simplePos="0" locked="0" layoutInCell="1" allowOverlap="1">` +
`<wp:simplePos x="0" y="0"/>${positionHXml}${positionVXml}${ext}` +
`<wp:wrapSquare wrapText="bothSides"/><wp:docPr id="1" name="Box 1"/>` +
`<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">` +
inner +
`</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>`
)
}
describe('page/margin-anchored textboxes outside the body column', () => {
it('floats a page-pct-anchored sidebar group at the resolved page position', async () => {
// mirrors Word resume templates: pctPosHOffset in mc:Choice, posOffset in
// the stripped mc:Fallback, positionV margin/align=top, full-height group
const posH =
`<mc:AlternateContent ${MC_NS}><mc:Choice Requires="wp14">` +
`<wp:positionH relativeFrom="page"><wp14:pctPosHOffset ${WP14_NS}>2000</wp14:pctPosHOffset></wp:positionH>` +
`</mc:Choice><mc:Fallback><wp:positionH relativeFrom="page"><wp:posOffset>151206</wp:posOffset></wp:positionH></mc:Fallback></mc:AlternateContent>`
const posV = `<wp:positionV relativeFrom="margin"><wp:align>top</wp:align></wp:positionV>`
const group =
`<wpg:wgp ${WPG_NS} ${WPS_NS}><wpg:cNvGrpSpPr/><wpg:grpSpPr>` +
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="600000" cy="8000000"/>` +
`<a:chOff x="0" y="0"/><a:chExt cx="600000" cy="8000000"/></a:xfrm></wpg:grpSpPr>` +
textWsp({ offX: 0, offY: 0, cx: 600000, cy: 4000000, text: 'name' }) +
textWsp({
offX: 0,
offY: 4400000,
cx: 600000,
cy: 3600000,
text: 'address',
bodyPrAttrs: ' anchor="b"',
}) +
`</wpg:wgp>`
const para = anchorPara(posH, posV, group, '<wp:extent cx="600000" cy="8000000"/>').replace(
'wordprocessingShape">',
'wordprocessingGroup">',
)
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const boxes = doc.blocks[0].textboxes
expect(boxes?.length).toBe(2)
const [name, address] = boxes!
const anchorX = Math.round((PAGE_W * 2000) / 100000) - MARGIN
expect(name.floating).toBe(true)
expect(name.offsetXEmu).toBe(anchorX)
expect(name.offsetYEmu).toBe(0)
expect(address.floating).toBe(true)
expect(address.offsetXEmu).toBe(anchorX)
expect(address.offsetYEmu).toBe(4400000)
expect(address.vAlign).toBe('bottom')
expect(name.vAlign).toBeUndefined()
})
it('keeps in-column wrapSquare boxes in the flow', async () => {
const posH = `<wp:positionH relativeFrom="page"><wp14:pctPosHOffset ${WP14_NS}>20000</wp14:pctPosHOffset></wp:positionH>`
const posV = `<wp:positionV relativeFrom="margin"><wp:align>top</wp:align></wp:positionV>`
const para = anchorPara(
posH,
posV,
textWsp({ offX: 0, offY: 0, cx: 600000, cy: 400000, text: 'callout' }),
'<wp:extent cx="600000" cy="400000"/>',
)
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const [box] = doc.blocks[0].textboxes!
expect(box.floating).toBeUndefined()
expect(box.offsetXEmu).toBeUndefined()
})
it('resolves page-relative wp:align right/bottom against the page geometry', async () => {
const posH = `<wp:positionH relativeFrom="page"><wp:align>right</wp:align></wp:positionH>`
const posV = `<wp:positionV relativeFrom="margin"><wp:align>bottom</wp:align></wp:positionV>`
const para = anchorPara(
posH,
posV,
textWsp({ offX: 0, offY: 0, cx: 600000, cy: 1000000, text: 'side' }),
'<wp:extent cx="600000" cy="1000000"/>',
)
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const [box] = doc.blocks[0].textboxes!
expect(box.floating).toBe(true)
expect(box.offsetXEmu).toBe(PAGE_W - 600000 - MARGIN)
expect(box.offsetYEmu).toBe(PAGE_H - 2 * MARGIN - 1000000)
})
it('leaves plain posOffset anchors on the legacy paragraph-relative path', async () => {
const posH = `<wp:positionH relativeFrom="page"><wp:posOffset>100000</wp:posOffset></wp:positionH>`
const posV = `<wp:positionV relativeFrom="paragraph"><wp:posOffset>50000</wp:posOffset></wp:positionV>`
const para = anchorPara(
posH,
posV,
textWsp({ offX: 0, offY: 0, cx: 600000, cy: 400000, text: 'legacy' }),
'<wp:extent cx="600000" cy="400000"/>',
)
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const [box] = doc.blocks[0].textboxes!
expect(box.floating).toBeUndefined()
expect(box.offsetXEmu).toBe(100000)
expect(box.offsetYEmu).toBe(50000)
})
it('resolves SDT-wrapped anchors against their own section, not the first one', async () => {
// section 1: wide page with narrow margins — an anchor resolved against it
// would land inside the column and stay in the flow
const sect1Para =
`<w:p><w:pPr><w:sectPr>` +
`<w:pgSz w:w="20000" w:h="16838"/>` +
`<w:pgMar w:top="1440" w:right="720" w:bottom="1440" w:left="720" w:header="708" w:footer="708" w:gutter="0"/>` +
`</w:sectPr></w:pPr></w:p>`
const posH = `<wp:positionH relativeFrom="page"><wp14:pctPosHOffset ${WP14_NS}>2000</wp14:pctPosHOffset></wp:positionH>`
const posV = `<wp:positionV relativeFrom="margin"><wp:align>top</wp:align></wp:positionV>`
const anchored = anchorPara(
posH,
posV,
textWsp({ offX: 0, offY: 0, cx: 600000, cy: 400000, text: 'sidebar' }),
'<wp:extent cx="600000" cy="400000"/>',
)
const bodyXml =
`<w:p><w:r><w:t>section one</w:t></w:r></w:p>${sect1Para}` +
`<w:sdt><w:sdtPr><w:id w:val="42"/></w:sdtPr><w:sdtContent>${anchored}</w:sdtContent></w:sdt>`
const doc = await parseDocx(await buildDocx({ bodyXml }))
const box = doc.blocks.find((b) => b.textboxes)?.textboxes?.[0]
// section 2 (trailing A4 sectPr) geometry, not section 1's
expect(box?.floating).toBe(true)
expect(box?.offsetXEmu).toBe(Math.round((PAGE_W * 2000) / 100000) - MARGIN)
})
})
+160 -12
View File
@@ -8,6 +8,7 @@ import {
generateParagraphXml,
parseDocx,
saveDocx,
styleRunFormat,
type GenerateContext,
type SaveBlock,
} from '../src/index'
@@ -208,26 +209,41 @@ describe.skipIf(!existsSync(REAL))('real document invariant (example/docx)', ()
})
})
describe('complex-script runs read the Cs twins (w:bCs/w:iCs/w:szCs)', () => {
it('w:b / w:sz do not apply to Arabic text; the Cs twins do', async () => {
describe('explicit w:rtl selects the property set (probed, Word for Mac)', () => {
it('non-rtl runs read w:b/w:i/w:sz and ignore the Cs twins, even for Arabic text', async () => {
const bodyXml =
'<w:p><w:r><w:rPr><w:b/><w:sz w:val="28"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>' +
'<w:p><w:r><w:rPr><w:bCs/><w:iCs/><w:szCs w:val="36"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>' +
'<w:p><w:r><w:rPr><w:b/><w:sz w:val="15"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>' +
'<w:p><w:r><w:rPr><w:bCs/><w:iCs/><w:sz w:val="28"/><w:szCs w:val="36"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>' +
'<w:p><w:r><w:rPr><w:b/><w:sz w:val="28"/></w:rPr><w:t>latin</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const [bOnly, csTwins, latin] = doc.blocks.filter((b) => b.runs?.length).map((b) => b.runs![0])
expect(bOnly.cs).toBe(true)
expect(bOnly.bold).toBeUndefined()
expect(bOnly.sizeHalfPoints).toBeUndefined()
expect(csTwins.bold).toBe(true)
expect(csTwins.italic).toBe(true)
expect(csTwins.sizeHalfPoints).toBe(36)
const [arabic, csTwins, latin] = doc.blocks.filter((b) => b.runs?.length).map((b) => b.runs![0])
expect(arabic.cs).toBeUndefined()
expect(arabic.bold).toBe(true)
expect(arabic.sizeHalfPoints).toBe(15)
expect(csTwins.cs).toBeUndefined()
expect(csTwins.bold).toBeUndefined()
expect(csTwins.italic).toBeUndefined()
expect(csTwins.sizeHalfPoints).toBe(28)
expect(latin.cs).toBeUndefined()
expect(latin.bold).toBe(true)
expect(latin.sizeHalfPoints).toBe(28)
})
it('w:rtl marks a run complex-script regardless of its characters', async () => {
it('rtl runs read w:bCs/w:iCs/w:szCs with no fallback to w:b/w:i/w:sz', async () => {
const bodyXml =
'<w:p><w:r><w:rPr><w:rtl/><w:b/><w:sz w:val="28"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>' +
'<w:p><w:r><w:rPr><w:rtl/><w:bCs/><w:szCs w:val="36"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const [base, twins] = doc.blocks.filter((b) => b.runs?.length).map((b) => b.runs![0])
expect(base.cs).toBe(true)
expect(base.bold).toBeUndefined()
expect(base.sizeHalfPoints).toBeUndefined()
expect(twins.cs).toBe(true)
expect(twins.bold).toBe(true)
expect(twins.sizeHalfPoints).toBe(36)
})
it('w:rtl selects the Cs set regardless of the run characters', async () => {
const bodyXml = '<w:p><w:r><w:rPr><w:rtl/><w:b/></w:rPr><w:t>123</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
expect(doc.blocks[0].runs![0].cs).toBe(true)
@@ -242,6 +258,138 @@ describe('complex-script runs read the Cs twins (w:bCs/w:iCs/w:szCs)', () => {
expect(xml).toContain('<w:b/>')
expect(xml).toContain('<w:sz w:val="28"/>')
expect(xml).not.toContain('<w:bCs/>')
expect(xml).not.toContain('w:szCs')
})
it('an untouched rtl run keeps its Cs-twin bytes on paragraph rebuild', async () => {
const bodyXml =
'<w:p><w:r><w:rPr><w:bCs/><w:szCs w:val="36"/><w:rtl/></w:rPr><w:t>عنوان</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const run = doc.blocks[0].runs![0]
const xml = generateParagraphXml({ type: 'paragraph', runs: [{ ...run }] }, GEN_CTX)
expect(xml).toContain('<w:bCs/><w:szCs w:val="36"/><w:rtl/>')
expect(xml).not.toContain('<w:b/>')
})
})
const RTL_STYLES_XML =
'<w:style w:type="paragraph" w:styleId="HeadB"><w:name w:val="Head B"/>' +
'<w:rPr><w:b/><w:sz w:val="30"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="HeadBCs"><w:name w:val="Head BCs"/>' +
'<w:rPr><w:bCs/><w:szCs w:val="36"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="RtlNormal"><w:name w:val="Rtl Normal"/>' +
'<w:rPr><w:rtl/><w:bCs/></w:rPr></w:style>' +
'<w:style w:type="character" w:styleId="ArChar"><w:name w:val="Ar Char"/>' +
'<w:rPr><w:rtl/><w:iCs/></w:rPr></w:style>'
describe('style chain follows the same rtl property-set selection', () => {
const styled = (styleId: string, rPr = '') =>
`<w:p><w:pPr><w:pStyle w:val="${styleId}"/></w:pPr>` +
`<w:r>${rPr ? `<w:rPr>${rPr}</w:rPr>` : ''}<w:t>عنوان</w:t></w:r></w:p>`
it('pStyle w:b/w:sz applies to non-rtl runs, not to rtl runs', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: styled('HeadB') + styled('HeadB', '<w:rtl/>'),
extraStylesXml: RTL_STYLES_XML,
}),
)
const display = doc.styles.get('HeadB')!.display
const [plain, rtl] = doc.blocks.filter((b) => b.runs?.length).map((b) => b.runs![0])
expect(plain.cs).toBeUndefined()
expect(styleRunFormat(display, !!plain.cs)).toEqual({
bold: true,
italic: undefined,
sizeHalfPoints: 30,
})
expect(rtl.cs).toBe(true)
expect(styleRunFormat(display, !!rtl.cs)).toEqual({
bold: undefined,
italic: undefined,
sizeHalfPoints: undefined,
})
})
it('pStyle w:bCs/w:szCs applies to rtl runs, ignored for non-rtl runs', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: styled('HeadBCs', '<w:rtl/>') + styled('HeadBCs'),
extraStylesXml: RTL_STYLES_XML,
}),
)
const display = doc.styles.get('HeadBCs')!.display
expect(display?.boldCs).toBe(true)
expect(display?.sizeCsHalfPoints).toBe(36)
const [rtl, plain] = doc.blocks.filter((b) => b.runs?.length).map((b) => b.runs![0])
expect(styleRunFormat(display, !!rtl.cs)).toEqual({
bold: true,
italic: undefined,
sizeHalfPoints: 36,
})
expect(styleRunFormat(display, !!plain.cs)).toEqual({
bold: undefined,
italic: undefined,
sizeHalfPoints: undefined,
})
})
it('style-level w:rtl inherits into runs without their own flag; explicit off wins', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
styled('RtlNormal', '<w:color w:val="FF0000"/>') +
styled('RtlNormal', '<w:rtl w:val="0"/>') +
`<w:p><w:pPr><w:pStyle w:val="RtlNormal"/></w:pPr><w:r><w:t>bare</w:t></w:r></w:p>`,
extraStylesXml: RTL_STYLES_XML,
}),
)
const [inherited, explicitOff, bare] = doc.blocks
.filter((b) => b.runs?.length)
.map((b) => b.runs![0])
expect(inherited.cs).toBe(true)
expect(explicitOff.cs).toBeUndefined()
expect(bare.cs).toBe(true)
})
it('character-style w:rtl inherits into the run', async () => {
const bodyXml =
'<w:p><w:r><w:rPr><w:rStyle w:val="ArChar"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml, extraStylesXml: RTL_STYLES_XML }))
const run = doc.blocks[0].runs![0]
expect(run.cs).toBe(true)
expect(styleRunFormat(doc.styles.get('ArChar')!.display, !!run.cs).italic).toBe(true)
})
it('an untouched w:b run under an rtl style keeps its bytes on paragraph rebuild', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: styled('RtlNormal', '<w:b/>'),
extraStylesXml: RTL_STYLES_XML,
}),
)
const run = doc.blocks[0].runs![0]
expect(run.cs).toBe(true)
expect(run.bold).toBeUndefined() // rtl run: direct w:b is not the selected set
const xml = generateParagraphXml(
{ type: 'paragraph', styleId: 'RtlNormal', runs: [{ ...run }] },
GEN_CTX,
)
expect(xml).toContain('<w:b/>')
expect(xml).not.toContain('<w:bCs/>')
})
it('a run whose cs flag was dropped by a round-trip still keeps its Cs bytes', async () => {
const bodyXml = '<w:p><w:r><w:rPr><w:bCs/><w:rtl/></w:rPr><w:t>عنوان</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const run = doc.blocks[0].runs![0]
expect(run.bold).toBe(true)
// editor mark round-trips can rebuild the Run without cs; raw w:rtl re-selects the set
const xml = generateParagraphXml(
{ type: 'paragraph', runs: [{ ...run, cs: undefined }] },
GEN_CTX,
)
expect(xml).toContain('<w:bCs/><w:rtl/>')
expect(xml).not.toContain('<w:b/>')
})
})
@@ -0,0 +1,22 @@
import { describe, expect, it } from 'vitest'
import { scanBody } from '../src/scan'
describe('scanBody with multiple <w:body> elements', () => {
it('keeps scanning past </w:body> into later sibling bodies (POI MultipleBodyBug)', () => {
const xml =
'<w:document>' +
'<w:body><w:p><w:r><w:t>BODY 1</w:t></w:r></w:p></w:body>' +
'<w:body><w:p><w:r><w:t>BODY 2</w:t></w:r></w:p></w:body>' +
'<w:body><w:p><w:r><w:t>BODY 3</w:t></w:r></w:p></w:body>' +
'</w:document>'
const scan = scanBody(xml)
expect(scan.elements.map((e) => e.name)).toEqual(['w:p', 'w:p', 'w:p'])
expect(xml.slice(scan.elements[2].start, scan.elements[2].end)).toContain('BODY 3')
expect(scan.innerEnd).toBe(scan.elements[2].end)
})
it('single body still terminates at its closing tag', () => {
const xml = '<w:document><w:body><w:p/></w:body></w:document>'
expect(scanBody(xml).elements.map((e) => e.name)).toEqual(['w:p'])
})
})
@@ -0,0 +1,295 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/parse'
import { buildDocx } from './helpers/build-docx'
const WPS_NS = 'xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"'
const WPG_NS = 'xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"'
const STYLE_REFS =
'<wps:style>' +
'<a:lnRef idx="2"><a:srgbClr val="123A5B"/></a:lnRef>' +
'<a:fillRef idx="1"><a:srgbClr val="2E6E9E"/></a:fillRef>' +
'<a:effectRef idx="0"><a:srgbClr val="000000"/></a:effectRef>' +
'<a:fontRef idx="minor"><a:srgbClr val="FFFFFF"/></a:fontRef>' +
'</wps:style>'
function wsp(opts: {
prst: string
offX?: number
offY?: number
cx: number
cy: number
xfrmAttrs?: string
ln?: string
text?: string
}): string {
const txbx = opts.text
? `<wps:txbx><w:txbxContent><w:p><w:r><w:t>${opts.text}</w:t></w:r></w:p></w:txbxContent></wps:txbx>`
: ''
return (
`<wps:wsp><wps:cNvSpPr/><wps:spPr>` +
`<a:xfrm${opts.xfrmAttrs ?? ''}><a:off x="${opts.offX ?? 0}" y="${opts.offY ?? 0}"/>` +
`<a:ext cx="${opts.cx}" cy="${opts.cy}"/></a:xfrm>` +
`<a:prstGeom prst="${opts.prst}"><a:avLst/></a:prstGeom>${opts.ln ?? ''}` +
`</wps:spPr>${STYLE_REFS}${txbx}<wps:bodyPr/></wps:wsp>`
)
}
function anchorParagraph(
inner: string,
opts?: { posX?: number; posY?: number; extCx?: number; extCy?: number },
): string {
return (
`<w:p><w:r><w:drawing><wp:anchor behindDoc="0" simplePos="0" locked="0" layoutInCell="1" allowOverlap="1">` +
`<wp:simplePos x="0" y="0"/>` +
`<wp:positionH relativeFrom="column"><wp:posOffset>${opts?.posX ?? 0}</wp:posOffset></wp:positionH>` +
`<wp:positionV relativeFrom="paragraph"><wp:posOffset>${opts?.posY ?? 0}</wp:posOffset></wp:positionV>` +
`<wp:extent cx="${opts?.extCx ?? 952500}" cy="${opts?.extCy ?? 952500}"/><wp:wrapNone/>` +
`<wp:docPr id="9" name="Shape 9"/>` +
`<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">` +
inner.replace('<wps:wsp>', `<wps:wsp ${WPS_NS}>`) +
`</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>`
)
}
describe('textless preset shapes render as display boxes', () => {
it('a star5 with wps:style colors becomes a floating readOnly box', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: anchorParagraph(wsp({ prst: 'star5', cx: 952500, cy: 857250 }), {
posX: 190500,
posY: 95250,
}),
}),
)
const box = doc.blocks[0].textboxes?.[0]
expect(box).toBeTruthy()
expect(box!.prst).toBe('star5')
expect(box!.readOnly).toBe(true)
expect(box!.floating).toBe(true)
expect(box!.fill).toBe('2E6E9E')
expect(box!.borderColor).toBe('123A5B')
expect(box!.widthPx).toBe(100)
expect(box!.heightPx).toBe(90)
expect(box!.offsetXEmu).toBe(190500)
expect(box!.offsetYEmu).toBe(95250)
})
it('a triangle keeps its preset and a text-bearing ellipse keeps its paras', async () => {
const body =
anchorParagraph(wsp({ prst: 'triangle', cx: 952500, cy: 857250 })) +
anchorParagraph(wsp({ prst: 'ellipse', cx: 1857375, cy: 876300, text: 'inside' }))
const doc = await parseDocx(await buildDocx({ bodyXml: body }))
expect(doc.blocks[0].textboxes?.[0]?.prst).toBe('triangle')
const ellipse = doc.blocks[1].textboxes?.[0]
expect(ellipse?.prst).toBe('ellipse')
expect(ellipse?.paras[0]?.runs[0]?.text).toBe('inside')
expect(ellipse?.readOnly).toBeUndefined()
})
})
describe('anchored connectors', () => {
it('a flipV straightConnector with a tail arrow renders as a diagonal lineArrow', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: anchorParagraph(
wsp({
prst: 'straightConnector1',
cx: 2362200,
cy: 390525,
xfrmAttrs: ' flipV="1"',
ln: '<a:ln><a:tailEnd type="triangle"/></a:ln>',
}),
),
}),
)
const box = doc.blocks[0].textboxes?.[0]
expect(box).toBeTruthy()
expect(box!.prst).toBe('lineArrow')
expect(box!.lineDiag).toBe(true)
expect(box!.flipV).toBe(true)
// stroke falls back to the wps:style lnRef color
expect(box!.borderColor).toBe('123A5B')
})
it('a head-only arrow reverses the segment so the arrowhead sits at the start', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: anchorParagraph(
wsp({
prst: 'straightConnector1',
cx: 2362200,
cy: 390525,
ln: '<a:ln><a:headEnd type="triangle"/></a:ln>',
}),
),
}),
)
const box = doc.blocks[0].textboxes?.[0]
expect(box!.prst).toBe('lineArrow')
// (0,0)→(w,h) with the arrow at (0,0) = the reversed segment
expect(box!.flipH).toBe(true)
expect(box!.flipV).toBe(true)
})
it('head-only on a flipV connector reverses onto the other diagonal', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: anchorParagraph(
wsp({
prst: 'straightConnector1',
cx: 2362200,
cy: 390525,
xfrmAttrs: ' flipV="1"',
ln: '<a:ln><a:headEnd type="triangle"/></a:ln>',
}),
),
}),
)
const box = doc.blocks[0].textboxes?.[0]
expect(box!.flipH).toBe(true)
expect(box!.flipV).toBeUndefined()
expect(box!.lineDiag).toBe(true)
})
it('a shallow flipped connector still renders as a line box', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: anchorParagraph(
wsp({ prst: 'straightConnector1', cx: 5230495, cy: 20955, xfrmAttrs: ' flipV="1"' }),
{ extCx: 5230495, extCy: 20955 },
),
}),
)
const box = doc.blocks[0].textboxes?.[0]
expect(box).toBeTruthy()
expect(box!.prst).toBe('line')
expect(box!.flipV).toBe(true)
expect(box!.lineDiag).toBe(true)
})
it('a shallow arrowed connector still renders as a line box', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: anchorParagraph(
wsp({
prst: 'straightConnector1',
cx: 5230495,
cy: 20955,
ln: '<a:ln><a:tailEnd type="triangle"/></a:ln>',
}),
{ extCx: 5230495, extCy: 20955 },
),
}),
)
expect(doc.blocks[0].textboxes?.[0]?.prst).toBe('lineArrow')
})
it('a zero-height flipped arrow keeps its flip (level line, arrow at the left tip)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: anchorParagraph(
wsp({
prst: 'straightConnector1',
cx: 2362200,
cy: 0,
xfrmAttrs: ' flipH="1"',
ln: '<a:ln><a:tailEnd type="triangle"/></a:ln>',
}),
{ extCx: 2362200, extCy: 0 },
),
}),
)
const box = doc.blocks[0].textboxes?.[0]
expect(box).toBeTruthy()
expect(box!.prst).toBe('lineArrow')
expect(box!.heightPx).toBe(12)
expect(box!.flipH).toBe(true)
// level line: no diagonal, the renderer reverses via flipH alone
expect(box!.lineDiag).toBeUndefined()
})
it('head-only on a zero-height flipH arrow cancels the reversal (arrow at the right tip)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: anchorParagraph(
wsp({
prst: 'straightConnector1',
cx: 2362200,
cy: 0,
xfrmAttrs: ' flipH="1"',
ln: '<a:ln><a:headEnd type="triangle"/></a:ln>',
}),
{ extCx: 2362200, extCy: 0 },
),
}),
)
const box = doc.blocks[0].textboxes?.[0]
expect(box!.prst).toBe('lineArrow')
// headEnd sits at the segment start; flipH puts that start at the right
// tip, so the reversed-segment representation has no flipH left
expect(box!.flipH).toBeUndefined()
expect(box!.flipV).toBe(true)
})
it('a near-flat anchored line stays on the decorative thin-rule path', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: anchorParagraph(wsp({ prst: 'line', cx: 5230495, cy: 20955 }), {
extCx: 5230495,
extCy: 20955,
}),
}),
)
expect(doc.blocks[0].textboxes).toBeUndefined()
expect(doc.blocks[0].decorative).toBe(true)
})
})
describe('wpg group children', () => {
const GROUP_PARA =
`<w:p><w:r><w:drawing><wp:anchor behindDoc="0" simplePos="0" locked="0" layoutInCell="1" allowOverlap="1">` +
`<wp:simplePos x="0" y="0"/>` +
`<wp:positionH relativeFrom="column"><wp:posOffset>100000</wp:posOffset></wp:positionH>` +
`<wp:positionV relativeFrom="paragraph"><wp:posOffset>200000</wp:posOffset></wp:positionV>` +
`<wp:extent cx="1476375" cy="723900"/><wp:wrapNone/>` +
`<wp:docPr id="14" name="Group 13"/>` +
`<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup">` +
`<wpg:wgp ${WPG_NS} ${WPS_NS}><wpg:cNvGrpSpPr/><wpg:grpSpPr>` +
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="1476375" cy="723900"/>` +
`<a:chOff x="1323975" y="4733925"/><a:chExt cx="1476375" cy="723900"/></a:xfrm>` +
`</wpg:grpSpPr>` +
wsp({ prst: 'star5', offX: 1323975, offY: 4733925, cx: 762000, cy: 723900 }) +
wsp({ prst: 'rightArrow', offX: 2038350, offY: 4733925, cx: 762000, cy: 723900, text: 'go' }) +
`</wpg:wgp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>`
it('maps child offsets through chOff and adds the anchor position', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: GROUP_PARA }))
const boxes = doc.blocks[0].textboxes
expect(boxes?.length).toBe(2)
const [star, arrow] = boxes!
// both children float at anchor + (childOff - chOff)
expect(star.floating).toBe(true)
expect(star.offsetXEmu).toBe(100000)
expect(star.offsetYEmu).toBe(200000)
expect(arrow.prst).toBe('rightArrow')
expect(arrow.offsetXEmu).toBe(100000 + (2038350 - 1323975))
expect(arrow.offsetYEmu).toBe(200000)
// document order preserved for the patch-save w:txbxContent mapping
expect(arrow.paras[0]?.runs[0]?.text).toBe('go')
})
it('scales child geometry when ext differs from chExt', async () => {
const scaled = GROUP_PARA.replace(
'<a:ext cx="1476375" cy="723900"/><a:chOff',
'<a:ext cx="738187" cy="361950"/><a:chOff',
)
const doc = await parseDocx(await buildDocx({ bodyXml: scaled }))
const [star, arrow] = doc.blocks[0].textboxes!
const sx = 738187 / 1476375
const sy = 361950 / 723900
expect(star.widthPx).toBe(Math.round(Math.round(762000 / 9525) * sx))
expect(star.heightPx).toBe(Math.round(Math.round(723900 / 9525) * sy))
expect(arrow.offsetXEmu).toBe(100000 + Math.round((2038350 - 1323975) * sx))
})
})
+132 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/index'
import { parseDocx, saveDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const DIAGRAM_DATA_XML =
@@ -104,3 +104,134 @@ describe('SmartArt / OLE visible degrade', () => {
expect(block.previewText ?? '').toBe('')
})
})
const OLE_OBJECT_RUN =
'<w:r><w:object w:dxaOrig="4150" w:dyaOrig="310">' +
'<v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="_x0000_i1025" ' +
'style="width:207.75pt;height:15.75pt"><v:imagedata r:id="rId10" o:title=""/></v:shape>' +
'<o:OLEObject xmlns:o="urn:schemas-microsoft-com:office:office" Type="Embed" ' +
'ProgID="Excel.Sheet.8" ShapeID="_x0000_i1025" DrawAspect="Content" ObjectID="_1"/>' +
'</w:object></w:r>'
describe('OLE embed sharing a paragraph with real text', () => {
const bodyXml =
'<w:p><w:r><w:rPr><w:color w:val="0000FF"/></w:rPr>' +
'<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>' +
OLE_OBJECT_RUN +
'</w:p>'
it('stays an editable paragraph; the object becomes a run-level image', async () => {
const parsed = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
const block = parsed.blocks[0]
expect(block.type).toBe('paragraph')
expect((block.runs ?? []).map((r) => r.text).join('')).toBe(
'Состоится пресс-конференция партнерств',
)
expect(block.runs?.[0].color).toBe('0000FF')
expect(block.runs?.[1].bold).toBe(true)
const imgRun = (block.runs ?? []).find((r) => r.image)
expect(imgRun?.image?.dataUrl).toMatch(/^data:image\/png;base64,/)
expect(imgRun?.image?.xml).toContain('<o:OLEObject')
// declared v:shape size (207.75pt × 15.75pt)
expect(imgRun?.image?.widthPx).toBe(277)
expect(imgRun?.image?.heightPx).toBe(21)
})
it('run image size falls back to w:object dxaOrig/dyaOrig (twips)', async () => {
const noStyle = bodyXml.replace(' style="width:207.75pt;height:15.75pt"', '')
const parsed = await parseDocx(await buildDocx({ bodyXml: noStyle, withImage: true }))
const imgRun = (parsed.blocks[0].runs ?? []).find((r) => r.image)
expect(imgRun?.image?.widthPx).toBe(277)
expect(imgRun?.image?.heightPx).toBe(21)
})
it('the w:object fragment round-trips through an edited save', async () => {
const parsed = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
const runs = parsed.blocks[0].runs!
const saved = await saveDocx(parsed, [
{ kind: 'generated', block: { type: 'paragraph', runs } },
])
const reparsed = await parseDocx(saved)
const block = reparsed.blocks[0]
expect(block.type).toBe('paragraph')
expect((block.runs ?? []).map((r) => r.text).join('')).toBe(
'Состоится пресс-конференция партнерств',
)
const imgRun = (block.runs ?? []).find((r) => r.image)
expect(imgRun?.image?.xml).toContain('<o:OLEObject')
})
it('an unresolvable preview keeps the protected chip with the text visible', async () => {
// no withImage: rId10 has no relationship, the preview cannot resolve
const parsed = await parseDocx(await buildDocx({ bodyXml }))
const block = parsed.blocks[0]
expect(block.type).toBe('passthrough')
expect(block.label).toBe('Embedded object')
expect(block.previewText).toContain('Состоится пресс-конференция')
})
})
function fieldOleParagraph(instr: string): string {
return (
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
`<w:r><w:instrText xml:space="preserve">${instr}</w:instrText></w:r>` +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
OLE_OBJECT_RUN +
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
)
}
describe('field-form OLE (EMBED/LINK field around w:object)', () => {
it('EMBED field takes the OLE display path: preview picture, ProgID, declared size', async () => {
const bodyXml = fieldOleParagraph(' EMBED Excel.Sheet.8 ')
const parsed = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
const block = parsed.blocks[0]
expect(block.type).toBe('passthrough')
expect(block.label).toBe('Embedded object')
expect(block.oleProgId).toBe('Excel.Sheet.8')
expect(block.imageDataUrl).toMatch(/^data:image\/png;base64,/)
expect(block.imageWidthPx).toBe(277)
expect(block.imageHeightPx).toBe(21)
})
it('LINK field (linked OLE) takes the same path', async () => {
const bodyXml = fieldOleParagraph(
' LINK Excel.Sheet.8 "Book1.xlsx" "Sheet1!R1C1:R2C2" \\a \\p ',
).replace('Type="Embed"', 'Type="Link"')
const parsed = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
const block = parsed.blocks[0]
expect(block.label).toBe('Embedded object')
expect(block.oleProgId).toBe('Excel.Sheet.8')
expect(block.imageDataUrl).toMatch(/^data:image\/png;base64,/)
})
it('a paragraph mixing EMBED with another field keeps the protected field chip', async () => {
const bodyXml = fieldOleParagraph(' EMBED Excel.Sheet.8 ').replace(
'<w:r><w:fldChar w:fldCharType="end"/></w:r>',
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:instrText xml:space="preserve"> TOC \\o </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r>',
)
const parsed = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
const block = parsed.blocks[0]
expect(block.label).toBe('Field (EMBED)')
expect(block.imageDataUrl).toBeUndefined()
})
it('no edits -> byte-identical save (passthrough keeps the field XML)', async () => {
const bytes = await buildDocx({
bodyXml: fieldOleParagraph(' EMBED Excel.Sheet.8 '),
withImage: true,
})
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(saved).toBe(bytes)
})
})
@@ -161,6 +161,31 @@ describe('generateTableModelXml', () => {
sizeHalfPoints: 30,
})
})
it('writes w:jc after w:tblW for an explicit alignment and round-trips it', async () => {
const xml = generateTableModelXml({
align: 'center',
rows: [[{ paras: ['a'] }, { paras: ['b'] }]],
})
expect(xml).toMatch(/<w:tblW[^>]*\/><w:jc w:val="center"\/>/)
const parsed = await parseDocx(await buildDocx({ bodyXml: xml }))
expect(parsed.blocks[0].table!.align).toBe('center')
})
it("align 'left' strips the original w:jc; undefined keeps it", () => {
const template =
'<w:tbl><w:tblPr><w:tblW w:w="8000" w:type="dxa"/><w:jc w:val="right"/></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 model = { rows: [[{ paras: ['New'] }]] }
expect(generateTableModelXml({ ...model, align: 'left' as const }, template)).not.toContain(
'<w:jc',
)
expect(generateTableModelXml(model, template)).toContain('<w:jc w:val="right"/>')
expect(generateTableModelXml({ ...model, align: 'center' as const }, template)).toContain(
'<w:jc w:val="center"/>',
)
})
})
describe('tcPr/trPr fidelity and new attributes', () => {
@@ -84,6 +84,36 @@ describe('textbox editing', () => {
})
})
it('extracts w:pStyle of textbox paragraphs so document style CSS reaches them', async () => {
const styled = TEXTBOX_PARAGRAPH.replace(
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr>',
'<w:p><w:pPr><w:pStyle w:val="KeyPoint"/><w:jc w:val="center"/></w:pPr>',
)
const doc = await parseDocx(await buildDocx({ bodyXml: styled }))
const box = doc.blocks[0].textboxes?.[0]
expect(box?.paras[0].styleId).toBeUndefined()
expect(box?.paras[1].styleId).toBe('KeyPoint')
})
it('keeps the anchor paragraph text sharing its paragraph with a textbox as strayRuns', async () => {
const withHeading = TEXTBOX_PARAGRAPH.replace(
'<w:p><w:r><mc:AlternateContent',
'<w:p><w:pPr><w:pStyle w:val="SectionHeading"/></w:pPr><w:r><mc:AlternateContent',
).replace(
'</mc:AlternateContent></w:r></w:p>',
'</mc:AlternateContent></w:r><w:r><w:t>Objective</w:t></w:r></w:p>',
)
const doc = await parseDocx(await buildDocx({ bodyXml: withHeading }))
const block = doc.blocks[0]
expect(block.type).toBe('passthrough')
expect(block.textboxes).toHaveLength(1)
expect(block.strayRuns?.map((r) => r.text).join('')).toBe('Objective')
expect(block.strayStyleId).toBe('SectionHeading')
expect(block.previewText).toContain('Objective')
// untouched block still saves its original bytes
expect(block.originalXml).toBe(withHeading)
})
it('pins the height of an auto-fit box: drops spAutoFit and round-trips fixed', async () => {
const autoFitXml = TEXTBOX_PARAGRAPH.replace(
'<wps:txbx>',
@@ -0,0 +1,196 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/parse'
import { buildDocx } from './helpers/build-docx'
/**
* Legacy VML WordArt (v:textpath, shapetype 136 family) and drawing-canvas
* groups (v:group editas="canvas"), as written by Word 2003-2010. Both used
* to degrade to an opaque "Embedded object" chip; they now surface their text.
*/
const V_NS =
'xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"'
function wordArtPict(
shapeAttrs: string,
inner: string,
pPr = '<w:pPr><w:jc w:val="center"/></w:pPr>',
): string {
return (
`<w:p>${pPr}<w:r><w:pict>` +
`<v:shape ${V_NS} id="wa1" type="#_x0000_t136" ${shapeAttrs}>${inner}</v:shape>` +
'</w:pict></w:r></w:p>'
)
}
describe('VML WordArt (v:textpath) display', () => {
it('renders the textpath string as a sized, styled text box instead of a chip', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: wordArtPict(
'style="width:148.5pt;height:28.5pt" fillcolor="#9400ed" strokecolor="#eaeaea" strokeweight="1pt"',
'<v:textpath style="font-family:&quot;Arial Black&quot;;font-size:20pt" trim="t" fitpath="t" string="My Text Here"/>',
),
}),
)
const block = doc.blocks[0]
expect(block.type).toBe('passthrough')
expect(block.label).toBe('Text box')
expect(block.imageAlign).toBe('center')
const box = block.textboxes?.[0]
expect(box?.widthPx).toBe(198) // 148.5pt
expect(box?.heightPx).toBe(38) // 28.5pt
expect(box?.readOnly).toBe(true)
expect(box?.textOutline).toEqual({ colorHex: 'eaeaea', widthPx: 1.33 })
const run = box?.paras[0]?.runs[0]
expect(box?.paras[0]?.align).toBe('center')
expect(run?.text).toBe('My Text Here')
expect(run?.sizeHalfPoints).toBe(40) // declared 20pt
expect(run?.fontAscii).toBe('Arial Black')
expect(run?.color).toBe('9400ed')
})
it('falls back to the gradient color2 when the shape has no fillcolor, honors stroked="f"', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: wordArtPict(
'style="width:187.5pt;height:28.5pt" stroked="f"',
'<v:fill color2="#aaaaaa" type="gradient"/>' +
'<v:textpath style="font-family:&quot;Arial Black&quot;;font-size:20pt" string="Мой текст"/>',
),
}),
)
const box = doc.blocks[0].textboxes?.[0]
expect(box?.paras[0]?.runs[0]?.color).toBe('aaaaaa')
expect(box?.textOutline).toBeUndefined()
})
it('ignores string-less v:textpath (shapetype template / watermark furniture)', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
`<w:p><w:r><w:pict><v:shapetype ${V_NS} id="_x0000_t136" o:spt="136">` +
'<v:textpath on="t" fitshape="t"/></v:shapetype></w:pict></w:r></w:p>',
}),
)
expect(doc.blocks[0].textboxes).toBeUndefined()
})
})
describe('VML drawing canvas (v:group) textboxes', () => {
const canvasParagraph = (trailing = ''): string =>
`<w:p><w:r><w:pict><v:group ${V_NS} editas="canvas" ` +
'style="width:126pt;height:99pt" coordorigin="3834,5690" coordsize="1976,1533">' +
'<v:shape id="bg" type="#_x0000_t75" style="position:absolute;left:3834;top:5690;width:1976;height:1533" o:preferrelative="f"/>' +
'<v:shape id="tb" type="#_x0000_t202" style="position:absolute;left:4257;top:5969;width:1130;height:1115">' +
'<v:textbox><w:txbxContent><w:p><w:r><w:t>Словарь</w:t></w:r></w:p></w:txbxContent></v:textbox>' +
'</v:shape></v:group></w:pict></w:r>' +
trailing +
'</w:p>'
it('scales group-coordinate children through the canvas extent', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: canvasParagraph() }))
const block = doc.blocks[0]
expect(block.label).toBe('Text box')
const box = block.textboxes?.[0]
// 1130/1976 × 126pt = 72pt = 96px; 1115/1533 × 99pt = 72pt = 96px
expect(box?.widthPx).toBe(96)
expect(box?.heightPx).toBe(96)
// VML strokes default on/black — Word draws the canvas textbox border
expect(box?.borderColor).toBe('000000')
expect(box?.paras[0]?.runs[0]?.text).toBe('Словарь')
})
it('keeps paragraph text next to the canvas visible as a display-only line', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: canvasParagraph('<w:r><w:t xml:space="preserve">Hyperlink line</w:t></w:r>'),
}),
)
const block = doc.blocks[0]
expect(block.label).toBe('Text box')
expect(block.textboxes).toHaveLength(2)
const stray = block.textboxes?.[1]
expect(stray?.readOnly).toBe(true)
expect(stray?.paras[0]?.runs.map((r) => r.text).join('')).toBe('Hyperlink line')
expect(block.previewText).toContain('Словарь')
expect(block.previewText).toContain('Hyperlink line')
})
it('keeps the hyperlink target on stray runs next to the canvas', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: canvasParagraph(
'<w:hyperlink r:id="rId20" w:history="1"><w:r>' +
'<w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr>' +
'<w:t>Hyperlink</w:t></w:r></w:hyperlink>',
),
extraRels:
'<Relationship Id="rId20" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="http://www.google.com" TargetMode="External"/>',
}),
)
const stray = doc.blocks[0].textboxes?.[1]
const run = stray?.paras[0]?.runs[0]
expect(run?.text).toBe('Hyperlink')
expect(run?.link?.href).toBe('http://www.google.com')
})
it('ignores a nested textbox jc when the host paragraph has none', async () => {
const bodyXml =
`<w:p><w:r><w:pict><v:shape ${V_NS} id="tb3" type="#_x0000_t202" style="width:100pt;height:20pt">` +
'<v:textbox><w:txbxContent><w:p><w:pPr><w:jc w:val="center"/></w:pPr>' +
'<w:r><w:t>inner</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape>' +
'</w:pict></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const block = doc.blocks[0]
expect(block.label).toBe('Text box')
expect(block.imageAlign).toBeUndefined()
// the inner paragraph keeps its own alignment inside the box
expect(block.textboxes?.[0]?.paras[0]?.align).toBe('center')
})
it('leaves paragraphs mixing a VML picture with real text on the editable path', async () => {
const bodyXml =
`<w:p><w:r><w:pict><v:shape ${V_NS} id="p1" type="#_x0000_t75" style="width:54pt;height:38.25pt">` +
'<v:imagedata r:id="rId999" o:title=""/></v:shape>' +
'<v:shape id="tb2" type="#_x0000_t202" style="width:100pt;height:20pt">' +
'<v:textbox><w:txbxContent><w:p><w:r><w:t>boxed</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape>' +
'</w:pict></w:r><w:r><w:t>editable text</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
// not converted into a protected textbox block: the run text stays editable
expect(doc.blocks[0].label).not.toBe('Text box')
})
})
describe('w14:textFill run color approximation', () => {
const W14_NS = 'xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"'
it('takes the solid fill color', async () => {
const bodyXml =
`<w:p><w:r><w:rPr><w14:textFill ${W14_NS}><w14:solidFill><w14:srgbClr w14:val="ED7D31"/></w14:solidFill></w14:textFill></w:rPr>` +
'<w:t>Solid</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
expect(doc.blocks[0].runs?.[0]?.color).toBe('ED7D31')
})
it('averages gradient stops (with tint/shade transforms) into one display color', async () => {
const bodyXml =
`<w:p><w:r><w:rPr><w14:textFill ${W14_NS}><w14:gradFill><w14:gsLst>` +
'<w14:gs w14:pos="0"><w14:srgbClr w14:val="ED7D31"><w14:tint w14:val="70000"/></w14:srgbClr></w14:gs>' +
'<w14:gs w14:pos="100000"><w14:srgbClr w14:val="ED7D31"><w14:shade w14:val="50000"/></w14:srgbClr></w14:gs>' +
'</w14:gsLst></w14:gradFill></w14:textFill></w:rPr>' +
'<w:t>Grad</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const color = doc.blocks[0].runs?.[0]?.color
// stop1 = ED7D31 tinted 70%, stop2 = ED7D31 shaded 50%: average is a mid orange
expect(color).toBe('B47144')
})
it('never overrides an explicit w:color', async () => {
const bodyXml =
`<w:p><w:r><w:rPr><w:color w:val="112233"/><w14:textFill ${W14_NS}><w14:solidFill><w14:srgbClr w14:val="ED7D31"/></w14:solidFill></w14:textFill></w:rPr>` +
'<w:t>Explicit</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
expect(doc.blocks[0].runs?.[0]?.color).toBe('112233')
})
})
@@ -0,0 +1,94 @@
import { crc32 } from 'node:zlib'
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 decoyDocumentXml = (text: string) =>
XML_DECL +
'<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
`<w:body><w:p><w:r><w:t>${text}</w:t></w:r></w:p></w:body></w:document>`
function findEocd(bytes: Uint8Array): number {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
for (let i = bytes.length - 22; i >= 0; i--) {
if (view.getUint32(i, true) === 0x06054b50) return i
}
throw new Error('no EOCD')
}
/**
* Give `entry`'s central-directory record a crc-valid Info-ZIP Unicode Path
* (0x7075) extra field claiming the name `claimed`, and clear its UTF-8 flag
* so the field takes effect — the layout of the POI unicode-path sample.
*/
function injectUnicodePath(bytes: Uint8Array, entry: string, claimed: string): Uint8Array {
const eocd = findEocd(bytes)
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
const count = view.getUint16(eocd + 10, true)
const decoder = new TextDecoder()
const encoder = new TextEncoder()
let p = view.getUint32(eocd + 16, true)
for (let i = 0; i < count; i++) {
expect(view.getUint32(p, true)).toBe(0x02014b50)
const nameLen = view.getUint16(p + 28, true)
const extraLen = view.getUint16(p + 30, true)
const commentLen = view.getUint16(p + 32, true)
const recordEnd = p + 46 + nameLen + extraLen + commentLen
if (decoder.decode(bytes.subarray(p + 46, p + 46 + nameLen)) === entry) {
const claimedBytes = encoder.encode(claimed)
const field = new Uint8Array(4 + 5 + claimedBytes.length)
const fv = new DataView(field.buffer)
fv.setUint16(0, 0x7075, true)
fv.setUint16(2, 5 + claimedBytes.length, true)
field[4] = 1
fv.setUint32(5, crc32(encoder.encode(entry)), true)
field.set(claimedBytes, 9)
const out = new Uint8Array(bytes.length + field.length)
out.set(bytes.subarray(0, recordEnd))
out.set(field, recordEnd)
out.set(bytes.subarray(recordEnd), recordEnd + field.length)
const ov = new DataView(out.buffer)
ov.setUint16(p + 8, view.getUint16(p + 8, true) & ~0x800, true) // clear UTF-8 flag
ov.setUint16(p + 30, extraLen + field.length, true)
const newEocd = eocd + field.length
ov.setUint32(newEocd + 12, view.getUint32(eocd + 12, true) + field.length, true) // cd size
return out
}
p = recordEnd
}
throw new Error(`entry not found: ${entry}`)
}
describe('zip unicode-path extra field shadowing (POI unicode-path corpus)', () => {
it('resolves word/document.xml by header name, like Word, not by a 0x7075 rename', async () => {
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>RIGHT</w:t></w:r></w:p>',
extraParts: [
{
path: 'decoy-content.xml',
xml: decoyDocumentXml('WRONG'),
contentType: 'application/xml',
},
],
})
// both entries claim each other's name, like the POI sample: an
// upath-honoring reader swaps them and reads the decoy as the document
const hostile = injectUnicodePath(
injectUnicodePath(bytes, 'decoy-content.xml', 'word/document.xml'),
'word/document.xml',
'decoy-content.xml',
)
const doc = await parseDocx(hostile)
expect(doc.blocks[0].runs).toEqual([{ text: 'RIGHT' }])
})
it('leaves plain zips untouched', async () => {
const bytes = await buildDocx({ bodyXml: '<w:p><w:r><w:t>plain</w:t></w:r></w:p>' })
const doc = await parseDocx(bytes)
expect(doc.blocks[0].runs).toEqual([{ text: 'plain' }])
})
})