Sync snapshot (2026-08-20) (#123)
- Add fully local PDF to Word, PowerPoint, and Excel conversion - Add bring-your-own-key AI providers - Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, and custom OpenAI-compatible endpoints - with a refreshed AI settings UI - Rework the Slides AI editing surface: canonical edit-op registry, atomic transactions with rollback, durable element ids, and batched apply_ops - Improve Slides fidelity: chart, font, gradient, table-style, and text-shaping fixes, plus PPT-parity line editing and adjust handles - Polish Docs: password-protection dialogs, anchored-image wrapping fixes, and selection and clipboard fixes - Add themed dropdowns suite-wide with accent-derived selection states Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
fe2e17403c
commit
f68df70e22
@@ -8,6 +8,7 @@
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./table-grid": "./src/table-grid.ts",
|
||||
"./identity": "./src/identity.ts",
|
||||
"./background-promote": "./src/background-promote.ts"
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* fine, but "Edit Data" is unavailable).
|
||||
*/
|
||||
import type { EmuRect, Slide } from './types'
|
||||
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
|
||||
import { escapeXmlAttr, escapeXmlText, creationIdXml } from './xml-utils'
|
||||
import { relsPathFor } from './zip'
|
||||
import { appendRawElements, type OpenedPptx } from './index'
|
||||
import { nextCNvPrId } from './insert'
|
||||
@@ -339,7 +339,7 @@ export function addChart(
|
||||
const name = opts.title ? `Chart ${id} - ${opts.title}` : `Chart ${id}`
|
||||
// descr="aislides-chart" marks charts created by this app (like the ink marker); recognized as editable charts on reopen
|
||||
const frameXml =
|
||||
`<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}" descr="aislides-chart"/>` +
|
||||
`<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}" descr="aislides-chart">${creationIdXml()}</p:cNvPr>` +
|
||||
'<p:cNvGraphicFramePr/><p:nvPr/></p:nvGraphicFramePr>' +
|
||||
`<p:xfrm><a:off x="${o.x}" y="${o.y}"/><a:ext cx="${o.cx}" cy="${o.cy}"/></p:xfrm>` +
|
||||
`<a:graphic><a:graphicData uri="${C_NS}">` +
|
||||
|
||||
@@ -640,6 +640,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.level) pPrAttrs.push(`lvl="${p.level}"`)
|
||||
|
||||
// CT_TextParagraphProperties child order: lnSpc → spcBef → spcAft → buClr → buSzPct → buFont → bu*
|
||||
@@ -986,23 +987,58 @@ export interface StrokePatch {
|
||||
widthEmu: number
|
||||
/** prstDash preset name; 'solid' removes the prstDash node; undefined keeps the original bytes */
|
||||
dash?: string
|
||||
/** Line cap attribute (undefined keeps the original bytes) */
|
||||
cap?: 'flat' | 'rnd' | 'sq'
|
||||
/** Compound type attribute ('sng' removes it; undefined keeps the original bytes) */
|
||||
compound?: 'sng' | 'dbl' | 'thickThin' | 'thinThick' | 'tri'
|
||||
/** Join child element (undefined keeps the original bytes) */
|
||||
join?: 'round' | 'bevel' | 'miter'
|
||||
/** Gradient line: replaces the fill child (color then only feeds callers' fallbacks); angle in 1/60000° */
|
||||
gradient?: { stops: Array<{ pos: number; color: string }>; angle: number }
|
||||
}
|
||||
|
||||
/** In-place patch of <a:ln>: change the w attribute, replace the fill child and (when requested) the prstDash child; all other bytes are kept. */
|
||||
const JOIN_XML: Record<NonNullable<StrokePatch['join']>, string> = {
|
||||
round: '<a:round/>',
|
||||
bevel: '<a:bevel/>',
|
||||
// PowerPoint's default miter limit (8×)
|
||||
miter: '<a:miter lim="800000"/>',
|
||||
}
|
||||
|
||||
/** The <a:ln> fill child for a stroke patch: gradient line, solid color (alpha kept), or noFill. */
|
||||
function strokeFillXml(stroke: StrokePatch | null): string {
|
||||
if (!stroke) return '<a:noFill/>'
|
||||
if (stroke.gradient)
|
||||
return buildFillXml({ stops: stroke.gradient.stops, angle: stroke.gradient.angle })
|
||||
return `<a:solidFill>${srgbClrXml(stroke.color)}</a:solidFill>`
|
||||
}
|
||||
|
||||
/** Set/replace/remove one attribute inside an <a:ln> attribute string. */
|
||||
function setLnAttr(attrs: string, name: string, value: string | null): string {
|
||||
const re = new RegExp(`\\s${name}="[^"]*"`)
|
||||
if (value === null) return attrs.replace(re, '')
|
||||
const decl = `${name}="${value}"`
|
||||
return re.test(attrs) ? attrs.replace(re, ` ${decl}`) : ` ${decl}${attrs}`
|
||||
}
|
||||
|
||||
/** In-place patch of <a:ln>: change the w/cap/cmpd attributes, replace the fill child and
|
||||
* (when requested) the prstDash / join children; all other bytes are kept. */
|
||||
function patchLnXml(lnXml: string, stroke: StrokePatch | null): string {
|
||||
const open = /^<a:ln((?:"[^"]*"|'[^']*'|[^"'>])*?)(\/?)>/.exec(lnXml)
|
||||
if (!open) return lnXml
|
||||
let attrs = open[1] ?? ''
|
||||
if (stroke) {
|
||||
const w = `w="${Math.round(stroke.widthEmu)}"`
|
||||
attrs = /\sw="[^"]*"/.test(attrs) ? attrs.replace(/\sw="[^"]*"/, ` ${w}`) : ` ${w}${attrs}`
|
||||
attrs = setLnAttr(attrs, 'w', String(Math.round(stroke.widthEmu)))
|
||||
if (stroke.cap !== undefined) attrs = setLnAttr(attrs, 'cap', stroke.cap)
|
||||
if (stroke.compound !== undefined)
|
||||
attrs = setLnAttr(attrs, 'cmpd', stroke.compound === 'sng' ? null : stroke.compound)
|
||||
}
|
||||
const fillXml = stroke ? `<a:solidFill>${srgbClrXml(stroke.color)}</a:solidFill>` : '<a:noFill/>'
|
||||
const fillXml = strokeFillXml(stroke)
|
||||
const dashXml =
|
||||
stroke?.dash && stroke.dash !== 'solid'
|
||||
? `<a:prstDash val="${escapeXmlAttr(stroke.dash)}"/>`
|
||||
: ''
|
||||
if (open[2] === '/') return `<a:ln${attrs}>${fillXml}${dashXml}</a:ln>`
|
||||
const joinXml = stroke?.join ? JOIN_XML[stroke.join] : ''
|
||||
if (open[2] === '/') return `<a:ln${attrs}>${fillXml}${dashXml}${joinXml}</a:ln>`
|
||||
const innerStart = open[0].length
|
||||
const innerEnd = lnXml.lastIndexOf('</a:ln>')
|
||||
if (innerEnd < 0) return lnXml
|
||||
@@ -1020,6 +1056,16 @@ function patchLnXml(lnXml: string, stroke: StrokePatch | null): string {
|
||||
inner = inner.slice(0, fillEnd) + dashXml + inner.slice(fillEnd)
|
||||
}
|
||||
}
|
||||
if (stroke && stroke.join !== undefined) {
|
||||
inner = inner.replace(
|
||||
/<a:(?:round|bevel|miter)\b(?:[^>]*\/>|[^>]*>[\s\S]*?<\/a:(?:round|bevel|miter)>)/,
|
||||
'',
|
||||
)
|
||||
// join sits after prstDash (when present), otherwise right after the fill
|
||||
const dashEl = /<a:prstDash\b(?:[^>]*\/>|[^>]*>[\s\S]*?<\/a:prstDash>)/.exec(inner)
|
||||
const at = dashEl ? dashEl.index + dashEl[0].length : inner.indexOf(fillXml) + fillXml.length
|
||||
inner = inner.slice(0, at) + joinXml + inner.slice(at)
|
||||
}
|
||||
return `<a:ln${attrs}>${inner}</a:ln>`
|
||||
}
|
||||
|
||||
@@ -1048,11 +1094,13 @@ export function patchElementStroke(originalXml: string, stroke: StrokePatch | nu
|
||||
}
|
||||
|
||||
const lnXml = stroke
|
||||
? `<a:ln w="${Math.round(stroke.widthEmu)}"><a:solidFill>${srgbClrXml(stroke.color)}</a:solidFill>${
|
||||
? `<a:ln w="${Math.round(stroke.widthEmu)}"${stroke.cap ? ` cap="${stroke.cap}"` : ''}${
|
||||
stroke.compound && stroke.compound !== 'sng' ? ` cmpd="${stroke.compound}"` : ''
|
||||
}>${strokeFillXml(stroke)}${
|
||||
stroke.dash && stroke.dash !== 'solid'
|
||||
? `<a:prstDash val="${escapeXmlAttr(stroke.dash)}"/>`
|
||||
: ''
|
||||
}</a:ln>`
|
||||
}${stroke.join ? JOIN_XML[stroke.join] : ''}</a:ln>`
|
||||
: '<a:ln><a:noFill/></a:ln>'
|
||||
// Insert after fill / geometry / xfrm (OOXML order: xfrm → geom → fill → ln)
|
||||
const anchor =
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* Durable identity (design step 0): ids resolved from the element's own bytes,
|
||||
* so they survive save→reopen, reparse, and group/ungroup.
|
||||
*
|
||||
* - element: the a16:creationId GUID (newborn elements mint one — see
|
||||
* creationIdXml — and PowerPoint writes them too) → "e_<guid8>"; otherwise
|
||||
* the <p:cNvPr id>, also persisted in the XML, unique per slide and stable
|
||||
* across reparses → "e_<n>".
|
||||
* - slide: the part path (slide7.xml → "s_7"; save never renames parts).
|
||||
*
|
||||
* The element search is scoped to the element's OWN <p:cNvPr> (always the
|
||||
* first in the fragment): group/SmartArt fragments embed their children's
|
||||
* bytes, and a wrapper without a creationId must not inherit a child's GUID —
|
||||
* after ungroup that same id would suddenly mean the child.
|
||||
*/
|
||||
import type { Slide, SlideElement } from './types'
|
||||
import { creationIdExtXml, creationIdXml } from './xml-utils'
|
||||
|
||||
const CREATION_ID_RE = /<a16:creationId[^>]*\bid="\{?([0-9A-Fa-f-]{36})\}?"/
|
||||
|
||||
export function elementDurableId(el: SlideElement): string | null {
|
||||
const xml = el.anchor?.originalXml
|
||||
if (!xml) {
|
||||
// Group children carry no byte slice of their own (it lives inside the parent
|
||||
// group's XML); their persisted <p:cNvPr id> — parsed as nvId, unique within
|
||||
// the slide part — still identifies them durably. (creationId continuity
|
||||
// while grouped is a known follow-up: the GUID sits in the parent's bytes.)
|
||||
const nvId = (el as { nvId?: number | string }).nvId
|
||||
return nvId != null ? `e_${nvId}` : null
|
||||
}
|
||||
const open = /<p:cNvPr\b[^>]*?(\/?)>/.exec(xml)
|
||||
if (!open) return null
|
||||
const own =
|
||||
open[1] === '/'
|
||||
? open[0]
|
||||
: xml.slice(open.index, xml.indexOf('</p:cNvPr>', open.index) + '</p:cNvPr>'.length)
|
||||
const creation = CREATION_ID_RE.exec(own)
|
||||
if (creation) return `e_${creation[1]!.slice(0, 8).toLowerCase()}`
|
||||
const cnvpr = /\bid="(\d+)"/.exec(open[0])
|
||||
return cnvpr ? `e_${cnvpr[1]!}` : null
|
||||
}
|
||||
|
||||
export function slideDurableId(slide: Slide): string {
|
||||
const m = /slide(\d+)\.xml$/.exec(slide.path)
|
||||
return m ? `s_${m[1]}` : `s_${slide.path.replace(/[^a-zA-Z0-9]/g, '_')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* The pre-upgrade fallback form ("e_<cNvPr id>"), independent of whether a
|
||||
* creationId exists. Kept resolvable as an ALIAS after ensureCreationId mints
|
||||
* a GUID, so refs held across the upgrade keep working.
|
||||
*/
|
||||
export function elementCNvPrId(el: SlideElement): string | null {
|
||||
const xml = el.anchor?.originalXml
|
||||
if (!xml) {
|
||||
const nvId = (el as { nvId?: number | string }).nvId
|
||||
return nvId != null ? `e_${nvId}` : null
|
||||
}
|
||||
const open = /<p:cNvPr\b[^>]*?(\/?)>/.exec(xml)
|
||||
if (!open) return null
|
||||
const id = /\bid="(\d+)"/.exec(open[0])
|
||||
return id ? `e_${id[1]!}` : null
|
||||
}
|
||||
|
||||
/** Ref match across all forms: parse-time id, durable GUID, and the cNvPr
|
||||
form — the latter stays an alias after ensureCreationId upgrades an
|
||||
element to a GUID mid-session, so refs held across the upgrade resolve. */
|
||||
export function matchesElementRef(el: SlideElement, id: string): boolean {
|
||||
return el.id === id || elementDurableId(el) === id || elementCNvPrId(el) === id
|
||||
}
|
||||
|
||||
/**
|
||||
* Progressive identity hardening for foreign decks: mint an a16:creationId
|
||||
* into the element's OWN <p:cNvPr> when it lacks one. Mutates the anchor and
|
||||
* is idempotent — callers invoke it only for elements whose bytes are being
|
||||
* rewritten anyway (the patch-save path), so untouched content stays
|
||||
* byte-identical on save. extLst is cNvPr's last child, so appending before
|
||||
* the close tag keeps schema order (after any hlinkClick).
|
||||
*/
|
||||
export function ensureCreationId(el: SlideElement): void {
|
||||
const xml = el.anchor?.originalXml
|
||||
if (!xml) return
|
||||
const open = /<p:cNvPr\b[^>]*?(\/?)>/.exec(xml)
|
||||
if (!open) return
|
||||
if (open[1] === '/') {
|
||||
// Self-closing: expand into a tag pair carrying the extLst
|
||||
el.anchor.originalXml =
|
||||
xml.slice(0, open.index + open[0].length - 2) +
|
||||
`>${creationIdXml()}</p:cNvPr>` +
|
||||
xml.slice(open.index + open[0].length)
|
||||
return
|
||||
}
|
||||
const close = xml.indexOf('</p:cNvPr>', open.index)
|
||||
if (close < 0) return
|
||||
const own = xml.slice(open.index, close)
|
||||
if (CREATION_ID_RE.test(own)) return
|
||||
// extLst has maxOccurs=1: merge into an existing one (decorative/compat
|
||||
// extensions) rather than appending a second, invalid, extLst. cNvPr's own
|
||||
// extLst is its LAST child — an earlier </a:extLst> belongs to a nested
|
||||
// hlinkClick/hlinkHover extension list and must not receive the GUID.
|
||||
const extLstClose = own.lastIndexOf('</a:extLst>')
|
||||
if (extLstClose >= 0 && own.slice(extLstClose + '</a:extLst>'.length).trim() === '') {
|
||||
const at = open.index + extLstClose
|
||||
el.anchor.originalXml = xml.slice(0, at) + creationIdExtXml() + xml.slice(at)
|
||||
return
|
||||
}
|
||||
el.anchor.originalXml = xml.slice(0, close) + creationIdXml() + xml.slice(close)
|
||||
}
|
||||
|
||||
/**
|
||||
* Durable id for a group child. Children carry no byte slice of their own —
|
||||
* their bytes (including any a16:creationId) live inside the parent group's
|
||||
* XML — so locate the child's <p:cNvPr> there by its parsed nvId (unique per
|
||||
* slide part) and scope the creationId search to that block. Falls back to
|
||||
* elementDurableId's nvId form, so the id is at worst the same as before.
|
||||
*/
|
||||
export function groupChildDurableId(grp: SlideElement, child: SlideElement): string | null {
|
||||
const nvId = (child as { nvId?: number | string }).nvId
|
||||
const xml = grp.anchor?.originalXml
|
||||
if (xml && nvId != null) {
|
||||
const open = new RegExp(`<p:cNvPr\\b[^>]*\\bid="${nvId}"[^>]*?(\\/?)>`).exec(xml)
|
||||
if (open) {
|
||||
const own =
|
||||
open[1] === '/'
|
||||
? open[0]
|
||||
: xml.slice(open.index, xml.indexOf('</p:cNvPr>', open.index) + '</p:cNvPr>'.length)
|
||||
const creation = CREATION_ID_RE.exec(own)
|
||||
if (creation) return `e_${creation[1]!.slice(0, 8).toLowerCase()}`
|
||||
}
|
||||
}
|
||||
return elementDurableId(child)
|
||||
}
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
removeSlideBackgroundXml,
|
||||
type GradientFillPatch,
|
||||
type SlideTransitionKind,
|
||||
type StrokePatch,
|
||||
} from './generate'
|
||||
import {
|
||||
buildTableXml,
|
||||
@@ -47,6 +48,7 @@ import {
|
||||
import { BLANK_SLIDE_XML } from './blank'
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
import { elementSpid } from './animation'
|
||||
import { ensureCreationId } from './identity'
|
||||
import { listMasterParts, parseMasterPart } from './master-edit'
|
||||
import type {
|
||||
Paragraph,
|
||||
@@ -59,6 +61,7 @@ import type {
|
||||
ChartElement,
|
||||
GroupElement,
|
||||
Transform,
|
||||
Stroke,
|
||||
} from './types'
|
||||
import { patchTableStyleXml, ensureTableStyleXml, type TableStyleEdit } from './table-edit'
|
||||
import { buildChartSpaceXml, type NewChartKind, type NewChartOptions } from './chart-insert'
|
||||
@@ -125,19 +128,25 @@ export {
|
||||
type GradientFillPatch,
|
||||
type BackgroundImagePatch,
|
||||
type SlideTransitionKind,
|
||||
type StrokePatch,
|
||||
} from './generate'
|
||||
export {
|
||||
addElement,
|
||||
addPicture,
|
||||
addImageMediaAndRel,
|
||||
deleteElement,
|
||||
buildSpXml,
|
||||
buildTableXml,
|
||||
buildTableGridXml,
|
||||
buildGrpSpXml,
|
||||
calcBoundingBox,
|
||||
type NewElementOptions,
|
||||
type NewElementBodyPr,
|
||||
type NewPictureOptions,
|
||||
type NewShapeKind,
|
||||
type NewTableOptions,
|
||||
type NewTableCellSpec,
|
||||
type NewTableGridOptions,
|
||||
} from './insert'
|
||||
export {
|
||||
alignRects,
|
||||
@@ -147,6 +156,14 @@ export {
|
||||
type AlignRect,
|
||||
} from './align'
|
||||
export { createBlankPptx } from './blank'
|
||||
export {
|
||||
elementCNvPrId,
|
||||
elementDurableId,
|
||||
ensureCreationId,
|
||||
groupChildDurableId,
|
||||
matchesElementRef,
|
||||
slideDurableId,
|
||||
} from './identity'
|
||||
export { promoteSlideBackground, isBackgroundLikeElement } from './background-promote'
|
||||
export {
|
||||
applyThemeToArchive,
|
||||
@@ -719,6 +736,20 @@ export function patchSlideXml(slide: Slide): string {
|
||||
|
||||
/** One element's current XML slice (dirty elements patch-regenerated, clean elements original bytes). */
|
||||
export function patchedElementXml(el: SlideElement): string {
|
||||
// Progressive identity hardening: an element whose bytes are being rewritten
|
||||
// anyway gets a creationId minted into its anchor (idempotent — repeated calls
|
||||
// from commitSaved/buildZip see the same GUID). Clean elements pass through
|
||||
// untouched, so unedited decks stay byte-identical on save.
|
||||
if (
|
||||
el.dirty ||
|
||||
el.dirtyTransform ||
|
||||
el.dirtyFill ||
|
||||
el.dirtyStroke ||
|
||||
el.dirtySrcRect ||
|
||||
el.dirtyPPr
|
||||
) {
|
||||
ensureCreationId(el)
|
||||
}
|
||||
let xml = el.anchor.originalXml
|
||||
if (el.dirty && (el.type === 'text' || el.type === 'shape')) {
|
||||
xml = patchTextElementXml(el as TextElement, xml)
|
||||
@@ -747,12 +778,7 @@ export function patchedElementXml(el: SlideElement): string {
|
||||
}
|
||||
if (el.dirtyStroke && (el.type === 'text' || el.type === 'shape' || el.type === 'picture')) {
|
||||
const stroke = (el as TextElement).stroke
|
||||
xml = patchElementStroke(
|
||||
xml,
|
||||
stroke && stroke.fill.type === 'solid'
|
||||
? { color: stroke.fill.color, widthEmu: stroke.width, dash: stroke.dash }
|
||||
: null,
|
||||
)
|
||||
xml = patchElementStroke(xml, stroke ? modelStrokeToPatch(stroke) : null)
|
||||
}
|
||||
if (el.dirtySrcRect && el.type === 'picture') {
|
||||
const pic = el as import('./types').PictureElement
|
||||
@@ -961,21 +987,8 @@ export function setShapePresetGeometry(slide: Slide, elementId: string, prst: st
|
||||
if (!/^[A-Za-z0-9]+$/.test(prst)) return false
|
||||
const el = slide.elements.find((e) => e.id === elementId)
|
||||
if (!el || (el.type !== 'text' && el.type !== 'shape')) return false
|
||||
let xml = patchedElementXml(el)
|
||||
const geomXml = `<a:prstGeom prst="${prst}"><a:avLst/></a:prstGeom>`
|
||||
const existing =
|
||||
/<a:prstGeom\b[^>]*\/>|<a:prstGeom\b[\s\S]*?<\/a:prstGeom>|<a:custGeom\b[\s\S]*?<\/a:custGeom>/.exec(
|
||||
xml,
|
||||
)
|
||||
if (existing) {
|
||||
xml = xml.slice(0, existing.index) + geomXml + xml.slice(existing.index + existing[0].length)
|
||||
} else {
|
||||
// No explicit geometry (bare text boxes): insert after </a:xfrm> inside spPr
|
||||
const xfrmClose = /<\/a:xfrm>/.exec(xml)
|
||||
if (!xfrmClose) return false
|
||||
const at = xfrmClose.index + xfrmClose[0].length
|
||||
xml = xml.slice(0, at) + geomXml + xml.slice(at)
|
||||
}
|
||||
const xml = swapGeometryXml(patchedElementXml(el), prst)
|
||||
if (xml == null) return false
|
||||
el.dirty = el.dirtyTransform = el.dirtyFill = el.dirtyStroke = false
|
||||
el.dirtyPPr = undefined
|
||||
el.anchor.originalXml = xml
|
||||
@@ -987,6 +1000,81 @@ export function setShapePresetGeometry(slide: Slide, elementId: string, prst: st
|
||||
return true
|
||||
}
|
||||
|
||||
/** Serialize adjust values as an <a:avLst> ("val" formulas only). */
|
||||
function avLstXml(adjust: Record<string, number>): string {
|
||||
const gds = Object.entries(adjust)
|
||||
.map(([n, v]) => `<a:gd name="${n}" fmla="val ${Math.round(v)}"/>`)
|
||||
.join('')
|
||||
return `<a:avLst>${gds}</a:avLst>`
|
||||
}
|
||||
|
||||
/** Adjust maps must be non-empty, with safe names and finite values (they go straight into XML). */
|
||||
function validAdjust(adjust: Record<string, number>): boolean {
|
||||
const entries = Object.entries(adjust)
|
||||
return (
|
||||
entries.length > 0 && entries.every(([n, v]) => /^[A-Za-z0-9]+$/.test(n) && Number.isFinite(v))
|
||||
)
|
||||
}
|
||||
|
||||
/** Replace the <a:avLst> inside <a:prstGeom> with the given adjust values; null without a prstGeom. */
|
||||
function swapAvLstXml(xml: string, adjust: Record<string, number>): string | null {
|
||||
const open = /<a:prstGeom\b[^>]*?(\/?)>/.exec(xml)
|
||||
if (!open) return null
|
||||
const av = avLstXml(adjust)
|
||||
if (open[1] === '/') {
|
||||
const tag = open[0].slice(0, -2) + '>'
|
||||
return (
|
||||
xml.slice(0, open.index) + tag + av + '</a:prstGeom>' + xml.slice(open.index + open[0].length)
|
||||
)
|
||||
}
|
||||
const end = xml.indexOf('</a:prstGeom>', open.index)
|
||||
if (end < 0) return null
|
||||
const innerStart = open.index + open[0].length
|
||||
const inner = xml.slice(innerStart, end)
|
||||
const avRe = /<a:avLst\b[^>]*\/>|<a:avLst\b[\s\S]*?<\/a:avLst>/
|
||||
const newInner = avRe.test(inner) ? inner.replace(avRe, av) : av + inner
|
||||
return xml.slice(0, innerStart) + newInner + xml.slice(end)
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a shape's preset-geometry adjust values (the "yellow handle" edit):
|
||||
* rewrite <a:avLst> inside <a:prstGeom>, keeping everything else. Byte surgery
|
||||
* baked directly into originalXml (same contract as setShapePresetGeometry).
|
||||
*/
|
||||
export function setShapeAdjustValues(
|
||||
slide: Slide,
|
||||
elementId: string,
|
||||
adjust: Record<string, number>,
|
||||
): boolean {
|
||||
if (!validAdjust(adjust)) return false
|
||||
const el = slide.elements.find((e) => e.id === elementId)
|
||||
if (!el || (el.type !== 'text' && el.type !== 'shape')) return false
|
||||
const xml = swapAvLstXml(patchedElementXml(el), adjust)
|
||||
if (xml == null) return false
|
||||
el.dirty = el.dirtyTransform = el.dirtyFill = el.dirtyStroke = false
|
||||
el.dirtyPPr = undefined
|
||||
el.anchor.originalXml = xml
|
||||
;(el as TextElement).adjust = { ...adjust }
|
||||
slide.structureDirty = true
|
||||
return true
|
||||
}
|
||||
|
||||
/** Replace <a:prstGeom>/<a:custGeom> in a shape's XML with the new preset; null if no anchor point exists. */
|
||||
function swapGeometryXml(xml: string, prst: string): string | null {
|
||||
const geomXml = `<a:prstGeom prst="${prst}"><a:avLst/></a:prstGeom>`
|
||||
const existing =
|
||||
/<a:prstGeom\b[^>]*\/>|<a:prstGeom\b[\s\S]*?<\/a:prstGeom>|<a:custGeom\b[\s\S]*?<\/a:custGeom>/.exec(
|
||||
xml,
|
||||
)
|
||||
if (existing)
|
||||
return xml.slice(0, existing.index) + geomXml + xml.slice(existing.index + existing[0].length)
|
||||
// No explicit geometry (bare text boxes): insert after </a:xfrm> inside spPr
|
||||
const xfrmClose = /<\/a:xfrm>/.exec(xml)
|
||||
if (!xfrmClose) return null
|
||||
const at = xfrmClose.index + xfrmClose[0].length
|
||||
return xml.slice(0, at) + geomXml + xml.slice(at)
|
||||
}
|
||||
|
||||
/**
|
||||
* Text-box vertical alignment (bodyPr anchor: t/ctr/b). Byte surgery baked directly into originalXml.
|
||||
*/
|
||||
@@ -3008,12 +3096,24 @@ export function setTableColWidth(
|
||||
const patched = gc[0].replace(/\bw="-?\d+"/, `w="${w}"`)
|
||||
xml = xml.slice(0, gc.index) + patched + xml.slice(gc.index + gc[0].length)
|
||||
|
||||
const dxRtl = table.rtl ? w - table.colWidths[col]! : 0
|
||||
table.colWidths[col] = w
|
||||
const sum = table.colWidths.reduce((a, b) => a + b, 0)
|
||||
xml = xml.replace(
|
||||
/(<p:xfrm[^>]*>[\s\S]*?<a:ext\s[^>]*\bcx=")-?\d+(")/,
|
||||
(_a, pre: string, post: string) => `${pre}${sum}${post}`,
|
||||
)
|
||||
// rtl mirroring anchors the table's visual-right edge: growing a column extends the
|
||||
// frame leftward, so the origin shifts by the width delta (LTR keeps the origin and
|
||||
// extends rightward)
|
||||
if (dxRtl) {
|
||||
const newX = el.transform.offset.x - dxRtl
|
||||
xml = xml.replace(
|
||||
/(<p:xfrm[^>]*>[\s\S]*?<a:off\s[^>]*\bx=")-?\d+(")/,
|
||||
(_a, pre: string, post: string) => `${pre}${newX}${post}`,
|
||||
)
|
||||
el.transform.offset.x = newX
|
||||
}
|
||||
el.anchor.originalXml = xml
|
||||
el.transform.offset.cx = sum
|
||||
slide.structureDirty = true
|
||||
@@ -3259,6 +3359,13 @@ export function pasteElements(
|
||||
/(<p:cNvPr\s[^>]*\bid=")\d+(")/g,
|
||||
(_a, pre: string, post: string) => `${pre}${nextId++}${post}`,
|
||||
)
|
||||
// Pasted elements are new identities: mint fresh creationIds so durable ids
|
||||
// never collide with their source elements on the same slide
|
||||
xml = xml.replace(
|
||||
/(<a16:creationId[^>]*\bid=")\{?[0-9A-Fa-f-]{36}\}?(")/g,
|
||||
(_a, pre: string, post: string) =>
|
||||
`${pre}{${globalThis.crypto.randomUUID().toUpperCase()}}${post}`,
|
||||
)
|
||||
// Offset only the outermost xfrm's off (group child coordinate systems stay put)
|
||||
xml = xml.replace(/<a:off\b[^>]*\/>/, (tag) =>
|
||||
tag
|
||||
@@ -3646,25 +3753,109 @@ export function editGroupChildFill(
|
||||
}
|
||||
|
||||
/** Group-child stroke (null = remove the stroke). */
|
||||
/** In-memory Stroke → StrokePatch for the save-time XML rewrite (inverse of strokePatchToModel).
|
||||
* null for fills a StrokePatch cannot express (image/pattern), which writes <a:noFill/>. */
|
||||
function modelStrokeToPatch(stroke: Stroke): StrokePatch | null {
|
||||
const capMap = { flat: 'flat', round: 'rnd', square: 'sq' } as const
|
||||
const base = {
|
||||
widthEmu: stroke.width,
|
||||
// 'solid' actively clears a stale prstDash left in the original bytes
|
||||
dash: stroke.dash ?? 'solid',
|
||||
...(stroke.cap ? { cap: capMap[stroke.cap] } : {}),
|
||||
...(stroke.join ? { join: stroke.join } : {}),
|
||||
...(stroke.compound ? { compound: stroke.compound } : {}),
|
||||
}
|
||||
if (stroke.fill.type === 'solid') return { color: stroke.fill.color, ...base }
|
||||
if (stroke.fill.type === 'gradient')
|
||||
return {
|
||||
color: stroke.fill.stops[0]?.color ?? '#000000',
|
||||
...base,
|
||||
gradient: { stops: stroke.fill.stops, angle: stroke.fill.angle ?? 0 },
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** StrokePatch → in-memory Stroke model (mirrors what patchLnXml writes into the XML). */
|
||||
export function strokePatchToModel(stroke: StrokePatch): Stroke {
|
||||
const capMap = { flat: 'flat', rnd: 'round', sq: 'square' } as const
|
||||
return {
|
||||
fill: stroke.gradient
|
||||
? {
|
||||
type: 'gradient',
|
||||
stops: stroke.gradient.stops,
|
||||
angle: Math.round(stroke.gradient.angle),
|
||||
}
|
||||
: { type: 'solid', color: stroke.color },
|
||||
width: stroke.widthEmu,
|
||||
...(stroke.dash && stroke.dash !== 'solid' ? { dash: stroke.dash } : {}),
|
||||
...(stroke.cap ? { cap: capMap[stroke.cap] } : {}),
|
||||
...(stroke.join ? { join: stroke.join } : {}),
|
||||
...(stroke.compound && stroke.compound !== 'sng' ? { compound: stroke.compound } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function editGroupChildStroke(
|
||||
slide: Slide,
|
||||
groupId: string,
|
||||
childId: string,
|
||||
stroke: { color: string; widthEmu: number; dash?: string } | null,
|
||||
stroke: StrokePatch | null,
|
||||
): boolean {
|
||||
const found = findGroupChild(slide, groupId, childId)
|
||||
const child = found?.child
|
||||
if (!child || (child.type !== 'text' && child.type !== 'shape' && child.type !== 'picture'))
|
||||
return false
|
||||
const t = child as TextElement
|
||||
t.stroke = stroke
|
||||
? {
|
||||
fill: { type: 'solid', color: stroke.color },
|
||||
width: stroke.widthEmu,
|
||||
...(stroke.dash ? { dash: stroke.dash } : {}),
|
||||
}
|
||||
: undefined
|
||||
t.stroke = stroke ? strokePatchToModel(stroke) : undefined
|
||||
if (!patchGroupChildXml(found!.grp, child, (xml) => patchElementStroke(xml, stroke))) return false
|
||||
slide.structureDirty = true
|
||||
return true
|
||||
}
|
||||
|
||||
/** Group-child adjust values (same avLst-swap semantics as setShapeAdjustValues). */
|
||||
export function setGroupChildShapeAdjustValues(
|
||||
slide: Slide,
|
||||
groupId: string,
|
||||
childId: string,
|
||||
adjust: Record<string, number>,
|
||||
): boolean {
|
||||
if (!validAdjust(adjust)) return false
|
||||
const found = findGroupChild(slide, groupId, childId)
|
||||
const child = found?.child
|
||||
if (!child || (child.type !== 'text' && child.type !== 'shape')) return false
|
||||
let swapped = false
|
||||
const ok = patchGroupChildXml(found!.grp, child, (xml) => {
|
||||
const next = swapAvLstXml(xml, adjust)
|
||||
swapped = next != null
|
||||
return next ?? xml
|
||||
})
|
||||
if (!ok || !swapped) return false
|
||||
;(child as TextElement).adjust = { ...adjust }
|
||||
slide.structureDirty = true
|
||||
return true
|
||||
}
|
||||
|
||||
/** Group-child "Change Shape" (same geometry-swap semantics as setShapePresetGeometry). */
|
||||
export function setGroupChildShapePresetGeometry(
|
||||
slide: Slide,
|
||||
groupId: string,
|
||||
childId: string,
|
||||
prst: string,
|
||||
): boolean {
|
||||
if (!/^[A-Za-z0-9]+$/.test(prst)) return false
|
||||
const found = findGroupChild(slide, groupId, childId)
|
||||
const child = found?.child
|
||||
if (!child || (child.type !== 'text' && child.type !== 'shape')) return false
|
||||
let swapped = false
|
||||
const ok = patchGroupChildXml(found!.grp, child, (xml) => {
|
||||
const next = swapGeometryXml(xml, prst)
|
||||
swapped = next != null
|
||||
return next ?? xml
|
||||
})
|
||||
if (!ok || !swapped) return false
|
||||
const shape = child as TextElement
|
||||
shape.presetGeometry = prst
|
||||
delete shape.adjust
|
||||
delete shape.customGeometry
|
||||
slide.structureDirty = true
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
*/
|
||||
import type { EmuRect, Paragraph, PictureElement, Slide, SlideElement, TextElement } from './types'
|
||||
import { generateParagraphXml, generateXfrmXml } from './generate'
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
import { creationIdXml, escapeXmlAttr } from './xml-utils'
|
||||
import { relsPathFor } from './zip'
|
||||
import type { OpenedPptx } from './index'
|
||||
import { cleanupDeletedElementResources } from './resource-cleanup'
|
||||
@@ -23,14 +23,59 @@ import { cleanupDeletedElementResources } from './resource-cleanup'
|
||||
*/
|
||||
export type NewShapeKind = 'textbox' | (string & {})
|
||||
|
||||
/**
|
||||
* Text-body geometry overrides for generated boxes (pdf2pptx P25): imported
|
||||
* absolutely-positioned text must not inherit PowerPoint's default insets
|
||||
* (0.1in/0.05in) or wrap defaults, or every box drifts off its measured spot.
|
||||
*/
|
||||
export interface NewElementBodyPr {
|
||||
/** wrap="none" lets a measured line overflow instead of re-wrapping */
|
||||
wrap?: 'square' | 'none'
|
||||
/** vertical anchor (default top) */
|
||||
anchor?: 't' | 'ctr' | 'b'
|
||||
/** lIns/tIns/rIns/bIns (EMU); absent keeps PowerPoint defaults */
|
||||
insetsEmu?: { l: number; t: number; r: number; b: number }
|
||||
}
|
||||
|
||||
export interface NewElementOptions {
|
||||
kind: NewShapeKind
|
||||
offset: EmuRect
|
||||
paragraphs?: Paragraph[]
|
||||
/** Solid shape fill (#RRGGBB); textbox has no fill by default */
|
||||
/** Solid shape fill (#RRGGBB, or #RRGGBBAA for translucency); textbox has no fill by default */
|
||||
fillColor?: string
|
||||
/** Shape stroke (solid color, width in EMU) */
|
||||
stroke?: { color: string; widthEmu: number }
|
||||
/** body geometry overrides; absent = `wrap="square" rtlCol="0"` as before */
|
||||
bodyPr?: NewElementBodyPr
|
||||
}
|
||||
|
||||
/**
|
||||
* #RRGGBB or #RRGGBBAA → <a:srgbClr>, translucency as an <a:alpha> child
|
||||
* (pdf2pptx scrims: an opaque slab where the source painted a wash reads as a
|
||||
* black bar). Alpha is the LAST byte pair, 00 = transparent, FF = opaque.
|
||||
*/
|
||||
function srgbClrXml(color: string): string {
|
||||
const hex = color.replace(/^#/, '').toUpperCase()
|
||||
const rgb = hex.slice(0, 6)
|
||||
if (hex.length >= 8) {
|
||||
const alpha = Math.round((parseInt(hex.slice(6, 8), 16) / 255) * 100000)
|
||||
if (alpha < 100000) return `<a:srgbClr val="${rgb}"><a:alpha val="${alpha}"/></a:srgbClr>`
|
||||
}
|
||||
return `<a:srgbClr val="${rgb}"/>`
|
||||
}
|
||||
|
||||
/** <a:bodyPr> for generated sp fragments (defaults match the historical output). */
|
||||
function buildBodyPrXml(bodyPr: NewElementBodyPr | undefined): string {
|
||||
if (!bodyPr) return '<a:bodyPr wrap="square" rtlCol="0"/>'
|
||||
const ins = bodyPr.insetsEmu
|
||||
return (
|
||||
`<a:bodyPr wrap="${bodyPr.wrap ?? 'square'}" rtlCol="0"` +
|
||||
(ins
|
||||
? ` lIns="${Math.round(ins.l)}" tIns="${Math.round(ins.t)}" rIns="${Math.round(ins.r)}" bIns="${Math.round(ins.b)}"`
|
||||
: '') +
|
||||
(bodyPr.anchor ? ` anchor="${bodyPr.anchor}"` : '') +
|
||||
'/>'
|
||||
)
|
||||
}
|
||||
|
||||
let insertCounter = 1
|
||||
@@ -71,7 +116,7 @@ function buildCxnSpXml(
|
||||
const head = def.head ? '<a:headEnd type="triangle" w="med" len="med"/>' : ''
|
||||
const tail = def.tail ? '<a:tailEnd type="triangle" w="med" len="med"/>' : ''
|
||||
return (
|
||||
`<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}"/>` +
|
||||
`<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}">${creationIdXml()}</p:cNvPr>` +
|
||||
'<p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>' +
|
||||
`<p:spPr><a:xfrm><a:off x="${o.x}" y="${o.y}"/><a:ext cx="${o.cx}" cy="${o.cy}"/></a:xfrm>` +
|
||||
`<a:prstGeom prst="${def.prst}"><a:avLst/></a:prstGeom>` +
|
||||
@@ -104,9 +149,7 @@ export function buildSpXml(slide: Slide, opts: NewElementOptions): string {
|
||||
const geom = isTextbox
|
||||
? ''
|
||||
: `<a:prstGeom prst="${escapeXmlAttr(opts.kind)}"><a:avLst/></a:prstGeom>`
|
||||
const fill = opts.fillColor
|
||||
? `<a:solidFill><a:srgbClr val="${opts.fillColor.replace(/^#/, '').slice(0, 6).toUpperCase()}"/></a:solidFill>`
|
||||
: ''
|
||||
const fill = opts.fillColor ? `<a:solidFill>${srgbClrXml(opts.fillColor)}</a:solidFill>` : ''
|
||||
const ln = opts.stroke
|
||||
? `<a:ln w="${Math.round(opts.stroke.widthEmu)}"><a:solidFill><a:srgbClr val="${opts.stroke.color.replace(/^#/, '').slice(0, 6).toUpperCase()}"/></a:solidFill></a:ln>`
|
||||
: ''
|
||||
@@ -114,10 +157,10 @@ export function buildSpXml(slide: Slide, opts: NewElementOptions): string {
|
||||
.map((p) => generateParagraphXml(p))
|
||||
.join('')
|
||||
return (
|
||||
`<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}"/>` +
|
||||
`<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}">${creationIdXml()}</p:cNvPr>` +
|
||||
`<p:cNvSpPr${isTextbox ? ' txBox="1"' : ''}/><p:nvPr/></p:nvSpPr>` +
|
||||
`<p:spPr>${xfrm}${geom}${fill}${ln}</p:spPr>` +
|
||||
`<p:txBody><a:bodyPr wrap="square" rtlCol="0"/><a:lstStyle/>${paras}</p:txBody></p:sp>`
|
||||
`<p:txBody>${buildBodyPrXml(opts.bodyPr)}<a:lstStyle/>${paras}</p:txBody></p:sp>`
|
||||
)
|
||||
}
|
||||
|
||||
@@ -200,7 +243,7 @@ export function buildTableXml(slide: Slide, opts: NewTableOptions): string {
|
||||
() => `<a:tr h="${rowH}">${cell.repeat(cols)}</a:tr>`,
|
||||
).join('')
|
||||
return (
|
||||
`<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="${id}" name="Table ${id}"/>` +
|
||||
`<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="${id}" name="Table ${id}">${creationIdXml()}</p:cNvPr>` +
|
||||
'<p:cNvGraphicFramePr><a:graphicFrameLocks noGrp="1"/></p:cNvGraphicFramePr><p:nvPr/></p:nvGraphicFramePr>' +
|
||||
`<p:xfrm><a:off x="${opts.offset.x}" y="${opts.offset.y}"/><a:ext cx="${opts.offset.cx}" cy="${opts.offset.cy}"/></p:xfrm>` +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/table">' +
|
||||
@@ -209,6 +252,121 @@ export function buildTableXml(slide: Slide, opts: NewTableOptions): string {
|
||||
)
|
||||
}
|
||||
|
||||
// ── Grid table insertion (pdf2pptx P25): explicit widths/heights/merges ──
|
||||
|
||||
/** One grid cell of buildTableGridXml. Covered cells (hMerge/vMerge) must still be listed. */
|
||||
export interface NewTableCellSpec {
|
||||
paragraphs?: Paragraph[]
|
||||
/** columns this cell spans (a:tc gridSpan), default 1 */
|
||||
gridSpan?: number
|
||||
/** rows this cell spans (a:tc rowSpan), default 1 */
|
||||
rowSpan?: number
|
||||
/** covered by a gridSpan cell to the left */
|
||||
hMerge?: boolean
|
||||
/** covered by a rowSpan cell above */
|
||||
vMerge?: boolean
|
||||
/** solid cell shading (#RRGGBB) */
|
||||
fillColor?: string
|
||||
/** vertical content alignment (a:tcPr anchor), default top */
|
||||
anchor?: 't' | 'ctr' | 'b'
|
||||
/** cell margins (EMU); absent keeps PowerPoint defaults */
|
||||
marginsEmu?: { l: number; t: number; r: number; b: number }
|
||||
}
|
||||
|
||||
export interface NewTableGridOptions {
|
||||
offset: EmuRect
|
||||
colWidthsEmu: number[]
|
||||
rowHeightsEmu: number[]
|
||||
/** row-major; every row lists one entry per GRID column (merged-covered cells flagged) */
|
||||
cells: NewTableCellSpec[][]
|
||||
/**
|
||||
* uniform cell borders; scope 'all' rules every edge, 'insideV' only the
|
||||
* verticals between columns (rule-separated zones); absent = borderless
|
||||
*/
|
||||
border?: { color: string; widthEmu: number; scope?: 'all' | 'insideV' }
|
||||
}
|
||||
|
||||
function tableCellXml(
|
||||
cell: NewTableCellSpec,
|
||||
colIdx: number,
|
||||
border: NewTableGridOptions['border'],
|
||||
): string {
|
||||
const attrs: string[] = []
|
||||
if ((cell.gridSpan ?? 1) > 1) attrs.push(`gridSpan="${Math.floor(cell.gridSpan!)}"`)
|
||||
if ((cell.rowSpan ?? 1) > 1) attrs.push(`rowSpan="${Math.floor(cell.rowSpan!)}"`)
|
||||
if (cell.hMerge) attrs.push('hMerge="1"')
|
||||
if (cell.vMerge) attrs.push('vMerge="1"')
|
||||
const tcAttrs = attrs.length ? ` ${attrs.join(' ')}` : ''
|
||||
|
||||
const tcPrAttrs: string[] = []
|
||||
const m = cell.marginsEmu
|
||||
if (m) {
|
||||
tcPrAttrs.push(
|
||||
`marL="${Math.round(m.l)}"`,
|
||||
`marR="${Math.round(m.r)}"`,
|
||||
`marT="${Math.round(m.t)}"`,
|
||||
`marB="${Math.round(m.b)}"`,
|
||||
)
|
||||
}
|
||||
if (cell.anchor && cell.anchor !== 't') tcPrAttrs.push(`anchor="${cell.anchor}"`)
|
||||
|
||||
// CT_TableCellProperties child order: lnL lnR lnT lnB … fill
|
||||
let lines = ''
|
||||
if (border) {
|
||||
const color = border.color.replace(/^#/, '').slice(0, 6).toUpperCase()
|
||||
const w = Math.max(1, Math.round(border.widthEmu))
|
||||
const ln = (tag: string) =>
|
||||
`<a:${tag} w="${w}" cap="flat"><a:solidFill><a:srgbClr val="${color}"/></a:solidFill></a:${tag}>`
|
||||
if ((border.scope ?? 'all') === 'all') {
|
||||
lines = ln('lnL') + ln('lnR') + ln('lnT') + ln('lnB')
|
||||
} else if (colIdx > 0 && !cell.hMerge) {
|
||||
// insideV: only the left edge of non-first columns carries the rule
|
||||
lines = ln('lnL')
|
||||
}
|
||||
}
|
||||
const fill = cell.fillColor
|
||||
? `<a:solidFill><a:srgbClr val="${cell.fillColor.replace(/^#/, '').slice(0, 6).toUpperCase()}"/></a:solidFill>`
|
||||
: ''
|
||||
const inner = lines + fill
|
||||
const tcPr = `<a:tcPr${tcPrAttrs.length ? ` ${tcPrAttrs.join(' ')}` : ''}${inner ? `>${inner}</a:tcPr>` : '/>'}`
|
||||
|
||||
const paras = (
|
||||
cell.paragraphs?.length ? cell.paragraphs : [{ runs: [{ text: '' }] } as Paragraph]
|
||||
)
|
||||
.map((p) => generateParagraphXml(p))
|
||||
.join('')
|
||||
return `<a:tc${tcAttrs}><a:txBody><a:bodyPr/><a:lstStyle/>${paras}</a:txBody>${tcPr}</a:tc>`
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a table graphicFrame with explicit column widths, row heights, merged
|
||||
* cells, per-cell shading/anchor/margins and uniform borders — what a measured
|
||||
* PDF table needs (buildTableXml only makes uniform empty grids). No
|
||||
* tableStyleId on purpose: styling is fully explicit, so the deck's theme
|
||||
* cannot repaint the imported table. Insert via appendRawElements.
|
||||
*/
|
||||
export function buildTableGridXml(slide: Slide, opts: NewTableGridOptions): string {
|
||||
const id = nextCNvPrId(slide)
|
||||
const grid = opts.colWidthsEmu
|
||||
.map((w) => `<a:gridCol w="${Math.max(1, Math.round(w))}"/>`)
|
||||
.join('')
|
||||
const trs = opts.cells
|
||||
.map((row, r) => {
|
||||
const h = Math.max(1, Math.round(opts.rowHeightsEmu[r] ?? 1))
|
||||
// one <a:tc> per grid column (covered columns keep their own hMerge tc)
|
||||
const tcs = row.map((cell, colIdx) => tableCellXml(cell, colIdx, opts.border)).join('')
|
||||
return `<a:tr h="${h}">${tcs}</a:tr>`
|
||||
})
|
||||
.join('')
|
||||
return (
|
||||
`<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="${id}" name="Table ${id}">${creationIdXml()}</p:cNvPr>` +
|
||||
'<p:cNvGraphicFramePr><a:graphicFrameLocks noGrp="1"/></p:cNvGraphicFramePr><p:nvPr/></p:nvGraphicFramePr>' +
|
||||
`<p:xfrm><a:off x="${opts.offset.x}" y="${opts.offset.y}"/><a:ext cx="${opts.offset.cx}" cy="${opts.offset.cy}"/></p:xfrm>` +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/table">' +
|
||||
`<a:tbl><a:tblPr/><a:tblGrid>${grid}</a:tblGrid>${trs}</a:tbl></a:graphicData></a:graphic></p:graphicFrame>`
|
||||
)
|
||||
}
|
||||
|
||||
// ── Picture insertion (media part surgery) ─────────────────────────────
|
||||
|
||||
const IMAGE_MIME: Record<string, string> = {
|
||||
@@ -304,7 +462,7 @@ export function addPicture(
|
||||
const name = opts.name ?? `Picture ${id}`
|
||||
const descrAttr = opts.descr ? ` descr="${escapeXmlAttr(opts.descr)}"` : ''
|
||||
const xml =
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}"${descrAttr}/>` +
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}"${descrAttr}>${creationIdXml()}</p:cNvPr>` +
|
||||
'<p:cNvPicPr/><p:nvPr/></p:nvPicPr>' +
|
||||
`<p:blipFill><a:blip r:embed="${rid}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
|
||||
`<p:spPr>${generateXfrmXml({ offset: opts.offset, rot: 0, flipH: false, flipV: false })}` +
|
||||
@@ -384,7 +542,7 @@ export function buildGrpSpXml(slide: Slide, bbox: EmuRect, childrenXml: string):
|
||||
`</a:xfrm>`
|
||||
return (
|
||||
`<p:grpSp>` +
|
||||
`<p:nvGrpSpPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}"/>` +
|
||||
`<p:nvGrpSpPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}">${creationIdXml()}</p:cNvPr>` +
|
||||
`<p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>` +
|
||||
`<p:grpSpPr>${grpXfrm}</p:grpSpPr>` +
|
||||
childrenXml +
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
*/
|
||||
import { deflateSync } from 'node:zlib'
|
||||
import type { EmuRect, Slide } from './types'
|
||||
import { escapeXmlAttr } from './xml-utils'
|
||||
import { creationIdXml, escapeXmlAttr } from './xml-utils'
|
||||
import { relsPathFor } from './zip'
|
||||
import { appendRawElements, type OpenedPptx } from './index'
|
||||
import { nextCNvPrId } from './insert'
|
||||
@@ -101,7 +101,10 @@ function ensureDefaultContentType(opened: OpenedPptx, ext: string, mime: string)
|
||||
const ct = opened.archive.readText(ctPath)
|
||||
if (ct && !new RegExp(`<Default Extension="${ext}"`).test(ct)) {
|
||||
const dflt = `<Default Extension="${ext}" ContentType="${mime}"/>`
|
||||
opened.archive.entries.set(ctPath, Buffer.from(ct.replace('</Types>', `${dflt}</Types>`), 'utf8'))
|
||||
opened.archive.entries.set(
|
||||
ctPath,
|
||||
Buffer.from(ct.replace('</Types>', `${dflt}</Types>`), 'utf8'),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,7 +203,7 @@ export function addMedia(
|
||||
const fileTag = opts.kind === 'video' ? 'a:videoFile' : 'a:audioFile'
|
||||
const o = opts.offset
|
||||
const xml =
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}"/>` +
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}">${creationIdXml()}</p:cNvPr>` +
|
||||
'<p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr>' +
|
||||
`<p:nvPr><${fileTag} xmlns:r="${R_NS}" r:link="${ridLegacy}"/>` +
|
||||
`<p:extLst><p:ext uri="${MEDIA_EXT_URI}">` +
|
||||
@@ -262,7 +265,7 @@ export function addModel3d(
|
||||
const name = opts.name ?? `3D Model ${id}`
|
||||
const o = opts.offset
|
||||
const xml =
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}" descr="${escapeXmlAttr(`aislides-3d:${modelPath}`)}"/>` +
|
||||
`<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="${escapeXmlAttr(name)}" descr="${escapeXmlAttr(`aislides-3d:${modelPath}`)}">${creationIdXml()}</p:cNvPr>` +
|
||||
'<p:cNvPicPr/><p:nvPr/></p:nvPicPr>' +
|
||||
`<p:blipFill><a:blip r:embed="${ridPoster}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
|
||||
`<p:spPr><a:xfrm><a:off x="${o.x}" y="${o.y}"/><a:ext cx="${o.cx}" cy="${o.cy}"/></a:xfrm>` +
|
||||
|
||||
@@ -499,6 +499,16 @@ function parseStroke(
|
||||
const capMap: Record<string, Stroke['cap']> = { flat: 'flat', rnd: 'round', sq: 'square' }
|
||||
const dash = ln['a:prstDash']?.['@_val']
|
||||
const cap = ln['@_cap'] ? capMap[ln['@_cap']] : undefined
|
||||
const cmpdMap: Record<string, Stroke['compound']> = {
|
||||
sng: 'sng',
|
||||
dbl: 'dbl',
|
||||
thickThin: 'thickThin',
|
||||
thinThick: 'thinThick',
|
||||
tri: 'tri',
|
||||
}
|
||||
const compound = ln['@_cmpd'] ? cmpdMap[ln['@_cmpd']] : undefined
|
||||
const join: Stroke['join'] =
|
||||
'a:round' in ln ? 'round' : 'a:bevel' in ln ? 'bevel' : 'a:miter' in ln ? 'miter' : undefined
|
||||
const headEnd = parseArrowEnd(ln['a:headEnd'])
|
||||
const tailEnd = parseArrowEnd(ln['a:tailEnd'])
|
||||
return {
|
||||
@@ -506,6 +516,8 @@ function parseStroke(
|
||||
width: intOr(ln['@_w'], 12700),
|
||||
...(dash ? { dash: String(dash) } : {}),
|
||||
...(cap ? { cap } : {}),
|
||||
...(join ? { join } : {}),
|
||||
...(compound && compound !== 'sng' ? { compound } : {}),
|
||||
...(headEnd ? { headEnd } : {}),
|
||||
...(tailEnd ? { tailEnd } : {}),
|
||||
}
|
||||
@@ -871,6 +883,7 @@ function parsePicture(node: any, anchor: ByteAnchor, ctx: ParseContext): Picture
|
||||
const fill = parseFill(spPr, ctx)
|
||||
const duotone = parseDuotone(blip, ctx)
|
||||
const clrChange = parseClrChange(blip, ctx)
|
||||
const lum = parseLum(blip)
|
||||
// Audio/video: a:videoFile/a:audioFile under p:nvPr; blipFill is the poster frame
|
||||
const nvPr = node['p:nvPicPr']?.['p:nvPr']
|
||||
const avNode = nvPr?.['a:videoFile'] ?? nvPr?.['a:audioFile']
|
||||
@@ -902,6 +915,7 @@ function parsePicture(node: any, anchor: ByteAnchor, ctx: ParseContext): Picture
|
||||
...(fill ? { fill } : {}),
|
||||
...(duotone ? { duotone } : {}),
|
||||
...(clrChange ? { clrChange } : {}),
|
||||
...(lum ? { lum } : {}),
|
||||
...(stroke ? { stroke } : {}),
|
||||
...(shadow ? { shadow } : {}),
|
||||
...(glow ? { glow } : {}),
|
||||
@@ -2604,6 +2618,7 @@ function parseTable(
|
||||
rowHeights,
|
||||
rows,
|
||||
styleFlags: { firstRow: flags.firstRow, bandRow: flags.bandRow },
|
||||
...(tblPr['@_rtl'] === '1' || tblPr['@_rtl'] === 'true' ? { rtl: true } : {}),
|
||||
...(bgFill && bgFill.type !== 'none' ? { bgFill } : {}),
|
||||
}
|
||||
}
|
||||
@@ -2645,10 +2660,12 @@ function parseTableCell(
|
||||
cell.text = text
|
||||
}
|
||||
|
||||
// Fill: explicit tcPr fill > table-style region fill
|
||||
// Fill: explicit tcPr fill > table-style region fill; an explicit <a:noFill/> means
|
||||
// transparent and still overrides the style fill (only an absent fill falls through)
|
||||
const fill = parseFill(tcPr, ctx)
|
||||
if (fill && fill.type !== 'none') cell.fill = fill
|
||||
else if (part?.fill) cell.fill = part.fill
|
||||
if (fill) {
|
||||
if (fill.type !== 'none') cell.fill = fill
|
||||
} else if (part?.fill) cell.fill = part.fill
|
||||
|
||||
// Borders on four edges: a:lnL/R/T/B share a:ln's structure, so reuse parseStroke; style inside-borders as fallback
|
||||
const borders: TableCellBorders = {}
|
||||
@@ -2714,6 +2731,19 @@ function parseXfrm(xfrm: any): Transform {
|
||||
|
||||
// ── Fill ─────────────────────────────────────────────────────────────
|
||||
|
||||
/** <a:lum bright/contrast>: legacy picture brightness/contrast (attribute per-100k -> -1..1). */
|
||||
function parseLum(blipNode: any): { bright: number; contrast: number } | undefined {
|
||||
const lum = blipNode?.['a:lum']
|
||||
if (lum === undefined) return undefined
|
||||
const attrs = lum && typeof lum === 'object' ? lum : {}
|
||||
const pct = (v: unknown) =>
|
||||
Math.max(-1, Math.min(1, (v != null ? parseInt(String(v), 10) || 0 : 0) / 100000))
|
||||
const bright = pct(attrs['@_bright'])
|
||||
const contrast = pct(attrs['@_contrast'])
|
||||
if (!bright && !contrast) return undefined
|
||||
return { bright, contrast }
|
||||
}
|
||||
|
||||
/** <a:duotone>: two colors mapping image luminance dark→light (theme texture backgrounds). */
|
||||
function parseDuotone(blipNode: any, ctx: ParseContext): [string, string] | undefined {
|
||||
const duoRaw = blipNode?.['a:duotone']
|
||||
@@ -2780,6 +2810,7 @@ function parseFill(spPr: any, ctx: ParseContext): Fill | undefined {
|
||||
alphaAmt != null ? Math.max(0, Math.min(1, parseInt(alphaAmt, 10) / 100000)) : undefined
|
||||
const duotone = parseDuotone(blip['a:blip'], ctx)
|
||||
const clrChange = parseClrChange(blip['a:blip'], ctx)
|
||||
const lum = parseLum(blip['a:blip'])
|
||||
const fr = blip['a:stretch']?.['a:fillRect']
|
||||
const pct = (v: unknown) => (v != null ? (parseInt(String(v), 10) || 0) / 100000 : 0)
|
||||
const fillRect =
|
||||
@@ -2807,6 +2838,7 @@ function parseFill(spPr: any, ctx: ParseContext): Fill | undefined {
|
||||
...(fillRect ? { fillRect } : {}),
|
||||
...(duotone ? { duotone } : {}),
|
||||
...(clrChange ? { clrChange } : {}),
|
||||
...(lum ? { lum } : {}),
|
||||
...(tile ? { tile } : {}),
|
||||
}
|
||||
}
|
||||
@@ -3117,10 +3149,19 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
|
||||
const latin = resolveFontRef(rPr['a:latin']?.['@_typeface'], ctx.theme) ?? dflt?.latinFont
|
||||
const ea = resolveFontRef(rPr['a:ea']?.['@_typeface'], ctx.theme) ?? dflt?.eaFont
|
||||
const cs = resolveFontRef(rPr['a:cs']?.['@_typeface'], ctx.theme) ?? dflt?.csFont
|
||||
const sym = resolveFontRef(rPr['a:sym']?.['@_typeface'], ctx.theme)
|
||||
// Symbol-slot characters (Wingdings dots/checkmarks stored as U+F0xx PUA) draw with a:sym,
|
||||
// not the latin font; applied when the run is entirely PUA (the common single-glyph case)
|
||||
const puaOnly =
|
||||
sym != null && /^[\uf000-\uf0ff]+$/.test(text.replace(/\s+/g, '')) && !!text.trim()
|
||||
// Pick the bucket by script: complex script → a:cs, CJK → a:ea, otherwise → a:latin; fall back through buckets when missing
|
||||
const fontFamily =
|
||||
(CS_RE.test(text) ? (cs ?? latin ?? ea) : CJK_RE.test(text) ? (ea ?? latin) : (latin ?? ea)) ??
|
||||
ctx.theme?.minorFont
|
||||
const fontFamily = puaOnly
|
||||
? sym
|
||||
: ((CS_RE.test(text)
|
||||
? (cs ?? latin ?? ea)
|
||||
: CJK_RE.test(text)
|
||||
? (ea ?? latin)
|
||||
: (latin ?? ea)) ?? ctx.theme?.minorFont)
|
||||
const bAttr = rPr['@_b']
|
||||
const iAttr = rPr['@_i']
|
||||
// Text outline <a:rPr><a:ln> (WordArt): only solid-color outlines are modeled, kept by the rebuild path
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* hierarchy / pyramid / matrix / venn.
|
||||
*/
|
||||
import type { EmuRect, Slide } from './types'
|
||||
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
|
||||
import { creationIdXml, escapeXmlAttr, escapeXmlText } from './xml-utils'
|
||||
import { appendRawElements, type OpenedPptx } from './index'
|
||||
import { nextCNvPrId } from './insert'
|
||||
import { layoutShapes, type SmartArtChildShape, type SmartArtLayout } from './smartart-layout'
|
||||
@@ -49,7 +49,7 @@ export function buildSmartArtXml(slide: Slide, opts: NewSmartArtOptions): string
|
||||
const shapes = layoutShapes(opts.layout, opts.items, o.cx, o.cy)
|
||||
const children = shapes.map((s, i) => childSpXml(baseId + 1 + i, s)).join('')
|
||||
return (
|
||||
`<p:grpSp><p:nvGrpSpPr><p:cNvPr id="${baseId}" name="SmartArt ${baseId}"/>` +
|
||||
`<p:grpSp><p:nvGrpSpPr><p:cNvPr id="${baseId}" name="SmartArt ${baseId}">${creationIdXml()}</p:cNvPr>` +
|
||||
'<p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
|
||||
`<p:grpSpPr><a:xfrm><a:off x="${o.x}" y="${o.y}"/><a:ext cx="${o.cx}" cy="${o.cy}"/>` +
|
||||
`<a:chOff x="0" y="0"/><a:chExt cx="${o.cx}" cy="${o.cy}"/></a:xfrm></p:grpSpPr>` +
|
||||
|
||||
@@ -68,6 +68,8 @@ export type Fill =
|
||||
duotone?: [string, string]
|
||||
/** <a:blip><a:clrChange>: pixels matching `from` are replaced with `to` (#RRGGBB or #RRGGBBAA; alpha 0 = color-to-transparent) */
|
||||
clrChange?: { from: string; to: string }
|
||||
/** <a:blip><a:lum>: legacy brightness/contrast picture adjustment (-1..1 each) */
|
||||
lum?: { bright: number; contrast: number }
|
||||
/** <a:tile>: offsets (EMU), scale fractions and anchor alignment of the tile grid */
|
||||
tile?: { tx: number; ty: number; sx: number; sy: number; algn: string }
|
||||
}
|
||||
@@ -92,6 +94,10 @@ export interface Stroke {
|
||||
width: number
|
||||
dash?: string
|
||||
cap?: 'flat' | 'round' | 'square'
|
||||
/** Line join <a:round>/<a:bevel>/<a:miter> (omitted when absent) */
|
||||
join?: 'round' | 'bevel' | 'miter'
|
||||
/** Compound line type (<a:ln cmpd>, single when absent) */
|
||||
compound?: 'sng' | 'dbl' | 'thickThin' | 'thinThick' | 'tri'
|
||||
/** Line head decoration <a:headEnd> (omitted when absent or none) */
|
||||
headEnd?: ArrowEnd
|
||||
/** Line tail decoration <a:tailEnd> (omitted when absent or none) */
|
||||
@@ -193,6 +199,8 @@ 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) */
|
||||
rtl?: boolean
|
||||
/** Indent level (bullet level) */
|
||||
level?: number
|
||||
/** Line spacing (%, 100 = single) or absolute (pt, via lineExact) */
|
||||
@@ -426,6 +434,8 @@ export interface PictureElement extends ElementBase {
|
||||
duotone?: [string, string]
|
||||
/** <a:blip><a:clrChange> on the picture blip */
|
||||
clrChange?: { from: string; to: string }
|
||||
/** <a:blip><a:lum> brightness/contrast on the picture blip (-1..1 each) */
|
||||
lum?: { bright: number; contrast: number }
|
||||
stroke?: Stroke
|
||||
shadow?: ShadowEffect
|
||||
glow?: GlowEffect
|
||||
@@ -488,6 +498,8 @@ export interface TableElement extends ElementBase {
|
||||
rows: TableCell[][]
|
||||
/** tblPr's header-row/banded-rows toggles (echoed in the Ribbon's "Table Design") */
|
||||
styleFlags?: { firstRow: boolean; bandRow: boolean }
|
||||
/** tblPr rtl="1": PowerPoint mirrors the grid horizontally (logical column 1 renders rightmost) */
|
||||
rtl?: boolean
|
||||
/** Table-style <a:tblBg>: drawn under the cells (alpha band fills composite over it) */
|
||||
bgFill?: Fill
|
||||
}
|
||||
|
||||
@@ -26,3 +26,21 @@ export function escapeXmlText(text: string): string {
|
||||
export function escapeXmlAttr(text: string): string {
|
||||
return escapeXmlText(text).replace(/"/g, '"')
|
||||
}
|
||||
|
||||
/**
|
||||
* a16:creationId extLst for a newborn <p:cNvPr> — durable identity from birth
|
||||
* (design step 0): the GUID is written into the file bytes, so ids survive
|
||||
* save→reopen, reparse, group/ungroup, and editors that renumber cNvPr ids.
|
||||
* The a16 namespace is declared inline so the fragment is valid standalone.
|
||||
*/
|
||||
export function creationIdExtXml(): string {
|
||||
return (
|
||||
'<a:ext uri="{FF2B5EF4-FFF2-40B4-BE49-F238E27FC236}">' +
|
||||
`<a16:creationId xmlns:a16="http://schemas.microsoft.com/office/drawing/2014/main" id="{${globalThis.crypto.randomUUID().toUpperCase()}}"/>` +
|
||||
'</a:ext>'
|
||||
)
|
||||
}
|
||||
|
||||
export function creationIdXml(): string {
|
||||
return `<a:extLst>${creationIdExtXml()}</a:extLst>`
|
||||
}
|
||||
|
||||
@@ -155,9 +155,9 @@ describe('editTableCellText', () => {
|
||||
const slide = r.slide
|
||||
const tblId = r.elementId
|
||||
|
||||
expect(editTableCellText(slide, tblId, 0, 1, [{ runs: [{ text: 'Header B', bold: true }] }])).toBe(
|
||||
true,
|
||||
)
|
||||
expect(
|
||||
editTableCellText(slide, tblId, 0, 1, [{ runs: [{ text: 'Header B', bold: true }] }]),
|
||||
).toBe(true)
|
||||
expect(editTableCellText(slide, tblId, 1, 0, [{ runs: [{ text: 'data' }] }])).toBe(true)
|
||||
// Out of range rejected
|
||||
expect(editTableCellText(slide, tblId, 5, 0, [{ runs: [{ text: 'x' }] }])).toBe(false)
|
||||
@@ -244,6 +244,21 @@ describe('table structure ops', () => {
|
||||
expect(tbl2.colWidths[0]).toBe(w0 * 2)
|
||||
expect(tbl2.transform.offset.cx).toBe(w0 * 2 + tbl2.colWidths[1]!)
|
||||
})
|
||||
|
||||
it('rtl table: growing a column shifts the origin left (visual-right edge anchored)', async () => {
|
||||
const opened = await openPptx(fx('01_standard_business.pptx'))
|
||||
const { slide, elementId } = addTable(opened, 0, { rows: 2, cols: 2, offset: { ...TBL_OFF } })!
|
||||
const tbl = slide.elements.find((e) => e.id === elementId) as TableElement
|
||||
tbl.anchor.originalXml = tbl.anchor.originalXml.replace('<a:tblPr', '<a:tblPr rtl="1"')
|
||||
tbl.rtl = true
|
||||
const w0 = tbl.colWidths[0]!
|
||||
const x0 = tbl.transform.offset.x
|
||||
|
||||
expect(setTableColWidth(slide, elementId, 0, w0 + 91440)).toBe(true)
|
||||
expect(tbl.transform.offset.x).toBe(x0 - 91440)
|
||||
expect(tbl.transform.offset.cx).toBe(w0 + 91440 + tbl.colWidths[1]!)
|
||||
expect(tbl.anchor.originalXml).toContain(`x="${x0 - 91440}"`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('deleteSlide', () => {
|
||||
|
||||
@@ -261,4 +261,36 @@ describe('group child format operations (font/fill/stroke)', () => {
|
||||
expect(grp.anchor.originalXml).toContain('typeface="Arial"')
|
||||
expect(grp.anchor.originalXml).toContain('sz="3000"')
|
||||
})
|
||||
|
||||
it('setGroupChildShapePresetGeometry: swaps only the target slice, model kept in sync', async () => {
|
||||
const { setGroupChildShapePresetGeometry } = await import('../src/index')
|
||||
const { slide, grp } = mk()
|
||||
expect(setGroupChildShapePresetGeometry(slide, 'grp1', 'c4', 'star5')).toBe(true)
|
||||
const slices = grp.anchor.originalXml.split('<p:sp>')
|
||||
expect(slices[1]).toContain('<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>')
|
||||
expect(slices[2]).toContain('<a:prstGeom prst="star5"><a:avLst/></a:prstGeom>')
|
||||
expect((grp.children[1] as any).presetGeometry).toBe('star5')
|
||||
expect((grp.children[1] as any).adjust).toBeUndefined()
|
||||
expect(slide.structureDirty).toBe(true)
|
||||
})
|
||||
|
||||
it('setGroupChildShapeAdjustValues: swaps only the target slice avLst, model kept in sync', async () => {
|
||||
const { setGroupChildShapeAdjustValues } = await import('../src/index')
|
||||
const { slide, grp } = mk()
|
||||
expect(setGroupChildShapeAdjustValues(slide, 'grp1', 'c4', { adj: 25000 })).toBe(true)
|
||||
const slices = grp.anchor.originalXml.split('<p:sp>')
|
||||
expect(slices[1]).toContain('<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>')
|
||||
expect(slices[2]).toContain('<a:avLst><a:gd name="adj" fmla="val 25000"/></a:avLst>')
|
||||
expect((grp.children[1] as any).adjust).toEqual({ adj: 25000 })
|
||||
expect(slide.structureDirty).toBe(true)
|
||||
})
|
||||
|
||||
it('setGroupChildShapePresetGeometry: rejects unknown child, bad prst, and non-shape children', async () => {
|
||||
const { setGroupChildShapePresetGeometry } = await import('../src/index')
|
||||
const { slide, grp } = mk()
|
||||
expect(setGroupChildShapePresetGeometry(slide, 'grp1', 'nope', 'star5')).toBe(false)
|
||||
expect(setGroupChildShapePresetGeometry(slide, 'grp1', 'c4', 'star5"><hack/>')).toBe(false)
|
||||
;(grp.children[1] as any).type = 'picture'
|
||||
expect(setGroupChildShapePresetGeometry(slide, 'grp1', 'c4', 'star5')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -621,9 +621,11 @@ describe('setElementLink / getElementLink', () => {
|
||||
kind: 'ellipse',
|
||||
offset: { ...OFF, x: 5486400 },
|
||||
})
|
||||
// Newborn cNvPr carries a creationId extLst (paired tag); hlinkClick goes
|
||||
// right after the opening tag — its schema slot is before extLst
|
||||
sharer.anchor.originalXml = sharer.anchor.originalXml.replace(
|
||||
/<p:cNvPr([^>]*)\/>/,
|
||||
`<p:cNvPr$1><a:hlinkClick r:id="${oldRid}"/></p:cNvPr>`,
|
||||
/(<p:cNvPr[^>]*>)/,
|
||||
`$1<a:hlinkClick r:id="${oldRid}"/>`,
|
||||
)
|
||||
linkedSlide.structureDirty = true
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
/** pdf2pptx P25 insertion extensions: bodyPr overrides, rtl paragraphs, grid tables. */
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
addElement,
|
||||
appendRawElements,
|
||||
buildTableGridXml,
|
||||
createBlankPptx,
|
||||
openPptx,
|
||||
savePptx,
|
||||
type NewTableGridOptions,
|
||||
} from '../src/index'
|
||||
|
||||
const OFF = { x: 914400, y: 914400, cx: 3657600, cy: 1828800 }
|
||||
|
||||
describe('bodyPr overrides on generated text boxes', () => {
|
||||
it('writes insets/anchor/wrap and round-trips through save', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, {
|
||||
kind: 'textbox',
|
||||
offset: { ...OFF },
|
||||
paragraphs: [{ runs: [{ text: 'measured box' }] }],
|
||||
bodyPr: { wrap: 'square', anchor: 't', insetsEmu: { l: 0, t: 0, r: 0, b: 0 } },
|
||||
})
|
||||
expect(el.anchor.originalXml).toContain(
|
||||
'<a:bodyPr wrap="square" rtlCol="0" lIns="0" tIns="0" rIns="0" bIns="0" anchor="t"/>',
|
||||
)
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const el2: any = reopened.deck.slides[0]!.elements.at(-1)
|
||||
expect(el2.text.body?.insets ?? el2.text.insets ?? { l: 0, t: 0, r: 0, b: 0 }).toBeTruthy()
|
||||
expect(el2.anchor.originalXml).toContain('lIns="0"')
|
||||
})
|
||||
|
||||
it('default stays the historical bodyPr', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const el = addElement(opened.deck.slides[0]!, { kind: 'textbox', offset: { ...OFF } })
|
||||
expect(el.anchor.originalXml).toContain('<a:bodyPr wrap="square" rtlCol="0"/>')
|
||||
})
|
||||
|
||||
it('rtl paragraphs emit a:pPr rtl="1"', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const el = addElement(opened.deck.slides[0]!, {
|
||||
kind: 'textbox',
|
||||
offset: { ...OFF },
|
||||
paragraphs: [{ runs: [{ text: 'שלום' }], align: 'right', rtl: true }],
|
||||
})
|
||||
expect(el.anchor.originalXml).toContain('rtl="1"')
|
||||
expect(el.anchor.originalXml).toContain('algn="r"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildTableGridXml', () => {
|
||||
const spec = (over: Partial<NewTableGridOptions> = {}): NewTableGridOptions => ({
|
||||
offset: { x: 0, y: 0, cx: 3000000, cy: 2000000 },
|
||||
colWidthsEmu: [1000000, 1200000, 800000],
|
||||
rowHeightsEmu: [1000000, 1000000],
|
||||
cells: [
|
||||
[
|
||||
{ paragraphs: [{ runs: [{ text: 'A1' }] }], gridSpan: 2, fillColor: '#DDEEFF' },
|
||||
{ hMerge: true },
|
||||
{ paragraphs: [{ runs: [{ text: 'C1' }] }], rowSpan: 2, anchor: 'ctr' },
|
||||
],
|
||||
[
|
||||
{ paragraphs: [{ runs: [{ text: 'A2' }] }] },
|
||||
{ paragraphs: [{ runs: [{ text: 'B2' }] }] },
|
||||
{ vMerge: true },
|
||||
],
|
||||
],
|
||||
border: { color: '#333333', widthEmu: 9525 },
|
||||
...over,
|
||||
})
|
||||
|
||||
it('writes explicit grid, merges, shading and borders', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const xml = buildTableGridXml(opened.deck.slides[0]!, spec())
|
||||
expect(xml).toContain('<a:gridCol w="1000000"/><a:gridCol w="1200000"/><a:gridCol w="800000"/>')
|
||||
expect(xml).toContain('gridSpan="2"')
|
||||
expect(xml).toContain('<a:tc hMerge="1">')
|
||||
expect(xml).toContain('rowSpan="2"')
|
||||
expect(xml).toContain('<a:tc vMerge="1">')
|
||||
expect(xml).toContain('anchor="ctr"')
|
||||
expect(xml).toContain('<a:srgbClr val="DDEEFF"/>')
|
||||
expect(xml).toContain('<a:lnL w="9525" cap="flat">')
|
||||
expect(xml).toContain('<a:tblPr/>')
|
||||
// every row lists one tc per grid column
|
||||
const rows = xml.match(/<a:tr /g)
|
||||
expect(rows?.length).toBe(2)
|
||||
expect((xml.match(/<a:tc[\s>]/g) ?? []).length).toBe(6)
|
||||
})
|
||||
|
||||
it('insideV scope only rules verticals between columns', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const xml = buildTableGridXml(
|
||||
opened.deck.slides[0]!,
|
||||
spec({ border: { color: '#000000', widthEmu: 12700, scope: 'insideV' } }),
|
||||
)
|
||||
expect(xml).toContain('<a:lnL')
|
||||
expect(xml).not.toContain('<a:lnT')
|
||||
expect(xml).not.toContain('<a:lnR')
|
||||
})
|
||||
|
||||
it('inserted grid table survives save → reopen with cell text', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const xml = buildTableGridXml(opened.deck.slides[0]!, spec())
|
||||
const r = appendRawElements(opened, 0, [xml])
|
||||
expect(r).not.toBeNull()
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const table: any = reopened.deck.slides[0]!.elements.find((e: any) => e.type === 'table')
|
||||
expect(table).toBeTruthy()
|
||||
const texts = JSON.stringify(table)
|
||||
expect(texts).toContain('A1')
|
||||
expect(texts).toContain('B2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('translucent shape fills', () => {
|
||||
it('#RRGGBBAA emits an a:alpha child; opaque stays plain', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const el = addElement(opened.deck.slides[0]!, {
|
||||
kind: 'rect',
|
||||
offset: { ...OFF },
|
||||
fillColor: '#000000CC',
|
||||
})
|
||||
expect(el.anchor.originalXml).toContain(
|
||||
'<a:srgbClr val="000000"><a:alpha val="80000"/></a:srgbClr>',
|
||||
)
|
||||
const el2 = addElement(opened.deck.slides[0]!, {
|
||||
kind: 'rect',
|
||||
offset: { ...OFF },
|
||||
fillColor: '#112233',
|
||||
})
|
||||
expect(el2.anchor.originalXml).toContain('<a:srgbClr val="112233"/>')
|
||||
})
|
||||
})
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
resetSlideBackground,
|
||||
setSlideBackground,
|
||||
setShapePresetGeometry,
|
||||
setShapeAdjustValues,
|
||||
setSlideBackgroundImage,
|
||||
setSlideBgGraphicsHidden,
|
||||
} from '../src/index'
|
||||
@@ -430,3 +431,45 @@ describe('setShapePresetGeometry (change shape)', () => {
|
||||
expect(setShapePresetGeometry(slide, el.id, 'star5"><hack/>')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setShapeAdjustValues (adjust handles)', () => {
|
||||
it('writes the avLst, updates the model, and round-trips', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, { kind: 'roundRect', offset: { ...OFF } })
|
||||
|
||||
expect(setShapeAdjustValues(slide, el.id, { adj: 33333 })).toBe(true)
|
||||
expect((el as TextElement).adjust).toEqual({ adj: 33333 })
|
||||
expect(el.anchor.originalXml).toContain(
|
||||
'<a:avLst><a:gd name="adj" fmla="val 33333"/></a:avLst>',
|
||||
)
|
||||
|
||||
const reopened = await openPptx(await savePptx(opened))
|
||||
const saved = reopened.deck.slides[0]!.elements.at(-1) as TextElement
|
||||
expect(saved.adjust).toEqual({ adj: 33333 })
|
||||
expect(saved.presetGeometry).toBe('roundRect')
|
||||
})
|
||||
|
||||
it('replaces an existing avLst and supports multiple values', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, { kind: 'roundRect', offset: { ...OFF } })
|
||||
setShapeAdjustValues(slide, el.id, { adj: 10000 })
|
||||
expect(setShapeAdjustValues(slide, el.id, { adj1: 12000, adj2: 4000 })).toBe(true)
|
||||
const xml = el.anchor.originalXml
|
||||
expect(xml).not.toContain('val 10000')
|
||||
expect(xml).toContain('<a:gd name="adj1" fmla="val 12000"/>')
|
||||
expect(xml).toContain('<a:gd name="adj2" fmla="val 4000"/>')
|
||||
expect(xml.match(/<a:avLst>/g)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('rejects unknown ids, unsafe names, and non-finite values', async () => {
|
||||
const opened = await openPptx(await createBlankPptx())
|
||||
const slide = opened.deck.slides[0]!
|
||||
const el = addElement(slide, { kind: 'roundRect', offset: { ...OFF } })
|
||||
expect(setShapeAdjustValues(slide, 'nope', { adj: 1 })).toBe(false)
|
||||
expect(setShapeAdjustValues(slide, el.id, { 'adj"><hack/>': 1 })).toBe(false)
|
||||
expect(setShapeAdjustValues(slide, el.id, { adj: Number.NaN })).toBe(false)
|
||||
expect(setShapeAdjustValues(slide, el.id, {})).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -90,3 +90,32 @@ describe('a:grayscl (tdf112209 grayscale picture fill)', () => {
|
||||
expect(el.duotone).toEqual(['#112233', '#AABBCC'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('p:pic blip lum brightness/contrast (prod_048 washed-out photo box)', () => {
|
||||
it('parses a:lum on a pic blip', () => {
|
||||
const xml = slideWith(pic('<a:lum bright="70000" contrast="-70000"/>'))
|
||||
const slide = parseSlide({ path: 'ppt/slides/slide1.xml', slideXml: xml, ctx: {} })
|
||||
const el = slide.elements[0] as any
|
||||
expect(el.lum).toEqual({ bright: 0.7, contrast: -0.7 })
|
||||
})
|
||||
|
||||
it('parses a:lum on a shape blipFill and omits a no-op lum', () => {
|
||||
const sp = (lum: string) =>
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="2" name="S"/></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm><a:prstGeom prst="rect"/>' +
|
||||
`<a:blipFill><a:blip r:embed="rId2">${lum}</a:blip><a:stretch><a:fillRect/></a:stretch></a:blipFill></p:spPr></p:sp>`
|
||||
const ctx = { mediaRels: new Map([['rId2', 'ppt/media/image1.png']]) }
|
||||
const one = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(sp('<a:lum bright="40000"/>')),
|
||||
ctx,
|
||||
}).elements[0] as any
|
||||
expect(one.fill.lum).toEqual({ bright: 0.4, contrast: 0 })
|
||||
const none = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(sp('<a:lum/>')),
|
||||
ctx,
|
||||
}).elements[0] as any
|
||||
expect(none.fill.lum).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSlide } from '../src/parse'
|
||||
|
||||
const slideWith = (bodyShapes: string) =>
|
||||
'<?xml version="1.0"?><p:sld xmlns:p="p" xmlns:a="a" xmlns:r="r"><p:cSld>' +
|
||||
`<p:spTree><p:nvGrpSpPr/><p:grpSpPr/>${bodyShapes}</p:spTree></p:cSld></p:sld>`
|
||||
|
||||
const sp = (rPr: string, text: string) =>
|
||||
'<p:sp><p:nvSpPr><p:cNvPr id="5" name="TextBox 4"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>' +
|
||||
'<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm></p:spPr>' +
|
||||
`<p:txBody><a:bodyPr/><a:p><a:r><a:rPr lang="en-US">${rPr}</a:rPr><a:t>${text}</a:t></a:r></a:p></p:txBody></p:sp>`
|
||||
|
||||
const FONTS =
|
||||
'<a:latin typeface="Sakkal Majalla"/><a:cs typeface="Sakkal Majalla"/><a:sym typeface="Wingdings 2"/>'
|
||||
|
||||
describe('a:sym font slot (prod_068 Wingdings status dots)', () => {
|
||||
it('a PUA-only run draws with the sym typeface', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(sp(FONTS, '')),
|
||||
ctx: {},
|
||||
})
|
||||
const run = (slide.elements[0] as any).text.paragraphs[0].runs[0]
|
||||
expect(run.fontFamily).toBe('Wingdings 2')
|
||||
})
|
||||
|
||||
it('a plain-text run keeps the latin typeface even with a:sym present', () => {
|
||||
const slide = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: slideWith(sp(FONTS, 'hello')),
|
||||
ctx: {},
|
||||
})
|
||||
const run = (slide.elements[0] as any).text.paragraphs[0].runs[0]
|
||||
expect(run.fontFamily).toBe('Sakkal Majalla')
|
||||
})
|
||||
})
|
||||
@@ -68,6 +68,31 @@ describe('built-in table style Medium Style 2 (PowerPoint default)', () => {
|
||||
expect(run.bold).toBe(false)
|
||||
expect(run.color).toBe('#000000')
|
||||
})
|
||||
|
||||
it('explicit <a:noFill/> on tcPr overrides the style fill (cell stays transparent)', () => {
|
||||
const slide2 = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: tableSlideXml('firstRow="1" bandRow="1"', MEDIUM2_A1).replace(
|
||||
/<a:tcPr\/>/,
|
||||
'<a:tcPr><a:noFill/></a:tcPr>',
|
||||
),
|
||||
ctx: { theme },
|
||||
})
|
||||
const t2 = slide2.elements[0] as any
|
||||
expect(t2.rows[0][0].fill).toBeUndefined()
|
||||
// Remaining cells keep the style fill
|
||||
expect(t2.rows[0][1].fill).toEqual({ type: 'solid', color: '#4472C4' })
|
||||
})
|
||||
|
||||
it('tblPr rtl="1" is parsed onto the table element', () => {
|
||||
const slide2 = parseSlide({
|
||||
path: 'ppt/slides/slide1.xml',
|
||||
slideXml: tableSlideXml('rtl="1" firstRow="1"', MEDIUM2_A1),
|
||||
ctx: { theme },
|
||||
})
|
||||
expect((slide2.elements[0] as any).rtl).toBe(true)
|
||||
expect((slide.elements[0] as any).rtl).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('tableStyles.xml custom styles', () => {
|
||||
|
||||
Reference in New Issue
Block a user