Sync snapshot (2026-09-02) (#181)

- Docs: DOCX rendering and pagination fidelity (page borders, VML pictures, header/footer images, cross-page tables, anchored floats, character-unit indents, CJK typography)
- Docs: more reliable PDF export for huge documents; AI rewrites keep the replaced content's formatting
- Sheets: merge workbooks; Excel-standard keyboard shortcuts; PDF export with header/footer variants and pictures
- Sheets: rendering, conditional formatting, chart and formula fidelity fixes; right-to-left sheet support
- Slides: WordArt text warp, improved text layout and font substitution; AI table edits keep formatting

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-09-03 00:12:17 +08:00
committed by GitHub
co-authored by GenOffice
parent 93b8938c45
commit 9f971edafa
491 changed files with 128943 additions and 103513 deletions
+32 -2
View File
@@ -55,6 +55,10 @@ export interface NewChartOptions extends ChartStyleOptions {
barDir?: 'col' | 'bar'
/** Per-point fills, [seriesIdx][pointIdx] (sparse; written as <c:dPt>, wins over the series color) */
pointColors?: Array<Array<string | undefined> | undefined>
/** Per-series solid colors (#RRGGBB, cycled); line-like series color the stroke, others the fill */
colorScheme?: string[]
/** Doughnut hole size (percent, c:holeSize, default 50) */
holeSizePct?: number
}
const CHART_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'
@@ -197,7 +201,7 @@ export function buildChartSpaceXml(opts: NewChartOptions): string {
} else if (opts.kind === 'doughnut') {
plot =
`<c:doughnutChart><c:varyColors val="1"/>${sers}${dLbls}` +
'<c:firstSliceAng val="0"/><c:holeSize val="50"/></c:doughnutChart>'
`<c:firstSliceAng val="0"/><c:holeSize val="${Math.min(90, Math.max(1, Math.round(opts.holeSizePct ?? 50)))}"/></c:doughnutChart>`
} else if (opts.kind === 'scatter') {
// Scatter (XY): x values come from categories (numeric strings use their value,
// otherwise ordinals 1..n), y values from the series values;
@@ -279,13 +283,39 @@ export function buildChartSpaceXml(opts: NewChartOptions): string {
legendPos === 'none'
? ''
: `<c:legend><c:legendPos val="${legendPos}"/><c:overlay val="0"/></c:legend>`
return (
const xml =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
`<c:chartSpace xmlns:c="${C_NS}" xmlns:a="${A_NS}" xmlns:r="${R_NS}">` +
`<c:chart>${title}${view3D}<c:plotArea><c:layout/>${plot}</c:plotArea>` +
legend +
'<c:plotVisOnly val="1"/><c:dispBlanksAs val="gap"/></c:chart>' +
'</c:chartSpace>'
return injectSeriesColors(xml, opts)
}
/**
* Per-series <c:spPr> solid colors, inserted at the CT_*Ser schema position
* (after c:tx, before c:dPt/c:cat). The last series of a combo chart is the
* line: its color goes on an <a:ln> stroke (lines use stroke, bars/pies fill).
*/
function injectSeriesColors(xml: string, opts: NewChartOptions): string {
const scheme = opts.colorScheme
if (!scheme?.length) return xml
const lineFamily = opts.kind === 'line' || opts.kind === 'scatter' || opts.kind === 'radar'
const comboLineIdx =
opts.kind === 'comboBarLine' && opts.series.length >= 2 ? opts.series.length - 1 : -1
return xml.replace(
/<c:ser><c:idx val="(\d+)"\/><c:order val="\d+"\/>(?:<c:tx>.*?<\/c:tx>)?/gs,
(head, idx: string) => {
const i = Number(idx)
const color = scheme[i % scheme.length]!.replace('#', '').slice(0, 6).toUpperCase()
const fill = `<a:solidFill><a:srgbClr val="${color}"/></a:solidFill>`
const spPr =
lineFamily || i === comboLineIdx
? `<c:spPr><a:ln w="28575">${fill}</a:ln></c:spPr>`
: `<c:spPr>${fill}</c:spPr>`
return head + spPr
},
)
}
+10
View File
@@ -684,6 +684,8 @@ export function generateParagraphXml(p: Paragraph): string {
const pPrAttrs: string[] = []
if (p.marL != null && want('marL')) pPrAttrs.push(`marL="${Math.round(p.marL)}"`)
if (p.marR != null && want('marR')) pPrAttrs.push(`marR="${Math.round(p.marR)}"`)
if (p.defTabSz != null && want('defTabSz')) pPrAttrs.push(`defTabSz="${Math.round(p.defTabSz)}"`)
if (p.indent != null && want('indent')) pPrAttrs.push(`indent="${Math.round(p.indent)}"`)
if (p.align && want('align')) pPrAttrs.push(`algn="${alignMap[p.align]}"`)
if (p.rtl != null) pPrAttrs.push(`rtl="${p.rtl ? 1 : 0}"`)
@@ -722,6 +724,14 @@ export function generateParagraphXml(p: Paragraph): string {
: `<a:buChar char="${escapeXmlAttr(b.char ?? '•')}"/>`
}
}
if (p.tabStops?.length && want('tabLst')) {
kids += `<a:tabLst>${p.tabStops
.map(
(t) =>
`<a:tab pos="${Math.round(t.pos)}"${t.algn ? ` algn="${escapeXmlAttr(t.algn)}"` : ''}/>`,
)
.join('')}</a:tabLst>`
}
const attrStr = pPrAttrs.length ? ` ${pPrAttrs.join(' ')}` : ''
const pPr = kids
+19 -22
View File
@@ -2585,6 +2585,8 @@ export function editChartElement(
catAxisTitle?: string
valAxisTitle?: string
gapWidthPct?: number
/** Doughnut hole size percent (kept from the existing chart when unspecified) */
holeSizePct?: number
/** Swap rows/columns: categories ↔ series (mutually exclusive with categories/series patches, triggered separately in the UI) */
switchRowCol?: boolean
/** Per-point fill overrides, seriesIdx → pointIdx → color; null clears back to the series color */
@@ -2693,6 +2695,10 @@ export function editChartElement(
const colorScheme =
patch.colorScheme ??
(existingColors.every((c): c is string => !!c) ? existingColors : undefined)
// A custom doughnut hole used to reset to the build default on every rebuild.
// A plain pie parses as holePct 0 — forwarding that would clamp a pie→doughnut
// switch to a 1% hole, so only a real (nonzero) hole is preserved.
const holeSizePct = patch.holeSizePct ?? (existing.holePct || undefined)
const opts: NewChartOptions = {
kind,
@@ -2708,8 +2714,10 @@ export function editChartElement(
...(gapWidthPct != null ? { gapWidthPct } : {}),
...(barDir ? { barDir } : {}),
...(pointColors.some((row) => row?.some((c) => c != null)) ? { pointColors } : {}),
...(colorScheme ? { colorScheme } : {}),
...(holeSizePct != null ? { holeSizePct } : {}),
}
const newXml = buildChartSpaceXmlWithColors(opts, colorScheme)
const newXml = buildChartSpaceXml(opts)
archive.entries.set(chartPath, Buffer.from(newXml, 'utf8'))
slide.structureDirty = true
return true
@@ -2739,26 +2747,6 @@ export function markChartEditable(slide: Slide, elementId: string): boolean {
return true
}
/** Chart XML build with colors (spPr solidFill on each series). */
function buildChartSpaceXmlWithColors(opts: NewChartOptions, colorScheme?: string[]): string {
const base = buildChartSpaceXml(opts)
if (!colorScheme || !colorScheme.length) return base
// The last series of a combo chart is the line: write the color as an <a:ln> stroke (lines use stroke color, bars/pies use fill color)
const lineSerIdx =
opts.kind === 'comboBarLine' && opts.series.length >= 2 ? opts.series.length - 1 : -1
let serIndex = 0
return base.replace(/<c:ser>/g, () => {
const color = colorScheme[serIndex % colorScheme.length]!.replace('#', '').toUpperCase()
const fill = `<a:solidFill><a:srgbClr val="${color}"/></a:solidFill>`
const spPr =
serIndex === lineSerIdx
? `<c:spPr><a:ln w="28575">${fill}</a:ln></c:spPr>`
: `<c:spPr>${fill}</c:spPr>`
serIndex++
return `<c:ser>${spPr}`
})
}
/** Escape RegExp special characters. */
function escapeRegex(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
@@ -3015,7 +3003,16 @@ export interface ParagraphFormatPatch {
/** PowerPoint default bullet hanging indent (0.25in = 228600 EMU) */
const BULLET_HANG_EMU = 228600
function applyParagraphFormat(paragraphs: Paragraph[], patch: ParagraphFormatPatch): PPrDirty {
/**
* Apply a paragraph-format patch to model paragraphs in place. Exported for
* callers that rebuild a text body themselves (table cell edits) and need the
* same bullet/spacing/direction semantics as setElementParagraphFormat without
* its element-wide scope.
*/
export function applyParagraphFormat(
paragraphs: Paragraph[],
patch: ParagraphFormatPatch,
): PPrDirty {
const dirty: PPrDirty = {}
for (const p of paragraphs) {
// Missing pPrExplicit = newly created element (all-explicit semantics); change values only, don't build the flag table
+63 -12
View File
@@ -36,6 +36,8 @@ export interface NewElementBodyPr {
anchor?: 't' | 'ctr' | 'b'
/** lIns/tIns/rIns/bIns (EMU); absent keeps PowerPoint defaults */
insetsEmu?: { l: number; t: number; r: number; b: number }
/** <a:normAutofit/> (shrink text on overflow) or <a:spAutoFit/> (grow the shape) */
autoFit?: 'shrink' | 'resize'
}
export interface NewElementOptions {
@@ -48,6 +50,8 @@ export interface NewElementOptions {
stroke?: { color: string; widthEmu: number }
/** body geometry overrides; absent = `wrap="square" rtlCol="0"` as before */
bodyPr?: NewElementBodyPr
/** prstGeom adjustment values (<a:avLst><a:gd name fmla="val N"/>), e.g. {adj: 25000} for roundRect radius */
adjustments?: Record<string, number>
}
/**
@@ -69,16 +73,25 @@ function srgbClrXml(color: string): string {
function buildBodyPrXml(bodyPr: NewElementBodyPr | undefined): string {
if (!bodyPr) return '<a:bodyPr wrap="square" rtlCol="0"/>'
const ins = bodyPr.insetsEmu
return (
const attrs =
`<a:bodyPr wrap="${bodyPr.wrap ?? 'square'}" rtlCol="0"` +
(ins
? ` lIns="${Math.round(ins.l)}" tIns="${Math.round(ins.t)}" rIns="${Math.round(ins.r)}" bIns="${Math.round(ins.b)}"`
: '') +
(bodyPr.anchor ? ` anchor="${bodyPr.anchor}"` : '') +
'/>'
(bodyPr.anchor ? ` anchor="${bodyPr.anchor}"` : '')
if (!bodyPr.autoFit) return attrs + '/>'
return (
attrs + `>${bodyPr.autoFit === 'shrink' ? '<a:normAutofit/>' : '<a:spAutoFit/>'}</a:bodyPr>`
)
}
function buildAvLstXml(adjustments: Record<string, number> | undefined): string {
if (!adjustments) return '<a:avLst/>'
return `<a:avLst>${Object.entries(adjustments)
.map(([n, v]) => `<a:gd name="${escapeXmlAttr(n)}" fmla="val ${Math.round(v)}"/>`)
.join('')}</a:avLst>`
}
let insertCounter = 1
// ── Line / connector insertion ─────────────────────────────
@@ -120,7 +133,7 @@ function buildCxnSpXml(
`<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}">${creationIdXml()}</p:cNvPr>` +
'<p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>' +
`<p:spPr><a:xfrm><a:off x="${o.x}" y="${o.y}"/><a:ext cx="${o.cx}" cy="${o.cy}"/></a:xfrm>` +
`<a:prstGeom prst="${def.prst}"><a:avLst/></a:prstGeom>` +
`<a:prstGeom prst="${def.prst}">${buildAvLstXml(opts.adjustments)}</a:prstGeom>` +
`<a:ln w="${Math.round(stroke.widthEmu)}" cap="flat">` +
`<a:solidFill><a:srgbClr val="${color}"/></a:solidFill>${head}${tail}</a:ln>` +
'</p:spPr></p:cxnSp>'
@@ -149,7 +162,7 @@ export function buildSpXml(slide: Slide, opts: NewElementOptions): string {
// Parser convention: has txBody and no prstGeom → 'text'; textbox omits prstGeom
const geom = isTextbox
? ''
: `<a:prstGeom prst="${escapeXmlAttr(opts.kind)}"><a:avLst/></a:prstGeom>`
: `<a:prstGeom prst="${escapeXmlAttr(opts.kind)}">${buildAvLstXml(opts.adjustments)}</a:prstGeom>`
const fill = opts.fillColor ? `<a:solidFill>${srgbClrXml(opts.fillColor)}</a:solidFill>` : ''
const ln = opts.stroke
? `<a:ln w="${Math.round(opts.stroke.widthEmu)}"><a:solidFill><a:srgbClr val="${opts.stroke.color.replace(/^#/, '').slice(0, 6).toUpperCase()}"/></a:solidFill></a:ln>`
@@ -180,6 +193,7 @@ export function addElement(slide: Slide, opts: NewElementOptions): TextElement {
},
transform: { offset: { ...opts.offset }, rot: 0, flipH: false, flipV: false },
presetGeometry: lineDef.prst,
...(opts.adjustments ? { adjust: { ...opts.adjustments } } : {}),
fill: { type: 'none' },
stroke: {
fill: { type: 'solid', color: stroke.color },
@@ -199,6 +213,7 @@ export function addElement(slide: Slide, opts: NewElementOptions): TextElement {
anchor: { spIndex: slide.elements.length, originalXml: xml, range: [0, 0] },
transform: { offset: { ...opts.offset }, rot: 0, flipH: false, flipV: false },
...(opts.kind !== 'textbox' ? { presetGeometry: opts.kind } : {}),
...(opts.kind !== 'textbox' && opts.adjustments ? { adjust: { ...opts.adjustments } } : {}),
...(opts.fillColor ? { fill: { type: 'solid' as const, color: opts.fillColor } } : {}),
...(opts.stroke
? {
@@ -208,7 +223,10 @@ export function addElement(slide: Slide, opts: NewElementOptions): TextElement {
},
}
: {}),
text: { paragraphs: opts.paragraphs?.length ? opts.paragraphs : [{ runs: [{ text: '' }] }] },
text: {
paragraphs: opts.paragraphs?.length ? opts.paragraphs : [{ runs: [{ text: '' }] }],
...(opts.bodyPr?.autoFit ? { autofit: opts.bodyPr.autoFit } : {}),
},
}
slide.elements.push(el)
slide.structureDirty = true
@@ -217,10 +235,24 @@ export function addElement(slide: Slide, opts: NewElementOptions): TextElement {
// ── Table insertion (graphicFrame + a:tbl) ─────────────────────────────
/** Per-cell structural attributes for buildTableXml (merges + vertical anchor). */
export interface NewTableCellProps {
gridSpan?: number
rowSpan?: number
hMerge?: boolean
vMerge?: boolean
anchor?: 't' | 'ctr' | 'b'
}
export interface NewTableOptions {
rows: number
cols: number
offset: EmuRect
/** explicit column widths / row heights (EMU); a length-matched list overrides the equal split */
colWidthsEmu?: number[]
rowHeightsEmu?: number[]
/** row-major per-cell attributes; absent entries = plain cell */
cellProps?: Array<Array<NewTableCellProps | undefined>>
}
/** PowerPoint's default style for new tables (Medium Style 2 - Accent 1, built-in fallback in the render layer) */
@@ -237,12 +269,31 @@ export function buildTableXml(slide: Slide, opts: NewTableOptions): string {
const cols = Math.max(1, Math.floor(opts.cols))
const colW = Math.max(1, Math.floor(opts.offset.cx / cols))
const rowH = Math.max(1, Math.floor(opts.offset.cy / rows))
const grid = Array.from({ length: cols }, () => `<a:gridCol w="${colW}"/>`).join('')
const cell = '<a:tc><a:txBody><a:bodyPr/><a:lstStyle/><a:p/></a:txBody><a:tcPr/></a:tc>'
const trs = Array.from(
{ length: rows },
() => `<a:tr h="${rowH}">${cell.repeat(cols)}</a:tr>`,
).join('')
const colWs =
opts.colWidthsEmu?.length === cols
? opts.colWidthsEmu.map((w) => Math.max(1, Math.round(w)))
: Array.from({ length: cols }, () => colW)
const rowHs =
opts.rowHeightsEmu?.length === rows
? opts.rowHeightsEmu.map((h) => Math.max(1, Math.round(h)))
: Array.from({ length: rows }, () => rowH)
const grid = colWs.map((w) => `<a:gridCol w="${w}"/>`).join('')
const cellXml = (r: number, c: number): string => {
const p = opts.cellProps?.[r]?.[c]
const attrs: string[] = []
if (p?.gridSpan && p.gridSpan > 1) attrs.push(`gridSpan="${Math.floor(p.gridSpan)}"`)
if (p?.rowSpan && p.rowSpan > 1) attrs.push(`rowSpan="${Math.floor(p.rowSpan)}"`)
if (p?.hMerge) attrs.push('hMerge="1"')
if (p?.vMerge) attrs.push('vMerge="1"')
const tcPr = p?.anchor && p.anchor !== 't' ? `<a:tcPr anchor="${p.anchor}"/>` : '<a:tcPr/>'
return `<a:tc${attrs.length ? ` ${attrs.join(' ')}` : ''}><a:txBody><a:bodyPr/><a:lstStyle/><a:p/></a:txBody>${tcPr}</a:tc>`
}
const trs = rowHs
.map(
(h, r) =>
`<a:tr h="${h}">${Array.from({ length: cols }, (_, c) => cellXml(r, c)).join('')}</a:tr>`,
)
.join('')
return (
`<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="${id}" name="Table ${id}">${creationIdXml()}</p:cNvPr>` +
'<p:cNvGraphicFramePr><a:graphicFrameLocks noGrp="1"/></p:cNvGraphicFramePr><p:nvPr/></p:nvGraphicFramePr>' +
+49
View File
@@ -15,6 +15,7 @@ import {
resolvePlaceholderPresetGeom,
resolvePlaceholderTransform,
resolvePlaceholderAnchor,
resolvePlaceholderAnchorCtr,
resolvePlaceholderInsets,
resolvePlaceholderFillSpPr,
parseLstStyleLevels,
@@ -406,6 +407,15 @@ function parseSpShape(
)
if (inherited) text.anchor = inherited
}
if (ph && text && text.anchorCtr == null) {
const inherited = resolvePlaceholderAnchorCtr(
ctx.layoutPlaceholders,
ctx.masterPlaceholders,
phType,
phIdx,
)
if (inherited != null) text.anchorCtr = inherited
}
let stroke = parseStroke(spPr, ctx)
let shadow = parseShadow(spPr, ctx)
@@ -3109,9 +3119,29 @@ function parseTextBody(
}
}
// WordArt preset text warp (<a:prstTxWarp prst avLst>): read-only display, the original
// bodyPr bytes carry it through save
let txWarp: TextBody['txWarp']
const warpNode = bodyPr['a:prstTxWarp']
if (warpNode && typeof warpNode === 'object' && warpNode['@_prst']) {
const prst = String(warpNode['@_prst'])
if (prst !== 'textNoShape' && prst !== 'textPlain') {
const adj: Record<string, number> = {}
const gds = warpNode['a:avLst']?.['a:gd']
for (const gd of Array.isArray(gds) ? gds : gds ? [gds] : []) {
const m = /^val (-?\d+)$/.exec(String(gd['@_fmla'] ?? ''))
if (gd['@_name'] && m) adj[String(gd['@_name'])] = parseInt(m[1]!, 10)
}
txWarp = { prst, ...(Object.keys(adj).length ? { adj } : {}) }
}
}
return {
paragraphs,
anchor: bodyPr['@_anchor'] ? anchorMap[bodyPr['@_anchor']] : undefined,
...(bodyPr['@_anchorCtr'] != null
? { anchorCtr: String(bodyPr['@_anchorCtr']) === '1' || bodyPr['@_anchorCtr'] === 'true' }
: {}),
insets: {
l: intOr(bodyPr['@_lIns'], inheritedInsets?.l ?? DEFAULT_BODY_INSETS.l),
t: intOr(bodyPr['@_tIns'], inheritedInsets?.t ?? DEFAULT_BODY_INSETS.t),
@@ -3127,6 +3157,7 @@ function parseTextBody(
? { numCol: intOr(bodyPr['@_numCol'], 1), spcCol: intOr(bodyPr['@_spcCol'], 0) }
: {}),
...(extrusion3d ? { extrusion3d } : {}),
...(txWarp ? { txWarp } : {}),
}
}
@@ -3219,14 +3250,26 @@ function parseParagraph(
}
const marLRaw = pPr['@_marL'] != null ? parseInt(pPr['@_marL'], 10) : undefined
const marRRaw = pPr['@_marR'] != null ? parseInt(pPr['@_marR'], 10) : undefined
const indentRaw = pPr['@_indent'] != null ? parseInt(pPr['@_indent'], 10) : undefined
const defTabSzRaw = pPr['@_defTabSz'] != null ? parseInt(pPr['@_defTabSz'], 10) : undefined
const tabNodes = pPr['a:tabLst']?.['a:tab']
const tabStops = (Array.isArray(tabNodes) ? tabNodes : tabNodes ? [tabNodes] : [])
.map((t: any) => ({
pos: parseInt(t['@_pos'], 10),
...(t['@_algn'] ? { algn: String(t['@_algn']) } : {}),
}))
.filter((t: { pos: number }) => Number.isFinite(t.pos))
.sort((a: { pos: number }, b: { pos: number }) => a.pos - b.pos)
// Inheritance fallback: explicit pPr wins, level defaults from the placeholder/lstStyle chain fill gaps
// (the master bodyStyle's buChar/marL/indent is where classic-template body bullets come from).
// No field-wise merge: a paragraph redefining its bullet resets unspecified buClr/buSzPct/buFont
// to follow the text (buClrTx/buSzTx/buFontTx semantics), not the chain's values.
const effBullet = bullet ?? dflt?.bullet
const hasMarL = marLRaw != null && !Number.isNaN(marLRaw)
const hasMarR = marRRaw != null && !Number.isNaN(marRRaw)
const hasIndent = indentRaw != null && !Number.isNaN(indentRaw)
const hasDefTabSz = defTabSzRaw != null && !Number.isNaN(defTabSzRaw)
const marL = hasMarL ? marLRaw : dflt?.marL
const indent = hasIndent ? indentRaw : dflt?.indent
@@ -3248,7 +3291,10 @@ function parseParagraph(
...(aftNode ? { spcAft: true } : {}),
...(bullet ? { bullet: true } : {}),
...(hasMarL ? { marL: true } : {}),
...(hasMarR ? { marR: true } : {}),
...(hasIndent ? { indent: true } : {}),
...(tabStops.length ? { tabLst: true } : {}),
...(hasDefTabSz ? { defTabSz: true } : {}),
}
return {
@@ -3265,7 +3311,10 @@ function parseParagraph(
...(spaceAfterPct != null ? { spaceAfterPct } : {}),
...(effBullet ? { bullet: effBullet } : {}),
...(marL != null ? { marL } : {}),
...(hasMarR ? { marR: marRRaw } : {}),
...(indent != null ? { indent } : {}),
...(tabStops.length ? { tabStops } : {}),
...(hasDefTabSz ? { defTabSz: defTabSzRaw } : {}),
}
}
+43 -1
View File
@@ -89,6 +89,8 @@ export interface PlaceholderGeom {
textStyle?: TextStyleLevels
/** Vertical anchor from this placeholder's <a:bodyPr anchor=""> */
anchor?: 'top' | 'middle' | 'bottom'
/** <a:bodyPr anchorCtr> (explicit 0 recorded too: it overrides an inherited 1) */
anchorCtr?: boolean
/** Explicit bodyPr inset attrs (EMU); slide bodyPr attrs missing these inherit per-attribute */
insets?: { l?: number; t?: number; r?: number; b?: number }
/** Raw spPr node when it carries an explicit fill (parse.ts resolves it with the part's rels) */
@@ -163,6 +165,9 @@ export function parsePlaceholderMap(layoutOrMasterXml: string, theme?: Theme): P
const textStyle = parseLstStyleLevels(asXmlNode(sp['p:txBody'])['a:lstStyle'], theme)
const bodyPrNode = asXmlNode(asXmlNode(sp['p:txBody'])['a:bodyPr'])
const anchor = ANCHOR_MAP[String(bodyPrNode['@_anchor'] ?? '')]
const anchorCtrRaw = bodyPrNode['@_anchorCtr']
const anchorCtr =
anchorCtrRaw != null ? String(anchorCtrRaw) === '1' || anchorCtrRaw === 'true' : undefined
const insEntries = (['l', 't', 'r', 'b'] as const).flatMap((k) => {
const v = bodyPrNode[`@_${k}Ins`]
const n = v != null ? parseInt(String(v), 10) : NaN
@@ -174,13 +179,23 @@ export function parsePlaceholderMap(layoutOrMasterXml: string, theme?: Theme): P
const prst = prstGeomNode['@_prst'] != null ? String(prstGeomNode['@_prst']) : undefined
const presetGeom =
prst && prst !== 'rect' ? { prst, avLstRaw: prstGeomNode['a:avLst'] } : undefined
if (!transform && !textStyle && !anchor && !insets && !hasFill && !presetGeom) continue
if (
!transform &&
!textStyle &&
!anchor &&
anchorCtr === undefined &&
!insets &&
!hasFill &&
!presetGeom
)
continue
entries.push({
type,
idx,
transform,
...(textStyle ? { textStyle } : {}),
...(anchor ? { anchor } : {}),
...(anchorCtr !== undefined ? { anchorCtr } : {}),
...(insets ? { insets } : {}),
...(hasFill ? { fillSpPr: spPr } : {}),
...(presetGeom ? { presetGeom } : {}),
@@ -429,6 +444,33 @@ export function resolvePlaceholderAnchor(
return findAnchorInMap(layout, type, idx) ?? findAnchorInMap(master, type, idx)
}
/** Same matching as findAnchorInMap for anchorCtr (an explicit 0 in the layout wins over a master 1). */
function findAnchorCtrInMap(
map: PlaceholderMap | undefined,
type: string | undefined,
idx: string | undefined,
): boolean | undefined {
if (!map || map.entries.length === 0) return undefined
const t = type ?? 'body'
const i = idx ?? ''
const marked = map.entries.filter((e) => e.anchorCtr !== undefined)
let hit = marked.find((e) => e.type === t && e.idx === i)
if (!hit) hit = marked.find((e) => e.type === t)
if (!hit && TITLE_TYPES.has(t)) hit = marked.find((e) => TITLE_TYPES.has(e.type))
if (!hit && BODY_TYPES.has(t)) hit = marked.find((e) => BODY_TYPES.has(e.type))
return hit?.anchorCtr
}
/** Resolve a placeholder's inherited anchorCtr: layout first, master as fallback. */
export function resolvePlaceholderAnchorCtr(
layout: PlaceholderMap | undefined,
master: PlaceholderMap | undefined,
type: string | undefined,
idx: string | undefined,
): boolean | undefined {
return findAnchorCtrInMap(layout, type, idx) ?? findAnchorCtrInMap(master, type, idx)
}
/**
* Placeholder text style inheritance chain (highest priority first):
* layout placeholder lstStyle → master placeholder lstStyle → master txStyles
+44 -15
View File
@@ -261,41 +261,70 @@ function setAttr(attrs: string, key: string, value: string | undefined): string
}
/** Apply the shading/border/clear parts of an edit to one tcPr's children. */
/** One ln* element in either form — self-closing or paired (they cannot nest). */
const LN_ELEMENT_RE =
/<a:(lnL|lnR|lnT|lnB|lnTlToBr|lnBlToTr)(?:\s[^>]*)?\/>|<a:(lnL|lnR|lnT|lnB|lnTlToBr|lnBlToTr)(?:\s[^>]*)?>.*?<\/a:\2>/gs
/** Transform only the segments outside ln* elements: a:ln* carry their own
solidFill children, so cell-fill edits must not reach inside them. */
function outsideLns(src: string, fn: (seg: string) => string): string {
let out = ''
let cursor = 0
for (const m of src.matchAll(LN_ELEMENT_RE)) {
out += fn(src.slice(cursor, m.index)) + m[0]
cursor = m.index + m[0].length
}
return out + fn(src.slice(cursor))
}
function applyTcPrEdit(inner: string, edit: TableStyleEdit): string {
if (edit.clearDirectFormatting) {
inner = inner.replace(/<a:(solidFill|gradFill|pattFill|blipFill)>.*?<\/a:\1>/gs, '')
inner = inner.replace(/<a:(solidFill|gradFill|pattFill|blipFill)(?:\s[^>]*)?>.*?<\/a:\1>/gs, '')
inner = inner.replace(/<a:(noFill|grpFill)\/>/g, '')
inner = inner.replace(/<a:(lnL|lnR|lnT|lnB|lnTlToBr|lnBlToTr)(\s[^>]*)?\/>/g, '')
inner = inner.replace(/<a:(lnL|lnR|lnT|lnB|lnTlToBr|lnBlToTr)(\s[^>]*)?>.*?<\/a:\1>/gs, '')
}
// Remove existing fill nodes
// CT_TableCellProperties is a sequence: ln* → cell3D → fill → headers/extLst.
// Misplaced children make the part schema-invalid and PowerPoint offers repair.
const insertFill = (fill: string) => {
const at = inner.search(/<a:(headers|extLst)[\s>/]/)
return at >= 0 ? inner.slice(0, at) + fill + inner.slice(at) : inner + fill
}
const insertLns = (lns: string) => {
const at = inner.search(
/<a:(lnTlToBr|lnBlToTr|cell3D|solidFill|gradFill|pattFill|blipFill|noFill|grpFill|headers|extLst)[\s>/]/,
)
return at >= 0 ? inner.slice(0, at) + lns + inner.slice(at) : inner + lns
}
// Replace existing cell-level fill nodes (border fills stay untouched)
if (edit.shadingColor !== undefined) {
inner = inner.replace(/<a:solidFill>.*?<\/a:solidFill>/gs, '')
inner = inner.replace(/<a:noFill\/>/g, '')
inner = inner.replace(/<a:noFill><\/a:noFill>/g, '')
inner = outsideLns(inner, (seg) =>
seg
.replace(/<a:(solidFill|gradFill|pattFill|blipFill)(?:\s[^>]*)?>.*?<\/a:\1>/gs, '')
.replace(/<a:(noFill|grpFill)\/>/g, '')
.replace(/<a:(noFill|grpFill)><\/a:\1>/g, ''),
)
if (edit.shadingColor === 'none') {
inner = '<a:noFill/>' + inner
inner = insertFill('<a:noFill/>')
} else if (edit.shadingColor) {
const c = edit.shadingColor.replace('#', '').toUpperCase()
inner = `<a:solidFill><a:srgbClr val="${c}"/></a:solidFill>` + inner
inner = insertFill(`<a:solidFill><a:srgbClr val="${c}"/></a:solidFill>`)
}
}
// Border handling
if (edit.borderPreset !== undefined) {
inner = inner.replace(/<a:lnL[^>]*>.*?<\/a:lnL>/gs, '')
inner = inner.replace(/<a:lnR[^>]*>.*?<\/a:lnR>/gs, '')
inner = inner.replace(/<a:lnT[^>]*>.*?<\/a:lnT>/gs, '')
inner = inner.replace(/<a:lnB[^>]*>.*?<\/a:lnB>/gs, '')
inner = inner.replace(/<a:(lnL|lnR|lnT|lnB)(?:\s[^>]*)?\/>/g, '')
inner = inner.replace(/<a:(lnL|lnR|lnT|lnB)(?:\s[^>]*)?>.*?<\/a:\1>/gs, '')
if (edit.borderPreset === 'all' && edit.borderColor) {
const c = edit.borderColor.replace('#', '').toUpperCase()
const w = edit.borderWidthEmu ?? 12700
const lnXml = (tag: string) =>
`<${tag} w="${w}"><a:solidFill><a:srgbClr val="${c}"/></a:solidFill></${tag}>`
inner = inner + lnXml('a:lnL') + lnXml('a:lnR') + lnXml('a:lnT') + lnXml('a:lnB')
inner = insertLns(lnXml('a:lnL') + lnXml('a:lnR') + lnXml('a:lnT') + lnXml('a:lnB'))
} else if (edit.borderPreset === 'none') {
inner =
inner +
'<a:lnL w="0"><a:noFill/></a:lnL><a:lnR w="0"><a:noFill/></a:lnR><a:lnT w="0"><a:noFill/></a:lnT><a:lnB w="0"><a:noFill/></a:lnB>'
inner = insertLns(
'<a:lnL w="0"><a:noFill/></a:lnL><a:lnR w="0"><a:noFill/></a:lnR><a:lnT w="0"><a:noFill/></a:lnT><a:lnB w="0"><a:noFill/></a:lnB>',
)
}
}
return inner
+13
View File
@@ -279,8 +279,14 @@ export interface Paragraph {
}
/** Paragraph left indent marL (EMU) */
marL?: number
/** Paragraph right indent marR (EMU) */
marR?: number
/** First-line indent (EMU, negative = hanging indent, common with bullets) */
indent?: number
/** <a:tabLst> custom tab stops (EMU from the text-frame left inset; laid out as left stops) */
tabStops?: Array<{ pos: number; algn?: string }>
/** <a:pPr defTabSz>: default tab grid (EMU, PowerPoint default 914400 = 1") */
defTabSz?: number
/**
* Which paragraph properties come from an explicit <a:pPr> (rather than display
* values inherited from lstStyle/placeholder/master). The rebuild path writes
@@ -295,7 +301,10 @@ export interface Paragraph {
spcAft?: boolean
bullet?: boolean
marL?: boolean
marR?: boolean
indent?: boolean
tabLst?: boolean
defTabSz?: boolean
}
}
@@ -304,6 +313,8 @@ export interface TextBody {
paragraphs: Paragraph[]
/** Vertical alignment */
anchor?: 'top' | 'middle' | 'bottom'
/** <a:bodyPr anchorCtr="1">: center the text block's bounding box horizontally */
anchorCtr?: boolean
/** Insets (EMU): left/top/right/bottom */
insets?: { l: number; t: number; r: number; b: number }
/** Autofit: none | shrink font to fit | resize box */
@@ -321,6 +332,8 @@ export interface TextBody {
spcCol?: number
/** <a:bodyPr><a:scene3d>+<a:sp3d>: WordArt text extrusion (camera angles in degrees) */
extrusion3d?: { color: ResolvedColor; depthEmu: number; latDeg: number; lonDeg: number }
/** <a:bodyPr><a:prstTxWarp>: WordArt envelope warp (display only; saved via original bytes) */
txWarp?: { prst: string; adj?: Record<string, number> }
}
// ── Elements ───────────────────────────────────────────────────────────
+15 -1
View File
@@ -19,8 +19,22 @@ export function xmlArray(v: unknown): XmlNode[] {
return v ? [asXmlNode(v)] : []
}
/** XML 1.0 forbids C0 controls (minus tab/LF/CR), U+FFFE/FFFF and lone
surrogates even when escaped — one such byte makes the whole part
unparseable and PowerPoint offers repair. VT/FF (common in PDF-extracted
text) degrade to a space; the rest have no textual meaning and drop. */
// eslint-disable-next-line no-control-regex -- the forbidden chars are the subject
const XML_INVALID_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]|\p{Cs}/gu
function sanitizeXmlChars(text: string): string {
XML_INVALID_CHARS.lastIndex = 0
if (!XML_INVALID_CHARS.test(text)) return text
XML_INVALID_CHARS.lastIndex = 0
return text.replace(XML_INVALID_CHARS, (ch) => (ch === '\u000B' || ch === '\u000C' ? ' ' : ''))
}
export function escapeXmlText(text: string): string {
return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
return sanitizeXmlChars(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}
export function escapeXmlAttr(text: string): string {
+74
View File
@@ -844,3 +844,77 @@ describe('category tick skips', () => {
expect(m.catAxis?.tickMarkSkip).toBe(192)
})
})
describe('buildChartSpaceXml colorScheme / holeSizePct (genpptx parity)', () => {
const BASE2 = {
kind: 'bar' as const,
categories: ['A', 'B'],
series: [
{ name: 'S1', values: [1, 2] },
{ name: 'S2', values: [3, 4] },
],
offset: { x: 0, y: 0, cx: 100, cy: 100 },
}
it('per-series spPr lands at the schema position (after c:tx, before c:cat) and round-trips', () => {
const xml = buildChartSpaceXml({ ...BASE2, colorScheme: ['#C00000', '#00B050'] })
expect(xml).toMatch(
/<c:ser><c:idx val="0"\/><c:order val="0"\/><c:tx>.*?<\/c:tx><c:spPr><a:solidFill><a:srgbClr val="C00000"\/><\/a:solidFill><\/c:spPr><c:cat>/s,
)
const m = parseChartXml(xml)!
expect(m.series.map((s) => s.color)).toEqual(['#C00000', '#00B050'])
})
it('colors cycle over the series when the scheme is shorter', () => {
const xml = buildChartSpaceXml({ ...BASE2, colorScheme: ['#112233'] })
const m = parseChartXml(xml)!
expect(m.series.map((s) => s.color)).toEqual(['#112233', '#112233'])
})
it('combo chart: the line series gets a stroke color, not a fill', () => {
const xml = buildChartSpaceXml({
...BASE2,
kind: 'comboBarLine',
colorScheme: ['#C00000', '#0070C0'],
})
expect(xml).toMatch(
/<c:lineChart>.*?<c:spPr><a:ln w="28575"><a:solidFill><a:srgbClr val="0070C0"\/><\/a:solidFill><\/a:ln><\/c:spPr>/s,
)
})
it('doughnut holeSizePct is written and round-trips (clamped to 1..90)', () => {
const opts = { ...BASE2, kind: 'doughnut' as const }
expect(buildChartSpaceXml({ ...opts, holeSizePct: 72 })).toContain('<c:holeSize val="72"/>')
expect(buildChartSpaceXml(opts)).toContain('<c:holeSize val="50"/>')
expect(buildChartSpaceXml({ ...opts, holeSizePct: 400 })).toContain('<c:holeSize val="90"/>')
const m = parseChartXml(buildChartSpaceXml({ ...opts, holeSizePct: 72 }))!
expect(m.holePct).toBe(72)
})
})
describe('colorScheme on line-family kinds (Bugbot: fill-only spPr keeps theme line colors)', () => {
it('plain line chart series get stroke colors, not fills', () => {
const xml = buildChartSpaceXml({
kind: 'line',
categories: ['A', 'B'],
series: [{ name: 'S1', values: [1, 2] }],
offset: { x: 0, y: 0, cx: 100, cy: 100 },
colorScheme: ['#FF00FF'],
})
expect(xml).toContain('<c:spPr><a:ln w="28575"><a:solidFill><a:srgbClr val="FF00FF"/>')
expect(xml).not.toMatch(/<c:spPr><a:solidFill>/)
})
it('scatter and radar are line-family too', () => {
for (const kind of ['scatter', 'radar'] as const) {
const xml = buildChartSpaceXml({
kind,
categories: ['1', '2'],
series: [{ name: 'S', values: [3, 4] }],
offset: { x: 0, y: 0, cx: 100, cy: 100 },
colorScheme: ['#123456'],
})
expect(xml, kind).toContain('<a:ln w="28575"><a:solidFill><a:srgbClr val="123456"/>')
}
})
})
@@ -873,3 +873,45 @@ describe('3-D chart kinds survive insert and edit round-trips', () => {
expect(el.chart.categories).toEqual(['A', 'B', 'C'])
})
})
describe('editChartElement doughnut hole preservation', () => {
it('a custom holeSizePct survives a data-only rebuild and is patchable', async () => {
const opened = await openPptx(fx('01_standard_business.pptx'))
const r = addChart(opened, 0, {
kind: 'doughnut',
categories: ['A', 'B'],
series: [{ name: 'S', values: [1, 2] }],
offset: { ...OFF },
holeSizePct: 72,
})!
const chartXml = (path: string) => {
const rels = opened.archive.readText(relsPathFor('ppt/slides/slide1.xml'))!
const target = /Target="([^"]*chart\d+\.xml)"/.exec(rels)![1]!
return opened.archive.readText(path || `ppt/charts/${target.split('/').pop()}`)!
}
expect(chartXml('')).toContain('<c:holeSize val="72"/>')
// Data-only edit: the hole used to reset to the build default (50)
expect(editChartElement(opened, 0, r.elementId, { categories: ['A', 'B', 'C'] })).toBe(true)
expect(chartXml('')).toContain('<c:holeSize val="72"/>')
// Explicit patch wins
expect(editChartElement(opened, 0, r.elementId, { holeSizePct: 30 })).toBe(true)
expect(chartXml('')).toContain('<c:holeSize val="30"/>')
})
})
describe('pie → doughnut type switch (Bugbot: parsed pie holePct 0 must not clamp to a 1% hole)', () => {
it('switching a pie to doughnut gets the default 50% hole', async () => {
const opened = await openPptx(fx('01_standard_business.pptx'))
const r = addChart(opened, 0, {
kind: 'pie',
categories: ['A', 'B'],
series: [{ name: 'S', values: [1, 2] }],
offset: { ...OFF },
})!
expect(editChartElement(opened, 0, r.elementId, { kind: 'doughnut' })).toBe(true)
const rels = opened.archive.readText(relsPathFor('ppt/slides/slide1.xml'))!
const target = /Target="([^"]*chart\d+\.xml)"/.exec(rels)![1]!
const xml = opened.archive.readText(`ppt/charts/${target.split('/').pop()}`)!
expect(xml).toContain('<c:holeSize val="50"/>')
})
})
+108 -1
View File
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { openPptx, savePptx, addElement, deleteElement } from '../src/index'
import { openPptx, savePptx, addElement, addTable, deleteElement } from '../src/index'
const here = dirname(fileURLToPath(import.meta.url))
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
@@ -92,3 +92,110 @@ describe('add/delete element', () => {
expect(slide.structureDirty).toBe(true)
})
})
describe('insert-time shape options (genpptx parity)', () => {
it('adjustments write prstGeom avLst guides and round-trip', async () => {
const opened = await openPptx(fx('01_standard_business.pptx'))
const slide = opened.deck.slides[0]!
const el = addElement(slide, {
kind: 'roundRect',
offset: { ...OFF },
adjustments: { adj: 25000 },
})
expect(el.anchor.originalXml).toContain(
'<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 25000"/></a:avLst></a:prstGeom>',
)
// The in-memory model must carry the guides too, or shape handles reset them
expect(el.adjust).toEqual({ adj: 25000 })
const reopened = await openPptx(await savePptx(opened))
const el2: any = reopened.deck.slides[0]!.elements.at(-1)
expect(el2.presetGeometry).toBe('roundRect')
expect(el2.anchor.originalXml).toContain('fmla="val 25000"')
expect(el2.adjust).toEqual({ adj: 25000 })
})
it('connector kinds carry adjustments into avLst and the model', async () => {
const opened = await openPptx(fx('01_standard_business.pptx'))
const slide = opened.deck.slides[0]!
const el = addElement(slide, {
kind: 'lineBent',
offset: { ...OFF },
adjustments: { adj1: 30000 },
})
expect(el.anchor.originalXml).toContain(
'<a:prstGeom prst="bentConnector3"><a:avLst><a:gd name="adj1" fmla="val 30000"/></a:avLst></a:prstGeom>',
)
expect(el.adjust).toEqual({ adj1: 30000 })
})
it('bodyPr autoFit "shrink"/"resize" emit normAutofit/spAutoFit children', async () => {
const opened = await openPptx(fx('01_standard_business.pptx'))
const slide = opened.deck.slides[0]!
const shrink = addElement(slide, {
kind: 'textbox',
offset: { ...OFF },
paragraphs: [{ runs: [{ text: 'x' }] }],
bodyPr: { autoFit: 'shrink' },
})
expect(shrink.anchor.originalXml).toContain('<a:normAutofit/></a:bodyPr>')
expect(shrink.text!.autofit).toBe('shrink')
const grow = addElement(slide, {
kind: 'textbox',
offset: { ...OFF },
bodyPr: { anchor: 'ctr', autoFit: 'resize' },
})
expect(grow.anchor.originalXml).toContain('anchor="ctr"><a:spAutoFit/></a:bodyPr>')
expect(grow.text!.autofit).toBe('resize')
})
})
describe('addTable explicit grid options (genpptx parity)', () => {
it('length-matched colWidthsEmu/rowHeightsEmu override the equal split', async () => {
const opened = await openPptx(fx('01_standard_business.pptx'))
const r = addTable(opened, 0, {
rows: 2,
cols: 2,
offset: { x: 0, y: 0, cx: 3000000, cy: 1000000 },
colWidthsEmu: [1000000, 2000000],
rowHeightsEmu: [400000, 600000],
})!
const el: any = opened.deck.slides[0]!.elements.find((e) => e.id === r.elementId)
expect(el.anchor.originalXml).toContain('<a:gridCol w="1000000"/><a:gridCol w="2000000"/>')
expect(el.anchor.originalXml).toContain('<a:tr h="400000">')
expect(el.anchor.originalXml).toContain('<a:tr h="600000">')
})
it('cellProps write merges and vertical anchors per cell', async () => {
const opened = await openPptx(fx('01_standard_business.pptx'))
const r = addTable(opened, 0, {
rows: 2,
cols: 2,
offset: { x: 0, y: 0, cx: 2000000, cy: 1000000 },
cellProps: [
[{ gridSpan: 2, anchor: 'ctr' }, { hMerge: true }],
[undefined, { anchor: 'b' }],
],
})!
const xml = (opened.deck.slides[0]!.elements.find((e) => e.id === r.elementId) as any).anchor
.originalXml as string
expect(xml).toContain('<a:tc gridSpan="2">')
expect(xml).toContain('<a:tc hMerge="1">')
expect(xml).toContain('<a:tcPr anchor="ctr"/>')
expect(xml).toContain('<a:tcPr anchor="b"/>')
const reopened = await openPptx(await savePptx(opened))
const tbl: any = reopened.deck.slides[0]!.elements.at(-1)
expect(tbl.type).toBe('table')
})
it('length-mismatched lists fall back to the equal split', async () => {
const opened = await openPptx(fx('01_standard_business.pptx'))
const r = addTable(opened, 0, {
rows: 2,
cols: 3,
offset: { x: 0, y: 0, cx: 3000000, cy: 1000000 },
colWidthsEmu: [1, 2],
})!
const el: any = opened.deck.slides[0]!.elements.find((e) => e.id === r.elementId)
expect(el.anchor.originalXml).toContain('<a:gridCol w="1000000"/>'.repeat(3))
})
})
@@ -0,0 +1,56 @@
/** pPr marR / tabLst / defTabSz: parse + rebuild round-trip. */
import { describe, it, expect } from 'vitest'
import { parseSlide } from '../src/parse'
import { generateParagraphXml } from '../src/generate'
import type { TextElement } from '../src/types'
const slideWith = (sp: string) =>
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld>' +
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${sp}</p:spTree></p:cSld></p:sld>`
const spWith = (txBodyInner: string) =>
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
`<p:txBody>${txBodyInner}</p:txBody></p:sp>`
const parseOne = (txBodyInner: string) => {
const slide = parseSlide({
path: 'ppt/slides/slide1.xml',
slideXml: slideWith(spWith(txBodyInner)),
ctx: {},
})
return slide.elements[0] as TextElement
}
describe('pPr marR / tabLst / defTabSz', () => {
it('parses marR, defTabSz and sorted tab stops', () => {
const el = parseOne(
'<a:bodyPr/><a:p><a:pPr marR="4128770" defTabSz="457200">' +
'<a:tabLst><a:tab pos="3384550" algn="l"/><a:tab pos="914400"/></a:tabLst>' +
'</a:pPr><a:r><a:t>x</a:t></a:r></a:p>',
)
const p = el.text!.paragraphs[0]!
expect(p.marR).toBe(4128770)
expect(p.defTabSz).toBe(457200)
expect(p.tabStops).toEqual([{ pos: 914400 }, { pos: 3384550, algn: 'l' }])
expect(p.pPrExplicit).toMatchObject({ marR: true, tabLst: true, defTabSz: true })
})
it('rebuild keeps marR/defTabSz attributes and the tabLst child', () => {
const el = parseOne(
'<a:bodyPr/><a:p><a:pPr marL="12700" marR="5080" defTabSz="457200">' +
'<a:tabLst><a:tab pos="3384550" algn="l"/></a:tabLst>' +
'</a:pPr><a:r><a:t>x</a:t></a:r></a:p>',
)
const xml = generateParagraphXml(el.text!.paragraphs[0]!)
expect(xml).toContain('marR="5080"')
expect(xml).toContain('defTabSz="457200"')
expect(xml).toContain('<a:tabLst><a:tab pos="3384550" algn="l"/></a:tabLst>')
})
it('paragraphs without them write none (no baked-in defaults)', () => {
const el = parseOne('<a:bodyPr/><a:p><a:pPr marL="12700"/><a:r><a:t>x</a:t></a:r></a:p>')
const xml = generateParagraphXml(el.text!.paragraphs[0]!)
expect(xml).not.toContain('marR=')
expect(xml).not.toContain('defTabSz=')
expect(xml).not.toContain('tabLst')
})
})
@@ -258,3 +258,78 @@ describe('custom table style outer borders (tcBdr left/right/top/bottom)', () =>
expect(def.insideH?.fill).toEqual({ type: 'solid', color: '#9E9E9E' })
})
})
describe('tcPr child order (CT_TableCellProperties is a sequence: ln* before fill)', () => {
it('borders added to a filled cell land before the cell fill node', () => {
const result = patchTableStyleXml(MINIMAL_TABLE_XML, {
borderPreset: 'all',
borderColor: '#000000',
})
const tcPr = result.slice(result.indexOf('<a:tcPr'), result.indexOf('</a:tcPr>'))
expect(tcPr.indexOf('<a:lnB')).toBeGreaterThan(-1)
expect(tcPr.indexOf('<a:lnB')).toBeLessThan(tcPr.indexOf('FF0000'))
})
it('clear-borders on a filled cell also lands before the cell fill node', () => {
const result = patchTableStyleXml(MINIMAL_TABLE_XML, { borderPreset: 'none' })
const tcPr = result.slice(result.indexOf('<a:tcPr'), result.indexOf('</a:tcPr>'))
expect(tcPr.indexOf('<a:lnL')).toBeLessThan(tcPr.indexOf('FF0000'))
})
it('shading added to a bordered cell lands after the ln* nodes and keeps border colors', () => {
const bordered = patchTableStyleXml(MINIMAL_TABLE_XML, {
borderPreset: 'all',
borderColor: '#00FF00',
})
const result = patchTableStyleXml(bordered, { shadingColor: '#AABBCC' })
const tcPr = result.slice(result.indexOf('<a:tcPr'), result.indexOf('</a:tcPr>'))
expect(tcPr.indexOf('AABBCC')).toBeGreaterThan(tcPr.lastIndexOf('<a:lnB'))
// Border fills are the ln elements' own children — shading must not eat them
expect((tcPr.match(/00FF00/g) ?? []).length).toBe(4)
})
it('a self-closing ln element is replaced, not duplicated', () => {
const selfClosing = MINIMAL_TABLE_XML.replace('<a:tcPr>', '<a:tcPr><a:lnB w="0"/>')
const result = patchTableStyleXml(selfClosing, {
borderPreset: 'all',
borderColor: '#000000',
})
const tcPr = result.slice(result.indexOf('<a:tcPr'), result.indexOf('</a:tcPr>'))
expect((tcPr.match(/<a:lnB[\s>]/g) ?? []).length).toBe(1)
expect(tcPr).not.toContain('<a:lnB w="0"/>')
})
it('shading replaces a gradient fill instead of stacking a second fill node', () => {
const grad = MINIMAL_TABLE_XML.replace(
'<a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>',
'<a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs></a:gsLst></a:gradFill>',
)
const result = patchTableStyleXml(grad, { shadingColor: '#AABBCC' })
expect(result).not.toContain('gradFill')
expect(result).toContain('AABBCC')
})
})
describe('fill strip matches attributed fill tags (Bugbot: gradFill almost always carries rotWithShape)', () => {
it('shading replaces an attributed gradFill instead of stacking a second fill', () => {
const grad = MINIMAL_TABLE_XML.replace(
'<a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>',
'<a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs></a:gsLst></a:gradFill>',
)
const result = patchTableStyleXml(grad, { shadingColor: '#AABBCC' })
expect(result).not.toContain('gradFill')
expect(result).toContain('AABBCC')
})
it('clearDirectFormatting also strips an attributed pattFill', () => {
const patt = MINIMAL_TABLE_XML.replace(
'<a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>',
'<a:pattFill prst="pct5"><a:fgClr><a:srgbClr val="FF0000"/></a:fgClr></a:pattFill>',
)
const result = patchTableStyleXml(patt, {
tblPrXml: TABLE_STYLE_PRESETS['zebraGray']!.tblPrXml,
clearDirectFormatting: true,
})
expect(result).not.toContain('pattFill')
})
})
@@ -0,0 +1,28 @@
import { describe, it, expect } from 'vitest'
import { escapeXmlText, escapeXmlAttr } from '../src/xml-utils'
describe('escapeXmlText XML 1.0 character defence', () => {
it('escapes markup characters', () => {
expect(escapeXmlText('a<b>&c')).toBe('a&lt;b&gt;&amp;c')
})
it('degrades VT/FF (PDF-extracted text) to a space', () => {
expect(escapeXmlText(`para${String.fromCharCode(0x0b)}break`)).toBe('para break')
expect(escapeXmlText(`page${String.fromCharCode(0x0c)}feed`)).toBe('page feed')
})
it('drops other forbidden chars: C0 controls, U+FFFE/FFFF, lone surrogates', () => {
expect(escapeXmlText(`a${String.fromCharCode(0)}b${String.fromCharCode(8)}c`)).toBe('abc')
expect(escapeXmlText('x￾y￿z')).toBe('xyz')
expect(escapeXmlText('a\uD800b')).toBe('ab')
})
it('keeps legal whitespace and paired surrogates', () => {
expect(escapeXmlText('a\tb\nc\rd')).toBe('a\tb\nc\rd')
expect(escapeXmlText('emoji \u{1F600}!')).toBe('emoji \u{1F600}!')
})
it('escapeXmlAttr inherits the defence', () => {
expect(escapeXmlAttr(`n${String.fromCharCode(1)}"q"`)).toBe('n&quot;q&quot;')
})
})