Sync snapshot (2026-08-26) (#159)
- Sheets: CSV export and save support, Excel-matching data validation - Docs: image, shape, WordArt, and chart rendering fixes - Slides: downloadable font catalog with a missing-font banner - Slides: better AI text layout and a speaker-notes tool Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
9711a4507c
commit
0a2c25d483
@@ -1,5 +1,5 @@
|
||||
import JSZip from 'jszip'
|
||||
import type { ChartDisplay, ChartSeries, NewChart } from './types'
|
||||
import type { ChartDisplay, ChartSeries, NewChart, ThemeColors } from './types'
|
||||
import {
|
||||
attrsOf,
|
||||
childrenOf,
|
||||
@@ -22,64 +22,318 @@ const CHART_KINDS: Record<string, ChartDisplay['kind']> = {
|
||||
'c:doughnutChart': 'pie',
|
||||
'c:areaChart': 'area',
|
||||
'c:area3DChart': 'area',
|
||||
'c:scatterChart': 'scatter',
|
||||
'c:bubbleChart': 'bubble',
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the display model of a chart part (word/charts/chartN.xml). Only the
|
||||
* caches Word writes next to the data references (c:strCache / c:numCache)
|
||||
* are read — the embedded workbook is never opened. Returns null when the
|
||||
* part has no series with cached values (e.g. scatter charts).
|
||||
* part has no series with cached values.
|
||||
*/
|
||||
export function parseChartPartXml(xml: string, partPath: string): ChartDisplay | null {
|
||||
export function parseChartPartXml(
|
||||
xml: string,
|
||||
partPath: string,
|
||||
theme?: ThemeColors | null,
|
||||
): ChartDisplay | null {
|
||||
const parsed = xmlParser.parse(xml) as XNode[]
|
||||
if (xml.includes('<cx:chartSpace')) return parseChartexPartXml(parsed, partPath)
|
||||
const space = parsed.find((n) => nameOf(n) === 'c:chartSpace')
|
||||
const chart = space ? findChild(space, 'c:chart') : undefined
|
||||
const plotArea = chart ? findChild(chart, 'c:plotArea') : undefined
|
||||
if (!chart || !plotArea) return null
|
||||
if (!space || !chart || !plotArea) return null
|
||||
|
||||
// first plotted chart type wins (combo charts render their primary series)
|
||||
const plot = childrenOf(plotArea).find((c) => (nameOf(c) ?? '').endsWith('Chart'))
|
||||
if (!plot) return null
|
||||
const kind = CHART_KINDS[nameOf(plot) ?? ''] ?? 'other'
|
||||
const horizontal = kind === 'bar' && attrsOf(findChild(plot, 'c:barDir') ?? {})['val'] === 'bar'
|
||||
const groupingVal = attrsOf(findChild(plot, 'c:grouping') ?? {})['val']
|
||||
const grouping =
|
||||
(kind === 'bar' || kind === 'area') &&
|
||||
(groupingVal === 'stacked' || groupingVal === 'percentStacked')
|
||||
? groupingVal
|
||||
: undefined
|
||||
const scatterStyle = attrsOf(findChild(plot, 'c:scatterStyle') ?? {})['val']
|
||||
const markers =
|
||||
kind === 'line'
|
||||
? attrsOf(findChild(plot, 'c:marker') ?? {})['val'] === '1'
|
||||
: kind === 'scatter'
|
||||
? scatterStyle === undefined || scatterStyle.toLowerCase().includes('marker')
|
||||
: false
|
||||
const scatterLines = kind === 'scatter' && /line|smooth/i.test(scatterStyle ?? '')
|
||||
|
||||
let categories: string[] = []
|
||||
const series: ChartSeries[] = []
|
||||
for (const ser of findChildren(plot, 'c:ser')) {
|
||||
const val = findChild(ser, 'c:val')
|
||||
const rawValues = val ? cachePoints(val) : []
|
||||
const values = rawValues.map((v) => {
|
||||
if (v === null || v.trim() === '') return null
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) ? n : null
|
||||
})
|
||||
// scatter/bubble series carry x/y pairs instead of category/value caches
|
||||
const val = findChild(ser, 'c:val') ?? findChild(ser, 'c:yVal')
|
||||
const values = val ? cacheNumbers(val) : []
|
||||
if (values.length === 0) continue
|
||||
const cat = findChild(ser, 'c:cat')
|
||||
const cat = findChild(ser, 'c:cat') ?? findChild(ser, 'c:xVal')
|
||||
if (cat && categories.length === 0) {
|
||||
categories = cachePoints(cat).map((v) => v ?? '')
|
||||
// date-formatted numeric caches hold Excel serials; display them as dates
|
||||
const fmt = catFormatCode(cat)
|
||||
if (fmt && /[yd]/i.test(fmt)) {
|
||||
categories = categories.map((v) => serialDateText(v) ?? v)
|
||||
} else if (nameOf(cat) === 'c:xVal') {
|
||||
// x caches carry raw doubles (0.70000000000000062); trim for display
|
||||
categories = categories.map((v) => {
|
||||
const n = Number(v)
|
||||
return v !== '' && Number.isFinite(n) ? String(Math.round(n * 10000) / 10000) : v
|
||||
})
|
||||
}
|
||||
}
|
||||
const name = seriesName(ser)
|
||||
series.push({ ...(name !== undefined ? { name } : {}), values })
|
||||
const entry: ChartSeries = { ...(name !== undefined ? { name } : {}), values }
|
||||
const color = solidFillHex(findChild(ser, 'c:spPr'), theme)
|
||||
if (color) entry.color = color
|
||||
const pointColors = dataPointColors(ser, theme)
|
||||
if (pointColors) entry.pointColors = pointColors
|
||||
if (kind === 'scatter' || kind === 'bubble') {
|
||||
const xVal = findChild(ser, 'c:xVal')
|
||||
const xValues = xVal ? cacheNumbers(xVal) : []
|
||||
if (xValues.some((v) => v !== null)) entry.xValues = xValues
|
||||
const sizeVal = findChild(ser, 'c:bubbleSize')
|
||||
const sizes = sizeVal ? cacheNumbers(sizeVal) : []
|
||||
if (sizes.some((v) => v !== null)) entry.sizes = sizes
|
||||
if (scatterLines && !seriesLineHidden(ser)) entry.line = true
|
||||
}
|
||||
series.push(entry)
|
||||
}
|
||||
if (series.length === 0) return null
|
||||
|
||||
const title = chartTitle(chart)
|
||||
const palette = chartPalette(chartStyleVal(space), theme)
|
||||
let title = chartTitle(chart)
|
||||
// Office names a single-series chart's auto title after the series
|
||||
if (title === 'Chart Title' && series.length === 1 && series[0].name) title = series[0].name
|
||||
return {
|
||||
partPath,
|
||||
kind,
|
||||
...(horizontal ? { horizontal } : {}),
|
||||
...(grouping ? { grouping } : {}),
|
||||
...(markers ? { markers } : {}),
|
||||
...(title !== undefined ? { title } : {}),
|
||||
categories,
|
||||
series,
|
||||
...(palette ? { palette } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** numeric cache of a c:val / c:yVal / c:xVal / c:bubbleSize container */
|
||||
function cacheNumbers(container: XNode): (number | null)[] {
|
||||
return cachePoints(container).map((v) => {
|
||||
if (v === null || v.trim() === '') return null
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) ? n : null
|
||||
})
|
||||
}
|
||||
|
||||
/** the series a:ln is an explicit a:noFill (scatter series drawn markers-only) */
|
||||
function seriesLineHidden(ser: XNode): boolean {
|
||||
const ln = findChild(findChild(ser, 'c:spPr') ?? {}, 'a:ln')
|
||||
return ln !== undefined && findChild(ln, 'a:noFill') !== undefined
|
||||
}
|
||||
|
||||
/** c:dPt explicit fills, sparse by point index (pie slices, highlighted bars) */
|
||||
function dataPointColors(ser: XNode, theme?: ThemeColors | null): (string | null)[] | null {
|
||||
const out: (string | null)[] = []
|
||||
let any = false
|
||||
for (const dPt of findChildren(ser, 'c:dPt')) {
|
||||
const idx = parseInt(attrsOf(findChild(dPt, 'c:idx') ?? {})['val'] ?? '', 10)
|
||||
if (!Number.isFinite(idx) || idx < 0) continue
|
||||
const color = solidFillHex(findChild(dPt, 'c:spPr'), theme)
|
||||
if (!color) continue
|
||||
out[idx] = color
|
||||
any = true
|
||||
}
|
||||
if (!any) return null
|
||||
for (let i = 0; i < out.length; i++) out[i] ??= null
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- chart style + color resolution ----
|
||||
|
||||
/** scheme slots charts reference in fills, resolved against the doc theme */
|
||||
const SCHEME_SLOTS: Record<string, keyof ThemeColors> = {
|
||||
accent1: 'accent1',
|
||||
accent2: 'accent2',
|
||||
accent3: 'accent3',
|
||||
accent4: 'accent4',
|
||||
accent5: 'accent5',
|
||||
accent6: 'accent6',
|
||||
dk1: 'dk1',
|
||||
lt1: 'lt1',
|
||||
dk2: 'dk2',
|
||||
lt2: 'lt2',
|
||||
tx1: 'dk1',
|
||||
bg1: 'lt1',
|
||||
tx2: 'dk2',
|
||||
bg2: 'lt2',
|
||||
}
|
||||
|
||||
/** resolve an spPr solid fill to hex (no '#'); schemeClr goes through the theme */
|
||||
function solidFillHex(spPr: XNode | undefined, theme?: ThemeColors | null): string | undefined {
|
||||
if (!spPr) return undefined
|
||||
const fill = findChild(spPr, 'a:solidFill')
|
||||
if (!fill) return undefined
|
||||
for (const clr of childrenOf(fill)) {
|
||||
const name = nameOf(clr)
|
||||
let base: string | undefined
|
||||
if (name === 'a:srgbClr') base = attrsOf(clr)['val']
|
||||
else if (name === 'a:sysClr') base = attrsOf(clr)['lastClr']
|
||||
else if (name === 'a:schemeClr') {
|
||||
const slot = SCHEME_SLOTS[attrsOf(clr)['val'] ?? '']
|
||||
base = slot ? theme?.[slot] : undefined
|
||||
}
|
||||
if (!base || !/^[0-9A-Fa-f]{6}$/.test(base)) continue
|
||||
return applyColorMods(base.toUpperCase(), clr)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** apply the transforms charts use (lumMod/lumOff/shade/tint) to a hex color */
|
||||
function applyColorMods(hex: string, clr: XNode): string {
|
||||
let lumMod: number | undefined
|
||||
let lumOff: number | undefined
|
||||
let shadeV: number | undefined
|
||||
let tintV: number | undefined
|
||||
for (const child of childrenOf(clr)) {
|
||||
const v = parseInt(attrsOf(child)['val'] ?? '', 10)
|
||||
if (!Number.isFinite(v)) continue
|
||||
const name = nameOf(child)
|
||||
if (name === 'a:lumMod') lumMod = v / 100000
|
||||
else if (name === 'a:lumOff') lumOff = v / 100000
|
||||
else if (name === 'a:shade') shadeV = v / 100000
|
||||
else if (name === 'a:tint') tintV = v / 100000
|
||||
}
|
||||
let out = hex
|
||||
if (shadeV !== undefined) out = shadeHex(out, shadeV)
|
||||
if (tintV !== undefined) out = tintHex(out, tintV)
|
||||
if (lumMod !== undefined || lumOff !== undefined) out = lumHex(out, lumMod ?? 1, lumOff ?? 0)
|
||||
return out
|
||||
}
|
||||
|
||||
const hexRgb = (hex: string): [number, number, number] => [
|
||||
parseInt(hex.slice(0, 2), 16),
|
||||
parseInt(hex.slice(2, 4), 16),
|
||||
parseInt(hex.slice(4, 6), 16),
|
||||
]
|
||||
|
||||
const rgbHex = (r: number, g: number, b: number): string =>
|
||||
[r, g, b]
|
||||
.map((c) =>
|
||||
Math.max(0, Math.min(255, Math.round(c)))
|
||||
.toString(16)
|
||||
.padStart(2, '0'),
|
||||
)
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
|
||||
/** a:shade — scale toward black */
|
||||
export function shadeHex(hex: string, factor: number): string {
|
||||
const [r, g, b] = hexRgb(hex)
|
||||
return rgbHex(r * factor, g * factor, b * factor)
|
||||
}
|
||||
|
||||
/** a:tint — scale toward white */
|
||||
export function tintHex(hex: string, factor: number): string {
|
||||
const [r, g, b] = hexRgb(hex)
|
||||
const t = (c: number) => c * factor + 255 * (1 - factor)
|
||||
return rgbHex(t(r), t(g), t(b))
|
||||
}
|
||||
|
||||
/** a:lumMod/a:lumOff — HSL luminance L' = L*mod + off */
|
||||
export function lumHex(hex: string, mod: number, off: number): string {
|
||||
const [r, g, b] = hexRgb(hex).map((c) => c / 255)
|
||||
const max = Math.max(r, g, b)
|
||||
const min = Math.min(r, g, b)
|
||||
let h = 0
|
||||
const l0 = (max + min) / 2
|
||||
const d = max - min
|
||||
let s = 0
|
||||
if (d !== 0) {
|
||||
s = d / (1 - Math.abs(2 * l0 - 1))
|
||||
if (max === r) h = ((g - b) / d) % 6
|
||||
else if (max === g) h = (b - r) / d + 2
|
||||
else h = (r - g) / d + 4
|
||||
h *= 60
|
||||
if (h < 0) h += 360
|
||||
}
|
||||
const l = Math.max(0, Math.min(1, l0 * mod + off))
|
||||
const c = (1 - Math.abs(2 * l - 1)) * s
|
||||
const x = c * (1 - Math.abs(((h / 60) % 2) - 1))
|
||||
const m = l - c / 2
|
||||
const seg =
|
||||
h < 60
|
||||
? [c, x, 0]
|
||||
: h < 120
|
||||
? [x, c, 0]
|
||||
: h < 180
|
||||
? [0, c, x]
|
||||
: h < 240
|
||||
? [0, x, c]
|
||||
: h < 300
|
||||
? [x, 0, c]
|
||||
: [c, 0, x]
|
||||
return rgbHex((seg[0] + m) * 255, (seg[1] + m) * 255, (seg[2] + m) * 255)
|
||||
}
|
||||
|
||||
/**
|
||||
* c:style 1-48 (Word 2010 wraps it: mc:Choice c14:style 101-148 with a
|
||||
* c:style fallback). The gallery column decides the series colors: 1 =
|
||||
* grayscale, 2 = accent cycle, 3-8 = single accent.
|
||||
*/
|
||||
function chartStyleVal(space: XNode): number | undefined {
|
||||
let node = findChild(space, 'c:style')
|
||||
if (!node) {
|
||||
const alt = findChild(space, 'mc:AlternateContent')
|
||||
const choice = alt ? findChild(alt, 'mc:Choice') : undefined
|
||||
const fallback = alt ? findChild(alt, 'mc:Fallback') : undefined
|
||||
node =
|
||||
(choice ? childrenOf(choice).find((c) => (nameOf(c) ?? '').endsWith(':style')) : undefined) ??
|
||||
(fallback ? findChild(fallback, 'c:style') : undefined)
|
||||
}
|
||||
let v = parseInt(attrsOf(node ?? {})['val'] ?? '', 10)
|
||||
if (v > 100) v -= 100
|
||||
return Number.isFinite(v) && v >= 1 && v <= 48 ? v : undefined
|
||||
}
|
||||
|
||||
/** Word's grayscale chart-style series colors (style column 1), approximated */
|
||||
const GRAYSCALE_PALETTE = ['595959', 'D9D9D9', 'A6A6A6', '404040', 'BFBFBF', '8C8C8C']
|
||||
|
||||
/** series color cycle for a chart style column, from the doc theme accents */
|
||||
function chartPalette(
|
||||
styleVal: number | undefined,
|
||||
theme?: ThemeColors | null,
|
||||
): string[] | undefined {
|
||||
const pos = styleVal === undefined ? 2 : ((styleVal - 1) % 8) + 1
|
||||
if (pos === 1) return GRAYSCALE_PALETTE
|
||||
const accents = [
|
||||
theme?.accent1,
|
||||
theme?.accent2,
|
||||
theme?.accent3,
|
||||
theme?.accent4,
|
||||
theme?.accent5,
|
||||
theme?.accent6,
|
||||
]
|
||||
if (accents.some((a) => !a || !/^[0-9A-Fa-f]{6}$/.test(a))) return undefined
|
||||
const list = accents.map((a) => a!.toUpperCase())
|
||||
if (pos === 2) return list
|
||||
const base = list[pos - 3]
|
||||
// monochromatic column: one hue, tint/shade ladder between series
|
||||
return [
|
||||
base,
|
||||
tintHex(base, 0.6),
|
||||
shadeHex(base, 0.75),
|
||||
tintHex(base, 0.3),
|
||||
shadeHex(base, 0.5),
|
||||
tintHex(base, 0.8),
|
||||
]
|
||||
}
|
||||
|
||||
/** cx layoutId → closest classic display kind (degrade: shapes differ, data/labels/title survive) */
|
||||
const CHARTEX_KINDS: Record<string, ChartDisplay['kind']> = {
|
||||
clusteredColumn: 'bar',
|
||||
@@ -100,7 +354,11 @@ const CHARTEX_KINDS: Record<string, ChartDisplay['kind']> = {
|
||||
function parseChartexPartXml(parsed: XNode[], partPath: string): ChartDisplay | null {
|
||||
const space = parsed.find((n) => nameOf(n) === 'cx:chartSpace')
|
||||
if (!space) return null
|
||||
const chartData = findChild(space, 'cx:chartData')
|
||||
// lenient lookup: consumers must skip unknown elements, and test corpora
|
||||
// rename cx:chartData to prove it — accept any child that carries cx:data
|
||||
const chartData =
|
||||
findChild(space, 'cx:chartData') ??
|
||||
childrenOf(space).find((c) => findChild(c, 'cx:data') !== undefined)
|
||||
// data id → {cats, vals}: strDim/numDim carry cx:lvl point caches (the first
|
||||
// strDim level holds the leaf labels of hierarchical charts)
|
||||
const dataById = new Map<string, { cats: string[]; vals: (number | null)[] }>()
|
||||
|
||||
@@ -1678,6 +1678,58 @@ function tableCellXml(
|
||||
* after structural edits; untouched tables and text-only edits keep their
|
||||
* original XML through the byte-preserving patch paths.
|
||||
*/
|
||||
const TBL_PR_ORDER = [
|
||||
'w:tblStyle',
|
||||
'w:tblpPr',
|
||||
'w:tblOverlap',
|
||||
'w:bidiVisual',
|
||||
'w:tblStyleRowBandSize',
|
||||
'w:tblStyleColBandSize',
|
||||
'w:tblW',
|
||||
'w:jc',
|
||||
'w:tblCellSpacing',
|
||||
'w:tblInd',
|
||||
'w:tblBorders',
|
||||
'w:shd',
|
||||
'w:tblLayout',
|
||||
'w:tblCellMar',
|
||||
'w:tblLook',
|
||||
] as const
|
||||
|
||||
/** Replace/remove/insert one tblPr child while keeping the OOXML schema order. */
|
||||
function setTblPrChild(tblPr: string, name: string, xml: string | null): string {
|
||||
const selfClosing = /^<w:tblPr(?:\s[^>]*)?\/>$/.test(tblPr)
|
||||
const open = selfClosing ? tblPr.replace(/\/>$/, '>') : /^<w:tblPr(?:\s[^>]*)?>/.exec(tblPr)?.[0]
|
||||
if (!open) return tblPr
|
||||
const inner = selfClosing ? '' : tblPr.slice(open.length, tblPr.lastIndexOf('</w:tblPr>'))
|
||||
const children = splitXmlChildren(inner).filter((child) => child.name !== name)
|
||||
if (xml) {
|
||||
const order = TBL_PR_ORDER.indexOf(name as (typeof TBL_PR_ORDER)[number])
|
||||
const at = children.findIndex((child) => {
|
||||
const childOrder = TBL_PR_ORDER.indexOf(child.name as (typeof TBL_PR_ORDER)[number])
|
||||
return order >= 0 && childOrder >= 0 && childOrder > order
|
||||
})
|
||||
children.splice(at < 0 ? children.length : at, 0, { name, xml })
|
||||
}
|
||||
return `${open}${children.map((child) => child.xml).join('')}</w:tblPr>`
|
||||
}
|
||||
|
||||
function tableLookXml(look: NonNullable<TableModel['tableLook']>): string {
|
||||
const val =
|
||||
(look.firstRow ? 0x20 : 0) |
|
||||
(look.lastRow ? 0x40 : 0) |
|
||||
(look.firstColumn ? 0x80 : 0) |
|
||||
(look.lastColumn ? 0x100 : 0) |
|
||||
(look.bandedRows ? 0 : 0x200) |
|
||||
(look.bandedColumns ? 0 : 0x400)
|
||||
return (
|
||||
`<w:tblLook w:val="${val.toString(16).toUpperCase().padStart(4, '0')}"` +
|
||||
` w:firstRow="${look.firstRow ? 1 : 0}" w:lastRow="${look.lastRow ? 1 : 0}"` +
|
||||
` w:firstColumn="${look.firstColumn ? 1 : 0}" w:lastColumn="${look.lastColumn ? 1 : 0}"` +
|
||||
` w:noHBand="${look.bandedRows ? 0 : 1}" w:noVBand="${look.bandedColumns ? 0 : 1}"/>`
|
||||
)
|
||||
}
|
||||
|
||||
export function generateTableModelXml(model: TableModel, originalTableXml?: string): string {
|
||||
const columnCount = Math.max(
|
||||
1,
|
||||
@@ -1727,18 +1779,52 @@ export function generateTableModelXml(model: TableModel, originalTableXml?: stri
|
||||
const rows = model.rows
|
||||
.map((row, ri) => {
|
||||
let gridColumn = 0
|
||||
const cells = row.map((cell) => {
|
||||
const cells: string[] = []
|
||||
// gridGap placeholders are the display stand-ins for w:gridBefore/w:gridAfter:
|
||||
// they advance the grid but are never written as w:tc
|
||||
const edges = { before: 0, wBefore: 0, after: 0, wAfter: 0 }
|
||||
for (const cell of row) {
|
||||
const span = Math.max(1, cell.colSpan ?? 1)
|
||||
const width = widths
|
||||
.slice(gridColumn, gridColumn + span)
|
||||
.reduce((sum, value) => sum + value, 0)
|
||||
gridColumn += span
|
||||
return tableCellXml(cell, width)
|
||||
})
|
||||
if (cell.gridGap) {
|
||||
if (cells.length === 0) {
|
||||
edges.before += span
|
||||
edges.wBefore += width
|
||||
} else {
|
||||
edges.after += span
|
||||
edges.wAfter += width
|
||||
}
|
||||
continue
|
||||
}
|
||||
cells.push(tableCellXml(cell, width))
|
||||
}
|
||||
// trPr: original bytes passed through (tblHeader/cantSplit etc.); row height is
|
||||
// replaced/inserted/removed per the model
|
||||
let trPr = model.rawTrPrs?.[ri] ?? ''
|
||||
if (trPr && !trPr.endsWith('</w:trPr>')) trPr = ''
|
||||
if (!trPr && (edges.before > 0 || edges.after > 0)) {
|
||||
// CT_TrPr schema order: gridBefore, gridAfter, wBefore, wAfter
|
||||
trPr =
|
||||
'<w:trPr>' +
|
||||
(edges.before > 0 ? `<w:gridBefore w:val="${edges.before}"/>` : '') +
|
||||
(edges.after > 0 ? `<w:gridAfter w:val="${edges.after}"/>` : '') +
|
||||
(edges.before > 0 ? `<w:wBefore w:w="${edges.wBefore}" w:type="dxa"/>` : '') +
|
||||
(edges.after > 0 ? `<w:wAfter w:w="${edges.wAfter}" w:type="dxa"/>` : '') +
|
||||
'</w:trPr>'
|
||||
}
|
||||
const repeatHeader = model.repeatHeaderRows?.[ri]
|
||||
if (repeatHeader !== null && repeatHeader !== undefined) {
|
||||
trPr = trPr.replace(/<w:tblHeader(?:\s[^>]*)?\/>/g, '')
|
||||
if (repeatHeader) {
|
||||
const tag = '<w:tblHeader/>'
|
||||
trPr = trPr ? trPr.replace('</w:trPr>', `${tag}</w:trPr>`) : `<w:trPr>${tag}</w:trPr>`
|
||||
} else if (/^<w:trPr(?:\s[^>]*)?>\s*<\/w:trPr>$/.test(trPr)) {
|
||||
trPr = ''
|
||||
}
|
||||
}
|
||||
const h = model.rowHeightsTwips?.[ri]
|
||||
if (h != null && h > 0) {
|
||||
const rule = model.rowHeightRules?.[ri] === 'exact' ? 'exact' : 'atLeast'
|
||||
@@ -1760,52 +1846,93 @@ export function generateTableModelXml(model: TableModel, originalTableXml?: stri
|
||||
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>${tblpPr}<w:tblW w:w="${totalWidth}" w:type="dxa"/>${tblInd}${borders}` +
|
||||
`<w:tblLayout w:type="fixed"/>${cellMar}</w:tblPr>`
|
||||
`<w:tblPr><w:tblW w:w="${totalWidth}" w:type="dxa"/>${tblInd}${borders}</w:tblPr>`
|
||||
// Table style reference: '' = remove, non-empty = replace/insert (tblStyle is the
|
||||
// first tblPr child)
|
||||
if (model.tblStyleId !== undefined) {
|
||||
tblPr = tblPr.replace(/<w:tblStyle[^>]*\/>/, '')
|
||||
if (model.tblStyleId !== '') {
|
||||
const tag = `<w:tblStyle w:val="${escapeXmlAttr(model.tblStyleId)}"/>`
|
||||
tblPr = /<w:tblPr\/>/.test(tblPr)
|
||||
? tblPr.replace('<w:tblPr/>', `<w:tblPr>${tag}</w:tblPr>`)
|
||||
: tblPr.replace(/(<w:tblPr(?:\s[^>]*)?>)/, `$1${tag}`)
|
||||
// Style banding/header-row switches default to 04A0 (firstRow + banding)
|
||||
if (!/<w:tblLook[\s/>]/.test(tblPr)) {
|
||||
tblPr = tblPr.replace(
|
||||
'</w:tblPr>',
|
||||
'<w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/></w:tblPr>',
|
||||
)
|
||||
tblPr = setTblPrChild(
|
||||
tblPr,
|
||||
'w:tblStyle',
|
||||
model.tblStyleId === '' ? null : `<w:tblStyle w:val="${escapeXmlAttr(model.tblStyleId)}"/>`,
|
||||
)
|
||||
}
|
||||
// Floating positioning + wrapping. null explicitly returns the table to the
|
||||
// text flow; undefined leaves an imported tblpPr byte-for-byte intact.
|
||||
const requestedFloatSide =
|
||||
model.floatSide === undefined && model.floatPos
|
||||
? model.floatPos.xTwips > 4680
|
||||
? 'right'
|
||||
: 'left'
|
||||
: model.floatSide
|
||||
if (requestedFloatSide !== undefined || (!originalTblPr && model.floatPos)) {
|
||||
if (!requestedFloatSide) {
|
||||
tblPr = setTblPrChild(tblPr, 'w:tblpPr', null)
|
||||
tblPr = setTblPrChild(tblPr, 'w:tblOverlap', null)
|
||||
} else {
|
||||
const pos = model.floatPos ?? {
|
||||
xTwips: requestedFloatSide === 'right' ? Math.max(0, 9360 - totalWidth) : 0,
|
||||
yTwips: 0,
|
||||
}
|
||||
const distance = pos.distanceTwips ?? {}
|
||||
const attr = (name: string, value: number | undefined) =>
|
||||
value == null ? '' : ` w:${name}="${Math.max(0, Math.round(value))}"`
|
||||
const tag =
|
||||
`<w:tblpPr${attr('leftFromText', distance.left)}${attr('rightFromText', distance.right)}` +
|
||||
`${attr('topFromText', distance.top)}${attr('bottomFromText', distance.bottom)}` +
|
||||
` w:vertAnchor="${pos.vertAnchor ?? 'page'}"` +
|
||||
` w:horzAnchor="${pos.horzAnchor ?? 'page'}"` +
|
||||
` w:tblpX="${Math.round(pos.xTwips)}" w:tblpY="${Math.round(pos.yTwips)}"/>`
|
||||
tblPr = setTblPrChild(tblPr, 'w:tblpPr', tag)
|
||||
tblPr = setTblPrChild(tblPr, 'w:tblOverlap', '<w:tblOverlap w:val="overlap"/>')
|
||||
}
|
||||
}
|
||||
const effectiveAutoFit =
|
||||
model.autoFit ?? (!originalTblPr ? (model.autoLayout ? 'contents' : 'fixed') : null)
|
||||
if (effectiveAutoFit) {
|
||||
tblPr = setTblPrChild(
|
||||
tblPr,
|
||||
'w:tblW',
|
||||
effectiveAutoFit === 'window'
|
||||
? '<w:tblW w:w="5000" w:type="pct"/>'
|
||||
: effectiveAutoFit === 'contents'
|
||||
? '<w:tblW w:w="0" w:type="auto"/>'
|
||||
: `<w:tblW w:w="${totalWidth}" w:type="dxa"/>`,
|
||||
)
|
||||
tblPr = setTblPrChild(
|
||||
tblPr,
|
||||
'w:tblLayout',
|
||||
`<w:tblLayout w:type="${effectiveAutoFit === 'fixed' ? 'fixed' : 'autofit'}"/>`,
|
||||
)
|
||||
}
|
||||
if (model.cellMarTwips !== undefined) {
|
||||
tblPr = setTblPrChild(tblPr, 'w:tblCellMar', cellMar || null)
|
||||
}
|
||||
if (model.tableLook) {
|
||||
tblPr = setTblPrChild(tblPr, 'w:tblLook', tableLookXml(model.tableLook))
|
||||
} else if (model.tblStyleId && !/<w:tblLook[\s/>]/.test(tblPr)) {
|
||||
tblPr = setTblPrChild(
|
||||
tblPr,
|
||||
'w:tblLook',
|
||||
tableLookXml({
|
||||
firstRow: true,
|
||||
lastRow: false,
|
||||
firstColumn: true,
|
||||
lastColumn: false,
|
||||
bandedRows: true,
|
||||
bandedColumns: false,
|
||||
}),
|
||||
)
|
||||
}
|
||||
// Table alignment (w:jc): explicit align replaces/removes the original;
|
||||
// undefined keeps whatever the original tblPr carried
|
||||
if (model.align) {
|
||||
tblPr = tblPr.replace(/<w:jc[^>]*\/>/, '')
|
||||
if (model.align !== 'left') {
|
||||
const tag = `<w:jc w:val="${model.align}"/>`
|
||||
// schema order puts w:jc right after w:tblW (after w:tblStyle when there is no tblW)
|
||||
if (/<w:tblW[^>]*\/>/.test(tblPr)) tblPr = tblPr.replace(/(<w:tblW[^>]*\/>)/, `$1${tag}`)
|
||||
else if (/<w:tblStyle[^>]*\/>/.test(tblPr))
|
||||
tblPr = tblPr.replace(/(<w:tblStyle[^>]*\/>)/, `$1${tag}`)
|
||||
else if (/<w:tblPr\/>/.test(tblPr))
|
||||
tblPr = tblPr.replace('<w:tblPr/>', `<w:tblPr>${tag}</w:tblPr>`)
|
||||
else tblPr = tblPr.replace(/(<w:tblPr(?:\s[^>]*)?>)/, `$1${tag}`)
|
||||
}
|
||||
tblPr = setTblPrChild(
|
||||
tblPr,
|
||||
'w:jc',
|
||||
model.align === 'left' ? null : `<w:jc w:val="${model.align}"/>`,
|
||||
)
|
||||
}
|
||||
return `<w:tbl>${tblPr}${grid}${rows}</w:tbl>`
|
||||
}
|
||||
|
||||
@@ -57,6 +57,7 @@ export {
|
||||
patchChartWorkbookXlsxBase64,
|
||||
parseChartPartXml,
|
||||
patchChartPartXml,
|
||||
lumHex,
|
||||
CHART_WORKBOOK_REL_TYPE,
|
||||
type ChartPatch,
|
||||
type ChartSeriesPatch,
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
/**
|
||||
* ISO Strict OOXML (purl.oclc.org URIs) and non-canonical namespace prefixes,
|
||||
* normalized to the transitional URIs + canonical prefixes that the rest of
|
||||
* the engine matches literally (`w:p`, `wps:wsp`, rel-type strings...). Runs
|
||||
* once per XML part at zip load, so parse offsets, patch splices and saved
|
||||
* output all see the same bytes.
|
||||
*/
|
||||
|
||||
const T = 'http://schemas.openxmlformats.org/'
|
||||
const S = 'http://purl.oclc.org/ooxml/'
|
||||
const MS = 'http://schemas.microsoft.com/office/'
|
||||
|
||||
/** ISO 29500 Strict namespace -> ECMA transitional equivalent (official 1:1 pairs) */
|
||||
const STRICT_TO_TRANSITIONAL: ReadonlyMap<string, string> = new Map([
|
||||
[`${S}wordprocessingml/main`, `${T}wordprocessingml/2006/main`],
|
||||
[`${S}officeDocument/relationships`, `${T}officeDocument/2006/relationships`],
|
||||
[`${S}officeDocument/math`, `${T}officeDocument/2006/math`],
|
||||
[`${S}officeDocument/extendedProperties`, `${T}officeDocument/2006/extended-properties`],
|
||||
[`${S}officeDocument/customProperties`, `${T}officeDocument/2006/custom-properties`],
|
||||
[`${S}officeDocument/docPropsVTypes`, `${T}officeDocument/2006/docPropsVTypes`],
|
||||
[`${S}officeDocument/bibliography`, `${T}officeDocument/2006/bibliography`],
|
||||
[`${S}officeDocument/characteristics`, `${T}officeDocument/2006/characteristics`],
|
||||
[`${S}officeDocument/customXml`, `${T}officeDocument/2006/customXml`],
|
||||
[`${S}schemaLibrary/main`, `${T}schemaLibrary/2006/main`],
|
||||
[`${S}drawingml/main`, `${T}drawingml/2006/main`],
|
||||
[`${S}drawingml/wordprocessingDrawing`, `${T}drawingml/2006/wordprocessingDrawing`],
|
||||
[`${S}drawingml/spreadsheetDrawing`, `${T}drawingml/2006/spreadsheetDrawing`],
|
||||
[`${S}drawingml/picture`, `${T}drawingml/2006/picture`],
|
||||
[`${S}drawingml/chart`, `${T}drawingml/2006/chart`],
|
||||
[`${S}drawingml/chartDrawing`, `${T}drawingml/2006/chartDrawing`],
|
||||
[`${S}drawingml/diagram`, `${T}drawingml/2006/diagram`],
|
||||
[`${S}drawingml/lockedCanvas`, `${T}drawingml/2006/lockedCanvas`],
|
||||
[`${S}drawingml/compatibility`, `${T}drawingml/2006/compatibility`],
|
||||
])
|
||||
|
||||
const STRICT_REL_BASE = `${S}officeDocument/relationships/`
|
||||
const TRANSITIONAL_REL_BASE = `${T}officeDocument/2006/relationships/`
|
||||
/** relationship-type tails that differ between the strict and transitional families */
|
||||
const REL_TAIL: Readonly<Record<string, string>> = {
|
||||
extendedProperties: 'extended-properties',
|
||||
customProperties: 'custom-properties',
|
||||
}
|
||||
|
||||
const W_URI = `${T}wordprocessingml/2006/main`
|
||||
const A_URI = `${T}drawingml/2006/main`
|
||||
const WP_URI = `${T}drawingml/2006/wordprocessingDrawing`
|
||||
const WPS_URI = `${MS}word/2010/wordprocessingShape`
|
||||
const MC_URI = `${T}markup-compatibility/2006`
|
||||
|
||||
/**
|
||||
* Prefixes the engine matches literally, keyed by (transitional) namespace URI.
|
||||
* A binding of one of these URIs to any other prefix gets renamed — matching
|
||||
* by URI + localName, never by localName alone, so unrelated namespaces that
|
||||
* happen to reuse a local name are left untouched.
|
||||
*/
|
||||
const CANONICAL_PREFIX_BY_URI: ReadonlyMap<string, string> = new Map([
|
||||
[W_URI, 'w'],
|
||||
[`${T}officeDocument/2006/relationships`, 'r'],
|
||||
[`${T}officeDocument/2006/math`, 'm'],
|
||||
[A_URI, 'a'],
|
||||
[WP_URI, 'wp'],
|
||||
[`${T}drawingml/2006/picture`, 'pic'],
|
||||
[`${T}drawingml/2006/chart`, 'c'],
|
||||
[`${T}drawingml/2006/diagram`, 'dgm'],
|
||||
[`${T}drawingml/2006/lockedCanvas`, 'lc'],
|
||||
[MC_URI, 'mc'],
|
||||
[WPS_URI, 'wps'],
|
||||
[`${MS}word/2010/wordprocessingGroup`, 'wpg'],
|
||||
[`${MS}word/2010/wordprocessingCanvas`, 'wpc'],
|
||||
[`${MS}word/2010/wordml`, 'w14'],
|
||||
[`${MS}word/2012/wordml`, 'w15'],
|
||||
['urn:schemas-microsoft-com:vml', 'v'],
|
||||
['urn:schemas-microsoft-com:office:office', 'o'],
|
||||
['urn:schemas-microsoft-com:office:word', 'w10'],
|
||||
])
|
||||
|
||||
// Strict "universal measures" ("612pt", "2.54cm"...) -> the plain numeric unit
|
||||
// each attribute is typed with (twips / half-points / eighth-points / points).
|
||||
const PT_PER_UNIT: Readonly<Record<string, number>> = {
|
||||
pt: 1,
|
||||
in: 72,
|
||||
pc: 12,
|
||||
pi: 12,
|
||||
cm: 72 / 2.54,
|
||||
mm: 72 / 25.4,
|
||||
}
|
||||
const MEASURE_RE = /^(-?\d+(?:\.\d+)?)(mm|cm|in|pt|pc|pi)$/
|
||||
const TWIPS = 20
|
||||
const HALF_POINTS = 2
|
||||
const EIGHTH_POINTS = 8
|
||||
const POINTS = 1
|
||||
|
||||
type AttrFactors = Readonly<Record<string, number>>
|
||||
const MARGIN_OR_BORDER: AttrFactors = { w: TWIPS, sz: EIGHTH_POINTS, space: POINTS }
|
||||
/** element localName -> attr localName -> target units per point (w: namespace only) */
|
||||
const MEASURE_ATTRS: ReadonlyMap<string, AttrFactors> = new Map<string, AttrFactors>([
|
||||
['pgSz', { w: TWIPS, h: TWIPS }],
|
||||
[
|
||||
'pgMar',
|
||||
{
|
||||
top: TWIPS,
|
||||
right: TWIPS,
|
||||
bottom: TWIPS,
|
||||
left: TWIPS,
|
||||
header: TWIPS,
|
||||
footer: TWIPS,
|
||||
gutter: TWIPS,
|
||||
},
|
||||
],
|
||||
[
|
||||
'ind',
|
||||
{ left: TWIPS, right: TWIPS, start: TWIPS, end: TWIPS, firstLine: TWIPS, hanging: TWIPS },
|
||||
],
|
||||
['spacing', { before: TWIPS, after: TWIPS, line: TWIPS, val: TWIPS }],
|
||||
['tab', { pos: TWIPS }],
|
||||
['defaultTabStop', { val: TWIPS }],
|
||||
['cols', { space: TWIPS }],
|
||||
['col', { w: TWIPS, space: TWIPS }],
|
||||
['tblInd', { w: TWIPS }],
|
||||
['tblW', { w: TWIPS }],
|
||||
['tcW', { w: TWIPS }],
|
||||
['tblCellSpacing', { w: TWIPS }],
|
||||
['object', { dxaOrig: TWIPS, dyaOrig: TWIPS }],
|
||||
['trHeight', { val: TWIPS }],
|
||||
['framePr', { w: TWIPS, h: TWIPS, x: TWIPS, y: TWIPS, hSpace: TWIPS, vSpace: TWIPS }],
|
||||
[
|
||||
'tblpPr',
|
||||
{
|
||||
leftFromText: TWIPS,
|
||||
rightFromText: TWIPS,
|
||||
topFromText: TWIPS,
|
||||
bottomFromText: TWIPS,
|
||||
tblpX: TWIPS,
|
||||
tblpY: TWIPS,
|
||||
},
|
||||
],
|
||||
['sz', { val: HALF_POINTS }],
|
||||
['szCs', { val: HALF_POINTS }],
|
||||
['kern', { val: HALF_POINTS }],
|
||||
['position', { val: HALF_POINTS }],
|
||||
['hps', { val: HALF_POINTS }],
|
||||
['hpsRaise', { val: HALF_POINTS }],
|
||||
['hpsBaseText', { val: HALF_POINTS }],
|
||||
// cell margins (w) and borders (sz/space) share these element names
|
||||
['top', MARGIN_OR_BORDER],
|
||||
['bottom', MARGIN_OR_BORDER],
|
||||
['left', MARGIN_OR_BORDER],
|
||||
['right', MARGIN_OR_BORDER],
|
||||
['start', MARGIN_OR_BORDER],
|
||||
['end', MARGIN_OR_BORDER],
|
||||
['between', MARGIN_OR_BORDER],
|
||||
['bar', MARGIN_OR_BORDER],
|
||||
['insideH', MARGIN_OR_BORDER],
|
||||
['insideV', MARGIN_OR_BORDER],
|
||||
['tl2br', MARGIN_OR_BORDER],
|
||||
['tr2bl', MARGIN_OR_BORDER],
|
||||
])
|
||||
|
||||
function convertMeasure(value: string, factor: number): string {
|
||||
const m = MEASURE_RE.exec(value)
|
||||
if (!m) return value
|
||||
return String(Math.round(parseFloat(m[1]) * PT_PER_UNIT[m[2]]! * factor))
|
||||
}
|
||||
|
||||
function mapUriValue(value: string): string {
|
||||
const direct = STRICT_TO_TRANSITIONAL.get(value)
|
||||
if (direct) return direct
|
||||
if (value.startsWith(STRICT_REL_BASE)) {
|
||||
const tail = value.slice(STRICT_REL_BASE.length)
|
||||
return TRANSITIONAL_REL_BASE + (REL_TAIL[tail] ?? tail)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
const XMLNS_DECL_RE = /xmlns(?::([A-Za-z_][\w.-]*))?\s*=\s*(["'])([^"']*)\2/g
|
||||
|
||||
/** Cheap pre-check; normalizeOoxmlXml is only worth calling when this is true. */
|
||||
export function needsOoxmlNormalization(xml: string): boolean {
|
||||
if (xml.includes(S)) return true
|
||||
XMLNS_DECL_RE.lastIndex = 0
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = XMLNS_DECL_RE.exec(xml)) !== null) {
|
||||
const canonical = CANONICAL_PREFIX_BY_URI.get(m[3]!)
|
||||
if (canonical !== undefined && canonical !== (m[1] ?? '')) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
interface Attr {
|
||||
name: string
|
||||
value: string
|
||||
}
|
||||
|
||||
interface Frame {
|
||||
/** rewritten name to emit for the matching end tag */
|
||||
name: string
|
||||
scoped: boolean
|
||||
wspScope: boolean
|
||||
}
|
||||
|
||||
const TAG_NAME_RE = /^<\/?\s*([^\s/>]+)/
|
||||
const ATTR_RE = /([^\s=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g
|
||||
|
||||
function splitQName(name: string): [prefix: string, local: string] {
|
||||
const i = name.indexOf(':')
|
||||
return i < 0 ? ['', name] : [name.slice(0, i), name.slice(i + 1)]
|
||||
}
|
||||
|
||||
export function normalizeOoxmlXml(xml: string): string {
|
||||
// scope stacks; lookups walk from the top so inner declarations shadow outer ones
|
||||
const bindings: Array<Map<string, string>> = [new Map()] // source prefix -> transitional URI
|
||||
const renames: Array<Map<string, string>> = [new Map()] // source prefix -> output prefix
|
||||
const outBindings: Array<Map<string, string>> = [new Map()] // output prefix -> transitional URI
|
||||
const frames: Frame[] = []
|
||||
let wspDepth = 0
|
||||
|
||||
const lookup = (stack: Array<Map<string, string>>, key: string): string | undefined => {
|
||||
for (let i = stack.length - 1; i >= 0; i--) {
|
||||
const v = stack[i]!.get(key)
|
||||
if (v !== undefined) return v
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
const renamePrefix = (prefix: string): string => lookup(renames, prefix) ?? prefix
|
||||
|
||||
let out = ''
|
||||
let cursor = 0
|
||||
while (cursor < xml.length) {
|
||||
const start = xml.indexOf('<', cursor)
|
||||
if (start < 0) break
|
||||
out += xml.slice(cursor, start)
|
||||
|
||||
const specialEnd = xml.startsWith('<!--', start)
|
||||
? '-->'
|
||||
: xml.startsWith('<![CDATA[', start)
|
||||
? ']]>'
|
||||
: xml.startsWith('<?', start)
|
||||
? '?>'
|
||||
: xml.startsWith('<!', start)
|
||||
? '>'
|
||||
: null
|
||||
if (specialEnd !== null) {
|
||||
const at = xml.indexOf(specialEnd, start + 2)
|
||||
const end = at < 0 ? xml.length : at + specialEnd.length
|
||||
out += xml.slice(start, end)
|
||||
cursor = end
|
||||
continue
|
||||
}
|
||||
|
||||
// find the tag end, tolerating '>' inside quoted attribute values
|
||||
let quote = ''
|
||||
let end = start + 1
|
||||
for (; end < xml.length; end += 1) {
|
||||
const ch = xml[end]!
|
||||
if (quote) {
|
||||
if (ch === quote) quote = ''
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
quote = ch
|
||||
} else if (ch === '>') {
|
||||
break
|
||||
}
|
||||
}
|
||||
if (end >= xml.length) {
|
||||
out += xml.slice(start)
|
||||
cursor = xml.length
|
||||
continue
|
||||
}
|
||||
const tag = xml.slice(start, end + 1)
|
||||
cursor = end + 1
|
||||
|
||||
if (tag.startsWith('</')) {
|
||||
const frame = frames.pop()
|
||||
if (frame) {
|
||||
out += `</${frame.name}>`
|
||||
if (frame.scoped) {
|
||||
bindings.pop()
|
||||
renames.pop()
|
||||
outBindings.pop()
|
||||
}
|
||||
if (frame.wspScope) wspDepth -= 1
|
||||
} else {
|
||||
out += tag
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const selfClosing = /\/\s*>$/.test(tag)
|
||||
const name = TAG_NAME_RE.exec(tag)?.[1]
|
||||
if (!name) {
|
||||
out += tag
|
||||
continue
|
||||
}
|
||||
const attrs: Attr[] = []
|
||||
ATTR_RE.lastIndex = TAG_NAME_RE.exec(tag)![0].length
|
||||
let am: RegExpExecArray | null
|
||||
while ((am = ATTR_RE.exec(tag)) !== null) {
|
||||
attrs.push({ name: am[1]!, value: am[2] ?? am[3] ?? '' })
|
||||
}
|
||||
|
||||
// namespace declarations open a scope; strict URIs map to transitional
|
||||
const newBindings = new Map<string, string>()
|
||||
const declByPrefix = new Map<string, Attr>()
|
||||
for (const attr of attrs) {
|
||||
if (attr.name !== 'xmlns' && !attr.name.startsWith('xmlns:')) continue
|
||||
attr.value = mapUriValue(attr.value)
|
||||
const declPrefix = attr.name === 'xmlns' ? '' : attr.name.slice(6)
|
||||
newBindings.set(declPrefix, attr.value)
|
||||
declByPrefix.set(declPrefix, attr)
|
||||
}
|
||||
let scoped = false
|
||||
if (newBindings.size > 0) {
|
||||
scoped = true
|
||||
bindings.push(newBindings)
|
||||
const newRenames = new Map<string, string>()
|
||||
renames.push(newRenames)
|
||||
const newOut = new Map<string, string>()
|
||||
outBindings.push(newOut)
|
||||
const drop = new Set<Attr>()
|
||||
const inject: Attr[] = []
|
||||
// declarations that keep their prefix claim it in the output first, so a
|
||||
// rename can neither steal it nor be blocked by a prefix that is itself
|
||||
// being renamed away
|
||||
for (const [prefix, uri] of newBindings) {
|
||||
const canonical = CANONICAL_PREFIX_BY_URI.get(uri)
|
||||
if (canonical === undefined || canonical === prefix) newOut.set(prefix, uri)
|
||||
}
|
||||
for (const [prefix, uri] of newBindings) {
|
||||
const canonical = CANONICAL_PREFIX_BY_URI.get(uri)
|
||||
if (canonical === undefined || canonical === prefix) continue
|
||||
const bound = lookup(outBindings, canonical)
|
||||
if (bound !== undefined && bound !== uri) {
|
||||
newOut.set(prefix, uri) // canonical prefix taken by another namespace: keep as-is
|
||||
continue
|
||||
}
|
||||
newRenames.set(prefix, canonical)
|
||||
// by captured reference: finding by name could hit a declaration whose
|
||||
// name an earlier rename already rewrote to this prefix
|
||||
const decl = declByPrefix.get(prefix)!
|
||||
if (bound === uri) {
|
||||
if (prefix !== '') drop.add(decl) // canonical binding already exists
|
||||
} else if (prefix === '') {
|
||||
inject.push({ name: `xmlns:${canonical}`, value: uri }) // keep xmlns= for other content
|
||||
} else {
|
||||
decl.name = `xmlns:${canonical}`
|
||||
}
|
||||
newOut.set(canonical, uri)
|
||||
if (prefix === '') newOut.set('', uri)
|
||||
}
|
||||
if (drop.size > 0 || inject.length > 0) {
|
||||
attrs.splice(0, attrs.length, ...attrs.filter((a) => !drop.has(a)), ...inject)
|
||||
}
|
||||
}
|
||||
|
||||
const [prefix, local] = splitQName(name)
|
||||
const elementUri = lookup(bindings, prefix)
|
||||
|
||||
// Word 2013 strict writes wordprocessingShape children in the wp (drawing)
|
||||
// namespace inside <a:graphicData uri="...wordprocessingShape">; the engine
|
||||
// matches wps:*, so shift those elements (only there) into the wps prefix.
|
||||
let targetPrefix = renamePrefix(prefix)
|
||||
if (wspDepth > 0 && elementUri === WP_URI) {
|
||||
targetPrefix = 'wps'
|
||||
if (lookup(outBindings, 'wps') !== WPS_URI) {
|
||||
attrs.push({ name: 'xmlns:wps', value: WPS_URI })
|
||||
if (!scoped) {
|
||||
scoped = true
|
||||
bindings.push(new Map())
|
||||
renames.push(new Map())
|
||||
outBindings.push(new Map())
|
||||
}
|
||||
outBindings[outBindings.length - 1]!.set('wps', WPS_URI)
|
||||
}
|
||||
}
|
||||
const newName = targetPrefix === '' ? local : `${targetPrefix}:${local}`
|
||||
|
||||
const inWNs = elementUri === W_URI
|
||||
const factors = inWNs ? MEASURE_ATTRS.get(local) : undefined
|
||||
const kept: Attr[] = []
|
||||
for (const attr of attrs) {
|
||||
if (attr.name === 'xmlns' || attr.name.startsWith('xmlns:')) {
|
||||
kept.push(attr)
|
||||
continue
|
||||
}
|
||||
const [ap, al] = splitQName(attr.name)
|
||||
if (inWNs && local === 'document' && al === 'conformance') continue
|
||||
if (ap !== '' && ap !== 'xml') {
|
||||
const np = renamePrefix(ap)
|
||||
if (np !== ap) attr.name = `${np}:${al}`
|
||||
}
|
||||
// MCE prefix lists must keep referring to the renamed prefixes
|
||||
const mceList =
|
||||
(al === 'Ignorable' || al === 'MustUnderstand') && lookup(bindings, ap) === MC_URI
|
||||
? true
|
||||
: al === 'Requires' && ap === '' && elementUri === MC_URI
|
||||
if (mceList) {
|
||||
attr.value = attr.value
|
||||
.split(/\s+/)
|
||||
.map((p) => renamePrefix(p))
|
||||
.join(' ')
|
||||
} else {
|
||||
attr.value = mapUriValue(attr.value)
|
||||
const factor = factors?.[al]
|
||||
if (factor !== undefined && (ap === '' || lookup(bindings, ap) === W_URI)) {
|
||||
attr.value = convertMeasure(attr.value, factor)
|
||||
}
|
||||
}
|
||||
kept.push(attr)
|
||||
}
|
||||
|
||||
const attrText = kept.map((a) => ` ${a.name}="${a.value.replace(/"/g, '"')}"`).join('')
|
||||
out += `<${newName}${attrText}${selfClosing ? '/>' : '>'}`
|
||||
|
||||
const wspScope =
|
||||
!selfClosing && local === 'graphicData' && elementUri === A_URI
|
||||
? attrs.some((a) => a.name === 'uri' && a.value === WPS_URI)
|
||||
: false
|
||||
if (wspScope) wspDepth += 1
|
||||
|
||||
if (selfClosing) {
|
||||
if (scoped) {
|
||||
bindings.pop()
|
||||
renames.pop()
|
||||
outBindings.pop()
|
||||
}
|
||||
} else {
|
||||
frames.push({ name: newName, scoped, wspScope })
|
||||
}
|
||||
}
|
||||
out += xml.slice(cursor)
|
||||
return out
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -127,6 +127,23 @@ const THEME_COLOR_SLOTS: Record<string, keyof ThemeColors> = {
|
||||
|
||||
const SLOT_FALLBACK: Partial<Record<keyof ThemeColors, string>> = { dk1: '000000', lt1: 'FFFFFF' }
|
||||
|
||||
/** built-in Office palette: what Word resolves theme colors against when a
|
||||
* document ships no word/theme/theme1.xml part */
|
||||
export const DEFAULT_THEME_COLORS: Readonly<ThemeColors> = {
|
||||
dk1: '000000',
|
||||
lt1: 'FFFFFF',
|
||||
dk2: '44546A',
|
||||
lt2: 'E7E6E6',
|
||||
accent1: '4472C4',
|
||||
accent2: 'ED7D31',
|
||||
accent3: 'A5A5A5',
|
||||
accent4: 'FFC000',
|
||||
accent5: '5B9BD5',
|
||||
accent6: '70AD47',
|
||||
hlink: '0563C1',
|
||||
folHlink: '954F72',
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a w:themeColor reference (+ optional w:themeTint / w:themeShade,
|
||||
* hex 00-FF) against the palette. sRGB per-channel approximation of Word's
|
||||
@@ -180,8 +197,8 @@ export function applyThemeColors(themeXml: string, colors: ThemeColors): string
|
||||
* format scheme skeleton.
|
||||
*/
|
||||
export function buildThemeXml(fonts: ThemeFonts, colors: ThemeColors): string {
|
||||
const c = (tag: (typeof COLOR_TAGS)[number], fallback: string) =>
|
||||
`<a:${tag}><a:srgbClr val="${colors[tag] ?? fallback}"/></a:${tag}>`
|
||||
const c = (tag: (typeof COLOR_TAGS)[number]) =>
|
||||
`<a:${tag}><a:srgbClr val="${colors[tag] ?? DEFAULT_THEME_COLORS[tag]}"/></a:${tag}>`
|
||||
const font = (tag: string, typeface: string) =>
|
||||
`<${tag}><a:latin typeface="${escapeXmlAttr(typeface)}"/>` +
|
||||
`<a:ea typeface="${escapeXmlAttr(fonts.eastAsia ?? '')}"/><a:cs typeface=""/></${tag}>`
|
||||
@@ -192,16 +209,16 @@ export function buildThemeXml(fonts: ThemeFonts, colors: ThemeColors): string {
|
||||
`<a:clrScheme name="${escapeXmlAttr(colors.name ?? 'Office')}">` +
|
||||
'<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>' +
|
||||
'<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>' +
|
||||
c('dk2', '44546A') +
|
||||
c('lt2', 'E7E6E6') +
|
||||
c('accent1', '4472C4') +
|
||||
c('accent2', 'ED7D31') +
|
||||
c('accent3', 'A5A5A5') +
|
||||
c('accent4', 'FFC000') +
|
||||
c('accent5', '5B9BD5') +
|
||||
c('accent6', '70AD47') +
|
||||
'<a:hlink><a:srgbClr val="0563C1"/></a:hlink>' +
|
||||
'<a:folHlink><a:srgbClr val="954F72"/></a:folHlink>' +
|
||||
c('dk2') +
|
||||
c('lt2') +
|
||||
c('accent1') +
|
||||
c('accent2') +
|
||||
c('accent3') +
|
||||
c('accent4') +
|
||||
c('accent5') +
|
||||
c('accent6') +
|
||||
`<a:hlink><a:srgbClr val="${DEFAULT_THEME_COLORS.hlink}"/></a:hlink>` +
|
||||
`<a:folHlink><a:srgbClr val="${DEFAULT_THEME_COLORS.folHlink}"/></a:folHlink>` +
|
||||
'</a:clrScheme>' +
|
||||
`<a:fontScheme name="Office">${font('a:majorFont', fonts.major)}${font('a:minorFont', fonts.minor)}</a:fontScheme>` +
|
||||
'<a:fmtScheme name="Office">' +
|
||||
|
||||
@@ -43,8 +43,8 @@ export interface Run {
|
||||
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 */
|
||||
caps?: 'all' | 'small'
|
||||
/** w:caps ('all') / w:smallCaps ('small') display transform, 'none' = explicit off. Display only; saving is kept faithful by rawRPr */
|
||||
caps?: 'all' | 'small' | 'none'
|
||||
/** 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" */
|
||||
@@ -142,6 +142,11 @@ export interface Run {
|
||||
wrap?: ImageWrap
|
||||
offsetXEmu?: number
|
||||
offsetYEmu?: number
|
||||
/** wp:anchor text-wrap distances (EMU; display-only) */
|
||||
wrapDistTopEmu?: number
|
||||
wrapDistBottomEmu?: number
|
||||
wrapDistLeftEmu?: number
|
||||
wrapDistRightEmu?: number
|
||||
/** wp:anchor allowOverlap="0" (display-only collision hint) */
|
||||
noOverlap?: boolean
|
||||
/** picture outline (pic:spPr a:ln solid fill, display-only) */
|
||||
@@ -556,8 +561,8 @@ export interface NoteRun {
|
||||
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'
|
||||
/** w:caps ('all') / w:smallCaps ('small') display transform, 'none' = explicit off */
|
||||
caps?: 'all' | 'small' | 'none'
|
||||
}
|
||||
|
||||
/** One footnote or endnote (display/edit model; separators are preserved separately). */
|
||||
@@ -587,6 +592,10 @@ export interface FieldDisplay {
|
||||
/** display-only metrics of the entry paragraph (direct pPr/run values; Word
|
||||
* sizes TOC lines by them while the style carries nothing) */
|
||||
szHalfPoints?: number
|
||||
/** face of the visible result runs (text fields): drives the line factor */
|
||||
fontFamily?: string
|
||||
/** explicit paragraph alignment (text fields): overrides the doc default */
|
||||
align?: 'left' | 'center' | 'right'
|
||||
lineRule?: 'auto' | 'atLeast' | 'exact'
|
||||
lineRawTwips?: number
|
||||
lineSpacing?: number
|
||||
@@ -608,6 +617,16 @@ export interface ChartSeries {
|
||||
name?: string
|
||||
/** cached numeric values by category position; null = gap in the cache */
|
||||
values: (number | null)[]
|
||||
/** explicit series fill (c:ser/c:spPr solid fill), hex without '#' */
|
||||
color?: string
|
||||
/** explicit per-point fills (c:dPt), e.g. pie slice colors; sparse by point index */
|
||||
pointColors?: (string | null)[]
|
||||
/** scatter/bubble: numeric x of each point (c:xVal) */
|
||||
xValues?: (number | null)[]
|
||||
/** bubble: point sizes (c:bubbleSize) */
|
||||
sizes?: (number | null)[]
|
||||
/** scatter: connect the points (c:scatterStyle line*, unless the series line is a:noFill) */
|
||||
line?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -619,13 +638,19 @@ export interface ChartSeries {
|
||||
export interface ChartDisplay {
|
||||
/** zip path of the chart part this model was read from */
|
||||
partPath: string
|
||||
kind: 'bar' | 'line' | 'pie' | 'area' | 'other'
|
||||
kind: 'bar' | 'line' | 'pie' | 'area' | 'scatter' | 'bubble' | 'other'
|
||||
/** bar charts: c:barDir="bar" (horizontal bars); default is column direction */
|
||||
horizontal?: boolean
|
||||
/** c:grouping: series stack per category (percentStacked normalizes each category to 100%) */
|
||||
grouping?: 'stacked' | 'percentStacked'
|
||||
/** line charts: draw point markers (c:marker) */
|
||||
markers?: boolean
|
||||
/** chart title; undefined when the chart has no title part (then not editable) */
|
||||
title?: string
|
||||
categories: string[]
|
||||
series: ChartSeries[]
|
||||
/** series color cycle from the chart style + theme accents (hex, no '#'); absent = Office default */
|
||||
palette?: string[]
|
||||
/** display size (from wp:extent), editable via the corner resize handle */
|
||||
widthPx?: number
|
||||
heightPx?: number
|
||||
@@ -736,6 +761,8 @@ export interface TableCell {
|
||||
/** per nested table: how many cell paragraphs precede it (reading-order anchor); absent = after all paragraphs */
|
||||
nestedTableAnchors?: number[]
|
||||
colSpan?: number
|
||||
/** display-only placeholder spanning a row's w:gridBefore/w:gridAfter columns (no borders/fill, not written back as w:tc) */
|
||||
gridGap?: boolean
|
||||
/** 'restart' opens a vertical merge, 'continue' is a merged-away cell */
|
||||
vMerge?: 'restart' | 'continue'
|
||||
/** cell shading fill, hex without '#' (w:shd w:fill) */
|
||||
@@ -759,6 +786,18 @@ export interface TableCell {
|
||||
cellRevision?: { kind: 'ins' | 'del' } & RevisionInfo
|
||||
}
|
||||
|
||||
export type TableAutoFitMode = 'contents' | 'window' | 'fixed'
|
||||
|
||||
/** Word's Table Style Options (w:tblLook). */
|
||||
export interface TableLook {
|
||||
firstRow: boolean
|
||||
lastRow: boolean
|
||||
firstColumn: boolean
|
||||
lastColumn: boolean
|
||||
bandedRows: boolean
|
||||
bandedColumns: boolean
|
||||
}
|
||||
|
||||
/** Editable interchange model of a table block, extracted from or generated to OOXML. */
|
||||
export interface TableModel {
|
||||
rows: TableCell[][]
|
||||
@@ -770,8 +809,14 @@ export interface TableModel {
|
||||
widthPct?: number
|
||||
/** autofit layout (no fixed w:tblLayout; w:tblW auto/absent/zero or pct): display may widen columns to min-content */
|
||||
autoLayout?: boolean
|
||||
/** editable Word AutoFit mode (w:tblLayout + w:tblW) */
|
||||
autoFit?: TableAutoFitMode
|
||||
/** table-level default cell margins (w:tblCellMar) */
|
||||
cellMarTwips?: CellMargins
|
||||
/** w:tblCellSpacing (twips, half the gap between adjacent cells); cells render boxed with gaps */
|
||||
cellSpacingTwips?: number
|
||||
/** table shading (tblPr w:shd), hex without '#'; shows through transparent cells and cell-spacing gaps */
|
||||
fill?: string
|
||||
/** table-level borders (w:tblBorders); undefined = not declared (default gridlines apply) */
|
||||
borders?: TableBorders
|
||||
/** table horizontal alignment (tblPr w:jc); default left */
|
||||
@@ -788,19 +833,25 @@ export interface TableModel {
|
||||
yTwips: number
|
||||
horzAnchor?: 'page' | 'margin' | 'text'
|
||||
vertAnchor?: 'page' | 'margin' | 'text'
|
||||
/** gap between the floating table and surrounding text (w:*FromText) */
|
||||
distanceTwips?: CellMargins
|
||||
}
|
||||
/** floating table (w:tblpPr): text wraps around the side opposite the anchor */
|
||||
floatSide?: 'left' | 'right'
|
||||
floatSide?: 'left' | 'right' | null
|
||||
/** per-row height (twips, w:trHeight; null = not set), aligned with rows */
|
||||
rowHeightsTwips?: Array<number | null>
|
||||
/** per-row height rule (w:trHeight w:hRule; absent/legacy models = atLeast), aligned with rows */
|
||||
rowHeightRules?: Array<'atLeast' | 'exact' | null>
|
||||
/** per-row repeat-as-header flag (w:trPr/w:tblHeader), aligned with rows */
|
||||
repeatHeaderRows?: Array<boolean | null>
|
||||
/** per-row raw <w:trPr>…</w:trPr> bytes (passed through verbatim), aligned with rows */
|
||||
rawTrPrs?: Array<string | null>
|
||||
/** row-level revisions (trPr w:ins/w:del = inserted/deleted row), aligned with rows */
|
||||
rowRevisions?: Array<({ kind: 'ins' | 'del' } & RevisionInfo) | null>
|
||||
/** table style reference (w:tblStyle w:val); '' = explicitly no style, undefined = leave as-is */
|
||||
tblStyleId?: string
|
||||
/** conditional table-style switches (w:tblLook) */
|
||||
tableLook?: TableLook
|
||||
/** RTL table (tblPr w:bidiVisual): columns display right to left */
|
||||
bidiVisual?: boolean
|
||||
}
|
||||
@@ -956,10 +1007,23 @@ export interface Block {
|
||||
imageCrop?: { l: number; t: number; r: number; b: number }
|
||||
/** fill placement (a:stretch/a:fillRect) as fractions of the shape box; negative = bleed (display-only) */
|
||||
imageFillRect?: { l: number; t: number; r: number; b: number }
|
||||
/** Preserved whitespace before an inline picture and its paragraph indents (display-only). */
|
||||
imageLeadingText?: string
|
||||
imageLeadingFont?: string
|
||||
imageLeadingExplicitSpaceWidthPx?: number
|
||||
imageLeadingImplicitSpaceCount?: number
|
||||
imageParagraphIndentLeft?: number
|
||||
imageParagraphIndentRight?: number
|
||||
imageParagraphIndentFirstLine?: number
|
||||
/** paragraph alignment of the image (w:jc) */
|
||||
imageAlign?: 'left' | 'center' | 'right'
|
||||
/** text wrapping of a floating image (wp:anchor); absent = inline (in line with text) */
|
||||
imageWrap?: ImageWrap
|
||||
/** wp:anchor text-wrap distances (EMU; display-only) */
|
||||
imageWrapDistTopEmu?: number
|
||||
imageWrapDistBottomEmu?: number
|
||||
imageWrapDistLeftEmu?: number
|
||||
imageWrapDistRightEmu?: number
|
||||
/**
|
||||
* stacking rank of a floating image among overlapping anchors, decoded from
|
||||
* wp:anchor relativeHeight minus the 251658240 base (0 when at/below base).
|
||||
@@ -984,6 +1048,8 @@ export interface Block {
|
||||
*/
|
||||
imageOffsetXEmu?: number
|
||||
imageOffsetYEmu?: number
|
||||
/** wp:anchor locked="1": moving the picture must not change its anchor paragraph */
|
||||
imageAnchorLocked?: boolean
|
||||
/** margin-relative wp:align of a floating image (Word position-gallery presets) */
|
||||
imagePosH?: 'left' | 'center' | 'right'
|
||||
imagePosV?: 'top' | 'center' | 'bottom'
|
||||
@@ -1246,8 +1312,8 @@ export interface StyleDisplay {
|
||||
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'
|
||||
/** w:caps ('all') / w:smallCaps ('small') display transform, 'none' = explicit off */
|
||||
caps?: 'all' | 'small' | 'none'
|
||||
/** multiple of single line spacing (w:spacing w:line, lineRule auto) */
|
||||
lineSpacing?: number
|
||||
/** F1: lineRule for accurate height calculation */
|
||||
@@ -1269,6 +1335,8 @@ export interface StyleDisplay {
|
||||
keepLines?: boolean
|
||||
/** pageBreakBefore from style definition */
|
||||
pageBreakBefore?: boolean
|
||||
/** w:suppressAutoHyphens from style definition (tri-state: explicit off overrides the chain) */
|
||||
suppressAutoHyphens?: boolean
|
||||
/** F1: contextualSpacing from style definition */
|
||||
contextualSpacing?: boolean
|
||||
/** paragraph alignment from the style (w:pPr w:jc) */
|
||||
@@ -1364,6 +1432,8 @@ export interface DocDefaults {
|
||||
spaceAfterAuto?: boolean
|
||||
/** rPrDefault w:lang w:val (BCP-47) — hyphenation/locale of the body text */
|
||||
lang?: string
|
||||
/** pPrDefault w:suppressAutoHyphens — every paragraph opts out of w:autoHyphenation */
|
||||
suppressAutoHyphens?: boolean
|
||||
}
|
||||
|
||||
/** word/settings.xml w:documentProtection (only the editing restriction subset). */
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import JSZip from 'jszip'
|
||||
import { needsOoxmlNormalization, normalizeOoxmlXml } from './ooxml-normalize'
|
||||
|
||||
const EOCD_SIG = 0x06054b50
|
||||
const CENTRAL_SIG = 0x02014b50
|
||||
@@ -49,7 +50,71 @@ function neutralizeUnicodePathFields(bytes: Uint8Array): Uint8Array {
|
||||
return out ?? bytes
|
||||
}
|
||||
|
||||
const MAX_ZIP_PARTS = 10000
|
||||
const MAX_PART_UNCOMPRESSED_BYTES = 512 * 1024 * 1024
|
||||
const MAX_TOTAL_UNCOMPRESSED_BYTES = 1.5 * 1024 * 1024 * 1024
|
||||
|
||||
/**
|
||||
* Reject zip bombs before any part is inflated, using the declared
|
||||
* uncompressed sizes from the central directory (JSZip keeps them in
|
||||
* the lazy `_data` compressed object).
|
||||
*/
|
||||
export function assertZipWithinLimits(zip: JSZip): void {
|
||||
const files = Object.values(zip.files).filter((f) => !f.dir)
|
||||
if (files.length > MAX_ZIP_PARTS) {
|
||||
throw new Error(`docx rejected: ${files.length} parts exceeds the ${MAX_ZIP_PARTS} limit`)
|
||||
}
|
||||
let total = 0
|
||||
for (const file of files) {
|
||||
const size =
|
||||
(file as unknown as { _data?: { uncompressedSize?: number } })._data?.uncompressedSize ?? 0
|
||||
if (size > MAX_PART_UNCOMPRESSED_BYTES) {
|
||||
throw new Error(
|
||||
`docx rejected: part ${file.name} declares ${size} uncompressed bytes ` +
|
||||
`(limit ${MAX_PART_UNCOMPRESSED_BYTES})`,
|
||||
)
|
||||
}
|
||||
if (size > 0) total += size
|
||||
}
|
||||
if (total > MAX_TOTAL_UNCOMPRESSED_BYTES) {
|
||||
throw new Error(
|
||||
`docx rejected: total uncompressed size ${total} exceeds the ` +
|
||||
`${MAX_TOTAL_UNCOMPRESSED_BYTES} limit`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// The gate parts carry the strict / non-canonical-prefix markers whenever the
|
||||
// package needs normalizing (strict packages are strict in document.xml and
|
||||
// their rels; prefix oddities live in document.xml).
|
||||
const NORMALIZE_GATE_PARTS = ['word/document.xml', 'word/_rels/document.xml.rels', '_rels/.rels']
|
||||
|
||||
/**
|
||||
* ISO Strict OOXML and non-canonical namespace prefixes are normalized here,
|
||||
* at the single zip entry point, so parseDocx offsets and saveDocx patches
|
||||
* operate on identical part text (and saved packages come out transitional).
|
||||
*/
|
||||
async function normalizeOoxmlParts(zip: JSZip): Promise<void> {
|
||||
let needed = false
|
||||
for (const path of NORMALIZE_GATE_PARTS) {
|
||||
const file = zip.file(path)
|
||||
if (file && needsOoxmlNormalization(await file.async('string'))) {
|
||||
needed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!needed) return
|
||||
for (const file of Object.values(zip.files)) {
|
||||
if (file.dir || !/\.(xml|rels)$/i.test(file.name)) continue
|
||||
const xml = await file.async('string')
|
||||
if (needsOoxmlNormalization(xml)) zip.file(file.name, normalizeOoxmlXml(xml))
|
||||
}
|
||||
}
|
||||
|
||||
/** Load a docx/zip resolving part names the way Word does. */
|
||||
export async function loadDocxZip(bytes: Uint8Array): Promise<JSZip> {
|
||||
return JSZip.loadAsync(neutralizeUnicodePathFields(bytes))
|
||||
const zip = await JSZip.loadAsync(neutralizeUnicodePathFields(bytes))
|
||||
assertZipWithinLimits(zip)
|
||||
await normalizeOoxmlParts(zip)
|
||||
return zip
|
||||
}
|
||||
|
||||
@@ -234,9 +234,9 @@ describe('styleUpserts style write-back', () => {
|
||||
describe('toggle-off (w:val="0") overrides inherited formatting', () => {
|
||||
const TOGGLE_STYLES =
|
||||
'<w:style w:type="paragraph" w:styleId="BoldBase"><w:name w:val="Bold Base"/>' +
|
||||
'<w:rPr><w:b/><w:i/><w:strike/><w:u w:val="single"/></w:rPr></w:style>' +
|
||||
'<w:rPr><w:b/><w:i/><w:strike/><w:u w:val="single"/><w:smallCaps/></w:rPr></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="PlainChild"><w:name w:val="Plain Child"/><w:basedOn w:val="BoldBase"/>' +
|
||||
'<w:rPr><w:b w:val="0"/><w:i w:val="false"/><w:strike w:val="0"/><w:u w:val="none"/></w:rPr></w:style>' +
|
||||
'<w:rPr><w:b w:val="0"/><w:i w:val="false"/><w:strike w:val="0"/><w:u w:val="none"/><w:smallCaps w:val="0"/></w:rPr></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="GrandChild"><w:name w:val="Grand Child"/><w:basedOn w:val="PlainChild"/></w:style>'
|
||||
|
||||
it('records explicit off in the style display and through basedOn chains', async () => {
|
||||
@@ -251,23 +251,26 @@ describe('toggle-off (w:val="0") overrides inherited formatting', () => {
|
||||
italic: true,
|
||||
strike: true,
|
||||
underline: true,
|
||||
caps: 'small',
|
||||
})
|
||||
const child = doc.styles.get('PlainChild')!.display!
|
||||
expect(child.bold).toBe(false)
|
||||
expect(child.italic).toBe(false)
|
||||
expect(child.strike).toBe(false)
|
||||
expect(child.underline).toBe(false)
|
||||
expect(child.caps).toBe('none')
|
||||
// the grandchild inherits the explicit off, not the grandparent's on
|
||||
const grand = doc.styles.get('GrandChild')!.display!
|
||||
expect(grand.bold).toBe(false)
|
||||
expect(grand.underline).toBe(false)
|
||||
expect(grand.caps).toBe('none')
|
||||
})
|
||||
|
||||
it('records explicit off on runs as false, absent as undefined', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:rPr><w:b w:val="0"/><w:u w:val="none"/></w:rPr><w:t>off</w:t></w:r>' +
|
||||
'<w:p><w:r><w:rPr><w:b w:val="0"/><w:u w:val="none"/><w:caps w:val="0"/></w:rPr><w:t>off</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:b/></w:rPr><w:t>on</w:t></w:r>' +
|
||||
'<w:r><w:t>unset</w:t></w:r></w:p>',
|
||||
}),
|
||||
@@ -275,8 +278,10 @@ describe('toggle-off (w:val="0") overrides inherited formatting', () => {
|
||||
const runs = doc.blocks[0].runs!
|
||||
expect(runs[0].bold).toBe(false)
|
||||
expect(runs[0].underline).toBe(false)
|
||||
expect(runs[0].caps).toBe('none')
|
||||
expect(runs[1].bold).toBe(true)
|
||||
expect(runs[2].bold).toBeUndefined()
|
||||
expect(runs[2].underline).toBeUndefined()
|
||||
expect(runs[2].caps).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseChartPartXml } from '../src/index'
|
||||
import type { ThemeColors } from '../src/types'
|
||||
|
||||
const THEME: ThemeColors = {
|
||||
dk1: '000000',
|
||||
lt1: 'FFFFFF',
|
||||
accent1: '4F81BD',
|
||||
accent2: 'C0504D',
|
||||
accent3: '9BBB59',
|
||||
accent4: '8064A2',
|
||||
accent5: '4BACC6',
|
||||
accent6: 'F79646',
|
||||
}
|
||||
|
||||
const chartSpace = (inner: string, pre = '') =>
|
||||
'<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" ' +
|
||||
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
|
||||
'xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" ' +
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
|
||||
`${pre}<c:chart><c:plotArea><c:layout/>${inner}</c:plotArea></c:chart></c:chartSpace>`
|
||||
|
||||
const numCache = (tag: string, values: (number | string)[], fmt = 'General') =>
|
||||
`<c:${tag}><c:numRef><c:f>S!$A$1</c:f><c:numCache><c:formatCode>${fmt}</c:formatCode>` +
|
||||
`<c:ptCount val="${values.length}"/>` +
|
||||
values.map((v, i) => `<c:pt idx="${i}"><c:v>${v}</c:v></c:pt>`).join('') +
|
||||
`</c:numCache></c:numRef></c:${tag}>`
|
||||
|
||||
const strCache = (tag: string, values: string[]) =>
|
||||
`<c:${tag}><c:strRef><c:f>S!$A$1</c:f><c:strCache><c:ptCount val="${values.length}"/>` +
|
||||
values.map((v, i) => `<c:pt idx="${i}"><c:v>${v}</c:v></c:pt>`).join('') +
|
||||
`</c:strCache></c:strRef></c:${tag}>`
|
||||
|
||||
const barSer = (i: number, values: number[], extra = '') =>
|
||||
`<c:ser><c:idx val="${i}"/><c:order val="${i}"/>` +
|
||||
`${strCache('tx', [`Series ${i + 1}`])}${extra}` +
|
||||
`${strCache('cat', ['A', 'B'])}${numCache('val', values)}</c:ser>`
|
||||
|
||||
describe('parseChartPartXml grouping and colors', () => {
|
||||
const bar = (grouping: string, extra = '') =>
|
||||
chartSpace(
|
||||
`<c:barChart><c:barDir val="col"/><c:grouping val="${grouping}"/>` +
|
||||
`${barSer(0, [1, 2], extra)}${barSer(1, [3, 4])}</c:barChart>`,
|
||||
)
|
||||
|
||||
it('keeps stacked / percentStacked grouping and drops clustered', () => {
|
||||
expect(parseChartPartXml(bar('stacked'), 'p')!.grouping).toBe('stacked')
|
||||
expect(parseChartPartXml(bar('percentStacked'), 'p')!.grouping).toBe('percentStacked')
|
||||
expect(parseChartPartXml(bar('clustered'), 'p')!.grouping).toBeUndefined()
|
||||
})
|
||||
|
||||
it('reads explicit series solid fills, resolving schemeClr through the theme', () => {
|
||||
const srgb = '<c:spPr><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></c:spPr>'
|
||||
expect(parseChartPartXml(bar('clustered', srgb), 'p')!.series[0].color).toBe('FF0000')
|
||||
const scheme = '<c:spPr><a:solidFill><a:schemeClr val="accent3"/></a:solidFill></c:spPr>'
|
||||
expect(parseChartPartXml(bar('clustered', scheme), 'p', THEME)!.series[0].color).toBe('9BBB59')
|
||||
// without a theme the scheme reference cannot resolve
|
||||
expect(parseChartPartXml(bar('clustered', scheme), 'p')!.series[0].color).toBeUndefined()
|
||||
})
|
||||
|
||||
it('darkens lumMod-modified scheme colors', () => {
|
||||
const mod =
|
||||
'<c:spPr><a:solidFill><a:schemeClr val="accent1"><a:lumMod val="60000"/></a:schemeClr>' +
|
||||
'</a:solidFill></c:spPr>'
|
||||
const color = parseChartPartXml(bar('clustered', mod), 'p', THEME)!.series[0].color!
|
||||
const lum = (hex: string) =>
|
||||
[0, 2, 4].reduce((a, i) => a + parseInt(hex.slice(i, i + 2), 16), 0)
|
||||
expect(lum(color)).toBeLessThan(lum('4F81BD'))
|
||||
})
|
||||
|
||||
it('collects c:dPt point fills sparsely by index', () => {
|
||||
const dPt =
|
||||
'<c:dPt><c:idx val="1"/><c:spPr><a:solidFill><a:srgbClr val="00FF00"/></a:solidFill>' +
|
||||
'</c:spPr></c:dPt>'
|
||||
const display = parseChartPartXml(bar('clustered', dPt), 'p')!
|
||||
expect(display.series[0].pointColors).toEqual([null, '00FF00'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseChartPartXml chart-style palette', () => {
|
||||
const clustered = `<c:barChart><c:barDir val="col"/>${barSer(0, [1, 2])}</c:barChart>`
|
||||
|
||||
it('theme accents drive the default cycle', () => {
|
||||
expect(parseChartPartXml(chartSpace(clustered), 'p', THEME)!.palette).toEqual([
|
||||
'4F81BD',
|
||||
'C0504D',
|
||||
'9BBB59',
|
||||
'8064A2',
|
||||
'4BACC6',
|
||||
'F79646',
|
||||
])
|
||||
expect(parseChartPartXml(chartSpace(clustered), 'p')!.palette).toBeUndefined()
|
||||
})
|
||||
|
||||
it('style column 1 is grayscale, also via the c14 AlternateContent form', () => {
|
||||
const direct = parseChartPartXml(chartSpace(clustered, '<c:style val="1"/>'), 'p', THEME)!
|
||||
expect(direct.palette![0]).toBe('595959')
|
||||
const alt =
|
||||
'<mc:AlternateContent><mc:Choice Requires="c14" ' +
|
||||
'xmlns:c14="http://schemas.microsoft.com/office/drawing/2007/8/2/chart">' +
|
||||
'<c14:style val="101"/></mc:Choice><mc:Fallback><c:style val="1"/></mc:Fallback>' +
|
||||
'</mc:AlternateContent>'
|
||||
expect(parseChartPartXml(chartSpace(clustered, alt), 'p', THEME)!.palette![0]).toBe('595959')
|
||||
})
|
||||
|
||||
it('single-accent columns lead with their accent', () => {
|
||||
const display = parseChartPartXml(chartSpace(clustered, '<c:style val="29"/>'), 'p', THEME)!
|
||||
expect(display.palette![0]).toBe('9BBB59')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseChartPartXml scatter and bubble', () => {
|
||||
it('reads x/y pairs, date category texts and the noFill line suppression', () => {
|
||||
const ser =
|
||||
'<c:ser><c:idx val="0"/><c:order val="0"/>' +
|
||||
strCache('tx', ['S1']) +
|
||||
'<c:spPr><a:ln w="28575"><a:noFill/></a:ln></c:spPr>' +
|
||||
numCache('xVal', [37377, 37408], 'm/d/yyyy') +
|
||||
numCache('yVal', [55, 57]) +
|
||||
'</c:ser>'
|
||||
const xml = chartSpace(
|
||||
`<c:scatterChart><c:scatterStyle val="lineMarker"/>${ser}</c:scatterChart>`,
|
||||
)
|
||||
const display = parseChartPartXml(xml, 'p')!
|
||||
expect(display.kind).toBe('scatter')
|
||||
expect(display.markers).toBe(true)
|
||||
expect(display.categories).toEqual(['5/1/2002', '6/1/2002'])
|
||||
expect(display.series[0].values).toEqual([55, 57])
|
||||
expect(display.series[0].xValues).toEqual([37377, 37408])
|
||||
expect(display.series[0].line).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the line for lineMarker series without noFill', () => {
|
||||
const ser =
|
||||
`<c:ser><c:idx val="0"/><c:order val="0"/>${numCache('xVal', [1, 2])}` +
|
||||
`${numCache('yVal', [3, 4])}</c:ser>`
|
||||
const xml = chartSpace(
|
||||
`<c:scatterChart><c:scatterStyle val="lineMarker"/>${ser}</c:scatterChart>`,
|
||||
)
|
||||
expect(parseChartPartXml(xml, 'p')!.series[0].line).toBe(true)
|
||||
})
|
||||
|
||||
it('names a single-series auto title after the series', () => {
|
||||
const ser =
|
||||
`<c:ser><c:idx val="0"/><c:order val="0"/>${strCache('tx', ['Y-Values'])}` +
|
||||
`${numCache('xVal', [1, 2])}${numCache('yVal', [3, 4])}</c:ser>`
|
||||
const xml = chartSpace(`<c:bubbleChart>${ser}</c:bubbleChart>`).replace(
|
||||
'<c:chart>',
|
||||
'<c:chart><c:title/>',
|
||||
)
|
||||
expect(parseChartPartXml(xml, 'p')!.title).toBe('Y-Values')
|
||||
})
|
||||
|
||||
it('reads bubble sizes and trims raw double x texts', () => {
|
||||
const ser =
|
||||
'<c:ser><c:idx val="0"/><c:order val="0"/>' +
|
||||
strCache('tx', ['Y-Values']) +
|
||||
numCache('xVal', ['0.70000000000000062', 1.8]) +
|
||||
numCache('yVal', [2.7, 3.2]) +
|
||||
numCache('bubbleSize', [10, 4]) +
|
||||
'</c:ser>'
|
||||
const display = parseChartPartXml(chartSpace(`<c:bubbleChart>${ser}</c:bubbleChart>`), 'p')!
|
||||
expect(display.kind).toBe('bubble')
|
||||
expect(display.categories).toEqual(['0.7', '1.8'])
|
||||
expect(display.series[0].sizes).toEqual([10, 4])
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseChartexPartXml leniency', () => {
|
||||
it('parses a waterfall whose cx:chartData was renamed (unknown-element corpus)', () => {
|
||||
const xml =
|
||||
'<cx:chartSpace xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" ' +
|
||||
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">' +
|
||||
'<cx:chartDataIntentionallyChanged><cx:data id="0">' +
|
||||
'<cx:numDim type="val"><cx:f>S!$A$2:$A$4</cx:f><cx:lvl ptCount="3">' +
|
||||
'<cx:pt idx="0">100</cx:pt><cx:pt idx="1">-40</cx:pt><cx:pt idx="2">60</cx:pt>' +
|
||||
'</cx:lvl></cx:numDim></cx:data></cx:chartDataIntentionallyChanged>' +
|
||||
'<cx:chart><cx:plotArea><cx:plotAreaRegion>' +
|
||||
'<cx:series layoutId="waterfall"><cx:tx><cx:txData><cx:v>Series1</cx:v></cx:txData></cx:tx>' +
|
||||
'<cx:dataId val="0"/></cx:series>' +
|
||||
'</cx:plotAreaRegion></cx:plotArea></cx:chart></cx:chartSpace>'
|
||||
const display = parseChartPartXml(xml, 'word/charts/chartEx1.xml')!
|
||||
expect(display.kind).toBe('bar')
|
||||
expect(display.series[0]).toEqual({ name: 'Series1', values: [100, -40, 60] })
|
||||
})
|
||||
})
|
||||
@@ -24,6 +24,19 @@ const TOC_ENTRY_PARAGRAPH =
|
||||
const FIELD_END_PAGEBREAK_PARAGRAPH =
|
||||
'<w:p><w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:br w:type="page"/></w:r></w:p>'
|
||||
|
||||
// paste artifact from Word web copy: an INCLUDEPICTURE field with a dead local
|
||||
// path sandwiched between styled text runs (public issue #118 demo.docx shape)
|
||||
const RPR =
|
||||
'<w:rPr><w:rFonts w:ascii="\u5b8b\u4f53" w:eastAsia="\u5b8b\u4f53"/><w:sz w:val="24"/></w:rPr>'
|
||||
const INCLUDEPICTURE_PARAGRAPH =
|
||||
`<w:p><w:pPr><w:jc w:val="left"/>${RPR}</w:pPr>` +
|
||||
`<w:r>${RPR}<w:t>\u9636\u8d70\u5230\u6cb3</w:t></w:r>` +
|
||||
`<w:r>${RPR}<w:t xml:space="preserve"> </w:t></w:r>` +
|
||||
`<w:r>${RPR}<w:fldChar w:fldCharType="begin"/></w:r>` +
|
||||
`<w:r>${RPR}<w:instrText xml:space="preserve"> INCLUDEPICTURE "/tmp/x.jpeg" \\* MERGEFORMATINET </w:instrText></w:r>` +
|
||||
`<w:r>${RPR}<w:fldChar w:fldCharType="end"/></w:r>` +
|
||||
`<w:r>${RPR}<w:t>\u5cb8\u8fb9</w:t></w:r></w:p>`
|
||||
|
||||
const PAGE_FIELD_PARAGRAPH =
|
||||
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r>' +
|
||||
@@ -56,6 +69,33 @@ describe('field paragraph display model', () => {
|
||||
expect(doc.blocks[0].runs?.[0]).toMatchObject({ text: '- 8 -', instrField: 'PAGE' })
|
||||
})
|
||||
|
||||
it('a resultless INCLUDEPICTURE text field keeps spaces and run metrics (public issue #118)', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: INCLUDEPICTURE_PARAGRAPH }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('passthrough')
|
||||
expect(block.fieldDisplay).toMatchObject({
|
||||
kind: 'text',
|
||||
left: '\u9636\u8d70\u5230\u6cb3 \u5cb8\u8fb9',
|
||||
szHalfPoints: 24,
|
||||
fontFamily: '\u5b8b\u4f53',
|
||||
align: 'left',
|
||||
})
|
||||
})
|
||||
|
||||
it('a text field with an explicit line multiple carries the spacing', async () => {
|
||||
const xml = INCLUDEPICTURE_PARAGRAPH.replace(
|
||||
'<w:pPr><w:jc w:val="left"/>',
|
||||
'<w:pPr><w:spacing w:line="360" w:lineRule="auto"/><w:jc w:val="left"/>',
|
||||
)
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
expect(doc.blocks[0].fieldDisplay).toMatchObject({
|
||||
kind: 'text',
|
||||
lineRule: 'auto',
|
||||
lineRawTwips: 360,
|
||||
lineSpacing: 1.5,
|
||||
})
|
||||
})
|
||||
|
||||
it('TOC entry carries its hyperlink anchor for click-to-jump', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: TOC_ENTRY_PARAGRAPH }))
|
||||
expect(doc.blocks[0].fieldDisplay?.anchor).toBe('_Toc1')
|
||||
@@ -341,3 +381,51 @@ describe('FORMCHECKBOX form fields', () => {
|
||||
expect(doc.blocks[0].type).toBe('passthrough')
|
||||
})
|
||||
})
|
||||
|
||||
// Mail-merge label/business-card layout: the visible text lives entirely in
|
||||
// field results inside table cells (complex MERGEFIELD runs and fldSimple).
|
||||
const MERGE_CELL_PARAGRAPH =
|
||||
'<w:p>' +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> MERGEFIELD Vorname </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
|
||||
'<w:r><w:rPr><w:noProof/></w:rPr><w:t>Erika</w:t></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
|
||||
'<w:r><w:t xml:space="preserve"> </w:t></w:r>' +
|
||||
'<w:fldSimple w:instr=" MERGEFIELD Nachname ">' +
|
||||
'<w:r><w:rPr><w:noProof/></w:rPr><w:t>Mustermann</w:t></w:r>' +
|
||||
'</w:fldSimple>' +
|
||||
'</w:p>'
|
||||
|
||||
const NEXT_FIELD_PARAGRAPH =
|
||||
'<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> NEXT </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
|
||||
|
||||
function cellTable(content: string): string {
|
||||
return (
|
||||
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr>' +
|
||||
content +
|
||||
'</w:tc></w:tr></w:tbl>'
|
||||
)
|
||||
}
|
||||
|
||||
describe('field cached results in table cells', () => {
|
||||
it('complex MERGEFIELD and fldSimple results stay visible as cell runs', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: cellTable(MERGE_CELL_PARAGRAPH) }))
|
||||
const cell = doc.blocks[0].table!.rows[0][0]
|
||||
const text = (cell.richParas?.[0]?.runs ?? []).map((r) => r.text).join('')
|
||||
expect(text).toBe('Erika Mustermann')
|
||||
// instruction text must not leak into the visible runs
|
||||
expect(text).not.toContain('MERGEFIELD')
|
||||
})
|
||||
|
||||
it('a resultless field (NEXT) contributes no text', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: cellTable(NEXT_FIELD_PARAGRAPH) }))
|
||||
const cell = doc.blocks[0].table!.rows[0][0]
|
||||
const text = (cell.richParas?.[0]?.runs ?? []).map((r) => r.text).join('')
|
||||
expect(text).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
import { buildDocx, IMAGE_PARAGRAPH_XML } from './helpers/build-docx'
|
||||
|
||||
/** overwrite the declared uncompressed size of every central-directory record */
|
||||
function patchCentralSizes(bytes: Uint8Array, size: number): Uint8Array {
|
||||
@@ -95,3 +95,21 @@ describe('malformed XML degrades instead of failing the document', () => {
|
||||
expect(doc.blocks[0].runs?.[0]?.text).toBe('hello')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DOCTYPE prologue in a relationships part', () => {
|
||||
it('opens the document and still resolves rels (external entity never fetched)', async () => {
|
||||
const zip = await JSZip.loadAsync(
|
||||
await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML + PLAIN_PARA, withImage: true }),
|
||||
)
|
||||
const rels = await zip.file('word/_rels/document.xml.rels')!.async('string')
|
||||
const poisoned = rels
|
||||
.replace('?>', '?>\n<!DOCTYPE test [\n<!ENTITY test SYSTEM "file:///dev/random">\n]>')
|
||||
.replace('<Relationship Id="rId10"', '&test;<Relationship Id="rId10"')
|
||||
expect(poisoned).toContain('<!DOCTYPE')
|
||||
zip.file('word/_rels/document.xml.rels', poisoned)
|
||||
const doc = await parseDocx(await zip.generateAsync({ type: 'uint8array' }))
|
||||
expect(doc.blocks[0].type).toBe('image')
|
||||
expect(doc.blocks[0].imageDataUrl).toMatch(/^data:image\/png;base64,/)
|
||||
expect(doc.blocks[1].runs?.[0]?.text).toBe('hello')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -115,6 +115,48 @@ describe('image text wrap (wp:anchor)', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('floats a wide bothSides picture right when its center passes mid-body (public issue #118)', async () => {
|
||||
// left edge before the midline, but the 3in-wide body fills the right half
|
||||
const xml = ANCHOR_SQUARE_RIGHT_XML.replace(
|
||||
'<wp:positionH relativeFrom="column"><wp:align>right</wp:align></wp:positionH>',
|
||||
'<wp:positionH relativeFrom="column"><wp:posOffset>2407073</wp:posOffset></wp:positionH>',
|
||||
).replace('<wp:extent cx="914400" cy="914400"/>', '<wp:extent cx="2851200" cy="2138400"/>')
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml, withImage: true }))
|
||||
expect(doc.blocks[0].imageWrap).toBe('square-right')
|
||||
expect(doc.blocks[0].imageOffsetXEmu).toBe(2407073)
|
||||
expect(doc.blocks[0].imageWrapDistTopEmu).toBe(0)
|
||||
expect(doc.blocks[0].imageWrapDistBottomEmu).toBe(0)
|
||||
expect(doc.blocks[0].imageWrapDistLeftEmu).toBe(114300)
|
||||
expect(doc.blocks[0].imageWrapDistRightEmu).toBe(114300)
|
||||
})
|
||||
|
||||
it('keeps leading spaces and first-line indent on an atomic picture block (public issue #118)', async () => {
|
||||
const xml = IMAGE_PARAGRAPH_XML.replace(
|
||||
'<w:p>',
|
||||
'<w:p><w:pPr><w:ind w:firstLine="420"/>' +
|
||||
'<w:rPr><w:rFonts w:eastAsia="SimSun"/><w:sz w:val="24"/></w:rPr></w:pPr>' +
|
||||
'<w:r><w:t xml:space="preserve"> </w:t></w:r>',
|
||||
)
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml, withImage: true }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('image')
|
||||
expect(block.imageLeadingText).toBe(' ')
|
||||
expect(block.imageLeadingFont).toBe('SimSun')
|
||||
expect(block.imageLeadingImplicitSpaceCount).toBe(4)
|
||||
expect(block.imageLeadingExplicitSpaceWidthPx).toBeUndefined()
|
||||
expect(block.imageParagraphIndentFirstLine).toBe(420)
|
||||
expect(block.imageWidthPx).toBe(96)
|
||||
|
||||
const explicit = xml.replace(
|
||||
'<w:r><w:t xml:space="preserve"> </w:t></w:r>',
|
||||
'<w:r><w:rPr><w:sz w:val="24"/></w:rPr>' + '<w:t xml:space="preserve"> </w:t></w:r>',
|
||||
)
|
||||
const explicitBlock = (await parseDocx(await buildDocx({ bodyXml: explicit, withImage: true })))
|
||||
.blocks[0]
|
||||
expect(explicitBlock.imageLeadingExplicitSpaceWidthPx).toBe(32)
|
||||
expect(explicitBlock.imageLeadingImplicitSpaceCount).toBeUndefined()
|
||||
})
|
||||
|
||||
it('converts inline -> square anchor with position and wrap elements', () => {
|
||||
const out = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-left')
|
||||
expect(out).toContain('<wp:anchor')
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* classification used to drop every text run in the paragraph.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/index'
|
||||
import { generateParagraphXml, parseDocx, type GenerateContext } from '../src/index'
|
||||
import { buildDocx, IMAGE_PARAGRAPH_XML } from './helpers/build-docx'
|
||||
|
||||
const INLINE_IMAGE_RUN =
|
||||
@@ -89,3 +89,43 @@ describe('text + inline image mixed paragraphs', () => {
|
||||
expect(doc.blocks[0].imageDataUrl).toMatch(/^data:image\/png;base64,/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('one run carrying several inline drawings', () => {
|
||||
const GEN_CTX: GenerateContext = {
|
||||
headingStyleIds: new Map(),
|
||||
allocateHyperlinkRel: () => 'rId999',
|
||||
}
|
||||
|
||||
const inlineDrawing = (cx: number, cy: number): string =>
|
||||
`<w:drawing><wp:inline><wp:extent cx="${cx}" cy="${cy}"/>` +
|
||||
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
|
||||
'</a:graphicData></a:graphic></wp:inline></w:drawing>'
|
||||
|
||||
it('splits the run so every drawing survives as its own image run', async () => {
|
||||
const bodyXml = `<w:p><w:r><w:rPr></w:rPr>${inlineDrawing(914400, 914400)}${inlineDrawing(457200, 457200)}</w:r></w:p>`
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('paragraph')
|
||||
const imageRuns = block.runs!.filter((r) => r.image)
|
||||
expect(imageRuns).toHaveLength(2)
|
||||
expect(imageRuns.map((r) => r.image?.widthPx)).toEqual([96, 48])
|
||||
// an edit-triggered rebuild must write both pictures back
|
||||
const regen = generateParagraphXml({ type: 'paragraph', runs: block.runs! }, GEN_CTX)
|
||||
expect(regen.match(/<w:drawing>/g)).toHaveLength(2)
|
||||
expect(regen.match(/r:embed="rId10"/g)).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('keeps text between the drawings in document order', async () => {
|
||||
const bodyXml =
|
||||
`<w:p><w:r>${inlineDrawing(914400, 914400)}` +
|
||||
`<w:t>mid</w:t>${inlineDrawing(457200, 457200)}</w:r></w:p>`
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
|
||||
const runs = doc.blocks[0].runs!
|
||||
expect(runs.filter((r) => r.image)).toHaveLength(2)
|
||||
expect(runs.map((r) => r.text).join('')).toBe('mid')
|
||||
const regen = generateParagraphXml({ type: 'paragraph', runs }, GEN_CTX)
|
||||
expect(regen.indexOf('mid')).toBeGreaterThan(regen.indexOf('<w:drawing>'))
|
||||
expect(regen.indexOf('mid')).toBeLessThan(regen.lastIndexOf('<w:drawing>'))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -157,3 +157,52 @@ describe('settings.xml layout flags', () => {
|
||||
expect(doc.defaultTabStopTwips).toBe(709)
|
||||
})
|
||||
})
|
||||
|
||||
describe('w:suppressAutoHyphens', () => {
|
||||
const stylesWith = (docDefaultsPPr: string, styleExtra = '') =>
|
||||
XML_DECL +
|
||||
'<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
`<w:docDefaults><w:pPrDefault><w:pPr>${docDefaultsPPr}</w:pPr></w:pPrDefault></w:docDefaults>` +
|
||||
styleExtra +
|
||||
'</w:styles>'
|
||||
|
||||
it('pPrDefault w:suppressAutoHyphens lands on docDefaults', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
extraParts: [settingsPart('<w:autoHyphenation/>')],
|
||||
stylesXml: stylesWith('<w:suppressAutoHyphens/>'),
|
||||
}),
|
||||
)
|
||||
expect(doc.autoHyphenation).toBe(true)
|
||||
expect(doc.docDefaults?.suppressAutoHyphens).toBe(true)
|
||||
})
|
||||
|
||||
it('explicit off at pPrDefault stays unset', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
stylesXml: stylesWith('<w:suppressAutoHyphens w:val="0"/>'),
|
||||
}),
|
||||
)
|
||||
expect(doc.docDefaults?.suppressAutoHyphens).toBeUndefined()
|
||||
})
|
||||
|
||||
it('style-level value is tri-state and survives the basedOn merge', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
stylesXml: stylesWith(
|
||||
'',
|
||||
'<w:style w:type="paragraph" w:styleId="NoHyph"><w:name w:val="NoHyph"/>' +
|
||||
'<w:pPr><w:suppressAutoHyphens/></w:pPr></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="ReHyph"><w:name w:val="ReHyph"/>' +
|
||||
'<w:basedOn w:val="NoHyph"/>' +
|
||||
'<w:pPr><w:suppressAutoHyphens w:val="false"/></w:pPr></w:style>',
|
||||
),
|
||||
}),
|
||||
)
|
||||
expect(doc.styles.get('NoHyph')?.display?.suppressAutoHyphens).toBe(true)
|
||||
expect(doc.styles.get('ReHyph')?.display?.suppressAutoHyphens).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -248,7 +248,12 @@ describe('captions', () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: generateCaptionXml('图', 1, '测试') }))
|
||||
const p = doc.blocks[0]
|
||||
expect(p.type).toBe('passthrough')
|
||||
expect(p.fieldDisplay).toEqual({ kind: 'text', left: '图 1 测试' })
|
||||
expect(p.fieldDisplay).toEqual({
|
||||
kind: 'text',
|
||||
left: '图 1 测试',
|
||||
szHalfPoints: 18,
|
||||
align: 'center',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { needsOoxmlNormalization, normalizeOoxmlXml } from '../src/ooxml-normalize'
|
||||
import { loadDocxZip } from '../src/zip-load'
|
||||
import { parseDocx } from '../src/index'
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||
const W_TRANS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
|
||||
const W_STRICT = 'http://purl.oclc.org/ooxml/wordprocessingml/main'
|
||||
const R_STRICT = 'http://purl.oclc.org/ooxml/officeDocument/relationships'
|
||||
|
||||
async function buildDocxBytes(documentXml: string, relsXml?: string): Promise<Uint8Array> {
|
||||
const zip = new JSZip()
|
||||
zip.file(
|
||||
'[Content_Types].xml',
|
||||
`${XML_DECL}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
|
||||
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
|
||||
'<Default Extension="xml" ContentType="application/xml"/>' +
|
||||
'<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>' +
|
||||
'</Types>',
|
||||
)
|
||||
zip.file(
|
||||
'_rels/.rels',
|
||||
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>' +
|
||||
'</Relationships>',
|
||||
)
|
||||
if (relsXml) zip.file('word/_rels/document.xml.rels', relsXml)
|
||||
zip.file('word/document.xml', documentXml)
|
||||
return zip.generateAsync({ type: 'uint8array' })
|
||||
}
|
||||
|
||||
describe('needsOoxmlNormalization', () => {
|
||||
it('is false for canonical transitional parts', () => {
|
||||
expect(needsOoxmlNormalization(`<w:document xmlns:w="${W_TRANS}"><w:body/></w:document>`)).toBe(
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
it('detects strict URIs and non-canonical prefixes', () => {
|
||||
expect(needsOoxmlNormalization(`<w:document xmlns:w="${W_STRICT}"/>`)).toBe(true)
|
||||
expect(needsOoxmlNormalization(`<fake:document xmlns:fake="${W_TRANS}"/>`)).toBe(true)
|
||||
expect(needsOoxmlNormalization(`<x:a xmlns:x="http://example.com/unrelated"/>`)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('non-canonical prefixes bound to known URIs', () => {
|
||||
it('renames the prefix and its declaration to the canonical one', () => {
|
||||
const out = normalizeOoxmlXml(
|
||||
`<fake:document xmlns:fake="${W_TRANS}"><fake:body>` +
|
||||
'<fake:p fake:rsidR="00A"><fake:r><fake:t>Hi</fake:t></fake:r></fake:p>' +
|
||||
'</fake:body></fake:document>',
|
||||
)
|
||||
expect(out).toContain(`<w:document xmlns:w="${W_TRANS}">`)
|
||||
expect(out).toContain('<w:p w:rsidR="00A"><w:r><w:t>Hi</w:t></w:r></w:p>')
|
||||
expect(out).not.toContain('fake:')
|
||||
})
|
||||
|
||||
it('leaves unrelated namespaces alone even when local names collide', () => {
|
||||
const src = `<f:document xmlns:f="http://example.com/foo"><f:body><f:p/></f:body></f:document>`
|
||||
expect(normalizeOoxmlXml(src)).toBe(src)
|
||||
})
|
||||
|
||||
it('skips the rename when the canonical prefix is taken by another namespace', () => {
|
||||
const src =
|
||||
`<x:document xmlns:x="${W_TRANS}" xmlns:w="http://example.com/other">` +
|
||||
'<x:body><x:p/><w:p/></x:body></x:document>'
|
||||
const out = normalizeOoxmlXml(src)
|
||||
expect(out).toContain('<x:body><x:p/><w:p/></x:body>')
|
||||
})
|
||||
|
||||
it('frees a canonical prefix that is itself renamed away', () => {
|
||||
const a = 'http://schemas.openxmlformats.org/drawingml/2006/main'
|
||||
const out = normalizeOoxmlXml(
|
||||
`<x:document xmlns:w="${a}" xmlns:x="${W_TRANS}">` +
|
||||
'<x:body><x:p><x:r><w:blip/></x:r></x:p></x:body></x:document>',
|
||||
)
|
||||
expect(out).toContain(`<w:document xmlns:a="${a}" xmlns:w="${W_TRANS}">`)
|
||||
expect(out).toContain('<w:body><w:p><w:r><a:blip/></w:r></w:p></w:body>')
|
||||
})
|
||||
|
||||
it('frees a canonical prefix regardless of declaration order', () => {
|
||||
const a = 'http://schemas.openxmlformats.org/drawingml/2006/main'
|
||||
const out = normalizeOoxmlXml(
|
||||
`<x:document xmlns:x="${W_TRANS}" xmlns:w="${a}">` +
|
||||
'<x:body><x:p><x:r><w:blip/></x:r></x:p></x:body></x:document>',
|
||||
)
|
||||
expect(out).toContain(`<w:document xmlns:w="${W_TRANS}" xmlns:a="${a}">`)
|
||||
expect(out).toContain('<w:body><w:p><w:r><a:blip/></w:r></w:p></w:body>')
|
||||
})
|
||||
|
||||
it('drops a duplicate declaration when the canonical binding already exists', () => {
|
||||
const out = normalizeOoxmlXml(
|
||||
`<w:document xmlns:w="${W_TRANS}" xmlns:ns3="${W_TRANS}">` +
|
||||
'<w:body><ns3:p><ns3:r><ns3:t>x</ns3:t></ns3:r></ns3:p></w:body></w:document>',
|
||||
)
|
||||
expect(out).toContain('<w:p><w:r><w:t>x</w:t></w:r></w:p>')
|
||||
expect(out).not.toContain('ns3')
|
||||
})
|
||||
|
||||
it('prefixes elements in a default wordprocessingml namespace', () => {
|
||||
const out = normalizeOoxmlXml(
|
||||
`<document xmlns="${W_TRANS}"><body><p><r><t>x</t></r></p></body></document>`,
|
||||
)
|
||||
expect(out).toContain(`xmlns:w="${W_TRANS}"`)
|
||||
expect(out).toContain('<w:body><w:p><w:r><w:t>x</w:t></w:r></w:p></w:body>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('strict OOXML normalization', () => {
|
||||
it('maps strict namespace URIs to transitional and drops w:conformance', () => {
|
||||
const out = normalizeOoxmlXml(
|
||||
`<w:document xmlns:w="${W_STRICT}" xmlns:r="${R_STRICT}" w:conformance="strict">` +
|
||||
'<w:body><w:p><w:hyperlink r:id="rId1"/></w:p></w:body></w:document>',
|
||||
)
|
||||
expect(out).toContain(`xmlns:w="${W_TRANS}"`)
|
||||
expect(out).toContain(
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"',
|
||||
)
|
||||
expect(out).not.toContain('conformance')
|
||||
expect(out).toContain('<w:hyperlink r:id="rId1"/>')
|
||||
})
|
||||
|
||||
it('maps strict relationship types, including divergent tails', () => {
|
||||
const out = normalizeOoxmlXml(
|
||||
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
|
||||
`<Relationship Id="rId1" Type="${R_STRICT}/styles" Target="styles.xml"/>` +
|
||||
`<Relationship Id="rId2" Type="${R_STRICT}/extendedProperties" Target="../docProps/app.xml"/>` +
|
||||
'</Relationships>',
|
||||
)
|
||||
expect(out).toContain(
|
||||
'Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"',
|
||||
)
|
||||
expect(out).toContain(
|
||||
'Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"',
|
||||
)
|
||||
})
|
||||
|
||||
it('converts universal measures to the native unit of each attribute', () => {
|
||||
const out = normalizeOoxmlXml(
|
||||
`<w:document xmlns:w="${W_STRICT}"><w:body>` +
|
||||
'<w:p><w:pPr><w:ind w:start="72pt" w:hanging="18pt"/>' +
|
||||
'<w:spacing w:before="12pt" w:line="12pt"/>' +
|
||||
'<w:pBdr><w:top w:val="single" w:sz="0.5pt" w:space="1pt"/></w:pBdr>' +
|
||||
'<w:rPr><w:sz w:val="12pt"/><w:position w:val="-3pt"/></w:rPr></w:pPr></w:p>' +
|
||||
'<w:sectPr><w:pgSz w:w="792pt" w:h="612pt" w:orient="landscape"/>' +
|
||||
'<w:pgMar w:top="72pt" w:right="72pt" w:bottom="72pt" w:left="72pt" w:header="36pt" w:footer="36pt" w:gutter="0pt"/>' +
|
||||
'</w:sectPr></w:body></w:document>',
|
||||
)
|
||||
expect(out).toContain('<w:ind w:start="1440" w:hanging="360"/>')
|
||||
expect(out).toContain('<w:spacing w:before="240" w:line="240"/>')
|
||||
expect(out).toContain('<w:top w:val="single" w:sz="4" w:space="1"/>')
|
||||
expect(out).toContain('<w:sz w:val="24"/>')
|
||||
expect(out).toContain('<w:position w:val="-6"/>')
|
||||
expect(out).toContain('<w:pgSz w:w="15840" w:h="12240" w:orient="landscape"/>')
|
||||
expect(out).toContain('w:header="720" w:footer="720" w:gutter="0"')
|
||||
})
|
||||
|
||||
it('leaves plain numeric values and non-w namespaces untouched', () => {
|
||||
const src =
|
||||
`<w:document xmlns:w="${W_STRICT}" xmlns:x="http://example.com/x"><w:body>` +
|
||||
'<w:p><w:pPr><w:ind w:start="720"/></w:pPr></w:p>' +
|
||||
'<x:ind x:start="72pt"/></w:body></w:document>'
|
||||
const out = normalizeOoxmlXml(src)
|
||||
expect(out).toContain('<w:ind w:start="720"/>')
|
||||
expect(out).toContain('<x:ind x:start="72pt"/>')
|
||||
})
|
||||
|
||||
it('shifts wordprocessingShape children written in the wp namespace into wps', () => {
|
||||
const out = normalizeOoxmlXml(
|
||||
`<w:document xmlns:w="${W_STRICT}" xmlns:wp="http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing">` +
|
||||
'<w:body><w:p><w:r><w:drawing><wp:anchor><wp:extent cx="100" cy="100"/>' +
|
||||
'<a:graphic xmlns:a="http://purl.oclc.org/ooxml/drawingml/main">' +
|
||||
'<a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
|
||||
'<wp:wsp><wp:cNvSpPr/><wp:spPr><a:prstGeom prst="rect"/></wp:spPr><wp:bodyPr/></wp:wsp>' +
|
||||
'</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p></w:body></w:document>',
|
||||
)
|
||||
expect(out).toContain(
|
||||
'<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">',
|
||||
)
|
||||
expect(out).toContain('<wps:cNvSpPr/><wps:spPr><a:prstGeom prst="rect"/></wps:spPr>')
|
||||
expect(out).toContain('<wps:bodyPr/></wps:wsp>')
|
||||
// the anchor level stays in the wp namespace
|
||||
expect(out).toContain('<wp:anchor><wp:extent cx="100" cy="100"/>')
|
||||
expect(out).toContain('xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"')
|
||||
})
|
||||
|
||||
it('keeps mc:Ignorable prefix lists aligned with renames', () => {
|
||||
const out = normalizeOoxmlXml(
|
||||
`<w:document xmlns:w="${W_STRICT}"` +
|
||||
' xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"' +
|
||||
' xmlns:cx="http://schemas.microsoft.com/office/word/2010/wordml"' +
|
||||
' mc:Ignorable="cx"><w:body><w:p cx:paraId="1"/></w:body></w:document>',
|
||||
)
|
||||
expect(out).toContain('mc:Ignorable="w14"')
|
||||
expect(out).toContain('<w:p w14:paraId="1"/>')
|
||||
})
|
||||
|
||||
it('remaps Ignorable tokens when the mc namespace itself uses another prefix', () => {
|
||||
const out = normalizeOoxmlXml(
|
||||
`<w:document xmlns:w="${W_STRICT}"` +
|
||||
' xmlns:m2="http://schemas.openxmlformats.org/markup-compatibility/2006"' +
|
||||
' xmlns:cx="http://schemas.microsoft.com/office/word/2010/wordml"' +
|
||||
' m2:Ignorable="cx"><w:body/></w:document>',
|
||||
)
|
||||
expect(out).toContain('mc:Ignorable="w14"')
|
||||
expect(out).toContain('xmlns:mc=')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseDocx over normalized packages', () => {
|
||||
it('parses a document with a non-standard prefix for the main namespace', async () => {
|
||||
const bytes = await buildDocxBytes(
|
||||
`${XML_DECL}<fake:document xmlns:fake="${W_TRANS}"><fake:body>` +
|
||||
'<fake:p><fake:r><fake:t>Body text survives</fake:t></fake:r></fake:p>' +
|
||||
'</fake:body></fake:document>',
|
||||
)
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(
|
||||
doc.blocks
|
||||
.flatMap((b) => b.runs ?? [])
|
||||
.map((r) => r.text)
|
||||
.join(''),
|
||||
).toContain('Body text survives')
|
||||
})
|
||||
|
||||
it('parses a strict document with landscape geometry in pt units', async () => {
|
||||
const bytes = await buildDocxBytes(
|
||||
`${XML_DECL}<w:document xmlns:w="${W_STRICT}" w:conformance="strict"><w:body>` +
|
||||
'<w:p><w:r><w:t>Strict text</w:t></w:r></w:p>' +
|
||||
'<w:sectPr><w:pgSz w:w="792pt" w:h="612pt" w:orient="landscape"/></w:sectPr>' +
|
||||
'</w:body></w:document>',
|
||||
)
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(
|
||||
doc.blocks
|
||||
.flatMap((b) => b.runs ?? [])
|
||||
.map((r) => r.text)
|
||||
.join(''),
|
||||
).toContain('Strict text')
|
||||
const zip = await loadDocxZip(bytes)
|
||||
const normalized = await zip.file('word/document.xml')!.async('string')
|
||||
expect(normalized).toContain('<w:pgSz w:w="15840" w:h="12240" w:orient="landscape"/>')
|
||||
expect(normalized).not.toContain('conformance')
|
||||
})
|
||||
})
|
||||
@@ -160,4 +160,35 @@ describe('page/margin-anchored textboxes outside the body column', () => {
|
||||
expect(box?.floating).toBe(true)
|
||||
expect(box?.offsetXEmu).toBe(Math.round((PAGE_W * 2000) / 100000) - MARGIN)
|
||||
})
|
||||
|
||||
it('centers a column-relative wp:align box in a single-column section', async () => {
|
||||
const posH = `<wp:positionH relativeFrom="column"><wp:align>center</wp:align></wp:positionH>`
|
||||
const posV = `<wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV>`
|
||||
const para = anchorPara(
|
||||
posH,
|
||||
posV,
|
||||
textWsp({ offX: 0, offY: 0, cx: 600000, cy: 400000, text: 'boxed' }),
|
||||
'<wp:extent cx="600000" cy="400000"/>',
|
||||
).replace('<wp:wrapSquare wrapText="bothSides"/>', '<wp:wrapNone/>')
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
|
||||
const [box] = doc.blocks[0].textboxes!
|
||||
expect(box.floating).toBe(true)
|
||||
expect(box.offsetXEmu).toBe(Math.round((PAGE_W - 2 * MARGIN - 600000) / 2))
|
||||
})
|
||||
|
||||
it('keeps column-relative align on the flow placement in multi-column sections', async () => {
|
||||
const posH = `<wp:positionH relativeFrom="column"><wp:align>center</wp:align></wp:positionH>`
|
||||
const posV = `<wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV>`
|
||||
const para = anchorPara(
|
||||
posH,
|
||||
posV,
|
||||
textWsp({ offX: 0, offY: 0, cx: 600000, cy: 400000, text: 'boxed' }),
|
||||
'<wp:extent cx="600000" cy="400000"/>',
|
||||
).replace('<wp:wrapSquare wrapText="bothSides"/>', '<wp:wrapNone/>')
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({ bodyXml: para, sectPrExtra: '<w:cols w:num="2" w:space="708"/>' }),
|
||||
)
|
||||
const [box] = doc.blocks[0].textboxes!
|
||||
expect(box.offsetXEmu).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -213,3 +213,40 @@ describe('empty paragraph line size', () => {
|
||||
expect(doc.blocks[2].format?.emptyRunFontFamily).toBe('Arial')
|
||||
})
|
||||
})
|
||||
|
||||
describe('paragraph-mark w:vanish', () => {
|
||||
it('collapses an empty paragraph with a hidden mark to an invisible marker', async () => {
|
||||
const bodyXml =
|
||||
'<w:p><w:r><w:t>before</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:ind w:left="120"/><w:rPr><w:vanish/></w:rPr></w:pPr></w:p>' +
|
||||
'<w:p><w:r><w:t>after</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml }))
|
||||
expect(doc.blocks[1].invisibleMarker).toBe(true)
|
||||
expect(doc.blocks[1].originalXml).toContain('w:vanish')
|
||||
})
|
||||
|
||||
it('keeps a paragraph with visible runs even when its mark is hidden', async () => {
|
||||
const bodyXml =
|
||||
'<w:p><w:pPr><w:rPr><w:vanish/></w:rPr></w:pPr><w:r><w:t>shown</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml }))
|
||||
expect(doc.blocks[0].invisibleMarker).toBeUndefined()
|
||||
expect(doc.blocks[0].runs?.[0]?.text).toBe('shown')
|
||||
})
|
||||
|
||||
it('keeps a text-less paragraph whose run carries a page break or note mark', async () => {
|
||||
const bodyXml =
|
||||
'<w:p><w:pPr><w:rPr><w:vanish/></w:rPr></w:pPr><w:r><w:br w:type="page"/></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:rPr><w:vanish/></w:rPr></w:pPr><w:r><w:footnoteReference w:id="2"/></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml }))
|
||||
expect(doc.blocks[0].invisibleMarker).toBeUndefined()
|
||||
expect(doc.blocks[1].invisibleMarker).toBeUndefined()
|
||||
})
|
||||
|
||||
it('still collapses when only pPr tab stops are present', async () => {
|
||||
const bodyXml =
|
||||
'<w:p><w:pPr><w:tabs><w:tab w:val="left" w:pos="720"/></w:tabs>' +
|
||||
'<w:rPr><w:vanish/></w:rPr></w:pPr></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml }))
|
||||
expect(doc.blocks[0].invisibleMarker).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -235,3 +235,57 @@ describe('field-form OLE (EMBED/LINK field around w:object)', () => {
|
||||
expect(saved).toBe(bytes)
|
||||
})
|
||||
})
|
||||
|
||||
describe('OLE preview inside a table cell', () => {
|
||||
const CELL_TABLE =
|
||||
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr>' +
|
||||
`<w:p>${OLE_OBJECT_RUN}</w:p>` +
|
||||
'</w:tc></w:tr></w:tbl>'
|
||||
|
||||
it('the preview picture becomes a run image at the declared size', async () => {
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: CELL_TABLE, withImage: true }))
|
||||
const cell = parsed.blocks[0].table!.rows[0][0]
|
||||
const imageRun = cell.richParas?.[0]?.runs.find((r) => r.image)
|
||||
expect(imageRun?.image?.dataUrl).toMatch(/^data:image\/png;base64,/)
|
||||
// declared v:shape size (207.75pt x 15.75pt)
|
||||
expect(imageRun?.image?.widthPx).toBe(277)
|
||||
expect(imageRun?.image?.heightPx).toBe(21)
|
||||
})
|
||||
})
|
||||
|
||||
describe('OLE embed sharing a paragraph with an inline picture', () => {
|
||||
const DRAWING_RUN =
|
||||
'<w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="914400"/>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
|
||||
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r>'
|
||||
|
||||
it('keeps both the OLE preview and the picture as run images', async () => {
|
||||
const bodyXml = `<w:p>${OLE_OBJECT_RUN}${DRAWING_RUN}</w:p>`
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
|
||||
const block = parsed.blocks[0]
|
||||
expect(block.type).toBe('paragraph')
|
||||
const images = (block.runs ?? []).filter((r) => r.image)
|
||||
expect(images).toHaveLength(2)
|
||||
expect(images[0].image?.widthPx).toBe(277)
|
||||
expect(images[1].image?.widthPx).toBe(96)
|
||||
})
|
||||
})
|
||||
|
||||
describe('OLE run carrying an empty sibling w:pict', () => {
|
||||
it('still resolves the object preview (first pict with a picture wins)', async () => {
|
||||
const bodyXml =
|
||||
'<w:p><w:r>' +
|
||||
OLE_OBJECT_RUN.replace('<w:r>', '').replace('</w:r>', '') +
|
||||
'<w:t>bit map object</w:t><w:pict></w:pict>' +
|
||||
'</w:r></w:p>'
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
|
||||
const block = parsed.blocks[0]
|
||||
expect(block.type).toBe('paragraph')
|
||||
const imageRun = (block.runs ?? []).find((r) => r.image)
|
||||
expect(imageRun?.image?.dataUrl).toMatch(/^data:image\/png;base64,/)
|
||||
expect((block.runs ?? []).map((r) => r.text).join('')).toBe('bit map object')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -197,6 +197,96 @@ describe('generateTableModelXml', () => {
|
||||
'<w:jc w:val="center"/>',
|
||||
)
|
||||
})
|
||||
|
||||
it('round-trips AutoFit, cell margins, floating position, and table style options', async () => {
|
||||
const xml = generateTableModelXml({
|
||||
rows: [[{ paras: ['a'] }, { paras: ['b'] }]],
|
||||
autoFit: 'window',
|
||||
cellMarTwips: { top: 80, right: 160, bottom: 90, left: 170 },
|
||||
floatSide: 'left',
|
||||
floatPos: {
|
||||
xTwips: 720,
|
||||
yTwips: 360,
|
||||
horzAnchor: 'margin',
|
||||
vertAnchor: 'text',
|
||||
distanceTwips: { top: 60, right: 120, bottom: 70, left: 130 },
|
||||
},
|
||||
tableLook: {
|
||||
firstRow: true,
|
||||
lastRow: true,
|
||||
firstColumn: false,
|
||||
lastColumn: true,
|
||||
bandedRows: false,
|
||||
bandedColumns: true,
|
||||
},
|
||||
})
|
||||
expect(xml).toContain('<w:tblW w:w="5000" w:type="pct"/>')
|
||||
expect(xml).toContain('<w:tblLayout w:type="autofit"/>')
|
||||
expect(xml).toContain('w:tblpX="720"')
|
||||
expect(xml).toContain('w:tblpY="360"')
|
||||
expect(xml).toContain('w:rightFromText="120"')
|
||||
expect(xml).toContain('<w:top w:w="80" w:type="dxa"/>')
|
||||
expect(xml).toContain('w:lastRow="1"')
|
||||
expect(xml).toContain('w:noHBand="1"')
|
||||
expect(xml).toContain('w:noVBand="0"')
|
||||
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const table = parsed.blocks[0].table!
|
||||
expect(table.autoFit).toBe('window')
|
||||
expect(table.cellMarTwips).toEqual({ top: 80, left: 170, bottom: 90, right: 160 })
|
||||
expect(table.floatSide).toBe('left')
|
||||
expect(table.floatPos).toMatchObject({
|
||||
xTwips: 720,
|
||||
yTwips: 360,
|
||||
horzAnchor: 'margin',
|
||||
vertAnchor: 'text',
|
||||
distanceTwips: { top: 60, right: 120, bottom: 70, left: 130 },
|
||||
})
|
||||
expect(table.tableLook).toMatchObject({
|
||||
firstRow: true,
|
||||
lastRow: true,
|
||||
firstColumn: false,
|
||||
lastColumn: true,
|
||||
bandedRows: false,
|
||||
bandedColumns: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('patches imported table properties and repeat-header rows explicitly', () => {
|
||||
const template =
|
||||
'<w:tbl><w:tblPr><w:tblpPr w:tblpXSpec="right"/><w:tblOverlap w:val="overlap"/>' +
|
||||
'<w:tblW w:w="4000" w:type="dxa"/><w:tblLayout w:type="fixed"/>' +
|
||||
'<w:tblCellMar><w:left w:w="100" w:type="dxa"/></w:tblCellMar></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr><w:trPr><w:tblHeader/></w:trPr><w:tc><w:p><w:r><w:t>Old</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||
'</w:tbl>'
|
||||
const out = generateTableModelXml(
|
||||
{
|
||||
rows: [[{ paras: ['New'] }]],
|
||||
autoFit: 'contents',
|
||||
cellMarTwips: { top: 0, right: 108, bottom: 0, left: 108 },
|
||||
floatSide: null,
|
||||
repeatHeaderRows: [false],
|
||||
},
|
||||
template,
|
||||
)
|
||||
expect(out).toContain('<w:tblW w:w="0" w:type="auto"/>')
|
||||
expect(out).toContain('<w:tblLayout w:type="autofit"/>')
|
||||
expect(out).not.toContain('w:tblpPr')
|
||||
expect(out).not.toContain('w:tblOverlap')
|
||||
expect(out).not.toContain('w:tblHeader')
|
||||
expect(out).toContain('<w:right w:w="108" w:type="dxa"/>')
|
||||
})
|
||||
|
||||
it('writes repeating header rows without disturbing other trPr children', () => {
|
||||
const xml = generateTableModelXml({
|
||||
rows: [[{ paras: ['Header'] }], [{ paras: ['Body'] }]],
|
||||
rawTrPrs: ['<w:trPr><w:cantSplit/></w:trPr>', null],
|
||||
repeatHeaderRows: [true, false],
|
||||
})
|
||||
expect(xml).toContain('<w:trPr><w:cantSplit/><w:tblHeader/></w:trPr>')
|
||||
expect(xml.match(/<w:tblHeader\/>/g)).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('tcPr/trPr fidelity and new attributes', () => {
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateTableModelXml, parseDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
function tc(text: string, tcPr = ''): string {
|
||||
const pr = tcPr ? `<w:tcPr>${tcPr}</w:tcPr>` : ''
|
||||
return `<w:tc>${pr}<w:p><w:r><w:t>${text}</w:t></w:r></w:p></w:tc>`
|
||||
}
|
||||
|
||||
function gridXml(widths: number[]): string {
|
||||
return `<w:tblGrid>${widths.map((w) => `<w:gridCol w:w="${w}"/>`).join('')}</w:tblGrid>`
|
||||
}
|
||||
|
||||
async function tableOf(bodyXml: string) {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml }))
|
||||
const block = doc.blocks[0]
|
||||
expect(block.type).toBe('table')
|
||||
return block.table!
|
||||
}
|
||||
|
||||
/** twips width a cell spans, from the resolved grid */
|
||||
function cellWidth(widths: number[], row: { colSpan?: number }[], index: number): number {
|
||||
let col = 0
|
||||
for (let i = 0; i < index; i++) col += row[i].colSpan ?? 1
|
||||
return widths.slice(col, col + (row[index].colSpan ?? 1)).reduce((a, b) => a + b, 0)
|
||||
}
|
||||
|
||||
describe('grid reconciliation from tcW boundaries', () => {
|
||||
it('rebuilds the grid when row spans under-cover it (govdocs roster shape)', async () => {
|
||||
// 7-column grid, but every row only spans 5 columns; the second cell would
|
||||
// otherwise land on the 28-twip sliver and collapse to one char per line
|
||||
const table = await tableOf(
|
||||
'<w:tbl><w:tblPr><w:tblW w:w="9692" w:type="dxa"/></w:tblPr>' +
|
||||
gridXml([79, 489, 4472, 810, 28, 3780, 34]) +
|
||||
'<w:tr>' +
|
||||
tc('Crew Name:', '<w:tcW w:w="5799" w:type="dxa"/><w:gridSpan w:val="4"/>') +
|
||||
tc('Host Unit/Address:', '<w:tcW w:w="3780" w:type="dxa"/>') +
|
||||
'</w:tr>' +
|
||||
'<w:tr>' +
|
||||
tc('a', '<w:tcW w:w="568" w:type="dxa"/><w:gridSpan w:val="2"/>') +
|
||||
tc('b', '<w:tcW w:w="4472" w:type="dxa"/>') +
|
||||
tc('c', '<w:tcW w:w="810" w:type="dxa"/>') +
|
||||
tc('d', '<w:tcW w:w="3842" w:type="dxa"/><w:gridSpan w:val="3"/>') +
|
||||
'</w:tr>' +
|
||||
'</w:tbl>',
|
||||
)
|
||||
const widths = table.colWidthsTwips!
|
||||
expect(cellWidth(widths, table.rows[0], 0)).toBe(5799)
|
||||
expect(cellWidth(widths, table.rows[0], 1)).toBe(3780)
|
||||
expect(cellWidth(widths, table.rows[1], 3)).toBe(3842)
|
||||
// no column may be a sliver that a text cell sits on alone
|
||||
expect(
|
||||
Math.min(...table.rows.flatMap((r) => r.map((_c, ci) => cellWidth(widths, r, ci)))),
|
||||
).toBeGreaterThan(500)
|
||||
})
|
||||
|
||||
it('re-aligns rows that dropped a gridSpan (govdocs workload shape)', async () => {
|
||||
// 8-column grid; the second data row lost the gridSpan on its label cell,
|
||||
// so its 7 cells drifted one column left and the label collapsed to 5 twips
|
||||
const auto = '<w:tcW w:w="0" w:type="auto"/>'
|
||||
const dataCells = tc('1,582', auto) + tc('1,537', auto) + tc('1,139', auto) + tc('1,093', auto)
|
||||
const table = await tableOf(
|
||||
'<w:tbl><w:tblPr><w:tblW w:w="10115" w:type="dxa"/></w:tblPr>' +
|
||||
gridXml([5, 3282, 1125, 1116, 1116, 1116, 1123, 1232]) +
|
||||
'<w:tr>' +
|
||||
tc('Labels', '<w:tcW w:w="3283" w:type="dxa"/><w:gridSpan w:val="2"/>') +
|
||||
tc('FY', '<w:tcW w:w="1124" w:type="dxa"/>') +
|
||||
dataCells +
|
||||
tc('Est.', '<w:tcW w:w="1230" w:type="dxa"/>') +
|
||||
'</w:tr>' +
|
||||
'<w:tr>' +
|
||||
tc('Pending', '<w:tcW w:w="3283" w:type="dxa"/>') +
|
||||
tc('260', '<w:tcW w:w="1124" w:type="dxa"/>') +
|
||||
dataCells +
|
||||
tc('89', '<w:tcW w:w="1230" w:type="dxa"/>') +
|
||||
'</w:tr>' +
|
||||
'</w:tbl>',
|
||||
)
|
||||
const widths = table.colWidthsTwips!
|
||||
// both label cells resolve to the same wide column(s)
|
||||
expect(cellWidth(widths, table.rows[0], 0)).toBe(3283)
|
||||
expect(cellWidth(widths, table.rows[1], 0)).toBe(3283)
|
||||
// both rows cover the same total width (no one-column drift / empty tail)
|
||||
const total = (r: { colSpan?: number }[]) =>
|
||||
r.reduce((sum, _c, i) => sum + cellWidth(widths, r, i), 0)
|
||||
expect(total(table.rows[1])).toBe(total(table.rows[0]))
|
||||
})
|
||||
|
||||
it('leaves consistent grids untouched', async () => {
|
||||
const table = await tableOf(
|
||||
'<w:tbl>' +
|
||||
gridXml([2000, 4000, 2000]) +
|
||||
'<w:tr>' +
|
||||
tc('a', '<w:tcW w:w="2000" w:type="dxa"/>') +
|
||||
tc('bc', '<w:tcW w:w="6000" w:type="dxa"/><w:gridSpan w:val="2"/>') +
|
||||
'</w:tr>' +
|
||||
'<w:tr>' +
|
||||
tc('a', '<w:tcW w:w="2000" w:type="dxa"/>') +
|
||||
tc('b', '<w:tcW w:w="4000" w:type="dxa"/>') +
|
||||
tc('c', '<w:tcW w:w="2000" w:type="dxa"/>') +
|
||||
'</w:tr>' +
|
||||
'</w:tbl>',
|
||||
)
|
||||
expect(table.colWidthsTwips).toEqual([2000, 4000, 2000])
|
||||
expect(table.rows[0][1].colSpan).toBe(2)
|
||||
expect(table.rows[1].every((c) => (c.colSpan ?? 1) === 1)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('gridBefore/gridAfter', () => {
|
||||
const STAGGERED =
|
||||
'<w:tbl><w:tblPr><w:tblW w:w="4000" w:type="dxa"/></w:tblPr>' +
|
||||
gridXml([1000, 1000, 1000, 1000]) +
|
||||
'<w:tr><w:trPr><w:gridAfter w:val="1"/><w:wAfter w:w="1000" w:type="dxa"/></w:trPr>' +
|
||||
tc('a1', '<w:tcW w:w="1000" w:type="dxa"/>') +
|
||||
tc('a2', '<w:tcW w:w="1000" w:type="dxa"/>') +
|
||||
tc('a3', '<w:tcW w:w="1000" w:type="dxa"/>') +
|
||||
'</w:tr>' +
|
||||
'<w:tr><w:trPr><w:gridBefore w:val="2"/><w:wBefore w:w="2000" w:type="dxa"/></w:trPr>' +
|
||||
tc('b1', '<w:tcW w:w="1000" w:type="dxa"/>') +
|
||||
tc('b2', '<w:tcW w:w="1000" w:type="dxa"/>') +
|
||||
'</w:tr>' +
|
||||
'</w:tbl>'
|
||||
|
||||
it('inserts borderless placeholder cells for the skipped columns', async () => {
|
||||
const table = await tableOf(STAGGERED)
|
||||
expect(table.colWidthsTwips).toEqual([1000, 1000, 1000, 1000])
|
||||
const [row1, row2] = table.rows
|
||||
expect(row1.map((c) => c.gridGap ?? false)).toEqual([false, false, false, true])
|
||||
expect(row2.map((c) => c.gridGap ?? false)).toEqual([true, false, false])
|
||||
expect(row2[0].colSpan).toBe(2)
|
||||
// offset row's first real cell starts at grid column 2
|
||||
expect(row2[1].paras[0]).toBe('b1')
|
||||
// rawTcPr still lands on the real cells despite the inserted placeholders
|
||||
expect(row2[0].rawTcPr).toBeUndefined()
|
||||
expect(row2[1].rawTcPr).toContain('<w:tcW w:w="1000"')
|
||||
expect(row1[3].rawTcPr).toBeUndefined()
|
||||
})
|
||||
|
||||
it('regenerates placeholders as trPr gridBefore/gridAfter, not cells', async () => {
|
||||
const table = await tableOf(STAGGERED)
|
||||
const xml = generateTableModelXml(table)
|
||||
expect(xml.match(/<w:tc>/g)).toHaveLength(5)
|
||||
// rawTrPr passthrough keeps the original offsets exactly once
|
||||
expect(xml.match(/<w:gridBefore\b/g)).toHaveLength(1)
|
||||
expect(xml.match(/<w:gridAfter\b/g)).toHaveLength(1)
|
||||
expect(xml).toContain('<w:wBefore w:w="2000"')
|
||||
const bare = { ...table, rawTrPrs: undefined }
|
||||
const regen = generateTableModelXml(bare)
|
||||
expect(regen).toContain('<w:gridBefore w:val="2"/>')
|
||||
expect(regen).toContain('<w:wBefore w:w="2000" w:type="dxa"/>')
|
||||
expect(regen.match(/<w:tc>/g)).toHaveLength(5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('cell spacing and shading patterns', () => {
|
||||
it('parses w:tblCellSpacing and table-level shading', async () => {
|
||||
const table = await tableOf(
|
||||
'<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/>' +
|
||||
'<w:tblCellSpacing w:w="142" w:type="dxa"/>' +
|
||||
'<w:shd w:val="clear" w:color="auto" w:fill="FFC000"/></w:tblPr>' +
|
||||
gridXml([2000, 2000]) +
|
||||
'<w:tr>' +
|
||||
tc('a', '<w:tcW w:w="2000" w:type="dxa"/>') +
|
||||
tc('b', '<w:tcW w:w="2000" w:type="dxa"/>') +
|
||||
'</w:tr>' +
|
||||
'</w:tbl>',
|
||||
)
|
||||
expect(table.cellSpacingTwips).toBe(142)
|
||||
expect(table.fill).toBe('FFC000')
|
||||
})
|
||||
|
||||
it('approximates pattern shading as blended fills', async () => {
|
||||
const table = await tableOf(
|
||||
'<w:tbl>' +
|
||||
gridXml([2000, 2000, 2000]) +
|
||||
'<w:tr>' +
|
||||
tc('gray', '<w:shd w:val="pct5" w:color="auto" w:fill="auto"/>') +
|
||||
tc('stripe', '<w:shd w:val="reverseDiagStripe" w:color="6FB31A" w:fill="auto"/>') +
|
||||
tc('plain', '<w:shd w:val="clear" w:color="auto" w:fill="auto"/>') +
|
||||
'</w:tr>' +
|
||||
'</w:tbl>',
|
||||
)
|
||||
const [gray, stripe, plain] = table.rows[0]
|
||||
expect(gray.fill).toBe('F2F2F2')
|
||||
expect(stripe.fill).toBe('B7D98D')
|
||||
expect(plain.fill).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/parse'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const WPS_NS = 'xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"'
|
||||
const MC_NS = 'xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"'
|
||||
|
||||
function anchorParagraph(wsp: string, drawingAttrs = ''): string {
|
||||
return (
|
||||
`<w:p><w:r><w:drawing${drawingAttrs}><wp:anchor behindDoc="0" simplePos="0" locked="0" layoutInCell="1" allowOverlap="1">` +
|
||||
'<wp:simplePos x="0" y="0"/>' +
|
||||
'<wp:positionH relativeFrom="column"><wp:posOffset>584200</wp:posOffset></wp:positionH>' +
|
||||
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>127000</wp:posOffset></wp:positionV>' +
|
||||
'<wp:extent cx="584200" cy="374650"/><wp:wrapNone/>' +
|
||||
'<wp:docPr id="1" name="Shape 1"/>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
|
||||
`${wsp}</a:graphicData></a:graphic>` +
|
||||
'</wp:anchor></w:drawing></w:r></w:p>'
|
||||
)
|
||||
}
|
||||
|
||||
describe('themeless documents (no word/theme/theme1.xml)', () => {
|
||||
it('resolves wps:style schemeClr against the built-in Office palette', async () => {
|
||||
// docx4j 2010-glow-then-Alt / 2010-mcAlternateCo: a gallery ellipse whose
|
||||
// only ink comes from fillRef/lnRef accent1 — colors:null dropped it
|
||||
const wsp =
|
||||
`<wps:wsp ${WPS_NS}><wps:cNvSpPr/><wps:spPr>` +
|
||||
'<a:xfrm><a:off x="0" y="0"/><a:ext cx="584200" cy="374650"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="ellipse"><a:avLst/></a:prstGeom></wps:spPr>' +
|
||||
'<wps:style>' +
|
||||
'<a:lnRef idx="2"><a:schemeClr val="accent1"><a:shade val="50000"/></a:schemeClr></a:lnRef>' +
|
||||
'<a:fillRef idx="1"><a:schemeClr val="accent1"/></a:fillRef>' +
|
||||
'<a:effectRef idx="0"><a:schemeClr val="accent1"/></a:effectRef>' +
|
||||
'<a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef>' +
|
||||
'</wps:style><wps:bodyPr/></wps:wsp>'
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: anchorParagraph(wsp) }))
|
||||
const box = parsed.blocks.find((b) => b.textboxes?.length)?.textboxes?.[0]
|
||||
expect(box).toBeDefined()
|
||||
expect(box?.prst).toBe('ellipse')
|
||||
expect(box?.fill).toBe('4472C4')
|
||||
// accent1 at 50% shade
|
||||
expect(box?.borderColor).toBe('223962')
|
||||
expect(parsed.themeColors?.accent1).toBe('4472C4')
|
||||
})
|
||||
})
|
||||
|
||||
describe('w:drawing with attributes (mc:MustUnderstand)', () => {
|
||||
it('extracts the shape from an attributed <w:drawing> open tag', async () => {
|
||||
const wsp =
|
||||
`<wps:wsp ${WPS_NS}><wps:cNvSpPr/><wps:spPr>` +
|
||||
'<a:xfrm><a:off x="0" y="0"/><a:ext cx="2366645" cy="1404620"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="roundRect"><a:avLst/></a:prstGeom>' +
|
||||
'<a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>' +
|
||||
'</wps:spPr><wps:bodyPr/></wps:wsp>'
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: anchorParagraph(wsp, ` ${MC_NS} mc:MustUnderstand="wps"`),
|
||||
}),
|
||||
)
|
||||
const box = parsed.blocks.find((b) => b.textboxes?.length)?.textboxes?.[0]
|
||||
expect(box).toBeDefined()
|
||||
expect(box?.fill).toBe('FF0000')
|
||||
expect(box?.floating).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('external textbox part (wps:txbx r:txbx)', () => {
|
||||
it('reads the referenced word/txbx1.xml paragraphs into the box, display-only', async () => {
|
||||
// TestFiles mcdoc: the Choice textbox stores its content in a separate
|
||||
// part whose w14:txbx root carries the w:p list directly
|
||||
const wsp =
|
||||
`<wps:wsp ${WPS_NS}><wps:cNvSpPr txBox="1"/><wps:spPr>` +
|
||||
'<a:xfrm><a:off x="0" y="0"/><a:ext cx="2366645" cy="1404620"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>' +
|
||||
'<a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill>' +
|
||||
'<a:ln w="9525"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln>' +
|
||||
'</wps:spPr><wps:txbx r:txbx="rId20" txbxSeq="0"/><wps:bodyPr/></wps:wsp>'
|
||||
const txbxPart =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
||||
'<w14:txbx xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" ' +
|
||||
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:p><w:r><w:t>hello</w:t></w:r></w:p></w14:txbx>'
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: anchorParagraph(wsp),
|
||||
extraRels:
|
||||
'<Relationship Id="rId20" Type="http://schemas.microsoft.com/office/2006/relationships/txbx" Target="txbx1.xml"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/txbx1.xml',
|
||||
xml: txbxPart,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.txbx+xml',
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
const box = parsed.blocks.find((b) => b.textboxes?.length)?.textboxes?.[0]
|
||||
expect(box).toBeDefined()
|
||||
expect(box?.fill).toBe('FFFFFF')
|
||||
expect(box?.borderColor).toBe('000000')
|
||||
expect(box?.paras.map((p) => p.runs.map((r) => r.text).join(''))).toEqual(['hello'])
|
||||
// the external content is not patchable in document.xml
|
||||
expect(box?.readOnly).toBe(true)
|
||||
expect(box?.txbxIndex).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -262,15 +262,17 @@ describe('w:themeColor resolution', () => {
|
||||
expect(doc.blocks[0].runs?.[1].color).toBe('335593')
|
||||
})
|
||||
|
||||
it('w:val alone still wins when the doc has no theme part', async () => {
|
||||
it('resolves against the built-in Office palette when the doc has no theme part', async () => {
|
||||
// Word materializes the default theme for themeless documents: accent1
|
||||
// still beats the cached w:val
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:rPr><w:color w:val="FF0000" w:themeColor="accent1"/></w:rPr><w:t>x</w:t></w:r></w:p>',
|
||||
}),
|
||||
)
|
||||
expect(doc.themeColors).toBeNull()
|
||||
expect(doc.blocks[0].runs?.[0].color).toBe('FF0000')
|
||||
expect(doc.themeColors?.accent1).toBe('4472C4')
|
||||
expect(doc.blocks[0].runs?.[0].color).toBe('4472C4')
|
||||
})
|
||||
|
||||
it('an untouched themed document still saves byte-identical', async () => {
|
||||
|
||||
@@ -65,6 +65,94 @@ describe('VML WordArt (v:textpath) display', () => {
|
||||
expect(box?.textOutline).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps anchored DrawingML photos sharing the paragraph with the WordArt shape', async () => {
|
||||
const anchoredPic = (blipXml: string, cx: number, cy: number): string =>
|
||||
'<w:r><w:drawing><wp:anchor distT="0" distB="0" distL="0" distR="0" simplePos="0" ' +
|
||||
'relativeHeight="2" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">' +
|
||||
'<wp:positionH relativeFrom="column"><wp:posOffset>914400</wp:posOffset></wp:positionH>' +
|
||||
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>457200</wp:posOffset></wp:positionV>' +
|
||||
`<wp:extent cx="${cx}" cy="${cy}"/>` +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
`<pic:pic><pic:blipFill>${blipXml}<a:stretch><a:fillRect/></a:stretch></pic:blipFill>` +
|
||||
// pic:spPr carries an EMPTY a:blip in its own blipFill (real-world Word
|
||||
// output): media resolution must not trip over it
|
||||
'<pic:spPr><a:blipFill dpi="0" rotWithShape="0"><a:blip/></a:blipFill>' +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic>' +
|
||||
'</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>'
|
||||
const bodyXml =
|
||||
'<w:p><w:r><w:pict>' +
|
||||
`<v:shape ${V_NS} id="wa1" type="#_x0000_t136" style="width:148.5pt;height:28.5pt" fillcolor="#9400ed">` +
|
||||
'<v:textpath style="font-family:"Arial Black";font-size:20pt" string="Moon Landing"/></v:shape>' +
|
||||
'</w:pict></w:r>' +
|
||||
anchoredPic('<a:blip r:embed="rId10"/>', 1418590, 1201420) +
|
||||
// second blip carries both r:embed and r:link — the embedded part must resolve
|
||||
anchoredPic('<a:blip r:embed="rId11" r:link="rId12"/>', 1448435, 1280160) +
|
||||
'</w:p>'
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml,
|
||||
withImage: true,
|
||||
extraRels:
|
||||
'<Relationship Id="rId11" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.png"/>' +
|
||||
'<Relationship Id="rId12" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="http://example.com/moon.jpg" TargetMode="External"/>',
|
||||
}),
|
||||
)
|
||||
const block = doc.blocks[0]
|
||||
expect(block.label).toBe('Text box')
|
||||
const boxes = block.textboxes ?? []
|
||||
expect(boxes.some((b) => b.paras[0]?.runs[0]?.text === 'Moon Landing')).toBe(true)
|
||||
const photos = boxes.filter((b) => b.fillImageDataUrl)
|
||||
expect(photos).toHaveLength(2)
|
||||
for (const photo of photos) {
|
||||
expect(photo.fillImageDataUrl).toMatch(/^data:image\/png;base64,/)
|
||||
}
|
||||
expect(photos.map((p) => p.widthPx)).toEqual([149, 152])
|
||||
})
|
||||
|
||||
it('does not lift a picture nested in VML textbox content into a page-level box', async () => {
|
||||
const innerDrawing =
|
||||
'<w:drawing><wp:inline><wp:extent cx="914400" cy="914400"/>' +
|
||||
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
|
||||
'</a:graphicData></a:graphic></wp:inline></w:drawing>'
|
||||
const bodyXml =
|
||||
`<w:p><w:r><w:pict><v:shape ${V_NS} id="tb1" type="#_x0000_t202" style="width:200pt;height:120pt">` +
|
||||
'<v:textbox><w:txbxContent>' +
|
||||
`<w:p><w:r><w:t>caption</w:t></w:r></w:p><w:p><w:r>${innerDrawing}</w:r></w:p>` +
|
||||
'</w:txbxContent></v:textbox></v:shape></w:pict></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
|
||||
const boxes = doc.blocks[0].textboxes ?? []
|
||||
expect(boxes).toHaveLength(1)
|
||||
expect(boxes[0].fillImageDataUrl).toBeUndefined()
|
||||
expect(boxes[0].paras[0]?.runs[0]?.text).toBe('caption')
|
||||
})
|
||||
|
||||
it('page-pins page-anchored wrapNone photos next to WordArt like the drawing branch', async () => {
|
||||
const pageAnchoredPic = (x: number, y: number): string =>
|
||||
'<w:r><w:drawing><wp:anchor distT="0" distB="0" distL="0" distR="0" simplePos="0" ' +
|
||||
'relativeHeight="2" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">' +
|
||||
`<wp:positionH relativeFrom="page"><wp:posOffset>${x}</wp:posOffset></wp:positionH>` +
|
||||
`<wp:positionV relativeFrom="page"><wp:posOffset>${y}</wp:posOffset></wp:positionV>` +
|
||||
'<wp:extent cx="914400" cy="914400"/><wp:wrapNone/>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
|
||||
'</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>'
|
||||
const bodyXml =
|
||||
'<w:p><w:r><w:t>logo line above</w:t></w:r></w:p>' +
|
||||
`<w:p><w:r><w:pict><v:shape ${V_NS} id="wa1" type="#_x0000_t136" style="width:148.5pt;height:28.5pt">` +
|
||||
'<v:textpath style="font-family:"Arial Black"" string="Cover Title"/></v:shape></w:pict></w:r>' +
|
||||
pageAnchoredPic(914400, 1828800) +
|
||||
pageAnchoredPic(2743200, 1828800) +
|
||||
'</w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
|
||||
const photos = (doc.blocks[1].textboxes ?? []).filter((b) => b.fillImageDataUrl)
|
||||
expect(photos).toHaveLength(2)
|
||||
// raw page coordinates, pinned to the page box (not the paragraph origin)
|
||||
expect(photos.map((p) => p.pagePinned)).toEqual([true, true])
|
||||
expect(photos.map((p) => p.offsetXEmu)).toEqual([914400, 2743200])
|
||||
expect(photos.map((p) => p.offsetYEmu)).toEqual([1828800, 1828800])
|
||||
})
|
||||
|
||||
it('ignores string-less v:textpath (shapetype template / watermark furniture)', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
|
||||
@@ -246,9 +246,10 @@ describe('removePersonalInformation', () => {
|
||||
const read = (path: string) => zip.file(path)!.async('string')
|
||||
|
||||
const documentXml = await read('word/document.xml')
|
||||
expect(documentXml).toContain("x:author='Author'")
|
||||
expect(documentXml).toContain("x:id='body-rev'")
|
||||
expect(documentXml).toContain("x:date='2024-02-01T02:03:04Z'")
|
||||
// load-time namespace normalization renames the x binding to the canonical w
|
||||
expect(documentXml).toContain('w:author="Author"')
|
||||
expect(documentXml).toContain('w:id="body-rev"')
|
||||
expect(documentXml).toContain('w:date="2024-02-01T02:03:04Z"')
|
||||
expect(documentXml).toContain('Body Person remains as content')
|
||||
expect(documentXml).toContain('author="Visible Person"')
|
||||
expect(documentXml).toContain("w:author='Visible Qualified'")
|
||||
@@ -282,10 +283,10 @@ describe('removePersonalInformation', () => {
|
||||
expect(xml).toContain(date)
|
||||
}
|
||||
const comments = await read('word/comments.xml')
|
||||
expect(comments).toContain("c:author='Author'")
|
||||
expect(comments).toContain("c:initials='A'")
|
||||
expect(comments).toContain("c:id='comment-7'")
|
||||
expect(comments).toContain("c:date='2024-03-01T02:03:04Z'")
|
||||
expect(comments).toContain('w:author="Author"')
|
||||
expect(comments).toContain('w:initials="A"')
|
||||
expect(comments).toContain('w:id="comment-7"')
|
||||
expect(comments).toContain('w:date="2024-03-01T02:03:04Z"')
|
||||
|
||||
const core = await read('docProps/core.xml')
|
||||
expect(core).toContain("<d:creator role='writer'></d:creator>")
|
||||
@@ -299,8 +300,8 @@ describe('removePersonalInformation', () => {
|
||||
expect(app).toContain('<ep:Application>Preserved App</ep:Application>')
|
||||
|
||||
const people = await read('word/people.xml')
|
||||
expect(people).toContain('<p:people')
|
||||
expect(people).not.toContain('<p:person ')
|
||||
expect(people).toContain(':people')
|
||||
expect(people).not.toContain(':person ')
|
||||
expect(people).not.toContain('People Person')
|
||||
expect(people).not.toContain('person@example.com')
|
||||
expect(people).not.toContain('person-keep')
|
||||
|
||||
Reference in New Issue
Block a user