@folijs/docx 0.0.0-stage → 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 (84) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +21 -0
  3. package/README.md +151 -2
  4. package/dist/export/content.d.ts +17 -0
  5. package/dist/export/content.d.ts.map +1 -0
  6. package/dist/export/content.js +165 -0
  7. package/dist/export/content.js.map +1 -0
  8. package/dist/export/index.d.ts +21 -0
  9. package/dist/export/index.d.ts.map +1 -0
  10. package/dist/export/index.js +360 -0
  11. package/dist/export/index.js.map +1 -0
  12. package/dist/export/parts.d.ts +24 -0
  13. package/dist/export/parts.d.ts.map +1 -0
  14. package/dist/export/parts.js +413 -0
  15. package/dist/export/parts.js.map +1 -0
  16. package/dist/export/properties.d.ts +39 -0
  17. package/dist/export/properties.d.ts.map +1 -0
  18. package/dist/export/properties.js +506 -0
  19. package/dist/export/properties.js.map +1 -0
  20. package/dist/export/xmlout.d.ts +63 -0
  21. package/dist/export/xmlout.d.ts.map +1 -0
  22. package/dist/export/xmlout.js +194 -0
  23. package/dist/export/xmlout.js.map +1 -0
  24. package/dist/import/content.d.ts +35 -0
  25. package/dist/import/content.d.ts.map +1 -0
  26. package/dist/import/content.js +370 -0
  27. package/dist/import/content.js.map +1 -0
  28. package/dist/import/index.d.ts +31 -0
  29. package/dist/import/index.d.ts.map +1 -0
  30. package/dist/import/index.js +106 -0
  31. package/dist/import/index.js.map +1 -0
  32. package/dist/import/ooxml.d.ts +39 -0
  33. package/dist/import/ooxml.d.ts.map +1 -0
  34. package/dist/import/ooxml.js +71 -0
  35. package/dist/import/ooxml.js.map +1 -0
  36. package/dist/import/parts.d.ts +35 -0
  37. package/dist/import/parts.d.ts.map +1 -0
  38. package/dist/import/parts.js +365 -0
  39. package/dist/import/parts.js.map +1 -0
  40. package/dist/import/properties.d.ts +50 -0
  41. package/dist/import/properties.d.ts.map +1 -0
  42. package/dist/import/properties.js +404 -0
  43. package/dist/import/properties.js.map +1 -0
  44. package/dist/import/report.d.ts +28 -0
  45. package/dist/import/report.d.ts.map +1 -0
  46. package/dist/import/report.js +42 -0
  47. package/dist/import/report.js.map +1 -0
  48. package/dist/index.d.ts +6 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +6 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/package.d.ts +70 -0
  53. package/dist/package.d.ts.map +1 -0
  54. package/dist/package.js +259 -0
  55. package/dist/package.js.map +1 -0
  56. package/dist/settings.d.ts +8 -0
  57. package/dist/settings.d.ts.map +1 -0
  58. package/dist/settings.js +72 -0
  59. package/dist/settings.js.map +1 -0
  60. package/dist/xml.d.ts +79 -0
  61. package/dist/xml.d.ts.map +1 -0
  62. package/dist/xml.js +384 -0
  63. package/dist/xml.js.map +1 -0
  64. package/dist/zip.d.ts +66 -0
  65. package/dist/zip.d.ts.map +1 -0
  66. package/dist/zip.js +356 -0
  67. package/dist/zip.js.map +1 -0
  68. package/package.json +36 -3
  69. package/src/export/content.ts +229 -0
  70. package/src/export/index.ts +473 -0
  71. package/src/export/parts.ts +545 -0
  72. package/src/export/properties.ts +608 -0
  73. package/src/export/xmlout.ts +225 -0
  74. package/src/import/content.ts +413 -0
  75. package/src/import/index.ts +139 -0
  76. package/src/import/ooxml.ts +78 -0
  77. package/src/import/parts.ts +423 -0
  78. package/src/import/properties.ts +507 -0
  79. package/src/import/report.ts +64 -0
  80. package/src/index.ts +24 -0
  81. package/src/package.ts +328 -0
  82. package/src/settings.ts +75 -0
  83. package/src/xml.ts +443 -0
  84. package/src/zip.ts +401 -0
@@ -0,0 +1,545 @@
1
+ /**
2
+ * `styles.xml`, `numbering.xml` and `comments.xml` from the envelope. With the original part,
3
+ * its prolog, root element and everything Foli does not model (latent styles, picture bullets,
4
+ * elements import could not use) stay as they were and where they were; each modeled element
5
+ * is written verbatim while unchanged, rewritten otherwise, left out when the editor removed
6
+ * it; new ones are added where Word expects them.
7
+ */
8
+
9
+ import type {
10
+ AbstractNumberingJSON,
11
+ CommentJSON,
12
+ FoliDocument,
13
+ NumberingInstanceJSON,
14
+ NumberingLevelJSON,
15
+ StyleJSON,
16
+ } from "@folijs/core";
17
+ import { attr, child, isW, W, W15 } from "../import/ooxml.js";
18
+ import {
19
+ abstractOf,
20
+ defaultsOf,
21
+ instanceOf,
22
+ level as levelOf,
23
+ styleOf,
24
+ usableStyle,
25
+ } from "../import/parts.js";
26
+ import { Recorder } from "../import/report.js";
27
+ import type { XmlElement, XmlNode } from "../xml.js";
28
+ import { blocksXml, type WriteContext } from "./content.js";
29
+ import { paragraphPropertiesXml, runPropertiesXml, same } from "./properties.js";
30
+ import {
31
+ attributesOf,
32
+ el,
33
+ escapeAttribute,
34
+ fragment,
35
+ merged,
36
+ type Namespaces,
37
+ onOff,
38
+ val,
39
+ } from "./xmlout.js";
40
+
41
+ type Json = Record<string, unknown>;
42
+ export interface OriginalPart {
43
+ readonly root: XmlElement;
44
+ readonly source: string;
45
+ }
46
+
47
+ const reading = (source: string) => ({ source, report: new Recorder() });
48
+ const text = (part: OriginalPart, node: XmlNode) => part.source.slice(node.start, node.end);
49
+
50
+ /** The original element's attributes except `skip`, as written (`w:customStyle`, `w15:tentative`…). */
51
+ function otherAttributes(
52
+ element: XmlElement | undefined,
53
+ source: string,
54
+ skip: readonly string[],
55
+ ): string {
56
+ if (!element) return "";
57
+ return element.attributes
58
+ .filter((a) => !skip.includes(a.name) && a.name !== "xmlns" && a.prefix !== "xmlns")
59
+ .map((a) => ` ${source.slice(a.start, a.end)}`)
60
+ .join("");
61
+ }
62
+
63
+ function original(ext: string | undefined, ns: Namespaces, expected?: string) {
64
+ return ext ? fragment(ext, ns, expected) : undefined;
65
+ }
66
+
67
+ function childSource(
68
+ o: { element: XmlElement; source: string } | undefined,
69
+ local: string,
70
+ ): string | undefined {
71
+ const c = o ? child(o.element, local) : undefined;
72
+ return c && o ? o.source.slice(c.start, c.end) : undefined;
73
+ }
74
+
75
+ /** A part's text: the original's prolog and root around `children`, or a new root. */
76
+ function wrapPart(
77
+ part: OriginalPart | undefined,
78
+ rootName: string,
79
+ ns: Namespaces,
80
+ children: string,
81
+ ): string {
82
+ if (!part) {
83
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<${rootName} ${ns.declarations}>${children}</${rootName}>`;
84
+ }
85
+ const { root, source } = part;
86
+ if (root.openEnd === root.end) {
87
+ // `<w:styles …/>`: opened to hold the children.
88
+ return `${source.slice(0, root.end - 2)}>${children}</${root.name}>${source.slice(root.end)}`;
89
+ }
90
+ return source.slice(0, root.openEnd) + children + source.slice(root.closeStart);
91
+ }
92
+
93
+ /**
94
+ * Walks the original part's children: `modeled` returns the matching envelope item for a child
95
+ * it models (or null when the editor removed it, undefined when the child is not one it
96
+ * models); `write` writes an item; `added` are written at `insertAt` (after the last child of
97
+ * that kind, or at the end).
98
+ */
99
+ function rebuild<T>(
100
+ part: OriginalPart | undefined,
101
+ modeled: (child: XmlElement) => T | null | undefined,
102
+ write: (item: T, child: XmlElement | undefined) => string,
103
+ added: readonly {
104
+ item: T;
105
+ after: (child: XmlElement) => boolean;
106
+ before?: (child: XmlElement) => boolean;
107
+ }[],
108
+ ): string {
109
+ const out: string[] = [];
110
+ const insertAfter: (number | undefined)[] = added.map(() => undefined);
111
+ const insertBefore: (number | undefined)[] = added.map(() => undefined);
112
+ for (const node of part?.root.children ?? []) {
113
+ if (node.kind !== "element") {
114
+ out.push(text(part as OriginalPart, node));
115
+ continue;
116
+ }
117
+ added.forEach((a, i) => {
118
+ if (insertBefore[i] === undefined && a.before?.(node)) insertBefore[i] = out.length;
119
+ });
120
+ const item = modeled(node);
121
+ if (item === undefined) out.push(text(part as OriginalPart, node));
122
+ else if (item !== null) out.push(write(item, node));
123
+ added.forEach((a, i) => {
124
+ if (a.after(node)) insertAfter[i] = out.length;
125
+ });
126
+ }
127
+ // Insert from the end so earlier positions stay valid.
128
+ const order = added
129
+ .map((a, i) => ({ a, at: insertAfter[i] ?? insertBefore[i] ?? out.length, i }))
130
+ .sort((x, y) => y.at - x.at || y.i - x.i);
131
+ for (const { a, at } of order) out.splice(at, 0, write(a.item, undefined));
132
+ return out.join("");
133
+ }
134
+
135
+ /** Items matched to the original elements they were read from, by `key` (their verbatim `ext`). */
136
+ function matcher<T>(
137
+ items: readonly T[],
138
+ key: (item: T) => string | undefined = (i) => (i as { ext?: string }).ext,
139
+ ) {
140
+ const byKey = new Map<string, T[]>();
141
+ for (const item of items) {
142
+ const k = key(item);
143
+ if (k !== undefined) byKey.set(k, [...(byKey.get(k) ?? []), item]);
144
+ }
145
+ const used = new Set<T>();
146
+ return {
147
+ take(k: string): T | undefined {
148
+ const item = byKey.get(k)?.find((i) => !used.has(i));
149
+ if (item) used.add(item);
150
+ return item;
151
+ },
152
+ rest: () => items.filter((i) => !used.has(i)),
153
+ };
154
+ }
155
+
156
+ // ---- styles ----------------------------------------------------------------------------------
157
+
158
+ const STYLE_ORDER = [
159
+ "name",
160
+ "aliases",
161
+ "basedOn",
162
+ "next",
163
+ "link",
164
+ "autoRedefine",
165
+ "hidden",
166
+ "uiPriority",
167
+ "semiHidden",
168
+ "unhideWhenUsed",
169
+ "qFormat",
170
+ "locked",
171
+ "personal",
172
+ "personalCompose",
173
+ "personalReply",
174
+ "rsid",
175
+ "pPr",
176
+ "rPr",
177
+ "tblPr",
178
+ "trPr",
179
+ "tcPr",
180
+ "tblStylePr",
181
+ ];
182
+
183
+ function styleXml(style: StyleJSON, ns: Namespaces): string {
184
+ const o = original(style.ext, ns);
185
+ if (o) {
186
+ const reread = styleOf(o.element, reading(o.source));
187
+ if (reread && same(normalizeStyle(style), normalizeStyle(reread))) return style.ext as string;
188
+ }
189
+ const reread = o ? styleOf(o.element, reading(o.source)) : undefined;
190
+ const generated = new Map<string, string>([
191
+ ["name", val("name", style.name)],
192
+ ["basedOn", val("basedOn", style.basedOn)],
193
+ ["next", val("next", style.next)],
194
+ ["link", val("link", style.link)],
195
+ [
196
+ "pPr",
197
+ o && same(style.paragraph ?? {}, reread?.paragraph ?? {})
198
+ ? (childSource(o, "pPr") ?? "")
199
+ : paragraphPropertiesXml(
200
+ { ...(style.paragraph ?? {}), ext: childSource(o, "pPr") },
201
+ ns,
202
+ "w:pPr",
203
+ false,
204
+ true,
205
+ ),
206
+ ],
207
+ [
208
+ "rPr",
209
+ runPropertiesXml(style.run ?? [], childSource(o, "rPr"), ns, "w:rPr", false, undefined, true),
210
+ ],
211
+ ]);
212
+ const children = merged(STYLE_ORDER, new Set(generated.keys()), generated, o);
213
+ const open =
214
+ el("w:style", {
215
+ "w:type": style.type,
216
+ "w:default": style.isDefault,
217
+ "w:styleId": style.id,
218
+ }).slice(0, -2) +
219
+ otherAttributes(o?.element, o?.source ?? "", ["w:type", "w:default", "w:styleId"]);
220
+ return `${open}>${children}</w:style>`;
221
+ }
222
+
223
+ /** A style as compared: run properties canonical, the verbatim element aside. */
224
+ function normalizeStyle(style: StyleJSON): Json {
225
+ return { ...style, ext: undefined, paragraph: style.paragraph ?? {}, run: style.run ?? [] };
226
+ }
227
+
228
+ function defaultsXml(defaults: FoliDocument["defaults"], ns: Namespaces): string {
229
+ const o = original(defaults.ext, ns);
230
+ if (o) {
231
+ const reread = defaultsOf(o.element, reading(o.source));
232
+ if (same({ ...defaults, ext: undefined }, { ...reread, ext: undefined }))
233
+ return defaults.ext as string;
234
+ }
235
+ const rPrDefault = o ? child(o.element, "rPrDefault") : undefined;
236
+ const pPrDefault = o ? child(o.element, "pPrDefault") : undefined;
237
+ const sub = (e: XmlElement | undefined) =>
238
+ e && o ? { element: e, source: o.source } : undefined;
239
+ const rPr = runPropertiesXml(
240
+ defaults.run ?? [],
241
+ childSource(sub(rPrDefault), "rPr"),
242
+ ns,
243
+ "w:rPr",
244
+ false,
245
+ undefined,
246
+ true,
247
+ );
248
+ const pPr = paragraphPropertiesXml(
249
+ { ...(defaults.paragraph ?? {}), ext: childSource(sub(pPrDefault), "pPr") },
250
+ ns,
251
+ "w:pPr",
252
+ false,
253
+ true,
254
+ );
255
+ return `<w:docDefaults${attributesOf(o)}>${rPr ? `<w:rPrDefault>${rPr}</w:rPrDefault>` : "<w:rPrDefault/>"}${pPr ? `<w:pPrDefault>${pPr}</w:pPrDefault>` : "<w:pPrDefault/>"}</w:docDefaults>`;
256
+ }
257
+
258
+ export function stylesXml(
259
+ doc: FoliDocument,
260
+ part: OriginalPart | undefined,
261
+ ns: Namespaces,
262
+ ): string {
263
+ const styles = matcher(doc.styles);
264
+ const hasDefaults = Object.keys(doc.defaults).length > 0;
265
+ let sawDefaults = false;
266
+ type Item = { kind: "defaults" } | { kind: "style"; style: StyleJSON };
267
+ const body = rebuild<Item>(
268
+ part,
269
+ (c) => {
270
+ if (isW(c, "docDefaults")) {
271
+ sawDefaults = true;
272
+ return hasDefaults ? { kind: "defaults" } : null;
273
+ }
274
+ if (!isW(c, "style") || !usableStyle(c) || !part) return undefined;
275
+ const style = styles.take(text(part, c));
276
+ return style ? { kind: "style", style } : null;
277
+ },
278
+ (item) => (item.kind === "defaults" ? defaultsXml(doc.defaults, ns) : styleXml(item.style, ns)),
279
+ [],
280
+ );
281
+ const added = styles
282
+ .rest()
283
+ .map((s) => styleXml(s, ns))
284
+ .join("");
285
+ const defaults = hasDefaults && !sawDefaults ? defaultsXml(doc.defaults, ns) : "";
286
+ return wrapPart(part, "w:styles", ns, defaults + body + added);
287
+ }
288
+
289
+ // ---- numbering -------------------------------------------------------------------------------
290
+
291
+ const LEVEL_ORDER = [
292
+ "start",
293
+ "numFmt",
294
+ "lvlRestart",
295
+ "pStyle",
296
+ "isLgl",
297
+ "suff",
298
+ "lvlText",
299
+ "lvlPicBulletId",
300
+ "legacy",
301
+ "lvlJc",
302
+ "pPr",
303
+ "rPr",
304
+ ];
305
+
306
+ function levelXml(level: NumberingLevelJSON, ns: Namespaces): string {
307
+ const o = original(level.ext, ns);
308
+ const reread = o ? levelOf(o.element, reading(o.source)) : undefined;
309
+ if (o && reread && same({ ...level, ext: undefined }, { ...reread, ext: undefined }))
310
+ return level.ext as string;
311
+ const s = (x: unknown) => (x === undefined ? undefined : String(x));
312
+ const generated = new Map<string, string>([
313
+ ["start", val("start", s(level.start))],
314
+ ["numFmt", val("numFmt", level.format)],
315
+ ["lvlRestart", val("lvlRestart", s(level.restart))],
316
+ ["pStyle", val("pStyle", level.style)],
317
+ ["isLgl", onOff("isLgl", level.legal)],
318
+ ["suff", val("suff", level.suffix)],
319
+ ["lvlText", level.text === undefined ? "" : el("w:lvlText", { "w:val": level.text })],
320
+ ["lvlJc", val("lvlJc", level.justification)],
321
+ [
322
+ "pPr",
323
+ o && same(level.paragraph ?? {}, reread?.paragraph ?? {})
324
+ ? (childSource(o, "pPr") ?? "")
325
+ : paragraphPropertiesXml(
326
+ { ...(level.paragraph ?? {}), ext: childSource(o, "pPr") },
327
+ ns,
328
+ "w:pPr",
329
+ false,
330
+ true,
331
+ ),
332
+ ],
333
+ [
334
+ "rPr",
335
+ runPropertiesXml(level.run ?? [], childSource(o, "rPr"), ns, "w:rPr", false, undefined, true),
336
+ ],
337
+ ]);
338
+ const children = merged(LEVEL_ORDER, new Set(generated.keys()), generated, o);
339
+ const open =
340
+ el("w:lvl", { "w:ilvl": level.level }).slice(0, -2) +
341
+ otherAttributes(o?.element, o?.source ?? "", ["w:ilvl"]);
342
+ return `${open}>${children}</w:lvl>`;
343
+ }
344
+
345
+ const ABSTRACT_ORDER = [
346
+ "nsid",
347
+ "multiLevelType",
348
+ "tmpl",
349
+ "name",
350
+ "styleLink",
351
+ "numStyleLink",
352
+ "lvl",
353
+ ];
354
+
355
+ function abstractXml(abstract: AbstractNumberingJSON, ns: Namespaces): string {
356
+ const o = original(abstract.ext, ns);
357
+ const reread = o ? abstractOf(o.element, reading(o.source)) : undefined;
358
+ if (o && reread && same({ ...abstract, ext: undefined }, { ...reread, ext: undefined }))
359
+ return abstract.ext as string;
360
+ const generated = new Map<string, string>([
361
+ ["multiLevelType", val("multiLevelType", abstract.multiLevelType)],
362
+ ["styleLink", val("styleLink", abstract.styleLink)],
363
+ ["numStyleLink", val("numStyleLink", abstract.numStyleLink)],
364
+ ["lvl", abstract.levels.map((l) => levelXml(l, ns)).join("")],
365
+ ]);
366
+ const children = merged(ABSTRACT_ORDER, new Set(generated.keys()), generated, o);
367
+ const open =
368
+ el("w:abstractNum", { "w:abstractNumId": abstract.id }).slice(0, -2) +
369
+ otherAttributes(o?.element, o?.source ?? "", ["w:abstractNumId"]);
370
+ return `${open}>${children}</w:abstractNum>`;
371
+ }
372
+
373
+ function instanceXml(instance: NumberingInstanceJSON, ns: Namespaces): string {
374
+ const o = original(instance.ext, ns);
375
+ const reread = o ? instanceOf(o.element, reading(o.source)) : undefined;
376
+ if (o && reread && same({ ...instance, ext: undefined }, { ...reread, ext: undefined }))
377
+ return instance.ext as string;
378
+ const overrides = (instance.overrides ?? [])
379
+ .map(
380
+ (ov) =>
381
+ `<w:lvlOverride w:ilvl="${ov.level}">${ov.start === undefined ? "" : val("startOverride", String(ov.start))}${ov.definition ? levelXml({ ...ov.definition, level: ov.level }, ns) : ""}</w:lvlOverride>`,
382
+ )
383
+ .join("");
384
+ const generated = new Map<string, string>([
385
+ ["abstractNumId", val("abstractNumId", String(instance.abstract))],
386
+ ["lvlOverride", overrides],
387
+ ]);
388
+ const children = merged(
389
+ ["abstractNumId", "lvlOverride"],
390
+ new Set(generated.keys()),
391
+ generated,
392
+ o,
393
+ );
394
+ const open =
395
+ el("w:num", { "w:numId": instance.id }).slice(0, -2) +
396
+ otherAttributes(o?.element, o?.source ?? "", ["w:numId"]);
397
+ return `${open}>${children}</w:num>`;
398
+ }
399
+
400
+ export function numberingXml(
401
+ doc: FoliDocument,
402
+ part: OriginalPart | undefined,
403
+ ns: Namespaces,
404
+ ): string {
405
+ const abstracts = matcher(doc.numbering.abstracts);
406
+ const instances = matcher(doc.numbering.instances);
407
+ const silent = reading(part?.source ?? "");
408
+ type Item =
409
+ | { kind: "abstract"; a: AbstractNumberingJSON }
410
+ | { kind: "num"; n: NumberingInstanceJSON };
411
+ // Taken before the walk: added items are known before their insertion point is.
412
+ const walk = (c: XmlElement): Item | null | undefined => {
413
+ if (!part) return undefined;
414
+ if (isW(c, "abstractNum")) {
415
+ if (!abstractOf(c, silent)) return undefined;
416
+ const a = abstracts.take(text(part, c));
417
+ return a ? { kind: "abstract", a } : null;
418
+ }
419
+ if (isW(c, "num")) {
420
+ if (!instanceOf(c, silent)) return undefined;
421
+ const n = instances.take(text(part, c));
422
+ return n ? { kind: "num", n } : null;
423
+ }
424
+ return undefined;
425
+ };
426
+ // A first pass decides what is matched; the second writes (rebuild needs `added` up front).
427
+ for (const node of part?.root.children ?? []) if (node.kind === "element") walk(node);
428
+ const newAbstracts = abstracts.rest();
429
+ const newInstances = instances.rest();
430
+ const again = {
431
+ abstracts: matcher(doc.numbering.abstracts),
432
+ instances: matcher(doc.numbering.instances),
433
+ };
434
+ const body = rebuild<Item>(
435
+ part,
436
+ (c) => {
437
+ if (!part) return undefined;
438
+ if (isW(c, "abstractNum")) {
439
+ if (!abstractOf(c, silent)) return undefined;
440
+ const a = again.abstracts.take(text(part, c));
441
+ return a ? { kind: "abstract", a } : null;
442
+ }
443
+ if (isW(c, "num")) {
444
+ if (!instanceOf(c, silent)) return undefined;
445
+ const n = again.instances.take(text(part, c));
446
+ return n ? { kind: "num", n } : null;
447
+ }
448
+ return undefined;
449
+ },
450
+ (item) => (item.kind === "abstract" ? abstractXml(item.a, ns) : instanceXml(item.n, ns)),
451
+ [
452
+ // CT_Numbering: numPicBullet*, abstractNum*, num*, numIdMacAtCleanup.
453
+ ...newAbstracts.map((a) => ({
454
+ item: { kind: "abstract", a } as Item,
455
+ after: (c: XmlElement) => isW(c, "abstractNum") || isW(c, "numPicBullet"),
456
+ before: (c: XmlElement) => isW(c, "num") || isW(c, "numIdMacAtCleanup"),
457
+ })),
458
+ ...newInstances.map((n) => ({
459
+ item: { kind: "num", n } as Item,
460
+ after: (c: XmlElement) => isW(c, "num") || isW(c, "abstractNum") || isW(c, "numPicBullet"),
461
+ before: (c: XmlElement) => isW(c, "numIdMacAtCleanup"),
462
+ })),
463
+ ],
464
+ );
465
+ return wrapPart(part, "w:numbering", ns, body);
466
+ }
467
+
468
+ // ---- comments ---------------------------------------------------------------------------------
469
+
470
+ /** A comment's start tag: as written while author, initials and date are what was read from it. */
471
+ function commentStart(comment: CommentJSON, ns: Namespaces): string {
472
+ if (comment.ext) {
473
+ const o = fragment(`${comment.ext}</w:comment>`, ns, "comment");
474
+ {
475
+ const author = attr(o.element, "author") ?? "";
476
+ const initials = attr(o.element, "initials");
477
+ const date = attr(o.element, "date");
478
+ const readDate = date && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(date) ? date : undefined;
479
+ if (
480
+ Number(attr(o.element, "id")) === comment.id &&
481
+ author.slice(0, 255) === comment.author &&
482
+ (initials !== undefined && initials.length <= 9 ? initials : undefined) ===
483
+ comment.initials &&
484
+ readDate === comment.date
485
+ ) {
486
+ return comment.ext;
487
+ }
488
+ }
489
+ }
490
+ return el("w:comment", {
491
+ "w:id": comment.id,
492
+ "w:author": comment.author,
493
+ "w:date": comment.date,
494
+ "w:initials": comment.initials,
495
+ }).replace(/\/>$/, ">");
496
+ }
497
+
498
+ export function commentsXml(
499
+ doc: FoliDocument,
500
+ part: OriginalPart | undefined,
501
+ context: WriteContext,
502
+ ): string {
503
+ // A comment is matched to the element it was read from by its start tag and id.
504
+ const comments = matcher(doc.comments, (c) => (c.ext ? `${c.ext}#${c.id}` : undefined));
505
+ const write = (c: CommentJSON) =>
506
+ `${commentStart(c, context.namespaces)}${blocksXml(c.content, context)}</w:comment>`;
507
+ const body = rebuild<CommentJSON>(
508
+ part,
509
+ (c) => {
510
+ if (!part || !isW(c, "comment")) return undefined;
511
+ const id = Number(attr(c, "id"));
512
+ if (!Number.isInteger(id) || id < 0 || id > 2_147_483_647) return undefined;
513
+ const start = part.source.slice(c.start, c.openEnd);
514
+ return comments.take(`${start}#${id}`) ?? null;
515
+ },
516
+ write,
517
+ [],
518
+ );
519
+ const added = comments.rest().map(write).join("");
520
+ return wrapPart(part, "w:comments", context.namespaces, body + added);
521
+ }
522
+
523
+ /**
524
+ * `commentsExtended.xml` for the comments' replies and resolved state, keyed by the `w14:paraId`
525
+ * of each comment's last paragraph (comments without one cannot be listed).
526
+ */
527
+ export function commentsExtendedXml(doc: FoliDocument, part: OriginalPart | undefined): string {
528
+ const paraId = (c: CommentJSON) => {
529
+ const last = c.content.filter((b) => b.type === "paragraph").at(-1);
530
+ return (last?.attrs?.attributes as Record<string, string> | undefined)?.["w14:paraId"];
531
+ };
532
+ const byId = new Map(doc.comments.map((c) => [c.id, c]));
533
+ const entries = doc.comments
534
+ .filter((c) => paraId(c))
535
+ .map((c) => {
536
+ const parent = c.parent === undefined ? undefined : byId.get(c.parent);
537
+ const parentId = parent ? paraId(parent) : undefined;
538
+ return `<w15:commentEx w15:paraId="${escapeAttribute(paraId(c) as string)}"${parentId ? ` w15:paraIdParent="${escapeAttribute(parentId)}"` : ""} w15:done="${c.done ? 1 : 0}"/>`;
539
+ })
540
+ .join("");
541
+ if (!part) {
542
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<w15:commentsEx xmlns:w15="${W15}" xmlns:w="${W}">${entries}</w15:commentsEx>`;
543
+ }
544
+ return wrapPart(part, part.root.name, { declarations: "", prefixes: new Set() }, entries);
545
+ }