返回 slidev
build.ts
根目录 / packages / slidev / node / commands / pptx / build.ts
1 /**
2 * `SlideIr[]` to a `.pptx` buffer, through `pptxgenjs`. Pure: no DOM,
3 * Playwright or filesystem, so every rule is unit-testable by building a
4 * fixture and unzipping the result.
5 */
6
7 import type { Buffer } from 'node:buffer'
8 import type PptxGenJS from 'pptxgenjs'
9 import type {
10 Border,
11 IrBox,
12 IrImage,
13 IrRaster,
14 IrRun,
15 IrText,
16 Rgba,
17 SlideIr,
18 } from './ir'
19 import { INCHES_PER_PX, PT_PER_PX } from './ir'
20
21 /**
22 * Extra width beyond the measured glyph bounds: PowerPoint sets the same
23 * string slightly wider than Chromium, so a tight single-line box re-wraps.
24 * Single-line boxes get the generous value and `wrap: false`; multi-line
25 * boxes re-wrap anyway, and widening them pushes into the next column.
26 */
27 const SLACK_SINGLE_LINE_PX = 12
28 const SLACK_MULTI_LINE_PX = 2
29
30 function hex(color: Rgba): string {
31 const channel = (v: number) => Math.max(0, Math.min(255, Math.round(v)))
32 .toString(16)
33 .padStart(2, '0')
34 .toUpperCase()
35 return `${channel(color.r)}${channel(color.g)}${channel(color.b)}`
36 }
37
38 /**
39 * CSS alpha (0 opaque..1) to PowerPoint transparency (0 opaque..100), or
40 * undefined when fully opaque: `pptxgenjs` tests the field for truthiness.
41 */
42 function transparency(color: Rgba): number | undefined {
43 if (color.a >= 1)
44 return undefined
45 return Math.round((1 - color.a) * 100)
46 }
47
48 /** Canvas pixels to inches, which is what every `pptxgenjs` coordinate wants. */
49 function inch(px: number): number {
50 return px * INCHES_PER_PX
51 }
52
53 /** Canvas pixels to points, which is what every `pptxgenjs` type size wants. */
54 function pt(px: number): number {
55 return px * PT_PER_PX
56 }
57
58 function runProps(run: IrRun): Record<string, unknown> {
59 const options: Record<string, unknown> = {
60 fontFace: run.fontFamily,
61 fontSize: pt(run.fontSize),
62 }
63 if (run.bold)
64 options.bold = true
65 if (run.italic)
66 options.italic = true
67 if (run.strike)
68 options.strike = true
69 if (run.underline)
70 options.underline = { style: run.underlineStyle ?? 'sng' }
71 else if (run.link)
72 // pptxgenjs underlines every hyperlink run unless told otherwise. CSS said
73 // not to: a theme that rules its links with a `border-bottom` already has
74 // that drawn as its own shape, so the default added a second line.
75 options.underline = { style: 'none' }
76 if (run.color) {
77 options.color = hex(run.color)
78 const alpha = transparency(run.color)
79 if (alpha !== undefined)
80 options.transparency = alpha
81 }
82 if (run.letterSpacing)
83 options.charSpacing = pt(run.letterSpacing)
84 if (run.link)
85 options.hyperlink = { url: run.link }
86 if (run.endsParagraph)
87 options.breakLine = true
88 // `softBreakBefore` emits a real <a:br/> inside one paragraph; a \v in the
89 // text renders in PowerPoint but not in Keynote or LibreOffice.
90 if (run.breakBefore)
91 options.softBreakBefore = true
92 return options
93 }
94
95 function addText(slide: PptxGenJS.Slide, node: IrText): void {
96 const slack = node.lineCount === 1
97 ? SLACK_SINGLE_LINE_PX
98 : SLACK_MULTI_LINE_PX
99
100 // Widening a box moves its content unless the origin moves too: a centered
101 // line would drift right by half the slack, a right-aligned one by all of it.
102 let x = node.rect.x
103 if (node.align === 'center')
104 x -= slack / 2
105 else if (node.align === 'right')
106 x -= slack
107
108 slide.addText(
109 node.runs.map(run => ({
110 text: run.text,
111 options: runProps(run),
112 })),
113 {
114 x: inch(x),
115 y: inch(node.rect.y),
116 w: inch(node.rect.w + slack),
117 h: inch(node.rect.h),
118 align: node.align,
119 // PowerPoint's default inset is 0.05in/0.1in; the IR position is glyph
120 // bounds, so any inset here is a visible offset.
121 margin: 0,
122 // The default 'middle' would center a one-line box measured from the glyphs.
123 valign: node.valign ?? 'top',
124 // Autofit would rescale type the moment PowerPoint disagrees about metrics.
125 fit: 'none',
126 isTextBox: true,
127 wrap: node.lineCount > 1,
128 // Only for multi-line text: a single-line box is measured from glyph ink,
129 // shorter than the CSS line box, and the taller value clips descenders.
130 ...(node.lineCount > 1
131 ? {
132 lineSpacing: pt(node.lineHeight),
133 }
134 : {}),
135 },
136 )
137 }
138
139 /**
140 * One side of a border, as its own filled rectangle: `pptxgenjs` gives a shape
141 * one uniform `line`, and `addShape(LINE)` centers its stroke on the geometry,
142 * putting half the border outside the element box.
143 */
144 function addEdge(slide: PptxGenJS.Slide, shapeType: typeof PptxGenJS.ShapeType, box: IrBox, side: 0 | 1 | 2 | 3, border: Border): void {
145 const { x, y, w, h } = box.rect
146 const t = border.width
147 const rect
148 = side === 0
149 ? { x, y, w, h: t }
150 : side === 1
151 ? { x: x + w - t, y, w: t, h }
152 : side === 2
153 ? { x, y: y + h - t, w, h: t }
154 : { x, y, w: t, h }
155
156 // A filled rectangle cannot carry a dash pattern, so a dashed or dotted rule
157 // came out solid: Slidev rules its links this way, and every link in a deck
158 // gained a solid bar. A line can be dashed, and for a hairline the half
159 // stroke that falls outside the box is well under a pixel.
160 if (border.style !== 'solid') {
161 slide.addShape(shapeType.line, {
162 x: inch(rect.x),
163 y: inch(rect.y),
164 w: inch(side === 0 || side === 2
165 ? rect.w
166 : 0),
167 h: inch(side === 0 || side === 2
168 ? 0
169 : rect.h),
170 line: {
171 color: hex(border.color),
172 transparency: transparency(border.color),
173 width: pt(border.width),
174 dashType: border.style === 'dotted'
175 ? 'sysDot'
176 : 'dash',
177 },
178 })
179 return
180 }
181
182 slide.addShape(shapeType.rect, {
183 x: inch(rect.x),
184 y: inch(rect.y),
185 w: inch(rect.w),
186 h: inch(rect.h),
187 fill: {
188 color: hex(border.color),
189 transparency: transparency(border.color),
190 },
191 })
192 }
193
194 function sameBorder(a?: Border, b?: Border): boolean {
195 if (!a || !b)
196 return a === b
197 return a.width === b.width && a.style === b.style && hex(a.color) === hex(b.color)
198 && a.color.a === b.color.a
199 }
200
201 function addBox(slide: PptxGenJS.Slide, shapeType: typeof PptxGenJS.ShapeType, node: IrBox): void {
202 const borders = node.borders
203 const uniform
204 = borders
205 && borders[0]
206 && sameBorder(borders[0], borders[1])
207 && sameBorder(borders[1], borders[2])
208 && sameBorder(borders[2], borders[3])
209
210 // With no fill and no uniform border there is nothing for this shape to
211 // carry: its only border is drawn as its own edge below. Emitting it anyway
212 // left a rectangle with neither fill nor outline specified, which PowerPoint
213 // resolves from its default shape style rather than leaving blank.
214 if (!node.fill && !uniform && !node.shadow) {
215 for (const side of [0, 1, 2, 3] as const) {
216 const border = borders?.[side]
217 if (border && border.width > 0)
218 addEdge(slide, shapeType, node, side, border)
219 }
220 return
221 }
222
223 const options: Record<string, unknown> = {
224 x: inch(node.rect.x),
225 y: inch(node.rect.y),
226 w: inch(node.rect.w),
227 h: inch(node.rect.h),
228 }
229
230 // `fill` and `line` are omitted rather than set to `{ type: 'none' }`.
231 // pptxgenjs writes `<a:noFill/>` for an ABSENT fill and nothing at all for
232 // that object, so the explicit-looking version was the one that inherited.
233 if (node.fill) {
234 options.fill = {
235 color: hex(node.fill),
236 transparency: transparency(node.fill),
237 }
238 }
239
240 if (uniform && borders[0]) {
241 options.line = {
242 color: hex(borders[0].color),
243 width: pt(borders[0].width),
244 dashType: borders[0].style === 'solid'
245 ? 'solid'
246 : borders[0].style === 'dotted'
247 ? 'sysDot'
248 : 'dash',
249 // `ShapeLineProps extends ShapeFillProps`: without `transparency` a
250 // hairline set in `rgba(0, 0, 0, 0.1)` comes out solid black.
251 transparency: transparency(borders[0].color),
252 }
253 }
254
255 if (node.shadow) {
256 options.shadow = {
257 type: 'outer',
258 blur: pt(node.shadow.blur),
259 offset: pt(node.shadow.offset),
260 angle: node.shadow.angle,
261 color: hex(node.shadow.color),
262 opacity: node.shadow.color.a,
263 }
264 }
265
266 if (node.radius) {
267 // `rectRadius` is documented as "values: 0.0 to 1.0" but is an inch
268 // measurement: the runtime multiplies it by EMU before dividing by the
269 // shorter side, so a value in the documented range rounds to zero.
270 const shorter = Math.min(node.rect.w, node.rect.h)
271 options.rectRadius = inch(Math.min(node.radius, shorter / 2))
272 slide.addShape(shapeType.roundRect, options)
273 }
274 else {
275 slide.addShape(shapeType.rect, options)
276 }
277
278 if (borders && !uniform) {
279 for (const side of [0, 1, 2, 3] as const) {
280 const border = borders[side]
281 if (border && border.width > 0)
282 addEdge(slide, shapeType, node, side, border)
283 }
284 }
285 }
286
287 function addPicture(slide: PptxGenJS.Slide, node: IrImage | IrRaster): void {
288 const options: Record<string, unknown> = {
289 data: node.data,
290 x: inch(node.rect.x),
291 y: inch(node.rect.y),
292 w: inch(node.rect.w),
293 h: inch(node.rect.h),
294 }
295 if (node.kind === 'image') {
296 if (node.alt)
297 options.altText = node.alt
298 if (node.link)
299 options.hyperlink = { url: node.link }
300 // `sizing.crop` reads `w`/`h` as the picture's full display size and the
301 // visible window from `sizing`, the opposite of every other option here;
302 // `<a:srcRect>` trims the rest away.
303 if (node.crop) {
304 options.w = inch(node.crop.w)
305 options.h = inch(node.crop.h)
306 options.sizing = {
307 type: 'crop',
308 x: inch(node.crop.x),
309 y: inch(node.crop.y),
310 w: inch(node.rect.w),
311 h: inch(node.rect.h),
312 }
313 }
314 }
315 else {
316 // The reason is the most useful alt text a rasterized element can carry.
317 options.altText = `Rendered as an image because of CSS ${node.reason}`
318 }
319 slide.addImage(options)
320 }
321
322 export interface BuildOptions {
323 /** Canvas width in pixels. The slide becomes `width / 96` inches wide. */
324 width: number
325 /** Canvas height in pixels. */
326 height: number
327 title?: string
328 author?: string
329 subject?: string
330 }
331
332 /**
333 * Build the deck. The constructor is passed in so the caller keeps its dynamic
334 * `import('pptxgenjs')`, which keeps the library off the CLI's startup path.
335 */
336 export async function buildPptx(
337 Pptx: typeof PptxGenJS,
338 slides: SlideIr[],
339 options: BuildOptions,
340 ): Promise<Buffer> {
341 const pptx = new Pptx()
342
343 // Same layout the image exporter defines; changing it here would silently
344 // change `--format pptx` output too.
345 const layoutName = `${options.width}x${options.height}`
346 pptx.defineLayout({
347 name: layoutName,
348 width: inch(options.width),
349 height: inch(options.height),
350 })
351 pptx.layout = layoutName
352
353 pptx.company = 'Created using Slidev'
354 if (options.title)
355 pptx.title = options.title
356 if (options.author)
357 pptx.author = options.author
358 if (options.subject)
359 pptx.subject = options.subject
360
361 for (const ir of slides) {
362 const slide = pptx.addSlide()
363
364 if (ir.fallbackPng) {
365 // Exactly what `--format pptx` produces, for this slide only: a theme
366 // the walker cannot handle degrades to today's behavior.
367 slide.background = { data: ir.fallbackPng }
368 }
369 else {
370 if (ir.background) {
371 slide.background = {
372 color: hex(ir.background),
373 transparency: transparency(ir.background),
374 }
375 }
376 for (const node of ir.nodes) {
377 switch (node.kind) {
378 case 'box':
379 addBox(slide, pptx.ShapeType, node)
380 break
381 case 'text':
382 addText(slide, node)
383 break
384 case 'image':
385 case 'raster':
386 addPicture(slide, node)
387 break
388 }
389 }
390 }
391
392 if (ir.note)
393 slide.addNotes(ir.note)
394 }
395
396 return await pptx.write({ outputType: 'nodebuffer' }) as Buffer
397 }
398
398 lines TYPESCRIPT