返回 slidev
normalize.ts
根目录 / packages / slidev / node / commands / pptx / normalize.ts
1 import type { UnparsedColors } from './color'
2 import type {
3 Border,
4 IrBox,
5 IrNode,
6 IrRun,
7 IrText,
8 RasterReason,
9 RawNode,
10 RawSlide,
11 RawSnapshot,
12 RawStyle,
13 Rect,
14 SlideIr,
15 } from './ir'
16 import { isVisible, parseColor, withOpacity } from './color'
17
18 /**
19 * `RawSnapshot` to `SlideIr`: every judgement in the exporter, in one pure module with
20 * no DOM or Playwright access, so each rule is testable from a hand-written fixture.
21 * Where a rule looks over-specific, it is a bug that already happened; see `normalize.test.ts`.
22 */
23
24 /**
25 * Fraction of the slide that may be rasterized before the whole slide falls back to
26 * a picture: past this, a half-vector slide invites editing that will not work.
27 */
28 const RASTER_AREA_LIMIT = 0.6
29
30 /**
31 * Fraction of a line's width kept free so PowerPoint does not re-wrap it: PowerPoint
32 * sets the same string a little wider than Chromium, so a shrink-wrapped container
33 * gains a wrap. The headroom scales with the line.
34 */
35 /**
36 * How much loose text a row of chips may hold and still be a row of chips.
37 *
38 * A separator between keys is punctuation; a sentence carrying inline `<code>`
39 * is words, and that stays one editable box.
40 */
41 const SEPARATOR_MAX_CHARS = 3
42
43 const WRAP_HEADROOM = 0.02
44 const WRAP_HEADROOM_MIN_PX = 4
45
46 /**
47 * CSS `display` values whose children are laid out, not flowed as text.
48 *
49 * `table-cell` and `table-caption` are excluded: a table lays out its rows and
50 * a row its cells, but the CONTENTS of a cell flow like any block, so treating
51 * one as a layout container split `<kbd>right</kbd> / <kbd>space</kbd>` into
52 * three boxes and left the slash sitting on the first key.
53 *
54 * `list-item` is absent for the same reason: it flows its children as text,
55 * and its ::marker is emitted before they are visited.
56 */
57 const LAYOUT_DISPLAY = /^(?:flex|grid|inline-flex|inline-grid|table(?!-cell|-caption))/
58
59 /**
60 * `display` values whose box participates in a line box and whose children flow as
61 * text. `inline-flex`, `inline-grid` and `inline-table` are excluded on purpose: they
62 * lay their children out as boxes, so a naive `^inline` match would concatenate their cells.
63 */
64 const INLINE_DISPLAY = /^(?:inline(?:-block)?$|contents|ruby)/
65
66 const RASTER_TAGS: Record<string, RasterReason> = {
67 SVG: 'svg',
68 CANVAS: 'canvas',
69 VIDEO: 'media',
70 AUDIO: 'media',
71 IFRAME: 'iframe',
72 }
73
74 export interface RasterRequest {
75 /** The `data-slidev-export-id` of the element to capture. */
76 sourceId: number
77 /** Page coordinates to clip, for a pseudo-element that has no element to select. */
78 clip?: Rect
79 /** Hide everything outside this element's own subtree. */
80 isolate: boolean
81 /** Also hide its children, which is only safe when they are redrawn. */
82 hideDescendants: boolean
83 /** The element to isolate against for a pseudo-element, which has no id attribute of its own; its originating element does. */
84 isolateId?: number
85 }
86
87 export interface NormalizeOptions {
88 /** Note text per 1-based slide number. */
89 notes: Map<number, string | undefined>
90 }
91
92 export interface NormalizeResult {
93 slides: SlideIr[]
94 rasterRequests: RasterRequest[]
95 /** Color strings no parser understood, so the caller can report them. */
96 unparsedColors: string[]
97 }
98
99 export function parseLength(value: string | undefined, basis?: number): number {
100 if (!value)
101 return 0
102 const n = Number.parseFloat(value)
103 if (Number.isNaN(n))
104 return 0
105 if (value.trim().endsWith('%')) {
106 return basis === undefined
107 ? 0
108 : (n / 100) * basis
109 }
110 return n
111 }
112
113 /**
114 * The part of `rect` on the slide, or undefined. Slides are `overflow: hidden`
115 * while PowerPoint has no clipping, so an unclamped shape stays on the canvas off
116 * the edge; a rect can also run to tens of millions of pixels.
117 */
118 export function clipToSlide(rect: Rect, size: { w: number, h: number }): Rect | undefined {
119 const x = Math.max(rect.x, 0)
120 const y = Math.max(rect.y, 0)
121 const right = Math.min(rect.x + rect.w, size.w)
122 const bottom = Math.min(rect.y + rect.h, size.h)
123 if (right <= x || bottom <= y)
124 return undefined
125 return { x, y, w: right - x, h: bottom - y }
126 }
127
128 /** Whether two rects share any area at all. */
129 function overlaps(a: Rect, b: Rect): boolean {
130 return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
131 }
132
133 function borderOf(style: RawStyle, side: 'Top' | 'Right' | 'Bottom' | 'Left', unparsed: UnparsedColors): Border | undefined {
134 const width = parseLength((style as any)[`border${side}Width`])
135 const lineStyle = (style as any)[`border${side}Style`] as string
136 const color = parseColor((style as any)[`border${side}Color`], unparsed)
137 if (width <= 0 || !lineStyle || lineStyle === 'none' || lineStyle === 'hidden' || !isVisible(color))
138 return undefined
139 return {
140 width,
141 color: color!,
142 style: lineStyle === 'dashed'
143 ? 'dashed'
144 : lineStyle === 'dotted'
145 ? 'dotted'
146 : 'solid',
147 }
148 }
149
150 /**
151 * Why this element cannot be drawn as shapes, or undefined if it can. Everything listed
152 * lacks a DrawingML primitive; the honest move is one picture at the exact box.
153 */
154 export function rasterReasonFor(node: RawNode, style: RawStyle | undefined): RasterReason | undefined {
155 // Before the tag map, which would report a Mermaid diagram as a plain 'svg';
156 // the reason reaches the log and the picture's alt text.
157 if (node.hasForeignObject)
158 return 'foreign-object'
159 // Also before the tag map: a formula's root is a `<span>`, so nothing else
160 // here would catch it.
161 if (node.isMath)
162 return 'math'
163 const tagReason = RASTER_TAGS[node.tag]
164 if (tagReason)
165 return tagReason
166 if (!style)
167 return undefined
168 // Before `background-image`, because gradient text is BOTH: a gradient
169 // clipped to the glyphs, with `color` left as a flat fallback. Reported as a
170 // background image it counts as a backdrop, so the text is drawn again over
171 // the picture, and the fallback color hides the gradient it was standing in
172 // for.
173 if (style.webkitBackgroundClip === 'text')
174 return 'background-clip-text'
175 if (style.backgroundImage && style.backgroundImage !== 'none')
176 return 'background-image'
177 if (style.filter && style.filter !== 'none')
178 return 'filter'
179 if (style.backdropFilter && style.backdropFilter !== 'none')
180 return 'backdrop-filter'
181 if (style.mixBlendMode && style.mixBlendMode !== 'normal')
182 return 'mix-blend-mode'
183 if (style.clipPath && style.clipPath !== 'none')
184 return 'clip-path'
185 if (style.transform && style.transform !== 'none')
186 return 'transform'
187 if (style.writingMode && style.writingMode !== 'horizontal-tb')
188 return 'writing-mode'
189 return undefined
190 }
191
192 /**
193 * Whether a rasterized element needs its siblings hidden during capture: a backdrop has
194 * content painted on top of it, which would bake into the picture and be drawn again as
195 * shapes. A leaf such as an `<svg>` has nothing on top.
196 */
197 function needsIsolation(reason: RasterReason): boolean {
198 return reason === 'background-image'
199 || reason === 'backdrop-filter'
200 || reason === 'filter'
201 || reason === 'mix-blend-mode'
202 }
203
204 function applyTransform(text: string, transform: string | undefined): string {
205 switch (transform) {
206 case 'uppercase':
207 return text.toUpperCase()
208 case 'lowercase':
209 return text.toLowerCase()
210 case 'capitalize':
211 return text.replace(/\b\p{L}/gu, c => c.toUpperCase())
212 default:
213 return text
214 }
215 }
216
217 function resolveLineHeight(style: RawStyle): number {
218 const fontSize = parseLength(style.fontSize)
219 if (!style.lineHeight || style.lineHeight === 'normal')
220 return fontSize * 1.2
221 return parseLength(style.lineHeight) || fontSize * 1.2
222 }
223
224 function alignOf(style: RawStyle | undefined): IrText['align'] {
225 switch (style?.textAlign) {
226 case 'center':
227 return 'center'
228 case 'right':
229 case 'end':
230 return 'right'
231 case 'justify':
232 return 'justify'
233 default:
234 return 'left'
235 }
236 }
237
238 /**
239 * CSS keywords rather than typefaces; naming one in the file makes PowerPoint
240 * substitute its default silently, so the fallback must skip these as well.
241 */
242 const GENERIC_FAMILIES = new Set([
243 'system-ui',
244 'ui-sans-serif',
245 'ui-serif',
246 'ui-monospace',
247 'ui-rounded',
248 'sans-serif',
249 'serif',
250 'monospace',
251 'cursive',
252 'fantasy',
253 'math',
254 'emoji',
255 'fangsong',
256 'inherit',
257 'initial',
258 'unset',
259 ])
260
261 export function fallbackFamily(stack: string): string {
262 for (const raw of stack.split(',')) {
263 const family = raw.trim().replace(/^["']|["']$/g, '').replace(/\s+Variable$/, '')
264 if (!family || family.startsWith('-') || GENERIC_FAMILIES.has(family.toLowerCase()))
265 continue
266 return family
267 }
268 return 'Arial'
269 }
270
271 function runFrom(text: string, style: RawStyle, fontResolution: Record<string, string>, unparsed: UnparsedColors, link?: string, opacity?: number, rule?: IrRun['underlineStyle']): IrRun {
272 const weight = Number(style.fontWeight)
273 const decoration = style.textDecorationLine || ''
274 const family = fontResolution[style.fontFamily] || fallbackFamily(style.fontFamily)
275 const run: IrRun = {
276 text: applyTransform(text, style.textTransform),
277 fontSize: parseLength(style.fontSize),
278 fontFamily: family,
279 }
280 if (weight >= 600)
281 run.bold = true
282 if (style.fontStyle === 'italic' || style.fontStyle === 'oblique')
283 run.italic = true
284 if (decoration.includes('underline')) {
285 run.underline = true
286 }
287 else if (rule) {
288 // An inline `border-bottom` IS an underline. Drawn as a separate line it
289 // has to be positioned against text PowerPoint may re-lay, and it cannot
290 // move when the text is edited, which is the whole point of this format.
291 run.underline = true
292 run.underlineStyle = rule
293 }
294 if (decoration.includes('line-through'))
295 run.strike = true
296 const color = withOpacity(parseColor(style.color, unparsed), opacity)
297 if (isVisible(color))
298 run.color = color
299 const spacing = parseLength(style.letterSpacing)
300 if (spacing)
301 run.letterSpacing = spacing
302 if (link)
303 run.link = link
304 return run
305 }
306
307 function boundsOf(rects: Rect[]): Rect {
308 const x = Math.min(...rects.map(r => r.x))
309 const y = Math.min(...rects.map(r => r.y))
310 return {
311 x,
312 y,
313 w: Math.max(...rects.map(r => r.x + r.w)) - x,
314 h: Math.max(...rects.map(r => r.y + r.h)) - y,
315 }
316 }
317
318 /**
319 * Group glyph rects into line boxes by vertical overlap, not by equal top: runs of
320 * different sizes on the same line align on the baseline, so their tops differ, and
321 * sub-pixel layout defeats rounding. A shared line overlaps by more than half the shorter rect.
322 */
323 function lineGroups(rects: Rect[]): { top: number, bottom: number }[] {
324 const groups: { top: number, bottom: number }[] = []
325 for (const rect of [...rects].sort((a, b) => a.y - b.y)) {
326 const current = groups[groups.length - 1]
327 const overlap = current
328 ? Math.min(current.bottom, rect.y + rect.h) - Math.max(current.top, rect.y)
329 : 0
330 if (current && overlap > 0.5 * Math.min(rect.h, current.bottom - current.top)) {
331 current.bottom = Math.max(current.bottom, rect.y + rect.h)
332 current.top = Math.min(current.top, rect.y)
333 }
334 else {
335 groups.push({ top: rect.y, bottom: rect.y + rect.h })
336 }
337 }
338 return groups
339 }
340
341 function countLines(rects: Rect[]): number {
342 return lineGroups(rects).length
343 }
344
345 /**
346 * How far apart the browser actually set the lines, or undefined for one line. The computed
347 * `line-height` is too small whenever a heading mixes sizes; the median keeps one
348 * unusually tall line from stretching the rest.
349 */
350 export function measuredLineHeight(rects: Rect[]): number | undefined {
351 const groups = lineGroups(rects)
352 if (groups.length < 2)
353 return undefined
354 const gaps = groups.slice(1).map((group, index) => group.top - groups[index].top)
355 gaps.sort((a, b) => a - b)
356 const median = gaps[Math.floor(gaps.length / 2)]
357 return median > 0
358 ? median
359 : undefined
360 }
361
362 /**
363 * The first non-inset `box-shadow`, as PowerPoint's polar form: an angle and a
364 * distance. Multiple shadows and inset shadows have no equivalent and are dropped.
365 */
366 export function parseShadow(value: string | undefined, unparsed?: UnparsedColors): IrBox['shadow'] {
367 if (!value || value === 'none' || value.includes('inset'))
368 return undefined
369 // Any functional color notation; `rgb()` included.
370 const color = parseColor(value.match(/^[a-z-]+\([^)]+\)/i)?.[0], unparsed)
371 if (!isVisible(color))
372 return undefined
373 const lengths = [
374 ...value.matchAll(/(-?[\d.]+)px/g),
375 ].map(m => Number(m[1]))
376 if (lengths.length < 2)
377 return undefined
378 const [x, y, blur = 0] = lengths
379 return {
380 blur,
381 offset: Math.round(Math.hypot(x, y) * 100) / 100,
382 // DrawingML measures clockwise from the positive x axis, like CSS's y-down space; no sign flip.
383 angle: Math.round(((Math.atan2(y, x) * 180) / Math.PI + 360) % 360),
384 color: color!,
385 }
386 }
387
388 /** One slide's `RawNode` tree to its `IrNode` list. Every helper below closes over the per-slide index and accumulators. */
389 function buildSlideIr(
390 slide: RawSlide,
391 styles: RawStyle[],
392 fontResolution: Record<string, string>,
393 unparsed: UnparsedColors,
394 ): { nodes: IrNode[], requests: RasterRequest[], rasterArea: number, textCount: number } {
395 const byId = new Map<number, RawNode>()
396 const childIndex = new Map<number, RawNode[]>()
397 let nodes: IrNode[] = []
398 const requests: RasterRequest[] = []
399 let rasterArea = 0
400 const pageRects = new Map<number, Rect | undefined>()
401 const boxed = new Set<number>()
402 /** Paint layer per emitted node, parallel to `nodes`. */
403 const layers: { tier: number, z: number }[] = []
404 /** Pseudo-element id to the id of the element it belongs to. */
405 const originators = new Map<number, number>()
406 const size = slide.size
407
408 for (const node of slide.nodes) {
409 byId.set(node.id, node)
410 const siblings = childIndex.get(node.parent) ?? []
411 siblings.push(node)
412 childIndex.set(node.parent, siblings)
413 }
414
415 /**
416 * Where an element paints: CSS puts positioned elements above in-flow content
417 * whatever the document order says. Two tiers and a z-index cover what a slide deck actually does.
418 */
419 function layerOf(node: RawNode): { tier: number, z: number } {
420 // The nearest positioned ancestor, not the nearest styled one: a page
421 // counter is a positioned `<footer>` wrapping a plain `<div>`.
422 let current: RawNode | undefined = node
423 while (current) {
424 const style = styleOf(current)
425 if (style && style.position !== 'static' && style.position !== '') {
426 const z = Number.parseInt(style.zIndex, 10)
427 return {
428 tier: 1,
429 z: Number.isNaN(z)
430 ? 0
431 : z,
432 }
433 }
434 current = byId.get(current.parent)
435 }
436 return { tier: 0, z: 0 }
437 }
438
439 function push(node: IrNode, source: RawNode): void {
440 nodes.push(node)
441 layers.push(layerOf(source))
442 }
443
444 function styleOf(node: RawNode): RawStyle | undefined {
445 return node.style >= 0
446 ? styles[node.style]
447 : undefined
448 }
449
450 function childrenOf(id: number): RawNode[] {
451 return childIndex.get(id) ?? []
452 }
453
454 /** The nearest ancestor element's style, which is what styles a text node. */
455 function inheritedStyle(node: RawNode): RawStyle | undefined {
456 let current: RawNode | undefined = node
457 while (current) {
458 const style = styleOf(current)
459 if (style)
460 return style
461 current = byId.get(current.parent)
462 }
463 return undefined
464 }
465
466 function linkFor(node: RawNode): string | undefined {
467 let current: RawNode | undefined = node
468 while (current) {
469 if (current.href)
470 return current.href
471 current = byId.get(current.parent)
472 }
473 return undefined
474 }
475
476 /** Whether an inline element paints something of its own behind its text. */
477 function hasDecoration(node: RawNode): boolean {
478 const style = styleOf(node)
479 if (!style)
480 return false
481 if (isVisible(withOpacity(parseColor(style.backgroundColor, unparsed), node.opacity)))
482 return true
483 return (['Top', 'Right', 'Bottom', 'Left'] as const).some(side => borderOf(style, side, unparsed))
484 }
485
486 function isInline(node: RawNode): boolean {
487 if (node.tag === '#text')
488 return true
489 const style = styleOf(node)
490 return !!style && INLINE_DISPLAY.test(style.display)
491 }
492
493 function run(): { nodes: IrNode[], requests: RasterRequest[], rasterArea: number, textCount: number } {
494 for (const root of childrenOf(-1))
495 visit(root)
496
497 // Everything downstream treats array order as paint order, so reorder into
498 // CSS paint order first; a stable sort keeps document order within a layer.
499 const order = nodes.map((node, index) => ({ node, index, layer: layers[index] }))
500 order.sort((a, b) =>
501 a.layer.tier - b.layer.tier || a.layer.z - b.layer.z || a.index - b.index)
502 nodes = order.map(entry => entry.node)
503
504 const texts = nodes.filter(n => n.kind === 'text')
505 // Picture over picture is not the doubling problem below: each is drawn from its own screenshot.
506 const drawnOver = nodes.filter(n => n.kind === 'text' || n.kind === 'image')
507
508 for (const node of nodes) {
509 if (node.kind !== 'raster')
510 continue
511
512 // `locator.screenshot()` clips the page rather than isolating, so
513 // anything also drawn as a shape inside this picture's box would print
514 // twice. Overlap tests that directly; the CSS reason was only a proxy.
515 const covered = drawnOver.some(other => overlaps(other.rect, node.rect))
516 if (covered)
517 node.isolate = true
518
519 requests.push({
520 sourceId: node.sourceId,
521 isolate: node.isolate,
522 hideDescendants: node.hideDescendants,
523 clip: pageRects.get(node.sourceId),
524 isolateId: originators.get(node.sourceId),
525 })
526
527 // Count only raster area with no editable text over it: a cover photo
528 // covers the whole slide by definition while its title vectorizes
529 // perfectly, and counting those sent every cover slide to the fallback.
530 if (texts.some(text => overlaps(text.rect, node.rect)))
531 continue
532 const visible = clipToSlide(node.rect, size)
533 if (visible)
534 rasterArea += visible.w * visible.h
535 }
536
537 return {
538 nodes,
539 requests,
540 rasterArea,
541 textCount: texts.length,
542 }
543 }
544
545 /** Whether a picture was actually emitted for this element. */
546 function emitRaster(node: RawNode, reason: RasterReason): boolean {
547 // A pseudo-element has no DOM node to screenshot, so it alone is captured
548 // by clipping the page at coordinates measured here; everything else is
549 // captured from its box read live at capture time, which cannot be stale.
550 if (node.tag === '::BEFORE' || node.tag === '::AFTER') {
551 pageRects.set(node.id, node.pageRect)
552 originators.set(node.id, node.parent)
553 }
554 const isolate = needsIsolation(reason)
555 const visible = clipToSlide(node.rect, size)
556 if (!visible)
557 return false
558 // An element that runs past the slide is captured as a page clip and
559 // placed at that same clipped rectangle so the picture is not squashed.
560 // Screenshotting it whole can ask Chromium to rasterize tens of millions
561 // of pixels, which kills the renderer.
562 const overflows = visible.w !== node.rect.w || visible.h !== node.rect.h
563 if (overflows && node.pageRect) {
564 pageRects.set(node.id, {
565 x: node.pageRect.x + (visible.x - node.rect.x),
566 y: node.pageRect.y + (visible.y - node.rect.y),
567 w: visible.w,
568 h: visible.h,
569 })
570 }
571
572 push({
573 kind: 'raster',
574 sourceId: node.id,
575 // Children are walked and redrawn only for a backdrop; only then is hiding them safe.
576 hideDescendants: isolate,
577 rect: overflows ? visible : node.rect,
578 data: '',
579 reason,
580 isolate,
581 }, node)
582 return true
583 }
584
585 function emitImage(node: RawNode): void {
586 if (!node.src)
587 return
588 // Clipped like every other shape, or a partly off-slide image lands outside the canvas.
589 const rect = clipToSlide(node.rect, size)
590 if (!rect)
591 return
592 // Show the visible part of an oversized image and crop the rest, as
593 // `overflow: hidden` does; scaling it to fit would compress it.
594 const clipped = rect.w !== node.rect.w || rect.h !== node.rect.h
595 push({
596 kind: 'image',
597 sourceId: node.id,
598 rect,
599 data: node.src,
600 alt: node.alt,
601 link: linkFor(node),
602 ...(clipped
603 ? {
604 crop: {
605 x: rect.x - node.rect.x,
606 y: rect.y - node.rect.y,
607 w: node.rect.w,
608 h: node.rect.h,
609 },
610 }
611 : {}),
612 }, node)
613 }
614
615 function emitBox(node: RawNode, style: RawStyle): void {
616 // `emitTextGroup` and `visit` can both reach the same node; two
617 // translucent fills would composite visibly darker.
618 if (boxed.has(node.id))
619 return
620 boxed.add(node.id)
621 const fill = withOpacity(parseColor(style.backgroundColor, unparsed), node.opacity)
622 const borders: [Border?, Border?, Border?, Border?] = [
623 borderOf(style, 'Top', unparsed),
624 borderOf(style, 'Right', unparsed),
625 borderOf(style, 'Bottom', unparsed),
626 borderOf(style, 'Left', unparsed),
627 ]
628 const hasBorder = borders.some(Boolean)
629 // Chromium keeps `border-radius` percentages in the computed value, so a
630 // basis is needed: `border-radius: 50%` on a 200px box is 100px, not 50px.
631 const radius = parseLength(style.borderTopLeftRadius, Math.min(node.rect.w, node.rect.h))
632 if (!isVisible(fill) && !hasBorder)
633 return
634 const shadow = parseShadow(style.boxShadow, unparsed)
635 // One shape per line fragment for a wrapped inline element, as the browser
636 // paints; one rect over the union would fill the ragged line ends.
637 const boxes = node.fragments?.length
638 ? node.fragments
639 : [node.rect]
640 for (const source of boxes) {
641 const rect = clipToSlide(source, size)
642 if (!rect)
643 continue
644 const box: IrBox = { kind: 'box', sourceId: node.id, rect }
645 if (isVisible(fill))
646 box.fill = fill
647 if (hasBorder)
648 box.borders = borders
649 if (radius > 0)
650 box.radius = radius
651 if (shadow)
652 box.shadow = shadow
653 push(box, node)
654 }
655 }
656
657 function visit(node: RawNode): void {
658 // A pseudo-element paints either an image or a short string, and has no children.
659 if (node.tag === '::BEFORE' || node.tag === '::AFTER') {
660 const style = styleOf(node)
661 if (!style)
662 return
663 const reason = rasterReasonFor(node, style)
664 if (reason && emitRaster(node, reason))
665 return
666 emitBox(node, style)
667 if (node.text) {
668 push({
669 kind: 'text',
670 sourceId: node.id,
671 rect: node.rect,
672 elementRect: node.rect,
673 lineCount: 1,
674 align: alignOf(style),
675 valign: 'middle',
676 lineHeight: resolveLineHeight(style),
677 runs: [
678 runFrom(node.text, style, fontResolution, unparsed),
679 ],
680 }, node)
681 }
682 return
683 }
684
685 if (node.tag === '#text') {
686 // Reached only when a text node has no block container of its own; guarded so a stray one is not lost.
687 emitTextGroup([node])
688 return
689 }
690
691 const style = styleOf(node)
692 const reason = rasterReasonFor(node, style)
693 // Treat the element as rasterized only when a picture was actually placed:
694 // a zero-sized wrapper has no box of its own while its positioned
695 // descendants do, and dropping the subtree would lose them.
696 if (reason && emitRaster(node, reason)) {
697 // A leaf such as an <svg> has no shapes worth recovering underneath it;
698 // a backdrop does, its children being drawn on top of the isolated picture.
699 if (!needsIsolation(reason))
700 return
701 // But not its own box: the screenshot already contains this element's
702 // background and borders, so drawing them again composites twice.
703 visitChildren(node)
704 return
705 }
706
707 if (style)
708 emitBox(node, style)
709
710 if (node.tag === 'IMG') {
711 emitImage(node)
712 return
713 }
714
715 // A ::marker is a pseudo-element: the bullet glyph has no text node, so a
716 // plain walk drops every bullet in the deck.
717 if (node.marker && style) {
718 const markerRect: Rect = {
719 x: Math.max(0, node.rect.x - parseLength(style.fontSize) * 1.2),
720 y: node.rect.y,
721 w: parseLength(style.fontSize) * 1.2,
722 h: resolveLineHeight(style),
723 }
724 push({
725 kind: 'text',
726 sourceId: node.id,
727 rect: markerRect,
728 elementRect: markerRect,
729 lineCount: 1,
730 align: 'left',
731 // Centered in the line box, where a browser puts a marker; anchored to
732 // the top it rides above its own item's first line.
733 valign: 'middle',
734 lineHeight: resolveLineHeight(style),
735 runs: [
736 runFrom(node.marker, style, fontResolution, unparsed, undefined, node.opacity),
737 ],
738 }, node)
739 }
740
741 visitChildren(node)
742 }
743
744 function visitChildren(node: RawNode): void {
745 const style = styleOf(node)
746 const children = childrenOf(node.id)
747 if (!children.length)
748 return
749
750 // A grid or flex container lays its children out as boxes; grouping them
751 // as one run of text concatenates unrelated cells.
752 if (style && LAYOUT_DISPLAY.test(style.display)) {
753 for (const child of children)
754 visit(child)
755 return
756 }
757
758 // Consecutive inline children form one anonymous block box, which is one
759 // text box; one shape each would lay out from the same origin and overlap.
760 let group: RawNode[] = []
761 const flush = () => {
762 if (group.length) {
763 emitTextGroup(group)
764 group = []
765 }
766 }
767 // A chip is padded and spaced by its own box, which flowed text cannot
768 // reproduce: `<kbd>right</kbd> / <kbd>space</kbd>` set as one run drifts
769 // off keys that keep their measured gaps, and two adjacent chips run their
770 // labels together entirely. So each part of a row of chips is placed on
771 // its own glyph bounds instead.
772 //
773 // Only when the row occupies a single line. Fragments can be positioned
774 // exactly while they do not wrap; a wrapping sentence has to flow, or its
775 // halves lay out from the same origin and overlap. That is also what keeps
776 // an ordinary sentence carrying one inline `<code>` in one editable box.
777 // Glyph bounds for a text node: its element rect is not where its ink is.
778 const lineBox = (child: RawNode): Rect =>
779 child.glyphRects?.length
780 ? boundsOf(child.glyphRects)
781 : child.rect
782 const placed = children.filter(child => isInline(child) && lineBox(child).h > 0)
783 // By overlap, not by matching tops: a padded chip's box starts above the
784 // glyph bounds of the text beside it, so equal tops never held here.
785 const oneLine = placed.length > 1 && lineGroups(placed.map(lineBox)).length === 1
786 // Everything outside the chips. A separator is punctuation; a sentence is
787 // words, and a sentence stays one editable box even though its inline
788 // `<code>` drifts by the width of its own padding.
789 const loose = children
790 .filter(child => child.tag === '#text')
791 .map(child => (child.text ?? '').replace(/\s+/g, ''))
792 .join('')
793 const labelRow = oneLine && loose.length <= SEPARATOR_MAX_CHARS
794 && placed.some(child => hasDecoration(child))
795
796 for (const child of children) {
797 if (isInline(child)) {
798 // An inline element carrying its own background or border is a chip: its
799 // decoration is a positioned shape, so its label gets its own text box anchored
800 // to the glyph bounds, keeping metric differences from sliding the label off
801 // the chip. Only when it stands alone: Slidev styles inline `<code>` with a
802 // background, and an unconditional split overlaps a wrapped sentence.
803 if (labelRow || (hasDecoration(child) && children.length === 1)) {
804 flush()
805 emitTextGroup([child], labelRow)
806 continue
807 }
808 group.push(child)
809 }
810 else {
811 flush()
812 visit(child)
813 }
814 }
815 flush()
816 }
817
818 /** Every text node under an inline subtree, in document order. */
819 function collectText(node: RawNode, out: RawNode[]): void {
820 if (node.tag === '#text') {
821 out.push(node)
822 return
823 }
824 const style = styleOf(node)
825 const reason = rasterReasonFor(node, style)
826 // An inline <svg> icon still becomes a picture, but only if it has a box;
827 // otherwise its subtree is walked as usual rather than dropped.
828 if (reason && emitRaster(node, reason))
829 return
830 // A <br> has no text node of its own, so without this marker the text on
831 // either side of it concatenates with no break.
832 if (node.tag === 'BR') {
833 out.push(node)
834 return
835 }
836 // An inline <img> reaches here rather than `visit`; drawn at its measured box.
837 if (node.tag === 'IMG') {
838 emitImage(node)
839 return
840 }
841 // Anything that is not inline establishes its own box rather than flowing
842 // with the text around it, so it lays out on its own instead of being
843 // folded into this paragraph. Shiki's `<code>` is `display: inline` and
844 // TwoSlash renders a diagnostic as a `<div>` inside it, which ran the
845 // message onto the end of the code line: "= 2Cannot assign to 'value'".
846 //
847 // Not the same test as `visitChildren` makes. There `LAYOUT_DISPLAY` asks
848 // whether to stop grouping children, which a `table-cell` must not do.
849 // Here the question is only whether this subtree flows with its
850 // surroundings, and no non-inline box does.
851 if (style && !isInline(node)) {
852 visit(node)
853 return
854 }
855 for (const child of childrenOf(node.id))
856 collectText(child, out)
857 }
858
859 /**
860 * The underline an inline element draws with `border-bottom`, if that is all
861 * it draws. Slidev rules its links this way.
862 *
863 * Only when the bottom is the only border and there is no fill: anything
864 * more is a box, and a box has to stay a shape.
865 */
866 function underlineRule(node: RawNode): IrRun['underlineStyle'] | undefined {
867 const style = styleOf(node)
868 if (!style || !isInline(node))
869 return undefined
870 if (isVisible(parseColor(style.backgroundColor, unparsed)))
871 return undefined
872 const bottom = borderOf(style, 'Bottom', unparsed)
873 if (!bottom)
874 return undefined
875 for (const side of ['Top', 'Right', 'Left'] as const) {
876 if (borderOf(style, side, unparsed))
877 return undefined
878 }
879 return bottom.style === 'dashed'
880 ? 'dash'
881 : bottom.style === 'dotted'
882 ? 'dotted'
883 : 'sng'
884 }
885
886 /** The underline rule an ancestor of this text node draws, if any. */
887 function ruleOver(node: RawNode): IrRun['underlineStyle'] | undefined {
888 let current: RawNode | undefined = byId.get(node.parent)
889 while (current) {
890 const rule = underlineRule(current)
891 if (rule)
892 return rule
893 current = byId.get(current.parent)
894 }
895 return undefined
896 }
897
898 function emitTextGroup(group: RawNode[], fragment = false): void {
899 // Inline decorations first: paint order is array order, so a chip emitted
900 // after its label would cover it.
901 for (const node of group) {
902 if (node.tag === '#text')
903 continue
904 // The group node itself too: the chip is usually the outermost inline element in the group.
905 const own = styleOf(node)
906 // A node whose only decoration is an underline is drawn by the run.
907 if (underlineRule(node))
908 boxed.add(node.id)
909 if (own)
910 emitBox(node, own)
911 forEachDescendant(node, (descendant) => {
912 const style = styleOf(descendant)
913 if (style)
914 emitBox(descendant, style)
915 })
916 }
917
918 const textNodes: RawNode[] = []
919 for (const node of group)
920 collectText(node, textNodes)
921 if (!textNodes.length)
922 return
923
924 const runs: IrRun[] = []
925 const rects: Rect[] = []
926
927 /**
928 * Line breaks waiting for the next run; a count, since two consecutive `<br>` need an
929 * empty run between them. Held against the next run so a trailing break does not add an empty last line.
930 */
931 let pendingBreaks = 0
932
933 const addRun = (text: string, style: RawStyle, node: RawNode) => {
934 // One empty run per surplus break, so the blank lines survive.
935 while (pendingBreaks > 1 && runs.length) {
936 runs.push({
937 ...runFrom('', style, fontResolution, unparsed, undefined, node.opacity),
938 breakBefore: true,
939 })
940 pendingBreaks--
941 }
942 const newRun = runFrom(text, style, fontResolution, unparsed, linkFor(node), node.opacity, ruleOver(node))
943 if (pendingBreaks && runs.length)
944 newRun.breakBefore = true
945 pendingBreaks = 0
946 runs.push(newRun)
947 }
948
949 for (const textNode of textNodes) {
950 if (textNode.tag === 'BR') {
951 pendingBreaks++
952 continue
953 }
954 const style = inheritedStyle(textNode)
955 if (!style)
956 continue
957 const raw = textNode.text ?? ''
958 if (!raw)
959 continue
960
961 // `white-space: pre` keeps its newlines, the only record of where a code
962 // block's lines end: Shiki separates line spans with "\n" text nodes, so
963 // folding them into spaces re-wraps the block into one paragraph.
964 if (style.whiteSpace.startsWith('pre')) {
965 const lines = raw.split('\n')
966 lines.forEach((line, index) => {
967 if (index > 0)
968 pendingBreaks++
969 if (line)
970 addRun(line, style, textNode)
971 })
972 rects.push(...(textNode.glyphRects ?? []))
973 continue
974 }
975
976 const text = raw.replace(/\s+/g, ' ')
977 if (!text.trim()) {
978 // A whitespace-only node is the space between two inline elements;
979 // folded into the previous run so it keeps no styling of its own.
980 if (runs.length && !runs[runs.length - 1].text.endsWith(' '))
981 runs[runs.length - 1].text += ' '
982 continue
983 }
984 addRun(text, style, textNode)
985 rects.push(...(textNode.glyphRects ?? [textNode.rect]))
986 }
987 if (!runs.length || !rects.length)
988 return
989
990 // Whitespace at line boundaries collapses in the browser but survives the
991 // fold above and shifts a centered line by half a space. Every line
992 // boundary counts, not just the box edges: a run after a break opens a new line.
993 // Not for a fragment: its edges are mid-line, where the browser rendered
994 // the spaces and the glyph bounds include them. Trimming there drew the
995 // text where the leading space had been, putting a separator on the key
996 // beside it.
997 if (!fragment) {
998 runs.forEach((run, index) => {
999 const opensLine = index === 0 || run.breakBefore
1000 const closesLine = index === runs.length - 1 || runs[index + 1]?.breakBefore
1001 if (opensLine)
1002 run.text = run.text.replace(/^ +/, '')
1003 if (closesLine)
1004 run.text = run.text.replace(/ +$/, '')
1005 })
1006 }
1007
1008 const container = byId.get(group[0].parent)
1009 const containerStyle = container
1010 ? styleOf(container)
1011 : undefined
1012 const anchorStyle = containerStyle ?? inheritedStyle(textNodes[0])!
1013
1014 const glyphs = boundsOf(rects)
1015 const lineCount = countLines(rects)
1016
1017 /**
1018 * The box PowerPoint will wrap inside. Wrapped text's glyph bounds are the width of
1019 * the longest line, which guarantees a second, tighter wrap; the browser wrapped
1020 * against the container's content box, so reproduce that. Single-line text keeps its exact glyph bounds.
1021 */
1022 let rect = glyphs
1023 let align = alignOf(anchorStyle)
1024
1025 /** Widen a box that has no room for PowerPoint's wider metrics. */
1026 const withHeadroom = (box: Rect): Rect => {
1027 const headroom = box.w - glyphs.w
1028 const wanted = Math.max(WRAP_HEADROOM_MIN_PX, glyphs.w * WRAP_HEADROOM)
1029 if (headroom >= wanted)
1030 return box
1031 const extra = wanted - Math.max(0, headroom)
1032 // Grown about the anchor, so the text does not slide sideways.
1033 const x = align === 'center'
1034 ? box.x - extra / 2
1035 : align === 'right'
1036 ? box.x - extra
1037 : box.x
1038 return {
1039 x,
1040 y: box.y,
1041 w: box.w + extra,
1042 h: box.h,
1043 }
1044 }
1045 let valign: IrText['valign']
1046
1047 /**
1048 * A chip label is pinned to its chip's box and centered there, keeping the inset even
1049 * however the font measures; positioned from the glyphs it ends hard against one edge
1050 * as soon as PowerPoint sets the string wider.
1051 */
1052 const decorated = group.length === 1 && group[0].tag !== '#text' && hasDecoration(group[0])
1053 if (decorated) {
1054 rect = group[0].rect
1055 align = 'center'
1056 valign = 'middle'
1057 }
1058 else if (lineCount > 1 && container && containerStyle) {
1059 const left = parseLength(containerStyle.paddingLeft)
1060 const right = parseLength(containerStyle.paddingRight)
1061 const width = container.rect.w - left - right
1062 if (width > 0) {
1063 rect = withHeadroom({
1064 x: container.rect.x + left,
1065 y: glyphs.y,
1066 w: width,
1067 h: glyphs.h,
1068 })
1069 }
1070 }
1071
1072 // Clipped like every other node, or browser-clipped text lands off the
1073 // canvas while still suppressing the whole-slide fallback.
1074 if (!clipToSlide(rect, size))
1075 return
1076
1077 push({
1078 kind: 'text',
1079 sourceId: group[0].id,
1080 rect,
1081 elementRect: container?.rect ?? glyphs,
1082 lineCount,
1083 align,
1084 valign,
1085 lineHeight: measuredLineHeight(rects) ?? resolveLineHeight(anchorStyle),
1086 runs,
1087 }, group[0])
1088 }
1089
1090 function forEachDescendant(node: RawNode, fn: (node: RawNode) => void): void {
1091 for (const child of childrenOf(node.id)) {
1092 if (child.tag !== '#text')
1093 fn(child)
1094 forEachDescendant(child, fn)
1095 }
1096 }
1097
1098 return run()
1099 }
1100
1101 export function normalize(snapshot: RawSnapshot, options: NormalizeOptions): NormalizeResult {
1102 const unparsedColors = new Set<string>()
1103 const slides: SlideIr[] = []
1104 const rasterRequests: RasterRequest[] = []
1105
1106 for (const raw of snapshot.slides) {
1107 const { nodes, requests, rasterArea, textCount } = buildSlideIr(raw, snapshot.styles, snapshot.fontResolution, unparsedColors)
1108
1109 const ir: SlideIr = {
1110 no: raw.no,
1111 clickIndex: raw.clickIndex,
1112 containerId: raw.containerId,
1113 size: raw.size,
1114 // Without the slide's own background, a dark theme exports as light text
1115 // on PowerPoint's default white.
1116 background: parseColor(raw.background, unparsedColors),
1117 nodes,
1118 note: options.notes.get(raw.no),
1119 }
1120
1121 const slideArea = raw.size.w * raw.size.h
1122 const hasSourceText = raw.nodes.some(n => n.tag === '#text' && (n.text ?? '').trim())
1123
1124 // Both conditions describe a slide where vectorizing produced something
1125 // worse than the picture it replaced; degrade to what `--format pptx` does.
1126 if (hasSourceText && textCount === 0) {
1127 ir.fallbackReason = 'no text could be recovered from a slide that has text'
1128 }
1129 else if (slideArea > 0 && rasterArea / slideArea > RASTER_AREA_LIMIT) {
1130 // Capped: rasters can overlap, so the raw sum can exceed the slide.
1131 const percent = Math.min(100, Math.round((rasterArea / slideArea) * 100))
1132 ir.fallbackReason = `${percent}% of the slide had to be rasterized`
1133 }
1134
1135 if (!ir.fallbackReason)
1136 rasterRequests.push(...requests)
1137
1138 slides.push(ir)
1139 }
1140
1141 return {
1142 slides,
1143 rasterRequests,
1144 unparsedColors: [...unparsedColors].sort(),
1145 }
1146 }
1147
1147 lines TYPESCRIPT