@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
@@ -4,7 +4,7 @@ import { spliceXml } from "../../selectiveXmlPatch.js";
4
4
  import { NAMESPACES, getLocalName } from "../../xmlParser.js";
5
5
  import { appendToXmlRoot } from "../../xmlRootInsertion.js";
6
6
  import { analyzeDocument } from "./blocks.js";
7
- import { freezeFields, setUpdateFieldsOnOpen, withoutContained } from "./builders.js";
7
+ import { freezeFields, sectionPropertiesXml, setKeepShiftReturnSpacing, setUpdateFieldsOnOpen, withoutContained } from "./builders.js";
8
8
  import { createRelationshipsEditor, noteXml, paragraphContentXml, paragraphXml, tableXml, templateCharacterStyles } from "./emit.js";
9
9
  import { readHeaderFooterParts } from "./inspect.js";
10
10
  import { styleNumbering } from "./labels.js";
@@ -388,9 +388,23 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
388
388
  };
389
389
  const instructions = new Map(resolved.references.map(({ reference, instruction }) => [reference, instruction]));
390
390
  const instructionOf = (segment) => segment.kind === "reference" ? instructions.get(segment.reference) ?? null : null;
391
+ const bodySection = wChild(template.body, "sectPr");
392
+ const sectionEnds = resolved.items.flatMap((item) => item.kind === "paragraph" && item.paragraph.endsSection !== null ? [item.paragraph] : []);
393
+ const sectionXmlOf = /* @__PURE__ */ new Map();
394
+ for (const [position, paragraph] of sectionEnds.entries()) {
395
+ const section = paragraph.endsSection;
396
+ const xml = bodySection === null || section === null ? null : sectionPropertiesXml(template.document.xml, bodySection, documentContext.prefixes.w, {
397
+ first: position === 0,
398
+ page: section.page,
399
+ start: position === 0 ? null : section.start ?? "nextPage"
400
+ });
401
+ if (xml === null) return Result.err(unreadable(pkg.documentPath, "A section could not be built."));
402
+ sectionXmlOf.set(paragraph, xml);
403
+ }
391
404
  const emitOf = (paragraph) => ({
392
405
  paragraph,
393
406
  bookmark: resolved.bookmarks.get(paragraph),
407
+ sectionXml: sectionXmlOf.get(paragraph) ?? null,
394
408
  instructionOf,
395
409
  styleBindsList: styleNumbering(paragraph.styleId ?? template.defaultStyleId, template.styles, template.numbering)?.kind === "reference"
396
410
  });
@@ -424,7 +438,6 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
424
438
  end: inner.end
425
439
  });
426
440
  }
427
- const bodySection = wChild(template.body, "sectPr");
428
441
  const keptElements = [
429
442
  ...resolved.keptTemplateBlocks.map(({ element }) => element),
430
443
  ...resolved.items.flatMap((item) => item.kind === "slot" ? [item.templateBlock.element] : []),
@@ -453,6 +466,9 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
453
466
  case "paragraph":
454
467
  xml = paragraphXml(emitOf(item.paragraph), documentContext);
455
468
  break;
469
+ case "separator":
470
+ xml = Result.ok(`<${documentContext.prefixes.w}:p/>`);
471
+ break;
456
472
  case "table":
457
473
  xml = tableXml({
458
474
  table: item.block.element,
@@ -469,7 +485,13 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
469
485
  body.push(xml.value);
470
486
  }
471
487
  if (bodySection !== null) {
472
- const section = keptXml(bodySection);
488
+ const { lastSection } = plan;
489
+ const rebuilt = sectionEnds.length > 0 || lastSection !== void 0 ? sectionPropertiesXml(template.document.xml, bodySection, documentContext.prefixes.w, {
490
+ first: sectionEnds.length === 0,
491
+ page: lastSection?.page,
492
+ start: sectionEnds.length === 0 ? null : lastSection?.start ?? null
493
+ }) : null;
494
+ const section = rebuilt === null ? keptXml(bodySection) : Result.ok(rebuilt);
473
495
  if (Result.isError(section)) return section;
474
496
  body.push(section.value);
475
497
  }
@@ -598,6 +620,19 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
598
620
  if (settings !== settingsXml.value) parts.set(settingsPath, settings);
599
621
  }
600
622
  }
623
+ if (plan.compat?.doNotExpandShiftReturn === true) {
624
+ const settingsPath = pkg.partPath("settings");
625
+ const written = settingsPath === null ? void 0 : parts.get(settingsPath);
626
+ const settingsXml = typeof written === "string" ? Result.ok(written) : await readTemplateText(settingsPath);
627
+ if (Result.isError(settingsXml)) return settingsXml;
628
+ if (settingsPath === null || settingsXml.value === null) return Result.err(new TemplatePlanError({
629
+ code: "part-missing",
630
+ message: "The template has no settings part to set a compatibility setting in."
631
+ }));
632
+ const settings = setKeepShiftReturnSpacing(settingsXml.value);
633
+ if (settings === null) return Result.err(unreadable(settingsPath, "The settings part could not be updated."));
634
+ if (settings !== settingsXml.value) parts.set(settingsPath, settings);
635
+ }
601
636
  return await Result.tryPromise({
602
637
  try: async () => {
603
638
  const zip = await ZipArchive.read(pkg.bytes);
@@ -7,7 +7,7 @@ import { Emphasis } from "./emphasis.js";
7
7
  import { LabelCounter, ParagraphLabel } from "./labels.js";
8
8
  import { LoadedPackage } from "./package.js";
9
9
  import { ParagraphRead, StoryState } from "./story.js";
10
- import { DocxBlock, DocxBlockManifest, TemplatePlanError } from "./types.js";
10
+ import { DocxBlock, DocxBlockManifest, DocxSection, TemplatePlanError } from "./types.js";
11
11
  import { RawPart } from "./xml.js";
12
12
  import { Result } from "better-result";
13
13
  export declare const blockHash: (text: string, label: string | null) => string;
@@ -32,6 +32,8 @@ export type AnalyzedStory = {
32
32
  state: StoryState;
33
33
  /** `w:sectPr` elements in document order, the body's own last. */
34
34
  sections: XmlElement[];
35
+ /** Whether the body states section properties of its own. */
36
+ hasBodySection: boolean;
35
37
  /** Names of block-level elements the walk has no reading for. */
36
38
  unreadBlocks: string[];
37
39
  warnings: string[];
@@ -39,10 +41,23 @@ export type AnalyzedStory = {
39
41
  type StoryResources = {
40
42
  styles: StyleMap;
41
43
  defaultStyleId: string | null;
44
+ /** The language the document defaults give every run, or null. */
45
+ defaultLanguage: string | null;
42
46
  numbering: NumberingMap | null;
47
+ /** The alignment each paragraph style states for itself (`w:jc`). */
48
+ alignments?: ReadonlyMap<string, string>;
43
49
  };
44
50
  /** The heading level a style outlines its paragraphs at, 0 being the highest. */
45
51
  export declare const styleOutlineLevel: (style: document_d_exports.Style | undefined) => number | null;
52
+ /** The alignment each style of a styles part states for itself (`w:jc`). */
53
+ export declare const statedAlignments: (stylesPath: string | null, stylesXml: string | null) => Map<string, string>;
54
+ /** The alignment of the nearest style in the `basedOn` chain that states one. */
55
+ export declare const styleAlignment: (styleId: string | null, styles: StyleMap, stated: ReadonlyMap<string, string>) => string | null;
56
+ /**
57
+ * The sections of a story with what each states. A body without section
58
+ * properties of its own still ends in a section, which states nothing.
59
+ */
60
+ export declare const storySections: ({ sections, hasBodySection }: AnalyzedStory) => DocxSection[];
46
61
  type AnalyzeStoryOptions = {
47
62
  container: XmlElement;
48
63
  resources: StoryResources;
@@ -1,11 +1,13 @@
1
1
  import { parseNumbering } from "../../numberingParser.js";
2
+ import { parseSectionProperties } from "../../sectionParser.js";
2
3
  import { parseStylesPackage } from "../../styleParser.js";
4
+ import { keepsShiftReturnSpacing } from "./builders.js";
3
5
  import { defaultsBaseline } from "./emphasis.js";
4
6
  import { createLabelCounter } from "./labels.js";
5
7
  import { guarded, loadPackage, readPartText, sha256Hex } from "./package.js";
6
8
  import { createStoryState, endStory, readParagraph, walkBlocks } from "./story.js";
7
9
  import { TemplatePlanError } from "./types.js";
8
- import { elementChildren, isW, readRawPart, wAttr, wChild } from "./xml.js";
10
+ import { elementChildren, isW, readRawPart, wAttr, wChild, wChildVal, wChildren } from "./xml.js";
9
11
  import { Result } from "better-result";
10
12
  // src/docx/server/templatePlan/blocks.ts
11
13
  /** The block manifest of a DOCX: its main story as addressable, hash-pinned blocks. */
@@ -17,6 +19,74 @@ const styleOutlineLevel = (style) => {
17
19
  return outline?.kind === "heading" ? outline.level : null;
18
20
  };
19
21
  const styleNameOf = (style) => style?.name ?? null;
22
+ /** A section's page and how it begins, as its `w:sectPr` states them. */
23
+ const sectionOf = (sectPr, index) => {
24
+ const properties = parseSectionProperties(sectPr);
25
+ return {
26
+ index,
27
+ start: properties.sectionStart ?? "nextPage",
28
+ orientation: properties.orientation ?? "portrait",
29
+ size: {
30
+ width: properties.pageWidth ?? null,
31
+ height: properties.pageHeight ?? null
32
+ },
33
+ margins: {
34
+ top: properties.marginTop ?? null,
35
+ right: properties.marginRight ?? null,
36
+ bottom: properties.marginBottom ?? null,
37
+ left: properties.marginLeft ?? null
38
+ },
39
+ columns: properties.columnCount ?? 1
40
+ };
41
+ };
42
+ /** The alignment each style of a styles part states for itself (`w:jc`). */
43
+ const statedAlignments = (stylesPath, stylesXml) => {
44
+ const alignments = /* @__PURE__ */ new Map();
45
+ const part = stylesPath === null || stylesXml === null ? null : readRawPart(stylesPath, stylesXml);
46
+ for (const style of wChildren(part?.root, "style")) {
47
+ const styleId = wAttr(style, "styleId");
48
+ const alignment = wChildVal(wChild(style, "pPr"), "jc");
49
+ if (styleId !== null && alignment !== null) alignments.set(styleId, alignment);
50
+ }
51
+ return alignments;
52
+ };
53
+ /** The alignment of the nearest style in the `basedOn` chain that states one. */
54
+ const styleAlignment = (styleId, styles, stated) => {
55
+ const seen = /* @__PURE__ */ new Set();
56
+ let cursor = styleId ?? void 0;
57
+ while (cursor !== void 0 && !seen.has(cursor)) {
58
+ seen.add(cursor);
59
+ const alignment = stated.get(cursor);
60
+ if (alignment !== void 0) return alignment;
61
+ cursor = styles.get(cursor)?.basedOn;
62
+ }
63
+ return null;
64
+ };
65
+ /**
66
+ * The sections of a story with what each states. A body without section
67
+ * properties of its own still ends in a section, which states nothing.
68
+ */
69
+ const storySections = ({ sections, hasBodySection }) => {
70
+ const stated = sections.map(sectionOf);
71
+ return hasBodySection ? stated : [...stated, {
72
+ index: stated.length,
73
+ start: "nextPage",
74
+ orientation: "portrait",
75
+ size: {
76
+ width: null,
77
+ height: null
78
+ },
79
+ margins: {
80
+ top: null,
81
+ right: null,
82
+ bottom: null,
83
+ left: null
84
+ },
85
+ columns: 1
86
+ }];
87
+ };
88
+ /** Page breaks among a paragraph's runs; a column break is not one. */
89
+ const pageBreaksOf = ({ atoms }) => atoms.filter(({ kind, element }) => kind === "pageBreak" && wAttr(element, "type") === "page").length;
20
90
  /** Read the blocks under `container` into ids, text, labels and hashes. */
21
91
  const analyzeStory = ({ container, resources, counter = createLabelCounter(resources) }) => {
22
92
  const state = createStoryState();
@@ -27,6 +97,7 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
27
97
  paragraphs: [],
28
98
  state,
29
99
  sections: [],
100
+ hasBodySection: false,
30
101
  unreadBlocks: [],
31
102
  warnings: []
32
103
  };
@@ -55,7 +126,8 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
55
126
  const style = resources.styles.get(styleId ?? resources.defaultStyleId ?? "");
56
127
  const label = counter.next({
57
128
  styleId,
58
- numPr: read.numPr
129
+ numPr: read.numPr,
130
+ language: read.language
59
131
  });
60
132
  const id = `p${index}`;
61
133
  const block = {
@@ -73,6 +145,12 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
73
145
  ...read.paraId === null ? {} : { paraId: read.paraId },
74
146
  inlineObjects: read.inlineObjects
75
147
  };
148
+ const pageBreaks = pageBreaksOf(read);
149
+ if (pageBreaks > 0) block.pageBreaks = pageBreaks;
150
+ if (read.pageBreakBefore ?? style?.pPr?.pageBreakBefore === true) block.pageBreakBefore = true;
151
+ if (read.hasSectionBreak) block.endsSection = true;
152
+ const alignment = read.alignment ?? (resources.alignments === void 0 ? null : styleAlignment(styleId ?? resources.defaultStyleId, resources.styles, resources.alignments));
153
+ if (alignment !== null) block.alignment = alignment;
76
154
  index += 1;
77
155
  const analyzed = {
78
156
  block,
@@ -166,7 +244,10 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
166
244
  }
167
245
  });
168
246
  const bodySection = wChild(container, "sectPr");
169
- if (bodySection !== null) story.sections.push(bodySection);
247
+ if (bodySection !== null) {
248
+ story.sections.push(bodySection);
249
+ story.hasBodySection = true;
250
+ }
170
251
  for (const [name, count] of unread) {
171
252
  story.unreadBlocks.push(name);
172
253
  story.warnings.push(`${count} block-level ${name} element(s) are not read as blocks.`);
@@ -278,13 +359,14 @@ const analyzeDocument = async (bytes) => {
278
359
  numberingPath,
279
360
  footnotesPath,
280
361
  endnotesPath,
281
- pkg.partPath("comments")
362
+ pkg.partPath("comments"),
363
+ pkg.partPath("settings")
282
364
  ]) {
283
365
  const text = await readPartText(pkg, path);
284
366
  if (Result.isError(text)) return text;
285
367
  texts.push(text.value);
286
368
  }
287
- const [stylesXml = null, numberingXml = null, footnotesXml = null, endnotesXml = null, commentsXml = null] = texts;
369
+ const [stylesXml = null, numberingXml = null, footnotesXml = null, endnotesXml = null, commentsXml = null, settingsXml = null] = texts;
288
370
  const read = Result.try({
289
371
  try: () => {
290
372
  const stylesPackage = stylesXml === null ? null : parseStylesPackage(stylesXml, null);
@@ -302,7 +384,9 @@ const analyzeDocument = async (bytes) => {
302
384
  resources: {
303
385
  styles,
304
386
  defaultStyleId,
305
- numbering
387
+ defaultLanguage: stylesPackage?.styleDefinitions.docDefaults?.rPr?.language?.val ?? null,
388
+ numbering,
389
+ alignments: statedAlignments(stylesPath, stylesXml)
306
390
  }
307
391
  }),
308
392
  footnotes: analyzeNotes("footnotes", footnotesPath, footnotesXml),
@@ -323,6 +407,8 @@ const analyzeDocument = async (bytes) => {
323
407
  const manifest = {
324
408
  sha256: pkg.sha256,
325
409
  blocks: story.topLevel.map(({ block }) => block),
410
+ sections: storySections(story),
411
+ compat: { doNotExpandShiftReturn: settingsXml !== null && keepsShiftReturnSpacing(settingsXml) },
326
412
  footnotes: noteList(footnotes),
327
413
  endnotes: noteList(endnotes),
328
414
  comments: countComments(commentsXml),
@@ -352,4 +438,4 @@ const analyzeDocument = async (bytes) => {
352
438
  * rendered list labels, styles and a hash per block, plus its notes.
353
439
  */
354
440
  const analyzeDocxBlocks = async (docx) => await guarded(async () => (await analyzeDocument(docx)).map(({ manifest }) => manifest));
355
- export { analyzeDocument, analyzeDocxBlocks, analyzeStory, blockHash, styleOutlineLevel };
441
+ export { analyzeDocument, analyzeDocxBlocks, analyzeStory, blockHash, statedAlignments, storySections, styleAlignment, styleOutlineLevel };
@@ -1,5 +1,6 @@
1
1
  import { XmlSplice } from "../../selectiveXmlPatch.js";
2
2
  import { XmlElement } from "../../xmlParser.js";
3
+ import { TemplatePlanSectionPage } from "./types.js";
3
4
  import { PartPrefixes, RawPart } from "./xml.js";
4
5
  /**
5
6
  * A hidden bookmark name in the form a cross-reference target takes: `_Ref`
@@ -39,9 +40,14 @@ type ComplexFieldOptions = {
39
40
  };
40
41
  /** A complex field: begin, instruction, separate, the cached result, end. */
41
42
  export declare const complexFieldXml: ({ prefix, instruction, resultRunsXml, runPropertiesXml }: ComplexFieldOptions) => string;
43
+ /** The letter case a REF instruction asks for its result in, or null. */
44
+ export declare const refCaseFormat: (instruction: string) => "lower" | "upper" | "firstcap" | null;
45
+ /** `text` in the letter case a `\*` switch names, as a field result has it. */
46
+ export declare const applyRefCaseFormat: (text: string, format: ReturnType<typeof refCaseFormat>) => string;
42
47
  /**
43
- * The field code of a REF to `bookmark` with `switches` (`\n \t \h`). Null
44
- * when the switches hold anything but single-letter switches.
48
+ * The field code of a REF to `bookmark` with `switches` (`\n \t \h`,
49
+ * `\n \* lower \h`). Null when the switches hold anything but
50
+ * single-letter switches and one letter-case format.
45
51
  */
46
52
  export declare const refFieldInstruction: (bookmark: string, switches: string) => string | null;
47
53
  /** The bookmark a REF, PAGEREF or NOTEREF instruction names. */
@@ -51,6 +57,35 @@ export declare const fieldBookmarkOf: (instruction: string) => string | null;
51
57
  * place in the schema's child order. Null when the part is not a settings part.
52
58
  */
53
59
  export declare const setUpdateFieldsOnOpen: (settingsXml: string, enabled: boolean) => string | null;
60
+ /** Whether a settings part keeps the spacing of a justified line that ends
61
+ * in a manual line break (`w:compat/w:doNotExpandShiftReturn`). */
62
+ export declare const keepsShiftReturnSpacing: (settingsXml: string) => boolean;
63
+ /**
64
+ * `settingsXml` with `w:doNotExpandShiftReturn` switched on in `w:compat`,
65
+ * each at its place in the schema's child order; every other byte of the
66
+ * part stays. Null when the part is not a settings part or gives the setting
67
+ * no certain place.
68
+ */
69
+ export declare const setKeepShiftReturnSpacing: (settingsXml: string) => string | null;
70
+ export type SectionRewrite = {
71
+ /**
72
+ * Whether the section begins the document. Every later one loses the
73
+ * first-page header and a page-number start: they belong to the
74
+ * document's first page, not to each part of it.
75
+ */
76
+ first: boolean;
77
+ /** The page to put in place of the template's, or undefined. */
78
+ page: TemplatePlanSectionPage | undefined;
79
+ /** How the section begins; null keeps what the template states. */
80
+ start: string | null;
81
+ };
82
+ /**
83
+ * A `w:sectPr` built from the template's: the same children in the same
84
+ * order, with the page, the start and the first-section properties changed
85
+ * as `rewrite` says. `xml` is the part `sectPr` was read from. Null when a
86
+ * child cannot be read back.
87
+ */
88
+ export declare const sectionPropertiesXml: (xml: string, sectPr: XmlElement, w: string, { first, page, start }: SectionRewrite) => string | null;
54
89
  export type FrozenFieldCount = {
55
90
  kind: string;
56
91
  count: number;
@@ -1,7 +1,9 @@
1
+ import { sliceText } from "../../../utils/sliceText.js";
1
2
  import { spliceXml } from "../../selectiveXmlPatch.js";
2
3
  import { updateSettingsOnOffChild } from "../../settingsHeaderFooterUpdate.js";
3
4
  import { sha256Hex } from "./package.js";
4
- import { elementChildren, escapeXmlAttribute, escapeXmlText, innerRangeOf, isW, rangeOf, readRawPart, wAttr, wChild, wName, walkElements } from "./xml.js";
5
+ import { elementChildren, escapeXmlAttribute, escapeXmlText, innerRangeOf, isW, partPrefixes, rangeOf, readRawPart, wAttr, wChild, wName, walkElements } from "./xml.js";
6
+ import { SETTINGS_CHILDREN } from "@stll/docx-core/schema";
5
7
  // src/docx/server/templatePlan/builders.ts
6
8
  /**
7
9
  * Raw OOXML builders a template plan is applied with: a hidden bookmark around
@@ -88,13 +90,47 @@ const complexFieldXml = ({ prefix, instruction, resultRunsXml, runPropertiesXml
88
90
  };
89
91
  /** The REF switches that take no argument. */
90
92
  const REF_SWITCH = /^\\[fhnprtw]$/u;
93
+ /** The general format switch and the letter cases it may name. */
94
+ const FORMAT_SWITCH = "\\*";
95
+ const CASE_FORMAT = /^(?:lower|upper|firstcap)$/iu;
96
+ /** The letter case a REF instruction asks for its result in, or null. */
97
+ const refCaseFormat = (instruction) => {
98
+ const name = /\\\*\s*(?<name>lower|upper|firstcap)\b/iu.exec(instruction)?.groups?.["name"]?.toLowerCase();
99
+ return name === "lower" || name === "upper" || name === "firstcap" ? name : null;
100
+ };
101
+ /** `text` in the letter case a `\*` switch names, as a field result has it. */
102
+ const applyRefCaseFormat = (text, format) => {
103
+ switch (format) {
104
+ case "lower": return text.toLowerCase();
105
+ case "upper": return text.toUpperCase();
106
+ case "firstcap": {
107
+ const initial = sliceText({
108
+ text,
109
+ units: "graphemes",
110
+ end: 1
111
+ });
112
+ return initial.toUpperCase() + text.slice(initial.length);
113
+ }
114
+ case null: return text;
115
+ default: return format;
116
+ }
117
+ };
91
118
  /**
92
- * The field code of a REF to `bookmark` with `switches` (`\n \t \h`). Null
93
- * when the switches hold anything but single-letter switches.
119
+ * The field code of a REF to `bookmark` with `switches` (`\n \t \h`,
120
+ * `\n \* lower \h`). Null when the switches hold anything but
121
+ * single-letter switches and one letter-case format.
94
122
  */
95
123
  const refFieldInstruction = (bookmark, switches) => {
96
124
  const parts = switches.trim().split(/\s+/u).filter(Boolean);
97
- return parts.every((part) => REF_SWITCH.test(part)) ? ` REF ${bookmark} ${parts.join(" ")}${parts.length === 0 ? "" : " "}` : null;
125
+ let formats = 0;
126
+ for (const [index, part] of parts.entries()) {
127
+ const afterFormat = parts[index - 1] === FORMAT_SWITCH;
128
+ if (part === FORMAT_SWITCH) {
129
+ formats += 1;
130
+ if (formats > 1 || !CASE_FORMAT.test(parts[index + 1] ?? "")) return null;
131
+ } else if (!afterFormat && !REF_SWITCH.test(part)) return null;
132
+ }
133
+ return ` REF ${bookmark} ${parts.join(" ")}${parts.length === 0 ? "" : " "}`;
98
134
  };
99
135
  /** The bookmark a REF, PAGEREF or NOTEREF instruction names. */
100
136
  const fieldBookmarkOf = (instruction) => /^\s*(?:REF|PAGEREF|NOTEREF)\s+"?(?<name>[^\s"\\]+)/iu.exec(instruction)?.groups?.["name"] ?? null;
@@ -103,6 +139,161 @@ const fieldBookmarkOf = (instruction) => /^\s*(?:REF|PAGEREF|NOTEREF)\s+"?(?<nam
103
139
  * place in the schema's child order. Null when the part is not a settings part.
104
140
  */
105
141
  const setUpdateFieldsOnOpen = (settingsXml, enabled) => updateSettingsOnOffChild(settingsXml, "updateFields", enabled ? true : void 0);
142
+ const SHIFT_RETURN = "doNotExpandShiftReturn";
143
+ /** The children of `w:compat` the schema orders in front of the setting. */
144
+ const COMPAT_BEFORE_SHIFT_RETURN = /* @__PURE__ */ new Set([
145
+ "useSingleBorderforContiguousCells",
146
+ "wpJustification",
147
+ "noTabHangInd",
148
+ "noLeading",
149
+ "spaceForUL",
150
+ "noColumnBalance",
151
+ "balanceSingleByteDoubleByteWidth",
152
+ "noExtraLineSpacing",
153
+ "doNotLeaveBackslashAlone",
154
+ "ulTrailSpace"
155
+ ]);
156
+ const SWITCHED_OFF = /* @__PURE__ */ new Set([
157
+ "0",
158
+ "false",
159
+ "off"
160
+ ]);
161
+ const SETTINGS_CHILD_ORDINALS = new Map(SETTINGS_CHILDREN.map((name, index) => [name, index]));
162
+ const settingsRoot = (settingsXml) => {
163
+ const part = readRawPart("word/settings.xml", settingsXml);
164
+ return part !== null && isW(part.root, "settings") ? part : null;
165
+ };
166
+ /** Whether a settings part keeps the spacing of a justified line that ends
167
+ * in a manual line break (`w:compat/w:doNotExpandShiftReturn`). */
168
+ const keepsShiftReturnSpacing = (settingsXml) => {
169
+ const setting = wChild(wChild(settingsRoot(settingsXml)?.root, "compat"), SHIFT_RETURN);
170
+ return setting !== null && !SWITCHED_OFF.has(wAttr(setting, "val") ?? "1");
171
+ };
172
+ /** An element of the part's WordprocessingML namespace, bound by the
173
+ * root's prefix or, under a default namespace, by one of its own. */
174
+ const settingsElement = (root, localName, inner) => {
175
+ const prefixes = partPrefixes(root);
176
+ const name = prefixes === null ? `folioW:${localName}` : `${prefixes.w}:${localName}`;
177
+ const binding = prefixes === null ? ` xmlns:folioW="${escapeXmlAttribute(root.namespaceUri ?? "")}"` : "";
178
+ return inner === null ? `<${name}${binding}/>` : `<${name}${binding}>${inner}</${name}>`;
179
+ };
180
+ /**
181
+ * `settingsXml` with `w:doNotExpandShiftReturn` switched on in `w:compat`,
182
+ * each at its place in the schema's child order; every other byte of the
183
+ * part stays. Null when the part is not a settings part or gives the setting
184
+ * no certain place.
185
+ */
186
+ const setKeepShiftReturnSpacing = (settingsXml) => {
187
+ const part = settingsRoot(settingsXml);
188
+ if (part === null) return null;
189
+ if (keepsShiftReturnSpacing(settingsXml)) return settingsXml;
190
+ const { root } = part;
191
+ const setting = settingsElement(root, SHIFT_RETURN, null);
192
+ const compat = wChild(root, "compat");
193
+ if (compat === null) {
194
+ const compatOrder = SETTINGS_CHILD_ORDINALS.get("compat") ?? 0;
195
+ const wrapper = settingsElement(root, "compat", setting);
196
+ const inner = innerRangeOf(settingsXml, root);
197
+ if (inner === null) {
198
+ const range = rangeOf(root);
199
+ return range === null || root.name === void 0 ? null : spliceXml(settingsXml, [{
200
+ start: range.end - 2,
201
+ end: range.end,
202
+ newXml: `>${wrapper}</${root.name}>`
203
+ }]);
204
+ }
205
+ const following = elementChildren(root).find((child) => {
206
+ const name = wName(child);
207
+ return name === null || (SETTINGS_CHILD_ORDINALS.get(name) ?? -1) > compatOrder;
208
+ });
209
+ const at = following === void 0 ? inner.end : rangeOf(following)?.start;
210
+ return at === void 0 ? null : spliceXml(settingsXml, [{
211
+ start: at,
212
+ end: at,
213
+ newXml: wrapper
214
+ }]);
215
+ }
216
+ const range = rangeOf(compat);
217
+ const inner = innerRangeOf(settingsXml, compat);
218
+ if (range === null) return null;
219
+ if (inner === null) return spliceXml(settingsXml, [{
220
+ start: range.start,
221
+ end: range.end,
222
+ newXml: settingsElement(root, "compat", setting)
223
+ }]);
224
+ const stated = wChild(compat, SHIFT_RETURN);
225
+ const statedRange = stated === null ? null : rangeOf(stated);
226
+ if (statedRange !== null) return spliceXml(settingsXml, [{
227
+ ...statedRange,
228
+ newXml: setting
229
+ }]);
230
+ const following = elementChildren(compat).find((child) => {
231
+ const name = wName(child);
232
+ return name === null || !COMPAT_BEFORE_SHIFT_RETURN.has(name);
233
+ });
234
+ const at = following === void 0 ? inner.end : rangeOf(following)?.start;
235
+ return at === void 0 ? null : spliceXml(settingsXml, [{
236
+ start: at,
237
+ end: at,
238
+ newXml: setting
239
+ }]);
240
+ };
241
+ /** The children of `w:sectPr` the schema orders in front of `w:type`. */
242
+ const SECTION_BEFORE_TYPE = /* @__PURE__ */ new Set([
243
+ "headerReference",
244
+ "footerReference",
245
+ "footnotePr",
246
+ "endnotePr"
247
+ ]);
248
+ const PAGE_NUMBER_KEPT = [
249
+ "fmt",
250
+ "chapStyle",
251
+ "chapSep"
252
+ ];
253
+ const MARGINS_KEPT = [
254
+ "header",
255
+ "footer",
256
+ "gutter"
257
+ ];
258
+ /**
259
+ * A `w:sectPr` built from the template's: the same children in the same
260
+ * order, with the page, the start and the first-section properties changed
261
+ * as `rewrite` says. `xml` is the part `sectPr` was read from. Null when a
262
+ * child cannot be read back.
263
+ */
264
+ const sectionPropertiesXml = (xml, sectPr, w, { first, page, start }) => {
265
+ const attributes = (element, names) => names.map((name) => [name, wAttr(element, name)]).filter(([, value]) => value !== null).map(([name, value]) => ` ${w}:${name}="${escapeXmlAttribute(value ?? "")}"`).join("");
266
+ const type = start === null ? "" : `<${w}:type ${w}:val="${start}"/>`;
267
+ const out = [];
268
+ let typeWritten = type === "";
269
+ for (const child of elementChildren(sectPr)) {
270
+ const name = wName(child);
271
+ if (!typeWritten && (name === null || !SECTION_BEFORE_TYPE.has(name))) {
272
+ out.push(type);
273
+ typeWritten = true;
274
+ }
275
+ if (name === "sectPrChange" || name === "type" && start !== null || name === "titlePg" && !first) continue;
276
+ if (name === "pgSz" && page !== void 0) {
277
+ out.push(`<${w}:pgSz ${w}:w="${page.width}" ${w}:h="${page.height}"${page.orientation === "landscape" ? ` ${w}:orient="landscape"` : ""}/>`);
278
+ continue;
279
+ }
280
+ if (name === "pgMar" && page?.margins !== void 0) {
281
+ const { top, right, bottom, left } = page.margins;
282
+ out.push(`<${w}:pgMar ${w}:top="${top}" ${w}:right="${right}" ${w}:bottom="${bottom}" ${w}:left="${left}"${attributes(child, MARGINS_KEPT)}/>`);
283
+ continue;
284
+ }
285
+ if (name === "pgNumType" && !first) {
286
+ const kept = attributes(child, PAGE_NUMBER_KEPT);
287
+ if (kept !== "") out.push(`<${w}:pgNumType${kept}/>`);
288
+ continue;
289
+ }
290
+ const range = rangeOf(child);
291
+ if (range === null) return null;
292
+ out.push(xml.slice(range.start, range.end));
293
+ }
294
+ if (!typeWritten) out.push(type);
295
+ return `<${w}:sectPr>${out.join("")}</${w}:sectPr>`;
296
+ };
106
297
  const fieldKindOfInstruction = (instruction) => /^\s*\\?(?<name>[A-Za-z][A-Za-z0-9]*)/u.exec(instruction)?.groups?.["name"]?.toUpperCase() ?? "";
107
298
  const textOf = (element) => (element.elements ?? []).map((child) => child.type === "text" ? String(child.text ?? "") : "").join("");
108
299
  /** Drop splices that lie inside an earlier one, so none overlap. */
@@ -234,4 +425,4 @@ const freezeFields = (part, kinds) => {
234
425
  }))
235
426
  };
236
427
  };
237
- export { bookmarkEndXml, bookmarkIdsOf, bookmarkStartXml, complexFieldXml, fieldBookmarkOf, freezeFields, mintRefBookmarkName, refFieldInstruction, setUpdateFieldsOnOpen, withoutContained, wrapParagraphContentInBookmark };
428
+ export { applyRefCaseFormat, bookmarkEndXml, bookmarkIdsOf, bookmarkStartXml, complexFieldXml, fieldBookmarkOf, freezeFields, keepsShiftReturnSpacing, mintRefBookmarkName, refCaseFormat, refFieldInstruction, sectionPropertiesXml, setKeepShiftReturnSpacing, setUpdateFieldsOnOpen, withoutContained, wrapParagraphContentInBookmark };
@@ -87,6 +87,8 @@ export type ParagraphEmit = {
87
87
  instructionOf: (segment: ExpectedSegment) => string | null;
88
88
  /** Whether the paragraph's style binds a list that `numbering: null` must cancel. */
89
89
  styleBindsList: boolean;
90
+ /** The `w:sectPr` of the section the paragraph is the last of, or null. */
91
+ sectionXml: string | null;
90
92
  };
91
93
  /** Runs of a placed paragraph, inside its bookmark when it is a reference target. */
92
94
  export declare const paragraphContentXml: ({ paragraph, bookmark, instructionOf }: ParagraphEmit, context: EmitContext) => RunsResult;
@@ -326,8 +326,10 @@ const paragraphXml = (emit, context) => {
326
326
  const { styleId, numbering } = emit.paragraph;
327
327
  const properties = [];
328
328
  if (styleId !== null) properties.push(`<${w}:pStyle ${w}:val="${escapeXmlAttribute(styleId)}"/>`);
329
+ if (emit.paragraph.pageBreakBefore) properties.push(`<${w}:pageBreakBefore/>`);
329
330
  if (numbering.kind === "direct") properties.push(`<${w}:numPr><${w}:ilvl ${w}:val="${numbering.ilvl}"/><${w}:numId ${w}:val="${numbering.numId}"/></${w}:numPr>`);
330
331
  else if (numbering.kind === "none" && emit.styleBindsList) properties.push(`<${w}:numPr><${w}:numId ${w}:val="${NO_LIST_NUM_ID}"/></${w}:numPr>`);
332
+ if (emit.sectionXml !== null) properties.push(emit.sectionXml);
331
333
  const runs = segmentsRunsXml(emit.paragraph.segments, context, emit.instructionOf);
332
334
  if (Result.isError(runs)) return runs;
333
335
  const xml = `<${w}:p>${properties.length === 0 ? "" : `<${w}:pPr>${properties.join("")}</${w}:pPr>`}${runs.value}</${w}:p>`;