Sync snapshot (2026-08-20) (#123)
- Add fully local PDF to Word, PowerPoint, and Excel conversion - Add bring-your-own-key AI providers - Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, and custom OpenAI-compatible endpoints - with a refreshed AI settings UI - Rework the Slides AI editing surface: canonical edit-op registry, atomic transactions with rollback, durable element ids, and batched apply_ops - Improve Slides fidelity: chart, font, gradient, table-style, and text-shaping fixes, plus PPT-parity line editing and adjust handles - Polish Docs: password-protection dialogs, anchored-image wrapping fixes, and selection and clipboard fixes - Add themed dropdowns suite-wide with accent-derived selection states Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
fe2e17403c
commit
f68df70e22
@@ -2,6 +2,7 @@ import type {
|
||||
GeneratedBlock,
|
||||
ImageWrap,
|
||||
ParaFormat,
|
||||
ParaFrame,
|
||||
Run,
|
||||
TabStop,
|
||||
TableCell,
|
||||
@@ -140,6 +141,17 @@ export function patchImageParagraphXml(xml: string, patch: ImagePatch): string {
|
||||
const WRAP_ELEMENT_RE =
|
||||
/<wp:wrapNone\s*\/>|<wp:wrapSquare[^>]*\/>|<wp:wrapSquare[\s\S]*?<\/wp:wrapSquare>|<wp:wrapTight[\s\S]*?<\/wp:wrapTight>|<wp:wrapThrough[\s\S]*?<\/wp:wrapThrough>|<wp:wrapTopAndBottom\s*\/>|<wp:wrapTopAndBottom[\s\S]*?<\/wp:wrapTopAndBottom>/g
|
||||
|
||||
/**
|
||||
* Re-encode ONLY the stacking rank of an existing wp:anchor as Word's
|
||||
* base + rank relativeHeight. Everything else — position basis (relativeFrom),
|
||||
* wrap element, distances — keeps its original bytes, so a picture never
|
||||
* shifts from a pure reorder (or from the save-time harmonization of wild
|
||||
* producer values). No-op on inline images (no wp:anchor).
|
||||
*/
|
||||
export function applyImageZOrder(xml: string, zOrder?: number): string {
|
||||
return xml.replace(/(<wp:anchor[^>]*?relativeHeight=")\d+(")/, `$1${251658240 + (zOrder ?? 0)}$2`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch an image paragraph between inline (in line with text, wrap = null) and floating
|
||||
* (wp:anchor with the given wrap mode). Position/wrap elements are rebuilt;
|
||||
@@ -151,8 +163,9 @@ const WRAP_ELEMENT_RE =
|
||||
export function applyImageWrap(
|
||||
xml: string,
|
||||
wrap: ImageWrap | null,
|
||||
posOffset?: { x: number; y: number },
|
||||
posOffset?: { x: number; y: number; relativeTo?: 'page' },
|
||||
marginAlign?: { h: 'left' | 'center' | 'right'; v: 'top' | 'center' | 'bottom' },
|
||||
zOrder?: number,
|
||||
): string {
|
||||
const hasAnchor = /<wp:anchor[\s>]/.test(xml)
|
||||
// Original wrapTight/wrapThrough bytes (including wp:wrapPolygon) — reused as a whole
|
||||
@@ -180,10 +193,12 @@ export function applyImageWrap(
|
||||
wrap === 'through-right'
|
||||
let position: string
|
||||
if (posOffset !== undefined) {
|
||||
const relH = posOffset.relativeTo ?? 'column'
|
||||
const relV = posOffset.relativeTo ?? 'paragraph'
|
||||
position =
|
||||
'<wp:simplePos x="0" y="0"/>' +
|
||||
`<wp:positionH relativeFrom="column"><wp:posOffset>${Math.round(posOffset.x)}</wp:posOffset></wp:positionH>` +
|
||||
`<wp:positionV relativeFrom="paragraph"><wp:posOffset>${Math.round(posOffset.y)}</wp:posOffset></wp:positionV>`
|
||||
`<wp:positionH relativeFrom="${relH}"><wp:posOffset>${Math.round(posOffset.x)}</wp:posOffset></wp:positionH>` +
|
||||
`<wp:positionV relativeFrom="${relV}"><wp:posOffset>${Math.round(posOffset.y)}</wp:posOffset></wp:positionV>`
|
||||
} else if (marginAlign !== undefined) {
|
||||
position =
|
||||
'<wp:simplePos x="0" y="0"/>' +
|
||||
@@ -211,7 +226,7 @@ export function applyImageWrap(
|
||||
: '<wp:wrapNone/>'
|
||||
const anchorOpen =
|
||||
`<wp:anchor distT="0" distB="0" distL="114300" distR="114300" simplePos="0"` +
|
||||
` relativeHeight="251658240" behindDoc="${behind}" locked="0" layoutInCell="1" allowOverlap="1">`
|
||||
` relativeHeight="${251658240 + (zOrder ?? 0)}" behindDoc="${behind}" locked="0" layoutInCell="1" allowOverlap="1">`
|
||||
if (hasAnchor) {
|
||||
out = out.replace(/<wp:anchor[^>]*>/, anchorOpen)
|
||||
} else {
|
||||
@@ -934,17 +949,41 @@ interface PPrChild {
|
||||
xml: string
|
||||
}
|
||||
|
||||
/** w:spacing element for a ParaFormat ('' when nothing is set) — shared by body and table-cell paragraphs */
|
||||
function paraSpacingXml(format: ParaFormat): string {
|
||||
const attrs: string[] = []
|
||||
if (format.spaceBefore && format.spaceBefore > 0) {
|
||||
attrs.push(`w:before="${Math.round(format.spaceBefore)}"`)
|
||||
}
|
||||
// explicit 0 overrides the style's space-after in Word, so it must be written back
|
||||
if (format.spaceAfter !== undefined && format.spaceAfter >= 0) {
|
||||
attrs.push(`w:after="${Math.round(format.spaceAfter)}"`)
|
||||
}
|
||||
if ((format.lineRule === 'exact' || format.lineRule === 'atLeast') && format.lineRawTwips) {
|
||||
// Exact/at-least line height: write the twips back verbatim (previously only auto was
|
||||
// recognized, so edited paragraphs lost their line spacing)
|
||||
attrs.push(`w:line="${Math.round(format.lineRawTwips)}"`, `w:lineRule="${format.lineRule}"`)
|
||||
} else if (format.lineSpacing && format.lineSpacing > 0) {
|
||||
attrs.push(`w:line="${Math.round(format.lineSpacing * 240)}"`, 'w:lineRule="auto"')
|
||||
}
|
||||
return attrs.length > 0 ? `<w:spacing ${attrs.join(' ')}/>` : ''
|
||||
}
|
||||
|
||||
/** pPr children the ParaFormat model owns (rebuilt on format edits) */
|
||||
function formatPPrChildren(format: ParaFormat | undefined): PPrChild[] {
|
||||
if (!format) return []
|
||||
const out: PPrChild[] = []
|
||||
if (format.pageBreakBefore) out.push({ name: 'w:pageBreakBefore', xml: '<w:pageBreakBefore/>' })
|
||||
if (format.borders) {
|
||||
const style = format.borderStyle
|
||||
const defaultSz = Math.max(2, Math.round(style?.szEighths ?? 4))
|
||||
const space = Math.min(31, Math.max(0, Math.round(style?.spacePt ?? 1)))
|
||||
const defaultColor = style?.color ? escapeXmlAttr(style.color) : 'auto'
|
||||
const line = (side: string, ch: 't' | 'b' | 'l' | 'r') => {
|
||||
const declared = format.borderLines?.[ch]
|
||||
const sz = declared?.szPt ? Math.max(1, Math.round(declared.szPt * 8)) : 4
|
||||
const color = declared?.color ? escapeXmlAttr(declared.color) : 'auto'
|
||||
return `<w:${side} w:val="single" w:sz="${sz}" w:space="1" w:color="${color}"/>`
|
||||
const sz = declared?.szPt ? Math.max(1, Math.round(declared.szPt * 8)) : defaultSz
|
||||
const color = declared?.color ? escapeXmlAttr(declared.color) : defaultColor
|
||||
return `<w:${side} w:val="single" w:sz="${sz}" w:space="${space}" w:color="${color}"/>`
|
||||
}
|
||||
const sides: string[] = []
|
||||
// schema order inside pBdr: top, left, bottom, right
|
||||
@@ -961,27 +1000,8 @@ function formatPPrChildren(format: ParaFormat | undefined): PPrChild[] {
|
||||
})
|
||||
}
|
||||
if (format.bidi) out.push({ name: 'w:bidi', xml: '<w:bidi/>' })
|
||||
const spacingAttrs: string[] = []
|
||||
if (format.spaceBefore && format.spaceBefore > 0) {
|
||||
spacingAttrs.push(`w:before="${Math.round(format.spaceBefore)}"`)
|
||||
}
|
||||
// explicit 0 overrides the style's space-after in Word, so it must be written back
|
||||
if (format.spaceAfter !== undefined && format.spaceAfter >= 0) {
|
||||
spacingAttrs.push(`w:after="${Math.round(format.spaceAfter)}"`)
|
||||
}
|
||||
if ((format.lineRule === 'exact' || format.lineRule === 'atLeast') && format.lineRawTwips) {
|
||||
// Exact/at-least line height: write the twips back verbatim (previously only auto was
|
||||
// recognized, so edited paragraphs lost their line spacing)
|
||||
spacingAttrs.push(
|
||||
`w:line="${Math.round(format.lineRawTwips)}"`,
|
||||
`w:lineRule="${format.lineRule}"`,
|
||||
)
|
||||
} else if (format.lineSpacing && format.lineSpacing > 0) {
|
||||
spacingAttrs.push(`w:line="${Math.round(format.lineSpacing * 240)}"`, 'w:lineRule="auto"')
|
||||
}
|
||||
if (spacingAttrs.length > 0) {
|
||||
out.push({ name: 'w:spacing', xml: `<w:spacing ${spacingAttrs.join(' ')}/>` })
|
||||
}
|
||||
const spacing = paraSpacingXml(format)
|
||||
if (spacing) out.push({ name: 'w:spacing', xml: spacing })
|
||||
const indAttrs: string[] = []
|
||||
// w:left/w:right are signed in OOXML — negative indents (text extending
|
||||
// into the margin) are valid and must survive a paragraph rebuild; the
|
||||
@@ -1011,7 +1031,9 @@ function formatPPrChildren(format: ParaFormat | undefined): PPrChild[] {
|
||||
.join('')
|
||||
out.push({ name: 'w:tabs', xml: `<w:tabs>${tabXml}</w:tabs>` })
|
||||
}
|
||||
if (format.dropCap) {
|
||||
if (format.frame) {
|
||||
out.push({ name: 'w:framePr', xml: framePrXml(format.frame) })
|
||||
} else if (format.dropCap) {
|
||||
const { type, lines } = format.dropCap
|
||||
out.push({
|
||||
name: 'w:framePr',
|
||||
@@ -1025,6 +1047,22 @@ function formatPPrChildren(format: ParaFormat | undefined): PPrChild[] {
|
||||
return out
|
||||
}
|
||||
|
||||
/** positioned paragraph frame (P19): w:framePr with absolute x/y, Word's attribute order */
|
||||
function framePrXml(frame: ParaFrame): string {
|
||||
const attrs = [`w:w="${Math.round(frame.wTwips)}"`]
|
||||
if (frame.hTwips !== undefined) {
|
||||
attrs.push(`w:h="${Math.round(frame.hTwips)}"`, `w:hRule="${frame.hRule ?? 'atLeast'}"`)
|
||||
}
|
||||
attrs.push(
|
||||
`w:wrap="${frame.wrap ?? 'none'}"`,
|
||||
`w:vAnchor="${frame.vAnchor ?? 'page'}"`,
|
||||
`w:hAnchor="${frame.hAnchor ?? 'page'}"`,
|
||||
`w:x="${Math.round(frame.xTwips)}"`,
|
||||
`w:y="${Math.round(frame.yTwips)}"`,
|
||||
)
|
||||
return `<w:framePr ${attrs.join(' ')}/>`
|
||||
}
|
||||
|
||||
const FORMAT_MANAGED_TAGS = new Set([
|
||||
'w:pageBreakBefore',
|
||||
'w:pBdr',
|
||||
@@ -1172,6 +1210,9 @@ function rawTabsUnchanged(raw: string | undefined, stops: TabStop[]): boolean {
|
||||
}
|
||||
|
||||
function rawFramePrUnchanged(raw: string | undefined, f: ParaFormat): boolean {
|
||||
// positioned frames (P19) rebuild whenever set: comparing every attribute
|
||||
// buys nothing — the generated framePr is byte-stable already
|
||||
if (f.frame !== undefined) return raw !== undefined && raw === framePrXml(f.frame)
|
||||
const val = rawAttr(raw, 'w:dropCap')
|
||||
const rawDc =
|
||||
val === 'drop' || val === 'margin'
|
||||
@@ -1246,7 +1287,7 @@ export function mergePPrFormat(rawPPr: string, format: ParaFormat | undefined):
|
||||
// build set of managed tags for this format (base + conditional)
|
||||
const managedTags = new Set(FORMAT_MANAGED_TAGS)
|
||||
if (format?.tabStops !== undefined) managedTags.add('w:tabs')
|
||||
if (format?.dropCap !== undefined) managedTags.add('w:framePr')
|
||||
if (format?.dropCap !== undefined || format?.frame !== undefined) managedTags.add('w:framePr')
|
||||
// only when the model carries a size: otherwise the paragraph-mark rPr stays unmanaged
|
||||
if (format?.emptyRunSizeHalfPoints !== undefined) managedTags.add('w:rPr')
|
||||
const rawChildren = splitXmlChildren(inner)
|
||||
@@ -1573,10 +1614,34 @@ export function generateTableModelXml(model: TableModel, originalTableXml?: stri
|
||||
: percentages.map((value) => Math.max(1, Math.round((value / totalPct) * 9360)))
|
||||
const totalWidth = widths.reduce((sum, value) => sum + value, 0)
|
||||
const border = (name: string) => `<w:${name} w:val="single" w:sz="4" w:space="0" w:color="auto"/>`
|
||||
const sides = ['top', 'left', 'bottom', 'right', 'insideH', 'insideV'] as const
|
||||
// model borders (e.g. 'none' for borderless source tables) win over the
|
||||
// self-contained single-line default
|
||||
const borders =
|
||||
'<w:tblBorders>' +
|
||||
['top', 'left', 'bottom', 'right', 'insideH', 'insideV'].map(border).join('') +
|
||||
sides
|
||||
.map((name) => {
|
||||
const b = model.borders?.[name]
|
||||
if (!b) return model.borders ? '' : border(name)
|
||||
return (
|
||||
`<w:${name} w:val="${escapeXmlAttr(b.style)}"` +
|
||||
(b.szEighths != null ? ` w:sz="${Math.round(b.szEighths)}"` : '') +
|
||||
` w:space="0" w:color="${escapeXmlAttr(b.color ?? 'auto')}"/>`
|
||||
)
|
||||
})
|
||||
.join('') +
|
||||
'</w:tblBorders>'
|
||||
const marSides = ['top', 'left', 'bottom', 'right'] as const
|
||||
const cellMar = model.cellMarTwips
|
||||
? '<w:tblCellMar>' +
|
||||
marSides
|
||||
.map((name) => {
|
||||
const w = model.cellMarTwips?.[name]
|
||||
return w != null ? `<w:${name} w:w="${Math.round(w)}" w:type="dxa"/>` : ''
|
||||
})
|
||||
.join('') +
|
||||
'</w:tblCellMar>'
|
||||
: ''
|
||||
const grid = `<w:tblGrid>${widths.map((width) => `<w:gridCol w:w="${width}"/>`).join('')}</w:tblGrid>`
|
||||
const rows = model.rows
|
||||
.map((row, ri) => {
|
||||
@@ -1610,10 +1675,24 @@ export function generateTableModelXml(model: TableModel, originalTableXml?: stri
|
||||
const originalTblPr = originalTableXml?.match(
|
||||
/<w:tblPr(?:\s[^>]*)?>[\s\S]*?<\/w:tblPr>|<w:tblPr(?:\s[^>]*)?\/>/,
|
||||
)?.[0]
|
||||
const tblInd =
|
||||
model.indentTwips && Math.round(model.indentTwips) !== 0
|
||||
? `<w:tblInd w:w="${Math.round(model.indentTwips)}" w:type="dxa"/>`
|
||||
: ''
|
||||
// floating table (P19 canvas): tblpPr + tblOverlap lead the fresh tblPr
|
||||
// (CT_TblPr order: tblStyle, tblpPr, tblOverlap, …, tblW)
|
||||
const tblpPr = model.floatPos
|
||||
? `<w:tblpPr w:leftFromText="0" w:rightFromText="0"` +
|
||||
` w:vertAnchor="${model.floatPos.vertAnchor ?? 'page'}"` +
|
||||
` w:horzAnchor="${model.floatPos.horzAnchor ?? 'page'}"` +
|
||||
` w:tblpX="${Math.round(model.floatPos.xTwips)}"` +
|
||||
` w:tblpY="${Math.round(model.floatPos.yTwips)}"/>` +
|
||||
'<w:tblOverlap w:val="overlap"/>'
|
||||
: ''
|
||||
let tblPr =
|
||||
originalTblPr ??
|
||||
`<w:tblPr><w:tblW w:w="${totalWidth}" w:type="dxa"/>${borders}` +
|
||||
'<w:tblLayout w:type="fixed"/></w:tblPr>'
|
||||
`<w:tblPr>${tblpPr}<w:tblW w:w="${totalWidth}" w:type="dxa"/>${tblInd}${borders}` +
|
||||
`<w:tblLayout w:type="fixed"/>${cellMar}</w:tblPr>`
|
||||
// Table style reference: '' = remove, non-empty = replace/insert (tblStyle is the
|
||||
// first tblPr child)
|
||||
if (model.tblStyleId !== undefined) {
|
||||
@@ -2054,6 +2133,7 @@ const RUN_MANAGED_GROUPS: Array<{ key: string; tags: string[] }> = [
|
||||
{ key: 'underline', tags: ['w:u'] },
|
||||
{ key: 'shading', tags: ['w:shd'] },
|
||||
{ key: 'vertAlign', tags: ['w:vertAlign'] },
|
||||
{ key: 'rtl', tags: ['w:rtl'] },
|
||||
{ key: 'rPrChange', tags: ['w:rPrChange'] },
|
||||
]
|
||||
|
||||
@@ -2069,11 +2149,17 @@ function rawBool(xml: string | undefined): boolean {
|
||||
}
|
||||
|
||||
/** rFonts built from the model alone (no original element to preserve).
|
||||
* Latin-only keeps eastAsia empty; a lone primary font fills every slot (legacy behavior). */
|
||||
function freshRFontsXml(font: string | undefined, fontAscii: string | undefined): string {
|
||||
const a = escapeXmlAttr(fontAscii ?? font ?? '')
|
||||
* Latin-only keeps eastAsia empty; a lone primary font fills every slot (legacy behavior);
|
||||
* a complex-script font fills the cs slot instead of mirroring the ascii font. */
|
||||
function freshRFontsXml(
|
||||
font: string | undefined,
|
||||
fontAscii: string | undefined,
|
||||
fontCs?: string,
|
||||
): string {
|
||||
const a = escapeXmlAttr(fontAscii ?? font ?? fontCs ?? '')
|
||||
const ea = font ? ` w:eastAsia="${escapeXmlAttr(font)}"` : ''
|
||||
return `<w:rFonts w:ascii="${a}"${ea} w:hAnsi="${a}" w:cs="${a}"/>`
|
||||
const cs = fontCs ? escapeXmlAttr(fontCs) : a
|
||||
return `<w:rFonts w:ascii="${a}"${ea} w:hAnsi="${a}" w:cs="${cs}"/>`
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2100,6 +2186,7 @@ function mergeRFontsXml(rawXml: string, run: Run): string {
|
||||
if (run.font && (hadEastAsia || run.font !== rawPrimary)) {
|
||||
set('w:eastAsia', 'w:eastAsiaTheme', run.font)
|
||||
}
|
||||
if (run.fontCs) set('w:cs', 'w:cstheme', run.fontCs)
|
||||
return `<w:rFonts${[...attrs].map(([k, v]) => ` ${k}="${v}"`).join('')}/>`
|
||||
}
|
||||
|
||||
@@ -2140,8 +2227,8 @@ function modelRPrChildren(run: Run, insideLink: boolean): PPrChild[] {
|
||||
if (insideLink) out.push({ name: 'w:rStyle', xml: '<w:rStyle w:val="Hyperlink"/>' })
|
||||
else if (run.styleId)
|
||||
out.push({ name: 'w:rStyle', xml: `<w:rStyle w:val="${escapeXmlAttr(run.styleId)}"/>` })
|
||||
if (run.font || run.fontAscii) {
|
||||
out.push({ name: 'w:rFonts', xml: freshRFontsXml(run.font, run.fontAscii) })
|
||||
if (run.font || run.fontAscii || run.fontCs) {
|
||||
out.push({ name: 'w:rFonts', xml: freshRFontsXml(run.font, run.fontAscii, run.fontCs) })
|
||||
}
|
||||
// the Cs twins carry the same flag for complex-script text; without them clicking Bold
|
||||
// on Arabic or Hebrew changes nothing on screen, which is what Word writes too
|
||||
@@ -2169,6 +2256,7 @@ function modelRPrChildren(run: Run, insideLink: boolean): PPrChild[] {
|
||||
}
|
||||
if (run.vertAlign)
|
||||
out.push({ name: 'w:vertAlign', xml: `<w:vertAlign w:val="${run.vertAlign}"/>` })
|
||||
if (run.rtl) out.push({ name: 'w:rtl', xml: '<w:rtl/>' })
|
||||
const rPrChange = revisionRPrChangeXml(run)
|
||||
if (rPrChange) out.push({ name: 'w:rPrChange', xml: rPrChange })
|
||||
return out
|
||||
@@ -2215,10 +2303,19 @@ export function mergeRPrModel(rawRPr: string, run: Run, insideLink: boolean): st
|
||||
return raw === modeled || (raw === 'Hyperlink' && !modeled)
|
||||
}
|
||||
case 'rFonts': {
|
||||
// mirrors the parse side: primary = eastAsia ?? ascii ?? hAnsi, latin = ascii ?? hAnsi
|
||||
// mirrors the parse side: primary = eastAsia ?? ascii ?? hAnsi, latin = ascii ?? hAnsi,
|
||||
// complex-script = literal w:cs
|
||||
const attrs = rawOf('w:rFonts')
|
||||
const ascii = rawAttr(attrs, 'w:ascii') ?? rawAttr(attrs, 'w:hAnsi')
|
||||
return (rawAttr(attrs, 'w:eastAsia') ?? ascii) === run.font && ascii === run.fontAscii
|
||||
// an absent model fontCs is "untouched", not a removal: editor-rebuilt
|
||||
// Runs drop unmodeled fields, and losing w:cs on an unrelated edit
|
||||
// would corrupt complex-script runs (mergeRFontsXml likewise only
|
||||
// writes w:cs when the model carries one)
|
||||
return (
|
||||
(rawAttr(attrs, 'w:eastAsia') ?? ascii) === run.font &&
|
||||
ascii === run.fontAscii &&
|
||||
(run.fontCs === undefined || rawAttr(attrs, 'w:cs') === run.fontCs)
|
||||
)
|
||||
}
|
||||
case 'bold':
|
||||
return rawBool(rawOf(cs ? 'w:bCs' : 'w:b')) === !!run.bold
|
||||
@@ -2254,6 +2351,8 @@ export function mergeRPrModel(rawRPr: string, run: Run, insideLink: boolean): st
|
||||
const modeled = raw === 'superscript' || raw === 'subscript' ? raw : undefined
|
||||
return modeled === run.vertAlign
|
||||
}
|
||||
case 'rtl':
|
||||
return rawBool(rawOf('w:rtl')) === !!run.rtl
|
||||
case 'rPrChange':
|
||||
return !!rawOf('w:rPrChange') === !!run.rPrChange
|
||||
default:
|
||||
@@ -2373,6 +2472,178 @@ export function buildTextboxParagraphXml(opts?: {
|
||||
return `<w:p><w:r>${alternateContent}</w:r></w:p>`
|
||||
}
|
||||
|
||||
/** one paragraph of anchored-textbox content: real runs plus ParaFormat-owned pPr */
|
||||
export interface TextboxContentParagraph {
|
||||
runs: Run[]
|
||||
format?: ParaFormat
|
||||
}
|
||||
|
||||
export interface AnchoredTextboxOptions {
|
||||
/**
|
||||
* 'paragraph': the box rides its holder paragraph through the flow (card
|
||||
* regions); 'page': absolute page coordinates (newsletter regions).
|
||||
*/
|
||||
anchor: 'paragraph' | 'page'
|
||||
/**
|
||||
* EMU offsets. paragraph anchor: x from the text column, y from the holder
|
||||
* paragraph; page anchor: both from the page edges.
|
||||
*/
|
||||
xEmu: number
|
||||
yEmu: number
|
||||
widthEmu: number
|
||||
heightEmu: number
|
||||
paragraphs: TextboxContentParagraph[]
|
||||
/** wp:docPr id / name suffix (caller must keep unique) */
|
||||
id?: number
|
||||
/** solid interior fill (RRGGBB); omitted = transparent */
|
||||
fillHex?: string
|
||||
/** border color (RRGGBB); omitted = no outline */
|
||||
borderHex?: string
|
||||
/** text insets in EMU; omitted = Word defaults (91440 horizontal / 45720 vertical) */
|
||||
insetsEmu?: { l: number; t: number; r: number; b: number }
|
||||
/** corner radius in EMU; maps to a:prstGeom roundRect with the matching adj */
|
||||
cornerRadiusEmu?: number
|
||||
/** written as relativeHeight base + zOrder (P16 z discipline) */
|
||||
zOrder?: number
|
||||
behindDoc?: boolean
|
||||
/** default: paragraph anchor wraps topAndBottom, page anchor wraps none */
|
||||
wrap?: 'topAndBottom' | 'none'
|
||||
/** exact line height (twips) for the holder <w:p>, so the anchor row adds no visible height */
|
||||
holderLineTwips?: number
|
||||
/** spacing-before (twips) on the holder <w:p> — the region's slot in the caller's spacing chain */
|
||||
holderSpacingBeforeTwips?: number
|
||||
/** page-break-before on the holder <w:p> (region starts its page) */
|
||||
holderPageBreakBefore?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a <w:p> holding a floating WPS text box whose content is real,
|
||||
* editable w:p paragraphs (P20 region container). Unlike
|
||||
* buildTextboxParagraphXml (cursor-position UI insert), this variant takes
|
||||
* explicit geometry, fill, insets and z-order — pdf2docx uses it to rebuild
|
||||
* measured card/column regions.
|
||||
*/
|
||||
export function buildAnchoredTextboxParagraphXml(opts: AnchoredTextboxOptions): string {
|
||||
const id = opts.id ?? 1
|
||||
const { xEmu, yEmu, widthEmu, heightEmu } = opts
|
||||
|
||||
const contentParaXml = (p: TextboxContentParagraph): string => {
|
||||
const children = formatPPrChildren(p.format)
|
||||
children.sort((a, b) => PPR_CHILD_ORDER.indexOf(a.name) - PPR_CHILD_ORDER.indexOf(b.name))
|
||||
const pPr = children.length > 0 ? `<w:pPr>${children.map((c) => c.xml).join('')}</w:pPr>` : ''
|
||||
return `<w:p>${pPr}${inlineRunsXml(p.runs)}</w:p>`
|
||||
}
|
||||
const txbxContent = `<w:txbxContent>${opts.paragraphs.map(contentParaXml).join('')}</w:txbxContent>`
|
||||
|
||||
// roundRect radius = adj / 100000 * min(cx, cy); clamp to the spec's half-side max
|
||||
const geom = opts.cornerRadiusEmu
|
||||
? `<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val ${Math.min(
|
||||
50000,
|
||||
Math.max(
|
||||
0,
|
||||
Math.round((opts.cornerRadiusEmu / Math.max(1, Math.min(widthEmu, heightEmu))) * 100000),
|
||||
),
|
||||
)}"/></a:avLst></a:prstGeom>`
|
||||
: `<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>`
|
||||
const fill = opts.fillHex
|
||||
? `<a:solidFill><a:srgbClr val="${escapeXmlAttr(opts.fillHex)}"/></a:solidFill>`
|
||||
: `<a:noFill/>`
|
||||
const line = opts.borderHex
|
||||
? `<a:ln><a:solidFill><a:srgbClr val="${escapeXmlAttr(opts.borderHex)}"/></a:solidFill></a:ln>`
|
||||
: `<a:ln><a:noFill/></a:ln>`
|
||||
const spPr =
|
||||
`<wps:spPr>` +
|
||||
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="${widthEmu}" cy="${heightEmu}"/></a:xfrm>` +
|
||||
geom +
|
||||
fill +
|
||||
line +
|
||||
`</wps:spPr>`
|
||||
|
||||
const ins = opts.insetsEmu ?? { l: 91440, t: 45720, r: 91440, b: 45720 }
|
||||
// fixed box: a:noAutofit keeps overflowing content from growing the region
|
||||
const bodyPr =
|
||||
`<wps:bodyPr wrap="square" lIns="${Math.round(ins.l)}" tIns="${Math.round(ins.t)}" ` +
|
||||
`rIns="${Math.round(ins.r)}" bIns="${Math.round(ins.b)}" anchor="t"><a:noAutofit/></wps:bodyPr>`
|
||||
|
||||
const wsp =
|
||||
`<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">` +
|
||||
`<wps:cNvSpPr txBox="1"/>` +
|
||||
spPr +
|
||||
`<wps:txbx>${txbxContent}</wps:txbx>` +
|
||||
bodyPr +
|
||||
`</wps:wsp>`
|
||||
|
||||
const graphic =
|
||||
`<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">` +
|
||||
`<a:graphicData xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ` +
|
||||
`uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">${wsp}</a:graphicData>` +
|
||||
`</a:graphic>`
|
||||
|
||||
const relFrom = opts.anchor === 'page' ? 'page' : undefined
|
||||
const posH =
|
||||
`<wp:positionH relativeFrom="${relFrom ?? 'column'}">` +
|
||||
`<wp:posOffset>${Math.round(xEmu)}</wp:posOffset></wp:positionH>`
|
||||
const posV =
|
||||
`<wp:positionV relativeFrom="${relFrom ?? 'paragraph'}">` +
|
||||
`<wp:posOffset>${Math.round(yEmu)}</wp:posOffset></wp:positionV>`
|
||||
const wrapMode = opts.wrap ?? (opts.anchor === 'page' ? 'none' : 'topAndBottom')
|
||||
const wrapEl = wrapMode === 'topAndBottom' ? '<wp:wrapTopAndBottom/>' : '<wp:wrapNone/>'
|
||||
|
||||
const anchor =
|
||||
`<wp:anchor xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ` +
|
||||
`distT="0" distB="0" distL="0" distR="0" simplePos="0" ` +
|
||||
`relativeHeight="${251658240 + (opts.zOrder ?? 0)}" behindDoc="${opts.behindDoc ? 1 : 0}" ` +
|
||||
`locked="0" layoutInCell="1" allowOverlap="1">` +
|
||||
`<wp:simplePos x="0" y="0"/>` +
|
||||
posH +
|
||||
posV +
|
||||
`<wp:extent cx="${widthEmu}" cy="${heightEmu}"/>` +
|
||||
`<wp:effectExtent l="0" t="0" r="0" b="0"/>` +
|
||||
wrapEl +
|
||||
`<wp:docPr id="${id}" name="Region ${id}"/>` +
|
||||
graphic +
|
||||
`</wp:anchor>`
|
||||
|
||||
// Requires="wps" must resolve at the AlternateContent scope, or Word
|
||||
// reports the whole file as unreadable content
|
||||
const mcNs =
|
||||
'xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" ' +
|
||||
'xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"'
|
||||
const vmlTag = opts.cornerRadiusEmu ? 'v:roundrect' : 'v:rect'
|
||||
const vmlFill = opts.fillHex
|
||||
? ` fillcolor="#${escapeXmlAttr(opts.fillHex)}" filled="t"`
|
||||
: ' filled="f"'
|
||||
const vmlRect =
|
||||
`<${vmlTag} xmlns:v="urn:schemas-microsoft-com:vml" ` +
|
||||
`style="position:absolute;margin-left:${xEmu / EMU_PER_PT}pt;margin-top:${yEmu / EMU_PER_PT}pt;` +
|
||||
`width:${widthEmu / EMU_PER_PT}pt;height:${heightEmu / EMU_PER_PT}pt"${vmlFill} stroked="f">` +
|
||||
`<v:textbox>${txbxContent}</v:textbox>` +
|
||||
`</${vmlTag}>`
|
||||
|
||||
const alternateContent =
|
||||
`<mc:AlternateContent ${mcNs}>` +
|
||||
`<mc:Choice Requires="wps"><w:drawing>${anchor}</w:drawing></mc:Choice>` +
|
||||
`<mc:Fallback><w:pict>${vmlRect}</w:pict></mc:Fallback>` +
|
||||
`</mc:AlternateContent>`
|
||||
|
||||
const holderSpacing =
|
||||
opts.holderLineTwips !== undefined || opts.holderSpacingBeforeTwips !== undefined
|
||||
? `<w:spacing` +
|
||||
(opts.holderSpacingBeforeTwips
|
||||
? ` w:before="${Math.round(opts.holderSpacingBeforeTwips)}"`
|
||||
: '') +
|
||||
` w:after="0"` +
|
||||
(opts.holderLineTwips !== undefined
|
||||
? ` w:line="${Math.round(opts.holderLineTwips)}" w:lineRule="exact"`
|
||||
: '') +
|
||||
`/>`
|
||||
: ''
|
||||
const holderBreak = opts.holderPageBreakBefore ? '<w:pageBreakBefore/>' : ''
|
||||
const holderPPr =
|
||||
holderSpacing || holderBreak ? `<w:pPr>${holderBreak}${holderSpacing}</w:pPr>` : ''
|
||||
return `<w:p>${holderPPr}<w:r>${alternateContent}</w:r></w:p>`
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a <w:p> fragment for a floating WPS shape (prstGeom) with optional
|
||||
* text content. Same anchor structure as buildTextboxParagraphXml.
|
||||
|
||||
@@ -12,9 +12,13 @@ export {
|
||||
export {
|
||||
TABLE_HEADER_FILL,
|
||||
applyImageWrap,
|
||||
applyImageZOrder,
|
||||
buildAnchoredTextboxParagraphXml,
|
||||
buildShapeParagraphXml,
|
||||
buildTextboxParagraphXml,
|
||||
buildWordArtParagraphXml,
|
||||
type AnchoredTextboxOptions,
|
||||
type TextboxContentParagraph,
|
||||
generateCaptionXml,
|
||||
generateIndexFieldXml,
|
||||
generateParagraphXml,
|
||||
|
||||
@@ -108,8 +108,12 @@ function noteRichParas(entryXml: string): NoteRun[][] {
|
||||
}
|
||||
out.push(runs)
|
||||
}
|
||||
// Strip the first paragraph's leading space (spacer after the self-reference mark)
|
||||
if (out[0]?.[0]) out[0][0].text = out[0][0].text.replace(/^\s+/, '')
|
||||
// Strip the first paragraph's leading space (spacer after the self-reference
|
||||
// mark); a spacer that was its own run empties out and is dropped entirely
|
||||
if (out[0]?.[0]) {
|
||||
out[0][0].text = out[0][0].text.replace(/^\s+/, '')
|
||||
if (out[0][0].text === '') out[0].shift()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -161,9 +165,51 @@ function separatorEntries(kind: NoteKind): string {
|
||||
)
|
||||
}
|
||||
|
||||
/** one rich display run → run XML (size/font/bold…; save-side of NoteRun) */
|
||||
function noteRunXml(run: NoteRun): string {
|
||||
const props: string[] = []
|
||||
const fonts: string[] = []
|
||||
if (run.fontAscii) {
|
||||
fonts.push(
|
||||
`w:ascii="${escapeXmlAttr(run.fontAscii)}" w:hAnsi="${escapeXmlAttr(run.fontAscii)}"`,
|
||||
)
|
||||
}
|
||||
if (run.font) fonts.push(`w:eastAsia="${escapeXmlAttr(run.font)}"`)
|
||||
if (fonts.length > 0) props.push(`<w:rFonts ${fonts.join(' ')}/>`)
|
||||
if (run.bold) props.push('<w:b/>')
|
||||
if (run.italic) props.push('<w:i/>')
|
||||
if (run.underline) props.push('<w:u w:val="single"/>')
|
||||
if (run.strike) props.push('<w:strike/>')
|
||||
if (run.color) props.push(`<w:color w:val="${escapeXmlAttr(run.color)}"/>`)
|
||||
if (run.sizeHalfPoints) {
|
||||
props.push(`<w:sz w:val="${run.sizeHalfPoints}"/><w:szCs w:val="${run.sizeHalfPoints}"/>`)
|
||||
}
|
||||
const rPr = props.length > 0 ? `<w:rPr>${props.join('')}</w:rPr>` : ''
|
||||
return `<w:r>${rPr}<w:t xml:space="preserve">${escapeXmlText(run.text)}</w:t></w:r>`
|
||||
}
|
||||
|
||||
function noteEntryXml(kind: NoteKind, note: NoteInfo): string {
|
||||
const entry = ENTRY[kind]
|
||||
const refTag = kind === 'footnote' ? 'w:footnoteRef' : 'w:endnoteRef'
|
||||
if (note.richParas?.length) {
|
||||
// rich rebuild (P17): runs keep their measured size/font, the reference
|
||||
// mark + spacer shrink to the first run's size, and the paragraph pins
|
||||
// single spacing — a note rendered from measured source content must not
|
||||
// inflate past its source area via template docDefaults (after=120,
|
||||
// line=276) or a body-sized marker run
|
||||
const paras = note.richParas.map((runs, i) => {
|
||||
const sz = runs[0]?.sizeHalfPoints
|
||||
const szXml = sz ? `<w:sz w:val="${sz}"/><w:szCs w:val="${sz}"/>` : ''
|
||||
const refRun =
|
||||
i === 0
|
||||
? `<w:r><w:rPr><w:vertAlign w:val="superscript"/>${szXml}</w:rPr><${refTag}/></w:r>` +
|
||||
`<w:r>${sz ? `<w:rPr>${szXml}</w:rPr>` : ''}<w:t xml:space="preserve"> </w:t></w:r>`
|
||||
: ''
|
||||
const pPr = '<w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr>'
|
||||
return `<w:p>${pPr}${refRun}${runs.map(noteRunXml).join('')}</w:p>`
|
||||
})
|
||||
return `<${entry} w:id="${escapeXmlAttr(note.id)}">${paras.join('')}</${entry}>`
|
||||
}
|
||||
const paras = note.text.split('\n').map((line, i) => {
|
||||
// OOXML convention: the note body starts with the self-reference mark
|
||||
const refRun =
|
||||
|
||||
@@ -296,6 +296,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
blocks.push(await buildBlock(el, i, xml, buildCtx))
|
||||
}
|
||||
applyTocEntryNumbers(blocks, numbering)
|
||||
normalizeImageZOrders(blocks)
|
||||
|
||||
const header = await readHeaderFooterPart(
|
||||
zip,
|
||||
@@ -1277,6 +1278,8 @@ function buildTextParagraph(
|
||||
if (runs.length === 0) {
|
||||
const emptySz = emptyParaSizeHalfPoints(pNode, pPr)
|
||||
if (emptySz) format = { ...(format ?? {}), emptyRunSizeHalfPoints: emptySz }
|
||||
const emptyFont = emptyParaMarkFont(pNode, pPr)
|
||||
if (emptyFont) format = { ...(format ?? {}), emptyRunFontFamily: emptyFont }
|
||||
}
|
||||
|
||||
// allowOverlap="0" colliding with a sibling anchor (tdf#134114): Word displaces
|
||||
@@ -2053,6 +2056,8 @@ interface DrawingAnchorMeta {
|
||||
offsetYEmu?: number
|
||||
/** wrapNone (front) / behindDoc anchors leave the text flow entirely */
|
||||
noWrap?: boolean
|
||||
/** wp:wrapTopAndBottom: body text is excluded from the drawing's vertical band */
|
||||
topBottom?: boolean
|
||||
anchored?: boolean
|
||||
/** wp:positionH/V relativeFrom */
|
||||
relH?: string
|
||||
@@ -2140,6 +2145,12 @@ function drawingAnchorMeta(frag: string): DrawingAnchorMeta {
|
||||
meta.extentYEmu = parseInt(extent[2], 10)
|
||||
}
|
||||
if (frag.includes('<wp:wrapNone') || /behindDoc="(?:1|true)"/.test(anchorTag)) meta.noWrap = true
|
||||
// the anchor's own wrap element sits before a:graphic; a nested drawing's
|
||||
// wrap must not leak up. behindDoc="1" + wrapTopAndBottom coexist in
|
||||
// generated docs — Word still excludes the band (behindDoc is z-order only)
|
||||
const graphicAt = frag.indexOf('<a:graphic')
|
||||
const ownXml = graphicAt === -1 ? frag : frag.slice(0, graphicAt)
|
||||
if (ownXml.includes('<wp:wrapTopAndBottom')) meta.topBottom = true
|
||||
return meta
|
||||
}
|
||||
|
||||
@@ -2536,6 +2547,7 @@ function extractTextboxes(
|
||||
box: TextboxDisplay,
|
||||
meta: DrawingAnchorMeta,
|
||||
pagePos: ResolvedAnchorPos | null,
|
||||
grouped = false,
|
||||
): void => {
|
||||
if (!meta.anchored) return
|
||||
// page/margin-anchored drawing sitting outside the body column (Word
|
||||
@@ -2550,6 +2562,26 @@ function extractTextboxes(
|
||||
}
|
||||
if (meta.offsetXEmu !== undefined) box.offsetXEmu = (box.offsetXEmu ?? 0) + meta.offsetXEmu
|
||||
if (meta.offsetYEmu !== undefined) box.offsetYEmu = (box.offsetYEmu ?? 0) + meta.offsetYEmu
|
||||
// wrapTopAndBottom (Word): body text is excluded from the box's whole
|
||||
// vertical band. The box floats at its offset and the anchor paragraph
|
||||
// reserves flow height down to the box bottom (union over its boxes).
|
||||
if (meta.topBottom && (meta.relV === 'paragraph' || meta.relV === 'line')) {
|
||||
// wp:extent cy covers the whole drawing: a usable height fallback only
|
||||
// for an ungrouped shape (each group child would claim the group height)
|
||||
const h =
|
||||
box.heightPx ??
|
||||
(!grouped && meta.extentYEmu !== undefined
|
||||
? Math.round(meta.extentYEmu / EMU_PER_PX)
|
||||
: undefined)
|
||||
if (h !== undefined) {
|
||||
const top = Math.round((box.offsetYEmu ?? 0) / EMU_PER_PX)
|
||||
if (top + h > 0) {
|
||||
box.bandTopPx = top
|
||||
box.bandBottomPx = top + h
|
||||
}
|
||||
}
|
||||
box.floating = true
|
||||
}
|
||||
if (meta.noWrap || multiDrawing) box.floating = true
|
||||
}
|
||||
|
||||
@@ -2582,7 +2614,7 @@ function extractTextboxes(
|
||||
// grouped shapes place absolutely at their mapped offset like Word
|
||||
box.floating = true
|
||||
}
|
||||
applyAnchor(box, meta, pagePos)
|
||||
applyAnchor(box, meta, pagePos, ctm !== null)
|
||||
out.push(box)
|
||||
}
|
||||
// document-order walk (box order must match w:txbxContent order for the
|
||||
@@ -3009,6 +3041,26 @@ function emptyParaSizeHalfPoints(pNode: XNode, pPr: XNode | undefined): number |
|
||||
return Number.isFinite(n) && n > 0 ? n : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* w:rFonts governing a run-less paragraph's line height: same sources as
|
||||
* emptyParaSizeHalfPoints — Word lays the empty line with the mark's face
|
||||
* metrics, not the document default face.
|
||||
*/
|
||||
function emptyParaMarkFont(pNode: XNode, pPr: XNode | undefined): string | undefined {
|
||||
const pick = (rPr: XNode | undefined): string | undefined => {
|
||||
const a = attrsOf(findChild(rPr ?? {}, 'w:rFonts') ?? {})
|
||||
return a['w:ascii'] ?? a['w:hAnsi'] ?? a['w:eastAsia']
|
||||
}
|
||||
let font = pPr ? pick(findChild(pPr, 'w:rPr')) : undefined
|
||||
if (!font) {
|
||||
for (const r of findChildren(pNode, 'w:r')) {
|
||||
const v = pick(findChild(r, 'w:rPr'))
|
||||
if (v) font = v
|
||||
}
|
||||
}
|
||||
return font
|
||||
}
|
||||
|
||||
function extractRuns(
|
||||
pNode: XNode,
|
||||
ctx: BuildContext,
|
||||
@@ -3452,13 +3504,20 @@ function buildRun(
|
||||
if (color) run.color = color
|
||||
const sz = attrsOf(findChild(rPr, cs ? 'w:szCs' : 'w:sz') ?? {})['w:val']
|
||||
if (sz) run.sizeHalfPoints = parseInt(sz, 10) || undefined
|
||||
const rf = themedRFonts(attrsOf(findChild(rPr, 'w:rFonts') ?? {}), themeFonts)
|
||||
const rfAttrs = attrsOf(findChild(rPr, 'w:rFonts') ?? {})
|
||||
const rf = themedRFonts(rfAttrs, themeFonts)
|
||||
const font = rf.eastAsia ?? rf.ascii ?? rf.hAnsi
|
||||
if (font) run.font = font
|
||||
if (rf.eaSlotEmpty && font && font === rf.eastAsia) run.eaSlotEmpty = true
|
||||
const fontAscii = rf.ascii ?? rf.hAnsi
|
||||
if (fontAscii) run.fontAscii = fontAscii
|
||||
// complex-script slot: literal attribute only — theme refs (w:cstheme) stay in
|
||||
// rawRPr so untouched runs keep their original bytes
|
||||
if (rfAttrs['w:cs']) run.fontCs = rfAttrs['w:cs']
|
||||
// theme-resolved cs font for display consumers
|
||||
if (rf.cs) run.csFont = rf.cs
|
||||
const rtl = onOffOf(rPr, 'w:rtl')
|
||||
if (rtl !== undefined) run.rtl = rtl
|
||||
const spc = parseInt(attrsOf(findChild(rPr, 'w:spacing') ?? {})['w:val'] ?? '', 10)
|
||||
if (spc) run.charSpacingTwips = spc
|
||||
// w:caps wins over w:smallCaps when both are on (Word)
|
||||
@@ -3522,6 +3581,7 @@ function buildRun(
|
||||
run.text = decoded
|
||||
delete run.font
|
||||
delete run.fontAscii
|
||||
delete run.fontCs
|
||||
if (run.rawRPr) run.rawRPr = run.rawRPr.replace(/<w:rFonts[^>]*\/>/, '')
|
||||
}
|
||||
}
|
||||
@@ -4101,10 +4161,12 @@ function extractCell(tc: XNode, ctx: BuildContext, depth: number): TableCell {
|
||||
: undefined
|
||||
const runs = extractRuns(p, ctx, [], [], true)
|
||||
const emptySz = runs.length === 0 ? emptyParaSizeHalfPoints(p, pPr) : undefined
|
||||
const emptyFont = runs.length === 0 ? emptyParaMarkFont(p, pPr) : undefined
|
||||
richParas.push({
|
||||
...format,
|
||||
...(cellStyleId ? { styleId: cellStyleId } : {}),
|
||||
...(emptySz ? { emptyRunSizeHalfPoints: emptySz } : {}),
|
||||
...(emptyFont ? { emptyRunFontFamily: emptyFont } : {}),
|
||||
...(list ? { list } : {}),
|
||||
runs,
|
||||
})
|
||||
@@ -4192,6 +4254,10 @@ async function hfImages(zip: JSZip, partPath: string, partXml: string): Promise<
|
||||
image.floating = true
|
||||
const anchorTag = /<wp:anchor[^>]*>/.exec(frag)?.[0] ?? ''
|
||||
if (/behindDoc="(?:1|true)"/.test(anchorTag)) image.behind = true
|
||||
const wrap = /<wp:wrap(None|Square|Tight|Through|TopAndBottom)[\s/>]/.exec(frag)?.[1]
|
||||
if (wrap) {
|
||||
image.wrap = wrap === 'TopAndBottom' ? 'topBottom' : (wrap.toLowerCase() as HfImage['wrap'])
|
||||
}
|
||||
readAnchorPos(frag, image)
|
||||
} else {
|
||||
const align = paraAlignAt(m.index!)
|
||||
@@ -4235,7 +4301,9 @@ async function hfImages(zip: JSZip, partPath: string, partXml: string): Promise<
|
||||
|
||||
/** wp:anchor wp:positionH/V of a header/footer image: wp:align keeps the VML-style
|
||||
* alignment fields, wp:posOffset (EMU) becomes a px offset from the page edge or
|
||||
* margin box (paragraph/column/character origins approximate to margin). */
|
||||
* margin box (horizontal paragraph/column/character origins approximate to margin;
|
||||
* vertical paragraph/line keeps 'paragraph' so body push-down can measure from the
|
||||
* header strip top). */
|
||||
function readAnchorPos(frag: string, image: HfImage): void {
|
||||
for (const axis of ['H', 'V'] as const) {
|
||||
const m = new RegExp(
|
||||
@@ -4253,13 +4321,17 @@ function readAnchorPos(frag: string, image: HfImage): void {
|
||||
}
|
||||
} else if (offset != null) {
|
||||
const px = Math.round(Number(offset) / EMU_PER_PX)
|
||||
const rel = m[1] === 'page' ? 'page' : 'margin'
|
||||
if (axis === 'H') {
|
||||
image.posXPx = px
|
||||
image.posHRel = rel
|
||||
image.posHRel = m[1] === 'page' ? 'page' : 'margin'
|
||||
} else {
|
||||
image.posYPx = px
|
||||
image.posVRel = rel
|
||||
image.posVRel =
|
||||
m[1] === 'page'
|
||||
? 'page'
|
||||
: m[1] === 'paragraph' || m[1] === 'line'
|
||||
? 'paragraph'
|
||||
: 'margin'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4833,6 +4905,28 @@ function fieldDisplayOf(xml: string): FieldDisplay | undefined {
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Word writes wp:anchor relativeHeight as 251658240 + rank, which decodes to
|
||||
* small z-orders; other producers write arbitrary values (LibreOffice: 1, 2,
|
||||
* …) that decode to huge magnitudes, defeating the editor's ±1 reorder steps
|
||||
* and its CSS bands. When any decoded rank is wild, re-rank every anchored
|
||||
* image by its decoded value (stable by document order) starting at 0; rank 0
|
||||
* is the base level, so its attribute is dropped like an untouched anchor.
|
||||
*/
|
||||
function normalizeImageZOrders(blocks: Block[]): void {
|
||||
const anchored = blocks.filter((b) => b.imageZOrder !== undefined)
|
||||
if (!anchored.some((b) => Math.abs(b.imageZOrder!) > 10000)) return
|
||||
anchored
|
||||
.map((b, i) => ({ b, i }))
|
||||
.sort((x, y) => x.b.imageZOrder! - y.b.imageZOrder! || x.i - y.i)
|
||||
.forEach(({ b }, rank) => {
|
||||
if (rank === 0) delete b.imageZOrder
|
||||
else b.imageZOrder = rank
|
||||
// raw XML still carries the wild value; flag for save-time harmonization
|
||||
b.imageZOrderNormalized = true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* TOC entries carry their outline number ("1.", "1.1.") as w:numPr numbering
|
||||
* (Pages exports one numId per entry with startOverride restarts). The field
|
||||
@@ -4908,6 +5002,7 @@ type ImageMeta = Pick<
|
||||
| 'imageHeightPx'
|
||||
| 'imageAlign'
|
||||
| 'imageWrap'
|
||||
| 'imageZOrder'
|
||||
| 'imageOffsetXEmu'
|
||||
| 'imageOffsetYEmu'
|
||||
| 'imagePosH'
|
||||
@@ -4998,6 +5093,13 @@ function imageMeta(xml: string): ImageMeta {
|
||||
const anchor = /<wp:anchor[^>]*>/.exec(xml)?.[0]
|
||||
if (anchor) {
|
||||
if (/allowOverlap="(?:0|false)"/.test(anchor)) meta.imageNoOverlap = true
|
||||
// relativeHeight = 251658240 base + zOrder; keep the delta so overlapping
|
||||
// anchors round-trip their paint order and the editor can reorder them
|
||||
const relHeight = Number(/relativeHeight="(\d+)"/.exec(anchor)?.[1] ?? NaN)
|
||||
if (Number.isFinite(relHeight)) {
|
||||
const z = relHeight - 251658240
|
||||
if (z !== 0) meta.imageZOrder = z
|
||||
}
|
||||
// an explicit wrap element wins over behindDoc: Word draws a
|
||||
// behindDoc+wrapTight object behind the text and still wraps around it
|
||||
if (/behindDoc="1"/.test(anchor) && !/<wp:wrap(Square|Tight|Through|TopAndBottom)/.test(xml))
|
||||
|
||||
@@ -122,6 +122,14 @@ export interface SaveOptions {
|
||||
sectionHf?: Array<{ lastBlockIndex: number; kind: 'header' | 'footer'; hf: HeaderFooter }>
|
||||
/** "different odd & even pages": set/remove settings.xml w:evenAndOddHeaders */
|
||||
evenAndOddHeaders?: boolean
|
||||
/**
|
||||
* Inject the newly created header/footer references into EVERY body sectPr
|
||||
* that has none (not just the trailing one). Generated multi-section
|
||||
* documents (pdf2docx) need the same header on every section: sections
|
||||
* inherit forward from the previous section only, so a reference on the
|
||||
* trailing sectPr alone leaves all earlier sections blank.
|
||||
*/
|
||||
hfAllSections?: boolean
|
||||
/**
|
||||
* Append numbering definitions to word/numbering.xml (when the part is missing, it is
|
||||
* created from the blank template, including rel/ContentType). newDefs = brand-new
|
||||
@@ -447,20 +455,29 @@ export async function saveDocx(
|
||||
|
||||
const newMedia: Array<{ path: string; base64: string }> = []
|
||||
const usedExtensions = new Set<string>()
|
||||
// identical bytes embed ONE media part (repeated logos / per-page backgrounds)
|
||||
const mediaRelByContent = new Map<string, string>()
|
||||
let imageSeq = nextImageSeq(zip)
|
||||
/** Land image bytes as a media part + relationship; returns the new rId. */
|
||||
let docPrSeq = imageSeq
|
||||
/** Land image bytes as a media part + relationship; returns the rId.
|
||||
* Identical bytes reuse ONE media part (repeated logos / per-page backgrounds). */
|
||||
const embedImageMedia = (image: { base64: string; mime: NewImage['mime'] }): string => {
|
||||
const ext = IMAGE_EXT[image.mime]
|
||||
const mediaPath = `word/media/aidocs${imageSeq++}.${ext}`
|
||||
const rId = `rId${nextRelNum++}`
|
||||
newRels.push({
|
||||
rId,
|
||||
type: IMAGE_REL_TYPE,
|
||||
target: mediaPath.replace(/^word\//, ''),
|
||||
external: false,
|
||||
})
|
||||
newMedia.push({ path: mediaPath, base64: image.base64 })
|
||||
usedExtensions.add(ext)
|
||||
const contentKey = `${image.mime}:${image.base64}`
|
||||
let rId = mediaRelByContent.get(contentKey)
|
||||
if (rId === undefined) {
|
||||
const mediaPath = `word/media/aidocs${imageSeq++}.${ext}`
|
||||
rId = `rId${nextRelNum++}`
|
||||
newRels.push({
|
||||
rId,
|
||||
type: IMAGE_REL_TYPE,
|
||||
target: mediaPath.replace(/^word\//, ''),
|
||||
external: false,
|
||||
})
|
||||
newMedia.push({ path: mediaPath, base64: image.base64 })
|
||||
usedExtensions.add(ext)
|
||||
mediaRelByContent.set(contentKey, rId)
|
||||
}
|
||||
return rId
|
||||
}
|
||||
const embedImage = (image: NewImage): string => {
|
||||
@@ -476,9 +493,20 @@ export async function saveDocx(
|
||||
const bh = Math.abs(cx * Math.sin(rad)) + Math.abs(cy * Math.cos(rad))
|
||||
const eeX = Math.max(0, Math.round((bw - cx) / 2))
|
||||
const eeY = Math.max(0, Math.round((bh - cy) / 2))
|
||||
const docPrId = 9000 + imageSeq
|
||||
const pPr =
|
||||
image.align && image.align !== 'left' ? `<w:pPr><w:jc w:val="${image.align}"/></w:pPr>` : ''
|
||||
// dedup means imageSeq does not advance for repeated bytes — docPr ids need their own counter
|
||||
const docPrId = 9000 + ++docPrSeq
|
||||
const ps = image.paraSpacing
|
||||
const spacingAttrs: string[] = []
|
||||
if (ps?.beforeTwips && ps.beforeTwips > 0)
|
||||
spacingAttrs.push(`w:before="${Math.round(ps.beforeTwips)}"`)
|
||||
if (ps?.afterTwips !== undefined && ps.afterTwips >= 0)
|
||||
spacingAttrs.push(`w:after="${Math.round(ps.afterTwips)}"`)
|
||||
if (ps?.lineTwips && ps.lineRule)
|
||||
spacingAttrs.push(`w:line="${Math.round(ps.lineTwips)}"`, `w:lineRule="${ps.lineRule}"`)
|
||||
// schema order inside pPr: w:spacing before w:jc
|
||||
const spacing = spacingAttrs.length > 0 ? `<w:spacing ${spacingAttrs.join(' ')}/>` : ''
|
||||
const jc = image.align && image.align !== 'left' ? `<w:jc w:val="${image.align}"/>` : ''
|
||||
const pPr = spacing || jc ? `<w:pPr>${spacing}${jc}</w:pPr>` : ''
|
||||
const xml =
|
||||
`<w:p>${pPr}<w:r><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0">` +
|
||||
`<wp:extent cx="${cx}" cy="${cy}"/>` +
|
||||
@@ -492,7 +520,9 @@ export async function saveDocx(
|
||||
`<pic:spPr><a:xfrm${rot ? ` rot="${rot * 60000}"` : ''}${image.flipH ? ' flipH="1"' : ''}${image.flipV ? ' flipV="1"' : ''}><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm>` +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr>' +
|
||||
'</pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>'
|
||||
return image.wrap ? applyImageWrap(xml, image.wrap) : xml
|
||||
return image.wrap
|
||||
? applyImageWrap(xml, image.wrap, image.posOffsetEmu, undefined, image.zOrder)
|
||||
: xml
|
||||
}
|
||||
|
||||
// ---- new embedded charts: chart part + workbook + relationship + drawing paragraph ----
|
||||
@@ -980,6 +1010,16 @@ export async function saveDocx(
|
||||
let newDocumentXml =
|
||||
documentXml.slice(0, bodyInnerStart) + parts.join('') + documentXml.slice(bodyInnerEnd)
|
||||
|
||||
// every ref-less body sectPr picks up the new header/footer references
|
||||
// (the trailing sectPr already received them above and is skipped by the
|
||||
// lookahead; sections that carry their own references keep them)
|
||||
if (options.hfAllSections && hfRefTags.length > 0) {
|
||||
newDocumentXml = newDocumentXml.replace(
|
||||
/(<w:sectPr(?:\s[^>]*)?>)(?!<w:headerReference|<w:footerReference)/g,
|
||||
`$1${hfRefTags.join('')}`,
|
||||
)
|
||||
}
|
||||
|
||||
if (options.comments !== undefined) {
|
||||
newDocumentXml = removeDeletedCommentMarkers(
|
||||
newDocumentXml,
|
||||
|
||||
@@ -63,6 +63,12 @@ export function sectionSettingsFromXml(xml: string): SectionSettings {
|
||||
}
|
||||
}
|
||||
|
||||
// explicit unequal column widths (w:cols > w:col children)
|
||||
const colsElement = /<w:cols[^>]*>[\s\S]*?<\/w:cols>/.exec(xml)?.[0]
|
||||
const colWidths = (colsElement?.match(/<w:col [^>]*w:w="\d+"[^>]*\/>/g) ?? [])
|
||||
.map((tag) => intAttr(tag, 'w:w', 0))
|
||||
.filter((w) => w > 0)
|
||||
|
||||
return {
|
||||
pageWidth: intAttr(pgSz, 'w:w', DEFAULT_SECTION.pageWidth),
|
||||
pageHeight: intAttr(pgSz, 'w:h', DEFAULT_SECTION.pageHeight),
|
||||
@@ -77,6 +83,8 @@ export function sectionSettingsFromXml(xml: string): SectionSettings {
|
||||
pageBorder: hasVisiblePageBorder(xml),
|
||||
columns: intAttr(/<w:cols[^>]*\/?>/.exec(xml)?.[0] ?? '', 'w:num', 1),
|
||||
colSpace: intAttr(/<w:cols[^>]*\/?>/.exec(xml)?.[0] ?? '', 'w:space', 720),
|
||||
...(colWidths.length >= 2 ? { colWidths } : {}),
|
||||
...(/<w:bidi\s*\/>/.test(xml) ? { bidi: true } : {}),
|
||||
...(docGrid ? { docGrid } : {}),
|
||||
...(textDirectionOf(xml) ? { textDirection: textDirectionOf(xml) } : {}),
|
||||
}
|
||||
@@ -207,6 +215,10 @@ export function applySectionSettings(sectPrXml: string, settings: SectionSetting
|
||||
tag = replaceMarAttr(tag, 'w:right', settings.marginRight)
|
||||
tag = replaceMarAttr(tag, 'w:bottom', settings.marginBottom)
|
||||
tag = replaceMarAttr(tag, 'w:left', settings.marginLeft)
|
||||
if (settings.headerDist !== undefined)
|
||||
tag = replaceMarAttr(tag, 'w:header', settings.headerDist)
|
||||
if (settings.footerDist !== undefined)
|
||||
tag = replaceMarAttr(tag, 'w:footer', settings.footerDist)
|
||||
xml = xml.replace(marMatch[0], tag)
|
||||
} else {
|
||||
const pgMar =
|
||||
@@ -232,7 +244,39 @@ export function applySectionSettings(sectPrXml: string, settings: SectionSetting
|
||||
// columns (w:cols may be self-closing or carry explicit <w:col> children)
|
||||
const colsMatch = /<w:cols[^>]*\/>|<w:cols[^>]*>[\s\S]*?<\/w:cols>/.exec(xml)
|
||||
const numAttr = settings.columns > 1 ? ` w:num="${settings.columns}"` : ''
|
||||
if (colsMatch) {
|
||||
const colsAnchor = (tag: string): string => {
|
||||
const anchor = /(<w:pgBorders[\s\S]*?<\/w:pgBorders>|<w:pgMar[^>]*\/>)/.exec(xml)
|
||||
if (anchor) return xml.replace(anchor[0], `${anchor[0]}${tag}`)
|
||||
return xml.replace(/<\/w:sectPr>/, `${tag}</w:sectPr>`)
|
||||
}
|
||||
if (
|
||||
settings.colWidths !== undefined &&
|
||||
settings.columns > 1 &&
|
||||
settings.colWidths.length === settings.columns
|
||||
) {
|
||||
// explicit unequal widths: rebuild the element (opt-in via colWidths) —
|
||||
// unless the document already carries exactly these values (round-trip)
|
||||
const currentWidths = (colsMatch?.[0].match(/<w:col [^>]*w:w="\d+"[^>]*\/>/g) ?? []).map((t) =>
|
||||
intAttr(t, 'w:w', 0),
|
||||
)
|
||||
const unchanged =
|
||||
colsMatch !== null &&
|
||||
intAttr(colsMatch[0], 'w:num', 1) === settings.columns &&
|
||||
currentWidths.length === settings.colWidths.length &&
|
||||
currentWidths.every((w, i) => w === settings.colWidths![i])
|
||||
if (!unchanged) {
|
||||
const space = settings.colSpace ?? 720
|
||||
const children = settings.colWidths
|
||||
.map((w, i) =>
|
||||
i < settings.colWidths!.length - 1
|
||||
? `<w:col w:w="${w}" w:space="${space}"/>`
|
||||
: `<w:col w:w="${w}"/>`,
|
||||
)
|
||||
.join('')
|
||||
const tag = `<w:cols${numAttr} w:space="${space}" w:equalWidth="0">${children}</w:cols>`
|
||||
xml = colsMatch ? xml.replace(colsMatch[0], tag) : colsAnchor(tag)
|
||||
}
|
||||
} else if (colsMatch) {
|
||||
const openTag = /^<w:cols[^>]*>/.exec(colsMatch[0])?.[0] ?? colsMatch[0]
|
||||
const selfClosing = colsMatch[0].endsWith('/>')
|
||||
const currentNum = / w:num="(\d+)"/.exec(openTag)?.[1] ?? '1'
|
||||
@@ -240,13 +284,29 @@ export function applySectionSettings(sectPrXml: string, settings: SectionSetting
|
||||
// explicit per-column widths only stay valid while the count is unchanged
|
||||
let tag = openTag.replace(/ w:num="\d+"/, '').replace(/\/?>$/, '/>')
|
||||
if (numAttr) tag = tag.replace(/^<w:cols/, `<w:cols${numAttr}`)
|
||||
// honor an explicitly different column gap (720 = OOXML default); equal
|
||||
// values leave the tag byte-identical for round-trip safety
|
||||
if (settings.colSpace !== undefined && settings.colSpace !== intAttr(tag, 'w:space', 720)) {
|
||||
tag = / w:space="\d+"/.test(tag)
|
||||
? tag.replace(/ w:space="\d+"/, ` w:space="${settings.colSpace}"`)
|
||||
: tag.replace(/\/>$/, ` w:space="${settings.colSpace}"/>`)
|
||||
}
|
||||
xml = xml.replace(colsMatch[0], tag)
|
||||
}
|
||||
} else if (numAttr) {
|
||||
const anchor = /(<w:pgBorders[\s\S]*?<\/w:pgBorders>|<w:pgMar[^>]*\/>)/.exec(xml)
|
||||
const cols = `<w:cols${numAttr} w:space="425"/>`
|
||||
if (anchor) xml = xml.replace(anchor[0], `${anchor[0]}${cols}`)
|
||||
else xml = xml.replace(/<\/w:sectPr>/, `${cols}</w:sectPr>`)
|
||||
xml = colsAnchor(`<w:cols${numAttr} w:space="${settings.colSpace ?? 425}"/>`)
|
||||
}
|
||||
|
||||
// section direction (w:bidi, after cols in CT_SectPr): undefined = keep the
|
||||
// document's tag untouched; true/false = ensure present/absent
|
||||
if (settings.bidi !== undefined) {
|
||||
const hasBidi = /<w:bidi\s*\/>/.test(xml)
|
||||
if (settings.bidi && !hasBidi) {
|
||||
if (/<w:docGrid/.test(xml)) xml = xml.replace(/(<w:docGrid)/, '<w:bidi/>$1')
|
||||
else xml = xml.replace(/<\/w:sectPr>/, '<w:bidi/></w:sectPr>')
|
||||
} else if (!settings.bidi && hasBidi) {
|
||||
xml = xml.replace(/<w:bidi\s*\/>/, '')
|
||||
}
|
||||
}
|
||||
return xml
|
||||
}
|
||||
|
||||
@@ -35,8 +35,12 @@ export interface Run {
|
||||
/** Latin-slot font (w:rFonts ascii/hAnsi) when the run declares one; may equal `font`.
|
||||
* Kept separate so editing one script's font never flattens the other slot. */
|
||||
fontAscii?: string
|
||||
/** Complex-script font (w:rFonts cs/cstheme). Display only; saving is kept faithful by rawRPr */
|
||||
/** complex-script-slot font (w:rFonts w:cs, literal attribute only — theme refs stay in rawRPr) */
|
||||
fontCs?: string
|
||||
/** Complex-script font (w:rFonts cs/cstheme, theme-resolved). Display only; saving is kept faithful by rawRPr */
|
||||
csFont?: string
|
||||
/** right-to-left run (w:rtl): text stored in logical order, rendered RTL */
|
||||
rtl?: boolean
|
||||
/** Character spacing (w:spacing, twips, may be negative). Display only; saving is kept faithful by rawRPr */
|
||||
charSpacingTwips?: number
|
||||
/** w:caps ('all') / w:smallCaps ('small') display transform. Display only; saving is kept faithful by rawRPr */
|
||||
@@ -221,6 +225,31 @@ export interface ParaBorderLine {
|
||||
}
|
||||
|
||||
/** Paragraph-level formatting that survives regeneration (subset of w:pPr). */
|
||||
/**
|
||||
* Absolutely positioned paragraph frame (w:framePr). All lengths in twips;
|
||||
* x/y measure from the anchor's top-left (page anchors by default). Height is
|
||||
* auto unless hTwips is set — auto frames grow with substituted-font wrap
|
||||
* instead of clipping.
|
||||
*/
|
||||
export interface ParaFrame {
|
||||
/** frame width (w:w); text wraps inside it */
|
||||
wTwips: number
|
||||
/** frame height (w:h); omit for auto height */
|
||||
hTwips?: number
|
||||
/** height rule, only written with hTwips (default 'atLeast') */
|
||||
hRule?: 'atLeast' | 'exact'
|
||||
/** x offset from the hAnchor's left edge (w:x) */
|
||||
xTwips: number
|
||||
/** y offset from the vAnchor's top edge (w:y) */
|
||||
yTwips: number
|
||||
/** horizontal anchor (w:hAnchor, default 'page') */
|
||||
hAnchor?: 'page' | 'margin' | 'text'
|
||||
/** vertical anchor (w:vAnchor, default 'page') */
|
||||
vAnchor?: 'page' | 'margin' | 'text'
|
||||
/** body-text wrapping around the frame (w:wrap, default 'none') */
|
||||
wrap?: 'none' | 'around' | 'through' | 'notBeside' | 'auto'
|
||||
}
|
||||
|
||||
export interface ParaFormat {
|
||||
/** w:jc */
|
||||
align?: ParaAlign
|
||||
@@ -264,12 +293,24 @@ export interface ParaFormat {
|
||||
shadingFill?: string
|
||||
/** paragraph borders, subset of "tblr" e.g. "b" or "tblr" (w:pBdr, single lines) */
|
||||
borders?: string
|
||||
/**
|
||||
* style details for the `borders` sides: hex color (no '#', default auto),
|
||||
* thickness in eighth-points (default 4 = 0.5pt), gap to the text in points
|
||||
* (w:space, Word clamps to 0–31, default 1)
|
||||
*/
|
||||
borderStyle?: { color?: string; szEighths?: number; spacePt?: number }
|
||||
/** per-side color/width of `borders` (w:color / w:sz); side absent = auto color, default width */
|
||||
borderLines?: Partial<Record<'t' | 'b' | 'l' | 'r', ParaBorderLine>>
|
||||
/** custom tab stops from w:tabs (non-empty overrides default 0.5in grid) */
|
||||
tabStops?: TabStop[]
|
||||
/** first-line drop cap (w:framePr w:dropCap="drop|margin") */
|
||||
dropCap?: { type: 'drop' | 'margin'; lines: number }
|
||||
/**
|
||||
* positioned paragraph frame (w:framePr, P19 canvas pages): the paragraph
|
||||
* leaves the text flow and renders at an absolute position. Takes
|
||||
* precedence over dropCap (both target the single w:framePr element).
|
||||
*/
|
||||
frame?: ParaFrame
|
||||
/**
|
||||
* RTL paragraph (w:bidi). align stores the visual value: per Word's quirk,
|
||||
* w:jc left/right swap meaning in bidi paragraphs; parsing converts to the
|
||||
@@ -282,6 +323,12 @@ export interface ParaFormat {
|
||||
* the paragraph has no runs, so empty lines keep their Word height.
|
||||
*/
|
||||
emptyRunSizeHalfPoints?: number
|
||||
/**
|
||||
* w:rFonts (ascii/hAnsi/eastAsia) from the same sources: the empty line lays
|
||||
* out with this face's metrics. Read-only for fidelity — generate leaves the
|
||||
* paragraph-mark rPr bytes untouched unless the size changed.
|
||||
*/
|
||||
emptyRunFontFamily?: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -312,6 +359,17 @@ export interface SectionSettings {
|
||||
columns: number
|
||||
/** column gap (w:cols w:space, twips; OOXML default 720) */
|
||||
colSpace?: number
|
||||
/**
|
||||
* explicit unequal column widths (w:cols w:equalWidth="0" > w:col w:w),
|
||||
* twips, layout order; length must equal `columns`. Absent = equal columns.
|
||||
* applySectionSettings only rebuilds w:cols children when this is provided.
|
||||
*/
|
||||
colWidths?: number[]
|
||||
/**
|
||||
* section base direction (sectPr w:bidi): Word fills columns right-to-left.
|
||||
* undefined = leave the document's tag untouched (round-trip safe).
|
||||
*/
|
||||
bidi?: boolean
|
||||
/** Header distance from the page top (w:pgMar w:header, twips; default 720). A tall header pushes the body down */
|
||||
headerDist?: number
|
||||
/** Footer distance from the page bottom (w:pgMar w:footer, twips; default 720). A tall footer pushes the body up */
|
||||
@@ -442,8 +500,10 @@ export interface HfImage {
|
||||
posYPx?: number
|
||||
/** wp:positionH relativeFrom: offsets measure from the page edge or the margin box */
|
||||
posHRel?: 'page' | 'margin'
|
||||
/** wp:positionV relativeFrom */
|
||||
posVRel?: 'page' | 'margin'
|
||||
/** wp:positionV relativeFrom ('paragraph' also covers 'line'; placement treats it like 'margin') */
|
||||
posVRel?: 'page' | 'margin' | 'paragraph'
|
||||
/** wp:anchor wrap mode; square/tight/through/topBottom header images push the body below them */
|
||||
wrap?: 'none' | 'square' | 'tight' | 'through' | 'topBottom'
|
||||
/** v:imagedata gain/blacklevel present (Word watermark washout preset) */
|
||||
washout?: boolean
|
||||
/** w:jc of the containing paragraph (inline images follow paragraph alignment) */
|
||||
@@ -470,6 +530,10 @@ export interface NoteRun {
|
||||
/** hex without '#' */
|
||||
color?: string
|
||||
sizeHalfPoints?: number
|
||||
/** Latin font (w:ascii / w:hAnsi) — save-side only, parse does not recover it */
|
||||
fontAscii?: string
|
||||
/** East-Asian font (w:eastAsia) — save-side only, parse does not recover it */
|
||||
font?: string
|
||||
/** w:caps ('all') / w:smallCaps ('small') display transform */
|
||||
caps?: 'all' | 'small'
|
||||
}
|
||||
@@ -684,6 +748,17 @@ export interface TableModel {
|
||||
align?: 'left' | 'center' | 'right'
|
||||
/** table left indent (w:tblInd, twips; effective only with left alignment) */
|
||||
indentTwips?: number
|
||||
/**
|
||||
* absolutely positioned floating table (w:tblpPr + w:tblOverlap, P19 canvas
|
||||
* pages): x/y in twips from the anchors' top-left (page anchors by
|
||||
* default). Only applies when the tblPr is built fresh (generated tables).
|
||||
*/
|
||||
floatPos?: {
|
||||
xTwips: number
|
||||
yTwips: number
|
||||
horzAnchor?: 'page' | 'margin' | 'text'
|
||||
vertAnchor?: 'page' | 'margin' | 'text'
|
||||
}
|
||||
/** floating table (w:tblpPr): text wraps around the side opposite the anchor */
|
||||
floatSide?: 'left' | 'right'
|
||||
/** per-row height (twips, w:trHeight; null = not set), aligned with rows */
|
||||
@@ -767,6 +842,30 @@ export interface NewImage {
|
||||
align?: 'left' | 'center' | 'right'
|
||||
/** floating wrap mode; absent = inline */
|
||||
wrap?: ImageWrap
|
||||
/**
|
||||
* numeric anchor position in EMU (only with `wrap`): positionH relative to
|
||||
* the column, positionV relative to the anchor paragraph. Absent = the
|
||||
* wrap mode's default <wp:align> placement. `relativeTo: 'page'` pins both
|
||||
* axes to the page box instead (full-page backgrounds).
|
||||
*/
|
||||
posOffsetEmu?: { x: number; y: number; relativeTo?: 'page' }
|
||||
/**
|
||||
* stacking rank among anchored drawings (only with `wrap`): written as
|
||||
* relativeHeight base + zOrder, so overlapping behindDoc anchors keep a
|
||||
* deterministic paint order (higher = in front). Absent = base value.
|
||||
*/
|
||||
zOrder?: number
|
||||
/**
|
||||
* explicit w:spacing on the picture's holder paragraph. Layout-rebuilding
|
||||
* writers (pdf2docx) set this so the paragraph does not inherit the
|
||||
* template docDefaults (space-after + multiplied line height).
|
||||
*/
|
||||
paraSpacing?: {
|
||||
beforeTwips?: number
|
||||
afterTwips?: number
|
||||
lineTwips?: number
|
||||
lineRule?: 'exact' | 'atLeast'
|
||||
}
|
||||
/** rotation in degrees clockwise (a:xfrm rot) */
|
||||
rotDeg?: number
|
||||
/** mirror flips (a:xfrm flipH/flipV) */
|
||||
@@ -831,6 +930,22 @@ export interface Block {
|
||||
imageAlign?: 'left' | 'center' | 'right'
|
||||
/** text wrapping of a floating image (wp:anchor); absent = inline (in line with text) */
|
||||
imageWrap?: ImageWrap
|
||||
/**
|
||||
* stacking rank of a floating image among overlapping anchors, decoded from
|
||||
* wp:anchor relativeHeight minus the 251658240 base (0 when at/below base).
|
||||
* Higher paints in front. Round-trips so opening an untouched doc and saving
|
||||
* preserves the original z-order, and the editor's bring-forward/send-back
|
||||
* commands write it back. Absent = inline / base level.
|
||||
*/
|
||||
imageZOrder?: number
|
||||
/**
|
||||
* imageZOrder was compressed from a wild producer relativeHeight
|
||||
* (LibreOffice writes 1, 2, …). Word paints by the raw value, so once any
|
||||
* wrap/z-order edit rewrites one anchor to base+rank encoding, every
|
||||
* normalized sibling must be rewritten too or the saved paint order
|
||||
* inverts (save-time harmonization; untouched documents keep their bytes).
|
||||
*/
|
||||
imageZOrderNormalized?: boolean
|
||||
/**
|
||||
* Horizontal/vertical posOffset (in EMU) of a floating image (wp:anchor
|
||||
* with wp:positionH/V using posOffset, not align). Used for free-position
|
||||
@@ -980,6 +1095,12 @@ export interface TextboxDisplay {
|
||||
* paragraph with other drawings — leave the flow like Word (absolute
|
||||
* position, no flow height) instead of stacking as blocks */
|
||||
floating?: boolean
|
||||
/** wrapTopAndBottom (paragraph/line-relative V): the anchor paragraph keeps
|
||||
* flow height down to this box bottom (px) so following text resumes below */
|
||||
bandBottomPx?: number
|
||||
/** the band's top edge (px, offset component of bandBottomPx); the renderer
|
||||
* adds the live box height so in-editor autogrow moves the band with it */
|
||||
bandTopPx?: number
|
||||
/** rotation in degrees clockwise (a:xfrm rot / 60000) */
|
||||
rotDeg?: number
|
||||
/** border width in CSS px (a:ln w) */
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildAnchoredTextboxParagraphXml } from '../src/generate'
|
||||
import { parseDocx } from '../src/parse'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
/**
|
||||
* P20 region container: a WPS text box with real w:p content, anchored either
|
||||
* to its holder paragraph (card regions that ride the flow, wrap topAndBottom)
|
||||
* or to the page (newsletter regions at absolute coordinates).
|
||||
*/
|
||||
|
||||
const CARD_PARAS = [
|
||||
{
|
||||
runs: [{ text: 'FINAL TAKEAWAY', bold: true, color: 'FFFFFF' }],
|
||||
format: { spaceAfter: 60, lineRule: 'exact' as const, lineRawTwips: 320 },
|
||||
},
|
||||
{
|
||||
runs: [{ text: '结论正文第二行', color: 'FFFFFF' }],
|
||||
format: {
|
||||
spaceAfter: 0,
|
||||
lineRule: 'exact' as const,
|
||||
lineRawTwips: 280,
|
||||
align: 'left' as const,
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
const cardXml = () =>
|
||||
buildAnchoredTextboxParagraphXml({
|
||||
anchor: 'paragraph',
|
||||
xEmu: 91440,
|
||||
yEmu: 12700,
|
||||
widthEmu: 5486400,
|
||||
heightEmu: 1371600,
|
||||
fillHex: '1A1A2E',
|
||||
insetsEmu: { l: 182880, t: 91440, r: 182880, b: 91440 },
|
||||
zOrder: 7,
|
||||
id: 42,
|
||||
paragraphs: CARD_PARAS,
|
||||
holderLineTwips: 20,
|
||||
})
|
||||
|
||||
describe('buildAnchoredTextboxParagraphXml (P20 region container)', () => {
|
||||
it('paragraph anchor floats with the flow and wraps topAndBottom', () => {
|
||||
const xml = cardXml()
|
||||
expect(xml).toContain(
|
||||
'<wp:positionH relativeFrom="column"><wp:posOffset>91440</wp:posOffset></wp:positionH>',
|
||||
)
|
||||
expect(xml).toContain(
|
||||
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>12700</wp:posOffset></wp:positionV>',
|
||||
)
|
||||
expect(xml).toContain('<wp:wrapTopAndBottom/>')
|
||||
expect(xml).not.toContain('<wp:wrapSquare')
|
||||
// CT_Anchor child order: wrap element sits between effectExtent and docPr
|
||||
const wrapAt = xml.indexOf('<wp:wrapTopAndBottom/>')
|
||||
expect(wrapAt).toBeGreaterThan(xml.indexOf('<wp:effectExtent'))
|
||||
expect(wrapAt).toBeLessThan(xml.indexOf('<wp:docPr'))
|
||||
expect(xml).toContain('<wp:extent cx="5486400" cy="1371600"/>')
|
||||
})
|
||||
|
||||
it('page anchor pins both axes to the page and wraps none', () => {
|
||||
const xml = buildAnchoredTextboxParagraphXml({
|
||||
anchor: 'page',
|
||||
xEmu: 457200,
|
||||
yEmu: 914400,
|
||||
widthEmu: 2743200,
|
||||
heightEmu: 3657600,
|
||||
paragraphs: [{ runs: [{ text: 'column A' }] }],
|
||||
})
|
||||
expect(xml).toContain(
|
||||
'<wp:positionH relativeFrom="page"><wp:posOffset>457200</wp:posOffset></wp:positionH>',
|
||||
)
|
||||
expect(xml).toContain(
|
||||
'<wp:positionV relativeFrom="page"><wp:posOffset>914400</wp:posOffset></wp:positionV>',
|
||||
)
|
||||
expect(xml).toContain('<wp:wrapNone/>')
|
||||
})
|
||||
|
||||
it('writes fill, z-order and behindDoc discipline', () => {
|
||||
const xml = cardXml()
|
||||
expect(xml).toContain('<a:solidFill><a:srgbClr val="1A1A2E"/></a:solidFill>')
|
||||
expect(xml).toContain(`relativeHeight="${251658240 + 7}"`)
|
||||
expect(xml).toContain('behindDoc="0"')
|
||||
// no border unless asked for
|
||||
expect(xml).toContain('<a:ln><a:noFill/></a:ln>')
|
||||
})
|
||||
|
||||
it('omitted fill stays transparent', () => {
|
||||
const xml = buildAnchoredTextboxParagraphXml({
|
||||
anchor: 'page',
|
||||
xEmu: 0,
|
||||
yEmu: 0,
|
||||
widthEmu: 914400,
|
||||
heightEmu: 914400,
|
||||
paragraphs: [{ runs: [{ text: 'x' }] }],
|
||||
})
|
||||
expect(xml).toContain('<a:noFill/>')
|
||||
expect(xml).not.toContain('<a:solidFill>')
|
||||
})
|
||||
|
||||
it('writes measured insets on wps:bodyPr', () => {
|
||||
const xml = cardXml()
|
||||
const bodyPr = /<wps:bodyPr[^>]*>/.exec(xml)?.[0] ?? ''
|
||||
expect(bodyPr).toContain('lIns="182880"')
|
||||
expect(bodyPr).toContain('tIns="91440"')
|
||||
expect(bodyPr).toContain('rIns="182880"')
|
||||
expect(bodyPr).toContain('bIns="91440"')
|
||||
// fixed box: content must not auto-grow the region
|
||||
expect(xml).toContain('<a:noAutofit/>')
|
||||
})
|
||||
|
||||
it('rounded corners map to roundRect with the measured radius', () => {
|
||||
const xml = buildAnchoredTextboxParagraphXml({
|
||||
anchor: 'paragraph',
|
||||
xEmu: 0,
|
||||
yEmu: 0,
|
||||
widthEmu: 4000000,
|
||||
heightEmu: 1000000,
|
||||
cornerRadiusEmu: 100000,
|
||||
paragraphs: [{ runs: [{ text: 'rounded' }] }],
|
||||
})
|
||||
// adj = radius / min(w,h) * 100000 = 100000/1000000*100000 = 10000
|
||||
expect(xml).toContain(
|
||||
'<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 10000"/></a:avLst></a:prstGeom>',
|
||||
)
|
||||
})
|
||||
|
||||
it('content is real editable w:p paragraphs with line structure', () => {
|
||||
const xml = cardXml()
|
||||
const txbx =
|
||||
/<wps:txbx><w:txbxContent>([\s\S]*?)<\/w:txbxContent><\/wps:txbx>/.exec(xml)?.[1] ?? ''
|
||||
expect(txbx.match(/<w:p>/g)?.length).toBe(2)
|
||||
expect(txbx).toContain('FINAL TAKEAWAY')
|
||||
expect(txbx).toContain('结论正文第二行')
|
||||
expect(txbx).toContain('<w:spacing w:after="60" w:line="320" w:lineRule="exact"/>')
|
||||
expect(txbx).toContain('<w:color w:val="FFFFFF"/>')
|
||||
})
|
||||
|
||||
it('holder paragraph keeps an exact tight line so the anchor row adds no height', () => {
|
||||
const xml = cardXml()
|
||||
expect(
|
||||
xml.startsWith(
|
||||
'<w:p><w:pPr><w:spacing w:after="0" w:line="20" w:lineRule="exact"/></w:pPr><w:r>',
|
||||
),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('holder paragraph carries spacing-before and page-break-before when asked', () => {
|
||||
const xml = buildAnchoredTextboxParagraphXml({
|
||||
anchor: 'paragraph',
|
||||
xEmu: 0,
|
||||
yEmu: 0,
|
||||
widthEmu: 914400,
|
||||
heightEmu: 914400,
|
||||
paragraphs: [{ runs: [{ text: 'x' }] }],
|
||||
holderLineTwips: 20,
|
||||
holderSpacingBeforeTwips: 240,
|
||||
holderPageBreakBefore: true,
|
||||
})
|
||||
expect(
|
||||
xml.startsWith(
|
||||
'<w:p><w:pPr><w:pageBreakBefore/><w:spacing w:before="240" w:after="0" w:line="20" w:lineRule="exact"/></w:pPr><w:r>',
|
||||
),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('declares Requires prefixes at AlternateContent scope and pt-sized VML fallback', () => {
|
||||
const xml = cardXml()
|
||||
const acTag = /<mc:AlternateContent[^>]*>/.exec(xml)?.[0] ?? ''
|
||||
for (const m of xml.matchAll(/Requires="([^"]+)"/g)) {
|
||||
for (const prefix of m[1]!.split(/\s+/)) {
|
||||
expect(acTag).toContain(`xmlns:${prefix}=`)
|
||||
}
|
||||
}
|
||||
const style = /<v:(?:round)?rect[^>]*style="([^"]*)"/.exec(xml)?.[1] ?? ''
|
||||
expect(style).toContain(`width:${5486400 / 12700}pt`)
|
||||
expect(style).toContain(`height:${1371600 / 12700}pt`)
|
||||
expect(xml).toContain('fillcolor="#1A1A2E"')
|
||||
})
|
||||
|
||||
it('round-trips through parseDocx as an editable textbox', async () => {
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: cardXml() }))
|
||||
const box = parsed.blocks.flatMap((b) => b.textboxes ?? [])[0]
|
||||
expect(box).toBeDefined()
|
||||
expect(box!.fill?.toUpperCase()).toBe('1A1A2E')
|
||||
expect(box!.paras.map((p) => p.runs.map((r) => r.text).join(''))).toEqual([
|
||||
'FINAL TAKEAWAY',
|
||||
'结论正文第二行',
|
||||
])
|
||||
expect(box!.readOnly).not.toBe(true)
|
||||
expect(box!.widthPx).toBe(Math.round(5486400 / 9525))
|
||||
expect(box!.insetLeftPx).toBeCloseTo(182880 / 9525, 1)
|
||||
})
|
||||
})
|
||||
@@ -119,6 +119,44 @@ describe('header/footer images (display-only Logo)', () => {
|
||||
expect(img.posYPx).toBeUndefined()
|
||||
})
|
||||
|
||||
it('anchored image reads the wrap mode and keeps paragraph-relative positionV (prod_004 shape)', 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="column"><wp:posOffset>190500</wp:posOffset></wp:positionH>' +
|
||||
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>-137208</wp:posOffset></wp:positionV>' +
|
||||
'<wp:extent cx="381000" cy="958215"/>' +
|
||||
'<wp:wrapSquare wrapText="bothSides"/>',
|
||||
).replace('</wp:inline>', '</wp:anchor>')
|
||||
const img = (await parseDocx(await buildHeaderLogoDocx(headerXml))).headerImages![0]
|
||||
expect(img.floating).toBe(true)
|
||||
expect(img.wrap).toBe('square')
|
||||
expect(img.posVRel).toBe('paragraph')
|
||||
expect(img.posYPx).toBe(-14)
|
||||
expect(img.heightPx).toBe(101)
|
||||
expect(img.posHRel).toBe('margin')
|
||||
})
|
||||
|
||||
it('wrapTopAndBottom and wrapNone map to topBottom / none', async () => {
|
||||
const withWrap = (wrapXml: string) =>
|
||||
HEADER_XML.replace(
|
||||
'<wp:inline distT="0" distB="0" distL="0" distR="0">' +
|
||||
'<wp:extent cx="381000" cy="190500"/>',
|
||||
'<wp:anchor behindDoc="0">' +
|
||||
'<wp:positionV relativeFrom="page"><wp:posOffset>335280</wp:posOffset></wp:positionV>' +
|
||||
'<wp:extent cx="381000" cy="377190"/>' +
|
||||
wrapXml,
|
||||
).replace('</wp:inline>', '</wp:anchor>')
|
||||
const tb = (await parseDocx(await buildHeaderLogoDocx(withWrap('<wp:wrapTopAndBottom/>'))))
|
||||
.headerImages![0]
|
||||
expect(tb.wrap).toBe('topBottom')
|
||||
expect(tb.posVRel).toBe('page')
|
||||
const none = (await parseDocx(await buildHeaderLogoDocx(withWrap('<wp:wrapNone/>'))))
|
||||
.headerImages![0]
|
||||
expect(none.wrap).toBe('none')
|
||||
})
|
||||
|
||||
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(
|
||||
|
||||
@@ -158,6 +158,31 @@ describe('first-page / even-page headers & footers', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('hfAllSections (P17)', () => {
|
||||
it('injects new header/footer references into every ref-less body sectPr', async () => {
|
||||
const midSect =
|
||||
'<w:p><w:pPr><w:sectPr><w:type w:val="continuous"/>' +
|
||||
'<w:pgSz w:w="11906" w:h="16838"/>' +
|
||||
'<w:pgMar w:top="975" w:right="1051" w:bottom="400" w:left="982" w:header="708" w:footer="708" w:gutter="0"/>' +
|
||||
'</w:sectPr></w:pPr></w:p>'
|
||||
const source = await buildDocx({ bodyXml: BODY + midSect + BODY })
|
||||
const parsed = await parseDocx(source)
|
||||
const saved = await saveDocx(
|
||||
parsed,
|
||||
parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
|
||||
{ header: { text: '重复页眉' }, hfAllSections: true },
|
||||
)
|
||||
const docXml = (await zipText(saved, 'word/document.xml'))!
|
||||
const refs = docXml.match(/<w:headerReference[^>]*\/>/g) ?? []
|
||||
expect(refs.length).toBe(2) // mid-body sectPr + trailing sectPr
|
||||
// both point at the same part
|
||||
const ids = refs.map((r) => /r:id="([^"]+)"/.exec(r)![1])
|
||||
expect(new Set(ids).size).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
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'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { applyImageWrap, parseDocx, saveDocx } from '../src/index'
|
||||
import { applyImageWrap, applyImageZOrder, parseDocx, saveDocx } from '../src/index'
|
||||
import { buildDocx, IMAGE_PARAGRAPH_XML } from './helpers/build-docx'
|
||||
|
||||
const ANCHOR_SQUARE_RIGHT_XML =
|
||||
@@ -144,6 +144,14 @@ describe('image text wrap (wp:anchor)', () => {
|
||||
expect(out).not.toContain('wp:wrapSquare')
|
||||
})
|
||||
|
||||
it('zOrder raises relativeHeight so stacked behind anchors keep paint order', () => {
|
||||
const out = applyImageWrap(ANCHOR_SQUARE_RIGHT_XML, 'behind', undefined, undefined, 7)
|
||||
expect(out).toContain('relativeHeight="251658247"')
|
||||
// default stays at the base value
|
||||
const plain = applyImageWrap(ANCHOR_SQUARE_RIGHT_XML, 'behind')
|
||||
expect(plain).toContain('relativeHeight="251658240"')
|
||||
})
|
||||
|
||||
it('applies margin-relative position presets (Word position gallery)', () => {
|
||||
const out = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-right', undefined, {
|
||||
h: 'center',
|
||||
@@ -194,6 +202,70 @@ describe('image text wrap (wp:anchor)', () => {
|
||||
expect(p3.blocks[0].imageDataUrl).toBeTruthy()
|
||||
})
|
||||
|
||||
it('parses imageZOrder from a non-base relativeHeight (round-trip paint order)', async () => {
|
||||
// relativeHeight = 251658240 base + 5
|
||||
const xml = ANCHOR_SQUARE_RIGHT_XML.replace('relativeHeight="1"', 'relativeHeight="251658245"')
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml, withImage: true }))
|
||||
expect(doc.blocks[0].imageZOrder).toBe(5)
|
||||
|
||||
// base value (or absent) leaves imageZOrder undefined
|
||||
const base = ANCHOR_SQUARE_RIGHT_XML.replace('relativeHeight="1"', 'relativeHeight="251658240"')
|
||||
const doc2 = await parseDocx(await buildDocx({ bodyXml: base, withImage: true }))
|
||||
expect(doc2.blocks[0].imageZOrder).toBeUndefined()
|
||||
})
|
||||
|
||||
it('applyImageZOrder re-encodes relativeHeight and nothing else', () => {
|
||||
const out = applyImageZOrder(ANCHOR_SQUARE_RIGHT_XML, 3)
|
||||
expect(out).toContain('relativeHeight="251658243"')
|
||||
// byte-identical apart from the one attribute value: position basis,
|
||||
// wrap element and distances must survive a pure reorder
|
||||
expect(out.replace('relativeHeight="251658243"', 'relativeHeight="1"')).toBe(
|
||||
ANCHOR_SQUARE_RIGHT_XML,
|
||||
)
|
||||
// no rank = base level; inline (no anchor) passes through untouched
|
||||
expect(applyImageZOrder(ANCHOR_SQUARE_RIGHT_XML)).toContain('relativeHeight="251658240"')
|
||||
expect(applyImageZOrder(IMAGE_PARAGRAPH_XML, 5)).toBe(IMAGE_PARAGRAPH_XML)
|
||||
})
|
||||
|
||||
it('compresses wild producer relativeHeight values to compact ranks', async () => {
|
||||
// LibreOffice-style: arbitrary small relativeHeight (1, 7) decodes to huge
|
||||
// negative ranks; parse re-ranks the document's anchors 0..n-1 in paint
|
||||
// order so the editor's ±1 reorder steps and CSS bands stay meaningful
|
||||
const second = ANCHOR_SQUARE_RIGHT_XML.replace(
|
||||
'relativeHeight="1"',
|
||||
'relativeHeight="7"',
|
||||
).replace('id="1" name="图片 1"', 'id="2" name="图片 2"')
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({ bodyXml: ANCHOR_SQUARE_RIGHT_XML + second, withImage: true }),
|
||||
)
|
||||
expect(doc.blocks[0].imageZOrder).toBeUndefined() // rank 0 = base level
|
||||
expect(doc.blocks[1].imageZOrder).toBe(1)
|
||||
})
|
||||
|
||||
it('round-trips imageZOrder through applyImageWrap + saveDocx + reparse', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true })
|
||||
const parsed = await parseDocx(bytes)
|
||||
// float it in front with a stacking rank of 3
|
||||
const saved = await saveDocx(parsed, [
|
||||
{
|
||||
kind: 'xml',
|
||||
xml: applyImageWrap(parsed.blocks[0].originalXml!, 'front', undefined, undefined, 3),
|
||||
},
|
||||
])
|
||||
const p2 = await parseDocx(saved)
|
||||
expect(p2.blocks[0].imageWrap).toBe('front')
|
||||
expect(p2.blocks[0].imageZOrder).toBe(3)
|
||||
// bump the rank; wrap unchanged
|
||||
const bumped = await saveDocx(p2, [
|
||||
{
|
||||
kind: 'xml',
|
||||
xml: applyImageWrap(p2.blocks[0].originalXml!, 'front', undefined, undefined, 13),
|
||||
},
|
||||
])
|
||||
const p3 = await parseDocx(bumped)
|
||||
expect(p3.blocks[0].imageZOrder).toBe(13)
|
||||
})
|
||||
|
||||
it('embeds new images as anchors when NewImage.wrap is set', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' })
|
||||
const parsed = await parseDocx(bytes)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildAnchoredTextboxParagraphXml,
|
||||
buildShapeParagraphXml,
|
||||
buildTextboxParagraphXml,
|
||||
buildWordArtParagraphXml,
|
||||
@@ -16,6 +17,17 @@ const BUILDERS: Array<[string, string]> = [
|
||||
['wordart', buildWordArtParagraphXml({ text: 'Hi' })],
|
||||
['textbox', buildTextboxParagraphXml()],
|
||||
['shape', buildShapeParagraphXml({ prst: 'ellipse' })],
|
||||
[
|
||||
'anchored-textbox',
|
||||
buildAnchoredTextboxParagraphXml({
|
||||
anchor: 'paragraph',
|
||||
xEmu: 0,
|
||||
yEmu: 0,
|
||||
widthEmu: 914400,
|
||||
heightEmu: 914400,
|
||||
paragraphs: [{ runs: [{ text: 'Hi' }] }],
|
||||
}),
|
||||
],
|
||||
]
|
||||
|
||||
describe('MCE Requires prefixes resolve at AlternateContent scope', () => {
|
||||
|
||||
@@ -278,4 +278,38 @@ describe('rich-text footnote display runs', () => {
|
||||
expect(notes[1].richParas).toBeUndefined()
|
||||
expect(notes[1].text).toBe('纯文本')
|
||||
})
|
||||
|
||||
it('serializes richParas runs with size/font formatting for fresh notes (P17)', async () => {
|
||||
const { buildNotesXml, parseNotesXml } = await import('../src/notes')
|
||||
const xml = buildNotesXml(
|
||||
'footnote',
|
||||
[
|
||||
{
|
||||
id: '201',
|
||||
text: 'small note tail',
|
||||
richParas: [
|
||||
[
|
||||
{ text: 'small note', sizeHalfPoints: 16, fontAscii: 'Arial', bold: true },
|
||||
{ text: ' tail', sizeHalfPoints: 16, color: '1F4E79' },
|
||||
],
|
||||
],
|
||||
},
|
||||
],
|
||||
null,
|
||||
)
|
||||
expect(xml).toContain('<w:sz w:val="16"/>')
|
||||
expect(xml).toContain('w:ascii="Arial"')
|
||||
expect(xml).toContain('<w:b/>')
|
||||
expect(xml).toContain('<w:color w:val="1F4E79"/>')
|
||||
// the self-reference mark + spacer shrink to the note's own size
|
||||
expect(xml).toContain('<w:vertAlign w:val="superscript"/><w:sz w:val="16"/>')
|
||||
// rich rebuilds pin single spacing so template docDefaults cannot inflate the area
|
||||
expect(xml).toContain('<w:spacing w:after="0" w:line="240" w:lineRule="auto"/>')
|
||||
const notes = parseNotesXml(xml, 'footnote')
|
||||
expect(notes[0]!.text).toBe('small note tail')
|
||||
expect(notes[0]!.richParas?.[0]).toEqual([
|
||||
{ text: 'small note', bold: true, sizeHalfPoints: 16 },
|
||||
{ text: ' tail', color: '1F4E79', sizeHalfPoints: 16 },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -200,4 +200,16 @@ describe('empty paragraph line size', () => {
|
||||
expect(doc.blocks[1].format?.emptyRunSizeHalfPoints).toBe(2)
|
||||
expect(doc.blocks[2].format?.emptyRunSizeHalfPoints).toBe(16)
|
||||
})
|
||||
|
||||
it('records the w:rFonts that faces a run-less paragraph', async () => {
|
||||
const bodyXml =
|
||||
'<w:p><w:r><w:t>before</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman"/></w:rPr></w:pPr></w:p>' +
|
||||
// no pPr rPr: falls back to the (dropped) empty run
|
||||
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Arial"/></w:rPr><w:t></w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml }))
|
||||
expect(doc.blocks[0].format?.emptyRunFontFamily).toBeUndefined()
|
||||
expect(doc.blocks[1].format?.emptyRunFontFamily).toBe('Times New Roman')
|
||||
expect(doc.blocks[2].format?.emptyRunFontFamily).toBe('Arial')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
generateParagraphXml,
|
||||
generateTableModelXml,
|
||||
mergePPrFormat,
|
||||
parseDocx,
|
||||
saveDocx,
|
||||
type GenerateContext,
|
||||
type ParaFormat,
|
||||
type TableModel,
|
||||
} from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const GEN_CTX: GenerateContext = {
|
||||
headingStyleIds: new Map([[1, 'Heading1']]),
|
||||
allocateHyperlinkRel: () => 'rId999',
|
||||
}
|
||||
|
||||
describe('positioned paragraph frames (w:framePr)', () => {
|
||||
it('emits a page-anchored frame with position, size and wrap', () => {
|
||||
const format: ParaFormat = {
|
||||
frame: { wTwips: 4000, xTwips: 1200, yTwips: 800 },
|
||||
lineRule: 'exact',
|
||||
lineRawTwips: 300,
|
||||
spaceAfter: 0,
|
||||
}
|
||||
const xml = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ text: 'slide title' }], format },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(xml).toContain('<w:framePr')
|
||||
expect(xml).toContain('w:w="4000"')
|
||||
expect(xml).toContain('w:x="1200"')
|
||||
expect(xml).toContain('w:y="800"')
|
||||
expect(xml).toContain('w:hAnchor="page"')
|
||||
expect(xml).toContain('w:vAnchor="page"')
|
||||
expect(xml).toContain('w:wrap="none"')
|
||||
// no height attrs unless requested (auto height must not clip substituted fonts)
|
||||
expect(xml).not.toContain('w:h=')
|
||||
expect(xml).not.toContain('w:hRule=')
|
||||
// schema order: framePr before spacing inside pPr
|
||||
expect(xml.indexOf('<w:framePr')).toBeLessThan(xml.indexOf('<w:spacing'))
|
||||
})
|
||||
|
||||
it('emits height, hRule, custom anchors and wrap when set', () => {
|
||||
const format: ParaFormat = {
|
||||
frame: {
|
||||
wTwips: 2000,
|
||||
hTwips: 600,
|
||||
hRule: 'exact',
|
||||
xTwips: 0,
|
||||
yTwips: 0,
|
||||
hAnchor: 'margin',
|
||||
vAnchor: 'margin',
|
||||
wrap: 'around',
|
||||
},
|
||||
}
|
||||
const xml = generateParagraphXml({ type: 'paragraph', runs: [{ text: 'x' }], format }, GEN_CTX)
|
||||
expect(xml).toContain('w:h="600"')
|
||||
expect(xml).toContain('w:hRule="exact"')
|
||||
expect(xml).toContain('w:hAnchor="margin"')
|
||||
expect(xml).toContain('w:vAnchor="margin"')
|
||||
expect(xml).toContain('w:wrap="around"')
|
||||
expect(xml).toContain('w:x="0"')
|
||||
expect(xml).toContain('w:y="0"')
|
||||
})
|
||||
|
||||
it('keeps CT_PPr child order when built from the model alone', () => {
|
||||
const merged = mergePPrFormat('<w:pPr/>', {
|
||||
frame: { wTwips: 1000, xTwips: 10, yTwips: 20 },
|
||||
pageBreakBefore: true,
|
||||
align: 'center',
|
||||
lineRule: 'exact',
|
||||
lineRawTwips: 240,
|
||||
})
|
||||
// pageBreakBefore (rank 3) < framePr (rank 4) < spacing < jc
|
||||
expect(merged.indexOf('<w:pageBreakBefore')).toBeLessThan(merged.indexOf('<w:framePr'))
|
||||
expect(merged.indexOf('<w:framePr')).toBeLessThan(merged.indexOf('<w:spacing'))
|
||||
expect(merged.indexOf('<w:spacing')).toBeLessThan(merged.indexOf('<w:jc'))
|
||||
})
|
||||
|
||||
it('frame wins over dropCap when both are set (single w:framePr)', () => {
|
||||
const xml = generateParagraphXml(
|
||||
{
|
||||
type: 'paragraph',
|
||||
runs: [{ text: 'x' }],
|
||||
format: {
|
||||
frame: { wTwips: 1000, xTwips: 10, yTwips: 20 },
|
||||
dropCap: { type: 'drop', lines: 3 },
|
||||
},
|
||||
},
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(xml.match(/<w:framePr/g)).toHaveLength(1)
|
||||
expect(xml).toContain('w:x="10"')
|
||||
expect(xml).not.toContain('w:dropCap')
|
||||
})
|
||||
|
||||
it('leaves an existing non-dropCap framePr untouched when the format has no frame', async () => {
|
||||
const rawPPr =
|
||||
'<w:pPr><w:framePr w:w="5000" w:hAnchor="page" w:vAnchor="page" w:x="100" w:y="200" w:wrap="none"/></w:pPr>'
|
||||
// no frame/dropCap in the format → w:framePr is unmanaged → raw bytes survive
|
||||
expect(mergePPrFormat(rawPPr, { align: 'center' })).toContain(
|
||||
'<w:framePr w:w="5000" w:hAnchor="page" w:vAnchor="page" w:x="100" w:y="200" w:wrap="none"/>',
|
||||
)
|
||||
})
|
||||
|
||||
it('round-trips a framed paragraph through saveDocx without corrupting the body', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({ bodyXml: '<w:p><w:r><w:t>seed</w:t></w:r></w:p>' }),
|
||||
)
|
||||
const saved = await saveDocx(doc, [
|
||||
{
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
runs: [{ text: 'framed' }],
|
||||
format: { frame: { wTwips: 3000, xTwips: 500, yTwips: 700 } },
|
||||
},
|
||||
},
|
||||
])
|
||||
const reparsed = await parseDocx(saved)
|
||||
const texts = reparsed.blocks.map((b) => (b.runs ?? []).map((r) => r.text).join(''))
|
||||
expect(texts).toContain('framed')
|
||||
})
|
||||
})
|
||||
|
||||
describe('floating table position (w:tblpPr)', () => {
|
||||
const model: TableModel = {
|
||||
rows: [[{ paras: ['a'] }, { paras: ['b'] }]],
|
||||
colWidthsTwips: [1000, 1000],
|
||||
floatPos: { xTwips: 2400, yTwips: 1800 },
|
||||
}
|
||||
|
||||
it('emits page-anchored tblpPr with overlap before tblW', () => {
|
||||
const xml = generateTableModelXml(model)
|
||||
expect(xml).toContain('<w:tblpPr')
|
||||
expect(xml).toContain('w:tblpX="2400"')
|
||||
expect(xml).toContain('w:tblpY="1800"')
|
||||
expect(xml).toContain('w:horzAnchor="page"')
|
||||
expect(xml).toContain('w:vertAnchor="page"')
|
||||
expect(xml).toContain('<w:tblOverlap w:val="overlap"/>')
|
||||
expect(xml.indexOf('<w:tblpPr')).toBeLessThan(xml.indexOf('<w:tblW'))
|
||||
expect(xml.indexOf('<w:tblpPr')).toBeLessThan(xml.indexOf('<w:tblOverlap'))
|
||||
})
|
||||
|
||||
it('omits tblpPr without floatPos (existing callers unchanged)', () => {
|
||||
const xml = generateTableModelXml({ ...model, floatPos: undefined })
|
||||
expect(xml).not.toContain('tblpPr')
|
||||
expect(xml).not.toContain('tblOverlap')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* Run-level RTL (w:rtl) + complex-script font slot (rFonts w:cs) — added for
|
||||
* pdf2docx P2. The round-trip rule: untouched runs keep their original bytes;
|
||||
* runs without cs info generate exactly what they did before.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateParagraphXml, parseDocx, saveDocx, type GenerateContext } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const GEN_CTX: GenerateContext = {
|
||||
headingStyleIds: new Map([[1, 'Heading1']]),
|
||||
allocateHyperlinkRel: () => 'rId999',
|
||||
}
|
||||
|
||||
const AR_RPR =
|
||||
'<w:rPr>' +
|
||||
'<w:rFonts w:ascii="Arial" w:hAnsi="Arial" w:cs="Traditional Arabic"/>' +
|
||||
'<w:sz w:val="24"/><w:szCs w:val="24"/><w:rtl/>' +
|
||||
'</w:rPr>'
|
||||
const AR_BODY =
|
||||
`<w:p><w:pPr><w:bidi/></w:pPr><w:r>${AR_RPR}<w:t>مرحبا</w:t></w:r></w:p>` +
|
||||
'<w:p><w:r><w:rPr><w:rtl w:val="0"/></w:rPr><w:t>ltr</w:t></w:r></w:p>'
|
||||
|
||||
describe('run-level w:rtl + rFonts w:cs slot', () => {
|
||||
it('parses w:rtl and the literal w:cs font into the run model', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: AR_BODY }))
|
||||
const run = doc.blocks[0].runs![0]
|
||||
expect(run.rtl).toBe(true)
|
||||
expect(run.fontCs).toBe('Traditional Arabic')
|
||||
expect(run.fontAscii).toBe('Arial')
|
||||
// negated rtl parses as explicit false
|
||||
expect(doc.blocks[1].runs![0].rtl).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps untouched RTL runs byte-identical through save', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: AR_BODY })
|
||||
const doc = await parseDocx(bytes)
|
||||
const blocks = doc.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
|
||||
expect(await saveDocx(doc, blocks)).toEqual(bytes)
|
||||
})
|
||||
|
||||
it('re-generating a parsed RTL run keeps its original rPr bytes (group equality)', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: AR_BODY }))
|
||||
const run = doc.blocks[0].runs![0]
|
||||
const xml = generateParagraphXml({ type: 'paragraph', runs: [{ ...run }] }, GEN_CTX)
|
||||
expect(xml).toContain(AR_RPR)
|
||||
})
|
||||
|
||||
it('generates w:rtl and the cs slot for model-only runs, in schema order', () => {
|
||||
const xml = generateParagraphXml(
|
||||
{
|
||||
type: 'paragraph',
|
||||
format: { bidi: true },
|
||||
runs: [
|
||||
{
|
||||
text: 'שלום',
|
||||
rtl: true,
|
||||
fontAscii: 'David',
|
||||
fontCs: 'David',
|
||||
sizeHalfPoints: 24,
|
||||
vertAlign: 'superscript',
|
||||
},
|
||||
],
|
||||
},
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(xml).toContain('<w:rFonts w:ascii="David" w:hAnsi="David" w:cs="David"/>')
|
||||
// schema order: vertAlign before rtl
|
||||
expect(xml).toMatch(/<w:vertAlign w:val="superscript"\/><w:rtl\/>/)
|
||||
expect(xml).toContain('<w:bidi/>')
|
||||
})
|
||||
|
||||
it('runs without cs info generate exactly the legacy rFonts shape', () => {
|
||||
const xml = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ text: 'plain', fontAscii: 'Georgia' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(xml).toContain('<w:rFonts w:ascii="Georgia" w:hAnsi="Georgia" w:cs="Georgia"/>')
|
||||
expect(xml).not.toContain('<w:rtl/>')
|
||||
})
|
||||
|
||||
it('editing the cs font rebuilds only that slot inside the original rFonts', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: AR_BODY }))
|
||||
const run = doc.blocks[0].runs![0]
|
||||
const xml = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ ...run, fontCs: 'Simplified Arabic' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(xml).toContain('<w:rFonts w:ascii="Arial" w:hAnsi="Arial" w:cs="Simplified Arabic"/>')
|
||||
expect(xml).toContain('<w:rtl/>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('table cell paragraphs carry w:bidi (visual↔logical jc swap)', () => {
|
||||
it('emits bidi + swapped jc for RTL cell paragraphs', async () => {
|
||||
const { generateTableModelXml } = await import('../src/index')
|
||||
const xml = generateTableModelXml({
|
||||
rows: [
|
||||
[
|
||||
{
|
||||
paras: ['مرحبا'],
|
||||
richParas: [{ bidi: true, align: 'left', runs: [{ text: 'مرحبا', rtl: true }] }],
|
||||
},
|
||||
{ paras: ['plain'], richParas: [{ align: 'left', runs: [{ text: 'plain' }] }] },
|
||||
],
|
||||
],
|
||||
})
|
||||
// visual left maps back to logical right inside a bidi cell paragraph
|
||||
expect(xml).toContain('<w:pPr><w:bidi/><w:jc w:val="right"/></w:pPr>')
|
||||
// non-bidi cell paragraphs are untouched
|
||||
expect(xml).toContain('<w:pPr><w:jc w:val="left"/></w:pPr>')
|
||||
expect(xml).toContain('<w:rtl/>')
|
||||
})
|
||||
})
|
||||
@@ -360,6 +360,81 @@ describe('sectionHf per-section headers/footers', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('column widths + section bidi (P3 pdf2docx support)', () => {
|
||||
const BASE =
|
||||
'<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/></w:sectPr>'
|
||||
|
||||
it('colWidths emits explicit unequal w:col children', async () => {
|
||||
const { sectionSettingsFromXml } = await import('../src/index')
|
||||
const base = sectionSettingsFromXml(BASE)
|
||||
const xml = applySectionSettings(BASE, {
|
||||
...base,
|
||||
columns: 2,
|
||||
colSpace: 400,
|
||||
colWidths: [3000, 6000],
|
||||
})
|
||||
expect(xml).toContain(
|
||||
'<w:cols w:num="2" w:space="400" w:equalWidth="0"><w:col w:w="3000" w:space="400"/><w:col w:w="6000"/></w:cols>',
|
||||
)
|
||||
})
|
||||
|
||||
it('parse reads colWidths and bidi back; re-applying identical values is byte-stable', async () => {
|
||||
const { sectionSettingsFromXml } = await import('../src/index')
|
||||
const base = sectionSettingsFromXml(BASE)
|
||||
const once = applySectionSettings(BASE, {
|
||||
...base,
|
||||
columns: 2,
|
||||
colSpace: 400,
|
||||
colWidths: [3000, 6000],
|
||||
bidi: true,
|
||||
})
|
||||
expect(once).toContain('<w:bidi/>')
|
||||
const parsed = sectionSettingsFromXml(once)
|
||||
expect(parsed.columns).toBe(2)
|
||||
expect(parsed.colWidths).toEqual([3000, 6000])
|
||||
expect(parsed.bidi).toBe(true)
|
||||
// round-trip: parse → apply must not rewrite the element
|
||||
expect(applySectionSettings(once, parsed)).toBe(once)
|
||||
})
|
||||
|
||||
it('undefined bidi leaves an existing w:bidi untouched; false removes it', async () => {
|
||||
const { sectionSettingsFromXml } = await import('../src/index')
|
||||
const withBidi = BASE.replace('</w:sectPr>', '<w:bidi/></w:sectPr>')
|
||||
const base = sectionSettingsFromXml(BASE)
|
||||
const kept = applySectionSettings(withBidi, { ...base, bidi: undefined })
|
||||
expect(kept).toContain('<w:bidi/>')
|
||||
const removed = applySectionSettings(withBidi, { ...base, bidi: false })
|
||||
expect(removed).not.toContain('<w:bidi/>')
|
||||
})
|
||||
|
||||
it('NewImage posOffsetEmu positions a floating image numerically', async () => {
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: P('文字') }))
|
||||
const blocks: SaveBlock[] = [
|
||||
...parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
|
||||
{
|
||||
kind: 'image',
|
||||
image: {
|
||||
base64:
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
|
||||
mime: 'image/png',
|
||||
widthPx: 100,
|
||||
heightPx: 80,
|
||||
wrap: 'square-right',
|
||||
posOffsetEmu: { x: 4165600, y: 0 },
|
||||
},
|
||||
},
|
||||
]
|
||||
const saved = await saveDocx(parsed, blocks, {})
|
||||
const reparsed = await parseDocx(saved)
|
||||
const xml = reparsed.internal.documentXml
|
||||
expect(xml).toContain('<wp:anchor')
|
||||
expect(xml).toContain('<wp:posOffset>4165600</wp:posOffset>')
|
||||
expect(xml).toContain('<wp:wrapSquare')
|
||||
})
|
||||
})
|
||||
|
||||
describe('pgNumType page numbering', () => {
|
||||
it('applyPageNumType inserts/replaces/removes', async () => {
|
||||
const { applyPageNumType } = await import('../src/index')
|
||||
|
||||
@@ -116,6 +116,17 @@ describe('generateTableModelXml', () => {
|
||||
expect(model.colWidthsPct?.map(Math.round)).toEqual([25, 35, 40])
|
||||
})
|
||||
|
||||
it('emits and round-trips the table left indent (w:tblInd, P17)', async () => {
|
||||
const xml = generateTableModelXml({
|
||||
colWidthsTwips: [2000, 2000],
|
||||
indentTwips: 1300,
|
||||
rows: [[{ paras: ['a'] }, { paras: ['b'] }]],
|
||||
})
|
||||
expect(xml).toContain('<w:tblInd w:w="1300" w:type="dxa"/>')
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
expect(parsed.blocks[0].table!.indentTwips).toBe(1300)
|
||||
})
|
||||
|
||||
it('reuses the imported tblPr while regenerating rows and rich runs', async () => {
|
||||
const template =
|
||||
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/>' +
|
||||
|
||||
@@ -42,6 +42,36 @@ describe('paragraph shading and borders', () => {
|
||||
expect(doc.blocks[0].format?.borders).toBe('tb')
|
||||
})
|
||||
|
||||
it('borderStyle sets color, thickness and text gap on the border sides', async () => {
|
||||
const xml = generateParagraphXml(
|
||||
{
|
||||
type: 'paragraph',
|
||||
format: {
|
||||
borders: 't',
|
||||
borderStyle: { color: '0A3C61', szEighths: 12, spacePt: 11 },
|
||||
},
|
||||
runs: [{ text: 'ruled title' }],
|
||||
},
|
||||
CTX,
|
||||
)
|
||||
expect(xml).toContain('<w:top w:val="single" w:sz="12" w:space="11" w:color="0A3C61"/>')
|
||||
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
expect(doc.blocks[0].format?.borders).toBe('t')
|
||||
})
|
||||
|
||||
it("borderStyle clamps w:space to Word's 31pt limit and floors w:sz", async () => {
|
||||
const xml = generateParagraphXml(
|
||||
{
|
||||
type: 'paragraph',
|
||||
format: { borders: 'b', borderStyle: { szEighths: 1, spacePt: 99 } },
|
||||
runs: [{ text: 'x' }],
|
||||
},
|
||||
CTX,
|
||||
)
|
||||
expect(xml).toContain('<w:bottom w:val="single" w:sz="2" w:space="31" w:color="auto"/>')
|
||||
})
|
||||
|
||||
it('keeps declared pBdr color and width (w:sz eighth-points -> pt)', async () => {
|
||||
const xml =
|
||||
'<w:p><w:pPr><w:pBdr>' +
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
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"'
|
||||
|
||||
function textWsp(opts: {
|
||||
cx: number
|
||||
cy: number
|
||||
text: string
|
||||
offY?: number
|
||||
autoFit?: boolean
|
||||
}): string {
|
||||
return (
|
||||
`<wps:wsp ${WPS_NS}><wps:cNvSpPr txBox="1"/><wps:spPr>` +
|
||||
`<a:xfrm><a:off x="0" y="${opts.offY ?? 0}"/><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.autoFit ? '<a:spAutoFit/>' : ''}</wps:bodyPr></wps:wsp>`
|
||||
)
|
||||
}
|
||||
|
||||
function drawing(opts: {
|
||||
offXEmu: number
|
||||
offYEmu: number
|
||||
cx: number
|
||||
cy: number
|
||||
text: string
|
||||
wrap: string
|
||||
relV?: string
|
||||
inner?: string
|
||||
}): string {
|
||||
return (
|
||||
`<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.offXEmu}</wp:posOffset></wp:positionH>` +
|
||||
`<wp:positionV relativeFrom="${opts.relV ?? 'paragraph'}"><wp:posOffset>${opts.offYEmu}</wp:posOffset></wp:positionV>` +
|
||||
`<wp:extent cx="${opts.cx}" cy="${opts.cy}"/>${opts.wrap}` +
|
||||
`<wp:docPr id="1" name="Box"/>` +
|
||||
`<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">` +
|
||||
(opts.inner ?? textWsp(opts)) +
|
||||
`</a:graphicData></a:graphic></wp:anchor></w:drawing>`
|
||||
)
|
||||
}
|
||||
|
||||
describe('wrapTopAndBottom band reservation', () => {
|
||||
it('marks both boxes of a two-anchor paragraph floating with their band bottoms', async () => {
|
||||
const para =
|
||||
`<w:p><w:r>` +
|
||||
drawing({
|
||||
offXEmu: 0,
|
||||
offYEmu: 0,
|
||||
cx: 1905000,
|
||||
cy: 257175, // 27 px
|
||||
text: 'card',
|
||||
wrap: '<wp:wrapTopAndBottom/>',
|
||||
}) +
|
||||
drawing({
|
||||
offXEmu: 2857500,
|
||||
offYEmu: 914400, // 96 px
|
||||
cx: 1905000,
|
||||
cy: 952500, // 100 px
|
||||
text: 'chip',
|
||||
wrap: '<wp:wrapTopAndBottom/>',
|
||||
}) +
|
||||
`</w:r></w:p>`
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
|
||||
const boxes = doc.blocks[0].textboxes
|
||||
expect(boxes?.length).toBe(2)
|
||||
const [card, chip] = boxes!
|
||||
expect(card.floating).toBe(true)
|
||||
expect(card.bandTopPx).toBe(0)
|
||||
expect(card.bandBottomPx).toBe(27)
|
||||
expect(chip.floating).toBe(true)
|
||||
expect(chip.offsetXEmu).toBe(2857500)
|
||||
expect(chip.bandTopPx).toBe(96)
|
||||
expect(chip.bandBottomPx).toBe(196)
|
||||
})
|
||||
|
||||
it('floats a lone topAndBottom box and reserves offset + height', async () => {
|
||||
const para =
|
||||
`<w:p><w:r>` +
|
||||
drawing({
|
||||
offXEmu: 91440,
|
||||
offYEmu: 190500, // 20 px
|
||||
cx: 1905000,
|
||||
cy: 476250, // 50 px
|
||||
text: 'solo',
|
||||
wrap: '<wp:wrapTopAndBottom/>',
|
||||
}) +
|
||||
`</w:r></w:p>`
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
|
||||
const [box] = doc.blocks[0].textboxes!
|
||||
expect(box.floating).toBe(true)
|
||||
expect(box.bandTopPx).toBe(20)
|
||||
expect(box.bandBottomPx).toBe(70)
|
||||
})
|
||||
|
||||
it('skips the extent fallback for a group child without its own height', async () => {
|
||||
const group =
|
||||
`<wpg:wgp xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup">` +
|
||||
`<wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="3810000" cy="1905000"/>` +
|
||||
`<a:chOff x="0" y="0"/><a:chExt cx="3810000" cy="1905000"/></a:xfrm></wpg:grpSpPr>` +
|
||||
textWsp({ cx: 1905000, cy: 476250, text: 'fixed' }) +
|
||||
textWsp({ cx: 1905000, cy: 476250, text: 'grows', offY: 476250, autoFit: true }) +
|
||||
`</wpg:wgp>`
|
||||
const para =
|
||||
`<w:p><w:r>` +
|
||||
drawing({
|
||||
offXEmu: 0,
|
||||
offYEmu: 190500, // 20 px
|
||||
cx: 3810000,
|
||||
cy: 1905000, // 200 px: whole-group extent, not any child's height
|
||||
text: '',
|
||||
wrap: '<wp:wrapTopAndBottom/>',
|
||||
inner: group,
|
||||
}) +
|
||||
`</w:r></w:p>`
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
|
||||
const boxes = doc.blocks[0].textboxes
|
||||
expect(boxes?.length).toBe(2)
|
||||
const [fixed, grows] = boxes!
|
||||
expect(fixed.bandTopPx).toBe(20)
|
||||
expect(fixed.bandBottomPx).toBe(70)
|
||||
expect(grows.floating).toBe(true)
|
||||
expect(grows.bandTopPx).toBeUndefined()
|
||||
expect(grows.bandBottomPx).toBeUndefined()
|
||||
})
|
||||
|
||||
it('clamps a negative offset band to the below-anchor extent', async () => {
|
||||
const para =
|
||||
`<w:p><w:r>` +
|
||||
drawing({
|
||||
offXEmu: 0,
|
||||
offYEmu: -95250, // -10 px
|
||||
cx: 1905000,
|
||||
cy: 476250, // 50 px
|
||||
text: 'raised',
|
||||
wrap: '<wp:wrapTopAndBottom/>',
|
||||
}) +
|
||||
`</w:r></w:p>`
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
|
||||
const [box] = doc.blocks[0].textboxes!
|
||||
expect(box.floating).toBe(true)
|
||||
expect(box.bandTopPx).toBe(-10)
|
||||
expect(box.bandBottomPx).toBe(40)
|
||||
})
|
||||
|
||||
it('leaves page-relative topAndBottom anchors on their previous path', async () => {
|
||||
const para =
|
||||
`<w:p><w:r>` +
|
||||
drawing({
|
||||
offXEmu: 0,
|
||||
offYEmu: 914400,
|
||||
cx: 1905000,
|
||||
cy: 476250,
|
||||
text: 'pagebox',
|
||||
wrap: '<wp:wrapTopAndBottom/>',
|
||||
relV: 'page',
|
||||
}) +
|
||||
`</w:r></w:p>`
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
|
||||
const [box] = doc.blocks[0].textboxes!
|
||||
expect(box.floating).toBeUndefined()
|
||||
expect(box.bandBottomPx).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps wrapNone semantics unchanged (floating, no band)', async () => {
|
||||
const para =
|
||||
`<w:p><w:r>` +
|
||||
drawing({
|
||||
offXEmu: 0,
|
||||
offYEmu: 190500,
|
||||
cx: 1905000,
|
||||
cy: 476250,
|
||||
text: 'overlay',
|
||||
wrap: '<wp:wrapNone/>',
|
||||
}) +
|
||||
`</w:r></w:p>`
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
|
||||
const [box] = doc.blocks[0].textboxes!
|
||||
expect(box.floating).toBe(true)
|
||||
expect(box.bandBottomPx).toBeUndefined()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user