Sync snapshot (2026-08-13) (#92)
- Docs: print dialog with live page preview and range selection; WYSIWYG print preview across apps - Docs: header/footer fidelity - alignment, color, size, images, and tab layout (w:tabs, w:ptab) - Docs: pagination and layout fixes - keepNext crash, blank pages, footnotes, line-height, font substitution, Tamil support - Sheets: import implicit cell addresses and row/column default styles; keep dialog inputs inside narrow grid columns - Slides: PowerPoint-style stage rulers, wheel page turning, and notes bar - Slides: insert 3-D pie and 3-D column charts; render 3-D chart variants as 2-D projections - PDF: comments margin with pin leader lines, note threads with replies, and selection-level text styles - PDF: searchable text insertion, page management, and auto-opening of extract/split output Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
945c370fb9
commit
d5558b6bbb
@@ -26,6 +26,10 @@ export type NewChartKind =
|
||||
| 'radar'
|
||||
/** Combo chart: first N-1 series as clustered columns, last series as a line (on the right secondary value axis) */
|
||||
| 'comboBarLine'
|
||||
/** 3-D pie (c:pie3DChart + c:view3D; this app renders the pseudo-3D projection, PowerPoint renders true 3-D) */
|
||||
| 'pie3D'
|
||||
/** 3-D clustered column (c:bar3DChart + c:view3D) */
|
||||
| 'bar3D'
|
||||
|
||||
/** Chart element/style toggles (unset = current defaults: legend at bottom, no gridlines, no data labels). */
|
||||
export interface ChartStyleOptions {
|
||||
@@ -53,10 +57,8 @@ export interface NewChartOptions extends ChartStyleOptions {
|
||||
pointColors?: Array<Array<string | undefined> | undefined>
|
||||
}
|
||||
|
||||
const CHART_CONTENT_TYPE =
|
||||
'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'
|
||||
const CHART_REL_TYPE =
|
||||
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart'
|
||||
const CHART_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'
|
||||
const CHART_REL_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart'
|
||||
const C_NS = 'http://schemas.openxmlformats.org/drawingml/2006/chart'
|
||||
const A_NS = 'http://schemas.openxmlformats.org/drawingml/2006/main'
|
||||
const R_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
|
||||
@@ -66,7 +68,9 @@ const colLetter = (i: number) => String.fromCharCode(66 + i) // B, C, D…
|
||||
function strCacheXml(values: string[], f: string): string {
|
||||
return (
|
||||
`<c:strRef><c:f>${escapeXmlText(f)}</c:f><c:strCache><c:ptCount val="${values.length}"/>` +
|
||||
values.map((v, i) => (v === '' ? '' : `<c:pt idx="${i}"><c:v>${escapeXmlText(v)}</c:v></c:pt>`)).join('') +
|
||||
values
|
||||
.map((v, i) => (v === '' ? '' : `<c:pt idx="${i}"><c:v>${escapeXmlText(v)}</c:v></c:pt>`))
|
||||
.join('') +
|
||||
'</c:strCache></c:strRef>'
|
||||
)
|
||||
}
|
||||
@@ -76,7 +80,9 @@ function numCacheXml(values: (number | null | undefined)[], f: string): string {
|
||||
`<c:numRef><c:f>${escapeXmlText(f)}</c:f><c:numCache><c:formatCode>General</c:formatCode>` +
|
||||
`<c:ptCount val="${values.length}"/>` +
|
||||
values
|
||||
.map((v, i) => (v == null || !Number.isFinite(v) ? '' : `<c:pt idx="${i}"><c:v>${v}</c:v></c:pt>`))
|
||||
.map((v, i) =>
|
||||
v == null || !Number.isFinite(v) ? '' : `<c:pt idx="${i}"><c:v>${v}</c:v></c:pt>`,
|
||||
)
|
||||
.join('') +
|
||||
'</c:numCache></c:numRef>'
|
||||
)
|
||||
@@ -104,7 +110,8 @@ export function buildChartSpaceXml(opts: NewChartOptions): string {
|
||||
const grid = opts.gridlines ? '<c:majorGridlines/>' : ''
|
||||
const catTitle = opts.catAxisTitle ? axTitleXml(opts.catAxisTitle, false) : ''
|
||||
const valTitle = opts.valAxisTitle ? axTitleXml(opts.valAxisTitle, true) : ''
|
||||
const gapWidth = opts.gapWidthPct != null ? `<c:gapWidth val="${Math.round(opts.gapWidthPct)}"/>` : ''
|
||||
const gapWidth =
|
||||
opts.gapWidthPct != null ? `<c:gapWidth val="${Math.round(opts.gapWidthPct)}"/>` : ''
|
||||
// Empty names stay empty: no <c:tx> for an unnamed series, no <c:cat> when every category name is empty
|
||||
const txXml = (name: string, i: number) =>
|
||||
name === '' ? '' : `<c:tx>${strCacheXml([name], `Sheet1!$${colLetter(i)}$1`)}</c:tx>`
|
||||
@@ -172,6 +179,21 @@ export function buildChartSpaceXml(opts: NewChartOptions): string {
|
||||
: '')
|
||||
} else if (opts.kind === 'pie') {
|
||||
plot = `<c:pieChart><c:varyColors val="1"/>${sers}${dLbls}<c:firstSliceAng val="0"/></c:pieChart>`
|
||||
} else if (opts.kind === 'pie3D') {
|
||||
plot = `<c:pie3DChart><c:varyColors val="1"/>${sers}${dLbls}</c:pie3DChart>`
|
||||
} else if (opts.kind === 'bar3D') {
|
||||
// bar3D takes three axes (category / value / series); the series axis is required by the schema
|
||||
const horizontal = opts.barDir === 'bar'
|
||||
plot =
|
||||
`<c:bar3DChart><c:barDir val="${horizontal ? 'bar' : 'col'}"/><c:grouping val="clustered"/><c:varyColors val="0"/>` +
|
||||
`${sers}${dLbls}${gapWidth}<c:shape val="box"/>` +
|
||||
'<c:axId val="111111111"/><c:axId val="222222222"/><c:axId val="333333333"/></c:bar3DChart>' +
|
||||
'<c:catAx><c:axId val="111111111"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
|
||||
`<c:delete val="0"/><c:axPos val="${horizontal ? 'l' : 'b'}"/>${catTitle}<c:crossAx val="222222222"/></c:catAx>` +
|
||||
'<c:valAx><c:axId val="222222222"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
|
||||
`<c:delete val="0"/><c:axPos val="${horizontal ? 'b' : 'l'}"/>${grid}${valTitle}<c:crossAx val="111111111"/></c:valAx>` +
|
||||
'<c:serAx><c:axId val="333333333"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
|
||||
'<c:delete val="0"/><c:axPos val="b"/><c:crossAx val="222222222"/></c:serAx>'
|
||||
} else if (opts.kind === 'doughnut') {
|
||||
plot =
|
||||
`<c:doughnutChart><c:varyColors val="1"/>${sers}${dLbls}` +
|
||||
@@ -205,7 +227,8 @@ export function buildChartSpaceXml(opts: NewChartOptions): string {
|
||||
`<c:delete val="0"/><c:axPos val="l"/>${grid}${valTitle}<c:crossAx val="111111111"/></c:valAx>`
|
||||
} else {
|
||||
// Horizontal bar chart (barDir=bar): category axis on the left, value axis at the bottom (matches how PowerPoint writes it)
|
||||
const isBarKind = opts.kind === 'bar' || opts.kind === 'barStacked' || opts.kind === 'barPercentStacked'
|
||||
const isBarKind =
|
||||
opts.kind === 'bar' || opts.kind === 'barStacked' || opts.kind === 'barPercentStacked'
|
||||
const horizontal = isBarKind && opts.barDir === 'bar'
|
||||
const axes =
|
||||
`<c:catAx><c:axId val="111111111"/><c:scaling><c:orientation val="minMax"/></c:scaling>` +
|
||||
@@ -223,7 +246,11 @@ export function buildChartSpaceXml(opts: NewChartOptions): string {
|
||||
inner = `<c:areaChart><c:grouping val="standard"/><c:varyColors val="0"/>${sers}${dLbls}${axIds}</c:areaChart>`
|
||||
} else {
|
||||
const grouping =
|
||||
opts.kind === 'barPercentStacked' ? 'percentStacked' : opts.kind === 'barStacked' ? 'stacked' : 'clustered'
|
||||
opts.kind === 'barPercentStacked'
|
||||
? 'percentStacked'
|
||||
: opts.kind === 'barStacked'
|
||||
? 'stacked'
|
||||
: 'clustered'
|
||||
const overlap = grouping === 'clustered' ? '' : '<c:overlap val="100"/>'
|
||||
inner =
|
||||
`<c:barChart><c:barDir val="${horizontal ? 'bar' : 'col'}"/><c:grouping val="${grouping}"/><c:varyColors val="0"/>` +
|
||||
@@ -238,6 +265,15 @@ export function buildChartSpaceXml(opts: NewChartOptions): string {
|
||||
'<c:overlay val="0"/></c:title><c:autoTitleDeleted val="0"/>'
|
||||
: '<c:autoTitleDeleted val="1"/>'
|
||||
|
||||
// 3-D view settings (schema position: after the title block, before plotArea);
|
||||
// rotX/rotY follow PowerPoint's defaults for each type
|
||||
const view3D =
|
||||
opts.kind === 'pie3D'
|
||||
? '<c:view3D><c:rotX val="30"/><c:rotY val="0"/><c:rAngAx val="0"/><c:perspective val="30"/></c:view3D>'
|
||||
: opts.kind === 'bar3D'
|
||||
? '<c:view3D><c:rotX val="15"/><c:rotY val="20"/><c:rAngAx val="1"/><c:perspective val="30"/></c:view3D>'
|
||||
: ''
|
||||
|
||||
const legendPos = opts.legendPos ?? 'b'
|
||||
const legend =
|
||||
legendPos === 'none'
|
||||
@@ -246,7 +282,7 @@ export function buildChartSpaceXml(opts: NewChartOptions): string {
|
||||
return (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
|
||||
`<c:chartSpace xmlns:c="${C_NS}" xmlns:a="${A_NS}" xmlns:r="${R_NS}">` +
|
||||
`<c:chart>${title}<c:plotArea><c:layout/>${plot}</c:plotArea>` +
|
||||
`<c:chart>${title}${view3D}<c:plotArea><c:layout/>${plot}</c:plotArea>` +
|
||||
legend +
|
||||
'<c:plotVisOnly val="1"/><c:dispBlanksAs val="gap"/></c:chart>' +
|
||||
'</c:chartSpace>'
|
||||
@@ -292,7 +328,10 @@ export function addChart(
|
||||
for (const m of rels.matchAll(/Id="rId(\d+)"/g)) maxRid = Math.max(maxRid, Number(m[1]))
|
||||
const rid = `rId${maxRid + 1}`
|
||||
const relXml = `<Relationship Id="${rid}" Type="${CHART_REL_TYPE}" Target="../charts/chart${maxNum + 1}.xml"/>`
|
||||
archive.entries.set(relsPath, Buffer.from(rels.replace('</Relationships>', `${relXml}</Relationships>`), 'utf8'))
|
||||
archive.entries.set(
|
||||
relsPath,
|
||||
Buffer.from(rels.replace('</Relationships>', `${relXml}</Relationships>`), 'utf8'),
|
||||
)
|
||||
|
||||
// 4) graphicFrame fragment + append reparse
|
||||
const id = nextCNvPrId(slide)
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
import { XMLParser } from 'fast-xml-parser'
|
||||
import { type Theme } from './theme'
|
||||
import { resolveColorNode } from './color'
|
||||
import type { Fill } from './types'
|
||||
|
||||
const chartParser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
@@ -91,10 +92,25 @@ export interface ChartModel {
|
||||
dataLabelsPct?: boolean
|
||||
/** Chart title (concatenated rich text of c:chart/c:title) */
|
||||
title?: string
|
||||
/** chartSpace-level <c:spPr> fill (whole-chart background, e.g. picture fill) */
|
||||
bgFill?: Fill
|
||||
/** Theme accent1..6 resolved to #RRGGBB (default series/wedge colors, PowerPoint varyColors order) */
|
||||
themePalette?: string[]
|
||||
/** 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 */
|
||||
pseudo3D?: boolean
|
||||
/** c:view3D rotX (degrees) — controls the pie tilt / bar extrusion feel */
|
||||
rotXDeg?: number
|
||||
}
|
||||
|
||||
/** Parse one chartN.xml. Returns null for unrecognized plot types (caller falls back to a placeholder chip). */
|
||||
export function parseChartXml(xml: string, theme?: Theme): ChartModel | null {
|
||||
export function parseChartXml(
|
||||
xml: string,
|
||||
theme?: Theme,
|
||||
/** DrawingML fill resolver (injected by parse.ts so chart-part blip rIds resolve correctly) */
|
||||
resolveFill?: (spPr: unknown) => Fill | undefined,
|
||||
): ChartModel | null {
|
||||
let doc: any
|
||||
try {
|
||||
doc = chartParser.parse(xml)
|
||||
@@ -106,10 +122,24 @@ export function parseChartXml(xml: string, theme?: Theme): ChartModel | null {
|
||||
if (!plotArea) return null
|
||||
|
||||
// Cartesian types (bar/area/line) may coexist combined (e.g. column+line combo); pie/scatter/radar stand alone.
|
||||
// 3D variants map onto the 2D pipelines (same data/palette/legend); the render layer adds a
|
||||
// pseudo-3D look (elliptical pie with a rim, extruded bars) driven by pseudo3D + c:view3D rotX.
|
||||
const cartesian: Array<{ kind: 'bar' | 'area' | 'line'; plot: any }> = []
|
||||
if (plotArea['c:barChart']) cartesian.push({ kind: 'bar', plot: plotArea['c:barChart'] })
|
||||
if (plotArea['c:areaChart']) cartesian.push({ kind: 'area', plot: plotArea['c:areaChart'] })
|
||||
if (plotArea['c:lineChart']) cartesian.push({ kind: 'line', plot: plotArea['c:lineChart'] })
|
||||
const barPlot = plotArea['c:barChart'] ?? plotArea['c:bar3DChart']
|
||||
const areaPlot = plotArea['c:areaChart'] ?? plotArea['c:area3DChart']
|
||||
const linePlot = plotArea['c:lineChart'] ?? plotArea['c:line3DChart']
|
||||
if (barPlot) cartesian.push({ kind: 'bar', plot: barPlot })
|
||||
if (areaPlot) cartesian.push({ kind: 'area', plot: areaPlot })
|
||||
if (linePlot) cartesian.push({ kind: 'line', plot: linePlot })
|
||||
|
||||
const piePlot = plotArea['c:pieChart'] ?? plotArea['c:pie3DChart'] ?? plotArea['c:doughnutChart']
|
||||
|
||||
const is3D = !!(
|
||||
plotArea['c:bar3DChart'] ||
|
||||
plotArea['c:area3DChart'] ||
|
||||
plotArea['c:line3DChart'] ||
|
||||
plotArea['c:pie3DChart']
|
||||
)
|
||||
|
||||
let kind: ChartKind
|
||||
let plot: any
|
||||
@@ -117,9 +147,9 @@ export function parseChartXml(xml: string, theme?: Theme): ChartModel | null {
|
||||
// Primary type is the first (bar > area > line): axis/bar params read from it; other combo series carry plotKind
|
||||
kind = cartesian[0]!.kind
|
||||
plot = cartesian[0]!.plot
|
||||
} else if (plotArea['c:pieChart'] || plotArea['c:doughnutChart']) {
|
||||
} else if (piePlot) {
|
||||
kind = 'pie'
|
||||
plot = plotArea['c:pieChart'] ?? plotArea['c:doughnutChart']
|
||||
plot = piePlot
|
||||
} else if (plotArea['c:scatterChart']) {
|
||||
kind = 'scatter'
|
||||
plot = plotArea['c:scatterChart']
|
||||
@@ -149,12 +179,19 @@ export function parseChartXml(xml: string, theme?: Theme): ChartModel | null {
|
||||
|
||||
const series: ChartSeries[] = []
|
||||
let categories: string[] = []
|
||||
const parsePlotSeries = (plotNode: any, plotKind: ChartKind, tagPlotKind: boolean, secondary = false) => {
|
||||
const parsePlotSeries = (
|
||||
plotNode: any,
|
||||
plotKind: ChartKind,
|
||||
tagPlotKind: boolean,
|
||||
secondary = false,
|
||||
) => {
|
||||
const sersRaw = plotNode['c:ser']
|
||||
const sers: any[] = Array.isArray(sersRaw) ? sersRaw : sersRaw ? [sersRaw] : []
|
||||
for (const ser of sers) {
|
||||
// Scatter: y values in c:yVal, x values in c:xVal; other types use c:val
|
||||
const s: ChartSeries = { values: readNumPoints(plotKind === 'scatter' ? ser['c:yVal'] : ser['c:val']) }
|
||||
const s: ChartSeries = {
|
||||
values: readNumPoints(plotKind === 'scatter' ? ser['c:yVal'] : ser['c:val']),
|
||||
}
|
||||
if (tagPlotKind) s.plotKind = plotKind as 'line' | 'bar' | 'area'
|
||||
if (secondary) s.secondaryAxis = true
|
||||
if (plotKind === 'scatter') {
|
||||
@@ -169,7 +206,8 @@ export function parseChartXml(xml: string, theme?: Theme): ChartModel | null {
|
||||
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'
|
||||
else if ((plotKind === 'scatter' || plotKind === 'radar') && markerSym != null)
|
||||
s.marker = markerSym !== 'none'
|
||||
// Per-data-point colors (one color per pie slice)
|
||||
const dPts: any[] = ser['c:dPt'] ?? []
|
||||
if (dPts.length) {
|
||||
@@ -200,6 +238,12 @@ export function parseChartXml(xml: string, theme?: Theme): ChartModel | null {
|
||||
|
||||
const model: ChartModel = { kind, categories, series }
|
||||
|
||||
if (is3D) {
|
||||
model.pseudo3D = true
|
||||
const rotX = parseInt(chart['c:view3D']?.['c:rotX']?.['@_val'], 10)
|
||||
if (Number.isFinite(rotX)) model.rotXDeg = rotX
|
||||
}
|
||||
|
||||
if (kind === 'bar') {
|
||||
const dir = plot['c:barDir']?.['@_val']
|
||||
model.barDir = dir === 'bar' ? 'bar' : 'col'
|
||||
@@ -229,19 +273,52 @@ export function parseChartXml(xml: string, theme?: Theme): ChartModel | null {
|
||||
const legendPos = chart['c:legend']?.['c:legendPos']?.['@_val']
|
||||
if (chart['c:legend']) model.legendPos = (legendPos as ChartModel['legendPos']) ?? 'r'
|
||||
|
||||
const chartTitle = collectText(chart['c:title']?.['c:tx']?.['c:rich'])
|
||||
// Whole-chart background (chartSpace-level spPr), e.g. picture fill
|
||||
const bgFill = resolveFill?.(doc['c:chartSpace']?.['c:spPr'])
|
||||
if (bgFill && bgFill.type !== 'none') model.bgFill = bgFill
|
||||
|
||||
// Theme accents: default series/wedge colors follow the file's theme, not a fixed palette
|
||||
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
|
||||
}
|
||||
// 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)
|
||||
if (Number.isFinite(defSz) && defSz > 0) model.defaultTextPt = defSz / 100
|
||||
|
||||
// Title text: rich text, or the cached cell-linked string (c:tx/c:strRef)
|
||||
const chartTitle =
|
||||
collectText(chart['c:title']?.['c:tx']?.['c:rich']) ||
|
||||
readStrPoints(chart['c:title']?.['c:tx'])[0]
|
||||
if (chartTitle) model.title = chartTitle
|
||||
// Auto title: a <c:title> with no c:tx at all (and autoTitleDeleted != 1) takes the sole series name
|
||||
else if (
|
||||
chart['c:title'] &&
|
||||
!chart['c:title']?.['c:tx'] &&
|
||||
chart['c:autoTitleDeleted']?.['@_val'] !== '1' &&
|
||||
series.length === 1 &&
|
||||
series[0]!.name
|
||||
) {
|
||||
model.title = series[0]!.name
|
||||
}
|
||||
|
||||
// Data labels: plot-level or any series-level c:dLbls (delete=1 counts as none)
|
||||
const dLblsInfo = (owner: any): { on: boolean; pct: boolean } => {
|
||||
const d = owner?.['c:dLbls']
|
||||
if (!d || typeof d !== 'object' || d['c:delete']?.['@_val'] === '1') return { on: false, pct: false }
|
||||
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 dLblOwners: any[] = (cartesian.length > 1 ? cartesian.map((c) => c.plot) : [plot]).flatMap(
|
||||
(p) => [p, ...((Array.isArray(p['c:ser']) ? p['c:ser'] : p['c:ser'] ? [p['c:ser']] : []) as any[])],
|
||||
(p) => [
|
||||
p,
|
||||
...((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)
|
||||
if (found) {
|
||||
@@ -296,7 +373,11 @@ function readStrPoints(node: any): string[] {
|
||||
if (strCache) return readPoints(strCache).map((v) => v ?? '')
|
||||
const multi = node?.['c:multiLvlStrRef']?.['c:multiLvlStrCache']
|
||||
if (multi) {
|
||||
const lvls: any[] = Array.isArray(multi['c:lvl']) ? multi['c:lvl'] : multi['c:lvl'] ? [multi['c:lvl']] : []
|
||||
const lvls: any[] = Array.isArray(multi['c:lvl'])
|
||||
? multi['c:lvl']
|
||||
: multi['c:lvl']
|
||||
? [multi['c:lvl']]
|
||||
: []
|
||||
// The innermost (first lvl) holds the leaf categories
|
||||
if (lvls.length) return readPoints(lvls[0]).map((v) => v ?? '')
|
||||
}
|
||||
@@ -336,7 +417,9 @@ function parseAxis(ax: any, theme?: Theme): ChartAxisStyle | undefined {
|
||||
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
|
||||
const defRPr = ax['c:txPr']?.['a:p']?.[0]?.['a:pPr']?.['a:defRPr'] ?? ax['c:txPr']?.['a:p']?.['a:pPr']?.['a:defRPr']
|
||||
const defRPr =
|
||||
ax['c:txPr']?.['a:p']?.[0]?.['a:pPr']?.['a:defRPr'] ??
|
||||
ax['c:txPr']?.['a:p']?.['a:pPr']?.['a:defRPr']
|
||||
if (defRPr) {
|
||||
const c = resolveColorNode(defRPr['a:solidFill'], theme)
|
||||
if (c) out.labelColor = c
|
||||
|
||||
@@ -706,6 +706,10 @@ function generateRunXml(r: TextRun): string {
|
||||
r.color && !r.colorInherited
|
||||
? `<a:solidFill><a:srgbClr val="${hex6(r.color)}"/></a:solidFill>`
|
||||
: ''
|
||||
// Text highlight (CT_TextCharacterProperties order: after the fill group, before the font slots)
|
||||
const highlight = r.highlight
|
||||
? `<a:highlight><a:srgbClr val="${hex6(r.highlight)}"/></a:highlight>`
|
||||
: ''
|
||||
// Original dual fonts/theme references restored first; no declaration (inherited) writes nothing;
|
||||
// a user-changed font writes all three slots, so a rebuilt run keeps the typeface the user picked
|
||||
const font =
|
||||
@@ -718,7 +722,7 @@ function generateRunXml(r: TextRun): string {
|
||||
: ''
|
||||
// Run-level hyperlink: rId written back (allocated by ensureRunLinkRels for links set this session)
|
||||
const hlink = hlinkXml(r)
|
||||
const rprInner = ln + color + font + hlink
|
||||
const rprInner = ln + color + highlight + font + hlink
|
||||
const rPr = rprInner
|
||||
? `<a:rPr${attrs}>${rprInner}</a:rPr>`
|
||||
: attrs
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
import JSZip from 'jszip'
|
||||
import { PackageArchive, relsPathFor, resolveTarget } from './zip'
|
||||
import { parseTheme, type Theme } from './theme'
|
||||
import { parseClrMap, parseTheme, type Theme } from './theme'
|
||||
import { parseSlide, parseDecorations, sliceGroupChildXmls, type ParseContext } from './parse'
|
||||
import { parsePlaceholderMap, parseMasterTextStyles } from './placeholder'
|
||||
import {
|
||||
@@ -268,28 +268,36 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
|
||||
|
||||
const chain = archive.resolveSlideChain(slidePath)
|
||||
const ctx: ParseContext = {}
|
||||
if (chain.themePath) {
|
||||
const themeXml = archive.readText(chain.themePath)
|
||||
if (themeXml) ctx.theme = parseTheme(themeXml)
|
||||
}
|
||||
// Placeholder geometry + text style inheritance + background inheritance: layout first, master fallback (read-only)
|
||||
const layoutXml = (chain.layoutPath ? archive.readText(chain.layoutPath) : undefined) ?? undefined
|
||||
const masterXml = (chain.masterPath ? archive.readText(chain.masterPath) : undefined) ?? undefined
|
||||
if (chain.themePath) {
|
||||
const themeXml = archive.readText(chain.themePath)
|
||||
if (themeXml) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
if (layoutXml) {
|
||||
ctx.layoutPlaceholders = parsePlaceholderMap(layoutXml, ctx.theme)
|
||||
ctx.layoutBg = layoutXml
|
||||
if (chain.layoutPath) ctx.layoutMediaRels = partMediaRels(archive, chain.layoutPath)
|
||||
}
|
||||
const masterXml = (chain.masterPath ? archive.readText(chain.masterPath) : undefined) ?? undefined
|
||||
if (masterXml) {
|
||||
ctx.masterPlaceholders = parsePlaceholderMap(masterXml, ctx.theme)
|
||||
ctx.masterTextStyles = parseMasterTextStyles(masterXml, ctx.theme)
|
||||
ctx.masterBg = masterXml
|
||||
if (chain.masterPath) ctx.masterMediaRels = partMediaRels(archive, chain.masterPath)
|
||||
}
|
||||
// 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 avRels = new Map<string, { target: string; external?: boolean }>()
|
||||
const diagramDrawings = new Map<string, string>()
|
||||
const diagramMediaRels = new Map<string, Map<string, string>>()
|
||||
const hlinkRels = new Map<string, string>()
|
||||
let slideOrder: string[] | undefined
|
||||
for (const rel of rels.values()) {
|
||||
@@ -303,8 +311,12 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
|
||||
} else if (rel.type.endsWith('/image')) {
|
||||
mediaRels.set(rel.id, resolveTarget(slidePath, rel.target))
|
||||
} else if (rel.type.endsWith('/chart')) {
|
||||
const xml = archive.readText(resolveTarget(slidePath, rel.target))
|
||||
if (xml) chartXmls.set(rel.id, xml)
|
||||
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))
|
||||
}
|
||||
} else if (/\/(?:video|audio|media)$/.test(rel.type)) {
|
||||
// Audio/video (r:link of a:videoFile/a:audioFile; embedded or external)
|
||||
const external = rel.targetMode === 'External'
|
||||
@@ -323,18 +335,22 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
|
||||
if (relId) {
|
||||
const drawRel = rels.get(relId) ?? archive.readRels(dataPath).get(relId)
|
||||
const basePath = rels.get(relId) ? slidePath : dataPath
|
||||
const drawingXml = drawRel
|
||||
? archive.readText(resolveTarget(basePath, drawRel.target))
|
||||
: undefined
|
||||
if (drawingXml) diagramDrawings.set(rel.id, drawingXml)
|
||||
const drawingPath = drawRel ? resolveTarget(basePath, drawRel.target) : undefined
|
||||
const drawingXml = drawingPath ? archive.readText(drawingPath) : undefined
|
||||
if (drawingXml && drawingPath) {
|
||||
diagramDrawings.set(rel.id, drawingXml)
|
||||
diagramMediaRels.set(rel.id, partMediaRels(archive, drawingPath))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.mediaRels = mediaRels
|
||||
ctx.chartXmls = chartXmls
|
||||
if (chartMediaRels.size) ctx.chartMediaRels = chartMediaRels
|
||||
if (hlinkRels.size) ctx.hlinkRels = hlinkRels
|
||||
if (avRels.size) ctx.avRels = avRels
|
||||
if (diagramDrawings.size) ctx.diagramDrawings = diagramDrawings
|
||||
if (diagramMediaRels.size) ctx.diagramMediaRels = diagramMediaRels
|
||||
// Table style definitions (embedded custom styles; built-in styles handled by table-style as fallback)
|
||||
ctx.tableStyles = archive.readText('ppt/tableStyles.xml') ?? undefined
|
||||
|
||||
@@ -435,32 +451,48 @@ function buildDecorations(
|
||||
const hasPh = (xml: string | undefined, type: string) =>
|
||||
!!xml && new RegExp(`<p:ph\\b[^>]*type="${type}"`).test(xml)
|
||||
|
||||
// Slide-level showMasterSp="0" ("hide background graphics") hides both master and layout
|
||||
// decoration shapes; layout-level only stops the master's from showing through. Footer
|
||||
// placeholders are not background graphics and keep following the <p:hf> toggles.
|
||||
const slideHidesInherited = /<p:sld\b[^>]*showMasterSp="(?:0|false)"/.test(slideXml)
|
||||
const masterShown =
|
||||
!/<p:sld\b[^>]*showMasterSp="(?:0|false)"/.test(slideXml) &&
|
||||
!slideHidesInherited &&
|
||||
!(layoutXml && /<p:sldLayout\b[^>]*showMasterSp="(?:0|false)"/.test(layoutXml))
|
||||
|
||||
if (masterShown && masterXml && parts.masterPath) {
|
||||
if (masterXml && parts.masterPath) {
|
||||
const hfTypes = new Set([...enabled].filter((k) => !slidePh.has(k) && !hasPh(layoutXml, k)))
|
||||
const ctx: ParseContext = {
|
||||
theme: parts.theme,
|
||||
mediaRels: partMediaRels(archive, parts.masterPath),
|
||||
if (masterShown || hfTypes.size) {
|
||||
const ctx: ParseContext = {
|
||||
theme: parts.theme,
|
||||
mediaRels: partMediaRels(archive, parts.masterPath),
|
||||
}
|
||||
out.push(
|
||||
...parseDecorations(masterXml, ctx, {
|
||||
hfTypes,
|
||||
hideShapes: !masterShown,
|
||||
...(slideNum != null ? { slideNum } : {}),
|
||||
}),
|
||||
)
|
||||
}
|
||||
out.push(
|
||||
...parseDecorations(masterXml, ctx, { hfTypes, ...(slideNum != null ? { slideNum } : {}) }),
|
||||
)
|
||||
}
|
||||
if (layoutXml && parts.layoutPath) {
|
||||
const hfTypes = new Set([...enabled].filter((k) => !slidePh.has(k)))
|
||||
// Layout footer placeholders often omit xfrm/font size, inheriting from the master
|
||||
const ctx: ParseContext = {
|
||||
theme: parts.theme,
|
||||
mediaRels: partMediaRels(archive, parts.layoutPath),
|
||||
masterPlaceholders: parts.masterPlaceholders,
|
||||
masterTextStyles: parts.masterTextStyles,
|
||||
if (!slideHidesInherited || hfTypes.size) {
|
||||
// Layout footer placeholders often omit xfrm/font size, inheriting from the master
|
||||
const ctx: ParseContext = {
|
||||
theme: parts.theme,
|
||||
mediaRels: partMediaRels(archive, parts.layoutPath),
|
||||
masterPlaceholders: parts.masterPlaceholders,
|
||||
masterTextStyles: parts.masterTextStyles,
|
||||
}
|
||||
out.push(
|
||||
...parseDecorations(layoutXml, ctx, {
|
||||
hfTypes,
|
||||
hideShapes: slideHidesInherited,
|
||||
...(slideNum != null ? { slideNum } : {}),
|
||||
}),
|
||||
)
|
||||
}
|
||||
out.push(
|
||||
...parseDecorations(layoutXml, ctx, { hfTypes, ...(slideNum != null ? { slideNum } : {}) }),
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1772,11 +1804,15 @@ export function editChartElement(
|
||||
? 'barPercentStacked'
|
||||
: existing.grouping === 'stacked'
|
||||
? 'barStacked'
|
||||
: 'bar'
|
||||
: existing.pseudo3D // 3-D column survives data/style-only rebuilds (stacked 3-D degrades to 2-D stacked)
|
||||
? 'bar3D'
|
||||
: 'bar'
|
||||
: existing.kind === 'pie'
|
||||
? (existing.holePct ?? 0) > 0
|
||||
? 'doughnut'
|
||||
: 'pie'
|
||||
: existing.pseudo3D
|
||||
? 'pie3D'
|
||||
: 'pie'
|
||||
: (existing.kind as NewChartKind)
|
||||
const kind: NewChartKind = patch.kind ?? derivedKind
|
||||
// Horizontal bar direction is preserved through rebuilds; an explicit type change resets it unless the patch asks for barDir 'bar' (the gallery's horizontal-bar entry)
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
*/
|
||||
import type { PackageArchive } from './zip'
|
||||
import { resolveTarget } from './zip'
|
||||
import { parseTheme } from './theme'
|
||||
import { parseClrMap, parseTheme } from './theme'
|
||||
import { parseSlide, parseDecorations, type ParseContext } from './parse'
|
||||
import { parsePlaceholderMap, parseMasterTextStyles } from './placeholder'
|
||||
import type { Slide } from './types'
|
||||
@@ -98,12 +98,15 @@ export function parseMasterPart(archive: PackageArchive, partPath: string): Slid
|
||||
ctx.tableStyles = archive.readText('ppt/tableStyles.xml') ?? undefined
|
||||
|
||||
const masterXml = !isMaster && masterPath ? archive.readText(masterPath) : undefined
|
||||
if (ctx.theme)
|
||||
ctx.theme.clrMap = isMaster ? parseClrMap(xml) : parseClrMap(masterXml ?? undefined, xml)
|
||||
if (isMaster) {
|
||||
ctx.masterTextStyles = parseMasterTextStyles(xml, ctx.theme)
|
||||
} else if (masterXml) {
|
||||
ctx.masterPlaceholders = parsePlaceholderMap(masterXml, ctx.theme)
|
||||
ctx.masterTextStyles = parseMasterTextStyles(masterXml, ctx.theme)
|
||||
ctx.masterBg = masterXml
|
||||
if (masterPath) ctx.masterMediaRels = partMedia(archive, masterPath)
|
||||
}
|
||||
|
||||
const slide = parseSlide({ path: partPath, slideXml: xml, masterPath, ctx })
|
||||
|
||||
@@ -104,6 +104,13 @@ export interface ParseContext {
|
||||
layoutBg?: string
|
||||
/** Full master XML (read-only, background inheritance fallback) */
|
||||
masterBg?: string
|
||||
/** Layout/master part image rels (blip rIds in inherited backgrounds live in those parts) */
|
||||
layoutMediaRels?: Map<string, string>
|
||||
masterMediaRels?: Map<string, string>
|
||||
/** Chart rId → that chart part's own image rels (for chart background picture fills) */
|
||||
chartMediaRels?: Map<string, Map<string, string>>
|
||||
/** Diagram data rId → the drawing part's own image rels (SmartArt picture fills) */
|
||||
diagramMediaRels?: Map<string, Map<string, string>>
|
||||
/** ppt/tableStyles.xml source (table style definitions, read-only) */
|
||||
tableStyles?: string
|
||||
}
|
||||
@@ -140,10 +147,15 @@ export function parseSlide(input: SlideParseInput): Slide {
|
||||
})
|
||||
|
||||
// Background: the slide's own <p:bg> wins, otherwise inherit layout→master (read-only).
|
||||
// Inherited backgrounds resolve blip rIds against their own part's rels, not the slide's.
|
||||
const background =
|
||||
parseBackground(slideXml, ctx) ??
|
||||
(ctx.layoutBg ? parseBackground(ctx.layoutBg, ctx) : undefined) ??
|
||||
(ctx.masterBg ? parseBackground(ctx.masterBg, ctx) : undefined)
|
||||
(ctx.layoutBg
|
||||
? parseBackground(ctx.layoutBg, { ...ctx, mediaRels: ctx.layoutMediaRels ?? ctx.mediaRels })
|
||||
: undefined) ??
|
||||
(ctx.masterBg
|
||||
? parseBackground(ctx.masterBg, { ...ctx, mediaRels: ctx.masterMediaRels ?? ctx.mediaRels })
|
||||
: undefined)
|
||||
|
||||
return {
|
||||
path,
|
||||
@@ -174,10 +186,22 @@ function parseBackground(xml: string, ctx: ParseContext): Fill | undefined {
|
||||
// bgPr directly contains solidFill/gradFill/blipFill/pattFill
|
||||
return parseFill(bgPr, ctx)
|
||||
}
|
||||
// <p:bgRef>: references the theme fillStyleLst + a color (simplified: take its color as solid)
|
||||
// <p:bgRef idx>: theme fill template (1..3 → fillStyleLst, 1001..1003 → bgFillStyleLst)
|
||||
// instantiated with the referenced color as phClr; color-only fallback when unresolvable.
|
||||
const bgRef = bg?.['p:bgRef']
|
||||
if (bgRef) {
|
||||
const color = resolveColorNode(bgRef, ctx)
|
||||
const idx = parseInt(String(bgRef['@_idx'] ?? ''), 10)
|
||||
const tpl =
|
||||
idx >= 1001
|
||||
? ctx.theme?.bgFillStyles?.[idx - 1001]
|
||||
: idx >= 1
|
||||
? ctx.theme?.fillStyles?.[idx - 1]
|
||||
: undefined
|
||||
if (tpl) {
|
||||
const fill = parseFill(tpl, { ...ctx, phClr: color })
|
||||
if (fill) return fill
|
||||
}
|
||||
if (color) return { type: 'solid', color }
|
||||
}
|
||||
return undefined
|
||||
@@ -747,7 +771,11 @@ function graphicFramePassthrough(node: any, anchor: ByteAnchor, ctx: ParseContex
|
||||
if (uri.includes('/chart')) {
|
||||
const rid = data?.['c:chart']?.['@_r:id']
|
||||
const chartXml = rid ? ctx.chartXmls?.get(rid) : undefined
|
||||
const model = chartXml ? parseChartXml(chartXml, ctx.theme) : null
|
||||
// Fill resolver bound to the chart part's own rels (blip rIds live there, not on the slide)
|
||||
const chartFillCtx: ParseContext = { ...ctx, mediaRels: ctx.chartMediaRels?.get(String(rid)) }
|
||||
const model = chartXml
|
||||
? parseChartXml(chartXml, ctx.theme, (spPr) => parseFill(spPr, chartFillCtx))
|
||||
: null
|
||||
if (model) {
|
||||
const cNvPr = node['p:nvGraphicFramePr']?.['p:cNvPr']
|
||||
const descr: string | undefined = cNvPr?.['@_descr'] || undefined
|
||||
@@ -780,7 +808,12 @@ function graphicFramePassthrough(node: any, anchor: ByteAnchor, ctx: ParseContex
|
||||
const dm = data?.['dgm:relIds']?.['@_r:dm']
|
||||
const drawingXml = dm ? ctx.diagramDrawings?.get(String(dm)) : undefined
|
||||
if (drawingXml) {
|
||||
const shapes = parseDiagramDrawing(drawingXml, ctx)
|
||||
// Picture-fill rIds inside the drawing resolve against the drawing part's own rels
|
||||
const drawingRels = dm ? ctx.diagramMediaRels?.get(String(dm)) : undefined
|
||||
const shapes = parseDiagramDrawing(
|
||||
drawingXml,
|
||||
drawingRels ? { ...ctx, mediaRels: drawingRels } : ctx,
|
||||
)
|
||||
if (shapes.length) el.previewShapes = shapes
|
||||
}
|
||||
}
|
||||
@@ -816,6 +849,37 @@ function parseDiagramDrawing(drawingXml: string, ctx: ParseContext): SlideElemen
|
||||
for (const sp of sps) {
|
||||
// The preview layer has no byte fidelity (never written back); the anchor is a placeholder
|
||||
const anchor: ByteAnchor = { spIndex: -1, originalXml: '', range: [0, 0] }
|
||||
// dsp:txXfrm gives the text its own frame; split text off the shape so both
|
||||
// render with their proper transforms (text rotation is shape rot + txXfrm rot)
|
||||
const txXfrm = sp['p:txXfrm']
|
||||
const txBody = sp['p:txBody']
|
||||
if (txXfrm && typeof txXfrm === 'object' && txBody) {
|
||||
const shapeOnly = { ...sp }
|
||||
delete shapeOnly['p:txBody']
|
||||
const shapeEl = parseSpShape(shapeOnly, anchor, ctx)
|
||||
if (shapeEl.type !== 'passthrough') out.push(shapeEl)
|
||||
const spRot = parseInt(sp['p:spPr']?.['a:xfrm']?.['@_rot'] ?? '0', 10) || 0
|
||||
const txRot = parseInt(txXfrm['@_rot'] ?? '0', 10) || 0
|
||||
const textXfrm = { ...txXfrm, '@_rot': String(spRot + txRot) }
|
||||
// Keep fontRef for the text color only. Copying the whole p:style still
|
||||
// applies effectRef — empty a:effectLst does not block the !shadow && !glow
|
||||
// fallback — so the split text frame would redraw the shape's shadow/glow.
|
||||
const fontRef = sp['p:style']?.['a:fontRef']
|
||||
const textSp = {
|
||||
'p:nvSpPr': sp['p:nvSpPr'],
|
||||
'p:spPr': {
|
||||
'a:xfrm': textXfrm,
|
||||
'a:prstGeom': { '@_prst': 'rect' },
|
||||
'a:noFill': {},
|
||||
'a:ln': { 'a:noFill': {} },
|
||||
},
|
||||
...(fontRef ? { 'p:style': { 'a:fontRef': fontRef } } : {}),
|
||||
'p:txBody': txBody,
|
||||
}
|
||||
const textEl = parseSpShape(textSp, anchor, ctx)
|
||||
if (textEl.type !== 'passthrough') out.push(textEl)
|
||||
continue
|
||||
}
|
||||
const el = parseSpShape(sp, anchor, ctx)
|
||||
if (el.type !== 'passthrough') out.push(el)
|
||||
}
|
||||
@@ -1051,6 +1115,9 @@ function parseGradFill(grad: any, ctx: ParseContext): Fill | undefined {
|
||||
const ang = grad['a:lin']?.['@_ang']
|
||||
const angle = ang != null ? parseInt(ang, 10) || 0 : undefined
|
||||
const pathType = grad['a:path']?.['@_path']
|
||||
const ftr = grad['a:path']?.['a:fillToRect']
|
||||
// Omitted fillToRect attributes default to 0 (whole tile rect), not to a centered inset
|
||||
const frac = (v: unknown) => (v != null ? (parseInt(String(v), 10) || 0) / 100000 : 0)
|
||||
return {
|
||||
type: 'gradient',
|
||||
stops,
|
||||
@@ -1058,6 +1125,16 @@ function parseGradFill(grad: any, ctx: ParseContext): Fill | undefined {
|
||||
...(pathType === 'circle' || pathType === 'rect' || pathType === 'shape'
|
||||
? { path: pathType }
|
||||
: {}),
|
||||
...(ftr
|
||||
? {
|
||||
fillTo: {
|
||||
l: frac(ftr['@_l']),
|
||||
t: frac(ftr['@_t']),
|
||||
r: frac(ftr['@_r']),
|
||||
b: frac(ftr['@_b']),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1271,6 +1348,9 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
|
||||
// The patch path uses this to avoid baking theme colors into srgbClr (theme switches must stay linked)
|
||||
const colorFollowsTheme = color != null && !(fill && fill['a:srgbClr'])
|
||||
const colorInherited = color != null && !fill
|
||||
// Text highlight <a:highlight> (PowerPoint draws it as a background behind the run)
|
||||
const highlightNode = rPr['a:highlight']
|
||||
const highlight = highlightNode ? resolveColorNode(highlightNode, ctx) : undefined
|
||||
// Font: run explicit (incl. +mj/+mn theme refs) → inherited default → theme font
|
||||
const latin = resolveFontRef(rPr['a:latin']?.['@_typeface'], ctx.theme) ?? dflt?.latinFont
|
||||
const ea = resolveFontRef(rPr['a:ea']?.['@_typeface'], ctx.theme) ?? dflt?.eaFont
|
||||
@@ -1303,6 +1383,10 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
|
||||
text,
|
||||
bold: bAttr != null ? bAttr === '1' || bAttr === 'true' : !!dflt?.bold,
|
||||
italic: iAttr != null ? iAttr === '1' || iAttr === 'true' : !!dflt?.italic,
|
||||
...(() => {
|
||||
const cap = rPr['@_cap'] != null ? String(rPr['@_cap']) : dflt?.cap
|
||||
return cap && cap !== 'none' ? { cap } : {}
|
||||
})(),
|
||||
underline: (uAttr !== undefined && uAttr !== 'none') || linkUnderline,
|
||||
...(uAttr !== undefined && uAttr !== 'none' ? { underlineStyle: String(uAttr) } : {}),
|
||||
...(linkUnderline ? { underlineImplicit: true } : {}),
|
||||
@@ -1319,6 +1403,7 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
|
||||
color,
|
||||
...(colorFollowsTheme ? { colorFollowsTheme } : {}),
|
||||
...(colorInherited ? { colorInherited } : {}),
|
||||
...(highlight ? { highlight } : {}),
|
||||
...(outline ? { outline } : {}),
|
||||
...(hlink?.['@_r:id']
|
||||
? {
|
||||
@@ -1342,6 +1427,8 @@ export interface DecorationOptions {
|
||||
hfTypes?: Set<string>
|
||||
/** Actual value of the slide-number field <a:fld type="slidenum"> (replaces the cached text) */
|
||||
slideNum?: number
|
||||
/** Skip non-placeholder shapes (showMasterSp="0"), keeping only the hf placeholders */
|
||||
hideShapes?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1371,7 +1458,7 @@ export function parseDecorations(
|
||||
const ph = (el as { placeholder?: string }).placeholder
|
||||
if (ph !== undefined) {
|
||||
if (!opts.hfTypes?.has(ph)) return
|
||||
} else if (/<p:ph[\s/>]/.test(fragXml)) {
|
||||
} else if (/<p:ph[\s/>]/.test(fragXml) || opts.hideShapes) {
|
||||
// Untyped <p:ph idx="…"/> (body family) or picture/table placeholders: content carriers, skip
|
||||
return
|
||||
}
|
||||
|
||||
@@ -33,6 +33,8 @@ export interface LevelTextStyle {
|
||||
fontSize?: number
|
||||
bold?: boolean
|
||||
italic?: boolean
|
||||
/** Character casing <a:defRPr cap>: 'all' | 'small' | 'none' */
|
||||
cap?: string
|
||||
color?: string
|
||||
latinFont?: string
|
||||
eaFont?: string
|
||||
@@ -205,6 +207,7 @@ function parseLvlPPr(pPrRaw: unknown, theme?: Theme): LevelTextStyle | undefined
|
||||
if (defRPr['@_sz']) out.fontSize = parseInt(String(defRPr['@_sz']), 10) / 100
|
||||
if (defRPr['@_b'] != null) out.bold = defRPr['@_b'] === '1' || defRPr['@_b'] === 'true'
|
||||
if (defRPr['@_i'] != null) out.italic = defRPr['@_i'] === '1' || defRPr['@_i'] === 'true'
|
||||
if (defRPr['@_cap'] != null) out.cap = String(defRPr['@_cap'])
|
||||
const color = resolveColorNode(defRPr['a:solidFill'], theme)
|
||||
if (color) out.color = color
|
||||
const latin = resolveFontRef(typefaceAttr(defRPr['a:latin']), theme)
|
||||
@@ -314,6 +317,7 @@ export function mergeTextStyleChain(
|
||||
if (out.fontSize == null && lvl.fontSize != null) out.fontSize = lvl.fontSize
|
||||
if (out.bold == null && lvl.bold != null) out.bold = lvl.bold
|
||||
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.latinFont == null && lvl.latinFont != null) out.latinFont = lvl.latinFont
|
||||
if (out.eaFont == null && lvl.eaFont != null) out.eaFont = lvl.eaFont
|
||||
|
||||
@@ -185,7 +185,11 @@ const line = (color: string, width = 12700): Stroke => ({ fill: solid(color), wi
|
||||
* predefined-table-styles implementation; colors are resolved to final values via the
|
||||
* theme; banded alpha is pre-blended against the underlying background).
|
||||
*/
|
||||
function builtinStyle(family: BuiltinFamily, accentName: string | undefined, theme: Theme | undefined): TableStyleDef {
|
||||
function builtinStyle(
|
||||
family: BuiltinFamily,
|
||||
accentName: string | undefined,
|
||||
theme: Theme | undefined,
|
||||
): TableStyleDef {
|
||||
const lt1 = resolveSchemeColor('lt1', theme) ?? '#FFFFFF'
|
||||
const dk1 = resolveSchemeColor('dk1', theme) ?? '#000000'
|
||||
const accent = accentName ? (resolveSchemeColor(accentName, theme) ?? '#4472C4') : undefined
|
||||
@@ -347,8 +351,14 @@ function builtinStyle(family: BuiltinFamily, accentName: string | undefined, the
|
||||
case 'dark2': {
|
||||
const a = accent ?? dk1
|
||||
// Header paired colors: base=dk1, Accent1->accent2 / Accent3->accent4 / Accent5->accent6
|
||||
const headerPair: Record<string, string> = { accent1: 'accent2', accent3: 'accent4', accent5: 'accent6' }
|
||||
const header = accentName ? (resolveSchemeColor(headerPair[accentName] ?? accentName, theme) ?? dk1) : dk1
|
||||
const headerPair: Record<string, string> = {
|
||||
accent1: 'accent2',
|
||||
accent3: 'accent4',
|
||||
accent5: 'accent6',
|
||||
}
|
||||
const header = accentName
|
||||
? (resolveSchemeColor(headerPair[accentName] ?? accentName, theme) ?? dk1)
|
||||
: dk1
|
||||
const band = solid(tint(a, 0.4))
|
||||
return {
|
||||
wholeTbl: { fill: solid(tint(a, 0.2)), textColor: dk1 },
|
||||
@@ -439,10 +449,7 @@ function readPart(part: unknown, theme: Theme | undefined): TablePartStyle | und
|
||||
if (!part || typeof part !== 'object') return undefined
|
||||
const p = asXmlNode(part)
|
||||
const out: TablePartStyle = {}
|
||||
const fillColor = readColor(
|
||||
asXmlNode(asXmlNode(p['a:tcStyle'])['a:fill'])['a:solidFill'],
|
||||
theme,
|
||||
)
|
||||
const fillColor = readColor(asXmlNode(asXmlNode(p['a:tcStyle'])['a:fill'])['a:solidFill'], theme)
|
||||
if (fillColor) out.fill = solid(fillColor)
|
||||
if (p['a:tcTxStyle']) {
|
||||
const tx = asXmlNode(p['a:tcTxStyle'])
|
||||
@@ -453,7 +460,11 @@ function readPart(part: unknown, theme: Theme | undefined): TablePartStyle | und
|
||||
return Object.keys(out).length ? out : undefined
|
||||
}
|
||||
|
||||
function readInside(part: unknown, tag: 'a:insideH' | 'a:insideV', theme: Theme | undefined): Stroke | undefined {
|
||||
function readInside(
|
||||
part: unknown,
|
||||
tag: 'a:insideH' | 'a:insideV' | 'a:left' | 'a:right' | 'a:top' | 'a:bottom',
|
||||
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
|
||||
@@ -463,7 +474,11 @@ function readInside(part: unknown, tag: 'a:insideH' | 'a:insideV', theme: Theme
|
||||
return line(c, parseInt(String(ln['@_w']), 10) || 12700)
|
||||
}
|
||||
|
||||
function parseTableStylesXml(xml: string, styleId: string, theme: Theme | undefined): TableStyleDef | undefined {
|
||||
function parseTableStylesXml(
|
||||
xml: string,
|
||||
styleId: string,
|
||||
theme: Theme | undefined,
|
||||
): TableStyleDef | undefined {
|
||||
let doc: XmlNode
|
||||
try {
|
||||
doc = asXmlNode(tsParser.parse(xml))
|
||||
@@ -474,7 +489,17 @@ function parseTableStylesXml(xml: string, styleId: string, theme: Theme | undefi
|
||||
const style = xmlArray(list).find((s) => s['@_styleId'] === styleId)
|
||||
if (!style) return undefined
|
||||
const def: TableStyleDef = {}
|
||||
for (const key of ['wholeTbl', 'band1H', 'band2H', 'band1V', 'band2V', 'firstRow', 'lastRow', 'firstCol', 'lastCol'] as const) {
|
||||
for (const key of [
|
||||
'wholeTbl',
|
||||
'band1H',
|
||||
'band2H',
|
||||
'band1V',
|
||||
'band2V',
|
||||
'firstRow',
|
||||
'lastRow',
|
||||
'firstCol',
|
||||
'lastCol',
|
||||
] as const) {
|
||||
const p = readPart(style['a:' + key], theme)
|
||||
if (p) def[key] = p
|
||||
}
|
||||
@@ -482,6 +507,13 @@ function parseTableStylesXml(xml: string, styleId: string, theme: Theme | undefi
|
||||
def.insideV = readInside(style['a:wholeTbl'], 'a:insideV', theme)
|
||||
if (!def.insideH) delete def.insideH
|
||||
if (!def.insideV) delete def.insideV
|
||||
const outer = {
|
||||
l: readInside(style['a:wholeTbl'], 'a:left', theme),
|
||||
r: readInside(style['a:wholeTbl'], 'a:right', theme),
|
||||
t: readInside(style['a:wholeTbl'], 'a:top', theme),
|
||||
b: readInside(style['a:wholeTbl'], 'a:bottom', theme),
|
||||
}
|
||||
if (outer.l || outer.r || outer.t || outer.b) def.outer = outer
|
||||
return Object.keys(def).length ? def : undefined
|
||||
}
|
||||
|
||||
@@ -498,7 +530,9 @@ export function cellPartStyle(
|
||||
nCols: number,
|
||||
): TablePartStyle {
|
||||
const merge = (base: TablePartStyle, over?: TablePartStyle): TablePartStyle =>
|
||||
over ? { ...base, ...Object.fromEntries(Object.entries(over).filter(([, v]) => v !== undefined)) } : base
|
||||
over
|
||||
? { ...base, ...Object.fromEntries(Object.entries(over).filter(([, v]) => v !== undefined)) }
|
||||
: base
|
||||
|
||||
let out: TablePartStyle = { ...(def.wholeTbl ?? {}) }
|
||||
const isFirstRow = flags.firstRow && r === 0
|
||||
|
||||
@@ -11,6 +11,11 @@ const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_
|
||||
export interface Theme {
|
||||
/** clrScheme: dk1/lt1/dk2/lt2/accent1..6/hlink/folHlink → #RRGGBB */
|
||||
colors: Record<string, string>
|
||||
/**
|
||||
* Master p:clrMap (or slide/layout a:overrideClrMapping): schemeClr name → clrScheme key.
|
||||
* Dark masters invert it (bg1="dk1" tx1="lt1" …); absent → standard mapping.
|
||||
*/
|
||||
clrMap?: Record<string, string>
|
||||
/** fontScheme: major / minor Latin fonts */
|
||||
majorFont?: string
|
||||
minorFont?: string
|
||||
@@ -85,7 +90,20 @@ export function parseTheme(themeXml: string): Theme {
|
||||
const elements = asXmlNode(themeEl['a:themeElements'])
|
||||
const clrScheme = asXmlNode(elements['a:clrScheme'])
|
||||
const colors: Record<string, string> = {}
|
||||
for (const key of ['dk1', 'lt1', 'dk2', 'lt2', 'accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6', 'hlink', 'folHlink']) {
|
||||
for (const key of [
|
||||
'dk1',
|
||||
'lt1',
|
||||
'dk2',
|
||||
'lt2',
|
||||
'accent1',
|
||||
'accent2',
|
||||
'accent3',
|
||||
'accent4',
|
||||
'accent5',
|
||||
'accent6',
|
||||
'hlink',
|
||||
'folHlink',
|
||||
]) {
|
||||
const c = readColorNode(clrScheme['a:' + key])
|
||||
if (c) colors[key] = c
|
||||
}
|
||||
@@ -122,7 +140,10 @@ export function parseTheme(themeXml: string): Theme {
|
||||
* Theme font reference ("+mj-lt" / "+mn-ea" etc.) → final font name.
|
||||
* Values not starting with "+" are returned as-is; returns undefined when the theme has no match.
|
||||
*/
|
||||
export function resolveFontRef(typeface: string | undefined, theme: Theme | undefined): string | undefined {
|
||||
export function resolveFontRef(
|
||||
typeface: string | undefined,
|
||||
theme: Theme | undefined,
|
||||
): string | undefined {
|
||||
if (!typeface) return undefined
|
||||
if (!typeface.startsWith('+')) return typeface
|
||||
switch (typeface) {
|
||||
@@ -144,10 +165,56 @@ export function resolveFontRef(typeface: string | undefined, theme: Theme | unde
|
||||
}
|
||||
|
||||
/** schemeClr name (e.g. 'tx1','bg1','accent1','phClr') → final #RRGGBB. */
|
||||
export function resolveSchemeColor(name: string, theme: Theme | undefined, phClr?: string): string | undefined {
|
||||
export function resolveSchemeColor(
|
||||
name: string,
|
||||
theme: Theme | undefined,
|
||||
phClr?: string,
|
||||
): string | undefined {
|
||||
if (name === 'phClr') return phClr
|
||||
// Standard mapping: tx1→dk1, bg1→lt1, tx2→dk2, bg2→lt2
|
||||
const map: Record<string, string> = { tx1: 'dk1', bg1: 'lt1', tx2: 'dk2', bg2: 'lt2' }
|
||||
const key = map[name] ?? name
|
||||
const standard: Record<string, string> = { tx1: 'dk1', bg1: 'lt1', tx2: 'dk2', bg2: 'lt2' }
|
||||
const key = theme?.clrMap?.[name] ?? standard[name] ?? name
|
||||
return theme?.colors[key]
|
||||
}
|
||||
|
||||
const CLR_MAP_NAMES = [
|
||||
'bg1',
|
||||
'tx1',
|
||||
'bg2',
|
||||
'tx2',
|
||||
'accent1',
|
||||
'accent2',
|
||||
'accent3',
|
||||
'accent4',
|
||||
'accent5',
|
||||
'accent6',
|
||||
'hlink',
|
||||
'folHlink',
|
||||
]
|
||||
|
||||
function clrMapFromTag(tag: string): Record<string, string> | undefined {
|
||||
const out: Record<string, string> = {}
|
||||
for (const name of CLR_MAP_NAMES) {
|
||||
const m = new RegExp(`\\b${name}="([^"]+)"`).exec(tag)
|
||||
if (m) out[name] = m[1]
|
||||
}
|
||||
return Object.keys(out).length ? out : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Effective color mapping for a slide: slide/layout <a:overrideClrMapping> wins over the
|
||||
* master's <p:clrMap> (<a:masterClrMapping/> just inherits). Undefined → standard mapping.
|
||||
*/
|
||||
export function parseClrMap(
|
||||
masterXml?: string,
|
||||
layoutXml?: string,
|
||||
slideXml?: string,
|
||||
): Record<string, string> | undefined {
|
||||
for (const xml of [slideXml, layoutXml]) {
|
||||
const tag = xml ? /<a:overrideClrMapping\b[^>]*\/?>/.exec(xml)?.[0] : undefined
|
||||
const map = tag ? clrMapFromTag(tag) : undefined
|
||||
if (map) return map
|
||||
}
|
||||
const tag = masterXml ? /<p:clrMap\b[^>]*\/?>/.exec(masterXml)?.[0] : undefined
|
||||
return tag ? clrMapFromTag(tag) : undefined
|
||||
}
|
||||
|
||||
@@ -53,6 +53,8 @@ export type Fill =
|
||||
angle?: number
|
||||
/** <a:path path>: circle/rect/shape = radial/path gradient (linear by default) */
|
||||
path?: 'circle' | 'rect' | 'shape'
|
||||
/** <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: 'pattern'; fg: ResolvedColor; bg: ResolvedColor; preset: string }
|
||||
@@ -133,7 +135,14 @@ export interface TextRun {
|
||||
csFont?: string
|
||||
/** Run has no explicit font declaration (inherits/theme); patches don't inject latin/ea when the font is unchanged */
|
||||
fontImplicit?: boolean
|
||||
/**
|
||||
* Effective character casing ('all' | 'small', explicit rPr cap or inherited from
|
||||
* placeholder styles). Display-only: the render layer uppercases; never written back.
|
||||
*/
|
||||
cap?: string
|
||||
color?: ResolvedColor
|
||||
/** Text highlight color <a:rPr><a:highlight> (drawn as a background behind the run) */
|
||||
highlight?: ResolvedColor
|
||||
/** color is display-only (from schemeClr/inheritance, not an explicit run srgbClr);
|
||||
* the patch path won't write srgbClr from it, avoiding baking in theme colors and breaking theme switches */
|
||||
colorFollowsTheme?: boolean
|
||||
|
||||
@@ -361,3 +361,101 @@ describe('buildChartSpaceXml style options (generate → parse round-trip)', ()
|
||||
expect(m.dataLabelsPct).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('chart theme palette and default text size', () => {
|
||||
const PIE_V = `<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea>
|
||||
<c:pieChart><c:varyColors val="1"/><c:ser><c:idx val="0"/><c:order val="0"/>
|
||||
<c:cat><c:strRef><c:strCache><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:numCache><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:txPr><a:bodyPr/><a:lstStyle/><a:p><a:pPr><a:defRPr sz="1800"/></a:pPr></a:p></c:txPr>
|
||||
</c:chartSpace>`
|
||||
const theme = {
|
||||
colors: {
|
||||
accent1: '#4F81BD',
|
||||
accent2: '#C0504D',
|
||||
accent3: '#9BBB59',
|
||||
accent4: '#8064A2',
|
||||
accent5: '#4BACC6',
|
||||
accent6: '#F79646',
|
||||
},
|
||||
clrMap: {},
|
||||
} as unknown as import('../src/theme').Theme
|
||||
|
||||
it('exposes theme accents as the default palette', () => {
|
||||
const m = parseChartXml(PIE_V, theme)!
|
||||
expect(m.themePalette).toEqual([
|
||||
'#4F81BD',
|
||||
'#C0504D',
|
||||
'#9BBB59',
|
||||
'#8064A2',
|
||||
'#4BACC6',
|
||||
'#F79646',
|
||||
])
|
||||
})
|
||||
|
||||
it('reads the chartSpace-level default text size', () => {
|
||||
const m = parseChartXml(PIE_V, theme)!
|
||||
expect(m.defaultTextPt).toBe(18)
|
||||
})
|
||||
|
||||
it('leaves both unset without theme/txPr', () => {
|
||||
const m = parseChartXml(PIE_V.replace(/<c:txPr>[\s\S]*<\/c:txPr>/, ''))!
|
||||
expect(m.themePalette).toBeUndefined()
|
||||
expect(m.defaultTextPt).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('3D chart variants flatten to their 2D projection', () => {
|
||||
it('pie3DChart parses as pie with data', () => {
|
||||
const m = parseChartXml(`<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea>
|
||||
<c:pie3DChart><c:varyColors val="1"/><c:ser><c:idx val="0"/><c:order val="0"/>
|
||||
<c:cat><c:strRef><c:strCache><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:numCache><c:pt idx="0"><c:v>7</c:v></c:pt><c:pt idx="1"><c:v>3</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser></c:pie3DChart></c:plotArea></c:chart></c:chartSpace>`)!
|
||||
expect(m.kind).toBe('pie')
|
||||
expect(m.holePct).toBe(0)
|
||||
expect(m.series[0]!.values).toEqual([7, 3])
|
||||
expect(m.categories).toEqual(['A', 'B'])
|
||||
})
|
||||
|
||||
it('bar3DChart parses as bar (standard grouping renders clustered)', () => {
|
||||
const m = parseChartXml(`<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea>
|
||||
<c:bar3DChart><c:barDir val="col"/><c:grouping val="standard"/>
|
||||
<c:ser><c:idx val="0"/><c:order val="0"/>
|
||||
<c:val><c:numRef><c:numCache><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:bar3DChart></c:plotArea></c:chart></c:chartSpace>`)!
|
||||
expect(m.kind).toBe('bar')
|
||||
expect(m.barDir).toBe('col')
|
||||
expect(m.grouping).toBe('standard')
|
||||
expect(m.series[0]!.values).toEqual([1, 2])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildChartSpaceXml 3D kinds (generate → parse round-trip)', () => {
|
||||
const data = {
|
||||
categories: ['A', 'B', 'C'],
|
||||
series: [{ name: 'S1', values: [3, 1, 2] }],
|
||||
offset: { x: 0, y: 0, cx: 100, cy: 100 },
|
||||
}
|
||||
it('pie3D writes c:pie3DChart + c:view3D and parses back as pseudo-3D pie', () => {
|
||||
const xml = buildChartSpaceXml({ kind: 'pie3D', ...data })
|
||||
expect(xml).toContain('<c:pie3DChart>')
|
||||
expect(xml).toContain('<c:view3D><c:rotX val="30"/>')
|
||||
const m = parseChartXml(xml)!
|
||||
expect(m.kind).toBe('pie')
|
||||
expect(m.pseudo3D).toBe(true)
|
||||
expect(m.rotXDeg).toBe(30)
|
||||
expect(m.series[0]!.values).toEqual([3, 1, 2])
|
||||
})
|
||||
it('bar3D writes c:bar3DChart with three axes + c:view3D and parses back as pseudo-3D bar', () => {
|
||||
const xml = buildChartSpaceXml({ kind: 'bar3D', ...data })
|
||||
expect(xml).toContain('<c:bar3DChart>')
|
||||
expect(xml).toContain('<c:serAx>')
|
||||
expect(xml).toContain('<c:view3D><c:rotX val="15"/>')
|
||||
const m = parseChartXml(xml)!
|
||||
expect(m.kind).toBe('bar')
|
||||
expect(m.barDir).toBe('col')
|
||||
expect(m.pseudo3D).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -775,3 +775,58 @@ describe('per-data-point chart colors', () => {
|
||||
expect(el.chart.series[0]!.pointColors?.[1]).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('3-D chart kinds survive insert and edit round-trips', () => {
|
||||
it('pie3D inserts, edits keep the 3-D type, and an explicit switch to 2-D works', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
addChart(opened, 0, {
|
||||
kind: 'pie3D',
|
||||
categories: ['A', 'B'],
|
||||
series: [{ name: 'S', values: [7, 3] }],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
let reopened = await openPptx(await savePptx(opened))
|
||||
let el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.kind).toBe('pie')
|
||||
expect(el.chart.pseudo3D).toBe(true)
|
||||
|
||||
// Data-only edit keeps 3-D
|
||||
expect(editChartElement(reopened, 0, el.id, { series: [{ name: 'S', values: [5, 5] }] })).toBe(
|
||||
true,
|
||||
)
|
||||
reopened = await openPptx(await savePptx(reopened))
|
||||
el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.pseudo3D).toBe(true)
|
||||
expect(el.chart.series[0]!.values).toEqual([5, 5])
|
||||
|
||||
// Explicit type change back to flat pie drops the 3-D view
|
||||
expect(editChartElement(reopened, 0, el.id, { kind: 'pie' })).toBe(true)
|
||||
reopened = await openPptx(await savePptx(reopened))
|
||||
el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.pseudo3D).toBeUndefined()
|
||||
})
|
||||
|
||||
it('bar3D inserts and a data edit keeps the 3-D type', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
addChart(opened, 0, {
|
||||
kind: 'bar3D',
|
||||
categories: ['A', 'B'],
|
||||
series: [{ name: 'S', values: [1, 2] }],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
let reopened = await openPptx(await savePptx(opened))
|
||||
let el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.kind).toBe('bar')
|
||||
expect(el.chart.pseudo3D).toBe(true)
|
||||
expect(
|
||||
editChartElement(reopened, 0, el.id, {
|
||||
categories: ['A', 'B', 'C'],
|
||||
series: [{ name: 'S', values: [1, 2, 3] }],
|
||||
}),
|
||||
).toBe(true)
|
||||
reopened = await openPptx(await savePptx(reopened))
|
||||
el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.pseudo3D).toBe(true)
|
||||
expect(el.chart.categories).toEqual(['A', 'B', 'C'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -118,6 +118,62 @@ describe('SmartArt prerendered drawing read-only preview', () => {
|
||||
})
|
||||
expect(slide.elements[0]!.anchor.originalXml).toBe(SMARTART_FRAME)
|
||||
})
|
||||
|
||||
it('dsp:txXfrm text frame keeps fontRef color but not the shape effectRef', () => {
|
||||
const drawing =
|
||||
'<dsp:drawing xmlns:dsp="dsp" xmlns:a="a"><dsp:spTree><dsp:nvGrpSpPr/><dsp:grpSpPr/>' +
|
||||
'<dsp:sp modelId="{X}"><dsp:nvSpPr><dsp:cNvPr id="1" name=""/><dsp:cNvSpPr/></dsp:nvSpPr>' +
|
||||
'<dsp:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="2000" cy="1000"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="roundRect"><a:avLst/></a:prstGeom></dsp:spPr>' +
|
||||
'<dsp:txXfrm><a:off x="100" y="200"/><a:ext cx="1800" cy="600"/></dsp:txXfrm>' +
|
||||
'<dsp:style><a:lnRef idx="2"><a:schemeClr val="accent1"/></a:lnRef>' +
|
||||
'<a:fillRef idx="1"><a:schemeClr val="accent1"/></a:fillRef>' +
|
||||
'<a:effectRef idx="3"><a:schemeClr val="accent1"/></a:effectRef>' +
|
||||
'<a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef></dsp:style>' +
|
||||
'<dsp:txBody><a:bodyPr/><a:p><a:r><a:t>Step One</a:t></a:r></a:p></dsp:txBody></dsp:sp>' +
|
||||
'</dsp:spTree></dsp:drawing>'
|
||||
const effectTheme: any = {
|
||||
colors: { accent1: '#4472C4', lt1: '#FFFFFF', dk1: '#000000' },
|
||||
effectStyles: [
|
||||
{ 'a:effectStyle': { 'a:effectLst': {} } },
|
||||
{ 'a:effectStyle': { 'a:effectLst': {} } },
|
||||
{
|
||||
'a:effectStyle': {
|
||||
'a:effectLst': {
|
||||
'a:glow': {
|
||||
'@_rad': '63500',
|
||||
'a:schemeClr': { '@_val': 'phClr', 'a:alpha': { '@_val': '40000' } },
|
||||
},
|
||||
'a:outerShdw': {
|
||||
'@_blurRad': '57150',
|
||||
'@_dist': '19050',
|
||||
'@_dir': '5400000',
|
||||
'a:srgbClr': { '@_val': '000000', 'a:alpha': { '@_val': '63000' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(SMARTART_FRAME),
|
||||
ctx: { theme: effectTheme, diagramDrawings: new Map([['rId1', drawing]]) },
|
||||
})
|
||||
const shapes = (slide.elements[0] as PassthroughElement).previewShapes as TextElement[]
|
||||
expect(shapes).toHaveLength(2)
|
||||
const [shape, text] = shapes
|
||||
expect(shape!.presetGeometry).toBe('roundRect')
|
||||
expect(shape!.shadow).toBeTruthy()
|
||||
expect(shape!.glow).toBeTruthy()
|
||||
expect(shape!.text).toBeUndefined()
|
||||
expect(text!.fill).toEqual({ type: 'none' })
|
||||
expect(text!.stroke).toBeUndefined()
|
||||
expect(text!.shadow).toBeUndefined()
|
||||
expect(text!.glow).toBeUndefined()
|
||||
expect(text!.text!.paragraphs[0]!.runs[0]!.text).toBe('Step One')
|
||||
expect(text!.text!.paragraphs[0]!.runs[0]!.color).toBe('#FFFFFF')
|
||||
})
|
||||
})
|
||||
|
||||
const OLE_FRAME =
|
||||
|
||||
@@ -384,3 +384,29 @@ describe('complex-script font follows the font change', () => {
|
||||
expect(out).not.toContain('<a:cs')
|
||||
})
|
||||
})
|
||||
|
||||
describe('text highlight <a:highlight>', () => {
|
||||
const HL =
|
||||
'<a:r><a:rPr lang="en-US"><a:highlight><a:srgbClr val="FF0000"/></a:highlight></a:rPr>' +
|
||||
'<a:t>marked</a:t></a:r>'
|
||||
|
||||
it('parses the run highlight color', () => {
|
||||
const { el } = parseEl(HL)
|
||||
expect(el.text!.paragraphs[0]!.runs[0]!.highlight).toBe('#FF0000')
|
||||
})
|
||||
|
||||
it('text-only edit keeps the highlight bytes', () => {
|
||||
const { el } = parseEl(HL)
|
||||
el.text!.paragraphs[0]!.runs[0]!.text = 'edited'
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('<a:highlight><a:srgbClr val="FF0000"/></a:highlight>')
|
||||
expect(out).toContain('edited')
|
||||
})
|
||||
|
||||
it('a structural rebuild rewrites the highlight', () => {
|
||||
const { el } = parseEl(HL)
|
||||
el.text!.paragraphs[0]!.runs.push({ text: ' added' }) // forces the rebuild path
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('<a:highlight><a:srgbClr val="FF0000"/></a:highlight>')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -207,3 +207,23 @@ describe('ensureTableStyleXml', () => {
|
||||
expect(def?.insideH?.fill).toEqual({ type: 'solid', color: '#D9D9D9' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('custom table style outer borders (tcBdr left/right/top/bottom)', () => {
|
||||
const XML = `<a:tblStyleLst xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" def="{X}">
|
||||
<a:tblStyle styleId="{X}" styleName="T"><a:wholeTbl><a:tcStyle><a:tcBdr>
|
||||
<a:left><a:ln w="9525"><a:solidFill><a:srgbClr val="9E9E9E"/></a:solidFill></a:ln></a:left>
|
||||
<a:right><a:ln w="9525"><a:solidFill><a:srgbClr val="9E9E9E"/></a:solidFill></a:ln></a:right>
|
||||
<a:top><a:ln w="9525"><a:solidFill><a:srgbClr val="9E9E9E"/></a:solidFill></a:ln></a:top>
|
||||
<a:bottom><a:ln w="9525"><a:solidFill><a:srgbClr val="9E9E9E"/></a:solidFill></a:ln></a:bottom>
|
||||
<a:insideH><a:ln w="9525"><a:solidFill><a:srgbClr val="9E9E9E"/></a:solidFill></a:ln></a:insideH>
|
||||
<a:insideV><a:ln w="9525"><a:solidFill><a:srgbClr val="9E9E9E"/></a:solidFill></a:ln></a:insideV>
|
||||
</a:tcBdr></a:tcStyle></a:wholeTbl></a:tblStyle></a:tblStyleLst>`
|
||||
it('reads the whole-table outer edges alongside inside lines', () => {
|
||||
const def = resolveTableStyle('{X}', XML, undefined)!
|
||||
for (const k of ['l', 'r', 't', 'b'] as const) {
|
||||
expect(def.outer?.[k]?.fill).toEqual({ type: 'solid', color: '#9E9E9E' })
|
||||
expect(def.outer?.[k]?.width).toBe(9525)
|
||||
}
|
||||
expect(def.insideH?.fill).toEqual({ type: 'solid', color: '#9E9E9E' })
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user