@folijs/core 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 (125) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/state/commands.d.ts +2 -0
  3. package/dist/state/commands.d.ts.map +1 -1
  4. package/dist/state/commands.js +38 -6
  5. package/dist/state/commands.js.map +1 -1
  6. package/dist/state/comments.d.ts.map +1 -1
  7. package/dist/state/comments.js +12 -3
  8. package/dist/state/comments.js.map +1 -1
  9. package/dist/state/controls.d.ts +128 -0
  10. package/dist/state/controls.d.ts.map +1 -0
  11. package/dist/state/controls.js +1459 -0
  12. package/dist/state/controls.js.map +1 -0
  13. package/dist/state/editor.d.ts +86 -1
  14. package/dist/state/editor.d.ts.map +1 -1
  15. package/dist/state/editor.js +168 -42
  16. package/dist/state/editor.js.map +1 -1
  17. package/dist/state/fields.d.ts +79 -0
  18. package/dist/state/fields.d.ts.map +1 -0
  19. package/dist/state/fields.js +398 -0
  20. package/dist/state/fields.js.map +1 -0
  21. package/dist/state/fieldupdate.d.ts +178 -0
  22. package/dist/state/fieldupdate.d.ts.map +1 -0
  23. package/dist/state/fieldupdate.js +1574 -0
  24. package/dist/state/fieldupdate.js.map +1 -0
  25. package/dist/state/find.d.ts +68 -0
  26. package/dist/state/find.d.ts.map +1 -0
  27. package/dist/state/find.js +397 -0
  28. package/dist/state/find.js.map +1 -0
  29. package/dist/state/history.d.ts +12 -1
  30. package/dist/state/history.d.ts.map +1 -1
  31. package/dist/state/history.js +43 -7
  32. package/dist/state/history.js.map +1 -1
  33. package/dist/state/index.d.ts +12 -5
  34. package/dist/state/index.d.ts.map +1 -1
  35. package/dist/state/index.js +10 -3
  36. package/dist/state/index.js.map +1 -1
  37. package/dist/state/mark.d.ts.map +1 -1
  38. package/dist/state/mark.js +8 -1
  39. package/dist/state/mark.js.map +1 -1
  40. package/dist/state/navigation.d.ts +70 -0
  41. package/dist/state/navigation.d.ts.map +1 -0
  42. package/dist/state/navigation.js +226 -0
  43. package/dist/state/navigation.js.map +1 -0
  44. package/dist/state/notes.d.ts +94 -0
  45. package/dist/state/notes.d.ts.map +1 -0
  46. package/dist/state/notes.js +444 -0
  47. package/dist/state/notes.js.map +1 -0
  48. package/dist/state/review.d.ts +13 -4
  49. package/dist/state/review.d.ts.map +1 -1
  50. package/dist/state/review.js +133 -18
  51. package/dist/state/review.js.map +1 -1
  52. package/dist/state/sections.d.ts +101 -0
  53. package/dist/state/sections.d.ts.map +1 -0
  54. package/dist/state/sections.js +472 -0
  55. package/dist/state/sections.js.map +1 -0
  56. package/dist/state/state.d.ts +2 -0
  57. package/dist/state/state.d.ts.map +1 -1
  58. package/dist/state/state.js +4 -0
  59. package/dist/state/state.js.map +1 -1
  60. package/dist/state/stories.d.ts +41 -0
  61. package/dist/state/stories.d.ts.map +1 -0
  62. package/dist/state/stories.js +243 -0
  63. package/dist/state/stories.js.map +1 -0
  64. package/dist/state/tables.d.ts.map +1 -1
  65. package/dist/state/tables.js +2 -1
  66. package/dist/state/tables.js.map +1 -1
  67. package/dist/state/track.d.ts +23 -0
  68. package/dist/state/track.d.ts.map +1 -1
  69. package/dist/state/track.js +58 -9
  70. package/dist/state/track.js.map +1 -1
  71. package/dist/state/word.d.ts +78 -16
  72. package/dist/state/word.d.ts.map +1 -1
  73. package/dist/state/word.js +230 -10
  74. package/dist/state/word.js.map +1 -1
  75. package/dist/state/wordclip.d.ts +15 -6
  76. package/dist/state/wordclip.d.ts.map +1 -1
  77. package/dist/state/wordclip.js +192 -14
  78. package/dist/state/wordclip.js.map +1 -1
  79. package/dist/state/wordformat.d.ts +1 -1
  80. package/dist/state/wordformat.d.ts.map +1 -1
  81. package/dist/state/wordformat.js +60 -1
  82. package/dist/state/wordformat.js.map +1 -1
  83. package/dist/v3/document.d.ts +130 -7
  84. package/dist/v3/document.d.ts.map +1 -1
  85. package/dist/v3/document.js +172 -30
  86. package/dist/v3/document.js.map +1 -1
  87. package/dist/v3/index.d.ts +1 -1
  88. package/dist/v3/index.d.ts.map +1 -1
  89. package/dist/v3/index.js +1 -1
  90. package/dist/v3/index.js.map +1 -1
  91. package/dist/v3/resolve.d.ts +9 -3
  92. package/dist/v3/resolve.d.ts.map +1 -1
  93. package/dist/v3/resolve.js +22 -4
  94. package/dist/v3/resolve.js.map +1 -1
  95. package/dist/v3/schema.d.ts +2 -0
  96. package/dist/v3/schema.d.ts.map +1 -1
  97. package/dist/v3/schema.js +89 -3
  98. package/dist/v3/schema.js.map +1 -1
  99. package/package.json +1 -1
  100. package/src/state/commands.ts +41 -4
  101. package/src/state/comments.ts +11 -3
  102. package/src/state/controls.ts +1596 -0
  103. package/src/state/editor.ts +291 -47
  104. package/src/state/fields.ts +432 -0
  105. package/src/state/fieldupdate.ts +1770 -0
  106. package/src/state/find.ts +510 -0
  107. package/src/state/history.ts +51 -7
  108. package/src/state/index.ts +123 -0
  109. package/src/state/mark.ts +8 -1
  110. package/src/state/navigation.ts +305 -0
  111. package/src/state/notes.ts +519 -0
  112. package/src/state/numeric-pictures.word.json +172 -0
  113. package/src/state/review.ts +171 -19
  114. package/src/state/sections.ts +571 -0
  115. package/src/state/state.ts +5 -0
  116. package/src/state/stories.ts +285 -0
  117. package/src/state/tables.ts +2 -1
  118. package/src/state/track.ts +65 -10
  119. package/src/state/word.ts +275 -12
  120. package/src/state/wordclip.ts +211 -29
  121. package/src/state/wordformat.ts +61 -1
  122. package/src/v3/document.ts +326 -41
  123. package/src/v3/index.ts +7 -0
  124. package/src/v3/resolve.ts +33 -9
  125. package/src/v3/schema.ts +92 -3
@@ -18,6 +18,7 @@ import {
18
18
  import { migrateToV3 } from "./migrate.js";
19
19
  import {
20
20
  checkCellProperties,
21
+ checkNoteProperties,
21
22
  checkRowProperties,
22
23
  checkSection,
23
24
  checkTableProperties,
@@ -26,8 +27,11 @@ import {
26
27
  schema,
27
28
  } from "./schema.js";
28
29
 
29
- /** The schema version of documents in the Word model (ADR-0005; v4 adds tables and pictures, ADR-0006). */
30
- export const SCHEMA_VERSION = 4;
30
+ /**
31
+ * The schema version of documents in the Word model (ADR-0005; v4 adds tables and pictures,
32
+ * ADR-0006; v5 stories, fields, content controls and notes, ADR-0007).
33
+ */
34
+ export const SCHEMA_VERSION = 5;
31
35
 
32
36
  /** Page setup of a section, in twips (1/1440 inch). Missing parts take Word's defaults. */
33
37
  export interface SectionJSON {
@@ -46,10 +50,32 @@ export interface SectionJSON {
46
50
  /** Relationship ids of the header and footer parts (their content stays in the package until Phase 11). */
47
51
  headers?: { default?: string; first?: string; even?: string };
48
52
  footers?: { default?: string; first?: string; even?: string };
53
+ /** `w:cols` (v5). `widths` when the columns are not of equal width. */
54
+ columns?: {
55
+ count?: number;
56
+ space?: number;
57
+ equalWidth?: boolean;
58
+ separator?: boolean;
59
+ widths?: { width: number; space?: number }[];
60
+ };
61
+ /** `w:pgNumType` (v5). */
62
+ pageNumbers?: { start?: number; format?: string };
63
+ footnotes?: NotePropertiesJSON;
64
+ endnotes?: NotePropertiesJSON;
65
+ /** `w:sectPrChange`: who changed the page setup while tracking, and what it was. */
66
+ change?: { id: number; author: string; date?: string | null; previous: SectionJSON };
49
67
  /** The `w:sectPr` this was read from, verbatim. */
50
68
  ext?: string;
51
69
  }
52
70
 
71
+ /** How notes are placed and numbered (`w:footnotePr`, `w:endnotePr`). */
72
+ export interface NotePropertiesJSON {
73
+ position?: "pageBottom" | "beneathText" | "sectEnd" | "docEnd";
74
+ format?: string;
75
+ start?: number;
76
+ restart?: "continuous" | "eachSect" | "eachPage";
77
+ }
78
+
53
79
  export interface BorderJSON {
54
80
  style: string;
55
81
  size?: number;
@@ -278,6 +304,74 @@ export interface CommentJSON {
278
304
  ext?: string;
279
305
  }
280
306
 
307
+ /**
308
+ * Content outside the body (schema v5, ADR-0007). `noteType` is a note's `w:type`: the separators
309
+ * and the continuation notice have no reference and are not numbered.
310
+ */
311
+ export interface StoryJSON {
312
+ kind: "header" | "footer" | "footnote" | "endnote";
313
+ noteType?: "normal" | "separator" | "continuationSeparator" | "continuationNotice";
314
+ /** A `doc` of blocks. */
315
+ content: NodeJSON;
316
+ /** What the part keeps of the story's own element, verbatim. */
317
+ ext?: string;
318
+ }
319
+
320
+ /** A content control's properties (`w:sdtPr`, schema v5), by the id its nodes refer to. */
321
+ export interface ControlJSON {
322
+ kind:
323
+ | "text"
324
+ | "richText"
325
+ | "dropDown"
326
+ | "comboBox"
327
+ | "date"
328
+ | "checkbox"
329
+ | "picture"
330
+ | "repeating"
331
+ | "repeatingItem"
332
+ | "other";
333
+ tag?: string;
334
+ alias?: string;
335
+ lock?: "sdtLocked" | "contentLocked" | "sdtContentLocked" | "unlocked";
336
+ items?: { value: string; display?: string }[];
337
+ dateFormat?: string;
338
+ /** `w:date/@w:fullDate`: the date picked, as Word writes it (`2026-03-03T00:00:00Z`). */
339
+ date?: string;
340
+ checked?: boolean;
341
+ /** A check box's glyphs (`w14:checkedState`, `w14:uncheckedState`): hex code and font. */
342
+ checkedState?: { value: string; font?: string };
343
+ uncheckedState?: { value: string; font?: string };
344
+ /** `w:text/@w:multiLine`: a plain text control that takes line breaks. */
345
+ multiLine?: boolean;
346
+ /** `w:sdtPr/w:rPr` as marks: how text put in place of the placeholder looks. */
347
+ format?: MarkJSON[];
348
+ /** `w15:doNotAllowInsertDeleteSection`: a repeating section's items are fixed. */
349
+ noInsertDelete?: boolean;
350
+ /** Deleted whole while tracking (in the editor: not written): accepting removes the control. */
351
+ deleted?: boolean;
352
+ /**
353
+ * `showing`: the content is the placeholder. `docPart`: the glossary entry it comes from.
354
+ * `text`: that entry's text, what emptying the control brings back.
355
+ */
356
+ placeholder?: { showing?: boolean; docPart?: string; text?: string };
357
+ /** `w:dataBinding`: kept, not evaluated. */
358
+ binding?: { xpath?: string; storeItemId?: string; prefixMappings?: string };
359
+ /** `w:sdtPr` and `w:sdtEndPr`, verbatim. */
360
+ ext?: string;
361
+ }
362
+
363
+ /** What `word/settings.xml` says about pages and notes (schema v5). */
364
+ export interface WordSettingsJSON {
365
+ /**
366
+ * `w:compat/w:doNotUseHTMLParagraphAutoSpacing`: the space after a paragraph and the space
367
+ * before the next add up (without it Word takes the larger, in every compatibility mode).
368
+ */
369
+ doNotUseHTMLParagraphAutoSpacing?: boolean;
370
+ evenAndOddHeaders?: boolean;
371
+ footnotes?: NotePropertiesJSON;
372
+ endnotes?: NotePropertiesJSON;
373
+ }
374
+
281
375
  /** A document in the Word model: the content tree and what Word keeps beside it. */
282
376
  export interface FoliDocument {
283
377
  schemaVersion: typeof SCHEMA_VERSION;
@@ -296,21 +390,37 @@ export interface FoliDocument {
296
390
  comments: CommentJSON[];
297
391
  /** The pictures' bytes, by the key `picture` nodes give (none when missing). */
298
392
  resources?: Record<string, ResourceJSON>;
393
+ /** Headers, footers and notes, by id (a header's or footer's is its relationship id). */
394
+ stories?: Record<string, StoryJSON>;
395
+ /** Content controls' properties, by the id their nodes refer to. */
396
+ controls?: Record<string, ControlJSON>;
397
+ settings?: WordSettingsJSON;
299
398
  content: NodeJSON;
300
399
  }
301
400
 
401
+ /** A document of schema v4 (no stories, fields or content controls in the model). */
402
+ export type FoliDocumentV4 = Omit<
403
+ FoliDocument,
404
+ "schemaVersion" | "stories" | "controls" | "settings"
405
+ > & { schemaVersion: 4 };
406
+
302
407
  /** A document of schema v3 (no tables or pictures in the model), as `migrateToV3` gives it. */
303
- export type FoliDocumentV3 = Omit<FoliDocument, "schemaVersion" | "resources"> & {
408
+ export type FoliDocumentV3 = Omit<FoliDocumentV4, "schemaVersion" | "resources"> & {
304
409
  schemaVersion: 3;
305
410
  };
306
411
 
307
412
  /** Schema v3 → v4: the version only (a table kept opaque stays so until imported again). */
308
- export function migrateToV4(doc: FoliDocumentV3): FoliDocument {
413
+ export function migrateToV4(doc: FoliDocumentV3): FoliDocumentV4 {
414
+ return { ...doc, schemaVersion: 4 };
415
+ }
416
+
417
+ /** Schema v4 → v5: the version only (what is opaque stays so until imported again). */
418
+ export function migrateToV5(doc: FoliDocumentV4): FoliDocument {
309
419
  return { ...doc, schemaVersion: SCHEMA_VERSION };
310
420
  }
311
421
 
312
422
  /**
313
- * A new document: `content` (schema v4; default: one empty paragraph) on A4 with 25.4 mm
423
+ * A new document: `content` (schema v5; default: one empty paragraph) on A4 with 25.4 mm
314
424
  * margins, with the styles and list definitions the editor's commands use (Normal, Heading 1–6,
315
425
  * List Paragraph, Hyperlink; bullets and numbers) and 11 pt Georgia, 1.5 lines: the look a
316
426
  * migrated 0.2.0 document has. `section` (in twips: `mmToTwips`) is merged over that page:
@@ -322,8 +432,10 @@ export function createDocument(
322
432
  section?: SectionJSON,
323
433
  ): FoliDocument {
324
434
  const empty = { type: "doc", content: [] } as const satisfies NodeJSON;
325
- const blank = migrateToV4(
326
- migrateToV3({ schemaVersion: 2, settings: DEFAULT_SETTINGS, content: empty as never }),
435
+ const blank = migrateToV5(
436
+ migrateToV4(
437
+ migrateToV3({ schemaVersion: 2, settings: DEFAULT_SETTINGS, content: empty as never }),
438
+ ),
327
439
  );
328
440
  const base = blank.section;
329
441
  return {
@@ -353,25 +465,35 @@ export function parseDocument(input: unknown): FoliDocument {
353
465
  if (!isRecord(input)) throw new FoliDocumentError("Document must be an object");
354
466
  const version = input.schemaVersion;
355
467
  if (version === 1 || version === 2) {
356
- return parseDocument(migrateToV4(migrateToV3(parseDocumentV2(input))));
468
+ return parseDocument(migrateToV5(migrateToV4(migrateToV3(parseDocumentV2(input)))));
357
469
  }
358
- if (version === 3) {
359
- if (Object.hasOwn(input, "resources")) fail("resources", "unknown key (schema 4 and later)");
470
+ if (version === 3 || version === 4) {
471
+ if (version === 3 && Object.hasOwn(input, "resources"))
472
+ fail("resources", "unknown key (schema 4 and later)");
473
+ for (const key of V5_KEYS)
474
+ if (Object.hasOwn(input, key)) fail(key, "unknown key (schema 5 and later)");
360
475
  const doc = parseDocument({ ...input, schemaVersion: SCHEMA_VERSION });
361
- // Tables and pictures are schema 4's: a schema 3 document holding one is not one.
476
+ // What a later schema added is not in a document that says it is of an earlier one.
477
+ const later = laterSection(doc.section);
478
+ if (later) fail("section", `${later} is of schema 5 (the document says schema ${version})`);
362
479
  for (const [path, content] of [
363
480
  ["content", doc.content],
364
481
  ...doc.comments.map((c, i) => [`comments[${i}].content`, { content: c.content }] as const),
365
482
  ] as const) {
366
- const found = nodeOfV4(content);
367
- if (found) fail(path, `${found} is a schema 4 node (the document says schema 3)`);
483
+ const found = laterNode(content, version);
484
+ if (found)
485
+ fail(
486
+ path,
487
+ `${found.name} is a schema ${found.schema} node (the document says schema ${version})`,
488
+ );
368
489
  }
369
- doc.styles.forEach((style, i) => {
370
- for (const key of ["table", "row", "cell", "conditions"]) {
371
- if (Object.hasOwn(style, key))
372
- fail(`styles[${i}]`, `unknown key ${key} (schema 4 and later)`);
373
- }
374
- });
490
+ if (version === 3)
491
+ doc.styles.forEach((style, i) => {
492
+ for (const key of ["table", "row", "cell", "conditions"]) {
493
+ if (Object.hasOwn(style, key))
494
+ fail(`styles[${i}]`, `unknown key ${key} (schema 4 and later)`);
495
+ }
496
+ });
375
497
  return doc;
376
498
  }
377
499
  if (version !== SCHEMA_VERSION) {
@@ -402,6 +524,9 @@ export function parseDocument(input: unknown): FoliDocument {
402
524
  if (input.theme !== undefined) check("theme", input.theme, checkTheme);
403
525
  check("comments", input.comments, listOf(checkComment));
404
526
  if (input.resources !== undefined) check("resources", input.resources, checkResources);
527
+ if (input.stories !== undefined) check("stories", input.stories, checkStories);
528
+ if (input.controls !== undefined) check("controls", input.controls, checkControls);
529
+ if (input.settings !== undefined) check("settings", input.settings, checkSettings);
405
530
  const styles = input.styles as StyleJSON[];
406
531
  const comments = input.comments as CommentJSON[];
407
532
  noCycles(
@@ -420,6 +545,14 @@ export function parseDocument(input: unknown): FoliDocument {
420
545
  );
421
546
 
422
547
  const content = parseContent(input.content);
548
+ const stories = Object.entries((input.stories ?? {}) as Record<string, StoryJSON>).map(
549
+ ([id, story]) => {
550
+ const path = `stories[${JSON.stringify(id)}].content`;
551
+ const tree = parseContent(story.content, path);
552
+ storyRules(tree, story.kind, path);
553
+ return [id, { ...structuredClone({ ...story, content: null }), content: copied(tree) }];
554
+ },
555
+ );
423
556
  // A copy: the validated document must not change when the caller's input does.
424
557
  const envelope = structuredClone({
425
558
  section: input.section,
@@ -428,7 +561,19 @@ export function parseDocument(input: unknown): FoliDocument {
428
561
  numbering: input.numbering,
429
562
  theme: input.theme,
430
563
  resources: input.resources,
431
- }) as Pick<FoliDocument, "section" | "defaults" | "styles" | "numbering" | "theme" | "resources">;
564
+ controls: input.controls,
565
+ settings: input.settings,
566
+ }) as Pick<
567
+ FoliDocument,
568
+ | "section"
569
+ | "defaults"
570
+ | "styles"
571
+ | "numbering"
572
+ | "theme"
573
+ | "resources"
574
+ | "controls"
575
+ | "settings"
576
+ >;
432
577
  return {
433
578
  schemaVersion: SCHEMA_VERSION,
434
579
  section: envelope.section,
@@ -438,18 +583,32 @@ export function parseDocument(input: unknown): FoliDocument {
438
583
  ...(envelope.theme === undefined ? {} : { theme: envelope.theme }),
439
584
  comments: comments.map((c, i) => ({
440
585
  ...structuredClone({ ...c, content: [] }),
441
- content: blocks(c.content, `comments[${i}].content`).map((block) => block.toJSON()),
586
+ content: blocks(c.content, `comments[${i}].content`).map((block) => {
587
+ block.descendants((node) => {
588
+ if (node.type.name === "noteReference")
589
+ fail(`comments[${i}].content`, "a comment cannot hold a note reference");
590
+ return true;
591
+ });
592
+ return copied(block);
593
+ }),
442
594
  })),
443
595
  ...(envelope.resources === undefined ? {} : { resources: envelope.resources }),
444
- content: content.toJSON(),
596
+ ...(input.stories === undefined ? {} : { stories: Object.fromEntries(stories) }),
597
+ ...(envelope.controls === undefined ? {} : { controls: envelope.controls }),
598
+ ...(envelope.settings === undefined ? {} : { settings: envelope.settings }),
599
+ content: copied(content),
445
600
  };
446
601
  }
447
602
 
603
+ /** A node's JSON sharing nothing with the input its attributes came from. */
604
+ const copied = (node: Node): NodeJSON => structuredClone(node.toJSON());
605
+
448
606
  /**
449
607
  * Parses untrusted schema v4 content into a `doc` node, with Word's rules the content
450
608
  * expressions do not say (`fragment`: content to paste, which a table may end): a table is never
451
- * followed by a table (Word would merge them) nor ends
452
- * the document, and a paragraph in a cell ends no section and holds no page or column break.
609
+ * followed by a table (Word would merge them; tables in different content controls stay apart)
610
+ * nor ends the document, and a paragraph in a cell ends no section and holds no page or column
611
+ * break.
453
612
  */
454
613
  export function parseContent(value: unknown, path = "content", fragment = false): Node {
455
614
  const doc = schema.nodeFromJSON(value, path);
@@ -464,7 +623,10 @@ function wordRules(parent: Node, path: string, inCell: boolean, fragment = false
464
623
  const at = `${path}.content[${index}]`;
465
624
  if (node.type.name === "table") {
466
625
  const next = parent.maybeChild(index + 1);
467
- if (next?.type.name === "table") {
626
+ if (
627
+ next?.type.name === "table" &&
628
+ JSON.stringify(next.attrs.controls) === JSON.stringify(node.attrs.controls)
629
+ ) {
468
630
  fail(at, "a table cannot follow a table (Word would merge them): a paragraph goes between");
469
631
  }
470
632
  if (!next && parent.type.name === "doc" && !fragment) {
@@ -487,15 +649,62 @@ function wordRules(parent: Node, path: string, inCell: boolean, fragment = false
487
649
  });
488
650
  }
489
651
 
652
+ /** What a story may not hold (ADR-0007): import keeps such content opaque instead. */
653
+ export function storyRules(tree: Node, kind: StoryJSON["kind"], path: string): void {
654
+ tree.descendants((node) => {
655
+ const name = node.type.name;
656
+ if (node.attrs.section) fail(path, "a story cannot end a section");
657
+ if (name === "noteReference") fail(path, "a story cannot hold a note reference");
658
+ if (COMMENT_NODES.has(name)) fail(path, `a ${kind} cannot hold comments`);
659
+ if (
660
+ (kind === "footnote" || kind === "endnote") &&
661
+ (name === "pageBreak" || name === "columnBreak")
662
+ )
663
+ fail(path, `a note cannot hold a ${name}`);
664
+ return true;
665
+ });
666
+ }
667
+
668
+ const COMMENT_NODES = new Set(["commentStart", "commentEnd", "commentReference"]);
669
+
490
670
  const V4_NODES = new Set(["table", "tableRow", "tableCell", "picture"]);
671
+ const V5_NODES = new Set([
672
+ "fieldStart",
673
+ "fieldCode",
674
+ "fieldSeparator",
675
+ "fieldEnd",
676
+ "controlStart",
677
+ "controlEnd",
678
+ "noteReference",
679
+ "noteMark",
680
+ ]);
681
+ const V5_KEYS = ["stories", "controls", "settings"];
682
+ const V5_SECTION_KEYS = ["columns", "pageNumbers", "footnotes", "endnotes"];
683
+
684
+ /** The first part of a section that schema 5 added, if any. */
685
+ function laterSection(section: unknown): string | undefined {
686
+ return isRecord(section) ? V5_SECTION_KEYS.find((key) => Object.hasOwn(section, key)) : undefined;
687
+ }
491
688
 
492
- /** The first schema 4 node type in validated content JSON, if any. */
493
- function nodeOfV4(content: NodeJSON | { content: NodeJSON[] }): string | undefined {
689
+ /**
690
+ * The first thing in validated content JSON that a schema after `version` added, if any: a node
691
+ * type, a block's `controls`, a part of a section.
692
+ */
693
+ function laterNode(
694
+ content: NodeJSON | { content: NodeJSON[] },
695
+ version: number,
696
+ ): { name: string; schema: number } | undefined {
494
697
  const stack: unknown[] = [content];
495
698
  while (stack.length) {
496
699
  const node = stack.pop();
497
700
  if (!isRecord(node)) continue;
498
- if (V4_NODES.has(node.type as string)) return node.type as string;
701
+ const name = node.type as string;
702
+ if (version < 4 && V4_NODES.has(name)) return { name, schema: 4 };
703
+ if (V5_NODES.has(name)) return { name, schema: 5 };
704
+ const attrs = isRecord(node.attrs) ? node.attrs : {};
705
+ if (attrs.controls) return { name: "controls", schema: 5 };
706
+ const part = laterSection(attrs.section);
707
+ if (part) return { name: part, schema: 5 };
499
708
  if (Array.isArray(node.content)) for (const child of node.content) stack.push(child);
500
709
  }
501
710
  return undefined;
@@ -510,6 +719,9 @@ const ENVELOPE_KEYS = [
510
719
  "theme",
511
720
  "comments",
512
721
  "resources",
722
+ "stories",
723
+ "controls",
724
+ "settings",
513
725
  "content",
514
726
  ];
515
727
 
@@ -636,19 +848,92 @@ export const checkResource: Check = (v) => {
636
848
  : undefined;
637
849
  };
638
850
 
639
- const checkResources: Check = (v) => {
640
- if (!isRecord(v)) return "must be an object";
641
- const entries = Object.entries(v);
642
- if (entries.length > 100_000) return "must have at most 100000 resources";
643
- for (const [key, value] of entries) {
644
- // An own `__proto__` key would read as the prototype wherever a missing key is looked up.
645
- const keyError = key === "__proto__" ? "is not a resource key" : text()(key);
646
- if (keyError) return `${key.slice(0, 64)} ${keyError}`;
647
- const error = checkResource(value);
648
- if (error) return `${key} ${error}`;
649
- }
650
- return undefined;
651
- };
851
+ /** An object keyed by ids, every value passing `check`. */
852
+ const recordOf =
853
+ (check: Check, what: string): Check =>
854
+ (v) => {
855
+ if (!isRecord(v)) return "must be an object";
856
+ const entries = Object.entries(v);
857
+ if (entries.length > 100_000) return `must have at most 100000 ${what}s`;
858
+ for (const [key, value] of entries) {
859
+ // An own `__proto__` key would read as the prototype wherever a missing key is looked up.
860
+ const keyError = key === "__proto__" ? `is not a ${what} key` : text()(key);
861
+ if (keyError) return `${key.slice(0, 64)} ${keyError}`;
862
+ const error = check(value);
863
+ if (error) return `${key} ${error}`;
864
+ }
865
+ return undefined;
866
+ };
867
+
868
+ const checkResources = recordOf(checkResource, "resource");
869
+
870
+ const NOTE_KINDS = ["footnote", "endnote"];
871
+ /** The tree is checked by `parseContent` afterwards, with its path. */
872
+ const checkStory: Check = (v) =>
873
+ shape(
874
+ {
875
+ kind: oneOf(["header", "footer", ...NOTE_KINDS]),
876
+ noteType: oneOf(["normal", "separator", "continuationSeparator", "continuationNotice"]),
877
+ content: (c) => (isRecord(c) ? undefined : "must be an object"),
878
+ ext: xml,
879
+ },
880
+ ["kind", "content"],
881
+ )(v) ??
882
+ (isRecord(v) && v.noteType !== undefined && !NOTE_KINDS.includes(v.kind as string)
883
+ ? "noteType is for notes"
884
+ : undefined);
885
+ const checkStories = recordOf(checkStory, "story");
886
+
887
+ /** A content control's properties. */
888
+ export const checkControl: Check = shape(
889
+ {
890
+ kind: oneOf([
891
+ "text",
892
+ "richText",
893
+ "dropDown",
894
+ "comboBox",
895
+ "date",
896
+ "checkbox",
897
+ "picture",
898
+ "repeating",
899
+ "repeatingItem",
900
+ "other",
901
+ ]),
902
+ tag: str(),
903
+ alias: str(),
904
+ lock: oneOf(["sdtLocked", "contentLocked", "sdtContentLocked", "unlocked"]),
905
+ items: listOf(shape({ value: str(), display: str() }, ["value"])),
906
+ dateFormat: str(),
907
+ date: str(),
908
+ checked: bool,
909
+ checkedState: shape({ value: str(), font: str() }, ["value"]),
910
+ uncheckedState: shape({ value: str(), font: str() }, ["value"]),
911
+ multiLine: bool,
912
+ format: runProperties,
913
+ noInsertDelete: bool,
914
+ deleted: bool,
915
+ placeholder: shape({ showing: bool, docPart: str(), text: str(65_535) }, [], true),
916
+ binding: shape(
917
+ { xpath: str(65_535), storeItemId: str(), prefixMappings: str(65_535) },
918
+ [],
919
+ true,
920
+ ),
921
+ ext: xml,
922
+ },
923
+ ["kind"],
924
+ );
925
+ const checkControls = recordOf(checkControl, "control");
926
+
927
+ const checkSettings: Check = shape(
928
+ {
929
+ doNotUseHTMLParagraphAutoSpacing: bool,
930
+ evenAndOddHeaders: bool,
931
+ footnotes: checkNoteProperties,
932
+ endnotes: checkNoteProperties,
933
+ },
934
+ [],
935
+ true,
936
+ );
652
937
 
653
938
  const checkLevel: Check = shape(
654
939
  {
package/src/v3/index.ts CHANGED
@@ -3,11 +3,16 @@ export {
3
3
  type BorderJSON,
4
4
  type CellPropertiesJSON,
5
5
  type CommentJSON,
6
+ type ControlJSON,
7
+ checkControl,
6
8
  createDocument,
7
9
  type FoliDocument,
8
10
  type FoliDocumentV3,
11
+ type FoliDocumentV4,
9
12
  type MeasureJSON,
10
13
  migrateToV4,
14
+ migrateToV5,
15
+ type NotePropertiesJSON,
11
16
  type NumberingInstanceJSON,
12
17
  type NumberingLevelJSON,
13
18
  type ParagraphPropertiesJSON,
@@ -17,12 +22,14 @@ export {
17
22
  type RowPropertiesJSON,
18
23
  SCHEMA_VERSION,
19
24
  type SectionJSON,
25
+ type StoryJSON,
20
26
  type StyleJSON,
21
27
  TABLE_CONDITIONS,
22
28
  type TableCondition,
23
29
  type TableConditionJSON,
24
30
  type TablePropertiesJSON,
25
31
  type ThemeJSON,
32
+ type WordSettingsJSON,
26
33
  } from "./document.js";
27
34
  export { migrateToV3 } from "./migrate.js";
28
35
  export {
package/src/v3/resolve.ts CHANGED
@@ -84,12 +84,16 @@ export interface ParagraphFormat {
84
84
  export interface ListMarker {
85
85
  /** As Word shows it ("1.", "1.1", "(a)", or a bullet's character as the file has it). */
86
86
  text: string;
87
+ /** The same without the words of its format: "Section 1." is "1." (`REF \\t`). */
88
+ plain: string;
87
89
  /** What follows the marker. */
88
90
  suffix: "tab" | "space" | "nothing";
89
91
  justification: string;
90
92
  /** The marker's formatting: the paragraph's, its mark's, then the level's run properties. */
91
93
  run: RunFormat;
92
94
  instance: number;
95
+ /** The definition counted: instances sharing one go on from each other. */
96
+ abstract: number;
93
97
  level: number;
94
98
  }
95
99
 
@@ -371,11 +375,22 @@ export function formatNumber(n: number, format: string | undefined): string {
371
375
  return letters(n).toLowerCase();
372
376
  case "ordinal":
373
377
  return ordinal(n);
378
+ case "chicago":
379
+ return chicago(n);
380
+ case "numberInDash":
381
+ return `- ${n} -`;
374
382
  default:
375
383
  return String(n);
376
384
  }
377
385
  }
378
386
 
387
+ /** Word's `chicago` marks: `*`, `†`, `‡`, `§`, then the same doubled, tripled... */
388
+ function chicago(n: number): string {
389
+ const marks = ["*", "†", "‡", "§"];
390
+ if (n < 1) return String(n);
391
+ return (marks[(n - 1) % 4] as string).repeat(Math.ceil(n / 4));
392
+ }
393
+
379
394
  const ROMAN: [number, string][] = [
380
395
  [1000, "M"],
381
396
  [900, "CM"],
@@ -499,8 +514,8 @@ function last<T, V>(layers: readonly T[], pick: (layer: T) => V | undefined | nu
499
514
  * columns, banded rows, first and last column, first and last row, then the corners. The first
500
515
  * and last row and column (when `look` turns them on) are left out of banding.
501
516
  *
502
- * shortcut: banding counts cells (not grid columns) and leaves out only the first and last
503
- * row; check against Word on the corpus's banded table (06) when tables reach the pages (10.5).
517
+ * shortcut: banding and the first and last column count cells, not grid columns; not checked
518
+ * against Word's drawing of a table with merged cells or rows starting late (`gridBefore`).
504
519
  */
505
520
  export function tableConditions(
506
521
  look: NonNullable<TablePropertiesJSON["look"]>,
@@ -532,7 +547,7 @@ export function tableConditions(
532
547
  return out;
533
548
  }
534
549
 
535
- type Envelope = Pick<FoliDocument, "defaults" | "styles" | "numbering" | "theme">;
550
+ type Envelope = Pick<FoliDocument, "defaults" | "styles" | "numbering" | "theme" | "settings">;
536
551
 
537
552
  interface Level {
538
553
  instance: NumberingInstanceJSON;
@@ -559,6 +574,11 @@ export class Resolver {
559
574
  #defaultTableStyle: string | undefined;
560
575
  readonly #layers = new Map<string, TableLayer>();
561
576
 
577
+ /** Whether a paragraph's space after and the next one's space before add up (else: the larger). */
578
+ get addsParagraphSpacing(): boolean {
579
+ return this.#envelope.settings?.doNotUseHTMLParagraphAutoSpacing === true;
580
+ }
581
+
562
582
  constructor(envelope: Envelope) {
563
583
  this.#envelope = envelope;
564
584
  // With duplicate ids, the first wins, as in Word.
@@ -693,7 +713,7 @@ export class Resolver {
693
713
  * for the cell, which come between them as ECMA-376 17.7.2 orders them), memoized.
694
714
  *
695
715
  * shortcut: Word lets a table style's properties win over the default paragraph style's
696
- * (Normal) in some cases; not modeled until the corpus's tables are measured on pages (10.5).
716
+ * (Normal) in some cases; not modeled (docs/limitations.md).
697
717
  */
698
718
  #paragraphStyle(id: string | undefined, layer?: TableLayer) {
699
719
  const key = JSON.stringify([layer?.key ?? null, id ?? null]);
@@ -869,20 +889,24 @@ export class Resolver {
869
889
  const restart = this.#definition(instance, abstract, deeper)?.restart;
870
890
  if (restart === undefined || (restart !== 0 && index < restart)) levels[deeper] = undefined;
871
891
  }
872
- const text = (level.text ?? "").replace(/%([1-9])/g, (_, d: string) => {
873
- const i = Number(d) - 1;
874
- const format = level.legal ? "decimal" : this.#definition(instance, abstract, i)?.format;
875
- return formatNumber(levels[i] ?? startOf(i), format);
876
- });
892
+ const written = (template: string) =>
893
+ template.replace(/%([1-9])/g, (_, d: string) => {
894
+ const i = Number(d) - 1;
895
+ const format = level.legal ? "decimal" : this.#definition(instance, abstract, i)?.format;
896
+ return formatNumber(levels[i] ?? startOf(i), format);
897
+ });
898
+ const text = written(level.text ?? "");
877
899
  const marker = cloneRun(run);
878
900
  applyDirect(marker, attrs.markFormat as MarkJSON[] | undefined, this.#envelope.theme);
879
901
  applyDirect(marker, level.run, this.#envelope.theme);
880
902
  return {
881
903
  text,
904
+ plain: written((level.text ?? "").replace(/\p{L}+/gu, "")).trim(),
882
905
  suffix: level.suffix ?? "tab",
883
906
  justification: level.justification ?? "left",
884
907
  run: marker,
885
908
  instance: instance.id,
909
+ abstract: abstract.id,
886
910
  level: index,
887
911
  };
888
912
  });