@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
@@ -5,21 +5,34 @@
5
5
  * byte for byte. Without a package, a new one is made.
6
6
  */
7
7
 
8
- import { type FoliDocument, parseDocument, type ResourceJSON } from "@folijs/core";
9
- import { child, REL } from "../import/ooxml.js";
8
+ import {
9
+ type ControlJSON,
10
+ type FoliDocument,
11
+ type NodeJSON,
12
+ parseDocument,
13
+ type ResourceJSON,
14
+ type SectionJSON,
15
+ type StoryJSON,
16
+ } from "@folijs/core";
17
+ import { controlsUsed, noteIds, packageStories } from "../import/index.js";
18
+ import { child, isW, REL, W } from "../import/ooxml.js";
10
19
  import { DocxError, type DocxPackage, type NewPart } from "../package.js";
11
- import { newSettingsXml, withTrackRevisions } from "../settings.js";
20
+ import { newSettingsXml, withSettings, withTrackRevisions } from "../settings.js";
21
+ import { parseXml, type XmlElement } from "../xml.js";
12
22
  import { deflateEntry, writeZip } from "../zip.js";
23
+ import { balanced } from "./balance.js";
13
24
  import { blocksXml, type WriteContext } from "./content.js";
14
25
  import {
15
26
  commentsExtendedXml,
16
27
  commentsXml,
28
+ notesXml,
17
29
  numberingXml,
18
30
  type OriginalPart,
19
31
  stylesXml,
32
+ wrapPart,
20
33
  } from "./parts.js";
21
34
  import { drawingXml, Media, pictureBytes } from "./pictures.js";
22
- import { sectionXml } from "./properties.js";
35
+ import { same, sectionXml } from "./properties.js";
23
36
  import {
24
37
  DEFAULT_NAMESPACES,
25
38
  escapeAttribute,
@@ -36,6 +49,10 @@ const CT = {
36
49
  commentsExtended:
37
50
  "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml",
38
51
  settings: "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml",
52
+ header: "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
53
+ footer: "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
54
+ footnotes: "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml",
55
+ endnotes: "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml",
39
56
  rels: "application/vnd.openxmlformats-package.relationships+xml",
40
57
  };
41
58
 
@@ -99,10 +116,13 @@ class Relationships {
99
116
  return this.add(REL.hyperlink, href, true);
100
117
  }
101
118
 
102
- add(type: string, target: string, external: boolean): string {
119
+ /** Adds a relationship; `wanted` is its id (a story's), refused if another has it. */
120
+ add(type: string, target: string, external: boolean, wanted?: string): string {
121
+ if (wanted !== undefined && this.#ids.has(wanted))
122
+ throw new DocxError(`Relationship id ${wanted} is already in use`);
103
123
  let n = this.#ids.size + 1;
104
124
  while (this.#ids.has(`rId${n}`)) n++;
105
- const id = `rId${n}`;
125
+ const id = wanted ?? `rId${n}`;
106
126
  this.#ids.add(id);
107
127
  this.added.push({ id, type, target, external });
108
128
  if (type === REL.hyperlink && external) this.#byTarget.set(target, id);
@@ -136,6 +156,7 @@ function contextFor(
136
156
  ): WriteContext {
137
157
  return {
138
158
  namespaces,
159
+ controls: media.controls,
139
160
  hyperlink: (href, id) => relationships.hyperlink(href, id),
140
161
  picture: (attrs) =>
141
162
  drawingXml(
@@ -187,7 +208,7 @@ export async function exportDocx(
187
208
  original?: DocxPackage,
188
209
  options: ExportOptions = {},
189
210
  ): Promise<Uint8Array> {
190
- const doc = withThreadIds(parseDocument(document), original);
211
+ const doc = balanced(withThreadIds(parseDocument(document), original), original);
191
212
  // Before the app is asked for any picture's bytes.
192
213
  const reference = original ? undefined : packageReference(doc);
193
214
  if (reference) {
@@ -195,19 +216,86 @@ export async function exportDocx(
195
216
  `The document refers to a part of its original package (${reference}): export it with that package`,
196
217
  );
197
218
  }
219
+ const referenced = noteReferences(doc);
220
+ const read =
221
+ original && (doc.stories || referenced.modeled.size)
222
+ ? packageStories(original)
223
+ : { stories: {}, controls: new Map<string, ControlJSON>() };
224
+ const originals: Readonly<Record<string, StoryJSON>> = read.stories;
225
+ // A story is unchanged if its tree is, and the controls in it say what they said.
226
+ const unchanged = (id: string) =>
227
+ Object.hasOwn(originals, id) &&
228
+ same(doc.stories?.[id], originals[id]) &&
229
+ [...controlsUsed(doc.stories?.[id])].every((c) =>
230
+ same(doc.controls?.[c], read.controls.get(c)),
231
+ );
232
+ // Notes the model does not hold (an unknown `w:type`) stay in their part: they count too.
233
+ const inPart = original && referenced.modeled.size ? noteIds(original) : new Set<string>();
234
+ for (const key of referenced.modeled)
235
+ if (!Object.hasOwn(doc.stories ?? {}, key) && !inPart.has(key))
236
+ throw new DocxError(`A note reference has no note: ${key.slice(0, 64)}`);
198
237
  // The parts written from the model: their drawings are the document's own.
199
238
  const rewritten = original
200
239
  ? [
201
240
  original.mainDocument,
202
241
  ...original
203
242
  .relationships(original.mainDocument)
204
- .filter((r) => r.type === REL.comments && r.partName)
243
+ .filter(
244
+ (r) =>
245
+ r.partName &&
246
+ (r.type === REL.comments ||
247
+ (doc.stories && Object.hasOwn(doc.stories, r.id) && !unchanged(r.id))),
248
+ )
205
249
  .map((r) => r.partName as string),
206
250
  ]
207
251
  : [];
208
252
  const bytes = await pictureBytes(doc, original, options.resource);
209
253
  const media = new Media(doc, original, bytes, rewritten);
210
- return original ? intoPackage(doc, original, options, media) : newPackage(doc, options, media);
254
+ return original
255
+ ? intoPackage(doc, original, originals, unchanged, referenced.isReferenced, options, media)
256
+ : newPackage(doc, referenced.isReferenced, options, media);
257
+ }
258
+
259
+ /**
260
+ * The notes the document refers to, as story ids: `modeled` by `noteReference` nodes. `isReferenced`
261
+ * also says yes to every note of a kind that verbatim XML refers to: which one it means is not
262
+ * worth guessing, and removing a note still referred to makes Word refuse the file.
263
+ */
264
+ function noteReferences(doc: FoliDocument): {
265
+ modeled: Set<string>;
266
+ isReferenced: (key: string) => boolean;
267
+ } {
268
+ const modeled = new Set<string>();
269
+ const verbatim = new Set<string>();
270
+ JSON.stringify([doc.content, doc.comments, doc.stories], (key, value) => {
271
+ if (key === "xml" && typeof value === "string")
272
+ for (const [, kind] of value.matchAll(/(foot|end)noteReference/g))
273
+ verbatim.add(`${kind}note`);
274
+ const node = value as { type?: unknown; attrs?: { story?: unknown } } | null;
275
+ if (node?.type === "noteReference" && typeof node.attrs?.story === "string")
276
+ modeled.add(node.attrs.story);
277
+ return value;
278
+ });
279
+ return {
280
+ modeled,
281
+ isReferenced: (key) => modeled.has(key) || verbatim.has(key.split(":")[0] as string),
282
+ };
283
+ }
284
+
285
+ /** `text` if it is a well-formed part whose `w:` content is WordprocessingML; DocxError if not. */
286
+ function checkedPart(name: string, text: string): string {
287
+ let root: XmlElement;
288
+ try {
289
+ root = parseXml(text).root;
290
+ } catch (error) {
291
+ throw new DocxError(`${name}: its namespaces do not fit what is written: ${error}`, {
292
+ cause: error,
293
+ });
294
+ }
295
+ for (const child of root.children)
296
+ if (child.kind === "element" && child.prefix === "w" && child.ns !== W)
297
+ throw new DocxError(`${name}: its w: prefix is not WordprocessingML`);
298
+ return text;
211
299
  }
212
300
 
213
301
  const PARA_ID = "w14:paraId";
@@ -270,9 +358,29 @@ function withThreadIds(doc: FoliDocument, pkg: DocxPackage | undefined): FoliDoc
270
358
  return copy;
271
359
  }
272
360
 
361
+ /** A free name for a new part: `/word/header1.xml`, `/word/header2.xml`… */
362
+ function freePart(stem: string, taken: (name: string) => boolean): string {
363
+ let n = 1;
364
+ while (taken(`/word/${stem}${n}.xml`)) n++;
365
+ return `/word/${stem}${n}.xml`;
366
+ }
367
+
368
+ const HEADER_FOOTER = {
369
+ header: { root: "w:hdr", rel: REL.header, contentType: CT.header },
370
+ footer: { root: "w:ftr", rel: REL.footer, contentType: CT.footer },
371
+ } as const;
372
+ const NOTES = {
373
+ footnote: { rel: REL.footnotes, contentType: CT.footnotes, name: "/word/footnotes.xml" },
374
+ endnote: { rel: REL.endnotes, contentType: CT.endnotes, name: "/word/endnotes.xml" },
375
+ } as const;
376
+ const NOTE_KINDS = ["footnote", "endnote"] as const;
377
+
273
378
  async function intoPackage(
274
379
  doc: FoliDocument,
275
380
  pkg: DocxPackage,
381
+ originals: Readonly<Record<string, StoryJSON>>,
382
+ unchanged: (id: string) => boolean,
383
+ isReferenced: (key: string) => boolean,
276
384
  options: ExportOptions,
277
385
  media: Media,
278
386
  ): Promise<Uint8Array> {
@@ -376,14 +484,85 @@ async function intoPackage(
376
484
  );
377
485
  }
378
486
 
487
+ // Stories: none in the document (schema v4, or none read) leaves their parts as they are.
488
+ const stories = doc.stories ?? {};
489
+ const ownRelationships = (name: string, existing: boolean) =>
490
+ new Relationships(existing ? pkg.relationships(name) : []);
491
+ const newNames = new Set<string>();
492
+ const writtenStories = new Map<string, string>();
493
+ for (const [id, story] of Object.entries(stories)) {
494
+ if (story.kind !== "header" && story.kind !== "footer") continue;
495
+ const { root, rel, contentType } = HEADER_FOOTER[story.kind];
496
+ const related = pkg.relationships(mainName).find((r) => r.id === id);
497
+ // Only a part this story was read from: an id can name any relationship of the package.
498
+ if (related && (related.type !== rel || !Object.hasOwn(originals, id)))
499
+ throw new DocxError(`Story ${id.slice(0, 64)} has the id of another relationship`);
500
+ if (!related && !/^[A-Za-z_][\w.-]*$/.test(id))
501
+ throw new DocxError(`Not a relationship id: ${id.slice(0, 64)}`);
502
+ const existing = related?.partName ? pkg.part(related.partName) : undefined;
503
+ if (existing && unchanged(id)) continue;
504
+ const name = existing?.name ?? freePart(story.kind, (n) => !!pkg.part(n) || newNames.has(n));
505
+ const xml = existing ? pkg.xml(existing.name) : undefined;
506
+ const ns = xml ? namespacesOf(xml.root, xml.source) : namespaces;
507
+ const partRels = ownRelationships(name, !!existing);
508
+ const inner = blocksXml(story.content.content ?? [], contextFor(ns, partRels, media, name));
509
+ const text = checkedPart(
510
+ name,
511
+ wrapPart(xml && { root: xml.root, source: xml.source }, root, ns, inner),
512
+ );
513
+ // Two relationships can share a part: both stories must then say the same.
514
+ const earlier = writtenStories.get(name);
515
+ if (earlier !== undefined && earlier !== text)
516
+ throw new DocxError(`${name} is shared by stories that differ`);
517
+ writtenStories.set(name, text);
518
+ if (existing) set(name, text);
519
+ else {
520
+ newNames.add(name);
521
+ add.push({ name, data: encoder.encode(text), contentType });
522
+ rels.add(rel, relative(mainName, name), false, id);
523
+ }
524
+ if (partRels.added.length) writeRelationships(name, partRels);
525
+ }
526
+ for (const kind of NOTE_KINDS) {
527
+ const { rel, contentType, name: defaultName } = NOTES[kind];
528
+ const name = pkg.relationships(mainName).find((r) => r.type === rel)?.partName;
529
+ const held = Object.values(stories).some((s) => s.kind === kind);
530
+ if (!name && !held) continue;
531
+ if (name && !doc.stories) continue;
532
+ const target = name ?? defaultName;
533
+ if (name && !isW(pkg.xml(name).root, `${kind}s`)) {
534
+ if (held) throw new DocxError(`${name} is not a ${kind}s part`);
535
+ continue;
536
+ }
537
+ const partRels = ownRelationships(target, !!name);
538
+ const write = (o: OriginalPart | undefined, ns: Namespaces) =>
539
+ checkedPart(
540
+ target,
541
+ notesXml(kind, stories, originals, unchanged, isReferenced, o, {
542
+ ...contextFor(ns, partRels, media, target),
543
+ note: kind,
544
+ }),
545
+ );
546
+ part(rel, defaultName, contentType, write, held);
547
+ if (partRels.added.length) writeRelationships(target, partRels);
548
+ }
549
+
379
550
  const { trackRevisions } = options;
380
- if (trackRevisions !== undefined) {
551
+ const { settings } = doc;
552
+ if (trackRevisions !== undefined || settings) {
381
553
  part(
382
554
  REL.settings,
383
555
  "/word/settings.xml",
384
556
  CT.settings,
385
- (o) => (o ? withTrackRevisions(o.source, o.root, trackRevisions) : newSettingsXml()),
386
- trackRevisions,
557
+ (o) => {
558
+ if (!o) return newSettingsXml(!!trackRevisions, settings);
559
+ const source =
560
+ trackRevisions === undefined
561
+ ? o.source
562
+ : withTrackRevisions(o.source, o.root, trackRevisions);
563
+ return settings ? withSettings(source, parseXml(source).root, settings) : source;
564
+ },
565
+ !!trackRevisions || !!settings,
387
566
  );
388
567
  }
389
568
 
@@ -439,6 +618,7 @@ function changedThreads(doc: FoliDocument, pkg: DocxPackage): boolean {
439
618
  /** A new package: content types, relationships, the document and the parts it needs. */
440
619
  async function newPackage(
441
620
  doc: FoliDocument,
621
+ isReferenced: (key: string) => boolean,
442
622
  options: ExportOptions,
443
623
  media: Media,
444
624
  ): Promise<Uint8Array> {
@@ -461,6 +641,51 @@ async function newPackage(
461
641
  numberingXml(doc, undefined, DEFAULT_NAMESPACES),
462
642
  );
463
643
  }
644
+ for (const [id, story] of Object.entries(doc.stories ?? {})) {
645
+ if (story.kind !== "header" && story.kind !== "footer") continue;
646
+ if (!/^[A-Za-z_][\w.-]*$/.test(id))
647
+ throw new DocxError(`Not a relationship id: ${id.slice(0, 64)}`);
648
+ const { root, rel, contentType } = HEADER_FOOTER[story.kind];
649
+ const name = freePart(story.kind, (n) => parts.some((p) => p.name === n));
650
+ const partRels = new Relationships([]);
651
+ const inner = blocksXml(
652
+ story.content.content ?? [],
653
+ contextFor(DEFAULT_NAMESPACES, partRels, media, name),
654
+ );
655
+ parts.push({
656
+ name,
657
+ text: wrapPart(undefined, root, DEFAULT_NAMESPACES, inner),
658
+ contentType,
659
+ });
660
+ rels.add(rel, relative("/word/document.xml", name), false, id);
661
+ if (partRels.added.length)
662
+ parts.push({
663
+ name: relationshipsPartName(name),
664
+ text: partRels.xml(undefined),
665
+ contentType: CT.rels,
666
+ });
667
+ }
668
+ for (const kind of NOTE_KINDS) {
669
+ const stories = doc.stories ?? {};
670
+ if (!Object.values(stories).some((s) => s.kind === kind)) continue;
671
+ const { rel, contentType, name } = NOTES[kind];
672
+ const partRels = new Relationships([]);
673
+ add(
674
+ name,
675
+ rel,
676
+ contentType,
677
+ notesXml(kind, stories, {}, () => false, isReferenced, undefined, {
678
+ ...contextFor(DEFAULT_NAMESPACES, partRels, media, name),
679
+ note: kind,
680
+ }),
681
+ );
682
+ if (partRels.added.length)
683
+ parts.push({
684
+ name: relationshipsPartName(name),
685
+ text: partRels.xml(undefined),
686
+ contentType: CT.rels,
687
+ });
688
+ }
464
689
  if (doc.comments.length) {
465
690
  const commentRels = new Relationships([]);
466
691
  add(
@@ -488,8 +713,13 @@ async function newPackage(
488
713
  );
489
714
  }
490
715
  }
491
- if (options.trackRevisions)
492
- add("/word/settings.xml", REL.settings, CT.settings, newSettingsXml());
716
+ if (options.trackRevisions || doc.settings)
717
+ add(
718
+ "/word/settings.xml",
719
+ REL.settings,
720
+ CT.settings,
721
+ newSettingsXml(!!options.trackRevisions, doc.settings),
722
+ );
493
723
  parts.push({
494
724
  name: "/word/_rels/document.xml.rels",
495
725
  text: rels.xml(undefined),
@@ -530,11 +760,18 @@ function bodySection(doc: FoliDocument, namespaces: Namespaces): string {
530
760
  function packageReference(doc: FoliDocument): string | undefined {
531
761
  const sections = [doc.section, ...(doc.content.content ?? []).map((b) => b.attrs?.section)];
532
762
  for (const s of sections) {
533
- const section = s as { headers?: object; footers?: object } | undefined;
534
- if (section?.headers || section?.footers) return "a header or footer";
763
+ const section = s as
764
+ | { headers?: Record<string, string>; footers?: Record<string, string> }
765
+ | undefined;
766
+ const ids = [
767
+ ...Object.values(section?.headers ?? {}),
768
+ ...Object.values(section?.footers ?? {}),
769
+ ];
770
+ if (ids.some((id) => !doc.stories || !Object.hasOwn(doc.stories, id)))
771
+ return "a header or footer";
535
772
  }
536
773
  let found: string | undefined;
537
- JSON.stringify([doc.content, doc.comments], (key, value) => {
774
+ JSON.stringify([doc.content, doc.comments, doc.stories], (key, value) => {
538
775
  if (!found && key === "xml" && typeof value === "string" && /\sr:[A-Za-z]+="/.test(value))
539
776
  found = "content kept verbatim";
540
777
  const link = value as {
@@ -12,9 +12,10 @@ import type {
12
12
  FoliDocument,
13
13
  NumberingInstanceJSON,
14
14
  NumberingLevelJSON,
15
+ StoryJSON,
15
16
  StyleJSON,
16
17
  } from "@folijs/core";
17
- import { attr, child, isW, W, W15 } from "../import/ooxml.js";
18
+ import { attr, child, integer, isW, W, W15 } from "../import/ooxml.js";
18
19
  import {
19
20
  abstractOf,
20
21
  defaultsOf,
@@ -24,6 +25,7 @@ import {
24
25
  usableStyle,
25
26
  } from "../import/parts.js";
26
27
  import { Recorder } from "../import/report.js";
28
+ import { notesOf } from "../import/stories.js";
27
29
  import { DocxError } from "../package.js";
28
30
  import type { XmlElement, XmlNode } from "../xml.js";
29
31
  import { blocksXml, type WriteContext } from "./content.js";
@@ -75,7 +77,7 @@ function childSource(
75
77
  }
76
78
 
77
79
  /** A part's text: the original's prolog and root around `children`, or a new root. */
78
- function wrapPart(
80
+ export function wrapPart(
79
81
  part: OriginalPart | undefined,
80
82
  rootName: string,
81
83
  ns: Namespaces,
@@ -535,6 +537,81 @@ export function commentsXml(
535
537
  return wrapPart(part, "w:comments", context.namespaces, body + added);
536
538
  }
537
539
 
540
+ /**
541
+ * The separators a new notes part starts with, as Word writes them (unless it has its own): single
542
+ * spaced, nothing after.
543
+ */
544
+ const noteSeparators = (
545
+ kind: "footnote" | "endnote",
546
+ stories: Readonly<Record<string, StoryJSON>>,
547
+ ) =>
548
+ (Object.hasOwn(stories, `${kind}:-1`)
549
+ ? ""
550
+ : `<w:${kind} w:type="separator" w:id="-1"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:separator/></w:r></w:p></w:${kind}>`) +
551
+ (Object.hasOwn(stories, `${kind}:0`)
552
+ ? ""
553
+ : `<w:${kind} w:type="continuationSeparator" w:id="0"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></w:${kind}>`);
554
+
555
+ /**
556
+ * A footnotes or endnotes part: a note unchanged from `originals` keeps its bytes, a changed one
557
+ * is written from its story, and new ones go at the end. One whose story is gone is removed,
558
+ * unless Word needs it: a separator, or a note something still refers to (`isReferenced`).
559
+ */
560
+ export function notesXml(
561
+ kind: "footnote" | "endnote",
562
+ stories: Readonly<Record<string, StoryJSON>>,
563
+ originals: Readonly<Record<string, StoryJSON>>,
564
+ unchanged: (key: string) => boolean,
565
+ isReferenced: (key: string) => boolean,
566
+ part: OriginalPart | undefined,
567
+ context: WriteContext,
568
+ ): string {
569
+ const write = (key: string, story: StoryJSON) => {
570
+ if (!new RegExp(`^${kind}:-?\\d+$`).test(key))
571
+ throw new DocxError(`Not the id of a ${kind}: ${key.slice(0, 64)}`);
572
+ const type = story.noteType ? ` w:type="${story.noteType}"` : "";
573
+ if (story.ext) {
574
+ // The element it was read from must be this note: a copy would repeat another's id.
575
+ const { element } = fragment(story.ext.replace(/\/?>$/, "/>"), context.namespaces, kind);
576
+ if (
577
+ integer(attr(element, "id")) !== Number(key.slice(kind.length + 1)) ||
578
+ attr(element, "type") !== story.noteType
579
+ )
580
+ throw new DocxError(`The start tag kept for ${key.slice(0, 64)} is another note's`);
581
+ }
582
+ const start =
583
+ story.ext?.replace(/\/>$/, ">") ?? `<w:${kind}${type} w:id="${key.slice(kind.length + 1)}">`;
584
+ return `${start}${blocksXml(story.content.content ?? [], context)}</w:${kind}>`;
585
+ };
586
+ const seen = new Set<string>();
587
+ const held = part ? notesOf(part.root, kind) : new Map<string, XmlElement>();
588
+ const keyOf = new Map([...held].map(([key, el]) => [el, key]));
589
+ const body = rebuild<string>(
590
+ part,
591
+ (child) => {
592
+ const key = keyOf.get(child);
593
+ if (key === undefined) return undefined;
594
+ seen.add(key);
595
+ if (!Object.hasOwn(stories, key)) {
596
+ const original = originals[key];
597
+ const needed =
598
+ !original || (original.noteType ?? "normal") !== "normal" || isReferenced(key);
599
+ return needed ? undefined : null;
600
+ }
601
+ const story = stories[key] as StoryJSON;
602
+ return story && unchanged(key) ? undefined : key;
603
+ },
604
+ (key) => write(key, stories[key] as StoryJSON),
605
+ [],
606
+ );
607
+ const added = Object.entries(stories)
608
+ .filter(([key, story]) => story.kind === kind && !seen.has(key))
609
+ .map(([key, story]) => write(key, story))
610
+ .join("");
611
+ const separators = part ? "" : noteSeparators(kind, stories);
612
+ return wrapPart(part, `w:${kind}s`, context.namespaces, separators + body + added);
613
+ }
614
+
538
615
  /**
539
616
  * `commentsExtended.xml` for the comments' replies and resolved state, keyed by the `w14:paraId`
540
617
  * of each comment's last paragraph (comments without one cannot be listed).
@@ -5,12 +5,14 @@
5
5
  * Its image is the package's part when the resource names one there, else a new media part
6
6
  * whose bytes come from the resource's `data:` URL or the app (`ExportOptions.resource`).
7
7
  */
8
+
8
9
  import type { FoliDocument, NodeJSON, ResourceJSON } from "@folijs/core";
9
10
  import { A, R } from "../import/ooxml.js";
10
11
  import { floatOf, PIC, WP } from "../import/pictures.js";
11
12
  import type { DocxPackage } from "../package.js";
12
13
  import { DocxError } from "../package.js";
13
14
  import type { XmlElement } from "../xml.js";
15
+ import { ControlWriter } from "./controls.js";
14
16
  import { same } from "./properties.js";
15
17
  import { escapeAttribute, fragment, type Namespaces } from "./xmlout.js";
16
18
 
@@ -27,7 +29,7 @@ const EXTENSIONS: Record<string, string> = {
27
29
  "image/x-wmf": "wmf",
28
30
  };
29
31
 
30
- /** Every picture node of the document (body and comments). */
32
+ /** Every picture node of the document (body, comments and stories). */
31
33
  function picturesOf(doc: FoliDocument): Json[] {
32
34
  const out: Json[] = [];
33
35
  const visit = (nodes: readonly NodeJSON[] | undefined) => {
@@ -38,6 +40,7 @@ function picturesOf(doc: FoliDocument): Json[] {
38
40
  };
39
41
  visit(doc.content.content);
40
42
  for (const comment of doc.comments) visit(comment.content);
43
+ for (const story of Object.values(doc.stories ?? {})) visit(story.content.content);
41
44
  return out;
42
45
  }
43
46
 
@@ -105,6 +108,8 @@ const docPrIds = (xml: string) =>
105
108
  /** The media parts pictures need, allocated as they are written, and the drawings' ids. */
106
109
  export class Media {
107
110
  readonly added: { name: string; data: Uint8Array; contentType: string }[] = [];
111
+ /** The document's content controls, written once across its parts. */
112
+ readonly controls: ControlWriter;
108
113
  readonly #parts = new Map<string, string>();
109
114
  /** Ids drawings Foli does not write hold (opaque content, headers and footers). */
110
115
  readonly #reserved = new Set<number>();
@@ -119,6 +124,7 @@ export class Media {
119
124
  /** The parts rewritten from the model (their drawings are the document's). */
120
125
  rewritten: readonly string[] = [],
121
126
  ) {
127
+ this.controls = new ControlWriter(doc.controls ?? {});
122
128
  // `wp:docPr` ids are unique in a document, across its parts: new ones above all of them.
123
129
  let max = 0;
124
130
  for (const attrs of picturesOf(doc))
@@ -129,7 +135,7 @@ export class Media {
129
135
  max = Math.max(max, id);
130
136
  }
131
137
  };
132
- JSON.stringify([doc.content, doc.comments], (key, value) => {
138
+ JSON.stringify([doc.content, doc.comments, doc.stories], (key, value) => {
133
139
  if (key === "xml" && typeof value === "string") reserve(value);
134
140
  return value;
135
141
  });
@@ -547,10 +547,47 @@ const SECTION_CHILDREN: Record<string, readonly string[]> = {
547
547
  pageSize: ["pgSz"],
548
548
  margins: ["pgMar"],
549
549
  titlePage: ["titlePg"],
550
+ columns: ["cols"],
551
+ pageNumbers: ["pgNumType"],
552
+ footnotes: ["footnotePr"],
553
+ endnotes: ["endnotePr"],
554
+ change: ["sectPrChange"],
550
555
  };
551
556
  const SECTION_MODELED = new Set(Object.values(SECTION_CHILDREN).flat());
552
557
 
553
- function sectionChild(name: string, value: unknown): string {
558
+ /** `w:footnotePr` or `w:endnotePr`: its children in CT_FtnProps order. */
559
+ function noteProperties(local: string, v: Json): string {
560
+ const s = (x: unknown) => (x === undefined ? undefined : String(x));
561
+ const children =
562
+ val("pos", s(v.position)) +
563
+ val("numFmt", s(v.format)) +
564
+ val("numStart", s(v.start)) +
565
+ val("numRestart", s(v.restart));
566
+ return children ? el(`w:${local}`, {}, children) : "";
567
+ }
568
+
569
+ /**
570
+ * The setup a tracked change records, every value it could have changed spelled out: Word finds
571
+ * no change in what the recorded `w:sectPr` leaves out (a `w:cols` without `w:num`, checked with
572
+ * Word 16). One read from a file stays as it was.
573
+ */
574
+ function previousSetup(previous: Json): Json {
575
+ if (previous.ext) return previous;
576
+ const size = (previous.pageSize ?? {}) as Json;
577
+ const columns = (previous.columns ?? {}) as Json;
578
+ return {
579
+ ...previous,
580
+ type: previous.type ?? "nextPage",
581
+ pageSize: { ...size, width: size.width ?? 12240, height: size.height ?? 15840 },
582
+ margins: previous.margins ?? {},
583
+ columns: {
584
+ ...columns,
585
+ count: columns.count ?? (columns.widths as unknown[] | undefined)?.length ?? 1,
586
+ },
587
+ };
588
+ }
589
+
590
+ function sectionChild(name: string, value: unknown, ns: Namespaces): string {
554
591
  if (value === undefined || value === null) return "";
555
592
  const v = value as Json;
556
593
  const s = (x: unknown) => (x === undefined || x === null ? undefined : String(x));
@@ -580,6 +617,35 @@ function sectionChild(name: string, value: unknown): string {
580
617
  });
581
618
  case "titlePage":
582
619
  return onOff("titlePg", value as boolean);
620
+ case "columns":
621
+ return el(
622
+ "w:cols",
623
+ {
624
+ "w:num": s(v.count),
625
+ "w:sep": v.separator as boolean | undefined,
626
+ "w:space": s(v.space),
627
+ "w:equalWidth": v.equalWidth as boolean | undefined,
628
+ },
629
+ ((v.widths ?? []) as Json[])
630
+ .map((col) => el("w:col", { "w:w": s(col.width), "w:space": s(col.space) }))
631
+ .join(""),
632
+ );
633
+ case "pageNumbers":
634
+ return el("w:pgNumType", { "w:fmt": s(v.format), "w:start": s(v.start) });
635
+ case "footnotes":
636
+ return noteProperties("footnotePr", v);
637
+ case "endnotes":
638
+ return noteProperties("endnotePr", v);
639
+ case "change":
640
+ return el(
641
+ "w:sectPrChange",
642
+ { "w:id": s(v.id), "w:author": s(v.author) ?? "", "w:date": s(v.date) },
643
+ // What the section was: never its header references (CT_SectPrBase has none).
644
+ sectionXml(
645
+ { ...previousSetup(v.previous as Json), headers: undefined, footers: undefined },
646
+ ns,
647
+ ),
648
+ );
583
649
  default:
584
650
  return "";
585
651
  }
@@ -597,7 +663,7 @@ export function sectionXml(section: Json, ns: Namespaces): string {
597
663
  generated.set(
598
664
  locals[0] as string,
599
665
  child(original, same(section[prop], reread[prop]), locals, () =>
600
- sectionChild(prop, section[prop]),
666
+ sectionChild(prop, section[prop], ns),
601
667
  ),
602
668
  );
603
669
  }