Sync snapshot (2026-08-30) (#168)
- Docs: DOCX rendering fidelity - drop caps, hidden (vanish) runs, paragraph pattern shading, floating-table anchoring and clamping, footnote sizing, justified-line spacing - Docs: editing - page breaks split the paragraph correctly, URLs auto-linkify, Insert Hyperlink prefills from the selection, more stable table pagination - Sheets: large streamed workbooks are splittable and formula-capable for the AI; copy_range carries live formulas; range sort up to 200k cells; 1M-cell copies over 2x faster - Sheets: correctness - sort by raw values, shared-formula edits, typed cached strings, empty-string cells, note edits reach the save; risky structural deletes are rejected up front - Sheets: AI chat can export sheets as standalone files; the formula bar grows to fit wrapped formulas - Slides: right-to-left support - paragraph direction toggle, RTL tables, mirrored margins and bullets - Slides: rendering - scaled gradients, embedded fonts, complex-script shaping, chart plot layouts and legends, theme-override colors - Shell: open documents by dropping them onto the window; per-type document icons for OS file associations - AI: localized busy message for overloaded providers; degenerate tool loops stopped with a unified turn budget - Markdown: prompts to save before pasting images into untitled documents Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
583a045212
commit
2239cce9e7
@@ -47,6 +47,8 @@ export type AnimEffectKind =
|
||||
| 'motionPath'
|
||||
|
||||
export type AnimTrigger = 'onClick' | 'withPrev' | 'afterPrev'
|
||||
|
||||
export const ANIM_TRIGGERS: readonly AnimTrigger[] = ['onClick', 'withPrev', 'afterPrev']
|
||||
export type AnimClass = 'entrance' | 'emphasis' | 'exit' | 'path'
|
||||
|
||||
export interface SlideAnimation {
|
||||
@@ -100,7 +102,10 @@ export function elementSpid(el: SlideElement): number | 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 }> = {
|
||||
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
|
||||
@@ -124,6 +129,8 @@ const PRESET: Record<AnimEffectKind, { id: number; cls: 'entr' | 'emph' | 'exit'
|
||||
}
|
||||
|
||||
/** presetClass:presetID(:presetSubtype) → effect (read-back mapping; unmodeled ones map to a same-class approximation). */
|
||||
export const ANIM_EFFECTS = Object.keys(PRESET) as readonly AnimEffectKind[]
|
||||
|
||||
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)
|
||||
@@ -213,7 +220,14 @@ function keyframeAnimXml(
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
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],
|
||||
@@ -553,7 +567,8 @@ function rebuildTimingPreservingXml(timing: string, anims: SlideAnimation[]): st
|
||||
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)
|
||||
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)
|
||||
@@ -584,7 +599,11 @@ export function patchSlideTimingXml(bodySuffix: string, anims: SlideAnimation[])
|
||||
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)
|
||||
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
|
||||
@@ -772,7 +791,8 @@ function appendBldPs(timing: string, items: Placed[]): string {
|
||||
}
|
||||
// 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]!)
|
||||
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) {
|
||||
@@ -827,7 +847,8 @@ export function patchSlideTimingIncrementalXml(
|
||||
// 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))
|
||||
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
|
||||
@@ -842,7 +863,10 @@ export function patchSlideTimingIncrementalXml(
|
||||
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))
|
||||
newTiming = appendBldPs(
|
||||
newTiming,
|
||||
groups.flatMap((g) => g.items),
|
||||
)
|
||||
return splice(newTiming)
|
||||
}
|
||||
|
||||
@@ -864,7 +888,9 @@ export function patchSlideTimingIncrementalXml(
|
||||
// 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
|
||||
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))
|
||||
}
|
||||
@@ -889,3 +915,139 @@ export function setSlideAnimations(slide: Slide, anims: SlideAnimation[]): void
|
||||
export function getSlideAnimations(slide: Slide): SlideAnimation[] {
|
||||
return readSlideTimingXml(slide.bodySuffix)
|
||||
}
|
||||
|
||||
/** Innermost balanced <tag>…</tag> span containing the given index. */
|
||||
function enclosingTagSpan(
|
||||
xml: string,
|
||||
at: number,
|
||||
tag: string,
|
||||
): { start: number; end: number } | null {
|
||||
const re = new RegExp(`<${tag}\\b[^>]*>|</${tag}>`, 'g')
|
||||
const stack: number[] = []
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(xml)) !== null) {
|
||||
if (m[0][1] !== '/') {
|
||||
if (!m[0].endsWith('/>')) stack.push(m.index)
|
||||
} else {
|
||||
const start = stack.pop()
|
||||
if (start === undefined) return null
|
||||
if (start <= at && at < re.lastIndex) return { start, end: re.lastIndex }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Nearest preceding open <tag> that is still open at `at` (self-closing and
|
||||
already-closed occurrences skipped; these tags do not self-nest). */
|
||||
function wrappedBy(xml: string, at: number, tag: string): boolean {
|
||||
let from = at
|
||||
for (;;) {
|
||||
const open = xml.lastIndexOf(`<${tag}`, from)
|
||||
if (open < 0) return false
|
||||
const gt = xml.indexOf('>', open)
|
||||
if (gt < 0) return false
|
||||
if (xml[gt - 1] === '/') {
|
||||
from = open - 1
|
||||
continue
|
||||
}
|
||||
return xml.indexOf(`</${tag}>`, gt) > at
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the spTgt at `at` is a trigger reference (wrapped by an open
|
||||
<p:cond>) rather than an effect/media target — an effect block's own
|
||||
already-closed delay cond (<p:cond delay="0"/> inside its cTn) must not
|
||||
count as a wrapper. */
|
||||
function isTriggerRef(xml: string, at: number): boolean {
|
||||
return wrappedBy(xml, at, 'p:cond')
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the effect blocks targeting the given cNvPr ids from the slide's
|
||||
* <p:timing>. Element removal must go through this or the timing keeps
|
||||
* dangling <p:spTgt spid> refs (PowerPoint flags the file). Byte surgery —
|
||||
* unmodeled effect parameters elsewhere survive (no rebuild):
|
||||
* - a trigger reference (<p:cond><p:tgtEl>) takes its whole interactiveSeq
|
||||
* with it (the animations only ever ran off the removed trigger shape);
|
||||
* - an effect/media target removes the narrowest wrapper (video/audio/par)
|
||||
* that does not contain surviving shapes' targets — when no such wrapper
|
||||
* exists the ref is left in place rather than destroying other animations;
|
||||
* - matching <p:bldP> build refs go too; a timing left with no targets and
|
||||
* no diagram builds is dropped entirely.
|
||||
*/
|
||||
export function pruneTimingForSpids(slide: Slide, spids: ReadonlySet<number>): boolean {
|
||||
if (!spids.size) return false
|
||||
const timing = /<p:timing>[\s\S]*?<\/p:timing>/.exec(slide.bodySuffix)?.[0]
|
||||
if (!timing) return false
|
||||
let xml = timing
|
||||
let changed = false
|
||||
for (;;) {
|
||||
const hits = [...xml.matchAll(/<p:spTgt spid="(\d+)"/g)].filter((x) => spids.has(Number(x[1])))
|
||||
let removed = false
|
||||
for (const hit of hits) {
|
||||
const at = hit.index
|
||||
let span: { start: number; end: number } | null = null
|
||||
if (isTriggerRef(xml, at)) {
|
||||
const seq = enclosingTagSpan(xml, at, 'p:seq')
|
||||
if (seq) {
|
||||
const head = xml.slice(seq.start, seq.start + 400)
|
||||
if (head.includes('nodeType="interactiveSeq"')) span = seq
|
||||
}
|
||||
}
|
||||
if (!span) {
|
||||
const candidates = ['p:video', 'p:audio', 'p:par']
|
||||
.map((t) => enclosingTagSpan(xml, at, t))
|
||||
.filter((sp): sp is { start: number; end: number } => sp !== null)
|
||||
.sort((a, b) => a.end - a.start - (b.end - b.start))
|
||||
span =
|
||||
candidates.find(
|
||||
(sp) =>
|
||||
![...xml.slice(sp.start, sp.end).matchAll(/<p:spTgt spid="(\d+)"/g)].some(
|
||||
(m) => !spids.has(Number(m[1])),
|
||||
),
|
||||
) ?? null
|
||||
}
|
||||
if (!span) continue
|
||||
xml = xml.slice(0, span.start) + xml.slice(span.end)
|
||||
changed = true
|
||||
removed = true
|
||||
break
|
||||
}
|
||||
if (!removed) break
|
||||
}
|
||||
for (const id of spids) {
|
||||
const re = new RegExp(
|
||||
`<p:bldP spid="${id}"[^>]*/>|<p:bldP spid="${id}"[^>]*>[\\s\\S]*?</p:bldP>`,
|
||||
'g',
|
||||
)
|
||||
if (re.test(xml)) {
|
||||
xml = xml.replace(re, '')
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (!changed) return false
|
||||
xml = xml.replace(/<p:bldLst\s*\/>|<p:bldLst\s*>\s*<\/p:bldLst>/g, '')
|
||||
if (/<p:spTgt\b/.test(xml)) {
|
||||
// Collapse innermost pars that lost every target, then their emptied ancestors
|
||||
let prev: string
|
||||
do {
|
||||
prev = xml
|
||||
xml = xml.replace(/<p:par\b[^>]*>(?:(?!<p:par\b|<\/p:par>)[\s\S])*?<\/p:par>/g, (blk) =>
|
||||
/<p:spTgt\b/.test(blk) ? blk : '',
|
||||
)
|
||||
} while (xml !== prev)
|
||||
}
|
||||
slide.bodySuffix =
|
||||
/<p:spTgt\b/.test(xml) || /<p:bldDgm\b/.test(xml)
|
||||
? slide.bodySuffix.replace(timing, xml)
|
||||
: slide.bodySuffix.replace(timing, '')
|
||||
slide.structureDirty = true
|
||||
return true
|
||||
}
|
||||
|
||||
/** Every cNvPr id inside an element's XML fragment (group children included). */
|
||||
export function cNvPrIdsInXml(xml: string): Set<number> {
|
||||
const out = new Set<number>()
|
||||
for (const m of xml.matchAll(/<p:cNvPr\b[^>]*?\bid="(\d+)"/g)) out.add(Number(m[1]))
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -140,7 +140,16 @@ export interface ChartModel {
|
||||
/** <c:legend><c:overlay val="1"/>: the legend floats over the plot, reserving no space */
|
||||
legendOverlay?: boolean
|
||||
/** c:legend manual layout: factor = offset from the auto position, edge = absolute, fractions of the frame */
|
||||
legendLayout?: { x?: number; y?: number; xMode?: 'edge' | 'factor'; yMode?: 'edge' | 'factor' }
|
||||
legendLayout?: {
|
||||
x?: number
|
||||
y?: number
|
||||
w?: number
|
||||
h?: number
|
||||
xMode?: 'edge' | 'factor'
|
||||
yMode?: 'edge' | 'factor'
|
||||
}
|
||||
/** Legend paragraphs are RTL (<c:legend><c:txPr>…<a:pPr rtl="1">): entries mirror (swatch right of the text, right-aligned rows) */
|
||||
legendRtl?: boolean
|
||||
/** Chart part has a Microsoft chartStyle companion (style1.xml); without one PowerPoint uses black label text */
|
||||
hasStylePart?: boolean
|
||||
/** Plot-area inner rectangle (c:plotArea/c:layout/c:manualLayout layoutTarget=inner), fractions of the chart frame */
|
||||
@@ -572,11 +581,13 @@ export function parseChartXml(
|
||||
}
|
||||
const mode = (k: string): 'edge' | 'factor' =>
|
||||
man[k]?.['@_val'] === 'edge' ? 'edge' : 'factor'
|
||||
const [lx, ly] = [frac('c:x'), frac('c:y')]
|
||||
const [lx, ly, lw, lh] = [frac('c:x'), frac('c:y'), frac('c:w'), frac('c:h')]
|
||||
if (lx !== undefined || ly !== undefined) {
|
||||
model.legendLayout = {
|
||||
...(lx !== undefined ? { x: lx, xMode: mode('c:xMode') } : {}),
|
||||
...(ly !== undefined ? { y: ly, yMode: mode('c:yMode') } : {}),
|
||||
...(lw !== undefined && lw > 0 ? { w: lw } : {}),
|
||||
...(lh !== undefined && lh > 0 ? { h: lh } : {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -587,6 +598,8 @@ export function parseChartXml(
|
||||
const legSz = parseInt(legRPr?.['@_sz'], 10)
|
||||
if (Number.isFinite(legSz) && legSz > 0) model.legendPt = legSz / 100
|
||||
if (legRPr?.['@_b'] === '1') model.legendBold = true
|
||||
const legPPr = (Array.isArray(legP) ? legP[0] : legP)?.['a:pPr']
|
||||
if (legPPr?.['@_rtl'] === '1') model.legendRtl = true
|
||||
}
|
||||
|
||||
// Plot-area inner rectangle (edge-mode fractions of the chart frame); PowerPoint positions
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Embedded font extraction — <p:embeddedFontLst> declares document-embedded faces whose
|
||||
* fntdata parts are EOT containers. PowerPoint renders missing families with these faces,
|
||||
* so fidelity needs them registered for measuring and drawing. Only uncompressed payloads
|
||||
* are usable here: MicroType-Express-compressed EOTs (flag 0x4) need a licensed
|
||||
* decompressor and are skipped.
|
||||
*/
|
||||
import { XMLParser } from 'fast-xml-parser'
|
||||
import { PackageArchive, resolveTarget } from './zip'
|
||||
import { asXmlNode, xmlArray } from './xml-utils'
|
||||
|
||||
export type EmbeddedFontStyle = 'regular' | 'bold' | 'italic' | 'boldItalic'
|
||||
|
||||
export interface EmbeddedFontFace {
|
||||
typeface: string
|
||||
style: EmbeddedFontStyle
|
||||
/** Single-face sfnt bytes (TTF/OTF), ready for opentype.js / FontFace */
|
||||
sfnt: Uint8Array
|
||||
}
|
||||
|
||||
const EOT_FLAG_COMPRESSED = 0x00000004 // TTEMBED_TTCOMPRESSED (MicroType Express)
|
||||
const EOT_FLAG_XOR = 0x10000000 // TTEMBED_XORENCRYPTDATA (payload XORed with 0x50)
|
||||
|
||||
const SFNT_MAGICS = [0x00010000, 0x4f54544f, 0x74727565, 0x74746366] // TrueType / 'OTTO' / 'true' / 'ttcf'
|
||||
|
||||
/** Unwrap an EOT container to its sfnt payload; null when compressed or malformed. */
|
||||
export function eotToSfnt(bytes: Uint8Array): Uint8Array | null {
|
||||
if (bytes.length < 16) return null
|
||||
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
||||
// Some producers (LibreOffice) store the bare sfnt without an EOT wrapper
|
||||
if (SFNT_MAGICS.includes(dv.getUint32(0, false))) return bytes
|
||||
const eotSize = dv.getUint32(0, true)
|
||||
const fontDataSize = dv.getUint32(4, true)
|
||||
const flags = dv.getUint32(12, true)
|
||||
if (eotSize !== bytes.length || fontDataSize === 0 || fontDataSize > bytes.length - 16)
|
||||
return null
|
||||
if (flags & EOT_FLAG_COMPRESSED) return null
|
||||
// The variable-length header precedes the payload, so the payload sits at the tail
|
||||
let sfnt = bytes.slice(bytes.length - fontDataSize)
|
||||
if (flags & EOT_FLAG_XOR) sfnt = sfnt.map((b) => b ^ 0x50)
|
||||
const magic = new DataView(sfnt.buffer, sfnt.byteOffset, 4).getUint32(0, false)
|
||||
if (!SFNT_MAGICS.includes(magic)) return null
|
||||
return sfnt
|
||||
}
|
||||
|
||||
/** Usable (uncompressed) embedded faces of a package; empty when none are declared. */
|
||||
export function listEmbeddedFonts(archive: PackageArchive): EmbeddedFontFace[] {
|
||||
const presXml = archive.readText('ppt/presentation.xml')
|
||||
if (!presXml || !presXml.includes('embeddedFont')) return []
|
||||
const parser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
attributeNamePrefix: '@_',
|
||||
isArray: (name) => name === 'p:embeddedFont',
|
||||
})
|
||||
let root: Record<string, unknown>
|
||||
try {
|
||||
root = asXmlNode(asXmlNode(parser.parse(presXml))['p:presentation'])
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
const lst = asXmlNode(root['p:embeddedFontLst'] ?? {})
|
||||
const rels = archive.readRels('ppt/presentation.xml')
|
||||
const out: EmbeddedFontFace[] = []
|
||||
for (const ef of xmlArray(lst['p:embeddedFont'])) {
|
||||
const typeface = String(asXmlNode(asXmlNode(ef)['p:font'] ?? {})['@_typeface'] ?? '')
|
||||
if (!typeface) continue
|
||||
const styles: EmbeddedFontStyle[] = ['regular', 'bold', 'italic', 'boldItalic']
|
||||
for (const style of styles) {
|
||||
const relId = asXmlNode(asXmlNode(ef)[`p:${style}`] ?? {})['@_r:id']
|
||||
if (relId == null) continue
|
||||
const rel = rels.get(String(relId))
|
||||
if (!rel) continue
|
||||
const part = resolveTarget('ppt/presentation.xml', rel.target)
|
||||
const bytes = archive.readBytes(part)
|
||||
if (!bytes) continue
|
||||
const sfnt = eotToSfnt(bytes)
|
||||
if (sfnt) out.push({ typeface, style, sfnt })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -152,6 +152,7 @@ export function patchParagraphPPrXml(paraXml: string, p: Paragraph, which: PPrDi
|
||||
else openTag = openTag.replace(/^<a:pPr/, `<a:pPr ${name}="${escapeXmlAttr(value)}"`)
|
||||
}
|
||||
if (which.align) setPPrAttr('algn', p.align ? ALIGN_MAP[p.align] : undefined)
|
||||
if (which.rtl) setPPrAttr('rtl', p.rtl != null ? (p.rtl ? '1' : '0') : undefined)
|
||||
if (which.level) setPPrAttr('lvl', p.level ? String(p.level) : undefined)
|
||||
if (which.indents) {
|
||||
setPPrAttr('marL', p.marL != null ? String(Math.round(p.marL)) : undefined)
|
||||
@@ -278,8 +279,8 @@ function patchRun(runXml: string, run: TextRun): string {
|
||||
function patchRunProps(runXml: string, run: TextRun): string {
|
||||
const attrPatch = (rprOpen: string): string => {
|
||||
let tag = rprOpen
|
||||
tag = setBoolAttr(tag, 'b', run.bold)
|
||||
tag = setBoolAttr(tag, 'i', run.italic)
|
||||
tag = setBoolAttr(tag, 'b', run.boldImplicit ? undefined : run.bold)
|
||||
tag = setBoolAttr(tag, 'i', run.italicImplicit ? undefined : run.italic)
|
||||
// Underline: keep the original style (dbl/wavy… not collapsed to sng); on removal
|
||||
// an existing u becomes none, and no u is injected when there was none (keeping bytes).
|
||||
// underlineImplicit (hlink styling) is display-only — never bake it into a u attr
|
||||
@@ -326,8 +327,9 @@ function patchRunProps(runXml: string, run: TextRun): string {
|
||||
// Color: patch or inject solidFill (child nodes can only be injected inside the paired form).
|
||||
// colorFollowsTheme = the display value comes from schemeClr/inheritance and the
|
||||
// user hasn't changed it → don't write, keep the original bytes (schemeClr with
|
||||
// lumMod/alpha modifiers stays linked to the theme)
|
||||
if (run.color && !run.colorFollowsTheme) {
|
||||
// lumMod/alpha modifiers stays linked to the theme); colorInherited = the rPr has
|
||||
// no solidFill at all → same deal, don't bake the resolved color in
|
||||
if (run.color && !run.colorFollowsTheme && !run.colorInherited) {
|
||||
runXml = patchRunColor(runXml, run.color)
|
||||
}
|
||||
// Font: patch/inject <a:latin>/<a:ea> only when the user actually changed it.
|
||||
@@ -341,9 +343,11 @@ function patchRunProps(runXml: string, run: TextRun): string {
|
||||
// No rPr: inject a minimal rPr after <a:r> (no font slots injected when the font is untouched,
|
||||
// so inheritance applies)
|
||||
const attrs = buildRPrAttrs(run)
|
||||
const color = run.color
|
||||
? `<a:solidFill><a:srgbClr val="${hex6(run.color)}"/></a:solidFill>`
|
||||
: ''
|
||||
const color = run.colorNodeXml
|
||||
? `<a:solidFill>${run.colorNodeXml}</a:solidFill>`
|
||||
: run.color && !run.colorFollowsTheme && !run.colorInherited
|
||||
? `<a:solidFill><a:srgbClr val="${hex6(run.color)}"/></a:solidFill>`
|
||||
: ''
|
||||
const font =
|
||||
run.fontFamily && !run.fontImplicit && !run.latinFont && !run.eaFont
|
||||
? fontSlotsXml(escapeXmlAttr(run.fontFamily))
|
||||
@@ -575,15 +579,23 @@ function patchRunColor(runXml: string, color: string): string {
|
||||
}
|
||||
|
||||
function buildRPrAttrs(run: TextRun): string {
|
||||
// Explicit "off" values (b="0", u="none", strike="noStrike", spc="0"…) are
|
||||
// overrides of inherited styling, not defaults — dropping them on a rebuild
|
||||
// flips the run to whatever the placeholder/master says (fld bodies always
|
||||
// rebuild, so slide-number placeholders were losing these).
|
||||
let s = ''
|
||||
if (run.fontSize != null && !run.fontSizeImplicit) s += ` sz="${Math.round(run.fontSize * 100)}"`
|
||||
if (run.bold) s += ' b="1"'
|
||||
if (run.italic) s += ' i="1"'
|
||||
if (run.bold != null && !run.boldImplicit) s += ` b="${run.bold ? '1' : '0'}"`
|
||||
if (run.italic != null && !run.italicImplicit) s += ` i="${run.italic ? '1' : '0'}"`
|
||||
if (run.underline && !run.underlineImplicit)
|
||||
s += ` u="${escapeXmlAttr(run.underlineStyle ?? 'sng')}"`
|
||||
else if (run.underlineExplicitNone) s += ' u="none"'
|
||||
if (run.strike) s += ` strike="${escapeXmlAttr(run.strikeStyle ?? 'sngStrike')}"`
|
||||
if (run.letterSpacing) s += ` spc="${Math.round(run.letterSpacing * 100)}"`
|
||||
if (run.baseline) s += ` baseline="${Math.round(run.baseline * 1000)}"`
|
||||
else if (run.strikeExplicitNone) s += ' strike="noStrike"'
|
||||
if (run.kern != null) s += ` kern="${Math.round(run.kern * 100)}"`
|
||||
if (run.capExplicit) s += ` cap="${escapeXmlAttr(run.capExplicit)}"`
|
||||
if (run.letterSpacing != null) s += ` spc="${Math.round(run.letterSpacing * 100)}"`
|
||||
if (run.baseline != null) s += ` baseline="${Math.round(run.baseline * 1000)}"`
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -674,7 +686,7 @@ export function generateParagraphXml(p: Paragraph): string {
|
||||
if (p.marL != null && want('marL')) pPrAttrs.push(`marL="${Math.round(p.marL)}"`)
|
||||
if (p.indent != null && want('indent')) pPrAttrs.push(`indent="${Math.round(p.indent)}"`)
|
||||
if (p.align && want('align')) pPrAttrs.push(`algn="${alignMap[p.align]}"`)
|
||||
if (p.rtl) pPrAttrs.push('rtl="1"')
|
||||
if (p.rtl != null) pPrAttrs.push(`rtl="${p.rtl ? 1 : 0}"`)
|
||||
if (p.level) pPrAttrs.push(`lvl="${p.level}"`)
|
||||
|
||||
// CT_TextParagraphProperties child order: lnSpc → spcBef → spcAft → buClr → buSzPct → buFont → bu*
|
||||
@@ -735,10 +747,12 @@ function generateRunXml(r: TextRun): string {
|
||||
const ln = r.outline
|
||||
? `<a:ln w="${Math.round(r.outline.widthEmu)}"><a:solidFill><a:srgbClr val="${hex6(r.outline.color)}"/></a:solidFill></a:ln>`
|
||||
: ''
|
||||
// Color purely inherited (rPr has no solidFill) → don't write; the inheritance chain still resolves in PowerPoint;
|
||||
// explicit schemeClr is materialized as srgbClr to keep visuals (the rebuild path can't restore the original scheme reference)
|
||||
const color =
|
||||
r.color && !r.colorInherited
|
||||
// Color purely inherited (rPr has no solidFill) → don't write; the inheritance chain still resolves in PowerPoint.
|
||||
// A non-plain-srgb original (schemeClr/prstClr/srgbClr+mods) restores its captured node verbatim
|
||||
// so theme linkage and modifiers survive the rebuild; only a truly changed color bakes an srgbClr.
|
||||
const color = r.colorNodeXml
|
||||
? `<a:solidFill>${r.colorNodeXml}</a:solidFill>`
|
||||
: r.color && !r.colorInherited
|
||||
? `<a:solidFill><a:srgbClr val="${hex6(r.color)}"/></a:solidFill>`
|
||||
: ''
|
||||
// Text highlight (CT_TextCharacterProperties order: after the fill group, before the font slots)
|
||||
@@ -1282,6 +1296,21 @@ export type SlideTransitionKind =
|
||||
| 'zoom'
|
||||
| 'random'
|
||||
|
||||
export const TRANSITION_KINDS = [
|
||||
'none',
|
||||
'morph',
|
||||
'fade',
|
||||
'push',
|
||||
'wipe',
|
||||
'split',
|
||||
'circle',
|
||||
'cover',
|
||||
'pull',
|
||||
'dissolve',
|
||||
'zoom',
|
||||
'random',
|
||||
] as const satisfies readonly SlideTransitionKind[]
|
||||
|
||||
const TRANSITION_INNER: Record<Exclude<SlideTransitionKind, 'none' | 'morph'>, string> = {
|
||||
fade: '<p:fade/>',
|
||||
push: '<p:push dir="u"/>',
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
import type { Paragraph, Slide, TextElement } from './types'
|
||||
import { generateParagraphXml } from './generate'
|
||||
import { cNvPrIdsInXml, pruneTimingForSpids } from './animation'
|
||||
import { materializeSlide, type OpenedPptx } from './index'
|
||||
import { nextCNvPrId } from './insert'
|
||||
|
||||
@@ -71,11 +72,19 @@ export function applyHeaderFooter(
|
||||
const slide = deck.slides[i]
|
||||
if (!slide) continue
|
||||
|
||||
// 1) Remove existing footer-family placeholders
|
||||
// 1) Remove existing footer-family placeholders (and their animations —
|
||||
// slide-number placeholders animated by templates would leave dangling
|
||||
// <p:spTgt spid> refs behind)
|
||||
const before = slide.elements.length
|
||||
const removed = slide.elements.filter((el) => el.placeholder && HF_TYPES.has(el.placeholder))
|
||||
slide.elements = slide.elements.filter(
|
||||
(el) => !(el.placeholder && HF_TYPES.has(el.placeholder)),
|
||||
)
|
||||
const removedIds = new Set<number>()
|
||||
for (const el of removed) {
|
||||
for (const id of cNvPrIdsInXml(el.anchor.originalXml)) removedIds.add(id)
|
||||
}
|
||||
pruneTimingForSpids(slide, removedIds)
|
||||
let dirty = slide.elements.length !== before
|
||||
|
||||
// 2) Append enabled placeholders (order: dt left → ftr center → sldNum right)
|
||||
|
||||
@@ -48,7 +48,7 @@ import {
|
||||
import { BLANK_SLIDE_XML } from './blank'
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
import { elementSpid } from './animation'
|
||||
import { ensureCreationId } from './identity'
|
||||
import { ensureCreationId, matchesElementRef } from './identity'
|
||||
import { listMasterParts, parseMasterPart } from './master-edit'
|
||||
import type {
|
||||
Paragraph,
|
||||
@@ -94,12 +94,22 @@ export {
|
||||
patchSlideTimingXml,
|
||||
readSlideTimingXml,
|
||||
setSlideAnimations,
|
||||
pruneTimingForSpids,
|
||||
cNvPrIdsInXml,
|
||||
ANIM_EFFECTS,
|
||||
ANIM_TRIGGERS,
|
||||
type AnimClass,
|
||||
type AnimEffectKind,
|
||||
type AnimTrigger,
|
||||
type SlideAnimation,
|
||||
} from './animation'
|
||||
export { PackageArchive } from './zip'
|
||||
export {
|
||||
listEmbeddedFonts,
|
||||
eotToSfnt,
|
||||
type EmbeddedFontFace,
|
||||
type EmbeddedFontStyle,
|
||||
} from './embedded-fonts'
|
||||
export { scanSlide, type SlideScan, type SpElement } from './scan'
|
||||
export {
|
||||
parseSlide,
|
||||
@@ -132,6 +142,7 @@ export {
|
||||
generateParagraphXml,
|
||||
generateXfrmXml,
|
||||
isConnectorXml,
|
||||
TRANSITION_KINDS,
|
||||
type GradientFillPatch,
|
||||
type BackgroundImagePatch,
|
||||
type SlideTransitionKind,
|
||||
@@ -340,6 +351,7 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
|
||||
const chartMediaRels = new Map<string, Map<string, string>>()
|
||||
const chartUserShapes = new Map<string, string>()
|
||||
const chartStyleRels = new Set<string>()
|
||||
const chartThemeOverrides = new Map<string, string>()
|
||||
const avRels = new Map<string, { target: string; external?: boolean }>()
|
||||
const diagramDrawings = new Map<string, string>()
|
||||
const diagramDatas = new Map<string, string>()
|
||||
@@ -372,6 +384,11 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
|
||||
if (usXml) chartUserShapes.set(rel.id, usXml)
|
||||
}
|
||||
if (sub.type.endsWith('/chartStyle')) chartStyleRels.add(rel.id)
|
||||
// Chart-local theme (accents remapped per chart): schemeClr must resolve against it
|
||||
if (sub.type.endsWith('/themeOverride')) {
|
||||
const ovXml = archive.readText(resolveTarget(target, sub.target))
|
||||
if (ovXml) chartThemeOverrides.set(rel.id, ovXml)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (/\/(?:video|audio|media)$/.test(rel.type)) {
|
||||
@@ -430,6 +447,7 @@ function parseSlideFromArchive(archive: PackageArchive, slidePath: string): Slid
|
||||
if (chartMediaRels.size) ctx.chartMediaRels = chartMediaRels
|
||||
if (chartUserShapes.size) ctx.chartUserShapes = chartUserShapes
|
||||
if (chartStyleRels.size) ctx.chartStyleRels = chartStyleRels
|
||||
ctx.chartThemeOverrides = chartThemeOverrides
|
||||
if (hlinkRels.size) ctx.hlinkRels = hlinkRels
|
||||
if (avRels.size) ctx.avRels = avRels
|
||||
if (diagramDrawings.size) ctx.diagramDrawings = diagramDrawings
|
||||
@@ -2393,6 +2411,30 @@ export function addTable(
|
||||
|
||||
// ── Table cell text editing ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* All <a:gridCol> spans in document order. gridCol comes in both forms —
|
||||
* self-closing, and paired when it carries children (Google Slides exports
|
||||
* attach an <a:extLst> a16:colId to every column) — so a self-closing-only
|
||||
* regex undercounts columns or, worse, indexes the wrong one on mixed tables.
|
||||
*/
|
||||
function gridColSpans(xml: string): Array<{ start: number; end: number; open: string }> {
|
||||
const spans: Array<{ start: number; end: number; open: string }> = []
|
||||
const re = /<a:gridCol\b[^>]*?(\/)?>/g
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(xml)) !== null) {
|
||||
if (m[1]) {
|
||||
spans.push({ start: m.index, end: m.index + m[0].length, open: m[0] })
|
||||
} else {
|
||||
const close = xml.indexOf('</a:gridCol>', re.lastIndex)
|
||||
if (close < 0) break
|
||||
const end = close + '</a:gridCol>'.length
|
||||
spans.push({ start: m.index, end, open: m[0] })
|
||||
re.lastIndex = end
|
||||
}
|
||||
}
|
||||
return spans
|
||||
}
|
||||
|
||||
/** Locate the nth <tag>…</tag> span in the xml (a:tr/a:tc never self-nest, so a sequential scan suffices). */
|
||||
function nthTagSpan(xml: string, tag: string, n: number): { start: number; end: number } | null {
|
||||
const openRe = new RegExp(`<${tag}(?:\\s[^>]*)?>`, 'g')
|
||||
@@ -2786,18 +2828,36 @@ function applyFontPatch(paragraphs: Paragraph[], patch: ElementFontPatch): void
|
||||
}
|
||||
if (patch.strike !== undefined) {
|
||||
r.strike = patch.strike
|
||||
if (!patch.strike) delete r.strikeStyle
|
||||
// Explicit off must survive a rebuild as strike="noStrike" (see buildRPrAttrs)
|
||||
if (!patch.strike) {
|
||||
delete r.strikeStyle
|
||||
r.strikeExplicitNone = true
|
||||
} else {
|
||||
delete r.strikeExplicitNone
|
||||
}
|
||||
}
|
||||
if (patch.bold !== undefined) {
|
||||
r.bold = patch.bold
|
||||
delete r.boldImplicit
|
||||
}
|
||||
if (patch.italic !== undefined) {
|
||||
r.italic = patch.italic
|
||||
delete r.italicImplicit
|
||||
}
|
||||
if (patch.bold !== undefined) r.bold = patch.bold
|
||||
if (patch.italic !== undefined) r.italic = patch.italic
|
||||
if (patch.underline !== undefined) {
|
||||
r.underline = patch.underline
|
||||
if (!patch.underline) delete r.underlineStyle
|
||||
if (!patch.underline) {
|
||||
delete r.underlineStyle
|
||||
r.underlineExplicitNone = true
|
||||
} else {
|
||||
delete r.underlineExplicitNone
|
||||
}
|
||||
}
|
||||
if (patch.color !== undefined) {
|
||||
r.color = patch.color
|
||||
delete r.colorFollowsTheme
|
||||
delete r.colorInherited
|
||||
delete r.colorNodeXml
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2946,6 +3006,8 @@ export interface ParagraphFormatPatch {
|
||||
spaceBeforePt?: number
|
||||
spaceAfterPt?: number
|
||||
align?: Paragraph['align']
|
||||
/** Paragraph base direction (a:pPr rtl); false writes an explicit rtl="0" */
|
||||
rtl?: boolean
|
||||
/** Indent level delta (multi-level list Tab/⇧Tab; clamp 0..8) */
|
||||
indentDelta?: 1 | -1
|
||||
}
|
||||
@@ -3037,6 +3099,10 @@ function applyParagraphFormat(paragraphs: Paragraph[], patch: ParagraphFormatPat
|
||||
mark('align')
|
||||
dirty.align = true
|
||||
}
|
||||
if (patch.rtl != null) {
|
||||
p.rtl = patch.rtl
|
||||
dirty.rtl = true
|
||||
}
|
||||
if (patch.indentDelta) {
|
||||
const lvl = Math.max(0, Math.min(8, (p.level ?? 0) + patch.indentDelta))
|
||||
if (lvl !== (p.level ?? 0)) {
|
||||
@@ -3207,8 +3273,7 @@ export function editTableStructure(
|
||||
trSpans.push(span)
|
||||
}
|
||||
const nRows = trSpans.length
|
||||
const gridColRe = /<a:gridCol\s[^>]*\/>/g
|
||||
const gridCols = [...xml.matchAll(gridColRe)]
|
||||
const gridCols = gridColSpans(xml)
|
||||
const nCols = gridCols.length
|
||||
if (!nRows || !nCols) return null
|
||||
|
||||
@@ -3232,7 +3297,7 @@ export function editTableStructure(
|
||||
const at = op.index
|
||||
const refCol = gridCols[at]
|
||||
if (!refCol) return null
|
||||
const colW = Number(/\bw="(\d+)"/.exec(refCol[0])?.[1] ?? 0)
|
||||
const colW = Number(/\bw="(\d+)"/.exec(refCol.open)?.[1] ?? 0)
|
||||
if (op.kind === 'delete-col' && nCols <= 1) return null
|
||||
|
||||
// Process tc row by row (replace back-to-front so offsets stay valid)
|
||||
@@ -3253,13 +3318,15 @@ export function editTableStructure(
|
||||
xml = xml.slice(0, tr.start) + newTr + xml.slice(tr.end)
|
||||
}
|
||||
// gridCol and frame width
|
||||
const gc = [...xml.matchAll(gridColRe)][at]!
|
||||
const gc = gridColSpans(xml)[at]!
|
||||
if (op.kind === 'insert-col') {
|
||||
const insertAt = op.before ? gc.index : gc.index + gc[0].length
|
||||
xml = xml.slice(0, insertAt) + gc[0] + xml.slice(insertAt)
|
||||
// Fresh self-closing clone: copying the full span would duplicate the
|
||||
// reference column's a16:colId, which must stay unique per column
|
||||
const insertAt = op.before ? gc.start : gc.end
|
||||
xml = xml.slice(0, insertAt) + `<a:gridCol w="${colW}"/>` + xml.slice(insertAt)
|
||||
xml = bumpFrameExt(xml, 'cx', colW)
|
||||
} else {
|
||||
xml = xml.slice(0, gc.index) + xml.slice(gc.index + gc[0].length)
|
||||
xml = xml.slice(0, gc.start) + xml.slice(gc.end)
|
||||
xml = bumpFrameExt(xml, 'cx', -colW)
|
||||
}
|
||||
}
|
||||
@@ -3423,13 +3490,13 @@ export function setTableColWidth(
|
||||
if (col < 0 || col >= table.colWidths.length) return false
|
||||
|
||||
let xml = patchedElementXml(el)
|
||||
const gc = [...xml.matchAll(/<a:gridCol\s[^>]*\/>/g)][col]
|
||||
const gc = gridColSpans(xml)[col]
|
||||
if (!gc) return false
|
||||
el.dirty = el.dirtyTransform = el.dirtyFill = el.dirtyStroke = false
|
||||
el.dirtyPPr = undefined
|
||||
const w = Math.max(1, Math.round(wEmu))
|
||||
const patched = gc[0].replace(/\bw="-?\d+"/, `w="${w}"`)
|
||||
xml = xml.slice(0, gc.index) + patched + xml.slice(gc.index + gc[0].length)
|
||||
const patched = gc.open.replace(/\bw="-?\d+"/, `w="${w}"`)
|
||||
xml = xml.slice(0, gc.start) + patched + xml.slice(gc.start + gc.open.length)
|
||||
|
||||
const dxRtl = table.rtl ? w - table.colWidths[col]! : 0
|
||||
table.colWidths[col] = w
|
||||
@@ -3521,7 +3588,8 @@ export function resizeTable(slide: Slide, elementId: string, cx: number, cy: num
|
||||
|
||||
const widths = scaleToSum(table.colWidths, targetCx)
|
||||
let ci = 0
|
||||
xml = xml.replace(/<a:gridCol\s[^>]*\/>/g, (m) =>
|
||||
// Opening tags only — paired-form gridCols (extLst children) must scale too
|
||||
xml = xml.replace(/<a:gridCol\b[^>]*>/g, (m) =>
|
||||
ci < widths.length ? m.replace(/\bw="-?\d+"/, `w="${widths[ci++]}"`) : m,
|
||||
)
|
||||
|
||||
@@ -3811,11 +3879,17 @@ export function groupElements(
|
||||
const slide = opened.deck.slides[slideIndex]
|
||||
if (!slide || sourceIds.length < 2) return null
|
||||
|
||||
// Validate: only text/shape/picture allowed
|
||||
// Validate: only text/shape/picture allowed. Refs resolve like every other
|
||||
// op (parse-time id, durable e_<guid8>, e_<cNvPr id>), deduplicated in case
|
||||
// two forms name the same element.
|
||||
const GROUPABLE = new Set(['text', 'shape', 'picture'])
|
||||
const targets = sourceIds
|
||||
.map((id) => slide.elements.find((e) => e.id === id))
|
||||
.filter(Boolean) as SlideElement[]
|
||||
const targets = [
|
||||
...new Set(
|
||||
sourceIds
|
||||
.map((id) => slide.elements.find((e) => matchesElementRef(e, id)))
|
||||
.filter(Boolean) as SlideElement[],
|
||||
),
|
||||
]
|
||||
if (targets.length < 2) return null
|
||||
if (targets.some((e) => !GROUPABLE.has(e.type))) return null
|
||||
|
||||
@@ -3829,8 +3903,8 @@ export function groupElements(
|
||||
const grpXml = buildGrpSpXml(slide, bbox, childrenXml)
|
||||
|
||||
// Remove the selected elements from the current slide
|
||||
const idSet = new Set(sourceIds)
|
||||
slide.elements = slide.elements.filter((e) => !idSet.has(e.id))
|
||||
const grouped = new Set(targets)
|
||||
slide.elements = slide.elements.filter((e) => !grouped.has(e))
|
||||
|
||||
// Append the grpSp and reparse
|
||||
const result = appendRawElements(opened, slideIndex, [grpXml])
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* Both change the spTree structure, driving a full-slide rebuild via
|
||||
* slide.structureDirty.
|
||||
*/
|
||||
import { cNvPrIdsInXml, pruneTimingForSpids } from './animation'
|
||||
import type { EmuRect, Paragraph, PictureElement, Slide, SlideElement, TextElement } from './types'
|
||||
import { generateParagraphXml, generateXfrmXml } from './generate'
|
||||
import { creationIdXml, escapeXmlAttr } from './xml-utils'
|
||||
@@ -494,6 +495,9 @@ export function deleteElement(opened: OpenedPptx, slide: Slide, elementId: strin
|
||||
slide.elements.splice(idx, 1)
|
||||
slide.structureDirty = true
|
||||
cleanupDeletedElementResources(opened, slide, removedXml)
|
||||
// Animations targeting the removed shape (or its group children) would
|
||||
// otherwise keep dangling <p:spTgt spid> refs
|
||||
pruneTimingForSpids(slide, cNvPrIdsInXml(removedXml))
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { XMLParser } from 'fast-xml-parser'
|
||||
import { layoutHierTree, parseHierConstraints } from './dgm-hier'
|
||||
import { scanSlide, type SpElement } from './scan'
|
||||
import { tableRowGridCols } from './table-grid'
|
||||
import { type Theme, resolveFontRef, resolveSchemeColor } from './theme'
|
||||
import { type Theme, resolveFontRef, resolveSchemeColor, themeWithOverride } from './theme'
|
||||
import { resolveColorNode as resolveColorNodeShared } from './color'
|
||||
import {
|
||||
resolvePlaceholderPresetGeom,
|
||||
@@ -134,6 +134,8 @@ export interface ParseContext {
|
||||
chartMediaRels?: Map<string, Map<string, string>>
|
||||
/** Chart rIds whose part has a Microsoft chartStyle companion (modern gray label defaults) */
|
||||
chartStyleRels?: Set<string>
|
||||
/** chart rId → its themeOverride part XML (chart-local clrScheme/fontScheme) */
|
||||
chartThemeOverrides?: Map<string, string>
|
||||
/** Diagram data rId → the drawing part's own image rels (SmartArt picture fills) */
|
||||
diagramMediaRels?: Map<string, Map<string, string>>
|
||||
/** ppt/tableStyles.xml source (table style definitions, read-only) */
|
||||
@@ -1078,7 +1080,9 @@ function graphicFramePassthrough(node: any, anchor: ByteAnchor, ctx: ParseContex
|
||||
if (uri.includes('/chartex')) {
|
||||
const rid = data?.['cx:chart']?.['@_r:id']
|
||||
const chartXml = rid ? ctx.chartXmls?.get(String(rid)) : undefined
|
||||
const model = chartXml ? parseChartExXml(chartXml, ctx.theme) : null
|
||||
const ovXml = rid ? ctx.chartThemeOverrides?.get(String(rid)) : undefined
|
||||
const chartTheme = ovXml ? themeWithOverride(ctx.theme, ovXml) : ctx.theme
|
||||
const model = chartXml ? parseChartExXml(chartXml, chartTheme) : null
|
||||
if (model) {
|
||||
const cNvPr = node['p:nvGraphicFramePr']?.['p:cNvPr']
|
||||
return {
|
||||
@@ -1095,10 +1099,17 @@ function graphicFramePassthrough(node: any, anchor: ByteAnchor, ctx: ParseContex
|
||||
if (uri.includes('/chart')) {
|
||||
const rid = data?.['c:chart']?.['@_r:id']
|
||||
const chartXml = rid ? ctx.chartXmls?.get(rid) : undefined
|
||||
// Fill resolver bound to the chart part's own rels (blip rIds live there, not on the slide)
|
||||
const chartFillCtx: ParseContext = { ...ctx, mediaRels: ctx.chartMediaRels?.get(String(rid)) }
|
||||
const ovXml = rid ? ctx.chartThemeOverrides?.get(String(rid)) : undefined
|
||||
const chartTheme = ovXml ? themeWithOverride(ctx.theme, ovXml) : ctx.theme
|
||||
// Fill resolver bound to the chart part's own rels (blip rIds live there, not on
|
||||
// the slide) and to the chart-local theme (accents may be remapped per chart)
|
||||
const chartFillCtx: ParseContext = {
|
||||
...ctx,
|
||||
mediaRels: ctx.chartMediaRels?.get(String(rid)),
|
||||
theme: chartTheme,
|
||||
}
|
||||
const model = chartXml
|
||||
? parseChartXml(chartXml, ctx.theme, (spPr) => parseFill(spPr, chartFillCtx))
|
||||
? parseChartXml(chartXml, chartTheme, (spPr) => parseFill(spPr, chartFillCtx))
|
||||
: null
|
||||
if (model && ctx.chartStyleRels?.has(String(rid))) model.hasStylePart = true
|
||||
if (model) {
|
||||
@@ -2965,6 +2976,7 @@ function parseGradFill(grad: any, ctx: ParseContext): Fill | undefined {
|
||||
// directionless gradFill gets the measured vertical default
|
||||
const angle =
|
||||
lin != null ? parseInt(lin['@_ang'], 10) || 0 : grad['a:path'] == null ? 5400000 : undefined
|
||||
const scaled = lin != null && (lin['@_scaled'] === '1' || lin['@_scaled'] === 'true')
|
||||
const ftr = grad['a:path']?.['a:fillToRect']
|
||||
// Omitted fillToRect attributes default to 0 (whole tile rect), not to a centered inset
|
||||
const frac = (v: unknown) => (v != null ? (parseInt(String(v), 10) || 0) / 100000 : 0)
|
||||
@@ -2972,6 +2984,7 @@ function parseGradFill(grad: any, ctx: ParseContext): Fill | undefined {
|
||||
type: 'gradient',
|
||||
stops,
|
||||
...(angle != null ? { angle } : {}),
|
||||
...(scaled ? { scaled: true } : {}),
|
||||
...(pathType === 'circle' || pathType === 'rect' || pathType === 'shape'
|
||||
? { path: pathType }
|
||||
: {}),
|
||||
@@ -2993,6 +3006,49 @@ function resolveColorNode(node: any, ctx: ParseContext): string | undefined {
|
||||
return resolveColorNodeShared(node, ctx.theme, ctx.phClr)
|
||||
}
|
||||
|
||||
const COLOR_NODE_TAGS = [
|
||||
'a:srgbClr',
|
||||
'a:schemeClr',
|
||||
'a:sysClr',
|
||||
'a:prstClr',
|
||||
'a:hslClr',
|
||||
'a:scrgbClr',
|
||||
]
|
||||
|
||||
const xmlAttrEsc = (v: string): string =>
|
||||
v.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"')
|
||||
|
||||
/** Re-serialize a parsed color node (tag + attrs + flat modifier children like tint/lumMod)
|
||||
* so the rebuild path can restore it verbatim instead of baking in the resolved value. */
|
||||
function colorNodeXml(fillNode: any): string | undefined {
|
||||
for (const tag of COLOR_NODE_TAGS) {
|
||||
const n = fillNode?.[tag]
|
||||
if (n == null) continue
|
||||
const node = typeof n === 'object' ? n : {}
|
||||
const attrs = Object.keys(node)
|
||||
.filter((k) => k.startsWith('@_'))
|
||||
.map((k) => ` ${k.slice(2)}="${xmlAttrEsc(String(node[k]))}"`)
|
||||
.join('')
|
||||
const kids = Object.keys(node)
|
||||
.filter((k) => k.startsWith('a:'))
|
||||
.map((k) => {
|
||||
const arr = Array.isArray(node[k]) ? node[k] : [node[k]]
|
||||
return arr
|
||||
.map((c: any) => {
|
||||
const cAttrs = Object.keys(c ?? {})
|
||||
.filter((x) => x.startsWith('@_'))
|
||||
.map((x) => ` ${x.slice(2)}="${xmlAttrEsc(String(c[x]))}"`)
|
||||
.join('')
|
||||
return `<${k}${cAttrs}/>`
|
||||
})
|
||||
.join('')
|
||||
})
|
||||
.join('')
|
||||
return kids ? `<${tag}${attrs}>${kids}</${tag}>` : `<${tag}${attrs}/>`
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
// ── Text ─────────────────────────────────────────────────────────────
|
||||
|
||||
function parseTextBody(
|
||||
@@ -3174,6 +3230,16 @@ function parseParagraph(
|
||||
const marL = hasMarL ? marLRaw : dflt?.marL
|
||||
const indent = hasIndent ? indentRaw : dflt?.indent
|
||||
|
||||
// rtl attribute: "1"/"true" and "0"/"false" are both explicit (an explicit LTR base
|
||||
// overrides first-strong-character inference in layout); absent stays undefined
|
||||
const rtlAttr = pPr['@_rtl']
|
||||
const rtl =
|
||||
rtlAttr === '1' || rtlAttr === 'true'
|
||||
? true
|
||||
: rtlAttr === '0' || rtlAttr === 'false'
|
||||
? false
|
||||
: undefined
|
||||
|
||||
// Record which properties come from an explicit pPr (the rebuild path writes only explicit items; inherited values are not baked in)
|
||||
const pPrExplicit: NonNullable<Paragraph['pPrExplicit']> = {
|
||||
...(pPr['@_algn'] ? { align: true } : {}),
|
||||
@@ -3188,6 +3254,7 @@ function parseParagraph(
|
||||
return {
|
||||
runs,
|
||||
align: pPr['@_algn'] ? alignMap[pPr['@_algn']] : dflt?.align,
|
||||
...(rtl != null ? { rtl } : {}),
|
||||
level,
|
||||
pPrExplicit,
|
||||
...(lineHeight != null ? { lineHeight } : {}),
|
||||
@@ -3236,7 +3303,11 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
|
||||
if (rPr['a:gradFill'] && typeof rPr['a:gradFill'] === 'object') {
|
||||
const g = parseFill(rPr, ctx)
|
||||
if (g?.type === 'gradient' && g.stops.length) {
|
||||
gradient = { stops: g.stops, ...(g.angle != null ? { angle: g.angle } : {}) }
|
||||
gradient = {
|
||||
stops: g.stops,
|
||||
...(g.angle != null ? { angle: g.angle } : {}),
|
||||
...(g.scaled ? { scaled: true } : {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
// PowerPoint styles linked runs with the theme hlink color unless the run has an explicit fill
|
||||
@@ -3246,8 +3317,14 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
|
||||
(hlinkTarget ? ctx.theme?.colors?.hlink : undefined) ??
|
||||
dflt?.color
|
||||
// Whether the color is display-only: from schemeClr/inheritance (not an explicit run srgbClr).
|
||||
// The patch path uses this to avoid baking theme colors into srgbClr (theme switches must stay linked)
|
||||
const colorFollowsTheme = color != null && !(fill && fill['a:srgbClr'])
|
||||
// The patch path uses this to avoid baking theme colors into srgbClr (theme switches must stay linked).
|
||||
// An srgbClr carrying transform children (lumMod/lumOff/alpha…) resolves to a computed display
|
||||
// value too: rewriting would bake the computation in and drop the modifiers, so it gets the same
|
||||
// keep-bytes-unless-changed treatment.
|
||||
const srgb = fill?.['a:srgbClr']
|
||||
const srgbHasMods =
|
||||
srgb != null && typeof srgb === 'object' && Object.keys(srgb).some((k) => k.startsWith('a:'))
|
||||
const colorFollowsTheme = color != null && (!(fill && srgb) || srgbHasMods)
|
||||
const colorInherited = color != null && !fill
|
||||
// Text highlight <a:highlight> (PowerPoint draws it as a background behind the run)
|
||||
const highlightNode = rPr['a:highlight']
|
||||
@@ -3332,15 +3409,20 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
|
||||
return {
|
||||
text,
|
||||
bold: bAttr != null ? bAttr === '1' || bAttr === 'true' : !!dflt?.bold,
|
||||
...(bAttr == null ? { boldImplicit: true } : {}),
|
||||
italic: iAttr != null ? iAttr === '1' || iAttr === 'true' : !!dflt?.italic,
|
||||
...(iAttr == null ? { italicImplicit: true } : {}),
|
||||
...(() => {
|
||||
const cap = rPr['@_cap'] != null ? String(rPr['@_cap']) : dflt?.cap
|
||||
return cap && cap !== 'none' ? { cap } : {}
|
||||
})(),
|
||||
...(rPr['@_cap'] != null ? { capExplicit: String(rPr['@_cap']) } : {}),
|
||||
underline: (uAttr !== undefined && uAttr !== 'none') || linkUnderline,
|
||||
...(uAttr !== undefined && uAttr !== 'none' ? { underlineStyle: String(uAttr) } : {}),
|
||||
...(uAttr === 'none' ? { underlineExplicitNone: true } : {}),
|
||||
...(linkUnderline ? { underlineImplicit: true } : {}),
|
||||
...(hasStrike ? { strike: true, strikeStyle: String(strikeAttr) } : {}),
|
||||
...(strikeAttr === 'noStrike' ? { strikeExplicitNone: true } : {}),
|
||||
...(latinRaw ? { latinFont: String(latinRaw) } : {}),
|
||||
...(eaRaw ? { eaFont: String(eaRaw) } : {}),
|
||||
...(csRaw ? { csFont: String(csRaw) } : {}),
|
||||
@@ -3354,6 +3436,13 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
|
||||
...(fontScriptHint != null ? { fontScriptHint } : {}),
|
||||
color,
|
||||
...(colorFollowsTheme ? { colorFollowsTheme } : {}),
|
||||
// Captured independent of resolution (a themeless parse still must not bake values in)
|
||||
...(fill && !(srgb != null && !srgbHasMods)
|
||||
? (() => {
|
||||
const raw = colorNodeXml(fill)
|
||||
return raw ? { colorNodeXml: raw } : {}
|
||||
})()
|
||||
: {}),
|
||||
...(colorInherited ? { colorInherited } : {}),
|
||||
...(highlight ? { highlight } : {}),
|
||||
...(outline ? { outline } : {}),
|
||||
|
||||
@@ -17,6 +17,8 @@ export interface TableStyleEdit {
|
||||
firstRow?: boolean
|
||||
/** Change only the bandRow flag */
|
||||
bandRow?: boolean
|
||||
/** Right-to-left table (tblPr rtl: mirrored grid); false removes the attribute */
|
||||
rtl?: boolean
|
||||
/** Shading color #RRGGBB or 'none' (<a:solidFill> / <a:noFill> per tc) */
|
||||
shadingColor?: string | null
|
||||
/** Border color + width (all = all borders; none = clear) */
|
||||
@@ -189,39 +191,33 @@ export function patchTableStyleXml(originalXml: string, edit: TableStyleEdit): s
|
||||
|
||||
// ── 1. Replace <a:tblPr> ──────────────────────────────────────────
|
||||
if (edit.tblPrXml !== undefined) {
|
||||
// Whole-block replacement
|
||||
xml = replaceTblPr(xml, edit.tblPrXml)
|
||||
} else if (edit.firstRow !== undefined || edit.bandRow !== undefined) {
|
||||
// Whole-block replacement. Presets carry their own firstRow/bandRow but never rtl —
|
||||
// table direction is orthogonal state and survives a style change (PowerPoint behavior)
|
||||
let next = edit.tblPrXml
|
||||
const rtl = /<a:tblPr[^>]*\srtl="([^"]*)"/.exec(xml)?.[1]
|
||||
if ((rtl === '1' || rtl === 'true') && !/\srtl="/.test(next)) {
|
||||
next = next.replace(/^<a:tblPr/, '<a:tblPr rtl="1"')
|
||||
}
|
||||
xml = replaceTblPr(xml, next)
|
||||
} else if (edit.firstRow !== undefined || edit.bandRow !== undefined || edit.rtl !== 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)
|
||||
}
|
||||
// With attributes present the greedy [^>]* swallows a trailing "/" into group 1,
|
||||
// so self-closing must be detected on the whole tag and the slash stripped
|
||||
const selfClosing = tblPrMatch[0].endsWith('/>')
|
||||
let attrs = (tblPrMatch[1] ?? '').replace(/\/\s*$/, '')
|
||||
if (edit.firstRow !== undefined)
|
||||
attrs = setAttr(attrs, 'firstRow', edit.firstRow ? '1' : undefined)
|
||||
if (edit.bandRow !== undefined)
|
||||
attrs = setAttr(attrs, 'bandRow', edit.bandRow ? '1' : undefined)
|
||||
if (edit.rtl !== undefined) attrs = setAttr(attrs, 'rtl', edit.rtl ? '1' : undefined)
|
||||
// Self-closing expands into <a:tblPr...></a:tblPr>
|
||||
xml =
|
||||
xml.slice(0, tblPrMatch.index) +
|
||||
`<a:tblPr${attrs}>` +
|
||||
(selfClosing ? '</a:tblPr>' : '') +
|
||||
xml.slice(tblPrMatch.index + tblPrMatch[0].length)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -136,6 +136,29 @@ export function parseTheme(themeXml: string): Theme {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Chart-part theme override (<a:themeOverride>, referenced from the chart's own
|
||||
* rels): the chart's schemeClr refs and default palette resolve against ITS
|
||||
* clrScheme/fontScheme, not the deck theme's — decks legitimately remap accents
|
||||
* per chart. Wrapping the override's themeElements as a full theme reuses
|
||||
* parseTheme; fields the override omits fall back to the base theme.
|
||||
*/
|
||||
export function themeWithOverride(base: Theme | undefined, overrideXml: string): Theme {
|
||||
const inner = /<a:themeOverride\b[^>]*>([\s\S]*)<\/a:themeOverride>/.exec(overrideXml)?.[1]
|
||||
if (!inner) return base ?? { colors: {} }
|
||||
const parsed = parseTheme(`<a:theme><a:themeElements>${inner}</a:themeElements></a:theme>`)
|
||||
// Per-field merge: parseTheme lists absent fonts as undefined, which a plain
|
||||
// spread would clobber the base values with. clrMap is a master concern and
|
||||
// never part of the override.
|
||||
const merged: Theme = { ...base, colors: { ...base?.colors, ...parsed.colors } }
|
||||
for (const [k, v] of Object.entries(parsed)) {
|
||||
if (k !== 'colors' && k !== 'clrMap' && v !== undefined) {
|
||||
;(merged as unknown as Record<string, unknown>)[k] = v
|
||||
}
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
|
||||
@@ -51,6 +51,8 @@ export type Fill =
|
||||
type: 'gradient'
|
||||
stops: Array<{ pos: number; color: ResolvedColor }>
|
||||
angle?: number
|
||||
/** <a:lin scaled="1">: the angle stretches with the fill box aspect (45° runs corner-to-corner) */
|
||||
scaled?: boolean
|
||||
/** <a:path path>: circle/rect/shape = radial/path gradient (linear by default) */
|
||||
path?: 'circle' | 'rect' | 'shape'
|
||||
/** <a:fillToRect> insets as fractions (may exceed 0..1); defines the gradient focus */
|
||||
@@ -149,13 +151,27 @@ export interface ShadowEffect {
|
||||
export interface TextRun {
|
||||
text: string
|
||||
bold?: boolean
|
||||
/** Run has no explicit b (bold resolved from inheritance); rebuild/patch omits b to keep the master/layout linkage */
|
||||
boldImplicit?: boolean
|
||||
italic?: boolean
|
||||
/** Run has no explicit i (see boldImplicit) */
|
||||
italicImplicit?: 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
|
||||
/** Original rPr carried an explicit u="none" — an override of inherited underline the rebuild path must re-emit */
|
||||
underlineExplicitNone?: boolean
|
||||
/** Original rPr carried strike="noStrike" (see underlineExplicitNone) */
|
||||
strikeExplicitNone?: boolean
|
||||
/** Explicit cap attribute verbatim (incl. "none"); `cap` below holds the resolved display value, which may be inherited */
|
||||
capExplicit?: string
|
||||
/** Verbatim color node of the run's explicit solidFill when it is not a plain srgbClr
|
||||
* (schemeClr/prstClr/sysClr/… or srgbClr with modifiers). The rebuild path re-emits it
|
||||
* instead of baking the resolved display value in; cleared when the user changes the color. */
|
||||
colorNodeXml?: 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 */
|
||||
@@ -220,7 +236,11 @@ export interface TextRun {
|
||||
/** Run-level outer shadow (<a:rPr>/defRPr <a:effectLst><a:outerShdw>) */
|
||||
shadow?: ShadowEffect
|
||||
/** WordArt gradient text fill (<a:rPr><a:gradFill>); color keeps a mid-stop fallback */
|
||||
gradient?: { stops: Array<{ pos: number; color: ResolvedColor }>; angle?: number }
|
||||
gradient?: {
|
||||
stops: Array<{ pos: number; color: ResolvedColor }>
|
||||
angle?: number
|
||||
scaled?: boolean
|
||||
}
|
||||
/** Run-level glow (<a:rPr><a:effectLst><a:glow>) */
|
||||
glow?: GlowEffect
|
||||
/** Run-level reflection (<a:rPr><a:effectLst><a:reflection>), rendered as a faded mirror */
|
||||
@@ -232,7 +252,7 @@ export type TextAlign = 'left' | 'center' | 'right' | 'justify'
|
||||
export interface Paragraph {
|
||||
runs: TextRun[]
|
||||
align?: TextAlign
|
||||
/** right-to-left paragraph (a:pPr rtl="1"); generated content only (pdf2pptx) */
|
||||
/** Paragraph base direction (a:pPr rtl): true = RTL base, false = explicit LTR base, absent = inferred from the first strong character */
|
||||
rtl?: boolean
|
||||
/** Indent level (bullet level) */
|
||||
level?: number
|
||||
@@ -335,6 +355,8 @@ export interface PPrDirty {
|
||||
spcBef?: boolean
|
||||
spcAft?: boolean
|
||||
align?: boolean
|
||||
/** Paragraph base direction rtl attribute */
|
||||
rtl?: boolean
|
||||
/** marL + indent as a pair (bullet indent linkage) */
|
||||
indents?: boolean
|
||||
/** Restrict the patch to these paragraph indices; absent = all paragraphs */
|
||||
|
||||
@@ -4,8 +4,11 @@ import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import {
|
||||
animClassOf,
|
||||
applyHeaderFooter,
|
||||
buildTimingXml,
|
||||
deleteElement,
|
||||
elementSpid,
|
||||
pruneTimingForSpids,
|
||||
getSlideAnimations,
|
||||
openPptx,
|
||||
readSlideTimingXml,
|
||||
@@ -70,8 +73,12 @@ describe('shape animations (<p:timing>)', () => {
|
||||
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 }])
|
||||
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 },
|
||||
@@ -88,7 +95,9 @@ describe('shape animations (<p:timing>)', () => {
|
||||
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 }])
|
||||
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)
|
||||
@@ -98,10 +107,13 @@ describe('shape animations (<p:timing>)', () => {
|
||||
|
||||
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 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 }])
|
||||
expect(anims).toEqual([
|
||||
{ spid: 7, effect: 'fade', trigger: 'onClick', durationMs: 500, delayMs: 0 },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -146,10 +158,19 @@ describe('extended effects + motion paths', () => {
|
||||
|
||||
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' },
|
||||
{
|
||||
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: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>')
|
||||
})
|
||||
|
||||
@@ -161,8 +182,22 @@ describe('extended effects + motion paths', () => {
|
||||
'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 },
|
||||
{
|
||||
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 },
|
||||
]
|
||||
@@ -173,9 +208,150 @@ describe('extended effects + motion paths', () => {
|
||||
})
|
||||
|
||||
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 }])
|
||||
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')
|
||||
})
|
||||
})
|
||||
|
||||
describe('pruneTimingForSpids (element removal must not leave dangling spTgt refs)', () => {
|
||||
async function seeded() {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const slide = opened.deck.slides[0]!
|
||||
const spids = slide.elements.map((el) => elementSpid(el)!)
|
||||
setSlideAnimations(slide, [
|
||||
{ spid: spids[0]!, effect: 'fade', trigger: 'onClick', durationMs: 500, delayMs: 0 },
|
||||
{ spid: spids[1]!, effect: 'flyIn', trigger: 'withPrev', durationMs: 800, delayMs: 0 },
|
||||
])
|
||||
return { opened, slide, spids }
|
||||
}
|
||||
|
||||
it('removes only the targeted effect, keeps the rest byte-preserved', async () => {
|
||||
const { slide, spids } = await seeded()
|
||||
expect(pruneTimingForSpids(slide, new Set([spids[0]!]))).toBe(true)
|
||||
const left = getSlideAnimations(slide)
|
||||
expect(left.map((a) => a.spid)).toEqual([spids[1]!])
|
||||
expect(slide.bodySuffix).not.toContain(`<p:spTgt spid="${spids[0]}"`)
|
||||
})
|
||||
|
||||
it('drops the whole <p:timing> when no target survives', async () => {
|
||||
const { slide, spids } = await seeded()
|
||||
pruneTimingForSpids(slide, new Set([spids[0]!, spids[1]!]))
|
||||
expect(slide.bodySuffix).not.toContain('<p:timing>')
|
||||
})
|
||||
|
||||
it('a trigger reference removes only its interactiveSeq, never the whole timing', async () => {
|
||||
const { slide, spids } = await seeded()
|
||||
const TRIGGER_SEQ =
|
||||
'<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="${spids[1]}"/></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>'
|
||||
const at = slide.bodySuffix.indexOf('</p:seq>') + '</p:seq>'.length
|
||||
slide.bodySuffix = slide.bodySuffix.slice(0, at) + TRIGGER_SEQ + slide.bodySuffix.slice(at)
|
||||
|
||||
// Deleting the trigger shape (99): its seq goes — including the triggered
|
||||
// effect on a surviving shape — but the main sequence stays intact
|
||||
expect(pruneTimingForSpids(slide, new Set([99]))).toBe(true)
|
||||
expect(slide.bodySuffix).toContain('<p:timing>')
|
||||
expect(slide.bodySuffix).not.toContain('interactiveSeq')
|
||||
expect(getSlideAnimations(slide).map((a) => a.spid)).toEqual([spids[0]!, spids[1]!])
|
||||
})
|
||||
|
||||
it('pruning an effect target inside an interactiveSeq removes only that effect par', async () => {
|
||||
const { slide, spids } = await seeded()
|
||||
// interactiveSeq triggered by shape 99 with TWO effects: one on spids[0]
|
||||
// (about to be deleted) and one on spids[1] (must survive). The effect's
|
||||
// own closed delay cond must not be mistaken for a trigger wrapper.
|
||||
const effectPar = (id: number, spid: number) =>
|
||||
`<p:par><p:cTn id="${id}" 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="${id + 1}" dur="1" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst></p:cTn>` +
|
||||
`<p:tgtEl><p:spTgt spid="${spid}"/></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>'
|
||||
const TRIGGER_SEQ =
|
||||
'<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>${effectPar(901, spids[0]!)}${effectPar(910, spids[1]!)}</p:childTnLst></p:cTn></p:seq>`
|
||||
const at = slide.bodySuffix.indexOf('</p:seq>') + '</p:seq>'.length
|
||||
slide.bodySuffix = slide.bodySuffix.slice(0, at) + TRIGGER_SEQ + slide.bodySuffix.slice(at)
|
||||
|
||||
pruneTimingForSpids(slide, new Set([spids[0]!]))
|
||||
expect(slide.bodySuffix).toContain('interactiveSeq') // seq survives
|
||||
const spidsLeft = [...slide.bodySuffix.matchAll(/<p:spTgt spid="(\d+)"/g)].map((m) =>
|
||||
Number(m[1]),
|
||||
)
|
||||
expect(spidsLeft).not.toContain(spids[0]!)
|
||||
expect(spidsLeft.filter((x) => x === spids[1]!).length).toBeGreaterThanOrEqual(2) // mainSeq + trigger effect
|
||||
expect(spidsLeft).toContain(99)
|
||||
})
|
||||
|
||||
it('prunes the matching bldP build refs and keeps the survivors', async () => {
|
||||
const { slide, spids } = await seeded()
|
||||
expect(slide.bodySuffix).toContain(`<p:bldP spid="${spids[0]}"`)
|
||||
pruneTimingForSpids(slide, new Set([spids[0]!]))
|
||||
expect(slide.bodySuffix).not.toContain(`<p:bldP spid="${spids[0]}"`)
|
||||
expect(slide.bodySuffix).toContain(`<p:bldP spid="${spids[1]}"`)
|
||||
})
|
||||
|
||||
it('a wrapper shared with a surviving target is left alone (no collateral destruction)', () => {
|
||||
// One par carrying behaviors for two shapes: pruning one of them must not
|
||||
// take the shared par (and the survivor's animation) with it
|
||||
const sharedPar =
|
||||
'<p:timing><p:tnLst><p:par><p:cTn id="1" nodeType="tmRoot"><p:childTnLst>' +
|
||||
'<p:par><p:cTn id="2"><p:childTnLst>' +
|
||||
'<p:set><p:cBhvr><p:cTn id="3" dur="1"/><p:tgtEl><p:spTgt spid="5"/></p:tgtEl></p:cBhvr></p:set>' +
|
||||
'<p:set><p:cBhvr><p:cTn id="4" dur="1"/><p:tgtEl><p:spTgt spid="6"/></p:tgtEl></p:cBhvr></p:set>' +
|
||||
'</p:childTnLst></p:cTn></p:par>' +
|
||||
'</p:childTnLst></p:cTn></p:par></p:tnLst></p:timing>'
|
||||
const slide = {
|
||||
bodySuffix: `${sharedPar}</p:sld>`,
|
||||
structureDirty: false,
|
||||
} as never as Parameters<typeof pruneTimingForSpids>[0]
|
||||
expect(pruneTimingForSpids(slide, new Set([5]))).toBe(false)
|
||||
expect((slide as { bodySuffix: string }).bodySuffix).toContain('<p:spTgt spid="6"')
|
||||
expect((slide as { bodySuffix: string }).bodySuffix).toContain('<p:spTgt spid="5"')
|
||||
})
|
||||
|
||||
it('deleteElement prunes the deleted shape from the timing', async () => {
|
||||
const { opened, slide, spids } = await seeded()
|
||||
const victim = slide.elements.find((el) => elementSpid(el) === spids[0])!
|
||||
expect(deleteElement(opened, slide, victim.id)).toBe(true)
|
||||
expect(slide.bodySuffix).not.toContain(`<p:spTgt spid="${spids[0]}"`)
|
||||
expect(getSlideAnimations(slide).map((a) => a.spid)).toEqual([spids[1]!])
|
||||
// survives save→reopen
|
||||
const saved = await openPptx(await savePptx(opened))
|
||||
const spidsAfter = new Set(
|
||||
[...saved.deck.slides[0]!.bodySuffix.matchAll(/<p:spTgt spid="(\d+)"/g)].map((m) =>
|
||||
Number(m[1]),
|
||||
),
|
||||
)
|
||||
expect(spidsAfter.has(spids[0]!)).toBe(false)
|
||||
expect(spidsAfter.has(spids[1]!)).toBe(true)
|
||||
})
|
||||
|
||||
it('applyHeaderFooter prunes animations of the placeholders it replaces', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
// First install footers, animate one, then re-apply: the old placeholder
|
||||
// is removed and its animation must go with it
|
||||
expect(applyHeaderFooter(opened, { footer: 'v1', slideNum: true })).toBe(true)
|
||||
const slide = opened.deck.slides[0]!
|
||||
const ftr = slide.elements.find((el) => el.placeholder === 'ftr')!
|
||||
const spid = elementSpid(ftr)!
|
||||
setSlideAnimations(slide, [
|
||||
{ spid, effect: 'fade', trigger: 'onClick', durationMs: 500, delayMs: 0 },
|
||||
])
|
||||
expect(applyHeaderFooter(opened, { footer: 'v2', slideNum: true })).toBe(true)
|
||||
const fresh = opened.deck.slides[0]!
|
||||
const ids = new Set(fresh.elements.map((el) => elementSpid(el)))
|
||||
for (const m of fresh.bodySuffix.matchAll(/<p:spTgt spid="(\d+)"/g)) {
|
||||
expect(ids.has(Number(m[1]))).toBe(true)
|
||||
}
|
||||
expect(fresh.bodySuffix).not.toContain(`<p:spTgt spid="${spid}"`)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import JSZip from 'jszip'
|
||||
import { PackageArchive } from '../src/zip'
|
||||
import { eotToSfnt, listEmbeddedFonts } from '../src/embedded-fonts'
|
||||
|
||||
/** Minimal valid-enough sfnt payload: TrueType magic + filler. */
|
||||
function fakeSfnt(seed = 1): Uint8Array {
|
||||
const b = new Uint8Array(64).fill(seed)
|
||||
b.set([0x00, 0x01, 0x00, 0x00], 0)
|
||||
return b
|
||||
}
|
||||
|
||||
/** Wrap a payload in a 16-byte-min EOT header (variable header fields collapsed to none). */
|
||||
function eotWrap(payload: Uint8Array, flags: number, headerPad = 32): Uint8Array {
|
||||
const out = new Uint8Array(16 + headerPad + payload.length)
|
||||
const dv = new DataView(out.buffer)
|
||||
dv.setUint32(0, out.length, true) // EOTSize
|
||||
dv.setUint32(4, payload.length, true) // FontDataSize
|
||||
dv.setUint32(8, 0x00020002, true) // Version
|
||||
dv.setUint32(12, flags, true)
|
||||
out.set(payload, 16 + headerPad)
|
||||
return out
|
||||
}
|
||||
|
||||
describe('eotToSfnt', () => {
|
||||
it('unwraps an uncompressed EOT to its trailing sfnt payload', () => {
|
||||
const sfnt = fakeSfnt()
|
||||
expect(eotToSfnt(eotWrap(sfnt, 0))).toEqual(sfnt)
|
||||
})
|
||||
|
||||
it('decodes the XOR-obfuscated payload variant', () => {
|
||||
const sfnt = fakeSfnt()
|
||||
const xored = sfnt.map((b) => b ^ 0x50)
|
||||
expect(eotToSfnt(eotWrap(xored, 0x10000000))).toEqual(sfnt)
|
||||
})
|
||||
|
||||
it('rejects MicroType-Express-compressed EOTs (flag 0x4)', () => {
|
||||
expect(eotToSfnt(eotWrap(fakeSfnt(), 0x00000005))).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects payloads without an sfnt magic and truncated headers', () => {
|
||||
expect(eotToSfnt(eotWrap(new Uint8Array(32).fill(9), 0))).toBeNull()
|
||||
expect(eotToSfnt(new Uint8Array(8))).toBeNull()
|
||||
})
|
||||
|
||||
it('passes through a bare sfnt without an EOT wrapper (LibreOffice-style fntdata)', () => {
|
||||
const sfnt = fakeSfnt()
|
||||
expect(eotToSfnt(sfnt)).toBe(sfnt)
|
||||
})
|
||||
})
|
||||
|
||||
describe('listEmbeddedFonts', () => {
|
||||
it('reads embeddedFontLst faces via presentation rels, skipping compressed parts', async () => {
|
||||
const zip = new JSZip()
|
||||
zip.file(
|
||||
'ppt/presentation.xml',
|
||||
'<?xml version="1.0"?><p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
|
||||
'<p:embeddedFontLst>' +
|
||||
'<p:embeddedFont><p:font typeface="League Spartan"/><p:regular r:id="rId7"/><p:bold r:id="rId8"/></p:embeddedFont>' +
|
||||
'<p:embeddedFont><p:font typeface="Poppins"/><p:regular r:id="rId9"/></p:embeddedFont>' +
|
||||
'</p:embeddedFontLst>' +
|
||||
'<p:sldSz cx="12192000" cy="6858000"/></p:presentation>',
|
||||
)
|
||||
zip.file(
|
||||
'ppt/_rels/presentation.xml.rels',
|
||||
'<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
'<Relationship Id="rId7" Type="f" Target="fonts/font1.fntdata"/>' +
|
||||
'<Relationship Id="rId8" Type="f" Target="fonts/font2.fntdata"/>' +
|
||||
'<Relationship Id="rId9" Type="f" Target="fonts/font3.fntdata"/>' +
|
||||
'</Relationships>',
|
||||
)
|
||||
const reg = fakeSfnt(1)
|
||||
const bold = fakeSfnt(2)
|
||||
zip.file('ppt/fonts/font1.fntdata', eotWrap(reg, 0))
|
||||
zip.file('ppt/fonts/font2.fntdata', eotWrap(bold, 0))
|
||||
zip.file('ppt/fonts/font3.fntdata', eotWrap(fakeSfnt(3), 0x5)) // MTX-compressed -> skipped
|
||||
const archive = await PackageArchive.open(await zip.generateAsync({ type: 'uint8array' }))
|
||||
const faces = listEmbeddedFonts(archive)
|
||||
expect(faces.map((f) => [f.typeface, f.style])).toEqual([
|
||||
['League Spartan', 'regular'],
|
||||
['League Spartan', 'bold'],
|
||||
])
|
||||
expect(faces[0]!.sfnt).toEqual(reg)
|
||||
expect(faces[1]!.sfnt).toEqual(bold)
|
||||
})
|
||||
|
||||
it('returns [] when no embedded fonts are declared', async () => {
|
||||
const zip = new JSZip()
|
||||
zip.file(
|
||||
'ppt/presentation.xml',
|
||||
'<?xml version="1.0"?><p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:sldSz cx="12192000" cy="6858000"/></p:presentation>',
|
||||
)
|
||||
const archive = await PackageArchive.open(await zip.generateAsync({ type: 'uint8array' }))
|
||||
expect(listEmbeddedFonts(archive)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -97,7 +97,9 @@ describe('slide master edit write-back (byte surgery)', () => {
|
||||
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
|
||||
// user explicitly recolored: no longer follows the theme or inheritance
|
||||
delete r.colorFollowsTheme
|
||||
delete r.colorInherited
|
||||
}
|
||||
title.dirty = true
|
||||
opened.archive.entries.set(masterPath, Buffer.from(patchSlideXml(master), 'utf8'))
|
||||
|
||||
@@ -151,6 +151,30 @@ describe('setElementParagraphFormat', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('paragraph direction rtl', () => {
|
||||
it('rtl=true injects rtl="1" on pPr, run bytes untouched', () => {
|
||||
const RUN = '<a:r><a:rPr sz="1800"/><a:t>Hi</a:t></a:r>'
|
||||
const { slide, el } = parseOne(`<a:bodyPr/><a:p>${RUN}</a:p>`)
|
||||
expect(setElementParagraphFormat(slide, el.id, { rtl: true })).toBe(true)
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('rtl="1"')
|
||||
expect(out).toContain(RUN)
|
||||
expect(el.text!.paragraphs[0]!.rtl).toBe(true)
|
||||
})
|
||||
|
||||
it('rtl=false rewrites an existing rtl="1" to rtl="0" (explicit LTR base)', () => {
|
||||
const { slide, el } = parseOne(
|
||||
'<a:bodyPr/><a:p><a:pPr rtl="1" algn="r"/><a:r><a:t>x</a:t></a:r></a:p>',
|
||||
)
|
||||
setElementParagraphFormat(slide, el.id, { rtl: false })
|
||||
const out = patchedElementXml(el)
|
||||
expect(out).toContain('rtl="0"')
|
||||
expect(out).not.toContain('rtl="1"')
|
||||
expect(out).toContain('algn="r"') // untouched sibling attribute
|
||||
expect(el.text!.paragraphs[0]!.rtl).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
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>')
|
||||
|
||||
@@ -3,7 +3,7 @@ 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 { openPptx, savePptx, reassembleSlideXml, generateParagraphXml } from '../src/index'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { tableRowGridCols } from '../src/table-grid'
|
||||
import { parsePlaceholderMap, parseMasterTextStyles } from '../src/placeholder'
|
||||
@@ -104,6 +104,24 @@ describe('fill / color-mod / background parsing', () => {
|
||||
{ pos: 1, color: '#00FF00' },
|
||||
])
|
||||
expect(el.fill.angle).toBe(2700000)
|
||||
expect(el.fill.scaled).toBeUndefined()
|
||||
})
|
||||
|
||||
it('gradient fill: a:lin scaled="1" surfaces the aspect-stretch flag', () => {
|
||||
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" scaled="1"/></a:gradFill></p:spPr></p:sp>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(sp),
|
||||
ctx: { theme },
|
||||
})
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.fill.type).toBe('gradient')
|
||||
expect(el.fill.scaled).toBe(true)
|
||||
})
|
||||
|
||||
it('gradFill with no a:lin/a:path defaults to a vertical ramp (PowerPoint-measured)', () => {
|
||||
@@ -387,6 +405,28 @@ describe('text body parsing fidelity', () => {
|
||||
expect(firstText(slide).paragraphs[0].lineExact).toBe(24)
|
||||
})
|
||||
|
||||
it('parses a:pPr rtl: "1"/"true" → true, "0" → false, absent → undefined', () => {
|
||||
const rtlOf = (pPr: string) =>
|
||||
firstText(
|
||||
parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(spWith(`<a:p>${pPr}<a:r><a:t>x</a:t></a:r></a:p>`)),
|
||||
ctx: {},
|
||||
}),
|
||||
).paragraphs[0].rtl
|
||||
expect(rtlOf('<a:pPr rtl="1"/>')).toBe(true)
|
||||
expect(rtlOf('<a:pPr rtl="true"/>')).toBe(true)
|
||||
expect(rtlOf('<a:pPr rtl="0"/>')).toBe(false)
|
||||
expect(rtlOf('<a:pPr/>')).toBeUndefined()
|
||||
expect(rtlOf('')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('generateParagraphXml round-trips explicit rtl (true and false)', () => {
|
||||
expect(generateParagraphXml({ runs: [{ text: 'x' }], rtl: true })).toContain('rtl="1"')
|
||||
expect(generateParagraphXml({ runs: [{ text: 'x' }], rtl: false })).toContain('rtl="0"')
|
||||
expect(generateParagraphXml({ runs: [{ text: 'x' }] })).not.toContain('rtl=')
|
||||
})
|
||||
|
||||
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>' +
|
||||
@@ -573,6 +613,28 @@ describe('placeholder text style inheritance', () => {
|
||||
expect(run.bold).toBe(false)
|
||||
})
|
||||
|
||||
it('explicit srgbClr with modifiers resolves the display color but keeps byte linkage', () => {
|
||||
const sp =
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="8" name="T"/><p:nvSpPr/><p:nvPr/></p:nvSpPr>' +
|
||||
'<p:spPr/><p:txBody><a:bodyPr/><a:p>' +
|
||||
'<a:r><a:rPr><a:solidFill><a:srgbClr val="44546A"><a:lumMod val="75000"/></a:srgbClr></a:solidFill></a:rPr><a:t>modded</a:t></a:r>' +
|
||||
'<a:r><a:rPr><a:solidFill><a:srgbClr val="112233"/></a:solidFill></a:rPr><a:t>plain</a:t></a:r>' +
|
||||
'</a:p></p:txBody></p:sp>'
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideXmlWith(sp),
|
||||
ctx: { theme },
|
||||
})
|
||||
const runs = (slide.elements[0] as any).text.paragraphs[0].runs
|
||||
// lumMod'ed srgbClr: display value is computed, so a rewrite would bake it in
|
||||
// and drop the modifier — the patch path must keep the original bytes
|
||||
expect(runs[0].colorFollowsTheme).toBe(true)
|
||||
expect(runs[0].color?.toUpperCase()).toBe('#333F50') // 44546A × lumMod 75%
|
||||
// plain srgbClr stays directly patchable
|
||||
expect(runs[1].colorFollowsTheme).toBeUndefined()
|
||||
expect(runs[1].color?.toUpperCase()).toBe('#112233')
|
||||
})
|
||||
|
||||
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>' +
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Full-rebuild rPr fidelity: explicit "off" attributes (b="0", u="none",
|
||||
* strike="noStrike", spc="0", baseline="0", cap="none", kern) are overrides of
|
||||
* inherited styling — a rebuild that drops them re-inherits from the
|
||||
* placeholder/master chain. Bodies containing <a:fld> always take the rebuild
|
||||
* path, so slide-number placeholders were losing these (edit-eval identity
|
||||
* sweep, prod_016 / Lecture_Week_5).
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { rebuildTxBody } from '../src/generate'
|
||||
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 parseEl = (spTree: string): TextElement => {
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: wrap(spTree), ctx: {} })
|
||||
return slide.elements[0] as TextElement
|
||||
}
|
||||
|
||||
const EXPLICIT_OFF_RPR =
|
||||
'kumimoji="0" lang="en-US" sz="900" b="0" i="0" u="none" strike="noStrike" ' +
|
||||
'kern="1200" cap="none" spc="0" baseline="0"'
|
||||
|
||||
describe('rebuildTxBody keeps explicit-off rPr attributes', () => {
|
||||
it('a fld run re-emits b/i/u/strike/kern/cap/spc/baseline overrides', () => {
|
||||
const el = parseEl(
|
||||
textBox(
|
||||
`<a:p>` +
|
||||
`<a:fld id="{B6D32A31-0000-0000-0000-000000000002}" type="slidenum">` +
|
||||
`<a:rPr ${EXPLICIT_OFF_RPR}/><a:t>7</a:t></a:fld>` +
|
||||
`</a:p>`,
|
||||
),
|
||||
)
|
||||
const xml = rebuildTxBody(el, el.anchor.originalXml)
|
||||
const rpr = /<a:fld[^>]*>(<a:rPr[^>]*\/?>)/.exec(xml)?.[1] ?? ''
|
||||
expect(rpr).toContain('b="0"')
|
||||
expect(rpr).toContain('i="0"')
|
||||
expect(rpr).toContain('u="none"')
|
||||
expect(rpr).toContain('strike="noStrike"')
|
||||
expect(rpr).toContain('kern="1200"')
|
||||
expect(rpr).toContain('cap="none"')
|
||||
expect(rpr).toContain('spc="0"')
|
||||
expect(rpr).toContain('baseline="0"')
|
||||
})
|
||||
|
||||
it('a plain run in the same rebuilt body keeps its overrides too', () => {
|
||||
const el = parseEl(
|
||||
textBox(
|
||||
`<a:p>` +
|
||||
`<a:r><a:rPr ${EXPLICIT_OFF_RPR}/><a:t>page </a:t></a:r>` +
|
||||
`<a:fld id="{B6D32A31-0000-0000-0000-000000000003}" type="slidenum">` +
|
||||
`<a:rPr lang="en-US"/><a:t>7</a:t></a:fld>` +
|
||||
`</a:p>`,
|
||||
),
|
||||
)
|
||||
const xml = rebuildTxBody(el, el.anchor.originalXml)
|
||||
const rpr = /<a:r><a:rPr[^>]*/.exec(xml)?.[0] ?? ''
|
||||
expect(rpr).toContain('b="0"')
|
||||
expect(rpr).toContain('u="none"')
|
||||
expect(rpr).toContain('strike="noStrike"')
|
||||
expect(rpr).toContain('cap="none"')
|
||||
})
|
||||
|
||||
it('inherited (attr-less) runs still write no override attributes', () => {
|
||||
const el = parseEl(
|
||||
textBox(
|
||||
`<a:p>` +
|
||||
`<a:r><a:rPr lang="en-US"/><a:t>plain</a:t></a:r>` +
|
||||
`<a:fld id="{B6D32A31-0000-0000-0000-000000000004}" type="slidenum">` +
|
||||
`<a:rPr lang="en-US"/><a:t>7</a:t></a:fld>` +
|
||||
`</a:p>`,
|
||||
),
|
||||
)
|
||||
const xml = rebuildTxBody(el, el.anchor.originalXml)
|
||||
for (const frag of ['b="', 'i="', 'u="', 'strike="', 'cap="', 'spc="', 'baseline="']) {
|
||||
expect(xml).not.toContain(frag)
|
||||
}
|
||||
})
|
||||
|
||||
it('non-plain color nodes restore verbatim instead of baking the resolved value', () => {
|
||||
const el = parseEl(
|
||||
textBox(
|
||||
`<a:p>` +
|
||||
`<a:fld id="{B6D32A31-0000-0000-0000-000000000006}" type="slidenum">` +
|
||||
`<a:rPr lang="en-US"><a:solidFill><a:prstClr val="black"><a:tint val="75000"/></a:prstClr></a:solidFill></a:rPr>` +
|
||||
`<a:t>7</a:t></a:fld>` +
|
||||
`<a:r><a:rPr lang="en-US"><a:solidFill><a:schemeClr val="accent1"><a:lumMod val="75000"/></a:schemeClr></a:solidFill></a:rPr>` +
|
||||
`<a:t>x</a:t></a:r>` +
|
||||
`</a:p>`,
|
||||
),
|
||||
)
|
||||
const xml = rebuildTxBody(el, el.anchor.originalXml)
|
||||
expect(xml).toContain('<a:prstClr val="black"><a:tint val="75000"/></a:prstClr>')
|
||||
expect(xml).toContain('<a:schemeClr val="accent1"><a:lumMod val="75000"/></a:schemeClr>')
|
||||
expect(xml).not.toMatch(/<a:srgbClr/)
|
||||
})
|
||||
|
||||
it('positive styles keep winning over the off markers (u/strike style preserved)', () => {
|
||||
const el = parseEl(
|
||||
textBox(
|
||||
`<a:p>` +
|
||||
`<a:r><a:rPr lang="en-US" b="1" u="dbl" strike="dblStrike"/><a:t>styled</a:t></a:r>` +
|
||||
`<a:fld id="{B6D32A31-0000-0000-0000-000000000005}" type="slidenum">` +
|
||||
`<a:rPr lang="en-US"/><a:t>7</a:t></a:fld>` +
|
||||
`</a:p>`,
|
||||
),
|
||||
)
|
||||
const xml = rebuildTxBody(el, el.anchor.originalXml)
|
||||
expect(xml).toContain('b="1"')
|
||||
expect(xml).toContain('u="dbl"')
|
||||
expect(xml).toContain('strike="dblStrike"')
|
||||
})
|
||||
})
|
||||
@@ -28,6 +28,37 @@ describe('patchTableStyleXml', () => {
|
||||
expect(result).toContain('{2D5ABB26-0587-4C30-8999-92F81FD0307C}')
|
||||
})
|
||||
|
||||
it('style preset keeps an existing rtl flag (direction is orthogonal to style)', () => {
|
||||
const rtlTable = patchTableStyleXml(MINIMAL_TABLE_XML, { rtl: true })
|
||||
const preset = TABLE_STYLE_PRESETS['zebraBlue']!
|
||||
const styled = patchTableStyleXml(rtlTable, { tblPrXml: preset.tblPrXml })
|
||||
expect(styled).toContain('rtl="1"')
|
||||
expect(styled).toContain(preset.styleId)
|
||||
// A table without rtl does not gain one from the preset
|
||||
const plain = patchTableStyleXml(MINIMAL_TABLE_XML, { tblPrXml: preset.tblPrXml })
|
||||
expect(plain).not.toContain('rtl=')
|
||||
})
|
||||
|
||||
it('rtl=true adds the tblPr rtl flag, rtl=false removes it; siblings untouched', () => {
|
||||
const on = patchTableStyleXml(MINIMAL_TABLE_XML, { rtl: true })
|
||||
expect(on).toContain('rtl="1"')
|
||||
expect(on).toContain('firstRow="1"')
|
||||
expect(on).toContain('{2D5ABB26-0587-4C30-8999-92F81FD0307C}')
|
||||
const off = patchTableStyleXml(on, { rtl: false })
|
||||
expect(off).not.toContain('rtl=')
|
||||
expect(off).toContain('bandRow="1"')
|
||||
})
|
||||
|
||||
it('rtl toggle expands a self-closing tblPr with attributes (trailing slash stripped)', () => {
|
||||
const selfClosing = MINIMAL_TABLE_XML.replace(
|
||||
/<a:tblPr[^>]*>.*?<\/a:tblPr>/,
|
||||
'<a:tblPr firstRow="1"/>',
|
||||
)
|
||||
const result = patchTableStyleXml(selfClosing, { rtl: true })
|
||||
expect(result).toContain('<a:tblPr firstRow="1" rtl="1"></a:tblPr>')
|
||||
expect(result).not.toContain('/ rtl')
|
||||
})
|
||||
|
||||
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"/>')
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
resizeTable,
|
||||
setTableRowHeight,
|
||||
setTableCellAnchor,
|
||||
setTableColWidth,
|
||||
editTableStructure,
|
||||
setElementTextAnchor,
|
||||
addElement,
|
||||
createBlankPptx,
|
||||
@@ -117,3 +119,74 @@ describe('setElementTextAnchor', () => {
|
||||
expect(el.anchor.originalXml).toMatch(/<a:bodyPr anchor="t"/)
|
||||
})
|
||||
})
|
||||
|
||||
// Google Slides exports attach an <a:extLst> a16:colId to every gridCol, so
|
||||
// the columns are paired tags, not self-closing — the surgery paths must not
|
||||
// assume the self-closing form (they used to, and missed or mis-indexed cols).
|
||||
function pairGridCols(tbl: TableElement): void {
|
||||
let i = 0
|
||||
tbl.anchor.originalXml = tbl.anchor.originalXml.replace(
|
||||
/<a:gridCol w="(\d+)"\/>/g,
|
||||
(_m, w: string) =>
|
||||
`<a:gridCol w="${w}"><a:extLst><a:ext uri="{9D8B030D-6E8A-4147-A177-3AD203B41FA5}">` +
|
||||
`<a16:colId xmlns:a16="http://schemas.microsoft.com/office/drawing/2014/main" val="${20000 + i++}"/>` +
|
||||
`</a:ext></a:extLst></a:gridCol>`,
|
||||
)
|
||||
}
|
||||
|
||||
describe('paired-form gridCol (extLst children)', () => {
|
||||
it('setTableColWidth patches the right column and keeps the extLst', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const r = addTable(opened, 0, {
|
||||
rows: 2,
|
||||
cols: 3,
|
||||
offset: { x: 0, y: 0, cx: 3000000, cy: 800000 },
|
||||
})!
|
||||
const tbl = r.slide.elements.find((e) => e.id === r.elementId) as TableElement
|
||||
pairGridCols(tbl)
|
||||
expect(setTableColWidth(r.slide, r.elementId, 1, 999000)).toBe(true)
|
||||
const xml = tbl.anchor.originalXml
|
||||
const cols = [...xml.matchAll(/<a:gridCol w="(\d+)">/g)].map((m) => Number(m[1]))
|
||||
expect(cols[1]).toBe(999000)
|
||||
expect(tbl.colWidths[1]).toBe(999000)
|
||||
expect([...xml.matchAll(/a16:colId/g)]).toHaveLength(3)
|
||||
const sum = tbl.colWidths.reduce((a, b) => a + b, 0)
|
||||
expect(xml).toContain(`cx="${sum}"`)
|
||||
})
|
||||
|
||||
it('resizeTable scales paired-form columns too', 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
|
||||
pairGridCols(tbl)
|
||||
expect(resizeTable(r.slide, r.elementId, 1000000, 400000)).toBe(true)
|
||||
const xml = tbl.anchor.originalXml
|
||||
const colSum = [...xml.matchAll(/<a:gridCol w="(\d+)">/g)].reduce((a, m) => a + Number(m[1]), 0)
|
||||
expect(colSum).toBe(1000000)
|
||||
})
|
||||
|
||||
it('editTableStructure counts paired-form columns and inserts a fresh colId-free clone', 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
|
||||
pairGridCols(tbl)
|
||||
const res = editTableStructure(opened, 0, r.elementId, { kind: 'insert-col', index: 1 })
|
||||
expect(res).not.toBeNull()
|
||||
const fresh = res!.slide.elements.find((e) => e.id === res!.elementId) as TableElement
|
||||
expect(fresh.colWidths).toHaveLength(3)
|
||||
// the clone must not duplicate the reference column's unique a16:colId
|
||||
expect([...fresh.anchor.originalXml.matchAll(/a16:colId/g)]).toHaveLength(2)
|
||||
const del = editTableStructure(opened, 0, res!.elementId, { kind: 'delete-col', index: 0 })
|
||||
expect(del).not.toBeNull()
|
||||
const after = del!.slide.elements.find((e) => e.id === del!.elementId) as TableElement
|
||||
expect(after.colWidths).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Chart-part theme overrides (<a:themeOverride>): the chart's schemeClr refs
|
||||
* resolve against ITS clrScheme, not the deck theme's — decks legitimately
|
||||
* remap accents per chart (prod_050: accent1 and accent5 swapped, so every
|
||||
* series painted the wrong blue without this).
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseTheme, themeWithOverride } from '../src/theme'
|
||||
|
||||
const BASE = parseTheme(
|
||||
`<a:theme><a:themeElements><a:clrScheme name="b">` +
|
||||
`<a:dk1><a:srgbClr val="000000"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1>` +
|
||||
`<a:dk2><a:srgbClr val="111111"/></a:dk2><a:lt2><a:srgbClr val="EEEEEE"/></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:themeElements></a:theme>`,
|
||||
)
|
||||
|
||||
const OVERRIDE =
|
||||
`<a:themeOverride xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">` +
|
||||
`<a:clrScheme name="o">` +
|
||||
`<a:dk1><a:srgbClr val="000000"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1>` +
|
||||
`<a:dk2><a:srgbClr val="222222"/></a:dk2><a:lt2><a:srgbClr val="DDDDDD"/></a:lt2>` +
|
||||
`<a:accent1><a:srgbClr val="5B9BD5"/></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:themeOverride>`
|
||||
|
||||
describe('themeWithOverride', () => {
|
||||
it('override clrScheme wins; base fonts survive when the override has none', () => {
|
||||
const t = themeWithOverride({ ...BASE, clrMap: { bg1: 'dk1' } }, OVERRIDE)
|
||||
expect(t.colors.accent5).toBe('#4472C4') // swapped relative to the base
|
||||
expect(t.colors.accent1).toBe('#5B9BD5')
|
||||
expect(t.minorFont).toBe('Calibri') // fontScheme absent from the override → base kept
|
||||
expect(t.clrMap).toEqual({ bg1: 'dk1' }) // clrMap is a master concern, never overridden
|
||||
})
|
||||
|
||||
it('an override fontScheme replaces the base fonts', () => {
|
||||
const ov = OVERRIDE.replace(
|
||||
'</a:clrScheme></a:themeOverride>',
|
||||
`</a:clrScheme><a:fontScheme name="of"><a:majorFont><a:latin typeface="Georgia"/></a:majorFont>` +
|
||||
`<a:minorFont><a:latin typeface="Verdana"/></a:minorFont></a:fontScheme></a:themeOverride>`,
|
||||
)
|
||||
const t = themeWithOverride(BASE, ov)
|
||||
expect(t.minorFont).toBe('Verdana')
|
||||
expect(t.majorFont).toBe('Georgia')
|
||||
})
|
||||
|
||||
it('a malformed override leaves the base theme untouched', () => {
|
||||
expect(themeWithOverride(BASE, '<a:nope/>')).toEqual(BASE)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user