@folijs/core 0.4.0 → 0.5.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 (91) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/model/schema.d.ts +9 -1
  3. package/dist/model/schema.d.ts.map +1 -1
  4. package/dist/model/schema.js +13 -3
  5. package/dist/model/schema.js.map +1 -1
  6. package/dist/state/commands.d.ts +8 -1
  7. package/dist/state/commands.d.ts.map +1 -1
  8. package/dist/state/commands.js +87 -34
  9. package/dist/state/commands.js.map +1 -1
  10. package/dist/state/comments.js +3 -3
  11. package/dist/state/comments.js.map +1 -1
  12. package/dist/state/editor.d.ts.map +1 -1
  13. package/dist/state/editor.js +2 -0
  14. package/dist/state/editor.js.map +1 -1
  15. package/dist/state/index.d.ts +4 -1
  16. package/dist/state/index.d.ts.map +1 -1
  17. package/dist/state/index.js +4 -1
  18. package/dist/state/index.js.map +1 -1
  19. package/dist/state/links.d.ts.map +1 -1
  20. package/dist/state/links.js +30 -19
  21. package/dist/state/links.js.map +1 -1
  22. package/dist/state/pictures.d.ts +51 -0
  23. package/dist/state/pictures.d.ts.map +1 -0
  24. package/dist/state/pictures.js +140 -0
  25. package/dist/state/pictures.js.map +1 -0
  26. package/dist/state/review.d.ts +1 -1
  27. package/dist/state/review.d.ts.map +1 -1
  28. package/dist/state/review.js +92 -13
  29. package/dist/state/review.js.map +1 -1
  30. package/dist/state/selection.d.ts +12 -1
  31. package/dist/state/selection.d.ts.map +1 -1
  32. package/dist/state/selection.js +12 -0
  33. package/dist/state/selection.js.map +1 -1
  34. package/dist/state/tablecommands.d.ts +77 -0
  35. package/dist/state/tablecommands.d.ts.map +1 -0
  36. package/dist/state/tablecommands.js +675 -0
  37. package/dist/state/tablecommands.js.map +1 -0
  38. package/dist/state/tables.d.ts +110 -0
  39. package/dist/state/tables.d.ts.map +1 -0
  40. package/dist/state/tables.js +729 -0
  41. package/dist/state/tables.js.map +1 -0
  42. package/dist/state/track.js +55 -6
  43. package/dist/state/track.js.map +1 -1
  44. package/dist/state/word.js +1 -1
  45. package/dist/state/word.js.map +1 -1
  46. package/dist/state/wordclip.d.ts.map +1 -1
  47. package/dist/state/wordclip.js +26 -9
  48. package/dist/state/wordclip.js.map +1 -1
  49. package/dist/state/wordformat.d.ts +9 -1
  50. package/dist/state/wordformat.d.ts.map +1 -1
  51. package/dist/state/wordformat.js +38 -16
  52. package/dist/state/wordformat.js.map +1 -1
  53. package/dist/v3/document.d.ts +114 -7
  54. package/dist/v3/document.d.ts.map +1 -1
  55. package/dist/v3/document.js +170 -13
  56. package/dist/v3/document.js.map +1 -1
  57. package/dist/v3/index.d.ts +2 -2
  58. package/dist/v3/index.d.ts.map +1 -1
  59. package/dist/v3/index.js +2 -2
  60. package/dist/v3/index.js.map +1 -1
  61. package/dist/v3/migrate.d.ts +2 -2
  62. package/dist/v3/migrate.d.ts.map +1 -1
  63. package/dist/v3/resolve.d.ts +50 -4
  64. package/dist/v3/resolve.d.ts.map +1 -1
  65. package/dist/v3/resolve.js +205 -15
  66. package/dist/v3/resolve.js.map +1 -1
  67. package/dist/v3/schema.d.ts +4 -0
  68. package/dist/v3/schema.d.ts.map +1 -1
  69. package/dist/v3/schema.js +166 -6
  70. package/dist/v3/schema.js.map +1 -1
  71. package/package.json +1 -1
  72. package/src/model/schema.ts +18 -2
  73. package/src/state/commands.ts +80 -28
  74. package/src/state/comments.ts +3 -3
  75. package/src/state/editor.ts +2 -0
  76. package/src/state/index.ts +34 -0
  77. package/src/state/links.ts +27 -17
  78. package/src/state/pictures.ts +168 -0
  79. package/src/state/review.ts +96 -14
  80. package/src/state/selection.ts +15 -1
  81. package/src/state/tablecommands.ts +741 -0
  82. package/src/state/tables.ts +760 -0
  83. package/src/state/track.ts +63 -6
  84. package/src/state/word.ts +1 -1
  85. package/src/state/wordclip.ts +28 -11
  86. package/src/state/wordformat.ts +35 -13
  87. package/src/v3/document.ts +285 -14
  88. package/src/v3/index.ts +14 -0
  89. package/src/v3/migrate.ts +2 -2
  90. package/src/v3/resolve.ts +259 -15
  91. package/src/v3/schema.ts +187 -7
package/src/v3/resolve.ts CHANGED
@@ -7,11 +7,16 @@
7
7
  import type { MarkJSON } from "../model/index.js";
8
8
  import type {
9
9
  AbstractNumberingJSON,
10
+ BorderJSON,
11
+ CellPropertiesJSON,
10
12
  FoliDocument,
13
+ MeasureJSON,
11
14
  NumberingInstanceJSON,
12
15
  NumberingLevelJSON,
13
16
  ParagraphPropertiesJSON,
14
17
  StyleJSON,
18
+ TableCondition,
19
+ TablePropertiesJSON,
15
20
  ThemeJSON,
16
21
  } from "./document.js";
17
22
 
@@ -411,6 +416,122 @@ function ordinal(n: number): string {
411
416
  return `${n}${suffix}`;
412
417
  }
413
418
 
419
+ /** A table's effective properties: its style's (the default table style's when it names none), then its own. */
420
+ export type TableFormat = Omit<TablePropertiesJSON, "style" | "ext"> & {
421
+ /** The table style that applies. */
422
+ style: string | null;
423
+ };
424
+
425
+ /** Where a cell is: its row among the table's rows, and its index among the row's cells. */
426
+ export interface CellPlace {
427
+ row: number;
428
+ rows: number;
429
+ cell: number;
430
+ cells: number;
431
+ }
432
+
433
+ type Side = "top" | "bottom" | "left" | "right";
434
+
435
+ /** A cell's effective formatting from the table style's parts that apply to it and its own properties. */
436
+ export interface CellFormat {
437
+ /** The table style that applies. */
438
+ style: string | null;
439
+ /** The table style's parts that apply, in the order they apply (later wins). */
440
+ conditions: TableCondition[];
441
+ /** Fill `RRGGBB`; null for none. */
442
+ shading: string | null;
443
+ /** The cell's own edges before conflicts with its neighbours are resolved (left-to-right text). */
444
+ borders: Partial<Record<Side, BorderJSON>>;
445
+ /** Twips. */
446
+ margins: Record<Side, number>;
447
+ verticalAlign: "top" | "center" | "bottom" | "both";
448
+ }
449
+
450
+ /** A table style's parts for a set of conditions, flattened in the order they apply. */
451
+ interface TableLayer {
452
+ key: string;
453
+ paragraph: ParagraphPropertiesJSON[];
454
+ run: MarkJSON[][];
455
+ cell: CellPropertiesJSON[];
456
+ }
457
+
458
+ const TABLE_KEYS = new Set([
459
+ "width",
460
+ "justification",
461
+ "indent",
462
+ "layout",
463
+ "borders",
464
+ "cellMargins",
465
+ "cellSpacing",
466
+ "shading",
467
+ "look",
468
+ "rowBandSize",
469
+ "columnBandSize",
470
+ ]);
471
+ const PER_SIDE = new Set(["borders", "cellMargins", "look"]);
472
+
473
+ /** Table properties merged in order, later winning (borders and margins side by side). */
474
+ function mergeTable(target: Json, props: Json | undefined | null): void {
475
+ if (!props) return;
476
+ for (const [key, value] of Object.entries(props)) {
477
+ if (value == null || !TABLE_KEYS.has(key)) continue;
478
+ target[key] = PER_SIDE.has(key) ? { ...(target[key] as Json), ...(value as Json) } : value;
479
+ }
480
+ }
481
+
482
+ /** A cell margin in twips: Word measures margins in `dxa` (other types count as none). */
483
+ function twipsOf(measure: MeasureJSON | undefined): number | undefined {
484
+ if (!measure) return undefined;
485
+ return measure.type === "dxa" ? measure.value : 0;
486
+ }
487
+
488
+ /** The last value `pick` gives among `layers` (later layers win). */
489
+ function last<T, V>(layers: readonly T[], pick: (layer: T) => V | undefined | null): V | undefined {
490
+ for (let i = layers.length - 1; i >= 0; i--) {
491
+ const value = pick(layers[i] as T);
492
+ if (value != null) return value;
493
+ }
494
+ return undefined;
495
+ }
496
+
497
+ /**
498
+ * The table style's parts that apply to a cell, in Word's order: the whole table, banded
499
+ * columns, banded rows, first and last column, first and last row, then the corners. The first
500
+ * and last row and column (when `look` turns them on) are left out of banding.
501
+ *
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).
504
+ */
505
+ export function tableConditions(
506
+ look: NonNullable<TablePropertiesJSON["look"]>,
507
+ place: CellPlace,
508
+ rowBand = 1,
509
+ columnBand = 1,
510
+ ): TableCondition[] {
511
+ const out: TableCondition[] = ["wholeTable"];
512
+ const firstRow = !!look.firstRow && place.row === 0;
513
+ const lastRow = !!look.lastRow && place.row === place.rows - 1;
514
+ const firstCol = !!look.firstColumn && place.cell === 0;
515
+ const lastCol = !!look.lastColumn && place.cell === place.cells - 1;
516
+ if (!look.noVBand && !firstCol && !lastCol) {
517
+ const i = place.cell - (look.firstColumn ? 1 : 0);
518
+ out.push(Math.floor(i / columnBand) % 2 === 0 ? "band1Vert" : "band2Vert");
519
+ }
520
+ if (!look.noHBand && !firstRow && !lastRow) {
521
+ const i = place.row - (look.firstRow ? 1 : 0);
522
+ out.push(Math.floor(i / rowBand) % 2 === 0 ? "band1Horz" : "band2Horz");
523
+ }
524
+ if (firstCol) out.push("firstCol");
525
+ if (lastCol) out.push("lastCol");
526
+ if (firstRow) out.push("firstRow");
527
+ if (lastRow) out.push("lastRow");
528
+ if (firstRow && firstCol) out.push("nwCell");
529
+ if (firstRow && lastCol) out.push("neCell");
530
+ if (lastRow && firstCol) out.push("swCell");
531
+ if (lastRow && lastCol) out.push("seCell");
532
+ return out;
533
+ }
534
+
414
535
  type Envelope = Pick<FoliDocument, "defaults" | "styles" | "numbering" | "theme">;
415
536
 
416
537
  interface Level {
@@ -435,14 +556,18 @@ export class Resolver {
435
556
  readonly #characterStyles = new Map<string, MarkJSON[][]>();
436
557
  readonly #instances = new Map<number, NumberingInstanceJSON>();
437
558
  readonly #abstracts = new Map<number, AbstractNumberingJSON>();
559
+ #defaultTableStyle: string | undefined;
560
+ readonly #layers = new Map<string, TableLayer>();
438
561
 
439
562
  constructor(envelope: Envelope) {
440
563
  this.#envelope = envelope;
441
564
  // With duplicate ids, the first wins, as in Word.
442
565
  for (const s of envelope.styles) if (!this.#styles.has(s.id)) this.#styles.set(s.id, s);
443
- // With several default paragraph styles, the last one applies (ECMA-376 17.7.4.17).
444
- for (const s of envelope.styles)
566
+ // With several default styles of a type, the last one applies (ECMA-376 17.7.4.17).
567
+ for (const s of envelope.styles) {
445
568
  if (s.type === "paragraph" && s.isDefault) this.#defaultParagraphStyle = s.id;
569
+ if (s.type === "table" && s.isDefault) this.#defaultTableStyle = s.id;
570
+ }
446
571
  for (const n of envelope.numbering.instances)
447
572
  if (!this.#instances.has(n.id)) this.#instances.set(n.id, n);
448
573
  for (const a of envelope.numbering.abstracts)
@@ -463,16 +588,120 @@ export class Resolver {
463
588
  return out;
464
589
  }
465
590
 
466
- /** A paragraph style's formatting over the defaults, memoized. */
467
- #paragraphStyle(id: string | undefined) {
468
- const key = id ?? "";
591
+ /** A table style and those it is based on (the default table style for a missing one). */
592
+ #tableChain(id: string | null | undefined): StyleJSON[] {
593
+ const chain = id ? this.#chain(id, "table") : [];
594
+ return chain.length ? chain : this.#chain(this.#defaultTableStyle, "table");
595
+ }
596
+
597
+ /** The table style's parts for `conditions`, memoized. */
598
+ #layer(style: string | null, conditions: readonly TableCondition[]): TableLayer {
599
+ // JSON: no two style ids and condition lists give the same key.
600
+ const key = JSON.stringify([style, conditions]);
601
+ const known = this.#layers.get(key);
602
+ if (known) return known;
603
+ const layer: TableLayer = { key, paragraph: [], run: [], cell: [] };
604
+ const chain = this.#tableChain(style);
605
+ for (const condition of conditions) {
606
+ for (const s of chain) {
607
+ const part =
608
+ condition === "wholeTable" ? s : s.conditions?.find((c) => c.type === condition);
609
+ if (part?.paragraph) layer.paragraph.push(part.paragraph);
610
+ if (part?.run) layer.run.push(part.run);
611
+ if (part?.cell) layer.cell.push(part.cell);
612
+ }
613
+ }
614
+ this.#layers.set(key, layer);
615
+ return layer;
616
+ }
617
+
618
+ /** A table's effective properties (`attrs`: the table node's attributes); the caller's to change. */
619
+ table(attrs: Json): TableFormat {
620
+ const chain = this.#tableChain(attrs.style as string | null | undefined);
621
+ const out: Json = {};
622
+ for (const s of chain) mergeTable(out, s.table as Json | undefined);
623
+ mergeTable(out, attrs);
624
+ // A copy: the merged values are the styles' and the node's own objects.
625
+ return structuredClone({
626
+ ...(out as Omit<TableFormat, "style">),
627
+ style: chain.at(-1)?.id ?? null,
628
+ });
629
+ }
630
+
631
+ /**
632
+ * A cell's effective formatting (ECMA-376 17.7.6): the table style's parts that apply where
633
+ * the cell is (`tableConditions`), the row's exceptions over the table's properties, and the
634
+ * cell's own properties (`table`, `row`, `cell`: the nodes' attributes). Pass the result to
635
+ * `paragraph` for the paragraphs in the cell. The result is the caller's to change.
636
+ */
637
+ cell(table: Json, row: Json, cell: Json, place: CellPlace): CellFormat {
638
+ const props = this.table(table) as Json;
639
+ mergeTable(props, row.exceptions as Json | null | undefined);
640
+ const format = props as TableFormat;
641
+ const conditions = tableConditions(
642
+ format.look ?? {},
643
+ place,
644
+ format.rowBandSize,
645
+ format.columnBandSize,
646
+ );
647
+ const layers = [...this.#layer(format.style, conditions).cell, cell as CellPropertiesJSON];
648
+ const fill = last(layers, (l) => l.shading)?.fill ?? format.shading?.fill;
649
+ const tableBorders = format.borders ?? {};
650
+ const edge = (
651
+ side: Side,
652
+ start: "start" | "end" | null,
653
+ inside: BorderJSON | undefined,
654
+ outer: boolean,
655
+ ) =>
656
+ last(layers, (l) => l.borders?.[side] ?? (start ? l.borders?.[start] : undefined)) ??
657
+ (outer ? (tableBorders[side] ?? (start ? tableBorders[start] : undefined)) : inside);
658
+ const borders: Partial<Record<Side, BorderJSON>> = {};
659
+ const sides: [Side, "start" | "end" | null, BorderJSON | undefined, boolean][] = [
660
+ ["top", null, tableBorders.insideH, place.row === 0],
661
+ ["bottom", null, tableBorders.insideH, place.row === place.rows - 1],
662
+ ["left", "start", tableBorders.insideV, place.cell === 0],
663
+ ["right", "end", tableBorders.insideV, place.cell === place.cells - 1],
664
+ ];
665
+ for (const [side, start, inside, outer] of sides) {
666
+ const border = edge(side, start, inside, outer);
667
+ // A copy: the border may be a style's or the node's own object.
668
+ if (border) borders[side] = { ...border };
669
+ }
670
+ const margin = (side: Side, start: "start" | "end" | null) =>
671
+ twipsOf(
672
+ last(layers, (l) => l.margins?.[side] ?? (start ? l.margins?.[start] : undefined)) ??
673
+ format.cellMargins?.[side] ??
674
+ (start ? format.cellMargins?.[start] : undefined),
675
+ ) ?? 0;
676
+ return {
677
+ style: format.style,
678
+ conditions,
679
+ shading: fill === undefined || fill === "auto" ? null : fill.toUpperCase(),
680
+ borders,
681
+ margins: {
682
+ top: margin("top", null),
683
+ bottom: margin("bottom", null),
684
+ left: margin("left", "start"),
685
+ right: margin("right", "end"),
686
+ },
687
+ verticalAlign: last(layers, (l) => l.verticalAlign) ?? "top",
688
+ };
689
+ }
690
+
691
+ /**
692
+ * A paragraph style's formatting over the defaults (and, in a table, the table style's parts
693
+ * for the cell, which come between them as ECMA-376 17.7.2 orders them), memoized.
694
+ *
695
+ * 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).
697
+ */
698
+ #paragraphStyle(id: string | undefined, layer?: TableLayer) {
699
+ const key = JSON.stringify([layer?.key ?? null, id ?? null]);
469
700
  const known = this.#paragraphStyles.get(key);
470
701
  if (known) return known;
471
- const { defaults } = this.#envelope;
472
702
  const paragraph = cloneParagraph(DEFAULT_PARAGRAPH);
473
703
  const run = cloneRun(DEFAULT_RUN);
474
- mergeParagraph(paragraph, defaults.paragraph);
475
- applyDirect(run, defaults.run, this.#envelope.theme);
704
+ this.#base(paragraph, run, layer);
476
705
  // A style that does not exist (or is not a paragraph style) is the default paragraph style.
477
706
  let chain = id === undefined ? [] : this.#chain(id, "paragraph");
478
707
  if (!chain.length) chain = this.#chain(this.#defaultParagraphStyle, "paragraph");
@@ -488,19 +717,34 @@ export class Resolver {
488
717
  return result;
489
718
  }
490
719
 
720
+ /** The document defaults, then a table style's parts for a cell. */
721
+ #base(paragraph: Merging, run: RunFormat | null, layer: TableLayer | undefined): void {
722
+ const { defaults, theme } = this.#envelope;
723
+ mergeParagraph(paragraph, defaults.paragraph);
724
+ if (run) applyDirect(run, defaults.run, theme);
725
+ for (const p of layer?.paragraph ?? []) mergeParagraph(paragraph, p);
726
+ // The table style's run properties are set, as the defaults are (not toggled).
727
+ if (run) for (const r of layer?.run ?? []) applyDirect(run, r, theme);
728
+ }
729
+
491
730
  /**
492
731
  * A paragraph's effective properties, and the formatting of its text before a run's own marks
493
- * (`attrs`: the paragraph node's attributes, as JSON or a live node has them). The results are
494
- * the caller's: changing them changes nothing else.
732
+ * (`attrs`: the paragraph node's attributes, as JSON or a live node has them; `cell`: the
733
+ * format of the table cell it is in, from `cell`). The results are the caller's: changing
734
+ * them changes nothing else.
495
735
  */
496
- paragraph(attrs: Json): { paragraph: ParagraphFormat; run: RunFormat } {
497
- const { paragraph, run } = this.#resolve(attrs);
736
+ paragraph(attrs: Json, cell?: CellFormat): { paragraph: ParagraphFormat; run: RunFormat } {
737
+ const { paragraph, run } = this.#resolve(attrs, cell);
498
738
  return { paragraph, run };
499
739
  }
500
740
 
501
- #resolve(attrs: Json): { paragraph: ParagraphFormat; run: RunFormat; level: Level | undefined } {
741
+ #resolve(
742
+ attrs: Json,
743
+ cell?: CellFormat,
744
+ ): { paragraph: ParagraphFormat; run: RunFormat; level: Level | undefined } {
502
745
  const props = attrs as ParagraphPropertiesJSON;
503
- const base = this.#paragraphStyle(props.style ?? undefined);
746
+ const layer = cell ? this.#layer(cell.style, cell.conditions) : undefined;
747
+ const base = this.#paragraphStyle(props.style ?? undefined, layer);
504
748
  let paragraph = cloneParagraph(base.paragraph);
505
749
  const directNumbering = props.numbering?.id != null;
506
750
  if (props.numbering) mergeParagraph(paragraph, { numbering: props.numbering });
@@ -512,7 +756,7 @@ export class Resolver {
512
756
  } else {
513
757
  // Numbering given by the style: the style's own indents win over the level's.
514
758
  const stacked = cloneParagraph(DEFAULT_PARAGRAPH);
515
- mergeParagraph(stacked, this.#envelope.defaults.paragraph);
759
+ this.#base(stacked, null, layer);
516
760
  mergeParagraph(stacked, level.level.paragraph);
517
761
  for (const style of base.chain) mergeParagraph(stacked, style.paragraph);
518
762
  stacked.style = paragraph.style;
package/src/v3/schema.ts CHANGED
@@ -126,6 +126,11 @@ const border = shape(
126
126
 
127
127
  const shading = shape({ pattern: token, color, fill: color, themeFill: token }, ["pattern"]);
128
128
 
129
+ const nullableAttr = (check: Check): AttributeSpec => ({
130
+ default: null,
131
+ validate: nullable(check),
132
+ });
133
+
129
134
  /** Who made a tracked change or comment, and when (ids are Word's `w:id`; authors may be empty). */
130
135
  const ID = int(0, 2_147_483_647);
131
136
  const revisionFields = { id: ID, author: str(), date: nullable(date) };
@@ -162,6 +167,131 @@ export const checkSection: Check = shape(
162
167
  true,
163
168
  );
164
169
 
170
+ /**
171
+ * A table measure (`w:tblW`, `w:tcW`, `w:tblInd`, cell margins): `value` in twips (`dxa`) or
172
+ * fiftieths of a percent (`pct`, 5000 = 100 %); `auto` and `nil` carry 0.
173
+ */
174
+ const measure = shape({ value: twips, type: oneOf(["auto", "dxa", "pct", "nil"]) }, [
175
+ "value",
176
+ "type",
177
+ ]);
178
+ const sides = (check: Check, extra: readonly string[] = []) =>
179
+ shape(
180
+ Object.fromEntries(
181
+ ["top", "left", "bottom", "right", "start", "end", ...extra].map((side) => [side, check]),
182
+ ),
183
+ );
184
+ /** Word's limit: 63 columns. Files beyond it stay valid up to this bound. */
185
+ const MAX_COLUMNS = 1000;
186
+
187
+ /** Table properties (`w:tblPr`), also a row's exceptions (`w:tblPrEx`) and a table style's. */
188
+ const tableProperties: Record<string, AttributeSpec> = {
189
+ style: nullableAttr(text()),
190
+ width: nullableAttr(measure),
191
+ justification: nullableAttr(oneOf(["left", "center", "right", "start", "end"])),
192
+ indent: nullableAttr(measure),
193
+ layout: nullableAttr(oneOf(["fixed", "autofit"])),
194
+ borders: nullableAttr(sides(border, ["insideH", "insideV"])),
195
+ cellMargins: nullableAttr(sides(measure)),
196
+ cellSpacing: nullableAttr(measure),
197
+ shading: nullableAttr(shading),
198
+ /** `w:tblLook`: which of the table style's conditional formats apply. */
199
+ look: nullableAttr(
200
+ shape({
201
+ firstRow: bool,
202
+ lastRow: bool,
203
+ firstColumn: bool,
204
+ lastColumn: bool,
205
+ noHBand: bool,
206
+ noVBand: bool,
207
+ }),
208
+ ),
209
+ /** Rows and columns per band of the table style's banding (`w:tblStyleRowBandSize`…). */
210
+ rowBandSize: nullableAttr(int(1, MAX_COLUMNS)),
211
+ columnBandSize: nullableAttr(int(1, MAX_COLUMNS)),
212
+ /** The element these properties were read from, verbatim. */
213
+ ext: nullableAttr(xml),
214
+ };
215
+
216
+ /** Row properties (`w:trPr`) as a row's attributes or a table style's. */
217
+ const rowProperties: Record<string, AttributeSpec> = {
218
+ /** In twips; `auto` lets the content decide (Word's default). */
219
+ height: nullableAttr(
220
+ shape({ value: positiveTwips, rule: oneOf(["auto", "exact", "atLeast"]) }, ["value"]),
221
+ ),
222
+ /** The row is never split across pages. */
223
+ cantSplit: nullableAttr(bool),
224
+ /** A header row: repeated at the top of each page the table continues on. */
225
+ header: nullableAttr(bool),
226
+ /** Grid columns left empty before the first cell and after the last, and their widths. */
227
+ gridBefore: nullableAttr(int(1, MAX_COLUMNS)),
228
+ widthBefore: nullableAttr(measure),
229
+ gridAfter: nullableAttr(int(1, MAX_COLUMNS)),
230
+ widthAfter: nullableAttr(measure),
231
+ ext: nullableAttr(xml),
232
+ };
233
+
234
+ /** Cell properties (`w:tcPr`) as a cell's attributes or a table style's. */
235
+ const cellProperties: Record<string, AttributeSpec> = {
236
+ width: nullableAttr(measure),
237
+ /** Grid columns the cell spans (null: one). */
238
+ gridSpan: nullableAttr(int(1, MAX_COLUMNS)),
239
+ /**
240
+ * A vertical merge: `restart` starts one, `continue` is covered by the cell above. Kept as
241
+ * Word writes it (a merged cell is present in every row it covers); layout derives the span.
242
+ */
243
+ vMerge: nullableAttr(oneOf(["restart", "continue"])),
244
+ borders: nullableAttr(sides(border, ["insideH", "insideV", "tl2br", "tr2bl"])),
245
+ shading: nullableAttr(shading),
246
+ margins: nullableAttr(sides(measure)),
247
+ verticalAlign: nullableAttr(oneOf(["top", "center", "bottom", "both"])),
248
+ textDirection: nullableAttr(token),
249
+ noWrap: nullableAttr(bool),
250
+ ext: nullableAttr(xml),
251
+ };
252
+
253
+ const propertiesCheck =
254
+ (specs: Record<string, AttributeSpec>): Check =>
255
+ (v) => {
256
+ if (!isRecord(v)) return "must be an object";
257
+ for (const [key, value] of Object.entries(v)) {
258
+ if (!Object.hasOwn(specs, key)) return `unknown key ${key}`;
259
+ const error =
260
+ value === null
261
+ ? "must not be null (leave it out)"
262
+ : (specs[key] as AttributeSpec).validate?.(value);
263
+ if (error) return `${key} ${error}`;
264
+ }
265
+ return undefined;
266
+ };
267
+
268
+ /** Table, row and cell properties as a table style or a row's exceptions give them. */
269
+ export const checkTableProperties: Check = propertiesCheck(tableProperties);
270
+ export const checkRowProperties: Check = propertiesCheck(rowProperties);
271
+ export const checkCellProperties: Check = propertiesCheck(cellProperties);
272
+
273
+ /** EMU (English Metric Units: 914 400 per inch), as DrawingML measures pictures. */
274
+ const emu = int(0, 2_147_483_647);
275
+ const offset = int(-2_147_483_648, 2_147_483_647);
276
+
277
+ /** Where a floating picture is (`wp:anchor`): null for an inline picture. */
278
+ const checkFloat: Check = shape(
279
+ {
280
+ /** `relativeFrom` (page, margin, column, paragraph, character…) and an offset or alignment. */
281
+ horizontal: shape({ relativeTo: token, offset, align: token }, ["relativeTo"]),
282
+ vertical: shape({ relativeTo: token, offset, align: token }, ["relativeTo"]),
283
+ /** How text goes around it; `behind` and `inFront` are no wrapping. */
284
+ wrap: oneOf(["square", "tight", "through", "topAndBottom", "behind", "inFront"]),
285
+ /** Which sides text goes on (`w:wrapText`). */
286
+ side: oneOf(["bothSides", "left", "right", "largest"]),
287
+ /** Distance from the text, in EMU. */
288
+ distance: shape({ top: emu, bottom: emu, left: emu, right: emu }),
289
+ allowOverlap: bool,
290
+ layoutInCell: bool,
291
+ },
292
+ ["horizontal", "vertical", "wrap"],
293
+ );
294
+
165
295
  /** Marks that describe how text looks: what a style, a paragraph mark or a recorded change holds. */
166
296
  export const RUN_PROPERTY_MARKS = [
167
297
  "characterStyle",
@@ -198,11 +328,6 @@ export const checkRunProperties: Check = (v) => {
198
328
  }
199
329
  };
200
330
 
201
- const nullableAttr = (check: Check): AttributeSpec => ({
202
- default: null,
203
- validate: nullable(check),
204
- });
205
-
206
331
  /**
207
332
  * Paragraph properties (`w:pPr`). The same attributes describe a style's, a numbering level's
208
333
  * and the defaults' paragraph properties.
@@ -337,7 +462,40 @@ export const schema = new Schema({
337
462
  attributes: nullableAttr(attributes),
338
463
  },
339
464
  },
340
- /** Block content Foli does not model yet (tables until Phase 10…), kept verbatim. */
465
+ /**
466
+ * A table (`w:tbl`, schema v4): rows of cells holding blocks. Word's rules beyond the
467
+ * content expressions (no table right after a table, none ending the body or a cell, no
468
+ * section or page break in a cell) are checked by `parseContent`.
469
+ */
470
+ table: {
471
+ group: "block",
472
+ content: "tableRow+",
473
+ attrs: {
474
+ ...tableProperties,
475
+ /** The grid's column widths in twips (`w:tblGrid`). */
476
+ grid: { default: [], validate: listOf(positiveTwips, MAX_COLUMNS) },
477
+ /** The `w:tblGrid` the grid was read from, verbatim. */
478
+ gridExt: nullableAttr(xml),
479
+ },
480
+ },
481
+ tableRow: {
482
+ content: "tableCell+",
483
+ attrs: {
484
+ ...rowProperties,
485
+ /** The row inserted or deleted as a tracked change (`w:trPr/w:ins`, `w:del`). */
486
+ revision: nullableAttr(shape({ insertion: revision, deletion: revision })),
487
+ /** The row's table property exceptions (`w:tblPrEx`). */
488
+ exceptions: nullableAttr(checkTableProperties),
489
+ /** `w:tr`'s own unknown attributes (`w14:paraId`, revision save ids…). */
490
+ attributes: nullableAttr(attributes),
491
+ },
492
+ },
493
+ tableCell: {
494
+ // As Word requires, a cell ends with a paragraph.
495
+ content: "block* paragraph",
496
+ attrs: cellProperties,
497
+ },
498
+ /** Block content Foli does not model yet (a table inside a content control…), kept verbatim. */
341
499
  opaqueBlock: {
342
500
  group: "block",
343
501
  attrs: { xml: { validate: xml }, label: nullableAttr(text()) },
@@ -383,7 +541,29 @@ export const schema = new Schema({
383
541
  inline: true,
384
542
  attrs: { id: { validate: ID }, ...markerAttributes },
385
543
  },
386
- /** Inline content Foli does not model yet (fields, drawings, symbols…), kept verbatim. */
544
+ /**
545
+ * A picture (`w:drawing` holding `pic:pic`, schema v4), inline or floating. Its bytes are
546
+ * the envelope's `resources[resource]`.
547
+ */
548
+ picture: {
549
+ group: "inline",
550
+ inline: true,
551
+ attrs: {
552
+ resource: { validate: text() },
553
+ /** In EMU. */
554
+ width: { validate: emu },
555
+ height: { validate: emu },
556
+ /** Alt text (`wp:docPr/@descr`): allowed to be missing, as Word allows it. */
557
+ alt: nullableAttr(str(65_535)),
558
+ title: nullableAttr(str(65_535)),
559
+ /** Marked decorative: no alt text needed. */
560
+ decorative: nullableAttr(bool),
561
+ float: nullableAttr(checkFloat),
562
+ /** The `w:drawing` it was read from, verbatim (cropping, effects…). */
563
+ ext: nullableAttr(xml),
564
+ },
565
+ },
566
+ /** Inline content Foli does not model yet (fields, charts, shapes, symbols…), kept verbatim. */
387
567
  opaqueInline: {
388
568
  group: "inline",
389
569
  inline: true,