Sync snapshot (2026-08-16) (#99)
- Docs: print dialog with live preview, EMF/WMF rendering, nested tables, margin comments, Word-style table UX - Slides: chart and SmartArt fidelity overhaul, Format Background pane, Shape Tools tab, PowerPoint line-spacing model - Sheets: ribbon batches (themes, page breaks, protection, goal seek), AI formula audit and workbook search, import fidelity fixes - PDF: comments margin with in-place note editing - UI: unified color pickers and save icon across apps (icon by @ulangmeier in #96) Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
e4d9d407c1
commit
04a994b9e9
@@ -16,7 +16,7 @@
|
||||
*/
|
||||
import { XMLParser } from 'fast-xml-parser'
|
||||
import { type Theme } from './theme'
|
||||
import { resolveColorNode } from './color'
|
||||
import { resolveColorNode, scaleLuminance } from './color'
|
||||
import type { Fill } from './types'
|
||||
|
||||
const chartParser = new XMLParser({
|
||||
@@ -27,7 +27,8 @@ const chartParser = new XMLParser({
|
||||
isArray: (name) => ['c:ser', 'c:pt', 'c:lvl', 'c:dPt'].includes(name),
|
||||
})
|
||||
|
||||
export type ChartKind = 'line' | 'bar' | 'pie' | 'area' | 'scatter' | 'radar' | 'unknown'
|
||||
export type ChartKind =
|
||||
'line' | 'bar' | 'pie' | 'area' | 'scatter' | 'radar' | 'funnel' | 'sunburst' | 'unknown'
|
||||
|
||||
export interface ChartSeries {
|
||||
name?: string
|
||||
@@ -38,15 +39,31 @@ export interface ChartSeries {
|
||||
plotKind?: 'line' | 'bar' | 'area'
|
||||
/** Scatter: x values (c:xVal numeric cache; y values in values). Empty → render layer uses ordinals 1..n */
|
||||
xValues?: Array<number | null>
|
||||
/** Bubble: per-point sizes (c:bubbleSize); marker radius ∝ √size (area represents value) */
|
||||
bubbleSizes?: Array<number | null>
|
||||
/** Line: smoothed curve */
|
||||
smooth?: boolean
|
||||
/** c:idx: automatic palette colors key off this, not document order */
|
||||
paletteIdx?: number
|
||||
/** Per-series data-label visibility (own c:dLbls, else the plot-level c:dLbls); undefined = fall back to the chart-level flag */
|
||||
dataLabels?: boolean
|
||||
/** Line/scatter series stroke dash (c:spPr a:prstDash, non-solid only) */
|
||||
dash?: string
|
||||
/** Line/scatter series stroke width (pt, c:spPr a:ln @w) */
|
||||
lineWidthPt?: number
|
||||
/** Whether to draw data point markers (line defaults to false; scatter/radar default
|
||||
* comes from the style; only set when <c:marker><c:symbol> is explicit) */
|
||||
marker?: boolean
|
||||
/** Explicit per-point colors <c:dPt> (common for pies; render layer palette otherwise) */
|
||||
pointColors?: Array<string | undefined>
|
||||
/** Pie: slice offset from center as percent of diameter (series-level c:explosion → all slices) */
|
||||
explosionPct?: number
|
||||
/** Pie: per-point explosion overrides (c:dPt/c:explosion) */
|
||||
pointExplosionPct?: Array<number | undefined>
|
||||
/** Combo dual axes: this series is on the secondary value axis (independent right-side range; decided by the plot's c:axId) */
|
||||
secondaryAxis?: boolean
|
||||
/** Series belongs to c:stockChart: no connecting lines, participates in whisker/up-down-bar roles */
|
||||
fromStock?: boolean
|
||||
}
|
||||
|
||||
export interface ChartAxisStyle {
|
||||
@@ -55,12 +72,32 @@ export interface ChartAxisStyle {
|
||||
max?: number
|
||||
labelColor?: string
|
||||
labelSizePt?: number
|
||||
labelBold?: boolean
|
||||
/** Explicit tick-label rotation from txPr bodyPr rot (degrees, e.g. -45) */
|
||||
labelRotDeg?: number
|
||||
/** <c:delete val="1"/>: axis hidden (no tick labels or axis line) but its scale still applies */
|
||||
hidden?: boolean
|
||||
/** Tick labels off (<c:tickLblPos val="none"/>): no labels, no reserved space */
|
||||
tickLblHidden?: boolean
|
||||
/** Labels not rendered but their space still reserved (invalid txPr baseline sentinel) */
|
||||
tickLblGarbage?: boolean
|
||||
/** <c:numFmt formatCode>: source-linked data labels format numbers with this (omitted for "General") */
|
||||
numFmt?: string
|
||||
lineColor?: string
|
||||
gridColor?: string
|
||||
gridDash?: boolean
|
||||
/** prstDash value (dash/dashDot/sysDash/...) for a finer dash pattern */
|
||||
gridDashVal?: string
|
||||
/** Explicit major gridline width (EMU) */
|
||||
gridWidthEmu?: number
|
||||
/** Minor gridlines: only drawn with an explicit color (PowerPoint hides them by default) */
|
||||
minorGridColor?: string
|
||||
minorGridWidthEmu?: number
|
||||
title?: string
|
||||
/** <c:orientation val="maxMin"/>: categories/values reversed (common for bar charts with the first category on top) */
|
||||
reversed?: boolean
|
||||
/** The category axis is a c:dateAx (PowerPoint rotates its labels as soon as they collide) */
|
||||
isDate?: boolean
|
||||
}
|
||||
|
||||
export interface ChartModel {
|
||||
@@ -74,6 +111,13 @@ export interface ChartModel {
|
||||
series: ChartSeries[]
|
||||
/** Legend position (undefined when there is no c:legend) */
|
||||
legendPos?: 't' | 'b' | 'l' | 'r' | 'tr'
|
||||
/** Legend text size (pt) from c:legend/c:txPr default run properties */
|
||||
legendPt?: number
|
||||
legendBold?: boolean
|
||||
/** <c:legend><c:overlay val="1"/>: the legend floats over the plot, reserving no space */
|
||||
legendOverlay?: boolean
|
||||
/** Plot-area inner rectangle (c:plotArea/c:layout/c:manualLayout layoutTarget=inner), fractions of the chart frame */
|
||||
plotLayout?: { x: number; y: number; w: number; h: number }
|
||||
valAxis?: ChartAxisStyle
|
||||
/** Secondary value axis (right side, combo column+line dual axes; undefined without a right value axis or style info) */
|
||||
valAxis2?: ChartAxisStyle
|
||||
@@ -86,16 +130,62 @@ export interface ChartModel {
|
||||
scatterStyle?: string
|
||||
/** Radar style (c:radarStyle) */
|
||||
radarStyle?: 'standard' | 'marker' | 'filled'
|
||||
/** Multi-level category axis: outer-level group labels with their starting leaf index */
|
||||
categoryGroups?: Array<{ label: string; start: number }>
|
||||
/** Data labels (showVal or showPercent on plot/ser-level c:dLbls) */
|
||||
dataLabels?: boolean
|
||||
/** Data labels show percentages only (showPercent only, common for pies) */
|
||||
dataLabelsPct?: boolean
|
||||
/** Data labels include the series name / category name (c:showSerName / c:showCatName) */
|
||||
dataLabelSerName?: boolean
|
||||
dataLabelCatName?: boolean
|
||||
/** Data labels omit the value itself (name-only labels) */
|
||||
dataLabelNoValue?: boolean
|
||||
/** Data-label number format (c:dLbls/c:numFmt formatCode, else the value axis's; omitted for "General") */
|
||||
dataLabelFmt?: string
|
||||
/** Data-label text size (pt) / bold from c:dLbls/c:txPr */
|
||||
dataLabelPt?: number
|
||||
dataLabelBold?: boolean
|
||||
/** Chart title (concatenated rich text of c:chart/c:title) */
|
||||
title?: string
|
||||
/** Title font size (pt) from c:title/c:txPr default run properties */
|
||||
titlePt?: number
|
||||
/** <c:title><c:overlay val="1"/>: the title floats over the plot, reserving no space */
|
||||
titleOverlay?: boolean
|
||||
/** chartSpace-level <c:spPr> fill (whole-chart background, e.g. picture fill) */
|
||||
bgFill?: Fill
|
||||
/** Plot-area fill (c:plotArea's own spPr) */
|
||||
plotFill?: Fill
|
||||
/** Plot-area border (c:plotArea spPr ln) */
|
||||
plotBorder?: { color: string; widthEmu: number }
|
||||
/** chartSpace-level <c:spPr><a:ln> frame border around the whole chart */
|
||||
border?: { color: string; widthEmu: number }
|
||||
/** Theme accent1..6 resolved to #RRGGBB (default series/wedge colors, PowerPoint varyColors order) */
|
||||
themePalette?: string[]
|
||||
/** Pie: explicit <c:varyColors val="0"/> — every wedge uses the series color */
|
||||
varyColors?: boolean
|
||||
/** Bubble: <c:bubbleScale> % (default 100), scales the largest bubble's diameter */
|
||||
bubbleScale?: number
|
||||
/** Bubble: <c:sizeRepresents val="w"/> — size maps to diameter instead of area */
|
||||
bubbleSizeIsWidth?: boolean
|
||||
/** Stock chart: series are (open,)high,low,close roles in document order */
|
||||
stock?: { hiLowLines: boolean; upDownBars: boolean; gapWidthPct?: number }
|
||||
/** Sunburst (chartEx): levels leaf-first as stored (levels[0][i] = leaf label of point i,
|
||||
* later levels = ancestors); '' = the point ends at a shallower depth. sizes align by point. */
|
||||
sunburst?: {
|
||||
levels: string[][]
|
||||
sizes: Array<number | null>
|
||||
pointColors?: Array<string | undefined>
|
||||
}
|
||||
/** chartUserShapes straight-line overlays; coordinates are fractions of the chart frame */
|
||||
userLines?: Array<{
|
||||
x1: number
|
||||
y1: number
|
||||
x2: number
|
||||
y2: number
|
||||
color: string
|
||||
widthEmu: number
|
||||
}>
|
||||
/** chartSpace-level <c:txPr> default text size (pt); chart text without its own txPr uses this */
|
||||
defaultTextPt?: number
|
||||
/** 3D chart type (pie3D/bar3D/…): render layer draws a pseudo-3D look on the 2D pipeline */
|
||||
@@ -128,9 +218,13 @@ export function parseChartXml(
|
||||
const barPlot = plotArea['c:barChart'] ?? plotArea['c:bar3DChart']
|
||||
const areaPlot = plotArea['c:areaChart'] ?? plotArea['c:area3DChart']
|
||||
const linePlot = plotArea['c:lineChart'] ?? plotArea['c:line3DChart']
|
||||
// Stock (open-)high-low-close rides the line pipeline: category axis + one value series
|
||||
// per role; whiskers/up-down bars come from the stock flags, connecting lines stay off
|
||||
const stockPlot = plotArea['c:stockChart']
|
||||
if (barPlot) cartesian.push({ kind: 'bar', plot: barPlot })
|
||||
if (areaPlot) cartesian.push({ kind: 'area', plot: areaPlot })
|
||||
if (linePlot) cartesian.push({ kind: 'line', plot: linePlot })
|
||||
if (stockPlot) cartesian.push({ kind: 'line', plot: stockPlot })
|
||||
|
||||
const piePlot = plotArea['c:pieChart'] ?? plotArea['c:pie3DChart'] ?? plotArea['c:doughnutChart']
|
||||
|
||||
@@ -150,9 +244,10 @@ export function parseChartXml(
|
||||
} else if (piePlot) {
|
||||
kind = 'pie'
|
||||
plot = piePlot
|
||||
} else if (plotArea['c:scatterChart']) {
|
||||
} else if (plotArea['c:scatterChart'] || plotArea['c:bubbleChart']) {
|
||||
// Bubble rides the scatter pipeline: same x/y value model, sized markers via bubbleSizes
|
||||
kind = 'scatter'
|
||||
plot = plotArea['c:scatterChart']
|
||||
plot = plotArea['c:scatterChart'] ?? plotArea['c:bubbleChart']
|
||||
} else if (plotArea['c:radarChart']) {
|
||||
kind = 'radar'
|
||||
plot = plotArea['c:radarChart']
|
||||
@@ -179,11 +274,13 @@ export function parseChartXml(
|
||||
|
||||
const series: ChartSeries[] = []
|
||||
let categories: string[] = []
|
||||
let categoryGroups: Array<{ label: string; start: number }> | undefined
|
||||
const parsePlotSeries = (
|
||||
plotNode: any,
|
||||
plotKind: ChartKind,
|
||||
tagPlotKind: boolean,
|
||||
secondary = false,
|
||||
fromStock = false,
|
||||
) => {
|
||||
const sersRaw = plotNode['c:ser']
|
||||
const sers: any[] = Array.isArray(sersRaw) ? sersRaw : sersRaw ? [sersRaw] : []
|
||||
@@ -193,42 +290,99 @@ export function parseChartXml(
|
||||
values: readNumPoints(plotKind === 'scatter' ? ser['c:yVal'] : ser['c:val']),
|
||||
}
|
||||
if (tagPlotKind) s.plotKind = plotKind as 'line' | 'bar' | 'area'
|
||||
// Excel/PowerPoint pick automatic series colors by c:idx, not document order
|
||||
const palIdx = parseInt(ser['c:idx']?.['@_val'], 10)
|
||||
if (Number.isFinite(palIdx)) s.paletteIdx = palIdx
|
||||
if (secondary) s.secondaryAxis = true
|
||||
if (fromStock) s.fromStock = true
|
||||
if (plotKind === 'scatter') {
|
||||
const xs = readNumPoints(ser['c:xVal'])
|
||||
if (xs.length) s.xValues = xs
|
||||
const sizes = readNumPoints(ser['c:bubbleSize'])
|
||||
if (sizes.length) s.bubbleSizes = sizes
|
||||
}
|
||||
const name = readStrPoints(ser['c:tx'])[0]
|
||||
if (name != null) s.name = name
|
||||
const color = serColor(ser, theme)
|
||||
// Bubble color is the fill (the line is only the outline), unlike line/scatter/radar
|
||||
const color = serColor(
|
||||
ser,
|
||||
theme,
|
||||
!s.bubbleSizes && (plotKind === 'line' || plotKind === 'scatter' || plotKind === 'radar'),
|
||||
)
|
||||
if (color) s.color = color
|
||||
if (ser['c:smooth']?.['@_val'] === '1') s.smooth = true
|
||||
const serLn = ser['c:spPr']?.['a:ln']
|
||||
const serDash = serLn?.['a:prstDash']?.['@_val']
|
||||
if (typeof serDash === 'string' && serDash !== 'solid') s.dash = serDash
|
||||
const serLnW = parseInt(serLn?.['@_w'], 10)
|
||||
if (Number.isFinite(serLnW) && serLnW > 0) s.lineWidthPt = serLnW / 12700
|
||||
// Data-label visibility is per series: a combo chart shows labels only on the
|
||||
// series that carry c:dLbls (acsa: bar series labeled, the index line not)
|
||||
const dlOn = (d: any) =>
|
||||
!!d &&
|
||||
typeof d === 'object' &&
|
||||
d['c:delete']?.['@_val'] !== '1' &&
|
||||
(d['c:showVal']?.['@_val'] === '1' || d['c:showPercent']?.['@_val'] === '1')
|
||||
const serDl = ser['c:dLbls']
|
||||
s.dataLabels = serDl && typeof serDl === 'object' ? dlOn(serDl) : dlOn(plotNode['c:dLbls'])
|
||||
const markerSym = ser['c:marker']?.['c:symbol']?.['@_val']
|
||||
if (plotKind === 'line') s.marker = markerSym != null && markerSym !== 'none'
|
||||
// scatter/radar: default marker decided by style; only set for explicit symbol (none → false)
|
||||
else if ((plotKind === 'scatter' || plotKind === 'radar') && markerSym != null)
|
||||
s.marker = markerSym !== 'none'
|
||||
const expl = parseInt(ser['c:explosion']?.['@_val'], 10)
|
||||
if (Number.isFinite(expl) && expl > 0) s.explosionPct = expl
|
||||
// Per-data-point colors (one color per pie slice)
|
||||
const dPts: any[] = ser['c:dPt'] ?? []
|
||||
if (dPts.length) {
|
||||
const pointColors: Array<string | undefined> = []
|
||||
const pointExpl: Array<number | undefined> = []
|
||||
for (const dPt of dPts) {
|
||||
const idx = parseInt(dPt['c:idx']?.['@_val'], 10)
|
||||
if (Number.isNaN(idx)) continue
|
||||
const c = resolveColorNode(dPt['c:spPr']?.['a:solidFill'], theme)
|
||||
if (c != null) pointColors[idx] = c
|
||||
const pe = parseInt(dPt['c:explosion']?.['@_val'], 10)
|
||||
if (Number.isFinite(pe)) pointExpl[idx] = pe
|
||||
}
|
||||
if (pointColors.length) s.pointColors = pointColors
|
||||
if (pointExpl.length) s.pointExplosionPct = pointExpl
|
||||
}
|
||||
series.push(s)
|
||||
// Categories: take the first non-empty series' cat
|
||||
if (!categories.length) categories = readStrPoints(ser['c:cat'])
|
||||
// Multi-level category axis: the outer level groups leaf categories (CA | SF, LA)
|
||||
if (!categoryGroups) {
|
||||
const multi = ser['c:cat']?.['c:multiLvlStrRef']?.['c:multiLvlStrCache']
|
||||
const lvlsRaw = multi?.['c:lvl']
|
||||
const lvls: any[] = Array.isArray(lvlsRaw) ? lvlsRaw : lvlsRaw ? [lvlsRaw] : []
|
||||
if (lvls.length > 1) {
|
||||
const ptsRaw = lvls[1]?.['c:pt']
|
||||
const pts: any[] = Array.isArray(ptsRaw) ? ptsRaw : ptsRaw ? [ptsRaw] : []
|
||||
const groups = pts
|
||||
.map((pt) => {
|
||||
const v = pt?.['c:v']
|
||||
return {
|
||||
label: typeof v === 'string' ? v : v != null ? String(v['#text'] ?? '') : '',
|
||||
start: parseInt(pt?.['@_idx'], 10) || 0,
|
||||
}
|
||||
})
|
||||
.sort((a, b) => a.start - b.start)
|
||||
if (groups.length) categoryGroups = groups
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cartesian.length > 1) {
|
||||
for (const c of cartesian)
|
||||
parsePlotSeries(c.plot, c.kind, true, secAxId != null && plotAxIds(c.plot).includes(secAxId))
|
||||
} else parsePlotSeries(plot, kind, false)
|
||||
parsePlotSeries(
|
||||
c.plot,
|
||||
c.kind,
|
||||
true,
|
||||
secAxId != null && plotAxIds(c.plot).includes(secAxId),
|
||||
c.plot === stockPlot,
|
||||
)
|
||||
} else parsePlotSeries(plot, kind, false, false, plot === stockPlot)
|
||||
if (!series.length) return null
|
||||
if (!categories.length) {
|
||||
// With no category cache, keep names empty (length from the longest series); never inject placeholders
|
||||
@@ -237,6 +391,7 @@ export function parseChartXml(
|
||||
}
|
||||
|
||||
const model: ChartModel = { kind, categories, series }
|
||||
if (categoryGroups) model.categoryGroups = categoryGroups
|
||||
|
||||
if (is3D) {
|
||||
model.pseudo3D = true
|
||||
@@ -244,11 +399,13 @@ export function parseChartXml(
|
||||
if (Number.isFinite(rotX)) model.rotXDeg = rotX
|
||||
}
|
||||
|
||||
if (kind === 'bar' || kind === 'area') {
|
||||
const grouping = plot['c:grouping']?.['@_val']
|
||||
if (grouping) model.grouping = grouping
|
||||
}
|
||||
if (kind === 'bar') {
|
||||
const dir = plot['c:barDir']?.['@_val']
|
||||
model.barDir = dir === 'bar' ? 'bar' : 'col'
|
||||
const grouping = plot['c:grouping']?.['@_val']
|
||||
if (grouping) model.grouping = grouping
|
||||
const gap = plot['c:gapWidth']?.['@_val']
|
||||
model.gapWidthPct = gap != null ? parseInt(gap, 10) : 150
|
||||
}
|
||||
@@ -258,11 +415,16 @@ export function parseChartXml(
|
||||
model.holePct = hole != null ? parseInt(hole, 10) || 0 : plotArea['c:doughnutChart'] ? 50 : 0
|
||||
const first = plot['c:firstSliceAng']?.['@_val']
|
||||
if (first != null) model.firstSliceAngDeg = parseInt(first, 10) || 0
|
||||
const vary = plot['c:varyColors']?.['@_val']
|
||||
if (vary === '0' || vary === 'false') model.varyColors = false
|
||||
}
|
||||
|
||||
if (kind === 'scatter') {
|
||||
const st = plot['c:scatterStyle']?.['@_val']
|
||||
if (st) model.scatterStyle = String(st)
|
||||
const bScale = parseInt(plot['c:bubbleScale']?.['@_val'], 10)
|
||||
if (Number.isFinite(bScale) && bScale > 0) model.bubbleScale = bScale
|
||||
if (plot['c:sizeRepresents']?.['@_val'] === 'w') model.bubbleSizeIsWidth = true
|
||||
}
|
||||
|
||||
if (kind === 'radar') {
|
||||
@@ -270,12 +432,80 @@ export function parseChartXml(
|
||||
model.radarStyle = st === 'filled' ? 'filled' : st === 'marker' ? 'marker' : 'standard'
|
||||
}
|
||||
|
||||
const legendPos = chart['c:legend']?.['c:legendPos']?.['@_val']
|
||||
if (chart['c:legend']) model.legendPos = (legendPos as ChartModel['legendPos']) ?? 'r'
|
||||
if (stockPlot) {
|
||||
// Empty elements (<c:hiLowLines/>) parse to "" — presence check must not be truthiness
|
||||
const udb = stockPlot['c:upDownBars']
|
||||
const gw = parseInt(udb?.['c:gapWidth']?.['@_val'], 10)
|
||||
model.stock = {
|
||||
hiLowLines: stockPlot['c:hiLowLines'] !== undefined,
|
||||
upDownBars: udb !== undefined,
|
||||
...(Number.isFinite(gw) && gw >= 0 ? { gapWidthPct: gw } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
// Whole-chart background (chartSpace-level spPr), e.g. picture fill
|
||||
const legendNode = chart['c:legend']
|
||||
const legendPos = legendNode?.['c:legendPos']?.['@_val']
|
||||
if (legendNode) {
|
||||
model.legendPos = (legendPos as ChartModel['legendPos']) ?? 'r'
|
||||
// <c:overlay val="1"/>: the legend floats over the plot, reserving no space
|
||||
if (legendNode['c:overlay']?.['@_val'] === '1') model.legendOverlay = true
|
||||
const legP = chart['c:legend']?.['c:txPr']?.['a:p']
|
||||
const legRPr = (Array.isArray(legP) ? legP[0] : legP)?.['a:pPr']?.['a:defRPr']
|
||||
// INT_MIN baseline sentinel: PowerPoint renders no legend at all
|
||||
if (legRPr?.['@_baseline'] === '-2147483648') delete model.legendPos
|
||||
const legSz = parseInt(legRPr?.['@_sz'], 10)
|
||||
if (Number.isFinite(legSz) && legSz > 0) model.legendPt = legSz / 100
|
||||
if (legRPr?.['@_b'] === '1') model.legendBold = true
|
||||
}
|
||||
|
||||
// Plot-area inner rectangle (edge-mode fractions of the chart frame); PowerPoint positions
|
||||
// gridlines/bars exactly here, with axis labels outside it
|
||||
const mLay = plotArea['c:layout']?.['c:manualLayout']
|
||||
if (mLay?.['c:layoutTarget']?.['@_val'] === 'inner') {
|
||||
const frac = (k: string) => Number(mLay[k]?.['@_val'])
|
||||
const edgeMode = (k: string) => {
|
||||
const m = mLay[k]?.['@_val']
|
||||
return m == null || m === 'edge'
|
||||
}
|
||||
const [lx, ly, lw, lh] = [frac('c:x'), frac('c:y'), frac('c:w'), frac('c:h')]
|
||||
if (
|
||||
edgeMode('c:xMode') &&
|
||||
edgeMode('c:yMode') &&
|
||||
[lx, ly, lw, lh].every(Number.isFinite) &&
|
||||
lw > 0 &&
|
||||
lh > 0
|
||||
) {
|
||||
model.plotLayout = { x: lx, y: ly, w: lw, h: lh }
|
||||
}
|
||||
}
|
||||
|
||||
// Plot-area fill/border (c:plotArea's own spPr)
|
||||
const paSpPr = plotArea['c:spPr']
|
||||
const paFill =
|
||||
resolveFill?.(paSpPr) ??
|
||||
(() => {
|
||||
const c = resolveColorNode(paSpPr?.['a:solidFill'], theme)
|
||||
return c ? ({ type: 'solid', color: c } as Fill) : undefined
|
||||
})()
|
||||
if (paFill && paFill.type !== 'none') model.plotFill = paFill
|
||||
const paLn = paSpPr?.['a:ln']
|
||||
const paBorderColor = paLn && !paLn['a:noFill'] && resolveColorNode(paLn['a:solidFill'], theme)
|
||||
if (paBorderColor) {
|
||||
const w = parseInt(paLn['@_w'], 10)
|
||||
model.plotBorder = { color: paBorderColor, widthEmu: Number.isFinite(w) && w > 0 ? w : 9525 }
|
||||
}
|
||||
|
||||
// Whole-chart background (chartSpace-level spPr), e.g. picture fill; no spPr →
|
||||
// transparent (PowerPoint-verified: overlapping frames show through, aspose Chart2)
|
||||
const bgFill = resolveFill?.(doc['c:chartSpace']?.['c:spPr'])
|
||||
if (bgFill && bgFill.type !== 'none') model.bgFill = bgFill
|
||||
// Whole-chart frame border (chartSpace-level ln)
|
||||
const spLn = doc['c:chartSpace']?.['c:spPr']?.['a:ln']
|
||||
const borderColor = spLn && !spLn['a:noFill'] && resolveColorNode(spLn['a:solidFill'], theme)
|
||||
if (borderColor) {
|
||||
const w = parseInt(spLn['@_w'], 10)
|
||||
model.border = { color: borderColor, widthEmu: Number.isFinite(w) && w > 0 ? w : 9525 }
|
||||
}
|
||||
|
||||
// Theme accents: default series/wedge colors follow the file's theme, not a fixed palette
|
||||
if (theme) {
|
||||
@@ -284,6 +514,25 @@ export function parseChartXml(
|
||||
.filter((c): c is string => !!c)
|
||||
if (accents.length === 6) model.themePalette = accents
|
||||
}
|
||||
// Legacy 2007 <c:style>: styles arrange in 8 columns; columns 3-8 color every series
|
||||
// with a monochrome luminance ramp of accent1-6 (dark→light in plot order). Ramp
|
||||
// anchors measured against PowerPoint for Mac (style 12, 4 series).
|
||||
const styleVal = parseInt(doc['c:chartSpace']?.['c:style']?.['@_val'], 10)
|
||||
const styleCol = Number.isFinite(styleVal) ? (styleVal - 1) % 8 : -1
|
||||
if (styleCol >= 2 && model.themePalette && series.length && series.every((s) => !s.color)) {
|
||||
const base = model.themePalette[styleCol - 2]
|
||||
if (base) {
|
||||
const anchors = [0.77, 0.93, 1.44, 1.92]
|
||||
const lumAt = (p: number): number => {
|
||||
const x = p * (anchors.length - 1)
|
||||
const i = Math.min(Math.floor(x), anchors.length - 2)
|
||||
return anchors[i]! + (anchors[i + 1]! - anchors[i]!) * (x - i)
|
||||
}
|
||||
series.forEach((s, i) => {
|
||||
s.color = scaleLuminance(base, series.length === 1 ? 1 : lumAt(i / (series.length - 1)))
|
||||
})
|
||||
}
|
||||
}
|
||||
// chartSpace-level default text size (hundredths of a pt)
|
||||
const txP = doc['c:chartSpace']?.['c:txPr']?.['a:p']
|
||||
const defSz = parseInt((Array.isArray(txP) ? txP[0] : txP)?.['a:pPr']?.['a:defRPr']?.['@_sz'], 10)
|
||||
@@ -293,26 +542,68 @@ export function parseChartXml(
|
||||
const chartTitle =
|
||||
collectText(chart['c:title']?.['c:tx']?.['c:rich']) ||
|
||||
readStrPoints(chart['c:title']?.['c:tx'])[0]
|
||||
if (chart['c:title']?.['c:overlay']?.['@_val'] === '1') model.titleOverlay = true
|
||||
if (chartTitle) model.title = chartTitle
|
||||
// Auto title: a <c:title> with no c:tx at all (and autoTitleDeleted != 1) takes the sole series name
|
||||
// Auto title: a <c:title> with no c:tx at all (and autoTitleDeleted != 1) takes the
|
||||
// sole series name; with several series PowerPoint shows the literal "Chart Title"
|
||||
else if (
|
||||
chart['c:title'] &&
|
||||
!chart['c:title']?.['c:tx'] &&
|
||||
chart['c:autoTitleDeleted']?.['@_val'] !== '1' &&
|
||||
series.length === 1 &&
|
||||
series[0]!.name
|
||||
chart['c:autoTitleDeleted']?.['@_val'] !== '1'
|
||||
) {
|
||||
model.title = series[0]!.name
|
||||
model.title = (series.length === 1 && series[0]!.name) || 'Chart Title'
|
||||
}
|
||||
if (model.title) {
|
||||
const titP = chart['c:title']?.['c:txPr']?.['a:p']
|
||||
const titleSz = parseInt(
|
||||
(Array.isArray(titP) ? titP[0] : titP)?.['a:pPr']?.['a:defRPr']?.['@_sz'],
|
||||
10,
|
||||
)
|
||||
if (Number.isFinite(titleSz) && titleSz > 0) model.titlePt = titleSz / 100
|
||||
// Rich-text titles usually carry the size on the first run, not on txPr
|
||||
if (!model.titlePt) {
|
||||
const rich = chart['c:title']?.['c:tx']?.['c:rich']
|
||||
const p0 = Array.isArray(rich?.['a:p']) ? rich['a:p'][0] : rich?.['a:p']
|
||||
const r0 = Array.isArray(p0?.['a:r']) ? p0['a:r'][0] : p0?.['a:r']
|
||||
const runSz = parseInt(r0?.['a:rPr']?.['@_sz'], 10)
|
||||
if (Number.isFinite(runSz) && runSz > 0) model.titlePt = runSz / 100
|
||||
}
|
||||
}
|
||||
|
||||
// Data labels: plot-level or any series-level c:dLbls (delete=1 counts as none)
|
||||
const dLblsInfo = (owner: any): { on: boolean; pct: boolean } => {
|
||||
const dLblsInfo = (
|
||||
owner: any,
|
||||
): {
|
||||
on: boolean
|
||||
pct: boolean
|
||||
ser?: boolean
|
||||
cat?: boolean
|
||||
val?: boolean
|
||||
fmt?: string
|
||||
sizePt?: number
|
||||
bold?: boolean
|
||||
} => {
|
||||
const d = owner?.['c:dLbls']
|
||||
if (!d || typeof d !== 'object' || d['c:delete']?.['@_val'] === '1')
|
||||
return { on: false, pct: false }
|
||||
const showVal = d['c:showVal']?.['@_val'] === '1'
|
||||
const showPct = d['c:showPercent']?.['@_val'] === '1'
|
||||
return { on: showVal || showPct, pct: showPct && !showVal }
|
||||
const showSer = d['c:showSerName']?.['@_val'] === '1'
|
||||
const showCat = d['c:showCatName']?.['@_val'] === '1'
|
||||
const fmt = d['c:numFmt']?.['@_formatCode']
|
||||
const dP = d['c:txPr']?.['a:p']
|
||||
const dRPr = (Array.isArray(dP) ? dP[0] : dP)?.['a:pPr']?.['a:defRPr']
|
||||
const dSz = parseInt(dRPr?.['@_sz'], 10)
|
||||
return {
|
||||
on: showVal || showPct || showSer || showCat,
|
||||
pct: showPct && !showVal,
|
||||
ser: showSer,
|
||||
cat: showCat,
|
||||
val: showVal || showPct,
|
||||
...(typeof fmt === 'string' && fmt && fmt !== 'General' ? { fmt } : {}),
|
||||
...(Number.isFinite(dSz) && dSz > 0 ? { sizePt: dSz / 100 } : {}),
|
||||
...(dRPr?.['@_b'] === '1' ? { bold: true } : {}),
|
||||
}
|
||||
}
|
||||
const dLblOwners: any[] = (cartesian.length > 1 ? cartesian.map((c) => c.plot) : [plot]).flatMap(
|
||||
(p) => [
|
||||
@@ -320,10 +611,19 @@ export function parseChartXml(
|
||||
...((Array.isArray(p['c:ser']) ? p['c:ser'] : p['c:ser'] ? [p['c:ser']] : []) as any[]),
|
||||
],
|
||||
)
|
||||
const found = dLblOwners.map(dLblsInfo).find((r) => r.on)
|
||||
const dLblResults = dLblOwners.map(dLblsInfo)
|
||||
const found = dLblResults.find((r) => r.on)
|
||||
if (found) {
|
||||
model.dataLabels = true
|
||||
if (found.pct) model.dataLabelsPct = true
|
||||
if (found.ser) model.dataLabelSerName = true
|
||||
if (found.cat) model.dataLabelCatName = true
|
||||
if (found.on && !found.val) model.dataLabelNoValue = true
|
||||
const fmt = found.fmt ?? dLblResults.find((r) => r.fmt)?.fmt
|
||||
if (fmt) model.dataLabelFmt = fmt
|
||||
const sizePt = found.sizePt ?? dLblResults.find((r) => r.sizePt)?.sizePt
|
||||
if (sizePt) model.dataLabelPt = sizePt
|
||||
if (found.bold ?? dLblResults.some((r) => r.bold)) model.dataLabelBold = true
|
||||
}
|
||||
|
||||
// Axes: scatter charts have dual value axes (x at the bottom axPos=b, y on the left); the x axis goes in the catAxis slot
|
||||
@@ -346,12 +646,22 @@ export function parseChartXml(
|
||||
const valAx2 = parseAxis(secValAxNode, theme)
|
||||
if (valAx2) model.valAxis2 = valAx2
|
||||
}
|
||||
const catAxRaw = plotArea['c:catAx']
|
||||
const catAxes: any[] = Array.isArray(catAxRaw) ? catAxRaw : catAxRaw ? [catAxRaw] : []
|
||||
const catAxNode = catAxes.find((a) => a?.['c:delete']?.['@_val'] !== '1') ?? catAxes[0]
|
||||
const catAx = parseAxis(catAxNode, theme)
|
||||
if (catAx) model.catAxis = catAx
|
||||
// A date axis is a category axis with time semantics — same label/gridline model.
|
||||
// Both kinds may coexist (a deleted secondary catAx next to the primary dateAx):
|
||||
// pick the first non-deleted candidate across the two lists
|
||||
const toArr = (raw: any): any[] => (Array.isArray(raw) ? raw : raw ? [raw] : [])
|
||||
const catCands = [
|
||||
...toArr(plotArea['c:catAx']).map((n) => ({ n, date: false })),
|
||||
...toArr(plotArea['c:dateAx']).map((n) => ({ n, date: true })),
|
||||
]
|
||||
const pick = catCands.find((c) => c.n?.['c:delete']?.['@_val'] !== '1') ?? catCands[0]
|
||||
const catAx = parseAxis(pick?.n, theme)
|
||||
if (catAx || pick?.date)
|
||||
model.catAxis = { ...(catAx ?? {}), ...(pick?.date ? { isDate: true } : {}) }
|
||||
}
|
||||
// Source-linked data labels inherit the value axis's number format
|
||||
if (model.dataLabels && !model.dataLabelFmt && model.valAxis?.numFmt)
|
||||
model.dataLabelFmt = model.valAxis.numFmt
|
||||
|
||||
return model
|
||||
}
|
||||
@@ -382,10 +692,54 @@ function readStrPoints(node: any): string[] {
|
||||
if (lvls.length) return readPoints(lvls[0]).map((v) => v ?? '')
|
||||
}
|
||||
const numCache = node?.['c:numRef']?.['c:numCache']
|
||||
if (numCache) return readPoints(numCache).map((v) => v ?? '')
|
||||
if (numCache) {
|
||||
// Date categories: numeric serials + a date formatCode in the cache (PowerPoint
|
||||
// displays the formatted date, e.g. 37261 + m/d/yyyy → 1/5/2002)
|
||||
const fmt = numCache['c:formatCode']
|
||||
const fmtStr = typeof fmt === 'string' ? fmt : String(fmt?.['#text'] ?? '')
|
||||
const isDate = /[ymd]/i.test(fmtStr) && !/[#0?]/.test(fmtStr)
|
||||
return readPoints(numCache).map((v) => {
|
||||
if (v == null) return ''
|
||||
if (!isDate) return v
|
||||
const serial = parseFloat(v)
|
||||
return Number.isFinite(serial) ? formatDateSerial(serial, fmtStr) : v
|
||||
})
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
/** Excel date serial (days since 1899-12-30) formatted per the common date codes. */
|
||||
function formatDateSerial(serial: number, fmt: string): string {
|
||||
const ms = (serial - 25569) * 86400000 // 25569 = days 1899-12-30 → 1970-01-01
|
||||
const d = new Date(ms)
|
||||
const yyyy = d.getUTCFullYear()
|
||||
const mNum = d.getUTCMonth() + 1
|
||||
const dayNum = d.getUTCDate()
|
||||
const MONTHS = [
|
||||
'Jan',
|
||||
'Feb',
|
||||
'Mar',
|
||||
'Apr',
|
||||
'May',
|
||||
'Jun',
|
||||
'Jul',
|
||||
'Aug',
|
||||
'Sep',
|
||||
'Oct',
|
||||
'Nov',
|
||||
'Dec',
|
||||
]
|
||||
return fmt
|
||||
.replace(/\\/g, '')
|
||||
.replace(/yyyy/gi, String(yyyy))
|
||||
.replace(/yy/gi, String(yyyy % 100).padStart(2, '0'))
|
||||
.replace(/mmm/gi, MONTHS[d.getUTCMonth()]!)
|
||||
.replace(/mm/gi, String(mNum).padStart(2, '0'))
|
||||
.replace(/(?<![a-z])m(?![a-z])/gi, String(mNum))
|
||||
.replace(/dd/gi, String(dayNum).padStart(2, '0'))
|
||||
.replace(/(?<![a-z])d(?![a-z])/gi, String(dayNum))
|
||||
}
|
||||
|
||||
/** c:pt list → value array ordered by idx. */
|
||||
function readPoints(cache: any): Array<string | null> {
|
||||
const ptsRaw = cache?.['c:pt']
|
||||
@@ -401,22 +755,25 @@ function readPoints(cache: any): Array<string | null> {
|
||||
return out
|
||||
}
|
||||
|
||||
/** Series main color: ln stroke first (lines), otherwise solidFill (bars/pies). */
|
||||
function serColor(ser: any, theme?: Theme): string | undefined {
|
||||
/** Series main color: line-family series read the ln stroke first; bars/pies read the
|
||||
* solidFill first (their ln is a segment outline, e.g. black borders around bars). */
|
||||
function serColor(ser: any, theme: Theme | undefined, preferLine: boolean): string | undefined {
|
||||
const spPr = ser['c:spPr']
|
||||
if (!spPr) return undefined
|
||||
const lnColor = resolveColorNode(spPr['a:ln']?.['a:solidFill'], theme)
|
||||
const fillColor = resolveColorNode(spPr['a:solidFill'], theme)
|
||||
return lnColor ?? fillColor
|
||||
return preferLine ? (lnColor ?? fillColor) : (fillColor ?? lnColor)
|
||||
}
|
||||
|
||||
function parseAxis(ax: any, theme?: Theme): ChartAxisStyle | undefined {
|
||||
if (!ax || typeof ax !== 'object') return undefined
|
||||
const out: ChartAxisStyle = {}
|
||||
if (ax['c:delete']?.['@_val'] === '1') out.hidden = true
|
||||
const scaling = ax['c:scaling']
|
||||
if (scaling?.['c:min']?.['@_val'] != null) out.min = Number(scaling['c:min']['@_val'])
|
||||
if (scaling?.['c:max']?.['@_val'] != null) out.max = Number(scaling['c:max']['@_val'])
|
||||
if (scaling?.['c:orientation']?.['@_val'] === 'maxMin') out.reversed = true
|
||||
if (ax['c:tickLblPos']?.['@_val'] === 'none') out.tickLblHidden = true
|
||||
const defRPr =
|
||||
ax['c:txPr']?.['a:p']?.[0]?.['a:pPr']?.['a:defRPr'] ??
|
||||
ax['c:txPr']?.['a:p']?.['a:pPr']?.['a:defRPr']
|
||||
@@ -424,16 +781,41 @@ function parseAxis(ax: any, theme?: Theme): ChartAxisStyle | undefined {
|
||||
const c = resolveColorNode(defRPr['a:solidFill'], theme)
|
||||
if (c) out.labelColor = c
|
||||
if (defRPr['@_sz']) out.labelSizePt = parseInt(defRPr['@_sz'], 10) / 100
|
||||
if (defRPr['@_b'] === '1') out.labelBold = true
|
||||
// INT_MIN baseline sentinel (Aspose-written): PowerPoint reserves the label space
|
||||
// but renders nothing there
|
||||
if (defRPr['@_baseline'] === '-2147483648') out.tickLblGarbage = true
|
||||
}
|
||||
// rot outside +-90 deg (e.g. Office's auto marker -60000000) is not an explicit rotation
|
||||
const rot = parseInt(ax['c:txPr']?.['a:bodyPr']?.['@_rot'], 10)
|
||||
if (Number.isFinite(rot) && rot !== 0 && Math.abs(rot) <= 5400000) out.labelRotDeg = rot / 60000
|
||||
const numFmt = ax['c:numFmt']?.['@_formatCode']
|
||||
if (typeof numFmt === 'string' && numFmt && numFmt !== 'General') out.numFmt = numFmt
|
||||
const lineColor = resolveColorNode(ax['c:spPr']?.['a:ln']?.['a:solidFill'], theme)
|
||||
if (lineColor) out.lineColor = lineColor
|
||||
// A self-closing <c:majorGridlines/> (no spPr) parses to an empty string; still counts as having gridlines
|
||||
const grid = ax['c:majorGridlines']
|
||||
if (grid !== undefined) {
|
||||
const spPr = typeof grid === 'object' ? grid['c:spPr'] : undefined
|
||||
const gc = resolveColorNode(spPr?.['a:ln']?.['a:solidFill'], theme)
|
||||
const ln = typeof grid === 'object' ? grid['c:spPr']?.['a:ln'] : undefined
|
||||
const gc = resolveColorNode(ln?.['a:solidFill'], theme)
|
||||
out.gridColor = gc ?? '#E6E6E6'
|
||||
if (spPr?.['a:ln']?.['a:prstDash']?.['@_val'] === 'dash') out.gridDash = true
|
||||
const dash = ln?.['a:prstDash']?.['@_val']
|
||||
if (dash && dash !== 'solid') {
|
||||
out.gridDash = true
|
||||
out.gridDashVal = String(dash)
|
||||
}
|
||||
const w = parseInt(ln?.['@_w'], 10)
|
||||
if (Number.isFinite(w) && w > 0) out.gridWidthEmu = w
|
||||
}
|
||||
const minor = ax['c:minorGridlines']
|
||||
if (minor !== undefined && typeof minor === 'object') {
|
||||
const ln = minor['c:spPr']?.['a:ln']
|
||||
const gc = resolveColorNode(ln?.['a:solidFill'], theme)
|
||||
if (gc) {
|
||||
out.minorGridColor = gc
|
||||
const w = parseInt(ln?.['@_w'], 10)
|
||||
if (Number.isFinite(w) && w > 0) out.minorGridWidthEmu = w
|
||||
}
|
||||
}
|
||||
// Axis title (all a:t inside c:title/c:tx/c:rich concatenated)
|
||||
const title = collectText(ax['c:title']?.['c:tx']?.['c:rich'])
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* chartEx parsing (2014 cx namespace: ppt/charts/chartExN.xml → ChartModel).
|
||||
*
|
||||
* Modern chart types PowerPoint stores outside the classic c: namespace.
|
||||
* Supported layoutIds: funnel (categories + values → centered bars) and
|
||||
* sunburst (multi-level strDim hierarchy + leaf sizes → rings). Other
|
||||
* layoutIds (waterfall, treemap, …) return null and fall back to the chip.
|
||||
*/
|
||||
import { XMLParser } from 'fast-xml-parser'
|
||||
import { type Theme } from './theme'
|
||||
import { resolveColorNode } from './color'
|
||||
import type { ChartModel } from './chart'
|
||||
|
||||
const cxParser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
attributeNamePrefix: '@_',
|
||||
trimValues: false,
|
||||
parseTagValue: false,
|
||||
isArray: (name) => ['cx:data', 'cx:lvl', 'cx:pt', 'cx:series', 'cx:dataPt'].includes(name),
|
||||
})
|
||||
|
||||
/** One cx:lvl: ptCount + sparse idx→text points → dense array ('' for gaps). */
|
||||
function readLvl(lvl: any): string[] {
|
||||
const n = parseInt(lvl?.['@_ptCount'], 10) || 0
|
||||
const out: string[] = Array.from({ length: n }, () => '')
|
||||
const ptsRaw = lvl?.['cx:pt']
|
||||
const pts: any[] = Array.isArray(ptsRaw) ? ptsRaw : ptsRaw ? [ptsRaw] : []
|
||||
for (const pt of pts) {
|
||||
const i = parseInt(pt?.['@_idx'], 10)
|
||||
if (!Number.isNaN(i) && i < n) out[i] = typeof pt === 'object' ? String(pt['#text'] ?? '') : ''
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** All a:t text values in a parsed subtree (handles xml:space="preserve" object form). */
|
||||
function collectAT(node: unknown): string[] {
|
||||
const out: string[] = []
|
||||
const walk = (n: unknown) => {
|
||||
if (n == null || typeof n !== 'object') return
|
||||
for (const [k, v] of Object.entries(n as Record<string, unknown>)) {
|
||||
if (k.startsWith('@_')) continue
|
||||
if (k === 'a:t') {
|
||||
for (const t of Array.isArray(v) ? v : [v]) {
|
||||
if (typeof t === 'string') out.push(t)
|
||||
else if (t && typeof t === 'object')
|
||||
out.push(String((t as Record<string, unknown>)['#text'] ?? ''))
|
||||
}
|
||||
} else {
|
||||
for (const c of Array.isArray(v) ? v : [v]) walk(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(node)
|
||||
return out
|
||||
}
|
||||
|
||||
export function parseChartExXml(xml: string, theme?: Theme): ChartModel | null {
|
||||
let doc: any
|
||||
try {
|
||||
doc = cxParser.parse(xml)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const space = doc['cx:chartSpace']
|
||||
const region = space?.['cx:chart']?.['cx:plotArea']?.['cx:plotAreaRegion']
|
||||
const seriesRaw = region?.['cx:series']
|
||||
const ser = Array.isArray(seriesRaw) ? seriesRaw[0] : seriesRaw
|
||||
const layoutId = ser?.['@_layoutId']
|
||||
if (layoutId !== 'funnel' && layoutId !== 'sunburst') return null
|
||||
|
||||
const dataId = ser?.['cx:dataId']?.['@_val'] ?? '0'
|
||||
const datas: any[] = space?.['cx:chartData']?.['cx:data'] ?? []
|
||||
const data = datas.find((d) => String(d?.['@_id']) === String(dataId)) ?? datas[0]
|
||||
if (!data) return null
|
||||
const strLvlsRaw = data['cx:strDim']?.['cx:lvl'] ?? []
|
||||
const strLvls: string[][] = (Array.isArray(strLvlsRaw) ? strLvlsRaw : [strLvlsRaw]).map(readLvl)
|
||||
const numLvlRaw = data['cx:numDim']?.['cx:lvl']
|
||||
const numLvl = Array.isArray(numLvlRaw) ? numLvlRaw[0] : numLvlRaw
|
||||
const values = readLvl(numLvl).map((v) => {
|
||||
const n = parseFloat(v)
|
||||
return Number.isFinite(n) ? n : null
|
||||
})
|
||||
if (!values.some((v) => v != null)) return null
|
||||
|
||||
const model: ChartModel = {
|
||||
kind: layoutId,
|
||||
categories: strLvls[0] ?? [],
|
||||
series: [{ values }],
|
||||
}
|
||||
// <cx:title/> with no rich text still renders as PowerPoint's placeholder title
|
||||
const title = space?.['cx:chart']?.['cx:title']
|
||||
if (title !== undefined) {
|
||||
model.title = collectAT(title?.['cx:tx']).join('') || 'Chart Title'
|
||||
}
|
||||
if (layoutId === 'sunburst') {
|
||||
model.sunburst = { levels: strLvls, sizes: values }
|
||||
const dPtsRaw = ser?.['cx:dataPt'] ?? []
|
||||
const dPts: any[] = Array.isArray(dPtsRaw) ? dPtsRaw : [dPtsRaw]
|
||||
const pointColors: Array<string | undefined> = []
|
||||
for (const dPt of dPts) {
|
||||
const i = parseInt(dPt?.['@_idx'], 10)
|
||||
const c = resolveColorNode(dPt?.['cx:spPr']?.['a:solidFill'], theme)
|
||||
if (!Number.isNaN(i) && c != null) pointColors[i] = c
|
||||
}
|
||||
if (pointColors.length) model.sunburst.pointColors = pointColors
|
||||
}
|
||||
if (layoutId === 'funnel') {
|
||||
const gap = parseFloat(
|
||||
space?.['cx:chart']?.['cx:plotArea']?.['cx:axis']?.['cx:catScaling']?.['@_gapWidth'],
|
||||
)
|
||||
if (Number.isFinite(gap) && gap >= 0) model.gapWidthPct = gap * 100
|
||||
}
|
||||
if (theme) {
|
||||
const accents = ['accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6']
|
||||
.map((k) => theme.colors?.[k])
|
||||
.filter((c): c is string => !!c)
|
||||
if (accents.length === 6) model.themePalette = accents
|
||||
}
|
||||
return model
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Color node resolution (srgbClr/schemeClr/sysClr + lumMod/lumOff/tint/shade/alpha modifiers).
|
||||
* Color node resolution (srgbClr/schemeClr/sysClr/prstClr + lumMod/lumOff/tint/shade/alpha modifiers).
|
||||
* Extracted from parse.ts into a shared module: used by both parse (run/fill colors) and
|
||||
* placeholder (lstStyle defRPr default colors) to avoid a circular dependency.
|
||||
*/
|
||||
@@ -10,7 +10,11 @@ import { asXmlNode, type XmlNode } from './xml-utils'
|
||||
* Resolve a color node + modifiers: srgbClr/schemeClr/sysClr, supporting alpha
|
||||
* (→#RRGGBBAA) and lumMod/lumOff (tint/shade, common for theme colors).
|
||||
*/
|
||||
export function resolveColorNode(node: unknown, theme: Theme | undefined, phClr?: string): string | undefined {
|
||||
export function resolveColorNode(
|
||||
node: unknown,
|
||||
theme: Theme | undefined,
|
||||
phClr?: string,
|
||||
): string | undefined {
|
||||
if (!node) return undefined
|
||||
const n = asXmlNode(node)
|
||||
let base: string | undefined
|
||||
@@ -24,11 +28,208 @@ export function resolveColorNode(node: unknown, theme: Theme | undefined, phClr?
|
||||
} else if (n['a:sysClr']) {
|
||||
mods = asXmlNode(n['a:sysClr'])
|
||||
base = '#' + String(mods['@_lastClr'] ?? '000000').toUpperCase()
|
||||
} else if (n['a:prstClr']) {
|
||||
mods = asXmlNode(n['a:prstClr'])
|
||||
base = PRESET_COLORS[String(mods['@_val'])]
|
||||
}
|
||||
if (!base) return undefined
|
||||
return applyColorMods(base, mods)
|
||||
}
|
||||
|
||||
/** ECMA-376 ST_PresetColorVal (CSS/X11 values plus the dk/lt/med aliases). */
|
||||
const PRESET_COLORS: Record<string, string> = {
|
||||
aliceBlue: '#F0F8FF',
|
||||
antiqueWhite: '#FAEBD7',
|
||||
aqua: '#00FFFF',
|
||||
aquamarine: '#7FFFD4',
|
||||
azure: '#F0FFFF',
|
||||
beige: '#F5F5DC',
|
||||
bisque: '#FFE4C4',
|
||||
black: '#000000',
|
||||
blanchedAlmond: '#FFEBCD',
|
||||
blue: '#0000FF',
|
||||
blueViolet: '#8A2BE2',
|
||||
brown: '#A52A2A',
|
||||
burlyWood: '#DEB887',
|
||||
cadetBlue: '#5F9EA0',
|
||||
chartreuse: '#7FFF00',
|
||||
chocolate: '#D2691E',
|
||||
coral: '#FF7F50',
|
||||
cornflowerBlue: '#6495ED',
|
||||
cornsilk: '#FFF8DC',
|
||||
crimson: '#DC143C',
|
||||
cyan: '#00FFFF',
|
||||
darkBlue: '#00008B',
|
||||
darkCyan: '#008B8B',
|
||||
darkGoldenrod: '#B8860B',
|
||||
darkGray: '#A9A9A9',
|
||||
darkGreen: '#006400',
|
||||
darkGrey: '#A9A9A9',
|
||||
darkKhaki: '#BDB76B',
|
||||
darkMagenta: '#8B008B',
|
||||
darkOliveGreen: '#556B2F',
|
||||
darkOrange: '#FF8C00',
|
||||
darkOrchid: '#9932CC',
|
||||
darkRed: '#8B0000',
|
||||
darkSalmon: '#E9967A',
|
||||
darkSeaGreen: '#8FBC8F',
|
||||
darkSlateBlue: '#483D8B',
|
||||
darkSlateGray: '#2F4F4F',
|
||||
darkSlateGrey: '#2F4F4F',
|
||||
darkTurquoise: '#00CED1',
|
||||
darkViolet: '#9400D3',
|
||||
deepPink: '#FF1493',
|
||||
deepSkyBlue: '#00BFFF',
|
||||
dimGray: '#696969',
|
||||
dimGrey: '#696969',
|
||||
dkBlue: '#00008B',
|
||||
dkCyan: '#008B8B',
|
||||
dkGoldenrod: '#B8860B',
|
||||
dkGray: '#A9A9A9',
|
||||
dkGreen: '#006400',
|
||||
dkGrey: '#A9A9A9',
|
||||
dkKhaki: '#BDB76B',
|
||||
dkMagenta: '#8B008B',
|
||||
dkOliveGreen: '#556B2F',
|
||||
dkOrange: '#FF8C00',
|
||||
dkOrchid: '#9932CC',
|
||||
dkRed: '#8B0000',
|
||||
dkSalmon: '#E9967A',
|
||||
dkSeaGreen: '#8FBC8F',
|
||||
dkSlateBlue: '#483D8B',
|
||||
dkSlateGray: '#2F4F4F',
|
||||
dkSlateGrey: '#2F4F4F',
|
||||
dkTurquoise: '#00CED1',
|
||||
dkViolet: '#9400D3',
|
||||
dodgerBlue: '#1E90FF',
|
||||
firebrick: '#B22222',
|
||||
floralWhite: '#FFFAF0',
|
||||
forestGreen: '#228B22',
|
||||
fuchsia: '#FF00FF',
|
||||
gainsboro: '#DCDCDC',
|
||||
ghostWhite: '#F8F8FF',
|
||||
gold: '#FFD700',
|
||||
goldenrod: '#DAA520',
|
||||
gray: '#808080',
|
||||
green: '#008000',
|
||||
greenYellow: '#ADFF2F',
|
||||
grey: '#808080',
|
||||
honeydew: '#F0FFF0',
|
||||
hotPink: '#FF69B4',
|
||||
indianRed: '#CD5C5C',
|
||||
indigo: '#4B0082',
|
||||
ivory: '#FFFFF0',
|
||||
khaki: '#F0E68C',
|
||||
lavender: '#E6E6FA',
|
||||
lavenderBlush: '#FFF0F5',
|
||||
lawnGreen: '#7CFC00',
|
||||
lemonChiffon: '#FFFACD',
|
||||
lightBlue: '#ADD8E6',
|
||||
lightCoral: '#F08080',
|
||||
lightCyan: '#E0FFFF',
|
||||
lightGoldenrodYellow: '#FAFAD2',
|
||||
lightGray: '#D3D3D3',
|
||||
lightGreen: '#90EE90',
|
||||
lightGrey: '#D3D3D3',
|
||||
lightPink: '#FFB6C1',
|
||||
lightSalmon: '#FFA07A',
|
||||
lightSeaGreen: '#20B2AA',
|
||||
lightSkyBlue: '#87CEFA',
|
||||
lightSlateGray: '#778899',
|
||||
lightSlateGrey: '#778899',
|
||||
lightSteelBlue: '#B0C4DE',
|
||||
lightYellow: '#FFFFE0',
|
||||
lime: '#00FF00',
|
||||
limeGreen: '#32CD32',
|
||||
linen: '#FAF0E6',
|
||||
ltBlue: '#ADD8E6',
|
||||
ltCoral: '#F08080',
|
||||
ltCyan: '#E0FFFF',
|
||||
ltGoldenrodYellow: '#FAFAD2',
|
||||
ltGray: '#D3D3D3',
|
||||
ltGreen: '#90EE90',
|
||||
ltGrey: '#D3D3D3',
|
||||
ltPink: '#FFB6C1',
|
||||
ltSalmon: '#FFA07A',
|
||||
ltSeaGreen: '#20B2AA',
|
||||
ltSkyBlue: '#87CEFA',
|
||||
ltSlateGray: '#778899',
|
||||
ltSlateGrey: '#778899',
|
||||
ltSteelBlue: '#B0C4DE',
|
||||
ltYellow: '#FFFFE0',
|
||||
magenta: '#FF00FF',
|
||||
maroon: '#800000',
|
||||
medAquamarine: '#66CDAA',
|
||||
medBlue: '#0000CD',
|
||||
mediumAquamarine: '#66CDAA',
|
||||
mediumBlue: '#0000CD',
|
||||
mediumOrchid: '#BA55D3',
|
||||
mediumPurple: '#9370DB',
|
||||
mediumSeaGreen: '#3CB371',
|
||||
mediumSlateBlue: '#7B68EE',
|
||||
mediumSpringGreen: '#00FA9A',
|
||||
mediumTurquoise: '#48D1CC',
|
||||
mediumVioletRed: '#C71585',
|
||||
medOrchid: '#BA55D3',
|
||||
medPurple: '#9370DB',
|
||||
medSeaGreen: '#3CB371',
|
||||
medSlateBlue: '#7B68EE',
|
||||
medSpringGreen: '#00FA9A',
|
||||
medTurquoise: '#48D1CC',
|
||||
medVioletRed: '#C71585',
|
||||
midnightBlue: '#191970',
|
||||
mintCream: '#F5FFFA',
|
||||
mistyRose: '#FFE4E1',
|
||||
moccasin: '#FFE4B5',
|
||||
navajoWhite: '#FFDEAD',
|
||||
navy: '#000080',
|
||||
oldLace: '#FDF5E6',
|
||||
olive: '#808000',
|
||||
oliveDrab: '#6B8E23',
|
||||
orange: '#FFA500',
|
||||
orangeRed: '#FF4500',
|
||||
orchid: '#DA70D6',
|
||||
paleGoldenrod: '#EEE8AA',
|
||||
paleGreen: '#98FB98',
|
||||
paleTurquoise: '#AFEEEE',
|
||||
paleVioletRed: '#DB7093',
|
||||
papayaWhip: '#FFEFD5',
|
||||
peachPuff: '#FFDAB9',
|
||||
peru: '#CD853F',
|
||||
pink: '#FFC0CB',
|
||||
plum: '#DDA0DD',
|
||||
powderBlue: '#B0E0E6',
|
||||
purple: '#800080',
|
||||
red: '#FF0000',
|
||||
rosyBrown: '#BC8F8F',
|
||||
royalBlue: '#4169E1',
|
||||
saddleBrown: '#8B4513',
|
||||
salmon: '#FA8072',
|
||||
sandyBrown: '#F4A460',
|
||||
seaGreen: '#2E8B57',
|
||||
seaShell: '#FFF5EE',
|
||||
sienna: '#A0522D',
|
||||
silver: '#C0C0C0',
|
||||
skyBlue: '#87CEEB',
|
||||
slateBlue: '#6A5ACD',
|
||||
slateGray: '#708090',
|
||||
slateGrey: '#708090',
|
||||
snow: '#FFFAFA',
|
||||
springGreen: '#00FF7F',
|
||||
steelBlue: '#4682B4',
|
||||
tan: '#D2B48C',
|
||||
teal: '#008080',
|
||||
thistle: '#D8BFD8',
|
||||
tomato: '#FF6347',
|
||||
turquoise: '#40E0D0',
|
||||
violet: '#EE82EE',
|
||||
wheat: '#F5DEB3',
|
||||
white: '#FFFFFF',
|
||||
whiteSmoke: '#F5F5F5',
|
||||
yellow: '#FFFF00',
|
||||
yellowGreen: '#9ACD32',
|
||||
}
|
||||
|
||||
/** Apply lumMod/lumOff/tint/shade/satMod/alpha modifiers (percentages, in units of 1/1000%). */
|
||||
export function applyColorMods(hex: string, mods: XmlNode | undefined): string {
|
||||
let { r, g, b } = hexToRgb(hex)
|
||||
@@ -59,21 +260,33 @@ export function applyColorMods(hex: string, mods: XmlNode | undefined): string {
|
||||
g += 255 * lumOff
|
||||
b += 255 * lumOff
|
||||
}
|
||||
// tint/shade blend in linear-gamma space (PowerPoint semantics: black + 55% tint
|
||||
// renders ≈#B1, not #73; verified against PowerPoint for Mac gradient stops)
|
||||
const lin = (v: number) => Math.pow(Math.max(v, 0) / 255, 2.2)
|
||||
const unlin = (v: number) => 255 * Math.pow(Math.max(v, 0), 1 / 2.2)
|
||||
if (shade != null) {
|
||||
r *= shade
|
||||
g *= shade
|
||||
b *= shade
|
||||
r = unlin(lin(r) * shade)
|
||||
g = unlin(lin(g) * shade)
|
||||
b = unlin(lin(b) * shade)
|
||||
}
|
||||
if (tint != null) {
|
||||
r = r * tint + 255 * (1 - tint)
|
||||
g = g * tint + 255 * (1 - tint)
|
||||
b = b * tint + 255 * (1 - tint)
|
||||
r = unlin(lin(r) * tint + (1 - tint))
|
||||
g = unlin(lin(g) * tint + (1 - tint))
|
||||
b = unlin(lin(b) * tint + (1 - tint))
|
||||
}
|
||||
const clamp = (v: number) => Math.max(0, Math.min(255, Math.round(v)))
|
||||
let out = '#' + [clamp(r), clamp(g), clamp(b)].map((v) => v.toString(16).padStart(2, '0')).join('').toUpperCase()
|
||||
let out =
|
||||
'#' +
|
||||
[clamp(r), clamp(g), clamp(b)]
|
||||
.map((v) => v.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
const alpha = pct('a:alpha')
|
||||
if (alpha != null && alpha < 1) {
|
||||
out += Math.round(alpha * 255).toString(16).padStart(2, '0').toUpperCase()
|
||||
out += Math.round(alpha * 255)
|
||||
.toString(16)
|
||||
.padStart(2, '0')
|
||||
.toUpperCase()
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -104,6 +317,18 @@ function rgbToHsl(r: number, g: number, b: number): { h: number; s: number; l: n
|
||||
return { h, s, l }
|
||||
}
|
||||
|
||||
/** Scale HSL luminance by a factor (legacy chart-style monochrome ramps). */
|
||||
export function scaleLuminance(hex: string, factor: number): string {
|
||||
const { r, g, b } = hexToRgb(hex)
|
||||
const { h, s, l } = rgbToHsl(r, g, b)
|
||||
const rgb = hslToRgb(h, s, Math.max(0, Math.min(0.97, l * factor)))
|
||||
const to2 = (v: number) =>
|
||||
Math.max(0, Math.min(255, Math.round(v)))
|
||||
.toString(16)
|
||||
.padStart(2, '0')
|
||||
return ('#' + to2(rgb.r) + to2(rgb.g) + to2(rgb.b)).toUpperCase()
|
||||
}
|
||||
|
||||
function hslToRgb(h: number, s: number, l: number): { r: number; g: number; b: number } {
|
||||
if (s === 0) {
|
||||
const v = l * 255
|
||||
|
||||
@@ -95,7 +95,7 @@ function buildPPrGroup(p: Paragraph, group: 'lnSpc' | 'spcBef' | 'spcAft' | 'bul
|
||||
if (b.font) s += `<a:buFont typeface="${escapeXmlAttr(b.font)}"/>`
|
||||
s +=
|
||||
b.type === 'number'
|
||||
? `<a:buAutoNum type="${escapeXmlAttr(b.numType ?? 'arabicPeriod')}"/>`
|
||||
? `<a:buAutoNum type="${escapeXmlAttr(b.numType ?? 'arabicPeriod')}"${b.startAt != null ? ` startAt="${b.startAt}"` : ''}/>`
|
||||
: `<a:buChar char="${escapeXmlAttr(b.char ?? '•')}"/>`
|
||||
return s
|
||||
}
|
||||
@@ -671,7 +671,7 @@ export function generateParagraphXml(p: Paragraph): string {
|
||||
if (b.font) kids += `<a:buFont typeface="${escapeXmlAttr(b.font)}"/>`
|
||||
kids +=
|
||||
b.type === 'number'
|
||||
? `<a:buAutoNum type="${escapeXmlAttr(b.numType ?? 'arabicPeriod')}"/>`
|
||||
? `<a:buAutoNum type="${escapeXmlAttr(b.numType ?? 'arabicPeriod')}"${b.startAt != null ? ` startAt="${b.startAt}"` : ''}/>`
|
||||
: `<a:buChar char="${escapeXmlAttr(b.char ?? '•')}"/>`
|
||||
}
|
||||
}
|
||||
@@ -1095,13 +1095,30 @@ export function patchPictureSrcRect(
|
||||
return xmlInner.slice(0, insertAt) + srcRectXml + xmlInner.slice(insertAt)
|
||||
}
|
||||
|
||||
/** Slide background image write-back parameters (the rel must already exist in the slide's rels). */
|
||||
export interface BackgroundImagePatch {
|
||||
imageRid: string
|
||||
/** Tile instead of stretch */
|
||||
tile?: boolean
|
||||
}
|
||||
|
||||
export type BackgroundFillPatch = string | GradientFillPatch | BackgroundImagePatch
|
||||
|
||||
/**
|
||||
* In-place patch of a slide's bodyPrefix: replace/inject the <p:bg> under <p:cSld>
|
||||
* with a solid color. Returns the new bodyPrefix (the caller writes it back to
|
||||
* slide.bodyPrefix and flags a rebuild).
|
||||
* with a solid color, gradient, or picture fill. Returns the new bodyPrefix (the
|
||||
* caller writes it back to slide.bodyPrefix and flags a rebuild).
|
||||
*/
|
||||
export function patchSlideBackgroundXml(bodyPrefix: string, color: string): string {
|
||||
const bgXml = `<p:bg><p:bgPr><a:solidFill><a:srgbClr val="${hex6(color)}"/></a:solidFill><a:effectLst/></p:bgPr></p:bg>`
|
||||
export function patchSlideBackgroundXml(bodyPrefix: string, fill: BackgroundFillPatch): string {
|
||||
const fillXml =
|
||||
typeof fill === 'object' && 'imageRid' in fill
|
||||
? `<a:blipFill><a:blip r:embed="${fill.imageRid}"/>` +
|
||||
(fill.tile
|
||||
? '<a:tile tx="0" ty="0" sx="100000" sy="100000" flip="none" algn="tl"/>'
|
||||
: '<a:stretch><a:fillRect/></a:stretch>') +
|
||||
'</a:blipFill>'
|
||||
: buildFillXml(fill)
|
||||
const bgXml = `<p:bg><p:bgPr>${fillXml}<a:effectLst/></p:bgPr></p:bg>`
|
||||
const existing = /<p:bg>[\s\S]*?<\/p:bg>|<p:bg\s[^>]*\/>/.exec(bodyPrefix)
|
||||
if (existing) {
|
||||
return (
|
||||
@@ -1116,6 +1133,30 @@ export function patchSlideBackgroundXml(bodyPrefix: string, color: string): stri
|
||||
return bodyPrefix.slice(0, at) + bgXml + bodyPrefix.slice(at)
|
||||
}
|
||||
|
||||
/** Remove the slide's own <p:bg> override (background falls back to layout/master). */
|
||||
export function removeSlideBackgroundXml(bodyPrefix: string): string {
|
||||
const existing = /<p:bg>[\s\S]*?<\/p:bg>|<p:bg\s[^>]*\/>/.exec(bodyPrefix)
|
||||
if (!existing) return bodyPrefix
|
||||
return bodyPrefix.slice(0, existing.index) + bodyPrefix.slice(existing.index + existing[0].length)
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle showMasterSp on the <p:sld> root ("hide background graphics").
|
||||
* hidden=true writes showMasterSp="0"; hidden=false removes the attribute
|
||||
* (default is shown).
|
||||
*/
|
||||
export function patchSlideShowMasterSpXml(bodyPrefix: string, hidden: boolean): string {
|
||||
const open = /<p:sld((?:\s(?:"[^"]*"|'[^']*'|[^"'>])*?)?)>/.exec(bodyPrefix)
|
||||
if (!open) return bodyPrefix
|
||||
let attrs = (open[1] ?? '').replace(/\s+showMasterSp="[^"]*"/, '')
|
||||
if (hidden) attrs += ' showMasterSp="0"'
|
||||
return (
|
||||
bodyPrefix.slice(0, open.index) +
|
||||
`<p:sld${attrs}>` +
|
||||
bodyPrefix.slice(open.index + open[0].length)
|
||||
)
|
||||
}
|
||||
|
||||
// ── Slide transition patch ──────────────────────────────────────────────
|
||||
|
||||
export type SlideTransitionKind =
|
||||
|
||||
@@ -7,8 +7,14 @@
|
||||
import JSZip from 'jszip'
|
||||
import { PackageArchive, relsPathFor, resolveTarget } from './zip'
|
||||
import { parseClrMap, parseTheme, type Theme } from './theme'
|
||||
import { parseSlide, parseDecorations, sliceGroupChildXmls, type ParseContext } from './parse'
|
||||
import { parsePlaceholderMap, parseMasterTextStyles } from './placeholder'
|
||||
import {
|
||||
parseSlide,
|
||||
parseDecorations,
|
||||
parseBackground,
|
||||
sliceGroupChildXmls,
|
||||
type ParseContext,
|
||||
} from './parse'
|
||||
import { parsePlaceholderMap, parseMasterTextStyles, parseDefaultTextStyle } from './placeholder'
|
||||
import {
|
||||
generateParagraphXml,
|
||||
patchElementFill,
|
||||
@@ -19,12 +25,14 @@ import {
|
||||
patchSlideAdvanceTimeXml,
|
||||
patchSlideBackgroundXml,
|
||||
patchSlideHiddenXml,
|
||||
patchSlideShowMasterSpXml,
|
||||
patchSlideTransitionXml,
|
||||
patchTextElementXml,
|
||||
rebuildTxBody,
|
||||
readSlideAdvanceTimeXml,
|
||||
readSlideHiddenXml,
|
||||
readSlideTransitionXml,
|
||||
removeSlideBackgroundXml,
|
||||
type GradientFillPatch,
|
||||
type SlideTransitionKind,
|
||||
} from './generate'
|
||||
@@ -103,13 +111,16 @@ export {
|
||||
patchSlideAdvanceTimeXml,
|
||||
patchSlideBackgroundXml,
|
||||
patchSlideHiddenXml,
|
||||
patchSlideShowMasterSpXml,
|
||||
patchSlideTransitionXml,
|
||||
readSlideAdvanceTimeXml,
|
||||
readSlideHiddenXml,
|
||||
readSlideTransitionXml,
|
||||
removeSlideBackgroundXml,
|
||||
generateParagraphXml,
|
||||
generateXfrmXml,
|
||||
type GradientFillPatch,
|
||||
type BackgroundImagePatch,
|
||||
type SlideTransitionKind,
|
||||
} from './generate'
|
||||
export {
|
||||
@@ -184,6 +195,7 @@ export {
|
||||
type ChartKind,
|
||||
type ChartAxisStyle,
|
||||
} from './chart'
|
||||
export { parseChartExXml } from './chartex'
|
||||
export { getSlideNotes, setSlideNotes, notesPathForSlide, unescapeXml } from './notes'
|
||||
export {
|
||||
getSlideComments,
|
||||
@@ -277,6 +289,7 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
|
||||
ctx.theme = parseTheme(themeXml)
|
||||
// Dark masters remap schemeClr names (bg1→dk1 …); must be in place before any color resolution below
|
||||
ctx.theme.clrMap = parseClrMap(masterXml, layoutXml, slideXml)
|
||||
ctx.themeMediaRels = partMediaRels(archive, chain.themePath)
|
||||
}
|
||||
}
|
||||
if (layoutXml) {
|
||||
@@ -290,14 +303,22 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
|
||||
ctx.masterBg = masterXml
|
||||
if (chain.masterPath) ctx.masterMediaRels = partMediaRels(archive, chain.masterPath)
|
||||
}
|
||||
// presentation.xml <p:defaultTextStyle>: base text defaults for non-placeholder shapes
|
||||
const presXml = archive.readText('ppt/presentation.xml')
|
||||
if (presXml) ctx.defaultTextStyle = parseDefaultTextStyle(presXml, ctx.theme)
|
||||
// Media rId → zip path; chart rId → chart part content
|
||||
const rels = archive.readRels(slidePath)
|
||||
const mediaRels = new Map<string, string>()
|
||||
const chartXmls = new Map<string, string>()
|
||||
const chartMediaRels = new Map<string, Map<string, string>>()
|
||||
const chartUserShapes = new Map<string, string>()
|
||||
const avRels = new Map<string, { target: string; external?: boolean }>()
|
||||
const diagramDrawings = new Map<string, string>()
|
||||
const diagramDatas = new Map<string, string>()
|
||||
const diagramMediaRels = new Map<string, Map<string, string>>()
|
||||
const diagramLayouts = new Map<string, string>()
|
||||
const diagramColors = new Map<string, string>()
|
||||
const vmlPreviews = new Map<string, string>()
|
||||
const hlinkRels = new Map<string, string>()
|
||||
let slideOrder: string[] | undefined
|
||||
for (const rel of rels.values()) {
|
||||
@@ -310,12 +331,19 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
|
||||
if (idx >= 0) hlinkRels.set(rel.id, `slide:${idx}`)
|
||||
} else if (rel.type.endsWith('/image')) {
|
||||
mediaRels.set(rel.id, resolveTarget(slidePath, rel.target))
|
||||
} else if (rel.type.endsWith('/chart')) {
|
||||
} else if (rel.type.endsWith('/chart') || rel.type.endsWith('/chartEx')) {
|
||||
const target = resolveTarget(slidePath, rel.target)
|
||||
const xml = archive.readText(target)
|
||||
if (xml) {
|
||||
chartXmls.set(rel.id, xml)
|
||||
chartMediaRels.set(rel.id, partMediaRels(archive, target))
|
||||
// User-drawn overlays live in a chartUserShapes drawing referenced from the chart part's own rels
|
||||
for (const sub of archive.readRels(target).values()) {
|
||||
if (sub.type.endsWith('/chartUserShapes')) {
|
||||
const usXml = archive.readText(resolveTarget(target, sub.target))
|
||||
if (usXml) chartUserShapes.set(rel.id, usXml)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (/\/(?:video|audio|media)$/.test(rel.type)) {
|
||||
// Audio/video (r:link of a:videoFile/a:audioFile; embedded or external)
|
||||
@@ -324,11 +352,29 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
|
||||
target: external ? rel.target : resolveTarget(slidePath, rel.target),
|
||||
...(external ? { external: true } : {}),
|
||||
})
|
||||
} else if (rel.type.endsWith('/vmlDrawing')) {
|
||||
// Legacy OLE previews: v:shape (matched by oleObj spid) → v:imagedata → the VML part's own image rel
|
||||
const vmlPath = resolveTarget(slidePath, rel.target)
|
||||
const vml = archive.readText(vmlPath)
|
||||
if (vml) {
|
||||
const vmlRels = archive.readRels(vmlPath)
|
||||
for (const m of vml.matchAll(/<v:shape\b([^>]*)>([\s\S]*?)<\/v:shape>/g)) {
|
||||
const relid = /<v:imagedata\b[^>]*\bo:relid="([^"]+)"/.exec(m[2]!)?.[1]
|
||||
const imgRel = relid ? vmlRels.get(relid) : undefined
|
||||
if (!imgRel) continue
|
||||
const target = resolveTarget(vmlPath, imgRel.target)
|
||||
for (const key of ['id', 'o:spid']) {
|
||||
const v = new RegExp(`\\b${key}="([^"]+)"`).exec(m[1]!)?.[1]
|
||||
if (v) vmlPreviews.set(v, target)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (rel.type.endsWith('/diagramData')) {
|
||||
// SmartArt prerendered drawing part: the data part's <dsp:dataModelExt relId="…">
|
||||
// points at a diagramDrawing relationship in the container part's (slide's) rels; fall back to the data part's own rels
|
||||
const dataPath = resolveTarget(slidePath, rel.target)
|
||||
const dataXml = archive.readText(dataPath)
|
||||
if (dataXml) diagramDatas.set(rel.id, dataXml)
|
||||
const relId = dataXml
|
||||
? /<dsp:dataModelExt\b[^>]*\brelId="([^"]+)"/.exec(dataXml)?.[1]
|
||||
: undefined
|
||||
@@ -342,15 +388,26 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
|
||||
diagramMediaRels.set(rel.id, partMediaRels(archive, drawingPath))
|
||||
}
|
||||
}
|
||||
} else if (rel.type.endsWith('/diagramLayout')) {
|
||||
const xml = archive.readText(resolveTarget(slidePath, rel.target))
|
||||
if (xml) diagramLayouts.set(rel.id, xml)
|
||||
} else if (rel.type.endsWith('/diagramColors')) {
|
||||
const xml = archive.readText(resolveTarget(slidePath, rel.target))
|
||||
if (xml) diagramColors.set(rel.id, xml)
|
||||
}
|
||||
}
|
||||
ctx.mediaRels = mediaRels
|
||||
ctx.chartXmls = chartXmls
|
||||
if (chartMediaRels.size) ctx.chartMediaRels = chartMediaRels
|
||||
if (chartUserShapes.size) ctx.chartUserShapes = chartUserShapes
|
||||
if (hlinkRels.size) ctx.hlinkRels = hlinkRels
|
||||
if (avRels.size) ctx.avRels = avRels
|
||||
if (diagramDrawings.size) ctx.diagramDrawings = diagramDrawings
|
||||
if (diagramDatas.size) ctx.diagramDatas = diagramDatas
|
||||
if (diagramMediaRels.size) ctx.diagramMediaRels = diagramMediaRels
|
||||
if (diagramLayouts.size) ctx.diagramLayouts = diagramLayouts
|
||||
if (diagramColors.size) ctx.diagramColors = diagramColors
|
||||
if (vmlPreviews.size) ctx.vmlPreviews = vmlPreviews
|
||||
// Table style definitions (embedded custom styles; built-in styles handled by table-style as fallback)
|
||||
ctx.tableStyles = archive.readText('ppt/tableStyles.xml') ?? undefined
|
||||
|
||||
@@ -697,13 +754,165 @@ export function patchedElementXml(el: SlideElement): string {
|
||||
return xml
|
||||
}
|
||||
|
||||
/** Set a solid slide background: patch the bodyPrefix and sync the model (written back with the whole-slide rebuild on save). */
|
||||
export function setSlideBackground(slide: Slide, color: string): void {
|
||||
slide.bodyPrefix = patchSlideBackgroundXml(slide.bodyPrefix, color)
|
||||
slide.background = { type: 'solid', color }
|
||||
/**
|
||||
* Set a solid or gradient slide background: patch the bodyPrefix and sync the model
|
||||
* (written back with the whole-slide rebuild on save).
|
||||
*/
|
||||
export function setSlideBackground(slide: Slide, fill: string | GradientFillPatch): void {
|
||||
slide.bodyPrefix = patchSlideBackgroundXml(slide.bodyPrefix, fill)
|
||||
slide.background =
|
||||
typeof fill === 'string'
|
||||
? { type: 'solid', color: fill }
|
||||
: {
|
||||
type: 'gradient',
|
||||
stops: fill.stops.map((s) => ({ pos: s.pos, color: s.color })),
|
||||
...(fill.radial ? { path: 'circle' as const } : { angle: Math.round(fill.angle ?? 0) }),
|
||||
}
|
||||
slide.bgOwn = true
|
||||
slide.structureDirty = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a picture slide background. Source is either fresh bytes (lands a new media
|
||||
* part) or an existing media path (e.g. applying one picked image to all slides —
|
||||
* only a rel is added). Returns the media path used, or null for unsupported formats.
|
||||
*/
|
||||
export function setSlideBackgroundImage(
|
||||
opened: OpenedPptx,
|
||||
slide: Slide,
|
||||
source: { bytes: Uint8Array; ext: string } | { mediaPath: string },
|
||||
tile?: boolean,
|
||||
): string | null {
|
||||
let rid: string | undefined
|
||||
let mediaPath: string
|
||||
if ('bytes' in source) {
|
||||
const added = addImageMediaAndRel(opened, slide, source.bytes, source.ext)
|
||||
if (!added) return null
|
||||
rid = added.rid
|
||||
mediaPath = added.mediaPath
|
||||
} else {
|
||||
mediaPath = source.mediaPath
|
||||
if (!opened.archive.entries.has(mediaPath)) return null
|
||||
rid = imageRelFor(opened.archive, slide, mediaPath)
|
||||
if (!rid) return null
|
||||
}
|
||||
slide.bodyPrefix = patchSlideBackgroundXml(slide.bodyPrefix, {
|
||||
imageRid: rid,
|
||||
...(tile ? { tile: true } : {}),
|
||||
})
|
||||
slide.background = { type: 'image', mediaRef: mediaPath, mode: tile ? 'tile' : 'stretch' }
|
||||
slide.bgOwn = true
|
||||
slide.structureDirty = true
|
||||
return mediaPath
|
||||
}
|
||||
|
||||
/** Find the slide's image rel for a media path, adding one when missing. */
|
||||
function imageRelFor(archive: PackageArchive, slide: Slide, mediaPath: string): string | undefined {
|
||||
for (const rel of archive.readRels(slide.path).values()) {
|
||||
if (rel.type.endsWith('/image') && resolveTarget(slide.path, rel.target) === mediaPath)
|
||||
return rel.id
|
||||
}
|
||||
const relsPath = relsPathFor(slide.path)
|
||||
const rels =
|
||||
archive.readText(relsPath) ??
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>'
|
||||
let maxRid = 0
|
||||
for (const m of rels.matchAll(/Id="rId(\d+)"/g)) maxRid = Math.max(maxRid, Number(m[1]))
|
||||
const rid = `rId${maxRid + 1}`
|
||||
// slide parts live in ppt/slides/, media in ppt/media/
|
||||
const target = mediaPath.replace(/^ppt\//, '../')
|
||||
const relXml = `<Relationship Id="${rid}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="${target}"/>`
|
||||
archive.entries.set(
|
||||
relsPath,
|
||||
Buffer.from(rels.replace('</Relationships>', `${relXml}</Relationships>`), 'utf8'),
|
||||
)
|
||||
return rid
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the slide's own <p:bg> override; the background falls back to the
|
||||
* layout/master definition (recomputed here so rendering updates without a reopen).
|
||||
*/
|
||||
export function resetSlideBackground(opened: OpenedPptx, slide: Slide): void {
|
||||
slide.bodyPrefix = removeSlideBackgroundXml(slide.bodyPrefix)
|
||||
delete slide.bgOwn
|
||||
slide.structureDirty = true
|
||||
const inherit = slideInheritanceCtx(opened.archive, slide.path)
|
||||
const inherited =
|
||||
(inherit.layoutXml
|
||||
? parseBackground(inherit.layoutXml, {
|
||||
theme: inherit.theme,
|
||||
mediaRels: inherit.layoutMediaRels,
|
||||
themeMediaRels: inherit.themeMediaRels,
|
||||
})
|
||||
: undefined) ??
|
||||
(inherit.masterXml
|
||||
? parseBackground(inherit.masterXml, {
|
||||
theme: inherit.theme,
|
||||
mediaRels: inherit.masterMediaRels,
|
||||
themeMediaRels: inherit.themeMediaRels,
|
||||
})
|
||||
: undefined)
|
||||
if (inherited) slide.background = inherited
|
||||
else delete slide.background
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle "hide background graphics" (<p:sld showMasterSp="0">) and rebuild the
|
||||
* slide's decoration layer so rendering reflects the change immediately.
|
||||
*/
|
||||
export function setSlideBgGraphicsHidden(opened: OpenedPptx, slide: Slide, hidden: boolean): void {
|
||||
slide.bodyPrefix = patchSlideShowMasterSpXml(slide.bodyPrefix, hidden)
|
||||
if (hidden) slide.masterSpHidden = true
|
||||
else delete slide.masterSpHidden
|
||||
slide.structureDirty = true
|
||||
const inherit = slideInheritanceCtx(opened.archive, slide.path)
|
||||
const decorations = buildDecorations(
|
||||
opened.archive,
|
||||
slide.path,
|
||||
slide.bodyPrefix, // carries the fresh showMasterSp attribute
|
||||
slide,
|
||||
inherit.layoutXml,
|
||||
inherit.masterXml,
|
||||
{
|
||||
layoutPath: inherit.layoutPath,
|
||||
masterPath: inherit.masterPath,
|
||||
theme: inherit.theme,
|
||||
masterPlaceholders: inherit.masterPlaceholders,
|
||||
masterTextStyles: inherit.masterTextStyles,
|
||||
},
|
||||
)
|
||||
if (decorations.length) slide.decorations = decorations
|
||||
else delete slide.decorations
|
||||
}
|
||||
|
||||
/** Layout/master inheritance bundle for one slide (theme + placeholder maps + part media rels). */
|
||||
function slideInheritanceCtx(archive: PackageArchive, slidePath: string) {
|
||||
const chain = archive.resolveSlideChain(slidePath)
|
||||
const layoutXml = (chain.layoutPath ? archive.readText(chain.layoutPath) : undefined) ?? undefined
|
||||
const masterXml = (chain.masterPath ? archive.readText(chain.masterPath) : undefined) ?? undefined
|
||||
let theme: Theme | undefined
|
||||
if (chain.themePath) {
|
||||
const themeXml = archive.readText(chain.themePath)
|
||||
if (themeXml) {
|
||||
theme = parseTheme(themeXml)
|
||||
theme.clrMap = parseClrMap(masterXml, layoutXml, archive.readText(slidePath) ?? undefined)
|
||||
}
|
||||
}
|
||||
return {
|
||||
layoutPath: chain.layoutPath,
|
||||
masterPath: chain.masterPath,
|
||||
layoutXml,
|
||||
masterXml,
|
||||
theme,
|
||||
masterPlaceholders: masterXml ? parsePlaceholderMap(masterXml, theme) : undefined,
|
||||
masterTextStyles: masterXml ? parseMasterTextStyles(masterXml, theme) : undefined,
|
||||
layoutMediaRels: chain.layoutPath ? partMediaRels(archive, chain.layoutPath) : undefined,
|
||||
masterMediaRels: chain.masterPath ? partMediaRels(archive, chain.masterPath) : undefined,
|
||||
themeMediaRels: chain.themePath ? partMediaRels(archive, chain.themePath) : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a picture element's srcRect crop (0..1 fractions, null = full image).
|
||||
* Flags dirtySrcRect so save surgically patches <a:srcRect>; no other bytes are
|
||||
|
||||
+1444
-16
File diff suppressed because it is too large
Load Diff
@@ -36,12 +36,26 @@ export interface LevelTextStyle {
|
||||
/** Character casing <a:defRPr cap>: 'all' | 'small' | 'none' */
|
||||
cap?: string
|
||||
color?: string
|
||||
/** <a:defRPr><a:effectLst><a:outerShdw> (rare; e.g. watermark text boxes) */
|
||||
shadow?: import('./types').ShadowEffect
|
||||
latinFont?: string
|
||||
eaFont?: string
|
||||
csFont?: string
|
||||
align?: TextAlign
|
||||
/** Bullet default (master bodyStyle levels commonly use buChar '•') */
|
||||
bullet?: { type: 'none' | 'char' | 'number'; char?: string }
|
||||
bullet?: {
|
||||
type: 'none' | 'char' | 'number'
|
||||
char?: string
|
||||
/** <a:buFont> typeface (symbol fonts like Wingdings) */
|
||||
font?: string
|
||||
color?: string
|
||||
/** <a:buSzPct> (%, 100 = same size as text) */
|
||||
sizePct?: number
|
||||
/** <a:buAutoNum type> (arabicPeriod/romanLcParen…) */
|
||||
numType?: string
|
||||
/** <a:buAutoNum startAt> */
|
||||
startAt?: number
|
||||
}
|
||||
/** Paragraph left indent (EMU) */
|
||||
marL?: number
|
||||
/** First-line indent (EMU, negative = hanging) */
|
||||
@@ -73,6 +87,10 @@ export interface PlaceholderGeom {
|
||||
transform: Transform | null
|
||||
/** Default text style from this placeholder txBody's <a:lstStyle> */
|
||||
textStyle?: TextStyleLevels
|
||||
/** Vertical anchor from this placeholder's <a:bodyPr anchor=""> */
|
||||
anchor?: 'top' | 'middle' | 'bottom'
|
||||
/** Raw spPr node when it carries an explicit fill (parse.ts resolves it with the part's rels) */
|
||||
fillSpPr?: unknown
|
||||
}
|
||||
|
||||
/** Placeholder geometry table for one layer (layout or master). */
|
||||
@@ -83,6 +101,14 @@ export interface PlaceholderMap {
|
||||
const TITLE_TYPES = new Set(['title', 'ctrTitle'])
|
||||
const BODY_TYPES = new Set(['body', 'subTitle', 'obj', ''])
|
||||
|
||||
const ANCHOR_MAP: Record<string, PlaceholderGeom['anchor']> = {
|
||||
t: 'top',
|
||||
ctr: 'middle',
|
||||
b: 'bottom',
|
||||
}
|
||||
|
||||
const FILL_TAGS = ['a:solidFill', 'a:gradFill', 'a:blipFill', 'a:pattFill', 'a:noFill']
|
||||
|
||||
function parseXfrmNode(xfrmRaw: unknown): Transform | null {
|
||||
if (!xfrmRaw) return null
|
||||
const xfrm = asXmlNode(xfrmRaw)
|
||||
@@ -128,10 +154,21 @@ export function parsePlaceholderMap(layoutOrMasterXml: string, theme?: Theme): P
|
||||
const ph = asXmlNode(phRaw)
|
||||
const type = String(ph['@_type'] ?? 'body')
|
||||
const idx = ph['@_idx'] != null ? String(ph['@_idx']) : ''
|
||||
const transform = parseXfrmNode(asXmlNode(sp['p:spPr'])['a:xfrm'])
|
||||
const spPr = asXmlNode(sp['p:spPr'])
|
||||
const transform = parseXfrmNode(spPr['a:xfrm'])
|
||||
const textStyle = parseLstStyleLevels(asXmlNode(sp['p:txBody'])['a:lstStyle'], theme)
|
||||
if (!transform && !textStyle) continue
|
||||
entries.push({ type, idx, transform, ...(textStyle ? { textStyle } : {}) })
|
||||
const anchorAttr = asXmlNode(asXmlNode(sp['p:txBody'])['a:bodyPr'])['@_anchor']
|
||||
const anchor = ANCHOR_MAP[String(anchorAttr ?? '')]
|
||||
const hasFill = FILL_TAGS.some((tag) => tag in spPr)
|
||||
if (!transform && !textStyle && !anchor && !hasFill) continue
|
||||
entries.push({
|
||||
type,
|
||||
idx,
|
||||
transform,
|
||||
...(textStyle ? { textStyle } : {}),
|
||||
...(anchor ? { anchor } : {}),
|
||||
...(hasFill ? { fillSpPr: spPr } : {}),
|
||||
})
|
||||
}
|
||||
return { entries }
|
||||
}
|
||||
@@ -192,7 +229,21 @@ function parseLvlPPr(pPrRaw: unknown, theme?: Theme): LevelTextStyle | undefined
|
||||
if (pPr['a:buNone'] !== undefined) out.bullet = { type: 'none' }
|
||||
else if (buChar != null) {
|
||||
out.bullet = { type: 'char', char: decodeAttrCharRefs(String(buChar)) }
|
||||
} else if (pPr['a:buAutoNum']) out.bullet = { type: 'number' }
|
||||
} else if (pPr['a:buAutoNum']) {
|
||||
out.bullet = { type: 'number' }
|
||||
const an = asXmlNode(pPr['a:buAutoNum'])
|
||||
if (an['@_type'] != null) out.bullet.numType = String(an['@_type'])
|
||||
const startAt = parseInt(String(an['@_startAt']), 10)
|
||||
if (Number.isFinite(startAt) && startAt > 1) out.bullet.startAt = startAt
|
||||
}
|
||||
if (out.bullet && out.bullet.type !== 'none') {
|
||||
const buFont = typefaceAttr(pPr['a:buFont'])
|
||||
if (buFont) out.bullet.font = buFont
|
||||
const buColor = resolveColorNode(pPr['a:buClr'], theme)
|
||||
if (buColor) out.bullet.color = buColor
|
||||
const buSz = asXmlNode(pPr['a:buSzPct'])['@_val']
|
||||
if (buSz != null) out.bullet.sizePct = (parseInt(String(buSz), 10) || 0) / 1000
|
||||
}
|
||||
if (pPr['@_marL'] != null) {
|
||||
const v = parseInt(String(pPr['@_marL']), 10)
|
||||
if (!Number.isNaN(v)) out.marL = v
|
||||
@@ -210,6 +261,20 @@ function parseLvlPPr(pPrRaw: unknown, theme?: Theme): LevelTextStyle | undefined
|
||||
if (defRPr['@_cap'] != null) out.cap = String(defRPr['@_cap'])
|
||||
const color = resolveColorNode(defRPr['a:solidFill'], theme)
|
||||
if (color) out.color = color
|
||||
const shdw = asXmlNode(asXmlNode(defRPr['a:effectLst'])['a:outerShdw'])
|
||||
const shdwColor = resolveColorNode(shdw, theme)
|
||||
if (shdwColor) {
|
||||
const num = (k: string) => {
|
||||
const v = parseInt(String(shdw[k] ?? ''), 10)
|
||||
return Number.isFinite(v) ? v : 0
|
||||
}
|
||||
out.shadow = {
|
||||
color: shdwColor,
|
||||
blurRad: num('@_blurRad'),
|
||||
dist: num('@_dist'),
|
||||
dirDeg: num('@_dir') / 60000,
|
||||
}
|
||||
}
|
||||
const latin = resolveFontRef(typefaceAttr(defRPr['a:latin']), theme)
|
||||
if (latin) out.latinFont = latin
|
||||
const ea = resolveFontRef(typefaceAttr(defRPr['a:ea']), theme)
|
||||
@@ -229,6 +294,20 @@ export function parseLstStyleLevels(lst: unknown, theme?: Theme): TextStyleLevel
|
||||
return levels.some(Boolean) ? { levels } : undefined
|
||||
}
|
||||
|
||||
/** presentation.xml <p:defaultTextStyle> → base defaults for non-placeholder text boxes. */
|
||||
export function parseDefaultTextStyle(
|
||||
presentationXml: string,
|
||||
theme?: Theme,
|
||||
): TextStyleLevels | undefined {
|
||||
let doc: XmlNode
|
||||
try {
|
||||
doc = asXmlNode(phParser.parse(presentationXml))
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
return parseLstStyleLevels(asXmlNode(doc['p:presentation'])['p:defaultTextStyle'], theme)
|
||||
}
|
||||
|
||||
/** master <p:txStyles> → default styles for the title/body/other families. */
|
||||
export function parseMasterTextStyles(masterXml: string, theme?: Theme): MasterTextStyles {
|
||||
let doc: XmlNode
|
||||
@@ -271,6 +350,35 @@ function findStyleInMap(
|
||||
return hit?.textStyle
|
||||
}
|
||||
|
||||
/** Find the bodyPr anchor in a layer's map by placeholder (type, idx). Unlike
|
||||
* findStyleInMap there is no idx-only step: master placeholders reuse idx values
|
||||
* across types (a dt idx="2" must not anchor a body idx="2" to the bottom). */
|
||||
function findAnchorInMap(
|
||||
map: PlaceholderMap | undefined,
|
||||
type: string | undefined,
|
||||
idx: string | undefined,
|
||||
): PlaceholderGeom['anchor'] {
|
||||
if (!map || map.entries.length === 0) return undefined
|
||||
const t = type ?? 'body'
|
||||
const i = idx ?? ''
|
||||
const anchored = map.entries.filter((e) => e.anchor)
|
||||
let hit = anchored.find((e) => e.type === t && e.idx === i)
|
||||
if (!hit) hit = anchored.find((e) => e.type === t)
|
||||
if (!hit && TITLE_TYPES.has(t)) hit = anchored.find((e) => TITLE_TYPES.has(e.type))
|
||||
if (!hit && BODY_TYPES.has(t)) hit = anchored.find((e) => BODY_TYPES.has(e.type))
|
||||
return hit?.anchor
|
||||
}
|
||||
|
||||
/** Resolve a placeholder's inherited vertical anchor: layout first, master as fallback. */
|
||||
export function resolvePlaceholderAnchor(
|
||||
layout: PlaceholderMap | undefined,
|
||||
master: PlaceholderMap | undefined,
|
||||
type: string | undefined,
|
||||
idx: string | undefined,
|
||||
): PlaceholderGeom['anchor'] {
|
||||
return findAnchorInMap(layout, type, idx) ?? findAnchorInMap(master, type, idx)
|
||||
}
|
||||
|
||||
/**
|
||||
* Placeholder text style inheritance chain (highest priority first):
|
||||
* layout placeholder lstStyle → master placeholder lstStyle → master txStyles
|
||||
@@ -319,6 +427,7 @@ export function mergeTextStyleChain(
|
||||
if (out.italic == null && lvl.italic != null) out.italic = lvl.italic
|
||||
if (out.cap == null && lvl.cap != null) out.cap = lvl.cap
|
||||
if (out.color == null && lvl.color != null) out.color = lvl.color
|
||||
if (out.shadow == null && lvl.shadow != null) out.shadow = lvl.shadow
|
||||
if (out.latinFont == null && lvl.latinFont != null) out.latinFont = lvl.latinFont
|
||||
if (out.eaFont == null && lvl.eaFont != null) out.eaFont = lvl.eaFont
|
||||
if (out.csFont == null && lvl.csFont != null) out.csFont = lvl.csFont
|
||||
@@ -389,6 +498,40 @@ function findInMap(
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Placeholder fill inheritance: the nearest layer (layout, then master) whose matching
|
||||
* placeholder spPr carries an explicit fill — including <a:noFill>, which stops the fallback.
|
||||
* Returns the raw spPr plus its layer so the caller resolves blip rIds in that part's rels.
|
||||
*/
|
||||
export function resolvePlaceholderFillSpPr(
|
||||
layout: PlaceholderMap | undefined,
|
||||
master: PlaceholderMap | undefined,
|
||||
type: string | undefined,
|
||||
idx: string | undefined,
|
||||
): { spPr: unknown; layer: 'layout' | 'master' } | undefined {
|
||||
const t = type ?? 'body'
|
||||
const i = idx ?? ''
|
||||
for (const [map, layer] of [
|
||||
[layout, 'layout'],
|
||||
[master, 'master'],
|
||||
] as const) {
|
||||
if (!map) continue
|
||||
// Match the placeholder first (same order as geometry inheritance), THEN take its
|
||||
// fill. Filtering to fill-carrying entries up front made an unrelated same-type
|
||||
// sibling donate its fill when the true match had none (fed deck: a body ph
|
||||
// picked up a decorative content placeholder's dark fill).
|
||||
const entries = map.entries
|
||||
const hit =
|
||||
entries.find((e) => e.type === t && e.idx === i) ??
|
||||
(i !== '' ? entries.find((e) => e.idx === i) : undefined) ??
|
||||
entries.find((e) => e.type === t) ??
|
||||
(TITLE_TYPES.has(t) ? entries.find((e) => TITLE_TYPES.has(e.type)) : undefined) ??
|
||||
(BODY_TYPES.has(t) ? entries.find((e) => BODY_TYPES.has(e.type)) : undefined)
|
||||
if (hit?.fillSpPr != null) return { spPr: hit.fillSpPr, layer }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve placeholder geometry: layout first, master as fallback.
|
||||
* undefined means neither layer has inheritable geometry (the render layer may
|
||||
|
||||
@@ -33,7 +33,16 @@ export interface SlideScan {
|
||||
const TAG_RE = /<\/?(?:[^<>"']|"[^"]*"|'[^']*')*>/g
|
||||
const NAME_RE = /^<\/?\s*([A-Za-z_][\w:.-]*)/
|
||||
|
||||
const SHAPE_TAGS = new Set(['p:sp', 'p:pic', 'p:graphicFrame', 'p:grpSp', 'p:cxnSp'])
|
||||
// mc:AlternateContent: scanned as an element so its Choice (e.g. a chartEx frame)
|
||||
// can render; save replays the whole block's original bytes
|
||||
const SHAPE_TAGS = new Set([
|
||||
'p:sp',
|
||||
'p:pic',
|
||||
'p:graphicFrame',
|
||||
'p:grpSp',
|
||||
'p:cxnSp',
|
||||
'mc:AlternateContent',
|
||||
])
|
||||
|
||||
export function scanSlide(slideXml: string): SlideScan {
|
||||
const spTreeOpen = /<p:spTree(?:\s(?:[^<>"']|"[^"]*"|'[^']*')*)?>/.exec(slideXml)
|
||||
|
||||
@@ -42,6 +42,10 @@ export interface TableStyleDef {
|
||||
/** First-row bottom edge / last-row top edge (header separator lines, used when the firstRow/lastRow flags are on) */
|
||||
firstRowBottom?: Stroke
|
||||
lastRowTop?: Stroke
|
||||
/** <a:tblBg> direct fill: whole-table background under transparent/alpha cell fills */
|
||||
tblBg?: Fill
|
||||
/** <a:tblBg><a:fillRef>: theme fillStyleLst template ref (parse.ts instantiates it with phClr) */
|
||||
tblBgRef?: { idx: number; phClr?: string }
|
||||
}
|
||||
|
||||
/** Region toggles from a:tblPr. */
|
||||
@@ -430,14 +434,30 @@ const tsParser = new XMLParser({
|
||||
function readColor(node: unknown, theme: Theme | undefined): string | undefined {
|
||||
if (!node || typeof node !== 'object') return undefined
|
||||
const n = asXmlNode(node)
|
||||
const srgb = asXmlNode(n['a:srgbClr'])['@_val']
|
||||
if (srgb) return '#' + String(srgb).toUpperCase()
|
||||
// tint/shade/alpha child modifiers; alpha lands as an #RRGGBBAA suffix so
|
||||
// banded fills composite over <a:tblBg> instead of collapsing to opaque
|
||||
const withMods = (base: string, clr: XmlNode): string => {
|
||||
let c = base
|
||||
const t = asXmlNode(clr['a:tint'])['@_val']
|
||||
if (t) c = tint(c, parseInt(String(t), 10) / 100000)
|
||||
const sh = asXmlNode(clr['a:shade'])['@_val']
|
||||
if (sh) c = shade(c, parseInt(String(sh), 10) / 100000)
|
||||
const al = asXmlNode(clr['a:alpha'])['@_val']
|
||||
if (al) {
|
||||
const a = Math.max(0, Math.min(255, Math.round((parseInt(String(al), 10) / 100000) * 255)))
|
||||
c = c + a.toString(16).padStart(2, '0').toUpperCase()
|
||||
}
|
||||
return c
|
||||
}
|
||||
if (n['a:srgbClr']) {
|
||||
const srgb = asXmlNode(n['a:srgbClr'])
|
||||
return withMods('#' + String(srgb['@_val']).toUpperCase(), srgb)
|
||||
}
|
||||
if (n['a:schemeClr']) {
|
||||
const scheme = asXmlNode(n['a:schemeClr'])
|
||||
const base = resolveSchemeColor(String(scheme['@_val']), theme)
|
||||
if (!base) return undefined
|
||||
const t = asXmlNode(scheme['a:tint'])['@_val']
|
||||
return t ? tint(base, parseInt(String(t), 10) / 100000) : base
|
||||
return withMods(base, scheme)
|
||||
}
|
||||
const prst = asXmlNode(n['a:prstClr'])['@_val']
|
||||
if (prst === 'black') return '#000000'
|
||||
@@ -466,12 +486,26 @@ function readInside(
|
||||
theme: Theme | undefined,
|
||||
): Stroke | undefined {
|
||||
const bdr = asXmlNode(asXmlNode(asXmlNode(part)['a:tcStyle'])['a:tcBdr'])
|
||||
const lnRaw = asXmlNode(bdr[tag])['a:ln']
|
||||
if (!lnRaw) return undefined
|
||||
const ln = asXmlNode(lnRaw)
|
||||
const c = readColor(ln['a:solidFill'], theme)
|
||||
if (!c) return undefined
|
||||
return line(c, parseInt(String(ln['@_w']), 10) || 12700)
|
||||
const edge = asXmlNode(bdr[tag])
|
||||
const lnRaw = edge['a:ln']
|
||||
if (lnRaw) {
|
||||
const ln = asXmlNode(lnRaw)
|
||||
if ('a:noFill' in ln) return undefined
|
||||
const c = readColor(ln['a:solidFill'], theme)
|
||||
if (!c) return undefined
|
||||
return line(c, parseInt(String(ln['@_w']), 10) || 12700)
|
||||
}
|
||||
// <a:lnRef idx>: theme lnStyleLst template; the ref's child color substitutes phClr
|
||||
const refRaw = edge['a:lnRef']
|
||||
if (refRaw) {
|
||||
const ref = asXmlNode(refRaw)
|
||||
const c = readColor(ref, theme)
|
||||
if (!c) return undefined
|
||||
const idx = parseInt(String(ref['@_idx'] ?? '0'), 10) || 0
|
||||
const tplLn = asXmlNode(asXmlNode(theme?.lnStyles?.[idx - 1])['a:ln'])
|
||||
return line(c, parseInt(String(tplLn['@_w']), 10) || 12700)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function parseTableStylesXml(
|
||||
@@ -489,6 +523,18 @@ function parseTableStylesXml(
|
||||
const style = xmlArray(list).find((s) => s['@_styleId'] === styleId)
|
||||
if (!style) return undefined
|
||||
const def: TableStyleDef = {}
|
||||
const tblBgRaw = style['a:tblBg']
|
||||
if (tblBgRaw) {
|
||||
const bg = asXmlNode(tblBgRaw)
|
||||
const direct = readColor(asXmlNode(bg['a:fill'])['a:solidFill'], theme)
|
||||
if (direct) def.tblBg = solid(direct)
|
||||
const refRaw = bg['a:fillRef']
|
||||
if (refRaw) {
|
||||
const ref = asXmlNode(refRaw)
|
||||
const idx = parseInt(String(ref['@_idx'] ?? '0'), 10) || 0
|
||||
if (idx > 0) def.tblBgRef = { idx, phClr: readColor(ref, theme) }
|
||||
}
|
||||
}
|
||||
for (const key of [
|
||||
'wholeTbl',
|
||||
'band1H',
|
||||
|
||||
@@ -56,7 +56,21 @@ export type Fill =
|
||||
/** <a:fillToRect> insets as fractions (may exceed 0..1); defines the gradient focus */
|
||||
fillTo?: { l: number; t: number; r: number; b: number }
|
||||
}
|
||||
| { type: 'image'; mediaRef: string; mode?: 'stretch' | 'tile' }
|
||||
| {
|
||||
type: 'image'
|
||||
mediaRef: string
|
||||
mode?: 'stretch' | 'tile'
|
||||
/** <a:blip><a:alphaModFix amt> (0-1, translucent picture fills e.g. washed-out backgrounds) */
|
||||
alpha?: number
|
||||
/** <a:stretch><a:fillRect> insets as fractions: the image maps into this subrect of the shape */
|
||||
fillRect?: { l: number; t: number; r: number; b: number }
|
||||
/** <a:blip><a:duotone>: [dark, light] colors mapped over image luminance (theme texture backgrounds) */
|
||||
duotone?: [string, string]
|
||||
/** <a:blip><a:clrChange>: pixels matching `from` are replaced with `to` (#RRGGBB or #RRGGBBAA; alpha 0 = color-to-transparent) */
|
||||
clrChange?: { from: string; to: string }
|
||||
/** <a:tile>: offsets (EMU), scale fractions and anchor alignment of the tile grid */
|
||||
tile?: { tx: number; ty: number; sx: number; sy: number; algn: string }
|
||||
}
|
||||
| { type: 'pattern'; fg: ResolvedColor; bg: ResolvedColor; preset: string }
|
||||
|
||||
/** OOXML arrowhead size: sm/med/lg (width or length direction), med by default */
|
||||
@@ -164,6 +178,8 @@ export interface TextRun {
|
||||
field?: string
|
||||
/** Text outline <a:rPr><a:ln> (common in WordArt); width in EMU */
|
||||
outline?: { color: ResolvedColor; widthEmu: number }
|
||||
/** Run-level outer shadow (<a:rPr>/defRPr <a:effectLst><a:outerShdw>) */
|
||||
shadow?: ShadowEffect
|
||||
}
|
||||
|
||||
export type TextAlign = 'left' | 'center' | 'right' | 'justify'
|
||||
@@ -191,6 +207,8 @@ export interface Paragraph {
|
||||
sizePct?: number
|
||||
/** <a:buAutoNum type> (arabicPeriod/romanLcParen…) */
|
||||
numType?: string
|
||||
/** <a:buAutoNum startAt>: first number of the sequence (default 1) */
|
||||
startAt?: number
|
||||
}
|
||||
/** Paragraph left indent marL (EMU) */
|
||||
marL?: number
|
||||
@@ -230,6 +248,10 @@ export interface TextBody {
|
||||
wrap?: boolean
|
||||
/** <a:bodyPr vert>: vertical text (Japanese tategaki etc.). Read-only display — write-back keeps original bodyPr bytes */
|
||||
vert?: 'eaVert' | 'vert' | 'vert270' | 'wordArtVert'
|
||||
/** <a:bodyPr numCol>: body text flows across N columns (fill one, then the next) */
|
||||
numCol?: number
|
||||
/** <a:bodyPr spcCol>: gap between columns (EMU) */
|
||||
spcCol?: number
|
||||
}
|
||||
|
||||
// ── Elements ───────────────────────────────────────────────────────────
|
||||
@@ -333,6 +355,11 @@ export interface TextElement extends ElementBase {
|
||||
/** Custom geometry (mutually exclusive with presetGeometry) */
|
||||
customGeometry?: CustomGeometry
|
||||
fill?: Fill
|
||||
/** <p:sp useBgFill="1">: painted with the slide's effective background fill (fill is only a fallback) */
|
||||
useBgFill?: boolean
|
||||
/** <a:effectLst><a:fillOverlay>: second fill composited over the base (PowerPoint blends
|
||||
* with the record's blend mode; the renderer approximates every mode as multiply) */
|
||||
fillOverlay?: Fill
|
||||
stroke?: Stroke
|
||||
shadow?: ShadowEffect
|
||||
glow?: GlowEffect
|
||||
@@ -359,7 +386,12 @@ export interface PictureElement extends ElementBase {
|
||||
/** Picture outline geometry <a:prstGeom> (ellipse avatars/rounded-corner frames etc. from picture styles; rect omitted) */
|
||||
presetGeometry?: string
|
||||
adjust?: Record<string, number>
|
||||
/** Shape fill from the pic's own spPr, drawn as a backdrop behind the image */
|
||||
fill?: Fill
|
||||
/** <a:blip><a:duotone> on the picture blip */
|
||||
duotone?: [string, string]
|
||||
/** <a:blip><a:clrChange> on the picture blip */
|
||||
clrChange?: { from: string; to: string }
|
||||
stroke?: Stroke
|
||||
shadow?: ShadowEffect
|
||||
glow?: GlowEffect
|
||||
@@ -384,6 +416,8 @@ export interface PassthroughElement extends ElementBase {
|
||||
previewShapes?: SlideElement[]
|
||||
/** OLE read-only preview: the preview picture embedded in the graphicFrame (stretched to fill the frame when rendering). */
|
||||
previewPicture?: PictureElement
|
||||
/** Render nothing (no placeholder chip): unparseable mc:AlternateContent kept only for byte fidelity */
|
||||
noChip?: boolean
|
||||
}
|
||||
|
||||
// ── Table (p:graphicFrame → a:tbl) ───────────────────────────────────
|
||||
@@ -420,6 +454,8 @@ export interface TableElement extends ElementBase {
|
||||
rows: TableCell[][]
|
||||
/** tblPr's header-row/banded-rows toggles (echoed in the Ribbon's "Table Design") */
|
||||
styleFlags?: { firstRow: boolean; bandRow: boolean }
|
||||
/** Table-style <a:tblBg>: drawn under the cells (alpha band fills composite over it) */
|
||||
bgFill?: Fill
|
||||
}
|
||||
|
||||
// ── Chart (p:graphicFrame → c:chart reference) ───────────────────────
|
||||
@@ -451,6 +487,10 @@ export interface Slide {
|
||||
masterPath?: string
|
||||
/** Background (inheritance resolved) */
|
||||
background?: Fill
|
||||
/** The slide carries its own <p:bg> override (false/absent = inherited from layout/master) */
|
||||
bgOwn?: boolean
|
||||
/** <p:sld showMasterSp="0">: master/layout background graphics hidden on this slide */
|
||||
masterSpHidden?: boolean
|
||||
/**
|
||||
* master/layout decoration layer (read-only render, never written back):
|
||||
* non-placeholder concrete shapes on the master (logos/color bars) + enabled
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { parsePlaceholderMap } from '../src/placeholder'
|
||||
|
||||
const slideWith = (bodyShapes: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${bodyShapes}</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
describe('useBgFill (tdf93868)', () => {
|
||||
it('flags <p:sp useBgFill="1"> so the render layer substitutes the slide background', () => {
|
||||
const sp =
|
||||
'<p:sp useBgFill="1"><p:nvSpPr><p:cNvPr id="2" name="R"/></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="roundRect"/><a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill></p:spPr></p:sp>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(sp), ctx: {} })
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.useBgFill).toBe(true)
|
||||
// spPr fill is kept only as a fallback
|
||||
expect(el.fill).toEqual({ type: 'solid', color: '#FFFFFF' })
|
||||
})
|
||||
|
||||
it('leaves plain shapes unflagged', () => {
|
||||
const sp =
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="rect"/><a:noFill/></p:spPr></p:sp>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(sp), ctx: {} })
|
||||
expect((slide.elements[0] as any).useBgFill).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('p:pic placeholder geometry backfill (customshape-bitmapfill-srcrect)', () => {
|
||||
it('inherits layout xfrm when a picture placeholder omits <a:xfrm>', () => {
|
||||
const layoutXml =
|
||||
'<p:sldLayout xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/>' +
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="2"/><p:nvPr><p:ph idx="1"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="6192000" y="1332000"/><a:ext cx="5493600" cy="4012789"/></a:xfrm></p:spPr></p:sp>' +
|
||||
'</p:spTree></p:cSld></p:sldLayout>'
|
||||
const pic =
|
||||
'<p:pic><p:nvPicPr><p:cNvPr id="6" name="Content Placeholder 5"/><p:cNvPicPr/>' +
|
||||
'<p:nvPr><p:ph idx="1"/></p:nvPr></p:nvPicPr>' +
|
||||
'<p:blipFill><a:blip r:embed="rId2"/><a:srcRect l="4393" r="4393"/><a:stretch/></p:blipFill>' +
|
||||
'<p:spPr/></p:pic>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(pic),
|
||||
ctx: { layoutPlaceholders: parsePlaceholderMap(layoutXml) },
|
||||
})
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.type).toBe('picture')
|
||||
expect(el.transform.offset).toEqual({ x: 6192000, y: 1332000, cx: 5493600, cy: 4012789 })
|
||||
})
|
||||
|
||||
it('keeps an explicit pic xfrm untouched', () => {
|
||||
const pic =
|
||||
'<p:pic><p:nvPicPr><p:cNvPr id="6"/><p:cNvPicPr/><p:nvPr><p:ph idx="1"/></p:nvPr></p:nvPicPr>' +
|
||||
'<p:blipFill><a:blip r:embed="rId2"/><a:stretch/></p:blipFill>' +
|
||||
'<p:spPr><a:xfrm><a:off x="10" y="20"/><a:ext cx="30" cy="40"/></a:xfrm></p:spPr></p:pic>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(pic), ctx: {} })
|
||||
expect((slide.elements[0] as any).transform.offset).toEqual({ x: 10, y: 20, cx: 30, cy: 40 })
|
||||
})
|
||||
})
|
||||
@@ -77,6 +77,20 @@ describe('parseChartXml', () => {
|
||||
expect(m.series[0]!.pointColors?.[2]).toBe('#0000AA')
|
||||
})
|
||||
|
||||
it('parses pie explosion: series-level c:explosion and per-point c:dPt overrides', () => {
|
||||
const PIE = `<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea>
|
||||
<c:pie3DChart><c:ser><c:idx val="0"/>
|
||||
<c:explosion val="25"/>
|
||||
<c:dPt><c:idx val="1"/><c:explosion val="10"/></c:dPt>
|
||||
<c:val><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>1</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser></c:pie3DChart>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
const m = parseChartXml(PIE)!
|
||||
expect(m.series[0]!.explosionPct).toBe(25)
|
||||
expect(m.series[0]!.pointExplosionPct?.[0]).toBeUndefined()
|
||||
expect(m.series[0]!.pointExplosionPct?.[1]).toBe(10)
|
||||
})
|
||||
|
||||
it('pie chart without holeSize defaults holePct 0', () => {
|
||||
const PIE = `<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea>
|
||||
<c:pieChart><c:ser><c:idx val="0"/>
|
||||
@@ -459,3 +473,168 @@ describe('buildChartSpaceXml 3D kinds (generate → parse round-trip)', () => {
|
||||
expect(m.pseudo3D).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('bubble / stock / varyColors / default background', () => {
|
||||
const BUBBLE_CHART = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:bubbleChart><c:varyColors val="0"/><c:ser><c:idx val="0"/>
|
||||
<c:xVal><c:numRef><c:f>x</c:f><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt><c:pt idx="2"><c:v>3</c:v></c:pt></c:numCache></c:numRef></c:xVal>
|
||||
<c:yVal><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>10</c:v></c:pt><c:pt idx="1"><c:v>20</c:v></c:pt><c:pt idx="2"><c:v>15</c:v></c:pt></c:numCache></c:numRef></c:yVal>
|
||||
<c:bubbleSize><c:numRef><c:f>s</c:f><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>10</c:v></c:pt><c:pt idx="1"><c:v>4</c:v></c:pt><c:pt idx="2"><c:v>8</c:v></c:pt></c:numCache></c:numRef></c:bubbleSize>
|
||||
</c:ser><c:bubbleScale val="75"/></c:bubbleChart>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
|
||||
it('bubble chart parses as scatter with per-point sizes and bubbleScale', () => {
|
||||
const m = parseChartXml(BUBBLE_CHART)!
|
||||
expect(m.kind).toBe('scatter')
|
||||
expect(m.series[0]!.xValues).toEqual([1, 2, 3])
|
||||
expect(m.series[0]!.values).toEqual([10, 20, 15])
|
||||
expect(m.series[0]!.bubbleSizes).toEqual([10, 4, 8])
|
||||
expect(m.bubbleScale).toBe(75)
|
||||
expect(m.bubbleSizeIsWidth).toBeUndefined()
|
||||
})
|
||||
|
||||
it('bubble sizeRepresents=w maps size to diameter', () => {
|
||||
const m = parseChartXml(
|
||||
BUBBLE_CHART.replace(
|
||||
'<c:bubbleScale val="75"/>',
|
||||
'<c:bubbleScale val="75"/><c:sizeRepresents val="w"/>',
|
||||
),
|
||||
)!
|
||||
expect(m.bubbleSizeIsWidth).toBe(true)
|
||||
})
|
||||
|
||||
const STOCK_CHART = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:stockChart>
|
||||
<c:ser><c:idx val="0"/><c:tx><c:strRef><c:f>o</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>Open</c:v></c:pt></c:strCache></c:strRef></c:tx>
|
||||
<c:val><c:numRef><c:f>a</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>30</c:v></c:pt><c:pt idx="1"><c:v>25</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser>
|
||||
<c:ser><c:idx val="1"/><c:val><c:numRef><c:f>b</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>40</c:v></c:pt><c:pt idx="1"><c:v>35</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser>
|
||||
<c:ser><c:idx val="2"/><c:val><c:numRef><c:f>c</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>20</c:v></c:pt><c:pt idx="1"><c:v>15</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser>
|
||||
<c:ser><c:idx val="3"/><c:val><c:numRef><c:f>d</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>35</c:v></c:pt><c:pt idx="1"><c:v>18</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser>
|
||||
<c:hiLowLines/><c:upDownBars><c:gapWidth val="120"/><c:upBars/><c:downBars/></c:upDownBars>
|
||||
</c:stockChart>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
|
||||
it('stock chart parses as line with stock flags and gap width', () => {
|
||||
const m = parseChartXml(STOCK_CHART)!
|
||||
expect(m.kind).toBe('line')
|
||||
expect(m.series).toHaveLength(4)
|
||||
expect(m.stock).toEqual({ hiLowLines: true, upDownBars: true, gapWidthPct: 120 })
|
||||
expect(m.series.every((s) => s.fromStock)).toBe(true)
|
||||
})
|
||||
|
||||
it('bubble series color prefers the fill over the outline', () => {
|
||||
const withBorder = BUBBLE_CHART.replace(
|
||||
'<c:ser><c:idx val="0"/>',
|
||||
'<c:ser><c:idx val="0"/><c:spPr><a:solidFill><a:srgbClr val="4CAF50"/></a:solidFill><a:ln><a:solidFill><a:srgbClr val="111111"/></a:solidFill></a:ln></c:spPr>',
|
||||
)
|
||||
const m = parseChartXml(withBorder)!
|
||||
expect(m.series[0]!.color).toBe('#4CAF50')
|
||||
})
|
||||
|
||||
const PLAIN_PIE = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:pieChart><c:varyColors val="0"/><c:ser><c:idx val="0"/>
|
||||
<c:cat><c:strRef><c:f>c</c:f><c:strCache><c:ptCount val="2"/><c:pt idx="0"><c:v>B</c:v></c:pt><c:pt idx="1"><c:v>C</c:v></c:pt></c:strCache></c:strRef></c:cat>
|
||||
<c:val><c:numRef><c:f>v</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>3</c:v></c:pt><c:pt idx="1"><c:v>1</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser></c:pieChart>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
|
||||
it('pie varyColors=0 is exposed (all wedges use the series color)', () => {
|
||||
const m = parseChartXml(PLAIN_PIE)!
|
||||
expect(m.varyColors).toBe(false)
|
||||
})
|
||||
|
||||
it('pie without varyColors stays multi-color (flag unset)', () => {
|
||||
const m = parseChartXml(PLAIN_PIE.replace('<c:varyColors val="0"/>', ''))!
|
||||
expect(m.varyColors).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('date axis and stacked area', () => {
|
||||
const AREA = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:areaChart><c:grouping val="stacked"/><c:ser><c:idx val="0"/>
|
||||
<c:cat><c:numRef><c:f>x</c:f><c:numCache><c:formatCode>m/d/yyyy</c:formatCode><c:ptCount val="2"/><c:pt idx="0"><c:v>37261</c:v></c:pt><c:pt idx="1"><c:v>37262</c:v></c:pt></c:numCache></c:numRef></c:cat>
|
||||
<c:val><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser></c:areaChart>
|
||||
<c:dateAx><c:delete val="0"/><c:tickLblPos val="nextTo"/></c:dateAx>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
|
||||
it('date-formatted numeric categories render as dates', () => {
|
||||
const m = parseChartXml(AREA)!
|
||||
expect(m.categories).toEqual(['1/5/2002', '1/6/2002'])
|
||||
})
|
||||
|
||||
it('area charts carry their grouping; c:dateAx parses as the category axis', () => {
|
||||
const m = parseChartXml(AREA)!
|
||||
expect(m.grouping).toBe('stacked')
|
||||
})
|
||||
})
|
||||
|
||||
const COMBO_LABELED = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/>
|
||||
<c:ser><c:idx val="0"/>
|
||||
<c:dLbls><c:showVal val="1"/></c:dLbls>
|
||||
<c:val><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>94</c:v></c:pt><c:pt idx="1"><c:v>97</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser>
|
||||
<c:axId val="1"/><c:axId val="2"/></c:barChart>
|
||||
<c:lineChart><c:ser><c:idx val="1"/>
|
||||
<c:spPr><a:ln w="19050"><a:solidFill><a:srgbClr val="404040"/></a:solidFill><a:prstDash val="sysDash"/></a:ln></c:spPr>
|
||||
<c:val><c:numRef><c:f>z</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>100</c:v></c:pt><c:pt idx="1"><c:v>100</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser><c:axId val="1"/><c:axId val="2"/></c:lineChart>
|
||||
<c:catAx><c:axId val="1"/></c:catAx><c:valAx><c:axId val="2"/></c:valAx>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
|
||||
describe('per-series data labels + line dash (acsa combo chart)', () => {
|
||||
it('only the series carrying c:dLbls shows labels; the index line stays label-free', () => {
|
||||
const m = parseChartXml(COMBO_LABELED)!
|
||||
const bar = m.series.find((s) => s.plotKind !== 'line') ?? m.series[0]!
|
||||
const line = m.series.find((s) => s.plotKind === 'line')!
|
||||
expect(bar.dataLabels).toBe(true)
|
||||
expect(line.dataLabels).toBe(false)
|
||||
})
|
||||
|
||||
it('parses the line series prstDash and stroke width', () => {
|
||||
const m = parseChartXml(COMBO_LABELED)!
|
||||
const line = m.series.find((s) => s.plotKind === 'line')!
|
||||
expect(line.dash).toBe('sysDash')
|
||||
expect(line.lineWidthPt).toBeCloseTo(1.5, 3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('showSerName/showCatName data labels', () => {
|
||||
it('parses name flags and value-less labels', () => {
|
||||
const xml = COMBO_LABELED.replace(
|
||||
'<c:dLbls><c:showVal val="1"/></c:dLbls>',
|
||||
'<c:dLbls><c:showSerName val="1"/><c:showCatName val="1"/></c:dLbls>',
|
||||
)
|
||||
const m = parseChartXml(xml)!
|
||||
expect(m.dataLabels).toBe(true)
|
||||
expect(m.dataLabelSerName).toBe(true)
|
||||
expect(m.dataLabelCatName).toBe(true)
|
||||
expect(m.dataLabelNoValue).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
const MULTILVL_CHART = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/>
|
||||
<c:ser><c:idx val="2"/><c:order val="0"/>
|
||||
<c:cat><c:multiLvlStrRef><c:f>S!$A$2:$B$5</c:f><c:multiLvlStrCache><c:ptCount val="4"/>
|
||||
<c:lvl><c:pt idx="0"><c:v>SF</c:v></c:pt><c:pt idx="1"><c:v>LA</c:v></c:pt><c:pt idx="2"><c:v>NY</c:v></c:pt><c:pt idx="3"><c:v>Albany</c:v></c:pt></c:lvl>
|
||||
<c:lvl><c:pt idx="0"><c:v>CA</c:v></c:pt><c:pt idx="2"><c:v>NY</c:v></c:pt></c:lvl>
|
||||
</c:multiLvlStrCache></c:multiLvlStrRef></c:cat>
|
||||
<c:val><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="4"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt><c:pt idx="2"><c:v>3</c:v></c:pt><c:pt idx="3"><c:v>4</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser></c:barChart>
|
||||
<c:catAx><c:tickLblPos val="none"/></c:catAx>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
|
||||
describe('multi-level categories + palette idx + hidden tick labels', () => {
|
||||
it('parses leaf categories, outer group labels, and the series palette index', () => {
|
||||
const m = parseChartXml(MULTILVL_CHART)!
|
||||
expect(m.categories).toEqual(['SF', 'LA', 'NY', 'Albany'])
|
||||
expect(m.categoryGroups).toEqual([
|
||||
{ label: 'CA', start: 0 },
|
||||
{ label: 'NY', start: 2 },
|
||||
])
|
||||
expect(m.series[0]!.paletteIdx).toBe(2)
|
||||
expect(m.catAxis?.tickLblHidden).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseChartExXml } from '../src/chartex'
|
||||
|
||||
const FUNNEL = `<?xml version="1.0"?><cx:chartSpace xmlns:cx="cx" xmlns:a="a" xmlns:r="r">
|
||||
<cx:chartData><cx:data id="0">
|
||||
<cx:strDim type="cat"><cx:f>S!A</cx:f><cx:lvl ptCount="3"><cx:pt idx="0">C1</cx:pt><cx:pt idx="1">C2</cx:pt><cx:pt idx="2">C3</cx:pt></cx:lvl></cx:strDim>
|
||||
<cx:numDim type="val"><cx:f>S!B</cx:f><cx:lvl ptCount="3"><cx:pt idx="0">50</cx:pt><cx:pt idx="1">100</cx:pt><cx:pt idx="2">200</cx:pt></cx:lvl></cx:numDim>
|
||||
</cx:data></cx:chartData>
|
||||
<cx:chart><cx:title/><cx:plotArea><cx:plotAreaRegion><cx:series layoutId="funnel"><cx:dataId val="0"/></cx:series></cx:plotAreaRegion>
|
||||
<cx:axis id="1"><cx:catScaling gapWidth="0.06"/></cx:axis></cx:plotArea></cx:chart></cx:chartSpace>`
|
||||
|
||||
const SUNBURST = `<?xml version="1.0"?><cx:chartSpace xmlns:cx="cx" xmlns:a="a" xmlns:r="r">
|
||||
<cx:chartData><cx:data id="0">
|
||||
<cx:strDim type="cat"><cx:f>S!A</cx:f>
|
||||
<cx:lvl ptCount="3"><cx:pt idx="0">Leaf1</cx:pt><cx:pt idx="1">Leaf2</cx:pt><cx:pt idx="2"/></cx:lvl>
|
||||
<cx:lvl ptCount="3"><cx:pt idx="0">Stem1</cx:pt><cx:pt idx="1">Stem1</cx:pt><cx:pt idx="2">Leaf3</cx:pt></cx:lvl>
|
||||
<cx:lvl ptCount="3"><cx:pt idx="0">Root</cx:pt><cx:pt idx="1">Root</cx:pt><cx:pt idx="2">Root</cx:pt></cx:lvl>
|
||||
</cx:strDim>
|
||||
<cx:numDim type="size"><cx:f>S!B</cx:f><cx:lvl ptCount="3"><cx:pt idx="0">10</cx:pt><cx:pt idx="1">20</cx:pt><cx:pt idx="2">30</cx:pt></cx:lvl></cx:numDim>
|
||||
</cx:data></cx:chartData>
|
||||
<cx:chart><cx:plotArea><cx:plotAreaRegion><cx:series layoutId="sunburst">
|
||||
<cx:dataPt idx="2"><cx:spPr><a:solidFill><a:srgbClr val="B0F0FF"><a:alpha val="0"/></a:srgbClr></a:solidFill></cx:spPr></cx:dataPt>
|
||||
<cx:dataId val="0"/></cx:series></cx:plotAreaRegion></cx:plotArea></cx:chart></cx:chartSpace>`
|
||||
|
||||
describe('parseChartExXml', () => {
|
||||
it('funnel: categories + values + gap fraction + placeholder title', () => {
|
||||
const m = parseChartExXml(FUNNEL)!
|
||||
expect(m.kind).toBe('funnel')
|
||||
expect(m.categories).toEqual(['C1', 'C2', 'C3'])
|
||||
expect(m.series[0]!.values).toEqual([50, 100, 200])
|
||||
expect(m.gapWidthPct).toBeCloseTo(6)
|
||||
expect(m.title).toBe('Chart Title')
|
||||
})
|
||||
|
||||
it('sunburst: leaf-first levels, sizes, transparent per-point color', () => {
|
||||
const m = parseChartExXml(SUNBURST)!
|
||||
expect(m.kind).toBe('sunburst')
|
||||
expect(m.sunburst!.levels).toEqual([
|
||||
['Leaf1', 'Leaf2', ''],
|
||||
['Stem1', 'Stem1', 'Leaf3'],
|
||||
['Root', 'Root', 'Root'],
|
||||
])
|
||||
expect(m.sunburst!.sizes).toEqual([10, 20, 30])
|
||||
expect(m.sunburst!.pointColors![2]).toBe('#B0F0FF00')
|
||||
expect(m.title).toBeUndefined()
|
||||
})
|
||||
|
||||
it('explicit rich title text wins over the placeholder (incl. xml:space form)', () => {
|
||||
const withTitle = FUNNEL.replace(
|
||||
'<cx:title/>',
|
||||
'<cx:title><cx:tx><cx:rich><a:p><a:r><a:t xml:space="preserve">My </a:t></a:r><a:r><a:t>Funnel</a:t></a:r></a:p></cx:rich></cx:tx></cx:title>',
|
||||
)
|
||||
expect(parseChartExXml(withTitle)!.title).toBe('My Funnel')
|
||||
})
|
||||
|
||||
it('unsupported layoutId returns null', () => {
|
||||
expect(parseChartExXml(FUNNEL.replace('layoutId="funnel"', 'layoutId="waterfall"'))).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { resolveColorNode } from '../src/color'
|
||||
|
||||
describe('resolveColorNode a:prstClr', () => {
|
||||
it('resolves preset names', () => {
|
||||
expect(resolveColorNode({ 'a:prstClr': { '@_val': 'red' } }, undefined)).toBe('#FF0000')
|
||||
expect(resolveColorNode({ 'a:prstClr': { '@_val': 'cornflowerBlue' } }, undefined)).toBe(
|
||||
'#6495ED',
|
||||
)
|
||||
expect(resolveColorNode({ 'a:prstClr': { '@_val': 'dkGray' } }, undefined)).toBe('#A9A9A9')
|
||||
})
|
||||
|
||||
it('applies lumOff/alpha modifiers (Aspose watermark: translucent pink)', () => {
|
||||
const node = {
|
||||
'a:prstClr': {
|
||||
'@_val': 'red',
|
||||
'a:lumOff': { '@_val': '30000' },
|
||||
'a:alpha': { '@_val': '40000' },
|
||||
},
|
||||
}
|
||||
expect(resolveColorNode(node, undefined)).toBe('#FF4D4D66')
|
||||
})
|
||||
|
||||
it('unknown preset name resolves to undefined', () => {
|
||||
expect(resolveColorNode({ 'a:prstClr': { '@_val': 'nope' } }, undefined)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import {
|
||||
parseDefaultTextStyle,
|
||||
parsePlaceholderMap,
|
||||
resolvePlaceholderFillSpPr,
|
||||
} from '../src/placeholder'
|
||||
|
||||
const slideWith = (bodyShapes: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${bodyShapes}</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
const PRES =
|
||||
'<?xml version="1.0"?><p:presentation xmlns:p="p" xmlns:a="a">' +
|
||||
'<p:defaultTextStyle><a:defPPr><a:defRPr lang="en-US"/></a:defPPr>' +
|
||||
'<a:lvl1pPr algn="ctr"><a:defRPr sz="1200"><a:latin typeface="Arial"/></a:defRPr></a:lvl1pPr>' +
|
||||
'</p:defaultTextStyle></p:presentation>'
|
||||
|
||||
describe('presentation defaultTextStyle (napierone 0042)', () => {
|
||||
it('parses lvl1 size and font', () => {
|
||||
const st = parseDefaultTextStyle(PRES)!
|
||||
expect(st.levels[0]?.fontSize).toBe(12)
|
||||
expect(st.levels[0]?.latinFont).toBe('Arial')
|
||||
})
|
||||
|
||||
it('applies to a non-placeholder TextBox run without explicit size', () => {
|
||||
const sp =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="5" name="TextBox 4"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
'<p:txBody><a:bodyPr/><a:p><a:r><a:rPr lang="en-GB"/><a:t>plain</a:t></a:r></a:p></p:txBody></p:sp>'
|
||||
const ctx = { defaultTextStyle: parseDefaultTextStyle(PRES) }
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(sp), ctx })
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.text.paragraphs[0].runs[0].fontSize).toBe(12)
|
||||
})
|
||||
|
||||
it('does not override an explicit run size', () => {
|
||||
const sp =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="5" name="TextBox 4"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
'<p:txBody><a:bodyPr/><a:p><a:r><a:rPr lang="en-GB" sz="2400"/><a:t>big</a:t></a:r></a:p></p:txBody></p:sp>'
|
||||
const ctx = { defaultTextStyle: parseDefaultTextStyle(PRES) }
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(sp), ctx })
|
||||
expect((slide.elements[0] as any).text.paragraphs[0].runs[0].fontSize).toBe(24)
|
||||
})
|
||||
})
|
||||
|
||||
describe('presentation defaultTextStyle scope', () => {
|
||||
it('does not apply to plain autoshapes (only txBox text boxes)', () => {
|
||||
const sp =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="6" name="Shape 5"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm><a:prstGeom prst="rect"/></p:spPr>' +
|
||||
'<p:txBody><a:bodyPr/><a:p><a:r><a:rPr lang="en-GB"/><a:t>shape text</a:t></a:r></a:p></p:txBody></p:sp>'
|
||||
const ctx = { defaultTextStyle: parseDefaultTextStyle(PRES) }
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(sp), ctx })
|
||||
expect((slide.elements[0] as any).text.paragraphs[0].runs[0].fontSize).not.toBe(12)
|
||||
})
|
||||
})
|
||||
|
||||
describe('placeholder fill donor matching (fed deck body ph)', () => {
|
||||
const LAYOUT =
|
||||
'<?xml version="1.0"?><p:sldLayout xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/>' +
|
||||
// the true match: body idx 10, has geometry but NO fill
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="18" name="Text Placeholder 12"/><p:nvPr><p:ph type="body" sz="quarter" idx="10"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="1106182" y="3257551"/><a:ext cx="5447018" cy="685799"/></a:xfrm></p:spPr></p:sp>' +
|
||||
// a decorative content placeholder (no type -> normalized body) WITH a dark fill
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="20" name="Content Placeholder 20"/><p:nvPr><p:ph idx="13"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="838199" y="637032"/><a:ext cx="758952" cy="201168"/></a:xfrm>' +
|
||||
'<a:solidFill><a:srgbClr val="3C718F"/></a:solidFill></p:spPr></p:sp>' +
|
||||
'</p:spTree></p:cSld></p:sldLayout>'
|
||||
|
||||
it('an exact placeholder match without a fill does not steal a sibling fill', () => {
|
||||
const map = parsePlaceholderMap(LAYOUT)
|
||||
expect(resolvePlaceholderFillSpPr(map, undefined, 'body', '10')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('the matched placeholder with a fill still donates it', () => {
|
||||
const map = parsePlaceholderMap(LAYOUT)
|
||||
const hit = resolvePlaceholderFillSpPr(map, undefined, 'body', '13')
|
||||
expect(hit).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,272 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { layoutDiagramFallback } from '../src/parse'
|
||||
|
||||
const DATA = `<?xml version="1.0"?><dgm:dataModel xmlns:dgm="d" xmlns:a="a">
|
||||
<dgm:ptLst>
|
||||
<dgm:pt modelId="doc" type="doc"><dgm:prSet/></dgm:pt>
|
||||
<dgm:pt modelId="n1"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Alpha</a:t></a:r></a:p></dgm:t></dgm:pt>
|
||||
<dgm:pt modelId="n2"/>
|
||||
<dgm:pt modelId="n3"/>
|
||||
<dgm:pt modelId="n4"/>
|
||||
<dgm:pt modelId="n5"/>
|
||||
<dgm:pt modelId="p1" type="pres"/>
|
||||
</dgm:ptLst>
|
||||
<dgm:cxnLst>
|
||||
<dgm:cxn modelId="c1" srcId="doc" destId="n1" srcOrd="0" destOrd="0"/>
|
||||
<dgm:cxn modelId="c2" srcId="doc" destId="n2" srcOrd="1" destOrd="0"/>
|
||||
<dgm:cxn modelId="c3" srcId="doc" destId="n3" srcOrd="2" destOrd="0"/>
|
||||
<dgm:cxn modelId="c4" srcId="doc" destId="n4" srcOrd="3" destOrd="0"/>
|
||||
<dgm:cxn modelId="c5" srcId="doc" destId="n5" srcOrd="4" destOrd="0"/>
|
||||
<dgm:cxn modelId="c6" type="presOf" srcId="n1" destId="p1" srcOrd="0" destOrd="0"/>
|
||||
</dgm:cxnLst></dgm:dataModel>`
|
||||
|
||||
describe('layoutDiagramFallback', () => {
|
||||
it('lays out a flat 5-node list as a 2-column snake, last row centered', () => {
|
||||
const shapes = layoutDiagramFallback(DATA, {}, 9144000, 6858000)
|
||||
expect(shapes).toHaveLength(5)
|
||||
const xs = shapes.map((s) => s.transform.offset.x)
|
||||
const ys = shapes.map((s) => s.transform.offset.y)
|
||||
// Two columns, three rows
|
||||
expect(new Set(xs.slice(0, 4)).size).toBe(2)
|
||||
expect(new Set(ys).size).toBe(3)
|
||||
// Last (odd) block centered between the two columns
|
||||
expect(xs[4]).toBeGreaterThan(xs[0]!)
|
||||
expect(xs[4]).toBeLessThan(xs[1]!)
|
||||
// Aspect 0.6 and node text carried through
|
||||
const s0 = shapes[0]!
|
||||
expect(s0.transform.offset.cy / s0.transform.offset.cx).toBeCloseTo(0.6, 2)
|
||||
expect(JSON.stringify(shapes[0])).toContain('Alpha')
|
||||
})
|
||||
|
||||
it('explicit type="node" points are kept', () => {
|
||||
const explicit = DATA.replace('<dgm:pt modelId="n2"/>', '<dgm:pt modelId="n2" type="node"/>')
|
||||
expect(layoutDiagramFallback(explicit, {}, 9144000, 6858000)).toHaveLength(5)
|
||||
})
|
||||
|
||||
it('a height-bound grid stays inside the frame', () => {
|
||||
// Wide short frame: height binds; grid bottom must not pass frameCy
|
||||
const shapes = layoutDiagramFallback(DATA, {}, 18000000, 2000000)
|
||||
const bottom = Math.max(...shapes.map((s) => s.transform.offset.y + s.transform.offset.cy))
|
||||
expect(bottom).toBeLessThanOrEqual(2000000)
|
||||
})
|
||||
|
||||
const HIER_DATA = `<?xml version="1.0"?><dgm:dataModel xmlns:dgm="d" xmlns:a="a">
|
||||
<dgm:ptLst>
|
||||
<dgm:pt modelId="doc" type="doc"/>
|
||||
<dgm:pt modelId="n1"><dgm:t><a:bodyPr/><a:p><a:r><a:t>A</a:t></a:r></a:p></dgm:t></dgm:pt>
|
||||
<dgm:pt modelId="n2"><dgm:t><a:bodyPr/><a:p><a:r><a:t>B1</a:t></a:r></a:p></dgm:t></dgm:pt>
|
||||
<dgm:pt modelId="n3"><dgm:t><a:bodyPr/><a:p><a:r><a:t>B2</a:t></a:r></a:p></dgm:t></dgm:pt>
|
||||
</dgm:ptLst>
|
||||
<dgm:cxnLst>
|
||||
<dgm:cxn modelId="c1" srcId="doc" destId="n1" srcOrd="0" destOrd="0"/>
|
||||
<dgm:cxn modelId="c2" srcId="n1" destId="n2" srcOrd="0" destOrd="0"/>
|
||||
<dgm:cxn modelId="c3" srcId="n1" destId="n3" srcOrd="1" destOrd="0"/>
|
||||
</dgm:cxnLst></dgm:dataModel>`
|
||||
|
||||
it('orgChart hangs a branch whose children are all leaves (rows below, trunk + stubs)', () => {
|
||||
const shapes = layoutDiagramFallback(HIER_DATA, {}, 9144000, 6858000, 'orgChart1')
|
||||
// 3 boxes + trunk + 2 stubs
|
||||
expect(shapes.length).toBe(6)
|
||||
const boxes = shapes.filter((sp: any) => sp.text)
|
||||
expect(boxes).toHaveLength(3)
|
||||
const [a, b1, b2] = boxes as any[]
|
||||
expect(a.transform.offset.y).toBeLessThan(b1.transform.offset.y)
|
||||
// hanging: B2 on its own row below B1
|
||||
expect(b2.transform.offset.y).toBeGreaterThan(b1.transform.offset.y)
|
||||
})
|
||||
|
||||
it('orgChart hangs a branch whose children are all leaves when nested deeper', () => {
|
||||
const deep = HIER_DATA.replace('srcId="doc" destId="n1"', 'srcId="doc" destId="n0"')
|
||||
.replace(
|
||||
'<dgm:pt modelId="n1">',
|
||||
'<dgm:pt modelId="n0"><dgm:t><a:bodyPr/><a:p><a:r><a:t>R</a:t></a:r></a:p></dgm:t></dgm:pt><dgm:pt modelId="n1">',
|
||||
)
|
||||
.replace(
|
||||
'</dgm:cxnLst>',
|
||||
'<dgm:cxn modelId="c0" srcId="n0" destId="n1" srcOrd="0" destOrd="0"/></dgm:cxnLst>',
|
||||
)
|
||||
const shapes = layoutDiagramFallback(deep, {}, 9144000, 6858000, 'orgChart1')
|
||||
const boxes = shapes.filter((sp: any) => sp.text) as any[]
|
||||
expect(boxes).toHaveLength(4)
|
||||
// hanging children of n1 (B1, B2 leaves) stack on separate rows
|
||||
const [, , b1, b2] = boxes
|
||||
expect(b2.transform.offset.y).toBeGreaterThan(b1.transform.offset.y)
|
||||
})
|
||||
|
||||
it('chevron layout puts all nodes on one horizontal band of chevrons', () => {
|
||||
const shapes = layoutDiagramFallback(DATA, {}, 9144000, 6858000, 'chevron1')
|
||||
expect(shapes).toHaveLength(5)
|
||||
const ys = new Set(shapes.map((sp: any) => Math.round(sp.transform.offset.y)))
|
||||
expect(ys.size).toBe(1)
|
||||
expect((shapes[0] as any).presetGeometry).toBe('chevron')
|
||||
})
|
||||
|
||||
it('columns family (hList1) emits header + tinted body per top node with cycled colors', () => {
|
||||
const colors = `<dgm:colorsDef xmlns:dgm="d" xmlns:a="a"><dgm:styleLbl name="node1">
|
||||
<dgm:fillClrLst meth="cycle"><a:schemeClr val="accent2"/><a:schemeClr val="accent3"/></dgm:fillClrLst>
|
||||
</dgm:styleLbl></dgm:colorsDef>`
|
||||
const theme: any = { colors: { accent2: '#C0504D', accent3: '#9BBB59' } }
|
||||
const shapes = layoutDiagramFallback(HIER_DATA, { theme }, 9144000, 6858000, 'hList1', colors)
|
||||
// one top node -> header + body
|
||||
expect(shapes).toHaveLength(2)
|
||||
expect((shapes[0] as any).fill).toEqual({ type: 'solid', color: '#C0504D' })
|
||||
// body = 20% tint of the header color
|
||||
expect((shapes[1] as any).fill.color).toBe('#F2DCDB')
|
||||
})
|
||||
|
||||
it('pyramid renders a single node as a full triangle with dark text', () => {
|
||||
const one = DATA.replace(/<dgm:cxn modelId="c[2-5][^/]*\/>/g, '')
|
||||
const shapes = layoutDiagramFallback(one, {}, 9144000, 6858000, 'pyramid1')
|
||||
expect(shapes).toHaveLength(1)
|
||||
expect((shapes[0] as any).presetGeometry).toBe('triangle')
|
||||
expect((shapes[0] as any).text.paragraphs[0].runs[0].color).toBe('#333333')
|
||||
})
|
||||
|
||||
it('multi-level pyramid keeps collinear side edges via trapezoid adj', () => {
|
||||
const shapes = layoutDiagramFallback(DATA, {}, 9144000, 6858000, 'pyramid1')
|
||||
expect(shapes).toHaveLength(5)
|
||||
expect((shapes[0] as any).presetGeometry).toBe('triangle')
|
||||
const t1 = shapes[1] as any
|
||||
expect(t1.presetGeometry).toBe('trapezoid')
|
||||
// adj encodes the per-side inset = w0/(2n) relative to min(w,h)
|
||||
expect(t1.adjust?.adj).toBeGreaterThan(0)
|
||||
// widths grow row by row
|
||||
expect((shapes[2] as any).transform.offset.cx).toBeGreaterThan(t1.transform.offset.cx)
|
||||
})
|
||||
|
||||
it('picture strips render outlined rows with dark labels', () => {
|
||||
const shapes = layoutDiagramFallback(DATA, {}, 9144000, 6858000, 'PictureStrips')
|
||||
expect(shapes).toHaveLength(5)
|
||||
const s0 = shapes[0] as any
|
||||
expect(s0.fill).toEqual({ type: 'none' })
|
||||
expect(s0.stroke).toBeTruthy()
|
||||
})
|
||||
|
||||
it('hierarchies render top-node tiles with descendant bullet text', () => {
|
||||
const hier = DATA.replace('srcId="doc" destId="n5"', 'srcId="n1" destId="n5"').replace(
|
||||
'<dgm:pt modelId="n5"/>',
|
||||
'<dgm:pt modelId="n5"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Kid</a:t></a:r></a:p></dgm:t></dgm:pt>',
|
||||
)
|
||||
const shapes = layoutDiagramFallback(hier, {}, 9144000, 6858000)
|
||||
// n5 is now a child of n1: one tile fewer, its text folded into n1's tile as a bullet line
|
||||
expect(shapes).toHaveLength(4)
|
||||
const n1 = shapes[0] as any
|
||||
const paras = n1.text.paragraphs
|
||||
expect(paras.length).toBeGreaterThanOrEqual(2)
|
||||
expect(paras[1].bullet?.type).toBe('char')
|
||||
})
|
||||
})
|
||||
|
||||
const EQ_DATA = `<?xml version="1.0"?><dgm:dataModel xmlns:dgm="d" xmlns:a="a">
|
||||
<dgm:ptLst>
|
||||
<dgm:pt modelId="doc" type="doc"/>
|
||||
<dgm:pt modelId="n1"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Higher quality</a:t></a:r></a:p></dgm:t></dgm:pt>
|
||||
<dgm:pt modelId="n2"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Improved value</a:t></a:r></a:p></dgm:t></dgm:pt>
|
||||
<dgm:pt modelId="n3"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Better deal</a:t></a:r></a:p></dgm:t></dgm:pt>
|
||||
</dgm:ptLst>
|
||||
<dgm:cxnLst>
|
||||
<dgm:cxn modelId="c1" srcId="doc" destId="n1" srcOrd="0" destOrd="0"/>
|
||||
<dgm:cxn modelId="c2" srcId="doc" destId="n2" srcOrd="1" destOrd="0"/>
|
||||
<dgm:cxn modelId="c3" srcId="doc" destId="n3" srcOrd="2" destOrd="0"/>
|
||||
</dgm:cxnLst></dgm:dataModel>`
|
||||
|
||||
describe('equation1 family (napierone 0005: a + b = c)', () => {
|
||||
it('lays out operand circles joined by mathPlus and mathEqual operators', () => {
|
||||
const shapes = layoutDiagramFallback(EQ_DATA, {}, 9144000, 3429000, 'equation1') as any[]
|
||||
const circles = shapes.filter((s) => s.presetGeometry === 'ellipse')
|
||||
expect(circles).toHaveLength(3)
|
||||
// circles are equal-sized and vertically centered
|
||||
expect(circles[0].transform.offset.cx).toBeCloseTo(circles[0].transform.offset.cy, 3)
|
||||
const ops = shapes.filter((s) => /^math/.test(s.presetGeometry ?? ''))
|
||||
expect(ops.map((o: any) => o.presetGeometry)).toEqual(['mathPlus', 'mathEqual'])
|
||||
// operators sit between the circles
|
||||
expect(ops[0].transform.offset.x).toBeGreaterThan(circles[0].transform.offset.x)
|
||||
expect(ops[0].transform.offset.x).toBeLessThan(circles[1].transform.offset.x)
|
||||
expect(JSON.stringify(circles[0])).toContain('Higher quality')
|
||||
})
|
||||
})
|
||||
|
||||
const CHEV_DATA = `<?xml version="1.0"?><dgm:dataModel xmlns:dgm="d" xmlns:a="a">
|
||||
<dgm:ptLst>
|
||||
<dgm:pt modelId="doc" type="doc"/>
|
||||
<dgm:pt modelId="n1"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Stage one</a:t></a:r></a:p></dgm:t></dgm:pt>
|
||||
<dgm:pt modelId="n2"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Stage two</a:t></a:r></a:p></dgm:t></dgm:pt>
|
||||
<dgm:pt modelId="k1"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Detail A</a:t></a:r></a:p></dgm:t></dgm:pt>
|
||||
</dgm:ptLst>
|
||||
<dgm:cxnLst>
|
||||
<dgm:cxn modelId="c1" srcId="doc" destId="n1" srcOrd="0" destOrd="0"/>
|
||||
<dgm:cxn modelId="c2" srcId="doc" destId="n2" srcOrd="1" destOrd="0"/>
|
||||
<dgm:cxn modelId="c3" srcId="n1" destId="k1" srcOrd="0" destOrd="0"/>
|
||||
</dgm:cxnLst></dgm:dataModel>`
|
||||
|
||||
describe('chevron2 vertical chevron list (napierone 0001)', () => {
|
||||
it('renders a down-rotated chevron accent plus an outlined bullet card per row', () => {
|
||||
const shapes = layoutDiagramFallback(CHEV_DATA, {}, 8568952, 6048672, 'chevron2') as any[]
|
||||
const chevrons = shapes.filter((s) => s.presetGeometry === 'chevron')
|
||||
expect(chevrons).toHaveLength(2)
|
||||
for (const c of chevrons) expect(c.transform.rot).toBe(5400000)
|
||||
const cards = shapes.filter((s) => s.presetGeometry === 'roundRect')
|
||||
expect(cards).toHaveLength(2)
|
||||
// cards sit to the right of the chevron column
|
||||
for (const card of cards) expect(card.transform.offset.x).toBeGreaterThan(0)
|
||||
expect(JSON.stringify(cards[0])).toContain('Detail A')
|
||||
// the label overlay stays unrotated so its text remains horizontal
|
||||
const labels = shapes.filter((s) => s.presetGeometry === 'rect' && s.text)
|
||||
expect(labels.length).toBeGreaterThanOrEqual(2)
|
||||
expect(JSON.stringify(labels[0])).toContain('Stage one')
|
||||
})
|
||||
|
||||
it('chevron1 keeps the horizontal band family', () => {
|
||||
const shapes = layoutDiagramFallback(CHEV_DATA, {}, 9144000, 2000000, 'chevron1') as any[]
|
||||
for (const s of shapes) expect(s.transform.rot ?? 0).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('vProcess5 stepped process (napierone 0014)', () => {
|
||||
it('staggers boxes to the right as they descend with a down arrow between steps', () => {
|
||||
const shapes = layoutDiagramFallback(EQ_DATA, {}, 9144000, 6858000, 'vProcess5') as any[]
|
||||
const boxes = shapes.filter((s) => !s.presetGeometry || s.presetGeometry === 'rect')
|
||||
expect(boxes.length).toBe(3)
|
||||
// strictly increasing x and y
|
||||
for (let i = 1; i < boxes.length; i++) {
|
||||
expect(boxes[i].transform.offset.x).toBeGreaterThan(boxes[i - 1].transform.offset.x)
|
||||
expect(boxes[i].transform.offset.y).toBeGreaterThan(boxes[i - 1].transform.offset.y)
|
||||
}
|
||||
const arrows = shapes.filter((s) => s.presetGeometry === 'downArrow')
|
||||
expect(arrows.length).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('flatGrid centering and tile text autofit (napierone 0005)', () => {
|
||||
it('centers the grid vertically in a width-bound frame', () => {
|
||||
// wide short frame relative to a 3x2 grid: rows leave headroom that splits evenly
|
||||
const six = DATA.replace(
|
||||
'<dgm:cxn modelId="c6" type="presOf" srcId="n1" destId="p1" srcOrd="0" destOrd="0"/>',
|
||||
'<dgm:cxn modelId="c6" srcId="doc" destId="p1" srcOrd="5" destOrd="0"/>',
|
||||
).replace('<dgm:pt modelId="p1" type="pres"/>', '<dgm:pt modelId="p1"/>')
|
||||
const frameCx = 7680684
|
||||
const frameCy = 3888432
|
||||
const shapes = layoutDiagramFallback(six, {}, frameCx, frameCy) as any[]
|
||||
expect(shapes).toHaveLength(6)
|
||||
const top = Math.min(...shapes.map((s) => s.transform.offset.y))
|
||||
const bottom = Math.max(...shapes.map((s) => s.transform.offset.y + s.transform.offset.cy))
|
||||
expect(top).toBeGreaterThan(frameCy * 0.05)
|
||||
expect(Math.abs(top - (frameCy - bottom))).toBeLessThan(frameCy * 0.01)
|
||||
})
|
||||
|
||||
it('wrapped tile text shrinks well below the cap', () => {
|
||||
const withText = DATA.replace(
|
||||
'<dgm:pt modelId="n2"/>',
|
||||
'<dgm:pt modelId="n2"><dgm:t><a:bodyPr/><a:p><a:r><a:t>De-layer service delivery</a:t></a:r></a:p></dgm:t></dgm:pt>',
|
||||
)
|
||||
const shapes = layoutDiagramFallback(withText, {}, 7680684, 3888432) as any[]
|
||||
const el = shapes.find((sp: any) =>
|
||||
sp.text?.paragraphs?.some((pp: any) =>
|
||||
pp.runs?.some((r: any) => r.text?.includes('De-layer')),
|
||||
),
|
||||
) as any
|
||||
const runSize = el.text.paragraphs[0].runs[0].fontSize
|
||||
expect(runSize).toBeLessThan(20)
|
||||
expect(runSize).toBeGreaterThan(10)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
|
||||
const slideWith = (bodyShapes: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${bodyShapes}</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
const GRP_XFRM =
|
||||
'<a:xfrm><a:off x="0" y="0"/><a:ext cx="9144000" cy="1124744"/>' +
|
||||
'<a:chOff x="0" y="0"/><a:chExt cx="9144000" cy="1124744"/></a:xfrm>'
|
||||
|
||||
const child = (fillXml: string, style = '') =>
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="8" name="R"/></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm>' +
|
||||
`<a:prstGeom prst="rect"/>${fillXml}</p:spPr>${style}</p:sp>`
|
||||
|
||||
const STYLE =
|
||||
'<p:style><a:fillRef idx="1"><a:schemeClr val="accent1"/></a:fillRef>' +
|
||||
'<a:fontRef idx="minor"/></p:style>'
|
||||
|
||||
describe('<a:grpFill/> (PlanS master banner)', () => {
|
||||
it('child with grpFill inherits the group grpSpPr fill, beating the style fillRef', () => {
|
||||
const grp =
|
||||
'<p:grpSp><p:nvGrpSpPr><p:cNvPr id="7" name="G"/></p:nvGrpSpPr>' +
|
||||
`<p:grpSpPr>${GRP_XFRM}<a:solidFill><a:srgbClr val="C5DCF0"/></a:solidFill></p:grpSpPr>` +
|
||||
child('<a:grpFill/>', STYLE) +
|
||||
'</p:grpSp>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(grp), ctx: {} })
|
||||
const g = slide.elements[0] as any
|
||||
expect(g.type).toBe('group')
|
||||
expect(g.children[0].fill).toEqual({ type: 'solid', color: '#C5DCF0' })
|
||||
})
|
||||
|
||||
it('nested group with grpFill defers to the outer group fill', () => {
|
||||
const inner =
|
||||
'<p:grpSp><p:nvGrpSpPr><p:cNvPr id="9" name="G2"/></p:nvGrpSpPr>' +
|
||||
`<p:grpSpPr>${GRP_XFRM}<a:grpFill/></p:grpSpPr>` +
|
||||
child('<a:grpFill/>') +
|
||||
'</p:grpSp>'
|
||||
const outer =
|
||||
'<p:grpSp><p:nvGrpSpPr><p:cNvPr id="7" name="G"/></p:nvGrpSpPr>' +
|
||||
`<p:grpSpPr>${GRP_XFRM}<a:solidFill><a:srgbClr val="112233"/></a:solidFill></p:grpSpPr>` +
|
||||
inner +
|
||||
'</p:grpSp>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(outer), ctx: {} })
|
||||
const g = (slide.elements[0] as any).children[0]
|
||||
expect(g.children[0].fill).toEqual({ type: 'solid', color: '#112233' })
|
||||
})
|
||||
|
||||
it('grpFill with no group fill leaves the shape on its normal fallback chain', () => {
|
||||
const grp =
|
||||
'<p:grpSp><p:nvGrpSpPr><p:cNvPr id="7" name="G"/></p:nvGrpSpPr>' +
|
||||
`<p:grpSpPr>${GRP_XFRM}</p:grpSpPr>` +
|
||||
child('<a:grpFill/>', STYLE) +
|
||||
'</p:grpSp>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(grp), ctx: {} })
|
||||
const g = slide.elements[0] as any
|
||||
// no group fill to inherit → style fillRef template applies (no theme here → undefined phClr → undefined)
|
||||
expect(g.children[0].fill).toBeUndefined()
|
||||
})
|
||||
|
||||
it('pic with grpFill records the group fill as its backdrop', () => {
|
||||
const pic =
|
||||
'<p:pic><p:nvPicPr><p:cNvPr id="9" name="Bild"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>' +
|
||||
'<p:blipFill><a:blip r:embed="rId3"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="rect"/><a:grpFill/></p:spPr></p:pic>'
|
||||
const grp =
|
||||
'<p:grpSp><p:nvGrpSpPr><p:cNvPr id="7" name="G"/></p:nvGrpSpPr>' +
|
||||
`<p:grpSpPr>${GRP_XFRM}<a:solidFill><a:srgbClr val="C5DCF0"/></a:solidFill></p:grpSpPr>` +
|
||||
pic +
|
||||
'</p:grpSp>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(grp), ctx: {} })
|
||||
const g = slide.elements[0] as any
|
||||
expect(g.children[0].type).toBe('picture')
|
||||
expect(g.children[0].fill).toEqual({ type: 'solid', color: '#C5DCF0' })
|
||||
})
|
||||
})
|
||||
@@ -494,22 +494,21 @@ describe('addMedia / addModel3d', () => {
|
||||
})
|
||||
|
||||
describe('unsupported chart kinds', () => {
|
||||
// Classic-namespace chart type the model doesn't support (same bucket as stock/surface;
|
||||
// chartex parts like waterfall/funnel never even reach parseChartXml)
|
||||
const BUBBLE_CHART = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:bubbleChart><c:ser><c:idx val="0"/>
|
||||
<c:xVal><c:numRef><c:f>x</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt></c:numCache></c:numRef></c:xVal>
|
||||
<c:yVal><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>10</c:v></c:pt><c:pt idx="1"><c:v>20</c:v></c:pt></c:numCache></c:numRef></c:yVal>
|
||||
<c:bubbleSize><c:numRef><c:f>s</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>5</c:v></c:pt><c:pt idx="1"><c:v>9</c:v></c:pt></c:numCache></c:numRef></c:bubbleSize>
|
||||
</c:ser></c:bubbleChart>
|
||||
// Classic-namespace chart type the model doesn't support (surface; chartex parts
|
||||
// like waterfall/funnel never even reach parseChartXml)
|
||||
const SURFACE_CHART = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:surface3DChart><c:ser><c:idx val="0"/>
|
||||
<c:cat><c:strRef><c:f>c</c:f><c:strCache><c:ptCount val="2"/><c:pt idx="0"><c:v>A</c:v></c:pt><c:pt idx="1"><c:v>B</c:v></c:pt></c:strCache></c:strRef></c:cat>
|
||||
<c:val><c:numRef><c:f>v</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>10</c:v></c:pt><c:pt idx="1"><c:v>20</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser></c:surface3DChart>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
|
||||
it('parseChartXml returns null for a bubble chart (no recognizable plot)', () => {
|
||||
expect(parseChartXml(BUBBLE_CHART)).toBeNull()
|
||||
it('parseChartXml returns null for a surface chart (no recognizable plot)', () => {
|
||||
expect(parseChartXml(SURFACE_CHART)).toBeNull()
|
||||
})
|
||||
|
||||
it('an unsupported chart degrades to a passthrough element and survives an unrelated edit + save byte-for-byte', async () => {
|
||||
// Build a deck with a chart, then swap its part for a bubble chart on disk
|
||||
// Build a deck with a chart, then swap its part for a surface chart on disk
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
addChart(opened, 0, {
|
||||
kind: 'bar',
|
||||
@@ -521,7 +520,7 @@ describe('unsupported chart kinds', () => {
|
||||
const chartPart = [...staged.archive.entries.keys()].find((p) =>
|
||||
/^ppt\/charts\/chart\d+\.xml$/.test(p),
|
||||
)!
|
||||
staged.archive.entries.set(chartPart, Buffer.from(BUBBLE_CHART, 'utf8'))
|
||||
staged.archive.entries.set(chartPart, Buffer.from(SURFACE_CHART, 'utf8'))
|
||||
const buf = await savePptx(staged)
|
||||
|
||||
// Reopen: the graphicFrame no longer parses as a chart — it must become a passthrough chip, not vanish
|
||||
@@ -538,7 +537,7 @@ describe('unsupported chart kinds', () => {
|
||||
const saved = await openPptx(await savePptx(reopened))
|
||||
|
||||
// The chart part and the graphicFrame bytes are untouched
|
||||
expect(saved.archive.readText(chartPart)).toBe(BUBBLE_CHART)
|
||||
expect(saved.archive.readText(chartPart)).toBe(SURFACE_CHART)
|
||||
const pt2 = saved.deck.slides[0]!.elements.find(
|
||||
(e) => e.type === 'passthrough',
|
||||
) as PassthroughElement
|
||||
|
||||
@@ -149,6 +149,37 @@ describe('fill / color-mod / background parsing', () => {
|
||||
expect(el.fill).toEqual({ type: 'image', mediaRef: 'ppt/media/image1.png', mode: 'stretch' })
|
||||
})
|
||||
|
||||
it('blip duotone → [dark, light] colors on the image fill (tdf123684 theme textures)', () => {
|
||||
const sp =
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="10" cy="10"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="rect"/><a:blipFill><a:blip r:embed="rId5">' +
|
||||
'<a:duotone><a:schemeClr val="accent1"><a:shade val="50000"/></a:schemeClr>' +
|
||||
'<a:schemeClr val="lt1"/></a:duotone>' +
|
||||
'</a:blip></a:blipFill></p:spPr></p:sp>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(sp),
|
||||
ctx: { theme, mediaRels: new Map([['rId5', 'ppt/media/t.png']]) },
|
||||
})
|
||||
// accent1 #0000FF shade 50% (gamma-corrected, matching PowerPoint) → #0000BA
|
||||
expect((slide.elements[0] as any).fill.duotone).toEqual(['#0000BA', '#FFFFFF'])
|
||||
})
|
||||
|
||||
it('duotone with mixed color tags keeps dark endpoint first (standard black + accent)', () => {
|
||||
const sp =
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="10" cy="10"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="rect"/><a:blipFill><a:blip r:embed="rId5">' +
|
||||
'<a:duotone><a:prstClr val="black"/><a:schemeClr val="accent1"/></a:duotone>' +
|
||||
'</a:blip></a:blipFill></p:spPr></p:sp>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(sp),
|
||||
ctx: { theme, mediaRels: new Map([['rId5', 'ppt/media/t.png']]) },
|
||||
})
|
||||
// The parser iterates schemeClr before prstClr; luminance ordering restores black first
|
||||
expect((slide.elements[0] as any).fill.duotone).toEqual(['#000000', '#0000FF'])
|
||||
})
|
||||
|
||||
it('slide <p:bg> solid background', () => {
|
||||
const bg = '<p:bg><p:bgPr><a:solidFill><a:srgbClr val="112233"/></a:solidFill></p:bgPr></p:bg>'
|
||||
const slide = parseSlide({
|
||||
@@ -159,6 +190,94 @@ describe('fill / color-mod / background parsing', () => {
|
||||
expect(slide.background).toEqual({ type: 'solid', color: '#112233' })
|
||||
})
|
||||
|
||||
it('placeholder inherits layout spPr fill; master noFill stops the fallback (bnc904423)', () => {
|
||||
const layoutXml =
|
||||
'<p:sldLayout xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/>' +
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="2"/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr><a:solidFill><a:srgbClr val="00CC99"/></a:solidFill></p:spPr></p:sp>' +
|
||||
'</p:spTree></p:cSld></p:sldLayout>'
|
||||
const masterXml =
|
||||
'<p:sldMaster xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/>' +
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="2"/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr><a:noFill/></p:spPr></p:sp>' +
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="3"/><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr><a:solidFill><a:srgbClr val="123456"/></a:solidFill></p:spPr></p:sp>' +
|
||||
'</p:spTree></p:cSld></p:sldMaster>'
|
||||
const title =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="2"/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>'
|
||||
const body =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="3"/><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(title + body),
|
||||
ctx: {
|
||||
theme,
|
||||
layoutPlaceholders: parsePlaceholderMap(layoutXml),
|
||||
masterPlaceholders: parsePlaceholderMap(masterXml),
|
||||
},
|
||||
})
|
||||
// Title: the layout fill wins over the master noFill
|
||||
expect((slide.elements[0] as any).fill).toEqual({ type: 'solid', color: '#00CC99' })
|
||||
// Body: no layout fill → master's applies
|
||||
expect((slide.elements[1] as any).fill).toEqual({ type: 'solid', color: '#123456' })
|
||||
})
|
||||
|
||||
it('p:style fontRef color beats master txStyles but not explicit run color (bnc904423)', () => {
|
||||
const masterTextStyles: any = {
|
||||
body: { levels: [{ color: '#000000' }] },
|
||||
}
|
||||
const sp = (runs: string) =>
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="4"/><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
'<p:style><a:fillRef idx="1"><a:schemeClr val="accent1"/></a:fillRef>' +
|
||||
'<a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef></p:style>' +
|
||||
`<p:txBody><a:bodyPr/><a:lstStyle/><a:p>${runs}</a:p></p:txBody></p:sp>`
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(sp('<a:r><a:t>inherit</a:t></a:r>')),
|
||||
ctx: { theme, masterTextStyles },
|
||||
})
|
||||
expect((slide.elements[0] as any).text.paragraphs[0].runs[0].color).toBe('#FFFFFF')
|
||||
const explicit = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(
|
||||
sp(
|
||||
'<a:r><a:rPr><a:solidFill><a:srgbClr val="FF00FF"/></a:solidFill></a:rPr><a:t>own</a:t></a:r>',
|
||||
),
|
||||
),
|
||||
ctx: { theme, masterTextStyles },
|
||||
})
|
||||
expect((explicit.elements[0] as any).text.paragraphs[0].runs[0].color).toBe('#FF00FF')
|
||||
})
|
||||
|
||||
it('master bgRef blipFill template resolves the blip in the theme part rels', () => {
|
||||
const themed: any = {
|
||||
...theme,
|
||||
bgFillStyles: [
|
||||
{},
|
||||
{},
|
||||
{ 'a:blipFill': { 'a:blip': { '@_r:embed': 'rId2' }, 'a:stretch': {} } },
|
||||
],
|
||||
}
|
||||
const masterBg =
|
||||
'<p:sldMaster><p:cSld><p:bg><p:bgRef idx="1003"><a:schemeClr val="lt1"/></p:bgRef></p:bg></p:cSld></p:sldMaster>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(''),
|
||||
ctx: {
|
||||
theme: themed,
|
||||
masterBg,
|
||||
masterMediaRels: new Map([['rId2', 'ppt/media/wrong-part.png']]),
|
||||
themeMediaRels: new Map([['rId2', 'ppt/media/image2.jpeg']]),
|
||||
},
|
||||
})
|
||||
expect(slide.background).toEqual({
|
||||
type: 'image',
|
||||
mediaRef: 'ppt/media/image2.jpeg',
|
||||
mode: 'stretch',
|
||||
})
|
||||
})
|
||||
|
||||
it('background inherits from master when slide has none', () => {
|
||||
const masterBg =
|
||||
'<p:sldMaster><p:cSld><p:bg><p:bgPr><a:solidFill><a:srgbClr val="ABCDEF"/></a:solidFill></p:bgPr></p:bg></p:cSld></p:sldMaster>'
|
||||
|
||||
@@ -12,7 +12,10 @@ import {
|
||||
editPictureSrcRect,
|
||||
patchElementStroke,
|
||||
replacePictureBytes,
|
||||
resetSlideBackground,
|
||||
setSlideBackground,
|
||||
setSlideBackgroundImage,
|
||||
setSlideBgGraphicsHidden,
|
||||
} from '../src/index'
|
||||
import type { PictureElement, TextElement } from '../src/types'
|
||||
|
||||
@@ -300,4 +303,89 @@ describe('setSlideBackground', () => {
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides[0]!.background).toEqual({ type: 'solid', color: '#222222' })
|
||||
})
|
||||
|
||||
it('gradient background round-trips through save → reopen', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
setSlideBackground(slide, {
|
||||
stops: [
|
||||
{ pos: 0, color: '#FF0000' },
|
||||
{ pos: 1, color: '#0000FF' },
|
||||
],
|
||||
angle: 90 * 60000,
|
||||
})
|
||||
expect(slide.background?.type).toBe('gradient')
|
||||
expect(slide.bgOwn).toBe(true)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const bg = reopened.deck.slides[0]!.background
|
||||
expect(bg?.type).toBe('gradient')
|
||||
if (bg?.type === 'gradient') {
|
||||
expect(bg.stops.map((s) => s.color)).toEqual(['#FF0000', '#0000FF'])
|
||||
expect(bg.angle).toBe(90 * 60000)
|
||||
}
|
||||
expect(reopened.deck.slides[0]!.bgOwn).toBe(true)
|
||||
})
|
||||
|
||||
it('image background lands media + rel and round-trips', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const used = setSlideBackgroundImage(opened, slide, { bytes: PNG_1PX, ext: 'png' })
|
||||
expect(used).toBe('ppt/media/image1.png')
|
||||
expect(slide.background).toEqual({
|
||||
type: 'image',
|
||||
mediaRef: 'ppt/media/image1.png',
|
||||
mode: 'stretch',
|
||||
})
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides[0]!.background).toEqual({
|
||||
type: 'image',
|
||||
mediaRef: 'ppt/media/image1.png',
|
||||
mode: 'stretch',
|
||||
})
|
||||
})
|
||||
|
||||
it('re-applying an existing media path adds no new media part (tile mode)', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
setSlideBackgroundImage(opened, slide, { bytes: PNG_1PX, ext: 'png' })
|
||||
const used = setSlideBackgroundImage(opened, slide, { mediaPath: 'ppt/media/image1.png' }, true)
|
||||
expect(used).toBe('ppt/media/image1.png')
|
||||
const mediaParts = [...opened.archive.entries.keys()].filter((p) => p.startsWith('ppt/media/'))
|
||||
expect(mediaParts).toEqual(['ppt/media/image1.png'])
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const bg = reopened.deck.slides[0]!.background
|
||||
expect(bg?.type === 'image' && bg.mode).toBe('tile')
|
||||
})
|
||||
|
||||
it('resetSlideBackground removes the override', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
setSlideBackground(slide, '#112233')
|
||||
resetSlideBackground(opened, slide)
|
||||
expect(slide.bgOwn).toBeUndefined()
|
||||
expect(slide.bodyPrefix).not.toContain('<p:bg>')
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides[0]!.bgOwn).toBeUndefined()
|
||||
expect(reopened.deck.slides[0]!.originalXml).not.toContain('<p:bg>')
|
||||
})
|
||||
|
||||
it('hide background graphics toggles <p:sld showMasterSp>', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
setSlideBgGraphicsHidden(opened, opened.deck.slides[0]!, true)
|
||||
expect(opened.deck.slides[0]!.masterSpHidden).toBe(true)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const slide = reopened.deck.slides[0]!
|
||||
expect(slide.masterSpHidden).toBe(true)
|
||||
|
||||
setSlideBgGraphicsHidden(reopened, slide, false)
|
||||
expect(slide.masterSpHidden).toBeUndefined()
|
||||
expect(slide.bodyPrefix).not.toContain('showMasterSp')
|
||||
const reopened2 = await openPptx(await savePptx(reopened))
|
||||
expect(reopened2.deck.slides[0]!.masterSpHidden).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
|
||||
const slideWith = (bodyShapes: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${bodyShapes}</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
const pic = (blipInner: string, spPrFill = '') =>
|
||||
'<p:pic><p:nvPicPr><p:cNvPr id="14" name="Picture 13"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>' +
|
||||
`<p:blipFill><a:blip r:embed="rId2">${blipInner}</a:blip><a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm>' +
|
||||
`<a:prstGeom prst="rect"/>${spPrFill}</p:spPr></p:pic>`
|
||||
|
||||
describe('p:pic spPr fill backdrop (napierone 0027 darkened map)', () => {
|
||||
it('parses the pic solidFill alongside a translucent blip', () => {
|
||||
const xml = slideWith(
|
||||
pic('<a:alphaModFix amt="26000"/>', '<a:solidFill><a:srgbClr val="000000"/></a:solidFill>'),
|
||||
)
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: xml, ctx: {} })
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.type).toBe('picture')
|
||||
expect(el.opacity).toBeCloseTo(0.26, 5)
|
||||
expect(el.fill).toEqual({ type: 'solid', color: '#000000' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('p:pic blip clrChange/duotone (napierone 0034 EMF silhouette)', () => {
|
||||
it('parses clrChange color-to-transparent and duotone on a pic blip', () => {
|
||||
const xml = slideWith(
|
||||
pic(
|
||||
'<a:clrChange><a:clrFrom><a:srgbClr val="000000"/></a:clrFrom>' +
|
||||
'<a:clrTo><a:srgbClr val="000000"><a:alpha val="0"/></a:srgbClr></a:clrTo></a:clrChange>' +
|
||||
'<a:duotone><a:srgbClr val="7C1E4F"/><a:prstClr val="white"/></a:duotone>',
|
||||
),
|
||||
)
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: xml, ctx: {} })
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.clrChange).toEqual({ from: '#000000', to: '#00000000' })
|
||||
expect(el.duotone).toEqual(['#7C1E4F', '#FFFFFF'])
|
||||
})
|
||||
|
||||
it('parses clrChange on a shape blipFill too', () => {
|
||||
const sp =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="2" name="S"/></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm><a:prstGeom prst="rect"/>' +
|
||||
'<a:blipFill><a:blip r:embed="rId2">' +
|
||||
'<a:clrChange><a:clrFrom><a:srgbClr val="FFFFFF"/></a:clrFrom>' +
|
||||
'<a:clrTo><a:srgbClr val="FF0000"/></a:clrTo></a:clrChange>' +
|
||||
'</a:blip><a:stretch><a:fillRect/></a:stretch></a:blipFill></p:spPr></p:sp>'
|
||||
const ctx = { mediaRels: new Map([['rId2', 'ppt/media/image1.png']]) }
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(sp), ctx })
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.fill.type).toBe('image')
|
||||
expect(el.fill.clrChange).toEqual({ from: '#FFFFFF', to: '#FF0000' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('buAutoNum startAt (PlanS numbered headings)', () => {
|
||||
it('parses startAt into the bullet', () => {
|
||||
const sp =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="5" name="T"/></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
'<p:txBody><a:bodyPr/><a:p><a:pPr marL="457200" indent="-457200">' +
|
||||
'<a:buAutoNum type="arabicPeriod" startAt="3"/></a:pPr>' +
|
||||
'<a:r><a:t>10 Principles</a:t></a:r></a:p></p:txBody></p:sp>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(sp), ctx: {} })
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.text.paragraphs[0].bullet).toMatchObject({
|
||||
type: 'number',
|
||||
numType: 'arabicPeriod',
|
||||
startAt: 3,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -65,7 +65,7 @@ describe('rebuild path: explicit paragraph properties written back', () => {
|
||||
)
|
||||
forceRebuild(el)
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('<a:buAutoNum type="romanLcPeriod"/>')
|
||||
expect(out).toContain('<a:buAutoNum type="romanLcPeriod" startAt="3"/>')
|
||||
})
|
||||
|
||||
it('buNone preserved (explicitly turning off the inherited bullet)', () => {
|
||||
|
||||
@@ -31,12 +31,12 @@ async function deckWithGap(): Promise<Buffer> {
|
||||
}
|
||||
|
||||
describe('non-shape spTree children preserved', () => {
|
||||
it('scan records the gap; rebuild without edits == original bytes', async () => {
|
||||
it('AlternateContent becomes an element anchored to its full bytes; rebuild without edits == original bytes', async () => {
|
||||
const opened = await openPptx(await deckWithGap())
|
||||
const slide = opened.deck.slides[0]!
|
||||
expect(slide.elements.some((e) => e.anchor.gapAfter?.includes('mc:AlternateContent'))).toBe(
|
||||
true,
|
||||
)
|
||||
expect(
|
||||
slide.elements.some((e) => e.anchor.originalXml.startsWith('<mc:AlternateContent')),
|
||||
).toBe(true)
|
||||
expect(patchSlideXml(slide)).toBe(slide.originalXml)
|
||||
})
|
||||
|
||||
|
||||
@@ -93,6 +93,40 @@ describe('tableStyles.xml custom styles', () => {
|
||||
expect(resolveTableStyle('{DEAD-BEEF}', xml, theme)).toBeUndefined()
|
||||
expect(resolveTableStyle(undefined, xml, theme)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('tblBg fillRef + alpha band fills + lnRef borders (bnc480256)', () => {
|
||||
const themed = {
|
||||
...theme,
|
||||
fillStyles: [
|
||||
{},
|
||||
{},
|
||||
{ 'a:gradFill': {} }, // placeholder; parse.ts instantiates the ref, table-style only records it
|
||||
],
|
||||
lnStyles: [
|
||||
{ 'a:ln': { '@_w': '25400', 'a:solidFill': { 'a:schemeClr': { '@_val': 'phClr' } } } },
|
||||
],
|
||||
} as unknown as Theme
|
||||
const bgXml =
|
||||
'<?xml version="1.0"?><a:tblStyleLst xmlns:a="a" def="{Y}">' +
|
||||
'<a:tblStyle styleId="{Y}" styleName="Bg">' +
|
||||
'<a:tblBg><a:fillRef idx="3"><a:schemeClr val="accent1"/></a:fillRef></a:tblBg>' +
|
||||
'<a:wholeTbl><a:tcStyle><a:tcBdr>' +
|
||||
'<a:insideH><a:lnRef idx="1"><a:schemeClr val="accent1"><a:tint val="50000"/></a:schemeClr></a:lnRef></a:insideH>' +
|
||||
'<a:insideV><a:ln><a:noFill/></a:ln></a:insideV>' +
|
||||
'</a:tcBdr><a:fill><a:noFill/></a:fill></a:tcStyle></a:wholeTbl>' +
|
||||
'<a:band1H><a:tcStyle><a:tcBdr/><a:fill><a:solidFill>' +
|
||||
'<a:schemeClr val="lt1"><a:alpha val="20000"/></a:schemeClr>' +
|
||||
'</a:solidFill></a:fill></a:tcStyle></a:band1H>' +
|
||||
'</a:tblStyle></a:tblStyleLst>'
|
||||
const def = resolveTableStyle('{Y}', bgXml, themed)!
|
||||
expect(def.tblBgRef).toEqual({ idx: 3, phClr: '#4472C4' })
|
||||
// alpha 20% → #RRGGBBAA suffix (composites over tblBg at render time)
|
||||
expect(def.band1H?.fill).toEqual({ type: 'solid', color: '#FFFFFF33' })
|
||||
// lnRef: phClr from the ref child (tint 50% of accent1), width from the theme lnStyle template
|
||||
expect(def.insideH).toEqual({ fill: { type: 'solid', color: '#A2B9E2' }, width: 25400 })
|
||||
// explicit <a:ln><a:noFill/> → no inside-vertical line
|
||||
expect(def.insideV).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('built-in style family expansion (full GUID table)', () => {
|
||||
|
||||
Reference in New Issue
Block a user