@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
@@ -1,4 +1,12 @@
1
- import { type FoliDocument, parseDocument } from "@folijs/core";
1
+ import {
2
+ type ControlJSON,
3
+ type FoliDocument,
4
+ parseDocument,
5
+ type ResourceJSON,
6
+ SCHEMA_VERSION,
7
+ type StoryJSON,
8
+ type WordSettingsJSON,
9
+ } from "@folijs/core";
2
10
  import {
3
11
  DocxError,
4
12
  type DocxPackage,
@@ -6,16 +14,19 @@ import {
6
14
  type Relationship,
7
15
  readPackage,
8
16
  } from "../package.js";
9
- import { trackRevisionsOf } from "../settings.js";
17
+ import { readSettings, trackRevisionsOf } from "../settings.js";
10
18
  import type { XmlElement } from "../xml.js";
11
19
  import { blocks, type ContentContext, Moves } from "./content.js";
12
20
  import { child, isW, REL, W_STRICT } from "./ooxml.js";
13
21
  import { comments, numbering, styles, theme } from "./parts.js";
14
22
  import { section } from "./properties.js";
15
23
  import { type ImportReport, Recorder } from "./report.js";
24
+ import { canonicalStories, readStories } from "./stories.js";
25
+
26
+ export { noteIds } from "./stories.js";
16
27
 
17
28
  export interface DocxImport {
18
- /** The document in schema v3, validated. */
29
+ /** The document in the current schema (v5), validated. */
19
30
  readonly document: FoliDocument;
20
31
  /**
21
32
  * The package it was read from. Export (8.5) writes the parts Foli does not edit back from
@@ -56,6 +67,8 @@ export function importPackage(pkg: DocxPackage): DocxImport {
56
67
  const body = child(main.root, "body");
57
68
  if (!body) throw new DocxError(`${pkg.mainDocument}: no w:body`);
58
69
 
70
+ const resources = new Map<string, ResourceJSON>();
71
+ const controls = new Map<string, ControlJSON>();
59
72
  const contextFor = (part: string, source: string): ContentContext => {
60
73
  report.part = part;
61
74
  // One lookup table per part: hyperlinks resolve in constant time.
@@ -64,7 +77,17 @@ export function importPackage(pkg: DocxPackage): DocxImport {
64
77
  byId ??= new Map(pkg.relationships(part).map((r) => [r.id, r]));
65
78
  return byId.get(id);
66
79
  };
67
- return { source, report, pkg, part, moves: new Moves(), relationship };
80
+ return {
81
+ source,
82
+ report,
83
+ pkg,
84
+ part,
85
+ moves: new Moves(),
86
+ relationship,
87
+ resources,
88
+ controls,
89
+ ordinals: { next: 0 },
90
+ };
68
91
  };
69
92
  const related = (
70
93
  type: string,
@@ -108,17 +131,38 @@ export function importPackage(pkg: DocxPackage): DocxImport {
108
131
  contextFor(commentsPart.name, commentsPart.source),
109
132
  )
110
133
  : [];
134
+ const stories = readStories(pkg, contextFor);
135
+ const usedControls = controlsUsed([content, commented, stories]);
136
+ // A settings part Foli cannot read is kept as it is, and read as saying nothing.
137
+ let trackRevisions = false;
138
+ let settings: WordSettingsJSON | undefined;
139
+ try {
140
+ const root = related(REL.settings)?.root;
141
+ trackRevisions = trackRevisionsOf(root);
142
+ settings = readSettings(root);
143
+ } catch (error) {
144
+ if (!(error instanceof DocxError)) throw error;
145
+ }
111
146
 
112
147
  let document: FoliDocument;
113
148
  try {
114
149
  document = parseDocument({
115
- schemaVersion: 3,
150
+ schemaVersion: SCHEMA_VERSION,
116
151
  section: lastSection,
152
+ ...(settings ? { settings } : {}),
117
153
  defaults: styled.defaults,
118
154
  styles: styled.styles,
119
155
  numbering: numbered,
120
156
  ...(themed ? { theme: themed } : {}),
121
157
  comments: commented,
158
+ ...(resources.size ? { resources: Object.fromEntries(resources) } : {}),
159
+ ...(Object.keys(stories).length ? { stories } : {}),
160
+ ...(settings ? { settings } : {}),
161
+ ...(usedControls.size
162
+ ? {
163
+ controls: Object.fromEntries([...controls].filter(([id]) => usedControls.has(id))),
164
+ }
165
+ : {}),
122
166
  content: { type: "doc", content },
123
167
  });
124
168
  } catch (error) {
@@ -126,14 +170,45 @@ export function importPackage(pkg: DocxPackage): DocxImport {
126
170
  // element over 16 MiB kept verbatim…). A DocxError like every other import failure.
127
171
  throw new DocxError(`Cannot import: ${(error as Error).message}`, { cause: error });
128
172
  }
129
- // A settings part Foli cannot read is kept as it is, and tracking taken as off.
130
- let trackRevisions = false;
131
- try {
132
- trackRevisions = trackRevisionsOf(related(REL.settings)?.root);
133
- } catch (error) {
134
- if (!(error instanceof DocxError)) throw error;
135
- }
136
173
  return { document, package: pkg, report: report.report(), trackRevisions };
137
174
  }
138
175
 
176
+ /** The ids of the controls `content` holds (one read but kept verbatim after all has none). */
177
+ export function controlsUsed(content: unknown): Set<string> {
178
+ const used = new Set<string>();
179
+ JSON.stringify(content, (key, value) => {
180
+ if (key === "controls" && Array.isArray(value)) for (const id of value) used.add(id);
181
+ const node = value as { type?: unknown; attrs?: { id?: unknown } } | null;
182
+ if (node?.type === "controlStart" && typeof node.attrs?.id === "string")
183
+ used.add(node.attrs.id);
184
+ return value;
185
+ });
186
+ return used;
187
+ }
188
+
189
+ /** The package's stories and their controls, as a validated document holds them. */
190
+ export function packageStories(pkg: DocxPackage): {
191
+ stories: Record<string, StoryJSON>;
192
+ controls: Map<string, ControlJSON>;
193
+ } {
194
+ const report = new Recorder();
195
+ const resources = new Map<string, ResourceJSON>();
196
+ const controls = new Map<string, ControlJSON>();
197
+ const stories = canonicalStories(pkg, (part, source) => {
198
+ const byId = new Map(pkg.relationships(part).map((r) => [r.id, r]));
199
+ return {
200
+ source,
201
+ report,
202
+ pkg,
203
+ part,
204
+ moves: new Moves(),
205
+ relationship: (id) => byId.get(id),
206
+ resources,
207
+ controls,
208
+ ordinals: { next: 0 },
209
+ };
210
+ });
211
+ return { stories, controls };
212
+ }
213
+
139
214
  export type { ImportReport } from "./report.js";
@@ -18,6 +18,10 @@ export const REL = {
18
18
  commentsExtended: "http://schemas.microsoft.com/office/2011/relationships/commentsExtended",
19
19
  hyperlink: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
20
20
  settings: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",
21
+ header: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header",
22
+ footer: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer",
23
+ footnotes: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes",
24
+ endnotes: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes",
21
25
  };
22
26
 
23
27
  /** 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
  }
@@ -381,7 +394,7 @@ export function comments(
381
394
  if (initials !== undefined && initials.length > 9) {
382
395
  context.report.unmodeled("w:comment@w:initials", "longer than 9");
383
396
  }
384
- const content = blocks(el.children, context);
397
+ const content = blocks(el.children, { ...context, story: "comment" });
385
398
  const comment = compact({
386
399
  id: commentId,
387
400
  author: author.length <= 255 ? author : author.slice(0, 255),
@@ -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
+ }
@@ -19,6 +19,13 @@ export function sourceOf(context: Context, element: XmlElement): string {
19
19
  return context.source.slice(element.start, element.end);
20
20
  }
21
21
 
22
+ /** `object` without its undefined values. */
23
+ export function compactDefined<T extends Record<string, unknown>>(object: T): Partial<T> {
24
+ return Object.fromEntries(
25
+ Object.entries(object).filter(([, value]) => value !== undefined),
26
+ ) as Partial<T>;
27
+ }
28
+
22
29
  const ATTRIBUTE_NAME = /^[A-Za-z_][\w.-]*(:[A-Za-z_][\w.-]*)?$/;
23
30
 
24
31
  /**
@@ -458,9 +465,54 @@ export function paragraphProperties(
458
465
  return out;
459
466
  }
460
467
 
468
+ /** `w:footnotePr` or `w:endnotePr` of a section: how its notes are placed and numbered. */
469
+ function noteProperties(element: XmlElement | undefined, context: Context) {
470
+ if (!element) return undefined;
471
+ const value = (local: string) => attr(child(element, local), "val");
472
+ return compact({
473
+ position: value("pos"),
474
+ format: value("numFmt"),
475
+ start: whole(child(element, "numStart"), "val", context),
476
+ restart: value("numRestart"),
477
+ });
478
+ }
479
+
480
+ /** `w:cols`: `widths` from its `w:col` children, when it has them. */
481
+ function sectionColumns(cols: XmlElement | undefined, context: Context) {
482
+ if (!cols) return undefined;
483
+ const on = (local: string) => {
484
+ const value = attr(cols, local);
485
+ return value === undefined ? undefined : !["0", "false", "off"].includes(value);
486
+ };
487
+ const widths = elements(cols)
488
+ .filter((el) => isW(el, "col"))
489
+ .map((el) => compact({ width: whole(el, "w", context), space: whole(el, "space", context) }));
490
+ return compact({
491
+ count: whole(cols, "num", context),
492
+ space: whole(cols, "space", context),
493
+ equalWidth: on("equalWidth"),
494
+ separator: on("sep"),
495
+ widths: widths.length ? widths : undefined,
496
+ });
497
+ }
498
+
499
+ /** `w:sectPrChange`: who changed the section's setup, and the setup before (`w:sectPr`). */
500
+ function sectionChange(element: XmlElement | undefined, context: Context) {
501
+ if (!element) return undefined;
502
+ const { id, author, date } = revisionOf(element);
503
+ const before = child(element, "sectPr");
504
+ return compact({
505
+ id,
506
+ author,
507
+ date: date ?? undefined,
508
+ previous: before ? section(before, context) : {},
509
+ });
510
+ }
511
+
461
512
  /** `w:sectPr` as a section; every part checked on its own. */
462
513
  export function section(sectPr: XmlElement, context: Context): Record<string, unknown> {
463
514
  const pgSz = child(sectPr, "pgSz");
515
+ const pgNumType = child(sectPr, "pgNumType");
464
516
  const pgMar = child(sectPr, "pgMar");
465
517
  const references = (local: string) =>
466
518
  compact(
@@ -494,6 +546,13 @@ export function section(sectPr: XmlElement, context: Context): Record<string, un
494
546
  titlePage: titlePg ? toggle(titlePg) : undefined,
495
547
  headers: references("headerReference"),
496
548
  footers: references("footerReference"),
549
+ columns: sectionColumns(child(sectPr, "cols"), context),
550
+ pageNumbers:
551
+ pgNumType &&
552
+ compact({ start: whole(pgNumType, "start", context), format: attr(pgNumType, "fmt") }),
553
+ footnotes: noteProperties(child(sectPr, "footnotePr"), context),
554
+ endnotes: noteProperties(child(sectPr, "endnotePr"), context),
555
+ change: sectionChange(child(sectPr, "sectPrChange"), context),
497
556
  };
498
557
  const out: Record<string, unknown> = {};
499
558
  for (const [key, value] of Object.entries(parts)) {
@@ -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,122 @@
1
+ /**
2
+ * Headers, footers, footnotes and endnotes as stories (ADR-0007): content trees of their own,
3
+ * read from their parts with the same reader as the body. A header's or footer's id is its
4
+ * relationship id; a note's is `footnote:<w:id>` or `endnote:<w:id>`. A note the model cannot
5
+ * name stays in its part, untouched.
6
+ */
7
+ import { parseContent, type StoryJSON } from "@folijs/core";
8
+ import type { DocxPackage } from "../package.js";
9
+ import type { XmlElement } from "../xml.js";
10
+ import { blocks, type ContentContext } from "./content.js";
11
+ import { attr, elements, integer, isW, REL } from "./ooxml.js";
12
+
13
+ const NOTE_TYPES = new Set(["normal", "separator", "continuationSeparator", "continuationNotice"]);
14
+
15
+ /** The notes of a footnotes or endnotes part that the model holds, by story id. */
16
+ export function notesOf(root: XmlElement, kind: "footnote" | "endnote"): Map<string, XmlElement> {
17
+ const out = new Map<string, XmlElement>();
18
+ for (const el of elements(root)) {
19
+ if (!isW(el, kind)) continue;
20
+ const id = integer(attr(el, "id"));
21
+ const type = attr(el, "type");
22
+ const key = `${kind}:${id}`;
23
+ if (id === undefined || (type !== undefined && !NOTE_TYPES.has(type)) || out.has(key)) continue;
24
+ out.set(key, el);
25
+ }
26
+ return out;
27
+ }
28
+
29
+ const docOf = (content: StoryJSON["content"]["content"]): StoryJSON["content"] => ({
30
+ type: "doc",
31
+ content: content?.length ? content : [{ type: "paragraph" }],
32
+ });
33
+
34
+ /** Every story of the package, by id. `contextFor` gives the reading context of a part. */
35
+ export function readStories(
36
+ pkg: DocxPackage,
37
+ contextFor: (part: string, source: string) => ContentContext,
38
+ ): Record<string, StoryJSON> {
39
+ const stories: Record<string, StoryJSON> = {};
40
+ const notesRead = new Set<string>();
41
+ for (const relationship of pkg.relationships(pkg.mainDocument)) {
42
+ const part = relationship.partName ? pkg.part(relationship.partName) : undefined;
43
+ if (relationship.external || !part) continue;
44
+ const headerOrFooter =
45
+ relationship.type === REL.header
46
+ ? ["header", "hdr"]
47
+ : relationship.type === REL.footer
48
+ ? ["footer", "ftr"]
49
+ : undefined;
50
+ const note =
51
+ relationship.type === REL.footnotes
52
+ ? "footnote"
53
+ : relationship.type === REL.endnotes
54
+ ? "endnote"
55
+ : undefined;
56
+ if (!headerOrFooter && !note) continue;
57
+ // A part that is not XML (a relationship can point anywhere) stays as it is.
58
+ let xml: ReturnType<DocxPackage["xml"]>;
59
+ try {
60
+ xml = pkg.xml(part.name);
61
+ } catch {
62
+ continue;
63
+ }
64
+ const context = contextFor(part.name, xml.source);
65
+ if (headerOrFooter) {
66
+ const [kind, root] = headerOrFooter as ["header" | "footer", string];
67
+ // An id the envelope cannot hold as a key: the part stays as it is.
68
+ if (!isW(xml.root, root) || relationship.id === "__proto__") continue;
69
+ stories[relationship.id] = {
70
+ kind,
71
+ content: docOf(blocks(xml.root.children, { ...context, story: kind })),
72
+ };
73
+ } else if (note) {
74
+ // One part per kind, of the right kind: any other stays as it is.
75
+ if (notesRead.has(note) || !isW(xml.root, `${note}s`)) continue;
76
+ notesRead.add(note);
77
+ for (const [key, el] of notesOf(xml.root, note)) {
78
+ const type = attr(el, "type");
79
+ stories[key] = {
80
+ kind: note,
81
+ ...(type ? { noteType: type as StoryJSON["noteType"] & string } : {}),
82
+ content: docOf(blocks(el.children, { ...context, story: note })),
83
+ ext: xml.source.slice(el.start, el.openEnd),
84
+ };
85
+ }
86
+ }
87
+ }
88
+ return stories;
89
+ }
90
+
91
+ /** The ids of every note in the package's notes parts, those the model does not hold too. */
92
+ export function noteIds(pkg: DocxPackage): Set<string> {
93
+ const ids = new Set<string>();
94
+ for (const [type, kind] of [
95
+ [REL.footnotes, "footnote"],
96
+ [REL.endnotes, "endnote"],
97
+ ] as const) {
98
+ const name = pkg.relationships(pkg.mainDocument).find((r) => r.type === type)?.partName;
99
+ if (!name || !pkg.part(name)) continue;
100
+ let root: XmlElement;
101
+ try {
102
+ root = pkg.xml(name).root;
103
+ } catch {
104
+ continue;
105
+ }
106
+ for (const el of elements(root)) {
107
+ const id = integer(attr(el, "id"));
108
+ if (isW(el, kind) && id !== undefined) ids.add(`${kind}:${id}`);
109
+ }
110
+ }
111
+ return ids;
112
+ }
113
+
114
+ /** The stories in the form a validated document holds them, to compare with one. */
115
+ export function canonicalStories(
116
+ pkg: DocxPackage,
117
+ contextFor: (part: string, source: string) => ContentContext,
118
+ ): Record<string, StoryJSON> {
119
+ const stories = readStories(pkg, contextFor);
120
+ for (const story of Object.values(stories)) story.content = parseContent(story.content).toJSON();
121
+ return stories;
122
+ }