@officedk/pptxdk 0.0.0-stage → 0.1.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 (194) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +48 -2
  3. package/dist/build.d.ts +94 -0
  4. package/dist/build.js +148 -0
  5. package/dist/capabilities/dist/all.js +32 -0
  6. package/dist/capabilities/dist/box/box-codegen.js +51 -0
  7. package/dist/capabilities/dist/box/box-declaration.js +31 -0
  8. package/dist/capabilities/dist/box/box-elements.js +17 -0
  9. package/dist/capabilities/dist/box/box.js +138 -0
  10. package/dist/capabilities/dist/chart/chart-codegen.js +77 -0
  11. package/dist/capabilities/dist/chart/chart-declaration.js +7 -0
  12. package/dist/capabilities/dist/chart/chart-elements.js +12 -0
  13. package/dist/capabilities/dist/chart/chart-import.js +2272 -0
  14. package/dist/capabilities/dist/chart/chart-labels.js +86 -0
  15. package/dist/capabilities/dist/chart/chart-model.js +9 -0
  16. package/dist/capabilities/dist/chart/chart-schemas.js +1078 -0
  17. package/dist/capabilities/dist/chart/chart-xml.js +788 -0
  18. package/dist/capabilities/dist/chart/chart.js +1124 -0
  19. package/dist/capabilities/dist/chart/preview/axes-and-grid.js +298 -0
  20. package/dist/capabilities/dist/chart/preview/bar-column.js +143 -0
  21. package/dist/capabilities/dist/chart/preview/data-labels.js +334 -0
  22. package/dist/capabilities/dist/chart/preview/error-bars.js +213 -0
  23. package/dist/capabilities/dist/chart/preview/index.js +190 -0
  24. package/dist/capabilities/dist/chart/preview/layout.js +519 -0
  25. package/dist/capabilities/dist/chart/preview/legend.js +273 -0
  26. package/dist/capabilities/dist/chart/preview/line-area.js +404 -0
  27. package/dist/capabilities/dist/chart/preview/markers.js +100 -0
  28. package/dist/capabilities/dist/chart/preview/number-format.js +247 -0
  29. package/dist/capabilities/dist/chart/preview/pie-doughnut.js +159 -0
  30. package/dist/capabilities/dist/chart/preview/scales.js +365 -0
  31. package/dist/capabilities/dist/chart/preview/scatter.js +131 -0
  32. package/dist/capabilities/dist/chart/preview/style.js +48 -0
  33. package/dist/capabilities/dist/chart/preview/text-render.js +116 -0
  34. package/dist/capabilities/dist/chart/preview/trendlines.js +537 -0
  35. package/dist/capabilities/dist/chart/preview/types.js +5 -0
  36. package/dist/capabilities/dist/document.js +148 -0
  37. package/dist/capabilities/dist/font/font-embedding.js +289 -0
  38. package/dist/capabilities/dist/font/font-family.js +10 -0
  39. package/dist/capabilities/dist/font/font-import.js +302 -0
  40. package/dist/capabilities/dist/font/font-subset.js +55 -0
  41. package/dist/capabilities/dist/font/font.js +25 -0
  42. package/dist/capabilities/dist/group/group-codegen.js +51 -0
  43. package/dist/capabilities/dist/group/group-declaration.js +42 -0
  44. package/dist/capabilities/dist/group/group-elements.js +12 -0
  45. package/dist/capabilities/dist/group/group-import.js +319 -0
  46. package/dist/capabilities/dist/group/group-xml.js +7 -0
  47. package/dist/capabilities/dist/group/group.js +211 -0
  48. package/dist/capabilities/dist/image/gif-decoder.js +244 -0
  49. package/dist/capabilities/dist/image/image-codegen.js +94 -0
  50. package/dist/capabilities/dist/image/image-declaration.js +8 -0
  51. package/dist/capabilities/dist/image/image-decode.js +221 -0
  52. package/dist/capabilities/dist/image/image-elements.js +12 -0
  53. package/dist/capabilities/dist/image/image-import.js +778 -0
  54. package/dist/capabilities/dist/image/image-schemas.js +149 -0
  55. package/dist/capabilities/dist/image/image-xml.js +12 -0
  56. package/dist/capabilities/dist/image/image.js +472 -0
  57. package/dist/capabilities/dist/masters/footer-placeholder.js +685 -0
  58. package/dist/capabilities/dist/masters/masters-codegen.js +21 -0
  59. package/dist/capabilities/dist/masters/masters.js +250 -0
  60. package/dist/capabilities/dist/motion/motion-api.js +527 -0
  61. package/dist/capabilities/dist/motion/motion-codegen.js +340 -0
  62. package/dist/capabilities/dist/motion/motion-elements.js +43 -0
  63. package/dist/capabilities/dist/motion/motion-import.js +1033 -0
  64. package/dist/capabilities/dist/motion/motion-plan.js +2189 -0
  65. package/dist/capabilities/dist/motion/motion-query.js +420 -0
  66. package/dist/capabilities/dist/motion/motion-schemas.js +216 -0
  67. package/dist/capabilities/dist/motion/motion.js +1372 -0
  68. package/dist/capabilities/dist/notes/notes-codegen.js +20 -0
  69. package/dist/capabilities/dist/notes/notes-declaration.js +8 -0
  70. package/dist/capabilities/dist/notes/notes-elements.js +12 -0
  71. package/dist/capabilities/dist/notes/notes-import.js +292 -0
  72. package/dist/capabilities/dist/notes/notes-schemas.js +35 -0
  73. package/dist/capabilities/dist/notes/notes-xml.js +38 -0
  74. package/dist/capabilities/dist/notes/notes.js +191 -0
  75. package/dist/capabilities/dist/placeholder/placeholder-codegen.js +23 -0
  76. package/dist/capabilities/dist/placeholder/placeholder-elements.js +12 -0
  77. package/dist/capabilities/dist/placeholder/placeholder.js +292 -0
  78. package/dist/capabilities/dist/shape/shape-codegen.js +166 -0
  79. package/dist/capabilities/dist/shape/shape-declaration.js +57 -0
  80. package/dist/capabilities/dist/shape/shape-elements.js +12 -0
  81. package/dist/capabilities/dist/shape/shape-import.js +579 -0
  82. package/dist/capabilities/dist/shape/shape-xml.js +6 -0
  83. package/dist/capabilities/dist/shape/shape.js +337 -0
  84. package/dist/capabilities/dist/shared/geometry.js +1423 -0
  85. package/dist/capabilities/dist/shared/identity.js +205 -0
  86. package/dist/capabilities/dist/shared/morph-api.js +11 -0
  87. package/dist/capabilities/dist/shared/placeholder-import.js +113 -0
  88. package/dist/capabilities/dist/shared/preset-definitions.js +21390 -0
  89. package/dist/capabilities/dist/shared/style-inheritance.js +166 -0
  90. package/dist/capabilities/dist/shared/style-parse.js +11 -0
  91. package/dist/capabilities/dist/shared/text-schemas.js +216 -0
  92. package/dist/capabilities/dist/shared/text-service.js +1883 -0
  93. package/dist/capabilities/dist/shared/visual.js +918 -0
  94. package/dist/capabilities/dist/slide-background/slide-background-codegen.js +44 -0
  95. package/dist/capabilities/dist/slide-background/slide-background-import.js +161 -0
  96. package/dist/capabilities/dist/slide-background/slide-background-xml.js +21 -0
  97. package/dist/capabilities/dist/slide-background/slide-background.js +221 -0
  98. package/dist/capabilities/dist/table/table-codegen.js +81 -0
  99. package/dist/capabilities/dist/table/table-declaration.js +15 -0
  100. package/dist/capabilities/dist/table/table-elements.js +27 -0
  101. package/dist/capabilities/dist/table/table-import.js +539 -0
  102. package/dist/capabilities/dist/table/table-schemas.js +279 -0
  103. package/dist/capabilities/dist/table/table-xml.js +37 -0
  104. package/dist/capabilities/dist/table/table.js +662 -0
  105. package/dist/capabilities/dist/text/text-codegen.js +129 -0
  106. package/dist/capabilities/dist/text/text-declaration.js +19 -0
  107. package/dist/capabilities/dist/text/text-elements.js +38 -0
  108. package/dist/capabilities/dist/text/text-import.js +1077 -0
  109. package/dist/capabilities/dist/text/text-xml.js +9 -0
  110. package/dist/capabilities/dist/text/text.js +335 -0
  111. package/dist/capabilities/dist/transition/transition-api.js +139 -0
  112. package/dist/capabilities/dist/transition/transition-codegen.js +45 -0
  113. package/dist/capabilities/dist/transition/transition-import.js +477 -0
  114. package/dist/capabilities/dist/transition/transition.js +260 -0
  115. package/dist/capability-D_xeNVIw.d.ts +29496 -0
  116. package/dist/cli.js +20 -0
  117. package/dist/codegen/dist/assets.js +78 -0
  118. package/dist/codegen/dist/codegen.js +611 -0
  119. package/dist/codegen/dist/identifiers.js +193 -0
  120. package/dist/codegen/dist/index.js +3 -0
  121. package/dist/codegen/dist/printer.js +143 -0
  122. package/dist/codegen/dist/types.js +49 -0
  123. package/dist/core/dist/author-ids.js +48 -0
  124. package/dist/core/dist/author-schemas.js +313 -0
  125. package/dist/core/dist/block-flex-layout.js +749 -0
  126. package/dist/core/dist/build.js +4 -0
  127. package/dist/core/dist/capability.js +13 -0
  128. package/dist/core/dist/declaration.js +15 -0
  129. package/dist/core/dist/diagnostics.js +21 -0
  130. package/dist/core/dist/document-internals.js +13 -0
  131. package/dist/core/dist/document.js +408 -0
  132. package/dist/core/dist/geometry-schemas.js +249 -0
  133. package/dist/core/dist/grid-layout.js +445 -0
  134. package/dist/core/dist/host.js +40 -0
  135. package/dist/core/dist/index.js +15 -0
  136. package/dist/core/dist/input-values.js +45 -0
  137. package/dist/core/dist/layout-protocol.js +66 -0
  138. package/dist/core/dist/layout-schemas.js +208 -0
  139. package/dist/core/dist/layout.js +299 -0
  140. package/dist/core/dist/masters.js +169 -0
  141. package/dist/core/dist/morph.js +30 -0
  142. package/dist/core/dist/placeholders.js +213 -0
  143. package/dist/core/dist/query.js +155 -0
  144. package/dist/core/dist/resolution.js +11 -0
  145. package/dist/core/dist/resolve.js +1827 -0
  146. package/dist/core/dist/stage-options.js +67 -0
  147. package/dist/core/dist/theme.js +931 -0
  148. package/dist/document-BHPUODPP.d.ts +27759 -0
  149. package/dist/emit/dist/emit.js +936 -0
  150. package/dist/emit/dist/index.js +5 -0
  151. package/dist/emit/dist/ooxml.js +606 -0
  152. package/dist/emit/dist/shape-tree.js +12 -0
  153. package/dist/import/dist/alternate-content.js +54 -0
  154. package/dist/import/dist/diagnostics.js +153 -0
  155. package/dist/import/dist/fonts.js +250 -0
  156. package/dist/import/dist/import.js +504 -0
  157. package/dist/import/dist/index.js +16 -0
  158. package/dist/import/dist/masters.js +1153 -0
  159. package/dist/import/dist/mechanism.js +10 -0
  160. package/dist/import/dist/namespaces.js +60 -0
  161. package/dist/import/dist/notes-masters.js +300 -0
  162. package/dist/import/dist/opc.js +233 -0
  163. package/dist/import/dist/resources.js +166 -0
  164. package/dist/import/dist/sections.js +139 -0
  165. package/dist/import/dist/themes.js +671 -0
  166. package/dist/import/dist/visual.js +761 -0
  167. package/dist/import/dist/xml-fragments.js +36 -0
  168. package/dist/import/dist/xml-reader.js +267 -0
  169. package/dist/index-B5m3hqjC.d.ts +7 -0
  170. package/dist/index-CCy-Yo8G.d.ts +1208 -0
  171. package/dist/index-DpxcZ4Gs.d.ts +725 -0
  172. package/dist/index.d.ts +7 -0
  173. package/dist/index.js +70 -0
  174. package/dist/node.d.ts +53 -0
  175. package/dist/node.js +194 -0
  176. package/dist/pptxdk/src/cli-commands.js +913 -0
  177. package/dist/pptxdk/src/compose.js +44 -0
  178. package/dist/pptxdk/src/slide.js +9 -0
  179. package/dist/preview/dist/index.js +240 -0
  180. package/dist/preview/dist/options.js +53 -0
  181. package/dist/preview-Cfw0QdMM.d.ts +86 -0
  182. package/dist/preview.d.ts +3 -0
  183. package/dist/preview.js +27 -0
  184. package/dist/react/dist/append.js +66 -0
  185. package/dist/react/dist/document-adapter.js +65 -0
  186. package/dist/react/dist/elements.js +59 -0
  187. package/dist/react/dist/index.js +68 -0
  188. package/dist/react/dist/reconciler.js +290 -0
  189. package/dist/react.d.ts +145 -0
  190. package/dist/react.js +27 -0
  191. package/dist/transition-Cips9wma.d.ts +82 -0
  192. package/dist/vanilla.d.ts +4 -0
  193. package/dist/vanilla.js +14 -0
  194. package/package.json +78 -3
@@ -0,0 +1,1883 @@
1
+ import { CapabilityError } from "../../../core/dist/diagnostics.js";
2
+ import { textStyleKeys, validateTextStyle } from "../../../core/dist/theme.js";
3
+ import "../../../core/dist/placeholders.js";
4
+ import { paddingStyleKeys } from "../../../core/dist/block-flex-layout.js";
5
+ import "../../../core/dist/capability.js";
6
+ import { pxToEmu, resolvedColorXml, xmlEscape } from "../../../emit/dist/ooxml.js";
7
+ import "../../../emit/dist/index.js";
8
+ import { fontPresentationContributions, requiresFontGlyph } from "../font/font-embedding.js";
9
+ import { matchesFontFamily } from "../font/font-family.js";
10
+ import { hasLocalDeclaration, localDeclaredKeySet, resolvePlaceholderBaseTextStyle, resolvePlaceholderLevelTextStyle } from "./style-inheritance.js";
11
+ import { parseParagraphStyle, parseRunStyle, parseTextInsets } from "./text-schemas.js";
12
+ import { resolveShadow, textShadowXml } from "./visual.js";
13
+ import { createHash } from "node:crypto";
14
+ import * as fontkit from "fontkit";
15
+ import * as hb from "harfbuzzjs";
16
+ import LineBreakerImplementation from "linebreak";
17
+ // ../capabilities/dist/shared/text-service.js
18
+ /**
19
+ * Author metadata accepted on P, Span, and SlideNumber declarations.
20
+ *
21
+ * Scoped id validation belongs to the formal build around these nodes; the shared text parser must
22
+ * skip the field while resolving styles instead of reporting it as an unimplemented parameter.
23
+ */
24
+ const textAuthorMetadataKeys = /* @__PURE__ */ new Set(["id"]);
25
+ const LineBreaker = LineBreakerImplementation;
26
+ const graphemes = new Intl.Segmenter(void 0, { granularity: "grapheme" });
27
+ const measureFaces = /* @__PURE__ */ new Map();
28
+ const hbFaces = /* @__PURE__ */ new Map();
29
+ let sharedHbBuffer;
30
+ let sharedHbBufferBusy = false;
31
+ function withHbBuffer(fn) {
32
+ if (!sharedHbBufferBusy) {
33
+ sharedHbBufferBusy = true;
34
+ sharedHbBuffer ??= new hb.Buffer();
35
+ try {
36
+ return fn(sharedHbBuffer);
37
+ } finally {
38
+ sharedHbBuffer.reset();
39
+ sharedHbBufferBusy = false;
40
+ }
41
+ }
42
+ const buffer = new hb.Buffer();
43
+ try {
44
+ return fn(buffer);
45
+ } finally {
46
+ buffer.reset();
47
+ }
48
+ }
49
+ const defaultTextStyle = Object.freeze({
50
+ fontFamily: "minor",
51
+ fontSize: 24,
52
+ fontWeight: "normal",
53
+ fontStyle: "normal",
54
+ color: "tx1"
55
+ });
56
+ function record(value) {
57
+ return typeof value === "object" && value !== null && !Array.isArray(value);
58
+ }
59
+ function escapedXml(value) {
60
+ try {
61
+ return xmlEscape(value);
62
+ } catch {
63
+ throw new CapabilityError("invalid-xml-character", "Text content or font name contains characters not allowed in XML 1.0");
64
+ }
65
+ }
66
+ function isHostText(child) {
67
+ return child.type === "#text" && "text" in child;
68
+ }
69
+ function hostChild(value) {
70
+ if (!record(value) || typeof value["type"] !== "string") return false;
71
+ if (value["type"] === "#text") return typeof value["text"] === "string";
72
+ return value["type"].trim() !== "" && record(value["props"]) && Array.isArray(value["children"]);
73
+ }
74
+ function styleRecord(value, label) {
75
+ if (value === void 0) return {};
76
+ if (!record(value)) throw new CapabilityError("invalid-style", `${label} must be an object`);
77
+ return value;
78
+ }
79
+ function onlyKnownKeys(value, allowed, label) {
80
+ const unknown = Object.keys(value).find((key) => !allowed.includes(key));
81
+ if (unknown !== void 0) throw new CapabilityError("unknown-style-property", `${label} contains unimplemented style ${unknown}`);
82
+ }
83
+ function positiveLength(value, label) {
84
+ let pixels;
85
+ if (typeof value === "number") pixels = value;
86
+ else if (typeof value === "string") {
87
+ const match = /^(\d+(?:\.\d+)?)(px|pt)$/u.exec(value);
88
+ if (match === null) throw new CapabilityError("invalid-text-length", `${label} must be a positive pixel value or px/pt length`);
89
+ const amount = Number(match[1]);
90
+ pixels = match[2] === "pt" ? amount * 4 / 3 : amount;
91
+ } else throw new CapabilityError("invalid-text-length", `${label} must be a positive pixel value or px/pt length`);
92
+ if (!Number.isFinite(pixels) || pixels <= 0) throw new CapabilityError("invalid-text-length", `${label} must be greater than 0`);
93
+ return pixels;
94
+ }
95
+ function centipoints(value) {
96
+ return Math.round(value * 100);
97
+ }
98
+ function spacingCentipoints(pixels, label) {
99
+ const value = Math.round(pixels * 75);
100
+ if (value < 0 || value > 158400) throw new CapabilityError(label === "lineHeight" ? "invalid-text-length" : "invalid-paragraph-spacing", `${label} converted value must be within DrawingML range of 0 to 1584pt`);
101
+ return value;
102
+ }
103
+ function letterSpacingCentipoints(value) {
104
+ const points = Math.round(value * 75);
105
+ if (!Number.isFinite(value) || points < -4e5 || points > 4e5) throw new CapabilityError("invalid-letter-spacing", "letterSpacing converted value must be within DrawingML range of -4000 to 4000pt");
106
+ return points;
107
+ }
108
+ function fontSizePoints(value) {
109
+ let points;
110
+ if (value === void 0) points = positiveLength(defaultTextStyle.fontSize, "fontSize") * .75;
111
+ else if (typeof value === "string" && value.endsWith("pt")) {
112
+ points = Number(value.slice(0, -2));
113
+ if (!Number.isFinite(points) || points <= 0) throw new CapabilityError("invalid-font-size", "fontSize must be greater than 0");
114
+ } else points = positiveLength(value, "fontSize") * .75;
115
+ const serialized = centipoints(points);
116
+ if (serialized < 100 || serialized > 4e5) throw new CapabilityError("invalid-font-size", "fontSize converted value must be within DrawingML range of 1 to 4000pt");
117
+ return serialized / 100;
118
+ }
119
+ function weightValue(value) {
120
+ if (value === void 0 || value === "normal") return 400;
121
+ if (value === "bold") return 700;
122
+ return value;
123
+ }
124
+ function fontFamilyValue(value) {
125
+ if (value === void 0) return { family: "Aptos" };
126
+ return typeof value === "string" ? { family: value } : value;
127
+ }
128
+ function normalizedFonts(style) {
129
+ const family = fontFamilyValue(style.fontFamily);
130
+ const weight = weightValue(style.fontWeight);
131
+ const faceStyle = style.fontStyle ?? "normal";
132
+ const providedFaces = (family.faces ?? []).filter((candidate) => (candidate.weight ?? 400) === weight && (candidate.style ?? "normal") === faceStyle).filter((candidate) => candidate.data !== void 0);
133
+ if (providedFaces.length === 0) return [{
134
+ family: family.family,
135
+ weight,
136
+ style: faceStyle,
137
+ substitute: family.substitute ?? false,
138
+ embeddable: family.embeddable ?? true,
139
+ hasResource: false,
140
+ identity: "missing"
141
+ }];
142
+ return providedFaces.map((face) => ({
143
+ family: family.family,
144
+ weight,
145
+ style: faceStyle,
146
+ substitute: family.substitute ?? false,
147
+ embeddable: family.embeddable ?? true,
148
+ hasResource: true,
149
+ identity: createHash("sha256").update(face.data).digest("hex"),
150
+ data: face.data
151
+ }));
152
+ }
153
+ function validateRunStyle(style) {
154
+ const { themeFont: _themeFont, color, ...rest } = style;
155
+ validateTextStyle({
156
+ ...rest,
157
+ ...color !== void 0 && !isResolvedColor(color) ? { color } : {}
158
+ });
159
+ return style;
160
+ }
161
+ function readRunStyle(value) {
162
+ return parseRunStyle(value, "Span.style");
163
+ }
164
+ function mergeRunStyle(parent, child, theme) {
165
+ const declared = Object.fromEntries(Object.entries(child).filter(([, value]) => value !== void 0));
166
+ if (child.fontFamily !== void 0) {
167
+ const font = theme.resolveFont(child.fontFamily);
168
+ declared["fontFamily"] = font.font ?? font.family;
169
+ if (child.themeFont === void 0 && font.themeFont === void 0) delete declared["themeFont"];
170
+ else declared["themeFont"] = child.themeFont ?? font.themeFont;
171
+ }
172
+ if (child.color !== void 0 && !isResolvedColor(child.color)) declared["color"] = theme.resolveColor(child.color);
173
+ if (child.lang !== void 0) declared["lang"] = child.lang;
174
+ const merged = {
175
+ ...parent,
176
+ ...declared
177
+ };
178
+ if (child.textShadow === "none") delete merged.textShadow;
179
+ if (child.fontFamily !== void 0 && declared["themeFont"] === void 0) {
180
+ const { themeFont: _themeFont, ...withoutThemeFont } = merged;
181
+ return validateRunStyle(withoutThemeFont);
182
+ }
183
+ return validateRunStyle(merged);
184
+ }
185
+ function isResolvedColor(value) {
186
+ return record(value) && typeof value["hex"] === "string";
187
+ }
188
+ function outputBold(font) {
189
+ const fallback = font.weight >= 600;
190
+ if (!font.hasResource || font.substitute) return fallback;
191
+ try {
192
+ return measureFace(font).font["OS/2"].fsSelection.bold;
193
+ } catch {
194
+ return fallback;
195
+ }
196
+ }
197
+ function mergeLocalRunDeclared(parent, child, theme) {
198
+ const declared = { ...parent };
199
+ for (const [key, value] of Object.entries(child)) {
200
+ if (!Object.hasOwn(child, key) || value === void 0) continue;
201
+ declared[key] = value;
202
+ }
203
+ if (hasLocalDeclaration(child, "fontFamily")) {
204
+ const resolved = theme.resolveFont(child["fontFamily"]);
205
+ declared["fontFamily"] = resolved.font ?? resolved.family;
206
+ if (resolved.themeFont === void 0) delete declared["themeFont"];
207
+ else declared["themeFont"] = resolved.themeFont;
208
+ }
209
+ if (hasLocalDeclaration(child, "color") && !isResolvedColor(child["color"])) declared["color"] = theme.resolveColor(child["color"]);
210
+ return declared;
211
+ }
212
+ function resolveRunStyleFromRecord(style, theme) {
213
+ const font = theme.resolveFont(style["fontFamily"] ?? defaultTextStyle.fontFamily);
214
+ const rawColor = style["color"];
215
+ const color = rawColor === void 0 ? theme.resolveColor(defaultTextStyle.color) : isResolvedColor(rawColor) ? rawColor : theme.resolveColor(rawColor);
216
+ return validateRunStyle({
217
+ fontFamily: font.font ?? font.family,
218
+ fontSize: style["fontSize"] ?? defaultTextStyle.fontSize,
219
+ fontWeight: style["fontWeight"] ?? defaultTextStyle.fontWeight,
220
+ fontStyle: style["fontStyle"] ?? defaultTextStyle.fontStyle,
221
+ color,
222
+ ...font.themeFont === void 0 ? {} : { themeFont: font.themeFont },
223
+ ...style["letterSpacing"] === void 0 ? {} : { letterSpacing: style["letterSpacing"] },
224
+ ...style["textTransform"] === void 0 ? {} : { textTransform: style["textTransform"] },
225
+ ...style["textDecoration"] === void 0 ? {} : { textDecoration: style["textDecoration"] },
226
+ ...style["textShadow"] === void 0 || style["textShadow"] === "none" ? {} : { textShadow: style["textShadow"] },
227
+ ...style["lang"] === void 0 ? {} : { lang: style["lang"] }
228
+ });
229
+ }
230
+ function readPlaceholderTextStyle(value, label, placeholder) {
231
+ const props = styleRecord(value, label);
232
+ onlyKnownKeys(props, [...textStyleKeys], label);
233
+ const localDeclaredStyle = {};
234
+ for (const key of textStyleKeys) if (hasLocalDeclaration(props, key)) localDeclaredStyle[key] = props[key];
235
+ const effectiveBase = resolvePlaceholderBaseTextStyle(placeholder, localDeclaredStyle);
236
+ const masterTheme = placeholder.masterTheme;
237
+ const merged = {
238
+ ...defaultTextStyle,
239
+ ...effectiveBase
240
+ };
241
+ const font = masterTheme.resolveFont(merged.fontFamily ?? defaultTextStyle.fontFamily);
242
+ if (merged.color !== void 0 && !isResolvedColor(merged.color)) masterTheme.resolveColor(merged.color);
243
+ validateTextStyle({
244
+ ...merged,
245
+ fontFamily: font.font ?? font.family,
246
+ ...isResolvedColor(merged.color) ? { color: void 0 } : {}
247
+ });
248
+ const result = {
249
+ ...merged,
250
+ fontFamily: font.font ?? font.family,
251
+ ...font.themeFont === void 0 ? {} : { themeFont: font.themeFont }
252
+ };
253
+ if (result.textShadow === "none") delete result.textShadow;
254
+ return {
255
+ style: result,
256
+ localDeclaredStyle
257
+ };
258
+ }
259
+ function readTextStyle(value, label, theme) {
260
+ const props = styleRecord(value, label);
261
+ onlyKnownKeys(props, [...textStyleKeys], label);
262
+ const style = {
263
+ ...defaultTextStyle,
264
+ ...theme.textStyle,
265
+ ...props
266
+ };
267
+ const runStyle = {
268
+ fontFamily: style.fontFamily,
269
+ fontSize: style.fontSize,
270
+ fontWeight: style.fontWeight,
271
+ fontStyle: style.fontStyle,
272
+ color: style.color,
273
+ themeFont: style.themeFont,
274
+ letterSpacing: style.letterSpacing,
275
+ textTransform: style.textTransform,
276
+ textDecoration: style.textDecoration,
277
+ textShadow: style.textShadow,
278
+ lang: style.lang
279
+ };
280
+ const font = theme.resolveFont(runStyle.fontFamily ?? defaultTextStyle.fontFamily);
281
+ if (runStyle.color !== void 0 && !isResolvedColor(runStyle.color)) theme.resolveColor(runStyle.color);
282
+ validateTextStyle({
283
+ ...style,
284
+ fontFamily: font.font ?? font.family,
285
+ ...isResolvedColor(style.color) ? { color: void 0 } : {}
286
+ });
287
+ const result = {
288
+ ...style,
289
+ fontFamily: font.font ?? font.family,
290
+ ...font.themeFont === void 0 ? {} : { themeFont: font.themeFont }
291
+ };
292
+ if (result.textShadow === "none") delete result.textShadow;
293
+ return result;
294
+ }
295
+ function paragraphStyle(value) {
296
+ return parseParagraphStyle(value, "P.style");
297
+ }
298
+ function collectRuns(children, style, runs, theme, fields, localDeclared) {
299
+ for (const child of children) {
300
+ if (!hostChild(child)) throw new CapabilityError("invalid-text-child", "Text content tree contains invalid nodes");
301
+ if (isHostText(child)) {
302
+ if (child.text !== "") runs.push({
303
+ text: child.text,
304
+ style,
305
+ ...localDeclared === void 0 ? {} : { localDeclared }
306
+ });
307
+ continue;
308
+ }
309
+ if (child.type !== "span" && child.type !== "slide-number") throw new CapabilityError("unsupported-text-child", `${child.type} cannot be used as text paragraph or run`);
310
+ const unknown = Object.keys(child.props).find((key) => key !== "style" && !textAuthorMetadataKeys.has(key));
311
+ if (unknown !== void 0) throw new CapabilityError("unknown-parameter", `Span contains unimplemented parameter ${unknown}`);
312
+ const spanStyle = readRunStyle(child.props["style"]);
313
+ const nextStyle = mergeRunStyle(style, spanStyle, theme);
314
+ const nextLocalDeclared = localDeclared === void 0 ? void 0 : mergeLocalRunDeclared(localDeclared, spanStyle, theme);
315
+ if (child.type === "slide-number") {
316
+ if (child.children.length > 0) throw new CapabilityError("invalid-slide-number", "SlideNumber cannot contain children");
317
+ runs.push({
318
+ text: String(fields.slideNumber),
319
+ style: nextStyle,
320
+ ...nextLocalDeclared === void 0 ? {} : { localDeclared: nextLocalDeclared },
321
+ field: {
322
+ id: fields.createId?.() ?? "00000000-0000-4000-8000-000000000001",
323
+ type: "slidenum"
324
+ }
325
+ });
326
+ continue;
327
+ }
328
+ collectRuns(child.children, nextStyle, runs, theme, fields, nextLocalDeclared);
329
+ }
330
+ }
331
+ function resolveDecoration(value) {
332
+ return value ?? "none";
333
+ }
334
+ function resolveTransform(value) {
335
+ return value ?? "none";
336
+ }
337
+ function resolveTextShadowModel(theme, value) {
338
+ if (value === void 0 || value === "none") return { kind: "none" };
339
+ return {
340
+ kind: "shadow",
341
+ shadow: resolveShadow(theme, value, "textShadow")
342
+ };
343
+ }
344
+ function resolveAlign(value, fallback = "left") {
345
+ return value ?? fallback;
346
+ }
347
+ function resolveVerticalAlign(value) {
348
+ return value ?? "top";
349
+ }
350
+ function resolveListModel(value) {
351
+ if (value === void 0) return void 0;
352
+ switch (value.type) {
353
+ case "bullet": return {
354
+ type: "bullet",
355
+ character: value.character ?? "•",
356
+ level: value.level ?? 0
357
+ };
358
+ case "number": return {
359
+ type: "number",
360
+ style: value.style ?? "arabicPeriod",
361
+ startAt: value.startAt ?? 1,
362
+ level: value.level ?? 0
363
+ };
364
+ default: return value;
365
+ }
366
+ }
367
+ function decorationAttribute(decoration) {
368
+ switch (decoration) {
369
+ case "none": return [];
370
+ case "underline": return ["u=\"sng\""];
371
+ case "line-through": return ["strike=\"sngStrike\""];
372
+ default: return decoration;
373
+ }
374
+ }
375
+ function transformAttribute(transform) {
376
+ switch (transform) {
377
+ case "none": return [];
378
+ case "uppercase": return ["cap=\"all\""];
379
+ default: return transform;
380
+ }
381
+ }
382
+ function runFontSlotsXml(style) {
383
+ const font = normalizedFonts(style)[0];
384
+ const latinTypeface = style.themeFont === "major" ? "+mj-lt" : style.themeFont === "minor" ? "+mn-lt" : font.family;
385
+ const eaTypeface = style.themeFont === "major" ? "+mj-ea" : style.themeFont === "minor" ? "+mn-ea" : font.family;
386
+ const csTypeface = style.themeFont === "major" ? "+mj-cs" : style.themeFont === "minor" ? "+mn-cs" : font.family;
387
+ return `<a:latin typeface="${escapedXml(latinTypeface)}"/><a:ea typeface="${escapedXml(eaTypeface)}"/><a:cs typeface="${escapedXml(csTypeface)}"/>`;
388
+ }
389
+ function runPropertiesXml(style, tag, theme, differential = false) {
390
+ if (differential) {
391
+ const attributes = [];
392
+ if (style.lang !== void 0) attributes.push(`lang="${escapedXml(style.lang)}"`);
393
+ if (style.fontSize !== void 0) attributes.push(`sz="${centipoints(fontSizePoints(style.fontSize))}"`);
394
+ if (style.fontWeight !== void 0) {
395
+ const font = normalizedFonts(style)[0];
396
+ attributes.push(`b="${outputBold(font) ? 1 : 0}"`);
397
+ }
398
+ if (style.fontStyle !== void 0) attributes.push(`i="${style.fontStyle === "italic" ? 1 : 0}"`);
399
+ if (style.textDecoration !== void 0) attributes.push(...decorationAttribute(resolveDecoration(style.textDecoration)));
400
+ if (style.textTransform !== void 0) attributes.push(...transformAttribute(resolveTransform(style.textTransform)));
401
+ if (style.letterSpacing !== void 0) attributes.push(`spc="${letterSpacingCentipoints(style.letterSpacing)}"`);
402
+ const fillXml = style.color === void 0 ? "" : `<a:solidFill>${resolvedColorXml(isResolvedColor(style.color) ? style.color : theme.resolveColor(style.color))}</a:solidFill>`;
403
+ const shadowXml = style.textShadow === void 0 ? "" : textShadowXml(theme, style.textShadow);
404
+ const fontXml = style.fontFamily === void 0 && style.themeFont === void 0 ? "" : runFontSlotsXml(style);
405
+ const attrText = attributes.length === 0 ? "" : ` ${attributes.join(" ")}`;
406
+ const childrenXml = `${fillXml}${shadowXml}${fontXml}`;
407
+ return childrenXml === "" ? `<${tag}${attrText}/>` : `<${tag}${attrText}>${childrenXml}</${tag}>`;
408
+ }
409
+ const font = normalizedFonts(style)[0];
410
+ const points = fontSizePoints(style.fontSize);
411
+ const bold = outputBold(font);
412
+ const color = isResolvedColor(style.color) ? style.color : theme.resolveColor(style.color ?? "dk1");
413
+ const fontSlots = runFontSlotsXml(style);
414
+ const decoration = resolveDecoration(style.textDecoration);
415
+ const transform = resolveTransform(style.textTransform);
416
+ return `<${tag} ${[
417
+ ...style.lang !== void 0 ? [`lang="${escapedXml(style.lang)}"`] : [],
418
+ `sz="${centipoints(points)}"`,
419
+ `b="${bold ? 1 : 0}"`,
420
+ `i="${font.style === "italic" ? 1 : 0}"`,
421
+ ...decorationAttribute(decoration),
422
+ ...transformAttribute(transform),
423
+ ...style.letterSpacing === void 0 || style.letterSpacing === 0 ? [] : [`spc="${letterSpacingCentipoints(style.letterSpacing)}"`]
424
+ ].join(" ")}><a:solidFill>${resolvedColorXml(color)}</a:solidFill>${textShadowXml(theme, style.textShadow)}${fontSlots}</${tag}>`;
425
+ }
426
+ function displayedText(run) {
427
+ return run.style.textTransform === "uppercase" ? run.text.toUpperCase() : run.text;
428
+ }
429
+ /** Emits a native `<a:fld type="slidenum">` run using a fresh or preallocated field GUID. */
430
+ function emitSlideNumberRunXml(run, theme, createFieldId, differential = false) {
431
+ const fieldId = createFieldId !== void 0 ? createFieldId() : run.field?.id ?? "00000000-0000-4000-8000-000000000001";
432
+ const fieldType = run.field?.type ?? "slidenum";
433
+ const rPr = differential ? runPropertiesXml(run.localDeclared ?? {}, "a:rPr", theme, true) : runPropertiesXml(run.style, "a:rPr", theme, false);
434
+ return `<a:fld id="${escapedXml(fieldId)}" type="${fieldType}">${rPr}<a:t>${escapedXml(run.text)}</a:t></a:fld>`;
435
+ }
436
+ function runXml(run, theme, differential = false) {
437
+ if (run.field !== void 0) return emitSlideNumberRunXml(run, theme, void 0, differential);
438
+ const text = escapedXml(run.text);
439
+ return `<a:r>${differential ? runPropertiesXml(run.localDeclared ?? {}, "a:rPr", theme, true) : runPropertiesXml(run.style, "a:rPr", theme, false)}<a:t xml:space="preserve">${text}</a:t></a:r>`;
440
+ }
441
+ function textResourceClaims(runs) {
442
+ const used = /* @__PURE__ */ new Map();
443
+ for (const run of runs) for (const font of normalizedFonts(run.style)) {
444
+ const key = `${font.family.toLocaleLowerCase("en-US")}\u0000${font.weight}\u0000${font.style}`;
445
+ const entry = used.get(key) ?? {
446
+ fonts: [],
447
+ fontPolicies: /* @__PURE__ */ new Map(),
448
+ text: []
449
+ };
450
+ if (!entry.fonts.some(({ identity }) => identity === font.identity)) entry.fonts.push(font);
451
+ const policyKey = `${font.identity}\u0000${font.substitute ? 1 : 0}\u0000${font.embeddable ? 1 : 0}`;
452
+ entry.fontPolicies.set(policyKey, font);
453
+ entry.text.push(displayedText(run), ...run.field?.type === "slidenum" ? ["0123456789"] : []);
454
+ used.set(key, entry);
455
+ }
456
+ const resourceClaims = [];
457
+ const fontUses = [];
458
+ const warnings = [];
459
+ const missingGlyphErrors = [];
460
+ for (const [key, entry] of used) {
461
+ for (const font of entry.fontPolicies.values()) fontUses.push({
462
+ family: font.family,
463
+ weight: font.weight,
464
+ style: font.style,
465
+ claimKey: key,
466
+ identity: font.identity,
467
+ ...font.data === void 0 ? {} : { bytes: font.data },
468
+ substitute: font.substitute,
469
+ embeddable: font.embeddable,
470
+ bold: outputBold(font),
471
+ italic: font.style === "italic"
472
+ });
473
+ for (const font of entry.fonts) if (!font.hasResource) warnings.push({
474
+ code: "font-measurement-unavailable",
475
+ message: `Explicit font resource is not provided for ${font.family} ${font.weight} ${font.style}; fixed-area text will not verify actual line wrapping or fitting`
476
+ });
477
+ else {
478
+ resourceClaims.push({
479
+ kind: "font-face",
480
+ key,
481
+ identity: font.identity,
482
+ characters: entry.text.join("")
483
+ });
484
+ const face = fontkitFace(font);
485
+ if (face !== void 0) {
486
+ const missing = missingCharacters(face, entry.text.join(""));
487
+ if (missing.length > 0) {
488
+ const shown = missing.slice(0, 10).join(" ");
489
+ const extra = missing.length - 10;
490
+ const message = `${font.family} is missing glyphs for characters ${shown}${extra > 0 ? `, and ${extra} more characters` : ""}`;
491
+ warnings.push({
492
+ code: "font-missing-glyph",
493
+ message
494
+ });
495
+ missingGlyphErrors.push(message);
496
+ }
497
+ }
498
+ }
499
+ }
500
+ return {
501
+ resourceClaims,
502
+ fontUses,
503
+ warnings,
504
+ missingGlyphErrors
505
+ };
506
+ }
507
+ function alignmentValue(value) {
508
+ if (value === void 0) return void 0;
509
+ switch (value) {
510
+ case "left": return "l";
511
+ case "center": return "ctr";
512
+ case "right": return "r";
513
+ case "justify": return "just";
514
+ default: return value;
515
+ }
516
+ }
517
+ function paragraphXml(paragraph, theme, differential = false) {
518
+ const style = differential ? paragraph.localStyle ?? {} : paragraph.style;
519
+ const { runs } = paragraph;
520
+ const attributes = [];
521
+ const align = alignmentValue(style.align);
522
+ if (align !== void 0) attributes.push(`algn="${align}"`);
523
+ if (paragraphBaseDirection(runs.map((run) => displayedText(run)).join("")) === "rtl") attributes.push("rtl=\"1\"");
524
+ const resolvedList = resolveListModel(style.list);
525
+ if (resolvedList !== void 0) attributes.push(`lvl="${resolvedList.level}"`);
526
+ const lineSpacing = style.lineHeight === void 0 ? "" : `<a:lnSpc><a:spcPts val="${spacingCentipoints(positiveLength(style.lineHeight, "lineHeight"), "lineHeight")}"/></a:lnSpc>`;
527
+ const spacingAfter = style.spacingAfter === void 0 || style.spacingAfter === 0 ? "" : `<a:spcAft><a:spcPts val="${spacingCentipoints(style.spacingAfter, "spacingAfter")}"/></a:spcAft>`;
528
+ let list = "";
529
+ if (resolvedList !== void 0) switch (resolvedList.type) {
530
+ case "bullet":
531
+ list = `<a:buChar char="${xmlEscape(resolvedList.character)}"/>`;
532
+ break;
533
+ case "number":
534
+ list = `<a:buAutoNum type="${resolvedList.style}" startAt="${resolvedList.startAt}"/>`;
535
+ break;
536
+ default: return resolvedList;
537
+ }
538
+ const pPr = attributes.length + lineSpacing.length + spacingAfter.length + list.length === 0 ? "" : `<a:pPr${attributes.length === 0 ? "" : ` ${attributes.join(" ")}`}${lineSpacing.length + spacingAfter.length + list.length === 0 ? "/>" : `>${lineSpacing}${spacingAfter}${list}</a:pPr>`}`;
539
+ const endStyle = differential ? paragraph.localEndStyle ?? {} : paragraph.endStyle;
540
+ const endProperties = runs.length === 0 ? differential ? runPropertiesXml(endStyle, "a:rPr", theme, true).replace(/<(\/?)a:rPr\b/gu, "<$1a:endParaRPr") : `<a:endParaRPr${endStyle.lang !== void 0 ? ` lang="${escapedXml(endStyle.lang)}"` : ""} sz="${centipoints(fontSizePoints(endStyle.fontSize))}"/>` : "";
541
+ return `<a:p>${pPr}${runs.map((run) => runXml(run, theme, differential)).join("")}${endProperties}</a:p>`;
542
+ }
543
+ function normalizeParagraphs(children, textStyle, theme, fields, placeholder, localSlideDeclaredStyle) {
544
+ const baseRunStyle = {
545
+ fontFamily: textStyle.fontFamily,
546
+ fontSize: textStyle.fontSize,
547
+ fontWeight: textStyle.fontWeight,
548
+ fontStyle: textStyle.fontStyle,
549
+ color: textStyle.color,
550
+ themeFont: textStyle.themeFont,
551
+ letterSpacing: textStyle.letterSpacing,
552
+ textTransform: textStyle.textTransform,
553
+ textDecoration: textStyle.textDecoration,
554
+ textShadow: textStyle.textShadow,
555
+ lang: textStyle.lang
556
+ };
557
+ validateRunStyle(baseRunStyle);
558
+ const localSlideRunDeclared = placeholder === void 0 ? void 0 : mergeLocalRunDeclared({}, localSlideDeclaredStyle ?? {}, placeholder.masterTheme);
559
+ const localSlidePStyle = placeholder === void 0 ? void 0 : {
560
+ ...hasLocalDeclaration(localSlideDeclaredStyle, "lineHeight") ? { lineHeight: localSlideDeclaredStyle["lineHeight"] } : {},
561
+ ...hasLocalDeclaration(localSlideDeclaredStyle, "align") ? { align: localSlideDeclaredStyle["align"] } : {},
562
+ ...hasLocalDeclaration(localSlideDeclaredStyle, "spacingAfter") ? { spacingAfter: localSlideDeclaredStyle["spacingAfter"] } : {}
563
+ };
564
+ const paragraphs = [];
565
+ let inline = [];
566
+ const baseParagraphStyle = {
567
+ ...textStyle.lineHeight === void 0 ? {} : { lineHeight: textStyle.lineHeight },
568
+ ...textStyle.align === void 0 ? {} : { align: textStyle.align },
569
+ ...textStyle.spacingAfter === void 0 ? {} : { spacingAfter: textStyle.spacingAfter },
570
+ ...textStyle.lang === void 0 ? {} : { lang: textStyle.lang }
571
+ };
572
+ const flushInline = () => {
573
+ if (inline.length > 0) {
574
+ paragraphs.push({
575
+ runs: inline,
576
+ style: baseParagraphStyle,
577
+ ...localSlidePStyle === void 0 ? {} : { localStyle: localSlidePStyle },
578
+ endStyle: baseRunStyle,
579
+ ...localSlideRunDeclared === void 0 ? {} : { localEndStyle: localSlideRunDeclared },
580
+ wrap: textStyle.textWrap ?? "normal"
581
+ });
582
+ inline = [];
583
+ }
584
+ };
585
+ for (const child of children) {
586
+ if (!hostChild(child)) throw new CapabilityError("invalid-text-child", "Text content tree contains invalid nodes");
587
+ if (isHostText(child) || child.type === "span" || child.type === "slide-number") {
588
+ collectRuns([child], baseRunStyle, inline, theme, fields, localSlideRunDeclared);
589
+ continue;
590
+ }
591
+ if (child.type !== "paragraph") throw new CapabilityError("unsupported-text-child", `${child.type} cannot be used directly in text box`);
592
+ flushInline();
593
+ const unknown = Object.keys(child.props).find((key) => key !== "style" && !textAuthorMetadataKeys.has(key));
594
+ if (unknown !== void 0) throw new CapabilityError("unknown-parameter", `P contains unimplemented parameter ${unknown}`);
595
+ const localPStyle = paragraphStyle(child.props["style"]);
596
+ const rawLevel = localPStyle.list?.level ?? 0;
597
+ const levelBase = placeholder === void 0 ? void 0 : resolvePlaceholderLevelTextStyle(placeholder, rawLevel, localSlideDeclaredStyle);
598
+ const effectiveTheme = placeholder?.masterTheme ?? theme;
599
+ const effectiveBaseP = levelBase === void 0 ? baseParagraphStyle : {
600
+ ...levelBase.lineHeight === void 0 ? {} : { lineHeight: levelBase.lineHeight },
601
+ ...levelBase.align === void 0 ? {} : { align: levelBase.align },
602
+ ...levelBase.spacingAfter === void 0 ? {} : { spacingAfter: levelBase.spacingAfter },
603
+ ...levelBase.lang === void 0 ? {} : { lang: levelBase.lang },
604
+ ...levelBase.list === void 0 ? {} : { list: levelBase.list }
605
+ };
606
+ const levelRunBase = levelBase === void 0 ? baseRunStyle : resolveRunStyleFromRecord(levelBase, effectiveTheme);
607
+ const style = {
608
+ ...effectiveBaseP,
609
+ ...localPStyle
610
+ };
611
+ const paragraphRunStyle = mergeRunStyle(levelRunBase, {
612
+ fontFamily: style.fontFamily,
613
+ fontSize: style.fontSize,
614
+ fontWeight: style.fontWeight,
615
+ fontStyle: style.fontStyle,
616
+ color: style.color,
617
+ letterSpacing: style.letterSpacing,
618
+ textTransform: style.textTransform,
619
+ textDecoration: style.textDecoration,
620
+ textShadow: style.textShadow,
621
+ lang: style.lang
622
+ }, effectiveTheme);
623
+ const mergedLocalPStyle = placeholder === void 0 ? void 0 : {
624
+ ...localSlidePStyle,
625
+ ...localPStyle
626
+ };
627
+ const localPRunDeclared = placeholder === void 0 ? void 0 : mergeLocalRunDeclared(localSlideRunDeclared ?? {}, localPStyle, effectiveTheme);
628
+ const runs = [];
629
+ collectRuns(child.children, paragraphRunStyle, runs, effectiveTheme, fields, localPRunDeclared);
630
+ paragraphs.push({
631
+ runs,
632
+ style,
633
+ ...mergedLocalPStyle === void 0 ? {} : { localStyle: mergedLocalPStyle },
634
+ endStyle: paragraphRunStyle,
635
+ ...localPRunDeclared === void 0 ? {} : { localEndStyle: localPRunDeclared },
636
+ wrap: textStyle.textWrap ?? "normal"
637
+ });
638
+ }
639
+ flushInline();
640
+ if (paragraphs.length === 0) paragraphs.push({
641
+ runs: [],
642
+ style: baseParagraphStyle,
643
+ ...localSlidePStyle === void 0 ? {} : { localStyle: localSlidePStyle },
644
+ endStyle: baseRunStyle,
645
+ ...localSlideRunDeclared === void 0 ? {} : { localEndStyle: localSlideRunDeclared },
646
+ wrap: textStyle.textWrap ?? "normal"
647
+ });
648
+ return paragraphs;
649
+ }
650
+ function measureFace(source) {
651
+ if (!source.hasResource || source.data === void 0) throw new CapabilityError("font-measurement-unavailable", `Content-sized text is missing explicit font resource for ${source.family} ${source.weight} ${source.style}`);
652
+ let parsed = measureFaces.get(source.identity);
653
+ if (parsed === void 0) try {
654
+ const data = source.data;
655
+ const bytes = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
656
+ const opened = fontkit.create(bytes);
657
+ if (!("unitsPerEm" in opened)) throw new Error("Font collection is not a single font file");
658
+ parsed = opened;
659
+ measureFaces.set(source.identity, parsed);
660
+ } catch (error) {
661
+ throw new CapabilityError("font-format-unsupported", `Cannot parse font metrics file for ${source.family}: ${error instanceof Error ? error.message : String(error)}`);
662
+ }
663
+ if (!source.substitute && !matchesFontFamily(parsed, source.family)) throw new CapabilityError("font-substitution-required", `Metrics file declares ${parsed.familyName}; retaining output font name ${source.family} requires setting Font.substitute explicitly`);
664
+ if (parsed["OS/2"].usWeightClass !== source.weight) throw new CapabilityError("font-face-mismatch", `Font value for ${source.family} ${source.weight} ${source.style} does not match file actual weight ${parsed["OS/2"].usWeightClass}`);
665
+ if ((parsed["OS/2"].fsSelection.italic || parsed["OS/2"].fsSelection.oblique || parsed.italicAngle !== 0) !== (source.style === "italic")) throw new CapabilityError("font-face-mismatch", `Font value for ${source.family} ${source.weight} ${source.style} does not match file actual glyph style`);
666
+ if (!Number.isFinite(parsed.unitsPerEm) || parsed.unitsPerEm <= 0 || !Number.isFinite(parsed.ascent) || !Number.isFinite(parsed.descent) || !Number.isFinite(parsed.lineGap)) throw new CapabilityError("font-metrics-invalid", `Font line metrics for ${source.family} are invalid`);
667
+ if (parsed.type === "TTF" && !hbFaces.has(source.identity)) {
668
+ const blob = new hb.Blob(source.data);
669
+ const hbFace = new hb.Face(blob, 0);
670
+ const font = new hb.Font(hbFace);
671
+ hbFaces.set(source.identity, {
672
+ blob,
673
+ face: hbFace,
674
+ font
675
+ });
676
+ }
677
+ return {
678
+ font: parsed,
679
+ identity: source.identity
680
+ };
681
+ }
682
+ function measureRunFace(style) {
683
+ const candidates = normalizedFonts(style).filter((candidate) => candidate.hasResource);
684
+ const unique = candidates.filter((candidate, index) => candidates.findIndex((other) => other.identity === candidate.identity) === index);
685
+ if (unique.length !== 1) throw new CapabilityError(unique.length === 0 ? "font-measurement-unavailable" : "conflicting-resource", unique.length === 0 ? "Content-sized text must provide a font file for each actually used weight and style" : "Multiple metrics files found for the same font weight and style; cannot determine measurement basis");
686
+ return measureFace(unique[0]);
687
+ }
688
+ function fontkitFace(source) {
689
+ if (!source.hasResource || source.data === void 0) return void 0;
690
+ let parsed = measureFaces.get(source.identity);
691
+ if (parsed === void 0) try {
692
+ const data = source.data;
693
+ const bytes = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
694
+ const opened = fontkit.create(bytes);
695
+ if (!("unitsPerEm" in opened) || typeof opened.hasGlyphForCodePoint !== "function") return;
696
+ parsed = opened;
697
+ measureFaces.set(source.identity, parsed);
698
+ } catch {
699
+ return;
700
+ }
701
+ return parsed;
702
+ }
703
+ function missingCharacters(face, text) {
704
+ const font = "font" in face ? face.font : face;
705
+ const missing = /* @__PURE__ */ new Set();
706
+ for (const character of text) {
707
+ if (!requiresFontGlyph(character)) continue;
708
+ const codePoint = character.codePointAt(0);
709
+ if (codePoint !== void 0 && !font.hasGlyphForCodePoint(codePoint)) missing.add(character);
710
+ }
711
+ return [...missing];
712
+ }
713
+ function rangeWidth(pieces, text, start, end) {
714
+ const nativeEighthPointGrid = 8;
715
+ const twipsPerPoint = 20;
716
+ let natural = 0;
717
+ let eighthPoint = 0;
718
+ let twips = 0;
719
+ let spacing = 0;
720
+ let hasVisibleGrapheme = false;
721
+ let pendingTracking = 0;
722
+ for (const piece of pieces) {
723
+ const from = Math.max(start, piece.start);
724
+ const to = Math.min(end, piece.end);
725
+ if (from >= to) continue;
726
+ const source = text.slice(from, to);
727
+ const transformed = piece.style.textTransform === "uppercase" ? source.toUpperCase() : source;
728
+ const visible = Array.from(transformed).filter(requiresFontGlyph).join("");
729
+ if (visible === "") continue;
730
+ const shaped = piece.face.font.layout(visible);
731
+ const face = piece.face.font;
732
+ const points = fontSizePoints(piece.style.fontSize);
733
+ const tenths = Math.ceil(centipoints(points) / 10) / 10;
734
+ for (const position of shaped.positions) {
735
+ const advance = position.xAdvance / face.unitsPerEm * points;
736
+ natural += advance;
737
+ eighthPoint += Math.round(advance * nativeEighthPointGrid) / nativeEighthPointGrid;
738
+ const tenthAdvance = position.xAdvance / face.unitsPerEm * tenths;
739
+ twips += Math.round(tenthAdvance * twipsPerPoint) / twipsPerPoint;
740
+ }
741
+ const pieceTracking = piece.style.letterSpacing ?? 0;
742
+ const visibleCount = Array.from(graphemes.segment(visible)).length;
743
+ if (visibleCount > 0) {
744
+ if (hasVisibleGrapheme) spacing += pendingTracking;
745
+ spacing += pieceTracking * (visibleCount - 1);
746
+ hasVisibleGrapheme = true;
747
+ pendingTracking = pieceTracking;
748
+ }
749
+ }
750
+ return Math.max(natural, eighthPoint, twips) * (4 / 3) + spacing;
751
+ }
752
+ function trimLineEnd(text, start, end) {
753
+ let trimmed = end;
754
+ while (trimmed > start && /\s/u.test(text[trimmed - 1] ?? "")) trimmed -= 1;
755
+ return trimmed;
756
+ }
757
+ function graphemeEnds(text, start, end) {
758
+ const result = [];
759
+ for (const segment of graphemes.segment(text)) {
760
+ const boundary = segment.index + segment.segment.length;
761
+ if (boundary > start && boundary <= end) result.push(boundary);
762
+ }
763
+ return result;
764
+ }
765
+ function trimMandatoryBreakEnd(text, start, end) {
766
+ let trimmed = end;
767
+ while (trimmed > start && /[\n\r\v\f\u0085\u2028\u2029]/u.test(text[trimmed - 1] ?? "")) trimmed -= 1;
768
+ return trimmed;
769
+ }
770
+ function wrapParagraph(text, pieces, width) {
771
+ if (text === "") return {
772
+ lines: [{
773
+ start: 0,
774
+ end: 0,
775
+ width: 0
776
+ }],
777
+ width: 0
778
+ };
779
+ const breaks = [];
780
+ const breaker = new LineBreaker(text);
781
+ let position = 0;
782
+ for (let next = breaker.nextBreak(); next !== null; next = breaker.nextBreak()) {
783
+ if (next.position > position) breaks.push(next);
784
+ position = next.position;
785
+ }
786
+ if (position < text.length) breaks.push({
787
+ position: text.length,
788
+ required: false
789
+ });
790
+ const lines = [];
791
+ const epsilon = .01;
792
+ let lineStart = 0;
793
+ let lineEnd = 0;
794
+ let unitStart = 0;
795
+ let endedWithRequiredBreak = false;
796
+ for (const lineBreak of breaks) {
797
+ const unitEnd = lineBreak.position;
798
+ const breakContentEnd = trimMandatoryBreakEnd(text, unitStart, unitEnd);
799
+ const required = lineBreak.required || breakContentEnd < unitEnd;
800
+ if (rangeWidth(pieces, text, lineStart, trimLineEnd(text, lineStart, unitEnd)) <= width + epsilon) {
801
+ lineEnd = unitEnd;
802
+ if (required) {
803
+ lines.push({
804
+ start: lineStart,
805
+ end: lineEnd
806
+ });
807
+ lineStart = unitEnd;
808
+ lineEnd = unitEnd;
809
+ }
810
+ unitStart = unitEnd;
811
+ endedWithRequiredBreak = required;
812
+ continue;
813
+ }
814
+ if (lineEnd > lineStart) {
815
+ lines.push({
816
+ start: lineStart,
817
+ end: lineEnd
818
+ });
819
+ lineStart = unitStart;
820
+ lineEnd = unitStart;
821
+ }
822
+ if (rangeWidth(pieces, text, unitStart, trimLineEnd(text, unitStart, unitEnd)) <= width + epsilon) lineEnd = unitEnd;
823
+ else {
824
+ let chunkStart = unitStart;
825
+ let previous = chunkStart;
826
+ const fallbackEnd = required ? breakContentEnd : unitEnd;
827
+ for (const boundary of graphemeEnds(text, unitStart, fallbackEnd)) {
828
+ if (rangeWidth(pieces, text, chunkStart, trimLineEnd(text, chunkStart, boundary)) > width + epsilon && previous > chunkStart) {
829
+ lines.push({
830
+ start: chunkStart,
831
+ end: previous
832
+ });
833
+ chunkStart = previous;
834
+ }
835
+ if (rangeWidth(pieces, text, chunkStart, trimLineEnd(text, chunkStart, boundary)) > width + epsilon && previous === chunkStart) {
836
+ lines.push({
837
+ start: chunkStart,
838
+ end: boundary
839
+ });
840
+ chunkStart = boundary;
841
+ }
842
+ previous = boundary;
843
+ }
844
+ lineStart = chunkStart;
845
+ lineEnd = fallbackEnd;
846
+ }
847
+ if (required) {
848
+ if (lineEnd > lineStart) lines.push({
849
+ start: lineStart,
850
+ end: lineEnd
851
+ });
852
+ lineStart = unitEnd;
853
+ lineEnd = unitEnd;
854
+ }
855
+ unitStart = unitEnd;
856
+ endedWithRequiredBreak = required;
857
+ }
858
+ if (lineStart < text.length || lineEnd > lineStart || lines.length === 0) lines.push({
859
+ start: lineStart,
860
+ end: text.length
861
+ });
862
+ else if (endedWithRequiredBreak) lines.push({
863
+ start: text.length,
864
+ end: text.length
865
+ });
866
+ const lineWidths = lines.map(({ start, end }) => rangeWidth(pieces, text, start, trimLineEnd(text, start, end)));
867
+ return {
868
+ lines: lines.map((line, index) => ({
869
+ ...line,
870
+ width: lineWidths[index]
871
+ })),
872
+ width: Math.max(0, ...lineWidths)
873
+ };
874
+ }
875
+ function paragraphLineHeight(paragraph) {
876
+ if (paragraph.style.lineHeight !== void 0) return spacingCentipoints(positiveLength(paragraph.style.lineHeight, "lineHeight"), "lineHeight") / 75;
877
+ const styles = paragraph.runs.length > 0 ? paragraph.runs.map((run) => run.style) : [paragraph.endStyle];
878
+ let maximum = 0;
879
+ for (const style of styles) {
880
+ const face = measureRunFace(style).font;
881
+ const lineHeight = (face.ascent - face.descent + face.lineGap) / face.unitsPerEm * fontSizePoints(style.fontSize) * (4 / 3);
882
+ if (!Number.isFinite(lineHeight) || lineHeight <= 0) throw new CapabilityError("font-metrics-invalid", "Font line metrics must produce a finite positive value");
883
+ maximum = Math.max(maximum, lineHeight);
884
+ }
885
+ if (maximum === 0) throw new CapabilityError("font-measurement-unavailable", "Content-sized text is missing font to determine line spacing");
886
+ return spacingCentipoints(maximum, "lineHeight") / 75;
887
+ }
888
+ function paragraphBaseline(paragraph) {
889
+ if (paragraph.runs.length !== 1 || paragraph.runs[0].text === "") return;
890
+ const style = paragraph.runs[0].style;
891
+ const face = measureRunFace(style).font;
892
+ const fontSize = fontSizePoints(style.fontSize) * (4 / 3);
893
+ const naturalLineHeight = (face.ascent - face.descent + face.lineGap) / face.unitsPerEm * fontSize;
894
+ const leading = (paragraphLineHeight(paragraph) - naturalLineHeight) / 2;
895
+ return face.ascent / face.unitsPerEm * fontSize + leading;
896
+ }
897
+ function paragraphPieces(paragraph) {
898
+ const sourceRuns = paragraph.runs.length > 0 ? paragraph.runs : [{
899
+ text: "",
900
+ style: paragraph.endStyle
901
+ }];
902
+ const pieces = [];
903
+ let start = 0;
904
+ for (const run of sourceRuns) {
905
+ const face = measureRunFace(run.style);
906
+ const shown = displayedText(run);
907
+ const letterSpacing = run.style.letterSpacing === void 0 ? void 0 : letterSpacingCentipoints(run.style.letterSpacing) / 75;
908
+ const measureStyle = letterSpacing === void 0 ? run.style : {
909
+ ...run.style,
910
+ letterSpacing
911
+ };
912
+ pieces.push({
913
+ text: shown,
914
+ style: measureStyle,
915
+ start,
916
+ end: start + shown.length,
917
+ face
918
+ });
919
+ start += shown.length;
920
+ }
921
+ return {
922
+ text: pieces.map((piece) => piece.text).join(""),
923
+ pieces
924
+ };
925
+ }
926
+ function listIndentMetrics(paragraph) {
927
+ const resolvedList = resolveListModel(paragraph.style.list);
928
+ if (resolvedList === void 0) return {
929
+ levelIndent: 0,
930
+ hangingIndent: 0,
931
+ contentIndent: 0,
932
+ baseFontPx: 0
933
+ };
934
+ const baseFontPx = fontSizePoints((paragraph.runs[0]?.style ?? paragraph.endStyle).fontSize) * 4 / 3;
935
+ const hangingIndent = Math.max(baseFontPx * 1.25, 20);
936
+ const levelIndent = resolvedList.level * (baseFontPx * 1.5);
937
+ return {
938
+ levelIndent,
939
+ hangingIndent,
940
+ contentIndent: levelIndent + hangingIndent,
941
+ baseFontPx
942
+ };
943
+ }
944
+ function paragraphMinContentWidth(paragraph) {
945
+ const { text, pieces } = paragraphPieces(paragraph);
946
+ const { contentIndent } = listIndentMetrics(paragraph);
947
+ if (text === "") return contentIndent;
948
+ if (paragraph.wrap === "nowrap") return wrapParagraph(text, pieces, Number.MAX_VALUE).width + contentIndent;
949
+ const breaker = new LineBreaker(text);
950
+ let start = 0;
951
+ let widest = 0;
952
+ for (let next = breaker.nextBreak(); next !== null; next = breaker.nextBreak()) {
953
+ const contentEnd = trimMandatoryBreakEnd(text, start, next.position);
954
+ widest = Math.max(widest, rangeWidth(pieces, text, start, trimLineEnd(text, start, contentEnd)));
955
+ start = next.position;
956
+ }
957
+ return widest + contentIndent;
958
+ }
959
+ function paragraphMeasurement(paragraph, width) {
960
+ const { text, pieces } = paragraphPieces(paragraph);
961
+ const { contentIndent } = listIndentMetrics(paragraph);
962
+ const wrapped = wrapParagraph(text, pieces, paragraph.wrap === "nowrap" ? Number.MAX_VALUE : Math.max(1, width - contentIndent));
963
+ const spacingAfter = paragraph.style.spacingAfter === void 0 ? 0 : spacingCentipoints(paragraph.style.spacingAfter, "spacingAfter") / 75;
964
+ return {
965
+ lineCount: wrapped.lines.length,
966
+ lines: wrapped.lines,
967
+ text,
968
+ pieces,
969
+ width: wrapped.width + contentIndent,
970
+ lineHeight: paragraphLineHeight(paragraph),
971
+ spacingAfter
972
+ };
973
+ }
974
+ function measureParagraphs(paragraphs, width) {
975
+ const measured = paragraphs.map((paragraph) => paragraphMeasurement(paragraph, width));
976
+ let height = 0;
977
+ measured.forEach((paragraph, index) => {
978
+ height += paragraph.lineCount * paragraph.lineHeight;
979
+ if (index < measured.length - 1) height += paragraph.spacingAfter;
980
+ });
981
+ return {
982
+ width: Math.max(0, ...measured.map((paragraph) => paragraph.width)),
983
+ height,
984
+ paragraphs: measured
985
+ };
986
+ }
987
+ const unsupportedColorFontTables = [
988
+ "COLR",
989
+ "CPAL",
990
+ "sbix",
991
+ "CBDT",
992
+ "CBLC",
993
+ "SVG "
994
+ ];
995
+ function hasUnsupportedColorFontTable(font) {
996
+ const tables = font.directory?.tables;
997
+ return unsupportedColorFontTables.some((table) => table in font || tables !== void 0 && table in tables);
998
+ }
999
+ function roundSvgNumber(value) {
1000
+ const rounded = Math.round(value * 1e6) / 1e6;
1001
+ return Object.is(rounded, -0) ? "0" : String(rounded);
1002
+ }
1003
+ function decorationForSegment(decoration, face, fontPx, startX, endX, color, textShadow) {
1004
+ if (endX <= startX) return void 0;
1005
+ const unitsPerEm = face.unitsPerEm;
1006
+ switch (decoration) {
1007
+ case "none": return;
1008
+ case "underline": {
1009
+ const thickness = Math.max(1, face.underlineThickness ? face.underlineThickness / unitsPerEm * fontPx : fontPx * .07);
1010
+ return {
1011
+ x: startX,
1012
+ y: (face.underlinePosition ? -face.underlinePosition / unitsPerEm * fontPx : fontPx * .12) - thickness / 2,
1013
+ width: endX - startX,
1014
+ height: thickness,
1015
+ color,
1016
+ ...textShadow === void 0 ? {} : { textShadow }
1017
+ };
1018
+ }
1019
+ case "line-through": {
1020
+ const os2 = face["OS/2"];
1021
+ const thickness = Math.max(1, os2?.yStrikeoutSize ? os2.yStrikeoutSize / unitsPerEm * fontPx : fontPx * .07);
1022
+ return {
1023
+ x: startX,
1024
+ y: -(os2?.yStrikeoutPosition ? os2.yStrikeoutPosition / unitsPerEm * fontPx : fontPx * .3) - thickness / 2,
1025
+ width: endX - startX,
1026
+ height: thickness,
1027
+ color,
1028
+ ...textShadow === void 0 ? {} : { textShadow }
1029
+ };
1030
+ }
1031
+ default: return decoration;
1032
+ }
1033
+ }
1034
+ function bidiCharType(ch) {
1035
+ if (ch === "‏") return "R";
1036
+ if (ch === "‎") return "L";
1037
+ if (/^\p{Mark}$/u.test(ch)) return "NSM";
1038
+ if (/^[\u0660-\u0669\u06F0-\u06F9]$/u.test(ch)) return "AN";
1039
+ if (/^\p{Nd}$/u.test(ch)) return "EN";
1040
+ if (/^[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Nko}\uFB50-\uFDFF\uFE70-\uFEFF]$/u.test(ch) && /^\p{Letter}$/u.test(ch)) return "AL";
1041
+ if (/^[\p{Script=Hebrew}\uFB1D-\uFB4F]$/u.test(ch) && /^\p{Letter}$/u.test(ch)) return "R";
1042
+ if (/^\p{Letter}$/u.test(ch)) return "L";
1043
+ if (ch === "+" || ch === "-" || ch === "−") return "ES";
1044
+ if (ch === "," || ch === "." || ch === ":" || ch === "/") return "CS";
1045
+ if (ch === "%" || /^\p{Sc}$/u.test(ch)) return "ET";
1046
+ return "ON";
1047
+ }
1048
+ function paragraphBaseDirection(text) {
1049
+ for (const ch of text) {
1050
+ const type = bidiCharType(ch);
1051
+ if (type === "R" || type === "AL") return "rtl";
1052
+ if (type === "L") return "ltr";
1053
+ }
1054
+ return "ltr";
1055
+ }
1056
+ function computeLineBidiLevels(lineText, baseOffset, baseDir) {
1057
+ const cps = [];
1058
+ let offset = baseOffset;
1059
+ for (const ch of lineText) {
1060
+ cps.push({
1061
+ start: offset,
1062
+ end: offset + ch.length,
1063
+ ch
1064
+ });
1065
+ offset += ch.length;
1066
+ }
1067
+ const n = cps.length;
1068
+ if (n === 0) return [];
1069
+ const embeddingLevel = baseDir === "rtl" ? 1 : 0;
1070
+ const dirStrong = embeddingLevel === 0 ? "L" : "R";
1071
+ const types = cps.map((cp) => bidiCharType(cp.ch));
1072
+ let prevW1 = dirStrong;
1073
+ for (let i = 0; i < n; i += 1) if (types[i] === "NSM") types[i] = prevW1;
1074
+ else prevW1 = types[i];
1075
+ let lastStrongW2 = dirStrong;
1076
+ for (let i = 0; i < n; i += 1) {
1077
+ const t = types[i];
1078
+ if (t === "L" || t === "R" || t === "AL") lastStrongW2 = t;
1079
+ else if (t === "EN" && lastStrongW2 === "AL") types[i] = "AN";
1080
+ }
1081
+ for (let i = 0; i < n; i += 1) if (types[i] === "AL") types[i] = "R";
1082
+ for (let i = 1; i < n - 1; i += 1) {
1083
+ const t = types[i];
1084
+ const prev = types[i - 1];
1085
+ const next = types[i + 1];
1086
+ if (t === "ES" && prev === "EN" && next === "EN") types[i] = "EN";
1087
+ else if (t === "CS" && (prev === "EN" && next === "EN" || prev === "AN" && next === "AN")) types[i] = prev;
1088
+ }
1089
+ for (let i = 0; i < n; i += 1) {
1090
+ if (types[i] !== "ET") continue;
1091
+ let end = i;
1092
+ while (end < n && types[end] === "ET") end += 1;
1093
+ const prevEn = i > 0 && types[i - 1] === "EN";
1094
+ const nextEn = end < n && types[end] === "EN";
1095
+ if (prevEn || nextEn) for (let k = i; k < end; k += 1) types[k] = "EN";
1096
+ i = end - 1;
1097
+ }
1098
+ for (let i = 0; i < n; i += 1) {
1099
+ const t = types[i];
1100
+ if (t === "ES" || t === "ET" || t === "CS") types[i] = "ON";
1101
+ }
1102
+ let lastStrongW7 = dirStrong;
1103
+ for (let i = 0; i < n; i += 1) {
1104
+ const t = types[i];
1105
+ if (t === "L" || t === "R") lastStrongW7 = t;
1106
+ else if (t === "EN" && lastStrongW7 === "L") types[i] = "L";
1107
+ }
1108
+ const neutralEffective = (t) => {
1109
+ if (t === "L") return "L";
1110
+ if (t === "R" || t === "EN" || t === "AN") return "R";
1111
+ };
1112
+ for (let i = 0; i < n; i += 1) {
1113
+ if (types[i] !== "ON") continue;
1114
+ let end = i;
1115
+ while (end < n && types[end] === "ON") end += 1;
1116
+ const leftSide = i === 0 ? dirStrong : neutralEffective(types[i - 1]) ?? dirStrong;
1117
+ const resolved = leftSide === (end === n ? dirStrong : neutralEffective(types[end]) ?? dirStrong) ? leftSide : dirStrong;
1118
+ for (let k = i; k < end; k += 1) types[k] = resolved;
1119
+ i = end - 1;
1120
+ }
1121
+ return cps.map((cp, index) => {
1122
+ const t = types[index];
1123
+ let level;
1124
+ if (embeddingLevel === 0) level = t === "L" ? 0 : t === "R" ? 1 : 2;
1125
+ else level = t === "R" ? 1 : 2;
1126
+ return {
1127
+ start: cp.start,
1128
+ end: cp.end,
1129
+ level
1130
+ };
1131
+ });
1132
+ }
1133
+ function buildVisualLineSegments(text, lineStart, trimmedEnd, pieces, baseDir) {
1134
+ if (lineStart >= trimmedEnd) return [];
1135
+ const spans = computeLineBidiLevels(text.slice(lineStart, trimmedEnd), lineStart, baseDir);
1136
+ const segments = [];
1137
+ let spanIdx = 0;
1138
+ for (const piece of pieces) {
1139
+ const pStart = Math.max(lineStart, piece.start);
1140
+ const pEnd = Math.min(trimmedEnd, piece.end);
1141
+ if (pStart >= pEnd) continue;
1142
+ while (spanIdx < spans.length && spans[spanIdx].end <= pStart) spanIdx += 1;
1143
+ let segStart = pStart;
1144
+ let currentLevel;
1145
+ while (spanIdx < spans.length && spans[spanIdx].start < pEnd) {
1146
+ const sp = spans[spanIdx];
1147
+ if (currentLevel === void 0) {
1148
+ currentLevel = sp.level;
1149
+ segStart = Math.max(pStart, sp.start);
1150
+ } else if (sp.level !== currentLevel) {
1151
+ const segEnd = Math.min(pEnd, sp.start);
1152
+ if (segEnd > segStart) segments.push({
1153
+ text: text.slice(segStart, segEnd),
1154
+ piece,
1155
+ level: currentLevel,
1156
+ isRtl: currentLevel % 2 === 1
1157
+ });
1158
+ currentLevel = sp.level;
1159
+ segStart = segEnd;
1160
+ }
1161
+ if (sp.end <= pEnd) spanIdx += 1;
1162
+ else break;
1163
+ }
1164
+ if (currentLevel !== void 0 && pEnd > segStart) segments.push({
1165
+ text: text.slice(segStart, pEnd),
1166
+ piece,
1167
+ level: currentLevel,
1168
+ isRtl: currentLevel % 2 === 1
1169
+ });
1170
+ }
1171
+ const maxLevel = Math.max(0, ...segments.map((seg) => seg.level));
1172
+ for (let lvl = maxLevel; lvl >= 1; lvl -= 1) {
1173
+ let i = 0;
1174
+ while (i < segments.length) {
1175
+ if (segments[i].level < lvl) {
1176
+ i += 1;
1177
+ continue;
1178
+ }
1179
+ let j = i;
1180
+ while (j < segments.length && segments[j].level >= lvl) j += 1;
1181
+ let left = i;
1182
+ let right = j - 1;
1183
+ while (left < right) {
1184
+ const tmp = segments[left];
1185
+ segments[left] = segments[right];
1186
+ segments[right] = tmp;
1187
+ left += 1;
1188
+ right -= 1;
1189
+ }
1190
+ i = j;
1191
+ }
1192
+ }
1193
+ return segments;
1194
+ }
1195
+ function shapeSegmentOutlines(face, text, isRtl, lang) {
1196
+ const visible = Array.from(text).filter(requiresFontGlyph).join("");
1197
+ if (visible === "") return [];
1198
+ const hbFont = hbFaces.get(face.identity)?.font;
1199
+ if (hbFont !== void 0) return withHbBuffer((buffer) => {
1200
+ buffer.addText(visible);
1201
+ buffer.guessSegmentProperties();
1202
+ buffer.setDirection(isRtl ? hb.Direction.RTL : hb.Direction.LTR);
1203
+ if (lang !== void 0) buffer.setLanguage(lang);
1204
+ hb.shape(hbFont, buffer);
1205
+ return buffer.getGlyphInfosAndPositions().map((item) => ({
1206
+ path: hbFont.glyphToPath(item.codepoint),
1207
+ xAdvance: item.xAdvance ?? 0,
1208
+ xOffset: item.xOffset ?? 0,
1209
+ yOffset: item.yOffset ?? 0,
1210
+ cluster: item.cluster,
1211
+ isSpace: /\p{White_Space}/u.test(visible[item.cluster] ?? "")
1212
+ }));
1213
+ });
1214
+ const fkRun = face.font.layout(visible, void 0, void 0, void 0, isRtl ? "rtl" : "ltr");
1215
+ return fkRun.glyphs.map((glyph, index) => {
1216
+ const pos = fkRun.positions[index];
1217
+ const isSpace = glyph.codePoints.some((cp) => /\p{White_Space}/u.test(String.fromCodePoint(cp)));
1218
+ return {
1219
+ path: glyph.path.toSVG(),
1220
+ xAdvance: pos.xAdvance,
1221
+ xOffset: pos.xOffset,
1222
+ yOffset: pos.yOffset,
1223
+ cluster: index,
1224
+ isSpace
1225
+ };
1226
+ });
1227
+ }
1228
+ /**
1229
+ * Converts font-measurement/outline unavailability errors encountered during paint()
1230
+ * into `preview-unsupported-font` while preserving `resolve()` error semantics.
1231
+ */
1232
+ function withPreviewFontBoundary(fn) {
1233
+ try {
1234
+ return fn();
1235
+ } catch (error) {
1236
+ if (error instanceof CapabilityError) {
1237
+ if (error.code === "preview-unsupported-font" || error.code === "preview-missing-glyph") throw error;
1238
+ if (error.code === "font-measurement-unavailable") throw new CapabilityError("preview-unsupported-font", "Preview requires an explicit monochrome outline font file for each used font weight and style");
1239
+ if (error.code === "font-format-unsupported" || error.code === "font-substitution-required" || error.code === "font-face-mismatch" || error.code === "font-metrics-invalid" || error.code === "conflicting-resource") throw new CapabilityError("preview-unsupported-font", error.message);
1240
+ }
1241
+ throw error;
1242
+ }
1243
+ }
1244
+ /**
1245
+ * Extracts vector glyph outlines for one paragraph using its formal measurement / line-break ranges.
1246
+ * Coordinates are relative to each line's baseline, in pixels.
1247
+ */
1248
+ function previewParagraphOutlines(paragraph, widthOrMeasured) {
1249
+ const { measured, text, pieces, baseDir } = withPreviewFontBoundary(() => {
1250
+ const resolvedMeasured = typeof widthOrMeasured === "number" ? paragraphMeasurement(paragraph, widthOrMeasured) : widthOrMeasured;
1251
+ for (const piece of resolvedMeasured.pieces) if (hasUnsupportedColorFontTable(piece.face.font)) throw new CapabilityError("preview-unsupported-font", "Preview requires monochrome outline fonts");
1252
+ return {
1253
+ measured: resolvedMeasured,
1254
+ text: resolvedMeasured.text,
1255
+ pieces: resolvedMeasured.pieces,
1256
+ baseDir: paragraphBaseDirection(resolvedMeasured.text)
1257
+ };
1258
+ });
1259
+ return {
1260
+ lines: measured.lines.map((line, lineIndex) => {
1261
+ let cursor = 0;
1262
+ let pendingTracking = 0;
1263
+ const glyphs = [];
1264
+ const decorations = [];
1265
+ let ascent = 0;
1266
+ let descent = 0;
1267
+ const trimmedEnd = trimLineEnd(text, line.start, line.end);
1268
+ buildVisualLineSegments(text, line.start, trimmedEnd, pieces, baseDir).forEach((seg, segIndex) => {
1269
+ const { piece } = seg;
1270
+ if (missingCharacters(piece.face, seg.text).length > 0) throw new CapabilityError("preview-missing-glyph", "Preview requires every visible glyph in the supplied font");
1271
+ const shaped = shapeSegmentOutlines(piece.face, seg.text, seg.isRtl, piece.style.lang);
1272
+ if (shaped.length === 0) return;
1273
+ const face = piece.face.font;
1274
+ const fontPx = fontSizePoints(piece.style.fontSize) * 4 / 3;
1275
+ const scale = fontPx / face.unitsPerEm;
1276
+ const trackingPx = piece.style.letterSpacing ?? 0;
1277
+ ascent = Math.max(ascent, face.ascent * scale);
1278
+ descent = Math.max(descent, -face.descent * scale);
1279
+ let segStartX;
1280
+ let segEndX = cursor;
1281
+ const glyphStart = glyphs.length;
1282
+ let lastCluster;
1283
+ let clusterHadAdvance = false;
1284
+ for (const item of shaped) {
1285
+ if (lastCluster !== void 0 && item.cluster !== lastCluster) {
1286
+ if (clusterHadAdvance && pendingTracking !== 0) {
1287
+ cursor += pendingTracking;
1288
+ pendingTracking = 0;
1289
+ }
1290
+ clusterHadAdvance = false;
1291
+ } else if (lastCluster === void 0 && pendingTracking !== 0) {
1292
+ cursor += pendingTracking;
1293
+ pendingTracking = 0;
1294
+ }
1295
+ lastCluster = item.cluster;
1296
+ if (segStartX === void 0) segStartX = cursor;
1297
+ glyphs.push({
1298
+ path: item.path,
1299
+ x: cursor + item.xOffset * scale,
1300
+ y: -item.yOffset * scale,
1301
+ scale,
1302
+ color: piece.style.color,
1303
+ ...piece.style.textShadow === void 0 ? {} : { textShadow: piece.style.textShadow },
1304
+ isSpace: item.isSpace && item.xAdvance > 0,
1305
+ clusterKey: `${segIndex}:${item.cluster}`
1306
+ });
1307
+ cursor += item.xAdvance * scale;
1308
+ segEndX = cursor;
1309
+ if (item.xAdvance > 0) {
1310
+ clusterHadAdvance = true;
1311
+ pendingTracking = trackingPx;
1312
+ }
1313
+ }
1314
+ const glyphEnd = glyphs.length;
1315
+ if (segStartX !== void 0 && glyphEnd > glyphStart) {
1316
+ const decoration = decorationForSegment(resolveDecoration(piece.style.textDecoration), face, fontPx, segStartX, segEndX, piece.style.color, piece.style.textShadow);
1317
+ if (decoration !== void 0) decorations.push({
1318
+ ...decoration,
1319
+ glyphStart,
1320
+ glyphEnd
1321
+ });
1322
+ }
1323
+ });
1324
+ if (glyphs.length === 0 && pieces.length > 0) {
1325
+ const fallbackPiece = pieces[0];
1326
+ const fallbackScale = fontSizePoints(fallbackPiece.style.fontSize) * 4 / (3 * fallbackPiece.face.font.unitsPerEm);
1327
+ ascent = fallbackPiece.face.font.ascent * fallbackScale;
1328
+ descent = -fallbackPiece.face.font.descent * fallbackScale;
1329
+ }
1330
+ const endsWithMandatoryBreak = trimMandatoryBreakEnd(text, line.start, line.end) < line.end || line.end < text.length && /[\n\r\v\f\u0085\u2028\u2029]/u.test(text[line.end] ?? "");
1331
+ const canJustify = lineIndex < measured.lines.length - 1 && !endsWithMandatoryBreak;
1332
+ return {
1333
+ ...line,
1334
+ glyphs,
1335
+ ...decorations.length === 0 ? {} : { decorations },
1336
+ ascent,
1337
+ descent,
1338
+ advance: cursor,
1339
+ canJustify
1340
+ };
1341
+ }),
1342
+ lineHeight: measured.lineHeight,
1343
+ spacingAfter: measured.spacingAfter,
1344
+ baseDir
1345
+ };
1346
+ }
1347
+ function applyJustifyLine(line, availableWidth) {
1348
+ const slack = availableWidth - line.advance;
1349
+ if (!line.canJustify || slack <= .01 || line.glyphs.length <= 1) return {
1350
+ glyphs: line.glyphs,
1351
+ decorations: line.decorations,
1352
+ advance: line.advance
1353
+ };
1354
+ const count = line.glyphs.length;
1355
+ const deltaBefore = Array.from({ length: count }).fill(0);
1356
+ const spaceCount = line.glyphs.filter((g) => g.isSpace === true).length;
1357
+ if (spaceCount > 0) {
1358
+ const extraPerSpace = slack / spaceCount;
1359
+ let cumulative = 0;
1360
+ for (let i = 0; i < count; i += 1) {
1361
+ deltaBefore[i] = cumulative;
1362
+ if (line.glyphs[i].isSpace === true) cumulative += extraPerSpace;
1363
+ }
1364
+ } else {
1365
+ let clusterTransitions = 0;
1366
+ for (let i = 1; i < count; i += 1) if (line.glyphs[i].clusterKey !== line.glyphs[i - 1].clusterKey) clusterTransitions += 1;
1367
+ if (clusterTransitions <= 0) return {
1368
+ glyphs: line.glyphs,
1369
+ decorations: line.decorations,
1370
+ advance: line.advance
1371
+ };
1372
+ const extraPerCluster = slack / clusterTransitions;
1373
+ let cumulative = 0;
1374
+ for (let i = 1; i < count; i += 1) {
1375
+ if (line.glyphs[i].clusterKey !== line.glyphs[i - 1].clusterKey) cumulative += extraPerCluster;
1376
+ deltaBefore[i] = cumulative;
1377
+ }
1378
+ }
1379
+ return {
1380
+ glyphs: line.glyphs.map((glyph, index) => ({
1381
+ ...glyph,
1382
+ x: glyph.x + deltaBefore[index]
1383
+ })),
1384
+ decorations: line.decorations?.map((deco) => {
1385
+ const gStart = deco.glyphStart ?? 0;
1386
+ const gEnd = deco.glyphEnd ?? count;
1387
+ const startDelta = deltaBefore[gStart] ?? 0;
1388
+ const endDelta = gEnd < count ? deltaBefore[gEnd] ?? 0 : deltaBefore[Math.max(gStart, gEnd - 1)] ?? 0;
1389
+ return {
1390
+ ...deco,
1391
+ x: deco.x + startDelta,
1392
+ width: deco.width + (endDelta - startDelta)
1393
+ };
1394
+ }),
1395
+ advance: availableWidth
1396
+ };
1397
+ }
1398
+ function shapeListPrefix(paragraph, prefixText) {
1399
+ const prefixStyle = paragraph.runs[0]?.style ?? paragraph.endStyle;
1400
+ const prefixFace = withPreviewFontBoundary(() => {
1401
+ const face = measureRunFace(prefixStyle);
1402
+ if (hasUnsupportedColorFontTable(face.font)) throw new CapabilityError("preview-unsupported-font", "Preview requires monochrome outline fonts");
1403
+ return face;
1404
+ });
1405
+ if (missingCharacters(prefixFace, prefixText).length > 0) throw new CapabilityError("preview-missing-glyph", "Preview requires every visible glyph in the supplied font");
1406
+ const shaped = shapeSegmentOutlines(prefixFace, prefixText, false, prefixStyle.lang);
1407
+ const scale = fontSizePoints(prefixStyle.fontSize) * 4 / (3 * prefixFace.font.unitsPerEm);
1408
+ let cursor = 0;
1409
+ return {
1410
+ glyphs: shaped.map((item) => {
1411
+ const glyph = {
1412
+ path: item.path,
1413
+ x: cursor + item.xOffset * scale,
1414
+ y: -item.yOffset * scale,
1415
+ scale,
1416
+ color: prefixStyle.color,
1417
+ ...prefixStyle.textShadow === void 0 ? {} : { textShadow: prefixStyle.textShadow }
1418
+ };
1419
+ cursor += item.xAdvance * scale;
1420
+ return glyph;
1421
+ }),
1422
+ advance: cursor
1423
+ };
1424
+ }
1425
+ /**
1426
+ * Positions paragraph glyph outlines inside a compiled box with insets, horizontal alignment,
1427
+ * and vertical alignment. Reuses pre-computed formal build line measurements when provided.
1428
+ */
1429
+ function previewTextBoxOutlines(options) {
1430
+ const { paragraphs, box, insets = {
1431
+ top: 0,
1432
+ right: 0,
1433
+ bottom: 0,
1434
+ left: 0
1435
+ }, verticalAlign: rawVerticalAlign, measuredLayout } = options;
1436
+ const verticalAlign = resolveVerticalAlign(rawVerticalAlign);
1437
+ const innerWidth = Math.max(0, box.width - insets.left - insets.right);
1438
+ const useBoundMeasurement = measuredLayout !== void 0 && measuredLayout.paragraphs.length === paragraphs.length;
1439
+ const outlinedParagraphs = paragraphs.map((paragraph, index) => ({
1440
+ paragraph,
1441
+ layout: previewParagraphOutlines(paragraph, useBoundMeasurement ? measuredLayout.paragraphs[index] : innerWidth)
1442
+ }));
1443
+ const totalHeight = outlinedParagraphs.reduce((total, { layout }, index) => total + layout.lines.length * layout.lineHeight + (index < outlinedParagraphs.length - 1 ? layout.spacingAfter : 0), 0);
1444
+ const freeHeight = box.height - insets.top - insets.bottom - totalHeight;
1445
+ let top = box.y + insets.top + (verticalAlign === "middle" ? freeHeight / 2 : verticalAlign === "bottom" ? freeHeight : 0);
1446
+ const activeNumberSeq = /* @__PURE__ */ new Map();
1447
+ return outlinedParagraphs.flatMap(({ paragraph, layout }) => {
1448
+ const resolvedList = resolveListModel(paragraph.style.list);
1449
+ let prefixText;
1450
+ if (resolvedList === void 0) activeNumberSeq.clear();
1451
+ else switch (resolvedList.type) {
1452
+ case "bullet":
1453
+ for (const key of activeNumberSeq.keys()) if (key >= resolvedList.level) activeNumberSeq.delete(key);
1454
+ prefixText = resolvedList.character;
1455
+ break;
1456
+ case "number": {
1457
+ for (const key of activeNumberSeq.keys()) if (key > resolvedList.level) activeNumberSeq.delete(key);
1458
+ const existing = activeNumberSeq.get(resolvedList.level);
1459
+ if (existing !== void 0 && existing.startAt === resolvedList.startAt) existing.current += 1;
1460
+ else activeNumberSeq.set(resolvedList.level, {
1461
+ startAt: resolvedList.startAt,
1462
+ current: resolvedList.startAt
1463
+ });
1464
+ prefixText = `${activeNumberSeq.get(resolvedList.level).current}.`;
1465
+ break;
1466
+ }
1467
+ default: return resolvedList;
1468
+ }
1469
+ const listPrefix = prefixText === void 0 ? void 0 : shapeListPrefix(paragraph, prefixText);
1470
+ const listIndent = listIndentMetrics(paragraph);
1471
+ const availableLineWidth = Math.max(1, innerWidth - listIndent.contentIndent);
1472
+ const align = resolveAlign(paragraph.style.align, layout.baseDir === "rtl" ? "right" : "left");
1473
+ const lines = layout.lines.map((line, lineIndex) => {
1474
+ const justified = align === "justify" ? applyJustifyLine(line, availableLineWidth) : {
1475
+ glyphs: line.glyphs,
1476
+ decorations: line.decorations,
1477
+ advance: line.advance
1478
+ };
1479
+ let horizontalOffset;
1480
+ let prefixOffset = 0;
1481
+ if (layout.baseDir === "rtl" && resolvedList !== void 0) switch (align) {
1482
+ case "center":
1483
+ horizontalOffset = (availableLineWidth - justified.advance) / 2;
1484
+ prefixOffset = horizontalOffset + justified.advance + .4 * listIndent.baseFontPx;
1485
+ break;
1486
+ case "left":
1487
+ case "justify":
1488
+ horizontalOffset = 0;
1489
+ prefixOffset = innerWidth - listIndent.levelIndent - (listPrefix?.advance ?? 0);
1490
+ break;
1491
+ case "right":
1492
+ horizontalOffset = availableLineWidth - justified.advance;
1493
+ prefixOffset = innerWidth - listIndent.levelIndent - (listPrefix?.advance ?? 0);
1494
+ break;
1495
+ default: return align;
1496
+ }
1497
+ else switch (align) {
1498
+ case "center":
1499
+ horizontalOffset = listIndent.contentIndent + (availableLineWidth - justified.advance) / 2;
1500
+ prefixOffset = horizontalOffset - (listPrefix?.advance ?? 0) - .4 * listIndent.baseFontPx;
1501
+ break;
1502
+ case "right":
1503
+ horizontalOffset = listIndent.contentIndent + (availableLineWidth - justified.advance);
1504
+ prefixOffset = horizontalOffset - (listPrefix?.advance ?? 0) - .4 * listIndent.baseFontPx;
1505
+ break;
1506
+ case "left":
1507
+ case "justify":
1508
+ horizontalOffset = listIndent.contentIndent;
1509
+ prefixOffset = listIndent.levelIndent;
1510
+ break;
1511
+ default: return align;
1512
+ }
1513
+ const left = box.x + insets.left + horizontalOffset;
1514
+ const baseline = top + line.ascent + (layout.lineHeight - line.ascent - line.descent) / 2;
1515
+ top += layout.lineHeight;
1516
+ const prefixGlyphs = lineIndex === 0 && listPrefix !== void 0 ? listPrefix.glyphs.map((glyph) => ({
1517
+ ...glyph,
1518
+ x: box.x + insets.left + prefixOffset + glyph.x,
1519
+ y: baseline + glyph.y
1520
+ })) : [];
1521
+ return {
1522
+ start: line.start,
1523
+ end: line.end,
1524
+ baseline,
1525
+ glyphs: [...prefixGlyphs, ...justified.glyphs.map((glyph) => ({
1526
+ ...glyph,
1527
+ x: left + glyph.x,
1528
+ y: baseline + glyph.y
1529
+ }))],
1530
+ ...justified.decorations === void 0 ? {} : { decorations: justified.decorations.map((deco) => ({
1531
+ ...deco,
1532
+ x: left + deco.x,
1533
+ y: baseline + deco.y
1534
+ })) }
1535
+ };
1536
+ });
1537
+ top += layout.spacingAfter;
1538
+ return lines;
1539
+ });
1540
+ }
1541
+ /** Serializes a single positioned glyph outline to an SVG path element. */
1542
+ function renderGlyphPathSvg(glyph, theme) {
1543
+ if (glyph.path === "") return "";
1544
+ const color = isResolvedColor(glyph.color) ? glyph.color : theme.resolveColor(glyph.color ?? "tx1");
1545
+ return `<path d="${xmlEscape(glyph.path)}" fill="#${color.hex}" fill-opacity="${color.alpha ?? 1}" transform="translate(${glyph.x} ${glyph.y}) scale(${glyph.scale} ${-glyph.scale})"/>`;
1546
+ }
1547
+ function renderDecorationRectSvg(deco, theme) {
1548
+ const color = isResolvedColor(deco.color) ? deco.color : theme.resolveColor(deco.color ?? "tx1");
1549
+ return `<rect x="${roundSvgNumber(deco.x)}" y="${roundSvgNumber(deco.y)}" width="${roundSvgNumber(deco.width)}" height="${roundSvgNumber(deco.height)}" fill="#${color.hex}" fill-opacity="${color.alpha ?? 1}"/>`;
1550
+ }
1551
+ /** Renders box-level positioned glyph outlines into SVG path fragments without importing textCapability. */
1552
+ function renderTextOutlinesSvg(options) {
1553
+ const { theme, idPrefix = "txt", rotate = 0, ...layoutOptions } = options;
1554
+ const lines = previewTextBoxOutlines(layoutOptions);
1555
+ const defs = [];
1556
+ const shadowFilterIds = /* @__PURE__ */ new Map();
1557
+ let shadowIndex = 0;
1558
+ const filterIdForShadow = (rawShadow) => {
1559
+ const resolved = resolveTextShadowModel(theme, rawShadow);
1560
+ switch (resolved.kind) {
1561
+ case "none": return;
1562
+ case "shadow": {
1563
+ const { shadow } = resolved;
1564
+ const rad = shadow.angle * Math.PI / 180;
1565
+ const worldDx = shadow.distance * Math.cos(rad);
1566
+ const worldDy = shadow.distance * Math.sin(rad);
1567
+ const rotRad = -rotate * Math.PI / 180;
1568
+ const localDx = worldDx * Math.cos(rotRad) - worldDy * Math.sin(rotRad);
1569
+ const localDy = worldDx * Math.sin(rotRad) + worldDy * Math.cos(rotRad);
1570
+ const sigma = shadow.blur / 2;
1571
+ const alpha = shadow.color.alpha ?? 1;
1572
+ const key = `${shadow.color.hex}:${roundSvgNumber(alpha)}:${roundSvgNumber(sigma)}:${roundSvgNumber(localDx)}:${roundSvgNumber(localDy)}`;
1573
+ const existing = shadowFilterIds.get(key);
1574
+ if (existing !== void 0) return existing;
1575
+ const id = `${idPrefix}-tshdw-${shadowIndex++}`;
1576
+ shadowFilterIds.set(key, id);
1577
+ const pad = shadow.blur * 3 + Math.abs(localDx) + Math.abs(localDy) + 64;
1578
+ const fx = roundSvgNumber(options.box.x - pad);
1579
+ const fy = roundSvgNumber(options.box.y - pad);
1580
+ const fw = roundSvgNumber(options.box.width + pad * 2);
1581
+ const fh = roundSvgNumber(options.box.height + pad * 2);
1582
+ defs.push(`<filter id="${id}" filterUnits="userSpaceOnUse" x="${fx}" y="${fy}" width="${fw}" height="${fh}"><feDropShadow dx="${roundSvgNumber(localDx)}" dy="${roundSvgNumber(localDy)}" stdDeviation="${roundSvgNumber(sigma)}" flood-color="#${shadow.color.hex}" flood-opacity="${roundSvgNumber(alpha)}"/></filter>`);
1583
+ return id;
1584
+ }
1585
+ default: return resolved;
1586
+ }
1587
+ };
1588
+ const parts = [];
1589
+ let activeFilter;
1590
+ let activeGroup = [];
1591
+ const flushGroup = () => {
1592
+ if (activeGroup.length === 0) return;
1593
+ const joined = activeGroup.join("");
1594
+ parts.push(activeFilter === void 0 ? joined : `<g filter="url(#${activeFilter})">${joined}</g>`);
1595
+ activeGroup = [];
1596
+ };
1597
+ const pushElement = (elementSvg, rawShadow) => {
1598
+ if (elementSvg === "") return;
1599
+ const filterId = filterIdForShadow(rawShadow);
1600
+ if (filterId !== activeFilter) {
1601
+ flushGroup();
1602
+ activeFilter = filterId;
1603
+ }
1604
+ activeGroup.push(elementSvg);
1605
+ };
1606
+ for (const line of lines) {
1607
+ for (const glyph of line.glyphs) pushElement(renderGlyphPathSvg(glyph, theme), glyph.textShadow);
1608
+ for (const deco of line.decorations ?? []) pushElement(renderDecorationRectSvg(deco, theme), deco.textShadow);
1609
+ }
1610
+ flushGroup();
1611
+ return `${defs.length > 0 ? `<defs>${defs.join("")}</defs>` : ""}${parts.join("")}`;
1612
+ }
1613
+ /** Returns layout dimensions based on actual fonts and line breaking rules from normalized paragraphs. */
1614
+ function measureTextLayoutFromParagraphs(paragraphs, style, availableWidth) {
1615
+ const measured = measureParagraphs(paragraphs, availableWidth ?? Number.POSITIVE_INFINITY);
1616
+ const minContentWidth = Math.max(0, ...paragraphs.map(paragraphMinContentWidth));
1617
+ let baseline;
1618
+ if (style.verticalAlign === void 0 || style.verticalAlign === "top") {
1619
+ if (paragraphs[0] === void 0) baseline = void 0;
1620
+ else try {
1621
+ baseline = paragraphBaseline(paragraphs[0]) ?? "unavailable";
1622
+ } catch {
1623
+ baseline = "unavailable";
1624
+ }
1625
+ }
1626
+ return {
1627
+ width: measured.width,
1628
+ height: measured.height,
1629
+ minContentWidth,
1630
+ minContentHeight: measured.height,
1631
+ ...baseline === void 0 ? {} : { baseline }
1632
+ };
1633
+ }
1634
+ function bodyAnchor(verticalAlign) {
1635
+ return {
1636
+ top: "t",
1637
+ middle: "ctr",
1638
+ bottom: "b"
1639
+ }[verticalAlign ?? "top"];
1640
+ }
1641
+ function textInsets(value, placeholder) {
1642
+ if (placeholder === void 0) return parseTextInsets(value);
1643
+ const effective = {};
1644
+ const layers = [
1645
+ placeholder.masterPlaceholder?.style,
1646
+ placeholder.layoutPlaceholder?.style,
1647
+ record(value) ? value : void 0
1648
+ ];
1649
+ for (const layer of layers) {
1650
+ if (layer === void 0) continue;
1651
+ for (const key of paddingStyleKeys) if (hasLocalDeclaration(layer, key)) {
1652
+ if (key === "padding") {
1653
+ delete effective["paddingTop"];
1654
+ delete effective["paddingRight"];
1655
+ delete effective["paddingBottom"];
1656
+ delete effective["paddingLeft"];
1657
+ }
1658
+ effective[key] = layer[key];
1659
+ }
1660
+ }
1661
+ return parseTextInsets(effective);
1662
+ }
1663
+ /** Parses text children, validates element structure, and resolves paragraphs and text styles once. */
1664
+ function parseTextContent(children, styleValue, theme, fields = { slideNumber: 1 }, label = "Text.style", placeholder, fullSlideStyle) {
1665
+ if (placeholder === void 0) {
1666
+ const style = readTextStyle(styleValue, label, theme);
1667
+ return {
1668
+ paragraphs: normalizeParagraphs(children, style, theme, fields),
1669
+ style
1670
+ };
1671
+ }
1672
+ const { style, localDeclaredStyle } = readPlaceholderTextStyle(styleValue, label, placeholder);
1673
+ const fullRecord = record(fullSlideStyle) ? fullSlideStyle : void 0;
1674
+ const localBodyDeclared = localDeclaredKeySet(fullRecord, [
1675
+ "textWrap",
1676
+ "verticalAlign",
1677
+ ...paddingStyleKeys
1678
+ ]);
1679
+ return {
1680
+ paragraphs: normalizeParagraphs(children, style, placeholder.masterTheme, fields, placeholder, localDeclaredStyle),
1681
+ style,
1682
+ localBodyDeclared
1683
+ };
1684
+ }
1685
+ const parseTextParagraphs = parseTextContent;
1686
+ function validateEmittableParagraphs(paragraphs, theme) {
1687
+ for (const paragraph of paragraphs) {
1688
+ if (paragraph.style.list?.type === "bullet") escapedXml(paragraph.style.list.character ?? "•");
1689
+ if (paragraph.runs.length === 0) {
1690
+ if (paragraph.endStyle.lang !== void 0) escapedXml(paragraph.endStyle.lang);
1691
+ centipoints(fontSizePoints(paragraph.endStyle.fontSize));
1692
+ continue;
1693
+ }
1694
+ for (const run of paragraph.runs) {
1695
+ escapedXml(run.text);
1696
+ for (const font of normalizedFonts(run.style)) escapedXml(font.family);
1697
+ if (run.style.lang !== void 0) escapedXml(run.style.lang);
1698
+ if (run.style.textShadow !== void 0 && run.style.textShadow !== "none") textShadowXml(theme, run.style.textShadow);
1699
+ }
1700
+ }
1701
+ }
1702
+ /**
1703
+ * Resolves text layout, wrapping metrics, overset diagnostics, plain-text observations,
1704
+ * and font resource claims from pre-parsed paragraphs without assigning emit-only field IDs.
1705
+ */
1706
+ function resolveTextBody(paragraphs, style, theme, verticalAlign = "top", layout, destination = "text-box", placeholderOptions) {
1707
+ const runs = paragraphs.flatMap((paragraph) => paragraph.runs.length > 0 ? paragraph.runs : [{
1708
+ text: "",
1709
+ style: paragraph.endStyle
1710
+ }]);
1711
+ const listRuns = paragraphs.flatMap((paragraph) => {
1712
+ const list = paragraph.style.list;
1713
+ if (list === void 0) return [];
1714
+ return [{
1715
+ text: list.type === "bullet" ? list.character ?? "•" : "0123456789.",
1716
+ style: paragraph.runs[0]?.style ?? paragraph.endStyle
1717
+ }];
1718
+ });
1719
+ const { resourceClaims, fontUses, warnings, missingGlyphErrors } = textResourceClaims([...runs, ...listRuns]);
1720
+ let measured;
1721
+ if (layout !== void 0) try {
1722
+ measured = measureParagraphs(paragraphs, layout.width === "max-content" ? Number.MAX_VALUE : layout.width);
1723
+ } catch (error) {
1724
+ if (layout.contentSized === true) throw error;
1725
+ if (error instanceof CapabilityError) {
1726
+ if (!warnings.some((warning) => warning.code === error.code)) warnings.push({
1727
+ code: error.code,
1728
+ message: `Failed to complete text measurement using provided fonts: ${error.message}`
1729
+ });
1730
+ } else warnings.push({
1731
+ code: "font-measurement-unavailable",
1732
+ message: `Failed to complete text measurement using provided fonts: ${error instanceof Error ? error.message : String(error)}`
1733
+ });
1734
+ }
1735
+ if (layout?.contentSized === true && measured === void 0) throw new CapabilityError("font-measurement-unavailable", "Content-sized text is missing complete font measurement basis");
1736
+ if (measured !== void 0 && layout !== void 0 && (typeof layout.width === "number" && measured.width > layout.width + .01 || layout.height !== void 0 && measured.height > layout.height + .01)) warnings.push({
1737
+ code: "overset",
1738
+ message: "Based on provided font metrics, text overflows text box width or height; build preserves original content and dimensions"
1739
+ });
1740
+ const outputParagraphs = layout?.contentSized === true && measured !== void 0 ? paragraphs.map((paragraph, index) => ({
1741
+ ...paragraph,
1742
+ style: {
1743
+ ...paragraph.style,
1744
+ lineHeight: measured.paragraphs[index].lineHeight
1745
+ }
1746
+ })) : paragraphs;
1747
+ validateEmittableParagraphs(outputParagraphs, theme);
1748
+ const text = outputParagraphs.map(({ runs: paragraphRuns }) => paragraphRuns.map(({ text: part }) => part).join("")).join("\n");
1749
+ return {
1750
+ paragraphs: outputParagraphs,
1751
+ style,
1752
+ verticalAlign,
1753
+ ...layout === void 0 ? {} : { layout },
1754
+ destination,
1755
+ ...placeholderOptions?.isPlaceholder === true ? { isPlaceholder: true } : {},
1756
+ ...placeholderOptions?.localBodyDeclared === void 0 ? {} : { localBodyDeclared: placeholderOptions.localBodyDeclared },
1757
+ text,
1758
+ paragraphCount: outputParagraphs.length,
1759
+ resourceClaims,
1760
+ fontUses,
1761
+ ...measured === void 0 ? {} : {
1762
+ measurement: {
1763
+ width: measured.width,
1764
+ height: measured.height
1765
+ },
1766
+ measuredLayout: measured
1767
+ },
1768
+ warnings,
1769
+ missingGlyphErrors
1770
+ };
1771
+ }
1772
+ /**
1773
+ * Emits PresentationML txBody XML and font embedding contributions from resolved text facts.
1774
+ * Preserves native paragraph/run structure without converting soft wraps into hard line breaks.
1775
+ */
1776
+ function emitTextBody(resolved, theme, options = {}) {
1777
+ const { createFieldId, embedFonts } = options;
1778
+ if ((embedFonts === "full" || embedFonts === "subset") && resolved.missingGlyphErrors.length > 0) throw new CapabilityError("font-missing-glyph", resolved.missingGlyphErrors[0]);
1779
+ const emittedParagraphs = createFieldId !== void 0 ? resolved.paragraphs.map((paragraph) => ({
1780
+ ...paragraph,
1781
+ runs: paragraph.runs.map((run) => run.field !== void 0 ? {
1782
+ ...run,
1783
+ field: {
1784
+ ...run.field,
1785
+ id: createFieldId()
1786
+ }
1787
+ } : run)
1788
+ })) : resolved.paragraphs;
1789
+ const { style, verticalAlign, layout, destination, isPlaceholder } = resolved;
1790
+ let xml;
1791
+ if (destination === "table-cell") xml = `<a:txBody><a:bodyPr/><a:lstStyle/>${emittedParagraphs.map((paragraph) => paragraphXml(paragraph, theme)).join("")}</a:txBody>`;
1792
+ else if (isPlaceholder) {
1793
+ const localBody = resolved.localBodyDeclared ?? /* @__PURE__ */ new Set();
1794
+ const bodyAttrs = [];
1795
+ if (localBody.has("textWrap")) bodyAttrs.push(`wrap="${style.textWrap === "nowrap" ? "none" : "square"}"`);
1796
+ if (paddingStyleKeys.some((key) => localBody.has(key)) && layout?.insets !== void 0) bodyAttrs.push(`lIns="${pxToEmu(layout.insets.left)}"`, `tIns="${pxToEmu(layout.insets.top)}"`, `rIns="${pxToEmu(layout.insets.right)}"`, `bIns="${pxToEmu(layout.insets.bottom)}"`);
1797
+ if (localBody.has("verticalAlign")) bodyAttrs.push(`anchor="${bodyAnchor(style.verticalAlign ?? verticalAlign)}"`);
1798
+ xml = `<p:txBody>${bodyAttrs.length === 0 ? "<a:bodyPr/>" : `<a:bodyPr ${bodyAttrs.join(" ")}/>`}<a:lstStyle/>${emittedParagraphs.map((paragraph) => paragraphXml(paragraph, theme, true)).join("")}</p:txBody>`;
1799
+ } else xml = `<p:txBody><a:bodyPr wrap="${style.textWrap === "nowrap" ? "none" : "square"}" lIns="${pxToEmu(layout?.insets?.left ?? 0)}" tIns="${pxToEmu(layout?.insets?.top ?? 0)}" rIns="${pxToEmu(layout?.insets?.right ?? 0)}" bIns="${pxToEmu(layout?.insets?.bottom ?? 0)}" anchor="${bodyAnchor(style.verticalAlign ?? verticalAlign)}"><a:noAutofit/></a:bodyPr><a:lstStyle/>${emittedParagraphs.map((paragraph) => paragraphXml(paragraph, theme)).join("")}</p:txBody>`;
1800
+ return {
1801
+ xml,
1802
+ presentationContributions: fontPresentationContributions(resolved.fontUses, embedFonts)
1803
+ };
1804
+ }
1805
+ /** Generates shared font styles for native chart text and registers font claims based on actual categories, series, and label text. */
1806
+ function writeChartTextProperties(styleValue, texts, label, theme) {
1807
+ const style = readTextStyle(styleValue, label, theme);
1808
+ const runStyle = {
1809
+ fontFamily: style.fontFamily,
1810
+ fontSize: style.fontSize,
1811
+ fontWeight: style.fontWeight,
1812
+ fontStyle: style.fontStyle,
1813
+ color: style.color,
1814
+ themeFont: style.themeFont,
1815
+ letterSpacing: style.letterSpacing,
1816
+ textTransform: style.textTransform,
1817
+ textDecoration: style.textDecoration,
1818
+ textShadow: style.textShadow,
1819
+ lang: style.lang
1820
+ };
1821
+ validateRunStyle(runStyle);
1822
+ const runs = texts.map((text) => ({
1823
+ text,
1824
+ style: runStyle
1825
+ }));
1826
+ for (const text of texts) escapedXml(text);
1827
+ const { resourceClaims, fontUses, warnings, missingGlyphErrors } = textResourceClaims(runs);
1828
+ const defaultProperties = runPropertiesXml(runStyle, "a:defRPr", theme);
1829
+ const outputText = texts.join("\n");
1830
+ const lineSpacing = style.lineHeight === void 0 ? "" : `<a:lnSpc><a:spcPts val="${spacingCentipoints(positiveLength(style.lineHeight, "lineHeight"), "lineHeight")}"/></a:lnSpc>`;
1831
+ const alignment = alignmentValue(style.align);
1832
+ const paragraphAlignment = alignment === void 0 ? "" : ` algn="${alignment}"`;
1833
+ const spacingAfter = style.spacingAfter === void 0 || style.spacingAfter === 0 ? "" : `<a:spcAft><a:spcPts val="${spacingCentipoints(style.spacingAfter, "spacingAfter")}"/></a:spcAft>`;
1834
+ const endParaLang = runStyle.lang !== void 0 ? ` lang="${escapedXml(runStyle.lang)}"` : "";
1835
+ return {
1836
+ xml: `<c:txPr><a:bodyPr anchor="${bodyAnchor(style.verticalAlign)}"/><a:lstStyle/><a:p><a:pPr${paragraphAlignment}>${lineSpacing}${spacingAfter}${defaultProperties}</a:pPr><a:endParaRPr${endParaLang}/></a:p></c:txPr>`,
1837
+ text: outputText,
1838
+ resourceClaims,
1839
+ fontUses,
1840
+ warnings,
1841
+ missingGlyphErrors
1842
+ };
1843
+ }
1844
+ /** Emits a native chart or axis title with actual run properties, not canvas text. */
1845
+ function writeChartTitle(text, styleValue, label, theme) {
1846
+ const style = readTextStyle(styleValue, label, theme);
1847
+ const runStyle = {
1848
+ fontFamily: style.fontFamily,
1849
+ fontSize: style.fontSize,
1850
+ fontWeight: style.fontWeight,
1851
+ fontStyle: style.fontStyle,
1852
+ color: style.color,
1853
+ themeFont: style.themeFont,
1854
+ letterSpacing: style.letterSpacing,
1855
+ textTransform: style.textTransform,
1856
+ textDecoration: style.textDecoration,
1857
+ textShadow: style.textShadow,
1858
+ lang: style.lang
1859
+ };
1860
+ validateRunStyle(runStyle);
1861
+ const escapedText = escapedXml(text);
1862
+ const { resourceClaims, fontUses, warnings, missingGlyphErrors } = textResourceClaims([{
1863
+ text,
1864
+ style: runStyle
1865
+ }]);
1866
+ const runProperties = runPropertiesXml(runStyle, "a:rPr", theme);
1867
+ const defaultProperties = runPropertiesXml(runStyle, "a:defRPr", theme);
1868
+ const lineSpacing = style.lineHeight === void 0 ? "" : `<a:lnSpc><a:spcPts val="${spacingCentipoints(positiveLength(style.lineHeight, "lineHeight"), "lineHeight")}"/></a:lnSpc>`;
1869
+ const alignment = alignmentValue(style.align);
1870
+ const paragraphAlignment = alignment === void 0 ? "" : ` algn="${alignment}"`;
1871
+ const spacingAfter = style.spacingAfter === void 0 || style.spacingAfter === 0 ? "" : `<a:spcAft><a:spcPts val="${spacingCentipoints(style.spacingAfter, "spacingAfter")}"/></a:spcAft>`;
1872
+ const endParaLang = runStyle.lang !== void 0 ? ` lang="${escapedXml(runStyle.lang)}"` : "";
1873
+ const bodyProperties = `<a:bodyPr anchor="${bodyAnchor(style.verticalAlign)}"/>`;
1874
+ return {
1875
+ xml: `<c:title><c:tx><c:rich>${bodyProperties}<a:lstStyle/><a:p><a:pPr${paragraphAlignment}>${lineSpacing}${spacingAfter}${defaultProperties}</a:pPr><a:r>${runProperties}<a:t>${escapedText}</a:t></a:r><a:endParaRPr${endParaLang}/></a:p></c:rich></c:tx><c:overlay val="0"/><c:txPr>${bodyProperties}<a:lstStyle/><a:p><a:pPr${paragraphAlignment}>${lineSpacing}${spacingAfter}${defaultProperties}</a:pPr><a:endParaRPr${endParaLang}/></a:p></c:txPr></c:title>`,
1876
+ text,
1877
+ resourceClaims,
1878
+ fontUses,
1879
+ warnings,
1880
+ missingGlyphErrors
1881
+ };
1882
+ }
1883
+ export { emitSlideNumberRunXml, emitTextBody, measureTextLayoutFromParagraphs, parseTextContent, parseTextParagraphs, previewParagraphOutlines, previewTextBoxOutlines, renderGlyphPathSvg, renderTextOutlinesSvg, resolveTextBody, textInsets, withPreviewFontBoundary, writeChartTextProperties, writeChartTitle };