@folijs/docx 0.5.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 (74) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +42 -14
  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 +5 -0
  8. package/dist/export/content.d.ts.map +1 -1
  9. package/dist/export/content.js +155 -22
  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.map +1 -1
  16. package/dist/export/index.js +214 -18
  17. package/dist/export/index.js.map +1 -1
  18. package/dist/export/parts.d.ts +9 -1
  19. package/dist/export/parts.d.ts.map +1 -1
  20. package/dist/export/parts.js +56 -2
  21. package/dist/export/parts.js.map +1 -1
  22. package/dist/export/pictures.d.ts +3 -0
  23. package/dist/export/pictures.d.ts.map +1 -1
  24. package/dist/export/pictures.js +15 -2
  25. package/dist/export/pictures.js.map +1 -1
  26. package/dist/export/properties.d.ts.map +1 -1
  27. package/dist/export/properties.js +56 -2
  28. package/dist/export/properties.js.map +1 -1
  29. package/dist/import/content.d.ts +11 -1
  30. package/dist/import/content.d.ts.map +1 -1
  31. package/dist/import/content.js +205 -17
  32. package/dist/import/content.js.map +1 -1
  33. package/dist/import/controls.d.ts +14 -0
  34. package/dist/import/controls.d.ts.map +1 -0
  35. package/dist/import/controls.js +123 -0
  36. package/dist/import/controls.js.map +1 -0
  37. package/dist/import/index.d.ts +10 -2
  38. package/dist/import/index.d.ts.map +1 -1
  39. package/dist/import/index.js +73 -12
  40. package/dist/import/index.js.map +1 -1
  41. package/dist/import/ooxml.d.ts +4 -0
  42. package/dist/import/ooxml.d.ts.map +1 -1
  43. package/dist/import/ooxml.js +4 -0
  44. package/dist/import/ooxml.js.map +1 -1
  45. package/dist/import/parts.js +1 -1
  46. package/dist/import/parts.js.map +1 -1
  47. package/dist/import/properties.d.ts +2 -0
  48. package/dist/import/properties.d.ts.map +1 -1
  49. package/dist/import/properties.js +55 -0
  50. package/dist/import/properties.js.map +1 -1
  51. package/dist/import/stories.d.ts +19 -0
  52. package/dist/import/stories.d.ts.map +1 -0
  53. package/dist/import/stories.js +119 -0
  54. package/dist/import/stories.js.map +1 -0
  55. package/dist/settings.d.ts +18 -4
  56. package/dist/settings.d.ts.map +1 -1
  57. package/dist/settings.js +173 -26
  58. package/dist/settings.js.map +1 -1
  59. package/package.json +3 -3
  60. package/src/export/balance.ts +113 -0
  61. package/src/export/content.ts +200 -19
  62. package/src/export/controls.ts +259 -0
  63. package/src/export/index.ts +254 -17
  64. package/src/export/parts.ts +79 -2
  65. package/src/export/pictures.ts +8 -2
  66. package/src/export/properties.ts +68 -2
  67. package/src/import/content.ts +220 -17
  68. package/src/import/controls.ts +137 -0
  69. package/src/import/index.ts +84 -11
  70. package/src/import/ooxml.ts +4 -0
  71. package/src/import/parts.ts +1 -1
  72. package/src/import/properties.ts +59 -0
  73. package/src/import/stories.ts +122 -0
  74. package/src/settings.ts +191 -27
@@ -4,10 +4,17 @@
4
4
  * for markers that have nothing to show: field characters, range ends).
5
5
  */
6
6
 
7
- import { type MarkJSON, type NodeJSON, type ResourceJSON, schema } from "@folijs/core";
7
+ import {
8
+ type ControlJSON,
9
+ type MarkJSON,
10
+ type NodeJSON,
11
+ type ResourceJSON,
12
+ schema,
13
+ } from "@folijs/core";
8
14
  import type { DocxPackage, Relationship } from "../package.js";
9
15
  import type { XmlElement, XmlNode } from "../xml.js";
10
- import { attr, child, deepText, integer, isW, R, REL, textOf, W } from "./ooxml.js";
16
+ import { controlProperties } from "./controls.js";
17
+ import { attr, child, deepText, elements, integer, isW, R, REL, textOf, W } from "./ooxml.js";
11
18
  import { pictureAttrs } from "./pictures.js";
12
19
  import {
13
20
  attributeBag,
@@ -33,6 +40,14 @@ export interface ContentContext extends Context {
33
40
  readonly tableDepth?: number;
34
41
  /** The envelope's resources (pictures' images), filled as content is read. */
35
42
  readonly resources: Map<string, ResourceJSON>;
43
+ /** The envelope's content controls, filled as content is read. */
44
+ readonly controls: Map<string, ControlJSON>;
45
+ /** Numbers the part's controls: their ids are `<part>#<n>`, the same on every reading. */
46
+ readonly ordinals: { next: number };
47
+ /**
48
+ * The kind of story being read (ADR-0007), or a comment: what one may not hold stays verbatim.
49
+ */
50
+ readonly story?: "header" | "footer" | "footnote" | "endnote" | "comment";
36
51
  }
37
52
 
38
53
  /** Tables nested deeper stay opaque: within the model's depth (three levels per table). */
@@ -87,6 +102,9 @@ const INLINE_LABELS: Record<string, string | null> = {
87
102
  customXmlDelRangeEnd: null,
88
103
  };
89
104
 
105
+ /** What a separator note holds: kept in its run, with nothing to report or edit. */
106
+ const NOTE_SEPARATORS = new Set(["separator", "continuationSeparator", "continuationNotice"]);
107
+
90
108
  /** Recomputed by Word, never kept: spelling marks, the last rendered page breaks. */
91
109
  const DROPPED = new Set(["proofErr", "lastRenderedPageBreak"]);
92
110
 
@@ -110,6 +128,8 @@ export function blocks(
110
128
  for (const node of nodes) {
111
129
  if (node.kind !== "element" || node === section) continue;
112
130
  if (isW(node, "p")) out.push(paragraph(node, context));
131
+ else if (isW(node, "sdt"))
132
+ out.push(...(blockControl(node, context) ?? [opaqueOf(node, context)]));
113
133
  else if (isW(node, "tbl")) {
114
134
  // A table right after a table is one table to Word (it merges them): kept verbatim.
115
135
  const table = out.at(-1)?.type === "table" ? undefined : tableOf(node, context);
@@ -125,6 +145,72 @@ export function blocks(
125
145
  return out;
126
146
  }
127
147
 
148
+ /** A control's properties taken into the envelope, its id and its content element. */
149
+ function controlOf(
150
+ sdt: XmlElement,
151
+ context: ContentContext,
152
+ ): { id: string; content: XmlElement } | undefined {
153
+ const content = child(sdt, "sdtContent");
154
+ if (!content || sdt.attributes.length) return undefined;
155
+ const children = elements(sdt);
156
+ const once = (local: string) => children.filter((c) => isW(c, local)).length <= 1;
157
+ const known = new Set(["sdtPr", "sdtEndPr", "sdtContent"]);
158
+ if (children.some((c) => !isW(c) || !known.has(c.local))) return undefined;
159
+ if (![...known].every(once)) return undefined;
160
+ const control = controlProperties(sdt, context);
161
+ if (!control) return undefined;
162
+ const id = `${context.part}#${context.ordinals.next++}`;
163
+ context.controls.set(id, control);
164
+ return { id, content };
165
+ }
166
+
167
+ /** How many controls the model lets a block, row or cell be in. */
168
+ const MAX_CONTROLS = 64;
169
+ const roomForControl = (node: NodeJSON) =>
170
+ ((node.attrs?.controls as string[] | undefined)?.length ?? 0) < MAX_CONTROLS;
171
+
172
+ /** `node` inside control `id`, outermost first. */
173
+ function inControl(node: NodeJSON, id: string): NodeJSON {
174
+ const controls = [id, ...((node.attrs?.controls as string[] | undefined) ?? [])];
175
+ return { ...node, attrs: { ...node.attrs, controls } };
176
+ }
177
+
178
+ /** A block-level control's blocks, each listing it; undefined keeps it verbatim (one that is empty). */
179
+ function blockControl(sdt: XmlElement, context: ContentContext): NodeJSON[] | undefined {
180
+ const control = controlOf(sdt, context);
181
+ if (!control) return undefined;
182
+ const inner = blocks(control.content.children, context);
183
+ if (!inner.length || !inner.every(roomForControl)) return undefined;
184
+ return inner.map((block) => inControl(block, control.id));
185
+ }
186
+
187
+ /**
188
+ * The rows (or cells) among `nodes`, those in row-level (cell-level) controls listing them;
189
+ * undefined when anything else is there, which keeps the table verbatim.
190
+ */
191
+ function controlled(
192
+ nodes: readonly XmlNode[],
193
+ local: "tr" | "tc",
194
+ read: (el: XmlElement) => NodeJSON | undefined,
195
+ context: ContentContext,
196
+ ): NodeJSON[] | undefined {
197
+ const out: NodeJSON[] = [];
198
+ for (const node of nodes) {
199
+ if (node.kind !== "element") continue;
200
+ if (isW(node, local)) {
201
+ const item = read(node);
202
+ if (!item) return undefined;
203
+ out.push(item);
204
+ } else if (isW(node, "sdt")) {
205
+ const control = controlOf(node, context);
206
+ const inner = control && controlled(control.content.children, local, read, context);
207
+ if (!control || !inner?.length || !inner.every(roomForControl)) return undefined;
208
+ out.push(...inner.map((item) => inControl(item, control.id)));
209
+ } else return undefined;
210
+ }
211
+ return out;
212
+ }
213
+
128
214
  function opaqueOf(node: XmlElement, context: ContentContext): NodeJSON {
129
215
  context.report.opaque(node.name);
130
216
  return {
@@ -154,11 +240,11 @@ function tableOf(tbl: XmlElement, context: ContentContext): NodeJSON | undefined
154
240
  } else if (stage <= 1 && isW(c, "tblGrid")) {
155
241
  tblGrid = c;
156
242
  stage = 2;
157
- } else if (isW(c, "tr")) {
243
+ } else if (isW(c, "tr") || isW(c, "sdt")) {
158
244
  stage = 2;
159
- const row = rowOf(c, inner);
160
- if (!row) return undefined;
161
- rows.push(row);
245
+ const read = controlled([c], "tr", (tr) => rowOf(tr, inner), inner);
246
+ if (!read) return undefined;
247
+ rows.push(...read);
162
248
  } else return undefined;
163
249
  }
164
250
  if (!rows.length) return undefined;
@@ -188,11 +274,11 @@ function rowOf(tr: XmlElement, context: ContentContext): NodeJSON | undefined {
188
274
  } else if (stage <= 1 && isW(c, "trPr")) {
189
275
  trPr = c;
190
276
  stage = 2;
191
- } else if (isW(c, "tc")) {
277
+ } else if (isW(c, "tc") || isW(c, "sdt")) {
192
278
  stage = 2;
193
- const cell = cellOf(c, context);
194
- if (!cell) return undefined;
195
- cells.push(cell);
279
+ const read = controlled([c], "tc", (tc) => cellOf(tc, context), context);
280
+ if (!read) return undefined;
281
+ cells.push(...read);
196
282
  } else return undefined;
197
283
  }
198
284
  if (!cells.length) return undefined;
@@ -244,7 +330,10 @@ function withLabel(attrs: Record<string, unknown>, value: string | null): Record
244
330
  }
245
331
 
246
332
  export function paragraph(p: XmlElement, context: ContentContext): NodeJSON {
247
- const attrs: Record<string, unknown> = paragraphProperties(child(p, "pPr"), context, true);
333
+ // A story ends no section: such a paragraph stays as it is.
334
+ const pPr = child(p, "pPr");
335
+ if (context.story && pPr && child(pPr, "sectPr")) return opaqueOf(p, context);
336
+ const attrs: Record<string, unknown> = paragraphProperties(pPr, context, true);
248
337
  const bag = attributeBag(p, [], context);
249
338
  if (bag) setParagraph(attrs, "attributes", bag, p.name, context);
250
339
  const content: NodeJSON[] = [];
@@ -326,6 +415,11 @@ function inlines(
326
415
  case "commentRangeStart":
327
416
  case "commentRangeEnd": {
328
417
  const type = MARKER_TYPES[el.local] as string;
418
+ // Stories hold no comments (ADR-0007): such an anchor stays verbatim.
419
+ if (type.startsWith("comment") && context.story && context.story !== "comment") {
420
+ opaque(el, BLOCK_LABELS);
421
+ break;
422
+ }
329
423
  const isStart = type === "bookmarkStart";
330
424
  const bag = attributeBag(el, isStart ? ["w:id", "w:name"] : ["w:id"], context);
331
425
  const attrs: Record<string, unknown> = { id: integer(attr(el, "id")) };
@@ -350,9 +444,37 @@ function inlines(
350
444
  context.moves.close(el.local.startsWith("moveFrom") ? "from" : "to", attr(el, "id") ?? "");
351
445
  opaque(el);
352
446
  break;
353
- case "fldSimple":
354
- opaque(el, INLINE_LABELS, deepText(el) || attr(el, "instr")?.trim() || "field");
447
+ case "fldSimple": {
448
+ const instruction = attr(el, "instr");
449
+ const start = node("fieldStart", {
450
+ simple: true,
451
+ // The start tag, as an element holding the result has it.
452
+ ext: context.source.slice(el.start, el.openEnd).replace(/\/>$/, ">"),
453
+ });
454
+ const code = node("fieldCode", { text: instruction ?? "" });
455
+ const leaves = valid(start, el, context) && valid(code, el, context);
456
+ if (instruction === undefined || !leaves) {
457
+ opaque(el, INLINE_LABELS, deepText(el) || "field");
458
+ break;
459
+ }
460
+ out.push(start, code, node("fieldSeparator"));
461
+ inlines(el.children, marks, context, out);
462
+ out.push(node("fieldEnd"));
355
463
  break;
464
+ }
465
+ case "sdt": {
466
+ const blocksInside = (c: XmlElement) =>
467
+ elements(c).some((e) => isW(e, "p") || isW(e, "tbl"));
468
+ const control = controlOf(el, context);
469
+ if (!control || blocksInside(control.content)) {
470
+ opaque(el);
471
+ break;
472
+ }
473
+ out.push(node("controlStart", { id: control.id }));
474
+ inlines(control.content.children, marks, context, out);
475
+ out.push(node("controlEnd", { id: control.id }));
476
+ break;
477
+ }
356
478
  default:
357
479
  if (DROPPED.has(el.local)) context.report.dropped(el.name);
358
480
  else opaque(el);
@@ -480,7 +602,9 @@ function run(
480
602
  break;
481
603
  case "br": {
482
604
  const type = attr(el, "type");
483
- if (type === "page") out.push(node("pageBreak", marks));
605
+ const inNote = context.story === "footnote" || context.story === "endnote";
606
+ if ((type === "page" || type === "column") && inNote) opaqueRun(el);
607
+ else if (type === "page") out.push(node("pageBreak", marks));
484
608
  else if (type === "column") out.push(node("columnBreak", marks));
485
609
  else {
486
610
  const clear = attr(el, "clear");
@@ -518,6 +642,10 @@ function run(
518
642
  break;
519
643
  }
520
644
  case "commentReference": {
645
+ if (context.story && context.story !== "comment") {
646
+ opaqueRun(el);
647
+ break;
648
+ }
521
649
  const bag = attributeBag(el, ["w:id"], context);
522
650
  const attrs: Record<string, unknown> = { id: integer(attr(el, "id")) };
523
651
  if (bag) attrs.attributes = bag;
@@ -526,16 +654,91 @@ function run(
526
654
  else opaqueRun(el);
527
655
  break;
528
656
  }
657
+ case "fldChar": {
658
+ const type = attr(el, "fldCharType");
659
+ const name = { begin: "fieldStart", separate: "fieldSeparator", end: "fieldEnd" }[
660
+ type ?? ""
661
+ ];
662
+ if (!name) {
663
+ opaqueRun(el);
664
+ break;
665
+ }
666
+ const known = ["w:fldCharType", "w:dirty", "w:fldLock"];
667
+ const plain = !elements(el).length && el.attributes.every((a) => known.includes(a.name));
668
+ const flags: Record<string, unknown> = {};
669
+ if (name === "fieldStart" && plain) {
670
+ const dirty = attr(el, "dirty");
671
+ const locked = attr(el, "fldLock");
672
+ if (dirty !== undefined) flags.dirty = !["0", "false", "off"].includes(dirty);
673
+ if (locked !== undefined) flags.locked = !["0", "false", "off"].includes(locked);
674
+ }
675
+ // Form field data, or anything else on it: the element itself is kept.
676
+ const simple = plain && (name === "fieldStart" || el.attributes.length === 1);
677
+ const attrs = simple ? flags : { ext: sourceOf(context, el) };
678
+ const leaf = valid(
679
+ node(name, marks, Object.keys(attrs).length ? attrs : undefined),
680
+ el,
681
+ context,
682
+ );
683
+ if (leaf) out.push(leaf);
684
+ else opaqueRun(el);
685
+ break;
686
+ }
687
+ case "instrText":
688
+ case "delInstrText": {
689
+ const bag = attributeBag(el, ["xml:space"], context);
690
+ const attrs: Record<string, unknown> = { text: spaced(el) };
691
+ if (bag) attrs.attributes = bag;
692
+ const leaf = valid(node("fieldCode", marks, attrs), el, context);
693
+ if (leaf) out.push(leaf);
694
+ else opaqueRun(el);
695
+ break;
696
+ }
697
+ case "footnoteReference":
698
+ case "endnoteReference": {
699
+ const id = integer(attr(el, "id"));
700
+ const custom = attr(el, "customMarkFollows");
701
+ const on = custom === undefined ? null : ["1", "true", "on"].includes(custom);
702
+ // A story holds no references (ADR-0007), and a value the node cannot say stays verbatim.
703
+ if (
704
+ context.story ||
705
+ id === undefined ||
706
+ (custom !== undefined && !["0", "1", "true", "false", "on", "off"].includes(custom))
707
+ ) {
708
+ opaqueRun(el);
709
+ break;
710
+ }
711
+ const bag = attributeBag(el, ["w:id", "w:customMarkFollows"], context);
712
+ const attrs: Record<string, unknown> = {
713
+ story: `${el.local === "footnoteReference" ? "footnote" : "endnote"}:${id}`,
714
+ };
715
+ if (on !== null) attrs.customMark = on;
716
+ if (bag) attrs.attributes = bag;
717
+ const leaf = valid(node("noteReference", marks, attrs), el, context);
718
+ if (leaf) out.push(leaf);
719
+ else opaqueRun(el);
720
+ break;
721
+ }
722
+ case "footnoteRef":
723
+ case "endnoteRef":
724
+ if (context.story === el.local.slice(0, -3) && !el.attributes.length)
725
+ out.push(node("noteMark", marks));
726
+ else opaqueRun(el);
727
+ break;
529
728
  default:
530
729
  if (DROPPED.has(el.local)) context.report.dropped(el.name);
531
- else opaqueRun(el);
730
+ else opaqueRun(el, undefined, context.story && NOTE_SEPARATORS.has(el.local));
532
731
  }
533
732
  }
534
733
  // A run with properties and nothing else shows nothing; Word drops those too.
535
734
  if (out.length === before) context.report.dropped("w:r (empty)");
536
735
 
537
- function opaqueRun(el: XmlElement, labelValue = label(INLINE_LABELS, el)): void {
538
- context.report.opaque(el.name);
736
+ function opaqueRun(
737
+ el: XmlElement,
738
+ labelValue = label(INLINE_LABELS, el),
739
+ expected: boolean | undefined = false,
740
+ ): void {
741
+ if (!expected) context.report.opaque(el.name);
539
742
  out.push(
540
743
  node("opaqueInline", marks, {
541
744
  ...withLabel({ xml: sourceOf(context, el) }, labelValue),
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Content controls (`w:sdt`, ADR-0007): their properties as the envelope's `controls`, with the
3
+ * elements they were read from kept verbatim in `ext`. Export reads the same way, to tell what a
4
+ * control says differently from its `ext`.
5
+ */
6
+ import { type ControlJSON, checkControl } from "@folijs/core";
7
+ import type { DocxPackage } from "../package.js";
8
+ import type { XmlElement } from "../xml.js";
9
+ import { attr, child, deepText, elements, isW, W, W14, W15 } from "./ooxml.js";
10
+ import { type Context, compactDefined, runProperties, sourceOf } from "./properties.js";
11
+
12
+ const KINDS: readonly [string, string, ControlJSON["kind"]][] = [
13
+ [W, "text", "text"],
14
+ [W, "richText", "richText"],
15
+ [W, "dropDownList", "dropDown"],
16
+ [W, "comboBox", "comboBox"],
17
+ [W, "date", "date"],
18
+ [W14, "checkbox", "checkbox"],
19
+ [W, "picture", "picture"],
20
+ [W15, "repeatingSection", "repeating"],
21
+ [W15, "repeatingSectionItem", "repeatingItem"],
22
+ ];
23
+ /** What marks a control as something other than an editable value. */
24
+ const OTHER = new Set([
25
+ "docPartObj",
26
+ "docPartList",
27
+ "group",
28
+ "equation",
29
+ "citation",
30
+ "bibliography",
31
+ ]);
32
+ const GLOSSARY =
33
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/glossaryDocument";
34
+
35
+ const on = (value: string | undefined) => value !== "0" && value !== "false" && value !== "off";
36
+
37
+ const glossaries = new WeakMap<DocxPackage, ReadonlyMap<string, string>>();
38
+
39
+ /** The text of the package's glossary entries, by name: what placeholders come back as. */
40
+ function glossaryTexts(pkg: DocxPackage): ReadonlyMap<string, string> {
41
+ const known = glossaries.get(pkg);
42
+ if (known) return known;
43
+ const texts = new Map<string, string>();
44
+ const relationship = pkg
45
+ .relationships(pkg.mainDocument)
46
+ .find((r) => r.type === GLOSSARY && !r.external);
47
+ const part = relationship?.partName ? pkg.part(relationship.partName) : undefined;
48
+ const parts = part && child(pkg.xml(part.name).root, "docParts");
49
+ for (const entry of parts ? elements(parts) : []) {
50
+ const name = attr(child(child(entry, "docPartPr") ?? entry, "name"), "val");
51
+ const body = child(entry, "docPartBody");
52
+ if (name && body) texts.set(name, deepText(body));
53
+ }
54
+ glossaries.set(pkg, texts);
55
+ return texts;
56
+ }
57
+
58
+ /** The properties of `sdt`'s `w:sdtPr` and `w:sdtEndPr`, or undefined if the model cannot hold them. */
59
+ export function controlProperties(
60
+ sdt: XmlElement,
61
+ context: Context & { pkg?: DocxPackage },
62
+ ): ControlJSON | undefined {
63
+ const pr = child(sdt, "sdtPr");
64
+ const end = child(sdt, "sdtEndPr");
65
+ const props = pr ? elements(pr) : [];
66
+ const find = (ns: string, local: string) => props.find((p) => p.ns === ns && p.local === local);
67
+ const value = (local: string) => attr(find(W, local), "val");
68
+ const typed = KINDS.find(([ns, local]) => find(ns, local));
69
+ const kind: ControlJSON["kind"] = props.some((p) => p.ns === W && OTHER.has(p.local))
70
+ ? "other"
71
+ : (typed?.[2] ?? "richText");
72
+ const list = find(W, "dropDownList") ?? find(W, "comboBox");
73
+ const date = find(W, "date");
74
+ const text = find(W, "text");
75
+ const checkbox = find(W14, "checkbox");
76
+ const inBox = (local: string) =>
77
+ checkbox && elements(checkbox).find((c) => c.ns === W14 && c.local === local);
78
+ const glyph = (local: string) => {
79
+ const state = inBox(local);
80
+ const code = attr(state, "val", W14);
81
+ return code === undefined
82
+ ? undefined
83
+ : compactDefined({ value: code, font: attr(state, "font", W14) });
84
+ };
85
+ const checked = inBox("checked");
86
+ const placeholder = find(W, "placeholder");
87
+ const showing = find(W, "showingPlcHdr");
88
+ const binding = find(W, "dataBinding");
89
+ const docPart = placeholder && attr(child(placeholder, "docPart"), "val");
90
+ const section = find(W15, "repeatingSection");
91
+ const fixed =
92
+ section && elements(section).find((c) => c.local === "doNotAllowInsertDeleteSection");
93
+ const format = pr ? runProperties(child(pr, "rPr"), context) : [];
94
+ const entry = docPart !== undefined ? context.pkg && glossaryTexts(context.pkg).get(docPart) : "";
95
+ const control = compactDefined({
96
+ kind,
97
+ tag: value("tag"),
98
+ alias: value("alias"),
99
+ lock: value("lock"),
100
+ items: list
101
+ ? elements(list)
102
+ .filter((item) => isW(item, "listItem"))
103
+ .map((item) =>
104
+ compactDefined({
105
+ value: attr(item, "value") ?? attr(item, "displayText") ?? "",
106
+ display: attr(item, "displayText"),
107
+ }),
108
+ )
109
+ : undefined,
110
+ dateFormat: date && attr(child(date, "dateFormat"), "val"),
111
+ date: date && attr(date, "fullDate"),
112
+ checked: checked ? on(attr(checked, "val", W14)) : undefined,
113
+ checkedState: glyph("checkedState"),
114
+ uncheckedState: glyph("uncheckedState"),
115
+ multiLine:
116
+ text && attr(text, "multiLine") !== undefined ? on(attr(text, "multiLine")) : undefined,
117
+ format: format.length ? format : undefined,
118
+ noInsertDelete: fixed ? on(attr(fixed, "val") ?? attr(fixed, "val", W15)) : undefined,
119
+ placeholder:
120
+ showing || docPart !== undefined
121
+ ? compactDefined({
122
+ showing: showing ? on(attr(showing, "val")) : undefined,
123
+ docPart,
124
+ text: entry || undefined,
125
+ })
126
+ : undefined,
127
+ binding: binding
128
+ ? compactDefined({
129
+ xpath: attr(binding, "xpath"),
130
+ storeItemId: attr(binding, "storeItemID"),
131
+ prefixMappings: attr(binding, "prefixMappings"),
132
+ })
133
+ : undefined,
134
+ ext: `<${sdt.name}>${pr ? sourceOf(context, pr) : ""}${end ? sourceOf(context, end) : ""}</${sdt.name}>`,
135
+ }) as unknown as ControlJSON;
136
+ return checkControl(control) ? undefined : control;
137
+ }
@@ -1,4 +1,12 @@
1
- import { type FoliDocument, parseDocument, type ResourceJSON, SCHEMA_VERSION } 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 the current schema (v4), 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
@@ -57,6 +68,7 @@ export function importPackage(pkg: DocxPackage): DocxImport {
57
68
  if (!body) throw new DocxError(`${pkg.mainDocument}: no w:body`);
58
69
 
59
70
  const resources = new Map<string, ResourceJSON>();
71
+ const controls = new Map<string, ControlJSON>();
60
72
  const contextFor = (part: string, source: string): ContentContext => {
61
73
  report.part = part;
62
74
  // One lookup table per part: hyperlinks resolve in constant time.
@@ -65,7 +77,17 @@ export function importPackage(pkg: DocxPackage): DocxImport {
65
77
  byId ??= new Map(pkg.relationships(part).map((r) => [r.id, r]));
66
78
  return byId.get(id);
67
79
  };
68
- return { source, report, pkg, part, moves: new Moves(), relationship, resources };
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
+ };
69
91
  };
70
92
  const related = (
71
93
  type: string,
@@ -109,18 +131,38 @@ export function importPackage(pkg: DocxPackage): DocxImport {
109
131
  contextFor(commentsPart.name, commentsPart.source),
110
132
  )
111
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
+ }
112
146
 
113
147
  let document: FoliDocument;
114
148
  try {
115
149
  document = parseDocument({
116
150
  schemaVersion: SCHEMA_VERSION,
117
151
  section: lastSection,
152
+ ...(settings ? { settings } : {}),
118
153
  defaults: styled.defaults,
119
154
  styles: styled.styles,
120
155
  numbering: numbered,
121
156
  ...(themed ? { theme: themed } : {}),
122
157
  comments: commented,
123
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
+ : {}),
124
166
  content: { type: "doc", content },
125
167
  });
126
168
  } catch (error) {
@@ -128,14 +170,45 @@ export function importPackage(pkg: DocxPackage): DocxImport {
128
170
  // element over 16 MiB kept verbatim…). A DocxError like every other import failure.
129
171
  throw new DocxError(`Cannot import: ${(error as Error).message}`, { cause: error });
130
172
  }
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
173
  return { document, package: pkg, report: report.report(), trackRevisions };
139
174
  }
140
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
+
141
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`. */
@@ -394,7 +394,7 @@ export function comments(
394
394
  if (initials !== undefined && initials.length > 9) {
395
395
  context.report.unmodeled("w:comment@w:initials", "longer than 9");
396
396
  }
397
- const content = blocks(el.children, context);
397
+ const content = blocks(el.children, { ...context, story: "comment" });
398
398
  const comment = compact({
399
399
  id: commentId,
400
400
  author: author.length <= 255 ? author : author.slice(0, 255),