@folijs/docx 0.3.0 → 0.5.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 (85) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +72 -10
  3. package/dist/export/content.d.ts +2 -0
  4. package/dist/export/content.d.ts.map +1 -1
  5. package/dist/export/content.js +41 -3
  6. package/dist/export/content.js.map +1 -1
  7. package/dist/export/index.d.ts +14 -2
  8. package/dist/export/index.d.ts.map +1 -1
  9. package/dist/export/index.js +76 -15
  10. package/dist/export/index.js.map +1 -1
  11. package/dist/export/parts.d.ts.map +1 -1
  12. package/dist/export/parts.js +13 -0
  13. package/dist/export/parts.js.map +1 -1
  14. package/dist/export/pictures.d.ts +51 -0
  15. package/dist/export/pictures.d.ts.map +1 -0
  16. package/dist/export/pictures.js +346 -0
  17. package/dist/export/pictures.js.map +1 -0
  18. package/dist/export/properties.d.ts +11 -1
  19. package/dist/export/properties.d.ts.map +1 -1
  20. package/dist/export/properties.js +1 -1
  21. package/dist/export/properties.js.map +1 -1
  22. package/dist/export/tables.d.ts +27 -0
  23. package/dist/export/tables.d.ts.map +1 -0
  24. package/dist/export/tables.js +344 -0
  25. package/dist/export/tables.js.map +1 -0
  26. package/dist/images.d.ts +21 -0
  27. package/dist/images.d.ts.map +1 -0
  28. package/dist/images.js +53 -0
  29. package/dist/images.js.map +1 -0
  30. package/dist/import/content.d.ts +5 -1
  31. package/dist/import/content.d.ts.map +1 -1
  32. package/dist/import/content.js +161 -7
  33. package/dist/import/content.js.map +1 -1
  34. package/dist/import/index.d.ts +6 -1
  35. package/dist/import/index.d.ts.map +1 -1
  36. package/dist/import/index.js +16 -4
  37. package/dist/import/index.js.map +1 -1
  38. package/dist/import/ooxml.d.ts +1 -0
  39. package/dist/import/ooxml.d.ts.map +1 -1
  40. package/dist/import/ooxml.js +1 -0
  41. package/dist/import/ooxml.js.map +1 -1
  42. package/dist/import/parts.d.ts.map +1 -1
  43. package/dist/import/parts.js +7 -0
  44. package/dist/import/parts.js.map +1 -1
  45. package/dist/import/pictures.d.ts +34 -0
  46. package/dist/import/pictures.d.ts.map +1 -0
  47. package/dist/import/pictures.js +147 -0
  48. package/dist/import/pictures.js.map +1 -0
  49. package/dist/import/properties.d.ts.map +1 -1
  50. package/dist/import/properties.js +2 -1
  51. package/dist/import/properties.js.map +1 -1
  52. package/dist/import/report.d.ts +6 -0
  53. package/dist/import/report.d.ts.map +1 -1
  54. package/dist/import/report.js +5 -0
  55. package/dist/import/report.js.map +1 -1
  56. package/dist/import/tables.d.ts +31 -0
  57. package/dist/import/tables.d.ts.map +1 -0
  58. package/dist/import/tables.js +236 -0
  59. package/dist/import/tables.js.map +1 -0
  60. package/dist/index.d.ts +2 -1
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +1 -0
  63. package/dist/index.js.map +1 -1
  64. package/dist/settings.d.ts +8 -0
  65. package/dist/settings.d.ts.map +1 -0
  66. package/dist/settings.js +72 -0
  67. package/dist/settings.js.map +1 -0
  68. package/package.json +2 -2
  69. package/src/export/content.ts +49 -5
  70. package/src/export/index.ts +135 -19
  71. package/src/export/parts.ts +15 -0
  72. package/src/export/pictures.ts +405 -0
  73. package/src/export/properties.ts +1 -1
  74. package/src/export/tables.ts +386 -0
  75. package/src/images.ts +60 -0
  76. package/src/import/content.ts +154 -9
  77. package/src/import/index.ts +20 -5
  78. package/src/import/ooxml.ts +1 -0
  79. package/src/import/parts.ts +13 -0
  80. package/src/import/pictures.ts +176 -0
  81. package/src/import/properties.ts +4 -1
  82. package/src/import/report.ts +11 -0
  83. package/src/import/tables.ts +267 -0
  84. package/src/index.ts +2 -1
  85. package/src/settings.ts +75 -0
@@ -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
+ }
@@ -4,10 +4,11 @@
4
4
  * for markers that have nothing to show: field characters, range ends).
5
5
  */
6
6
 
7
- import { type MarkJSON, type NodeJSON, schema } from "@folijs/core";
7
+ import { type MarkJSON, type NodeJSON, type ResourceJSON, schema } from "@folijs/core";
8
8
  import type { DocxPackage, Relationship } from "../package.js";
9
9
  import type { XmlElement, XmlNode } from "../xml.js";
10
10
  import { attr, child, deepText, integer, isW, R, REL, textOf, W } from "./ooxml.js";
11
+ import { pictureAttrs } from "./pictures.js";
11
12
  import {
12
13
  attributeBag,
13
14
  type Context,
@@ -18,6 +19,7 @@ import {
18
19
  setParagraph,
19
20
  sourceOf,
20
21
  } from "./properties.js";
22
+ import { cellProperties, grid, rowProperties, tableProperties } from "./tables.js";
21
23
 
22
24
  export interface ContentContext extends Context {
23
25
  readonly pkg: DocxPackage;
@@ -27,8 +29,15 @@ export interface ContentContext extends Context {
27
29
  readonly moves: Moves;
28
30
  /** The part's relationship with this id (hyperlink targets). */
29
31
  readonly relationship: (id: string) => Relationship | undefined;
32
+ /** How many tables the content is in. */
33
+ readonly tableDepth?: number;
34
+ /** The envelope's resources (pictures' images), filled as content is read. */
35
+ readonly resources: Map<string, ResourceJSON>;
30
36
  }
31
37
 
38
+ /** Tables nested deeper stay opaque: within the model's depth (three levels per table). */
39
+ const MAX_TABLE_DEPTH = 64;
40
+
32
41
  /** Labels of the opaque elements that show something; anything else unknown shows its name. */
33
42
  const BLOCK_LABELS: Record<string, string | null> = {
34
43
  tbl: "table",
@@ -97,21 +106,139 @@ export function blocks(
97
106
  section?: XmlElement,
98
107
  ): NodeJSON[] {
99
108
  const out: NodeJSON[] = [];
109
+ const tables = new Map<NodeJSON, XmlElement>();
100
110
  for (const node of nodes) {
101
111
  if (node.kind !== "element" || node === section) continue;
102
112
  if (isW(node, "p")) out.push(paragraph(node, context));
103
- else if (node.ns === W && DROPPED.has(node.local)) context.report.dropped(node.name);
104
- else {
105
- context.report.opaque(node.name);
106
- out.push({
107
- type: "opaqueBlock",
108
- attrs: withLabel({ xml: sourceOf(context, node) }, label(BLOCK_LABELS, node)),
109
- });
110
- }
113
+ else if (isW(node, "tbl")) {
114
+ // A table right after a table is one table to Word (it merges them): kept verbatim.
115
+ const table = out.at(-1)?.type === "table" ? undefined : tableOf(node, context);
116
+ if (table) tables.set(table, node);
117
+ out.push(table ?? opaqueOf(node, context));
118
+ } else if (node.ns === W && DROPPED.has(node.local)) context.report.dropped(node.name);
119
+ else out.push(opaqueOf(node, context));
111
120
  }
121
+ // Content does not end with a table (Word always puts a paragraph after one).
122
+ const last = out.at(-1);
123
+ const source = last && tables.get(last);
124
+ if (source) out[out.length - 1] = opaqueOf(source, context);
112
125
  return out;
113
126
  }
114
127
 
128
+ function opaqueOf(node: XmlElement, context: ContentContext): NodeJSON {
129
+ context.report.opaque(node.name);
130
+ return {
131
+ type: "opaqueBlock",
132
+ attrs: withLabel({ xml: sourceOf(context, node) }, label(BLOCK_LABELS, node)),
133
+ };
134
+ }
135
+
136
+ /**
137
+ * `w:tbl` as a table; undefined when the model cannot hold it as it is (rows or cells inside a
138
+ * content control or custom XML, markers between rows, elements out of Word's order, a cell
139
+ * not ending with a paragraph, tables nested too deep): the caller keeps it verbatim.
140
+ */
141
+ function tableOf(tbl: XmlElement, context: ContentContext): NodeJSON | undefined {
142
+ const tableDepth = (context.tableDepth ?? 0) + 1;
143
+ if (tableDepth > MAX_TABLE_DEPTH || tbl.attributes.length) return undefined;
144
+ const inner: ContentContext = { ...context, tableDepth };
145
+ let tblPr: XmlElement | undefined;
146
+ let tblGrid: XmlElement | undefined;
147
+ const rows: NodeJSON[] = [];
148
+ let stage = 0; // 0: w:tblPr may come, 1: w:tblGrid may come, 2: rows
149
+ for (const c of tbl.children) {
150
+ if (c.kind !== "element") continue;
151
+ if (stage === 0 && isW(c, "tblPr")) {
152
+ tblPr = c;
153
+ stage = 1;
154
+ } else if (stage <= 1 && isW(c, "tblGrid")) {
155
+ tblGrid = c;
156
+ stage = 2;
157
+ } else if (isW(c, "tr")) {
158
+ stage = 2;
159
+ const row = rowOf(c, inner);
160
+ if (!row) return undefined;
161
+ rows.push(row);
162
+ } else return undefined;
163
+ }
164
+ if (!rows.length) return undefined;
165
+ return {
166
+ type: "table",
167
+ attrs: {
168
+ ...tableProperties(tblPr, context, true),
169
+ grid: grid(tblGrid, context),
170
+ ...(tblGrid ? { gridExt: sourceOf(context, tblGrid) } : {}),
171
+ },
172
+ content: rows,
173
+ };
174
+ }
175
+
176
+ const ROW_ATTRS = schema.nodes.tableRow?.spec.attrs ?? {};
177
+
178
+ function rowOf(tr: XmlElement, context: ContentContext): NodeJSON | undefined {
179
+ let tblPrEx: XmlElement | undefined;
180
+ let trPr: XmlElement | undefined;
181
+ const cells: NodeJSON[] = [];
182
+ let stage = 0; // 0: w:tblPrEx, 1: w:trPr, 2: cells
183
+ for (const c of tr.children) {
184
+ if (c.kind !== "element") continue;
185
+ if (stage === 0 && isW(c, "tblPrEx")) {
186
+ tblPrEx = c;
187
+ stage = 1;
188
+ } else if (stage <= 1 && isW(c, "trPr")) {
189
+ trPr = c;
190
+ stage = 2;
191
+ } else if (isW(c, "tc")) {
192
+ stage = 2;
193
+ const cell = cellOf(c, context);
194
+ if (!cell) return undefined;
195
+ cells.push(cell);
196
+ } else return undefined;
197
+ }
198
+ if (!cells.length) return undefined;
199
+ const attrs: Record<string, unknown> = rowProperties(trPr, context, true);
200
+ if (tblPrEx) {
201
+ const exceptions = tableProperties(tblPrEx, context, true);
202
+ // Not a row's to override (CT_TblPrEx): left in the element, not modeled.
203
+ for (const key of ["style", "rowBandSize", "columnBandSize"]) {
204
+ if (key in exceptions) {
205
+ context.report.unmodeled(tblPrEx.name, `${key} is not an exception (kept in the element)`);
206
+ delete exceptions[key];
207
+ }
208
+ }
209
+ const error = ROW_ATTRS.exceptions?.validate?.(exceptions);
210
+ // Its values are checked one by one: only a too-large element can fail here.
211
+ if (error) return undefined;
212
+ attrs.exceptions = exceptions;
213
+ }
214
+ const bag = attributeBag(tr, [], context);
215
+ if (bag) attrs.attributes = bag;
216
+ return { type: "tableRow", ...(Object.keys(attrs).length ? { attrs } : {}), content: cells };
217
+ }
218
+
219
+ function cellOf(tc: XmlElement, context: ContentContext): NodeJSON | undefined {
220
+ if (tc.attributes.length) return undefined;
221
+ const first = tc.children.find((c): c is XmlElement => c.kind === "element");
222
+ const tcPr = first && isW(first, "tcPr") ? first : undefined;
223
+ const content = blocks(
224
+ tc.children.filter((c) => c !== tcPr),
225
+ context,
226
+ );
227
+ if (content.at(-1)?.type !== "paragraph" || !content.every(allowedInCell)) return undefined;
228
+ const attrs = cellProperties(tcPr, context, true);
229
+ return { type: "tableCell", ...(Object.keys(attrs).length ? { attrs } : {}), content };
230
+ }
231
+
232
+ /**
233
+ * Whether a cell's block is one the model allows there: not a paragraph that ends a section or
234
+ * holds a page or column break. A table with one stays verbatim (lossless) instead.
235
+ */
236
+ function allowedInCell(block: NodeJSON): boolean {
237
+ if (block.type !== "paragraph") return true;
238
+ if (block.attrs?.section) return false;
239
+ return !block.content?.some((n) => n.type === "pageBreak" || n.type === "columnBreak");
240
+ }
241
+
115
242
  function withLabel(attrs: Record<string, unknown>, value: string | null): Record<string, unknown> {
116
243
  return value === null ? attrs : { ...attrs, label: value.slice(0, 255) || null };
117
244
  }
@@ -372,6 +499,24 @@ function run(
372
499
  case "softHyphen":
373
500
  text("­");
374
501
  break;
502
+ case "drawing": {
503
+ const image: [string?, ResourceJSON?] = [];
504
+ const attrs = pictureAttrs(
505
+ el,
506
+ { ...context, partOf: (name) => context.pkg.part(name) },
507
+ image,
508
+ );
509
+ const leaf = attrs && valid(node("picture", marks, attrs), el, context);
510
+ if (!leaf) {
511
+ opaqueRun(el);
512
+ break;
513
+ }
514
+ out.push(leaf);
515
+ const [key, entry] = image;
516
+ if (key && entry && !context.resources.has(key)) context.resources.set(key, entry);
517
+ if (!attrs.alt && !attrs.decorative) context.report.withoutAlt();
518
+ break;
519
+ }
375
520
  case "commentReference": {
376
521
  const bag = attributeBag(el, ["w:id"], context);
377
522
  const attrs: Record<string, unknown> = { id: integer(attr(el, "id")) };