@blackbelt-technology/pi-dashboard-deck3d 0.9.0 → 0.10.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 (105) hide show
  1. package/.pi/skills/deck3d/SKILL.agent.md +78 -0
  2. package/.pi/skills/deck3d/SKILL.md +68 -0
  3. package/.pi/skills/deck3d/reference/effects.md +185 -2
  4. package/.pi/skills/deck3d/reference/ir-fields.md +26 -3
  5. package/.pi/skills/deck3d-from-pptx/SKILL.md +134 -0
  6. package/.pi/skills/deck3d-from-pptx/reference/steps.md +72 -0
  7. package/README.md +30 -2
  8. package/assets/preview/stub-chrome.png +0 -0
  9. package/assets/preview/stub-icon.json +59 -0
  10. package/assets/preview/stub-layout.json +195 -0
  11. package/assets/preview/stub-outline.json +48 -0
  12. package/dist/cli.js +11780 -5934
  13. package/dist/runtime.js +5916 -4007
  14. package/fixtures/business-2031/assets/stub-chrome.png +0 -0
  15. package/fixtures/business-2031/assets/stub-icon.json +59 -0
  16. package/fixtures/business-2031/assets/stub-layout.json +195 -0
  17. package/fixtures/business-2031/assets/stub-outline.json +48 -0
  18. package/fixtures/business-2031/build-overrides.mjs +58 -13
  19. package/fixtures/business-2031/deck.agent.md +60 -0
  20. package/fixtures/business-2031/deck.json +133 -8
  21. package/fixtures/business-2031/overrides.json +133 -8
  22. package/package.json +8 -4
  23. package/scripts/gen-stub-assets.ts +31 -0
  24. package/src/art/cutout.ts +97 -0
  25. package/src/art/decode.ts +169 -0
  26. package/src/art/icon.ts +380 -0
  27. package/src/art/png.ts +232 -0
  28. package/src/art/trace.ts +288 -0
  29. package/src/check/rules.ts +13 -8
  30. package/src/cli.ts +313 -51
  31. package/src/compare/index.ts +131 -0
  32. package/src/compare/ssim.ts +91 -0
  33. package/src/fx/art-geometry.ts +137 -0
  34. package/src/fx/art3d.meta.json +30 -0
  35. package/src/fx/art3d.ts +131 -0
  36. package/src/fx/bank.meta.json +26 -0
  37. package/src/fx/bank.ts +8 -0
  38. package/src/fx/compose.ts +5 -4
  39. package/src/fx/crane.meta.json +26 -0
  40. package/src/fx/crane.ts +8 -0
  41. package/src/fx/dolly.ts +5 -1
  42. package/src/fx/fade.ts +5 -1
  43. package/src/fx/flythrough.ts +5 -1
  44. package/src/fx/frame-chrome.meta.json +17 -0
  45. package/src/fx/frame-chrome.ts +134 -0
  46. package/src/fx/haze.meta.json +19 -0
  47. package/src/fx/haze.ts +91 -0
  48. package/src/fx/icon3d.meta.json +21 -0
  49. package/src/fx/icon3d.ts +167 -0
  50. package/src/fx/index.ts +96 -66
  51. package/src/fx/iris.ts +5 -1
  52. package/src/fx/meta.schema.json +10 -2
  53. package/src/fx/path.meta.json +25 -0
  54. package/src/fx/path.ts +8 -0
  55. package/src/fx/persistent.ts +11 -0
  56. package/src/fx/revolve.meta.json +26 -0
  57. package/src/fx/revolve.ts +8 -0
  58. package/src/fx/slide-layer.meta.json +26 -0
  59. package/src/fx/slide-layer.ts +557 -0
  60. package/src/fx/slide-space.ts +142 -0
  61. package/src/fx/stub-assets.ts +117 -0
  62. package/src/fx/swing.meta.json +26 -0
  63. package/src/fx/swing.ts +8 -0
  64. package/src/fx/types.ts +63 -2
  65. package/src/ir/merge.ts +5 -2
  66. package/src/ir/schema.json +140 -3
  67. package/src/ir/types.ts +54 -0
  68. package/src/ir/validate.ts +91 -3
  69. package/src/parse/harvest/index.ts +4 -1
  70. package/src/parse/markdown.ts +38 -7
  71. package/src/pptx/baseline.ts +183 -0
  72. package/src/pptx/extract.ts +161 -0
  73. package/src/pptx/fallback.ts +70 -0
  74. package/src/pptx/import.ts +256 -0
  75. package/src/pptx/master.ts +135 -0
  76. package/src/pptx/media.ts +81 -0
  77. package/src/pptx/package.ts +109 -0
  78. package/src/pptx/ref.ts +100 -0
  79. package/src/pptx/shapes.ts +276 -0
  80. package/src/pptx/stage.ts +82 -0
  81. package/src/pptx/text.ts +202 -0
  82. package/src/pptx/theme.ts +194 -0
  83. package/src/pptx/types.ts +159 -0
  84. package/src/pptx/xfrm.ts +93 -0
  85. package/src/pptx/xml.ts +106 -0
  86. package/src/pptx/zip.ts +239 -0
  87. package/src/render/assets.ts +57 -0
  88. package/src/render/build.ts +75 -0
  89. package/src/render/index.ts +7 -2
  90. package/src/render/template.html +1 -1
  91. package/src/runtime/assets.ts +75 -0
  92. package/src/runtime/fade.ts +110 -0
  93. package/src/runtime/hud.ts +37 -9
  94. package/src/runtime/index.ts +431 -67
  95. package/src/runtime/post.ts +11 -5
  96. package/src/runtime/scene.ts +25 -2
  97. package/src/runtime/transition.ts +222 -0
  98. package/src/runtime/types.ts +13 -2
  99. package/src/serve/index.ts +199 -16
  100. package/src/util/cleanup.ts +13 -0
  101. package/src/util/confine.ts +15 -0
  102. package/src/variants/pick.ts +282 -0
  103. package/src/variants/render.ts +179 -0
  104. package/src/variants/schema.json +48 -0
  105. package/src/variants/style.ts +318 -0
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Shape tree walker (design D1 `shapes.ts` + `pictures.ts`): `p:spTree` →
3
+ * draw items in z-order. Supported: text boxes and placeholders, solid-filled
4
+ * presets `rect | line | ellipse | roundRect`, pictures (PNG, JPEG, GIF, SVG)
5
+ * with crop/rotation/flip, groups (flattened through `xfrm.ts`). Everything
6
+ * else becomes a `fallback` item naming its construct.
7
+ */
8
+ import type { MasterChain, PhInfo } from "./master.js";
9
+ import { isTitleType, placeholderOf } from "./master.js";
10
+ import { extOf, type MediaRegistry } from "./media.js";
11
+ import type { Package } from "./package.js";
12
+ import { bodyText, readTextBody } from "./text.js";
13
+ import { type ColorEnv, resolveColor } from "./theme.js";
14
+ import type { FallbackConstruct, LayoutItem, ThemeInfo } from "./types.js";
15
+ import { type Frame, groupFrame, normDeg, type Placed, readXfrm, toSlide } from "./xfrm.js";
16
+ import { child, descendant, num, path, type XNode } from "./xml.js";
17
+
18
+ /** An item before its `sNN-iMMM` id is assigned. */
19
+ export type DraftItem = LayoutItem extends infer T ? (T extends LayoutItem ? Omit<T, "id"> : never) : never;
20
+
21
+ export interface Draft {
22
+ item: DraftItem;
23
+ /** Plain text the item carries (fingerprint, baseline deck). */
24
+ text: string;
25
+ /** This text belongs to the fallback item emitted just before it (same shape). */
26
+ coversPrev?: boolean;
27
+ /** Title / centre-title placeholder. */
28
+ isTitle: boolean;
29
+ placeholder?: string;
30
+ }
31
+
32
+ export interface WalkCtx {
33
+ pkg: Package;
34
+ /** Part whose relationships resolve `r:embed` (slide, layout or master). */
35
+ part: string;
36
+ scale: number;
37
+ color: ColorEnv;
38
+ theme: ThemeInfo;
39
+ chain: MasterChain;
40
+ media: MediaRegistry;
41
+ origin?: "master";
42
+ /** Master/layout placeholders are prompts, never drawn. */
43
+ skipPlaceholders: boolean;
44
+ }
45
+
46
+ const SUPPORTED_PRESETS = new Set(["rect", "line", "ellipse", "roundRect"]);
47
+ const RASTER = new Set(["png", "jpg", "jpeg", "gif"]);
48
+
49
+ const GRAPHIC_URI: Array<[string, FallbackConstruct]> = [
50
+ ["/chart", "chart"],
51
+ ["/diagram", "smartart"],
52
+ ["/table", "table"],
53
+ ["/ole", "ole"],
54
+ ];
55
+
56
+ function base(p: Placed, ctx: WalkCtx) {
57
+ return {
58
+ rect: toSlide(p, ctx.scale),
59
+ rotation: normDeg(p.rot),
60
+ flipH: p.flipH,
61
+ flipV: p.flipV,
62
+ ...(ctx.origin ? { origin: ctx.origin } : {}),
63
+ };
64
+ }
65
+
66
+ function fallback(p: Placed, ctx: WalkCtx, construct: FallbackConstruct, text = ""): Draft {
67
+ return { item: { kind: "fallback", construct, ...base(p, ctx) }, text, isTitle: false };
68
+ }
69
+
70
+ function placedOf(shape: XNode, xfrmNode: XNode | undefined, ph: PhInfo | undefined, ctx: WalkCtx, frame: Frame): Placed | undefined {
71
+ const own = readXfrm(xfrmNode);
72
+ const inherited = own ? undefined : ph ? readXfrm(ctx.chain.resolve(ph).xfrm) : undefined;
73
+ const p = own ?? inherited;
74
+ return p ? frame(p) : undefined;
75
+ }
76
+
77
+ /** Fill of `p:spPr`, falling back to the shape style's `a:fillRef`. */
78
+ function shapeFill(spPr: XNode | undefined, style: XNode | undefined, ctx: WalkCtx): { hex?: string; alpha: number; unsupported?: true } {
79
+ if (child(spPr, "a:noFill")) return { alpha: 0 };
80
+ const solid = child(spPr, "a:solidFill");
81
+ if (solid) {
82
+ const c = resolveColor(solid, ctx.color);
83
+ return c ? { hex: c.hex, alpha: c.alpha } : { alpha: 0 };
84
+ }
85
+ if (child(spPr, "a:gradFill") || child(spPr, "a:blipFill") || child(spPr, "a:pattFill") || child(spPr, "a:grpFill")) {
86
+ return { alpha: 1, unsupported: true };
87
+ }
88
+ const ref = child(style, "a:fillRef");
89
+ if (ref && num(ref.attrs.idx) > 0) {
90
+ const c = resolveColor(ref, ctx.color);
91
+ if (c) return { hex: c.hex, alpha: c.alpha };
92
+ }
93
+ return { alpha: 0 };
94
+ }
95
+
96
+ function shapeLine(spPr: XNode | undefined, style: XNode | undefined, ctx: WalkCtx): { color: string; width: number } | undefined {
97
+ const ln = child(spPr, "a:ln");
98
+ if (child(ln, "a:noFill")) return undefined;
99
+ const width = num(ln?.attrs.w, 12700) * ctx.scale;
100
+ const solid = child(ln, "a:solidFill");
101
+ const c = solid ? resolveColor(solid, ctx.color) : undefined;
102
+ if (c) return { color: c.hex, width: Math.round(width * 100) / 100 };
103
+ const ref = child(style, "a:lnRef");
104
+ if (!solid && ref && num(ref.attrs.idx) > 0) {
105
+ const rc = resolveColor(ref, ctx.color);
106
+ if (rc) return { color: rc.hex, width: Math.round(width * 100) / 100 };
107
+ }
108
+ return undefined;
109
+ }
110
+
111
+ function textDrafts(shape: XNode, p: Placed, ph: PhInfo | undefined, ctx: WalkCtx, style: XNode | undefined): Draft[] {
112
+ const tx = child(shape, "p:txBody");
113
+ if (!tx) return [];
114
+ const text = bodyText(tx);
115
+ if (!text.trim()) return [];
116
+ const inh = ctx.chain.resolve(ph);
117
+ const fontRef = child(style, "a:fontRef");
118
+ const body = readTextBody(tx, {
119
+ color: ctx.color,
120
+ theme: ctx.theme,
121
+ scale: ctx.scale,
122
+ lists: inh.lists,
123
+ bodyPrs: inh.bodyPrs,
124
+ fontRefColor: fontRef ? resolveColor(fontRef, ctx.color)?.hex : undefined,
125
+ });
126
+ if (body.wordArt) return [fallback(p, ctx, "wordart", text)];
127
+ const item: DraftItem = {
128
+ kind: "text",
129
+ ...base(p, ctx),
130
+ ...(ph ? { placeholder: ph.type } : {}),
131
+ anchor: body.anchor,
132
+ insets: body.insets,
133
+ vertical: body.vertical,
134
+ ...(body.textRotation ? { textRotation: body.textRotation } : {}),
135
+ autofit: body.autofit,
136
+ paragraphs: body.paragraphs,
137
+ };
138
+ return [{ item, text, isTitle: !!ph && isTitleType(ph.type), placeholder: ph?.type }];
139
+ }
140
+
141
+ function walkSp(shape: XNode, ctx: WalkCtx, frame: Frame): Draft[] {
142
+ const ph = placeholderOf(shape);
143
+ if (ph && ctx.skipPlaceholders) return [];
144
+ const spPr = child(shape, "p:spPr");
145
+ const p = placedOf(shape, child(spPr, "a:xfrm"), ph, ctx, frame);
146
+ if (!p) return [];
147
+ const style = child(shape, "p:style");
148
+ const geom = child(spPr, "a:prstGeom");
149
+ const preset = geom?.attrs.prst;
150
+ const fill = shapeFill(spPr, style, ctx);
151
+ const line = shapeLine(spPr, style, ctx);
152
+ const visible = fill.unsupported || (fill.hex && fill.alpha > 0) || !!line;
153
+ const out: Draft[] = [];
154
+ if (visible) {
155
+ const custom = !!child(spPr, "a:custGeom");
156
+ if (fill.unsupported) out.push(fallback(p, ctx, "fill"));
157
+ else if (custom || (preset && !SUPPORTED_PRESETS.has(preset))) out.push(fallback(p, ctx, "shape"));
158
+ else {
159
+ out.push({
160
+ item: {
161
+ kind: "rect",
162
+ ...base(p, ctx),
163
+ preset: (preset ?? "rect") as "rect" | "line" | "ellipse" | "roundRect",
164
+ ...(fill.hex && fill.alpha > 0 ? { fill: fill.hex } : {}),
165
+ alpha: fill.hex ? fill.alpha : 0,
166
+ ...(line ? { line } : {}),
167
+ },
168
+ text: "",
169
+ isTitle: false,
170
+ });
171
+ }
172
+ }
173
+ const texts = textDrafts(shape, p, ph, ctx, style);
174
+ // A fallback is a crop of the WHOLE shape, text included: link the text to it.
175
+ if (out[out.length - 1]?.item.kind === "fallback") for (const t of texts) if (t.item.kind === "text") t.coversPrev = true;
176
+ return [...out, ...texts];
177
+ }
178
+
179
+ function walkCxn(shape: XNode, ctx: WalkCtx, frame: Frame): Draft[] {
180
+ const spPr = child(shape, "p:spPr");
181
+ const p = placedOf(shape, child(spPr, "a:xfrm"), undefined, ctx, frame);
182
+ if (!p) return [];
183
+ const line = shapeLine(spPr, child(shape, "p:style"), ctx);
184
+ if (!line) return [];
185
+ const preset = child(spPr, "a:prstGeom")?.attrs.prst;
186
+ if (preset && preset !== "line" && preset !== "straightConnector1") return [fallback(p, ctx, "shape")];
187
+ return [{ item: { kind: "rect", ...base(p, ctx), preset: "line", alpha: 0, line }, text: "", isTitle: false }];
188
+ }
189
+
190
+ function walkPic(shape: XNode, ctx: WalkCtx, frame: Frame): Draft[] {
191
+ const ph = placeholderOf(shape);
192
+ if (ph && ctx.skipPlaceholders) return [];
193
+ const spPr = child(shape, "p:spPr");
194
+ const p = placedOf(shape, child(spPr, "a:xfrm"), ph, ctx, frame);
195
+ if (!p) return [];
196
+ const nvPr = path(shape, "p:nvPicPr", "p:nvPr");
197
+ if (child(nvPr, "a:videoFile") || child(nvPr, "a:audioFile") || descendant(nvPr, "p14:media")) return [fallback(p, ctx, "media")];
198
+ const blipFill = child(shape, "p:blipFill");
199
+ const blip = child(blipFill, "a:blip");
200
+ const rels = ctx.pkg.rels(ctx.part);
201
+ const rel = rels[blip?.attrs["r:embed"] ?? ""];
202
+ if (!rel || rel.external || !ctx.pkg.has(rel.part)) return [fallback(p, ctx, "media")];
203
+ const ext = extOf(rel.part);
204
+ if (ext === "emf" || ext === "wmf") return [fallback(p, ctx, ext)];
205
+ if (!RASTER.has(ext) && ext !== "svg") return [fallback(p, ctx, "media")];
206
+ // Any blip child other than its extension list is a picture effect.
207
+ if (blip?.children.some((c) => c.name !== "a:extLst")) return [fallback(p, ctx, "picture-effect")];
208
+ const raster = ctx.media.addPart(rel.part, ctx.pkg.bytes(rel.part) as Uint8Array);
209
+ const svgEmbed = descendant(blip, "asvg:svgBlip")?.attrs["r:embed"];
210
+ const svgRel = svgEmbed ? rels[svgEmbed] : undefined;
211
+ const svg = svgRel && !svgRel.external && ctx.pkg.has(svgRel.part) ? ctx.media.addPart(svgRel.part, ctx.pkg.bytes(svgRel.part) as Uint8Array) : undefined;
212
+ const src = child(blipFill, "a:srcRect");
213
+ const frac = (v: string | undefined) => Math.round((num(v) / 100000) * 10000) / 10000;
214
+ return [
215
+ {
216
+ item: {
217
+ kind: "img",
218
+ ...base(p, ctx),
219
+ media: raster.name,
220
+ asset: raster.asset,
221
+ crop: { l: frac(src?.attrs.l), t: frac(src?.attrs.t), r: frac(src?.attrs.r), b: frac(src?.attrs.b) },
222
+ ...(svg ? { svg: svg.name, svgAsset: svg.asset } : {}),
223
+ },
224
+ text: "",
225
+ isTitle: false,
226
+ },
227
+ ];
228
+ }
229
+
230
+ function walkGraphicFrame(shape: XNode, ctx: WalkCtx, frame: Frame): Draft[] {
231
+ const ph = placeholderOf(shape);
232
+ if (ph && ctx.skipPlaceholders) return [];
233
+ const p = placedOf(shape, child(shape, "p:xfrm"), ph, ctx, frame);
234
+ if (!p) return [];
235
+ const uri = path(shape, "a:graphic", "a:graphicData")?.attrs.uri ?? "";
236
+ const construct = GRAPHIC_URI.find(([suffix]) => uri.endsWith(suffix))?.[1] ?? "ole";
237
+ return [fallback(p, ctx, construct)];
238
+ }
239
+
240
+ /** Walk the children of a shape tree or group in z-order. */
241
+ export function walkTree(tree: XNode | undefined, ctx: WalkCtx, frame: Frame): Draft[] {
242
+ const out: Draft[] = [];
243
+ for (const node of tree?.children ?? []) {
244
+ // AlternateContent: the fallback branch is the one every reader understands.
245
+ const n = node.name === "mc:AlternateContent" ? (child(node, "mc:Fallback") ?? child(node, "mc:Choice")) : node;
246
+ if (!n) continue;
247
+ const items = n === node ? [n] : n.children;
248
+ for (const shape of items) {
249
+ switch (shape.name) {
250
+ case "p:sp":
251
+ out.push(...walkSp(shape, ctx, frame));
252
+ break;
253
+ case "p:cxnSp":
254
+ out.push(...walkCxn(shape, ctx, frame));
255
+ break;
256
+ case "p:pic":
257
+ out.push(...walkPic(shape, ctx, frame));
258
+ break;
259
+ case "p:graphicFrame":
260
+ out.push(...walkGraphicFrame(shape, ctx, frame));
261
+ break;
262
+ case "p:grpSp":
263
+ out.push(...walkTree(shape, ctx, groupFrame(path(shape, "p:grpSpPr", "a:xfrm"), frame)));
264
+ break;
265
+ case "p:contentPart": {
266
+ const p = readXfrm(child(shape, "p:xfrm"));
267
+ if (p) out.push(fallback(frame(p), ctx, "shape"));
268
+ break;
269
+ }
270
+ default:
271
+ break;
272
+ }
273
+ }
274
+ }
275
+ return out;
276
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Atomic output staging (design D1 `stage.ts`): every output is written into
3
+ * a sibling temp directory and moved into place only after all of it was
4
+ * written. A failure before the commit removes the staging dir and leaves the
5
+ * target exactly as it was.
6
+ */
7
+ import { existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs";
8
+ import { basename, dirname, join } from "node:path";
9
+
10
+ /** Write hook — tests inject a failing writer to prove atomicity. */
11
+ export type WriteFn = (path: string, data: Uint8Array | string) => void;
12
+ /** Rename hook — tests inject a failing rename to prove the commit rolls back. */
13
+ export type RenameFn = (from: string, to: string) => void;
14
+
15
+ export const defaultWrite: WriteFn = (path, data) => writeFileSync(path, data);
16
+
17
+ export class Stage {
18
+ readonly target: string;
19
+ private readonly write: WriteFn;
20
+ private readonly rename: RenameFn;
21
+ readonly dir: string;
22
+
23
+ constructor(
24
+ target: string,
25
+ write: WriteFn = defaultWrite,
26
+ rename: RenameFn = renameSync,
27
+ ) {
28
+ this.target = target;
29
+ this.write = write;
30
+ this.rename = rename;
31
+ const parent = dirname(target);
32
+ mkdirSync(parent, { recursive: true });
33
+ this.dir = mkdtempSync(join(parent, `.${basename(target)}.deck3d-import-`));
34
+ }
35
+
36
+ file(rel: string, data: Uint8Array | string): void {
37
+ const path = join(this.dir, rel);
38
+ mkdirSync(dirname(path), { recursive: true });
39
+ this.write(path, data);
40
+ }
41
+
42
+ discard(): void {
43
+ rmSync(this.dir, { recursive: true, force: true });
44
+ }
45
+
46
+ /**
47
+ * Move the staged top-level entries into `target`. A fresh target is ONE
48
+ * rename. For an existing deck each replaced entry is first renamed aside
49
+ * (inside the staging dir); if ANY rename fails, every entry already
50
+ * swapped is put back, so a failed re-import leaves the deck exactly as it
51
+ * was. The staging dir (with the asides) is removed on every path.
52
+ */
53
+ commit(entries: string[]): void {
54
+ if (!existsSync(this.target)) {
55
+ this.rename(this.dir, this.target);
56
+ return;
57
+ }
58
+ const swapped: Array<{ to: string; aside?: string }> = [];
59
+ try {
60
+ for (const name of entries) {
61
+ const from = join(this.dir, name);
62
+ if (!existsSync(from)) continue;
63
+ const to = join(this.target, name);
64
+ const aside = existsSync(to) ? join(this.dir, `${name}.old`) : undefined;
65
+ if (aside) this.rename(to, aside);
66
+ swapped.push({ to, aside });
67
+ this.rename(from, to);
68
+ }
69
+ } catch (err) {
70
+ // Roll back with the real fs calls: the injected one may keep failing.
71
+ for (const { to, aside } of swapped.reverse()) {
72
+ if (aside) {
73
+ rmSync(to, { recursive: true, force: true });
74
+ renameSync(aside, to);
75
+ } else rmSync(to, { recursive: true, force: true });
76
+ }
77
+ throw err;
78
+ } finally {
79
+ this.discard();
80
+ }
81
+ }
82
+ }
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Text bodies → paragraphs and runs (design D1 `text.ts`).
3
+ *
4
+ * Paragraph/run properties resolve through a priority chain of list styles:
5
+ * the paragraph's own `a:pPr`/`a:rPr` → the shape's `a:lstStyle` → the
6
+ * matching layout placeholder → the matching master placeholder → the
7
+ * master's `p:txStyles` entry → the presentation `defaultTextStyle`. Sizes
8
+ * apply the `normAutofit` `fontScale` and line spacing the `lnSpcReduction`
9
+ * that the authoring application STORED — fit is never recomputed.
10
+ */
11
+ import { type ColorEnv, resolveColor } from "./theme.js";
12
+ import type { Insets, LayoutParagraph, LayoutRun, ThemeInfo } from "./types.js";
13
+ import { child, kids, num, type XNode } from "./xml.js";
14
+
15
+ /** EMU per point. */
16
+ const EMU_PT = 12700;
17
+ const DEFAULT_SIZE_PT = 18;
18
+
19
+ export interface TextEnv {
20
+ color: ColorEnv;
21
+ theme: ThemeInfo;
22
+ /** EMU → slide units. */
23
+ scale: number;
24
+ /** List-style nodes (children `a:lvlNpPr`, `a:defPPr`), highest priority first. */
25
+ lists: XNode[];
26
+ /** `a:bodyPr` nodes, highest priority first (shape, layout ph, master ph). */
27
+ bodyPrs: XNode[];
28
+ /** Colour from the shape's `p:style/a:fontRef`, a run's last colour fallback. */
29
+ fontRefColor?: string;
30
+ }
31
+
32
+ export interface TextBody {
33
+ paragraphs: LayoutParagraph[];
34
+ anchor: "t" | "ctr" | "b";
35
+ insets: Insets;
36
+ vertical: boolean;
37
+ /** Present for vertical text: 90 (`vert`, `eaVert`, …) or 270 (`vert270`). */
38
+ textRotation?: 90 | 270;
39
+ autofit: "none" | "norm" | "shape";
40
+ /** `a:prstTxWarp` other than `textNoShape` — WordArt, rendered as a fallback. */
41
+ wordArt: boolean;
42
+ }
43
+
44
+ function levelNodes(lists: XNode[], lvl: number): XNode[] {
45
+ const out: XNode[] = [];
46
+ for (const list of lists) {
47
+ const lv = child(list, `a:lvl${lvl + 1}pPr`);
48
+ if (lv) out.push(lv);
49
+ const def = child(list, "a:defPPr");
50
+ if (def) out.push(def);
51
+ }
52
+ return out;
53
+ }
54
+
55
+ function firstAttr(nodes: Array<XNode | undefined>, name: string): string | undefined {
56
+ for (const n of nodes) {
57
+ const v = n?.attrs[name];
58
+ if (v !== undefined) return v;
59
+ }
60
+ return undefined;
61
+ }
62
+
63
+ function firstChild(nodes: Array<XNode | undefined>, name: string): XNode | undefined {
64
+ for (const n of nodes) {
65
+ const c = child(n, name);
66
+ if (c) return c;
67
+ }
68
+ return undefined;
69
+ }
70
+
71
+ function bool(v: string | undefined): boolean {
72
+ return v === "1" || v === "true";
73
+ }
74
+
75
+ function resolveFont(typeface: string | undefined, theme: ThemeInfo): string {
76
+ if (!typeface || typeface === "+mn-lt" || typeface === "+mn-ea" || typeface === "+mn-cs") return theme.fonts.minor;
77
+ if (typeface === "+mj-lt" || typeface === "+mj-ea" || typeface === "+mj-cs") return theme.fonts.major;
78
+ return typeface;
79
+ }
80
+
81
+ const round2 = (v: number) => Math.round(v * 100) / 100;
82
+ const round3 = (v: number) => Math.round(v * 1000) / 1000;
83
+
84
+ interface Autofit {
85
+ mode: "none" | "norm" | "shape";
86
+ fontScale: number;
87
+ lnSpcReduction: number;
88
+ }
89
+
90
+ function readAutofit(bodyPrs: XNode[]): Autofit {
91
+ for (const b of bodyPrs) {
92
+ const norm = child(b, "a:normAutofit");
93
+ if (norm) {
94
+ return {
95
+ mode: "norm",
96
+ fontScale: num(norm.attrs.fontScale, 100000) / 100000,
97
+ lnSpcReduction: num(norm.attrs.lnSpcReduction, 0) / 100000,
98
+ };
99
+ }
100
+ if (child(b, "a:spAutoFit")) return { mode: "shape", fontScale: 1, lnSpcReduction: 0 };
101
+ if (child(b, "a:noAutofit")) return { mode: "none", fontScale: 1, lnSpcReduction: 0 };
102
+ }
103
+ return { mode: "none", fontScale: 1, lnSpcReduction: 0 };
104
+ }
105
+
106
+ /** Space value of `a:spcBef`/`a:spcAft`/`a:lnSpc`: `{pts}` (points) or `{pct}` (fraction). */
107
+ function spacing(node: XNode | undefined): { pts?: number; pct?: number } | undefined {
108
+ if (!node) return undefined;
109
+ const pts = child(node, "a:spcPts");
110
+ if (pts) return { pts: num(pts.attrs.val) / 100 };
111
+ const pct = child(node, "a:spcPct");
112
+ if (pct) return { pct: num(pct.attrs.val) / 100000 };
113
+ return undefined;
114
+ }
115
+
116
+ function paragraphText(p: XNode): string {
117
+ let s = "";
118
+ for (const c of p.children) {
119
+ if (c.name === "a:r" || c.name === "a:fld") s += child(c, "a:t")?.text ?? "";
120
+ else if (c.name === "a:br") s += "\n";
121
+ }
122
+ return s;
123
+ }
124
+
125
+ /** Plain text of a `p:txBody`, paragraphs joined by `\n`. */
126
+ export function bodyText(txBody: XNode | undefined): string {
127
+ return kids(txBody, "a:p").map(paragraphText).join("\n");
128
+ }
129
+
130
+ export function readTextBody(txBody: XNode, env: TextEnv): TextBody {
131
+ const bodyPrs = [child(txBody, "a:bodyPr"), ...env.bodyPrs].filter((n): n is XNode => !!n);
132
+ const lists = [child(txBody, "a:lstStyle"), ...env.lists].filter((n): n is XNode => !!n);
133
+ const fit = readAutofit(bodyPrs);
134
+ const anchorRaw = firstAttr(bodyPrs, "anchor");
135
+ const anchor: TextBody["anchor"] = anchorRaw === "ctr" ? "ctr" : anchorRaw === "b" ? "b" : "t";
136
+ const ins = (name: string, d: number) => round2(num(firstAttr(bodyPrs, name), d) * env.scale);
137
+ const vert = firstAttr(bodyPrs, "vert");
138
+ const warp = firstChild(bodyPrs, "a:prstTxWarp");
139
+
140
+ const paragraphs: LayoutParagraph[] = [];
141
+ for (const p of kids(txBody, "a:p")) {
142
+ const pPr = child(p, "a:pPr");
143
+ const lvl = Math.min(8, Math.max(0, num(pPr?.attrs.lvl, 0)));
144
+ const pNodes = [pPr, ...levelNodes(lists, lvl)];
145
+ const defRPrs = pNodes.map((n) => child(n, "a:defRPr"));
146
+
147
+ const runs: LayoutRun[] = [];
148
+ let firstSizePt: number | undefined;
149
+ for (const r of p.children) {
150
+ if (r.name !== "a:r" && r.name !== "a:fld" && r.name !== "a:br") continue;
151
+ const rPr = child(r, "a:rPr");
152
+ const rNodes = [rPr, ...defRPrs];
153
+ const sizePt = num(firstAttr(rNodes, "sz"), DEFAULT_SIZE_PT * 100) / 100;
154
+ firstSizePt ??= sizePt;
155
+ const fill = firstChild(rNodes, "a:solidFill");
156
+ const color = resolveColor(fill, env.color)?.hex ?? env.fontRefColor ?? env.color.theme.colors.dk1;
157
+ const latin = firstChild(rNodes, "a:latin");
158
+ const u = firstAttr(rNodes, "u");
159
+ const text = r.name === "a:br" ? "\n" : (child(r, "a:t")?.text ?? "");
160
+ runs.push({
161
+ text,
162
+ size: round2(sizePt * fit.fontScale * EMU_PT * env.scale),
163
+ bold: bool(firstAttr(rNodes, "b")),
164
+ italic: bool(firstAttr(rNodes, "i")),
165
+ underline: u !== undefined && u !== "none",
166
+ color,
167
+ font: resolveFont(latin?.attrs.typeface, env.theme),
168
+ });
169
+ }
170
+
171
+ const sizePt = (firstSizePt ?? num(firstAttr(defRPrs, "sz"), DEFAULT_SIZE_PT * 100) / 100) * fit.fontScale;
172
+ const ln = spacing(firstChild(pNodes, "a:lnSpc"));
173
+ const baseLine = ln?.pct ?? (ln?.pts !== undefined ? ln.pts / (sizePt * 1.2) : 1);
174
+ const lineSpacing = round3(Math.max(0.1, baseLine - fit.lnSpcReduction));
175
+ const toUnits = (s: { pts?: number; pct?: number } | undefined) =>
176
+ round2(s ? (s.pts !== undefined ? s.pts : (s.pct ?? 0) * sizePt) * EMU_PT * env.scale : 0);
177
+ const algn = firstAttr(pNodes, "algn");
178
+ // The highest-priority node that says anything about bullets decides.
179
+ const buNode = pNodes.find((n) => child(n, "a:buNone") || child(n, "a:buChar") || child(n, "a:buAutoNum"));
180
+ const buChar = child(buNode, "a:buChar");
181
+ const para: LayoutParagraph = {
182
+ align: algn === "ctr" ? "ctr" : algn === "r" ? "r" : algn === "just" || algn === "dist" ? "just" : "l",
183
+ lineSpacing,
184
+ spaceBefore: toUnits(spacing(firstChild(pNodes, "a:spcBef"))),
185
+ spaceAfter: toUnits(spacing(firstChild(pNodes, "a:spcAft"))),
186
+ level: lvl,
187
+ runs,
188
+ };
189
+ if (buChar?.attrs.char) para.bullet = buChar.attrs.char;
190
+ paragraphs.push(para);
191
+ }
192
+
193
+ return {
194
+ paragraphs,
195
+ anchor,
196
+ insets: { l: ins("lIns", 91440), t: ins("tIns", 45720), r: ins("rIns", 91440), b: ins("bIns", 45720) },
197
+ vertical: vert !== undefined && vert !== "horz",
198
+ ...(vert !== undefined && vert !== "horz" ? { textRotation: (vert === "vert270" ? 270 : 90) as 90 | 270 } : {}),
199
+ autofit: fit.mode,
200
+ wordArt: !!warp && warp.attrs.prst !== undefined && warp.attrs.prst !== "textNoShape",
201
+ };
202
+ }