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