@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
@@ -1,4 +1,4 @@
1
- import { type FoliDocument, parseDocument } from "@folijs/core";
1
+ import { type FoliDocument, parseDocument, type ResourceJSON, SCHEMA_VERSION } from "@folijs/core";
2
2
  import {
3
3
  DocxError,
4
4
  type DocxPackage,
@@ -6,6 +6,7 @@ import {
6
6
  type Relationship,
7
7
  readPackage,
8
8
  } from "../package.js";
9
+ import { trackRevisionsOf } from "../settings.js";
9
10
  import type { XmlElement } from "../xml.js";
10
11
  import { blocks, type ContentContext, Moves } from "./content.js";
11
12
  import { child, isW, REL, W_STRICT } from "./ooxml.js";
@@ -14,7 +15,7 @@ import { section } from "./properties.js";
14
15
  import { type ImportReport, Recorder } from "./report.js";
15
16
 
16
17
  export interface DocxImport {
17
- /** The document in schema v3, validated. */
18
+ /** The document in the current schema (v4), validated. */
18
19
  readonly document: FoliDocument;
19
20
  /**
20
21
  * The package it was read from. Export (8.5) writes the parts Foli does not edit back from
@@ -22,6 +23,11 @@ export interface DocxImport {
22
23
  */
23
24
  readonly package: DocxPackage;
24
25
  readonly report: ImportReport;
26
+ /**
27
+ * Whether Word records edits to it as tracked changes (`w:trackRevisions` in its settings):
28
+ * pass it to the editor (`trackChanges`), and back to `exportDocx` when it changes.
29
+ */
30
+ readonly trackRevisions: boolean;
25
31
  }
26
32
 
27
33
  /** Reads a `.docx` into schema v3, keeping its package for export. */
@@ -50,6 +56,7 @@ export function importPackage(pkg: DocxPackage): DocxImport {
50
56
  const body = child(main.root, "body");
51
57
  if (!body) throw new DocxError(`${pkg.mainDocument}: no w:body`);
52
58
 
59
+ const resources = new Map<string, ResourceJSON>();
53
60
  const contextFor = (part: string, source: string): ContentContext => {
54
61
  report.part = part;
55
62
  // One lookup table per part: hyperlinks resolve in constant time.
@@ -58,7 +65,7 @@ export function importPackage(pkg: DocxPackage): DocxImport {
58
65
  byId ??= new Map(pkg.relationships(part).map((r) => [r.id, r]));
59
66
  return byId.get(id);
60
67
  };
61
- return { source, report, pkg, part, moves: new Moves(), relationship };
68
+ return { source, report, pkg, part, moves: new Moves(), relationship, resources };
62
69
  };
63
70
  const related = (
64
71
  type: string,
@@ -106,13 +113,14 @@ export function importPackage(pkg: DocxPackage): DocxImport {
106
113
  let document: FoliDocument;
107
114
  try {
108
115
  document = parseDocument({
109
- schemaVersion: 3,
116
+ schemaVersion: SCHEMA_VERSION,
110
117
  section: lastSection,
111
118
  defaults: styled.defaults,
112
119
  styles: styled.styles,
113
120
  numbering: numbered,
114
121
  ...(themed ? { theme: themed } : {}),
115
122
  comments: commented,
123
+ ...(resources.size ? { resources: Object.fromEntries(resources) } : {}),
116
124
  content: { type: "doc", content },
117
125
  });
118
126
  } catch (error) {
@@ -120,7 +128,14 @@ export function importPackage(pkg: DocxPackage): DocxImport {
120
128
  // element over 16 MiB kept verbatim…). A DocxError like every other import failure.
121
129
  throw new DocxError(`Cannot import: ${(error as Error).message}`, { cause: error });
122
130
  }
123
- return { document, package: pkg, report: report.report() };
131
+ // A settings part Foli cannot read is kept as it is, and tracking taken as off.
132
+ let trackRevisions = false;
133
+ try {
134
+ trackRevisions = trackRevisionsOf(related(REL.settings)?.root);
135
+ } catch (error) {
136
+ if (!(error instanceof DocxError)) throw error;
137
+ }
138
+ return { document, package: pkg, report: report.report(), trackRevisions };
124
139
  }
125
140
 
126
141
  export type { ImportReport } from "./report.js";
@@ -17,6 +17,7 @@ export const REL = {
17
17
  comments: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
18
18
  commentsExtended: "http://schemas.microsoft.com/office/2011/relationships/commentsExtended",
19
19
  hyperlink: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
20
+ settings: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",
20
21
  };
21
22
 
22
23
  /** Whether `node` is the WordprocessingML element `local`. */
@@ -15,6 +15,7 @@ import type { XmlElement } from "../xml.js";
15
15
  import { blocks, type ContentContext } from "./content.js";
16
16
  import { A, attr, child, compact, elements, integer, isW, toggle, W14, W15 } from "./ooxml.js";
17
17
  import { type Context, onOff, paragraphProperties, runProperties, sourceOf } from "./properties.js";
18
+ import { tableStyleParts } from "./tables.js";
18
19
 
19
20
  const STYLE_TYPES = ["paragraph", "character", "table", "numbering"];
20
21
  /** Word's ids (`w:numId`, `w:abstractNumId`, comment ids): what the model holds. */
@@ -110,6 +111,17 @@ export function styleOf(el: XmlElement, context: Context): StyleJSON | undefined
110
111
  const props = stylePPr ? paragraphProperties(stylePPr, context, false) : {};
111
112
  const marks = runList(child(el, "rPr"), context);
112
113
  const name = attr(child(el, "name"), "val");
114
+ // shortcut: a `wholeTable` conditional format is kept in `ext`, not applied; read it if a
115
+ // real document's table style uses one.
116
+ const table =
117
+ type === "table"
118
+ ? tableStyleParts(
119
+ el,
120
+ context,
121
+ (pPr) => paragraphProperties(pPr, context, false),
122
+ (rPr) => runList(rPr, context),
123
+ )
124
+ : {};
113
125
  return compact({
114
126
  id: styleId,
115
127
  type: type as StyleJSON["type"],
@@ -120,6 +132,7 @@ export function styleOf(el: XmlElement, context: Context): StyleJSON | undefined
120
132
  isDefault: onOff(el, "default", context),
121
133
  paragraph: Object.keys(props).length ? props : undefined,
122
134
  run: marks.length ? marks : undefined,
135
+ ...table,
123
136
  ext: sourceOf(context, el),
124
137
  }) as StyleJSON;
125
138
  }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Pictures (10.8, 10.9, ADR-0006): a `w:drawing` holding one DrawingML picture (`pic:pic`),
3
+ * inline (`wp:inline`) or floating (`wp:anchor`, its position and wrapping as `float`), becomes
4
+ * a `picture` node; its image part becomes a resource of the envelope, keyed by part name.
5
+ * Charts, shapes and anything else stay opaque.
6
+ */
7
+ import type { ResourceJSON } from "@folijs/core";
8
+ import type { XmlElement } from "../xml.js";
9
+ import { A, attr, integer, R, textOf } from "./ooxml.js";
10
+ import { type Context, sourceOf } from "./properties.js";
11
+
12
+ export const WP = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing";
13
+ export const PIC = "http://schemas.openxmlformats.org/drawingml/2006/picture";
14
+ const ADEC = "http://schemas.microsoft.com/office/drawing/2017/decorative";
15
+ const IMAGE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
16
+ /** The largest EMU the schema takes. */
17
+ const MAX_EMU = 2_147_483_647;
18
+ /** `wp:wrap*` to the model's wrapping (`wp:wrapNone` is behind or in front, by `behindDoc`). */
19
+ const WRAPS: Record<string, string> = {
20
+ wrapSquare: "square",
21
+ wrapTight: "tight",
22
+ wrapThrough: "through",
23
+ wrapTopAndBottom: "topAndBottom",
24
+ };
25
+ const SIDES = new Set(["bothSides", "left", "right", "largest"]);
26
+
27
+ export interface PictureContext extends Context {
28
+ /** The part's relationship with this id. */
29
+ readonly relationship: (
30
+ id: string,
31
+ ) => { type: string; external: boolean; partName?: string } | undefined;
32
+ /** A part of the package by name. */
33
+ readonly partOf: (name: string) => { contentType: string; data: Uint8Array } | undefined;
34
+ }
35
+
36
+ const kid = (el: XmlElement | undefined, ns: string, local: string) =>
37
+ el?.children.find(
38
+ (c): c is XmlElement => c.kind === "element" && c.ns === ns && c.local === local,
39
+ );
40
+
41
+ function descendant(el: XmlElement | undefined, ns: string, local: string): XmlElement | undefined {
42
+ if (!el) return undefined;
43
+ for (const c of el.children) {
44
+ if (c.kind !== "element") continue;
45
+ if (c.ns === ns && c.local === local) return c;
46
+ const found = descendant(c, ns, local);
47
+ if (found) return found;
48
+ }
49
+ return undefined;
50
+ }
51
+
52
+ /** An attribute without a prefix (DrawingML's own). */
53
+ const plain = (el: XmlElement | undefined, local: string) =>
54
+ el?.attributes.find((a) => a.local === local && !a.prefix)?.value;
55
+
56
+ const emu = (value: string | undefined) => {
57
+ const n = integer(value);
58
+ return n !== undefined && n >= 0 && n <= MAX_EMU ? n : undefined;
59
+ };
60
+
61
+ const flag = (value: string | undefined) =>
62
+ value === "1" || value === "true" ? true : value === "0" || value === "false" ? false : undefined;
63
+
64
+ /** A `wp:positionH`/`wp:positionV`: where it is from, and its offset or alignment. */
65
+ function position(el: XmlElement | undefined) {
66
+ const relativeTo = plain(el, "relativeFrom");
67
+ if (!el || !relativeTo) return undefined;
68
+ const offsetEl = kid(el, WP, "posOffset");
69
+ const offset = offsetEl ? integer(textOf(offsetEl).trim()) : undefined;
70
+ const align = kid(el, WP, "align");
71
+ if (offset !== undefined && offset >= -MAX_EMU - 1 && offset <= MAX_EMU)
72
+ return { relativeTo, offset };
73
+ if (align) return { relativeTo, align: textOf(align).trim() };
74
+ return undefined;
75
+ }
76
+
77
+ /** The `float` of a `wp:anchor`: undefined for one the model cannot hold (kept opaque). */
78
+ export function floatOf(anchor: XmlElement): Record<string, unknown> | undefined {
79
+ const horizontal = position(kid(anchor, WP, "positionH"));
80
+ const vertical = position(kid(anchor, WP, "positionV"));
81
+ // Kept opaque: a position from the page's corner (`simplePos="1"`), a hidden picture, and a
82
+ // size relative to the page (`wp14:sizeRelH`/`sizeRelV`, which a new extent would not change).
83
+ if (
84
+ !horizontal ||
85
+ !vertical ||
86
+ flag(plain(anchor, "simplePos")) === true ||
87
+ flag(plain(anchor, "hidden")) === true ||
88
+ anchor.children.some(
89
+ (c) =>
90
+ c.kind === "element" &&
91
+ (c.local === "sizeRelH" || c.local === "sizeRelV") &&
92
+ // Word writes a percentage of 0 on every anchor: the size is its extent then.
93
+ c.children.some(
94
+ (p) => p.kind === "element" && /^pct/.test(p.local) && Number(textOf(p).trim()) !== 0,
95
+ ),
96
+ )
97
+ )
98
+ return undefined;
99
+ const wrapEl = anchor.children.find(
100
+ (c): c is XmlElement => c.kind === "element" && c.ns === WP && c.local.startsWith("wrap"),
101
+ );
102
+ const wrap = !wrapEl
103
+ ? undefined
104
+ : wrapEl.local === "wrapNone"
105
+ ? flag(plain(anchor, "behindDoc"))
106
+ ? "behind"
107
+ : "inFront"
108
+ : WRAPS[wrapEl.local];
109
+ if (!wrap) return undefined;
110
+ const side = plain(wrapEl, "wrapText");
111
+ const distance = {
112
+ top: emu(plain(anchor, "distT")) ?? 0,
113
+ bottom: emu(plain(anchor, "distB")) ?? 0,
114
+ left: emu(plain(anchor, "distL")) ?? 0,
115
+ right: emu(plain(anchor, "distR")) ?? 0,
116
+ };
117
+ const allowOverlap = flag(plain(anchor, "allowOverlap"));
118
+ const layoutInCell = flag(plain(anchor, "layoutInCell"));
119
+ return {
120
+ horizontal,
121
+ vertical,
122
+ wrap,
123
+ ...(side && SIDES.has(side) ? { side } : {}),
124
+ distance,
125
+ ...(allowOverlap !== undefined ? { allowOverlap } : {}),
126
+ ...(layoutInCell !== undefined ? { layoutInCell } : {}),
127
+ };
128
+ }
129
+
130
+ /**
131
+ * The picture node's attributes for `drawing`, its image added to `resources`; undefined for
132
+ * a drawing Foli keeps opaque (not one inline picture, no embedded image part).
133
+ */
134
+ export function pictureAttrs(
135
+ drawing: XmlElement,
136
+ context: PictureContext,
137
+ /** Filled with the image's resource key and entry. */
138
+ resource: [string?, ResourceJSON?] = [],
139
+ ): Record<string, unknown> | undefined {
140
+ const children = drawing.children.filter((c) => c.kind === "element");
141
+ const inline = kid(drawing, WP, "inline") ?? kid(drawing, WP, "anchor");
142
+ if (!inline || children.length !== 1) return undefined;
143
+ const float = inline.local === "anchor" ? floatOf(inline) : null;
144
+ if (float === undefined) return undefined;
145
+ const data = descendant(inline, A, "graphicData");
146
+ if (plain(data, "uri") !== PIC) return undefined;
147
+ const blip = descendant(data, A, "blip");
148
+ const id = attr(blip, "embed", R);
149
+ const relationship = id === undefined ? undefined : context.relationship(id);
150
+ if (!relationship || relationship.type !== IMAGE || relationship.external) return undefined;
151
+ const name = relationship.partName;
152
+ const part = name ? context.partOf(name) : undefined;
153
+ if (!name || !part?.contentType.startsWith("image/")) return undefined;
154
+ const extent = kid(inline, WP, "extent");
155
+ const width = emu(plain(extent, "cx"));
156
+ const height = emu(plain(extent, "cy"));
157
+ if (width === undefined || height === undefined) return undefined;
158
+ const key = name.replace(/^\//, "");
159
+ // Added by the caller once the node is valid (a drawing kept opaque has no resource).
160
+ resource.push(key, { contentType: part.contentType, size: part.data.length, part: key });
161
+ const docPr = kid(inline, WP, "docPr");
162
+ const alt = plain(docPr, "descr");
163
+ const title = plain(docPr, "title");
164
+ const decorative = plain(descendant(docPr, ADEC, "decorative"), "val");
165
+ return {
166
+ resource: key,
167
+ width,
168
+ height,
169
+ // An empty description is kept as it is (it is not Word's missing one).
170
+ ...(alt !== undefined ? { alt } : {}),
171
+ ...(title !== undefined ? { title } : {}),
172
+ ...(decorative === "1" || decorative === "true" ? { decorative: true } : {}),
173
+ ...(float ? { float } : {}),
174
+ ext: sourceOf(context, drawing),
175
+ };
176
+ }
@@ -252,7 +252,10 @@ export function runProperties(rPr: XmlElement | undefined, context: Context): Ma
252
252
  break;
253
253
  case "rPrChange": {
254
254
  const { id, author, date } = revisionOf(el);
255
- const previous = runProperties(child(el, "rPr"), context);
255
+ // In canonical form, as the editor records it (attributes left at their defaults out).
256
+ const previous = runProperties(child(el, "rPr"), context).map((m) =>
257
+ schema.markFromJSON(m).toJSON(),
258
+ );
256
259
  const change = { type: "formatChange", attrs: { id, author, date, previous } };
257
260
  marks.push(
258
261
  mark(change, el.name, context) ??
@@ -15,6 +15,11 @@ export interface ImportReport {
15
15
  */
16
16
  readonly unmodeled: readonly string[];
17
17
  readonly unmodeledCount: number;
18
+ /**
19
+ * Pictures with no alt text that are not marked decorative: allowed (Word allows them), but a
20
+ * screen reader has nothing to say for them.
21
+ */
22
+ readonly picturesWithoutAlt: number;
18
23
  }
19
24
 
20
25
  export class Recorder {
@@ -23,6 +28,7 @@ export class Recorder {
23
28
  readonly #dropped = new Map<string, number>();
24
29
  readonly #unmodeled: string[] = [];
25
30
  #unmodeledCount = 0;
31
+ #withoutAlt = 0;
26
32
  /** The part being read, for messages. */
27
33
  part = "";
28
34
 
@@ -39,12 +45,17 @@ export class Recorder {
39
45
  if (this.#unmodeled.length < 100) this.#unmodeled.push(`${this.part}: ${element}: ${reason}`);
40
46
  }
41
47
 
48
+ withoutAlt(): void {
49
+ this.#withoutAlt++;
50
+ }
51
+
42
52
  report(): ImportReport {
43
53
  return {
44
54
  opaque: sorted(this.#opaque),
45
55
  dropped: sorted(this.#dropped),
46
56
  unmodeled: [...this.#unmodeled],
47
57
  unmodeledCount: this.#unmodeledCount,
58
+ picturesWithoutAlt: this.#withoutAlt,
48
59
  };
49
60
  }
50
61
  }
@@ -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
- export { exportDocx } from "./export/index.js";
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,