@folijs/docx 0.5.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 (74) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +42 -14
  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 +5 -0
  8. package/dist/export/content.d.ts.map +1 -1
  9. package/dist/export/content.js +155 -22
  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.map +1 -1
  16. package/dist/export/index.js +214 -18
  17. package/dist/export/index.js.map +1 -1
  18. package/dist/export/parts.d.ts +9 -1
  19. package/dist/export/parts.d.ts.map +1 -1
  20. package/dist/export/parts.js +56 -2
  21. package/dist/export/parts.js.map +1 -1
  22. package/dist/export/pictures.d.ts +3 -0
  23. package/dist/export/pictures.d.ts.map +1 -1
  24. package/dist/export/pictures.js +15 -2
  25. package/dist/export/pictures.js.map +1 -1
  26. package/dist/export/properties.d.ts.map +1 -1
  27. package/dist/export/properties.js +56 -2
  28. package/dist/export/properties.js.map +1 -1
  29. package/dist/import/content.d.ts +11 -1
  30. package/dist/import/content.d.ts.map +1 -1
  31. package/dist/import/content.js +205 -17
  32. package/dist/import/content.js.map +1 -1
  33. package/dist/import/controls.d.ts +14 -0
  34. package/dist/import/controls.d.ts.map +1 -0
  35. package/dist/import/controls.js +123 -0
  36. package/dist/import/controls.js.map +1 -0
  37. package/dist/import/index.d.ts +10 -2
  38. package/dist/import/index.d.ts.map +1 -1
  39. package/dist/import/index.js +73 -12
  40. package/dist/import/index.js.map +1 -1
  41. package/dist/import/ooxml.d.ts +4 -0
  42. package/dist/import/ooxml.d.ts.map +1 -1
  43. package/dist/import/ooxml.js +4 -0
  44. package/dist/import/ooxml.js.map +1 -1
  45. package/dist/import/parts.js +1 -1
  46. package/dist/import/parts.js.map +1 -1
  47. package/dist/import/properties.d.ts +2 -0
  48. package/dist/import/properties.d.ts.map +1 -1
  49. package/dist/import/properties.js +55 -0
  50. package/dist/import/properties.js.map +1 -1
  51. package/dist/import/stories.d.ts +19 -0
  52. package/dist/import/stories.d.ts.map +1 -0
  53. package/dist/import/stories.js +119 -0
  54. package/dist/import/stories.js.map +1 -0
  55. package/dist/settings.d.ts +18 -4
  56. package/dist/settings.d.ts.map +1 -1
  57. package/dist/settings.js +173 -26
  58. package/dist/settings.js.map +1 -1
  59. package/package.json +3 -3
  60. package/src/export/balance.ts +113 -0
  61. package/src/export/content.ts +200 -19
  62. package/src/export/controls.ts +259 -0
  63. package/src/export/index.ts +254 -17
  64. package/src/export/parts.ts +79 -2
  65. package/src/export/pictures.ts +8 -2
  66. package/src/export/properties.ts +68 -2
  67. package/src/import/content.ts +220 -17
  68. package/src/import/controls.ts +137 -0
  69. package/src/import/index.ts +84 -11
  70. package/src/import/ooxml.ts +4 -0
  71. package/src/import/parts.ts +1 -1
  72. package/src/import/properties.ts +59 -0
  73. package/src/import/stories.ts +122 -0
  74. package/src/settings.ts +191 -27
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Fields and inline content controls as an edit can leave them, made writable (ADR-0007). A field
3
+ * part without its partner is dropped, with the code of a field that lost its end, so the code
4
+ * never becomes text; the result stays. An inline control a paragraph split runs over becomes one
5
+ * control per paragraph, as `w:sdt` cannot cross a paragraph; ends without a partner are dropped
6
+ * when written.
7
+ */
8
+ import type { FoliDocument, NodeJSON } from "@folijs/core";
9
+ import type { DocxPackage } from "../package.js";
10
+
11
+ function paragraphsOf(nodes: readonly NodeJSON[], out: NodeJSON[] = []): NodeJSON[] {
12
+ for (const node of nodes) {
13
+ if (node.type === "paragraph") out.push(node);
14
+ else if (node.content) paragraphsOf(node.content, out);
15
+ }
16
+ return out;
17
+ }
18
+
19
+ function balanceFields(paragraphs: readonly NodeJSON[]): void {
20
+ const drop = new Set<NodeJSON>();
21
+ const open: NodeJSON[][] = [];
22
+ for (const paragraph of paragraphs) {
23
+ for (const node of paragraph.content ?? []) {
24
+ if (node.type === "fieldStart") open.push([node]);
25
+ else if (node.type === "fieldCode" || node.type === "fieldSeparator") {
26
+ const field = open.at(-1);
27
+ if (field) field.push(node);
28
+ else drop.add(node);
29
+ } else if (node.type === "fieldEnd" && !open.pop()) drop.add(node);
30
+ }
31
+ }
32
+ for (const field of open) for (const node of field) drop.add(node);
33
+ if (!drop.size) return;
34
+ for (const paragraph of paragraphs)
35
+ if (paragraph.content) paragraph.content = paragraph.content.filter((n) => !drop.has(n));
36
+ }
37
+
38
+ function balanceControls(paragraphs: readonly NodeJSON[]): void {
39
+ const endsLeft = new Map<unknown, number>();
40
+ const ends = (paragraph: NodeJSON) =>
41
+ (paragraph.content ?? []).filter((n) => n.type === "controlEnd");
42
+ for (const paragraph of paragraphs)
43
+ for (const end of ends(paragraph))
44
+ endsLeft.set(end.attrs?.id, (endsLeft.get(end.attrs?.id) ?? 0) + 1);
45
+ if (!endsLeft.size) return;
46
+ let open: unknown[] = [];
47
+ for (const paragraph of paragraphs) {
48
+ const content: NodeJSON[] = open.map(
49
+ (id) => ({ type: "controlStart", attrs: { id } }) as NodeJSON,
50
+ );
51
+ const here = [...open];
52
+ for (const node of paragraph.content ?? []) {
53
+ content.push(node);
54
+ const id = node.attrs?.id;
55
+ if (node.type === "controlStart") here.push(id);
56
+ else if (node.type === "controlEnd") {
57
+ endsLeft.set(id, (endsLeft.get(id) as number) - 1);
58
+ const at = here.lastIndexOf(id);
59
+ if (at >= 0) here.splice(at, 1);
60
+ }
61
+ }
62
+ // Innermost first; a control with no end further on has lost it, and its start is dropped.
63
+ open = here.filter((id) => (endsLeft.get(id) ?? 0) > 0);
64
+ for (const id of [...open].reverse())
65
+ content.push({ type: "controlEnd", attrs: { id } } as NodeJSON);
66
+ if (content.length) paragraph.content = content;
67
+ }
68
+ }
69
+
70
+ /** Whether the field characters of a part's XML open and close properly. */
71
+ function fieldsWhole(xml: string): boolean {
72
+ let depth = 0;
73
+ for (const [, type] of xml.matchAll(/fldCharType\s*=\s*["'](begin|separate|end)["']/g)) {
74
+ if (type === "begin") depth++;
75
+ else if (depth === 0) return false;
76
+ else if (type === "end") depth--;
77
+ }
78
+ return depth === 0;
79
+ }
80
+
81
+ /** Whether content kept verbatim among `nodes` holds field characters. */
82
+ function holdsVerbatimField(nodes: readonly NodeJSON[]): boolean {
83
+ return nodes.some(
84
+ (node) =>
85
+ (typeof node.attrs?.xml === "string" && node.attrs.xml.includes("fldChar")) ||
86
+ holdsVerbatimField(node.content ?? []),
87
+ );
88
+ }
89
+
90
+ /**
91
+ * `doc` (a validated copy, changed in place) with its fields and inline controls writable. Field
92
+ * parts are only repaired where an edit can be what broke them: not in a package holding broken
93
+ * fields of its own (Word reads those in its way), nor where verbatim content holds field
94
+ * characters, whose partners the model cannot see.
95
+ */
96
+ export function balanced(doc: FoliDocument, original?: DocxPackage): FoliDocument {
97
+ const packageWhole =
98
+ !original ||
99
+ original.parts
100
+ .filter((part) => /^\/word\/[^/]+\.xml$/.test(part.name))
101
+ .every((part) => fieldsWhole(original.text(part.name)));
102
+ const trees = [
103
+ doc.content.content ?? [],
104
+ ...doc.comments.map((c) => c.content),
105
+ ...Object.values(doc.stories ?? {}).map((s) => s.content.content ?? []),
106
+ ];
107
+ for (const tree of trees) {
108
+ const paragraphs = paragraphsOf(tree);
109
+ if (packageWhole && !holdsVerbatimField(tree)) balanceFields(paragraphs);
110
+ balanceControls(paragraphs);
111
+ }
112
+ return doc;
113
+ }
@@ -5,6 +5,7 @@
5
5
 
6
6
  import type { MarkJSON, NodeJSON } from "@folijs/core";
7
7
  import { DocxError } from "../package.js";
8
+ import type { ControlWriter } from "./controls.js";
8
9
  import { paragraphPropertiesXml, runPropertiesXml, same } from "./properties.js";
9
10
  import {
10
11
  cellPropertiesXml,
@@ -13,7 +14,7 @@ import {
13
14
  rowPropertiesXml,
14
15
  tablePropertiesXml,
15
16
  } from "./tables.js";
16
- import { bagXml, el, escapeText, fragment, type Namespaces } from "./xmlout.js";
17
+ import { bagXml, el, escapeAttribute, escapeText, fragment, type Namespaces } from "./xmlout.js";
17
18
 
18
19
  export interface WriteContext {
19
20
  readonly namespaces: Namespaces;
@@ -24,6 +25,10 @@ export interface WriteContext {
24
25
  readonly hyperlink: (href: string, id: string | undefined) => string;
25
26
  /** A picture's `w:drawing` (its image related to the part, its media part allocated). */
26
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;
27
32
  }
28
33
 
29
34
  type Json = Record<string, unknown>;
@@ -35,15 +40,36 @@ function verbatim(xml: unknown, context: WriteContext): string {
35
40
  return text;
36
41
  }
37
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
+
38
66
  export function blocksXml(blocks: readonly NodeJSON[], context: WriteContext): string {
39
- let out = "";
40
- for (const block of blocks) {
41
- if (block.type === "paragraph") out += paragraphXml(block, context);
42
- else if (block.type === "opaqueBlock") out += verbatim(block.attrs?.xml, context);
43
- else if (block.type === "table") out += tableXml(block, context);
44
- else notYet(block);
45
- }
46
- 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
+ });
47
73
  }
48
74
 
49
75
  /** A table: its properties, its grid, then each row's exceptions, properties and cells. */
@@ -51,15 +77,14 @@ function tableXml(table: NodeJSON, context: WriteContext): string {
51
77
  const ns = context.namespaces;
52
78
  const attrs = (table.attrs ?? {}) as Json;
53
79
  let out = `<w:tbl>${tablePropertiesXml(attrs, ns)}${gridXml(attrs, ns)}`;
54
- for (const row of table.content ?? []) {
80
+ out += inControls(table.content ?? [], 0, context, (row) => {
55
81
  const r = (row.attrs ?? {}) as Json;
56
- out += `<w:tr${bagXml(r.attributes, ns)}>${exceptionsXml(r.exceptions, ns)}${rowPropertiesXml(r, ns)}`;
57
- for (const cell of row.content ?? []) {
82
+ const cells = inControls(row.content ?? [], 0, context, (cell) => {
58
83
  const c = (cell.attrs ?? {}) as Json;
59
- out += `<w:tc>${cellPropertiesXml(c, ns)}${blocksXml(cell.content ?? [], context)}</w:tc>`;
60
- }
61
- out += "</w:tr>";
62
- }
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
+ });
63
88
  return `${out}</w:tbl>`;
64
89
  }
65
90
 
@@ -95,8 +120,113 @@ function grouped(
95
120
  return out;
96
121
  }
97
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
+
98
224
  /** Hyperlinks outermost, then insertions (or move destinations), then deletions (or move sources). */
99
- function inlinesXml(nodes: readonly NodeJSON[], context: WriteContext): string {
225
+ function plainInlinesXml(
226
+ nodes: readonly NodeJSON[],
227
+ context: WriteContext,
228
+ outerDeleted: boolean,
229
+ ): string {
100
230
  return grouped(
101
231
  nodes,
102
232
  (n) => markOf(n, "link"),
@@ -117,7 +247,7 @@ function inlinesXml(nodes: readonly NodeJSON[], context: WriteContext): string {
117
247
  del as MarkJSON | undefined,
118
248
  "del",
119
249
  "moveFrom",
120
- runsXml(g2, !!del, context),
250
+ runsXml(g2, !!del || outerDeleted, context),
121
251
  context,
122
252
  ),
123
253
  ),
@@ -175,7 +305,13 @@ function inRun(node: NodeJSON): boolean {
175
305
  "pageBreak",
176
306
  "columnBreak",
177
307
  "commentReference",
308
+ "noteReference",
309
+ "noteMark",
178
310
  "picture",
311
+ "fieldStart",
312
+ "fieldCode",
313
+ "fieldSeparator",
314
+ "fieldEnd",
179
315
  ].includes(node.type);
180
316
  }
181
317
 
@@ -218,13 +354,32 @@ function markerXml(node: NodeJSON, context: WriteContext): string {
218
354
  return tag("w:commentRangeStart", { "w:id": String(a.id) });
219
355
  case "commentEnd":
220
356
  return tag("w:commentRangeEnd", { "w:id": String(a.id) });
357
+ case ELEMENT:
358
+ return String(a.xml);
221
359
  case "opaqueInline":
222
360
  return verbatim(a.xml, context);
361
+ // Their partner is gone (an edit): the content around them stays.
362
+ case "controlStart":
363
+ case "controlEnd":
364
+ return "";
223
365
  default:
224
366
  return notYet(node);
225
367
  }
226
368
  }
227
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
+
228
383
  /**
229
384
  * Text as `w:t` (or `w:delText`), with tabs and Word's special hyphens as their elements, and
230
385
  * line ends and vertical tabs (Office's line break in pasted text) as breaks.
@@ -263,11 +418,37 @@ function runContentXml(node: NodeJSON, deleted: boolean, context: WriteContext):
263
418
  return el("w:br", { "w:type": "column" });
264
419
  case "commentReference":
265
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
+ }
266
447
  case "opaqueInline":
267
448
  return verbatim(a.xml, context);
268
449
  case "picture":
269
450
  return context.picture(a);
270
451
  default:
271
- return "";
452
+ return notYet(node);
272
453
  }
273
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
+ }