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