@stll/folio-core 0.68.0 → 0.69.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 (177) hide show
  1. package/dist/ai-edits/headless.js +2 -2
  2. package/dist/ai-edits/newListNumbering.d.ts +14 -1
  3. package/dist/ai-edits/newListNumbering.js +24 -1
  4. package/dist/ai-edits/pending-suggestions.js +2 -2
  5. package/dist/controller/canonicalClipboard.js +2 -2
  6. package/dist/controller/canonicalComposition.js +34 -5
  7. package/dist/controller/canonicalInput.js +4 -6
  8. package/dist/controller/canonicalLockGuard.d.ts +17 -2
  9. package/dist/controller/canonicalLockGuard.js +46 -1
  10. package/dist/controller/canonicalProjectionBlocks.d.ts +79 -0
  11. package/dist/controller/canonicalProjectionBlocks.js +75 -0
  12. package/dist/controller/canonicalPublicOperations.js +476 -100
  13. package/dist/controller/canonicalSeedContent.d.ts +12 -0
  14. package/dist/controller/canonicalSeedContent.js +131 -0
  15. package/dist/controller/canonicalSession.d.ts +53 -21
  16. package/dist/controller/canonicalSession.js +489 -210
  17. package/dist/controller/canonicalSourceNormalization.d.ts +21 -0
  18. package/dist/controller/canonicalSourceNormalization.js +148 -0
  19. package/dist/controller/canonicalStoryEditor.d.ts +1 -1
  20. package/dist/controller/canonicalStoryEditor.js +16 -12
  21. package/dist/controller/folioEditor.js +3 -0
  22. package/dist/controller/headerFooterEditorManager.d.ts +5 -0
  23. package/dist/controller/headerFooterEditorManager.js +7 -2
  24. package/dist/controller/hiddenEditorApi.d.ts +11 -2
  25. package/dist/controller/hiddenEditorApi.js +3 -0
  26. package/dist/controller/hiddenEditorManager.d.ts +7 -0
  27. package/dist/controller/hiddenEditorManager.js +66 -11
  28. package/dist/controller/layoutPipeline.js +2 -1
  29. package/dist/controller/layoutSession.d.ts +3 -0
  30. package/dist/controller/layoutSession.js +3 -1
  31. package/dist/controller/noteEditorManager.d.ts +5 -0
  32. package/dist/controller/noteEditorManager.js +7 -2
  33. package/dist/display-list/dom/renderDisplayListToDom.js +9 -7
  34. package/dist/document-operations.d.ts +1 -1
  35. package/dist/docx/canonicalSave.js +7 -2
  36. package/dist/docx/commentAnchorIndex.d.ts +19 -0
  37. package/dist/docx/commentAnchorIndex.js +55 -1
  38. package/dist/docx/containerChildren.js +1 -1
  39. package/dist/docx/contentTypeRegistry.js +1 -1
  40. package/dist/docx/hostCommentThreads.d.ts +11 -1
  41. package/dist/docx/hostCommentThreads.js +25 -2
  42. package/dist/docx/listModelNormalization.js +4 -5
  43. package/dist/docx/listNumberingInstances.d.ts +1 -1
  44. package/dist/docx/listNumberingInstances.js +2 -2
  45. package/dist/docx/numberingIds.d.ts +6 -0
  46. package/dist/docx/numberingIds.js +6 -1
  47. package/dist/docx/numberingReferenceNormalization.d.ts +4 -0
  48. package/dist/docx/numberingReferenceNormalization.js +12 -2
  49. package/dist/docx/paragraphPropertySource.d.ts +22 -0
  50. package/dist/docx/paragraphPropertySource.js +85 -16
  51. package/dist/docx/parser.js +2 -0
  52. package/dist/docx/removeHeaderFooterParts.js +1 -1
  53. package/dist/docx/reviewResolutionProvenance.js +72 -19
  54. package/dist/docx/serializer/documentSerializer.js +2 -1
  55. package/dist/docx/serializer/partNamespaces.d.ts +1 -1
  56. package/dist/docx/serializer/partNamespaces.js +1 -1
  57. package/dist/docx/server/build.d.ts +1 -1
  58. package/dist/docx/storyBlockReplay.js +15 -2
  59. package/dist/docx/structuralXmlPatch.js +25 -4
  60. package/dist/docx/xmlParser.d.ts +1 -1
  61. package/dist/docx/xmlParser.js +2 -3
  62. package/dist/i18n/messages/ar.gen.js +1 -0
  63. package/dist/i18n/messages/catalogs.gen.d.ts +17 -0
  64. package/dist/i18n/messages/catalogs.gen.js +17 -0
  65. package/dist/i18n/messages/cs.gen.js +1 -0
  66. package/dist/i18n/messages/de.gen.js +1 -0
  67. package/dist/i18n/messages/en.gen.js +1 -0
  68. package/dist/i18n/messages/es.gen.js +1 -0
  69. package/dist/i18n/messages/et.gen.js +1 -0
  70. package/dist/i18n/messages/fr.gen.js +1 -0
  71. package/dist/i18n/messages/he.gen.js +1 -0
  72. package/dist/i18n/messages/hi.gen.js +1 -0
  73. package/dist/i18n/messages/hu.gen.js +1 -0
  74. package/dist/i18n/messages/lt.gen.js +1 -0
  75. package/dist/i18n/messages/lv.gen.js +1 -0
  76. package/dist/i18n/messages/messages.gen.d.ts +1 -0
  77. package/dist/i18n/messages/pl.gen.js +1 -0
  78. package/dist/i18n/messages/pt-BR.gen.js +1 -0
  79. package/dist/i18n/messages/sk.gen.js +1 -0
  80. package/dist/i18n/messages/tr.gen.js +1 -0
  81. package/dist/i18n/messages/zh-CN.gen.js +1 -0
  82. package/dist/internal/pageBreakRunDescendantIndex.d.ts +7 -2
  83. package/dist/internal/pageBreakRunDescendantIndex.js +12 -3
  84. package/dist/internal/subtreeHolds.d.ts +12 -0
  85. package/dist/internal/subtreeHolds.js +25 -0
  86. package/dist/internal/wholeStoryRevisionResolution.js +1 -1
  87. package/dist/layout-bridge/cellSelectionHighlight.js +3 -3
  88. package/dist/layout-bridge/convert/flowBlockPostprocessing.js +20 -12
  89. package/dist/layout-bridge/convert/flowConversionShared.d.ts +15 -1
  90. package/dist/layout-bridge/convert/flowConversionShared.js +9 -1
  91. package/dist/layout-bridge/convert/paragraphAttrs.d.ts +15 -4
  92. package/dist/layout-bridge/convert/paragraphAttrs.js +11 -4
  93. package/dist/layout-bridge/convert/paragraphBlockCache.d.ts +26 -0
  94. package/dist/layout-bridge/convert/paragraphBlockCache.js +137 -0
  95. package/dist/layout-bridge/convert/paragraphConversion.d.ts +12 -2
  96. package/dist/layout-bridge/convert/paragraphConversion.js +37 -5
  97. package/dist/layout-bridge/convert/paragraphRuns.d.ts +2 -2
  98. package/dist/layout-bridge/convert/sectionBoundaries.js +16 -0
  99. package/dist/layout-bridge/convert/toFlowBlocks.js +144 -15
  100. package/dist/layout-bridge/convert/topLevelConversion.d.ts +74 -0
  101. package/dist/layout-bridge/convert/topLevelConversion.js +109 -0
  102. package/dist/layout-bridge/dom/clickToPositionDom.js +41 -40
  103. package/dist/layout-bridge/dom/findBodyPmSpans.js +4 -3
  104. package/dist/layout-bridge/dom/findHfPmSpans.js +10 -15
  105. package/dist/layout-bridge/dom/imeCaretAnchor.d.ts +8 -0
  106. package/dist/layout-bridge/dom/imeCaretAnchor.js +71 -7
  107. package/dist/layout-bridge/dom/textStreamDom.js +3 -2
  108. package/dist/layout-bridge/headerFooterLayout.js +12 -11
  109. package/dist/layout-bridge/tableInsertHover.js +2 -1
  110. package/dist/layout-engine/measure/cache.d.ts +2 -0
  111. package/dist/layout-engine/measure/cache.js +6 -1
  112. package/dist/layout-engine/measure/paragraphKeyMemo.d.ts +8 -0
  113. package/dist/layout-engine/measure/paragraphKeyMemo.js +92 -0
  114. package/dist/layout-engine/types.d.ts +6 -0
  115. package/dist/layout-painter/imageLayout.js +2 -1
  116. package/dist/layout-painter/pageShellStyles.d.ts +10 -0
  117. package/dist/layout-painter/pageShellStyles.js +32 -0
  118. package/dist/layout-painter/reconcileRenderedContent.d.ts +19 -0
  119. package/dist/layout-painter/reconcileRenderedContent.js +117 -0
  120. package/dist/layout-painter/renderFragment.js +4 -6
  121. package/dist/layout-painter/renderImage.js +2 -2
  122. package/dist/layout-painter/renderPage.js +8 -29
  123. package/dist/layout-painter/renderParagraph.js +3 -3
  124. package/dist/layout-painter/renderTable.js +9 -12
  125. package/dist/layout-painter/renderTextBox.js +2 -2
  126. package/dist/layout-painter/sdtBoundary.js +3 -2
  127. package/dist/paged-layout/blockGeometry.js +3 -2
  128. package/dist/paged-layout/editorScrollRoot.d.ts +9 -0
  129. package/dist/paged-layout/editorScrollRoot.js +10 -1
  130. package/dist/paged-layout/rangeProjection.js +5 -4
  131. package/dist/paged-layout/scrollToPmPosition.js +3 -3
  132. package/dist/paged-layout/selectionViewportRect.d.ts +6 -0
  133. package/dist/paged-layout/selectionViewportRect.js +8 -2
  134. package/dist/prosemirror/attrs/index.js +1 -0
  135. package/dist/prosemirror/commands/comments.d.ts +5 -2
  136. package/dist/prosemirror/commands/comments.js +88 -8
  137. package/dist/prosemirror/commentRecords.d.ts +137 -0
  138. package/dist/prosemirror/commentRecords.js +400 -0
  139. package/dist/prosemirror/conversion/fromProseDoc.js +9 -3
  140. package/dist/prosemirror/conversion/index.d.ts +1 -1
  141. package/dist/prosemirror/conversion/toProseDoc.d.ts +13 -4
  142. package/dist/prosemirror/conversion/toProseDoc.js +126 -38
  143. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +22 -0
  144. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +61 -32
  145. package/dist/prosemirror/extensions/marks/CommentExtension.js +3 -1
  146. package/dist/prosemirror/extensions/nodes/CommentReferenceExtension.js +3 -1
  147. package/dist/prosemirror/index.d.ts +1 -1
  148. package/dist/prosemirror/nativeSelection.d.ts +33 -0
  149. package/dist/prosemirror/nativeSelection.js +74 -0
  150. package/dist/prosemirror/numberedRefFields.d.ts +2 -0
  151. package/dist/prosemirror/numberedRefFields.js +16 -5
  152. package/dist/prosemirror/paragraphMarkJoin.d.ts +6 -8
  153. package/dist/prosemirror/paragraphMarkJoin.js +155 -16
  154. package/dist/prosemirror/plugins/contentControlWidgets.js +2 -2
  155. package/dist/prosemirror/plugins/documentNumbering.js +33 -14
  156. package/dist/prosemirror/plugins/suggestionMode.js +13 -1
  157. package/dist/prosemirror/runIdentityAcrossRevisions.d.ts +23 -1
  158. package/dist/prosemirror/runIdentityAcrossRevisions.js +57 -8
  159. package/dist/prosemirror/schema/marks.d.ts +7 -1
  160. package/dist/prosemirror/storyListNumbering.js +7 -2
  161. package/dist/prosemirror/tableResize.d.ts +10 -9
  162. package/dist/prosemirror/tableResize.js +60 -49
  163. package/dist/prosemirror/textInput.d.ts +30 -1
  164. package/dist/prosemirror/textInput.js +144 -17
  165. package/dist/prosemirror/utils/visualLineNavigation.js +20 -18
  166. package/dist/prosemirror/validation.d.ts +19 -0
  167. package/dist/prosemirror/validation.js +78 -5
  168. package/dist/render-dom/HeaderFooterSelectionOverlay.js +5 -4
  169. package/dist/render-dom/RenderedDomContext.js +7 -6
  170. package/dist/types/canonicalCapabilities.d.ts +12 -11
  171. package/dist/types/canonicalCapabilities.js +12 -13
  172. package/dist/utils/findMatchView.js +4 -3
  173. package/dist/utils/formatToStyle.d.ts +1 -1
  174. package/dist/utils/mergeDocumentContent.js +2 -2
  175. package/dist/utils/paintedPositions.d.ts +60 -0
  176. package/dist/utils/paintedPositions.js +101 -0
  177. package/package.json +2 -3
@@ -2,7 +2,9 @@ import { SUGGESTED_SUPPORTED_OPERATION_TYPES } from "../ai-edits/apply.js";
2
2
  import { splitsGraphemeCluster, splitsSurrogatePair } from "../ai-edits/character-boundaries.js";
3
3
  import { buildCleanBlockText, resolveCleanTextRange } from "../ai-edits/clean-text.js";
4
4
  import { stripInlineEmphasisMarkers } from "../ai-edits/inline-emphasis.js";
5
+ import { createBatchListMinter } from "../ai-edits/newListNumbering.js";
5
6
  import { collectNoteReferenceLabels, hashFolioAIBlockContent, hashFolioAIBlockText } from "../ai-edits/snapshot.js";
7
+ import { findOutermostTableBoundary } from "../ai-edits/table-targets.js";
6
8
  import { wordDiffSessionFromOptions } from "../ai-edits/word-diff.js";
7
9
  import { getFolioDocumentOperationIssues, getFolioDocumentOperationReceiptsForStory, parseFolioDocumentOperationBatch, withDistinctSuggestionIds } from "../document-operations.js";
8
10
  import { maxAnnotationIdInDoc } from "../prosemirror/plugins/revisionIds.js";
@@ -10,9 +12,9 @@ import { CANONICAL_GAP } from "../types/canonicalCapabilities.js";
10
12
  import { canonicalCommentBody, compileCanonicalComments } from "./canonicalComments.js";
11
13
  import { lockViolationBetween } from "./canonicalLockGuard.js";
12
14
  import { Result, TaggedError, panic } from "better-result";
13
- import { CONTENT_CONTROL_LOCK, lockedControlMessage } from "@stll/docx-core/model";
15
+ import { CONTENT_CONTROL_LOCK, lockedControlMessage, paragraphNumberingReference } from "@stll/docx-core/model";
14
16
  import { Mark } from "prosemirror-model";
15
- import { OP_STORIES, applyDocumentOps, compileEditorIntent, createEditorIntentIdAllocator, documentStories, findStoryBody, freshCommentId, paragraphLength, pendingSuggestionIdsIn } from "@stll/docx-core/ops";
17
+ import { applyDocumentOps, compileEditorIntent, createEditorIntentIdAllocator, documentStories, findStoryBody, freshCommentId, paragraphLength, pendingSuggestionIdsIn, revisionSpan, storyParagraphs } from "@stll/docx-core/ops";
16
18
  // src/controller/canonicalPublicOperations.ts
17
19
  /** Public batches compile against the read projection; only the canonical journal publishes. */
18
20
  /** A new public kind cannot bypass a canonical compiler/refusal decision. */
@@ -79,21 +81,28 @@ const statedParagraphPatch = (properties) => {
79
81
  if (properties.styleId !== void 0) patch["styleId"] = properties.styleId;
80
82
  if (properties.outlineLevel !== void 0) patch["outlineLevel"] = properties.outlineLevel;
81
83
  if (properties.alignment !== void 0) patch["alignment"] = properties.alignment;
84
+ const { numbering } = properties;
85
+ if (numbering !== void 0 && numbering.kind !== "newList") patch["numPr"] = numbering.kind === "inherit" ? null : numbering;
82
86
  const { spacing, indentation } = properties;
83
87
  if (spacing !== void 0) for (const field of SPACING_FIELDS) patch[field] = spacing === null ? null : spacing[field] ?? null;
84
88
  if (indentation !== void 0) for (const field of INDENTATION_FIELDS) patch[field] = indentation === null ? null : indentation[field] ?? null;
85
89
  return patch;
86
90
  };
87
- const resolveParagraphProperties = ({ operation, paragraph, projection, refusal }) => {
88
- if (operation.properties.numbering !== void 0) return refusal("unsupportedBlock", "Canonical paragraph numbering changes are unavailable.");
89
- const patch = statedParagraphPatch(operation.properties);
91
+ const resolveParagraphProperties = ({ operation, paragraph, projection, mintList, refusal }) => {
92
+ const requested = operation.properties.numbering;
93
+ const stated = statedNumbering(requested, mintList);
94
+ const patch = statedParagraphPatch({
95
+ ...operation.properties,
96
+ ...stated.numbering === void 0 ? {} : { numbering: stated.numbering }
97
+ });
90
98
  if (Object.keys(patch).length === 0) return refusal("emptyOperation");
91
99
  const at = projection.addressAt(paragraph.start);
92
100
  if (at.isErr()) return refusal("unsupportedBlock");
93
101
  const intents = [{
94
102
  type: "formatParagraph",
95
103
  at: at.value,
96
- patch
104
+ patch,
105
+ ...stated.newList === void 0 ? {} : { newList: stated.newList }
97
106
  }];
98
107
  return Result.ok({
99
108
  type: "plain",
@@ -104,23 +113,72 @@ const resolveParagraphProperties = ({ operation, paragraph, projection, refusal
104
113
  to: paragraph.start + paragraph.node.content.size
105
114
  });
106
115
  };
116
+ /**
117
+ * The intent that states `properties` on one paragraph by its identity,
118
+ * none when they state nothing.
119
+ */
120
+ const statedPropertiesIntents = ({ story, blockId, properties, mintList }) => {
121
+ if (properties === void 0) return [];
122
+ const stated = statedNumbering(properties.numbering, mintList);
123
+ const patch = statedParagraphPatch({
124
+ ...properties,
125
+ ...stated.numbering === void 0 ? {} : { numbering: stated.numbering }
126
+ });
127
+ if (Object.keys(patch).length === 0) return [];
128
+ return [{
129
+ type: "formatParagraph",
130
+ at: {
131
+ story,
132
+ blockId,
133
+ offset: 0
134
+ },
135
+ patch,
136
+ ...stated.newList === void 0 ? {} : { newList: stated.newList }
137
+ }];
138
+ };
107
139
  const isBlockInsertion = (operation) => operation.type === "insertAfterBlock" || operation.type === "insertBeforeBlock";
108
140
  /**
141
+ * Where an insertion beside `paragraph` goes: beside the paragraph, or, for a
142
+ * paragraph in a table cell, beside the outermost table, as the default
143
+ * engine places it. The point names the paragraph on the far side of the
144
+ * table; none stands there when the table starts or ends its container.
145
+ */
146
+ const blockInsertionPlace = (operation, paragraph, projection) => {
147
+ const side = operation.type === "insertAfterBlock" ? "after" : "before";
148
+ const table = findOutermostTableBoundary(projection.doc, paragraph.start - 1);
149
+ if (table === null) return {
150
+ at: {
151
+ type: side,
152
+ blockId: paragraph.blockId
153
+ },
154
+ position: side === "after" ? paragraph.start + paragraph.node.content.size : paragraph.start
155
+ };
156
+ const position = table[side];
157
+ const resolved = projection.doc.resolve(position);
158
+ const beside = side === "after" ? resolved.nodeAfter : resolved.nodeBefore;
159
+ if (beside?.type.name !== "paragraph") return void 0;
160
+ const neighbour = projection.paragraphStartingAt(side === "after" ? position : position - beside.nodeSize);
161
+ if (neighbour === void 0) return void 0;
162
+ return {
163
+ at: {
164
+ type: side === "after" ? "before" : "after",
165
+ blockId: neighbour.blockId
166
+ },
167
+ position
168
+ };
169
+ };
170
+ /**
109
171
  * One new paragraph beside the anchor, as the default engine writes it: the
110
172
  * anchor's stated paragraph properties unless `inheritFormatting` is false,
111
173
  * with the operation's own on top, holding the text as one plain run.
112
174
  */
113
- const resolveBlockInsertion = ({ operation, paragraph, story, refusal }) => {
114
- const unavailable = [
115
- ["numbering", "paragraph numbering"],
116
- ["moveId", "tracked moves"],
117
- ["comment", "comments on an inserted block"]
118
- ].find(([key]) => operation[key] !== void 0);
119
- if (unavailable !== void 0) return refusal("unsupportedBlock", `Canonical block insertion with ${unavailable[1]} is unavailable.`);
175
+ const resolveBlockInsertion = ({ operation, paragraph, projection, story, mintList, refusal }) => {
176
+ const requested = operation.numbering;
177
+ const stated = statedNumbering(requested, mintList);
120
178
  const { text } = operation;
121
179
  if (stripInlineEmphasisMarkers(text) !== text) return refusal("unsupportedBlock", "Canonical public emphasis replacements are unavailable.");
122
180
  const inline = operation.lineBreakMode === "inline";
123
- if (/\[\^(?:e)?\d+\]/u.test(text) || inline && text.includes("\r")) return refusal("unsupportedBlock", "Canonical block insertion requires plain text.");
181
+ if (/\[\^(?:e)?\d+\]/u.test(text)) return refusal("unsupportedBlock", "Canonical block insertion requires plain text.");
124
182
  const split = !inline && LINE_BREAK_PATTERN.test(text);
125
183
  const lines = split ? text.split(LINE_BREAK_PATTERN).filter((line) => line.trim().length > 0) : [text];
126
184
  const texts = lines.length === 0 ? [""] : lines;
@@ -130,7 +188,8 @@ const resolveBlockInsertion = ({ operation, paragraph, story, refusal }) => {
130
188
  ...operation.outlineLevel === void 0 ? {} : { outlineLevel: operation.outlineLevel },
131
189
  ...operation.alignment === void 0 ? {} : { alignment: operation.alignment },
132
190
  ...operation.spacing === void 0 ? {} : { spacing: operation.spacing },
133
- ...operation.indentation === void 0 ? {} : { indentation: operation.indentation }
191
+ ...operation.indentation === void 0 ? {} : { indentation: operation.indentation },
192
+ ...stated.numbering === void 0 ? {} : { numbering: stated.numbering }
134
193
  }))) if (value === null) Reflect.deleteProperty(formatting, key);
135
194
  else formatting[key] = value;
136
195
  const everyParagraph = operation.formattingScope === "allParagraphs";
@@ -157,59 +216,129 @@ const resolveBlockInsertion = ({ operation, paragraph, story, refusal }) => {
157
216
  ...Object.keys(own).length === 0 ? {} : { formatting: own }
158
217
  };
159
218
  });
219
+ const place = blockInsertionPlace(operation, paragraph, projection);
220
+ if (place === void 0) return refusal("unsupportedBlock", "Canonical insertion beside a table needs a paragraph on that side of it.");
160
221
  const intents = [{
161
222
  type: "insertParagraphs",
162
223
  story,
163
- at: {
164
- type: operation.type === "insertAfterBlock" ? "after" : "before",
165
- blockId: paragraph.blockId
166
- },
167
- paragraphs
224
+ at: place.at,
225
+ paragraphs,
226
+ ...stated.newList === void 0 ? {} : { newList: stated.newList }
168
227
  }];
169
- const position = operation.type === "insertAfterBlock" ? paragraph.start + paragraph.node.content.size : paragraph.start;
170
- const normalizations = split ? [{
171
- id: operation.id,
172
- code: "splitMultilineText",
173
- paragraphCount: texts.length
174
- }] : [];
175
- return Result.ok({
176
- type: "plain",
177
- operation,
228
+ const { position } = place;
229
+ if (operation.comment !== void 0 && texts.every((line) => line.length === 0)) return refusal("unsupportedBlock");
230
+ const resolved = {
178
231
  intents,
179
- normalizations,
232
+ normalizations: split ? [{
233
+ id: operation.id,
234
+ code: "splitMultilineText",
235
+ paragraphCount: texts.length
236
+ }] : [],
180
237
  from: position,
181
238
  to: position
239
+ };
240
+ if (operation.comment === void 0) return Result.ok({
241
+ type: "plain",
242
+ operation,
243
+ ...resolved
244
+ });
245
+ const anchor = {
246
+ story,
247
+ blockId: place.at.blockId,
248
+ offset: 0
249
+ };
250
+ return Result.ok({
251
+ type: "commented",
252
+ operation,
253
+ comment: {
254
+ text: operation.comment.text,
255
+ from: anchor,
256
+ to: anchor,
257
+ inserted: true
258
+ },
259
+ ...resolved
182
260
  });
183
261
  };
184
262
  const LINE_BREAK_PATTERN = /\r\n|\r|\n/u;
185
- /** A line's text with each tab and line break as the element it is. */
186
- const inlineText = (line) => line.split(/([\t\n])/u).flatMap((part) => {
263
+ /**
264
+ * The operations a canonical suggestion can carry: the default engine's;
265
+ * splits and merges, which the canonical session records as tracked paragraph
266
+ * marks stamped with the suggestion; and comments, which it holds as proposed
267
+ * by the suggestion until it is accepted or rejected.
268
+ */
269
+ const CANONICAL_SUGGESTED_OPERATION_TYPES = /* @__PURE__ */ new Set([
270
+ ...SUGGESTED_SUPPORTED_OPERATION_TYPES,
271
+ "splitBlock",
272
+ "mergeBlockWithNext",
273
+ "commentOnRange",
274
+ "commentOnBlock"
275
+ ]);
276
+ /**
277
+ * Whether one of two resolved operations inserts beside the paragraph the
278
+ * other deletes by identity: they touch only at that paragraph's edge, and
279
+ * both apply, as in the default engine. A deletion of a paragraph that ends
280
+ * its container still refuses the insertion beside it.
281
+ */
282
+ const besideItsDeletion = (left, right) => {
283
+ const pair = ({ operation: insertion }, { operation: deletion, removesParagraphBeforeBlock }) => (insertion.type === "insertAfterBlock" || insertion.type === "insertBeforeBlock") && deletion.type === "deleteBlock" && removesParagraphBeforeBlock === true && insertion.blockId === deletion.blockId;
284
+ return pair(left, right) || pair(right, left);
285
+ };
286
+ /** A block operation without the move it names: a plain insertion or deletion. */
287
+ const withoutMove = (operation) => {
288
+ if (operation.type !== "deleteBlock" && operation.type !== "insertAfterBlock" && operation.type !== "insertBeforeBlock") return operation;
289
+ const { moveId: _moveId, ...plain } = operation;
290
+ return plain;
291
+ };
292
+ /** The move a block operation names, if it is a half of one. */
293
+ const blockMoveId = (operation) => operation.type === "deleteBlock" || operation.type === "insertAfterBlock" || operation.type === "insertBeforeBlock" ? operation.moveId : void 0;
294
+ /**
295
+ * A line's text with each tab and line break as the element it is; CRLF, CR
296
+ * and LF are each one line break.
297
+ */
298
+ const inlineText = (line) => line.split(/(\t|\r\n|\r|\n)/u).flatMap((part) => {
187
299
  if (part === " ") return [{ type: "tab" }];
188
- if (part === "\n") return [{ type: "break" }];
300
+ if (LINE_BREAK_PATTERN.test(part)) return [{ type: "break" }];
189
301
  return part === "" ? [] : [{
190
302
  type: "text",
191
303
  text: part
192
304
  }];
193
305
  });
194
- const compilePublicIntents = ({ document, intents, mode, author, date, suggestionId, nextRevisionId, allocate }) => {
306
+ const compilePublicIntents = ({ document, intents, mode, author, date, suggestionId, nextRevisionId, allocate, reservedBlockIds }) => {
195
307
  const ops = [];
196
308
  const revisions = [];
309
+ const allocated = /* @__PURE__ */ new Map();
197
310
  for (const sourceIntent of intents) {
198
311
  const ids = allocate(document, sourceIntent);
199
- const intent = sourceIntent.type === "splitParagraph" ? {
200
- type: "splitParagraph",
201
- at: sourceIntent.at,
202
- ...sourceIntent.to === void 0 ? {} : { to: sourceIntent.to },
203
- newBlockId: ids.newBlockId
204
- } : sourceIntent;
312
+ let intent = sourceIntent;
313
+ if (sourceIntent.type === "splitParagraph") {
314
+ allocated.set(sourceIntent.newBlockId, ids.newBlockId);
315
+ intent = {
316
+ type: "splitParagraph",
317
+ at: sourceIntent.at,
318
+ ...sourceIntent.to === void 0 ? {} : { to: sourceIntent.to },
319
+ ...sourceIntent.newHalf === void 0 ? {} : { newHalf: sourceIntent.newHalf },
320
+ newBlockId: ids.newBlockId
321
+ };
322
+ } else if (sourceIntent.type === "formatParagraph") {
323
+ const blockId = allocated.get(sourceIntent.at.blockId);
324
+ if (blockId !== void 0) intent = {
325
+ ...sourceIntent,
326
+ at: {
327
+ ...sourceIntent.at,
328
+ blockId
329
+ }
330
+ };
331
+ }
205
332
  const firstRevisionId = nextRevisionId;
206
333
  const compiled = compileEditorIntent(document, {
207
334
  intent,
208
335
  mode: mode === "direct" ? {
209
336
  type: "editing",
210
- newIds: ids.newIds
337
+ newIds: ids.newIds,
338
+ reservedBlockIds
211
339
  } : {
212
340
  type: "suggesting",
341
+ reservedBlockIds,
213
342
  revision: {
214
343
  id: firstRevisionId,
215
344
  author,
@@ -239,6 +368,22 @@ const compilePublicIntents = ({ document, intents, mode, author, date, suggestio
239
368
  };
240
369
  const CanonicalPublicOperationResolutionErrorBase = TaggedError("CanonicalPublicOperationResolutionError");
241
370
  var CanonicalPublicOperationResolutionError = class extends CanonicalPublicOperationResolutionErrorBase {};
371
+ /**
372
+ * The stated numbering a request names, minting its new list once for the
373
+ * operation, as the default engine allocates one instance per operation.
374
+ */
375
+ const statedNumbering = (numbering, mint) => {
376
+ if (numbering === void 0) return {};
377
+ if (numbering.kind !== "newList") return { numbering };
378
+ const minted = mint(numbering.format);
379
+ return {
380
+ numbering: paragraphNumberingReference({
381
+ numId: minted.numId,
382
+ ilvl: numbering.level ?? 0
383
+ }),
384
+ newList: minted.newList
385
+ };
386
+ };
242
387
  const canonicalPublicStory = (story) => {
243
388
  if (story === "main") return story;
244
389
  switch (story.type) {
@@ -281,6 +426,7 @@ var CanonicalPublicOperations = class {
281
426
  const normalizations = [];
282
427
  const refusals = /* @__PURE__ */ new Map();
283
428
  const resolved = [];
429
+ const mintList = createBatchListMinter(() => session.document);
284
430
  const { diff } = wordDiffSessionFromOptions(options.wordDiff);
285
431
  let nextRevisionId = options.revisionStamp?.idSeed ?? 1;
286
432
  if (!session.isComposing && options.revisionStamp === void 0) for (const currentStory of documentStories(session.document)) {
@@ -321,17 +467,17 @@ var CanonicalPublicOperations = class {
321
467
  ...normalizations.length === 0 ? {} : { normalizations }
322
468
  };
323
469
  };
470
+ const besideDeletions = {
471
+ deleted: new Set(batch.operations.flatMap((operation) => operation.type === "deleteBlock" ? [operation.blockId] : [])),
472
+ insertedBeside: new Set(batch.operations.flatMap((operation) => operation.type === "insertAfterBlock" || operation.type === "insertBeforeBlock" ? [operation.blockId] : []))
473
+ };
474
+ const overlapsResolved = (candidate) => resolved.some((earlier) => earlier !== candidate && !besideItsDeletion(earlier, candidate) && (candidate.from < earlier.to && candidate.to > earlier.from || earlier.from === earlier.to && candidate.from <= earlier.from && candidate.to >= earlier.from || candidate.from === candidate.to && candidate.from >= earlier.from && candidate.from <= earlier.to));
324
475
  for (const operation of batch.operations) {
325
- if (story !== OP_STORIES.MAIN) {
326
- refusals.set(operation.id, { gap: CANONICAL_GAP.publicSecondaryStories });
327
- skip(operation.id, "unsupportedBlock", "Canonical public secondary-story routing is unavailable.");
328
- continue;
329
- }
330
476
  if (!state || projected.isErr() || session.isComposing) {
331
477
  skip(operation.id, "documentNotEditable");
332
478
  continue;
333
479
  }
334
- if (batch.mode === "suggested" && !SUGGESTED_SUPPORTED_OPERATION_TYPES.has(operation.type)) {
480
+ if (batch.mode === "suggested" && !CANONICAL_SUGGESTED_OPERATION_TYPES.has(operation.type)) {
335
481
  skip(operation.id, "unsupportedMode");
336
482
  continue;
337
483
  }
@@ -352,29 +498,94 @@ var CanonicalPublicOperations = class {
352
498
  state,
353
499
  story,
354
500
  diff,
355
- tracked: batch.mode !== "direct"
501
+ tracked: batch.mode !== "direct",
502
+ mintList,
503
+ besideDeletions
356
504
  });
357
505
  if (compiled.isErr()) {
358
506
  if (compiled.error.reason === "unsupportedBlock") refusals.set(operation.id, { gap: CANONICAL_GAP.publicUnsupportedInline });
359
507
  skip(operation.id, compiled.error.reason, compiled.error.message);
360
508
  continue;
361
509
  }
362
- if (resolved.some(({ from, to }) => compiled.value.from < to && compiled.value.to > from || from === to && compiled.value.from <= from && compiled.value.to >= from || compiled.value.from === compiled.value.to && compiled.value.from >= from && compiled.value.from <= to)) {
510
+ if (overlapsResolved(compiled.value)) {
363
511
  skip(operation.id, "overlappingOperation");
364
512
  continue;
365
513
  }
366
514
  resolved.push(compiled.value);
367
515
  }
516
+ for (const item of [...resolved]) {
517
+ if (item.besideDeletion !== true || !state) continue;
518
+ const { operation } = item;
519
+ if (operation.type !== "deleteBlock" && operation.type !== "insertAfterBlock" && operation.type !== "insertBeforeBlock") continue;
520
+ if (resolved.some(({ operation: other }) => operation.type === "deleteBlock" ? (other.type === "insertAfterBlock" || other.type === "insertBeforeBlock") && other.blockId === operation.blockId : other.type === "deleteBlock" && other.blockId === operation.blockId)) continue;
521
+ resolved.splice(resolved.indexOf(item), 1);
522
+ const alone = this.resolve({
523
+ operation,
524
+ options,
525
+ state,
526
+ story,
527
+ diff,
528
+ tracked: batch.mode !== "direct",
529
+ mintList,
530
+ besideDeletions: {
531
+ deleted: /* @__PURE__ */ new Set(),
532
+ insertedBeside: /* @__PURE__ */ new Set()
533
+ }
534
+ });
535
+ if (alone.isErr()) {
536
+ skip(operation.id, alone.error.reason, alone.error.message);
537
+ continue;
538
+ }
539
+ if (overlapsResolved(alone.value)) {
540
+ skip(operation.id, "overlappingOperation");
541
+ continue;
542
+ }
543
+ resolved.push(alone.value);
544
+ }
545
+ const moveSides = /* @__PURE__ */ new Map();
546
+ for (const { operation } of resolved) {
547
+ const moveId = blockMoveId(operation);
548
+ if (moveId === void 0) continue;
549
+ const sides = moveSides.get(moveId) ?? {
550
+ from: 0,
551
+ to: 0
552
+ };
553
+ if (operation.type === "deleteBlock") sides.from += 1;
554
+ else sides.to += 1;
555
+ moveSides.set(moveId, sides);
556
+ }
557
+ const unpairable = new Set(batch.mode === "suggested" ? resolved.flatMap(({ operation }) => operation.type === "insertBeforeBlock" && operation.moveId !== void 0 && resolved.some((candidate) => candidate.operation.type === "deleteBlock" && candidate.operation.moveId === operation.moveId && candidate.operation.blockId === operation.blockId) ? [operation.moveId] : []) : []);
558
+ const paired = (moveId) => !unpairable.has(moveId) && moveSides.get(moveId)?.from === 1 && moveSides.get(moveId)?.to === 1;
559
+ const pairedMoves = /* @__PURE__ */ new Set();
560
+ for (const [index, item] of resolved.entries()) {
561
+ const moveId = blockMoveId(item.operation);
562
+ if (moveId === void 0) continue;
563
+ if (!paired(moveId)) {
564
+ normalizations.push({
565
+ id: item.operation.id,
566
+ code: "unpairedMove",
567
+ moveId
568
+ });
569
+ continue;
570
+ }
571
+ pairedMoves.add(moveId);
572
+ const intents = [];
573
+ for (const intent of item.intents) intents.push(intent.type === "insertParagraphs" || intent.type === "deleteParagraphs" ? Object.assign({}, intent, { move: true }) : intent);
574
+ resolved[index] = {
575
+ ...item,
576
+ intents
577
+ };
578
+ }
368
579
  if (batch.atomic && skipped.length > 0) {
369
580
  for (const { operation } of resolved) skip(operation.id, "atomicBatchRejected");
370
581
  return result([], null);
371
582
  }
372
583
  if (!state || projected.isErr() || session.isComposing) return result([], null);
373
- resolved.sort((left, right) => right.from - left.from);
584
+ resolved.sort((left, right) => right.from - left.from || left.to - left.from - (right.to - right.from));
374
585
  let document = session.document;
375
586
  const ops = [];
376
587
  const appliedById = /* @__PURE__ */ new Map();
377
- const allocate = createEditorIntentIdAllocator();
588
+ const allocate = createEditorIntentIdAllocator({ reservedBlockIds: session.reservedBlockIds });
378
589
  const date = options.revisionStamp?.date ?? (/* @__PURE__ */ new Date()).toISOString();
379
590
  for (const resolvedOperation of resolved) {
380
591
  const { operation, intents, normalizations: adjustments } = resolvedOperation;
@@ -383,6 +594,7 @@ var CanonicalPublicOperations = class {
383
594
  document,
384
595
  intents,
385
596
  allocate,
597
+ reservedBlockIds: session.reservedBlockIds,
386
598
  nextRevisionId,
387
599
  mode: batch.mode === "direct" ? "direct" : "tracked-changes",
388
600
  suggestionId,
@@ -402,16 +614,77 @@ var CanonicalPublicOperations = class {
402
614
  case "commented": {
403
615
  const { comment } = resolvedOperation;
404
616
  const id = freshCommentId(nextDocument);
405
- const before = findStoryBody(document, story)?.content.find((block) => block.type === "paragraph" && block.paraId === comment.from.blockId);
406
- const after = findStoryBody(nextDocument, story)?.content.find((block) => block.type === "paragraph" && block.paraId === comment.from.blockId);
407
- if (id.isErr() || before?.type !== "paragraph" || after?.type !== "paragraph") {
617
+ const proposedBy = suggestionId === void 0 ? {} : { suggestionId };
618
+ if (comment.inserted === true) {
619
+ const paragraphsIn = (current) => {
620
+ const body = findStoryBody(current, story);
621
+ return body === void 0 ? [] : storyParagraphs(body).map(({ paragraph }) => paragraph);
622
+ };
623
+ const known = new Set(paragraphsIn(document).flatMap(({ paraId }) => paraId === void 0 ? [] : [paraId]));
624
+ const added = paragraphsIn(nextDocument).filter(({ paraId }) => paraId !== void 0 && !known.has(paraId));
625
+ const firstAdded = added.at(0);
626
+ const lastAdded = added.at(-1);
627
+ const commented = id.isErr() || firstAdded?.paraId === void 0 || lastAdded?.paraId === void 0 ? void 0 : compileCanonicalComments({
628
+ document: nextDocument,
629
+ command: {
630
+ type: "create",
631
+ comment: {
632
+ id: id.value,
633
+ author: options.author ?? "AI",
634
+ date,
635
+ done: false,
636
+ content: canonicalCommentBody(nextDocument, comment.text),
637
+ ...proposedBy
638
+ },
639
+ anchor: {
640
+ kind: "range",
641
+ from: {
642
+ story,
643
+ blockId: firstAdded.paraId,
644
+ offset: 0
645
+ },
646
+ to: {
647
+ story,
648
+ blockId: lastAdded.paraId,
649
+ offset: paragraphLength(lastAdded)
650
+ }
651
+ }
652
+ }
653
+ });
654
+ if (commented === void 0 || commented.isErr() || id.isErr()) {
655
+ refusals.set(operation.id, { gap: CANONICAL_GAP.publicComments });
656
+ skip(operation.id, "unsupportedBlock", commented?.isErr() === true ? commented.error.message : "The inserted paragraphs cannot carry the comment.");
657
+ continue;
658
+ }
659
+ nextDocument = commented.value.document;
660
+ operationOps.push(...commented.value.ops);
661
+ commentId = id.value;
662
+ break;
663
+ }
664
+ const anchorIn = (current) => {
665
+ const body = findStoryBody(current, story);
666
+ return body === void 0 ? void 0 : storyParagraphs(body).find(({ paragraph }) => paragraph.paraId === comment.from.blockId)?.paragraph;
667
+ };
668
+ const before = anchorIn(document);
669
+ const after = anchorIn(nextDocument);
670
+ if (id.isErr() || before === void 0 || after === void 0) {
408
671
  refusals.set(operation.id, { gap: CANONICAL_GAP.publicComments });
409
672
  skip(operation.id, "unsupportedBlock", id.isErr() ? id.error.message : "The comment anchor no longer exists.");
410
673
  continue;
411
674
  }
412
- const to = {
675
+ const changed = batch.mode === "direct" ? void 0 : revisionSpan(after.content, new Set(compiled.value.revisions));
676
+ const from = changed === void 0 ? comment.from : {
677
+ story: comment.from.story,
678
+ blockId: comment.from.blockId,
679
+ offset: changed.from
680
+ };
681
+ const to = changed === void 0 ? {
413
682
  ...comment.to,
414
683
  offset: comment.to.offset + paragraphLength(after) - paragraphLength(before)
684
+ } : {
685
+ story: comment.from.story,
686
+ blockId: comment.from.blockId,
687
+ offset: changed.to
415
688
  };
416
689
  const commented = compileCanonicalComments({
417
690
  document: nextDocument,
@@ -422,14 +695,15 @@ var CanonicalPublicOperations = class {
422
695
  author: options.author ?? "AI",
423
696
  date,
424
697
  done: false,
425
- content: canonicalCommentBody(nextDocument, comment.text)
698
+ content: canonicalCommentBody(nextDocument, comment.text),
699
+ ...proposedBy
426
700
  },
427
- anchor: to.offset === comment.from.offset ? {
701
+ anchor: to.offset === from.offset ? {
428
702
  kind: "point",
429
- at: comment.from
703
+ at: from
430
704
  } : {
431
705
  kind: "range",
432
- from: comment.from,
706
+ from,
433
707
  to
434
708
  }
435
709
  }
@@ -471,6 +745,37 @@ var CanonicalPublicOperations = class {
471
745
  ...suggestionId === void 0 ? {} : { suggestionId }
472
746
  });
473
747
  }
748
+ const applyingHalves = /* @__PURE__ */ new Map();
749
+ for (const { operation } of resolved) {
750
+ const moveId = blockMoveId(operation);
751
+ if (moveId !== void 0 && appliedById.has(operation.id)) applyingHalves.set(moveId, (applyingHalves.get(moveId) ?? 0) + 1);
752
+ }
753
+ const orphaned = new Set([...pairedMoves].filter((moveId) => applyingHalves.get(moveId) === 1));
754
+ if (orphaned.size > 0) {
755
+ const orphanedMove = (operation) => {
756
+ const moveId = blockMoveId(operation);
757
+ return moveId !== void 0 && orphaned.has(moveId);
758
+ };
759
+ const plain = this.apply({
760
+ ...options,
761
+ batch: {
762
+ ...batch,
763
+ operations: batch.operations.map((operation) => orphanedMove(operation) ? withoutMove(operation) : operation)
764
+ }
765
+ });
766
+ const appliedIds = new Set(plain.applied.map(({ id }) => id));
767
+ return {
768
+ ...plain,
769
+ normalizations: [...plain.normalizations ?? [], ...batch.operations.flatMap((operation) => {
770
+ const moveId = blockMoveId(operation);
771
+ return moveId !== void 0 && orphaned.has(moveId) && appliedIds.has(operation.id) ? [{
772
+ id: operation.id,
773
+ code: "unpairedMove",
774
+ moveId
775
+ }] : [];
776
+ })]
777
+ };
778
+ }
474
779
  if (batch.atomic && skipped.length > 0) {
475
780
  for (const { id } of appliedById.values()) skip(id, "atomicBatchRejected");
476
781
  return result([], null);
@@ -551,9 +856,8 @@ var CanonicalPublicOperations = class {
551
856
  * paragraph before it, whose mark then ends the list. Tracked, the text and
552
857
  * the mark are marked deleted.
553
858
  */
554
- resolveBlockDeletion({ operation, paragraph, projection, projectionStory, doc, tracked, refusal }) {
555
- if (operation.comment !== void 0) return refusal("unsupportedBlock", "Canonical comments on a deleted block are unavailable.");
556
- if (operation.moveId !== void 0) return refusal("unsupportedBlock", "Canonical tracked moves are unavailable.");
859
+ resolveBlockDeletion({ operation, paragraph, projection, projectionStory, doc, tracked, gainsFollower, refusal }) {
860
+ if (operation.comment !== void 0 && !tracked) return refusal("unsupportedBlock");
557
861
  const end = paragraph.start + paragraph.node.content.size;
558
862
  const after = doc.resolve(end + 1).nodeAfter;
559
863
  const before = doc.resolve(paragraph.start - 1).nodeBefore;
@@ -563,13 +867,36 @@ var CanonicalPublicOperations = class {
563
867
  };
564
868
  const next = neighbour(after);
565
869
  const previous = neighbour(before);
566
- if (tracked && next === void 0 && after !== null) return refusal("unsupportedBlock", "Canonical tracked deletion of a paragraph before a table is unavailable.");
567
- let range;
568
- if (next !== void 0) range = {
870
+ const commentFrom = projection.addressAt(paragraph.start);
871
+ const commentTo = projection.addressAt(end);
872
+ if (commentFrom.isErr() || commentTo.isErr()) return refusal("unsupportedBlock");
873
+ const tracking = (resolved) => Result.ok(operation.comment === void 0 ? {
874
+ type: "plain",
875
+ operation,
876
+ ...resolved
877
+ } : {
878
+ type: "commented",
879
+ operation,
880
+ comment: {
881
+ text: operation.comment.text,
882
+ from: commentFrom.value,
883
+ to: commentTo.value
884
+ },
885
+ ...resolved
886
+ });
887
+ if (next !== void 0 || gainsFollower || tracked && (after !== null || operation.moveId !== void 0)) return tracking({
888
+ intents: [{
889
+ type: "deleteParagraphs",
890
+ story: projectionStory,
891
+ blockIds: [paragraph.blockId]
892
+ }],
893
+ normalizations: [],
569
894
  from: paragraph.start,
570
- to: next.start
571
- };
572
- else if (!tracked) {
895
+ to: end,
896
+ ...after === null && !gainsFollower ? {} : { removesParagraphBeforeBlock: true }
897
+ });
898
+ let range;
899
+ if (!tracked) {
573
900
  const own = (from, to) => {
574
901
  const start = projection.addressAt(from);
575
902
  const stop = projection.addressAt(to);
@@ -607,22 +934,19 @@ var CanonicalPublicOperations = class {
607
934
  const from = projection.addressAt(range.from);
608
935
  const to = projection.addressAt(range.to);
609
936
  if (from.isErr() || to.isErr()) return refusal("unsupportedBlock");
610
- const intents = [{
611
- type: "replaceText",
612
- from: from.value,
613
- to: to.value,
614
- text: ""
615
- }];
616
- return Result.ok({
617
- type: "plain",
618
- operation,
619
- intents,
937
+ return tracking({
938
+ intents: [{
939
+ type: "replaceText",
940
+ from: from.value,
941
+ to: to.value,
942
+ text: ""
943
+ }],
620
944
  normalizations: [],
621
945
  from: Math.min(range.from, paragraph.start),
622
946
  to: Math.max(range.to, end)
623
947
  });
624
948
  }
625
- resolve({ operation, options, state, story, diff, tracked }) {
949
+ resolve({ operation, options, state, story, diff, tracked, mintList, besideDeletions }) {
626
950
  const refusal = (reason, message) => Result.err(new CanonicalPublicOperationResolutionError({
627
951
  reason,
628
952
  message: message ?? `The operation was refused: ${reason}.`
@@ -656,27 +980,49 @@ var CanonicalPublicOperations = class {
656
980
  const hash = hashFolioAIBlockContent(clean.text);
657
981
  if (operation.precondition && hash !== operation.precondition.blockTextHash) return refusal("preconditionFailed");
658
982
  if (hash !== anchor.textHash) return refusal("changedBlock");
659
- if (isBlockInsertion(operation)) return resolveBlockInsertion({
660
- operation,
661
- paragraph,
662
- story,
663
- refusal
664
- });
983
+ const followed = state.doc.resolve(paragraph.start + paragraph.node.content.size + 1).nodeAfter?.type.name === "paragraph";
984
+ if (isBlockInsertion(operation)) {
985
+ const besideDeletion = !tracked && operation.type === "insertBeforeBlock" && !followed && besideDeletions.deleted.has(blockId);
986
+ const inserted = resolveBlockInsertion({
987
+ operation: besideDeletion ? {
988
+ ...operation,
989
+ type: "insertAfterBlock"
990
+ } : operation,
991
+ paragraph,
992
+ projection: projection.value,
993
+ story,
994
+ mintList,
995
+ refusal
996
+ });
997
+ return besideDeletion && inserted.isOk() ? Result.ok({
998
+ ...inserted.value,
999
+ besideDeletion: true
1000
+ }) : inserted;
1001
+ }
665
1002
  if (operation.type === "setBlockParagraphProperties") return resolveParagraphProperties({
666
1003
  operation,
667
1004
  paragraph,
668
1005
  projection: projection.value,
1006
+ mintList,
669
1007
  refusal
670
1008
  });
671
- if (operation.type === "deleteBlock") return this.resolveBlockDeletion({
672
- operation,
673
- paragraph,
674
- projection: projection.value,
675
- projectionStory: story,
676
- doc: state.doc,
677
- tracked,
678
- refusal
679
- });
1009
+ if (operation.type === "deleteBlock") {
1010
+ const gainsFollower = !followed && besideDeletions.insertedBeside.has(blockId);
1011
+ const deleted = this.resolveBlockDeletion({
1012
+ operation,
1013
+ paragraph,
1014
+ projection: projection.value,
1015
+ projectionStory: story,
1016
+ doc: state.doc,
1017
+ tracked,
1018
+ gainsFollower,
1019
+ refusal
1020
+ });
1021
+ return gainsFollower && deleted.isOk() ? Result.ok({
1022
+ ...deleted.value,
1023
+ besideDeletion: true
1024
+ }) : deleted;
1025
+ }
680
1026
  let start = 0;
681
1027
  let end = clean.text.length;
682
1028
  let text = "";
@@ -710,13 +1056,12 @@ var CanonicalPublicOperations = class {
710
1056
  text = operation.text;
711
1057
  break;
712
1058
  case "splitBlock":
713
- if (operation.firstParagraphProperties || operation.secondParagraphProperties) return refusal("unsupportedBlock", "Canonical split paragraph properties are unavailable.");
714
1059
  start = operation.offset;
715
1060
  end = start + (operation.separator?.length ?? 0);
716
1061
  if (start <= 0 || start >= clean.text.length || clean.text.slice(start, end) !== (operation.separator ?? "")) return refusal("staleRange");
717
1062
  break;
718
1063
  case "mergeBlockWithNext":
719
- if (operation.mergedParagraphProperties || operation.separator) return refusal("unsupportedBlock", "Canonical public join properties and separators are unavailable.");
1064
+ if (/[\t\r\n]/u.test(operation.separator ?? "")) return refusal("unsupportedBlock", "Canonical public join separators require plain text.");
720
1065
  start = clean.text.length;
721
1066
  end = start;
722
1067
  break;
@@ -755,7 +1100,8 @@ var CanonicalPublicOperations = class {
755
1100
  type: "splitParagraph",
756
1101
  at: from.value,
757
1102
  to: to.value,
758
- newBlockId: createEditorIntentIdAllocator()(this.options.session.document, {
1103
+ newHalf: "second",
1104
+ newBlockId: createEditorIntentIdAllocator({ reservedBlockIds: this.options.session.reservedBlockIds })(this.options.session.document, {
759
1105
  type: "splitParagraph",
760
1106
  at: from.value,
761
1107
  to: to.value
@@ -769,7 +1115,8 @@ var CanonicalPublicOperations = class {
769
1115
  type: "joinParagraphs",
770
1116
  story,
771
1117
  blockId,
772
- nextBlockId: next.blockId
1118
+ nextBlockId: next.blockId,
1119
+ survivor: "first"
773
1120
  };
774
1121
  break;
775
1122
  }
@@ -870,9 +1217,11 @@ var CanonicalPublicOperations = class {
870
1217
  code: "uniformReplacementFormatting"
871
1218
  });
872
1219
  }
873
- const edges = gap.from < gap.to ? projection.value.rangeEdgesAt(gap.from, gap.to) : void 0;
1220
+ const lastCharacter = change.end > change.start ? clean.offsets[change.end - 1] : void 0;
1221
+ const changeEnd = lastCharacter === void 0 ? gap.to : Math.max(gap.from, Math.min(gap.to, lastCharacter + 1));
1222
+ const edges = gap.from < changeEnd ? projection.value.rangeEdgesAt(gap.from, changeEnd) : void 0;
874
1223
  const changeFrom = projection.value.addressAt(gap.from, edges?.start);
875
- const changeTo = projection.value.addressAt(gap.to, edges?.end);
1224
+ const changeTo = projection.value.addressAt(changeEnd, edges?.end);
876
1225
  if (changeFrom.isErr() || changeTo.isErr()) return refusal("unsupportedBlock");
877
1226
  intents.push({
878
1227
  type: "replaceText",
@@ -882,6 +1231,33 @@ var CanonicalPublicOperations = class {
882
1231
  ...intent.runPropsPatch === void 0 ? {} : { runPropsPatch: intent.runPropsPatch }
883
1232
  });
884
1233
  }
1234
+ } else if (operation.type === "mergeBlockWithNext" && intent.type === "joinParagraphs") {
1235
+ const separator = operation.separator ?? "";
1236
+ if (separator !== "") {
1237
+ const at = projection.value.addressAt(paragraph.start + paragraph.node.content.size);
1238
+ if (at.isErr()) return refusal("unsupportedBlock");
1239
+ intents.push({
1240
+ type: "replaceText",
1241
+ from: at.value,
1242
+ to: at.value,
1243
+ text: separator
1244
+ });
1245
+ }
1246
+ intents.push(intent);
1247
+ intents.push(...statedPropertiesIntents({
1248
+ story,
1249
+ blockId: tracked ? intent.nextBlockId : intent.blockId,
1250
+ properties: operation.mergedParagraphProperties,
1251
+ mintList
1252
+ }));
1253
+ } else if (operation.type === "splitBlock" && intent.type === "splitParagraph") {
1254
+ intents.push(intent);
1255
+ for (const [half, properties] of [[paragraph.blockId, operation.firstParagraphProperties], [intent.newBlockId, operation.secondParagraphProperties]]) intents.push(...statedPropertiesIntents({
1256
+ story,
1257
+ blockId: half,
1258
+ properties,
1259
+ mintList
1260
+ }));
885
1261
  } else intents.push(intent);
886
1262
  const structural = operation.type === "splitBlock" || operation.type === "mergeBlockWithNext";
887
1263
  const nextParagraph = operation.type === "mergeBlockWithNext" && intent.type === "joinParagraphs" ? projection.value.paragraph(intent.nextBlockId) : void 0;