pptx-templates 0.3.9 → 0.5.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 (294) hide show
  1. package/AI-INSTRUCTOR.md +46 -3
  2. package/CHANGELOG.md +236 -1
  3. package/README.md +61 -168
  4. package/dist/automizer.d.ts +7 -0
  5. package/dist/automizer.js +168 -176
  6. package/dist/automizer.js.map +1 -1
  7. package/dist/classes/content-type-registry.js +23 -36
  8. package/dist/classes/content-type-registry.js.map +1 -1
  9. package/dist/classes/element-importer.js +130 -148
  10. package/dist/classes/element-importer.js.map +1 -1
  11. package/dist/classes/has-shapes.js +81 -126
  12. package/dist/classes/has-shapes.js.map +1 -1
  13. package/dist/classes/layout.js +47 -67
  14. package/dist/classes/layout.js.map +1 -1
  15. package/dist/classes/master.js +70 -89
  16. package/dist/classes/master.js.map +1 -1
  17. package/dist/classes/placeholder-normalizer.js +48 -37
  18. package/dist/classes/placeholder-normalizer.js.map +1 -1
  19. package/dist/classes/related-content-copier.js +65 -86
  20. package/dist/classes/related-content-copier.js.map +1 -1
  21. package/dist/classes/shape.js +79 -110
  22. package/dist/classes/shape.js.map +1 -1
  23. package/dist/classes/slide-master-remover.js +108 -130
  24. package/dist/classes/slide-master-remover.js.map +1 -1
  25. package/dist/classes/slide-notes-copier.js +24 -41
  26. package/dist/classes/slide-notes-copier.js.map +1 -1
  27. package/dist/classes/slide.js +112 -141
  28. package/dist/classes/slide.js.map +1 -1
  29. package/dist/classes/template.js +82 -117
  30. package/dist/classes/template.js.map +1 -1
  31. package/dist/constants/constants.js.map +1 -1
  32. package/dist/enums/chart-type.js.map +1 -1
  33. package/dist/enums/content-type-map.js.map +1 -1
  34. package/dist/enums/element-type.js.map +1 -1
  35. package/dist/errors.js +5 -5
  36. package/dist/errors.js.map +1 -1
  37. package/dist/extensions/cli/index.js +3 -13
  38. package/dist/extensions/cli/index.js.map +1 -1
  39. package/dist/extensions/hide-slide/index.js +48 -46
  40. package/dist/extensions/hide-slide/index.js.map +1 -1
  41. package/dist/extensions/index.d.ts +13 -3
  42. package/dist/extensions/index.js +3 -1
  43. package/dist/extensions/index.js.map +1 -1
  44. package/dist/extensions/link-scheme/index.d.ts +12 -0
  45. package/dist/extensions/link-scheme/index.js +40 -0
  46. package/dist/extensions/link-scheme/index.js.map +1 -0
  47. package/dist/extensions/master-parts/index.js +36 -49
  48. package/dist/extensions/master-parts/index.js.map +1 -1
  49. package/dist/extensions/pptxgenjs-compat/img-broken-png.js.map +1 -1
  50. package/dist/extensions/pptxgenjs-compat/index.js.map +1 -1
  51. package/dist/extensions/pptxgenjs-compat/svg-fallback.js +56 -70
  52. package/dist/extensions/pptxgenjs-compat/svg-fallback.js.map +1 -1
  53. package/dist/extensions/regexp-escape/index.d.ts +10 -0
  54. package/dist/extensions/regexp-escape/index.js +15 -0
  55. package/dist/extensions/regexp-escape/index.js.map +1 -0
  56. package/dist/extensions/run-merge/index.js +4 -5
  57. package/dist/extensions/run-merge/index.js.map +1 -1
  58. package/dist/extensions/shape-geometry/index.js +33 -11
  59. package/dist/extensions/shape-geometry/index.js.map +1 -1
  60. package/dist/extensions/shape-geometry/presets.d.ts +1 -1
  61. package/dist/extensions/shape-geometry/presets.js.map +1 -1
  62. package/dist/extensions/shape-geometry/types.js.map +1 -1
  63. package/dist/extensions/template-lint/cli.js +71 -49
  64. package/dist/extensions/template-lint/cli.js.map +1 -1
  65. package/dist/extensions/template-lint/config.js +29 -13
  66. package/dist/extensions/template-lint/config.js.map +1 -1
  67. package/dist/extensions/template-lint/data-model.js +17 -20
  68. package/dist/extensions/template-lint/data-model.js.map +1 -1
  69. package/dist/extensions/template-lint/hints.js.map +1 -1
  70. package/dist/extensions/template-lint/index.js.map +1 -1
  71. package/dist/extensions/template-lint/init-cli.d.ts +2 -0
  72. package/dist/extensions/template-lint/init-cli.js +33 -23
  73. package/dist/extensions/template-lint/init-cli.js.map +1 -1
  74. package/dist/extensions/template-lint/lint.d.ts +1 -1
  75. package/dist/extensions/template-lint/lint.js +83 -64
  76. package/dist/extensions/template-lint/lint.js.map +1 -1
  77. package/dist/extensions/template-lint/skeleton.js +5 -6
  78. package/dist/extensions/template-lint/skeleton.js.map +1 -1
  79. package/dist/extensions/template-lint/types.js.map +1 -1
  80. package/dist/extensions/template-lint/usage-cli.js +17 -18
  81. package/dist/extensions/template-lint/usage-cli.js.map +1 -1
  82. package/dist/extensions/template-lint/usage.js +8 -9
  83. package/dist/extensions/template-lint/usage.js.map +1 -1
  84. package/dist/extensions/template-lint/watch.d.ts +2 -0
  85. package/dist/extensions/template-lint/watch.js +52 -7
  86. package/dist/extensions/template-lint/watch.js.map +1 -1
  87. package/dist/extensions/template-logic/clone.d.ts +2 -16
  88. package/dist/extensions/template-logic/clone.js +15 -90
  89. package/dist/extensions/template-logic/clone.js.map +1 -1
  90. package/dist/extensions/template-logic/commands.d.ts +1 -1
  91. package/dist/extensions/template-logic/commands.js +12 -11
  92. package/dist/extensions/template-logic/commands.js.map +1 -1
  93. package/dist/extensions/template-logic/expression.d.ts +15 -2
  94. package/dist/extensions/template-logic/expression.js +143 -63
  95. package/dist/extensions/template-logic/expression.js.map +1 -1
  96. package/dist/extensions/template-logic/images.js +58 -55
  97. package/dist/extensions/template-logic/images.js.map +1 -1
  98. package/dist/extensions/template-logic/index.js +16 -24
  99. package/dist/extensions/template-logic/index.js.map +1 -1
  100. package/dist/extensions/template-logic/list-commands.js +8 -19
  101. package/dist/extensions/template-logic/list-commands.js.map +1 -1
  102. package/dist/extensions/template-logic/renderer.d.ts +9 -0
  103. package/dist/extensions/template-logic/renderer.js +480 -477
  104. package/dist/extensions/template-logic/renderer.js.map +1 -1
  105. package/dist/extensions/template-logic/types.d.ts +8 -1
  106. package/dist/extensions/template-logic/types.js.map +1 -1
  107. package/dist/extensions/template-render/cli.js +34 -22
  108. package/dist/extensions/template-render/cli.js.map +1 -1
  109. package/dist/extensions/template-render/index.js +152 -107
  110. package/dist/extensions/template-render/index.js.map +1 -1
  111. package/dist/extensions/template-render/prune.d.ts +14 -0
  112. package/dist/extensions/template-render/prune.js +131 -0
  113. package/dist/extensions/template-render/prune.js.map +1 -0
  114. package/dist/extensions/template-render/zip-text.d.ts +9 -0
  115. package/dist/extensions/template-render/zip-text.js +27 -0
  116. package/dist/extensions/template-render/zip-text.js.map +1 -0
  117. package/dist/extensions/template-render/zip-writer.d.ts +16 -0
  118. package/dist/extensions/template-render/zip-writer.js +151 -0
  119. package/dist/extensions/template-render/zip-writer.js.map +1 -0
  120. package/dist/extensions/text-flow/flow.js +183 -207
  121. package/dist/extensions/text-flow/flow.js.map +1 -1
  122. package/dist/extensions/text-flow/font-file.d.ts +9 -0
  123. package/dist/extensions/text-flow/font-file.js +40 -22
  124. package/dist/extensions/text-flow/font-file.js.map +1 -1
  125. package/dist/extensions/text-flow/fonts.d.ts +4 -0
  126. package/dist/extensions/text-flow/fonts.js +67 -23
  127. package/dist/extensions/text-flow/fonts.js.map +1 -1
  128. package/dist/extensions/text-flow/index.js.map +1 -1
  129. package/dist/extensions/text-flow/layout.js +8 -9
  130. package/dist/extensions/text-flow/layout.js.map +1 -1
  131. package/dist/extensions/text-flow/slide-styles.js +18 -22
  132. package/dist/extensions/text-flow/slide-styles.js.map +1 -1
  133. package/dist/extensions/text-flow/styles.d.ts +7 -1
  134. package/dist/extensions/text-flow/styles.js +108 -64
  135. package/dist/extensions/text-flow/styles.js.map +1 -1
  136. package/dist/helper/archive/archive-fs.d.ts +11 -0
  137. package/dist/helper/archive/archive-fs.js +195 -142
  138. package/dist/helper/archive/archive-fs.js.map +1 -1
  139. package/dist/helper/archive/archive-jszip.js +101 -125
  140. package/dist/helper/archive/archive-jszip.js.map +1 -1
  141. package/dist/helper/archive/archive.d.ts +6 -0
  142. package/dist/helper/archive/archive.js +21 -30
  143. package/dist/helper/archive/archive.js.map +1 -1
  144. package/dist/helper/archive/jszip-fast-read.d.ts +26 -0
  145. package/dist/helper/archive/jszip-fast-read.js +166 -0
  146. package/dist/helper/archive/jszip-fast-read.js.map +1 -0
  147. package/dist/helper/cell-id-helper.d.ts +1 -0
  148. package/dist/helper/cell-id-helper.js +6 -2
  149. package/dist/helper/cell-id-helper.js.map +1 -1
  150. package/dist/helper/compute-src-rect.js +4 -5
  151. package/dist/helper/compute-src-rect.js.map +1 -1
  152. package/dist/helper/content-tracker.js +86 -114
  153. package/dist/helper/content-tracker.js.map +1 -1
  154. package/dist/helper/count-helper.js +48 -78
  155. package/dist/helper/count-helper.js.map +1 -1
  156. package/dist/helper/css-style-parser.d.ts +1 -1
  157. package/dist/helper/css-style-parser.js +1 -2
  158. package/dist/helper/css-style-parser.js.map +1 -1
  159. package/dist/helper/file-helper.js +30 -48
  160. package/dist/helper/file-helper.js.map +1 -1
  161. package/dist/helper/general-helper.js.map +1 -1
  162. package/dist/helper/generate/generate-pptxgenjs.js +36 -48
  163. package/dist/helper/generate/generate-pptxgenjs.js.map +1 -1
  164. package/dist/helper/html-to-multitext-helper.d.ts +4 -4
  165. package/dist/helper/html-to-multitext-helper.js +46 -23
  166. package/dist/helper/html-to-multitext-helper.js.map +1 -1
  167. package/dist/helper/hyperlink-processor.js +125 -139
  168. package/dist/helper/hyperlink-processor.js.map +1 -1
  169. package/dist/helper/image-dimensions.js.map +1 -1
  170. package/dist/helper/jszip-helper.d.ts +1 -1
  171. package/dist/helper/jszip-helper.js +40 -33
  172. package/dist/helper/jszip-helper.js.map +1 -1
  173. package/dist/helper/layout-index.js +51 -71
  174. package/dist/helper/layout-index.js.map +1 -1
  175. package/dist/helper/logger.js +4 -4
  176. package/dist/helper/logger.js.map +1 -1
  177. package/dist/helper/media-deduplicator.d.ts +24 -0
  178. package/dist/helper/media-deduplicator.js +81 -34
  179. package/dist/helper/media-deduplicator.js.map +1 -1
  180. package/dist/helper/modify-background-helper.js +46 -46
  181. package/dist/helper/modify-background-helper.js.map +1 -1
  182. package/dist/helper/modify-chart-helper.d.ts +1 -1
  183. package/dist/helper/modify-chart-helper.js +597 -591
  184. package/dist/helper/modify-chart-helper.js.map +1 -1
  185. package/dist/helper/modify-cleanup-helper.js +112 -112
  186. package/dist/helper/modify-cleanup-helper.js.map +1 -1
  187. package/dist/helper/modify-color-helper.d.ts +1 -1
  188. package/dist/helper/modify-color-helper.js +53 -53
  189. package/dist/helper/modify-color-helper.js.map +1 -1
  190. package/dist/helper/modify-helper.js +25 -25
  191. package/dist/helper/modify-helper.js.map +1 -1
  192. package/dist/helper/modify-hyperlink-element.js.map +1 -1
  193. package/dist/helper/modify-hyperlink-helper.js +152 -158
  194. package/dist/helper/modify-hyperlink-helper.js.map +1 -1
  195. package/dist/helper/modify-image-helper.d.ts +1 -1
  196. package/dist/helper/modify-image-helper.js +121 -132
  197. package/dist/helper/modify-image-helper.js.map +1 -1
  198. package/dist/helper/modify-presentation-helper.js +137 -154
  199. package/dist/helper/modify-presentation-helper.js.map +1 -1
  200. package/dist/helper/modify-shape-helper.js +262 -262
  201. package/dist/helper/modify-shape-helper.js.map +1 -1
  202. package/dist/helper/modify-table-helper.js +95 -84
  203. package/dist/helper/modify-table-helper.js.map +1 -1
  204. package/dist/helper/modify-text-helper.d.ts +8 -0
  205. package/dist/helper/modify-text-helper.js +202 -190
  206. package/dist/helper/modify-text-helper.js.map +1 -1
  207. package/dist/helper/modify-xml-helper.js +36 -36
  208. package/dist/helper/modify-xml-helper.js.map +1 -1
  209. package/dist/helper/multitext-helper.js +13 -9
  210. package/dist/helper/multitext-helper.js.map +1 -1
  211. package/dist/helper/ppt-paths.js +17 -17
  212. package/dist/helper/ppt-paths.js.map +1 -1
  213. package/dist/helper/shape-type-detector.js +18 -29
  214. package/dist/helper/shape-type-detector.js.map +1 -1
  215. package/dist/helper/text-replace-helper.js +8 -8
  216. package/dist/helper/text-replace-helper.js.map +1 -1
  217. package/dist/helper/xml/lnLRTB.js.map +1 -1
  218. package/dist/helper/xml/prstGeom.js.map +1 -1
  219. package/dist/helper/xml-clone.d.ts +24 -0
  220. package/dist/helper/xml-clone.js +269 -0
  221. package/dist/helper/xml-clone.js.map +1 -0
  222. package/dist/helper/xml-elements.js +17 -20
  223. package/dist/helper/xml-elements.js.map +1 -1
  224. package/dist/helper/xml-find.d.ts +4 -0
  225. package/dist/helper/xml-find.js +48 -0
  226. package/dist/helper/xml-find.js.map +1 -0
  227. package/dist/helper/xml-helper.js +102 -135
  228. package/dist/helper/xml-helper.js.map +1 -1
  229. package/dist/helper/xml-parse-cache.d.ts +31 -0
  230. package/dist/helper/xml-parse-cache.js +71 -0
  231. package/dist/helper/xml-parse-cache.js.map +1 -0
  232. package/dist/helper/xml-placeholder-helper.js +10 -10
  233. package/dist/helper/xml-placeholder-helper.js.map +1 -1
  234. package/dist/helper/xml-pretty-print.js.map +1 -1
  235. package/dist/helper/xml-relationship-helper.js +132 -147
  236. package/dist/helper/xml-relationship-helper.js.map +1 -1
  237. package/dist/helper/xml-serializer.d.ts +2 -0
  238. package/dist/helper/xml-serializer.js +192 -0
  239. package/dist/helper/xml-serializer.js.map +1 -0
  240. package/dist/helper/xml-slide-helper.js +109 -129
  241. package/dist/helper/xml-slide-helper.js.map +1 -1
  242. package/dist/helper/xml-template-helper.js +120 -144
  243. package/dist/helper/xml-template-helper.js.map +1 -1
  244. package/dist/helper/xmldom-sax-patch.js +52 -2
  245. package/dist/helper/xmldom-sax-patch.js.map +1 -1
  246. package/dist/index.d.ts +4 -4
  247. package/dist/index.js +4 -2
  248. package/dist/index.js.map +1 -1
  249. package/dist/interfaces/iarchive.js.map +1 -1
  250. package/dist/interfaces/ichart.js.map +1 -1
  251. package/dist/interfaces/icounter.js.map +1 -1
  252. package/dist/interfaces/igenerator.js.map +1 -1
  253. package/dist/interfaces/iimage.js.map +1 -1
  254. package/dist/interfaces/ilayout.js.map +1 -1
  255. package/dist/interfaces/imaster.js.map +1 -1
  256. package/dist/interfaces/imulti-text.js.map +1 -1
  257. package/dist/interfaces/ipptxgenjs-slide.js.map +1 -1
  258. package/dist/interfaces/ipresentation-props.js.map +1 -1
  259. package/dist/interfaces/ishape-action.js.map +1 -1
  260. package/dist/interfaces/ishape.js.map +1 -1
  261. package/dist/interfaces/islide.js.map +1 -1
  262. package/dist/interfaces/itemplate.js.map +1 -1
  263. package/dist/interfaces/pres-template.js.map +1 -1
  264. package/dist/interfaces/root-pres-template.js.map +1 -1
  265. package/dist/modify/modify-chart.d.ts +4 -4
  266. package/dist/modify/modify-chart.js +35 -23
  267. package/dist/modify/modify-chart.js.map +1 -1
  268. package/dist/modify/modify-table.d.ts +0 -1
  269. package/dist/modify/modify-table.js +19 -27
  270. package/dist/modify/modify-table.js.map +1 -1
  271. package/dist/shapes/chart.js +238 -287
  272. package/dist/shapes/chart.js.map +1 -1
  273. package/dist/shapes/diagram.d.ts +14 -0
  274. package/dist/shapes/diagram.js +167 -103
  275. package/dist/shapes/diagram.js.map +1 -1
  276. package/dist/shapes/generic.js +62 -83
  277. package/dist/shapes/generic.js.map +1 -1
  278. package/dist/shapes/hyperlink.d.ts +0 -1
  279. package/dist/shapes/hyperlink.js +84 -124
  280. package/dist/shapes/hyperlink.js.map +1 -1
  281. package/dist/shapes/image.js +118 -149
  282. package/dist/shapes/image.js.map +1 -1
  283. package/dist/shapes/ole.js +148 -188
  284. package/dist/shapes/ole.js.map +1 -1
  285. package/dist/types/chart-types.js.map +1 -1
  286. package/dist/types/modify-types.js.map +1 -1
  287. package/dist/types/shape-types.js.map +1 -1
  288. package/dist/types/table-types.js.map +1 -1
  289. package/dist/types/types.d.ts +7 -0
  290. package/dist/types/types.js.map +1 -1
  291. package/dist/types/xml-types.js.map +1 -1
  292. package/dist/vendor/pptxgenjs/README.md +8 -3
  293. package/dist/vendor/pptxgenjs/index.js +19 -2
  294. package/package.json +13 -16
@@ -1,16 +1,8 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.TemplateRenderer = exports.TemplateRenderError = void 0;
13
- const xmldom_1 = require("@xmldom/xmldom");
4
+ const xml_serializer_1 = require("../../helper/xml-serializer");
5
+ const xml_find_1 = require("../../helper/xml-find");
14
6
  const xml_helper_1 = require("../../helper/xml-helper");
15
7
  const xml_relationship_helper_1 = require("../../helper/xml-relationship-helper");
16
8
  const multitext_helper_1 = require("../../helper/multitext-helper");
@@ -21,6 +13,7 @@ const images_1 = require("./images");
21
13
  const clone_1 = require("./clone");
22
14
  const text_flow_1 = require("../text-flow");
23
15
  const logger_1 = require("../../helper/logger");
16
+ const link_scheme_1 = require("../link-scheme");
24
17
  /** Tags that open, split or close a block. */
25
18
  const BLOCK_TYPES = [
26
19
  'if',
@@ -102,20 +95,19 @@ class Scope {
102
95
  }
103
96
  /** Own variables, to undo the EXECs of a trial render. */
104
97
  snapshot() {
105
- return Object.assign({}, this.vars);
98
+ return { ...this.vars };
106
99
  }
107
100
  restore(snapshot) {
108
101
  Object.keys(this.vars).forEach((key) => delete this.vars[key]);
109
102
  Object.assign(this.vars, snapshot);
110
103
  }
111
104
  assignExisting(name, value) {
112
- var _a, _b;
113
105
  if (this.writable &&
114
106
  Object.prototype.hasOwnProperty.call(this.vars, name)) {
115
107
  this.vars[name] = value;
116
108
  return true;
117
109
  }
118
- return (_b = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.assignExisting(name, value)) !== null && _b !== void 0 ? _b : false;
110
+ return this.parent?.assignExisting(name, value) ?? false;
119
111
  }
120
112
  }
121
113
  class TemplateRenderError extends Error {
@@ -125,11 +117,13 @@ class TemplateRenderError extends Error {
125
117
  }
126
118
  }
127
119
  exports.TemplateRenderError = TemplateRenderError;
120
+ /** FOR iterations one renderer may run; nesting multiplies, so cap the total. */
121
+ const MAX_LOOP_ITERATIONS = 200_000;
128
122
  class TemplateRenderer {
129
123
  constructor(data, options = {}, context = {}) {
130
- var _a, _b, _c, _d;
131
124
  this.options = options;
132
125
  this.context = context;
126
+ this.loopIterations = 0;
133
127
  this.aliases = new Map();
134
128
  this.errors = [];
135
129
  this.links = new Map();
@@ -141,6 +135,8 @@ class TemplateRenderer {
141
135
  this.flowLimits = new Map();
142
136
  /** flow(list, n, options): the options per box, as an expression. */
143
137
  this.flowOptions = new Map();
138
+ /** flow(): each box tokenized once, for all its measuring copies. */
139
+ this.copySources = new Map();
144
140
  /** Rendering an alt text (renderAltTexts). */
145
141
  this.inAltText = false;
146
142
  this.hideSlideWarned = false;
@@ -148,8 +144,8 @@ class TemplateRenderer {
148
144
  this.opening = syntax.opening;
149
145
  this.tagPattern = syntax.pattern;
150
146
  this.evaluation = {
151
- strict: (_a = options.strict) !== null && _a !== void 0 ? _a : false,
152
- allowStringPatterns: (_b = options.allowStringPatterns) !== null && _b !== void 0 ? _b : false,
147
+ strict: options.strict ?? false,
148
+ allowStringPatterns: options.allowStringPatterns ?? false,
153
149
  };
154
150
  // Built-in helpers; additionalJsContext and data can shadow them.
155
151
  // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -158,45 +154,43 @@ class TemplateRenderer {
158
154
  flow: (list) => this.flowEntries(list),
159
155
  flowRest: (list) => this.flowRest(list),
160
156
  // the entries no earlier slide of the deck shows (renderDeck)
161
- flowContinue: (list) => { var _a; return ((_a = options.flowShown) !== null && _a !== void 0 ? _a : new text_flow_1.FlowShown()).continue(list); },
157
+ flowContinue: (list) => (options.flowShown ?? new text_flow_1.FlowShown()).continue(list),
162
158
  // 1-based number of this slide among the slides a list needs
163
- flowPage: ((_c = options.flowPage) !== null && _c !== void 0 ? _c : 0) + 1,
159
+ flowPage: (options.flowPage ?? 0) + 1,
164
160
  get flowPages() {
165
- var _a, _b;
166
- return (_b = (_a = self.textFlow) === null || _a === void 0 ? void 0 : _a.pages) !== null && _b !== void 0 ? _b : 1;
161
+ return self.textFlow?.pages ?? 1;
167
162
  },
168
163
  }, undefined, false);
169
- const jsContext = new Scope((_d = options.additionalJsContext) !== null && _d !== void 0 ? _d : {}, builtins, false);
170
- this.root = new Scope({}, new Scope(data !== null && data !== void 0 ? data : {}, jsContext, false));
164
+ const jsContext = new Scope(options.additionalJsContext ?? {}, builtins, false);
165
+ this.root = new Scope({}, new Scope(data ?? {}, jsContext, false));
171
166
  }
172
- render(element) {
173
- return __awaiter(this, void 0, void 0, function* () {
174
- var _a;
175
- this.collectAliases(element);
176
- const targets = this.findTargets(element);
177
- this.setupFlow(targets);
178
- // Collected before the text is rendered: alt text written while
179
- // rendering (IMAGE … alt from the data) is content, not a template
180
- const altTexts = this.altTextHolders(element);
181
- for (const target of targets) {
182
- this.currentBody = target.tagName === 'p:txBody' ? target : undefined;
183
- if (target.tagName === 'a:tbl') {
184
- yield this.renderTable(target);
185
- }
186
- else if (this.containsTag(target)) {
187
- const bodyTokens = this.tokenizeBody(target);
188
- yield this.writeBody(target, bodyTokens, this.parse(bodyTokens.tokens, textControl), this.root);
189
- yield this.placePendingImages(target);
190
- }
167
+ async render(element) {
168
+ this.collectAliases(element);
169
+ const targets = this.findTargets(element);
170
+ this.setupFlow(targets);
171
+ // Collected before the text is rendered: alt text written while
172
+ // rendering (IMAGE … alt from the data) is content, not a template
173
+ const altTexts = this.altTextHolders(element);
174
+ for (const target of targets) {
175
+ this.currentBody = target.tagName === 'p:txBody' ? target : undefined;
176
+ if (target.tagName === 'a:tbl') {
177
+ await this.renderTable(target);
191
178
  }
192
- // flow() cards left without an entry (the last slide of a list)
193
- (_a = this.textFlow) === null || _a === void 0 ? void 0 : _a.emptyGroups().forEach((group) => { var _a; return (_a = group.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(group); });
194
- yield this.renderAltTexts(altTexts.filter((cNvPr) => isWithin(cNvPr, element)));
195
- if (this.errors.length) {
196
- throw new TemplateRenderError(`Template rendering failed with ${this.errors.length} error(s):\n` +
197
- this.errors.map((e) => `- ${e}`).join('\n'));
179
+ else if (this.containsTag(target)) {
180
+ const bodyTokens = this.tokenizeBody(target);
181
+ await this.writeBody(target, bodyTokens, this.parse(bodyTokens.tokens, textControl), this.root);
182
+ await this.placePendingImages(target);
198
183
  }
199
- });
184
+ }
185
+ // flow() cards left without an entry (the last slide of a list)
186
+ this.textFlow
187
+ ?.emptyGroups()
188
+ .forEach((group) => group.parentNode?.removeChild(group));
189
+ await this.renderAltTexts(altTexts.filter((cNvPr) => isWithin(cNvPr, element)));
190
+ if (this.errors.length) {
191
+ throw new TemplateRenderError(`Template rendering failed with ${this.errors.length} error(s):\n` +
192
+ this.errors.map((e) => `- ${e}`).join('\n'));
193
+ }
200
194
  }
201
195
  /** `{{HIDE-SLIDE …}}` outside the speaker notes: removed, not applied. */
202
196
  warnHideSlide(tag) {
@@ -215,7 +209,7 @@ class TemplateRenderer {
215
209
  targets
216
210
  .filter((t) => t.tagName === 'p:txBody' && this.containsTag(t))
217
211
  .forEach((body) => {
218
- const text = xml_helper_1.XmlHelper.collectionToArray(body.getElementsByTagName('a:t'))
212
+ const text = (0, xml_find_1.elementsByTagName)(body, 'a:t')
219
213
  .map((t) => t.textContent)
220
214
  .join('');
221
215
  const keys = new Set();
@@ -256,7 +250,7 @@ class TemplateRenderer {
256
250
  this.textFlow = new text_flow_1.TextFlow(boxes, {
257
251
  renderCopy: (body, entries) => this.renderCopy(body, entries),
258
252
  measureKey: (body) => this.flowMeasureKey(body),
259
- styles: () => __awaiter(this, void 0, void 0, function* () { var _a, _b, _c; return (_c = (yield ((_b = (_a = this.context).styles) === null || _b === void 0 ? void 0 : _b.call(_a)))) !== null && _c !== void 0 ? _c : {}; }),
253
+ styles: async () => (await this.context.styles?.()) ?? {},
260
254
  }, {
261
255
  fonts: this.options.fonts,
262
256
  flowOverflow: this.options.flowOverflow,
@@ -310,84 +304,90 @@ class TemplateRenderer {
310
304
  evaluate: (scope, options) => {
311
305
  if (this.flowOverride)
312
306
  return expr.evaluate(scope, options);
313
- return (() => __awaiter(this, void 0, void 0, function* () {
307
+ return (async () => {
314
308
  for (const list of lists) {
315
309
  let value = list.expr.evaluate(scope, options);
316
310
  if (isThenable(value))
317
- value = yield value;
318
- yield this.textFlow.prepare(list.key, value, yield this.flowLimitValues(scope, options), yield this.flowUnmeasured(scope, options));
311
+ value = await value;
312
+ await this.textFlow.prepare(list.key, value, await this.flowLimitValues(scope, options), await this.flowUnmeasured(scope, options));
319
313
  }
320
314
  return expr.evaluate(scope, options);
321
- }))();
315
+ })();
322
316
  },
323
317
  };
324
318
  }
325
319
  /** flow(list, n): the number `n` of each box that has one. */
326
- flowLimitValues(scope, options) {
327
- return __awaiter(this, void 0, void 0, function* () {
328
- const limits = new Map();
329
- for (const [body, expr] of this.flowLimits) {
330
- let value = expr.evaluate(scope, options);
331
- if (isThenable(value))
332
- value = yield value;
333
- const limit = Number(value);
334
- if (!Number.isInteger(limit) || limit < 1) {
335
- throw new Error(`flow(…, ${expr.source}): the number of entries per text box ` +
336
- `must be a whole number of at least 1, not ${String(value)}`);
337
- }
338
- limits.set(body, limit);
320
+ async flowLimitValues(scope, options) {
321
+ const limits = new Map();
322
+ for (const [body, expr] of this.flowLimits) {
323
+ let value = expr.evaluate(scope, options);
324
+ if (isThenable(value))
325
+ value = await value;
326
+ const limit = Number(value);
327
+ if (!Number.isInteger(limit) || limit < 1) {
328
+ throw new Error(`flow(…, ${expr.source}): the number of entries per text box ` +
329
+ `must be a whole number of at least 1, not ${String(value)}`);
339
330
  }
340
- return limits;
341
- });
331
+ limits.set(body, limit);
332
+ }
333
+ return limits;
342
334
  }
343
335
  /** flow(list, n, { measure: false }): the boxes that are not measured. */
344
- flowUnmeasured(scope, options) {
345
- return __awaiter(this, void 0, void 0, function* () {
346
- const unmeasured = new Set();
347
- for (const [body, expr] of this.flowOptions) {
348
- let value = expr.evaluate(scope, options);
349
- if (isThenable(value))
350
- value = yield value;
351
- if (value === null || typeof value !== 'object') {
352
- throw new Error(`flow(…, …, ${expr.source}): the options must be an object, ` +
353
- `such as { measure: false }, not ${String(value)}`);
354
- }
355
- if (value.measure === false) {
356
- unmeasured.add(body);
357
- }
336
+ async flowUnmeasured(scope, options) {
337
+ const unmeasured = new Set();
338
+ for (const [body, expr] of this.flowOptions) {
339
+ let value = expr.evaluate(scope, options);
340
+ if (isThenable(value))
341
+ value = await value;
342
+ if (value === null || typeof value !== 'object') {
343
+ throw new Error(`flow(…, …, ${expr.source}): the options must be an object, ` +
344
+ `such as { measure: false }, not ${String(value)}`);
358
345
  }
359
- return unmeasured;
360
- });
346
+ if (value.measure === false) {
347
+ unmeasured.add(body);
348
+ }
349
+ }
350
+ return unmeasured;
361
351
  }
362
352
  /**
363
353
  * Renders a detached copy of a text body with flow() returning `entries`
364
354
  * and returns its paragraphs. EXEC assignments and collected errors of
365
355
  * this trial render are undone; the real render repeats them.
366
356
  */
367
- renderCopy(body, entries) {
368
- return __awaiter(this, void 0, void 0, function* () {
369
- const copy = (0, clone_1.cloneXml)(body, true);
370
- const saved = {
371
- override: this.flowOverride,
372
- current: this.currentBody,
373
- errors: this.errors.length,
374
- vars: this.root.snapshot(),
375
- };
376
- this.flowOverride = () => entries;
377
- this.currentBody = copy;
378
- try {
379
- const tokens = this.tokenizeBody(copy);
380
- yield this.writeBody(copy, tokens, this.parse(tokens.tokens, textControl), this.root);
381
- return this.childElements(copy, 'a:p');
382
- }
383
- finally {
384
- this.pendingImages.delete(copy);
385
- this.flowOverride = saved.override;
386
- this.currentBody = saved.current;
387
- this.errors.length = saved.errors;
388
- this.root.restore(saved.vars);
389
- }
390
- });
357
+ async renderCopy(body, entries) {
358
+ // Tokens and blocks of the box are only read while writing, so one
359
+ // tokenized copy serves every entry. Each render writes into a body
360
+ // with the box's properties and a paragraph for writeBody to replace.
361
+ let source = this.copySources.get(body);
362
+ if (!source) {
363
+ const tokens = this.tokenizeBody((0, clone_1.cloneXml)(body, true));
364
+ source = { tokens, blocks: this.parse(tokens.tokens, textControl) };
365
+ this.copySources.set(body, source);
366
+ }
367
+ const copy = (0, clone_1.cloneXml)(body, false);
368
+ this.childElements(body)
369
+ .filter((child) => child.tagName !== 'a:p')
370
+ .forEach((child) => copy.appendChild((0, clone_1.cloneXml)(child, true)));
371
+ copy.appendChild(body.ownerDocument.createElement('a:p'));
372
+ const saved = {
373
+ override: this.flowOverride,
374
+ current: this.currentBody,
375
+ errors: this.errors.length,
376
+ vars: this.root.snapshot(),
377
+ };
378
+ this.flowOverride = () => entries;
379
+ this.currentBody = copy;
380
+ try {
381
+ await this.writeBody(copy, source.tokens, source.blocks, this.root);
382
+ return this.childElements(copy, 'a:p');
383
+ }
384
+ finally {
385
+ this.pendingImages.delete(copy);
386
+ this.flowOverride = saved.override;
387
+ this.currentBody = saved.current;
388
+ this.errors.length = saved.errors;
389
+ this.root.restore(saved.vars);
390
+ }
391
391
  }
392
392
  /**
393
393
  * flow(): boxes with the same key render and measure the same, so one
@@ -400,7 +400,7 @@ class TemplateRenderer {
400
400
  flowMeasureKey(body) {
401
401
  if (this.options.errorHandler)
402
402
  return undefined;
403
- const text = xml_helper_1.XmlHelper.collectionToArray(body.getElementsByTagName('a:t'))
403
+ const text = (0, xml_find_1.elementsByTagName)(body, 'a:t')
404
404
  .map((t) => t.textContent)
405
405
  .join('');
406
406
  for (const match of text.matchAll(this.tagPattern)) {
@@ -410,19 +410,19 @@ class TemplateRenderer {
410
410
  if (command.type === 'HTML')
411
411
  return undefined;
412
412
  }
413
- catch (_a) {
413
+ catch {
414
414
  return undefined;
415
415
  }
416
416
  }
417
417
  const shape = (0, clone_1.cloneXml)(body.parentNode, true);
418
418
  const childOf = (parent, tagName) => parent && this.childElements(parent, tagName)[0];
419
419
  const off = childOf(childOf(childOf(shape, 'p:spPr'), 'a:xfrm'), 'a:off');
420
- off === null || off === void 0 ? void 0 : off.setAttribute('x', '0');
421
- off === null || off === void 0 ? void 0 : off.setAttribute('y', '0');
420
+ off?.setAttribute('x', '0');
421
+ off?.setAttribute('y', '0');
422
422
  const cNvPr = childOf(childOf(shape, 'p:nvSpPr'), 'p:cNvPr');
423
- cNvPr === null || cNvPr === void 0 ? void 0 : cNvPr.removeAttribute('id');
424
- cNvPr === null || cNvPr === void 0 ? void 0 : cNvPr.removeAttribute('name');
425
- return new xmldom_1.XMLSerializer().serializeToString(shape);
423
+ cNvPr?.removeAttribute('id');
424
+ cNvPr?.removeAttribute('name');
425
+ return (0, xml_serializer_1.serializeXml)(shape);
426
426
  }
427
427
  /** Shape text bodies and tables, in document order. */
428
428
  findTargets(element) {
@@ -443,13 +443,12 @@ class TemplateRenderer {
443
443
  return targets;
444
444
  }
445
445
  containsTag(element) {
446
- var _a;
447
- return ((_a = element.textContent) !== null && _a !== void 0 ? _a : '').includes(this.opening);
446
+ return (element.textContent ?? '').includes(this.opening);
448
447
  }
449
448
  /** ALIAS definitions apply everywhere, so collect them up front. */
450
449
  collectAliases(element) {
451
- xml_helper_1.XmlHelper.collectionToArray(element.getElementsByTagName('a:p')).forEach((paragraph) => {
452
- const text = xml_helper_1.XmlHelper.collectionToArray(paragraph.getElementsByTagName('a:t'))
450
+ (0, xml_find_1.elementsByTagName)(element, 'a:p').forEach((paragraph) => {
451
+ const text = (0, xml_find_1.elementsByTagName)(paragraph, 'a:t')
453
452
  .map((t) => t.textContent)
454
453
  .join('');
455
454
  for (const match of text.matchAll(this.tagPattern)) {
@@ -457,7 +456,7 @@ class TemplateRenderer {
457
456
  try {
458
457
  command = (0, commands_1.parseCommand)(match[1], match[0]);
459
458
  }
460
- catch (_a) {
459
+ catch {
461
460
  continue; // reported where the tag is rendered
462
461
  }
463
462
  if (command.type === 'ALIAS') {
@@ -638,7 +637,10 @@ class TemplateRenderer {
638
637
  }
639
638
  compileStatements(source, tag) {
640
639
  try {
641
- return (0, expression_1.parseStatements)(source).map((statement) => (Object.assign(Object.assign({}, statement), { expr: this.withFlow(statement.expr, tag) })));
640
+ return (0, expression_1.parseStatements)(source).map((statement) => ({
641
+ ...statement,
642
+ expr: this.withFlow(statement.expr, tag),
643
+ }));
642
644
  }
643
645
  catch (error) {
644
646
  if (!this.handlesErrors)
@@ -662,26 +664,24 @@ class TemplateRenderer {
662
664
  * async. Errors go to errorHandler, are collected (failFast: false) or
663
665
  * reject the render.
664
666
  */
665
- value(tag, fn) {
666
- return __awaiter(this, void 0, void 0, function* () {
667
- try {
668
- let result = fn();
669
- if (isThenable(result))
670
- result = yield result;
671
- return result;
667
+ async value(tag, fn) {
668
+ try {
669
+ let result = fn();
670
+ if (isThenable(result))
671
+ result = await result;
672
+ return result;
673
+ }
674
+ catch (error) {
675
+ const err = error instanceof Error ? error : new Error(String(error));
676
+ if (this.options.errorHandler) {
677
+ return this.options.errorHandler(err, tag);
672
678
  }
673
- catch (error) {
674
- const err = error instanceof Error ? error : new Error(String(error));
675
- if (this.options.errorHandler) {
676
- return this.options.errorHandler(err, tag);
677
- }
678
- if (this.options.failFast === false) {
679
- this.errors.push(this.withTag(tag, err.message));
680
- return undefined;
681
- }
682
- throw this.tagged(err, tag);
679
+ if (this.options.failFast === false) {
680
+ this.errors.push(this.withTag(tag, err.message));
681
+ return undefined;
683
682
  }
684
- });
683
+ throw this.tagged(err, tag);
684
+ }
685
685
  }
686
686
  /*
687
687
  * Parsing & evaluating blocks (shared by text bodies and table rows)
@@ -692,7 +692,7 @@ class TemplateRenderer {
692
692
  const current = () => (stack.length ? stack[stack.length - 1].body : root);
693
693
  items.forEach((item) => {
694
694
  const tag = control(item);
695
- const directive = tag === null || tag === void 0 ? void 0 : tag.directive;
695
+ const directive = tag?.directive;
696
696
  if (!directive || !BLOCK_TYPES.includes(directive.type)) {
697
697
  current().push({ kind: 'item', item });
698
698
  return;
@@ -724,7 +724,7 @@ class TemplateRenderer {
724
724
  }
725
725
  case 'elseif':
726
726
  case 'else': {
727
- if ((top === null || top === void 0 ? void 0 : top.block.kind) !== 'if') {
727
+ if (top?.block.kind !== 'if') {
728
728
  throw new TemplateRenderError(`${tag.tag} without a matching {{IF …}}`);
729
729
  }
730
730
  const branches = top.block.branches;
@@ -743,7 +743,7 @@ class TemplateRenderer {
743
743
  case 'endif':
744
744
  case 'endfor': {
745
745
  const expected = directive.type === 'endif' ? 'if' : 'for';
746
- if ((top === null || top === void 0 ? void 0 : top.block.kind) !== expected) {
746
+ if (top?.block.kind !== expected) {
747
747
  throw new TemplateRenderError(`${tag.tag} without a matching ${expected.toUpperCase()}` +
748
748
  (top ? ` (open: ${top.tag})` : ''));
749
749
  }
@@ -757,41 +757,42 @@ class TemplateRenderer {
757
757
  }
758
758
  return root;
759
759
  }
760
- evaluate(blocks, scope, emit) {
761
- return __awaiter(this, void 0, void 0, function* () {
762
- for (const block of blocks) {
763
- if (block.kind === 'item') {
764
- yield emit(block.item, scope);
765
- }
766
- else if (block.kind === 'if') {
767
- for (const branch of block.branches) {
768
- const pass = !branch.expr ||
769
- (yield this.value(branch.tag, () => branch.expr.evaluate(scope, this.evaluation)));
770
- if (pass) {
771
- yield this.evaluate(branch.body, scope, emit);
772
- break;
773
- }
760
+ async evaluate(blocks, scope, emit) {
761
+ for (const block of blocks) {
762
+ if (block.kind === 'item') {
763
+ await emit(block.item, scope);
764
+ }
765
+ else if (block.kind === 'if') {
766
+ for (const branch of block.branches) {
767
+ const pass = !branch.expr ||
768
+ (await this.value(branch.tag, () => branch.expr.evaluate(scope, this.evaluation)));
769
+ if (pass) {
770
+ await this.evaluate(branch.body, scope, emit);
771
+ break;
774
772
  }
775
773
  }
776
- else {
777
- const value = yield this.value(block.tag, () => {
778
- const list = block.expr.evaluate(scope, this.evaluation);
779
- if (isThenable(list))
780
- return list.then((v) => this.toList(v, block.expr));
781
- return this.toList(list, block.expr);
782
- });
783
- const entries = Array.isArray(value) ? value : [];
784
- for (let idx = 0; idx < entries.length; idx++) {
785
- const loopScope = new Scope({
786
- [block.variable]: entries[idx],
787
- [`$${block.variable}`]: entries[idx],
788
- $idx: idx,
789
- }, scope);
790
- yield this.evaluate(block.body, loopScope, emit);
774
+ }
775
+ else {
776
+ const value = await this.value(block.tag, () => {
777
+ const list = block.expr.evaluate(scope, this.evaluation);
778
+ if (isThenable(list))
779
+ return list.then((v) => this.toList(v, block.expr));
780
+ return this.toList(list, block.expr);
781
+ });
782
+ const entries = Array.isArray(value) ? value : [];
783
+ for (let idx = 0; idx < entries.length; idx++) {
784
+ if (++this.loopIterations > MAX_LOOP_ITERATIONS) {
785
+ throw new TemplateRenderError(`More than ${MAX_LOOP_ITERATIONS} FOR iterations ("${block.expr.source}")`);
791
786
  }
787
+ const loopScope = new Scope({
788
+ [block.variable]: entries[idx],
789
+ [`$${block.variable}`]: entries[idx],
790
+ $idx: idx,
791
+ }, scope);
792
+ await this.evaluate(block.body, loopScope, emit);
792
793
  }
793
794
  }
794
- });
795
+ }
795
796
  }
796
797
  toList(value, expr) {
797
798
  if (value === null || value === undefined)
@@ -804,132 +805,128 @@ class TemplateRenderer {
804
805
  /*
805
806
  * Writing text bodies
806
807
  */
807
- writeBody(body, bodyTokens, blocks, scope) {
808
- return __awaiter(this, void 0, void 0, function* () {
809
- var _a;
810
- const sourceParagraphs = this.childElements(body, 'a:p');
811
- const first = sourceParagraphs[0];
812
- if (!first)
813
- return;
814
- // The source paragraph, not its clone in a repeated table row: that is
815
- // the one `controlOnly` knows.
816
- const firstSource = (_a = bodyTokens.first) !== null && _a !== void 0 ? _a : first;
817
- const paragraphs = [{ source: firstSource, nodes: [] }];
818
- const current = () => paragraphs[paragraphs.length - 1];
819
- yield this.evaluate(blocks, scope, (token, tokenScope) => __awaiter(this, void 0, void 0, function* () {
820
- switch (token.kind) {
821
- case 'break':
822
- paragraphs.push({ source: token.paragraph, nodes: [] });
823
- break;
824
- case 'node':
825
- current().nodes.push((0, clone_1.cloneXml)(token.node, true));
826
- break;
827
- case 'text':
828
- current().nodes.push(...this.createRuns(token.run, token.text));
829
- break;
830
- case 'tag':
831
- yield this.emitTag(token, tokenScope, body, paragraphs);
832
- break;
833
- }
834
- }));
835
- let kept = paragraphs.filter((p) => p.raw ||
836
- !(bodyTokens.controlOnly.has(p.source) || p.continuation) ||
837
- p.nodes.some((n) => n.tagName !== 'a:r' || this.runText(n).trim() !== ''));
838
- // A text body needs at least one paragraph.
839
- if (!kept.length)
840
- kept = [{ source: firstSource, nodes: [] }];
841
- sourceParagraphs.forEach((p) => body.removeChild(p));
842
- kept.forEach((p) => { var _a; return body.appendChild((_a = p.raw) !== null && _a !== void 0 ? _a : this.createParagraph(p)); });
808
+ async writeBody(body, bodyTokens, blocks, scope) {
809
+ const sourceParagraphs = this.childElements(body, 'a:p');
810
+ const first = sourceParagraphs[0];
811
+ if (!first)
812
+ return;
813
+ // The source paragraph, not its clone in a repeated table row: that is
814
+ // the one `controlOnly` knows.
815
+ const firstSource = bodyTokens.first ?? first;
816
+ const paragraphs = [{ source: firstSource, nodes: [] }];
817
+ const current = () => paragraphs[paragraphs.length - 1];
818
+ await this.evaluate(blocks, scope, async (token, tokenScope) => {
819
+ switch (token.kind) {
820
+ case 'break':
821
+ paragraphs.push({ source: token.paragraph, nodes: [] });
822
+ break;
823
+ case 'node':
824
+ current().nodes.push((0, clone_1.cloneXml)(token.node, true));
825
+ break;
826
+ case 'text':
827
+ current().nodes.push(...this.createRuns(token.run, token.text));
828
+ break;
829
+ case 'tag':
830
+ await this.emitTag(token, tokenScope, body, paragraphs);
831
+ break;
832
+ }
843
833
  });
834
+ let kept = paragraphs.filter((p) => p.raw ||
835
+ !(bodyTokens.controlOnly.has(p.source) || p.continuation) ||
836
+ p.nodes.some((n) => n.tagName !== 'a:r' || this.runText(n).trim() !== ''));
837
+ // A text body needs at least one paragraph.
838
+ if (!kept.length)
839
+ kept = [{ source: firstSource, nodes: [] }];
840
+ sourceParagraphs.forEach((p) => body.removeChild(p));
841
+ kept.forEach((p) => body.appendChild(p.raw ?? this.createParagraph(p)));
844
842
  }
845
- emitTag(token, scope, body, paragraphs) {
846
- return __awaiter(this, void 0, void 0, function* () {
847
- var _a;
848
- const { directive, tag, run } = token;
849
- const current = paragraphs[paragraphs.length - 1];
850
- const evaluate = (expr) => this.value(tag, () => expr.evaluate(scope, this.evaluation));
851
- switch (directive.type) {
852
- case 'insert': {
853
- const value = yield this.value(tag, () => __awaiter(this, void 0, void 0, function* () {
854
- const result = yield directive.expr.evaluate(scope, this.evaluation);
855
- if (this.options.rejectNullish &&
856
- (result === null || result === undefined)) {
857
- throw new Error(`"${directive.expr.source}" is ${result}`);
858
- }
859
- return result;
860
- }));
861
- current.nodes.push(...this.createRuns(run, this.format(value)));
862
- break;
863
- }
864
- case 'hideslide':
865
- this.warnHideSlide(directive.tag);
843
+ async emitTag(token, scope, body, paragraphs) {
844
+ const { directive, tag, run } = token;
845
+ const current = paragraphs[paragraphs.length - 1];
846
+ const evaluate = (expr) => this.value(tag, () => expr.evaluate(scope, this.evaluation));
847
+ switch (directive.type) {
848
+ case 'insert': {
849
+ const value = await this.value(tag, async () => {
850
+ const result = await directive.expr.evaluate(scope, this.evaluation);
851
+ if (this.options.rejectNullish &&
852
+ (result === null || result === undefined)) {
853
+ throw new Error(`"${directive.expr.source}" is ${result}`);
854
+ }
855
+ return result;
856
+ });
857
+ current.nodes.push(...this.createRuns(run, this.format(value)));
858
+ break;
859
+ }
860
+ case 'hideslide':
861
+ this.warnHideSlide(directive.tag);
862
+ break;
863
+ case 'exec':
864
+ await this.runExec(directive.statements, scope, tag);
865
+ break;
866
+ case 'html': {
867
+ const html = this.format(await evaluate(directive.expr));
868
+ if (!html)
866
869
  break;
867
- case 'exec':
868
- yield this.runExec(directive.statements, scope, tag);
870
+ const generated = this.htmlParagraphs(body, current.source, run, html, await this.relations());
871
+ generated.forEach((raw) => paragraphs.push({ source: current.source, nodes: [], raw }));
872
+ paragraphs.push({
873
+ source: current.source,
874
+ nodes: [],
875
+ continuation: true,
876
+ });
877
+ break;
878
+ }
879
+ case 'link': {
880
+ const value = await evaluate(directive.expr);
881
+ if (value === null || value === undefined || value === '')
869
882
  break;
870
- case 'html': {
871
- const html = this.format(yield evaluate(directive.expr));
872
- if (!html)
873
- break;
874
- const generated = this.htmlParagraphs(body, current.source, run, html, yield this.relations());
875
- generated.forEach((raw) => paragraphs.push({ source: current.source, nodes: [], raw }));
876
- paragraphs.push({
877
- source: current.source,
878
- nodes: [],
879
- continuation: true,
880
- });
883
+ const runs = await this.value(tag, async () => {
884
+ const { link, label } = this.toLink(value);
885
+ const relations = await this.relations();
886
+ if (!relations) {
887
+ throw new Error('LINK needs the slide relationships');
888
+ }
889
+ const relId = this.linkRelation(relations, link);
890
+ const created = this.createRuns(run, label);
891
+ created
892
+ .filter((n) => n.tagName === 'a:r')
893
+ .forEach((r) => this.setHyperlink(r, relId, link.internal));
894
+ return created;
895
+ });
896
+ if (Array.isArray(runs))
897
+ current.nodes.push(...runs);
898
+ break;
899
+ }
900
+ case 'image': {
901
+ const value = await evaluate(directive.expr);
902
+ if (value === null || value === undefined || value === '')
881
903
  break;
882
- }
883
- case 'link': {
884
- const value = yield evaluate(directive.expr);
885
- if (value === null || value === undefined || value === '')
886
- break;
887
- const runs = yield this.value(tag, () => __awaiter(this, void 0, void 0, function* () {
888
- const { link, label } = this.toLink(value);
889
- const relations = yield this.relations();
890
- if (!relations) {
891
- throw new Error('LINK needs the slide relationships');
892
- }
893
- const relId = this.linkRelation(relations, link);
894
- const created = this.createRuns(run, label);
895
- created
896
- .filter((n) => n.tagName === 'a:r')
897
- .forEach((r) => this.setHyperlink(r, relId, link.internal));
898
- return created;
899
- }));
900
- if (Array.isArray(runs))
901
- current.nodes.push(...runs);
904
+ // a measuring copy (flowOverride) never places its pictures
905
+ if (this.flowOverride || this.context.countOnly)
902
906
  break;
903
- }
904
- case 'image': {
905
- const value = yield evaluate(directive.expr);
906
- if (value === null || value === undefined || value === '')
907
- break;
908
- const image = yield this.value(tag, () => __awaiter(this, void 0, void 0, function* () {
909
- if (body.tagName !== 'p:txBody') {
910
- throw new Error('IMAGE is not supported inside table cells');
911
- }
912
- if (!(yield this.imageTarget())) {
913
- throw new Error('IMAGE needs slide.modify(modify.renderTemplate(…)); ' +
914
- 'modifyElement() callbacks cannot add media files');
915
- }
916
- return (0, images_1.loadImage)(value, this.options.imageRoot);
917
- }));
918
- if (!image || typeof image !== 'object' || !('content' in image))
919
- break;
920
- const pending = (_a = this.pendingImages.get(body)) !== null && _a !== void 0 ? _a : [];
921
- pending.push(image);
922
- this.pendingImages.set(body, pending);
907
+ const image = await this.value(tag, async () => {
908
+ if (body.tagName !== 'p:txBody') {
909
+ throw new Error('IMAGE is not supported inside table cells');
910
+ }
911
+ if (!(await this.imageTarget())) {
912
+ throw new Error('IMAGE needs slide.modify(modify.renderTemplate(…)); ' +
913
+ 'modifyElement() callbacks cannot add media files');
914
+ }
915
+ return (0, images_1.loadImage)(value, this.options.imageRoot);
916
+ });
917
+ if (!image || typeof image !== 'object' || !('content' in image))
923
918
  break;
924
- }
919
+ const pending = this.pendingImages.get(body) ?? [];
920
+ pending.push(image);
921
+ this.pendingImages.set(body, pending);
922
+ break;
925
923
  }
926
- });
924
+ }
927
925
  }
928
926
  imageTarget() {
929
- var _a;
930
- (_a = this.imageTargetPromise) !== null && _a !== void 0 ? _a : (this.imageTargetPromise = this.context.images
927
+ this.imageTargetPromise ??= this.context.images
931
928
  ? this.context.images()
932
- : Promise.resolve(undefined));
929
+ : Promise.resolve(undefined);
933
930
  return this.imageTargetPromise;
934
931
  }
935
932
  /**
@@ -946,128 +943,117 @@ class TemplateRenderer {
946
943
  try {
947
944
  return (0, commands_1.parseCommand)((0, commands_1.resolveAlias)(inner, this.aliases, tag), tag).type;
948
945
  }
949
- catch (_a) {
946
+ catch {
950
947
  return undefined;
951
948
  }
952
949
  };
953
- return xml_helper_1.XmlHelper.collectionToArray(element.getElementsByTagName('p:cNvPr')).filter((cNvPr) => {
954
- var _a;
955
- return (0, commands_1.isAltTextTemplate)((_a = cNvPr.getAttribute('descr')) !== null && _a !== void 0 ? _a : '', this.tagPattern, commandType);
956
- });
950
+ return (0, xml_find_1.elementsByTagName)(element, 'p:cNvPr').filter((cNvPr) => (0, commands_1.isAltTextTemplate)(cNvPr.getAttribute('descr') ?? '', this.tagPattern, commandType));
957
951
  }
958
- renderAltTexts(holders) {
959
- return __awaiter(this, void 0, void 0, function* () {
960
- var _a, _b, _c;
961
- for (const cNvPr of holders) {
962
- const descr = cNvPr.getAttribute('descr');
963
- const shape = (_a = cNvPr.parentNode) === null || _a === void 0 ? void 0 : _a.parentNode;
964
- const matches = [...descr.matchAll(this.tagPattern)];
965
- const first = matches[0][0];
966
- let blocks;
967
- // The tag never reaches the output, also not after an error
968
- // (errorHandler, continueOnError)
969
- cNvPr.removeAttribute('descr');
970
- try {
971
- const tags = matches.map((match) => {
972
- const directive = this.parseDirective(match[1], match[0]);
973
- if (!ALT_TEXT_TYPES.includes(directive.type)) {
974
- throw this.tagged(new Error('only IMAGE, IF, ELSE-IF, ELSE, FOR and EXEC work in alt text'), match[0]);
975
- }
976
- return { tag: match[0], directive };
977
- });
978
- blocks = this.parse(tags, (tag) => tag);
979
- }
980
- catch (error) {
981
- yield this.fail(first, error);
982
- continue;
983
- }
984
- const images = [];
985
- const saved = { body: this.currentBody, altText: this.inAltText };
986
- this.currentBody = (_b = this.textFlow) === null || _b === void 0 ? void 0 : _b.boxOfCard(shape);
987
- this.inAltText = true;
988
- try {
989
- yield this.evaluate(blocks, this.root, (_a, scope_1) => __awaiter(this, [_a, scope_1], void 0, function* ({ tag, directive }, scope) {
990
- if (directive.type === 'exec') {
991
- yield this.runExec(directive.statements, scope, tag);
992
- }
993
- else if (directive.type === 'image') {
994
- const value = yield this.value(tag, () => directive.expr.evaluate(scope, this.evaluation));
995
- if (value !== null && value !== undefined && value !== '') {
996
- images.push({ tag, value });
997
- }
998
- }
999
- }));
1000
- }
1001
- finally {
1002
- this.currentBody = saved.body;
1003
- this.inAltText = saved.altText;
1004
- }
1005
- if (!images.length)
1006
- continue;
1007
- const { tag, value } = images[0];
1008
- if (images.length > 1) {
1009
- const error = new Error(`the alt text yields ${images.length} pictures; a shape holds one`);
1010
- yield this.fail(images[1].tag, error);
1011
- continue;
1012
- }
1013
- const image = yield this.value(tag, () => __awaiter(this, void 0, void 0, function* () {
1014
- if (!(yield this.imageTarget())) {
1015
- throw new Error('IMAGE needs slide.modify(modify.renderTemplate(…)); ' +
1016
- 'modifyElement() callbacks cannot add media files');
952
+ async renderAltTexts(holders) {
953
+ for (const cNvPr of holders) {
954
+ const descr = cNvPr.getAttribute('descr');
955
+ const shape = cNvPr.parentNode?.parentNode;
956
+ const matches = [...descr.matchAll(this.tagPattern)];
957
+ const first = matches[0][0];
958
+ let blocks;
959
+ // The tag never reaches the output, also not after an error
960
+ // (errorHandler, continueOnError)
961
+ cNvPr.removeAttribute('descr');
962
+ try {
963
+ const tags = matches.map((match) => {
964
+ const directive = this.parseDirective(match[1], match[0]);
965
+ if (!ALT_TEXT_TYPES.includes(directive.type)) {
966
+ throw this.tagged(new Error('only IMAGE, IF, ELSE-IF, ELSE, FOR and EXEC work in alt text'), match[0]);
1017
967
  }
1018
- return (0, images_1.loadImage)(value, this.options.imageRoot);
1019
- }));
1020
- if (!image || typeof image !== 'object' || !('content' in image))
1021
- continue;
1022
- const loaded = image;
1023
- try {
1024
- const holder = yield (0, images_1.fillWithImage)(yield this.imageTarget(), shape, loaded);
1025
- if (loaded.spec.alt) {
1026
- (_c = holder
1027
- .getElementsByTagName('p:cNvPr')[0]) === null || _c === void 0 ? void 0 : _c.setAttribute('descr', loaded.spec.alt);
968
+ return { tag: match[0], directive };
969
+ });
970
+ blocks = this.parse(tags, (tag) => tag);
971
+ }
972
+ catch (error) {
973
+ await this.fail(first, error);
974
+ continue;
975
+ }
976
+ const images = [];
977
+ const saved = { body: this.currentBody, altText: this.inAltText };
978
+ this.currentBody = this.textFlow?.boxOfCard(shape);
979
+ this.inAltText = true;
980
+ try {
981
+ await this.evaluate(blocks, this.root, async ({ tag, directive }, scope) => {
982
+ if (directive.type === 'exec') {
983
+ await this.runExec(directive.statements, scope, tag);
984
+ }
985
+ else if (directive.type === 'image') {
986
+ const value = await this.value(tag, () => directive.expr.evaluate(scope, this.evaluation));
987
+ if (value !== null && value !== undefined && value !== '') {
988
+ images.push({ tag, value });
989
+ }
1028
990
  }
991
+ });
992
+ }
993
+ finally {
994
+ this.currentBody = saved.body;
995
+ this.inAltText = saved.altText;
996
+ }
997
+ if (!images.length || this.context.countOnly)
998
+ continue;
999
+ const { tag, value } = images[0];
1000
+ if (images.length > 1) {
1001
+ const error = new Error(`the alt text yields ${images.length} pictures; a shape holds one`);
1002
+ await this.fail(images[1].tag, error);
1003
+ continue;
1004
+ }
1005
+ const image = await this.value(tag, async () => {
1006
+ if (!(await this.imageTarget())) {
1007
+ throw new Error('IMAGE needs slide.modify(modify.renderTemplate(…)); ' +
1008
+ 'modifyElement() callbacks cannot add media files');
1029
1009
  }
1030
- catch (error) {
1031
- yield this.fail(tag, error);
1010
+ return (0, images_1.loadImage)(value, this.options.imageRoot);
1011
+ });
1012
+ if (!image || typeof image !== 'object' || !('content' in image))
1013
+ continue;
1014
+ const loaded = image;
1015
+ try {
1016
+ const holder = await (0, images_1.fillWithImage)(await this.imageTarget(), shape, loaded);
1017
+ if (loaded.spec.alt) {
1018
+ holder
1019
+ .getElementsByTagName('p:cNvPr')[0]
1020
+ ?.setAttribute('descr', xml_helper_1.XmlHelper.sanitizeAttr(loaded.spec.alt));
1032
1021
  }
1033
1022
  }
1034
- });
1023
+ catch (error) {
1024
+ await this.fail(tag, error);
1025
+ }
1026
+ }
1035
1027
  }
1036
1028
  /** An error at `tag`, handled as in value(): errorHandler, collected or thrown. */
1037
- fail(tag, error) {
1038
- return __awaiter(this, void 0, void 0, function* () {
1039
- yield this.value(tag, () => {
1040
- throw error;
1041
- });
1029
+ async fail(tag, error) {
1030
+ await this.value(tag, () => {
1031
+ throw error;
1042
1032
  });
1043
1033
  }
1044
- runExec(statements, scope, tag) {
1045
- return __awaiter(this, void 0, void 0, function* () {
1046
- for (const statement of statements) {
1047
- const value = yield this.value(tag, () => statement.expr.evaluate(scope, this.evaluation));
1048
- if (statement.assign)
1049
- scope.assign(statement.assign, value);
1050
- }
1051
- });
1034
+ async runExec(statements, scope, tag) {
1035
+ for (const statement of statements) {
1036
+ const value = await this.value(tag, () => statement.expr.evaluate(scope, this.evaluation));
1037
+ if (statement.assign)
1038
+ scope.assign(statement.assign, value);
1039
+ }
1052
1040
  }
1053
1041
  /** Pictures go where the shape is; a shape left without text is removed. */
1054
- placePendingImages(body) {
1055
- return __awaiter(this, void 0, void 0, function* () {
1056
- const images = this.pendingImages.get(body);
1057
- if (!(images === null || images === void 0 ? void 0 : images.length))
1058
- return;
1059
- this.pendingImages.delete(body);
1060
- const shape = body.parentNode;
1061
- const text = xml_helper_1.XmlHelper.collectionToArray(body.getElementsByTagName('a:t'))
1062
- .map((t) => t.textContent)
1063
- .join('');
1064
- try {
1065
- yield (0, images_1.placeImages)(yield this.imageTarget(), shape, images, text.trim() === '');
1066
- }
1067
- catch (error) {
1068
- throw this.tagged(error, 'IMAGE');
1069
- }
1070
- });
1042
+ async placePendingImages(body) {
1043
+ const images = this.pendingImages.get(body);
1044
+ if (!images?.length)
1045
+ return;
1046
+ this.pendingImages.delete(body);
1047
+ const shape = body.parentNode;
1048
+ const text = (0, xml_find_1.elementsByTagName)(body, 'a:t')
1049
+ .map((t) => t.textContent)
1050
+ .join('');
1051
+ try {
1052
+ await (0, images_1.placeImages)(await this.imageTarget(), shape, images, text.trim() === '');
1053
+ }
1054
+ catch (error) {
1055
+ throw this.tagged(error, 'IMAGE');
1056
+ }
1071
1057
  }
1072
1058
  createParagraph(output) {
1073
1059
  const paragraph = (0, clone_1.cloneXml)(output.source, false);
@@ -1099,10 +1085,26 @@ class TemplateRenderer {
1099
1085
  }
1100
1086
  if (line === '')
1101
1087
  return;
1102
- const run = (0, clone_1.cloneXml)(template, true);
1103
- const t = run.getElementsByTagName('a:t')[0];
1104
- while (t.firstChild)
1105
- t.removeChild(t.firstChild);
1088
+ // the template's own text is not copied: <a:t> gets the new text
1089
+ const run = (0, clone_1.cloneXml)(template, false);
1090
+ let t;
1091
+ for (let child = template.firstChild; child; child = child.nextSibling) {
1092
+ const isText = !t && child.nodeType === 1 && child.tagName === 'a:t';
1093
+ const copy = (0, clone_1.cloneXml)(child, !isText);
1094
+ if (isText)
1095
+ t = copy;
1096
+ run.appendChild(copy);
1097
+ }
1098
+ if (!t) {
1099
+ // no <a:t> of its own: as before (a nested one, or the error)
1100
+ const copy = (0, clone_1.cloneXml)(template, true);
1101
+ t = copy.getElementsByTagName('a:t')[0];
1102
+ while (t.firstChild)
1103
+ t.removeChild(t.firstChild);
1104
+ t.appendChild(doc.createTextNode(xml_helper_1.XmlHelper.sanitizeText(line)));
1105
+ nodes.push(copy);
1106
+ return;
1107
+ }
1106
1108
  t.appendChild(doc.createTextNode(xml_helper_1.XmlHelper.sanitizeText(line)));
1107
1109
  nodes.push(run);
1108
1110
  });
@@ -1119,10 +1121,9 @@ class TemplateRenderer {
1119
1121
  * HTML and hyperlinks
1120
1122
  */
1121
1123
  relations() {
1122
- var _a;
1123
- (_a = this.relationsPromise) !== null && _a !== void 0 ? _a : (this.relationsPromise = this.context.relations
1124
+ this.relationsPromise ??= this.context.relations
1124
1125
  ? this.context.relations()
1125
- : Promise.resolve(undefined));
1126
+ : Promise.resolve(undefined);
1126
1127
  return this.relationsPromise;
1127
1128
  }
1128
1129
  /**
@@ -1142,12 +1143,11 @@ class TemplateRenderer {
1142
1143
  const document = /<body[\s>]/i.test(html)
1143
1144
  ? html
1144
1145
  : `<html><body>${html}</body></html>`;
1145
- new multitext_helper_1.MultiTextHelper(host, relations).run(new html_to_multitext_helper_1.HtmlToMultiTextHelper().run(document));
1146
+ (0, link_scheme_1.runWithLinkSchemes)(this.options.allowedLinkSchemes, () => new multitext_helper_1.MultiTextHelper(host, relations).run(new html_to_multitext_helper_1.HtmlToMultiTextHelper().run(document)));
1146
1147
  return this.childElements(scratch, 'a:p');
1147
1148
  }
1148
1149
  toLink(value) {
1149
- var _a;
1150
- const spec = typeof value === 'object'
1150
+ const spec = value !== null && typeof value === 'object'
1151
1151
  ? value
1152
1152
  : { url: value };
1153
1153
  const url = spec.url;
@@ -1155,8 +1155,13 @@ class TemplateRenderer {
1155
1155
  throw new Error('LINK needs a url, e.g. {{LINK ({ url, label })}}');
1156
1156
  }
1157
1157
  const internal = typeof url === 'number';
1158
+ if (internal && !(Number.isInteger(url) && url >= 1)) {
1159
+ throw new Error(`LINK to slide ${url}: a slide number is a whole number from 1`);
1160
+ }
1161
+ if (!internal)
1162
+ (0, link_scheme_1.assertLinkScheme)(String(url), this.options.allowedLinkSchemes);
1158
1163
  const target = internal ? `../slides/slide${url}.xml` : String(url);
1159
- const label = this.format((_a = spec.label) !== null && _a !== void 0 ? _a : url);
1164
+ const label = this.format(spec.label ?? url);
1160
1165
  return { link: { target, internal }, label };
1161
1166
  }
1162
1167
  linkRelation(relations, link) {
@@ -1171,7 +1176,7 @@ class TemplateRenderer {
1171
1176
  const rel = root.ownerDocument.createElement('Relationship');
1172
1177
  rel.setAttribute('Id', id);
1173
1178
  rel.setAttribute('Type', link.internal ? REL_TYPE_SLIDE : REL_TYPE_HYPERLINK);
1174
- rel.setAttribute('Target', link.target);
1179
+ rel.setAttribute('Target', xml_helper_1.XmlHelper.sanitizeAttr(link.target));
1175
1180
  if (!link.internal)
1176
1181
  rel.setAttribute('TargetMode', 'External');
1177
1182
  root.appendChild(rel);
@@ -1196,74 +1201,72 @@ class TemplateRenderer {
1196
1201
  /*
1197
1202
  * Tables: blocks left open inside a cell span (and repeat) table rows.
1198
1203
  */
1199
- renderTable(table) {
1200
- return __awaiter(this, void 0, void 0, function* () {
1201
- if (!this.containsTag(table))
1202
- return;
1203
- const rows = this.childElements(table, 'a:tr');
1204
- const rowTokens = [];
1205
- rows.forEach((row) => {
1206
- const openers = [];
1207
- // Closers before the row's first opener end a block from an earlier
1208
- // row; they must not close the block this row opens.
1209
- const leading = [];
1210
- const closers = [];
1211
- let hasContent = false;
1212
- const cells = this.childElements(row, 'a:tc').map((cell) => {
1213
- const body = this.childElements(cell, 'a:txBody')[0];
1214
- if (!body)
1215
- return undefined;
1216
- const bodyTokens = this.tokenizeBody(body);
1217
- const rowLevel = this.extractRowLevelTags(bodyTokens.tokens);
1218
- rowLevel.closers.forEach((t) => (openers.length ? closers : leading).push({
1219
- tag: t.tag,
1220
- directive: t.directive,
1221
- }));
1222
- rowLevel.openers.forEach((t) => openers.push({ tag: t.tag, directive: t.directive }));
1223
- const extracted = new Set([
1224
- ...rowLevel.openers,
1225
- ...rowLevel.closers,
1226
- ]);
1227
- bodyTokens.tokens = bodyTokens.tokens.filter((t) => !extracted.has(t));
1228
- hasContent =
1229
- hasContent ||
1230
- bodyTokens.tokens.some((t) => (t.kind === 'tag' && CONTENT_TYPES.includes(t.directive.type)) ||
1231
- (t.kind === 'text' && t.text.trim() !== '') ||
1232
- (t.kind === 'node' && t.node.tagName === 'a:fld'));
1233
- return bodyTokens;
1234
- });
1235
- // Without an opener, all closers end blocks this row still belongs to
1236
- if (!openers.length)
1237
- closers.push(...leading.splice(0));
1238
- const isControlRow = !hasContent && (openers.length || closers.length);
1239
- rowTokens.push(...leading, ...openers);
1240
- if (!isControlRow)
1241
- rowTokens.push({ row, cells });
1242
- rowTokens.push(...closers);
1243
- });
1244
- const output = [];
1245
- yield this.evaluate(this.parse(rowTokens, (t) => t.directive ? { tag: t.tag, directive: t.directive } : undefined), this.root, (token, scope) => __awaiter(this, void 0, void 0, function* () {
1246
- const row = (0, clone_1.cloneXml)(token.row, true);
1247
- const cells = this.childElements(row, 'a:tc');
1248
- for (let c = 0; c < cells.length; c++) {
1249
- const bodyTokens = token.cells[c];
1250
- const body = this.childElements(cells[c], 'a:txBody')[0];
1251
- if (!bodyTokens || !body)
1252
- continue;
1253
- yield this.writeBody(body, bodyTokens, this.parse(bodyTokens.tokens, textControl), scope);
1254
- }
1255
- output.push(row);
1256
- }));
1257
- const anchor = rows[rows.length - 1].nextSibling;
1258
- rows.forEach((row) => table.removeChild(row));
1259
- output.forEach((row, r) => {
1260
- table.insertBefore(row, anchor);
1261
- const rowId = row.getElementsByTagName('a16:rowId')[0];
1262
- if (rowId)
1263
- rowId.setAttribute('val', String(10000 + r));
1204
+ async renderTable(table) {
1205
+ if (!this.containsTag(table))
1206
+ return;
1207
+ const rows = this.childElements(table, 'a:tr');
1208
+ const rowTokens = [];
1209
+ rows.forEach((row) => {
1210
+ const openers = [];
1211
+ // Closers before the row's first opener end a block from an earlier
1212
+ // row; they must not close the block this row opens.
1213
+ const leading = [];
1214
+ const closers = [];
1215
+ let hasContent = false;
1216
+ const cells = this.childElements(row, 'a:tc').map((cell) => {
1217
+ const body = this.childElements(cell, 'a:txBody')[0];
1218
+ if (!body)
1219
+ return undefined;
1220
+ const bodyTokens = this.tokenizeBody(body);
1221
+ const rowLevel = this.extractRowLevelTags(bodyTokens.tokens);
1222
+ rowLevel.closers.forEach((t) => (openers.length ? closers : leading).push({
1223
+ tag: t.tag,
1224
+ directive: t.directive,
1225
+ }));
1226
+ rowLevel.openers.forEach((t) => openers.push({ tag: t.tag, directive: t.directive }));
1227
+ const extracted = new Set([
1228
+ ...rowLevel.openers,
1229
+ ...rowLevel.closers,
1230
+ ]);
1231
+ bodyTokens.tokens = bodyTokens.tokens.filter((t) => !extracted.has(t));
1232
+ hasContent =
1233
+ hasContent ||
1234
+ bodyTokens.tokens.some((t) => (t.kind === 'tag' && CONTENT_TYPES.includes(t.directive.type)) ||
1235
+ (t.kind === 'text' && t.text.trim() !== '') ||
1236
+ (t.kind === 'node' && t.node.tagName === 'a:fld'));
1237
+ return bodyTokens;
1264
1238
  });
1265
- this.updateFrameHeight(table, output);
1239
+ // Without an opener, all closers end blocks this row still belongs to
1240
+ if (!openers.length)
1241
+ closers.push(...leading.splice(0));
1242
+ const isControlRow = !hasContent && (openers.length || closers.length);
1243
+ rowTokens.push(...leading, ...openers);
1244
+ if (!isControlRow)
1245
+ rowTokens.push({ row, cells });
1246
+ rowTokens.push(...closers);
1247
+ });
1248
+ const output = [];
1249
+ await this.evaluate(this.parse(rowTokens, (t) => t.directive ? { tag: t.tag, directive: t.directive } : undefined), this.root, async (token, scope) => {
1250
+ const row = (0, clone_1.cloneXml)(token.row, true);
1251
+ const cells = this.childElements(row, 'a:tc');
1252
+ for (let c = 0; c < cells.length; c++) {
1253
+ const bodyTokens = token.cells[c];
1254
+ const body = this.childElements(cells[c], 'a:txBody')[0];
1255
+ if (!bodyTokens || !body)
1256
+ continue;
1257
+ await this.writeBody(body, bodyTokens, this.parse(bodyTokens.tokens, textControl), scope);
1258
+ }
1259
+ output.push(row);
1260
+ });
1261
+ const anchor = rows[rows.length - 1].nextSibling;
1262
+ rows.forEach((row) => table.removeChild(row));
1263
+ output.forEach((row, r) => {
1264
+ table.insertBefore(row, anchor);
1265
+ const rowId = row.getElementsByTagName('a16:rowId')[0];
1266
+ if (rowId)
1267
+ rowId.setAttribute('val', String(10000 + r));
1266
1268
  });
1269
+ this.updateFrameHeight(table, output);
1267
1270
  }
1268
1271
  /** Block tags that are not closed (or opened) within the same cell. */
1269
1272
  extractRowLevelTags(tokens) {
@@ -1289,12 +1292,13 @@ class TemplateRenderer {
1289
1292
  return { openers: stack, closers };
1290
1293
  }
1291
1294
  updateFrameHeight(table, rows) {
1292
- var _a;
1293
1295
  let frame = table.parentNode;
1294
1296
  while (frame && frame.tagName !== 'p:graphicFrame') {
1295
1297
  frame = frame.parentNode;
1296
1298
  }
1297
- const ext = (_a = frame === null || frame === void 0 ? void 0 : frame.getElementsByTagName('p:xfrm')[0]) === null || _a === void 0 ? void 0 : _a.getElementsByTagName('a:ext')[0];
1299
+ const ext = frame
1300
+ ?.getElementsByTagName('p:xfrm')[0]
1301
+ ?.getElementsByTagName('a:ext')[0];
1298
1302
  if (!ext)
1299
1303
  return;
1300
1304
  const height = rows.reduce((sum, row) => sum + Number(row.getAttribute('h') || 0), 0);
@@ -1316,8 +1320,7 @@ class TemplateRenderer {
1316
1320
  return children;
1317
1321
  }
1318
1322
  runText(run) {
1319
- var _a, _b;
1320
- return (_b = (_a = run.getElementsByTagName('a:t')[0]) === null || _a === void 0 ? void 0 : _a.textContent) !== null && _b !== void 0 ? _b : '';
1323
+ return (0, xml_find_1.firstElementByTagName)(run, 'a:t')?.textContent ?? '';
1321
1324
  }
1322
1325
  }
1323
1326
  exports.TemplateRenderer = TemplateRenderer;