@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
@@ -0,0 +1,411 @@
1
+ /**
2
+ * Pictures back to DrawingML (10.8, ADR-0006). A picture read from a file is its `w:drawing`
3
+ * as read, with only what the model changed written into it (size, alt text, title, the image's
4
+ * relationship): unchanged, it comes back byte for byte. A new one is a fresh inline drawing.
5
+ * Its image is the package's part when the resource names one there, else a new media part
6
+ * whose bytes come from the resource's `data:` URL or the app (`ExportOptions.resource`).
7
+ */
8
+
9
+ import type { FoliDocument, NodeJSON, ResourceJSON } from "@folijs/core";
10
+ import { A, R } from "../import/ooxml.js";
11
+ import { floatOf, PIC, WP } from "../import/pictures.js";
12
+ import type { DocxPackage } from "../package.js";
13
+ import { DocxError } from "../package.js";
14
+ import type { XmlElement } from "../xml.js";
15
+ import { ControlWriter } from "./controls.js";
16
+ import { same } from "./properties.js";
17
+ import { escapeAttribute, fragment, type Namespaces } from "./xmlout.js";
18
+
19
+ type Json = Record<string, unknown>;
20
+
21
+ const EXTENSIONS: Record<string, string> = {
22
+ "image/png": "png",
23
+ "image/jpeg": "jpeg",
24
+ "image/gif": "gif",
25
+ "image/bmp": "bmp",
26
+ "image/tiff": "tiff",
27
+ "image/svg+xml": "svg",
28
+ "image/x-emf": "emf",
29
+ "image/x-wmf": "wmf",
30
+ };
31
+
32
+ /** Every picture node of the document (body, comments and stories). */
33
+ function picturesOf(doc: FoliDocument): Json[] {
34
+ const out: Json[] = [];
35
+ const visit = (nodes: readonly NodeJSON[] | undefined) => {
36
+ for (const node of nodes ?? []) {
37
+ if (node.type === "picture") out.push((node.attrs ?? {}) as Json);
38
+ visit(node.content);
39
+ }
40
+ };
41
+ visit(doc.content.content);
42
+ for (const comment of doc.comments) visit(comment.content);
43
+ for (const story of Object.values(doc.stories ?? {})) visit(story.content.content);
44
+ return out;
45
+ }
46
+
47
+ /** A `data:` URL's bytes (base64 or percent-encoded), or undefined when it is not one. */
48
+ function dataBytes(url: string, key: string): Uint8Array | undefined {
49
+ const comma = url.indexOf(",");
50
+ if (!url.startsWith("data:") || comma < 0) return undefined;
51
+ const base64 = /;base64$/i.test(url.slice(0, comma));
52
+ const body = url.slice(comma + 1);
53
+ try {
54
+ if (!base64) return new TextEncoder().encode(decodeURIComponent(body));
55
+ const binary = atob(body.replace(/\s/g, ""));
56
+ return Uint8Array.from(binary, (c) => c.charCodeAt(0));
57
+ } catch (error) {
58
+ throw new DocxError(`The picture ${key} has a data: URL that cannot be read`, { cause: error });
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Whether the package's part is the resource's image: the part it names, an image of the size
64
+ * import recorded (a part of that name in another package is another image).
65
+ */
66
+ function ownPart(resource: ResourceJSON, pkg: DocxPackage | undefined): boolean {
67
+ const part = resource.part ? pkg?.part(`/${resource.part}`) : undefined;
68
+ return !!part && part.contentType.startsWith("image/") && part.data.length === resource.size;
69
+ }
70
+
71
+ /** The bytes of each picture's image the package does not hold, before anything is written. */
72
+ export async function pictureBytes(
73
+ doc: FoliDocument,
74
+ pkg: DocxPackage | undefined,
75
+ ask:
76
+ | ((
77
+ key: string,
78
+ resource: ResourceJSON,
79
+ ) => Promise<Uint8Array | undefined> | Uint8Array | undefined)
80
+ | undefined,
81
+ ): Promise<Map<string, Uint8Array>> {
82
+ const out = new Map<string, Uint8Array>();
83
+ for (const attrs of picturesOf(doc)) {
84
+ const key = String(attrs.resource);
85
+ if (out.has(key)) continue;
86
+ const resource = doc.resources?.[key];
87
+ if (!resource)
88
+ throw new DocxError(`Picture resource ${key} is not in the document's resources`);
89
+ if (ownPart(resource, pkg)) continue;
90
+ const bytes =
91
+ (resource.data ? dataBytes(resource.data, key) : undefined) ?? (await ask?.(key, resource));
92
+ if (!bytes) {
93
+ throw new DocxError(
94
+ resource.part
95
+ ? `The document refers to a part of its original package (the picture ${key}): export it with that package, or give its bytes (a data: URL, ExportOptions.resource)`
96
+ : `No bytes for the picture ${key}: give them as a data: URL or through ExportOptions.resource`,
97
+ );
98
+ }
99
+ out.set(key, bytes);
100
+ }
101
+ return out;
102
+ }
103
+
104
+ /** `wp:docPr` ids (any prefix) in XML text. */
105
+ const docPrIds = (xml: string) =>
106
+ [...xml.matchAll(/<(?:[\w.-]+:)?docPr\b[^>]*?\bid="(\d+)"/g)].map((m) => Number(m[1]));
107
+
108
+ /** The media parts pictures need, allocated as they are written, and the drawings' ids. */
109
+ export class Media {
110
+ readonly added: { name: string; data: Uint8Array; contentType: string }[] = [];
111
+ /** The document's content controls, written once across its parts. */
112
+ readonly controls: ControlWriter;
113
+ readonly #parts = new Map<string, string>();
114
+ /** Ids drawings Foli does not write hold (opaque content, headers and footers). */
115
+ readonly #reserved = new Set<number>();
116
+ /** Ids the pictures written so far took. */
117
+ readonly #claimed = new Set<number>();
118
+ #nextId: number;
119
+
120
+ constructor(
121
+ readonly doc: FoliDocument,
122
+ readonly pkg: DocxPackage | undefined,
123
+ readonly bytes: ReadonlyMap<string, Uint8Array>,
124
+ /** The parts rewritten from the model (their drawings are the document's). */
125
+ rewritten: readonly string[] = [],
126
+ ) {
127
+ this.controls = new ControlWriter(doc.controls ?? {});
128
+ // `wp:docPr` ids are unique in a document, across its parts: new ones above all of them.
129
+ let max = 0;
130
+ for (const attrs of picturesOf(doc))
131
+ for (const id of docPrIds(String(attrs.ext ?? ""))) max = Math.max(max, id);
132
+ const reserve = (xml: string) => {
133
+ for (const id of docPrIds(xml)) {
134
+ this.#reserved.add(id);
135
+ max = Math.max(max, id);
136
+ }
137
+ };
138
+ JSON.stringify([doc.content, doc.comments, doc.stories], (key, value) => {
139
+ if (key === "xml" && typeof value === "string") reserve(value);
140
+ return value;
141
+ });
142
+ const skip = new Set(rewritten.map((n) => n.toLowerCase()));
143
+ for (const part of pkg?.parts ?? [])
144
+ if (part.contentType.endsWith("+xml") && !skip.has(part.name.toLowerCase()))
145
+ reserve(new TextDecoder().decode(part.data));
146
+ this.#nextId = max + 1;
147
+ }
148
+
149
+ /** The part (absolute name) holding `key`'s image in the output package. */
150
+ part(key: string): string {
151
+ const known = this.#parts.get(key);
152
+ if (known) return known;
153
+ const resource = this.doc.resources?.[key] as ResourceJSON;
154
+ let name: string;
155
+ if (ownPart(resource, this.pkg)) name = `/${resource.part}`;
156
+ else {
157
+ const extension = EXTENSIONS[resource.contentType] ?? "bin";
158
+ const taken = (n: string) =>
159
+ this.pkg?.part(n) !== undefined || this.added.some((p) => p.name === n);
160
+ let i = this.added.length + 1;
161
+ while (taken(`/word/media/foli-image${i}.${extension}`)) i++;
162
+ name = `/word/media/foli-image${i}.${extension}`;
163
+ this.added.push({
164
+ name,
165
+ data: this.bytes.get(key) as Uint8Array,
166
+ contentType: resource.contentType,
167
+ });
168
+ }
169
+ this.#parts.set(key, name);
170
+ return name;
171
+ }
172
+
173
+ /** Takes `id` for a drawing written as read; false when another drawing has it already. */
174
+ claim(id: number | undefined): boolean {
175
+ if (id === undefined || this.#reserved.has(id) || this.#claimed.has(id)) return false;
176
+ this.#claimed.add(id);
177
+ return true;
178
+ }
179
+
180
+ freshId(): number {
181
+ while (this.#reserved.has(this.#nextId) || this.#claimed.has(this.#nextId)) this.#nextId++;
182
+ this.#claimed.add(this.#nextId);
183
+ return this.#nextId++;
184
+ }
185
+ }
186
+
187
+ const WP14 = "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing";
188
+
189
+ const kid = (el: XmlElement | undefined, ns: string, local: string) =>
190
+ el?.children.find(
191
+ (c): c is XmlElement => c.kind === "element" && c.ns === ns && c.local === local,
192
+ );
193
+
194
+ function descendants(el: XmlElement, test: (e: XmlElement) => boolean, out: XmlElement[] = []) {
195
+ for (const c of el.children) {
196
+ if (c.kind !== "element") continue;
197
+ if (test(c)) out.push(c);
198
+ descendants(c, test, out);
199
+ }
200
+ return out;
201
+ }
202
+
203
+ /** Edits to a source string: replace `[from, to)` with `text`. */
204
+ type Edit = { from: number; to: number; text: string };
205
+
206
+ const attrOf = (el: XmlElement | undefined, local: string, ns?: string) =>
207
+ el?.attributes.find((x) => x.local === local && (ns ? x.ns === ns : !x.prefix));
208
+
209
+ /** The edits setting (or, undefined, removing) attribute `local` (`ns`: none for plain) of `el`. */
210
+ function setAttr(
211
+ source: string,
212
+ el: XmlElement | undefined,
213
+ local: string,
214
+ value: string | undefined,
215
+ edits: Edit[],
216
+ ns?: string,
217
+ qualified = local,
218
+ ): void {
219
+ if (!el) return;
220
+ const a = attrOf(el, local, ns);
221
+ if (a) {
222
+ if (value === undefined) edits.push({ from: a.start - 1, to: a.end, text: "" });
223
+ else if (a.value !== value)
224
+ edits.push({ from: a.valueStart, to: a.valueEnd, text: escapeAttribute(value) });
225
+ } else if (value !== undefined) {
226
+ const at = source[el.openEnd - 2] === "/" ? el.openEnd - 2 : el.openEnd - 1;
227
+ edits.push({ from: at, to: at, text: ` ${qualified}="${escapeAttribute(value)}"` });
228
+ }
229
+ }
230
+
231
+ /** A part's relationships as a picture's drawing needs them. */
232
+ export interface PictureRelations {
233
+ /** The id relating image part `part` (`current` when it already does). */
234
+ image(part: string, current: string | undefined): string;
235
+ /** The part relationship `id` points to, if any. */
236
+ target(id: string): string | undefined;
237
+ }
238
+
239
+ /** `relativeFrom` values Word reads, horizontal and vertical (the first is the default). */
240
+ const RELATIVE = {
241
+ H: [
242
+ "column",
243
+ "margin",
244
+ "page",
245
+ "character",
246
+ "leftMargin",
247
+ "rightMargin",
248
+ "insideMargin",
249
+ "outsideMargin",
250
+ ],
251
+ V: [
252
+ "paragraph",
253
+ "margin",
254
+ "page",
255
+ "line",
256
+ "topMargin",
257
+ "bottomMargin",
258
+ "insideMargin",
259
+ "outsideMargin",
260
+ ],
261
+ };
262
+ const ALIGN = {
263
+ H: ["left", "right", "center", "inside", "outside"],
264
+ V: ["top", "bottom", "center", "inside", "outside"],
265
+ };
266
+
267
+ /** A `wp:positionH`/`wp:positionV` for a float's position, values Word cannot read replaced. */
268
+ function positionXml(axis: "H" | "V", position: Json | undefined): string {
269
+ const from = String(position?.relativeTo);
270
+ const relativeTo = RELATIVE[axis].includes(from) ? from : RELATIVE[axis][0];
271
+ const offset = position?.offset;
272
+ const align = String(position?.align);
273
+ const value =
274
+ typeof offset !== "number" && ALIGN[axis].includes(align)
275
+ ? `<wp:align>${align}</wp:align>`
276
+ : `<wp:posOffset>${typeof offset === "number" ? offset : 0}</wp:posOffset>`;
277
+ return `<wp:position${axis} relativeFrom="${relativeTo}">${value}</wp:position${axis}>`;
278
+ }
279
+
280
+ /** The `wp:wrap*` element for a float's wrapping. */
281
+ function wrapXml(float: Json): string {
282
+ const side = ["bothSides", "left", "right", "largest"].includes(String(float.side))
283
+ ? String(float.side)
284
+ : "bothSides";
285
+ switch (float.wrap) {
286
+ case "topAndBottom":
287
+ return "<wp:wrapTopAndBottom/>";
288
+ case "behind":
289
+ case "inFront":
290
+ return "<wp:wrapNone/>";
291
+ case "tight":
292
+ case "through": {
293
+ // The picture's rectangle as the wrap polygon (21600 is the full side).
294
+ const tag = float.wrap === "tight" ? "wp:wrapTight" : "wp:wrapThrough";
295
+ return (
296
+ `<${tag} wrapText="${side}"><wp:wrapPolygon edited="0"><wp:start x="0" y="0"/>` +
297
+ '<wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/><wp:lineTo x="21600" y="0"/>' +
298
+ `<wp:lineTo x="0" y="0"/></wp:wrapPolygon></${tag}>`
299
+ );
300
+ }
301
+ default:
302
+ return `<wp:wrapSquare wrapText="${side}"/>`;
303
+ }
304
+ }
305
+
306
+ /**
307
+ * The `w:drawing` for picture `attrs`, inline or floating (`wp:anchor`). From its `ext` with
308
+ * only what the model changed from it written in (size, alt text, title), its image's
309
+ * relationship, and a new id when another drawing of the document has its id; fresh when it
310
+ * has none, when its position or wrapping changed, or when it was read in another part or
311
+ * package and refers to other relationships (an SVG's PNG fallback, a click link) that mean
312
+ * something else here.
313
+ */
314
+ export function drawingXml(
315
+ attrs: Json,
316
+ relations: PictureRelations,
317
+ namespaces: Namespaces,
318
+ media: Media,
319
+ ): string {
320
+ const width = String(attrs.width);
321
+ const height = String(attrs.height);
322
+ const alt = (attrs.alt as string | null | undefined) ?? undefined;
323
+ const title = (attrs.title as string | null | undefined) ?? undefined;
324
+ const ext = typeof attrs.ext === "string" ? attrs.ext : undefined;
325
+ const part = media.part(String(attrs.resource));
326
+ const float = attrs.float && typeof attrs.float === "object" ? (attrs.float as Json) : undefined;
327
+ if (ext) {
328
+ const { element, source } = fragment(ext, namespaces);
329
+ const anchor = kid(element, WP, "anchor");
330
+ const inline = kid(element, WP, "inline") ?? anchor;
331
+ // shortcut: a float changed from the file's is written fresh, losing what only its `ext`
332
+ // holds (cropping, effects, z-order, lock, wrap polygon, an SVG part, a click link); edit
333
+ // `wp:positionH`/`wp:wrap*` in place once a command changes floats.
334
+ const sameFloat = same(anchor ? (floatOf(anchor) ?? false) : undefined, float);
335
+ const blip = descendants(element, (e) => e.ns === A && e.local === "blip")[0];
336
+ const current = attrOf(blip, "embed", R)?.value;
337
+ // Read against this part: its image id still points to its image here.
338
+ const here =
339
+ current !== undefined && relations.target(current)?.toLowerCase() === part.toLowerCase();
340
+ const others = descendants(element, () => true).some((e) =>
341
+ e.attributes.some((a) => a.ns === R && !(e === blip && a.local === "embed")),
342
+ );
343
+ if (blip && inline && sameFloat && (here || !others)) {
344
+ const edits: Edit[] = [];
345
+ setAttr(source, blip, "embed", relations.image(part, current), edits, R, "r:embed");
346
+ const extent = kid(inline, WP, "extent");
347
+ // Only what the model changed: values the file holds twice may differ, and stay so.
348
+ if (attrOf(extent, "cx")?.value !== width || attrOf(extent, "cy")?.value !== height) {
349
+ setAttr(source, extent, "cx", width, edits);
350
+ setAttr(source, extent, "cy", height, edits);
351
+ const spPr = descendants(element, (e) => e.ns === PIC && e.local === "spPr")[0];
352
+ const size = kid(kid(spPr, A, "xfrm"), A, "ext");
353
+ setAttr(source, size, "cx", width, edits);
354
+ setAttr(source, size, "cy", height, edits);
355
+ }
356
+ const docPr = kid(inline, WP, "docPr");
357
+ const cNvPr = descendants(element, (e) => e.ns === PIC && e.local === "cNvPr")[0];
358
+ for (const [local, value] of [
359
+ ["descr", alt],
360
+ ["title", title],
361
+ ] as const) {
362
+ if (attrOf(docPr, local)?.value === value) continue;
363
+ setAttr(source, docPr, local, value, edits);
364
+ setAttr(source, cNvPr, local, value, edits);
365
+ }
366
+ const id = attrOf(docPr, "id")?.value;
367
+ if (!media.claim(id === undefined ? undefined : Number(id))) {
368
+ // A copy of a drawing (pasted twice): its own ids, Word's anchor ids left to Word.
369
+ const fresh = String(media.freshId());
370
+ setAttr(source, docPr, "id", fresh, edits);
371
+ setAttr(source, cNvPr, "id", fresh, edits);
372
+ setAttr(source, inline, "anchorId", undefined, edits, WP14);
373
+ setAttr(source, inline, "editId", undefined, edits, WP14);
374
+ }
375
+ let out = source;
376
+ for (const edit of edits.sort((a, b) => b.from - a.from))
377
+ out = out.slice(0, edit.from) + edit.text + out.slice(edit.to);
378
+ const shift = edits.reduce((sum, e) => sum + e.text.length - (e.to - e.from), 0);
379
+ return out.slice(element.start, element.end + shift);
380
+ }
381
+ }
382
+ const embed = relations.image(part, undefined);
383
+ const id = media.freshId();
384
+ const descr = alt === undefined ? "" : ` descr="${escapeAttribute(alt)}"`;
385
+ const titled = title === undefined ? "" : ` title="${escapeAttribute(title)}"`;
386
+ const extent = `<wp:extent cx="${width}" cy="${height}"/><wp:effectExtent l="0" t="0" r="0" b="0"/>`;
387
+ const distance = (float?.distance ?? {}) as Json;
388
+ const dist = (side: string) => (typeof distance[side] === "number" ? distance[side] : 0);
389
+ const flag = (value: unknown) => (value === false ? "0" : "1");
390
+ const tag = float ? "wp:anchor" : "wp:inline";
391
+ // Namespaces declared where used: a part that has no pictures yet may not declare them.
392
+ const open = float
393
+ ? `<wp:anchor xmlns:wp="${WP}" distT="${dist("top")}" distB="${dist("bottom")}" ` +
394
+ `distL="${dist("left")}" distR="${dist("right")}" simplePos="0" relativeHeight="251658240" ` +
395
+ `behindDoc="${float.wrap === "behind" ? 1 : 0}" locked="0" ` +
396
+ `layoutInCell="${flag(float.layoutInCell)}" allowOverlap="${flag(float.allowOverlap)}">` +
397
+ `<wp:simplePos x="0" y="0"/>${positionXml("H", float.horizontal as Json)}` +
398
+ `${positionXml("V", float.vertical as Json)}${extent}${wrapXml(float)}`
399
+ : `<wp:inline xmlns:wp="${WP}" distT="0" distB="0" distL="0" distR="0">${extent}`;
400
+ return (
401
+ `<w:drawing>${open}` +
402
+ `<wp:docPr id="${id}" name="Picture ${id}"${descr}${titled}/>` +
403
+ `<wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="${A}" noChangeAspect="1"/></wp:cNvGraphicFramePr>` +
404
+ `<a:graphic xmlns:a="${A}"><a:graphicData uri="${PIC}"><pic:pic xmlns:pic="${PIC}">` +
405
+ `<pic:nvPicPr><pic:cNvPr id="${id}" name="Picture ${id}"${descr}${titled}/><pic:cNvPicPr/></pic:nvPicPr>` +
406
+ `<pic:blipFill><a:blip xmlns:r="${R}" r:embed="${embed}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>` +
407
+ `<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${width}" cy="${height}"/></a:xfrm>` +
408
+ `<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic>` +
409
+ `</${tag}></w:drawing>`
410
+ );
411
+ }
@@ -547,10 +547,47 @@ const SECTION_CHILDREN: Record<string, readonly string[]> = {
547
547
  pageSize: ["pgSz"],
548
548
  margins: ["pgMar"],
549
549
  titlePage: ["titlePg"],
550
+ columns: ["cols"],
551
+ pageNumbers: ["pgNumType"],
552
+ footnotes: ["footnotePr"],
553
+ endnotes: ["endnotePr"],
554
+ change: ["sectPrChange"],
550
555
  };
551
556
  const SECTION_MODELED = new Set(Object.values(SECTION_CHILDREN).flat());
552
557
 
553
- function sectionChild(name: string, value: unknown): string {
558
+ /** `w:footnotePr` or `w:endnotePr`: its children in CT_FtnProps order. */
559
+ function noteProperties(local: string, v: Json): string {
560
+ const s = (x: unknown) => (x === undefined ? undefined : String(x));
561
+ const children =
562
+ val("pos", s(v.position)) +
563
+ val("numFmt", s(v.format)) +
564
+ val("numStart", s(v.start)) +
565
+ val("numRestart", s(v.restart));
566
+ return children ? el(`w:${local}`, {}, children) : "";
567
+ }
568
+
569
+ /**
570
+ * The setup a tracked change records, every value it could have changed spelled out: Word finds
571
+ * no change in what the recorded `w:sectPr` leaves out (a `w:cols` without `w:num`, checked with
572
+ * Word 16). One read from a file stays as it was.
573
+ */
574
+ function previousSetup(previous: Json): Json {
575
+ if (previous.ext) return previous;
576
+ const size = (previous.pageSize ?? {}) as Json;
577
+ const columns = (previous.columns ?? {}) as Json;
578
+ return {
579
+ ...previous,
580
+ type: previous.type ?? "nextPage",
581
+ pageSize: { ...size, width: size.width ?? 12240, height: size.height ?? 15840 },
582
+ margins: previous.margins ?? {},
583
+ columns: {
584
+ ...columns,
585
+ count: columns.count ?? (columns.widths as unknown[] | undefined)?.length ?? 1,
586
+ },
587
+ };
588
+ }
589
+
590
+ function sectionChild(name: string, value: unknown, ns: Namespaces): string {
554
591
  if (value === undefined || value === null) return "";
555
592
  const v = value as Json;
556
593
  const s = (x: unknown) => (x === undefined || x === null ? undefined : String(x));
@@ -580,6 +617,35 @@ function sectionChild(name: string, value: unknown): string {
580
617
  });
581
618
  case "titlePage":
582
619
  return onOff("titlePg", value as boolean);
620
+ case "columns":
621
+ return el(
622
+ "w:cols",
623
+ {
624
+ "w:num": s(v.count),
625
+ "w:sep": v.separator as boolean | undefined,
626
+ "w:space": s(v.space),
627
+ "w:equalWidth": v.equalWidth as boolean | undefined,
628
+ },
629
+ ((v.widths ?? []) as Json[])
630
+ .map((col) => el("w:col", { "w:w": s(col.width), "w:space": s(col.space) }))
631
+ .join(""),
632
+ );
633
+ case "pageNumbers":
634
+ return el("w:pgNumType", { "w:fmt": s(v.format), "w:start": s(v.start) });
635
+ case "footnotes":
636
+ return noteProperties("footnotePr", v);
637
+ case "endnotes":
638
+ return noteProperties("endnotePr", v);
639
+ case "change":
640
+ return el(
641
+ "w:sectPrChange",
642
+ { "w:id": s(v.id), "w:author": s(v.author) ?? "", "w:date": s(v.date) },
643
+ // What the section was: never its header references (CT_SectPrBase has none).
644
+ sectionXml(
645
+ { ...previousSetup(v.previous as Json), headers: undefined, footers: undefined },
646
+ ns,
647
+ ),
648
+ );
583
649
  default:
584
650
  return "";
585
651
  }
@@ -597,7 +663,7 @@ export function sectionXml(section: Json, ns: Namespaces): string {
597
663
  generated.set(
598
664
  locals[0] as string,
599
665
  child(original, same(section[prop], reread[prop]), locals, () =>
600
- sectionChild(prop, section[prop]),
666
+ sectionChild(prop, section[prop], ns),
601
667
  ),
602
668
  );
603
669
  }
@@ -605,4 +671,4 @@ export function sectionXml(section: Json, ns: Namespaces): string {
605
671
  return `<w:sectPr${attributesOf(original)}>${children}</w:sectPr>`;
606
672
  }
607
673
 
608
- export { wrap };
674
+ export { child as keptOrFresh, reading, wrap };