Sync snapshot (2026-08-23) (#130)
- Convert scanned PDFs to editable text with local OCR, running through the operating system's own engine on macOS and Windows - Add a much richer AI workflow to Docs, PDF, and Markdown: selection-scoped questions, batched edits, character-level edits, comment and tracked-change awareness, citations back to the source block, and in-document image generation - Let Slides open the same presentation in a second window and edit it from both - Improve PDF to Excel table recovery: tables spanning pages merge into one worksheet, and label/value grids and rule-less statement bands become real rows - Fix a large wave of Word layout fidelity in Docs, Excel parity in Sheets, and PowerPoint import fidelity in Slides Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
f68df70e22
commit
6d9b6812dd
@@ -7,6 +7,7 @@
|
||||
"description": "pptx parsing (Slide element tree with byte anchors + inheritance resolution), OOXML fragment generation, element-patch save",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./custgeom": "./src/custgeom.ts",
|
||||
"./table-grid": "./src/table-grid.ts",
|
||||
"./identity": "./src/identity.ts",
|
||||
"./background-promote": "./src/background-promote.ts"
|
||||
|
||||
@@ -109,6 +109,9 @@ export interface ChartAxisStyle {
|
||||
/** Explicit tick units (c:majorUnit / c:minorUnit) */
|
||||
majorUnit?: number
|
||||
minorUnit?: number
|
||||
/** Category-axis explicit skips: label every Nth category / tick+gridline every Nth slot */
|
||||
tickLblSkip?: number
|
||||
tickMarkSkip?: number
|
||||
title?: string
|
||||
/** <c:title><c:overlay val="1"/>: the axis title floats over the plot, reserving no space */
|
||||
titleOverlay?: boolean
|
||||
@@ -263,17 +266,21 @@ export function parseChartXml(
|
||||
// Cartesian types (bar/area/line) may coexist combined (e.g. column+line combo); pie/scatter/radar stand alone.
|
||||
// 3D variants map onto the 2D pipelines (same data/palette/legend); the render layer adds a
|
||||
// pseudo-3D look (elliptical pie with a rim, extruded bars) driven by pseudo3D + c:view3D rotX.
|
||||
const cartesian: Array<{ kind: 'bar' | 'area' | 'line'; plot: any }> = []
|
||||
const barPlot = plotArea['c:barChart'] ?? plotArea['c:bar3DChart']
|
||||
const areaPlot = plotArea['c:areaChart'] ?? plotArea['c:area3DChart']
|
||||
const linePlot = plotArea['c:lineChart'] ?? plotArea['c:line3DChart']
|
||||
// The same plot type may appear twice in one plotArea (primary + secondary-axis group:
|
||||
// two c:lineChart nodes) — fast-xml-parser then yields an array; flatten each node into
|
||||
// its own combo entry so the secondary group's series and axId still parse.
|
||||
const plots = (n: any): any[] => (Array.isArray(n) ? n : n ? [n] : [])
|
||||
const cartesian: Array<{ kind: 'bar' | 'area' | 'line'; plot: any; stock?: boolean }> = []
|
||||
// Stock (open-)high-low-close rides the line pipeline: category axis + one value series
|
||||
// per role; whiskers/up-down bars come from the stock flags, connecting lines stay off
|
||||
const stockPlot = plotArea['c:stockChart']
|
||||
if (barPlot) cartesian.push({ kind: 'bar', plot: barPlot })
|
||||
if (areaPlot) cartesian.push({ kind: 'area', plot: areaPlot })
|
||||
if (linePlot) cartesian.push({ kind: 'line', plot: linePlot })
|
||||
if (stockPlot) cartesian.push({ kind: 'line', plot: stockPlot })
|
||||
for (const p of plots(plotArea['c:barChart'] ?? plotArea['c:bar3DChart']))
|
||||
cartesian.push({ kind: 'bar', plot: p })
|
||||
for (const p of plots(plotArea['c:areaChart'] ?? plotArea['c:area3DChart']))
|
||||
cartesian.push({ kind: 'area', plot: p })
|
||||
for (const p of plots(plotArea['c:lineChart'] ?? plotArea['c:line3DChart']))
|
||||
cartesian.push({ kind: 'line', plot: p })
|
||||
for (const p of plots(stockPlot)) cartesian.push({ kind: 'line', plot: p, stock: true })
|
||||
|
||||
const piePlot = plotArea['c:pieChart'] ?? plotArea['c:pie3DChart'] ?? plotArea['c:doughnutChart']
|
||||
|
||||
@@ -338,6 +345,9 @@ export function parseChartXml(
|
||||
const s: ChartSeries = {
|
||||
values: readNumPoints(plotKind === 'scatter' ? ser['c:yVal'] : ser['c:val']),
|
||||
}
|
||||
// A numRef with no numCache has no renderable data: PowerPoint plots nothing and
|
||||
// omits the series from the legend (external workbook data is never re-fetched)
|
||||
if (!s.values.length) continue
|
||||
if (tagPlotKind) s.plotKind = plotKind as 'line' | 'bar' | 'area'
|
||||
// Excel/PowerPoint pick automatic series colors by c:idx, not document order
|
||||
const palIdx = parseInt(ser['c:idx']?.['@_val'], 10)
|
||||
@@ -449,9 +459,9 @@ export function parseChartXml(
|
||||
c.kind,
|
||||
true,
|
||||
secAxId != null && plotAxIds(c.plot).includes(secAxId),
|
||||
c.plot === stockPlot,
|
||||
!!c.stock,
|
||||
)
|
||||
} else parsePlotSeries(plot, kind, false, false, plot === stockPlot)
|
||||
} else parsePlotSeries(plot, kind, false, false, !!cartesian[0]?.stock)
|
||||
if (!series.length) return null
|
||||
if (!categories.length) {
|
||||
// With no category cache, keep names empty (length from the longest series); never inject placeholders
|
||||
@@ -954,6 +964,10 @@ function parseAxis(ax: any, theme?: Theme): ChartAxisStyle | undefined {
|
||||
if (Number.isFinite(majorUnit) && majorUnit > 0) out.majorUnit = majorUnit
|
||||
const minorUnit = Number(ax['c:minorUnit']?.['@_val'])
|
||||
if (Number.isFinite(minorUnit) && minorUnit > 0) out.minorUnit = minorUnit
|
||||
const lblSkip = parseInt(ax['c:tickLblSkip']?.['@_val'], 10)
|
||||
if (Number.isFinite(lblSkip) && lblSkip > 1) out.tickLblSkip = lblSkip
|
||||
const markSkip = parseInt(ax['c:tickMarkSkip']?.['@_val'], 10)
|
||||
if (Number.isFinite(markSkip) && markSkip > 1) out.tickMarkSkip = markSkip
|
||||
// Axis title (all a:t inside c:title/c:tx/c:rich concatenated)
|
||||
const titleNode = ax['c:title']
|
||||
const title = collectText(titleNode?.['c:tx']?.['c:rich'])
|
||||
|
||||
@@ -16,7 +16,15 @@
|
||||
* possible). The Phase 3 editor uses the former (lossless) when only text and
|
||||
* formatting change without structural edits; structural changes use the latter.
|
||||
*/
|
||||
import type { SlideElement, TextElement, Paragraph, TextRun, Transform, PPrDirty } from './types'
|
||||
import type {
|
||||
SlideElement,
|
||||
TextElement,
|
||||
TextBody,
|
||||
Paragraph,
|
||||
TextRun,
|
||||
Transform,
|
||||
PPrDirty,
|
||||
} from './types'
|
||||
import { escapeXmlText, escapeXmlAttr } from './xml-utils'
|
||||
|
||||
/**
|
||||
@@ -595,21 +603,47 @@ function setAttr(tag: string, name: string, value: string | undefined, existingR
|
||||
return tag.replace(/^<a:rPr/, `<a:rPr ${name}="${escapeXmlAttr(value)}"`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Bytes of a <p:cxnSp>. CT_Connector's sequence is nvCxnSpPr/spPr/style/extLst —
|
||||
* there is no txBody child, so a connector can never gain text (PowerPoint offers no
|
||||
* text editing on a line either).
|
||||
*/
|
||||
export function isConnectorXml(xml: string): boolean {
|
||||
return /^\s*<p:cxnSp[\s/>]/.test(xml)
|
||||
}
|
||||
|
||||
/**
|
||||
* A shape that never carried text gains a whole <p:txBody>. CT_Shape's sequence is
|
||||
* nvSpPr/spPr/style?/txBody?/extLst?, so the element belongs after </p:style> whenever
|
||||
* the shape references a theme style — landing it right after </p:spPr> would order
|
||||
* txBody ahead of style, and PowerPoint refuses to open the deck.
|
||||
*/
|
||||
function injectTxBody(body: TextBody, originalXml: string, paras: string): string {
|
||||
if (isConnectorXml(originalXml)) return originalXml
|
||||
const anchor =
|
||||
body.anchor === 'middle' ? ' anchor="ctr"' : body.anchor === 'bottom' ? ' anchor="b"' : ''
|
||||
const txBody = `<p:txBody><a:bodyPr${anchor}/><a:lstStyle/>${paras}</p:txBody>`
|
||||
// Placeholders inherit their geometry, so a self-closing <p:spPr/> is routine
|
||||
for (const re of [/<\/p:style>/, /<\/p:spPr>/, /<p:spPr\b[^>]*\/>/]) {
|
||||
const at = re.exec(originalXml)
|
||||
if (!at) continue
|
||||
const end = at.index + at[0].length
|
||||
return originalXml.slice(0, end) + txBody + originalXml.slice(end)
|
||||
}
|
||||
// Nothing recognizable to anchor against: appending still beats dropping the text
|
||||
const close = originalXml.lastIndexOf('</p:sp>')
|
||||
return close < 0 ? originalXml : originalXml.slice(0, close) + txBody + originalXml.slice(close)
|
||||
}
|
||||
|
||||
/** Rebuild the <p:txBody>'s paragraph content on structural change, keeping the txBody wrapper and <a:bodyPr>. */
|
||||
export function rebuildTxBody(el: TextElement, originalXml: string): string {
|
||||
const body = el.text!
|
||||
const paras = body.paragraphs.map((p) => generateParagraphXml(p)).join('')
|
||||
// CT_TextBody requires at least one <a:p>
|
||||
const paras = body.paragraphs.map((p) => generateParagraphXml(p)).join('') || '<a:p/>'
|
||||
|
||||
// Keep the original txBody's bodyPr / lstStyle prefix verbatim; only the <a:p>… after it is replaced
|
||||
const txOpen = /<p:txBody\b[^>]*>/.exec(originalXml)
|
||||
if (!txOpen) {
|
||||
// No txBody originally (a plain shape gained text): inject a full txBody after spPr
|
||||
const txBody = `<p:txBody><a:bodyPr/><a:lstStyle/>${paras}</p:txBody>`
|
||||
if (/<\/p:spPr>/.test(originalXml)) {
|
||||
return originalXml.replace(/(<\/p:spPr>)/, `$1${txBody}`)
|
||||
}
|
||||
return originalXml
|
||||
}
|
||||
if (!txOpen) return injectTxBody(body, originalXml, paras)
|
||||
const txStart = txOpen.index
|
||||
const txContentStart = txStart + txOpen[0].length
|
||||
const txEnd = originalXml.lastIndexOf('</p:txBody>')
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* path (proving fidelity). Element-level patch regeneration is left for Phase 3.
|
||||
*/
|
||||
import JSZip from 'jszip'
|
||||
import { PackageArchive, relsPathFor, resolveTarget } from './zip'
|
||||
import { PackageArchive, relsPathFor, resolveTarget, type Relationship } from './zip'
|
||||
import { parseClrMap, parseTheme, type Theme } from './theme'
|
||||
import {
|
||||
parseSlide,
|
||||
@@ -99,6 +99,7 @@ export { scanSlide, type SlideScan, type SpElement } from './scan'
|
||||
export {
|
||||
parseSlide,
|
||||
parseDecorations,
|
||||
DEFAULT_BODY_INSETS,
|
||||
EMU_PER_PT,
|
||||
type ParseContext,
|
||||
type DecorationOptions,
|
||||
@@ -125,6 +126,7 @@ export {
|
||||
removeSlideBackgroundXml,
|
||||
generateParagraphXml,
|
||||
generateXfrmXml,
|
||||
isConnectorXml,
|
||||
type GradientFillPatch,
|
||||
type BackgroundImagePatch,
|
||||
type SlideTransitionKind,
|
||||
@@ -1102,6 +1104,102 @@ export function setElementTextAnchor(
|
||||
return true
|
||||
}
|
||||
|
||||
/** Patch for setElementTextBodyProps; only the provided fields are written. */
|
||||
export interface TextBodyPropsPatch {
|
||||
/** Text direction ('horz' clears the vert attribute) */
|
||||
vert?: 'horz' | 'eaVert' | 'vert' | 'vert270' | 'wordArtVert'
|
||||
/** Autofit mode (noAutofit / normAutofit / spAutoFit) */
|
||||
autofit?: 'none' | 'shrink' | 'resize'
|
||||
/** Internal margins (EMU); only the provided sides are written */
|
||||
insets?: Partial<{ l: number; t: number; r: number; b: number }>
|
||||
wrap?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Text-box body properties (direction/autofit/insets/wrap): <a:bodyPr> byte
|
||||
* surgery baked into originalXml, mirroring setElementTextAnchor.
|
||||
*/
|
||||
export function setElementTextBodyProps(
|
||||
slide: Slide,
|
||||
elementId: string,
|
||||
patch: TextBodyPropsPatch,
|
||||
): boolean {
|
||||
const el = slide.elements.find((e) => e.id === elementId)
|
||||
if (!el || (el.type !== 'text' && el.type !== 'shape')) return false
|
||||
const t = el as TextElement
|
||||
if (!t.text) return false
|
||||
let xml = patchedElementXml(el)
|
||||
const whole = /<a:bodyPr\b[^>]*?\/>|<a:bodyPr\b[^>]*>[\s\S]*?<\/a:bodyPr>/.exec(xml)
|
||||
if (!whole) return false
|
||||
const bodyXml = whole[0]
|
||||
const selfClosing = !bodyXml.includes('</a:bodyPr>')
|
||||
let openTag = selfClosing
|
||||
? bodyXml.slice(0, -2).trimEnd() + '>'
|
||||
: bodyXml.slice(0, bodyXml.indexOf('>') + 1)
|
||||
let inner = selfClosing
|
||||
? ''
|
||||
: bodyXml.slice(bodyXml.indexOf('>') + 1, bodyXml.lastIndexOf('</a:bodyPr>'))
|
||||
|
||||
const setAttr = (name: string, value: string | null) => {
|
||||
openTag = openTag.replace(new RegExp(`\\s+${name}="[^"]*"`), '')
|
||||
if (value != null) openTag = openTag.replace(/^<a:bodyPr/, `<a:bodyPr ${name}="${value}"`)
|
||||
}
|
||||
|
||||
if (patch.vert !== undefined) setAttr('vert', patch.vert === 'horz' ? null : patch.vert)
|
||||
if (patch.wrap !== undefined) setAttr('wrap', patch.wrap ? 'square' : 'none')
|
||||
if (patch.insets) {
|
||||
for (const side of ['l', 't', 'r', 'b'] as const) {
|
||||
const v = patch.insets[side]
|
||||
if (v != null) setAttr(`${side}Ins`, String(Math.max(0, Math.round(v))))
|
||||
}
|
||||
}
|
||||
if (patch.autofit) {
|
||||
inner = inner.replace(
|
||||
/<a:(?:noAutofit|normAutofit|spAutoFit)\b[^>]*?\/>|<a:(?:noAutofit|normAutofit|spAutoFit)\b[^>]*>[\s\S]*?<\/a:(?:noAutofit|normAutofit|spAutoFit)>/,
|
||||
'',
|
||||
)
|
||||
const child =
|
||||
patch.autofit === 'none'
|
||||
? '<a:noAutofit/>'
|
||||
: patch.autofit === 'shrink'
|
||||
? '<a:normAutofit/>'
|
||||
: '<a:spAutoFit/>'
|
||||
// schema order: the autofit choice sits after <a:prstTxWarp> when present, else first
|
||||
const warp = /<a:prstTxWarp\b(?:[^>]*?\/>|[\s\S]*?<\/a:prstTxWarp>)/.exec(inner)
|
||||
const at = warp ? warp.index + warp[0].length : 0
|
||||
inner = inner.slice(0, at) + child + inner.slice(at)
|
||||
}
|
||||
|
||||
const rebuilt = inner ? `${openTag}${inner}</a:bodyPr>` : `${openTag.slice(0, -1).trimEnd()}/>`
|
||||
xml = xml.slice(0, whole.index) + rebuilt + xml.slice(whole.index + bodyXml.length)
|
||||
el.dirty = el.dirtyTransform = el.dirtyFill = el.dirtyStroke = false
|
||||
el.dirtyPPr = undefined
|
||||
el.anchor.originalXml = xml
|
||||
// Mirror into the parsed model so re-renders see the new values without a reparse
|
||||
if (patch.vert !== undefined) {
|
||||
if (patch.vert === 'horz') delete t.text.vert
|
||||
else t.text.vert = patch.vert
|
||||
}
|
||||
if (patch.wrap !== undefined) t.text.wrap = patch.wrap
|
||||
if (patch.insets) {
|
||||
const base = { l: 91440, t: 45720, r: 91440, b: 45720, ...(t.text.insets ?? {}) }
|
||||
if (patch.insets.l != null) base.l = Math.max(0, Math.round(patch.insets.l))
|
||||
if (patch.insets.t != null) base.t = Math.max(0, Math.round(patch.insets.t))
|
||||
if (patch.insets.r != null) base.r = Math.max(0, Math.round(patch.insets.r))
|
||||
if (patch.insets.b != null) base.b = Math.max(0, Math.round(patch.insets.b))
|
||||
t.text.insets = base
|
||||
}
|
||||
if (patch.autofit) {
|
||||
t.text.autofit = patch.autofit
|
||||
if (patch.autofit !== 'shrink') {
|
||||
delete t.text.fontScale
|
||||
delete t.text.lnSpcReduction
|
||||
}
|
||||
}
|
||||
slide.structureDirty = true
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Shape fill (top-level or one-level group child). The XML patch is baked into
|
||||
* the owning fragment so a dropped picture fill can immediately release its
|
||||
@@ -1567,15 +1665,60 @@ export async function mergeSlideFromPptx(
|
||||
target: OpenedPptx,
|
||||
sourceBytes: Uint8Array,
|
||||
): Promise<Slide | null> {
|
||||
const { deck, archive } = target
|
||||
const source = await extractMergeSlideSource(sourceBytes)
|
||||
return source ? mergeSlideFromSource(target, source) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* A single-slide pptx reduced to the plain data the merge needs: slide XML, its
|
||||
* relationships, referenced media bytes, and the source layout chain for the
|
||||
* empty-deck fallback. Fully serializable, so ops and journals can carry it.
|
||||
*/
|
||||
export interface MergeSlideSource {
|
||||
srcSlidePath: string
|
||||
slideXml: string
|
||||
rels: Relationship[]
|
||||
/** Referenced media bytes keyed by their resolved source path */
|
||||
media: Array<{ path: string; bytes: Uint8Array }>
|
||||
/** Source layout→master→theme chain parts (used only when the target has no layout) */
|
||||
layoutChain: Array<{ path: string; bytes: Uint8Array; rels?: Uint8Array }>
|
||||
}
|
||||
|
||||
/** Async half of the merge: unzip the source and extract everything the sync half needs. Pure read. */
|
||||
export async function extractMergeSlideSource(
|
||||
sourceBytes: Uint8Array,
|
||||
): Promise<MergeSlideSource | null> {
|
||||
const src = await PackageArchive.open(sourceBytes)
|
||||
const { slidePaths } = src.readPresentation()
|
||||
const srcSlidePath = slidePaths[0]
|
||||
if (!srcSlidePath) return null
|
||||
|
||||
let slideXml = src.readText(srcSlidePath)
|
||||
const slideXml = src.readText(srcSlidePath)
|
||||
if (slideXml == null) return null
|
||||
const srcRels = src.readRels(srcSlidePath)
|
||||
const rels = [...src.readRels(srcSlidePath).values()]
|
||||
const media: MergeSlideSource['media'] = []
|
||||
for (const rel of rels) {
|
||||
if (!MEDIA_REL_SUFFIXES.some((s) => rel.type.endsWith(s))) continue
|
||||
const path = resolveTarget(srcSlidePath, rel.target)
|
||||
const bytes = src.readBytes(path)
|
||||
if (bytes) media.push({ path, bytes })
|
||||
}
|
||||
const layoutChain: MergeSlideSource['layoutChain'] = []
|
||||
const chain = src.resolveSlideChain(srcSlidePath)
|
||||
for (const p of [chain.layoutPath, chain.masterPath, chain.themePath]) {
|
||||
if (!p) continue
|
||||
const bytes = src.readBytes(p)
|
||||
if (!bytes) continue
|
||||
const relsBytes = src.readBytes(relsPathFor(p))
|
||||
layoutChain.push({ path: p, bytes, ...(relsBytes ? { rels: relsBytes } : {}) })
|
||||
}
|
||||
return { srcSlidePath, slideXml, rels, media, layoutChain }
|
||||
}
|
||||
|
||||
/** Sync half of the merge: land an extracted source into the target deck (appended at the end). */
|
||||
export function mergeSlideFromSource(target: OpenedPptx, source: MergeSlideSource): Slide | null {
|
||||
const { deck, archive } = target
|
||||
let slideXml = source.slideXml
|
||||
const mediaByPath = new Map(source.media.map((m) => [m.path, m.bytes]))
|
||||
|
||||
// Relative Target of any existing target slide's slideLayout (the appended slide reuses the same layout)
|
||||
const anchorSlide = deck.slides[deck.slides.length - 1]
|
||||
@@ -1589,11 +1732,11 @@ export async function mergeSlideFromPptx(
|
||||
let ridSeq = 0
|
||||
const nextRid = () => `rId${++ridSeq}`
|
||||
|
||||
for (const rel of srcRels.values()) {
|
||||
for (const rel of source.rels) {
|
||||
if (MEDIA_REL_SUFFIXES.some((s) => rel.type.endsWith(s))) {
|
||||
// Media: move source bytes into the target, assign a non-conflicting path, remap the rId
|
||||
const srcMediaPath = resolveTarget(srcSlidePath, rel.target)
|
||||
const bytes = src.readBytes(srcMediaPath)
|
||||
const srcMediaPath = resolveTarget(source.srcSlidePath, rel.target)
|
||||
const bytes = mediaByPath.get(srcMediaPath)
|
||||
if (!bytes) continue
|
||||
const ext = (srcMediaPath.split('.').pop() || 'png').toLowerCase()
|
||||
const destPath = nextMediaPath(archive, ext)
|
||||
@@ -1618,7 +1761,7 @@ export async function mergeSlideFromPptx(
|
||||
`<Relationship Id="${nextRid()}" Type="${LAYOUT_REL_TYPE}" Target="${escapeXmlAttr(t)}"/>`,
|
||||
)
|
||||
// With no target layout (rare: empty deck), move the source's whole layout→master→theme chain over
|
||||
if (!layoutTarget) importLayoutChain(src, archive, srcSlidePath)
|
||||
if (!layoutTarget) importLayoutChain(archive, source)
|
||||
}
|
||||
// notesSlide and others (e.g. comments) are dropped
|
||||
}
|
||||
@@ -1637,19 +1780,11 @@ export async function mergeSlideFromPptx(
|
||||
}
|
||||
|
||||
/** Starting from an empty deck: move the source single slide's layout→master→theme chain into the target verbatim (rare branch). */
|
||||
function importLayoutChain(
|
||||
src: PackageArchive,
|
||||
archive: PackageArchive,
|
||||
srcSlidePath: string,
|
||||
): void {
|
||||
const chain = src.resolveSlideChain(srcSlidePath)
|
||||
for (const p of [chain.layoutPath, chain.masterPath, chain.themePath]) {
|
||||
if (!p) continue
|
||||
const b = src.readBytes(p)
|
||||
if (b && !archive.has(p)) archive.entries.set(p, b)
|
||||
const rp = relsPathFor(p)
|
||||
const rb = src.readBytes(rp)
|
||||
if (rb && !archive.has(rp)) archive.entries.set(rp, rb)
|
||||
function importLayoutChain(archive: PackageArchive, source: MergeSlideSource): void {
|
||||
for (const part of source.layoutChain) {
|
||||
if (!archive.has(part.path)) archive.entries.set(part.path, part.bytes)
|
||||
const rp = relsPathFor(part.path)
|
||||
if (part.rels && !archive.has(rp)) archive.entries.set(rp, part.rels)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import { tableRowGridCols } from './table-grid'
|
||||
import { type Theme, resolveFontRef, resolveSchemeColor } from './theme'
|
||||
import { resolveColorNode as resolveColorNodeShared } from './color'
|
||||
import {
|
||||
resolvePlaceholderPresetGeom,
|
||||
resolvePlaceholderTransform,
|
||||
resolvePlaceholderAnchor,
|
||||
resolvePlaceholderFillSpPr,
|
||||
@@ -84,6 +85,9 @@ const parser = new XMLParser({
|
||||
|
||||
const EMU_PER_PT = 12700
|
||||
|
||||
/** <a:bodyPr> inset defaults (EMU): 0.1" left/right, 0.05" top/bottom. */
|
||||
export const DEFAULT_BODY_INSETS = { l: 91440, t: 45720, r: 91440, b: 45720 }
|
||||
|
||||
export interface ParseContext {
|
||||
theme?: Theme
|
||||
/** Effective fill of the enclosing group (<a:grpFill/> in a child resolves to this) */
|
||||
@@ -244,6 +248,21 @@ export function parseBackground(xml: string, ctx: ParseContext): Fill | undefine
|
||||
return undefined
|
||||
}
|
||||
|
||||
const NV_PR_KEYS: Record<string, string> = {
|
||||
'p:sp': 'p:nvSpPr',
|
||||
'p:pic': 'p:nvPicPr',
|
||||
'p:grpSp': 'p:nvGrpSpPr',
|
||||
'p:graphicFrame': 'p:nvGraphicFramePr',
|
||||
'p:cxnSp': 'p:nvCxnSpPr',
|
||||
}
|
||||
|
||||
function isHiddenElement(node: any, tagName: string): boolean {
|
||||
const nvKey = NV_PR_KEYS[tagName]
|
||||
if (!nvKey) return false
|
||||
const hidden = node?.[nvKey]?.['p:cNvPr']?.['@_hidden']
|
||||
return hidden === '1' || hidden === 'true'
|
||||
}
|
||||
|
||||
function parseShapeFragment(
|
||||
sp: SpElement,
|
||||
fragXml: string,
|
||||
@@ -265,13 +284,23 @@ function parseShapeFragment(
|
||||
const node = doc[sp.name] ? (Array.isArray(doc[sp.name]) ? doc[sp.name][0] : doc[sp.name]) : null
|
||||
if (!node) return null
|
||||
|
||||
// <p:cNvPr hidden="1">: PowerPoint never paints the shape (slideshow, PDF export,
|
||||
// or editing canvas) — consulting templates hide whole scaffold layers this way.
|
||||
// Keep the bytes (silent passthrough) so saves replay them verbatim.
|
||||
if (isHiddenElement(node, sp.name)) {
|
||||
const silent = passthrough(anchor, 'unknown', node)
|
||||
silent.noChip = true
|
||||
return silent
|
||||
}
|
||||
|
||||
switch (sp.name) {
|
||||
case 'p:sp':
|
||||
// fragXml explicitly: decoration anchors carry an empty originalXml, and custGeom
|
||||
// parses from raw bytes — without it master/layout freeforms degrade to rects
|
||||
return parseSpShape(node, anchor, ctx, fragXml)
|
||||
case 'p:pic':
|
||||
return parsePicture(node, anchor, ctx)
|
||||
// fragXml for the same reason as p:sp: pic custGeom parses from raw bytes
|
||||
return parsePicture(node, anchor, ctx, fragXml)
|
||||
case 'p:grpSp':
|
||||
return parseGroup(node, anchor, ctx, fragXml)
|
||||
case 'p:graphicFrame':
|
||||
@@ -446,6 +475,7 @@ function parseSpShape(
|
||||
transform,
|
||||
// <p:ph> without a type (content placeholder) defaults to body per ECMA
|
||||
placeholder: ph ? (phType ?? 'body') : undefined,
|
||||
...(nv?.['p:cNvSpPr']?.['@_txBox'] === '1' ? { txBox: true } : {}),
|
||||
name,
|
||||
presetGeometry,
|
||||
...(adjust ? { adjust } : {}),
|
||||
@@ -738,13 +768,14 @@ function parseGroupChild(
|
||||
): SlideElement | null {
|
||||
// Child byte anchor: no independent byte roundtrip inside a group (whole group passes through), so use an empty anchor.
|
||||
const childAnchor: ByteAnchor = { spIndex: -1, originalXml: '', range: [0, 0] }
|
||||
if (isHiddenElement(child, tag)) return null
|
||||
let el: SlideElement | null
|
||||
switch (tag) {
|
||||
case 'p:sp':
|
||||
el = parseSpShape(child, childAnchor, ctx, rawXml)
|
||||
break
|
||||
case 'p:pic':
|
||||
el = parsePicture(child, childAnchor, ctx)
|
||||
el = parsePicture(child, childAnchor, ctx, rawXml)
|
||||
break
|
||||
case 'p:grpSp':
|
||||
el = parseGroup(child, childAnchor, ctx, rawXml)
|
||||
@@ -848,7 +879,12 @@ function blipEmbedId(blip: any): string | undefined {
|
||||
return undefined
|
||||
}
|
||||
|
||||
function parsePicture(node: any, anchor: ByteAnchor, ctx: ParseContext): PictureElement {
|
||||
function parsePicture(
|
||||
node: any,
|
||||
anchor: ByteAnchor,
|
||||
ctx: ParseContext,
|
||||
rawXml?: string,
|
||||
): PictureElement {
|
||||
const spPr = node['p:spPr'] ?? {}
|
||||
let transform = parseXfrm(spPr['a:xfrm'])
|
||||
// Pictures dropped into a placeholder may omit <a:xfrm> entirely; geometry comes from layout/master
|
||||
@@ -870,8 +906,28 @@ function parsePicture(node: any, anchor: ByteAnchor, ctx: ParseContext): Picture
|
||||
const descr = node['p:nvPicPr']?.['p:cNvPr']?.['@_descr']
|
||||
const srcRect = parseSrcRect(blipFill?.['a:srcRect'])
|
||||
// picture styles outline geometry (ellipse avatars/rounded-corner frames etc.); rect is the default and not recorded
|
||||
const picGeom = spPr['a:prstGeom']?.['@_prst']
|
||||
const picAdjust = parseAvLst(spPr['a:prstGeom']?.['a:avLst'])
|
||||
let picGeom = spPr['a:prstGeom']?.['@_prst']
|
||||
let picAdjust = parseAvLst(spPr['a:prstGeom']?.['a:avLst'])
|
||||
// Placeholder pictures without their own geometry clip to the layout/master
|
||||
// placeholder's shape (e.g. a parallelogram picture placeholder)
|
||||
if (!picGeom && !spPr['a:custGeom'] && picPh) {
|
||||
const inheritedGeom = resolvePlaceholderPresetGeom(
|
||||
ctx.layoutPlaceholders,
|
||||
ctx.masterPlaceholders,
|
||||
picPh['@_type'],
|
||||
picPh['@_idx'] != null ? String(picPh['@_idx']) : undefined,
|
||||
)
|
||||
if (inheritedGeom) {
|
||||
picGeom = inheritedGeom.prst
|
||||
picAdjust = parseAvLst(inheritedGeom.avLstRaw)
|
||||
}
|
||||
}
|
||||
// custGeom picture frame (photo clipped to a freeform path, e.g. diagonal hero images)
|
||||
const customGeometry =
|
||||
spPr['a:custGeom'] != null
|
||||
? parseCustGeom(rawXml || anchor.originalXml, transform.offset.cx, transform.offset.cy)
|
||||
: undefined
|
||||
const scene3d = parseScene3D(spPr, ctx)
|
||||
const softEdgeRad = spPr['a:effectLst']?.['a:softEdge']?.['@_rad']
|
||||
const alphaAmt = blip?.['a:alphaModFix']?.['@_amt']
|
||||
const opacity =
|
||||
@@ -909,6 +965,8 @@ function parsePicture(node: any, anchor: ByteAnchor, ctx: ParseContext): Picture
|
||||
...(picGeom && picGeom !== 'rect'
|
||||
? { presetGeometry: picGeom, ...(picAdjust ? { adjust: picAdjust } : {}) }
|
||||
: {}),
|
||||
...(customGeometry ? { customGeometry } : {}),
|
||||
...(scene3d ? { scene3d } : {}),
|
||||
...(opacity != null && opacity < 1 ? { opacity } : {}),
|
||||
...(softEdgeRad != null ? { softEdge: intOr(softEdgeRad, 0) } : {}),
|
||||
...(media ? { media } : {}),
|
||||
@@ -2959,10 +3017,10 @@ function parseTextBody(txBody: any, ctx: ParseContext, phChain: TextStyleLevels[
|
||||
paragraphs,
|
||||
anchor: bodyPr['@_anchor'] ? anchorMap[bodyPr['@_anchor']] : undefined,
|
||||
insets: {
|
||||
l: intOr(bodyPr['@_lIns'], 91440),
|
||||
t: intOr(bodyPr['@_tIns'], 45720),
|
||||
r: intOr(bodyPr['@_rIns'], 91440),
|
||||
b: intOr(bodyPr['@_bIns'], 45720),
|
||||
l: intOr(bodyPr['@_lIns'], DEFAULT_BODY_INSETS.l),
|
||||
t: intOr(bodyPr['@_tIns'], DEFAULT_BODY_INSETS.t),
|
||||
r: intOr(bodyPr['@_rIns'], DEFAULT_BODY_INSETS.r),
|
||||
b: intOr(bodyPr['@_bIns'], DEFAULT_BODY_INSETS.b),
|
||||
},
|
||||
autofit,
|
||||
...(fontScale != null ? { fontScale } : {}),
|
||||
@@ -3020,6 +3078,15 @@ function parseParagraph(
|
||||
runs.push(run)
|
||||
}
|
||||
|
||||
// Empty paragraph: line height comes from <a:endParaRPr> (the paragraph mark) and
|
||||
// overrides even an empty run's own rPr (probe-measured; Google Slides exports lean
|
||||
// on this with 80pt marks between text blocks). Parsed as a textless marker run.
|
||||
const endPr = p['a:endParaRPr']
|
||||
if (endPr && typeof endPr === 'object' && runs.every((r) => !r.text)) {
|
||||
const mark = parseRun({ 'a:rPr': endPr, 'a:t': '' }, ctx, dflt)
|
||||
runs.splice(0, runs.length, mark)
|
||||
}
|
||||
|
||||
// Line spacing: spcPct (%) or spcPts (absolute pt); space before/after: spcPts / spcPct (as % of single line height).
|
||||
// An explicit node overrides wholesale; otherwise inherited from the lstStyle/placeholder/master txStyles chain
|
||||
const lnSpcNode = pPr['a:lnSpc']
|
||||
@@ -3204,6 +3271,7 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
|
||||
fontSize: rPr['@_sz'] ? parseInt(rPr['@_sz'], 10) / 100 : dflt?.fontSize,
|
||||
...(rPr['@_sz'] ? {} : { fontSizeImplicit: true }),
|
||||
...(rPr['@_spc'] ? { letterSpacing: parseInt(rPr['@_spc'], 10) / 100 } : {}),
|
||||
...(rPr['@_kern'] != null ? { kern: (parseInt(rPr['@_kern'], 10) || 0) / 100 } : {}),
|
||||
...(rPr['@_baseline'] ? { baseline: parseInt(rPr['@_baseline'], 10) / 1000 } : {}),
|
||||
fontFamily,
|
||||
color,
|
||||
|
||||
@@ -91,6 +91,8 @@ export interface PlaceholderGeom {
|
||||
anchor?: 'top' | 'middle' | 'bottom'
|
||||
/** Raw spPr node when it carries an explicit fill (parse.ts resolves it with the part's rels) */
|
||||
fillSpPr?: unknown
|
||||
/** Non-rect <a:prstGeom>: placeholder pictures inherit it as their clip shape */
|
||||
presetGeom?: { prst: string; avLstRaw?: unknown }
|
||||
}
|
||||
|
||||
/** Placeholder geometry table for one layer (layout or master). */
|
||||
@@ -160,7 +162,11 @@ export function parsePlaceholderMap(layoutOrMasterXml: string, theme?: Theme): P
|
||||
const anchorAttr = asXmlNode(asXmlNode(sp['p:txBody'])['a:bodyPr'])['@_anchor']
|
||||
const anchor = ANCHOR_MAP[String(anchorAttr ?? '')]
|
||||
const hasFill = FILL_TAGS.some((tag) => tag in spPr)
|
||||
if (!transform && !textStyle && !anchor && !hasFill) continue
|
||||
const prstGeomNode = asXmlNode(spPr['a:prstGeom'])
|
||||
const prst = prstGeomNode['@_prst'] != null ? String(prstGeomNode['@_prst']) : undefined
|
||||
const presetGeom =
|
||||
prst && prst !== 'rect' ? { prst, avLstRaw: prstGeomNode['a:avLst'] } : undefined
|
||||
if (!transform && !textStyle && !anchor && !hasFill && !presetGeom) continue
|
||||
entries.push({
|
||||
type,
|
||||
idx,
|
||||
@@ -168,6 +174,7 @@ export function parsePlaceholderMap(layoutOrMasterXml: string, theme?: Theme): P
|
||||
...(textStyle ? { textStyle } : {}),
|
||||
...(anchor ? { anchor } : {}),
|
||||
...(hasFill ? { fillSpPr: spPr } : {}),
|
||||
...(presetGeom ? { presetGeom } : {}),
|
||||
})
|
||||
}
|
||||
return { entries }
|
||||
@@ -545,3 +552,31 @@ export function resolvePlaceholderTransform(
|
||||
): Transform | undefined {
|
||||
return findInMap(layout, type, idx) ?? findInMap(master, type, idx)
|
||||
}
|
||||
|
||||
/**
|
||||
* Placeholder preset-geometry inheritance (layout first, master as fallback).
|
||||
* Matches the placeholder first (same order as fill inheritance) so an unrelated
|
||||
* sibling never donates its shape.
|
||||
*/
|
||||
export function resolvePlaceholderPresetGeom(
|
||||
layout: PlaceholderMap | undefined,
|
||||
master: PlaceholderMap | undefined,
|
||||
type: string | undefined,
|
||||
idx: string | undefined,
|
||||
): PlaceholderGeom['presetGeom'] | undefined {
|
||||
const t = type ?? 'body'
|
||||
const i = idx ?? ''
|
||||
for (const map of [layout, master]) {
|
||||
if (!map) continue
|
||||
const entries = map.entries
|
||||
const hit =
|
||||
entries.find((e) => e.type === t && e.idx === i) ??
|
||||
(i !== '' ? entries.find((e) => e.idx === i) : undefined) ??
|
||||
entries.find((e) => e.type === t) ??
|
||||
(TITLE_TYPES.has(t) ? entries.find((e) => TITLE_TYPES.has(e.type)) : undefined) ??
|
||||
(BODY_TYPES.has(t) ? entries.find((e) => BODY_TYPES.has(e.type)) : undefined)
|
||||
if (hit?.presetGeom) return hit.presetGeom
|
||||
if (hit) return undefined
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
@@ -140,6 +140,9 @@ export interface TextRun {
|
||||
fontSizeImplicit?: boolean
|
||||
/** Letter spacing <a:rPr spc> (pt, may be negative; PowerPoint stores 1/100pt) */
|
||||
letterSpacing?: number
|
||||
/** Kerning threshold <a:rPr kern> (pt): kern pairs apply only at fontSize ≥ this; 0 = never.
|
||||
* Absent = PowerPoint's 12 pt default (probe-measured: 18 pt kerns, 10 pt does not). */
|
||||
kern?: number
|
||||
/** Font family (final font name after theme inheritance, for render/editor display) */
|
||||
fontFamily?: string
|
||||
/**
|
||||
@@ -327,6 +330,8 @@ interface ElementBase {
|
||||
dirtyPPr?: PPrDirty
|
||||
/** Placeholder type (title/body/…), located via layout/master inheritance */
|
||||
placeholder?: string
|
||||
/** <p:cNvSpPr txBox="1">: an Insert > Text Box, which stays top-left where an autoshape centers */
|
||||
txBox?: boolean
|
||||
name?: string
|
||||
/**
|
||||
* <p:cNvPr descr="…">: editor-owned metadata payload (e.g. vector points of
|
||||
@@ -428,6 +433,10 @@ export interface PictureElement extends ElementBase {
|
||||
/** Picture outline geometry <a:prstGeom> (ellipse avatars/rounded-corner frames etc. from picture styles; rect omitted) */
|
||||
presetGeometry?: string
|
||||
adjust?: Record<string, number>
|
||||
/** Picture outline <a:custGeom> (the image is clipped to the custom path; mutually exclusive with presetGeometry) */
|
||||
customGeometry?: CustomGeometry
|
||||
/** <a:scene3d> on the pic: a flat 180° camera rotation mirrors the bitmap */
|
||||
scene3d?: Scene3D
|
||||
/** Shape fill from the pic's own spPr, drawn as a backdrop behind the image */
|
||||
fill?: Fill
|
||||
/** <a:blip><a:duotone> on the picture blip */
|
||||
|
||||
@@ -779,3 +779,68 @@ describe('axis units / gridline defaults / title overlay', () => {
|
||||
expect(m.catAxis?.gridColorAuto).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('dual plot groups and cache-less series', () => {
|
||||
const ser = (idx: number, name: string, vals: string, axIds = '') =>
|
||||
`<c:ser><c:idx val="${idx}"/><c:order val="${idx}"/>` +
|
||||
`<c:tx><c:strRef><c:f>S!$B$1</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>${name}</c:v></c:pt></c:strCache></c:strRef></c:tx>` +
|
||||
`<c:val>${vals}</c:val></c:ser>${axIds}`
|
||||
const cached =
|
||||
'<c:numRef><c:f>S!$B$2:$B$3</c:f><c:numCache><c:ptCount val="2"/>' +
|
||||
'<c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt></c:numCache></c:numRef>'
|
||||
const uncached = '<c:numRef><c:f>ext!$C$2:$C$3</c:f></c:numRef>'
|
||||
|
||||
it('two c:lineChart nodes (secondary-axis group) both contribute series', () => {
|
||||
const xml =
|
||||
`<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>` +
|
||||
`<c:lineChart>${ser(0, 'P', cached)}<c:axId val="1"/><c:axId val="2"/></c:lineChart>` +
|
||||
`<c:lineChart>${ser(1, 'S', cached)}<c:axId val="1"/><c:axId val="3"/></c:lineChart>` +
|
||||
`<c:catAx><c:axId val="1"/></c:catAx>` +
|
||||
`<c:valAx><c:axId val="2"/><c:axPos val="l"/><c:delete val="0"/></c:valAx>` +
|
||||
`<c:valAx><c:axId val="3"/><c:axPos val="r"/><c:delete val="0"/></c:valAx>` +
|
||||
`</c:plotArea></c:chart></c:chartSpace>`
|
||||
const m = parseChartXml(xml)!
|
||||
expect(m).not.toBeNull()
|
||||
expect(m.series.length).toBe(2)
|
||||
expect(m.series.map((s) => s.name)).toEqual(['P', 'S'])
|
||||
expect(m.series[1]!.secondaryAxis).toBe(true)
|
||||
})
|
||||
|
||||
it('a series whose val has a numRef but no cache is dropped (PowerPoint plots and lists nothing)', () => {
|
||||
const xml =
|
||||
`<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>` +
|
||||
`<c:lineChart>${ser(0, 'Flow', uncached)}${ser(1, 'Temp', cached)}</c:lineChart>` +
|
||||
`</c:plotArea></c:chart></c:chartSpace>`
|
||||
const m = parseChartXml(xml)!
|
||||
expect(m.series.length).toBe(1)
|
||||
expect(m.series[0]!.name).toBe('Temp')
|
||||
})
|
||||
|
||||
it('an all-gaps cached series keeps its slot (ptCount sized, no points)', () => {
|
||||
const gaps =
|
||||
'<c:numRef><c:f>S!$B$2:$B$3</c:f><c:numCache><c:ptCount val="2"/></c:numCache></c:numRef>'
|
||||
const xml =
|
||||
`<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>` +
|
||||
`<c:lineChart>${ser(0, 'Gaps', gaps)}</c:lineChart>` +
|
||||
`</c:plotArea></c:chart></c:chartSpace>`
|
||||
const m = parseChartXml(xml)!
|
||||
expect(m.series.length).toBe(1)
|
||||
expect(m.series[0]!.values).toEqual([null, null])
|
||||
})
|
||||
})
|
||||
|
||||
describe('category tick skips', () => {
|
||||
it('parses explicit c:tickLblSkip / c:tickMarkSkip on the category axis', () => {
|
||||
const xml =
|
||||
`<?xml version="1.0"?><c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea><c:layout/>` +
|
||||
`<c:lineChart><c:ser><c:idx val="0"/><c:val><c:numRef><c:f>S!$B$2</c:f><c:numCache><c:ptCount val="2"/>` +
|
||||
`<c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser>` +
|
||||
`<c:axId val="1"/><c:axId val="2"/></c:lineChart>` +
|
||||
`<c:catAx><c:axId val="1"/><c:tickLblSkip val="192"/><c:tickMarkSkip val="192"/></c:catAx>` +
|
||||
`<c:valAx><c:axId val="2"/><c:axPos val="l"/><c:delete val="0"/></c:valAx>` +
|
||||
`</c:plotArea></c:chart></c:chartSpace>`
|
||||
const m = parseChartXml(xml)!
|
||||
expect(m.catAxis?.tickLblSkip).toBe(192)
|
||||
expect(m.catAxis?.tickMarkSkip).toBe(192)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -238,3 +238,58 @@ describe('parseSlide attaches customGeometry', () => {
|
||||
expect(grpEl.children[0].customGeometry?.path).toBe('M 0 1 L 0.5 0 L 1 1 Z')
|
||||
})
|
||||
})
|
||||
|
||||
const PIC_NS =
|
||||
SLIDE_NS + ' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'
|
||||
|
||||
const picWrap = (spPrExtra: string) =>
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="3" name="Picture 2"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>` +
|
||||
`<p:blipFill><a:blip r:embed="rId2"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
|
||||
`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm>` +
|
||||
spPrExtra +
|
||||
`</p:spPr></p:pic>`
|
||||
|
||||
const picSlide = (spPrExtra: string, wrap: (inner: string) => string = (s) => s) =>
|
||||
parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml:
|
||||
`<?xml version="1.0"?><p:sld ${PIC_NS}><p:cSld><p:spTree>` +
|
||||
`<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/>` +
|
||||
wrap(picWrap(spPrExtra)) +
|
||||
`</p:spTree></p:cSld></p:sld>`,
|
||||
ctx: {},
|
||||
})
|
||||
|
||||
describe('parseSlide attaches picture custGeom and scene3d', () => {
|
||||
it('pic custGeom: the freeform clip path is parsed from raw bytes', () => {
|
||||
const el = picSlide(TRIANGLE_CUSTGEOM).elements[0] as any
|
||||
expect(el.type).toBe('picture')
|
||||
expect(el.customGeometry?.path).toBe('M 0 1 L 0.5 0 L 1 1 Z')
|
||||
})
|
||||
|
||||
it('pic scene3d: camera preset and rot are recorded', () => {
|
||||
const el = picSlide(
|
||||
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` +
|
||||
`<a:scene3d><a:camera prst="orthographicFront"><a:rot lat="0" lon="10800000" rev="0"/></a:camera>` +
|
||||
`<a:lightRig rig="threePt" dir="t"/></a:scene3d>`,
|
||||
).elements[0] as any
|
||||
expect(el.type).toBe('picture')
|
||||
expect(el.scene3d?.cameraPreset).toBe('orthographicFront')
|
||||
expect(el.scene3d?.cameraRot).toEqual({ lat: 0, lon: 10800000, rev: 0 })
|
||||
})
|
||||
|
||||
it('pic custGeom inside a group parses from its source slice', () => {
|
||||
const grpEl = picSlide(
|
||||
TRIANGLE_CUSTGEOM,
|
||||
(inner) =>
|
||||
`<p:grpSp><p:nvGrpSpPr><p:cNvPr id="10" name="g"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>` +
|
||||
`<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/>` +
|
||||
`<a:chOff x="0" y="0"/><a:chExt cx="914400" cy="914400"/></a:xfrm></p:grpSpPr>` +
|
||||
inner +
|
||||
`</p:grpSp>`,
|
||||
).elements[0] as any
|
||||
expect(grpEl.type).toBe('group')
|
||||
expect(grpEl.children[0].type).toBe('picture')
|
||||
expect(grpEl.children[0].customGeometry?.path).toBe('M 0 1 L 0.5 0 L 1 1 Z')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* <p:cNvPr hidden="1"> shapes: PowerPoint never paints them (slideshow, PDF export,
|
||||
* or the editing canvas). They must not surface as renderable elements, while their
|
||||
* bytes stay in the file (silent passthrough) so saves replay them verbatim.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide, parseDecorations } from '../src/parse'
|
||||
|
||||
const slideWith = (body: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${body}</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
const sp = (id: number, extra = '') =>
|
||||
`<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="s${id}"${extra}/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
|
||||
`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm>` +
|
||||
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></p:spPr>` +
|
||||
`<p:txBody><a:bodyPr/><a:p><a:r><a:t>t${id}</a:t></a:r></a:p></p:txBody></p:sp>`
|
||||
|
||||
const pic = (id: number, extra = '') =>
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="p${id}"${extra}/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>` +
|
||||
`<p:blipFill><a:blip r:embed="rId2"/><a:stretch/></p:blipFill>` +
|
||||
`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm></p:spPr></p:pic>`
|
||||
|
||||
describe('cNvPr hidden="1"', () => {
|
||||
it('hidden sp becomes a silent passthrough, visible sibling still parses', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(sp(2, ' hidden="1"') + sp(3)),
|
||||
ctx: {},
|
||||
})
|
||||
expect(slide.elements).toHaveLength(2)
|
||||
expect(slide.elements[0]!.type).toBe('passthrough')
|
||||
expect((slide.elements[0] as any).noChip).toBe(true)
|
||||
expect(slide.elements[1]!.type).not.toBe('passthrough')
|
||||
})
|
||||
|
||||
it('hidden pic is skipped too', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(pic(2, ' hidden="1"')),
|
||||
ctx: {},
|
||||
})
|
||||
expect(slide.elements[0]!.type).toBe('passthrough')
|
||||
})
|
||||
|
||||
it('hidden group child is dropped while visible children stay', () => {
|
||||
const grp =
|
||||
`<p:grpSp><p:nvGrpSpPr><p:cNvPr id="10" name="g"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>` +
|
||||
`<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/>` +
|
||||
`<a:chOff x="0" y="0"/><a:chExt cx="914400" cy="914400"/></a:xfrm></p:grpSpPr>` +
|
||||
sp(11, ' hidden="1"') +
|
||||
sp(12) +
|
||||
`</p:grpSp>`
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(grp),
|
||||
ctx: {},
|
||||
})
|
||||
const g = slide.elements[0] as any
|
||||
expect(g.type).toBe('group')
|
||||
expect(g.children).toHaveLength(1)
|
||||
expect(g.children[0].name).toBe('s12')
|
||||
})
|
||||
|
||||
it('hidden master/layout decorations do not render', () => {
|
||||
const decorations = parseDecorations(slideWith(sp(2, ' hidden="1"') + sp(3)), {})
|
||||
expect(decorations).toHaveLength(1)
|
||||
expect((decorations[0] as any).name).toBe('s3')
|
||||
})
|
||||
})
|
||||
@@ -213,3 +213,37 @@ describe('per-paragraph paraIndices (editing-mode selection)', () => {
|
||||
expect(el.dirtyPPr).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('empty paragraph endParaRPr', () => {
|
||||
it('empty paragraph takes its line style from endParaRPr (marker run)', () => {
|
||||
const { el } = parseOne(
|
||||
'<a:bodyPr/><a:p><a:r><a:rPr sz="2000"/><a:t>X</a:t></a:r></a:p>' +
|
||||
'<a:p><a:endParaRPr sz="8000" b="1"/></a:p>',
|
||||
)
|
||||
const p = el.text!.paragraphs[1]!
|
||||
expect(p.runs.length).toBe(1)
|
||||
expect(p.runs[0]!.text).toBe('')
|
||||
expect(p.runs[0]!.fontSize).toBe(80)
|
||||
expect(p.runs[0]!.bold).toBe(true)
|
||||
})
|
||||
|
||||
it("endParaRPr overrides an empty run's own rPr (probe-measured PowerPoint rule)", () => {
|
||||
const { el } = parseOne(
|
||||
'<a:bodyPr/><a:p><a:r><a:rPr sz="1400"/><a:t></a:t></a:r>' +
|
||||
'<a:endParaRPr sz="8000"/></a:p>',
|
||||
)
|
||||
const p = el.text!.paragraphs[0]!
|
||||
expect(p.runs.length).toBe(1)
|
||||
expect(p.runs[0]!.fontSize).toBe(80)
|
||||
})
|
||||
|
||||
it('a paragraph with real text keeps its runs (endParaRPr ignored)', () => {
|
||||
const { el } = parseOne(
|
||||
'<a:bodyPr/><a:p><a:r><a:rPr sz="2000"/><a:t>Hello</a:t></a:r>' +
|
||||
'<a:endParaRPr sz="8000"/></a:p>',
|
||||
)
|
||||
const p = el.text!.paragraphs[0]!
|
||||
expect(p.runs[0]!.text).toBe('Hello')
|
||||
expect(p.runs[0]!.fontSize).toBe(20)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Placeholder pictures without their own <a:prstGeom> inherit the layout/master
|
||||
* placeholder's shape (with adjustment values), so the image clips like PowerPoint
|
||||
* (e.g. parallelogram picture placeholders in cover layouts).
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { parsePlaceholderMap } from '../src/placeholder'
|
||||
|
||||
const layoutXml =
|
||||
'<?xml version="1.0"?><p:sldLayout xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree>' +
|
||||
'<p:nvGrpSpPr/><p:grpSpPr/>' +
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="5" name="Picture Placeholder 2"/><p:cNvSpPr/>' +
|
||||
'<p:nvPr><p:ph type="pic" sz="quarter" idx="12"/></p:nvPr></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm flipH="1"><a:off x="3918353" y="-12"/><a:ext cx="17689293" cy="335935"/></a:xfrm>' +
|
||||
'<a:prstGeom prst="parallelogram"><a:avLst><a:gd name="adj" fmla="val 88235"/></a:avLst></a:prstGeom>' +
|
||||
'</p:spPr><p:txBody><a:bodyPr/><a:p/></p:txBody></p:sp>' +
|
||||
'</p:spTree></p:cSld></p:sldLayout>'
|
||||
|
||||
const slideXml =
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld><p:spTree>' +
|
||||
'<p:nvGrpSpPr/><p:grpSpPr/>' +
|
||||
'<p:pic><p:nvPicPr><p:cNvPr id="27" name="Picture Placeholder 26"/><p:cNvPicPr/>' +
|
||||
'<p:nvPr><p:ph type="pic" sz="quarter" idx="12"/></p:nvPr></p:nvPicPr>' +
|
||||
'<p:blipFill><a:blip r:embed="rId3"/><a:stretch/></p:blipFill>' +
|
||||
'<p:spPr><a:xfrm flipH="1"><a:off x="3918353" y="-12"/><a:ext cx="17689293" cy="10286993"/></a:xfrm></p:spPr></p:pic>' +
|
||||
'</p:spTree></p:cSld></p:sld>'
|
||||
|
||||
describe('placeholder picture geometry inheritance', () => {
|
||||
it('pic without own prstGeom inherits the layout placeholder shape and adjust values', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml,
|
||||
ctx: { layoutPlaceholders: parsePlaceholderMap(layoutXml) },
|
||||
})
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.type).toBe('picture')
|
||||
expect(el.presetGeometry).toBe('parallelogram')
|
||||
expect(el.adjust).toEqual({ adj: 88235 })
|
||||
})
|
||||
|
||||
it('pic with its own geometry keeps it (no inheritance override)', () => {
|
||||
const own = slideXml.replace(
|
||||
'</a:xfrm></p:spPr></p:pic>',
|
||||
'</a:xfrm><a:prstGeom prst="ellipse"><a:avLst/></a:prstGeom></p:spPr></p:pic>',
|
||||
)
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: own,
|
||||
ctx: { layoutPlaceholders: parsePlaceholderMap(layoutXml) },
|
||||
})
|
||||
expect((slide.elements[0] as any).presetGeometry).toBe('ellipse')
|
||||
})
|
||||
|
||||
it('non-placeholder pic does not inherit', () => {
|
||||
const noPh = slideXml.replace('<p:ph type="pic" sz="quarter" idx="12"/>', '')
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: noPh,
|
||||
ctx: { layoutPlaceholders: parsePlaceholderMap(layoutXml) },
|
||||
})
|
||||
expect((slide.elements[0] as any).presetGeometry).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Verifies the core replace_at sequence (redo one slide in place):
|
||||
* mergeSlideFromPptx (new slide appended at the end) → moveSlide (into position) → deleteSlide (remove old slide).
|
||||
* This is the engine-level equivalent of the replace_at branch in slides-main 'slides:html-to-pptx';
|
||||
* This is the engine-level equivalent of the replace_at branch in slides-main 'slides:land-generated-pages';
|
||||
* no Electron dependency — runs the real openPptx → operations → savePptx → openPptx chain.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/** setElementTextBodyProps: bodyPr direction/autofit/insets/wrap byte surgery. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { addElement, createBlankPptx, openPptx, setElementTextBodyProps } from '../src/index'
|
||||
import type { TextElement } from '../src/types'
|
||||
|
||||
async function textboxSlide() {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, {
|
||||
kind: 'textbox',
|
||||
offset: { x: 0, y: 0, cx: 1000, cy: 1000 },
|
||||
paragraphs: [{ runs: [{ text: 'x' }] }],
|
||||
})
|
||||
return { slide, el: el as TextElement }
|
||||
}
|
||||
|
||||
describe('setElementTextBodyProps', () => {
|
||||
it('vert attribute set and cleared, model kept in sync', async () => {
|
||||
const { slide, el } = await textboxSlide()
|
||||
expect(setElementTextBodyProps(slide, el.id, { vert: 'eaVert' })).toBe(true)
|
||||
expect(el.anchor.originalXml).toMatch(/<a:bodyPr vert="eaVert"/)
|
||||
expect(el.text!.vert).toBe('eaVert')
|
||||
expect(setElementTextBodyProps(slide, el.id, { vert: 'horz' })).toBe(true)
|
||||
expect(el.anchor.originalXml).not.toMatch(/<a:bodyPr[^>]*\svert="/)
|
||||
expect(el.text!.vert).toBeUndefined()
|
||||
})
|
||||
|
||||
it('wrap toggles wrap="none" / wrap="square"', async () => {
|
||||
const { slide, el } = await textboxSlide()
|
||||
expect(setElementTextBodyProps(slide, el.id, { wrap: false })).toBe(true)
|
||||
expect(el.anchor.originalXml).toMatch(/<a:bodyPr wrap="none"/)
|
||||
expect(el.text!.wrap).toBe(false)
|
||||
expect(setElementTextBodyProps(slide, el.id, { wrap: true })).toBe(true)
|
||||
expect(el.anchor.originalXml).toMatch(/<a:bodyPr wrap="square"/)
|
||||
expect(el.text!.wrap).toBe(true)
|
||||
})
|
||||
|
||||
it('insets written per side (EMU), previously written sides kept', async () => {
|
||||
const { slide, el } = await textboxSlide()
|
||||
expect(setElementTextBodyProps(slide, el.id, { insets: { l: 180000 } })).toBe(true)
|
||||
expect(el.anchor.originalXml).toMatch(/lIns="180000"/)
|
||||
expect(el.text!.insets).toMatchObject({ l: 180000, t: 45720 })
|
||||
expect(setElementTextBodyProps(slide, el.id, { insets: { t: 0 } })).toBe(true)
|
||||
expect(el.anchor.originalXml).toMatch(/tIns="0"/)
|
||||
expect(el.anchor.originalXml).toMatch(/lIns="180000"/)
|
||||
expect(el.text!.insets).toMatchObject({ l: 180000, t: 0 })
|
||||
})
|
||||
|
||||
it('autofit child swapped in place (self-closing bodyPr expands)', async () => {
|
||||
const { slide, el } = await textboxSlide()
|
||||
expect(setElementTextBodyProps(slide, el.id, { autofit: 'shrink' })).toBe(true)
|
||||
expect(el.anchor.originalXml).toMatch(/<a:bodyPr[^>]*><a:normAutofit\/><\/a:bodyPr>/)
|
||||
expect(el.text!.autofit).toBe('shrink')
|
||||
expect(setElementTextBodyProps(slide, el.id, { autofit: 'resize' })).toBe(true)
|
||||
expect(el.anchor.originalXml).toMatch(/<a:spAutoFit\/>/)
|
||||
expect(el.anchor.originalXml).not.toMatch(/normAutofit/)
|
||||
expect(el.text!.autofit).toBe('resize')
|
||||
expect(setElementTextBodyProps(slide, el.id, { autofit: 'none' })).toBe(true)
|
||||
expect(el.anchor.originalXml).toMatch(/<a:noAutofit\/>/)
|
||||
expect(el.text!.autofit).toBe('none')
|
||||
})
|
||||
|
||||
it('combined patch applies attributes and autofit together', async () => {
|
||||
const { slide, el } = await textboxSlide()
|
||||
expect(
|
||||
setElementTextBodyProps(slide, el.id, {
|
||||
vert: 'vert270',
|
||||
wrap: false,
|
||||
insets: { b: 91440 },
|
||||
autofit: 'shrink',
|
||||
}),
|
||||
).toBe(true)
|
||||
const xml = el.anchor.originalXml
|
||||
expect(xml).toMatch(/vert="vert270"/)
|
||||
expect(xml).toMatch(/wrap="none"/)
|
||||
expect(xml).toMatch(/bIns="91440"/)
|
||||
expect(xml).toMatch(/<a:normAutofit\/>/)
|
||||
})
|
||||
|
||||
it('rejects elements without a text body', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
expect(setElementTextBodyProps(slide, 'nope', { wrap: false })).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Injecting a <p:txBody> into an element that never had one (a shape gains text for
|
||||
* the first time). CT_Shape's sequence is nvSpPr/spPr/style?/txBody?/extLst?, so the
|
||||
* insertion point — not just the presence of the element — decides whether PowerPoint
|
||||
* can still open the deck.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
import { rebuildTxBody, isConnectorXml } from '../src/generate'
|
||||
import { patchSlideXml, patchGroupChildText, findGroupChild } from '../src/index'
|
||||
import type { GroupElement, 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 SPPR = `<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="457200"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr>`
|
||||
const STYLE = `<p:style><a:lnRef idx="2"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="1"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="0"><a:schemeClr val="accent1"/></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef></p:style>`
|
||||
const nvSpPr = (id: number, name: string, inner = '') =>
|
||||
`<p:nvSpPr><p:cNvPr id="${id}" name="${name}"/><p:cNvSpPr/><p:nvPr>${inner}</p:nvPr></p:nvSpPr>`
|
||||
|
||||
/** Autoshape without a <p:txBody> (AI/converter output, or text deleted in another tool) */
|
||||
const SHAPE = `<p:sp>${nvSpPr(2, 'Rect 1')}${SPPR}</p:sp>`
|
||||
/** Same, but carrying the theme style reference PowerPoint writes for every autoshape */
|
||||
const SHAPE_STYLED = `<p:sp>${nvSpPr(3, 'Rect 2')}${SPPR}${STYLE}</p:sp>`
|
||||
/** Placeholder: geometry is inherited, so spPr is routinely self-closing */
|
||||
const PLACEHOLDER = `<p:sp>${nvSpPr(4, 'PH', '<p:ph type="body" idx="1"/>')}<p:spPr/></p:sp>`
|
||||
const CONNECTOR = `<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="5" name="Straight Connector 1"/><p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>${SPPR}${STYLE}</p:cxnSp>`
|
||||
|
||||
/** Type text into the first element the way the setText op does. */
|
||||
function typeInto(elXml: string) {
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: wrap(elXml), ctx: {} })
|
||||
const el = slide.elements[0] as TextElement
|
||||
el.text = {
|
||||
paragraphs: [{ runs: [{ text: 'HELLO' }] }],
|
||||
insets: { l: 91440, t: 45720, r: 91440, b: 45720 },
|
||||
anchor: 'middle',
|
||||
}
|
||||
el.dirty = true
|
||||
return { el, out: patchSlideXml(slide) }
|
||||
}
|
||||
|
||||
/** Order of a <p:sp>'s modelled children, as written back. */
|
||||
const childOrder = (xml: string) =>
|
||||
[...xml.matchAll(/<(p:spPr|p:style|p:txBody)\b/g)].map((m) => m[1]).join(' ')
|
||||
|
||||
describe('the flags that decide whether a fresh body gets centered', () => {
|
||||
const parseOne = (elXml: string) =>
|
||||
parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: wrap(elXml), ctx: {} })
|
||||
.elements[0] as TextElement
|
||||
|
||||
it('an autoshape is neither a placeholder nor a text box', () => {
|
||||
const el = parseOne(SHAPE)
|
||||
expect(el.placeholder).toBeUndefined()
|
||||
expect(el.txBox).toBeUndefined()
|
||||
})
|
||||
|
||||
it('<p:ph> surfaces as the placeholder type', () => {
|
||||
expect(parseOne(PLACEHOLDER).placeholder).toBe('body')
|
||||
})
|
||||
|
||||
it('<p:cNvSpPr txBox="1"> surfaces as txBox', () => {
|
||||
const xml = `<p:sp><p:nvSpPr><p:cNvPr id="6" name="TextBox 1"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>${SPPR}</p:sp>`
|
||||
expect(parseOne(xml).txBox).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('txBody injection into an element that had none', () => {
|
||||
it('plain shape: txBody lands after spPr and the text round-trips', () => {
|
||||
const { out } = typeInto(SHAPE)
|
||||
expect(out).toContain('<p:txBody>')
|
||||
expect(childOrder(out)).toBe('p:spPr p:txBody')
|
||||
const el = parseSlide({ path: 'p', slideXml: out, ctx: {} }).elements[0] as TextElement
|
||||
expect(el.text?.paragraphs[0]?.runs[0]?.text).toBe('HELLO')
|
||||
})
|
||||
|
||||
it('styled shape: txBody follows p:style (CT_Shape sequence), not spPr', () => {
|
||||
const { out } = typeInto(SHAPE_STYLED)
|
||||
expect(childOrder(out)).toBe('p:spPr p:style p:txBody')
|
||||
const el = parseSlide({ path: 'p', slideXml: out, ctx: {} }).elements[0] as TextElement
|
||||
expect(el.text?.paragraphs[0]?.runs[0]?.text).toBe('HELLO')
|
||||
})
|
||||
|
||||
it('self-closing <p:spPr/>: the text is not dropped', () => {
|
||||
const { out } = typeInto(PLACEHOLDER)
|
||||
expect(out).toContain('<p:spPr/><p:txBody>')
|
||||
const el = parseSlide({ path: 'p', slideXml: out, ctx: {} }).elements[0] as TextElement
|
||||
expect(el.text?.paragraphs[0]?.runs[0]?.text).toBe('HELLO')
|
||||
})
|
||||
|
||||
it('connector: refused — CT_Connector has no txBody child', () => {
|
||||
const { out } = typeInto(CONNECTOR)
|
||||
expect(out).not.toContain('<p:txBody>')
|
||||
expect(isConnectorXml(CONNECTOR)).toBe(true)
|
||||
expect(isConnectorXml(SHAPE)).toBe(false)
|
||||
})
|
||||
|
||||
it('anchor is written into the synthesized bodyPr and survives a reload', () => {
|
||||
const { out } = typeInto(SHAPE)
|
||||
expect(out).toContain('<a:bodyPr anchor="ctr"/>')
|
||||
const el = parseSlide({ path: 'p', slideXml: out, ctx: {} }).elements[0] as TextElement
|
||||
expect(el.text?.anchor).toBe('middle')
|
||||
})
|
||||
|
||||
it('insets match the parser defaults, so the live model and the reload agree', () => {
|
||||
const { el, out } = typeInto(SHAPE)
|
||||
const reloaded = parseSlide({ path: 'p', slideXml: out, ctx: {} }).elements[0] as TextElement
|
||||
expect(reloaded.text?.insets).toEqual(el.text?.insets)
|
||||
})
|
||||
|
||||
it('an empty body still writes one <a:p> (CT_TextBody requires it)', () => {
|
||||
const slide = parseSlide({ path: 'p', slideXml: wrap(SHAPE), ctx: {} })
|
||||
const el = slide.elements[0] as TextElement
|
||||
el.text = { paragraphs: [] }
|
||||
expect(rebuildTxBody(el, el.anchor.originalXml)).toContain('<a:lstStyle/><a:p/></p:txBody>')
|
||||
})
|
||||
|
||||
it('group child gains a txBody inside the group bytes', () => {
|
||||
const grpSpPr = `<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="457200"/><a:chOff x="0" y="0"/><a:chExt cx="914400" cy="457200"/></a:xfrm></p:grpSpPr>`
|
||||
const group = `<p:grpSp><p:nvGrpSpPr><p:cNvPr id="9" name="Group 1"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>${grpSpPr}${SHAPE_STYLED}</p:grpSp>`
|
||||
const slide = parseSlide({ path: 'p', slideXml: wrap(group), ctx: {} })
|
||||
const grp = slide.elements[0] as GroupElement
|
||||
const child = findGroupChild(slide, grp.id, grp.children[0]!.id)!.child as TextElement
|
||||
child.text = { paragraphs: [{ runs: [{ text: 'IN GROUP' }] }], anchor: 'middle' }
|
||||
expect(patchGroupChildText(slide, grp.id, child)).toBe(true)
|
||||
expect(childOrder(grp.anchor.originalXml)).toBe('p:spPr p:style p:txBody')
|
||||
const reloaded = parseSlide({ path: 'p', slideXml: patchSlideXml(slide), ctx: {} })
|
||||
const reChild = (reloaded.elements[0] as GroupElement).children[0] as TextElement
|
||||
expect(reChild.text?.paragraphs[0]?.runs[0]?.text).toBe('IN GROUP')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user