@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
@@ -91,6 +91,8 @@ export declare const resolveCleanTextRange: ({ cleanBlock, startOffset, endOffse
91
91
  } | null;
92
92
  /** Whether the clean view leaves out an inline node. */
93
93
  export declare const isOmittedFromCleanView: (node: Node) => boolean;
94
+ /** Read inline text the way the saved story reads it, with proposals rejected. */
95
+ export declare const isOmittedFromSavedSuggestionText: (node: Node) => boolean;
94
96
  export type BuildCleanBlockTextOptions = {
95
97
  /**
96
98
  * `"text"` reads a field as the result Word shows, which is the view a reader
@@ -107,8 +109,9 @@ export type BuildCleanBlockTextOptions = {
107
109
  * documents' editor text wants.
108
110
  */
109
111
  noteReferences?: NoteReferenceLabels | "sourceText";
112
+ view?: "saved-without-suggestions";
110
113
  };
111
- export declare const buildCleanBlockText: (blockNode: Node, blockFrom: number, { fieldResults, noteReferences }?: BuildCleanBlockTextOptions) => CleanBlockText;
114
+ export declare const buildCleanBlockText: (blockNode: Node, blockFrom: number, { fieldResults, noteReferences, view }?: BuildCleanBlockTextOptions) => CleanBlockText;
112
115
  /**
113
116
  * A "redline-aware" view of a textblock: the same left-to-right traversal as
114
117
  * {@link buildCleanBlockText}, but every tracked change and comment anchor is
@@ -1,4 +1,4 @@
1
- import { expectPageBreakRunAttrs } from "../prosemirror/attrs/index.js";
1
+ import { expectPageBreakRunAttrs, expectTrackedChangeMarkAttrs } from "../prosemirror/attrs/index.js";
2
2
  import { runFormattingInlineAtomCleanText, runFormattingInlineControlCharacter, runFormattingInlineControlNodeName } from "../prosemirror/runFormattingInlineCarriers.js";
3
3
  import { createNoteReferenceNumbering, noteReferenceMarker } from "../utils/noteReferenceLabels.js";
4
4
  import { noteReferenceOf } from "./note-references.js";
@@ -50,6 +50,19 @@ const COMMENT_MARK = "comment";
50
50
  const HIDDEN_MARK = "hidden";
51
51
  /** Whether the clean view leaves out an inline node. */
52
52
  const isOmittedFromCleanView = (node) => node.marks.some((mark) => mark.type.name === DELETION_MARK || mark.type.name === HIDDEN_MARK);
53
+ /** Read inline text the way the saved story reads it, with proposals rejected. */
54
+ const isOmittedFromSavedSuggestionText = (node) => node.marks.some((mark) => {
55
+ const name = mark.type.name;
56
+ if (name === HIDDEN_MARK) return true;
57
+ if (name !== INSERTION_MARK && name !== DELETION_MARK) return false;
58
+ const attrs = expectTrackedChangeMarkAttrs(mark);
59
+ const ancestors = attrs._docxRevisionAncestors ?? [];
60
+ if (ancestors.some(({ type, suggestionId }) => suggestionId !== void 0 && (type === "insertion" || type === "moveTo"))) return true;
61
+ if (attrs.suggestionId === void 0) return name === DELETION_MARK;
62
+ if (name === INSERTION_MARK) return true;
63
+ const kept = ancestors.findLast(({ suggestionId }) => suggestionId === void 0);
64
+ return kept?.type === "deletion" || kept?.type === "moveFrom";
65
+ });
53
66
  const DEFAULT_BUILD_CLEAN_BLOCK_TEXT_OPTIONS = { fieldResults: "text" };
54
67
  /**
55
68
  * The marker a reference reads as: the story's number when the labels know
@@ -63,7 +76,8 @@ const noteReferenceLabelFor = (node, labels, local) => {
63
76
  const { displayNumber } = local().next(reference.noteType, reference.noteId);
64
77
  return noteReferenceMarker(reference.noteType, displayNumber);
65
78
  };
66
- const buildCleanBlockText = (blockNode, blockFrom, { fieldResults, noteReferences } = DEFAULT_BUILD_CLEAN_BLOCK_TEXT_OPTIONS) => {
79
+ const buildCleanBlockText = (blockNode, blockFrom, { fieldResults, noteReferences, view } = DEFAULT_BUILD_CLEAN_BLOCK_TEXT_OPTIONS) => {
80
+ const omitted = view === "saved-without-suggestions" ? isOmittedFromSavedSuggestionText : isOmittedFromCleanView;
67
81
  let text = "";
68
82
  const offsets = [];
69
83
  let structuralBoundaries;
@@ -72,7 +86,7 @@ const buildCleanBlockText = (blockNode, blockFrom, { fieldResults, noteReference
72
86
  let localNumbering;
73
87
  const local = () => localNumbering ??= createNoteReferenceNumbering();
74
88
  blockNode.descendants((node, pos) => {
75
- if (noteReferences !== "sourceText" && node.isText && !isOmittedFromCleanView(node)) {
89
+ if (noteReferences !== "sourceText" && node.isText && !omitted(node)) {
76
90
  const reference = noteReferenceOf(node);
77
91
  const label = reference === null ? null : noteReferenceLabelFor(node, labels, local);
78
92
  if (reference !== null && label !== null) {
@@ -102,7 +116,7 @@ const buildCleanBlockText = (blockNode, blockFrom, { fieldResults, noteReference
102
116
  from,
103
117
  to: from + node.nodeSize,
104
118
  ...clear !== void 0 ? { clear } : {},
105
- presentInCleanView: !node.marks.some(({ type }) => type.name === DELETION_MARK)
119
+ presentInCleanView: view === "saved-without-suggestions" ? !omitted(node) : !node.marks.some(({ type }) => type.name === DELETION_MARK)
106
120
  });
107
121
  return false;
108
122
  }
@@ -111,7 +125,7 @@ const buildCleanBlockText = (blockNode, blockFrom, { fieldResults, noteReference
111
125
  else if (node.type.name === "structuredField") atomText = node.textContent;
112
126
  else atomText = runFormattingInlineAtomCleanText(node);
113
127
  if (atomText !== null) {
114
- if (isOmittedFromCleanView(node)) return false;
128
+ if (omitted(node)) return false;
115
129
  const startPos = blockFrom + 1 + pos;
116
130
  if (atomText.length > 1) (structuralBoundaries ??= []).push({
117
131
  type: "field",
@@ -126,7 +140,7 @@ const buildCleanBlockText = (blockNode, blockFrom, { fieldResults, noteReference
126
140
  return false;
127
141
  }
128
142
  if (!node.isText || node.text === void 0) return true;
129
- if (isOmittedFromCleanView(node)) return false;
143
+ if (omitted(node)) return false;
130
144
  const startPos = blockFrom + 1 + pos;
131
145
  for (let i = 0; i < node.text.length; i++) offsets.push(startPos + i);
132
146
  text += node.text;
@@ -235,4 +249,4 @@ const cleanTextInlineNodes = ({ schema, text, marks = [] }) => {
235
249
  if (trailing.length > 0) nodes.push(schema.text(trailing, marks));
236
250
  return nodes;
237
251
  };
238
- export { buildAnnotatedBlockText, buildAnnotatedBlockTextWithNoteReferences, buildCleanBlockText, cleanTextInlineNodes, isOmittedFromCleanView, resolveCleanTextRange };
252
+ export { buildAnnotatedBlockText, buildAnnotatedBlockTextWithNoteReferences, buildCleanBlockText, cleanTextInlineNodes, isOmittedFromCleanView, isOmittedFromSavedSuggestionText, resolveCleanTextRange };
@@ -1,5 +1,5 @@
1
1
  import { CanonicalRoomBase } from "../canonical/canonicalRoomBase.js";
2
- import { MatchInlineAtomsOptions } from "../compare/inline-atoms.js";
2
+ import { matchInlineAtomsOnModel } from "../compare/inline-atoms-model.js";
3
3
  import { InlineProvenanceTargetOptions } from "../compare/inline-provenance.js";
4
4
  import { ImportReferencedStyleDefinitionsResult } from "../compare/style-resources.js";
5
5
  import { FolioDocumentOperationBatchInput, FolioDocumentOperationResult, FolioDocumentOperationUndoHandle, FolioDocumentOperationUndoResult } from "../document-operations.js";
@@ -221,7 +221,9 @@ type StoryInlineProvenanceResult = {
221
221
  } | {
222
222
  status: "budget-exceeded";
223
223
  };
224
- type MatchStoryInlineAtomsOptions = Omit<MatchInlineAtomsOptions, "state" | "author"> & {
224
+ type ModelInlineAtomOptions = Parameters<typeof matchInlineAtomsOnModel>[0];
225
+ type MatchStoryInlineAtomsOptions = Omit<ModelInlineAtomOptions, "document" | "story" | "target" | "author" | "noteReferenceLabels"> & Partial<Pick<ModelInlineAtomOptions, "noteReferenceLabels">> & {
226
+ targetSnapshot: FolioAIEditSnapshot;
225
227
  story: FolioEditableDocumentStoryHandle;
226
228
  targetReviewer: FolioDocxReviewer;
227
229
  targetStory: FolioEditableDocumentStoryHandle;
@@ -772,6 +774,7 @@ export declare class FolioDocxReviewer {
772
774
  private resolveStoryOnSession;
773
775
  /** The current document model with edits merged back in. */
774
776
  toDocument(): document_d_exports.Document;
777
+ private savedDocument;
775
778
  /**
776
779
  * Serialise the reviewed document to a new `.docx` buffer. Tries a selective
777
780
  * patch first (only changed paragraphs are rewritten; every other byte of the
@@ -37,10 +37,10 @@ import { canonicalJson } from "../utils/canonicalJson.js";
37
37
  import { buildAnnotatedBlockTextWithNoteReferences } from "./clean-text.js";
38
38
  import { anchoredCommentIdsInBlocks, anchoredCommentIdsInProseDoc, coveredCommentIdsInProseDoc, withoutLostCommentThreads } from "./comment-lifecycle.js";
39
39
  import { stagedFinalSectionProperties } from "./finalSectionReview.js";
40
- import { FolioPendingSuggestionRegistry, createPendingSuggestionSourceSnapshot } from "./pending-suggestions.js";
40
+ import { FolioPendingSuggestionRegistry } from "./pending-suggestions.js";
41
41
  import { getCommentAnchorsFromDoc, getTrackedChangeStatsFromDoc, getTrackedChangesFromDoc, getTrackedChangesFromSnapshot, listedRevisionGroups } from "./read.js";
42
42
  import { classifyResourceReference } from "./referenceClassification.js";
43
- import { collectNoteReferenceLabels, createReviewerSnapshot, detachFolioAIEditSnapshotExternalHyperlinks, folioStoryTables, isFolioAIContentBlock, normalizeFolioAIBlockText, sourceDocumentOf } from "./snapshot.js";
43
+ import { collectNoteReferenceLabels, createFolioAIEditSnapshotWithStyleResolver, createReviewerSnapshot, detachFolioAIEditSnapshotExternalHyperlinks, folioStoryTables, isFolioAIContentBlock, normalizeFolioAIBlockText, sourceDocumentOf } from "./snapshot.js";
44
44
  import { matchTableGeometryOperations } from "./table-geometry.js";
45
45
  import { tableTemplateCanCrossPackageLosslessly } from "./table-template.js";
46
46
  import { TaggedError, panic } from "better-result";
@@ -1007,10 +1007,12 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1007
1007
  sourceSnapshotForStory,
1008
1008
  activeSuggestionIds: this.activeSuggestionIds()
1009
1009
  });
1010
+ const savedAbsorptions = /* @__PURE__ */ new Map();
1010
1011
  this.pendingSuggestions.placeRemovedAnchors({
1011
1012
  activeSuggestionIds: this.activeSuggestionIds(),
1012
1013
  stateForStory: (story) => this.getEditableStoryState(story),
1013
- savedSource: sourceSnapshotForStory
1014
+ savedSource: (story) => this.pendingSuggestionSource(story, savedAbsorptions),
1015
+ absorptionsForStory: (story) => savedAbsorptions.get(canonicalJson(canonicalOpStory(story))) ?? []
1014
1016
  });
1015
1017
  return {
1016
1018
  resolved: true,
@@ -1176,10 +1178,12 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1176
1178
  /** Export staged AI operations for storage by the host, outside the DOCX. */
1177
1179
  exportPendingSuggestions() {
1178
1180
  const active = this.activeSuggestionIds();
1181
+ const savedAbsorptions = /* @__PURE__ */ new Map();
1179
1182
  return this.pendingSuggestions.exportPendingSuggestions({
1180
1183
  activeSuggestionIds: active,
1181
- snapshotForStory: (story) => this.pendingSuggestionSource(story),
1182
- stateForStory: (story) => this.getEditableStoryState(story)
1184
+ snapshotForStory: (story) => this.pendingSuggestionSource(story, savedAbsorptions),
1185
+ stateForStory: (story) => this.getEditableStoryState(story),
1186
+ absorptionsForStory: (story) => savedAbsorptions.get(canonicalJson(canonicalOpStory(story))) ?? []
1183
1187
  });
1184
1188
  }
1185
1189
  /**
@@ -1188,9 +1192,11 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1188
1192
  * the document the save writes, so a reviewer reopened on the saved package
1189
1193
  * reads the same story.
1190
1194
  */
1191
- pendingSuggestionSource(story) {
1195
+ pendingSuggestionSource(story, absorptions) {
1192
1196
  if (!this.getEditableStoryState(story)) return null;
1193
- const document = this.toDocument();
1197
+ const document = this.savedDocument(absorptions === void 0 ? void 0 : { onAbsorptions: (resolvedStory, absorbed) => {
1198
+ absorptions.set(canonicalJson(resolvedStory), absorbed);
1199
+ } });
1194
1200
  const created = createCanonicalSession(document, document.package.styles);
1195
1201
  if (created.isErr()) throw created.error;
1196
1202
  const saved = new FolioDocxReviewer({
@@ -1204,7 +1210,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1204
1210
  },
1205
1211
  positionalParaIds: this.positionalParaIds
1206
1212
  }).getEditableStoryState(story);
1207
- return saved ? createPendingSuggestionSourceSnapshot(saved, /* @__PURE__ */ new Set()) : null;
1213
+ return saved ? createFolioAIEditSnapshotWithStyleResolver(saved.doc, getDocumentStyleResolver(saved)) : null;
1208
1214
  }
1209
1215
  /** Validate saved proposals against this document before restaging them. */
1210
1216
  loadPendingSuggestions(records) {
@@ -2053,7 +2059,10 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2053
2059
  }
2054
2060
  /** The current document model with edits merged back in. */
2055
2061
  toDocument() {
2056
- const model = withoutPendingSuggestions(this.engine.session.captureSaveSnapshot().document);
2062
+ return this.savedDocument();
2063
+ }
2064
+ savedDocument(options) {
2065
+ const model = withoutPendingSuggestions(this.engine.session.captureSaveSnapshot().document, options);
2057
2066
  if (model.isErr()) throw model.error;
2058
2067
  return cloneDocumentWithParagraphPropertySources(reconcileDocumentPartRelationships(model.value));
2059
2068
  }
@@ -74,7 +74,7 @@ export declare const endsWithNoteReference: ({ structuralBoundaries }: Structura
74
74
  * Only a document comparison does this. Its operations come from a revised
75
75
  * document that adds and removes references, so refusing them would drop the
76
76
  * edit; each marker it writes is turned back into the reference the revised
77
- * document holds once the operations land (`compare/inline-atoms.ts`), and a
77
+ * document holds once the operations land (`compare/inline-atoms-model.ts`), and a
78
78
  * removed reference is a tracked deletion of the reference itself. Every other
79
79
  * caller keeps the protection. The scope is synchronous, like the applier.
80
80
  */
@@ -65,7 +65,7 @@ let comparisonEditsNoteReferences = false;
65
65
  * Only a document comparison does this. Its operations come from a revised
66
66
  * document that adds and removes references, so refusing them would drop the
67
67
  * edit; each marker it writes is turned back into the reference the revised
68
- * document holds once the operations land (`compare/inline-atoms.ts`), and a
68
+ * document holds once the operations land (`compare/inline-atoms-model.ts`), and a
69
69
  * removed reference is a tracked deletion of the reference itself. Every other
70
70
  * caller keeps the protection. The scope is synchronous, like the applier.
71
71
  */
@@ -1,6 +1,8 @@
1
+ import { document_d_exports } from "../types/document.js";
1
2
  import { FolioDocumentStoryHandle } from "./headless.js";
2
3
  import { FolioAIEditAppliedOperation, FolioAIEditApplyResult, FolioAIEditOperation, FolioAIEditSnapshot } from "./types.js";
3
4
  import { EditorState } from "prosemirror-state";
5
+ import { ParagraphAbsorption } from "@stll/docx-core/ops";
4
6
  export declare const FOLIO_PENDING_SUGGESTION_VERSION: 1;
5
7
  /** A host-owned, JSON-serializable proposal. It is never written into the DOCX. */
6
8
  export type FolioPendingSuggestionRecord = {
@@ -77,17 +79,17 @@ type AbsorptionStep = (options: AbsorptionStepOptions) => void;
77
79
  type PlaceRemovedAnchorsOptions = {
78
80
  activeSuggestionIds: ReadonlySet<string>;
79
81
  stateForStory: (story: FolioDocumentStoryHandle) => EditorState | null;
80
- savedSource?: (story: FolioDocumentStoryHandle) => FolioAIEditSnapshot | null;
82
+ savedSource: (story: FolioDocumentStoryHandle) => FolioAIEditSnapshot | null;
83
+ absorptionsForStory?: (story: FolioDocumentStoryHandle) => readonly ParagraphAbsorption[];
81
84
  };
82
85
  type ExportPendingSuggestionsOptions = {
83
86
  activeSuggestionIds: ReadonlySet<string>;
84
87
  stateForStory?: PlaceRemovedAnchorsOptions["stateForStory"];
88
+ absorptionsForStory?: PlaceRemovedAnchorsOptions["absorptionsForStory"];
85
89
  snapshotForStory: (story: FolioDocumentStoryHandle, commentIds: ReadonlySet<number>) => FolioAIEditSnapshot | null;
86
90
  };
87
- /** Drop only comments attached to proposals that have not been accepted. */
88
- export declare const withoutPendingSuggestionCommentMarks: (state: EditorState, commentIds: ReadonlySet<number>) => EditorState;
89
- /** The saved package's story, with all pending proposals removed. */
90
- export declare const createPendingSuggestionSourceSnapshot: (state: EditorState, commentIds: ReadonlySet<number>) => FolioAIEditSnapshot;
91
+ /** The main story a save writes, with pending proposals and their comments removed. */
92
+ export declare const createPendingSuggestionSourceSnapshot: (document: document_d_exports.Document, commentIds: ReadonlySet<number>) => FolioAIEditSnapshot;
91
93
  /** Tracks only operations that successfully staged in `suggested` mode. */
92
94
  export declare class FolioPendingSuggestionRegistry {
93
95
  private readonly records;
@@ -106,7 +108,7 @@ export declare class FolioPendingSuggestionRegistry {
106
108
  * places is retired ({@link retiredRecord}): no record restages on a
107
109
  * removed or absorbed paragraph. Run after the change publishes.
108
110
  */
109
- placeRemovedAnchors({ activeSuggestionIds, stateForStory, savedSource }: PlaceRemovedAnchorsOptions): void;
111
+ placeRemovedAnchors({ activeSuggestionIds, stateForStory, savedSource, absorptionsForStory }: PlaceRemovedAnchorsOptions): void;
110
112
  /**
111
113
  * Prepare re-anchoring for a resolution that absorbs paragraphs: a live
112
114
  * proposal anchored to an absorbed paragraph now lives in the survivor, so
@@ -123,7 +125,7 @@ export declare class FolioPendingSuggestionRegistry {
123
125
  recordApplied({ snapshot, story, operations, applied, author, activeSuggestionIds }: RecordAppliedOptions): void;
124
126
  /** Rebase records after ordinary revisions change their source story. */
125
127
  replaceRestagedStory({ story, restaged, activeSuggestionIds }: ReplaceRestagedStoryOptions): void;
126
- exportPendingSuggestions({ activeSuggestionIds, snapshotForStory, stateForStory }: ExportPendingSuggestionsOptions): FolioPendingSuggestionRecord[];
128
+ exportPendingSuggestions({ activeSuggestionIds, snapshotForStory, stateForStory, absorptionsForStory }: ExportPendingSuggestionsOptions): FolioPendingSuggestionRecord[];
127
129
  loadPendingSuggestions({ records, snapshotForStory, sourceSnapshotForStory, apply, activeSuggestionIds }: LoadPendingSuggestionsOptions): FolioPendingSuggestionLoadResult[];
128
130
  }
129
131
  export {};
@@ -1,29 +1,30 @@
1
1
  import { parseFolioDocumentOperationBatch } from "../document-operations.js";
2
2
  import { expectParagraphAttrs, expectTrackedChangeMarkAttrs } from "../prosemirror/attrs/index.js";
3
- import { getSuggestions, rejectEverySuggestion, rejectEverySuggestionMapped } from "../prosemirror/commands/comments.js";
3
+ import { getSuggestions } from "../prosemirror/commands/comments.js";
4
+ import { storyConversionOptions } from "../prosemirror/conversion/storyConversionOptions.js";
5
+ import { toProseDoc } from "../prosemirror/conversion/toProseDoc.js";
4
6
  import { getDocumentStyleResolver } from "../prosemirror/plugins/documentStyleState.js";
7
+ import { createStyleResolver } from "../prosemirror/styles/styleResolver.js";
5
8
  import { getFolioParaIdFromBlockId } from "../types/block-id.js";
6
9
  import { canonicalJson } from "../utils/canonicalJson.js";
7
10
  import { persistedBlock } from "./block-identity.js";
8
- import { buildCleanBlockText, isOmittedFromCleanView } from "./clean-text.js";
11
+ import { buildCleanBlockText, isOmittedFromSavedSuggestionText } from "./clean-text.js";
9
12
  import { noteReferenceOf } from "./note-references.js";
10
13
  import { createFolioAIEditSnapshotWithStyleResolver, createFolioAITextRangeHandle, hashFolioAIBlockText, sourceDocumentOf } from "./snapshot.js";
11
14
  import { panic } from "better-result";
15
+ import { withoutPendingSuggestions } from "@stll/docx-core/ops";
12
16
  // src/ai-edits/pending-suggestions.ts
13
17
  const FOLIO_PENDING_SUGGESTION_VERSION = 1;
14
- /** Drop only comments attached to proposals that have not been accepted. */
15
- const withoutPendingSuggestionCommentMarks = (state, commentIds) => {
16
- if (commentIds.size === 0) return state;
17
- let transaction = state.tr;
18
- state.doc.descendants((node, position) => {
19
- for (const mark of node.marks) if (mark.type.name === "comment" && commentIds.has(mark.attrs["commentId"])) transaction = transaction.removeMark(position, position + node.nodeSize, mark);
20
- });
21
- return transaction.docChanged ? state.apply(transaction) : state;
22
- };
23
- /** The saved package's story, with all pending proposals removed. */
24
- const createPendingSuggestionSourceSnapshot = (state, commentIds) => {
25
- const source = withoutPendingSuggestionCommentMarks(rejectEverySuggestion(state), commentIds);
26
- return createFolioAIEditSnapshotWithStyleResolver(source.doc, getDocumentStyleResolver(source));
18
+ /** The main story a save writes, with pending proposals and their comments removed. */
19
+ const createPendingSuggestionSourceSnapshot = (document, commentIds) => {
20
+ const saved = withoutPendingSuggestions(document, { commentIds }).unwrap();
21
+ const { styles, theme, numbering } = saved.package;
22
+ const doc = toProseDoc(saved, storyConversionOptions({
23
+ styles,
24
+ theme,
25
+ numbering
26
+ }));
27
+ return createFolioAIEditSnapshotWithStyleResolver(doc, styles === void 0 ? null : createStyleResolver(styles));
27
28
  };
28
29
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29
30
  const operationBlockId = (operation) => {
@@ -129,28 +130,76 @@ const containerKey = ({ containerPath = [], table }) => canonicalJson({
129
130
  ]
130
131
  });
131
132
  const suggestionSnapshot = (state) => createFolioAIEditSnapshotWithStyleResolver(state.doc, getDocumentStyleResolver(state));
132
- /** `rejected` read as a snapshot, its paragraphs in the order a save lists them. */
133
- const settledSnapshot = ({ state }) => createFolioAIEditSnapshotWithStyleResolver(state.doc, getDocumentStyleResolver(state));
134
133
  /**
135
- * The paragraph at `paragraphStart` of the rejected story, as a save names
136
- * it: the saved package may name the paragraphs otherwise, and both read
137
- * alike. `null` when the save reads other text there.
134
+ * Native review names each surviving paragraph. Read its source segments in
135
+ * authored order and count what the saved story keeps. Verify the complete
136
+ * text against the saved projection before using offsets from any segment.
138
137
  */
139
- const savedParagraphAt = ({ rejected, settled, saved, paragraphStart }) => {
140
- const paragraph = rejected.state.doc.nodeAt(paragraphStart);
141
- const index = settled.blocks.findIndex(({ id }) => settled.anchors[id]?.from === paragraphStart);
142
- const block = index < 0 ? void 0 : saved.blocks[index];
143
- const anchor = block === void 0 ? void 0 : saved.anchors[block.id];
144
- if (paragraph === null || block === void 0 || anchor === void 0) return null;
145
- const clean = buildCleanBlockText(paragraph, paragraphStart, { fieldResults: "text" });
146
- if (anchor.text !== clean.text) return null;
147
- return {
148
- block,
149
- anchor,
150
- offsetAt: (position) => {
151
- const offset = clean.offsets.findIndex((at) => at >= position);
152
- return offset < 0 ? clean.text.length : offset;
138
+ const savedPositionMap = ({ state, saved, absorptions }) => {
139
+ const savedDoc = sourceDocumentOf(saved);
140
+ const owners = /* @__PURE__ */ new Map();
141
+ for (const block of saved.blocks) {
142
+ const anchor = saved.anchors[block.id];
143
+ if (anchor === void 0) continue;
144
+ const node = savedDoc.nodeAt(anchor.from);
145
+ if (node?.type.name !== "paragraph") continue;
146
+ const paraId = expectParagraphAttrs(node).paraId?.toUpperCase();
147
+ if (paraId) owners.set(paraId, owners.has(paraId) ? null : {
148
+ block,
149
+ anchor
150
+ });
151
+ }
152
+ const survivors = new Map(absorptions.map(({ absorbed, survivor }) => [absorbed.toUpperCase(), survivor.toUpperCase()]));
153
+ const segments = /* @__PURE__ */ new Map();
154
+ state.doc.descendants((node, start) => {
155
+ if (node.type.name !== "paragraph") return true;
156
+ const paraId = expectParagraphAttrs(node).paraId?.toUpperCase();
157
+ if (!paraId) return true;
158
+ const survivor = finalSurvivor(survivors, paraId);
159
+ if (!owners.get(survivor)) return true;
160
+ const { text, offsets } = buildCleanBlockText(node, start, {
161
+ fieldResults: "text",
162
+ view: "saved-without-suggestions"
163
+ });
164
+ const segment = {
165
+ start,
166
+ text,
167
+ offsets
168
+ };
169
+ const group = segments.get(survivor);
170
+ if (group === void 0) segments.set(survivor, [segment]);
171
+ else group.push(segment);
172
+ return true;
173
+ });
174
+ const verified = /* @__PURE__ */ new Map();
175
+ for (const [id, group] of segments) {
176
+ const paragraph = owners.get(id);
177
+ if (!paragraph || group.map(({ text }) => text).join("") !== paragraph.anchor.text) continue;
178
+ let offset = 0;
179
+ for (const segment of group) {
180
+ verified.set(segment.start, {
181
+ ...paragraph,
182
+ offset,
183
+ segment
184
+ });
185
+ offset += segment.text.length;
186
+ }
187
+ }
188
+ return (position) => {
189
+ const at = state.doc.resolve(position);
190
+ for (let depth = at.depth; depth > 0; depth--) {
191
+ if (at.node(depth).type.name !== "paragraph") continue;
192
+ const mapped = verified.get(at.before(depth));
193
+ if (mapped === void 0) return null;
194
+ const { segment, offset, block, anchor } = mapped;
195
+ const index = segment.offsets.findIndex((source) => source >= position);
196
+ return {
197
+ block,
198
+ anchor,
199
+ offset: offset + (index < 0 ? segment.text.length : index)
200
+ };
153
201
  }
202
+ return null;
154
203
  };
155
204
  };
156
205
  /**
@@ -161,7 +210,7 @@ const savedParagraphAt = ({ rejected, settled, saved, paragraphStart }) => {
161
210
  * `null` when the mark is gone, or stands in no saved paragraph or at its
162
211
  * edge.
163
212
  */
164
- const currentSplitRecord = ({ record, state, saved }) => {
213
+ const currentSplitRecord = ({ record, state, savedPosition }) => {
165
214
  const { operation, suggestionId, splitRevisionId } = record;
166
215
  if (operation.type !== "splitBlock" || splitRevisionId === void 0) return null;
167
216
  const ends = [];
@@ -174,19 +223,9 @@ const currentSplitRecord = ({ record, state, saved }) => {
174
223
  });
175
224
  const end = ends.at(0);
176
225
  if (end === void 0) return null;
177
- const rejected = rejectEverySuggestionMapped(state);
178
- const at = rejected.mapping.map(end, -1);
179
- const $at = rejected.state.doc.resolve(at);
180
- if ($at.parent.type.name !== "paragraph") return null;
181
- const paragraph = savedParagraphAt({
182
- rejected,
183
- settled: settledSnapshot(rejected),
184
- saved,
185
- paragraphStart: $at.before()
186
- });
226
+ const paragraph = savedPosition(end);
187
227
  if (paragraph === null) return null;
188
- const { block, anchor, offsetAt } = paragraph;
189
- const offset = offsetAt(at);
228
+ const { block, anchor, offset } = paragraph;
190
229
  if (offset === 0 || offset >= anchor.text.length) return null;
191
230
  return {
192
231
  ...record,
@@ -273,16 +312,10 @@ const proposedComment = (operation) => operation.type === "replaceBlock" || oper
273
312
  * `null` when the suggestion proposes something else too, or when its marks
274
313
  * are no ranges of text a save holds.
275
314
  */
276
- const currentTextRecords = ({ records, state, saved }) => {
315
+ const currentTextRecords = ({ records, state, savedPosition }) => {
277
316
  const [record] = records;
278
317
  if (record === void 0 || !records.every(({ operation }) => proposesText(operation))) return null;
279
318
  const { suggestionId } = record;
280
- const rejected = rejectEverySuggestionMapped(state);
281
- /** What a saved package holds of the node at `from` to `to`. */
282
- const savedNode = (from, to) => {
283
- const at = rejected.mapping.map(from, 1);
284
- return at < rejected.mapping.map(to, -1) ? rejected.state.doc.nodeAt(at) : null;
285
- };
286
319
  const pieces = [];
287
320
  state.doc.descendants((node, from) => {
288
321
  if (!node.isInline) return true;
@@ -301,22 +334,19 @@ const currentTextRecords = ({ records, state, saved }) => {
301
334
  });
302
335
  return false;
303
336
  });
304
- /** Where a piece starts once every proposal is rejected. */
305
- const savedStart = ({ from, owner }) => rejected.mapping.map(from, owner === "insertion" ? -1 : 1);
306
337
  /** The first and last of the suggestion's pieces in each saved paragraph. */
307
338
  const spans = /* @__PURE__ */ new Map();
308
339
  for (const [index, piece] of pieces.entries()) {
309
340
  if (piece.owner === null) continue;
310
- const $at = rejected.state.doc.resolve(savedStart(piece));
311
- if ($at.parent.type.name !== "paragraph") return null;
312
- const span = spans.get($at.before());
313
- if (span === void 0) spans.set($at.before(), {
341
+ const at = savedPosition(piece.from);
342
+ if (at === null) return null;
343
+ const span = spans.get(at.block.id);
344
+ if (span === void 0) spans.set(at.block.id, {
314
345
  first: index,
315
346
  last: index
316
347
  });
317
348
  else span.last = index;
318
349
  }
319
- const settled = settledSnapshot(rejected);
320
350
  const ids = records.map(({ operation }) => operation.id);
321
351
  const nextId = (position) => {
322
352
  const known = ids[position];
@@ -328,25 +358,22 @@ const currentTextRecords = ({ records, state, saved }) => {
328
358
  return id;
329
359
  };
330
360
  const current = [];
331
- for (const [paragraphStart, { first, last }] of spans) {
361
+ for (const { first, last } of spans.values()) {
332
362
  const start = pieces[first];
333
363
  const end = pieces[last];
334
- const paragraph = savedParagraphAt({
335
- rejected,
336
- settled,
337
- saved,
338
- paragraphStart
339
- });
340
- if (start === void 0 || end === void 0 || paragraph === null) return null;
341
- const { block, anchor, offsetAt } = paragraph;
342
- const from = offsetAt(savedStart(start));
343
- const to = Math.max(from, offsetAt(rejected.mapping.map(end.to, -1)));
364
+ if (start === void 0 || end === void 0) return null;
365
+ const fromPosition = savedPosition(start.from);
366
+ const toPosition = savedPosition(end.to);
367
+ if (fromPosition === null || toPosition === null || fromPosition.block.id !== toPosition.block.id) return null;
368
+ const { block, anchor, offset: from } = fromPosition;
369
+ const to = Math.max(from, toPosition.offset);
344
370
  let replace = "";
345
371
  for (const piece of pieces.slice(first, last + 1)) {
346
372
  if (piece.owner === "insertion") replace += piece.text;
347
373
  if (piece.owner !== null) continue;
348
- const kept = savedNode(piece.from, piece.to);
349
- if (kept === null || isOmittedFromCleanView(kept)) continue;
374
+ const kept = state.doc.nodeAt(piece.from);
375
+ if (kept === null || isOmittedFromSavedSuggestionText(kept)) continue;
376
+ if (savedPosition(piece.from)?.block.id !== block.id) continue;
350
377
  if (!kept.isText || noteReferenceOf(kept) !== null) return null;
351
378
  replace += piece.text;
352
379
  }
@@ -543,7 +570,7 @@ var FolioPendingSuggestionRegistry = class FolioPendingSuggestionRegistry {
543
570
  * places is retired ({@link retiredRecord}): no record restages on a
544
571
  * removed or absorbed paragraph. Run after the change publishes.
545
572
  */
546
- placeRemovedAnchors({ activeSuggestionIds, stateForStory, savedSource }) {
573
+ placeRemovedAnchors({ activeSuggestionIds, stateForStory, savedSource, absorptionsForStory }) {
547
574
  const views = /* @__PURE__ */ new Map();
548
575
  for (const [key, record] of Array.from(this.records)) {
549
576
  const { suggestionId, story, anchor } = record;
@@ -559,13 +586,18 @@ var FolioPendingSuggestionRegistry = class FolioPendingSuggestionRegistry {
559
586
  views.set(storyKey, view);
560
587
  }
561
588
  if (view === null || view.live.anchors[anchor.paraId] !== void 0) continue;
562
- if (view.saved === void 0) view.saved = savedSource?.(story) ?? null;
589
+ if (view.saved === void 0) view.saved = savedSource(story);
563
590
  const saved = view.saved;
564
591
  if (saved !== null && (record.splitRevisionId !== void 0 || proposesText(record.operation))) {
592
+ const savedPosition = view.savedPosition ??= savedPositionMap({
593
+ state: view.state,
594
+ saved,
595
+ absorptions: absorptionsForStory?.(story) ?? []
596
+ });
565
597
  const split = currentSplitRecord({
566
598
  record,
567
599
  state: view.state,
568
- saved
600
+ savedPosition
569
601
  });
570
602
  if (split !== null) {
571
603
  this.records.set(key, split);
@@ -575,7 +607,7 @@ var FolioPendingSuggestionRegistry = class FolioPendingSuggestionRegistry {
575
607
  const texts = currentTextRecords({
576
608
  records: entries.map(([, other]) => other),
577
609
  state: view.state,
578
- saved
610
+ savedPosition
579
611
  });
580
612
  if (texts !== null) {
581
613
  for (const [other] of entries) this.records.delete(other);
@@ -584,10 +616,10 @@ var FolioPendingSuggestionRegistry = class FolioPendingSuggestionRegistry {
584
616
  }
585
617
  }
586
618
  const ranges = getSuggestions(view.state).find((entry) => entry.suggestionId === suggestionId)?.ranges ?? [];
587
- const placed = placedRecord({
619
+ const placed = saved === null ? null : placedRecord({
588
620
  record,
589
621
  live: view.live,
590
- saved: saved ?? createPendingSuggestionSourceSnapshot(view.state, /* @__PURE__ */ new Set()),
622
+ saved,
591
623
  ranges
592
624
  });
593
625
  this.records.set(key, placed ?? retiredRecord(record));
@@ -690,10 +722,11 @@ var FolioPendingSuggestionRegistry = class FolioPendingSuggestionRegistry {
690
722
  activeSuggestionIds
691
723
  });
692
724
  }
693
- exportPendingSuggestions({ activeSuggestionIds, snapshotForStory, stateForStory }) {
725
+ exportPendingSuggestions({ activeSuggestionIds, snapshotForStory, stateForStory, absorptionsForStory }) {
694
726
  const pending = [];
695
727
  const savedStories = /* @__PURE__ */ new Map();
696
728
  const liveStories = /* @__PURE__ */ new Map();
729
+ const savedPositions = /* @__PURE__ */ new Map();
697
730
  const commentIdsByStory = /* @__PURE__ */ new Map();
698
731
  for (const record of this.records.values()) {
699
732
  if (!activeSuggestionIds.has(record.suggestionId) || record.commentId === void 0) continue;
@@ -725,7 +758,8 @@ var FolioPendingSuggestionRegistry = class FolioPendingSuggestionRegistry {
725
758
  if (stateForStory !== void 0) this.placeRemovedAnchors({
726
759
  activeSuggestionIds,
727
760
  stateForStory: liveStateOf,
728
- savedSource: (story) => savedStoryOf(story)?.snapshot ?? null
761
+ savedSource: (story) => savedStoryOf(story)?.snapshot ?? null,
762
+ ...absorptionsForStory === void 0 ? {} : { absorptionsForStory }
729
763
  });
730
764
  for (const [key, record] of this.records) if (activeSuggestionIds.has(record.suggestionId)) {
731
765
  const saved = savedStoryOf(record.story);
@@ -733,11 +767,23 @@ var FolioPendingSuggestionRegistry = class FolioPendingSuggestionRegistry {
733
767
  let updated = record;
734
768
  if (record.splitRevisionId !== void 0) {
735
769
  const state = liveStateOf(record.story);
736
- if (state !== null) updated = currentSplitRecord({
737
- record,
738
- state,
739
- saved: saved.snapshot
740
- }) ?? record;
770
+ if (state !== null) {
771
+ const storyKey = canonicalJson(record.story);
772
+ let savedPosition = savedPositions.get(storyKey);
773
+ if (savedPosition === void 0) {
774
+ savedPosition = savedPositionMap({
775
+ state,
776
+ saved: saved.snapshot,
777
+ absorptions: absorptionsForStory?.(record.story) ?? []
778
+ });
779
+ savedPositions.set(storyKey, savedPosition);
780
+ }
781
+ updated = currentSplitRecord({
782
+ record,
783
+ state,
784
+ savedPosition
785
+ }) ?? record;
786
+ }
741
787
  }
742
788
  const current = {
743
789
  ...updated,
@@ -860,4 +906,4 @@ var FolioPendingSuggestionRegistry = class FolioPendingSuggestionRegistry {
860
906
  });
861
907
  }
862
908
  };
863
- export { FOLIO_PENDING_SUGGESTION_VERSION, FolioPendingSuggestionRegistry, createPendingSuggestionSourceSnapshot, withoutPendingSuggestionCommentMarks };
909
+ export { FOLIO_PENDING_SUGGESTION_VERSION, FolioPendingSuggestionRegistry, createPendingSuggestionSourceSnapshot };
@@ -158,7 +158,11 @@ export type PendingMarkEditOptions = {
158
158
  /** The paragraph's accepted reading. */
159
159
  cleanText: string;
160
160
  };
161
- /** The shared property boundary, independent of the paragraph's representation. */
161
+ /**
162
+ * The shared property boundary, independent of the paragraph's
163
+ * representation: any mark accepting removes, including one added and then
164
+ * deleted by another author, takes the edited properties with it.
165
+ */
162
166
  export declare const pendingParagraphPropertiesRefusal: (mark: unknown) => PendingRefusal | undefined;
163
167
  /**
164
168
  * The refusal an operation that places no block meets on a paragraph whose