Sync snapshot (2026-08-19) (#110)

- Improve Docs pagination, anchored-object fidelity, password protection, recovery safety, and multilingual font fallback
- Scale Sheets editing and saves for large workbooks with safer AI bulk operations, aggregation, undo, recovery, and richer visual fidelity
- Expand Slides fidelity with 3D rendering, SmartArt and WordArt improvements, pattern and texture fills, and resource cleanup
- Add AI PDF creation, text insertion, reading-position restore, safer atomic saves, and improved comments and page workflows
- Add Markdown math rendering and protect linked assets across save, conversion, and document lifecycle operations
- Read legacy DOC and PPT attachments locally and strengthen document package resource cleanup
- Document default-on usage analytics with a persistent Settings opt-out and a dedicated, tested privacy page

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-08-19 20:14:50 +08:00
committed by GitHub
co-authored by GenOffice
parent 04a994b9e9
commit fe2e17403c
372 changed files with 40308 additions and 4357 deletions
+170 -13
View File
@@ -41,6 +41,9 @@ export interface ChartSeries {
xValues?: Array<number | null>
/** Bubble: per-point sizes (c:bubbleSize); marker radius ∝ √size (area represents value) */
bubbleSizes?: Array<number | null>
/** Value-from-cells data labels (c15:datalabelsRange cache), shown when the c15
* showDataLabelsRange flag is on */
pointLabels?: string[]
/** Line: smoothed curve */
smooth?: boolean
/** c:idx: automatic palette colors key off this, not document order */
@@ -73,6 +76,12 @@ export interface ChartAxisStyle {
labelColor?: string
labelSizePt?: number
labelBold?: boolean
/** Axis-title run styling (first rich run, else title txPr default run) */
titleSizePt?: number
titleBold?: boolean
titleItalic?: boolean
titleColor?: string
/** 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 */
@@ -85,6 +94,8 @@ export interface ChartAxisStyle {
numFmt?: string
lineColor?: string
gridColor?: string
/** gridColor is the fallback (no explicit spPr color); the render layer picks the real default by hasStylePart */
gridColorAuto?: boolean
gridDash?: boolean
/** prstDash value (dash/dashDot/sysDash/...) for a finer dash pattern */
gridDashVal?: string
@@ -93,7 +104,14 @@ export interface ChartAxisStyle {
/** Minor gridlines: only drawn with an explicit color (PowerPoint hides them by default) */
minorGridColor?: string
minorGridWidthEmu?: number
/** <c:minorGridlines/> present without an explicit color */
minorGridAuto?: boolean
/** Explicit tick units (c:majorUnit / c:minorUnit) */
majorUnit?: number
minorUnit?: number
title?: string
/** <c:title><c:overlay val="1"/>: the axis title floats over the plot, reserving no space */
titleOverlay?: boolean
/** <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) */
@@ -107,6 +125,8 @@ export interface ChartModel {
grouping?: 'clustered' | 'stacked' | 'percentStacked' | 'standard'
/** Gap between bars (% of bar width, c:gapWidth, default 150) */
gapWidthPct?: number
/** Series overlap within a category (% of bar width, c:overlap; negative spreads bars apart) */
overlapPct?: number
categories: string[]
series: ChartSeries[]
/** Legend position (undefined when there is no c:legend) */
@@ -116,6 +136,10 @@ export interface ChartModel {
legendBold?: boolean
/** <c:legend><c:overlay val="1"/>: the legend floats over the plot, reserving no space */
legendOverlay?: boolean
/** c:legend manual layout: factor = offset from the auto position, edge = absolute, fractions of the frame */
legendLayout?: { x?: number; y?: number; xMode?: 'edge' | 'factor'; yMode?: 'edge' | 'factor' }
/** Chart part has a Microsoft chartStyle companion (style1.xml); without one PowerPoint uses black label text */
hasStylePart?: 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
@@ -152,6 +176,10 @@ export interface ChartModel {
titlePt?: number
/** <c:title><c:overlay val="1"/>: the title floats over the plot, reserving no space */
titleOverlay?: boolean
/** Explicit c:title run styling (txPr default run, else the first rich run) */
titleBold?: boolean
titleItalic?: boolean
titleColor?: string
/** chartSpace-level <c:spPr> fill (whole-chart background, e.g. picture fill) */
bgFill?: Fill
/** Plot-area fill (c:plotArea's own spPr) */
@@ -192,6 +220,27 @@ export interface ChartModel {
pseudo3D?: boolean
/** c:view3D rotX (degrees) — controls the pie tilt / bar extrusion feel */
rotXDeg?: number
/** c:bar3DChart: full 3D stage (series spread along a depth axis); angles in degrees */
bar3D?: {
rotX: number
rotY: number
/** c:depthPercent: bar depth as % of bar width */
depthPct: number
/** c:rAngAx: right-angle axes (parallel skew projection; PowerPoint's default) */
rAngAx: boolean
/** c:gapDepth: gap between depth rows as % of bar depth */
gapDepthPct: number
/** c:serAx present and visible: PowerPoint labels series names along the depth axis */
serAxLabels: boolean
}
/** c:area3DChart: full 3D stage (standard grouping spreads series along the depth axis) */
area3D?: {
rotX: number
rotY: number
/** c:gapDepth: gap between depth rows as % of ribbon depth */
gapDepthPct: number
serAxLabels: boolean
}
}
/** Parse one chartN.xml. Returns null for unrecognized plot types (caller falls back to a placeholder chip). */
@@ -311,6 +360,24 @@ export function parseChartXml(
)
if (color) s.color = color
if (ser['c:smooth']?.['@_val'] === '1') s.smooth = true
// Value-from-cells data labels (2012 c15 extension): strings live in the range cache,
// gated by c15:showDataLabelsRange on the series dLbls
const serExtRaw = ser['c:extLst']?.['c:ext']
const serExts: any[] = Array.isArray(serExtRaw) ? serExtRaw : serExtRaw ? [serExtRaw] : []
const rangeCache = serExts
.map((e) => e?.['c15:datalabelsRange']?.['c15:dlblRangeCache'])
.find(Boolean)
const dLblExtRaw = ser['c:dLbls']?.['c:extLst']?.['c:ext']
const dLblExts: any[] = Array.isArray(dLblExtRaw)
? dLblExtRaw
: dLblExtRaw
? [dLblExtRaw]
: []
const showRange = dLblExts.some((e) => e?.['c15:showDataLabelsRange']?.['@_val'] === '1')
if (rangeCache && showRange) {
const labs = readPoints(rangeCache).map((v) => v ?? '')
if (labs.some((v) => v)) s.pointLabels = labs
}
const serLn = ser['c:spPr']?.['a:ln']
const serDash = serLn?.['a:prstDash']?.['@_val']
if (typeof serDash === 'string' && serDash !== 'solid') s.dash = serDash
@@ -326,7 +393,9 @@ export function parseChartXml(
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'
if (plotKind === 'line')
// Stock OHLC series show markers by default (PowerPoint draws marker-only lines)
s.marker = fromStock ? markerSym !== 'none' : 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'
@@ -397,9 +466,39 @@ export function parseChartXml(
model.pseudo3D = true
const rotX = parseInt(chart['c:view3D']?.['c:rotX']?.['@_val'], 10)
if (Number.isFinite(rotX)) model.rotXDeg = rotX
const b3 = plotArea['c:bar3DChart']
const a3 = plotArea['c:area3DChart']
const v3 = chart['c:view3D']
const num = (node: any, dflt: number) => {
const v = parseInt(node?.['@_val'], 10)
return Number.isFinite(v) ? v : dflt
}
const serAx = plotArea['c:serAx']
const serAxLabels =
serAx != null &&
serAx['c:delete']?.['@_val'] !== '1' &&
serAx['c:tickLblPos']?.['@_val'] !== 'none'
if (b3) {
model.bar3D = {
rotX: num(v3?.['c:rotX'], 15),
rotY: num(v3?.['c:rotY'], 20),
depthPct: num(v3?.['c:depthPercent'], 100),
rAngAx: v3?.['c:rAngAx']?.['@_val'] !== '0',
gapDepthPct: num(b3['c:gapDepth'], 150),
serAxLabels,
}
}
if (a3) {
model.area3D = {
rotX: num(v3?.['c:rotX'], 15),
rotY: num(v3?.['c:rotY'], 20),
gapDepthPct: num(a3['c:gapDepth'], 150),
serAxLabels,
}
}
}
if (kind === 'bar' || kind === 'area') {
if (kind === 'bar' || kind === 'area' || kind === 'line') {
const grouping = plot['c:grouping']?.['@_val']
if (grouping) model.grouping = grouping
}
@@ -408,6 +507,8 @@ export function parseChartXml(
model.barDir = dir === 'bar' ? 'bar' : 'col'
const gap = plot['c:gapWidth']?.['@_val']
model.gapWidthPct = gap != null ? parseInt(gap, 10) : 150
const ov = plot['c:overlap']?.['@_val']
if (ov != null) model.overlapPct = parseInt(ov, 10) || 0
}
if (kind === 'pie') {
@@ -447,8 +548,28 @@ export function parseChartXml(
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
// Measured PowerPoint behavior: explicit <c:overlay val="1"/> floats the legend, and so does
// a legend with no <c:legendPos> at all (unless overlay is explicitly 0)
const overlay = legendNode['c:overlay']?.['@_val']
if (overlay === '1' || (overlay === undefined && legendPos === undefined)) {
model.legendOverlay = true
}
const man = legendNode['c:layout']?.['c:manualLayout']
if (man) {
const frac = (k: string) => {
const v = Number(man[k]?.['@_val'])
return Number.isFinite(v) ? v : undefined
}
const mode = (k: string): 'edge' | 'factor' =>
man[k]?.['@_val'] === 'edge' ? 'edge' : 'factor'
const [lx, ly] = [frac('c:x'), frac('c:y')]
if (lx !== undefined || ly !== undefined) {
model.legendLayout = {
...(lx !== undefined ? { x: lx, xMode: mode('c:xMode') } : {}),
...(ly !== undefined ? { y: ly, yMode: mode('c:yMode') } : {}),
}
}
}
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
@@ -560,14 +681,23 @@ export function parseChartXml(
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
// Rich-text titles usually carry the styling on the first run, not on txPr
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 titleRPr = r0?.['a:rPr'] ?? p0?.['a:pPr']?.['a:defRPr']
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)
const runSz = parseInt(titleRPr?.['@_sz'], 10)
if (Number.isFinite(runSz) && runSz > 0) model.titlePt = runSz / 100
}
const styleRPr = titleRPr ?? (Array.isArray(titP) ? titP[0] : titP)?.['a:pPr']?.['a:defRPr']
if (styleRPr) {
// Explicit b="0" must reach the render layer (its default for chart titles is bold)
if (styleRPr['@_b'] != null) model.titleBold = styleRPr['@_b'] === '1'
if (styleRPr['@_i'] === '1') model.titleItalic = true
const c = resolveColorNode(styleRPr['a:solidFill'], theme)
if (c) model.titleColor = c
}
}
// Data labels: plot-level or any series-level c:dLbls (delete=1 counts as none)
@@ -799,6 +929,7 @@ function parseAxis(ax: any, theme?: Theme): ChartAxisStyle | undefined {
const ln = typeof grid === 'object' ? grid['c:spPr']?.['a:ln'] : undefined
const gc = resolveColorNode(ln?.['a:solidFill'], theme)
out.gridColor = gc ?? '#E6E6E6'
if (!gc) out.gridColorAuto = true
const dash = ln?.['a:prstDash']?.['@_val']
if (dash && dash !== 'solid') {
out.gridDash = true
@@ -808,18 +939,44 @@ function parseAxis(ax: any, theme?: Theme): ChartAxisStyle | undefined {
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']
if (minor !== undefined) {
const ln = typeof minor === 'object' ? minor['c:spPr']?.['a:ln'] : undefined
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
} else {
out.minorGridAuto = true
}
}
const majorUnit = Number(ax['c:majorUnit']?.['@_val'])
if (Number.isFinite(majorUnit) && majorUnit > 0) out.majorUnit = majorUnit
const minorUnit = Number(ax['c:minorUnit']?.['@_val'])
if (Number.isFinite(minorUnit) && minorUnit > 0) out.minorUnit = minorUnit
// Axis title (all a:t inside c:title/c:tx/c:rich concatenated)
const title = collectText(ax['c:title']?.['c:tx']?.['c:rich'])
if (title) out.title = title
const titleNode = ax['c:title']
const title = collectText(titleNode?.['c:tx']?.['c:rich'])
if (title) {
out.title = title
if (titleNode?.['c:overlay']?.['@_val'] === '1') out.titleOverlay = true
const tp0raw = titleNode?.['c:tx']?.['c:rich']?.['a:p']
const tp0 = Array.isArray(tp0raw) ? tp0raw[0] : tp0raw
const tr0 = Array.isArray(tp0?.['a:r']) ? tp0['a:r'][0] : tp0?.['a:r']
const txp = titleNode?.['c:txPr']?.['a:p']
const rPr =
tr0?.['a:rPr'] ??
tp0?.['a:pPr']?.['a:defRPr'] ??
(Array.isArray(txp) ? txp[0] : txp)?.['a:pPr']?.['a:defRPr']
if (rPr) {
const sz = parseInt(rPr['@_sz'], 10)
if (Number.isFinite(sz) && sz > 0) out.titleSizePt = sz / 100
if (rPr['@_b'] === '1') out.titleBold = true
if (rPr['@_i'] === '1') out.titleItalic = true
const c = resolveColorNode(rPr['a:solidFill'], theme)
if (c) out.titleColor = c
}
}
return Object.keys(out).length ? out : undefined
}
+22 -6
View File
@@ -11,6 +11,7 @@ import type { OpenedPptx } from './index'
import { resolveTarget, type PackageArchive } from './zip'
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
import { appendRelationship, unescapeXml } from './notes'
import { removeRelationshipAndCollectOwnedTarget } from './resource-cleanup'
const XMLDECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const NS_P = 'http://schemas.openxmlformats.org/presentationml/2006/main'
@@ -73,14 +74,24 @@ function readAuthors(archive: PackageArchive): Map<number, { name: string; initi
return map
}
/** Path of a slide's comments part (null if the slide has no comments). */
function commentsPathForSlide(archive: PackageArchive, slidePath: string): string | null {
/** Relationship and path of a slide's comments part (null when absent). */
function commentsRelationshipForSlide(
archive: PackageArchive,
slidePath: string,
): { id: string; path: string } | null {
for (const rel of archive.readRels(slidePath).values()) {
if (rel.type === COMMENTS_REL) return resolveTarget(slidePath, rel.target)
if (rel.type === COMMENTS_REL) {
return { id: rel.id, path: resolveTarget(slidePath, rel.target) }
}
}
return null
}
/** Path of a slide's comments part (null if the slide has no comments). */
function commentsPathForSlide(archive: PackageArchive, slidePath: string): string | null {
return commentsRelationshipForSlide(archive, slidePath)?.path ?? null
}
/** Read all comments on a slide (in order of appearance). */
export function getSlideComments(archive: PackageArchive, slidePath: string): SlideComment[] {
const partPath = commentsPathForSlide(archive, slidePath)
@@ -201,8 +212,9 @@ export function deleteSlideComment(
const slide = opened.deck.slides[slideIndex]
if (!slide) return false
const { archive } = opened
const partPath = commentsPathForSlide(archive, slide.path)
if (!partPath) return false
const relationship = commentsRelationshipForSlide(archive, slide.path)
if (!relationship) return false
const partPath = relationship.path
const xml = archive.readText(partPath)
if (!xml) return false
for (const m of xml.matchAll(/<p:cm\b([^>]*)>[\s\S]*?<\/p:cm>/g)) {
@@ -211,7 +223,11 @@ export function deleteSlideComment(
Number(/\bauthorId="(\d+)"/.exec(attrs)?.[1] ?? -1) === ref.authorId &&
Number(/\bidx="(\d+)"/.exec(attrs)?.[1] ?? -1) === ref.idx
) {
setEntry(archive, partPath, xml.slice(0, m.index!) + xml.slice(m.index! + m[0].length))
const next = xml.slice(0, m.index!) + xml.slice(m.index! + m[0].length)
setEntry(archive, partPath, next)
if (!/<p:cm\b/.test(next)) {
removeRelationshipAndCollectOwnedTarget(archive, slide.path, relationship.id)
}
return true
}
}
+295
View File
@@ -0,0 +1,295 @@
/**
* Hierarchy-family (orgChart1) diagram layout interpreter.
*
* PowerPoint org charts carry the full layout algorithm in diagrams/layoutN.xml:
* box proportions and gaps as <dgm:constr> factors, and the std/hang branch
* decision as <dgm:choose> conditions on node depth. This module evaluates those
* instead of approximating them:
* - box h = `h` fact × w (0.5); sibling gap = `sibSp` fact × w (0.21);
* row gap = `sp` fact × w (0.21) — all read from the constraint list
* - subtrees pack by per-row contours (a hanging overhang may slide under a
* sibling's box row), parent centered on the midpoint of its outer children
* - `init` auto-branch: deep all-leaf branches hang beside the trunk once the
* standard layout reaches 4+ rows (see branchOf)
* - hang trunk drops from the hidden rootConnector (left 20% of the box, so
* x = left + 0.1w); hanging boxes start at left + 0.25w (PowerPoint measured)
* - the whole unit-space layout scales uniformly into the frame and centers
* All geometry below is in units of one box width.
*/
export interface HierTreeNode {
texts: string[]
children: HierTreeNode[]
asst?: boolean
hierBranch?: string
spPr?: any
}
export interface HierConstraints {
boxAspect: number
sibSp: number
sp: number
trunkOff: number
hangIndent: number
fontMax: number
}
export interface HierBox {
node: HierTreeNode
x: number
y: number
w: number
h: number
}
export interface HierLine {
x1: number
y1: number
x2: number
y2: number
}
const DEFAULTS: HierConstraints = {
boxAspect: 0.5,
sibSp: 0.21,
sp: 0.21,
trunkOff: 0.1,
hangIndent: 0.25,
fontMax: 65,
}
/** Pull the factors this engine consumes out of the layout part's constraint lists. */
export function parseHierConstraints(layoutXml: string | undefined): HierConstraints {
const cons = { ...DEFAULTS }
if (!layoutXml) return cons
const fact = (re: RegExp): number | undefined => {
const m = re.exec(layoutXml)
if (!m) return undefined
const v = parseFloat(m[1]!)
return Number.isFinite(v) && v > 0 ? v : undefined
}
cons.boxAspect =
fact(
/<dgm:constr type="h" for="des" forName="rootComposite1?"[^>]*refForName="rootComposite1?"[^>]*fact="([\d.]+)"/,
) ?? cons.boxAspect
cons.sibSp =
fact(/<dgm:constr type="sibSp"[^>]*refForName="rootComposite1?"[^>]*fact="([\d.]+)"/) ??
cons.sibSp
cons.sp =
fact(/<dgm:constr type="sp" for="des" forName="hierRoot1"[^>]*fact="([\d.]+)"/) ?? cons.sp
const connW = fact(/<dgm:constr type="w" for="ch" forName="rootConnector1?"[^>]*fact="([\d.]+)"/)
if (connW != null) cons.trunkOff = connW / 2
const fsz = /<dgm:constr type="primFontSz"[^>]*\bval="([\d.]+)"/.exec(layoutXml)
if (fsz) cons.fontMax = parseFloat(fsz[1]!) || cons.fontMax
return cons
}
interface Sub {
rows: number
/** per-row x extents relative to this subtree's root box center */
l: number[]
r: number[]
boxes: Array<{ node: HierTreeNode; cx: number; row: number }>
lines: HierLine[]
}
const isLeafAsst = (c: HierTreeNode) => !!c.asst && !c.children.length
const kidsOf = (n: HierTreeNode) => n.children.filter((c) => !isLeafAsst(c))
const asstsOf = (n: HierTreeNode) => n.children.filter(isLeafAsst)
type Branch = 'std' | 'hangR' | 'hangL'
/** Whole-tree row count with every branch laid out standard (incl. assistant rows). */
function stdRowsOf(node: HierTreeNode): number {
const kids = kidsOf(node)
const asstRows = asstsOf(node).length ? 1 : 0
return kids.length ? 1 + asstRows + Math.max(...kids.map(stdRowsOf)) : 1 + asstRows
}
/**
* Branch style for a node's children. Explicit hierBranch (from the node's
* presentation point) wins. `init` means the algorithm decides; PowerPoint
* measured (smartart-org-chart2 hangs its depth-3 leaves, smartart-recursion —
* same depth, one row shorter — keeps everything standard): only charts whose
* standard layout reaches 4+ rows hang their deep all-leaf branches, never at
* the root row.
*/
function branchOf(
node: HierTreeNode,
depth: number,
kids: HierTreeNode[],
stdRows: number,
): Branch {
if (!kids.length) return 'std'
const allLeaves = node.children.every((c) => !c.children.length)
const hb = node.hierBranch
if (hb === 'l') return 'hangL'
if (hb === 'r' || hb === 'hang') return 'hangR'
if (hb === 'std') return 'std'
return stdRows >= 4 && depth >= 2 && kids.length >= 2 && allLeaves ? 'hangR' : 'std'
}
function shiftSub(sub: Sub, dx: number, dRow: number, into: Sub, dy: number) {
for (let i = 0; i < sub.rows; i++) {
const row = dRow + i
const sl = sub.l[i]! + dx
const sr = sub.r[i]! + dx
into.l[row] = into.l[row] == null ? sl : Math.min(into.l[row]!, sl)
into.r[row] = into.r[row] == null ? sr : Math.max(into.r[row]!, sr)
}
for (const b of sub.boxes) into.boxes.push({ node: b.node, cx: b.cx + dx, row: b.row + dRow })
for (const ln of sub.lines)
into.lines.push({ x1: ln.x1 + dx, y1: ln.y1 + dy, x2: ln.x2 + dx, y2: ln.y2 + dy })
into.rows = Math.max(into.rows, dRow + sub.rows)
}
export function layoutHierTree(
roots: HierTreeNode[],
cons: HierConstraints,
frameCx: number,
frameCy: number,
): {
boxes: HierBox[]
lines: Array<{ x: number; y: number; cx: number; cy: number }>
boxW: number
} | null {
if (!roots.length) return null
const bh = cons.boxAspect
const pitch = bh + cons.sp
const rowTop = (row: number) => row * pitch
const stdRows = Math.max(...roots.map(stdRowsOf))
const layout = (node: HierTreeNode, depth: number): Sub => {
const kids = kidsOf(node)
const assts = asstsOf(node)
const out: Sub = { rows: 1, l: [-0.5], r: [0.5], boxes: [{ node, cx: 0, row: 0 }], lines: [] }
if (!kids.length && !assts.length) return out
const branch = branchOf(node, depth, kids, stdRows)
const mir = branch === 'hangL' ? -1 : 1
const trunkX = branch === 'std' ? 0 : mir * (cons.trunkOff - 0.5)
const childRow0 = 1 + (assts.length ? 1 : 0)
if (assts.length) {
// Leaf assistants: own row between the parent and its children, tucked
// beside the trunk with a sp/2 elbow (PowerPoint measured)
const asstMidY = rowTop(1) + bh / 2
assts.forEach((a, j) => {
const right = trunkX - cons.sp / 2 - j * (1 + cons.sibSp)
out.boxes.push({ node: a, cx: right - 0.5, row: 1 })
out.lines.push({ x1: right, y1: asstMidY, x2: trunkX, y2: asstMidY })
out.l[1] = Math.min(out.l[1] ?? Infinity, right - 1)
out.r[1] = Math.max(out.r[1] ?? -Infinity, trunkX)
})
out.rows = 2
}
if (!kids.length) {
// assistant-only: trunk still drops to the assistant elbow
out.lines.push({ x1: trunkX, y1: bh, x2: trunkX, y2: rowTop(1) + bh / 2 })
return out
}
const subs = kids.map((k) => layout(k, depth + 1))
if (branch === 'std') {
// Contour packing: each subtree shifts right until every shared row keeps
// a sibSp gap; the parent centers on its first/last child box centers
const merged: { l: number[]; r: number[] } = { l: [], r: [] }
const offs: number[] = []
for (const sub of subs) {
let dx = 0
if (offs.length) {
dx = -Infinity
for (let i = 0; i < sub.rows; i++)
if (merged.r[i] != null) dx = Math.max(dx, merged.r[i]! + cons.sibSp - sub.l[i]!)
if (!Number.isFinite(dx)) dx = merged.r[0]! + cons.sibSp - sub.l[0]!
}
offs.push(dx)
for (let i = 0; i < sub.rows; i++) {
merged.l[i] =
merged.l[i] == null ? sub.l[i]! + dx : Math.min(merged.l[i]!, sub.l[i]! + dx)
merged.r[i] =
merged.r[i] == null ? sub.r[i]! + dx : Math.max(merged.r[i]!, sub.r[i]! + dx)
}
}
const mid = (offs[0]! + offs[offs.length - 1]!) / 2
const busY = rowTop(childRow0) - cons.sp / 2
out.lines.push({ x1: trunkX, y1: bh, x2: trunkX, y2: busY })
for (let i = 0; i < subs.length; i++) {
const cx = offs[i]! - mid
out.lines.push({ x1: trunkX, y1: busY, x2: cx, y2: busY })
out.lines.push({ x1: cx, y1: busY, x2: cx, y2: rowTop(childRow0) })
shiftSub(subs[i]!, cx, childRow0, out, rowTop(childRow0))
}
} else {
// Hanging: children stack below the trunk, boxes starting at parent-left
// + hangIndent (mirrored for hangL); each child may itself be a subtree
let row = childRow0
let lastMidY = bh
for (const sub of subs) {
const cx = mir * (cons.hangIndent - 0.5 + 0.5)
const midY = rowTop(row) + bh / 2
out.lines.push({ x1: trunkX, y1: midY, x2: cx - mir * 0.5, y2: midY })
shiftSub(sub, cx, row, out, rowTop(row))
lastMidY = midY
row += sub.rows
}
out.lines.push({ x1: trunkX, y1: bh, x2: trunkX, y2: lastMidY })
}
return out
}
// Top level (hierChild1): root subtrees pack like siblings
const top: Sub = { rows: 0, l: [], r: [], boxes: [], lines: [] }
const merged: { l: number[]; r: number[] } = { l: [], r: [] }
let placed = 0
for (const r of roots) {
const sub = layout(r, 1)
let dx = 0
if (placed) {
dx = -Infinity
for (let i = 0; i < sub.rows; i++)
if (merged.r[i] != null) dx = Math.max(dx, merged.r[i]! + cons.sibSp - sub.l[i]!)
if (!Number.isFinite(dx)) dx = 0
}
for (let i = 0; i < sub.rows; i++) {
merged.l[i] = merged.l[i] == null ? sub.l[i]! + dx : Math.min(merged.l[i]!, sub.l[i]! + dx)
merged.r[i] = merged.r[i] == null ? sub.r[i]! + dx : Math.max(merged.r[i]!, sub.r[i]! + dx)
}
shiftSub(sub, dx, 0, top, 0)
placed++
}
let minX = Infinity
let maxX = -Infinity
for (let i = 0; i < top.rows; i++) {
if (top.l[i] != null) minX = Math.min(minX, top.l[i]!)
if (top.r[i] != null) maxX = Math.max(maxX, top.r[i]!)
}
for (const ln of top.lines) {
minX = Math.min(minX, ln.x1, ln.x2)
maxX = Math.max(maxX, ln.x1, ln.x2)
}
const unitW = maxX - minX
const unitH = top.rows * bh + (top.rows - 1) * cons.sp
if (!(unitW > 0) || !(unitH > 0)) return null
const scale = Math.min(frameCx / unitW, frameCy / unitH)
const offX = (frameCx - unitW * scale) / 2 - minX * scale
const offY = (frameCy - unitH * scale) / 2
const boxes: HierBox[] = top.boxes.map((b) => ({
node: b.node,
x: offX + (b.cx - 0.5) * scale,
y: offY + rowTop(b.row) * scale,
w: scale,
h: bh * scale,
}))
const lines = top.lines.map((ln) => ({
x: offX + Math.min(ln.x1, ln.x2) * scale,
y: offY + Math.min(ln.y1, ln.y2) * scale,
cx: Math.abs(ln.x2 - ln.x1) * scale,
cy: Math.abs(ln.y2 - ln.y1) * scale,
}))
return { boxes, lines, boxW: scale }
}
+37 -10
View File
@@ -827,30 +827,51 @@ export interface GradientFillPatch {
stops: Array<{ pos: number; color: string }>
/** 1/60000 degree (for linear) */
angle?: number
/** Radial (circle path, center outward) */
/** Radial (alias for path: 'circle') */
radial?: boolean
/** <a:path path> kind (PPT: radial/rectangular/path); linear when absent */
path?: 'circle' | 'rect' | 'shape'
/** <a:fillToRect> focus insets as fractions (default: centered 0.5 each) */
fillTo?: { l: number; t: number; r: number; b: number }
}
type FillPatch = 'none' | string | GradientFillPatch | { rawFillXml: string }
function gsLstXml(stops: GradientFillPatch['stops']): string {
// srgbClrXml keeps an #RRGGBBAA stop's alpha as <a:alpha>
return `<a:gsLst>${stops
.map(
(s) =>
`<a:gs pos="${Math.round(Math.max(0, Math.min(1, s.pos)) * 100000)}"><a:srgbClr val="${hex6(s.color)}"/></a:gs>`,
`<a:gs pos="${Math.round(Math.max(0, Math.min(1, s.pos)) * 100000)}">${srgbClrXml(s.color)}</a:gs>`,
)
.join('')}</a:gsLst>`
}
const RADIAL_PATH_XML =
'<a:path path="circle"><a:fillToRect l="50000" t="50000" r="50000" b="50000"/></a:path>'
/** Path gradient (circle/rect/shape) focused on fillTo (default: centered) */
function gradPathXml(
kind: 'circle' | 'rect' | 'shape',
fillTo?: { l: number; t: number; r: number; b: number },
): string {
const pct = (v: number) => Math.round(v * 100000)
const ftr = fillTo ?? { l: 0.5, t: 0.5, r: 0.5, b: 0.5 }
return `<a:path path="${kind}"><a:fillToRect l="${pct(ftr.l)}" t="${pct(ftr.t)}" r="${pct(ftr.r)}" b="${pct(ftr.b)}"/></a:path>`
}
/** Requested path kind of a gradient patch (radial is a legacy alias for circle). */
function gradPathKind(patch: GradientFillPatch): 'circle' | 'rect' | 'shape' | undefined {
return patch.path ?? (patch.radial ? 'circle' : undefined)
}
function buildFillXml(fill: FillPatch): string {
if (typeof fill === 'object' && 'rawFillXml' in fill) return fill.rawFillXml
if (typeof fill === 'object')
if (typeof fill === 'object') {
const kind = gradPathKind(fill)
return `<a:gradFill rotWithShape="1">${gsLstXml(fill.stops)}${
fill.radial ? RADIAL_PATH_XML : `<a:lin ang="${Math.round(fill.angle ?? 0)}" scaled="1"/>`
kind
? gradPathXml(kind, fill.fillTo)
: `<a:lin ang="${Math.round(fill.angle ?? 0)}" scaled="1"/>`
}</a:gradFill>`
}
if (fill === 'none') return '<a:noFill/>'
return `<a:solidFill>${srgbClrXml(fill)}</a:solidFill>`
}
@@ -895,9 +916,14 @@ function patchGradFillXml(gradXml: string, patch: GradientFillPatch): string {
gsIdx = parts.length
parts.push(gsLstXml(patch.stops))
} else if (c.name === 'a:lin' || c.name === 'a:path') {
if (patch.radial) {
const kind = gradPathKind(patch)
if (kind) {
if (c.name === 'a:path') {
parts.push(seg) // keep the original path (off-center fillToRect etc.)
const existingKind = /path="([^"]*)"/.exec(seg)?.[1]
// The same (or legacy radial's unspecified) path kind keeps the original node
// (off-center fillToRect etc.); an explicit kind change or focus change replaces it.
const keep = patch.path ? existingKind === patch.path && !patch.fillTo : !patch.fillTo
parts.push(keep ? seg : gradPathXml(patch.path ?? kind, patch.fillTo))
hasShade = true
}
} else if (c.name === 'a:lin') {
@@ -911,8 +937,9 @@ function patchGradFillXml(gradXml: string, patch: GradientFillPatch): string {
}
if (gsIdx < 0) return buildFillXml(patch)
if (!hasShade) {
const shade = patch.radial
? RADIAL_PATH_XML
const kind = gradPathKind(patch)
const shade = kind
? gradPathXml(kind, patch.fillTo)
: `<a:lin ang="${Math.round(patch.angle ?? 0)}" scaled="1"/>`
parts.splice(gsIdx + 1, 0, shade) // in the lin/path sequence it immediately follows gsLst
}
+28 -15
View File
@@ -13,18 +13,16 @@ import type { GroupElement, Slide } from './types'
import { escapeXmlAttr } from './xml-utils'
import { sliceGroupChildXmls } from './parse'
import { relsPathFor, resolveTarget } from './zip'
import { materializeSlide, patchedElementXml, type OpenedPptx } from './index'
import { cleanupSupersededSlideResources } from './resource-cleanup'
import { materializeSlide, patchedElementXml, patchSlideXml, type OpenedPptx } from './index'
const HYPERLINK_REL_TYPE =
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink'
const SLIDE_REL_TYPE =
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide'
const SLIDE_REL_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide'
const SLDJUMP_ACTION = 'ppaction://hlinksldjump'
const R_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
export type LinkTarget =
| { kind: 'url'; url: string }
| { kind: 'slide'; slideIndex: number }
export type LinkTarget = { kind: 'url'; url: string } | { kind: 'slide'; slideIndex: number }
const EMPTY_RELS =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>'
@@ -45,7 +43,10 @@ function appendRel(
const rid = `rId${maxRid + 1}`
const mode = external ? ' TargetMode="External"' : ''
const relXml = `<Relationship Id="${rid}" Type="${type}" Target="${escapeXmlAttr(target)}"${mode}/>`
archive.entries.set(relsPath, Buffer.from(rels.replace('</Relationships>', `${relXml}</Relationships>`), 'utf8'))
archive.entries.set(
relsPath,
Buffer.from(rels.replace('</Relationships>', `${relXml}</Relationships>`), 'utf8'),
)
return rid
}
@@ -55,9 +56,9 @@ function stripHlink(xml: string): string {
}
/**
* Set/clear an element hyperlink. target=null clears it (the relationship is left
* orphaned, which is harmless). On success returns the materialized new slide model
* (all element ids refreshed); on failure returns null.
* Set/clear an element hyperlink. Relationships no longer used by any live slide
* XML are pruned after the fragment changes. On success returns the materialized
* new slide model (all element ids refreshed); on failure returns null.
*/
export function setElementLink(
opened: OpenedPptx,
@@ -70,6 +71,7 @@ export function setElementLink(
const el = slide.elements.find((e) => e.id === elementId)
if (!el) return null
const previousXml = patchSlideXml(slide)
let xml = stripHlink(patchedElementXml(el))
if (target) {
@@ -104,6 +106,7 @@ export function setElementLink(
// Post-surgery fragment is the sole truth: clear text dirty so patches don't overwrite; structural rebuild persists it
el.dirty = false
slide.structureDirty = true
cleanupSupersededSlideResources(opened, slide, previousXml, patchSlideXml(slide))
return materializeSlide(opened, slideIndex)
}
@@ -122,13 +125,16 @@ export function encodeRunLink(target: LinkTarget): string {
/**
* Allocate slide-rels relationships for runs whose hyperlink was set this session
* (hyperlink present, hyperlinkRId absent — the edit path clears the rId on change).
* Cleared links just lose their rId; the old relationship is left orphaned like
* setElementLink does. Returns whether anything was allocated.
* The caller reconciles the before/after slide XML after its text patch so cleared
* or replaced relationship ids can be removed safely. Returns whether anything
* was allocated.
*/
export function ensureRunLinkRels(
opened: OpenedPptx,
slideIndex: number,
paragraphs: Array<{ runs: Array<{ hyperlink?: string; hyperlinkRId?: string; hyperlinkAction?: string }> }>,
paragraphs: Array<{
runs: Array<{ hyperlink?: string; hyperlinkRId?: string; hyperlinkAction?: string }>
}>,
): boolean {
const slide = opened.deck.slides[slideIndex]
if (!slide) return false
@@ -144,7 +150,13 @@ export function ensureRunLinkRels(
} else {
const dst = opened.deck.slides[target.slideIndex]
if (!dst) continue
run.hyperlinkRId = appendRel(opened, slide, SLIDE_REL_TYPE, dst.path.split('/').pop()!, false)
run.hyperlinkRId = appendRel(
opened,
slide,
SLIDE_REL_TYPE,
dst.path.split('/').pop()!,
false,
)
run.hyperlinkAction = SLDJUMP_ACTION
}
changed = true
@@ -164,7 +176,8 @@ export function getRunLinks(
): Array<{ elementId: string; paraIndex: number; runIndex: number; target: LinkTarget }> {
const slide = opened.deck.slides[slideIndex]
if (!slide) return []
const out: Array<{ elementId: string; paraIndex: number; runIndex: number; target: LinkTarget }> = []
const out: Array<{ elementId: string; paraIndex: number; runIndex: number; target: LinkTarget }> =
[]
const rels = opened.archive.readRels(slide.path)
const resolve = (rid: string): LinkTarget | null => {
const rel = rels.get(rid)
+195 -35
View File
@@ -71,8 +71,11 @@ import {
type SlideBundle,
} from './slide-transfer'
import { moveSlide } from './sections'
import { cleanupSupersededSlideResources, removePartWithOwnedResources } from './resource-cleanup'
export * from './types'
export { cleanupSupersededSlideResources }
export type { ResourceCleanupStats } from './resource-cleanup'
export {
animClassOf,
buildTimingXml,
@@ -312,6 +315,7 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
const chartXmls = new Map<string, string>()
const chartMediaRels = new Map<string, Map<string, string>>()
const chartUserShapes = new Map<string, string>()
const chartStyleRels = new Set<string>()
const avRels = new Map<string, { target: string; external?: boolean }>()
const diagramDrawings = new Map<string, string>()
const diagramDatas = new Map<string, string>()
@@ -343,6 +347,7 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
const usXml = archive.readText(resolveTarget(target, sub.target))
if (usXml) chartUserShapes.set(rel.id, usXml)
}
if (sub.type.endsWith('/chartStyle')) chartStyleRels.add(rel.id)
}
}
} else if (/\/(?:video|audio|media)$/.test(rel.type)) {
@@ -400,6 +405,7 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
ctx.chartXmls = chartXmls
if (chartMediaRels.size) ctx.chartMediaRels = chartMediaRels
if (chartUserShapes.size) ctx.chartUserShapes = chartUserShapes
if (chartStyleRels.size) ctx.chartStyleRels = chartStyleRels
if (hlinkRels.size) ctx.hlinkRels = hlinkRels
if (avRels.size) ctx.avRels = avRels
if (diagramDrawings.size) ctx.diagramDrawings = diagramDrawings
@@ -734,7 +740,8 @@ export function patchedElementXml(el: SlideElement): string {
xml = patchElementFill(xml, {
stops: fill.stops,
...(fill.angle != null ? { angle: fill.angle } : {}),
...(fill.path ? { radial: true } : {}),
...(fill.path ? { path: fill.path } : {}),
...(fill.path && fill.fillTo ? { fillTo: fill.fillTo } : {}),
})
}
}
@@ -758,7 +765,12 @@ export function patchedElementXml(el: SlideElement): string {
* 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 {
export function setSlideBackground(
opened: OpenedPptx,
slide: Slide,
fill: string | GradientFillPatch,
): void {
const previousXml = patchSlideXml(slide)
slide.bodyPrefix = patchSlideBackgroundXml(slide.bodyPrefix, fill)
slide.background =
typeof fill === 'string'
@@ -770,6 +782,7 @@ export function setSlideBackground(slide: Slide, fill: string | GradientFillPatc
}
slide.bgOwn = true
slide.structureDirty = true
cleanupSupersededSlideResources(opened, slide, previousXml, patchSlideXml(slide))
}
/**
@@ -796,6 +809,7 @@ export function setSlideBackgroundImage(
rid = imageRelFor(opened.archive, slide, mediaPath)
if (!rid) return null
}
const previousXml = patchSlideXml(slide)
slide.bodyPrefix = patchSlideBackgroundXml(slide.bodyPrefix, {
imageRid: rid,
...(tile ? { tile: true } : {}),
@@ -803,6 +817,7 @@ export function setSlideBackgroundImage(
slide.background = { type: 'image', mediaRef: mediaPath, mode: tile ? 'tile' : 'stretch' }
slide.bgOwn = true
slide.structureDirty = true
cleanupSupersededSlideResources(opened, slide, previousXml, patchSlideXml(slide))
return mediaPath
}
@@ -834,6 +849,7 @@ function imageRelFor(archive: PackageArchive, slide: Slide, mediaPath: string):
* layout/master definition (recomputed here so rendering updates without a reopen).
*/
export function resetSlideBackground(opened: OpenedPptx, slide: Slide): void {
const previousXml = patchSlideXml(slide)
slide.bodyPrefix = removeSlideBackgroundXml(slide.bodyPrefix)
delete slide.bgOwn
slide.structureDirty = true
@@ -855,6 +871,7 @@ export function resetSlideBackground(opened: OpenedPptx, slide: Slide): void {
: undefined)
if (inherited) slide.background = inherited
else delete slide.background
cleanupSupersededSlideResources(opened, slide, previousXml, patchSlideXml(slide))
}
/**
@@ -935,6 +952,41 @@ export function editPictureSrcRect(
return true
}
/**
* Change a shape's preset geometry ("Change Shape"): replace <a:prstGeom> (or
* <a:custGeom>) with the new preset and a fresh <a:avLst/>, keeping transform,
* fill, outline, and text. Byte surgery baked directly into originalXml.
*/
export function setShapePresetGeometry(slide: Slide, elementId: string, prst: string): boolean {
if (!/^[A-Za-z0-9]+$/.test(prst)) return false
const el = slide.elements.find((e) => e.id === elementId)
if (!el || (el.type !== 'text' && el.type !== 'shape')) return false
let xml = patchedElementXml(el)
const geomXml = `<a:prstGeom prst="${prst}"><a:avLst/></a:prstGeom>`
const existing =
/<a:prstGeom\b[^>]*\/>|<a:prstGeom\b[\s\S]*?<\/a:prstGeom>|<a:custGeom\b[\s\S]*?<\/a:custGeom>/.exec(
xml,
)
if (existing) {
xml = xml.slice(0, existing.index) + geomXml + xml.slice(existing.index + existing[0].length)
} else {
// No explicit geometry (bare text boxes): insert after </a:xfrm> inside spPr
const xfrmClose = /<\/a:xfrm>/.exec(xml)
if (!xfrmClose) return false
const at = xfrmClose.index + xfrmClose[0].length
xml = xml.slice(0, at) + geomXml + xml.slice(at)
}
el.dirty = el.dirtyTransform = el.dirtyFill = el.dirtyStroke = false
el.dirtyPPr = undefined
el.anchor.originalXml = xml
const shape = el as TextElement
shape.presetGeometry = prst
delete shape.adjust
delete shape.customGeometry
slide.structureDirty = true
return true
}
/**
* Text-box vertical alignment (bodyPr anchor: t/ctr/b). Byte surgery baked directly into originalXml.
*/
@@ -963,29 +1015,139 @@ export function setElementTextAnchor(
}
/**
* Shape image fill: after landing the image in the package (media + rels), the
* spPr fill node is replaced with a blipFill, byte surgery baked directly into
* originalXml. Returns the mediaPath (for render-layer decoding), null on failure.
* Shape fill (top-level or one-level group child). The XML patch is baked into
* the owning fragment so a dropped picture fill can immediately release its
* obsolete relationship and unshared media.
*/
export function setElementFill(
opened: OpenedPptx,
slide: Slide,
elementId: string,
fill: string | GradientFillPatch,
opts: { groupId?: string } = {},
): boolean {
let grp: GroupElement | undefined
let child: SlideElement | undefined
let el: SlideElement | undefined
if (opts.groupId) {
const found = findGroupChild(slide, opts.groupId, elementId)
if (
!found ||
(found.child.type !== 'text' && found.child.type !== 'shape') ||
!found.child.nvId
)
return false
;({ grp, child } = found)
} else {
el = slide.elements.find((candidate) => candidate.id === elementId)
if (!el || (el.type !== 'text' && el.type !== 'shape')) return false
}
const model =
typeof fill === 'string'
? fill === 'none'
? { type: 'none' as const }
: { type: 'solid' as const, color: fill }
: (() => {
const path = fill.path ?? (fill.radial ? ('circle' as const) : undefined)
return {
type: 'gradient' as const,
stops: fill.stops,
...(fill.angle != null ? { angle: fill.angle } : {}),
...(path ? { path } : {}),
...(path && fill.fillTo ? { fillTo: fill.fillTo } : {}),
}
})()
const previousXml = patchSlideXml(slide)
if (grp && child) {
if (!patchGroupChildXml(grp, child, (xml) => patchElementFill(xml, fill))) return false
;(child as TextElement).fill = model
} else if (el) {
el.anchor.originalXml = patchElementFill(patchedElementXml(el), fill)
;(el as TextElement).fill = model
el.dirty = el.dirtyTransform = el.dirtyFill = el.dirtyStroke = false
el.dirtyPPr = undefined
}
slide.structureDirty = true
cleanupSupersededSlideResources(opened, slide, previousXml, patchSlideXml(slide))
return true
}
/**
* Shape picture/texture fill (top-level or one-level group child): lands the
* image in the package (media + rels), or reuses an already-landed media path
* (applying one pick to many shapes only adds rels), then replaces the spPr
* fill node with a blipFill, byte surgery baked directly into originalXml.
* tile repeats the image at natural size (texture), stretch maps it onto the
* bounds. Returns the mediaPath (render-layer decoding / reuse), null on failure.
*/
export function setElementImageFill(
opened: OpenedPptx,
slide: Slide,
elementId: string,
bytes: Uint8Array,
ext: string,
source: { bytes: Uint8Array; ext: string } | { mediaPath: string },
opts: { tile?: boolean; groupId?: string } = {},
): string | null {
const el = slide.elements.find((e) => e.id === elementId)
if (!el || (el.type !== 'text' && el.type !== 'shape')) return null
const added = addImageMediaAndRel(opened, slide, bytes, ext)
if (!added) return null
const rawFillXml = `<a:blipFill rotWithShape="1"><a:blip r:embed="${added.rid}"/><a:stretch><a:fillRect/></a:stretch></a:blipFill>`
const xml = patchElementFill(patchedElementXml(el), { rawFillXml })
el.dirty = el.dirtyTransform = el.dirtyFill = el.dirtyStroke = false
el.dirtyPPr = undefined
el.anchor.originalXml = xml
;(el as TextElement).fill = { type: 'image', mediaRef: added.mediaPath, mode: 'stretch' }
// Resolve the target before touching the package: a failed lookup must not
// leave an orphaned media part behind (multi-target fills would grow the
// archive on every failed attempt).
let grp: GroupElement | undefined
let child: SlideElement | undefined
let el: SlideElement | undefined
if (opts.groupId) {
const found = findGroupChild(slide, opts.groupId, elementId)
if (
!found ||
(found.child.type !== 'text' && found.child.type !== 'shape') ||
!found.child.nvId
)
return null
;({ grp, child } = found)
} else {
el = slide.elements.find((e) => e.id === elementId)
if (!el || (el.type !== 'text' && el.type !== 'shape')) return null
}
const previousXml = patchSlideXml(slide)
let rid: string
let mediaPath: string
if ('bytes' in source) {
const added = addImageMediaAndRel(opened, slide, source.bytes, source.ext)
if (!added) return null
;({ rid, mediaPath } = added)
} else {
mediaPath = source.mediaPath
if (!opened.archive.entries.has(mediaPath)) return null
const existing = imageRelFor(opened.archive, slide, mediaPath)
if (!existing) return null
rid = existing
}
const rawFillXml =
`<a:blipFill rotWithShape="1"><a:blip r:embed="${rid}"/>` +
(opts.tile
? '<a:tile tx="0" ty="0" sx="100000" sy="100000" flip="none" algn="tl"/>'
: '<a:stretch><a:fillRect/></a:stretch>') +
'</a:blipFill>'
const model = {
type: 'image' as const,
mediaRef: mediaPath,
mode: opts.tile ? ('tile' as const) : ('stretch' as const),
// mirror what parse restores from the <a:tile> node, so the pre-save
// render already tiles at the natural (zoom-scaled) size
...(opts.tile ? { tile: { tx: 0, ty: 0, sx: 1, sy: 1, algn: 'tl' } } : {}),
}
if (grp && child) {
if (!patchGroupChildXml(grp, child, (xml) => patchElementFill(xml, { rawFillXml }))) return null
;(child as TextElement).fill = model
} else if (el) {
const xml = patchElementFill(patchedElementXml(el), { rawFillXml })
el.dirty = el.dirtyTransform = el.dirtyFill = el.dirtyStroke = false
el.dirtyPPr = undefined
el.anchor.originalXml = xml
;(el as TextElement).fill = model
}
slide.structureDirty = true
return added.mediaPath
cleanupSupersededSlideResources(opened, slide, previousXml, patchSlideXml(slide))
return mediaPath
}
/**
@@ -1042,6 +1204,7 @@ export function replacePictureBytes(
let xml = patchedElementXml(el)
const blip = /<a:blip\b[^>]*\/?>/.exec(xml)
if (!blip) return false
const previousXml = patchSlideXml(slide)
const added = addImageMediaAndRel(opened, slide, bytes, ext)
if (!added) return false
let tag = blip[0]
@@ -1069,6 +1232,7 @@ export function replacePictureBytes(
el.dirtyPPr = undefined
el.anchor.originalXml = xml
slide.structureDirty = true
cleanupSupersededSlideResources(opened, slide, previousXml, patchSlideXml(slide))
return true
}
@@ -1449,17 +1613,7 @@ export function deleteSlide(opened: OpenedPptx, index: number): boolean {
archive.entries.set(presRelsPath, Buffer.from(presRels.replace(relTag, ''), 'utf8'))
}
const ctPath = '[Content_Types].xml'
const ct = archive.readText(ctPath)
if (ct) {
const override = new RegExp(
`<Override PartName="/${slide.path.replace(/[.\\/]/g, '\\$&')}"[^>]*/>`,
).exec(ct)?.[0]
if (override) archive.entries.set(ctPath, Buffer.from(ct.replace(override, ''), 'utf8'))
}
archive.entries.delete(slide.path)
archive.entries.delete(relsPathFor(slide.path))
removePartWithOwnedResources(archive, slide.path)
deck.slides.splice(index, 1)
return true
}
@@ -3474,12 +3628,18 @@ export function editGroupChildFill(
? fill === 'none'
? { type: 'none' }
: { type: 'solid', color: fill }
: {
type: 'gradient',
stops: fill.stops,
...(fill.angle != null ? { angle: fill.angle } : {}),
...(fill.radial ? { path: 'circle' as const } : {}),
}
: (() => {
// Mirror the XML patch onto the model (radial is the legacy alias for path: circle),
// so the canvas re-render shows the right shading without a reload
const path = fill.path ?? (fill.radial ? ('circle' as const) : undefined)
return {
type: 'gradient' as const,
stops: fill.stops,
...(fill.angle != null ? { angle: fill.angle } : {}),
...(path ? { path } : {}),
...(path && fill.fillTo ? { fillTo: fill.fillTo } : {}),
}
})()
if (!patchGroupChildXml(found!.grp, child, (xml) => patchElementFill(xml, fill))) return false
slide.structureDirty = true
return true
+9 -2
View File
@@ -13,6 +13,7 @@ import { generateParagraphXml, generateXfrmXml } from './generate'
import { escapeXmlAttr } from './xml-utils'
import { relsPathFor } from './zip'
import type { OpenedPptx } from './index'
import { cleanupDeletedElementResources } from './resource-cleanup'
/**
* 'textbox' is a special value (plain text box without prstGeom); anything else is
@@ -323,12 +324,18 @@ export function addPicture(
return el
}
/** Delete by element id; returns whether anything was removed. */
export function deleteElement(slide: Slide, elementId: string): boolean {
/**
* Delete by element id and collect relationships/resources no longer used by any
* retained package part. The OpenedPptx context is required because media may be
* shared by other objects or slides.
*/
export function deleteElement(opened: OpenedPptx, slide: Slide, elementId: string): boolean {
const idx = slide.elements.findIndex((e) => e.id === elementId)
if (idx < 0) return false
const removedXml = slide.elements[idx]!.anchor.originalXml
slide.elements.splice(idx, 1)
slide.structureDirty = true
cleanupDeletedElementResources(opened, slide, removedXml)
return true
}
+488 -147
View File
@@ -6,6 +6,7 @@
* simple shapes; everything else → passthrough.
*/
import { XMLParser } from 'fast-xml-parser'
import { layoutHierTree, parseHierConstraints } from './dgm-hier'
import { scanSlide, type SpElement } from './scan'
import { tableRowGridCols } from './table-grid'
import { type Theme, resolveFontRef, resolveSchemeColor } from './theme'
@@ -126,6 +127,8 @@ export interface ParseContext {
themeMediaRels?: Map<string, string>
/** Chart rId → that chart part's own image rels (for chart background picture fills) */
chartMediaRels?: Map<string, Map<string, string>>
/** Chart rIds whose part has a Microsoft chartStyle companion (modern gray label defaults) */
chartStyleRels?: Set<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) */
@@ -372,6 +375,7 @@ function parseSpShape(
let stroke = parseStroke(spPr, ctx)
let shadow = parseShadow(spPr, ctx)
let glow = parseGlow(spPr, ctx)
const scene3d = parseScene3D(spPr, ctx)
// <a:fillOverlay> holds a second fill element directly (a:gradFill/…), so parseFill reads it like an spPr
const overlayNode = spPr?.['a:effectLst']?.['a:fillOverlay']
const fillOverlay = overlayNode ? parseFill(overlayNode, ctx) : undefined
@@ -452,6 +456,7 @@ function parseSpShape(
...(stroke ? { stroke } : {}),
...(shadow ? { shadow } : {}),
...(glow ? { glow } : {}),
...(scene3d ? { scene3d } : {}),
text,
}
return el
@@ -600,6 +605,39 @@ function parseShadow(spPr: any, ctx: ParseContext): ShadowEffect | undefined {
}
}
/** <a:scene3d> (camera + light rig) and <a:sp3d> (extrusion). Only attached when a camera exists. */
function parseScene3D(spPr: any, ctx: ParseContext): import('./types').Scene3D | undefined {
const s3 = spPr?.['a:scene3d']
const camera = s3?.['a:camera']
const cameraPreset = camera?.['@_prst']
if (!cameraPreset) return undefined
const sp3d = spPr?.['a:sp3d']
const rot = (node: any): { lat: number; lon: number; rev: number } | undefined => {
const r = node?.['a:rot']
if (!r || typeof r !== 'object') return undefined
return { lat: intOr(r['@_lat'], 0), lon: intOr(r['@_lon'], 0), rev: intOr(r['@_rev'], 0) }
}
const rig = s3['a:lightRig']
const extrusionClr = sp3d?.['a:extrusionClr']
const extrusionColor =
extrusionClr && typeof extrusionClr === 'object'
? resolveColorNode(extrusionClr, ctx)
: undefined
const cameraRot = rot(camera)
const lightRot = rot(rig)
return {
cameraPreset,
...(cameraRot ? { cameraRot } : {}),
...(rig?.['@_rig'] ? { lightRig: rig['@_rig'] } : {}),
...(rig?.['@_dir'] ? { lightDir: rig['@_dir'] } : {}),
...(lightRot ? { lightRot } : {}),
...(sp3d?.['@_extrusionH'] != null ? { extrusionEmu: intOr(sp3d['@_extrusionH'], 0) } : {}),
...(sp3d?.['@_z'] != null ? { zEmu: intOr(sp3d['@_z'], 0) } : {}),
...(extrusionColor ? { extrusionColor } : {}),
...(sp3d?.['@_prstMaterial'] ? { material: sp3d['@_prstMaterial'] } : {}),
}
}
/** <a:avLst> adjust values: <a:gd name="adj" fmla="val 50000"/> → { adj: 50000 }. */
function parseAvLst(avLst: any): Record<string, number> | undefined {
const gdRaw = avLst?.['a:gd']
@@ -957,6 +995,7 @@ function graphicFramePassthrough(node: any, anchor: ByteAnchor, ctx: ParseContex
const model = chartXml
? parseChartXml(chartXml, ctx.theme, (spPr) => parseFill(spPr, chartFillCtx))
: null
if (model && ctx.chartStyleRels?.has(String(rid))) model.hasStylePart = true
if (model) {
const usXml = rid ? ctx.chartUserShapes?.get(String(rid)) : undefined
if (usXml) {
@@ -998,9 +1037,18 @@ function graphicFramePassthrough(node: any, anchor: ByteAnchor, ctx: ParseContex
if (drawingXml) {
// Picture-fill rIds inside the drawing resolve against the drawing part's own rels
const drawingRels = dm ? ctx.diagramMediaRels?.get(String(dm)) : undefined
// PowerPoint re-renders SmartArt from data+colors, so the drawing part's cached
// text color can be stale — resolve the truth per modelId from the color part
const csRel = data?.['dgm:relIds']?.['@_r:cs']
const txColors = diagramTextColors(
dm ? ctx.diagramDatas?.get(String(dm)) : undefined,
csRel ? ctx.diagramColors?.get(String(csRel)) : undefined,
ctx,
)
const shapes = parseDiagramDrawing(
drawingXml,
drawingRels ? { ...ctx, mediaRels: drawingRels } : ctx,
txColors,
)
// A single text-less shape is a stub (writers emit just a background rect);
// fall through to the layout fallback instead of drawing one giant block
@@ -1030,6 +1078,7 @@ function graphicFramePassthrough(node: any, anchor: ByteAnchor, ctx: ParseContex
transform.offset.cy,
uniqueId,
colorsXml,
layoutXml,
)
if (shapes.length) el.previewShapes = shapes
}
@@ -1066,7 +1115,43 @@ function graphicFramePassthrough(node: any, anchor: ByteAnchor, ctx: ParseContex
* references). Coordinate system: the diagram canvas (origin 0,0, size ≈
* graphicFrame ext).
*/
function parseDiagramDrawing(drawingXml: string, ctx: ParseContext): SlideElement[] {
/**
* dsp text-color truth: map dsp modelId → diagram-colors styleLbl txFillClrLst color,
* via the data part's presentation points (presStyleLbl). PowerPoint resolves SmartArt
* text from these, ignoring the drawing part's cached (possibly stale) fontRef color.
*/
function diagramTextColors(
dataXml: string | undefined,
colorsXml: string | undefined,
ctx: ParseContext,
): Map<string, string> {
const out = new Map<string, string>()
if (!dataXml || !colorsXml) return out
const lblColor = new Map<string, string>()
for (const m of colorsXml.matchAll(/<dgm:styleLbl name="([^"]+)">([\s\S]*?)<\/dgm:styleLbl>/g)) {
const lst = /<dgm:txFillClrLst[^>]*>([\s\S]*?)<\/dgm:txFillClrLst>/.exec(m[2]!)?.[1]
if (!lst) continue
const cm = /<a:schemeClr val="([^"]+)"|<a:srgbClr val="([^"]+)"/.exec(lst)
if (!cm) continue
const c = cm[1]
? resolveColorNode({ 'a:schemeClr': { '@_val': cm[1] } }, ctx)
: '#' + String(cm[2]).toUpperCase()
if (c) lblColor.set(m[1]!, c)
}
if (!lblColor.size) return out
for (const m of dataXml.matchAll(/<dgm:pt modelId="([^"]+)" type="pres"[\s\S]*?<\/dgm:pt>/g)) {
const lbl = /presStyleLbl="([^"]+)"/.exec(m[0])?.[1]
const c = lbl ? lblColor.get(lbl) : undefined
if (c) out.set(m[1]!, c)
}
return out
}
function parseDiagramDrawing(
drawingXml: string,
ctx: ParseContext,
txColors?: Map<string, string>,
): SlideElement[] {
const xml = drawingXml.replace(/<(\/?)dsp:/g, '<$1p:')
let doc: any
try {
@@ -1079,9 +1164,21 @@ function parseDiagramDrawing(drawingXml: string, ctx: ParseContext): SlideElemen
const spsRaw = spTree['p:sp']
const sps: any[] = Array.isArray(spsRaw) ? spsRaw : spsRaw ? [spsRaw] : []
const out: SlideElement[] = []
for (const sp of sps) {
for (let 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] }
// Text color truth comes from the color part (see diagramTextColors); explicit run
// colors in the txBody still win since the fontRef is only the inherited fallback
const txC = txColors?.get(String(sp['@_modelId'] ?? ''))
if (txC && sp['p:txBody']) {
sp = {
...sp,
'p:style': {
...(sp['p:style'] ?? {}),
'a:fontRef': { '@_idx': 'minor', 'a:srgbClr': { '@_val': txC.replace('#', '') } },
},
}
}
// 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']
@@ -1133,6 +1230,10 @@ interface DgmTreeNode {
texts: string[]
spPr?: any
children: DgmTreeNode[]
/** dgm:pt type="asst": org-chart assistant (own row, hangs left of the trunk) */
asst?: boolean
/** Explicit ST_HierBranchStyle from the presentation point ('hang'/'l'/'r'/'std'; init omitted) */
hierBranch?: string
}
/** Depth-first bullet lines of a node's descendants (lvl 1 = direct child). */
@@ -1179,6 +1280,8 @@ function dgmSp(
stroke?: string
noFill?: boolean
adj?: number
/** Named adjust values (multi-adj presets like downArrow adj1/adj2) */
adjs?: Array<{ name: string; val: number }>
/** xfrm rotation (60000ths of a degree) */
rot?: number
} = {},
@@ -1197,9 +1300,20 @@ function dgmSp(
},
'a:prstGeom': {
'@_prst': opts.prst ?? 'rect',
...(opts.adj != null
? { 'a:avLst': { 'a:gd': { '@_name': 'adj', '@_fmla': 'val ' + Math.round(opts.adj) } } }
: {}),
...(opts.adjs?.length
? {
'a:avLst': {
'a:gd': opts.adjs.map((a) => ({
'@_name': a.name,
'@_fmla': 'val ' + Math.round(a.val),
})),
},
}
: opts.adj != null
? {
'a:avLst': { 'a:gd': { '@_name': 'adj', '@_fmla': 'val ' + Math.round(opts.adj) } },
}
: {}),
},
...fillNode,
...(opts.stroke
@@ -1268,6 +1382,7 @@ export function layoutDiagramFallback(
frameCy: number,
layoutId?: string,
colorsXml?: string,
layoutXml?: string,
): SlideElement[] {
let doc: any
try {
@@ -1285,10 +1400,23 @@ export function layoutDiagramFallback(
// dgm:pt type defaults to 'node'; some writers emit it explicitly
const nodePts = new Map(
pts
.filter((p) => p?.['@_type'] == null || p?.['@_type'] === 'node')
.filter((p) => p?.['@_type'] == null || p?.['@_type'] === 'node' || p?.['@_type'] === 'asst')
.map((p) => [String(p['@_modelId']), p]),
)
// Plain parent-child connections (type absent or parOf), grouped by parent, ordered by srcOrd
// Node → explicit hierBranch (on its presentation point, via presOf): 'hang'/'l'/'r'
// force a hanging branch, 'std' forces side-by-side, 'init' leaves it to the heuristic
const presPts = new Map(
pts.filter((p) => p?.['@_type'] === 'pres').map((p) => [String(p['@_modelId']), p]),
)
const hierBranchOf = new Map<string, string>()
for (const pres of presPts.values()) {
const prSet = pres?.['dgm:prSet']
const hb = prSet?.['dgm:presLayoutVars']?.['dgm:hierBranch']?.['@_val']
const assoc = prSet?.['@_presAssocID']
if (hb && hb !== 'init' && assoc && !hierBranchOf.has(String(assoc)))
hierBranchOf.set(String(assoc), String(hb))
}
const bySrc = new Map<string, any[]>()
for (const c of cxns) {
const t = c?.['@_type']
@@ -1311,6 +1439,8 @@ export function layoutDiagramFallback(
id: d,
texts: collectDgmTexts(pt),
...(pt?.['dgm:spPr']?.['a:solidFill'] ? { spPr: pt['dgm:spPr'] } : {}),
...(pt?.['@_type'] === 'asst' ? { asst: true } : {}),
...(hierBranchOf.has(d) ? { hierBranch: hierBranchOf.get(d) } : {}),
children: build(d),
}
})
@@ -1346,44 +1476,50 @@ export function layoutDiagramFallback(
}
return Math.max(6, s)
}
// Layouts our families still model worse than the neutral placeholder chip
if (layoutId === 'cycle4') return []
const byLayout =
layoutId === 'hList1' || layoutId === 'hList2'
? 'columns'
: layoutId === 'hList3'
? 'tableList'
: layoutId != null && /^pList/.test(layoutId)
? 'pictureList'
: layoutId != null && /^list/.test(layoutId)
? 'boxList'
: layoutId === 'vList5' || (layoutId != null && /^Bracket/.test(layoutId))
? 'sideList'
: layoutId === 'vProcess5'
? 'stepped'
: layoutId != null && /^(vList|vProcess)/.test(layoutId)
? 'stacked'
: layoutId != null && /^bList/.test(layoutId)
? 'cards'
: layoutId != null && /^(process|hProcess|bProcess)/.test(layoutId)
? 'procCards'
: layoutId != null && /^equation/.test(layoutId)
? 'equation'
: layoutId != null && /^pyramid/.test(layoutId)
? 'pyramid'
: layoutId != null && /^Picture/.test(layoutId)
? 'strips'
: layoutId === 'chevron2'
? 'chevronList'
: layoutId != null && /^chevron/.test(layoutId)
? 'chevronRow'
: layoutId != null && /^(cycle[127]|radial)/.test(layoutId)
? 'cycle'
: layoutId != null && /orgchart/i.test(layoutId)
? 'orgChart'
: layoutId != null && /^hierarchy/.test(layoutId)
? 'hierarchy'
: 'blocks'
layoutId === 'cycle4'
? 'cycleMatrix'
: layoutId != null && /^arrow5/.test(layoutId)
? 'arrowRing'
: layoutId != null && /^hProcess3(#|$)/.test(layoutId)
? 'ruleArrow'
: layoutId === 'hList1' || layoutId === 'hList2'
? 'columns'
: layoutId === 'hList3'
? 'tableList'
: layoutId != null && /^pList/.test(layoutId)
? 'pictureList'
: layoutId != null && /^list/.test(layoutId)
? 'boxList'
: layoutId === 'vList5' || (layoutId != null && /^Bracket/.test(layoutId))
? 'sideList'
: layoutId === 'vProcess5'
? 'stepped'
: layoutId != null && /^(vList|vProcess)/.test(layoutId)
? 'stacked'
: layoutId != null && /^bList/.test(layoutId)
? 'cards'
: layoutId != null && /^(process|hProcess|bProcess)/.test(layoutId)
? 'procCards'
: layoutId != null && /^lProcess/.test(layoutId)
? 'colProcess'
: layoutId != null && /^equation/.test(layoutId)
? 'equation'
: layoutId != null && /^pyramid/.test(layoutId)
? 'pyramid'
: layoutId != null && /^Picture/.test(layoutId)
? 'strips'
: layoutId === 'chevron2'
? 'chevronList'
: layoutId != null && /^chevron/.test(layoutId)
? 'chevronRow'
: layoutId != null && /^(cycle[127]|radial)/.test(layoutId)
? 'cycle'
: layoutId != null && /orgchart/i.test(layoutId)
? 'orgChart'
: layoutId != null && /^hierarchy/.test(layoutId)
? 'hierarchy'
: 'blocks'
const family = byLayout === 'blocks' && !hasHierarchy ? 'flatGrid' : byLayout
if (family === 'flatGrid') {
@@ -1467,6 +1603,68 @@ export function layoutDiagramFallback(
)
}
})
} else if (family === 'colProcess') {
// lProcess1-style linear process: one column per top node — a colored header
// block, then each child in its own tinted block, with a small connector dot
// in every gap (all proportions measured against PowerPoint, napierone 0005 p8)
const n = roots.length
const gap = frameCx * 0.045
const cw = (frameCx - gap * (n - 1)) / n
const kMax = Math.max(...roots.map((r) => r.children.length), 1)
// Columns fill ~78% of the frame height, roughly centered (napierone 0005 p8)
const usedCy = frameCy * 0.78
const yTop = (frameCy - usedCy) * 0.55
const bh = usedCy / (1 + 1.48 * kMax) // header ≈ child-block height, gaps 0.48×
const vGap = bh * 0.48
roots.forEach((node, i) => {
const x = i * (cw + gap)
const base = colorOf(node, i)
const baseHex = typeof base === 'string' ? base : undefined
if (!roots.some((r) => r.children.length)) {
// Childless nodes render as the layout's background shape: a large tinted
// rounded panel with dark top-anchored text (lProcess2 bgShp look)
const pw = Math.min(cw, frameCy * 1.5)
const pt = fitSizeW(frameCy * 0.25, pw, node.texts, 22)
sps.push(
dgmSp(
{ x: x + (cw - pw) / 2, y: frameCy * 0.06, cx: pw, cy: frameCy * 0.88 },
baseHex ? dgmTint(baseHex, 0.22) : base,
node.texts.map((tx) => ({ text: tx, lvl: 0, sizePt: pt })),
{ textColor: '#000000', anchor: 't', prst: 'roundRect', adj: 10000 },
),
)
return
}
const t = fitSizeW(bh * 0.9, cw, node.texts, 26)
sps.push(
dgmSp(
{ x, y: yTop, cx: cw, cy: bh },
base,
node.texts.map((tx) => ({ text: tx, lvl: 0, sizePt: t })),
),
)
node.children.forEach((kid, k) => {
const y = yTop + bh + k * (vGap + bh)
const dotD = bh * 0.14
sps.push(
dgmSp(
{ x: x + cw / 2 - dotD / 2, y: y + vGap / 2 - dotD / 2, cx: dotD, cy: dotD },
base,
[],
{ prst: 'ellipse' },
),
)
const kt = fitSizeW(bh * 0.7, cw, kid.texts, 17)
sps.push(
dgmSp(
{ x, y: y + vGap, cx: cw, cy: bh },
baseHex ? dgmTint(baseHex, 0.25) : base,
kid.texts.map((tx) => ({ text: tx, lvl: 0, sizePt: kt })),
{ textColor: '#404040', prst: 'roundRect', adj: 8000 },
),
)
})
})
} else if (family === 'columns') {
// Per top node: colored header (title) + tinted body (descendant bullets);
// column width caps at 0.62 x column height and the group centers (PPT hList look)
@@ -1744,6 +1942,126 @@ export function layoutDiagramFallback(
),
)
})
} else if (family === 'arrowRing') {
// arrow5 (cycle alg, rotPath=alongPath): downArrows on a ring all pointing at the
// center, first at 12 o'clock going clockwise, tails on the ring's outer edge.
// Sizes calibrated against PowerPoint at n=3 (box 209×185 px in a 213px-radius ring)
// and n=16 (62×99): length = R·min(0.98, 4.66/n), aspect widens as the ring crowds.
const n = Math.max(roots.length, 1)
const R = Math.min(frameCx, frameCy) / 2
const bh = R * Math.min(0.98, 4.66 / n)
const aspect = Math.min(1.8, Math.max(0.8, 0.885 + (n - 3) * 0.055))
const bw = bh * aspect
const rc = R - bh / 2
const cxr = frameCx / 2
const cyr = frameCy / 2
const sizePt = Math.max(5, Math.min(20, 2 + (bh / 12700) * 0.08))
roots.forEach((node, i) => {
const ang = -Math.PI / 2 + (i * 2 * Math.PI) / n
const x = cxr + Math.cos(ang) * rc
const y = cyr + Math.sin(ang) * rc
sps.push(
dgmSp(
{ x: x - bw / 2, y: y - bh / 2, cx: bw, cy: bh },
colorOf(node, i),
node.texts.map((tx) => ({ text: tx, lvl: 0, sizePt })),
{
prst: 'downArrow',
// Head shorter than the preset default (measured 29-36% of ss vs 50%)
adjs: [
{ name: 'adj1', val: 50000 },
{ name: 'adj2', val: 32000 },
],
rot: Math.round(((ang * 180) / Math.PI + 90) * 60000),
},
),
)
})
} else if (family === 'cycleMatrix') {
// Cycle Matrix (cycle4): four quadrant wedges around the center, one corner child
// card per quadrant, clockwise from top-left (geometry measured against PowerPoint:
// R = 0.44 x frame height, cross gap ~3% of H, cards 0.333W x 0.316H inset 6.4% x)
const nodes = roots.slice(0, 4)
const cxr = frameCx / 2
const cyr = frameCy / 2
const R = frameCy * 0.44
const gap = frameCy * 0.015
const bw = frameCx * 0.333
const bh = frameCy * 0.316
const bx = frameCx * 0.064
const quads = [
{ a1: 10800000, dx: -1, dy: -1, bxy: { x: bx, y: 0 } },
{ a1: 16200000, dx: 1, dy: -1, bxy: { x: frameCx - bx - bw, y: 0 } },
{ a1: 0, dx: 1, dy: 1, bxy: { x: frameCx - bx - bw, y: frameCy - bh } },
{ a1: 5400000, dx: -1, dy: 1, bxy: { x: bx, y: frameCy - bh } },
]
const labelPt = Math.max(10, Math.min(24, (R / 12700) * 0.115))
// Corner cards first: PowerPoint tucks them behind the wedge circle
nodes.forEach((node, i) => {
const q = quads[i]!
const bullets = dgmBulletLines(node)
const strokeColor = node.spPr
? (resolveColorNode(node.spPr['a:solidFill'], ctx) ?? colors[0]!)
: colors[0]!
sps.push(
dgmSp(
{ x: q.bxy.x, y: q.bxy.y, cx: bw, cy: bh },
'#FFFFFF',
bullets.map((b) => ({
text: b.text,
lvl: b.lvl,
sizePt: Math.max(8, Math.min(12, labelPt * 0.45)),
})),
{
prst: 'roundRect',
adj: 9000,
stroke: strokeColor,
align: 'l',
anchor: 't',
textColor: '#000000',
},
),
)
})
nodes.forEach((node, i) => {
const q = quads[i]!
const fill: string | { spPr: any } = node.spPr ? { spPr: node.spPr } : colors[0]!
const wcx = cxr + q.dx * gap
const wcy = cyr + q.dy * gap
sps.push(
dgmSp({ x: wcx - R, y: wcy - R, cx: 2 * R, cy: 2 * R }, fill, [], {
prst: 'pie',
adjs: [
{ name: 'adj1', val: q.a1 },
{ name: 'adj2', val: q.a1 + 5400000 },
],
}),
)
// Quadrant label sits halfway out along the quadrant diagonal
const lw = R * 0.9
const lh = labelPt * 12700 * 1.6
sps.push(
dgmSp(
{
x: wcx + q.dx * R * 0.5 - lw / 2,
y: wcy + q.dy * R * 0.5 - lh / 2,
cx: lw,
cy: lh,
},
'#FFFFFF',
node.texts.filter(Boolean).map((t) => ({ text: t, lvl: 0, sizePt: labelPt })),
{ noFill: true },
),
)
})
// Center hub: white ring (stand-in for PowerPoint's circular-arrows glyph)
const r0 = frameCy * 0.07
sps.push(
dgmSp({ x: cxr - r0, y: cyr - r0, cx: 2 * r0, cy: 2 * r0 }, '#FFFFFF', [], {
prst: 'donut',
adj: 28000,
}),
)
} else if (family === 'cycle') {
// Nodes on a circle; radial* = big center circle with satellite circles touching it
const central = layoutId != null && /^radial/.test(layoutId)
@@ -1805,88 +2123,35 @@ export function layoutDiagramFallback(
})
}
} else if (family === 'orgChart') {
// Tidy-ish org tree: leaf-count spans, one row per depth
// hierBranch 'init': PowerPoint hangs a branch when all its children are leaves (>=2)
const hangs = (node: DgmTreeNode): boolean =>
node.children.length >= 2 && node.children.every((c) => !c.children.length)
const leaves = (node: DgmTreeNode): number =>
hangs(node) || !node.children.length
? node.children.length
? 1.5
: 1
: node.children.reduce((a, c) => a + leaves(c), 0)
const depthOf = (node: DgmTreeNode): number =>
hangs(node)
? 1 + node.children.length
: node.children.length
? 1 + Math.max(...node.children.map(depthOf))
: 1
const totalLeaves = roots.reduce((a, r) => a + leaves(r), 0)
const depth = Math.max(...roots.map(depthOf))
const rowCy = frameCy / depth
const bh = Math.min(rowCy * 0.66, frameCy * 0.2)
const slotW = frameCx / Math.max(totalLeaves, 1)
const bw = Math.min(slotW * 0.94, frameCx / 5.5)
const lineW = Math.max(frameCx * 0.0012, 9525)
const lineColor = typeof colors[0] === 'string' ? colors[0]! : '#4472C4'
const rowY = (d: number) => d * rowCy + (rowCy - bh) / 2
const vline = (x: number, y1: number, y2: number) =>
sps.push(dgmSp({ x: x - lineW / 2, y: y1, cx: lineW, cy: y2 - y1 }, lineColor, []))
const hline = (x1: number, x2: number, y: number) =>
sps.push(
dgmSp(
{
x: Math.min(x1, x2) - lineW / 2,
y: y - lineW / 2,
cx: Math.abs(x2 - x1) + lineW,
cy: lineW,
},
lineColor,
[],
),
)
const box = (node: DgmTreeNode, cx: number, d: number) =>
sps.push(
dgmSp(
{ x: cx - bw / 2, y: rowY(d), cx: bw, cy: bh },
colorOf(node, 0),
node.texts.map((tx) => ({
text: tx,
lvl: 0,
sizePt: fitSize(bh, Math.max(node.texts.length, 1), 20),
})),
),
)
const place = (node: DgmTreeNode, slot0: number, d: number): number => {
const span = leaves(node)
const cx = (slot0 + span / 2) * slotW
box(node, cx, d)
if (hangs(node)) {
// Hanging branch: children stack in rows below, trunk at the parent's left third
const trunkX = cx - bw * 0.3
vline(trunkX, rowY(d) + bh, rowY(d + node.children.length) + bh / 2)
node.children.forEach((c, j) => {
const cy0 = rowY(d + 1 + j)
const ccx = cx + bw * 0.14
hline(trunkX, ccx - bw / 2, cy0 + bh / 2)
box(c, ccx, d + 1 + j)
})
} else {
let sNext = slot0
for (const c of node.children) {
const cSpan = leaves(c)
const ccx = (sNext + cSpan / 2) * slotW
const midY = (rowY(d) + bh + rowY(d + 1)) / 2
vline(cx, rowY(d) + bh, midY)
hline(cx, ccx, midY)
vline(ccx, midY, rowY(d + 1))
sNext += place(c, sNext, d + 1)
}
}
return span
// Constraint interpreter: factors and branch rules come from the layout part
// (see dgm-hier.ts); connectors render as thin rects like the other families
const cons = parseHierConstraints(layoutXml)
const geo = layoutHierTree(roots, cons, frameCx, frameCy)
if (geo) {
const lineW = Math.max(frameCx * 0.0012, 9525)
const lineColor = typeof colors[0] === 'string' ? colors[0]! : '#4472C4'
// primFontSz op=equ: every node box shares the smallest fitting size
const withText = geo.boxes.filter((b) => b.node.texts.length)
const sizePt = withText.length
? Math.min(...withText.map((b) => fitSizeW(b.h, b.w, b.node.texts, cons.fontMax)))
: cons.fontMax
for (const ln of geo.lines)
sps.push(
dgmSp(
{ x: ln.x - lineW / 2, y: ln.y - lineW / 2, cx: ln.cx + lineW, cy: ln.cy + lineW },
lineColor,
[],
),
)
for (const b of geo.boxes)
sps.push(
dgmSp(
{ x: b.x, y: b.y, cx: b.w, cy: b.h },
colorOf(b.node as DgmTreeNode, 0),
b.node.texts.map((tx) => ({ text: tx, lvl: 0, sizePt })),
),
)
}
let s0 = 0
for (const r of roots) s0 += place(r, s0, 0)
} else if (family === 'cards') {
// bList cards: outlined white card with child bullets, accent footer strip with the parent title
const n = roots.length
@@ -2103,33 +2368,69 @@ export function layoutDiagramFallback(
),
)
})
} else if (family === 'boxList') {
// Vertical Box List: per item a rounded title box upper-left + a light body panel below
const n = roots.length
const gap = frameCy * 0.05
const ih = (frameCy - gap * (n - 1)) / n
} else if (family === 'ruleArrow') {
// hProcess3 (linear rule): one big frame-wide rightArrow, top-node texts spread
// across the shaft (PowerPoint measured: arrow 90% of frame height centered,
// shaft 40% of the arrow box, head ≈ 25% of the width)
const n = Math.max(roots.length, 1)
const ah = frameCy * 0.9
const ay = (frameCy - ah) / 2
const headLen = Math.min(frameCx * 0.255, ah * 0.554)
sps.push(
dgmSp({ x: 0, y: ay, cx: frameCx, cy: ah }, colorOf(roots[0]!, 0), [], {
prst: 'rightArrow',
adjs: [
{ name: 'adj1', val: 40400 },
{ name: 'adj2', val: Math.round((headLen / Math.min(frameCx, ah)) * 100000) },
],
}),
)
const bodyW = frameCx - headLen
const slot = bodyW / n
const shaftH = ah * 0.404
roots.forEach((node, i) => {
const y = i * (ih + gap)
const base = colorOf(node, i)
const baseHex = typeof base === 'string' ? base : undefined
const titleCy = ih * 0.45
sps.push(
dgmSp(
{ x: frameCx * 0.03, y, cx: frameCx * 0.55, cy: titleCy },
{ x: i * slot, y: ay + (ah - shaftH) / 2, cx: slot, cy: shaftH },
'#FFFFFF',
node.texts.map((tx) => ({
text: tx,
lvl: 0,
sizePt: fitSize(shaftH, Math.max(node.texts.length, 1), 26),
bold: true,
})),
{ noFill: true },
),
)
})
} else if (family === 'boxList') {
// Vertical Box List (PowerPoint measured on smartart-linear-rule-vert): per item a
// rounded title pill (69% width, inset 5.3%) over a full-width outlined body panel
// that starts at the pill's vertical middle and runs to just above the next pill
const n = roots.length
const pitch = frameCy / Math.max(n, 1)
roots.forEach((node, i) => {
const y = i * pitch + pitch * 0.04
const base = colorOf(node, i)
const baseHex = typeof base === 'string' ? base : undefined
const titleCy = pitch * 0.7
sps.push(
dgmSp(
{ x: frameCx * 0.053, y, cx: frameCx * 0.692, cy: titleCy },
base,
node.texts.map((tx) => ({
text: tx,
lvl: 0,
sizePt: fitSize(titleCy, Math.max(node.texts.length, 1), 20),
sizePt: fitSize(titleCy, Math.max(node.texts.length, 1) * 2, 14),
})),
{ prst: 'roundRect', align: 'l' },
),
)
const bullets = dgmBulletLines(node)
const bodyCy = ih - titleCy * 0.55
const bodyCy = titleCy * 0.9
sps.push(
dgmSp(
{ x: 0, y: y + titleCy * 0.55, cx: frameCx * 0.72, cy: bodyCy },
{ x: 0, y: y + titleCy * 0.5, cx: frameCx, cy: bodyCy },
base,
bullets.map((l) => ({
text: l.text,
@@ -2416,7 +2717,8 @@ function parseXfrm(xfrm: any): Transform {
/** <a:duotone>: two colors mapping image luminance dark→light (theme texture backgrounds). */
function parseDuotone(blipNode: any, ctx: ParseContext): [string, string] | undefined {
const duoRaw = blipNode?.['a:duotone']
if (!duoRaw) return undefined
// <a:grayscl/>: luminance-only rendering — exactly a black→white duotone ramp
if (!duoRaw) return blipNode?.['a:grayscl'] !== undefined ? ['#000000', '#FFFFFF'] : undefined
const clrs: Array<{ c: string; tag: string }> = []
for (const tag of ['a:schemeClr', 'a:srgbClr', 'a:prstClr', 'a:sysClr']) {
const raw = duoRaw[tag]
@@ -2485,14 +2787,16 @@ function parseFill(spPr: any, ctx: ParseContext): Fill | undefined {
? { l: pct(fr['@_l']), t: pct(fr['@_t']), r: pct(fr['@_r']), b: pct(fr['@_b']) }
: undefined
const tl = blip['a:tile']
// A bare self-closing <a:tile/> parses to '' — it still tiles with all defaults
const tlAttrs = tl && typeof tl === 'object' ? tl : {}
const tile =
tl && typeof tl === 'object'
tl !== undefined
? {
tx: intOr(tl['@_tx'], 0),
ty: intOr(tl['@_ty'], 0),
sx: intOr(tl['@_sx'], 100000) / 100000,
sy: intOr(tl['@_sy'], 100000) / 100000,
algn: String(tl['@_algn'] ?? 'tl'),
tx: intOr(tlAttrs['@_tx'], 0),
ty: intOr(tlAttrs['@_ty'], 0),
sx: intOr(tlAttrs['@_sx'], 100000) / 100000,
sy: intOr(tlAttrs['@_sy'], 100000) / 100000,
algn: String(tlAttrs['@_algn'] ?? 'tl'),
}
: undefined
return {
@@ -2530,10 +2834,14 @@ function parseGradFill(grad: any, ctx: ParseContext): Fill | undefined {
})
.filter((s: any): s is { pos: number; color: string } => !!s)
if (!stops.length) return undefined
// Linear gradient angle: <a:lin ang=""> (unit 1/60000 degree); radial etc. get the default angle for now
const ang = grad['a:lin']?.['@_ang']
const angle = ang != null ? parseInt(ang, 10) || 0 : undefined
// Linear gradient angle: <a:lin ang=""> (unit 1/60000 degree). A gradFill with neither
// a:lin nor a:path renders top→bottom in PowerPoint (tdf104788 measured), not the spec's 0°
const lin = grad['a:lin']
const pathType = grad['a:path']?.['@_path']
// An explicit a:lin without ang keeps the schema default 0; only a fully
// directionless gradFill gets the measured vertical default
const angle =
lin != null ? parseInt(lin['@_ang'], 10) || 0 : grad['a:path'] == null ? 5400000 : undefined
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)
@@ -2597,6 +2905,24 @@ function parseTextBody(txBody: any, ctx: ParseContext, phChain: TextStyleLevels[
? vertRaw
: undefined
// WordArt text extrusion: bodyPr-level sp3d depth + camera tilt decide the offset direction
let extrusion3d: TextBody['extrusion3d']
const bodySp3d = bodyPr['a:sp3d']
const depthEmu = bodySp3d ? intOr(bodySp3d['@_extrusionH'], 0) : 0
if (depthEmu > 0) {
const extClr = bodySp3d['a:extrusionClr']
const color =
(extClr && typeof extClr === 'object' ? resolveColorNode(extClr, ctx) : undefined) ??
'#808080'
const rot = bodyPr['a:scene3d']?.['a:camera']?.['a:rot']
extrusion3d = {
color,
depthEmu,
latDeg: intOr(rot?.['@_lat'], 0) / 60000,
lonDeg: intOr(rot?.['@_lon'], 0) / 60000,
}
}
return {
paragraphs,
anchor: bodyPr['@_anchor'] ? anchorMap[bodyPr['@_anchor']] : undefined,
@@ -2614,6 +2940,7 @@ function parseTextBody(txBody: any, ctx: ParseContext, phChain: TextStyleLevels[
...(intOr(bodyPr['@_numCol'], 1) > 1
? { numCol: intOr(bodyPr['@_numCol'], 1), spcCol: intOr(bodyPr['@_spcCol'], 0) }
: {}),
...(extrusion3d ? { extrusion3d } : {}),
}
}
@@ -2765,9 +3092,18 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
const hlink = rPr['a:hlinkClick']
const hlinkTarget = hlink?.['@_r:id'] ? ctx.hlinkRels?.get(String(hlink['@_r:id'])) : undefined
const fill = rPr['a:solidFill']
// WordArt gradient text fill: resolved stops for display, mid-stop as the flat fallback color
let gradient: TextRun['gradient']
if (rPr['a:gradFill'] && typeof rPr['a:gradFill'] === 'object') {
const g = parseFill(rPr, ctx)
if (g?.type === 'gradient' && g.stops.length) {
gradient = { stops: g.stops, ...(g.angle != null ? { angle: g.angle } : {}) }
}
}
// PowerPoint styles linked runs with the theme hlink color unless the run has an explicit fill
const color =
(fill ? resolveColorNode(fill, ctx) : undefined) ??
gradient?.stops[Math.floor(gradient.stops.length / 2)]?.color ??
(hlinkTarget ? ctx.theme?.colors?.hlink : undefined) ??
dflt?.color
// Whether the color is display-only: from schemeClr/inheritance (not an explicit run srgbClr).
@@ -2798,6 +3134,8 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
}
}
const runShadow = parseShadow(rPr, ctx) ?? dflt?.shadow
const runGlow = parseGlow(rPr, ctx)
const reflection = rPr['a:effectLst']?.['a:reflection'] != null
const uAttr = rPr['@_u']
const strikeAttr = rPr['@_strike']
const hasStrike = strikeAttr !== undefined && strikeAttr !== 'noStrike'
@@ -2833,6 +3171,9 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
...(highlight ? { highlight } : {}),
...(outline ? { outline } : {}),
...(runShadow ? { shadow: runShadow } : {}),
...(gradient ? { gradient } : {}),
...(runGlow ? { glow: runGlow } : {}),
...(reflection ? { reflection: true } : {}),
...(hlink?.['@_r:id']
? {
hyperlinkRId: String(hlink['@_r:id']),
@@ -0,0 +1,353 @@
/**
* Relationship-aware cleanup for package parts dropped by slide mutations.
*
* A media/chart part cannot be removed merely because one shape stopped using it:
* duplicated slides and copied objects may point at the same target. Cleanup first
* removes only relationships no longer used by the owning XML, then collects the
* now-unreachable resource subgraph.
*/
import type { Slide } from './types'
import { PackageArchive, relsPathFor, resolveTarget } from './zip'
export interface ResourceCleanupStats {
relationshipsRemoved: number
partsRemoved: number
bytesRemoved: number
}
interface ResourceCleanupContext {
archive: PackageArchive
deck: { slides: Slide[] }
}
const EMPTY_STATS: ResourceCleanupStats = {
relationshipsRemoved: 0,
partsRemoved: 0,
bytesRemoved: 0,
}
const RELATIONSHIP_TAG = /<Relationship\b[^>]*\/\s*>/g
const ATTRIBUTE = /\s[\w:.-]+\s*=\s*(["'])(.*?)\1/g
const ID_ATTRIBUTE = /\bId\s*=\s*(["'])(.*?)\1/
const PART_NAME_ATTRIBUTE = /\bPartName\s*=\s*(["'])(.*?)\1/
const OVERRIDE_TAG = /<Override\b[^>]*\/\s*>/g
const MODEL_3D_REF = /aislides-3d:(ppt\/media\/[^"'&<\s]+)/g
/**
* Parts below these directories are owned by a slide object/slide and can be
* collected once no retained package part points at them.
*/
const OWNED_RESOURCE_PREFIXES = [
'ppt/media/',
'ppt/charts/',
'ppt/embeddings/',
'ppt/diagrams/',
'ppt/drawings/',
'ppt/oleObjects/',
'ppt/activeX/',
'ppt/ctrlProps/',
'ppt/controls/',
'ppt/tags/',
'ppt/notesSlides/',
'ppt/comments/',
'ppt/threadedComments/',
'ppt/printerSettings/',
'ppt/vmlDrawings/',
'ppt/ink/',
'ppt/model3d/',
'ppt/models3d/',
] as const
function isOwnedResourcePath(path: string): boolean {
return OWNED_RESOURCE_PREFIXES.some((prefix) => path.startsWith(prefix))
}
function attributeValues(xml: string): Set<string> {
const out = new Set<string>()
for (const match of xml.matchAll(ATTRIBUTE)) out.add(match[2]!)
return out
}
function model3dRefs(xml: string): Set<string> {
const out = new Set<string>()
for (const match of xml.matchAll(MODEL_3D_REF)) out.add(match[1]!)
return out
}
function currentSlideXml(slide: Slide): string {
const parts = [slide.bodyPrefix]
for (const element of slide.elements) {
parts.push(element.anchor.originalXml)
if (element.anchor.gapAfter) parts.push(element.anchor.gapAfter)
}
parts.push(slide.bodySuffix)
return parts.join('')
}
function sourcePartForRels(path: string): string | null {
if (path === '_rels/.rels') return ''
const marker = '/_rels/'
const markerAt = path.lastIndexOf(marker)
if (markerAt < 0 || !path.endsWith('.rels')) return null
const dir = path.slice(0, markerAt)
const name = path.slice(markerAt + marker.length, -'.rels'.length)
return `${dir}/${name}`
}
function stripRelationships(xml: string, ids: ReadonlySet<string>): string {
return xml.replace(RELATIONSHIP_TAG, (tag) => {
const id = ID_ATTRIBUTE.exec(tag)?.[2]
return id && ids.has(id) ? '' : tag
})
}
function removeContentTypeOverrides(
archive: PackageArchive,
removedParts: ReadonlySet<string>,
): void {
if (removedParts.size === 0) return
const path = '[Content_Types].xml'
const xml = archive.readText(path)
if (!xml) return
const next = xml.replace(OVERRIDE_TAG, (tag) => {
const partName = PART_NAME_ATTRIBUTE.exec(tag)?.[2]?.replace(/^\//, '')
return partName && removedParts.has(partName) ? '' : tag
})
if (next !== xml) archive.entries.set(path, Buffer.from(next, 'utf8'))
}
function packageRelationshipGraph(archive: PackageArchive): {
outgoing: Map<string, Set<string>>
incoming: Map<string, Set<string>>
} {
const outgoing = new Map<string, Set<string>>()
const incoming = new Map<string, Set<string>>()
for (const path of archive.entries.keys()) {
if (!path.endsWith('.rels')) continue
const source = sourcePartForRels(path)
if (source == null || (source !== '' && !archive.entries.has(source))) continue
for (const rel of archive.readRels(source).values()) {
if (rel.targetMode === 'External') continue
const target = resolveTarget(source, rel.target)
let targets = outgoing.get(source)
if (!targets) outgoing.set(source, (targets = new Set()))
targets.add(target)
let sources = incoming.get(target)
if (!sources) incoming.set(target, (sources = new Set()))
sources.add(source)
}
}
return { outgoing, incoming }
}
/**
* Remove the candidate resource closure only when it has no incoming edge from a
* retained package part. If a shared chart/image is retained, its dependencies
* are retained too.
*/
function removeUnreferencedOwnedParts(
archive: PackageArchive,
initialCandidates: Iterable<string>,
xmlOverrides: ReadonlyMap<string, string> = new Map(),
): ResourceCleanupStats {
const { outgoing, incoming } = packageRelationshipGraph(archive)
const closure = new Set<string>()
const pending = [...initialCandidates]
while (pending.length) {
const path = pending.pop()!
if (closure.has(path) || !isOwnedResourcePath(path) || !archive.entries.has(path)) continue
closure.add(path)
for (const target of outgoing.get(path) ?? []) {
if (isOwnedResourcePath(target)) pending.push(target)
}
}
if (closure.size === 0) return { ...EMPTY_STATS }
const retained = new Set<string>()
for (const path of closure) {
for (const source of incoming.get(path) ?? []) {
if (!closure.has(source)) {
retained.add(path)
break
}
}
}
// GenOffice's simplified 3D placeholder records the model path in cNvPr@descr
// rather than an OOXML relationship, so include those direct references.
for (const [path, bytes] of archive.entries) {
if (!path.endsWith('.xml') || closure.has(path)) continue
const xml = xmlOverrides.get(path) ?? Buffer.from(bytes).toString('utf8')
for (const target of model3dRefs(xml)) {
if (closure.has(target)) retained.add(target)
}
}
const propagate = [...retained]
while (propagate.length) {
const source = propagate.pop()!
for (const target of outgoing.get(source) ?? []) {
if (closure.has(target) && !retained.has(target)) {
retained.add(target)
propagate.push(target)
}
}
}
const removed = new Set<string>()
let bytesRemoved = 0
for (const path of closure) {
if (retained.has(path)) continue
const bytes = archive.entries.get(path)
if (!bytes) continue
bytesRemoved += bytes.byteLength
removed.add(path)
archive.entries.delete(path)
archive.entries.delete(relsPathFor(path))
}
removeContentTypeOverrides(archive, removed)
return {
relationshipsRemoved: 0,
partsRemoved: removed.size,
bytesRemoved,
}
}
/**
* Remove selected relationship rows and collect their now-unreferenced owned
* targets. The package graph is rebuilt after the rows are removed, so another
* relationship to the same target keeps that target and its dependency closure.
*/
function removeRelationshipsAndCollectOwnedTargets(
archive: PackageArchive,
sourcePart: string,
relationshipIds: Iterable<string>,
extraCandidates: Iterable<string> = [],
xmlOverrides: ReadonlyMap<string, string> = new Map(),
): ResourceCleanupStats {
const rels = archive.readRels(sourcePart)
const ids = new Set<string>()
const candidates = new Set(extraCandidates)
for (const id of relationshipIds) {
const rel = rels.get(id)
if (!rel) continue
ids.add(id)
if (rel.targetMode !== 'External') {
const target = resolveTarget(sourcePart, rel.target)
if (isOwnedResourcePath(target)) candidates.add(target)
}
}
if (ids.size) {
const path = relsPathFor(sourcePart)
const xml = archive.readText(path)
if (xml) archive.entries.set(path, Buffer.from(stripRelationships(xml, ids), 'utf8'))
}
const collected = removeUnreferencedOwnedParts(archive, candidates, xmlOverrides)
return {
relationshipsRemoved: ids.size,
partsRemoved: collected.partsRemoved,
bytesRemoved: collected.bytesRemoved,
}
}
/**
* Compare XML from before and after a slide mutation. Relationship ids that
* disappeared from the live slide are pruned, then their unshared owned targets
* are collected. Callers pass the fully patched current slide XML so pending
* in-memory edits participate in the liveness check.
*/
export function cleanupSupersededSlideResources(
opened: ResourceCleanupContext,
slide: Slide,
previousXml: string,
currentXml: string,
): ResourceCleanupStats {
const { archive } = opened
const rels = archive.readRels(slide.path)
const previousValues = attributeValues(previousXml)
const currentValues = attributeValues(currentXml)
const liveSlideXml = new Map(
opened.deck.slides.map((deckSlide) => [deckSlide.path, currentSlideXml(deckSlide)]),
)
liveSlideXml.set(slide.path, currentXml)
const ids = new Set<string>()
const candidates = new Set<string>()
for (const id of rels.keys()) {
if (!previousValues.has(id) || currentValues.has(id)) continue
ids.add(id)
}
const currentModels = model3dRefs(currentXml)
for (const target of model3dRefs(previousXml)) {
if (!currentModels.has(target)) candidates.add(target)
}
return removeRelationshipsAndCollectOwnedTargets(
archive,
slide.path,
ids,
candidates,
liveSlideXml,
)
}
/**
* Called after an element has left slide.elements. It removes relationship rows
* used only by that element, then collects unshared media/chart dependency parts.
*/
export function cleanupDeletedElementResources(
opened: ResourceCleanupContext,
slide: Slide,
removedElementXml: string,
): ResourceCleanupStats {
return cleanupSupersededSlideResources(opened, slide, removedElementXml, currentSlideXml(slide))
}
/**
* Remove one explicit relationship and collect its internal owned target only
* when no retained package relationship still points at it. This covers
* relationship-owned parts (such as a slide's comments part) that are not
* referenced from the source XML.
*/
export function removeRelationshipAndCollectOwnedTarget(
archive: PackageArchive,
sourcePart: string,
relationshipId: string,
): ResourceCleanupStats {
return removeRelationshipsAndCollectOwnedTargets(archive, sourcePart, [relationshipId])
}
/**
* Delete a package part and collect resource parts that were owned exclusively by
* it. Used by slide deletion after the presentation relationship is removed.
*/
export function removePartWithOwnedResources(
archive: PackageArchive,
partPath: string,
): ResourceCleanupStats {
const candidates = new Set<string>()
for (const rel of archive.readRels(partPath).values()) {
if (rel.targetMode === 'External') continue
const target = resolveTarget(partPath, rel.target)
if (isOwnedResourcePath(target)) candidates.add(target)
}
const xml = archive.readText(partPath)
if (xml) {
for (const target of model3dRefs(xml)) candidates.add(target)
}
let bytesRemoved = archive.entries.get(partPath)?.byteLength ?? 0
archive.entries.delete(partPath)
archive.entries.delete(relsPathFor(partPath))
removeContentTypeOverrides(archive, new Set([partPath]))
const collected = removeUnreferencedOwnedParts(archive, candidates)
bytesRemoved += collected.bytesRemoved
return {
relationshipsRemoved: 0,
partsRemoved: 1 + collected.partsRemoved,
bytesRemoved,
}
}
+5
View File
@@ -390,6 +390,11 @@ export function resolveTableStyle(
const def = parseTableStylesXml(tableStylesXml, styleId, theme)
if (def) return def
}
// A tableStyles part that defines explicit styles but not this id renders unstyled in
// PowerPoint — the built-in gallery only backs an empty part (def-id only). Measured on
// prod imports: same undefined Medium2/Accent1 id styled with an empty part, transparent
// with a populated one (decorative shapes behind the table show through).
if (tableStylesXml && /<a:tblStyle[\s>]/.test(tableStylesXml)) return undefined
const builtin = BUILTIN[styleId]
if (builtin) return builtinStyle(builtin.family, builtin.accent, theme)
if (styleId === LEGACY_NO_STYLE) return {}
+34
View File
@@ -180,6 +180,12 @@ export interface TextRun {
outline?: { color: ResolvedColor; widthEmu: number }
/** Run-level outer shadow (<a:rPr>/defRPr <a:effectLst><a:outerShdw>) */
shadow?: ShadowEffect
/** WordArt gradient text fill (<a:rPr><a:gradFill>); color keeps a mid-stop fallback */
gradient?: { stops: Array<{ pos: number; color: ResolvedColor }>; angle?: number }
/** Run-level glow (<a:rPr><a:effectLst><a:glow>) */
glow?: GlowEffect
/** Run-level reflection (<a:rPr><a:effectLst><a:reflection>), rendered as a faded mirror */
reflection?: boolean
}
export type TextAlign = 'left' | 'center' | 'right' | 'justify'
@@ -252,6 +258,8 @@ export interface TextBody {
numCol?: number
/** <a:bodyPr spcCol>: gap between columns (EMU) */
spcCol?: number
/** <a:bodyPr><a:scene3d>+<a:sp3d>: WordArt text extrusion (camera angles in degrees) */
extrusion3d?: { color: ResolvedColor; depthEmu: number; latDeg: number; lonDeg: number }
}
// ── Elements ───────────────────────────────────────────────────────────
@@ -346,6 +354,31 @@ export interface CustomGeometry {
strokePath?: string
}
/**
* <a:scene3d> + <a:sp3d>: 3D scene (camera + light rig) and shape extrusion.
* Angles are in 1/60000 degree (OOXML ST_Angle); lengths in EMU.
*/
export interface Scene3D {
/** <a:camera prst> preset name (ST_PresetCameraType) */
cameraPreset: string
/** <a:camera><a:rot>: overrides the preset's angles when present */
cameraRot?: { lat: number; lon: number; rev: number }
/** <a:lightRig rig> preset name (ST_LightRigType) */
lightRig?: string
/** <a:lightRig dir>: rig rotation in 45° steps (tl/t/tr/l/r/bl/b/br) */
lightDir?: string
/** <a:lightRig><a:rot> */
lightRot?: { lat: number; lon: number; rev: number }
/** <a:sp3d extrusionH> extrusion depth (EMU) */
extrusionEmu?: number
/** <a:sp3d z> shape z-position in the scene (EMU) */
zEmu?: number
/** <a:sp3d><a:extrusionClr> resolved color for the extruded side walls */
extrusionColor?: ResolvedColor
/** <a:sp3d prstMaterial> (legacyWireframe renders edges only) */
material?: string
}
export interface TextElement extends ElementBase {
type: 'text' | 'shape'
/** Shape's preset geometry (rect/ellipse/roundRect/…); absent for text */
@@ -363,6 +396,7 @@ export interface TextElement extends ElementBase {
stroke?: Stroke
shadow?: ShadowEffect
glow?: GlowEffect
scene3d?: Scene3D
text?: TextBody
}
+141
View File
@@ -59,6 +59,37 @@ describe('parseChartXml', () => {
expect(parseChartXml('<c:chartSpace><c:chart/></c:chartSpace>')).toBeNull()
})
const legendVariant = (legend: string) =>
parseChartXml(
BAR_CHART.replace('</c:plotArea>', `</c:plotArea><c:legend>${legend}</c:legend>`),
)!
it('legend without c:legendPos floats: defaults to right + overlay (PowerPoint measured)', () => {
const m = legendVariant('<c:layout/>')
expect(m.legendPos).toBe('r')
expect(m.legendOverlay).toBe(true)
})
it('explicit c:legendPos without c:overlay reserves space (no overlay)', () => {
const m = legendVariant('<c:legendPos val="r"/><c:layout/>')
expect(m.legendOverlay).toBeUndefined()
})
it('explicit c:overlay val=0 wins even without c:legendPos', () => {
const m = legendVariant('<c:overlay val="0"/>')
expect(m.legendOverlay).toBeUndefined()
})
it('parses legend manual layout: factor offsets and edge absolutes', () => {
const m = legendVariant(
'<c:legendPos val="b"/><c:layout><c:manualLayout>' +
'<c:xMode val="factor"/><c:yMode val="edge"/><c:x val="-0.5"/><c:y val="0.9"/>' +
'</c:manualLayout></c:layout><c:overlay val="1"/>',
)
expect(m.legendOverlay).toBe(true)
expect(m.legendLayout).toEqual({ x: -0.5, xMode: 'factor', y: 0.9, yMode: 'edge' })
})
it('parses doughnut hole size + per-point colors (c:dPt)', () => {
const DOUGHNUT = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
<c:doughnutChart><c:ser><c:idx val="0"/>
@@ -638,3 +669,113 @@ describe('multi-level categories + palette idx + hidden tick labels', () => {
expect(m.catAxis?.tickLblHidden).toBe(true)
})
})
const BAR3D_CHART = `<?xml version="1.0"?>
<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
<c:chart><c:view3D><c:rotX val="25"/><c:perspective val="30"/></c:view3D><c:plotArea><c:layout/>
<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: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:gapDepth val="80"/><c:shape val="box"/></c:bar3DChart>
<c:serAx><c:axId val="1"/><c:delete val="0"/></c:serAx>
</c:plotArea></c:chart></c:chartSpace>`
describe('bar3D view parameters', () => {
it('parses view3D overrides with ECMA defaults and the serAx flag', () => {
const m = parseChartXml(BAR3D_CHART)!
expect(m.bar3D).toEqual({
rotX: 25,
rotY: 20,
depthPct: 100,
rAngAx: true,
gapDepthPct: 80,
serAxLabels: true,
})
expect(m.pseudo3D).toBe(true)
})
})
describe('chart title and axis-title styling', () => {
it('reads bold/italic/color from the first rich title run', () => {
const xml = `<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
<c:chart><c:title><c:tx><c:rich><a:p><a:pPr><a:defRPr/></a:pPr><a:r><a:rPr sz="2000" b="1" i="1"><a:solidFill><a:srgbClr val="808080"/></a:solidFill></a:rPr><a:t>T</a:t></a:r></a:p></c:rich></c:tx><c:overlay val="1"/></c:title>
<c:plotArea><c:lineChart><c:ser><c:idx val="0"/><c:val><c:numRef><c:numCache><c:pt idx="0"><c:v>1</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser></c:lineChart>
<c:catAx><c:axId val="1"/><c:title><c:tx><c:rich><a:p><a:r><a:rPr sz="1400" i="1"><a:solidFill><a:srgbClr val="808080"/></a:solidFill></a:rPr><a:t>Cat</a:t></a:r></a:p></c:rich></c:tx><c:overlay val="1"/></c:title><c:delete val="0"/></c:catAx>
<c:valAx><c:axId val="2"/><c:delete val="0"/></c:valAx>
</c:plotArea></c:chart></c:chartSpace>`
const m = parseChartXml(xml)!
expect(m.title).toBe('T')
expect(m.titleBold).toBe(true)
expect(m.titleItalic).toBe(true)
expect(m.titleColor).toBe('#808080')
expect(m.catAxis?.title).toBe('Cat')
expect(m.catAxis?.titleItalic).toBe(true)
expect(m.catAxis?.titleColor).toBe('#808080')
expect(m.catAxis?.titleSizePt).toBe(14)
})
it('explicit b="0" on the title run reaches the model as non-bold', () => {
const xml = `<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
<c:chart><c:title><c:tx><c:rich><a:p><a:r><a:rPr sz="1200" b="0"/><a:t>T</a:t></a:r></a:p></c:rich></c:tx></c:title>
<c:plotArea><c:lineChart><c:ser><c:idx val="0"/><c:val><c:numRef><c:numCache><c:pt idx="0"><c:v>1</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser></c:lineChart>
<c:catAx><c:axId val="1"/></c:catAx><c:valAx><c:axId val="2"/></c:valAx></c:plotArea></c:chart></c:chartSpace>`
const m = parseChartXml(xml)!
expect(m.titleBold).toBe(false)
})
it('parses c15 datalabelsRange cell labels when the show flag is on', () => {
const xml = `<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
<c:chart><c:plotArea><c:bubbleChart><c:ser><c:idx val="0"/>
<c:dLbls><c:showVal val="0"/><c:extLst><c:ext uri="{CE6537A1-D6FC-4f65-9D91-7224C49458BB}" xmlns:c15="http://schemas.microsoft.com/office/drawing/2012/chart"><c15:showDataLabelsRange val="1"/></c:ext></c:extLst></c:dLbls>
<c:xVal><c:numRef><c:numCache><c:pt idx="0"><c:v>1</c:v></c:pt></c:numCache></c:numRef></c:xVal>
<c:yVal><c:numRef><c:numCache><c:pt idx="0"><c:v>2</c:v></c:pt></c:numCache></c:numRef></c:yVal>
<c:bubbleSize><c:numRef><c:numCache><c:pt idx="0"><c:v>5</c:v></c:pt></c:numCache></c:numRef></c:bubbleSize>
<c:extLst><c:ext uri="{02D57815-91ED-43cb-92C2-25804820EDAC}" xmlns:c15="http://schemas.microsoft.com/office/drawing/2012/chart"><c15:datalabelsRange><c15:f>Sheet1!$A$1</c15:f><c15:dlblRangeCache><c:ptCount val="1"/><c:pt idx="0"><c:v>Cell label</c:v></c:pt></c15:dlblRangeCache></c15:datalabelsRange></c:ext></c:extLst>
</c:ser></c:bubbleChart><c:valAx><c:axId val="1"/></c:valAx><c:valAx><c:axId val="2"/></c:valAx></c:plotArea></c:chart></c:chartSpace>`
const m = parseChartXml(xml)!
expect(m.series[0]?.pointLabels).toEqual(['Cell label'])
})
it('stock series default to visible markers', () => {
const xml = `<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
<c:chart><c:plotArea><c:stockChart>
<c:ser><c:idx val="0"/><c:val><c:numRef><c:numCache><c:pt idx="0"><c:v>1</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser>
<c:ser><c:idx val="1"/><c:marker><c:symbol val="none"/></c:marker><c:val><c:numRef><c:numCache><c:pt idx="0"><c:v>2</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser>
</c:stockChart><c:catAx><c:axId val="1"/></c:catAx><c:valAx><c:axId val="2"/></c:valAx></c:plotArea></c:chart></c:chartSpace>`
const m = parseChartXml(xml)!
expect(m.series[0]?.marker).toBe(true)
expect(m.series[1]?.marker).toBe(false)
})
})
const UNITS_CHART = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
<c:lineChart><c:grouping val="stacked"/><c:ser><c:idx val="0"/>
<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:lineChart>
<c:catAx><c:majorGridlines/><c:minorGridlines/></c:catAx>
<c:valAx><c:scaling><c:orientation val="maxMin"/></c:scaling>
<c:majorGridlines/><c:minorGridlines/>
<c:title><c:tx><c:rich><a:p><a:r><a:rPr sz="2000"/><a:t>Primary</a:t></a:r></a:p></c:rich></c:tx><c:overlay val="1"/></c:title>
<c:majorUnit val="2"/><c:minorUnit val="0.5"/>
</c:valAx>
</c:plotArea></c:chart></c:chartSpace>`
describe('axis units / gridline defaults / title overlay', () => {
it('parses majorUnit/minorUnit, orientation, line grouping and axis-title overlay', () => {
const m = parseChartXml(UNITS_CHART)!
expect(m.grouping).toBe('stacked')
expect(m.valAxis?.majorUnit).toBe(2)
expect(m.valAxis?.minorUnit).toBe(0.5)
expect(m.valAxis?.reversed).toBe(true)
expect(m.valAxis?.title).toBe('Primary')
expect(m.valAxis?.titleOverlay).toBe(true)
})
it('flags default-colored gridlines so the render layer can pick style-aware grays', () => {
const m = parseChartXml(UNITS_CHART)!
expect(m.valAxis?.gridColor).toBe('#E6E6E6')
expect(m.valAxis?.gridColorAuto).toBe(true)
expect(m.valAxis?.minorGridAuto).toBe(true)
expect(m.catAxis?.gridColorAuto).toBe(true)
})
})
+141
View File
@@ -0,0 +1,141 @@
import { describe, expect, it } from 'vitest'
import { layoutHierTree, parseHierConstraints, type HierTreeNode } from '../src/dgm-hier'
const n = (
text: string,
children: HierTreeNode[] = [],
extra: Partial<HierTreeNode> = {},
): HierTreeNode => ({
texts: text ? [text] : [],
children,
...extra,
})
const CONS = parseHierConstraints(undefined)
// Frame chosen so the unit layout is height-bound with a comfortable margin
const layout = (roots: HierTreeNode[]) => layoutHierTree(roots, CONS, 8000000, 6000000)!
const box = (g: ReturnType<typeof layout>, text: string) =>
g.boxes.find((b) => b.node.texts[0] === text)!
describe('parseHierConstraints', () => {
it('reads factors from orgChart1-style constraint lists', () => {
const xml = `
<dgm:constr type="h" for="des" forName="rootComposite1" refType="w" refFor="des" refForName="rootComposite1" fact="0.6"/>
<dgm:constr type="sibSp" refType="w" refFor="des" refForName="rootComposite1" fact="0.3"/>
<dgm:constr type="sp" for="des" forName="hierRoot1" refType="w" refFor="des" refForName="rootComposite1" fact="0.25"/>
<dgm:constr type="w" for="ch" forName="rootConnector1" refType="w" refFor="ch" refForName="rootText1" fact="0.2"/>
<dgm:constr type="primFontSz" val="65"/>`
const c = parseHierConstraints(xml)
expect(c.boxAspect).toBe(0.6)
expect(c.sibSp).toBe(0.3)
expect(c.sp).toBe(0.25)
expect(c.trunkOff).toBeCloseTo(0.1)
expect(c.fontMax).toBe(65)
})
it('falls back to orgChart1 defaults without a layout part', () => {
expect(CONS.boxAspect).toBe(0.5)
expect(CONS.sibSp).toBe(0.21)
})
it('reads primFontSz with attributes between type and val, skipping valueless op=equ', () => {
const xml = `
<dgm:constr type="primFontSz" for="des" ptType="node" op="equ"/>
<dgm:constr type="primFontSz" for="ch" forName="rootText1" val="48"/>`
expect(parseHierConstraints(xml).fontMax).toBe(48)
})
})
describe('layoutHierTree', () => {
// smartart-org-chart2.pptx shape: A → (B1 → C1, C2 → D1, D2; B2 → C3, C4)
const tree = () =>
n('A', [n('B1', [n('C1'), n('C2', [n('D1'), n('D2')])]), n('B2', [n('C3'), n('C4')])])
it('all node boxes share one size with the constraint aspect', () => {
const g = layout([tree()])
const w = g.boxes[0]!.w
for (const b of g.boxes) {
expect(b.w).toBeCloseTo(w)
expect(b.h / b.w).toBeCloseTo(CONS.boxAspect)
}
})
it('deep all-leaf branches hang: boxes indent 0.25w from the parent left', () => {
const g = layout([tree()])
const b2 = box(g, 'B2')
const c3 = box(g, 'C3')
const c4 = box(g, 'C4')
expect(c3.x - b2.x).toBeCloseTo(0.25 * b2.w, 0)
expect(c4.x).toBeCloseTo(c3.x)
// stacked one row apart
expect(c4.y - c3.y).toBeCloseTo((CONS.boxAspect + CONS.sp) * b2.w, 0)
})
it('root-level children never hang even when all leaves', () => {
const g = layout([n('A', [n('B1'), n('B2')])])
expect(box(g, 'B1').y).toBeCloseTo(box(g, 'B2').y)
})
it('3-row charts stay standard even with deep all-leaf branches (recursion measured)', () => {
// smartart-recursion.pptx: A → (B1 → C1, C2; B2 → C3) renders all-std in PowerPoint
const g = layout([n('A', [n('B1', [n('C1'), n('C2')]), n('B2', [n('C3')])])])
expect(box(g, 'C1').y).toBeCloseTo(box(g, 'C2').y)
expect(box(g, 'C2').y).toBeCloseTo(box(g, 'C3').y)
})
it('contour packing lets a hang overhang slide past a sibling box row', () => {
// B1's D-hang extends right below B2's box row; B2 must pack against the
// C row contour, not the D overhang bounding box (PowerPoint measured)
const g = layout([tree()])
const b1 = box(g, 'B1')
const b2 = box(g, 'B2')
const d1 = box(g, 'D1')
expect(b2.x).toBeLessThan(d1.x + d1.w)
// measured center pitch: 1.815 box widths
expect((b2.x - b1.x) / b1.w).toBeCloseTo(1.815, 1)
})
it('parents center on the midpoint of their outer children', () => {
const g = layout([tree()])
const a = box(g, 'A')
const b1 = box(g, 'B1')
const b2 = box(g, 'B2')
expect(a.x + a.w / 2).toBeCloseTo((b1.x + b1.w / 2 + b2.x + b2.w / 2) / 2, 0)
})
it('leaf assistants get their own row tucked left of the trunk', () => {
// smartart-org-chart.pptx shape
const g = layout([
n('Manager', [n('Assistant', [], { asst: true }), n('Employee'), n('Employee2')]),
n('Manager2'),
])
const mgr = box(g, 'Manager')
const asst = box(g, 'Assistant')
const emp = box(g, 'Employee')
const trunk = mgr.x + mgr.w / 2
expect(asst.x + asst.w).toBeCloseTo(trunk - (CONS.sp / 2) * mgr.w, 0)
expect(asst.y).toBeGreaterThan(mgr.y)
expect(emp.y).toBeGreaterThan(asst.y)
})
it('explicit hierBranch overrides the auto rule', () => {
const g = layout([n('A', [n('B', [n('C1'), n('C2')], { hierBranch: 'std' })])])
expect(box(g, 'C1').y).toBeCloseTo(box(g, 'C2').y)
const g2 = layout([n('A', [n('B', [n('C1'), n('C2')], { hierBranch: 'l' })])])
const b = box(g2, 'B')
const c1 = box(g2, 'C1')
expect(c1.x + c1.w).toBeCloseTo(b.x + b.w - 0.25 * b.w, 0)
})
it('scales into the frame and stays inside it', () => {
const g = layoutHierTree([tree()], CONS, 3000000, 2000000)!
for (const b of g.boxes) {
expect(b.x).toBeGreaterThanOrEqual(-1)
expect(b.y).toBeGreaterThanOrEqual(-1)
expect(b.x + b.w).toBeLessThanOrEqual(3000001)
expect(b.y + b.h).toBeLessThanOrEqual(2000001)
}
})
})
@@ -63,19 +63,42 @@ describe('layoutDiagramFallback', () => {
<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)', () => {
it('orgChart keeps root children side by side (hang never fires at the root row)', () => {
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
// PowerPoint measured (smartart-org-chart): a root's leaf children stay on one row
expect(b2.transform.offset.y).toBe(b1.transform.offset.y)
expect(b2.transform.offset.x).toBeGreaterThan(b1.transform.offset.x)
})
it('orgChart hangs an all-leaves branch on tall charts (std depth ≥ 4, PPT measured)', () => {
// R → n1(B1,B2 leaves) + a 4-row sibling chain n4→n5→n6: n1's leaves hang
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="n4"/><dgm:pt modelId="n5"/><dgm:pt modelId="n6"/><dgm:pt modelId="n1">',
)
.replace(
'</dgm:cxnLst>',
'<dgm:cxn modelId="c0" srcId="n0" destId="n1" srcOrd="0" destOrd="0"/>' +
'<dgm:cxn modelId="c7" srcId="n0" destId="n4" srcOrd="1" destOrd="0"/>' +
'<dgm:cxn modelId="c8" srcId="n4" destId="n5" srcOrd="0" destOrd="0"/>' +
'<dgm:cxn modelId="c9" srcId="n5" destId="n6" srcOrd="0" destOrd="0"/></dgm:cxnLst>',
)
const shapes = layoutDiagramFallback(deep, {}, 9144000, 6858000, 'orgChart1')
const boxes = shapes.filter((sp: any) => sp.text) as any[]
// n1's leaf children (B1, B2) hang on separate rows
const texts = boxes.map((b) => JSON.stringify(b))
const b1 = boxes[texts.findIndex((t) => t.includes('B1'))]!
const b2 = boxes[texts.findIndex((t) => t.includes('B2'))]!
expect(b2.transform.offset.y).toBeGreaterThan(b1.transform.offset.y)
})
it('orgChart hangs a branch whose children are all leaves when nested deeper', () => {
it('orgChart keeps an all-leaves branch side by side on short charts (recursion measured)', () => {
const deep = HIER_DATA.replace('srcId="doc" destId="n1"', 'srcId="doc" destId="n0"')
.replace(
'<dgm:pt modelId="n1">',
@@ -88,9 +111,8 @@ describe('layoutDiagramFallback', () => {
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)
expect(b2.transform.offset.y).toBe(b1.transform.offset.y)
})
it('chevron layout puts all nodes on one horizontal band of chevrons', () => {
@@ -270,3 +292,148 @@ describe('flatGrid centering and tile text autofit (napierone 0005)', () => {
expect(runSize).toBeGreaterThan(10)
})
})
describe('lProcess column process family (napierone 0005 p8)', () => {
const LPROC_DATA = `<?xml version="1.0"?><dgm:dataModel xmlns:dgm="d" xmlns:a="a">
<dgm:ptLst>
<dgm:pt modelId="doc" type="doc"/>
<dgm:pt modelId="h1"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Engage</a:t></a:r></a:p></dgm:t></dgm:pt>
<dgm:pt modelId="h2"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Identify</a:t></a:r></a:p></dgm:t></dgm:pt>
<dgm:pt modelId="k1"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Departments</a:t></a:r></a:p></dgm:t></dgm:pt>
<dgm:pt modelId="k2"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Controls</a:t></a:r></a:p></dgm:t></dgm:pt>
</dgm:ptLst>
<dgm:cxnLst>
<dgm:cxn modelId="c1" srcId="doc" destId="h1" srcOrd="0" destOrd="0"/>
<dgm:cxn modelId="c2" srcId="doc" destId="h2" srcOrd="1" destOrd="0"/>
<dgm:cxn modelId="c3" srcId="h1" destId="k1" srcOrd="0" destOrd="0"/>
<dgm:cxn modelId="c4" srcId="h2" destId="k2" srcOrd="0" destOrd="0"/>
</dgm:cxnLst></dgm:dataModel>`
it('renders one column per top node: header, connector dot, tinted child block', () => {
const shapes = layoutDiagramFallback(LPROC_DATA, {}, 9144000, 3000000, 'lProcess1')
// 2 columns × (header + dot + child) = 6 shapes
expect(shapes).toHaveLength(6)
const [h1, dot, kid] = shapes as any[]
expect(JSON.stringify(h1)).toContain('Engage')
expect(JSON.stringify(kid)).toContain('Departments')
// dot is a small ellipse centered between header bottom and child top
expect(JSON.stringify(dot)).toContain('ellipse')
expect(dot.transform.offset.cx).toBeLessThan(h1.transform.offset.cx / 4)
expect(dot.transform.offset.y).toBeGreaterThan(h1.transform.offset.y + h1.transform.offset.cy)
expect(kid.transform.offset.y).toBeGreaterThan(dot.transform.offset.y)
// both columns share the header y; second column sits right of the first
const h2 = shapes[3] as any
expect(h2.transform.offset.y).toBe(h1.transform.offset.y)
expect(h2.transform.offset.x).toBeGreaterThan(h1.transform.offset.x)
})
it('childless lProcess2 nodes render as a large tinted top-anchored panel', () => {
const single = LPROC_DATA.replace(/<dgm:cxn modelId="c3".*destOrd="0"\/>/, '')
.replace(/<dgm:cxn modelId="c4".*destOrd="0"\/>/, '')
.replace(/<dgm:pt modelId="k1">.*?<\/dgm:pt>/, '')
.replace(/<dgm:pt modelId="k2">.*?<\/dgm:pt>/, '')
const shapes = layoutDiagramFallback(single, {}, 9144000, 3000000, 'lProcess2')
expect(shapes).toHaveLength(2)
const p = shapes[0] as any
// tall panel, not a slim header bar
expect(p.transform.offset.cy).toBeGreaterThan(3000000 * 0.7)
expect(JSON.stringify(p)).toContain('roundRect')
})
})
describe('arrow5 ring of inward arrows (smartart-autoTxRot / smartart-rotation)', () => {
it("places downArrows on a ring, first at 12 o'clock pointing down, clockwise", () => {
const shapes = layoutDiagramFallback(DATA, {}, 9144000, 6858000, 'arrow5')
expect(shapes).toHaveLength(5)
const geo = JSON.stringify(shapes[0])
expect(geo).toContain('downArrow')
// First node: centered horizontally, at the ring top, unrotated (points at the center)
const t0 = shapes[0]!.transform.offset
expect(t0.x + t0.cx / 2).toBeCloseTo(9144000 / 2, -4)
expect(shapes[0]!.transform.rot).toBe(0)
// Second node (clockwise) sits right of center and is rotated by 360/5 degrees
const t1 = shapes[1]!.transform.offset
expect(t1.x + t1.cx / 2).toBeGreaterThan(9144000 / 2)
expect(shapes[1]!.transform.rot).toBe(72 * 60000)
})
it('modified layout copies (arrow5#1) dispatch to the same family', () => {
const shapes = layoutDiagramFallback(DATA, {}, 9144000, 6858000, 'arrow5#1')
expect(JSON.stringify(shapes[0])).toContain('downArrow')
})
})
describe('orgChart assistants (dgm:pt type="asst")', () => {
const ASST = HIER_ASST()
function HIER_ASST() {
return `<?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>Boss</a:t></a:r></a:p></dgm:t></dgm:pt>
<dgm:pt modelId="as" type="asst"><dgm:t><a:bodyPr/><a:p><a:r><a:t>Asst</a:t></a:r></a:p></dgm:t></dgm:pt>
<dgm:pt modelId="n2"><dgm:t><a:bodyPr/><a:p><a:r><a:t>E1</a:t></a:r></a:p></dgm:t></dgm:pt>
<dgm:pt modelId="n3"><dgm:t><a:bodyPr/><a:p><a:r><a:t>E2</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:cxn modelId="c4" srcId="n1" destId="as" srcOrd="2" destOrd="0"/>
</dgm:cxnLst></dgm:dataModel>`
}
it('a childless assistant gets its own row between parent and children, left of the trunk', () => {
const shapes = layoutDiagramFallback(ASST, {}, 9144000, 6858000, 'orgChart1')
const boxes = shapes.filter((sp: any) => sp.text) as any[]
expect(boxes).toHaveLength(4)
const texts = boxes.map((b) => JSON.stringify(b))
const at = (name: string) => boxes[texts.findIndex((t) => t.includes(name))]!
const boss = at('Boss')
const asst = at('Asst')
const e1 = at('E1')
// Own row: below the boss, above the employees
expect(asst.transform.offset.y).toBeGreaterThan(boss.transform.offset.y)
expect(asst.transform.offset.y).toBeLessThan(e1.transform.offset.y)
// Tucked left of the boss's trunk
const bossCx = boss.transform.offset.x + boss.transform.offset.cx / 2
expect(asst.transform.offset.x + asst.transform.offset.cx).toBeLessThan(bossCx)
// Employees stay side by side (root children never hang)
expect(at('E2').transform.offset.y).toBe(e1.transform.offset.y)
})
})
describe('cycleMatrix family (cycle4)', () => {
const CM_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>A1</a:t></a:r></a:p></dgm:t></dgm:pt>
<dgm:pt modelId="n2"><dgm:spPr><a:solidFill><a:srgbClr val="ED7D31"/></a:solidFill></dgm:spPr><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>C1</a:t></a:r></a:p></dgm:t></dgm:pt>
<dgm:pt modelId="n4"><dgm:t><a:bodyPr/><a:p><a:r><a:t>D1</a:t></a:r></a:p></dgm:t></dgm:pt>
<dgm:pt modelId="k1"><dgm:t><a:bodyPr/><a:p><a:r><a:t>A2</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:cxn modelId="c4" srcId="doc" destId="n4" srcOrd="3" destOrd="0"/>
<dgm:cxn modelId="c5" srcId="n1" destId="k1" srcOrd="0" destOrd="0"/>
</dgm:cxnLst></dgm:dataModel>`
it('emits four corner cards behind four pie quadrants with a center hub', () => {
const shapes = layoutDiagramFallback(CM_DATA, {}, 6096000, 4064000, 'cycle4') as any[]
const pies = shapes.filter((s) => s.presetGeometry === 'pie')
const cards = shapes.filter((s) => s.presetGeometry === 'roundRect')
const hub = shapes.filter((s) => s.presetGeometry === 'donut')
expect(pies).toHaveLength(4)
expect(cards).toHaveLength(4)
expect(hub).toHaveLength(1)
// Cards precede the wedges (PowerPoint tucks them behind the circle)
expect(shapes.indexOf(cards[0])).toBeLessThan(shapes.indexOf(pies[0]))
// Second node's explicit dgm:spPr fill carries through
expect(JSON.stringify(pies[1])).toContain('ED7D31')
// The first card carries the child bullet
expect(JSON.stringify(cards[0])).toContain('A2')
// The custom-filled node's card stroke follows its wedge color
expect(JSON.stringify(cards[1])).toContain('ED7D31')
})
})
@@ -34,6 +34,7 @@ import {
type PictureElement,
type TextElement,
} from '../src/index'
import { relsPathFor } from '../src/zip'
const here = dirname(fileURLToPath(import.meta.url))
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
@@ -585,8 +586,49 @@ describe('setElementLink / getElementLink', () => {
const el = addElement(slide, { kind: 'rect', offset: { ...OFF } })
const s1 = setElementLink(opened, 0, el.id, { kind: 'url', url: 'https://x.dev' })!
const linked = s1.elements.at(-1)!
const oldRid = /r:id="([^"]+)"/.exec(linked.anchor.originalXml)![1]!
const s2 = setElementLink(opened, 0, linked.id, null)!
expect(getElementLink(opened, 0, s2.elements.at(-1)!.id)).toBeNull()
expect(opened.archive.readText(relsPathFor(s2.path))).not.toContain(`Id="${oldRid}"`)
})
it('replacing a link prunes the obsolete hyperlink relationship', async () => {
const opened = await openPptx(fx('01_standard_business.pptx'))
const slide = opened.deck.slides[0]!
const el = addElement(slide, { kind: 'rect', offset: { ...OFF } })
const first = setElementLink(opened, 0, el.id, { kind: 'url', url: 'https://old.dev' })!
const linked = first.elements.at(-1)!
const oldRid = /r:id="([^"]+)"/.exec(linked.anchor.originalXml)![1]!
const second = setElementLink(opened, 0, linked.id, { kind: 'url', url: 'https://new.dev' })!
const rels = opened.archive.readText(relsPathFor(second.path))!
expect(rels).not.toContain(`Id="${oldRid}"`)
expect(rels).not.toContain('Target="https://old.dev"')
expect(rels).toContain('Target="https://new.dev"')
})
it('keeps an old hyperlink relationship while another element still uses its rId', async () => {
const opened = await openPptx(fx('01_standard_business.pptx'))
const slide = opened.deck.slides[0]!
const el = addElement(slide, { kind: 'rect', offset: { ...OFF } })
const linkedSlide = setElementLink(opened, 0, el.id, {
kind: 'url',
url: 'https://shared.dev',
})!
const linked = linkedSlide.elements.at(-1)!
const oldRid = /r:id="([^"]+)"/.exec(linked.anchor.originalXml)![1]!
const sharer = addElement(linkedSlide, {
kind: 'ellipse',
offset: { ...OFF, x: 5486400 },
})
sharer.anchor.originalXml = sharer.anchor.originalXml.replace(
/<p:cNvPr([^>]*)\/>/,
`<p:cNvPr$1><a:hlinkClick r:id="${oldRid}"/></p:cNvPr>`,
)
linkedSlide.structureDirty = true
setElementLink(opened, 0, linked.id, { kind: 'url', url: 'https://new.dev' })
expect(opened.archive.readText(relsPathFor(linkedSlide.path))).toContain(`Id="${oldRid}"`)
})
it('getSlideLinks collects every linked element on the slide', async () => {
+6 -3
View File
@@ -28,7 +28,10 @@ describe('add/delete element', () => {
const el2: any = slide2.elements[slide2.elements.length - 1]
expect(el2.type).toBe('text')
expect(el2.transform.offset).toEqual(OFF)
const text = el2.text.paragraphs.flatMap((p: any) => p.runs).map((r: any) => r.text).join('')
const text = el2.text.paragraphs
.flatMap((p: any) => p.runs)
.map((r: any) => r.text)
.join('')
expect(text).toBe('Newly inserted textbox')
expect(el2.text.paragraphs[0].runs[0].bold).toBe(true)
})
@@ -76,7 +79,7 @@ describe('add/delete element', () => {
const before = slide.elements.length
expect(before).toBeGreaterThan(1)
const victim = slide.elements[0]!
expect(deleteElement(slide, victim.id)).toBe(true)
expect(deleteElement(opened, slide, victim.id)).toBe(true)
const reopened = await openPptx(await savePptx(opened))
expect(reopened.deck.slides[0]!.elements.length).toBe(before - 1)
@@ -85,7 +88,7 @@ describe('add/delete element', () => {
it('delete-only edit still marks the deck dirty for save', async () => {
const opened = await openPptx(fx('01_standard_business.pptx'))
const slide = opened.deck.slides[0]!
deleteElement(slide, slide.elements[0]!.id)
deleteElement(opened, slide, slide.elements[0]!.id)
expect(slide.structureDirty).toBe(true)
})
})
@@ -12,6 +12,7 @@ import {
savePptx,
setSlideNotes,
} from '../src/index'
import { relsPathFor, resolveTarget } from '../src/zip'
const here = dirname(fileURLToPath(import.meta.url))
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
@@ -100,4 +101,25 @@ describe('slide comments', () => {
getSlideComments(reopened.archive, reopened.deck.slides[1]!.path).map((c) => c.text),
).toEqual(['second slide'])
})
it('removes the empty comment part, slide relationship, and override after the last delete', async () => {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
const comment = addSlideComment(opened, 0, { author: 'Carol', text: 'Remove me' })!
const relationship = [...opened.archive.readRels(slide.path).values()].find((rel) =>
rel.type.endsWith('/comments'),
)!
const partPath = resolveTarget(slide.path, relationship.target)
expect(opened.archive.entries.has(partPath)).toBe(true)
expect(deleteSlideComment(opened, 0, comment)).toBe(true)
expect(opened.archive.entries.has(partPath)).toBe(false)
expect(opened.archive.readText(relsPathFor(slide.path))).not.toContain(
`Id="${relationship.id}"`,
)
expect(opened.archive.readText('[Content_Types].xml')).not.toContain(`PartName="/${partPath}"`)
const reopened = await openPptx(await savePptx(opened))
expect(getSlideComments(reopened.archive, reopened.deck.slides[0]!.path)).toEqual([])
})
})
+34
View File
@@ -106,6 +106,40 @@ describe('fill / color-mod / background parsing', () => {
expect(el.fill.angle).toBe(2700000)
})
it('gradFill with no a:lin/a:path defaults to a vertical ramp (PowerPoint-measured)', () => {
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:gradFill><a:gsLst>' +
'<a:gs pos="0"><a:srgbClr val="FFC000"/></a:gs>' +
'<a:gs pos="100000"><a:srgbClr val="FFFFD5"/></a:gs>' +
'</a:gsLst></a:gradFill></p:spPr></p:sp>'
const slide = parseSlide({
path: 'ppt/slides/slide1.xml',
slideXml: slideWith(sp),
ctx: { theme },
})
const el = slide.elements[0] as any
expect(el.fill.type).toBe('gradient')
expect(el.fill.angle).toBe(5400000)
expect(el.fill.path).toBeUndefined()
})
it('an explicit a:lin without ang keeps the schema default 0', () => {
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:gradFill><a:gsLst>' +
'<a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs>' +
'<a:gs pos="100000"><a:srgbClr val="00FF00"/></a:gs>' +
'</a:gsLst><a:lin scaled="1"/></a:gradFill></p:spPr></p:sp>'
const slide = parseSlide({
path: 'ppt/slides/slide1.xml',
slideXml: slideWith(sp),
ctx: { theme },
})
const el = slide.elements[0] as any
expect(el.fill.angle).toBe(0)
})
it('themed schemeClr with lumMod/lumOff modifier', () => {
const sp =
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="10" cy="10"/></a:xfrm>' +
@@ -14,6 +14,7 @@ import {
replacePictureBytes,
resetSlideBackground,
setSlideBackground,
setShapePresetGeometry,
setSlideBackgroundImage,
setSlideBgGraphicsHidden,
} from '../src/index'
@@ -286,7 +287,7 @@ describe('patchElementStroke', () => {
describe('setSlideBackground', () => {
it('injects <p:bg> and round-trips through save → reopen', async () => {
const opened = await openPptx(await createBlankPptx())
setSlideBackground(opened.deck.slides[0]!, '#1A2B3C')
setSlideBackground(opened, opened.deck.slides[0]!, '#1A2B3C')
expect(opened.deck.slides[0]!.background).toEqual({ type: 'solid', color: '#1A2B3C' })
const reopened = await openPptx(await savePptx(opened))
@@ -296,8 +297,8 @@ describe('setSlideBackground', () => {
it('replaces an existing bg without duplicating', async () => {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
setSlideBackground(slide, '#111111')
setSlideBackground(slide, '#222222')
setSlideBackground(opened, slide, '#111111')
setSlideBackground(opened, slide, '#222222')
expect((slide.bodyPrefix.match(/<p:bg>/g) ?? []).length).toBe(1)
const reopened = await openPptx(await savePptx(opened))
@@ -307,7 +308,7 @@ describe('setSlideBackground', () => {
it('gradient background round-trips through save → reopen', async () => {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
setSlideBackground(slide, {
setSlideBackground(opened, slide, {
stops: [
{ pos: 0, color: '#FF0000' },
{ pos: 1, color: '#0000FF' },
@@ -363,7 +364,7 @@ describe('setSlideBackground', () => {
it('resetSlideBackground removes the override', async () => {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
setSlideBackground(slide, '#112233')
setSlideBackground(opened, slide, '#112233')
resetSlideBackground(opened, slide)
expect(slide.bgOwn).toBeUndefined()
expect(slide.bodyPrefix).not.toContain('<p:bg>')
@@ -389,3 +390,43 @@ describe('setSlideBackground', () => {
expect(reopened2.deck.slides[0]!.masterSpHidden).toBeUndefined()
})
})
describe('setShapePresetGeometry (change shape)', () => {
it('swaps prstGeom keeping fill/transform and round-trips', async () => {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
const el = addElement(slide, { kind: 'rect', offset: { ...OFF }, fillColor: '#4472C4' })
expect(setShapePresetGeometry(slide, el.id, 'star5')).toBe(true)
expect((el as TextElement).presetGeometry).toBe('star5')
expect(el.anchor.originalXml).toContain('<a:prstGeom prst="star5"><a:avLst/></a:prstGeom>')
const reopened = await openPptx(await savePptx(opened))
const saved = reopened.deck.slides[0]!.elements.at(-1) as TextElement
expect(saved.presetGeometry).toBe('star5')
expect(saved.fill).toEqual({ type: 'solid', color: '#4472C4' })
expect(saved.transform).toEqual(el.transform)
})
it('resets adjust values when changing geometry', async () => {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
const el = addElement(slide, { kind: 'roundRect', offset: { ...OFF } })
setShapePresetGeometry(slide, el.id, 'ellipse')
expect((el as TextElement).adjust).toBeUndefined()
expect(el.anchor.originalXml).not.toContain('a:gd')
const reopened = await openPptx(await savePptx(opened))
const saved = reopened.deck.slides[0]!.elements.at(-1) as TextElement
expect(saved.presetGeometry).toBe('ellipse')
})
it('rejects unknown element ids and invalid prst names', async () => {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
const el = addElement(slide, { kind: 'rect', offset: { ...OFF } })
expect(setShapePresetGeometry(slide, 'nope', 'star5')).toBe(false)
expect(setShapePresetGeometry(slide, el.id, 'star5"><hack/>')).toBe(false)
})
})
@@ -72,3 +72,21 @@ describe('buAutoNum startAt (PlanS numbered headings)', () => {
})
})
})
describe('a:grayscl (tdf112209 grayscale picture fill)', () => {
it('maps grayscl to a black-to-white duotone ramp on a pic blip', () => {
const xml = slideWith(pic('<a:grayscl/>'))
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: xml, ctx: {} })
const el = slide.elements[0] as any
expect(el.duotone).toEqual(['#000000', '#FFFFFF'])
})
it('an explicit duotone wins over grayscl', () => {
const xml = slideWith(
pic('<a:grayscl/><a:duotone><a:srgbClr val="112233"/><a:srgbClr val="AABBCC"/></a:duotone>'),
)
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: xml, ctx: {} })
const el = slide.elements[0] as any
expect(el.duotone).toEqual(['#112233', '#AABBCC'])
})
})
@@ -0,0 +1,321 @@
import { describe, expect, it } from 'vitest'
import {
addChart,
addElement,
addMedia,
addModel3d,
addPicture,
createBlankPptx,
deleteElement,
deleteSlide,
duplicateSlide,
groupElements,
openPptx,
replacePictureBytes,
resetSlideBackground,
savePptx,
setElementFill,
setElementImageFill,
setSlideBackground,
setSlideBackgroundImage,
} from '../src/index'
import type { GroupElement, PictureElement } from '../src/types'
import { relsPathFor } from '../src/zip'
const PNG_1PX = new Uint8Array(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAF/gL+XwV2AAAAAElFTkSuQmCC',
'base64',
),
)
const GIF_1PX = new Uint8Array(
Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64'),
)
const OFF = { x: 914400, y: 914400, cx: 3657600, cy: 2057400 }
const mediaParts = (opened: Awaited<ReturnType<typeof openPptx>>) =>
[...opened.archive.entries.keys()].filter((path) => path.startsWith('ppt/media/'))
describe('deleted resource cleanup', () => {
it('removes an unshared picture relationship and media part', async () => {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
const picture = addPicture(opened, slide, { bytes: PNG_1PX, ext: 'png', offset: OFF })!
const mediaPath = picture.mediaRef
expect(opened.archive.entries.has(mediaPath)).toBe(true)
expect(deleteElement(opened, slide, picture.id)).toBe(true)
expect(opened.archive.entries.has(mediaPath)).toBe(false)
expect(opened.archive.readText(relsPathFor(slide.path))).not.toContain('/image"')
const reopened = await openPptx(await savePptx(opened))
expect(mediaParts(reopened)).toEqual([])
})
it('keeps a media part until the final slide reference is deleted', async () => {
const opened = await openPptx(await createBlankPptx())
const first = opened.deck.slides[0]!
const picture = addPicture(opened, first, { bytes: PNG_1PX, ext: 'png', offset: OFF })!
const mediaPath = picture.mediaRef
const second = duplicateSlide(opened, 0)!
const duplicatePicture = second.elements.find((element) => element.type === 'picture')!
expect(deleteElement(opened, first, picture.id)).toBe(true)
expect(opened.archive.entries.has(mediaPath)).toBe(true)
expect(deleteElement(opened, second, duplicatePicture.id)).toBe(true)
expect(opened.archive.entries.has(mediaPath)).toBe(false)
})
it('removes both embedded video relationships, bytes, and poster on element deletion', async () => {
const opened = await openPptx(await createBlankPptx())
const added = addMedia(opened, 0, {
kind: 'video',
bytes: new Uint8Array([0, 0, 0, 24, 0x66, 0x74, 0x79, 0x70]),
ext: 'mp4',
offset: OFF,
})!
expect(mediaParts(opened).length).toBe(2)
expect(deleteElement(opened, added.slide, added.elementId)).toBe(true)
expect(mediaParts(opened)).toEqual([])
const rels = opened.archive.readText(relsPathFor(added.slide.path))!
expect(rels).not.toContain('/video"')
expect(rels).not.toContain('/media"')
expect(rels).not.toContain('/image"')
})
it('removes an unshared chart part and its content-type override', async () => {
const opened = await openPptx(await createBlankPptx())
const added = addChart(opened, 0, {
kind: 'bar',
categories: ['Q1', 'Q2'],
series: [{ name: 'Sales', values: [10, 20] }],
offset: OFF,
})!
const chartPath = [...opened.archive.entries.keys()].find((path) =>
/^ppt\/charts\/chart\d+\.xml$/.test(path),
)!
expect(deleteElement(opened, added.slide, added.elementId)).toBe(true)
expect(opened.archive.entries.has(chartPath)).toBe(false)
expect(opened.archive.readText('[Content_Types].xml')).not.toContain(`PartName="/${chartPath}"`)
})
it('collects a shared 3D model after deleting its final live placeholder', async () => {
const opened = await openPptx(await createBlankPptx())
const added = addModel3d(opened, 0, {
bytes: new Uint8Array([0x67, 0x6c, 0x54, 0x46]),
ext: 'glb',
offset: OFF,
})!
const modelPath = mediaParts(opened).find((path) => path.endsWith('.glb'))!
const second = duplicateSlide(opened, 0)!
const duplicateModel = second.elements.find((element) =>
element.descr?.startsWith('aislides-3d:'),
)!
expect(deleteElement(opened, added.slide, added.elementId)).toBe(true)
expect(opened.archive.entries.has(modelPath)).toBe(true)
expect(deleteElement(opened, second, duplicateModel.id)).toBe(true)
expect(opened.archive.entries.has(modelPath)).toBe(false)
})
it('collects resources owned by a deleted slide', async () => {
const opened = await openPptx(await createBlankPptx())
duplicateSlide(opened, 0)
addMedia(opened, 0, {
kind: 'video',
bytes: new Uint8Array([0, 0, 0, 24, 0x66, 0x74, 0x79, 0x70]),
ext: 'mp4',
offset: OFF,
})
expect(mediaParts(opened).length).toBe(2)
expect(deleteSlide(opened, 0)).toBe(true)
expect(mediaParts(opened)).toEqual([])
expect(opened.deck.slides).toHaveLength(1)
})
})
describe('superseded picture resource cleanup', () => {
it('removes the old picture relationship and media after replacement', async () => {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
const picture = addPicture(opened, slide, { bytes: PNG_1PX, ext: 'png', offset: OFF })!
const oldMedia = picture.mediaRef
const oldRid = /r:embed="([^"]+)"/.exec(picture.anchor.originalXml)![1]!
expect(replacePictureBytes(opened, slide, picture.id, GIF_1PX, 'gif')).toBe(true)
expect(opened.archive.entries.has(oldMedia)).toBe(false)
expect(opened.archive.readText(relsPathFor(slide.path))).not.toContain(`Id="${oldRid}"`)
expect(opened.archive.entries.has((picture as PictureElement).mediaRef)).toBe(true)
})
it('keeps replaced picture media while another slide still uses it', async () => {
const opened = await openPptx(await createBlankPptx())
const first = opened.deck.slides[0]!
const picture = addPicture(opened, first, { bytes: PNG_1PX, ext: 'png', offset: OFF })!
const oldMedia = picture.mediaRef
const second = duplicateSlide(opened, 0)!
const duplicate = second.elements.find((element) => element.type === 'picture')!
expect(replacePictureBytes(opened, first, picture.id, GIF_1PX, 'gif')).toBe(true)
expect(opened.archive.entries.has(oldMedia)).toBe(true)
expect(replacePictureBytes(opened, second, duplicate.id, GIF_1PX, 'gif')).toBe(true)
expect(opened.archive.entries.has(oldMedia)).toBe(false)
})
})
describe('superseded slide background cleanup', () => {
it('collects an old image background when replaced by a new image', async () => {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
const oldMedia = setSlideBackgroundImage(opened, slide, { bytes: PNG_1PX, ext: 'png' })!
const oldRid = /r:embed="([^"]+)"/.exec(slide.bodyPrefix)![1]!
const newMedia = setSlideBackgroundImage(opened, slide, { bytes: GIF_1PX, ext: 'gif' })!
expect(newMedia).not.toBe(oldMedia)
expect(opened.archive.entries.has(oldMedia)).toBe(false)
expect(opened.archive.entries.has(newMedia)).toBe(true)
expect(opened.archive.readText(relsPathFor(slide.path))).not.toContain(`Id="${oldRid}"`)
})
it('collects image backgrounds replaced by solid, gradient, or reset', async () => {
const transitions = [
(opened: Awaited<ReturnType<typeof openPptx>>) =>
setSlideBackground(opened, opened.deck.slides[0]!, '#112233'),
(opened: Awaited<ReturnType<typeof openPptx>>) =>
setSlideBackground(opened, opened.deck.slides[0]!, {
stops: [
{ pos: 0, color: '#112233' },
{ pos: 1, color: '#445566' },
],
angle: 5400000,
}),
(opened: Awaited<ReturnType<typeof openPptx>>) =>
resetSlideBackground(opened, opened.deck.slides[0]!),
]
for (const transition of transitions) {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
const oldMedia = setSlideBackgroundImage(opened, slide, { bytes: PNG_1PX, ext: 'png' })!
transition(opened)
expect(opened.archive.entries.has(oldMedia)).toBe(false)
expect(opened.archive.readText(relsPathFor(slide.path))).not.toContain('/image"')
}
})
it('preserves shared background media until the final slide drops it', async () => {
const opened = await openPptx(await createBlankPptx())
const first = opened.deck.slides[0]!
const media = setSlideBackgroundImage(opened, first, { bytes: PNG_1PX, ext: 'png' })!
const second = duplicateSlide(opened, 0)!
setSlideBackground(opened, first, '#112233')
expect(opened.archive.entries.has(media)).toBe(true)
resetSlideBackground(opened, second)
expect(opened.archive.entries.has(media)).toBe(false)
})
})
describe('superseded shape picture-fill cleanup', () => {
function addShape(opened: Awaited<ReturnType<typeof openPptx>>, x = 0) {
return addElement(opened.deck.slides[0]!, {
kind: 'rect',
offset: { ...OFF, x },
fillColor: '#112233',
})
}
it('collects an old picture fill when replaced by a new image', async () => {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
const shape = addShape(opened)
const oldMedia = setElementImageFill(opened, slide, shape.id, {
bytes: PNG_1PX,
ext: 'png',
})!
const newMedia = setElementImageFill(opened, slide, shape.id, {
bytes: GIF_1PX,
ext: 'gif',
})!
expect(newMedia).not.toBe(oldMedia)
expect(opened.archive.entries.has(oldMedia)).toBe(false)
expect(opened.archive.entries.has(newMedia)).toBe(true)
})
it('collects picture fills replaced by solid, gradient, or none', async () => {
const fills = [
'#112233',
{
stops: [
{ pos: 0, color: '#112233' },
{ pos: 1, color: '#445566' },
],
angle: 5400000,
},
'none',
]
for (const fill of fills) {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
const shape = addShape(opened)
const oldMedia = setElementImageFill(opened, slide, shape.id, {
bytes: PNG_1PX,
ext: 'png',
})!
expect(setElementFill(opened, slide, shape.id, fill)).toBe(true)
expect(opened.archive.entries.has(oldMedia)).toBe(false)
expect(opened.archive.readText(relsPathFor(slide.path))).not.toContain('/image"')
}
})
it('preserves shared fill media until the final shape drops it', async () => {
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
const first = addShape(opened)
const second = addShape(opened, 4000000)
const media = setElementImageFill(opened, slide, first.id, {
bytes: PNG_1PX,
ext: 'png',
})!
setElementImageFill(opened, slide, second.id, { mediaPath: media })
expect(setElementFill(opened, slide, first.id, '#112233')).toBe(true)
expect(opened.archive.entries.has(media)).toBe(true)
expect(setElementFill(opened, slide, second.id, 'none')).toBe(true)
expect(opened.archive.entries.has(media)).toBe(false)
})
it('cleans a superseded picture fill on a group child', async () => {
const opened = await openPptx(await createBlankPptx())
const first = addShape(opened)
const second = addShape(opened, 4000000)
const grouped = groupElements(opened, 0, [first.id, second.id])!
const slide = grouped.slide
const group = slide.elements.find((element) => element.id === grouped.groupId) as GroupElement
const child = group.children.find((element) => element.type === 'shape')!
const media = setElementImageFill(
opened,
slide,
child.id,
{ bytes: PNG_1PX, ext: 'png' },
{ groupId: group.id },
)!
expect(
setElementFill(opened, slide, child.id, '#112233', {
groupId: group.id,
}),
).toBe(true)
expect(opened.archive.entries.has(media)).toBe(false)
})
})
@@ -10,14 +10,17 @@ import { parseSlide } from '../src/parse'
import {
openPptx,
savePptx,
cleanupSupersededSlideResources,
duplicateSlide,
ensureRunLinkRels,
getRunLinks,
patchSlideXml,
patchTextElementXml,
type OpenedPptx,
type TextElement,
} from '../src/index'
import type { Theme } from '../src/theme'
import { relsPathFor } from '../src/zip'
const here = dirname(fileURLToPath(import.meta.url))
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
@@ -187,4 +190,48 @@ describe('ensureRunLinkRels + save round-trip', () => {
target: { kind: 'url', url: 'https://live.example/' },
})
})
it('prunes obsolete run hyperlink relationships on replace and clear', async () => {
let opened = await openPptx(fx('01_standard_business.pptx'))
let found = findTextRun(opened)
let slide = opened.deck.slides[0]!
let previousXml = patchSlideXml(slide)
let run = found.el.text!.paragraphs[found.pi]!.runs[found.ri]!
run.hyperlink = 'https://old.run.dev'
delete run.hyperlinkRId
ensureRunLinkRels(opened, 0, found.el.text!.paragraphs)
found.el.dirty = true
cleanupSupersededSlideResources(opened, slide, previousXml, patchSlideXml(slide))
opened = await openPptx(await savePptx(opened))
found = findTextRun(opened)
slide = opened.deck.slides[0]!
run = found.el.text!.paragraphs[found.pi]!.runs[found.ri]!
const oldRid = run.hyperlinkRId!
previousXml = patchSlideXml(slide)
run.hyperlink = 'https://new.run.dev'
delete run.hyperlinkRId
delete run.hyperlinkAction
ensureRunLinkRels(opened, 0, found.el.text!.paragraphs)
found.el.dirty = true
cleanupSupersededSlideResources(opened, slide, previousXml, patchSlideXml(slide))
let rels = opened.archive.readText(relsPathFor(slide.path))!
expect(rels).not.toContain(`Id="${oldRid}"`)
expect(rels).not.toContain('Target="https://old.run.dev"')
expect(rels).toContain('Target="https://new.run.dev"')
const newRid = run.hyperlinkRId!
previousXml = patchSlideXml(slide)
delete run.hyperlink
delete run.hyperlinkRId
delete run.hyperlinkAction
delete run.hyperlinkTooltip
found.el.dirty = true
cleanupSupersededSlideResources(opened, slide, previousXml, patchSlideXml(slide))
rels = opened.archive.readText(relsPathFor(slide.path))!
expect(rels).not.toContain(`Id="${newRid}"`)
expect(rels).not.toContain('Target="https://new.run.dev"')
})
})
@@ -0,0 +1,65 @@
import { describe, it, expect } from 'vitest'
import { parseSlide } from '../src/parse'
const SLIDE_NS =
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"'
function spWith(spPrInner: string): string {
return (
`<p:sp><p:nvSpPr><p:cNvPr id="2" name="s"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm>` +
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` +
spPrInner +
`</p:spPr></p:sp>`
)
}
function parseSp(spPrInner: string): any {
const slideXml =
`<?xml version="1.0"?><p:sld ${SLIDE_NS}><p:cSld><p:spTree>` +
`<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/>` +
spWith(spPrInner) +
`</p:spTree></p:cSld></p:sld>`
return parseSlide({ path: 'ppt/slides/slide1.xml', slideXml, ctx: {} }).elements[0]
}
describe('parseSlide attaches scene3d', () => {
it('camera preset + light rig + sp3d extrusion', () => {
const el = parseSp(
`<a:scene3d><a:camera prst="isometricRightUp"/><a:lightRig rig="threePt" dir="t"/></a:scene3d>` +
`<a:sp3d extrusionH="457200"/>`,
)
expect(el.scene3d).toEqual({
cameraPreset: 'isometricRightUp',
lightRig: 'threePt',
lightDir: 't',
extrusionEmu: 457200,
})
})
it('camera/light rotation overrides, z shift, material, extrusion color', () => {
const el = parseSp(
`<a:scene3d><a:camera prst="orthographicFront"><a:rot lat="0" lon="13499976" rev="0"/></a:camera>` +
`<a:lightRig rig="twoPt" dir="t"><a:rot lat="0" lon="0" rev="5400000"/></a:lightRig></a:scene3d>` +
`<a:sp3d z="228600" extrusionH="914400" prstMaterial="legacyWireframe">` +
`<a:extrusionClr><a:srgbClr val="00FFFF"/></a:extrusionClr></a:sp3d>`,
)
expect(el.scene3d).toEqual({
cameraPreset: 'orthographicFront',
cameraRot: { lat: 0, lon: 13499976, rev: 0 },
lightRig: 'twoPt',
lightDir: 't',
lightRot: { lat: 0, lon: 0, rev: 5400000 },
extrusionEmu: 914400,
zEmu: 228600,
extrusionColor: '#00FFFF',
material: 'legacyWireframe',
})
})
it('no scene3d → field absent; sp3d without a camera is ignored', () => {
expect(parseSp('').scene3d).toBeUndefined()
expect(parseSp('<a:sp3d extrusionH="914400"/>').scene3d).toBeUndefined()
})
})
+52 -1
View File
@@ -139,7 +139,7 @@ describe('setElementImageFill', () => {
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
'base64',
)
const mediaPath = setElementImageFill(opened, slide, r.id, png, 'png')
const mediaPath = setElementImageFill(opened, slide, r.id, { bytes: png, ext: 'png' })
expect(mediaPath).toMatch(/^ppt\/media\/image\d+\.png$/)
const el = slide.elements.find((e) => e.id === r.id)!
expect(el.anchor.originalXml).toContain('<a:blipFill rotWithShape="1"><a:blip r:embed="rId')
@@ -152,4 +152,55 @@ describe('setElementImageFill', () => {
const reopened = await openPptx(await savePptx(opened))
expect(reopened.archive.entries.has(mediaPath!)).toBe(true)
})
it('tile mode + landed-media reuse: second shape adds no media part, both tile', async () => {
const { setElementImageFill } = await import('../src/index')
const opened = await openPptx(await createBlankPptx())
const slide = opened.deck.slides[0]!
const a = addElement(slide, {
kind: 'rect',
offset: { x: 0, y: 0, cx: 1000, cy: 1000 },
fillColor: '#FF0000',
})
const b = addElement(slide, {
kind: 'rect',
offset: { x: 2000, y: 0, cx: 1000, cy: 1000 },
fillColor: '#00FF00',
})
const png = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
'base64',
)
const mediaCount = () =>
[...opened.archive.entries.keys()].filter((p) => p.startsWith('ppt/media/')).length
const before = mediaCount()
const landed = setElementImageFill(
opened,
slide,
a.id,
{ bytes: png, ext: 'png' },
{
tile: true,
},
)
expect(landed).toMatch(/^ppt\/media\/image\d+\.png$/)
expect(mediaCount()).toBe(before + 1)
// second target reuses the landed part: only a fill swap, no new media
const reused = setElementImageFill(opened, slide, b.id, { mediaPath: landed! }, { tile: true })
expect(reused).toBe(landed)
expect(mediaCount()).toBe(before + 1)
for (const id of [a.id, b.id]) {
const el = slide.elements.find((e) => e.id === id)!
expect(el.anchor.originalXml).toContain('<a:tile')
// tile metrics mirror what parse restores, so pre-save render scales tiles correctly
expect((el as import('../src/types').TextElement).fill).toMatchObject({
type: 'image',
mode: 'tile',
tile: { tx: 0, ty: 0, sx: 1, sy: 1, algn: 'tl' },
})
}
// a failed lookup must not land an orphaned media part
expect(setElementImageFill(opened, slide, 'no-such-id', { bytes: png, ext: 'png' })).toBeNull()
expect(mediaCount()).toBe(before + 1)
})
})
@@ -94,6 +94,20 @@ describe('tableStyles.xml custom styles', () => {
expect(resolveTableStyle(undefined, xml, theme)).toBeUndefined()
})
it('a populated part without the referenced built-in id renders unstyled; an empty part keeps the built-in', () => {
// PowerPoint-measured: the built-in gallery only backs a def-id-only part
expect(resolveTableStyle(MEDIUM2_A1, xml, theme)).toBeUndefined()
const emptyPart = `<?xml version="1.0"?><a:tblStyleLst xmlns:a="a" def="${MEDIUM2_A1}"/>`
expect(resolveTableStyle(MEDIUM2_A1, emptyPart, theme)?.firstRow?.fill).toEqual({
type: 'solid',
color: '#4472C4',
})
expect(resolveTableStyle(MEDIUM2_A1, undefined, theme)?.firstRow?.fill).toEqual({
type: 'solid',
color: '#4472C4',
})
})
it('tblBg fillRef + alpha band fills + lnRef borders (bnc480256)', () => {
const themed = {
...theme,
@@ -0,0 +1,69 @@
import { describe, it, expect } from 'vitest'
import { parseSlide } from '../src/parse'
import type { TextElement } from '../src/types'
const slideWith = (sp: string) =>
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld>' +
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${sp}</p:spTree></p:cSld></p:sld>`
const parseEl = (bodyPr: string, runs: string) => {
const sp =
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
`<p:txBody>${bodyPr}<a:p>${runs}</a:p></p:txBody></p:sp>`
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(sp), ctx: {} })
return slide.elements[0] as TextElement
}
describe('WordArt run effects', () => {
it('parses gradient text fill with a mid-stop fallback color', () => {
const el = parseEl(
'<a:bodyPr/>',
'<a:r><a:rPr lang="en"><a:gradFill><a:gsLst>' +
'<a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs>' +
'<a:gs pos="50000"><a:srgbClr val="00FF00"/></a:gs>' +
'<a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs>' +
'</a:gsLst><a:lin ang="5400000"/></a:gradFill></a:rPr><a:t>W</a:t></a:r>',
)
const r = el.text!.paragraphs[0]!.runs[0]!
expect(r.gradient?.stops.map((s) => s.color)).toEqual(['#FF0000', '#00FF00', '#0000FF'])
expect(r.gradient?.angle).toBe(5400000)
expect(r.color).toBe('#00FF00')
})
it('parses run glow and reflection', () => {
const el = parseEl(
'<a:bodyPr/>',
'<a:r><a:rPr lang="en"><a:effectLst>' +
'<a:glow rad="53100"><a:srgbClr val="ED7D31"/></a:glow>' +
'<a:reflection blurRad="12700" stA="50000"/>' +
'</a:effectLst></a:rPr><a:t>W</a:t></a:r>',
)
const r = el.text!.paragraphs[0]!.runs[0]!
expect(r.glow).toEqual({ color: '#ED7D31', radius: 53100 })
expect(r.reflection).toBe(true)
})
it('parses bodyPr text extrusion (sp3d + camera tilt)', () => {
const el = parseEl(
'<a:bodyPr><a:scene3d><a:camera prst="orthographicFront"><a:rot lat="1800000" lon="0" rev="0"/></a:camera>' +
'<a:lightRig rig="threePt" dir="t"/></a:scene3d>' +
'<a:sp3d extrusionH="127000"><a:extrusionClr><a:srgbClr val="C0504D"/></a:extrusionClr></a:sp3d></a:bodyPr>',
'<a:r><a:rPr lang="en"/><a:t>W</a:t></a:r>',
)
expect(el.text!.extrusion3d).toEqual({
color: '#C0504D',
depthEmu: 127000,
latDeg: 30,
lonDeg: 0,
})
})
it('no effects → fields absent', () => {
const el = parseEl('<a:bodyPr/>', '<a:r><a:rPr lang="en"/><a:t>W</a:t></a:r>')
const r = el.text!.paragraphs[0]!.runs[0]!
expect(r.gradient).toBeUndefined()
expect(r.glow).toBeUndefined()
expect(r.reflection).toBeUndefined()
expect(el.text!.extrusion3d).toBeUndefined()
})
})