@stll/folio-core 0.74.0 → 0.75.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 (113) hide show
  1. package/dist/ai-edits/clean-text.d.ts +4 -1
  2. package/dist/ai-edits/clean-text.js +21 -7
  3. package/dist/ai-edits/headless.d.ts +5 -2
  4. package/dist/ai-edits/headless.js +18 -9
  5. package/dist/ai-edits/note-references.d.ts +1 -1
  6. package/dist/ai-edits/note-references.js +1 -1
  7. package/dist/ai-edits/pending-suggestions.d.ts +9 -7
  8. package/dist/ai-edits/pending-suggestions.js +134 -88
  9. package/dist/ai-edits/pendingJoin.d.ts +5 -1
  10. package/dist/ai-edits/pendingJoin.js +6 -2
  11. package/dist/ai-edits/retired-comment-receipts.d.ts +2 -2
  12. package/dist/ai-edits/retired-comment-receipts.js +3 -18
  13. package/dist/ai-edits/tracked-batch-fidelity.d.ts +6 -10
  14. package/dist/ai-edits/tracked-batch-fidelity.js +3 -182
  15. package/dist/canonical/canonicalBatchReview.d.ts +4 -1
  16. package/dist/canonical/canonicalBatchReview.js +32 -14
  17. package/dist/canonical/canonicalComments.d.ts +6 -2
  18. package/dist/canonical/canonicalComments.js +8 -4
  19. package/dist/canonical/canonicalPublicOperations.js +29 -9
  20. package/dist/canonical/canonicalRefusalGrounds.d.ts +4 -0
  21. package/dist/canonical/canonicalRefusalGrounds.js +56 -0
  22. package/dist/canonical/canonicalSession.d.ts +12 -6
  23. package/dist/canonical/canonicalSession.js +116 -121
  24. package/dist/canonical/canonicalTrackedBatchFidelity.js +3 -3
  25. package/dist/compare/inline-atoms.d.ts +35 -41
  26. package/dist/compare/inline-atoms.js +2 -465
  27. package/dist/compare/section-boundary-properties.d.ts +3 -30
  28. package/dist/compare/section-boundary-properties.js +4 -72
  29. package/dist/controller/canonicalClipboard.js +43 -42
  30. package/dist/controller/canonicalComposition.d.ts +1 -1
  31. package/dist/controller/canonicalComposition.js +5 -5
  32. package/dist/controller/canonicalInput.d.ts +4 -2
  33. package/dist/controller/canonicalInput.js +33 -16
  34. package/dist/controller/canonicalStoryEditor.d.ts +2 -3
  35. package/dist/controller/canonicalStoryEditor.js +43 -25
  36. package/dist/controller/canonicalStructure.d.ts +19 -2
  37. package/dist/controller/canonicalStructure.js +139 -42
  38. package/dist/controller/deferredDisplayListPainter.d.ts +8 -0
  39. package/dist/controller/deferredDisplayListPainter.js +34 -0
  40. package/dist/controller/folioEditor.js +4 -2
  41. package/dist/controller/headerFooterEditorManager.js +3 -17
  42. package/dist/controller/hiddenEditorApi.d.ts +24 -3
  43. package/dist/controller/hiddenEditorApi.js +2 -0
  44. package/dist/controller/hiddenEditorManager.js +132 -189
  45. package/dist/controller/layoutPipeline.d.ts +4 -86
  46. package/dist/controller/layoutPipeline.js +8 -727
  47. package/dist/controller/layoutPipelineExecution.d.ts +94 -0
  48. package/dist/controller/layoutPipelineExecution.js +730 -0
  49. package/dist/controller/noteEditorManager.js +3 -16
  50. package/dist/docx/blockContentParser.d.ts +1 -3
  51. package/dist/docx/blockContentParser.js +3 -10
  52. package/dist/docx/canonicalSave.d.ts +4 -3
  53. package/dist/docx/canonicalSave.js +4 -3
  54. package/dist/docx/listMarkerComputation.d.ts +24 -17
  55. package/dist/docx/listMarkerComputation.js +31 -60
  56. package/dist/docx/listModelNormalization.js +8 -15
  57. package/dist/docx/rezip.d.ts +16 -3
  58. package/dist/docx/rezip.js +35 -9
  59. package/dist/docx/selectiveSave.js +13 -5
  60. package/dist/docx/server/templatePlan/apply.js +38 -3
  61. package/dist/docx/server/templatePlan/blocks.d.ts +16 -1
  62. package/dist/docx/server/templatePlan/blocks.js +93 -7
  63. package/dist/docx/server/templatePlan/builders.d.ts +37 -2
  64. package/dist/docx/server/templatePlan/builders.js +196 -5
  65. package/dist/docx/server/templatePlan/emit.d.ts +2 -0
  66. package/dist/docx/server/templatePlan/emit.js +2 -0
  67. package/dist/docx/server/templatePlan/inspect.js +19 -52
  68. package/dist/docx/server/templatePlan/labels.d.ts +7 -2
  69. package/dist/docx/server/templatePlan/labels.js +104 -22
  70. package/dist/docx/server/templatePlan/plan.d.ts +13 -1
  71. package/dist/docx/server/templatePlan/plan.js +22 -7
  72. package/dist/docx/server/templatePlan/planShape.js +31 -2
  73. package/dist/docx/server/templatePlan/story.d.ts +8 -0
  74. package/dist/docx/server/templatePlan/story.js +11 -1
  75. package/dist/docx/server/templatePlan/types.d.ts +138 -16
  76. package/dist/docx/server/templatePlan/verify.js +50 -9
  77. package/dist/i18n/messages/ar.gen.js +1 -0
  78. package/dist/i18n/messages/catalogs.gen.d.ts +17 -0
  79. package/dist/i18n/messages/catalogs.gen.js +17 -0
  80. package/dist/i18n/messages/cs.gen.js +1 -0
  81. package/dist/i18n/messages/de.gen.js +1 -0
  82. package/dist/i18n/messages/en.gen.js +1 -0
  83. package/dist/i18n/messages/es.gen.js +1 -0
  84. package/dist/i18n/messages/et.gen.js +1 -0
  85. package/dist/i18n/messages/fr.gen.js +1 -0
  86. package/dist/i18n/messages/he.gen.js +1 -0
  87. package/dist/i18n/messages/hi.gen.js +1 -0
  88. package/dist/i18n/messages/hu.gen.js +1 -0
  89. package/dist/i18n/messages/lt.gen.js +1 -0
  90. package/dist/i18n/messages/lv.gen.js +1 -0
  91. package/dist/i18n/messages/messages.gen.d.ts +1 -0
  92. package/dist/i18n/messages/pl.gen.js +1 -0
  93. package/dist/i18n/messages/pt-BR.gen.js +1 -0
  94. package/dist/i18n/messages/sk.gen.js +1 -0
  95. package/dist/i18n/messages/tr.gen.js +1 -0
  96. package/dist/i18n/messages/zh-CN.gen.js +1 -0
  97. package/dist/layout-bridge/convert/toFlowBlocks.js +0 -12
  98. package/dist/layout-bridge/convert/topLevelConversion.js +1 -10
  99. package/dist/prosemirror/extensions/features/ImagePasteExtension.js +1 -1
  100. package/dist/prosemirror/listMarker.d.ts +1 -6
  101. package/dist/prosemirror/listMarker.js +4 -56
  102. package/dist/server.d.ts +2 -2
  103. package/dist/types/canonicalCapabilities.d.ts +40 -45
  104. package/dist/types/canonicalCapabilities.js +51 -43
  105. package/dist/types/canonicalComments.d.ts +2 -2
  106. package/dist/types/canonicalSections.d.ts +2 -2
  107. package/dist/utils/clipboard.d.ts +2 -28
  108. package/dist/utils/clipboard.js +1 -96
  109. package/dist/utils/clipboardFiles.d.ts +27 -0
  110. package/dist/utils/clipboardFiles.js +98 -0
  111. package/dist/utils/rulerControl.d.ts +1 -0
  112. package/dist/utils/rulerControl.js +2 -1
  113. package/package.json +2 -2
@@ -1,26 +1,15 @@
1
1
  import { RELATIONSHIP_TYPES } from "../../relsParser.js";
2
2
  import { parseSectionProperties } from "../../sectionParser.js";
3
- import { analyzeDocument, styleOutlineLevel } from "./blocks.js";
3
+ import { analyzeDocument, statedAlignments, storySections, styleAlignment, styleOutlineLevel } from "./blocks.js";
4
4
  import { styleNumbering } from "./labels.js";
5
5
  import { guarded, readPartText } from "./package.js";
6
6
  import { createStoryState, endStory, readParagraph, walkBlocks } from "./story.js";
7
7
  import { TemplatePlanError } from "./types.js";
8
- import { integerOrNull, isW, readRawPart, twipsOrNull, wAttr, wChild, wChildVal, wChildren, walkElements } from "./xml.js";
8
+ import { integerOrNull, isW, readRawPart, twipsOrNull, wAttr, wChild, wChildren, walkElements } from "./xml.js";
9
9
  import { Result } from "better-result";
10
10
  // src/docx/server/templatePlan/inspect.ts
11
11
  /** A template's inventory: what a plan may name when it places blocks onto it. */
12
12
  const DEFAULT_LEVEL_START = 1;
13
- /** The `w:jc` each style of the styles part states itself, by style id. */
14
- const statedAlignments = ({ stylesPath, stylesXml }) => {
15
- const alignments = /* @__PURE__ */ new Map();
16
- const part = stylesPath === null || stylesXml === null ? null : readRawPart(stylesPath, stylesXml);
17
- for (const style of wChildren(part?.root, "style")) {
18
- const styleId = wAttr(style, "styleId");
19
- const alignment = wChildVal(wChild(style, "pPr"), "jc");
20
- if (styleId !== null && alignment !== null) alignments.set(styleId, alignment);
21
- }
22
- return alignments;
23
- };
24
13
  /** The indent each level of the numbering part states, by definition and level. */
25
14
  const statedIndents = ({ numberingPath, numberingXml }) => {
26
15
  const indents = /* @__PURE__ */ new Map();
@@ -43,19 +32,7 @@ const NO_INDENT = {
43
32
  };
44
33
  const inspectStyles = (analyzed) => {
45
34
  const { styles, numbering } = analyzed;
46
- const stated = statedAlignments(analyzed);
47
- /** The alignment of the nearest style in the `basedOn` chain that states one. */
48
- const alignmentOf = (styleId) => {
49
- const seen = /* @__PURE__ */ new Set();
50
- let cursor = styleId;
51
- while (cursor !== void 0 && !seen.has(cursor)) {
52
- seen.add(cursor);
53
- const alignment = stated.get(cursor);
54
- if (alignment !== void 0) return alignment;
55
- cursor = styles.get(cursor)?.basedOn;
56
- }
57
- return null;
58
- };
35
+ const stated = statedAlignments(analyzed.stylesPath, analyzed.stylesXml);
59
36
  return [...styles.values()].map((style) => {
60
37
  const bound = styleNumbering(style.styleId, styles, numbering);
61
38
  return {
@@ -68,7 +45,7 @@ const inspectStyles = (analyzed) => {
68
45
  ilvl: bound.ilvl ?? 0
69
46
  } : null,
70
47
  outlineLvl: styleOutlineLevel(style),
71
- alignment: alignmentOf(style.styleId),
48
+ alignment: styleAlignment(style.styleId, styles, stated),
72
49
  isDefault: style.default === true
73
50
  };
74
51
  });
@@ -99,35 +76,25 @@ const inspectNumbering = (analyzed) => {
99
76
  }))
100
77
  };
101
78
  };
102
- const inspectSections = ({ story, pkg }) => story.sections.map((sectPr, index) => {
103
- const properties = parseSectionProperties(sectPr);
79
+ const inspectSections = ({ story, pkg }) => {
104
80
  const partOf = (rId) => {
105
81
  const relationship = pkg.documentRelationships.get(rId);
106
82
  return relationship === void 0 ? null : pkg.resolveDocumentTarget(relationship.target);
107
83
  };
108
- return {
109
- index,
110
- orientation: properties.orientation ?? "portrait",
111
- size: {
112
- width: properties.pageWidth ?? null,
113
- height: properties.pageHeight ?? null
114
- },
115
- margins: {
116
- top: properties.marginTop ?? null,
117
- right: properties.marginRight ?? null,
118
- bottom: properties.marginBottom ?? null,
119
- left: properties.marginLeft ?? null
120
- },
121
- headers: (properties.headerReferences ?? []).map(({ type, rId }) => ({
122
- type,
123
- part: partOf(rId)
124
- })),
125
- footers: (properties.footerReferences ?? []).map(({ type, rId }) => ({
126
- type,
127
- part: partOf(rId)
128
- }))
129
- };
130
- });
84
+ return storySections(story).map((section) => {
85
+ const properties = parseSectionProperties(story.sections[section.index] ?? null);
86
+ return Object.assign(section, {
87
+ headers: (properties.headerReferences ?? []).map(({ type, rId }) => ({
88
+ type,
89
+ part: partOf(rId)
90
+ })),
91
+ footers: (properties.footerReferences ?? []).map(({ type, rId }) => ({
92
+ type,
93
+ part: partOf(rId)
94
+ }))
95
+ });
96
+ });
97
+ };
131
98
  const fieldOf = (part, { instruction, kind, result }) => ({
132
99
  part,
133
100
  instruction: instruction.trim(),
@@ -15,7 +15,8 @@ export type ParagraphLabel = {
15
15
  /**
16
16
  * The label and what its list puts after it, when the label can stand as
17
17
  * text: it reads the same wherever the file is opened. Null for a bullet,
18
- * whose glyph belongs to a font, and for a number a language spells.
18
+ * whose glyph belongs to a font, for a number a language spells out, and
19
+ * for an ordinal in a language whose way of writing it is not known.
19
20
  */
20
21
  asText: {
21
22
  label: string;
@@ -32,6 +33,8 @@ export type LabelCounter = {
32
33
  next: (paragraph: {
33
34
  styleId: string | null;
34
35
  numPr: ParagraphNumberingOverride | undefined;
36
+ /** The language the paragraph mark states itself, or null. */
37
+ language?: string | null;
35
38
  }) => ParagraphLabel;
36
39
  };
37
40
  type LabelCounterOptions = {
@@ -39,7 +42,9 @@ type LabelCounterOptions = {
39
42
  styles: StyleMap;
40
43
  /** The style a paragraph without `w:pStyle` takes. */
41
44
  defaultStyleId: string | null;
45
+ /** The language the document defaults give every run. */
46
+ defaultLanguage?: string | null;
42
47
  };
43
48
  /** A counter over one story; call `next` for every paragraph in document order. */
44
- export declare const createLabelCounter: ({ numbering, styles, defaultStyleId }: LabelCounterOptions) => LabelCounter;
49
+ export declare const createLabelCounter: ({ numbering, styles, defaultStyleId, defaultLanguage }: LabelCounterOptions) => LabelCounter;
45
50
  export {};
@@ -25,11 +25,11 @@ const PLAIN_FORMATS = /* @__PURE__ */ new Set([
25
25
  "lowerLetter"
26
26
  ]);
27
27
  const LEVEL_PLACEHOLDER = /%([1-9])/gu;
28
- const labelAsText = ({ label, template, levelFormats, suffix }) => {
28
+ const labelAsText = ({ label, template, levelFormats, suffix, ordinalKnown }) => {
29
29
  if (label.trim() === "") return null;
30
30
  for (const [, digit] of template.matchAll(LEVEL_PLACEHOLDER)) {
31
31
  const format = levelFormats?.[Number(digit) - 1];
32
- if (format === void 0 || !PLAIN_FORMATS.has(format)) return null;
32
+ if (!(format !== void 0 && (PLAIN_FORMATS.has(format) || format === "ordinal" && ordinalKnown))) return null;
33
33
  }
34
34
  return {
35
35
  label,
@@ -62,17 +62,69 @@ const styleNumbering = (styleId, styles, numbering) => {
62
62
  return stated;
63
63
  };
64
64
  const stripTrailingPeriods = (value) => value.replace(/\.+$/u, "");
65
- /** Drop the literal runs of a level text that hold a letter; keep delimiters. */
66
- const numberOnlyLabel = ({ template, counters, levelFormats, forceDecimal }) => {
67
- const { value, components } = resolveListTemplateWithComponents({
65
+ /**
66
+ * The `ordinal` format by the language of the paragraph mark, as the
67
+ * reference consumer prints it: Czech and German write the number with a
68
+ * period, French `1er` and `2e`, English `1st`. A language not listed here
69
+ * has no entry: its ordinals are not known to be any of these.
70
+ */
71
+ const ORDINALS = {
72
+ cs: (value) => `${String(value)}.`,
73
+ de: (value) => `${String(value)}.`,
74
+ fr: (value) => value === 1 ? "1er" : `${String(value)}e`
75
+ };
76
+ const primaryLanguage = (language) => language === null ? null : language.split(/[-_]/u).at(0)?.toLowerCase() ?? null;
77
+ /** A level text over its counters, ordinals written by the language. */
78
+ const renderLabel = ({ template, counters, levelFormats, forceDecimal, language }) => {
79
+ const rendered = resolveListTemplateWithComponents({
68
80
  template,
69
81
  counters,
70
82
  levelFormats,
71
83
  forceDecimal
72
84
  });
85
+ const isOrdinal = (level) => !forceDecimal && levelFormats?.[level] === "ordinal";
86
+ const hasOrdinal = rendered.components.some(({ level }) => isOrdinal(level));
87
+ const primary = primaryLanguage(language);
88
+ const ordinal = primary === null ? void 0 : ORDINALS[primary];
89
+ if (!hasOrdinal || ordinal === void 0) return {
90
+ ...rendered,
91
+ byLanguage: hasOrdinal,
92
+ known: !hasOrdinal || primary === "en"
93
+ };
94
+ let value = "";
95
+ let cursor = 0;
96
+ const components = rendered.components.map((component) => {
97
+ const { level, start, end } = component;
98
+ value += rendered.value.slice(cursor, start);
99
+ cursor = end;
100
+ const written = isOrdinal(level) ? ordinal(counters[level] ?? 0) : rendered.value.slice(start, end);
101
+ const moved = {
102
+ ...component,
103
+ start: value.length
104
+ };
105
+ value += written;
106
+ return {
107
+ ...moved,
108
+ end: value.length
109
+ };
110
+ });
111
+ value += rendered.value.slice(cursor);
112
+ return {
113
+ value,
114
+ components,
115
+ byLanguage: true,
116
+ known: true
117
+ };
118
+ };
119
+ /**
120
+ * Drop the literal runs of a level text that hold a letter. Of the others
121
+ * a `\t` field keeps the delimiters and drops the blanks: `Part %1 -` gives
122
+ * `B-`.
123
+ */
124
+ const numberOnlyLabel = ({ value, components }) => {
73
125
  let out = "";
74
126
  let cursor = 0;
75
- const literal = (text) => /\p{L}/u.test(text) ? "" : text;
127
+ const literal = (text) => /\p{L}/u.test(text) ? "" : text.replaceAll(/\s+/gu, "");
76
128
  for (const { start, end } of components) {
77
129
  out += literal(value.slice(cursor, start)) + value.slice(start, end);
78
130
  cursor = end;
@@ -80,20 +132,47 @@ const numberOnlyLabel = ({ template, counters, levelFormats, forceDecimal }) =>
80
132
  out += literal(value.slice(cursor));
81
133
  return stripTrailingPeriods(out.trim());
82
134
  };
135
+ /**
136
+ * The language each style gives a paragraph mark: its own, or the one of
137
+ * the nearest style it is based on. Resolved once per style, so a long
138
+ * `basedOn` chain is walked once however many paragraphs use it.
139
+ */
140
+ const createStyleLanguages = (styles) => {
141
+ const resolved = /* @__PURE__ */ new Map();
142
+ return (styleId) => {
143
+ if (styleId === null) return null;
144
+ const walked = /* @__PURE__ */ new Set();
145
+ let language = null;
146
+ let cursor = styleId;
147
+ while (cursor !== void 0 && !walked.has(cursor)) {
148
+ const known = resolved.get(cursor);
149
+ if (known !== void 0) {
150
+ language = known;
151
+ break;
152
+ }
153
+ walked.add(cursor);
154
+ const style = styles.get(cursor);
155
+ const stated = style?.rPr?.language?.val;
156
+ if (stated !== void 0) {
157
+ language = stated;
158
+ break;
159
+ }
160
+ cursor = style?.basedOn;
161
+ }
162
+ for (const id of walked) resolved.set(id, language);
163
+ return language;
164
+ };
165
+ };
83
166
  /** A counter over one story; call `next` for every paragraph in document order. */
84
- const createLabelCounter = ({ numbering, styles, defaultStyleId }) => {
167
+ const createLabelCounter = ({ numbering, styles, defaultStyleId, defaultLanguage = null }) => {
85
168
  const counters = {
86
169
  numbering,
87
170
  listCounters: /* @__PURE__ */ new Map(),
88
171
  abstractCounters: /* @__PURE__ */ new Map(),
89
- restartedNumIds: /* @__PURE__ */ new Set(),
90
- previousList: {
91
- abstractNumId: null,
92
- fromStyle: false,
93
- numId: null
94
- }
172
+ startedLevels: /* @__PURE__ */ new Set()
95
173
  };
96
- return { next: ({ styleId, numPr }) => {
174
+ const styleLanguage = createStyleLanguages(styles);
175
+ return { next: ({ styleId, numPr, language = null }) => {
97
176
  const fromStyle = styleNumbering(styleId ?? defaultStyleId, styles, numbering);
98
177
  const inherits = fromStyle !== void 0 && (numPr === void 0 || numPr.kind === "levelOnly");
99
178
  const effective = inherits ? mergeParagraphNumbering(fromStyle, numPr) : numPr;
@@ -116,7 +195,14 @@ const createLabelCounter = ({ numbering, styles, defaultStyleId }) => {
116
195
  const advance = computeListMarker(paragraph, counters);
117
196
  if (advance === null || listRendering === null || numbering === null || resolved.kind !== "reference") return NO_LABEL;
118
197
  const abstractNumId = numbering.getAbstractNumId(resolved.numId);
119
- const label = listRendering.marker;
198
+ const rendered = renderLabel({
199
+ template,
200
+ counters: advance.counters,
201
+ levelFormats: listRendering.levelNumFmts,
202
+ forceDecimal: listRendering.isLegal === true,
203
+ language: language ?? styleLanguage(styleId ?? defaultStyleId) ?? defaultLanguage
204
+ });
205
+ const label = rendered.byLanguage && rendered.known ? rendered.value : listRendering.marker;
120
206
  const numberingInfo = abstractNumId === null ? null : {
121
207
  numId: resolved.numId,
122
208
  ilvl: resolved.ilvl,
@@ -140,15 +226,11 @@ const createLabelCounter = ({ numbering, styles, defaultStyleId }) => {
140
226
  label,
141
227
  template,
142
228
  levelFormats: listRendering.levelNumFmts,
143
- suffix: listRendering.markerSuffix
229
+ suffix: listRendering.markerSuffix,
230
+ ordinalKnown: rendered.known
144
231
  }),
145
232
  paragraphNumber: stripTrailingPeriods(label.trim()),
146
- numberOnly: numberOnlyLabel({
147
- template,
148
- counters: advance.counters,
149
- levelFormats: listRendering.levelNumFmts,
150
- forceDecimal: listRendering.isLegal === true
151
- })
233
+ numberOnly: numberOnlyLabel(rendered)
152
234
  };
153
235
  } };
154
236
  };
@@ -9,7 +9,7 @@ import { AnalyzedBlock, AnalyzedDocument } from "./blocks.js";
9
9
  import { BookmarkWrap } from "./builders.js";
10
10
  import { StoryOrigin } from "./resources.js";
11
11
  import { AtomKind, AtomLink, InlineAtom, ParagraphRead, StoryField } from "./story.js";
12
- import { TemplatePlan, TemplatePlanError, TemplatePlanOmitReason, TemplatePlanReference } from "./types.js";
12
+ import { TemplatePlan, TemplatePlanError, TemplatePlanOmitReason, TemplatePlanReference, TemplatePlanSection } from "./types.js";
13
13
  import { Result } from "better-result";
14
14
  export type ExpectedPiece = {
15
15
  kind: AtomKind;
@@ -67,10 +67,22 @@ export type ResolvedParagraph = {
67
67
  signatures: string[];
68
68
  inlineObjects: number;
69
69
  placement: "body" | "nested" | "slot";
70
+ /** Whether the paragraph starts on a new page. */
71
+ pageBreakBefore: boolean;
72
+ /** The section the paragraph is the last of, or null. */
73
+ endsSection: TemplatePlanSection | null;
70
74
  };
71
75
  export type ResolvedItem = {
72
76
  kind: "template";
73
77
  block: AnalyzedBlock;
78
+ } |
79
+ /**
80
+ * An empty paragraph the writer adds, in no plan: between two tables that
81
+ * would otherwise stand next to each other and read as one, and after a
82
+ * table that would end the body.
83
+ */
84
+ {
85
+ kind: "separator";
74
86
  } | {
75
87
  kind: "paragraph";
76
88
  paragraph: ResolvedParagraph;
@@ -6,7 +6,7 @@ import { emphasisDeviation, emphasisSignature, paragraphBaseline, readDirectEmph
6
6
  import { styleNumbering } from "./labels.js";
7
7
  import { PLAN_HIGHLIGHT_COLORS, planShapeIssue } from "./planShape.js";
8
8
  import { TemplatePlanError } from "./types.js";
9
- import { isW, maxOf, wAttr, wChildVal, walkElements } from "./xml.js";
9
+ import { isW, maxOf, wAttr, wChild, wChildVal, walkElements } from "./xml.js";
10
10
  import { Result } from "better-result";
11
11
  // src/docx/server/templatePlan/plan.ts
12
12
  /**
@@ -300,6 +300,15 @@ const piecesContent = (pieces) => {
300
300
  signatures
301
301
  };
302
302
  };
303
+ const isTableItem = (item) => item.kind === "table" || item.kind === "template" && item.block.block.kind === "table";
304
+ /** Puts a separator between two neighbouring tables and after a last one. */
305
+ const partTables = (items) => {
306
+ for (let index = items.length - 1; index >= 0; index -= 1) {
307
+ const item = items[index];
308
+ const next = items[index + 1];
309
+ if (item !== void 0 && isTableItem(item) && (next === void 0 || isTableItem(next))) items.splice(index + 1, 0, { kind: "separator" });
310
+ }
311
+ };
303
312
  const plainPiece = (kind, text) => ({
304
313
  kind,
305
314
  text,
@@ -452,7 +461,7 @@ const resolvePlan = (source, template, plan) => {
452
461
  placed.add(id);
453
462
  return Result.ok(void 0);
454
463
  };
455
- const resolveParagraph = ({ parts, separators, styleId, numbering, placement, ordinal }) => {
464
+ const resolveParagraph = ({ parts, separators, styleId, numbering, placement, ordinal, pageBreakBefore = false, endsSection }) => {
456
465
  const first = parts.at(0);
457
466
  if (first === void 0) return invalid("A plan item names no source block.");
458
467
  const firstId = first.block.block.id;
@@ -543,7 +552,9 @@ const resolvePlan = (source, template, plan) => {
543
552
  segments,
544
553
  ...piecesContent(pieces),
545
554
  inlineObjects: pieces.filter(({ kind }) => kind === "object").length,
546
- placement
555
+ placement,
556
+ pageBreakBefore,
557
+ endsSection: endsSection ?? null
547
558
  };
548
559
  for (const { block } of resolvedParts) byBlockId.set(block.block.id, paragraph);
549
560
  return Result.ok(paragraph);
@@ -559,7 +570,7 @@ const resolvePlan = (source, template, plan) => {
559
570
  };
560
571
  const resolveTable = (block, item, tableOrdinal) => {
561
572
  const { id } = block.block;
562
- if (item.mergeNext !== void 0 || item.stripLabel !== void 0 || item.labelAsText !== void 0 || item.numbering !== void 0) return invalid(`Table ${id} takes a style and nested placements only.`);
573
+ if (item.mergeNext !== void 0 || item.stripLabel !== void 0 || item.labelAsText !== void 0 || item.pageBreakBefore !== void 0 || item.endsSection !== void 0 || item.numbering !== void 0) return invalid(`Table ${id} takes a style and nested placements only.`);
563
574
  if (item.styleId !== void 0 && template.styles.get(item.styleId)?.type !== "table") return Result.err(refuse({
564
575
  code: "style-unknown",
565
576
  message: `The template has no table style ${item.styleId}.`,
@@ -673,9 +684,9 @@ const resolvePlan = (source, template, plan) => {
673
684
  message: `Block ${next.blockId} does not have the hash the plan pins.`,
674
685
  blockId: next.blockId
675
686
  }));
676
- if (next.styleId !== void 0 || next.numbering !== void 0 || next.cellStyleId !== void 0 || next.nested !== void 0) return Result.err(refuse({
687
+ if (next.styleId !== void 0 || next.numbering !== void 0 || next.cellStyleId !== void 0 || next.nested !== void 0 || next.pageBreakBefore !== void 0 || next.endsSection !== void 0) return Result.err(refuse({
677
688
  code: "merge-invalid",
678
- message: `Block ${next.blockId} joins the paragraph before it and cannot carry a style or list of its own.`,
689
+ message: `Block ${next.blockId} joins the paragraph before it and cannot carry a style, a list, a page start or a section end of its own.`,
679
690
  blockId: next.blockId
680
691
  }));
681
692
  separators.push(merge);
@@ -693,7 +704,9 @@ const resolvePlan = (source, template, plan) => {
693
704
  styleId: item.styleId,
694
705
  numbering: item.numbering,
695
706
  placement: "body",
696
- ordinal
707
+ ordinal,
708
+ pageBreakBefore: item.pageBreakBefore === true,
709
+ endsSection: item.endsSection
697
710
  });
698
711
  if (Result.isError(paragraph)) return paragraph;
699
712
  items.push({
@@ -756,6 +769,8 @@ const resolvePlan = (source, template, plan) => {
756
769
  }));
757
770
  nestedSlots.push(slot);
758
771
  }
772
+ partTables(items);
773
+ if ((plan.lastSection !== void 0 || items.some((item) => item.kind === "paragraph" && item.paragraph.endsSection !== null)) && wChild(template.body, "sectPr") === null) return invalid("The template has no last section to build the plan's sections from.");
759
774
  const keptPosition = /* @__PURE__ */ new Map();
760
775
  for (const [position, item] of items.entries()) if (item.kind === "template") keptPosition.set(item.block.block.id, position);
761
776
  const templateOrder = template.story.topLevel.map(({ block }) => block.id);
@@ -64,6 +64,29 @@ const numberingIssue = (value, where) => {
64
64
  if (group !== void 0 && !(isString(group) && group !== "")) return `${where} names a malformed list group.`;
65
65
  return null;
66
66
  };
67
+ const SECTION_STARTS = /* @__PURE__ */ new Set([
68
+ "nextPage",
69
+ "evenPage",
70
+ "oddPage"
71
+ ]);
72
+ const ORIENTATIONS = /* @__PURE__ */ new Set(["portrait", "landscape"]);
73
+ const isTwips = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
74
+ /** Why `section` is not a section of a plan, or null when it is one. */
75
+ const sectionIssue = (section, where) => {
76
+ if (section === void 0) return null;
77
+ if (!isObject(section)) return `${where} describes a malformed section.`;
78
+ const { page, start } = section;
79
+ if (start !== void 0 && !(isString(start) && SECTION_STARTS.has(start))) return `${where} names an unknown section start.`;
80
+ if (page === void 0) return null;
81
+ if (!isObject(page) || !(isString(page["orientation"]) && ORIENTATIONS.has(page["orientation"])) || !isTwips(page["width"]) || !isTwips(page["height"]) || page["width"] === 0 || page["height"] === 0) return `${where} describes a malformed page.`;
82
+ const margins = page["margins"];
83
+ return margins === void 0 || isObject(margins) && [
84
+ "top",
85
+ "right",
86
+ "bottom",
87
+ "left"
88
+ ].every((side) => isTwips(margins[side])) ? null : `${where} describes malformed page margins.`;
89
+ };
67
90
  const sourceItemIssue = (item, where) => {
68
91
  if (!isString(item["blockId"]) || !isString(item["hash"])) return `${where} names no source block and hash.`;
69
92
  for (const key of [
@@ -71,9 +94,11 @@ const sourceItemIssue = (item, where) => {
71
94
  "cellStyleId",
72
95
  "stripLabel"
73
96
  ]) if (!isOptionalString(item[key])) return `${where} carries a malformed ${key}.`;
74
- if (!isOptionalBoolean(item["labelAsText"])) return `${where} carries a malformed labelAsText.`;
97
+ for (const key of ["labelAsText", "pageBreakBefore"]) if (!isOptionalBoolean(item[key])) return `${where} carries a malformed ${key}.`;
75
98
  const merge = item["mergeNext"];
76
99
  if (merge !== void 0 && !(isString(merge) && MERGES.has(merge))) return `${where} names an unknown merge.`;
100
+ const section = sectionIssue(item["endsSection"], where);
101
+ if (section !== null) return section;
77
102
  const numbering = numberingIssue(item["numbering"], where);
78
103
  if (numbering !== null) return numbering;
79
104
  const nested = item["nested"];
@@ -172,9 +197,13 @@ const fieldsIssue = (fields) => {
172
197
  if (updateOnOpen !== void 0 && typeof updateOnOpen !== "boolean") return "The plan's update-on-open choice is not a boolean.";
173
198
  return null;
174
199
  };
200
+ const compatIssue = (compat) => {
201
+ if (compat === void 0) return null;
202
+ return isObject(compat) && isOptionalBoolean(compat["doNotExpandShiftReturn"]) ? null : "The plan's compatibility settings are malformed.";
203
+ };
175
204
  /** Why `plan` is not a version 1 template plan, or null when it is one. */
176
205
  const planShapeIssue = (plan) => {
177
206
  if (!isObject(plan) || plan["version"] !== 1 || !isString(plan["sourceSha256"]) || !isString(plan["templateSha256"])) return "The plan is not a version 1 template plan.";
178
- return bodyIssue(plan["body"]) ?? omitIssue(plan["omit"]) ?? patchesIssue(plan["numberingPatches"]) ?? spansIssue(plan) ?? fieldsIssue(plan["fields"]);
207
+ return bodyIssue(plan["body"]) ?? omitIssue(plan["omit"]) ?? patchesIssue(plan["numberingPatches"]) ?? spansIssue(plan) ?? fieldsIssue(plan["fields"]) ?? compatIssue(plan["compat"]) ?? sectionIssue(plan["lastSection"], "The plan's last section");
179
208
  };
180
209
  export { OMIT_REASONS, PLAN_HIGHLIGHT_COLORS, isPlainText, planShapeIssue };
@@ -89,6 +89,8 @@ export type ParagraphRead = {
89
89
  element: XmlElement;
90
90
  ordinal: number;
91
91
  styleId: string | null;
92
+ /** The language the paragraph mark states (`w:pPr/w:rPr/w:lang`), or null. */
93
+ language: string | null;
92
94
  numPr: ParagraphNumberingOverride | undefined;
93
95
  paraId: string | null;
94
96
  outlineLevel: number | null;
@@ -104,9 +106,15 @@ export type ParagraphRead = {
104
106
  /** Names of content the reader has no text for and the transfer cannot carry. */
105
107
  unsupported: string[];
106
108
  hasSectionBreak: boolean;
109
+ /** `w:pageBreakBefore` as the paragraph itself states it; null when it does not. */
110
+ pageBreakBefore: boolean | null;
111
+ /** `w:jc` as the paragraph itself states it, or null. */
112
+ alignment: string | null;
107
113
  /** Whether the paragraph mark is a tracked insertion or deletion. */
108
114
  hasTrackedMark: boolean;
109
115
  };
116
+ /** An on/off property as its element states it; null without the element. */
117
+ export declare const toggleOf: (element: XmlElement | null) => boolean | null;
110
118
  /** Read one `w:p`, advancing the story's field and revision state. */
111
119
  export declare const readParagraph: (element: XmlElement, state: StoryState) => ParagraphRead;
112
120
  export type StoryBlockVisitor = {
@@ -24,6 +24,13 @@ const endStory = (state) => {
24
24
  state.strayFieldEnds += state.open.length;
25
25
  state.open = [];
26
26
  };
27
+ const TOGGLE_OFF = /* @__PURE__ */ new Set([
28
+ "0",
29
+ "false",
30
+ "off"
31
+ ]);
32
+ /** An on/off property as its element states it; null without the element. */
33
+ const toggleOf = (element) => element === null ? null : !TOGGLE_OFF.has(wAttr(element, "val") ?? "1");
27
34
  const REVISION_INCLUDED = /* @__PURE__ */ new Set(["ins", "moveTo"]);
28
35
  const REVISION_EXCLUDED = /* @__PURE__ */ new Set(["del", "moveFrom"]);
29
36
  const TRANSPARENT_WRAPPERS = /* @__PURE__ */ new Set([
@@ -323,6 +330,7 @@ const readParagraph = (element, state) => {
323
330
  element,
324
331
  ordinal: state.paragraphOrdinal,
325
332
  styleId: wChildVal(properties, "pStyle"),
333
+ language: wChildVal(wChild(properties, "rPr"), "lang"),
326
334
  numPr: readParagraphNumbering(wChild(properties, "numPr")),
327
335
  paraId: paraIdAttribute(element) ?? null,
328
336
  outlineLevel: headingLevelOf(outline),
@@ -335,6 +343,8 @@ const readParagraph = (element, state) => {
335
343
  inlineObjects: 0,
336
344
  unsupported: [],
337
345
  hasSectionBreak: wChild(properties, "sectPr") !== null,
346
+ pageBreakBefore: toggleOf(wChild(properties, "pageBreakBefore")),
347
+ alignment: wChildVal(properties, "jc"),
338
348
  hasTrackedMark
339
349
  };
340
350
  state.paragraphOrdinal += 1;
@@ -437,4 +447,4 @@ const walkBlocks = (container, visitor, depth = 0) => {
437
447
  } else if (name === null || !IGNORED_BLOCK_CHILDREN.has(name)) visitor.unread(child);
438
448
  }
439
449
  };
440
- export { NOTE_REFERENCE_MARK, createStoryState, endStory, readParagraph, walkBlocks };
450
+ export { NOTE_REFERENCE_MARK, createStoryState, endStory, readParagraph, toggleOf, walkBlocks };