@folijs/docx 0.4.0 → 0.6.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 (107) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +95 -15
  3. package/dist/export/balance.d.ts +17 -0
  4. package/dist/export/balance.d.ts.map +1 -0
  5. package/dist/export/balance.js +111 -0
  6. package/dist/export/balance.js.map +1 -0
  7. package/dist/export/content.d.ts +7 -0
  8. package/dist/export/content.d.ts.map +1 -1
  9. package/dist/export/content.js +185 -14
  10. package/dist/export/content.js.map +1 -1
  11. package/dist/export/controls.d.ts +18 -0
  12. package/dist/export/controls.d.ts.map +1 -0
  13. package/dist/export/controls.js +232 -0
  14. package/dist/export/controls.js.map +1 -0
  15. package/dist/export/index.d.ts +6 -1
  16. package/dist/export/index.d.ts.map +1 -1
  17. package/dist/export/index.js +277 -28
  18. package/dist/export/index.js.map +1 -1
  19. package/dist/export/parts.d.ts +9 -1
  20. package/dist/export/parts.d.ts.map +1 -1
  21. package/dist/export/parts.js +69 -2
  22. package/dist/export/parts.js.map +1 -1
  23. package/dist/export/pictures.d.ts +54 -0
  24. package/dist/export/pictures.d.ts.map +1 -0
  25. package/dist/export/pictures.js +359 -0
  26. package/dist/export/pictures.js.map +1 -0
  27. package/dist/export/properties.d.ts +11 -1
  28. package/dist/export/properties.d.ts.map +1 -1
  29. package/dist/export/properties.js +57 -3
  30. package/dist/export/properties.js.map +1 -1
  31. package/dist/export/tables.d.ts +27 -0
  32. package/dist/export/tables.d.ts.map +1 -0
  33. package/dist/export/tables.js +344 -0
  34. package/dist/export/tables.js.map +1 -0
  35. package/dist/images.d.ts +21 -0
  36. package/dist/images.d.ts.map +1 -0
  37. package/dist/images.js +53 -0
  38. package/dist/images.js.map +1 -0
  39. package/dist/import/content.d.ts +15 -1
  40. package/dist/import/content.d.ts.map +1 -1
  41. package/dist/import/content.js +357 -15
  42. package/dist/import/content.js.map +1 -1
  43. package/dist/import/controls.d.ts +14 -0
  44. package/dist/import/controls.d.ts.map +1 -0
  45. package/dist/import/controls.js +123 -0
  46. package/dist/import/controls.js.map +1 -0
  47. package/dist/import/index.d.ts +10 -2
  48. package/dist/import/index.d.ts.map +1 -1
  49. package/dist/import/index.js +76 -13
  50. package/dist/import/index.js.map +1 -1
  51. package/dist/import/ooxml.d.ts +4 -0
  52. package/dist/import/ooxml.d.ts.map +1 -1
  53. package/dist/import/ooxml.js +4 -0
  54. package/dist/import/ooxml.js.map +1 -1
  55. package/dist/import/parts.d.ts.map +1 -1
  56. package/dist/import/parts.js +8 -1
  57. package/dist/import/parts.js.map +1 -1
  58. package/dist/import/pictures.d.ts +34 -0
  59. package/dist/import/pictures.d.ts.map +1 -0
  60. package/dist/import/pictures.js +147 -0
  61. package/dist/import/pictures.js.map +1 -0
  62. package/dist/import/properties.d.ts +2 -0
  63. package/dist/import/properties.d.ts.map +1 -1
  64. package/dist/import/properties.js +55 -0
  65. package/dist/import/properties.js.map +1 -1
  66. package/dist/import/report.d.ts +6 -0
  67. package/dist/import/report.d.ts.map +1 -1
  68. package/dist/import/report.js +5 -0
  69. package/dist/import/report.js.map +1 -1
  70. package/dist/import/stories.d.ts +19 -0
  71. package/dist/import/stories.d.ts.map +1 -0
  72. package/dist/import/stories.js +119 -0
  73. package/dist/import/stories.js.map +1 -0
  74. package/dist/import/tables.d.ts +31 -0
  75. package/dist/import/tables.d.ts.map +1 -0
  76. package/dist/import/tables.js +236 -0
  77. package/dist/import/tables.js.map +1 -0
  78. package/dist/index.d.ts +1 -0
  79. package/dist/index.d.ts.map +1 -1
  80. package/dist/index.js +1 -0
  81. package/dist/index.js.map +1 -1
  82. package/dist/settings.d.ts +18 -4
  83. package/dist/settings.d.ts.map +1 -1
  84. package/dist/settings.js +173 -26
  85. package/dist/settings.js.map +1 -1
  86. package/package.json +3 -3
  87. package/src/export/balance.ts +113 -0
  88. package/src/export/content.ts +240 -15
  89. package/src/export/controls.ts +259 -0
  90. package/src/export/index.ts +357 -32
  91. package/src/export/parts.ts +94 -2
  92. package/src/export/pictures.ts +411 -0
  93. package/src/export/properties.ts +69 -3
  94. package/src/export/tables.ts +386 -0
  95. package/src/images.ts +60 -0
  96. package/src/import/content.ts +365 -17
  97. package/src/import/controls.ts +137 -0
  98. package/src/import/index.ts +87 -12
  99. package/src/import/ooxml.ts +4 -0
  100. package/src/import/parts.ts +14 -1
  101. package/src/import/pictures.ts +176 -0
  102. package/src/import/properties.ts +59 -0
  103. package/src/import/report.ts +11 -0
  104. package/src/import/stories.ts +122 -0
  105. package/src/import/tables.ts +267 -0
  106. package/src/index.ts +1 -0
  107. package/src/settings.ts +191 -27
@@ -4,8 +4,17 @@
4
4
  */
5
5
 
6
6
  import type { MarkJSON, NodeJSON } from "@folijs/core";
7
+ import { DocxError } from "../package.js";
8
+ import type { ControlWriter } from "./controls.js";
7
9
  import { paragraphPropertiesXml, runPropertiesXml, same } from "./properties.js";
8
- import { bagXml, el, escapeText, fragment, type Namespaces } from "./xmlout.js";
10
+ import {
11
+ cellPropertiesXml,
12
+ exceptionsXml,
13
+ gridXml,
14
+ rowPropertiesXml,
15
+ tablePropertiesXml,
16
+ } from "./tables.js";
17
+ import { bagXml, el, escapeAttribute, escapeText, fragment, type Namespaces } from "./xmlout.js";
9
18
 
10
19
  export interface WriteContext {
11
20
  readonly namespaces: Namespaces;
@@ -14,6 +23,12 @@ export interface WriteContext {
14
23
  * still has it with that target, otherwise a new one.
15
24
  */
16
25
  readonly hyperlink: (href: string, id: string | undefined) => string;
26
+ /** A picture's `w:drawing` (its image related to the part, its media part allocated). */
27
+ readonly picture: (attrs: Record<string, unknown>) => string;
28
+ /** The kind of note being written: what its `noteMark` is. */
29
+ readonly note?: "footnote" | "endnote";
30
+ /** The document's content controls. */
31
+ readonly controls: ControlWriter;
17
32
  }
18
33
 
19
34
  type Json = Record<string, unknown>;
@@ -25,19 +40,65 @@ function verbatim(xml: unknown, context: WriteContext): string {
25
40
  return text;
26
41
  }
27
42
 
43
+ /** A control around `inner` (`w:sdtPr`, `w:sdtEndPr`, then the content, as `w:sdt` requires). */
44
+ function controlXml(id: string, inner: string, context: WriteContext): string {
45
+ const { properties } = context.controls.parts(id, context.namespaces);
46
+ return `<w:sdt>${properties}<w:sdtContent>${inner}</w:sdtContent></w:sdt>`;
47
+ }
48
+
49
+ /** `items` written by `write`, the runs of them in one control (at `depth`) inside it. */
50
+ function inControls(
51
+ items: readonly NodeJSON[],
52
+ depth: number,
53
+ context: WriteContext,
54
+ write: (item: NodeJSON) => string,
55
+ ): string {
56
+ return grouped(
57
+ items,
58
+ (n) => (n.attrs?.controls as string[] | undefined)?.[depth],
59
+ (group, id) =>
60
+ id === undefined
61
+ ? group.map(write).join("")
62
+ : controlXml(id as string, inControls(group, depth + 1, context, write), context),
63
+ );
64
+ }
65
+
28
66
  export function blocksXml(blocks: readonly NodeJSON[], context: WriteContext): string {
29
- let out = "";
30
- for (const block of blocks) {
31
- if (block.type === "paragraph") out += paragraphXml(block, context);
32
- else if (block.type === "opaqueBlock") out += verbatim(block.attrs?.xml, context);
33
- }
34
- return out;
67
+ return inControls(blocks, 0, context, (block) => {
68
+ if (block.type === "paragraph") return paragraphXml(block, context);
69
+ if (block.type === "opaqueBlock") return verbatim(block.attrs?.xml, context);
70
+ if (block.type === "table") return tableXml(block, context);
71
+ return notYet(block);
72
+ });
73
+ }
74
+
75
+ /** A table: its properties, its grid, then each row's exceptions, properties and cells. */
76
+ function tableXml(table: NodeJSON, context: WriteContext): string {
77
+ const ns = context.namespaces;
78
+ const attrs = (table.attrs ?? {}) as Json;
79
+ let out = `<w:tbl>${tablePropertiesXml(attrs, ns)}${gridXml(attrs, ns)}`;
80
+ out += inControls(table.content ?? [], 0, context, (row) => {
81
+ const r = (row.attrs ?? {}) as Json;
82
+ const cells = inControls(row.content ?? [], 0, context, (cell) => {
83
+ const c = (cell.attrs ?? {}) as Json;
84
+ return `<w:tc>${cellPropertiesXml(c, ns)}${blocksXml(cell.content ?? [], context)}</w:tc>`;
85
+ });
86
+ return `<w:tr${bagXml(r.attributes, ns)}>${exceptionsXml(r.exceptions, ns)}${rowPropertiesXml(r, ns)}${cells}</w:tr>`;
87
+ });
88
+ return `${out}</w:tbl>`;
89
+ }
90
+
91
+ /** Content export does not write yet (pictures: 10.8): refused, never dropped. */
92
+ function notYet(node: NodeJSON): never {
93
+ throw new DocxError(`A ${node.type} cannot be exported to .docx yet`);
35
94
  }
36
95
 
37
96
  export function paragraphXml(p: NodeJSON, context: WriteContext): string {
38
97
  const attrs = (p.attrs ?? {}) as Json;
39
98
  const own = bagXml(attrs.attributes, context.namespaces);
40
- return `<w:p${own}>${paragraphPropertiesXml(attrs, context.namespaces)}${inlinesXml(p.content ?? [], context)}</w:p>`;
99
+ const inner = `${paragraphPropertiesXml(attrs, context.namespaces)}${inlinesXml(p.content ?? [], context)}`;
100
+ // An empty paragraph as Word writes it.
101
+ return inner ? `<w:p${own}>${inner}</w:p>` : `<w:p${own}/>`;
41
102
  }
42
103
 
43
104
  const markOf = (node: NodeJSON, type: string) => node.marks?.find((m) => m.type === type);
@@ -59,8 +120,113 @@ function grouped(
59
120
  return out;
60
121
  }
61
122
 
123
+ /** An element already written, standing in the inline content while runs are grouped. */
124
+ const ELEMENT = "#element";
125
+
126
+ /** Where the node matching the opening one at `from` is, by nesting; -1 if none. */
127
+ function closing(
128
+ nodes: readonly NodeJSON[],
129
+ from: number,
130
+ opens: (n: NodeJSON) => boolean,
131
+ closes: (n: NodeJSON) => boolean,
132
+ ): number {
133
+ let depth = 0;
134
+ for (let i = from; i < nodes.length; i++) {
135
+ const node = nodes[i] as NodeJSON;
136
+ if (opens(node)) depth++;
137
+ else if (closes(node) && --depth === 0) return i;
138
+ }
139
+ return -1;
140
+ }
141
+
142
+ /** A field read from `w:fldSimple`, written as one: start, its code, a separator, the result. */
143
+ function simpleFieldXml(
144
+ inner: readonly NodeJSON[],
145
+ context: WriteContext,
146
+ deleted: boolean,
147
+ ): string | undefined {
148
+ const start = inner[0] as NodeJSON;
149
+ const code = inner[1];
150
+ if (code?.type !== "fieldCode" || inner[2]?.type !== "fieldSeparator") return undefined;
151
+ const instruction = String(code.attrs?.text ?? "");
152
+ const ext = start.attrs?.ext as string | undefined;
153
+ let open = `<w:fldSimple w:instr="${escapeAttribute(instruction)}">`;
154
+ if (ext) {
155
+ const { element, source } = fragment(`${ext}</w:fldSimple>`, context.namespaces, "fldSimple");
156
+ const others = element.attributes
157
+ .filter((a) => a.name !== "w:instr")
158
+ .map((a) => ` ${source.slice(a.start, a.end)}`)
159
+ .join("");
160
+ const same = element.attributes.find((a) => a.name === "w:instr")?.value === instruction;
161
+ open = same ? ext : `<w:fldSimple w:instr="${escapeAttribute(instruction)}"${others}>`;
162
+ }
163
+ return `${open}${inlinesXml(inner.slice(3), context, deleted)}</w:fldSimple>`;
164
+ }
165
+
166
+ /** The hyperlink and tracked changes `a` and `b` both have: they go around the whole element. */
167
+ function sharedStructure(a: NodeJSON, b: NodeJSON): MarkJSON[] {
168
+ return (a.marks ?? []).filter(
169
+ (m) => STRUCTURE.has(m.type) && (b.marks ?? []).some((other) => same(m, other)),
170
+ );
171
+ }
172
+
173
+ /**
174
+ * Inline content: inline controls and simple fields as the elements around what they hold, inside
175
+ * the hyperlink and tracked changes around both their ends (ends whose partner is gone are
176
+ * dropped, their content kept); the rest in runs. `deleted`: inside a tracked deletion.
177
+ */
178
+ function inlinesXml(nodes: readonly NodeJSON[], context: WriteContext, deleted = false): string {
179
+ const out: NodeJSON[] = [];
180
+ for (let i = 0; i < nodes.length; i++) {
181
+ const node = nodes[i] as NodeJSON;
182
+ const control = node.type === "controlStart";
183
+ const field = node.type === "fieldStart" && !!node.attrs?.simple;
184
+ const id = node.attrs?.id;
185
+ const end =
186
+ !control && !field
187
+ ? -1
188
+ : closing(
189
+ nodes,
190
+ i,
191
+ (n) =>
192
+ control ? n.type === "controlStart" && n.attrs?.id === id : n.type === "fieldStart",
193
+ (n) =>
194
+ control ? n.type === "controlEnd" && n.attrs?.id === id : n.type === "fieldEnd",
195
+ );
196
+ if (end < 0) {
197
+ out.push(node);
198
+ continue;
199
+ }
200
+ const shared = sharedStructure(node, nodes[end] as NodeJSON);
201
+ const without = (n: NodeJSON): NodeJSON => {
202
+ const marks = (n.marks ?? []).filter((m) => !shared.some((s) => same(m, s)));
203
+ const { marks: _marks, ...rest } = n;
204
+ return marks.length ? { ...rest, marks } : rest;
205
+ };
206
+ const gone = deleted || shared.some((m) => m.type === "deletion");
207
+ const xml = control
208
+ ? controlXml(
209
+ String(id),
210
+ inlinesXml(nodes.slice(i + 1, end).map(without), context, gone),
211
+ context,
212
+ )
213
+ : simpleFieldXml(nodes.slice(i, end).map(without), context, gone);
214
+ if (xml === undefined) {
215
+ out.push(node);
216
+ continue;
217
+ }
218
+ out.push({ type: ELEMENT, attrs: { xml }, ...(shared.length ? { marks: shared } : {}) });
219
+ i = end;
220
+ }
221
+ return plainInlinesXml(out, context, deleted);
222
+ }
223
+
62
224
  /** Hyperlinks outermost, then insertions (or move destinations), then deletions (or move sources). */
63
- function inlinesXml(nodes: readonly NodeJSON[], context: WriteContext): string {
225
+ function plainInlinesXml(
226
+ nodes: readonly NodeJSON[],
227
+ context: WriteContext,
228
+ outerDeleted: boolean,
229
+ ): string {
64
230
  return grouped(
65
231
  nodes,
66
232
  (n) => markOf(n, "link"),
@@ -81,7 +247,7 @@ function inlinesXml(nodes: readonly NodeJSON[], context: WriteContext): string {
81
247
  del as MarkJSON | undefined,
82
248
  "del",
83
249
  "moveFrom",
84
- runsXml(g2, !!del, context),
250
+ runsXml(g2, !!del || outerDeleted, context),
85
251
  context,
86
252
  ),
87
253
  ),
@@ -132,9 +298,21 @@ function hyperlinkXml(link: MarkJSON, inner: string, context: WriteContext): str
132
298
  /** Inline nodes that are a run's content (the rest stands between runs). */
133
299
  function inRun(node: NodeJSON): boolean {
134
300
  if (node.type === "opaqueInline") return node.attrs?.run === true;
135
- return ["text", "tab", "hardBreak", "pageBreak", "columnBreak", "commentReference"].includes(
136
- node.type,
137
- );
301
+ return [
302
+ "text",
303
+ "tab",
304
+ "hardBreak",
305
+ "pageBreak",
306
+ "columnBreak",
307
+ "commentReference",
308
+ "noteReference",
309
+ "noteMark",
310
+ "picture",
311
+ "fieldStart",
312
+ "fieldCode",
313
+ "fieldSeparator",
314
+ "fieldEnd",
315
+ ].includes(node.type);
138
316
  }
139
317
 
140
318
  const STRUCTURE = new Set(["link", "insertion", "deletion"]);
@@ -176,13 +354,32 @@ function markerXml(node: NodeJSON, context: WriteContext): string {
176
354
  return tag("w:commentRangeStart", { "w:id": String(a.id) });
177
355
  case "commentEnd":
178
356
  return tag("w:commentRangeEnd", { "w:id": String(a.id) });
357
+ case ELEMENT:
358
+ return String(a.xml);
179
359
  case "opaqueInline":
180
360
  return verbatim(a.xml, context);
181
- default:
361
+ // Their partner is gone (an edit): the content around them stays.
362
+ case "controlStart":
363
+ case "controlEnd":
182
364
  return "";
365
+ default:
366
+ return notYet(node);
183
367
  }
184
368
  }
185
369
 
370
+ /** A `w:fldChar`: the element as read if it holds more than the model does. */
371
+ function fieldCharXml(type: string, a: Json, context: WriteContext): string {
372
+ // A simple field's `ext` is its start tag: this one has lost its shape, and is written plain.
373
+ if (a.ext && !a.simple) return verbatim(a.ext, context);
374
+ const flag = (value: unknown) =>
375
+ value === null || value === undefined ? undefined : value ? "1" : "0";
376
+ return el("w:fldChar", {
377
+ "w:fldCharType": type,
378
+ "w:dirty": flag(a.dirty),
379
+ "w:fldLock": flag(a.locked),
380
+ });
381
+ }
382
+
186
383
  /**
187
384
  * Text as `w:t` (or `w:delText`), with tabs and Word's special hyphens as their elements, and
188
385
  * line ends and vertical tabs (Office's line break in pasted text) as breaks.
@@ -221,9 +418,37 @@ function runContentXml(node: NodeJSON, deleted: boolean, context: WriteContext):
221
418
  return el("w:br", { "w:type": "column" });
222
419
  case "commentReference":
223
420
  return `${el("w:commentReference", { "w:id": String(a.id) }).slice(0, -2)}${bagXml(a.attributes, context.namespaces, ["w:id"])}/>`;
421
+ case "noteReference": {
422
+ const [kind, id] = String(a.story).split(/:(.*)/s) as [string, string];
423
+ if ((kind !== "footnote" && kind !== "endnote") || !/^-?\d+$/.test(id ?? ""))
424
+ throw new DocxError(`Not a note's id: ${String(a.story).slice(0, 64)}`);
425
+ const known = ["w:customMarkFollows", "w:id"];
426
+ const open = el(`w:${kind}Reference`, {
427
+ "w:customMarkFollows": a.customMark === undefined ? undefined : a.customMark ? "1" : "0",
428
+ "w:id": id,
429
+ }).slice(0, -2);
430
+ return `${open}${bagXml(a.attributes, context.namespaces, known)}/>`;
431
+ }
432
+ case "noteMark":
433
+ return context.note ? `<w:${context.note}Ref/>` : notYet(node);
434
+ case "fieldStart":
435
+ return fieldCharXml("begin", a, context);
436
+ case "fieldSeparator":
437
+ return fieldCharXml("separate", a, context);
438
+ case "fieldEnd":
439
+ return fieldCharXml("end", a, context);
440
+ case "fieldCode": {
441
+ const name = deleted ? "w:delInstrText" : "w:instrText";
442
+ const value = String(a.text ?? "");
443
+ const preserve = /^\s|\s$/.test(value) ? ' xml:space="preserve"' : "";
444
+ const bag = bagXml(a.attributes, context.namespaces, ["xml:space"]);
445
+ return `<${name}${preserve}${bag}>${escapeText(value)}</${name}>`;
446
+ }
224
447
  case "opaqueInline":
225
448
  return verbatim(a.xml, context);
449
+ case "picture":
450
+ return context.picture(a);
226
451
  default:
227
- return "";
452
+ return notYet(node);
228
453
  }
229
454
  }
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Content controls written back (ADR-0007). A control keeps the `w:sdtPr` and `w:sdtEndPr` it was
3
+ * read from: what changed is patched child by child, the rest stays byte for byte. A new control
4
+ * gets a whole `w:sdtPr`. A control written twice (an edit split it) gets a new `w:id` the second
5
+ * time; a copy carries none (core drops it), and Word gives it one.
6
+ */
7
+ import type { ControlJSON } from "@folijs/core";
8
+ import { controlProperties } from "../import/controls.js";
9
+ import { child, elements, W14, W15 } from "../import/ooxml.js";
10
+ import { Recorder } from "../import/report.js";
11
+ import { DocxError } from "../package.js";
12
+ import type { XmlElement } from "../xml.js";
13
+ import { same } from "./properties.js";
14
+ import { el, escapeAttribute, fragment, type Namespaces, val } from "./xmlout.js";
15
+
16
+ /** `w:sdtPr`'s children in the order the schema gives them; the kind's element comes after. */
17
+ const ORDER = [
18
+ "rPr",
19
+ "alias",
20
+ "tag",
21
+ "id",
22
+ "lock",
23
+ "placeholder",
24
+ "temporary",
25
+ "showingPlcHdr",
26
+ "dataBinding",
27
+ "label",
28
+ "tabIndex",
29
+ ];
30
+ const ID = /(<[\w.-]+:id\b[^>]*?[\w.-]+:val=")(-?\d+)(")/;
31
+
32
+ interface Edit {
33
+ from: number;
34
+ to: number;
35
+ text: string;
36
+ }
37
+
38
+ const itemsXml = (items: NonNullable<ControlJSON["items"]>) =>
39
+ items
40
+ .map((item) =>
41
+ el("w:listItem", {
42
+ "w:displayText": item.display ?? item.value,
43
+ "w:value": item.value,
44
+ }),
45
+ )
46
+ .join("");
47
+
48
+ /** An extension's element, its namespace declared on it where the part does not. */
49
+ const extension = (prefix: "w14" | "w15", uri: string, ns: Namespaces) =>
50
+ ns.prefixes.has(prefix) ? {} : { [`xmlns:${prefix}`]: uri };
51
+
52
+ /** The element of a control's kind, as Word writes it. */
53
+ function kindXml(control: ControlJSON, ns: Namespaces): string {
54
+ switch (control.kind) {
55
+ case "text":
56
+ return el("w:text", control.multiLine ? { "w:multiLine": "1" } : {});
57
+ case "dropDown":
58
+ return el("w:dropDownList", {}, itemsXml(control.items ?? []));
59
+ case "comboBox":
60
+ return el("w:comboBox", {}, itemsXml(control.items ?? []));
61
+ case "date":
62
+ return el(
63
+ "w:date",
64
+ { "w:fullDate": control.date },
65
+ val("dateFormat", control.dateFormat ?? "d MMMM yyyy") +
66
+ val("lid", "en-US") +
67
+ val("storeMappedDataAs", "dateTime") +
68
+ val("calendar", "gregorian"),
69
+ );
70
+ case "checkbox": {
71
+ const glyph = (name: string, state: ControlJSON["checkedState"], code: string) =>
72
+ el(`w14:${name}`, {
73
+ "w14:val": state?.value ?? code,
74
+ "w14:font": state?.font ?? "MS Gothic",
75
+ });
76
+ return el(
77
+ "w14:checkbox",
78
+ extension("w14", W14, ns),
79
+ el("w14:checked", { "w14:val": control.checked ? "1" : "0" }) +
80
+ glyph("checkedState", control.checkedState, "2612") +
81
+ glyph("uncheckedState", control.uncheckedState, "2610"),
82
+ );
83
+ }
84
+ case "picture":
85
+ return el("w:picture");
86
+ case "repeating":
87
+ return el("w15:repeatingSection", extension("w15", W15, ns));
88
+ case "repeatingItem":
89
+ return el("w15:repeatingSectionItem", extension("w15", W15, ns));
90
+ default:
91
+ return "";
92
+ }
93
+ }
94
+
95
+ /** The whole `w:sdtPr` of a control that has none yet. */
96
+ function newProperties(control: ControlJSON, id: number, ns: Namespaces): string {
97
+ const { placeholder } = control;
98
+ return el(
99
+ "w:sdtPr",
100
+ {},
101
+ val("alias", control.alias) +
102
+ val("tag", control.tag) +
103
+ val("id", id) +
104
+ val("lock", control.lock) +
105
+ (placeholder?.docPart ? el("w:placeholder", {}, val("docPart", placeholder.docPart)) : "") +
106
+ (placeholder?.showing ? el("w:showingPlcHdr") : "") +
107
+ kindXml(control, ns),
108
+ );
109
+ }
110
+
111
+ /** The kept `w:sdtPr` with what `control` says differently written into it. */
112
+ function patched(source: string, pr: XmlElement, control: ControlJSON, kept: ControlJSON): string {
113
+ const edits: Edit[] = [];
114
+ const children = elements(pr);
115
+ const prefix = pr.name.includes(":") ? `${pr.name.split(":")[0]}:` : "";
116
+ const named = (local: string) => children.find((c) => c.ns === pr.ns && c.local === local);
117
+ /** Where a new child goes: before the first that comes after it. */
118
+ const insertAt = (local: string) => {
119
+ const rank = ORDER.indexOf(local);
120
+ const next = children.find((c) => {
121
+ const at = c.ns === pr.ns ? ORDER.indexOf(c.local) : -1;
122
+ return at < 0 || at > rank;
123
+ });
124
+ return next ? next.start : pr.closeStart;
125
+ };
126
+ const child1 = (local: string, value: string | undefined) => {
127
+ const old = named(local);
128
+ const xml = value === undefined ? "" : el(`${prefix}${local}`, { [`${prefix}val`]: value });
129
+ if (old) edits.push({ from: old.start, to: old.end, text: xml });
130
+ else if (xml) {
131
+ const at = insertAt(local);
132
+ edits.push({ from: at, to: at, text: xml });
133
+ }
134
+ };
135
+ const isEmptyTag = (element: XmlElement) => element.openEnd === element.end;
136
+ /** `element`'s start tag with attribute `name` set, or gone. */
137
+ const withAttribute = (element: XmlElement, name: string, value: string | undefined) => {
138
+ const end = isEmptyTag(element) ? element.openEnd - 2 : element.openEnd - 1;
139
+ let tag = source.slice(element.start, end);
140
+ tag = tag.replace(new RegExp(`\\s${name}\\s*=\\s*("[^"]*"|'[^']*')`), "");
141
+ if (value !== undefined) tag += ` ${name}="${escapeAttribute(value)}"`;
142
+ edits.push({ from: element.start, to: end, text: tag });
143
+ };
144
+ /** `element` holding `inner` in place of its children (none: `inner` goes first among them). */
145
+ const withChildren = (element: XmlElement, inner: string, replace = true) => {
146
+ if (isEmptyTag(element))
147
+ edits.push({
148
+ from: element.openEnd - 2,
149
+ to: element.end,
150
+ text: `>${inner}</${element.name}>`,
151
+ });
152
+ else
153
+ edits.push({
154
+ from: element.openEnd,
155
+ to: replace ? element.closeStart : element.openEnd,
156
+ text: inner,
157
+ });
158
+ };
159
+ if (control.kind !== kept.kind) throw new DocxError("A content control cannot change kind");
160
+ if (control.alias !== kept.alias) child1("alias", control.alias);
161
+ if (control.tag !== kept.tag) child1("tag", control.tag);
162
+ if (control.lock !== kept.lock) child1("lock", control.lock);
163
+ const showing = control.placeholder?.showing === true;
164
+ if (showing !== (kept.placeholder?.showing === true)) {
165
+ const old = named("showingPlcHdr");
166
+ if (old) edits.push({ from: old.start, to: old.end, text: showing ? `<${old.name}/>` : "" });
167
+ else {
168
+ const at = insertAt("showingPlcHdr");
169
+ edits.push({ from: at, to: at, text: `<${prefix}showingPlcHdr/>` });
170
+ }
171
+ }
172
+ const list = named("dropDownList") ?? named("comboBox");
173
+ if (list && !same(control.items, kept.items)) withChildren(list, itemsXml(control.items ?? []));
174
+ const date = named("date");
175
+ if (date) {
176
+ if (control.date !== kept.date) withAttribute(date, `${prefix}fullDate`, control.date);
177
+ if (control.dateFormat !== kept.dateFormat) {
178
+ const format = child(date, "dateFormat");
179
+ const xml = el(`${prefix}dateFormat`, { [`${prefix}val`]: control.dateFormat });
180
+ if (format) edits.push({ from: format.start, to: format.end, text: xml });
181
+ else withChildren(date, xml, false);
182
+ }
183
+ }
184
+ const text = named("text");
185
+ if (text && (control.multiLine ?? false) !== (kept.multiLine ?? false))
186
+ withAttribute(text, `${prefix}multiLine`, control.multiLine ? "1" : undefined);
187
+ const box = children.find((c) => c.ns === W14 && c.local === "checkbox");
188
+ if (box && (control.checked ?? false) !== (kept.checked ?? false)) {
189
+ const checked = elements(box).find((c) => c.ns === W14 && c.local === "checked");
190
+ const name = checked?.name ?? box.name.replace("checkbox", "checked");
191
+ const boxPrefix = name.slice(0, name.indexOf(":") + 1);
192
+ const xml = el(name, { [`${boxPrefix}val`]: control.checked ? "1" : "0" });
193
+ if (checked) edits.push({ from: checked.start, to: checked.end, text: xml });
194
+ else withChildren(box, xml, false);
195
+ }
196
+ let out = source.slice(pr.start, pr.end);
197
+ // From the end; of two put at one place, the first made ends up first.
198
+ const order = edits.map((edit, i) => ({ edit, i }));
199
+ order.sort((a, b) => b.edit.from - a.edit.from || b.edit.to - a.edit.to || b.i - a.i);
200
+ for (const { edit } of order)
201
+ out = out.slice(0, edit.from - pr.start) + edit.text + out.slice(edit.to - pr.start);
202
+ return out;
203
+ }
204
+
205
+ export class ControlWriter {
206
+ readonly #written = new Set<string>();
207
+ /** Every `w:id` the document's controls hold. */
208
+ readonly #held = new Set<string>();
209
+ /** Above any id Word gives. */
210
+ #nextId = 2_000_000_000;
211
+
212
+ constructor(readonly controls: Readonly<Record<string, ControlJSON>>) {
213
+ for (const control of Object.values(controls)) {
214
+ const id = control.ext && ID.exec(control.ext)?.[2];
215
+ if (id) this.#held.add(id);
216
+ }
217
+ }
218
+
219
+ #freshId(): number {
220
+ while (this.#held.has(String(this.#nextId))) this.#nextId++;
221
+ return this.#nextId++;
222
+ }
223
+
224
+ /** What goes before a control's content, in the order `w:sdt` requires. */
225
+ parts(id: string, ns: Namespaces): { properties: string } {
226
+ if (!Object.hasOwn(this.controls, id))
227
+ throw new DocxError(`Content control ${id.slice(0, 64)} has no properties`);
228
+ const control = this.controls[id] as ControlJSON;
229
+ let properties = control.ext
230
+ ? this.#kept(control, ns)
231
+ : newProperties(control, this.#freshId(), ns);
232
+ // The same control written twice: an edit has separated its parts, and ids are unique.
233
+ if (this.#written.has(id))
234
+ properties = properties.replace(
235
+ ID,
236
+ (_, start, _id, end) => `${start}${this.#freshId()}${end}`,
237
+ );
238
+ this.#written.add(id);
239
+ return { properties };
240
+ }
241
+
242
+ #kept(control: ControlJSON, ns: Namespaces): string {
243
+ const { element, source } = fragment(control.ext as string, ns, "sdt");
244
+ const pr = child(element, "sdtPr");
245
+ const reread = controlProperties(element, { source, report: new Recorder() });
246
+ const end = child(element, "sdtEndPr");
247
+ const after = end ? source.slice(end.start, end.end) : "";
248
+ const whatItSays = (c: ControlJSON | undefined) => {
249
+ const { ext: _ext, deleted: _deleted, placeholder, ...rest } = c ?? ({} as ControlJSON);
250
+ const { text: _text, ...shown } = placeholder ?? {};
251
+ return { ...rest, placeholder: { ...shown, showing: shown.showing === true } };
252
+ };
253
+ if (reread && same(whatItSays(control), whatItSays(reread)))
254
+ return source.slice(element.openEnd, element.closeStart);
255
+ if (!pr || !reread || pr.openEnd === pr.end)
256
+ return newProperties(control, this.#freshId(), ns) + after;
257
+ return patched(source, pr, control, reread) + after;
258
+ }
259
+ }