Sync snapshot (2026-08-13) (#92)
- Docs: print dialog with live page preview and range selection; WYSIWYG print preview across apps - Docs: header/footer fidelity - alignment, color, size, images, and tab layout (w:tabs, w:ptab) - Docs: pagination and layout fixes - keepNext crash, blank pages, footnotes, line-height, font substitution, Tamil support - Sheets: import implicit cell addresses and row/column default styles; keep dialog inputs inside narrow grid columns - Slides: PowerPoint-style stage rulers, wheel page turning, and notes bar - Slides: insert 3-D pie and 3-D column charts; render 3-D chart variants as 2-D projections - PDF: comments margin with pin leader lines, note threads with replies, and selection-level text styles - PDF: searchable text insertion, page management, and auto-opening of extract/split output Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
945c370fb9
commit
d5558b6bbb
@@ -940,13 +940,18 @@ function formatPPrChildren(format: ParaFormat | undefined): PPrChild[] {
|
||||
const out: PPrChild[] = []
|
||||
if (format.pageBreakBefore) out.push({ name: 'w:pageBreakBefore', xml: '<w:pageBreakBefore/>' })
|
||||
if (format.borders) {
|
||||
const line = (side: string) => `<w:${side} w:val="single" w:sz="4" w:space="1" w: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 sides: string[] = []
|
||||
// schema order inside pBdr: top, left, bottom, right
|
||||
if (format.borders.includes('t')) sides.push(line('top'))
|
||||
if (format.borders.includes('l')) sides.push(line('left'))
|
||||
if (format.borders.includes('b')) sides.push(line('bottom'))
|
||||
if (format.borders.includes('r')) sides.push(line('right'))
|
||||
if (format.borders.includes('t')) sides.push(line('top', 't'))
|
||||
if (format.borders.includes('l')) sides.push(line('left', 'l'))
|
||||
if (format.borders.includes('b')) sides.push(line('bottom', 'b'))
|
||||
if (format.borders.includes('r')) sides.push(line('right', 'r'))
|
||||
if (sides.length > 0) out.push({ name: 'w:pBdr', xml: `<w:pBdr>${sides.join('')}</w:pBdr>` })
|
||||
}
|
||||
if (format.shadingFill) {
|
||||
@@ -1105,6 +1110,7 @@ function rawIndUnchanged(raw: string | undefined, f: ParaFormat): boolean {
|
||||
|
||||
function rawPBdrUnchanged(raw: string | undefined, f: ParaFormat): boolean {
|
||||
let rawBorders = ''
|
||||
const rawLines: NonNullable<ParaFormat['borderLines']> = {}
|
||||
if (raw) {
|
||||
const inner = raw.replace(/^<w:pBdr[^>]*>/, '').replace(/<\/w:pBdr>$/, '')
|
||||
const kids = splitXmlChildren(inner)
|
||||
@@ -1118,11 +1124,26 @@ function rawPBdrUnchanged(raw: string | undefined, f: ParaFormat): boolean {
|
||||
// mirror extractParaFormat: nil is a reset, not a border, or the raw/model
|
||||
// comparison never matches and the pBdr always gets rebuilt from the model
|
||||
const val = el ? rawAttr(el.xml, 'w:val') : undefined
|
||||
if (el && val !== 'none' && val !== 'nil') rawBorders += ch
|
||||
if (!el || val === 'none' || val === 'nil') continue
|
||||
rawBorders += ch
|
||||
const color = rawAttr(el.xml, 'w:color')
|
||||
const sz = parseInt(rawAttr(el.xml, 'w:sz') ?? '', 10)
|
||||
const line: NonNullable<ParaFormat['borderLines']>[typeof ch] = {}
|
||||
if (color && color !== 'auto') line.color = color
|
||||
if (Number.isFinite(sz) && sz > 0) line.szPt = sz / 8
|
||||
if (line.color !== undefined || line.szPt !== undefined) rawLines[ch] = line
|
||||
}
|
||||
}
|
||||
const norm = (s: string | undefined) => (s ? [...new Set(s)].sort().join('') : '')
|
||||
return norm(rawBorders) === norm(f.borders)
|
||||
if (norm(rawBorders) !== norm(f.borders)) return false
|
||||
const normLines = (lines: ParaFormat['borderLines']) =>
|
||||
JSON.stringify(
|
||||
(['t', 'b', 'l', 'r'] as const).map((ch) => [
|
||||
lines?.[ch]?.color ?? null,
|
||||
lines?.[ch]?.szPt ?? null,
|
||||
]),
|
||||
)
|
||||
return normLines(rawLines) === normLines(f.borderLines)
|
||||
}
|
||||
|
||||
function rawTabsUnchanged(raw: string | undefined, stops: TabStop[]): boolean {
|
||||
|
||||
@@ -66,7 +66,8 @@ export function parseNotesXml(xml: string, kind: NoteKind): NoteInfo[] {
|
||||
const richParas = noteRichParas(entryXml)
|
||||
const hasFormat = richParas.some((paras) =>
|
||||
paras.some(
|
||||
(r) => r.bold || r.italic || r.underline || r.strike || r.color || r.sizeHalfPoints,
|
||||
(r) =>
|
||||
r.bold || r.italic || r.underline || r.strike || r.color || r.sizeHalfPoints || r.caps,
|
||||
),
|
||||
)
|
||||
return { id, text, ...(hasFormat ? { richParas } : {}) }
|
||||
@@ -101,6 +102,8 @@ function noteRichParas(entryXml: string): NoteRun[][] {
|
||||
if (color) run.color = color.toUpperCase()
|
||||
const sz = /<w:sz [^>]*w:val="(\d+)"/.exec(rPr)?.[1]
|
||||
if (sz) run.sizeHalfPoints = parseInt(sz, 10)
|
||||
if (flag(rPr, 'caps')) run.caps = 'all'
|
||||
else if (flag(rPr, 'smallCaps')) run.caps = 'small'
|
||||
runs.push(run)
|
||||
}
|
||||
out.push(runs)
|
||||
|
||||
@@ -218,6 +218,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
'header',
|
||||
'default',
|
||||
theme.colors,
|
||||
styles,
|
||||
)
|
||||
const footer = await readHeaderFooterPart(
|
||||
zip,
|
||||
@@ -226,6 +227,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
'footer',
|
||||
'default',
|
||||
theme.colors,
|
||||
styles,
|
||||
)
|
||||
const headerFirst = await readHeaderFooterPart(
|
||||
zip,
|
||||
@@ -234,6 +236,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
'header',
|
||||
'first',
|
||||
theme.colors,
|
||||
styles,
|
||||
)
|
||||
const footerFirst = await readHeaderFooterPart(
|
||||
zip,
|
||||
@@ -242,6 +245,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
'footer',
|
||||
'first',
|
||||
theme.colors,
|
||||
styles,
|
||||
)
|
||||
const headerEven = await readHeaderFooterPart(
|
||||
zip,
|
||||
@@ -250,6 +254,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
'header',
|
||||
'even',
|
||||
theme.colors,
|
||||
styles,
|
||||
)
|
||||
const footerEven = await readHeaderFooterPart(
|
||||
zip,
|
||||
@@ -258,10 +263,11 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
'footer',
|
||||
'even',
|
||||
theme.colors,
|
||||
styles,
|
||||
)
|
||||
const titlePg = /<w:titlePg\s*\/>/.test(documentXml)
|
||||
const evenAndOddHeaders = await parseEvenAndOddHeaders(zip)
|
||||
const hfParts = await parseAllHfParts(zip, rels, theme.colors)
|
||||
const hfParts = await parseAllHfParts(zip, rels, styles, theme.colors)
|
||||
|
||||
// ink annotations (freehand strokes): our own anchored floating pictures, restored
|
||||
// into an editable overlay layer instead of being shown as image blocks
|
||||
@@ -396,9 +402,10 @@ function parseSdtBlock(sdtXml: string): { shell: SdtShell; pXml: string } | null
|
||||
if (!contentOpen) return null
|
||||
|
||||
const contentTagEnd = contentOpen.index + contentOpen[0].length
|
||||
// find the matching </w:sdtContent>
|
||||
const contentClose = sdtXml.indexOf('</w:sdtContent>', contentTagEnd)
|
||||
if (contentClose === -1) return null
|
||||
// find the matching </w:sdtContent> — last one, so nested content controls
|
||||
// don't truncate the region (same boundary rule as splitSdtParts/sdtTableXml)
|
||||
const contentClose = sdtXml.lastIndexOf('</w:sdtContent>')
|
||||
if (contentClose < contentTagEnd) return null
|
||||
|
||||
// extract the first w:p inside sdtContent
|
||||
const innerContent = sdtXml.slice(contentTagEnd, contentClose)
|
||||
@@ -480,6 +487,10 @@ function splitSdtParts(sdtXml: string): SdtPart[] | null {
|
||||
let name = ''
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = tagRe.exec(sdtXml)) !== null && m.index < innerEnd) {
|
||||
// nested content controls are transparent containers (Word cover-page
|
||||
// building blocks wrap each field in its own sdt): descend instead of
|
||||
// treating the inner sdt as one opaque child
|
||||
if (m[2] === 'w:sdt' || m[2] === 'w:sdtContent') continue
|
||||
if (m[1] === '/') {
|
||||
depth--
|
||||
if (depth === 0) children.push({ name, start, end: m.index + m[0].length })
|
||||
@@ -626,8 +637,8 @@ async function buildBlock(
|
||||
}
|
||||
return innerBlock
|
||||
}
|
||||
// No usable paragraph found → passthrough
|
||||
return { ...base, type: 'passthrough', label: 'Content control', previewText: '' }
|
||||
// No usable paragraph found → passthrough; keep the text visible at least
|
||||
return { ...base, type: 'passthrough', label: 'Content control', previewText: plainText(xml) }
|
||||
}
|
||||
if (INVISIBLE_BODY_MARKERS.has(el.name)) {
|
||||
return { ...base, type: 'passthrough', label: el.name, invisibleMarker: true }
|
||||
@@ -803,6 +814,25 @@ async function buildBlock(
|
||||
) {
|
||||
return { ...base, type: 'passthrough', label: 'Drawing object', invisibleMarker: true }
|
||||
}
|
||||
// VML horizontal rule (<hr> import: <v:rect o:hr="t">): Word draws a thin
|
||||
// line at the declared height; a full-width chip both misrenders it and
|
||||
// eats ~a line of page budget per rule
|
||||
const hrRect = !detect.includes('<w:object')
|
||||
? /<v:rect\b[^>]*\bo:hr="t"[^>]*>/.exec(detect)?.[0]
|
||||
: undefined
|
||||
if (hrRect && plainText(detect).trim() === '') {
|
||||
const fill = /fillcolor="#?([0-9A-Fa-f]{6})"/.exec(hrRect)?.[1]
|
||||
const hPt = parseFloat(/height:([\d.]+)pt/.exec(hrRect)?.[1] ?? '')
|
||||
return {
|
||||
...base,
|
||||
type: 'passthrough',
|
||||
label: 'Drawing object',
|
||||
decorative: true,
|
||||
...(fill ? { ruleColorHex: fill.toUpperCase() } : {}),
|
||||
// VML HR width:0 means "fill the available width" — ruleWidthPx stays unset
|
||||
...(hPt > 0 ? { ruleThicknessPx: Math.max(1, Math.round((hPt / 72) * 96)) } : {}),
|
||||
}
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
type: 'passthrough',
|
||||
@@ -1913,6 +1943,33 @@ function autoSpaceOf(pPr: XNode): boolean | undefined {
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** pPr <w:tabs> → TabStop[] (shared by direct paragraph format and style display) */
|
||||
function tabStopsOf(pPr: XNode): import('./types').TabStop[] | undefined {
|
||||
const tabsEl = findChild(pPr, 'w:tabs')
|
||||
if (!tabsEl) return undefined
|
||||
const stops: import('./types').TabStop[] = []
|
||||
for (const tab of findChildren(tabsEl, 'w:tab')) {
|
||||
const attrs = attrsOf(tab)
|
||||
const pos = parseInt(attrs['w:pos'] ?? '', 10)
|
||||
const val = attrs['w:val'] ?? 'left'
|
||||
if (!Number.isFinite(pos)) continue
|
||||
const validVals = ['left', 'center', 'right', 'decimal', 'bar', 'clear'] as const
|
||||
const safeVal = validVals.includes(val as (typeof validVals)[number])
|
||||
? (val as (typeof validVals)[number])
|
||||
: 'left'
|
||||
const stop: import('./types').TabStop = { pos, val: safeVal }
|
||||
const leader = attrs['w:leader']
|
||||
if (leader && leader !== 'none') {
|
||||
const validLeaders = ['dot', 'hyphen', 'underscore', 'heavy', 'middleDot'] as const
|
||||
if (validLeaders.includes(leader as (typeof validLeaders)[number])) {
|
||||
stop.leader = leader as (typeof validLeaders)[number]
|
||||
}
|
||||
}
|
||||
stops.push(stop)
|
||||
}
|
||||
return stops.length > 0 ? stops : undefined
|
||||
}
|
||||
|
||||
function extractParaFormat(pPr: XNode): ParaFormat | undefined {
|
||||
const format: ParaFormat = {}
|
||||
if (boolProp(pPr, 'w:bidi')) format.bidi = true
|
||||
@@ -1991,47 +2048,38 @@ function extractParaFormat(pPr: XNode): ParaFormat | undefined {
|
||||
const fill = attrsOf(shd)['w:fill']
|
||||
if (fill && fill !== 'auto') format.shadingFill = fill
|
||||
}
|
||||
const pBdr = findChild(pPr, 'w:pBdr')
|
||||
if (pBdr) {
|
||||
const pBdrs = findChildren(pPr, 'w:pBdr')
|
||||
if (pBdrs.length > 0) {
|
||||
let borders = ''
|
||||
const lines: NonNullable<ParaFormat['borderLines']> = {}
|
||||
for (const [side, ch] of [
|
||||
['top', 't'],
|
||||
['bottom', 'b'],
|
||||
['left', 'l'],
|
||||
['right', 'r'],
|
||||
] as const) {
|
||||
const el = findChild(pBdr, `w:${side}`)
|
||||
// duplicated w:pBdr: later containers override earlier ones per side
|
||||
let el: XNode | undefined
|
||||
for (const pBdr of pBdrs) el = findChild(pBdr, `w:${side}`) ?? el
|
||||
// ST_Border spells "no border" both ways, and Word writes nil whenever a style-level
|
||||
// border is reset, so treating it as present stamps a rule the document never had
|
||||
const val = el ? attrsOf(el)['w:val'] : undefined
|
||||
if (el && val !== 'none' && val !== 'nil') borders += ch
|
||||
const attrs = el ? attrsOf(el) : undefined
|
||||
const val = attrs?.['w:val']
|
||||
if (!el || val === 'none' || val === 'nil') continue
|
||||
borders += ch
|
||||
const line: import('./types').ParaBorderLine = {}
|
||||
if (attrs?.['w:color'] && attrs['w:color'] !== 'auto') line.color = attrs['w:color']
|
||||
const sz = parseInt(attrs?.['w:sz'] ?? '', 10)
|
||||
if (Number.isFinite(sz) && sz > 0) line.szPt = sz / 8
|
||||
if (line.color !== undefined || line.szPt !== undefined) lines[ch] = line
|
||||
}
|
||||
if (borders) format.borders = borders
|
||||
}
|
||||
const tabsEl = findChild(pPr, 'w:tabs')
|
||||
if (tabsEl) {
|
||||
const stops: import('./types').TabStop[] = []
|
||||
for (const tab of findChildren(tabsEl, 'w:tab')) {
|
||||
const attrs = attrsOf(tab)
|
||||
const pos = parseInt(attrs['w:pos'] ?? '', 10)
|
||||
const val = attrs['w:val'] ?? 'left'
|
||||
if (!Number.isFinite(pos)) continue
|
||||
const validVals = ['left', 'center', 'right', 'decimal', 'bar', 'clear'] as const
|
||||
const safeVal = validVals.includes(val as (typeof validVals)[number])
|
||||
? (val as (typeof validVals)[number])
|
||||
: 'left'
|
||||
const stop: import('./types').TabStop = { pos, val: safeVal }
|
||||
const leader = attrs['w:leader']
|
||||
if (leader && leader !== 'none') {
|
||||
const validLeaders = ['dot', 'hyphen', 'underscore', 'heavy', 'middleDot'] as const
|
||||
if (validLeaders.includes(leader as (typeof validLeaders)[number])) {
|
||||
stop.leader = leader as (typeof validLeaders)[number]
|
||||
}
|
||||
}
|
||||
stops.push(stop)
|
||||
if (borders) {
|
||||
format.borders = borders
|
||||
if (Object.keys(lines).length > 0) format.borderLines = lines
|
||||
}
|
||||
if (stops.length > 0) format.tabStops = stops
|
||||
}
|
||||
const stops = tabStopsOf(pPr)
|
||||
if (stops) format.tabStops = stops
|
||||
// Drop cap: w:framePr w:dropCap="drop"|"margin"
|
||||
const framePr = findChild(pPr, 'w:framePr')
|
||||
if (framePr) {
|
||||
@@ -2308,6 +2356,8 @@ const EMPTY_EA_THEME_FONT = 'DengXian'
|
||||
/** empty EA slot faces by settings.xml w:themeFontLang w:eastAsia (zh-CN / missing → DengXian) */
|
||||
const EMPTY_EA_SLOT_BY_LANG: Record<string, { major: string; minor: string }> = {
|
||||
ja: { major: 'Yu Gothic', minor: 'Yu Mincho' },
|
||||
// Word probe + fontTable: ko-KR empty EA slot substitutes Malgun Gothic
|
||||
ko: { major: 'Malgun Gothic', minor: 'Malgun Gothic' },
|
||||
}
|
||||
|
||||
function emptyEaSlotFont(fonts: ThemeFonts, eaRef: string | undefined): string {
|
||||
@@ -2370,7 +2420,7 @@ function buildRun(
|
||||
for (const child of childrenOf(rNode)) {
|
||||
const name = nameOf(child)
|
||||
if (name === 'w:t' || name === 'w:delText') text += decodeNumericCharRefs(textOf(child))
|
||||
else if (name === 'w:tab') text += '\t'
|
||||
else if (name === 'w:tab' || name === 'w:ptab') text += '\t'
|
||||
// In-paragraph page breaks (w:br w:type="page") are encoded as \f and preserved; column/soft breaks become \n
|
||||
else if (name === 'w:br') text += attrsOf(child)['w:type'] === 'page' ? '\f' : '\n'
|
||||
else if (name === 'w:cr') text += '\n'
|
||||
@@ -2453,6 +2503,9 @@ function buildRun(
|
||||
if (rf.cs) run.csFont = rf.cs
|
||||
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)
|
||||
if (onOffOf(rPr, 'w:caps')) run.caps = 'all'
|
||||
else if (onOffOf(rPr, 'w:smallCaps')) run.caps = 'small'
|
||||
const wScale = parseInt(attrsOf(findChild(rPr, 'w:w') ?? {})['w:val'] ?? '', 10)
|
||||
if (wScale > 0 && wScale !== 100) run.charScalePct = wScale
|
||||
const highlight = attrsOf(findChild(rPr, 'w:highlight') ?? {})['w:val']
|
||||
@@ -2593,9 +2646,10 @@ function extractTable(xml: string, ctx: BuildContext): TableModel | undefined {
|
||||
|
||||
/** One w:tbl node → display model (shared by top-level tables and tables nested in cells) */
|
||||
/**
|
||||
* Per-column widths reconstructed from cell w:tcW (dxa) across all rows: the first
|
||||
* un-spanned cell seen per grid slot wins. Undefined unless every column got a value —
|
||||
* partial data would skew the ratio worse than the tblGrid fallback.
|
||||
* Per-column widths reconstructed from cell w:tcW (dxa) across all rows: the widest
|
||||
* un-spanned cell per grid slot wins (Word widens a column to fit later rows, never
|
||||
* narrows it). Undefined unless every column got a value — partial data would skew
|
||||
* the ratio worse than the tblGrid fallback.
|
||||
*/
|
||||
function tcwColumnWidths(tbl: XNode): number[] | undefined {
|
||||
const cols: number[] = []
|
||||
@@ -2611,7 +2665,7 @@ function tcwColumnWidths(tbl: XNode): number[] | undefined {
|
||||
// duplicated w:tcW: Word keeps the last occurrence (generators leave stale first values)
|
||||
const a = attrsOf(findChildren(tcPr ?? {}, 'w:tcW').at(-1) ?? {})
|
||||
const w = !a['w:type'] || a['w:type'] === 'dxa' ? Number(a['w:w']) || 0 : 0
|
||||
if (span === 1 && w > 0 && !(cols[idx] > 0)) cols[idx] = w
|
||||
if (span === 1 && w > 0) cols[idx] = Math.max(cols[idx] || 0, w)
|
||||
idx += span
|
||||
}
|
||||
colCount = Math.max(colCount, idx)
|
||||
@@ -2633,23 +2687,29 @@ function extractTableModel(tbl: XNode, ctx: BuildContext): TableModel | undefine
|
||||
if (widths.every((w) => w > 0)) colWidthsTwips = widths
|
||||
}
|
||||
}
|
||||
const tblPrNode = findChild(tbl, 'w:tblPr')
|
||||
const fixedLayout = attrsOf(findChild(tblPrNode ?? {}, 'w:tblLayout') ?? {})['w:type'] === 'fixed'
|
||||
// Cell-level w:tcW is Word's actual layout input for auto tables; generators often
|
||||
// leave a stale evenly-split tblGrid behind. When the two disagree, tcW wins.
|
||||
const tcwWidths = tcwColumnWidths(tbl)
|
||||
if (tcwWidths) {
|
||||
const tcwTotal = tcwWidths.reduce((a, b) => a + b, 0)
|
||||
const tcwPct = tcwWidths.map((w) => (w / tcwTotal) * 100)
|
||||
// Fixed layout sizes columns from tcW alone, so a matching ratio with a
|
||||
// different absolute sum still means the grid is stale.
|
||||
const gridTotal = (colWidthsTwips ?? []).reduce((a, b) => a + b, 0)
|
||||
const disagree =
|
||||
!colWidthsPct ||
|
||||
colWidthsPct.length !== tcwPct.length ||
|
||||
colWidthsPct.some((w, i) => Math.abs(w - tcwPct[i]) > 2)
|
||||
colWidthsPct.some((w, i) => Math.abs(w - tcwPct[i]) > 2) ||
|
||||
(fixedLayout && Math.abs(gridTotal - tcwTotal) > tcwWidths.length)
|
||||
if (disagree) {
|
||||
colWidthsPct = tcwPct
|
||||
colWidthsTwips = tcwWidths
|
||||
}
|
||||
}
|
||||
const tblPrNode = findChild(tbl, 'w:tblPr')
|
||||
const tblW = attrsOf(findChild(tblPrNode ?? {}, 'w:tblW') ?? {})
|
||||
const tblWNode = findChild(tblPrNode ?? {}, 'w:tblW')
|
||||
const tblW = attrsOf(tblWNode ?? {})
|
||||
let widthPct: number | undefined
|
||||
if (tblW['w:type'] === 'pct') {
|
||||
const raw = String(tblW['w:w'] ?? '')
|
||||
@@ -2658,7 +2718,7 @@ function extractTableModel(tbl: XNode, ctx: BuildContext): TableModel | undefine
|
||||
if (Number.isFinite(pct) && pct > 0 && pct <= 100) widthPct = pct
|
||||
}
|
||||
const cellMar = cellMarginsOf(findChild(tblPrNode ?? {}, 'w:tblCellMar'))
|
||||
const tblBorders = borderLinesOf(findChild(tblPrNode ?? {}, 'w:tblBorders'), true)
|
||||
const tblBorders = mergedBorderLinesOf(tblPrNode, 'w:tblBorders', true)
|
||||
const tblJc = attrsOf(findChild(tblPrNode ?? {}, 'w:jc') ?? {})['w:val']
|
||||
const tblAlign =
|
||||
tblJc === 'center' ? 'center' : tblJc === 'right' || tblJc === 'end' ? 'right' : undefined
|
||||
@@ -2705,6 +2765,12 @@ function extractTableModel(tbl: XNode, ctx: BuildContext): TableModel | undefine
|
||||
const model: TableModel = { rows, colWidthsPct }
|
||||
if (colWidthsTwips) model.colWidthsTwips = colWidthsTwips
|
||||
if (widthPct) model.widthPct = widthPct
|
||||
const tblWType = tblW['w:type']
|
||||
const autoWidth =
|
||||
!tblWNode ||
|
||||
tblWType === 'auto' ||
|
||||
((!tblWType || tblWType === 'dxa') && !(Number(tblW['w:w']) > 0))
|
||||
if (!fixedLayout && autoWidth && !widthPct) model.autoLayout = true
|
||||
if (effCellMar) model.cellMarTwips = effCellMar
|
||||
if (effBorders) model.borders = effBorders
|
||||
if (tblAlign) model.align = tblAlign
|
||||
@@ -2856,6 +2922,31 @@ function borderLinesOf(node: XNode | undefined, withInside: boolean): TableBorde
|
||||
return Object.keys(borders).length > 0 ? borders : undefined
|
||||
}
|
||||
|
||||
/** Duplicated border containers (two w:tcBorders in one tcPr etc.): Word merges per side, later wins */
|
||||
function mergedBorderLinesOf(
|
||||
parent: XNode | undefined,
|
||||
tag: string,
|
||||
withInside: true,
|
||||
): TableBorders | undefined
|
||||
function mergedBorderLinesOf(
|
||||
parent: XNode | undefined,
|
||||
tag: string,
|
||||
withInside: false,
|
||||
): CellBorders | undefined
|
||||
function mergedBorderLinesOf(
|
||||
parent: XNode | undefined,
|
||||
tag: string,
|
||||
withInside: boolean,
|
||||
): TableBorders | undefined {
|
||||
if (!parent) return undefined
|
||||
let merged: TableBorders | undefined
|
||||
for (const node of findChildren(parent, tag)) {
|
||||
const b = borderLinesOf(node, withInside as true)
|
||||
if (b) merged = { ...merged, ...b }
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
function cellMarginsOf(node: XNode | undefined): CellMargins | undefined {
|
||||
if (!node) return undefined
|
||||
const SIDES: Array<[string, keyof CellMargins]> = [
|
||||
@@ -2899,7 +2990,7 @@ function extractCell(tc: XNode, ctx: BuildContext): TableCell {
|
||||
else if (dir === 'btLr' || dir === 'btLrV') cell.textDirection = 'btLr'
|
||||
const hMerge = findChild(tcPr, 'w:hMerge')
|
||||
if (hMerge) cell.hMerge = attrsOf(hMerge)['w:val'] === 'restart' ? 'restart' : 'continue'
|
||||
const borders = borderLinesOf(findChild(tcPr, 'w:tcBorders'), false)
|
||||
const borders = mergedBorderLinesOf(tcPr, 'w:tcBorders', false)
|
||||
if (borders) cell.borders = borders
|
||||
for (const kind of ['ins', 'del'] as const) {
|
||||
const node = findChild(tcPr, kind === 'ins' ? 'w:cellIns' : 'w:cellDel')
|
||||
@@ -3005,10 +3096,22 @@ async function hfImages(zip: JSZip, partPath: string, partXml: string): Promise<
|
||||
const relsPath = partPath.replace(/([^/]+)$/, '_rels/$1.rels')
|
||||
const rels = await parseRels(zip, relsPath)
|
||||
const out: HfImage[] = []
|
||||
for (const frag of partXml.match(/<w:drawing>[\s\S]*?<\/w:drawing>/g) ?? []) {
|
||||
const rId = /<a:blip[^>]*r:embed="([^"]+)"/.exec(frag)?.[1]
|
||||
if (!rId) continue
|
||||
const dataUrl = await mediaDataUrl(zip, rels, rId)
|
||||
/** w:jc of the paragraph containing offset `at` (inline images follow it) */
|
||||
const paraAlignAt = (at: number): HfImage['align'] => {
|
||||
const pStart = Math.max(partXml.lastIndexOf('<w:p ', at), partXml.lastIndexOf('<w:p>', at))
|
||||
if (pStart < 0) return undefined
|
||||
const jc = /<w:jc w:val="(\w+)"/.exec(partXml.slice(pStart, at))?.[1]
|
||||
return jc === 'left' || jc === 'center' || jc === 'right' ? jc : undefined
|
||||
}
|
||||
for (const m of partXml.matchAll(/<w:drawing>[\s\S]*?<\/w:drawing>/g)) {
|
||||
const frag = m[0]
|
||||
// mc:AlternateContent may hold several blips (mac Word: PDF Choice + PNG
|
||||
// Fallback); use the first one whose media resolves
|
||||
let dataUrl: string | null = null
|
||||
for (const b of frag.matchAll(/<a:blip[^>]*r:embed="([^"]+)"/g)) {
|
||||
dataUrl = await mediaDataUrl(zip, rels, b[1])
|
||||
if (dataUrl) break
|
||||
}
|
||||
if (!dataUrl) continue
|
||||
const image: HfImage = { dataUrl }
|
||||
const extent = /<wp:extent[^>]*\/?>/.exec(frag)?.[0] ?? ''
|
||||
@@ -3017,9 +3120,14 @@ async function hfImages(zip: JSZip, partPath: string, partXml: string): Promise<
|
||||
if (Number.isFinite(cx) && cx > 0) image.widthPx = Math.round(cx / EMU_PER_PX)
|
||||
if (Number.isFinite(cy) && cy > 0) image.heightPx = Math.round(cy / EMU_PER_PX)
|
||||
if (/<wp:anchor[\s>]/.test(frag)) image.floating = true
|
||||
else {
|
||||
const align = paraAlignAt(m.index!)
|
||||
if (align) image.align = align
|
||||
}
|
||||
out.push(image)
|
||||
}
|
||||
for (const frag of partXml.match(/<w:pict>[\s\S]*?<\/w:pict>/g) ?? []) {
|
||||
for (const m of partXml.matchAll(/<w:pict>[\s\S]*?<\/w:pict>/g)) {
|
||||
const frag = m[0]
|
||||
if (frag.includes('<v:textpath')) continue
|
||||
const rId = /<v:imagedata[^>]*r:id="([^"]+)"/.exec(frag)?.[1]
|
||||
if (!rId) continue
|
||||
@@ -3041,6 +3149,9 @@ async function hfImages(zip: JSZip, partPath: string, partXml: string): Promise<
|
||||
const posV = /mso-position-vertical:(\w+)/.exec(style)?.[1]
|
||||
if (posH === 'left' || posH === 'center' || posH === 'right') image.posH = posH
|
||||
if (posV === 'top' || posV === 'center' || posV === 'bottom') image.posV = posV
|
||||
} else {
|
||||
const align = paraAlignAt(m.index!)
|
||||
if (align) image.align = align
|
||||
}
|
||||
if (/<v:imagedata[^>]*(?:gain|blacklevel)="/.test(frag)) image.washout = true
|
||||
out.push(image)
|
||||
@@ -3061,6 +3172,7 @@ function hfContentFromXml(
|
||||
xml: string,
|
||||
kind: 'header' | 'footer',
|
||||
theme?: ThemeColors | null,
|
||||
styles?: Map<string, StyleInfo>,
|
||||
): { text: string; hasPageNumber: boolean; watermark: string | null; paras: HfParagraph[] } {
|
||||
// Rewrite each field span (begin..end) for display. PAGE and NUMPAGES become
|
||||
// private-use markers (the renderer substitutes real numbers; a literal '#'
|
||||
@@ -3120,7 +3232,7 @@ function hfContentFromXml(
|
||||
hasPageNumber,
|
||||
watermark: kind === 'header' ? readWatermarkText(xml) : null,
|
||||
// strip leftover field chars so the page marker parses as plain text
|
||||
paras: hfParagraphs(cleaned.replace(/<w:fldChar[^>]*\/>/g, ''), theme),
|
||||
paras: hfParagraphs(cleaned.replace(/<w:fldChar[^>]*\/>/g, ''), theme, styles),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3132,6 +3244,7 @@ async function readHeaderFooterPart(
|
||||
kind: 'header' | 'footer',
|
||||
hfType: 'default' | 'first' | 'even' = 'default',
|
||||
theme?: ThemeColors | null,
|
||||
styles?: Map<string, StyleInfo>,
|
||||
): Promise<{
|
||||
text: string
|
||||
hasPageNumber: boolean
|
||||
@@ -3151,7 +3264,7 @@ async function readHeaderFooterPart(
|
||||
const file = zip.file(path)
|
||||
if (!file) return null
|
||||
const xml = await file.async('string')
|
||||
const content = hfContentFromXml(xml, kind, theme)
|
||||
const content = hfContentFromXml(xml, kind, theme, styles)
|
||||
const images = await hfImages(zip, path, xml)
|
||||
return images.length > 0 ? { ...content, images } : content
|
||||
}
|
||||
@@ -3160,6 +3273,7 @@ async function readHeaderFooterPart(
|
||||
async function parseAllHfParts(
|
||||
zip: JSZip,
|
||||
rels: Map<string, RelInfo>,
|
||||
styles: Map<string, StyleInfo> | undefined,
|
||||
theme?: ThemeColors | null,
|
||||
): Promise<Record<string, HfPartInfo>> {
|
||||
const out: Record<string, HfPartInfo> = {}
|
||||
@@ -3174,7 +3288,7 @@ async function parseAllHfParts(
|
||||
const file = zip.file(path)
|
||||
if (!file) continue
|
||||
const xml = await file.async('string')
|
||||
const content = hfContentFromXml(xml, kind, theme)
|
||||
const content = hfContentFromXml(xml, kind, theme, styles)
|
||||
const images = await hfImages(zip, path, xml)
|
||||
out[rId] = {
|
||||
text: content.text,
|
||||
@@ -3187,7 +3301,11 @@ async function parseAllHfParts(
|
||||
}
|
||||
|
||||
/** rich paragraphs of a header/footer part (watermark/drawing paragraphs skipped) */
|
||||
function hfParagraphs(partXml: string, theme?: ThemeColors | null): HfParagraph[] {
|
||||
function hfParagraphs(
|
||||
partXml: string,
|
||||
theme?: ThemeColors | null,
|
||||
styles?: Map<string, StyleInfo>,
|
||||
): HfParagraph[] {
|
||||
let parsed: XNode[]
|
||||
try {
|
||||
parsed = xmlParser.parse(partXml) as XNode[]
|
||||
@@ -3203,7 +3321,8 @@ function hfParagraphs(partXml: string, theme?: ThemeColors | null): HfParagraph[
|
||||
themeColors: theme,
|
||||
} as unknown as BuildContext
|
||||
const out: HfParagraph[] = []
|
||||
for (const node of childrenOf(root)) {
|
||||
// paragraphs may sit inside (nested) w:sdt content controls (OpenXML SDK footers)
|
||||
for (const node of childrenThroughSdt(root, ['w:tbl', 'w:p'])) {
|
||||
const name = nameOf(node)
|
||||
if (name === 'w:tbl') {
|
||||
// layout tables (logo | title | date rows): one display paragraph per row
|
||||
@@ -3221,7 +3340,36 @@ function hfParagraphs(partXml: string, theme?: ThemeColors | null): HfParagraph[
|
||||
continue
|
||||
}
|
||||
const pPr = findChild(pNode, 'w:pPr')
|
||||
out.push({ ...(pPr ? extractParaFormat(pPr) : {}), runs })
|
||||
const direct = pPr ? extractParaFormat(pPr) : undefined
|
||||
// display-only style layer: Word's built-in Header/Footer styles carry the
|
||||
// center/right tab stops (and sometimes w:jc); direct pPr wins per property
|
||||
const styleId = pPr ? attrsOf(findChild(pPr, 'w:pStyle') ?? {})['w:val'] : undefined
|
||||
const d = styleId ? styles?.get(styleId)?.display : undefined
|
||||
// absolute position tabs (w:ptab): carry their own alignment, ignore stops.
|
||||
// Indexed by overall tab order — regular w:tab occupies a slot as undefined,
|
||||
// so mixed tab/ptab paragraphs keep their alignments on the right segment.
|
||||
const ptabAligns: Array<'left' | 'center' | 'right' | undefined> = []
|
||||
let sawPtab = false
|
||||
const walkTabs = (n: XNode): void => {
|
||||
for (const c of childrenOf(n)) {
|
||||
const name = nameOf(c)
|
||||
if (name === 'w:pPr') continue
|
||||
if (name === 'w:tab') ptabAligns.push(undefined)
|
||||
else if (name === 'w:ptab') {
|
||||
sawPtab = true
|
||||
const a = attrsOf(c)['w:alignment']
|
||||
ptabAligns.push(a === 'center' ? 'center' : a === 'right' ? 'right' : 'left')
|
||||
} else walkTabs(c)
|
||||
}
|
||||
}
|
||||
walkTabs(pNode)
|
||||
out.push({
|
||||
...(d?.align && d.align !== 'justify' ? { align: d.align } : {}),
|
||||
...(d?.tabStops ? { tabStops: d.tabStops } : {}),
|
||||
...direct,
|
||||
...(sawPtab ? { ptabAligns } : {}),
|
||||
runs,
|
||||
})
|
||||
}
|
||||
// trailing all-empty paragraphs are layout noise
|
||||
while (out.length > 0 && out[out.length - 1].runs.length === 0 && !out[out.length - 1].cells) {
|
||||
@@ -3265,13 +3413,17 @@ function hfTableRowParagraphs(tbl: XNode, ctx: BuildContext): HfParagraph[] {
|
||||
const pPr = findChild(p, 'w:pPr')
|
||||
if (!align && pPr) align = extractParaFormat(pPr)?.align
|
||||
}
|
||||
const fill = attrsOf(findChild(findChild(tc, 'w:tcPr') ?? {}, 'w:shd') ?? {})['w:fill']
|
||||
return {
|
||||
runs,
|
||||
...(align ? { align } : {}),
|
||||
...(fill && fill !== 'auto' ? { fill } : {}),
|
||||
...(total > 0 && widths[i] > 0 ? { widthPct: (widths[i] / total) * 100 } : {}),
|
||||
}
|
||||
})
|
||||
if (cells.some((c) => c.runs.some((r) => r.text !== ''))) out.push({ runs: [], cells })
|
||||
// shaded-only rows still render (banner bars with no text)
|
||||
if (cells.some((c) => c.runs.some((r) => r.text !== '') || c.fill))
|
||||
out.push({ runs: [], cells })
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -4098,8 +4250,13 @@ async function extractDiagramDrawing(
|
||||
async function oleDisplay(
|
||||
xml: string,
|
||||
ctx: BuildContext,
|
||||
): Promise<Pick<Block, 'imageDataUrl' | 'oleProgId'>> {
|
||||
const out: Pick<Block, 'imageDataUrl' | 'oleProgId'> = {}
|
||||
): Promise<
|
||||
Pick<Block, 'imageDataUrl' | 'oleProgId' | 'imageWidthPx' | 'imageHeightPx' | 'imageAlign'>
|
||||
> {
|
||||
const out: Pick<
|
||||
Block,
|
||||
'imageDataUrl' | 'oleProgId' | 'imageWidthPx' | 'imageHeightPx' | 'imageAlign'
|
||||
> = {}
|
||||
const progId = /<o:OLEObject[^>]*ProgID="([^"]+)"/.exec(xml)?.[1]
|
||||
if (progId) out.oleProgId = progId
|
||||
const path = relPartPath(ctx, /<v:imagedata[^>]*r:id="([^"]+)"/.exec(xml)?.[1])
|
||||
@@ -4113,6 +4270,22 @@ async function oleDisplay(
|
||||
out.imageDataUrl = `data:${mime};base64,${await file.async('base64')}`
|
||||
}
|
||||
}
|
||||
// Word draws the preview at the declared size — v:shape style (pt), falling
|
||||
// back to w:object dxaOrig/dyaOrig (twips). Without it the metafile preview's
|
||||
// intrinsic pixels (2x dpiScale) blow up to the full content width.
|
||||
const style = /<v:shape [^>]*style="([^"]*)"/.exec(xml)?.[1] ?? ''
|
||||
const wPt = parseFloat(/(?:^|;)width:([\d.]+)pt/.exec(style)?.[1] ?? '')
|
||||
const hPt = parseFloat(/(?:^|;)height:([\d.]+)pt/.exec(style)?.[1] ?? '')
|
||||
const objAttrs = /<w:object\b[^>]*>/.exec(xml)?.[0] ?? ''
|
||||
const wTw = parseInt(/w:dxaOrig="(\d+)"/.exec(objAttrs)?.[1] ?? '', 10)
|
||||
const hTw = parseInt(/w:dyaOrig="(\d+)"/.exec(objAttrs)?.[1] ?? '', 10)
|
||||
const w = wPt > 0 ? (wPt / 72) * 96 : wTw > 0 ? wTw / 15 : 0
|
||||
const h = hPt > 0 ? (hPt / 72) * 96 : hTw > 0 ? hTw / 15 : 0
|
||||
if (w > 0) out.imageWidthPx = Math.round(w)
|
||||
if (h > 0) out.imageHeightPx = Math.round(h)
|
||||
const jc = /<w:jc w:val="([^"]+)"/.exec(xml)?.[1]
|
||||
if (jc === 'center') out.imageAlign = 'center'
|
||||
else if (jc === 'right' || jc === 'end') out.imageAlign = 'right'
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -4149,8 +4322,9 @@ async function extractChart(xml: string, ctx: BuildContext): Promise<ChartDispla
|
||||
|
||||
/** Word's substitution face when the East Asian font slot is empty, by w:lang w:eastAsia */
|
||||
const EA_LANG_DEFAULT_FONT: Record<string, string> = {
|
||||
ko: 'Batang',
|
||||
'ko-kr': 'Batang',
|
||||
// Word probe + fontTable: ko-KR empty EA slot substitutes Malgun Gothic, not Batang
|
||||
ko: 'Malgun Gothic',
|
||||
'ko-kr': 'Malgun Gothic',
|
||||
ja: 'MS Mincho',
|
||||
'ja-jp': 'MS Mincho',
|
||||
'zh-cn': 'SimSun',
|
||||
@@ -4188,7 +4362,7 @@ async function parseStyles(
|
||||
// docDefaults keeps the lang-based backfill below for the empty-slot case
|
||||
if (ddRf.eastAsia && !ddRf.eaSlotEmpty) dd.eastAsiaFont = ddRf.eastAsia
|
||||
// Empty EA slot + explicit w:lang w:eastAsia: Word substitutes the locale's
|
||||
// default face (e.g. ko-KR theme with <a:ea typeface=""/> renders Batang)
|
||||
// default face (e.g. ko-KR theme with <a:ea typeface=""/> renders Malgun Gothic)
|
||||
const eaLang = rPr ? attrsOf(findChild(rPr, 'w:lang') ?? {})['w:eastAsia'] : undefined
|
||||
if (!dd.eastAsiaFont && eaLang) {
|
||||
const eaDefault = EA_LANG_DEFAULT_FONT[eaLang.toLowerCase()]
|
||||
@@ -4333,6 +4507,7 @@ async function parseStyles(
|
||||
'font',
|
||||
'fontAscii',
|
||||
'csFont',
|
||||
'caps',
|
||||
] as const
|
||||
for (const [fromId, toId] of linkedIds) {
|
||||
const a = styles.get(fromId)
|
||||
@@ -4411,7 +4586,7 @@ function tableStyleDisplayOf(
|
||||
}
|
||||
}
|
||||
const styleTblPr = findChild(styleNode, 'w:tblPr')
|
||||
const borders = borderLinesOf(findChild(styleTblPr ?? {}, 'w:tblBorders'), true)
|
||||
const borders = mergedBorderLinesOf(styleTblPr, 'w:tblBorders', true)
|
||||
if (borders) display.borders = borders
|
||||
const cellMar = cellMarginsOf(findChild(styleTblPr ?? {}, 'w:tblCellMar'))
|
||||
if (cellMar) display.cellMarTwips = cellMar
|
||||
@@ -4465,6 +4640,8 @@ function styleDisplayOf(
|
||||
if (rf.eaSlotEmpty && font && font === rf.eastAsia) display.eaSlotEmpty = true
|
||||
const spc = parseInt(attrsOf(findChild(rPr, 'w:spacing') ?? {})['w:val'] ?? '', 10)
|
||||
if (spc) display.charSpacingTwips = spc
|
||||
if (onOffOf(rPr, 'w:caps')) display.caps = 'all'
|
||||
else if (onOffOf(rPr, 'w:smallCaps')) display.caps = 'small'
|
||||
}
|
||||
const pPr = findChild(styleNode, 'w:pPr')
|
||||
if (pPr) {
|
||||
@@ -4486,12 +4663,15 @@ function styleDisplayOf(
|
||||
}
|
||||
if (boolProp(pPr, 'w:keepNext')) display.keepNext = true
|
||||
if (boolProp(pPr, 'w:keepLines')) display.keepLines = true
|
||||
if (boolProp(pPr, 'w:pageBreakBefore')) display.pageBreakBefore = true
|
||||
if (boolProp(pPr, 'w:contextualSpacing')) display.contextualSpacing = true
|
||||
const autoSpace = autoSpaceOf(pPr)
|
||||
if (autoSpace !== undefined) display.autoSpace = autoSpace
|
||||
const jc = attrsOf(findChild(pPr, 'w:jc') ?? {})['w:val']
|
||||
if (jc === 'center' || jc === 'right' || jc === 'left' || jc === 'justify') display.align = jc
|
||||
else if (jc === 'both' || jc === 'distribute') display.align = 'justify'
|
||||
const stops = tabStopsOf(pPr)
|
||||
if (stops) display.tabStops = stops
|
||||
const ind = findChild(pPr, 'w:ind')
|
||||
if (ind) {
|
||||
const a = attrsOf(ind)
|
||||
|
||||
@@ -39,6 +39,8 @@ export interface Run {
|
||||
csFont?: string
|
||||
/** 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 */
|
||||
caps?: 'all' | 'small'
|
||||
/** Horizontal character scale percent (w:w). Display only (approximated as spacing); saving is kept faithful by rawRPr */
|
||||
charScalePct?: number
|
||||
/** OOXML named highlight color (w:highlight), e.g. "yellow" */
|
||||
@@ -189,6 +191,14 @@ export interface TabStop {
|
||||
leader?: 'none' | 'dot' | 'hyphen' | 'underscore' | 'heavy' | 'middleDot'
|
||||
}
|
||||
|
||||
/** Declared look of one w:pBdr side. */
|
||||
export interface ParaBorderLine {
|
||||
/** hex without '#' (w:color); undefined = auto */
|
||||
color?: string
|
||||
/** line width in pt (w:sz eighth-points / 8) */
|
||||
szPt?: number
|
||||
}
|
||||
|
||||
/** Paragraph-level formatting that survives regeneration (subset of w:pPr). */
|
||||
export interface ParaFormat {
|
||||
/** w:jc */
|
||||
@@ -233,6 +243,8 @@ export interface ParaFormat {
|
||||
shadingFill?: string
|
||||
/** paragraph borders, subset of "tblr" e.g. "b" or "tblr" (w:pBdr, single lines) */
|
||||
borders?: string
|
||||
/** 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") */
|
||||
@@ -314,6 +326,8 @@ export interface SectionInfo {
|
||||
|
||||
/** one rich paragraph of a header / footer part */
|
||||
export interface HfParagraph extends ParaFormat {
|
||||
/** w:ptab alignments indexed by overall tab order (regular w:tab slots are undefined); margin-relative, ignores tab stops */
|
||||
ptabAligns?: Array<'left' | 'center' | 'right' | undefined>
|
||||
runs: Run[]
|
||||
/** layout-table row: one entry per cell, rendered as columns. Display-only —
|
||||
* saving keeps the part's original w:tbl bytes and never serializes cells. */
|
||||
@@ -326,6 +340,8 @@ export interface HfTableCell {
|
||||
align?: ParaAlign
|
||||
/** column width as % of the row (w:tcW, falling back to tblGrid) */
|
||||
widthPct?: number
|
||||
/** cell shading fill (w:tcPr w:shd w:fill hex, non-auto) */
|
||||
fill?: string
|
||||
}
|
||||
|
||||
/** one w:lvl of a numbering definition */
|
||||
@@ -391,6 +407,8 @@ export interface HfImage {
|
||||
posV?: 'top' | 'center' | 'bottom'
|
||||
/** v:imagedata gain/blacklevel present (Word watermark washout preset) */
|
||||
washout?: boolean
|
||||
/** w:jc of the containing paragraph (inline images follow paragraph alignment) */
|
||||
align?: 'left' | 'center' | 'right'
|
||||
}
|
||||
|
||||
/** Parsed content of one header/footer part (any w:type variant). */
|
||||
@@ -413,6 +431,8 @@ export interface NoteRun {
|
||||
/** hex without '#' */
|
||||
color?: string
|
||||
sizeHalfPoints?: number
|
||||
/** w:caps ('all') / w:smallCaps ('small') display transform */
|
||||
caps?: 'all' | 'small'
|
||||
}
|
||||
|
||||
/** One footnote or endnote (display/edit model; separators are preserved separately). */
|
||||
@@ -605,6 +625,8 @@ export interface TableModel {
|
||||
colWidthsTwips?: number[]
|
||||
/** table width as a percentage of the body width (w:tblW type="pct"); absolute widths are ignored when set */
|
||||
widthPct?: number
|
||||
/** autofit layout (w:tblW auto/absent/zero, no fixed w:tblLayout): display may widen columns to min-content */
|
||||
autoLayout?: boolean
|
||||
/** table-level default cell margins (w:tblCellMar) */
|
||||
cellMarTwips?: CellMargins
|
||||
/** table-level borders (w:tblBorders); undefined = not declared (default gridlines apply) */
|
||||
@@ -959,6 +981,10 @@ export interface StyleDisplay {
|
||||
csFont?: string
|
||||
/** character spacing (rPr w:spacing, twips, may be negative) */
|
||||
charSpacingTwips?: number
|
||||
/** style-level pPr w:tabs (Word's built-in Header/Footer styles carry the center/right stops) */
|
||||
tabStops?: TabStop[]
|
||||
/** w:caps ('all') / w:smallCaps ('small') display transform */
|
||||
caps?: 'all' | 'small'
|
||||
/** multiple of single line spacing (w:spacing w:line, lineRule auto) */
|
||||
lineSpacing?: number
|
||||
/** F1: lineRule for accurate height calculation */
|
||||
@@ -975,6 +1001,8 @@ export interface StyleDisplay {
|
||||
keepNext?: boolean
|
||||
/** keepLines from style definition */
|
||||
keepLines?: boolean
|
||||
/** pageBreakBefore from style definition */
|
||||
pageBreakBefore?: boolean
|
||||
/** F1: contextualSpacing from style definition */
|
||||
contextualSpacing?: boolean
|
||||
/** paragraph alignment from the style (w:pPr w:jc) */
|
||||
|
||||
@@ -121,9 +121,9 @@ export function escapeXmlAttr(text: string): string {
|
||||
return escapeXmlText(text).replace(/"/g, '"')
|
||||
}
|
||||
|
||||
/** Text contains complex-script characters (Arabic/Hebrew/Syriac/Thaana/NKo), i.e. the w:*Cs run properties apply */
|
||||
/** Text contains complex-script characters (Arabic/Hebrew/Syriac/Thaana/NKo/Indic/Thai), i.e. the w:*Cs run properties apply */
|
||||
export function textHasComplexScript(text: string): boolean {
|
||||
return /[\u0590-\u05FF\u0600-\u077F\u0780-\u07FF\u08A0-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/.test(
|
||||
return /[\u0590-\u05FF\u0600-\u077F\u0780-\u07FF\u08A0-\u08FF\u0900-\u0DFF\u0E00-\u0E7F\uFB1D-\uFDFF\uFE70-\uFEFF]/.test(
|
||||
text,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
type SaveBlock,
|
||||
} from '../src/index'
|
||||
import { patchParagraphTexts } from '../src/text-patch'
|
||||
import { escapeXmlText } from '../src/xml-utils'
|
||||
import { escapeXmlText, textHasComplexScript } from '../src/xml-utils'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const P = (text: string) => `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`
|
||||
@@ -90,6 +90,17 @@ describe('escapeXmlText', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('textHasComplexScript', () => {
|
||||
it('classifies Arabic, Tamil, Devanagari and Thai as cs; Latin/CJK as not', () => {
|
||||
expect(textHasComplexScript('مرحبا')).toBe(true)
|
||||
expect(textHasComplexScript('தமிழ்')).toBe(true)
|
||||
expect(textHasComplexScript('हिन्दी')).toBe(true)
|
||||
expect(textHasComplexScript('ไทย')).toBe(true)
|
||||
expect(textHasComplexScript('hello')).toBe(false)
|
||||
expect(textHasComplexScript('中文한글かな')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('nextNoteId', () => {
|
||||
it('starts at 1 for a document with no existing notes', () => {
|
||||
expect(nextNoteId([])).toBe('1')
|
||||
|
||||
@@ -171,7 +171,7 @@ describe('linkedStyle (w:link) and docDefaults backfill', () => {
|
||||
// theme EA typeface empty → w:eastAsiaTheme resolves to nothing → lang decides
|
||||
const rFonts = '<w:rFonts w:asciiTheme="minorHAnsi" w:eastAsiaTheme="minorEastAsia"/>'
|
||||
const ko = await withDefaults(`${rFonts}<w:lang w:val="en-US" w:eastAsia="ko-KR"/>`)
|
||||
expect(ko.docDefaults?.eastAsiaFont).toBe('Batang')
|
||||
expect(ko.docDefaults?.eastAsiaFont).toBe('Malgun Gothic')
|
||||
const ja = await withDefaults(`${rFonts}<w:lang w:eastAsia="ja-JP"/>`)
|
||||
expect(ja.docDefaults?.eastAsiaFont).toBe('MS Mincho')
|
||||
const zh = await withDefaults(`${rFonts}<w:lang w:eastAsia="zh-CN"/>`)
|
||||
|
||||
@@ -91,6 +91,137 @@ describe('rich header / footer', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('paragraphs inside nested w:sdt keep their alignment (POI Bug60341: OpenXML SDK footer)', async () => {
|
||||
const FOOTER =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
|
||||
'<w:ftr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:sdt><w:sdtContent><w:sdt><w:sdtContent>' +
|
||||
'<w:p><w:pPr><w:pStyle w:val="Footer"/><w:jc w:val="right"/></w:pPr>' +
|
||||
'<w:r><w:t xml:space="preserve">Page </w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText>PAGE</w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
|
||||
'<w:r><w:t>2</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
|
||||
'</w:p>' +
|
||||
'</w:sdtContent></w:sdt></w:sdtContent></w:sdt></w:ftr>'
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>body</w:t></w:r></w:p>',
|
||||
extraRels:
|
||||
'<Relationship Id="rId62" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/footer1.xml',
|
||||
xml: FOOTER,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml',
|
||||
},
|
||||
],
|
||||
sectPrExtra: '<w:footerReference w:type="default" r:id="rId62"/>',
|
||||
})
|
||||
const parsed = await parseDocx(bytes)
|
||||
expect(parsed.footerParas).toHaveLength(1)
|
||||
expect(parsed.footerParas![0].align).toBe('right')
|
||||
expect(parsed.footerParas![0].runs.map((r) => r.text).join('')).toBe(`Page ${PAGE_MARK}`)
|
||||
})
|
||||
|
||||
it('Header style w:tabs and w:jc reach the paragraphs; direct pPr wins (POI ThreeColHead)', async () => {
|
||||
const HEADER =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
|
||||
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:p><w:pPr><w:pStyle w:val="Header"/></w:pPr>' +
|
||||
'<w:r><w:t xml:space="preserve">Left\tMid\tRight</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:pStyle w:val="Header"/><w:jc w:val="right"/></w:pPr>' +
|
||||
'<w:r><w:t>direct wins</w:t></w:r></w:p>' +
|
||||
'</w:hdr>'
|
||||
const STYLES =
|
||||
'<w:style w:type="paragraph" w:styleId="Header"><w:name w:val="header"/>' +
|
||||
'<w:pPr><w:tabs><w:tab w:val="center" w:pos="4513"/><w:tab w:val="right" w:pos="9026"/></w:tabs>' +
|
||||
'<w:jc w:val="left"/></w:pPr></w:style>'
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>body</w:t></w:r></w:p>',
|
||||
extraStylesXml: STYLES,
|
||||
extraRels:
|
||||
'<Relationship Id="rId61" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/header1.xml',
|
||||
xml: HEADER,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
|
||||
},
|
||||
],
|
||||
sectPrExtra: '<w:headerReference w:type="default" r:id="rId61"/>',
|
||||
})
|
||||
const parsed = await parseDocx(bytes)
|
||||
expect(parsed.headerParas![0].tabStops).toEqual([
|
||||
{ pos: 4513, val: 'center' },
|
||||
{ pos: 9026, val: 'right' },
|
||||
])
|
||||
expect(parsed.headerParas![0].align).toBe('left')
|
||||
expect(parsed.headerParas![1].align).toBe('right')
|
||||
expect(parsed.headerParas![1].tabStops).toEqual([
|
||||
{ pos: 4513, val: 'center' },
|
||||
{ pos: 9026, val: 'right' },
|
||||
])
|
||||
})
|
||||
|
||||
it('w:ptab absolute tabs surface as \\t runs with their alignments (POI ThreeColHead)', async () => {
|
||||
const HEADER =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
|
||||
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:p><w:pPr><w:pStyle w:val="Header"/></w:pPr>' +
|
||||
'<w:r><w:t>First header column!</w:t></w:r>' +
|
||||
'<w:r><w:ptab w:relativeTo="margin" w:alignment="center" w:leader="none"/></w:r>' +
|
||||
'<w:r><w:t>Mid header</w:t></w:r>' +
|
||||
'<w:r><w:ptab w:relativeTo="margin" w:alignment="right" w:leader="none"/></w:r>' +
|
||||
'<w:r><w:t>Right header!</w:t></w:r>' +
|
||||
'</w:p></w:hdr>'
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>body</w:t></w:r></w:p>',
|
||||
extraRels:
|
||||
'<Relationship Id="rId61" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/header1.xml',
|
||||
xml: HEADER,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
|
||||
},
|
||||
],
|
||||
sectPrExtra: '<w:headerReference w:type="default" r:id="rId61"/>',
|
||||
})
|
||||
const parsed = await parseDocx(bytes)
|
||||
const para = parsed.headerParas![0]
|
||||
expect(para.runs.map((r) => r.text).join('')).toBe(
|
||||
'First header column!\tMid header\tRight header!',
|
||||
)
|
||||
expect(para.ptabAligns).toEqual(['center', 'right'])
|
||||
})
|
||||
|
||||
it('mixed w:tab / w:ptab keeps ptab alignments on the right tab index', async () => {
|
||||
const HEADER =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
|
||||
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:p><w:r><w:t>a</w:t></w:r>' +
|
||||
'<w:r><w:tab/><w:t>b</w:t></w:r>' +
|
||||
'<w:r><w:ptab w:relativeTo="margin" w:alignment="right" w:leader="none"/></w:r>' +
|
||||
'<w:r><w:t>c</w:t></w:r>' +
|
||||
'</w:p></w:hdr>'
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>body</w:t></w:r></w:p>',
|
||||
extraRels:
|
||||
'<Relationship Id="rId61" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/header1.xml',
|
||||
xml: HEADER,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
|
||||
},
|
||||
],
|
||||
sectPrExtra: '<w:headerReference w:type="default" r:id="rId61"/>',
|
||||
})
|
||||
const parsed = await parseDocx(bytes)
|
||||
expect(parsed.headerParas![0].ptabAligns).toEqual([undefined, 'right'])
|
||||
})
|
||||
|
||||
it('literal # before a PAGE field stays literal; the field parses to PAGE_MARK', async () => {
|
||||
// regression: the footer "[Course #] | Page <PAGE field>" used to render the
|
||||
// page number inside "[Course #]" because '#' doubled as the field marker
|
||||
@@ -169,7 +300,7 @@ describe('surgical header rewrite (real Word headers carry tables/logos)', () =>
|
||||
const HEADER_TBL =
|
||||
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="4000"/><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr>' +
|
||||
'<w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/><w:shd w:val="clear" w:fill="1F3864"/></w:tcPr>' +
|
||||
'<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>ACME 公司</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr>' +
|
||||
'<w:p><w:r><w:t>Logo 占位</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||
@@ -248,6 +379,8 @@ describe('surgical header rewrite (real Word headers carry tables/logos)', () =>
|
||||
expect(row.cells![0].runs[0]).toMatchObject({ text: 'ACME 公司', bold: true })
|
||||
expect(row.cells![1].runs[0]).toMatchObject({ text: 'Logo 占位' })
|
||||
expect(row.cells!.map((c) => Math.round(c.widthPct!))).toEqual([50, 50])
|
||||
expect(row.cells![0].fill).toBe('1F3864')
|
||||
expect(row.cells![1].fill).toBeUndefined()
|
||||
expect(paras[1].runs[0].text).toBe('公司内部资料')
|
||||
// legacy plain text separates cell texts instead of gluing them
|
||||
expect(parsed.headerText).toBe('ACME 公司 Logo 占位 公司内部资料')
|
||||
@@ -337,6 +470,7 @@ describe('header paragraph borders', () => {
|
||||
it('does not read a nil side as a border', async () => {
|
||||
const parsed = await withNilBorderHeader()
|
||||
expect(parsed.headerParas?.[0]?.borders).toBe('b')
|
||||
expect(parsed.headerParas?.[0]?.borderLines).toEqual({ b: { color: '4472C4', szPt: 2.25 } })
|
||||
})
|
||||
|
||||
it('does not stamp rules the header never had when it is saved back', async () => {
|
||||
|
||||
@@ -23,7 +23,7 @@ const HEADER_RELS =
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.png"/>' +
|
||||
'</Relationships>'
|
||||
|
||||
async function buildHeaderLogoDocx(): Promise<Uint8Array> {
|
||||
async function buildHeaderLogoDocx(headerXml: string = HEADER_XML): Promise<Uint8Array> {
|
||||
return buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>Body</w:t></w:r></w:p>',
|
||||
withImage: true,
|
||||
@@ -33,7 +33,7 @@ async function buildHeaderLogoDocx(): Promise<Uint8Array> {
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/header1.xml',
|
||||
xml: HEADER_XML,
|
||||
xml: headerXml,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
|
||||
},
|
||||
{
|
||||
@@ -69,4 +69,27 @@ describe('header/footer images (display-only Logo)', () => {
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
|
||||
expect(await saveDocx(doc, blocks)).toEqual(bytes)
|
||||
})
|
||||
|
||||
it('inline image follows its paragraph alignment (POI headerPic: w:jc right)', async () => {
|
||||
const headerXml = HEADER_XML.replace(
|
||||
'<w:p><w:r><w:drawing>',
|
||||
'<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:drawing>',
|
||||
)
|
||||
const doc = await parseDocx(await buildHeaderLogoDocx(headerXml))
|
||||
expect(doc.headerImages![0].align).toBe('right')
|
||||
})
|
||||
|
||||
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(
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic>',
|
||||
'<mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">' +
|
||||
'<mc:Choice Requires="ma"><pic:pic><pic:blipFill><a:blip r:embed="rId9"/></pic:blipFill></pic:pic></mc:Choice>' +
|
||||
'<mc:Fallback><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic></mc:Fallback>' +
|
||||
'</mc:AlternateContent>',
|
||||
)
|
||||
const doc = await parseDocx(await buildHeaderLogoDocx(headerXml))
|
||||
expect(doc.headerImages).toHaveLength(1)
|
||||
expect(doc.headerImages![0].dataUrl.startsWith('data:image/png;base64,')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -148,6 +148,27 @@ describe('parseDocx', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('style-level pageBreakBefore', () => {
|
||||
it('parses pageBreakBefore into style display, inherited via basedOn, without touching paragraph format', async () => {
|
||||
const bytes = await buildDocx({
|
||||
extraStylesXml:
|
||||
'<w:style w:type="paragraph" w:styleId="ChapterTitle"><w:name w:val="Chapter Title"/>' +
|
||||
'<w:pPr><w:pageBreakBefore/></w:pPr></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="ChapterSub"><w:name w:val="Chapter Sub"/>' +
|
||||
'<w:basedOn w:val="ChapterTitle"/></w:style>',
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:pStyle w:val="ChapterTitle"/></w:pPr><w:r><w:t>ch</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:t>body</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.styles.get('ChapterTitle')?.display?.pageBreakBefore).toBe(true)
|
||||
expect(doc.styles.get('ChapterSub')?.display?.pageBreakBefore).toBe(true)
|
||||
expect(doc.styles.get('Normal')?.display?.pageBreakBefore).toBeUndefined()
|
||||
// style-level value must not leak into paragraph format (would be saved as redundant pPr)
|
||||
expect(doc.blocks[0].format?.pageBreakBefore).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('empty paragraph line size', () => {
|
||||
it('records the w:sz that governs a run-less paragraph', async () => {
|
||||
const bodyXml =
|
||||
|
||||
@@ -17,6 +17,7 @@ const RAW =
|
||||
// what extractParaFormat yields for RAW
|
||||
const MODEL: ParaFormat = {
|
||||
borders: 'tb',
|
||||
borderLines: { t: { color: 'FF0000', szPt: 1.5 }, b: { color: 'FF0000', szPt: 1.5 } },
|
||||
shadingFill: 'EEEEEE',
|
||||
spaceBefore: 240,
|
||||
spaceAfter: 120,
|
||||
@@ -65,6 +66,24 @@ describe('mergePPrFormat keeps unedited groups byte-identical', () => {
|
||||
expect(mergePPrFormat(raw, doc.blocks[0].format)).toBe(raw)
|
||||
})
|
||||
|
||||
it('changing only a border color rebuilds pBdr with the declared color/sz', () => {
|
||||
const out = mergePPrFormat(RAW, {
|
||||
...MODEL,
|
||||
borderLines: { t: { color: '00FF00', szPt: 1.5 }, b: { color: 'FF0000', szPt: 1.5 } },
|
||||
})
|
||||
expect(out).toContain('<w:top w:val="single" w:sz="12" w:space="1" w:color="00FF00"/>')
|
||||
expect(out).toContain('<w:bottom w:val="single" w:sz="12" w:space="1" w:color="FF0000"/>')
|
||||
expect(out).not.toContain('dashed')
|
||||
})
|
||||
|
||||
it('rebuilding pBdr from a bare model writes declared color/sz', () => {
|
||||
const out = mergePPrFormat('<w:pPr></w:pPr>', {
|
||||
borders: 'b',
|
||||
borderLines: { b: { color: '4472C4', szPt: 2.25 } },
|
||||
})
|
||||
expect(out).toContain('<w:bottom w:val="single" w:sz="18" w:space="1" w:color="4472C4"/>')
|
||||
})
|
||||
|
||||
it('changing indent rebuilds w:ind and drops the char-unit variants', () => {
|
||||
// Word prefers *Chars over the twips attrs, so a stale firstLineChars would
|
||||
// override the user's new indent — the rebuilt w:ind must not carry them
|
||||
|
||||
@@ -193,6 +193,26 @@ describe('eastAsia theme slot', () => {
|
||||
expect(doc.blocks[0].runs![1].font).toBe('Yu Mincho')
|
||||
})
|
||||
|
||||
it('themeFontLang ko resolves empty slots to Malgun Gothic', async () => {
|
||||
const settingsPart = {
|
||||
path: 'word/settings.xml',
|
||||
xml:
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
||||
'<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:themeFontLang w:val="en-US" w:eastAsia="ko-KR"/></w:settings>',
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml',
|
||||
}
|
||||
const para =
|
||||
`<w:p><w:r><w:rPr>${HEADING_RFONTS}</w:rPr><w:t>제목</w:t></w:r>` +
|
||||
'<w:r><w:rPr><w:rFonts w:eastAsiaTheme="minorEastAsia"/></w:rPr><w:t>본문</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({ bodyXml: para, extraParts: [themePart(''), settingsPart] }),
|
||||
)
|
||||
expect(doc.themeFonts?.eaLang).toBe('ko-KR')
|
||||
expect(doc.blocks[0].runs![0].font).toBe('Malgun Gothic')
|
||||
expect(doc.blocks[0].runs![1].font).toBe('Malgun Gothic')
|
||||
})
|
||||
|
||||
it('an empty theme slot on a style rPr also resolves to DengXian', async () => {
|
||||
const styles =
|
||||
'<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/>' +
|
||||
|
||||
@@ -255,3 +255,51 @@ describe('multi-paragraph SDT (TOC)', () => {
|
||||
expect(Buffer.from(saved).equals(Buffer.from(bytes))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('nested SDT (Word cover-page building blocks)', () => {
|
||||
// outer docPartObj sdt wrapping several inner field sdts + plain paragraphs
|
||||
const NESTED_SDT =
|
||||
'<w:sdt><w:sdtPr><w:docPartObj><w:docPartGallery w:val="Cover Pages"/></w:docPartObj></w:sdtPr><w:sdtContent>' +
|
||||
'<w:sdt><w:sdtPr><w:alias w:val="Title"/><w:text/></w:sdtPr><w:sdtContent>' +
|
||||
'<w:p><w:r><w:t>Resume Title</w:t></w:r></w:p>' +
|
||||
'</w:sdtContent></w:sdt>' +
|
||||
'<w:p><w:r><w:t>plain between</w:t></w:r></w:p>' +
|
||||
'<w:sdt><w:sdtPr><w:alias w:val="Company"/><w:text/></w:sdtPr><w:sdtContent>' +
|
||||
'<w:p><w:r><w:t>ACME Corp</w:t></w:r></w:p>' +
|
||||
'</w:sdtContent></w:sdt>' +
|
||||
'</w:sdtContent></w:sdt>'
|
||||
|
||||
it('descends nested content controls: every inner paragraph becomes a block', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: NESTED_SDT }))
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
// regression: only "Resume Title" survived; "plain between" and "ACME Corp" were dropped
|
||||
expect(visible.map((b) => b.runs?.map((r) => r.text).join('') ?? b.previewText)).toEqual([
|
||||
'Resume Title',
|
||||
'plain between',
|
||||
'ACME Corp',
|
||||
])
|
||||
})
|
||||
|
||||
it('untouched nested sdt saves byte-identical', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: NESTED_SDT })
|
||||
const doc = await parseDocx(bytes)
|
||||
const saved = await saveDocx(
|
||||
doc,
|
||||
doc.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! })),
|
||||
)
|
||||
expect(Buffer.from(saved).equals(Buffer.from(bytes))).toBe(true)
|
||||
})
|
||||
|
||||
it('sdtContent without any paragraph keeps its text as previewText', async () => {
|
||||
const RUN_ONLY_SDT =
|
||||
'<w:sdt><w:sdtPr><w:alias w:val="Odd"/></w:sdtPr><w:sdtContent>' +
|
||||
'<w:r><w:t>bare run text</w:t></w:r>' +
|
||||
'</w:sdtContent></w:sdt>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: RUN_ONLY_SDT }))
|
||||
const visible = doc.blocks.filter((b) => !b.hidden)
|
||||
expect(visible[0].type).toBe('passthrough')
|
||||
expect(visible[0].previewText).toContain('bare run text')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -60,6 +60,41 @@ describe('SmartArt / OLE visible degrade', () => {
|
||||
expect(block.label).toBe('Embedded object')
|
||||
expect(block.oleProgId).toBe('Excel.Sheet.12')
|
||||
expect(block.imageDataUrl).toMatch(/^data:image\/png;base64,/)
|
||||
// declared v:shape size (32pt = 43px), not the preview's intrinsic pixels
|
||||
expect(block.imageWidthPx).toBe(43)
|
||||
expect(block.imageHeightPx).toBe(43)
|
||||
})
|
||||
|
||||
it('OLE follows the paragraph w:jc like other inline objects', async () => {
|
||||
const oleP = OLE_P.replace('<w:r>', '<w:pPr><w:jc w:val="center"/></w:pPr><w:r>')
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: oleP, withImage: true }))
|
||||
expect(parsed.blocks[0].imageAlign).toBe('center')
|
||||
})
|
||||
|
||||
it('OLE size falls back to w:object dxaOrig/dyaOrig (twips)', async () => {
|
||||
const oleP = OLE_P.replace('<w:object>', '<w:object w:dxaOrig="1365" w:dyaOrig="765">').replace(
|
||||
' style="width:32pt;height:32pt"',
|
||||
'',
|
||||
)
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: oleP, withImage: true }))
|
||||
const block = parsed.blocks[0]
|
||||
expect(block.imageWidthPx).toBe(91)
|
||||
expect(block.imageHeightPx).toBe(51)
|
||||
})
|
||||
|
||||
it('VML horizontal rule (v:rect o:hr) is a decorative line, not a chip', async () => {
|
||||
const hrP =
|
||||
'<w:p><w:r><w:pict><v:rect xmlns:v="urn:schemas-microsoft-com:vml" ' +
|
||||
'xmlns:o="urn:schemas-microsoft-com:office:office" id="_x0000_i1026" ' +
|
||||
'style="width:0;height:1.5pt" o:hralign="center" o:hrstd="t" o:hr="t" ' +
|
||||
'fillcolor="#aca899" stroked="f"/></w:pict></w:r></w:p>'
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: hrP }))
|
||||
const block = parsed.blocks[0]
|
||||
expect(block.type).toBe('passthrough')
|
||||
expect(block.decorative).toBe(true)
|
||||
expect(block.ruleColorHex).toBe('ACA899')
|
||||
expect(block.ruleThicknessPx).toBe(2)
|
||||
expect(block.ruleWidthPx).toBeUndefined()
|
||||
})
|
||||
|
||||
it('a missing diagram part degrades to the bare label, not an error', async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/index'
|
||||
import { parseDocx, saveDocx, type SaveBlock } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const STYLED_TABLE_XML =
|
||||
@@ -180,3 +180,93 @@ describe('cell alignment aggregation and trailing empty paragraphs', () => {
|
||||
expect(cell.richParas?.[1].runs).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('fixed-layout grid vs tcW arbitration', () => {
|
||||
const fixedTable = (tblLayout: string) =>
|
||||
`<w:tbl><w:tblPr><w:tblW w:type="auto" w:w="0"/>${tblLayout}<w:tblInd w:w="1450" w:type="dxa"/></w:tblPr>` +
|
||||
'<w:tblGrid><w:gridCol w:w="6120"/><w:gridCol w:w="6120"/></w:tblGrid>' +
|
||||
'<w:tr>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:type="dxa" w:w="4680"/></w:tcPr><w:p><w:r><w:t>a</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:type="dxa" w:w="4680"/></w:tcPr><w:p><w:r><w:t>b</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr></w:tbl>'
|
||||
|
||||
it('fixed layout takes tcW even when the grid has the same ratio (stale wider grid)', async () => {
|
||||
// regression sample 30: grid 12240 total pushed the table + 1450 indent off paper,
|
||||
// Word lays the same table out from the 9360-total first-row tcW
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({ bodyXml: fixedTable('<w:tblLayout w:type="fixed"/>') }),
|
||||
)
|
||||
expect(doc.blocks[0].table!.colWidthsTwips).toEqual([4680, 4680])
|
||||
})
|
||||
|
||||
it('auto layout keeps the grid when only the absolute sums differ', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: fixedTable('') }))
|
||||
expect(doc.blocks[0].table!.colWidthsTwips).toEqual([6120, 6120])
|
||||
})
|
||||
|
||||
it('garbage over-wide grid widths stay raw in the model (clamping is render-side only)', async () => {
|
||||
const xml =
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="1871"/><w:gridCol w:w="130618601"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>x</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:p><w:r><w:t>y</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
expect(doc.blocks[0].table!.colWidthsTwips).toEqual([1871, 130618601])
|
||||
})
|
||||
|
||||
it('tcW column widths take the max across rows, not the first row (Word widens to fit)', async () => {
|
||||
const xml =
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="5000"/><w:gridCol w:w="5000"/></w:tblGrid>' +
|
||||
'<w:tr>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:type="dxa" w:w="2000"/></w:tcPr><w:p><w:r><w:t>a</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:type="dxa" w:w="6000"/></w:tcPr><w:p><w:r><w:t>b</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr><w:tr>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:type="dxa" w:w="4000"/></w:tcPr><w:p><w:r><w:t>c</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:tcPr><w:tcW w:type="dxa" w:w="6000"/></w:tcPr><w:p><w:r><w:t>d</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr></w:tbl>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
expect(doc.blocks[0].table!.colWidthsTwips).toEqual([4000, 6000])
|
||||
})
|
||||
|
||||
it('tcW preference never touches saved bytes: roundtrip keeps the original tblGrid', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: fixedTable('<w:tblLayout w:type="fixed"/>') })
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].table!.colWidthsTwips).toEqual([4680, 4680])
|
||||
const saved = await saveDocx(
|
||||
doc,
|
||||
doc.blocks
|
||||
.filter((b) => !b.hidden)
|
||||
.map((b): SaveBlock => ({ kind: 'original', docxIndex: b.docxIndex! })),
|
||||
)
|
||||
expect(saved).toBe(bytes)
|
||||
expect(doc.blocks[0].originalXml).toContain(
|
||||
'<w:tblGrid><w:gridCol w:w="6120"/><w:gridCol w:w="6120"/></w:tblGrid>',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('duplicated border containers merge per side, later wins', () => {
|
||||
it('a second w:tcBorders overrides the sides of an all-nil first one', async () => {
|
||||
const xml =
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="3000"/></w:tblGrid><w:tr><w:tc><w:tcPr>' +
|
||||
'<w:tcBorders><w:top w:val="nil"/><w:left w:val="nil"/><w:bottom w:val="nil"/><w:right w:val="nil"/></w:tcBorders>' +
|
||||
'<w:tcBorders><w:bottom w:val="single" w:sz="4" w:color="000000"/></w:tcBorders>' +
|
||||
'</w:tcPr><w:p><w:r><w:t>签名</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const cell = doc.blocks[0].table!.rows[0][0]
|
||||
expect(cell.borders?.bottom).toEqual({ style: 'single', szEighths: 4, color: '000000' })
|
||||
expect(cell.borders?.top).toEqual({ style: 'nil' })
|
||||
})
|
||||
|
||||
it('a second w:tblBorders overrides the sides of the first one', async () => {
|
||||
const xml =
|
||||
'<w:tbl><w:tblPr>' +
|
||||
'<w:tblBorders><w:top w:val="nil"/><w:bottom w:val="nil"/></w:tblBorders>' +
|
||||
'<w:tblBorders><w:bottom w:val="single" w:sz="8"/></w:tblBorders>' +
|
||||
'</w:tblPr><w:tblGrid><w:gridCol w:w="3000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>x</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const borders = doc.blocks[0].table!.borders
|
||||
expect(borders?.bottom).toEqual({ style: 'single', szEighths: 8 })
|
||||
expect(borders?.top).toEqual({ style: 'nil' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -41,6 +41,31 @@ describe('paragraph shading and borders', () => {
|
||||
expect(doc.blocks[0].format?.shadingFill).toBe('FFF2CC')
|
||||
expect(doc.blocks[0].format?.borders).toBe('tb')
|
||||
})
|
||||
|
||||
it('keeps declared pBdr color and width (w:sz eighth-points -> pt)', async () => {
|
||||
const xml =
|
||||
'<w:p><w:pPr><w:pBdr>' +
|
||||
'<w:top w:val="single" w:sz="4" w:space="1" w:color="auto"/>' +
|
||||
'<w:bottom w:val="single" w:sz="12" w:space="1" w:color="0B5394"/>' +
|
||||
'</w:pBdr></w:pPr><w:r><w:t>x</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
expect(doc.blocks[0].format?.borders).toBe('tb')
|
||||
expect(doc.blocks[0].format?.borderLines).toEqual({
|
||||
t: { szPt: 0.5 },
|
||||
b: { color: '0B5394', szPt: 1.5 },
|
||||
})
|
||||
})
|
||||
|
||||
it('a later duplicated w:pBdr overrides a side declared look', async () => {
|
||||
const xml =
|
||||
'<w:p><w:pPr>' +
|
||||
'<w:pBdr><w:bottom w:val="single" w:sz="4" w:color="FF0000"/></w:pBdr>' +
|
||||
'<w:pBdr><w:bottom w:val="single" w:sz="24" w:color="0B5394"/></w:pBdr>' +
|
||||
'</w:pPr><w:r><w:t>x</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
expect(doc.blocks[0].format?.borders).toBe('b')
|
||||
expect(doc.blocks[0].format?.borderLines).toEqual({ b: { color: '0B5394', szPt: 3 } })
|
||||
})
|
||||
})
|
||||
|
||||
describe('page border and columns (sectPr)', () => {
|
||||
|
||||
Reference in New Issue
Block a user