pptx-templates 0.3.8 → 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 (224) hide show
  1. package/AI-INSTRUCTOR.md +91 -2
  2. package/CHANGELOG.md +125 -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.d.ts +2 -0
  45. package/dist/extensions/shape-geometry/index.js +13 -13
  46. package/dist/extensions/shape-geometry/index.js.map +1 -1
  47. package/dist/extensions/template-lint/cli.js +49 -41
  48. package/dist/extensions/template-lint/cli.js.map +1 -1
  49. package/dist/extensions/template-lint/config.js +18 -10
  50. package/dist/extensions/template-lint/config.js.map +1 -1
  51. package/dist/extensions/template-lint/data-model.js +17 -20
  52. package/dist/extensions/template-lint/data-model.js.map +1 -1
  53. package/dist/extensions/template-lint/init-cli.js +12 -17
  54. package/dist/extensions/template-lint/init-cli.js.map +1 -1
  55. package/dist/extensions/template-lint/lint.js +195 -62
  56. package/dist/extensions/template-lint/lint.js.map +1 -1
  57. package/dist/extensions/template-lint/skeleton.js +5 -6
  58. package/dist/extensions/template-lint/skeleton.js.map +1 -1
  59. package/dist/extensions/template-lint/usage-cli.js +10 -14
  60. package/dist/extensions/template-lint/usage-cli.js.map +1 -1
  61. package/dist/extensions/template-lint/usage.js +8 -9
  62. package/dist/extensions/template-lint/usage.js.map +1 -1
  63. package/dist/extensions/template-logic/clone.d.ts +2 -16
  64. package/dist/extensions/template-logic/clone.js +15 -90
  65. package/dist/extensions/template-logic/clone.js.map +1 -1
  66. package/dist/extensions/template-logic/commands.d.ts +8 -0
  67. package/dist/extensions/template-logic/commands.js +21 -12
  68. package/dist/extensions/template-logic/commands.js.map +1 -1
  69. package/dist/extensions/template-logic/expression.d.ts +6 -0
  70. package/dist/extensions/template-logic/expression.js +56 -54
  71. package/dist/extensions/template-logic/expression.js.map +1 -1
  72. package/dist/extensions/template-logic/images.d.ts +14 -0
  73. package/dist/extensions/template-logic/images.js +277 -49
  74. package/dist/extensions/template-logic/images.js.map +1 -1
  75. package/dist/extensions/template-logic/index.js +20 -27
  76. package/dist/extensions/template-logic/index.js.map +1 -1
  77. package/dist/extensions/template-logic/list-commands.js +31 -16
  78. package/dist/extensions/template-logic/list-commands.js.map +1 -1
  79. package/dist/extensions/template-logic/renderer.d.ts +24 -0
  80. package/dist/extensions/template-logic/renderer.js +505 -380
  81. package/dist/extensions/template-logic/renderer.js.map +1 -1
  82. package/dist/extensions/template-logic/types.d.ts +5 -0
  83. package/dist/extensions/template-logic/types.js +6 -0
  84. package/dist/extensions/template-logic/types.js.map +1 -1
  85. package/dist/extensions/template-render/cli.js +7 -18
  86. package/dist/extensions/template-render/cli.js.map +1 -1
  87. package/dist/extensions/template-render/index.js +152 -107
  88. package/dist/extensions/template-render/index.js.map +1 -1
  89. package/dist/extensions/template-render/prune.d.ts +14 -0
  90. package/dist/extensions/template-render/prune.js +131 -0
  91. package/dist/extensions/template-render/prune.js.map +1 -0
  92. package/dist/extensions/template-render/zip-text.d.ts +9 -0
  93. package/dist/extensions/template-render/zip-text.js +27 -0
  94. package/dist/extensions/template-render/zip-text.js.map +1 -0
  95. package/dist/extensions/template-render/zip-writer.d.ts +16 -0
  96. package/dist/extensions/template-render/zip-writer.js +151 -0
  97. package/dist/extensions/template-render/zip-writer.js.map +1 -0
  98. package/dist/extensions/text-flow/flow.d.ts +5 -0
  99. package/dist/extensions/text-flow/flow.js +196 -207
  100. package/dist/extensions/text-flow/flow.js.map +1 -1
  101. package/dist/extensions/text-flow/font-file.js +9 -7
  102. package/dist/extensions/text-flow/font-file.js.map +1 -1
  103. package/dist/extensions/text-flow/fonts.d.ts +4 -0
  104. package/dist/extensions/text-flow/fonts.js +45 -22
  105. package/dist/extensions/text-flow/fonts.js.map +1 -1
  106. package/dist/extensions/text-flow/layout.js +5 -6
  107. package/dist/extensions/text-flow/layout.js.map +1 -1
  108. package/dist/extensions/text-flow/slide-styles.js +18 -22
  109. package/dist/extensions/text-flow/slide-styles.js.map +1 -1
  110. package/dist/extensions/text-flow/styles.d.ts +11 -0
  111. package/dist/extensions/text-flow/styles.js +121 -62
  112. package/dist/extensions/text-flow/styles.js.map +1 -1
  113. package/dist/helper/archive/archive-fs.js +102 -138
  114. package/dist/helper/archive/archive-fs.js.map +1 -1
  115. package/dist/helper/archive/archive-jszip.js +101 -125
  116. package/dist/helper/archive/archive-jszip.js.map +1 -1
  117. package/dist/helper/archive/archive.d.ts +6 -0
  118. package/dist/helper/archive/archive.js +21 -30
  119. package/dist/helper/archive/archive.js.map +1 -1
  120. package/dist/helper/archive/jszip-fast-read.d.ts +19 -0
  121. package/dist/helper/archive/jszip-fast-read.js +153 -0
  122. package/dist/helper/archive/jszip-fast-read.js.map +1 -0
  123. package/dist/helper/compute-src-rect.js +4 -5
  124. package/dist/helper/compute-src-rect.js.map +1 -1
  125. package/dist/helper/content-tracker.js +86 -114
  126. package/dist/helper/content-tracker.js.map +1 -1
  127. package/dist/helper/count-helper.js +48 -78
  128. package/dist/helper/count-helper.js.map +1 -1
  129. package/dist/helper/css-style-parser.js +1 -2
  130. package/dist/helper/css-style-parser.js.map +1 -1
  131. package/dist/helper/file-helper.js +30 -48
  132. package/dist/helper/file-helper.js.map +1 -1
  133. package/dist/helper/generate/generate-pptxgenjs.js +36 -48
  134. package/dist/helper/generate/generate-pptxgenjs.js.map +1 -1
  135. package/dist/helper/html-to-multitext-helper.js +34 -18
  136. package/dist/helper/html-to-multitext-helper.js.map +1 -1
  137. package/dist/helper/hyperlink-processor.js +125 -139
  138. package/dist/helper/hyperlink-processor.js.map +1 -1
  139. package/dist/helper/jszip-helper.js +23 -32
  140. package/dist/helper/jszip-helper.js.map +1 -1
  141. package/dist/helper/layout-index.js +51 -71
  142. package/dist/helper/layout-index.js.map +1 -1
  143. package/dist/helper/logger.js +4 -4
  144. package/dist/helper/logger.js.map +1 -1
  145. package/dist/helper/media-deduplicator.d.ts +24 -0
  146. package/dist/helper/media-deduplicator.js +81 -34
  147. package/dist/helper/media-deduplicator.js.map +1 -1
  148. package/dist/helper/modify-background-helper.js +46 -46
  149. package/dist/helper/modify-background-helper.js.map +1 -1
  150. package/dist/helper/modify-chart-helper.js +597 -591
  151. package/dist/helper/modify-chart-helper.js.map +1 -1
  152. package/dist/helper/modify-cleanup-helper.js +112 -112
  153. package/dist/helper/modify-cleanup-helper.js.map +1 -1
  154. package/dist/helper/modify-color-helper.js +53 -53
  155. package/dist/helper/modify-color-helper.js.map +1 -1
  156. package/dist/helper/modify-helper.js +25 -25
  157. package/dist/helper/modify-helper.js.map +1 -1
  158. package/dist/helper/modify-hyperlink-helper.js +143 -154
  159. package/dist/helper/modify-hyperlink-helper.js.map +1 -1
  160. package/dist/helper/modify-image-helper.js +121 -132
  161. package/dist/helper/modify-image-helper.js.map +1 -1
  162. package/dist/helper/modify-presentation-helper.js +137 -154
  163. package/dist/helper/modify-presentation-helper.js.map +1 -1
  164. package/dist/helper/modify-shape-helper.js +262 -262
  165. package/dist/helper/modify-shape-helper.js.map +1 -1
  166. package/dist/helper/modify-table-helper.js +84 -84
  167. package/dist/helper/modify-table-helper.js.map +1 -1
  168. package/dist/helper/modify-text-helper.js +187 -189
  169. package/dist/helper/modify-text-helper.js.map +1 -1
  170. package/dist/helper/modify-xml-helper.js +36 -36
  171. package/dist/helper/modify-xml-helper.js.map +1 -1
  172. package/dist/helper/multitext-helper.js +9 -7
  173. package/dist/helper/multitext-helper.js.map +1 -1
  174. package/dist/helper/ppt-paths.js +17 -17
  175. package/dist/helper/ppt-paths.js.map +1 -1
  176. package/dist/helper/shape-type-detector.js +18 -29
  177. package/dist/helper/shape-type-detector.js.map +1 -1
  178. package/dist/helper/text-replace-helper.js +6 -7
  179. package/dist/helper/text-replace-helper.js.map +1 -1
  180. package/dist/helper/xml-clone.d.ts +24 -0
  181. package/dist/helper/xml-clone.js +269 -0
  182. package/dist/helper/xml-clone.js.map +1 -0
  183. package/dist/helper/xml-elements.js +17 -20
  184. package/dist/helper/xml-elements.js.map +1 -1
  185. package/dist/helper/xml-find.d.ts +4 -0
  186. package/dist/helper/xml-find.js +48 -0
  187. package/dist/helper/xml-find.js.map +1 -0
  188. package/dist/helper/xml-helper.js +99 -134
  189. package/dist/helper/xml-helper.js.map +1 -1
  190. package/dist/helper/xml-parse-cache.d.ts +31 -0
  191. package/dist/helper/xml-parse-cache.js +71 -0
  192. package/dist/helper/xml-parse-cache.js.map +1 -0
  193. package/dist/helper/xml-placeholder-helper.js +10 -10
  194. package/dist/helper/xml-placeholder-helper.js.map +1 -1
  195. package/dist/helper/xml-relationship-helper.js +120 -144
  196. package/dist/helper/xml-relationship-helper.js.map +1 -1
  197. package/dist/helper/xml-serializer.d.ts +2 -0
  198. package/dist/helper/xml-serializer.js +192 -0
  199. package/dist/helper/xml-serializer.js.map +1 -0
  200. package/dist/helper/xml-slide-helper.js +109 -129
  201. package/dist/helper/xml-slide-helper.js.map +1 -1
  202. package/dist/helper/xml-template-helper.js +120 -144
  203. package/dist/helper/xml-template-helper.js.map +1 -1
  204. package/dist/helper/xmldom-sax-patch.js +52 -2
  205. package/dist/helper/xmldom-sax-patch.js.map +1 -1
  206. package/dist/index.js +4 -2
  207. package/dist/index.js.map +1 -1
  208. package/dist/modify/modify-chart.js +35 -23
  209. package/dist/modify/modify-chart.js.map +1 -1
  210. package/dist/modify/modify-table.js +11 -14
  211. package/dist/modify/modify-table.js.map +1 -1
  212. package/dist/shapes/chart.js +238 -287
  213. package/dist/shapes/chart.js.map +1 -1
  214. package/dist/shapes/diagram.js +73 -104
  215. package/dist/shapes/diagram.js.map +1 -1
  216. package/dist/shapes/generic.js +62 -83
  217. package/dist/shapes/generic.js.map +1 -1
  218. package/dist/shapes/hyperlink.js +98 -124
  219. package/dist/shapes/hyperlink.js.map +1 -1
  220. package/dist/shapes/image.js +112 -151
  221. package/dist/shapes/image.js.map +1 -1
  222. package/dist/shapes/ole.js +148 -188
  223. package/dist/shapes/ole.js.map +1 -1
  224. 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");
@@ -39,6 +31,8 @@ const STRUCTURAL_TYPES = [
39
31
  'html',
40
32
  'image',
41
33
  ];
34
+ /** Tags that work in alt text (renderAltTexts). */
35
+ const ALT_TEXT_TYPES = [...BLOCK_TYPES, 'exec', 'image'];
42
36
  /** Tags that produce visible content (keep a table row). */
43
37
  const CONTENT_TYPES = ['insert', 'html', 'link'];
44
38
  /** Children of <a:rPr>, schema order (CT_TextCharacterProperties). */
@@ -69,6 +63,14 @@ const RPR_CHILD_ORDER = [
69
63
  const REL_TYPE_HYPERLINK = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink';
70
64
  const REL_TYPE_SLIDE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide';
71
65
  const textControl = (token) => token.kind === 'tag' ? token : undefined;
66
+ /** `node` is still in `root` (not removed while rendering). */
67
+ const isWithin = (node, root) => {
68
+ for (let n = node; n; n = n.parentNode) {
69
+ if (n === root)
70
+ return true;
71
+ }
72
+ return false;
73
+ };
72
74
  const isThenable = (value) => !!value && typeof value.then === 'function';
73
75
  class Scope {
74
76
  constructor(vars, parent, writable = true) {
@@ -92,20 +94,19 @@ class Scope {
92
94
  }
93
95
  /** Own variables, to undo the EXECs of a trial render. */
94
96
  snapshot() {
95
- return Object.assign({}, this.vars);
97
+ return { ...this.vars };
96
98
  }
97
99
  restore(snapshot) {
98
100
  Object.keys(this.vars).forEach((key) => delete this.vars[key]);
99
101
  Object.assign(this.vars, snapshot);
100
102
  }
101
103
  assignExisting(name, value) {
102
- var _a, _b;
103
104
  if (this.writable &&
104
105
  Object.prototype.hasOwnProperty.call(this.vars, name)) {
105
106
  this.vars[name] = value;
106
107
  return true;
107
108
  }
108
- 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;
109
110
  }
110
111
  }
111
112
  class TemplateRenderError extends Error {
@@ -117,7 +118,6 @@ class TemplateRenderError extends Error {
117
118
  exports.TemplateRenderError = TemplateRenderError;
118
119
  class TemplateRenderer {
119
120
  constructor(data, options = {}, context = {}) {
120
- var _a, _b, _c, _d;
121
121
  this.options = options;
122
122
  this.context = context;
123
123
  this.aliases = new Map();
@@ -131,13 +131,17 @@ class TemplateRenderer {
131
131
  this.flowLimits = new Map();
132
132
  /** flow(list, n, options): the options per box, as an expression. */
133
133
  this.flowOptions = new Map();
134
+ /** flow(): each box tokenized once, for all its measuring copies. */
135
+ this.copySources = new Map();
136
+ /** Rendering an alt text (renderAltTexts). */
137
+ this.inAltText = false;
134
138
  this.hideSlideWarned = false;
135
139
  const syntax = (0, commands_1.tagSyntax)(options);
136
140
  this.opening = syntax.opening;
137
141
  this.tagPattern = syntax.pattern;
138
142
  this.evaluation = {
139
- strict: (_a = options.strict) !== null && _a !== void 0 ? _a : false,
140
- allowStringPatterns: (_b = options.allowStringPatterns) !== null && _b !== void 0 ? _b : false,
143
+ strict: options.strict ?? false,
144
+ allowStringPatterns: options.allowStringPatterns ?? false,
141
145
  };
142
146
  // Built-in helpers; additionalJsContext and data can shadow them.
143
147
  // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -146,41 +150,43 @@ class TemplateRenderer {
146
150
  flow: (list) => this.flowEntries(list),
147
151
  flowRest: (list) => this.flowRest(list),
148
152
  // the entries no earlier slide of the deck shows (renderDeck)
149
- 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),
150
154
  // 1-based number of this slide among the slides a list needs
151
- flowPage: ((_c = options.flowPage) !== null && _c !== void 0 ? _c : 0) + 1,
155
+ flowPage: (options.flowPage ?? 0) + 1,
152
156
  get flowPages() {
153
- var _a, _b;
154
- 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;
155
158
  },
156
159
  }, undefined, false);
157
- const jsContext = new Scope((_d = options.additionalJsContext) !== null && _d !== void 0 ? _d : {}, builtins, false);
158
- 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));
159
162
  }
160
- render(element) {
161
- return __awaiter(this, void 0, void 0, function* () {
162
- var _a;
163
- this.collectAliases(element);
164
- const targets = this.findTargets(element);
165
- this.setupFlow(targets);
166
- for (const target of targets) {
167
- this.currentBody = target.tagName === 'p:txBody' ? target : undefined;
168
- if (target.tagName === 'a:tbl') {
169
- yield this.renderTable(target);
170
- }
171
- else if (this.containsTag(target)) {
172
- const bodyTokens = this.tokenizeBody(target);
173
- yield this.writeBody(target, bodyTokens, this.parse(bodyTokens.tokens, textControl), this.root);
174
- yield this.placePendingImages(target);
175
- }
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);
176
174
  }
177
- // flow() cards left without an entry (the last slide of a list)
178
- (_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); });
179
- if (this.errors.length) {
180
- throw new TemplateRenderError(`Template rendering failed with ${this.errors.length} error(s):\n` +
181
- 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);
182
179
  }
183
- });
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
+ }
184
190
  }
185
191
  /** `{{HIDE-SLIDE …}}` outside the speaker notes: removed, not applied. */
186
192
  warnHideSlide(tag) {
@@ -199,7 +205,7 @@ class TemplateRenderer {
199
205
  targets
200
206
  .filter((t) => t.tagName === 'p:txBody' && this.containsTag(t))
201
207
  .forEach((body) => {
202
- const text = xml_helper_1.XmlHelper.collectionToArray(body.getElementsByTagName('a:t'))
208
+ const text = (0, xml_find_1.elementsByTagName)(body, 'a:t')
203
209
  .map((t) => t.textContent)
204
210
  .join('');
205
211
  const keys = new Set();
@@ -240,7 +246,7 @@ class TemplateRenderer {
240
246
  this.textFlow = new text_flow_1.TextFlow(boxes, {
241
247
  renderCopy: (body, entries) => this.renderCopy(body, entries),
242
248
  measureKey: (body) => this.flowMeasureKey(body),
243
- 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?.()) ?? {},
244
250
  }, {
245
251
  fonts: this.options.fonts,
246
252
  flowOverflow: this.options.flowOverflow,
@@ -253,6 +259,10 @@ class TemplateRenderer {
253
259
  flowEntries(list) {
254
260
  if (this.flowOverride)
255
261
  return this.flowOverride();
262
+ if (this.inAltText && !this.currentBody) {
263
+ throw new Error('flow() in alt text works only on a shape in a card: a group ' +
264
+ 'with a text box that loops over flow(…)');
265
+ }
256
266
  if (!this.textFlow) {
257
267
  throw new Error('flow() works only in the loop of a text box, not in a table');
258
268
  }
@@ -290,84 +300,90 @@ class TemplateRenderer {
290
300
  evaluate: (scope, options) => {
291
301
  if (this.flowOverride)
292
302
  return expr.evaluate(scope, options);
293
- return (() => __awaiter(this, void 0, void 0, function* () {
303
+ return (async () => {
294
304
  for (const list of lists) {
295
305
  let value = list.expr.evaluate(scope, options);
296
306
  if (isThenable(value))
297
- value = yield value;
298
- 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));
299
309
  }
300
310
  return expr.evaluate(scope, options);
301
- }))();
311
+ })();
302
312
  },
303
313
  };
304
314
  }
305
315
  /** flow(list, n): the number `n` of each box that has one. */
306
- flowLimitValues(scope, options) {
307
- return __awaiter(this, void 0, void 0, function* () {
308
- const limits = new Map();
309
- for (const [body, expr] of this.flowLimits) {
310
- let value = expr.evaluate(scope, options);
311
- if (isThenable(value))
312
- value = yield value;
313
- const limit = Number(value);
314
- if (!Number.isInteger(limit) || limit < 1) {
315
- throw new Error(`flow(…, ${expr.source}): the number of entries per text box ` +
316
- `must be a whole number of at least 1, not ${String(value)}`);
317
- }
318
- 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)}`);
319
326
  }
320
- return limits;
321
- });
327
+ limits.set(body, limit);
328
+ }
329
+ return limits;
322
330
  }
323
331
  /** flow(list, n, { measure: false }): the boxes that are not measured. */
324
- flowUnmeasured(scope, options) {
325
- return __awaiter(this, void 0, void 0, function* () {
326
- const unmeasured = new Set();
327
- for (const [body, expr] of this.flowOptions) {
328
- let value = expr.evaluate(scope, options);
329
- if (isThenable(value))
330
- value = yield value;
331
- if (value === null || typeof value !== 'object') {
332
- throw new Error(`flow(…, …, ${expr.source}): the options must be an object, ` +
333
- `such as { measure: false }, not ${String(value)}`);
334
- }
335
- if (value.measure === false) {
336
- unmeasured.add(body);
337
- }
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)}`);
338
341
  }
339
- return unmeasured;
340
- });
342
+ if (value.measure === false) {
343
+ unmeasured.add(body);
344
+ }
345
+ }
346
+ return unmeasured;
341
347
  }
342
348
  /**
343
349
  * Renders a detached copy of a text body with flow() returning `entries`
344
350
  * and returns its paragraphs. EXEC assignments and collected errors of
345
351
  * this trial render are undone; the real render repeats them.
346
352
  */
347
- renderCopy(body, entries) {
348
- return __awaiter(this, void 0, void 0, function* () {
349
- const copy = (0, clone_1.cloneXml)(body, true);
350
- const saved = {
351
- override: this.flowOverride,
352
- current: this.currentBody,
353
- errors: this.errors.length,
354
- vars: this.root.snapshot(),
355
- };
356
- this.flowOverride = () => entries;
357
- this.currentBody = copy;
358
- try {
359
- const tokens = this.tokenizeBody(copy);
360
- yield this.writeBody(copy, tokens, this.parse(tokens.tokens, textControl), this.root);
361
- return this.childElements(copy, 'a:p');
362
- }
363
- finally {
364
- this.pendingImages.delete(copy);
365
- this.flowOverride = saved.override;
366
- this.currentBody = saved.current;
367
- this.errors.length = saved.errors;
368
- this.root.restore(saved.vars);
369
- }
370
- });
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
+ }
371
387
  }
372
388
  /**
373
389
  * flow(): boxes with the same key render and measure the same, so one
@@ -380,7 +396,7 @@ class TemplateRenderer {
380
396
  flowMeasureKey(body) {
381
397
  if (this.options.errorHandler)
382
398
  return undefined;
383
- const text = xml_helper_1.XmlHelper.collectionToArray(body.getElementsByTagName('a:t'))
399
+ const text = (0, xml_find_1.elementsByTagName)(body, 'a:t')
384
400
  .map((t) => t.textContent)
385
401
  .join('');
386
402
  for (const match of text.matchAll(this.tagPattern)) {
@@ -390,19 +406,19 @@ class TemplateRenderer {
390
406
  if (command.type === 'HTML')
391
407
  return undefined;
392
408
  }
393
- catch (_a) {
409
+ catch {
394
410
  return undefined;
395
411
  }
396
412
  }
397
413
  const shape = (0, clone_1.cloneXml)(body.parentNode, true);
398
414
  const childOf = (parent, tagName) => parent && this.childElements(parent, tagName)[0];
399
415
  const off = childOf(childOf(childOf(shape, 'p:spPr'), 'a:xfrm'), 'a:off');
400
- off === null || off === void 0 ? void 0 : off.setAttribute('x', '0');
401
- off === null || off === void 0 ? void 0 : off.setAttribute('y', '0');
416
+ off?.setAttribute('x', '0');
417
+ off?.setAttribute('y', '0');
402
418
  const cNvPr = childOf(childOf(shape, 'p:nvSpPr'), 'p:cNvPr');
403
- cNvPr === null || cNvPr === void 0 ? void 0 : cNvPr.removeAttribute('id');
404
- cNvPr === null || cNvPr === void 0 ? void 0 : cNvPr.removeAttribute('name');
405
- return new xmldom_1.XMLSerializer().serializeToString(shape);
419
+ cNvPr?.removeAttribute('id');
420
+ cNvPr?.removeAttribute('name');
421
+ return (0, xml_serializer_1.serializeXml)(shape);
406
422
  }
407
423
  /** Shape text bodies and tables, in document order. */
408
424
  findTargets(element) {
@@ -423,13 +439,12 @@ class TemplateRenderer {
423
439
  return targets;
424
440
  }
425
441
  containsTag(element) {
426
- var _a;
427
- return ((_a = element.textContent) !== null && _a !== void 0 ? _a : '').includes(this.opening);
442
+ return (element.textContent ?? '').includes(this.opening);
428
443
  }
429
444
  /** ALIAS definitions apply everywhere, so collect them up front. */
430
445
  collectAliases(element) {
431
- xml_helper_1.XmlHelper.collectionToArray(element.getElementsByTagName('a:p')).forEach((paragraph) => {
432
- 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')
433
448
  .map((t) => t.textContent)
434
449
  .join('');
435
450
  for (const match of text.matchAll(this.tagPattern)) {
@@ -437,7 +452,7 @@ class TemplateRenderer {
437
452
  try {
438
453
  command = (0, commands_1.parseCommand)(match[1], match[0]);
439
454
  }
440
- catch (_a) {
455
+ catch {
441
456
  continue; // reported where the tag is rendered
442
457
  }
443
458
  if (command.type === 'ALIAS') {
@@ -618,7 +633,10 @@ class TemplateRenderer {
618
633
  }
619
634
  compileStatements(source, tag) {
620
635
  try {
621
- 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
+ }));
622
640
  }
623
641
  catch (error) {
624
642
  if (!this.handlesErrors)
@@ -642,26 +660,24 @@ class TemplateRenderer {
642
660
  * async. Errors go to errorHandler, are collected (failFast: false) or
643
661
  * reject the render.
644
662
  */
645
- value(tag, fn) {
646
- return __awaiter(this, void 0, void 0, function* () {
647
- try {
648
- let result = fn();
649
- if (isThenable(result))
650
- result = yield result;
651
- 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);
652
674
  }
653
- catch (error) {
654
- const err = error instanceof Error ? error : new Error(String(error));
655
- if (this.options.errorHandler) {
656
- return this.options.errorHandler(err, tag);
657
- }
658
- if (this.options.failFast === false) {
659
- this.errors.push(this.withTag(tag, err.message));
660
- return undefined;
661
- }
662
- throw this.tagged(err, tag);
675
+ if (this.options.failFast === false) {
676
+ this.errors.push(this.withTag(tag, err.message));
677
+ return undefined;
663
678
  }
664
- });
679
+ throw this.tagged(err, tag);
680
+ }
665
681
  }
666
682
  /*
667
683
  * Parsing & evaluating blocks (shared by text bodies and table rows)
@@ -672,7 +688,7 @@ class TemplateRenderer {
672
688
  const current = () => (stack.length ? stack[stack.length - 1].body : root);
673
689
  items.forEach((item) => {
674
690
  const tag = control(item);
675
- const directive = tag === null || tag === void 0 ? void 0 : tag.directive;
691
+ const directive = tag?.directive;
676
692
  if (!directive || !BLOCK_TYPES.includes(directive.type)) {
677
693
  current().push({ kind: 'item', item });
678
694
  return;
@@ -704,7 +720,7 @@ class TemplateRenderer {
704
720
  }
705
721
  case 'elseif':
706
722
  case 'else': {
707
- if ((top === null || top === void 0 ? void 0 : top.block.kind) !== 'if') {
723
+ if (top?.block.kind !== 'if') {
708
724
  throw new TemplateRenderError(`${tag.tag} without a matching {{IF …}}`);
709
725
  }
710
726
  const branches = top.block.branches;
@@ -723,7 +739,7 @@ class TemplateRenderer {
723
739
  case 'endif':
724
740
  case 'endfor': {
725
741
  const expected = directive.type === 'endif' ? 'if' : 'for';
726
- if ((top === null || top === void 0 ? void 0 : top.block.kind) !== expected) {
742
+ if (top?.block.kind !== expected) {
727
743
  throw new TemplateRenderError(`${tag.tag} without a matching ${expected.toUpperCase()}` +
728
744
  (top ? ` (open: ${top.tag})` : ''));
729
745
  }
@@ -737,41 +753,39 @@ class TemplateRenderer {
737
753
  }
738
754
  return root;
739
755
  }
740
- evaluate(blocks, scope, emit) {
741
- return __awaiter(this, void 0, void 0, function* () {
742
- for (const block of blocks) {
743
- if (block.kind === 'item') {
744
- yield emit(block.item, scope);
745
- }
746
- else if (block.kind === 'if') {
747
- for (const branch of block.branches) {
748
- const pass = !branch.expr ||
749
- (yield this.value(branch.tag, () => branch.expr.evaluate(scope, this.evaluation)));
750
- if (pass) {
751
- yield this.evaluate(branch.body, scope, emit);
752
- break;
753
- }
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;
754
768
  }
755
769
  }
756
- else {
757
- const value = yield this.value(block.tag, () => {
758
- const list = block.expr.evaluate(scope, this.evaluation);
759
- if (isThenable(list))
760
- return list.then((v) => this.toList(v, block.expr));
761
- return this.toList(list, block.expr);
762
- });
763
- const entries = Array.isArray(value) ? value : [];
764
- for (let idx = 0; idx < entries.length; idx++) {
765
- const loopScope = new Scope({
766
- [block.variable]: entries[idx],
767
- [`$${block.variable}`]: entries[idx],
768
- $idx: idx,
769
- }, scope);
770
- yield this.evaluate(block.body, loopScope, emit);
771
- }
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);
772
786
  }
773
787
  }
774
- });
788
+ }
775
789
  }
776
790
  toList(value, expr) {
777
791
  if (value === null || value === undefined)
@@ -784,157 +798,256 @@ class TemplateRenderer {
784
798
  /*
785
799
  * Writing text bodies
786
800
  */
787
- writeBody(body, bodyTokens, blocks, scope) {
788
- return __awaiter(this, void 0, void 0, function* () {
789
- var _a;
790
- const sourceParagraphs = this.childElements(body, 'a:p');
791
- const first = sourceParagraphs[0];
792
- if (!first)
793
- return;
794
- // The source paragraph, not its clone in a repeated table row: that is
795
- // the one `controlOnly` knows.
796
- const firstSource = (_a = bodyTokens.first) !== null && _a !== void 0 ? _a : first;
797
- const paragraphs = [{ source: firstSource, nodes: [] }];
798
- const current = () => paragraphs[paragraphs.length - 1];
799
- yield this.evaluate(blocks, scope, (token, tokenScope) => __awaiter(this, void 0, void 0, function* () {
800
- switch (token.kind) {
801
- case 'break':
802
- paragraphs.push({ source: token.paragraph, nodes: [] });
803
- break;
804
- case 'node':
805
- current().nodes.push((0, clone_1.cloneXml)(token.node, true));
806
- break;
807
- case 'text':
808
- current().nodes.push(...this.createRuns(token.run, token.text));
809
- break;
810
- case 'tag':
811
- yield this.emitTag(token, tokenScope, body, paragraphs);
812
- break;
813
- }
814
- }));
815
- let kept = paragraphs.filter((p) => p.raw ||
816
- !(bodyTokens.controlOnly.has(p.source) || p.continuation) ||
817
- p.nodes.some((n) => n.tagName !== 'a:r' || this.runText(n).trim() !== ''));
818
- // A text body needs at least one paragraph.
819
- if (!kept.length)
820
- kept = [{ source: firstSource, nodes: [] }];
821
- sourceParagraphs.forEach((p) => body.removeChild(p));
822
- 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
+ }
823
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)));
824
835
  }
825
- emitTag(token, scope, body, paragraphs) {
826
- return __awaiter(this, void 0, void 0, function* () {
827
- var _a;
828
- const { directive, tag, run } = token;
829
- const current = paragraphs[paragraphs.length - 1];
830
- const evaluate = (expr) => this.value(tag, () => expr.evaluate(scope, this.evaluation));
831
- switch (directive.type) {
832
- case 'insert': {
833
- const value = yield this.value(tag, () => __awaiter(this, void 0, void 0, function* () {
834
- const result = yield directive.expr.evaluate(scope, this.evaluation);
835
- if (this.options.rejectNullish &&
836
- (result === null || result === undefined)) {
837
- throw new Error(`"${directive.expr.source}" is ${result}`);
838
- }
839
- return result;
840
- }));
841
- current.nodes.push(...this.createRuns(run, this.format(value)));
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)
842
862
  break;
843
- }
844
- case 'hideslide':
845
- this.warnHideSlide(directive.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 === '')
846
875
  break;
847
- case 'exec':
848
- for (const statement of directive.statements) {
849
- const value = yield evaluate(statement.expr);
850
- if (statement.assign)
851
- scope.assign(statement.assign, value);
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');
852
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 === '')
853
896
  break;
854
- case 'html': {
855
- const html = this.format(yield evaluate(directive.expr));
856
- if (!html)
857
- break;
858
- const generated = this.htmlParagraphs(body, current.source, run, html, yield this.relations());
859
- generated.forEach((raw) => paragraphs.push({ source: current.source, nodes: [], raw }));
860
- paragraphs.push({
861
- source: current.source,
862
- nodes: [],
863
- continuation: true,
864
- });
865
- break;
866
- }
867
- case 'link': {
868
- const value = yield evaluate(directive.expr);
869
- if (value === null || value === undefined || value === '')
870
- break;
871
- const runs = yield this.value(tag, () => __awaiter(this, void 0, void 0, function* () {
872
- const { link, label } = this.toLink(value);
873
- const relations = yield this.relations();
874
- if (!relations) {
875
- throw new Error('LINK needs the slide relationships');
876
- }
877
- const relId = this.linkRelation(relations, link);
878
- const created = this.createRuns(run, label);
879
- created
880
- .filter((n) => n.tagName === 'a:r')
881
- .forEach((r) => this.setHyperlink(r, relId, link.internal));
882
- return created;
883
- }));
884
- if (Array.isArray(runs))
885
- current.nodes.push(...runs);
897
+ // a measuring copy (flowOverride) never places its pictures
898
+ if (this.flowOverride || this.context.countOnly)
886
899
  break;
887
- }
888
- case 'image': {
889
- const value = yield evaluate(directive.expr);
890
- if (value === null || value === undefined || value === '')
891
- break;
892
- const image = yield this.value(tag, () => __awaiter(this, void 0, void 0, function* () {
893
- if (body.tagName !== 'p:txBody') {
894
- throw new Error('IMAGE is not supported inside table cells');
895
- }
896
- if (!(yield this.imageTarget())) {
897
- throw new Error('IMAGE needs slide.modify(modify.renderTemplate(…)); ' +
898
- 'modifyElement() callbacks cannot add media files');
899
- }
900
- return (0, images_1.loadImage)(value, this.options.imageRoot);
901
- }));
902
- if (!image || typeof image !== 'object' || !('content' in image))
903
- break;
904
- const pending = (_a = this.pendingImages.get(body)) !== null && _a !== void 0 ? _a : [];
905
- pending.push(image);
906
- 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))
907
911
  break;
908
- }
912
+ const pending = this.pendingImages.get(body) ?? [];
913
+ pending.push(image);
914
+ this.pendingImages.set(body, pending);
915
+ break;
909
916
  }
910
- });
917
+ }
911
918
  }
912
919
  imageTarget() {
913
- var _a;
914
- (_a = this.imageTargetPromise) !== null && _a !== void 0 ? _a : (this.imageTargetPromise = this.context.images
920
+ this.imageTargetPromise ??= this.context.images
915
921
  ? this.context.images()
916
- : Promise.resolve(undefined));
922
+ : Promise.resolve(undefined);
917
923
  return this.imageTargetPromise;
918
924
  }
919
- /** Pictures go where the shape is; a shape left without text is removed. */
920
- placePendingImages(body) {
921
- return __awaiter(this, void 0, void 0, function* () {
922
- const images = this.pendingImages.get(body);
923
- if (!(images === null || images === void 0 ? void 0 : images.length))
924
- return;
925
- this.pendingImages.delete(body);
926
- const shape = body.parentNode;
927
- const text = xml_helper_1.XmlHelper.collectionToArray(body.getElementsByTagName('a:t'))
928
- .map((t) => t.textContent)
929
- .join('');
925
+ /**
926
+ * The alt text of a picture or shape as a small template: `{{IMAGE …}}`,
927
+ * optionally inside IF and FOR blocks and with EXEC, and nothing else.
928
+ * The picture it yields fills the shape (fillWithImage). Rendered after
929
+ * the text, so EXEC variables apply; in a flow() card, flow(list) gives
930
+ * the entries of that card. No picture (no IMAGE reached, or null,
931
+ * undefined, '') keeps the picture that is there (a backup). Only alt
932
+ * texts of tags with an IMAGE among them count (isAltTextTemplate).
933
+ */
934
+ altTextHolders(element) {
935
+ const commandType = (inner, tag) => {
936
+ try {
937
+ return (0, commands_1.parseCommand)((0, commands_1.resolveAlias)(inner, this.aliases, tag), tag).type;
938
+ }
939
+ catch {
940
+ return undefined;
941
+ }
942
+ };
943
+ return (0, xml_find_1.elementsByTagName)(element, 'p:cNvPr').filter((cNvPr) => (0, commands_1.isAltTextTemplate)(cNvPr.getAttribute('descr') ?? '', this.tagPattern, commandType));
944
+ }
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');
930
955
  try {
931
- yield (0, images_1.placeImages)(yield this.imageTarget(), shape, images, text.trim() === '');
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]);
960
+ }
961
+ return { tag: match[0], directive };
962
+ });
963
+ blocks = this.parse(tags, (tag) => tag);
932
964
  }
933
965
  catch (error) {
934
- throw this.tagged(error, 'IMAGE');
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);
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;
935
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');
1002
+ }
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);
1014
+ }
1015
+ }
1016
+ catch (error) {
1017
+ await this.fail(tag, error);
1018
+ }
1019
+ }
1020
+ }
1021
+ /** An error at `tag`, handled as in value(): errorHandler, collected or thrown. */
1022
+ async fail(tag, error) {
1023
+ await this.value(tag, () => {
1024
+ throw error;
936
1025
  });
937
1026
  }
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
+ }
1033
+ }
1034
+ /** Pictures go where the shape is; a shape left without text is removed. */
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
+ }
1050
+ }
938
1051
  createParagraph(output) {
939
1052
  const paragraph = (0, clone_1.cloneXml)(output.source, false);
940
1053
  const pPr = this.childElements(output.source, 'a:pPr')[0];
@@ -965,10 +1078,26 @@ class TemplateRenderer {
965
1078
  }
966
1079
  if (line === '')
967
1080
  return;
968
- const run = (0, clone_1.cloneXml)(template, true);
969
- const t = run.getElementsByTagName('a:t')[0];
970
- while (t.firstChild)
971
- 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
+ }
972
1101
  t.appendChild(doc.createTextNode(xml_helper_1.XmlHelper.sanitizeText(line)));
973
1102
  nodes.push(run);
974
1103
  });
@@ -985,10 +1114,9 @@ class TemplateRenderer {
985
1114
  * HTML and hyperlinks
986
1115
  */
987
1116
  relations() {
988
- var _a;
989
- (_a = this.relationsPromise) !== null && _a !== void 0 ? _a : (this.relationsPromise = this.context.relations
1117
+ this.relationsPromise ??= this.context.relations
990
1118
  ? this.context.relations()
991
- : Promise.resolve(undefined));
1119
+ : Promise.resolve(undefined);
992
1120
  return this.relationsPromise;
993
1121
  }
994
1122
  /**
@@ -1012,7 +1140,6 @@ class TemplateRenderer {
1012
1140
  return this.childElements(scratch, 'a:p');
1013
1141
  }
1014
1142
  toLink(value) {
1015
- var _a;
1016
1143
  const spec = typeof value === 'object'
1017
1144
  ? value
1018
1145
  : { url: value };
@@ -1022,7 +1149,7 @@ class TemplateRenderer {
1022
1149
  }
1023
1150
  const internal = typeof url === 'number';
1024
1151
  const target = internal ? `../slides/slide${url}.xml` : String(url);
1025
- const label = this.format((_a = spec.label) !== null && _a !== void 0 ? _a : url);
1152
+ const label = this.format(spec.label ?? url);
1026
1153
  return { link: { target, internal }, label };
1027
1154
  }
1028
1155
  linkRelation(relations, link) {
@@ -1062,74 +1189,72 @@ class TemplateRenderer {
1062
1189
  /*
1063
1190
  * Tables: blocks left open inside a cell span (and repeat) table rows.
1064
1191
  */
1065
- renderTable(table) {
1066
- return __awaiter(this, void 0, void 0, function* () {
1067
- if (!this.containsTag(table))
1068
- return;
1069
- const rows = this.childElements(table, 'a:tr');
1070
- const rowTokens = [];
1071
- rows.forEach((row) => {
1072
- const openers = [];
1073
- // Closers before the row's first opener end a block from an earlier
1074
- // row; they must not close the block this row opens.
1075
- const leading = [];
1076
- const closers = [];
1077
- let hasContent = false;
1078
- const cells = this.childElements(row, 'a:tc').map((cell) => {
1079
- const body = this.childElements(cell, 'a:txBody')[0];
1080
- if (!body)
1081
- return undefined;
1082
- const bodyTokens = this.tokenizeBody(body);
1083
- const rowLevel = this.extractRowLevelTags(bodyTokens.tokens);
1084
- rowLevel.closers.forEach((t) => (openers.length ? closers : leading).push({
1085
- tag: t.tag,
1086
- directive: t.directive,
1087
- }));
1088
- rowLevel.openers.forEach((t) => openers.push({ tag: t.tag, directive: t.directive }));
1089
- const extracted = new Set([
1090
- ...rowLevel.openers,
1091
- ...rowLevel.closers,
1092
- ]);
1093
- bodyTokens.tokens = bodyTokens.tokens.filter((t) => !extracted.has(t));
1094
- hasContent =
1095
- hasContent ||
1096
- bodyTokens.tokens.some((t) => (t.kind === 'tag' && CONTENT_TYPES.includes(t.directive.type)) ||
1097
- (t.kind === 'text' && t.text.trim() !== '') ||
1098
- (t.kind === 'node' && t.node.tagName === 'a:fld'));
1099
- return bodyTokens;
1100
- });
1101
- // Without an opener, all closers end blocks this row still belongs to
1102
- if (!openers.length)
1103
- closers.push(...leading.splice(0));
1104
- const isControlRow = !hasContent && (openers.length || closers.length);
1105
- rowTokens.push(...leading, ...openers);
1106
- if (!isControlRow)
1107
- rowTokens.push({ row, cells });
1108
- rowTokens.push(...closers);
1109
- });
1110
- const output = [];
1111
- 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* () {
1112
- const row = (0, clone_1.cloneXml)(token.row, true);
1113
- const cells = this.childElements(row, 'a:tc');
1114
- for (let c = 0; c < cells.length; c++) {
1115
- const bodyTokens = token.cells[c];
1116
- const body = this.childElements(cells[c], 'a:txBody')[0];
1117
- if (!bodyTokens || !body)
1118
- continue;
1119
- yield this.writeBody(body, bodyTokens, this.parse(bodyTokens.tokens, textControl), scope);
1120
- }
1121
- output.push(row);
1122
- }));
1123
- const anchor = rows[rows.length - 1].nextSibling;
1124
- rows.forEach((row) => table.removeChild(row));
1125
- output.forEach((row, r) => {
1126
- table.insertBefore(row, anchor);
1127
- const rowId = row.getElementsByTagName('a16:rowId')[0];
1128
- if (rowId)
1129
- 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;
1130
1226
  });
1131
- 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));
1132
1256
  });
1257
+ this.updateFrameHeight(table, output);
1133
1258
  }
1134
1259
  /** Block tags that are not closed (or opened) within the same cell. */
1135
1260
  extractRowLevelTags(tokens) {
@@ -1155,12 +1280,13 @@ class TemplateRenderer {
1155
1280
  return { openers: stack, closers };
1156
1281
  }
1157
1282
  updateFrameHeight(table, rows) {
1158
- var _a;
1159
1283
  let frame = table.parentNode;
1160
1284
  while (frame && frame.tagName !== 'p:graphicFrame') {
1161
1285
  frame = frame.parentNode;
1162
1286
  }
1163
- 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];
1164
1290
  if (!ext)
1165
1291
  return;
1166
1292
  const height = rows.reduce((sum, row) => sum + Number(row.getAttribute('h') || 0), 0);
@@ -1182,8 +1308,7 @@ class TemplateRenderer {
1182
1308
  return children;
1183
1309
  }
1184
1310
  runText(run) {
1185
- var _a, _b;
1186
- 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 ?? '';
1187
1312
  }
1188
1313
  }
1189
1314
  exports.TemplateRenderer = TemplateRenderer;