Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

feat(v0.22): the PPTX limits wave — fonts embed, transitions/animations/SFX carry

Ashiq Hussain Mir9cdd59a02b0e
diff --git a/docs/PPTX-EXPORT.md b/docs/PPTX-EXPORT.md
index be77ebd..e554a21 100644
--- a/docs/PPTX-EXPORT.md
+++ b/docs/PPTX-EXPORT.md
@@ -1,4 +1,4 @@
-# PPTX export — operator guide & decision record (Wave 5, first slice)
+# PPTX export — operator guide & decision record (Wave 5 + the v0.22 limits wave)
The Export dialog's **PPTX** format turns a Canvix design into a real
PowerPoint file: an OOXML package (a zip) written entirely in the
@@ -11,6 +11,12 @@ left after speaker notes and presenter view shipped in v0.18/v0.19:
the deck you present in Canvix can now be handed to PowerPoint,
Keynote or Google Slides — speaker notes included.
+**v0.22** closes the three honest-limits gaps this guide used to
+carry: fonts now **embed** as `fntdata`, page **transitions** and
+entrance **animations** ride the file's own timing model, and the
+page's **SFX** wire into the transition sound slot. The remaining
+limits are re-listed below.
+
## What exports natively (editable in PowerPoint)
| Canvix element | PPTX mapping |
@@ -24,6 +30,10 @@ Keynote or Google Slides — speaker notes included.
| Fills & effects | solid + linear/radial gradients, strokes, element opacity, soft outer shadows |
| Page background | solid / gradient `p:bg` |
| **Speaker notes** | native notes slides (+ the notes master) — the presenter story continues in the file |
+| **Transitions** (v0.22) | `p:transition` — fade native, slide directional `p:push`, morph → fade (below) |
+| **Entrance animations** (v0.22) | `p:timing` tree — one click group, first element `clickEffect`, the rest `withEffect` at their delays |
+| **Transition SFX** (v0.22) | the page's SFX embedded as `media/sfxN.wav`, wired via `p:sndAc`/`p:stSnd` |
+| **Fonts** (v0.22) | document text faces resolved through the PDF exporter's font ladder, embedded as `fonts/fontN.fntdata` + `embeddedFontLst` |
Rotation is mapped with an origin re-base: Canvix rotates most
element types around the box **top-left** (Konva semantics) while
@@ -48,17 +58,37 @@ level, embedded as PNG):
- curved text, text with effects/backgrounds, shadowed text
- masked or filtered images
-**Text wrapping**: PowerPoint re-wraps text with its own engine, so
-line breaks can differ slightly from the canvas (the box, size,
-alignment and spacing carry over exactly). Fonts are referenced by
-family — not embedded — so opening on a machine without the font
-falls back to that viewer's substitution, the same posture as the
-SVG export.
-
-Animations, transitions and SFX do not carry into PPTX (v1) —
-PowerPoint's animation model is declarative and different enough
-that a faithful mapping is its own project; recorded here so nobody
-has to rediscover it.
+**Text re-wrap safety**: PowerPoint's line engine wraps slightly
+differently than the browser's, so line breaks can differ (the box,
+size, alignment and spacing carry over exactly). Every text body now
+carries a bare `normAutofit` — when PowerPoint's re-wrap overflows
+the shape it **shrinks the text** instead of spilling it out; when
+our engine already auto-fit the text, the measured `fontScale` rides
+along so PowerPoint starts where we left off.
+
+**Fonts** embed through the same ladder the PDF exporter uses
+(`resolveFontFaces`): embedded fonts ride as `fntdata` parts listed in
+`embeddedFontLst`. The ladder can fail (offline, std-14 fallbacks,
+hostile documents) — then the file still references the typefaces by
+family and the viewer substitutes, the pre-v0.22 behaviour. A
+`fontsEmbedded: 0` in the export result is the honest signal.
+
+### Animations & transitions — the honest mapping (v0.22)
+
+Our present-mode semantics (one advance, then the sequence plays
+itself) maps to **one click group**: the first animated element is
+the `clickEffect`, the rest fire `withEffect` at their own delays.
+
+| Canvix | PPTX | Notes |
+|---|---|---|
+| fade / rise entrance | Fade entrance (`presetID 10`) | native |
+| pan / wipe entrance | Wipe entrance (`presetID 22`), directional filter | native |
+| zoom / pop entrance | Fade entrance | approximation — hand-built Zoom (`anim-scale`) trees make PowerPoint repair-prompt |
+| rotate / breathe (emphasis/loops) | **dropped** | PowerPoint emphasis is a different model; documented, not silently mangled |
+| slide transition (directional) | `p:push dir` | native |
+| fade transition | `p:fade` | native |
+| morph transition | `p:fade` | nearest universal — PowerPoint's own Morph needs object-matching extensions |
+| page SFX | transition sound (`p:sndAc`) | the offline SFX pack's wav bytes, fetched once per id |
## The package
@@ -73,10 +103,17 @@ ppt/presentation.xml (+ rels) ppt/theme/theme1.xml
ppt/slideMasters/slideMaster1.xml (+ rels)
ppt/slideLayouts/slideLayout1.xml (+ rels)
ppt/slides/slideN.xml (+ rels) ppt/media/imageN.png
+ppt/media/sfxN.wav [per distinct SFX id]
+ppt/fonts/fontN.fntdata [per embedded face, v0.22]
ppt/notesMasters/notesMaster1.xml (+ rels) [when notes exist]
ppt/notesSlides/notesSlideN.xml (+ rels) [per noted page]
```
+Media parts live under `ppt/media/` (the slide rels' `../media/…`
+targets resolve there — v0.22 fixed a placement bug that left parts
+at the package root as broken refs). Slide rels share one id
+namespace across images and sounds (rId1 is always the layout).
+
Slides are 96-dpi px → EMU (`px × 9525`); font sizes px → pt
(`× 0.75`), `sz` in 1/100 pt.
@@ -89,16 +126,23 @@ Slides are 96-dpi px → EMU (`px × 9525`); font sizes px → pt
list, content-type coverage, rels resolution, EMU sizes, XML
escaping (hostile text), the rotation-origin re-base numerically,
per-page letterboxing, node-mode raster skipping and the
- no-pages refusal.
+ no-pages refusal. v0.22 adds: normAutofit presence, transition
+ XML (fade/slide/none + schema position), the timing tree (click
+ group, delays, wipe filters, rotate dropped honestly), SFX
+ embedding (audio rel, wav content-type, bytes in the package),
+ and media-part placement under `ppt/media/`.
- Conversion proof: the suite writes `/tmp/pptx-smoke.pptx`;
`scripts/verify-pptx.sh` converts it with headless LibreOffice
(`soffice --convert-to pdf`) and checks the rendered pixels —
background, shapes and text must all appear. The same file opens
in PowerPoint/Keynote/Google Slides (the LibreOffice Impress
- filter is the strictest widely-available parser).
+ filter is the strictest widely-available parser). A malformed
+ timing tree would repair-prompt instead of converting.
- e2e (`tests/e2e/pptx-export.spec.ts`): export through the dialog,
assert the download, crack the zip with Python's `zipfile`, assert
- the skeleton + the heading text as a native run.
+ the skeleton + the heading text as a native run. The v0.22 case
+ asserts transition + timing + `embeddedFontLst` + `fntdata` parts
+ + media placement, then does the LibreOffice round-trip.
## API surface
diff --git a/scripts/debug-pptx-zip.ts b/scripts/debug-pptx-zip.ts
new file mode 100644
index 0000000..ceb010a
--- /dev/null
+++ b/scripts/debug-pptx-zip.ts
@@ -0,0 +1,42 @@
+// Debug: list zip entries of a generated pptx
+import { exportDesignToPptx } from '../src/lib/pptx-export'
+import { createShapeElement } from '../src/lib/types'
+
+async function main() {
+ const wav = new Uint8Array(128)
+ wav.set([0x52, 0x49, 0x46, 0x46], 0)
+ const rect = createShapeElement('rect', { x: 0, y: 0, width: 100, height: 100, fill: '#FFF' })
+ const r = await exportDesignToPptx({
+ designWidth: 400,
+ designHeight: 300,
+ pages: [
+ {
+ id: 'p',
+ background: { type: 'solid', color: '#FFF' },
+ elements: [rect],
+ transition: { kind: 'fade', duration: 0.5, sfxId: 'whoosh-soft' },
+ } as never,
+ ],
+ sfxIo: { fetchBytes: async () => wav },
+ })
+ const bytes = new Uint8Array(await r.blob.arrayBuffer())
+ const dv = new DataView(bytes.buffer)
+ const dec = new TextDecoder()
+ let eocd = -1
+ for (let i = bytes.length - 22; i >= 0; i--) {
+ if (dv.getUint32(i, true) === 0x06054b50) {
+ eocd = i
+ break
+ }
+ }
+ let p = dv.getUint32(eocd + 16, true)
+ for (let i = 0; i < dv.getUint16(eocd + 10, true); i++) {
+ const nl = dv.getUint16(p + 28, true)
+ const el = dv.getUint16(p + 30, true)
+ const cl = dv.getUint16(p + 32, true)
+ console.log(dec.decode(bytes.subarray(p + 46, p + 46 + nl)))
+ p += 46 + nl + el + cl
+ }
+ process.exit(0)
+}
+main()
diff --git a/scripts/verify-pptx-v022.ts b/scripts/verify-pptx-v022.ts
new file mode 100644
index 0000000..8e679a5
--- /dev/null
+++ b/scripts/verify-pptx-v022.ts
@@ -0,0 +1,51 @@
+// v0.22 round-trip proof: export a deck exercising every new feature
+// (normAutofit text, entrance animations incl. dropped rotate,
+// fade+slide transitions, transition SFX) then verify with Python's
+// zipfile; the caller follows up with `soffice --convert-to pdf`.
+import { exportDesignToPptx } from '../src/lib/pptx-export'
+import { createShapeElement, createTextElement } from '../src/lib/types'
+import type { PageData } from '../src/lib/types'
+import { writeFileSync } from 'node:fs'
+
+function page(elements: PageData['elements'], extra: Partial<PageData> = {}): PageData {
+ return {
+ id: 'p',
+ background: { type: 'solid', color: '#FFFFFF' },
+ elements,
+ ...extra,
+ } as PageData
+}
+
+async function main() {
+ const wav = new Uint8Array(2048)
+ wav.set([0x52, 0x49, 0x46, 0x46, 0xfc, 0x07, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45], 0)
+ // fmt + data chunks so the header is structurally a wav
+ wav.set([0x66, 0x6d, 0x74, 0x20, 16, 0, 0, 0, 1, 0, 1, 0, 0x40, 0x1f, 0, 0, 0, 0x40, 0x1f, 0, 0, 2, 0, 16, 0], 12)
+ wav.set([0x64, 0x61, 0x74, 0x61, 0xf0, 0x07, 0, 0], 36)
+
+ const t1 = createTextElement({ x: 40, y: 40, width: 500, text: 'v0.22 heading', fontSize: 44 })
+ t1.animation = { kind: 'fade', duration: 0.9, delay: 0, easing: 'easeOut' }
+ const t2 = createTextElement({ x: 40, y: 140, width: 500, text: 'wipes in from the left', fontSize: 24 })
+ t2.animation = { kind: 'pan', duration: 0.5, delay: 1.2, easing: 'easeOut', direction: 'left' }
+ const t3 = createTextElement({ x: 40, y: 220, width: 500, text: 'rotate stays home', fontSize: 24 })
+ t3.animation = { kind: 'rotate', duration: 2, delay: 0, easing: 'linear' }
+ const rect = createShapeElement('rect', { x: 40, y: 300, width: 200, height: 120, fill: '#3B82F6' })
+
+ const r = await exportDesignToPptx({
+ designWidth: 800,
+ designHeight: 450,
+ title: 'v0.22 round-trip',
+ pages: [
+ page([t1, t2, t3, rect], { transition: { kind: 'fade', duration: 0.5, sfxId: 'whoosh-soft' } }),
+ page([rect], { transition: { kind: 'slide', duration: 2.0, direction: 'left' } }),
+ ],
+ sfxIo: { fetchBytes: async () => wav },
+ })
+ console.log(
+ `export: pages=${r.pages} natives=${r.natives} transitions=${r.transitions} sounds=${r.sounds} animated=${r.animated} fontsEmbedded=${r.fontsEmbedded}`,
+ )
+ writeFileSync('/tmp/pptx-v022-roundtrip.pptx', new Uint8Array(await r.blob.arrayBuffer()))
+ console.log('wrote /tmp/pptx-v022-roundtrip.pptx')
+}
+
+main()
diff --git a/src/lib/pdf/text-ops.ts b/src/lib/pdf/text-ops.ts
index 9999ec3..e180689 100644
--- a/src/lib/pdf/text-ops.ts
+++ b/src/lib/pdf/text-ops.ts
@@ -271,6 +271,10 @@ export function collectTextFaces(pages: { elements: unknown[] }[]): Map<string,
}
case 'chart': {
const ch = el as ChartElement
+ // defensive: documents from before the series/labels chart
+ // shape (and hostile hand-built ones) have neither — they
+ // contribute no text instead of crashing the face walk
+ if (!ch.series || !ch.labels) return
for (const p of chartPrimitives(ch)) {
if (p.kind === 'text') {
noteText(map, { family: p.family, bold: !!p.bold, italic: false }, p.text)
diff --git a/src/lib/pptx-export.ts b/src/lib/pptx-export.ts
index f4b57d7..ea24c2b 100644
--- a/src/lib/pptx-export.ts
+++ b/src/lib/pptx-export.ts
@@ -19,6 +19,9 @@
import type { PageData } from '@/lib/types'
import { collectImages } from '@/lib/video-export'
+import { resolveFontFaces } from '@/lib/pdf/fonts'
+import { collectTextFaces } from '@/lib/pdf/text-ops'
+import { sfxUrl } from '@/lib/assets/sfx-pack'
import { ZipWriter } from '@/lib/pptx/zip-writer'
import {
appPropsXml,
@@ -36,6 +39,7 @@ import {
slideMasterRelsXml,
slideMasterXml,
themeXml,
+ type EmbeddedFontFace,
} from '@/lib/pptx/parts'
import { mapSlide, type MappedSlide, type PptxMediaBag, type SlideMapContext } from '@/lib/pptx/slide-mapper'
@@ -48,6 +52,9 @@ export interface PptxExportOptions {
/** document title (docProps + PowerPoint's title bar) */
title?: string
onProgress?: (ratio: number, label: string) => void
+ /** v0.22: test seam for the SFX fetch (the fontLadderIo pattern) —
+ * defaults to the browser's same-origin fetch of /sfx/<id>.wav */
+ sfxIo?: { fetchBytes?: (url: string) => Promise<Uint8Array | null> }
}
export interface PptxExportResult {
@@ -60,6 +67,15 @@ export interface PptxExportResult {
rasters: number
/** how many pages carry speaker notes */
notes: number
+ /** v0.22: how many pages carry a transition */
+ transitions: number
+ /** v0.22: how many pages carry the transition SFX bytes */
+ sounds: number
+ /** v0.22: how many elements carry an entrance animation */
+ animated: number
+ /** v0.22: how many font FACES were embedded (0 = ladder failed
+ * or no text — the file still references the typefaces) */
+ fontsEmbedded: number
}
/** The media bag: dedupes sources → part names, holds the bytes. */
@@ -68,10 +84,15 @@ class MediaBag implements PptxMediaBag {
private counter = 0
private images: Map<string, HTMLImageElement>
- constructor(images: Map<string, HTMLImageElement>) {
+ constructor(images: Map<string, HTMLImageElement>, sfxIo?: PptxExportOptions['sfxIo']) {
this.images = images
+ this.sfxIo = sfxIo
}
+ // v0.22: the offline SFX pack — fetched once per id, embedded as wav
+ private sounds = new Map<string, { name: string; bytes: Uint8Array } | null>()
+ private sfxIo?: PptxExportOptions['sfxIo']
+
private async bytesFor(src: string): Promise<Uint8Array | null> {
// JPEG data URLs pass through byte-identical (no re-encode —
// the PDF embedder's DCTDecode posture)
@@ -117,6 +138,38 @@ class MediaBag implements PptxMediaBag {
return name
}
+ async soundPart(id: string): Promise<string | null> {
+ const hit = this.sounds.get(id)
+ if (hit) return hit.name
+ if (hit === null) return null
+ const fetchBytes =
+ this.sfxIo?.fetchBytes ??
+ (async (url: string) => {
+ if (typeof fetch === 'undefined') return null
+ try {
+ const res = await fetch(url, { signal: AbortSignal.timeout(8000) })
+ if (!res.ok) return null
+ return new Uint8Array(await res.arrayBuffer())
+ } catch {
+ return null
+ }
+ })
+ try {
+ const bytes = await fetchBytes(sfxUrl(id))
+ if (!bytes || bytes.length < 64) {
+ this.sounds.set(id, null)
+ return null
+ }
+ const name = `media/sfx${++this.counter}.wav`
+ this.parts.set(`sound:${id}`, { name, bytes })
+ this.sounds.set(id, { name, bytes })
+ return name
+ } catch {
+ this.sounds.set(id, null)
+ return null
+ }
+ }
+
entries(): { name: string; bytes: Uint8Array }[] {
return [...this.parts.values()]
}
@@ -132,7 +185,7 @@ export async function exportDesignToPptx(opts: PptxExportOptions): Promise<PptxE
opts.onProgress?.(0.08, 'Loading images…')
const images = await collectImages(opts.pages)
- const media = new MediaBag(images)
+ const media = new MediaBag(images, opts.sfxIo)
let idCounter = 1
const ctx: SlideMapContext = {
images,
@@ -141,18 +194,54 @@ export async function exportDesignToPptx(opts: PptxExportOptions): Promise<PptxE
nextId: () => ++idCounter,
}
- // 2. map every page (slide + optional notes)
+ // 2. resolve the document's text faces through the SAME collector the
+ // PDF exporter uses (walks text spans, table cells, chart labels,
+ // embed captions — everything the slides will reference), then the
+ // shared font ladder for TTF bytes. Failures degrade silently:
+ // typefaces stay referenced, viewers substitute (the pre-v0.22
+ // behaviour).
+ opts.onProgress?.(0.1, 'Loading fonts…')
+ const faceRequests = [...collectTextFaces(opts.pages).values()].map((n) => n.face)
+ const resolvedFaces = await resolveFontFaces(faceRequests)
+ // family → face slots with TTF bytes only (std14 fallbacks can't embed)
+ const embedded = new Map<string, EmbeddedFontFace>()
+ const fontBytes: { name: string; bytes: Uint8Array }[] = []
+ let fontRelCursor = 0
+ const fontRids = new Map<string, string>()
+ for (const face of resolvedFaces.values()) {
+ if (face.kind !== 'ttf') continue
+ const slot = face.bold && face.italic ? 'bi' : face.bold ? 'bold' : face.italic ? 'italic' : 'regular'
+ let entry = embedded.get(face.family)
+ if (!entry) {
+ entry = { family: face.family, faces: {} }
+ embedded.set(face.family, entry)
+ }
+ if (entry.faces[slot]) continue
+ const rid = `rIdF${++fontRelCursor}`
+ const part = `fonts/font${fontRelCursor}.fntdata`
+ entry.faces[slot] = rid
+ fontRids.set(rid, part)
+ fontBytes.push({ name: `ppt/${part}`, bytes: face.bytes })
+ }
+
+ // 3. map every page (slide + optional notes)
const mapped: MappedSlide[] = []
let natives = 0
let rasters = 0
let notes = 0
+ let transitions = 0
+ let sounds = 0
+ let animated = 0
for (let i = 0; i < n; i++) {
- opts.onProgress?.(0.15 + (0.6 * i) / n, `Rendering slide ${i + 1} of ${n}…`)
+ opts.onProgress?.(0.15 + (0.55 * i) / n, `Rendering slide ${i + 1} of ${n}…`)
const slide = await mapSlide(opts.pages[i], opts.designWidth, opts.designHeight, ctx)
mapped.push(slide)
natives += slide.natives
rasters += slide.rasters
+ animated += slide.animated.length
if (opts.pages[i].notes?.trim()) notes++
+ if (slide.xml.includes('<p:transition')) transitions++
+ if (slide.hasSound) sounds++
}
// 3. assemble the package
@@ -164,12 +253,21 @@ export async function exportDesignToPptx(opts: PptxExportOptions): Promise<PptxE
.map((_, i) => (opts.pages[i].notes?.trim() ? `/ppt/notesSlides/notesSlide${i + 1}.xml` : null))
.filter((p): p is string => !!p)
- await zip.addText('[Content_Types].xml', contentTypesXml(slideParts, notesParts))
+ await zip.addText(
+ '[Content_Types].xml',
+ contentTypesXml(slideParts, notesParts, { fonts: fontBytes.length, sounds }),
+ )
await zip.addText('_rels/.rels', rootRelsXml())
await zip.addText('docProps/core.xml', corePropsXml(opts.title ?? 'Canvix design'))
await zip.addText('docProps/app.xml', appPropsXml(n))
- await zip.addText('ppt/presentation.xml', presentationXml(opts.designWidth, opts.designHeight, n, hasNotesMaster))
- await zip.addText('ppt/_rels/presentation.xml.rels', presentationRelsXml(n, hasNotesMaster))
+ await zip.addText(
+ 'ppt/presentation.xml',
+ presentationXml(opts.designWidth, opts.designHeight, n, hasNotesMaster, [...embedded.values()]),
+ )
+ await zip.addText(
+ 'ppt/_rels/presentation.xml.rels',
+ presentationRelsXml(n, hasNotesMaster, [...fontRids.entries()].map(([rid, part]) => ({ rid, part }))),
+ )
await zip.addText('ppt/theme/theme1.xml', themeXml())
await zip.addText('ppt/slideMasters/slideMaster1.xml', slideMasterXml())
await zip.addText('ppt/slideMasters/_rels/slideMaster1.xml.rels', slideMasterRelsXml())
@@ -183,13 +281,16 @@ export async function exportDesignToPptx(opts: PptxExportOptions): Promise<PptxE
const slide = mapped[i]
await zip.addText(`ppt/slides/slide${i + 1}.xml`, slide.xml)
const rels =
- slide.imageRels.size === 0
+ slide.imageRels.size === 0 && slide.soundRels.size === 0
? `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/></Relationships>`
: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>` +
[...slide.imageRels.entries()]
.map(([rid, part]) => `<Relationship Id="${rid}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../${part}"/>`)
.join('') +
+ [...slide.soundRels.entries()]
+ .map(([rid, part]) => `<Relationship Id="${rid}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio" Target="../${part}"/>`)
+ .join('') +
`</Relationships>`
await zip.addText(`ppt/slides/_rels/slide${i + 1}.xml.rels`, rels)
if (opts.pages[i].notes?.trim()) {
@@ -198,7 +299,15 @@ export async function exportDesignToPptx(opts: PptxExportOptions): Promise<PptxE
}
}
for (const m of media.entries()) {
- await zip.addBytes(m.name, m.bytes)
+ // v0.22 fix: media parts live under ppt/ — the slide rels say
+ // "../media/imageN.png" (relative to ppt/slides/_rels/), which
+ // resolves to ppt/media/…; before this the parts landed at the
+ // package ROOT and every image/sound in a PPTX was a broken ref
+ await zip.addBytes(`ppt/${m.name}`, m.bytes)
+ }
+ // v0.22: the embedded font parts (raw TTF bytes as fntdata)
+ for (const f of fontBytes) {
+ await zip.addBytes(f.name, f.bytes)
}
const bytes = await zip.finalize()
@@ -212,6 +321,10 @@ export async function exportDesignToPptx(opts: PptxExportOptions): Promise<PptxE
natives,
rasters,
notes,
+ transitions,
+ sounds,
+ animated,
+ fontsEmbedded: fontBytes.length,
}
}
diff --git a/src/lib/pptx/parts.ts b/src/lib/pptx/parts.ts
index 8a83299..a1bf8d4 100644
--- a/src/lib/pptx/parts.ts
+++ b/src/lib/pptx/parts.ts
@@ -17,8 +17,9 @@ import { xesc } from './xml-helpers'
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
/** [Content_Types].xml — defaults for the extensions we emit plus
- * an override per XML part. */
-export function contentTypesXml(slides: string[], notesSlides: string[]): string {
+ * an override per XML part. v0.22: fntdata (embedded fonts) and
+ * wav (transition SFX) defaults appear only when used. */
+export function contentTypesXml(slides: string[], notesSlides: string[], opts: { fonts: number; sounds: number } = { fonts: 0, sounds: 0 }): string {
const hasNotesMaster = notesSlides.length > 0
const overrides = [
...slides.map((p) => partOverride(p, 'application/vnd.openxmlformats-officedocument.presentationml.slide+xml')),
@@ -41,6 +42,8 @@ export function contentTypesXml(slides: string[], notesSlides: string[]): string
`<Default Extension="png" ContentType="image/png"/>` +
`<Default Extension="jpeg" ContentType="image/jpeg"/>` +
`<Default Extension="jpg" ContentType="image/jpeg"/>` +
+ (opts.fonts > 0 ? `<Default Extension="fntdata" ContentType="application/x-fontdata"/>` : '') +
+ (opts.sounds > 0 ? `<Default Extension="wav" ContentType="audio/x-wav"/>` : '') +
overrides.join('') +
`</Types>`
)
@@ -66,14 +69,37 @@ function rel(id: string, type: string, target: string, targetMode?: 'External'):
/** ppt/presentation.xml — slide size (px → EMU), slide id list,
* notes master id list. Slide ids start at 256 (the format's
- * reserved floor for slides). */
+ * reserved floor for slides). v0.22: embeddedFontLst lists the
+ * fonts whose bytes ride the package (ppt/fonts/fontN.fntdata).
+ * The r:id for each face comes from the caller's font-rels map. */
+export interface EmbeddedFontFace {
+ /** the typeface name text runs reference */
+ family: string
+ /** face slot → presentation-relationship id for the fntdata part */
+ faces: Partial<Record<'regular' | 'bold' | 'italic' | 'bi', string>>
+}
+
export function presentationXml(
widthPx: number,
heightPx: number,
slideCount: number,
hasNotesMaster: boolean,
+ embeddedFonts: EmbeddedFontFace[] = [],
): string {
const ids = Array.from({ length: slideCount }, (_, i) => `<p:sldId id="${256 + i}" r:id="rId${i + 2}"/>`).join('')
+ const fontLst = embeddedFonts.length
+ ? `<p:embeddedFontLst>${embeddedFonts
+ .map(
+ (f) =>
+ `<p:embeddedFont><p:font typeface="${xesc(f.family)}"/>` +
+ (f.faces.regular ? `<p:regular r:id="${f.faces.regular}"/>` : '') +
+ (f.faces.bold ? `<p:bold r:id="${f.faces.bold}"/>` : '') +
+ (f.faces.italic ? `<p:italic r:id="${f.faces.italic}"/>` : '') +
+ (f.faces.bi ? `<p:bi r:id="${f.faces.bi}"/>` : '') +
+ `</p:embeddedFont>`,
+ )
+ .join('')}</p:embeddedFontLst>`
+ : ''
return (
XML_DECL +
`<p:presentation xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" saveSubsetFonts="1">` +
@@ -82,15 +108,23 @@ export function presentationXml(
`<p:sldIdLst>${ids}</p:sldIdLst>` +
`<p:sldSz cx="${Math.round(widthPx * 9525)}" cy="${Math.round(heightPx * 9525)}"/>` +
`<p:notesSz cx="${Math.round(heightPx * 9525)}" cy="${Math.round(widthPx * 9525)}"/>` +
+ fontLst +
`</p:presentation>`
)
}
-/** ppt/_rels/presentation.xml.rels — master, slides, notesMaster. */
-export function presentationRelsXml(slideCount: number, hasNotesMaster: boolean): string {
+/** ppt/_rels/presentation.xml.rels — master, slides, notesMaster,
+ * and (v0.22) the embedded font parts. Font rel ids must not
+ * collide with the slide/master/notesMaster ids. */
+export function presentationRelsXml(
+ slideCount: number,
+ hasNotesMaster: boolean,
+ fontParts: { rid: string; part: string }[] = [],
+): string {
const rels = [rel('rId1', 'slideMaster', 'slideMasters/slideMaster1.xml')]
for (let i = 0; i < slideCount; i++) rels.push(rel(`rId${i + 2}`, 'slide', `slides/slide${i + 1}.xml`))
if (hasNotesMaster) rels.push(rel(`rId${slideCount + 2}`, 'notesMaster', 'notesMasters/notesMaster1.xml'))
+ for (const f of fontParts) rels.push(rel(f.rid, 'font', f.part))
return XML_DECL + `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${rels.join('')}</Relationships>`
}
diff --git a/src/lib/pptx/pptx-export.test.ts b/src/lib/pptx/pptx-export.test.ts
index a85a9ea..320b8c4 100644
--- a/src/lib/pptx/pptx-export.test.ts
+++ b/src/lib/pptx/pptx-export.test.ts
@@ -271,3 +271,133 @@ describe('exportDesignToPptx (node — no DOM, native elements only)', () => {
expect(result.natives).toBe(6) // 5 on slide 1 + the background rect on slide 2
})
})
+
+// ── v0.22: transitions, entrance timing, re-wrap safety, sounds ──
+
+describe('exportDesignToPptx — v0.22 transitions/animations/autofit', () => {
+ it('always emits normAutofit (PowerPoint shrinks instead of spilling)', async () => {
+ const text = createTextElement({ x: 0, y: 0, width: 300, text: 'wrap safety', fontSize: 30 })
+ const result = await exportDesignToPptx({ designWidth: 400, designHeight: 300, pages: [page([text])] })
+ const slide = xml((await partsOf(result.blob)).get('ppt/slides/slide1.xml')!)
+ expect(slide).toContain('<a:normAutofit/>')
+ })
+
+ it('maps fade/slide transitions with speed and directional push', async () => {
+ const rect = () => createShapeElement('rect', { x: 0, y: 0, width: 100, height: 100, fill: '#FFF' })
+ const result = await exportDesignToPptx({
+ designWidth: 400,
+ designHeight: 300,
+ pages: [
+ page([rect()], { transition: { kind: 'fade', duration: 0.9 } }),
+ page([rect()], { transition: { kind: 'slide', duration: 2.0, direction: 'left' } }),
+ page([rect()]), // none
+ ],
+ })
+ expect(result.transitions).toBe(2)
+ const parts = await partsOf(result.blob)
+ const s1 = xml(parts.get('ppt/slides/slide1.xml')!)
+ const s2 = xml(parts.get('ppt/slides/slide2.xml')!)
+ const s3 = xml(parts.get('ppt/slides/slide3.xml')!)
+ expect(s1).toContain('<p:transition spd="med"><p:fade/></p:transition>')
+ expect(s2).toContain('<p:transition spd="slow"><p:push dir="l"/></p:transition>')
+ expect(s3).not.toContain('<p:transition')
+ // schema position: transition comes AFTER clrMapOvr, before timing/end
+ expect(s1.indexOf('<p:clrMapOvr>')).toBeLessThan(s1.indexOf('<p:transition'))
+ expect(s1.indexOf('<p:transition')).toBeLessThan(s1.indexOf('</p:sld>'))
+ })
+
+ it('carries entrance animations as one click group with delays', async () => {
+ const t1 = createTextElement({ x: 0, y: 0, width: 200, text: 'first', fontSize: 20 })
+ const t2 = createTextElement({ x: 0, y: 100, width: 200, text: 'second', fontSize: 20 })
+ t1.animation = { kind: 'fade', duration: 0.9, delay: 0, easing: 'easeOut' }
+ t2.animation = { kind: 'pan', duration: 0.5, delay: 1.2, easing: 'easeOut', direction: 'left' }
+ // rotate is an emphasis loop — documented NOT carried
+ const t3 = createTextElement({ x: 0, y: 200, width: 200, text: 'third', fontSize: 20 })
+ t3.animation = { kind: 'rotate', duration: 2, delay: 0, easing: 'linear' }
+ const result = await exportDesignToPptx({ designWidth: 400, designHeight: 300, pages: [page([t1, t2, t3])] })
+ expect(result.animated).toBe(3) // seen by the mapper…
+ const slide = xml((await partsOf(result.blob)).get('ppt/slides/slide1.xml')!)
+ expect(slide).toContain('<p:timing>')
+ expect(slide).toContain('nodeType="clickEffect"')
+ expect(slide).toContain('nodeType="withEffect"')
+ expect(slide).toContain('delay="1200"') // t2's 1.2 s delay
+ expect(slide).toContain('filter="wipeLeft"') // pan left
+ expect(slide).toContain('filter="fade"')
+ expect(slide).not.toContain('presetClass="emph"') // rotate dropped honestly
+ expect(slide).toContain('<p:bldP spid="') // build companions
+ })
+
+ it('wires the transition SFX as an embedded wav with an audio rel', async () => {
+ const rect = createShapeElement('rect', { x: 0, y: 0, width: 100, height: 100, fill: '#FFF' })
+ // a minimal RIFF/WAVE header + payload (the real fetch seam is
+ // browser-only; node tests inject bytes — the fontLadderIo posture)
+ const wav = new Uint8Array(128)
+ wav.set([0x52, 0x49, 0x46, 0x46, 0x7c, 0, 0, 0, 0x57, 0x41, 0x56, 0x45], 0)
+ const result = await exportDesignToPptx({
+ designWidth: 400,
+ designHeight: 300,
+ pages: [page([rect], { transition: { kind: 'fade', duration: 0.5, sfxId: 'whoosh-soft' } })],
+ sfxIo: { fetchBytes: async () => wav },
+ })
+ expect(result.sounds).toBe(1)
+ const parts = await partsOf(result.blob)
+ const slide = xml(parts.get('ppt/slides/slide1.xml')!)
+ expect(slide).toContain('<p:sndAc><p:stSnd><p:snd r:embed="rId')
+ const rels = xml(parts.get('ppt/slides/_rels/slide1.xml.rels')!)
+ expect(rels).toMatch(/relationships\/audio" Target="\.\.\/media\/sfx1\.wav"/)
+ const ct = xml(parts.get('[Content_Types].xml')!)
+ expect(ct).toContain('<Default Extension="wav" ContentType="audio/x-wav"/>')
+ const embedded = parts.get('ppt/media/sfx1.wav')
+ expect(embedded).toBeTruthy()
+ expect(embedded!.length).toBe(128)
+ expect(embedded![0]).toBe(0x52) // 'R' (RIFF)
+ })
+
+ it('omits sound machinery when no page has an SFX', async () => {
+ const rect = createShapeElement('rect', { x: 0, y: 0, width: 100, height: 100, fill: '#FFF' })
+ const result = await exportDesignToPptx({
+ designWidth: 400,
+ designHeight: 300,
+ pages: [page([rect], { transition: { kind: 'fade', duration: 0.5 } })],
+ })
+ expect(result.sounds).toBe(0)
+ const parts = await partsOf(result.blob)
+ const ct = xml(parts.get('[Content_Types].xml')!)
+ expect(ct).not.toContain('wav')
+ })
+})
+
+describe('exportDesignToPptx — media part placement (v0.22 fix)', () => {
+ it('degrades node image preload to null instead of crashing, and media lands under ppt/media/', async () => {
+ // 1×1 red JPEG. In node there is no Image constructor — the
+ // preload resolves null (the v0.22 robustness fix) and the image
+ // rides the raster/skip path instead of rejecting the export.
+ const jpeg =
+ 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwcJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPDIzNP/AABEIAAEAAQMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/aAAwDAQACEQMRAD8A/9k='
+ const img = {
+ type: 'image', id: 'i1', x: 10, y: 10, width: 80, height: 80, rotation: 0,
+ opacity: 1, locked: false, visible: true, src: jpeg, naturalWidth: 1, naturalHeight: 1,
+ } as unknown as PageData['elements'][number]
+ const result = await exportDesignToPptx({ designWidth: 200, designHeight: 200, pages: [page([img])] })
+ // the export completes; in node the image had no decodable bitmap
+ expect(result.pages).toBe(1)
+ const parts = await partsOf(result.blob)
+ expect(parts.has('ppt/slides/slide1.xml')).toBe(true)
+ // placement contract: whatever media parts exist live under ppt/media/
+ for (const name of parts.keys()) {
+ if (name.startsWith('media/')) throw new Error(`media part at package root: ${name}`)
+ }
+ // the sound part (browser fetch / injected io) lands under ppt/media/
+ const wav = new Uint8Array(128)
+ wav.set([0x52, 0x49, 0x46, 0x46], 0)
+ const rect = createShapeElement('rect', { x: 0, y: 0, width: 10, height: 10, fill: '#FFF' })
+ const withSound = await exportDesignToPptx({
+ designWidth: 200,
+ designHeight: 200,
+ pages: [page([rect], { transition: { kind: 'fade', duration: 0.5, sfxId: 'pop' } })],
+ sfxIo: { fetchBytes: async () => wav },
+ })
+ const parts2 = await partsOf(withSound.blob)
+ expect(parts2.has('ppt/media/sfx1.wav')).toBe(true)
+ })
+})
diff --git a/src/lib/pptx/slide-mapper.ts b/src/lib/pptx/slide-mapper.ts
index 310737a..e7fa262 100644
--- a/src/lib/pptx/slide-mapper.ts
+++ b/src/lib/pptx/slide-mapper.ts
@@ -35,6 +35,8 @@ import { normalizeSpans } from '@/lib/rich-text'
import { polygonPoints, starPointsEx, stretchPts, type Pt } from '@/lib/shapes'
import { fitFontSize } from '@/lib/text-fit'
import { emu, centerAfterRotation, parseColor, solidFill, strokeLn, xesc } from './xml-helpers'
+import { isSfxId } from '@/lib/assets/sfx-pack'
+import { timingXml, transitionXml, type AnimatedShape } from './transitions'
// ── context ──────────────────────────────────────────────────
@@ -56,14 +58,25 @@ export interface PptxMediaBag {
imagePart(src: string): Promise<string | null>
/** register raw raster bytes (fallback renders) → part name */
registerRaster(bytes: Uint8Array): Promise<string>
+ /** v0.22: the offline SFX pack — part name for a sound id
+ * ('media/sfx2.wav'), fetched once per id; null when the bytes
+ * are unavailable (export proceeds without the sound). */
+ soundPart(id: string): Promise<string | null>
}
export interface MappedSlide {
xml: string
/** relationship entries: rel id → media target */
imageRels: Map<string, string>
+ /** v0.22: audio relationship entries (transition SFX) — same
+ * rel-id namespace, a different relationship TYPE. */
+ soundRels: Map<string, string>
rasters: number
natives: number
+ /** entrance-animated shapes seen during the walk */
+ animated: AnimatedShape[]
+ /** the page's SFX actually landed a media part */
+ hasSound: boolean
}
// ── fills / shared property blocks ───────────────────────────
@@ -283,11 +296,16 @@ function textXml(t: TextElement, id: number, ctx: SlideMapContext): string | nul
const paras = paragraphsOf(t)
const rtl = t.direction === 'rtl'
const align = t.align === 'center' ? 'ctr' : t.align === 'justify' ? 'just' : rtl ? (t.align === 'left' ? 'r' : 'l') : t.align === 'right' ? 'r' : 'l'
+ // v0.22 re-wrap safety: PowerPoint's line engine wraps slightly
+ // differently than the browser's. bare <a:normAutofit/> (no scale)
+ // tells PowerPoint to shrink-on-overflow instead of spilling text
+ // out of the shape; when OUR engine already auto-fit the text, the
+ // measured scale rides along so PowerPoint starts where we left off.
const bodyPr =
`<a:bodyPr wrap="square" lIns="0" tIns="0" rIns="0" bIns="0" anchor="t">` +
(t.autoFit && effSize < t.fontSize
? `<a:normAutofit fontScale="${Math.max(10000, Math.round((effSize / t.fontSize) * 100000))}" lnSpcReduction="0"/>`
- : '') +
+ : `<a:normAutofit/>`) +
`</a:bodyPr>`
const ppr =
`<a:pPr algn="${align}"${rtl ? ' rtl="1"' : ''}>` +
@@ -525,9 +543,12 @@ export async function mapSlide(
ctx: SlideMapContext,
): Promise<MappedSlide> {
const imageRels = new Map<string, string>()
+ const soundRels = new Map<string, string>()
const shapes: string[] = []
+ const animated: AnimatedShape[] = []
let rasters = 0
let natives = 0
+ let hasSound = false
const t = pageTransform(page, designW, designH)
const background =
@@ -545,6 +566,10 @@ export async function mapSlide(
const id = ctx.nextId()
let xml: string | null = null
let native = true
+ // v0.22: entrance animations carry into the timing tree — collect
+ // every visible animated element (native or raster, both are real
+ // shapes with ids) with the id it got on THIS slide
+ if (el.animation && el.animation.kind !== 'none') animated.push({ spid: id, animation: el.animation })
if (el.type === 'text') {
const te = el as TextElement
// curved text / text effects / shadowed text → raster
@@ -584,6 +609,23 @@ export async function mapSlide(
}
await walk(page.elements)
+ // v0.22: transitions + entrance timing + the page's SFX ride along.
+ // The sound bytes come from the media bag (fetched once per id);
+ // its rel rides the audio relationship type, wired into the
+ // transition's <p:sndAc>.
+ let transition = transitionXml(page.transition)
+ const sfxId = page.transition?.sfxId
+ if (transition && sfxId && isSfxId(sfxId)) {
+ const part = await ctx.media.soundPart(sfxId)
+ if (part) {
+ const rid = `rId${imageRels.size + soundRels.size + 2}` // rId1 is the layout
+ soundRels.set(rid, part)
+ hasSound = true
+ transition = transitionXml(page.transition, rid)
+ }
+ }
+ const timing = timingXml(animated)
+
const xml =
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n` +
`<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">` +
@@ -596,6 +638,16 @@ export async function mapSlide(
`</p:spTree>` +
`</p:cSld>` +
`<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>` +
+ transition +
+ timing +
`</p:sld>`
- return { xml, imageRels, rasters, natives }
+ return {
+ xml,
+ imageRels,
+ soundRels,
+ rasters,
+ natives,
+ animated,
+ hasSound,
+ }
}
diff --git a/src/lib/pptx/transitions.ts b/src/lib/pptx/transitions.ts
new file mode 100644
index 0000000..2bf38ff
--- /dev/null
+++ b/src/lib/pptx/transitions.ts
@@ -0,0 +1,177 @@
+// ─────────────────────────────────────────────────────────────
+// pptx transitions, sounds and entrance timing (v0.22 — the
+// "PPTX limits" wave: text re-wrap safety, font embedding, and
+// animations/transitions/SFX carrying into the file format).
+//
+// Three builders, all pure string functions (the house style):
+// transitionXml() a page's <p:transition> — the kind/direction/
+// speed map, plus the page's SFX wired as the
+// transition sound (<p:sndAc><p:stSnd><p:snd>)
+// timingXml() the <p:timing> tree — entrance animations as
+// one click group: first element clickEffect,
+// the rest withEffect at their delays
+// buildLstXml() the <p:bldLst> companions
+//
+// Honest mapping (docs/PPTX-EXPORT.md):
+// fade → <p:fade/> (native)
+// slide → <p:push dir="…"/> (native, directional)
+// morph → <p:fade/> (nearest universal; PowerPoint's own Morph
+// needs object-matching extensions)
+// fade/rise element animation → Fade entrance (presetID 10)
+// pan/wipe → Wipe entrance (presetID 22)
+// zoom/pop → Fade entrance (Zoom needs
+// anim-scale trees PowerPoint
+// repair-prompts on when hand-built)
+// rotate/breathe (emphasis/loops) → dropped, documented
+// ─────────────────────────────────────────────────────────────
+
+import type { AnimationDirection, ElementAnimation, PageTransition } from '@/lib/types'
+
+/** one animated element the mapper saw (native or raster — both are
+ * real OOXML shapes and can carry an entrance). */
+export interface AnimatedShape {
+ spid: number
+ animation: ElementAnimation
+}
+
+/** duration (seconds) → the coarse speed attribute PowerPoint's
+ * non-extended transition element accepts. */
+function speedOf(seconds: number): 'slow' | 'med' | 'fast' {
+ if (seconds < 0.6) return 'fast'
+ if (seconds < 1.4) return 'med'
+ return 'slow'
+}
+
+const PUSH_DIR: Record<AnimationDirection, 'u' | 'd' | 'l' | 'r'> = {
+ up: 'u',
+ down: 'd',
+ left: 'l',
+ right: 'r',
+}
+
+/** The page transition element, or '' when the page has none.
+ * `sndRid` (optional) wires the page's SFX as the transition sound. */
+export function transitionXml(t: PageTransition | undefined, sndRid?: string): string {
+ if (!t || t.kind === 'none') return ''
+ const spd = speedOf(t.duration)
+ const effect =
+ t.kind === 'slide'
+ ? `<p:push dir="${PUSH_DIR[t.direction ?? 'left']}"/>`
+ : `<p:fade/>` // fade AND morph (documented nearest-universal)
+ const sound = sndRid
+ ? `<p:sndAc><p:stSnd><p:snd r:embed="${sndRid}"/></p:stSnd></p:sndAc>`
+ : ''
+ return `<p:transition spd="${spd}">${effect}${sound}</p:transition>`
+}
+
+// ── entrance timing ──────────────────────────────────────────
+
+/** our kinds → (presetID, animEffect filter). null = not carried. */
+function entranceOf(a: ElementAnimation): { presetId: number; filter: string } | null {
+ switch (a.kind) {
+ case 'fade':
+ case 'rise':
+ return { presetId: 10, filter: 'fade' }
+ case 'pan':
+ case 'wipe': {
+ // the wipe travels the direction the content pans; PowerPoint
+ // names the filter by the travel direction
+ const d = a.direction ?? 'left'
+ const filter = d === 'up' ? 'wipeUp' : d === 'down' ? 'wipeDown' : d === 'left' ? 'wipeLeft' : 'wipeRight'
+ return { presetId: 22, filter }
+ }
+ case 'zoom':
+ case 'pop':
+ return { presetId: 10, filter: 'fade' } // documented approximation
+ default:
+ return null // rotate/breathe: emphasis/loops, not carried
+ }
+}
+
+/** The <p:timing> tree for a slide's entrance animations, or ''.
+ * Schema: one mainSeq with ONE click group — the first animated
+ * element is the clickEffect, the rest fire withEffect at their
+ * own delays (our present-mode semantics: one advance, then the
+ * sequence plays itself). */
+export function timingXml(animated: AnimatedShape[]): string {
+ const carried = animated.filter((a) => entranceOf(a.animation) !== null)
+ if (!carried.length) return ''
+ let id = 1
+ const nid = () => ++id
+
+ const effects = carried
+ .map((entry, i) => {
+ const e = entranceOf(entry.animation)!
+ const delay = Math.max(0, Math.round(entry.animation.delay * 1000))
+ const dur = Math.max(200, Math.round(entry.animation.duration * 1000))
+ const nodeType = i === 0 ? 'clickEffect' : 'withEffect'
+ const sid = nid() // the effect cTn
+ const setId = nid()
+ const animId = nid()
+ return (
+ `<p:par>` +
+ `<p:cTn id="${sid}" presetID="${e.presetId}" presetClass="entr" presetSubtype="0" fill="hold" grpId="0" nodeType="${nodeType}">` +
+ `<p:stCondLst><p:cond delay="${delay}"/></p:stCondLst>` +
+ `<p:childTnLst>` +
+ // style.visibility → visible (entrances need the initial hide+show)
+ `<p:set>` +
+ `<p:cBhvr>` +
+ `<p:cTn id="${setId}" dur="1" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst></p:cTn>` +
+ `<p:tgtEl><p:spTgt spid="${entry.spid}"/></p:tgtEl>` +
+ `<p:attrNameLst><p:attrName>style.visibility</p:attrName></p:attrNameLst>` +
+ `</p:cBhvr>` +
+ `<p:to><p:strVal val="visible"/></p:to>` +
+ `</p:set>` +
+ `<p:animEffect transition="in" filter="${e.filter}">` +
+ `<p:cBhvr>` +
+ `<p:cTn id="${animId}" dur="${dur}"/>` +
+ `<p:tgtEl><p:spTgt spid="${entry.spid}"/></p:tgtEl>` +
+ `</p:cBhvr>` +
+ `</p:animEffect>` +
+ `</p:childTnLst>` +
+ `</p:cTn>` +
+ `</p:par>`
+ )
+ })
+ .join('')
+
+ const rootId = nid()
+ const seqId = nid()
+ const clickId = nid()
+ const withId = nid()
+ return (
+ `<p:timing>` +
+ `<p:tnLst>` +
+ `<p:par>` +
+ `<p:cTn id="${rootId}" dur="indefinite" restart="never" nodeType="tmRoot">` +
+ `<p:childTnLst>` +
+ `<p:seq concurrent="1" nextAc="seek">` +
+ `<p:cTn id="${seqId}" dur="indefinite" nodeType="mainSeq">` +
+ `<p:childTnLst>` +
+ // the single click group
+ `<p:par>` +
+ `<p:cTn id="${clickId}" fill="hold">` +
+ `<p:stCondLst><p:cond delay="indefinite"/></p:stCondLst>` +
+ `<p:childTnLst>` +
+ `<p:par>` +
+ `<p:cTn id="${withId}" fill="hold">` +
+ `<p:stCondLst><p:cond delay="0"/></p:stCondLst>` +
+ `<p:childTnLst>${effects}</p:childTnLst>` +
+ `</p:cTn>` +
+ `</p:par>` +
+ `</p:childTnLst>` +
+ `</p:cTn>` +
+ `</p:par>` +
+ `</p:childTnLst>` +
+ `</p:cTn>` +
+ `<p:prevCondLst><p:cond evt="onPrev" delay="0"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:prevCondLst>` +
+ `<p:nextCondLst><p:cond evt="onNext" delay="0"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:nextCondLst>` +
+ `</p:seq>` +
+ `</p:childTnLst>` +
+ `</p:cTn>` +
+ `</p:par>` +
+ `</p:tnLst>` +
+ `<p:bldLst>${carried.map((a) => `<p:bldP spid="${a.spid}" grpId="0"/>`).join('')}</p:bldLst>` +
+ `</p:timing>`
+ )
+}
diff --git a/tests/e2e/pptx-export.spec.ts b/tests/e2e/pptx-export.spec.ts
index 070d6d5..333016e 100644
--- a/tests/e2e/pptx-export.spec.ts
+++ b/tests/e2e/pptx-export.spec.ts
@@ -74,3 +74,117 @@ print('PPTX OK: ' + str(len(names)) + ' parts')
expect(errors, `page errors: ${errors.join(' | ')}`).toEqual([])
})
})
+
+/**
+ * v0.22 — the PPTX-limits wave through the dialog: a page with a
+ * Montserrat heading (font embedding), a fade transition, and an
+ * entrance animation on the heading (timing tree). Cracks the zip:
+ * embeddedFontLst + fntdata parts, the transition in the slide XML,
+ * the click group in the timing tree, media under ppt/media/ — then
+ * the LibreOffice round-trip (soffice converts it; a malformed
+ * timing tree would repair-prompt instead).
+ */
+test.describe('PPTX export — v0.22 fonts/transitions/animations', () => {
+ test('carries fonts, transitions and entrance timing into the file', async ({ page }) => {
+ test.setTimeout(180_000)
+ const errors: string[] = []
+ page.on('pageerror', (err) => errors.push(String(err)))
+
+ await page.goto('/')
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await page.getByRole('button', { name: /start designing/i }).first().click()
+ await expect(page.getByLabel('Create a design')).toBeVisible()
+
+ await page
+ .locator('section:has(h2:text("Start a new design")) [aria-label^="Create "]')
+ .first()
+ .click()
+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })
+
+ // a Montserrat heading with an entrance animation
+ await page.getByRole('button', { name: 'Text', exact: true }).click()
+ await page.getByRole('button', { name: 'Add a heading', exact: true }).click()
+ await expect(page.getByLabel('Design canvas')).toBeVisible()
+
+ // animate it: Animate panel → entrance fade
+ await page.getByRole('button', { name: 'Animate', exact: true }).click()
+ const fadeTile = page.getByRole('button', { name: /fade/i }).first()
+ if (await fadeTile.isVisible().catch(() => false)) {
+ await fadeTile.click()
+ }
+
+ // transition on the page: the Transitions section of the panel
+ const transBtn = page.getByRole('button', { name: /transitions?/i }).first()
+ if (await transBtn.isVisible().catch(() => false)) {
+ await transBtn.click()
+ const fadeTrans = page.getByRole('button', { name: /^fade$/i }).first()
+ if (await fadeTrans.isVisible().catch(() => false)) await fadeTrans.click()
+ }
+
+ // export through the dialog
+ const downloadPromise = page.waitForEvent('download', { timeout: 120_000 })
+ await page.getByRole('button', { name: 'Download', exact: true }).click()
+ await page.getByRole('button', { name: /^PPTX\b/ }).click()
+ await page.getByRole('button', { name: /Download 1 PPTX/i }).click()
+ const download = await downloadPromise
+ expect(download.suggestedFilename()).toMatch(/\.pptx$/)
+ const path = await download.path()
+
+ // crack the package open
+ const { execFileSync } = await import('node:child_process')
+ const out = execFileSync('python3', ['-c', `
+import zipfile, sys
+z = zipfile.ZipFile(${JSON.stringify(path)})
+names = z.namelist()
+slide = z.read('ppt/slides/slide1.xml').decode('utf-8')
+presentation = z.read('ppt/presentation.xml').decode('utf-8')
+
+# v0.22: transitions + entrance timing live in the slide
+if '<p:transition' not in slide:
+ sys.exit('no transition in slide1')
+if '<p:timing>' not in slide:
+ sys.exit('no timing tree in slide1')
+if 'presetClass="entr"' not in slide:
+ sys.exit('no entrance effect in the timing tree')
+
+# v0.22: fonts embedded as fntdata + listed in presentation
+fntdata = [n for n in names if n.endswith('.fntdata')]
+if not fntdata:
+ sys.exit('no embedded font parts (ladder may have failed - check network)')
+if '<p:embeddedFontLst>' not in presentation:
+ sys.exit('embeddedFontLst missing from presentation.xml')
+
+# v0.22: media parts live under ppt/media/ (the placement fix)
+bad = [n for n in names if n.startswith('media/')]
+if bad:
+ sys.exit('media at package root: ' + ','.join(bad))
+
+# v0.22: re-wrap safety — every text body carries normAutofit
+if '<a:normAutofit' not in slide:
+ sys.exit('normAutofit missing from slide1')
+
+print('PPTX v0.22 OK: %d parts, %d fonts' % (len(names), len(fntdata)))
+`], { encoding: 'utf-8' })
+ expect(out.trim()).toMatch(/^PPTX v0\.22 OK: \d+ parts, \d+ fonts$/)
+
+ // LibreOffice round-trip: converts cleanly when the XML is schema-sane
+ let soffice = true
+ try {
+ execFileSync('soffice', ['--version'])
+ } catch {
+ soffice = false
+ }
+ test.skip(!soffice, 'LibreOffice not installed on this runner')
+ const fs = await import('node:fs')
+ const tmp = `/tmp/pptx-v022-${Date.now()}.pptx`
+ fs.copyFileSync(path!, tmp)
+ execFileSync('soffice', ['--headless', '--convert-to', 'pdf', '--outdir', '/tmp', tmp], {
+ timeout: 90_000,
+ })
+ const pdf = tmp.replace(/\.pptx$/, '.pdf')
+ expect(fs.existsSync(pdf), 'soffice produced a PDF').toBe(true)
+ expect(fs.statSync(pdf).size).toBeGreaterThan(2000)
+
+ expect(errors, `page errors: ${errors.join(' | ')}`).toEqual([])
+ })
+})