@stll/folio-core 0.76.0 → 0.78.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 (92) hide show
  1. package/dist/ai-edits/headless.d.ts +6 -4
  2. package/dist/ai-edits/headless.js +32 -15
  3. package/dist/ai-edits/pending-suggestions.d.ts +9 -0
  4. package/dist/ai-edits/pending-suggestions.js +11 -0
  5. package/dist/ai-edits/read.js +24 -1
  6. package/dist/ai-edits/table-geometry.js +12 -4
  7. package/dist/canonical/canonicalBatchReview.js +7 -6
  8. package/dist/canonical/canonicalInlineProjection.d.ts +2 -2
  9. package/dist/canonical/canonicalInlineProjection.js +2 -2
  10. package/dist/canonical/canonicalProjectionBlocks.d.ts +10 -1
  11. package/dist/canonical/canonicalPublicOperations.js +19 -40
  12. package/dist/canonical/canonicalSeedContent.d.ts +18 -3
  13. package/dist/canonical/canonicalSeedContent.js +28 -15
  14. package/dist/canonical/canonicalSession.d.ts +22 -12
  15. package/dist/canonical/canonicalSession.js +190 -194
  16. package/dist/compare/inline-provenance.js +8 -1
  17. package/dist/controller/canonicalClipboard.d.ts +2 -1
  18. package/dist/controller/canonicalClipboard.js +312 -47
  19. package/dist/controller/canonicalComposition.js +67 -14
  20. package/dist/controller/canonicalStoryEditor.js +2 -0
  21. package/dist/controller/hiddenEditorManager.js +2 -0
  22. package/dist/docx/importedIdCollisions.js +29 -4
  23. package/dist/docx/paragraphParser.js +1 -1
  24. package/dist/docx/reviewResolutionProvenance.d.ts +2 -0
  25. package/dist/docx/reviewResolutionProvenance.js +22 -2
  26. package/dist/docx/server/templatePlan/apply.js +47 -2
  27. package/dist/docx/server/templatePlan/blocks.d.ts +34 -7
  28. package/dist/docx/server/templatePlan/blocks.js +190 -13
  29. package/dist/docx/server/templatePlan/builders.d.ts +8 -1
  30. package/dist/docx/server/templatePlan/builders.js +21 -5
  31. package/dist/docx/server/templatePlan/emit.d.ts +2 -0
  32. package/dist/docx/server/templatePlan/emit.js +108 -6
  33. package/dist/docx/server/templatePlan/plan.d.ts +26 -1
  34. package/dist/docx/server/templatePlan/plan.js +181 -21
  35. package/dist/docx/server/templatePlan/planShape.js +15 -3
  36. package/dist/docx/server/templatePlan/revisions.d.ts +55 -0
  37. package/dist/docx/server/templatePlan/revisions.js +276 -2
  38. package/dist/docx/server/templatePlan/story.d.ts +58 -1
  39. package/dist/docx/server/templatePlan/story.js +176 -12
  40. package/dist/docx/server/templatePlan/types.d.ts +153 -1
  41. package/dist/docx/server/templatePlan/verify.js +58 -15
  42. package/dist/docx/settingsHeaderFooterUpdate.d.ts +1 -1
  43. package/dist/docx/tableGridXml.d.ts +3 -7
  44. package/dist/docx/tableGridXml.js +23 -15
  45. package/dist/docx/tableParser.js +3 -1
  46. package/dist/layout-bridge/convert/footnoteLayout.js +34 -8
  47. package/dist/prosemirror/canonicalMarkupDocument.d.ts +20 -0
  48. package/dist/prosemirror/canonicalMarkupDocument.js +73 -0
  49. package/dist/prosemirror/canonicalTableCommands.d.ts +1 -1
  50. package/dist/prosemirror/canonicalTableCommands.js +7 -9
  51. package/dist/prosemirror/conversion/markupViewSource.d.ts +17 -0
  52. package/dist/prosemirror/conversion/markupViewSource.js +11 -0
  53. package/dist/prosemirror/conversion/toProseDoc.d.ts +8 -0
  54. package/dist/prosemirror/conversion/toProseDoc.js +43 -19
  55. package/dist/prosemirror/independentMarkupProjection.d.ts +27 -0
  56. package/dist/prosemirror/independentMarkupProjection.js +147 -0
  57. package/dist/prosemirror/markupViewNotes.d.ts +1 -1
  58. package/dist/prosemirror/markupViewNotes.js +24 -27
  59. package/dist/prosemirror/markupViewPositionMap.d.ts +16 -0
  60. package/dist/prosemirror/markupViewPositionMap.js +316 -0
  61. package/dist/prosemirror/markupViewProjection.d.ts +3 -46
  62. package/dist/prosemirror/markupViewProjection.js +90 -17
  63. package/dist/prosemirror/replacedAnnotations.d.ts +4 -78
  64. package/dist/prosemirror/replacedAnnotations.js +11 -194
  65. package/dist/prosemirror/styles/styleResolver.d.ts +1 -0
  66. package/dist/prosemirror/styles/styleResolver.js +4 -1
  67. package/dist/server.d.ts +2 -2
  68. package/dist/types/canonicalCapabilities.d.ts +3 -10
  69. package/dist/types/canonicalCapabilities.js +3 -10
  70. package/package.json +2 -2
  71. package/dist/internal/revisionResolutionEdits.d.ts +0 -11
  72. package/dist/internal/revisionResolutionEdits.js +0 -18
  73. package/dist/internal/revisionResolutionInline.d.ts +0 -24
  74. package/dist/internal/revisionResolutionInline.js +0 -302
  75. package/dist/internal/revisionResolutionStep.d.ts +0 -3
  76. package/dist/internal/revisionResolutionStep.js +0 -113
  77. package/dist/internal/revisionResolutionTracking.d.ts +0 -9
  78. package/dist/internal/revisionResolutionTracking.js +0 -124
  79. package/dist/internal/wholeStoryRevisionResolution.d.ts +0 -56
  80. package/dist/internal/wholeStoryRevisionResolution.js +0 -783
  81. package/dist/prosemirror/commands/resolveAllTableChanges.d.ts +0 -38
  82. package/dist/prosemirror/commands/resolveAllTableChanges.js +0 -642
  83. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.d.ts +0 -13
  84. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.js +0 -45
  85. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +0 -8
  86. package/dist/prosemirror/commands/tableCellMergeResolution.js +0 -56
  87. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +0 -60
  88. package/dist/prosemirror/commands/tableMergeFoldDecisions.js +0 -78
  89. package/dist/prosemirror/rejoinRunCarriers.d.ts +0 -42
  90. package/dist/prosemirror/rejoinRunCarriers.js +0 -65
  91. package/dist/prosemirror/runPropertyChangeResolution.d.ts +0 -15
  92. package/dist/prosemirror/runPropertyChangeResolution.js +0 -34
@@ -1,4 +1,5 @@
1
1
  import { CanonicalSessionError } from "../canonical/canonicalSession.js";
2
+ import { retainMarkupViewSource } from "../prosemirror/conversion/markupViewSource.js";
2
3
  import { adoptNativeSelection, isCompositionKeyDown } from "../prosemirror/nativeSelection.js";
3
4
  import { CANONICAL_CONDITION } from "../types/canonicalCapabilities.js";
4
5
  import { createCanonicalInputBoundary, unclassifiedMutationMessage } from "./canonicalInput.js";
@@ -116,6 +117,7 @@ const createCanonicalStoryEditor = ({ story, getView, getApi, onRefusal, onSelec
116
117
  view.updateState(view.state);
117
118
  return;
118
119
  }
120
+ retainMarkupViewSource(view.state, applied.state);
119
121
  view.updateState(applied.state);
120
122
  if (applied.transactions.some((step) => step.selectionSet)) {
121
123
  getApi()?.noteCanonicalStoryView({
@@ -15,6 +15,7 @@ import { canonicalSelectionRange } from "../prosemirror/canonicalSelectionRange.
15
15
  import { registerClipboardIntentHandler } from "../prosemirror/clipboardIntent.js";
16
16
  import { pasteWithoutFormatting } from "../prosemirror/commands/pastePlainText.js";
17
17
  import { createCommentRecordsPlugin, isCommentRecordsSync } from "../prosemirror/commentRecords.js";
18
+ import { retainMarkupViewSource } from "../prosemirror/conversion/markupViewSource.js";
18
19
  import { createEmptyDoc, toProseDoc } from "../prosemirror/conversion/toProseDoc.js";
19
20
  import { registerEditorCommandOwner } from "../prosemirror/executeEditorCommand.js";
20
21
  import { ensureBaseDirectionInState } from "../prosemirror/extensions/features/AutoBidiDetectionExtension.js";
@@ -732,6 +733,7 @@ const createHiddenEditorManager = (hostDeps) => {
732
733
  return;
733
734
  }
734
735
  const documentEdits = applied.transactions.filter((appliedTransaction) => appliedTransaction.docChanged && !isCommentRecordsSync(appliedTransaction));
736
+ retainMarkupViewSource(view.state, applied.state);
735
737
  view.updateState(applied.state);
736
738
  const docChanged = documentEdits.length > 0;
737
739
  const selectionChanged = applied.transactions.some((appliedTransaction) => appliedTransaction.selectionSet || appliedTransaction.docChanged && !isCommentRecordsSync(appliedTransaction));
@@ -151,6 +151,31 @@ const IMPORTED_ID_COLLISION_REGISTRY = {
151
151
  encoding: "string"
152
152
  }
153
153
  };
154
+ /**
155
+ * The rules naming each element local name, in registry order, each with the
156
+ * namespaces it names that local name in: most elements of a part are named by
157
+ * no rule, and are passed over without resolving their namespace.
158
+ */
159
+ const RULES_BY_LOCAL_NAME = (() => {
160
+ const index = /* @__PURE__ */ new Map();
161
+ for (const rule of Object.values(IMPORTED_ID_COLLISION_REGISTRY)) for (const site of rule.sites) for (const localName of site.elements) {
162
+ let rules = index.get(localName);
163
+ if (rules === void 0) {
164
+ rules = [];
165
+ index.set(localName, rules);
166
+ }
167
+ let entry = rules.find((candidate) => candidate.rule === rule);
168
+ if (entry === void 0) {
169
+ entry = {
170
+ rule,
171
+ namespaces: /* @__PURE__ */ new Set()
172
+ };
173
+ rules.push(entry);
174
+ }
175
+ entry.namespaces.add(site.namespace);
176
+ }
177
+ return index;
178
+ })();
154
179
  const normalizedIdentity = (value, encoding) => {
155
180
  if (encoding === "string") return value;
156
181
  if (encoding === "hex") return /^[0-9a-f]{8}$/iu.test(value) ? value.toUpperCase() : void 0;
@@ -161,18 +186,18 @@ const normalizedIdentity = (value, encoding) => {
161
186
  };
162
187
  /** Reports repeated source definitions without changing the package or choosing a winner. */
163
188
  const diagnoseImportedIdCollisions = (parts, context) => {
164
- const rules = Object.values(IMPORTED_ID_COLLISION_REGISTRY);
165
189
  const packageSeen = /* @__PURE__ */ new Map();
166
190
  for (const [part, xml] of parts) {
167
191
  const partSeen = /* @__PURE__ */ new Map();
168
192
  const scoped = context.scoped({ part });
169
193
  scanSelectedStreamingXmlElements(xml, ({ element, attributeValueSpans }) => {
170
194
  if (element.name === void 0) return;
195
+ const candidates = RULES_BY_LOCAL_NAME.get(getLocalName(element.name));
196
+ if (candidates === void 0) return;
171
197
  const namespace = toTransitionalNamespaceUri(getNamespaceUri(element) ?? "");
172
- const localName = getLocalName(element.name);
173
- for (const rule of rules) {
198
+ for (const { rule, namespaces } of candidates) {
174
199
  const kind = rule.kind;
175
- if (!rule.sites.some((site) => namespace === site.namespace && site.elements.has(localName))) continue;
200
+ if (!namespaces.has(namespace)) continue;
176
201
  const paragraphIdentity = paragraphIdentityForKind(kind, element);
177
202
  const seen = rule.scope === "package" ? packageSeen : partSeen;
178
203
  for (const [name, rawValue] of Object.entries(element.attributes ?? {})) {
@@ -428,8 +428,8 @@ const linkedRevisionContent = (wrapped, linkOver) => {
428
428
  };
429
429
  const hoistRevision = (wrapper) => (child, { styles, theme, rels, media, previews, inScopeXmlns, items, linkOver }) => {
430
430
  const wrapped = parseParagraphContents(child, styles, theme, null, rels, media, previews, TRACKED_CHANGE_PARSE_CONTEXT[wrapper], inScopeXmlns, "hyperlink");
431
- const content = linkedRevisionContent(wrapped, linkOver);
432
431
  const split = parseSplitResolutionPiece(child);
432
+ const content = wrapped.length === 0 && split !== void 0 ? [linkOver([])] : linkedRevisionContent(wrapped, linkOver);
433
433
  const resolutionJoins = parseResolutionJoins(child);
434
434
  items.push({
435
435
  type: "hoistedRevision",
@@ -73,6 +73,8 @@ export declare const serializeSplitResolutionPiece: (value: SplitResolutionPiece
73
73
  */
74
74
  export declare const parseParagraphPropertyChangeOwner: (node: XmlElement) => Pick<document_d_exports.ParagraphPropertyChange, "resolvesWith">;
75
75
  export declare const serializeParagraphPropertyChangeOwner: (change: document_d_exports.ParagraphPropertyChange) => string;
76
+ export declare const parseTableGeometryChange: (node: XmlElement) => Pick<document_d_exports.TableGridChange, "geometryChange">;
77
+ export declare const serializeTableGeometryChange: (change: document_d_exports.TableGridChange) => string;
76
78
  /**
77
79
  * Why the reader drops a provenance attribute's value, or `undefined` when it
78
80
  * reads it (or does not read that attribute at all).
@@ -490,6 +490,25 @@ const serializeParagraphPropertyChangeOwner = (change) => serializeAttribute({
490
490
  value: change.resolvesWith,
491
491
  valid: isRevisionId
492
492
  });
493
+ const TABLE_GEOMETRY_CHANGE = "tableGeometryChange";
494
+ const isTableGeometryChange = (value) => {
495
+ if (!record(value) || value["type"] !== "deleteColumn" && value["type"] !== "mergeCells" || Object.keys(value).some((key) => key !== "type" && key !== "revisionIds")) return false;
496
+ const ids = value["revisionIds"];
497
+ return Array.isArray(ids) && ids.length > 0 && ids.every(isRevisionId) && new Set(ids).size === ids.length;
498
+ };
499
+ const parseTableGeometryChange = (node) => {
500
+ const geometryChange = parseAttribute({
501
+ node,
502
+ attribute: TABLE_GEOMETRY_CHANGE,
503
+ valid: isTableGeometryChange
504
+ });
505
+ return geometryChange === void 0 ? {} : { geometryChange };
506
+ };
507
+ const serializeTableGeometryChange = (change) => serializeAttribute({
508
+ attribute: TABLE_GEOMETRY_CHANGE,
509
+ value: change.geometryChange,
510
+ valid: isTableGeometryChange
511
+ });
493
512
  /** Every provenance attribute folio reads, with the shape its value must have. */
494
513
  const PROVENANCE_VALUE_SHAPES = {
495
514
  resolutionJoins: isStoredJoinsOf,
@@ -501,7 +520,8 @@ const PROVENANCE_VALUE_SHAPES = {
501
520
  [ENCLOSING_ATTRIBUTE]: enclosingHandoffs,
502
521
  [PARAGRAPH_MARK_FIELDS.survivor.attribute]: isParagraphMarkSurvivor,
503
522
  [PARAGRAPH_MARK_FIELDS.splitDate.attribute]: isParagraphMarkSplitDate,
504
- resolvesWith: isRevisionId
523
+ resolvesWith: isRevisionId,
524
+ [TABLE_GEOMETRY_CHANGE]: isTableGeometryChange
505
525
  };
506
526
  /**
507
527
  * Why the reader drops a provenance attribute's value, or `undefined` when it
@@ -513,4 +533,4 @@ const reviewProvenanceIssue = (attribute, encoded) => {
513
533
  const decoded = decodeProvenance(encoded, shape);
514
534
  return decoded.status === "dropped" ? decoded.reason : void 0;
515
535
  };
516
- export { REVIEW_HISTORY_VERSION, ReviewResolutionProvenanceError, isBoundaryJoins, isParagraphMarkResolutionJoin, isResolutionJoins, isSplitResolutionPiece, legacyKeptCutPiece, paragraphMarkResolutionJoinAttributes, parseBoundaryJoins, parseCopyOriginAncestors, parseKeptCut, parseParagraphMarkResolutionJoin, parseParagraphPropertyChangeOwner, parseResolutionJoins, parseSplitResolutionPiece, reviewProvenanceIssue, serializeBoundaryJoins, serializeCopyOriginAncestors, serializeKeptCut, serializeParagraphMarkResolutionJoin, serializeParagraphPropertyChangeOwner, serializeResolutionJoins, serializeSplitResolutionPiece, versionOneKeptMarkers };
536
+ export { REVIEW_HISTORY_VERSION, ReviewResolutionProvenanceError, isBoundaryJoins, isParagraphMarkResolutionJoin, isResolutionJoins, isSplitResolutionPiece, legacyKeptCutPiece, paragraphMarkResolutionJoinAttributes, parseBoundaryJoins, parseCopyOriginAncestors, parseKeptCut, parseParagraphMarkResolutionJoin, parseParagraphPropertyChangeOwner, parseResolutionJoins, parseSplitResolutionPiece, parseTableGeometryChange, reviewProvenanceIssue, serializeBoundaryJoins, serializeCopyOriginAncestors, serializeKeptCut, serializeParagraphMarkResolutionJoin, serializeParagraphPropertyChangeOwner, serializeResolutionJoins, serializeSplitResolutionPiece, serializeTableGeometryChange, versionOneKeptMarkers };
@@ -4,13 +4,13 @@ import { spliceXml } from "../../selectiveXmlPatch.js";
4
4
  import { NAMESPACES, getLocalName } from "../../xmlParser.js";
5
5
  import { appendToXmlRoot } from "../../xmlRootInsertion.js";
6
6
  import { analyzeDocument, analyzeSource, viewOf } from "./blocks.js";
7
- import { freezeFields, inheritedReferencesXml, sectionPropertiesXml, setKeepShiftReturnSpacing, setUpdateFieldsOnOpen, withoutContained } from "./builders.js";
7
+ import { bookmarkIdsOf, freezeFields, inheritedReferencesXml, sectionPropertiesXml, setKeepShiftReturnSpacing, setTrackingOff, setUpdateFieldsOnOpen, withoutContained } from "./builders.js";
8
8
  import { removeInvisibleEffects } from "./effects.js";
9
9
  import { createRelationshipsEditor, noteXml, paragraphContentXml, paragraphXml, tableXml, templateCharacterStyles } from "./emit.js";
10
10
  import { readHeaderFooterParts } from "./inspect.js";
11
11
  import { styleNumbering } from "./labels.js";
12
12
  import { guarded, readPartText, relationshipsPathFor } from "./package.js";
13
- import { resolvePlan } from "./plan.js";
13
+ import { fieldSeparatorRun, resolvePlan } from "./plan.js";
14
14
  import { readStoryResources } from "./resources.js";
15
15
  import { TemplatePlanError } from "./types.js";
16
16
  import { reportTemplatePlanOutput } from "./verify.js";
@@ -69,6 +69,8 @@ const RANGE_MARKERS = [["bookmarkStart", "bookmarkEnd"], ["commentRangeStart", "
69
69
  * Splices removing range markers whose other half the output does not carry:
70
70
  * a bookmark or comment range that started in a block the plan dropped.
71
71
  */
72
+ /** How far above the bookmarks' ids the ids of kept tracked changes start. */
73
+ const REVISION_ID_OFFSET = 1e5;
72
74
  const orphanMarkerSplices = ({ kept, replaced }) => {
73
75
  const splices = [];
74
76
  for (const [startName, endName] of RANGE_MARKERS) {
@@ -363,6 +365,7 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
363
365
  const media = /* @__PURE__ */ new Map();
364
366
  const mediaPaths = /* @__PURE__ */ new Set();
365
367
  let unsupportedMedia = null;
368
+ let revisionId = maxOf(bookmarkIdsOf(template.document.root), 0) + REVISION_ID_OFFSET;
366
369
  let drawingId = 0;
367
370
  const noteDrawingIds = (root) => {
368
371
  walkElements(root, (element) => {
@@ -413,6 +416,10 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
413
416
  nextDrawingId: () => {
414
417
  drawingId += 1;
415
418
  return drawingId;
419
+ },
420
+ nextRevisionId: () => {
421
+ revisionId += 1;
422
+ return revisionId;
416
423
  }
417
424
  };
418
425
  const documentContext = {
@@ -474,6 +481,36 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
474
481
  end: inner.end
475
482
  });
476
483
  }
484
+ for (const { element } of resolved.emptied) {
485
+ const inner = innerRangeOf(template.document.xml, element);
486
+ if (inner === null) continue;
487
+ const properties = wChild(element, "pPr");
488
+ const start = (properties === null ? null : rangeOf(properties)?.end) ?? inner.start;
489
+ templateSplices.push({
490
+ start,
491
+ end: inner.end,
492
+ newXml: ""
493
+ });
494
+ replaced.push({
495
+ start,
496
+ end: inner.end
497
+ });
498
+ }
499
+ for (const { element } of resolved.emptiedContents.keys()) {
500
+ const start = rangeOf(fieldSeparatorRun(element) ?? element)?.end;
501
+ const inner = innerRangeOf(template.document.xml, element);
502
+ if (start === void 0 || inner === null) continue;
503
+ const { w } = documentContext.prefixes;
504
+ templateSplices.push({
505
+ start,
506
+ end: inner.end,
507
+ newXml: `<${w}:r><${w}:fldChar ${w}:fldCharType="end"/></${w}:r>`
508
+ });
509
+ replaced.push({
510
+ start,
511
+ end: inner.end
512
+ });
513
+ }
477
514
  const keptElements = [
478
515
  ...resolved.keptTemplateBlocks.map(({ element }) => element),
479
516
  ...resolved.items.flatMap((item) => item.kind === "slot" ? [item.templateBlock.element] : []),
@@ -670,6 +707,14 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
670
707
  if (settings === null) return Result.err(unreadable(settingsPath, "The settings part could not be updated."));
671
708
  if (settings !== settingsXml.value) parts.set(settingsPath, settings);
672
709
  }
710
+ if (plan.trackedChanges === "keep") {
711
+ const settingsPath = pkg.partPath("settings");
712
+ const written = settingsPath === null ? void 0 : parts.get(settingsPath);
713
+ const settingsXml = typeof written === "string" ? Result.ok(written) : await readTemplateText(settingsPath);
714
+ if (Result.isError(settingsXml)) return settingsXml;
715
+ const settings = settingsXml.value === null ? null : setTrackingOff(settingsXml.value);
716
+ if (settingsPath !== null && settings !== null && settings !== settingsXml.value) parts.set(settingsPath, settings);
717
+ }
673
718
  if (plan.textEffects !== "keep") {
674
719
  const kept = [
675
720
  [pkg.documentPath, documentXml],
@@ -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, DocxSection, TemplatePlanError, TemplatePlanTrackedView } from "./types.js";
10
+ import { DocxBlock, DocxBlockManifest, DocxSection, TemplatePlanError, TemplatePlanTrackedChanges } 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;
@@ -95,13 +95,22 @@ export declare const styleLook: (styleId: string | null, styles: StyleMap, { sty
95
95
  * properties of its own still ends in a section, which states nothing.
96
96
  */
97
97
  export declare const storySections: ({ sections, hasBodySection }: AnalyzedStory) => DocxSection[];
98
+ /**
99
+ * Whether a bookmark of `read` holds all of the paragraph's content. In a
100
+ * reading that keeps tracked changes the paragraph's own content begins
101
+ * behind the last paragraph mark deleted in it (what stands in front is the
102
+ * paragraph the mark ended) and ends in front of a mark somebody inserted.
103
+ */
104
+ export declare const bookmarkEncloses: (read: ParagraphRead | null, name: string) => boolean;
98
105
  type AnalyzeStoryOptions = {
99
106
  container: XmlElement;
100
107
  resources: StoryResources;
101
108
  counter?: LabelCounter;
109
+ /** Read inline insertions and deletions as tagged atoms. */
110
+ keepsRevisions?: boolean;
102
111
  };
103
112
  /** Read the blocks under `container` into ids, text, labels and hashes. */
104
- export declare const analyzeStory: ({ container, resources, counter }: AnalyzeStoryOptions) => AnalyzedStory;
113
+ export declare const analyzeStory: ({ container, resources, counter, keepsRevisions }: AnalyzeStoryOptions) => AnalyzedStory;
105
114
  export type AnalyzedNote = {
106
115
  id: string;
107
116
  element: XmlElement;
@@ -140,10 +149,27 @@ export type AnalyzedDocument = {
140
149
  manifest: DocxBlockManifest;
141
150
  };
142
151
  /** Open a package and analyse its main story, notes, styles and numbering. */
143
- export declare const analyzeDocument: (bytes: Uint8Array) => Promise<Result<AnalyzedDocument, TemplatePlanError>>;
152
+ export declare const analyzeDocument: (bytes: Uint8Array, { keepsRevisions }?: {
153
+ keepsRevisions?: boolean;
154
+ }) => Promise<Result<AnalyzedDocument, TemplatePlanError>>;
144
155
  /** The view a plan states, when what was handed in is shaped like a plan
145
156
  * at all; its shape is checked where the plan is resolved. */
146
- export declare const viewOf: (plan: unknown) => TemplatePlanTrackedView | undefined;
157
+ export declare const viewOf: (plan: unknown) => TemplatePlanTrackedChanges | undefined;
158
+ /**
159
+ * A source read with its tracked changes kept: the blocks are those of the
160
+ * accepted view, and the atoms of an insertion or a deletion carry its tag,
161
+ * a paragraph mark's among them; an inserted table row keeps its record and
162
+ * a deleted one is set aside whole. A change that is not carried yet (a
163
+ * table cell, a move) or cannot be tagged is refused with what stands in the
164
+ * way, for the caller to offer one view instead.
165
+ */
166
+ /**
167
+ * A document read with its tracked changes kept, source or output alike:
168
+ * deleted paragraph marks carried as deletions inside the joined paragraph,
169
+ * inline insertions and deletions as tagged atoms. The manifest keeps the
170
+ * hash of the bytes that were given.
171
+ */
172
+ export declare const analyzeKeptForm: (bytes: Uint8Array) => Promise<Result<AnalyzedDocument, TemplatePlanError>>;
147
173
  /**
148
174
  * Analyse a source in the view a caller chose of its tracked changes, or
149
175
  * as it stands. In a view, the package that is analysed is the resolved
@@ -151,14 +177,15 @@ export declare const viewOf: (plan: unknown) => TemplatePlanTrackedView | undefi
151
177
  * plan pins the file, not a rewriting of it. Without a view, a document
152
178
  * that tracks changes says what it tracks.
153
179
  */
154
- export declare const analyzeSource: (bytes: Uint8Array, view: TemplatePlanTrackedView | undefined) => Promise<Result<AnalyzedDocument, TemplatePlanError>>;
180
+ export declare const analyzeSource: (bytes: Uint8Array, view: TemplatePlanTrackedChanges | undefined) => Promise<Result<AnalyzedDocument, TemplatePlanError>>;
155
181
  /**
156
182
  * Read a DOCX into the blocks a template plan addresses: ids, visible text,
157
183
  * rendered list labels, styles and a hash per block, plus its notes. With
158
184
  * `trackedChanges`, the blocks are those of that view of a document with
159
- * tracked changes.
185
+ * tracked changes; with `keep`, those of the accepted view, read off the
186
+ * document as it stands, or the refusal a plan that keeps them would get.
160
187
  */
161
188
  export declare const analyzeDocxBlocks: (docx: Uint8Array, options?: {
162
- trackedChanges?: TemplatePlanTrackedView;
189
+ trackedChanges?: TemplatePlanTrackedChanges;
163
190
  }) => Promise<Result<DocxBlockManifest, TemplatePlanError>>;
164
191
  export {};
@@ -1,11 +1,11 @@
1
1
  import { parseNumbering } from "../../numberingParser.js";
2
2
  import { parseSectionProperties } from "../../sectionParser.js";
3
3
  import { parseStylesPackage } from "../../styleParser.js";
4
- import { keepsShiftReturnSpacing } from "./builders.js";
4
+ import { fieldBookmarkOf, keepsShiftReturnSpacing } from "./builders.js";
5
5
  import { defaultsBaseline } from "./emphasis.js";
6
6
  import { createLabelCounter } from "./labels.js";
7
7
  import { guarded, loadPackage, readPartText, sha256Hex } from "./package.js";
8
- import { resolveTrackedChanges } from "./revisions.js";
8
+ import { keptRevisionObstacles, resolveTrackedChanges, withDeletedMarksJoined } from "./revisions.js";
9
9
  import { createStoryState, endStory, readParagraph, toggleOf, walkBlocks } from "./story.js";
10
10
  import { TemplatePlanError } from "./types.js";
11
11
  import { elementChildren, halfPointsOrNull, integerOrNull, isW, readRawPart, twipsOrNull, wAttr, wChild, wChildVal, wChildren } from "./xml.js";
@@ -210,9 +210,106 @@ const selfNumbersOf = ({ atoms }) => {
210
210
  }
211
211
  return offsets;
212
212
  };
213
+ /**
214
+ * Whether a bookmark of `read` holds all of the paragraph's content. In a
215
+ * reading that keeps tracked changes the paragraph's own content begins
216
+ * behind the last paragraph mark deleted in it (what stands in front is the
217
+ * paragraph the mark ended) and ends in front of a mark somebody inserted.
218
+ */
219
+ const bookmarkEncloses = (read, name) => {
220
+ const start = read?.bookmarks.find((bookmark) => bookmark.name === name);
221
+ const end = start === void 0 ? void 0 : read?.bookmarkEnds.find(({ id }) => id === start.id);
222
+ if (read === null || start === void 0 || end === void 0) return false;
223
+ const own = read.atoms.findLastIndex(({ revision }) => revision?.deleted === "") + 1;
224
+ const marked = read.atoms.at(-1)?.revision?.mark === true ? 1 : 0;
225
+ return start.atomIndex === own && end.atomIndex === read.atoms.length - marked;
226
+ };
227
+ /**
228
+ * The `REF` fields of a paragraph whose result stands in its text: begun
229
+ * and ended in it, in the code of no field and in the result of no other.
230
+ */
231
+ const crossReferencesOf = (read, state) => {
232
+ const spans = /* @__PURE__ */ new Map();
233
+ let at = 0;
234
+ for (const { text, fields } of read.atoms) {
235
+ const start = at;
236
+ at += text.length;
237
+ for (const [depth, index] of fields.entries()) {
238
+ const span = spans.get(index);
239
+ if (span === void 0) spans.set(index, {
240
+ start,
241
+ end: at,
242
+ outermost: depth === 0
243
+ });
244
+ else {
245
+ span.end = at;
246
+ span.outermost &&= depth === 0;
247
+ }
248
+ }
249
+ }
250
+ const found = [];
251
+ for (const [index, { start, end, outermost }] of spans) {
252
+ const field = state.fields[index];
253
+ const bookmark = field === void 0 ? null : fieldBookmarkOf(field.instruction);
254
+ if (field === void 0 || bookmark === null || field.kind !== "REF" || !field.closed || field.nestedInCode || !outermost || start === end || field.paragraphOrdinal !== read.ordinal || field.endParagraphOrdinal !== read.ordinal) continue;
255
+ found.push({
256
+ start,
257
+ end,
258
+ instruction: field.instruction,
259
+ bookmark
260
+ });
261
+ }
262
+ return found;
263
+ };
264
+ /**
265
+ * Where each bookmark of a story stands: the paragraph it starts and ends
266
+ * in, and whether it holds all of its content. Null for one that ends in
267
+ * another paragraph or not at all. The first bookmark of a name counts.
268
+ */
269
+ const bookmarkTargetsOf = (story) => {
270
+ const targets = /* @__PURE__ */ new Map();
271
+ for (const { block, read } of story.order) for (const start of read?.bookmarks ?? []) {
272
+ if (targets.has(start.name)) continue;
273
+ const end = read?.bookmarkEnds.find(({ id }) => id === start.id);
274
+ targets.set(start.name, end === void 0 || end.atomIndex < start.atomIndex ? null : {
275
+ blockId: block.id,
276
+ whole: bookmarkEncloses(read, start.name)
277
+ });
278
+ }
279
+ return targets;
280
+ };
281
+ /**
282
+ * The tracked changes a paragraph read with them kept holds, by where they
283
+ * sit in its text. Neighbouring pieces of one change are one entry.
284
+ */
285
+ const revisionsOf = ({ atoms }) => {
286
+ const found = [];
287
+ let at = 0;
288
+ for (const { text, revision } of atoms) {
289
+ const start = at;
290
+ at += text.length;
291
+ if (revision === void 0) continue;
292
+ const kind = revision.kind === "ins" ? "insertion" : "deletion";
293
+ const paragraphMark = revision.mark === true || revision.deleted === "";
294
+ const last = found.at(-1);
295
+ if (last !== void 0 && !paragraphMark && last.paragraphMark === void 0 && last.kind === kind && last.end === start && last.author === revision.author && last.date === revision.date) {
296
+ last.end = at;
297
+ continue;
298
+ }
299
+ found.push({
300
+ kind,
301
+ start,
302
+ end: at,
303
+ author: revision.author,
304
+ date: revision.date,
305
+ ...paragraphMark ? { paragraphMark: true } : {}
306
+ });
307
+ }
308
+ return found;
309
+ };
213
310
  /** Read the blocks under `container` into ids, text, labels and hashes. */
214
- const analyzeStory = ({ container, resources, counter = createLabelCounter(resources) }) => {
215
- const state = createStoryState();
311
+ const analyzeStory = ({ container, resources, counter = createLabelCounter(resources), keepsRevisions = false }) => {
312
+ const state = createStoryState({ keepsRevisions });
216
313
  const story = {
217
314
  topLevel: [],
218
315
  order: [],
@@ -228,6 +325,7 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
228
325
  let index = 0;
229
326
  let sectionIndex = 0;
230
327
  const unread = /* @__PURE__ */ new Map();
328
+ const fieldsToBookmarks = /* @__PURE__ */ new Map();
231
329
  const register = (analyzed) => {
232
330
  story.order.push(analyzed);
233
331
  story.byId.set(analyzed.block.id, analyzed);
@@ -268,14 +366,24 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
268
366
  ...read.paraId === null ? {} : { paraId: read.paraId },
269
367
  inlineObjects: read.inlineObjects
270
368
  };
369
+ if (read.pageShapes > 0) block.pageShapes = read.pageShapes;
271
370
  const pageBreaks = pageBreaksOf(read);
272
371
  if (pageBreaks > 0) block.pageBreaks = pageBreaks;
273
372
  const selfNumbers = selfNumbersOf(read);
274
373
  if (selfNumbers.length > 0) block.selfNumbers = selfNumbers;
374
+ const revisions = revisionsOf(read);
375
+ if (revisions.length > 0) block.revisions = revisions;
376
+ const references = crossReferencesOf(read, state);
377
+ if (references.length > 0) fieldsToBookmarks.set(block, references);
275
378
  if (read.pageBreakBefore ?? style?.pPr?.pageBreakBefore === true) block.pageBreakBefore = true;
276
379
  if (read.hasSectionBreak) block.endsSection = true;
277
380
  const alignment = read.alignment ?? (resources.alignments === void 0 ? null : styleAlignment(styleId ?? resources.defaultStyleId, resources.styles, resources.alignments));
278
381
  if (alignment !== null) block.alignment = alignment;
382
+ const { before, after } = read.spacing;
383
+ if (before !== null || after !== null) block.spacing = {
384
+ ...before === null ? {} : { before },
385
+ ...after === null ? {} : { after }
386
+ };
279
387
  const ofLevel = (label.numbering === null ? void 0 : resources.levelIndents?.get(levelKey(label.numbering.abstractNumId, label.numbering.ilvl))) ?? NO_INDENT;
280
388
  const ofStyle = modelIndent(style?.pPr);
281
389
  const ofDefaults = resources.defaultIndent ?? NO_INDENT;
@@ -373,6 +481,20 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
373
481
  state.trackedChanges += 1;
374
482
  }
375
483
  });
484
+ if (fieldsToBookmarks.size > 0) {
485
+ const targets = bookmarkTargetsOf(story);
486
+ for (const [block, references] of fieldsToBookmarks) block.crossReferences = references.map(({ start, end, instruction, bookmark }) => {
487
+ const target = targets.get(bookmark) ?? null;
488
+ return {
489
+ start,
490
+ end,
491
+ instruction,
492
+ bookmark,
493
+ targetBlockId: target?.blockId ?? null,
494
+ targetWhole: target?.whole ?? false
495
+ };
496
+ });
497
+ }
376
498
  const bodySection = wChild(container, "sectPr");
377
499
  if (bodySection !== null) {
378
500
  story.sections.push(bodySection);
@@ -389,7 +511,7 @@ const NOTE_ELEMENT = {
389
511
  footnotes: "footnote",
390
512
  endnotes: "endnote"
391
513
  };
392
- const analyzeNotes = (kind, path, xml) => {
514
+ const analyzeNotes = (kind, path, xml, keepsRevisions = false) => {
393
515
  const notes = {
394
516
  kind,
395
517
  path,
@@ -397,7 +519,7 @@ const analyzeNotes = (kind, path, xml) => {
397
519
  notes: [],
398
520
  byId: /* @__PURE__ */ new Map(),
399
521
  usedIds: [],
400
- state: createStoryState()
522
+ state: createStoryState({ keepsRevisions })
401
523
  };
402
524
  if (path === null || xml === null) return notes;
403
525
  const part = readRawPart(path, xml);
@@ -455,7 +577,7 @@ const countComments = (xml) => {
455
577
  return part === null ? 0 : elementChildren(part.root).filter(({ name }) => (name ?? "").endsWith("comment")).length;
456
578
  };
457
579
  /** Open a package and analyse its main story, notes, styles and numbering. */
458
- const analyzeDocument = async (bytes) => {
580
+ const analyzeDocument = async (bytes, { keepsRevisions = false } = {}) => {
459
581
  const loaded = await loadPackage(bytes);
460
582
  if (Result.isError(loaded)) return loaded;
461
583
  const pkg = loaded.value;
@@ -519,10 +641,11 @@ const analyzeDocument = async (bytes) => {
519
641
  alignments: statedAlignments(stylesPath, stylesXml),
520
642
  levelIndents: statedLevelIndents(numberingPath, numberingXml),
521
643
  defaultIndent: statedDefaultIndent(stylesPath, stylesXml)
522
- }
644
+ },
645
+ keepsRevisions
523
646
  }),
524
- footnotes: analyzeNotes("footnotes", footnotesPath, footnotesXml),
525
- endnotes: analyzeNotes("endnotes", endnotesPath, endnotesXml)
647
+ footnotes: analyzeNotes("footnotes", footnotesPath, footnotesXml, keepsRevisions),
648
+ endnotes: analyzeNotes("endnotes", endnotesPath, endnotesXml, keepsRevisions)
526
649
  };
527
650
  },
528
651
  catch: (cause) => cause instanceof TemplatePlanError ? cause : new TemplatePlanError({
@@ -569,7 +692,59 @@ const analyzeDocument = async (bytes) => {
569
692
  * at all; its shape is checked where the plan is resolved. */
570
693
  const viewOf = (plan) => {
571
694
  const view = typeof plan === "object" && plan !== null && "trackedChanges" in plan ? plan.trackedChanges : void 0;
572
- return view === "accept" || view === "reject" ? view : void 0;
695
+ return view === "accept" || view === "reject" || view === "keep" ? view : void 0;
696
+ };
697
+ /**
698
+ * A source read with its tracked changes kept: the blocks are those of the
699
+ * accepted view, and the atoms of an insertion or a deletion carry its tag,
700
+ * a paragraph mark's among them; an inserted table row keeps its record and
701
+ * a deleted one is set aside whole. A change that is not carried yet (a
702
+ * table cell, a move) or cannot be tagged is refused with what stands in the
703
+ * way, for the caller to offer one view instead.
704
+ */
705
+ /**
706
+ * A document read with its tracked changes kept, source or output alike:
707
+ * deleted paragraph marks carried as deletions inside the joined paragraph,
708
+ * inline insertions and deletions as tagged atoms. The manifest keeps the
709
+ * hash of the bytes that were given.
710
+ */
711
+ const analyzeKeptForm = async (bytes) => {
712
+ const joined = await withDeletedMarksJoined(bytes);
713
+ if (Result.isError(joined)) return joined;
714
+ const analyzed = await analyzeDocument(joined.value, { keepsRevisions: true });
715
+ if (Result.isError(analyzed)) return analyzed;
716
+ return Result.ok({
717
+ ...analyzed.value,
718
+ manifest: {
719
+ ...analyzed.value.manifest,
720
+ sha256: sha256Hex(bytes)
721
+ }
722
+ });
723
+ };
724
+ const analyzeKeeping = async (bytes) => {
725
+ const obstacles = await keptRevisionObstacles(bytes);
726
+ if (Result.isError(obstacles)) return obstacles;
727
+ const analyzed = await analyzeKeptForm(bytes);
728
+ if (Result.isError(analyzed)) return analyzed;
729
+ const { story, footnotes, endnotes, manifest } = analyzed.value;
730
+ const untagged = story.state.untaggedRevisions + footnotes.state.untaggedRevisions + endnotes.state.untaggedRevisions;
731
+ const { tableCells, moves } = obstacles.value.obstacles;
732
+ const found = [
733
+ [tableCells, "table cell change(s)"],
734
+ [moves, "move(s)"],
735
+ [untagged, "change(s) inside another change, a drawing or an equation, or deleted paragraph mark(s) with no paragraph to join"]
736
+ ].flatMap(([count, what]) => typeof count === "number" && count > 0 ? [`${String(count)} ${what}`] : []);
737
+ if (found.length > 0) return Result.err(new TemplatePlanError({
738
+ code: "tracked-changes",
739
+ message: `The tracked changes of the source cannot be kept: ${found.join(", ")}. Format one view of it instead.`
740
+ }));
741
+ return Result.ok({
742
+ ...analyzed.value,
743
+ manifest: {
744
+ ...manifest,
745
+ trackedChangesKept: obstacles.value.tracked
746
+ }
747
+ });
573
748
  };
574
749
  /**
575
750
  * Analyse a source in the view a caller chose of its tracked changes, or
@@ -579,6 +754,7 @@ const viewOf = (plan) => {
579
754
  * that tracks changes says what it tracks.
580
755
  */
581
756
  const analyzeSource = async (bytes, view) => {
757
+ if (view === "keep") return await analyzeKeeping(bytes);
582
758
  if (view === void 0) {
583
759
  const analyzed = await analyzeDocument(bytes);
584
760
  if (Result.isError(analyzed) || analyzed.value.manifest.trackedChanges === 0) return analyzed;
@@ -611,7 +787,8 @@ const analyzeSource = async (bytes, view) => {
611
787
  * Read a DOCX into the blocks a template plan addresses: ids, visible text,
612
788
  * rendered list labels, styles and a hash per block, plus its notes. With
613
789
  * `trackedChanges`, the blocks are those of that view of a document with
614
- * tracked changes.
790
+ * tracked changes; with `keep`, those of the accepted view, read off the
791
+ * document as it stands, or the refusal a plan that keeps them would get.
615
792
  */
616
793
  const analyzeDocxBlocks = async (docx, options = {}) => await guarded(async () => (await analyzeSource(docx, options.trackedChanges)).map(({ manifest }) => manifest));
617
- export { analyzeDocument, analyzeDocxBlocks, analyzeSource, analyzeStory, blockHash, statedAlignments, statedLooks, storySections, styleAlignment, styleLook, styleOutlineLevel, viewOf };
794
+ export { analyzeDocument, analyzeDocxBlocks, analyzeKeptForm, analyzeSource, analyzeStory, blockHash, bookmarkEncloses, statedAlignments, statedLooks, storySections, styleAlignment, styleLook, styleOutlineLevel, viewOf };
@@ -47,7 +47,8 @@ export declare const applyRefCaseFormat: (text: string, format: ReturnType<typeo
47
47
  /**
48
48
  * The field code of a REF to `bookmark` with `switches` (`\n \t \h`,
49
49
  * `\n \* lower \h`). Null when the switches hold anything but
50
- * single-letter switches and one letter-case format.
50
+ * single-letter switches, one letter-case format and one format that
51
+ * keeps the result's look.
51
52
  */
52
53
  export declare const refFieldInstruction: (bookmark: string, switches: string) => string | null;
53
54
  /** The bookmark a REF, PAGEREF or NOTEREF instruction names. */
@@ -57,6 +58,12 @@ export declare const fieldBookmarkOf: (instruction: string) => string | null;
57
58
  * place in the schema's child order. Null when the part is not a settings part.
58
59
  */
59
60
  export declare const setUpdateFieldsOnOpen: (settingsXml: string, enabled: boolean) => string | null;
61
+ /**
62
+ * `settingsXml` without `w:trackRevisions`: a document that carries tracked
63
+ * changes of its source records no new ones until its reader switches
64
+ * tracking on. Null when the part is not a settings part.
65
+ */
66
+ export declare const setTrackingOff: (settingsXml: string) => string | null;
60
67
  /** Whether a settings part keeps the spacing of a justified line that ends
61
68
  * in a manual line break (`w:compat/w:doNotExpandShiftReturn`). */
62
69
  export declare const keepsShiftReturnSpacing: (settingsXml: string) => boolean;