Initial public release
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@genoffice/pptx-engine",
|
||||
"version": "0.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "pptx parsing (Slide element tree with byte anchors + inheritance resolution), OOXML fragment generation, element-patch save",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./table-grid": "./src/table-grid.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"fast-xml-parser": "^5.3.4",
|
||||
"jszip": "^3.10.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.10.1",
|
||||
"pptxgenjs": "^4.0.1",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Element alignment and even distribution — pure geometry functions (no IO, no
|
||||
* model dependencies).
|
||||
*
|
||||
* Coordinate system: input/output are axis-aligned rects { x, y, w, h } in CSS px
|
||||
* (no rotation). Maps directly to the render layer's NodeBox (equivalent to
|
||||
* PlacedBox without rotation), so the UI layer can call it directly.
|
||||
*
|
||||
* Design:
|
||||
* - All 6 alignments are relative to the selection's bounding box (multi-select)
|
||||
* or the page (single-select).
|
||||
* - The 2 distributions (horizontal/vertical) spread spacing evenly; require ≥3 elements.
|
||||
* - Returns each element's new { x, y } (w/h unchanged); only elements whose
|
||||
* position changes appear in the result.
|
||||
*/
|
||||
|
||||
export interface AlignRect {
|
||||
x: number
|
||||
y: number
|
||||
w: number
|
||||
h: number
|
||||
}
|
||||
|
||||
export type AlignKind = 'left' | 'center-h' | 'right' | 'top' | 'center-v' | 'bottom'
|
||||
|
||||
export type DistributeKind = 'horizontal' | 'vertical'
|
||||
|
||||
// ── Internal helpers ────────────────────────────────────────────────────────
|
||||
|
||||
/** Axis-aligned bounding box */
|
||||
function boundingBox(rects: AlignRect[]): AlignRect {
|
||||
let minX = Infinity,
|
||||
minY = Infinity,
|
||||
maxX = -Infinity,
|
||||
maxY = -Infinity
|
||||
for (const r of rects) {
|
||||
minX = Math.min(minX, r.x)
|
||||
minY = Math.min(minY, r.y)
|
||||
maxX = Math.max(maxX, r.x + r.w)
|
||||
maxY = Math.max(maxY, r.y + r.h)
|
||||
}
|
||||
return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }
|
||||
}
|
||||
|
||||
// ── Public API ───────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Compute each element's new x/y coordinates after alignment.
|
||||
*
|
||||
* @param rects element rects (px), in the same order as their ids
|
||||
* @param kind alignment type
|
||||
* @param containerRect the page rect (in slide coordinates) for single-select;
|
||||
* null for multi-select → align relative to the selection's
|
||||
* bounding box
|
||||
* @returns each element's new { x, y } (same order as rects)
|
||||
*/
|
||||
export function alignRects(
|
||||
rects: AlignRect[],
|
||||
kind: AlignKind,
|
||||
containerRect: AlignRect | null,
|
||||
): Array<{ x: number; y: number }> {
|
||||
const box = containerRect ?? boundingBox(rects)
|
||||
|
||||
return rects.map((r) => {
|
||||
let x = r.x
|
||||
let y = r.y
|
||||
switch (kind) {
|
||||
case 'left':
|
||||
x = box.x
|
||||
break
|
||||
case 'center-h':
|
||||
x = box.x + (box.w - r.w) / 2
|
||||
break
|
||||
case 'right':
|
||||
x = box.x + box.w - r.w
|
||||
break
|
||||
case 'top':
|
||||
y = box.y
|
||||
break
|
||||
case 'center-v':
|
||||
y = box.y + (box.h - r.h) / 2
|
||||
break
|
||||
case 'bottom':
|
||||
y = box.y + box.h - r.h
|
||||
break
|
||||
}
|
||||
return { x, y }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute each element's new x/y after even distribution (only the coordinate
|
||||
* along the distribution axis changes).
|
||||
*
|
||||
* Distribution rule: the two end elements stay put, middle elements are spaced
|
||||
* evenly (divided by element centers).
|
||||
*
|
||||
* Requires rects.length ≥ 3; with fewer than 3 returns as-is (meaningless operation).
|
||||
*
|
||||
* @param rects element rects
|
||||
* @param kind 'horizontal' | 'vertical'
|
||||
* @returns each element's new { x, y } (same order as rects)
|
||||
*/
|
||||
export function distributeRects(
|
||||
rects: AlignRect[],
|
||||
kind: DistributeKind,
|
||||
): Array<{ x: number; y: number }> {
|
||||
if (rects.length < 3) return rects.map((r) => ({ x: r.x, y: r.y }))
|
||||
|
||||
if (kind === 'horizontal') {
|
||||
// Sort by left x to find the two ends
|
||||
const indexed = rects.map((r, i) => ({ r, i })).sort((a, b) => a.r.x - b.r.x)
|
||||
const first = indexed[0]!
|
||||
const last = indexed[indexed.length - 1]!
|
||||
const totalSpan = last.r.x + last.r.w - first.r.x
|
||||
const totalWidth = indexed.reduce((s, { r }) => s + r.w, 0)
|
||||
const gap = (totalSpan - totalWidth) / (rects.length - 1)
|
||||
const result: Array<{ x: number; y: number }> = rects.map((r) => ({ x: r.x, y: r.y }))
|
||||
let cursor = first.r.x
|
||||
for (const { r, i } of indexed) {
|
||||
result[i] = { x: cursor, y: rects[i]!.y }
|
||||
cursor += r.w + gap
|
||||
}
|
||||
return result
|
||||
} else {
|
||||
// Sort by top y
|
||||
const indexed = rects.map((r, i) => ({ r, i })).sort((a, b) => a.r.y - b.r.y)
|
||||
const first = indexed[0]!
|
||||
const last = indexed[indexed.length - 1]!
|
||||
const totalSpan = last.r.y + last.r.h - first.r.y
|
||||
const totalHeight = indexed.reduce((s, { r }) => s + r.h, 0)
|
||||
const gap = (totalSpan - totalHeight) / (rects.length - 1)
|
||||
const result: Array<{ x: number; y: number }> = rects.map((r) => ({ x: r.x, y: r.y }))
|
||||
let cursor = first.r.y
|
||||
for (const { r, i } of indexed) {
|
||||
result[i] = { x: rects[i]!.x, y: cursor }
|
||||
cursor += r.h + gap
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,891 @@
|
||||
/**
|
||||
* Shape animation (<p:timing>) read/write — the engine layer behind PowerPoint's
|
||||
* "Animations" tab.
|
||||
*
|
||||
* Model: a slide's animations are an ordered list SlideAnimation[], each item =
|
||||
* target shape (spid) + effect + trigger (onClick/withPrev/afterPrev) +
|
||||
* duration/delay. On write-back the whole <p:timing> is rebuilt (tmRoot → mainSeq
|
||||
* → one par per "click group" → one par per effect), structurally identical to
|
||||
* the skeleton PowerPoint itself generates, so the saved pptx plays directly in
|
||||
* PowerPoint.
|
||||
*
|
||||
* spid targeting: OOXML animations use <p:spTgt spid="N"/> pointing at the shape's
|
||||
* <p:cNvPr id="N">. The editor's element ids are transient (they change on
|
||||
* reparse), so elementSpid() extracts the stable cNvPr id from the element's raw
|
||||
* bytes for the mapping.
|
||||
*
|
||||
* Read-back: parsing our own generated skeleton round-trips losslessly; complex
|
||||
* timings generated by PowerPoint get a best-effort downgrade (unmodeled presetIDs
|
||||
* map to a similar effect in the same class).
|
||||
*/
|
||||
import type { Slide, SlideElement } from './types'
|
||||
|
||||
export type AnimEffectKind =
|
||||
// Entrance
|
||||
| 'appear'
|
||||
| 'fade'
|
||||
| 'flyIn'
|
||||
| 'wipe'
|
||||
| 'wipeDown'
|
||||
| 'splitIn'
|
||||
| 'bounce'
|
||||
| 'flipIn'
|
||||
| 'zoom'
|
||||
// Emphasis
|
||||
| 'pulse'
|
||||
| 'spin'
|
||||
| 'grow'
|
||||
| 'teeter'
|
||||
// Exit
|
||||
| 'disappear'
|
||||
| 'fadeOut'
|
||||
| 'flyOut'
|
||||
| 'wipeOut'
|
||||
| 'shrink'
|
||||
| 'zoomOut'
|
||||
// Motion path (move along a path)
|
||||
| 'motionPath'
|
||||
|
||||
export type AnimTrigger = 'onClick' | 'withPrev' | 'afterPrev'
|
||||
export type AnimClass = 'entrance' | 'emphasis' | 'exit' | 'path'
|
||||
|
||||
export interface SlideAnimation {
|
||||
/** Target shape's cNvPr id (<p:spTgt spid>) */
|
||||
spid: number
|
||||
effect: AnimEffectKind
|
||||
trigger: AnimTrigger
|
||||
durationMs: number
|
||||
delayMs: number
|
||||
/**
|
||||
* Motion path (valid when effect='motionPath'): SVG subset M/L/C/Z,
|
||||
* coordinates 0..1 relative to slide width/height (same as OOXML animMotion's
|
||||
* relative path).
|
||||
*/
|
||||
motionPath?: string
|
||||
/** Per-paragraph animation: 0-based paragraph number (written as pgRg st/end); unset = whole shape */
|
||||
paragraph?: number
|
||||
}
|
||||
|
||||
/** Effect → class (entrance/emphasis/exit/motion path). */
|
||||
export function animClassOf(effect: AnimEffectKind): AnimClass {
|
||||
switch (effect) {
|
||||
case 'appear':
|
||||
case 'fade':
|
||||
case 'flyIn':
|
||||
case 'wipe':
|
||||
case 'wipeDown':
|
||||
case 'splitIn':
|
||||
case 'bounce':
|
||||
case 'flipIn':
|
||||
case 'zoom':
|
||||
return 'entrance'
|
||||
case 'pulse':
|
||||
case 'spin':
|
||||
case 'grow':
|
||||
case 'teeter':
|
||||
return 'emphasis'
|
||||
case 'motionPath':
|
||||
return 'path'
|
||||
default:
|
||||
return 'exit'
|
||||
}
|
||||
}
|
||||
|
||||
/** Extract the element's own <p:cNvPr id> from its raw bytes (the first one is the element itself; group children follow). */
|
||||
export function elementSpid(el: SlideElement): number | null {
|
||||
const m = /<p:cNvPr\s[^>]*\bid="(\d+)"/.exec(el.anchor.originalXml)
|
||||
return m ? Number(m[1]) : null
|
||||
}
|
||||
|
||||
// ── Write: SlideAnimation[] → <p:timing> ───────────────────────────────
|
||||
|
||||
/** presetID/presetClass/presetSubtype (used by PowerPoint's animation pane to show effect names). */
|
||||
const PRESET: Record<AnimEffectKind, { id: number; cls: 'entr' | 'emph' | 'exit' | 'path'; sub: number }> = {
|
||||
appear: { id: 1, cls: 'entr', sub: 0 },
|
||||
fade: { id: 10, cls: 'entr', sub: 0 },
|
||||
flyIn: { id: 2, cls: 'entr', sub: 4 }, // from bottom
|
||||
wipe: { id: 22, cls: 'entr', sub: 1 }, // from bottom
|
||||
wipeDown: { id: 22, cls: 'entr', sub: 4 }, // from top
|
||||
splitIn: { id: 16, cls: 'entr', sub: 21 }, // expand left/right from center
|
||||
bounce: { id: 26, cls: 'entr', sub: 0 },
|
||||
flipIn: { id: 30, cls: 'entr', sub: 0 }, // flip in from far to near (Grow & Turn)
|
||||
zoom: { id: 23, cls: 'entr', sub: 16 },
|
||||
pulse: { id: 26, cls: 'emph', sub: 0 },
|
||||
spin: { id: 8, cls: 'emph', sub: 0 },
|
||||
grow: { id: 6, cls: 'emph', sub: 0 },
|
||||
teeter: { id: 32, cls: 'emph', sub: 0 },
|
||||
disappear: { id: 1, cls: 'exit', sub: 0 },
|
||||
fadeOut: { id: 10, cls: 'exit', sub: 0 },
|
||||
flyOut: { id: 2, cls: 'exit', sub: 4 }, // to bottom
|
||||
wipeOut: { id: 22, cls: 'exit', sub: 1 },
|
||||
shrink: { id: 30, cls: 'exit', sub: 0 }, // shrink and rotate (Shrink & Turn)
|
||||
zoomOut: { id: 23, cls: 'exit', sub: 16 },
|
||||
motionPath: { id: 0, cls: 'path', sub: 0 }, // custom path
|
||||
}
|
||||
|
||||
/** presetClass:presetID(:presetSubtype) → effect (read-back mapping; unmodeled ones map to a same-class approximation). */
|
||||
function effectFromPreset(cls: string, id: number, sub: number): AnimEffectKind {
|
||||
if (cls === 'path') return 'motionPath'
|
||||
// Effects sharing a presetID distinguished by subtype (e.g. wipe direction)
|
||||
const bySub: Record<string, AnimEffectKind> = {
|
||||
'entr:22:1': 'wipe',
|
||||
'entr:22:4': 'wipeDown',
|
||||
}
|
||||
const exact: Record<string, AnimEffectKind> = {
|
||||
'entr:1': 'appear',
|
||||
'entr:10': 'fade',
|
||||
'entr:2': 'flyIn',
|
||||
'entr:22': 'wipe',
|
||||
'entr:16': 'splitIn',
|
||||
'entr:26': 'bounce',
|
||||
'entr:30': 'flipIn',
|
||||
'entr:23': 'zoom',
|
||||
'emph:26': 'pulse',
|
||||
'emph:8': 'spin',
|
||||
'emph:6': 'grow',
|
||||
'emph:32': 'teeter',
|
||||
'exit:1': 'disappear',
|
||||
'exit:10': 'fadeOut',
|
||||
'exit:2': 'flyOut',
|
||||
'exit:22': 'wipeOut',
|
||||
'exit:30': 'shrink',
|
||||
'exit:23': 'zoomOut',
|
||||
}
|
||||
const hit = bySub[`${cls}:${id}:${sub}`] ?? exact[`${cls}:${id}`]
|
||||
if (hit) return hit
|
||||
if (cls === 'exit') return 'fadeOut'
|
||||
if (cls === 'emph') return 'pulse'
|
||||
return 'fade'
|
||||
}
|
||||
|
||||
const NODE_TYPE: Record<AnimTrigger, string> = {
|
||||
onClick: 'clickEffect',
|
||||
withPrev: 'withEffect',
|
||||
afterPrev: 'afterEffect',
|
||||
}
|
||||
|
||||
interface IdGen {
|
||||
next: () => number
|
||||
}
|
||||
|
||||
/**
|
||||
* Behavior target <p:tgtEl>. With paragraph, adds txEl/pgRg: ECMA-376
|
||||
* CT_IndexRange's st/end are 0-based paragraph indices (files generated by
|
||||
* PowerPoint use st="0" for the first paragraph), mapping directly.
|
||||
*/
|
||||
function tgtElXml(a: SlideAnimation): string {
|
||||
const inner =
|
||||
a.paragraph == null
|
||||
? `<p:spTgt spid="${a.spid}"/>`
|
||||
: `<p:spTgt spid="${a.spid}"><p:txEl><p:pgRg st="${a.paragraph}" end="${a.paragraph}"/></p:txEl></p:spTgt>`
|
||||
return `<p:tgtEl>${inner}</p:tgtEl>`
|
||||
}
|
||||
|
||||
/** Set style.visibility (entrance=visible / exit=hidden). delay is relative to the effect start. */
|
||||
function setVisibilityXml(gen: IdGen, tgt: string, visible: boolean, delayMs: number): string {
|
||||
return (
|
||||
'<p:set><p:cBhvr>' +
|
||||
`<p:cTn id="${gen.next()}" dur="1" fill="hold"><p:stCondLst><p:cond delay="${delayMs}"/></p:stCondLst></p:cTn>` +
|
||||
tgt +
|
||||
'<p:attrNameLst><p:attrName>style.visibility</p:attrName></p:attrNameLst>' +
|
||||
`</p:cBhvr><p:to><p:strVal val="${visible ? 'visible' : 'hidden'}"/></p:to></p:set>`
|
||||
)
|
||||
}
|
||||
|
||||
/** Attribute keyframe animation (tm is a per-mille time point 0..100000, val a formula string). */
|
||||
function keyframeAnimXml(
|
||||
gen: IdGen,
|
||||
tgt: string,
|
||||
dur: number,
|
||||
attr: string,
|
||||
frames: Array<[tm: number, val: string]>,
|
||||
): string {
|
||||
const tavs = frames
|
||||
.map(([tm, val]) => `<p:tav tm="${tm}"><p:val><p:strVal val="${val}"/></p:val></p:tav>`)
|
||||
.join('')
|
||||
return (
|
||||
'<p:anim calcmode="lin" valueType="num">' +
|
||||
`<p:cBhvr additive="base"><p:cTn id="${gen.next()}" dur="${dur}" fill="hold"/>` +
|
||||
tgt +
|
||||
`<p:attrNameLst><p:attrName>${attr}</p:attrName></p:attrNameLst></p:cBhvr>` +
|
||||
`<p:tavLst>${tavs}</p:tavLst></p:anim>`
|
||||
)
|
||||
}
|
||||
|
||||
/** ppt_x/ppt_y translation animation (for fly in/out). */
|
||||
function moveAnimXml(gen: IdGen, tgt: string, dur: number, attr: 'ppt_x' | 'ppt_y', from: string, to: string): string {
|
||||
return keyframeAnimXml(gen, tgt, dur, attr, [
|
||||
[0, from],
|
||||
[100000, to],
|
||||
])
|
||||
}
|
||||
|
||||
/** Default motionPath (straight line to the right, 1/4 of the slide width). */
|
||||
export const DEFAULT_MOTION_PATH = 'M 0 0 L 0.25 0'
|
||||
|
||||
/** Move along a path (<p:animMotion>); the path gets the " E" end marker per OOXML convention. */
|
||||
function motionAnimXml(gen: IdGen, tgt: string, dur: number, path: string): string {
|
||||
const p = path.trim() || DEFAULT_MOTION_PATH
|
||||
const pathAttr = /\bE$/.test(p) ? p : `${p} E`
|
||||
return (
|
||||
`<p:animMotion origin="layout" path="${pathAttr}" pathEditMode="relative">` +
|
||||
`<p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}" fill="hold"/>` +
|
||||
tgt +
|
||||
'<p:attrNameLst><p:attrName>ppt_x</p:attrName><p:attrName>ppt_y</p:attrName></p:attrNameLst>' +
|
||||
'</p:cBhvr></p:animMotion>'
|
||||
)
|
||||
}
|
||||
|
||||
/** Behavior list of one effect (a combination of set/animEffect/anim/animScale/animRot). */
|
||||
function effectBehaviorsXml(gen: IdGen, a: SlideAnimation): string {
|
||||
const dur = Math.max(1, Math.round(a.durationMs))
|
||||
const target = tgtElXml(a)
|
||||
const show = setVisibilityXml(gen, target, true, 0)
|
||||
const hideAtEnd = setVisibilityXml(gen, target, false, Math.max(0, dur - 1))
|
||||
switch (a.effect) {
|
||||
case 'appear':
|
||||
return show
|
||||
case 'fade':
|
||||
return (
|
||||
show +
|
||||
`<p:animEffect transition="in" filter="fade"><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}"/>${target}</p:cBhvr></p:animEffect>`
|
||||
)
|
||||
case 'flyIn':
|
||||
return (
|
||||
show +
|
||||
moveAnimXml(gen, target, dur, 'ppt_x', '#ppt_x', '#ppt_x') +
|
||||
moveAnimXml(gen, target, dur, 'ppt_y', '1+#ppt_h/2', '#ppt_y')
|
||||
)
|
||||
case 'wipe':
|
||||
return (
|
||||
show +
|
||||
`<p:animEffect transition="in" filter="wipe(up)"><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}"/>${target}</p:cBhvr></p:animEffect>`
|
||||
)
|
||||
case 'wipeDown':
|
||||
return (
|
||||
show +
|
||||
`<p:animEffect transition="in" filter="wipe(down)"><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}"/>${target}</p:cBhvr></p:animEffect>`
|
||||
)
|
||||
case 'splitIn':
|
||||
return (
|
||||
show +
|
||||
`<p:animEffect transition="in" filter="split(inHorizontal)"><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}"/>${target}</p:cBhvr></p:animEffect>`
|
||||
)
|
||||
case 'bounce':
|
||||
// Drop from above + damped rebound (ppt_y keyframes approximating PowerPoint's bounce)
|
||||
return (
|
||||
show +
|
||||
keyframeAnimXml(gen, target, dur, 'ppt_y', [
|
||||
[0, '#ppt_y-0.25'],
|
||||
[55000, '#ppt_y'],
|
||||
[70000, '#ppt_y-0.08'],
|
||||
[85000, '#ppt_y'],
|
||||
[92000, '#ppt_y-0.03'],
|
||||
[100000, '#ppt_y'],
|
||||
])
|
||||
)
|
||||
case 'flipIn':
|
||||
// Expand horizontally from 0 + fade in (approximation of Grow & Turn)
|
||||
return (
|
||||
show +
|
||||
`<p:animEffect transition="in" filter="fade"><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}"/>${target}</p:cBhvr></p:animEffect>` +
|
||||
`<p:animScale><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}" fill="hold"/>${target}</p:cBhvr>` +
|
||||
'<p:from x="0" y="100000"/><p:to x="100000" y="100000"/></p:animScale>'
|
||||
)
|
||||
case 'zoom':
|
||||
return (
|
||||
show +
|
||||
`<p:animScale><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}" fill="hold"/>${target}</p:cBhvr>` +
|
||||
'<p:from x="0" y="0"/><p:to x="100000" y="100000"/></p:animScale>'
|
||||
)
|
||||
case 'pulse':
|
||||
return (
|
||||
`<p:animScale><p:cBhvr><p:cTn id="${gen.next()}" dur="${Math.max(1, Math.round(dur / 2))}" autoRev="1" fill="hold"/>${target}</p:cBhvr>` +
|
||||
'<p:by x="106000" y="106000"/></p:animScale>'
|
||||
)
|
||||
case 'spin':
|
||||
return (
|
||||
`<p:animRot by="21600000"><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}" fill="hold"/>${target}` +
|
||||
'<p:attrNameLst><p:attrName>r</p:attrName></p:attrNameLst></p:cBhvr></p:animRot>'
|
||||
)
|
||||
case 'grow':
|
||||
return (
|
||||
`<p:animScale><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}" fill="hold"/>${target}</p:cBhvr>` +
|
||||
'<p:by x="150000" y="150000"/></p:animScale>'
|
||||
)
|
||||
case 'teeter':
|
||||
// Teeter: rock left/right around its own angle, then settle back
|
||||
return keyframeAnimXml(gen, target, dur, 'ppt_r', [
|
||||
[0, '#ppt_r'],
|
||||
[12500, '#ppt_r-9'],
|
||||
[37500, '#ppt_r+9'],
|
||||
[62500, '#ppt_r-6'],
|
||||
[87500, '#ppt_r+3'],
|
||||
[100000, '#ppt_r'],
|
||||
])
|
||||
case 'disappear':
|
||||
return setVisibilityXml(gen, target, false, 0)
|
||||
case 'fadeOut':
|
||||
return (
|
||||
`<p:animEffect transition="out" filter="fade"><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}"/>${target}</p:cBhvr></p:animEffect>` +
|
||||
hideAtEnd
|
||||
)
|
||||
case 'flyOut':
|
||||
return (
|
||||
moveAnimXml(gen, target, dur, 'ppt_x', '#ppt_x', '#ppt_x') +
|
||||
moveAnimXml(gen, target, dur, 'ppt_y', '#ppt_y', '1+#ppt_h/2') +
|
||||
hideAtEnd
|
||||
)
|
||||
case 'wipeOut':
|
||||
return (
|
||||
`<p:animEffect transition="out" filter="wipe(down)"><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}"/>${target}</p:cBhvr></p:animEffect>` +
|
||||
hideAtEnd
|
||||
)
|
||||
case 'shrink':
|
||||
// Shrink and rotate out (approximation of Shrink & Turn)
|
||||
return (
|
||||
`<p:animScale><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}" fill="hold"/>${target}</p:cBhvr>` +
|
||||
'<p:from x="100000" y="100000"/><p:to x="1000" y="1000"/></p:animScale>' +
|
||||
`<p:animRot by="-5400000"><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}" fill="hold"/>${target}` +
|
||||
'<p:attrNameLst><p:attrName>r</p:attrName></p:attrNameLst></p:cBhvr></p:animRot>' +
|
||||
hideAtEnd
|
||||
)
|
||||
case 'zoomOut':
|
||||
return (
|
||||
`<p:animScale><p:cBhvr><p:cTn id="${gen.next()}" dur="${dur}" fill="hold"/>${target}</p:cBhvr>` +
|
||||
'<p:from x="100000" y="100000"/><p:to x="1000" y="1000"/></p:animScale>' +
|
||||
hideAtEnd
|
||||
)
|
||||
case 'motionPath':
|
||||
return motionAnimXml(gen, target, dur, a.motionPath ?? DEFAULT_MOTION_PATH)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the whole <p:timing>. Grouping rules (matching slideshow playback):
|
||||
* onClick starts a new "click group"; withPrev joins the current group (start =
|
||||
* previous effect's start + delay); afterPrev joins the current group (start =
|
||||
* previous effect's end + delay). If the first item is not onClick, group 0
|
||||
* plays automatically after the slide transition (stCondLst delay=0).
|
||||
*/
|
||||
interface Placed {
|
||||
a: SlideAnimation
|
||||
startMs: number
|
||||
grpId: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Grouping + absolute in-group start: onClick starts a new "click group"; withPrev
|
||||
* start = previous start + delay; afterPrev start = previous end + delay.
|
||||
* grpBase = animation count already used per spid (continued on incremental append).
|
||||
*/
|
||||
function placeAnims(
|
||||
anims: SlideAnimation[],
|
||||
grpBase?: Map<number, number>,
|
||||
): Array<{ auto: boolean; items: Placed[] }> {
|
||||
const groups: Array<{ auto: boolean; items: Placed[] }> = []
|
||||
const grpCount = new Map<number, number>(grpBase ?? [])
|
||||
let prevStart = 0
|
||||
let prevEnd = 0
|
||||
for (const a of anims) {
|
||||
if (a.trigger === 'onClick' || groups.length === 0) {
|
||||
groups.push({ auto: a.trigger !== 'onClick', items: [] })
|
||||
prevStart = 0
|
||||
prevEnd = 0
|
||||
}
|
||||
const base = a.trigger === 'afterPrev' ? prevEnd : a.trigger === 'withPrev' ? prevStart : 0
|
||||
const start = base + Math.max(0, Math.round(a.delayMs))
|
||||
const grpId = grpCount.get(a.spid) ?? 0
|
||||
grpCount.set(a.spid, grpId + 1)
|
||||
groups[groups.length - 1]!.items.push({ a, startMs: start, grpId })
|
||||
prevStart = start
|
||||
prevEnd = start + Math.max(1, Math.round(a.durationMs))
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
/** One effect's <p:par> (cTn with presetID/presetClass + start + behaviors). */
|
||||
function effectParXml(gen: IdGen, p: Placed): string {
|
||||
const preset = PRESET[p.a.effect]
|
||||
return (
|
||||
'<p:par>' +
|
||||
`<p:cTn id="${gen.next()}" presetID="${preset.id}" presetClass="${preset.cls}" presetSubtype="${preset.sub}" fill="hold" grpId="${p.grpId}" nodeType="${NODE_TYPE[p.a.trigger]}">` +
|
||||
`<p:stCondLst><p:cond delay="${p.startMs}"/></p:stCondLst>` +
|
||||
`<p:childTnLst>${effectBehaviorsXml(gen, p.a)}</p:childTnLst>` +
|
||||
'</p:cTn></p:par>'
|
||||
)
|
||||
}
|
||||
|
||||
/** The two-level <p:par> wrapper of one "click group". */
|
||||
function groupParXml(gen: IdGen, g: { auto: boolean; items: Placed[] }): string {
|
||||
const effects = g.items.map((p) => effectParXml(gen, p)).join('')
|
||||
return (
|
||||
'<p:par>' +
|
||||
`<p:cTn id="${gen.next()}" fill="hold">` +
|
||||
`<p:stCondLst><p:cond delay="${g.auto ? '0' : 'indefinite'}"/></p:stCondLst>` +
|
||||
'<p:childTnLst><p:par>' +
|
||||
`<p:cTn id="${gen.next()}" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst>` +
|
||||
`<p:childTnLst>${effects}</p:childTnLst></p:cTn>` +
|
||||
'</p:par></p:childTnLst></p:cTn></p:par>'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* bldP list for a full rebuild (shapes with paragraph animation get a single
|
||||
* summarizing build="p" bldP instead of one plain bldP per grpId).
|
||||
*/
|
||||
function bldPsXml(anims: SlideAnimation[]): string {
|
||||
const paraSpids = new Set(anims.filter((a) => a.paragraph != null).map((a) => a.spid))
|
||||
const bldSeen = new Set<string>()
|
||||
return anims
|
||||
.map((a, i) => {
|
||||
if (paraSpids.has(a.spid)) {
|
||||
const key = `p:${a.spid}`
|
||||
if (bldSeen.has(key)) return ''
|
||||
bldSeen.add(key)
|
||||
// grpId=0: on a full rebuild the spid's first animation always has grpId 0
|
||||
return `<p:bldP spid="${a.spid}" grpId="0" uiExpand="1" build="p"/>`
|
||||
}
|
||||
// grpId matches effect generation: the nth animation of the same spid has grpId=n
|
||||
const before = anims.slice(0, i).filter((x) => x.spid === a.spid).length
|
||||
const key = `${a.spid}:${before}`
|
||||
if (bldSeen.has(key)) return ''
|
||||
bldSeen.add(key)
|
||||
return `<p:bldP spid="${a.spid}" grpId="${before}"/>`
|
||||
})
|
||||
.join('')
|
||||
}
|
||||
|
||||
export function buildTimingXml(anims: SlideAnimation[]): string {
|
||||
if (anims.length === 0) return ''
|
||||
let idCounter = 0
|
||||
const gen: IdGen = { next: () => ++idCounter }
|
||||
const rootId = gen.next() // 1 tmRoot
|
||||
const seqId = gen.next() // 2 mainSeq
|
||||
|
||||
const groupXml = placeAnims(anims)
|
||||
.map((g) => groupParXml(gen, g))
|
||||
.join('')
|
||||
|
||||
const bldPs = bldPsXml(anims)
|
||||
|
||||
return (
|
||||
'<p:timing><p:tnLst><p:par>' +
|
||||
`<p:cTn id="${rootId}" dur="indefinite" restart="never" nodeType="tmRoot"><p:childTnLst>` +
|
||||
'<p:seq concurrent="1" nextAc="seek">' +
|
||||
`<p:cTn id="${seqId}" dur="indefinite" nodeType="mainSeq"><p:childTnLst>${groupXml}</p:childTnLst></p:cTn>` +
|
||||
'<p:prevCondLst><p:cond evt="onPrev" delay="0"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:prevCondLst>' +
|
||||
'<p:nextCondLst><p:cond evt="onNext" delay="0"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:nextCondLst>' +
|
||||
'</p:seq></p:childTnLst></p:cTn>' +
|
||||
'</p:par></p:tnLst>' +
|
||||
`<p:bldLst>${bldPs}</p:bldLst></p:timing>`
|
||||
)
|
||||
}
|
||||
|
||||
const TIMING_RE = /<p:timing\b[^>]*\/>|<p:timing\b[^>]*>[\s\S]*?<\/p:timing>/
|
||||
|
||||
/** Content span of the mainSeq cTn; returns null when there is no main sequence. */
|
||||
function mainSeqSpan(timing: string): { start: number; end: number } | null {
|
||||
const m = /<p:cTn\b[^>]*\bnodeType="mainSeq"[^>]*>/.exec(timing)
|
||||
if (!m) return null
|
||||
const start = m.index + m[0].length
|
||||
return { start, end: findCTnEnd(timing, start) }
|
||||
}
|
||||
|
||||
/** Whether the tmRoot cTn's childTnLst has no children left (after removing the main sequence, decides whether the whole timing is still meaningful). */
|
||||
function rootChildTnLstEmpty(timing: string): boolean {
|
||||
const rootM = /<p:cTn\b[^>]*\bnodeType="tmRoot"[^>]*>/.exec(timing)
|
||||
if (!rootM) return true
|
||||
const childOpen = timing.indexOf('<p:childTnLst>', rootM.index + rootM[0].length)
|
||||
if (childOpen < 0) return true
|
||||
const childClose = findBalancedClose(timing, childOpen, 'p:childTnLst')
|
||||
if (childClose < 0) return true
|
||||
return !timing.slice(childOpen + '<p:childTnLst>'.length, childClose).trim()
|
||||
}
|
||||
|
||||
/** Strip all <p:bldP> from bldLst and write ours; bldDgm/bldOleChart/bldGraphic etc. are kept. */
|
||||
function rebuildBldLst(timing: string, anims: SlideAnimation[]): string {
|
||||
const ours = bldPsXml(anims)
|
||||
const bldOpen = /<p:bldLst\b[^>]*>/.exec(timing)
|
||||
if (!bldOpen) {
|
||||
if (!ours) return timing
|
||||
const tEnd = timing.lastIndexOf('</p:timing>')
|
||||
if (tEnd < 0) return timing
|
||||
return timing.slice(0, tEnd) + `<p:bldLst>${ours}</p:bldLst>` + timing.slice(tEnd)
|
||||
}
|
||||
const close = findBalancedClose(timing, bldOpen.index, 'p:bldLst')
|
||||
if (close < 0) return timing
|
||||
const inner = timing.slice(bldOpen.index + bldOpen[0].length, close)
|
||||
const kept = inner.replace(/<p:bldP\b[^>]*\/>|<p:bldP\b[^>]*>[\s\S]*?<\/p:bldP>/g, '')
|
||||
const newInner = ours + kept
|
||||
const replacement = newInner ? `<p:bldLst>${newInner}</p:bldLst>` : ''
|
||||
return timing.slice(0, bldOpen.index) + replacement + timing.slice(close + '</p:bldLst>'.length)
|
||||
}
|
||||
|
||||
/**
|
||||
* Overwrite-style rebuild that only touches the main sequence: the mainSeq childTnLst
|
||||
* is replaced with new effect groups; unmodeled siblings (interactiveSeq, media
|
||||
* timelines, ...) keep their original bytes; bldP is rewritten, other bld* kept.
|
||||
* Empty anims removes the whole <p:seq> (main sequence); if the root childTnLst becomes
|
||||
* empty as a result, returns '' (delete the timing).
|
||||
* Returns null when the structure is unexpected; the caller falls back to a fresh build.
|
||||
*/
|
||||
function rebuildTimingPreservingXml(timing: string, anims: SlideAnimation[]): string | null {
|
||||
const seqCtnM = /<p:cTn\b[^>]*\bnodeType="mainSeq"[^>]*>/.exec(timing)
|
||||
let newTiming: string
|
||||
if (anims.length === 0) {
|
||||
if (!seqCtnM) return rebuildBldLst(timing, anims)
|
||||
const seqStart = timing.lastIndexOf('<p:seq', seqCtnM.index)
|
||||
if (seqStart < 0) return null
|
||||
const seqClose = findBalancedClose(timing, seqStart, 'p:seq')
|
||||
if (seqClose < 0) return null
|
||||
newTiming = timing.slice(0, seqStart) + timing.slice(seqClose + '</p:seq>'.length)
|
||||
newTiming = rebuildBldLst(newTiming, anims)
|
||||
return rootChildTnLstEmpty(newTiming) ? '' : newTiming
|
||||
}
|
||||
|
||||
const gen = makeGenAfterMaxId(timing)
|
||||
const groupXml = placeAnims(anims)
|
||||
.map((g) => groupParXml(gen, g))
|
||||
.join('')
|
||||
if (seqCtnM) {
|
||||
const childOpen = timing.indexOf('<p:childTnLst>', seqCtnM.index + seqCtnM[0].length)
|
||||
if (childOpen < 0) return null
|
||||
const childClose = findBalancedClose(timing, childOpen, 'p:childTnLst')
|
||||
if (childClose < 0) return null
|
||||
newTiming = timing.slice(0, childOpen + '<p:childTnLst>'.length) + groupXml + timing.slice(childClose)
|
||||
} else {
|
||||
// Original timing has no main sequence (only trigger/media nodes): insert a brand-new <p:seq> at the end of the tmRoot childTnLst
|
||||
const rootM = /<p:cTn\b[^>]*\bnodeType="tmRoot"[^>]*>/.exec(timing)
|
||||
if (!rootM) return null
|
||||
const childOpen = timing.indexOf('<p:childTnLst>', rootM.index + rootM[0].length)
|
||||
if (childOpen < 0) return null
|
||||
const childClose = findBalancedClose(timing, childOpen, 'p:childTnLst')
|
||||
if (childClose < 0) return null
|
||||
const seqXml =
|
||||
'<p:seq concurrent="1" nextAc="seek">' +
|
||||
`<p:cTn id="${gen.next()}" dur="indefinite" nodeType="mainSeq"><p:childTnLst>${groupXml}</p:childTnLst></p:cTn>` +
|
||||
'<p:prevCondLst><p:cond evt="onPrev" delay="0"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:prevCondLst>' +
|
||||
'<p:nextCondLst><p:cond evt="onNext" delay="0"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:nextCondLst>' +
|
||||
'</p:seq>'
|
||||
newTiming = timing.slice(0, childClose) + seqXml + timing.slice(childClose)
|
||||
}
|
||||
return rebuildBldLst(newTiming, anims)
|
||||
}
|
||||
|
||||
/**
|
||||
* In-place patch of the bodySuffix's <p:timing> (schema order: after transition, before extLst).
|
||||
* With an existing timing, only the main sequence is rebuilt and unmodeled sibling
|
||||
* nodes are kept; empty anims removes the main sequence (the timing stays if other
|
||||
* nodes remain, and is removed only when fully empty). Returns the new bodySuffix.
|
||||
*/
|
||||
export function patchSlideTimingXml(bodySuffix: string, anims: SlideAnimation[]): string {
|
||||
const timingM = TIMING_RE.exec(bodySuffix)
|
||||
if (timingM) {
|
||||
const rebuilt = rebuildTimingPreservingXml(timingM[0], anims)
|
||||
if (rebuilt != null)
|
||||
return bodySuffix.slice(0, timingM.index) + rebuilt + bodySuffix.slice(timingM.index + timingM[0].length)
|
||||
}
|
||||
const stripped = bodySuffix.replace(TIMING_RE, '')
|
||||
if (anims.length === 0) return stripped
|
||||
const xml = buildTimingXml(anims)
|
||||
// Insertion point: before </p:sld>; with a slide-level <p:extLst> (legal after
|
||||
// timing, but PowerPoint emits timing first), insert before the last extLst
|
||||
const ext = stripped.lastIndexOf('<p:extLst')
|
||||
const sldEnd = stripped.lastIndexOf('</p:sld>')
|
||||
const at = ext >= 0 ? ext : sldEnd
|
||||
if (at < 0) return stripped
|
||||
return stripped.slice(0, at) + xml + stripped.slice(at)
|
||||
}
|
||||
|
||||
// ── Read: <p:timing> → SlideAnimation[] ────────────────────────────────
|
||||
|
||||
/** Balanced scan: from openEnd (end of the open tag) find the matching </p:cTn>, returning the content end. */
|
||||
function findCTnEnd(xml: string, openEnd: number): number {
|
||||
const re = /<p:cTn\b[^>]*?(\/?)>|<\/p:cTn>/g
|
||||
re.lastIndex = openEnd
|
||||
let depth = 1
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(xml)) !== null) {
|
||||
if (m[0] === '</p:cTn>') {
|
||||
depth--
|
||||
if (depth === 0) return m.index
|
||||
} else if (m[1] !== '/') {
|
||||
depth++
|
||||
}
|
||||
}
|
||||
return xml.length
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the bodySuffix's animation list (for UI echo + slideshow).
|
||||
* Parses every effect cTn carrying presetClass; delay is derived back to the user
|
||||
* delay per the write convention (withPrev minus previous start / afterPrev minus
|
||||
* previous end).
|
||||
*/
|
||||
export function readSlideTimingXml(bodySuffix: string): SlideAnimation[] {
|
||||
const timing = TIMING_RE.exec(bodySuffix)?.[0]
|
||||
if (!timing) return []
|
||||
// Read only the main sequence: interactiveSeq trigger animations etc. are not modeled, avoiding mistakenly absorbing them as click animations on rewrite
|
||||
const seq = mainSeqSpan(timing)
|
||||
if (!seq) return []
|
||||
const out: SlideAnimation[] = []
|
||||
const re = /<p:cTn\b([^>]*\bpresetClass="[^"]*"[^>]*)>/g
|
||||
re.lastIndex = seq.start
|
||||
let m: RegExpExecArray | null
|
||||
let prevStart = 0
|
||||
let prevEnd = 0
|
||||
while ((m = re.exec(timing)) !== null && m.index < seq.end) {
|
||||
const attrs = m[1]!
|
||||
const cls = /\bpresetClass="([^"]*)"/.exec(attrs)?.[1] ?? 'entr'
|
||||
const pid = Number(/\bpresetID="(\d+)"/.exec(attrs)?.[1] ?? '0')
|
||||
const psub = Number(/\bpresetSubtype="(\d+)"/.exec(attrs)?.[1] ?? '0')
|
||||
const nodeType = /\bnodeType="([^"]*)"/.exec(attrs)?.[1] ?? 'clickEffect'
|
||||
const trigger: AnimTrigger =
|
||||
nodeType === 'withEffect' ? 'withPrev' : nodeType === 'afterEffect' ? 'afterPrev' : 'onClick'
|
||||
const bodyEnd = findCTnEnd(timing, re.lastIndex)
|
||||
const body = timing.slice(re.lastIndex, bodyEnd)
|
||||
re.lastIndex = bodyEnd
|
||||
|
||||
const spidM = /<p:spTgt\s[^>]*\bspid="(\d+)"/.exec(body)
|
||||
if (!spidM) continue
|
||||
const spid = Number(spidM[1])
|
||||
// Start: the effect cTn's own stCondLst (first cond delay at the body start)
|
||||
const startMs = Number(/^\s*<p:stCondLst><p:cond delay="(\d+)"/.exec(body)?.[1] ?? '0')
|
||||
// Duration: the largest numeric dur among the behaviors
|
||||
let durationMs = 0
|
||||
const durRe = /\bdur="(\d+)"/g
|
||||
let dm: RegExpExecArray | null
|
||||
while ((dm = durRe.exec(body)) !== null) durationMs = Math.max(durationMs, Number(dm[1]))
|
||||
// pulse with autoRev: actual duration = dur*2
|
||||
if (/\bautoRev="1"/.test(body)) durationMs *= 2
|
||||
const effect = effectFromPreset(cls, pid, psub)
|
||||
if (effect === 'appear' || effect === 'disappear') durationMs = 0
|
||||
|
||||
if (trigger === 'onClick') {
|
||||
prevStart = 0
|
||||
prevEnd = 0
|
||||
}
|
||||
const base = trigger === 'afterPrev' ? prevEnd : trigger === 'withPrev' ? prevStart : 0
|
||||
const delayMs = Math.max(0, startMs - base)
|
||||
prevStart = startMs
|
||||
prevEnd = startMs + Math.max(1, durationMs)
|
||||
|
||||
const anim: SlideAnimation = { spid, effect, trigger, durationMs, delayMs }
|
||||
const pgM = /<p:pgRg\s[^>]*\bst="(\d+)"/.exec(body)
|
||||
if (pgM) anim.paragraph = Number(pgM[1])
|
||||
if (effect === 'motionPath') {
|
||||
// Path read-back: drop the " E" end marker added on write, restoring the user path
|
||||
const path = /<p:animMotion\b[^>]*\bpath="([^"]*)"/.exec(body)?.[1]
|
||||
anim.motionPath = (path ?? DEFAULT_MOTION_PATH).replace(/\s*E$/, '').trim()
|
||||
}
|
||||
out.push(anim)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ── Incremental write-back (keeps unmodeled timing nodes) ──────────────
|
||||
|
||||
function animEq(x: SlideAnimation, y: SlideAnimation): boolean {
|
||||
return (
|
||||
x.spid === y.spid &&
|
||||
x.effect === y.effect &&
|
||||
x.trigger === y.trigger &&
|
||||
x.durationMs === y.durationMs &&
|
||||
x.delayMs === y.delayMs &&
|
||||
(x.motionPath ?? null) === (y.motionPath ?? null) &&
|
||||
(x.paragraph ?? null) === (y.paragraph ?? null)
|
||||
)
|
||||
}
|
||||
|
||||
/** Balanced scan for the matching close tag: openStart points at the '<' of <tag …>; returns the start of </tag>, or -1 if not found. */
|
||||
function findBalancedClose(xml: string, openStart: number, tag: string): number {
|
||||
const re = new RegExp(`<${tag}\\b[^>]*?(/?)>|</${tag}>`, 'g')
|
||||
re.lastIndex = openStart
|
||||
let depth = 0
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(xml)) !== null) {
|
||||
if (m[0].startsWith(`</`)) {
|
||||
depth--
|
||||
if (depth === 0) return m.index
|
||||
} else if (m[1] !== '/') {
|
||||
depth++
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
/** Span in the timing of the nth effect <p:par> (cTn with presetClass inside the main sequence); order matches readSlideTimingXml. */
|
||||
function nthEffectParSpan(timing: string, n: number): { start: number; end: number } | null {
|
||||
const seq = mainSeqSpan(timing)
|
||||
if (!seq) return null
|
||||
const re = /<p:cTn\b[^>]*\bpresetClass="[^"]*"[^>]*>/g
|
||||
re.lastIndex = seq.start
|
||||
let m: RegExpExecArray | null
|
||||
let i = 0
|
||||
while ((m = re.exec(timing)) !== null && m.index < seq.end) {
|
||||
if (i++ < n) {
|
||||
re.lastIndex = findCTnEnd(timing, re.lastIndex)
|
||||
continue
|
||||
}
|
||||
const parStart = timing.lastIndexOf('<p:par', m.index)
|
||||
if (parStart < 0) return null
|
||||
const closeAt = findBalancedClose(timing, parStart, 'p:par')
|
||||
if (closeAt < 0) return null
|
||||
return { start: parStart, end: closeAt + '</p:par>'.length }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Replay the grouping semantics to compute each animation's absolute in-group start (same as placeAnims). */
|
||||
function absStarts(anims: SlideAnimation[]): number[] {
|
||||
const out: number[] = []
|
||||
let prevStart = 0
|
||||
let prevEnd = 0
|
||||
for (const a of anims) {
|
||||
if (a.trigger === 'onClick') {
|
||||
prevStart = 0
|
||||
prevEnd = 0
|
||||
}
|
||||
const base = a.trigger === 'afterPrev' ? prevEnd : a.trigger === 'withPrev' ? prevStart : 0
|
||||
const start = base + Math.max(0, Math.round(a.delayMs))
|
||||
out.push(start)
|
||||
prevStart = start
|
||||
prevEnd = start + Math.max(1, Math.round(a.durationMs))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Largest numeric id already in the timing; incrementally generated cTn ids continue after it (unique within the slide). */
|
||||
function makeGenAfterMaxId(timing: string): IdGen {
|
||||
let maxId = 0
|
||||
for (const m of timing.matchAll(/\bid="(\d+)"/g)) maxId = Math.max(maxId, Number(m[1]))
|
||||
let c = maxId
|
||||
return { next: () => ++c }
|
||||
}
|
||||
|
||||
/** Append bldP into <p:bldLst> (created before </p:timing> if missing). Existing (spid,grpId) pairs are skipped. */
|
||||
function appendBldPs(timing: string, items: Placed[]): string {
|
||||
const seen = new Set<string>()
|
||||
for (const m of timing.matchAll(/<p:bldP\b[^>]*\bspid="(\d+)"[^>]*\bgrpId="(\d+)"/g)) {
|
||||
seen.add(`${m[1]}:${m[2]}`)
|
||||
}
|
||||
// spids already having build="p": write only one paragraph bldP per shape
|
||||
const paraSeen = new Set<string>()
|
||||
for (const m of timing.matchAll(/<p:bldP\b[^>]*\bspid="(\d+)"[^>]*\bbuild="p"/g)) paraSeen.add(m[1]!)
|
||||
const parts: string[] = []
|
||||
for (const p of items) {
|
||||
if (p.a.paragraph != null) {
|
||||
const k = String(p.a.spid)
|
||||
if (paraSeen.has(k)) continue
|
||||
paraSeen.add(k)
|
||||
parts.push(`<p:bldP spid="${p.a.spid}" grpId="${p.grpId}" uiExpand="1" build="p"/>`)
|
||||
} else {
|
||||
const k = `${p.a.spid}:${p.grpId}`
|
||||
if (seen.has(k)) continue
|
||||
seen.add(k)
|
||||
parts.push(`<p:bldP spid="${p.a.spid}" grpId="${p.grpId}"/>`)
|
||||
}
|
||||
}
|
||||
const add = parts.join('')
|
||||
if (!add) return timing
|
||||
const bldEnd = timing.lastIndexOf('</p:bldLst>')
|
||||
if (bldEnd >= 0) return timing.slice(0, bldEnd) + add + timing.slice(bldEnd)
|
||||
const tEnd = timing.lastIndexOf('</p:timing>')
|
||||
if (tEnd < 0) return timing
|
||||
return timing.slice(0, tEnd) + `<p:bldLst>${add}</p:bldLst>` + timing.slice(tEnd)
|
||||
}
|
||||
|
||||
/**
|
||||
* Incremental <p:timing> patch: touches only the affected effect nodes; unmodeled
|
||||
* sibling nodes (interactive trigger sequences, text-level animations, media
|
||||
* timelines, ...) keep their original bytes. Two supported shapes:
|
||||
* A. Pure append (old list is a prefix of the new one, and the first added item
|
||||
* is onClick) → new click groups are inserted at the end of the mainSeq;
|
||||
* B. Tail single-item edit (same length, only one item changed, trigger/target
|
||||
* unchanged, and no chained dependency after it) → replace that effect's
|
||||
* <p:par> wholesale.
|
||||
* Everything else (delete/reorder/trigger change) returns null and the caller
|
||||
* falls back to a full rebuild.
|
||||
*/
|
||||
export function patchSlideTimingIncrementalXml(
|
||||
bodySuffix: string,
|
||||
anims: SlideAnimation[],
|
||||
): string | null {
|
||||
const timingM = TIMING_RE.exec(bodySuffix)
|
||||
if (!timingM) return null
|
||||
const timing = timingM[0]
|
||||
const old = readSlideTimingXml(bodySuffix)
|
||||
if (!old.length || !anims.length) return null
|
||||
const splice = (newTiming: string) =>
|
||||
bodySuffix.slice(0, timingM.index) + newTiming + bodySuffix.slice(timingM.index + timing.length)
|
||||
|
||||
// A. Pure append
|
||||
if (anims.length > old.length && old.every((o, i) => animEq(o, anims[i]!))) {
|
||||
const added = anims.slice(old.length)
|
||||
if (added[0]!.trigger !== 'onClick') return null
|
||||
// Mixing whole-shape and paragraph animations on one shape changes the bldP form
|
||||
// (plain ↔ build="p"); defer to a full rebuild
|
||||
const kindBySpid = new Map<number, number>()
|
||||
for (const a of anims) kindBySpid.set(a.spid, (kindBySpid.get(a.spid) ?? 0) | (a.paragraph == null ? 1 : 2))
|
||||
if (added.some((a) => kindBySpid.get(a.spid) === 3)) return null
|
||||
const seqM = /<p:cTn\b[^>]*\bnodeType="mainSeq"[^>]*>/.exec(timing)
|
||||
if (!seqM) return null
|
||||
const childOpen = timing.indexOf('<p:childTnLst>', seqM.index + seqM[0].length)
|
||||
if (childOpen < 0) return null
|
||||
const childClose = findBalancedClose(timing, childOpen, 'p:childTnLst')
|
||||
if (childClose < 0) return null
|
||||
|
||||
const gen = makeGenAfterMaxId(timing)
|
||||
const grpBase = new Map<number, number>()
|
||||
for (const a of old) grpBase.set(a.spid, (grpBase.get(a.spid) ?? 0) + 1)
|
||||
const groups = placeAnims(added, grpBase)
|
||||
const groupsXml = groups.map((g) => groupParXml(gen, g)).join('')
|
||||
let newTiming = timing.slice(0, childClose) + groupsXml + timing.slice(childClose)
|
||||
newTiming = appendBldPs(newTiming, groups.flatMap((g) => g.items))
|
||||
return splice(newTiming)
|
||||
}
|
||||
|
||||
// B. Tail single-item edit
|
||||
if (anims.length === old.length) {
|
||||
const diffIdx = anims.flatMap((a, i) => (animEq(a, old[i]!) ? [] : [i]))
|
||||
if (diffIdx.length !== 1) return null
|
||||
const i = diffIdx[0]!
|
||||
const o = old[i]!
|
||||
const a = anims[i]!
|
||||
// Trigger/target unchanged (a paragraph change affects the bldP form); no later withPrev/afterPrev chain depends on this item's start/end
|
||||
if (o.trigger !== a.trigger || o.spid !== a.spid) return null
|
||||
if ((o.paragraph ?? null) !== (a.paragraph ?? null)) return null
|
||||
const next = anims[i + 1]
|
||||
if (next && next.trigger !== 'onClick') return null
|
||||
const span = nthEffectParSpan(timing, i)
|
||||
if (!span) return null
|
||||
const gen = makeGenAfterMaxId(timing)
|
||||
// Keep the original cTn's grpId (bldP is keyed on it); recompute from the list only when missing
|
||||
const origGrpId = /\bgrpId="(\d+)"/.exec(timing.slice(span.start, span.end))?.[1]
|
||||
const grpId =
|
||||
origGrpId != null ? Number(origGrpId) : anims.slice(0, i).filter((x) => x.spid === a.spid).length
|
||||
const par = effectParXml(gen, { a, startMs: absStarts(anims)[i]!, grpId })
|
||||
return splice(timing.slice(0, span.start) + par + timing.slice(span.end))
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the slide's full animation list. Tries the incremental patch first (append /
|
||||
* tail single-item edit, keeping unmodeled timing nodes); when inapplicable, falls
|
||||
* back to the overwrite-style full rebuild (writes bodySuffix, persisted with the
|
||||
* whole-slide rebuild on save).
|
||||
*/
|
||||
export function setSlideAnimations(slide: Slide, anims: SlideAnimation[]): void {
|
||||
slide.bodySuffix =
|
||||
patchSlideTimingIncrementalXml(slide.bodySuffix, anims) ??
|
||||
patchSlideTimingXml(slide.bodySuffix, anims)
|
||||
slide.structureDirty = true
|
||||
}
|
||||
|
||||
/** Read the current slide's animation list. */
|
||||
export function getSlideAnimations(slide: Slide): SlideAnimation[] {
|
||||
return readSlideTimingXml(slide.bodySuffix)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Blank presentation template — starting point for the start screen's
|
||||
* "AI generate / New blank" actions. A hand-written minimal set of valid OOXML
|
||||
* parts (16:9, single blank slide); once parsed by openPptx it goes through
|
||||
* exactly the same edit/save pipeline as opening a real file.
|
||||
*/
|
||||
import JSZip from 'jszip'
|
||||
|
||||
const XMLDECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
const NS_A = 'http://schemas.openxmlformats.org/drawingml/2006/main'
|
||||
const NS_R = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
|
||||
const NS_P = 'http://schemas.openxmlformats.org/presentationml/2006/main'
|
||||
|
||||
const CONTENT_TYPES =
|
||||
XMLDECL +
|
||||
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
|
||||
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
|
||||
'<Default Extension="xml" ContentType="application/xml"/>' +
|
||||
'<Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/>' +
|
||||
'<Override PartName="/ppt/slideMasters/slideMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"/>' +
|
||||
'<Override PartName="/ppt/slideLayouts/slideLayout1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/>' +
|
||||
'<Override PartName="/ppt/slides/slide1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>' +
|
||||
'<Override PartName="/ppt/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>' +
|
||||
'</Types>'
|
||||
|
||||
const ROOT_RELS =
|
||||
XMLDECL +
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/>' +
|
||||
'</Relationships>'
|
||||
|
||||
const PRESENTATION =
|
||||
XMLDECL +
|
||||
`<p:presentation xmlns:a="${NS_A}" xmlns:r="${NS_R}" xmlns:p="${NS_P}">` +
|
||||
'<p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst>' +
|
||||
'<p:sldIdLst><p:sldId id="256" r:id="rId2"/></p:sldIdLst>' +
|
||||
'<p:sldSz cx="12192000" cy="6858000"/><p:notesSz cx="6858000" cy="9144000"/>' +
|
||||
'</p:presentation>'
|
||||
|
||||
const PRESENTATION_RELS =
|
||||
XMLDECL +
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="slideMasters/slideMaster1.xml"/>' +
|
||||
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide1.xml"/>' +
|
||||
'</Relationships>'
|
||||
|
||||
const EMPTY_SPTREE =
|
||||
'<p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
|
||||
'<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/>' +
|
||||
'<a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr></p:spTree>'
|
||||
|
||||
/** Minimal blank slide XML (empty spTree); insertBlankSlide also uses it as new slide content. */
|
||||
export const BLANK_SLIDE_XML =
|
||||
XMLDECL +
|
||||
`<p:sld xmlns:a="${NS_A}" xmlns:r="${NS_R}" xmlns:p="${NS_P}">` +
|
||||
`<p:cSld>${EMPTY_SPTREE}</p:cSld>` +
|
||||
'<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>'
|
||||
|
||||
const SLIDE1_RELS =
|
||||
XMLDECL +
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>' +
|
||||
'</Relationships>'
|
||||
|
||||
const LAYOUT1 =
|
||||
XMLDECL +
|
||||
`<p:sldLayout xmlns:a="${NS_A}" xmlns:r="${NS_R}" xmlns:p="${NS_P}" type="blank">` +
|
||||
`<p:cSld name="Blank">${EMPTY_SPTREE}</p:cSld>` +
|
||||
'<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>'
|
||||
|
||||
const LAYOUT1_RELS =
|
||||
XMLDECL +
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="../slideMasters/slideMaster1.xml"/>' +
|
||||
'</Relationships>'
|
||||
|
||||
const MASTER1 =
|
||||
XMLDECL +
|
||||
`<p:sldMaster xmlns:a="${NS_A}" xmlns:r="${NS_R}" xmlns:p="${NS_P}">` +
|
||||
`<p:cSld>${EMPTY_SPTREE}</p:cSld>` +
|
||||
'<p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>' +
|
||||
'<p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/></p:sldLayoutIdLst>' +
|
||||
'<p:txStyles><p:titleStyle/><p:bodyStyle/><p:otherStyle/></p:txStyles>' +
|
||||
'</p:sldMaster>'
|
||||
|
||||
const MASTER1_RELS =
|
||||
XMLDECL +
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>' +
|
||||
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/>' +
|
||||
'</Relationships>'
|
||||
|
||||
const fillStyles =
|
||||
'<a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
|
||||
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
|
||||
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:fillStyleLst>'
|
||||
const lnStyles =
|
||||
'<a:lnStyleLst>' +
|
||||
['6350', '12700', '19050']
|
||||
.map((w) => `<a:ln w="${w}"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>`)
|
||||
.join('') +
|
||||
'</a:lnStyleLst>'
|
||||
const effectStyles =
|
||||
'<a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle>' +
|
||||
'<a:effectStyle><a:effectLst/></a:effectStyle>' +
|
||||
'<a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst>'
|
||||
const bgFillStyles =
|
||||
'<a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
|
||||
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
|
||||
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:bgFillStyleLst>'
|
||||
|
||||
const THEME1 =
|
||||
XMLDECL +
|
||||
`<a:theme xmlns:a="${NS_A}" name="Office">` +
|
||||
'<a:themeElements>' +
|
||||
'<a:clrScheme name="Office">' +
|
||||
'<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>' +
|
||||
'<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>' +
|
||||
'<a:dk2><a:srgbClr val="44546A"/></a:dk2>' +
|
||||
'<a:lt2><a:srgbClr val="E7E6E6"/></a:lt2>' +
|
||||
'<a:accent1><a:srgbClr val="C43E1C"/></a:accent1>' +
|
||||
'<a:accent2><a:srgbClr val="ED7D31"/></a:accent2>' +
|
||||
'<a:accent3><a:srgbClr val="A5A5A5"/></a:accent3>' +
|
||||
'<a:accent4><a:srgbClr val="FFC000"/></a:accent4>' +
|
||||
'<a:accent5><a:srgbClr val="4472C4"/></a:accent5>' +
|
||||
'<a:accent6><a:srgbClr val="70AD47"/></a:accent6>' +
|
||||
'<a:hlink><a:srgbClr val="0563C1"/></a:hlink>' +
|
||||
'<a:folHlink><a:srgbClr val="954F72"/></a:folHlink>' +
|
||||
'</a:clrScheme>' +
|
||||
'<a:fontScheme name="Office">' +
|
||||
'<a:majorFont><a:latin typeface="Calibri Light"/><a:ea typeface="Microsoft YaHei"/><a:cs typeface=""/></a:majorFont>' +
|
||||
'<a:minorFont><a:latin typeface="Calibri"/><a:ea typeface="Microsoft YaHei"/><a:cs typeface=""/></a:minorFont>' +
|
||||
'</a:fontScheme>' +
|
||||
`<a:fmtScheme name="Office">${fillStyles}${lnStyles}${effectStyles}${bgFillStyles}</a:fmtScheme>` +
|
||||
'</a:themeElements></a:theme>'
|
||||
|
||||
/** Generate blank presentation bytes (16:9, one blank slide). */
|
||||
export async function createBlankPptx(): Promise<Uint8Array> {
|
||||
const zip = new JSZip()
|
||||
zip.file('[Content_Types].xml', CONTENT_TYPES)
|
||||
zip.file('_rels/.rels', ROOT_RELS)
|
||||
zip.file('ppt/presentation.xml', PRESENTATION)
|
||||
zip.file('ppt/_rels/presentation.xml.rels', PRESENTATION_RELS)
|
||||
zip.file('ppt/slides/slide1.xml', BLANK_SLIDE_XML)
|
||||
zip.file('ppt/slides/_rels/slide1.xml.rels', SLIDE1_RELS)
|
||||
zip.file('ppt/slideLayouts/slideLayout1.xml', LAYOUT1)
|
||||
zip.file('ppt/slideLayouts/_rels/slideLayout1.xml.rels', LAYOUT1_RELS)
|
||||
zip.file('ppt/slideMasters/slideMaster1.xml', MASTER1)
|
||||
zip.file('ppt/slideMasters/_rels/slideMaster1.xml.rels', MASTER1_RELS)
|
||||
zip.file('ppt/theme/theme1.xml', THEME1)
|
||||
return zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' })
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
/**
|
||||
* Chart insertion — writes the chart part (ppt/charts/chartN.xml) + Content_Types
|
||||
* Override + slide rels + graphicFrame fragment, going through appendRawElements to
|
||||
* reuse the existing chart parsing/rendering.
|
||||
*
|
||||
* The chartSpace template mirrors docx-engine's buildChartPartXml (data goes through
|
||||
* strCache/numCache caches, no embedded workbook attached; PowerPoint renders it
|
||||
* fine, but "Edit Data" is unavailable).
|
||||
*/
|
||||
import type { EmuRect, Slide } from './types'
|
||||
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
|
||||
import { relsPathFor } from './zip'
|
||||
import { appendRawElements, type OpenedPptx } from './index'
|
||||
import { nextCNvPrId } from './insert'
|
||||
|
||||
export type NewChartKind =
|
||||
| 'bar'
|
||||
| 'barStacked'
|
||||
/** Percent-stacked column (no insert entry point; used to preserve the type subdivision when rebuilding an externally created chart during edits) */
|
||||
| 'barPercentStacked'
|
||||
| 'line'
|
||||
| 'area'
|
||||
| 'pie'
|
||||
| 'doughnut'
|
||||
| 'scatter'
|
||||
| 'radar'
|
||||
/** Combo chart: first N-1 series as clustered columns, last series as a line (on the right secondary value axis) */
|
||||
| 'comboBarLine'
|
||||
|
||||
/** Chart element/style toggles (unset = current defaults: legend at bottom, no gridlines, no data labels). */
|
||||
export interface ChartStyleOptions {
|
||||
/** Legend position; 'none' = do not write c:legend */
|
||||
legendPos?: 'b' | 't' | 'r' | 'l' | 'none'
|
||||
/** Data labels (plot-level c:dLbls showVal) */
|
||||
dataLabels?: boolean
|
||||
/** Major gridlines on the value axis */
|
||||
gridlines?: boolean
|
||||
catAxisTitle?: string
|
||||
valAxisTitle?: string
|
||||
/** Gap between bars (% of bar width, c:gapWidth, PowerPoint default 150) */
|
||||
gapWidthPct?: number
|
||||
}
|
||||
|
||||
export interface NewChartOptions extends ChartStyleOptions {
|
||||
kind: NewChartKind
|
||||
title?: string
|
||||
categories: string[]
|
||||
series: Array<{ name: string; values: number[] }>
|
||||
offset: EmuRect
|
||||
/** Bar direction (bar = horizontal bar chart; no insert entry point, used to preserve the direction when rebuilding an externally created chart during edits) */
|
||||
barDir?: 'col' | 'bar'
|
||||
/** Per-point fills, [seriesIdx][pointIdx] (sparse; written as <c:dPt>, wins over the series color) */
|
||||
pointColors?: Array<Array<string | undefined> | undefined>
|
||||
}
|
||||
|
||||
const CHART_CONTENT_TYPE =
|
||||
'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'
|
||||
const CHART_REL_TYPE =
|
||||
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart'
|
||||
const C_NS = 'http://schemas.openxmlformats.org/drawingml/2006/chart'
|
||||
const A_NS = 'http://schemas.openxmlformats.org/drawingml/2006/main'
|
||||
const R_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
|
||||
|
||||
const colLetter = (i: number) => String.fromCharCode(66 + i) // B, C, D…
|
||||
|
||||
function strCacheXml(values: string[], f: string): string {
|
||||
return (
|
||||
`<c:strRef><c:f>${escapeXmlText(f)}</c:f><c:strCache><c:ptCount val="${values.length}"/>` +
|
||||
values.map((v, i) => (v === '' ? '' : `<c:pt idx="${i}"><c:v>${escapeXmlText(v)}</c:v></c:pt>`)).join('') +
|
||||
'</c:strCache></c:strRef>'
|
||||
)
|
||||
}
|
||||
|
||||
function numCacheXml(values: (number | null | undefined)[], f: string): string {
|
||||
return (
|
||||
`<c:numRef><c:f>${escapeXmlText(f)}</c:f><c:numCache><c:formatCode>General</c:formatCode>` +
|
||||
`<c:ptCount val="${values.length}"/>` +
|
||||
values
|
||||
.map((v, i) => (v == null || !Number.isFinite(v) ? '' : `<c:pt idx="${i}"><c:v>${v}</c:v></c:pt>`))
|
||||
.join('') +
|
||||
'</c:numCache></c:numRef>'
|
||||
)
|
||||
}
|
||||
|
||||
/** Data label fragment (dLbls follows ser in the schema; shared by all chart types). */
|
||||
const DLBLS_XML =
|
||||
'<c:dLbls><c:showLegendKey val="0"/><c:showVal val="1"/><c:showCatName val="0"/>' +
|
||||
'<c:showSerName val="0"/><c:showPercent val="0"/><c:showBubbleSize val="0"/></c:dLbls>'
|
||||
|
||||
/** Axis title fragment (value axis vertical, rot=-5400000). */
|
||||
function axTitleXml(text: string, vertical: boolean): string {
|
||||
return (
|
||||
'<c:title><c:tx><c:rich>' +
|
||||
`<a:bodyPr${vertical ? ' rot="-5400000" vert="horz"' : ''}/><a:lstStyle/>` +
|
||||
`<a:p><a:r><a:t>${escapeXmlText(text)}</a:t></a:r></a:p>` +
|
||||
'</c:rich></c:tx><c:overlay val="0"/></c:title>'
|
||||
)
|
||||
}
|
||||
|
||||
/** Full c:chartSpace part XML. */
|
||||
export function buildChartSpaceXml(opts: NewChartOptions): string {
|
||||
const rows = opts.categories.length
|
||||
const dLbls = opts.dataLabels ? DLBLS_XML : ''
|
||||
const grid = opts.gridlines ? '<c:majorGridlines/>' : ''
|
||||
const catTitle = opts.catAxisTitle ? axTitleXml(opts.catAxisTitle, false) : ''
|
||||
const valTitle = opts.valAxisTitle ? axTitleXml(opts.valAxisTitle, true) : ''
|
||||
const gapWidth = opts.gapWidthPct != null ? `<c:gapWidth val="${Math.round(opts.gapWidthPct)}"/>` : ''
|
||||
// Empty names stay empty: no <c:tx> for an unnamed series, no <c:cat> when every category name is empty
|
||||
const txXml = (name: string, i: number) =>
|
||||
name === '' ? '' : `<c:tx>${strCacheXml([name], `Sheet1!$${colLetter(i)}$1`)}</c:tx>`
|
||||
const catXml = opts.categories.some((c) => c !== '')
|
||||
? `<c:cat>${strCacheXml(opts.categories, `Sheet1!$A$2:$A$${rows + 1}`)}</c:cat>`
|
||||
: ''
|
||||
// Per-point <c:dPt> fills (schema position: after tx/spPr, before dLbls/cat/val)
|
||||
const dPtXml = (i: number): string => {
|
||||
const colors = opts.pointColors?.[i]
|
||||
if (!colors) return ''
|
||||
let out = ''
|
||||
colors.forEach((c, pi) => {
|
||||
if (!c) return
|
||||
const hex = c.replace('#', '').toUpperCase()
|
||||
out +=
|
||||
`<c:dPt><c:idx val="${pi}"/><c:bubble3D val="0"/>` +
|
||||
`<c:spPr><a:solidFill><a:srgbClr val="${hex}"/></a:solidFill></c:spPr></c:dPt>`
|
||||
})
|
||||
return out
|
||||
}
|
||||
// Single-series fragment (idx/order use global ordinals so colors stay in order when a combo chart splits into two plots)
|
||||
const serXml = (ser: { name: string; values: number[] }, i: number): string => {
|
||||
const col = colLetter(i)
|
||||
return (
|
||||
`<c:ser><c:idx val="${i}"/><c:order val="${i}"/>` +
|
||||
txXml(ser.name, i) +
|
||||
dPtXml(i) +
|
||||
catXml +
|
||||
`<c:val>${numCacheXml(ser.values.slice(0, rows), `Sheet1!$${col}$2:$${col}$${rows + 1}`)}</c:val>` +
|
||||
'</c:ser>'
|
||||
)
|
||||
}
|
||||
const sers = opts.series.map(serXml).join('')
|
||||
|
||||
let plot: string
|
||||
if (opts.kind === 'comboBarLine') {
|
||||
// Combo chart (columns + line): with ≥2 series the last is a line, the rest are
|
||||
// clustered columns; a single series degrades to plain columns.
|
||||
// Columns use the primary axes (category axis 1111… + left value axis 2222…), the line
|
||||
// uses the secondary axes (hidden category axis 3333… + right secondary value axis 4444…),
|
||||
// matching how PowerPoint writes "combo chart + secondary axis".
|
||||
const lineCount = opts.series.length >= 2 ? 1 : 0
|
||||
const barEnd = opts.series.length - lineCount
|
||||
const barSers = opts.series.slice(0, barEnd).map(serXml).join('')
|
||||
const lineSers = opts.series
|
||||
.slice(barEnd)
|
||||
.map((ser, k) => serXml(ser, barEnd + k))
|
||||
.join('')
|
||||
plot =
|
||||
'<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:varyColors val="0"/>' +
|
||||
`${barSers}${dLbls}${gapWidth}<c:axId val="111111111"/><c:axId val="222222222"/></c:barChart>` +
|
||||
(lineSers
|
||||
? '<c:lineChart><c:grouping val="standard"/><c:varyColors val="0"/>' +
|
||||
`${lineSers}${dLbls}<c:marker val="1"/><c:axId val="333333333"/><c:axId val="444444444"/></c:lineChart>`
|
||||
: '') +
|
||||
'<c:catAx><c:axId val="111111111"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
|
||||
`<c:delete val="0"/><c:axPos val="b"/>${catTitle}<c:crossAx val="222222222"/></c:catAx>` +
|
||||
'<c:valAx><c:axId val="222222222"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
|
||||
`<c:delete val="0"/><c:axPos val="l"/>${grid}${valTitle}<c:crossAx val="111111111"/></c:valAx>` +
|
||||
(lineSers
|
||||
? '<c:valAx><c:axId val="444444444"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
|
||||
'<c:delete val="0"/><c:axPos val="r"/><c:crossAx val="333333333"/><c:crosses val="max"/></c:valAx>' +
|
||||
'<c:catAx><c:axId val="333333333"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
|
||||
'<c:delete val="1"/><c:axPos val="b"/><c:crossAx val="444444444"/></c:catAx>'
|
||||
: '')
|
||||
} else if (opts.kind === 'pie') {
|
||||
plot = `<c:pieChart><c:varyColors val="1"/>${sers}${dLbls}<c:firstSliceAng val="0"/></c:pieChart>`
|
||||
} else if (opts.kind === 'doughnut') {
|
||||
plot =
|
||||
`<c:doughnutChart><c:varyColors val="1"/>${sers}${dLbls}` +
|
||||
'<c:firstSliceAng val="0"/><c:holeSize val="50"/></c:doughnutChart>'
|
||||
} else if (opts.kind === 'scatter') {
|
||||
// Scatter (XY): x values come from categories (numeric strings use their value,
|
||||
// otherwise ordinals 1..n), y values from the series values;
|
||||
// series data uses c:xVal/c:yVal, with dual value axes (x axis axPos=b, y axis axPos=l)
|
||||
const xs = opts.categories.map((c, i) => {
|
||||
const v = Number(c)
|
||||
return c.trim() !== '' && Number.isFinite(v) ? v : i + 1
|
||||
})
|
||||
const scatterSers = opts.series
|
||||
.map((ser, i) => {
|
||||
const col = colLetter(i)
|
||||
return (
|
||||
`<c:ser><c:idx val="${i}"/><c:order val="${i}"/>` +
|
||||
txXml(ser.name, i) +
|
||||
`<c:xVal>${numCacheXml(xs, `Sheet1!$A$2:$A$${rows + 1}`)}</c:xVal>` +
|
||||
`<c:yVal>${numCacheXml(ser.values.slice(0, rows), `Sheet1!$${col}$2:$${col}$${rows + 1}`)}</c:yVal>` +
|
||||
'<c:smooth val="0"/></c:ser>'
|
||||
)
|
||||
})
|
||||
.join('')
|
||||
plot =
|
||||
'<c:scatterChart><c:scatterStyle val="lineMarker"/><c:varyColors val="0"/>' +
|
||||
`${scatterSers}${dLbls}<c:axId val="111111111"/><c:axId val="222222222"/></c:scatterChart>` +
|
||||
'<c:valAx><c:axId val="111111111"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
|
||||
`<c:delete val="0"/><c:axPos val="b"/>${catTitle}<c:crossAx val="222222222"/></c:valAx>` +
|
||||
'<c:valAx><c:axId val="222222222"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
|
||||
`<c:delete val="0"/><c:axPos val="l"/>${grid}${valTitle}<c:crossAx val="111111111"/></c:valAx>`
|
||||
} else {
|
||||
// Horizontal bar chart (barDir=bar): category axis on the left, value axis at the bottom (matches how PowerPoint writes it)
|
||||
const isBarKind = opts.kind === 'bar' || opts.kind === 'barStacked' || opts.kind === 'barPercentStacked'
|
||||
const horizontal = isBarKind && opts.barDir === 'bar'
|
||||
const axes =
|
||||
`<c:catAx><c:axId val="111111111"/><c:scaling><c:orientation val="minMax"/></c:scaling>` +
|
||||
`<c:delete val="0"/><c:axPos val="${horizontal ? 'l' : 'b'}"/>${catTitle}<c:crossAx val="222222222"/></c:catAx>` +
|
||||
'<c:valAx><c:axId val="222222222"/><c:scaling><c:orientation val="minMax"/></c:scaling>' +
|
||||
`<c:delete val="0"/><c:axPos val="${horizontal ? 'b' : 'l'}"/>${grid}${valTitle}<c:crossAx val="111111111"/></c:valAx>`
|
||||
const axIds = '<c:axId val="111111111"/><c:axId val="222222222"/>'
|
||||
let inner: string
|
||||
if (opts.kind === 'radar') {
|
||||
// Radar: categories are vertices (clockwise from 12 o'clock), standard style (unfilled lines)
|
||||
inner = `<c:radarChart><c:radarStyle val="standard"/><c:varyColors val="0"/>${sers}${dLbls}${axIds}</c:radarChart>`
|
||||
} else if (opts.kind === 'line') {
|
||||
inner = `<c:lineChart><c:grouping val="standard"/><c:varyColors val="0"/>${sers}${dLbls}<c:marker val="1"/>${axIds}</c:lineChart>`
|
||||
} else if (opts.kind === 'area') {
|
||||
inner = `<c:areaChart><c:grouping val="standard"/><c:varyColors val="0"/>${sers}${dLbls}${axIds}</c:areaChart>`
|
||||
} else {
|
||||
const grouping =
|
||||
opts.kind === 'barPercentStacked' ? 'percentStacked' : opts.kind === 'barStacked' ? 'stacked' : 'clustered'
|
||||
const overlap = grouping === 'clustered' ? '' : '<c:overlap val="100"/>'
|
||||
inner =
|
||||
`<c:barChart><c:barDir val="${horizontal ? 'bar' : 'col'}"/><c:grouping val="${grouping}"/><c:varyColors val="0"/>` +
|
||||
`${sers}${dLbls}${gapWidth}${overlap}${axIds}</c:barChart>`
|
||||
}
|
||||
plot = inner + axes
|
||||
}
|
||||
|
||||
const title = opts.title
|
||||
? '<c:title><c:tx><c:rich><a:bodyPr/><a:lstStyle/><a:p><a:r>' +
|
||||
`<a:t>${escapeXmlText(opts.title)}</a:t></a:r></a:p></c:rich></c:tx>` +
|
||||
'<c:overlay val="0"/></c:title><c:autoTitleDeleted val="0"/>'
|
||||
: '<c:autoTitleDeleted val="1"/>'
|
||||
|
||||
const legendPos = opts.legendPos ?? 'b'
|
||||
const legend =
|
||||
legendPos === 'none'
|
||||
? ''
|
||||
: `<c:legend><c:legendPos val="${legendPos}"/><c:overlay val="0"/></c:legend>`
|
||||
return (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
|
||||
`<c:chartSpace xmlns:c="${C_NS}" xmlns:a="${A_NS}" xmlns:r="${R_NS}">` +
|
||||
`<c:chart>${title}<c:plotArea><c:layout/>${plot}</c:plotArea>` +
|
||||
legend +
|
||||
'<c:plotVisOnly val="1"/><c:dispBlanksAs val="gap"/></c:chart>' +
|
||||
'</c:chartSpace>'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a chart: part surgery + graphicFrame fragment append + reparse.
|
||||
* Returns the new slide and element id (all ids on the slide refreshed).
|
||||
*/
|
||||
export function addChart(
|
||||
opened: OpenedPptx,
|
||||
slideIndex: number,
|
||||
opts: NewChartOptions,
|
||||
): { slide: Slide; elementId: string } | null {
|
||||
const { archive } = opened
|
||||
const slide = opened.deck.slides[slideIndex]
|
||||
if (!slide || !opts.categories.length || !opts.series.length) return null
|
||||
|
||||
// 1) chart part: number = current max + 1
|
||||
let maxNum = 0
|
||||
for (const path of archive.entries.keys()) {
|
||||
const m = /^ppt\/charts\/chart(\d+)\.xml$/.exec(path)
|
||||
if (m) maxNum = Math.max(maxNum, Number(m[1]))
|
||||
}
|
||||
const chartPath = `ppt/charts/chart${maxNum + 1}.xml`
|
||||
archive.entries.set(chartPath, Buffer.from(buildChartSpaceXml(opts), 'utf8'))
|
||||
|
||||
// 2) [Content_Types].xml Override
|
||||
const ctPath = '[Content_Types].xml'
|
||||
const ct = archive.readText(ctPath)
|
||||
if (ct && !ct.includes(`PartName="/${chartPath}"`)) {
|
||||
const override = `<Override PartName="/${chartPath}" ContentType="${CHART_CONTENT_TYPE}"/>`
|
||||
archive.entries.set(ctPath, Buffer.from(ct.replace('</Types>', `${override}</Types>`), 'utf8'))
|
||||
}
|
||||
|
||||
// 3) slide rels
|
||||
const relsPath = relsPathFor(slide.path)
|
||||
const rels =
|
||||
archive.readText(relsPath) ??
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>'
|
||||
let maxRid = 0
|
||||
for (const m of rels.matchAll(/Id="rId(\d+)"/g)) maxRid = Math.max(maxRid, Number(m[1]))
|
||||
const rid = `rId${maxRid + 1}`
|
||||
const relXml = `<Relationship Id="${rid}" Type="${CHART_REL_TYPE}" Target="../charts/chart${maxNum + 1}.xml"/>`
|
||||
archive.entries.set(relsPath, Buffer.from(rels.replace('</Relationships>', `${relXml}</Relationships>`), 'utf8'))
|
||||
|
||||
// 4) graphicFrame fragment + append reparse
|
||||
const id = nextCNvPrId(slide)
|
||||
const o = opts.offset
|
||||
const name = opts.title ? `Chart ${id} - ${opts.title}` : `Chart ${id}`
|
||||
// descr="aislides-chart" marks charts created by this app (like the ink marker); recognized as editable charts on reopen
|
||||
const frameXml =
|
||||
`<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}" descr="aislides-chart"/>` +
|
||||
'<p:cNvGraphicFramePr/><p:nvPr/></p:nvGraphicFramePr>' +
|
||||
`<p:xfrm><a:off x="${o.x}" y="${o.y}"/><a:ext cx="${o.cx}" cy="${o.cy}"/></p:xfrm>` +
|
||||
`<a:graphic><a:graphicData uri="${C_NS}">` +
|
||||
`<c:chart xmlns:c="${C_NS}" xmlns:r="${R_NS}" r:id="${rid}"/>` +
|
||||
'</a:graphicData></a:graphic></p:graphicFrame>'
|
||||
|
||||
const r = appendRawElements(opened, slideIndex, [frameXml])
|
||||
return r ? { slide: r.slide, elementId: r.elementIds[r.elementIds.length - 1]! } : null
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
/**
|
||||
* Chart parsing (ppt/charts/chartN.xml → ChartModel).
|
||||
*
|
||||
* Read-only semantic parsing: on a slide a chart is a separate part referenced by
|
||||
* a <p:graphicFrame>; byte fidelity is guaranteed by passing the graphicFrame's
|
||||
* anchor bytes through verbatim, and the chart part is never rewritten.
|
||||
*
|
||||
* Supports data + explicit styling (series colors, axis label styles, gridlines)
|
||||
* for lineChart / barChart (incl. horizontal bars) / pieChart (incl. doughnut) /
|
||||
* areaChart / scatterChart / radarChart; missing styles fall back to the theme
|
||||
* palette. bar/area/line can be combined in one plotArea (column+line combo);
|
||||
* combined series carry plotKind and the primary type is picked bar > area > line;
|
||||
* series on the secondary value axis (axPos=r, not deleted, matched by the plot's
|
||||
* c:axId) carry secondaryAxis, with the secondary axis style/range parsed into
|
||||
* valAxis2.
|
||||
*/
|
||||
import { XMLParser } from 'fast-xml-parser'
|
||||
import { type Theme } from './theme'
|
||||
import { resolveColorNode } from './color'
|
||||
|
||||
const chartParser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
attributeNamePrefix: '@_',
|
||||
trimValues: false,
|
||||
parseTagValue: false,
|
||||
isArray: (name) => ['c:ser', 'c:pt', 'c:lvl', 'c:dPt'].includes(name),
|
||||
})
|
||||
|
||||
export type ChartKind = 'line' | 'bar' | 'pie' | 'area' | 'scatter' | 'radar' | 'unknown'
|
||||
|
||||
export interface ChartSeries {
|
||||
name?: string
|
||||
/** Series main color #RRGGBB (explicit spPr color; render layer fills in from the theme palette otherwise) */
|
||||
color?: string
|
||||
values: Array<number | null>
|
||||
/** Combo chart (e.g. bar+line): the plot type this series belongs to; default = ChartModel.kind */
|
||||
plotKind?: 'line' | 'bar' | 'area'
|
||||
/** Scatter: x values (c:xVal numeric cache; y values in values). Empty → render layer uses ordinals 1..n */
|
||||
xValues?: Array<number | null>
|
||||
/** Line: smoothed curve */
|
||||
smooth?: boolean
|
||||
/** Whether to draw data point markers (line defaults to false; scatter/radar default
|
||||
* comes from the style; only set when <c:marker><c:symbol> is explicit) */
|
||||
marker?: boolean
|
||||
/** Explicit per-point colors <c:dPt> (common for pies; render layer palette otherwise) */
|
||||
pointColors?: Array<string | undefined>
|
||||
/** Combo dual axes: this series is on the secondary value axis (independent right-side range; decided by the plot's c:axId) */
|
||||
secondaryAxis?: boolean
|
||||
}
|
||||
|
||||
export interface ChartAxisStyle {
|
||||
/** Explicit min/max (render layer computes a nice range from the data otherwise) */
|
||||
min?: number
|
||||
max?: number
|
||||
labelColor?: string
|
||||
labelSizePt?: number
|
||||
lineColor?: string
|
||||
gridColor?: string
|
||||
gridDash?: boolean
|
||||
title?: string
|
||||
/** <c:orientation val="maxMin"/>: categories/values reversed (common for bar charts with the first category on top) */
|
||||
reversed?: boolean
|
||||
}
|
||||
|
||||
export interface ChartModel {
|
||||
kind: ChartKind
|
||||
/** bar only: col = vertical columns, bar = horizontal bars */
|
||||
barDir?: 'col' | 'bar'
|
||||
grouping?: 'clustered' | 'stacked' | 'percentStacked' | 'standard'
|
||||
/** Gap between bars (% of bar width, c:gapWidth, default 150) */
|
||||
gapWidthPct?: number
|
||||
categories: string[]
|
||||
series: ChartSeries[]
|
||||
/** Legend position (undefined when there is no c:legend) */
|
||||
legendPos?: 't' | 'b' | 'l' | 'r' | 'tr'
|
||||
valAxis?: ChartAxisStyle
|
||||
/** Secondary value axis (right side, combo column+line dual axes; undefined without a right value axis or style info) */
|
||||
valAxis2?: ChartAxisStyle
|
||||
catAxis?: ChartAxisStyle
|
||||
/** Doughnut hole (% of radius, c:holeSize; pie = 0) */
|
||||
holePct?: number
|
||||
/** First slice start angle (degrees, 12 o'clock = 0, clockwise; c:firstSliceAng) */
|
||||
firstSliceAngDeg?: number
|
||||
/** Scatter style (c:scatterStyle: line/lineMarker/marker/smooth/smoothMarker/none) */
|
||||
scatterStyle?: string
|
||||
/** Radar style (c:radarStyle) */
|
||||
radarStyle?: 'standard' | 'marker' | 'filled'
|
||||
/** Data labels (showVal or showPercent on plot/ser-level c:dLbls) */
|
||||
dataLabels?: boolean
|
||||
/** Data labels show percentages only (showPercent only, common for pies) */
|
||||
dataLabelsPct?: boolean
|
||||
/** Chart title (concatenated rich text of c:chart/c:title) */
|
||||
title?: string
|
||||
}
|
||||
|
||||
/** Parse one chartN.xml. Returns null for unrecognized plot types (caller falls back to a placeholder chip). */
|
||||
export function parseChartXml(xml: string, theme?: Theme): ChartModel | null {
|
||||
let doc: any
|
||||
try {
|
||||
doc = chartParser.parse(xml)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const chart = doc['c:chartSpace']?.['c:chart']
|
||||
const plotArea = chart?.['c:plotArea']
|
||||
if (!plotArea) return null
|
||||
|
||||
// Cartesian types (bar/area/line) may coexist combined (e.g. column+line combo); pie/scatter/radar stand alone.
|
||||
const cartesian: Array<{ kind: 'bar' | 'area' | 'line'; plot: any }> = []
|
||||
if (plotArea['c:barChart']) cartesian.push({ kind: 'bar', plot: plotArea['c:barChart'] })
|
||||
if (plotArea['c:areaChart']) cartesian.push({ kind: 'area', plot: plotArea['c:areaChart'] })
|
||||
if (plotArea['c:lineChart']) cartesian.push({ kind: 'line', plot: plotArea['c:lineChart'] })
|
||||
|
||||
let kind: ChartKind
|
||||
let plot: any
|
||||
if (cartesian.length) {
|
||||
// Primary type is the first (bar > area > line): axis/bar params read from it; other combo series carry plotKind
|
||||
kind = cartesian[0]!.kind
|
||||
plot = cartesian[0]!.plot
|
||||
} else if (plotArea['c:pieChart'] || plotArea['c:doughnutChart']) {
|
||||
kind = 'pie'
|
||||
plot = plotArea['c:pieChart'] ?? plotArea['c:doughnutChart']
|
||||
} else if (plotArea['c:scatterChart']) {
|
||||
kind = 'scatter'
|
||||
plot = plotArea['c:scatterChart']
|
||||
} else if (plotArea['c:radarChart']) {
|
||||
kind = 'radar'
|
||||
plot = plotArea['c:radarChart']
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
|
||||
// Extract value axis nodes up front: combo dual axes need the secondary value
|
||||
// axis's axId (axPos=r and not deleted) first, so series parsing can decide
|
||||
// "primary or secondary axis" by the owning plot's c:axId
|
||||
const valAxRaw = plotArea['c:valAx']
|
||||
const valAxes: any[] = Array.isArray(valAxRaw) ? valAxRaw : valAxRaw ? [valAxRaw] : []
|
||||
const secValAxNode =
|
||||
kind !== 'scatter' && cartesian.length > 1
|
||||
? valAxes.find((a) => a?.['c:axPos']?.['@_val'] === 'r' && a?.['c:delete']?.['@_val'] !== '1')
|
||||
: undefined
|
||||
const secAxId: string | undefined = secValAxNode?.['c:axId']?.['@_val']
|
||||
// Axes attached to a plot node (two c:axIds: category axis + value axis)
|
||||
const plotAxIds = (plotNode: any): string[] => {
|
||||
const raw = plotNode?.['c:axId']
|
||||
const arr: any[] = Array.isArray(raw) ? raw : raw ? [raw] : []
|
||||
return arr.map((a) => a?.['@_val']).filter((v): v is string => v != null)
|
||||
}
|
||||
|
||||
const series: ChartSeries[] = []
|
||||
let categories: string[] = []
|
||||
const parsePlotSeries = (plotNode: any, plotKind: ChartKind, tagPlotKind: boolean, secondary = false) => {
|
||||
const sersRaw = plotNode['c:ser']
|
||||
const sers: any[] = Array.isArray(sersRaw) ? sersRaw : sersRaw ? [sersRaw] : []
|
||||
for (const ser of sers) {
|
||||
// Scatter: y values in c:yVal, x values in c:xVal; other types use c:val
|
||||
const s: ChartSeries = { values: readNumPoints(plotKind === 'scatter' ? ser['c:yVal'] : ser['c:val']) }
|
||||
if (tagPlotKind) s.plotKind = plotKind as 'line' | 'bar' | 'area'
|
||||
if (secondary) s.secondaryAxis = true
|
||||
if (plotKind === 'scatter') {
|
||||
const xs = readNumPoints(ser['c:xVal'])
|
||||
if (xs.length) s.xValues = xs
|
||||
}
|
||||
const name = readStrPoints(ser['c:tx'])[0]
|
||||
if (name != null) s.name = name
|
||||
const color = serColor(ser, theme)
|
||||
if (color) s.color = color
|
||||
if (ser['c:smooth']?.['@_val'] === '1') s.smooth = true
|
||||
const markerSym = ser['c:marker']?.['c:symbol']?.['@_val']
|
||||
if (plotKind === 'line') s.marker = markerSym != null && markerSym !== 'none'
|
||||
// scatter/radar: default marker decided by style; only set for explicit symbol (none → false)
|
||||
else if ((plotKind === 'scatter' || plotKind === 'radar') && markerSym != null) s.marker = markerSym !== 'none'
|
||||
// Per-data-point colors (one color per pie slice)
|
||||
const dPts: any[] = ser['c:dPt'] ?? []
|
||||
if (dPts.length) {
|
||||
const pointColors: Array<string | undefined> = []
|
||||
for (const dPt of dPts) {
|
||||
const idx = parseInt(dPt['c:idx']?.['@_val'], 10)
|
||||
if (Number.isNaN(idx)) continue
|
||||
const c = resolveColorNode(dPt['c:spPr']?.['a:solidFill'], theme)
|
||||
if (c != null) pointColors[idx] = c
|
||||
}
|
||||
if (pointColors.length) s.pointColors = pointColors
|
||||
}
|
||||
series.push(s)
|
||||
// Categories: take the first non-empty series' cat
|
||||
if (!categories.length) categories = readStrPoints(ser['c:cat'])
|
||||
}
|
||||
}
|
||||
if (cartesian.length > 1) {
|
||||
for (const c of cartesian)
|
||||
parsePlotSeries(c.plot, c.kind, true, secAxId != null && plotAxIds(c.plot).includes(secAxId))
|
||||
} else parsePlotSeries(plot, kind, false)
|
||||
if (!series.length) return null
|
||||
if (!categories.length) {
|
||||
// With no category cache, keep names empty (length from the longest series); never inject placeholders
|
||||
const n = Math.max(...series.map((s) => s.values.length), 0)
|
||||
categories = Array.from({ length: n }, () => '')
|
||||
}
|
||||
|
||||
const model: ChartModel = { kind, categories, series }
|
||||
|
||||
if (kind === 'bar') {
|
||||
const dir = plot['c:barDir']?.['@_val']
|
||||
model.barDir = dir === 'bar' ? 'bar' : 'col'
|
||||
const grouping = plot['c:grouping']?.['@_val']
|
||||
if (grouping) model.grouping = grouping
|
||||
const gap = plot['c:gapWidth']?.['@_val']
|
||||
model.gapWidthPct = gap != null ? parseInt(gap, 10) : 150
|
||||
}
|
||||
|
||||
if (kind === 'pie') {
|
||||
const hole = plot['c:holeSize']?.['@_val']
|
||||
model.holePct = hole != null ? parseInt(hole, 10) || 0 : plotArea['c:doughnutChart'] ? 50 : 0
|
||||
const first = plot['c:firstSliceAng']?.['@_val']
|
||||
if (first != null) model.firstSliceAngDeg = parseInt(first, 10) || 0
|
||||
}
|
||||
|
||||
if (kind === 'scatter') {
|
||||
const st = plot['c:scatterStyle']?.['@_val']
|
||||
if (st) model.scatterStyle = String(st)
|
||||
}
|
||||
|
||||
if (kind === 'radar') {
|
||||
const st = plot['c:radarStyle']?.['@_val']
|
||||
model.radarStyle = st === 'filled' ? 'filled' : st === 'marker' ? 'marker' : 'standard'
|
||||
}
|
||||
|
||||
const legendPos = chart['c:legend']?.['c:legendPos']?.['@_val']
|
||||
if (chart['c:legend']) model.legendPos = (legendPos as ChartModel['legendPos']) ?? 'r'
|
||||
|
||||
const chartTitle = collectText(chart['c:title']?.['c:tx']?.['c:rich'])
|
||||
if (chartTitle) model.title = chartTitle
|
||||
|
||||
// Data labels: plot-level or any series-level c:dLbls (delete=1 counts as none)
|
||||
const dLblsInfo = (owner: any): { on: boolean; pct: boolean } => {
|
||||
const d = owner?.['c:dLbls']
|
||||
if (!d || typeof d !== 'object' || d['c:delete']?.['@_val'] === '1') return { on: false, pct: false }
|
||||
const showVal = d['c:showVal']?.['@_val'] === '1'
|
||||
const showPct = d['c:showPercent']?.['@_val'] === '1'
|
||||
return { on: showVal || showPct, pct: showPct && !showVal }
|
||||
}
|
||||
const dLblOwners: any[] = (cartesian.length > 1 ? cartesian.map((c) => c.plot) : [plot]).flatMap(
|
||||
(p) => [p, ...((Array.isArray(p['c:ser']) ? p['c:ser'] : p['c:ser'] ? [p['c:ser']] : []) as any[])],
|
||||
)
|
||||
const found = dLblOwners.map(dLblsInfo).find((r) => r.on)
|
||||
if (found) {
|
||||
model.dataLabels = true
|
||||
if (found.pct) model.dataLabelsPct = true
|
||||
}
|
||||
|
||||
// Axes: scatter charts have dual value axes (x at the bottom axPos=b, y on the left); the x axis goes in the catAxis slot
|
||||
if (kind === 'scatter' && valAxes.length >= 2) {
|
||||
const xAxNode = valAxes.find((a) => a?.['c:axPos']?.['@_val'] === 'b') ?? valAxes[0]
|
||||
const yAxNode = valAxes.find((a) => a !== xAxNode) ?? valAxes[1]
|
||||
const xAx = parseAxis(xAxNode, theme)
|
||||
if (xAx) model.catAxis = xAx
|
||||
const yAx = parseAxis(yAxNode, theme)
|
||||
if (yAx) model.valAxis = yAx
|
||||
} else {
|
||||
// A combo chart (column + line secondary axis) has two axis pairs in plotArea:
|
||||
// the value axis is the left primary (axPos=l), the category axis is the
|
||||
// non-deleted one (c:delete≠1); the secondary system's hidden category axis is skipped
|
||||
const valAxNode = valAxes.find((a) => a?.['c:axPos']?.['@_val'] === 'l') ?? valAxes[0]
|
||||
const valAx = parseAxis(valAxNode, theme)
|
||||
if (valAx) model.valAxis = valAx
|
||||
// Secondary value axis (combo dual axes): min/max/style handed to the render layer to draw the right-side ticks
|
||||
if (secValAxNode) {
|
||||
const valAx2 = parseAxis(secValAxNode, theme)
|
||||
if (valAx2) model.valAxis2 = valAx2
|
||||
}
|
||||
const catAxRaw = plotArea['c:catAx']
|
||||
const catAxes: any[] = Array.isArray(catAxRaw) ? catAxRaw : catAxRaw ? [catAxRaw] : []
|
||||
const catAxNode = catAxes.find((a) => a?.['c:delete']?.['@_val'] !== '1') ?? catAxes[0]
|
||||
const catAx = parseAxis(catAxNode, theme)
|
||||
if (catAx) model.catAxis = catAx
|
||||
}
|
||||
|
||||
return model
|
||||
}
|
||||
|
||||
/** Numeric cache inside <c:val>/<c:cat>/<c:tx> → number[] (idx order kept, empty points null). */
|
||||
function readNumPoints(node: any): Array<number | null> {
|
||||
const cache = node?.['c:numRef']?.['c:numCache'] ?? node?.['c:numLit']
|
||||
if (!cache) return []
|
||||
return readPoints(cache).map((v) => {
|
||||
if (v == null || v === '') return null
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) ? n : null
|
||||
})
|
||||
}
|
||||
|
||||
/** String cache (strRef/strCache or the innermost lvl of multiLvlStrRef) → string[]. */
|
||||
function readStrPoints(node: any): string[] {
|
||||
const strCache = node?.['c:strRef']?.['c:strCache']
|
||||
if (strCache) return readPoints(strCache).map((v) => v ?? '')
|
||||
const multi = node?.['c:multiLvlStrRef']?.['c:multiLvlStrCache']
|
||||
if (multi) {
|
||||
const lvls: any[] = Array.isArray(multi['c:lvl']) ? multi['c:lvl'] : multi['c:lvl'] ? [multi['c:lvl']] : []
|
||||
// The innermost (first lvl) holds the leaf categories
|
||||
if (lvls.length) return readPoints(lvls[0]).map((v) => v ?? '')
|
||||
}
|
||||
const numCache = node?.['c:numRef']?.['c:numCache']
|
||||
if (numCache) return readPoints(numCache).map((v) => v ?? '')
|
||||
return []
|
||||
}
|
||||
|
||||
/** c:pt list → value array ordered by idx. */
|
||||
function readPoints(cache: any): Array<string | null> {
|
||||
const ptsRaw = cache?.['c:pt']
|
||||
const pts: any[] = Array.isArray(ptsRaw) ? ptsRaw : ptsRaw ? [ptsRaw] : []
|
||||
const count = cache?.['c:ptCount']?.['@_val']
|
||||
const n = count != null ? parseInt(count, 10) : pts.length
|
||||
const out: Array<string | null> = new Array(Math.max(n, pts.length)).fill(null)
|
||||
for (const pt of pts) {
|
||||
const idx = parseInt(pt['@_idx'], 10) || 0
|
||||
const v = pt['c:v']
|
||||
out[idx] = typeof v === 'string' ? v : v != null ? String(v['#text'] ?? v) : null
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Series main color: ln stroke first (lines), otherwise solidFill (bars/pies). */
|
||||
function serColor(ser: any, theme?: Theme): string | undefined {
|
||||
const spPr = ser['c:spPr']
|
||||
if (!spPr) return undefined
|
||||
const lnColor = resolveColorNode(spPr['a:ln']?.['a:solidFill'], theme)
|
||||
const fillColor = resolveColorNode(spPr['a:solidFill'], theme)
|
||||
return lnColor ?? fillColor
|
||||
}
|
||||
|
||||
function parseAxis(ax: any, theme?: Theme): ChartAxisStyle | undefined {
|
||||
if (!ax || typeof ax !== 'object') return undefined
|
||||
const out: ChartAxisStyle = {}
|
||||
const scaling = ax['c:scaling']
|
||||
if (scaling?.['c:min']?.['@_val'] != null) out.min = Number(scaling['c:min']['@_val'])
|
||||
if (scaling?.['c:max']?.['@_val'] != null) out.max = Number(scaling['c:max']['@_val'])
|
||||
if (scaling?.['c:orientation']?.['@_val'] === 'maxMin') out.reversed = true
|
||||
const defRPr = ax['c:txPr']?.['a:p']?.[0]?.['a:pPr']?.['a:defRPr'] ?? ax['c:txPr']?.['a:p']?.['a:pPr']?.['a:defRPr']
|
||||
if (defRPr) {
|
||||
const c = resolveColorNode(defRPr['a:solidFill'], theme)
|
||||
if (c) out.labelColor = c
|
||||
if (defRPr['@_sz']) out.labelSizePt = parseInt(defRPr['@_sz'], 10) / 100
|
||||
}
|
||||
const lineColor = resolveColorNode(ax['c:spPr']?.['a:ln']?.['a:solidFill'], theme)
|
||||
if (lineColor) out.lineColor = lineColor
|
||||
// A self-closing <c:majorGridlines/> (no spPr) parses to an empty string; still counts as having gridlines
|
||||
const grid = ax['c:majorGridlines']
|
||||
if (grid !== undefined) {
|
||||
const spPr = typeof grid === 'object' ? grid['c:spPr'] : undefined
|
||||
const gc = resolveColorNode(spPr?.['a:ln']?.['a:solidFill'], theme)
|
||||
out.gridColor = gc ?? '#E6E6E6'
|
||||
if (spPr?.['a:ln']?.['a:prstDash']?.['@_val'] === 'dash') out.gridDash = true
|
||||
}
|
||||
// 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
|
||||
return Object.keys(out).length ? out : undefined
|
||||
}
|
||||
|
||||
/** Collect all a:t inside a rich text node. */
|
||||
function collectText(rich: any): string | undefined {
|
||||
if (!rich) return undefined
|
||||
const paras: any[] = Array.isArray(rich['a:p']) ? rich['a:p'] : rich['a:p'] ? [rich['a:p']] : []
|
||||
const parts: string[] = []
|
||||
for (const p of paras) {
|
||||
const runs: any[] = Array.isArray(p['a:r']) ? p['a:r'] : p['a:r'] ? [p['a:r']] : []
|
||||
for (const r of runs) {
|
||||
const t = r['a:t']
|
||||
parts.push(typeof t === 'string' ? t : String(t?.['#text'] ?? ''))
|
||||
}
|
||||
}
|
||||
const s = parts.join('')
|
||||
return s.trim() ? s : undefined
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Color node resolution (srgbClr/schemeClr/sysClr + lumMod/lumOff/tint/shade/alpha modifiers).
|
||||
* Extracted from parse.ts into a shared module: used by both parse (run/fill colors) and
|
||||
* placeholder (lstStyle defRPr default colors) to avoid a circular dependency.
|
||||
*/
|
||||
import { type Theme, resolveSchemeColor } from './theme'
|
||||
import { asXmlNode, type XmlNode } from './xml-utils'
|
||||
|
||||
/**
|
||||
* Resolve a color node + modifiers: srgbClr/schemeClr/sysClr, supporting alpha
|
||||
* (→#RRGGBBAA) and lumMod/lumOff (tint/shade, common for theme colors).
|
||||
*/
|
||||
export function resolveColorNode(node: unknown, theme: Theme | undefined, phClr?: string): string | undefined {
|
||||
if (!node) return undefined
|
||||
const n = asXmlNode(node)
|
||||
let base: string | undefined
|
||||
let mods: XmlNode | undefined
|
||||
if (n['a:srgbClr']) {
|
||||
mods = asXmlNode(n['a:srgbClr'])
|
||||
base = '#' + String(mods['@_val']).toUpperCase()
|
||||
} else if (n['a:schemeClr']) {
|
||||
mods = asXmlNode(n['a:schemeClr'])
|
||||
base = resolveSchemeColor(String(mods['@_val']), theme, phClr)
|
||||
} else if (n['a:sysClr']) {
|
||||
mods = asXmlNode(n['a:sysClr'])
|
||||
base = '#' + String(mods['@_lastClr'] ?? '000000').toUpperCase()
|
||||
}
|
||||
if (!base) return undefined
|
||||
return applyColorMods(base, mods)
|
||||
}
|
||||
|
||||
/** Apply lumMod/lumOff/tint/shade/satMod/alpha modifiers (percentages, in units of 1/1000%). */
|
||||
export function applyColorMods(hex: string, mods: XmlNode | undefined): string {
|
||||
let { r, g, b } = hexToRgb(hex)
|
||||
const pct = (k: string): number | undefined => {
|
||||
const v = asXmlNode(mods?.[k])['@_val']
|
||||
return v != null ? (parseInt(String(v), 10) || 0) / 100000 : undefined
|
||||
}
|
||||
const lumMod = pct('a:lumMod')
|
||||
const lumOff = pct('a:lumOff')
|
||||
const shade = pct('a:shade')
|
||||
const tint = pct('a:tint')
|
||||
// satMod (frequent in theme gradient templates): HSL saturation multiplier
|
||||
const satMod = pct('a:satMod')
|
||||
if (satMod != null) {
|
||||
const { h, s, l } = rgbToHsl(r, g, b)
|
||||
const rgb2 = hslToRgb(h, Math.max(0, Math.min(1, s * satMod)), l)
|
||||
r = rgb2.r
|
||||
g = rgb2.g
|
||||
b = rgb2.b
|
||||
}
|
||||
if (lumMod != null) {
|
||||
r *= lumMod
|
||||
g *= lumMod
|
||||
b *= lumMod
|
||||
}
|
||||
if (lumOff != null) {
|
||||
r += 255 * lumOff
|
||||
g += 255 * lumOff
|
||||
b += 255 * lumOff
|
||||
}
|
||||
if (shade != null) {
|
||||
r *= shade
|
||||
g *= shade
|
||||
b *= shade
|
||||
}
|
||||
if (tint != null) {
|
||||
r = r * tint + 255 * (1 - tint)
|
||||
g = g * tint + 255 * (1 - tint)
|
||||
b = b * tint + 255 * (1 - tint)
|
||||
}
|
||||
const clamp = (v: number) => Math.max(0, Math.min(255, Math.round(v)))
|
||||
let out = '#' + [clamp(r), clamp(g), clamp(b)].map((v) => v.toString(16).padStart(2, '0')).join('').toUpperCase()
|
||||
const alpha = pct('a:alpha')
|
||||
if (alpha != null && alpha < 1) {
|
||||
out += Math.round(alpha * 255).toString(16).padStart(2, '0').toUpperCase()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function hexToRgb(hex: string): { r: number; g: number; b: number } {
|
||||
const h = hex.replace(/^#/, '')
|
||||
return {
|
||||
r: parseInt(h.slice(0, 2), 16) || 0,
|
||||
g: parseInt(h.slice(2, 4), 16) || 0,
|
||||
b: parseInt(h.slice(4, 6), 16) || 0,
|
||||
}
|
||||
}
|
||||
|
||||
function rgbToHsl(r: number, g: number, b: number): { h: number; s: number; l: number } {
|
||||
r /= 255
|
||||
g /= 255
|
||||
b /= 255
|
||||
const max = Math.max(r, g, b)
|
||||
const min = Math.min(r, g, b)
|
||||
const l = (max + min) / 2
|
||||
if (max === min) return { h: 0, s: 0, l }
|
||||
const d = max - min
|
||||
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
|
||||
let h: number
|
||||
if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6
|
||||
else if (max === g) h = ((b - r) / d + 2) / 6
|
||||
else h = ((r - g) / d + 4) / 6
|
||||
return { h, s, l }
|
||||
}
|
||||
|
||||
function hslToRgb(h: number, s: number, l: number): { r: number; g: number; b: number } {
|
||||
if (s === 0) {
|
||||
const v = l * 255
|
||||
return { r: v, g: v, b: v }
|
||||
}
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s
|
||||
const p = 2 * l - q
|
||||
const f = (t: number) => {
|
||||
if (t < 0) t += 1
|
||||
if (t > 1) t -= 1
|
||||
if (t < 1 / 6) return p + (q - p) * 6 * t
|
||||
if (t < 1 / 2) return q
|
||||
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6
|
||||
return p
|
||||
}
|
||||
return { r: f(h + 1 / 3) * 255, g: f(h) * 255, b: f(h - 1 / 3) * 255 }
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* Slide comments (classic comments part) read/write — archive surgery.
|
||||
*
|
||||
* Structure: ppt/commentAuthors.xml (author table, referenced by
|
||||
* presentation.xml.rels) + one ppt/comments/commentN.xml per slide (referenced by
|
||||
* slide rels). A comment is uniquely identified by (authorId, idx). All changes
|
||||
* land in archive.entries: savePptx persists automatically, and the main process's
|
||||
* snapshot-style undo covers them automatically.
|
||||
*/
|
||||
import type { OpenedPptx } from './index'
|
||||
import { resolveTarget, type PackageArchive } from './zip'
|
||||
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
|
||||
import { appendRelationship, unescapeXml } from './notes'
|
||||
|
||||
const XMLDECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
const NS_P = 'http://schemas.openxmlformats.org/presentationml/2006/main'
|
||||
|
||||
const REL_BASE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
|
||||
const COMMENTS_REL = `${REL_BASE}/comments`
|
||||
const AUTHORS_REL = `${REL_BASE}/commentAuthors`
|
||||
|
||||
const COMMENTS_CT = 'application/vnd.openxmlformats-officedocument.presentationml.comments+xml'
|
||||
const AUTHORS_CT = 'application/vnd.openxmlformats-officedocument.presentationml.commentAuthors+xml'
|
||||
|
||||
const AUTHORS_PATH = 'ppt/commentAuthors.xml'
|
||||
|
||||
export interface SlideComment {
|
||||
authorId: number
|
||||
author: string
|
||||
initials: string
|
||||
/** ISO timestamp (the dt attribute in the part) */
|
||||
dt: string
|
||||
idx: number
|
||||
text: string
|
||||
}
|
||||
|
||||
function setEntry(archive: PackageArchive, path: string, xml: string): void {
|
||||
archive.entries.set(path, Buffer.from(xml, 'utf8'))
|
||||
}
|
||||
|
||||
function addContentTypeOverride(
|
||||
archive: PackageArchive,
|
||||
partPath: string,
|
||||
contentType: string,
|
||||
): void {
|
||||
const ctPath = '[Content_Types].xml'
|
||||
const ct = archive.readText(ctPath)
|
||||
if (!ct || ct.includes(`PartName="/${partPath}"`)) return
|
||||
setEntry(
|
||||
archive,
|
||||
ctPath,
|
||||
ct.replace(
|
||||
'</Types>',
|
||||
`<Override PartName="/${partPath}" ContentType="${contentType}"/></Types>`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** Author table: id → {name, initials}. */
|
||||
function readAuthors(archive: PackageArchive): Map<number, { name: string; initials: string }> {
|
||||
const map = new Map<number, { name: string; initials: string }>()
|
||||
const xml = archive.readText(AUTHORS_PATH)
|
||||
if (!xml) return map
|
||||
for (const m of xml.matchAll(/<p:cmAuthor\b([^>]*)\/>/g)) {
|
||||
const attrs = m[1]!
|
||||
const id = Number(/\bid="(\d+)"/.exec(attrs)?.[1] ?? -1)
|
||||
if (id < 0) continue
|
||||
map.set(id, {
|
||||
name: unescapeXml(/\bname="([^"]*)"/.exec(attrs)?.[1] ?? ''),
|
||||
initials: unescapeXml(/\binitials="([^"]*)"/.exec(attrs)?.[1] ?? ''),
|
||||
})
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
/** Path of a slide's comments part (null if the slide has no comments). */
|
||||
function commentsPathForSlide(archive: PackageArchive, slidePath: string): string | null {
|
||||
for (const rel of archive.readRels(slidePath).values()) {
|
||||
if (rel.type === COMMENTS_REL) return resolveTarget(slidePath, rel.target)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Read all comments on a slide (in order of appearance). */
|
||||
export function getSlideComments(archive: PackageArchive, slidePath: string): SlideComment[] {
|
||||
const partPath = commentsPathForSlide(archive, slidePath)
|
||||
if (!partPath) return []
|
||||
const xml = archive.readText(partPath)
|
||||
if (!xml) return []
|
||||
const authors = readAuthors(archive)
|
||||
const out: SlideComment[] = []
|
||||
for (const m of xml.matchAll(/<p:cm\b([^>]*)>([\s\S]*?)<\/p:cm>/g)) {
|
||||
const attrs = m[1]!
|
||||
const authorId = Number(/\bauthorId="(\d+)"/.exec(attrs)?.[1] ?? 0)
|
||||
const a = authors.get(authorId)
|
||||
out.push({
|
||||
authorId,
|
||||
author: a?.name ?? 'Unknown author',
|
||||
initials: a?.initials ?? '',
|
||||
dt: /\bdt="([^"]*)"/.exec(attrs)?.[1] ?? '',
|
||||
idx: Number(/\bidx="(\d+)"/.exec(attrs)?.[1] ?? 0),
|
||||
text: unescapeXml(/<p:text>([\s\S]*?)<\/p:text>/.exec(m[2]!)?.[1] ?? ''),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the author exists and return {authorId, nextIdx} (bumping lastIdx).
|
||||
* Creates the author table / content type / presentation rel if missing.
|
||||
*/
|
||||
function ensureAuthor(
|
||||
archive: PackageArchive,
|
||||
name: string,
|
||||
initials: string,
|
||||
): { authorId: number; nextIdx: number } {
|
||||
let xml = archive.readText(AUTHORS_PATH)
|
||||
if (!xml) {
|
||||
xml = XMLDECL + `<p:cmAuthorLst xmlns:p="${NS_P}"></p:cmAuthorLst>`
|
||||
addContentTypeOverride(archive, AUTHORS_PATH, AUTHORS_CT)
|
||||
appendRelationship(archive, 'ppt/presentation.xml', AUTHORS_REL, 'commentAuthors.xml')
|
||||
}
|
||||
// Existing author with the same name: reuse its id, lastIdx + 1
|
||||
for (const m of xml.matchAll(/<p:cmAuthor\b([^>]*)\/>/g)) {
|
||||
const attrs = m[1]!
|
||||
if (unescapeXml(/\bname="([^"]*)"/.exec(attrs)?.[1] ?? '') !== name) continue
|
||||
const authorId = Number(/\bid="(\d+)"/.exec(attrs)?.[1] ?? 0)
|
||||
const lastIdx = Number(/\blastIdx="(\d+)"/.exec(attrs)?.[1] ?? 0)
|
||||
const nextIdx = lastIdx + 1
|
||||
const bumped = m[0].includes('lastIdx="')
|
||||
? m[0].replace(/\blastIdx="\d+"/, `lastIdx="${nextIdx}"`)
|
||||
: m[0].replace('/>', ` lastIdx="${nextIdx}"/>`)
|
||||
setEntry(archive, AUTHORS_PATH, xml.replace(m[0], bumped))
|
||||
return { authorId, nextIdx }
|
||||
}
|
||||
// New author
|
||||
let maxId = -1
|
||||
for (const m of xml.matchAll(/<p:cmAuthor\b[^>]*\bid="(\d+)"/g))
|
||||
maxId = Math.max(maxId, Number(m[1]))
|
||||
const authorId = maxId + 1
|
||||
const tag =
|
||||
`<p:cmAuthor id="${authorId}" name="${escapeXmlAttr(name)}"` +
|
||||
` initials="${escapeXmlAttr(initials)}" lastIdx="1" clrIdx="${authorId}"/>`
|
||||
setEntry(archive, AUTHORS_PATH, xml.replace('</p:cmAuthorLst>', `${tag}</p:cmAuthorLst>`))
|
||||
return { authorId, nextIdx: 1 }
|
||||
}
|
||||
|
||||
/** Add a comment; returns the new comment (with assigned authorId/idx). */
|
||||
export function addSlideComment(
|
||||
opened: OpenedPptx,
|
||||
slideIndex: number,
|
||||
opts: { author: string; initials?: string; text: string },
|
||||
): SlideComment | null {
|
||||
const slide = opened.deck.slides[slideIndex]
|
||||
if (!slide) return null
|
||||
const { archive } = opened
|
||||
const initials =
|
||||
opts.initials ??
|
||||
opts.author
|
||||
.split(/\s+/)
|
||||
.map((w) => w[0] ?? '')
|
||||
.join('')
|
||||
.toUpperCase() ??
|
||||
''
|
||||
const { authorId, nextIdx } = ensureAuthor(archive, opts.author, initials)
|
||||
|
||||
let partPath = commentsPathForSlide(archive, slide.path)
|
||||
if (!partPath) {
|
||||
let maxNum = 0
|
||||
for (const path of archive.entries.keys()) {
|
||||
const m = /^ppt\/comments\/comment(\d+)\.xml$/.exec(path)
|
||||
if (m) maxNum = Math.max(maxNum, Number(m[1]))
|
||||
}
|
||||
partPath = `ppt/comments/comment${maxNum + 1}.xml`
|
||||
setEntry(archive, partPath, XMLDECL + `<p:cmLst xmlns:p="${NS_P}"></p:cmLst>`)
|
||||
addContentTypeOverride(archive, partPath, COMMENTS_CT)
|
||||
appendRelationship(archive, slide.path, COMMENTS_REL, `../${partPath.slice(4)}`)
|
||||
}
|
||||
const xml = archive.readText(partPath)
|
||||
if (!xml) return null
|
||||
|
||||
const dt = new Date().toISOString()
|
||||
// Positions staggered along the top-left diagonal so comment badges don't overlap
|
||||
const count = [...xml.matchAll(/<p:cm\b/g)].length
|
||||
const pos = 10 + (count % 8) * 6
|
||||
const cm =
|
||||
`<p:cm authorId="${authorId}" dt="${dt}" idx="${nextIdx}">` +
|
||||
`<p:pos x="${pos}" y="${pos}"/>` +
|
||||
`<p:text>${escapeXmlText(opts.text)}</p:text></p:cm>`
|
||||
setEntry(archive, partPath, xml.replace('</p:cmLst>', `${cm}</p:cmLst>`))
|
||||
|
||||
return { authorId, author: opts.author, initials, dt, idx: nextIdx, text: opts.text }
|
||||
}
|
||||
|
||||
/** Delete a comment (by authorId + idx). */
|
||||
export function deleteSlideComment(
|
||||
opened: OpenedPptx,
|
||||
slideIndex: number,
|
||||
ref: { authorId: number; idx: number },
|
||||
): boolean {
|
||||
const slide = opened.deck.slides[slideIndex]
|
||||
if (!slide) return false
|
||||
const { archive } = opened
|
||||
const partPath = commentsPathForSlide(archive, slide.path)
|
||||
if (!partPath) return false
|
||||
const xml = archive.readText(partPath)
|
||||
if (!xml) return false
|
||||
for (const m of xml.matchAll(/<p:cm\b([^>]*)>[\s\S]*?<\/p:cm>/g)) {
|
||||
const attrs = m[1]!
|
||||
if (
|
||||
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))
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
/**
|
||||
* <a:custGeom> custom geometry parsing (read-only rendering).
|
||||
*
|
||||
* fast-xml-parser does not preserve document order of mixed child nodes
|
||||
* (moveTo/lnTo/… order would be lost), so we scan tags in order directly over
|
||||
* the raw XML bytes.
|
||||
* Output is a normalized SVG path: coordinates 0..1, relative to each <a:path>'s
|
||||
* declared w/h; arcTo is converted to cubic beziers; gdLst/avLst formulas are
|
||||
* evaluated first so pt/arcTo can reference them.
|
||||
*/
|
||||
import type { CustomGeometry } from './types'
|
||||
|
||||
// Tag matcher tolerating '>' inside attribute values (same pattern as scan.ts)
|
||||
const TAG_RE = /<\/?(?:[^<>"']|"[^"]*"|'[^']*')*>/g
|
||||
const NAME_RE = /^<\/?\s*([A-Za-z_][\w:.-]*)/
|
||||
const ATTR_RE = /([\w:]+)\s*=\s*"([^"]*)"/g
|
||||
|
||||
function tagAttrs(tag: string): Record<string, string> {
|
||||
const out: Record<string, string> = {}
|
||||
ATTR_RE.lastIndex = 0
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = ATTR_RE.exec(tag))) out[m[1]!] = m[2]!
|
||||
return out
|
||||
}
|
||||
|
||||
const DEG = Math.PI / 180
|
||||
/** OOXML angle (1/60000 of a degree) → radians */
|
||||
const a2r = (v: number) => (v / 60000) * DEG
|
||||
|
||||
/**
|
||||
* gd formula evaluation (CT_GeomGuide fmla). Evaluated in order; may reference
|
||||
* earlier guides and built-in variables (w/h/ss/hc/vc/l/t/r/b/wdN/hdN/ssdN/cdN…,
|
||||
* angles in 1/60000 of a degree).
|
||||
*/
|
||||
export function evalGuides(
|
||||
gds: Array<{ name: string; fmla: string }>,
|
||||
w: number,
|
||||
h: number,
|
||||
): Record<string, number> {
|
||||
const ss = Math.min(w, h)
|
||||
const env: Record<string, number> = {
|
||||
w,
|
||||
h,
|
||||
ss,
|
||||
ls: Math.max(w, h),
|
||||
hc: w / 2,
|
||||
vc: h / 2,
|
||||
l: 0,
|
||||
t: 0,
|
||||
r: w,
|
||||
b: h,
|
||||
wd2: w / 2,
|
||||
wd3: w / 3,
|
||||
wd4: w / 4,
|
||||
wd5: w / 5,
|
||||
wd6: w / 6,
|
||||
wd8: w / 8,
|
||||
wd10: w / 10,
|
||||
wd12: w / 12,
|
||||
wd32: w / 32,
|
||||
hd2: h / 2,
|
||||
hd3: h / 3,
|
||||
hd4: h / 4,
|
||||
hd5: h / 5,
|
||||
hd6: h / 6,
|
||||
hd8: h / 8,
|
||||
hd10: h / 10,
|
||||
hd12: h / 12,
|
||||
ssd2: ss / 2,
|
||||
ssd4: ss / 4,
|
||||
ssd6: ss / 6,
|
||||
ssd8: ss / 8,
|
||||
ssd16: ss / 16,
|
||||
ssd32: ss / 32,
|
||||
cd2: 10800000,
|
||||
cd4: 5400000,
|
||||
cd8: 2700000,
|
||||
'3cd4': 16200000,
|
||||
'3cd8': 8100000,
|
||||
'5cd8': 13500000,
|
||||
'7cd8': 18900000,
|
||||
}
|
||||
const val = (tok: string | undefined): number => {
|
||||
if (tok == null) return 0
|
||||
const n = Number(tok)
|
||||
return Number.isFinite(n) ? n : (env[tok] ?? 0)
|
||||
}
|
||||
for (const gd of gds) {
|
||||
const parts = gd.fmla.trim().split(/\s+/)
|
||||
const op = parts[0]
|
||||
const x = val(parts[1])
|
||||
const y = val(parts[2])
|
||||
const z = val(parts[3])
|
||||
let out: number
|
||||
switch (op) {
|
||||
case 'val':
|
||||
out = x
|
||||
break
|
||||
case '*/':
|
||||
out = z === 0 ? 0 : (x * y) / z
|
||||
break
|
||||
case '+-':
|
||||
out = x + y - z
|
||||
break
|
||||
case '+/':
|
||||
out = z === 0 ? 0 : (x + y) / z
|
||||
break
|
||||
case '?:':
|
||||
out = x > 0 ? y : z
|
||||
break
|
||||
case 'abs':
|
||||
out = Math.abs(x)
|
||||
break
|
||||
case 'min':
|
||||
out = Math.min(x, y)
|
||||
break
|
||||
case 'max':
|
||||
out = Math.max(x, y)
|
||||
break
|
||||
case 'pin':
|
||||
out = Math.min(Math.max(y, x), z)
|
||||
break
|
||||
case 'mod':
|
||||
out = Math.sqrt(x * x + y * y + z * z)
|
||||
break
|
||||
case 'sqrt':
|
||||
out = Math.sqrt(Math.max(x, 0))
|
||||
break
|
||||
case 'at2':
|
||||
out = (Math.atan2(y, x) / DEG) * 60000
|
||||
break
|
||||
case 'cat2':
|
||||
out = x * Math.cos(Math.atan2(z, y))
|
||||
break
|
||||
case 'sat2':
|
||||
out = x * Math.sin(Math.atan2(z, y))
|
||||
break
|
||||
case 'cos':
|
||||
out = x * Math.cos(a2r(y))
|
||||
break
|
||||
case 'sin':
|
||||
out = x * Math.sin(a2r(y))
|
||||
break
|
||||
case 'tan':
|
||||
out = x * Math.tan(a2r(y))
|
||||
break
|
||||
default:
|
||||
out = 0
|
||||
}
|
||||
env[gd.name] = out
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
interface RawCmd {
|
||||
c: 'M' | 'L' | 'Q' | 'C' | 'Z' | 'A'
|
||||
/** pt coordinate tokens for M/L/Q/C (numbers or guide names) */
|
||||
pts?: Array<[string, string]>
|
||||
/** arcTo attribute tokens */
|
||||
arc?: { wR: string; hR: string; stAng: string; swAng: string }
|
||||
}
|
||||
|
||||
interface RawPath {
|
||||
w?: number
|
||||
h?: number
|
||||
fill?: string
|
||||
stroke?: string
|
||||
cmds: RawCmd[]
|
||||
}
|
||||
|
||||
const CMD_PT_COUNT: Record<string, number> = {
|
||||
'a:moveTo': 1,
|
||||
'a:lnTo': 1,
|
||||
'a:quadBezTo': 2,
|
||||
'a:cubicBezTo': 3,
|
||||
}
|
||||
const CMD_LETTER: Record<string, RawCmd['c']> = {
|
||||
'a:moveTo': 'M',
|
||||
'a:lnTo': 'L',
|
||||
'a:quadBezTo': 'Q',
|
||||
'a:cubicBezTo': 'C',
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract and parse <a:custGeom> from a shape's raw XML.
|
||||
* shapeW/shapeH: element box in EMU (basis for guide evaluation; fallback space
|
||||
* when a path declares no w/h).
|
||||
*/
|
||||
export function parseCustGeom(
|
||||
shapeXml: string,
|
||||
shapeW: number,
|
||||
shapeH: number,
|
||||
): CustomGeometry | undefined {
|
||||
const start = shapeXml.indexOf('<a:custGeom')
|
||||
if (start < 0) return undefined
|
||||
const end = shapeXml.indexOf('</a:custGeom>', start)
|
||||
if (end < 0) return undefined
|
||||
const xml = shapeXml.slice(start, end)
|
||||
|
||||
const gds: Array<{ name: string; fmla: string }> = []
|
||||
const paths: RawPath[] = []
|
||||
let inGuides = false
|
||||
let cur: RawPath | null = null
|
||||
let pending: { c: RawCmd['c']; need: number; pts: Array<[string, string]> } | null = null
|
||||
|
||||
TAG_RE.lastIndex = 0
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = TAG_RE.exec(xml))) {
|
||||
const tag = m[0]
|
||||
if (tag.startsWith('<!--') || tag.startsWith('<![') || tag.startsWith('<?')) continue
|
||||
const closing = tag.startsWith('</')
|
||||
const name = NAME_RE.exec(tag)?.[1] ?? ''
|
||||
if (closing) {
|
||||
if (name === 'a:avLst' || name === 'a:gdLst') inGuides = false
|
||||
else if (name === 'a:path' && cur) {
|
||||
paths.push(cur)
|
||||
cur = null
|
||||
pending = null
|
||||
}
|
||||
continue
|
||||
}
|
||||
const self = tag.endsWith('/>')
|
||||
switch (name) {
|
||||
case 'a:avLst':
|
||||
case 'a:gdLst':
|
||||
if (!self) inGuides = true
|
||||
break
|
||||
case 'a:gd': {
|
||||
if (!inGuides) break // gd elsewhere (e.g. cxnLst) does not participate
|
||||
const a = tagAttrs(tag)
|
||||
if (a.name && a.fmla) gds.push({ name: a.name, fmla: a.fmla })
|
||||
break
|
||||
}
|
||||
case 'a:path': {
|
||||
const a = tagAttrs(tag)
|
||||
cur = {
|
||||
w: a.w ? Number(a.w) || 0 : undefined,
|
||||
h: a.h ? Number(a.h) || 0 : undefined,
|
||||
fill: a.fill,
|
||||
stroke: a.stroke,
|
||||
cmds: [],
|
||||
}
|
||||
if (self) {
|
||||
paths.push(cur)
|
||||
cur = null
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'a:moveTo':
|
||||
case 'a:lnTo':
|
||||
case 'a:quadBezTo':
|
||||
case 'a:cubicBezTo':
|
||||
if (cur) pending = { c: CMD_LETTER[name]!, need: CMD_PT_COUNT[name]!, pts: [] }
|
||||
break
|
||||
case 'a:pt': {
|
||||
if (!cur || !pending) break
|
||||
const a = tagAttrs(tag)
|
||||
pending.pts.push([a.x ?? '0', a.y ?? '0'])
|
||||
if (pending.pts.length >= pending.need) {
|
||||
cur.cmds.push({ c: pending.c, pts: pending.pts })
|
||||
pending = null
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'a:arcTo': {
|
||||
if (!cur) break
|
||||
const a = tagAttrs(tag)
|
||||
cur.cmds.push({
|
||||
c: 'A',
|
||||
arc: { wR: a.wR ?? '0', hR: a.hR ?? '0', stAng: a.stAng ?? '0', swAng: a.swAng ?? '0' },
|
||||
})
|
||||
break
|
||||
}
|
||||
case 'a:close':
|
||||
if (cur) cur.cmds.push({ c: 'Z' })
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const env = evalGuides(gds, shapeW, shapeH)
|
||||
const resolve = (tok: string): number => {
|
||||
const n = Number(tok)
|
||||
return Number.isFinite(n) ? n : (env[tok] ?? 0)
|
||||
}
|
||||
|
||||
const absList = paths.map((p) => toAbsCmds(p, resolve))
|
||||
// Fallback normalization space when a path declares no w/h and the element box is 0:
|
||||
// shared across paths (they live in one guide coordinate space; per-path maxima would skew relative scale)
|
||||
let fw = 0
|
||||
let fh = 0
|
||||
paths.forEach((p, i) => {
|
||||
if (!p.w) fw = Math.max(fw, maxCoord(absList[i]!, 0))
|
||||
if (!p.h) fh = Math.max(fh, maxCoord(absList[i]!, 1))
|
||||
})
|
||||
|
||||
// Each path normalized independently (its w/h maps to the full element box), emitted
|
||||
// in document order; the three output layers keep that order internally (cross-layer
|
||||
// paint order is bounded by the render contract's fixed path/fillPath/strokePath sequence)
|
||||
const buckets = { path: [] as string[], fillPath: [] as string[], strokePath: [] as string[] }
|
||||
paths.forEach((p, i) => {
|
||||
const abs = absList[i]!
|
||||
if (!abs.length) return
|
||||
const vw = p.w || shapeW || fw || 1
|
||||
const vh = p.h || shapeH || fh || 1
|
||||
const d = emitNorm(abs, vw, vh)
|
||||
if (!d) return
|
||||
const fillNone = p.fill === 'none'
|
||||
const strokeNone = p.stroke === '0' || p.stroke === 'false' || p.stroke === 'none'
|
||||
if (fillNone && strokeNone) return
|
||||
if (fillNone) buckets.strokePath.push(d)
|
||||
else if (strokeNone) buckets.fillPath.push(d)
|
||||
else buckets.path.push(d)
|
||||
})
|
||||
|
||||
const out: CustomGeometry = {}
|
||||
if (buckets.path.length) out.path = buckets.path.join(' ')
|
||||
if (buckets.fillPath.length) out.fillPath = buckets.fillPath.join(' ')
|
||||
if (buckets.strokePath.length) out.strokePath = buckets.strokePath.join(' ')
|
||||
return out.path || out.fillPath || out.strokePath ? out : undefined
|
||||
}
|
||||
|
||||
interface AbsCmd {
|
||||
c: 'M' | 'L' | 'Q' | 'C' | 'Z'
|
||||
xy: number[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Ray angle → ellipse parametric angle, staying in the same revolution.
|
||||
* OOXML arcTo angles point at the ellipse from the center; the parametric form
|
||||
* (wR·cos t, hR·sin t) only matches when wR == hR.
|
||||
*/
|
||||
function paramAngle(a: number, wR: number, hR: number): number {
|
||||
if (wR === hR || !wR || !hR) return a
|
||||
const t = Math.atan2(Math.sin(a) * wR, Math.cos(a) * hR)
|
||||
return t + 2 * Math.PI * Math.round((a - t) / (2 * Math.PI))
|
||||
}
|
||||
|
||||
/** Commands → absolute coordinates (path space); arcTo converted to cubics in place. */
|
||||
function toAbsCmds(p: RawPath, resolve: (tok: string) => number): AbsCmd[] {
|
||||
const out: AbsCmd[] = []
|
||||
let cx = 0
|
||||
let cy = 0
|
||||
let sx = 0
|
||||
let sy = 0
|
||||
for (const cmd of p.cmds) {
|
||||
if (cmd.c === 'Z') {
|
||||
out.push({ c: 'Z', xy: [] })
|
||||
// close returns the pen to the subpath start; a following arcTo derives its center from here
|
||||
cx = sx
|
||||
cy = sy
|
||||
continue
|
||||
}
|
||||
if (cmd.c === 'A') {
|
||||
const wR = resolve(cmd.arc!.wR)
|
||||
const hR = resolve(cmd.arc!.hR)
|
||||
const stRay = a2r(resolve(cmd.arc!.stAng))
|
||||
const swRay = a2r(resolve(cmd.arc!.swAng))
|
||||
if (swRay === 0) continue
|
||||
const st = paramAngle(stRay, wR, hR)
|
||||
// Endpoint-converted sweep, restored to swRay's revolution count (each endpoint shifts < π/2)
|
||||
let sw = paramAngle(stRay + swRay, wR, hR) - st
|
||||
sw += 2 * Math.PI * Math.round((swRay - sw) / (2 * Math.PI))
|
||||
// Treat current point as at stAng on the ellipse and derive the center
|
||||
const ecx = cx - wR * Math.cos(st)
|
||||
const ecy = cy - hR * Math.sin(st)
|
||||
const segs = Math.max(1, Math.ceil(Math.abs(sw) / (Math.PI / 2)))
|
||||
const da = sw / segs
|
||||
const k = (4 / 3) * Math.tan(da / 4)
|
||||
for (let i = 0; i < segs; i++) {
|
||||
const a1 = st + i * da
|
||||
const a2 = a1 + da
|
||||
const x1 = ecx + wR * Math.cos(a1)
|
||||
const y1 = ecy + hR * Math.sin(a1)
|
||||
const x2 = ecx + wR * Math.cos(a2)
|
||||
const y2 = ecy + hR * Math.sin(a2)
|
||||
out.push({
|
||||
c: 'C',
|
||||
xy: [
|
||||
x1 - k * wR * Math.sin(a1),
|
||||
y1 + k * hR * Math.cos(a1),
|
||||
x2 + k * wR * Math.sin(a2),
|
||||
y2 - k * hR * Math.cos(a2),
|
||||
x2,
|
||||
y2,
|
||||
],
|
||||
})
|
||||
cx = x2
|
||||
cy = y2
|
||||
}
|
||||
continue
|
||||
}
|
||||
const xy: number[] = []
|
||||
for (const [xs, ys] of cmd.pts!) {
|
||||
xy.push(resolve(xs), resolve(ys))
|
||||
}
|
||||
out.push({ c: cmd.c, xy })
|
||||
if (cmd.c === 'M') {
|
||||
sx = xy[0]!
|
||||
sy = xy[1]!
|
||||
}
|
||||
cx = xy[xy.length - 2]!
|
||||
cy = xy[xy.length - 1]!
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function maxCoord(cmds: AbsCmd[], axis: 0 | 1): number {
|
||||
let mx = 0
|
||||
for (const c of cmds) for (let i = axis; i < c.xy.length; i += 2) mx = Math.max(mx, c.xy[i]!)
|
||||
return mx
|
||||
}
|
||||
|
||||
function emitNorm(cmds: AbsCmd[], vw: number, vh: number): string {
|
||||
const r5 = (v: number) => Math.round(v * 100000) / 100000
|
||||
const parts: string[] = []
|
||||
for (const c of cmds) {
|
||||
parts.push(c.c)
|
||||
for (let i = 0; i < c.xy.length; i += 2) {
|
||||
parts.push(String(r5(c.xy[i]! / vw)), String(r5(c.xy[i + 1]! / vh)))
|
||||
}
|
||||
}
|
||||
return parts.length ? parts.join(' ') : ''
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Format Painter — pure functions with no side effects, easy to unit test.
|
||||
*
|
||||
* Format scope:
|
||||
* - Shapes/text boxes: the modelable part of spPr (fill / stroke / presetGeometry / adjust)
|
||||
* - Text: default run format (fontFamily/fontSize/bold/italic/underline/color of the
|
||||
* first run of the first paragraph) + paragraph alignment (first paragraph's align)
|
||||
* - Cross-type: text→shape applies only the spPr part; shape→text applies only the text part
|
||||
*
|
||||
* Uses the existing editFill / editStroke / editText IPC channels; the caller takes the
|
||||
* CopiedFormat to the target element and calls each patch function field by field.
|
||||
*/
|
||||
|
||||
import type { Fill, Stroke, TextElement } from './types'
|
||||
|
||||
// ── Format containers ────────────────────────────────────────────────────
|
||||
|
||||
/** Copied shape appearance format (spPr layer) */
|
||||
export interface ShapeFormat {
|
||||
fill?: Fill
|
||||
stroke?: Stroke
|
||||
/** Corner-radius adjustments for preset geometry such as roundRect */
|
||||
adjust?: Record<string, number>
|
||||
}
|
||||
|
||||
/** Copied default text run format (first run of the first paragraph) */
|
||||
export interface TextRunFormat {
|
||||
fontFamily?: string
|
||||
fontSize?: number
|
||||
bold?: boolean
|
||||
italic?: boolean
|
||||
underline?: boolean
|
||||
color?: string
|
||||
}
|
||||
|
||||
/** Copied paragraph format (first paragraph) */
|
||||
export interface ParagraphFormat {
|
||||
align?: 'left' | 'center' | 'right' | 'justify'
|
||||
}
|
||||
|
||||
/** Full container of formats copied by the format painter */
|
||||
export interface CopiedFormat {
|
||||
/** Source element type */
|
||||
sourceType: 'text' | 'shape' | 'picture'
|
||||
shape?: ShapeFormat
|
||||
run?: TextRunFormat
|
||||
paragraph?: ParagraphFormat
|
||||
}
|
||||
|
||||
// ── Extraction (source element → CopiedFormat) ─────────────────────────
|
||||
|
||||
/**
|
||||
* Extract format from a TextElement (type='text'|'shape').
|
||||
* Only extracts the "write-back-able" parts; ignores passthrough/group/picture.
|
||||
*/
|
||||
export function extractFormat(el: TextElement): CopiedFormat {
|
||||
const shape: ShapeFormat = {}
|
||||
if (el.fill) shape.fill = el.fill
|
||||
if (el.stroke) shape.stroke = el.stroke
|
||||
if (el.adjust && Object.keys(el.adjust).length > 0) shape.adjust = el.adjust
|
||||
|
||||
const run: TextRunFormat = {}
|
||||
const para: ParagraphFormat = {}
|
||||
|
||||
const firstPara = el.text?.paragraphs?.[0]
|
||||
if (firstPara) {
|
||||
if (firstPara.align) para.align = firstPara.align
|
||||
const firstRun = firstPara.runs?.[0]
|
||||
if (firstRun) {
|
||||
if (firstRun.fontFamily != null) run.fontFamily = firstRun.fontFamily
|
||||
if (firstRun.fontSize != null) run.fontSize = firstRun.fontSize
|
||||
if (firstRun.bold != null) run.bold = firstRun.bold
|
||||
if (firstRun.italic != null) run.italic = firstRun.italic
|
||||
if (firstRun.underline != null) run.underline = firstRun.underline
|
||||
if (firstRun.color != null) run.color = firstRun.color
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sourceType: el.type as 'text' | 'shape',
|
||||
shape: Object.keys(shape).length > 0 ? shape : undefined,
|
||||
run: Object.keys(run).length > 0 ? run : undefined,
|
||||
paragraph: Object.keys(para).length > 0 ? para : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Application (CopiedFormat → target element delta) ──────────────────
|
||||
|
||||
export interface FormatPatchResult {
|
||||
/** Fill change (undefined = no change) */
|
||||
fill?: Fill
|
||||
/** Stroke change (undefined = no change; null = remove stroke) */
|
||||
stroke?: Fill extends Fill ? Stroke | null : Stroke | null
|
||||
/** Text run change (undefined = no change) */
|
||||
runFormat?: TextRunFormat
|
||||
/** Paragraph alignment change (undefined = no change) */
|
||||
align?: 'left' | 'center' | 'right' | 'justify'
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a CopiedFormat to the target element and compute the delta to modify.
|
||||
* Cross-type application takes the intersection:
|
||||
* - target is picture: apply stroke only (no fill/text)
|
||||
* - target is shape: apply spPr + text run + alignment
|
||||
* - target is text: apply spPr + text run + alignment
|
||||
*/
|
||||
export function applyFormat(
|
||||
fmt: CopiedFormat,
|
||||
targetType: 'text' | 'shape' | 'picture',
|
||||
): FormatPatchResult {
|
||||
const result: FormatPatchResult = {}
|
||||
|
||||
if (targetType === 'picture') {
|
||||
// Picture: apply stroke only
|
||||
if (fmt.shape?.stroke !== undefined) result.stroke = fmt.shape.stroke
|
||||
return result
|
||||
}
|
||||
|
||||
// shape / text: apply everything
|
||||
if (fmt.shape?.fill !== undefined) result.fill = fmt.shape.fill
|
||||
if (fmt.shape?.stroke !== undefined) result.stroke = fmt.shape.stroke
|
||||
if (fmt.run && Object.keys(fmt.run).length > 0) result.runFormat = fmt.run
|
||||
if (fmt.paragraph?.align) result.align = fmt.paragraph.align
|
||||
|
||||
return result
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* Header/footer — "Apply to All" writes dt / ftr / sldNum placeholder
|
||||
* entities into each slide, one slide at a time.
|
||||
*
|
||||
* Simplification: placeholders carry an explicit xfrm (bottom left/center/right
|
||||
* segments) instead of relying on same-idx placeholder inheritance from the layout,
|
||||
* so they are visible with stable positions under any template.
|
||||
*/
|
||||
import type { Paragraph, Slide, TextElement } from './types'
|
||||
import { generateParagraphXml } from './generate'
|
||||
import { materializeSlide, type OpenedPptx } from './index'
|
||||
import { nextCNvPrId } from './insert'
|
||||
|
||||
export interface HeaderFooterOptions {
|
||||
/** Footer text; null/undefined/'' = no footer */
|
||||
footer?: string | null
|
||||
/** Whether to show the slide number */
|
||||
slideNum?: boolean
|
||||
/** Date text (fixed text); null/'' = hidden. When auto=true, writes a dynamic datetime field */
|
||||
date?: string | null
|
||||
/** Use a dynamic date field (auto-updates when opened in PowerPoint) */
|
||||
dateAuto?: boolean
|
||||
}
|
||||
|
||||
const HF_TYPES = new Set(['ftr', 'sldNum', 'dt'])
|
||||
|
||||
function hfSpXml(
|
||||
slide: Slide,
|
||||
type: 'dt' | 'ftr' | 'sldNum',
|
||||
idx: number,
|
||||
box: { x: number; y: number; cx: number; cy: number },
|
||||
para: Paragraph,
|
||||
): string {
|
||||
const id = nextCNvPrId(slide)
|
||||
const nameMap = {
|
||||
dt: 'Date Placeholder',
|
||||
ftr: 'Footer Placeholder',
|
||||
sldNum: 'Slide Number Placeholder',
|
||||
}
|
||||
return (
|
||||
`<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="${nameMap[type]} ${id}"/>` +
|
||||
'<p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr>' +
|
||||
`<p:nvPr><p:ph type="${type}" sz="${type === 'dt' ? 'half' : 'quarter'}" idx="${idx}"/></p:nvPr></p:nvSpPr>` +
|
||||
`<p:spPr><a:xfrm><a:off x="${box.x}" y="${box.y}"/><a:ext cx="${box.cx}" cy="${box.cy}"/></a:xfrm>` +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr>' +
|
||||
'<p:txBody><a:bodyPr vert="horz" lIns="0" tIns="0" rIns="0" bIns="0" rtlCol="0" anchor="ctr"/><a:lstStyle/>' +
|
||||
generateParagraphXml(para) +
|
||||
'</p:txBody></p:sp>'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply header/footer to the given slides (all slides by default).
|
||||
* Removes existing dt/ftr/sldNum placeholder elements first, then appends new
|
||||
* ones per the toggles. Returns whether any slide was modified.
|
||||
*/
|
||||
export function applyHeaderFooter(
|
||||
opened: OpenedPptx,
|
||||
opts: HeaderFooterOptions,
|
||||
slideIndexes?: number[],
|
||||
): boolean {
|
||||
const { deck } = opened
|
||||
const targets = slideIndexes ?? deck.slides.map((_, i) => i)
|
||||
const { cx, cy } = deck.size
|
||||
const barH = Math.round(cy * 0.045)
|
||||
const barY = Math.round(cy * 0.93)
|
||||
const style = { fontSize: 12, color: '898989' }
|
||||
let changed = false
|
||||
|
||||
for (const i of targets) {
|
||||
const slide = deck.slides[i]
|
||||
if (!slide) continue
|
||||
|
||||
// 1) Remove existing footer-family placeholders
|
||||
const before = slide.elements.length
|
||||
slide.elements = slide.elements.filter(
|
||||
(el) => !(el.placeholder && HF_TYPES.has(el.placeholder)),
|
||||
)
|
||||
let dirty = slide.elements.length !== before
|
||||
|
||||
// 2) Append enabled placeholders (order: dt left → ftr center → sldNum right)
|
||||
const pushSp = (xml: string) => {
|
||||
const el: TextElement = {
|
||||
// materialize reparses the whole slide, so these temporary model fields suffice
|
||||
id: `hfnew_${slide.elements.length}_${Date.now().toString(36)}`,
|
||||
type: 'text',
|
||||
anchor: { spIndex: slide.elements.length, originalXml: xml, range: [0, 0] },
|
||||
transform: { offset: { x: 0, y: 0, cx: 0, cy: 0 }, rot: 0, flipH: false, flipV: false },
|
||||
}
|
||||
slide.elements.push(el)
|
||||
dirty = true
|
||||
}
|
||||
|
||||
if (opts.date) {
|
||||
pushSp(
|
||||
hfSpXml(
|
||||
slide,
|
||||
'dt',
|
||||
10,
|
||||
{ x: Math.round(cx * 0.05), y: barY, cx: Math.round(cx * 0.22), cy: barH },
|
||||
{
|
||||
align: 'left',
|
||||
runs: [
|
||||
opts.dateAuto
|
||||
? { text: opts.date, field: 'datetime1', ...style }
|
||||
: { text: opts.date, ...style },
|
||||
],
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
if (opts.footer) {
|
||||
pushSp(
|
||||
hfSpXml(
|
||||
slide,
|
||||
'ftr',
|
||||
11,
|
||||
{ x: Math.round(cx * 0.3), y: barY, cx: Math.round(cx * 0.4), cy: barH },
|
||||
{
|
||||
align: 'center',
|
||||
runs: [{ text: opts.footer, ...style }],
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
if (opts.slideNum) {
|
||||
pushSp(
|
||||
hfSpXml(
|
||||
slide,
|
||||
'sldNum',
|
||||
12,
|
||||
{ x: Math.round(cx * 0.86), y: barY, cx: Math.round(cx * 0.09), cy: barH },
|
||||
{
|
||||
align: 'right',
|
||||
runs: [{ text: String(i + 1), field: 'slidenum', ...style }],
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
if (dirty) {
|
||||
slide.structureDirty = true
|
||||
materializeSlide(opened, i)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
/** Read a slide's current footer state (for dialog echo-back). */
|
||||
export function readHeaderFooter(slide: Slide): {
|
||||
footer: string | null
|
||||
slideNum: boolean
|
||||
date: string | null
|
||||
} {
|
||||
let footer: string | null = null
|
||||
let date: string | null = null
|
||||
let slideNum = false
|
||||
for (const el of slide.elements) {
|
||||
if (el.type !== 'text' && el.type !== 'shape') continue
|
||||
const text = (el as TextElement).text?.paragraphs
|
||||
.map((p) => p.runs.map((r) => r.text).join(''))
|
||||
.join('\n')
|
||||
.trim()
|
||||
if (el.placeholder === 'ftr') footer = text || null
|
||||
else if (el.placeholder === 'dt') date = text || null
|
||||
else if (el.placeholder === 'sldNum') slideNum = true
|
||||
}
|
||||
return { footer, slideNum, date }
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
/**
|
||||
* Element-level hyperlinks — <a:hlinkClick> under <p:cNvPr>.
|
||||
*
|
||||
* Two kinds of targets:
|
||||
* - External URL: a hyperlink relationship with TargetMode="External" in the slide rels;
|
||||
* - In-document slide jump: hlinkClick with action="ppaction://hlinksldjump",
|
||||
* whose relationship (type=slide) points at the target slideN.xml.
|
||||
*
|
||||
* Implemented via "XML surgery + materialize": edit the cNvPr in the element's
|
||||
* current fragment, then reparse the whole slide (same path as appendRawElements).
|
||||
*/
|
||||
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'
|
||||
|
||||
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 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 }
|
||||
|
||||
const EMPTY_RELS =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>'
|
||||
|
||||
/** Append a relationship to the slide rels and return the new rId. */
|
||||
function appendRel(
|
||||
opened: OpenedPptx,
|
||||
slide: Slide,
|
||||
type: string,
|
||||
target: string,
|
||||
external: boolean,
|
||||
): string {
|
||||
const { archive } = opened
|
||||
const relsPath = relsPathFor(slide.path)
|
||||
const rels = archive.readText(relsPath) ?? EMPTY_RELS
|
||||
let maxRid = 0
|
||||
for (const m of rels.matchAll(/Id="rId(\d+)"/g)) maxRid = Math.max(maxRid, Number(m[1]))
|
||||
const rid = `rId${maxRid + 1}`
|
||||
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'))
|
||||
return rid
|
||||
}
|
||||
|
||||
/** Strip the hlinkClick inside the element XML's first cNvPr (keeping other children). */
|
||||
function stripHlink(xml: string): string {
|
||||
return xml.replace(/<a:hlinkClick\b[^>]*\/>|<a:hlinkClick\b[^>]*>[\s\S]*?<\/a:hlinkClick>/, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function setElementLink(
|
||||
opened: OpenedPptx,
|
||||
slideIndex: number,
|
||||
elementId: string,
|
||||
target: LinkTarget | null,
|
||||
): Slide | null {
|
||||
const slide = opened.deck.slides[slideIndex]
|
||||
if (!slide) return null
|
||||
const el = slide.elements.find((e) => e.id === elementId)
|
||||
if (!el) return null
|
||||
|
||||
let xml = stripHlink(patchedElementXml(el))
|
||||
|
||||
if (target) {
|
||||
let hlink: string
|
||||
if (target.kind === 'url') {
|
||||
const rid = appendRel(opened, slide, HYPERLINK_REL_TYPE, target.url, true)
|
||||
hlink = `<a:hlinkClick xmlns:r="${R_NS}" r:id="${rid}"/>`
|
||||
} else {
|
||||
const dst = opened.deck.slides[target.slideIndex]
|
||||
if (!dst) return null
|
||||
// Same directory ppt/slides/, so Target is just the file name
|
||||
const fileName = dst.path.split('/').pop()!
|
||||
const rid = appendRel(opened, slide, SLIDE_REL_TYPE, fileName, false)
|
||||
hlink = `<a:hlinkClick xmlns:r="${R_NS}" r:id="${rid}" action="${SLDJUMP_ACTION}"/>`
|
||||
}
|
||||
// Insert into the first cNvPr (hlinkClick is cNvPr's first valid child)
|
||||
const cNvPr = /<p:cNvPr\b((?:"[^"]*"|'[^']*'|[^"'>])*?)(\/?)>/.exec(xml)
|
||||
if (!cNvPr) return null
|
||||
if (cNvPr[2] === '/') {
|
||||
// Self-closing → expand into a tag pair
|
||||
xml =
|
||||
xml.slice(0, cNvPr.index) +
|
||||
`<p:cNvPr${cNvPr[1]}>${hlink}</p:cNvPr>` +
|
||||
xml.slice(cNvPr.index + cNvPr[0].length)
|
||||
} else {
|
||||
const at = cNvPr.index + cNvPr[0].length
|
||||
xml = xml.slice(0, at) + hlink + xml.slice(at)
|
||||
}
|
||||
}
|
||||
|
||||
el.anchor = { ...el.anchor, originalXml: xml }
|
||||
// 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
|
||||
return materializeSlide(opened, slideIndex)
|
||||
}
|
||||
|
||||
/** Parse a TextRun.hyperlink encoded target ("slide:N" or url); null on bad input. */
|
||||
export function decodeRunLink(s: string): LinkTarget | null {
|
||||
const m = /^slide:(\d+)$/.exec(s)
|
||||
if (m) return { kind: 'slide', slideIndex: Number(m[1]) }
|
||||
return s ? { kind: 'url', url: s } : null
|
||||
}
|
||||
|
||||
/** TextRun.hyperlink encoding of a link target. */
|
||||
export function encodeRunLink(target: LinkTarget): string {
|
||||
return target.kind === 'slide' ? `slide:${target.slideIndex}` : target.url
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function ensureRunLinkRels(
|
||||
opened: OpenedPptx,
|
||||
slideIndex: number,
|
||||
paragraphs: Array<{ runs: Array<{ hyperlink?: string; hyperlinkRId?: string; hyperlinkAction?: string }> }>,
|
||||
): boolean {
|
||||
const slide = opened.deck.slides[slideIndex]
|
||||
if (!slide) return false
|
||||
let changed = false
|
||||
for (const p of paragraphs) {
|
||||
for (const run of p.runs) {
|
||||
if (!run.hyperlink || run.hyperlinkRId) continue
|
||||
const target = decodeRunLink(run.hyperlink)
|
||||
if (!target) continue
|
||||
if (target.kind === 'url') {
|
||||
run.hyperlinkRId = appendRel(opened, slide, HYPERLINK_REL_TYPE, target.url, true)
|
||||
delete run.hyperlinkAction
|
||||
} 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.hyperlinkAction = SLDJUMP_ACTION
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
/**
|
||||
* All run-level hyperlinks on a slide, resolved live against the rels (parse-time
|
||||
* TextRun.hyperlink can go stale after slide reorders). Keyed by element + paragraph +
|
||||
* run indexes; the slideshow matches these against layout glyph runs to hit-test clicks.
|
||||
*/
|
||||
export function getRunLinks(
|
||||
opened: OpenedPptx,
|
||||
slideIndex: number,
|
||||
): 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 rels = opened.archive.readRels(slide.path)
|
||||
const resolve = (rid: string): LinkTarget | null => {
|
||||
const rel = rels.get(rid)
|
||||
if (!rel) return null
|
||||
if (rel.type === HYPERLINK_REL_TYPE) return { kind: 'url', url: rel.target }
|
||||
if (rel.type === SLIDE_REL_TYPE) {
|
||||
const abs = resolveTarget(slide.path, rel.target)
|
||||
const idx = opened.deck.slides.findIndex((s) => s.path === abs)
|
||||
if (idx >= 0) return { kind: 'slide', slideIndex: idx }
|
||||
}
|
||||
return null
|
||||
}
|
||||
const walk = (elements: Slide['elements']) => {
|
||||
for (const el of elements) {
|
||||
if (el.type === 'group') {
|
||||
walk((el as GroupElement).children)
|
||||
continue
|
||||
}
|
||||
if ((el.type !== 'text' && el.type !== 'shape') || !('text' in el) || !el.text) continue
|
||||
el.text.paragraphs.forEach((p, paraIndex) => {
|
||||
p.runs.forEach((run, runIndex) => {
|
||||
if (!run.hyperlinkRId) return
|
||||
const target = resolve(run.hyperlinkRId)
|
||||
if (target) out.push({ elementId: el.id, paraIndex, runIndex, target })
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
walk(slide.elements)
|
||||
return out
|
||||
}
|
||||
|
||||
/** Resolve the hlinkClick rId in an element fragment against the slide rels; null if none/unresolvable. */
|
||||
function resolveLinkInXml(opened: OpenedPptx, slide: Slide, xml: string): LinkTarget | null {
|
||||
const m = /<a:hlinkClick\b[^>]*\br:id="(rId\d+)"/.exec(xml)
|
||||
if (!m) return null
|
||||
const rel = opened.archive.readRels(slide.path).get(m[1]!)
|
||||
if (!rel) return null
|
||||
if (rel.type === HYPERLINK_REL_TYPE) return { kind: 'url', url: rel.target }
|
||||
if (rel.type === SLIDE_REL_TYPE) {
|
||||
const abs = resolveTarget(slide.path, rel.target)
|
||||
const idx = opened.deck.slides.findIndex((s) => s.path === abs)
|
||||
if (idx >= 0) return { kind: 'slide', slideIndex: idx }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Read an element's current hyperlink (for UI echo-back); returns null if none. */
|
||||
export function getElementLink(
|
||||
opened: OpenedPptx,
|
||||
slideIndex: number,
|
||||
elementId: string,
|
||||
): LinkTarget | null {
|
||||
const slide = opened.deck.slides[slideIndex]
|
||||
const el = slide?.elements.find((e) => e.id === elementId)
|
||||
if (!slide || !el) return null
|
||||
return resolveLinkInXml(opened, slide, el.anchor.originalXml)
|
||||
}
|
||||
|
||||
/**
|
||||
* All element hyperlinks on a slide (groups scanned recursively) — the slideshow
|
||||
* uses this to hit-test clicks and follow slide jumps (Zoom) / external URLs.
|
||||
* Group children have empty anchors (their bytes live only inside the group's
|
||||
* fragment), so each child's XML is sliced out of the group XML by index.
|
||||
*/
|
||||
export function getSlideLinks(
|
||||
opened: OpenedPptx,
|
||||
slideIndex: number,
|
||||
): Array<{ elementId: string; target: LinkTarget }> {
|
||||
const slide = opened.deck.slides[slideIndex]
|
||||
if (!slide) return []
|
||||
const out: Array<{ elementId: string; target: LinkTarget }> = []
|
||||
const walk = (elements: Slide['elements'], xmlOf: (i: number) => string) => {
|
||||
for (let i = 0; i < elements.length; i++) {
|
||||
const el = elements[i]!
|
||||
const xml = xmlOf(i)
|
||||
if (el.type === 'group') {
|
||||
// Restrict the group's own match to its nvGrpSpPr header so a child link
|
||||
// doesn't make the whole group clickable
|
||||
const own = /<p:nvGrpSpPr>[\s\S]*?<\/p:nvGrpSpPr>/.exec(xml)?.[0] ?? ''
|
||||
const target = resolveLinkInXml(opened, slide, own)
|
||||
if (target) out.push({ elementId: el.id, target })
|
||||
// Child fragments are in document order, matching (grp as GroupElement).children
|
||||
const childXmls = sliceGroupChildXmls(xml)
|
||||
walk((el as GroupElement).children, (j) => childXmls[j] ?? '')
|
||||
continue
|
||||
}
|
||||
const target = resolveLinkInXml(opened, slide, xml)
|
||||
if (target) out.push({ elementId: el.id, target })
|
||||
}
|
||||
}
|
||||
walk(slide.elements, (i) => slide.elements[i]!.anchor.originalXml)
|
||||
return out
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,386 @@
|
||||
/**
|
||||
* Element insertion — synthesizes a raw <p:sp> fragment and hangs it on
|
||||
* slide.elements.
|
||||
*
|
||||
* Naturally compatible with patch-based saving: a new element's
|
||||
* anchor.originalXml is the generated XML, which patchSlideXml includes when
|
||||
* splicing elements together; deletion is removal from the array.
|
||||
* Both change the spTree structure, driving a full-slide rebuild via
|
||||
* slide.structureDirty.
|
||||
*/
|
||||
import type { EmuRect, Paragraph, PictureElement, Slide, SlideElement, TextElement } from './types'
|
||||
import { generateParagraphXml, generateXfrmXml } from './generate'
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
import { relsPathFor } from './zip'
|
||||
import type { OpenedPptx } from './index'
|
||||
|
||||
/**
|
||||
* 'textbox' is a special value (plain text box without prstGeom); anything else is
|
||||
* an OOXML preset geometry name (rect/roundRect/ellipse/triangle/star5/rightArrow/
|
||||
* chevron…). Presets whose polygon approximation the render layer hasn't
|
||||
* implemented fall back to a rectangle; always correct in PowerPoint.
|
||||
*/
|
||||
export type NewShapeKind = 'textbox' | (string & {})
|
||||
|
||||
export interface NewElementOptions {
|
||||
kind: NewShapeKind
|
||||
offset: EmuRect
|
||||
paragraphs?: Paragraph[]
|
||||
/** Solid shape fill (#RRGGBB); textbox has no fill by default */
|
||||
fillColor?: string
|
||||
/** Shape stroke (solid color, width in EMU) */
|
||||
stroke?: { color: string; widthEmu: number }
|
||||
}
|
||||
|
||||
let insertCounter = 1
|
||||
|
||||
// ── Line / connector insertion ─────────────────────────────
|
||||
|
||||
/** Insertable line/connector kinds: p:cxnSp fragments with optional arrow ends */
|
||||
const LINE_KINDS: Record<string, { prst: string; head?: boolean; tail?: boolean }> = {
|
||||
line: { prst: 'line' },
|
||||
lineArrow: { prst: 'straightConnector1', tail: true },
|
||||
lineArrowDouble: { prst: 'straightConnector1', head: true, tail: true },
|
||||
lineBent: { prst: 'bentConnector3' },
|
||||
lineCurved: { prst: 'curvedConnector3' },
|
||||
}
|
||||
|
||||
export function isLineKind(kind: string): boolean {
|
||||
return Object.prototype.hasOwnProperty.call(LINE_KINDS, kind)
|
||||
}
|
||||
|
||||
const DEFAULT_LINE_STROKE = { color: '#000000', widthEmu: 12700 }
|
||||
|
||||
function buildCxnSpXml(
|
||||
slide: Slide,
|
||||
opts: NewElementOptions,
|
||||
def: { prst: string; head?: boolean; tail?: boolean },
|
||||
): string {
|
||||
const id = nextCNvPrId(slide)
|
||||
const name = `${
|
||||
def.prst.startsWith('bentConnector')
|
||||
? 'Elbow Connector'
|
||||
: def.prst.startsWith('curvedConnector')
|
||||
? 'Curved Connector'
|
||||
: 'Straight Connector'
|
||||
} ${id}`
|
||||
const o = opts.offset
|
||||
const stroke = opts.stroke ?? DEFAULT_LINE_STROKE
|
||||
const color = stroke.color.replace(/^#/, '').slice(0, 6).toUpperCase()
|
||||
const head = def.head ? '<a:headEnd type="triangle" w="med" len="med"/>' : ''
|
||||
const tail = def.tail ? '<a:tailEnd type="triangle" w="med" len="med"/>' : ''
|
||||
return (
|
||||
`<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}"/>` +
|
||||
'<p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>' +
|
||||
`<p:spPr><a:xfrm><a:off x="${o.x}" y="${o.y}"/><a:ext cx="${o.cx}" cy="${o.cy}"/></a:xfrm>` +
|
||||
`<a:prstGeom prst="${def.prst}"><a:avLst/></a:prstGeom>` +
|
||||
`<a:ln w="${Math.round(stroke.widthEmu)}" cap="flat">` +
|
||||
`<a:solidFill><a:srgbClr val="${color}"/></a:solidFill>${head}${tail}</a:ln>` +
|
||||
'</p:spPr></p:cxnSp>'
|
||||
)
|
||||
}
|
||||
|
||||
/** Max cNvPr id used in the slide (including new elements); new elements take max+1 */
|
||||
export function nextCNvPrId(slide: Slide): number {
|
||||
let max = 1
|
||||
const scan = (xml: string) => {
|
||||
for (const m of xml.matchAll(/<p:cNvPr\s[^>]*\bid="(\d+)"/g)) {
|
||||
max = Math.max(max, Number(m[1]))
|
||||
}
|
||||
}
|
||||
scan(slide.originalXml)
|
||||
for (const el of slide.elements) scan(el.anchor.originalXml)
|
||||
return max + 1
|
||||
}
|
||||
|
||||
export function buildSpXml(slide: Slide, opts: NewElementOptions): string {
|
||||
const id = nextCNvPrId(slide)
|
||||
const isTextbox = opts.kind === 'textbox'
|
||||
const name = isTextbox ? `TextBox ${id}` : `Shape ${id}`
|
||||
const o = opts.offset
|
||||
const xfrm = `<a:xfrm><a:off x="${o.x}" y="${o.y}"/><a:ext cx="${o.cx}" cy="${o.cy}"/></a:xfrm>`
|
||||
// Parser convention: has txBody and no prstGeom → 'text'; textbox omits prstGeom
|
||||
const geom = isTextbox
|
||||
? ''
|
||||
: `<a:prstGeom prst="${escapeXmlAttr(opts.kind)}"><a:avLst/></a:prstGeom>`
|
||||
const fill = opts.fillColor
|
||||
? `<a:solidFill><a:srgbClr val="${opts.fillColor.replace(/^#/, '').slice(0, 6).toUpperCase()}"/></a:solidFill>`
|
||||
: ''
|
||||
const ln = opts.stroke
|
||||
? `<a:ln w="${Math.round(opts.stroke.widthEmu)}"><a:solidFill><a:srgbClr val="${opts.stroke.color.replace(/^#/, '').slice(0, 6).toUpperCase()}"/></a:solidFill></a:ln>`
|
||||
: ''
|
||||
const paras = (opts.paragraphs?.length ? opts.paragraphs : [{ runs: [{ text: '' }] }])
|
||||
.map((p) => generateParagraphXml(p))
|
||||
.join('')
|
||||
return (
|
||||
`<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}"/>` +
|
||||
`<p:cNvSpPr${isTextbox ? ' txBox="1"' : ''}/><p:nvPr/></p:nvSpPr>` +
|
||||
`<p:spPr>${xfrm}${geom}${fill}${ln}</p:spPr>` +
|
||||
`<p:txBody><a:bodyPr wrap="square" rtlCol="0"/><a:lstStyle/>${paras}</p:txBody></p:sp>`
|
||||
)
|
||||
}
|
||||
|
||||
/** Synthesize a new element and hang it on the slide; returns the model element (immediately usable by the render layer). */
|
||||
export function addElement(slide: Slide, opts: NewElementOptions): TextElement {
|
||||
const lineDef = LINE_KINDS[opts.kind]
|
||||
if (lineDef) {
|
||||
const stroke = opts.stroke ?? DEFAULT_LINE_STROKE
|
||||
const el: TextElement = {
|
||||
id: `spnew_${(insertCounter++).toString(36)}_${Date.now().toString(36)}`,
|
||||
type: 'shape',
|
||||
anchor: {
|
||||
spIndex: slide.elements.length,
|
||||
originalXml: buildCxnSpXml(slide, opts, lineDef),
|
||||
range: [0, 0],
|
||||
},
|
||||
transform: { offset: { ...opts.offset }, rot: 0, flipH: false, flipV: false },
|
||||
presetGeometry: lineDef.prst,
|
||||
fill: { type: 'none' },
|
||||
stroke: {
|
||||
fill: { type: 'solid', color: stroke.color },
|
||||
width: Math.round(stroke.widthEmu),
|
||||
...(lineDef.head ? { headEnd: { type: 'triangle' as const } } : {}),
|
||||
...(lineDef.tail ? { tailEnd: { type: 'triangle' as const } } : {}),
|
||||
},
|
||||
}
|
||||
slide.elements.push(el)
|
||||
slide.structureDirty = true
|
||||
return el
|
||||
}
|
||||
const xml = buildSpXml(slide, opts)
|
||||
const el: TextElement = {
|
||||
id: `spnew_${(insertCounter++).toString(36)}_${Date.now().toString(36)}`,
|
||||
type: opts.kind === 'textbox' ? 'text' : 'shape',
|
||||
anchor: { spIndex: slide.elements.length, originalXml: xml, range: [0, 0] },
|
||||
transform: { offset: { ...opts.offset }, rot: 0, flipH: false, flipV: false },
|
||||
...(opts.kind !== 'textbox' ? { presetGeometry: opts.kind } : {}),
|
||||
...(opts.fillColor ? { fill: { type: 'solid' as const, color: opts.fillColor } } : {}),
|
||||
...(opts.stroke
|
||||
? {
|
||||
stroke: {
|
||||
fill: { type: 'solid' as const, color: opts.stroke.color },
|
||||
width: Math.round(opts.stroke.widthEmu),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
text: { paragraphs: opts.paragraphs?.length ? opts.paragraphs : [{ runs: [{ text: '' }] }] },
|
||||
}
|
||||
slide.elements.push(el)
|
||||
slide.structureDirty = true
|
||||
return el
|
||||
}
|
||||
|
||||
// ── Table insertion (graphicFrame + a:tbl) ─────────────────────────────
|
||||
|
||||
export interface NewTableOptions {
|
||||
rows: number
|
||||
cols: number
|
||||
offset: EmuRect
|
||||
}
|
||||
|
||||
/** PowerPoint's default style for new tables (Medium Style 2 - Accent 1, built-in fallback in the render layer) */
|
||||
const DEFAULT_TABLE_STYLE_ID = '{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}'
|
||||
|
||||
/**
|
||||
* Build the table graphicFrame fragment (equal-width columns / equal-height rows,
|
||||
* default built-in style, empty cells). Insertion goes through appendRawElements
|
||||
* (materialize+reparse), reusing the existing table parsing/rendering pipeline.
|
||||
*/
|
||||
export function buildTableXml(slide: Slide, opts: NewTableOptions): string {
|
||||
const id = nextCNvPrId(slide)
|
||||
const rows = Math.max(1, Math.floor(opts.rows))
|
||||
const cols = Math.max(1, Math.floor(opts.cols))
|
||||
const colW = Math.max(1, Math.floor(opts.offset.cx / cols))
|
||||
const rowH = Math.max(1, Math.floor(opts.offset.cy / rows))
|
||||
const grid = Array.from({ length: cols }, () => `<a:gridCol w="${colW}"/>`).join('')
|
||||
const cell = '<a:tc><a:txBody><a:bodyPr/><a:lstStyle/><a:p/></a:txBody><a:tcPr/></a:tc>'
|
||||
const trs = Array.from(
|
||||
{ length: rows },
|
||||
() => `<a:tr h="${rowH}">${cell.repeat(cols)}</a:tr>`,
|
||||
).join('')
|
||||
return (
|
||||
`<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="${id}" name="Table ${id}"/>` +
|
||||
'<p:cNvGraphicFramePr><a:graphicFrameLocks noGrp="1"/></p:cNvGraphicFramePr><p:nvPr/></p:nvGraphicFramePr>' +
|
||||
`<p:xfrm><a:off x="${opts.offset.x}" y="${opts.offset.y}"/><a:ext cx="${opts.offset.cx}" cy="${opts.offset.cy}"/></p:xfrm>` +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/table">' +
|
||||
`<a:tbl><a:tblPr firstRow="1" bandRow="1"><a:tableStyleId>${DEFAULT_TABLE_STYLE_ID}</a:tableStyleId></a:tblPr>` +
|
||||
`<a:tblGrid>${grid}</a:tblGrid>${trs}</a:tbl></a:graphicData></a:graphic></p:graphicFrame>`
|
||||
)
|
||||
}
|
||||
|
||||
// ── Picture insertion (media part surgery) ─────────────────────────────
|
||||
|
||||
const IMAGE_MIME: Record<string, string> = {
|
||||
png: 'image/png',
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
gif: 'image/gif',
|
||||
bmp: 'image/bmp',
|
||||
webp: 'image/webp',
|
||||
tif: 'image/tiff',
|
||||
tiff: 'image/tiff',
|
||||
}
|
||||
|
||||
const IMAGE_REL_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'
|
||||
|
||||
export interface NewPictureOptions {
|
||||
/** Image bytes */
|
||||
bytes: Uint8Array
|
||||
/** Lowercase extension (png/jpg/…) */
|
||||
ext: string
|
||||
offset: EmuRect
|
||||
/** cNvPr name (default Picture N; hand-drawn ink is marked with the aislides-ink prefix) */
|
||||
name?: string
|
||||
/** cNvPr descr: editor-specific payload (e.g. ink vector points), recoverable on reopen */
|
||||
descr?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a picture: media bytes into the package + [Content_Types] Default +
|
||||
* slide rels registration + synthesized <p:pic> fragment hung on slide.elements.
|
||||
* The dataUrl is generated on demand by the caller (media resolver).
|
||||
*/
|
||||
/**
|
||||
* Land an image into the package: media part + Content_Types Default + slide rels.
|
||||
* Returns the new relationship id and media path (shared by picture insertion /
|
||||
* shape picture fill).
|
||||
*/
|
||||
export function addImageMediaAndRel(
|
||||
opened: OpenedPptx,
|
||||
slide: Slide,
|
||||
bytes: Uint8Array,
|
||||
extRaw: string,
|
||||
): { rid: string; mediaPath: string } | null {
|
||||
const { archive } = opened
|
||||
const ext = extRaw.toLowerCase()
|
||||
const mime = IMAGE_MIME[ext]
|
||||
if (!mime) return null
|
||||
|
||||
// 1) media part: number = current max + 1
|
||||
let maxNum = 0
|
||||
for (const path of archive.entries.keys()) {
|
||||
const m = /^ppt\/media\/image(\d+)\./.exec(path)
|
||||
if (m) maxNum = Math.max(maxNum, Number(m[1]))
|
||||
}
|
||||
const mediaPath = `ppt/media/image${maxNum + 1}.${ext}`
|
||||
archive.entries.set(mediaPath, bytes)
|
||||
|
||||
// 2) [Content_Types] Default (added the first time this extension appears)
|
||||
const ctPath = '[Content_Types].xml'
|
||||
const ct = archive.readText(ctPath)
|
||||
if (ct && !new RegExp(`<Default Extension="${ext}"`).test(ct)) {
|
||||
const dflt = `<Default Extension="${ext}" ContentType="${mime}"/>`
|
||||
archive.entries.set(ctPath, Buffer.from(ct.replace('</Types>', `${dflt}</Types>`), 'utf8'))
|
||||
}
|
||||
|
||||
// 3) slide rels: new rId (the rels file may not exist)
|
||||
const relsPath = relsPathFor(slide.path)
|
||||
const rels =
|
||||
archive.readText(relsPath) ??
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>'
|
||||
let maxRid = 0
|
||||
for (const m of rels.matchAll(/Id="rId(\d+)"/g)) maxRid = Math.max(maxRid, Number(m[1]))
|
||||
const rid = `rId${maxRid + 1}`
|
||||
const relXml = `<Relationship Id="${rid}" Type="${IMAGE_REL_TYPE}" Target="../media/image${maxNum + 1}.${ext}"/>`
|
||||
archive.entries.set(
|
||||
relsPath,
|
||||
Buffer.from(rels.replace('</Relationships>', `${relXml}</Relationships>`), 'utf8'),
|
||||
)
|
||||
return { rid, mediaPath }
|
||||
}
|
||||
|
||||
export function addPicture(
|
||||
opened: OpenedPptx,
|
||||
slide: Slide,
|
||||
opts: NewPictureOptions,
|
||||
): PictureElement | null {
|
||||
const added = addImageMediaAndRel(opened, slide, opts.bytes, opts.ext)
|
||||
if (!added) return null
|
||||
const { rid, mediaPath } = added
|
||||
|
||||
// 4) <p:pic> fragment
|
||||
const id = nextCNvPrId(slide)
|
||||
const name = opts.name ?? `Picture ${id}`
|
||||
const descrAttr = opts.descr ? ` descr="${escapeXmlAttr(opts.descr)}"` : ''
|
||||
const xml =
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}"${descrAttr}/>` +
|
||||
'<p:cNvPicPr/><p:nvPr/></p:nvPicPr>' +
|
||||
`<p:blipFill><a:blip r:embed="${rid}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
|
||||
`<p:spPr>${generateXfrmXml({ offset: opts.offset, rot: 0, flipH: false, flipV: false })}` +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>'
|
||||
|
||||
const el: PictureElement = {
|
||||
id: `picnew_${(insertCounter++).toString(36)}_${Date.now().toString(36)}`,
|
||||
type: 'picture',
|
||||
anchor: { spIndex: slide.elements.length, originalXml: xml, range: [0, 0] },
|
||||
transform: { offset: { ...opts.offset }, rot: 0, flipH: false, flipV: false },
|
||||
name,
|
||||
...(opts.descr ? { descr: opts.descr } : {}),
|
||||
mediaRef: mediaPath,
|
||||
}
|
||||
slide.elements.push(el)
|
||||
slide.structureDirty = true
|
||||
return el
|
||||
}
|
||||
|
||||
/** Delete by element id; returns whether anything was removed. */
|
||||
export function deleteElement(slide: Slide, elementId: string): boolean {
|
||||
const idx = slide.elements.findIndex((e) => e.id === elementId)
|
||||
if (idx < 0) return false
|
||||
slide.elements.splice(idx, 1)
|
||||
slide.structureDirty = true
|
||||
return true
|
||||
}
|
||||
|
||||
// ── Grouping (p:grpSp) ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Compute the bounding box of a set of elements (slide coordinates, EMU).
|
||||
* Ignores rotation: uses the axis-aligned bounding box of each element's offset
|
||||
* rect.
|
||||
*/
|
||||
export function calcBoundingBox(elements: SlideElement[]): EmuRect {
|
||||
let minX = Infinity,
|
||||
minY = Infinity,
|
||||
maxX = -Infinity,
|
||||
maxY = -Infinity
|
||||
for (const el of elements) {
|
||||
const o = el.transform.offset
|
||||
minX = Math.min(minX, o.x)
|
||||
minY = Math.min(minY, o.y)
|
||||
maxX = Math.max(maxX, o.x + o.cx)
|
||||
maxY = Math.max(maxY, o.y + o.cy)
|
||||
}
|
||||
return { x: minX, y: minY, cx: maxX - minX, cy: maxY - minY }
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the <p:grpSp> XML fragment.
|
||||
*
|
||||
* OOXML conventions (ECMA 376 §19.3.1.22):
|
||||
* - grpSpPr/xfrm describes the group's position and size on the slide (<a:off>/<a:ext>)
|
||||
* - grpSpPr/xfrm/chOff + chExt define the child coordinate system's origin and size
|
||||
* - This implementation sets chOff == bbox.xy and chExt == bbox.cxcy, i.e. the child
|
||||
* coordinate system is 1:1 with the slide's → child elements can reuse their
|
||||
* original slide coordinates inside the group with no transform
|
||||
* - childrenXml: concatenation of each child's raw XML fragment (passthrough
|
||||
* children keep their original bytes)
|
||||
*/
|
||||
export function buildGrpSpXml(slide: Slide, bbox: EmuRect, childrenXml: string): string {
|
||||
const id = nextCNvPrId(slide)
|
||||
const name = `Group ${id}`
|
||||
const { x, y, cx, cy } = bbox
|
||||
const grpXfrm =
|
||||
`<a:xfrm>` +
|
||||
`<a:off x="${x}" y="${y}"/><a:ext cx="${cx}" cy="${cy}"/>` +
|
||||
`<a:chOff x="${x}" y="${y}"/><a:chExt cx="${cx}" cy="${cy}"/>` +
|
||||
`</a:xfrm>`
|
||||
return (
|
||||
`<p:grpSp>` +
|
||||
`<p:nvGrpSpPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}"/>` +
|
||||
`<p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>` +
|
||||
`<p:grpSpPr>${grpXfrm}</p:grpSpPr>` +
|
||||
childrenXml +
|
||||
`</p:grpSp>`
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
/**
|
||||
* SlideLayout listing + inserting a new slide with a given layout.
|
||||
*
|
||||
* Read-only: layout parts are never written back.
|
||||
* Provides:
|
||||
* - listSlideLayouts: enumerate every slideLayout's path/name/placeholders in the pptx
|
||||
* - insertBlankSlideWithLayout: insert a blank slide after a given position, with
|
||||
* rels pointing at the chosen layout
|
||||
*/
|
||||
import type { PackageArchive } from './zip'
|
||||
import { resolveTarget, relsPathFor } from './zip'
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
import type { SlideDeck } from './types'
|
||||
|
||||
// ── Layout placeholder summary ─────────────────────────────────────────────
|
||||
|
||||
/** Summary of one placeholder (used to generate empty placeholder elements for new slides) */
|
||||
export interface LayoutPlaceholder {
|
||||
/** ph type: 'title'|'ctrTitle'|'body'|'subTitle'|'obj'|'ftr'|'sldNum'|'dt'|'' */
|
||||
type: string
|
||||
/** ph idx */
|
||||
idx: string
|
||||
/** Geometry (EMU; read directly from the layout) */
|
||||
x: number
|
||||
y: number
|
||||
cx: number
|
||||
cy: number
|
||||
/** Editor default hint text (shown in the empty box) */
|
||||
hint: string
|
||||
}
|
||||
|
||||
/** Description of one slideLayout */
|
||||
export interface SlideLayoutInfo {
|
||||
/** Path inside the zip, e.g. ppt/slideLayouts/slideLayout3.xml */
|
||||
path: string
|
||||
/** Layout name (<p:cSld name="…">, falling back to the file name) */
|
||||
name: string
|
||||
/** Layout type attribute (blank/title/titleBody/…; from <p:sldLayout type="…">) */
|
||||
layoutType: string
|
||||
/** Main placeholders (excluding functional placeholders ftr/sldNum/dt/pic) */
|
||||
placeholders: LayoutPlaceholder[]
|
||||
}
|
||||
|
||||
const HINT_MAP: Record<string, string> = {
|
||||
title: 'Click to add title',
|
||||
ctrTitle: 'Click to add title',
|
||||
body: 'Click to add text',
|
||||
subTitle: 'Click to add subtitle',
|
||||
obj: 'Click to add content',
|
||||
'': 'Click to add text',
|
||||
}
|
||||
|
||||
const FUNCTION_TYPES = new Set(['ftr', 'sldNum', 'dt', 'pic'])
|
||||
|
||||
/** Quick-parse the <p:cSld> name attribute from the layout XML */
|
||||
function parseLayoutName(xml: string, fallback: string): string {
|
||||
const m = /<p:cSld\s[^>]*name="([^"]*)"/.exec(xml)
|
||||
return m?.[1] || fallback
|
||||
}
|
||||
|
||||
/** Quick-parse the <p:sldLayout> type attribute from the layout XML */
|
||||
function parseLayoutType(xml: string): string {
|
||||
const m = /<p:sldLayout\b[^>]*\btype="([^"]*)"/.exec(xml)
|
||||
return m?.[1] ?? 'custom'
|
||||
}
|
||||
|
||||
/** Parse all placeholder geometry from the layout XML (only non-functional placeholders with an xfrm) */
|
||||
function parseLayoutPlaceholders(xml: string): LayoutPlaceholder[] {
|
||||
const results: LayoutPlaceholder[] = []
|
||||
for (const spMatch of xml.matchAll(/<p:sp>([\s\S]*?)<\/p:sp>/g)) {
|
||||
const sp = spMatch[1]!
|
||||
const phMatch = /<p:ph\b([^>]*)\/?>/.exec(sp)
|
||||
if (!phMatch) continue
|
||||
const phAttr = phMatch[1]!
|
||||
const typeM = /\btype="([^"]*)"/.exec(phAttr)
|
||||
const idxM = /\bidx="([^"]*)"/.exec(phAttr)
|
||||
const type = typeM?.[1] ?? ''
|
||||
const idx = idxM?.[1] ?? ''
|
||||
if (FUNCTION_TYPES.has(type)) continue
|
||||
// Try to parse the xfrm (may come from the layout or the master)
|
||||
const xfrmM = /<a:xfrm\b[^>]*>([\s\S]*?)<\/a:xfrm>/.exec(sp)
|
||||
if (!xfrmM) continue
|
||||
const xfrmContent = xfrmM[1]!
|
||||
const offM = /<a:off\s[^>]*x="([^"]*)"[^>]*y="([^"]*)"/.exec(xfrmContent)
|
||||
const extM = /<a:ext\s[^>]*cx="([^"]*)"[^>]*cy="([^"]*)"/.exec(xfrmContent)
|
||||
if (!offM || !extM) continue
|
||||
const x = parseInt(offM[1]!, 10)
|
||||
const y = parseInt(offM[2]!, 10)
|
||||
const cx = parseInt(extM[1]!, 10)
|
||||
const cy = parseInt(extM[2]!, 10)
|
||||
if (isNaN(x) || isNaN(y) || isNaN(cx) || isNaN(cy)) continue
|
||||
results.push({ type, idx, x, y, cx, cy, hint: HINT_MAP[type] ?? 'Click to add text' })
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
/**
|
||||
* Enumerate all slideLayouts in the archive (sorted by number).
|
||||
* Only scans ppt/slideLayouts/slideLayoutN.xml files; does not rely on
|
||||
* presentation.xml's sldLayoutIdLst.
|
||||
*/
|
||||
export function listSlideLayouts(archive: PackageArchive): SlideLayoutInfo[] {
|
||||
const paths = [...archive.entries.keys()]
|
||||
.filter((p) => /^ppt\/slideLayouts\/slideLayout\d+\.xml$/.test(p))
|
||||
.sort((a, b) => {
|
||||
const na = parseInt(/(\d+)/.exec(a)?.[1] ?? '0', 10)
|
||||
const nb = parseInt(/(\d+)/.exec(b)?.[1] ?? '0', 10)
|
||||
return na - nb
|
||||
})
|
||||
|
||||
return paths.map((path) => {
|
||||
const xml = archive.readText(path) ?? ''
|
||||
const fileName = path.slice(path.lastIndexOf('/') + 1, -4)
|
||||
const name = parseLayoutName(xml, fileName)
|
||||
const layoutType = parseLayoutType(xml)
|
||||
const placeholders = parseLayoutPlaceholders(xml)
|
||||
return { path, name, layoutType, placeholders }
|
||||
})
|
||||
}
|
||||
|
||||
// ── Blank slide insertion (with a given layout) ─────────────────────────
|
||||
|
||||
const SLIDE_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.presentationml.slide+xml'
|
||||
const SLIDE_REL_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide'
|
||||
export const LAYOUT_REL_TYPE =
|
||||
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout'
|
||||
|
||||
/** Generate the next unused slide path (current max number + 1). */
|
||||
function nextSlidePath(archive: PackageArchive): string {
|
||||
let max = 0
|
||||
for (const path of archive.entries.keys()) {
|
||||
const m = /^ppt\/slides\/slide(\d+)\.xml$/.exec(path)
|
||||
if (m) max = Math.max(max, parseInt(m[1]!, 10))
|
||||
}
|
||||
return `ppt/slides/slide${max + 1}.xml`
|
||||
}
|
||||
|
||||
export interface InsertLayoutSlideOptions {
|
||||
/** Insert after this slide index (0-based) */
|
||||
sourceIndex: number
|
||||
/** Target layout path (from listSlideLayouts), e.g. 'ppt/slideLayouts/slideLayout2.xml' */
|
||||
layoutPath: string
|
||||
}
|
||||
|
||||
const XMLDECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
const NS_A = 'http://schemas.openxmlformats.org/drawingml/2006/main'
|
||||
const NS_R = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
|
||||
const NS_P = 'http://schemas.openxmlformats.org/presentationml/2006/main'
|
||||
|
||||
const EMPTY_SPTREE =
|
||||
'<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
|
||||
'<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/>' +
|
||||
'<a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>'
|
||||
|
||||
/**
|
||||
* Build blank slide XML containing the layout's placeholders.
|
||||
* Each non-functional placeholder produces a minimal text box (<p:sp>) with a
|
||||
* hint text paragraph.
|
||||
*/
|
||||
function buildSlideXmlWithPlaceholders(placeholders: LayoutPlaceholder[]): string {
|
||||
const shapes: string[] = []
|
||||
let id = 2
|
||||
for (const ph of placeholders) {
|
||||
const typeAttr = ph.type ? ` type="${escapeXmlAttr(ph.type)}"` : ''
|
||||
const idxAttr = ph.idx ? ` idx="${escapeXmlAttr(ph.idx)}"` : ''
|
||||
shapes.push(
|
||||
`<p:sp>` +
|
||||
`<p:nvSpPr>` +
|
||||
`<p:cNvPr id="${id++}" name="ph${ph.idx || '0'}"/>` +
|
||||
`<p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr>` +
|
||||
`<p:nvPr><p:ph${typeAttr}${idxAttr}/></p:nvPr>` +
|
||||
`</p:nvSpPr>` +
|
||||
`<p:spPr><a:xfrm><a:off x="${ph.x}" y="${ph.y}"/><a:ext cx="${ph.cx}" cy="${ph.cy}"/></a:xfrm></p:spPr>` +
|
||||
// Empty paragraph (like a new PowerPoint slide): the click hint is drawn by the edit canvas, not persisted
|
||||
`<p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody>` +
|
||||
`</p:sp>`,
|
||||
)
|
||||
}
|
||||
const spTree = `<p:spTree>${EMPTY_SPTREE}${shapes.join('')}</p:spTree>`
|
||||
return (
|
||||
XMLDECL +
|
||||
`<p:sld xmlns:a="${NS_A}" xmlns:r="${NS_R}" xmlns:p="${NS_P}">` +
|
||||
`<p:cSld>${spTree}</p:cSld>` +
|
||||
'<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a blank slide associated with a given layout.
|
||||
* The internal caller is responsible for:
|
||||
* 1. writing the new path into the archive
|
||||
* 2. registering it in presentation.xml + rels + [Content_Types].xml
|
||||
* 3. parsing and splicing it into deck.slides
|
||||
*
|
||||
* This function only performs the archive surgery of 1-3; parseSlide is up to the
|
||||
* caller (index.ts). Returns the new slide's path, or null on failure.
|
||||
*/
|
||||
export function prepareInsertSlideWithLayout(
|
||||
archive: PackageArchive,
|
||||
deck: SlideDeck,
|
||||
sourceIndex: number,
|
||||
layoutPath: string,
|
||||
): string | null {
|
||||
const src = deck.slides[sourceIndex]
|
||||
if (!src) return null
|
||||
if (!archive.readText(layoutPath)) return null
|
||||
|
||||
// Parse the layout placeholders and build the new slide XML with placeholder text boxes
|
||||
const layoutXml = archive.readText(layoutPath) ?? ''
|
||||
const layoutInfo: SlideLayoutInfo = {
|
||||
path: layoutPath,
|
||||
name: parseLayoutName(layoutXml, ''),
|
||||
layoutType: parseLayoutType(layoutXml),
|
||||
placeholders: parseLayoutPlaceholders(layoutXml),
|
||||
}
|
||||
const newSlideXml = buildSlideXmlWithPlaceholders(layoutInfo.placeholders)
|
||||
|
||||
const newPath = nextSlidePath(archive)
|
||||
archive.entries.set(newPath, Buffer.from(newSlideXml, 'utf8'))
|
||||
|
||||
// slide rels → point at the chosen layout
|
||||
const relTarget = `../${layoutPath.slice(4)}` // 'ppt/' → '../'
|
||||
const relsXml =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
`<Relationship Id="rId1" Type="${LAYOUT_REL_TYPE}" Target="${escapeXmlAttr(relTarget)}"/>` +
|
||||
'</Relationships>'
|
||||
archive.entries.set(relsPathFor(newPath), Buffer.from(relsXml, 'utf8'))
|
||||
|
||||
// [Content_Types].xml
|
||||
const ctPath = '[Content_Types].xml'
|
||||
const ct = archive.readText(ctPath)
|
||||
if (ct && !ct.includes(`PartName="/${newPath}"`)) {
|
||||
archive.entries.set(
|
||||
ctPath,
|
||||
Buffer.from(
|
||||
ct.replace(
|
||||
'</Types>',
|
||||
`<Override PartName="/${newPath}" ContentType="${SLIDE_CONTENT_TYPE}"/></Types>`,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// presentation.xml.rels + presentation.xml
|
||||
const presRelsPath = 'ppt/_rels/presentation.xml.rels'
|
||||
const presPath = 'ppt/presentation.xml'
|
||||
const presRels = archive.readText(presRelsPath)
|
||||
const pres = archive.readText(presPath)
|
||||
if (!presRels || !pres) return null
|
||||
|
||||
let maxRid = 0
|
||||
for (const m of presRels.matchAll(/Id="rId(\d+)"/g)) maxRid = Math.max(maxRid, Number(m[1]))
|
||||
const newRid = `rId${maxRid + 1}`
|
||||
const relEntry = `<Relationship Id="${newRid}" Type="${SLIDE_REL_TYPE}" Target="${newPath.slice('ppt/'.length)}"/>`
|
||||
archive.entries.set(
|
||||
presRelsPath,
|
||||
Buffer.from(presRels.replace('</Relationships>', `${relEntry}</Relationships>`), 'utf8'),
|
||||
)
|
||||
|
||||
let maxSldId = 255
|
||||
for (const m of pres.matchAll(/<p:sldId\s[^>]*\bid="(\d+)"/g))
|
||||
maxSldId = Math.max(maxSldId, Number(m[1]))
|
||||
const newSldTag = `<p:sldId id="${maxSldId + 1}" r:id="${newRid}"/>`
|
||||
|
||||
// Insert after the source slide's sldId
|
||||
const srcRid = [...archive.readRels(presPath).values()].find(
|
||||
(r) => resolveTarget(presPath, r.target) === src.path,
|
||||
)?.id
|
||||
const srcTag = srcRid
|
||||
? new RegExp(`<p:sldId\\s[^>]*r:id="${srcRid}"[^>]*/>`).exec(pres)?.[0]
|
||||
: undefined
|
||||
const nextPres = srcTag
|
||||
? pres.replace(srcTag, `${srcTag}${newSldTag}`)
|
||||
: pres.replace('</p:sldIdLst>', `${newSldTag}</p:sldIdLst>`)
|
||||
archive.entries.set(presPath, Buffer.from(nextPres, 'utf8'))
|
||||
|
||||
return newPath
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Slide master / layout edit view support (6.16).
|
||||
*
|
||||
* Exception to the fidelity rule: only layout/master parts the user actively edited
|
||||
* in master view are written back, reusing the slide byte-surgery path (scanSlide
|
||||
* anchors + patchSlideXml); untouched elements pass through with original bytes.
|
||||
* This module only enumerates and parses; the caller writes back via patchSlideXml
|
||||
* and then writes the archive entry.
|
||||
*/
|
||||
import type { PackageArchive } from './zip'
|
||||
import { resolveTarget } from './zip'
|
||||
import { parseTheme } from './theme'
|
||||
import { parseSlide, parseDecorations, type ParseContext } from './parse'
|
||||
import { parsePlaceholderMap, parseMasterTextStyles } from './placeholder'
|
||||
import type { Slide } from './types'
|
||||
|
||||
export interface MasterPartInfo {
|
||||
/** Path inside the zip, e.g. ppt/slideMasters/slideMaster1.xml */
|
||||
partPath: string
|
||||
kind: 'master' | 'layout'
|
||||
/** <p:cSld name="…">, falling back to the file name */
|
||||
name: string
|
||||
}
|
||||
|
||||
const partNum = (p: string) => parseInt(/(\d+)\.xml$/.exec(p)?.[1] ?? '0', 10)
|
||||
|
||||
function cSldName(xml: string | null | undefined, fallback: string): string {
|
||||
const m = xml ? /<p:cSld\s[^>]*name="([^"]*)"/.exec(xml) : null
|
||||
return m?.[1] || fallback
|
||||
}
|
||||
|
||||
/** Enumerate parts for the master edit view: each master first, followed by its layouts. */
|
||||
export function listMasterParts(archive: PackageArchive): MasterPartInfo[] {
|
||||
const masters = [...archive.entries.keys()]
|
||||
.filter((p) => /^ppt\/slideMasters\/slideMaster\d+\.xml$/.test(p))
|
||||
.sort((a, b) => partNum(a) - partNum(b))
|
||||
const out: MasterPartInfo[] = []
|
||||
for (const m of masters) {
|
||||
out.push({ partPath: m, kind: 'master', name: cSldName(archive.readText(m), baseName(m)) })
|
||||
const layouts = [...archive.readRels(m).values()]
|
||||
.filter((r) => r.type.endsWith('/slideLayout'))
|
||||
.map((r) => resolveTarget(m, r.target))
|
||||
.sort((a, b) => partNum(a) - partNum(b))
|
||||
for (const l of layouts) {
|
||||
out.push({ partPath: l, kind: 'layout', name: cSldName(archive.readText(l), baseName(l)) })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function baseName(p: string): string {
|
||||
return p.slice(p.lastIndexOf('/') + 1, -4)
|
||||
}
|
||||
|
||||
/** A part's own image rels (same logic as index.ts partMediaRels, duplicated to avoid a circular dependency). */
|
||||
function partMedia(archive: PackageArchive, partPath: string): Map<string, string> {
|
||||
const media = new Map<string, string>()
|
||||
for (const rel of archive.readRels(partPath).values()) {
|
||||
if (rel.type.endsWith('/image')) media.set(rel.id, resolveTarget(partPath, rel.target))
|
||||
}
|
||||
return media
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a layout/master part into an editable Slide (its spTree structure is isomorphic
|
||||
* to a slide's, so scanSlide applies directly).
|
||||
* - master: text styles come from its own <p:txStyles>; placeholders always have an
|
||||
* explicit xfrm, so no geometry inheritance is needed.
|
||||
* - layout: placeholder geometry/text styles/background inherit from its master; the
|
||||
* master decoration layer is rendered underneath.
|
||||
*/
|
||||
export function parseMasterPart(archive: PackageArchive, partPath: string): Slide | null {
|
||||
const xml = archive.readText(partPath)
|
||||
if (!xml) return null
|
||||
const isMaster = partPath.includes('/slideMasters/')
|
||||
|
||||
let masterPath: string | undefined = isMaster ? partPath : undefined
|
||||
if (!isMaster) {
|
||||
for (const rel of archive.readRels(partPath).values()) {
|
||||
if (rel.type.endsWith('/slideMaster')) {
|
||||
masterPath = resolveTarget(partPath, rel.target)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ctx: ParseContext = {}
|
||||
if (masterPath) {
|
||||
for (const rel of archive.readRels(masterPath).values()) {
|
||||
if (rel.type.endsWith('/theme')) {
|
||||
const themeXml = archive.readText(resolveTarget(masterPath, rel.target))
|
||||
if (themeXml) ctx.theme = parseTheme(themeXml)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.mediaRels = partMedia(archive, partPath)
|
||||
ctx.tableStyles = archive.readText('ppt/tableStyles.xml') ?? undefined
|
||||
|
||||
const masterXml = !isMaster && masterPath ? archive.readText(masterPath) : undefined
|
||||
if (isMaster) {
|
||||
ctx.masterTextStyles = parseMasterTextStyles(xml, ctx.theme)
|
||||
} else if (masterXml) {
|
||||
ctx.masterPlaceholders = parsePlaceholderMap(masterXml, ctx.theme)
|
||||
ctx.masterTextStyles = parseMasterTextStyles(masterXml, ctx.theme)
|
||||
ctx.masterBg = masterXml
|
||||
}
|
||||
|
||||
const slide = parseSlide({ path: partPath, slideXml: xml, masterPath, ctx })
|
||||
|
||||
// Layout view renders master concrete shapes underneath (master decorations stay visible when editing a layout)
|
||||
if (!isMaster && masterXml && masterPath) {
|
||||
if (!/<p:sldLayout\b[^>]*showMasterSp="(?:0|false)"/.test(xml)) {
|
||||
const dctx: ParseContext = { theme: ctx.theme, mediaRels: partMedia(archive, masterPath) }
|
||||
const dec = parseDecorations(masterXml, dctx, {})
|
||||
if (dec.length) slide.decorations = dec
|
||||
}
|
||||
}
|
||||
return slide
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
/**
|
||||
* Audio/video / 3D model insertion — media part surgery.
|
||||
*
|
||||
* Video/audio: the modern PowerPoint dual-relationship form —
|
||||
* <a:videoFile r:link> (2007 semantics) + p14:media r:embed (2010 semantics),
|
||||
* both relationships pointing at the same embedded ppt/media/mediaN.ext part;
|
||||
* blipFill is the poster frame.
|
||||
*
|
||||
* 3D models (simplified): glb bytes embedded in the package + a poster placeholder
|
||||
* image element (cNvPr descr records the model part path so it is recoverable);
|
||||
* no am3d extension XML is written (the schema is complex and easily triggers
|
||||
* repair); shows as the poster image in PowerPoint.
|
||||
*/
|
||||
import { deflateSync } from 'node:zlib'
|
||||
import type { EmuRect, Slide } from './types'
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
import { relsPathFor } from './zip'
|
||||
import { appendRawElements, type OpenedPptx } from './index'
|
||||
import { nextCNvPrId } from './insert'
|
||||
|
||||
const R_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
|
||||
const IMAGE_REL_TYPE = `${R_NS}/image`
|
||||
const VIDEO_REL_TYPE = `${R_NS}/video`
|
||||
const AUDIO_REL_TYPE = `${R_NS}/audio`
|
||||
const MEDIA_REL_TYPE = 'http://schemas.microsoft.com/office/2007/relationships/media'
|
||||
const P14_NS = 'http://schemas.microsoft.com/office/powerpoint/2010/main'
|
||||
/** Fixed uri of the <p:ext> that hosts p14:media (ECMA/Microsoft convention) */
|
||||
const MEDIA_EXT_URI = '{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}'
|
||||
|
||||
const MEDIA_MIME: Record<string, string> = {
|
||||
mp4: 'video/mp4',
|
||||
m4v: 'video/mp4',
|
||||
mov: 'video/quicktime',
|
||||
webm: 'video/webm',
|
||||
avi: 'video/x-msvideo',
|
||||
mp3: 'audio/mpeg',
|
||||
wav: 'audio/wav',
|
||||
m4a: 'audio/mp4',
|
||||
aac: 'audio/aac',
|
||||
ogg: 'audio/ogg',
|
||||
glb: 'model/gltf-binary',
|
||||
gltf: 'model/gltf+json',
|
||||
}
|
||||
|
||||
// ── Solid-color PNG generation (poster frame fallback, no canvas dependency) ──
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const t = new Int32Array(256)
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
|
||||
t[n] = c
|
||||
}
|
||||
return t
|
||||
})()
|
||||
|
||||
function crc32(buf: Uint8Array): number {
|
||||
let c = -1
|
||||
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]!) & 0xff]! ^ (c >>> 8)
|
||||
return (c ^ -1) >>> 0
|
||||
}
|
||||
|
||||
function pngChunk(type: string, data: Uint8Array): Buffer {
|
||||
const head = Buffer.alloc(8)
|
||||
head.writeUInt32BE(data.length, 0)
|
||||
head.write(type, 4, 'ascii')
|
||||
const crcBuf = Buffer.alloc(4)
|
||||
crcBuf.writeUInt32BE(crc32(Buffer.concat([Buffer.from(type, 'ascii'), data])), 0)
|
||||
return Buffer.concat([head, data, crcBuf])
|
||||
}
|
||||
|
||||
/** Generate a w×h solid-color PNG (RGB, no alpha). Used as a poster frame placeholder. */
|
||||
export function solidPng(w: number, h: number, rgb: [number, number, number]): Buffer {
|
||||
const ihdr = Buffer.alloc(13)
|
||||
ihdr.writeUInt32BE(w, 0)
|
||||
ihdr.writeUInt32BE(h, 4)
|
||||
ihdr[8] = 8 // bit depth
|
||||
ihdr[9] = 2 // color type RGB
|
||||
const raw = Buffer.alloc(h * (1 + w * 3))
|
||||
for (let y = 0; y < h; y++) {
|
||||
const row = y * (1 + w * 3)
|
||||
raw[row] = 0 // filter none
|
||||
for (let x = 0; x < w; x++) {
|
||||
raw[row + 1 + x * 3] = rgb[0]
|
||||
raw[row + 2 + x * 3] = rgb[1]
|
||||
raw[row + 3 + x * 3] = rgb[2]
|
||||
}
|
||||
}
|
||||
return Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
pngChunk('IHDR', ihdr),
|
||||
pngChunk('IDAT', deflateSync(raw)),
|
||||
pngChunk('IEND', Buffer.alloc(0)),
|
||||
])
|
||||
}
|
||||
|
||||
// ── Shared part / rels surgery ─────────────────────────────────────────
|
||||
|
||||
function ensureDefaultContentType(opened: OpenedPptx, ext: string, mime: string): void {
|
||||
const ctPath = '[Content_Types].xml'
|
||||
const ct = opened.archive.readText(ctPath)
|
||||
if (ct && !new RegExp(`<Default Extension="${ext}"`).test(ct)) {
|
||||
const dflt = `<Default Extension="${ext}" ContentType="${mime}"/>`
|
||||
opened.archive.entries.set(ctPath, Buffer.from(ct.replace('</Types>', `${dflt}</Types>`), 'utf8'))
|
||||
}
|
||||
}
|
||||
|
||||
/** New media part: ppt/media/{prefix}N.ext, numbered max + 1 across the whole media dir. */
|
||||
function newMediaPart(opened: OpenedPptx, prefix: string, ext: string, bytes: Uint8Array): string {
|
||||
let maxNum = 0
|
||||
for (const path of opened.archive.entries.keys()) {
|
||||
const m = /^ppt\/media\/[a-zA-Z]+(\d+)\./.exec(path)
|
||||
if (m) maxNum = Math.max(maxNum, Number(m[1]))
|
||||
}
|
||||
const partPath = `ppt/media/${prefix}${maxNum + 1}.${ext}`
|
||||
opened.archive.entries.set(partPath, bytes)
|
||||
return partPath
|
||||
}
|
||||
|
||||
/** Append relationships to the slide rels; returns the assigned rIds (in order). */
|
||||
function appendRels(
|
||||
opened: OpenedPptx,
|
||||
slide: Slide,
|
||||
rels: Array<{ type: string; target: string; external?: boolean }>,
|
||||
): string[] {
|
||||
const relsPath = relsPathFor(slide.path)
|
||||
let xml =
|
||||
opened.archive.readText(relsPath) ??
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>'
|
||||
let maxRid = 0
|
||||
for (const m of xml.matchAll(/Id="rId(\d+)"/g)) maxRid = Math.max(maxRid, Number(m[1]))
|
||||
const rids: string[] = []
|
||||
for (const rel of rels) {
|
||||
const rid = `rId${++maxRid}`
|
||||
rids.push(rid)
|
||||
const mode = rel.external ? ' TargetMode="External"' : ''
|
||||
xml = xml.replace(
|
||||
'</Relationships>',
|
||||
`<Relationship Id="${rid}" Type="${rel.type}" Target="${escapeXmlAttr(rel.target)}"${mode}/></Relationships>`,
|
||||
)
|
||||
}
|
||||
opened.archive.entries.set(relsPath, Buffer.from(xml, 'utf8'))
|
||||
return rids
|
||||
}
|
||||
|
||||
// ── Audio/video ────────────────────────────────────────────────────────
|
||||
|
||||
export interface NewMediaOptions {
|
||||
kind: 'video' | 'audio'
|
||||
bytes: Uint8Array
|
||||
/** Lowercase extension (mp4/mov/webm/mp3/wav/m4a…) */
|
||||
ext: string
|
||||
/** Poster frame (defaults to a generated solid-color placeholder PNG) */
|
||||
poster?: { bytes: Uint8Array; ext: string }
|
||||
offset: EmuRect
|
||||
/** cNvPr name (defaults to a filename-style name) */
|
||||
name?: string
|
||||
}
|
||||
|
||||
/** Insert audio/video: media/poster parts + dual relationships + <p:pic> fragment, append + reparse. */
|
||||
export function addMedia(
|
||||
opened: OpenedPptx,
|
||||
slideIndex: number,
|
||||
opts: NewMediaOptions,
|
||||
): { slide: Slide; elementId: string } | null {
|
||||
const slide = opened.deck.slides[slideIndex]
|
||||
if (!slide) return null
|
||||
const ext = opts.ext.toLowerCase()
|
||||
const mime = MEDIA_MIME[ext]
|
||||
if (!mime) return null
|
||||
|
||||
// 1) media part + Content_Types
|
||||
const mediaPath = newMediaPart(opened, 'media', ext, opts.bytes)
|
||||
ensureDefaultContentType(opened, ext, mime)
|
||||
|
||||
// 2) Poster frame part (solid color by default)
|
||||
const poster = opts.poster ?? {
|
||||
bytes: solidPng(16, 9, opts.kind === 'video' ? [38, 38, 44] : [240, 240, 244]),
|
||||
ext: 'png',
|
||||
}
|
||||
const posterExt = poster.ext.toLowerCase()
|
||||
const posterPath = newMediaPart(opened, 'image', posterExt, poster.bytes)
|
||||
ensureDefaultContentType(
|
||||
opened,
|
||||
posterExt,
|
||||
posterExt === 'jpg' || posterExt === 'jpeg' ? 'image/jpeg' : 'image/png',
|
||||
)
|
||||
|
||||
// 3) Three relationships: poster image + legacy video/audio + p14 media
|
||||
const mediaTarget = `../media/${mediaPath.split('/').pop()}`
|
||||
const [ridPoster, ridLegacy, ridMedia] = appendRels(opened, slide, [
|
||||
{ type: IMAGE_REL_TYPE, target: `../media/${posterPath.split('/').pop()}` },
|
||||
{ type: opts.kind === 'video' ? VIDEO_REL_TYPE : AUDIO_REL_TYPE, target: mediaTarget },
|
||||
{ type: MEDIA_REL_TYPE, target: mediaTarget },
|
||||
]) as [string, string, string]
|
||||
|
||||
// 4) <p:pic> fragment (videoFile/audioFile + p14:media extension hung on nvPr)
|
||||
const id = nextCNvPrId(slide)
|
||||
const name = opts.name ?? `${opts.kind === 'video' ? 'Video' : 'Audio'} ${id}`
|
||||
const fileTag = opts.kind === 'video' ? 'a:videoFile' : 'a:audioFile'
|
||||
const o = opts.offset
|
||||
const xml =
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}"/>` +
|
||||
'<p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr>' +
|
||||
`<p:nvPr><${fileTag} xmlns:r="${R_NS}" r:link="${ridLegacy}"/>` +
|
||||
`<p:extLst><p:ext uri="${MEDIA_EXT_URI}">` +
|
||||
`<p14:media xmlns:p14="${P14_NS}" xmlns:r="${R_NS}" r:embed="${ridMedia}"/>` +
|
||||
'</p:ext></p:extLst></p:nvPr></p:nvPicPr>' +
|
||||
`<p:blipFill><a:blip r:embed="${ridPoster}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
|
||||
`<p:spPr><a:xfrm><a:off x="${o.x}" y="${o.y}"/><a:ext cx="${o.cx}" cy="${o.cy}"/></a:xfrm>` +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>'
|
||||
|
||||
const r = appendRawElements(opened, slideIndex, [xml])
|
||||
return r ? { slide: r.slide, elementId: r.elementIds[r.elementIds.length - 1]! } : null
|
||||
}
|
||||
|
||||
// ── 3D models (simplified) ─────────────────────────────────────────────
|
||||
|
||||
export interface NewModel3dOptions {
|
||||
bytes: Uint8Array
|
||||
/** glb/gltf */
|
||||
ext: string
|
||||
/** Poster image (dark gray placeholder by default) */
|
||||
poster?: { bytes: Uint8Array; ext: string }
|
||||
offset: EmuRect
|
||||
name?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed a 3D model: model bytes go into the package (PowerPoint preserves unknown
|
||||
* parts) + a poster placeholder image element; descr records
|
||||
* `aislides-3d:{partPath}` for recognition on reopen. No am3d extension is written.
|
||||
*/
|
||||
export function addModel3d(
|
||||
opened: OpenedPptx,
|
||||
slideIndex: number,
|
||||
opts: NewModel3dOptions,
|
||||
): { slide: Slide; elementId: string } | null {
|
||||
const slide = opened.deck.slides[slideIndex]
|
||||
if (!slide) return null
|
||||
const ext = opts.ext.toLowerCase()
|
||||
const mime = MEDIA_MIME[ext]
|
||||
if (!mime) return null
|
||||
|
||||
const modelPath = newMediaPart(opened, 'media', ext, opts.bytes)
|
||||
ensureDefaultContentType(opened, ext, mime)
|
||||
|
||||
const poster = opts.poster ?? { bytes: solidPng(16, 9, [58, 58, 66]), ext: 'png' }
|
||||
const posterExt = poster.ext.toLowerCase()
|
||||
const posterPath = newMediaPart(opened, 'image', posterExt, poster.bytes)
|
||||
ensureDefaultContentType(
|
||||
opened,
|
||||
posterExt,
|
||||
posterExt === 'jpg' || posterExt === 'jpeg' ? 'image/jpeg' : 'image/png',
|
||||
)
|
||||
|
||||
const [ridPoster] = appendRels(opened, slide, [
|
||||
{ type: IMAGE_REL_TYPE, target: `../media/${posterPath.split('/').pop()}` },
|
||||
]) as [string]
|
||||
|
||||
const id = nextCNvPrId(slide)
|
||||
const name = opts.name ?? `3D Model ${id}`
|
||||
const o = opts.offset
|
||||
const xml =
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}" descr="${escapeXmlAttr(`aislides-3d:${modelPath}`)}"/>` +
|
||||
'<p:cNvPicPr/><p:nvPr/></p:nvPicPr>' +
|
||||
`<p:blipFill><a:blip r:embed="${ridPoster}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
|
||||
`<p:spPr><a:xfrm><a:off x="${o.x}" y="${o.y}"/><a:ext cx="${o.cx}" cy="${o.cy}"/></a:xfrm>` +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>'
|
||||
|
||||
const r = appendRawElements(opened, slideIndex, [xml])
|
||||
return r ? { slide: r.slide, elementId: r.elementIds[r.elementIds.length - 1]! } : null
|
||||
}
|
||||
|
||||
/** Check whether a picture element is a 3D model placeholder (for render-layer badges). */
|
||||
export function model3dPartOf(el: { descr?: string }): string | null {
|
||||
const m = el.descr && /^aislides-3d:(.+)$/.exec(el.descr)
|
||||
return m ? m[1]! : null
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* Speaker notes (notesSlide) read/write — archive surgery, same approach as
|
||||
* duplicateSlide.
|
||||
*
|
||||
* - Read: slide rels → notesSlide part → body placeholder <a:t> text (\n-separated).
|
||||
* - Write: patch the existing notesSlide's body txBody; if there is no notesSlide,
|
||||
* create one (creating a notesMaster too if needed and registering it in
|
||||
* presentation.xml).
|
||||
* All changes land in archive.entries: savePptx persists automatically, and the
|
||||
* main process's snapshot-style undo (shallow copy of entries) covers them.
|
||||
*/
|
||||
import type { OpenedPptx } from './index'
|
||||
import { relsPathFor, resolveTarget, type PackageArchive } from './zip'
|
||||
import { escapeXmlText } from './xml-utils'
|
||||
|
||||
const XMLDECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
const NS_A = 'http://schemas.openxmlformats.org/drawingml/2006/main'
|
||||
const NS_R = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
|
||||
const NS_P = 'http://schemas.openxmlformats.org/presentationml/2006/main'
|
||||
|
||||
const REL_BASE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
|
||||
const NOTES_SLIDE_REL = `${REL_BASE}/notesSlide`
|
||||
const NOTES_MASTER_REL = `${REL_BASE}/notesMaster`
|
||||
const SLIDE_REL = `${REL_BASE}/slide`
|
||||
const THEME_REL = `${REL_BASE}/theme`
|
||||
|
||||
const NOTES_SLIDE_CT = 'application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml'
|
||||
const NOTES_MASTER_CT = 'application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml'
|
||||
|
||||
function setEntry(archive: PackageArchive, path: string, xml: string): void {
|
||||
archive.entries.set(path, Buffer.from(xml, 'utf8'))
|
||||
}
|
||||
|
||||
/** Unescape XML text (for reading <a:t>). */
|
||||
export function unescapeXml(s: string): string {
|
||||
return s
|
||||
.replace(/&#x([0-9a-fA-F]+);/g, (_m, h: string) => String.fromCodePoint(parseInt(h, 16)))
|
||||
.replace(/&#(\d+);/g, (_m, d: string) => String.fromCodePoint(Number(d)))
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, '&')
|
||||
}
|
||||
|
||||
/** Path of the slide's notesSlide part (null if there is no notes slide). */
|
||||
export function notesPathForSlide(archive: PackageArchive, slidePath: string): string | null {
|
||||
for (const rel of archive.readRels(slidePath).values()) {
|
||||
if (rel.type === NOTES_SLIDE_REL) return resolveTarget(slidePath, rel.target)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Find the body placeholder sp block in the notesSlide xml. */
|
||||
function findBodySp(xml: string): { xml: string; start: number; end: number } | null {
|
||||
for (const m of xml.matchAll(/<p:sp>[\s\S]*?<\/p:sp>/g)) {
|
||||
if (/<p:ph\b[^>]*type="body"/.test(m[0])) {
|
||||
return { xml: m[0], start: m.index!, end: m.index! + m[0].length }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Read notes as plain text (body placeholder paragraphs joined by \n); '' if none. */
|
||||
export function getSlideNotes(archive: PackageArchive, slidePath: string): string {
|
||||
const notesPath = notesPathForSlide(archive, slidePath)
|
||||
if (!notesPath) return ''
|
||||
const xml = archive.readText(notesPath)
|
||||
if (!xml) return ''
|
||||
const body = findBodySp(xml)
|
||||
if (!body) return ''
|
||||
const tx = /<p:txBody>([\s\S]*?)<\/p:txBody>/.exec(body.xml)?.[1]
|
||||
if (!tx) return ''
|
||||
const paras = [...tx.matchAll(/<a:p>([\s\S]*?)<\/a:p>/g)].map((p) =>
|
||||
[...p[1]!.matchAll(/<a:t>([\s\S]*?)<\/a:t>/g)].map((t) => unescapeXml(t[1]!)).join(''),
|
||||
)
|
||||
// Drop trailing empty paragraphs (PowerPoint templates often carry an empty placeholder paragraph)
|
||||
while (paras.length && paras[paras.length - 1] === '') paras.pop()
|
||||
return paras.join('\n')
|
||||
}
|
||||
|
||||
/** text (\n-separated) → notes txBody. */
|
||||
function buildNotesTxBody(text: string): string {
|
||||
const lines = text.split('\n')
|
||||
const paras =
|
||||
lines.every((l) => l === '')
|
||||
? '<a:p><a:endParaRPr lang="zh-CN"/></a:p>'
|
||||
: lines
|
||||
.map((line) =>
|
||||
line === ''
|
||||
? '<a:p><a:endParaRPr lang="zh-CN"/></a:p>'
|
||||
: `<a:p><a:r><a:rPr lang="zh-CN" dirty="0"/><a:t>${escapeXmlText(line)}</a:t></a:r></a:p>`,
|
||||
)
|
||||
.join('')
|
||||
return `<p:txBody><a:bodyPr/><a:lstStyle/>${paras}</p:txBody>`
|
||||
}
|
||||
|
||||
const NOTES_BODY_SP_OPEN =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="3" name="Notes Placeholder"/>' +
|
||||
'<p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr>' +
|
||||
'<p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/>'
|
||||
|
||||
/**
|
||||
* Write notes (overwrite): patch the existing notesSlide's body txBody;
|
||||
* if there is no notesSlide, create the part (with a notesMaster if needed).
|
||||
*/
|
||||
export function setSlideNotes(opened: OpenedPptx, slideIndex: number, text: string): boolean {
|
||||
const slide = opened.deck.slides[slideIndex]
|
||||
if (!slide) return false
|
||||
const { archive } = opened
|
||||
const notesPath = notesPathForSlide(archive, slide.path) ?? createNotesSlide(opened, slide.path)
|
||||
if (!notesPath) return false
|
||||
const xml = archive.readText(notesPath)
|
||||
if (!xml) return false
|
||||
|
||||
const txBody = buildNotesTxBody(text)
|
||||
const body = findBodySp(xml)
|
||||
let next: string
|
||||
if (body) {
|
||||
const patched = body.xml.replace(/<p:txBody>[\s\S]*?<\/p:txBody>/, () => txBody)
|
||||
next = xml.slice(0, body.start) + patched + xml.slice(body.end)
|
||||
} else {
|
||||
next = xml.replace('</p:spTree>', `${NOTES_BODY_SP_OPEN}${txBody}</p:sp></p:spTree>`)
|
||||
}
|
||||
setEntry(archive, notesPath, next)
|
||||
return true
|
||||
}
|
||||
|
||||
/** Add an Override to [Content_Types].xml (skipped if already present). */
|
||||
function addContentTypeOverride(archive: PackageArchive, partPath: string, contentType: string): void {
|
||||
const ctPath = '[Content_Types].xml'
|
||||
const ct = archive.readText(ctPath)
|
||||
if (!ct || ct.includes(`PartName="/${partPath}"`)) return
|
||||
setEntry(
|
||||
archive,
|
||||
ctPath,
|
||||
ct.replace('</Types>', `<Override PartName="/${partPath}" ContentType="${contentType}"/></Types>`),
|
||||
)
|
||||
}
|
||||
|
||||
/** Append a relationship to a part's rels, creating the rels file if missing. Returns the new rId. */
|
||||
export function appendRelationship(
|
||||
archive: PackageArchive,
|
||||
partPath: string,
|
||||
type: string,
|
||||
target: string,
|
||||
): string {
|
||||
const relsPath = relsPathFor(partPath)
|
||||
let xml =
|
||||
archive.readText(relsPath) ??
|
||||
XMLDECL +
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>'
|
||||
let maxRid = 0
|
||||
for (const m of xml.matchAll(/Id="rId(\d+)"/g)) maxRid = Math.max(maxRid, Number(m[1]))
|
||||
const rid = `rId${maxRid + 1}`
|
||||
xml = xml.replace(
|
||||
'</Relationships>',
|
||||
`<Relationship Id="${rid}" Type="${type}" Target="${target}"/></Relationships>`,
|
||||
)
|
||||
setEntry(archive, relsPath, xml)
|
||||
return rid
|
||||
}
|
||||
|
||||
/** Ensure a notesMaster exists and return its part path. Created and registered in the presentation if missing. */
|
||||
function ensureNotesMaster(archive: PackageArchive): string | null {
|
||||
for (const path of archive.entries.keys()) {
|
||||
if (/^ppt\/notesMasters\/notesMaster\d+\.xml$/.test(path)) return path
|
||||
}
|
||||
const path = 'ppt/notesMasters/notesMaster1.xml'
|
||||
const emptyTree =
|
||||
'<p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
|
||||
'<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/>' +
|
||||
'<a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr></p:spTree>'
|
||||
const xml =
|
||||
XMLDECL +
|
||||
`<p:notesMaster xmlns:a="${NS_A}" xmlns:r="${NS_R}" xmlns:p="${NS_P}">` +
|
||||
`<p:cSld>${emptyTree}</p:cSld>` +
|
||||
'<p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2"' +
|
||||
' accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>' +
|
||||
'</p:notesMaster>'
|
||||
setEntry(archive, path, xml)
|
||||
addContentTypeOverride(archive, path, NOTES_MASTER_CT)
|
||||
// rels: reuse an existing theme part (valid: multiple parts may point to the same theme)
|
||||
const theme = [...archive.entries.keys()].find((p) => /^ppt\/theme\/theme\d+\.xml$/.test(p))
|
||||
if (theme) appendRelationship(archive, path, THEME_REL, `../${theme.slice(4)}`)
|
||||
// Register notesMasterIdLst in presentation.xml
|
||||
const presPath = 'ppt/presentation.xml'
|
||||
const pres = archive.readText(presPath)
|
||||
if (pres && !pres.includes('<p:notesMasterIdLst>')) {
|
||||
const rid = appendRelationship(archive, presPath, NOTES_MASTER_REL, 'notesMasters/notesMaster1.xml')
|
||||
const lst = `<p:notesMasterIdLst><p:notesMasterId r:id="${rid}"/></p:notesMasterIdLst>`
|
||||
const next = pres.includes('</p:sldMasterIdLst>')
|
||||
? pres.replace('</p:sldMasterIdLst>', `</p:sldMasterIdLst>${lst}`)
|
||||
: pres.replace('<p:sldIdLst>', `${lst}<p:sldIdLst>`)
|
||||
setEntry(archive, presPath, next)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
/** Create an empty notesSlide for a slide (part + rels + CT + slide rels); returns the part path. */
|
||||
function createNotesSlide(opened: OpenedPptx, slidePath: string): string | null {
|
||||
const { archive } = opened
|
||||
if (!ensureNotesMaster(archive)) return null
|
||||
|
||||
let maxNum = 0
|
||||
for (const path of archive.entries.keys()) {
|
||||
const m = /^ppt\/notesSlides\/notesSlide(\d+)\.xml$/.exec(path)
|
||||
if (m) maxNum = Math.max(maxNum, Number(m[1]))
|
||||
}
|
||||
const notesPath = `ppt/notesSlides/notesSlide${maxNum + 1}.xml`
|
||||
|
||||
const xml =
|
||||
XMLDECL +
|
||||
`<p:notes xmlns:a="${NS_A}" xmlns:r="${NS_R}" xmlns:p="${NS_P}">` +
|
||||
'<p:cSld><p:spTree>' +
|
||||
'<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
|
||||
'<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/>' +
|
||||
'<a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>' +
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="2" name="Slide Image Placeholder"/>' +
|
||||
'<p:cNvSpPr><a:spLocks noGrp="1" noRot="1" noChangeAspect="1"/></p:cNvSpPr>' +
|
||||
'<p:nvPr><p:ph type="sldImg"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>' +
|
||||
NOTES_BODY_SP_OPEN +
|
||||
'<p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="zh-CN"/></a:p></p:txBody></p:sp>' +
|
||||
'</p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:notes>'
|
||||
setEntry(archive, notesPath, xml)
|
||||
addContentTypeOverride(archive, notesPath, NOTES_SLIDE_CT)
|
||||
|
||||
// notesSlide rels: notesMaster + owning slide
|
||||
const master = [...archive.entries.keys()].find((p) => /^ppt\/notesMasters\/notesMaster\d+\.xml$/.test(p))!
|
||||
appendRelationship(archive, notesPath, NOTES_MASTER_REL, `../${master.slice(4)}`)
|
||||
appendRelationship(archive, notesPath, SLIDE_REL, `../${slidePath.slice(4)}`)
|
||||
|
||||
// slide rels: point to the new notesSlide
|
||||
appendRelationship(archive, slidePath, NOTES_SLIDE_REL, `../${notesPath.slice(4)}`)
|
||||
return notesPath
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,400 @@
|
||||
/**
|
||||
* Placeholder geometry inheritance (Phase 2, filling a gap left by Phase 1).
|
||||
*
|
||||
* Placeholder shapes on a slide (<p:ph>) often omit their own <a:xfrm>; geometry
|
||||
* must be backfilled from the slideLayout per OOXML inheritance rules, and from
|
||||
* the slideMaster when the layout lacks it.
|
||||
*
|
||||
* Matching rules (aligned with PowerPoint / pptxtojson):
|
||||
* 1. exact (type, idx) match first;
|
||||
* 2. then by idx (when type is missing/inconsistent);
|
||||
* 3. then by type;
|
||||
* 4. body-like types (body/subTitle, etc.) fall back to each other, as do
|
||||
* title/ctrTitle.
|
||||
*
|
||||
* Read-only: layout/master geometry is used only for render inheritance, never
|
||||
* written back to the original pptx.
|
||||
*/
|
||||
import { XMLParser } from 'fast-xml-parser'
|
||||
import type { Transform, TextAlign } from './types'
|
||||
import { type Theme, resolveFontRef } from './theme'
|
||||
import { resolveColorNode } from './color'
|
||||
import { asXmlNode, xmlArray, type XmlNode } from './xml-utils'
|
||||
|
||||
const phParser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
attributeNamePrefix: '@_',
|
||||
isArray: (name) => ['p:sp'].includes(name),
|
||||
})
|
||||
|
||||
/** Default run/paragraph style for one indent level (from lstStyle's lvlNpPr/defRPr). */
|
||||
export interface LevelTextStyle {
|
||||
/** Font size (pt) */
|
||||
fontSize?: number
|
||||
bold?: boolean
|
||||
italic?: boolean
|
||||
color?: string
|
||||
latinFont?: string
|
||||
eaFont?: string
|
||||
csFont?: string
|
||||
align?: TextAlign
|
||||
/** Bullet default (master bodyStyle levels commonly use buChar '•') */
|
||||
bullet?: { type: 'none' | 'char' | 'number'; char?: string }
|
||||
/** Paragraph left indent (EMU) */
|
||||
marL?: number
|
||||
/** First-line indent (EMU, negative = hanging) */
|
||||
indent?: number
|
||||
/** Line/paragraph spacing defaults (lnSpc/spcBef/spcAft from master txStyles; source of inherited line spacing) */
|
||||
lineHeight?: number
|
||||
lineExact?: number
|
||||
spaceBefore?: number
|
||||
spaceAfter?: number
|
||||
spaceBeforePct?: number
|
||||
spaceAfterPct?: number
|
||||
}
|
||||
|
||||
/** Default styles for the 9 levels (index = level, 0-based). */
|
||||
export interface TextStyleLevels {
|
||||
levels: Array<LevelTextStyle | undefined>
|
||||
}
|
||||
|
||||
/** master <p:txStyles>: the title/body/other families. */
|
||||
export interface MasterTextStyles {
|
||||
title?: TextStyleLevels
|
||||
body?: TextStyleLevels
|
||||
other?: TextStyleLevels
|
||||
}
|
||||
|
||||
export interface PlaceholderGeom {
|
||||
type: string // ph type, normalized to 'body' when missing
|
||||
idx: string // ph idx, '' when missing
|
||||
transform: Transform | null
|
||||
/** Default text style from this placeholder txBody's <a:lstStyle> */
|
||||
textStyle?: TextStyleLevels
|
||||
}
|
||||
|
||||
/** Placeholder geometry table for one layer (layout or master). */
|
||||
export interface PlaceholderMap {
|
||||
entries: PlaceholderGeom[]
|
||||
}
|
||||
|
||||
const TITLE_TYPES = new Set(['title', 'ctrTitle'])
|
||||
const BODY_TYPES = new Set(['body', 'subTitle', 'obj', ''])
|
||||
|
||||
function parseXfrmNode(xfrmRaw: unknown): Transform | null {
|
||||
if (!xfrmRaw) return null
|
||||
const xfrm = asXmlNode(xfrmRaw)
|
||||
const offRaw = xfrm['a:off']
|
||||
const extRaw = xfrm['a:ext']
|
||||
if (!offRaw && !extRaw) return null
|
||||
const off = asXmlNode(offRaw)
|
||||
const ext = asXmlNode(extRaw)
|
||||
return {
|
||||
offset: {
|
||||
x: offRaw ? parseInt(String(off['@_x']), 10) || 0 : 0,
|
||||
y: offRaw ? parseInt(String(off['@_y']), 10) || 0 : 0,
|
||||
cx: extRaw ? parseInt(String(ext['@_cx']), 10) || 0 : 0,
|
||||
cy: extRaw ? parseInt(String(ext['@_cy']), 10) || 0 : 0,
|
||||
},
|
||||
rot: xfrm['@_rot'] ? parseInt(String(xfrm['@_rot']), 10) || 0 : 0,
|
||||
flipH: xfrm['@_flipH'] === '1' || xfrm['@_flipH'] === 'true',
|
||||
flipV: xfrm['@_flipV'] === '1' || xfrm['@_flipV'] === 'true',
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the placeholder geometry table + lstStyle text style defaults from a
|
||||
* layout/master's full XML. Collects shapes that carry <p:ph> and at least one of
|
||||
* <a:xfrm> or <a:lstStyle>.
|
||||
*/
|
||||
export function parsePlaceholderMap(layoutOrMasterXml: string, theme?: Theme): PlaceholderMap {
|
||||
const entries: PlaceholderGeom[] = []
|
||||
let doc: XmlNode
|
||||
try {
|
||||
doc = asXmlNode(phParser.parse(layoutOrMasterXml))
|
||||
} catch {
|
||||
return { entries }
|
||||
}
|
||||
// Path: p:sldLayout / p:sldMaster → p:cSld → p:spTree → p:sp[]
|
||||
const root = asXmlNode(doc['p:sldLayout'] ?? doc['p:sldMaster'])
|
||||
const spTreeRaw = asXmlNode(root['p:cSld'])['p:spTree']
|
||||
if (!spTreeRaw) return { entries }
|
||||
const spTree = asXmlNode(spTreeRaw)
|
||||
for (const sp of xmlArray(spTree['p:sp'])) {
|
||||
const phRaw = asXmlNode(asXmlNode(sp['p:nvSpPr'])['p:nvPr'])['p:ph']
|
||||
if (!phRaw) continue
|
||||
const ph = asXmlNode(phRaw)
|
||||
const type = String(ph['@_type'] ?? 'body')
|
||||
const idx = ph['@_idx'] != null ? String(ph['@_idx']) : ''
|
||||
const transform = parseXfrmNode(asXmlNode(sp['p:spPr'])['a:xfrm'])
|
||||
const textStyle = parseLstStyleLevels(asXmlNode(sp['p:txBody'])['a:lstStyle'], theme)
|
||||
if (!transform && !textStyle) continue
|
||||
entries.push({ type, idx, transform, ...(textStyle ? { textStyle } : {}) })
|
||||
}
|
||||
return { entries }
|
||||
}
|
||||
|
||||
// ── lstStyle / txStyles text style parsing ───────────────────────────
|
||||
|
||||
const ALIGN_MAP: Record<string, TextAlign> = {
|
||||
l: 'left',
|
||||
ctr: 'center',
|
||||
r: 'right',
|
||||
just: 'justify',
|
||||
}
|
||||
|
||||
/** fast-xml-parser does not decode numeric character references in attributes (• etc.); done here. */
|
||||
function decodeAttrCharRefs(s: string): string {
|
||||
return s
|
||||
.replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCodePoint(parseInt(h, 16)))
|
||||
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(parseInt(d, 10)))
|
||||
}
|
||||
|
||||
/** <a:spcPct val="150000"/> → 150 (%). */
|
||||
function spcPctVal(node: unknown): number | undefined {
|
||||
const v = asXmlNode(asXmlNode(node)['a:spcPct'])['@_val']
|
||||
return v != null ? parseInt(String(v), 10) / 1000 : undefined
|
||||
}
|
||||
|
||||
/** <a:spcPts val="2400"/> → 24 (pt). */
|
||||
function spcPtsVal(node: unknown): number | undefined {
|
||||
const v = asXmlNode(asXmlNode(node)['a:spcPts'])['@_val']
|
||||
return v != null ? parseInt(String(v), 10) / 100 : undefined
|
||||
}
|
||||
|
||||
/** Typeface attribute of e.g. <a:latin typeface="…"/> as a string (undefined when absent). */
|
||||
function typefaceAttr(node: unknown): string | undefined {
|
||||
const v = asXmlNode(node)['@_typeface']
|
||||
return v != null ? String(v) : undefined
|
||||
}
|
||||
|
||||
/** <a:lvlNpPr> (including defRPr) → LevelTextStyle. */
|
||||
function parseLvlPPr(pPrRaw: unknown, theme?: Theme): LevelTextStyle | undefined {
|
||||
if (!pPrRaw || typeof pPrRaw !== 'object') return undefined
|
||||
const pPr = asXmlNode(pPrRaw)
|
||||
const out: LevelTextStyle = {}
|
||||
const algn = String(pPr['@_algn'] ?? '')
|
||||
if (algn && ALIGN_MAP[algn]) out.align = ALIGN_MAP[algn]
|
||||
const lineHeight = spcPctVal(pPr['a:lnSpc'])
|
||||
const lineExact = spcPtsVal(pPr['a:lnSpc'])
|
||||
if (lineHeight != null) out.lineHeight = lineHeight
|
||||
if (lineExact != null) out.lineExact = lineExact
|
||||
const spcBef = pPr['a:spcBef']
|
||||
const spcAft = pPr['a:spcAft']
|
||||
if (spcPtsVal(spcBef) != null) out.spaceBefore = spcPtsVal(spcBef)
|
||||
if (spcPctVal(spcBef) != null) out.spaceBeforePct = spcPctVal(spcBef)
|
||||
if (spcPtsVal(spcAft) != null) out.spaceAfter = spcPtsVal(spcAft)
|
||||
if (spcPctVal(spcAft) != null) out.spaceAfterPct = spcPctVal(spcAft)
|
||||
// Bullet + indent defaults (a body placeholder's bullets mostly come from here)
|
||||
const buChar = asXmlNode(pPr['a:buChar'])['@_char']
|
||||
if (pPr['a:buNone'] !== undefined) out.bullet = { type: 'none' }
|
||||
else if (buChar != null) {
|
||||
out.bullet = { type: 'char', char: decodeAttrCharRefs(String(buChar)) }
|
||||
} else if (pPr['a:buAutoNum']) out.bullet = { type: 'number' }
|
||||
if (pPr['@_marL'] != null) {
|
||||
const v = parseInt(String(pPr['@_marL']), 10)
|
||||
if (!Number.isNaN(v)) out.marL = v
|
||||
}
|
||||
if (pPr['@_indent'] != null) {
|
||||
const v = parseInt(String(pPr['@_indent']), 10)
|
||||
if (!Number.isNaN(v)) out.indent = v
|
||||
}
|
||||
const defRPrRaw = pPr['a:defRPr']
|
||||
if (defRPrRaw && typeof defRPrRaw === 'object') {
|
||||
const defRPr = asXmlNode(defRPrRaw)
|
||||
if (defRPr['@_sz']) out.fontSize = parseInt(String(defRPr['@_sz']), 10) / 100
|
||||
if (defRPr['@_b'] != null) out.bold = defRPr['@_b'] === '1' || defRPr['@_b'] === 'true'
|
||||
if (defRPr['@_i'] != null) out.italic = defRPr['@_i'] === '1' || defRPr['@_i'] === 'true'
|
||||
const color = resolveColorNode(defRPr['a:solidFill'], theme)
|
||||
if (color) out.color = color
|
||||
const latin = resolveFontRef(typefaceAttr(defRPr['a:latin']), theme)
|
||||
if (latin) out.latinFont = latin
|
||||
const ea = resolveFontRef(typefaceAttr(defRPr['a:ea']), theme)
|
||||
if (ea) out.eaFont = ea
|
||||
const cs = resolveFontRef(typefaceAttr(defRPr['a:cs']), theme)
|
||||
if (cs) out.csFont = cs
|
||||
}
|
||||
return Object.keys(out).length ? out : undefined
|
||||
}
|
||||
|
||||
/** <a:lstStyle> (or one txStyles family) → 9-level style table. */
|
||||
export function parseLstStyleLevels(lst: unknown, theme?: Theme): TextStyleLevels | undefined {
|
||||
if (!lst || typeof lst !== 'object') return undefined
|
||||
const l = asXmlNode(lst)
|
||||
const levels: Array<LevelTextStyle | undefined> = []
|
||||
for (let i = 1; i <= 9; i++) levels[i - 1] = parseLvlPPr(l[`a:lvl${i}pPr`], theme)
|
||||
return levels.some(Boolean) ? { levels } : undefined
|
||||
}
|
||||
|
||||
/** master <p:txStyles> → default styles for the title/body/other families. */
|
||||
export function parseMasterTextStyles(masterXml: string, theme?: Theme): MasterTextStyles {
|
||||
let doc: XmlNode
|
||||
try {
|
||||
doc = asXmlNode(phParser.parse(masterXml))
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
const txRaw = asXmlNode(doc['p:sldMaster'])['p:txStyles']
|
||||
if (!txRaw) return {}
|
||||
const tx = asXmlNode(txRaw)
|
||||
return {
|
||||
...(parseLstStyleLevels(tx['p:titleStyle'], theme)
|
||||
? { title: parseLstStyleLevels(tx['p:titleStyle'], theme)! }
|
||||
: {}),
|
||||
...(parseLstStyleLevels(tx['p:bodyStyle'], theme)
|
||||
? { body: parseLstStyleLevels(tx['p:bodyStyle'], theme)! }
|
||||
: {}),
|
||||
...(parseLstStyleLevels(tx['p:otherStyle'], theme)
|
||||
? { other: parseLstStyleLevels(tx['p:otherStyle'], theme)! }
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** Find the lstStyle in a layer's map by placeholder (type, idx). Same match order as geometry inheritance. */
|
||||
function findStyleInMap(
|
||||
map: PlaceholderMap | undefined,
|
||||
type: string | undefined,
|
||||
idx: string | undefined,
|
||||
): TextStyleLevels | undefined {
|
||||
if (!map || map.entries.length === 0) return undefined
|
||||
const t = type ?? 'body'
|
||||
const i = idx ?? ''
|
||||
const styled = map.entries.filter((e) => e.textStyle)
|
||||
let hit = styled.find((e) => e.type === t && e.idx === i)
|
||||
if (!hit && i !== '') hit = styled.find((e) => e.idx === i)
|
||||
if (!hit) hit = styled.find((e) => e.type === t)
|
||||
if (!hit && TITLE_TYPES.has(t)) hit = styled.find((e) => TITLE_TYPES.has(e.type))
|
||||
if (!hit && BODY_TYPES.has(t)) hit = styled.find((e) => BODY_TYPES.has(e.type))
|
||||
return hit?.textStyle
|
||||
}
|
||||
|
||||
/**
|
||||
* Placeholder text style inheritance chain (highest priority first):
|
||||
* layout placeholder lstStyle → master placeholder lstStyle → master txStyles
|
||||
* (by ph family). The caller may prepend the slide shape's own lstStyle.
|
||||
*/
|
||||
export function placeholderStyleChain(
|
||||
layout: PlaceholderMap | undefined,
|
||||
master: PlaceholderMap | undefined,
|
||||
masterTx: MasterTextStyles | undefined,
|
||||
type: string | undefined,
|
||||
idx: string | undefined,
|
||||
): TextStyleLevels[] {
|
||||
const chain: TextStyleLevels[] = []
|
||||
const fromLayout = findStyleInMap(layout, type, idx)
|
||||
if (fromLayout) chain.push(fromLayout)
|
||||
const fromMaster = findStyleInMap(master, type, idx)
|
||||
if (fromMaster) chain.push(fromMaster)
|
||||
const t = type ?? 'body'
|
||||
const family = TITLE_TYPES.has(t)
|
||||
? masterTx?.title
|
||||
: BODY_TYPES.has(t)
|
||||
? masterTx?.body
|
||||
: masterTx?.other
|
||||
if (family) chain.push(family)
|
||||
return chain
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge one level's default style field by field along the inheritance chain
|
||||
* (earlier layers win). When a layer lacks the level, fall back to that layer's
|
||||
* lvl1 (lenient fallback).
|
||||
*/
|
||||
export function mergeTextStyleChain(
|
||||
chain: Array<TextStyleLevels | undefined>,
|
||||
level: number,
|
||||
): LevelTextStyle | undefined {
|
||||
const out: LevelTextStyle = {}
|
||||
let any = false
|
||||
for (const layer of chain) {
|
||||
if (!layer) continue
|
||||
const lvl = layer.levels[level] ?? layer.levels[0]
|
||||
if (!lvl) continue
|
||||
any = true
|
||||
if (out.fontSize == null && lvl.fontSize != null) out.fontSize = lvl.fontSize
|
||||
if (out.bold == null && lvl.bold != null) out.bold = lvl.bold
|
||||
if (out.italic == null && lvl.italic != null) out.italic = lvl.italic
|
||||
if (out.color == null && lvl.color != null) out.color = lvl.color
|
||||
if (out.latinFont == null && lvl.latinFont != null) out.latinFont = lvl.latinFont
|
||||
if (out.eaFont == null && lvl.eaFont != null) out.eaFont = lvl.eaFont
|
||||
if (out.csFont == null && lvl.csFont != null) out.csFont = lvl.csFont
|
||||
if (out.align == null && lvl.align != null) out.align = lvl.align
|
||||
if (out.bullet == null && lvl.bullet != null) out.bullet = lvl.bullet
|
||||
if (out.marL == null && lvl.marL != null) out.marL = lvl.marL
|
||||
if (out.indent == null && lvl.indent != null) out.indent = lvl.indent
|
||||
// Line/paragraph spacing inherit as attribute pairs (pct and pts are two value forms of the same lnSpc/spcBef/spcAft node)
|
||||
if (
|
||||
out.lineHeight == null &&
|
||||
out.lineExact == null &&
|
||||
(lvl.lineHeight != null || lvl.lineExact != null)
|
||||
) {
|
||||
if (lvl.lineHeight != null) out.lineHeight = lvl.lineHeight
|
||||
if (lvl.lineExact != null) out.lineExact = lvl.lineExact
|
||||
}
|
||||
if (
|
||||
out.spaceBefore == null &&
|
||||
out.spaceBeforePct == null &&
|
||||
(lvl.spaceBefore != null || lvl.spaceBeforePct != null)
|
||||
) {
|
||||
if (lvl.spaceBefore != null) out.spaceBefore = lvl.spaceBefore
|
||||
if (lvl.spaceBeforePct != null) out.spaceBeforePct = lvl.spaceBeforePct
|
||||
}
|
||||
if (
|
||||
out.spaceAfter == null &&
|
||||
out.spaceAfterPct == null &&
|
||||
(lvl.spaceAfter != null || lvl.spaceAfterPct != null)
|
||||
) {
|
||||
if (lvl.spaceAfter != null) out.spaceAfter = lvl.spaceAfter
|
||||
if (lvl.spaceAfterPct != null) out.spaceAfterPct = lvl.spaceAfterPct
|
||||
}
|
||||
}
|
||||
return any ? out : undefined
|
||||
}
|
||||
|
||||
function findInMap(
|
||||
map: PlaceholderMap | undefined,
|
||||
type: string | undefined,
|
||||
idx: string | undefined,
|
||||
): Transform | undefined {
|
||||
if (!map || map.entries.length === 0) return undefined
|
||||
const t = type ?? 'body'
|
||||
const i = idx ?? ''
|
||||
// Search only entries with geometry (pure lstStyle entries do not participate in geometry inheritance)
|
||||
const geo = map.entries.filter((e) => e.transform)
|
||||
|
||||
// 1. Exact (type, idx)
|
||||
let hit = geo.find((e) => e.type === t && e.idx === i)
|
||||
if (hit) return hit.transform!
|
||||
// 2. By idx (when idx is non-empty)
|
||||
if (i !== '') {
|
||||
hit = geo.find((e) => e.idx === i)
|
||||
if (hit) return hit.transform!
|
||||
}
|
||||
// 3. By type
|
||||
hit = geo.find((e) => e.type === t)
|
||||
if (hit) return hit.transform!
|
||||
// 4. Family fallback
|
||||
if (TITLE_TYPES.has(t)) {
|
||||
hit = geo.find((e) => TITLE_TYPES.has(e.type))
|
||||
if (hit) return hit.transform!
|
||||
}
|
||||
if (BODY_TYPES.has(t)) {
|
||||
hit = geo.find((e) => BODY_TYPES.has(e.type))
|
||||
if (hit) return hit.transform!
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve placeholder geometry: layout first, master as fallback.
|
||||
* undefined means neither layer has inheritable geometry (the render layer may
|
||||
* further fall back to a default or (0,0)).
|
||||
*/
|
||||
export function resolvePlaceholderTransform(
|
||||
layout: PlaceholderMap | undefined,
|
||||
master: PlaceholderMap | undefined,
|
||||
type: string | undefined,
|
||||
idx: string | undefined,
|
||||
): Transform | undefined {
|
||||
return findInMap(layout, type, idx) ?? findInMap(master, type, idx)
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Byte-level scanner for slideN.xml.
|
||||
*
|
||||
* Same idea as docx-engine.scanBody: never parse->serialize (that silently alters
|
||||
* untouched bytes: attribute order, self-closing form, entity encoding). Only locate
|
||||
* the exact character range of each top-level shape inside <p:spTree>
|
||||
* (p:sp / p:pic / p:graphicFrame / p:grpSp / p:cxnSp); on save, splice in new
|
||||
* fragments and copy unmodified shapes verbatim from the original substring.
|
||||
*
|
||||
* The leading <p:nvGrpSpPr> / <p:grpSpPr> inside spTree are not shapes; they go
|
||||
* into bodyPrefix.
|
||||
*/
|
||||
|
||||
export interface SpElement {
|
||||
/** tag: p:sp / p:pic / p:graphicFrame / p:grpSp / p:cxnSp */
|
||||
name: string
|
||||
/** range [start, end) in slideN.xml string */
|
||||
start: number
|
||||
end: number
|
||||
/** Raw bytes between this shape and the next non-adjacent shape (mc:AlternateContent / p:contentPart etc.), replayed verbatim on rebuild */
|
||||
gapAfter?: string
|
||||
}
|
||||
|
||||
export interface SlideScan {
|
||||
elements: SpElement[]
|
||||
/** From the start of <p:spTree> up to the first shape (spTree open tag + nvGrpSpPr/grpSpPr) */
|
||||
bodyPrefix: string
|
||||
/** From the end of the last shape to the end of the file (</p:spTree> and trailing content) */
|
||||
bodySuffix: string
|
||||
}
|
||||
|
||||
// Matches one XML tag, tolerating '>' inside attribute values.
|
||||
const TAG_RE = /<\/?(?:[^<>"']|"[^"]*"|'[^']*')*>/g
|
||||
const NAME_RE = /^<\/?\s*([A-Za-z_][\w:.-]*)/
|
||||
|
||||
const SHAPE_TAGS = new Set(['p:sp', 'p:pic', 'p:graphicFrame', 'p:grpSp', 'p:cxnSp'])
|
||||
|
||||
export function scanSlide(slideXml: string): SlideScan {
|
||||
const spTreeOpen = /<p:spTree(?:\s(?:[^<>"']|"[^"]*"|'[^']*')*)?>/.exec(slideXml)
|
||||
if (!spTreeOpen) {
|
||||
throw new Error('slide xml has no <p:spTree> element')
|
||||
}
|
||||
const scanFrom = spTreeOpen.index + spTreeOpen[0].length
|
||||
|
||||
const elements: SpElement[] = []
|
||||
TAG_RE.lastIndex = scanFrom
|
||||
let depth = 0
|
||||
let currentStart = -1
|
||||
let currentName = ''
|
||||
let match: RegExpExecArray | null
|
||||
let spTreeCloseAt = -1
|
||||
|
||||
while ((match = TAG_RE.exec(slideXml)) !== null) {
|
||||
const tag = match[0]
|
||||
if (tag.startsWith('<!--') || tag.startsWith('<![') || tag.startsWith('<?')) continue
|
||||
const isClosing = tag.startsWith('</')
|
||||
const isSelfClosing = !isClosing && tag.endsWith('/>')
|
||||
const name = NAME_RE.exec(tag)?.[1] ?? ''
|
||||
|
||||
if (isClosing) {
|
||||
if (depth === 0) {
|
||||
if (name === 'p:spTree') {
|
||||
spTreeCloseAt = match.index
|
||||
break
|
||||
}
|
||||
throw new Error(`unexpected closing tag </${name}> at spTree level`)
|
||||
}
|
||||
depth--
|
||||
if (depth === 0 && SHAPE_TAGS.has(currentName)) {
|
||||
elements.push({ name: currentName, start: currentStart, end: match.index + tag.length })
|
||||
}
|
||||
} else if (isSelfClosing) {
|
||||
if (depth === 0 && SHAPE_TAGS.has(name)) {
|
||||
elements.push({ name, start: match.index, end: match.index + tag.length })
|
||||
}
|
||||
// Self-closing top-level nvGrpSpPr / grpSpPr: not a shape, ignore (handled by prefix/suffix logic)
|
||||
} else {
|
||||
if (depth === 0) {
|
||||
currentStart = match.index
|
||||
currentName = name
|
||||
}
|
||||
depth++
|
||||
}
|
||||
}
|
||||
|
||||
if (spTreeCloseAt < 0) throw new Error('slide xml: unterminated <p:spTree>')
|
||||
|
||||
for (let i = 0; i + 1 < elements.length; i++) {
|
||||
const gap = slideXml.slice(elements[i].end, elements[i + 1].start)
|
||||
if (gap) elements[i].gapAfter = gap
|
||||
}
|
||||
|
||||
const firstShapeStart = elements.length ? elements[0].start : spTreeCloseAt
|
||||
const lastShapeEnd = elements.length ? elements[elements.length - 1].end : spTreeCloseAt
|
||||
|
||||
return {
|
||||
elements,
|
||||
bodyPrefix: slideXml.slice(0, firstShapeStart),
|
||||
bodySuffix: slideXml.slice(lastShapeEnd),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
/**
|
||||
* Section read/write — modeled after PowerPoint's "sections".
|
||||
*
|
||||
* OOXML storage: inside <p:extLst> at the end of ppt/presentation.xml:
|
||||
* <p:ext uri="{521415D9-36F7-43E2-AB2F-B90AF26B5E84}">
|
||||
* <p14:sectionLst xmlns:p14="…/powerpoint/2010/main">
|
||||
* <p14:section name="…" id="{GUID}">
|
||||
* <p14:sldIdLst><p14:sldId id="256"/>…</p14:sldIdLst>
|
||||
* </p14:section>…
|
||||
*
|
||||
* Note: a p14:sldId's id is the numeric slide id from p:sldIdLst (what PowerPoint
|
||||
* actually writes), not an rId; parsing tolerates the odd generator that writes
|
||||
* rIds by mistake.
|
||||
*
|
||||
* After slide-order changes (adding/deleting slides), section data may be stale
|
||||
* (dangling references / incomplete coverage), so every edit operation first does
|
||||
* a positional normalization: each section covers [its first slide, next
|
||||
* section's first slide), and slides before the first section count as
|
||||
* unsectioned — an intuitive rule that naturally self-heals stale
|
||||
* references.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { resolveTarget } from './zip'
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
import { unescapeXml } from './notes'
|
||||
import type { OpenedPptx } from './index'
|
||||
|
||||
export interface SectionInfo {
|
||||
/** Section GUID (with braces, PowerPoint style) */
|
||||
id: string
|
||||
name: string
|
||||
/** Indices in deck.slides of the slides in this section (in slide order) */
|
||||
slideIndices: number[]
|
||||
}
|
||||
|
||||
const PRES_PATH = 'ppt/presentation.xml'
|
||||
/** Fixed uri of the extension hosting sectionLst (defined in [MS-PPTX]) */
|
||||
const SECTION_EXT_URI = '{521415D9-36F7-43E2-AB2F-B90AF26B5E84}'
|
||||
const P14_NS = 'http://schemas.microsoft.com/office/powerpoint/2010/main'
|
||||
|
||||
/** New section GUID: uppercase with braces (the format found in pptx files). */
|
||||
function newSectionId(): string {
|
||||
return `{${randomUUID().toUpperCase()}}`
|
||||
}
|
||||
|
||||
/** Index array for [start, end). */
|
||||
function range(start: number, end: number): number[] {
|
||||
const out: number[] = []
|
||||
for (let i = start; i < end; i++) out.push(i)
|
||||
return out
|
||||
}
|
||||
|
||||
/** Ordered entries of presentation.xml sldIdLst: numeric sldId / rId / deck index. */
|
||||
interface SlideEntry {
|
||||
sldId: string
|
||||
rId: string
|
||||
deckIndex: number
|
||||
}
|
||||
|
||||
function readSlideEntries(opened: OpenedPptx): SlideEntry[] {
|
||||
const { archive, deck } = opened
|
||||
const pres = archive.readText(PRES_PATH)
|
||||
if (!pres) return []
|
||||
const inner = /<p:sldIdLst>([\s\S]*?)<\/p:sldIdLst>/.exec(pres)?.[1] ?? ''
|
||||
const rels = archive.readRels(PRES_PATH)
|
||||
const out: SlideEntry[] = []
|
||||
for (const m of inner.matchAll(/<p:sldId\b[^>]*\/>/g)) {
|
||||
const sldId = /\bid="(\d+)"/.exec(m[0])?.[1]
|
||||
const rId = /\br:id="([^"]+)"/.exec(m[0])?.[1]
|
||||
if (!sldId || !rId) continue
|
||||
const rel = rels.get(rId)
|
||||
const path = rel ? resolveTarget(PRES_PATH, rel.target) : undefined
|
||||
const deckIndex = path ? deck.slides.findIndex((s) => s.path === path) : -1
|
||||
out.push({ sldId, rId, deckIndex })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse presentation.xml's p14:sectionLst. Returns [] if there are no sections
|
||||
* (older documents). sldIds referencing deleted slides are silently skipped.
|
||||
*/
|
||||
export function getSections(opened: OpenedPptx): SectionInfo[] {
|
||||
const pres = opened.archive.readText(PRES_PATH)
|
||||
if (!pres) return []
|
||||
const lst = /<p14:sectionLst[^>]*>([\s\S]*?)<\/p14:sectionLst>/.exec(pres)?.[1]
|
||||
if (!lst) return []
|
||||
const entries = readSlideEntries(opened)
|
||||
const bySldId = new Map(entries.map((e) => [e.sldId, e.deckIndex]))
|
||||
const byRid = new Map(entries.map((e) => [e.rId, e.deckIndex]))
|
||||
const out: SectionInfo[] = []
|
||||
for (const m of lst.matchAll(/<p14:section\b([^>]*?)(?:\/>|>([\s\S]*?)<\/p14:section>)/g)) {
|
||||
const attrs = m[1] ?? ''
|
||||
const inner = m[2] ?? ''
|
||||
const name = unescapeXml(/\bname="([^"]*)"/.exec(attrs)?.[1] ?? '')
|
||||
const id = /\bid="([^"]+)"/.exec(attrs)?.[1] ?? newSectionId()
|
||||
const slideIndices: number[] = []
|
||||
for (const sm of inner.matchAll(/<p14:sldId\s[^>]*id="([^"]+)"/g)) {
|
||||
const idx = bySldId.get(sm[1]!) ?? byRid.get(sm[1]!) ?? -1
|
||||
if (idx >= 0) slideIndices.push(idx)
|
||||
}
|
||||
out.push({ id, name, slideIndices })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the section structure back into presentation.xml's extLst (created if
|
||||
* missing). With empty sections the whole sectionLst extension is removed (and
|
||||
* the extLst too if it becomes empty). Only presentation.xml is touched;
|
||||
* [Content_Types]/rels are unaffected.
|
||||
*/
|
||||
export function setSections(opened: OpenedPptx, sections: SectionInfo[]): void {
|
||||
const { archive } = opened
|
||||
const pres = archive.readText(PRES_PATH)
|
||||
if (!pres) return
|
||||
const byIndex = new Map(readSlideEntries(opened).map((e) => [e.deckIndex, e.sldId]))
|
||||
|
||||
// First remove the whole p:ext hosting the existing sectionLst; drop the extLst too if it becomes empty
|
||||
let next = pres.replace(
|
||||
/<p:ext\b[^>]*>\s*<p14:sectionLst[\s\S]*?<\/p14:sectionLst>\s*<\/p:ext>/,
|
||||
'',
|
||||
)
|
||||
next = next.replace(/<p:extLst>\s*<\/p:extLst>/, '')
|
||||
|
||||
if (sections.length) {
|
||||
const secXml = sections
|
||||
.map((s) => {
|
||||
const ids = s.slideIndices.map((i) => byIndex.get(i)).filter((v): v is string => v != null)
|
||||
const lst = ids.length
|
||||
? `<p14:sldIdLst>${ids.map((id) => `<p14:sldId id="${id}"/>`).join('')}</p14:sldIdLst>`
|
||||
: '<p14:sldIdLst/>'
|
||||
return `<p14:section name="${escapeXmlAttr(s.name)}" id="${s.id || newSectionId()}">${lst}</p14:section>`
|
||||
})
|
||||
.join('')
|
||||
const ext = `<p:ext uri="${SECTION_EXT_URI}"><p14:sectionLst xmlns:p14="${P14_NS}">${secXml}</p14:sectionLst></p:ext>`
|
||||
if (/<\/p:extLst>/.test(next)) {
|
||||
next = next.replace('</p:extLst>', `${ext}</p:extLst>`)
|
||||
} else if (/<p:extLst\/>/.test(next)) {
|
||||
next = next.replace('<p:extLst/>', `<p:extLst>${ext}</p:extLst>`)
|
||||
} else {
|
||||
next = next.replace('</p:presentation>', `<p:extLst>${ext}</p:extLst></p:presentation>`)
|
||||
}
|
||||
}
|
||||
archive.entries.set(PRES_PATH, Buffer.from(next, 'utf8'))
|
||||
}
|
||||
|
||||
/**
|
||||
* Positional normalization: each section's start = its minimum index (empty
|
||||
* sections take the next section's start), section i covers
|
||||
* [starts[i], starts[i+1]), the last section runs to total. Returns the
|
||||
* unsectioned leading slides + the normalized sections.
|
||||
*/
|
||||
export function normalizeSections(
|
||||
sections: SectionInfo[],
|
||||
total: number,
|
||||
): { lead: number[]; starts: number[]; sections: SectionInfo[] } {
|
||||
if (!sections.length) return { lead: range(0, total), starts: [], sections: [] }
|
||||
const starts = new Array<number>(sections.length)
|
||||
let nextStart = total
|
||||
for (let i = sections.length - 1; i >= 0; i--) {
|
||||
const own = sections[i]!.slideIndices.length
|
||||
? Math.min(...sections[i]!.slideIndices)
|
||||
: nextStart
|
||||
starts[i] = Math.min(own, nextStart)
|
||||
nextStart = starts[i]!
|
||||
}
|
||||
const norm = sections.map((s, i) => ({
|
||||
...s,
|
||||
slideIndices: range(starts[i]!, i + 1 < sections.length ? starts[i + 1]! : total),
|
||||
}))
|
||||
return { lead: range(0, starts[0]!), starts, sections: norm }
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a section before slide atSlideIndex (covering atSlideIndex through the end
|
||||
* of its containing section). For documents without sections: slides before
|
||||
* atSlideIndex go into an auto-created "default section".
|
||||
* Returns the updated section list; null for an invalid index.
|
||||
*/
|
||||
export function addSection(
|
||||
opened: OpenedPptx,
|
||||
atSlideIndex: number,
|
||||
name: string,
|
||||
): SectionInfo[] | null {
|
||||
const total = opened.deck.slides.length
|
||||
if (atSlideIndex < 0 || atSlideIndex >= total) return null
|
||||
const cur = getSections(opened)
|
||||
const newSec: SectionInfo = { id: newSectionId(), name, slideIndices: [] }
|
||||
let next: SectionInfo[]
|
||||
if (!cur.length) {
|
||||
next = []
|
||||
if (atSlideIndex > 0)
|
||||
next.push({
|
||||
id: newSectionId(),
|
||||
name: 'Default Section',
|
||||
slideIndices: range(0, atSlideIndex),
|
||||
})
|
||||
newSec.slideIndices = range(atSlideIndex, total)
|
||||
next.push(newSec)
|
||||
} else {
|
||||
const { starts, sections } = normalizeSections(cur, total)
|
||||
if (atSlideIndex < starts[0]!) {
|
||||
// Inserting within the unsectioned leading slides: new section covers [at, first section's start)
|
||||
newSec.slideIndices = range(atSlideIndex, starts[0]!)
|
||||
next = [newSec, ...sections]
|
||||
} else {
|
||||
// Find section g containing at, split into [g.start, at) + new section [at, g.end)
|
||||
let g = sections.length - 1
|
||||
for (let i = 0; i < sections.length; i++) {
|
||||
const end = i + 1 < sections.length ? starts[i + 1]! : total
|
||||
if (atSlideIndex >= starts[i]! && atSlideIndex < end) {
|
||||
g = i
|
||||
break
|
||||
}
|
||||
}
|
||||
const end = g + 1 < sections.length ? starts[g + 1]! : total
|
||||
newSec.slideIndices = range(atSlideIndex, end)
|
||||
const gSec = { ...sections[g]!, slideIndices: range(starts[g]!, atSlideIndex) }
|
||||
next = [...sections.slice(0, g), gSec, newSec, ...sections.slice(g + 1)]
|
||||
}
|
||||
}
|
||||
setSections(opened, next)
|
||||
return getSections(opened)
|
||||
}
|
||||
|
||||
/** Rename a section; returns null if the id does not exist. */
|
||||
export function renameSection(opened: OpenedPptx, id: string, name: string): SectionInfo[] | null {
|
||||
const cur = getSections(opened)
|
||||
const s = cur.find((x) => x.id === id)
|
||||
if (!s) return null
|
||||
s.name = name
|
||||
setSections(opened, cur)
|
||||
return getSections(opened)
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a section but keep its slides: the section's slides merge into the
|
||||
* previous section (or the next one for the first section); when no sections
|
||||
* remain the whole sectionLst is removed. Returns null if the id does not exist.
|
||||
*/
|
||||
export function removeSection(
|
||||
opened: OpenedPptx,
|
||||
id: string,
|
||||
_opts?: { keepSlides?: boolean },
|
||||
): SectionInfo[] | null {
|
||||
const total = opened.deck.slides.length
|
||||
const cur = getSections(opened)
|
||||
const i = cur.findIndex((x) => x.id === id)
|
||||
if (i < 0) return null
|
||||
const { sections } = normalizeSections(cur, total)
|
||||
const removed = sections.splice(i, 1)[0]!
|
||||
if (sections.length) {
|
||||
if (i > 0) {
|
||||
sections[i - 1]!.slideIndices = [...sections[i - 1]!.slideIndices, ...removed.slideIndices]
|
||||
} else {
|
||||
sections[0]!.slideIndices = [...removed.slideIndices, ...sections[0]!.slideIndices]
|
||||
}
|
||||
}
|
||||
setSections(opened, sections)
|
||||
return getSections(opened)
|
||||
}
|
||||
|
||||
/**
|
||||
* Move slide fromIndex to toIndex (the insertion index after removal, i.e.
|
||||
* drag-drop semantics). Keeps presentation.xml's sldIdLst order and deck.slides
|
||||
* in sync; with sections, the moved slide joins the section at the drop position
|
||||
* (a section emptied by the move stays as an empty section).
|
||||
*/
|
||||
export function moveSlide(opened: OpenedPptx, fromIndex: number, toIndex: number): boolean {
|
||||
const { deck, archive } = opened
|
||||
const total = deck.slides.length
|
||||
if (fromIndex < 0 || fromIndex >= total) return false
|
||||
const to = Math.max(0, Math.min(toIndex, total - 1))
|
||||
if (fromIndex === to) return false
|
||||
|
||||
// Before moving, label each slide with its section by position (-1 = unsectioned leading slide)
|
||||
const cur = getSections(opened)
|
||||
let labels: number[] | null = null
|
||||
if (cur.length) {
|
||||
const { sections } = normalizeSections(cur, total)
|
||||
labels = new Array<number>(total).fill(-1)
|
||||
sections.forEach((s, si) => {
|
||||
for (const i of s.slideIndices) labels![i] = si
|
||||
})
|
||||
}
|
||||
|
||||
// presentation.xml sldIdLst: move the sldId tag wholesale (id/rId travel with it)
|
||||
const pres = archive.readText(PRES_PATH)
|
||||
if (!pres) return false
|
||||
const m = /<p:sldIdLst>([\s\S]*?)<\/p:sldIdLst>/.exec(pres)
|
||||
if (!m) return false
|
||||
const tags = [...m[1]!.matchAll(/<p:sldId\b[^>]*\/>/g)].map((t) => t[0])
|
||||
if (tags.length !== total) return false
|
||||
const [tag] = tags.splice(fromIndex, 1)
|
||||
tags.splice(to, 0, tag!)
|
||||
archive.entries.set(
|
||||
PRES_PATH,
|
||||
Buffer.from(pres.replace(m[0], `<p:sldIdLst>${tags.join('')}</p:sldIdLst>`), 'utf8'),
|
||||
)
|
||||
|
||||
// Sync deck.slides
|
||||
const [slide] = deck.slides.splice(fromIndex, 1)
|
||||
deck.slides.splice(to, 0, slide!)
|
||||
|
||||
// Section membership: the moved slide adopts the label of the slide it displaces at the drop point (keeping sections contiguous), written back in the new order
|
||||
if (labels) {
|
||||
labels.splice(fromIndex, 1)
|
||||
const adopt = to < labels.length ? labels[to]! : (labels[labels.length - 1] ?? -1)
|
||||
labels.splice(to, 0, adopt)
|
||||
const rebuilt = cur.map((s, si) => ({
|
||||
...s,
|
||||
slideIndices: labels!.flatMap((l, pos) => (l === si ? [pos] : [])),
|
||||
}))
|
||||
setSections(opened, rebuilt)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a whole section up/down: swaps places with the adjacent section, keeping
|
||||
* presentation.xml's sldIdLst order and deck.slides order in sync (unsectioned
|
||||
* leading slides stay pinned at the front). Returns the updated section list.
|
||||
*/
|
||||
export function moveSection(
|
||||
opened: OpenedPptx,
|
||||
id: string,
|
||||
dir: 'up' | 'down',
|
||||
): SectionInfo[] | null {
|
||||
const { deck, archive } = opened
|
||||
const total = deck.slides.length
|
||||
const cur = getSections(opened)
|
||||
const idx = cur.findIndex((s) => s.id === id)
|
||||
if (idx < 0) return null
|
||||
const j = dir === 'up' ? idx - 1 : idx + 1
|
||||
if (j < 0 || j >= cur.length) return null
|
||||
|
||||
const { lead, sections } = normalizeSections(cur, total)
|
||||
const order = [...sections]
|
||||
;[order[idx], order[j]] = [order[j]!, order[idx]!]
|
||||
const newOldOrder = [...lead, ...order.flatMap((s) => s.slideIndices)]
|
||||
if (newOldOrder.length !== total) return null
|
||||
|
||||
// Sync presentation.xml sldIdLst order (sldId tags moved wholesale, id/rId travel with them)
|
||||
const pres = archive.readText(PRES_PATH)
|
||||
if (!pres) return null
|
||||
const m = /<p:sldIdLst>([\s\S]*?)<\/p:sldIdLst>/.exec(pres)
|
||||
if (!m) return null
|
||||
const tags = [...m[1]!.matchAll(/<p:sldId\b[^>]*\/>/g)].map((t) => t[0])
|
||||
if (tags.length !== total) return null
|
||||
const newInner = newOldOrder.map((i) => tags[i]!).join('')
|
||||
archive.entries.set(
|
||||
PRES_PATH,
|
||||
Buffer.from(pres.replace(m[0], `<p:sldIdLst>${newInner}</p:sldIdLst>`), 'utf8'),
|
||||
)
|
||||
|
||||
// Sync deck.slides order
|
||||
deck.slides = newOldOrder.map((i) => deck.slides[i]!)
|
||||
|
||||
// Recompute section indices for the new slide order and write back
|
||||
let pos = lead.length
|
||||
const rebuilt = order.map((s) => {
|
||||
const indices = range(pos, pos + s.slideIndices.length)
|
||||
pos += s.slideIndices.length
|
||||
return { ...s, slideIndices: indices }
|
||||
})
|
||||
setSections(opened, rebuilt)
|
||||
return getSections(opened)
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
/// Copying a slide between two decks. A bundle carries the slide's XML plus every
|
||||
/// package part it depends on (media, charts and their embedded workbooks, …) so
|
||||
/// the target deck can be a different file — or a different process.
|
||||
///
|
||||
/// Two things keep this simple. Relationship ids only have to be unique inside one
|
||||
/// part's .rels, so the copied slide keeps the source's rIds verbatim and its XML
|
||||
/// never needs rewriting. And the layout is not copied: the slide is re-pointed at
|
||||
/// a layout in the destination, which is what PowerPoint's "use destination theme"
|
||||
/// paste does.
|
||||
|
||||
import { PackageArchive, relsPathFor, resolveTarget, type Relationship } from './zip'
|
||||
|
||||
const LAYOUT_REL = '/slideLayout'
|
||||
const NOTES_REL = '/notesSlide'
|
||||
|
||||
export interface SlideBundleRel {
|
||||
readonly id: string
|
||||
readonly type: string
|
||||
/** absolute source path for internal targets; the raw target for external ones */
|
||||
readonly target: string
|
||||
readonly external?: boolean
|
||||
/** true for the slideLayout rel, which the destination re-points */
|
||||
readonly layout?: boolean
|
||||
}
|
||||
|
||||
/** The source layout→master→theme chain, for "keep source formatting" pastes. */
|
||||
export interface SlideBundleChain {
|
||||
readonly layoutPath: string
|
||||
readonly masterPath: string
|
||||
readonly themePath?: string
|
||||
/** the chain parts and everything they reference, base64 like `parts` */
|
||||
readonly parts: Readonly<Record<string, string>>
|
||||
readonly contentTypes: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
export interface SlideBundle {
|
||||
readonly slideXml: string
|
||||
readonly rels: readonly SlideBundleRel[]
|
||||
/** every dependency part, base64 so the bundle survives IPC and JSON */
|
||||
readonly parts: Readonly<Record<string, string>>
|
||||
/** ContentType per dependency: keyed by lower-case extension or by part path */
|
||||
readonly contentTypes: Readonly<Record<string, string>>
|
||||
/** cSld/@name of the source layout, used to find its counterpart by name */
|
||||
readonly layoutName?: string
|
||||
/** source deck's slide size, so the caller can warn about a mismatch */
|
||||
readonly slideSize?: { cx: number; cy: number }
|
||||
readonly chain?: SlideBundleChain
|
||||
}
|
||||
|
||||
function extOf(path: string): string {
|
||||
const dot = path.lastIndexOf('.')
|
||||
return dot < 0 ? '' : path.slice(dot + 1).toLowerCase()
|
||||
}
|
||||
|
||||
function overrideContentType(ct: string | null, partPath: string): string | undefined {
|
||||
if (!ct) return undefined
|
||||
const re = new RegExp(
|
||||
`<Override[^>]*PartName="/${partPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"[^>]*ContentType="([^"]+)"`,
|
||||
)
|
||||
return re.exec(ct)?.[1]
|
||||
}
|
||||
|
||||
function defaultContentType(ct: string | null, ext: string): string | undefined {
|
||||
if (!ct) return undefined
|
||||
return new RegExp(`<Default[^>]*Extension="${ext}"[^>]*ContentType="([^"]+)"`, 'i').exec(ct)?.[1]
|
||||
}
|
||||
|
||||
/** Walks a part's rel graph, collecting bytes + content types for everything reachable. */
|
||||
function collectPart(
|
||||
archive: PackageArchive,
|
||||
partPath: string,
|
||||
parts: Record<string, string>,
|
||||
contentTypes: Record<string, string>,
|
||||
): void {
|
||||
if (parts[partPath]) return
|
||||
const bytes = archive.readBytes(partPath)
|
||||
if (!bytes) return
|
||||
parts[partPath] = Buffer.from(bytes).toString('base64')
|
||||
|
||||
const ct = archive.readText('[Content_Types].xml')
|
||||
const override = overrideContentType(ct, partPath)
|
||||
if (override) contentTypes[partPath] = override
|
||||
else {
|
||||
const ext = extOf(partPath)
|
||||
const dflt = defaultContentType(ct, ext)
|
||||
if (ext && dflt) contentTypes[ext] = dflt
|
||||
}
|
||||
|
||||
const relsPath = relsPathFor(partPath)
|
||||
const relsXml = archive.readText(relsPath)
|
||||
if (!relsXml) return
|
||||
parts[relsPath] = Buffer.from(relsXml, 'utf8').toString('base64')
|
||||
for (const rel of archive.readRels(partPath).values()) {
|
||||
if (rel.targetMode === 'External') continue
|
||||
collectPart(archive, resolveTarget(partPath, rel.target), parts, contentTypes)
|
||||
}
|
||||
}
|
||||
|
||||
function layoutNameOf(archive: PackageArchive, layoutPath: string): string | undefined {
|
||||
const xml = archive.readText(layoutPath)
|
||||
return xml ? /<p:cSld[^>]*\sname="([^"]*)"/.exec(xml)?.[1] : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot a slide and its dependencies. `slideXml` is passed in so callers can
|
||||
* hand over the patched (unsaved-edits-included) XML.
|
||||
*/
|
||||
export function collectSlideBundle(
|
||||
archive: PackageArchive,
|
||||
slidePath: string,
|
||||
slideXml: string,
|
||||
): SlideBundle {
|
||||
const parts: Record<string, string> = {}
|
||||
const contentTypes: Record<string, string> = {}
|
||||
const rels: SlideBundleRel[] = []
|
||||
let layoutName: string | undefined
|
||||
|
||||
for (const rel of archive.readRels(slidePath).values()) {
|
||||
if (rel.type.endsWith(NOTES_REL)) continue
|
||||
if (rel.targetMode === 'External') {
|
||||
rels.push({ id: rel.id, type: rel.type, target: rel.target, external: true })
|
||||
continue
|
||||
}
|
||||
const absolute = resolveTarget(slidePath, rel.target)
|
||||
if (rel.type.endsWith(LAYOUT_REL)) {
|
||||
layoutName = layoutNameOf(archive, absolute)
|
||||
rels.push({ id: rel.id, type: rel.type, target: absolute, layout: true })
|
||||
continue
|
||||
}
|
||||
collectPart(archive, absolute, parts, contentTypes)
|
||||
rels.push({ id: rel.id, type: rel.type, target: absolute })
|
||||
}
|
||||
|
||||
let slideSize: { cx: number; cy: number } | undefined
|
||||
try {
|
||||
slideSize = archive.readPresentation().size
|
||||
} catch {
|
||||
/* malformed source presentation: the size is only used for a warning */
|
||||
}
|
||||
|
||||
let chain: SlideBundleChain | undefined
|
||||
const c = archive.resolveSlideChain(slidePath)
|
||||
if (c.layoutPath && c.masterPath) {
|
||||
const chainParts: Record<string, string> = {}
|
||||
const chainCT: Record<string, string> = {}
|
||||
// collectPart walks the rel graph: layout → master → theme + the master's other layouts + media
|
||||
collectPart(archive, c.layoutPath, chainParts, chainCT)
|
||||
chain = {
|
||||
layoutPath: c.layoutPath,
|
||||
masterPath: c.masterPath,
|
||||
...(c.themePath ? { themePath: c.themePath } : {}),
|
||||
parts: chainParts,
|
||||
contentTypes: chainCT,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
slideXml,
|
||||
rels,
|
||||
parts,
|
||||
contentTypes,
|
||||
layoutName,
|
||||
...(slideSize ? { slideSize } : {}),
|
||||
...(chain ? { chain } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** First `<dir>/<base><n>.<ext>` free in the target archive and not yet allocated this pass. */
|
||||
function freePath(archive: PackageArchive, sourcePath: string, taken: ReadonlySet<string>): string {
|
||||
const slash = sourcePath.lastIndexOf('/')
|
||||
const dir = sourcePath.slice(0, slash)
|
||||
const file = sourcePath.slice(slash + 1)
|
||||
const dot = file.lastIndexOf('.')
|
||||
const stem = dot < 0 ? file : file.slice(0, dot)
|
||||
const ext = dot < 0 ? '' : file.slice(dot)
|
||||
const base = /^(.*?)(\d+)$/.exec(stem)?.[1] ?? stem
|
||||
for (let n = 1; ; n += 1) {
|
||||
const candidate = `${dir}/${base}${n}${ext}`
|
||||
if (!archive.has(candidate) && !taken.has(candidate)) return candidate
|
||||
}
|
||||
}
|
||||
|
||||
function relative(fromPart: string, toPath: string): string {
|
||||
const from = fromPart.slice(0, fromPart.lastIndexOf('/')).split('/').filter(Boolean)
|
||||
const to = toPath.split('/').filter(Boolean)
|
||||
let shared = 0
|
||||
while (shared < from.length && shared < to.length && from[shared] === to[shared]) shared += 1
|
||||
return [...Array.from({ length: from.length - shared }, () => '..'), ...to.slice(shared)].join(
|
||||
'/',
|
||||
)
|
||||
}
|
||||
|
||||
function escapeAttr(value: string): string {
|
||||
return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('"', '"')
|
||||
}
|
||||
|
||||
/** All layout paths in the target, with their display names. */
|
||||
export function listLayouts(archive: PackageArchive): { path: string; name?: string }[] {
|
||||
const layouts: { path: string; name?: string }[] = []
|
||||
for (const path of archive.entries.keys()) {
|
||||
if (/^ppt\/slideLayouts\/slideLayout\d+\.xml$/.test(path)) {
|
||||
layouts.push({ path, name: layoutNameOf(archive, path) })
|
||||
}
|
||||
}
|
||||
return layouts
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a bundle's dependency parts into `archive` under fresh names and returns
|
||||
* the slide's .rels XML, with every rId preserved and the layout rel pointed at
|
||||
* `layoutPath`. The caller writes the slide part itself.
|
||||
*/
|
||||
/**
|
||||
* Writes a bag of bundled parts into `archive` under non-conflicting names,
|
||||
* rewriting each part's own rels to wherever its dependencies landed. Returns
|
||||
* the source→destination path map.
|
||||
*/
|
||||
function writeParts(
|
||||
archive: PackageArchive,
|
||||
parts: Readonly<Record<string, string>>,
|
||||
contentTypes: Readonly<Record<string, string>>,
|
||||
): Map<string, string> {
|
||||
// rels parts follow their owner, so map the owners first
|
||||
const pathMap = new Map<string, string>()
|
||||
const taken = new Set<string>()
|
||||
for (const sourcePath of Object.keys(parts)) {
|
||||
if (sourcePath.includes('/_rels/')) continue
|
||||
const dest =
|
||||
archive.has(sourcePath) || taken.has(sourcePath)
|
||||
? freePath(archive, sourcePath, taken)
|
||||
: sourcePath
|
||||
taken.add(dest)
|
||||
pathMap.set(sourcePath, dest)
|
||||
}
|
||||
|
||||
for (const [sourcePath, base64] of Object.entries(parts)) {
|
||||
if (sourcePath.includes('/_rels/')) continue
|
||||
const targetPath = pathMap.get(sourcePath)
|
||||
if (!targetPath) continue
|
||||
archive.entries.set(targetPath, new Uint8Array(Buffer.from(base64, 'base64')))
|
||||
|
||||
const sourceRels = parts[relsPathFor(sourcePath)]
|
||||
if (!sourceRels) continue
|
||||
let relsXml = Buffer.from(sourceRels, 'base64').toString('utf8')
|
||||
// rewrite this part's own targets to wherever their parts landed
|
||||
relsXml = relsXml.replaceAll(/Target="([^"]+)"/g, (whole, target: string) => {
|
||||
if (/^[a-z]+:/i.test(target)) return whole
|
||||
const absolute = resolveTarget(sourcePath, target)
|
||||
const mapped = pathMap.get(absolute)
|
||||
return mapped ? `Target="${escapeAttr(relative(targetPath, mapped))}"` : whole
|
||||
})
|
||||
archive.entries.set(relsPathFor(targetPath), new Uint8Array(Buffer.from(relsXml, 'utf8')))
|
||||
}
|
||||
|
||||
ensureContentTypes(archive, contentTypes, pathMap)
|
||||
return pathMap
|
||||
}
|
||||
|
||||
export function materializeSlideBundle(
|
||||
archive: PackageArchive,
|
||||
bundle: SlideBundle,
|
||||
slidePath: string,
|
||||
layoutPath: string,
|
||||
): string {
|
||||
const pathMap = writeParts(archive, bundle.parts, bundle.contentTypes)
|
||||
|
||||
const relLines = bundle.rels.map((rel) => {
|
||||
if (rel.layout) {
|
||||
return `<Relationship Id="${rel.id}" Type="${rel.type}" Target="${escapeAttr(relative(slidePath, layoutPath))}"/>`
|
||||
}
|
||||
if (rel.external) {
|
||||
return `<Relationship Id="${rel.id}" Type="${rel.type}" Target="${escapeAttr(rel.target)}" TargetMode="External"/>`
|
||||
}
|
||||
const mapped = pathMap.get(rel.target) ?? rel.target
|
||||
return `<Relationship Id="${rel.id}" Type="${rel.type}" Target="${escapeAttr(relative(slidePath, mapped))}"/>`
|
||||
})
|
||||
return (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
`${relLines.join('')}</Relationships>`
|
||||
)
|
||||
}
|
||||
|
||||
function ensureContentTypes(
|
||||
archive: PackageArchive,
|
||||
contentTypes: Readonly<Record<string, string>>,
|
||||
pathMap: Map<string, string>,
|
||||
): void {
|
||||
const ctPath = '[Content_Types].xml'
|
||||
let ct = archive.readText(ctPath)
|
||||
if (!ct) return
|
||||
for (const [key, contentType] of Object.entries(contentTypes)) {
|
||||
if (key.includes('/')) {
|
||||
const targetPath = pathMap.get(key)
|
||||
if (!targetPath) continue
|
||||
const override = `<Override PartName="/${targetPath}" ContentType="${contentType}"/>`
|
||||
if (!ct.includes(`PartName="/${targetPath}"`))
|
||||
ct = ct.replace('</Types>', `${override}</Types>`)
|
||||
} else if (!new RegExp(`<Default[^>]*Extension="${key}"`, 'i').test(ct)) {
|
||||
ct = ct.replace(
|
||||
'</Types>',
|
||||
`<Default Extension="${key}" ContentType="${contentType}"/></Types>`,
|
||||
)
|
||||
}
|
||||
}
|
||||
archive.entries.set(ctPath, new Uint8Array(Buffer.from(ct, 'utf8')))
|
||||
}
|
||||
|
||||
const PRES_PATH = 'ppt/presentation.xml'
|
||||
const MASTER_REL_TYPE =
|
||||
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster'
|
||||
|
||||
function partText(parts: Readonly<Record<string, string>>, path: string): string | null {
|
||||
const base64 = parts[path]
|
||||
return base64 == null ? null : Buffer.from(base64, 'base64').toString('utf8')
|
||||
}
|
||||
|
||||
/**
|
||||
* A target layout whose XML, owning master and theme are byte-identical to the
|
||||
* bundled chain — i.e. this chain was already imported (or the decks share the
|
||||
* template), so "keep source formatting" can reuse it instead of adding a master.
|
||||
*/
|
||||
function findIdenticalLayout(
|
||||
archive: PackageArchive,
|
||||
masterXml: string,
|
||||
themeXml: string | null,
|
||||
layoutXml: string,
|
||||
): string | null {
|
||||
for (const path of archive.entries.keys()) {
|
||||
if (!/^ppt\/slideMasters\/slideMaster\d+\.xml$/.test(path)) continue
|
||||
if (archive.readText(path) !== masterXml) continue
|
||||
const rels = [...archive.readRels(path).values()]
|
||||
if (themeXml != null) {
|
||||
const themeRel = rels.find((r) => r.type.endsWith('/theme'))
|
||||
const themePath = themeRel ? resolveTarget(path, themeRel.target) : null
|
||||
if (!themePath || archive.readText(themePath) !== themeXml) continue
|
||||
}
|
||||
for (const rel of rels) {
|
||||
if (!rel.type.endsWith(LAYOUT_REL)) continue
|
||||
const layoutPath = resolveTarget(path, rel.target)
|
||||
if (archive.readText(layoutPath) === layoutXml) return layoutPath
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Register an imported slideMaster with presentation.xml(.rels). */
|
||||
function registerMaster(archive: PackageArchive, masterPath: string): boolean {
|
||||
const presRelsPath = relsPathFor(PRES_PATH)
|
||||
const pres = archive.readText(PRES_PATH)
|
||||
const presRels = archive.readText(presRelsPath)
|
||||
if (!pres || !presRels || !pres.includes('</p:sldMasterIdLst>')) return false
|
||||
let maxRid = 0
|
||||
for (const m of presRels.matchAll(/Id="rId(\d+)"/g)) maxRid = Math.max(maxRid, Number(m[1]))
|
||||
const rid = `rId${maxRid + 1}`
|
||||
archive.entries.set(
|
||||
presRelsPath,
|
||||
Buffer.from(
|
||||
presRels.replace(
|
||||
'</Relationships>',
|
||||
`<Relationship Id="${rid}" Type="${MASTER_REL_TYPE}" Target="${escapeAttr(relative(PRES_PATH, masterPath))}"/></Relationships>`,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
)
|
||||
// sldMasterId ids must be unique and ≥ 2147483648
|
||||
let maxId = 2147483647
|
||||
for (const m of pres.matchAll(/<p:sldMasterId\s[^>]*id="(\d+)"/g))
|
||||
maxId = Math.max(maxId, Number(m[1]))
|
||||
archive.entries.set(
|
||||
PRES_PATH,
|
||||
Buffer.from(
|
||||
pres.replace(
|
||||
'</p:sldMasterIdLst>',
|
||||
`<p:sldMasterId id="${maxId + 1}" r:id="${rid}"/></p:sldMasterIdLst>`,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* "Keep source formatting": land the bundled layout→master→theme chain in the
|
||||
* target (registering the master) and return the layout path the pasted slide
|
||||
* should point at. Returns null when the bundle has no chain or the target's
|
||||
* presentation.xml can't take another master — callers fall back to chooseLayout.
|
||||
*/
|
||||
export function importSourceLayout(archive: PackageArchive, bundle: SlideBundle): string | null {
|
||||
const chain = bundle.chain
|
||||
if (!chain) return null
|
||||
const layoutXml = partText(chain.parts, chain.layoutPath)
|
||||
const masterXml = partText(chain.parts, chain.masterPath)
|
||||
if (layoutXml == null || masterXml == null) return null
|
||||
const themeXml = chain.themePath ? partText(chain.parts, chain.themePath) : null
|
||||
|
||||
const existing = findIdenticalLayout(archive, masterXml, themeXml, layoutXml)
|
||||
if (existing) return existing
|
||||
|
||||
const pres = archive.readText(PRES_PATH)
|
||||
if (!pres || !pres.includes('</p:sldMasterIdLst>')) return null
|
||||
const pathMap = writeParts(archive, chain.parts, chain.contentTypes)
|
||||
const masterPath = pathMap.get(chain.masterPath)
|
||||
const layoutPath = pathMap.get(chain.layoutPath)
|
||||
if (!masterPath || !layoutPath || !registerMaster(archive, masterPath)) return null
|
||||
return layoutPath
|
||||
}
|
||||
|
||||
/** The destination layout for a pasted slide: same name first, else the neighbour's. */
|
||||
export function chooseLayout(
|
||||
archive: PackageArchive,
|
||||
bundle: SlideBundle,
|
||||
neighbourSlidePath?: string,
|
||||
): string | null {
|
||||
const layouts = listLayouts(archive)
|
||||
if (bundle.layoutName) {
|
||||
const byName = layouts.find((layout) => layout.name === bundle.layoutName)
|
||||
if (byName) return byName.path
|
||||
}
|
||||
if (neighbourSlidePath) {
|
||||
const chain = archive.resolveSlideChain(neighbourSlidePath)
|
||||
if (chain.layoutPath) return chain.layoutPath
|
||||
}
|
||||
return layouts[0]?.path ?? null
|
||||
}
|
||||
|
||||
export type { Relationship }
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* SmartArt preset layout math, split from smartart.ts so the renderer can import
|
||||
* it for gallery previews without pulling in the archive/XML machinery (Node-only deps).
|
||||
*/
|
||||
import type { EmuRect } from './types'
|
||||
|
||||
export type SmartArtLayout =
|
||||
'list' | 'process' | 'cycle' | 'hierarchy' | 'pyramid' | 'matrix' | 'venn'
|
||||
|
||||
/** PowerPoint default theme accent series (colors picked in order) */
|
||||
export const SMARTART_PALETTE = [
|
||||
'4472C4',
|
||||
'ED7D31',
|
||||
'A5A5A5',
|
||||
'FFC000',
|
||||
'5B9BD5',
|
||||
'70AD47',
|
||||
'264478',
|
||||
'9E480E',
|
||||
]
|
||||
|
||||
export interface SmartArtChildShape {
|
||||
prst: string
|
||||
box: EmuRect
|
||||
text?: string
|
||||
color: string
|
||||
fontSize?: number
|
||||
/** Fill opacity 0..1 (venn overlaps); omitted = opaque */
|
||||
alpha?: number
|
||||
}
|
||||
|
||||
/** Generate child shapes per layout (child coordinate space = the group's own resolution-independent coords, in EMU). */
|
||||
export function layoutShapes(
|
||||
layout: SmartArtLayout,
|
||||
items: string[],
|
||||
cx: number,
|
||||
cy: number,
|
||||
): SmartArtChildShape[] {
|
||||
const n = Math.min(Math.max(items.length, 1), 8)
|
||||
const texts = items.slice(0, n)
|
||||
const color = (i: number) => SMARTART_PALETTE[i % SMARTART_PALETTE.length]!
|
||||
const out: SmartArtChildShape[] = []
|
||||
|
||||
if (layout === 'list') {
|
||||
const gap = Math.round(cy * 0.04)
|
||||
const h = Math.round((cy - gap * (n - 1)) / n)
|
||||
texts.forEach((t, i) => {
|
||||
out.push({
|
||||
prst: 'roundRect',
|
||||
box: { x: 0, y: i * (h + gap), cx, cy: h },
|
||||
text: t,
|
||||
color: color(i),
|
||||
})
|
||||
})
|
||||
} else if (layout === 'process') {
|
||||
// Horizontal chevron flow: adjacent arrows overlap by 1/4 to interlock
|
||||
const overlap = 0.25
|
||||
const w = Math.round(cx / (n - (n - 1) * overlap))
|
||||
const h = Math.round(cy * 0.6)
|
||||
const y = Math.round((cy - h) / 2)
|
||||
texts.forEach((t, i) => {
|
||||
out.push({
|
||||
prst: i === 0 ? 'homePlate' : 'chevron',
|
||||
box: { x: Math.round(i * w * (1 - overlap)), y, cx: w, cy: h },
|
||||
text: t,
|
||||
color: color(i),
|
||||
fontSize: 12,
|
||||
})
|
||||
})
|
||||
} else if (layout === 'cycle') {
|
||||
// n ellipses distributed around a circle
|
||||
const nodeW = Math.round(cx * 0.3)
|
||||
const nodeH = Math.round(cy * 0.26)
|
||||
const rx = (cx - nodeW) / 2
|
||||
const ry = (cy - nodeH) / 2
|
||||
texts.forEach((t, i) => {
|
||||
const ang = -Math.PI / 2 + (i * 2 * Math.PI) / n
|
||||
out.push({
|
||||
prst: 'ellipse',
|
||||
box: {
|
||||
x: Math.round(cx / 2 - nodeW / 2 + Math.cos(ang) * rx),
|
||||
y: Math.round(cy / 2 - nodeH / 2 + Math.sin(ang) * ry),
|
||||
cx: nodeW,
|
||||
cy: nodeH,
|
||||
},
|
||||
text: t,
|
||||
color: color(i),
|
||||
fontSize: 12,
|
||||
})
|
||||
})
|
||||
} else if (layout === 'pyramid') {
|
||||
// Stacked slices: triangle apex, trapezoid layers widening toward the base
|
||||
const h = Math.round(cy / n)
|
||||
texts.forEach((t, i) => {
|
||||
const w = Math.round((cx * (i + 1)) / n)
|
||||
out.push({
|
||||
prst: i === 0 ? 'triangle' : 'trapezoid',
|
||||
box: { x: Math.round((cx - w) / 2), y: i * h, cx: w, cy: h },
|
||||
text: t,
|
||||
color: color(i),
|
||||
fontSize: 12,
|
||||
})
|
||||
})
|
||||
} else if (layout === 'matrix') {
|
||||
// 2-column quadrant grid
|
||||
const gap = Math.round(Math.min(cx, cy) * 0.03)
|
||||
const rows = Math.ceil(n / 2)
|
||||
const w = Math.round((cx - gap) / 2)
|
||||
const h = Math.round((cy - gap * (rows - 1)) / rows)
|
||||
texts.forEach((t, i) => {
|
||||
out.push({
|
||||
prst: 'roundRect',
|
||||
box: { x: (i % 2) * (w + gap), y: Math.floor(i / 2) * (h + gap), cx: w, cy: h },
|
||||
text: t,
|
||||
color: color(i),
|
||||
fontSize: 12,
|
||||
})
|
||||
})
|
||||
} else if (layout === 'venn') {
|
||||
// 2..4 translucent circles overlapping around the center
|
||||
const m = Math.min(n, 4)
|
||||
const s = Math.min(cx, cy)
|
||||
const d = Math.round(s * 0.6)
|
||||
const ringR = Math.round(s * 0.2)
|
||||
const start = m === 2 ? 0 : -Math.PI / 2
|
||||
texts.slice(0, m).forEach((t, i) => {
|
||||
const ang = start + (i * 2 * Math.PI) / m
|
||||
out.push({
|
||||
prst: 'ellipse',
|
||||
box: {
|
||||
x: Math.round(cx / 2 - d / 2 + Math.cos(ang) * ringR),
|
||||
y: Math.round(cy / 2 - d / 2 + Math.sin(ang) * ringR),
|
||||
cx: d,
|
||||
cy: d,
|
||||
},
|
||||
text: t,
|
||||
color: color(i),
|
||||
fontSize: 12,
|
||||
alpha: 0.55,
|
||||
})
|
||||
})
|
||||
} else {
|
||||
// hierarchy: first item centered on top, the rest in the bottom row
|
||||
const top = texts[0]!
|
||||
const rest = texts.slice(1)
|
||||
const h = Math.round(cy * 0.32)
|
||||
const topW = Math.round(cx * 0.36)
|
||||
out.push({
|
||||
prst: 'roundRect',
|
||||
box: { x: Math.round((cx - topW) / 2), y: 0, cx: topW, cy: h },
|
||||
text: top,
|
||||
color: color(0),
|
||||
})
|
||||
if (rest.length) {
|
||||
const gap = Math.round(cx * 0.03)
|
||||
const w = Math.round((cx - gap * (rest.length - 1)) / rest.length)
|
||||
rest.forEach((t, i) => {
|
||||
// Vertical connector from top node to child (thin rect, avoids connector semantics)
|
||||
const nodeX = i * (w + gap)
|
||||
out.push({
|
||||
prst: 'rect',
|
||||
box: {
|
||||
x: Math.round(nodeX + w / 2 - cx * 0.002),
|
||||
y: h,
|
||||
cx: Math.max(Math.round(cx * 0.004), 9525),
|
||||
cy: Math.round(cy * 0.18),
|
||||
},
|
||||
color: 'A5A5A5',
|
||||
})
|
||||
out.push({
|
||||
prst: 'roundRect',
|
||||
box: { x: nodeX, y: Math.round(cy * 0.5), cx: w, cy: Math.round(cy * 0.5) },
|
||||
text: t,
|
||||
color: color(i + 1),
|
||||
fontSize: 12,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* SmartArt (simplified) — instead of writing real diagram parts (the
|
||||
* data/layout/colors/quickStyle quartet is too heavy), generate a <p:grpSp> shape
|
||||
* group from a preset layout; it is freely editable and is just a plain shape group
|
||||
* in PowerPoint.
|
||||
*
|
||||
* Supported layouts: list (vertical list) / process (horizontal flow) / cycle /
|
||||
* hierarchy / pyramid / matrix / venn.
|
||||
*/
|
||||
import type { EmuRect, Slide } from './types'
|
||||
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
|
||||
import { appendRawElements, type OpenedPptx } from './index'
|
||||
import { nextCNvPrId } from './insert'
|
||||
import { layoutShapes, type SmartArtChildShape, type SmartArtLayout } from './smartart-layout'
|
||||
|
||||
export type { SmartArtLayout } from './smartart-layout'
|
||||
|
||||
export interface NewSmartArtOptions {
|
||||
layout: SmartArtLayout
|
||||
/** Text for each node (determines node count, 1..8) */
|
||||
items: string[]
|
||||
offset: EmuRect
|
||||
}
|
||||
|
||||
/** Fragment for a single child shape (in child coordinate space). */
|
||||
function childSpXml(id: number, s: SmartArtChildShape): string {
|
||||
const para = s.text
|
||||
? `<a:p><a:pPr algn="ctr"/><a:r><a:rPr sz="${Math.round((s.fontSize ?? 14) * 100)}" b="1">` +
|
||||
'<a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill></a:rPr>' +
|
||||
`<a:t>${escapeXmlText(s.text)}</a:t></a:r></a:p>`
|
||||
: '<a:p/>'
|
||||
return (
|
||||
`<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="${escapeXmlAttr(`SmartShape ${id}`)}"/>` +
|
||||
'<p:cNvSpPr/><p:nvPr/></p:nvSpPr>' +
|
||||
`<p:spPr><a:xfrm><a:off x="${s.box.x}" y="${s.box.y}"/><a:ext cx="${s.box.cx}" cy="${s.box.cy}"/></a:xfrm>` +
|
||||
`<a:prstGeom prst="${s.prst}"><a:avLst/></a:prstGeom>` +
|
||||
`<a:solidFill><a:srgbClr val="${s.color}">` +
|
||||
(s.alpha != null && s.alpha < 1 ? `<a:alpha val="${Math.round(s.alpha * 100000)}"/>` : '') +
|
||||
'</a:srgbClr></a:solidFill></p:spPr>' +
|
||||
'<p:txBody><a:bodyPr wrap="square" anchor="ctr" rtlCol="0"><a:normAutofit/></a:bodyPr>' +
|
||||
`<a:lstStyle/>${para}</p:txBody></p:sp>`
|
||||
)
|
||||
}
|
||||
|
||||
/** Build the grpSp group fragment. */
|
||||
export function buildSmartArtXml(slide: Slide, opts: NewSmartArtOptions): string {
|
||||
const baseId = nextCNvPrId(slide)
|
||||
const o = opts.offset
|
||||
const shapes = layoutShapes(opts.layout, opts.items, o.cx, o.cy)
|
||||
const children = shapes.map((s, i) => childSpXml(baseId + 1 + i, s)).join('')
|
||||
return (
|
||||
`<p:grpSp><p:nvGrpSpPr><p:cNvPr id="${baseId}" name="SmartArt ${baseId}"/>` +
|
||||
'<p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
|
||||
`<p:grpSpPr><a:xfrm><a:off x="${o.x}" y="${o.y}"/><a:ext cx="${o.cx}" cy="${o.cy}"/>` +
|
||||
`<a:chOff x="0" y="0"/><a:chExt cx="${o.cx}" cy="${o.cy}"/></a:xfrm></p:grpSpPr>` +
|
||||
`${children}</p:grpSp>`
|
||||
)
|
||||
}
|
||||
|
||||
/** Insert SmartArt (shape-group version): append + reparse, returning the new slide and element id. */
|
||||
export function addSmartArt(
|
||||
opened: OpenedPptx,
|
||||
slideIndex: number,
|
||||
opts: NewSmartArtOptions,
|
||||
): { slide: Slide; elementId: string } | null {
|
||||
const slide = opened.deck.slides[slideIndex]
|
||||
if (!slide || !opts.items.length) return null
|
||||
const r = appendRawElements(opened, slideIndex, [buildSmartArtXml(slide, opts)])
|
||||
return r ? { slide: r.slide, elementId: r.elementIds[r.elementIds.length - 1]! } : null
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
/**
|
||||
* Table style editing — surgically patches <a:tblPr> style attributes
|
||||
* (firstRow/bandRow/tableStyleId) and each cell's <a:tcPr> fill/borders.
|
||||
*
|
||||
* Design philosophy: reuse the existing anchor.originalXml surgical-patch pattern,
|
||||
* replacing only the <a:tblPr> and <a:tcPr> nodes and keeping all other bytes
|
||||
* intact. Tables are "modeled" in this app (not passthrough), so editing is allowed.
|
||||
*/
|
||||
import type { Slide } from './types'
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
|
||||
/** Table style edit parameters (engine side of the IPC EditTableStyleOp) */
|
||||
export interface TableStyleEdit {
|
||||
/** Whole-block tblPr XML replacement applied directly (used for styleName presets) */
|
||||
tblPrXml?: string
|
||||
/** Change only the firstRow flag */
|
||||
firstRow?: boolean
|
||||
/** Change only the bandRow flag */
|
||||
bandRow?: boolean
|
||||
/** Shading color #RRGGBB or 'none' (<a:solidFill> / <a:noFill> per tc) */
|
||||
shadingColor?: string | null
|
||||
/** Border color + width (all = all borders; none = clear) */
|
||||
borderColor?: string | null
|
||||
borderWidthEmu?: number | null
|
||||
borderPreset?: 'all' | 'none' | null
|
||||
/** Clear all tcPr direct fills/borders (what PowerPoint does when applying a gallery preset; otherwise direct cell formatting hides the style) */
|
||||
clearDirectFormatting?: boolean
|
||||
/** Cells the shading/border edit applies to, as (row, tc index); undefined = whole table */
|
||||
cells?: Array<{ row: number; col: number }>
|
||||
}
|
||||
|
||||
// ── Preset styles ────────────────────────────────────────────────────
|
||||
// Color presets do not reference PowerPoint built-in style GUIDs (built-ins follow
|
||||
// the file theme's accent colors, so a "dark blue header" would come out orange in
|
||||
// an orange theme). Instead, fixed-color custom <a:tblStyle> definitions are
|
||||
// written into ppt/tableStyles.xml — the button swatch, this app's rendering, and
|
||||
// PowerPoint all agree.
|
||||
|
||||
const inLn = (tag: 'insideH' | 'insideV', color: string) =>
|
||||
`<a:${tag}><a:ln w="9525" cap="flat"><a:solidFill><a:srgbClr val="${color}"/></a:solidFill></a:ln></a:${tag}>`
|
||||
|
||||
/** Style XML for one table region (wholeTbl/band1H/firstRow…). */
|
||||
function partXml(
|
||||
tag: string,
|
||||
o: { fill?: string; text?: string; bold?: boolean; insideH?: string; insideV?: string },
|
||||
): string {
|
||||
const tx =
|
||||
o.text || o.bold
|
||||
? `<a:tcTxStyle${o.bold ? ' b="on"' : ''}>${o.text ? `<a:srgbClr val="${o.text}"/>` : ''}</a:tcTxStyle>`
|
||||
: ''
|
||||
const bdr =
|
||||
o.insideH || o.insideV
|
||||
? `<a:tcBdr>${o.insideH ? inLn('insideH', o.insideH) : ''}${o.insideV ? inLn('insideV', o.insideV) : ''}</a:tcBdr>`
|
||||
: ''
|
||||
const fill = o.fill
|
||||
? `<a:fill><a:solidFill><a:srgbClr val="${o.fill}"/></a:solidFill></a:fill>`
|
||||
: ''
|
||||
const tc = bdr || fill ? `<a:tcStyle>${bdr}${fill}</a:tcStyle>` : ''
|
||||
return `<a:${tag}>${tx}${tc}</a:${tag}>`
|
||||
}
|
||||
|
||||
/** Fixed-color banded/header style (band = alternate-row shading; header = header fill). */
|
||||
function customStyle(
|
||||
styleId: string,
|
||||
name: string,
|
||||
o: { band?: string; header?: { fill: string; text: string }; insideH?: string; whole?: string },
|
||||
): string {
|
||||
// CT_TableStyle child order: wholeTbl → band1H → … → firstRow
|
||||
return (
|
||||
`<a:tblStyle styleId="${styleId}" styleName="${name}">` +
|
||||
partXml('wholeTbl', { text: '000000', fill: o.whole, insideH: o.insideH }) +
|
||||
(o.band ? partXml('band1H', { fill: o.band }) : '') +
|
||||
partXml('firstRow', {
|
||||
bold: true,
|
||||
...(o.header ? { fill: o.header.fill, text: o.header.text } : {}),
|
||||
}) +
|
||||
'</a:tblStyle>'
|
||||
)
|
||||
}
|
||||
|
||||
const ID_ZEBRA_BLUE = '{A10FF1CE-0000-4000-9000-000000000001}'
|
||||
const ID_ZEBRA_GRAY = '{A10FF1CE-0000-4000-9000-000000000002}'
|
||||
const ID_HEADER_DARKBLUE = '{A10FF1CE-0000-4000-9000-000000000003}'
|
||||
const ID_HEADER_ORANGE = '{A10FF1CE-0000-4000-9000-000000000004}'
|
||||
const ID_NO_BORDER = '{A10FF1CE-0000-4000-9000-000000000005}'
|
||||
|
||||
export interface TableStylePreset {
|
||||
tblPrXml: string
|
||||
description: string
|
||||
/** Custom style: must first be ensured into ppt/tableStyles.xml */
|
||||
styleId?: string
|
||||
styleDefXml?: string
|
||||
/** Grid presets: add border lines to every cell directly (incl. outer frame; the style mechanism only covers inner lines) */
|
||||
border?: { color: string; widthEmu: number }
|
||||
}
|
||||
|
||||
const tblPr = (styleId: string, flags = '') =>
|
||||
`<a:tblPr${flags}><a:tableStyleId>${styleId}</a:tableStyleId></a:tblPr>`
|
||||
// Official "No Style, No Grid" GUID (we previously misused a made-up ...307D; the read side stays compatible with it)
|
||||
const NO_STYLE = '{2D5ABB26-0587-4C30-8999-92F81FD0307C}'
|
||||
|
||||
/** The 8 preset styles (keys map to the ribbon style gallery). */
|
||||
export const TABLE_STYLE_PRESETS: Record<string, TableStylePreset> = {
|
||||
none: { tblPrXml: tblPr(NO_STYLE), description: 'No style' },
|
||||
lightGrid: {
|
||||
tblPrXml: tblPr(NO_STYLE),
|
||||
description: 'Light grid',
|
||||
border: { color: '#BFBFBF', widthEmu: 12700 },
|
||||
},
|
||||
zebraBlue: {
|
||||
tblPrXml: tblPr(ID_ZEBRA_BLUE, ' firstRow="1" bandRow="1"'),
|
||||
description: 'Banded blue',
|
||||
styleId: ID_ZEBRA_BLUE,
|
||||
styleDefXml: customStyle(ID_ZEBRA_BLUE, 'Banded blue', {
|
||||
whole: 'FFFFFF',
|
||||
band: 'D6E4F0',
|
||||
header: { fill: '4472C4', text: 'FFFFFF' },
|
||||
}),
|
||||
},
|
||||
zebraGray: {
|
||||
tblPrXml: tblPr(ID_ZEBRA_GRAY, ' firstRow="1" bandRow="1"'),
|
||||
description: 'Banded gray',
|
||||
styleId: ID_ZEBRA_GRAY,
|
||||
styleDefXml: customStyle(ID_ZEBRA_GRAY, 'Banded gray', {
|
||||
whole: 'FFFFFF',
|
||||
band: 'EDEDED',
|
||||
header: { fill: '595959', text: 'FFFFFF' },
|
||||
}),
|
||||
},
|
||||
headerDarkBlue: {
|
||||
tblPrXml: tblPr(ID_HEADER_DARKBLUE, ' firstRow="1"'),
|
||||
description: 'Dark blue header',
|
||||
styleId: ID_HEADER_DARKBLUE,
|
||||
styleDefXml: customStyle(ID_HEADER_DARKBLUE, 'Dark blue header', {
|
||||
whole: 'FFFFFF',
|
||||
insideH: 'D9D9D9',
|
||||
band: 'E9EDF5',
|
||||
header: { fill: '1F3864', text: 'FFFFFF' },
|
||||
}),
|
||||
},
|
||||
headerOrange: {
|
||||
tblPrXml: tblPr(ID_HEADER_ORANGE, ' firstRow="1"'),
|
||||
description: 'Orange header',
|
||||
styleId: ID_HEADER_ORANGE,
|
||||
styleDefXml: customStyle(ID_HEADER_ORANGE, 'Orange header', {
|
||||
whole: 'FFFFFF',
|
||||
insideH: 'D9D9D9',
|
||||
band: 'FBE5D6',
|
||||
header: { fill: 'ED7D31', text: 'FFFFFF' },
|
||||
}),
|
||||
},
|
||||
noBorder: {
|
||||
tblPrXml: tblPr(ID_NO_BORDER, ' firstRow="1" bandRow="1"'),
|
||||
description: 'Minimal (no borders)',
|
||||
styleId: ID_NO_BORDER,
|
||||
styleDefXml: customStyle(ID_NO_BORDER, 'Minimal (no borders)', { band: 'F2F2F2' }),
|
||||
},
|
||||
fullBorder: {
|
||||
tblPrXml: tblPr(NO_STYLE),
|
||||
description: 'All borders',
|
||||
border: { color: '#000000', widthEmu: 12700 },
|
||||
},
|
||||
}
|
||||
|
||||
const EMPTY_TABLE_STYLES_XML =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
|
||||
'<a:tblStyleLst xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" def="{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"/>'
|
||||
|
||||
/** Ensure the given style definition exists in tableStyles.xml; returned as-is if already present. */
|
||||
export function ensureTableStyleXml(
|
||||
tableStylesXml: string | null | undefined,
|
||||
styleId: string,
|
||||
styleDefXml: string,
|
||||
): string {
|
||||
const xml = tableStylesXml?.includes('<a:tblStyleLst') ? tableStylesXml : EMPTY_TABLE_STYLES_XML
|
||||
if (xml.includes(styleId)) return xml
|
||||
const sc = /<a:tblStyleLst([^>]*)\/>/.exec(xml)
|
||||
if (sc) return xml.replace(sc[0], `<a:tblStyleLst${sc[1]}>${styleDefXml}</a:tblStyleLst>`)
|
||||
return xml.replace('</a:tblStyleLst>', `${styleDefXml}</a:tblStyleLst>`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Surgically patch a table element's originalXml (graphicFrame fragment), applying
|
||||
* the style edit. Returns the patched XML; the caller writes it back to
|
||||
* anchor.originalXml and sets dirty = true.
|
||||
*/
|
||||
export function patchTableStyleXml(originalXml: string, edit: TableStyleEdit): string {
|
||||
let xml = originalXml
|
||||
|
||||
// ── 1. Replace <a:tblPr> ──────────────────────────────────────────
|
||||
if (edit.tblPrXml !== undefined) {
|
||||
// Whole-block replacement
|
||||
xml = replaceTblPr(xml, edit.tblPrXml)
|
||||
} else if (edit.firstRow !== undefined || edit.bandRow !== undefined) {
|
||||
// Change only the flags, keeping the rest (styleId etc.)
|
||||
const tblPrMatch = /<a:tblPr(\s[^>]*)?(\/?>)/s.exec(xml)
|
||||
if (tblPrMatch) {
|
||||
if (tblPrMatch[2] === '/>') {
|
||||
// Self-closing → expand, then change the flags
|
||||
let attrs = tblPrMatch[1] ?? ''
|
||||
if (edit.firstRow !== undefined)
|
||||
attrs = setAttr(attrs, 'firstRow', edit.firstRow ? '1' : undefined)
|
||||
if (edit.bandRow !== undefined)
|
||||
attrs = setAttr(attrs, 'bandRow', edit.bandRow ? '1' : undefined)
|
||||
// A closing </a:tblPr> for the self-closing form doesn't exist → only rewrite the open tag
|
||||
const newOpen = `<a:tblPr${attrs}>`
|
||||
// Expand <a:tblPr.../> into <a:tblPr...></a:tblPr>
|
||||
xml =
|
||||
xml.slice(0, tblPrMatch.index) +
|
||||
newOpen +
|
||||
'</a:tblPr>' +
|
||||
xml.slice(tblPrMatch.index + tblPrMatch[0].length)
|
||||
} else {
|
||||
let attrs = tblPrMatch[1] ?? ''
|
||||
if (edit.firstRow !== undefined)
|
||||
attrs = setAttr(attrs, 'firstRow', edit.firstRow ? '1' : undefined)
|
||||
if (edit.bandRow !== undefined)
|
||||
attrs = setAttr(attrs, 'bandRow', edit.bandRow ? '1' : undefined)
|
||||
const newOpen = `<a:tblPr${attrs}>`
|
||||
xml =
|
||||
xml.slice(0, tblPrMatch.index) +
|
||||
newOpen +
|
||||
xml.slice(tblPrMatch.index + tblPrMatch[0].length)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 2. Shading / borders: patch the targeted <a:tcPr> nodes ────────
|
||||
if (
|
||||
edit.shadingColor !== undefined ||
|
||||
edit.borderPreset !== undefined ||
|
||||
edit.clearDirectFormatting
|
||||
) {
|
||||
xml = edit.cells ? patchCellsTcPr(xml, edit) : patchAllTcPr(xml, edit)
|
||||
}
|
||||
|
||||
return xml
|
||||
}
|
||||
|
||||
/** Replace <a:tblPr>…</a:tblPr> (or its self-closing form) in the XML with a new value. */
|
||||
function replaceTblPr(xml: string, newTblPr: string): string {
|
||||
// Self-closing
|
||||
const sc = /<a:tblPr[^>]*\/>/.exec(xml)
|
||||
if (sc) return xml.slice(0, sc.index) + newTblPr + xml.slice(sc.index + sc[0].length)
|
||||
// Open/close tag pair
|
||||
const open = xml.indexOf('<a:tblPr')
|
||||
if (open < 0) {
|
||||
// No tblPr: insert right after <a:tbl>
|
||||
const tbl = xml.indexOf('<a:tbl>')
|
||||
if (tbl >= 0)
|
||||
return xml.slice(0, tbl + '<a:tbl>'.length) + newTblPr + xml.slice(tbl + '<a:tbl>'.length)
|
||||
return xml
|
||||
}
|
||||
const close = xml.indexOf('</a:tblPr>', open)
|
||||
if (close < 0) return xml
|
||||
return xml.slice(0, open) + newTblPr + xml.slice(close + '</a:tblPr>'.length)
|
||||
}
|
||||
|
||||
/** Set or remove key="value" in an XML attribute string (remove: value=undefined). */
|
||||
function setAttr(attrs: string, key: string, value: string | undefined): string {
|
||||
const re = new RegExp(`\\s${key}="[^"]*"`)
|
||||
const cleaned = attrs.replace(re, '')
|
||||
if (value === undefined) return cleaned
|
||||
return `${cleaned} ${key}="${escapeXmlAttr(value)}"`
|
||||
}
|
||||
|
||||
/** Apply the shading/border/clear parts of an edit to one tcPr's children. */
|
||||
function applyTcPrEdit(inner: string, edit: TableStyleEdit): string {
|
||||
if (edit.clearDirectFormatting) {
|
||||
inner = inner.replace(/<a:(solidFill|gradFill|pattFill|blipFill)>.*?<\/a:\1>/gs, '')
|
||||
inner = inner.replace(/<a:(noFill|grpFill)\/>/g, '')
|
||||
inner = inner.replace(/<a:(lnL|lnR|lnT|lnB|lnTlToBr|lnBlToTr)(\s[^>]*)?\/>/g, '')
|
||||
inner = inner.replace(/<a:(lnL|lnR|lnT|lnB|lnTlToBr|lnBlToTr)(\s[^>]*)?>.*?<\/a:\1>/gs, '')
|
||||
}
|
||||
// Remove existing fill nodes
|
||||
if (edit.shadingColor !== undefined) {
|
||||
inner = inner.replace(/<a:solidFill>.*?<\/a:solidFill>/gs, '')
|
||||
inner = inner.replace(/<a:noFill\/>/g, '')
|
||||
inner = inner.replace(/<a:noFill><\/a:noFill>/g, '')
|
||||
if (edit.shadingColor === 'none') {
|
||||
inner = '<a:noFill/>' + inner
|
||||
} else if (edit.shadingColor) {
|
||||
const c = edit.shadingColor.replace('#', '').toUpperCase()
|
||||
inner = `<a:solidFill><a:srgbClr val="${c}"/></a:solidFill>` + inner
|
||||
}
|
||||
}
|
||||
// Border handling
|
||||
if (edit.borderPreset !== undefined) {
|
||||
inner = inner.replace(/<a:lnL[^>]*>.*?<\/a:lnL>/gs, '')
|
||||
inner = inner.replace(/<a:lnR[^>]*>.*?<\/a:lnR>/gs, '')
|
||||
inner = inner.replace(/<a:lnT[^>]*>.*?<\/a:lnT>/gs, '')
|
||||
inner = inner.replace(/<a:lnB[^>]*>.*?<\/a:lnB>/gs, '')
|
||||
if (edit.borderPreset === 'all' && edit.borderColor) {
|
||||
const c = edit.borderColor.replace('#', '').toUpperCase()
|
||||
const w = edit.borderWidthEmu ?? 12700
|
||||
const lnXml = (tag: string) =>
|
||||
`<${tag} w="${w}"><a:solidFill><a:srgbClr val="${c}"/></a:solidFill></${tag}>`
|
||||
inner = inner + lnXml('a:lnL') + lnXml('a:lnR') + lnXml('a:lnT') + lnXml('a:lnB')
|
||||
} else if (edit.borderPreset === 'none') {
|
||||
inner =
|
||||
inner +
|
||||
'<a:lnL w="0"><a:noFill/></a:lnL><a:lnR w="0"><a:noFill/></a:lnR><a:lnT w="0"><a:noFill/></a:lnT><a:lnB w="0"><a:noFill/></a:lnB>'
|
||||
}
|
||||
}
|
||||
return inner
|
||||
}
|
||||
|
||||
/** Patch the fill/borders of every <a:tcPr> in the XML. */
|
||||
function patchAllTcPr(xml: string, edit: TableStyleEdit): string {
|
||||
const out: string[] = []
|
||||
let cursor = 0
|
||||
const re = /<a:tcPr([^>]*)>(.*?)<\/a:tcPr>|<a:tcPr([^>]*)\/>/gs
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(xml)) !== null) {
|
||||
out.push(xml.slice(cursor, m.index))
|
||||
// Existing children (non-self-closing form)
|
||||
const inner = applyTcPrEdit(m[2] ?? '', edit)
|
||||
const attrs = m[1] ?? m[3] ?? ''
|
||||
out.push(`<a:tcPr${attrs}>${inner}</a:tcPr>`)
|
||||
cursor = m.index + m[0].length
|
||||
}
|
||||
out.push(xml.slice(cursor))
|
||||
return out.join('')
|
||||
}
|
||||
|
||||
/** Span of the nth <tag> element in [from,to); only for tags that cannot nest (a:tr / a:tc). */
|
||||
function nthSpan(
|
||||
xml: string,
|
||||
tag: string,
|
||||
n: number,
|
||||
from = 0,
|
||||
to = xml.length,
|
||||
): { start: number; end: number } | null {
|
||||
const re = new RegExp(`<${tag}[\\s>]`, 'g')
|
||||
re.lastIndex = from
|
||||
let i = 0
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(xml)) !== null && m.index < to) {
|
||||
if (i === n) {
|
||||
const close = xml.indexOf(`</${tag}>`, m.index)
|
||||
if (close < 0 || close + tag.length + 3 > to) return null
|
||||
return { start: m.index, end: close + tag.length + 3 }
|
||||
}
|
||||
i++
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Patch the fill/borders of the <a:tcPr> of just the cells in edit.cells (creating a tcPr when a cell has none). */
|
||||
function patchCellsTcPr(xml: string, edit: TableStyleEdit): string {
|
||||
// Back to front so earlier spans stay valid while splicing
|
||||
const cells = [...edit.cells!].sort((a, b) => b.row - a.row || b.col - a.col)
|
||||
for (const { row, col } of cells) {
|
||||
if (row < 0 || col < 0) continue
|
||||
const tr = nthSpan(xml, 'a:tr', row)
|
||||
if (!tr) continue
|
||||
const tc = nthSpan(xml, 'a:tc', col, tr.start, tr.end)
|
||||
if (!tc) continue
|
||||
let tcXml = xml.slice(tc.start, tc.end)
|
||||
const m = /<a:tcPr([^>]*)>(.*?)<\/a:tcPr>|<a:tcPr([^>]*)\/>/s.exec(tcXml)
|
||||
if (m) {
|
||||
const inner = applyTcPrEdit(m[2] ?? '', edit)
|
||||
const attrs = m[1] ?? m[3] ?? ''
|
||||
tcXml =
|
||||
tcXml.slice(0, m.index) +
|
||||
`<a:tcPr${attrs}>${inner}</a:tcPr>` +
|
||||
tcXml.slice(m.index + m[0].length)
|
||||
} else {
|
||||
// tcPr follows txBody in CT_TableCell
|
||||
tcXml = tcXml.replace(/<\/a:tc>$/, `<a:tcPr>${applyTcPrEdit('', edit)}</a:tcPr></a:tc>`)
|
||||
}
|
||||
xml = xml.slice(0, tc.start) + tcXml + xml.slice(tc.end)
|
||||
}
|
||||
return xml
|
||||
}
|
||||
|
||||
/** Find the table element with the given sourceId in the slide; returns its anchor.originalXml location. */
|
||||
export function findTableElementInSlide(
|
||||
slide: Slide,
|
||||
sourceId: string,
|
||||
): import('./types').TableElement | null {
|
||||
for (const el of slide.elements) {
|
||||
if (el.id === sourceId && el.type === 'table') {
|
||||
return el as import('./types').TableElement
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Table grid-column accounting shared by parse (style lookups) and pptx-render (cell
|
||||
* geometry). Pure and dependency-free: pptx-render's renderer bundle imports this
|
||||
* subpath, so it must not pull in Node-only modules.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Starting grid column of each tc in a row. Standard OOXML rows carry one tc per grid
|
||||
* column (merge continuations included), so each tc advances the cursor by 1; when a
|
||||
* gridSpan anchor's continuation tcs are absent (non-standard producers) the anchor
|
||||
* advances by its span instead.
|
||||
*/
|
||||
export function tableRowGridCols(row: Array<{ gridSpan?: number; merged?: boolean }>): number[] {
|
||||
const cols: number[] = []
|
||||
let c = 0
|
||||
row.forEach((cell, i) => {
|
||||
cols.push(c)
|
||||
const span = cell.gridSpan ?? 1
|
||||
const followers = span > 1 ? row.slice(i + 1, i + span) : []
|
||||
c += followers.length === span - 1 && followers.every((f) => f.merged) ? 1 : span
|
||||
})
|
||||
return cols
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
/**
|
||||
* Table style resolution — tableStyleId referenced by a:tblPr → final fill/text styles
|
||||
* for each table region.
|
||||
*
|
||||
* Two sources:
|
||||
* 1. <a:tblStyle> in ppt/tableStyles.xml (custom styles embedded in the file);
|
||||
* 2. PowerPoint built-in styles (tableStyles.xml usually has only the def id, no body):
|
||||
* All 74 built-in GUIDs are generated from family patterns (Themed 1-2 / Light 1-3 /
|
||||
* Medium 1-4 / Dark 1-2 x no-accent + Accent1-6). The GUID table comes from official
|
||||
* Microsoft docs; family color rules are converted against the LibreOffice oox
|
||||
* predefined-table-styles implementation; banded colors with alpha are pre-blended
|
||||
* into solid colors over the white/table background. Unknown GUIDs return undefined
|
||||
* (keeping the unstyled rendering).
|
||||
*/
|
||||
import { XMLParser } from 'fast-xml-parser'
|
||||
import { resolveSchemeColor, type Theme } from './theme'
|
||||
import type { Fill, Stroke } from './types'
|
||||
import { asXmlNode, xmlArray, type XmlNode } from './xml-utils'
|
||||
|
||||
/** Style for one table region (whole table / banding / first row, etc.). */
|
||||
export interface TablePartStyle {
|
||||
fill?: Fill
|
||||
bold?: boolean
|
||||
textColor?: string
|
||||
}
|
||||
|
||||
export interface TableStyleDef {
|
||||
wholeTbl?: TablePartStyle
|
||||
band1H?: TablePartStyle
|
||||
band2H?: TablePartStyle
|
||||
band1V?: TablePartStyle
|
||||
band2V?: TablePartStyle
|
||||
firstRow?: TablePartStyle
|
||||
lastRow?: TablePartStyle
|
||||
firstCol?: TablePartStyle
|
||||
lastCol?: TablePartStyle
|
||||
/** Inner separator lines between cells (lt1 white lines for the Medium family) */
|
||||
insideH?: Stroke
|
||||
insideV?: Stroke
|
||||
/** Four sides of the whole-table outer border */
|
||||
outer?: { l?: Stroke; r?: Stroke; t?: Stroke; b?: Stroke }
|
||||
/** First-row bottom edge / last-row top edge (header separator lines, used when the firstRow/lastRow flags are on) */
|
||||
firstRowBottom?: Stroke
|
||||
lastRowTop?: Stroke
|
||||
}
|
||||
|
||||
/** Region toggles from a:tblPr. */
|
||||
export interface TableStyleFlags {
|
||||
firstRow: boolean
|
||||
lastRow: boolean
|
||||
firstCol: boolean
|
||||
lastCol: boolean
|
||||
bandRow: boolean
|
||||
bandCol: boolean
|
||||
}
|
||||
|
||||
type BuiltinFamily =
|
||||
| 'themed1'
|
||||
| 'themed2'
|
||||
| 'light1'
|
||||
| 'light2'
|
||||
| 'light3'
|
||||
| 'medium1'
|
||||
| 'medium2'
|
||||
| 'medium3'
|
||||
| 'medium4'
|
||||
| 'dark1'
|
||||
| 'dark2'
|
||||
|
||||
// 74 built-in style GUIDs -> family + accent (GUID table from official Microsoft docs hh273476).
|
||||
// themed1 without accent = No Style, No Grid; themed2 without accent = No Style, Table Grid.
|
||||
const BUILTIN: Record<string, { family: BuiltinFamily; accent?: string }> = {
|
||||
'{2D5ABB26-0587-4C30-8999-92F81FD0307C}': { family: 'themed1' },
|
||||
'{3C2FFA5D-87B4-456A-9821-1D502468CF0F}': { family: 'themed1', accent: 'accent1' },
|
||||
'{284E427A-3D55-4303-BF80-6455036E1DE7}': { family: 'themed1', accent: 'accent2' },
|
||||
'{69C7853C-536D-4A76-A0AE-DD22124D55A5}': { family: 'themed1', accent: 'accent3' },
|
||||
'{775DCB02-9BB8-47FD-8907-85C794F793BA}': { family: 'themed1', accent: 'accent4' },
|
||||
'{35758FB7-9AC5-4552-8A53-C91805E547FA}': { family: 'themed1', accent: 'accent5' },
|
||||
'{08FB837D-C827-4EFA-A057-4D05807E0F7C}': { family: 'themed1', accent: 'accent6' },
|
||||
'{5940675A-B579-460E-94D1-54222C63F5DA}': { family: 'themed2' },
|
||||
'{D113A9D2-9D6B-4929-AA2D-F23B5EE8CBE7}': { family: 'themed2', accent: 'accent1' },
|
||||
'{18603FDC-E32A-4AB5-989C-0864C3EAD2B8}': { family: 'themed2', accent: 'accent2' },
|
||||
'{306799F8-075E-4A3A-A7F6-7FBC6576F1A4}': { family: 'themed2', accent: 'accent3' },
|
||||
'{E269D01E-BC32-4049-B463-5C60D7B0CCD2}': { family: 'themed2', accent: 'accent4' },
|
||||
'{327F97BB-C833-4FB7-BDE5-3F7075034690}': { family: 'themed2', accent: 'accent5' },
|
||||
'{638B1855-1B75-4FBE-930C-398BA8C253C6}': { family: 'themed2', accent: 'accent6' },
|
||||
'{9D7B26C5-4107-4FEC-AEDC-1716B250A1EF}': { family: 'light1' },
|
||||
'{3B4B98B0-60AC-42C2-AFA5-B58CD77FA1E5}': { family: 'light1', accent: 'accent1' },
|
||||
'{0E3FDE45-AF77-4B5C-9715-49D594BDF05E}': { family: 'light1', accent: 'accent2' },
|
||||
'{C083E6E3-FA7D-4D7B-A595-EF9225AFEA82}': { family: 'light1', accent: 'accent3' },
|
||||
'{D27102A9-8310-4765-A935-A1911B00CA55}': { family: 'light1', accent: 'accent4' },
|
||||
'{5FD0F851-EC5A-4D38-B0AD-8093EC10F338}': { family: 'light1', accent: 'accent5' },
|
||||
'{68D230F3-CF80-4859-8CE7-A43EE81993B5}': { family: 'light1', accent: 'accent6' },
|
||||
'{7E9639D4-E3E2-4D34-9284-5A2195B3D0D7}': { family: 'light2' },
|
||||
'{69012ECD-51FC-41F1-AA8D-1B2483CD663E}': { family: 'light2', accent: 'accent1' },
|
||||
'{72833802-FEF1-4C79-8D5D-14CF1EAF98D9}': { family: 'light2', accent: 'accent2' },
|
||||
'{F2DE63D5-997A-4646-A377-4702673A728D}': { family: 'light2', accent: 'accent3' },
|
||||
'{17292A2E-F333-43FB-9621-5CBBE7FDCDCB}': { family: 'light2', accent: 'accent4' },
|
||||
'{5A111915-BE36-4E01-A7E5-04B1672EAD32}': { family: 'light2', accent: 'accent5' },
|
||||
'{912C8C85-51F0-491E-9774-3900AFEF0FD7}': { family: 'light2', accent: 'accent6' },
|
||||
'{616DA210-FB5B-4158-B5E0-FEB733F419BA}': { family: 'light3' },
|
||||
'{BC89EF96-8CEA-46FF-86C4-4CE0E7609802}': { family: 'light3', accent: 'accent1' },
|
||||
'{5DA37D80-6434-44D0-A028-1B22A696006F}': { family: 'light3', accent: 'accent2' },
|
||||
'{8799B23B-EC83-4686-B30A-512413B5E67A}': { family: 'light3', accent: 'accent3' },
|
||||
'{ED083AE6-46FA-4A59-8FB0-9F97EB10719F}': { family: 'light3', accent: 'accent4' },
|
||||
'{BDBED569-4797-4DF1-A0F4-6AAB3CD982D8}': { family: 'light3', accent: 'accent5' },
|
||||
'{E8B1032C-EA38-4F05-BA0D-38AFFFC7BED3}': { family: 'light3', accent: 'accent6' },
|
||||
'{793D81CF-94F2-401A-BA57-92F5A7B2D0C5}': { family: 'medium1' },
|
||||
'{B301B821-A1FF-4177-AEE7-76D212191A09}': { family: 'medium1', accent: 'accent1' },
|
||||
'{9DCAF9ED-07DC-4A11-8D7F-57B35C25682E}': { family: 'medium1', accent: 'accent2' },
|
||||
'{1FECB4D8-DB02-4DC6-A0A2-4F2EBAE1DC90}': { family: 'medium1', accent: 'accent3' },
|
||||
'{1E171933-4619-4E11-9A3F-F7608DF75F80}': { family: 'medium1', accent: 'accent4' },
|
||||
'{FABFCF23-3B69-468F-B69F-88F6DE6A72F2}': { family: 'medium1', accent: 'accent5' },
|
||||
'{10A1B5D5-9B99-4C35-A422-299274C87663}': { family: 'medium1', accent: 'accent6' },
|
||||
'{073A0DAA-6AF3-43AB-8588-CEC1D06C72B9}': { family: 'medium2' },
|
||||
'{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}': { family: 'medium2', accent: 'accent1' },
|
||||
'{21E4AEA4-8DFA-4A89-87EB-49C32662AFE0}': { family: 'medium2', accent: 'accent2' },
|
||||
'{F5AB1C69-6EDB-4FF4-983F-18BD219EF322}': { family: 'medium2', accent: 'accent3' },
|
||||
'{00A15C55-8517-42AA-B614-E9B94910E393}': { family: 'medium2', accent: 'accent4' },
|
||||
'{7DF18680-E054-41AD-8BC1-D1AEF772440D}': { family: 'medium2', accent: 'accent5' },
|
||||
'{93296810-A885-4BE3-A3E7-6D5BEEA58F35}': { family: 'medium2', accent: 'accent6' },
|
||||
'{8EC20E35-A176-4012-BC5E-935CFFF8708E}': { family: 'medium3' },
|
||||
'{6E25E649-3F16-4E02-A733-19D2CDBF48F0}': { family: 'medium3', accent: 'accent1' },
|
||||
'{85BE263C-DBD7-4A20-BB59-AAB30ACAA65A}': { family: 'medium3', accent: 'accent2' },
|
||||
'{EB344D84-9AFB-497E-A393-DC336BA19D2E}': { family: 'medium3', accent: 'accent3' },
|
||||
'{EB9631B5-78F2-41C9-869B-9F39066F8104}': { family: 'medium3', accent: 'accent4' },
|
||||
'{74C1A8A3-306A-4EB7-A6B1-4F7E0EB9C5D6}': { family: 'medium3', accent: 'accent5' },
|
||||
'{2A488322-F2BA-4B5B-9748-0D474271808F}': { family: 'medium3', accent: 'accent6' },
|
||||
'{D7AC3CCA-C797-4891-BE02-D94E43425B78}': { family: 'medium4' },
|
||||
'{69CF1AB2-1976-4502-BF36-3FF5EA218861}': { family: 'medium4', accent: 'accent1' },
|
||||
'{8A107856-5554-42FB-B03E-39F5DBC370BA}': { family: 'medium4', accent: 'accent2' },
|
||||
'{0505E3EF-67EA-436B-97B2-0124C06EBD24}': { family: 'medium4', accent: 'accent3' },
|
||||
'{C4B1156A-380E-4F78-BDF5-A606A8083BF9}': { family: 'medium4', accent: 'accent4' },
|
||||
'{22838BEF-8BB2-4498-84A7-C5851F593DF1}': { family: 'medium4', accent: 'accent5' },
|
||||
'{16D9F66E-5EB9-4882-86FB-DCBF35E3C3E4}': { family: 'medium4', accent: 'accent6' },
|
||||
'{E8034E78-7F5D-4C2E-B375-FC64B27BC917}': { family: 'dark1' },
|
||||
'{125E5076-3810-47DD-B79F-674D7AD40C01}': { family: 'dark1', accent: 'accent1' },
|
||||
'{37CE84F3-28C3-443E-9E96-99CF82512B78}': { family: 'dark1', accent: 'accent2' },
|
||||
'{D03447BB-5D67-496B-8E87-E561075AD55C}': { family: 'dark1', accent: 'accent3' },
|
||||
'{E929F9F4-4A8F-4326-A1B4-22849713DDAB}': { family: 'dark1', accent: 'accent4' },
|
||||
'{8FD4443E-F989-4FC4-A0C8-D5A2AF1F390B}': { family: 'dark1', accent: 'accent5' },
|
||||
'{AF606853-7671-496A-8E4F-DF71F8EC918B}': { family: 'dark1', accent: 'accent6' },
|
||||
'{5202B0CA-FC54-4496-8BCA-5EF66A818D29}': { family: 'dark2' },
|
||||
'{0660B408-B3CF-4A94-85FC-2B1E0A45F4A2}': { family: 'dark2', accent: 'accent1' },
|
||||
'{91EBBBCC-DAD2-459C-BE2E-F6DE35CF9A28}': { family: 'dark2', accent: 'accent3' },
|
||||
'{46F890A9-2807-4EBB-B81D-B2AA78EC7F39}': { family: 'dark2', accent: 'accent5' },
|
||||
}
|
||||
|
||||
/** Compatibility: the made-up "no style" GUID this app used to write (not in the official table). */
|
||||
export const LEGACY_NO_STYLE = '{2D5ABB26-0587-4C30-8999-92F81FD0307D}'
|
||||
|
||||
/** tint: keep pct of the color and blend the rest toward white (OOXML <a:tint val="20000"> = 20%). */
|
||||
function tint(hex: string, pct: number): string {
|
||||
return mixToward(hex, pct, 255)
|
||||
}
|
||||
|
||||
/** shade: keep pct of the color and blend the rest toward black (OOXML <a:shade>). */
|
||||
function shade(hex: string, pct: number): string {
|
||||
return mixToward(hex, pct, 0)
|
||||
}
|
||||
|
||||
function mixToward(hex: string, pct: number, target: number): string {
|
||||
const h = hex.replace('#', '')
|
||||
const ch = (i: number) => parseInt(h.slice(i, i + 2), 16)
|
||||
const mix = (c: number) => Math.round(target * (1 - pct) + c * pct)
|
||||
const to = (c: number) => c.toString(16).toUpperCase().padStart(2, '0')
|
||||
return `#${to(mix(ch(0)))}${to(mix(ch(2)))}${to(mix(ch(4)))}`
|
||||
}
|
||||
|
||||
/** Pre-blended solid color of fg composited over bg at alpha opacity (banded alpha fill -> solid color). */
|
||||
function over(fg: string, alpha: number, bg: string): string {
|
||||
const f = fg.replace('#', '')
|
||||
const b = bg.replace('#', '')
|
||||
const ch = (s: string, i: number) => parseInt(s.slice(i, i + 2), 16)
|
||||
const mix = (i: number) => Math.round(ch(f, i) * alpha + ch(b, i) * (1 - alpha))
|
||||
const to = (c: number) => c.toString(16).toUpperCase().padStart(2, '0')
|
||||
return `#${to(mix(0))}${to(mix(2))}${to(mix(4))}`
|
||||
}
|
||||
|
||||
const solid = (color: string): Fill => ({ type: 'solid', color })
|
||||
const line = (color: string, width = 12700): Stroke => ({ fill: solid(color), width })
|
||||
|
||||
/**
|
||||
* Built-in style family -> region styles (color rules follow the LibreOffice
|
||||
* predefined-table-styles implementation; colors are resolved to final values via the
|
||||
* theme; banded alpha is pre-blended against the underlying background).
|
||||
*/
|
||||
function builtinStyle(family: BuiltinFamily, accentName: string | undefined, theme: Theme | undefined): TableStyleDef {
|
||||
const lt1 = resolveSchemeColor('lt1', theme) ?? '#FFFFFF'
|
||||
const dk1 = resolveSchemeColor('dk1', theme) ?? '#000000'
|
||||
const accent = accentName ? (resolveSchemeColor(accentName, theme) ?? '#4472C4') : undefined
|
||||
|
||||
switch (family) {
|
||||
case 'themed1': {
|
||||
if (!accent) return { wholeTbl: { textColor: dk1 } } // No Style, No Grid
|
||||
const band = solid(over(accent, 0.4, lt1))
|
||||
return {
|
||||
wholeTbl: { textColor: dk1 },
|
||||
firstRow: { fill: solid(accent), textColor: lt1 },
|
||||
band1H: { fill: band },
|
||||
band1V: { fill: band },
|
||||
insideH: line(accent),
|
||||
insideV: line(accent),
|
||||
outer: { l: line(accent), r: line(accent), t: line(accent), b: line(accent) },
|
||||
firstRowBottom: line(lt1),
|
||||
}
|
||||
}
|
||||
case 'themed2': {
|
||||
if (!accent) {
|
||||
// No Style, Table Grid: all-dk1 grid
|
||||
return {
|
||||
wholeTbl: { textColor: dk1 },
|
||||
insideH: line(dk1),
|
||||
insideV: line(dk1),
|
||||
outer: { l: line(dk1), r: line(dk1), t: line(dk1), b: line(dk1) },
|
||||
}
|
||||
}
|
||||
const outer = line(tint(accent, 0.5))
|
||||
const band = solid(over(lt1, 0.2, accent))
|
||||
return {
|
||||
wholeTbl: { fill: solid(accent), textColor: lt1 },
|
||||
band1H: { fill: band },
|
||||
band1V: { fill: band },
|
||||
outer: { l: outer, r: outer, t: outer, b: outer },
|
||||
firstRowBottom: line(lt1),
|
||||
lastRowTop: line(lt1),
|
||||
}
|
||||
}
|
||||
case 'light1': {
|
||||
const a = accent ?? dk1
|
||||
const band = solid(over(a, 0.2, lt1))
|
||||
return {
|
||||
wholeTbl: { textColor: dk1 },
|
||||
firstRow: { bold: true, textColor: dk1 },
|
||||
firstCol: { bold: true },
|
||||
lastCol: { bold: true, textColor: dk1 },
|
||||
band1H: { fill: band },
|
||||
band1V: { fill: band },
|
||||
outer: { t: line(a), b: line(a) },
|
||||
firstRowBottom: line(a),
|
||||
lastRowTop: line(a),
|
||||
}
|
||||
}
|
||||
case 'light2': {
|
||||
const a = accent ?? dk1
|
||||
return {
|
||||
wholeTbl: { textColor: dk1 },
|
||||
firstRow: { fill: solid(a), textColor: lt1, bold: true },
|
||||
outer: { l: line(a), r: line(a), t: line(a), b: line(a) },
|
||||
lastRowTop: line(a),
|
||||
}
|
||||
}
|
||||
case 'light3': {
|
||||
const a = accent ?? dk1
|
||||
const band = solid(over(a, 0.2, lt1))
|
||||
return {
|
||||
wholeTbl: { textColor: dk1 },
|
||||
firstRow: { textColor: a, bold: true },
|
||||
band1H: { fill: band },
|
||||
band1V: { fill: band },
|
||||
insideH: line(a),
|
||||
insideV: line(a),
|
||||
outer: { l: line(a), r: line(a), t: line(a), b: line(a) },
|
||||
firstRowBottom: line(a),
|
||||
lastRowTop: line(a),
|
||||
}
|
||||
}
|
||||
case 'medium1': {
|
||||
const a = accent ?? dk1
|
||||
const band = solid(tint(a, 0.2))
|
||||
return {
|
||||
wholeTbl: { fill: solid(lt1), textColor: dk1 },
|
||||
firstRow: { fill: solid(a), textColor: lt1, bold: true },
|
||||
lastRow: { fill: solid(lt1), bold: true },
|
||||
band1H: { fill: band },
|
||||
band1V: { fill: band },
|
||||
insideH: line(a),
|
||||
outer: { l: line(a), r: line(a), t: line(a), b: line(a) },
|
||||
lastRowTop: line(a),
|
||||
}
|
||||
}
|
||||
case 'medium2': {
|
||||
const a = accent ?? dk1
|
||||
return {
|
||||
wholeTbl: { fill: solid(tint(a, 0.2)), textColor: dk1 },
|
||||
band1H: { fill: solid(tint(a, 0.4)) },
|
||||
band1V: { fill: solid(tint(a, 0.4)) },
|
||||
firstRow: { fill: solid(a), textColor: lt1, bold: true },
|
||||
lastRow: { fill: solid(a), textColor: lt1, bold: true },
|
||||
firstCol: { fill: solid(a), textColor: lt1, bold: true },
|
||||
lastCol: { fill: solid(a), textColor: lt1, bold: true },
|
||||
insideH: line(lt1),
|
||||
insideV: line(lt1),
|
||||
outer: { l: line(lt1), r: line(lt1), t: line(lt1), b: line(lt1) },
|
||||
firstRowBottom: line(lt1),
|
||||
lastRowTop: line(lt1),
|
||||
}
|
||||
}
|
||||
case 'medium3': {
|
||||
const a = accent ?? dk1
|
||||
const band = solid(tint(dk1, 0.2))
|
||||
return {
|
||||
wholeTbl: { fill: solid(lt1), textColor: dk1 },
|
||||
firstRow: { fill: solid(a), textColor: lt1, bold: true },
|
||||
lastRow: { fill: solid(lt1), bold: true },
|
||||
firstCol: { fill: solid(a), textColor: lt1 },
|
||||
lastCol: { fill: solid(a), textColor: lt1 },
|
||||
band1H: { fill: band },
|
||||
band1V: { fill: band },
|
||||
outer: { t: line(dk1), b: line(dk1) },
|
||||
firstRowBottom: line(dk1),
|
||||
lastRowTop: line(dk1),
|
||||
}
|
||||
}
|
||||
case 'medium4': {
|
||||
const a = accent ?? dk1
|
||||
const band = solid(tint(a, 0.4))
|
||||
return {
|
||||
wholeTbl: { fill: solid(tint(a, 0.2)), textColor: dk1 },
|
||||
firstRow: { fill: solid(tint(a, 0.2)), textColor: a, bold: true },
|
||||
lastRow: { fill: solid(tint(dk1, 0.2)) },
|
||||
band1H: { fill: band },
|
||||
band1V: { fill: band },
|
||||
insideH: line(a),
|
||||
insideV: line(a),
|
||||
outer: { l: line(a), r: line(a), t: line(a), b: line(a) },
|
||||
lastRowTop: line(dk1),
|
||||
}
|
||||
}
|
||||
case 'dark1': {
|
||||
// accent variants use shade (dark background, light text); the no-accent variant uses dk1 tint (light gray background, dark text)
|
||||
const a = accent ?? dk1
|
||||
const tf = accent ? shade : tint
|
||||
const body = accent ? lt1 : dk1
|
||||
return {
|
||||
wholeTbl: { fill: solid(tf(a, 0.2)), textColor: body },
|
||||
firstRow: { fill: solid(dk1), textColor: lt1, bold: true },
|
||||
lastRow: { fill: solid(tf(a, 0.2)), textColor: body, bold: true },
|
||||
firstCol: { fill: solid(tf(a, 0.6)) },
|
||||
lastCol: { fill: solid(tf(a, 0.6)) },
|
||||
band1H: { fill: solid(tf(a, 0.4)) },
|
||||
band1V: { fill: solid(tf(a, 0.4)) },
|
||||
firstRowBottom: line(lt1),
|
||||
lastRowTop: line(lt1),
|
||||
}
|
||||
}
|
||||
case 'dark2': {
|
||||
const a = accent ?? dk1
|
||||
// Header paired colors: base=dk1, Accent1->accent2 / Accent3->accent4 / Accent5->accent6
|
||||
const headerPair: Record<string, string> = { accent1: 'accent2', accent3: 'accent4', accent5: 'accent6' }
|
||||
const header = accentName ? (resolveSchemeColor(headerPair[accentName] ?? accentName, theme) ?? dk1) : dk1
|
||||
const band = solid(tint(a, 0.4))
|
||||
return {
|
||||
wholeTbl: { fill: solid(tint(a, 0.2)), textColor: dk1 },
|
||||
firstRow: { fill: solid(header), textColor: lt1, bold: true },
|
||||
lastRow: { fill: solid(tint(a, 0.2)), bold: true },
|
||||
band1H: { fill: band },
|
||||
band1V: { fill: band },
|
||||
lastRowTop: line(dk1),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* styleId → style definition. Prefers explicit definitions in tableStyles.xml, falling
|
||||
* back to the built-in table.
|
||||
*/
|
||||
export function resolveTableStyle(
|
||||
styleId: string | undefined,
|
||||
tableStylesXml: string | undefined,
|
||||
theme: Theme | undefined,
|
||||
): TableStyleDef | undefined {
|
||||
if (!styleId) return undefined
|
||||
if (tableStylesXml && tableStylesXml.includes(styleId)) {
|
||||
const def = parseTableStylesXml(tableStylesXml, styleId, theme)
|
||||
if (def) return def
|
||||
}
|
||||
const builtin = BUILTIN[styleId]
|
||||
if (builtin) return builtinStyle(builtin.family, builtin.accent, theme)
|
||||
if (styleId === LEGACY_NO_STYLE) return {}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Style borders for cell (r,c) (composed from region borders; explicit tcPr borders
|
||||
* take precedence): inner separator lines + whole-table outer border + header
|
||||
* separator lines (when the firstRow/lastRow flags are on).
|
||||
*/
|
||||
export function cellStyleBorders(
|
||||
def: TableStyleDef,
|
||||
flags: TableStyleFlags,
|
||||
r: number,
|
||||
c: number,
|
||||
nRows: number,
|
||||
nCols: number,
|
||||
): { l?: Stroke; r?: Stroke; t?: Stroke; b?: Stroke } {
|
||||
const out: { l?: Stroke; r?: Stroke; t?: Stroke; b?: Stroke } = {}
|
||||
if (r < nRows - 1 && def.insideH) out.b = def.insideH
|
||||
if (c < nCols - 1 && def.insideV) out.r = def.insideV
|
||||
if (def.outer) {
|
||||
if (r === 0 && def.outer.t) out.t = def.outer.t
|
||||
if (r === nRows - 1 && def.outer.b) out.b = def.outer.b
|
||||
if (c === 0 && def.outer.l) out.l = def.outer.l
|
||||
if (c === nCols - 1 && def.outer.r) out.r = def.outer.r
|
||||
}
|
||||
if (flags.firstRow && r === 0 && nRows > 1 && def.firstRowBottom) out.b = def.firstRowBottom
|
||||
if (flags.lastRow && r === nRows - 1 && nRows > 1 && def.lastRowTop) out.t = def.lastRowTop
|
||||
return out
|
||||
}
|
||||
|
||||
// ── tableStyles.xml parsing ─────────────────────────────────────────
|
||||
|
||||
const tsParser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
attributeNamePrefix: '@_',
|
||||
isArray: (name) => name === 'a:tblStyle',
|
||||
})
|
||||
|
||||
function readColor(node: unknown, theme: Theme | undefined): string | undefined {
|
||||
if (!node || typeof node !== 'object') return undefined
|
||||
const n = asXmlNode(node)
|
||||
const srgb = asXmlNode(n['a:srgbClr'])['@_val']
|
||||
if (srgb) return '#' + String(srgb).toUpperCase()
|
||||
if (n['a:schemeClr']) {
|
||||
const scheme = asXmlNode(n['a:schemeClr'])
|
||||
const base = resolveSchemeColor(String(scheme['@_val']), theme)
|
||||
if (!base) return undefined
|
||||
const t = asXmlNode(scheme['a:tint'])['@_val']
|
||||
return t ? tint(base, parseInt(String(t), 10) / 100000) : base
|
||||
}
|
||||
const prst = asXmlNode(n['a:prstClr'])['@_val']
|
||||
if (prst === 'black') return '#000000'
|
||||
if (prst === 'white') return '#FFFFFF'
|
||||
return undefined
|
||||
}
|
||||
|
||||
function readPart(part: unknown, theme: Theme | undefined): TablePartStyle | undefined {
|
||||
if (!part || typeof part !== 'object') return undefined
|
||||
const p = asXmlNode(part)
|
||||
const out: TablePartStyle = {}
|
||||
const fillColor = readColor(
|
||||
asXmlNode(asXmlNode(p['a:tcStyle'])['a:fill'])['a:solidFill'],
|
||||
theme,
|
||||
)
|
||||
if (fillColor) out.fill = solid(fillColor)
|
||||
if (p['a:tcTxStyle']) {
|
||||
const tx = asXmlNode(p['a:tcTxStyle'])
|
||||
if (tx['@_b'] === 'on') out.bold = true
|
||||
const c = readColor(tx, theme)
|
||||
if (c) out.textColor = c
|
||||
}
|
||||
return Object.keys(out).length ? out : undefined
|
||||
}
|
||||
|
||||
function readInside(part: unknown, tag: 'a:insideH' | 'a:insideV', theme: Theme | undefined): Stroke | undefined {
|
||||
const bdr = asXmlNode(asXmlNode(asXmlNode(part)['a:tcStyle'])['a:tcBdr'])
|
||||
const lnRaw = asXmlNode(bdr[tag])['a:ln']
|
||||
if (!lnRaw) return undefined
|
||||
const ln = asXmlNode(lnRaw)
|
||||
const c = readColor(ln['a:solidFill'], theme)
|
||||
if (!c) return undefined
|
||||
return line(c, parseInt(String(ln['@_w']), 10) || 12700)
|
||||
}
|
||||
|
||||
function parseTableStylesXml(xml: string, styleId: string, theme: Theme | undefined): TableStyleDef | undefined {
|
||||
let doc: XmlNode
|
||||
try {
|
||||
doc = asXmlNode(tsParser.parse(xml))
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
const list = asXmlNode(doc['a:tblStyleLst'])['a:tblStyle'] ?? []
|
||||
const style = xmlArray(list).find((s) => s['@_styleId'] === styleId)
|
||||
if (!style) return undefined
|
||||
const def: TableStyleDef = {}
|
||||
for (const key of ['wholeTbl', 'band1H', 'band2H', 'band1V', 'band2V', 'firstRow', 'lastRow', 'firstCol', 'lastCol'] as const) {
|
||||
const p = readPart(style['a:' + key], theme)
|
||||
if (p) def[key] = p
|
||||
}
|
||||
def.insideH = readInside(style['a:wholeTbl'], 'a:insideH', theme)
|
||||
def.insideV = readInside(style['a:wholeTbl'], 'a:insideV', theme)
|
||||
if (!def.insideH) delete def.insideH
|
||||
if (!def.insideV) delete def.insideV
|
||||
return Object.keys(def).length ? def : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the final region style for cell (r,c) (OOXML precedence:
|
||||
* wholeTbl < banding < lastRow/firstCol/lastCol < firstRow).
|
||||
*/
|
||||
export function cellPartStyle(
|
||||
def: TableStyleDef,
|
||||
flags: TableStyleFlags,
|
||||
r: number,
|
||||
c: number,
|
||||
nRows: number,
|
||||
nCols: number,
|
||||
): TablePartStyle {
|
||||
const merge = (base: TablePartStyle, over?: TablePartStyle): TablePartStyle =>
|
||||
over ? { ...base, ...Object.fromEntries(Object.entries(over).filter(([, v]) => v !== undefined)) } : base
|
||||
|
||||
let out: TablePartStyle = { ...(def.wholeTbl ?? {}) }
|
||||
const isFirstRow = flags.firstRow && r === 0
|
||||
const isLastRow = flags.lastRow && r === nRows - 1
|
||||
const isFirstCol = flags.firstCol && c === 0
|
||||
const isLastCol = flags.lastCol && c === nCols - 1
|
||||
|
||||
if (flags.bandRow && !isFirstRow && !isLastRow) {
|
||||
const dataR = r - (flags.firstRow ? 1 : 0)
|
||||
out = merge(out, dataR % 2 === 0 ? def.band1H : def.band2H)
|
||||
}
|
||||
if (flags.bandCol && !isFirstCol && !isLastCol) {
|
||||
const dataC = c - (flags.firstCol ? 1 : 0)
|
||||
out = merge(out, dataC % 2 === 0 ? def.band1V : def.band2V)
|
||||
}
|
||||
if (isLastCol) out = merge(out, def.lastCol)
|
||||
if (isFirstCol) out = merge(out, def.firstCol)
|
||||
if (isLastRow) out = merge(out, def.lastRow)
|
||||
if (isFirstRow) out = merge(out, def.firstRow)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* Theme application (Design tab theme gallery) — rewrites <a:clrScheme> and
|
||||
* <a:fontScheme> of every ppt/theme/theme*.xml in the package, in place.
|
||||
*
|
||||
* Semantics match PowerPoint: content referencing schemeClr / +mj-lt / +mn-lt
|
||||
* follows the new theme; content with explicit srgbClr / explicit fonts stays
|
||||
* as-is. After rewriting, the caller (main process) must save→reopen to reparse
|
||||
* the inheritance chain so elements' resolved colors/fonts refresh.
|
||||
*
|
||||
* Exception: theme parts are the sole exemption from the "never write back
|
||||
* layout/master/theme" rule — the whole point of the theme gallery is to replace
|
||||
* the theme; layout/master themselves are still untouched.
|
||||
*/
|
||||
import type { OpenedPptx } from './index'
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
|
||||
/** One theme definition: 12 scheme colors + optional heading/body fonts. */
|
||||
export interface ThemeSpec {
|
||||
name: string
|
||||
/** dk1/lt1/dk2/lt2/accent1..6/hlink/folHlink → #RRGGBB (upper or lower case) */
|
||||
colors: Record<string, string>
|
||||
/** Heading (title) Latin font; original theme kept if unset */
|
||||
majorFont?: string
|
||||
/** Body Latin font; original theme kept if unset */
|
||||
minorFont?: string
|
||||
}
|
||||
|
||||
const SCHEME_KEYS = [
|
||||
'dk1',
|
||||
'lt1',
|
||||
'dk2',
|
||||
'lt2',
|
||||
'accent1',
|
||||
'accent2',
|
||||
'accent3',
|
||||
'accent4',
|
||||
'accent5',
|
||||
'accent6',
|
||||
'hlink',
|
||||
'folHlink',
|
||||
] as const
|
||||
|
||||
const hex6 = (c: string) => c.replace(/^#/, '').slice(0, 6).toUpperCase()
|
||||
|
||||
/** Rewrite a theme XML's clrScheme/fontScheme; returned as-is if the scheme structure is missing. */
|
||||
export function patchThemeXml(xml: string, spec: ThemeSpec): string {
|
||||
let out = xml
|
||||
// Colors: replace the whole <a:dk1>…</a:dk1> section per key (sysClr/srgbClr both become srgbClr)
|
||||
for (const key of SCHEME_KEYS) {
|
||||
const color = spec.colors[key]
|
||||
if (!color) continue
|
||||
out = out.replace(
|
||||
new RegExp(`<a:${key}>[\\s\\S]*?</a:${key}>`),
|
||||
`<a:${key}><a:srgbClr val="${hex6(color)}"/></a:${key}>`,
|
||||
)
|
||||
}
|
||||
out = out.replace(/(<a:clrScheme name=")[^"]*(")/, `$1${escapeXmlAttr(spec.name)}$2`)
|
||||
// Fonts: replace only the major/minor Latin typeface; East Asian / cs kept
|
||||
if (spec.majorFont) {
|
||||
out = out.replace(
|
||||
/(<a:majorFont>[\s\S]*?<a:latin[^>]*typeface=")[^"]*(")/,
|
||||
`$1${escapeXmlAttr(spec.majorFont)}$2`,
|
||||
)
|
||||
}
|
||||
if (spec.minorFont) {
|
||||
out = out.replace(
|
||||
/(<a:minorFont>[\s\S]*?<a:latin[^>]*typeface=")[^"]*(")/,
|
||||
`$1${escapeXmlAttr(spec.minorFont)}$2`,
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const THEME_PART_RE = /^ppt\/theme\/theme\d+\.xml$/
|
||||
|
||||
/** Apply the theme to all theme parts in the package; returns the number rewritten. */
|
||||
export function applyThemeToArchive(opened: OpenedPptx, spec: ThemeSpec): number {
|
||||
const { archive } = opened
|
||||
let patched = 0
|
||||
for (const path of [...archive.entries.keys()]) {
|
||||
if (!THEME_PART_RE.test(path)) continue
|
||||
const xml = archive.readText(path)
|
||||
if (!xml) continue
|
||||
const next = patchThemeXml(xml, spec)
|
||||
if (next !== xml) {
|
||||
archive.entries.set(path, Buffer.from(next, 'utf8'))
|
||||
patched++
|
||||
}
|
||||
}
|
||||
return patched
|
||||
}
|
||||
|
||||
// ── Explicit color remapping ──────────────────────────────────────────
|
||||
// Real-world decks (especially AI-generated/exported ones) use almost exclusively
|
||||
// explicit srgbClr colors that never reference the scheme — swapping only the theme
|
||||
// parts changes nothing visually. Here the deck's existing explicit colors are
|
||||
// remapped wholesale onto the new theme palette:
|
||||
// · neutrals (low saturation / near black-white) map onto the new theme's
|
||||
// dk1↔lt1 axis, bucketed by lightness;
|
||||
// · chromatic colors are clustered by hue, and clusters are assigned to
|
||||
// accent1..6 in order of frequency;
|
||||
// · output replaces only hue/base saturation, keeping the original lightness —
|
||||
// shading levels and contrast structure stay intact.
|
||||
|
||||
interface Hsl {
|
||||
/** 0..360 */
|
||||
h: number
|
||||
/** 0..1 */
|
||||
s: number
|
||||
/** 0..1 */
|
||||
l: number
|
||||
}
|
||||
|
||||
function hexToHsl(hex: string): Hsl {
|
||||
const h6 = hex.replace(/^#/, '')
|
||||
const r = (parseInt(h6.slice(0, 2), 16) || 0) / 255
|
||||
const g = (parseInt(h6.slice(2, 4), 16) || 0) / 255
|
||||
const b = (parseInt(h6.slice(4, 6), 16) || 0) / 255
|
||||
const max = Math.max(r, g, b)
|
||||
const min = Math.min(r, g, b)
|
||||
const l = (max + min) / 2
|
||||
const d = max - min
|
||||
if (d === 0) return { h: 0, s: 0, l }
|
||||
const s = d / (1 - Math.abs(2 * l - 1))
|
||||
let h: number
|
||||
if (max === r) h = 60 * (((g - b) / d) % 6)
|
||||
else if (max === g) h = 60 * ((b - r) / d + 2)
|
||||
else h = 60 * ((r - g) / d + 4)
|
||||
if (h < 0) h += 360
|
||||
return { h, s: Math.min(1, s), l }
|
||||
}
|
||||
|
||||
function hslToHex({ h, s, l }: Hsl): string {
|
||||
const c = (1 - Math.abs(2 * l - 1)) * s
|
||||
const x = c * (1 - Math.abs(((h / 60) % 2) - 1))
|
||||
const m = l - c / 2
|
||||
const [r, g, b] =
|
||||
h < 60
|
||||
? [c, x, 0]
|
||||
: h < 120
|
||||
? [x, c, 0]
|
||||
: h < 180
|
||||
? [0, c, x]
|
||||
: h < 240
|
||||
? [0, x, c]
|
||||
: h < 300
|
||||
? [x, 0, c]
|
||||
: [c, 0, x]
|
||||
const to255 = (v: number) => Math.max(0, Math.min(255, Math.round((v + m) * 255)))
|
||||
return [to255(r), to255(g), to255(b)]
|
||||
.map((v) => v.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
}
|
||||
|
||||
const hueDist = (a: number, b: number): number => {
|
||||
const d = Math.abs(a - b) % 360
|
||||
return d > 180 ? 360 - d : d
|
||||
}
|
||||
|
||||
/** Low saturation / near black-white counts as neutral (mapped along the dk1↔lt1 axis) */
|
||||
const isNeutral = ({ s, l }: Hsl) => s < 0.15 || l > 0.95 || l < 0.07
|
||||
|
||||
const SRGB_RE = /<a:srgbClr val="([0-9A-Fa-f]{6})"/g
|
||||
|
||||
/** Count explicit srgbClr colors in a batch of slide XML (uppercase hex → occurrence count). */
|
||||
export function collectExplicitColors(xmls: string[]): Map<string, number> {
|
||||
const counts = new Map<string, number>()
|
||||
for (const xml of xmls) {
|
||||
for (const m of xml.matchAll(SRGB_RE)) {
|
||||
const hex = m[1]!.toUpperCase()
|
||||
counts.set(hex, (counts.get(hex) ?? 0) + 1)
|
||||
}
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
/**
|
||||
* Mapping table from explicit colors to new theme colors. Identity mappings are omitted.
|
||||
* Cluster assignment is deterministic: iterated by (occurrence count desc, hex asc).
|
||||
*/
|
||||
export function buildColorMap(counts: Map<string, number>, spec: ThemeSpec): Map<string, string> {
|
||||
const neutralFor = (l: number): string => {
|
||||
const key = l > 0.85 ? 'lt1' : l > 0.55 ? 'lt2' : l > 0.28 ? 'dk2' : 'dk1'
|
||||
return hex6(spec.colors[key] ?? (l > 0.5 ? 'FFFFFF' : '000000'))
|
||||
}
|
||||
const accents = [1, 2, 3, 4, 5, 6]
|
||||
.map((i) => spec.colors[`accent${i}`])
|
||||
.filter((c): c is string => !!c)
|
||||
.map((c) => hexToHsl(c))
|
||||
|
||||
const sorted = [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
|
||||
const clusters: Array<{ hue: number }> = []
|
||||
const map = new Map<string, string>()
|
||||
for (const [hex] of sorted) {
|
||||
const hsl = hexToHsl(hex)
|
||||
let out: string
|
||||
if (isNeutral(hsl)) {
|
||||
out = neutralFor(hsl.l)
|
||||
} else if (accents.length === 0) {
|
||||
continue
|
||||
} else {
|
||||
let idx = clusters.findIndex((c) => hueDist(c.hue, hsl.h) <= 35)
|
||||
if (idx < 0) {
|
||||
clusters.push({ hue: hsl.h })
|
||||
idx = clusters.length - 1
|
||||
}
|
||||
const target = accents[idx % accents.length]!
|
||||
// Target hue + target base saturation, keeping original lightness (shading levels unchanged)
|
||||
out = hslToHex({ h: target.h, s: target.s, l: hsl.l })
|
||||
}
|
||||
if (out !== hex) map.set(hex, out)
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
/** Recolor a slide XML per the mapping table (only <a:srgbClr val> touched). */
|
||||
export function recolorXml(xml: string, map: Map<string, string>): string {
|
||||
if (map.size === 0) return xml
|
||||
return xml.replace(SRGB_RE, (full, hex: string) => {
|
||||
const to = map.get(hex.toUpperCase())
|
||||
return to ? full.replace(hex, to) : full
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Remap all slides' explicit colors onto the theme palette (rewriting archive
|
||||
* entries directly). Requires the model to have no unpersisted edits (caller should
|
||||
* save→reopen first), otherwise dirty elements would overwrite with old colors on
|
||||
* save. Returns the number of distinct colors mapped.
|
||||
*/
|
||||
export function remapDeckColors(opened: OpenedPptx, spec: ThemeSpec): number {
|
||||
const { archive, deck } = opened
|
||||
const paths = deck.slides.map((s) => s.path)
|
||||
const xmls = paths.map((p) => archive.readText(p)).filter((x): x is string => !!x)
|
||||
const map = buildColorMap(collectExplicitColors(xmls), spec)
|
||||
if (map.size === 0) return 0
|
||||
for (const path of paths) {
|
||||
const xml = archive.readText(path)
|
||||
if (!xml) continue
|
||||
const next = recolorXml(xml, map)
|
||||
if (next !== xml) archive.entries.set(path, Buffer.from(next, 'utf8'))
|
||||
}
|
||||
return map.size
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* Theme reading (read-only, never written back).
|
||||
* Provides color scheme and font scheme lookups so inheritance resolution can turn
|
||||
* schemeClr / theme fonts into final values.
|
||||
*/
|
||||
import { XMLParser } from 'fast-xml-parser'
|
||||
import { asXmlNode, type XmlNode } from './xml-utils'
|
||||
|
||||
const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_' })
|
||||
|
||||
export interface Theme {
|
||||
/** clrScheme: dk1/lt1/dk2/lt2/accent1..6/hlink/folHlink → #RRGGBB */
|
||||
colors: Record<string, string>
|
||||
/** fontScheme: major / minor Latin fonts */
|
||||
majorFont?: string
|
||||
minorFont?: string
|
||||
/** fontScheme: major / minor East Asian fonts */
|
||||
majorEaFont?: string
|
||||
minorEaFont?: string
|
||||
/** fontScheme: major / minor Complex Script fonts (Arabic/Hebrew/Thai/Hindi etc.) */
|
||||
majorCsFont?: string
|
||||
minorCsFont?: string
|
||||
/**
|
||||
* fmtScheme templates (referenced by style refs: fillRef/lnRef/effectRef; phClr is
|
||||
* substituted by the referencing side). Each entry is a parsed node (e.g.
|
||||
* { 'a:gradFill': {...} } / { 'a:ln': {...} } / { 'a:effectStyle': {...} }), mapping
|
||||
* to idx 1..3 in original XML order; bgFills map to idx 1001..1003.
|
||||
*/
|
||||
fillStyles?: XmlNode[]
|
||||
lnStyles?: XmlNode[]
|
||||
effectStyles?: XmlNode[]
|
||||
bgFillStyles?: XmlNode[]
|
||||
}
|
||||
|
||||
/** Scan the top-level children (depth 1) of an xml fragment and return each child's full fragment (order preserved). */
|
||||
function topLevelFragments(xml: string): string[] {
|
||||
const out: string[] = []
|
||||
const re = /<(\/?)([a-zA-Z][\w:]*)((?:"[^"]*"|'[^']*'|[^"'>])*?)(\/?)>/g
|
||||
let depth = 0
|
||||
let curStart = -1
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(xml)) !== null) {
|
||||
const closing = m[1] === '/'
|
||||
const selfClose = m[4] === '/'
|
||||
if (!closing && !selfClose) {
|
||||
if (depth === 0) curStart = m.index
|
||||
depth++
|
||||
} else if (closing) {
|
||||
depth--
|
||||
if (depth === 0 && curStart >= 0) out.push(xml.slice(curStart, re.lastIndex))
|
||||
} else if (selfClose && depth === 0) {
|
||||
out.push(xml.slice(m.index, re.lastIndex))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Get the list of inner fragments of <tag>...</tag> and parse each into a regular node (preserving idx order). */
|
||||
function parseStyleList(themeXml: string, tag: string): XmlNode[] | undefined {
|
||||
const m = new RegExp(`<a:${tag}\\b[^>]*>([\\s\\S]*?)</a:${tag}>`).exec(themeXml)
|
||||
if (!m) return undefined
|
||||
const items = topLevelFragments(m[1]!).map((frag) => asXmlNode(parser.parse(frag)))
|
||||
return items.length ? items : undefined
|
||||
}
|
||||
|
||||
function readColorNode(node: unknown): string | undefined {
|
||||
if (!node) return undefined
|
||||
const n = asXmlNode(node)
|
||||
const srgb = asXmlNode(n['a:srgbClr'])
|
||||
if (n['a:srgbClr']) return '#' + String(srgb['@_val']).toUpperCase()
|
||||
const sys = asXmlNode(n['a:sysClr'])
|
||||
if (n['a:sysClr']) return '#' + String(sys['@_lastClr'] ?? '000000').toUpperCase()
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Font typeface attribute of e.g. fontScheme['a:majorFont']['a:latin'] (undefined when absent). */
|
||||
function typeface(scheme: XmlNode, font: string, script: string): string | undefined {
|
||||
const v = asXmlNode(asXmlNode(scheme[font])[script])['@_typeface']
|
||||
return typeof v === 'string' && v ? v : undefined
|
||||
}
|
||||
|
||||
export function parseTheme(themeXml: string): Theme {
|
||||
const doc = asXmlNode(parser.parse(themeXml))
|
||||
const themeEl = asXmlNode(doc['a:theme'] ?? doc.theme)
|
||||
const elements = asXmlNode(themeEl['a:themeElements'])
|
||||
const clrScheme = asXmlNode(elements['a:clrScheme'])
|
||||
const colors: Record<string, string> = {}
|
||||
for (const key of ['dk1', 'lt1', 'dk2', 'lt2', 'accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6', 'hlink', 'folHlink']) {
|
||||
const c = readColorNode(clrScheme['a:' + key])
|
||||
if (c) colors[key] = c
|
||||
}
|
||||
const fontScheme = asXmlNode(elements['a:fontScheme'])
|
||||
const majorFont = typeface(fontScheme, 'a:majorFont', 'a:latin')
|
||||
const minorFont = typeface(fontScheme, 'a:minorFont', 'a:latin')
|
||||
const majorEaFont = typeface(fontScheme, 'a:majorFont', 'a:ea')
|
||||
const minorEaFont = typeface(fontScheme, 'a:minorFont', 'a:ea')
|
||||
const majorCsFont = typeface(fontScheme, 'a:majorFont', 'a:cs')
|
||||
const minorCsFont = typeface(fontScheme, 'a:minorFont', 'a:cs')
|
||||
// fmtScheme templates are parsed in order from raw-text slices (fillStyleLst children mix element types; regular parsing would lose the idx order)
|
||||
const fmtM = /<a:fmtScheme\b[^>]*>[\s\S]*?<\/a:fmtScheme>/.exec(themeXml)
|
||||
const fmt = fmtM?.[0] ?? ''
|
||||
const fillStyles = parseStyleList(fmt, 'fillStyleLst')
|
||||
const lnStyles = parseStyleList(fmt, 'lnStyleLst')
|
||||
const effectStyles = parseStyleList(fmt, 'effectStyleLst')
|
||||
const bgFillStyles = parseStyleList(fmt, 'bgFillStyleLst')
|
||||
return {
|
||||
colors,
|
||||
majorFont,
|
||||
minorFont,
|
||||
majorEaFont,
|
||||
minorEaFont,
|
||||
majorCsFont,
|
||||
minorCsFont,
|
||||
...(fillStyles ? { fillStyles } : {}),
|
||||
...(lnStyles ? { lnStyles } : {}),
|
||||
...(effectStyles ? { effectStyles } : {}),
|
||||
...(bgFillStyles ? { bgFillStyles } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Theme font reference ("+mj-lt" / "+mn-ea" etc.) → final font name.
|
||||
* Values not starting with "+" are returned as-is; returns undefined when the theme has no match.
|
||||
*/
|
||||
export function resolveFontRef(typeface: string | undefined, theme: Theme | undefined): string | undefined {
|
||||
if (!typeface) return undefined
|
||||
if (!typeface.startsWith('+')) return typeface
|
||||
switch (typeface) {
|
||||
case '+mj-lt':
|
||||
return theme?.majorFont
|
||||
case '+mn-lt':
|
||||
return theme?.minorFont
|
||||
case '+mj-ea':
|
||||
return theme?.majorEaFont ?? theme?.majorFont
|
||||
case '+mn-ea':
|
||||
return theme?.minorEaFont ?? theme?.minorFont
|
||||
case '+mj-cs':
|
||||
return theme?.majorCsFont ?? theme?.majorFont
|
||||
case '+mn-cs':
|
||||
return theme?.minorCsFont ?? theme?.minorFont
|
||||
default:
|
||||
return theme?.minorFont
|
||||
}
|
||||
}
|
||||
|
||||
/** schemeClr name (e.g. 'tx1','bg1','accent1','phClr') → final #RRGGBB. */
|
||||
export function resolveSchemeColor(name: string, theme: Theme | undefined, phClr?: string): string | undefined {
|
||||
if (name === 'phClr') return phClr
|
||||
// Standard mapping: tx1→dk1, bg1→lt1, tx2→dk2, bg2→lt2
|
||||
const map: Record<string, string> = { tx1: 'dk1', bg1: 'lt1', tx2: 'dk2', bg2: 'lt2' }
|
||||
const key = map[name] ?? name
|
||||
return theme?.colors[key]
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
/**
|
||||
* pptx-engine data model
|
||||
*
|
||||
* Design principles:
|
||||
* 1. The in-house model is the core asset (Canva-style): rendering / editing /
|
||||
* saving all revolve around it.
|
||||
* 2. Byte-level fidelity: every parseable element carries a dual anchor —
|
||||
* `slideXmlRange` (original XML byte range) + `originalXml` (original slice).
|
||||
* On save, untouched elements pass through as their original bytes.
|
||||
* 3. Inheritance chain pre-resolved: elements carry `resolved` final styles
|
||||
* (merged slide→layout→master→theme); the render layer uses them directly and
|
||||
* never walks inheritance. The original pptx's layout/master/theme are never
|
||||
* written back.
|
||||
* 4. Risky content is passthrough: only a placeholder is shown, original bytes
|
||||
* pass through on save.
|
||||
*
|
||||
* Coordinate unit: EMU (English Metric Unit, 1 inch = 914400 EMU, 1 px@96dpi = 9525 EMU).
|
||||
* Angle unit: 60000ths of a degree (OOXML native), with a convenience `deg` field.
|
||||
*/
|
||||
|
||||
// ── Geometry ───────────────────────────────────────────────────────────
|
||||
|
||||
export interface EmuRect {
|
||||
/** Top-left x (EMU), relative to the containing coordinate system (slide or owning group's child coords) */
|
||||
x: number
|
||||
/** Top-left y (EMU) */
|
||||
y: number
|
||||
/** Width (EMU) */
|
||||
cx: number
|
||||
/** Height (EMU) */
|
||||
cy: number
|
||||
}
|
||||
|
||||
export interface Transform {
|
||||
offset: EmuRect
|
||||
/** Rotation in 1/60000 degree units; deg = rot / 60000 */
|
||||
rot: number
|
||||
flipH: boolean
|
||||
flipV: boolean
|
||||
}
|
||||
|
||||
// ── Color / fill / stroke (inheritance resolved to final values) ────────
|
||||
|
||||
/** Resolved final color: uniform #RRGGBB(AA) or 'none' */
|
||||
export type ResolvedColor = string
|
||||
|
||||
export type Fill =
|
||||
| { type: 'none' }
|
||||
| { type: 'solid'; color: ResolvedColor }
|
||||
| {
|
||||
type: 'gradient'
|
||||
stops: Array<{ pos: number; color: ResolvedColor }>
|
||||
angle?: number
|
||||
/** <a:path path>: circle/rect/shape = radial/path gradient (linear by default) */
|
||||
path?: 'circle' | 'rect' | 'shape'
|
||||
}
|
||||
| { type: 'image'; mediaRef: string; mode?: 'stretch' | 'tile' }
|
||||
| { type: 'pattern'; fg: ResolvedColor; bg: ResolvedColor; preset: string }
|
||||
|
||||
/** OOXML arrowhead size: sm/med/lg (width or length direction), med by default */
|
||||
export type ArrowEndSize = 'sm' | 'med' | 'lg'
|
||||
|
||||
/** Line-end arrow decoration (<a:headEnd>/<a:tailEnd>) */
|
||||
export interface ArrowEnd {
|
||||
/** Arrowhead type */
|
||||
type: 'arrow' | 'triangle' | 'stealth' | 'diamond' | 'oval' | 'none'
|
||||
/** Width size (horizontal, med by default) */
|
||||
w?: ArrowEndSize
|
||||
/** Length size (vertical/depth, med by default) */
|
||||
len?: ArrowEndSize
|
||||
}
|
||||
|
||||
export interface Stroke {
|
||||
fill: Fill
|
||||
/** Line width (EMU) */
|
||||
width: number
|
||||
dash?: string
|
||||
cap?: 'flat' | 'round' | 'square'
|
||||
/** Line head decoration <a:headEnd> (omitted when absent or none) */
|
||||
headEnd?: ArrowEnd
|
||||
/** Line tail decoration <a:tailEnd> (omitted when absent or none) */
|
||||
tailEnd?: ArrowEnd
|
||||
}
|
||||
|
||||
/** Glow <a:glow>: color + radius (EMU) */
|
||||
export interface GlowEffect {
|
||||
color: ResolvedColor
|
||||
radius: number
|
||||
}
|
||||
|
||||
/** Outer shadow <a:outerShdw> (the most common effectLst entry) */
|
||||
export interface ShadowEffect {
|
||||
color: ResolvedColor
|
||||
/** Blur radius (EMU) */
|
||||
blurRad: number
|
||||
/** Offset distance (EMU) */
|
||||
dist: number
|
||||
/** Direction (degrees, clockwise, 0 = right) */
|
||||
dirDeg: number
|
||||
}
|
||||
|
||||
// ── Text ───────────────────────────────────────────────────────────────
|
||||
|
||||
/** A run of contiguous same-format text (maps to <a:r>); line breaks/soft returns split into separate runs or paragraphs */
|
||||
export interface TextRun {
|
||||
text: string
|
||||
bold?: boolean
|
||||
italic?: boolean
|
||||
underline?: boolean
|
||||
/** Original underline style (sng/dbl/wavy…); underline is the display boolean, write-back restores from this */
|
||||
underlineStyle?: string
|
||||
strike?: boolean
|
||||
/** Original strikethrough style (sngStrike/dblStrike); strike is the display boolean, write-back restores from this */
|
||||
strikeStyle?: string
|
||||
/** Font size (pt) */
|
||||
fontSize?: number
|
||||
/** Run has no explicit sz (inherits); rebuild/injected rPr omits sz to avoid baking in the master font size */
|
||||
fontSizeImplicit?: boolean
|
||||
/** Letter spacing <a:rPr spc> (pt, may be negative; PowerPoint stores 1/100pt) */
|
||||
letterSpacing?: number
|
||||
/** Font family (final font name after theme inheritance, for render/editor display) */
|
||||
fontFamily?: string
|
||||
/**
|
||||
* Original <a:latin>/<a:ea> typeface text (incl. +mj-lt/+mn-ea theme refs).
|
||||
* Present = the user has not changed the font: patches keep the original bytes
|
||||
* and regeneration writes the original values back, so CJK/Latin dual fonts and
|
||||
* theme linkage survive; cleared when the user changes the font (along with
|
||||
* fontImplicit)
|
||||
*/
|
||||
latinFont?: string
|
||||
eaFont?: string
|
||||
/** Original <a:cs> typeface (complex-script bucket), written back on the rebuild path */
|
||||
csFont?: string
|
||||
/** Run has no explicit font declaration (inherits/theme); patches don't inject latin/ea when the font is unchanged */
|
||||
fontImplicit?: boolean
|
||||
color?: ResolvedColor
|
||||
/** color is display-only (from schemeClr/inheritance, not an explicit run srgbClr);
|
||||
* the patch path won't write srgbClr from it, avoiding baking in theme colors and breaking theme switches */
|
||||
colorFollowsTheme?: boolean
|
||||
/** rPr has no solidFill at all (color purely inherited); the rebuild path writes no fill.
|
||||
* Explicit schemeClr is not included here (materialized as srgbClr on rebuild to keep visuals) */
|
||||
colorInherited?: boolean
|
||||
/** Superscript/subscript baseline offset (%) */
|
||||
baseline?: number
|
||||
/** Hyperlink target, rId resolved at parse: external url, or "slide:N" (0-based) for in-doc jumps */
|
||||
hyperlink?: string
|
||||
/** Run-level <a:hlinkClick> original r:id/action/tooltip (written back verbatim; absent on a run
|
||||
* whose hyperlink was set this session until ensureRunLinkRels allocates the relationship) */
|
||||
hyperlinkRId?: string
|
||||
hyperlinkAction?: string
|
||||
hyperlinkTooltip?: string
|
||||
/** underline=true came from hlink styling, not an explicit u attr; write-back never emits u from it */
|
||||
underlineImplicit?: boolean
|
||||
/** Dynamic field <a:fld type="…"> (slidenum/datetime…); text is the cached value */
|
||||
field?: string
|
||||
/** Text outline <a:rPr><a:ln> (common in WordArt); width in EMU */
|
||||
outline?: { color: ResolvedColor; widthEmu: number }
|
||||
}
|
||||
|
||||
export type TextAlign = 'left' | 'center' | 'right' | 'justify'
|
||||
|
||||
export interface Paragraph {
|
||||
runs: TextRun[]
|
||||
align?: TextAlign
|
||||
/** Indent level (bullet level) */
|
||||
level?: number
|
||||
/** Line spacing (%, 100 = single) or absolute (pt, via lineExact) */
|
||||
lineHeight?: number
|
||||
lineExact?: number
|
||||
/** Space before/after (pt, spcPts) or as a percentage of single line height (spcPct, 100 = one line) */
|
||||
spaceBefore?: number
|
||||
spaceAfter?: number
|
||||
spaceBeforePct?: number
|
||||
spaceAfterPct?: number
|
||||
bullet?: {
|
||||
type: 'none' | 'char' | 'number'
|
||||
char?: string
|
||||
color?: ResolvedColor
|
||||
/** <a:buFont> typeface (symbol fonts like Wingdings) */
|
||||
font?: string
|
||||
/** <a:buSzPct> (%, 100 = same size as text) */
|
||||
sizePct?: number
|
||||
/** <a:buAutoNum type> (arabicPeriod/romanLcParen…) */
|
||||
numType?: string
|
||||
}
|
||||
/** Paragraph left indent marL (EMU) */
|
||||
marL?: number
|
||||
/** First-line indent (EMU, negative = hanging indent, common with bullets) */
|
||||
indent?: number
|
||||
/**
|
||||
* Which paragraph properties come from an explicit <a:pPr> (rather than display
|
||||
* values inherited from lstStyle/placeholder/master). The rebuild path writes
|
||||
* only explicit items to avoid baking in inheritance; paragraphs produced by
|
||||
* parse always have this field, newly created elements may omit it (omitted =
|
||||
* all treated as explicit). Set the matching bit when the user edits a property.
|
||||
*/
|
||||
pPrExplicit?: {
|
||||
align?: boolean
|
||||
lnSpc?: boolean
|
||||
spcBef?: boolean
|
||||
spcAft?: boolean
|
||||
bullet?: boolean
|
||||
marL?: boolean
|
||||
indent?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
/** Text-box body-level properties */
|
||||
export interface TextBody {
|
||||
paragraphs: Paragraph[]
|
||||
/** Vertical alignment */
|
||||
anchor?: 'top' | 'middle' | 'bottom'
|
||||
/** Insets (EMU): left/top/right/bottom */
|
||||
insets?: { l: number; t: number; r: number; b: number }
|
||||
/** Autofit: none | shrink font to fit | resize box */
|
||||
autofit?: 'none' | 'shrink' | 'resize'
|
||||
/** <a:normAutofit fontScale>: font-shrink ratio precomputed by PowerPoint (0-1), used directly for rendering */
|
||||
fontScale?: number
|
||||
/** <a:normAutofit lnSpcReduction>: line-spacing reduction ratio (0-1, at most 0.2) */
|
||||
lnSpcReduction?: number
|
||||
wrap?: boolean
|
||||
/** <a:bodyPr vert>: vertical text (Japanese tategaki etc.). Read-only display — write-back keeps original bodyPr bytes */
|
||||
vert?: 'eaVert' | 'vert' | 'vert270' | 'wordArtVert'
|
||||
}
|
||||
|
||||
// ── Elements ───────────────────────────────────────────────────────────
|
||||
|
||||
export type ElementType =
|
||||
| 'text' // text box (may be text-only, no fill)
|
||||
| 'shape' // autoshape (may carry text)
|
||||
| 'picture' // picture
|
||||
| 'group' // group
|
||||
| 'table' // table (a:tbl inside a graphicFrame; read-only render, saved as original bytes)
|
||||
| 'chart' // chart (graphicFrame referencing a chart part; read-only render, saved as original bytes)
|
||||
| 'passthrough' // protected block (smartart/ole/connector/animation anchor etc., display-only for now)
|
||||
|
||||
/** Dual anchor — the core of byte-level fidelity */
|
||||
export interface ByteAnchor {
|
||||
/** Index of this element among the top-level elements of its slideN.xml (0-based) */
|
||||
spIndex: number
|
||||
/** Original XML slice (passed through verbatim on save when untouched) */
|
||||
originalXml: string
|
||||
/** Range [start, end) of the original XML within the slideN.xml string */
|
||||
range: [number, number]
|
||||
/** Non-shape spTree bytes between this shape and the next (mc:AlternateContent etc.), replayed verbatim on rebuild */
|
||||
gapAfter?: string
|
||||
}
|
||||
|
||||
/** Paragraph-property dirty flags: which pPr groups need a surgical patch (set by element-level paragraph formatting ops). */
|
||||
export interface PPrDirty {
|
||||
bullet?: boolean
|
||||
/** Indent level lvl (Tab/⇧Tab multi-level lists) */
|
||||
level?: boolean
|
||||
lnSpc?: boolean
|
||||
spcBef?: boolean
|
||||
spcAft?: boolean
|
||||
align?: boolean
|
||||
/** marL + indent as a pair (bullet indent linkage) */
|
||||
indents?: boolean
|
||||
/** Restrict the patch to these paragraph indices; absent = all paragraphs */
|
||||
paraIndices?: number[]
|
||||
}
|
||||
|
||||
interface ElementBase {
|
||||
id: string
|
||||
type: ElementType
|
||||
anchor: ByteAnchor
|
||||
transform: Transform
|
||||
/** Editor dirty flag: when true, save must regenerate OOXML; otherwise originalXml passes through */
|
||||
dirty?: boolean
|
||||
/** Geometry dirty flag: when true, save patches <a:xfrm> in place (orthogonal to text patches) */
|
||||
dirtyTransform?: boolean
|
||||
/** Fill dirty flag: when true, save patches the spPr fill node in place */
|
||||
dirtyFill?: boolean
|
||||
/** Stroke dirty flag: when true, save patches the spPr <a:ln> in place */
|
||||
dirtyStroke?: boolean
|
||||
/** Picture-crop dirty flag: when true, save patches p:blipFill's <a:srcRect> in place */
|
||||
dirtySrcRect?: boolean
|
||||
/** Paragraph-property dirty flags: on save, surgically patch pPr per <a:p> (run bytes untouched) */
|
||||
dirtyPPr?: PPrDirty
|
||||
/** Placeholder type (title/body/…), located via layout/master inheritance */
|
||||
placeholder?: string
|
||||
name?: string
|
||||
/**
|
||||
* <p:cNvPr descr="…">: editor-owned metadata payload (e.g. vector points of
|
||||
* freehand ink), written back verbatim with originalXml on save so the editable
|
||||
* state can be restored on reopen.
|
||||
*/
|
||||
descr?: string
|
||||
/**
|
||||
* <p:cNvPr id>: matching key between group children and slices of the group's
|
||||
* originalXml (for in-group editing). parseGroup iterates children grouped by
|
||||
* tag, which differs from document order, so index alignment is not possible.
|
||||
*/
|
||||
nvId?: string
|
||||
/** Connector attachment <a:stCxn>/<a:endCxn>: target shape cNvPr id + connection point index (for move-following) */
|
||||
connection?: {
|
||||
start?: { id: number; idx: number }
|
||||
end?: { id: number; idx: number }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <a:custGeom> custom geometry (read-only render; save passes originalXml through,
|
||||
* never written back). Each field is a normalized SVG path (M/L/C/Q/Z, coords 0..1
|
||||
* relative to the w/h declared by <a:path>; arcTo converted to cubic); the render
|
||||
* layer scales it to the element frame.
|
||||
*/
|
||||
export interface CustomGeometry {
|
||||
/** Main fill+stroke path */
|
||||
path?: string
|
||||
/** stroke="0" subpath: fill only (e.g. the pie sector of arc shapes) */
|
||||
fillPath?: string
|
||||
/** fill="none" subpath: stroke only (e.g. guide arcs) */
|
||||
strokePath?: string
|
||||
}
|
||||
|
||||
export interface TextElement extends ElementBase {
|
||||
type: 'text' | 'shape'
|
||||
/** Shape's preset geometry (rect/ellipse/roundRect/…); absent for text */
|
||||
presetGeometry?: string
|
||||
/** Preset geometry adjust values <a:avLst>: e.g. roundRect's adj (1/1000 %, 50000 = pill) */
|
||||
adjust?: Record<string, number>
|
||||
/** Custom geometry (mutually exclusive with presetGeometry) */
|
||||
customGeometry?: CustomGeometry
|
||||
fill?: Fill
|
||||
stroke?: Stroke
|
||||
shadow?: ShadowEffect
|
||||
glow?: GlowEffect
|
||||
text?: TextBody
|
||||
}
|
||||
|
||||
export interface PictureElement extends ElementBase {
|
||||
type: 'picture'
|
||||
/** Picture media path inside the zip (word/ppt/media/imageN.ext) */
|
||||
mediaRef: string
|
||||
/** Decoded dataURL (for rendering, may be lazy-loaded) */
|
||||
dataUrl?: string
|
||||
/** Source crop <a:srcRect>: fraction cropped from each edge (0..1) */
|
||||
srcRect?: { l: number; t: number; r: number; b: number }
|
||||
/** Whole-image opacity <a:blip><a:alphaModFix amt> (0..1, 1 = opaque; default 1) */
|
||||
opacity?: number
|
||||
/** Soft edges <a:softEdge rad> (EMU feather radius) */
|
||||
softEdge?: number
|
||||
/**
|
||||
* Audio/video (a:videoFile/a:audioFile under p:nvPr): blipFill is the poster
|
||||
* frame; target is the media file's zip path or an external URL (external).
|
||||
*/
|
||||
media?: { kind: 'video' | 'audio'; target?: string; external?: boolean }
|
||||
/** Picture outline geometry <a:prstGeom> (ellipse avatars/rounded-corner frames etc. from picture styles; rect omitted) */
|
||||
presetGeometry?: string
|
||||
adjust?: Record<string, number>
|
||||
fill?: Fill
|
||||
stroke?: Stroke
|
||||
shadow?: ShadowEffect
|
||||
glow?: GlowEffect
|
||||
}
|
||||
|
||||
export interface GroupElement extends ElementBase {
|
||||
type: 'group'
|
||||
children: SlideElement[]
|
||||
/** Child coordinate system (<a:chOff>/<a:chExt>), used to map child coords to the parent */
|
||||
childOffset?: EmuRect
|
||||
}
|
||||
|
||||
export interface PassthroughElement extends ElementBase {
|
||||
type: 'passthrough'
|
||||
/** Protection reason category, for the UI placeholder chip */
|
||||
kind: 'chart' | 'smartart' | 'table' | 'ole' | 'connector' | 'media' | 'unknown'
|
||||
/**
|
||||
* SmartArt read-only preview: shapes parsed from the pptx's built-in prerendered
|
||||
* drawing part (diagrams/drawingN.xml), coordinate origin (0,0), size ≈ transform
|
||||
* ext (the diagram canvas). Render-only; save still uses the anchor's original bytes.
|
||||
*/
|
||||
previewShapes?: SlideElement[]
|
||||
/** OLE read-only preview: the preview picture embedded in the graphicFrame (stretched to fill the frame when rendering). */
|
||||
previewPicture?: PictureElement
|
||||
}
|
||||
|
||||
// ── Table (p:graphicFrame → a:tbl) ───────────────────────────────────
|
||||
|
||||
/** Cell borders on all four edges (no border by default; table-style inheritance not yet supported). */
|
||||
export interface TableCellBorders {
|
||||
l?: Stroke
|
||||
r?: Stroke
|
||||
t?: Stroke
|
||||
b?: Stroke
|
||||
}
|
||||
|
||||
export interface TableCell {
|
||||
/** Cell text (reuses the TextBody model; anchor/insets already overridden per tcPr) */
|
||||
text?: TextBody
|
||||
/** Cell fill (explicit tcPr fill; table-style inheritance not yet supported) */
|
||||
fill?: Fill
|
||||
borders?: TableCellBorders
|
||||
/** Horizontal merge span in columns (gridSpan, default 1) */
|
||||
gridSpan?: number
|
||||
/** Vertical merge span in rows (rowSpan, default 1) */
|
||||
rowSpan?: number
|
||||
/** Placeholder cell covered by a merge (hMerge/vMerge), not rendered */
|
||||
merged?: boolean
|
||||
}
|
||||
|
||||
export interface TableElement extends ElementBase {
|
||||
type: 'table'
|
||||
/** Column widths (EMU, from a:tblGrid/a:gridCol) */
|
||||
colWidths: number[]
|
||||
/** Row heights (EMU, from a:tr@h) */
|
||||
rowHeights: number[]
|
||||
/** rows[r][c], aligned with rowHeights/colWidths */
|
||||
rows: TableCell[][]
|
||||
/** tblPr's header-row/banded-rows toggles (echoed in the Ribbon's "Table Design") */
|
||||
styleFlags?: { firstRow: boolean; bandRow: boolean }
|
||||
}
|
||||
|
||||
// ── Chart (p:graphicFrame → c:chart reference) ───────────────────────
|
||||
|
||||
export interface ChartElement extends ElementBase {
|
||||
type: 'chart'
|
||||
/** Parsed chart data model (see chart.ts) */
|
||||
chart: import('./chart').ChartModel
|
||||
}
|
||||
|
||||
export type SlideElement =
|
||||
TextElement | PictureElement | GroupElement | TableElement | ChartElement | PassthroughElement
|
||||
|
||||
// ── Slide / presentation ───────────────────────────────────────────────
|
||||
|
||||
export interface Slide {
|
||||
/** Path inside the zip, e.g. ppt/slides/slide1.xml */
|
||||
path: string
|
||||
/** Full original slideN.xml string (the base for save patches) */
|
||||
originalXml: string
|
||||
/** Body prefix / suffix (bytes outside the <p:spTree> content, kept verbatim on save) */
|
||||
bodyPrefix: string
|
||||
bodySuffix: string
|
||||
elements: SlideElement[]
|
||||
/** Structure dirty flag: set after element add/remove; save rebuilds the whole slide (complements element-level dirty) */
|
||||
structureDirty?: boolean
|
||||
/** Inheritance sources (for rendering, never written back) */
|
||||
layoutPath?: string
|
||||
masterPath?: string
|
||||
/** Background (inheritance resolved) */
|
||||
background?: Fill
|
||||
/**
|
||||
* master/layout decoration layer (read-only render, never written back):
|
||||
* non-placeholder concrete shapes on the master (logos/color bars) + enabled
|
||||
* footer/slide-number/date placeholders. Drawn below elements, above background.
|
||||
*/
|
||||
decorations?: SlideElement[]
|
||||
}
|
||||
|
||||
export interface SlideSize {
|
||||
cx: number // EMU
|
||||
cy: number // EMU
|
||||
}
|
||||
|
||||
export interface SlideDeck {
|
||||
/** Bytes of every zip entry of the original pptx (untouched entries written back byte-for-byte on save) */
|
||||
// The actual byte storage is held by zip.ts's PackageArchive; only parse results live here
|
||||
slides: Slide[]
|
||||
size: SlideSize
|
||||
/** Original SHA-256 (verified before save to ensure the file was not changed externally) */
|
||||
originalHash: string
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/** XML escaping utilities (same as docx-engine's, used for patch generation). */
|
||||
|
||||
/**
|
||||
* A fast-xml-parser element node: attributes are '@_'-prefixed, text is '#text',
|
||||
* child elements are nested nodes (a single child collapses to an object instead
|
||||
* of an array). Parse trees are inherently untyped, so readers probe them through
|
||||
* the narrowing helpers below instead of `any`.
|
||||
*/
|
||||
export type XmlNode = Record<string, unknown>
|
||||
|
||||
/** View an unknown parse-tree value as an element node; non-objects read as empty. */
|
||||
export function asXmlNode(v: unknown): XmlNode {
|
||||
return typeof v === 'object' && v !== null ? (v as XmlNode) : {}
|
||||
}
|
||||
|
||||
/** Normalize fast-xml-parser's single-child collapse: always get an array of element nodes. */
|
||||
export function xmlArray(v: unknown): XmlNode[] {
|
||||
if (Array.isArray(v)) return v.map(asXmlNode)
|
||||
return v ? [asXmlNode(v)] : []
|
||||
}
|
||||
|
||||
export function escapeXmlText(text: string): string {
|
||||
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||||
}
|
||||
|
||||
export function escapeXmlAttr(text: string): string {
|
||||
return escapeXmlText(text).replace(/"/g, '"')
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* pptx package management — open the zip, archive the original by SHA-256, and read
|
||||
* parts and .rels.
|
||||
*
|
||||
* Byte fidelity: PackageArchive holds the original bytes of every entry; on save,
|
||||
* unmodified entries are written back byte-for-byte (handled by the patch layer).
|
||||
* This module only handles reading and metadata.
|
||||
*/
|
||||
import JSZip from 'jszip'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { XMLParser } from 'fast-xml-parser'
|
||||
import type { SlideSize } from './types'
|
||||
import { asXmlNode, xmlArray } from './xml-utils'
|
||||
|
||||
const relsParser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
attributeNamePrefix: '@_',
|
||||
isArray: (name) => name === 'Relationship' || name === 'sldId' || name === 'Override',
|
||||
})
|
||||
|
||||
export interface Relationship {
|
||||
id: string
|
||||
type: string
|
||||
target: string
|
||||
targetMode?: string
|
||||
}
|
||||
|
||||
export class PackageArchive {
|
||||
private constructor(
|
||||
private readonly zip: JSZip,
|
||||
/** Original bytes of every entry, keyed by path inside the zip */
|
||||
readonly entries: Map<string, Uint8Array>,
|
||||
readonly originalHash: string,
|
||||
) {}
|
||||
|
||||
static async open(bytes: Uint8Array): Promise<PackageArchive> {
|
||||
const originalHash = createHash('sha256').update(bytes).digest('hex')
|
||||
const zip = await JSZip.loadAsync(bytes)
|
||||
const entries = new Map<string, Uint8Array>()
|
||||
const names = Object.keys(zip.files)
|
||||
for (const name of names) {
|
||||
const file = zip.files[name]
|
||||
if (file.dir) continue
|
||||
entries.set(name, await file.async('uint8array'))
|
||||
}
|
||||
return new PackageArchive(zip, entries, originalHash)
|
||||
}
|
||||
|
||||
has(path: string): boolean {
|
||||
return this.entries.has(path)
|
||||
}
|
||||
|
||||
/** Read a part as a UTF-8 string (for XML parts). */
|
||||
readText(path: string): string | null {
|
||||
const bytes = this.entries.get(path)
|
||||
if (!bytes) return null
|
||||
return Buffer.from(bytes).toString('utf8')
|
||||
}
|
||||
|
||||
readBytes(path: string): Uint8Array | null {
|
||||
return this.entries.get(path) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a part's relationships file. partPath e.g. 'ppt/slides/slide1.xml' →
|
||||
* 'ppt/slides/_rels/slide1.xml.rels'.
|
||||
*/
|
||||
readRels(partPath: string): Map<string, Relationship> {
|
||||
const relsPath = relsPathFor(partPath)
|
||||
const rels = new Map<string, Relationship>()
|
||||
const xml = this.readText(relsPath)
|
||||
if (!xml) return rels
|
||||
const doc = asXmlNode(relsParser.parse(xml))
|
||||
const list = asXmlNode(doc.Relationships).Relationship
|
||||
for (const r of xmlArray(list)) {
|
||||
const id = String(r['@_Id'] ?? '')
|
||||
rels.set(id, {
|
||||
id,
|
||||
type: String(r['@_Type'] ?? ''),
|
||||
target: String(r['@_Target'] ?? ''),
|
||||
...(r['@_TargetMode'] != null ? { targetMode: String(r['@_TargetMode']) } : {}),
|
||||
})
|
||||
}
|
||||
return rels
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the presentation's slide size and the slide part paths in order.
|
||||
*/
|
||||
readPresentation(): { size: SlideSize; slidePaths: string[] } {
|
||||
const presXml = this.readText('ppt/presentation.xml')
|
||||
if (!presXml) throw new Error('pptx: missing ppt/presentation.xml')
|
||||
|
||||
const parser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
attributeNamePrefix: '@_',
|
||||
isArray: (name) => name === 'p:sldId',
|
||||
})
|
||||
const pres = asXmlNode(parser.parse(presXml))
|
||||
const rootRaw = pres['p:presentation'] ?? pres.presentation
|
||||
if (!rootRaw) throw new Error('pptx: malformed presentation.xml')
|
||||
const root = asXmlNode(rootRaw)
|
||||
|
||||
// Slide size
|
||||
const szRaw = root['p:sldSz'] ?? root.sldSz
|
||||
const sz = szRaw ? asXmlNode(szRaw) : null
|
||||
const size: SlideSize = {
|
||||
cx: sz ? parseInt(String(sz['@_cx']), 10) : 9144000,
|
||||
cy: sz ? parseInt(String(sz['@_cy']), 10) : 6858000,
|
||||
}
|
||||
|
||||
// Slide order: presentation.xml.rels maps r:id to slide parts
|
||||
const rels = this.readRels('ppt/presentation.xml')
|
||||
const sldIdLst = asXmlNode(root['p:sldIdLst'] ?? root.sldIdLst)
|
||||
const slidePaths: string[] = []
|
||||
for (const id of xmlArray(sldIdLst['p:sldId'])) {
|
||||
const rId = id['@_r:id'] ?? id['@_id']
|
||||
if (!rId) continue
|
||||
const rel = rels.get(String(rId))
|
||||
if (!rel) continue
|
||||
slidePaths.push(resolveTarget('ppt/presentation.xml', rel.target))
|
||||
}
|
||||
return { size, slidePaths }
|
||||
}
|
||||
|
||||
/** Resolve a slide's layout / master part paths (via the rels chain). */
|
||||
resolveSlideChain(slidePath: string): { layoutPath?: string; masterPath?: string; themePath?: string } {
|
||||
const slideRels = this.readRels(slidePath)
|
||||
let layoutPath: string | undefined
|
||||
for (const rel of slideRels.values()) {
|
||||
if (rel.type.endsWith('/slideLayout')) {
|
||||
layoutPath = resolveTarget(slidePath, rel.target)
|
||||
break
|
||||
}
|
||||
}
|
||||
let masterPath: string | undefined
|
||||
let themePath: string | undefined
|
||||
if (layoutPath) {
|
||||
const layoutRels = this.readRels(layoutPath)
|
||||
for (const rel of layoutRels.values()) {
|
||||
if (rel.type.endsWith('/slideMaster')) {
|
||||
masterPath = resolveTarget(layoutPath, rel.target)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (masterPath) {
|
||||
const masterRels = this.readRels(masterPath)
|
||||
for (const rel of masterRels.values()) {
|
||||
if (rel.type.endsWith('/theme')) {
|
||||
themePath = resolveTarget(masterPath, rel.target)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return { layoutPath, masterPath, themePath }
|
||||
}
|
||||
}
|
||||
|
||||
/** 'ppt/slides/slide1.xml' → 'ppt/slides/_rels/slide1.xml.rels' */
|
||||
export function relsPathFor(partPath: string): string {
|
||||
const idx = partPath.lastIndexOf('/')
|
||||
const dir = idx >= 0 ? partPath.slice(0, idx) : ''
|
||||
const file = idx >= 0 ? partPath.slice(idx + 1) : partPath
|
||||
return `${dir ? dir + '/' : ''}_rels/${file}.rels`
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a relative target into an absolute path inside the zip.
|
||||
* basePart is the referencing part's path (its directory is the base); target may be
|
||||
* something like '../slideLayouts/slideLayout1.xml'.
|
||||
*/
|
||||
export function resolveTarget(basePart: string, target: string): string {
|
||||
if (target.startsWith('/')) return target.slice(1)
|
||||
const baseDir = basePart.slice(0, basePart.lastIndexOf('/'))
|
||||
const parts = baseDir.split('/').filter(Boolean)
|
||||
for (const seg of target.split('/')) {
|
||||
if (seg === '.' || seg === '') continue
|
||||
if (seg === '..') parts.pop()
|
||||
else parts.push(seg)
|
||||
}
|
||||
return parts.join('/')
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* Unit tests for pure geometry align/distribute functions (alignRects / distributeRects).
|
||||
* No IO, no model dependency; verifies correctness of 6 alignments + 2 distributions.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { alignRects, distributeRects } from '../src/align'
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const R = (x: number, y: number, w: number, h: number) => ({ x, y, w, h })
|
||||
|
||||
// ── Alignment tests ───────────────────────────────────────────────────────────
|
||||
|
||||
describe('alignRects', () => {
|
||||
describe('multi-select (no container — aligns to bounding box)', () => {
|
||||
const rects = [R(100, 200, 50, 30), R(300, 100, 80, 60)]
|
||||
|
||||
it('left: all elements x = bounding box left edge', () => {
|
||||
const result = alignRects(rects, 'left', null)
|
||||
expect(result[0]!.x).toBe(100)
|
||||
expect(result[1]!.x).toBe(100)
|
||||
// y unchanged
|
||||
expect(result[0]!.y).toBe(200)
|
||||
expect(result[1]!.y).toBe(100)
|
||||
})
|
||||
|
||||
it('right: all elements right edge = bounding box right edge', () => {
|
||||
const result = alignRects(rects, 'right', null)
|
||||
// bbox right = 300+80 = 380; el0 right = x+50 → x = 380-50 = 330
|
||||
expect(result[0]!.x).toBe(330)
|
||||
// el1 right = x+80 → x = 380-80 = 300 (unchanged)
|
||||
expect(result[1]!.x).toBe(300)
|
||||
})
|
||||
|
||||
it('center-h: all elements centered horizontally on bounding box', () => {
|
||||
const result = alignRects(rects, 'center-h', null)
|
||||
// bbox x=100, w=280 → center x=100+280/2=240; el0: 240-50/2=215
|
||||
expect(result[0]!.x).toBe(215)
|
||||
// el1: 240-80/2=200
|
||||
expect(result[1]!.x).toBe(200)
|
||||
})
|
||||
|
||||
it('top: all elements y = bounding box top edge', () => {
|
||||
const result = alignRects(rects, 'top', null)
|
||||
expect(result[0]!.y).toBe(100)
|
||||
expect(result[1]!.y).toBe(100)
|
||||
})
|
||||
|
||||
it('bottom: all elements bottom edge = bounding box bottom edge', () => {
|
||||
const result = alignRects(rects, 'bottom', null)
|
||||
// bbox bottom = max(200+30, 100+60) = 230; el0: 230-30=200; el1: 230-60=170
|
||||
expect(result[0]!.y).toBe(200)
|
||||
expect(result[1]!.y).toBe(170)
|
||||
})
|
||||
|
||||
it('center-v: all elements vertically centered on bounding box', () => {
|
||||
const result = alignRects(rects, 'center-v', null)
|
||||
// bbox y=100, h=130 → center y=100+130/2=165; el0: 165-30/2=150; el1: 165-60/2=135
|
||||
expect(result[0]!.y).toBe(150)
|
||||
expect(result[1]!.y).toBe(135)
|
||||
})
|
||||
})
|
||||
|
||||
describe('single-select (container = slide page rect)', () => {
|
||||
const slide = R(0, 0, 1280, 720)
|
||||
const rects = [R(100, 100, 200, 100)]
|
||||
|
||||
it('left aligns to slide left', () => {
|
||||
const result = alignRects(rects, 'left', slide)
|
||||
expect(result[0]!.x).toBe(0)
|
||||
})
|
||||
|
||||
it('right aligns to slide right edge', () => {
|
||||
const result = alignRects(rects, 'right', slide)
|
||||
expect(result[0]!.x).toBe(1280 - 200)
|
||||
})
|
||||
|
||||
it('center-h centers on slide', () => {
|
||||
const result = alignRects(rects, 'center-h', slide)
|
||||
expect(result[0]!.x).toBe((1280 - 200) / 2)
|
||||
})
|
||||
|
||||
it('top aligns to slide top', () => {
|
||||
const result = alignRects(rects, 'top', slide)
|
||||
expect(result[0]!.y).toBe(0)
|
||||
})
|
||||
|
||||
it('bottom aligns to slide bottom edge', () => {
|
||||
const result = alignRects(rects, 'bottom', slide)
|
||||
expect(result[0]!.y).toBe(720 - 100)
|
||||
})
|
||||
|
||||
it('center-v centers on slide vertically', () => {
|
||||
const result = alignRects(rects, 'center-v', slide)
|
||||
expect(result[0]!.y).toBe((720 - 100) / 2)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// ── Distribution tests ────────────────────────────────────────────────────────
|
||||
|
||||
describe('distributeRects', () => {
|
||||
it('horizontal: 3 equal-width rects distribute evenly', () => {
|
||||
// a: x=0,w=50 b: x=200,w=50 c: x=300,w=50 → span=350, gap=(350-150)/2=100
|
||||
// sorted: a(0), b(200), c(300)
|
||||
// first=a at 0, cursor: a→50, gap=100, b→150, c→300
|
||||
const rects = [R(0, 0, 50, 20), R(200, 0, 50, 20), R(300, 0, 50, 20)]
|
||||
const result = distributeRects(rects, 'horizontal')
|
||||
const xs = result.map((r) => r.x).sort((a, b) => a - b)
|
||||
expect(xs[0]).toBe(0)
|
||||
expect(xs[1]).toBe(150)
|
||||
expect(xs[2]).toBe(300)
|
||||
})
|
||||
|
||||
it('vertical: 3 equal-height rects distribute evenly', () => {
|
||||
const rects = [R(0, 0, 20, 50), R(0, 200, 20, 50), R(0, 300, 20, 50)]
|
||||
const result = distributeRects(rects, 'vertical')
|
||||
const ys = result.map((r) => r.y).sort((a, b) => a - b)
|
||||
expect(ys[0]).toBe(0)
|
||||
expect(ys[1]).toBe(150)
|
||||
expect(ys[2]).toBe(300)
|
||||
})
|
||||
|
||||
it('with < 3 elements returns original positions unchanged', () => {
|
||||
const rects = [R(10, 20, 50, 30), R(100, 200, 50, 30)]
|
||||
const result = distributeRects(rects, 'horizontal')
|
||||
expect(result[0]).toEqual({ x: 10, y: 20 })
|
||||
expect(result[1]).toEqual({ x: 100, y: 200 })
|
||||
})
|
||||
|
||||
it('horizontal: 4 variable-width rects distribute evenly', () => {
|
||||
// a: x=0,w=30 b: x=100,w=40 c: x=200,w=20 d: x=300,w=50
|
||||
// sorted by x: a,b,c,d
|
||||
// span = 350; totalWidth = 140; gap = (350-140)/3 = 70
|
||||
// positions: a=0, b=0+30+70=100, c=100+40+70=210, d=210+20+70=300
|
||||
const rects = [R(0, 0, 30, 20), R(100, 0, 40, 20), R(200, 0, 20, 20), R(300, 0, 50, 20)]
|
||||
const result = distributeRects(rects, 'horizontal')
|
||||
const xs = result.map((r) => r.x)
|
||||
expect(xs[0]).toBe(0) // a stays
|
||||
expect(xs[1]).toBeCloseTo(100) // b
|
||||
expect(xs[2]).toBeCloseTo(210) // c
|
||||
expect(xs[3]).toBe(300) // d stays
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* Incremental animation write-back: appends and single edits at the tail use surgical patches,
|
||||
* keeping original bytes of unmodeled timing nodes; delete/reorder/trigger changes fall back to full rebuild.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
buildTimingXml,
|
||||
patchSlideTimingIncrementalXml,
|
||||
patchSlideTimingXml,
|
||||
readSlideTimingXml,
|
||||
type SlideAnimation,
|
||||
} from '../src/animation'
|
||||
|
||||
const A1: SlideAnimation = {
|
||||
spid: 4,
|
||||
effect: 'fade',
|
||||
trigger: 'onClick',
|
||||
durationMs: 500,
|
||||
delayMs: 0,
|
||||
}
|
||||
const A2: SlideAnimation = {
|
||||
spid: 5,
|
||||
effect: 'flyIn',
|
||||
trigger: 'onClick',
|
||||
durationMs: 1000,
|
||||
delayMs: 0,
|
||||
}
|
||||
|
||||
/** Injects an unmodeled interactive sequence into our generated timing (skeleton of a PowerPoint trigger animation). */
|
||||
const EXOTIC =
|
||||
'<p:seq concurrent="1" nextAc="none"><p:cTn id="900" restart="whenNotActive" fill="hold" evtFilter="cancelBubble" nodeType="interactiveSeq">' +
|
||||
'<p:stCondLst><p:cond evt="onClick" delay="0"><p:tgtEl><p:spTgt spid="99"/></p:tgtEl></p:cond></p:stCondLst>' +
|
||||
'<p:childTnLst/></p:cTn></p:seq>'
|
||||
|
||||
/** bodySuffix skeleton: clrMapOvr + timing. */
|
||||
function bodySuffixWith(timing: string): string {
|
||||
return `<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>${timing}</p:sld>`
|
||||
}
|
||||
|
||||
/** Inject an exotic node into timing (after mainSeq, inside tmRoot childTnLst). */
|
||||
function withExotic(timing: string): string {
|
||||
const at = timing.indexOf('</p:seq>') + '</p:seq>'.length
|
||||
return timing.slice(0, at) + EXOTIC + timing.slice(at)
|
||||
}
|
||||
|
||||
describe('patchSlideTimingIncrementalXml', () => {
|
||||
it('append animation: original effects and unmodeled nodes keep their bytes, new group attached at the end of mainSeq', () => {
|
||||
const body = bodySuffixWith(withExotic(buildTimingXml([A1])))
|
||||
const out = patchSlideTimingIncrementalXml(body, [A1, A2])
|
||||
expect(out).not.toBeNull()
|
||||
expect(out!).toContain(EXOTIC) // unmodeled node kept as-is
|
||||
const anims = readSlideTimingXml(out!)
|
||||
expect(anims.length).toBe(2)
|
||||
expect(anims[1]).toMatchObject({ spid: 5, effect: 'flyIn' })
|
||||
// Original A1 effect cTn bytes untouched (the par buildTimingXml generated separately is still there)
|
||||
const a1Par = /<p:cTn[^>]*presetClass="entr"[^>]*>/.exec(buildTimingXml([A1]))![0]
|
||||
expect(out!).toContain(a1Par)
|
||||
// bldP appended
|
||||
expect(out!).toContain('<p:bldP spid="5" grpId="0"/>')
|
||||
})
|
||||
|
||||
it('appended cTn ids do not clash with existing ones', () => {
|
||||
const body = bodySuffixWith(withExotic(buildTimingXml([A1]))) // exotic contains id="900"
|
||||
const out = patchSlideTimingIncrementalXml(body, [A1, A2])!
|
||||
const ids = [...out.matchAll(/\bid="(\d+)"/g)].map((m) => Number(m[1]))
|
||||
expect(new Set(ids).size).toBe(ids.length)
|
||||
expect(Math.max(...ids)).toBeGreaterThan(900)
|
||||
})
|
||||
|
||||
it('single tail edit: only that effect par replaced, siblings and unmodeled nodes preserved', () => {
|
||||
const body = bodySuffixWith(withExotic(buildTimingXml([A1, A2])))
|
||||
const edited = { ...A2, durationMs: 2000, delayMs: 250 }
|
||||
const out = patchSlideTimingIncrementalXml(body, [A1, edited])
|
||||
expect(out).not.toBeNull()
|
||||
expect(out!).toContain(EXOTIC)
|
||||
const anims = readSlideTimingXml(out!)
|
||||
expect(anims[1]).toMatchObject({ durationMs: 2000, delayMs: 250, effect: 'flyIn' })
|
||||
expect(anims[0]).toMatchObject({ spid: 4, effect: 'fade', durationMs: 500 })
|
||||
})
|
||||
|
||||
it('delete/reorder/trigger change → returns null (falls back to rebuild)', () => {
|
||||
const body = bodySuffixWith(buildTimingXml([A1, A2]))
|
||||
expect(patchSlideTimingIncrementalXml(body, [A2])).toBeNull() // delete
|
||||
expect(patchSlideTimingIncrementalXml(body, [A2, A1])).toBeNull() // reorder
|
||||
expect(patchSlideTimingIncrementalXml(body, [A1, { ...A2, trigger: 'withPrev' }])).toBeNull() // trigger change
|
||||
// Append whose first entry is not onClick (would merge into the old group) → fall back
|
||||
expect(
|
||||
patchSlideTimingIncrementalXml(body, [A1, A2, { ...A1, trigger: 'withPrev' }]),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('round-trip: appending after an append still takes the incremental path', () => {
|
||||
let body = bodySuffixWith(withExotic(buildTimingXml([A1])))
|
||||
body = patchSlideTimingIncrementalXml(body, [A1, A2])!
|
||||
const A3: SlideAnimation = {
|
||||
spid: 4,
|
||||
effect: 'zoomOut',
|
||||
trigger: 'onClick',
|
||||
durationMs: 300,
|
||||
delayMs: 100,
|
||||
}
|
||||
const out = patchSlideTimingIncrementalXml(body, [A1, A2, A3])
|
||||
expect(out).not.toBeNull()
|
||||
expect(out!).toContain(EXOTIC)
|
||||
const anims = readSlideTimingXml(out!)
|
||||
expect(anims.length).toBe(3)
|
||||
expect(anims[2]).toMatchObject({ spid: 4, effect: 'zoomOut', delayMs: 100 })
|
||||
// Second animation on the same spid continues with grpId 1
|
||||
expect(out!).toContain('<p:bldP spid="4" grpId="1"/>')
|
||||
})
|
||||
})
|
||||
|
||||
/** Interactive sequence with a real trigger effect (presetClass cTn inside interactiveSeq). */
|
||||
const EXOTIC_WITH_EFFECT =
|
||||
'<p:seq concurrent="1" nextAc="none"><p:cTn id="900" restart="whenNotActive" fill="hold" evtFilter="cancelBubble" nodeType="interactiveSeq">' +
|
||||
'<p:stCondLst><p:cond evt="onClick" delay="0"><p:tgtEl><p:spTgt spid="99"/></p:tgtEl></p:cond></p:stCondLst>' +
|
||||
'<p:childTnLst><p:par><p:cTn id="901" presetID="10" presetClass="entr" presetSubtype="0" fill="hold" nodeType="clickEffect">' +
|
||||
'<p:stCondLst><p:cond delay="0"/></p:stCondLst>' +
|
||||
'<p:childTnLst><p:set><p:cBhvr><p:cTn id="902" dur="1"/><p:tgtEl><p:spTgt spid="88"/></p:tgtEl><p:attrNameLst><p:attrName>style.visibility</p:attrName></p:attrNameLst></p:cBhvr><p:to><p:strVal val="visible"/></p:to></p:set></p:childTnLst>' +
|
||||
'</p:cTn></p:par></p:childTnLst></p:cTn></p:seq>'
|
||||
|
||||
describe('trigger animations are not mistakenly absorbed', () => {
|
||||
it('readSlideTimingXml reads only the main sequence; effects inside interactiveSeq do not appear in the list', () => {
|
||||
const body = bodySuffixWith(
|
||||
withExotic(buildTimingXml([A1])).replace(EXOTIC, EXOTIC_WITH_EFFECT),
|
||||
)
|
||||
const anims = readSlideTimingXml(body)
|
||||
expect(anims.length).toBe(1)
|
||||
expect(anims[0]).toMatchObject({ spid: 4, effect: 'fade' })
|
||||
})
|
||||
|
||||
it('no main sequence (trigger-only timing) -> reads back an empty list', () => {
|
||||
const timing = `<p:timing><p:tnLst><p:par><p:cTn id="1" dur="indefinite" restart="never" nodeType="tmRoot"><p:childTnLst>${EXOTIC_WITH_EFFECT}</p:childTnLst></p:cTn></p:par></p:tnLst></p:timing>`
|
||||
expect(readSlideTimingXml(bodySuffixWith(timing))).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('patchSlideTimingXml full rebuild preserves unmodeled nodes', () => {
|
||||
it('deleting an animation (reorder/removal falls back to rebuild): interactiveSeq keeps original bytes', () => {
|
||||
const body = bodySuffixWith(withExotic(buildTimingXml([A1, A2])))
|
||||
const out = patchSlideTimingXml(body, [A2]) // remove A1
|
||||
expect(out).toContain(EXOTIC)
|
||||
const anims = readSlideTimingXml(out)
|
||||
expect(anims.length).toBe(1)
|
||||
expect(anims[0]).toMatchObject({ spid: 5, effect: 'flyIn' })
|
||||
})
|
||||
|
||||
it('reordering animations: trigger effects are kept and not absorbed', () => {
|
||||
const body = bodySuffixWith(
|
||||
withExotic(buildTimingXml([A1, A2])).replace(EXOTIC, EXOTIC_WITH_EFFECT),
|
||||
)
|
||||
const out = patchSlideTimingXml(body, [A2, A1])
|
||||
expect(out).toContain(EXOTIC_WITH_EFFECT)
|
||||
const anims = readSlideTimingXml(out)
|
||||
expect(anims.map((a) => a.spid)).toEqual([5, 4])
|
||||
})
|
||||
|
||||
it('rebuilt cTn ids do not clash with preserved nodes', () => {
|
||||
const body = bodySuffixWith(withExotic(buildTimingXml([A1, A2]))) // exotic id=900
|
||||
const out = patchSlideTimingXml(body, [A2, A1])
|
||||
const ids = [...out.matchAll(/\bid="(\d+)"/g)].map((m) => Number(m[1]))
|
||||
expect(new Set(ids).size).toBe(ids.length)
|
||||
})
|
||||
|
||||
it('clearing animations: main sequence removed, interactiveSeq kept, timing stays', () => {
|
||||
const body = bodySuffixWith(withExotic(buildTimingXml([A1])))
|
||||
const out = patchSlideTimingXml(body, [])
|
||||
expect(out).toContain('<p:timing>')
|
||||
expect(out).toContain(EXOTIC)
|
||||
expect(out).not.toContain('nodeType="mainSeq"')
|
||||
expect(readSlideTimingXml(out)).toEqual([])
|
||||
})
|
||||
|
||||
it('clearing animations with no unmodeled nodes: the whole timing is removed', () => {
|
||||
const body = bodySuffixWith(buildTimingXml([A1]))
|
||||
const out = patchSlideTimingXml(body, [])
|
||||
expect(out).not.toContain('<p:timing>')
|
||||
})
|
||||
|
||||
it('bldLst: bldP rewritten, unmodeled builds like bldDgm kept', () => {
|
||||
let timing = withExotic(buildTimingXml([A1, A2]))
|
||||
timing = timing.replace('</p:bldLst>', '<p:bldDgm spid="77" grpId="0"/></p:bldLst>')
|
||||
const out = patchSlideTimingXml(bodySuffixWith(timing), [A2])
|
||||
expect(out).toContain('<p:bldDgm spid="77" grpId="0"/>')
|
||||
expect(out).toContain('<p:bldP spid="5" grpId="0"/>')
|
||||
expect(out).not.toContain('<p:bldP spid="4"')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Per-paragraph animation (pgRg + build="p"): write/read round-trip, mixing with whole-shape animations, incremental path.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import {
|
||||
buildTimingXml,
|
||||
elementSpid,
|
||||
getSlideAnimations,
|
||||
openPptx,
|
||||
patchSlideTimingIncrementalXml,
|
||||
readSlideTimingXml,
|
||||
savePptx,
|
||||
setSlideAnimations,
|
||||
type SlideAnimation,
|
||||
} from '../src/index'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const para = (spid: number, paragraph: number, o?: Partial<SlideAnimation>): SlideAnimation => ({
|
||||
spid,
|
||||
effect: 'fade',
|
||||
trigger: 'onClick',
|
||||
durationMs: 500,
|
||||
delayMs: 0,
|
||||
paragraph,
|
||||
...o,
|
||||
})
|
||||
|
||||
describe('paragraph builds (pgRg + build="p")', () => {
|
||||
it('two-paragraph fade: pgRg on every behavior target + a single build="p" bldP', () => {
|
||||
const anims = [para(4, 0), para(4, 1)]
|
||||
const xml = buildTimingXml(anims)
|
||||
// fade = set + animEffect; the two animations have 4 behavior targets total, all with txEl/pgRg
|
||||
expect(xml.match(/<p:pgRg st="0" end="0"\/>/g)!.length).toBe(2)
|
||||
expect(xml.match(/<p:pgRg st="1" end="1"\/>/g)!.length).toBe(2)
|
||||
expect(xml.match(/<p:spTgt spid="4"><p:txEl><p:pgRg/g)!.length).toBe(4)
|
||||
// bldP: one build="p" for the whole shape; no longer writes a plain bldP per grpId
|
||||
expect(xml.match(/<p:bldP\b/g)!.length).toBe(1)
|
||||
expect(xml).toContain('<p:bldP spid="4" grpId="0" uiExpand="1" build="p"/>')
|
||||
expect(readSlideTimingXml(`</p:cSld>${xml}</p:sld>`)).toEqual(anims)
|
||||
})
|
||||
|
||||
it('round-trips through save/reopen, mixed with whole-shape animations', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const spids = slide.elements.map((el) => elementSpid(el)!)
|
||||
const anims: SlideAnimation[] = [
|
||||
para(spids[0]!, 0),
|
||||
para(spids[0]!, 1, { trigger: 'afterPrev', durationMs: 800 }),
|
||||
{ spid: spids[1]!, effect: 'flyIn', trigger: 'onClick', durationMs: 700, delayMs: 100 },
|
||||
para(spids[0]!, 2, { effect: 'wipe' }),
|
||||
]
|
||||
setSlideAnimations(slide, anims)
|
||||
expect(getSlideAnimations(slide)).toEqual(anims)
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideAnimations(reopened.deck.slides[0]!)).toEqual(anims)
|
||||
// Paragraph shape build="p" and whole-shape plain bldP coexist
|
||||
const suffix = reopened.deck.slides[0]!.bodySuffix
|
||||
expect(suffix).toContain(`<p:bldP spid="${spids[0]}" grpId="0" uiExpand="1" build="p"/>`)
|
||||
expect(suffix).toContain(`<p:bldP spid="${spids[1]}" grpId="0"/>`)
|
||||
})
|
||||
|
||||
it('paragraph targets survive behaviors of movement/scale/motion effects', () => {
|
||||
const anims: SlideAnimation[] = [
|
||||
para(6, 0, { effect: 'flyIn' }),
|
||||
para(6, 1, { effect: 'zoom' }),
|
||||
para(6, 2, { effect: 'motionPath', motionPath: 'M 0 0 L 0.25 0' }),
|
||||
]
|
||||
const xml = buildTimingXml(anims)
|
||||
// Each behavior's target (set/anim/animScale/animMotion) carries the paragraph
|
||||
expect(xml.match(/<p:tgtEl><p:spTgt spid="6"\/><\/p:tgtEl>/g)).toBeNull()
|
||||
expect(readSlideTimingXml(`</p:cSld>${xml}</p:sld>`)).toEqual(anims)
|
||||
})
|
||||
|
||||
it('incremental append of paragraph animations keeps bytes and adds one build="p" bldP', () => {
|
||||
const body = `<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>${buildTimingXml([para(4, 0)])}</p:sld>`
|
||||
const out = patchSlideTimingIncrementalXml(body, [para(4, 0), para(4, 1), para(4, 2)])
|
||||
expect(out).not.toBeNull()
|
||||
expect(readSlideTimingXml(out!)).toEqual([para(4, 0), para(4, 1), para(4, 2)])
|
||||
// Appending does not duplicate the build="p" bldP
|
||||
expect(out!.match(/<p:bldP\b/g)!.length).toBe(1)
|
||||
})
|
||||
|
||||
it('incremental tail edit of a paragraph animation patches in place', () => {
|
||||
const anims = [para(4, 0), para(4, 1)]
|
||||
const body = `<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>${buildTimingXml(anims)}</p:sld>`
|
||||
const edited = [para(4, 0), para(4, 1, { durationMs: 1500, delayMs: 200 })]
|
||||
const out = patchSlideTimingIncrementalXml(body, edited)
|
||||
expect(out).not.toBeNull()
|
||||
expect(readSlideTimingXml(out!)).toEqual(edited)
|
||||
})
|
||||
|
||||
it('falls back to full rebuild when paragraph shape changes bldP form', () => {
|
||||
const whole: SlideAnimation = { spid: 4, effect: 'fade', trigger: 'onClick', durationMs: 500, delayMs: 0 }
|
||||
const wholeBody = `</p:cSld>${buildTimingXml([whole])}</p:sld>`
|
||||
// Appending a paragraph animation to a whole-shape spid → needs a switch to build="p"; falls back
|
||||
expect(patchSlideTimingIncrementalXml(wholeBody, [whole, para(4, 0)])).toBeNull()
|
||||
// Tail edit changing the paragraph → falls back
|
||||
const paraBody = `</p:cSld>${buildTimingXml([para(4, 0), para(4, 1)])}</p:sld>`
|
||||
expect(patchSlideTimingIncrementalXml(paraBody, [para(4, 0), para(4, 2)])).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import {
|
||||
animClassOf,
|
||||
buildTimingXml,
|
||||
elementSpid,
|
||||
getSlideAnimations,
|
||||
openPptx,
|
||||
readSlideTimingXml,
|
||||
savePptx,
|
||||
setSlideAnimations,
|
||||
setSlideTransition,
|
||||
type SlideAnimation,
|
||||
} from '../src/index'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
describe('shape animations (<p:timing>)', () => {
|
||||
it('elementSpid extracts the cNvPr id of each element', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const spids = slide.elements.map((el) => elementSpid(el))
|
||||
expect(spids.every((s) => typeof s === 'number' && s! > 0)).toBe(true)
|
||||
expect(new Set(spids).size).toBe(spids.length) // unique within the slide
|
||||
})
|
||||
|
||||
it('classifies effects', () => {
|
||||
expect(animClassOf('fade')).toBe('entrance')
|
||||
expect(animClassOf('spin')).toBe('emphasis')
|
||||
expect(animClassOf('flyOut')).toBe('exit')
|
||||
})
|
||||
|
||||
it('builds a PowerPoint-shaped timing tree', () => {
|
||||
const xml = buildTimingXml([
|
||||
{ spid: 4, effect: 'fade', trigger: 'onClick', durationMs: 500, delayMs: 0 },
|
||||
])
|
||||
expect(xml).toContain('nodeType="tmRoot"')
|
||||
expect(xml).toContain('nodeType="mainSeq"')
|
||||
expect(xml).toContain('presetID="10" presetClass="entr"')
|
||||
expect(xml).toContain('<p:spTgt spid="4"/>')
|
||||
expect(xml).toContain('<p:bldP spid="4" grpId="0"/>')
|
||||
// cTn ids are globally unique
|
||||
const ids = [...xml.matchAll(/<p:cTn id="(\d+)"/g)].map((m) => Number(m[1]))
|
||||
expect(new Set(ids).size).toBe(ids.length)
|
||||
})
|
||||
|
||||
it('round-trips a mixed animation list through save/reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const spids = slide.elements.map((el) => elementSpid(el)!)
|
||||
const anims: SlideAnimation[] = [
|
||||
{ spid: spids[0]!, effect: 'appear', trigger: 'onClick', durationMs: 0, delayMs: 0 },
|
||||
{ spid: spids[1]!, effect: 'flyIn', trigger: 'withPrev', durationMs: 800, delayMs: 200 },
|
||||
{ spid: spids[0]!, effect: 'spin', trigger: 'afterPrev', durationMs: 1000, delayMs: 0 },
|
||||
{ spid: spids[1]!, effect: 'fadeOut', trigger: 'onClick', durationMs: 500, delayMs: 100 },
|
||||
]
|
||||
setSlideAnimations(slide, anims)
|
||||
expect(getSlideAnimations(slide)).toEqual(anims)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideAnimations(reopened.deck.slides[0]!)).toEqual(anims)
|
||||
// Other slides are unaffected
|
||||
expect(getSlideAnimations(reopened.deck.slides[1]!)).toEqual([])
|
||||
})
|
||||
|
||||
it('replaces existing timing instead of stacking, and can clear', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const spid = elementSpid(slide.elements[0]!)!
|
||||
setSlideAnimations(slide, [{ spid, effect: 'fade', trigger: 'onClick', durationMs: 500, delayMs: 0 }])
|
||||
setSlideAnimations(slide, [{ spid, effect: 'zoom', trigger: 'onClick', durationMs: 700, delayMs: 0 }])
|
||||
expect(slide.bodySuffix.match(/<p:timing>/g)!.length).toBe(1)
|
||||
expect(getSlideAnimations(slide)).toEqual([
|
||||
{ spid, effect: 'zoom', trigger: 'onClick', durationMs: 700, delayMs: 0 },
|
||||
])
|
||||
|
||||
setSlideAnimations(slide, [])
|
||||
expect(slide.bodySuffix).not.toContain('<p:timing')
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideAnimations(reopened.deck.slides[0]!)).toEqual([])
|
||||
})
|
||||
|
||||
it('coexists with a slide transition (transition before timing)', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const spid = elementSpid(slide.elements[0]!)!
|
||||
setSlideTransition(slide, 'fade')
|
||||
setSlideAnimations(slide, [{ spid, effect: 'wipe', trigger: 'onClick', durationMs: 500, delayMs: 0 }])
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const suffix = reopened.deck.slides[0]!.bodySuffix
|
||||
expect(suffix.indexOf('<p:transition')).toBeGreaterThanOrEqual(0)
|
||||
expect(suffix.indexOf('<p:transition')).toBeLessThan(suffix.indexOf('<p:timing'))
|
||||
expect(getSlideAnimations(reopened.deck.slides[0]!)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('reads foreign presets with best-effort fallback', () => {
|
||||
// Unmodeled presetIDs (e.g. entr box 4) degrade to a similar effect of the same class
|
||||
const xml = buildTimingXml([{ spid: 7, effect: 'fade', trigger: 'onClick', durationMs: 500, delayMs: 0 }])
|
||||
.replace('presetID="10"', 'presetID="4"')
|
||||
const anims = readSlideTimingXml(`</p:cSld>${xml}</p:sld>`)
|
||||
expect(anims).toEqual([{ spid: 7, effect: 'fade', trigger: 'onClick', durationMs: 500, delayMs: 0 }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('extended effects + motion paths', () => {
|
||||
it('classifies the new effects', () => {
|
||||
expect(animClassOf('bounce')).toBe('entrance')
|
||||
expect(animClassOf('flipIn')).toBe('entrance')
|
||||
expect(animClassOf('teeter')).toBe('emphasis')
|
||||
expect(animClassOf('shrink')).toBe('exit')
|
||||
expect(animClassOf('motionPath')).toBe('path')
|
||||
})
|
||||
|
||||
it('round-trips every new effect kind through save/reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const spid = elementSpid(slide.elements[0]!)!
|
||||
const anims: SlideAnimation[] = (
|
||||
['wipeDown', 'splitIn', 'bounce', 'flipIn', 'teeter', 'wipeOut', 'shrink'] as const
|
||||
).map((effect, i) => ({
|
||||
spid,
|
||||
effect,
|
||||
trigger: i === 0 ? ('onClick' as const) : ('afterPrev' as const),
|
||||
durationMs: 500 + i * 100,
|
||||
delayMs: 0,
|
||||
}))
|
||||
setSlideAnimations(slide, anims)
|
||||
expect(getSlideAnimations(slide)).toEqual(anims)
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideAnimations(reopened.deck.slides[0]!)).toEqual(anims)
|
||||
})
|
||||
|
||||
it('distinguishes wipe directions by presetSubtype on read-back', () => {
|
||||
const anims: SlideAnimation[] = [
|
||||
{ spid: 3, effect: 'wipe', trigger: 'onClick', durationMs: 500, delayMs: 0 },
|
||||
{ spid: 3, effect: 'wipeDown', trigger: 'onClick', durationMs: 500, delayMs: 0 },
|
||||
]
|
||||
const xml = buildTimingXml(anims)
|
||||
expect(xml).toContain('filter="wipe(up)"')
|
||||
expect(xml).toContain('filter="wipe(down)"')
|
||||
expect(readSlideTimingXml(`</p:cSld>${xml}</p:sld>`)).toEqual(anims)
|
||||
})
|
||||
|
||||
it('writes motion paths as p:animMotion with a relative path and E terminator', () => {
|
||||
const xml = buildTimingXml([
|
||||
{ spid: 5, effect: 'motionPath', trigger: 'onClick', durationMs: 2000, delayMs: 0, motionPath: 'M 0 0 L 0.3 0' },
|
||||
])
|
||||
expect(xml).toContain('presetID="0" presetClass="path"')
|
||||
expect(xml).toContain('<p:animMotion origin="layout" path="M 0 0 L 0.3 0 E" pathEditMode="relative">')
|
||||
expect(xml).toContain('<p:attrName>ppt_x</p:attrName><p:attrName>ppt_y</p:attrName>')
|
||||
})
|
||||
|
||||
it('round-trips motion paths (line + bezier circle) through save/reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const spids = slide.elements.map((el) => elementSpid(el)!)
|
||||
const circle =
|
||||
'M 0 0 C 0.069 0 0.125 0.056 0.125 0.125 C 0.125 0.194 0.069 0.25 0 0.25 ' +
|
||||
'C -0.069 0.25 -0.125 0.194 -0.125 0.125 C -0.125 0.056 -0.069 0 0 0 Z'
|
||||
const anims: SlideAnimation[] = [
|
||||
{ spid: spids[0]!, effect: 'motionPath', trigger: 'onClick', durationMs: 2000, delayMs: 0, motionPath: 'M 0 0 L 0.25 0.25' },
|
||||
{ spid: spids[1]!, effect: 'motionPath', trigger: 'withPrev', durationMs: 3000, delayMs: 100, motionPath: circle },
|
||||
// Mixing new and old: existing effects are unaffected
|
||||
{ spid: spids[0]!, effect: 'fadeOut', trigger: 'onClick', durationMs: 500, delayMs: 0 },
|
||||
]
|
||||
setSlideAnimations(slide, anims)
|
||||
expect(getSlideAnimations(slide)).toEqual(anims)
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideAnimations(reopened.deck.slides[0]!)).toEqual(anims)
|
||||
})
|
||||
|
||||
it('falls back to the default path when motionPath is missing (legacy data safety)', () => {
|
||||
const xml = buildTimingXml([{ spid: 9, effect: 'motionPath', trigger: 'onClick', durationMs: 2000, delayMs: 0 }])
|
||||
expect(xml).toContain('path="M 0 0 L 0.25 0 E"')
|
||||
const back = readSlideTimingXml(`</p:cSld>${xml}</p:sld>`)
|
||||
expect(back[0]!.motionPath).toBe('M 0 0 L 0.25 0')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Tests for normAutofit fontScale write-back (patchBodyPrAutofit):
|
||||
* attribute replace/insert/clear, and stacking with patchTextElementXml (bodyPr kept as-is).
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { patchBodyPrAutofit, patchTextElementXml } from '../src/index'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
const SP = (bodyPr: string) =>
|
||||
`<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="100" cy="100"/></a:xfrm></p:spPr>` +
|
||||
`<p:txBody>${bodyPr}<a:lstStyle/><a:p><a:r><a:rPr lang="en-US" sz="1800"/><a:t>hi</a:t></a:r></a:p></p:txBody></p:sp>`
|
||||
|
||||
describe('patchBodyPrAutofit', () => {
|
||||
it('writes fontScale/lnSpcReduction onto bare normAutofit', () => {
|
||||
const out = patchBodyPrAutofit(SP('<a:bodyPr><a:normAutofit/></a:bodyPr>'), 0.625, 0.2)
|
||||
expect(out).toContain('<a:normAutofit fontScale="62500" lnSpcReduction="20000"/>')
|
||||
})
|
||||
|
||||
it('replaces existing attributes', () => {
|
||||
const out = patchBodyPrAutofit(
|
||||
SP('<a:bodyPr><a:normAutofit fontScale="90000" lnSpcReduction="10000"/></a:bodyPr>'),
|
||||
0.5,
|
||||
)
|
||||
expect(out).toContain('<a:normAutofit fontScale="50000"/>')
|
||||
expect(out).not.toContain('90000')
|
||||
})
|
||||
|
||||
it('clears attributes when scale back to 1', () => {
|
||||
const out = patchBodyPrAutofit(SP('<a:bodyPr><a:normAutofit fontScale="62500"/></a:bodyPr>'), 1)
|
||||
expect(out).toContain('<a:normAutofit/>')
|
||||
expect(out).not.toContain('fontScale')
|
||||
})
|
||||
|
||||
it('handles paired-tag normAutofit and leaves non-autofit xml untouched', () => {
|
||||
const paired = patchBodyPrAutofit(
|
||||
SP('<a:bodyPr><a:normAutofit></a:normAutofit></a:bodyPr>'),
|
||||
0.8,
|
||||
)
|
||||
expect(paired).toContain('<a:normAutofit fontScale="80000"/>')
|
||||
const noFit = SP('<a:bodyPr><a:spAutoFit/></a:bodyPr>')
|
||||
expect(patchBodyPrAutofit(noFit, 0.8)).toBe(noFit)
|
||||
})
|
||||
|
||||
it('survives patchTextElementXml (bodyPr preserved through text regen)', () => {
|
||||
const xml = patchBodyPrAutofit(SP('<a:bodyPr><a:normAutofit/></a:bodyPr>'), 0.75)
|
||||
const el = {
|
||||
id: 'e',
|
||||
type: 'shape',
|
||||
anchor: { spIndex: 0, originalXml: xml, range: [0, xml.length] },
|
||||
transform: { offset: { x: 0, y: 0, cx: 100, cy: 100 }, rot: 0, flipH: false, flipV: false },
|
||||
text: {
|
||||
autofit: 'shrink',
|
||||
fontScale: 0.75,
|
||||
paragraphs: [{ runs: [{ text: 'edited', fontSize: 18 }] }],
|
||||
},
|
||||
} as unknown as TextElement
|
||||
const out = patchTextElementXml(el, xml)
|
||||
expect(out).toContain('fontScale="75000"')
|
||||
expect(out).toContain('edited')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { openPptx, savePptx, createBlankPptx, addElement, duplicateSlide } from '../src/index'
|
||||
|
||||
describe('createBlankPptx', () => {
|
||||
it('opens as a 16:9 single blank slide', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
expect(opened.deck.slides.length).toBe(1)
|
||||
expect(opened.deck.size).toEqual({ cx: 12192000, cy: 6858000 })
|
||||
expect(opened.deck.slides[0]!.elements.length).toBe(0)
|
||||
})
|
||||
|
||||
it('theme default fonts: Calibri latin + Microsoft YaHei ea (cross-platform CJK)', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const theme = opened.archive.readText('ppt/theme/theme1.xml')!
|
||||
expect(theme).toContain('<a:latin typeface="Calibri"/>')
|
||||
expect(theme.match(/<a:ea typeface="Microsoft YaHei"\/>/g)?.length).toBe(2)
|
||||
})
|
||||
|
||||
it('supports the full edit pipeline: add element + add slide + save round-trip', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
addElement(opened.deck.slides[0]!, {
|
||||
kind: 'textbox',
|
||||
offset: { x: 914400, y: 914400, cx: 6096000, cy: 914400 },
|
||||
paragraphs: [{ runs: [{ text: 'Generated Title', bold: true, fontSize: 40 }] }],
|
||||
})
|
||||
duplicateSlide(opened, 0, { clearText: true })
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides.length).toBe(2)
|
||||
const texts = reopened.deck.slides[0]!.elements
|
||||
.flatMap((e: any) => e.text?.paragraphs ?? [])
|
||||
.flatMap((p: any) => p.runs)
|
||||
.map((r: any) => r.text)
|
||||
.join('')
|
||||
expect(texts).toBe('Generated Title')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,363 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseChartXml } from '../src/chart'
|
||||
import { buildChartSpaceXml } from '../src/chart-insert'
|
||||
|
||||
const LINE_CHART = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:lineChart><c:ser>
|
||||
<c:idx val="0"/><c:tx><c:strRef><c:f>S!$B$1</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>Revenue</c:v></c:pt></c:strCache></c:strRef></c:tx>
|
||||
<c:spPr><a:ln w="19050"><a:solidFill><a:srgbClr val="4CAF50"/></a:solidFill></a:ln></c:spPr>
|
||||
<c:marker><c:symbol val="circle"/></c:marker>
|
||||
<c:cat><c:strRef><c:f>S!$A$2:$A$4</c:f><c:strCache><c:ptCount val="3"/>
|
||||
<c:pt idx="0"><c:v>2016</c:v></c:pt><c:pt idx="1"><c:v>2017</c:v></c:pt><c:pt idx="2"><c:v>2018</c:v></c:pt></c:strCache></c:strRef></c:cat>
|
||||
<c:val><c:numRef><c:f>S!$B$2:$B$4</c:f><c:numCache><c:ptCount val="3"/>
|
||||
<c:pt idx="0"><c:v>100</c:v></c:pt><c:pt idx="1"><c:v>120</c:v></c:pt><c:pt idx="2"><c:v>145</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
<c:smooth val="1"/>
|
||||
</c:ser></c:lineChart>
|
||||
<c:valAx><c:scaling><c:orientation val="minMax"/></c:scaling><c:majorGridlines><c:spPr><a:ln><a:solidFill><a:srgbClr val="E6E6E6"/></a:solidFill><a:prstDash val="dash"/></a:ln></c:spPr></c:majorGridlines>
|
||||
<c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr sz="1200"><a:solidFill><a:srgbClr val="666666"/></a:solidFill></a:defRPr></a:pPr></a:p></c:txPr></c:valAx>
|
||||
</c:plotArea><c:legend><c:legendPos val="t"/></c:legend></c:chart></c:chartSpace>`
|
||||
|
||||
const BAR_CHART = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/>
|
||||
<c:ser><c:idx val="0"/>
|
||||
<c:spPr><a:solidFill><a:srgbClr val="629BF8"/></a:solidFill></c:spPr>
|
||||
<c:cat><c:strRef><c:f>x</c:f><c:strCache><c:ptCount val="2"/><c:pt idx="0"><c:v>AAPL</c:v></c:pt><c:pt idx="1"><c:v>MSFT</c:v></c:pt></c:strCache></c:strRef></c:cat>
|
||||
<c:val><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>30.5</c:v></c:pt><c:pt idx="1"><c:v>35</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser><c:gapWidth val="28"/></c:barChart>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
|
||||
describe('parseChartXml', () => {
|
||||
it('parses line chart: series name/color/smooth/marker + categories + values + legend + axis', () => {
|
||||
const m = parseChartXml(LINE_CHART)!
|
||||
expect(m.kind).toBe('line')
|
||||
expect(m.series).toHaveLength(1)
|
||||
expect(m.series[0]!.name).toBe('Revenue')
|
||||
expect(m.series[0]!.color).toBe('#4CAF50')
|
||||
expect(m.series[0]!.smooth).toBe(true)
|
||||
expect(m.series[0]!.marker).toBe(true)
|
||||
expect(m.series[0]!.values).toEqual([100, 120, 145])
|
||||
expect(m.categories).toEqual(['2016', '2017', '2018'])
|
||||
expect(m.legendPos).toBe('t')
|
||||
expect(m.valAxis?.gridColor).toBe('#E6E6E6')
|
||||
expect(m.valAxis?.gridDash).toBe(true)
|
||||
expect(m.valAxis?.labelColor).toBe('#666666')
|
||||
expect(m.valAxis?.labelSizePt).toBe(12)
|
||||
})
|
||||
|
||||
it('parses clustered bar chart with fill color and gapWidth', () => {
|
||||
const m = parseChartXml(BAR_CHART)!
|
||||
expect(m.kind).toBe('bar')
|
||||
expect(m.barDir).toBe('col')
|
||||
expect(m.grouping).toBe('clustered')
|
||||
expect(m.gapWidthPct).toBe(28)
|
||||
expect(m.series[0]!.color).toBe('#629BF8')
|
||||
expect(m.series[0]!.values).toEqual([30.5, 35])
|
||||
expect(m.legendPos).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns null for chart space without recognizable plot', () => {
|
||||
expect(parseChartXml('<c:chartSpace><c:chart/></c:chartSpace>')).toBeNull()
|
||||
})
|
||||
|
||||
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"/>
|
||||
<c:dPt><c:idx val="0"/><c:spPr><a:solidFill><a:srgbClr val="AA0000"/></a:solidFill></c:spPr></c:dPt>
|
||||
<c:dPt><c:idx val="2"/><c:spPr><a:solidFill><a:srgbClr val="0000AA"/></a:solidFill></c:spPr></c:dPt>
|
||||
<c:cat><c:strRef><c:f>x</c:f><c:strCache><c:ptCount val="3"/><c:pt idx="0"><c:v>A</c:v></c:pt><c:pt idx="1"><c:v>B</c:v></c:pt><c:pt idx="2"><c:v>C</c:v></c:pt></c:strCache></c:strRef></c:cat>
|
||||
<c:val><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt><c:pt idx="2"><c:v>3</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser><c:firstSliceAng val="90"/><c:holeSize val="60"/></c:doughnutChart>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
const m = parseChartXml(DOUGHNUT)!
|
||||
expect(m.kind).toBe('pie')
|
||||
expect(m.holePct).toBe(60)
|
||||
expect(m.firstSliceAngDeg).toBe(90)
|
||||
expect(m.series[0]!.pointColors?.[0]).toBe('#AA0000')
|
||||
expect(m.series[0]!.pointColors?.[1]).toBeUndefined()
|
||||
expect(m.series[0]!.pointColors?.[2]).toBe('#0000AA')
|
||||
})
|
||||
|
||||
it('pie chart without holeSize defaults holePct 0', () => {
|
||||
const PIE = `<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea>
|
||||
<c:pieChart><c:ser><c:idx val="0"/>
|
||||
<c:val><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>1</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser></c:pieChart>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
const m = parseChartXml(PIE)!
|
||||
expect(m.kind).toBe('pie')
|
||||
expect(m.holePct).toBe(0)
|
||||
})
|
||||
|
||||
it('parses stacked column grouping', () => {
|
||||
const STACKED = BAR_CHART.replace('val="clustered"', 'val="stacked"')
|
||||
const m = parseChartXml(STACKED)!
|
||||
expect(m.grouping).toBe('stacked')
|
||||
})
|
||||
|
||||
it('parses horizontal bar (barDir=bar) with reversed category axis', () => {
|
||||
const HBAR = BAR_CHART.replace('val="col"', 'val="bar"').replace(
|
||||
'</c:plotArea>',
|
||||
'<c:catAx><c:scaling><c:orientation val="maxMin"/></c:scaling></c:catAx></c:plotArea>',
|
||||
)
|
||||
const m = parseChartXml(HBAR)!
|
||||
expect(m.barDir).toBe('bar')
|
||||
expect(m.catAxis?.reversed).toBe(true)
|
||||
})
|
||||
|
||||
it('parses scatter chart: xVal/yVal + scatterStyle + dual value-axis dispatch', () => {
|
||||
const SCATTER = `<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea>
|
||||
<c:scatterChart><c:scatterStyle val="lineMarker"/>
|
||||
<c:ser><c:idx val="0"/>
|
||||
<c:tx><c:strRef><c:f>t</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>Sample</c:v></c:pt></c:strCache></c:strRef></c:tx>
|
||||
<c:marker><c:symbol val="none"/></c:marker>
|
||||
<c:xVal><c:numRef><c:f>x</c:f><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>1.5</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt><c:pt idx="2"><c:v>4</c:v></c:pt></c:numCache></c:numRef></c:xVal>
|
||||
<c:yVal><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>10</c:v></c:pt><c:pt idx="1"><c:v>20</c:v></c:pt><c:pt idx="2"><c:v>15</c:v></c:pt></c:numCache></c:numRef></c:yVal>
|
||||
</c:ser></c:scatterChart>
|
||||
<c:valAx><c:axPos val="b"/><c:scaling><c:min val="0"/><c:max val="5"/></c:scaling></c:valAx>
|
||||
<c:valAx><c:axPos val="l"/><c:majorGridlines/></c:valAx>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
const m = parseChartXml(SCATTER)!
|
||||
expect(m.kind).toBe('scatter')
|
||||
expect(m.scatterStyle).toBe('lineMarker')
|
||||
expect(m.series[0]!.name).toBe('Sample')
|
||||
expect(m.series[0]!.xValues).toEqual([1.5, 2, 4])
|
||||
expect(m.series[0]!.values).toEqual([10, 20, 15])
|
||||
expect(m.series[0]!.marker).toBe(false) // explicit symbol=none
|
||||
// The value axis with axPos=b goes into the catAxis slot (x axis); the other goes into valAxis
|
||||
expect(m.catAxis?.min).toBe(0)
|
||||
expect(m.catAxis?.max).toBe(5)
|
||||
expect(m.valAxis?.gridColor).toBe('#E6E6E6')
|
||||
})
|
||||
|
||||
it('parses radar chart: radarStyle + categories', () => {
|
||||
const RADAR = `<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea>
|
||||
<c:radarChart><c:radarStyle val="filled"/>
|
||||
<c:ser><c:idx val="0"/>
|
||||
<c:spPr><a:solidFill><a:srgbClr val="ED7D31"/></a:solidFill></c:spPr>
|
||||
<c:cat><c:strRef><c:f>x</c:f><c:strCache><c:ptCount val="4"/><c:pt idx="0"><c:v>Listen</c:v></c:pt><c:pt idx="1"><c:v>Speak</c:v></c:pt><c:pt idx="2"><c:v>Read</c:v></c:pt><c:pt idx="3"><c:v>Write</c:v></c:pt></c:strCache></c:strRef></c:cat>
|
||||
<c:val><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="4"/><c:pt idx="0"><c:v>3</c:v></c:pt><c:pt idx="1"><c:v>4</c:v></c:pt><c:pt idx="2"><c:v>5</c:v></c:pt><c:pt idx="3"><c:v>2</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser></c:radarChart>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
const m = parseChartXml(RADAR)!
|
||||
expect(m.kind).toBe('radar')
|
||||
expect(m.radarStyle).toBe('filled')
|
||||
expect(m.categories).toEqual(['Listen', 'Speak', 'Read', 'Write'])
|
||||
expect(m.series[0]!.color).toBe('#ED7D31')
|
||||
expect(m.series[0]!.values).toEqual([3, 4, 5, 2])
|
||||
})
|
||||
|
||||
it('parses bar+line combo: both plots kept, series tagged with plotKind', () => {
|
||||
const COMBO = `<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/>
|
||||
<c:ser><c:idx val="0"/>
|
||||
<c:tx><c:strRef><c:f>n</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>Sales</c:v></c:pt></c:strCache></c:strRef></c:tx>
|
||||
<c:spPr><a:solidFill><a:srgbClr val="4472C4"/></a:solidFill></c:spPr>
|
||||
<c:cat><c:strRef><c:f>x</c:f><c:strCache><c:ptCount val="3"/><c:pt idx="0"><c:v>Q1</c:v></c:pt><c:pt idx="1"><c:v>Q2</c:v></c:pt><c:pt idx="2"><c:v>Q3</c:v></c:pt></c:strCache></c:strRef></c:cat>
|
||||
<c:val><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>10</c:v></c:pt><c:pt idx="1"><c:v>20</c:v></c:pt><c:pt idx="2"><c:v>30</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser><c:gapWidth val="150"/></c:barChart>
|
||||
<c:lineChart><c:ser><c:idx val="1"/>
|
||||
<c:tx><c:strRef><c:f>n2</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>Growth Rate</c:v></c:pt></c:strCache></c:strRef></c:tx>
|
||||
<c:spPr><a:ln><a:solidFill><a:srgbClr val="ED7D31"/></a:solidFill></a:ln></c:spPr>
|
||||
<c:val><c:numRef><c:f>y2</c:f><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>5</c:v></c:pt><c:pt idx="1"><c:v>8</c:v></c:pt><c:pt idx="2"><c:v>12</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
<c:smooth val="1"/>
|
||||
</c:ser></c:lineChart>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
const m = parseChartXml(COMBO)!
|
||||
expect(m.kind).toBe('bar') // primary type: bar > line
|
||||
expect(m.barDir).toBe('col')
|
||||
expect(m.series).toHaveLength(2)
|
||||
expect(m.series[0]!.name).toBe('Sales')
|
||||
expect(m.series[0]!.plotKind).toBe('bar')
|
||||
expect(m.series[0]!.values).toEqual([10, 20, 30])
|
||||
expect(m.series[1]!.name).toBe('Growth Rate')
|
||||
expect(m.series[1]!.plotKind).toBe('line')
|
||||
expect(m.series[1]!.values).toEqual([5, 8, 12])
|
||||
expect(m.series[1]!.smooth).toBe(true)
|
||||
expect(m.categories).toEqual(['Q1', 'Q2', 'Q3'])
|
||||
})
|
||||
|
||||
it('single-plot chart keeps plotKind undefined (non-combo unchanged)', () => {
|
||||
const m = parseChartXml(BAR_CHART)!
|
||||
expect(m.series[0]!.plotKind).toBeUndefined()
|
||||
})
|
||||
|
||||
it('combo dual axis: secondary value axis (axPos=r) matched via plot axId → series assignment + min/max of both axes', () => {
|
||||
const COMBO_DUAL = `<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/>
|
||||
<c:ser><c:idx val="0"/>
|
||||
<c:tx><c:strRef><c:f>n</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>Revenue</c:v></c:pt></c:strCache></c:strRef></c:tx>
|
||||
<c:cat><c:strRef><c:f>x</c:f><c:strCache><c:ptCount val="3"/><c:pt idx="0"><c:v>Q1</c:v></c:pt><c:pt idx="1"><c:v>Q2</c:v></c:pt><c:pt idx="2"><c:v>Q3</c:v></c:pt></c:strCache></c:strRef></c:cat>
|
||||
<c:val><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>120</c:v></c:pt><c:pt idx="1"><c:v>180</c:v></c:pt><c:pt idx="2"><c:v>240</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser><c:axId val="111111111"/><c:axId val="222222222"/></c:barChart>
|
||||
<c:lineChart><c:ser><c:idx val="1"/>
|
||||
<c:tx><c:strRef><c:f>n2</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>Growth</c:v></c:pt></c:strCache></c:strRef></c:tx>
|
||||
<c:val><c:numRef><c:f>y2</c:f><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>10</c:v></c:pt><c:pt idx="1"><c:v>20</c:v></c:pt><c:pt idx="2"><c:v>30</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser><c:axId val="333333333"/><c:axId val="444444444"/></c:lineChart>
|
||||
<c:catAx><c:axId val="111111111"/><c:delete val="0"/><c:axPos val="b"/><c:crossAx val="222222222"/></c:catAx>
|
||||
<c:valAx><c:axId val="222222222"/><c:scaling><c:min val="0"/><c:max val="250"/></c:scaling><c:delete val="0"/><c:axPos val="l"/><c:crossAx val="111111111"/></c:valAx>
|
||||
<c:valAx><c:axId val="444444444"/><c:scaling><c:min val="0"/><c:max val="30"/></c:scaling><c:delete val="0"/><c:axPos val="r"/><c:crossAx val="333333333"/><c:crosses val="max"/></c:valAx>
|
||||
<c:catAx><c:axId val="333333333"/><c:delete val="1"/><c:axPos val="b"/><c:crossAx val="444444444"/></c:catAx>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
const m = parseChartXml(COMBO_DUAL)!
|
||||
// Series → axis assignment: bars on primary, line on secondary (lineChart's axId 444444444 matches the axPos=r value axis)
|
||||
expect(m.series.map((s) => !!s.secondaryAxis)).toEqual([false, true])
|
||||
// Primary/secondary value axes parse their min/max independently
|
||||
expect(m.valAxis?.min).toBe(0)
|
||||
expect(m.valAxis?.max).toBe(250)
|
||||
expect(m.valAxis2?.min).toBe(0)
|
||||
expect(m.valAxis2?.max).toBe(30)
|
||||
// Category axis is the non-deleted one (the secondary plot's hidden category axis is skipped)
|
||||
expect(m.categories).toEqual(['Q1', 'Q2', 'Q3'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildChartSpaceXml comboBarLine (generate → parse round-trip)', () => {
|
||||
const OPTS = {
|
||||
kind: 'comboBarLine' as const,
|
||||
title: 'Quarterly Results',
|
||||
categories: ['Q1', 'Q2', 'Q3', 'Q4'],
|
||||
series: [
|
||||
{ name: 'Sales Amount', values: [4.3, 2.5, 3.5, 4.5] },
|
||||
{ name: 'Cost', values: [2.4, 1.8, 2.6, 2.8] },
|
||||
{ name: 'Growth Rate', values: [2.0, 1.2, 2.6, 3.4] },
|
||||
],
|
||||
offset: { x: 0, y: 0, cx: 100, cy: 100 },
|
||||
}
|
||||
|
||||
it('first N-1 series go to barChart, the last to lineChart, line attached to the right secondary value axis', () => {
|
||||
const xml = buildChartSpaceXml(OPTS)
|
||||
// Both bars and a line inside the same plotArea
|
||||
expect(xml).toContain('<c:barChart>')
|
||||
expect(xml).toContain('<c:lineChart>')
|
||||
// Bars on the primary axes, line on the secondary (own axId + right value axis crosses=max + hidden category axis)
|
||||
expect(xml).toContain('<c:axId val="333333333"/><c:axId val="444444444"/>')
|
||||
expect(xml).toMatch(
|
||||
/<c:valAx><c:axId val="444444444"\/>.*?<c:axPos val="r"\/>.*?<c:crosses val="max"\/>/,
|
||||
)
|
||||
expect(xml).toMatch(/<c:catAx><c:axId val="333333333"\/>.*?<c:delete val="1"\/>/)
|
||||
// 2 bar series, 1 line series
|
||||
expect((xml.match(/<c:barChart>.*?<\/c:barChart>/)![0].match(/<c:ser>/g) ?? []).length).toBe(2)
|
||||
expect((xml.match(/<c:lineChart>.*?<\/c:lineChart>/)![0].match(/<c:ser>/g) ?? []).length).toBe(
|
||||
1,
|
||||
)
|
||||
})
|
||||
|
||||
it('round-trip: parses back as combo (primary type bar + plotKind markers), data and categories intact', () => {
|
||||
const m = parseChartXml(buildChartSpaceXml(OPTS))!
|
||||
expect(m.kind).toBe('bar')
|
||||
expect(m.series).toHaveLength(3)
|
||||
expect(m.series.map((s) => s.plotKind)).toEqual(['bar', 'bar', 'line'])
|
||||
// Series → axis assignment round-trip: bars on primary, line on the right secondary value axis
|
||||
expect(m.series.map((s) => !!s.secondaryAxis)).toEqual([false, false, true])
|
||||
expect(m.series.map((s) => s.name)).toEqual(['Sales Amount', 'Cost', 'Growth Rate'])
|
||||
expect(m.series[0]!.values).toEqual([4.3, 2.5, 3.5, 4.5])
|
||||
expect(m.series[2]!.values).toEqual([2.0, 1.2, 2.6, 3.4])
|
||||
expect(m.categories).toEqual(['Q1', 'Q2', 'Q3', 'Q4'])
|
||||
})
|
||||
|
||||
it('single series degrades to a plain bar chart (no lineChart / secondary axis)', () => {
|
||||
const xml = buildChartSpaceXml({ ...OPTS, series: [OPTS.series[0]!] })
|
||||
expect(xml).toContain('<c:barChart>')
|
||||
expect(xml).not.toContain('<c:lineChart>')
|
||||
expect(xml).not.toContain('444444444')
|
||||
const m = parseChartXml(xml)!
|
||||
expect(m.kind).toBe('bar')
|
||||
expect(m.series[0]!.plotKind).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildChartSpaceXml style options (generate → parse round-trip)', () => {
|
||||
const BASE = {
|
||||
kind: 'bar' as const,
|
||||
categories: ['A', 'B', 'C'],
|
||||
series: [{ name: 'S1', values: [1, 2, 3] }],
|
||||
offset: { x: 0, y: 0, cx: 100, cy: 100 },
|
||||
}
|
||||
|
||||
it('defaults: legend at bottom, no gridlines, no data labels, no axis titles', () => {
|
||||
const m = parseChartXml(buildChartSpaceXml(BASE))!
|
||||
expect(m.legendPos).toBe('b')
|
||||
expect(m.valAxis?.gridColor).toBeUndefined()
|
||||
expect(m.dataLabels).toBeUndefined()
|
||||
expect(m.valAxis?.title).toBeUndefined()
|
||||
})
|
||||
|
||||
it('legendPos/dataLabels/gridlines/axis titles/gapWidth full round-trip', () => {
|
||||
const m = parseChartXml(
|
||||
buildChartSpaceXml({
|
||||
...BASE,
|
||||
legendPos: 'r',
|
||||
dataLabels: true,
|
||||
gridlines: true,
|
||||
catAxisTitle: 'Quarter',
|
||||
valAxisTitle: 'Sales (100M)',
|
||||
gapWidthPct: 80,
|
||||
}),
|
||||
)!
|
||||
expect(m.legendPos).toBe('r')
|
||||
expect(m.dataLabels).toBe(true)
|
||||
expect(m.dataLabelsPct).toBeUndefined()
|
||||
expect(m.valAxis?.gridColor).toBeTruthy()
|
||||
expect(m.catAxis?.title).toBe('Quarter')
|
||||
expect(m.valAxis?.title).toBe('Sales (100M)')
|
||||
expect(m.gapWidthPct).toBe(80)
|
||||
})
|
||||
|
||||
it('legendPos none writes no c:legend', () => {
|
||||
const xml = buildChartSpaceXml({ ...BASE, legendPos: 'none' })
|
||||
expect(xml).not.toContain('<c:legend>')
|
||||
expect(parseChartXml(xml)!.legendPos).toBeUndefined()
|
||||
})
|
||||
|
||||
it('combo charts carry dLbls on both plots; pie/line/scatter supported too', () => {
|
||||
for (const kind of ['comboBarLine', 'pie', 'line', 'scatter'] as const) {
|
||||
const xml = buildChartSpaceXml({
|
||||
...BASE,
|
||||
kind,
|
||||
series: [
|
||||
{ name: 'S1', values: [1, 2, 3] },
|
||||
{ name: 'S2', values: [4, 5, 6] },
|
||||
],
|
||||
dataLabels: true,
|
||||
})
|
||||
expect(parseChartXml(xml)!.dataLabels, kind).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('empty series/category names round-trip as empty: c:tx and c:cat omitted, no placeholders injected', () => {
|
||||
const xml = buildChartSpaceXml({
|
||||
...BASE,
|
||||
categories: ['', '', ''],
|
||||
series: [{ name: '', values: [1, 2, 3] }],
|
||||
})
|
||||
expect(xml).not.toContain('<c:tx>')
|
||||
expect(xml).not.toContain('<c:cat>')
|
||||
const m = parseChartXml(xml)!
|
||||
expect(m.series[0]!.name).toBeUndefined()
|
||||
expect(m.series[0]!.values).toEqual([1, 2, 3])
|
||||
expect(m.categories).toEqual(['', '', ''])
|
||||
})
|
||||
|
||||
it('partially empty category names keep empty slots (no pt written for empty strings)', () => {
|
||||
const xml = buildChartSpaceXml({
|
||||
...BASE,
|
||||
categories: ['Q1', '', 'Q3'],
|
||||
series: [{ name: 'S', values: [4, 5, 6] }],
|
||||
})
|
||||
const m = parseChartXml(xml)!
|
||||
expect(m.categories).toEqual(['Q1', '', 'Q3'])
|
||||
expect(m.series[0]!.name).toBe('S')
|
||||
})
|
||||
|
||||
it('dLbls with only showPercent parses as dataLabelsPct (common in external pie charts)', () => {
|
||||
const PIE = `<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:pieChart><c:ser><c:idx val="0"/>
|
||||
<c:cat><c:strRef><c:f>x</c:f><c:strCache><c:ptCount val="2"/><c:pt idx="0"><c:v>A</c:v></c:pt><c:pt idx="1"><c:v>B</c:v></c:pt></c:strCache></c:strRef></c:cat>
|
||||
<c:val><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>3</c:v></c:pt><c:pt idx="1"><c:v>7</c:v></c:pt></c:numCache></c:numRef></c:val>
|
||||
</c:ser><c:dLbls><c:showVal val="0"/><c:showPercent val="1"/></c:dLbls></c:pieChart>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
const m = parseChartXml(PIE)!
|
||||
expect(m.dataLabels).toBe(true)
|
||||
expect(m.dataLabelsPct).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,394 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import {
|
||||
addPicture,
|
||||
addElement,
|
||||
addTable,
|
||||
copyElementData,
|
||||
deleteSlide,
|
||||
editTableCellText,
|
||||
editTableStructure,
|
||||
setTableColWidth,
|
||||
elementSpid,
|
||||
getSlideAnimations,
|
||||
getSlideTransition,
|
||||
openPptx,
|
||||
pasteElements,
|
||||
reorderElement,
|
||||
savePptx,
|
||||
setSlideAnimations,
|
||||
setSlideTransition,
|
||||
} from '../src/index'
|
||||
import type { PictureElement, TableElement, TextElement } from '../src/types'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const OFF = { x: 914400, y: 914400, cx: 1828800, cy: 914400 }
|
||||
const SHIFT = { dx: 152400, dy: 152400 }
|
||||
|
||||
// 1x1 red PNG
|
||||
const PNG_1PX = Uint8Array.from(
|
||||
Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
|
||||
'base64',
|
||||
),
|
||||
)
|
||||
|
||||
describe('copy/paste elements', () => {
|
||||
it('pastes a textbox onto the same slide with shifted offset', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, {
|
||||
kind: 'textbox',
|
||||
offset: { ...OFF },
|
||||
paragraphs: [{ runs: [{ text: 'copy me', bold: true }] }],
|
||||
})
|
||||
const before = slide.elements.length
|
||||
const clip = copyElementData(opened, slide, el)
|
||||
|
||||
const r = pasteElements(opened, 0, [clip], SHIFT)
|
||||
expect(r).not.toBeNull()
|
||||
expect(r!.slide.elements.length).toBe(before + 1)
|
||||
expect(r!.elementIds.length).toBe(1)
|
||||
|
||||
const pasted = r!.slide.elements.at(-1) as TextElement
|
||||
expect(pasted.type).toBe('text')
|
||||
expect(pasted.text!.paragraphs[0]!.runs[0]!.text).toBe('copy me')
|
||||
expect(pasted.text!.paragraphs[0]!.runs[0]!.bold).toBe(true)
|
||||
expect(pasted.transform.offset.x).toBe(OFF.x + SHIFT.dx)
|
||||
expect(pasted.transform.offset.y).toBe(OFF.y + SHIFT.dy)
|
||||
|
||||
// cNvPr id does not clash with the original element
|
||||
const ids = r!.slide.elements.flatMap((e) =>
|
||||
[...e.anchor.originalXml.matchAll(/<p:cNvPr\s[^>]*\bid="(\d+)"/g)].map((m) => m[1]),
|
||||
)
|
||||
expect(new Set(ids).size).toBe(ids.length)
|
||||
|
||||
// Still present after save → reopen
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides[0]!.elements.length).toBe(before + 1)
|
||||
})
|
||||
|
||||
it('pastes a picture onto another slide (rels surgery, media shared)', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
expect(opened.deck.slides.length).toBeGreaterThan(1)
|
||||
const slide0 = opened.deck.slides[0]!
|
||||
const pic = addPicture(opened, slide0, { bytes: PNG_1PX, ext: 'png', offset: { ...OFF } })!
|
||||
const clip = copyElementData(opened, slide0, pic)
|
||||
expect(clip.rels.length).toBe(1)
|
||||
expect(clip.rels[0]!.target).toBe(pic.mediaRef)
|
||||
|
||||
const before1 = opened.deck.slides[1]!.elements.length
|
||||
const r = pasteElements(opened, 1, [clip], SHIFT)
|
||||
expect(r).not.toBeNull()
|
||||
const pasted = r!.slide.elements.at(-1) as PictureElement
|
||||
expect(pasted.type).toBe('picture')
|
||||
expect(pasted.mediaRef).toBe(pic.mediaRef)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2 = reopened.deck.slides[1]!.elements.at(-1) as PictureElement
|
||||
expect(reopened.deck.slides[1]!.elements.length).toBe(before1 + 1)
|
||||
expect(el2.type).toBe('picture')
|
||||
expect(el2.mediaRef).toBe(pic.mediaRef)
|
||||
// media part not copied
|
||||
const mediaParts = [...reopened.archive.entries.keys()].filter((p) =>
|
||||
p.startsWith('ppt/media/'),
|
||||
)
|
||||
expect(mediaParts.filter((p) => p === pic.mediaRef).length).toBe(1)
|
||||
})
|
||||
|
||||
it('pending text edits are baked into the copied xml', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, {
|
||||
kind: 'textbox',
|
||||
offset: { ...OFF },
|
||||
paragraphs: [{ runs: [{ text: 'original text' }] }],
|
||||
})
|
||||
el.text!.paragraphs = [{ runs: [{ text: 'edited text' }] }]
|
||||
el.dirty = true
|
||||
|
||||
const clip = copyElementData(opened, slide, el)
|
||||
expect(clip.xml).toContain('edited text')
|
||||
})
|
||||
})
|
||||
|
||||
describe('addTable', () => {
|
||||
it('inserts a styled table that parses and round-trips', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const before = opened.deck.slides[0]!.elements.length
|
||||
const r = addTable(opened, 0, {
|
||||
rows: 3,
|
||||
cols: 4,
|
||||
offset: { x: 914400, y: 914400, cx: 4572000, cy: 1828800 },
|
||||
})
|
||||
expect(r).not.toBeNull()
|
||||
expect(r!.slide.elements.length).toBe(before + 1)
|
||||
|
||||
const tbl = r!.slide.elements.at(-1) as TableElement
|
||||
expect(tbl.type).toBe('table')
|
||||
expect(tbl.rows.length).toBe(3)
|
||||
expect(tbl.colWidths.length).toBe(4)
|
||||
expect(tbl.rows[0]!.length).toBe(4)
|
||||
// Header row gets the fill from the built-in Medium Style 2
|
||||
expect(tbl.rows[0]![0]!.fill).toBeDefined()
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const tbl2 = reopened.deck.slides[0]!.elements.at(-1) as TableElement
|
||||
expect(tbl2.type).toBe('table')
|
||||
expect(tbl2.rows.length).toBe(3)
|
||||
expect(tbl2.colWidths.length).toBe(4)
|
||||
})
|
||||
})
|
||||
|
||||
describe('editTableCellText', () => {
|
||||
it('writes cell paragraphs, keeps style, survives save/reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addTable(opened, 0, {
|
||||
rows: 2,
|
||||
cols: 2,
|
||||
offset: { x: 914400, y: 914400, cx: 3657600, cy: 1828800 },
|
||||
})!
|
||||
const slide = r.slide
|
||||
const tblId = r.elementId
|
||||
|
||||
expect(editTableCellText(slide, tblId, 0, 1, [{ runs: [{ text: 'Header B', bold: true }] }])).toBe(
|
||||
true,
|
||||
)
|
||||
expect(editTableCellText(slide, tblId, 1, 0, [{ runs: [{ text: 'data' }] }])).toBe(true)
|
||||
// Out of range rejected
|
||||
expect(editTableCellText(slide, tblId, 5, 0, [{ runs: [{ text: 'x' }] }])).toBe(false)
|
||||
|
||||
const tbl = slide.elements.find((e) => e.id === tblId) as TableElement
|
||||
expect(tbl.rows[0]![1]!.text!.paragraphs[0]!.runs[0]!.text).toBe('Header B')
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const tbl2 = reopened.deck.slides[0]!.elements.at(-1) as TableElement
|
||||
expect(tbl2.rows[0]![1]!.text!.paragraphs[0]!.runs[0]!.text).toBe('Header B')
|
||||
expect(tbl2.rows[0]![1]!.text!.paragraphs[0]!.runs[0]!.bold).toBe(true)
|
||||
expect(tbl2.rows[1]![0]!.text!.paragraphs[0]!.runs[0]!.text).toBe('data')
|
||||
// Table style reference not broken
|
||||
expect(tbl2.rows[0]![0]!.fill).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('table structure ops', () => {
|
||||
const TBL_OFF = { x: 914400, y: 914400, cx: 3657600, cy: 1828800 }
|
||||
|
||||
it('inserts and deletes rows/cols, frame ext follows, round-trips', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const added = addTable(opened, 0, { rows: 2, cols: 2, offset: { ...TBL_OFF } })!
|
||||
const slide = added.slide
|
||||
let elementId = added.elementId
|
||||
editTableCellText(slide, elementId, 0, 0, [{ runs: [{ text: 'A1' }] }])
|
||||
|
||||
// Insert row below → 3 rows, frame gets taller
|
||||
let r = editTableStructure(opened, 0, elementId, { kind: 'insert-row', index: 0 })!
|
||||
expect(r).not.toBeNull()
|
||||
let tbl = r.slide.elements.find((e) => e.id === r!.elementId) as TableElement
|
||||
expect(tbl.rows.length).toBe(3)
|
||||
expect(tbl.transform.offset.cy).toBeGreaterThan(TBL_OFF.cy)
|
||||
// New row text is empty; original text remains
|
||||
expect(tbl.rows[0]![0]!.text!.paragraphs[0]!.runs[0]!.text).toBe('A1')
|
||||
elementId = r.elementId
|
||||
|
||||
// Insert column on the left → 3 columns, frame gets wider
|
||||
r = editTableStructure(opened, 0, elementId, { kind: 'insert-col', index: 1, before: true })!
|
||||
tbl = r.slide.elements.find((e) => e.id === r!.elementId) as TableElement
|
||||
expect(tbl.colWidths.length).toBe(3)
|
||||
expect(tbl.transform.offset.cx).toBeGreaterThan(TBL_OFF.cx)
|
||||
elementId = r.elementId
|
||||
|
||||
// Delete row/column back to 2×2
|
||||
r = editTableStructure(opened, 0, elementId, { kind: 'delete-row', index: 2 })!
|
||||
elementId = r.elementId
|
||||
r = editTableStructure(opened, 0, elementId, { kind: 'delete-col', index: 1 })!
|
||||
tbl = r.slide.elements.find((e) => e.id === r!.elementId) as TableElement
|
||||
expect(tbl.rows.length).toBe(2)
|
||||
expect(tbl.colWidths.length).toBe(2)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const tbl2 = reopened.deck.slides[0]!.elements.at(-1) as TableElement
|
||||
expect(tbl2.rows.length).toBe(2)
|
||||
expect(tbl2.colWidths.length).toBe(2)
|
||||
expect(tbl2.rows[0]![0]!.text!.paragraphs[0]!.runs[0]!.text).toBe('A1')
|
||||
})
|
||||
|
||||
it('refuses last row/col and merged tables', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const { slide, elementId } = addTable(opened, 0, { rows: 1, cols: 1, offset: { ...TBL_OFF } })!
|
||||
expect(editTableStructure(opened, 0, elementId, { kind: 'delete-row', index: 0 })).toBeNull()
|
||||
expect(editTableStructure(opened, 0, elementId, { kind: 'delete-col', index: 0 })).toBeNull()
|
||||
|
||||
const el = slide.elements.find((e) => e.id === elementId)!
|
||||
el.anchor.originalXml = el.anchor.originalXml.replace('<a:tc>', '<a:tc gridSpan="1">')
|
||||
expect(editTableStructure(opened, 0, elementId, { kind: 'insert-row', index: 0 })).toBeNull()
|
||||
})
|
||||
|
||||
it('setTableColWidth updates gridCol, model and frame width in place', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const { slide, elementId } = addTable(opened, 0, { rows: 2, cols: 2, offset: { ...TBL_OFF } })!
|
||||
const tbl = slide.elements.find((e) => e.id === elementId) as TableElement
|
||||
const w0 = tbl.colWidths[0]!
|
||||
|
||||
expect(setTableColWidth(slide, elementId, 0, w0 * 2)).toBe(true)
|
||||
expect(tbl.colWidths[0]).toBe(w0 * 2)
|
||||
expect(tbl.transform.offset.cx).toBe(w0 * 2 + tbl.colWidths[1]!)
|
||||
expect(setTableColWidth(slide, elementId, 5, 100)).toBe(false)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const tbl2 = reopened.deck.slides[0]!.elements.at(-1) as TableElement
|
||||
expect(tbl2.colWidths[0]).toBe(w0 * 2)
|
||||
expect(tbl2.transform.offset.cx).toBe(w0 * 2 + tbl2.colWidths[1]!)
|
||||
})
|
||||
})
|
||||
|
||||
describe('deleteSlide', () => {
|
||||
it('removes the slide from deck and package, round-trips', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const total = opened.deck.slides.length
|
||||
expect(total).toBeGreaterThan(1)
|
||||
const victim = opened.deck.slides[1]!.path
|
||||
|
||||
expect(deleteSlide(opened, 1)).toBe(true)
|
||||
expect(opened.deck.slides.length).toBe(total - 1)
|
||||
expect(opened.archive.entries.has(victim)).toBe(false)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides.length).toBe(total - 1)
|
||||
expect(reopened.deck.slides.some((s) => s.path === victim)).toBe(false)
|
||||
// No longer referenced by presentation.xml or [Content_Types]
|
||||
expect(reopened.archive.readText('[Content_Types].xml')).not.toContain(`/${victim}`)
|
||||
})
|
||||
|
||||
it('refuses to delete the last remaining slide', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
while (opened.deck.slides.length > 1) expect(deleteSlide(opened, 0)).toBe(true)
|
||||
expect(deleteSlide(opened, 0)).toBe(false)
|
||||
expect(opened.deck.slides.length).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('reorderElement', () => {
|
||||
it('moves element to front/back and persists order', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, { kind: 'rect', offset: { ...OFF }, fillColor: '#112233' })
|
||||
expect(slide.elements.at(-1)!.id).toBe(el.id)
|
||||
|
||||
expect(reorderElement(slide, el.id, 'back')).toBe(true)
|
||||
expect(slide.elements[0]!.id).toBe(el.id)
|
||||
expect(reorderElement(slide, el.id, 'back')).toBe(false) // already at the bottom
|
||||
expect(reorderElement(slide, el.id, 'forward')).toBe(true)
|
||||
expect(slide.elements[1]!.id).toBe(el.id)
|
||||
expect(reorderElement(slide, el.id, 'front')).toBe(true)
|
||||
expect(slide.elements.at(-1)!.id).toBe(el.id)
|
||||
|
||||
reorderElement(slide, el.id, 'back')
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const first: any = reopened.deck.slides[0]!.elements[0]
|
||||
expect(first.fill).toEqual({ type: 'solid', color: '#112233' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('slide transitions', () => {
|
||||
it('sets, reads back, replaces and clears a transition across save/reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
expect(getSlideTransition(slide)).toBe('none')
|
||||
|
||||
setSlideTransition(slide, 'fade')
|
||||
expect(getSlideTransition(slide)).toBe('fade')
|
||||
expect(slide.bodySuffix).toContain('<p:transition><p:fade/></p:transition>')
|
||||
|
||||
// Replace, don't stack
|
||||
setSlideTransition(slide, 'push')
|
||||
expect(slide.bodySuffix.match(/<p:transition/g)!.length).toBe(1)
|
||||
expect(getSlideTransition(slide)).toBe('push')
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideTransition(reopened.deck.slides[0]!)).toBe('push')
|
||||
|
||||
setSlideTransition(reopened.deck.slides[0]!, 'none')
|
||||
expect(getSlideTransition(reopened.deck.slides[0]!)).toBe('none')
|
||||
const again = await openPptx(await savePptx(reopened))
|
||||
expect(again.deck.slides[0]!.bodySuffix).not.toContain('<p:transition')
|
||||
})
|
||||
|
||||
it('writes morph as AlternateContent(p159:morph) with a fade fallback', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
setSlideTransition(slide, 'morph')
|
||||
expect(getSlideTransition(slide)).toBe('morph')
|
||||
// Newer PowerPoint uses p159:morph; older versions use the Fallback fade
|
||||
expect(slide.bodySuffix).toContain('<mc:AlternateContent')
|
||||
expect(slide.bodySuffix).toContain('<p159:morph option="byObject"/>')
|
||||
expect(slide.bodySuffix).toContain(
|
||||
'<mc:Fallback><p:transition spd="slow"><p:fade/></p:transition></mc:Fallback>',
|
||||
)
|
||||
expect(slide.bodySuffix).toContain('Requires="p159"')
|
||||
|
||||
// Lossless across save/reopen
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideTransition(reopened.deck.slides[0]!)).toBe('morph')
|
||||
})
|
||||
|
||||
it('replaces morph with a plain transition (no AlternateContent left) and clears it', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
setSlideTransition(slide, 'morph')
|
||||
setSlideTransition(slide, 'wipe')
|
||||
expect(slide.bodySuffix).not.toContain('<mc:AlternateContent')
|
||||
expect(slide.bodySuffix.match(/<p:transition/g)!.length).toBe(1)
|
||||
expect(getSlideTransition(slide)).toBe('wipe')
|
||||
|
||||
setSlideTransition(slide, 'morph')
|
||||
setSlideTransition(slide, 'none')
|
||||
expect(slide.bodySuffix).not.toContain('<p:transition')
|
||||
expect(slide.bodySuffix).not.toContain('<mc:AlternateContent')
|
||||
})
|
||||
|
||||
it('coexists with shape animations (morph transition before timing)', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const spid = elementSpid(slide.elements[0]!)!
|
||||
setSlideTransition(slide, 'morph')
|
||||
setSlideAnimations(slide, [
|
||||
{ spid, effect: 'fade', trigger: 'onClick', durationMs: 500, delayMs: 0 },
|
||||
])
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const suffix = reopened.deck.slides[0]!.bodySuffix
|
||||
expect(suffix.indexOf('p159:morph')).toBeGreaterThanOrEqual(0)
|
||||
expect(suffix.indexOf('p159:morph')).toBeLessThan(suffix.indexOf('<p:timing'))
|
||||
expect(getSlideTransition(reopened.deck.slides[0]!)).toBe('morph')
|
||||
expect(getSlideAnimations(reopened.deck.slides[0]!)).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('additional transition effects', () => {
|
||||
it('cover/pull/dissolve/zoom write-read round-trip', async () => {
|
||||
const { patchSlideTransitionXml, readSlideTransitionXml } = await import('../src/generate')
|
||||
for (const kind of ['cover', 'pull', 'dissolve', 'zoom'] as const) {
|
||||
const body = patchSlideTransitionXml(
|
||||
'<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>',
|
||||
kind,
|
||||
)
|
||||
expect(body).toContain(`<p:${kind}`)
|
||||
expect(readSlideTransitionXml(body)).toBe(kind)
|
||||
}
|
||||
})
|
||||
|
||||
it('replacing a transition leaves no stale nodes', async () => {
|
||||
const { patchSlideTransitionXml, readSlideTransitionXml } = await import('../src/generate')
|
||||
let body = patchSlideTransitionXml(
|
||||
'<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>',
|
||||
'cover',
|
||||
)
|
||||
body = patchSlideTransitionXml(body, 'zoom')
|
||||
expect(body).not.toContain('<p:cover')
|
||||
expect(readSlideTransitionXml(body)).toBe('zoom')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Phase 2: Connector shape attachments (a:stCxn/a:endCxn) —
|
||||
* setElementConnection byte surgery + move-following via updateConnectorsForMoved.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
openPptx,
|
||||
savePptx,
|
||||
createBlankPptx,
|
||||
setElementConnection,
|
||||
updateConnectorsForMoved,
|
||||
elementSpid,
|
||||
} from '../src/index'
|
||||
import { addElement } from '../src/insert'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
async function setup() {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const a = addElement(slide, {
|
||||
kind: 'rect',
|
||||
offset: { x: 0, y: 0, cx: 1000000, cy: 500000 },
|
||||
fillColor: '#4472C4',
|
||||
})
|
||||
const b = addElement(slide, {
|
||||
kind: 'rect',
|
||||
offset: { x: 3000000, y: 2000000, cx: 1000000, cy: 500000 },
|
||||
fillColor: '#ED7D31',
|
||||
})
|
||||
const cxn = addElement(slide, {
|
||||
kind: 'lineArrow',
|
||||
offset: { x: 1000000, y: 250000, cx: 2000000, cy: 2000000 },
|
||||
})
|
||||
return { opened, slide, a, b, cxn }
|
||||
}
|
||||
|
||||
describe('setElementConnection', () => {
|
||||
it('writes stCxn/endCxn into cNvCxnSpPr and updates the model', async () => {
|
||||
const { slide, a, b, cxn } = await setup()
|
||||
const aId = elementSpid(a)!
|
||||
const bId = elementSpid(b)!
|
||||
expect(
|
||||
setElementConnection(slide, cxn.id, {
|
||||
start: { id: aId, idx: 3 },
|
||||
end: { id: bId, idx: 0 },
|
||||
}),
|
||||
).toBe(true)
|
||||
const xml = cxn.anchor.originalXml
|
||||
expect(xml).toMatch(
|
||||
new RegExp(
|
||||
`<p:cNvCxnSpPr[^>]*><a:stCxn id="${aId}" idx="3"/><a:endCxn id="${bId}" idx="0"/></p:cNvCxnSpPr>`,
|
||||
),
|
||||
)
|
||||
expect(cxn.connection).toEqual({ start: { id: aId, idx: 3 }, end: { id: bId, idx: 0 } })
|
||||
})
|
||||
|
||||
it('undefined keeps the other end, null detaches', async () => {
|
||||
const { slide, a, b, cxn } = await setup()
|
||||
const aId = elementSpid(a)!
|
||||
const bId = elementSpid(b)!
|
||||
setElementConnection(slide, cxn.id, { start: { id: aId, idx: 3 }, end: { id: bId, idx: 0 } })
|
||||
// Re-attach only the end; start untouched
|
||||
setElementConnection(slide, cxn.id, { end: { id: bId, idx: 1 } })
|
||||
expect(cxn.connection).toEqual({ start: { id: aId, idx: 3 }, end: { id: bId, idx: 1 } })
|
||||
expect(cxn.anchor.originalXml).toContain(`<a:stCxn id="${aId}" idx="3"/>`)
|
||||
expect(cxn.anchor.originalXml).toContain(`<a:endCxn id="${bId}" idx="1"/>`)
|
||||
// Detach the start
|
||||
setElementConnection(slide, cxn.id, { start: null })
|
||||
expect(cxn.connection).toEqual({ end: { id: bId, idx: 1 } })
|
||||
expect(cxn.anchor.originalXml).not.toContain('<a:stCxn')
|
||||
})
|
||||
|
||||
it('attached connector follows the shape after updateConnectorsForMoved', async () => {
|
||||
const { slide, a, b, cxn } = await setup()
|
||||
setElementConnection(slide, cxn.id, {
|
||||
start: { id: elementSpid(a)!, idx: 3 },
|
||||
end: { id: elementSpid(b)!, idx: 0 },
|
||||
})
|
||||
b.transform.offset = { x: 5000000, y: 4000000, cx: 1000000, cy: 500000 }
|
||||
b.dirtyTransform = true
|
||||
expect(updateConnectorsForMoved(slide, [b.id])).toBe(1)
|
||||
// start = right midpoint of a (1000000, 250000); end = top midpoint of b (5500000, 4000000)
|
||||
expect(cxn.transform.offset).toEqual({ x: 1000000, y: 250000, cx: 4500000, cy: 3750000 })
|
||||
expect(cxn.transform.flipH).toBe(false)
|
||||
expect(cxn.transform.flipV).toBe(false)
|
||||
expect(cxn.dirtyTransform).toBe(true)
|
||||
})
|
||||
|
||||
it('round-trips through save: stCxn/endCxn reparsed into connection', async () => {
|
||||
const { opened, slide, a, b, cxn } = await setup()
|
||||
const aId = elementSpid(a)!
|
||||
const bId = elementSpid(b)!
|
||||
setElementConnection(slide, cxn.id, { start: { id: aId, idx: 3 }, end: { id: bId, idx: 0 } })
|
||||
const reopened = await openPptx(Buffer.from(await savePptx(opened)))
|
||||
const parsed = reopened.deck.slides[0]!.elements.find(
|
||||
(e) => (e as TextElement).presetGeometry === 'straightConnector1',
|
||||
)
|
||||
expect(parsed?.connection).toEqual({ start: { id: aId, idx: 3 }, end: { id: bId, idx: 0 } })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide, parseDecorations } from '../src/parse'
|
||||
import type { TextElement, GroupElement } from '../src/types'
|
||||
|
||||
const wrap = (spTree: string) =>
|
||||
`<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld><p:spTree>` +
|
||||
`<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/>` +
|
||||
spTree +
|
||||
`</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
const CXN = `<p:cxnSp>
|
||||
<p:nvCxnSpPr><p:cNvPr id="4" name="Straight Arrow Connector 3"/><p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>
|
||||
<p:spPr>
|
||||
<a:xfrm flipV="1"><a:off x="100" y="200"/><a:ext cx="914400" cy="457200"/></a:xfrm>
|
||||
<a:prstGeom prst="bentConnector3"><a:avLst><a:gd name="adj1" fmla="val 75000"/></a:avLst></a:prstGeom>
|
||||
<a:ln w="19050"><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill><a:prstDash val="dash"/><a:tailEnd type="triangle"/></a:ln>
|
||||
</p:spPr>
|
||||
</p:cxnSp>`
|
||||
|
||||
describe('p:cxnSp connector parsing', () => {
|
||||
it('parses connector as stroked shape with geometry/adjust/arrow', () => {
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: wrap(CXN), ctx: {} })
|
||||
expect(slide.elements).toHaveLength(1)
|
||||
const el = slide.elements[0] as TextElement
|
||||
expect(el.type).toBe('shape')
|
||||
expect(el.presetGeometry).toBe('bentConnector3')
|
||||
expect(el.adjust?.adj1).toBe(75000)
|
||||
expect(el.transform.flipV).toBe(true)
|
||||
expect(el.fill).toEqual({ type: 'none' })
|
||||
expect(el.stroke?.width).toBe(19050)
|
||||
expect(el.stroke?.fill).toEqual({ type: 'solid', color: '#FF0000' })
|
||||
expect(el.stroke?.dash).toBe('dash')
|
||||
expect(el.stroke?.tailEnd).toEqual({ type: 'triangle' })
|
||||
expect(el.stroke?.headEnd).toBeUndefined()
|
||||
})
|
||||
|
||||
it('connector without explicit ln fill falls back to visible stroke', () => {
|
||||
const bare = `<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="5" name="c"/><p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>
|
||||
<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="0"/></a:xfrm>
|
||||
<a:prstGeom prst="line"><a:avLst/></a:prstGeom></p:spPr></p:cxnSp>`
|
||||
const slide = parseSlide({ path: 'p', slideXml: wrap(bare), ctx: {} })
|
||||
const el = slide.elements[0] as TextElement
|
||||
expect(el.stroke).toBeTruthy()
|
||||
expect(el.stroke!.fill.type).toBe('solid')
|
||||
})
|
||||
|
||||
it('parses connector inside a group', () => {
|
||||
const grp = `<p:grpSp><p:nvGrpSpPr><p:cNvPr id="6" name="g"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>
|
||||
<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/><a:chOff x="0" y="0"/><a:chExt cx="914400" cy="914400"/></a:xfrm></p:grpSpPr>
|
||||
${CXN}</p:grpSp>`
|
||||
const slide = parseSlide({ path: 'p', slideXml: wrap(grp), ctx: {} })
|
||||
const g = slide.elements[0] as GroupElement
|
||||
expect(g.type).toBe('group')
|
||||
expect(g.children).toHaveLength(1)
|
||||
expect((g.children[0] as TextElement).presetGeometry).toBe('bentConnector3')
|
||||
})
|
||||
})
|
||||
|
||||
const LAYOUT = `<?xml version="1.0"?><p:sldLayout xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree>
|
||||
<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/>
|
||||
<p:sp>
|
||||
<p:nvSpPr><p:cNvPr id="2" name="Title Placeholder"/><p:cNvSpPr/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>
|
||||
<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm></p:spPr>
|
||||
<p:txBody><a:bodyPr/><a:p><a:r><a:t>Click to edit title</a:t></a:r></a:p></p:txBody>
|
||||
</p:sp>
|
||||
<p:sp>
|
||||
<p:nvSpPr><p:cNvPr id="3" name="logo color bar"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>
|
||||
<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="12192000" cy="100000"/></a:xfrm>
|
||||
<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>
|
||||
<a:solidFill><a:srgbClr val="C43E1C"/></a:solidFill></p:spPr>
|
||||
</p:sp>
|
||||
<p:sp>
|
||||
<p:nvSpPr><p:cNvPr id="4" name="Slide Number"/><p:cNvSpPr/><p:nvPr><p:ph type="sldNum" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr>
|
||||
<p:spPr><a:xfrm><a:off x="11000000" y="6500000"/><a:ext cx="900000" cy="300000"/></a:xfrm></p:spPr>
|
||||
<p:txBody><a:bodyPr/><a:p><a:fld id="{X}" type="slidenum"><a:rPr lang="en-US"/><a:t>‹#›</a:t></a:fld></a:p></p:txBody>
|
||||
</p:sp>
|
||||
<p:sp>
|
||||
<p:nvSpPr><p:cNvPr id="5" name="Footer"/><p:cNvSpPr/><p:nvPr><p:ph type="ftr" sz="quarter" idx="11"/></p:nvPr></p:nvSpPr>
|
||||
<p:spPr><a:xfrm><a:off x="4000000" y="6500000"/><a:ext cx="4000000" cy="300000"/></a:xfrm></p:spPr>
|
||||
<p:txBody><a:bodyPr/><a:p><a:r><a:t>Company Confidential</a:t></a:r></a:p></p:txBody>
|
||||
</p:sp>
|
||||
</p:spTree></p:cSld></p:sldLayout>`
|
||||
|
||||
describe('parseDecorations (master/layout decoration layer)', () => {
|
||||
it('keeps non-placeholder shapes, drops content placeholders', () => {
|
||||
const decos = parseDecorations(LAYOUT, {}, { hfTypes: new Set() })
|
||||
expect(decos).toHaveLength(1)
|
||||
expect(decos[0]!.name).toBe('logo color bar')
|
||||
expect((decos[0] as TextElement).fill).toEqual({ type: 'solid', color: '#C43E1C' })
|
||||
})
|
||||
|
||||
it('includes enabled footer-family placeholders and substitutes slide number', () => {
|
||||
const decos = parseDecorations(LAYOUT, {}, { hfTypes: new Set(['ftr', 'sldNum']), slideNum: 7 })
|
||||
expect(decos).toHaveLength(3)
|
||||
const sldNum = decos.find((d) => (d as TextElement).placeholder === 'sldNum') as TextElement
|
||||
expect(sldNum).toBeTruthy()
|
||||
const runs = sldNum.text!.paragraphs.flatMap((p) => p.runs)
|
||||
expect(runs.some((r) => r.field === 'slidenum' && r.text === '7')).toBe(true)
|
||||
const ftr = decos.find((d) => (d as TextElement).placeholder === 'ftr') as TextElement
|
||||
expect(ftr.text!.paragraphs[0]!.runs[0]!.text).toBe('Company Confidential')
|
||||
})
|
||||
|
||||
it('subset of hfTypes filters accordingly', () => {
|
||||
const decos = parseDecorations(LAYOUT, {}, { hfTypes: new Set(['ftr']) })
|
||||
expect(decos.map((d) => (d as TextElement).placeholder ?? 'none').sort()).toEqual(
|
||||
['ftr', 'none'].sort(),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
/** Connector attachment parsing + endpoint follow after a connected shape moves. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { updateConnectorsForMoved } from '../src/index'
|
||||
|
||||
const SP = (id: number, x: number, y: number) =>
|
||||
`<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="S${id}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
|
||||
`<p:spPr><a:xfrm><a:off x="${x}" y="${y}"/><a:ext cx="1000" cy="600"/></a:xfrm>` +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:sp>'
|
||||
|
||||
const CXN =
|
||||
'<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="9" name="C"/>' +
|
||||
'<p:cNvCxnSpPr><a:stCxn id="2" idx="3"/><a:endCxn id="3" idx="1"/></p:cNvCxnSpPr><p:nvPr/></p:nvCxnSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="1000" y="300"/><a:ext cx="1000" cy="0"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="straightConnector1"><a:avLst/></a:prstGeom></p:spPr></p:cxnSp>'
|
||||
|
||||
const slideXml =
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree>' +
|
||||
`<p:nvGrpSpPr/><p:grpSpPr/>${SP(2, 0, 0)}${SP(3, 2000, 0)}${CXN}</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
describe('connector following', () => {
|
||||
it('parses stCxn/endCxn attachment relations', () => {
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml, ctx: {} })
|
||||
const cxn = slide.elements.find((e) => e.connection)!
|
||||
expect(cxn.connection).toEqual({ start: { id: 2, idx: 3 }, end: { id: 3, idx: 1 } })
|
||||
})
|
||||
|
||||
it('endpoints reflow after a connected shape moves (idx 3=right-edge midpoint → idx 1=left-edge midpoint)', () => {
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml, ctx: {} })
|
||||
const s3 = slide.elements.find((e) => e.name === 'S3')!
|
||||
// Move S3 to (4000, 2000)
|
||||
s3.transform.offset = { x: 4000, y: 2000, cx: 1000, cy: 600 }
|
||||
const n = updateConnectorsForMoved(slide, [s3.id])
|
||||
expect(n).toBe(1)
|
||||
const cxn = slide.elements.find((e) => e.connection)!
|
||||
// Start = midpoint of S2's right edge (1000, 300); end = midpoint of S3's left edge (4000, 2300)
|
||||
expect(cxn.transform.offset).toEqual({ x: 1000, y: 300, cx: 3000, cy: 2000 })
|
||||
expect(cxn.transform.flipH).toBe(false)
|
||||
expect(cxn.transform.flipV).toBe(false)
|
||||
expect(cxn.dirtyTransform).toBe(true)
|
||||
})
|
||||
|
||||
it('flip expresses direction when the target moves above-left of the start', () => {
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml, ctx: {} })
|
||||
const s3 = slide.elements.find((e) => e.name === 'S3')!
|
||||
s3.transform.offset = { x: -3000, y: -2000, cx: 1000, cy: 600 }
|
||||
updateConnectorsForMoved(slide, [s3.id])
|
||||
const cxn = slide.elements.find((e) => e.connection)!
|
||||
expect(cxn.transform.flipH).toBe(true)
|
||||
expect(cxn.transform.flipV).toBe(true)
|
||||
})
|
||||
|
||||
it('moving an unattached element does not affect connectors', () => {
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml, ctx: {} })
|
||||
const cxnBefore = JSON.stringify(slide.elements.find((e) => e.connection)!.transform)
|
||||
expect(updateConnectorsForMoved(slide, ['nonexistent'])).toBe(0)
|
||||
expect(JSON.stringify(slide.elements.find((e) => e.connection)!.transform)).toBe(cxnBefore)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* Connector (p:cxnSp) parsing tests:
|
||||
* - one each of straight / bent / curved + arrows + flip
|
||||
* - roundtrip: connector slide bytes stay identical
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { openPptx, savePptx, reassembleSlideXml } from '../src/index'
|
||||
import type { TextElement } from '../src/types'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
// XML construction helpers
|
||||
const wrap = (spTree: string) =>
|
||||
`<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld><p:spTree>` +
|
||||
`<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/>` +
|
||||
spTree +
|
||||
`</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
// ── 1. straight connector (line/straightConnector1) ───────────────────────────
|
||||
|
||||
const STRAIGHT_CXN = `<p:cxnSp>
|
||||
<p:nvCxnSpPr><p:cNvPr id="10" name="Straight Connector 1"/><p:cNvCxnSpPr><a:stCxn id="2" idx="3"/><a:endCxn id="3" idx="1"/></p:cNvCxnSpPr><p:nvPr/></p:nvCxnSpPr>
|
||||
<p:spPr>
|
||||
<a:xfrm flipH="1"><a:off x="500" y="300"/><a:ext cx="914400" cy="457200"/></a:xfrm>
|
||||
<a:prstGeom prst="line"><a:avLst/></a:prstGeom>
|
||||
<a:ln w="19050">
|
||||
<a:solidFill><a:srgbClr val="0070C0"/></a:solidFill>
|
||||
<a:headEnd type="arrow" w="sm" len="lg"/>
|
||||
<a:tailEnd type="stealth" w="lg" len="sm"/>
|
||||
</a:ln>
|
||||
</p:spPr>
|
||||
</p:cxnSp>`
|
||||
|
||||
describe('straight connector parsing', () => {
|
||||
it('parses as type=shape, presetGeometry=line, flipH correct', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: wrap(STRAIGHT_CXN),
|
||||
ctx: {},
|
||||
})
|
||||
expect(slide.elements).toHaveLength(1)
|
||||
const el = slide.elements[0] as TextElement
|
||||
expect(el.type).toBe('shape')
|
||||
expect(el.presetGeometry).toBe('line')
|
||||
expect(el.transform.flipH).toBe(true)
|
||||
expect(el.transform.flipV).toBe(false)
|
||||
expect(el.fill).toEqual({ type: 'none' })
|
||||
expect(el.stroke?.fill).toEqual({ type: 'solid', color: '#0070C0' })
|
||||
expect(el.stroke?.width).toBe(19050)
|
||||
})
|
||||
|
||||
it('headEnd parses with type/w/len', () => {
|
||||
const slide = parseSlide({ path: 'p', slideXml: wrap(STRAIGHT_CXN), ctx: {} })
|
||||
const el = slide.elements[0] as TextElement
|
||||
expect(el.stroke?.headEnd).toEqual({ type: 'arrow', w: 'sm', len: 'lg' })
|
||||
})
|
||||
|
||||
it('tailEnd stealth parses with type/w/len', () => {
|
||||
const slide = parseSlide({ path: 'p', slideXml: wrap(STRAIGHT_CXN), ctx: {} })
|
||||
const el = slide.elements[0] as TextElement
|
||||
expect(el.stroke?.tailEnd).toEqual({ type: 'stealth', w: 'lg', len: 'sm' })
|
||||
})
|
||||
})
|
||||
|
||||
// ── 2. bent connector (bentConnector3) ───────────────────────────────────────
|
||||
|
||||
const BENT_CXN = `<p:cxnSp>
|
||||
<p:nvCxnSpPr><p:cNvPr id="11" name="Elbow Connector"/><p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>
|
||||
<p:spPr>
|
||||
<a:xfrm flipV="1"><a:off x="100" y="200"/><a:ext cx="914400" cy="457200"/></a:xfrm>
|
||||
<a:prstGeom prst="bentConnector3">
|
||||
<a:avLst><a:gd name="adj1" fmla="val 75000"/></a:avLst>
|
||||
</a:prstGeom>
|
||||
<a:ln w="19050">
|
||||
<a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>
|
||||
<a:prstDash val="dash"/>
|
||||
<a:tailEnd type="triangle"/>
|
||||
</a:ln>
|
||||
</p:spPr>
|
||||
</p:cxnSp>`
|
||||
|
||||
describe('bent connector parsing', () => {
|
||||
it('presetGeometry=bentConnector3, adj1=75000', () => {
|
||||
const slide = parseSlide({ path: 'p', slideXml: wrap(BENT_CXN), ctx: {} })
|
||||
const el = slide.elements[0] as TextElement
|
||||
expect(el.presetGeometry).toBe('bentConnector3')
|
||||
expect(el.adjust?.adj1).toBe(75000)
|
||||
expect(el.transform.flipV).toBe(true)
|
||||
expect(el.stroke?.dash).toBe('dash')
|
||||
expect(el.stroke?.tailEnd).toEqual({ type: 'triangle' })
|
||||
expect(el.stroke?.headEnd).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
// ── 3. curved connector (curvedConnector3) ───────────────────────────────────
|
||||
|
||||
const CURVED_CXN = `<p:cxnSp>
|
||||
<p:nvCxnSpPr><p:cNvPr id="12" name="Curved Connector"/><p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>
|
||||
<p:spPr>
|
||||
<a:xfrm><a:off x="200" y="400"/><a:ext cx="1828800" cy="914400"/></a:xfrm>
|
||||
<a:prstGeom prst="curvedConnector3">
|
||||
<a:avLst><a:gd name="adj1" fmla="val 50000"/></a:avLst>
|
||||
</a:prstGeom>
|
||||
<a:ln w="12700">
|
||||
<a:solidFill><a:srgbClr val="00B050"/></a:solidFill>
|
||||
<a:headEnd type="oval"/>
|
||||
<a:tailEnd type="diamond" w="lg" len="lg"/>
|
||||
</a:ln>
|
||||
</p:spPr>
|
||||
</p:cxnSp>`
|
||||
|
||||
describe('curved connector parsing', () => {
|
||||
it('presetGeometry=curvedConnector3, oval/diamond arrowheads', () => {
|
||||
const slide = parseSlide({ path: 'p', slideXml: wrap(CURVED_CXN), ctx: {} })
|
||||
const el = slide.elements[0] as TextElement
|
||||
expect(el.presetGeometry).toBe('curvedConnector3')
|
||||
expect(el.adjust?.adj1).toBe(50000)
|
||||
expect(el.stroke?.headEnd).toEqual({ type: 'oval' })
|
||||
expect(el.stroke?.tailEnd).toEqual({ type: 'diamond', w: 'lg', len: 'lg' })
|
||||
})
|
||||
})
|
||||
|
||||
// ── 4. Fallback to a visible stroke when ln is absent ────────────────────
|
||||
|
||||
const BARE_CXN = `<p:cxnSp>
|
||||
<p:nvCxnSpPr><p:cNvPr id="13" name="c"/><p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>
|
||||
<p:spPr>
|
||||
<a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="0"/></a:xfrm>
|
||||
<a:prstGeom prst="line"><a:avLst/></a:prstGeom>
|
||||
</p:spPr>
|
||||
</p:cxnSp>`
|
||||
|
||||
describe('fallback without explicit ln', () => {
|
||||
it('has a default visible stroke when ln is absent', () => {
|
||||
const slide = parseSlide({ path: 'p', slideXml: wrap(BARE_CXN), ctx: {} })
|
||||
const el = slide.elements[0] as TextElement
|
||||
expect(el.stroke).toBeTruthy()
|
||||
expect(el.stroke!.fill.type).toBe('solid')
|
||||
})
|
||||
})
|
||||
|
||||
// ── 5. Roundtrip: byte fidelity after parse + reassemble ─────────────────
|
||||
|
||||
describe('connector slide roundtrip fidelity', () => {
|
||||
it('pptx containing cxnSp reassembles to byte-identical slide XML', async () => {
|
||||
// Use 01_standard_business.pptx (fine even without connectors: fidelity means unchanged)
|
||||
const { deck } = await openPptx(fx('01_standard_business.pptx'))
|
||||
// Confirm reassemble == originalXml slide by slide
|
||||
for (const slide of deck.slides) {
|
||||
expect(reassembleSlideXml(slide)).toBe(slide.originalXml)
|
||||
}
|
||||
})
|
||||
|
||||
it('reparses after savePptx: connector elements neither lost nor distorted', async () => {
|
||||
// Building a minimal pptx with cxnSp: the helper-wrapped xml can't be packed into a pptx,
|
||||
// so use 01_standard_business.pptx to verify saving doesn't break existing slides
|
||||
const original = await openPptx(fx('01_standard_business.pptx'))
|
||||
const savedBytes = await savePptx(original)
|
||||
const reopened = await openPptx(savedBytes)
|
||||
expect(reopened.deck.slides.length).toBe(original.deck.slides.length)
|
||||
// Element count matches per slide (any cxnSp present is not lost)
|
||||
for (let i = 0; i < original.deck.slides.length; i++) {
|
||||
expect(reopened.deck.slides[i]!.elements.length).toBe(
|
||||
original.deck.slides[i]!.elements.length,
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,253 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import {
|
||||
openPptx,
|
||||
savePptx,
|
||||
copySlide,
|
||||
pasteSlide,
|
||||
listLayouts,
|
||||
chooseLayout,
|
||||
materializeSlideBundle,
|
||||
} from '../src/index'
|
||||
import type { SlideBundle } from '../src/index'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const slideText = (slide: any): string =>
|
||||
slide.elements
|
||||
.filter((e: any) => e.type === 'text' || e.type === 'shape')
|
||||
.flatMap((e: any) => e.text?.paragraphs ?? [])
|
||||
.flatMap((p: any) => p.runs)
|
||||
.map((r: any) => r.text)
|
||||
.join('')
|
||||
|
||||
describe('copySlide / pasteSlide across decks', () => {
|
||||
it('carries a slide into another deck and survives save → reopen', async () => {
|
||||
const source = await openPptx(fx('05_unicode_cjk_emoji.pptx'))
|
||||
const target = await openPptx(fx('01_standard_business.pptx'))
|
||||
const sourceText = slideText(source.deck.slides[0])
|
||||
const targetCount = target.deck.slides.length
|
||||
|
||||
const bundle = copySlide(source, 0)
|
||||
expect(bundle).not.toBeNull()
|
||||
const pasted = pasteSlide(target, 0, bundle!)
|
||||
expect(pasted).not.toBeNull()
|
||||
expect(target.deck.slides.length).toBe(targetCount + 1)
|
||||
expect(target.deck.slides[1]).toBe(pasted)
|
||||
|
||||
const reopened = await openPptx(await savePptx(target))
|
||||
expect(reopened.deck.slides.length).toBe(targetCount + 1)
|
||||
expect(slideText(reopened.deck.slides[1])).toBe(sourceText)
|
||||
})
|
||||
|
||||
it('points the pasted slide at a layout that exists in the destination', async () => {
|
||||
const source = await openPptx(fx('05_unicode_cjk_emoji.pptx'))
|
||||
const target = await openPptx(fx('01_standard_business.pptx'))
|
||||
const bundle = copySlide(source, 0)!
|
||||
const pasted = pasteSlide(target, 0, bundle)!
|
||||
|
||||
const layoutRel = [...target.archive.readRels(pasted.path).values()].find((rel) =>
|
||||
rel.type.endsWith('/slideLayout'),
|
||||
)
|
||||
expect(layoutRel).toBeDefined()
|
||||
const layoutPath = `ppt/${layoutRel!.target.replace('../', '')}`
|
||||
expect(listLayouts(target.archive).map((l) => l.path)).toContain(layoutPath)
|
||||
// the source's own layout part must not have been dragged along
|
||||
expect(target.archive.has('ppt/slideLayouts/slideLayout99.xml')).toBe(false)
|
||||
})
|
||||
|
||||
it('copies referenced media under a fresh name without clobbering the target', async () => {
|
||||
const source = await openPptx(fx('05_unicode_cjk_emoji.pptx'))
|
||||
const target = await openPptx(fx('01_standard_business.pptx'))
|
||||
const mediaBefore = [...target.archive.entries.keys()].filter((p) => p.startsWith('ppt/media/'))
|
||||
const sourceMedia = [...source.archive.entries.keys()].filter((p) => p.startsWith('ppt/media/'))
|
||||
|
||||
const bundle = copySlide(source, 0)!
|
||||
const pasted = pasteSlide(target, 0, bundle)!
|
||||
const rels = [...target.archive.readRels(pasted.path).values()]
|
||||
const imageRels = rels.filter((rel) => rel.type.endsWith('/image'))
|
||||
|
||||
for (const rel of imageRels) {
|
||||
const path = `ppt/${rel.target.replace('../', '')}`
|
||||
expect(target.archive.has(path)).toBe(true)
|
||||
}
|
||||
// nothing that already existed in the target was overwritten
|
||||
for (const path of mediaBefore) expect(target.archive.has(path)).toBe(true)
|
||||
if (sourceMedia.length > 0 && imageRels.length > 0) {
|
||||
const after = [...target.archive.entries.keys()].filter((p) => p.startsWith('ppt/media/'))
|
||||
expect(after.length).toBeGreaterThan(mediaBefore.length)
|
||||
}
|
||||
|
||||
// every content type the new parts need is declared
|
||||
const ct = target.archive.readText('[Content_Types].xml')!
|
||||
for (const rel of imageRels) {
|
||||
const ext = rel.target.slice(rel.target.lastIndexOf('.') + 1).toLowerCase()
|
||||
expect(ct.toLowerCase()).toContain(`extension="${ext}"`)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps rIds stable so the pasted slide XML needs no rewriting', async () => {
|
||||
const source = await openPptx(fx('05_unicode_cjk_emoji.pptx'))
|
||||
const target = await openPptx(fx('01_standard_business.pptx'))
|
||||
const sourceRelIds = [...source.archive.readRels(source.deck.slides[0]!.path).values()]
|
||||
.filter((rel) => !rel.type.endsWith('/notesSlide'))
|
||||
.map((rel) => rel.id)
|
||||
.sort()
|
||||
|
||||
const pasted = pasteSlide(target, 0, copySlide(source, 0)!)!
|
||||
const pastedRelIds = [...target.archive.readRels(pasted.path).values()]
|
||||
.map((rel) => rel.id)
|
||||
.sort()
|
||||
expect(pastedRelIds).toEqual(sourceRelIds)
|
||||
})
|
||||
|
||||
it('gives each bundled media part its own destination when names collide with the target', async () => {
|
||||
const target = await openPptx(fx('01_standard_business.pptx'))
|
||||
// the target now occupies both names the bundle wants
|
||||
target.archive.entries.set('ppt/media/image2.png', new Uint8Array([9, 9, 9]))
|
||||
|
||||
const IMAGE_REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'
|
||||
const LAYOUT_REL =
|
||||
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout'
|
||||
const bundle: SlideBundle = {
|
||||
slideXml: '<p:sld/>',
|
||||
rels: [
|
||||
{ id: 'rId1', type: LAYOUT_REL, target: 'ppt/slideLayouts/slideLayout1.xml', layout: true },
|
||||
{ id: 'rId2', type: IMAGE_REL, target: 'ppt/media/image1.png' },
|
||||
{ id: 'rId3', type: IMAGE_REL, target: 'ppt/media/image2.png' },
|
||||
],
|
||||
parts: {
|
||||
'ppt/media/image1.png': Buffer.from('AAAA-image-A').toString('base64'),
|
||||
'ppt/media/image2.png': Buffer.from('BBBB-image-B').toString('base64'),
|
||||
},
|
||||
contentTypes: { png: 'image/png' },
|
||||
}
|
||||
|
||||
const layoutPath = chooseLayout(target.archive, bundle)!
|
||||
const relsXml = materializeSlideBundle(
|
||||
target.archive,
|
||||
bundle,
|
||||
'ppt/slides/slide99.xml',
|
||||
layoutPath,
|
||||
)
|
||||
|
||||
const targets = [...relsXml.matchAll(/Target="(\.\.\/media\/[^"]+)"/g)].map((m) => m[1]!)
|
||||
expect(new Set(targets).size).toBe(2)
|
||||
const bytesAt = (t: string) =>
|
||||
Buffer.from(target.archive.readBytes('ppt/' + t.replace('../', ''))!).toString()
|
||||
expect(bytesAt(targets[0]!)).toBe('AAAA-image-A')
|
||||
expect(bytesAt(targets[1]!)).toBe('BBBB-image-B')
|
||||
})
|
||||
|
||||
it('pastes at the front when afterIndex is -1', async () => {
|
||||
const source = await openPptx(fx('05_unicode_cjk_emoji.pptx'))
|
||||
const target = await openPptx(fx('01_standard_business.pptx'))
|
||||
const sourceText = slideText(source.deck.slides[0])
|
||||
|
||||
const pasted = pasteSlide(target, -1, copySlide(source, 0)!)
|
||||
expect(target.deck.slides[0]).toBe(pasted)
|
||||
const reopened = await openPptx(await savePptx(target))
|
||||
expect(slideText(reopened.deck.slides[0])).toBe(sourceText)
|
||||
})
|
||||
|
||||
it('keep-source-formatting imports the source layout chain and registers its master', async () => {
|
||||
// forge a source deck whose theme differs from the target's
|
||||
const source = await openPptx(fx('05_unicode_cjk_emoji.pptx'))
|
||||
const themeXml = source.archive.readText('ppt/theme/theme1.xml')!
|
||||
source.archive.entries.set(
|
||||
'ppt/theme/theme1.xml',
|
||||
Buffer.from(themeXml.replace('4F81BD', '123456'), 'utf8'),
|
||||
)
|
||||
const target = await openPptx(fx('01_standard_business.pptx'))
|
||||
const masters = () =>
|
||||
[...target.archive.entries.keys()].filter((p) =>
|
||||
/^ppt\/slideMasters\/slideMaster\d+\.xml$/.test(p),
|
||||
).length
|
||||
const mastersBefore = masters()
|
||||
|
||||
const bundle = copySlide(source, 0)!
|
||||
expect(bundle.chain).toBeDefined()
|
||||
const pasted = pasteSlide(target, 0, bundle, { keepSourceFormatting: true })
|
||||
expect(pasted).not.toBeNull()
|
||||
|
||||
// a new master arrived and is registered in presentation.xml(.rels)
|
||||
expect(masters()).toBe(mastersBefore + 1)
|
||||
const pres = target.archive.readText('ppt/presentation.xml')!
|
||||
expect([...pres.matchAll(/<p:sldMasterId\s/g)].length).toBe(mastersBefore + 1)
|
||||
|
||||
// the pasted slide points at the imported layout (byte-identical to the source's)
|
||||
const layoutRel = [...target.archive.readRels(pasted!.path).values()].find((rel) =>
|
||||
rel.type.endsWith('/slideLayout'),
|
||||
)!
|
||||
const layoutPath = `ppt/${layoutRel.target.replace('../', '')}`
|
||||
expect(target.archive.readText(layoutPath)).toBe(
|
||||
source.archive.readText(bundle.chain!.layoutPath),
|
||||
)
|
||||
|
||||
// survives save → reopen
|
||||
const reopened = await openPptx(await savePptx(target))
|
||||
expect(reopened.deck.slides.length).toBe(target.deck.slides.length)
|
||||
})
|
||||
|
||||
it('keep-source-formatting reuses an identical existing master instead of importing', async () => {
|
||||
// the two fixtures share one template: the chain must be reused, not duplicated
|
||||
const source = await openPptx(fx('05_unicode_cjk_emoji.pptx'))
|
||||
const target = await openPptx(fx('01_standard_business.pptx'))
|
||||
const masterParts = () =>
|
||||
[...target.archive.entries.keys()].filter((p) => p.startsWith('ppt/slideMasters/')).length
|
||||
const mastersBefore = masterParts()
|
||||
|
||||
const bundle = copySlide(source, 0)!
|
||||
expect(pasteSlide(target, 0, bundle, { keepSourceFormatting: true })).not.toBeNull()
|
||||
expect(masterParts()).toBe(mastersBefore)
|
||||
})
|
||||
|
||||
it('pasting the same foreign chain twice imports its master only once', async () => {
|
||||
const source = await openPptx(fx('05_unicode_cjk_emoji.pptx'))
|
||||
const themeXml = source.archive.readText('ppt/theme/theme1.xml')!
|
||||
source.archive.entries.set(
|
||||
'ppt/theme/theme1.xml',
|
||||
Buffer.from(themeXml.replace('4F81BD', '123456'), 'utf8'),
|
||||
)
|
||||
const target = await openPptx(fx('01_standard_business.pptx'))
|
||||
const masters = () =>
|
||||
[...target.archive.entries.keys()].filter((p) =>
|
||||
/^ppt\/slideMasters\/slideMaster\d+\.xml$/.test(p),
|
||||
).length
|
||||
const mastersBefore = masters()
|
||||
|
||||
const bundle = copySlide(source, 0)!
|
||||
pasteSlide(target, 0, bundle, { keepSourceFormatting: true })
|
||||
pasteSlide(target, 1, bundle, { keepSourceFormatting: true })
|
||||
expect(masters()).toBe(mastersBefore + 1)
|
||||
})
|
||||
|
||||
it('keep-source-formatting falls back to the destination theme without a chain', async () => {
|
||||
const source = await openPptx(fx('05_unicode_cjk_emoji.pptx'))
|
||||
const target = await openPptx(fx('01_standard_business.pptx'))
|
||||
const { chain: _chain, ...rest } = copySlide(source, 0)!
|
||||
const pasted = pasteSlide(target, 0, rest as SlideBundle, { keepSourceFormatting: true })
|
||||
expect(pasted).not.toBeNull()
|
||||
const layoutRel = [...target.archive.readRels(pasted!.path).values()].find((rel) =>
|
||||
rel.type.endsWith('/slideLayout'),
|
||||
)!
|
||||
const layoutPath = `ppt/${layoutRel.target.replace('../', '')}`
|
||||
expect(listLayouts(target.archive).map((l) => l.path)).toContain(layoutPath)
|
||||
})
|
||||
|
||||
it('pasting twice produces two independent slides', async () => {
|
||||
const source = await openPptx(fx('05_unicode_cjk_emoji.pptx'))
|
||||
const target = await openPptx(fx('01_standard_business.pptx'))
|
||||
const bundle = copySlide(source, 0)!
|
||||
const first = pasteSlide(target, 0, bundle)!
|
||||
const second = pasteSlide(target, 1, bundle)!
|
||||
expect(first.path).not.toBe(second.path)
|
||||
|
||||
const reopened = await openPptx(await savePptx(target))
|
||||
expect(reopened.deck.slides.length).toBe(target.deck.slides.length)
|
||||
expect(slideText(reopened.deck.slides[1])).toBe(slideText(reopened.deck.slides[2]))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,240 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseCustGeom, evalGuides } from '../src/custgeom'
|
||||
import { parseSlide } from '../src/parse'
|
||||
|
||||
describe('evalGuides (gd guide formula evaluation)', () => {
|
||||
const g = (fmla: string, w = 200, h = 100) => evalGuides([{ name: 'x', fmla }], w, h).x
|
||||
|
||||
it('val / built-in variables', () => {
|
||||
expect(g('val 50000')).toBe(50000)
|
||||
expect(evalGuides([{ name: 'x', fmla: 'val w' }], 200, 100).x).toBe(200)
|
||||
expect(g('val hc')).toBe(100)
|
||||
expect(g('val ss')).toBe(100)
|
||||
expect(g('val wd2')).toBe(100)
|
||||
expect(g('val 3cd4')).toBe(16200000)
|
||||
})
|
||||
|
||||
it('*/ (mulDiv) and +- (addSub) and +/', () => {
|
||||
expect(g('*/ w 1 2')).toBe(100)
|
||||
expect(g('+- w h 50')).toBe(250)
|
||||
expect(g('+/ w h 2')).toBe(150)
|
||||
})
|
||||
|
||||
it('pin clamps to range', () => {
|
||||
expect(evalGuides([{ name: 'x', fmla: 'pin 10 5 20' }], 1, 1).x).toBe(10)
|
||||
expect(evalGuides([{ name: 'x', fmla: 'pin 10 15 20' }], 1, 1).x).toBe(15)
|
||||
expect(evalGuides([{ name: 'x', fmla: 'pin 10 99 20' }], 1, 1).x).toBe(20)
|
||||
})
|
||||
|
||||
it('at2 returns 1/60000 degree units', () => {
|
||||
expect(g('at2 1 1')).toBeCloseTo(2700000, 0) // 45°
|
||||
expect(g('at2 0 1')).toBeCloseTo(5400000, 0) // 90°
|
||||
})
|
||||
|
||||
it('cos/sin/tan take angles in 1/60000 degree units', () => {
|
||||
expect(g('cos 100 3600000')).toBeCloseTo(50, 5) // cos60°
|
||||
expect(g('sin 100 1800000')).toBeCloseTo(50, 5) // sin30°
|
||||
expect(g('tan 100 2700000')).toBeCloseTo(100, 5) // tan45°
|
||||
})
|
||||
|
||||
it('cat2/sat2/mod/sqrt/abs/min/max/?:', () => {
|
||||
expect(g('cat2 100 1 1')).toBeCloseTo(100 * Math.SQRT1_2, 4)
|
||||
expect(g('sat2 100 1 1')).toBeCloseTo(100 * Math.SQRT1_2, 4)
|
||||
expect(g('mod 3 4 0')).toBe(5)
|
||||
expect(g('sqrt 81')).toBe(9)
|
||||
expect(g('abs -7')).toBe(7)
|
||||
expect(g('min w h')).toBe(100)
|
||||
expect(g('max w h')).toBe(200)
|
||||
expect(g('?: 1 11 22')).toBe(11)
|
||||
expect(g('?: -1 11 22')).toBe(22)
|
||||
})
|
||||
|
||||
it('a guide can reference earlier guides', () => {
|
||||
const env = evalGuides(
|
||||
[
|
||||
{ name: 'a', fmla: 'val 40' },
|
||||
{ name: 'b', fmla: '*/ a 2 1' },
|
||||
],
|
||||
1,
|
||||
1,
|
||||
)
|
||||
expect(env.b).toBe(80)
|
||||
})
|
||||
})
|
||||
|
||||
const spWrap = (custGeom: string, cx = 914400, cy = 914400) =>
|
||||
`<p:sp><p:nvSpPr><p:cNvPr id="2" name="Freeform 1"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
|
||||
`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm>` +
|
||||
custGeom +
|
||||
`<a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></p:spPr></p:sp>`
|
||||
|
||||
describe('parseCustGeom', () => {
|
||||
it('triangle pathLst → normalized M/L/Z', () => {
|
||||
const xml = spWrap(
|
||||
`<a:custGeom><a:avLst/><a:gdLst/><a:pathLst>` +
|
||||
`<a:path w="100" h="100">` +
|
||||
`<a:moveTo><a:pt x="0" y="100"/></a:moveTo>` +
|
||||
`<a:lnTo><a:pt x="50" y="0"/></a:lnTo>` +
|
||||
`<a:lnTo><a:pt x="100" y="100"/></a:lnTo>` +
|
||||
`<a:close/></a:path></a:pathLst></a:custGeom>`,
|
||||
)
|
||||
const geo = parseCustGeom(xml, 914400, 914400)
|
||||
expect(geo?.path).toBe('M 0 1 L 0.5 0 L 1 1 Z')
|
||||
})
|
||||
|
||||
it('pt references gdLst formulas (element EMU space used when path declares no w/h)', () => {
|
||||
const xml = spWrap(
|
||||
`<a:custGeom><a:avLst><a:gd name="adj" fmla="val 50000"/></a:avLst>` +
|
||||
`<a:gdLst><a:gd name="gx" fmla="*/ w adj 100000"/></a:gdLst><a:pathLst>` +
|
||||
`<a:path>` +
|
||||
`<a:moveTo><a:pt x="0" y="0"/></a:moveTo>` +
|
||||
`<a:lnTo><a:pt x="gx" y="h"/></a:lnTo>` +
|
||||
`<a:close/></a:path></a:pathLst></a:custGeom>`,
|
||||
200000,
|
||||
100000,
|
||||
)
|
||||
const geo = parseCustGeom(xml, 200000, 100000)
|
||||
expect(geo?.path).toBe('M 0 0 L 0.5 1 Z')
|
||||
})
|
||||
|
||||
it('quadBezTo/cubicBezTo output in order', () => {
|
||||
const xml = spWrap(
|
||||
`<a:custGeom><a:pathLst><a:path w="10" h="10">` +
|
||||
`<a:moveTo><a:pt x="0" y="0"/></a:moveTo>` +
|
||||
`<a:cubicBezTo><a:pt x="1" y="0"/><a:pt x="2" y="0"/><a:pt x="5" y="5"/></a:cubicBezTo>` +
|
||||
`<a:quadBezTo><a:pt x="8" y="10"/><a:pt x="10" y="10"/></a:quadBezTo>` +
|
||||
`</a:path></a:pathLst></a:custGeom>`,
|
||||
)
|
||||
const geo = parseCustGeom(xml, 914400, 914400)
|
||||
expect(geo?.path).toBe('M 0 0 C 0.1 0 0.2 0 0.5 0.5 Q 0.8 1 1 1')
|
||||
})
|
||||
|
||||
it('arcTo converts to cubic, endpoint lands on the swept ellipse position', () => {
|
||||
// From (100,50), radii (50,50), stAng 0, sweep 90° → endpoint (50,100)
|
||||
const xml = spWrap(
|
||||
`<a:custGeom><a:pathLst><a:path w="100" h="100">` +
|
||||
`<a:moveTo><a:pt x="100" y="50"/></a:moveTo>` +
|
||||
`<a:arcTo wR="50" hR="50" stAng="0" swAng="5400000"/>` +
|
||||
`</a:path></a:pathLst></a:custGeom>`,
|
||||
)
|
||||
const geo = parseCustGeom(xml, 914400, 914400)
|
||||
expect(geo?.path).toMatch(/^M 1 0\.5 C /)
|
||||
const nums = geo!
|
||||
.path!.split(' ')
|
||||
.filter((t) => Number.isFinite(Number(t)))
|
||||
.map(Number)
|
||||
expect(nums[nums.length - 2]).toBeCloseTo(0.5, 4)
|
||||
expect(nums[nums.length - 1]).toBeCloseTo(1, 4)
|
||||
})
|
||||
|
||||
it('fill="none"/stroke="0" bucketed separately, multiple paths concatenated', () => {
|
||||
const xml = spWrap(
|
||||
`<a:custGeom><a:pathLst>` +
|
||||
`<a:path w="10" h="10" stroke="0"><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:lnTo><a:pt x="10" y="10"/></a:lnTo><a:close/></a:path>` +
|
||||
`<a:path w="10" h="10" fill="none"><a:moveTo><a:pt x="0" y="10"/></a:moveTo><a:lnTo><a:pt x="10" y="0"/></a:lnTo></a:path>` +
|
||||
`<a:path w="10" h="10"><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:lnTo><a:pt x="10" y="0"/></a:lnTo><a:close/></a:path>` +
|
||||
`</a:pathLst></a:custGeom>`,
|
||||
)
|
||||
const geo = parseCustGeom(xml, 914400, 914400)
|
||||
expect(geo?.fillPath).toBe('M 0 0 L 1 1 Z')
|
||||
expect(geo?.strokePath).toBe('M 0 1 L 1 0')
|
||||
expect(geo?.path).toBe('M 0 0 L 1 0 Z')
|
||||
})
|
||||
|
||||
it('close resets the current point to the subpath start, subsequent arcTo center is correct', () => {
|
||||
// M(50,0) L(100,0) Z → current point back to (50,0); arc center = (50,0)-50*(cos180,sin180) = (100,0)
|
||||
// Sweep -90° (180°→90°) endpoint = (100,0)+50*(cos90,sin90) = (100,50)
|
||||
const xml = spWrap(
|
||||
`<a:custGeom><a:pathLst><a:path w="100" h="100">` +
|
||||
`<a:moveTo><a:pt x="50" y="0"/></a:moveTo>` +
|
||||
`<a:lnTo><a:pt x="100" y="0"/></a:lnTo>` +
|
||||
`<a:close/>` +
|
||||
`<a:arcTo wR="50" hR="50" stAng="10800000" swAng="-5400000"/>` +
|
||||
`</a:path></a:pathLst></a:custGeom>`,
|
||||
)
|
||||
const geo = parseCustGeom(xml, 914400, 914400)
|
||||
const nums = geo!
|
||||
.path!.split(' ')
|
||||
.filter((t) => Number.isFinite(Number(t)))
|
||||
.map(Number)
|
||||
expect(nums[nums.length - 2]).toBeCloseTo(1, 4)
|
||||
expect(nums[nums.length - 1]).toBeCloseTo(0.5, 4)
|
||||
})
|
||||
|
||||
it('arcTo wR≠hR: stAng/swAng are ray angles, converted via parametric angles', () => {
|
||||
// Ellipse wR=50000 hR=25000, start on the 45° ray (parametric angle 63.4349°) = center(50000,50000)+(22361,22361)
|
||||
// Sweep to the 90° ray (parametric angle also 90°) → endpoint (50000, 75000)
|
||||
const xml = spWrap(
|
||||
`<a:custGeom><a:pathLst><a:path w="100000" h="100000">` +
|
||||
`<a:moveTo><a:pt x="72361" y="72361"/></a:moveTo>` +
|
||||
`<a:arcTo wR="50000" hR="25000" stAng="2700000" swAng="2700000"/>` +
|
||||
`</a:path></a:pathLst></a:custGeom>`,
|
||||
)
|
||||
const geo = parseCustGeom(xml, 914400, 914400)
|
||||
const nums = geo!
|
||||
.path!.split(' ')
|
||||
.filter((t) => Number.isFinite(Number(t)))
|
||||
.map(Number)
|
||||
expect(nums[nums.length - 2]).toBeCloseTo(0.5, 3)
|
||||
expect(nums[nums.length - 1]).toBeCloseTo(0.75, 3)
|
||||
})
|
||||
|
||||
it('multiple paths without w/h and zero element box: shared fallback coordinate space, original order preserved', () => {
|
||||
const xml =
|
||||
`<p:sp><p:spPr><a:custGeom><a:pathLst>` +
|
||||
`<a:path><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:lnTo><a:pt x="50" y="50"/></a:lnTo></a:path>` +
|
||||
`<a:path><a:moveTo><a:pt x="0" y="100"/></a:moveTo><a:lnTo><a:pt x="100" y="0"/></a:lnTo></a:path>` +
|
||||
`</a:pathLst></a:custGeom></p:spPr></p:sp>`
|
||||
const geo = parseCustGeom(xml, 0, 0)
|
||||
expect(geo?.path).toBe('M 0 0 L 0.5 0.5 M 0 1 L 1 0')
|
||||
})
|
||||
|
||||
it('no custGeom / empty pathLst → undefined', () => {
|
||||
expect(parseCustGeom('<p:sp><p:spPr/></p:sp>', 100, 100)).toBeUndefined()
|
||||
expect(
|
||||
parseCustGeom(spWrap('<a:custGeom><a:pathLst/></a:custGeom>'), 914400, 914400),
|
||||
).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
const SLIDE_NS =
|
||||
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
|
||||
'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"'
|
||||
|
||||
const TRIANGLE_CUSTGEOM =
|
||||
`<a:custGeom><a:avLst/><a:gdLst/><a:pathLst><a:path w="100" h="100">` +
|
||||
`<a:moveTo><a:pt x="0" y="100"/></a:moveTo><a:lnTo><a:pt x="50" y="0"/></a:lnTo>` +
|
||||
`<a:lnTo><a:pt x="100" y="100"/></a:lnTo><a:close/></a:path></a:pathLst></a:custGeom>`
|
||||
|
||||
describe('parseSlide attaches customGeometry', () => {
|
||||
it('top-level sp: customGeometry takes effect and the element is classified as shape', () => {
|
||||
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/>` +
|
||||
spWrap(TRIANGLE_CUSTGEOM) +
|
||||
`</p:spTree></p:cSld></p:sld>`
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml, ctx: {} })
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.type).toBe('shape')
|
||||
expect(el.presetGeometry).toBeUndefined()
|
||||
expect(el.customGeometry?.path).toBe('M 0 1 L 0.5 0 L 1 1 Z')
|
||||
})
|
||||
|
||||
it('sp inside a group: custGeom parsed from source slices in order', () => {
|
||||
const grp =
|
||||
`<p:grpSp><p:nvGrpSpPr><p:cNvPr id="10" name="g"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>` +
|
||||
`<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/>` +
|
||||
`<a:chOff x="0" y="0"/><a:chExt cx="914400" cy="914400"/></a:xfrm></p:grpSpPr>` +
|
||||
spWrap(TRIANGLE_CUSTGEOM) +
|
||||
`</p:grpSp>`
|
||||
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/>` +
|
||||
grp +
|
||||
`</p:spTree></p:cSld></p:sld>`
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml, ctx: {} })
|
||||
const grpEl = slide.elements[0] as any
|
||||
expect(grpEl.type).toBe('group')
|
||||
expect(grpEl.children[0].customGeometry?.path).toBe('M 0 1 L 0.5 0 L 1 1 Z')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { openPptx, savePptx, duplicateSlide, insertBlankSlide } from '../src/index'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const slideText = (slide: any): string =>
|
||||
slide.elements
|
||||
.filter((e: any) => e.type === 'text' || e.type === 'shape')
|
||||
.flatMap((e: any) => e.text?.paragraphs ?? [])
|
||||
.flatMap((p: any) => p.runs)
|
||||
.map((r: any) => r.text)
|
||||
.join('')
|
||||
|
||||
describe('duplicateSlide', () => {
|
||||
it('inserts a copy right after the source and survives save → reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const before = opened.deck.slides.length
|
||||
const srcText = slideText(opened.deck.slides[0])
|
||||
const dup = duplicateSlide(opened, 0)
|
||||
expect(dup).not.toBeNull()
|
||||
expect(opened.deck.slides.length).toBe(before + 1)
|
||||
expect(opened.deck.slides[1]).toBe(dup)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides.length).toBe(before + 1)
|
||||
// sldIdLst order: the copy comes right after the source slide
|
||||
expect(slideText(reopened.deck.slides[1])).toBe(srcText)
|
||||
})
|
||||
|
||||
it('carries the source page pending edits into the copy', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const src = opened.deck.slides[0]!
|
||||
const el: any = src.elements.find((e: any) => (e.type === 'text' || e.type === 'shape') && e.text)
|
||||
el.text.paragraphs = [{ runs: [{ text: 'edited before copying' }] }]
|
||||
el.dirty = true
|
||||
|
||||
duplicateSlide(opened, 0)
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(slideText(reopened.deck.slides[1])).toContain('edited before copying')
|
||||
})
|
||||
|
||||
it('clearText makes a layout-preserving blank page', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const srcCount = opened.deck.slides[0]!.elements.length
|
||||
duplicateSlide(opened, 0, { clearText: true })
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const copy = reopened.deck.slides[1]!
|
||||
expect(copy.elements.length).toBe(srcCount)
|
||||
expect(slideText(copy)).toBe('')
|
||||
})
|
||||
|
||||
it('two duplicates get distinct part paths and sldIds', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const a = duplicateSlide(opened, 0)!
|
||||
const b = duplicateSlide(opened, 0)!
|
||||
expect(a.path).not.toBe(b.path)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides.length).toBe(7)
|
||||
})
|
||||
})
|
||||
|
||||
describe('insertBlankSlide', () => {
|
||||
it('inserts an element-free slide after the source and survives save → reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const before = opened.deck.slides.length
|
||||
const blank = insertBlankSlide(opened, 0)
|
||||
expect(blank).not.toBeNull()
|
||||
expect(opened.deck.slides.length).toBe(before + 1)
|
||||
expect(opened.deck.slides[1]).toBe(blank)
|
||||
expect(blank!.elements.length).toBe(0)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides.length).toBe(before + 1)
|
||||
expect(reopened.deck.slides[1]!.elements.length).toBe(0)
|
||||
})
|
||||
|
||||
it('reuses the source slide layout relationship', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const src = opened.deck.slides[0]!
|
||||
const blank = insertBlankSlide(opened, 0)!
|
||||
const layoutOf = (p: string) =>
|
||||
[...opened.archive.readRels(p).values()].find((r) => r.type.endsWith('/slideLayout'))
|
||||
?.target
|
||||
expect(layoutOf(blank.path)).toBeTruthy()
|
||||
expect(layoutOf(blank.path)).toBe(layoutOf(src.path))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* <a:fld> in-paragraph ordering (#88): a field must stay at its document
|
||||
* position relative to plain runs — "fld(2) + r(h)" renders as "2h", not "h2".
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
const wrap = (spTree: string) =>
|
||||
`<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld><p:spTree>` +
|
||||
`<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/>` +
|
||||
spTree +
|
||||
`</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
const textBox = (paragraphs: string) => `<p:sp>
|
||||
<p:nvSpPr><p:cNvPr id="2" name="TextBox 1"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>
|
||||
<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="457200"/></a:xfrm></p:spPr>
|
||||
<p:txBody><a:bodyPr/>${paragraphs}</p:txBody>
|
||||
</p:sp>`
|
||||
|
||||
const runsOf = (spTree: string, paraIndex = 0) => {
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: wrap(spTree), ctx: {} })
|
||||
const el = slide.elements[0] as TextElement
|
||||
return el.text!.paragraphs[paraIndex]!.runs
|
||||
}
|
||||
|
||||
describe('a:fld document-order preservation (#88)', () => {
|
||||
it('fld before a plain run stays first (fld("2") + r("h") → "2h")', () => {
|
||||
const runs = runsOf(
|
||||
textBox(
|
||||
`<a:p>` +
|
||||
`<a:fld id="{B6D32A31-0000-0000-0000-000000000000}" type="datetime2"><a:rPr lang="en-US"/><a:t>2</a:t></a:fld>` +
|
||||
`<a:r><a:rPr lang="en-US"/><a:t>h</a:t></a:r>` +
|
||||
`</a:p>`,
|
||||
),
|
||||
)
|
||||
expect(runs.map((r) => r.text)).toEqual(['2', 'h'])
|
||||
expect(runs[0]!.field).toBe('datetime2')
|
||||
expect(runs[1]!.field).toBeUndefined()
|
||||
})
|
||||
|
||||
it('run + fld + run keeps interleaved order (r("8~") + fld("10") + r("h") → "8~10h")', () => {
|
||||
const runs = runsOf(
|
||||
textBox(
|
||||
`<a:p>` +
|
||||
`<a:r><a:rPr lang="en-US"/><a:t>8~</a:t></a:r>` +
|
||||
`<a:fld id="{B6D32A31-0000-0000-0000-000000000001}" type="datetime10"><a:rPr lang="en-US"/><a:t>10</a:t></a:fld>` +
|
||||
`<a:r><a:rPr lang="en-US"/><a:t>h</a:t></a:r>` +
|
||||
`</a:p>`,
|
||||
),
|
||||
)
|
||||
expect(runs.map((r) => r.text)).toEqual(['8~', '10', 'h'])
|
||||
expect(runs.map((r) => r.field)).toEqual([undefined, 'datetime10', undefined])
|
||||
})
|
||||
|
||||
it('slidenum fld alone in its paragraph still parses with field set', () => {
|
||||
const runs = runsOf(
|
||||
textBox(
|
||||
`<a:p>` +
|
||||
`<a:fld id="{B6D32A31-0000-0000-0000-000000000002}" type="slidenum"><a:rPr lang="en-US"/><a:t>7</a:t></a:fld>` +
|
||||
`</a:p>`,
|
||||
),
|
||||
)
|
||||
expect(runs.map((r) => r.text)).toEqual(['7'])
|
||||
expect(runs[0]!.field).toBe('slidenum')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,191 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { openPptx, savePptx, addElement, patchElementFill } from '../src/index'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
describe('patchElementFill', () => {
|
||||
it('replaces an existing solidFill without touching the outline fill', () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1" cy="1"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>' +
|
||||
'<a:solidFill><a:srgbClr val="112233"/></a:solidFill>' +
|
||||
'<a:ln><a:solidFill><a:srgbClr val="ABCDEF"/></a:solidFill></a:ln>' +
|
||||
'</p:spPr></p:sp>'
|
||||
const out = patchElementFill(xml, '#C43E1C')
|
||||
expect(out).toContain('<a:solidFill><a:srgbClr val="C43E1C"/></a:solidFill><a:ln>')
|
||||
expect(out).toContain('<a:ln><a:solidFill><a:srgbClr val="ABCDEF"/></a:solidFill></a:ln>')
|
||||
expect(out).not.toContain('112233')
|
||||
})
|
||||
|
||||
it('injects fill after geometry when the sp has none', () => {
|
||||
const xml = '<p:sp><p:spPr><a:prstGeom prst="ellipse"><a:avLst/></a:prstGeom></p:spPr></p:sp>'
|
||||
const out = patchElementFill(xml, '#00FF00')
|
||||
expect(out).toContain('</a:prstGeom><a:solidFill><a:srgbClr val="00FF00"/></a:solidFill>')
|
||||
})
|
||||
|
||||
it("'none' writes <a:noFill/> replacing gradient fill", () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs></a:gsLst></a:gradFill></p:spPr></p:sp>'
|
||||
const out = patchElementFill(xml, 'none')
|
||||
expect(out).toContain('<a:noFill/>')
|
||||
expect(out).not.toContain('gradFill')
|
||||
})
|
||||
|
||||
it('dirtyFill round-trips through save → reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, {
|
||||
kind: 'rect',
|
||||
offset: { x: 914400, y: 914400, cx: 914400, cy: 914400 },
|
||||
fillColor: '#112233',
|
||||
})
|
||||
// Simulate the edit-fill handler
|
||||
el.fill = { type: 'solid', color: '#C43E1C' }
|
||||
el.dirtyFill = true
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2 = reopened.deck.slides[0]!.elements.at(-1) as TextElement
|
||||
expect(el2.fill).toEqual({ type: 'solid', color: '#C43E1C' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('gradient fill write-back', () => {
|
||||
it('linear gradient gradFill + lin ang', async () => {
|
||||
const { patchElementFill } = await import('../src/generate')
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1" cy="1"/></a:xfrm><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></p:spPr></p:sp>'
|
||||
const out = patchElementFill(xml, {
|
||||
stops: [
|
||||
{ pos: 0, color: '#112233' },
|
||||
{ pos: 1, color: '#445566' },
|
||||
],
|
||||
angle: 5400000,
|
||||
})
|
||||
expect(out).toContain('<a:gradFill rotWithShape="1">')
|
||||
expect(out).toContain('<a:gs pos="0"><a:srgbClr val="112233"/></a:gs>')
|
||||
expect(out).toContain('<a:gs pos="100000"><a:srgbClr val="445566"/></a:gs>')
|
||||
expect(out).toContain('<a:lin ang="5400000" scaled="1"/>')
|
||||
expect(out).not.toContain('FF0000')
|
||||
})
|
||||
|
||||
it('radial gradient writes path circle', async () => {
|
||||
const { patchElementFill } = await import('../src/generate')
|
||||
const xml = '<p:sp><p:spPr><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:sp>'
|
||||
const out = patchElementFill(xml, {
|
||||
stops: [
|
||||
{ pos: 0, color: '#000000' },
|
||||
{ pos: 1, color: '#ffffff' },
|
||||
],
|
||||
radial: true,
|
||||
})
|
||||
expect(out).toContain('<a:path path="circle">')
|
||||
expect(out).not.toContain('<a:lin')
|
||||
})
|
||||
})
|
||||
|
||||
describe('same-kind fill in-place patch (unmodeled parameters preserved)', () => {
|
||||
it('solid->solid keeps alpha', () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:solidFill><a:schemeClr val="accent1"><a:lumMod val="60000"/><a:alpha val="50000"/></a:schemeClr></a:solidFill></p:spPr></p:sp>'
|
||||
const out = patchElementFill(xml, '#C43E1C')
|
||||
expect(out).toContain(
|
||||
'<a:solidFill><a:srgbClr val="C43E1C"><a:alpha val="50000"/></a:srgbClr></a:solidFill>',
|
||||
)
|
||||
})
|
||||
|
||||
it('an 8-digit color sets an explicit alpha', () => {
|
||||
const xml = '<p:sp><p:spPr><a:solidFill><a:srgbClr val="C43E1C"/></a:solidFill></p:spPr></p:sp>'
|
||||
// 0x33 = 51/255 → 20% opacity
|
||||
const out = patchElementFill(xml, '#C0000033')
|
||||
expect(out).toContain(
|
||||
'<a:solidFill><a:srgbClr val="C00000"><a:alpha val="20000"/></a:srgbClr></a:solidFill>',
|
||||
)
|
||||
})
|
||||
|
||||
it('an explicit FF alpha removes the existing alpha', () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:solidFill><a:srgbClr val="C43E1C"><a:alpha val="50000"/></a:srgbClr></a:solidFill></p:spPr></p:sp>'
|
||||
const out = patchElementFill(xml, '#C43E1CFF')
|
||||
expect(out).toContain('<a:solidFill><a:srgbClr val="C43E1C"/></a:solidFill>')
|
||||
expect(out).not.toContain('a:alpha')
|
||||
})
|
||||
|
||||
it('inserting a fresh fill honors the alpha', () => {
|
||||
const xml = '<p:sp><p:spPr><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:sp>'
|
||||
const out = patchElementFill(xml, '#C0000080')
|
||||
expect(out).toContain(
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:solidFill><a:srgbClr val="C00000"><a:alpha val="50196"/></a:srgbClr></a:solidFill>',
|
||||
)
|
||||
})
|
||||
|
||||
it('grad->grad keeps gradFill attributes / tileRect / off-center path, replaces gsLst', () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:gradFill flip="xy" rotWithShape="0">' +
|
||||
'<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:path path="rect"><a:fillToRect l="20000" t="30000" r="80000" b="70000"/></a:path>' +
|
||||
'<a:tileRect l="-10000"/>' +
|
||||
'</a:gradFill></p:spPr></p:sp>'
|
||||
const out = patchElementFill(xml, {
|
||||
stops: [
|
||||
{ pos: 0, color: '#111111' },
|
||||
{ pos: 1, color: '#222222' },
|
||||
],
|
||||
radial: true,
|
||||
})
|
||||
expect(out).toContain('<a:gradFill flip="xy" rotWithShape="0">')
|
||||
expect(out).toContain(
|
||||
'<a:gs pos="0"><a:srgbClr val="111111"/></a:gs><a:gs pos="100000"><a:srgbClr val="222222"/></a:gs>',
|
||||
)
|
||||
// The original off-center path keeps its bytes, not overwritten by the default centered circle
|
||||
expect(out).toContain(
|
||||
'<a:path path="rect"><a:fillToRect l="20000" t="30000" r="80000" b="70000"/></a:path>',
|
||||
)
|
||||
expect(out).toContain('<a:tileRect l="-10000"/>')
|
||||
expect(out).not.toContain('FF0000')
|
||||
})
|
||||
|
||||
it('grad->grad linear angle change keeps scaled, radial path replaced by a:lin', () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:gradFill rotWithShape="1">' +
|
||||
'<a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs></a:gsLst>' +
|
||||
'<a:lin ang="2700000" scaled="0"/>' +
|
||||
'</a:gradFill></p:spPr></p:sp>'
|
||||
const out = patchElementFill(xml, {
|
||||
stops: [
|
||||
{ pos: 0, color: '#111111' },
|
||||
{ pos: 1, color: '#222222' },
|
||||
],
|
||||
angle: 5400000,
|
||||
})
|
||||
expect(out).toContain('<a:lin ang="5400000" scaled="0"/>')
|
||||
expect(out).not.toContain('<a:path')
|
||||
})
|
||||
|
||||
it('lin->radial with no existing path adds a default circle path right after gsLst', () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs></a:gsLst><a:lin ang="0" scaled="1"/><a:tileRect/></a:gradFill></p:spPr></p:sp>'
|
||||
const out = patchElementFill(xml, {
|
||||
stops: [
|
||||
{ pos: 0, color: '#111111' },
|
||||
{ pos: 1, color: '#222222' },
|
||||
],
|
||||
radial: true,
|
||||
})
|
||||
expect(out).toContain('</a:gsLst><a:path path="circle">')
|
||||
expect(out).toContain('</a:path><a:tileRect/>')
|
||||
expect(out).not.toContain('<a:lin')
|
||||
})
|
||||
|
||||
it('cross-type (grad->solid) replaces the whole block', () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs></a:gsLst><a:lin ang="0" scaled="1"/></a:gradFill></p:spPr></p:sp>'
|
||||
const out = patchElementFill(xml, '#123456')
|
||||
expect(out).toContain('<a:solidFill><a:srgbClr val="123456"/></a:solidFill>')
|
||||
expect(out).not.toContain('gradFill')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
/** Global find/replace: in-run matching, case toggle, firstOnly/element scope, dynamic-field skip, byte fidelity. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { patchedElementXml, replaceAllInDeck } from '../src/index'
|
||||
import type { SlideDeck, TextElement } from '../src/types'
|
||||
|
||||
const slideWith = (sps: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${sps}</p:spTree></p:cSld></p:sld>`
|
||||
const sp = (runs: string) =>
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
`<p:txBody><a:bodyPr/><a:p>${runs}</a:p></p:txBody></p:sp>`
|
||||
|
||||
const deckWith = (...slidesSps: string[]): SlideDeck => {
|
||||
const slides = slidesSps.map((sps, i) =>
|
||||
parseSlide({ path: `ppt/slides/slide${i + 1}.xml`, slideXml: slideWith(sps), ctx: {} }),
|
||||
)
|
||||
return { slides } as unknown as SlideDeck
|
||||
}
|
||||
|
||||
describe('replaceAllInDeck', () => {
|
||||
it('replaces across slides + counts + marks only changed slides', () => {
|
||||
const deck = deckWith(
|
||||
sp('<a:r><a:t>Hello world, hello</a:t></a:r>'),
|
||||
sp('<a:r><a:t>no match here</a:t></a:r>'),
|
||||
sp('<a:r><a:t>Hello again</a:t></a:r>'),
|
||||
)
|
||||
const r = replaceAllInDeck(deck, 'hello', 'hi')
|
||||
expect(r.count).toBe(3)
|
||||
expect(r.changedSlides).toEqual([0, 2])
|
||||
const el = deck.slides[0]!.elements[0] as TextElement
|
||||
expect(el.text!.paragraphs[0]!.runs[0]!.text).toBe('hi world, hi')
|
||||
expect(el.dirty).toBe(true)
|
||||
})
|
||||
|
||||
it('matchCase is case-sensitive', () => {
|
||||
const deck = deckWith(sp('<a:r><a:t>Hello hello</a:t></a:r>'))
|
||||
const r = replaceAllInDeck(deck, 'hello', 'x', { matchCase: true })
|
||||
expect(r.count).toBe(1)
|
||||
expect((deck.slides[0]!.elements[0] as TextElement).text!.paragraphs[0]!.runs[0]!.text).toBe(
|
||||
'Hello x',
|
||||
)
|
||||
})
|
||||
|
||||
it('firstOnly + element scope replaces only the first match', () => {
|
||||
const deck = deckWith(sp('<a:r><a:t>aaa</a:t></a:r>'), sp('<a:r><a:t>aaa</a:t></a:r>'))
|
||||
const el0 = deck.slides[0]!.elements[0]!
|
||||
const r = replaceAllInDeck(deck, 'a', 'b', {
|
||||
firstOnly: true,
|
||||
slideIndex: 0,
|
||||
elementId: el0.id,
|
||||
})
|
||||
expect(r.count).toBe(1)
|
||||
expect((el0 as TextElement).text!.paragraphs[0]!.runs[0]!.text).toBe('baa')
|
||||
expect((deck.slides[1]!.elements[0] as TextElement).text!.paragraphs[0]!.runs[0]!.text).toBe(
|
||||
'aaa',
|
||||
)
|
||||
})
|
||||
|
||||
it('dynamic field runs skipped; rPr keeps original bytes after replacement (in-place patch)', () => {
|
||||
const deck = deckWith(
|
||||
sp(
|
||||
'<a:r><a:rPr sz="1800" b="1"><a:latin typeface="Calibri"/></a:rPr><a:t>foo bar</a:t></a:r>',
|
||||
) + sp('<a:fld id="{X}" type="slidenum"><a:rPr/><a:t>foo</a:t></a:fld>'),
|
||||
)
|
||||
const r = replaceAllInDeck(deck, 'foo', 'baz')
|
||||
expect(r.count).toBe(1) // 'foo' inside fld is untouched
|
||||
const el = deck.slides[0]!.elements[0]!
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('baz bar')
|
||||
// Font size/bold/font declarations kept (explicit b/i booleans overriding inheritance is existing semantics of the alignment path)
|
||||
expect(out).toMatch(
|
||||
/<a:rPr[^>]*\bsz="1800"[^>]*\bb="1"[^>]*><a:latin typeface="Calibri"\/><\/a:rPr>/,
|
||||
)
|
||||
})
|
||||
|
||||
it('regex special characters match literally', () => {
|
||||
const deck = deckWith(sp('<a:r><a:t>1+1=2 (a.b)</a:t></a:r>'))
|
||||
expect(replaceAllInDeck(deck, '1+1', '2').count).toBe(1)
|
||||
expect(replaceAllInDeck(deck, '(a.b)', 'c').count).toBe(1)
|
||||
expect((deck.slides[0]!.elements[0] as TextElement).text!.paragraphs[0]!.runs[0]!.text).toBe(
|
||||
'2=2 c',
|
||||
)
|
||||
})
|
||||
})
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2013 Steve Canny, https://github.com/scanny/python-pptx
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,8 @@
|
||||
# pptx test fixtures
|
||||
|
||||
`01_standard_business.pptx` and `05_unicode_cjk_emoji.pptx` were generated
|
||||
with [python-pptx](https://github.com/scanny/python-pptx) (MIT License,
|
||||
copyright Steve Canny) and derive their slide master / layouts / theme from
|
||||
python-pptx's built-in default template. The MIT permission notice those
|
||||
parts are distributed under is in `LICENSE-python-pptx.txt` next to this
|
||||
file. Slide text content is synthetic test data authored for this repository.
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Mirroring an element writes a:xfrm flipH/flipV, so arrows can point
|
||||
* the other way. Rotation cannot express a single-axis mirror, and the render layer
|
||||
* already honors the flags — this pins the write-back half.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { addElement, openPptx, savePptx } from '../src/index'
|
||||
import { patchElementXfrm } from '../src/generate'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const OFF = { x: 914400, y: 914400, cx: 1828800, cy: 914400 }
|
||||
|
||||
describe('flip write-back', () => {
|
||||
it('flipH/flipV land on a:xfrm and survive save → reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, { kind: 'rightArrow', offset: { ...OFF } })
|
||||
el.transform.flipH = true
|
||||
el.dirtyTransform = true
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2 = reopened.deck.slides[0]!.elements.at(-1) as TextElement
|
||||
expect(el2.transform.flipH).toBe(true)
|
||||
expect(el2.transform.flipV).toBe(false)
|
||||
})
|
||||
|
||||
it('a single flip is not the same as a 180° rotation', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, { kind: 'line', offset: { ...OFF } })
|
||||
el.transform.flipV = true
|
||||
el.dirtyTransform = true
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2 = reopened.deck.slides[0]!.elements.at(-1) as TextElement
|
||||
expect(el2.transform.flipV).toBe(true)
|
||||
expect(el2.transform.rot).toBe(0)
|
||||
})
|
||||
|
||||
it('clearing a flip removes the attribute instead of writing flipH="0"', () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:xfrm flipH="1" flipV="1"><a:off x="1" y="2"/><a:ext cx="3" cy="4"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="line"><a:avLst/></a:prstGeom></p:spPr></p:sp>'
|
||||
const el = {
|
||||
type: 'shape' as const,
|
||||
transform: { offset: { x: 1, y: 2, cx: 3, cy: 4 }, rot: 0, flipH: false, flipV: true },
|
||||
}
|
||||
const out = patchElementXfrm(el as never, xml)
|
||||
expect(out).toContain('<a:xfrm flipV="1">')
|
||||
expect(out).not.toContain('flipH')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Format painter pure-function unit tests — extract / apply / cross-type intersection.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { extractFormat, applyFormat } from '../src/format-brush'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
function makeTextEl(partial: Partial<TextElement>): TextElement {
|
||||
return {
|
||||
id: 'el1',
|
||||
type: 'text',
|
||||
anchor: { spIndex: 0, originalXml: '', range: [0, 0] },
|
||||
transform: { offset: { x: 0, y: 0, cx: 100, cy: 50 }, rot: 0, flipH: false, flipV: false },
|
||||
...partial,
|
||||
} as TextElement
|
||||
}
|
||||
|
||||
// ── extractFormat ────────────────────────────────────────────────────────
|
||||
|
||||
describe('extractFormat', () => {
|
||||
it('extracts fill / stroke / run format', () => {
|
||||
const el = makeTextEl({
|
||||
type: 'shape',
|
||||
fill: { type: 'solid', color: '#FF0000' },
|
||||
stroke: { fill: { type: 'solid', color: '#000000' }, width: 12700 },
|
||||
text: {
|
||||
paragraphs: [
|
||||
{
|
||||
align: 'center',
|
||||
runs: [
|
||||
{
|
||||
text: 'hello',
|
||||
bold: true,
|
||||
italic: false,
|
||||
fontSize: 24,
|
||||
color: '#333333',
|
||||
fontFamily: 'Arial',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
anchor: 'top',
|
||||
wrap: true,
|
||||
},
|
||||
})
|
||||
|
||||
const fmt = extractFormat(el)
|
||||
|
||||
expect(fmt.sourceType).toBe('shape')
|
||||
expect(fmt.shape?.fill).toEqual({ type: 'solid', color: '#FF0000' })
|
||||
expect(fmt.shape?.stroke?.width).toBe(12700)
|
||||
expect(fmt.run?.bold).toBe(true)
|
||||
expect(fmt.run?.fontSize).toBe(24)
|
||||
expect(fmt.run?.fontFamily).toBe('Arial')
|
||||
expect(fmt.run?.color).toBe('#333333')
|
||||
expect(fmt.paragraph?.align).toBe('center')
|
||||
})
|
||||
|
||||
it('shape without text extracts only the spPr part', () => {
|
||||
const el = makeTextEl({
|
||||
type: 'shape',
|
||||
fill: { type: 'solid', color: '#0000FF' },
|
||||
text: undefined,
|
||||
})
|
||||
const fmt = extractFormat(el)
|
||||
expect(fmt.shape?.fill).toEqual({ type: 'solid', color: '#0000FF' })
|
||||
expect(fmt.run).toBeUndefined()
|
||||
expect(fmt.paragraph).toBeUndefined()
|
||||
})
|
||||
|
||||
it('plain textbox without fill leaves the shape field undefined', () => {
|
||||
const el = makeTextEl({
|
||||
type: 'text',
|
||||
fill: undefined,
|
||||
stroke: undefined,
|
||||
text: {
|
||||
paragraphs: [{ runs: [{ text: 'abc', fontFamily: 'Calibri', fontSize: 18 }] }],
|
||||
wrap: true,
|
||||
},
|
||||
})
|
||||
const fmt = extractFormat(el)
|
||||
expect(fmt.shape).toBeUndefined()
|
||||
expect(fmt.run?.fontFamily).toBe('Calibri')
|
||||
expect(fmt.run?.fontSize).toBe(18)
|
||||
})
|
||||
})
|
||||
|
||||
// ── applyFormat ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('applyFormat', () => {
|
||||
const fmt = {
|
||||
sourceType: 'shape' as const,
|
||||
shape: {
|
||||
fill: { type: 'solid' as const, color: '#FF0000' },
|
||||
stroke: { fill: { type: 'solid' as const, color: '#000000' }, width: 12700 },
|
||||
},
|
||||
run: { bold: true, fontSize: 24, fontFamily: 'Arial', color: '#111111' },
|
||||
paragraph: { align: 'center' as const },
|
||||
}
|
||||
|
||||
it('apply to shape: fill + stroke + run + alignment all applied', () => {
|
||||
const result = applyFormat(fmt, 'shape')
|
||||
expect(result.fill).toEqual({ type: 'solid', color: '#FF0000' })
|
||||
expect(result.stroke?.width).toBe(12700)
|
||||
expect(result.runFormat?.bold).toBe(true)
|
||||
expect(result.align).toBe('center')
|
||||
})
|
||||
|
||||
it('apply to text: same full set as shape', () => {
|
||||
const result = applyFormat(fmt, 'text')
|
||||
expect(result.fill).toEqual({ type: 'solid', color: '#FF0000' })
|
||||
expect(result.runFormat?.fontSize).toBe(24)
|
||||
expect(result.align).toBe('center')
|
||||
})
|
||||
|
||||
it('apply to picture: keeps only the stroke, does not apply fill / text', () => {
|
||||
const result = applyFormat(fmt, 'picture')
|
||||
expect(result.fill).toBeUndefined()
|
||||
expect(result.stroke?.width).toBe(12700)
|
||||
expect(result.runFormat).toBeUndefined()
|
||||
expect(result.align).toBeUndefined()
|
||||
})
|
||||
|
||||
it('without shape format, both fill/stroke are undefined', () => {
|
||||
const fmtTextOnly = {
|
||||
sourceType: 'text' as const,
|
||||
run: { fontSize: 12 },
|
||||
paragraph: { align: 'left' as const },
|
||||
}
|
||||
const result = applyFormat(fmtTextOnly, 'shape')
|
||||
expect(result.fill).toBeUndefined()
|
||||
expect(result.stroke).toBeUndefined()
|
||||
expect(result.runFormat?.fontSize).toBe(12)
|
||||
expect(result.align).toBe('left')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* In-group editing (patching group children) tests:
|
||||
* 1. groupChildSlices: document-order slicing, nvId extraction, nested-group inner children not double-counted.
|
||||
* 2. editGroupChildTransform: nvId matching (no mismatch even when children array order ≠ document order),
|
||||
* model and XML updated in sync, nested-group chOff/chExt preserved.
|
||||
* 3. patchGroupChildText: child txBody regenerated into the group XML.
|
||||
* 4. Integration: groupElements → edit a child → save and reopen with correct coordinates/text.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
groupChildSlices,
|
||||
editGroupChildTransform,
|
||||
patchGroupChildText,
|
||||
groupElements,
|
||||
openPptx,
|
||||
savePptx,
|
||||
} from '../src/index'
|
||||
import type { GroupElement, Slide, SlideElement, TextElement } from '../src/types'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const SP = (id: number, x: number, y: number) =>
|
||||
`<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="s${id}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
|
||||
`<p:spPr><a:xfrm><a:off x="${x}" y="${y}"/><a:ext cx="100" cy="100"/></a:xfrm>` +
|
||||
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr>` +
|
||||
`<p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>hi</a:t></a:r></a:p></p:txBody></p:sp>`
|
||||
|
||||
const PIC = (id: number) =>
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="p${id}"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>` +
|
||||
`<p:blipFill><a:blip r:embed="rId9"/></p:blipFill>` +
|
||||
`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="50" cy="50"/></a:xfrm></p:spPr></p:pic>`
|
||||
|
||||
const NESTED_GRP = (id: number, inner: string) =>
|
||||
`<p:grpSp><p:nvGrpSpPr><p:cNvPr id="${id}" name="g${id}"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>` +
|
||||
`<p:grpSpPr><a:xfrm><a:off x="10" y="10"/><a:ext cx="200" cy="200"/>` +
|
||||
`<a:chOff x="0" y="0"/><a:chExt cx="200" cy="200"/></a:xfrm></p:grpSpPr>${inner}</p:grpSp>`
|
||||
|
||||
const GRP_XML = (inner: string) =>
|
||||
`<p:grpSp><p:nvGrpSpPr><p:cNvPr id="1" name="g"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>` +
|
||||
`<p:grpSpPr><a:xfrm><a:off x="1000" y="1000"/><a:ext cx="5000" cy="5000"/>` +
|
||||
`<a:chOff x="1000" y="1000"/><a:chExt cx="5000" cy="5000"/></a:xfrm></p:grpSpPr>${inner}</p:grpSp>`
|
||||
|
||||
function makeChild(id: string, nvId: string, type: SlideElement['type'] = 'shape'): SlideElement {
|
||||
return {
|
||||
id,
|
||||
type,
|
||||
nvId,
|
||||
anchor: { spIndex: -1, originalXml: '', range: [0, 0] },
|
||||
transform: { offset: { x: 0, y: 0, cx: 100, cy: 100 }, rot: 0, flipH: false, flipV: false },
|
||||
} as SlideElement
|
||||
}
|
||||
|
||||
function makeSlide(grpXml: string, children: SlideElement[]): { slide: Slide; grp: GroupElement } {
|
||||
const grp: GroupElement = {
|
||||
id: 'grp1',
|
||||
type: 'group',
|
||||
anchor: { spIndex: 0, originalXml: grpXml, range: [0, grpXml.length] },
|
||||
transform: {
|
||||
offset: { x: 1000, y: 1000, cx: 5000, cy: 5000 },
|
||||
rot: 0,
|
||||
flipH: false,
|
||||
flipV: false,
|
||||
},
|
||||
childOffset: { x: 1000, y: 1000, cx: 5000, cy: 5000 },
|
||||
children,
|
||||
}
|
||||
return { slide: { elements: [grp] } as unknown as Slide, grp }
|
||||
}
|
||||
|
||||
describe('groupChildSlices', () => {
|
||||
it('extracts children in document order with nvId', () => {
|
||||
const slices = groupChildSlices(GRP_XML(SP(2, 0, 0) + PIC(3) + SP(4, 9, 9)))
|
||||
expect(slices.map((s) => s.nvId)).toEqual(['2', '3', '4'])
|
||||
expect(slices[1]!.xml.startsWith('<p:pic')).toBe(true)
|
||||
})
|
||||
|
||||
it('nested group counts as one slice (inner children not duplicated)', () => {
|
||||
const slices = groupChildSlices(GRP_XML(SP(2, 0, 0) + NESTED_GRP(3, SP(5, 1, 1)) + SP(4, 9, 9)))
|
||||
expect(slices.map((s) => s.nvId)).toEqual(['2', '3', '4'])
|
||||
expect(slices[1]!.xml).toContain('id="5"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('editGroupChildTransform', () => {
|
||||
it('patches the nvId-matched child even when children array order differs', () => {
|
||||
// children array order deliberately reversed vs document order (parseGroup's per-tag traversal does this)
|
||||
const { slide, grp } = makeSlide(GRP_XML(SP(2, 0, 0) + PIC(3) + SP(4, 900, 900)), [
|
||||
makeChild('c4', '4'),
|
||||
makeChild('c2', '2'),
|
||||
makeChild('c3', '3', 'picture'),
|
||||
])
|
||||
const ok = editGroupChildTransform(
|
||||
slide,
|
||||
'grp1',
|
||||
'c4',
|
||||
{ x: 2000, y: 3000, cx: 400, cy: 500 },
|
||||
45,
|
||||
)
|
||||
expect(ok).toBe(true)
|
||||
const xml = grp.anchor.originalXml
|
||||
// The sp with id=4 is rewritten; the sp with id=2 stays as-is
|
||||
expect(xml).toContain('<a:off x="2000" y="3000"/><a:ext cx="400" cy="500"/>')
|
||||
expect(xml).toContain('rot="2700000"')
|
||||
expect(xml).toContain('<a:off x="0" y="0"/>')
|
||||
// Model kept in sync
|
||||
const c4 = grp.children.find((c) => c.id === 'c4')!
|
||||
expect(c4.transform.offset).toEqual({ x: 2000, y: 3000, cx: 400, cy: 500 })
|
||||
expect(c4.transform.rot).toBe(2700000)
|
||||
expect(slide.structureDirty).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps chOff/chExt when the child is a nested group', () => {
|
||||
const { slide, grp } = makeSlide(GRP_XML(NESTED_GRP(3, SP(5, 1, 1))), [
|
||||
makeChild('c3', '3', 'group'),
|
||||
])
|
||||
const ok = editGroupChildTransform(slide, 'grp1', 'c3', { x: 7, y: 8, cx: 300, cy: 300 }, 0)
|
||||
expect(ok).toBe(true)
|
||||
const xml = grp.anchor.originalXml
|
||||
expect(xml).toContain(
|
||||
'<a:off x="7" y="8"/><a:ext cx="300" cy="300"/><a:chOff x="0" y="0"/><a:chExt cx="200" cy="200"/>',
|
||||
)
|
||||
})
|
||||
|
||||
it('returns false when nvId missing or unmatched (model untouched)', () => {
|
||||
const { slide, grp } = makeSlide(GRP_XML(SP(2, 0, 0)), [makeChild('c9', '9')])
|
||||
expect(editGroupChildTransform(slide, 'grp1', 'c9', { x: 1, y: 1, cx: 1, cy: 1 }, 0)).toBe(
|
||||
false,
|
||||
)
|
||||
expect(grp.children[0]!.transform.offset.x).toBe(0)
|
||||
expect(slide.structureDirty).toBeFalsy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('patchGroupChildText', () => {
|
||||
it('regenerates child txBody inside group xml', () => {
|
||||
const { slide, grp } = makeSlide(GRP_XML(SP(2, 0, 0) + SP(4, 9, 9)), [
|
||||
makeChild('c2', '2'),
|
||||
makeChild('c4', '4'),
|
||||
])
|
||||
const child = grp.children[1] as TextElement
|
||||
child.text = {
|
||||
paragraphs: [{ runs: [{ text: 'edited!' }] }],
|
||||
autofit: 'none',
|
||||
insets: { l: 0, t: 0, r: 0, b: 0 },
|
||||
} as unknown as TextElement['text']
|
||||
const ok = patchGroupChildText(slide, 'grp1', child)
|
||||
expect(ok).toBe(true)
|
||||
const xml = grp.anchor.originalXml
|
||||
expect(xml).toContain('edited!')
|
||||
// Two sp: only id=4 is regenerated; id=2's "hi" remains
|
||||
expect(xml).toContain('hi')
|
||||
expect(slide.structureDirty).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('integration: group → edit child → save → reopen', () => {
|
||||
it('child transform edit survives roundtrip', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
let slideIdx = -1
|
||||
let ids: string[] = []
|
||||
for (let i = 0; i < opened.deck.slides.length; i++) {
|
||||
const els = opened.deck.slides[i]!.elements.filter(
|
||||
(e) => e.type === 'text' || e.type === 'shape' || e.type === 'picture',
|
||||
)
|
||||
if (els.length >= 2) {
|
||||
slideIdx = i
|
||||
ids = els.slice(0, 2).map((e) => e.id)
|
||||
break
|
||||
}
|
||||
}
|
||||
if (slideIdx < 0) return
|
||||
|
||||
const result = groupElements(opened, slideIdx, ids)
|
||||
expect(result).not.toBeNull()
|
||||
const slide = opened.deck.slides[slideIdx]!
|
||||
const grp = slide.elements.find((e) => e.id === result!.groupId) as GroupElement
|
||||
expect(grp.children.length).toBe(2)
|
||||
const child = grp.children[0]!
|
||||
expect(child.nvId).toBeTruthy()
|
||||
|
||||
const ok = editGroupChildTransform(
|
||||
slide,
|
||||
grp.id,
|
||||
child.id,
|
||||
{ x: 123456, y: 234567, cx: 345678, cy: 456789 },
|
||||
0,
|
||||
)
|
||||
expect(ok).toBe(true)
|
||||
|
||||
const out = await savePptx(opened)
|
||||
const reopened = await openPptx(out)
|
||||
const freshGrp = reopened.deck.slides[slideIdx]!.elements.find(
|
||||
(e) => e.type === 'group',
|
||||
) as GroupElement
|
||||
expect(freshGrp).toBeDefined()
|
||||
const freshChild = freshGrp.children.find((c) => c.nvId === child.nvId)!
|
||||
expect(freshChild.transform.offset).toEqual({ x: 123456, y: 234567, cx: 345678, cy: 456789 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('group child format operations (font/fill/stroke)', () => {
|
||||
const mk = () =>
|
||||
makeSlide(GRP_XML(SP(2, 0, 0) + SP(4, 9, 9)), [makeChild('c2', '2'), makeChild('c4', '4')])
|
||||
|
||||
it('editGroupChildFill: model fill updated + group XML child slice patched', async () => {
|
||||
const { editGroupChildFill } = await import('../src/index')
|
||||
const { slide, grp } = mk()
|
||||
expect(editGroupChildFill(slide, 'grp1', 'c4', '#FF8800')).toBe(true)
|
||||
expect((grp.children[1] as any).fill).toEqual({ type: 'solid', color: '#FF8800' })
|
||||
// Only the id=4 slice carries the new fill
|
||||
const slices = grp.anchor.originalXml.split('<p:sp>')
|
||||
expect(slices[2]).toContain('FF8800')
|
||||
expect(slices[1]).not.toContain('FF8800')
|
||||
expect(slide.structureDirty).toBe(true)
|
||||
})
|
||||
|
||||
it('editGroupChildStroke: adding and removing a stroke', async () => {
|
||||
const { editGroupChildStroke } = await import('../src/index')
|
||||
const { slide, grp } = mk()
|
||||
expect(editGroupChildStroke(slide, 'grp1', 'c2', { color: '#112233', widthEmu: 19050 })).toBe(
|
||||
true,
|
||||
)
|
||||
expect(grp.anchor.originalXml).toContain('112233')
|
||||
expect(editGroupChildStroke(slide, 'grp1', 'c2', null)).toBe(true)
|
||||
expect((grp.children[0] as any).stroke).toBeUndefined()
|
||||
})
|
||||
|
||||
it('setGroupChildFont: run font/size updated + txBody regenerated', async () => {
|
||||
const { setGroupChildFont } = await import('../src/index')
|
||||
const { slide, grp } = mk()
|
||||
const child = grp.children[0] as any
|
||||
child.text = { paragraphs: [{ runs: [{ text: 'hi', fontSize: 18 }] }] }
|
||||
expect(setGroupChildFont(slide, 'grp1', 'c2', { fontFamily: 'Arial', fontSizePt: 30 })).toBe(
|
||||
true,
|
||||
)
|
||||
expect(child.text.paragraphs[0].runs[0].fontFamily).toBe('Arial')
|
||||
expect(child.text.paragraphs[0].runs[0].fontSize).toBe(30)
|
||||
expect(grp.anchor.originalXml).toContain('typeface="Arial"')
|
||||
expect(grp.anchor.originalXml).toContain('sz="3000"')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,292 @@
|
||||
/**
|
||||
* Element group/ungroup (groupElements / ungroupElement) tests:
|
||||
* 1. buildGrpSpXml unit tests (generates correct p:grpSp XML).
|
||||
* 2. calcBoundingBox unit tests (bounding-box computation).
|
||||
* 3. groupElements integration: after grouping, save and reopen; child coordinates correct, original bytes passed through.
|
||||
* 4. ungroupElement integration: after ungrouping, children promoted to top level with correct coordinate conversion.
|
||||
* 5. Edge cases: fewer than 2 elements / contains passthrough → rejected.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { calcBoundingBox, buildGrpSpXml } from '../src/insert'
|
||||
import {
|
||||
appendRawElements,
|
||||
createBlankPptx,
|
||||
groupElements,
|
||||
ungroupElement,
|
||||
openPptx,
|
||||
savePptx,
|
||||
} from '../src/index'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import type { GroupElement, SlideElement } from '../src/types'
|
||||
import JSZip from 'jszip'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
// ── Unit tests: calcBoundingBox ──────────────────────────────────────────────
|
||||
|
||||
describe('calcBoundingBox', () => {
|
||||
const makeEl = (x: number, y: number, cx: number, cy: number): SlideElement => ({
|
||||
id: 'el',
|
||||
type: 'shape',
|
||||
anchor: { spIndex: 0, originalXml: '', range: [0, 0] },
|
||||
transform: { offset: { x, y, cx, cy }, rot: 0, flipH: false, flipV: false },
|
||||
})
|
||||
|
||||
it('calculates bounding box from two elements', () => {
|
||||
const a = makeEl(100, 200, 300, 400)
|
||||
const b = makeEl(500, 100, 200, 300)
|
||||
const bbox = calcBoundingBox([a, b])
|
||||
expect(bbox.x).toBe(100)
|
||||
expect(bbox.y).toBe(100)
|
||||
expect(bbox.cx).toBe(600) // 500+200 - 100
|
||||
expect(bbox.cy).toBe(500) // max(200+400, 100+300) - 100 = 600 - 100 = 500
|
||||
})
|
||||
|
||||
it('single element → bbox equals element offset', () => {
|
||||
const a = makeEl(50, 60, 100, 200)
|
||||
const bbox = calcBoundingBox([a])
|
||||
expect(bbox).toEqual({ x: 50, y: 60, cx: 100, cy: 200 })
|
||||
})
|
||||
})
|
||||
|
||||
// ── Unit tests: buildGrpSpXml ────────────────────────────────────────────────
|
||||
|
||||
const MAKE_SP = (x: number, y: number, cx: number, cy: number) =>
|
||||
`<p:sp><p:nvSpPr><p:cNvPr id="2" name="sp"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
|
||||
`<p:spPr><a:xfrm><a:off x="${x}" y="${y}"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm>` +
|
||||
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr>` +
|
||||
`<p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody></p:sp>`
|
||||
|
||||
const MOCK_SLIDE: any = {
|
||||
elements: [
|
||||
{
|
||||
id: 'el1',
|
||||
type: 'shape',
|
||||
anchor: { originalXml: MAKE_SP(100, 100, 200, 200) },
|
||||
transform: { offset: { x: 100, y: 100, cx: 200, cy: 200 } },
|
||||
},
|
||||
],
|
||||
originalXml: '<p:sld><p:cSld><p:spTree><p:grpSpPr/></p:spTree></p:cSld></p:sld>',
|
||||
}
|
||||
|
||||
describe('buildGrpSpXml', () => {
|
||||
it('generates valid p:grpSp with chOff/chExt matching bbox', () => {
|
||||
const bbox = { x: 100, y: 100, cx: 500, cy: 400 }
|
||||
const childXml = MAKE_SP(100, 100, 200, 200)
|
||||
const xml = buildGrpSpXml(MOCK_SLIDE, bbox, childXml)
|
||||
expect(xml).toContain('<p:grpSp>')
|
||||
expect(xml).toContain('<p:grpSpPr>')
|
||||
expect(xml).toContain(`<a:off x="100" y="100"/>`)
|
||||
expect(xml).toContain(`<a:ext cx="500" cy="400"/>`)
|
||||
expect(xml).toContain(`<a:chOff x="100" y="100"/>`)
|
||||
expect(xml).toContain(`<a:chExt cx="500" cy="400"/>`)
|
||||
expect(xml).toContain('</p:grpSp>')
|
||||
// Child element XML kept as-is
|
||||
expect(xml).toContain('<p:sp>')
|
||||
})
|
||||
})
|
||||
|
||||
// ── Integration tests: groupElements + ungroupElement ────────────────────────
|
||||
|
||||
describe('groupElements integration', () => {
|
||||
it('rejects group with < 2 elements', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const firstId = slide.elements.find((e) => e.type === 'text' || e.type === 'shape')?.id
|
||||
if (!firstId) return
|
||||
const result = groupElements(opened, 0, [firstId])
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects group with passthrough elements', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const editableIds = slide.elements
|
||||
.filter((e) => e.type === 'text' || e.type === 'shape' || e.type === 'picture')
|
||||
.slice(0, 1)
|
||||
.map((e) => e.id)
|
||||
const ptIds = slide.elements
|
||||
.filter((e) => e.type === 'passthrough')
|
||||
.slice(0, 1)
|
||||
.map((e) => e.id)
|
||||
if (editableIds.length === 0 || ptIds.length === 0) return
|
||||
const result = groupElements(opened, 0, [...editableIds, ...ptIds])
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('groups 2 editable elements, saves and reopens correctly', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
// Find groupable elements
|
||||
let slideIdx = -1
|
||||
let ids: string[] = []
|
||||
for (let i = 0; i < opened.deck.slides.length; i++) {
|
||||
const els = opened.deck.slides[i]!.elements.filter(
|
||||
(e) => e.type === 'text' || e.type === 'shape' || e.type === 'picture',
|
||||
)
|
||||
if (els.length >= 2) {
|
||||
slideIdx = i
|
||||
ids = els.slice(0, 2).map((e) => e.id)
|
||||
break
|
||||
}
|
||||
}
|
||||
if (slideIdx < 0) return // fixture has too few groupable elements
|
||||
|
||||
const slide = opened.deck.slides[slideIdx]!
|
||||
const originalCount = slide.elements.length
|
||||
|
||||
// Record the selected elements' bounding box (for verification)
|
||||
const elA = slide.elements.find((e) => e.id === ids[0])!
|
||||
const elB = slide.elements.find((e) => e.id === ids[1])!
|
||||
const minX = Math.min(elA.transform.offset.x, elB.transform.offset.x)
|
||||
const minY = Math.min(elA.transform.offset.y, elB.transform.offset.y)
|
||||
|
||||
const result = groupElements(opened, slideIdx, ids)
|
||||
expect(result).not.toBeNull()
|
||||
// Element count drops by one after grouping (2 become 1 group)
|
||||
expect(result!.slide.elements.length).toBe(originalCount - 1)
|
||||
// The group element exists
|
||||
const grp = result!.slide.elements.find((e) => e.id === result!.groupId)
|
||||
expect(grp).toBeDefined()
|
||||
expect(grp!.type).toBe('group')
|
||||
// Group position = top-left of the bounding box
|
||||
expect(grp!.transform.offset.x).toBe(minX)
|
||||
expect(grp!.transform.offset.y).toBe(minY)
|
||||
|
||||
// Save and reopen
|
||||
const out = await savePptx(opened)
|
||||
const reopened = await openPptx(out)
|
||||
const freshSlide = reopened.deck.slides[slideIdx]!
|
||||
const freshGrp = freshSlide.elements.find((e) => e.type === 'group')
|
||||
expect(freshGrp).toBeDefined()
|
||||
// The group contains 2 child elements
|
||||
const g = freshGrp as import('../src/types').GroupElement
|
||||
expect(g.children.length).toBe(2)
|
||||
})
|
||||
|
||||
it('ungroupElement lifts children to top level', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
// Find groupable elements
|
||||
let slideIdx = -1
|
||||
let ids: string[] = []
|
||||
for (let i = 0; i < opened.deck.slides.length; i++) {
|
||||
const els = opened.deck.slides[i]!.elements.filter(
|
||||
(e) => e.type === 'text' || e.type === 'shape' || e.type === 'picture',
|
||||
)
|
||||
if (els.length >= 2) {
|
||||
slideIdx = i
|
||||
ids = els.slice(0, 2).map((e) => e.id)
|
||||
break
|
||||
}
|
||||
}
|
||||
if (slideIdx < 0) return
|
||||
|
||||
const original = opened.deck.slides[slideIdx]!
|
||||
const originalCount = original.elements.length
|
||||
|
||||
// Group first
|
||||
const grouped = groupElements(opened, slideIdx, ids)
|
||||
if (!grouped) return
|
||||
|
||||
// Then ungroup
|
||||
const fresh = ungroupElement(opened, slideIdx, grouped.groupId)
|
||||
expect(fresh).not.toBeNull()
|
||||
|
||||
// After ungrouping, element count returns to originalCount (2 children promoted, group gone = originalCount)
|
||||
// Note: after materialize, ids of the original originalXml children may change, so only check the count
|
||||
expect(fresh!.elements.length).toBe(originalCount)
|
||||
})
|
||||
|
||||
it('nested group ungroup: only direct children promoted, sp inside the nested group not extracted by mistake', async () => {
|
||||
const sp = (name: string, x: number, y: number, cx: number, cy: number) =>
|
||||
`<p:sp><p:nvSpPr><p:cNvPr id="2" name="${name}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
|
||||
`<p:spPr><a:xfrm><a:off x="${x}" y="${y}"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm>` +
|
||||
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr>` +
|
||||
`<p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody></p:sp>`
|
||||
const inner =
|
||||
`<p:grpSp><p:nvGrpSpPr><p:cNvPr id="21" name="inner"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>` +
|
||||
`<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="2000" cy="2000"/>` +
|
||||
`<a:chOff x="0" y="0"/><a:chExt cx="2000" cy="2000"/></a:xfrm></p:grpSpPr>` +
|
||||
sp('X', 0, 0, 1000, 1000) +
|
||||
`</p:grpSp>`
|
||||
const outer =
|
||||
`<p:grpSp><p:nvGrpSpPr><p:cNvPr id="20" name="outer"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>` +
|
||||
`<p:grpSpPr><a:xfrm><a:off x="1000" y="1000"/><a:ext cx="4000" cy="4000"/>` +
|
||||
`<a:chOff x="0" y="0"/><a:chExt cx="4000" cy="4000"/></a:xfrm></p:grpSpPr>` +
|
||||
inner +
|
||||
sp('Y', 2000, 2000, 1000, 1000) +
|
||||
`</p:grpSp>`
|
||||
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const before = opened.deck.slides[0]!.elements.length
|
||||
const appended = appendRawElements(opened, 0, [outer])!
|
||||
const grpId = appended.elementIds[appended.elementIds.length - 1]!
|
||||
|
||||
const fresh = ungroupElement(opened, 0, grpId)
|
||||
expect(fresh).not.toBeNull()
|
||||
// 2 direct children: the inner group + sp Y (sp X inside the nested group is not promoted separately)
|
||||
expect(fresh!.elements.length).toBe(before + 2)
|
||||
const grps = fresh!.elements.filter((e) => e.type === 'group') as GroupElement[]
|
||||
expect(grps.length).toBe(1)
|
||||
expect(grps[0]!.children.length).toBe(1)
|
||||
// chOff/chExt 1:1, coordinates = child coordinates + group offset
|
||||
expect(grps[0]!.transform.offset).toMatchObject({ x: 1000, y: 1000, cx: 2000, cy: 2000 })
|
||||
const spY = fresh!.elements.find((e) => e.type !== 'group' && e.name === 'Y')!
|
||||
expect(spY.transform.offset).toMatchObject({ x: 3000, y: 3000, cx: 1000, cy: 1000 })
|
||||
})
|
||||
|
||||
it('roundtrip: no group edits → slide bytes unchanged (fidelity)', async () => {
|
||||
const original = fx('01_standard_business.pptx')
|
||||
const opened = await openPptx(original)
|
||||
const out = await savePptx(opened)
|
||||
const origZip = await JSZip.loadAsync(original)
|
||||
const outZip = await JSZip.loadAsync(out)
|
||||
for (const slide of opened.deck.slides) {
|
||||
const a = await origZip.file(slide.path)!.async('uint8array')
|
||||
const b = await outZip.file(slide.path)!.async('uint8array')
|
||||
expect(Buffer.from(b).equals(Buffer.from(a))).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// ── #43-A: mixed-type group children keep document order ─────────────────────
|
||||
|
||||
const SLIDE_NS =
|
||||
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
|
||||
'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"'
|
||||
|
||||
describe('parseGroup document order', () => {
|
||||
it('group mixing sp/pic: children keep document order (z-order)', () => {
|
||||
const sp = (name: string) =>
|
||||
`<p:sp><p:nvSpPr><p:cNvPr id="2" name="${name}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
|
||||
`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm>` +
|
||||
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr>` +
|
||||
`<p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody></p:sp>`
|
||||
const pic =
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="3" name="P"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>` +
|
||||
`<p:blipFill><a:blip r:embed="rId99"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
|
||||
`<p:spPr><a:xfrm><a:off x="10" y="10"/><a:ext cx="20" cy="20"/></a:xfrm>` +
|
||||
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>`
|
||||
const grp =
|
||||
`<p:grpSp><p:nvGrpSpPr><p:cNvPr id="10" name="g"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>` +
|
||||
`<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1000" cy="1000"/>` +
|
||||
`<a:chOff x="0" y="0"/><a:chExt cx="1000" cy="1000"/></a:xfrm></p:grpSpPr>` +
|
||||
sp('A') +
|
||||
pic +
|
||||
sp('B') +
|
||||
`</p:grpSp>`
|
||||
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/>` +
|
||||
grp +
|
||||
`</p:spTree></p:cSld></p:sld>`
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml, ctx: {} })
|
||||
const g = slide.elements[0] as GroupElement
|
||||
expect(g.type).toBe('group')
|
||||
expect(g.children.map((c) => c.name)).toEqual(['A', 'P', 'B'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { getSlideHidden, openPptx, savePptx, setSlideHidden } from '../src/index'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
describe('hidden slide (<p:sld show="0">)', () => {
|
||||
it('defaults to visible', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
for (const s of opened.deck.slides) expect(getSlideHidden(s)).toBe(false)
|
||||
})
|
||||
|
||||
it('hides a slide, survives save/reopen, and can be un-hidden', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
setSlideHidden(slide, true)
|
||||
expect(getSlideHidden(slide)).toBe(true)
|
||||
|
||||
// Root element carries show="0", patched only onto the <p:sld> opening tag
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const xml = reopened.deck.slides[0]!.originalXml
|
||||
const sldOpen = /<p:sld\b[^>]*>/.exec(xml)![0]
|
||||
expect(sldOpen).toContain('show="0"')
|
||||
expect(getSlideHidden(reopened.deck.slides[0]!)).toBe(true)
|
||||
expect(getSlideHidden(reopened.deck.slides[1]!)).toBe(false)
|
||||
|
||||
// Unhide: attribute is removed cleanly
|
||||
setSlideHidden(reopened.deck.slides[0]!, false)
|
||||
expect(getSlideHidden(reopened.deck.slides[0]!)).toBe(false)
|
||||
const again = await openPptx(await savePptx(reopened))
|
||||
expect(/<p:sld\b[^>]*>/.exec(again.deck.slides[0]!.originalXml)![0]).not.toContain('show=')
|
||||
})
|
||||
|
||||
it('hide is idempotent and does not stack attributes', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
setSlideHidden(slide, true)
|
||||
setSlideHidden(slide, true)
|
||||
const sldOpen = /<p:sld\b[^>]*>/.exec(slide.bodyPrefix)![0]
|
||||
expect(sldOpen.match(/show="0"/g)!.length).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,777 @@
|
||||
/**
|
||||
* Tests for new insert capabilities: chart / SmartArt / audio-video / 3D / hyperlink / header-footer /
|
||||
* field textbox / WordArt outline / arbitrary preset geometry shapes.
|
||||
* All verify the insert → save → reopen roundtrip.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import {
|
||||
openPptx,
|
||||
savePptx,
|
||||
addElement,
|
||||
addChart,
|
||||
editChartElement,
|
||||
markChartEditable,
|
||||
buildChartSpaceXml,
|
||||
parseChartXml,
|
||||
addSmartArt,
|
||||
addMedia,
|
||||
addModel3d,
|
||||
model3dPartOf,
|
||||
solidPng,
|
||||
setElementLink,
|
||||
getElementLink,
|
||||
getSlideLinks,
|
||||
groupElements,
|
||||
applyHeaderFooter,
|
||||
readHeaderFooter,
|
||||
duplicateSlide,
|
||||
type ChartElement,
|
||||
type GroupElement,
|
||||
type PassthroughElement,
|
||||
type PictureElement,
|
||||
type TextElement,
|
||||
} from '../src/index'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const OFF = { x: 914400, y: 914400, cx: 4572000, cy: 2743200 }
|
||||
|
||||
describe('addChart', () => {
|
||||
it('bar chart round-trips categories/series and renders as chart element', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addChart(opened, 0, {
|
||||
kind: 'bar',
|
||||
title: 'Quarterly Sales',
|
||||
categories: ['Q1', 'Q2', 'Q3'],
|
||||
series: [
|
||||
{ name: 'East', values: [10, 20, 30] },
|
||||
{ name: 'South', values: [15, 12, 22] },
|
||||
],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
expect(r).not.toBeNull()
|
||||
const el = r!.slide.elements.find((e) => e.id === r!.elementId)
|
||||
expect(el?.type).toBe('chart')
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2 = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el2.type).toBe('chart')
|
||||
expect(el2.chart.kind).toBe('bar')
|
||||
expect(el2.chart.categories).toEqual(['Q1', 'Q2', 'Q3'])
|
||||
expect(el2.chart.series.length).toBe(2)
|
||||
expect(el2.chart.series[0]!.values).toEqual([10, 20, 30])
|
||||
expect(el2.chart.legendPos).toBe('b')
|
||||
// Title isn't in ChartModel; verify the part XML on disk
|
||||
const chartPart = [...reopened.archive.entries.keys()].find((p) =>
|
||||
/^ppt\/charts\/chart\d+\.xml$/.test(p),
|
||||
)!
|
||||
expect(reopened.archive.readText(chartPart)).toContain('Quarterly Sales')
|
||||
})
|
||||
|
||||
it('pie and doughnut charts parse back with their kinds', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
addChart(opened, 0, {
|
||||
kind: 'pie',
|
||||
categories: ['A', 'B'],
|
||||
series: [{ name: 'S', values: [1, 2] }],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
addChart(opened, 0, {
|
||||
kind: 'doughnut',
|
||||
categories: ['A', 'B'],
|
||||
series: [{ name: 'S', values: [3, 4] }],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const els = reopened.deck.slides[0]!.elements.slice(-2) as ChartElement[]
|
||||
// The engine models a doughnut chart as pie + holePct
|
||||
expect(els.map((e) => e.chart.kind)).toEqual(['pie', 'pie'])
|
||||
expect(els.map((e) => e.chart.holePct)).toEqual([0, 50])
|
||||
})
|
||||
|
||||
it('two charts on one slide get distinct parts', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
addChart(opened, 0, {
|
||||
kind: 'line',
|
||||
categories: ['a'],
|
||||
series: [{ name: 's', values: [1] }],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
addChart(opened, 0, {
|
||||
kind: 'bar',
|
||||
categories: ['a'],
|
||||
series: [{ name: 's', values: [1] }],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
const chartParts = [...opened.archive.entries.keys()].filter((p) =>
|
||||
/^ppt\/charts\/chart\d+\.xml$/.test(p),
|
||||
)
|
||||
expect(new Set(chartParts).size).toBe(chartParts.length)
|
||||
expect(chartParts.length).toBeGreaterThanOrEqual(2)
|
||||
})
|
||||
|
||||
it('scatter chart round-trips: numeric categories go into c:xVal, series values into c:yVal, dual value axes', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addChart(opened, 0, {
|
||||
kind: 'scatter',
|
||||
categories: ['0.5', '1.8', '3'],
|
||||
series: [{ name: 'Sample', values: [10, 20, 15] }],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
expect(r).not.toBeNull()
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.type).toBe('chart')
|
||||
expect(el.chart.kind).toBe('scatter')
|
||||
expect(el.chart.scatterStyle).toBe('lineMarker')
|
||||
expect(el.chart.series[0]!.name).toBe('Sample')
|
||||
expect(el.chart.series[0]!.xValues).toEqual([0.5, 1.8, 3])
|
||||
expect(el.chart.series[0]!.values).toEqual([10, 20, 15])
|
||||
})
|
||||
|
||||
it('scatter with non-numeric categories falls back to 1..n x values', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
addChart(opened, 0, {
|
||||
kind: 'scatter',
|
||||
categories: ['a', 'b', 'c'],
|
||||
series: [{ name: 's', values: [1, 2, 3] }],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.series[0]!.xValues).toEqual([1, 2, 3])
|
||||
})
|
||||
|
||||
it('radar chart round-trips: category vertices + radarStyle standard', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addChart(opened, 0, {
|
||||
kind: 'radar',
|
||||
title: 'Skill Radar',
|
||||
categories: ['Listen', 'Speak', 'Read', 'Write'],
|
||||
series: [
|
||||
{ name: 'A', values: [3, 4, 5, 2] },
|
||||
{ name: 'B', values: [2, 5, 3, 4] },
|
||||
],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
expect(r).not.toBeNull()
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.type).toBe('chart')
|
||||
expect(el.chart.kind).toBe('radar')
|
||||
expect(el.chart.radarStyle).toBe('standard')
|
||||
expect(el.chart.categories).toEqual(['Listen', 'Speak', 'Read', 'Write'])
|
||||
expect(el.chart.series.map((s) => s.values)).toEqual([
|
||||
[3, 4, 5, 2],
|
||||
[2, 5, 3, 4],
|
||||
])
|
||||
const chartPart = [...reopened.archive.entries.keys()]
|
||||
.filter((p) => /^ppt\/charts\/chart\d+\.xml$/.test(p))
|
||||
.at(-1)!
|
||||
expect(reopened.archive.readText(chartPart)).toContain('Skill Radar')
|
||||
})
|
||||
|
||||
it('buildChartSpaceXml scatter/radar produce valid OOXML recognizable by parseChartXml', () => {
|
||||
const scatterXml = buildChartSpaceXml({
|
||||
kind: 'scatter',
|
||||
categories: ['1', '2'],
|
||||
series: [{ name: 's', values: [3, 4] }],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
expect(scatterXml).toContain('<c:scatterChart>')
|
||||
expect(scatterXml).toContain('<c:xVal>')
|
||||
const sm = parseChartXml(scatterXml)!
|
||||
expect(sm.kind).toBe('scatter')
|
||||
expect(sm.series[0]!.xValues).toEqual([1, 2])
|
||||
|
||||
const radarXml = buildChartSpaceXml({
|
||||
kind: 'radar',
|
||||
categories: ['a', 'b', 'c'],
|
||||
series: [{ name: 's', values: [1, 2, 3] }],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
expect(radarXml).toContain('<c:radarChart>')
|
||||
const rm = parseChartXml(radarXml)!
|
||||
expect(rm.kind).toBe('radar')
|
||||
expect(rm.categories).toEqual(['a', 'b', 'c'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('editChartElement style edits and preservation', () => {
|
||||
it('style toggles take effect; later type-only edits keep legend/gridlines/data labels/colors', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addChart(opened, 0, {
|
||||
kind: 'bar',
|
||||
categories: ['Q1', 'Q2'],
|
||||
series: [
|
||||
{ name: 'A', values: [1, 2] },
|
||||
{ name: 'B', values: [3, 4] },
|
||||
],
|
||||
offset: { ...OFF },
|
||||
})!
|
||||
expect(
|
||||
editChartElement(opened, 0, r.elementId, {
|
||||
legendPos: 'r',
|
||||
dataLabels: true,
|
||||
gridlines: true,
|
||||
valAxisTitle: 'Amount (100M)',
|
||||
gapWidthPct: 80,
|
||||
colorScheme: ['#112233', '#445566'],
|
||||
}),
|
||||
).toBe(true)
|
||||
|
||||
let reopened = await openPptx(await savePptx(opened))
|
||||
let el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.legendPos).toBe('r')
|
||||
expect(el.chart.dataLabels).toBe(true)
|
||||
expect(el.chart.valAxis?.gridColor).toBeTruthy()
|
||||
expect(el.chart.valAxis?.title).toBe('Amount (100M)')
|
||||
expect(el.chart.gapWidthPct).toBe(80)
|
||||
expect(el.chart.series.map((s) => s.color)).toEqual(['#112233', '#445566'])
|
||||
|
||||
// Type-only change: style and colors carried over after rebuild
|
||||
expect(editChartElement(reopened, 0, el.id, { kind: 'line' })).toBe(true)
|
||||
reopened = await openPptx(await savePptx(reopened))
|
||||
el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.kind).toBe('line')
|
||||
expect(el.chart.legendPos).toBe('r')
|
||||
expect(el.chart.dataLabels).toBe(true)
|
||||
expect(el.chart.valAxis?.gridColor).toBeTruthy()
|
||||
expect(el.chart.valAxis?.title).toBe('Amount (100M)')
|
||||
expect(el.chart.series.map((s) => s.color)).toEqual(['#112233', '#445566'])
|
||||
})
|
||||
|
||||
it('percentStacked and horizontal bar direction are preserved through rebuilds (edits do not degrade)', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addChart(opened, 0, {
|
||||
kind: 'barPercentStacked',
|
||||
categories: ['Q1', 'Q2'],
|
||||
series: [
|
||||
{ name: 'A', values: [1, 2] },
|
||||
{ name: 'B', values: [3, 4] },
|
||||
],
|
||||
offset: { ...OFF },
|
||||
barDir: 'bar',
|
||||
})!
|
||||
let reopened = await openPptx(await savePptx(opened))
|
||||
let el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.grouping).toBe('percentStacked')
|
||||
expect(el.chart.barDir).toBe('bar')
|
||||
|
||||
// Style-only change: type subdivision and direction do not degrade
|
||||
expect(editChartElement(reopened, 0, el.id, { gridlines: true })).toBe(true)
|
||||
reopened = await openPptx(await savePptx(reopened))
|
||||
el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.grouping).toBe('percentStacked')
|
||||
expect(el.chart.barDir).toBe('bar')
|
||||
void r
|
||||
})
|
||||
|
||||
it('barPercentStacked/horizontal bar XML: grouping/overlap/barDir/swapped axis positions', () => {
|
||||
const xml = buildChartSpaceXml({
|
||||
kind: 'barPercentStacked',
|
||||
categories: ['a'],
|
||||
series: [{ name: 's', values: [1] }],
|
||||
offset: { ...OFF },
|
||||
barDir: 'bar',
|
||||
})
|
||||
expect(xml).toContain('<c:barDir val="bar"/>')
|
||||
expect(xml).toContain('<c:grouping val="percentStacked"/>')
|
||||
expect(xml).toContain('<c:overlap val="100"/>')
|
||||
// Horizontal bar chart: category axis on the left, value axis at the bottom
|
||||
expect(xml).toMatch(/<c:catAx>.*?<c:axPos val="l"\/>/)
|
||||
expect(xml).toMatch(/<c:valAx>.*?<c:axPos val="b"\/>/)
|
||||
})
|
||||
|
||||
it('chart title parse round-trip; style-only edits keep the title; switchRowCol swaps rows/columns', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addChart(opened, 0, {
|
||||
kind: 'bar',
|
||||
title: 'Quarterly Results',
|
||||
categories: ['Q1', 'Q2'],
|
||||
series: [
|
||||
{ name: 'A', values: [1, 2] },
|
||||
{ name: 'B', values: [3, 4] },
|
||||
],
|
||||
offset: { ...OFF },
|
||||
})!
|
||||
let reopened = await openPptx(await savePptx(opened))
|
||||
let el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.title).toBe('Quarterly Results')
|
||||
|
||||
// Style-only change: title kept
|
||||
editChartElement(reopened, 0, el.id, { gridlines: true })
|
||||
reopened = await openPptx(await savePptx(reopened))
|
||||
el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.title).toBe('Quarterly Results')
|
||||
|
||||
// Row/column switch: categories ↔ series
|
||||
editChartElement(reopened, 0, el.id, { switchRowCol: true })
|
||||
reopened = await openPptx(await savePptx(reopened))
|
||||
el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.categories).toEqual(['A', 'B'])
|
||||
expect(el.chart.series.map((s) => s.name)).toEqual(['Q1', 'Q2'])
|
||||
expect(el.chart.series[0]!.values).toEqual([1, 3])
|
||||
expect(el.chart.series[1]!.values).toEqual([2, 4])
|
||||
void r
|
||||
})
|
||||
|
||||
it('markChartEditable: a foreign chart becomes editable after marking, saves round-trip', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addChart(opened, 0, {
|
||||
kind: 'bar',
|
||||
categories: ['a'],
|
||||
series: [{ name: 's', values: [1] }],
|
||||
offset: { ...OFF },
|
||||
})!
|
||||
// Simulate a foreign chart: strip the descr marker
|
||||
let reopened = await openPptx(await savePptx(opened))
|
||||
let el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
el.anchor.originalXml = el.anchor.originalXml.replace(' descr="aislides-chart"', '')
|
||||
delete el.descr
|
||||
expect(editChartElement(reopened, 0, el.id, { gridlines: true })).toBe(false)
|
||||
|
||||
expect(markChartEditable(reopened.deck.slides[0]!, el.id)).toBe(true)
|
||||
expect(editChartElement(reopened, 0, el.id, { gridlines: true })).toBe(true)
|
||||
|
||||
reopened = await openPptx(await savePptx(reopened))
|
||||
el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.descr).toBe('aislides-chart')
|
||||
expect(el.chart.valAxis?.gridColor).toBeTruthy()
|
||||
void r
|
||||
})
|
||||
|
||||
it('legendPos none turns the legend off; passing an empty axis title clears it', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addChart(opened, 0, {
|
||||
kind: 'bar',
|
||||
categories: ['a'],
|
||||
series: [{ name: 's', values: [1] }],
|
||||
offset: { ...OFF },
|
||||
})!
|
||||
editChartElement(opened, 0, r.elementId, { valAxisTitle: 'Title' })
|
||||
let reopened = await openPptx(await savePptx(opened))
|
||||
let el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.valAxis?.title).toBe('Title')
|
||||
|
||||
editChartElement(reopened, 0, el.id, { legendPos: 'none', valAxisTitle: '' })
|
||||
reopened = await openPptx(await savePptx(reopened))
|
||||
el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.legendPos).toBeUndefined()
|
||||
expect(el.chart.valAxis?.title).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('addSmartArt (shape-group simplification)', () => {
|
||||
it('process layout becomes an editable group with one shape per item', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addSmartArt(opened, 0, {
|
||||
layout: 'process',
|
||||
items: ['Research', 'Design', 'Develop', 'Launch'],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
expect(r).not.toBeNull()
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el = reopened.deck.slides[0]!.elements.at(-1) as GroupElement
|
||||
expect(el.type).toBe('group')
|
||||
expect(el.children.length).toBe(4)
|
||||
const texts = el.children
|
||||
.map((c) => (c as TextElement).text?.paragraphs[0]?.runs[0]?.text)
|
||||
.filter(Boolean)
|
||||
expect(texts).toEqual(['Research', 'Design', 'Develop', 'Launch'])
|
||||
})
|
||||
|
||||
it('hierarchy layout adds connector bars between levels', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addSmartArt(opened, 0, {
|
||||
layout: 'hierarchy',
|
||||
items: ['CEO', 'R&D', 'Marketing'],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
const el = r!.slide.elements.find((e) => e.id === r!.elementId) as GroupElement
|
||||
// 1 top-level + 2×(connector+node) = 5
|
||||
expect(el.children.length).toBe(5)
|
||||
})
|
||||
|
||||
it('pyramid layout stacks a triangle apex over widening trapezoids', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addSmartArt(opened, 0, {
|
||||
layout: 'pyramid',
|
||||
items: ['Vision', 'Strategy', 'Execution'],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
expect(r).not.toBeNull()
|
||||
const xml = opened.deck.slides[0]!.originalXml
|
||||
expect(xml).toContain('prst="triangle"')
|
||||
expect((xml.match(/prst="trapezoid"/g) ?? []).length).toBe(2)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el = reopened.deck.slides[0]!.elements.at(-1) as GroupElement
|
||||
expect(el.type).toBe('group')
|
||||
expect(el.children.length).toBe(3)
|
||||
})
|
||||
|
||||
it('matrix layout lays items on a 2-column grid', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addSmartArt(opened, 0, {
|
||||
layout: 'matrix',
|
||||
items: ['S', 'W', 'O', 'T'],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
const el = r!.slide.elements.find((e) => e.id === r!.elementId) as GroupElement
|
||||
expect(el.children.length).toBe(4)
|
||||
})
|
||||
|
||||
it('venn layout writes translucent overlapping circles', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addSmartArt(opened, 0, {
|
||||
layout: 'venn',
|
||||
items: ['A', 'B', 'C'],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
expect(r).not.toBeNull()
|
||||
const xml = opened.deck.slides[0]!.originalXml
|
||||
expect((xml.match(/<a:alpha val="55000"\/>/g) ?? []).length).toBe(3)
|
||||
expect((xml.match(/prst="ellipse"/g) ?? []).length).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('addMedia / addModel3d', () => {
|
||||
it('video embeds media part with dual rels and parses back as picture.media', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const bytes = new Uint8Array([0, 0, 0, 24, 0x66, 0x74, 0x79, 0x70]) // fake mp4 header
|
||||
const r = addMedia(opened, 0, { kind: 'video', bytes, ext: 'mp4', offset: { ...OFF } })
|
||||
expect(r).not.toBeNull()
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el = reopened.deck.slides[0]!.elements.at(-1) as PictureElement
|
||||
expect(el.type).toBe('picture')
|
||||
expect(el.media?.kind).toBe('video')
|
||||
expect(el.media?.target).toMatch(/^ppt\/media\/media\d+\.mp4$/)
|
||||
// Content_Types has an mp4 Default
|
||||
expect(reopened.archive.readText('[Content_Types].xml')).toContain('Extension="mp4"')
|
||||
})
|
||||
|
||||
it('audio parses back with audio kind', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addMedia(opened, 0, {
|
||||
kind: 'audio',
|
||||
bytes: new Uint8Array([0x49, 0x44, 0x33]),
|
||||
ext: 'mp3',
|
||||
offset: { ...OFF },
|
||||
})
|
||||
expect(r).not.toBeNull()
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el = reopened.deck.slides[0]!.elements.at(-1) as PictureElement
|
||||
expect(el.media?.kind).toBe('audio')
|
||||
})
|
||||
|
||||
it('3d model embeds glb part and poster picture with descr marker', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const glb = new Uint8Array([0x67, 0x6c, 0x54, 0x46]) // "glTF"
|
||||
const r = addModel3d(opened, 0, { bytes: glb, ext: 'glb', offset: { ...OFF } })
|
||||
expect(r).not.toBeNull()
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el = reopened.deck.slides[0]!.elements.at(-1) as PictureElement
|
||||
expect(el.type).toBe('picture')
|
||||
const part = model3dPartOf(el)
|
||||
expect(part).toMatch(/^ppt\/media\/media\d+\.glb$/)
|
||||
expect(reopened.archive.readBytes(part!)).toEqual(glb)
|
||||
})
|
||||
|
||||
it('solidPng produces a decodable png signature', () => {
|
||||
const png = solidPng(4, 3, [10, 20, 30])
|
||||
expect([...png.slice(0, 8)]).toEqual([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
|
||||
})
|
||||
})
|
||||
|
||||
describe('unsupported chart kinds', () => {
|
||||
// Classic-namespace chart type the model doesn't support (same bucket as stock/surface;
|
||||
// chartex parts like waterfall/funnel never even reach parseChartXml)
|
||||
const BUBBLE_CHART = `<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>
|
||||
<c:bubbleChart><c:ser><c:idx val="0"/>
|
||||
<c:xVal><c:numRef><c:f>x</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt></c:numCache></c:numRef></c:xVal>
|
||||
<c:yVal><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>10</c:v></c:pt><c:pt idx="1"><c:v>20</c:v></c:pt></c:numCache></c:numRef></c:yVal>
|
||||
<c:bubbleSize><c:numRef><c:f>s</c:f><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>5</c:v></c:pt><c:pt idx="1"><c:v>9</c:v></c:pt></c:numCache></c:numRef></c:bubbleSize>
|
||||
</c:ser></c:bubbleChart>
|
||||
</c:plotArea></c:chart></c:chartSpace>`
|
||||
|
||||
it('parseChartXml returns null for a bubble chart (no recognizable plot)', () => {
|
||||
expect(parseChartXml(BUBBLE_CHART)).toBeNull()
|
||||
})
|
||||
|
||||
it('an unsupported chart degrades to a passthrough element and survives an unrelated edit + save byte-for-byte', async () => {
|
||||
// Build a deck with a chart, then swap its part for a bubble chart on disk
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
addChart(opened, 0, {
|
||||
kind: 'bar',
|
||||
categories: ['A', 'B'],
|
||||
series: [{ name: 'S', values: [1, 2] }],
|
||||
offset: { ...OFF },
|
||||
})
|
||||
const staged = await openPptx(await savePptx(opened))
|
||||
const chartPart = [...staged.archive.entries.keys()].find((p) =>
|
||||
/^ppt\/charts\/chart\d+\.xml$/.test(p),
|
||||
)!
|
||||
staged.archive.entries.set(chartPart, Buffer.from(BUBBLE_CHART, 'utf8'))
|
||||
const buf = await savePptx(staged)
|
||||
|
||||
// Reopen: the graphicFrame no longer parses as a chart — it must become a passthrough chip, not vanish
|
||||
const reopened = await openPptx(buf)
|
||||
const pt = reopened.deck.slides[0]!.elements.find(
|
||||
(e) => e.type === 'passthrough',
|
||||
) as PassthroughElement
|
||||
expect(pt).toBeDefined()
|
||||
expect(pt.kind).toBe('chart')
|
||||
const frameXmlBefore = pt.anchor.originalXml
|
||||
|
||||
// Edit an unrelated element and save
|
||||
addElement(reopened.deck.slides[0]!, { kind: 'rect', offset: { ...OFF, y: 4000000 } })
|
||||
const saved = await openPptx(await savePptx(reopened))
|
||||
|
||||
// The chart part and the graphicFrame bytes are untouched
|
||||
expect(saved.archive.readText(chartPart)).toBe(BUBBLE_CHART)
|
||||
const pt2 = saved.deck.slides[0]!.elements.find(
|
||||
(e) => e.type === 'passthrough',
|
||||
) as PassthroughElement
|
||||
expect(pt2.kind).toBe('chart')
|
||||
expect(pt2.anchor.originalXml).toBe(frameXmlBefore)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setElementLink / getElementLink', () => {
|
||||
it('url link survives save → reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, { kind: 'rect', offset: { ...OFF }, fillColor: '#4472C4' })
|
||||
const fresh = setElementLink(opened, 0, el.id, {
|
||||
kind: 'url',
|
||||
url: 'https://example.com/a?b=1',
|
||||
})
|
||||
expect(fresh).not.toBeNull()
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const last = reopened.deck.slides[0]!.elements.at(-1)!
|
||||
expect(getElementLink(reopened, 0, last.id)).toEqual({
|
||||
kind: 'url',
|
||||
url: 'https://example.com/a?b=1',
|
||||
})
|
||||
})
|
||||
|
||||
it('slide jump link resolves to target slide index', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
duplicateSlide(opened, 0) // ensure at least 2 slides
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, { kind: 'roundRect', offset: { ...OFF } })
|
||||
setElementLink(opened, 0, el.id, { kind: 'slide', slideIndex: 1 })
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const last = reopened.deck.slides[0]!.elements.at(-1)!
|
||||
expect(getElementLink(reopened, 0, last.id)).toEqual({ kind: 'slide', slideIndex: 1 })
|
||||
// The action attribute exists
|
||||
expect(last.anchor.originalXml).toContain('ppaction://hlinksldjump')
|
||||
})
|
||||
|
||||
it('clearing the link removes hlinkClick', 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 s1 = setElementLink(opened, 0, el.id, { kind: 'url', url: 'https://x.dev' })!
|
||||
const linked = s1.elements.at(-1)!
|
||||
const s2 = setElementLink(opened, 0, linked.id, null)!
|
||||
expect(getElementLink(opened, 0, s2.elements.at(-1)!.id)).toBeNull()
|
||||
})
|
||||
|
||||
it('getSlideLinks collects every linked element on the slide', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
duplicateSlide(opened, 0)
|
||||
const slide = opened.deck.slides[0]!
|
||||
const a = addElement(slide, { kind: 'rect', offset: { ...OFF } })
|
||||
const s1 = setElementLink(opened, 0, a.id, { kind: 'url', url: 'https://example.com' })!
|
||||
const b = addElement(s1, { kind: 'roundRect', offset: { ...OFF, x: 5486400 } })
|
||||
const s2 = setElementLink(opened, 0, b.id, { kind: 'slide', slideIndex: 1 })!
|
||||
|
||||
const links = getSlideLinks(opened, 0)
|
||||
expect(links).toHaveLength(2)
|
||||
const byId = new Map(links.map((l) => [l.elementId, l.target]))
|
||||
expect(byId.get(s2.elements.at(-2)!.id)).toEqual({ kind: 'url', url: 'https://example.com' })
|
||||
expect(byId.get(s2.elements.at(-1)!.id)).toEqual({ kind: 'slide', slideIndex: 1 })
|
||||
})
|
||||
|
||||
it('getSlideLinks attributes a grouped child link to the child, not the group', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const a = addElement(slide, { kind: 'rect', offset: { ...OFF } })
|
||||
const s1 = setElementLink(opened, 0, a.id, { kind: 'url', url: 'https://grouped.dev' })!
|
||||
const b = addElement(s1, { kind: 'ellipse', offset: { ...OFF, x: 5486400 } })
|
||||
const linked = s1.elements.at(-2)!
|
||||
const grouped = groupElements(opened, 0, [linked.id, b.id])!
|
||||
expect(grouped).not.toBeNull()
|
||||
|
||||
const links = getSlideLinks(opened, 0)
|
||||
expect(links).toHaveLength(1)
|
||||
expect(links[0]!.target).toEqual({ kind: 'url', url: 'https://grouped.dev' })
|
||||
expect(links[0]!.elementId).not.toBe(grouped.groupId)
|
||||
const group = grouped.slide.elements.find((e) => e.id === grouped.groupId) as GroupElement
|
||||
expect(group.children.some((c) => c.id === links[0]!.elementId)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyHeaderFooter', () => {
|
||||
it('writes footer + slide number + date placeholders into every slide', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const changed = applyHeaderFooter(opened, {
|
||||
footer: 'Confidential · Internal',
|
||||
slideNum: true,
|
||||
date: 'July 23, 2026',
|
||||
})
|
||||
expect(changed).toBe(true)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
for (const slide of reopened.deck.slides) {
|
||||
const state = readHeaderFooter(slide)
|
||||
expect(state.footer).toBe('Confidential · Internal')
|
||||
expect(state.slideNum).toBe(true)
|
||||
expect(state.date).toBe('July 23, 2026')
|
||||
}
|
||||
})
|
||||
|
||||
it('re-applying replaces (not duplicates) placeholders and can clear them', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
applyHeaderFooter(opened, { footer: 'v1', slideNum: true })
|
||||
applyHeaderFooter(opened, { footer: 'v2', slideNum: false })
|
||||
const slide = opened.deck.slides[0]!
|
||||
const state = readHeaderFooter(slide)
|
||||
expect(state.footer).toBe('v2')
|
||||
expect(state.slideNum).toBe(false)
|
||||
const ftrCount = slide.elements.filter((e) => e.placeholder === 'ftr').length
|
||||
expect(ftrCount).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('field runs & wordart & preset shapes', () => {
|
||||
it('slidenum field textbox round-trips as a:fld', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, {
|
||||
kind: 'textbox',
|
||||
offset: { ...OFF },
|
||||
paragraphs: [{ runs: [{ text: '1', field: 'slidenum' }] }],
|
||||
})
|
||||
expect(el.anchor.originalXml).toContain('type="slidenum"')
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2 = reopened.deck.slides[0]!.elements.at(-1) as TextElement
|
||||
const run = el2.text!.paragraphs[0]!.runs[0]!
|
||||
expect(run.field).toBe('slidenum')
|
||||
})
|
||||
|
||||
it('wordart outline (rPr a:ln) round-trips', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
addElement(slide, {
|
||||
kind: 'textbox',
|
||||
offset: { ...OFF },
|
||||
paragraphs: [
|
||||
{
|
||||
runs: [
|
||||
{
|
||||
text: 'WordArt',
|
||||
bold: true,
|
||||
fontSize: 54,
|
||||
color: '#4472C4',
|
||||
outline: { color: '#FFFFFF', widthEmu: 19050 },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2 = reopened.deck.slides[0]!.elements.at(-1) as TextElement
|
||||
const run = el2.text!.paragraphs[0]!.runs[0]!
|
||||
expect(run.outline).toEqual({ color: '#FFFFFF', widthEmu: 19050 })
|
||||
expect(run.fontSize).toBe(54)
|
||||
})
|
||||
|
||||
it('arbitrary preset geometry (star5 / chevron) round-trips', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
addElement(slide, { kind: 'star5', offset: { ...OFF }, fillColor: '#FFC000' })
|
||||
addElement(slide, { kind: 'chevron', offset: { ...OFF }, fillColor: '#70AD47' })
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const els = reopened.deck.slides[0]!.elements.slice(-2) as TextElement[]
|
||||
expect(els.map((e) => e.presetGeometry)).toEqual(['star5', 'chevron'])
|
||||
})
|
||||
|
||||
it('shape stroke option writes spPr a:ln', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
addElement(slide, {
|
||||
kind: 'rect',
|
||||
offset: { ...OFF },
|
||||
fillColor: '#FFFFFF',
|
||||
stroke: { color: '#4472C4', widthEmu: 28575 },
|
||||
})
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2 = reopened.deck.slides[0]!.elements.at(-1) as TextElement
|
||||
expect(el2.stroke?.width).toBe(28575)
|
||||
expect(el2.stroke?.fill).toEqual({ type: 'solid', color: '#4472C4' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('per-data-point chart colors (#90)', () => {
|
||||
it('pointColors patch writes <c:dPt>, survives save/reopen and later style-only rebuilds', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addChart(opened, 0, {
|
||||
kind: 'doughnut',
|
||||
categories: ['蓝', '橙', '黄', '绿'],
|
||||
series: [{ name: 'S', values: [1, 2, 3, 4] }],
|
||||
offset: { ...OFF },
|
||||
})!
|
||||
// The issue's scenario: blue/orange/yellow/green per sector — impossible via the 5 schemes
|
||||
expect(
|
||||
editChartElement(opened, 0, r.elementId, {
|
||||
pointColors: { 0: { 0: '#4472C4', 1: '#ED7D31', 2: '#FFC000', 3: '#70AD47' } },
|
||||
}),
|
||||
).toBe(true)
|
||||
|
||||
let reopened = await openPptx(await savePptx(opened))
|
||||
let el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.series[0]!.pointColors).toEqual(['#4472C4', '#ED7D31', '#FFC000', '#70AD47'])
|
||||
|
||||
// A style-only rebuild must not drop the dPt colors
|
||||
expect(editChartElement(reopened, 0, el.id, { dataLabels: true })).toBe(true)
|
||||
reopened = await openPptx(await savePptx(reopened))
|
||||
el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.series[0]!.pointColors).toEqual(['#4472C4', '#ED7D31', '#FFC000', '#70AD47'])
|
||||
expect(el.chart.dataLabels).toBe(true)
|
||||
})
|
||||
|
||||
it('single-point override and null clear', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addChart(opened, 0, {
|
||||
kind: 'bar',
|
||||
categories: ['Q1', 'Q2', 'Q3'],
|
||||
series: [{ name: 'A', values: [1, 2, 3] }],
|
||||
offset: { ...OFF },
|
||||
})!
|
||||
editChartElement(opened, 0, r.elementId, { pointColors: { 0: { 1: '#FF0000' } } })
|
||||
let reopened = await openPptx(await savePptx(opened))
|
||||
let el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.series[0]!.pointColors?.[1]).toBe('#FF0000')
|
||||
expect(el.chart.series[0]!.pointColors?.[0]).toBeUndefined()
|
||||
|
||||
editChartElement(reopened, 0, el.id, { pointColors: { 0: { 1: null } } })
|
||||
reopened = await openPptx(await savePptx(reopened))
|
||||
el = reopened.deck.slides[0]!.elements.at(-1) as ChartElement
|
||||
expect(el.chart.series[0]!.pointColors?.[1]).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { openPptx, savePptx, addElement, deleteElement } from '../src/index'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const OFF = { x: 914400, y: 914400, cx: 3657600, cy: 914400 }
|
||||
|
||||
describe('add/delete element', () => {
|
||||
it('added textbox survives save → reopen with text and geometry', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const before = slide.elements.length
|
||||
const el = addElement(slide, {
|
||||
kind: 'textbox',
|
||||
offset: { ...OFF },
|
||||
paragraphs: [{ runs: [{ text: 'Newly inserted textbox', bold: true }] }],
|
||||
})
|
||||
expect(el.type).toBe('text')
|
||||
expect(slide.elements.length).toBe(before + 1)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const slide2 = reopened.deck.slides[0]!
|
||||
expect(slide2.elements.length).toBe(before + 1)
|
||||
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('')
|
||||
expect(text).toBe('Newly inserted textbox')
|
||||
expect(el2.text.paragraphs[0].runs[0].bold).toBe(true)
|
||||
})
|
||||
|
||||
it('added shape round-trips preset geometry and solid fill', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
addElement(slide, { kind: 'ellipse', offset: { ...OFF }, fillColor: '#C43E1C' })
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2: any = reopened.deck.slides[0]!.elements.at(-1)
|
||||
expect(el2.type).toBe('shape')
|
||||
expect(el2.presetGeometry).toBe('ellipse')
|
||||
expect(el2.fill).toEqual({ type: 'solid', color: '#C43E1C' })
|
||||
})
|
||||
|
||||
it('run fontFamily writes both latin and ea slots and round-trips', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, {
|
||||
kind: 'textbox',
|
||||
offset: { ...OFF },
|
||||
paragraphs: [{ runs: [{ text: '中文 Latin', fontFamily: '微软雅黑' }] }],
|
||||
})
|
||||
expect(el.anchor.originalXml).toContain('<a:latin typeface="微软雅黑"/>')
|
||||
expect(el.anchor.originalXml).toContain('<a:ea typeface="微软雅黑"/>')
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2: any = reopened.deck.slides[0]!.elements.at(-1)
|
||||
expect(el2.text.paragraphs[0].runs[0].fontFamily).toBe('微软雅黑')
|
||||
})
|
||||
|
||||
it('cNvPr ids stay unique after two inserts', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const a = addElement(slide, { kind: 'rect', offset: { ...OFF } })
|
||||
const b = addElement(slide, { kind: 'rect', offset: { ...OFF } })
|
||||
const idOf = (xml: string) => /<p:cNvPr\s[^>]*\bid="(\d+)"/.exec(xml)![1]
|
||||
expect(idOf(a.anchor.originalXml)).not.toBe(idOf(b.anchor.originalXml))
|
||||
})
|
||||
|
||||
it('delete element persists through save → reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const before = slide.elements.length
|
||||
expect(before).toBeGreaterThan(1)
|
||||
const victim = slide.elements[0]!
|
||||
expect(deleteElement(slide, victim.id)).toBe(true)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides[0]!.elements.length).toBe(before - 1)
|
||||
})
|
||||
|
||||
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)
|
||||
expect(slide.structureDirty).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Layout selection tests:
|
||||
* 1. listSlideLayouts enumerates the slideLayouts in the pptx
|
||||
* 2. insertSlideWithLayout inserts a new slide → rels point to the chosen layout, placeholder count correct
|
||||
* 3. save → reopen roundtrip does not break existing slides
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { openPptx, savePptx, listSlideLayouts, insertSlideWithLayout } from '../src/index'
|
||||
import { resolveTarget, relsPathFor } from '../src/zip'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
describe('listSlideLayouts', () => {
|
||||
it('returns a non-empty layout list, each entry with path / name / layoutType', async () => {
|
||||
const { archive } = await openPptx(fx('01_standard_business.pptx'))
|
||||
const layouts = listSlideLayouts(archive)
|
||||
expect(layouts.length).toBeGreaterThan(0)
|
||||
for (const lay of layouts) {
|
||||
expect(lay.path).toMatch(/^ppt\/slideLayouts\/slideLayout\d+\.xml$/)
|
||||
expect(typeof lay.name).toBe('string')
|
||||
expect(typeof lay.layoutType).toBe('string')
|
||||
expect(Array.isArray(lay.placeholders)).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('layout paths sorted by number ascending', async () => {
|
||||
const { archive } = await openPptx(fx('01_standard_business.pptx'))
|
||||
const layouts = listSlideLayouts(archive)
|
||||
const nums = layouts.map((l) => parseInt(/(\d+)/.exec(l.path)?.[1] ?? '0', 10))
|
||||
expect(nums).toEqual([...nums].sort((a, b) => a - b))
|
||||
})
|
||||
})
|
||||
|
||||
describe('insertSlideWithLayout', () => {
|
||||
it('new slide rels point to the chosen layout (correct after save+reopen)', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const layouts = listSlideLayouts(opened.archive)
|
||||
expect(layouts.length).toBeGreaterThan(0)
|
||||
|
||||
const targetLayout = layouts[0]!
|
||||
const before = opened.deck.slides.length
|
||||
|
||||
const newSlide = insertSlideWithLayout(opened, 0, targetLayout.path)
|
||||
expect(newSlide).not.toBeNull()
|
||||
expect(opened.deck.slides.length).toBe(before + 1)
|
||||
// New slide inserted at index=1 (after sourceIndex=0)
|
||||
expect(opened.deck.slides[1]).toBe(newSlide)
|
||||
|
||||
// save + reopen
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides.length).toBe(before + 1)
|
||||
|
||||
// Verify the new slide's rels point to the chosen layout
|
||||
const newPath = reopened.deck.slides[1]!.path
|
||||
const relsPath = relsPathFor(newPath)
|
||||
const _relsXml = reopened.archive.readText(relsPath) ?? ''
|
||||
// The Target in rels has the form '../../ppt/slideLayouts/slideLayoutN.xml';
|
||||
// resolving it from the slide path should equal layoutPath
|
||||
const relEntries = [...reopened.archive.readRels(newPath).values()]
|
||||
const layoutRel = relEntries.find(
|
||||
(r) => r.type.endsWith('/slideLayout') || r.type.includes('slideLayout'),
|
||||
)
|
||||
expect(layoutRel).toBeDefined()
|
||||
const resolvedLayout = resolveTarget(newPath, layoutRel!.target)
|
||||
expect(resolvedLayout).toBe(targetLayout.path)
|
||||
|
||||
// Original slide 0 is intact (still has elements)
|
||||
expect(reopened.deck.slides[0]!.elements.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('when the chosen layout has placeholders, the new slide contains matching ph elements', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const layouts = listSlideLayouts(opened.archive)
|
||||
// Find a layout that has a title placeholder
|
||||
const withTitle = layouts.find((l) =>
|
||||
l.placeholders.some((p) => p.type === 'title' || p.type === 'ctrTitle'),
|
||||
)
|
||||
if (!withTitle) return // skip if the fixture has no such layout
|
||||
|
||||
const newSlide = insertSlideWithLayout(opened, 0, withTitle.path)
|
||||
expect(newSlide).not.toBeNull()
|
||||
|
||||
const saved = await savePptx(opened)
|
||||
const reopened = await openPptx(saved)
|
||||
const slide = reopened.deck.slides[1]!
|
||||
// The new slide's XML should contain p:ph tags (placeholder textboxes)
|
||||
const slideXml = reopened.archive.readText(slide.path) ?? ''
|
||||
expect(slideXml).toContain('<p:ph')
|
||||
})
|
||||
|
||||
it('roundtrip: original slide bytes unchanged before/after the insertion', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const layouts = listSlideLayouts(opened.archive)
|
||||
const targetLayout = layouts[0]!
|
||||
|
||||
// Record slide 0's XML before insertion
|
||||
const originalPath = opened.deck.slides[0]!.path
|
||||
const originalXml = opened.archive.readText(originalPath) ?? ''
|
||||
|
||||
insertSlideWithLayout(opened, 0, targetLayout.path)
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
|
||||
// Slide 0 (the unchanged slide) should keep identical XML
|
||||
const afterXml = reopened.archive.readText(reopened.deck.slides[0]!.path) ?? ''
|
||||
expect(afterXml).toBe(originalXml)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
/** Phase 1: Insertable straight lines / arrow lines as p:cxnSp connectors. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { openPptx, savePptx, createBlankPptx } from '../src/index'
|
||||
import { addElement, isLineKind } from '../src/insert'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
describe('line insertion (p:cxnSp)', () => {
|
||||
it('recognizes line kinds', () => {
|
||||
expect(isLineKind('line')).toBe(true)
|
||||
expect(isLineKind('lineArrow')).toBe(true)
|
||||
expect(isLineKind('lineArrowDouble')).toBe(true)
|
||||
expect(isLineKind('rect')).toBe(false)
|
||||
expect(isLineKind('textbox')).toBe(false)
|
||||
})
|
||||
|
||||
it('plain line: cxnSp with prst=line, stroke only, zero height allowed', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, {
|
||||
kind: 'line',
|
||||
offset: { x: 100, y: 200, cx: 3000000, cy: 0 },
|
||||
stroke: { color: '#ff0000', widthEmu: 12700 },
|
||||
})
|
||||
expect(el.type).toBe('shape')
|
||||
expect(el.presetGeometry).toBe('line')
|
||||
expect(el.fill).toEqual({ type: 'none' })
|
||||
expect(el.stroke?.headEnd).toBeUndefined()
|
||||
expect(el.stroke?.tailEnd).toBeUndefined()
|
||||
const xml = el.anchor.originalXml
|
||||
expect(xml).toContain('<p:cxnSp>')
|
||||
expect(xml).toContain('<a:prstGeom prst="line">')
|
||||
expect(xml).toContain('<a:srgbClr val="FF0000"/>')
|
||||
expect(xml).not.toContain('txBody')
|
||||
expect(xml).not.toContain('headEnd')
|
||||
expect(xml).not.toContain('tailEnd')
|
||||
})
|
||||
|
||||
it('arrow lines: straightConnector1 with tailEnd / headEnd+tailEnd', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const single = addElement(slide, { kind: 'lineArrow', offset: { x: 0, y: 0, cx: 100, cy: 50 } })
|
||||
expect(single.presetGeometry).toBe('straightConnector1')
|
||||
expect(single.stroke?.tailEnd?.type).toBe('triangle')
|
||||
expect(single.stroke?.headEnd).toBeUndefined()
|
||||
expect(single.anchor.originalXml).toContain('<a:tailEnd type="triangle"')
|
||||
|
||||
const dbl = addElement(slide, {
|
||||
kind: 'lineArrowDouble',
|
||||
offset: { x: 0, y: 0, cx: 100, cy: 50 },
|
||||
})
|
||||
expect(dbl.stroke?.headEnd?.type).toBe('triangle')
|
||||
expect(dbl.stroke?.tailEnd?.type).toBe('triangle')
|
||||
expect(dbl.anchor.originalXml).toContain('<a:headEnd type="triangle"')
|
||||
})
|
||||
|
||||
it('bent/curved connectors insert with their preset geometry (phase 2)', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
expect(isLineKind('lineBent')).toBe(true)
|
||||
expect(isLineKind('lineCurved')).toBe(true)
|
||||
const bent = addElement(slide, { kind: 'lineBent', offset: { x: 0, y: 0, cx: 100, cy: 80 } })
|
||||
expect(bent.presetGeometry).toBe('bentConnector3')
|
||||
expect(bent.anchor.originalXml).toContain('<a:prstGeom prst="bentConnector3">')
|
||||
expect(bent.anchor.originalXml).toContain('name="Elbow Connector')
|
||||
const curved = addElement(slide, {
|
||||
kind: 'lineCurved',
|
||||
offset: { x: 0, y: 0, cx: 100, cy: 80 },
|
||||
})
|
||||
expect(curved.presetGeometry).toBe('curvedConnector3')
|
||||
expect(curved.anchor.originalXml).toContain('<a:prstGeom prst="curvedConnector3">')
|
||||
expect(curved.anchor.originalXml).toContain('name="Curved Connector')
|
||||
})
|
||||
|
||||
it('round-trips through save and reparses as a connector', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
addElement(slide, {
|
||||
kind: 'lineArrow',
|
||||
offset: { x: 914400, y: 914400, cx: 1828800, cy: 0 },
|
||||
stroke: { color: '#0070c0', widthEmu: 19050 },
|
||||
})
|
||||
const reopened = await openPptx(Buffer.from(await savePptx(opened)))
|
||||
const parsed = reopened.deck.slides[0]!.elements.find(
|
||||
(e) => (e as TextElement).presetGeometry === 'straightConnector1',
|
||||
) as TextElement | undefined
|
||||
expect(parsed).toBeDefined()
|
||||
expect(parsed!.type).toBe('shape')
|
||||
expect(parsed!.fill).toEqual({ type: 'none' })
|
||||
expect(parsed!.stroke?.tailEnd?.type).toBe('triangle')
|
||||
expect(parsed!.stroke?.width).toBe(19050)
|
||||
expect(parsed!.transform.offset).toEqual({ x: 914400, y: 914400, cx: 1828800, cy: 0 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,110 @@
|
||||
/** Master/layout editing: enumeration/parsing, byte-surgery write-back, inheritance taking effect (6.16). */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import {
|
||||
openPptx,
|
||||
savePptx,
|
||||
patchSlideXml,
|
||||
listMasterParts,
|
||||
parseMasterPart,
|
||||
materializeSlide,
|
||||
} from '../src/index'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
describe('listMasterParts / parseMasterPart', () => {
|
||||
it('enumeration: master first, layouts after; both part kinds parse into elements', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const parts = listMasterParts(opened.archive)
|
||||
expect(parts[0]!.kind).toBe('master')
|
||||
expect(parts.filter((p) => p.kind === 'layout').length).toBeGreaterThan(1)
|
||||
|
||||
const master = parseMasterPart(opened.archive, parts[0]!.partPath)!
|
||||
expect(master.elements.length).toBeGreaterThan(0)
|
||||
expect(master.elements.some((e) => e.placeholder === 'title')).toBe(true)
|
||||
|
||||
const layout = parseMasterPart(opened.archive, parts[1]!.partPath)!
|
||||
expect(layout.elements.length).toBeGreaterThan(0)
|
||||
expect(layout.elements.every((e) => e.transform.offset.cx >= 0)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('slide master edit write-back (byte surgery)', () => {
|
||||
it('edit master title placeholder text: dirty element regenerated, other elements pass through byte-for-byte, persists after savePptx', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const parts = listMasterParts(opened.archive)
|
||||
const masterPath = parts[0]!.partPath
|
||||
const layoutPath = parts[1]!.partPath
|
||||
const layoutBefore = opened.archive.readText(layoutPath)!
|
||||
const master = parseMasterPart(opened.archive, masterPath)!
|
||||
|
||||
const title = master.elements.find((e) => e.placeholder === 'title') as TextElement
|
||||
title.text!.paragraphs[0]!.runs[0]!.text = 'MASTER-EDITED'
|
||||
title.dirty = true
|
||||
|
||||
const patched = patchSlideXml(master)
|
||||
expect(patched).toContain('MASTER-EDITED')
|
||||
// Untouched elements preserved byte-for-byte
|
||||
for (const el of master.elements) {
|
||||
if (el === title) continue
|
||||
expect(patched).toContain(el.anchor.originalXml)
|
||||
}
|
||||
opened.archive.entries.set(masterPath, Buffer.from(patched, 'utf8'))
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.archive.readText(masterPath)).toContain('MASTER-EDITED')
|
||||
// Unedited layout parts are byte-identical
|
||||
expect(reopened.archive.readText(layoutPath)).toBe(layoutBefore)
|
||||
})
|
||||
|
||||
it('edit layout placeholder geometry: slide placeholders without explicit xfrm inherit the new geometry, still there after save and reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide0 = opened.deck.slides[0]!
|
||||
const slideTitle = slide0.elements.find((e) => e.placeholder === 'ctrTitle')!
|
||||
expect(slideTitle.anchor.originalXml).not.toContain('<a:xfrm') // precondition: geometry is inherited
|
||||
|
||||
const layoutPath = slide0.layoutPath!
|
||||
const layout = parseMasterPart(opened.archive, layoutPath)!
|
||||
const layoutTitle = layout.elements.find((e) => e.placeholder === 'ctrTitle')!
|
||||
const newX = 1234567
|
||||
layoutTitle.transform = {
|
||||
...layoutTitle.transform,
|
||||
offset: { ...layoutTitle.transform.offset, x: newX },
|
||||
}
|
||||
layoutTitle.dirtyTransform = true
|
||||
opened.archive.entries.set(layoutPath, Buffer.from(patchSlideXml(layout), 'utf8'))
|
||||
|
||||
// Inheritance takes effect immediately after reparse
|
||||
const fresh = materializeSlide(opened, 0)!
|
||||
const freshTitle = fresh.elements.find((e) => e.placeholder === 'ctrTitle')!
|
||||
expect(freshTitle.transform.offset.x).toBe(newX)
|
||||
|
||||
// Still in effect after save and reopen
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const t2 = reopened.deck.slides[0]!.elements.find((e) => e.placeholder === 'ctrTitle')!
|
||||
expect(t2.transform.offset.x).toBe(newX)
|
||||
})
|
||||
|
||||
it('edit master placeholder text color (run-level patch): part parses with the new color after save and reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const masterPath = listMasterParts(opened.archive)[0]!.partPath
|
||||
const master = parseMasterPart(opened.archive, masterPath)!
|
||||
const title = master.elements.find((e) => e.placeholder === 'title') as TextElement
|
||||
for (const p of title.text!.paragraphs)
|
||||
for (const r of p.runs) {
|
||||
r.color = '#FF0000'
|
||||
delete r.colorFollowsTheme // user explicitly recolored: no longer follows the theme
|
||||
}
|
||||
title.dirty = true
|
||||
opened.archive.entries.set(masterPath, Buffer.from(patchSlideXml(master), 'utf8'))
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const m2 = parseMasterPart(reopened.archive, masterPath)!
|
||||
const t2 = m2.elements.find((e) => e.placeholder === 'title') as TextElement
|
||||
expect(t2.text!.paragraphs[0]!.runs[0]!.color?.toUpperCase()).toBe('#FF0000')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
/** Undecodable media (e.g. TIFF) must never be dropped from the saved package. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import JSZip from 'jszip'
|
||||
import { openPptx, savePptx, createBlankPptx } from '../src/index'
|
||||
|
||||
async function deckWithTiffMedia(): Promise<Buffer> {
|
||||
const zip = await JSZip.loadAsync(await createBlankPptx())
|
||||
// Payload content doesn't matter for preservation — only the bytes surviving does
|
||||
const tiffBytes = new Uint8Array([0x49, 0x49, 0x2a, 0x00, 1, 2, 3, 4, 5, 6, 7, 8])
|
||||
zip.file('ppt/media/image1.tiff', tiffBytes)
|
||||
zip.file('ppt/media/image2.tif', tiffBytes)
|
||||
return zip.generateAsync({ type: 'nodebuffer' })
|
||||
}
|
||||
|
||||
describe('media preservation on save', () => {
|
||||
it('keeps .tif/.tiff parts byte-for-byte through open -> save', async () => {
|
||||
const opened = await openPptx(await deckWithTiffMedia())
|
||||
const out = await JSZip.loadAsync(await savePptx(opened))
|
||||
const tiff = out.file('ppt/media/image1.tiff')
|
||||
const tif = out.file('ppt/media/image2.tif')
|
||||
expect(tiff).not.toBeNull()
|
||||
expect(tif).not.toBeNull()
|
||||
const bytes = await tiff!.async('uint8array')
|
||||
expect(Array.from(bytes.slice(0, 4))).toEqual([0x49, 0x49, 0x2a, 0x00])
|
||||
})
|
||||
|
||||
it('keeps them after an edit marks the slide dirty', async () => {
|
||||
const opened = await openPptx(await deckWithTiffMedia())
|
||||
const slide = opened.deck.slides[0]!
|
||||
slide.structureDirty = true
|
||||
const out = await JSZip.loadAsync(await savePptx(opened))
|
||||
expect(out.file('ppt/media/image1.tiff')).not.toBeNull()
|
||||
expect(out.file('ppt/media/image2.tif')).not.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* Parsing tests for media (audio/video) / SmartArt pre-render / OLE preview + graphicFrame p:xfrm patch.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import JSZip from 'jszip'
|
||||
import { openPptx, createBlankPptx } from '../src/index'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { patchElementXfrm } from '../src/generate'
|
||||
import type { PassthroughElement, PictureElement, TextElement } from '../src/types'
|
||||
|
||||
const theme: any = { colors: { accent1: '#4472C4', lt1: '#FFFFFF', dk1: '#000000' } }
|
||||
|
||||
const slideWith = (body: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${body}</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
describe('audio/video pictures (p:nvPr a:videoFile/a:audioFile)', () => {
|
||||
const pic = (av: string) =>
|
||||
'<p:pic><p:nvPicPr><p:cNvPr id="4" name="movie.mp4"/><p:cNvPicPr/>' +
|
||||
`<p:nvPr>${av}</p:nvPr></p:nvPicPr>` +
|
||||
'<p:blipFill><a:blip r:embed="rId3"/></p:blipFill>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr></p:pic>'
|
||||
|
||||
it('video: kind + embedded media path parsed, poster frame still goes through mediaRef', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(pic('<a:videoFile r:link="rId2"/>')),
|
||||
ctx: {
|
||||
theme,
|
||||
mediaRels: new Map([['rId3', 'ppt/media/poster1.png']]),
|
||||
avRels: new Map([['rId2', { target: 'ppt/media/media1.mp4' }]]),
|
||||
},
|
||||
})
|
||||
const el = slide.elements[0] as PictureElement
|
||||
expect(el.type).toBe('picture')
|
||||
expect(el.mediaRef).toBe('ppt/media/poster1.png')
|
||||
expect(el.media).toEqual({ kind: 'video', target: 'ppt/media/media1.mp4' })
|
||||
})
|
||||
|
||||
it('audio: external URL keeps the external flag', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(pic('<a:audioFile r:link="rId2"/>')),
|
||||
ctx: {
|
||||
theme,
|
||||
avRels: new Map([['rId2', { target: 'https://example.com/a.mp3', external: true }]]),
|
||||
},
|
||||
})
|
||||
const el = slide.elements[0] as PictureElement
|
||||
expect(el.media).toEqual({ kind: 'audio', target: 'https://example.com/a.mp3', external: true })
|
||||
})
|
||||
|
||||
it('plain pictures carry no media field', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(pic('')),
|
||||
ctx: { theme },
|
||||
})
|
||||
expect((slide.elements[0] as PictureElement).media).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
const SMARTART_FRAME =
|
||||
'<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="5" name="Diagram 1"/></p:nvGraphicFramePr>' +
|
||||
'<p:xfrm><a:off x="100" y="200"/><a:ext cx="4000" cy="3000"/></p:xfrm>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/diagram">' +
|
||||
'<dgm:relIds xmlns:dgm="dgm" r:dm="rId1" r:lo="rId2" r:qs="rId3" r:cs="rId4"/>' +
|
||||
'</a:graphicData></a:graphic></p:graphicFrame>'
|
||||
|
||||
const DIAGRAM_DRAWING =
|
||||
'<dsp:drawing xmlns:dsp="dsp" xmlns:a="a"><dsp:spTree><dsp:nvGrpSpPr/><dsp:grpSpPr/>' +
|
||||
'<dsp:sp modelId="{X}"><dsp:nvSpPr><dsp:cNvPr id="1" name=""/><dsp:cNvSpPr/></dsp:nvSpPr>' +
|
||||
'<dsp:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="2000" cy="1000"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="roundRect"><a:avLst/></a:prstGeom></dsp:spPr>' +
|
||||
'<dsp:style><a:lnRef idx="2"><a:schemeClr val="accent1"/></a:lnRef>' +
|
||||
'<a:fillRef idx="1"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="0"/>' +
|
||||
'<a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef></dsp:style>' +
|
||||
'<dsp:txBody><a:bodyPr/><a:p><a:r><a:t>Step One</a:t></a:r></a:p></dsp:txBody></dsp:sp>' +
|
||||
'</dsp:spTree></dsp:drawing>'
|
||||
|
||||
describe('SmartArt prerendered drawing read-only preview', () => {
|
||||
it('parses previewShapes: shape colors from dsp:style theme references, text color from fontRef', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(SMARTART_FRAME),
|
||||
ctx: { theme, diagramDrawings: new Map([['rId1', DIAGRAM_DRAWING]]) },
|
||||
})
|
||||
const el = slide.elements[0] as PassthroughElement
|
||||
expect(el.type).toBe('passthrough')
|
||||
expect(el.kind).toBe('smartart')
|
||||
expect(el.transform.offset).toEqual({ x: 100, y: 200, cx: 4000, cy: 3000 })
|
||||
expect(el.previewShapes?.length).toBe(1)
|
||||
const sp = el.previewShapes![0] as TextElement
|
||||
expect(sp.presetGeometry).toBe('roundRect')
|
||||
expect(sp.fill).toEqual({ type: 'solid', color: '#4472C4' })
|
||||
expect(sp.stroke?.fill).toEqual({ type: 'solid', color: '#4472C4' })
|
||||
const run = sp.text!.paragraphs[0]!.runs[0]!
|
||||
expect(run.text).toBe('Step One')
|
||||
expect(run.color).toBe('#FFFFFF')
|
||||
})
|
||||
|
||||
it('without a drawing part (ctx missing) it remains a plain placeholder passthrough', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(SMARTART_FRAME),
|
||||
ctx: { theme },
|
||||
})
|
||||
const el = slide.elements[0] as PassthroughElement
|
||||
expect(el.kind).toBe('smartart')
|
||||
expect(el.previewShapes).toBeUndefined()
|
||||
})
|
||||
|
||||
it('save byte fidelity: anchor.originalXml not polluted by preview parsing', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(SMARTART_FRAME),
|
||||
ctx: { theme, diagramDrawings: new Map([['rId1', DIAGRAM_DRAWING]]) },
|
||||
})
|
||||
expect(slide.elements[0]!.anchor.originalXml).toBe(SMARTART_FRAME)
|
||||
})
|
||||
})
|
||||
|
||||
const OLE_FRAME =
|
||||
'<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="6" name="Object 1"/></p:nvGraphicFramePr>' +
|
||||
'<p:xfrm><a:off x="10" y="20"/><a:ext cx="900" cy="600"/></p:xfrm>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/presentationml/2006/ole">' +
|
||||
'<mc:AlternateContent xmlns:mc="mc"><mc:Choice Requires="v"><p:oleObj spid="_x0000_s1026"/></mc:Choice>' +
|
||||
'<mc:Fallback><p:oleObj><p:pic><p:nvPicPr><p:cNvPr id="7" name=""/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>' +
|
||||
'<p:blipFill><a:blip r:embed="rId7"/></p:blipFill>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="900" cy="600"/></a:xfrm></p:spPr></p:pic></p:oleObj></mc:Fallback>' +
|
||||
'</mc:AlternateContent></a:graphicData></a:graphic></p:graphicFrame>'
|
||||
|
||||
describe('OLE embedded preview picture', () => {
|
||||
it('drills through mc:AlternateContent to use the fallback p:pic as preview', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(OLE_FRAME),
|
||||
ctx: { theme, mediaRels: new Map([['rId7', 'ppt/media/image9.emf']]) },
|
||||
})
|
||||
const el = slide.elements[0] as PassthroughElement
|
||||
expect(el.kind).toBe('ole')
|
||||
expect(el.previewPicture?.mediaRef).toBe('ppt/media/image9.emf')
|
||||
})
|
||||
})
|
||||
|
||||
describe('graphicFrame p:xfrm patch (table/chart/smartart/ole movable)', () => {
|
||||
it('replaces the p:xfrm off/ext without touching the embedded pic a:xfrm', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(OLE_FRAME),
|
||||
ctx: { theme },
|
||||
})
|
||||
const el = slide.elements[0]!
|
||||
el.transform = { ...el.transform, offset: { x: 111, y: 222, cx: 900, cy: 600 } }
|
||||
const patched = patchElementXfrm(el, el.anchor.originalXml)
|
||||
expect(patched).toContain('<p:xfrm><a:off x="111" y="222"/><a:ext cx="900" cy="600"/></p:xfrm>')
|
||||
// The embedded preview picture's own a:xfrm kept as-is
|
||||
expect(patched).toContain('<a:xfrm><a:off x="0" y="0"/><a:ext cx="900" cy="600"/></a:xfrm>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('openPptx end-to-end: slide rels → diagramData → dataModelExt → drawing part / video rels', () => {
|
||||
const R = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
|
||||
|
||||
it('assembles ctx from the zip: SmartArt previewShapes + video media parsed end-to-end', async () => {
|
||||
const bytes = await createBlankPptx()
|
||||
const zip = await JSZip.loadAsync(bytes)
|
||||
|
||||
const videoPic =
|
||||
'<p:pic><p:nvPicPr><p:cNvPr id="20" name="movie.mp4"/><p:cNvPicPr/>' +
|
||||
'<p:nvPr><a:videoFile r:link="rId12"/></p:nvPr></p:nvPicPr>' +
|
||||
'<p:blipFill><a:blip r:embed="rId13"/></p:blipFill>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="500" cy="400"/></a:xfrm></p:spPr></p:pic>'
|
||||
const smartartFrame = SMARTART_FRAME.replace('r:dm="rId1"', 'r:dm="rId10"')
|
||||
|
||||
const slideXml = String(await zip.file('ppt/slides/slide1.xml')!.async('string')).replace(
|
||||
'</p:spTree>',
|
||||
`${smartartFrame}${videoPic}</p:spTree>`,
|
||||
)
|
||||
zip.file('ppt/slides/slide1.xml', slideXml)
|
||||
|
||||
const slideRels = String(
|
||||
await zip.file('ppt/slides/_rels/slide1.xml.rels')!.async('string'),
|
||||
).replace(
|
||||
'</Relationships>',
|
||||
`<Relationship Id="rId10" Type="${R}/diagramData" Target="../diagrams/data1.xml"/>` +
|
||||
`<Relationship Id="rId11" Type="http://schemas.microsoft.com/office/2007/relationships/diagramDrawing" Target="../diagrams/drawing1.xml"/>` +
|
||||
`<Relationship Id="rId12" Type="${R}/video" Target="../media/media1.mp4"/>` +
|
||||
`<Relationship Id="rId13" Type="${R}/image" Target="../media/poster1.png"/>` +
|
||||
'</Relationships>',
|
||||
)
|
||||
zip.file('ppt/slides/_rels/slide1.xml.rels', slideRels)
|
||||
|
||||
zip.file(
|
||||
'ppt/diagrams/data1.xml',
|
||||
'<?xml version="1.0"?><dgm:dataModel xmlns:dgm="dgm" xmlns:dsp="dsp">' +
|
||||
'<dgm:extLst><a:ext xmlns:a="a" uri="{X}">' +
|
||||
'<dsp:dataModelExt relId="rId11" minVer="v"/></a:ext></dgm:extLst></dgm:dataModel>',
|
||||
)
|
||||
zip.file('ppt/diagrams/drawing1.xml', DIAGRAM_DRAWING)
|
||||
zip.file('ppt/media/media1.mp4', new Uint8Array([0]))
|
||||
zip.file('ppt/media/poster1.png', new Uint8Array([0]))
|
||||
|
||||
const rebuilt = await zip.generateAsync({ type: 'uint8array' })
|
||||
const { deck } = await openPptx(rebuilt)
|
||||
const els = deck.slides[0]!.elements
|
||||
|
||||
const sa = els.find((e) => e.type === 'passthrough') as PassthroughElement
|
||||
expect(sa.kind).toBe('smartart')
|
||||
expect(sa.previewShapes?.length).toBe(1)
|
||||
expect((sa.previewShapes![0] as TextElement).presetGeometry).toBe('roundRect')
|
||||
|
||||
const vid = els.find((e) => e.type === 'picture') as PictureElement
|
||||
expect(vid.mediaRef).toBe('ppt/media/poster1.png')
|
||||
expect(vid.media).toEqual({ kind: 'video', target: 'ppt/media/media1.mp4' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('sp a:xfrm patch regression', () => {
|
||||
it('sp elements still take the a:xfrm path', () => {
|
||||
const sp =
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="1" y="2"/><a:ext cx="10" cy="10"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="rect"/></p:spPr></p:sp>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(sp),
|
||||
ctx: { theme },
|
||||
})
|
||||
const el = slide.elements[0]!
|
||||
el.transform = { ...el.transform, offset: { x: 5, y: 6, cx: 10, cy: 10 } }
|
||||
const patched = patchElementXfrm(el, el.anchor.originalXml)
|
||||
expect(patched).toContain('<a:off x="5" y="6"/>')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* mergeSlideFromPptx integration tests (mirrors html→pptx per-slide conversion + deck-level merge):
|
||||
* each slide is converted to its own single-slide pptx and merged into an existing deck,
|
||||
* without re-converting earlier slides. Uses pptxgenjs to generate real single-slide pptx
|
||||
* (same library and structure as the html-pipeline convert-worker), running the real
|
||||
* openPptx → mergeSlideFromPptx → savePptx → openPptx chain with no mocks.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import PptxGenJS from 'pptxgenjs'
|
||||
import { openPptx, savePptx, mergeSlideFromPptx } from '../src/index'
|
||||
|
||||
// 1x1 red-dot PNG (base64)
|
||||
const RED_DOT =
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
|
||||
|
||||
async function onePagePptx(text: string, withImage = false): Promise<Uint8Array> {
|
||||
const p = new PptxGenJS()
|
||||
p.defineLayout({ name: 'W', width: 13.333, height: 7.5 })
|
||||
p.layout = 'W'
|
||||
const s = p.addSlide()
|
||||
s.addText(text, { x: 1, y: 1, w: 8, h: 1, fontSize: 32 })
|
||||
if (withImage) s.addImage({ data: 'image/png;base64,' + RED_DOT, x: 1, y: 3, w: 2, h: 2 })
|
||||
const buf = (await p.write({ outputType: 'nodebuffer' })) as Buffer
|
||||
return new Uint8Array(buf)
|
||||
}
|
||||
|
||||
describe('mergeSlideFromPptx', () => {
|
||||
it('merges a single-slide pptx into an existing deck, slide count grows and content is kept', async () => {
|
||||
const base = await openPptx(await onePagePptx('PAGE_ONE'))
|
||||
expect(base.deck.slides.length).toBe(1)
|
||||
|
||||
const s2 = await mergeSlideFromPptx(base, await onePagePptx('PAGE_TWO'))
|
||||
expect(s2).not.toBeNull()
|
||||
expect(base.deck.slides.length).toBe(2)
|
||||
|
||||
const s3 = await mergeSlideFromPptx(base, await onePagePptx('PAGE_THREE'))
|
||||
expect(s3).not.toBeNull()
|
||||
expect(base.deck.slides.length).toBe(3)
|
||||
|
||||
// Reopen after save: all three slides present, in the right order
|
||||
const reopened = await openPptx(await savePptx(base))
|
||||
expect(reopened.deck.slides.length).toBe(3)
|
||||
// pptxgenjs textboxes parse as text-bearing shapes (not pure text); accept both
|
||||
const texts = reopened.deck.slides.map((sl) =>
|
||||
sl.elements
|
||||
.filter((el) => el.type === 'text' || el.type === 'shape')
|
||||
.map(
|
||||
(el) =>
|
||||
(
|
||||
el as { text?: { paragraphs: Array<{ runs: Array<{ text: string }> }> } }
|
||||
).text?.paragraphs
|
||||
?.flatMap((pg) => pg.runs.map((r) => r.text))
|
||||
.join('') ?? '',
|
||||
)
|
||||
.join(' '),
|
||||
)
|
||||
expect(texts[0]).toContain('PAGE_ONE')
|
||||
expect(texts[1]).toContain('PAGE_TWO')
|
||||
expect(texts[2]).toContain('PAGE_THREE')
|
||||
})
|
||||
|
||||
it('merging a slide with an image: media bytes moved in, rIds do not clash', async () => {
|
||||
const base = await openPptx(await onePagePptx('COVER', true))
|
||||
const before = [...base.archive.entries.keys()].filter((k) => /ppt\/media\//.test(k)).length
|
||||
expect(before).toBeGreaterThanOrEqual(1)
|
||||
|
||||
// Merge another slide with an image — both media are originally named image-1-1.png, so remap must avoid overwriting
|
||||
await mergeSlideFromPptx(base, await onePagePptx('SECOND', true))
|
||||
expect(base.deck.slides.length).toBe(2)
|
||||
|
||||
const reopened = await openPptx(await savePptx(base))
|
||||
expect(reopened.deck.slides.length).toBe(2)
|
||||
const media = [...reopened.archive.entries.keys()].filter((k) => /ppt\/media\//.test(k))
|
||||
// Both images exist independently (neither overwritten)
|
||||
expect(media.length).toBeGreaterThanOrEqual(2)
|
||||
// The second slide does contain a picture element
|
||||
const picCount = reopened.deck.slides[1]!.elements.filter((el) => el.type === 'picture').length
|
||||
expect(picCount).toBeGreaterThanOrEqual(1)
|
||||
})
|
||||
|
||||
it('saved output opens with a standard zip and has the right number of slide parts', async () => {
|
||||
const base = await openPptx(await onePagePptx('A'))
|
||||
await mergeSlideFromPptx(base, await onePagePptx('B'))
|
||||
const bytes = await savePptx(base)
|
||||
const reopened = await openPptx(bytes)
|
||||
const slideParts = [...reopened.archive.entries.keys()].filter((k) =>
|
||||
/^ppt\/slides\/slide\d+\.xml$/.test(k),
|
||||
)
|
||||
expect(slideParts.length).toBe(2)
|
||||
// presentation.xml's sldId list should also have 2 entries
|
||||
const pres = reopened.archive.readText('ppt/presentation.xml') ?? ''
|
||||
const sldIds = [...pres.matchAll(/<p:sldId\b/g)].length
|
||||
expect(sldIds).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import {
|
||||
addSlideComment,
|
||||
createBlankPptx,
|
||||
deleteSlideComment,
|
||||
getSlideComments,
|
||||
getSlideNotes,
|
||||
openPptx,
|
||||
savePptx,
|
||||
setSlideNotes,
|
||||
} from '../src/index'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
describe('speaker notes', () => {
|
||||
it('creates notesSlide (and notesMaster) on a blank deck and survives save → reopen', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
expect(getSlideNotes(opened.archive, opened.deck.slides[0]!.path)).toBe('')
|
||||
|
||||
expect(setSlideNotes(opened, 0, 'note line one\nline two <special & chars>')).toBe(true)
|
||||
expect(getSlideNotes(opened.archive, opened.deck.slides[0]!.path)).toBe(
|
||||
'note line one\nline two <special & chars>',
|
||||
)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideNotes(reopened.archive, reopened.deck.slides[0]!.path)).toBe(
|
||||
'note line one\nline two <special & chars>',
|
||||
)
|
||||
// notesMaster is registered
|
||||
expect(reopened.archive.has('ppt/notesMasters/notesMaster1.xml')).toBe(true)
|
||||
expect(reopened.archive.readText('ppt/presentation.xml')).toContain('notesMasterIdLst')
|
||||
expect(reopened.archive.readText('[Content_Types].xml')).toContain('notesSlide+xml')
|
||||
})
|
||||
|
||||
it('overwrites existing notes and clears them', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
setSlideNotes(opened, 0, 'old note')
|
||||
setSlideNotes(opened, 0, 'new note')
|
||||
expect(getSlideNotes(opened.archive, opened.deck.slides[0]!.path)).toBe('new note')
|
||||
setSlideNotes(opened, 0, '')
|
||||
expect(getSlideNotes(opened.archive, opened.deck.slides[0]!.path)).toBe('')
|
||||
})
|
||||
|
||||
it('works on a real pptx fixture', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
setSlideNotes(opened, 0, 'Introduce yourself first')
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideNotes(reopened.archive, reopened.deck.slides[0]!.path)).toBe(
|
||||
'Introduce yourself first',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('slide comments', () => {
|
||||
it('adds comments (authors part + slide part) and survives save → reopen', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slidePath = opened.deck.slides[0]!.path
|
||||
expect(getSlideComments(opened.archive, slidePath)).toEqual([])
|
||||
|
||||
const c1 = addSlideComment(opened, 0, { author: 'Carol', text: 'Title is too long' })!
|
||||
const c2 = addSlideComment(opened, 0, { author: 'Carol', text: 'Change palette & fonts' })!
|
||||
expect(c1.idx).toBe(1)
|
||||
expect(c2.idx).toBe(2)
|
||||
expect(c1.authorId).toBe(c2.authorId)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const list = getSlideComments(reopened.archive, reopened.deck.slides[0]!.path)
|
||||
expect(list.map((c) => c.text)).toEqual(['Title is too long', 'Change palette & fonts'])
|
||||
expect(list[0]!.author).toBe('Carol')
|
||||
expect(reopened.archive.readText('ppt/presentation.xml')).toBeTruthy()
|
||||
expect(reopened.archive.readText('[Content_Types].xml')).toContain('commentAuthors+xml')
|
||||
})
|
||||
|
||||
it('assigns distinct author ids and deletes by (authorId, idx)', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const a = addSlideComment(opened, 0, { author: 'Alice', text: 'A' })!
|
||||
const b = addSlideComment(opened, 0, { author: 'Bob', text: 'B' })!
|
||||
expect(a.authorId).not.toBe(b.authorId)
|
||||
|
||||
expect(deleteSlideComment(opened, 0, { authorId: a.authorId, idx: a.idx })).toBe(true)
|
||||
const slidePath = opened.deck.slides[0]!.path
|
||||
expect(getSlideComments(opened.archive, slidePath).map((c) => c.text)).toEqual(['B'])
|
||||
// Deleting a non-existent one again → false
|
||||
expect(deleteSlideComment(opened, 0, { authorId: a.authorId, idx: a.idx })).toBe(false)
|
||||
})
|
||||
|
||||
it('comments on different slides go to different parts', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
addSlideComment(opened, 0, { author: 'Carol', text: 'first slide' })
|
||||
addSlideComment(opened, 1, { author: 'Carol', text: 'second slide' })
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(
|
||||
getSlideComments(reopened.archive, reopened.deck.slides[0]!.path).map((c) => c.text),
|
||||
).toEqual(['first slide'])
|
||||
expect(
|
||||
getSlideComments(reopened.archive, reopened.deck.slides[1]!.path).map((c) => c.text),
|
||||
).toEqual(['second slide'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* Element-level paragraph format (bullet/line spacing/paragraph spacing/alignment):
|
||||
* setElementParagraphFormat + surgical pPr patch (run bytes untouched, unmodeled children like defRPr kept).
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { patchedElementXml, setElementParagraphFormat } from '../src/index'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
const slideWith = (sp: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${sp}</p:spTree></p:cSld></p:sld>`
|
||||
const spWith = (txBodyInner: string) =>
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
`<p:txBody>${txBodyInner}</p:txBody></p:sp>`
|
||||
|
||||
const parseOne = (txBodyInner: string) => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(spWith(txBodyInner)),
|
||||
ctx: {},
|
||||
})
|
||||
return { slide, el: slide.elements[0] as TextElement }
|
||||
}
|
||||
|
||||
describe('setElementParagraphFormat', () => {
|
||||
it('add bullet: buChar + hanging indent injected, run bytes untouched', () => {
|
||||
const RUN = '<a:r><a:rPr sz="1800" b="1"/><a:t>Hello</a:t></a:r>'
|
||||
const { slide, el } = parseOne(
|
||||
`<a:bodyPr/><a:p>${RUN}</a:p><a:p><a:r><a:t>Two</a:t></a:r></a:p>`,
|
||||
)
|
||||
expect(setElementParagraphFormat(slide, el.id, { bullet: 'char' })).toBe(true)
|
||||
const out = patchedElementXml(el)
|
||||
expect(out.match(/<a:buChar char="•"\/>/g)!.length).toBe(2)
|
||||
expect(out).toContain('marL="228600"')
|
||||
expect(out).toContain('indent="-228600"')
|
||||
expect(out).toContain(RUN) // original run bytes fully preserved
|
||||
})
|
||||
|
||||
it('custom bullet character written as buChar', () => {
|
||||
const { slide, el } = parseOne('<a:bodyPr/><a:p><a:r><a:t>x</a:t></a:r></a:p>')
|
||||
setElementParagraphFormat(slide, el.id, { bullet: 'char', bulletChar: '◆' })
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('<a:buChar char="◆"/>')
|
||||
expect(el.text!.paragraphs[0]!.bullet).toEqual({ type: 'char', char: '◆' })
|
||||
})
|
||||
|
||||
it('bulletHangEmu adjusts hanging indent of existing bullets', () => {
|
||||
const { slide, el } = parseOne(
|
||||
'<a:bodyPr/><a:p><a:pPr marL="342900" indent="-342900"><a:buChar char="•"/></a:pPr><a:r><a:t>x</a:t></a:r></a:p>' +
|
||||
'<a:p><a:r><a:t>plain</a:t></a:r></a:p>',
|
||||
)
|
||||
setElementParagraphFormat(slide, el.id, { bulletHangEmu: 114300 })
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('marL="114300"')
|
||||
expect(out).toContain('indent="-114300"')
|
||||
// The bullet-less paragraph is untouched
|
||||
expect(el.text!.paragraphs[1]!.marL).toBeUndefined()
|
||||
})
|
||||
|
||||
it('bulletHangEmu together with bullet overrides the default hang', () => {
|
||||
const { slide, el } = parseOne('<a:bodyPr/><a:p><a:r><a:t>x</a:t></a:r></a:p>')
|
||||
setElementParagraphFormat(slide, el.id, {
|
||||
bullet: 'char',
|
||||
bulletChar: '-',
|
||||
bulletHangEmu: 342900,
|
||||
})
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('<a:buChar char="-"/>')
|
||||
expect(out).toContain('marL="342900"')
|
||||
expect(out).toContain('indent="-342900"')
|
||||
})
|
||||
|
||||
it('bullet size/color written as buSzPct/buClr, bullet-less paragraph untouched', () => {
|
||||
const { slide, el } = parseOne(
|
||||
'<a:bodyPr/><a:p><a:pPr marL="228600" indent="-228600"><a:buChar char="•"/></a:pPr><a:r><a:t>x</a:t></a:r></a:p>' +
|
||||
'<a:p><a:r><a:t>plain</a:t></a:r></a:p>',
|
||||
)
|
||||
setElementParagraphFormat(slide, el.id, { bulletSizePct: 80, bulletColor: '#C00000' })
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('<a:buClr><a:srgbClr val="C00000"/></a:buClr>')
|
||||
expect(out).toContain('<a:buSzPct val="80000"/>')
|
||||
// Schema order: buClr → buSzPct → buChar
|
||||
expect(out).toMatch(/<a:buClr>[\s\S]*?<a:buSzPct[^>]*\/><a:buChar/)
|
||||
expect(el.text!.paragraphs[0]!.bullet).toMatchObject({ sizePct: 80, color: '#C00000' })
|
||||
expect(el.text!.paragraphs[1]!.bullet).toBeUndefined()
|
||||
})
|
||||
|
||||
it('changing the bullet glyph keeps existing color/size', () => {
|
||||
const { slide, el } = parseOne('<a:bodyPr/><a:p><a:r><a:t>x</a:t></a:r></a:p>')
|
||||
setElementParagraphFormat(slide, el.id, { bullet: 'char' })
|
||||
setElementParagraphFormat(slide, el.id, { bulletSizePct: 125, bulletColor: '#0070C0' })
|
||||
setElementParagraphFormat(slide, el.id, { bullet: 'char', bulletChar: '◆' })
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('<a:buChar char="◆"/>')
|
||||
expect(out).toContain('<a:buSzPct val="125000"/>')
|
||||
expect(out).toContain('<a:buClr><a:srgbClr val="0070C0"/></a:buClr>')
|
||||
})
|
||||
|
||||
it('numbered list writes buAutoNum', () => {
|
||||
const { slide, el } = parseOne('<a:bodyPr/><a:p><a:r><a:t>x</a:t></a:r></a:p>')
|
||||
setElementParagraphFormat(slide, el.id, { bullet: 'number' })
|
||||
expect(patchedElementXml(el)).toContain('<a:buAutoNum type="arabicPeriod"/>')
|
||||
})
|
||||
|
||||
it('remove bullet: buNone + indent reset to zero; existing explicit buChar replaced', () => {
|
||||
const { slide, el } = parseOne(
|
||||
'<a:bodyPr/><a:p><a:pPr marL="342900" indent="-342900"><a:buChar char="v"/></a:pPr><a:r><a:t>x</a:t></a:r></a:p>',
|
||||
)
|
||||
setElementParagraphFormat(slide, el.id, { bullet: 'none' })
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('<a:buNone/>')
|
||||
expect(out).not.toContain('buChar')
|
||||
expect(out).toContain('marL="0"')
|
||||
expect(out).toContain('indent="0"')
|
||||
})
|
||||
|
||||
it('line/paragraph spacing written, unmodeled defRPr inside pPr preserved', () => {
|
||||
const { slide, el } = parseOne(
|
||||
'<a:bodyPr/><a:p><a:pPr algn="ctr"><a:defRPr sz="2000"/></a:pPr><a:r><a:t>x</a:t></a:r></a:p>',
|
||||
)
|
||||
setElementParagraphFormat(slide, el.id, { lineSpacingPct: 150, spaceAfterPt: 12 })
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('<a:lnSpc><a:spcPct val="150000"/></a:lnSpc>')
|
||||
expect(out).toContain('<a:spcAft><a:spcPts val="1200"/></a:spcAft>')
|
||||
expect(out).toContain('<a:defRPr sz="2000"/>') // unmodeled child elements untouched
|
||||
expect(out).toContain('algn="ctr"') // unchanged attributes untouched
|
||||
})
|
||||
|
||||
it('justify + replace existing lnSpc (schema order keeps lnSpc first)', () => {
|
||||
const { slide, el } = parseOne(
|
||||
'<a:bodyPr/><a:p><a:pPr><a:lnSpc><a:spcPct val="100000"/></a:lnSpc><a:spcBef><a:spcPts val="600"/></a:spcBef></a:pPr><a:r><a:t>x</a:t></a:r></a:p>',
|
||||
)
|
||||
setElementParagraphFormat(slide, el.id, { align: 'justify', lineSpacingPct: 200 })
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('algn="just"')
|
||||
expect(out).toContain('<a:lnSpc><a:spcPct val="200000"/></a:lnSpc>')
|
||||
expect(out).toContain('<a:spcBef><a:spcPts val="600"/></a:spcBef>') // unchanged group preserved
|
||||
expect(out).toMatch(/<a:pPr[^>]*><a:lnSpc>[\s\S]*?<a:spcBef>/) // order is schema-valid
|
||||
expect(out.match(/<a:lnSpc>/g)!.length).toBe(1)
|
||||
})
|
||||
|
||||
it('model-level pPrExplicit flags set (later rebuild path also writes them back)', () => {
|
||||
const { slide, el } = parseOne('<a:bodyPr/><a:p><a:r><a:t>x</a:t></a:r></a:p>')
|
||||
setElementParagraphFormat(slide, el.id, { bullet: 'char', lineSpacingPct: 115 })
|
||||
const p = el.text!.paragraphs[0]!
|
||||
expect(p.pPrExplicit?.bullet).toBe(true)
|
||||
expect(p.pPrExplicit?.lnSpc).toBe(true)
|
||||
expect(p.bullet?.type).toBe('char')
|
||||
expect(p.lineHeight).toBe(115)
|
||||
})
|
||||
})
|
||||
|
||||
describe('multi-level indentation indentDelta', () => {
|
||||
it('increasing level writes lvl, own bullet hanging indent grows with the level', () => {
|
||||
const { slide, el } = parseOne('<a:bodyPr/><a:p><a:r><a:t>x</a:t></a:r></a:p>')
|
||||
setElementParagraphFormat(slide, el.id, { bullet: 'char' })
|
||||
setElementParagraphFormat(slide, el.id, { indentDelta: 1 })
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('lvl="1"')
|
||||
expect(out).toContain('marL="457200"') // 228600 * (1+1)
|
||||
setElementParagraphFormat(slide, el.id, { indentDelta: -1 })
|
||||
const out2 = patchedElementXml(el)
|
||||
expect(out2).not.toContain('lvl=')
|
||||
expect(out2).toContain('marL="228600"')
|
||||
})
|
||||
|
||||
it('level clamped between 0 and 8', () => {
|
||||
const { slide, el } = parseOne('<a:bodyPr/><a:p><a:r><a:t>x</a:t></a:r></a:p>')
|
||||
expect(setElementParagraphFormat(slide, el.id, { indentDelta: -1 })).toBe(false)
|
||||
for (let i = 0; i < 12; i++) setElementParagraphFormat(slide, el.id, { indentDelta: 1 })
|
||||
expect(el.text!.paragraphs[0]!.level).toBe(8)
|
||||
})
|
||||
})
|
||||
|
||||
describe('per-paragraph paraIndices (#85 editing-mode selection)', () => {
|
||||
const TWO_PARAS =
|
||||
'<a:bodyPr/><a:p><a:r><a:t>Heading</a:t></a:r></a:p>' +
|
||||
'<a:p><a:pPr marL="228600" indent="-228600"><a:buChar char="•"/></a:pPr><a:r><a:t>Body</a:t></a:r></a:p>'
|
||||
|
||||
it('bullet on paragraph 1 only: paragraph 0 bytes untouched', () => {
|
||||
const { slide, el } = parseOne(TWO_PARAS)
|
||||
expect(setElementParagraphFormat(slide, el.id, { bullet: 'char', bulletChar: '○' }, [1])).toBe(
|
||||
true,
|
||||
)
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('<a:buChar char="○"/>')
|
||||
expect(out).toContain('<a:p><a:r><a:t>Heading</a:t></a:r></a:p>') // p0 verbatim, no pPr injected
|
||||
expect(el.text!.paragraphs[0]!.bullet).toBeUndefined()
|
||||
expect(el.dirtyPPr?.paraIndices).toEqual([1])
|
||||
})
|
||||
|
||||
it('bullet off on paragraph 1 only (the issue scenario: heading stays clean)', () => {
|
||||
const { slide, el } = parseOne(TWO_PARAS)
|
||||
setElementParagraphFormat(slide, el.id, { bullet: 'none' }, [1])
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('<a:buNone/>')
|
||||
expect(out).toContain('<a:p><a:r><a:t>Heading</a:t></a:r></a:p>')
|
||||
})
|
||||
|
||||
it('restricted ops accumulate indices; an element-wide op widens to all paragraphs', () => {
|
||||
const { slide, el } = parseOne(TWO_PARAS)
|
||||
setElementParagraphFormat(slide, el.id, { lineSpacingPct: 150 }, [0])
|
||||
setElementParagraphFormat(slide, el.id, { spaceAfterPt: 6 }, [1])
|
||||
expect(el.dirtyPPr?.paraIndices).toEqual([0, 1])
|
||||
setElementParagraphFormat(slide, el.id, { lineSpacingPct: 115 })
|
||||
expect(el.dirtyPPr?.paraIndices).toBeUndefined()
|
||||
})
|
||||
|
||||
it('out-of-range indices are a no-op', () => {
|
||||
const { slide, el } = parseOne(TWO_PARAS)
|
||||
expect(setElementParagraphFormat(slide, el.id, { bullet: 'char' }, [9])).toBe(false)
|
||||
expect(el.dirtyPPr).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,725 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import JSZip from 'jszip'
|
||||
import { openPptx, savePptx, reassembleSlideXml } from '../src/index'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { tableRowGridCols } from '../src/table-grid'
|
||||
import { parsePlaceholderMap, parseMasterTextStyles } from '../src/placeholder'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const FIXTURES = ['01_standard_business.pptx', '05_unicode_cjk_emoji.pptx']
|
||||
|
||||
describe('openPptx', () => {
|
||||
for (const name of FIXTURES) {
|
||||
it(`parses ${name} without throwing`, async () => {
|
||||
const { deck } = await openPptx(fx(name))
|
||||
expect(deck.slides.length).toBeGreaterThan(0)
|
||||
// Slide size is positive
|
||||
expect(deck.size.cx).toBeGreaterThan(0)
|
||||
expect(deck.size.cy).toBeGreaterThan(0)
|
||||
// Each slide has elements or at least parses without error
|
||||
for (const s of deck.slides) {
|
||||
expect(Array.isArray(s.elements)).toBe(true)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
it('extracts text from standard business deck', async () => {
|
||||
const { deck } = await openPptx(fx('01_standard_business.pptx'))
|
||||
const allText = deck.slides
|
||||
.flatMap((s) => s.elements)
|
||||
.filter(
|
||||
(e): e is Extract<typeof e, { type: 'text' | 'shape' }> =>
|
||||
e.type === 'text' || e.type === 'shape',
|
||||
)
|
||||
.flatMap((e) => e.text?.paragraphs ?? [])
|
||||
.flatMap((p) => p.runs)
|
||||
.map((r) => r.text)
|
||||
.join('')
|
||||
expect(allText.trim().length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('backfills placeholder geometry from layout/master (fixes Phase 1 xfrm=0,0)', async () => {
|
||||
const { deck } = await openPptx(fx('01_standard_business.pptx'))
|
||||
const placeholders = deck.slides.flatMap((s) => s.elements).filter((e) => !!e.placeholder)
|
||||
expect(placeholders.length).toBeGreaterThan(0)
|
||||
// Placeholders got geometry backfilled from layout/master: no longer all stuck at (0,0), and sizes are non-zero
|
||||
for (const el of placeholders) {
|
||||
const o = el.transform.offset
|
||||
expect(o.cx).toBeGreaterThan(0)
|
||||
expect(o.cy).toBeGreaterThan(0)
|
||||
}
|
||||
// At least one placeholder has a non-zero offset (proves inheritance actually happened, not all zeros)
|
||||
expect(placeholders.some((el) => el.transform.offset.x > 0 || el.transform.offset.y > 0)).toBe(
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves CJK / emoji text bytes on extraction', async () => {
|
||||
const { deck } = await openPptx(fx('05_unicode_cjk_emoji.pptx'))
|
||||
const allText = deck.slides
|
||||
.flatMap((s) => s.elements)
|
||||
.filter(
|
||||
(e): e is Extract<typeof e, { type: 'text' | 'shape' }> =>
|
||||
e.type === 'text' || e.type === 'shape',
|
||||
)
|
||||
.flatMap((e) => e.text?.paragraphs ?? [])
|
||||
.flatMap((p) => p.runs)
|
||||
.map((r) => r.text)
|
||||
.join('')
|
||||
// Contains at least some non-ASCII characters (CJK/emoji)
|
||||
// eslint-disable-next-line no-control-regex -- ASCII range check is intentional
|
||||
expect(/[^\x00-\x7F]/.test(allText)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fill / color-mod / background parsing', () => {
|
||||
const theme: any = { colors: { accent1: '#0000FF', lt1: '#FFFFFF', dk1: '#000000' } }
|
||||
|
||||
const slideWith = (bodyShapes: string, bg = '') =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
bg +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${bodyShapes}</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
it('gradient fill: stops + angle (60000ths → raw)', () => {
|
||||
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 ang="2700000"/></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.stops).toEqual([
|
||||
{ pos: 0, color: '#FF0000' },
|
||||
{ pos: 1, color: '#00FF00' },
|
||||
])
|
||||
expect(el.fill.angle).toBe(2700000)
|
||||
})
|
||||
|
||||
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>' +
|
||||
'<a:prstGeom prst="rect"/><a:solidFill><a:schemeClr val="accent1">' +
|
||||
'<a:lumMod val="50000"/></a:schemeClr></a:solidFill></p:spPr></p:sp>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(sp),
|
||||
ctx: { theme },
|
||||
})
|
||||
const el = slide.elements[0] as any
|
||||
// accent1=#0000FF, lumMod 50% → #000080
|
||||
expect(el.fill).toEqual({ type: 'solid', color: '#000080' })
|
||||
})
|
||||
|
||||
it('solid fill with alpha → #RRGGBBAA', () => {
|
||||
const sp =
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="10" cy="10"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="rect"/><a:solidFill><a:srgbClr val="FF0000">' +
|
||||
'<a:alpha val="50000"/></a:srgbClr></a:solidFill></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.color).toBe('#FF000080')
|
||||
})
|
||||
|
||||
it('image (blipFill) fill via media resolver', () => {
|
||||
const sp =
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="10" cy="10"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="rect"/><a:blipFill><a:blip r:embed="rId5"/></a:blipFill></p:spPr></p:sp>'
|
||||
const mediaRels = new Map([['rId5', 'ppt/media/image1.png']])
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(sp),
|
||||
ctx: { theme, mediaRels },
|
||||
})
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.fill).toEqual({ type: 'image', mediaRef: 'ppt/media/image1.png', mode: 'stretch' })
|
||||
})
|
||||
|
||||
it('slide <p:bg> solid background', () => {
|
||||
const bg = '<p:bg><p:bgPr><a:solidFill><a:srgbClr val="112233"/></a:solidFill></p:bgPr></p:bg>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith('', bg),
|
||||
ctx: { theme },
|
||||
})
|
||||
expect(slide.background).toEqual({ type: 'solid', color: '#112233' })
|
||||
})
|
||||
|
||||
it('background inherits from master when slide has none', () => {
|
||||
const masterBg =
|
||||
'<p:sldMaster><p:cSld><p:bg><p:bgPr><a:solidFill><a:srgbClr val="ABCDEF"/></a:solidFill></p:bgPr></p:bg></p:cSld></p:sldMaster>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(''),
|
||||
ctx: { theme, masterBg },
|
||||
})
|
||||
expect(slide.background).toEqual({ type: 'solid', color: '#ABCDEF' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('text body parsing fidelity', () => {
|
||||
const slideWith = (bodyShapes: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${bodyShapes}</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
const spWith = (txBody: string) =>
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
`<p:txBody><a:bodyPr/>${txBody}</p:txBody></p:sp>`
|
||||
|
||||
const firstText = (slide: ReturnType<typeof parseSlide>) => (slide.elements[0] as any).text
|
||||
|
||||
it('pure numeric run text stays string (no fast-xml-parser number coercion)', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(spWith('<a:p><a:r><a:t>2026</a:t></a:r></a:p>')),
|
||||
ctx: {},
|
||||
})
|
||||
expect(firstText(slide).paragraphs[0].runs[0].text).toBe('2026')
|
||||
})
|
||||
|
||||
it('preserves leading/trailing spaces in run text', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(
|
||||
spWith(
|
||||
'<a:p><a:r><a:t>a </a:t></a:r><a:r><a:rPr b="1"/><a:t>bold</a:t></a:r><a:r><a:t> b</a:t></a:r></a:p>',
|
||||
),
|
||||
),
|
||||
ctx: {},
|
||||
})
|
||||
const runs = firstText(slide).paragraphs[0].runs
|
||||
expect(runs.map((r: any) => r.text).join('')).toBe('a bold b')
|
||||
})
|
||||
|
||||
it('parses lnSpc (spcPct %) + spcBef/spcAft (spcPts pt)', () => {
|
||||
const pPr =
|
||||
'<a:pPr><a:lnSpc><a:spcPct val="150000"/></a:lnSpc>' +
|
||||
'<a:spcBef><a:spcPts val="600"/></a:spcBef>' +
|
||||
'<a:spcAft><a:spcPts val="300"/></a:spcAft></a:pPr>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(spWith(`<a:p>${pPr}<a:r><a:t>x</a:t></a:r></a:p>`)),
|
||||
ctx: {},
|
||||
})
|
||||
const p = firstText(slide).paragraphs[0]
|
||||
expect(p.lineHeight).toBe(150)
|
||||
expect(p.spaceBefore).toBe(6)
|
||||
expect(p.spaceAfter).toBe(3)
|
||||
})
|
||||
|
||||
it('parses lnSpc absolute (spcPts → lineExact pt)', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(
|
||||
spWith(
|
||||
'<a:p><a:pPr><a:lnSpc><a:spcPts val="2400"/></a:lnSpc></a:pPr><a:r><a:t>x</a:t></a:r></a:p>',
|
||||
),
|
||||
),
|
||||
ctx: {},
|
||||
})
|
||||
expect(firstText(slide).paragraphs[0].lineExact).toBe(24)
|
||||
})
|
||||
|
||||
it('bodyPr vert: eaVert/vert/vert270/wordArtVert parsed, horz/absent undefined', () => {
|
||||
const spVert = (bodyPr: string) =>
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
`<p:txBody>${bodyPr}<a:p><a:r><a:t>縦</a:t></a:r></a:p></p:txBody></p:sp>`
|
||||
const vertOf = (bodyPr: string) =>
|
||||
firstText(
|
||||
parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(spVert(bodyPr)), ctx: {} }),
|
||||
).vert
|
||||
expect(vertOf('<a:bodyPr vert="eaVert"/>')).toBe('eaVert')
|
||||
expect(vertOf('<a:bodyPr vert="vert"/>')).toBe('vert')
|
||||
expect(vertOf('<a:bodyPr vert="vert270"/>')).toBe('vert270')
|
||||
expect(vertOf('<a:bodyPr vert="wordArtVert"/>')).toBe('wordArtVert')
|
||||
expect(vertOf('<a:bodyPr vert="horz"/>')).toBeUndefined()
|
||||
expect(vertOf('<a:bodyPr/>')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('<a:br/> soft break becomes "\\n" sentinel run', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(
|
||||
spWith('<a:p><a:r><a:t>A</a:t></a:r><a:br/><a:r><a:t>B</a:t></a:r></a:p>'),
|
||||
),
|
||||
ctx: {},
|
||||
})
|
||||
const texts = firstText(slide).paragraphs[0].runs.map((r: any) => r.text)
|
||||
expect(texts).toEqual(['A', '\n', 'B'])
|
||||
})
|
||||
|
||||
it('parses <a:ln> stroke (width + solid fill + dash)', () => {
|
||||
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:ln w="25400" cap="rnd"><a:solidFill><a:srgbClr val="FF6600"/></a:solidFill>' +
|
||||
'<a:prstDash val="dash"/></a:ln></p:spPr></p:sp>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(sp), ctx: {} })
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.stroke).toEqual({
|
||||
fill: { type: 'solid', color: '#FF6600' },
|
||||
width: 25400,
|
||||
dash: 'dash',
|
||||
cap: 'round',
|
||||
})
|
||||
})
|
||||
|
||||
it('<a:ln><a:noFill/> means no stroke', () => {
|
||||
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:ln w="12700"><a:noFill/></a:ln></p:spPr></p:sp>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(sp), ctx: {} })
|
||||
expect((slide.elements[0] as any).stroke).toBeUndefined()
|
||||
})
|
||||
|
||||
it('parses <a:outerShdw> shadow (blur/dist/dir/color+alpha)', () => {
|
||||
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:effectLst>' +
|
||||
'<a:outerShdw blurRad="63500" dist="25400" dir="16200000"><a:srgbClr val="000000"><a:alpha val="20000"/></a:srgbClr></a:outerShdw>' +
|
||||
'</a:effectLst></p:spPr></p:sp>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(sp), ctx: {} })
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.shadow).toEqual({ color: '#00000033', blurRad: 63500, dist: 25400, dirDeg: 270 })
|
||||
})
|
||||
|
||||
it('parses picture <a:srcRect> crop as fractions, all-zero → undefined', () => {
|
||||
const pic = (srcRect: string) =>
|
||||
'<p:pic><p:nvPicPr><p:cNvPr id="9" name="P"/></p:nvPicPr>' +
|
||||
`<p:blipFill><a:blip r:embed="rId1"/>${srcRect}<a:stretch/></p:blipFill>` +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr></p:pic>'
|
||||
const mediaRels = new Map([['rId1', 'ppt/media/image1.png']])
|
||||
const s1 = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(pic('<a:srcRect l="10000" t="25000" r="0" b="5000"/>')),
|
||||
ctx: { mediaRels },
|
||||
})
|
||||
expect((s1.elements[0] as any).srcRect).toEqual({ l: 0.1, t: 0.25, r: 0, b: 0.05 })
|
||||
const s2 = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(pic('<a:srcRect l="0" t="0" r="0" b="0"/>')),
|
||||
ctx: { mediaRels },
|
||||
})
|
||||
expect((s2.elements[0] as any).srcRect).toBeUndefined()
|
||||
})
|
||||
|
||||
it('parses prstGeom avLst adjust values (roundRect adj)', () => {
|
||||
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="roundRect"><a:avLst><a:gd name="adj" fmla="val 50000"/></a:avLst></a:prstGeom>' +
|
||||
'</p:spPr></p:sp>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(sp), ctx: {} })
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.presetGeometry).toBe('roundRect')
|
||||
expect(el.adjust).toEqual({ adj: 50000 })
|
||||
})
|
||||
|
||||
it('CJK run prefers a:ea typeface, latin run prefers a:latin', () => {
|
||||
const rPr = '<a:rPr sz="1400"><a:latin typeface="Calibri"/><a:ea typeface="SimSun"/></a:rPr>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(
|
||||
spWith(`<a:p><a:r>${rPr}<a:t>中文</a:t></a:r><a:r>${rPr}<a:t>latin</a:t></a:r></a:p>`),
|
||||
),
|
||||
ctx: {},
|
||||
})
|
||||
const runs = firstText(slide).paragraphs[0].runs
|
||||
expect(runs[0].fontFamily).toBe('SimSun')
|
||||
expect(runs[1].fontFamily).toBe('Calibri')
|
||||
})
|
||||
})
|
||||
|
||||
describe('placeholder text style inheritance', () => {
|
||||
const layoutXml =
|
||||
'<?xml version="1.0"?><p:sldLayout xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/>' +
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="1" name="T"/><p:nvSpPr/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="100" y="100"/><a:ext cx="5000" cy="1000"/></a:xfrm></p:spPr>' +
|
||||
'<p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr algn="ctr"><a:defRPr sz="3600" b="1">' +
|
||||
'<a:solidFill><a:srgbClr val="112233"/></a:solidFill><a:latin typeface="+mj-lt"/>' +
|
||||
'</a:defRPr></a:lvl1pPr></a:lstStyle><a:p><a:r><a:t>x</a:t></a:r></a:p></p:txBody></p:sp>' +
|
||||
'</p:spTree></p:cSld></p:sldLayout>'
|
||||
|
||||
const masterXml =
|
||||
'<?xml version="1.0"?><p:sldMaster xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/></p:spTree></p:cSld>' +
|
||||
'<p:txStyles><p:bodyStyle><a:lvl1pPr><a:defRPr sz="1800"><a:latin typeface="+mn-lt"/></a:defRPr></a:lvl1pPr>' +
|
||||
'<a:lvl2pPr><a:defRPr sz="1400"/></a:lvl2pPr></p:bodyStyle></p:txStyles></p:sldMaster>'
|
||||
|
||||
const theme: any = { colors: {}, majorFont: 'Georgia', minorFont: 'Calibri' }
|
||||
|
||||
const slideXmlWith = (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 pm = parsePlaceholderMap
|
||||
const pmt = parseMasterTextStyles
|
||||
|
||||
it('title placeholder run without rPr inherits layout lstStyle (sz/b/color/align/+mj-lt)', () => {
|
||||
const sp =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="2" name="Title"/><p:nvSpPr/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr/><p:txBody><a:bodyPr/><a:p><a:r><a:t>Hello</a:t></a:r></a:p></p:txBody></p:sp>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideXmlWith(sp),
|
||||
ctx: {
|
||||
theme,
|
||||
layoutPlaceholders: pm(layoutXml, theme),
|
||||
masterTextStyles: pmt(masterXml, theme),
|
||||
},
|
||||
})
|
||||
const el = slide.elements[0] as any
|
||||
const p = el.text.paragraphs[0]
|
||||
expect(p.align).toBe('center')
|
||||
expect(p.runs[0].fontSize).toBe(36)
|
||||
expect(p.runs[0].bold).toBe(true)
|
||||
expect(p.runs[0].color).toBe('#112233')
|
||||
expect(p.runs[0].fontFamily).toBe('Georgia') // +mj-lt → theme majorFont
|
||||
})
|
||||
|
||||
it('body placeholder inherits master txStyles bodyStyle per level', () => {
|
||||
const sp =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="3" name="Body"/><p:nvSpPr/><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr/><p:txBody><a:bodyPr/>' +
|
||||
'<a:p><a:r><a:t>L1</a:t></a:r></a:p>' +
|
||||
'<a:p><a:pPr lvl="1"/><a:r><a:t>L2</a:t></a:r></a:p>' +
|
||||
'</p:txBody></p:sp>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideXmlWith(sp),
|
||||
ctx: { theme, masterTextStyles: pmt(masterXml, theme) },
|
||||
})
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.text.paragraphs[0].runs[0].fontSize).toBe(18)
|
||||
expect(el.text.paragraphs[0].runs[0].fontFamily).toBe('Calibri') // +mn-lt
|
||||
expect(el.text.paragraphs[1].runs[0].fontSize).toBe(14) // lvl2
|
||||
})
|
||||
|
||||
it('explicit run rPr beats inherited defaults', () => {
|
||||
const sp =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="4" name="Title"/><p:nvSpPr/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr/><p:txBody><a:bodyPr/><a:p><a:r><a:rPr sz="2000" b="0"/><a:t>Hi</a:t></a:r></a:p></p:txBody></p:sp>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideXmlWith(sp),
|
||||
ctx: { theme, layoutPlaceholders: pm(layoutXml, theme) },
|
||||
})
|
||||
const run = (slide.elements[0] as any).text.paragraphs[0].runs[0]
|
||||
expect(run.fontSize).toBe(20)
|
||||
expect(run.bold).toBe(false)
|
||||
})
|
||||
|
||||
it('placeholder geometry inheritance still works with style-only entries present', () => {
|
||||
const sp =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="5" name="Title"/><p:nvSpPr/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr/><p:txBody><a:bodyPr/><a:p><a:r><a:t>Geo</a:t></a:r></a:p></p:txBody></p:sp>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideXmlWith(sp),
|
||||
ctx: { theme, layoutPlaceholders: pm(layoutXml, theme) },
|
||||
})
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.transform.offset.x).toBe(100)
|
||||
expect(el.transform.offset.cx).toBe(5000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('table (p:graphicFrame a:tbl) parsing', () => {
|
||||
const tableXml =
|
||||
'<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="9" name="Table 1"/></p:nvGraphicFramePr>' +
|
||||
'<p:xfrm><a:off x="914400" y="914400"/><a:ext cx="3657600" cy="1828800"/></p:xfrm>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/table"><a:tbl>' +
|
||||
'<a:tblPr/><a:tblGrid><a:gridCol w="1828800"/><a:gridCol w="1828800"/></a:tblGrid>' +
|
||||
'<a:tr h="914400">' +
|
||||
'<a:tc><a:txBody><a:bodyPr/><a:p><a:r><a:rPr sz="1200" b="1"/><a:t>H1</a:t></a:r></a:p></a:txBody>' +
|
||||
'<a:tcPr marL="90000" marR="90000" marT="45000" marB="45000" anchor="ctr">' +
|
||||
'<a:lnB w="19050"><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></a:lnB>' +
|
||||
'<a:solidFill><a:srgbClr val="112233"/></a:solidFill></a:tcPr></a:tc>' +
|
||||
'<a:tc gridSpan="1"><a:txBody><a:bodyPr/><a:p><a:r><a:t>H2</a:t></a:r></a:p></a:txBody><a:tcPr/></a:tc>' +
|
||||
'</a:tr>' +
|
||||
'<a:tr h="914400">' +
|
||||
'<a:tc gridSpan="2"><a:txBody><a:bodyPr/><a:p><a:r><a:t>Wide</a:t></a:r></a:p></a:txBody><a:tcPr/></a:tc>' +
|
||||
'<a:tc hMerge="1"><a:txBody><a:bodyPr/><a:p/></a:txBody><a:tcPr/></a:tc>' +
|
||||
'</a:tr>' +
|
||||
'</a:tbl></a:graphicData></a:graphic></p:graphicFrame>'
|
||||
const slideXml =
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${tableXml}</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
it('parses grid, rows, cell text/fill/borders/margins/anchor and merges', () => {
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml, ctx: {} })
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.type).toBe('table')
|
||||
expect(el.colWidths).toEqual([1828800, 1828800])
|
||||
expect(el.rowHeights).toEqual([914400, 914400])
|
||||
expect(el.transform.offset).toEqual({ x: 914400, y: 914400, cx: 3657600, cy: 1828800 })
|
||||
|
||||
const c00 = el.rows[0][0]
|
||||
expect(c00.text.paragraphs[0].runs[0].text).toBe('H1')
|
||||
expect(c00.text.paragraphs[0].runs[0].fontSize).toBe(12)
|
||||
expect(c00.text.anchor).toBe('middle')
|
||||
expect(c00.text.insets).toEqual({ l: 90000, r: 90000, t: 45000, b: 45000 })
|
||||
expect(c00.fill).toEqual({ type: 'solid', color: '#112233' })
|
||||
expect(c00.borders.b.width).toBe(19050)
|
||||
expect(c00.borders.l).toBeUndefined()
|
||||
|
||||
const wide = el.rows[1][0]
|
||||
expect(wide.gridSpan).toBe(2)
|
||||
expect(el.rows[1][1].merged).toBe(true)
|
||||
})
|
||||
|
||||
it('table element keeps byte fidelity (originalXml passthrough on save)', () => {
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml, ctx: {} })
|
||||
expect(reassembleSlideXml(slide)).toBe(slideXml)
|
||||
})
|
||||
})
|
||||
|
||||
describe('tableRowGridCols', () => {
|
||||
it('plain row: one tc per column', () => {
|
||||
expect(tableRowGridCols([{}, {}, {}])).toEqual([0, 1, 2])
|
||||
})
|
||||
|
||||
it('standard merge with continuation tcs advances by 1 per tc', () => {
|
||||
expect(tableRowGridCols([{}, { gridSpan: 2 }, { merged: true }, {}])).toEqual([0, 1, 2, 3])
|
||||
expect(tableRowGridCols([{ gridSpan: 3 }, { merged: true }, { merged: true }, {}])).toEqual([
|
||||
0, 1, 2, 3,
|
||||
])
|
||||
})
|
||||
|
||||
it('non-standard merge without continuation tcs advances by span', () => {
|
||||
expect(tableRowGridCols([{}, { gridSpan: 2 }, {}])).toEqual([0, 1, 3])
|
||||
})
|
||||
|
||||
it('adjacent merges stay independent', () => {
|
||||
expect(
|
||||
tableRowGridCols([{ gridSpan: 2 }, { merged: true }, { gridSpan: 2 }, { merged: true }]),
|
||||
).toEqual([0, 1, 2, 3])
|
||||
})
|
||||
|
||||
it('vMerge continuation row mirroring a gridSpan anchor', () => {
|
||||
expect(tableRowGridCols([{ gridSpan: 2, merged: true }, { merged: true }, {}])).toEqual([
|
||||
0, 1, 2,
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('group (p:grpSp) parsing', () => {
|
||||
const groupSlideXml =
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree>' +
|
||||
'<p:nvGrpSpPr/><p:grpSpPr/>' +
|
||||
'<p:grpSp><p:nvGrpSpPr><p:cNvPr id="1" name="G1"/></p:nvGrpSpPr>' +
|
||||
'<p:grpSpPr><a:xfrm><a:off x="1000" y="2000"/><a:ext cx="5000" cy="4000"/>' +
|
||||
'<a:chOff x="0" y="0"/><a:chExt cx="5000" cy="4000"/></a:xfrm></p:grpSpPr>' +
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="2" name="child1"/></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="100" y="100"/><a:ext cx="1000" cy="500"/></a:xfrm></p:spPr>' +
|
||||
'<p:txBody><a:bodyPr/><a:p><a:r><a:t>InGroup</a:t></a:r></a:p></p:txBody></p:sp>' +
|
||||
'<p:pic><p:nvPicPr><p:cNvPr id="3" name="childpic"/></p:nvPicPr>' +
|
||||
'<p:blipFill><a:blip r:embed="rId9"/></p:blipFill>' +
|
||||
'<p:spPr><a:xfrm><a:off x="2000" y="200"/><a:ext cx="800" cy="800"/></a:xfrm></p:spPr></p:pic>' +
|
||||
'</p:grpSp>' +
|
||||
'</p:spTree></p:cSld></p:sld>'
|
||||
|
||||
it('expands group children (sp + pic) with geometry + childOffset', () => {
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: groupSlideXml, ctx: {} })
|
||||
const grp = slide.elements.find((e) => e.type === 'group') as any
|
||||
expect(grp).toBeTruthy()
|
||||
expect(grp.transform.offset.x).toBe(1000)
|
||||
expect(grp.transform.offset.cx).toBe(5000)
|
||||
expect(grp.childOffset).toEqual({ x: 0, y: 0, cx: 5000, cy: 4000 })
|
||||
expect(grp.children.length).toBe(2)
|
||||
const [c1, c2] = grp.children
|
||||
expect(c1.type).toBe('text')
|
||||
expect(c1.transform.offset.x).toBe(100)
|
||||
expect(c1.text.paragraphs[0].runs[0].text).toBe('InGroup')
|
||||
expect(c2.type).toBe('picture')
|
||||
expect(c2.transform.offset.x).toBe(2000)
|
||||
})
|
||||
|
||||
it('group emits original bytes on reassemble (fidelity: no child roundtrip)', () => {
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: groupSlideXml, ctx: {} })
|
||||
expect(reassembleSlideXml(slide)).toBe(groupSlideXml)
|
||||
})
|
||||
})
|
||||
|
||||
describe('byte-fidelity roundtrip', () => {
|
||||
for (const name of FIXTURES) {
|
||||
it(`${name}: reassembleSlideXml == originalXml (no edits)`, async () => {
|
||||
const { deck } = await openPptx(fx(name))
|
||||
for (const slide of deck.slides) {
|
||||
const rebuilt = reassembleSlideXml(slide)
|
||||
expect(rebuilt).toBe(slide.originalXml)
|
||||
}
|
||||
})
|
||||
|
||||
it(`${name}: savePptx with no dirty produces byte-identical slide parts`, async () => {
|
||||
const original = fx(name)
|
||||
const opened = await openPptx(original)
|
||||
const out = await savePptx(opened)
|
||||
|
||||
// Unzip and compare each slideN.xml's decompressed bytes
|
||||
const origZip = await JSZip.loadAsync(original)
|
||||
const outZip = await JSZip.loadAsync(out)
|
||||
for (const slide of opened.deck.slides) {
|
||||
const a = await origZip.file(slide.path)!.async('uint8array')
|
||||
const b = await outZip.file(slide.path)!.async('uint8array')
|
||||
expect(Buffer.from(b).equals(Buffer.from(a))).toBe(true)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
describe('bullet (buChar/buAutoNum/buNone) and paragraph indent parsing', () => {
|
||||
const sldWith = (pPr: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/>' +
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="2" name="tb"/></p:nvSpPr><p:spPr/>' +
|
||||
`<p:txBody><a:bodyPr/><a:p>${pPr}<a:r><a:t>hi</a:t></a:r></a:p></p:txBody></p:sp>` +
|
||||
'</p:spTree></p:cSld></p:sld>'
|
||||
|
||||
it('buChar + marL/indent', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: sldWith('<a:pPr marL="127000" indent="-127000"><a:buChar char="•"/></a:pPr>'),
|
||||
ctx: {},
|
||||
})
|
||||
const p = (slide.elements[0] as any).text.paragraphs[0]
|
||||
expect(p.bullet).toEqual({ type: 'char', char: '•' })
|
||||
expect(p.marL).toBe(127000)
|
||||
expect(p.indent).toBe(-127000)
|
||||
})
|
||||
|
||||
it('buAutoNum / buNone', () => {
|
||||
const num = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: sldWith('<a:pPr><a:buAutoNum type="arabicPeriod"/></a:pPr>'),
|
||||
ctx: {},
|
||||
})
|
||||
expect((num.elements[0] as any).text.paragraphs[0].bullet.type).toBe('number')
|
||||
const none = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: sldWith('<a:pPr><a:buNone/></a:pPr>'),
|
||||
ctx: {},
|
||||
})
|
||||
expect((none.elements[0] as any).text.paragraphs[0].bullet.type).toBe('none')
|
||||
})
|
||||
})
|
||||
|
||||
describe('slide master bodyStyle bullet/indent inheritance', () => {
|
||||
const masterXml =
|
||||
'<?xml version="1.0"?><p:sldMaster xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/></p:spTree></p:cSld>' +
|
||||
'<p:txStyles><p:bodyStyle>' +
|
||||
'<a:lvl1pPr marL="342900" indent="-342900"><a:buChar char="•"/><a:defRPr sz="1800"/></a:lvl1pPr>' +
|
||||
'</p:bodyStyle></p:txStyles></p:sldMaster>'
|
||||
const sldWith = (paras: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/>' +
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="3" name="Body"/><p:nvSpPr/><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr>' +
|
||||
`<p:spPr/><p:txBody><a:bodyPr/>${paras}</p:txBody></p:sp>` +
|
||||
'</p:spTree></p:cSld></p:sld>'
|
||||
|
||||
it('body paragraphs without explicit pPr inherit buChar + marL/indent (entities decoded)', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: sldWith('<a:p><a:r><a:t>Financial results</a:t></a:r></a:p>'),
|
||||
ctx: { masterTextStyles: parseMasterTextStyles(masterXml) },
|
||||
})
|
||||
const p = (slide.elements[0] as any).text.paragraphs[0]
|
||||
expect(p.bullet).toEqual({ type: 'char', char: '•' })
|
||||
expect(p.marL).toBe(342900)
|
||||
expect(p.indent).toBe(-342900)
|
||||
})
|
||||
|
||||
it('explicit buNone overrides master inheritance', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: sldWith('<a:p><a:pPr><a:buNone/></a:pPr><a:r><a:t>No bullet</a:t></a:r></a:p>'),
|
||||
ctx: { masterTextStyles: parseMasterTextStyles(masterXml) },
|
||||
})
|
||||
expect((slide.elements[0] as any).text.paragraphs[0].bullet.type).toBe('none')
|
||||
})
|
||||
})
|
||||
|
||||
describe('line/paragraph spacing inheritance (lstStyle → paragraph) + spcPct paragraph spacing', () => {
|
||||
const slideWith = (bodyShapes: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${bodyShapes}</p:spTree></p:cSld></p:sld>`
|
||||
const spWith = (txBody: string) =>
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
`<p:txBody><a:bodyPr/>${txBody}</p:txBody></p:sp>`
|
||||
const LST =
|
||||
'<a:lstStyle><a:lvl1pPr>' +
|
||||
'<a:lnSpc><a:spcPct val="90000"/></a:lnSpc>' +
|
||||
'<a:spcBef><a:spcPct val="50000"/></a:spcBef>' +
|
||||
'<a:spcAft><a:spcPts val="300"/></a:spcAft>' +
|
||||
'</a:lvl1pPr></a:lstStyle>'
|
||||
const firstText = (slide: ReturnType<typeof parseSlide>) => (slide.elements[0] as any).text
|
||||
|
||||
it('spcPct before/after spacing parses into percentage fields', () => {
|
||||
const pPr =
|
||||
'<a:pPr><a:spcBef><a:spcPct val="50000"/></a:spcBef><a:spcAft><a:spcPct val="20000"/></a:spcAft></a:pPr>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(spWith(`<a:p>${pPr}<a:r><a:t>x</a:t></a:r></a:p>`)),
|
||||
ctx: {},
|
||||
})
|
||||
const p = firstText(slide).paragraphs[0]
|
||||
expect(p.spaceBeforePct).toBe(50)
|
||||
expect(p.spaceAfterPct).toBe(20)
|
||||
expect(p.spaceBefore).toBeUndefined()
|
||||
})
|
||||
|
||||
it('line/paragraph spacing inherited from lstStyle when there is no explicit pPr', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(spWith(`${LST}<a:p><a:r><a:t>x</a:t></a:r></a:p>`)),
|
||||
ctx: {},
|
||||
})
|
||||
const p = firstText(slide).paragraphs[0]
|
||||
expect(p.lineHeight).toBe(90)
|
||||
expect(p.spaceBeforePct).toBe(50)
|
||||
expect(p.spaceAfter).toBe(3)
|
||||
})
|
||||
|
||||
it('explicit lnSpc overrides inheritance wholesale (no mixing with inherited pct/pts)', () => {
|
||||
const pPr = '<a:pPr><a:lnSpc><a:spcPts val="2400"/></a:lnSpc></a:pPr>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(spWith(`${LST}<a:p>${pPr}<a:r><a:t>x</a:t></a:r></a:p>`)),
|
||||
ctx: {},
|
||||
})
|
||||
const p = firstText(slide).paragraphs[0]
|
||||
expect(p.lineExact).toBe(24)
|
||||
expect(p.lineHeight).toBeUndefined() // don't mix in lstStyle's 90%
|
||||
expect(p.spaceBeforePct).toBe(50) // non-overridden paragraph spacing still inherited
|
||||
})
|
||||
})
|
||||
|
||||
describe('master txStyles paragraph spacing inheritance (real template fixture)', () => {
|
||||
it('body-family placeholders inherit bodyStyle spcBef 20%, title family is explicit 0', async () => {
|
||||
const { openPptx } = await import('../src/index')
|
||||
const { readFileSync } = await import('node:fs')
|
||||
const { fileURLToPath } = await import('node:url')
|
||||
const { dirname, join } = await import('node:path')
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const opened = await openPptx(readFileSync(join(here, 'fixtures', '01_standard_business.pptx')))
|
||||
const byPh = (ph: string) => {
|
||||
for (const s of opened.deck.slides)
|
||||
for (const el of s.elements) {
|
||||
const e = el as any
|
||||
if (e.placeholder === ph && e.text?.paragraphs?.length) return e.text.paragraphs[0]
|
||||
}
|
||||
return null
|
||||
}
|
||||
expect(byPh('subTitle')?.spaceBeforePct).toBe(20)
|
||||
expect(byPh('ctrTitle')?.spaceBeforePct).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,236 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import JSZip from 'jszip'
|
||||
import {
|
||||
openPptx,
|
||||
savePptx,
|
||||
patchSlideXml,
|
||||
patchTextElementXml,
|
||||
setElementFont,
|
||||
addTable,
|
||||
editTableCellText,
|
||||
} from '../src/index'
|
||||
import type { TextElement, TableElement } from '../src/types'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
function firstTextEl(els: any[]): TextElement {
|
||||
return els.find(
|
||||
(e) => (e.type === 'text' || e.type === 'shape') && e.text?.paragraphs?.length,
|
||||
) as TextElement
|
||||
}
|
||||
|
||||
describe('Phase 3.3 element-patch save', () => {
|
||||
it('no dirty → slide XML byte-identical (fidelity preserved)', async () => {
|
||||
const original = fx('01_standard_business.pptx')
|
||||
const opened = await openPptx(original)
|
||||
const out = await savePptx(opened)
|
||||
const origZip = await JSZip.loadAsync(original)
|
||||
const outZip = await JSZip.loadAsync(out)
|
||||
for (const slide of opened.deck.slides) {
|
||||
const a = await origZip.file(slide.path)!.async('uint8array')
|
||||
const b = await outZip.file(slide.path)!.async('uint8array')
|
||||
expect(Buffer.from(b).equals(Buffer.from(a))).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('patchSlideXml with no dirty == originalXml', async () => {
|
||||
const { deck } = await openPptx(fx('01_standard_business.pptx'))
|
||||
for (const slide of deck.slides) {
|
||||
expect(patchSlideXml(slide)).toBe(slide.originalXml)
|
||||
}
|
||||
})
|
||||
|
||||
it('editing text content: new text lands, other bytes intact', async () => {
|
||||
const { deck } = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = deck.slides.find((s) => firstTextEl(s.elements))!
|
||||
const el = firstTextEl(slide.elements)
|
||||
const _oldText = el
|
||||
.text!.paragraphs.flatMap((p) => p.runs)
|
||||
.map((r) => r.text)
|
||||
.join('')
|
||||
// Change the first run's text
|
||||
el.text!.paragraphs[0]!.runs[0]!.text = 'PATCHED_TITLE_TEXT'
|
||||
el.dirty = true
|
||||
|
||||
const rebuilt = patchSlideXml(slide)
|
||||
expect(rebuilt).toContain('PATCHED_TITLE_TEXT')
|
||||
// bodyPrefix (spTree open + nvGrpSpPr) kept as-is
|
||||
expect(rebuilt.startsWith(slide.bodyPrefix)).toBe(true)
|
||||
expect(rebuilt.endsWith(slide.bodySuffix)).toBe(true)
|
||||
// Original bytes of other unchanged elements still present
|
||||
const otherEl = slide.elements.find((e) => e !== el && e.anchor.originalXml.length > 20)
|
||||
if (otherEl) expect(rebuilt).toContain(otherEl.anchor.originalXml)
|
||||
})
|
||||
|
||||
it('escapes XML special chars in edited text', () => {
|
||||
const el = {
|
||||
type: 'text',
|
||||
text: { paragraphs: [{ runs: [{ text: '<b>&"x"</b>' }] }] },
|
||||
} as unknown as TextElement
|
||||
const original =
|
||||
'<p:sp><p:txBody><a:p><a:r><a:rPr/><a:t>old</a:t></a:r></a:p></p:txBody></p:sp>'
|
||||
const out = patchTextElementXml(el, original)
|
||||
expect(out).toContain('<b>&"x"</b>')
|
||||
expect(out).not.toContain('<b>&"x"</b>')
|
||||
})
|
||||
|
||||
it('text patch keeps bodyPr vert bytes (vertical-text edit round-trip lossless)', () => {
|
||||
const bodyPr = '<a:bodyPr vert="eaVert" wrap="none"/>'
|
||||
const original = `<p:sp><p:txBody>${bodyPr}<a:p><a:r><a:rPr/><a:t>旧</a:t></a:r></a:p></p:txBody></p:sp>`
|
||||
// In-place patch path (paragraph count unchanged)
|
||||
const el1 = {
|
||||
type: 'text',
|
||||
text: { paragraphs: [{ runs: [{ text: '新しい縦書き' }] }] },
|
||||
} as unknown as TextElement
|
||||
const out1 = patchTextElementXml(el1, original)
|
||||
expect(out1).toContain(bodyPr)
|
||||
expect(out1).toContain('新しい縦書き')
|
||||
// Structural change → rebuild-txBody path (original bodyPr bytes still kept)
|
||||
const el2 = {
|
||||
type: 'text',
|
||||
text: { paragraphs: [{ runs: [{ text: '一段目' }] }, { runs: [{ text: '二段目' }] }] },
|
||||
} as unknown as TextElement
|
||||
const out2 = patchTextElementXml(el2, original)
|
||||
expect(out2).toContain(bodyPr)
|
||||
expect(out2).toContain('二段目')
|
||||
})
|
||||
|
||||
it('formatting patch: bold + size + color on existing rPr', () => {
|
||||
const el = {
|
||||
type: 'text',
|
||||
text: {
|
||||
paragraphs: [{ runs: [{ text: 'hi', bold: true, fontSize: 24, color: '#FF0000' }] }],
|
||||
},
|
||||
} as unknown as TextElement
|
||||
const original =
|
||||
'<p:sp><p:txBody><a:p><a:r><a:rPr lang="en-US" sz="1800"/><a:t>hi</a:t></a:r></a:p></p:txBody></p:sp>'
|
||||
const out = patchTextElementXml(el, original)
|
||||
expect(out).toContain('sz="2400"') // 24pt
|
||||
expect(out).toMatch(/b="1"/)
|
||||
expect(out).toContain('srgbClr val="FF0000"')
|
||||
expect(out).toContain('<a:t>hi</a:t>')
|
||||
// Original lang attribute kept
|
||||
expect(out).toContain('lang="en-US"')
|
||||
})
|
||||
|
||||
it('injects rPr when run had none', () => {
|
||||
const el = {
|
||||
type: 'text',
|
||||
text: { paragraphs: [{ runs: [{ text: 'x', bold: true, color: '#00FF00' }] }] },
|
||||
} as unknown as TextElement
|
||||
const original = '<p:sp><p:txBody><a:p><a:r><a:t>x</a:t></a:r></a:p></p:txBody></p:sp>'
|
||||
const out = patchTextElementXml(el, original)
|
||||
expect(out).toContain('<a:rPr')
|
||||
expect(out).toMatch(/b="1"/)
|
||||
expect(out).toContain('srgbClr val="00FF00"')
|
||||
})
|
||||
|
||||
it('structural rebuild path when run count changes', () => {
|
||||
const el = {
|
||||
type: 'text',
|
||||
text: {
|
||||
paragraphs: [{ runs: [{ text: 'A' }, { text: 'B' }] }], // 2 runs vs 1 original
|
||||
},
|
||||
} as unknown as TextElement
|
||||
const original =
|
||||
'<p:sp><p:spPr/><p:txBody><a:bodyPr wrap="square"/><a:lstStyle/><a:p><a:r><a:rPr/><a:t>orig</a:t></a:r></a:p></p:txBody></p:sp>'
|
||||
const out = patchTextElementXml(el, original)
|
||||
// bodyPr kept as-is
|
||||
expect(out).toContain('<a:bodyPr wrap="square"/>')
|
||||
// Both new run texts present
|
||||
expect(out).toContain('<a:t>A</a:t>')
|
||||
expect(out).toContain('<a:t>B</a:t>')
|
||||
// Old text has been replaced
|
||||
expect(out).not.toContain('orig')
|
||||
})
|
||||
|
||||
it('full save roundtrip after edit: file opens again with new text', async () => {
|
||||
const { deck } = await openPptx(fx('05_unicode_cjk_emoji.pptx'))
|
||||
const slide = deck.slides.find((s) => firstTextEl(s.elements))!
|
||||
const el = firstTextEl(slide.elements)
|
||||
el.text!.paragraphs[0]!.runs[0]!.text = '编辑后的标题ABC'
|
||||
el.dirty = true
|
||||
const opened = { deck, archive: (await openPptx(fx('05_unicode_cjk_emoji.pptx'))).archive }
|
||||
// Save with the same deck (archive only supplies the other entries' bytes)
|
||||
const out = await savePptx({ deck, archive: opened.archive })
|
||||
// Reopen the output and confirm the new text parses back
|
||||
const reopened = await openPptx(out)
|
||||
const text = reopened.deck.slides
|
||||
.flatMap((s) => s.elements)
|
||||
.filter((e: any) => e.type === 'text' || e.type === 'shape')
|
||||
.flatMap((e: any) => e.text?.paragraphs ?? [])
|
||||
.flatMap((p: any) => p.runs)
|
||||
.map((r: any) => r.text)
|
||||
.join('')
|
||||
expect(text).toContain('编辑后的标题ABC')
|
||||
})
|
||||
})
|
||||
|
||||
describe('setElementFont (change font family/size for a whole selected element)', () => {
|
||||
it('text/shape: all runs get family+size, dirty set, XML regenerates', async () => {
|
||||
const { deck } = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = deck.slides.find((s) => firstTextEl(s.elements))!
|
||||
const el = firstTextEl(slide.elements)
|
||||
expect(setElementFont(slide, el.id, { fontFamily: 'Noto Sans SC', fontSizePt: 20 })).toBe(true)
|
||||
for (const p of el.text!.paragraphs)
|
||||
for (const r of p.runs) {
|
||||
expect(r.fontFamily).toBe('Noto Sans SC')
|
||||
expect(r.fontSize).toBe(20)
|
||||
}
|
||||
expect(el.dirty).toBe(true)
|
||||
const rebuilt = patchSlideXml(slide)
|
||||
expect(rebuilt).toContain('typeface="Noto Sans SC"')
|
||||
expect(rebuilt).toContain('sz="2000"')
|
||||
})
|
||||
|
||||
it('only family: size untouched; unknown/no-text element returns false', async () => {
|
||||
const { deck } = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = deck.slides.find((s) => firstTextEl(s.elements))!
|
||||
const el = firstTextEl(slide.elements)
|
||||
const sizeBefore = el.text!.paragraphs[0]!.runs[0]!.fontSize
|
||||
expect(setElementFont(slide, el.id, { fontFamily: 'Arial' })).toBe(true)
|
||||
expect(el.text!.paragraphs[0]!.runs[0]!.fontSize).toBe(sizeBefore)
|
||||
expect(setElementFont(slide, 'no-such-id', { fontFamily: 'Arial' })).toBe(false)
|
||||
const pic = slide.elements.find((e) => e.type === 'picture')
|
||||
if (pic) expect(setElementFont(slide, pic.id, { fontFamily: 'Arial' })).toBe(false)
|
||||
})
|
||||
|
||||
it('table: sizes cells with text and leaves a persisted marker on empty cells (#205)', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addTable(opened, 0, {
|
||||
rows: 2,
|
||||
cols: 2,
|
||||
offset: { x: 0, y: 0, cx: 1905000, cy: 952500 },
|
||||
})!
|
||||
editTableCellText(r.slide, r.elementId, 0, 0, [{ runs: [{ text: 'Hello' }] }])
|
||||
expect(setElementFont(r.slide, r.elementId, { fontSizePt: 14 })).toBe(true)
|
||||
|
||||
const tbl = r.slide.elements.find((e) => e.id === r.elementId) as TableElement
|
||||
expect(tbl.rows[0]![0]!.text!.paragraphs[0]!.runs[0]!.fontSize).toBe(14)
|
||||
// Empty cell got a textless marker run carrying the size
|
||||
const marker = tbl.rows[0]![1]!.text!.paragraphs[0]!.runs[0]!
|
||||
expect(marker.text).toBe('')
|
||||
expect(marker.fontSize).toBe(14)
|
||||
// sz persisted for every cell (4 cells; the texty cell's run + 3 markers)
|
||||
expect(tbl.anchor.originalXml.match(/sz="1400"/g)?.length).toBe(4)
|
||||
|
||||
// Marker survives save/reopen
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const tbl2 = reopened.deck.slides[0]!.elements.find((e) => e.type === 'table') as TableElement
|
||||
expect(tbl2.rows[0]![1]!.text!.paragraphs[0]!.runs[0]!.fontSize).toBe(14)
|
||||
})
|
||||
|
||||
it('table with only empty cells still reports a change (#205)', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addTable(opened, 0, {
|
||||
rows: 2,
|
||||
cols: 2,
|
||||
offset: { x: 0, y: 0, cx: 1905000, cy: 952500 },
|
||||
})!
|
||||
expect(setElementFont(r.slide, r.elementId, { fontSizePt: 14 })).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,189 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import JSZip from 'jszip'
|
||||
import {
|
||||
openPptx,
|
||||
savePptx,
|
||||
addElement,
|
||||
addPicture,
|
||||
createBlankPptx,
|
||||
patchElementStroke,
|
||||
setSlideBackground,
|
||||
} from '../src/index'
|
||||
import type { PictureElement, TextElement } from '../src/types'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const OFF = { x: 914400, y: 914400, cx: 1828800, cy: 914400 }
|
||||
|
||||
// 1x1 red PNG
|
||||
const PNG_1PX = Uint8Array.from(
|
||||
Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
|
||||
'base64',
|
||||
),
|
||||
)
|
||||
|
||||
describe('addPicture', () => {
|
||||
it('media/rels/content-types all land and survive save → reopen', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addPicture(opened, slide, { bytes: PNG_1PX, ext: 'png', offset: { ...OFF } })
|
||||
expect(el).not.toBeNull()
|
||||
expect(el!.mediaRef).toBe('ppt/media/image1.png')
|
||||
|
||||
const out = await savePptx(opened)
|
||||
const zip = await JSZip.loadAsync(out)
|
||||
expect(zip.file('ppt/media/image1.png')).not.toBeNull()
|
||||
expect(await zip.file('[Content_Types].xml')!.async('string')).toContain('Extension="png"')
|
||||
|
||||
const reopened = await openPptx(out)
|
||||
const pic = reopened.deck.slides[0]!.elements.find(
|
||||
(e) => e.type === 'picture',
|
||||
) as PictureElement
|
||||
expect(pic).toBeDefined()
|
||||
expect(pic.mediaRef).toBe('ppt/media/image1.png')
|
||||
expect(pic.transform.offset).toEqual(OFF)
|
||||
})
|
||||
|
||||
it('second picture gets image2 and a distinct rId', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
addPicture(opened, slide, { bytes: PNG_1PX, ext: 'png', offset: { ...OFF } })
|
||||
const b = addPicture(opened, slide, { bytes: PNG_1PX, ext: 'png', offset: { ...OFF } })
|
||||
expect(b!.mediaRef).toBe('ppt/media/image2.png')
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const pics = reopened.deck.slides[0]!.elements.filter((e) => e.type === 'picture')
|
||||
expect(pics.length).toBe(2)
|
||||
expect(new Set(pics.map((p) => (p as PictureElement).mediaRef)).size).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('patchElementStroke', () => {
|
||||
it('stroke color+width round-trips through save → reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, { kind: 'rect', offset: { ...OFF }, fillColor: '#112233' })
|
||||
el.stroke = { fill: { type: 'solid', color: '#C43E1C' }, width: 3 * 12700 }
|
||||
el.dirtyStroke = true
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2 = reopened.deck.slides[0]!.elements.at(-1) as TextElement
|
||||
expect(el2.stroke?.fill).toEqual({ type: 'solid', color: '#C43E1C' })
|
||||
expect(el2.stroke?.width).toBe(3 * 12700)
|
||||
})
|
||||
|
||||
it('null stroke writes explicit noFill, keeping other ln bytes', () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:ln w="12700"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln></p:spPr></p:sp>'
|
||||
const out = patchElementStroke(xml, null)
|
||||
expect(out).toContain('<a:ln w="12700"><a:noFill/></a:ln>')
|
||||
})
|
||||
|
||||
it('keeps dash/arrows/cap/cmpd when only color+width change', () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:prstGeom prst="line"><a:avLst/></a:prstGeom>' +
|
||||
'<a:ln w="9525" cap="rnd" cmpd="dbl" algn="ctr">' +
|
||||
'<a:solidFill><a:srgbClr val="000000"/></a:solidFill>' +
|
||||
'<a:prstDash val="dash"/><a:round/>' +
|
||||
'<a:headEnd type="oval" w="med" len="med"/><a:tailEnd type="arrow" w="lg" len="lg"/>' +
|
||||
'</a:ln></p:spPr></p:sp>'
|
||||
const out = patchElementStroke(xml, { color: '#C43E1C', widthEmu: 25400 })
|
||||
expect(out).toContain('<a:ln w="25400" cap="rnd" cmpd="dbl" algn="ctr">')
|
||||
expect(out).toContain('<a:solidFill><a:srgbClr val="C43E1C"/></a:solidFill>')
|
||||
expect(out).toContain('<a:prstDash val="dash"/><a:round/>')
|
||||
expect(out).toContain('<a:headEnd type="oval" w="med" len="med"/>')
|
||||
expect(out).toContain('<a:tailEnd type="arrow" w="lg" len="lg"/>')
|
||||
expect(out).not.toContain('val="000000"')
|
||||
})
|
||||
|
||||
it('patches a self-closing <a:ln/> and a ln without w attribute', () => {
|
||||
const selfClosed = '<p:sp><p:spPr><a:ln cap="sq"/></p:spPr></p:sp>'
|
||||
const out1 = patchElementStroke(selfClosed, { color: '#112233', widthEmu: 12700 })
|
||||
expect(out1).toContain(
|
||||
'<a:ln w="12700" cap="sq"><a:solidFill><a:srgbClr val="112233"/></a:solidFill></a:ln>',
|
||||
)
|
||||
|
||||
const noW = '<p:sp><p:spPr><a:ln><a:prstDash val="sysDot"/></a:ln></p:spPr></p:sp>'
|
||||
const out2 = patchElementStroke(noW, { color: '#445566', widthEmu: 19050 })
|
||||
expect(out2).toContain('<a:ln w="19050">')
|
||||
// fill is inserted before prstDash (CT_LineProperties sequence)
|
||||
expect(out2).toContain(
|
||||
'<a:solidFill><a:srgbClr val="445566"/></a:solidFill><a:prstDash val="sysDot"/>',
|
||||
)
|
||||
})
|
||||
|
||||
it('gradient line fill is replaced, dash preserved', () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:ln w="9525">' +
|
||||
'<a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs></a:gsLst></a:gradFill>' +
|
||||
'<a:prstDash val="lgDash"/></a:ln></p:spPr></p:sp>'
|
||||
const out = patchElementStroke(xml, { color: '#00FF00', widthEmu: 9525 })
|
||||
expect(out).toContain(
|
||||
'<a:solidFill><a:srgbClr val="00FF00"/></a:solidFill><a:prstDash val="lgDash"/>',
|
||||
)
|
||||
expect(out).not.toContain('gradFill')
|
||||
})
|
||||
|
||||
it('dash preset writes <a:prstDash> after the fill, replacing an existing one', () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:ln w="9525">' +
|
||||
'<a:solidFill><a:srgbClr val="000000"/></a:solidFill>' +
|
||||
'<a:prstDash val="lgDash"/><a:headEnd type="oval"/></a:ln></p:spPr></p:sp>'
|
||||
const out = patchElementStroke(xml, { color: '#C00000', widthEmu: 19050, dash: 'sysDot' })
|
||||
expect(out).toContain(
|
||||
'<a:solidFill><a:srgbClr val="C00000"/></a:solidFill><a:prstDash val="sysDot"/><a:headEnd type="oval"/>',
|
||||
)
|
||||
expect(out).not.toContain('lgDash')
|
||||
})
|
||||
|
||||
it("dash 'solid' removes the prstDash node; missing ln gets one with a dash", () => {
|
||||
const xml =
|
||||
'<p:sp><p:spPr><a:ln w="9525"><a:solidFill><a:srgbClr val="000000"/></a:solidFill><a:prstDash val="dash"/></a:ln></p:spPr></p:sp>'
|
||||
const out = patchElementStroke(xml, { color: '#000000', widthEmu: 9525, dash: 'solid' })
|
||||
expect(out).not.toContain('prstDash')
|
||||
|
||||
const bare = '<p:sp><p:spPr><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:sp>'
|
||||
const out2 = patchElementStroke(bare, { color: '#C00000', widthEmu: 19050, dash: 'sysDot' })
|
||||
expect(out2).toContain(
|
||||
'<a:ln w="19050"><a:solidFill><a:srgbClr val="C00000"/></a:solidFill><a:prstDash val="sysDot"/></a:ln>',
|
||||
)
|
||||
})
|
||||
|
||||
it('stroke dash round-trips through save → reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, { kind: 'rect', offset: { ...OFF }, fillColor: '#112233' })
|
||||
el.stroke = { fill: { type: 'solid', color: '#C43E1C' }, width: 19050, dash: 'sysDot' }
|
||||
el.dirtyStroke = true
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2 = reopened.deck.slides[0]!.elements.at(-1) as TextElement
|
||||
expect(el2.stroke?.dash).toBe('sysDot')
|
||||
})
|
||||
})
|
||||
|
||||
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')
|
||||
expect(opened.deck.slides[0]!.background).toEqual({ type: 'solid', color: '#1A2B3C' })
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides[0]!.background).toEqual({ type: 'solid', color: '#1A2B3C' })
|
||||
})
|
||||
|
||||
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')
|
||||
expect((slide.bodyPrefix.match(/<p:bg>/g) ?? []).length).toBe(1)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides[0]!.background).toEqual({ type: 'solid', color: '#222222' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Picture crop (srcRect) tests:
|
||||
* 1. patchPictureSrcRect unit tests (patch correctly written / removed / repeated round-trips).
|
||||
* 2. editPictureSrcRect + savePptx roundtrip: pictures whose crop changed get srcRect written;
|
||||
* bytes of other unchanged elements stay fully untouched.
|
||||
* 3. With no crop at all, srcRect does not appear in the output.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { patchPictureSrcRect } from '../src/generate'
|
||||
import { openPptx, savePptx, editPictureSrcRect } from '../src/index'
|
||||
import JSZip from 'jszip'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
// ── Unit tests: patchPictureSrcRect ─────────────────────────────────────────
|
||||
|
||||
const PIC_XML_NO_SRCRECT = `<p:pic><p:nvPicPr><p:cNvPr id="3" name="img"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr><p:blipFill><a:blip r:embed="rId2"/><a:stretch><a:fillRect/></a:stretch></p:blipFill><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="9144000" cy="6858000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>`
|
||||
|
||||
const PIC_XML_WITH_SRCRECT = `<p:pic><p:nvPicPr><p:cNvPr id="3" name="img"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr><p:blipFill><a:blip r:embed="rId2"/><a:srcRect l="10000" t="5000" r="10000" b="5000"/><a:stretch><a:fillRect/></a:stretch></p:blipFill><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="9144000" cy="6858000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>`
|
||||
|
||||
describe('parsePicture presetGeometry (picture styles)', () => {
|
||||
const slideWith = (body: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${body}</p:spTree></p:cSld></p:sld>`
|
||||
const picWithGeom = (geom: string) =>
|
||||
PIC_XML_NO_SRCRECT.replace('<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>', geom)
|
||||
|
||||
it('ellipse geometry parses into presetGeometry; rect is the default and not recorded', async () => {
|
||||
const { parseSlide } = await import('../src/parse')
|
||||
const withEllipse = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(picWithGeom('<a:prstGeom prst="ellipse"><a:avLst/></a:prstGeom>')),
|
||||
ctx: {},
|
||||
})
|
||||
expect((withEllipse.elements[0] as any).presetGeometry).toBe('ellipse')
|
||||
|
||||
const withRect = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(PIC_XML_NO_SRCRECT), ctx: {} })
|
||||
expect((withRect.elements[0] as any).presetGeometry).toBeUndefined()
|
||||
})
|
||||
|
||||
it('roundRect adj adjustment values are parsed along with the geometry', async () => {
|
||||
const { parseSlide } = await import('../src/parse')
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(
|
||||
picWithGeom('<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 25000"/></a:avLst></a:prstGeom>'),
|
||||
),
|
||||
ctx: {},
|
||||
})
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.presetGeometry).toBe('roundRect')
|
||||
expect(el.adjust).toEqual({ adj: 25000 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('patchPictureSrcRect - unit', () => {
|
||||
it('inserts srcRect after <a:blip> when not present', () => {
|
||||
const result = patchPictureSrcRect(PIC_XML_NO_SRCRECT, { l: 0.1, t: 0.05, r: 0.1, b: 0.05 })
|
||||
expect(result).toContain('<a:srcRect l="10000" t="5000" r="10000" b="5000"/>')
|
||||
// blip should still be there
|
||||
expect(result).toContain('<a:blip r:embed="rId2"/>')
|
||||
})
|
||||
|
||||
it('replaces existing srcRect', () => {
|
||||
const result = patchPictureSrcRect(PIC_XML_WITH_SRCRECT, { l: 0.2, t: 0, r: 0, b: 0.3 })
|
||||
expect(result).toContain('<a:srcRect l="20000" b="30000"/>')
|
||||
// old srcRect gone
|
||||
expect(result).not.toContain('l="10000"')
|
||||
})
|
||||
|
||||
it('removes srcRect when null', () => {
|
||||
const result = patchPictureSrcRect(PIC_XML_WITH_SRCRECT, null)
|
||||
expect(result).not.toContain('<a:srcRect')
|
||||
})
|
||||
|
||||
it('roundtrip: set then clear leaves original byte structure', () => {
|
||||
const withCrop = patchPictureSrcRect(PIC_XML_NO_SRCRECT, { l: 0.1, t: 0.1, r: 0.1, b: 0.1 })
|
||||
const cleared = patchPictureSrcRect(withCrop, null)
|
||||
// No srcRect left
|
||||
expect(cleared).not.toContain('<a:srcRect')
|
||||
// blip still intact
|
||||
expect(cleared).toContain('<a:blip r:embed="rId2"/>')
|
||||
// stretch still intact
|
||||
expect(cleared).toContain('<a:stretch><a:fillRect/></a:stretch>')
|
||||
})
|
||||
|
||||
it('skips zero values in attributes', () => {
|
||||
const result = patchPictureSrcRect(PIC_XML_NO_SRCRECT, { l: 0, t: 0.1, r: 0, b: 0 })
|
||||
// l/r/b are zero → omitted
|
||||
expect(result).toContain('<a:srcRect t="10000"/>')
|
||||
expect(result).not.toContain('l="0"')
|
||||
})
|
||||
|
||||
it('null srcRect on xml with no srcRect is no-op', () => {
|
||||
const result = patchPictureSrcRect(PIC_XML_NO_SRCRECT, null)
|
||||
expect(result).toBe(PIC_XML_NO_SRCRECT)
|
||||
})
|
||||
})
|
||||
|
||||
// ── Integration tests: editPictureSrcRect + savePptx ───────────────────────
|
||||
|
||||
describe('editPictureSrcRect + savePptx roundtrip', () => {
|
||||
it('roundtrip: no picture edits → slides byte-identical (fidelity)', async () => {
|
||||
const original = fx('01_standard_business.pptx')
|
||||
const opened = await openPptx(original)
|
||||
const out = await savePptx(opened)
|
||||
const origZip = await JSZip.loadAsync(original)
|
||||
const outZip = await JSZip.loadAsync(out)
|
||||
for (const slide of opened.deck.slides) {
|
||||
const a = await origZip.file(slide.path)!.async('uint8array')
|
||||
const b = await outZip.file(slide.path)!.async('uint8array')
|
||||
expect(Buffer.from(b).equals(Buffer.from(a))).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('editPictureSrcRect sets srcRect and marks dirtySrcRect', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
// Find the first picture element
|
||||
let picId: string | undefined
|
||||
let slideIdx = 0
|
||||
for (let i = 0; i < opened.deck.slides.length; i++) {
|
||||
const pic = opened.deck.slides[i]!.elements.find((e) => e.type === 'picture')
|
||||
if (pic) { picId = pic.id; slideIdx = i; break }
|
||||
}
|
||||
if (!picId) {
|
||||
// Pass directly if the standard business pptx has no pictures (test fixtures cover the base case)
|
||||
return
|
||||
}
|
||||
const slide = opened.deck.slides[slideIdx]!
|
||||
const ok = editPictureSrcRect(slide, picId, { l: 0.1, t: 0.1, r: 0.1, b: 0.1 })
|
||||
expect(ok).toBe(true)
|
||||
const pic = slide.elements.find((e) => e.id === picId)!
|
||||
expect(pic.dirtySrcRect).toBe(true)
|
||||
// srcRect written after save
|
||||
const out = await savePptx(opened)
|
||||
const outZip = await JSZip.loadAsync(out)
|
||||
const xml = await outZip.file(slide.path)!.async('string')
|
||||
expect(xml).toContain('<a:srcRect')
|
||||
})
|
||||
|
||||
it('editPictureSrcRect with null removes srcRect', async () => {
|
||||
// Set first, then clear
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
let picId: string | undefined
|
||||
let slideIdx = 0
|
||||
for (let i = 0; i < opened.deck.slides.length; i++) {
|
||||
const pic = opened.deck.slides[i]!.elements.find((e) => e.type === 'picture')
|
||||
if (pic) { picId = pic.id; slideIdx = i; break }
|
||||
}
|
||||
if (!picId) return
|
||||
const slide = opened.deck.slides[slideIdx]!
|
||||
// Write first, then clear
|
||||
editPictureSrcRect(slide, picId, { l: 0.1, t: 0.1, r: 0.1, b: 0.1 })
|
||||
editPictureSrcRect(slide, picId, null)
|
||||
const pic = slide.elements.find((e) => e.id === picId)!
|
||||
expect(pic.dirtySrcRect).toBe(true)
|
||||
const out = await savePptx(opened)
|
||||
const outZip = await JSZip.loadAsync(out)
|
||||
const xml = await outZip.file(slide.path)!.async('string')
|
||||
// After clearing, no srcRect (an empty <a:srcRect/> tag may appear, but never one with attributes)
|
||||
expect(xml).not.toMatch(/<a:srcRect [^/]/)
|
||||
})
|
||||
|
||||
it('returns false for non-existent or non-picture element', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
expect(editPictureSrcRect(slide, 'nonexistent_id', { l: 0.1, t: 0.1, r: 0, b: 0 })).toBe(false)
|
||||
// text element
|
||||
const textEl = slide.elements.find((e) => e.type === 'text' || e.type === 'shape')
|
||||
if (textEl) {
|
||||
expect(editPictureSrcRect(slide, textEl.id, { l: 0.1, t: 0.1, r: 0, b: 0 })).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,60 @@
|
||||
/** Picture opacity: alphaModFix parsing + byte-surgery write-back. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { setPictureOpacity } from '../src/index'
|
||||
import type { PictureElement } from '../src/types'
|
||||
|
||||
const slideWith = (inner: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${inner}</p:spTree></p:cSld></p:sld>`
|
||||
const pic = (blip: string) =>
|
||||
'<p:pic><p:nvPicPr><p:cNvPr id="7" name="P"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>' +
|
||||
`<p:blipFill>${blip}<a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr></p:pic>'
|
||||
|
||||
const parseOne = (blip: string) =>
|
||||
parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(pic(blip)), ctx: {} })
|
||||
|
||||
describe('picture opacity', () => {
|
||||
it('parses alphaModFix → opacity', () => {
|
||||
const slide = parseOne('<a:blip r:embed="rId2"><a:alphaModFix amt="40000"/></a:blip>')
|
||||
const el = slide.elements[0] as PictureElement
|
||||
expect(el.opacity).toBeCloseTo(0.4)
|
||||
})
|
||||
|
||||
it('setting opacity: self-closing blip expanded for injection; restoring 1 removes the marker', () => {
|
||||
const slide = parseOne('<a:blip r:embed="rId2"/>')
|
||||
const el = slide.elements[0] as PictureElement
|
||||
expect(setPictureOpacity(slide, el.id, 0.35)).toBe(true)
|
||||
expect(el.anchor.originalXml).toContain(
|
||||
'<a:blip r:embed="rId2"><a:alphaModFix amt="35000"/></a:blip>',
|
||||
)
|
||||
expect(el.opacity).toBeCloseTo(0.35)
|
||||
expect(setPictureOpacity(slide, el.id, 1)).toBe(true)
|
||||
expect(el.anchor.originalXml).not.toContain('alphaModFix')
|
||||
expect(el.opacity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('existing alphaModFix is replaced, not stacked', () => {
|
||||
const slide = parseOne('<a:blip r:embed="rId2"><a:alphaModFix amt="40000"/></a:blip>')
|
||||
const el = slide.elements[0] as PictureElement
|
||||
setPictureOpacity(slide, el.id, 0.8)
|
||||
const hits = el.anchor.originalXml.match(/alphaModFix/g) ?? []
|
||||
expect(hits.length).toBe(1)
|
||||
expect(el.anchor.originalXml).toContain('amt="80000"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('picture softEdge', () => {
|
||||
it('parses a:softEdge rad → PictureElement.softEdge', () => {
|
||||
const slideXml =
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/>' +
|
||||
'<p:pic><p:nvPicPr><p:cNvPr id="7" name="P"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>' +
|
||||
'<p:blipFill><a:blip r:embed="rId2"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm>' +
|
||||
'<a:effectLst><a:softEdge rad="63500"/></a:effectLst></p:spPr></p:pic>' +
|
||||
'</p:spTree></p:cSld></p:sld>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml, ctx: {} })
|
||||
expect((slide.elements[0] as PictureElement).softEdge).toBe(63500)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
/** SVG-only pictures: <a:blip> without r:embed whose image is the asvg:svgBlip extension. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import type { PictureElement, TextElement } from '../src/types'
|
||||
|
||||
const SVG_EXT =
|
||||
'<a:extLst><a:ext uri="{96DAC541-7B7A-43D3-8B79-37D633B846F1}">' +
|
||||
'<asvg:svgBlip xmlns:asvg="http://schemas.microsoft.com/office/drawing/2016/SVG/main" r:embed="rId4"/>' +
|
||||
'</a:ext></a:extLst>'
|
||||
|
||||
const slideWith = (inner: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${inner}</p:spTree></p:cSld></p:sld>`
|
||||
const pic = (blip: string) =>
|
||||
'<p:pic><p:nvPicPr><p:cNvPr id="7" name="P"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>' +
|
||||
`<p:blipFill>${blip}<a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr></p:pic>'
|
||||
|
||||
const mediaRels = new Map([
|
||||
['rId2', 'ppt/media/image1.png'],
|
||||
['rId4', 'ppt/media/image2.svg'],
|
||||
])
|
||||
const parseOne = (inner: string) =>
|
||||
parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(inner), ctx: { mediaRels } })
|
||||
|
||||
describe('svgBlip fallback', () => {
|
||||
it('SVG-only picture (blip without r:embed) resolves media via asvg:svgBlip', () => {
|
||||
const slide = parseOne(pic(`<a:blip>${SVG_EXT}</a:blip>`))
|
||||
const el = slide.elements[0] as PictureElement
|
||||
expect(el.mediaRef).toBe('ppt/media/image2.svg')
|
||||
})
|
||||
|
||||
it('raster r:embed still wins when both are present', () => {
|
||||
const slide = parseOne(pic(`<a:blip r:embed="rId2">${SVG_EXT}</a:blip>`))
|
||||
const el = slide.elements[0] as PictureElement
|
||||
expect(el.mediaRef).toBe('ppt/media/image1.png')
|
||||
})
|
||||
|
||||
it('shape blipFill fill resolves media via asvg:svgBlip', () => {
|
||||
const shape =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="8" name="S"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm>' +
|
||||
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:blipFill><a:blip>${SVG_EXT}</a:blip><a:stretch/></a:blipFill></p:spPr>` +
|
||||
'<p:txBody><a:bodyPr/><a:p/></p:txBody></p:sp>'
|
||||
const slide = parseOne(shape)
|
||||
const el = slide.elements[0] as TextElement
|
||||
expect(el.fill).toEqual({ type: 'image', mediaRef: 'ppt/media/image2.svg', mode: 'stretch' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* Fidelity of the rebuildTxBody fallback path: on text-structure changes (run add/remove),
|
||||
* explicit paragraph properties (bullet/marL/indent/lnSpc/spcBef/spcAft) and run-level
|
||||
* hlinkClick/strike/cs are written back; display values inherited from lstStyle are not baked in.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { patchTextElementXml } from '../src/index'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
const slideWith = (sp: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${sp}</p:spTree></p:cSld></p:sld>`
|
||||
const spWith = (txBodyInner: string) =>
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
`<p:txBody>${txBodyInner}</p:txBody></p:sp>`
|
||||
|
||||
const parseEl = (txBodyInner: string) => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(spWith(txBodyInner)),
|
||||
ctx: {},
|
||||
})
|
||||
return slide.elements[0] as TextElement
|
||||
}
|
||||
|
||||
/** Append a run to trigger the structural rebuild path. */
|
||||
const forceRebuild = (el: TextElement) => {
|
||||
el.text!.paragraphs[el.text!.paragraphs.length - 1]!.runs.push({ text: ' added' })
|
||||
}
|
||||
|
||||
describe('rebuild path: explicit paragraph properties written back', () => {
|
||||
const PPR =
|
||||
'<a:pPr marL="342900" indent="-342900" algn="just">' +
|
||||
'<a:lnSpc><a:spcPct val="150000"/></a:lnSpc>' +
|
||||
'<a:spcBef><a:spcPts val="1200"/></a:spcBef>' +
|
||||
'<a:spcAft><a:spcPct val="50000"/></a:spcAft>' +
|
||||
'<a:buClr><a:srgbClr val="FF0000"/></a:buClr>' +
|
||||
'<a:buSzPct val="75000"/><a:buFont typeface="Wingdings"/>' +
|
||||
'<a:buChar char="v"/></a:pPr>'
|
||||
|
||||
it('bullet/indent/line spacing/paragraph spacing all preserved', () => {
|
||||
const el = parseEl(`<a:bodyPr/><a:p>${PPR}<a:r><a:t>x</a:t></a:r></a:p>`)
|
||||
const p = el.text!.paragraphs[0]!
|
||||
expect(p.bullet).toMatchObject({ type: 'char', char: 'v', font: 'Wingdings', sizePct: 75 })
|
||||
expect(p.marL).toBe(342900)
|
||||
expect(p.indent).toBe(-342900)
|
||||
forceRebuild(el)
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('marL="342900"')
|
||||
expect(out).toContain('indent="-342900"')
|
||||
expect(out).toContain('algn="just"')
|
||||
expect(out).toContain('<a:lnSpc><a:spcPct val="150000"/></a:lnSpc>')
|
||||
expect(out).toContain('<a:spcBef><a:spcPts val="1200"/></a:spcBef>')
|
||||
expect(out).toContain('<a:spcAft><a:spcPct val="50000"/></a:spcAft>')
|
||||
expect(out).toContain('<a:buClr><a:srgbClr val="FF0000"/></a:buClr>')
|
||||
expect(out).toContain('<a:buSzPct val="75000"/>')
|
||||
expect(out).toContain('<a:buFont typeface="Wingdings"/>')
|
||||
expect(out).toContain('<a:buChar char="v"/>')
|
||||
})
|
||||
|
||||
it('buAutoNum numbering format preserved', () => {
|
||||
const el = parseEl(
|
||||
'<a:bodyPr/><a:p><a:pPr><a:buAutoNum type="romanLcPeriod" startAt="3"/></a:pPr><a:r><a:t>x</a:t></a:r></a:p>',
|
||||
)
|
||||
forceRebuild(el)
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('<a:buAutoNum type="romanLcPeriod"/>')
|
||||
})
|
||||
|
||||
it('buNone preserved (explicitly turning off the inherited bullet)', () => {
|
||||
const el = parseEl('<a:bodyPr/><a:p><a:pPr><a:buNone/></a:pPr><a:r><a:t>x</a:t></a:r></a:p>')
|
||||
forceRebuild(el)
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('<a:buNone/>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('rebuild path: inherited values not materialized', () => {
|
||||
const LST =
|
||||
'<a:lstStyle><a:lvl1pPr marL="228600" algn="ctr"><a:buChar char="•"/>' +
|
||||
'<a:defRPr sz="2000"/></a:lvl1pPr></a:lstStyle>'
|
||||
|
||||
it('algn/buChar/marL/sz inherited from lstStyle are not written into <a:p>', () => {
|
||||
const el = parseEl(`<a:bodyPr/>${LST}<a:p><a:r><a:rPr/><a:t>x</a:t></a:r></a:p>`)
|
||||
const p = el.text!.paragraphs[0]!
|
||||
// Display values already merged (for rendering)
|
||||
expect(p.align).toBe('center')
|
||||
expect(p.bullet?.char).toBe('•')
|
||||
expect(p.runs[0]!.fontSize).toBe(20)
|
||||
expect(p.runs[0]!.fontSizeImplicit).toBe(true)
|
||||
forceRebuild(el)
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
// lstStyle kept as-is, but inherited values not materialized inside <a:p>
|
||||
const pStart = out.indexOf('<a:p>')
|
||||
const body = out.slice(pStart)
|
||||
expect(body).not.toContain('algn=')
|
||||
expect(body).not.toContain('buChar')
|
||||
expect(body).not.toContain('marL=')
|
||||
expect(body).not.toContain('sz=')
|
||||
})
|
||||
|
||||
it('inherited color writes no solidFill; explicit schemeClr materialized to keep visuals', () => {
|
||||
const el = parseEl(
|
||||
'<a:bodyPr/><a:p><a:r><a:rPr/><a:t>a</a:t></a:r>' +
|
||||
'<a:r><a:rPr><a:solidFill><a:schemeClr val="accent1"/></a:solidFill></a:rPr><a:t>b</a:t></a:r></a:p>',
|
||||
)
|
||||
const [r1, r2] = el.text!.paragraphs[0]!.runs
|
||||
expect(r1!.colorInherited ?? false).toBe(r1!.color != null)
|
||||
expect(r2!.colorInherited).toBeUndefined()
|
||||
forceRebuild(el)
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
// Only the schemeClr run materializes srgbClr (without a theme, resolveColorNode may fail to
|
||||
// resolve the color — then neither is written; assert the inherited run never writes fill)
|
||||
const firstRun = /<a:r><a:rPr[^>]*\/?>(?:<\/a:rPr>)?<a:t>a<\/a:t>/.exec(out)
|
||||
expect(firstRun).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('rebuild path: run-level hlinkClick/strike/cs written back', () => {
|
||||
it('hlinkClick r:id + action + tooltip preserved', () => {
|
||||
const el = parseEl(
|
||||
'<a:bodyPr/><a:p><a:r><a:rPr><a:hlinkClick r:id="rId9" action="ppaction://hlinksldjump" tooltip="jump"/></a:rPr>' +
|
||||
'<a:t>link</a:t></a:r></a:p>',
|
||||
)
|
||||
const r = el.text!.paragraphs[0]!.runs[0]!
|
||||
expect(r.hyperlinkRId).toBe('rId9')
|
||||
expect(r.hyperlinkAction).toBe('ppaction://hlinksldjump')
|
||||
forceRebuild(el)
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('r:id="rId9"')
|
||||
expect(out).toContain('action="ppaction://hlinksldjump"')
|
||||
expect(out).toContain('tooltip="jump"')
|
||||
})
|
||||
|
||||
it('strike and a:cs font preserved', () => {
|
||||
const el = parseEl(
|
||||
'<a:bodyPr/><a:p><a:r><a:rPr strike="dblStrike"><a:cs typeface="Arial"/></a:rPr><a:t>x</a:t></a:r></a:p>',
|
||||
)
|
||||
const r = el.text!.paragraphs[0]!.runs[0]!
|
||||
expect(r.strike).toBe(true)
|
||||
expect(r.strikeStyle).toBe('dblStrike')
|
||||
expect(r.csFont).toBe('Arial')
|
||||
forceRebuild(el)
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('strike="dblStrike"')
|
||||
expect(out).toContain('<a:cs typeface="Arial"/>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('in-place patch path: strike toggle', () => {
|
||||
it('enabling strikethrough injects strike="sngStrike"', () => {
|
||||
const el = parseEl('<a:bodyPr/><a:p><a:r><a:rPr/><a:t>x</a:t></a:r></a:p>')
|
||||
el.text!.paragraphs[0]!.runs[0]!.strike = true
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('strike="sngStrike"')
|
||||
})
|
||||
|
||||
it('removing strikethrough: existing strike becomes noStrike, runs without strike get nothing injected', () => {
|
||||
const el = parseEl(
|
||||
'<a:bodyPr/><a:p><a:r><a:rPr strike="sngStrike"/><a:t>a</a:t></a:r><a:r><a:rPr/><a:t>b</a:t></a:r></a:p>',
|
||||
)
|
||||
const [r1, r2] = el.text!.paragraphs[0]!.runs
|
||||
r1!.strike = false
|
||||
delete r1!.strikeStyle
|
||||
r2!.text = 'b2'
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('strike="noStrike"')
|
||||
expect(out.match(/\sstrike="/g)!.length).toBe(1)
|
||||
})
|
||||
|
||||
it('run without explicit sz: text-only edit does not inject sz (inheritance not materialized)', () => {
|
||||
const el = parseEl(
|
||||
'<a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="2000"/></a:lvl1pPr></a:lstStyle>' +
|
||||
'<a:p><a:r><a:rPr/><a:t>x</a:t></a:r></a:p>',
|
||||
)
|
||||
el.text!.paragraphs[0]!.runs[0]!.text = 'y'
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
const pStart = out.indexOf('<a:p>')
|
||||
expect(out.slice(pStart)).not.toContain('sz=')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Verifies the core replace_at sequence (redo one slide in place):
|
||||
* mergeSlideFromPptx (new slide appended at the end) → moveSlide (into position) → deleteSlide (remove old slide).
|
||||
* This is the engine-level equivalent of the replace_at branch in slides-main 'slides:html-to-pptx';
|
||||
* no Electron dependency — runs the real openPptx → operations → savePptx → openPptx chain.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import PptxGenJS from 'pptxgenjs'
|
||||
import { openPptx, savePptx, mergeSlideFromPptx, moveSlide, deleteSlide } from '../src/index'
|
||||
|
||||
async function onePagePptx(text: string): Promise<Uint8Array> {
|
||||
const p = new PptxGenJS()
|
||||
p.defineLayout({ name: 'W', width: 13.333, height: 7.5 })
|
||||
p.layout = 'W'
|
||||
const s = p.addSlide()
|
||||
s.addText(text, { x: 1, y: 1, w: 8, h: 1, fontSize: 32 })
|
||||
const buf = (await p.write({ outputType: 'nodebuffer' })) as Buffer
|
||||
return new Uint8Array(buf)
|
||||
}
|
||||
|
||||
/** Readable text per slide (concatenated text/shape elements) */
|
||||
function slideTexts(opened: Awaited<ReturnType<typeof openPptx>>): string[] {
|
||||
return opened.deck.slides.map((sl) =>
|
||||
sl.elements
|
||||
.filter((el) => el.type === 'text' || el.type === 'shape')
|
||||
.map(
|
||||
(el) =>
|
||||
(
|
||||
el as { text?: { paragraphs: Array<{ runs: Array<{ text: string }> }> } }
|
||||
).text?.paragraphs
|
||||
?.flatMap((pg) => pg.runs.map((r) => r.text))
|
||||
.join('') ?? '',
|
||||
)
|
||||
.join(' '),
|
||||
)
|
||||
}
|
||||
|
||||
async function threePageDeck() {
|
||||
const base = await openPptx(await onePagePptx('P1'))
|
||||
await mergeSlideFromPptx(base, await onePagePptx('P2'))
|
||||
await mergeSlideFromPptx(base, await onePagePptx('P3'))
|
||||
expect(base.deck.slides.length).toBe(3)
|
||||
return base
|
||||
}
|
||||
|
||||
describe('replace_at sequence (merge → move → delete)', () => {
|
||||
it('replace a middle slide in place: slide count unchanged, new slide in position, old slide gone', async () => {
|
||||
const base = await threePageDeck()
|
||||
const atIndex = 1 // replace P2
|
||||
|
||||
const total = base.deck.slides.length
|
||||
const merged = await mergeSlideFromPptx(base, await onePagePptx('NEW_P2'))
|
||||
expect(merged).not.toBeNull()
|
||||
expect(moveSlide(base, total, atIndex)).toBe(true)
|
||||
expect(deleteSlide(base, atIndex + 1)).toBe(true)
|
||||
|
||||
expect(base.deck.slides.length).toBe(3)
|
||||
const texts = slideTexts(base)
|
||||
expect(texts[0]).toContain('P1')
|
||||
expect(texts[1]).toContain('NEW_P2')
|
||||
expect(texts[1]).not.toContain('P2 ') // no leftover text from the old slide
|
||||
expect(texts[2]).toContain('P3')
|
||||
})
|
||||
|
||||
it('replacing the last slide (atIndex=last) also works', async () => {
|
||||
const base = await threePageDeck()
|
||||
const atIndex = 2
|
||||
const total = base.deck.slides.length
|
||||
await mergeSlideFromPptx(base, await onePagePptx('NEW_P3'))
|
||||
expect(moveSlide(base, total, atIndex)).toBe(true)
|
||||
expect(deleteSlide(base, atIndex + 1)).toBe(true)
|
||||
|
||||
const texts = slideTexts(base)
|
||||
expect(base.deck.slides.length).toBe(3)
|
||||
expect(texts[2]).toContain('NEW_P3')
|
||||
})
|
||||
|
||||
it('replacing the first slide keeps order and content correct after save and reopen', async () => {
|
||||
const base = await threePageDeck()
|
||||
const atIndex = 0
|
||||
const total = base.deck.slides.length
|
||||
await mergeSlideFromPptx(base, await onePagePptx('NEW_P1'))
|
||||
expect(moveSlide(base, total, atIndex)).toBe(true)
|
||||
expect(deleteSlide(base, atIndex + 1)).toBe(true)
|
||||
|
||||
const reopened = await openPptx(await savePptx(base))
|
||||
expect(reopened.deck.slides.length).toBe(3)
|
||||
const texts = slideTexts(reopened)
|
||||
expect(texts[0]).toContain('NEW_P1')
|
||||
expect(texts[1]).toContain('P2')
|
||||
expect(texts[2]).toContain('P3')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Run-level format fidelity: latin/ea dual fonts kept + underline style not collapsed.
|
||||
* Modeled via parseSlide (with latinFont/eaFont/fontImplicit/underlineStyle markers),
|
||||
* then asserted at the byte level through patchTextElementXml.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { patchTextElementXml, setElementFont } from '../src/index'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
const slideWith = (sp: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${sp}</p:spTree></p:cSld></p:sld>`
|
||||
const spWith = (runs: string) =>
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
`<p:txBody><a:bodyPr/><a:p>${runs}</a:p></p:txBody></p:sp>`
|
||||
|
||||
const parseEl = (runs: string) => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(spWith(runs)),
|
||||
ctx: {},
|
||||
})
|
||||
return { slide, el: slide.elements[0] as TextElement }
|
||||
}
|
||||
|
||||
describe('latin/ea dual fonts preserved', () => {
|
||||
const DUAL =
|
||||
'<a:r><a:rPr lang="en" sz="1800"><a:latin typeface="Calibri"/><a:ea typeface="微软雅黑"/></a:rPr><a:t>混排 text</a:t></a:r>'
|
||||
|
||||
it('parses latinFont/eaFont verbatim', () => {
|
||||
const { el } = parseEl(DUAL)
|
||||
const r = el.text!.paragraphs[0]!.runs[0]!
|
||||
expect(r.latinFont).toBe('Calibri')
|
||||
expect(r.eaFont).toBe('微软雅黑')
|
||||
expect(r.fontImplicit).toBeUndefined()
|
||||
})
|
||||
|
||||
it('text-only edit: dual font declarations keep their original bytes', () => {
|
||||
const { el } = parseEl(DUAL)
|
||||
el.text!.paragraphs[0]!.runs[0]!.text = 'edited 编辑'
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('<a:latin typeface="Calibri"/>')
|
||||
expect(out).toContain('<a:ea typeface="微软雅黑"/>')
|
||||
expect(out).toContain('edited 编辑')
|
||||
})
|
||||
|
||||
it('theme font reference (+mn-lt) not materialized when the font is unchanged', () => {
|
||||
const { el } = parseEl('<a:r><a:rPr><a:latin typeface="+mn-lt"/></a:rPr><a:t>x</a:t></a:r>')
|
||||
el.text!.paragraphs[0]!.runs[0]!.text = 'y'
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('typeface="+mn-lt"')
|
||||
})
|
||||
|
||||
it('run without font declaration (inherited): text-only edit does not inject latin/ea', () => {
|
||||
const { el } = parseEl('<a:r><a:rPr sz="1800"/><a:t>x</a:t></a:r>')
|
||||
expect(el.text!.paragraphs[0]!.runs[0]!.fontImplicit).toBe(true)
|
||||
el.text!.paragraphs[0]!.runs[0]!.text = 'y'
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).not.toContain('<a:latin')
|
||||
})
|
||||
|
||||
it('setElementFont explicit font change: both latin/ea rewritten to the new font', () => {
|
||||
const { slide, el } = parseEl(DUAL)
|
||||
setElementFont(slide, el.id, { fontFamily: 'Arial' })
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('<a:latin typeface="Arial"/>')
|
||||
expect(out).toContain('<a:ea typeface="Arial"/>')
|
||||
expect(out).not.toContain('微软雅黑')
|
||||
})
|
||||
})
|
||||
|
||||
describe('underline style not collapsed', () => {
|
||||
it('u="dbl" stays dbl after a text-only edit', () => {
|
||||
const { el } = parseEl('<a:r><a:rPr u="dbl"/><a:t>x</a:t></a:r>')
|
||||
const r = el.text!.paragraphs[0]!.runs[0]!
|
||||
expect(r.underline).toBe(true)
|
||||
expect(r.underlineStyle).toBe('dbl')
|
||||
r.text = 'y'
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('u="dbl"')
|
||||
expect(out).not.toContain('u="sng"')
|
||||
})
|
||||
|
||||
it('removing underline: existing u becomes none; runs without u get nothing injected', () => {
|
||||
const { el } = parseEl(
|
||||
'<a:r><a:rPr u="wavy"/><a:t>a</a:t></a:r><a:r><a:rPr/><a:t>b</a:t></a:r>',
|
||||
)
|
||||
const [r1, r2] = el.text!.paragraphs[0]!.runs
|
||||
r1!.underline = false
|
||||
delete r1!.underlineStyle
|
||||
r2!.text = 'b2'
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('u="none"')
|
||||
expect(out).not.toContain('u="wavy"')
|
||||
// The second run had no u originally; do not inject one
|
||||
expect(out.match(/\su="/g)!.length).toBe(1)
|
||||
})
|
||||
|
||||
it('newly enabled underline writes sng', () => {
|
||||
const { el } = parseEl('<a:r><a:rPr/><a:t>x</a:t></a:r>')
|
||||
el.text!.paragraphs[0]!.runs[0]!.underline = true
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('u="sng"')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* Run-level hyperlinks (#146): parse-time rId resolution + hlink styling, rels allocation
|
||||
* for links set in-session, patch-path <a:hlinkClick> surgery, and live lookup for the show.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import {
|
||||
openPptx,
|
||||
savePptx,
|
||||
duplicateSlide,
|
||||
ensureRunLinkRels,
|
||||
getRunLinks,
|
||||
patchTextElementXml,
|
||||
type OpenedPptx,
|
||||
type TextElement,
|
||||
} from '../src/index'
|
||||
import type { Theme } from '../src/theme'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const slideWith = (sp: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${sp}</p:spTree></p:cSld></p:sld>`
|
||||
const spWith = (txBodyInner: string) =>
|
||||
'<p:sp><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
`<p:txBody>${txBodyInner}</p:txBody></p:sp>`
|
||||
|
||||
const parseEl = (txBodyInner: string, hlinkRels?: Map<string, string>, theme?: Theme) => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(spWith(txBodyInner)),
|
||||
ctx: { ...(hlinkRels ? { hlinkRels } : {}), ...(theme ? { theme } : {}) },
|
||||
})
|
||||
return slide.elements[0] as TextElement
|
||||
}
|
||||
|
||||
/** First element whose text has a non-empty run, plus that run's paragraph/run indexes. */
|
||||
function findTextRun(opened: OpenedPptx, slideIndex = 0) {
|
||||
for (const el of opened.deck.slides[slideIndex]!.elements) {
|
||||
if (el.type !== 'text' && el.type !== 'shape') continue
|
||||
const text = (el as TextElement).text
|
||||
if (!text) continue
|
||||
for (let pi = 0; pi < text.paragraphs.length; pi++) {
|
||||
const runs = text.paragraphs[pi]!.runs
|
||||
for (let ri = 0; ri < runs.length; ri++) {
|
||||
if (runs[ri]!.text.trim() && !runs[ri]!.field) {
|
||||
return { el: el as TextElement, pi, ri }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error('fixture has no text run')
|
||||
}
|
||||
|
||||
describe('parse: run hlinkClick resolved via ctx.hlinkRels', () => {
|
||||
const LINKED =
|
||||
'<a:bodyPr/><a:p><a:r><a:rPr><a:hlinkClick r:id="rId5"/></a:rPr><a:t>go</a:t></a:r></a:p>'
|
||||
|
||||
it('url target + hlink styling (implicit underline, theme hlink color)', () => {
|
||||
const theme = { colors: { hlink: '#0563C1' } } as unknown as Theme
|
||||
const el = parseEl(LINKED, new Map([['rId5', 'https://x.dev']]), theme)
|
||||
const r = el.text!.paragraphs[0]!.runs[0]!
|
||||
expect(r.hyperlink).toBe('https://x.dev')
|
||||
expect(r.hyperlinkRId).toBe('rId5')
|
||||
expect(r.underline).toBe(true)
|
||||
expect(r.underlineImplicit).toBe(true)
|
||||
expect(r.color).toBe('#0563C1')
|
||||
expect(r.colorFollowsTheme).toBe(true)
|
||||
expect(r.colorInherited).toBe(true)
|
||||
})
|
||||
|
||||
it('slide jump target keeps the slide:N encoding', () => {
|
||||
const el = parseEl(LINKED, new Map([['rId5', 'slide:3']]))
|
||||
expect(el.text!.paragraphs[0]!.runs[0]!.hyperlink).toBe('slide:3')
|
||||
})
|
||||
|
||||
it('explicit u="none" and explicit fill beat hlink styling', () => {
|
||||
const el = parseEl(
|
||||
'<a:bodyPr/><a:p><a:r><a:rPr u="none"><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>' +
|
||||
'<a:hlinkClick r:id="rId5"/></a:rPr><a:t>go</a:t></a:r></a:p>',
|
||||
new Map([['rId5', 'https://x.dev']]),
|
||||
)
|
||||
const r = el.text!.paragraphs[0]!.runs[0]!
|
||||
expect(r.underline).toBe(false)
|
||||
expect(r.underlineImplicit).toBeUndefined()
|
||||
expect(r.color).toBe('#FF0000')
|
||||
expect(r.colorFollowsTheme).toBeUndefined()
|
||||
})
|
||||
|
||||
it('unresolvable rId keeps hyperlinkRId without hyperlink or styling', () => {
|
||||
const el = parseEl(LINKED)
|
||||
const r = el.text!.paragraphs[0]!.runs[0]!
|
||||
expect(r.hyperlinkRId).toBe('rId5')
|
||||
expect(r.hyperlink).toBeUndefined()
|
||||
expect(r.underline).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('patch path: hlinkClick surgery without structural change', () => {
|
||||
it('adds hlinkClick for a link set this session', () => {
|
||||
const el = parseEl('<a:bodyPr/><a:p><a:r><a:rPr b="1"/><a:t>text</a:t></a:r></a:p>')
|
||||
const r = el.text!.paragraphs[0]!.runs[0]!
|
||||
r.hyperlink = 'https://x.dev'
|
||||
r.hyperlinkRId = 'rId7'
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).toContain('<a:hlinkClick')
|
||||
expect(out).toContain('r:id="rId7"')
|
||||
})
|
||||
|
||||
it('removes hlinkClick when the link was cleared, keeping other rPr children', () => {
|
||||
const el = parseEl(
|
||||
'<a:bodyPr/><a:p><a:r><a:rPr><a:latin typeface="Arial"/>' +
|
||||
'<a:hlinkClick r:id="rId5"/></a:rPr><a:t>go</a:t></a:r></a:p>',
|
||||
new Map([['rId5', 'https://x.dev']]),
|
||||
)
|
||||
const r = el.text!.paragraphs[0]!.runs[0]!
|
||||
delete r.hyperlink
|
||||
delete r.hyperlinkRId
|
||||
r.underline = false
|
||||
delete r.underlineImplicit
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).not.toContain('hlinkClick')
|
||||
expect(out).toContain('<a:latin typeface="Arial"/>')
|
||||
})
|
||||
|
||||
it('implicit (hlink-derived) underline never bakes a u attribute', () => {
|
||||
const el = parseEl(LINKED_RID9, new Map([['rId9', 'https://x.dev']]))
|
||||
el.text!.paragraphs[0]!.runs[0]!.text = 'changed'
|
||||
const out = patchTextElementXml(el, el.anchor.originalXml)
|
||||
expect(out).not.toMatch(/\su="/)
|
||||
expect(out).toContain('r:id="rId9"') // untouched original hlink bytes
|
||||
})
|
||||
})
|
||||
const LINKED_RID9 =
|
||||
'<a:bodyPr/><a:p><a:r><a:rPr><a:hlinkClick r:id="rId9"/></a:rPr><a:t>go</a:t></a:r></a:p>'
|
||||
|
||||
describe('ensureRunLinkRels + save round-trip', () => {
|
||||
it('url link set in-session survives save → reopen with resolved target', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const { el, pi, ri } = findTextRun(opened)
|
||||
const run = el.text!.paragraphs[pi]!.runs[ri]!
|
||||
run.hyperlink = 'https://run.example/x?a=1'
|
||||
delete run.hyperlinkRId
|
||||
el.dirty = true
|
||||
expect(ensureRunLinkRels(opened, 0, el.text!.paragraphs)).toBe(true)
|
||||
expect(run.hyperlinkRId).toMatch(/^rId\d+$/)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const again = findTextRun(reopened)
|
||||
const r2 = again.el.text!.paragraphs[again.pi]!.runs[again.ri]!
|
||||
expect(r2.hyperlink).toBe('https://run.example/x?a=1')
|
||||
expect(r2.underlineImplicit).toBe(true)
|
||||
})
|
||||
|
||||
it('slide jump gets the hlinksldjump action and resolves back to slide:N', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
duplicateSlide(opened, 0)
|
||||
const { el, pi, ri } = findTextRun(opened)
|
||||
const run = el.text!.paragraphs[pi]!.runs[ri]!
|
||||
run.hyperlink = 'slide:1'
|
||||
delete run.hyperlinkRId
|
||||
el.dirty = true
|
||||
ensureRunLinkRels(opened, 0, el.text!.paragraphs)
|
||||
expect(run.hyperlinkAction).toBe('ppaction://hlinksldjump')
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const again = findTextRun(reopened)
|
||||
expect(again.el.text!.paragraphs[again.pi]!.runs[again.ri]!.hyperlink).toBe('slide:1')
|
||||
})
|
||||
|
||||
it('getRunLinks resolves live from the model rIds', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const { el, pi, ri } = findTextRun(opened)
|
||||
const run = el.text!.paragraphs[pi]!.runs[ri]!
|
||||
run.hyperlink = 'https://live.example/'
|
||||
delete run.hyperlinkRId
|
||||
ensureRunLinkRels(opened, 0, el.text!.paragraphs)
|
||||
const links = getRunLinks(opened, 0)
|
||||
expect(links).toContainEqual({
|
||||
elementId: el.id,
|
||||
paraIndex: pi,
|
||||
runIndex: ri,
|
||||
target: { kind: 'url', url: 'https://live.example/' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { mkdtempSync, readFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import JSZip from 'jszip'
|
||||
import { openPptx, savePptx, savePptxToFile, commitSaved, addElement } from '../src/index'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
const out = () => join(mkdtempSync(join(tmpdir(), 'save-stream-')), 'out.pptx')
|
||||
|
||||
describe('savePptxToFile', () => {
|
||||
it('writes a package that reopens with the same slides as the in-memory save', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const target = out()
|
||||
await savePptxToFile(opened, target)
|
||||
|
||||
const fromDisk = await openPptx(readFileSync(target))
|
||||
const fromMemory = await openPptx(
|
||||
await savePptx(await openPptx(fx('01_standard_business.pptx'))),
|
||||
)
|
||||
expect(fromDisk.deck.slides.length).toBe(fromMemory.deck.slides.length)
|
||||
expect([...fromDisk.archive.entries.keys()].sort()).toEqual(
|
||||
[...fromMemory.archive.entries.keys()].sort(),
|
||||
)
|
||||
})
|
||||
|
||||
it('carries unsaved edits into the streamed file', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
addElement(opened.deck.slides[0]!, {
|
||||
kind: 'textbox',
|
||||
offset: { x: 914400, y: 914400, cx: 6096000, cy: 914400 },
|
||||
paragraphs: [{ runs: [{ text: 'streamed edit', bold: true, fontSize: 28 }] }],
|
||||
})
|
||||
const target = out()
|
||||
await savePptxToFile(opened, target)
|
||||
|
||||
const reopened = await openPptx(readFileSync(target))
|
||||
const xml = reopened.archive.readText(reopened.deck.slides[0]!.path)!
|
||||
expect(xml).toContain('streamed edit')
|
||||
})
|
||||
|
||||
it('stores already-compressed media instead of deflating it again', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const target = out()
|
||||
await savePptxToFile(opened, target)
|
||||
|
||||
const zip = await JSZip.loadAsync(readFileSync(target))
|
||||
const sizes = (name: string) =>
|
||||
(
|
||||
zip.files[name] as unknown as {
|
||||
_data: { compressedSize: number; uncompressedSize: number }
|
||||
}
|
||||
)._data
|
||||
const media = Object.keys(zip.files).filter((name) => /\.(png|jpe?g|gif)$/i.test(name))
|
||||
expect(media.length).toBeGreaterThan(0)
|
||||
// STORE leaves the bytes untouched, so the two sizes match exactly
|
||||
for (const name of media) {
|
||||
const { compressedSize, uncompressedSize } = sizes(name)
|
||||
expect(compressedSize, name).toBe(uncompressedSize)
|
||||
}
|
||||
// xml parts are still deflated
|
||||
const xml = sizes('ppt/presentation.xml')
|
||||
expect(xml.compressedSize).toBeLessThan(xml.uncompressedSize)
|
||||
})
|
||||
|
||||
// commitSaved replaces the post-save reopen; a stale anchor would silently
|
||||
// revert the first edit on the second save.
|
||||
it('commitSaved: two consecutive edit+save cycles keep both edits', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
addElement(slide, {
|
||||
kind: 'textbox',
|
||||
offset: { x: 914400, y: 914400, cx: 6096000, cy: 914400 },
|
||||
paragraphs: [{ runs: [{ text: 'FIRST_CYCLE_EDIT' }] }],
|
||||
})
|
||||
await savePptx(opened)
|
||||
commitSaved(opened)
|
||||
expect(slide.structureDirty).toBeUndefined()
|
||||
|
||||
addElement(slide, {
|
||||
kind: 'textbox',
|
||||
offset: { x: 914400, y: 2286000, cx: 6096000, cy: 914400 },
|
||||
paragraphs: [{ runs: [{ text: 'SECOND_CYCLE_EDIT' }] }],
|
||||
})
|
||||
const finalBytes = await savePptx(opened)
|
||||
|
||||
const reopened = await openPptx(finalBytes)
|
||||
const xml = reopened.archive.readText(slide.path)!
|
||||
expect(xml).toContain('FIRST_CYCLE_EDIT')
|
||||
expect(xml).toContain('SECOND_CYCLE_EDIT')
|
||||
})
|
||||
})
|
||||
|
||||
describe('savePptxToFile error containment', () => {
|
||||
it('rejects instead of throwing past the caller when the target is unwritable', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
let uncaught: unknown = null
|
||||
const onUncaught = (error: unknown) => {
|
||||
uncaught = error
|
||||
}
|
||||
process.on('uncaughtException', onUncaught)
|
||||
try {
|
||||
await expect(savePptxToFile(opened, '/definitely/not/a/directory/out.pptx')).rejects.toThrow()
|
||||
await new Promise((resolve) => setTimeout(resolve, 200))
|
||||
} finally {
|
||||
process.off('uncaughtException', onUncaught)
|
||||
}
|
||||
expect(uncaught).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,229 @@
|
||||
/**
|
||||
* Section read/write tests: round-trip, add/remove/rename/move.
|
||||
* Fixture 01_standard_business.pptx has 5 slides and no sections.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import {
|
||||
addSection,
|
||||
getSections,
|
||||
moveSection,
|
||||
moveSlide,
|
||||
openPptx,
|
||||
removeSection,
|
||||
renameSection,
|
||||
savePptx,
|
||||
setSections,
|
||||
type OpenedPptx,
|
||||
} from '../src/index'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const open = () => openPptx(fx('01_standard_business.pptx'))
|
||||
const presXml = (o: OpenedPptx) => o.archive.readText('ppt/presentation.xml')!
|
||||
|
||||
describe('sections (p14:sectionLst)', () => {
|
||||
it('getSections returns [] for legacy documents without sections', async () => {
|
||||
const opened = await open()
|
||||
expect(getSections(opened)).toEqual([])
|
||||
})
|
||||
|
||||
it('setSections → savePptx → openPptx round-trip is consistent and does not touch Content_Types/rels', async () => {
|
||||
const opened = await open()
|
||||
const ctBefore = opened.archive.readText('[Content_Types].xml')
|
||||
const relsBefore = opened.archive.readText('ppt/_rels/presentation.xml.rels')
|
||||
const secs = [
|
||||
{
|
||||
id: '{11111111-2222-3333-4444-555555555555}',
|
||||
name: 'Opening & "Intro"',
|
||||
slideIndices: [0, 1],
|
||||
},
|
||||
{ id: '{AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE}', name: 'Body', slideIndices: [2, 3, 4] },
|
||||
]
|
||||
setSections(opened, secs)
|
||||
|
||||
const xml = presXml(opened)
|
||||
expect(xml).toContain('<p14:sectionLst')
|
||||
expect(xml).toContain('{521415D9-36F7-43E2-AB2F-B90AF26B5E84}')
|
||||
// Special characters escaped as attribute values
|
||||
expect(xml).toContain('name="Opening & "Intro""')
|
||||
expect(opened.archive.readText('[Content_Types].xml')).toBe(ctBefore)
|
||||
expect(opened.archive.readText('ppt/_rels/presentation.xml.rels')).toBe(relsBefore)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSections(reopened)).toEqual(secs)
|
||||
})
|
||||
|
||||
it('p14:sldId references the numeric slide id (not rId)', async () => {
|
||||
const opened = await open()
|
||||
setSections(opened, [
|
||||
{ id: '{11111111-2222-3333-4444-555555555555}', name: 'A', slideIndices: [0] },
|
||||
])
|
||||
// The fixture's first slide has sldId 256
|
||||
expect(presXml(opened)).toContain('<p14:sldId id="256"/>')
|
||||
})
|
||||
|
||||
it('addSection: sectionless document auto-gains a default section; then split an existing section', async () => {
|
||||
const opened = await open()
|
||||
const r1 = addSection(opened, 2, 'New Section')!
|
||||
expect(r1.map((s) => ({ name: s.name, slideIndices: s.slideIndices }))).toEqual([
|
||||
{ name: 'Default Section', slideIndices: [0, 1] },
|
||||
{ name: 'New Section', slideIndices: [2, 3, 4] },
|
||||
])
|
||||
// Split off another section before slide 4 (index 3)
|
||||
const r2 = addSection(opened, 3, 'Split Again')!
|
||||
expect(r2.map((s) => ({ name: s.name, slideIndices: s.slideIndices }))).toEqual([
|
||||
{ name: 'Default Section', slideIndices: [0, 1] },
|
||||
{ name: 'New Section', slideIndices: [2] },
|
||||
{ name: 'Split Again', slideIndices: [3, 4] },
|
||||
])
|
||||
// Out-of-range index rejected
|
||||
expect(addSection(opened, 5, 'x')).toBeNull()
|
||||
})
|
||||
|
||||
it('renameSection: rename takes effect and round-trips', async () => {
|
||||
const opened = await open()
|
||||
const [a] = addSection(opened, 0, 'Old Name')!
|
||||
const r = renameSection(opened, a!.id, 'New Name')!
|
||||
expect(r[0]!.name).toBe('New Name')
|
||||
expect(renameSection(opened, '{00000000-0000-0000-0000-000000000000}', 'x')).toBeNull()
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSections(reopened)[0]!.name).toBe('New Name')
|
||||
})
|
||||
|
||||
it('removeSection(keepSlides): slides merge into the adjacent section; sectionLst removed when all sections are gone', async () => {
|
||||
const opened = await open()
|
||||
addSection(opened, 2, 'Second Half')
|
||||
const secs = getSections(opened) // [default section 0-1, second half 2-4]
|
||||
const r1 = removeSection(opened, secs[1]!.id, { keepSlides: true })!
|
||||
expect(r1).toHaveLength(1)
|
||||
expect(r1[0]!.slideIndices).toEqual([0, 1, 2, 3, 4])
|
||||
// Delete the first (only) section → no sections
|
||||
const r2 = removeSection(opened, r1[0]!.id, { keepSlides: true })!
|
||||
expect(r2).toEqual([])
|
||||
expect(presXml(opened)).not.toContain('p14:sectionLst')
|
||||
// All slides retained
|
||||
expect(opened.deck.slides).toHaveLength(5)
|
||||
})
|
||||
|
||||
it('removeSection: removing the first section merges its slides into the next one', async () => {
|
||||
const opened = await open()
|
||||
addSection(opened, 2, 'Second Half')
|
||||
const secs = getSections(opened)
|
||||
const r = removeSection(opened, secs[0]!.id, { keepSlides: true })!
|
||||
expect(r).toHaveLength(1)
|
||||
expect(r[0]!.name).toBe('Second Half')
|
||||
expect(r[0]!.slideIndices).toEqual([0, 1, 2, 3, 4])
|
||||
})
|
||||
|
||||
it('moveSection: whole section moves up, sldIdLst / deck.slides / section indices stay in sync, round-trip holds', async () => {
|
||||
const opened = await open()
|
||||
const pathsBefore = opened.deck.slides.map((s) => s.path)
|
||||
addSection(opened, 2, 'Second Half') // [default section 0-1, second half 2-4]
|
||||
const secs = getSections(opened)
|
||||
const r = moveSection(opened, secs[1]!.id, 'up')!
|
||||
expect(r.map((s) => ({ name: s.name, slideIndices: s.slideIndices }))).toEqual([
|
||||
{ name: 'Second Half', slideIndices: [0, 1, 2] },
|
||||
{ name: 'Default Section', slideIndices: [3, 4] },
|
||||
])
|
||||
// deck.slides order: original slides 2,3,4 moved to the front
|
||||
expect(opened.deck.slides.map((s) => s.path)).toEqual([
|
||||
pathsBefore[2],
|
||||
pathsBefore[3],
|
||||
pathsBefore[4],
|
||||
pathsBefore[0],
|
||||
pathsBefore[1],
|
||||
])
|
||||
// Edge cases: moving first section up / last section down rejected
|
||||
expect(moveSection(opened, r[0]!.id, 'up')).toBeNull()
|
||||
expect(moveSection(opened, r[1]!.id, 'down')).toBeNull()
|
||||
|
||||
// Round-trip: slide order and sections consistent after save and reopen
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides.map((s) => s.path)).toEqual([
|
||||
pathsBefore[2],
|
||||
pathsBefore[3],
|
||||
pathsBefore[4],
|
||||
pathsBefore[0],
|
||||
pathsBefore[1],
|
||||
])
|
||||
expect(
|
||||
getSections(reopened).map((s) => ({ name: s.name, slideIndices: s.slideIndices })),
|
||||
).toEqual([
|
||||
{ name: 'Second Half', slideIndices: [0, 1, 2] },
|
||||
{ name: 'Default Section', slideIndices: [3, 4] },
|
||||
])
|
||||
})
|
||||
|
||||
it('moveSlide: moving a slide down in a sectionless document keeps sldIdLst / deck.slides in sync and round-trips', async () => {
|
||||
const opened = await open()
|
||||
const p = opened.deck.slides.map((s) => s.path)
|
||||
expect(moveSlide(opened, 0, 3)).toBe(true)
|
||||
expect(opened.deck.slides.map((s) => s.path)).toEqual([p[1], p[2], p[3], p[0], p[4]])
|
||||
// A sectionless document should not gain sections just from moving a slide
|
||||
expect(presXml(opened)).not.toContain('p14:sectionLst')
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.slides.map((s) => s.path)).toEqual([p[1], p[2], p[3], p[0], p[4]])
|
||||
|
||||
// Edge cases: same position / out of range rejected
|
||||
expect(moveSlide(opened, 2, 2)).toBe(false)
|
||||
expect(moveSlide(opened, 9, 0)).toBe(false)
|
||||
})
|
||||
|
||||
it('moveSlide: moving across sections assigns the slide to the target section, sections stay contiguous', async () => {
|
||||
const opened = await open()
|
||||
addSection(opened, 2, 'Second Half') // [default section 0-1, second half 2-4]
|
||||
const p = opened.deck.slides.map((s) => s.path)
|
||||
// Move slide 1 (default section) to index 3 (inside the second-half section)
|
||||
expect(moveSlide(opened, 0, 3)).toBe(true)
|
||||
expect(opened.deck.slides.map((s) => s.path)).toEqual([p[1], p[2], p[3], p[0], p[4]])
|
||||
expect(
|
||||
getSections(opened).map((s) => ({ name: s.name, slideIndices: s.slideIndices })),
|
||||
).toEqual([
|
||||
{ name: 'Default Section', slideIndices: [0] },
|
||||
{ name: 'Second Half', slideIndices: [1, 2, 3, 4] },
|
||||
])
|
||||
// Move back before the section start: assigned to the default section
|
||||
expect(moveSlide(opened, 3, 0)).toBe(true)
|
||||
expect(
|
||||
getSections(opened).map((s) => ({ name: s.name, slideIndices: s.slideIndices })),
|
||||
).toEqual([
|
||||
{ name: 'Default Section', slideIndices: [0, 1] },
|
||||
{ name: 'Second Half', slideIndices: [2, 3, 4] },
|
||||
])
|
||||
expect(opened.deck.slides.map((s) => s.path)).toEqual(p)
|
||||
|
||||
// Round-trip: section structure consistent after save and reopen
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(
|
||||
getSections(reopened).map((s) => ({ name: s.name, slideIndices: s.slideIndices })),
|
||||
).toEqual([
|
||||
{ name: 'Default Section', slideIndices: [0, 1] },
|
||||
{ name: 'Second Half', slideIndices: [2, 3, 4] },
|
||||
])
|
||||
})
|
||||
|
||||
it('moveSlide: moving all slides out of a section leaves it empty', async () => {
|
||||
const opened = await open()
|
||||
addSection(opened, 4, 'Tail Section') // [default section 0-3, tail section 4]
|
||||
expect(moveSlide(opened, 4, 0)).toBe(true)
|
||||
expect(
|
||||
getSections(opened).map((s) => ({ name: s.name, slideIndices: s.slideIndices })),
|
||||
).toEqual([
|
||||
{ name: 'Default Section', slideIndices: [0, 1, 2, 3, 4] },
|
||||
{ name: 'Tail Section', slideIndices: [] },
|
||||
])
|
||||
})
|
||||
|
||||
it('setSections([]) clears sections and leaves no empty extLst in presentation.xml', async () => {
|
||||
const opened = await open()
|
||||
addSection(opened, 0, 'Only Section')
|
||||
setSections(opened, [])
|
||||
expect(getSections(opened)).toEqual([])
|
||||
expect(presXml(opened)).not.toContain('<p:extLst>')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,50 @@
|
||||
/** Switching an existing slide's layout + resetting the layout. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { listSlideLayouts } from '../src/layout'
|
||||
import { openPptx, savePptx, setSlideLayout, resetSlideLayout } from '../src/index'
|
||||
import { relsPathFor } from '../src/zip'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
describe('setSlideLayout / resetSlideLayout', () => {
|
||||
it('switch layout: rels point to the new layout, effective after save and reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const layouts = listSlideLayouts(opened.archive)
|
||||
expect(layouts.length).toBeGreaterThan(1)
|
||||
const slide0 = opened.deck.slides[0]!
|
||||
const curRel = opened.archive.readText(relsPathFor(slide0.path))!
|
||||
const target = layouts.find((l) => !curRel.includes(l.path.slice('ppt/'.length)))!
|
||||
const fresh = setSlideLayout(opened, 0, target.path)
|
||||
expect(fresh).not.toBeNull()
|
||||
const newRel = opened.archive.readText(relsPathFor(fresh!.path))!
|
||||
expect(newRel).toContain(target.path.slice('ppt/'.length))
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const rel2 = reopened.archive.readText(relsPathFor(reopened.deck.slides[0]!.path))!
|
||||
expect(rel2).toContain(target.path.slice('ppt/'.length))
|
||||
})
|
||||
|
||||
it('reset layout: explicit placeholder xfrm removed, geometry falls back to layout inheritance', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const ph = slide.elements.find(
|
||||
(e) => e.placeholder && (e.type === 'text' || e.type === 'shape'),
|
||||
) as TextElement
|
||||
expect(ph).toBeTruthy()
|
||||
// First move the placeholder away (writes an explicit xfrm)
|
||||
ph.transform.offset = { x: 111, y: 222, cx: 3333333, cy: 444444 }
|
||||
ph.dirtyTransform = true
|
||||
const fresh = resetSlideLayout(opened, 0)
|
||||
expect(fresh).not.toBeNull()
|
||||
const ph2 = fresh!.elements.find((e) => e.placeholder === ph.placeholder)!
|
||||
// After reset, geometry comes from layout inheritance (no longer the moved value)
|
||||
expect(ph2.transform.offset.x).not.toBe(111)
|
||||
expect(ph2.transform.offset.cx).toBeGreaterThan(0)
|
||||
expect(ph2.anchor.originalXml).not.toContain('<a:xfrm')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
/** Slide size switching: sldSz write-back + per-axis proportional rescale + round-trip idempotence. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { openPptx, savePptx, setSlideSize, createBlankPptx, addElement } from '../src/index'
|
||||
|
||||
describe('setSlideSize', () => {
|
||||
it('16:9 → 4:3: sldSz updated, elements rescaled per axis (full-bleed stays full-bleed)', async () => {
|
||||
const opened = await openPptx(await createBlankPptx()) // blank is 16:9
|
||||
const slide = opened.deck.slides[0]!
|
||||
addElement(slide, {
|
||||
kind: 'rect',
|
||||
offset: { x: 0, y: 0, cx: 12192000, cy: 6858000 },
|
||||
fillColor: '#123456',
|
||||
})
|
||||
expect(setSlideSize(opened, 9144000, 6858000)).toBe(true)
|
||||
expect(opened.deck.size).toEqual({ cx: 9144000, cy: 6858000 })
|
||||
|
||||
const el = slide.elements[0]!
|
||||
expect(el.transform.offset).toMatchObject({ x: 0, y: 0, cx: 9144000, cy: 6858000 })
|
||||
expect(el.dirtyTransform).toBe(true)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.deck.size.cx).toBe(9144000)
|
||||
})
|
||||
|
||||
it('4:3 → 16:9: content rescales with the canvas (wider, same height)', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
setSlideSize(opened, 9144000, 6858000)
|
||||
const slide = opened.deck.slides[0]!
|
||||
addElement(slide, {
|
||||
kind: 'rect',
|
||||
offset: { x: 900, y: 200, cx: 3000, cy: 400 },
|
||||
fillColor: '#123456',
|
||||
})
|
||||
expect(setSlideSize(opened, 12192000, 6858000)).toBe(true)
|
||||
const el = slide.elements[0]!
|
||||
const sx = 12192000 / 9144000
|
||||
expect(el.transform.offset).toMatchObject({
|
||||
x: Math.round(900 * sx),
|
||||
y: 200,
|
||||
cx: Math.round(3000 * sx),
|
||||
cy: 400,
|
||||
})
|
||||
})
|
||||
|
||||
it('A → B → A restores the original layout (idempotent round-trip)', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
addElement(slide, {
|
||||
kind: 'rect',
|
||||
offset: { x: 1234567, y: 765432, cx: 4567890, cy: 2345678 },
|
||||
fillColor: '#123456',
|
||||
})
|
||||
const before = { ...slide.elements[0]!.transform.offset }
|
||||
// 16:9 → 3:4 portrait → back (the issue's repro shape)
|
||||
setSlideSize(opened, 6858000, 9144000)
|
||||
setSlideSize(opened, 12192000, 6858000)
|
||||
const after = opened.deck.slides[0]!.elements[0]!.transform.offset
|
||||
expect(Math.abs(after.x - before.x)).toBeLessThanOrEqual(2)
|
||||
expect(Math.abs(after.y - before.y)).toBeLessThanOrEqual(2)
|
||||
expect(Math.abs(after.cx - before.cx)).toBeLessThanOrEqual(2)
|
||||
expect(Math.abs(after.cy - before.cy)).toBeLessThanOrEqual(2)
|
||||
expect(opened.deck.size).toEqual({ cx: 12192000, cy: 6858000 })
|
||||
})
|
||||
|
||||
it('same size rejected (no empty history step created)', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
expect(setSlideSize(opened, 12192000, 6858000)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setSlideSize scales masters in sync', () => {
|
||||
it('when shrinking, layout/master elements scale proportionally and center, part bytes written back', async () => {
|
||||
const { listMasterParts, parseMasterPart } = await import('../src/master-edit')
|
||||
const { readFileSync } = await import('node:fs')
|
||||
const { fileURLToPath } = await import('node:url')
|
||||
const { dirname, join } = await import('node:path')
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const opened = await openPptx(readFileSync(join(here, 'fixtures', '01_standard_business.pptx')))
|
||||
const parts = listMasterParts(opened.archive)
|
||||
expect(parts.length).toBeGreaterThan(0)
|
||||
const before = parseMasterPart(opened.archive, parts[0]!.partPath)!
|
||||
const el0 = before.elements.find((e) => e.transform.offset.cx > 0)
|
||||
expect(el0).toBeTruthy()
|
||||
const oldCx = el0!.transform.offset.cx
|
||||
|
||||
const oldSize = { ...opened.deck.size }
|
||||
setSlideSize(opened, 9144000, 6858000)
|
||||
const after = parseMasterPart(opened.archive, parts[0]!.partPath)!
|
||||
// Compute the ratio from the file's actual sldSz (generator may not write the standard 12192000)
|
||||
const sx = 9144000 / oldSize.cx
|
||||
// Element order is stable after reparse; compare scale ratios index by index
|
||||
before.elements.forEach((b, i) => {
|
||||
// Passthrough without p:xfrm cannot be patched; skip it (the engine skips it too)
|
||||
if (!b.transform.offset.cx || b.type === 'passthrough') return
|
||||
const a = after.elements[i]!
|
||||
expect(
|
||||
Math.abs(a.transform.offset.cx - Math.round(b.transform.offset.cx * sx)),
|
||||
).toBeLessThanOrEqual(1)
|
||||
})
|
||||
expect(oldCx).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('when enlarging, master elements rescale in sync with the slides', async () => {
|
||||
const { listMasterParts, parseMasterPart } = await import('../src/master-edit')
|
||||
const { readFileSync } = await import('node:fs')
|
||||
const { fileURLToPath } = await import('node:url')
|
||||
const { dirname, join } = await import('node:path')
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const opened = await openPptx(readFileSync(join(here, 'fixtures', '01_standard_business.pptx')))
|
||||
const parts = listMasterParts(opened.archive)
|
||||
expect(parts.length).toBeGreaterThan(0)
|
||||
const before = parseMasterPart(opened.archive, parts[0]!.partPath)!
|
||||
|
||||
const old = { ...opened.deck.size }
|
||||
expect(setSlideSize(opened, old.cx * 2, old.cy)).toBe(true)
|
||||
const after = parseMasterPart(opened.archive, parts[0]!.partPath)!
|
||||
before.elements.forEach((b, i) => {
|
||||
if (!b.transform.offset.cx || b.type === 'passthrough') return
|
||||
const a = after.elements[i]!
|
||||
expect(
|
||||
Math.abs(a.transform.offset.cx - Math.round(b.transform.offset.cx * 2)),
|
||||
).toBeLessThanOrEqual(1)
|
||||
expect(a.transform.offset.cy).toBe(b.transform.offset.cy)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('setElementImageFill', () => {
|
||||
it('shape fill replaced by blipFill, media/rels land in the package', async () => {
|
||||
const { setElementImageFill } = await import('../src/index')
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const r = addElement(slide, {
|
||||
kind: 'rect',
|
||||
offset: { x: 0, y: 0, cx: 1000, cy: 1000 },
|
||||
fillColor: '#FF0000',
|
||||
})
|
||||
const png = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
|
||||
'base64',
|
||||
)
|
||||
const mediaPath = setElementImageFill(opened, slide, r.id, png, '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')
|
||||
expect(el.anchor.originalXml).not.toContain('FF0000')
|
||||
expect((el as import('../src/types').TextElement).fill).toMatchObject({
|
||||
type: 'image',
|
||||
mediaRef: mediaPath,
|
||||
})
|
||||
// Save and reopen: media part exists, blipFill parses back to a picture fill
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(reopened.archive.entries.has(mediaPath!)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* Speaker notes tests (Task 3):
|
||||
* 1. Read notes (pptx that has a notesSlide)
|
||||
* 2. Write new notes (blank deck, no notesSlide → part auto-created)
|
||||
* 3. Write to a real pptx fixture → save+reopen roundtrip
|
||||
* 4. Iron rule: notesSlide bytes of slides without written notes stay unchanged
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import {
|
||||
createBlankPptx,
|
||||
getSlideNotes,
|
||||
openPptx,
|
||||
savePptx,
|
||||
setSlideNotes,
|
||||
insertBlankSlide,
|
||||
} from '../src/index'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
describe('speaker notes', () => {
|
||||
it('getSlideNotes returns empty string on a fresh deck without notes', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
expect(getSlideNotes(opened.archive, opened.deck.slides[0]!.path)).toBe('')
|
||||
})
|
||||
|
||||
it('getSlideNotes reads back immediately after setSlideNotes', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
expect(setSlideNotes(opened, 0, 'first line\nsecond line')).toBe(true)
|
||||
expect(getSlideNotes(opened.archive, opened.deck.slides[0]!.path)).toBe('first line\nsecond line')
|
||||
})
|
||||
|
||||
it('save → reopen persists notes (notesSlide part auto-created)', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
setSlideNotes(opened, 0, 'Introduce yourself first & special chars <test>')
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideNotes(reopened.archive, reopened.deck.slides[0]!.path)).toBe(
|
||||
'Introduce yourself first & special chars <test>',
|
||||
)
|
||||
// notesSlide part is registered in [Content_Types].xml
|
||||
expect(reopened.archive.readText('[Content_Types].xml')).toContain('notesSlide+xml')
|
||||
// notesMaster has been created
|
||||
expect(reopened.archive.has('ppt/notesMasters/notesMaster1.xml')).toBe(true)
|
||||
})
|
||||
|
||||
it('real pptx fixture → write notes → save+reopen correct', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
setSlideNotes(opened, 0, 'Speaker notes for the first slide')
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideNotes(reopened.archive, reopened.deck.slides[0]!.path)).toBe(
|
||||
'Speaker notes for the first slide',
|
||||
)
|
||||
// Other slides' notes unmodified (no notesSlide, or original note bytes unchanged)
|
||||
if (opened.deck.slides.length > 1) {
|
||||
const slide1Before = getSlideNotes(opened.archive, opened.deck.slides[1]!.path)
|
||||
const slide1After = getSlideNotes(reopened.archive, reopened.deck.slides[1]!.path)
|
||||
expect(slide1After).toBe(slide1Before)
|
||||
}
|
||||
})
|
||||
|
||||
it('clearing notes then saving: reopen returns empty string', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
setSlideNotes(opened, 0, 'temporary note')
|
||||
setSlideNotes(opened, 0, '')
|
||||
expect(getSlideNotes(opened.archive, opened.deck.slides[0]!.path)).toBe('')
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideNotes(reopened.archive, reopened.deck.slides[0]!.path)).toBe('')
|
||||
})
|
||||
|
||||
it('iron rule: slides without written notes gain no notesSlide, existing notesSlide bytes unchanged', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const deck = opened.deck
|
||||
const _slidePath = deck.slides[0]!.path
|
||||
|
||||
// If the fixture already has notesSlides, record the original bytes
|
||||
const notesPathBefore: string[] = []
|
||||
for (const s of deck.slides) {
|
||||
for (const rel of opened.archive.readRels(s.path).values()) {
|
||||
if (rel.type.endsWith('/notesSlide')) {
|
||||
const p = `ppt/${rel.target.replace(/^\.\.\//, '')}`
|
||||
notesPathBefore.push(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Write notes only on page 0; leave other slides untouched
|
||||
setSlideNotes(opened, 0, 'only slide 0 changed')
|
||||
const saved = await savePptx(opened)
|
||||
const reopened = await openPptx(saved)
|
||||
|
||||
// Multi-slide pptx: from slide 1 on, slides without written notes keep notesSlide bytes unchanged (or still absent)
|
||||
if (deck.slides.length > 1) {
|
||||
for (let i = 1; i < deck.slides.length; i++) {
|
||||
const sl = deck.slides[i]!
|
||||
let origNotes: string | null = null
|
||||
for (const rel of opened.archive.readRels(sl.path).values()) {
|
||||
if (rel.type.endsWith('/notesSlide')) {
|
||||
origNotes = opened.archive.readText(`ppt/${rel.target.replace(/^\.\.\//, '')}`)
|
||||
}
|
||||
}
|
||||
let afterNotes: string | null = null
|
||||
for (const rel of reopened.archive.readRels(reopened.deck.slides[i]!.path).values()) {
|
||||
if (rel.type.endsWith('/notesSlide')) {
|
||||
afterNotes = reopened.archive.readText(`ppt/${rel.target.replace(/^\.\.\//, '')}`)
|
||||
}
|
||||
}
|
||||
expect(afterNotes).toBe(origNotes)
|
||||
}
|
||||
}
|
||||
|
||||
// Slide 0 notes were written correctly
|
||||
expect(getSlideNotes(reopened.archive, reopened.deck.slides[0]!.path)).toBe('only slide 0 changed')
|
||||
})
|
||||
|
||||
it('multiple slides: per-slide notes do not interfere', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
// Insert a second slide
|
||||
insertBlankSlide(opened, 0)
|
||||
setSlideNotes(opened, 0, 'slide 0 notes')
|
||||
setSlideNotes(opened, 1, 'slide 1 notes')
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
expect(getSlideNotes(reopened.archive, reopened.deck.slides[0]!.path)).toBe('slide 0 notes')
|
||||
expect(getSlideNotes(reopened.archive, reopened.deck.slides[1]!.path)).toBe('slide 1 notes')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
/** #43-D/E: non-shape spTree children between two shapes (mc:AlternateContent etc.) are preserved verbatim on rebuild. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import JSZip from 'jszip'
|
||||
import { openPptx, savePptx, addElement, createBlankPptx, patchSlideXml } from '../src/index'
|
||||
|
||||
const ALT =
|
||||
'<mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">' +
|
||||
'<mc:Choice Requires="p14"><p:contentPart r:id="rId99"/></mc:Choice>' +
|
||||
'<mc:Fallback><p:sp><p:nvSpPr><p:cNvPr id="90" name="alt"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr/></p:sp></mc:Fallback>' +
|
||||
'</mc:AlternateContent>'
|
||||
|
||||
/** Minimal pptx with mc:AlternateContent injected between two rectangles */
|
||||
async function deckWithGap(): Promise<Buffer> {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
addElement(slide, {
|
||||
kind: 'rect',
|
||||
offset: { x: 0, y: 0, cx: 100, cy: 100 },
|
||||
fillColor: '#111111',
|
||||
})
|
||||
addElement(slide, {
|
||||
kind: 'rect',
|
||||
offset: { x: 200, y: 200, cx: 100, cy: 100 },
|
||||
fillColor: '#222222',
|
||||
})
|
||||
const zip = await JSZip.loadAsync(await savePptx(opened))
|
||||
const xml = await zip.file('ppt/slides/slide1.xml')!.async('string')
|
||||
const at = xml.indexOf('</p:sp>') + '</p:sp>'.length
|
||||
zip.file('ppt/slides/slide1.xml', xml.slice(0, at) + ALT + xml.slice(at))
|
||||
return zip.generateAsync({ type: 'nodebuffer' })
|
||||
}
|
||||
|
||||
describe('non-shape spTree children preserved', () => {
|
||||
it('scan records the gap; rebuild without edits == original bytes', async () => {
|
||||
const opened = await openPptx(await deckWithGap())
|
||||
const slide = opened.deck.slides[0]!
|
||||
expect(slide.elements.some((e) => e.anchor.gapAfter?.includes('mc:AlternateContent'))).toBe(
|
||||
true,
|
||||
)
|
||||
expect(patchSlideXml(slide)).toBe(slide.originalXml)
|
||||
})
|
||||
|
||||
it('after editing a shape and saving, the non-shape fragment between the two shapes keeps its bytes', async () => {
|
||||
const opened = await openPptx(await deckWithGap())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const last = slide.elements[slide.elements.length - 1]!
|
||||
last.transform.offset.x = 999999
|
||||
last.dirtyTransform = true
|
||||
const zip = await JSZip.loadAsync(await savePptx(opened))
|
||||
const xml = await zip.file('ppt/slides/slide1.xml')!.async('string')
|
||||
expect(xml).toContain(ALT)
|
||||
expect(xml).toContain('x="999999"')
|
||||
// The fragment still sits before the edited shape (original position)
|
||||
expect(xml.indexOf(ALT)).toBeLessThan(xml.indexOf('x="999999"'))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,209 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { patchTableStyleXml, ensureTableStyleXml, TABLE_STYLE_PRESETS } from '../src/table-edit'
|
||||
import { resolveTableStyle } from '../src/table-style'
|
||||
|
||||
/** Minimal table graphicFrame XML (with tblPr + 2 tc) */
|
||||
const MINIMAL_TABLE_XML =
|
||||
'<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="5" name="T"/></p:nvGraphicFramePr>' +
|
||||
'<a:graphic><a:graphicData>' +
|
||||
'<a:tbl>' +
|
||||
'<a:tblPr firstRow="1" bandRow="1"><a:tableStyleId>{2D5ABB26-0587-4C30-8999-92F81FD0307C}</a:tableStyleId></a:tblPr>' +
|
||||
'<a:tblGrid><a:gridCol w="1828800"/></a:tblGrid>' +
|
||||
'<a:tr h="914400"><a:tc><a:txBody><a:bodyPr/><a:p/></a:txBody>' +
|
||||
'<a:tcPr><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></a:tcPr></a:tc></a:tr>' +
|
||||
'</a:tbl></a:graphicData></a:graphic></p:graphicFrame>'
|
||||
|
||||
describe('patchTableStyleXml', () => {
|
||||
it('replaces the whole tblPr block (preset style)', () => {
|
||||
const preset = TABLE_STYLE_PRESETS['zebraBlue']!
|
||||
const result = patchTableStyleXml(MINIMAL_TABLE_XML, { tblPrXml: preset.tblPrXml })
|
||||
expect(result).toContain(preset.styleId)
|
||||
expect(result).not.toContain('{2D5ABB26-0587-4C30-8999-92F81FD0307C}')
|
||||
})
|
||||
|
||||
it('changes only the firstRow flag, keeps bandRow and styleId', () => {
|
||||
const result = patchTableStyleXml(MINIMAL_TABLE_XML, { firstRow: false })
|
||||
expect(result).not.toContain('firstRow="1"')
|
||||
expect(result).toContain('bandRow="1"')
|
||||
expect(result).toContain('{2D5ABB26-0587-4C30-8999-92F81FD0307C}')
|
||||
})
|
||||
|
||||
it('set shading color → solidFill inserted in every tcPr, replacing existing fills', () => {
|
||||
const result = patchTableStyleXml(MINIMAL_TABLE_XML, { shadingColor: '#AABBCC' })
|
||||
expect(result).toContain('<a:srgbClr val="AABBCC"/>')
|
||||
// The original FF0000 is replaced
|
||||
expect(result).not.toContain('FF0000')
|
||||
})
|
||||
|
||||
it('clear shading (shadingColor=none) → noFill', () => {
|
||||
const result = patchTableStyleXml(MINIMAL_TABLE_XML, { shadingColor: 'none' })
|
||||
expect(result).toContain('<a:noFill/>')
|
||||
expect(result).not.toContain('FF0000')
|
||||
})
|
||||
|
||||
it('all-borders preset → lnL/lnR/lnT/lnB inserted into tcPr', () => {
|
||||
const result = patchTableStyleXml(MINIMAL_TABLE_XML, {
|
||||
borderPreset: 'all',
|
||||
borderColor: '#000000',
|
||||
borderWidthEmu: 12700,
|
||||
})
|
||||
expect(result).toContain('<a:lnL')
|
||||
expect(result).toContain('<a:lnR')
|
||||
expect(result).toContain('<a:lnT')
|
||||
expect(result).toContain('<a:lnB')
|
||||
})
|
||||
|
||||
it('clear-borders preset → tcPr gains w=0 noFill borders', () => {
|
||||
const result = patchTableStyleXml(MINIMAL_TABLE_XML, { borderPreset: 'none' })
|
||||
expect(result).toContain('<a:lnL w="0"><a:noFill/></a:lnL>')
|
||||
expect(result).toContain('<a:lnT w="0"><a:noFill/></a:lnT>')
|
||||
})
|
||||
|
||||
it('clearDirectFormatting → removes direct tcPr fills and borders, keeps text and margins', () => {
|
||||
const xml =
|
||||
'<a:tbl><a:tblPr/><a:tr><a:tc><a:txBody><a:p><a:r><a:rPr><a:solidFill><a:srgbClr val="F4EFE6"/></a:solidFill></a:rPr><a:t>H</a:t></a:r></a:p></a:txBody>' +
|
||||
'<a:tcPr marL="171907" anchor="ctr"><a:lnL w="0"><a:solidFill><a:srgbClr val="C4B79E"/></a:solidFill></a:lnL><a:lnB w="0"/><a:solidFill><a:srgbClr val="0F3B3A"/></a:solidFill></a:tcPr></a:tc></a:tr></a:tbl>'
|
||||
const result = patchTableStyleXml(xml, {
|
||||
tblPrXml: TABLE_STYLE_PRESETS['zebraGray']!.tblPrXml,
|
||||
clearDirectFormatting: true,
|
||||
})
|
||||
expect(result).toContain(TABLE_STYLE_PRESETS['zebraGray']!.styleId!)
|
||||
expect(result).toContain('<a:tcPr marL="171907" anchor="ctr"></a:tcPr>')
|
||||
expect(result).not.toContain('0F3B3A')
|
||||
expect(result).not.toContain('lnL')
|
||||
// Run-level text color untouched (table style edits never override run-level colors)
|
||||
expect(result).toContain('F4EFE6')
|
||||
})
|
||||
|
||||
it('cells scope: only the targeted cell is patched, siblings untouched', () => {
|
||||
const tc = (fill: string) =>
|
||||
`<a:tc><a:txBody><a:bodyPr/><a:p/></a:txBody><a:tcPr><a:solidFill><a:srgbClr val="${fill}"/></a:solidFill></a:tcPr></a:tc>`
|
||||
const xml =
|
||||
'<p:graphicFrame><a:graphic><a:graphicData><a:tbl><a:tblPr/>' +
|
||||
`<a:tr h="1">${tc('111111')}${tc('222222')}</a:tr>` +
|
||||
`<a:tr h="1">${tc('333333')}${tc('444444')}</a:tr>` +
|
||||
'</a:tbl></a:graphicData></a:graphic></p:graphicFrame>'
|
||||
const result = patchTableStyleXml(xml, {
|
||||
shadingColor: '#AABBCC',
|
||||
cells: [{ row: 1, col: 0 }],
|
||||
})
|
||||
expect(result).toContain('111111')
|
||||
expect(result).toContain('222222')
|
||||
expect(result).toContain('444444')
|
||||
expect(result).not.toContain('333333')
|
||||
expect(result).toContain('<a:srgbClr val="AABBCC"/>')
|
||||
})
|
||||
|
||||
it('cells scope: a whole row and a cell without tcPr both work', () => {
|
||||
const bareTc = '<a:tc><a:txBody><a:bodyPr/><a:p/></a:txBody></a:tc>'
|
||||
const xml =
|
||||
'<a:tbl><a:tblPr/>' +
|
||||
`<a:tr h="1">${bareTc}${bareTc}</a:tr>` +
|
||||
`<a:tr h="1">${bareTc}${bareTc}</a:tr>` +
|
||||
'</a:tbl>'
|
||||
const result = patchTableStyleXml(xml, {
|
||||
shadingColor: '#EFF2FC',
|
||||
cells: [
|
||||
{ row: 0, col: 0 },
|
||||
{ row: 0, col: 1 },
|
||||
],
|
||||
})
|
||||
// Row 0: both cells gain a created tcPr with the fill; row 1 untouched
|
||||
const row1 = result.slice(result.indexOf('<a:tr'), result.indexOf('</a:tr>'))
|
||||
expect((row1.match(/EFF2FC/g) ?? []).length).toBe(2)
|
||||
expect(result.match(/EFF2FC/g)?.length).toBe(2)
|
||||
expect(result).toContain(
|
||||
'<a:tcPr><a:solidFill><a:srgbClr val="EFF2FC"/></a:solidFill></a:tcPr></a:tc>',
|
||||
)
|
||||
})
|
||||
|
||||
it('cells scope: shadingColor none writes noFill only in the target cell', () => {
|
||||
const tc = (fill: string) =>
|
||||
`<a:tc><a:txBody><a:bodyPr/><a:p/></a:txBody><a:tcPr><a:solidFill><a:srgbClr val="${fill}"/></a:solidFill></a:tcPr></a:tc>`
|
||||
const xml = `<a:tbl><a:tblPr/><a:tr h="1">${tc('111111')}${tc('222222')}</a:tr></a:tbl>`
|
||||
const result = patchTableStyleXml(xml, {
|
||||
shadingColor: 'none',
|
||||
cells: [{ row: 0, col: 1 }],
|
||||
})
|
||||
expect(result).toContain('111111')
|
||||
expect(result).not.toContain('222222')
|
||||
expect((result.match(/<a:noFill\/>/g) ?? []).length).toBe(1)
|
||||
})
|
||||
|
||||
it('all 8 preset styles have valid tblPrXml', () => {
|
||||
for (const [key, preset] of Object.entries(TABLE_STYLE_PRESETS)) {
|
||||
expect(preset.tblPrXml).toContain('<a:tblPr')
|
||||
expect(preset.tblPrXml).toContain('</a:tblPr>')
|
||||
expect(preset.description).toBeTruthy()
|
||||
// Check key coverage
|
||||
expect([
|
||||
'none',
|
||||
'lightGrid',
|
||||
'zebraBlue',
|
||||
'zebraGray',
|
||||
'headerDarkBlue',
|
||||
'headerOrange',
|
||||
'noBorder',
|
||||
'fullBorder',
|
||||
]).toContain(key)
|
||||
}
|
||||
expect(Object.keys(TABLE_STYLE_PRESETS)).toHaveLength(8)
|
||||
})
|
||||
|
||||
it('fixed-color presets: styleDefXml uses literal srgbClr, tblPr references the same styleId', () => {
|
||||
for (const key of ['zebraBlue', 'zebraGray', 'headerDarkBlue', 'headerOrange', 'noBorder']) {
|
||||
const p = TABLE_STYLE_PRESETS[key]!
|
||||
expect(p.styleId).toBeTruthy()
|
||||
expect(p.styleDefXml).toContain(`styleId="${p.styleId}"`)
|
||||
expect(p.tblPrXml).toContain(p.styleId!)
|
||||
expect(p.styleDefXml).not.toContain('schemeClr')
|
||||
}
|
||||
// Dark-blue/orange presets: header color matches the ribbon swatch
|
||||
expect(TABLE_STYLE_PRESETS['headerDarkBlue']!.styleDefXml).toContain('val="1F3864"')
|
||||
expect(TABLE_STYLE_PRESETS['headerOrange']!.styleDefXml).toContain('val="ED7D31"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ensureTableStyleXml', () => {
|
||||
const DEF = TABLE_STYLE_PRESETS['headerDarkBlue']!.styleDefXml!
|
||||
const ID = TABLE_STYLE_PRESETS['headerDarkBlue']!.styleId!
|
||||
|
||||
it('self-closing tblStyleLst → expanded with the definition inserted', () => {
|
||||
const src =
|
||||
'<?xml version="1.0"?><a:tblStyleLst xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" def="{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"/>'
|
||||
const out = ensureTableStyleXml(src, ID, DEF)
|
||||
expect(out).toContain(`styleId="${ID}"`)
|
||||
expect(out).toContain('</a:tblStyleLst>')
|
||||
expect(out).toContain('def="{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"')
|
||||
})
|
||||
|
||||
it('idempotent when the definition already exists', () => {
|
||||
const once = ensureTableStyleXml(null, ID, DEF)
|
||||
expect(ensureTableStyleXml(once, ID, DEF)).toBe(once)
|
||||
})
|
||||
|
||||
it('missing part (null) → created from the empty template', () => {
|
||||
const out = ensureTableStyleXml(null, ID, DEF)
|
||||
expect(out).toContain('<a:tblStyleLst')
|
||||
expect(out).toContain(`styleId="${ID}"`)
|
||||
})
|
||||
|
||||
it('non-self-closing list → appended at the end', () => {
|
||||
const zebra = TABLE_STYLE_PRESETS['zebraBlue']!
|
||||
const withOne = ensureTableStyleXml(null, ID, DEF)
|
||||
const withTwo = ensureTableStyleXml(withOne, zebra.styleId!, zebra.styleDefXml!)
|
||||
expect(withTwo).toContain(`styleId="${ID}"`)
|
||||
expect(withTwo).toContain(`styleId="${zebra.styleId}"`)
|
||||
})
|
||||
|
||||
it('loop back: resolveTableStyle parses the preset literal colors', () => {
|
||||
const xml = ensureTableStyleXml(null, ID, DEF)
|
||||
const def = resolveTableStyle(ID, xml, undefined)
|
||||
expect(def?.firstRow?.fill).toEqual({ type: 'solid', color: '#1F3864' })
|
||||
expect(def?.firstRow?.textColor).toBe('#FFFFFF')
|
||||
expect(def?.firstRow?.bold).toBe(true)
|
||||
expect(def?.band1H?.fill).toEqual({ type: 'solid', color: '#E9EDF5' })
|
||||
expect(def?.wholeTbl?.fill).toEqual({ type: 'solid', color: '#FFFFFF' })
|
||||
expect(def?.insideH?.fill).toEqual({ type: 'solid', color: '#D9D9D9' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
/** Table cell merge/split: byte surgery + reparse + save/reopen round-trip. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { addTable, editTableCellText, mergeTableCells, openPptx, savePptx } from '../src/index'
|
||||
import type { TableElement } from '../src/types'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
async function makeTable() {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addTable(opened, 0, {
|
||||
rows: 3,
|
||||
cols: 3,
|
||||
offset: { x: 914400, y: 914400, cx: 4572000, cy: 1828800 },
|
||||
})!
|
||||
editTableCellText(r.slide, r.elementId, 0, 0, [{ runs: [{ text: 'A1' }] }])
|
||||
editTableCellText(r.slide, r.elementId, 0, 1, [{ runs: [{ text: 'B1' }] }])
|
||||
return { opened, slideIndex: 0, tblId: r.elementId }
|
||||
}
|
||||
|
||||
const tableOf = (opened: Awaited<ReturnType<typeof makeTable>>['opened'], id: string) =>
|
||||
opened.deck.slides[0]!.elements.find((e) => e.id === id) as TableElement
|
||||
|
||||
describe('mergeTableCells', () => {
|
||||
it('merge right: gridSpan + hMerge + text merged into the anchor cell', async () => {
|
||||
const { opened, tblId } = await makeTable()
|
||||
const r = mergeTableCells(opened, 0, tblId, { kind: 'merge-right', row: 0, col: 0 })
|
||||
expect(r).not.toBeNull()
|
||||
const tbl = tableOf(opened, r!.elementId)
|
||||
expect(tbl.rows[0]![0]!.gridSpan).toBe(2)
|
||||
expect(tbl.rows[0]![1]!.merged).toBe(true)
|
||||
const anchorText = tbl.rows[0]![0]!.text!.paragraphs.map((p) =>
|
||||
p.runs.map((x) => x.text).join(''),
|
||||
).join('|')
|
||||
expect(anchorText).toContain('A1')
|
||||
expect(anchorText).toContain('B1')
|
||||
})
|
||||
|
||||
it('merge down + save/reopen preserves rowSpan/vMerge', async () => {
|
||||
const { opened, tblId } = await makeTable()
|
||||
const r = mergeTableCells(opened, 0, tblId, { kind: 'merge-down', row: 0, col: 0 })!
|
||||
const saved = await savePptx(opened)
|
||||
const reopened = await openPptx(saved)
|
||||
const tbl = reopened.deck.slides[0]!.elements.find((e) => e.type === 'table') as TableElement
|
||||
expect(tbl.rows[0]![0]!.rowSpan).toBe(2)
|
||||
expect(tbl.rows[1]![0]!.merged).toBe(true)
|
||||
expect(r.elementId).toBeTruthy()
|
||||
})
|
||||
|
||||
it('consecutive merge-right extends gridSpan', async () => {
|
||||
const { opened, tblId } = await makeTable()
|
||||
const r1 = mergeTableCells(opened, 0, tblId, { kind: 'merge-right', row: 0, col: 0 })!
|
||||
const r2 = mergeTableCells(opened, 0, r1.elementId, { kind: 'merge-right', row: 0, col: 0 })!
|
||||
const tbl = tableOf(opened, r2.elementId)
|
||||
expect(tbl.rows[0]![0]!.gridSpan).toBe(3)
|
||||
})
|
||||
|
||||
it('split: clears spans and continuation markers', async () => {
|
||||
const { opened, tblId } = await makeTable()
|
||||
const r1 = mergeTableCells(opened, 0, tblId, { kind: 'merge-right', row: 1, col: 0 })!
|
||||
const r2 = mergeTableCells(opened, 0, r1.elementId, { kind: 'split', row: 1, col: 0 })!
|
||||
const tbl = tableOf(opened, r2.elementId)
|
||||
expect(tbl.rows[1]![0]!.gridSpan ?? 1).toBe(1)
|
||||
expect(tbl.rows[1]![1]!.merged ?? false).toBe(false)
|
||||
})
|
||||
|
||||
it('invalid targets rejected: merging on a continuation cell / splitting a plain cell', async () => {
|
||||
const { opened, tblId } = await makeTable()
|
||||
const r1 = mergeTableCells(opened, 0, tblId, { kind: 'merge-right', row: 0, col: 0 })!
|
||||
expect(
|
||||
mergeTableCells(opened, 0, r1.elementId, { kind: 'merge-right', row: 0, col: 1 }),
|
||||
).toBeNull()
|
||||
expect(mergeTableCells(opened, 0, r1.elementId, { kind: 'split', row: 2, col: 0 })).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,119 @@
|
||||
/** Table row height setting + cell/textbox vertical alignment. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import {
|
||||
addTable,
|
||||
openPptx,
|
||||
savePptx,
|
||||
resizeTable,
|
||||
setTableRowHeight,
|
||||
setTableCellAnchor,
|
||||
setElementTextAnchor,
|
||||
addElement,
|
||||
createBlankPptx,
|
||||
} from '../src/index'
|
||||
import type { TableElement, TextElement } from '../src/types'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
describe('setTableRowHeight', () => {
|
||||
it('row height written to a:tr h, outer frame cy kept in sync', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addTable(opened, 0, {
|
||||
rows: 2,
|
||||
cols: 2,
|
||||
offset: { x: 0, y: 0, cx: 2000000, cy: 800000 },
|
||||
})!
|
||||
const tbl = r.slide.elements.find((e) => e.id === r.elementId) as TableElement
|
||||
const h0 = tbl.rowHeights[0]!
|
||||
expect(setTableRowHeight(r.slide, r.elementId, 0, h0 * 2)).toBe(true)
|
||||
expect(tbl.rowHeights[0]).toBe(h0 * 2)
|
||||
expect(tbl.anchor.originalXml).toContain(`<a:tr h="${h0 * 2}"`)
|
||||
const sum = tbl.rowHeights.reduce((a, b) => a + b, 0)
|
||||
expect(tbl.transform.offset.cy).toBe(sum)
|
||||
expect(setTableRowHeight(r.slide, r.elementId, 9, 100)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resizeTable', () => {
|
||||
it('redistributes gridCol widths and tr heights so XML sums match the frame', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addTable(opened, 0, {
|
||||
rows: 3,
|
||||
cols: 4,
|
||||
offset: { x: 0, y: 0, cx: 2000000, cy: 900000 },
|
||||
})!
|
||||
const tbl = r.slide.elements.find((e) => e.id === r.elementId) as TableElement
|
||||
|
||||
expect(resizeTable(r.slide, r.elementId, 1000000, 600000)).toBe(true)
|
||||
expect(tbl.colWidths.reduce((a, b) => a + b, 0)).toBe(1000000)
|
||||
expect(tbl.rowHeights.reduce((a, b) => a + b, 0)).toBe(600000)
|
||||
expect(tbl.transform.offset.cx).toBe(1000000)
|
||||
expect(tbl.transform.offset.cy).toBe(600000)
|
||||
|
||||
// XML agrees with the model: gridCol/tr h rewritten, ext synced
|
||||
const xml = tbl.anchor.originalXml
|
||||
const colSum = [...xml.matchAll(/<a:gridCol w="(\d+)"/g)].reduce((a, m) => a + Number(m[1]), 0)
|
||||
const rowSum = [...xml.matchAll(/<a:tr h="(\d+)"/g)].reduce((a, m) => a + Number(m[1]), 0)
|
||||
expect(colSum).toBe(1000000)
|
||||
expect(rowSum).toBe(600000)
|
||||
expect(xml).toMatch(/<a:ext cx="1000000" cy="600000"\/>/)
|
||||
})
|
||||
|
||||
it('proportions survive save → reopen', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addTable(opened, 0, {
|
||||
rows: 2,
|
||||
cols: 2,
|
||||
offset: { x: 0, y: 0, cx: 2000000, cy: 800000 },
|
||||
})!
|
||||
// make col0 twice col1, then shrink the table by half
|
||||
expect(resizeTable(r.slide, r.elementId, 2000000, 800000)).toBe(true)
|
||||
const tbl = r.slide.elements.find((e) => e.id === r.elementId) as TableElement
|
||||
tbl.colWidths = [1333334, 666666]
|
||||
expect(resizeTable(r.slide, r.elementId, 1000000, 400000)).toBe(true)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const tbl2 = reopened.deck.slides[0]!.elements.find((e) => e.type === 'table') as TableElement
|
||||
expect(tbl2.colWidths.reduce((a, b) => a + b, 0)).toBe(1000000)
|
||||
expect(tbl2.colWidths[0]).toBeGreaterThan(tbl2.colWidths[1]! * 1.9)
|
||||
expect(tbl2.rowHeights.reduce((a, b) => a + b, 0)).toBe(400000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setTableCellAnchor', () => {
|
||||
it('tcPr anchor written / replaced', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addTable(opened, 0, {
|
||||
rows: 2,
|
||||
cols: 2,
|
||||
offset: { x: 0, y: 0, cx: 2000000, cy: 800000 },
|
||||
})!
|
||||
expect(setTableCellAnchor(r.slide, r.elementId, 0, 0, 'middle')).toBe(true)
|
||||
const tbl = r.slide.elements.find((e) => e.id === r.elementId) as TableElement
|
||||
expect(tbl.anchor.originalXml).toMatch(/<a:tcPr anchor="ctr"/)
|
||||
expect(setTableCellAnchor(r.slide, r.elementId, 0, 0, 'bottom')).toBe(true)
|
||||
expect(tbl.anchor.originalXml).toMatch(/<a:tcPr anchor="b"/)
|
||||
expect(tbl.anchor.originalXml).not.toMatch(/anchor="ctr"[^>]*anchor=/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setElementTextAnchor', () => {
|
||||
it('bodyPr anchor written, model kept in sync', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, {
|
||||
kind: 'textbox',
|
||||
offset: { x: 0, y: 0, cx: 1000, cy: 1000 },
|
||||
paragraphs: [{ runs: [{ text: 'x' }] }],
|
||||
})
|
||||
expect(setElementTextAnchor(slide, el.id, 'middle')).toBe(true)
|
||||
expect(el.anchor.originalXml).toMatch(/<a:bodyPr anchor="ctr"/)
|
||||
expect((el as TextElement).text!.anchor).toBe('middle')
|
||||
expect(setElementTextAnchor(slide, el.id, 'top')).toBe(true)
|
||||
expect(el.anchor.originalXml).toMatch(/<a:bodyPr anchor="t"/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { resolveTableStyle } from '../src/table-style'
|
||||
import type { Theme } from '../src/theme'
|
||||
|
||||
const theme = {
|
||||
colors: {
|
||||
dk1: '#000000',
|
||||
lt1: '#FFFFFF',
|
||||
accent1: '#4472C4',
|
||||
accent2: '#ED7D31',
|
||||
},
|
||||
} as unknown as Theme
|
||||
|
||||
const MEDIUM2_A1 = '{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}'
|
||||
|
||||
function tableSlideXml(tblPrAttrs: string, styleId: string): string {
|
||||
const tc = (t: string) =>
|
||||
`<a:tc><a:txBody><a:bodyPr/><a:p><a:r><a:t>${t}</a:t></a:r></a:p></a:txBody><a:tcPr/></a:tc>`
|
||||
return (
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/>' +
|
||||
'<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="9" name="T"/></p:nvGraphicFramePr>' +
|
||||
'<p:xfrm><a:off x="0" y="0"/><a:ext cx="3657600" cy="2743200"/></p:xfrm>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/table"><a:tbl>' +
|
||||
`<a:tblPr ${tblPrAttrs}><a:tableStyleId>${styleId}</a:tableStyleId></a:tblPr>` +
|
||||
'<a:tblGrid><a:gridCol w="1828800"/><a:gridCol w="1828800"/></a:tblGrid>' +
|
||||
`<a:tr h="914400">${tc('H1')}${tc('H2')}</a:tr>` +
|
||||
`<a:tr h="914400">${tc('A1')}${tc('A2')}</a:tr>` +
|
||||
`<a:tr h="914400">${tc('B1')}${tc('B2')}</a:tr>` +
|
||||
'</a:tbl></a:graphicData></a:graphic></p:graphicFrame>' +
|
||||
'</p:spTree></p:cSld></p:sld>'
|
||||
)
|
||||
}
|
||||
|
||||
describe('built-in table style Medium Style 2 (PowerPoint default)', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: tableSlideXml('firstRow="1" bandRow="1"', MEDIUM2_A1),
|
||||
ctx: { theme },
|
||||
})
|
||||
const tbl = slide.elements[0] as any
|
||||
|
||||
it('header row: solid accent1 fill + bold white text', () => {
|
||||
const h = tbl.rows[0][0]
|
||||
expect(h.fill).toEqual({ type: 'solid', color: '#4472C4' })
|
||||
const run = h.text.paragraphs[0].runs[0]
|
||||
expect(run.bold).toBe(true)
|
||||
expect(run.color).toBe('#FFFFFF')
|
||||
})
|
||||
|
||||
it('banded rows: odd data rows 40% tint, even 20% tint (wholeTbl)', () => {
|
||||
// accent1 #4472C4: 40% tint = 255*0.6 + c*0.4
|
||||
expect(tbl.rows[1][0].fill.color).toBe('#B4C7E7')
|
||||
expect(tbl.rows[2][0].fill.color).toBe('#DAE3F3')
|
||||
})
|
||||
|
||||
it('inner separator lines + outer border: lt1 white lines (last-row bottom edge comes from the outer border)', () => {
|
||||
expect(tbl.rows[0][0].borders.b.fill.color).toBe('#FFFFFF')
|
||||
expect(tbl.rows[0][0].borders.r.fill.color).toBe('#FFFFFF')
|
||||
expect(tbl.rows[2][0].borders.b.fill.color).toBe('#FFFFFF')
|
||||
expect(tbl.rows[0][1].borders.r.fill.color).toBe('#FFFFFF')
|
||||
expect(tbl.rows[0][0].borders.t.fill.color).toBe('#FFFFFF')
|
||||
expect(tbl.rows[0][0].borders.l.fill.color).toBe('#FFFFFF')
|
||||
})
|
||||
|
||||
it('data row text not bold, color dk1', () => {
|
||||
const run = tbl.rows[1][0].text.paragraphs[0].runs[0]
|
||||
expect(run.bold).toBe(false)
|
||||
expect(run.color).toBe('#000000')
|
||||
})
|
||||
})
|
||||
|
||||
describe('tableStyles.xml custom styles', () => {
|
||||
const xml =
|
||||
'<?xml version="1.0"?><a:tblStyleLst xmlns:a="a" def="{X}">' +
|
||||
'<a:tblStyle styleId="{X}" styleName="Custom">' +
|
||||
'<a:wholeTbl><a:tcTxStyle><a:schemeClr val="dk1"/></a:tcTxStyle>' +
|
||||
'<a:tcStyle><a:fill><a:solidFill><a:srgbClr val="EEEEEE"/></a:solidFill></a:fill></a:tcStyle></a:wholeTbl>' +
|
||||
'<a:firstRow><a:tcTxStyle b="on"><a:schemeClr val="lt1"/></a:tcTxStyle>' +
|
||||
'<a:tcStyle><a:fill><a:solidFill><a:srgbClr val="AA0000"/></a:solidFill></a:fill></a:tcStyle></a:firstRow>' +
|
||||
'</a:tblStyle></a:tblStyleLst>'
|
||||
|
||||
it('parses wholeTbl/firstRow fill and text styles', () => {
|
||||
const def = resolveTableStyle('{X}', xml, theme)!
|
||||
expect(def.wholeTbl?.fill).toEqual({ type: 'solid', color: '#EEEEEE' })
|
||||
expect(def.wholeTbl?.textColor).toBe('#000000')
|
||||
expect(def.firstRow?.fill).toEqual({ type: 'solid', color: '#AA0000' })
|
||||
expect(def.firstRow?.bold).toBe(true)
|
||||
expect(def.firstRow?.textColor).toBe('#FFFFFF')
|
||||
})
|
||||
|
||||
it('unknown styleId that is not built-in → undefined (stays unstyled)', () => {
|
||||
expect(resolveTableStyle('{DEAD-BEEF}', xml, theme)).toBeUndefined()
|
||||
expect(resolveTableStyle(undefined, xml, theme)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('built-in style family expansion (full GUID table)', () => {
|
||||
it('Light Style 1 - Accent1: no whole-table fill, 20% pre-blended bands, bold first row + accent separator line', () => {
|
||||
const def = resolveTableStyle('{3B4B98B0-60AC-42C2-AFA5-B58CD77FA1E5}', undefined, theme)!
|
||||
expect(def.wholeTbl?.fill).toBeUndefined()
|
||||
expect(def.firstRow?.bold).toBe(true)
|
||||
// accent1 20% alpha over white = #DAE3F3
|
||||
expect(def.band1H?.fill).toEqual({ type: 'solid', color: '#DAE3F3' })
|
||||
expect(def.firstRowBottom?.fill).toEqual({ type: 'solid', color: '#4472C4' })
|
||||
expect(def.outer?.t?.fill).toEqual({ type: 'solid', color: '#4472C4' })
|
||||
expect(def.outer?.l).toBeUndefined() // Light1 only has top/bottom outer borders
|
||||
})
|
||||
|
||||
it('Dark Style 1 - Accent1: shade dark background + light text; no-accent variant tint light background dark text', () => {
|
||||
const dark = resolveTableStyle('{125E5076-3810-47DD-B79F-674D7AD40C01}', undefined, theme)!
|
||||
// accent1 shade 20% = #0E1727
|
||||
expect(dark.wholeTbl?.fill).toEqual({ type: 'solid', color: '#0E1727' })
|
||||
expect(dark.wholeTbl?.textColor).toBe('#FFFFFF')
|
||||
expect(dark.firstRow?.fill).toEqual({ type: 'solid', color: '#000000' })
|
||||
const base = resolveTableStyle('{E8034E78-7F5D-4C2E-B375-FC64B27BC917}', undefined, theme)!
|
||||
expect(base.wholeTbl?.fill).toEqual({ type: 'solid', color: '#CCCCCC' }) // dk1 tint 20%
|
||||
expect(base.wholeTbl?.textColor).toBe('#000000')
|
||||
})
|
||||
|
||||
it('Dark Style 2 - Accent1: header uses the paired color accent2', () => {
|
||||
const def = resolveTableStyle('{0660B408-B3CF-4A94-85FC-2B1E0A45F4A2}', undefined, theme)!
|
||||
expect(def.firstRow?.fill).toEqual({ type: 'solid', color: '#ED7D31' })
|
||||
})
|
||||
|
||||
it('No Style, Table Grid (themed2 without accent): all-dk1 grid including outer border', () => {
|
||||
const def = resolveTableStyle('{5940675A-B579-460E-94D1-54222C63F5DA}', undefined, theme)!
|
||||
expect(def.insideH?.fill).toEqual({ type: 'solid', color: '#000000' })
|
||||
expect(def.outer?.t?.fill).toEqual({ type: 'solid', color: '#000000' })
|
||||
expect(def.wholeTbl?.fill).toBeUndefined()
|
||||
})
|
||||
|
||||
it('No Style, No Grid (official 307C) and the legacy made-up 307D both resolve to no style', () => {
|
||||
const noGrid = resolveTableStyle('{2D5ABB26-0587-4C30-8999-92F81FD0307C}', undefined, theme)!
|
||||
expect(noGrid.insideH).toBeUndefined()
|
||||
expect(noGrid.firstRow).toBeUndefined()
|
||||
expect(resolveTableStyle('{2D5ABB26-0587-4C30-8999-92F81FD0307D}', undefined, theme)).toEqual(
|
||||
{},
|
||||
)
|
||||
})
|
||||
|
||||
it('Medium Style 3 - Accent2: first/last columns solid accent fill, outer border only top/bottom dk1', () => {
|
||||
const def = resolveTableStyle('{85BE263C-DBD7-4A20-BB59-AAB30ACAA65A}', undefined, theme)!
|
||||
expect(def.firstCol?.fill).toEqual({ type: 'solid', color: '#ED7D31' })
|
||||
expect(def.lastCol?.textColor).toBe('#FFFFFF')
|
||||
expect(def.outer?.t?.fill).toEqual({ type: 'solid', color: '#000000' })
|
||||
expect(def.outer?.l).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* Theme fmtScheme template inheritance: p:style's fillRef/lnRef/effectRef take the
|
||||
* fillStyleLst/lnStyleLst/effectStyleLst template by idx and substitute phClr.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseTheme } from '../src/theme'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { applyColorMods } from '../src/color'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
// Trimmed-down Office theme: fillStyleLst = [solid, linear gradient, radial gradient],
|
||||
// lnStyleLst has three line widths (6350/12700/19050, second entry dashed), effectStyleLst third entry has shadow + glow
|
||||
const THEME_XML =
|
||||
'<?xml version="1.0"?><a:theme xmlns:a="a" name="T"><a:themeElements>' +
|
||||
'<a:clrScheme name="c"><a:dk1><a:srgbClr val="000000"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1>' +
|
||||
'<a:dk2><a:srgbClr val="44546A"/></a:dk2><a:lt2><a:srgbClr val="E7E6E6"/></a:lt2>' +
|
||||
'<a:accent1><a:srgbClr val="4472C4"/></a:accent1><a:accent2><a:srgbClr val="ED7D31"/></a:accent2>' +
|
||||
'<a:accent3><a:srgbClr val="A5A5A5"/></a:accent3><a:accent4><a:srgbClr val="FFC000"/></a:accent4>' +
|
||||
'<a:accent5><a:srgbClr val="5B9BD5"/></a:accent5><a:accent6><a:srgbClr val="70AD47"/></a:accent6>' +
|
||||
'<a:hlink><a:srgbClr val="0563C1"/></a:hlink><a:folHlink><a:srgbClr val="954F72"/></a:folHlink></a:clrScheme>' +
|
||||
'<a:fontScheme name="f"><a:majorFont><a:latin typeface="Calibri Light"/></a:majorFont>' +
|
||||
'<a:minorFont><a:latin typeface="Calibri"/></a:minorFont></a:fontScheme>' +
|
||||
'<a:fmtScheme name="Office">' +
|
||||
'<a:fillStyleLst>' +
|
||||
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
|
||||
'<a:gradFill rotWithShape="1"><a:gsLst>' +
|
||||
'<a:gs pos="0"><a:schemeClr val="phClr"><a:lumMod val="110000"/><a:satMod val="105000"/><a:tint val="67000"/></a:schemeClr></a:gs>' +
|
||||
'<a:gs pos="100000"><a:schemeClr val="phClr"><a:lumMod val="105000"/><a:satMod val="109000"/><a:tint val="81000"/></a:schemeClr></a:gs>' +
|
||||
'</a:gsLst><a:lin ang="5400000" scaled="0"/></a:gradFill>' +
|
||||
'<a:gradFill rotWithShape="1"><a:gsLst>' +
|
||||
'<a:gs pos="0"><a:schemeClr val="phClr"><a:satMod val="103000"/></a:schemeClr></a:gs>' +
|
||||
'<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="78000"/></a:schemeClr></a:gs>' +
|
||||
'</a:gsLst><a:path path="circle"><a:fillToRect l="50000" t="50000" r="50000" b="50000"/></a:path></a:gradFill>' +
|
||||
'</a:fillStyleLst>' +
|
||||
'<a:lnStyleLst>' +
|
||||
'<a:ln w="6350" cap="flat"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>' +
|
||||
'<a:ln w="12700" cap="flat"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="dash"/></a:ln>' +
|
||||
'<a:ln w="19050" cap="flat"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>' +
|
||||
'</a:lnStyleLst>' +
|
||||
'<a:effectStyleLst>' +
|
||||
'<a:effectStyle><a:effectLst/></a:effectStyle>' +
|
||||
'<a:effectStyle><a:effectLst/></a:effectStyle>' +
|
||||
'<a:effectStyle><a:effectLst>' +
|
||||
'<a:glow rad="63500"><a:schemeClr val="phClr"><a:alpha val="40000"/></a:schemeClr></a:glow>' +
|
||||
'<a:outerShdw blurRad="57150" dist="19050" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="63000"/></a:srgbClr></a:outerShdw>' +
|
||||
'</a:effectLst></a:effectStyle>' +
|
||||
'</a:effectStyleLst>' +
|
||||
'<a:bgFillStyleLst>' +
|
||||
'<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
|
||||
'<a:solidFill><a:schemeClr val="phClr"><a:tint val="95000"/></a:schemeClr></a:solidFill>' +
|
||||
'<a:gradFill><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"/></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="60000"/></a:schemeClr></a:gs></a:gsLst><a:lin ang="0" scaled="1"/></a:gradFill>' +
|
||||
'</a:bgFillStyleLst>' +
|
||||
'</a:fmtScheme></a:themeElements></a:theme>'
|
||||
|
||||
const theme = parseTheme(THEME_XML)
|
||||
|
||||
const slideWith = (body: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${body}</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
const shapeWithStyle = (style: string, spPrExtra = '') =>
|
||||
'<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="1000" cy="1000"/></a:xfrm>' +
|
||||
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>${spPrExtra}</p:spPr>` +
|
||||
`<p:style>${style}</p:style>` +
|
||||
'<p:txBody><a:bodyPr/><a:p><a:r><a:t>x</a:t></a:r></a:p></p:txBody></p:sp>'
|
||||
|
||||
const STYLE_REFS =
|
||||
'<a:lnRef idx="2"><a:schemeClr val="accent1"/></a:lnRef>' +
|
||||
'<a:fillRef idx="2"><a:schemeClr val="accent2"/></a:fillRef>' +
|
||||
'<a:effectRef idx="3"><a:schemeClr val="accent1"/></a:effectRef>' +
|
||||
'<a:fontRef idx="minor"><a:schemeClr val="dk1"/></a:fontRef>'
|
||||
|
||||
describe('parseTheme fmtScheme', () => {
|
||||
it('fillStyleLst/lnStyleLst/effectStyleLst/bgFillStyleLst parse in order', () => {
|
||||
expect(theme.fillStyles).toHaveLength(3)
|
||||
expect(theme.fillStyles![0]['a:solidFill']).toBeTruthy()
|
||||
expect(theme.fillStyles![1]['a:gradFill']).toBeTruthy()
|
||||
expect(theme.lnStyles).toHaveLength(3)
|
||||
expect((theme.lnStyles![1]!['a:ln'] as Record<string, unknown>)['@_w']).toBe('12700')
|
||||
expect(theme.effectStyles).toHaveLength(3)
|
||||
expect(theme.bgFillStyles).toHaveLength(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('p:style references -> fmtScheme templates', () => {
|
||||
const parse = () =>
|
||||
parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(shapeWithStyle(STYLE_REFS)), ctx: { theme } })
|
||||
|
||||
it('fillRef idx=2 -> linear gradient template, phClr substituted with accent2 and modifiers applied', () => {
|
||||
const el = parse().elements[0] as TextElement
|
||||
expect(el.fill?.type).toBe('gradient')
|
||||
const grad = el.fill as Extract<TextElement['fill'], { type: 'gradient' }>
|
||||
expect(grad.stops).toHaveLength(2)
|
||||
expect(grad.angle).toBe(5400000)
|
||||
// First stop = accent2 + lumMod 110% + satMod 105% + tint 67%
|
||||
const expected = applyColorMods('#ED7D31', {
|
||||
'a:lumMod': { '@_val': '110000' },
|
||||
'a:satMod': { '@_val': '105000' },
|
||||
'a:tint': { '@_val': '67000' },
|
||||
})
|
||||
expect(grad.stops[0]!.color).toBe(expected)
|
||||
expect(grad.stops[0]!.color).not.toBe('#ED7D31')
|
||||
})
|
||||
|
||||
it('lnRef idx=2 -> template line width 12700 + dash (no longer hardcoded 1pt solid)', () => {
|
||||
const el = parse().elements[0] as TextElement
|
||||
expect(el.stroke?.width).toBe(12700)
|
||||
expect(el.stroke?.dash).toBe('dash')
|
||||
expect(el.stroke?.fill).toEqual({ type: 'solid', color: '#4472C4' })
|
||||
})
|
||||
|
||||
it('effectRef idx=3 -> shadow + glow (phClr substituted with the reference color)', () => {
|
||||
const el = parse().elements[0] as TextElement
|
||||
expect(el.shadow).toBeTruthy()
|
||||
expect(el.shadow!.blurRad).toBe(57150)
|
||||
expect(el.shadow!.dist).toBe(19050)
|
||||
expect(el.shadow!.color.startsWith('#000000')).toBe(true)
|
||||
expect(el.glow).toBeTruthy()
|
||||
expect(el.glow!.radius).toBe(63500)
|
||||
expect(el.glow!.color.startsWith('#4472C4')).toBe(true)
|
||||
})
|
||||
|
||||
it('fillRef idx=1001 -> first entry of bgFillStyleLst', () => {
|
||||
const style =
|
||||
'<a:lnRef idx="0"/><a:fillRef idx="1001"><a:schemeClr val="accent3"/></a:fillRef>' +
|
||||
'<a:effectRef idx="0"/><a:fontRef idx="minor"/>'
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(shapeWithStyle(style)), ctx: { theme } })
|
||||
expect((slide.elements[0] as TextElement).fill).toEqual({ type: 'solid', color: '#A5A5A5' })
|
||||
})
|
||||
|
||||
it('explicit spPr fill/stroke wins over style references (not overridden by templates)', () => {
|
||||
const explicit = '<a:solidFill><a:srgbClr val="112233"/></a:solidFill><a:ln w="25400"><a:solidFill><a:srgbClr val="445566"/></a:solidFill></a:ln>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(shapeWithStyle(STYLE_REFS, explicit)),
|
||||
ctx: { theme },
|
||||
})
|
||||
const el = slide.elements[0] as TextElement
|
||||
expect(el.fill).toEqual({ type: 'solid', color: '#112233' })
|
||||
expect(el.stroke?.width).toBe(25400)
|
||||
})
|
||||
|
||||
it('explicit <a:ln><a:noFill/> wins over lnRef: no stroke is drawn (#102)', () => {
|
||||
const noOutline = '<a:ln><a:noFill/></a:ln>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(shapeWithStyle(STYLE_REFS, noOutline)),
|
||||
ctx: { theme },
|
||||
})
|
||||
expect((slide.elements[0] as TextElement).stroke).toBeUndefined()
|
||||
})
|
||||
|
||||
it('connector with explicit <a:ln><a:noFill/> draws no stroke; absent a:ln still falls back (#102)', () => {
|
||||
const cxn = (ln: string) =>
|
||||
'<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="7" name="C"/><p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1000" cy="1000"/></a:xfrm>' +
|
||||
`<a:prstGeom prst="line"><a:avLst/></a:prstGeom>${ln}</p:spPr></p:cxnSp>`
|
||||
const parseCxn = (ln: string) =>
|
||||
parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(cxn(ln)), ctx: { theme } })
|
||||
.elements[0] as TextElement
|
||||
expect(parseCxn('<a:ln><a:noFill/></a:ln>').stroke).toBeUndefined()
|
||||
expect(parseCxn('').stroke).toBeTruthy()
|
||||
})
|
||||
|
||||
it('theme without fmtScheme (legacy behavior): falls back to reference-color solid + 1pt', () => {
|
||||
const bare: any = { colors: { accent1: '#4472C4', accent2: '#ED7D31', dk1: '#000000' } }
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: slideWith(shapeWithStyle(STYLE_REFS)), ctx: { theme: bare } })
|
||||
const el = slide.elements[0] as TextElement
|
||||
expect(el.fill?.type).toBe('solid')
|
||||
expect(el.stroke?.width).toBe(12700)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { openPptx, savePptx, patchElementXfrm } from '../src/index'
|
||||
import type { SlideElement } from '../src/types'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const fx = (name: string) => readFileSync(join(here, 'fixtures', name))
|
||||
|
||||
const OFF = { x: 914400, y: 457200, cx: 3657600, cy: 1828800 }
|
||||
|
||||
describe('dirtyTransform xfrm patch', () => {
|
||||
it('save → reopen round-trips new geometry', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = slide.elements.find((e) => e.type === 'text' || e.type === 'shape')!
|
||||
el.transform = { ...el.transform, offset: { ...OFF }, rot: 15 * 60000 }
|
||||
el.dirtyTransform = true
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2 = reopened.deck.slides[0]!.elements.find(
|
||||
(e) => e.anchor.spIndex === el.anchor.spIndex,
|
||||
)!
|
||||
expect(el2.transform.offset).toEqual(OFF)
|
||||
expect(el2.transform.rot).toBe(15 * 60000)
|
||||
})
|
||||
|
||||
it('text dirty + transform dirty compose on the same element', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides.find((s) =>
|
||||
s.elements.some((e: any) => (e.type === 'text' || e.type === 'shape') && e.text?.paragraphs?.length),
|
||||
)!
|
||||
const el: any = slide.elements.find(
|
||||
(e: any) => (e.type === 'text' || e.type === 'shape') && e.text?.paragraphs?.length,
|
||||
)!
|
||||
el.text.paragraphs = [{ runs: [{ text: 'combined patch', bold: true }] }]
|
||||
el.dirty = true
|
||||
el.transform = { ...el.transform, offset: { ...OFF }, rot: 0 }
|
||||
el.dirtyTransform = true
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const slideIdx = opened.deck.slides.indexOf(slide)
|
||||
const el2: any = reopened.deck.slides[slideIdx]!.elements.find(
|
||||
(e) => e.anchor.spIndex === el.anchor.spIndex,
|
||||
)!
|
||||
expect(el2.transform.offset).toEqual(OFF)
|
||||
const text = el2.text.paragraphs.flatMap((p: any) => p.runs).map((r: any) => r.text).join('')
|
||||
expect(text).toBe('combined patch')
|
||||
})
|
||||
|
||||
it('injects <a:xfrm> when the sp inherits geometry (no xfrm in xml)', () => {
|
||||
const el = {
|
||||
type: 'text',
|
||||
transform: { offset: { ...OFF }, rot: 0, flipH: false, flipV: true },
|
||||
} as unknown as SlideElement
|
||||
const xml = '<p:sp><p:nvSpPr/><p:spPr><a:prstGeom prst="rect"/></p:spPr></p:sp>'
|
||||
const out = patchElementXfrm(el, xml)
|
||||
expect(out).toContain('<a:xfrm flipV="1"><a:off x="914400" y="457200"/>')
|
||||
expect(out.indexOf('<a:xfrm')).toBeLessThan(out.indexOf('<a:prstGeom'))
|
||||
})
|
||||
|
||||
it('keeps group chOff/chExt while replacing off/ext', () => {
|
||||
const el = {
|
||||
type: 'group',
|
||||
transform: { offset: { ...OFF }, rot: 0, flipH: false, flipV: false },
|
||||
} as unknown as SlideElement
|
||||
const xml =
|
||||
'<p:grpSp><p:grpSpPr><a:xfrm rot="600000"><a:off x="1" y="2"/><a:ext cx="3" cy="4"/>' +
|
||||
'<a:chOff x="0" y="0"/><a:chExt cx="3" cy="4"/></a:xfrm></p:grpSpPr></p:grpSp>'
|
||||
const out = patchElementXfrm(el, xml)
|
||||
expect(out).toContain('<a:off x="914400" y="457200"/>')
|
||||
expect(out).toContain('<a:chOff x="0" y="0"/>')
|
||||
expect(out).toContain('<a:chExt cx="3" cy="4"/>')
|
||||
expect(out).not.toContain('rot="600000"')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src", "tests", "scripts"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user