@stll/folio-core 0.66.1 → 0.67.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 (170) hide show
  1. package/dist/ai-edits/apply.d.ts +13 -1
  2. package/dist/ai-edits/apply.js +572 -140
  3. package/dist/ai-edits/batch-claims.d.ts +26 -0
  4. package/dist/ai-edits/batch-claims.js +32 -5
  5. package/dist/ai-edits/clean-text.js +4 -1
  6. package/dist/ai-edits/headless.d.ts +6 -0
  7. package/dist/ai-edits/headless.js +25 -3
  8. package/dist/ai-edits/newListNumbering.d.ts +4 -1
  9. package/dist/ai-edits/newListNumbering.js +4 -2
  10. package/dist/ai-edits/read.js +6 -4
  11. package/dist/ai-edits/snapshot.js +24 -14
  12. package/dist/ai-edits/table-cell-mutations.js +3 -2
  13. package/dist/ai-edits/table-row-column-mutations.js +20 -6
  14. package/dist/ai-edits/types.d.ts +1 -1
  15. package/dist/controller/canonicalComposition.d.ts +1 -1
  16. package/dist/controller/canonicalComposition.js +76 -18
  17. package/dist/controller/canonicalInput.d.ts +0 -1
  18. package/dist/controller/canonicalInput.js +19 -1
  19. package/dist/controller/canonicalSession.js +1 -2
  20. package/dist/controller/hiddenEditorManager.d.ts +6 -0
  21. package/dist/controller/hiddenEditorManager.js +3 -1
  22. package/dist/controller/layoutPipeline.d.ts +2 -0
  23. package/dist/controller/layoutPipeline.js +7 -3
  24. package/dist/controller/layoutSession.d.ts +1 -0
  25. package/dist/display-list/build/tablePrimitives.d.ts +3 -1
  26. package/dist/display-list/build/tablePrimitives.js +29 -13
  27. package/dist/document-operations.d.ts +13 -1
  28. package/dist/document-operations.js +11 -4
  29. package/dist/docx/chartPreview.d.ts +4 -1
  30. package/dist/docx/chartPreview.js +26 -15
  31. package/dist/docx/listNumberingInstances.d.ts +6 -4
  32. package/dist/docx/listNumberingInstances.js +12 -11
  33. package/dist/docx/mainDocumentPart.d.ts +6 -0
  34. package/dist/docx/mainDocumentPart.js +65 -0
  35. package/dist/docx/numberingIds.d.ts +10 -0
  36. package/dist/docx/numberingIds.js +5 -1
  37. package/dist/docx/packageParts.d.ts +1 -1
  38. package/dist/docx/packageParts.js +10 -4
  39. package/dist/docx/paragraphParser.js +16 -3
  40. package/dist/docx/paragraphProperties.js +2 -1
  41. package/dist/docx/previewBudget.d.ts +6 -0
  42. package/dist/docx/previewBudget.js +7 -1
  43. package/dist/docx/rezip.js +4 -4
  44. package/dist/docx/serializer/paragraphSerializer.js +86 -66
  45. package/dist/docx/shapeAlternateContent.js +19 -0
  46. package/dist/docx/unzip.js +2 -0
  47. package/dist/i18n/messages/ar.gen.js +2 -0
  48. package/dist/i18n/messages/catalogs.gen.d.ts +34 -0
  49. package/dist/i18n/messages/catalogs.gen.js +34 -0
  50. package/dist/i18n/messages/cs.gen.js +2 -0
  51. package/dist/i18n/messages/de.gen.js +2 -0
  52. package/dist/i18n/messages/en.gen.js +2 -0
  53. package/dist/i18n/messages/es.gen.js +2 -0
  54. package/dist/i18n/messages/et.gen.js +2 -0
  55. package/dist/i18n/messages/fr.gen.js +2 -0
  56. package/dist/i18n/messages/he.gen.js +2 -0
  57. package/dist/i18n/messages/hi.gen.js +2 -0
  58. package/dist/i18n/messages/hu.gen.js +2 -0
  59. package/dist/i18n/messages/lt.gen.js +2 -0
  60. package/dist/i18n/messages/lv.gen.js +2 -0
  61. package/dist/i18n/messages/messages.gen.d.ts +2 -0
  62. package/dist/i18n/messages/pl.gen.js +2 -0
  63. package/dist/i18n/messages/pt-BR.gen.js +2 -0
  64. package/dist/i18n/messages/sk.gen.js +2 -0
  65. package/dist/i18n/messages/tr.gen.js +2 -0
  66. package/dist/i18n/messages/zh-CN.gen.js +2 -0
  67. package/dist/internal/wholeStoryRevisionResolution.d.ts +1 -1
  68. package/dist/internal/wholeStoryRevisionResolution.js +81 -21
  69. package/dist/layout-bridge/convert/altChunkPlaceholder.d.ts +10 -0
  70. package/dist/layout-bridge/convert/altChunkPlaceholder.js +70 -0
  71. package/dist/layout-bridge/convert/fixedTableColumnWidths.js +2 -1
  72. package/dist/layout-bridge/convert/flowConversionShared.d.ts +10 -0
  73. package/dist/layout-bridge/convert/flowConversionShared.js +11 -1
  74. package/dist/layout-bridge/convert/footnoteLayout.d.ts +1 -0
  75. package/dist/layout-bridge/convert/footnoteLayout.js +4 -1
  76. package/dist/layout-bridge/convert/headerFooterLayout.d.ts +1 -0
  77. package/dist/layout-bridge/convert/headerFooterLayout.js +6 -1
  78. package/dist/layout-bridge/convert/runMarkFormatting.js +1 -0
  79. package/dist/layout-bridge/convert/tableConversion.js +6 -2
  80. package/dist/layout-bridge/convert/toFlowBlocks.js +4 -0
  81. package/dist/layout-bridge/engine/clickToPosition.js +5 -1
  82. package/dist/layout-engine/measure/tableCellFloating.d.ts +2 -0
  83. package/dist/layout-engine/measure/tableCellFloating.js +1 -0
  84. package/dist/layout-engine/measure/tableVisibleBand.d.ts +16 -0
  85. package/dist/layout-engine/measure/tableVisibleBand.js +28 -0
  86. package/dist/layout-engine/tableLayout.js +7 -4
  87. package/dist/layout-engine/tableRowBreak.d.ts +10 -0
  88. package/dist/layout-engine/tableRowBreak.js +151 -36
  89. package/dist/layout-engine/types.d.ts +7 -2
  90. package/dist/layout-painter/previewSvg.d.ts +8 -0
  91. package/dist/layout-painter/previewSvg.js +47 -0
  92. package/dist/layout-painter/renderImage.js +2 -1
  93. package/dist/layout-painter/renderPage.d.ts +1 -0
  94. package/dist/layout-painter/renderPage.js +6 -3
  95. package/dist/layout-painter/renderParagraph.js +3 -2
  96. package/dist/layout-painter/renderTable.d.ts +5 -2
  97. package/dist/layout-painter/renderTable.js +33 -19
  98. package/dist/markdown/renderRuns.js +68 -12
  99. package/dist/prosemirror/anchoredTextBoxes.d.ts +2 -1
  100. package/dist/prosemirror/commands/comments.js +22 -7
  101. package/dist/prosemirror/commands/deleteBesideInlineAnchor.d.ts +9 -0
  102. package/dist/prosemirror/commands/deleteBesideInlineAnchor.js +36 -0
  103. package/dist/prosemirror/commands/pastePlainText.d.ts +6 -0
  104. package/dist/prosemirror/commands/pastePlainText.js +13 -3
  105. package/dist/prosemirror/commands/resolveAllTableChanges.js +30 -2
  106. package/dist/prosemirror/commands/resolveParagraphProperties.js +15 -2
  107. package/dist/prosemirror/commentReferenceIntegrity.d.ts +8 -2
  108. package/dist/prosemirror/commentReferenceIntegrity.js +19 -4
  109. package/dist/prosemirror/conversion/fromProseDoc.js +94 -22
  110. package/dist/prosemirror/conversion/hyphenTextCarriers.d.ts +23 -1
  111. package/dist/prosemirror/conversion/hyphenTextCarriers.js +46 -1
  112. package/dist/prosemirror/conversion/toProseDoc.js +21 -13
  113. package/dist/prosemirror/extensions/StarterKit.js +1 -1
  114. package/dist/prosemirror/extensions/core/ParagraphExtension.d.ts +3 -1
  115. package/dist/prosemirror/extensions/core/ParagraphExtension.js +8 -9
  116. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.js +46 -11
  117. package/dist/prosemirror/extensions/features/BaseKeymapExtension.js +3 -2
  118. package/dist/prosemirror/extensions/features/BidiShortcutExtension.js +2 -3
  119. package/dist/prosemirror/extensions/features/ListExtension.js +22 -1
  120. package/dist/prosemirror/extensions/features/pasteCleanup.js +6 -0
  121. package/dist/prosemirror/extensions/features/pastedHtmlLists.js +2 -1
  122. package/dist/prosemirror/extensions/markRegistry.d.ts +3 -1
  123. package/dist/prosemirror/extensions/markRegistry.js +3 -0
  124. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +5 -0
  125. package/dist/prosemirror/extensions/marks/HyphenElementExtension.d.ts +6 -0
  126. package/dist/prosemirror/extensions/marks/HyphenElementExtension.js +54 -0
  127. package/dist/prosemirror/extensions/marks/TextColorExtension.js +1 -1
  128. package/dist/prosemirror/extensions/marks/TrackedChangeExtensions.js +8 -4
  129. package/dist/prosemirror/extensions/nodes/BookmarkBoundaryExtension.js +5 -1
  130. package/dist/prosemirror/extensions/nodes/CommentRangeBoundaryExtension.js +2 -1
  131. package/dist/prosemirror/extensions/nodes/CommentReferenceExtension.js +4 -3
  132. package/dist/prosemirror/extensions/nodes/MoveRangeBoundaryExtension.js +2 -1
  133. package/dist/prosemirror/extensions/nodes/NoteMarkerExtension.js +2 -1
  134. package/dist/prosemirror/extensions/nodes/RangeAnchorExtension.js +2 -1
  135. package/dist/prosemirror/extensions/nodes/RenderedPageBreakExtension.js +2 -1
  136. package/dist/prosemirror/extensions/nodes/TableExtension.js +87 -7
  137. package/dist/prosemirror/extensions/nodes/inlineAnchorDom.d.ts +11 -0
  138. package/dist/prosemirror/extensions/nodes/inlineAnchorDom.js +21 -0
  139. package/dist/prosemirror/fieldRepresentation.js +2 -1
  140. package/dist/prosemirror/hyphenElementAttrs.d.ts +10 -0
  141. package/dist/prosemirror/hyphenElementAttrs.js +32 -0
  142. package/dist/prosemirror/keptRangeBoundaries.d.ts +2 -0
  143. package/dist/prosemirror/keptRangeBoundaries.js +1 -1
  144. package/dist/prosemirror/listNumbering.js +3 -2
  145. package/dist/prosemirror/paragraphIndentation.js +2 -1
  146. package/dist/prosemirror/paragraphPropertyCarry.d.ts +1 -14
  147. package/dist/prosemirror/paragraphPropertyCarry.js +4 -28
  148. package/dist/prosemirror/plugins/suggestionMode.d.ts +0 -8
  149. package/dist/prosemirror/plugins/suggestionMode.js +194 -27
  150. package/dist/prosemirror/replacedAnnotations.d.ts +1 -0
  151. package/dist/prosemirror/replacedAnnotations.js +1 -0
  152. package/dist/prosemirror/rowGridOmissions.d.ts +11 -0
  153. package/dist/prosemirror/rowGridOmissions.js +21 -0
  154. package/dist/prosemirror/sectionCarrier.d.ts +8 -0
  155. package/dist/prosemirror/sectionCarrier.js +29 -1
  156. package/dist/prosemirror/styles/paragraphStyleCascade.d.ts +10 -0
  157. package/dist/prosemirror/styles/paragraphStyleCascade.js +12 -2
  158. package/dist/prosemirror/tableGridMutation.d.ts +19 -2
  159. package/dist/prosemirror/tableGridMutation.js +118 -15
  160. package/dist/prosemirror/tablePositionedBookmarks.d.ts +2 -0
  161. package/dist/prosemirror/tablePositionedBookmarks.js +80 -0
  162. package/dist/prosemirror/tableRunIn.d.ts +24 -9
  163. package/dist/prosemirror/tableRunIn.js +107 -21
  164. package/dist/prosemirror/textInput.js +3 -1
  165. package/dist/prosemirror/validation.js +7 -1
  166. package/dist/utils/createDocument.js +11 -8
  167. package/dist/utils/formatToStyle.js +2 -2
  168. package/dist/utils/units.d.ts +5 -0
  169. package/dist/utils/units.js +6 -1
  170. package/package.json +3 -3
@@ -1,4 +1,5 @@
1
- import { isNumberingReference } from "../docx/numberingReference.js";
1
+ import { NO_NUMBERING_IDS_IN_USE } from "../docx/numberingIds.js";
2
+ import { isNumberingReference as isNumberingReference$1 } from "../docx/numberingReference.js";
2
3
  import { formattingEquals } from "../docx/runConsolidator.js";
3
4
  import { isStyleSourcedParagraphNumbering } from "../internal/paragraphFormattingSerialization.js";
4
5
  import { addTrackedDeletionMark } from "../prosemirror/addTrackedDeletionMark.js";
@@ -20,7 +21,7 @@ import { directParagraphAlignment } from "../prosemirror/paragraphAlignment.js";
20
21
  import { styleResolvedParagraphFormatting } from "../prosemirror/paragraphFormattingProvenance.js";
21
22
  import { directParagraphIndentation, paragraphIndentationAttrPatch, paragraphIndentationEqual, paragraphIndentationFromFormatting, withDirectParagraphIndentation } from "../prosemirror/paragraphIndentation.js";
22
23
  import { joinAtParagraphMark } from "../prosemirror/paragraphMarkJoin.js";
23
- import { carriedParagraphProperties, carryParagraphProperties, paragraphLeftAfter, propertiesSetInBatch, recordReplacedParagraphProperties } from "../prosemirror/paragraphPropertyCarry.js";
24
+ import { carryParagraphProperties, paragraphLeftAfter, recordReplacedParagraphProperties } from "../prosemirror/paragraphPropertyCarry.js";
24
25
  import { directParagraphSpacing, paragraphSpacingAttrPatch, paragraphSpacingEqual, paragraphSpacingFromFormatting, withDirectParagraphSpacing } from "../prosemirror/paragraphSpacing.js";
25
26
  import { getDocumentNumbering, getDocumentNumberingInstanceIds } from "../prosemirror/plugins/documentNumbering.js";
26
27
  import { getDocumentStyleDefinitions, getDocumentStyleResolver } from "../prosemirror/plugins/documentStyleState.js";
@@ -34,6 +35,7 @@ import { paragraphRunStyleContext, paragraphRunStyleContextAt, resolveParagraphB
34
35
  import { sectionPropertiesOf } from "../prosemirror/sectionCarrier.js";
35
36
  import { listAttrsFromNumbering, listLevelAttrPatch, listLevelIndentRemovalPatch } from "../prosemirror/styles/resolvedStyleAttrs.js";
36
37
  import { removeRowsWithoutCellsAfterBatch } from "../prosemirror/tableGridMutation.js";
38
+ import { runInCellPending } from "../prosemirror/tableRunIn.js";
37
39
  import { isZeroWidthAnchor } from "../prosemirror/zeroWidthAnchors.js";
38
40
  import { getFolioParaIdFromBlockId } from "../types/block-id.js";
39
41
  import { CANONICAL_GAP } from "../types/canonicalCapabilities.js";
@@ -56,10 +58,11 @@ import { findEnclosingTableCell, findEnclosingTableRow, findOutermostTableBounda
56
58
  import { tableFromTemplate } from "./table-template.js";
57
59
  import { wordDiffSessionFromOptions } from "./word-diff.js";
58
60
  import { panic } from "better-result";
61
+ import { REVIEW_CARRIERS } from "@stll/docx-core/model";
59
62
  import { Fragment, Mark } from "prosemirror-model";
60
63
  import { TableMap } from "prosemirror-tables";
61
64
  import { canSplit } from "prosemirror-transform";
62
- import { contentRank, groupInsertionRuns, orderBatchOperations } from "@stll/docx-core/ops";
65
+ import { contentRank, deletionRemovesBlock, groupInsertionRuns, orderAddressingBeforeRemoval, orderBatchOperations } from "@stll/docx-core/ops";
63
66
  // src/ai-edits/apply.ts
64
67
  const coarseWordDiff = (before, after) => {
65
68
  if (before === after) return before.length === 0 ? [] : [{
@@ -377,8 +380,8 @@ const withoutRevisionsOnZeroWidthAnchors = (tr, batchRevisionIds, deletedTextBox
377
380
  * text box's anchor is the exception: it stands for the box's drawing run,
378
381
  * which is the paragraph's content, and the box follows it.
379
382
  */
380
- const undeletedContentAtomRanges = (tr, blockFrom) => {
381
- const position = tr.mapping.map(blockFrom);
383
+ const undeletedContentAtomRanges = (tr, blockFrom, readAt) => {
384
+ const position = tr.mapping.slice(readAt).map(blockFrom);
382
385
  const block = tr.doc.nodeAt(position);
383
386
  if (!block?.isTextblock) return [];
384
387
  const ranges = [];
@@ -567,7 +570,7 @@ const applyReplaceBlockStyleId = ({ item, tr, styleResolver, revisionInfo }) =>
567
570
  revisionId: null,
568
571
  revisionIds: []
569
572
  };
570
- const blockPosition = tr.mapping.map(item.blockFrom, -1);
573
+ const blockPosition = sinceRead(tr, item).map(item.blockFrom, -1);
571
574
  const block = tr.doc.nodeAt(blockPosition);
572
575
  if (!block) return {
573
576
  tr,
@@ -854,9 +857,16 @@ const applyTrackedInlineFormattingToRanges = ({ tr, schema, doc = tr.doc, ranges
854
857
  suggestionId
855
858
  };
856
859
  const revisionIds = [];
860
+ let fieldChange = null;
857
861
  for (const segment of segments) {
858
- const revisionId = revisionIdSeed + revisionIds.length;
859
- revisionIds.push(revisionId);
862
+ const { representation } = segment;
863
+ const insideField = fieldChange !== null && representation.role === "serialized-result" && representation.position < fieldChange.end;
864
+ const revisionId = insideField && fieldChange !== null ? fieldChange.id : revisionIdSeed + revisionIds.length;
865
+ if (!insideField) revisionIds.push(revisionId);
866
+ if (representation.role === "owner" && representation.carrierDisposition === "structured-field") fieldChange = {
867
+ id: revisionId,
868
+ end: representation.position + representation.node.nodeSize
869
+ };
860
870
  const change = {
861
871
  type: "runPropertyChange",
862
872
  info: {
@@ -1039,6 +1049,28 @@ const foldedBlankCellRanges = (doc, { tablePosition, rectangle }) => {
1039
1049
  }] : [];
1040
1050
  });
1041
1051
  };
1052
+ /**
1053
+ * The paragraphs before `paragraph`, which ends its container, nearest first,
1054
+ * up to the container's start or another block, past those that go whole, as
1055
+ * `finalParagraphPredecessor` looks past them. See the `deleteBlock` claim's
1056
+ * `paragraphsBefore`.
1057
+ */
1058
+ const paragraphsBeforeFinal = ($paragraph, paragraph) => {
1059
+ const paragraphs = [];
1060
+ let position = $paragraph.pos;
1061
+ for (let index = $paragraph.index() - 1; index >= 0; index--) {
1062
+ const node = $paragraph.parent.child(index);
1063
+ position -= node.nodeSize;
1064
+ if (node.type !== paragraph.type) break;
1065
+ const mark = node.attrs["pPrMark"];
1066
+ if (isPlainDeletedPPrMark(mark) && holdsOnlyDeletedContent(node)) continue;
1067
+ paragraphs.push({
1068
+ block: position,
1069
+ keepsBreak: mark == null
1070
+ });
1071
+ }
1072
+ return paragraphs;
1073
+ };
1042
1074
  /** What `item` claims of the document its batch resolved against; see `batch-claims.ts`. */
1043
1075
  const batchClaimOf = ({ item, doc, producesTrackedChanges }) => {
1044
1076
  const block = item.blockFrom;
@@ -1090,7 +1122,9 @@ const batchClaimOf = ({ item, doc, producesTrackedChanges }) => {
1090
1122
  type: "deleteBlock",
1091
1123
  block,
1092
1124
  end: item.blockTo,
1093
- keepsParagraph
1125
+ keepsParagraph,
1126
+ endsContainer: endsItsContainer,
1127
+ paragraphsBefore: producesTrackedChanges && endsItsContainer ? paragraphsBeforeFinal(at, item.blockNode) : []
1094
1128
  };
1095
1129
  }
1096
1130
  case "insertAfterBlock":
@@ -1308,22 +1342,255 @@ const rebuiltBlockContent = ({ doc, blockFrom, blockTo, content }) => annotatedR
1308
1342
  }).fragment;
1309
1343
  const isBatchableParagraphInsertion = (item, mode) => {
1310
1344
  if (item.operation.type !== "insertAfterBlock" && item.operation.type !== "insertBeforeBlock") return false;
1345
+ if (item.joinSide !== void 0) return false;
1311
1346
  if (item.commentText !== void 0) return false;
1312
1347
  const insertTexts = item.insertTexts ?? [""];
1313
1348
  const isEmptyInsert = insertTexts.length === 1 && insertTexts[0]?.length === 0;
1314
1349
  return !(mode === "tracked-changes" && item.operation.pageBreakBefore === true && isEmptyInsert);
1315
1350
  };
1316
- const insertionWithLiveAnchor = (item, tr) => {
1351
+ const insertionWithLiveAnchor = (item, tr, joinedInto) => {
1317
1352
  if (item.operation.type !== "insertAfterBlock" && item.operation.type !== "insertBeforeBlock") panic("Only paragraph insertions have insertion anchors", { operationId: item.operation.id });
1318
- const mapped = tr.mapping.mapResult(item.blockFrom, 1);
1353
+ const mapped = liveBlockResult(tr, item, 1);
1319
1354
  const anchor = mapped.deletedAcross ? null : tr.doc.nodeAt(mapped.pos);
1320
- const paraId = item.blockNode.attrs["paraId"];
1355
+ let paraId = item.blockNode.attrs["paraId"];
1356
+ while (typeof paraId === "string" && joinedInto.has(paraId)) paraId = joinedInto.get(paraId);
1321
1357
  if (!anchor?.isTextblock || anchor.type !== item.blockNode.type || typeof paraId === "string" && anchor.attrs["paraId"] !== paraId) return null;
1322
1358
  return {
1323
1359
  ...item,
1324
1360
  blockNode: anchor
1325
1361
  };
1326
1362
  };
1363
+ /** Operations that place a block in a gap between blocks. */
1364
+ const BLOCK_INSERTION_TYPES = /* @__PURE__ */ new Set([
1365
+ "insertAfterBlock",
1366
+ "insertBeforeBlock",
1367
+ "insertTable",
1368
+ "insertSignatureTable"
1369
+ ]);
1370
+ /** The steps of `tr` since `item` read its positions. */
1371
+ const sinceRead = (tr, item) => tr.mapping.slice(item.readAt ?? 0);
1372
+ /**
1373
+ * Where the block `item` names stands now, mapped from the document the
1374
+ * batch read, so the result also says whether an earlier step deleted it.
1375
+ */
1376
+ const liveBlockResult = (tr, item, assoc) => tr.mapping.mapResult(item.batchBlockFrom ?? item.blockFrom, assoc);
1377
+ /**
1378
+ * `item` with its positions read in the document as it stands now. A batch
1379
+ * runs its operations in the shared order (`orderAddressingBeforeRemoval`),
1380
+ * which can run an edit before one further left; every operation therefore
1381
+ * reads its positions through the steps already taken rather than the
1382
+ * document the batch read. A block's start stays with its content and its
1383
+ * end with what precedes it.
1384
+ */
1385
+ const readNow = (item, tr) => {
1386
+ const steps = tr.mapping.maps.length;
1387
+ if ((item.readAt ?? 0) === steps) return item;
1388
+ const mapping = sinceRead(tr, item);
1389
+ const blockFrom = mapping.map(item.blockFrom, 1);
1390
+ const blockTo = Math.max(blockFrom, mapping.map(item.blockTo, -1));
1391
+ let from;
1392
+ let to;
1393
+ if (item.from === item.to) {
1394
+ const side = item.from === item.blockTo || BLOCK_INSERTION_TYPES.has(item.operation.type) ? -1 : 1;
1395
+ from = mapping.map(item.from, side);
1396
+ to = from;
1397
+ } else {
1398
+ from = mapping.map(item.from, 1);
1399
+ to = Math.max(from, mapping.map(item.to, -1));
1400
+ }
1401
+ return {
1402
+ ...item,
1403
+ from,
1404
+ to,
1405
+ blockFrom,
1406
+ blockTo,
1407
+ readAt: steps
1408
+ };
1409
+ };
1410
+ /**
1411
+ * The paragraph a pending join makes of the one at `paragraphPos`: where its
1412
+ * break is pending removal while its words stay, accepting runs them into the
1413
+ * paragraph the join leaves, which already carries the joined paragraph's
1414
+ * properties (see `carryParagraphProperties`). Null when the paragraph stands
1415
+ * alone, or goes whole as a pending deletion.
1416
+ */
1417
+ const pendingJoinSurvivor = ({ doc, paragraphPos, cleanText, noteReferences, removedBreakPositions }) => {
1418
+ const paragraph = doc.nodeAt(paragraphPos);
1419
+ if (paragraph?.type.name !== "paragraph" || !isDeletedPPrMark(paragraph.attrs["pPrMark"]) || isPendingDeletion(doc, paragraphPos, paragraph, cleanText)) return null;
1420
+ const survivor = paragraphLeftAfter({
1421
+ doc,
1422
+ paragraphPos,
1423
+ ...removedBreakPositions ? { removedBreakPositions } : {}
1424
+ });
1425
+ const left = survivor === null ? null : doc.nodeAt(survivor);
1426
+ if (survivor === null || left?.type !== paragraph.type) return null;
1427
+ return isDeletedPPrMark(left.attrs["pPrMark"]) && isPendingDeletion(doc, survivor, left, buildCleanBlockText(left, survivor, {
1428
+ fieldResults: "text",
1429
+ noteReferences
1430
+ }).text) ? null : survivor;
1431
+ };
1432
+ /**
1433
+ * The insertion with the paragraph its new paragraphs copy properties from as
1434
+ * its anchor: a paragraph a pending join runs into another reads as that one,
1435
+ * as the joined paragraph does when the merge is applied directly. A
1436
+ * suggestion is read against the document as it stands, where the join has
1437
+ * not run anything together yet, so it copies the paragraph it names.
1438
+ */
1439
+ const insertionFormattingAnchor = ({ item, tr, mode, noteReferences, removedBreakPositions }) => {
1440
+ if (mode === "suggested") return item;
1441
+ const position = sinceRead(tr, item).map(item.blockFrom, 1);
1442
+ const anchor = tr.doc.nodeAt(position);
1443
+ if (anchor?.type !== item.blockNode.type) return item;
1444
+ const survivor = pendingJoinSurvivor({
1445
+ doc: tr.doc,
1446
+ paragraphPos: position,
1447
+ cleanText: buildCleanBlockText(anchor, position, {
1448
+ fieldResults: "text",
1449
+ noteReferences
1450
+ }).text,
1451
+ noteReferences,
1452
+ removedBreakPositions
1453
+ });
1454
+ const source = survivor === null ? null : tr.doc.nodeAt(survivor);
1455
+ return source ? {
1456
+ ...item,
1457
+ blockNode: source
1458
+ } : item;
1459
+ };
1460
+ const keepsWords = ({ doc, paragraphPos, noteReferences }) => {
1461
+ const paragraph = doc.nodeAt(paragraphPos);
1462
+ if (paragraph?.type.name !== "paragraph") return false;
1463
+ const cleanText = buildCleanBlockText(paragraph, paragraphPos, {
1464
+ fieldResults: "text",
1465
+ noteReferences
1466
+ }).text;
1467
+ return cleanText.length > 0 && !isPendingDeletion(doc, paragraphPos, paragraph, cleanText);
1468
+ };
1469
+ /**
1470
+ * Whether accepting runs the paragraph into the one its pending join leaves:
1471
+ * it keeps words, or it is empty. One whose words are all pending deletion
1472
+ * goes whole instead.
1473
+ */
1474
+ const joinsIn = (options) => options.doc.nodeAt(options.paragraphPos)?.content.size === 0 || keepsWords(options);
1475
+ /**
1476
+ * Whether a pending join runs earlier words on to `paragraphPos`, the start of
1477
+ * a paragraph or a place between blocks: the paragraphs before it, back to one
1478
+ * that keeps words, all have their breaks pending removal.
1479
+ */
1480
+ const joinRunsWordsInto = ({ doc, paragraphPos, noteReferences }) => {
1481
+ const $place = doc.resolve(paragraphPos);
1482
+ let position = paragraphPos;
1483
+ for (let index = $place.index() - 1; index >= 0; index--) {
1484
+ const previous = $place.parent.child(index);
1485
+ position -= previous.nodeSize;
1486
+ if (previous.type.name !== "paragraph" || !isDeletedPPrMark(previous.attrs["pPrMark"])) return false;
1487
+ if (keepsWords({
1488
+ doc,
1489
+ paragraphPos: position,
1490
+ noteReferences
1491
+ })) return true;
1492
+ }
1493
+ return false;
1494
+ };
1495
+ /**
1496
+ * Whether a pending join runs earlier words on to `paragraphPos`, right before
1497
+ * a table. A paragraph put there cannot stand apart once accepted: keeping its
1498
+ * own break, it takes the words, and taking the deleted break from them, it
1499
+ * runs into the table's first cell. Where that cell is itself pending nothing
1500
+ * runs into it, so a paragraph right after the words can take their break and
1501
+ * stand; so can one with a paragraph going whole between it and the table.
1502
+ */
1503
+ const joinStopsAtTableAfter = (options) => {
1504
+ if (!joinRunsWordsInto(options)) return false;
1505
+ const $place = options.doc.resolve(options.paragraphPos);
1506
+ for (let index = $place.index(); index < $place.parent.childCount; index++) {
1507
+ const next = $place.parent.child(index);
1508
+ if (next.type.name === "paragraph") return false;
1509
+ if (next.type.spec["tableRole"] === "table") {
1510
+ const before = $place.nodeBefore;
1511
+ return !runInCellPending(next) || before !== null && holdsOnlyDeletedContent(before);
1512
+ }
1513
+ }
1514
+ return false;
1515
+ };
1516
+ /**
1517
+ * Where a block goes before and after the paragraph at `paragraphPos`, read
1518
+ * as the joined paragraph a pending join makes of it. A join runs the words
1519
+ * of each paragraph whose break is pending removal into the paragraph it
1520
+ * leaves, so a block put between them would take those words once accepted,
1521
+ * as the same edits applied directly never do. Where a paragraph runs into
1522
+ * one the join leaves that keeps words of its own, a block after any
1523
+ * paragraph of the join goes after the paragraph it leaves, and a block
1524
+ * before that one goes before the first paragraph the join takes in, empty
1525
+ * ones included. A join into a paragraph with no words left (an emptied
1526
+ * final carrier, or one going whole) runs nothing together, nor does a
1527
+ * paragraph going whole with no join running through it: blocks keep their
1528
+ * places.
1529
+ */
1530
+ const pendingJoinBounds = (options) => {
1531
+ const { doc, paragraphPos, noteReferences } = options;
1532
+ const paragraph = doc.nodeAt(paragraphPos);
1533
+ let after = paragraphPos;
1534
+ if (paragraph?.type.name === "paragraph" && isDeletedPPrMark(paragraph.attrs["pPrMark"]) && (joinsIn(options) || joinRunsWordsInto(options))) {
1535
+ const survivor = paragraphLeftAfter({
1536
+ doc,
1537
+ paragraphPos
1538
+ });
1539
+ if (survivor !== null && keepsWords({
1540
+ doc,
1541
+ paragraphPos: survivor,
1542
+ noteReferences
1543
+ })) after = survivor;
1544
+ }
1545
+ let before = paragraphPos;
1546
+ if (paragraph?.type.name === "paragraph" && keepsWords(options)) {
1547
+ let start = paragraphPos;
1548
+ for (;;) {
1549
+ const previous = doc.resolve(start).nodeBefore;
1550
+ if (previous?.type !== paragraph.type || !isDeletedPPrMark(previous.attrs["pPrMark"])) break;
1551
+ start -= previous.nodeSize;
1552
+ if (joinsIn({
1553
+ doc,
1554
+ paragraphPos: start,
1555
+ noteReferences
1556
+ })) before = start;
1557
+ }
1558
+ }
1559
+ return {
1560
+ before,
1561
+ after: endOfParagraphWithItsTextBoxes(doc, after)
1562
+ };
1563
+ };
1564
+ /** Where a block insertion lands as it runs (see `joinSide`). */
1565
+ const insertionAt = ({ item, tr, noteReferences }) => {
1566
+ if (item.joinSide === void 0) return item.from;
1567
+ const position = sinceRead(tr, item).map(item.blockFrom, 1);
1568
+ if (tr.doc.nodeAt(position)?.type.name !== "paragraph") return item.from;
1569
+ return pendingJoinBounds({
1570
+ doc: tr.doc,
1571
+ paragraphPos: position,
1572
+ noteReferences
1573
+ })[item.joinSide];
1574
+ };
1575
+ /**
1576
+ * Where a block insertion lands as it runs, with the comments running across
1577
+ * that boundary. They are the ones the batch read there, so an edit that runs
1578
+ * first cannot move a comment's end out from around the block; but where an
1579
+ * earlier edit moved the join the block follows, the block lands at another
1580
+ * boundary, and carries the comments across that one.
1581
+ */
1582
+ const insertionPlacement = (options) => {
1583
+ const { item, tr } = options;
1584
+ const at = insertionAt(options);
1585
+ if (item.joinAt === void 0) return {
1586
+ at,
1587
+ comments: item.boundaryComments
1588
+ };
1589
+ return {
1590
+ at,
1591
+ comments: at === tr.mapping.map(item.joinAt, item.joinSide === "after" ? -1 : 1) ? item.boundaryComments : commentsAcrossBlockBoundary(tr.doc, at)
1592
+ };
1593
+ };
1327
1594
  /** The comments running across both edges of the table at `tablePosition`: over all of it. */
1328
1595
  const commentsAcrossTable = (doc, tablePosition) => {
1329
1596
  const table = doc.nodeAt(tablePosition);
@@ -1351,6 +1618,10 @@ const isInsertedPPrMark = (value) => typeof value === "object" && value !== null
1351
1618
  const isSuggestedParagraphInsert = (paragraph) => typeof paragraph.attrs["_suggestedInsert"] === "object" && paragraph.attrs["_suggestedInsert"] !== null;
1352
1619
  /** A paragraph mark that is a pending deletion, or a relocation's source. */
1353
1620
  const isDeletedPPrMark = (value) => typeof value === "object" && value !== null && "kind" in value && (value.kind === "del" || value.kind === "moveFrom");
1621
+ const pendingJoinInsertionRefusal = {
1622
+ reason: "pendingParagraphMarkDeletion",
1623
+ message: "Accepting the pending paragraph mark deletion before this place would run the paragraph together with the words before it or the table after it. Resolve that change first, or insert elsewhere."
1624
+ };
1354
1625
  const pendingParagraphMarkPropertyRefusal = {
1355
1626
  reason: "pendingParagraphMarkDeletion",
1356
1627
  canonicalRefusal: { gap: CANONICAL_GAP.publicPendingParagraphMarkProperties },
@@ -1614,6 +1885,20 @@ const deletedFinalParagraphAfter = (at, paragraphTypeName, insertedBy) => {
1614
1885
  }
1615
1886
  return null;
1616
1887
  };
1888
+ /** Whether every row of `node` is a table row one insertion revision of this batch added. */
1889
+ const isWhollyInsertedTable = (node, batchRevisionIds) => {
1890
+ if (node.type.spec["tableRole"] !== "table" || node.childCount === 0) return false;
1891
+ let revisionId;
1892
+ for (let index = 0; index < node.childCount; index++) {
1893
+ const row = node.child(index);
1894
+ if (row.type.spec["tableRole"] !== "row") return false;
1895
+ const { trIns, trDel } = expectTableRowAttrs(row);
1896
+ if (!trIns || trDel || !batchRevisionIds.has(trIns.revisionId)) return false;
1897
+ revisionId ??= trIns.revisionId;
1898
+ if (trIns.revisionId !== revisionId) return false;
1899
+ }
1900
+ return true;
1901
+ };
1617
1902
  /**
1618
1903
  * Where the added break of the final paragraph at `at` rotates to: the free
1619
1904
  * mark `addedBreakCarrierBefore` finds, or else a paragraph the batch deletes
@@ -1628,19 +1913,7 @@ const finalBreakCarrierBefore = (at, paragraphTypeName, batchRevisionIds) => {
1628
1913
  const free = addedBreakCarrierBefore({
1629
1914
  at,
1630
1915
  paragraphTypeName,
1631
- canCrossTable: (table) => {
1632
- if (table.childCount === 0) return false;
1633
- let revisionId;
1634
- for (let index = 0; index < table.childCount; index++) {
1635
- const row = table.child(index);
1636
- if (row.type.spec["tableRole"] !== "row") return false;
1637
- const { trIns, trDel } = expectTableRowAttrs(row);
1638
- if (!trIns || trDel || !batchRevisionIds.has(trIns.revisionId)) return false;
1639
- revisionId ??= trIns.revisionId;
1640
- if (trIns.revisionId !== revisionId) return false;
1641
- }
1642
- return true;
1643
- }
1916
+ canCrossTable: (table) => isWhollyInsertedTable(table, batchRevisionIds)
1644
1917
  });
1645
1918
  if (free) return {
1646
1919
  ...free,
@@ -1746,22 +2019,6 @@ const collapsedFinalRunSource = (doc, at, batchRevisionIds) => {
1746
2019
  }
1747
2020
  return source;
1748
2021
  };
1749
- /**
1750
- * Whether a sibling between a final carrier's predecessor and the carrier
1751
- * has its break deleted by this batch.
1752
- */
1753
- const crossesBatchDeletion = ({ doc, from, to, batchRevisionIds }) => {
1754
- const $to = doc.resolve(to);
1755
- let position = to;
1756
- for (let index = $to.index() - 1; index >= 0 && position > from; index--) {
1757
- const node = $to.parent.child(index);
1758
- position -= node.nodeSize;
1759
- const mark = node.attrs["pPrMark"];
1760
- const revisionId = isPlainDeletedPPrMark(mark) ? addedOrDeletedBreakRevisionId(mark) : null;
1761
- if (revisionId !== null && batchRevisionIds.has(revisionId)) return true;
1762
- }
1763
- return false;
1764
- };
1765
2022
  const canRetractFinalBreak = ({ predecessor, target }) => {
1766
2023
  if (target.type !== predecessor.type) return false;
1767
2024
  return !(JSON.stringify(paragraphPropertiesBeforePendingChanges(target)) !== JSON.stringify(paragraphPropertiesSnapshot(predecessor)) && hasSerializableParagraphPropertyChange(expectParagraphAttrs(predecessor)._propertyChanges));
@@ -1778,8 +2035,8 @@ const pendingRemovedFinalBreakPositions = (tr, deletions) => {
1778
2035
  return positions;
1779
2036
  };
1780
2037
  /** An unoccupied final carrier takes admissible writes from the finished batch. */
1781
- const finalParagraphCarry = ({ tr, at, target, predecessor, batchRevisionIds, styleResolver, numbering }) => {
1782
- const { node: previous, position } = predecessor;
2038
+ const finalParagraphCarry = ({ target, predecessor, batchRevisionIds, styleResolver, numbering }) => {
2039
+ const { node: previous } = predecessor;
1783
2040
  const beforeBatch = hasSerializableParagraphPropertyChange(expectParagraphAttrs(target)._propertyChanges) ? resolveParagraphChangeAttrs({
1784
2041
  node: previous,
1785
2042
  mode: "reject",
@@ -1788,15 +2045,7 @@ const finalParagraphCarry = ({ tr, at, target, predecessor, batchRevisionIds, st
1788
2045
  styleResolver,
1789
2046
  numbering
1790
2047
  }) : null;
1791
- return {
1792
- source: beforeBatch ? previous.type.create(beforeBatch, previous.content, previous.marks) : previous,
1793
- keep: crossesBatchDeletion({
1794
- doc: tr.doc,
1795
- from: position + previous.nodeSize,
1796
- to: at,
1797
- batchRevisionIds
1798
- }) ? /* @__PURE__ */ new Set() : propertiesSetInBatch(target, batchRevisionIds)
1799
- };
2048
+ return { source: beforeBatch ? previous.type.create(beforeBatch, previous.content, previous.marks) : previous };
1800
2049
  };
1801
2050
  /** Deferred retirement still owns a slot before a later explicit formatting merge. */
1802
2051
  const hasDeferredParagraphPropertyWrite = ({ tr, deletions, targets, mergedPropertyTargets, batchRevisionIds, styleResolver, numbering }) => {
@@ -1819,26 +2068,19 @@ const hasDeferredParagraphPropertyWrite = ({ tr, deletions, targets, mergedPrope
1819
2068
  }))) continue;
1820
2069
  const transfer = mark == null ? finalParagraphCarry({
1821
2070
  tr,
1822
- at,
1823
2071
  target,
1824
2072
  predecessor,
1825
2073
  batchRevisionIds,
1826
2074
  styleResolver,
1827
2075
  numbering
1828
- }) : {
1829
- source: predecessor.node,
1830
- keep: propertiesSetInBatch(writeTarget, batchRevisionIds)
1831
- };
1832
- if (JSON.stringify(paragraphPropertiesSnapshot(writeTarget)) !== JSON.stringify(carriedParagraphProperties({
1833
- ...transfer,
1834
- target: writeTarget
1835
- }))) return true;
2076
+ }) : { source: predecessor.node };
2077
+ if (JSON.stringify(paragraphPropertiesSnapshot(writeTarget)) !== JSON.stringify(paragraphPropertiesSnapshot(transfer.source))) return true;
1836
2078
  }
1837
2079
  return false;
1838
2080
  };
1839
2081
  /** The paragraph a merge leaves owns its properties, even across pending deleted breaks. */
1840
2082
  const paragraphPropertyRevisionTargets = ({ item, tr, deletedFinalParagraphs }) => {
1841
- const position = tr.mapping.map(item.blockFrom, item.operation.type === "replaceBlock" ? -1 : 1);
2083
+ const position = sinceRead(tr, item).map(item.blockFrom, item.operation.type === "replaceBlock" ? -1 : 1);
1842
2084
  const source = tr.doc.nodeAt(position) ?? item.blockNode;
1843
2085
  const targets = source.type.name === "paragraph" ? [source] : [];
1844
2086
  if (item.operation.type !== "mergeBlockWithNext") return targets;
@@ -1915,8 +2157,7 @@ const withRetiredFinalParagraphs = ({ tr, deletions, mergedPropertyTargets, appl
1915
2157
  author,
1916
2158
  date,
1917
2159
  ...revisionExtras
1918
- },
1919
- keep: /* @__PURE__ */ new Set()
2160
+ }
1920
2161
  });
1921
2162
  if (carried.tracked) {
1922
2163
  nextRevisionId++;
@@ -1950,7 +2191,6 @@ const withRetiredFinalParagraphs = ({ tr, deletions, mergedPropertyTargets, appl
1950
2191
  position: at,
1951
2192
  ...finalParagraphCarry({
1952
2193
  tr,
1953
- at,
1954
2194
  target: emptied,
1955
2195
  predecessor,
1956
2196
  batchRevisionIds,
@@ -1995,7 +2235,6 @@ const withRetiredFinalParagraphs = ({ tr, deletions, mergedPropertyTargets, appl
1995
2235
  doc: tr.doc,
1996
2236
  paragraphPos: position
1997
2237
  }) ?? position : position;
1998
- const carryTarget = tr.doc.nodeAt(carryPosition) ?? following;
1999
2238
  const revisionId = nextRevisionId;
2000
2239
  if (carryParagraphProperties({
2001
2240
  tr,
@@ -2008,8 +2247,7 @@ const withRetiredFinalParagraphs = ({ tr, deletions, mergedPropertyTargets, appl
2008
2247
  author,
2009
2248
  date,
2010
2249
  ...revisionExtras
2011
- },
2012
- keep: propertiesSetInBatch(carryTarget, batchRevisionIds)
2250
+ }
2013
2251
  }).tracked) {
2014
2252
  nextRevisionId++;
2015
2253
  addedRevisions.push({
@@ -2069,6 +2307,7 @@ const withRotatedAddedFinalBreaks = ({ tr, batchRevisionIds, revisionSeed, autho
2069
2307
  let carriedDeletedFormatting = null;
2070
2308
  parent.forEach((node, offset) => {
2071
2309
  const position = contentStart + offset;
2310
+ if (isWhollyInsertedTable(node, batchRevisionIds)) return;
2072
2311
  if (node.type.name !== "paragraph") {
2073
2312
  previous = null;
2074
2313
  carriedDeletedMark = null;
@@ -2215,25 +2454,38 @@ const withRotatedAddedFinalBreaks = ({ tr, batchRevisionIds, revisionSeed, autho
2215
2454
  const liveCurrent = next.doc.nodeAt(current.position);
2216
2455
  if (!liveCurrent || liveCurrent.type.name !== final.type.name) panic("A final-mark rotation lost its paragraph", { position: current.position });
2217
2456
  const existing = expectParagraphAttrs(liveCurrent)._propertyChanges;
2218
- if (hasSerializableParagraphPropertyChange(existing)) panic("A final-mark rotation cannot append a second w:pPrChange", { position: current.position });
2219
- const revisionId = nextRevisionId++;
2220
- next = next.setNodeMarkup(current.position, void 0, {
2221
- ...liveCurrent.attrs,
2222
- _propertyChanges: [...Array.isArray(existing) ? existing : [], {
2223
- type: "paragraphPropertyChange",
2224
- info: {
2225
- id: revisionId,
2226
- author,
2227
- date,
2228
- ...initials ? { initials } : {}
2229
- },
2457
+ if (hasSerializableParagraphPropertyChange(existing)) {
2458
+ const serialized = (existing ?? []).filter(({ info }) => info.provenance !== "suggested");
2459
+ if (!serialized.every(({ info }) => batchRevisionIds.has(info.id))) panic("A final-mark rotation met a w:pPrChange from outside", { position: current.position });
2460
+ const restated = [];
2461
+ for (const change of existing ?? []) restated.push(serialized.includes(change) ? {
2462
+ ...change,
2230
2463
  previousFormatting
2231
- }]
2232
- });
2233
- synthesizedRevisions.push({
2234
- ownerRevisionId,
2235
- revisionId
2236
- });
2464
+ } : change);
2465
+ next = next.setNodeMarkup(current.position, void 0, {
2466
+ ...liveCurrent.attrs,
2467
+ _propertyChanges: restated
2468
+ });
2469
+ } else {
2470
+ const revisionId = nextRevisionId++;
2471
+ next = next.setNodeMarkup(current.position, void 0, {
2472
+ ...liveCurrent.attrs,
2473
+ _propertyChanges: [...Array.isArray(existing) ? existing : [], {
2474
+ type: "paragraphPropertyChange",
2475
+ info: {
2476
+ id: revisionId,
2477
+ author,
2478
+ date,
2479
+ ...initials ? { initials } : {}
2480
+ },
2481
+ previousFormatting
2482
+ }]
2483
+ });
2484
+ synthesizedRevisions.push({
2485
+ ownerRevisionId,
2486
+ revisionId
2487
+ });
2488
+ }
2237
2489
  }
2238
2490
  if (cancels) {
2239
2491
  const deleted = next.doc.nodeAt(previous.position);
@@ -2490,7 +2742,29 @@ const buildInsertedParagraphs = ({ item, schema, formattingFromStyle, mode, auth
2490
2742
  nextRevisionId
2491
2743
  };
2492
2744
  };
2493
- const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: requestedOperations, mode = "tracked-changes", author = "AI", initials, createCommentId, revisionStamp, revisionIdSeed, wordDiff, wordDiffMode = "bounded", tableTemplates, replacementBackground = "clear", undefinedReferences }) => {
2745
+ /** The story's last block but for text boxes, which stand after their paragraph. */
2746
+ const lastBlockBeforeTextBoxes = (doc) => {
2747
+ let position = doc.content.size;
2748
+ for (let index = doc.childCount - 1; index >= 0; index--) {
2749
+ const node = doc.child(index);
2750
+ position -= node.nodeSize;
2751
+ if (node.type.name !== "textBox") return {
2752
+ node,
2753
+ position
2754
+ };
2755
+ }
2756
+ return null;
2757
+ };
2758
+ /**
2759
+ * A story that ended with a table now ends with a tracked paragraph: resolving
2760
+ * it away restores that ending, though a story otherwise keeps a final paragraph.
2761
+ */
2762
+ const markTerminalTableReviewCarrier = (tr, before) => {
2763
+ if (lastBlockBeforeTextBoxes(before)?.node.type.name !== "table") return;
2764
+ const last = lastBlockBeforeTextBoxes(tr.doc);
2765
+ if (last?.node.type.name === "paragraph" && expectParagraphAttrs(last.node).pPrMark?.kind === "ins") tr.setNodeAttribute(last.position, "reviewCarrier", REVIEW_CARRIERS.TERMINAL_TABLE);
2766
+ };
2767
+ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: requestedOperations, mode = "tracked-changes", author = "AI", initials, createCommentId, revisionStamp, revisionIdSeed, wordDiff, wordDiffMode = "bounded", tableTemplates, replacementBackground = "clear", undefinedReferences, numberingIdsElsewhere }) => {
2494
2768
  seedRevisionIdsFromDoc(view.state.doc);
2495
2769
  const applied = [];
2496
2770
  const skipped = [];
@@ -2571,7 +2845,8 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
2571
2845
  liveBlocks,
2572
2846
  liveBlocksByParaId,
2573
2847
  noteReferences,
2574
- doc: view.state.doc
2848
+ doc: view.state.doc,
2849
+ mode
2575
2850
  });
2576
2851
  if (resolution.type === "skip") {
2577
2852
  skipped.push({
@@ -2652,7 +2927,8 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
2652
2927
  "splitTableCell"
2653
2928
  ].includes(operation.type) ? removedBlocksBy.get(targetBlockId) : void 0;
2654
2929
  const continuesMergeChain = operation.type === "mergeBlockWithNext" && removedBy?.type === "mergeBlockWithNext";
2655
- if (removedBy !== void 0 && !continuesMergeChain) {
2930
+ const formatsBeforeRemoval = operation.type === "setBlockParagraphProperties" && (removedBy?.type === "mergeBlockWithNext" || removedBy?.type === "deleteBlock");
2931
+ if (removedBy !== void 0 && !continuesMergeChain && !formatsBeforeRemoval) {
2656
2932
  skipped.push({
2657
2933
  id: operation.id,
2658
2934
  reason: "overlappingOperation",
@@ -2692,6 +2968,7 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
2692
2968
  });
2693
2969
  resolved.push({
2694
2970
  ...resolution.operation,
2971
+ batchBlockFrom: resolution.operation.blockFrom,
2695
2972
  originalIndex: index,
2696
2973
  ...commentText !== void 0 && { commentText }
2697
2974
  });
@@ -2813,18 +3090,71 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
2813
3090
  inputIndex: item.originalIndex
2814
3091
  };
2815
3092
  };
2816
- const executionOrder = orderBatchOperations(executableResolved, batchAddress);
3093
+ const batchDeletions = new Set(executableResolved.flatMap((item) => item.operation.type === "deleteBlock" ? [item.blockFrom] : []));
3094
+ const blockAccess = (item) => {
3095
+ const doc = view.state.doc;
3096
+ if (item.operation.type === "mergeBlockWithNext") {
3097
+ const next = paragraphJoinAfter(doc, item.blockTo);
3098
+ return {
3099
+ addresses: [item.blockFrom],
3100
+ removes: next ? [next.nextPosition] : []
3101
+ };
3102
+ }
3103
+ if (item.operation.type === "deleteTableRow" || item.operation.type === "deleteTable") return {
3104
+ addresses: [],
3105
+ removes: [item.blockFrom]
3106
+ };
3107
+ if (item.tableColumnInsertion ?? item.tableColumnDeletion ?? item.tableCellMerge ?? item.tableCellSplit) return {
3108
+ addresses: [],
3109
+ removes: []
3110
+ };
3111
+ if (item.operation.type !== "deleteBlock") return {
3112
+ addresses: [item.blockFrom],
3113
+ removes: []
3114
+ };
3115
+ const at = doc.resolve(item.blockFrom);
3116
+ let hasKeptParagraphBefore = false;
3117
+ let position = at.pos;
3118
+ for (let index = at.index() - 1; index >= 0; index -= 1) {
3119
+ const previous = at.parent.child(index);
3120
+ position -= previous.nodeSize;
3121
+ if (previous.type !== item.blockNode.type) break;
3122
+ if (!batchDeletions.has(position)) {
3123
+ hasKeptParagraphBefore = true;
3124
+ break;
3125
+ }
3126
+ }
3127
+ const appended = executableResolved.some((other) => other.blockFrom === item.blockFrom && (other.operation.type === "insertAfterBlock" || other.operation.type === "insertTable" && other.operation.position !== "before"));
3128
+ return {
3129
+ addresses: [],
3130
+ removes: deletionRemovesBlock({
3131
+ endsContainer: !appended && paragraphEndsItsContainer(at, item.blockNode.type.name),
3132
+ hasKeptParagraphBefore
3133
+ }) ? [item.blockFrom] : []
3134
+ };
3135
+ };
3136
+ const groupRuns = (items) => groupInsertionRuns(items, (candidate) => isBatchableParagraphInsertion(candidate, mode) ? candidate.from : null, (candidate) => candidate.operation.type === "setBlockParagraphProperties");
3137
+ const executionOrder = orderAddressingBeforeRemoval(groupRuns(orderBatchOperations(executableResolved, batchAddress)), (run) => {
3138
+ const access = run.map(blockAccess);
3139
+ return {
3140
+ addresses: access.flatMap(({ addresses }) => addresses),
3141
+ removes: access.flatMap(({ removes }) => removes)
3142
+ };
3143
+ }).flat();
2817
3144
  const allocateNewLists = ({ items }) => {
2818
- const allocated = resolveNewListOperations(items.map(({ operation }) => operation), numbering);
3145
+ const allocated = resolveNewListOperations(items.map(({ operation }) => operation), numbering, numberingIdsElsewhere);
2819
3146
  numbering = allocated.numbering;
2820
3147
  for (const [index, candidate] of items.entries()) candidate.operation = allocated.operations[index] ?? panic("A will-apply operation lost its new-list allocation", { id: candidate.operation.id });
2821
3148
  };
2822
- const executionGroups = groupInsertionRuns(executionOrder, (candidate) => isBatchableParagraphInsertion(candidate, mode) ? candidate.from : null, (candidate) => candidate.operation.type === "setBlockParagraphProperties");
3149
+ /** Paragraphs a retracted break of this batch joined, to the one it left. */
3150
+ const joinedInto = /* @__PURE__ */ new Map();
3151
+ const executionGroups = groupRuns(executionOrder);
2823
3152
  for (const executionGroup of executionGroups) {
2824
3153
  const insertionState = tr;
2825
- const insertionRun = executionGroup.flatMap((candidate) => {
3154
+ const insertionRun = executionGroup.flatMap((resolvedCandidate) => {
3155
+ const candidate = readNow(resolvedCandidate, insertionState);
2826
3156
  if (candidate.operation.type !== "insertAfterBlock" && candidate.operation.type !== "insertBeforeBlock") return [candidate];
2827
- const liveCandidate = insertionWithLiveAnchor(candidate, insertionState);
3157
+ const liveCandidate = insertionWithLiveAnchor(candidate, insertionState, joinedInto);
2828
3158
  if (!liveCandidate) {
2829
3159
  if (!isSuggested) return [candidate];
2830
3160
  if (candidate.operation.moveId !== void 0) refusedMoveIds.add(candidate.operation.moveId);
@@ -2835,7 +3165,7 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
2835
3165
  return [];
2836
3166
  }
2837
3167
  if (isSuggested) {
2838
- const blockFrom = insertionState.mapping.map(candidate.blockFrom, 1);
3168
+ const blockFrom = sinceRead(insertionState, candidate).map(candidate.blockFrom, 1);
2839
3169
  if (isPendingDeletion(insertionState.doc, blockFrom, liveCandidate.blockNode, buildCleanBlockText(liveCandidate.blockNode, blockFrom, {
2840
3170
  fieldResults: "text",
2841
3171
  noteReferences
@@ -2887,10 +3217,17 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
2887
3217
  const runApplied = [];
2888
3218
  for (const insertion of insertionRun) {
2889
3219
  const insertionSuggestionId = isSuggested ? insertion.operation.suggestionId ?? insertion.operation.id : null;
2890
- const built = buildInsertedParagraphs({
3220
+ const formatted = insertionFormattingAnchor({
2891
3221
  item: insertion,
3222
+ tr,
3223
+ mode,
3224
+ noteReferences,
3225
+ removedBreakPositions: pendingRemovedFinalBreakPositions(tr, deletedFinalParagraphs)
3226
+ });
3227
+ const built = buildInsertedParagraphs({
3228
+ item: formatted,
2892
3229
  schema: view.state.schema,
2893
- formattingFromStyle: formattingFromStyleForInsertion(insertion),
3230
+ formattingFromStyle: formattingFromStyleForInsertion(formatted),
2894
3231
  mode,
2895
3232
  author,
2896
3233
  date,
@@ -2918,7 +3255,11 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
2918
3255
  for (const group of nodeGroups.toReversed()) for (const node of group) nodes.push(node);
2919
3256
  tr = insertBlocksInsideComments({
2920
3257
  tr,
2921
- at: item.from,
3258
+ at: insertionAt({
3259
+ item,
3260
+ tr,
3261
+ noteReferences
3262
+ }),
2922
3263
  blocks: nodes,
2923
3264
  ...item.boundaryComments !== void 0 && { carriedComments: item.boundaryComments }
2924
3265
  });
@@ -3115,7 +3456,7 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
3115
3456
  case "replaceBlock": {
3116
3457
  if (!isResolvedReplaceBlockOperation(item)) panic("Resolved replaceBlock operation lost its impact discriminator");
3117
3458
  const { changesStyle, changesText } = REPLACE_BLOCK_IMPACT[item.replaceBlockImpact];
3118
- if (changesStyle && isDeletedPPrMark(tr.doc.nodeAt(tr.mapping.map(item.blockFrom, -1))?.attrs["pPrMark"])) {
3459
+ if (changesStyle && isDeletedPPrMark(tr.doc.nodeAt(sinceRead(tr, item).map(item.blockFrom, -1))?.attrs["pPrMark"])) {
3119
3460
  skipped.push({
3120
3461
  id: item.operation.id,
3121
3462
  ...pendingParagraphMarkPropertyRefusal
@@ -3286,10 +3627,17 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
3286
3627
  items: [item]
3287
3628
  });
3288
3629
  assertNewListsAllocated(item.operation);
3289
- const built = buildInsertedParagraphs({
3630
+ const formatted = insertionFormattingAnchor({
3290
3631
  item,
3632
+ tr,
3633
+ mode,
3634
+ noteReferences,
3635
+ removedBreakPositions: pendingRemovedFinalBreakPositions(tr, deletedFinalParagraphs)
3636
+ });
3637
+ const built = buildInsertedParagraphs({
3638
+ item: formatted,
3291
3639
  schema: view.state.schema,
3292
- formattingFromStyle: formattingFromStyleForInsertion(item),
3640
+ formattingFromStyle: formattingFromStyleForInsertion(formatted),
3293
3641
  mode,
3294
3642
  author,
3295
3643
  date,
@@ -3303,11 +3651,16 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
3303
3651
  });
3304
3652
  operationRevisionSeed = built.nextRevisionId;
3305
3653
  if (built.revisionIds.length > 0) appliedRevisionIds = built.revisionIds;
3654
+ const placement = insertionPlacement({
3655
+ item,
3656
+ tr,
3657
+ noteReferences
3658
+ });
3306
3659
  tr = insertBlocksInsideComments({
3307
3660
  tr,
3308
- at: item.from,
3661
+ at: placement.at,
3309
3662
  blocks: built.nodes,
3310
- ...item.boundaryComments !== void 0 && { carriedComments: item.boundaryComments }
3663
+ ...placement.comments !== void 0 && { carriedComments: placement.comments }
3311
3664
  });
3312
3665
  break;
3313
3666
  }
@@ -3345,7 +3698,11 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
3345
3698
  }, signatureTable.content, signatureTable.marks);
3346
3699
  appliedRevisionIds = [revisionId];
3347
3700
  }
3348
- tr = tr.insert(item.from, node);
3701
+ tr = tr.insert(insertionAt({
3702
+ item,
3703
+ tr,
3704
+ noteReferences
3705
+ }), node);
3349
3706
  break;
3350
3707
  }
3351
3708
  case "insertTableRow": {
@@ -3617,7 +3974,7 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
3617
3974
  to: item.to,
3618
3975
  mark: deletionMark
3619
3976
  });
3620
- const atomRanges = undeletedContentAtomRanges(tr, item.blockFrom);
3977
+ const atomRanges = undeletedContentAtomRanges(tr, item.blockFrom, item.readAt ?? 0);
3621
3978
  for (const { from, to } of atomRanges) addTrackedDeletionMark({
3622
3979
  insertionPolicy: "preserve-pending",
3623
3980
  tr,
@@ -3625,7 +3982,7 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
3625
3982
  to,
3626
3983
  mark: deletionMark
3627
3984
  });
3628
- for (const anchorId of textBoxAnchorIdsBetween(tr.doc, tr.mapping.map(item.blockFrom), tr.mapping.map(item.blockTo))) deletedTextBoxAnchorIds.add(anchorId);
3985
+ for (const anchorId of textBoxAnchorIdsBetween(tr.doc, sinceRead(tr, item).map(item.blockFrom), sinceRead(tr, item).map(item.blockTo))) deletedTextBoxAnchorIds.add(anchorId);
3629
3986
  encloseWholeControls({
3630
3987
  tr,
3631
3988
  from: item.blockFrom,
@@ -3634,7 +3991,7 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
3634
3991
  });
3635
3992
  const inlineRevisionApplied = item.from < item.to || atomRanges.length > 0;
3636
3993
  appliedRevisionIds = inlineRevisionApplied ? [revisionId] : [];
3637
- let markPosition = tr.mapping.map(item.blockFrom);
3994
+ let markPosition = sinceRead(tr, item).map(item.blockFrom);
3638
3995
  const markOwner = tr.doc.nodeAt(markPosition);
3639
3996
  const across = markOwner && !isPairedMove(item.operation.moveId) && addedBreakRevisionId(markOwner.attrs["pPrMark"]) !== null ? paragraphAcrossVanishingTables(tr.doc, markPosition) : null;
3640
3997
  if (across !== null) markPosition = moveParagraphPastTables(tr, markPosition, across);
@@ -3729,10 +4086,15 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
3729
4086
  continue;
3730
4087
  }
3731
4088
  if (producesTrackedChanges) appliedRevisionIds = [operationRevisionSeed++];
3732
- const carriedComments = tableAfterDeletedSplit.get(item.blockFrom);
3733
- const usesRetractedSplit = carriedComments !== void 0 && item.from === item.blockTo;
3734
- let at = usesRetractedSplit ? tr.mapping.map(item.blockFrom, -1) : item.from;
3735
- let insertionComments = carriedComments ?? item.boundaryComments;
4089
+ const carriedComments = tableAfterDeletedSplit.get(item.batchBlockFrom ?? item.blockFrom);
4090
+ const usesRetractedSplit = carriedComments !== void 0 && item.from === item.blockTo && liveBlockResult(tr, item, 1).deletedAcross;
4091
+ const placement = insertionPlacement({
4092
+ item,
4093
+ tr,
4094
+ noteReferences
4095
+ });
4096
+ let at = usesRetractedSplit ? sinceRead(tr, item).map(item.blockFrom, -1) : placement.at;
4097
+ let insertionComments = carriedComments ?? placement.comments;
3736
4098
  if (!usesRetractedSplit) {
3737
4099
  const boundary = tr.doc.resolve(at);
3738
4100
  const before = boundary.nodeBefore;
@@ -3857,7 +4219,7 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
3857
4219
  break;
3858
4220
  }
3859
4221
  case "setBlockParagraphProperties": {
3860
- const mapped = tr.mapping.mapResult(item.blockFrom);
4222
+ const mapped = liveBlockResult(tr, item);
3861
4223
  const liveBlock = mapped.deletedAcross ? null : tr.doc.nodeAt(mapped.pos);
3862
4224
  const paraId = item.blockNode.attrs["paraId"];
3863
4225
  if (!liveBlock || liveBlock.type !== item.blockNode.type || typeof paraId === "string" && liveBlock.attrs["paraId"] !== paraId) {
@@ -3954,6 +4316,19 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
3954
4316
  kind: "ins",
3955
4317
  info
3956
4318
  });
4319
+ const second = tr.doc.nodeAt(item.from + 1);
4320
+ const survivor = mode === "tracked-changes" && isDeletedPPrMark(second?.attrs["pPrMark"]) ? paragraphLeftAfter({
4321
+ doc: tr.doc,
4322
+ paragraphPos: item.from + 1
4323
+ }) : null;
4324
+ const source = survivor === null ? null : tr.doc.nodeAt(survivor);
4325
+ if (source) tr = carryParagraphProperties({
4326
+ tr,
4327
+ position: item.blockFrom,
4328
+ source,
4329
+ styleResolver,
4330
+ numbering
4331
+ }).tr;
3957
4332
  }
3958
4333
  const allocateSplitParagraphPropertyRevisionInfo = () => ({
3959
4334
  id: operationRevisionSeed++,
@@ -3987,7 +4362,7 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
3987
4362
  break;
3988
4363
  }
3989
4364
  case "mergeBlockWithNext": {
3990
- const mapped = tr.mapping.mapResult(item.blockFrom, 1);
4365
+ const mapped = liveBlockResult(tr, item, 1);
3991
4366
  const live = mapped.deletedAcross ? null : tr.doc.nodeAt(mapped.pos);
3992
4367
  const paraId = item.blockNode.attrs["paraId"];
3993
4368
  if (!live || live.type !== item.blockNode.type || typeof paraId === "string" && live.attrs["paraId"] !== paraId) {
@@ -4102,7 +4477,7 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
4102
4477
  const nextPosition = join.nextPosition + separator.length;
4103
4478
  const next = tr.doc.nodeAt(nextPosition);
4104
4479
  if (!paragraph || !next) panic("A resolved merge lost its paragraphs");
4105
- if (isInsertedPPrMark(paragraph.attrs["pPrMark"])) {
4480
+ if (addedBreakRevisionId(paragraph.attrs["pPrMark"]) !== null) {
4106
4481
  joinAtParagraphMark({
4107
4482
  tr,
4108
4483
  paragraphPos: blockFrom,
@@ -4110,6 +4485,9 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
4110
4485
  next,
4111
4486
  styleResolver
4112
4487
  });
4488
+ const firstId = paragraph.attrs["paraId"];
4489
+ const nextId = next.attrs["paraId"];
4490
+ if (typeof firstId === "string" && typeof nextId === "string") joinedInto.set(firstId, nextId);
4113
4491
  const joinedMark = tr.doc.nodeAt(blockFrom)?.attrs["pPrMark"];
4114
4492
  const removedBreakPositions = pendingRemovedFinalBreakPositions(tr, deletedFinalParagraphs);
4115
4493
  const carryPos = isDeletedPPrMark(joinedMark) || removedBreakPositions.has(blockFrom) ? paragraphLeftAfter({
@@ -4245,6 +4623,7 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
4245
4623
  });
4246
4624
  }
4247
4625
  removeRowsWithoutCellsAfterBatch(tr, emptiedRows);
4626
+ markTerminalTableReviewCarrier(tr, view.state.doc);
4248
4627
  if (tr.docChanged || deferredNoopFinalDeletions.size > 0) {
4249
4628
  const batchRevisionIds = new Set(applied.flatMap(({ revisionIds }) => revisionIds ?? []));
4250
4629
  tr = withoutRevisionsOnZeroWidthAnchors(tr, batchRevisionIds, deletedTextBoxAnchorIds);
@@ -4348,8 +4727,16 @@ const applyFolioAIEditOperationsInternal = ({ view, snapshot, operations: reques
4348
4727
  nextRevisionId: revisionSeed
4349
4728
  };
4350
4729
  };
4351
- const applyFolioAIEditOperations = (options) => applyFolioAIEditOperationsInternal(options);
4352
- const previewFolioAIEditOperations = (options) => previewFolioAIEditOperationsWithResult(options).outcome;
4730
+ const applyFolioAIEditOperations = (options) => applyFolioAIEditOperationsInternal({
4731
+ ...options,
4732
+ numberingIdsElsewhere: NO_NUMBERING_IDS_IN_USE
4733
+ });
4734
+ /** {@link applyFolioAIEditOperations} for a caller holding every story. Internal. */
4735
+ const applyFolioAIEditOperationsInPackage = (options) => applyFolioAIEditOperationsInternal(options);
4736
+ const previewFolioAIEditOperations = (options) => previewFolioAIEditOperationsWithResult({
4737
+ ...options,
4738
+ numberingIdsElsewhere: NO_NUMBERING_IDS_IN_USE
4739
+ }).outcome;
4353
4740
  /**
4354
4741
  * A preview together with the document it would leave and the provisional
4355
4742
  * comment ids it placed, for a caller that checks the result before reporting
@@ -5228,7 +5615,7 @@ const refuseNoteReferenceEdit = (item, noteReferences) => {
5228
5615
  reason: "protectedReference"
5229
5616
  } : null;
5230
5617
  };
5231
- const resolveOperationTarget = ({ snapshot, operation, liveBlocks, liveBlocksByParaId, noteReferences, doc }) => {
5618
+ const resolveOperationTarget = ({ snapshot, operation, liveBlocks, liveBlocksByParaId, noteReferences, doc, mode }) => {
5232
5619
  const blockId = operation.type === "replaceRange" || operation.type === "commentOnRange" || operation.type === "formatRange" ? operation.range.blockId : operation.blockId;
5233
5620
  const primaryBlock = resolveStableBlock({
5234
5621
  snapshot,
@@ -5243,6 +5630,28 @@ const resolveOperationTarget = ({ snapshot, operation, liveBlocks, liveBlocksByP
5243
5630
  type: "skip",
5244
5631
  reason: "preconditionFailed"
5245
5632
  };
5633
+ const joinBounds = () => mode === "suggested" ? {
5634
+ before: blockFrom,
5635
+ after: endOfParagraphWithItsTextBoxes(doc, blockFrom)
5636
+ } : pendingJoinBounds({
5637
+ doc,
5638
+ paragraphPos: blockFrom,
5639
+ noteReferences
5640
+ });
5641
+ const beside = (side) => {
5642
+ const plain = side === "after" ? endOfParagraphWithItsTextBoxes(doc, blockFrom) : blockFrom;
5643
+ const at = joinBounds()[side];
5644
+ const from = side === "after" ? plain : at;
5645
+ return at === plain ? {
5646
+ from,
5647
+ at
5648
+ } : {
5649
+ from,
5650
+ at,
5651
+ joinSide: side,
5652
+ joinAt: at
5653
+ };
5654
+ };
5246
5655
  if (operation.type === "replaceRange" || operation.type === "commentOnRange" || operation.type === "formatRange") {
5247
5656
  const { startOffset, endOffset, selectedTextHash } = operation.range;
5248
5657
  if (cleanBlock.offsets[startOffset] === void 0 || cleanBlock.offsets[endOffset] === void 0) return {
@@ -5291,11 +5700,20 @@ const resolveOperationTarget = ({ snapshot, operation, liveBlocks, liveBlocksByP
5291
5700
  }
5292
5701
  if (operation.type === "insertAfterBlock" || operation.type === "insertBeforeBlock") {
5293
5702
  const tableBoundary = findOutermostTableBoundary(doc, blockFrom);
5294
- const isInsertAfter = operation.type === "insertAfterBlock";
5295
- let insertFrom;
5296
- if (tableBoundary) insertFrom = isInsertAfter ? tableBoundary.after : tableBoundary.before;
5297
- else insertFrom = isInsertAfter ? endOfParagraphWithItsTextBoxes(doc, blockFrom) : blockFrom;
5298
- const insertTexts = operation.lineBreakMode !== "inline" && LINE_BREAK_PATTERN.test(operation.text) ? splitInsertParagraphTexts(operation.text) : [operation.text];
5703
+ const side = operation.type === "insertAfterBlock" ? "after" : "before";
5704
+ const placed = tableBoundary ? {
5705
+ from: tableBoundary[side],
5706
+ at: tableBoundary[side]
5707
+ } : beside(side);
5708
+ if (joinStopsAtTableAfter({
5709
+ doc,
5710
+ paragraphPos: placed.at,
5711
+ noteReferences
5712
+ })) return {
5713
+ type: "skip",
5714
+ ...pendingJoinInsertionRefusal
5715
+ };
5716
+ const insertFrom = placed.from;
5299
5717
  return {
5300
5718
  type: "resolved",
5301
5719
  operation: {
@@ -5305,8 +5723,12 @@ const resolveOperationTarget = ({ snapshot, operation, liveBlocks, liveBlocksByP
5305
5723
  blockFrom,
5306
5724
  blockTo,
5307
5725
  blockNode,
5308
- insertTexts,
5309
- boundaryComments: commentsAcrossBlockBoundary(doc, insertFrom)
5726
+ insertTexts: operation.lineBreakMode !== "inline" && LINE_BREAK_PATTERN.test(operation.text) ? splitInsertParagraphTexts(operation.text) : [operation.text],
5727
+ boundaryComments: commentsAcrossBlockBoundary(doc, placed.at),
5728
+ ...placed.joinSide !== void 0 && {
5729
+ joinSide: placed.joinSide,
5730
+ joinAt: placed.joinAt
5731
+ }
5310
5732
  }
5311
5733
  };
5312
5734
  }
@@ -5317,18 +5739,23 @@ const resolveOperationTarget = ({ snapshot, operation, liveBlocks, liveBlocksByP
5317
5739
  };
5318
5740
  const position = operation.position ?? "after";
5319
5741
  const tableBoundary = findOutermostTableBoundary(doc, blockFrom);
5320
- let insertFrom;
5321
- if (tableBoundary) insertFrom = position === "after" ? tableBoundary.after : tableBoundary.before;
5322
- else insertFrom = position === "after" ? endOfParagraphWithItsTextBoxes(doc, blockFrom) : blockFrom;
5742
+ const placed = tableBoundary ? {
5743
+ from: tableBoundary[position],
5744
+ at: tableBoundary[position]
5745
+ } : beside(position);
5323
5746
  return {
5324
5747
  type: "resolved",
5325
5748
  operation: {
5326
5749
  operation,
5327
- from: insertFrom,
5328
- to: insertFrom,
5750
+ from: placed.from,
5751
+ to: placed.from,
5329
5752
  blockFrom,
5330
5753
  blockTo,
5331
- blockNode
5754
+ blockNode,
5755
+ ...placed.joinSide !== void 0 && {
5756
+ joinSide: placed.joinSide,
5757
+ joinAt: placed.joinAt
5758
+ }
5332
5759
  }
5333
5760
  };
5334
5761
  }
@@ -5549,21 +5976,26 @@ const resolveOperationTarget = ({ snapshot, operation, liveBlocks, liveBlocksByP
5549
5976
  };
5550
5977
  }
5551
5978
  if (operation.type === "insertTable") {
5552
- const boundary = findOutermostTableBoundary(doc, blockFrom) ?? {
5553
- before: blockFrom,
5554
- after: endOfParagraphWithItsTextBoxes(doc, blockFrom)
5555
- };
5556
- const insertFrom = (operation.position ?? "after") === "after" ? boundary.after : boundary.before;
5979
+ const side = (operation.position ?? "after") === "after" ? "after" : "before";
5980
+ const tableBoundary = findOutermostTableBoundary(doc, blockFrom);
5981
+ const placed = tableBoundary ? {
5982
+ from: tableBoundary[side],
5983
+ at: tableBoundary[side]
5984
+ } : beside(side);
5557
5985
  return {
5558
5986
  type: "resolved",
5559
5987
  operation: {
5560
5988
  operation,
5561
- from: insertFrom,
5562
- to: insertFrom,
5989
+ from: placed.from,
5990
+ to: placed.from,
5563
5991
  blockFrom,
5564
5992
  blockTo,
5565
5993
  blockNode,
5566
- boundaryComments: commentsAcrossBlockBoundary(doc, insertFrom)
5994
+ boundaryComments: commentsAcrossBlockBoundary(doc, placed.at),
5995
+ ...placed.joinSide !== void 0 && {
5996
+ joinSide: placed.joinSide,
5997
+ joinAt: placed.joinAt
5998
+ }
5567
5999
  }
5568
6000
  };
5569
6001
  }
@@ -5889,7 +6321,7 @@ const describeUndefinedParagraphStyle = ({ path, styleId, definedAs }, definitio
5889
6321
  return `${path} "${styleId}" ${definedAs === void 0 ? "names no style in this document" : `names a ${definedAs} style, not a paragraph style`} (${available}).`;
5890
6322
  };
5891
6323
  /** The `w:num` id a stated numbering names, when it names one. */
5892
- const statedNumberingInstance = (numbering) => numbering?.kind === "reference" && isNumberingReference(numbering.numId) ? numbering.numId : void 0;
6324
+ const statedNumberingInstance = (numbering) => numbering?.kind === "reference" && isNumberingReference$1(numbering.numId) ? numbering.numId : void 0;
5893
6325
  /**
5894
6326
  * Every numbering instance an operation names, with the field that names it.
5895
6327
  * Only reference variants name an instance; inheritance, cancellation and level-only do not.
@@ -5947,4 +6379,4 @@ const getOperationQuote = (operation) => {
5947
6379
  if (operation.type === "replaceInBlock") return operation.find;
5948
6380
  if (operation.type === "commentOnBlock") return operation.quote;
5949
6381
  };
5950
- export { applyFolioAIEditOperations, insertCleanText, previewFolioAIEditOperations, previewFolioAIEditOperationsWithResult };
6382
+ export { applyFolioAIEditOperations, applyFolioAIEditOperationsInPackage, insertCleanText, previewFolioAIEditOperations, previewFolioAIEditOperationsWithResult };