@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,386 @@
1
+ /**
2
+ * Table, row and cell attributes back to `w:tblPr`, `w:tblPrEx`, `w:trPr`, `w:tcPr` and
3
+ * `w:tblGrid`, as paragraph properties are written: an element read from a file comes back
4
+ * verbatim while its values are what import read from it; otherwise each child is decided on
5
+ * its own, and children Foli does not model stay where Word requires them.
6
+ */
7
+
8
+ import { cellProperties, grid, rowProperties, tableProperties } from "../import/tables.js";
9
+ import type { XmlElement } from "../xml.js";
10
+ import { keptOrFresh, reading, same } from "./properties.js";
11
+ import { attributesOf, el, fragment, merged, type Namespaces, onOff, val } from "./xmlout.js";
12
+
13
+ type Json = Record<string, unknown>;
14
+ type Reader = (element: XmlElement, context: ReturnType<typeof reading>) => Json;
15
+
16
+ interface Spec {
17
+ /** The element's name. */
18
+ name: string;
19
+ /** Its children in the order Word requires. */
20
+ order: readonly string[];
21
+ /** Attribute → the children it is written as. */
22
+ children: Readonly<Record<string, readonly string[]>>;
23
+ read: Reader;
24
+ write: (prop: string, value: Json | unknown) => string;
25
+ }
26
+
27
+ const s = (x: unknown) => (x === undefined || x === null ? undefined : String(x));
28
+
29
+ function measureXml(local: string, m: unknown): string {
30
+ if (!m) return "";
31
+ const v = m as Json;
32
+ return el(`w:${local}`, { "w:w": s(v.value), "w:type": s(v.type) });
33
+ }
34
+
35
+ function borderXml(local: string, b: unknown): string {
36
+ if (!b) return "";
37
+ const v = b as Json;
38
+ return el(`w:${local}`, {
39
+ "w:val": s(v.style),
40
+ "w:sz": s(v.size),
41
+ "w:space": s(v.space),
42
+ "w:color": s(v.color),
43
+ "w:themeColor": s(v.themeColor),
44
+ });
45
+ }
46
+
47
+ const BORDER_SIDES = [
48
+ "top",
49
+ "left",
50
+ "start",
51
+ "bottom",
52
+ "right",
53
+ "end",
54
+ "insideH",
55
+ "insideV",
56
+ "tl2br",
57
+ "tr2bl",
58
+ ];
59
+ const MARGIN_SIDES = ["top", "left", "start", "bottom", "right", "end"];
60
+
61
+ function sidesXml(name: string, value: unknown, sides: readonly string[], one: typeof borderXml) {
62
+ if (!value) return "";
63
+ const v = value as Json;
64
+ return el(name, {}, sides.map((side) => one(side, v[side])).join(""));
65
+ }
66
+
67
+ function shadingXml(value: unknown): string {
68
+ if (!value) return "";
69
+ const v = value as Json;
70
+ return el("w:shd", {
71
+ "w:val": s(v.pattern),
72
+ "w:color": s(v.color),
73
+ "w:fill": s(v.fill),
74
+ "w:themeFill": s(v.themeFill),
75
+ });
76
+ }
77
+
78
+ const LOOK_BITS: [string, number][] = [
79
+ ["firstRow", 0x0020],
80
+ ["lastRow", 0x0040],
81
+ ["firstColumn", 0x0080],
82
+ ["lastColumn", 0x0100],
83
+ ["noHBand", 0x0200],
84
+ ["noVBand", 0x0400],
85
+ ];
86
+
87
+ /** `w:tblLook` as Word writes it: the bit mask and the named attributes. */
88
+ function lookXml(value: unknown): string {
89
+ if (!value) return "";
90
+ const v = value as Json;
91
+ const mask = LOOK_BITS.reduce((m, [key, bit]) => (v[key] ? m | bit : m), 0);
92
+ return el("w:tblLook", {
93
+ "w:val": mask.toString(16).toUpperCase().padStart(4, "0"),
94
+ ...Object.fromEntries(LOOK_BITS.map(([key]) => [`w:${key}`, v[key] as boolean | undefined])),
95
+ });
96
+ }
97
+
98
+ const TABLE_CHILDREN: Record<string, readonly string[]> = {
99
+ style: ["tblStyle"],
100
+ rowBandSize: ["tblStyleRowBandSize"],
101
+ columnBandSize: ["tblStyleColBandSize"],
102
+ width: ["tblW"],
103
+ justification: ["jc"],
104
+ cellSpacing: ["tblCellSpacing"],
105
+ indent: ["tblInd"],
106
+ borders: ["tblBorders"],
107
+ shading: ["shd"],
108
+ layout: ["tblLayout"],
109
+ cellMargins: ["tblCellMar"],
110
+ look: ["tblLook"],
111
+ };
112
+
113
+ function tableChild(prop: string, value: unknown): string {
114
+ switch (prop) {
115
+ case "style":
116
+ return val("tblStyle", s(value));
117
+ case "rowBandSize":
118
+ return val("tblStyleRowBandSize", s(value));
119
+ case "columnBandSize":
120
+ return val("tblStyleColBandSize", s(value));
121
+ case "width":
122
+ return measureXml("tblW", value);
123
+ case "justification":
124
+ return val("jc", s(value));
125
+ case "cellSpacing":
126
+ return measureXml("tblCellSpacing", value);
127
+ case "indent":
128
+ return measureXml("tblInd", value);
129
+ case "borders":
130
+ return sidesXml("w:tblBorders", value, BORDER_SIDES, borderXml);
131
+ case "shading":
132
+ return shadingXml(value);
133
+ case "layout":
134
+ return value ? el("w:tblLayout", { "w:type": s(value) }) : "";
135
+ case "cellMargins":
136
+ return sidesXml("w:tblCellMar", value, MARGIN_SIDES, measureXml);
137
+ case "look":
138
+ return lookXml(value);
139
+ default:
140
+ return "";
141
+ }
142
+ }
143
+
144
+ /** CT_TblPr child order (ECMA-376 Part 1, 17.4.60). */
145
+ const TABLE: Spec = {
146
+ name: "w:tblPr",
147
+ order: [
148
+ "tblStyle",
149
+ "tblpPr",
150
+ "tblOverlap",
151
+ "bidiVisual",
152
+ "tblStyleRowBandSize",
153
+ "tblStyleColBandSize",
154
+ "tblW",
155
+ "jc",
156
+ "tblCellSpacing",
157
+ "tblInd",
158
+ "tblBorders",
159
+ "shd",
160
+ "tblLayout",
161
+ "tblCellMar",
162
+ "tblLook",
163
+ "tblCaption",
164
+ "tblDescription",
165
+ "tblPrChange",
166
+ ],
167
+ children: TABLE_CHILDREN,
168
+ read: (element, context) => tableProperties(element, context, false),
169
+ write: tableChild,
170
+ };
171
+
172
+ /** CT_TblPrEx (17.4.61): what a row may override. */
173
+ const EXCEPTIONS: Spec = {
174
+ name: "w:tblPrEx",
175
+ order: [
176
+ "tblW",
177
+ "jc",
178
+ "tblCellSpacing",
179
+ "tblInd",
180
+ "tblBorders",
181
+ "shd",
182
+ "tblLayout",
183
+ "tblCellMar",
184
+ "tblLook",
185
+ "tblPrExChange",
186
+ ],
187
+ children: Object.fromEntries(
188
+ Object.entries(TABLE_CHILDREN).filter(([, [local]]) =>
189
+ [
190
+ "tblW",
191
+ "jc",
192
+ "tblCellSpacing",
193
+ "tblInd",
194
+ "tblBorders",
195
+ "shd",
196
+ "tblLayout",
197
+ "tblCellMar",
198
+ "tblLook",
199
+ ].includes(local as string),
200
+ ),
201
+ ),
202
+ read: (element, context) => tableProperties(element, context, false),
203
+ write: tableChild,
204
+ };
205
+
206
+ function revisionXml(local: string, r: unknown): string {
207
+ if (!r) return "";
208
+ const v = r as Json;
209
+ return el(`w:${local}`, { "w:id": s(v.id), "w:author": s(v.author) ?? "", "w:date": s(v.date) });
210
+ }
211
+
212
+ /** CT_TrPr (17.4.82; Word writes its children in this order). */
213
+ const ROW: Spec = {
214
+ name: "w:trPr",
215
+ order: [
216
+ "cnfStyle",
217
+ "divId",
218
+ "gridBefore",
219
+ "gridAfter",
220
+ "wBefore",
221
+ "wAfter",
222
+ "cantSplit",
223
+ "trHeight",
224
+ "tblHeader",
225
+ "tblCellSpacing",
226
+ "jc",
227
+ "hidden",
228
+ "ins",
229
+ "del",
230
+ "trPrChange",
231
+ ],
232
+ children: {
233
+ gridBefore: ["gridBefore"],
234
+ gridAfter: ["gridAfter"],
235
+ widthBefore: ["wBefore"],
236
+ widthAfter: ["wAfter"],
237
+ cantSplit: ["cantSplit"],
238
+ height: ["trHeight"],
239
+ header: ["tblHeader"],
240
+ revision: ["ins", "del"],
241
+ },
242
+ read: (element, context) => rowProperties(element, context, true),
243
+ write: (prop, value) => {
244
+ const v = (value ?? {}) as Json;
245
+ switch (prop) {
246
+ case "gridBefore":
247
+ case "gridAfter":
248
+ return val(prop, s(value));
249
+ case "widthBefore":
250
+ return measureXml("wBefore", value);
251
+ case "widthAfter":
252
+ return measureXml("wAfter", value);
253
+ case "cantSplit":
254
+ return onOff("cantSplit", value as boolean | undefined);
255
+ case "height":
256
+ return value ? el("w:trHeight", { "w:val": s(v.value), "w:hRule": s(v.rule) }) : "";
257
+ case "header":
258
+ return onOff("tblHeader", value as boolean | undefined);
259
+ case "revision":
260
+ return revisionXml("ins", v.insertion) + revisionXml("del", v.deletion);
261
+ default:
262
+ return "";
263
+ }
264
+ },
265
+ };
266
+
267
+ /** CT_TcPr (17.4.70). */
268
+ const CELL: Spec = {
269
+ name: "w:tcPr",
270
+ order: [
271
+ "cnfStyle",
272
+ "tcW",
273
+ "gridSpan",
274
+ "hMerge",
275
+ "vMerge",
276
+ "tcBorders",
277
+ "shd",
278
+ "noWrap",
279
+ "tcMar",
280
+ "textDirection",
281
+ "tcFitText",
282
+ "vAlign",
283
+ "hideMark",
284
+ "headers",
285
+ "cellIns",
286
+ "cellDel",
287
+ "cellMerge",
288
+ "tcPrChange",
289
+ ],
290
+ children: {
291
+ width: ["tcW"],
292
+ gridSpan: ["gridSpan"],
293
+ vMerge: ["vMerge"],
294
+ borders: ["tcBorders"],
295
+ shading: ["shd"],
296
+ noWrap: ["noWrap"],
297
+ margins: ["tcMar"],
298
+ textDirection: ["textDirection"],
299
+ verticalAlign: ["vAlign"],
300
+ },
301
+ read: (element, context) => cellProperties(element, context, false),
302
+ write: (prop, value) => {
303
+ switch (prop) {
304
+ case "width":
305
+ return measureXml("tcW", value);
306
+ case "gridSpan":
307
+ return val("gridSpan", s(value));
308
+ case "vMerge":
309
+ // `<w:vMerge/>` is a continuation, as Word writes it.
310
+ return value === "continue" ? el("w:vMerge") : val("vMerge", s(value));
311
+ case "borders":
312
+ return sidesXml("w:tcBorders", value, BORDER_SIDES, borderXml);
313
+ case "shading":
314
+ return shadingXml(value);
315
+ case "noWrap":
316
+ return onOff("noWrap", value as boolean | undefined);
317
+ case "margins":
318
+ return sidesXml("w:tcMar", value, MARGIN_SIDES, measureXml);
319
+ case "textDirection":
320
+ return val("textDirection", s(value));
321
+ case "verticalAlign":
322
+ return val("vAlign", s(value));
323
+ default:
324
+ return "";
325
+ }
326
+ },
327
+ };
328
+
329
+ /** `attrs` (with their `ext`) as the element `spec` describes; empty when nothing is set unless `always`. */
330
+ function propertiesXml(spec: Spec, attrs: Json, ns: Namespaces, always: boolean): string {
331
+ const ext = attrs.ext as string | undefined;
332
+ const local = spec.name.slice(2);
333
+ const original = ext ? fragment(ext, ns, local) : undefined;
334
+ const pick = (json: Json) =>
335
+ Object.fromEntries(Object.keys(spec.children).map((k) => [k, json[k] ?? undefined]));
336
+ const current = pick(attrs);
337
+ const reread = original ? pick(spec.read(original.element, reading(original))) : {};
338
+ if (original && same(current, reread)) return ext as string;
339
+ const generated = new Map<string, string>();
340
+ for (const [prop, locals] of Object.entries(spec.children)) {
341
+ const text = keptOrFresh(original, same(current[prop], reread[prop]), locals, () =>
342
+ spec.write(prop, current[prop]),
343
+ );
344
+ generated.set(locals[0] as string, text);
345
+ for (const other of locals.slice(1)) generated.set(other, "");
346
+ }
347
+ const modeled = new Set(Object.values(spec.children).flat());
348
+ const children = merged(spec.order, modeled, generated, original);
349
+ return children || attributesOf(original) || always
350
+ ? `<${spec.name}${attributesOf(original)}>${children}</${spec.name}>`
351
+ : "";
352
+ }
353
+
354
+ /** A table's `w:tblPr` (always written: Word requires it). */
355
+ export const tablePropertiesXml = (attrs: Json, ns: Namespaces) =>
356
+ propertiesXml(TABLE, attrs, ns, true);
357
+
358
+ export const exceptionsXml = (exceptions: unknown, ns: Namespaces) =>
359
+ exceptions ? propertiesXml(EXCEPTIONS, exceptions as Json, ns, false) : "";
360
+
361
+ export const rowPropertiesXml = (attrs: Json, ns: Namespaces) =>
362
+ propertiesXml(ROW, attrs, ns, false);
363
+
364
+ export const cellPropertiesXml = (attrs: Json, ns: Namespaces) =>
365
+ propertiesXml(CELL, attrs, ns, false);
366
+
367
+ /** A new table style's `w:tblPr`, `w:trPr` and `w:tcPr` (empty for a part it does not set). */
368
+ export const stylePartsXml = (
369
+ style: { table?: unknown; row?: unknown; cell?: unknown },
370
+ ns: Namespaces,
371
+ ) => ({
372
+ tblPr: style.table ? propertiesXml(TABLE, style.table as Json, ns, false) : "",
373
+ trPr: style.row ? propertiesXml(ROW, style.row as Json, ns, false) : "",
374
+ tcPr: style.cell ? propertiesXml(CELL, style.cell as Json, ns, false) : "",
375
+ });
376
+
377
+ /** `w:tblGrid`: as read while the widths are the same, else written from them. */
378
+ export function gridXml(attrs: Json, ns: Namespaces): string {
379
+ const widths = (attrs.grid ?? []) as number[];
380
+ const ext = attrs.gridExt as string | undefined;
381
+ if (ext) {
382
+ const original = fragment(ext, ns, "tblGrid");
383
+ if (same(grid(original.element, reading(original)), widths)) return ext;
384
+ }
385
+ return `<w:tblGrid>${widths.map((w) => el("w:gridCol", { "w:w": w })).join("")}</w:tblGrid>`;
386
+ }
package/src/images.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { ResourceJSON } from "@folijs/core";
2
+ import type { DocxPackage } from "./package.js";
3
+
4
+ /** URLs for the images of a package's pictures, for the view to show them. */
5
+ export interface PackageImages {
6
+ /**
7
+ * An object URL for the image of resource `key` when it is a part of the package (made once,
8
+ * then reused); undefined otherwise. Fits `EditorViewOptions.resource`.
9
+ */
10
+ url(key: string, resource?: ResourceJSON): string | undefined;
11
+ /** Frees every URL made (they stop working). */
12
+ revoke(): void;
13
+ }
14
+
15
+ /** Image types browsers show in an `img`; EMF, WMF and TIFF parts are shown as a box. */
16
+ // `image/jpg` as some producers write it.
17
+ const RASTER = new Set([
18
+ "image/png",
19
+ "image/jpeg",
20
+ "image/jpg",
21
+ "image/gif",
22
+ "image/webp",
23
+ "image/bmp",
24
+ ]);
25
+
26
+ /**
27
+ * URLs for the pictures' images that live in `pkg` (`word/media/…`): the view cannot show a
28
+ * package part otherwise. Raster images get object URLs (`blob:`); an SVG gets a `data:` URL,
29
+ * never a `blob:` one (opened on its own, a `blob:` SVG would run its scripts as the app's
30
+ * origin; a `data:` document has none). Types browsers cannot show, and where there are no
31
+ * object URLs (no DOM), none.
32
+ */
33
+ export function packageImages(pkg: DocxPackage): PackageImages {
34
+ const urls = new Map<string, string>();
35
+ const blobs: string[] = [];
36
+ return {
37
+ url(key, resource) {
38
+ const known = urls.get(key);
39
+ if (known) return known;
40
+ const part = resource?.part ? pkg.part(`/${resource.part}`) : undefined;
41
+ if (!part) return undefined;
42
+ let url: string;
43
+ if (part.contentType === "image/svg+xml") {
44
+ let binary = "";
45
+ for (const byte of part.data) binary += String.fromCharCode(byte);
46
+ url = `data:image/svg+xml;base64,${btoa(binary)}`;
47
+ } else if (RASTER.has(part.contentType) && typeof URL.createObjectURL === "function") {
48
+ url = URL.createObjectURL(new Blob([part.data as BlobPart], { type: part.contentType }));
49
+ blobs.push(url);
50
+ } else return undefined;
51
+ urls.set(key, url);
52
+ return url;
53
+ },
54
+ revoke() {
55
+ for (const url of blobs) URL.revokeObjectURL(url);
56
+ blobs.length = 0;
57
+ urls.clear();
58
+ },
59
+ };
60
+ }