decklight 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/PLATFORM.md +666 -0
  2. package/README.md +224 -150
  3. package/SPEC.md +732 -886
  4. package/cli/agent-review.mjs +245 -0
  5. package/cli/agents.mjs +25 -5
  6. package/cli/associate.mjs +12 -12
  7. package/cli/audit.mjs +42 -10
  8. package/cli/banner.mjs +41 -17
  9. package/cli/bundle-audio.mjs +183 -0
  10. package/cli/bundle.mjs +383 -31
  11. package/cli/cast.mjs +7 -7
  12. package/cli/check.mjs +961 -0
  13. package/cli/clone-deck.mjs +179 -0
  14. package/cli/commands.mjs +345 -0
  15. package/cli/comments.mjs +64 -18
  16. package/cli/commit-flow.mjs +44 -19
  17. package/cli/commit-message.mjs +51 -74
  18. package/cli/commit-split.mjs +601 -0
  19. package/cli/deck-refs.mjs +59 -0
  20. package/cli/deck-routes.mjs +67 -0
  21. package/cli/deckfile.mjs +3 -5
  22. package/cli/decklight.mjs +68 -289
  23. package/cli/design-system-deps.mjs +209 -0
  24. package/cli/design-system-edit.mjs +194 -0
  25. package/cli/design-system-refs.mjs +409 -0
  26. package/cli/design-system.mjs +429 -0
  27. package/cli/doctor.mjs +115 -0
  28. package/cli/edit-git.mjs +353 -0
  29. package/cli/edit-handover.mjs +445 -0
  30. package/cli/edit-look.mjs +388 -0
  31. package/cli/edit-slides.mjs +683 -0
  32. package/cli/edit.mjs +2126 -842
  33. package/cli/enhance.mjs +483 -0
  34. package/cli/extension.mjs +10 -10
  35. package/cli/font-refs.mjs +273 -0
  36. package/cli/font.mjs +246 -0
  37. package/cli/git-tree.mjs +1 -1
  38. package/cli/git.mjs +65 -11
  39. package/cli/import.mjs +56 -10
  40. package/cli/init.mjs +400 -234
  41. package/cli/library.mjs +127 -0
  42. package/cli/loader.mjs +3 -1
  43. package/cli/marketplace.mjs +215 -21
  44. package/cli/narrate.mjs +176 -0
  45. package/cli/open-browser.mjs +63 -0
  46. package/cli/open.mjs +943 -0
  47. package/cli/pdf.mjs +41 -13
  48. package/cli/pkg.mjs +44 -2
  49. package/cli/plugin.mjs +43 -41
  50. package/cli/port-conflict.mjs +53 -23
  51. package/cli/pptx-export.mjs +71 -26
  52. package/cli/publish.mjs +8 -4
  53. package/cli/qr.mjs +1 -1
  54. package/cli/record.mjs +14 -12
  55. package/cli/remote.mjs +11 -11
  56. package/cli/restore.mjs +11 -4
  57. package/cli/review-ref.mjs +125 -0
  58. package/cli/review-remote.mjs +92 -48
  59. package/cli/review-routes.mjs +254 -0
  60. package/cli/review-store.mjs +47 -7
  61. package/cli/review-submit.mjs +47 -57
  62. package/cli/runtime-link.mjs +560 -0
  63. package/cli/serve.mjs +235 -44
  64. package/cli/setup.mjs +112 -0
  65. package/cli/sign.mjs +1 -1
  66. package/cli/skill-content.mjs +190 -33
  67. package/cli/skills.mjs +107 -24
  68. package/cli/start.mjs +110 -0
  69. package/cli/supervise.mjs +6 -6
  70. package/cli/theme-refs.mjs +515 -0
  71. package/cli/theme.mjs +181 -137
  72. package/cli/trust.mjs +83 -0
  73. package/cli/units.mjs +39 -42
  74. package/cli/update-check.mjs +1 -5
  75. package/cli/upgrade.mjs +194 -28
  76. package/cli/upstream.mjs +4 -3
  77. package/cli/util.mjs +4 -4
  78. package/cli/wizard.mjs +6 -6
  79. package/dist/build-info.json +1 -1
  80. package/dist/decklight.css +1126 -49
  81. package/dist/decklight.js +212 -115
  82. package/dist/decklight.js.map +4 -4
  83. package/docs/GLOSSARY.md +141 -0
  84. package/docs/architecture.svg +17 -17
  85. package/package.json +4 -2
  86. package/themes/README.md +9 -8
  87. package/themes/reveal-solarized.css +10 -0
  88. package/tools/args.mjs +20 -0
  89. package/tools/atomic-write.mjs +48 -0
  90. package/tools/brand-palette.mjs +717 -0
  91. package/tools/bridge.mjs +1 -1
  92. package/tools/build-groups.mjs +42 -0
  93. package/tools/color.mjs +48 -0
  94. package/tools/deck-html.mjs +396 -11
  95. package/tools/design-system-format.mjs +753 -0
  96. package/tools/elevenlabs-tts.mjs +110 -17
  97. package/tools/exec.mjs +35 -2
  98. package/tools/extension-check.mjs +31 -7
  99. package/tools/font-format.mjs +190 -0
  100. package/tools/font-stacks.mjs +24 -0
  101. package/tools/gemini-tts.mjs +3 -0
  102. package/tools/lipsync-config.mjs +103 -0
  103. package/tools/lipsync-engines.mjs +205 -2
  104. package/tools/lipsync-server.mjs +264 -41
  105. package/tools/lipsync.mjs +37 -18
  106. package/tools/local-voice.mjs +32 -42
  107. package/tools/narration-manifest.mjs +196 -0
  108. package/tools/narration-synth.mjs +416 -0
  109. package/tools/pptx.mjs +776 -19
  110. package/tools/publish-targets.mjs +1 -1
  111. package/tools/publish-voices.mjs +3 -3
  112. package/tools/recording-impact.mjs +7 -3
  113. package/tools/render-theme.mjs +33 -0
  114. package/tools/review-anchor.mjs +28 -12
  115. package/tools/semver.mjs +40 -0
  116. package/tools/sentences.mjs +180 -0
  117. package/tools/shot.mjs +14 -7
  118. package/tools/site-voices.mjs +232 -0
  119. package/tools/template-theme.mjs +1 -1
  120. package/tools/test-impact.mjs +19 -10
  121. package/tools/theme-check.mjs +30 -3
  122. package/tools/tts-cache.mjs +4 -3
  123. package/tools/tts-engines.mjs +38 -20
  124. package/tools/tts-setup.mjs +7 -7
  125. package/tools/video-options.mjs +34 -0
  126. package/tools/video.mjs +461 -48
  127. package/tools/voiceover-server.mjs +185 -104
  128. package/tools/voiceover.mjs +119 -261
  129. package/tools/zip.mjs +1 -1
  130. package/cli/dev.mjs +0 -623
  131. package/cli/present.mjs +0 -853
  132. package/cli/review.mjs +0 -361
  133. package/tools/publish-site-voices.mjs +0 -75
package/tools/pptx.mjs CHANGED
@@ -167,7 +167,9 @@ export function tableHtml(tbl, { rels } = {}) {
167
167
  const GRAPHIC = {
168
168
  table: null, // handled
169
169
  chart: 'chart dropped — rebuild as data-chart (SPEC CHARTS)',
170
- diagram: 'SmartArt dropped — rebuild as an SVG diagram (SPEC SVG_DIAGRAMS)',
170
+ // Only when its data model cannot be read at all — otherwise the words
171
+ // cross, and often the shape with them (parseDiagram, below).
172
+ diagram: 'SmartArt dropped — its data could not be read; rebuild as an SVG diagram (SPEC SVG_DIAGRAMS)',
171
173
  };
172
174
 
173
175
  /** OOXML chart element → data-chart type. Anything else is still a drop. */
@@ -177,8 +179,16 @@ const CHART_TYPES = {
177
179
  'c:areaChart': 'area', 'c:area3DChart': 'area',
178
180
  'c:pieChart': 'pie', 'c:pie3DChart': 'pie',
179
181
  'c:doughnutChart': 'donut',
182
+ // x/y pairs rather than a value per category — read from c:xVal/c:yVal below
183
+ 'c:scatterChart': 'scatter',
180
184
  };
181
185
 
186
+ /** A chart part's own title, as plain text — '' when it has none. */
187
+ function titleOfChart(doc) {
188
+ const node = find(doc, 'c:title');
189
+ return node ? findAll(node, 'a:t').map((t) => textOf(t)).join('').trim() : '';
190
+ }
191
+
182
192
  /** The `c:pt` values of a cache, in index order; numbers where they parse. */
183
193
  function cachePoints(node, numeric) {
184
194
  const pts = findAll(node, 'c:pt').map((pt) => [Number(pt.attrs.idx ?? 0), textOf(find(pt, 'c:v') ?? pt).trim()]);
@@ -209,6 +219,18 @@ export function parseChart(xml) {
209
219
  const series = findAll(kindNode, 'c:ser').map((ser, i) => {
210
220
  const tx = find(ser, 'c:tx');
211
221
  const name = tx ? textOf(tx).trim() : `series ${i + 1}`;
222
+ if (type === 'scatter') {
223
+ // A scatter's x is a MEASUREMENT, in its own cache, so the pairing is
224
+ // by index: the k-th x goes with the k-th y, and a series missing
225
+ // either of them has no points rather than points at zero.
226
+ const xs = find(ser, 'c:xVal');
227
+ const ys = find(ser, 'c:yVal');
228
+ const xv = xs ? cachePoints(xs, true) : [];
229
+ const yv = ys ? cachePoints(ys, true) : [];
230
+ const points = xv.map((x, k) => [x, yv[k]])
231
+ .filter(([x, y]) => Number.isFinite(x) && Number.isFinite(y));
232
+ return { name: name || `series ${i + 1}`, labels: [], data: [], points };
233
+ }
212
234
  const cat = find(ser, 'c:cat');
213
235
  const val = find(ser, 'c:val');
214
236
  return {
@@ -216,11 +238,26 @@ export function parseChart(xml) {
216
238
  labels: cat ? cachePoints(cat, false) : [],
217
239
  data: val ? cachePoints(val, true).map((n) => (Number.isFinite(n) ? n : 0)) : [],
218
240
  };
219
- }).filter((sr) => sr.data.length);
241
+ }).filter((sr) => (type === 'scatter' ? sr.points.length : sr.data.length));
220
242
  if (!series.length) return null;
243
+ if (type === 'scatter') {
244
+ // The axis titles are the chart's own, where it has them: a scatter with
245
+ // two unnamed numeric axes is a picture of nothing in particular.
246
+ const axisTitle = (i) => {
247
+ const ax = findAll(doc, 'c:valAx')[i];
248
+ const t = ax && find(ax, 'c:title');
249
+ return t ? findAll(t, 'a:t').map((n) => textOf(n)).join('').trim() || null : null;
250
+ };
251
+ return {
252
+ type,
253
+ title: titleOfChart(doc),
254
+ x: axisTitle(0),
255
+ y: axisTitle(1),
256
+ series: series.map(({ name, points }) => ({ name, points })),
257
+ };
258
+ }
221
259
  const labels = series.find((sr) => sr.labels.length)?.labels ?? series[0].data.map((_, i) => String(i + 1));
222
- const titleNode = find(doc, 'c:title');
223
- const title = titleNode ? findAll(titleNode, 'a:t').map((t) => textOf(t)).join('').trim() : '';
260
+ const title = titleOfChart(doc);
224
261
  return {
225
262
  type,
226
263
  title,
@@ -231,6 +268,576 @@ export function parseChart(xml) {
231
268
  };
232
269
  }
233
270
 
271
+ // ── SmartArt ────────────────────────────────────────────────────────────────
272
+ //
273
+ // A SmartArt graphic is three parts: a DATA model (the words, and how they
274
+ // relate), a LAYOUT (which picture PowerPoint chose to draw of them), and a
275
+ // drawing cache that is a rendering of the first two and worth nothing here.
276
+ //
277
+ // It used to be a loud drop, and loud was right — but the words were always
278
+ // crossable, and a slide whose whole content is one SmartArt graphic came
279
+ // across EMPTY, with a line underneath saying so. Now the words always cross;
280
+ // the shape crosses when decklight can draw it.
281
+
282
+ /** Which picture PowerPoint was drawing, read from the layout part's own id. */
283
+ export function diagramKind(layoutXml) {
284
+ const id = find(parseXml(layoutXml ?? ''), 'dgm:layoutDef')?.attrs.uniqueId ?? '';
285
+ const name = id.split('/').pop().toLowerCase();
286
+ if (/cycle|gear|radial/.test(name)) return 'cycle';
287
+ if (/hierarchy|orgchart|org\d/.test(name)) return 'hierarchy';
288
+ if (/process|chevron|arrow|step|funnel|timeline/.test(name)) return 'process';
289
+ return 'list';
290
+ }
291
+
292
+ /**
293
+ * The data model as a tree of `{ text, plain, children }`.
294
+ *
295
+ * Two things make this less obvious than it looks. The point list carries
296
+ * PRESENTATION points beside the content ones — the boxes and connectors the
297
+ * chosen layout needed — and importing those would put the drawing's scaffolding
298
+ * on the slide as words. And the nesting is not in the XML's shape: it is in a
299
+ * separate connection list, where `parOf` links a parent to a child and `srcOrd`
300
+ * is the order, so the tree has to be rebuilt from the edges.
301
+ */
302
+ export function parseDiagram(dataXml, { rels } = {}) {
303
+ const doc = parseXml(dataXml ?? '');
304
+ const pts = new Map();
305
+ let rootId = null;
306
+ for (const pt of findAll(doc, 'dgm:pt')) {
307
+ const id = pt.attrs.modelId;
308
+ if (!id) continue;
309
+ const type = pt.attrs.type ?? 'node';
310
+ if (type === 'doc') { rootId = id; continue; }
311
+ // `pres` is the layout's own scaffolding; parTrans/sibTrans are the text
312
+ // ON a connector, which is a label for an edge and not a node of its own.
313
+ if (type !== 'node' && type !== 'asst') continue;
314
+ const t = find(pt, 'dgm:t');
315
+ const paras = t ? children(t, 'a:p') : [];
316
+ pts.set(id, {
317
+ text: paras.map((q) => paragraphHtml(q, { rels })).filter(Boolean).join(' '),
318
+ plain: t ? textOf(t).replace(/\s+/g, ' ').trim() : '',
319
+ children: [],
320
+ });
321
+ }
322
+ const kids = new Map();
323
+ for (const cxn of findAll(doc, 'dgm:cxn')) {
324
+ if ((cxn.attrs.type ?? 'parOf') !== 'parOf') continue;
325
+ const { srcId, destId } = cxn.attrs;
326
+ if (!srcId || !destId || !pts.has(destId)) continue;
327
+ if (!kids.has(srcId)) kids.set(srcId, []);
328
+ kids.get(srcId).push({ ord: Number(cxn.attrs.srcOrd ?? 0), id: destId });
329
+ }
330
+ // `seen` is not defensive tidiness: a malformed or circular connection list
331
+ // would otherwise recurse until the stack ends, on a file nobody can inspect.
332
+ const build = (id, seen) => (kids.get(id) ?? [])
333
+ .slice()
334
+ .sort((a, b) => a.ord - b.ord)
335
+ .filter((k) => !seen.has(k.id))
336
+ .map((k) => {
337
+ seen.add(k.id);
338
+ const node = pts.get(k.id);
339
+ return { ...node, children: build(k.id, seen) };
340
+ })
341
+ .filter((node) => node.text || node.children.length);
342
+ return rootId ? build(rootId, new Set([rootId])) : [];
343
+ }
344
+
345
+ /** Text as `<tspan>` lines, wrapped to a width in characters. */
346
+ function wrapLines(text, chars) {
347
+ const lines = [];
348
+ let line = '';
349
+ for (const word of text.split(/\s+/).filter(Boolean)) {
350
+ if (!line) line = word;
351
+ else if (line.length + 1 + word.length <= chars) line += ` ${word}`;
352
+ else { lines.push(line); line = word; }
353
+ }
354
+ if (line) lines.push(line);
355
+ return lines;
356
+ }
357
+
358
+ const flat = (nodes) => nodes.every((n) => !n.children.length);
359
+
360
+ /**
361
+ * A flat sequence as an SVG strip — one box per step, an arrow between each.
362
+ *
363
+ * `cycle` is the same strip with the last arrow curving back under it to the
364
+ * first box, which is what a cycle IS once it is on a page that reads left to
365
+ * right. Drawing a ring instead would look more like PowerPoint and read worse
366
+ * at the back of a room.
367
+ */
368
+ export function diagramSvg(nodes, kind) {
369
+ const W = 960, H = kind === 'cycle' ? 168 : 120, GAP = 30, TOP = 14, BOX_H = 84;
370
+ const n = nodes.length;
371
+ const boxW = Math.round((W - GAP * (n - 1)) / n);
372
+ const chars = Math.max(8, Math.floor(boxW / 8.4));
373
+ const arrow = `<defs><marker id="dgm-arrow" markerWidth="6" markerHeight="4" refX="5" refY="2" orient="auto">`
374
+ + `<polygon points="0 0, 6 2, 0 4" style="fill: var(--d-stroke)"/></marker></defs>`;
375
+ const groups = nodes.map((node, i) => {
376
+ const x = i * (boxW + GAP);
377
+ const mid = x + boxW / 2;
378
+ const lines = wrapLines(node.plain, chars).slice(0, 3);
379
+ const first = TOP + BOX_H / 2 - ((lines.length - 1) * 19) / 2 + 6;
380
+ const text = lines
381
+ .map((l, k) => `<tspan x="${Math.round(mid)}" y="${Math.round(first + k * 19)}">${escapeHtml(l)}</tspan>`)
382
+ .join('');
383
+ const link = i < n - 1
384
+ ? `<line x1="${x + boxW + 4}" y1="${TOP + BOX_H / 2}" x2="${x + boxW + GAP - 6}" y2="${TOP + BOX_H / 2}"`
385
+ + ` stroke-width="2" style="stroke: var(--d-stroke)" marker-end="url(#dgm-arrow)"/>`
386
+ : '';
387
+ return `<g><rect x="${x}" y="${TOP}" width="${boxW}" height="${BOX_H}" rx="10"`
388
+ + ` style="fill: var(--d-fill-${(i % 6) + 1}); stroke: var(--d-stroke)" stroke-width="2"/>`
389
+ + `<text text-anchor="middle" font-size="15" font-weight="600"`
390
+ + ` style="font-family: var(--font-body); fill: var(--d-text)">${text}</text>${link}</g>`;
391
+ });
392
+ // the return leg: out of the last box, under the strip, back into the first
393
+ const loop = kind === 'cycle' && n > 1
394
+ ? `<path d="M ${W - Math.round(boxW / 2)} ${TOP + BOX_H} V ${H - 18} H ${Math.round(boxW / 2)} V ${TOP + BOX_H + 6}"`
395
+ + ` fill="none" stroke-width="2" style="stroke: var(--d-stroke)" marker-end="url(#dgm-arrow)"/>`
396
+ : '';
397
+ return `<svg viewBox="0 0 ${W} ${H}" width="${W}" role="img" aria-label="${escapeHtml(nodes.map((x) => x.plain).join(' → '))}">`
398
+ + `${arrow}${groups.join('')}${loop}</svg>`;
399
+ }
400
+
401
+ /** A diagram's nodes as a nested list — every word, none of the shape. */
402
+ export function diagramList(nodes, ordered) {
403
+ const items = [];
404
+ const walk = (list, level) => {
405
+ for (const node of list) {
406
+ items.push({ level, html: node.text || escapeHtml(node.plain) });
407
+ walk(node.children, level + 1);
408
+ }
409
+ };
410
+ walk(nodes, 0);
411
+ return listHtml({ ordered, items });
412
+ }
413
+
414
+ /**
415
+ * A SmartArt graphic as markup, and the word for what happened to it.
416
+ *
417
+ * The strip is drawn only when it would be READABLE: a flat sequence of at most
418
+ * six steps. Past that the boxes are too narrow for their own words, and a list
419
+ * that can be read beats a picture that cannot — an ordered one for a process,
420
+ * because the numbering is the half of the shape a list can still carry.
421
+ */
422
+ export function diagramBlockHtml({ shape, nodes }) {
423
+ const sequence = shape === 'process' || shape === 'cycle';
424
+ if (sequence && flat(nodes) && nodes.length > 1 && nodes.length <= 6) {
425
+ return { html: diagramSvg(nodes, shape), as: 'an SVG diagram' };
426
+ }
427
+ return { html: diagramList(nodes, sequence), as: 'a nested list' };
428
+ }
429
+
430
+ // ── drawn diagrams ──────────────────────────────────────────────────────────
431
+ //
432
+ // The other way a PowerPoint deck carries a diagram: no SmartArt, no picture,
433
+ // just boxes and arrows somebody dragged onto the slide. There is no marker
434
+ // saying "this is a diagram" — it is shapes with positions, and connectors
435
+ // that name the shapes they join.
436
+ //
437
+ // Before this, every one of those slides came across as a pile of paragraphs
438
+ // in document order, with the arrows gone and nothing said about it: the
439
+ // silent partial loss this importer's own preamble says is the failure that
440
+ // matters. Now the arrangement crosses, or — when the evidence is not strong
441
+ // enough to be sure it IS an arrangement — the report at least says what was
442
+ // flattened.
443
+
444
+ /** A drawing unit: 914400 EMU to the inch, 96 of those to the CSS pixel. */
445
+ const EMU_PX = 9525;
446
+
447
+ /** `a:xfrm` in EMU, in whatever space the shape's parent uses; null when the slide never placed it. */
448
+ function shapeBoxEmu(node) {
449
+ const xfrm = find(find(node, 'p:spPr') ?? node, 'a:xfrm');
450
+ const off = xfrm && find(xfrm, 'a:off');
451
+ const ext = xfrm && find(xfrm, 'a:ext');
452
+ if (!off || !ext) return null;
453
+ const n = (v) => Number(v ?? NaN);
454
+ const box = { x: n(off.attrs.x), y: n(off.attrs.y), w: n(ext.attrs.cx), h: n(ext.attrs.cy),
455
+ flipH: xfrm.attrs.flipH === '1', flipV: xfrm.attrs.flipV === '1' };
456
+ return Object.values(box).slice(0, 4).every(Number.isFinite) ? box : null;
457
+ }
458
+
459
+ const toPx = (box) => box && { ...box, x: box.x / EMU_PX, y: box.y / EMU_PX, w: box.w / EMU_PX, h: box.h / EMU_PX };
460
+
461
+ /**
462
+ * `a:xfrm` as pixels, or null for a shape the slide never placed. `frames` are
463
+ * the groups the shape sits inside, outermost first: a grouped shape's own
464
+ * transform is in its group's child space, and only the composed frames say
465
+ * where on the slide that is.
466
+ */
467
+ export function shapeBox(node, frames = []) {
468
+ let box = shapeBoxEmu(node);
469
+ if (!box) return null;
470
+ // innermost group first: a nested group's frame places into ITS parent's
471
+ // child space, which the outer frame then places on the slide
472
+ for (let i = frames.length - 1; i >= 0; i--) box = placeIn(box, frames[i]);
473
+ return toPx(box);
474
+ }
475
+
476
+ /**
477
+ * A group's frame: how its children's coordinates map into its parent's.
478
+ *
479
+ * Shapes inside a `p:grpSp` are NOT placed on the slide. Their `a:off`/`a:ext`
480
+ * are in the group's own child space, whose origin and size are `a:chOff` /
481
+ * `a:chExt` on the group's `a:xfrm`, and the group's `a:off`/`a:ext` say where
482
+ * that space lands on the slide. Move or resize a group after grouping it and
483
+ * the two stop agreeing — which is every group anyone has ever adjusted, and
484
+ * reading the children's boxes as slide coordinates put them wherever they
485
+ * were BEFORE the adjustment. Groups nest, so frames compose.
486
+ *
487
+ * Null when the group carries no transform (its children are already in the
488
+ * parent's space). A child extent of zero cannot scale anything; that axis
489
+ * keeps its size and only moves.
490
+ */
491
+ export function groupFrame(grpSp) {
492
+ const xfrm = find(find(grpSp, 'p:grpSpPr') ?? grpSp, 'a:xfrm');
493
+ const off = xfrm && find(xfrm, 'a:off');
494
+ const ext = xfrm && find(xfrm, 'a:ext');
495
+ if (!off || !ext) return null;
496
+ const n = (v, d = NaN) => (v == null ? d : Number(v));
497
+ const chOff = find(xfrm, 'a:chOff');
498
+ const chExt = find(xfrm, 'a:chExt');
499
+ const frame = {
500
+ x: n(off.attrs.x), y: n(off.attrs.y),
501
+ cx: n(chOff?.attrs.x, 0), cy: n(chOff?.attrs.y, 0),
502
+ sx: n(chExt?.attrs.cx) ? n(ext.attrs.cx) / n(chExt.attrs.cx) : 1,
503
+ sy: n(chExt?.attrs.cy) ? n(ext.attrs.cy) / n(chExt.attrs.cy) : 1,
504
+ };
505
+ return Object.values(frame).every(Number.isFinite) ? frame : null;
506
+ }
507
+
508
+ /** A box in a group's child space, placed by that group's frame — all in EMU. */
509
+ export function placeIn(box, frame) {
510
+ if (!frame) return box;
511
+ return {
512
+ ...box,
513
+ x: frame.x + (box.x - frame.cx) * frame.sx,
514
+ y: frame.y + (box.y - frame.cy) * frame.sy,
515
+ w: box.w * frame.sx,
516
+ h: box.h * frame.sy,
517
+ };
518
+ }
519
+
520
+ /** The preset shape name, e.g. `roundRect` — absent for a shape with custom geometry. */
521
+ const presetOf = (node) => find(node, 'a:prstGeom')?.attrs.prst ?? '';
522
+ /** PowerPoint marks an inserted TEXT BOX so; a drawn shape carries no such flag. */
523
+ const isTextBox = (node) => find(node, 'p:cNvSpPr')?.attrs.txBox === '1';
524
+ /** Geometry somebody drew by hand rather than picked from the gallery. */
525
+ const hasCustomGeometry = (node) => !!find(find(node, 'p:spPr') ?? node, 'a:custGeom');
526
+ /** `a:noFill` as the shape's OWN fill — a direct child of spPr, not the line's. */
527
+ const hasNoFill = (node) => { const spPr = find(node, 'p:spPr'); return !!spPr && children(spPr, 'a:noFill').length > 0; };
528
+ /** `a:xfrm@rot` in degrees — the file stores 60,000ths of one. */
529
+ export function rotationOf(node) {
530
+ const xfrm = find(find(node, 'p:spPr') ?? node, 'a:xfrm');
531
+ const r = Number(xfrm?.attrs.rot ?? 0);
532
+ return Number.isFinite(r) ? r / 60000 : 0;
533
+ }
534
+ /** A line's end decorations: `a:ln/a:headEnd` and `a:tailEnd`, anything but `none` is an arrowhead. */
535
+ function lineEnds(node) {
536
+ const ln = find(find(node, 'p:spPr') ?? node, 'a:ln');
537
+ const arrow = (name) => { const t = ln && find(ln, name)?.attrs.type; return !!t && t !== 'none'; };
538
+ return { headArrow: arrow('a:headEnd'), tailArrow: arrow('a:tailEnd') };
539
+ }
540
+ /** Presets that are lines, whatever element carries them. */
541
+ const LINE = /^(line|straightConnector\d*|bentConnector\d*|curvedConnector\d*)$/;
542
+ /**
543
+ * A line's two ends from its box: a connector runs corner to corner of its
544
+ * `a:xfrm`, and the flips say which corners. Bent and curved connectors are
545
+ * drawn straight between the same two points.
546
+ */
547
+ export function lineGeometry(box, { headArrow = false, tailArrow = false } = {}) {
548
+ if (!box) return null;
549
+ const x1 = box.flipH ? box.x + box.w : box.x, x2 = box.flipH ? box.x : box.x + box.w;
550
+ const y1 = box.flipV ? box.y + box.h : box.y, y2 = box.flipV ? box.y : box.y + box.h;
551
+ return { x1, y1, x2, y2, headArrow, tailArrow };
552
+ }
553
+ /**
554
+ * A shape's body as HTML. A paragraph is a bullet unless it says otherwise —
555
+ * PowerPoint's default, and right for a body placeholder — but inside a drawn
556
+ * box a single unmarked paragraph is the box's LABEL, not a list of one; only
557
+ * a real list, or several paragraphs, is the kind of body that wraps.
558
+ */
559
+ export function shapeBodyHtml(blocks) {
560
+ if (blocks.length === 1 && blocks[0].kind === 'list' && blocks[0].items.length === 1) return `<p>${blocks[0].items[0].html}</p>`;
561
+ return blocks.map((b) => (b.kind === 'list' ? listHtml(b) : `<p>${b.html}</p>`)).join('');
562
+ }
563
+
564
+ /**
565
+ * `a:custGeom` as SVG path data on the shape's box — the geometry somebody
566
+ * drew by hand, which no preset table can know.
567
+ *
568
+ * Each `a:path` is a subpath in its own coordinate space (`w`/`h`, or the
569
+ * shape's EMU extent when omitted), scaled onto the placed box. Lines and
570
+ * Béziers map one to one. `a:arcTo` is the odd one: it gives radii and a
571
+ * start/sweep angle (in 60,000ths of a degree) from the CURRENT point, so the
572
+ * centre is recovered from that point and the end computed from it — which is
573
+ * exactly what SVG's arc command wants the other way round. A path may say it
574
+ * is unfilled or unstroked; that travels with it.
575
+ */
576
+ export function customPathD(node, box, emuExt = null) {
577
+ const geom = find(find(node, 'p:spPr') ?? node, 'a:custGeom');
578
+ const lst = geom && find(geom, 'a:pathLst');
579
+ if (!lst || !box) return null;
580
+ const rad = (v) => (Number(v ?? 0) / 60000) * (Math.PI / 180);
581
+ const f = (n) => Math.round(n * 100) / 100;
582
+ const out = [];
583
+ for (const path of children(lst, 'a:path')) {
584
+ const pw = Number(path.attrs.w) || emuExt?.w || box.w * EMU_PX;
585
+ const ph = Number(path.attrs.h) || emuExt?.h || box.h * EMU_PX;
586
+ const sx = box.w / pw, sy = box.h / ph;
587
+ const P = (pt) => [box.x + Number(pt.attrs.x) * sx, box.y + Number(pt.attrs.y) * sy];
588
+ let d = '';
589
+ let cur = [box.x, box.y];
590
+ for (const c of path.children ?? []) {
591
+ const pts = children(c, 'a:pt').map(P);
592
+ if (c.name === 'a:moveTo' && pts[0]) { d += `M${f(pts[0][0])} ${f(pts[0][1])}`; cur = pts[0]; }
593
+ else if (c.name === 'a:lnTo' && pts[0]) { d += `L${f(pts[0][0])} ${f(pts[0][1])}`; cur = pts[0]; }
594
+ else if (c.name === 'a:cubicBezTo' && pts.length === 3) { d += `C${pts.map(([x, y]) => `${f(x)} ${f(y)}`).join(' ')}`; cur = pts[2]; }
595
+ else if (c.name === 'a:quadBezTo' && pts.length === 2) { d += `Q${pts.map(([x, y]) => `${f(x)} ${f(y)}`).join(' ')}`; cur = pts[1]; }
596
+ else if (c.name === 'a:arcTo') {
597
+ const rx = Number(c.attrs.wR) * sx, ry = Number(c.attrs.hR) * sy;
598
+ const st = rad(c.attrs.stAng), sw = rad(c.attrs.swAng);
599
+ if (!(rx > 0 && ry > 0) || !sw) continue;
600
+ const cx = cur[0] - rx * Math.cos(st), cy = cur[1] - ry * Math.sin(st);
601
+ const end = [cx + rx * Math.cos(st + sw), cy + ry * Math.sin(st + sw)];
602
+ d += `A${f(rx)} ${f(ry)} 0 ${Math.abs(sw) > Math.PI ? 1 : 0} ${sw > 0 ? 1 : 0} ${f(end[0])} ${f(end[1])}`;
603
+ cur = end;
604
+ } else if (c.name === 'a:close') d += 'Z';
605
+ }
606
+ if (d) out.push({ d, fill: path.attrs.fill !== 'none', stroke: path.attrs.stroke !== '0' });
607
+ }
608
+ return out.length ? out : null;
609
+ }
610
+
611
+ /**
612
+ * Attach the lines PowerPoint never attached. `a:stCxn`/`a:endCxn` are written
613
+ * only when an arrow was snapped to a box's connection site; a line merely
614
+ * drawn from one box to another carries no such thing, and is the commoner of
615
+ * the two in a deck drawn in a hurry. An end that lands within `tol` px of a
616
+ * shape's edge (or inside it) belongs to that shape; both ends on two different
617
+ * shapes is an attachment. The arrow keeps its direction: a line with a head
618
+ * arrow and no tail arrow points backwards, so its ends swap.
619
+ */
620
+ export function attachLoose(shapes, links, tol = 8) {
621
+ const near = (x, y) => shapes.find((s) => x >= s.box.x - tol && x <= s.box.x + s.box.w + tol
622
+ && y >= s.box.y - tol && y <= s.box.y + s.box.h + tol);
623
+ return links.map((l) => {
624
+ if ((l.from != null && l.to != null) || !l.geo) return l;
625
+ const a = near(l.geo.x1, l.geo.y1), b = near(l.geo.x2, l.geo.y2);
626
+ if (!a || !b || a === b || a.id == null || b.id == null) return l;
627
+ const backwards = l.geo.headArrow && !l.geo.tailArrow;
628
+ return { ...l, from: backwards ? b.id : a.id, to: backwards ? a.id : b.id, inferred: true };
629
+ });
630
+ }
631
+
632
+ /**
633
+ * Two text boxes SIDE BY SIDE are a layout — and the layout is worth keeping.
634
+ * The importer used to keep only their words, flowed one under the other,
635
+ * which turned every comparison slide into a list of two lists. decklight has
636
+ * a `split` layout (two sibling blocks as columns, PRESENTING), so the pair
637
+ * crosses as one: the two boxes, in left-to-right order, or null.
638
+ *
639
+ * Exactly two text-bearing placed shapes, both with something in them, each
640
+ * entirely left of or right of the other (8px of slack), overlapping in
641
+ * height by at least half the shorter one. A third box, a stacked pair or an
642
+ * empty one is not a comparison.
643
+ */
644
+ export function twoColumns(shapes, blocks) {
645
+ // a column is a text box or a plain rectangle with words in it — a chevron
646
+ // beside a box is a drawing that did not qualify, not a comparison
647
+ const text = shapes.filter((s) => !s.image && s.plain && !drawnIntent(s) && blocks.some((b) => b.placed === s));
648
+ if (text.length !== 2 || shapes.some((s) => !s.image && s.plain && !text.includes(s))) return null;
649
+ const [a, b] = [...text].sort((p, q) => p.box.x - q.box.x);
650
+ if (a.box.x + a.box.w > b.box.x + 8) return null;
651
+ const overlap = Math.min(a.box.y + a.box.h, b.box.y + b.box.h) - Math.max(a.box.y, b.box.y);
652
+ if (overlap < Math.min(a.box.h, b.box.h) / 2) return null;
653
+ return [a, b];
654
+ }
655
+
656
+ /**
657
+ * Drawn intent, per shape: geometry that was CHOSEN. A text box is never it
658
+ * (PowerPoint flags those), and a plain `rect` is what a text box is when the
659
+ * flag is missing — so only a preset other than rect, or custom geometry,
660
+ * says somebody was drawing rather than typing.
661
+ */
662
+ export const drawnIntent = (s) => !s.textBox && (!!s.custom || (!!s.prst && s.prst !== 'rect'));
663
+
664
+ const ROUND = /roundRect|round1Rect|round2SameRect|round2DiagRect|snip|Callout|^can$|flowChartProcess/;
665
+ const OVAL = /ellipse|circle|oval|cloud|flowChartConnector|flowChartTerminator/;
666
+ const DIAMOND = /diamond|flowChartDecision/;
667
+ const TRIANGLE = /triangle/;
668
+ /**
669
+ * The presets people actually draw with, as polygons on the unit box. The
670
+ * adjust handles (how deep a chevron's notch is, how wide an arrow's shaft)
671
+ * are ignored: these are themed approximations of a shape's KIND, which is
672
+ * what a diagram is read by. Anything else falls back to a rectangle.
673
+ */
674
+ export const POLYGONS = {
675
+ chevron: [[0, 0], [.8, 0], [1, .5], [.8, 1], [0, 1], [.2, .5]],
676
+ homePlate: [[0, 0], [.8, 0], [1, .5], [.8, 1], [0, 1]],
677
+ rightArrow: [[0, .25], [.6, .25], [.6, 0], [1, .5], [.6, 1], [.6, .75], [0, .75]],
678
+ leftArrow: [[1, .25], [.4, .25], [.4, 0], [0, .5], [.4, 1], [.4, .75], [1, .75]],
679
+ upArrow: [[.25, 1], [.25, .4], [0, .4], [.5, 0], [1, .4], [.75, .4], [.75, 1]],
680
+ downArrow: [[.25, 0], [.25, .6], [0, .6], [.5, 1], [1, .6], [.75, .6], [.75, 0]],
681
+ leftRightArrow: [[0, .5], [.3, 0], [.3, .25], [.7, .25], [.7, 0], [1, .5], [.7, 1], [.7, .75], [.3, .75], [.3, 1]],
682
+ hexagon: [[.25, 0], [.75, 0], [1, .5], [.75, 1], [.25, 1], [0, .5]],
683
+ pentagon: [[.5, 0], [1, .38], [.81, 1], [.19, 1], [0, .38]],
684
+ parallelogram: [[.25, 0], [1, 0], [.75, 1], [0, 1]],
685
+ trapezoid: [[.25, 0], [.75, 0], [1, 1], [0, 1]],
686
+ plus: [[.33, 0], [.67, 0], [.67, .33], [1, .33], [1, .67], [.67, .67], [.67, 1], [.33, 1], [.33, .67], [0, .67], [0, .33], [.33, .33]],
687
+ star5: [[.5, 0], [.62, .38], [1, .38], [.69, .62], [.81, 1], [.5, .76], [.19, 1], [.31, .62], [0, .38], [.38, .38]],
688
+ star4: [[.5, 0], [.62, .38], [1, .5], [.62, .62], [.5, 1], [.38, .62], [0, .5], [.38, .38]],
689
+ };
690
+
691
+ /**
692
+ * The shapes and connectors of a slide, as one drawing — or null when what is
693
+ * there is not evidence enough that it IS one.
694
+ *
695
+ * The test is deliberately strict, because the cost of a false positive is a
696
+ * perfectly ordinary slide turned into a strange picture. A connector that
697
+ * NAMES the shapes at both of its ends (`a:stCxn` / `a:endCxn`) is the strong
698
+ * signal: PowerPoint writes those when somebody attaches an arrow to a box,
699
+ * which is drawing a diagram and not laying out a caption. Two shapes and one
700
+ * attached connector is the floor.
701
+ */
702
+ export function asDrawing(shapes, links, { mode = 'auto' } = {}) {
703
+ if (mode === 'text') return null;
704
+ // strict means the file's own attachments; auto is allowed to see one
705
+ if (mode === 'auto') links = attachLoose(shapes, links);
706
+ const joined = links.filter((l) => l.from != null && l.to != null);
707
+ // a line that is not attached at both ends still has a place on the slide,
708
+ // and is drawn from it
709
+ const loose = links.filter((l) => !(l.from != null && l.to != null) && l.geo);
710
+ const attached = shapes.length >= 2 && joined.length > 0;
711
+ // `auto` believes the shapes themselves: two placed shapes of which one was
712
+ // DRAWN (a chevron, an ellipse, a hand-drawn outline), or a loose line among
713
+ // them, is an arrangement. Two text boxes side by side are still a layout.
714
+ // …and a PICTURE with lines on it is an arrangement of one: the screenshot
715
+ // the arrows point at. A lone text box with a line beside it is not.
716
+ const annotated = shapes.some((s) => s.image) && loose.length > 0;
717
+ const intent = mode === 'auto' && (shapes.length >= 2 || annotated) && (shapes.some(drawnIntent) || loose.length > 0);
718
+ if (!attached && !intent) return null;
719
+ const pad = 12;
720
+ const xs = shapes.map((s) => s.box);
721
+ const px = [...xs.map((b) => b.x), ...loose.flatMap((l) => [l.geo.x1, l.geo.x2])];
722
+ const py = [...xs.map((b) => b.y), ...loose.flatMap((l) => [l.geo.y1, l.geo.y2])];
723
+ const qx = [...xs.map((b) => b.x + b.w), ...loose.flatMap((l) => [l.geo.x1, l.geo.x2])];
724
+ const qy = [...xs.map((b) => b.y + b.h), ...loose.flatMap((l) => [l.geo.y1, l.geo.y2])];
725
+ const minX = Math.min(...px) - pad, minY = Math.min(...py) - pad;
726
+ const maxX = Math.max(...qx) + pad, maxY = Math.max(...qy) + pad;
727
+ return { shapes, links, loose, box: { x: minX, y: minY, w: maxX - minX, h: maxY - minY } };
728
+ }
729
+
730
+ /** Where a line from `b` towards `to` leaves b's box — its edge, not its middle. */
731
+ function edgePoint(b, to) {
732
+ const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
733
+ const dx = to.x - cx, dy = to.y - cy;
734
+ if (!dx && !dy) return { x: cx, y: cy };
735
+ // the smaller scale is the edge the ray crosses first
736
+ const sx = dx ? b.w / 2 / Math.abs(dx) : Infinity;
737
+ const sy = dy ? b.h / 2 / Math.abs(dy) : Infinity;
738
+ const t = Math.min(sx, sy);
739
+ return { x: cx + dx * t, y: cy + dy * t };
740
+ }
741
+
742
+ /** A drawing as a themed SVG, in the coordinates the slide used. */
743
+ export function drawingSvg({ shapes, links, loose = [], box }) {
744
+ const at = (b) => ({ x: b.x - box.x, y: b.y - box.y, w: b.w, h: b.h });
745
+ const byId = new Map(shapes.map((s) => [s.id, s]));
746
+ // auto-start-reverse: the one marker serves both ends of a line
747
+ const arrow = `<defs><marker id="dwg-arrow" markerWidth="6" markerHeight="4" refX="5" refY="2" orient="auto-start-reverse">`
748
+ + `<polygon points="0 0, 6 2, 0 4" style="fill: var(--d-stroke)"/></marker></defs>`;
749
+ // lines with a place of their own — drawn where they were, arrowheads where
750
+ // the file put them, and stopped at nothing because they joined nothing
751
+ const free = loose.map(({ geo: g }) => `<line x1="${Math.round(g.x1 - box.x)}" y1="${Math.round(g.y1 - box.y)}"`
752
+ + ` x2="${Math.round(g.x2 - box.x)}" y2="${Math.round(g.y2 - box.y)}" stroke-width="2" style="stroke: var(--d-stroke)"`
753
+ + `${g.headArrow ? ' marker-start="url(#dwg-arrow)"' : ''}${g.tailArrow ? ' marker-end="url(#dwg-arrow)"' : ''}/>`).join('');
754
+
755
+ const lines = links.map((l) => {
756
+ const a = byId.get(l.from), b = byId.get(l.to);
757
+ if (!a || !b) return '';
758
+ const g = l.geo;
759
+ // A connector with geometry of its own is drawn WHERE THE FILE DREW IT,
760
+ // its arrowheads where the file put them. Drawing it centre to centre
761
+ // instead turned a line that was perfectly vertical in PowerPoint into
762
+ // a slanted one whenever the two boxes' centres differed by a hair —
763
+ // which they always do. Centre to centre, clipped at the edges, stays
764
+ // only for a connector with no geometry (older fixtures, tests), which
765
+ // is an arrow.
766
+ if (g) {
767
+ const start = g.headArrow ? ' marker-start="url(#dwg-arrow)"' : '';
768
+ const end = g.tailArrow ? ' marker-end="url(#dwg-arrow)"' : '';
769
+ return `<line x1="${Math.round(g.x1 - box.x)}" y1="${Math.round(g.y1 - box.y)}"`
770
+ + ` x2="${Math.round(g.x2 - box.x)}" y2="${Math.round(g.y2 - box.y)}"`
771
+ + ` stroke-width="2" style="stroke: var(--d-stroke)"${start}${end}/>`;
772
+ }
773
+ const ca = { x: a.box.x + a.box.w / 2, y: a.box.y + a.box.h / 2 };
774
+ const cb = { x: b.box.x + b.box.w / 2, y: b.box.y + b.box.h / 2 };
775
+ const p1 = edgePoint(a.box, cb), p2 = edgePoint(b.box, ca);
776
+ return `<line x1="${Math.round(p1.x - box.x)}" y1="${Math.round(p1.y - box.y)}"`
777
+ + ` x2="${Math.round(p2.x - box.x)}" y2="${Math.round(p2.y - box.y)}"`
778
+ + ` stroke-width="2" style="stroke: var(--d-stroke)" marker-end="url(#dwg-arrow)"/>`;
779
+ }).join('');
780
+
781
+ let slot = 0; // palette slots go to shapes; a picture brings its own colours
782
+ const boxes = shapes.map((s) => {
783
+ const r = at(s.box);
784
+ const [x, y, w, h] = [r.x, r.y, r.w, r.h].map(Math.round);
785
+ // Rotation carries the label with the shape, as PowerPoint turns the
786
+ // words too. A FLIP does not: a mirrored arrow still reads left to right
787
+ // in PowerPoint, so the mirror wraps the shape alone and the text sits
788
+ // outside it — the fixture's first render read its label backwards.
789
+ const cx0 = x + w / 2, cy0 = y + h / 2;
790
+ const transform0 = s.rot ? ` transform="rotate(${Math.round(s.rot * 100) / 100} ${cx0} ${cy0})"` : '';
791
+ const mirror = (s.box.flipH || s.box.flipV)
792
+ ? [`<g transform="translate(${cx0} ${cy0}) scale(${s.box.flipH ? -1 : 1} ${s.box.flipV ? -1 : 1}) translate(${-cx0} ${-cy0})">`, '</g>']
793
+ : ['', ''];
794
+ // a picture in the arrangement is the picture, at its place — stretched
795
+ // to its box exactly as PowerPoint shows it
796
+ if (s.image) {
797
+ return `<g${transform0}>${mirror[0]}<image x="${x}" y="${y}" width="${w}" height="${h}" preserveAspectRatio="none"`
798
+ + ` href="data:${s.mime};base64,${s.bytes.toString('base64')}"${s.alt ? ` aria-label="${escapeHtml(s.alt)}"` : ''}/>${mirror[1]}</g>`;
799
+ }
800
+ const i = slot++;
801
+ // an outline somebody left unfilled is a region, not a box; filling it by
802
+ // palette slot would change what it says
803
+ const fill = s.noFill ? 'none' : `var(--d-fill-${(i % 6) + 1})`;
804
+ const stroke = ` style="fill: ${fill}; stroke: var(--d-stroke)" stroke-width="2"`;
805
+ let shape;
806
+ const poly = POLYGONS[s.prst];
807
+ if (s.path) {
808
+ // hand-drawn geometry: the path itself, each subpath with its own say on
809
+ // fill. Its numbers are slide coordinates; the diagram's origin moves them.
810
+ const shift = ` transform="translate(${-Math.round(box.x)} ${-Math.round(box.y)})"`;
811
+ shape = `<g${shift}>` + s.path.map((p) => `<path d="${p.d}" style="fill: ${p.fill && !s.noFill ? fill : 'none'}; stroke: ${p.stroke ? 'var(--d-stroke)' : 'none'}" stroke-width="2"/>`).join('') + '</g>';
812
+ } else if (poly) shape = `<polygon points="${poly.map(([px, py]) => `${Math.round(x + px * w)},${Math.round(y + py * h)}`).join(' ')}"${stroke}/>`;
813
+ else if (OVAL.test(s.prst)) shape = `<ellipse cx="${x + w / 2}" cy="${y + h / 2}" rx="${w / 2}" ry="${h / 2}"${stroke}/>`;
814
+ else if (DIAMOND.test(s.prst)) shape = `<polygon points="${x + w / 2},${y} ${x + w},${y + h / 2} ${x + w / 2},${y + h} ${x},${y + h / 2}"${stroke}/>`;
815
+ else if (TRIANGLE.test(s.prst)) shape = `<polygon points="${x + w / 2},${y} ${x + w},${y + h} ${x},${y + h}"${stroke}/>`;
816
+ else shape = `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${ROUND.test(s.prst) ? 10 : 3}"${stroke}/>`;
817
+ // Four short lines of <text> is a label. More than that, or a list, or
818
+ // several paragraphs, is a box with something to SAY — and <text> cannot
819
+ // wrap, so it went in as HTML that can, never as four lines and silence.
820
+ const lines_ = wrapLines(s.plain, Math.max(6, Math.floor(w / 8.4)));
821
+ const wordy = !!s.html && (lines_.length > 4 || /<(ul|ol)\b/.test(s.html) || (s.html.match(/<p>/g) ?? []).length > 1);
822
+ let text = '';
823
+ if (wordy) {
824
+ text = `<foreignObject x="${x}" y="${y}" width="${w}" height="${h}">`
825
+ + `<div xmlns="http://www.w3.org/1999/xhtml" class="dwg-text">${s.html}</div></foreignObject>`;
826
+ } else if (lines_.length) {
827
+ const first = y + h / 2 - ((lines_.length - 1) * 18) / 2 + 5;
828
+ text = `<text text-anchor="middle" font-size="14" font-weight="600"`
829
+ + ` style="font-family: var(--font-body); fill: var(--d-text)">`
830
+ + lines_.map((t, k) => `<tspan x="${Math.round(x + w / 2)}" y="${Math.round(first + k * 18)}">${escapeHtml(t)}</tspan>`).join('')
831
+ + `</text>`;
832
+ }
833
+ return `<g${transform0}>${mirror[0]}${shape}${mirror[1]}${text}</g>`;
834
+ }).join('');
835
+
836
+ const label = shapes.map((s) => s.plain).filter(Boolean).join(', ');
837
+ return `<svg viewBox="0 0 ${Math.round(box.w)} ${Math.round(box.h)}" width="${Math.round(Math.min(box.w, 960))}"`
838
+ + ` role="img" aria-label="${escapeHtml(label || 'diagram')}">${arrow}${free}${lines}${boxes}</svg>`;
839
+ }
840
+
234
841
  /**
235
842
  * One slide, as the pieces a `<section>` needs.
236
843
  *
@@ -238,7 +845,7 @@ export function parseChart(xml) {
238
845
  * order the slide did. Groups are walked into: a shape inside a group is still
239
846
  * content, and skipping groups loses whole slides' worth of text.
240
847
  */
241
- export function parseSlide(xml, { rels, mediaOf, chartOf, slideNo = 0 } = {}) {
848
+ export function parseSlide(xml, { rels, mediaOf, chartOf, diagramOf, slideNo = 0, shapes: mode = 'auto' } = {}) {
242
849
  const doc = parseXml(xml);
243
850
  const sld = find(doc, 'p:sld');
244
851
  const hidden = sld?.attrs.show === '0';
@@ -254,11 +861,31 @@ export function parseSlide(xml, { rels, mediaOf, chartOf, slideNo = 0 } = {}) {
254
861
  let title = null;
255
862
  let titleIsH1 = false;
256
863
  let subtitle = null;
864
+ let layout = null; // 'split' when two text boxes sit side by side
257
865
  const blocks = [];
866
+ const drawn = []; // placed, non-placeholder shapes — a diagram, maybe
867
+ const links = []; // connectors, and which shapes they join
258
868
 
259
- const walk = (tree) => {
869
+ const walk = (tree, frames = []) => {
260
870
  for (const node of tree.children ?? []) {
261
- if (node.name === 'p:grpSp') { walk(node); continue; }
871
+ if (node.name === 'p:grpSp') {
872
+ const frame = groupFrame(node);
873
+ walk(node, frame ? [...frames, frame] : frames);
874
+ continue;
875
+ }
876
+
877
+ // A connector NAMES the shapes it joins; that is what makes a set of
878
+ // boxes a diagram rather than a layout (asDrawing).
879
+ if (node.name === 'p:cxnSp') {
880
+ const cxn = find(node, 'p:cNvCxnSpPr');
881
+ links.push({
882
+ from: cxn && find(cxn, 'a:stCxn')?.attrs.id,
883
+ to: cxn && find(cxn, 'a:endCxn')?.attrs.id,
884
+ // its own place, for when it is attached at neither end
885
+ geo: lineGeometry(shapeBox(node, frames), lineEnds(node)),
886
+ });
887
+ continue;
888
+ }
262
889
 
263
890
  if (node.name === 'p:sp') {
264
891
  if (find(node, 'a:videoFile') || find(node, 'a:audioFile')) {
@@ -268,6 +895,39 @@ export function parseSlide(xml, { rels, mediaOf, chartOf, slideNo = 0 } = {}) {
268
895
  const ph = find(node, 'p:ph');
269
896
  const type = ph?.attrs.type ?? '';
270
897
  const txBody = find(node, 'p:txBody');
898
+ // A shape the slide PLACED, which is not one of the layout's
899
+ // placeholders, may be part of a drawing. It is only kept as one if
900
+ // the connectors bear that out (below); otherwise its text is read
901
+ // exactly as it always was, and a shape with no text is skipped.
902
+ let placed = false;
903
+ if (!ph) {
904
+ const box = shapeBox(node, frames);
905
+ const prst = presetOf(node);
906
+ // a line drawn as a shape is a line: it joins the connectors, not the boxes
907
+ if (box && LINE.test(prst)) {
908
+ links.push({ from: null, to: null, geo: lineGeometry(box, lineEnds(node)) });
909
+ continue;
910
+ }
911
+ if (box) {
912
+ // the block carries its SHAPE, not a flag: the drawing swap needs only
913
+ // truthiness, but the column pairing needs to know which box is which
914
+ drawn.push(placed = {
915
+ id: find(node, 'p:cNvPr')?.attrs.id,
916
+ box,
917
+ prst,
918
+ textBox: isTextBox(node),
919
+ custom: hasCustomGeometry(node),
920
+ path: customPathD(node, box, shapeBoxEmu(node)),
921
+ noFill: hasNoFill(node),
922
+ rot: rotationOf(node),
923
+ plain: txBody ? textOf(txBody).replace(/\s+/g, ' ').trim() : '',
924
+ // the body as the HTML it would have been on the slide, for a box
925
+ // with more to say than a label
926
+ html: txBody ? shapeBodyHtml(bodyBlocks(txBody, { rels })) : '',
927
+ at: blocks.length,
928
+ });
929
+ }
930
+ }
271
931
  if (!txBody) continue;
272
932
  const text = textOf(txBody).trim();
273
933
 
@@ -284,7 +944,10 @@ export function parseSlide(xml, { rels, mediaOf, chartOf, slideNo = 0 } = {}) {
284
944
  const id = find(node, 'p:cNvPr')?.attrs.id;
285
945
  const wantsBuild = id && builds.has(id);
286
946
  for (const b of bodyBlocks(txBody, { rels })) {
287
- blocks.push(wantsBuild && b.kind === 'list' ? { ...b, build: true } : b);
947
+ const block = wantsBuild && b.kind === 'list' ? { ...b, build: true } : b;
948
+ // `placed` is how the drawing swap finds these again exactly, rather
949
+ // than by comparing their contents — two boxes can say the same word.
950
+ blocks.push(placed ? { ...block, placed } : block);
288
951
  }
289
952
  continue;
290
953
  }
@@ -299,7 +962,17 @@ export function parseSlide(xml, { rels, mediaOf, chartOf, slideNo = 0 } = {}) {
299
962
  const media = rel && mediaOf?.(rel.target);
300
963
  if (!media) { drop('an image could not be read from the file'); continue; }
301
964
  const alt = find(node, 'p:cNvPr')?.attrs.descr ?? '';
302
- blocks.push({ kind: 'image', ...media, alt });
965
+ // A placed picture may be part of an arrangement — the screenshot the
966
+ // arrows point at. It is kept as its own block unless the drawing
967
+ // decision (below) takes it, exactly like a placed shape's text.
968
+ const box = shapeBox(node, frames);
969
+ if (box) {
970
+ drawn.push({
971
+ id: find(node, 'p:cNvPr')?.attrs.id, box, image: true, ...media, alt,
972
+ prst: '', plain: '', html: '', rot: rotationOf(node), at: blocks.length,
973
+ });
974
+ }
975
+ blocks.push(box ? { kind: 'image', ...media, alt, placed: true } : { kind: 'image', ...media, alt });
303
976
  continue;
304
977
  }
305
978
 
@@ -320,6 +993,20 @@ export function parseSlide(xml, { rels, mediaOf, chartOf, slideNo = 0 } = {}) {
320
993
  drop(GRAPHIC.chart);
321
994
  continue;
322
995
  }
996
+ if (kind === 'diagram') {
997
+ // The frame holds only relationships: r:dm is the data model, r:lo
998
+ // the layout that says which picture was drawn of it.
999
+ const ids = find(node, 'dgm:relIds');
1000
+ const dm = ids && rels?.get(ids.attrs['r:dm'])?.target;
1001
+ const nodes = dm && diagramOf ? parseDiagram(diagramOf(dm), { rels }) : [];
1002
+ if (nodes.length) {
1003
+ const lo = ids && rels?.get(ids.attrs['r:lo'])?.target;
1004
+ blocks.push({ kind: 'diagram', shape: diagramKind(lo && diagramOf ? diagramOf(lo) : ''), nodes });
1005
+ continue;
1006
+ }
1007
+ drop(GRAPHIC.diagram);
1008
+ continue;
1009
+ }
323
1010
  drop(GRAPHIC[kind] ?? `an embedded ${kind || 'object'} was dropped`);
324
1011
  continue;
325
1012
  }
@@ -332,7 +1019,49 @@ export function parseSlide(xml, { rels, mediaOf, chartOf, slideNo = 0 } = {}) {
332
1019
  const tree = find(sld, 'p:spTree');
333
1020
  if (tree) walk(tree);
334
1021
 
335
- return { slideNo, hidden, title, titleIsH1, subtitle, blocks, drops };
1022
+ // The drawing decision is made once the whole slide has been seen: a
1023
+ // connector can be written after the shapes it joins, and one shape is never
1024
+ // a diagram. When it holds, the shapes' own text blocks give way to the
1025
+ // picture that has them in it; when it does not, nothing changes except that
1026
+ // the slide now SAYS its arrangement did not survive.
1027
+ const drawing = asDrawing(drawn, links, { mode });
1028
+ if (drawing) {
1029
+ const at = blocks.findIndex((b) => b.placed);
1030
+ const kept = blocks.filter((b) => !b.placed);
1031
+ kept.splice(at < 0 ? kept.length : Math.min(at, kept.length), 0, { kind: 'drawing', drawing });
1032
+ blocks.length = 0;
1033
+ blocks.push(...kept);
1034
+ } else {
1035
+ // Not a drawing — but perhaps a comparison: two boxes side by side cross
1036
+ // as the split layout's two columns, left first, whatever order the file
1037
+ // listed them in. Anything else on the slide follows, as the footer.
1038
+ const cols = twoColumns(drawn, blocks);
1039
+ if (cols) {
1040
+ layout = 'split';
1041
+ for (const b of blocks) if (b.placed) b.column = cols.indexOf(b.placed);
1042
+ // gathered BEFORE the list is emptied — a lazy filter here read an empty list
1043
+ const left = blocks.filter((b) => b.column === 0);
1044
+ const right = blocks.filter((b) => b.column === 1);
1045
+ const rest = blocks.filter((b) => b.column == null || b.column < 0);
1046
+ blocks.length = 0;
1047
+ blocks.push(...left, ...right, ...rest);
1048
+ }
1049
+ for (const b of blocks) delete b.placed;
1050
+ // Said only when the slide LOOKED like a drawing — three placed shapes, or
1051
+ // two with a line between them. Two text boxes side by side is a layout,
1052
+ // and warning about every one of those is how a report stops being read.
1053
+ // …unless text was asked for by name, in which case that IS the answer.
1054
+ // Under strict, a slide that auto WOULD draw is worth a line on its own:
1055
+ // that is the one case where the fix is a flag rather than a redraw.
1056
+ const auto = mode === 'strict' && !!asDrawing(drawn, links, { mode: 'auto' });
1057
+ const boxes = drawn.filter((s) => !s.image);
1058
+ if (mode !== 'text' && (auto || boxes.length >= 3 || (boxes.length >= 2 && links.length))) {
1059
+ drop(`${boxes.length} drawn shape${boxes.length === 1 ? '' : 's'} came across as text — the arrangement did not (SPEC SVG_DIAGRAMS)`
1060
+ + (auto ? ' · --shapes auto would draw it' : ''));
1061
+ }
1062
+ }
1063
+
1064
+ return { slideNo, hidden, title, titleIsH1, subtitle, layout, blocks, drops };
336
1065
  }
337
1066
 
338
1067
  /** The notes text of a notesSlide part — the body placeholder, paragraph per line. */
@@ -351,8 +1080,13 @@ export function notesText(xml, { rels } = {}) {
351
1080
 
352
1081
  /** A parsed slide as the `<section>` markup, plus what its report line says. */
353
1082
  /** A chart block as SPEC CHARTS markup — JSON in a script tag, so `</` must not end it early. */
354
- export function chartHtml({ type, title, labels, series }) {
355
- const json = JSON.stringify({ labels, series }).replace(/<\//g, '<\\/');
1083
+ export function chartHtml({ type, title, labels, series, x, y }) {
1084
+ // A scatter carries pairs and two axis names; everything else carries
1085
+ // categories. Same wrapper, different payload — CHARTS reads both.
1086
+ const body = type === 'scatter'
1087
+ ? { ...(x ? { x } : {}), ...(y ? { y } : {}), series }
1088
+ : { labels, series };
1089
+ const json = JSON.stringify(body).replace(/<\//g, '<\\/');
356
1090
  const attrs = [`class="chart"`, `data-chart="${type}"`, title ? `data-title="${escapeHtml(title)}"` : null].filter(Boolean);
357
1091
  return `<div ${attrs.join(' ')}>\n <script type="application/json">${json}</script>\n </div>`;
358
1092
  }
@@ -365,6 +1099,9 @@ export function slideSection(slide, notes = [], { build = 'auto' } = {}) {
365
1099
  }
366
1100
  if (slide.subtitle) parts.push(` <p>${slide.subtitle}</p>`);
367
1101
 
1102
+ const head = parts.length;
1103
+ const cols = [[], []];
1104
+ const push = (b, html) => (b.column === 0 || b.column === 1 ? cols[b.column] : parts).push(html);
368
1105
  let bullets = 0;
369
1106
  for (const b of slide.blocks) {
370
1107
  if (b.kind === 'list') {
@@ -372,23 +1109,42 @@ export function slideSection(slide, notes = [], { build = 'auto' } = {}) {
372
1109
  // --build all forces it on, none forces it off; auto follows PowerPoint's
373
1110
  // own per-paragraph build list
374
1111
  const on = build === 'all' || (build === 'auto' && b.build);
375
- parts.push(` ${listHtml(b, { build: on ? 'fade-up' : null })}`);
1112
+ push(b, ` ${listHtml(b, { build: on ? 'fade-up' : null })}`);
376
1113
  } else if (b.kind === 'p') {
377
- parts.push(` <p>${b.html}</p>`);
1114
+ push(b, ` <p>${b.html}</p>`);
378
1115
  } else if (b.kind === 'table') {
379
1116
  const rows = children(b.node, 'a:tr');
380
1117
  const cols = rows.length ? children(rows[0], 'a:tc').length : 0;
381
1118
  did.push(`table ${rows.length}×${cols}`);
382
- parts.push(` ${tableHtml(b.node)}`);
1119
+ push(b, ` ${tableHtml(b.node)}`);
383
1120
  } else if (b.kind === 'chart') {
384
- did.push(`chart (${b.type}, ${b.series.length} series × ${b.labels.length})`);
385
- parts.push(` ${chartHtml(b)}`);
1121
+ const size = b.type === 'scatter'
1122
+ ? `${b.series.reduce((n, sr) => n + sr.points.length, 0)} points`
1123
+ : `${b.labels.length}`;
1124
+ did.push(`chart (${b.type}, ${b.series.length} series × ${size})`);
1125
+ push(b, ` ${chartHtml(b)}`);
1126
+ } else if (b.kind === 'diagram') {
1127
+ const { html, as } = diagramBlockHtml(b);
1128
+ const count = (function count(list) { return list.reduce((n, x) => n + 1 + count(x.children), 0); })(b.nodes);
1129
+ did.push(`SmartArt (${b.shape}, ${count} node${count === 1 ? '' : 's'}) as ${as}`);
1130
+ push(b, ` ${html}`);
1131
+ } else if (b.kind === 'drawing') {
1132
+ const pics = b.drawing.shapes.filter((s) => s.image).length;
1133
+ const n = b.drawing.shapes.length - pics;
1134
+ const k = b.drawing.loose?.length ?? 0;
1135
+ const parts_ = [n ? `${n} drawn shape${n === 1 ? '' : 's'}` : '', k ? `${k} line${k === 1 ? '' : 's'}` : '', pics ? `${pics} image${pics === 1 ? '' : 's'}` : ''].filter(Boolean);
1136
+ did.push(`${parts_.join(' and ')} as an SVG diagram`);
1137
+ push(b, ` ${drawingSvg(b.drawing)}`);
386
1138
  } else if (b.kind === 'image') {
387
1139
  did.push(`image inlined (${Math.round(b.bytes.length / 1024)} KB)`);
388
- parts.push(` <img src="data:${b.mime};base64,${b.bytes.toString('base64')}"`
1140
+ push(b, ` <img src="data:${b.mime};base64,${b.bytes.toString('base64')}"`
389
1141
  + `${b.alt ? ` alt="${escapeHtml(b.alt)}"` : ' alt=""'}>`);
390
1142
  }
391
1143
  }
1144
+ if (slide.layout === 'split') {
1145
+ did.push('two columns');
1146
+ parts.splice(head, 0, ...cols.map((c) => ` <div>\n${c.map((l) => ` ${l}`).join('\n')}\n </div>`));
1147
+ }
392
1148
  if (bullets) did.unshift(`${bullets} bullet${bullets === 1 ? '' : 's'}`);
393
1149
  if (notes.length) {
394
1150
  did.push('notes');
@@ -396,5 +1152,6 @@ export function slideSection(slide, notes = [], { build = 'auto' } = {}) {
396
1152
  for (const line of notes) parts.push(` <p>${line}</p>`);
397
1153
  parts.push(' </aside>');
398
1154
  }
399
- return { html: ` <section${slide.hidden ? ' data-hidden' : ''}>\n${parts.join('\n')}\n </section>`, did };
1155
+ const attrs = `${slide.hidden ? ' data-hidden' : ''}${slide.layout ? ` data-layout="${slide.layout}"` : ''}`;
1156
+ return { html: ` <section${attrs}>\n${parts.join('\n')}\n </section>`, did };
400
1157
  }