@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,267 @@
1
+ /**
2
+ * Word's table property elements (`w:tblPr`, `w:tblPrEx`, `w:trPr`, `w:tcPr`, a table style's
3
+ * `w:tblStylePr`) to schema v4 attributes. As for paragraphs, each value is checked on its own
4
+ * against the schema: one the model cannot hold is reported and stays in the element's `ext`.
5
+ */
6
+
7
+ import { type AttributeSpec, schema, TABLE_CONDITIONS } from "@folijs/core";
8
+ import type { XmlElement } from "../xml.js";
9
+ import { attr, child, compact, elements, integer, toggle } from "./ooxml.js";
10
+ import { type Context, onOff, revisionOf, sourceOf } from "./properties.js";
11
+
12
+ type Json = Record<string, unknown>;
13
+
14
+ const specs = (type: string) => schema.nodes[type]?.spec.attrs ?? {};
15
+ const TABLE = specs("table");
16
+ const ROW = specs("tableRow");
17
+ const CELL = specs("tableCell");
18
+
19
+ const nameOf = (element: XmlElement, local: string) =>
20
+ `${element.prefix ? `${element.prefix}:` : ""}${local}`;
21
+
22
+ /** Keeps `value` as `name` if the schema accepts it there; reports it otherwise. */
23
+ function set(
24
+ out: Json,
25
+ attrs: Readonly<Record<string, AttributeSpec>>,
26
+ name: string,
27
+ value: unknown,
28
+ element: string,
29
+ context: Context,
30
+ ): void {
31
+ if (value === undefined) return;
32
+ const error = attrs[name]?.validate?.(value);
33
+ if (error) context.report.unmodeled(element, `${name} ${error}`);
34
+ else out[name] = value;
35
+ }
36
+
37
+ /**
38
+ * A measure (`w:tblW`, `w:tcW`, `w:tblInd`, a margin): `w:w` in twips or fiftieths of a percent
39
+ * (`pct`, which Strict files may write as `50%`). Undefined, reported, when unreadable.
40
+ */
41
+ export function measure(el: XmlElement | undefined, context: Context): Json | undefined {
42
+ if (!el) return undefined;
43
+ const type = attr(el, "type") ?? "dxa";
44
+ const raw = attr(el, "w");
45
+ const percent = raw?.endsWith("%") ? Number(raw.slice(0, -1)) : Number.NaN;
46
+ const value =
47
+ raw === undefined
48
+ ? 0
49
+ : type === "pct" && Number.isFinite(percent)
50
+ ? Math.round(percent * 50)
51
+ : integer(raw);
52
+ if (value === undefined) {
53
+ context.report.unmodeled(`${el.name}@w:w`, `${raw} is not a whole number`);
54
+ return undefined;
55
+ }
56
+ return { value, type };
57
+ }
58
+
59
+ /** A border element's attributes. */
60
+ export function border(el: XmlElement, context: Context): Json | undefined {
61
+ const whole = (local: string) => {
62
+ const value = attr(el, local);
63
+ const n = integer(value);
64
+ if (value !== undefined && n === undefined)
65
+ context.report.unmodeled(`${el.name}@${local}`, `${value} is not a whole number`);
66
+ return n;
67
+ };
68
+ return compact({
69
+ style: attr(el, "val"),
70
+ size: whole("sz"),
71
+ space: whole("space"),
72
+ color: attr(el, "color"),
73
+ themeColor: attr(el, "themeColor"),
74
+ });
75
+ }
76
+
77
+ function borders(el: XmlElement | undefined, context: Context): Json | undefined {
78
+ if (!el) return undefined;
79
+ return compact(
80
+ Object.fromEntries(elements(el).map((side) => [side.local, border(side, context)])),
81
+ );
82
+ }
83
+
84
+ function margins(el: XmlElement | undefined, context: Context): Json | undefined {
85
+ if (!el) return undefined;
86
+ return compact(
87
+ Object.fromEntries(elements(el).map((side) => [side.local, measure(side, context)])),
88
+ );
89
+ }
90
+
91
+ export function shading(el: XmlElement | undefined): Json | undefined {
92
+ if (!el) return undefined;
93
+ return compact({
94
+ pattern: attr(el, "val"),
95
+ color: attr(el, "color"),
96
+ fill: attr(el, "fill"),
97
+ themeFill: attr(el, "themeFill"),
98
+ });
99
+ }
100
+
101
+ /** `w:tblLook`: Word 2010's attributes, or the older `w:val` bit mask. */
102
+ const LOOK_BITS: [string, number][] = [
103
+ ["firstRow", 0x0020],
104
+ ["lastRow", 0x0040],
105
+ ["firstColumn", 0x0080],
106
+ ["lastColumn", 0x0100],
107
+ ["noHBand", 0x0200],
108
+ ["noVBand", 0x0400],
109
+ ];
110
+
111
+ function look(el: XmlElement | undefined, context: Context): Json | undefined {
112
+ if (!el) return undefined;
113
+ const named = compact(
114
+ Object.fromEntries(LOOK_BITS.map(([key]) => [key, onOff(el, key, context)])),
115
+ );
116
+ if (named) return named;
117
+ const mask = Number.parseInt(attr(el, "val") ?? "", 16);
118
+ if (!Number.isFinite(mask)) return undefined;
119
+ return Object.fromEntries(LOOK_BITS.map(([key, bit]) => [key, (mask & bit) !== 0]));
120
+ }
121
+
122
+ const value = (el: XmlElement | undefined) => attr(el, "val");
123
+ const whole = (el: XmlElement | undefined) => integer(attr(el, "val"));
124
+ const on = (el: XmlElement | undefined) => (el ? toggle(el) : undefined);
125
+
126
+ /**
127
+ * `w:tblPr` (or `w:tblPrEx`) as table properties. With `ext`, the element itself is kept
128
+ * verbatim (a table's and a row's exceptions; a style's are in its own `ext`).
129
+ */
130
+ export function tableProperties(el: XmlElement | undefined, context: Context, ext: boolean): Json {
131
+ const out: Json = {};
132
+ if (!el) return out;
133
+ const at = (local: string) => child(el, local);
134
+ const keep = (name: string, v: unknown, local: string) =>
135
+ set(out, TABLE, name, v, nameOf(el, local), context);
136
+ keep("style", value(at("tblStyle")), "tblStyle");
137
+ keep("width", measure(at("tblW"), context), "tblW");
138
+ keep("justification", value(at("jc")), "jc");
139
+ keep("indent", measure(at("tblInd"), context), "tblInd");
140
+ keep("layout", attr(at("tblLayout"), "type"), "tblLayout");
141
+ keep("borders", borders(at("tblBorders"), context), "tblBorders");
142
+ keep("cellMargins", margins(at("tblCellMar"), context), "tblCellMar");
143
+ keep("cellSpacing", measure(at("tblCellSpacing"), context), "tblCellSpacing");
144
+ keep("shading", shading(at("shd")), "shd");
145
+ keep("look", look(at("tblLook"), context), "tblLook");
146
+ keep("rowBandSize", whole(at("tblStyleRowBandSize")), "tblStyleRowBandSize");
147
+ keep("columnBandSize", whole(at("tblStyleColBandSize")), "tblStyleColBandSize");
148
+ if (ext) out.ext = sourceOf(context, el);
149
+ return out;
150
+ }
151
+
152
+ /** `w:tblGrid`'s column widths. */
153
+ export function grid(el: XmlElement | undefined, context: Context): number[] {
154
+ if (!el) return [];
155
+ const widths = elements(el)
156
+ .filter((c) => c.local === "gridCol")
157
+ .map((c) => integer(attr(c, "w")) ?? 0);
158
+ const error = TABLE.grid?.validate?.(widths);
159
+ if (error) {
160
+ context.report.unmodeled(el.name, `grid ${error}`);
161
+ return [];
162
+ }
163
+ return widths;
164
+ }
165
+
166
+ /** `w:trPr` as row properties; with `node`, also the row's revision and the element verbatim. */
167
+ export function rowProperties(el: XmlElement | undefined, context: Context, node: boolean): Json {
168
+ const out: Json = {};
169
+ if (!el) return out;
170
+ const at = (local: string) => child(el, local);
171
+ const keep = (name: string, v: unknown, local: string) =>
172
+ set(out, ROW, name, v, nameOf(el, local), context);
173
+ const height = at("trHeight");
174
+ if (height) {
175
+ keep(
176
+ "height",
177
+ compact({ value: integer(attr(height, "val")) ?? 0, rule: attr(height, "hRule") }),
178
+ "trHeight",
179
+ );
180
+ }
181
+ keep("cantSplit", on(at("cantSplit")), "cantSplit");
182
+ keep("header", on(at("tblHeader")), "tblHeader");
183
+ keep("gridBefore", whole(at("gridBefore")), "gridBefore");
184
+ keep("widthBefore", measure(at("wBefore"), context), "wBefore");
185
+ keep("gridAfter", whole(at("gridAfter")), "gridAfter");
186
+ keep("widthAfter", measure(at("wAfter"), context), "wAfter");
187
+ if (!node) return out;
188
+ const revision = (local: string) => {
189
+ const change = at(local);
190
+ if (!change) return undefined;
191
+ const { id, author, date } = revisionOf(change);
192
+ return id === undefined ? undefined : compact({ id, author, date: date ?? undefined });
193
+ };
194
+ keep("revision", compact({ insertion: revision("ins"), deletion: revision("del") }), "ins");
195
+ out.ext = sourceOf(context, el);
196
+ return out;
197
+ }
198
+
199
+ /** `w:tcPr` as cell properties; with `node`, also the element verbatim. */
200
+ export function cellProperties(el: XmlElement | undefined, context: Context, node: boolean): Json {
201
+ const out: Json = {};
202
+ if (!el) return out;
203
+ const at = (local: string) => child(el, local);
204
+ const keep = (name: string, v: unknown, local: string) =>
205
+ set(out, CELL, name, v, nameOf(el, local), context);
206
+ keep("width", measure(at("tcW"), context), "tcW");
207
+ keep("gridSpan", whole(at("gridSpan")), "gridSpan");
208
+ const vMerge = at("vMerge");
209
+ // `<w:vMerge/>` continues the merge above.
210
+ if (vMerge) keep("vMerge", value(vMerge) ?? "continue", "vMerge");
211
+ keep("borders", borders(at("tcBorders"), context), "tcBorders");
212
+ keep("shading", shading(at("shd")), "shd");
213
+ keep("margins", margins(at("tcMar"), context), "tcMar");
214
+ keep("verticalAlign", value(at("vAlign")), "vAlign");
215
+ keep("textDirection", value(at("textDirection")), "textDirection");
216
+ keep("noWrap", on(at("noWrap")), "noWrap");
217
+ if (node) out.ext = sourceOf(context, el);
218
+ return out;
219
+ }
220
+
221
+ const nonEmpty = (json: Json) => (Object.keys(json).length ? json : undefined);
222
+
223
+ /** A table style's parts (`w:tblPr`, `w:trPr`, `w:tcPr`, `w:tblStylePr`) for its `StyleJSON`. */
224
+ export function tableStyleParts(
225
+ style: XmlElement,
226
+ context: Context,
227
+ paragraph: (pPr: XmlElement) => Json,
228
+ run: (rPr: XmlElement | undefined) => unknown[],
229
+ ): Json {
230
+ const parts = (el: XmlElement) => {
231
+ const pPr = child(el, "pPr");
232
+ const marks = run(child(el, "rPr"));
233
+ return {
234
+ paragraph: pPr ? nonEmpty(paragraph(pPr)) : undefined,
235
+ run: marks.length ? marks : undefined,
236
+ table: nonEmpty(tableProperties(child(el, "tblPr"), context, false)),
237
+ row: nonEmpty(rowProperties(child(el, "trPr"), context, false)),
238
+ cell: nonEmpty(cellProperties(child(el, "tcPr"), context, false)),
239
+ };
240
+ };
241
+ const own = parts(style);
242
+ const seen = new Set<string>();
243
+ const conditions: Json[] = [];
244
+ for (const c of elements(style)) {
245
+ if (c.local !== "tblStylePr") continue;
246
+ const type = attr(c, "type") ?? "";
247
+ // A type the model does not know, or one already read (Word uses the first): kept in `ext`.
248
+ if (
249
+ !(TABLE_CONDITIONS as readonly string[]).includes(type) ||
250
+ type === "wholeTable" ||
251
+ seen.has(type)
252
+ ) {
253
+ context.report.unmodeled(`${c.name}@w:type`, `${type} (kept in the style's element)`);
254
+ continue;
255
+ }
256
+ seen.add(type);
257
+ conditions.push(compact({ type, ...parts(c), ext: sourceOf(context, c) }) as Json);
258
+ }
259
+ return (
260
+ compact({
261
+ table: own.table,
262
+ row: own.row,
263
+ cell: own.cell,
264
+ conditions: conditions.length ? conditions : undefined,
265
+ }) ?? {}
266
+ );
267
+ }
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { type ExportOptions, exportDocx } from "./export/index.js";
2
+ export { type PackageImages, packageImages } from "./images.js";
2
3
  export { type DocxImport, type ImportReport, importDocx, importPackage } from "./import/index.js";
3
4
  export {
4
5
  DocxError,
package/src/settings.ts CHANGED
@@ -1,22 +1,71 @@
1
1
  /**
2
- * Word's document settings part (`settings.xml`): Foli reads and writes only
3
- * `w:trackRevisions` (whether Word records edits as tracked changes); the rest is kept verbatim.
2
+ * Word's document settings part (`settings.xml`): Foli reads and writes `w:trackRevisions`
3
+ * (whether Word records edits as tracked changes), `w:evenAndOddHeaders` and the note properties
4
+ * of `w:footnotePr` and `w:endnotePr`, and reads `w:doNotUseHTMLParagraphAutoSpacing`; the rest is
5
+ * kept verbatim, and so is the part when none of them changes.
4
6
  */
5
- import { isW, W } from "./import/ooxml.js";
6
- import type { XmlElement } from "./xml.js";
7
+ import type { NotePropertiesJSON, WordSettingsJSON } from "@folijs/core";
8
+ import { child, isW, toggle, W } from "./import/ooxml.js";
9
+ import { parseXml, type XmlElement } from "./xml.js";
7
10
 
8
- /** Whether `settings` (the `w:settings` root) turns tracked changes on. */
9
- export function trackRevisionsOf(settings: XmlElement | undefined): boolean {
10
- const element = settings?.children.find(
11
- (c): c is XmlElement => c.kind === "element" && isW(c, "trackRevisions"),
12
- );
11
+ const elementsOf = (parent: XmlElement) =>
12
+ parent.children.filter((c): c is XmlElement => c.kind === "element");
13
+ const valOf = (element: XmlElement | undefined, name = "val") =>
14
+ element?.attributes.find((a) => a.ns === W && a.local === name)?.value;
15
+
16
+ /** Whether the on-off element `local` of `settings` is on. */
17
+ function isOn(settings: XmlElement | undefined, local: string): boolean {
18
+ const element = settings && elementsOf(settings).find((c) => isW(c, local));
13
19
  if (!element) return false;
14
- const value = element.attributes.find((a) => a.ns === W && a.local === "val")?.value;
20
+ const value = valOf(element);
15
21
  return value === undefined || !["false", "0", "off"].includes(value);
16
22
  }
17
23
 
18
- /** Elements `w:settings` has before `w:trackRevisions` (ECMA-376 CT_Settings, in order). */
19
- const BEFORE = new Set([
24
+ /** Whether `settings` (the `w:settings` root) turns tracked changes on. */
25
+ export const trackRevisionsOf = (settings: XmlElement | undefined): boolean =>
26
+ isOn(settings, "trackRevisions");
27
+
28
+ const POSITIONS = new Set(["pageBottom", "beneathText", "sectEnd", "docEnd"]);
29
+ const RESTARTS = new Set(["continuous", "eachSect", "eachPage"]);
30
+
31
+ /** A `w:footnotePr` or `w:endnotePr` of the settings (its separators stay in the file). */
32
+ function noteProperties(element: XmlElement | undefined): NotePropertiesJSON {
33
+ const value = (local: string) => valOf(element && elementsOf(element).find((c) => isW(c, local)));
34
+ const position = value("pos");
35
+ const format = value("numFmt");
36
+ const start = Number(value("numStart"));
37
+ const restart = value("numRestart");
38
+ return {
39
+ ...(position && POSITIONS.has(position)
40
+ ? { position: position as NotePropertiesJSON["position"] & string }
41
+ : {}),
42
+ ...(format && /^[\w-]+$/.test(format) ? { format } : {}),
43
+ ...(Number.isInteger(start) && start >= 0 && value("numStart") ? { start } : {}),
44
+ ...(restart && RESTARTS.has(restart)
45
+ ? { restart: restart as NotePropertiesJSON["restart"] & string }
46
+ : {}),
47
+ };
48
+ }
49
+
50
+ /** What the document's `settings` model holds of the part, undefined when nothing. */
51
+ export function readSettings(settings: XmlElement | undefined): WordSettingsJSON | undefined {
52
+ if (!settings) return undefined;
53
+ const notes = (local: string) => noteProperties(elementsOf(settings).find((c) => isW(c, local)));
54
+ const footnotes = notes("footnotePr");
55
+ const endnotes = notes("endnotePr");
56
+ const compat = child(settings, "compat");
57
+ const spacing = compat && child(compat, "doNotUseHTMLParagraphAutoSpacing");
58
+ const out: WordSettingsJSON = {
59
+ ...(spacing && toggle(spacing) ? { doNotUseHTMLParagraphAutoSpacing: true } : {}),
60
+ ...(isOn(settings, "evenAndOddHeaders") ? { evenAndOddHeaders: true } : {}),
61
+ ...(Object.keys(footnotes).length ? { footnotes } : {}),
62
+ ...(Object.keys(endnotes).length ? { endnotes } : {}),
63
+ };
64
+ return Object.keys(out).length ? out : undefined;
65
+ }
66
+
67
+ /** `w:settings`' children in their order (ECMA-376 CT_Settings), as far as Foli writes them. */
68
+ const ORDER = [
20
69
  "writeProtection",
21
70
  "view",
22
71
  "zoom",
@@ -48,19 +97,65 @@ const BEFORE = new Set([
48
97
  "documentType",
49
98
  "mailMerge",
50
99
  "revisionView",
51
- ]);
100
+ "trackRevisions",
101
+ "doNotTrackMoves",
102
+ "doNotTrackFormatting",
103
+ "documentProtection",
104
+ "autoFormatOverride",
105
+ "styleLockTheme",
106
+ "styleLockQFSet",
107
+ "defaultTabStop",
108
+ "autoHyphenation",
109
+ "consecutiveHyphenLimit",
110
+ "hyphenationZone",
111
+ "doNotHyphenateCaps",
112
+ "showEnvelope",
113
+ "summaryLength",
114
+ "clickAndTypeStyle",
115
+ "defaultTableStyle",
116
+ "evenAndOddHeaders",
117
+ "bookFoldRevPrinting",
118
+ "bookFoldPrinting",
119
+ "bookFoldPrintingSheets",
120
+ "drawingGridHorizontalSpacing",
121
+ "drawingGridVerticalSpacing",
122
+ "displayHorizontalDrawingGridEvery",
123
+ "displayVerticalDrawingGridEvery",
124
+ "doNotUseMarginsForDrawingGridOrigin",
125
+ "drawingGridHorizontalOrigin",
126
+ "drawingGridVerticalOrigin",
127
+ "doNotShadeFormData",
128
+ "noPunctuationKerning",
129
+ "characterSpacingControl",
130
+ "printTwoOnOne",
131
+ "strictFirstAndLastChars",
132
+ "noLineBreaksAfter",
133
+ "noLineBreaksBefore",
134
+ "savePreviewPicture",
135
+ "doNotValidateAgainstSchema",
136
+ "saveInvalidXml",
137
+ "ignoreMixedContent",
138
+ "alwaysShowPlaceholderText",
139
+ "doNotDemarcateInvalidXml",
140
+ "saveXmlDataOnly",
141
+ "useXSLTWhenSaving",
142
+ "saveThroughXslt",
143
+ "showXMLTags",
144
+ "alwaysMergeEmptyNamespace",
145
+ "updateFields",
146
+ "hdrShapeDefaults",
147
+ "footnotePr",
148
+ "endnotePr",
149
+ ];
52
150
 
53
- /** `source` (a settings part, `root` its `w:settings`) with tracked changes `on`. */
54
- export function withTrackRevisions(source: string, root: XmlElement, on: boolean): string {
55
- if (trackRevisionsOf(root) === on) return source;
56
- const children = root.children.filter((c): c is XmlElement => c.kind === "element");
57
- const existing = children.find((c) => isW(c, "trackRevisions"));
58
- const prefix = root.prefix ? `${root.prefix}:` : "";
59
- const element = `<${prefix}trackRevisions/>`;
60
- // Off: removed. On over an explicit "off": replaced.
61
- if (existing)
62
- return source.slice(0, existing.start) + (on ? element : "") + source.slice(existing.end);
63
- const after = children.filter((c) => c.ns === W && BEFORE.has(c.local)).at(-1);
151
+ /** `source` with the child `local` of `root` being `element` ("": none), in its place. */
152
+ function placed(source: string, root: XmlElement, local: string, element: string): string {
153
+ const children = elementsOf(root);
154
+ const existing = children.find((c) => isW(c, local));
155
+ if (existing) return source.slice(0, existing.start) + element + source.slice(existing.end);
156
+ if (!element) return source;
157
+ const before = new Set(ORDER.slice(0, ORDER.indexOf(local)));
158
+ const after = children.filter((c) => c.ns === W && before.has(c.local)).at(-1);
64
159
  if (after) return source.slice(0, after.end) + element + source.slice(after.end);
65
160
  if (root.openEnd === root.end) {
66
161
  // `<w:settings/>`: opened and closed.
@@ -69,7 +164,76 @@ export function withTrackRevisions(source: string, root: XmlElement, on: boolean
69
164
  return source.slice(0, root.openEnd) + element + source.slice(root.openEnd);
70
165
  }
71
166
 
72
- /** A new settings part with tracked changes on. */
73
- export function newSettingsXml(): string {
74
- return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<w:settings xmlns:w="${W}"><w:trackRevisions/></w:settings>`;
167
+ const prefixOf = (root: XmlElement) => (root.prefix ? `${root.prefix}:` : "");
168
+
169
+ /** `source` (a settings part, `root` its `w:settings`) with tracked changes `on`. */
170
+ export function withTrackRevisions(source: string, root: XmlElement, on: boolean): string {
171
+ if (trackRevisionsOf(root) === on) return source;
172
+ return placed(source, root, "trackRevisions", on ? `<${prefixOf(root)}trackRevisions/>` : "");
173
+ }
174
+
175
+ /** A note properties element: `kept` (its separators, verbatim) after the properties. */
176
+ function notesXml(prefix: string, local: string, v: NotePropertiesJSON, kept = ""): string {
177
+ const value = (name: string, x: string | number | undefined) =>
178
+ x === undefined ? "" : `<${prefix}${name} ${prefix}val="${x}"/>`;
179
+ const children =
180
+ value("pos", v.position) +
181
+ value("numFmt", v.format) +
182
+ value("numStart", v.start) +
183
+ value("numRestart", v.restart) +
184
+ kept;
185
+ return children ? `<${prefix}${local}>${children}</${prefix}${local}>` : "";
186
+ }
187
+
188
+ const NOTES = [
189
+ ["footnotes", "footnotePr", "footnote"],
190
+ ["endnotes", "endnotePr", "endnote"],
191
+ ] as const;
192
+
193
+ /** The same properties, whatever their order. */
194
+ const sameNotes = (a: NotePropertiesJSON, b: NotePropertiesJSON) =>
195
+ a.position === b.position &&
196
+ a.format === b.format &&
197
+ a.start === b.start &&
198
+ a.restart === b.restart;
199
+
200
+ /**
201
+ * `source` saying what `settings` says. What they leave out stays as the file has it, and a part
202
+ * that already says it is returned as it is.
203
+ */
204
+ export function withSettings(source: string, root: XmlElement, settings: WordSettingsJSON): string {
205
+ let text = source;
206
+ let current = root;
207
+ const put = (local: string, element: string) => {
208
+ text = placed(text, current, local, element);
209
+ current = parseXml(text).root;
210
+ };
211
+ const prefix = prefixOf(root);
212
+ const even = settings.evenAndOddHeaders;
213
+ if (even !== undefined && even !== isOn(current, "evenAndOddHeaders"))
214
+ put("evenAndOddHeaders", even ? `<${prefix}evenAndOddHeaders/>` : "");
215
+ for (const [key, local, separator] of NOTES) {
216
+ const wanted = settings[key];
217
+ if (!wanted) continue;
218
+ const element = elementsOf(current).find((c) => isW(c, local));
219
+ if (sameNotes(wanted, noteProperties(element))) continue;
220
+ const kept = (element ? elementsOf(element) : [])
221
+ .filter((c) => isW(c, separator))
222
+ .map((c) => text.slice(c.start, c.end))
223
+ .join("");
224
+ put(local, notesXml(prefix, local, wanted, kept));
225
+ }
226
+ return text;
227
+ }
228
+
229
+ /** A new settings part. */
230
+ export function newSettingsXml(trackRevisions: boolean, settings: WordSettingsJSON = {}): string {
231
+ const children =
232
+ (trackRevisions ? "<w:trackRevisions/>" : "") +
233
+ (settings.evenAndOddHeaders ? "<w:evenAndOddHeaders/>" : "") +
234
+ NOTES.map(([key, local]) => notesXml("w:", local, settings[key] ?? {})).join("") +
235
+ (settings.doNotUseHTMLParagraphAutoSpacing
236
+ ? "<w:compat><w:doNotUseHTMLParagraphAutoSpacing/></w:compat>"
237
+ : "");
238
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<w:settings xmlns:w="${W}">${children}</w:settings>`;
75
239
  }