@stll/folio-core 0.73.0 → 0.74.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 (135) hide show
  1. package/dist/ai-edits/headless.js +2 -5
  2. package/dist/ai-edits/pendingJoin.js +6 -1
  3. package/dist/ai-edits/result-validation.js +1 -1
  4. package/dist/ai-edits/snapshot.js +1 -1
  5. package/dist/ai-edits/table-cell-mutations.js +1 -1
  6. package/dist/ai-edits/tracked-batch-fidelity.js +1 -1
  7. package/dist/canonical/canonicalInlineGaps.d.ts +56 -0
  8. package/dist/canonical/canonicalInlineGaps.js +118 -0
  9. package/dist/canonical/canonicalInlineProjection.d.ts +4 -13
  10. package/dist/canonical/canonicalInlineProjection.js +6 -28
  11. package/dist/canonical/canonicalProjectionBlocks.d.ts +4 -4
  12. package/dist/canonical/canonicalPublicOperations.js +70 -27
  13. package/dist/canonical/canonicalSelection.js +1 -1
  14. package/dist/canonical/canonicalSession.js +14 -21
  15. package/dist/controller/autocompleteSuggestion.js +1 -1
  16. package/dist/controller/canonicalClipboard.js +2 -2
  17. package/dist/controller/canonicalComposition.js +1 -1
  18. package/dist/controller/canonicalInput.js +1 -1
  19. package/dist/controller/canonicalPresence.js +1 -1
  20. package/dist/controller/canonicalRoomAuthority.js +1 -1
  21. package/dist/controller/canonicalRoomWire.js +1 -1
  22. package/dist/controller/canonicalStructure.js +1 -1
  23. package/dist/controller/canonicalTabRoom.js +1 -1
  24. package/dist/controller/canonicalYjsRoom.js +1 -1
  25. package/dist/controller/hiddenEditorApi.js +2 -17
  26. package/dist/controller/hiddenEditorManager.js +4 -8
  27. package/dist/document-operations.js +1 -1
  28. package/dist/docx/canonicalSave.d.ts +1 -1
  29. package/dist/docx/canonicalSave.js +1 -1
  30. package/dist/docx/canonicalSessionInput.js +1 -1
  31. package/dist/docx/containerChildren.js +1 -1
  32. package/dist/docx/createDocx.d.ts +4 -0
  33. package/dist/docx/createDocx.js +6 -0
  34. package/dist/docx/modelValidation.js +1 -1
  35. package/dist/docx/parser.js +1 -1
  36. package/dist/docx/reviewResolutionProvenance.js +1 -1
  37. package/dist/docx/rezip.d.ts +1 -1
  38. package/dist/docx/rezip.js +2 -2
  39. package/dist/docx/serializer/borderSerializer.js +1 -1
  40. package/dist/docx/serializer/commentSerializer.js +1 -1
  41. package/dist/docx/serializer/documentSerializer.js +1 -1
  42. package/dist/docx/serializer/paragraphSerializer.js +3 -3
  43. package/dist/docx/serializer/runSerializer.js +1 -1
  44. package/dist/docx/serializer/sectionPropertiesSerializer.js +1 -1
  45. package/dist/docx/serializer/tableSerializer.js +1 -1
  46. package/dist/docx/serializer/textFormattingSerializer.js +1 -1
  47. package/dist/docx/serializer/trackedChangeAttributes.js +1 -1
  48. package/dist/docx/server/templatePlan/apply.js +69 -11
  49. package/dist/docx/server/templatePlan/inspect.js +88 -35
  50. package/dist/docx/server/templatePlan/labels.d.ts +10 -1
  51. package/dist/docx/server/templatePlan/labels.js +31 -2
  52. package/dist/docx/server/templatePlan/plan.d.ts +2 -0
  53. package/dist/docx/server/templatePlan/plan.js +41 -7
  54. package/dist/docx/server/templatePlan/planShape.js +22 -3
  55. package/dist/docx/server/templatePlan/types.d.ts +38 -2
  56. package/dist/docx/server/templatePlan/types.js +1 -0
  57. package/dist/docx/server/templatePlan/verify.js +11 -3
  58. package/dist/docx/server/templatePlan/xml.d.ts +5 -0
  59. package/dist/docx/server/templatePlan/xml.js +7 -1
  60. package/dist/docx/storyBlockReplay.js +1 -1
  61. package/dist/docx/xmlParser.js +1 -1
  62. package/dist/i18n/loadMessages.d.ts +5 -0
  63. package/dist/i18n/loadMessages.js +46 -0
  64. package/dist/i18n/locales.d.ts +3 -0
  65. package/dist/i18n/locales.js +17 -0
  66. package/dist/i18n/messages.d.ts +3 -2
  67. package/dist/i18n/messages.js +4 -16
  68. package/dist/internal/clipboardTransformPlugin.d.ts +3 -0
  69. package/dist/internal/clipboardTransformPlugin.js +13 -0
  70. package/dist/internal/extensionRuntime.d.ts +7 -0
  71. package/dist/internal/extensionRuntime.js +28 -0
  72. package/dist/internal/paragraphFormattingSerialization.js +1 -1
  73. package/dist/internal/starterKitExtensions.d.ts +20 -0
  74. package/dist/internal/starterKitExtensions.js +123 -0
  75. package/dist/internal/wholeStoryRevisionResolution.js +2 -2
  76. package/dist/prosemirror/attrs/index.js +1 -1
  77. package/dist/prosemirror/canonicalSelectionRange.js +1 -1
  78. package/dist/prosemirror/canonicalTableCommands.js +1 -1
  79. package/dist/prosemirror/commands/comments.js +3 -3
  80. package/dist/prosemirror/commands/contentControls.js +1 -1
  81. package/dist/prosemirror/commands/pastePlainText.js +2 -3
  82. package/dist/prosemirror/commands/replaceRangeText.js +1 -1
  83. package/dist/prosemirror/commentRecords.js +2 -2
  84. package/dist/prosemirror/conversion/fromProseDoc.d.ts +0 -5
  85. package/dist/prosemirror/conversion/fromProseDoc.js +2 -9
  86. package/dist/prosemirror/conversion/index.d.ts +2 -2
  87. package/dist/prosemirror/conversion/index.js +2 -2
  88. package/dist/prosemirror/extensions/ExtensionManager.js +4 -22
  89. package/dist/prosemirror/extensions/StarterKit.d.ts +4 -27
  90. package/dist/prosemirror/extensions/StarterKit.js +29 -115
  91. package/dist/prosemirror/extensions/core/ParagraphExtension.js +2 -2
  92. package/dist/prosemirror/extensions/features/BaseKeymapExtension.js +1 -1
  93. package/dist/prosemirror/extensions/features/ListExtension.js +7 -2
  94. package/dist/prosemirror/extensions/features/pastedHeadingStyles.js +1 -1
  95. package/dist/prosemirror/extensions/index.d.ts +2 -1
  96. package/dist/prosemirror/extensions/marks/FootnoteRefExtension.js +8 -3
  97. package/dist/prosemirror/extensions/nodes/TableExtension.js +7 -40
  98. package/dist/prosemirror/hyperlinkRemoval.js +7 -2
  99. package/dist/prosemirror/index.d.ts +2 -2
  100. package/dist/prosemirror/index.js +2 -2
  101. package/dist/prosemirror/keptRangeBoundaries.js +1 -1
  102. package/dist/prosemirror/listNumbering.js +1 -1
  103. package/dist/prosemirror/noteReferenceOccurrences.js +1 -1
  104. package/dist/prosemirror/noteReferenceReview.d.ts +2 -56
  105. package/dist/prosemirror/noteReferenceReview.js +2 -243
  106. package/dist/prosemirror/pastedCommentCopies.js +1 -1
  107. package/dist/prosemirror/plugins/documentNumbering.js +1 -1
  108. package/dist/prosemirror/plugins/documentStyles.js +1 -1
  109. package/dist/prosemirror/replacedAnnotations.js +1 -1
  110. package/dist/prosemirror/suggestionCommands.d.ts +47 -0
  111. package/dist/prosemirror/suggestionCommands.js +31 -0
  112. package/dist/prosemirror/tableCellPaste.js +1 -1
  113. package/dist/prosemirror/tableRunIn.js +1 -1
  114. package/dist/prosemirror/textInput.js +1 -1
  115. package/dist/types/canonicalCapabilities.d.ts +6 -52
  116. package/dist/types/canonicalCapabilities.js +6 -52
  117. package/package.json +2 -2
  118. package/dist/ai-edits/apply.d.ts +0 -94
  119. package/dist/ai-edits/apply.js +0 -6637
  120. package/dist/ai-edits/note-story-inventory.d.ts +0 -5
  121. package/dist/ai-edits/note-story-inventory.js +0 -10
  122. package/dist/ai-edits/revisionStretches.d.ts +0 -32
  123. package/dist/ai-edits/revisionStretches.js +0 -147
  124. package/dist/document-operations-apply.d.ts +0 -15
  125. package/dist/document-operations-apply.js +0 -280
  126. package/dist/prosemirror/extensions/core/HistoryExtension.d.ts +0 -12
  127. package/dist/prosemirror/extensions/core/HistoryExtension.js +0 -114
  128. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.d.ts +0 -23
  129. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.js +0 -270
  130. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +0 -51
  131. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +0 -411
  132. package/dist/prosemirror/plugins/suggestionMode.d.ts +0 -92
  133. package/dist/prosemirror/plugins/suggestionMode.js +0 -1515
  134. package/dist/prosemirror/tablePositionedBookmarks.d.ts +0 -8
  135. package/dist/prosemirror/tablePositionedBookmarks.js +0 -80
@@ -1,1515 +0,0 @@
1
- import { maxOf, minOf } from "../../utils/extremes.js";
2
- import { addTrackedDeletionMark } from "../addTrackedDeletionMark.js";
3
- import { expectParagraphAttrs, expectTableRowAttrs, expectTrackedChangeMarkAttrs } from "../attrs/index.js";
4
- import { clearIndentOnBackspace } from "../commands/clearParagraphIndent.js";
5
- import { paragraphJoinAfter } from "../commands/paragraphBookmarkJoin.js";
6
- import { paragraphPropertiesSnapshot } from "../commands/propertyChangeScope.js";
7
- import { paragraphEndsItsContainer } from "../containerFinalParagraph.js";
8
- import { encloseWholeControls } from "../contentControlRevisions.js";
9
- import { splitBlockClearBorders } from "../extensions/features/BaseKeymapExtension.js";
10
- import { JOINED_RUNS_RESTYLED_META } from "../extensions/features/JoinedRunStyleExtension.js";
11
- import { expandNoteReferenceDeletionRange } from "../extensions/marks/noteReferenceDeletion.js";
12
- import { isInlineAnchor } from "../extensions/nodes/inlineAnchorDom.js";
13
- import { joinAtParagraphMark } from "../paragraphMarkJoin.js";
14
- import { carryParagraphProperties, paragraphLeftAfter, recordReplacedParagraphProperties } from "../paragraphPropertyCarry.js";
15
- import { createPluginKeyOwner } from "../pluginKeyOwner.js";
16
- import { rebaseParagraphRuns } from "../rebaseParagraphRunFormatting.js";
17
- import { RUN_FORMATTING_MARK_NAMES } from "../runFormattingMarkNames.js";
18
- import { paragraphRunStyleContext } from "../runStyleFormatting.js";
19
- import { cellPasteRange, pasteTableCells } from "../tableCellPaste.js";
20
- import { deleteTableRowAt } from "../tableGridMutation.js";
21
- import { afterNativeCompositionFlush, formattingMarksBesideLockedControl, handleEditorBeforeInput, keepTypedTextInComments } from "../textInput.js";
22
- import { canCarryTrackedRunMark } from "../trackedRunInlineAtoms.js";
23
- import { getDocumentNumbering } from "./documentNumbering.js";
24
- import { documentStylesKey, getDocumentStyleResolver } from "./documentStyleState.js";
25
- import { selectLockedInlineControl } from "./lockedControlKeyHandling.js";
26
- import { mintRevisionId, seedRevisionIdsFromDoc } from "./revisionIds.js";
27
- import { Slice } from "prosemirror-model";
28
- import { CellSelection } from "prosemirror-tables";
29
- import { Mapping, ReplaceAroundStep, ReplaceStep } from "prosemirror-transform";
30
- import { AllSelection, EditorState, Plugin, Selection, TextSelection } from "prosemirror-state";
31
- import { joinBackward, joinForward, selectNodeBackward, selectNodeForward } from "prosemirror-commands";
32
- import { isHistoryTransaction } from "prosemirror-history";
33
- import { undoInputRule } from "prosemirror-inputrules";
34
- // src/prosemirror/plugins/suggestionMode.ts
35
- /**
36
- * Suggestion Mode Plugin
37
- *
38
- * When active, intercepts all text insertions and deletions,
39
- * wrapping them in tracked change marks (insertion/deletion)
40
- * instead of modifying the document directly.
41
- *
42
- * - Typed text is marked as insertion (green underline)
43
- * - Deleted text is NOT removed — it's marked as deletion (red strikethrough)
44
- * - Text already marked as insertion by the current author is deleted normally
45
- * (retracting your own suggestion)
46
- */
47
- const suggestionModeKey = createPluginKeyOwner("suggestionMode");
48
- const SUGGESTION_META = "suggestionModeApplied";
49
- const SUGGESTION_BYPASS_META = "suggestionModeBypass";
50
- /**
51
- * The text a tracked text-input transaction typed. Rules that react to typing
52
- * (list autoformat) read it, because this plugin claims text input before any
53
- * input rule sees it.
54
- */
55
- const SUGGESTED_TEXT_INPUT_META = "suggestionModeTextInput";
56
- function makeMarkAttrs(pluginState) {
57
- return {
58
- revisionId: mintRevisionId(),
59
- author: pluginState.author,
60
- date: (/* @__PURE__ */ new Date()).toISOString()
61
- };
62
- }
63
- function makeRevisionInfo(state) {
64
- const pluginState = suggestionModeKey.getState(state);
65
- if (!pluginState?.active) return null;
66
- const attrs = makeMarkAttrs(pluginState);
67
- return {
68
- id: attrs.revisionId,
69
- author: attrs.author,
70
- date: attrs.date
71
- };
72
- }
73
- /**
74
- * A removed paragraph mark leaves the paragraph after it once accepted. An
75
- * edit that reads as the paragraph before it (Backspace or Delete at the
76
- * break, a deletion running from inside one paragraph into another) gives the
77
- * paragraph left that paragraph's properties now, under the mark's revision:
78
- * accepting reads as the edit made directly, rejecting restores its own.
79
- */
80
- function carryIntoParagraphLeft(state, tr, source, survivorPos, info) {
81
- carryParagraphProperties({
82
- tr,
83
- position: survivorPos,
84
- source,
85
- styleResolver: getDocumentStyleResolver(state),
86
- numbering: getDocumentNumbering(state),
87
- revision: {
88
- id: info.id,
89
- author: info.author ?? "",
90
- date: info.date ?? ""
91
- }
92
- });
93
- }
94
- function makeParagraphMarkInfo(pluginState) {
95
- const attrs = makeMarkAttrs(pluginState);
96
- return {
97
- id: attrs.revisionId,
98
- author: attrs.author,
99
- date: attrs.date
100
- };
101
- }
102
- /**
103
- * Find an adjacent mark of the same type by the same author.
104
- * Reuses its revisionId so consecutive edits group into one change.
105
- */
106
- function findAdjacentRevision(doc, pos, markTypeName, author) {
107
- try {
108
- const $pos = doc.resolve(pos);
109
- for (const node of [$pos.nodeBefore, $pos.nodeAfter]) if (node?.isText) {
110
- const mark = node.marks.find((m) => m.type.name === markTypeName && m.attrs["author"] === author);
111
- if (mark) return mark.attrs;
112
- }
113
- } catch {}
114
- return null;
115
- }
116
- /**
117
- * Find an adjacent revision at either edge of a range.
118
- * This keeps consecutive backspaces grouped even though the cursor moves left.
119
- */
120
- function findAdjacentRevisionForRange(doc, from, to, markTypeName, author) {
121
- return findAdjacentRevision(doc, from, markTypeName, author) ?? findAdjacentRevision(doc, to, markTypeName, author);
122
- }
123
- /**
124
- * Walk a selected range and track its text, paragraph breaks, and table rows.
125
- * Retract the current author's own inserted text.
126
- * Processes in reverse order to maintain position validity.
127
- */
128
- function markRangeAsDeleted(tr, doc, from, to, deletionType, pluginState, joinState) {
129
- let hasMarkableContent = false;
130
- const stepsBeforeDoc = doc === tr.doc ? tr.mapping.maps.length : 0;
131
- doc.nodesBetween(from, to, (node, pos) => {
132
- if (!canCarryTrackedRunMark(node)) return;
133
- if (Math.max(pos, from) >= Math.min(pos + node.nodeSize, to)) return;
134
- if (node.marks.some((m) => m.type === deletionType)) return;
135
- hasMarkableContent = true;
136
- });
137
- const delAttrs = findAdjacentRevisionForRange(doc, from, to, "deletion", pluginState.author) || makeMarkAttrs(pluginState);
138
- let removedMark = false;
139
- const retractedBreaks = [];
140
- const retractedRows = [];
141
- doc.nodesBetween(from, to, (node, pos) => {
142
- if (node.type.name === "tableRow" && pos >= from && pos + node.nodeSize <= to) {
143
- const { trIns, trDel } = expectTableRowAttrs(node);
144
- if (trIns == null && trDel == null) tr.setNodeAttribute(pos, "trDel", delAttrs);
145
- else if (trIns?.author === pluginState.author) retractedRows.push(pos);
146
- }
147
- if (node.type.name !== "paragraph") return;
148
- const boundary = pos + node.nodeSize;
149
- if (boundary <= from || boundary > to) return;
150
- const mark = node.attrs["pPrMark"];
151
- if (mark == null) {
152
- tr.setNodeAttribute(pos, "pPrMark", {
153
- kind: "del",
154
- info: {
155
- id: delAttrs.revisionId,
156
- author: delAttrs.author,
157
- date: delAttrs.date
158
- }
159
- });
160
- removedMark = true;
161
- } else if (isCurrentAuthorParagraphInsertion(mark, pluginState.author)) {
162
- retractedBreaks.push(pos);
163
- removedMark = true;
164
- } else if (isOtherAuthorParagraphInsertion(mark, pluginState.author)) {
165
- tr.setNodeAttribute(pos, "pPrMark", {
166
- ...mark,
167
- deletion: { info: {
168
- id: delAttrs.revisionId,
169
- author: delAttrs.author,
170
- date: delAttrs.date
171
- } }
172
- });
173
- removedMark = true;
174
- }
175
- });
176
- const $first = doc.resolve(from);
177
- const $last = doc.resolve(to);
178
- if (joinState && removedMark && $first.parent.type.name === "paragraph" && $last.parent.type.name === "paragraph" && $first.parent !== $last.parent && from > $first.start()) {
179
- const lastPos = tr.mapping.slice(stepsBeforeDoc).map($last.before());
180
- const lastMark = tr.doc.nodeAt(lastPos)?.attrs["pPrMark"];
181
- const survivorPos = lastMark?.kind === "del" || lastMark?.kind === "moveFrom" ? paragraphLeftAfter({
182
- doc: tr.doc,
183
- paragraphPos: lastPos
184
- }) ?? lastPos : lastPos;
185
- carryIntoParagraphLeft(joinState, tr, $first.parent, survivorPos, {
186
- id: delAttrs.revisionId,
187
- author: delAttrs.author,
188
- date: delAttrs.date
189
- });
190
- }
191
- if (hasMarkableContent) {
192
- encloseWholeControls({
193
- tr,
194
- from,
195
- to,
196
- revisionId: delAttrs.revisionId
197
- });
198
- addTrackedDeletionMark({
199
- tr,
200
- from,
201
- to,
202
- mark: deletionType.create(delAttrs),
203
- insertionPolicy: "retract-own"
204
- });
205
- }
206
- retractParagraphBreaks({
207
- tr,
208
- positions: retractedBreaks,
209
- stepsBeforeDoc,
210
- styleResolver: joinState ? getDocumentStyleResolver(joinState) : null
211
- });
212
- retractTableRows({
213
- tr,
214
- positions: retractedRows,
215
- stepsBeforeDoc
216
- });
217
- }
218
- /**
219
- * Remove the rows the current author inserted that a deletion spans whole:
220
- * the suggestion is withdrawn, as rejecting it does (`deleteTableRowAt`), so
221
- * a vertical merge crossing a row closes one row sooner and a table left with
222
- * no row goes with it.
223
- */
224
- function retractTableRows({ tr, positions, stepsBeforeDoc }) {
225
- for (const position of positions.toReversed()) {
226
- const rowPos = tr.mapping.slice(stepsBeforeDoc).map(position);
227
- if (tr.doc.nodeAt(rowPos)?.type.name !== "tableRow") continue;
228
- deleteTableRowAt(tr, rowPos);
229
- }
230
- }
231
- /**
232
- * Remove the current author's inserted paragraph breaks a deletion spans: the
233
- * suggestion is withdrawn, so the paragraph runs on into the next one, as
234
- * accepting a struck break joins them. Without this the emptied paragraph
235
- * outlives its words, and accepting keeps a paragraph the direct edit removed.
236
- */
237
- function retractParagraphBreaks({ tr, positions, stepsBeforeDoc, styleResolver }) {
238
- for (const position of positions.toReversed()) {
239
- const paragraphPos = tr.mapping.slice(stepsBeforeDoc).map(position);
240
- const paragraph = tr.doc.nodeAt(paragraphPos);
241
- if (paragraph?.type.name !== "paragraph") continue;
242
- const join = paragraphJoinAfter(tr.doc, paragraphPos + paragraph.nodeSize);
243
- if (!join) continue;
244
- joinAtParagraphMark({
245
- tr,
246
- paragraphPos,
247
- paragraph,
248
- next: join.next,
249
- styleResolver
250
- });
251
- }
252
- }
253
- /** Preserve clipboard revisions inside the revision that inserted their content. */
254
- function enclosePastedRunRevisions({ tr, from, to, revision: insertion }) {
255
- tr.doc.nodesBetween(from, to, (node, pos) => {
256
- if (!canCarryTrackedRunMark(node)) return;
257
- const revision = node.marks.find(({ type }) => type.name === "insertion" || type.name === "deletion");
258
- if (!revision) return;
259
- const previous = expectTrackedChangeMarkAttrs(revision);
260
- tr.addMark(Math.max(from, pos), Math.min(to, pos + node.nodeSize), revision.type.create({
261
- ...revision.attrs,
262
- _docxRevisionAncestors: [{
263
- type: "insertion",
264
- ...insertion,
265
- outerWrapperCount: 0
266
- }, ...previous._docxRevisionAncestors ?? []]
267
- }));
268
- });
269
- }
270
- /**
271
- * Track every inserted run, paragraph break, and table row in `[from, to)`.
272
- * Content already carrying a revision keeps its attribution.
273
- */
274
- function markRangeAsInserted(tr, doc, from, to, insertionType, deletionType, attrs) {
275
- doc.nodesBetween(from, to, (node, pos) => {
276
- if (!canCarryTrackedRunMark(node)) return;
277
- if (node.marks.some((mark) => mark.type === insertionType || mark.type === deletionType)) return;
278
- const start = Math.max(pos, from);
279
- const end = Math.min(pos + node.nodeSize, to);
280
- if (start >= end) return;
281
- tr.addMark(start, end, insertionType.create(attrs));
282
- });
283
- const $end = doc.resolve(to);
284
- const endsBetweenBlocks = !$end.parent.isTextblock && $end.nodeBefore !== null && $end.nodeBefore.type.name !== "paragraph";
285
- doc.nodesBetween(from, to, (node, pos) => {
286
- if (node.type.name === "paragraph") {
287
- const boundary = pos + node.nodeSize;
288
- const keepsOwnMark = endsBetweenBlocks && boundary - 1 === from;
289
- if (boundary > from && boundary < to && !keepsOwnMark && node.attrs["pPrMark"] == null) tr.setNodeAttribute(pos, "pPrMark", {
290
- kind: "ins",
291
- info: {
292
- id: attrs.revisionId,
293
- author: attrs.author,
294
- date: attrs.date
295
- }
296
- });
297
- }
298
- if (node.type.name === "tableRow" && pos >= from && pos + node.nodeSize <= to && node.attrs["trIns"] == null && node.attrs["trDel"] == null) tr.setNodeAttribute(pos, "trIns", attrs);
299
- });
300
- encloseWholeControls({
301
- tr,
302
- from,
303
- to,
304
- revisionId: attrs.revisionId
305
- });
306
- }
307
- /**
308
- * With track changes on, pasting over a non-empty text selection marks the
309
- * replaced text as a tracked deletion and the pasted slice as a tracked
310
- * insertion (so they read as one replacement), matching typing over a
311
- * selection. Select-all (an `AllSelection`) counts as a text selection over the
312
- * whole document. Returns false for a collapsed cursor or another selection so the
313
- * default paste + the `appendTransaction` catch-all marks a plain insertion
314
- * (eigenpal/docx-editor#784).
315
- */
316
- /**
317
- * A paste at the end of the document's final paragraph that leaves a table
318
- * last: the editor puts an empty paragraph after it, which ends the document
319
- * now (see JoinedRunStyleExtension). The paragraph that ended it keeps its
320
- * words, but its break is the paste's: rejecting the paste joins it into the
321
- * new final paragraph, which records what it read as. Placed here so the
322
- * appended paragraph is part of the tracked paste.
323
- */
324
- function pasteEndsDocumentWithBlock(view, slice, pluginState) {
325
- const { state } = view;
326
- const { $from } = state.selection;
327
- const insertionType = state.schema.marks["insertion"];
328
- const deletionType = state.schema.marks["deletion"];
329
- const paragraphType = state.schema.nodes["paragraph"];
330
- if (!insertionType || !deletionType || !paragraphType || $from.depth !== 1 || $from.parent.type !== paragraphType || $from.parent !== state.doc.lastChild || $from.parentOffset !== $from.parent.content.size || expectParagraphAttrs($from.parent).pPrMark != null) return false;
331
- const tr = state.tr;
332
- const firstStep = tr.steps.length;
333
- tr.replaceSelection(slice);
334
- const last = tr.doc.lastChild;
335
- if (!last || last.type === paragraphType || last.isTextblock) return false;
336
- const placed = tr.steps.slice(firstStep).flatMap((step, offset) => {
337
- const later = new Mapping(tr.mapping.maps.slice(firstStep + offset + 1));
338
- const ranges = [];
339
- step.getMap().forEach((_oldFrom, _oldTo, newFrom, newTo) => {
340
- ranges.push({
341
- from: later.map(newFrom, -1),
342
- to: later.map(newTo, 1)
343
- });
344
- });
345
- return ranges;
346
- });
347
- if (placed.length === 0) return false;
348
- const insertFrom = minOf(placed.map((range) => range.from));
349
- const insertTo = maxOf(placed.map((range) => range.to));
350
- const final = paragraphType.createAndFill();
351
- if (!final) return false;
352
- const caret = tr.selection.head;
353
- const finalPos = tr.doc.content.size;
354
- tr.insert(finalPos, final);
355
- tr.setMeta(SUGGESTION_META, true).setMeta("paste", true).setMeta("uiEvent", "paste");
356
- const revision = makeMarkAttrs(pluginState);
357
- enclosePastedRunRevisions({
358
- tr,
359
- from: insertFrom,
360
- to: insertTo,
361
- revision
362
- });
363
- markRangeAsInserted(tr, tr.doc, insertFrom, insertTo, insertionType, deletionType, revision);
364
- const info = {
365
- id: revision.revisionId,
366
- author: revision.author,
367
- date: revision.date
368
- };
369
- tr.setNodeAttribute($from.before(), "pPrMark", {
370
- kind: "ins",
371
- info
372
- });
373
- recordReplacedParagraphProperties({
374
- tr,
375
- position: finalPos,
376
- replaced: $from.parent,
377
- revision: info
378
- });
379
- tr.setSelection(Selection.near(tr.doc.resolve(caret), -1));
380
- view.dispatch(tr.scrollIntoView());
381
- return true;
382
- }
383
- function handleSuggestionPaste(view, slice, pluginState) {
384
- const { selection } = view.state;
385
- const selectsAll = selection instanceof AllSelection;
386
- if (!(selection instanceof TextSelection || selectsAll)) return false;
387
- const insertionType = view.state.schema.marks["insertion"];
388
- const deletionType = view.state.schema.marks["deletion"];
389
- if (!insertionType || !deletionType) return false;
390
- if (selection.empty) {
391
- const { $from } = selection;
392
- const closedBlocks = slice.openStart === 0 && slice.openEnd === 0 && slice.content.firstChild?.isBlock === true;
393
- const prefix = $from.parent.content.cut(0, $from.parentOffset);
394
- let deletedPrefix = false;
395
- let keptPrefix = false;
396
- prefix.forEach((node) => {
397
- if (isInlineAnchor(node)) return;
398
- if (node.marks.some((mark) => mark.type === deletionType)) deletedPrefix = true;
399
- else keptPrefix = true;
400
- });
401
- deletedPrefix &&= !keptPrefix;
402
- if (!deletedPrefix && pasteEndsDocumentWithBlock(view, slice, pluginState)) return true;
403
- if (!closedBlocks || $from.parent.type.name !== "paragraph" || !deletedPrefix) return false;
404
- const suffix = $from.parent.content.cut($from.parentOffset);
405
- let deletedSuffix = true;
406
- suffix.forEach((node) => {
407
- if (!node.marks.some((mark) => mark.type === deletionType)) deletedSuffix = false;
408
- });
409
- const rotates = deletedSuffix && ($from.parent.attrs["pPrMark"]?.kind ?? "del") === "del" && paragraphEndsItsContainer($from.doc.resolve($from.before()), "paragraph") && slice.content.firstChild?.type === $from.parent.type && slice.content.lastChild?.type === $from.parent.type;
410
- const tr = view.state.tr.setMeta(SUGGESTION_META, true).setMeta("paste", true);
411
- const at = rotates ? $from.after() : $from.before();
412
- tr.replaceRange(at, at, slice);
413
- const revision = makeMarkAttrs(pluginState);
414
- const end = tr.mapping.map(at, 1);
415
- enclosePastedRunRevisions({
416
- tr,
417
- from: at,
418
- to: end,
419
- revision
420
- });
421
- tr.doc.nodesBetween(at, end, (node, pos) => {
422
- if (node.type.name !== "paragraph" || node.attrs["pPrMark"] != null) return false;
423
- tr.setNodeAttribute(pos, "pPrMark", {
424
- kind: "ins",
425
- info: {
426
- id: revision.revisionId,
427
- author: revision.author,
428
- date: revision.date
429
- }
430
- });
431
- return false;
432
- });
433
- markRangeAsInserted(tr, tr.doc, at, end, insertionType, deletionType, revision);
434
- if (rotates) {
435
- const rotation = tr.steps.length;
436
- rotateIntoFinalParagraph(view.state, tr, $from.before(), revision);
437
- tr.setSelection(TextSelection.near(tr.doc.resolve(tr.mapping.slice(rotation).map(end, -1)), -1));
438
- view.dispatch(tr.scrollIntoView());
439
- return true;
440
- }
441
- if (deletedSuffix && $from.parent.attrs["pPrMark"] == null && !paragraphEndsItsContainer($from.doc.resolve($from.before()), "paragraph")) tr.setNodeAttribute(tr.mapping.map($from.before()), "pPrMark", {
442
- kind: "del",
443
- info: makeParagraphMarkInfo(pluginState)
444
- });
445
- tr.setSelection(TextSelection.create(tr.doc, tr.mapping.map(selection.from)));
446
- view.dispatch(tr.scrollIntoView());
447
- return true;
448
- }
449
- let directCaret = null;
450
- if (selectsAll && (slice.openStart > 0 || slice.openEnd > 0)) {
451
- const direct = view.state.tr.replaceSelection(slice);
452
- slice = new Slice(direct.doc.content, 0, 0);
453
- directCaret = direct.selection.head;
454
- }
455
- const { from, to } = selectsAll ? {
456
- from: Selection.atStart(view.state.doc).from,
457
- to: Selection.atEnd(view.state.doc).to
458
- } : selection;
459
- const tr = view.state.tr;
460
- tr.setMeta(SUGGESTION_META, true);
461
- const { doc } = view.state;
462
- const $from = doc.resolve(from);
463
- const $to = doc.resolve(to);
464
- const closedBlocks = slice.openStart === 0 && slice.content.firstChild?.isBlock === true;
465
- const beforeStruck = closedBlocks && $from.parent.isTextblock && $from.parentOffset === 0;
466
- const wholeBlocks = beforeStruck && $to.parent.isTextblock && $to.parentOffset === $to.parent.content.size;
467
- const endsContainer = wholeBlocks && paragraphEndsItsContainer(doc.resolve($to.before()), $to.parent.type.name);
468
- const rotates = endsContainer && slice.content.firstChild?.type === $to.parent.type && slice.content.lastChild?.type === $to.parent.type;
469
- const struckFrom = selectsAll ? 0 : from;
470
- const tableFirst = endsContainer && !rotates;
471
- if (!tableFirst) markRangeAsDeleted(tr, doc, struckFrom, wholeBlocks && !endsContainer ? $to.after() : to, deletionType, pluginState);
472
- const firstBreakRetracts = isCurrentAuthorParagraphInsertion($from.parent.attrs["pPrMark"], pluginState.author);
473
- const carryAcross = () => {
474
- if (selectsAll || $from.parent.type.name !== "paragraph" || $from.parent === $to.parent || from <= $from.start()) return;
475
- const firstPos = tr.mapping.map($from.before());
476
- const mark = tr.doc.nodeAt(firstPos)?.attrs["pPrMark"];
477
- const survivorPos = paragraphLeftAfter({
478
- doc: tr.doc,
479
- paragraphPos: firstPos
480
- });
481
- if (mark?.kind === "del" && survivorPos !== null) carryIntoParagraphLeft(view.state, tr, $from.parent, survivorPos, mark.info);
482
- else if (firstBreakRetracts) carryParagraphProperties({
483
- tr,
484
- position: firstPos,
485
- source: $from.parent,
486
- styleResolver: getDocumentStyleResolver(view.state),
487
- numbering: getDocumentNumbering(view.state),
488
- ...isCurrentAuthorParagraphInsertion(mark, pluginState.author) ? {} : { revision: makeParagraphMarkInfo(pluginState) }
489
- });
490
- };
491
- const inlineSlice = slice.content.firstChild?.isInline === true;
492
- if (inlineSlice) carryAcross();
493
- let at = tr.mapping.map(to);
494
- if (rotates) at = tr.mapping.map($to.after());
495
- else if (tableFirst) at = selectsAll ? 0 : $from.before();
496
- else if (beforeStruck) at = tr.mapping.map(from, -1);
497
- const firstStep = tr.steps.length;
498
- tr.replaceRange(at, at, slice);
499
- const placed = tr.steps.slice(firstStep).flatMap((step, offset) => {
500
- const later = new Mapping(tr.mapping.maps.slice(firstStep + offset + 1));
501
- const ranges = [];
502
- step.getMap().forEach((_oldFrom, _oldTo, newFrom, newTo) => {
503
- ranges.push({
504
- from: later.map(newFrom, -1),
505
- to: later.map(newTo, 1)
506
- });
507
- });
508
- return ranges;
509
- });
510
- let insertFrom = placed.length === 0 ? at : minOf(placed.map((range) => range.from));
511
- let insertTo = placed.length === 0 ? at : maxOf(placed.map((range) => range.to));
512
- if (tableFirst) {
513
- const struck = tr.steps.length;
514
- markRangeAsDeleted(tr, tr.doc, tr.mapping.map(struckFrom), tr.mapping.map(to), deletionType, pluginState);
515
- const since = tr.mapping.slice(struck);
516
- insertFrom = since.map(insertFrom, -1);
517
- insertTo = since.map(insertTo, -1);
518
- }
519
- const insertAttrs = findAdjacentRevision(doc, from, "insertion", pluginState.author) || makeMarkAttrs(pluginState);
520
- enclosePastedRunRevisions({
521
- tr,
522
- from: insertFrom,
523
- to: insertTo,
524
- revision: insertAttrs
525
- });
526
- markRangeAsInserted(tr, tr.doc, insertFrom, insertTo, insertionType, deletionType, insertAttrs);
527
- if (!inlineSlice) carryAcross();
528
- if ($to.parent.type.name === "paragraph") {
529
- const $end = tr.doc.resolve(closedBlocks ? Math.max(insertFrom, insertTo - 1) : tr.mapping.map(to));
530
- const endsPastFirst = $end.parent.type.name === "paragraph" && $end.before() !== tr.mapping.map($from.before());
531
- const endMark = endsPastFirst ? expectParagraphAttrs($end.parent).pPrMark ?? expectParagraphAttrs($to.parent).pPrMark : null;
532
- if (endsPastFirst && endMark != null && $end.parent.attrs["pPrMark"] == null) tr.setNodeAttribute($end.before(), "pPrMark", endMark);
533
- if (endsPastFirst && endMark?.kind !== "ins") recordReplacedParagraphProperties({
534
- tr,
535
- position: $end.before(),
536
- replaced: $to.parent,
537
- revision: {
538
- id: insertAttrs.revisionId,
539
- author: insertAttrs.author,
540
- date: insertAttrs.date
541
- }
542
- });
543
- }
544
- const firstPasted = slice.content.firstChild;
545
- if (selectsAll && !closedBlocks && firstPasted?.type.name === "paragraph") {
546
- const $first = tr.doc.resolve(insertFrom);
547
- if ($first.parent.type.name === "paragraph") carryParagraphProperties({
548
- tr,
549
- position: $first.before(),
550
- source: firstPasted,
551
- revision: {
552
- id: insertAttrs.revisionId,
553
- author: insertAttrs.author,
554
- date: insertAttrs.date
555
- },
556
- styleResolver: getDocumentStyleResolver(view.state),
557
- numbering: getDocumentNumbering(view.state)
558
- });
559
- }
560
- if (rotates) {
561
- const rotation = tr.steps.length;
562
- const joined = rotateIntoFinalParagraph(view.state, tr, tr.mapping.map($to.before()), insertAttrs);
563
- insertFrom = Math.min(tr.mapping.slice(rotation).map(insertFrom, -1), joined);
564
- insertTo = tr.mapping.slice(rotation).map(insertTo);
565
- }
566
- if (tableFirst) {
567
- const end = directCaret !== null && insertFrom + directCaret <= insertTo ? insertFrom + directCaret : insertTo;
568
- tr.setSelection(TextSelection.near(tr.doc.resolve(end), -1));
569
- view.dispatch(tr.scrollIntoView());
570
- return true;
571
- }
572
- const caret = beforeStruck && !wholeBlocks ? tr.mapping.map(to) : insertTo;
573
- tr.setSelection(TextSelection.near(tr.doc.resolve(caret)));
574
- view.dispatch(tr.scrollIntoView());
575
- return true;
576
- }
577
- /**
578
- * With track changes on, a paste into a table's cells (a cell selection, or a
579
- * block of copied cells) replaces each cell's content the way a paste over a
580
- * text selection does: the old content struck through, the pasted content
581
- * after it as an insertion. When the pasted content is whole paragraphs, the
582
- * last one ends the cell, so its paragraph mark is tracked as added too:
583
- * rejecting then drops it and accepting joins the struck paragraphs into it.
584
- */
585
- const holdsOnlyStruckText = (paragraph, deletion) => {
586
- let struck = true;
587
- paragraph.forEach((node) => {
588
- if (!node.marks.some((mark) => mark.type === deletion)) struck = false;
589
- });
590
- return struck;
591
- };
592
- function handleSuggestionTableCellPaste(view, slice, pluginState) {
593
- const insertionType = view.state.schema.marks["insertion"];
594
- const deletionType = view.state.schema.marks["deletion"];
595
- if (!insertionType || !deletionType) return false;
596
- const revision = makeMarkAttrs(pluginState);
597
- return pasteTableCells(view.state, slice, (tr) => view.dispatch(tr.setMeta(SUGGESTION_META, true)), {
598
- revision,
599
- replaceCellContent: (tr, cellPos, content) => {
600
- const cell = tr.doc.nodeAt(cellPos);
601
- if (!cell) return;
602
- const { from, to } = cellPasteRange(cell, cellPos, content);
603
- const mapFrom = tr.mapping.maps.length;
604
- markRangeAsDeleted(tr, tr.doc, from, to, deletionType, pluginState);
605
- const insertFrom = tr.mapping.slice(mapFrom).map(to);
606
- const sizeBefore = tr.doc.content.size;
607
- tr.replaceRange(insertFrom, insertFrom, content);
608
- let insertTo = insertFrom + (tr.doc.content.size - sizeBefore);
609
- let pastedFrom = insertFrom;
610
- const finalParagraph = cell.lastChild;
611
- const $pasteFrom = tr.doc.resolve(pastedFrom);
612
- const $pasteTo = tr.doc.resolve(insertTo);
613
- if (content.openStart > 0 && content.openEnd > 0 && finalParagraph?.type.name === "paragraph" && $pasteFrom.parent.type.name === "paragraph" && $pasteTo.parent.type.name === "paragraph" && $pasteFrom.before() !== $pasteTo.before()) {
614
- tr.setNodeAttribute($pasteFrom.before(), "pPrMark", {
615
- kind: "ins",
616
- info: {
617
- id: revision.revisionId,
618
- author: revision.author,
619
- date: revision.date
620
- }
621
- });
622
- tr.setNodeAttribute($pasteTo.before(), "pPrMark", finalParagraph.attrs["pPrMark"]);
623
- recordReplacedParagraphProperties({
624
- tr,
625
- position: $pasteTo.before(),
626
- replaced: finalParagraph,
627
- revision: {
628
- id: revision.revisionId,
629
- author: revision.author,
630
- date: revision.date
631
- }
632
- });
633
- }
634
- const emptyInsertions = [];
635
- const struckBreaks = [];
636
- tr.doc.nodeAt(cellPos)?.forEach((node, offset, index) => {
637
- const pos = cellPos + 1 + offset;
638
- if (pos >= pastedFrom || node.type.name !== "paragraph" || !isCurrentAuthorParagraphInsertion(node.attrs["pPrMark"], pluginState.author)) return;
639
- if (node.content.size === 0) emptyInsertions.push({
640
- from: pos,
641
- to: pos + node.nodeSize
642
- });
643
- else if (holdsOnlyStruckText(node, deletionType) && isCurrentAuthorParagraphInsertion(cell.maybeChild(index)?.attrs["pPrMark"], pluginState.author)) struckBreaks.push(pos + node.nodeSize);
644
- });
645
- const retraction = tr.mapping.maps.length;
646
- for (const range of emptyInsertions.toReversed()) tr.delete(range.from, range.to);
647
- for (const boundary of struckBreaks.toReversed()) {
648
- const at = tr.mapping.slice(retraction).map(boundary);
649
- const { nodeBefore, nodeAfter } = tr.doc.resolve(at);
650
- if (nodeBefore?.type.name !== "paragraph" || !nodeAfter) continue;
651
- tr.setNodeMarkup(at - nodeBefore.nodeSize, void 0, nodeAfter.attrs);
652
- tr.join(at);
653
- }
654
- const retracted = tr.mapping.slice(retraction);
655
- pastedFrom = retracted.map(pastedFrom);
656
- insertTo = retracted.map(insertTo);
657
- enclosePastedRunRevisions({
658
- tr,
659
- from: pastedFrom,
660
- to: insertTo,
661
- revision
662
- });
663
- markRangeAsInserted(tr, tr.doc, pastedFrom, insertTo, insertionType, deletionType, revision);
664
- tr.doc.nodesBetween(pastedFrom, insertTo, (node, pos) => {
665
- if (node.type.name === "paragraph" && pos >= pastedFrom && pos + node.nodeSize <= insertTo && node.attrs["pPrMark"] == null) tr.setNodeAttribute(pos, "pPrMark", {
666
- kind: "ins",
667
- info: {
668
- id: revision.revisionId,
669
- author: revision.author,
670
- date: revision.date
671
- }
672
- });
673
- });
674
- }
675
- });
676
- }
677
- /**
678
- * Pasted paragraphs replaced a container's last paragraph. They were placed
679
- * after it, and the paragraph was struck but keeps its mark, as a container's
680
- * last paragraph must. Join the first pasted paragraph onto it, so the struck
681
- * text and the first paste share one paragraph whose break is the inserted one,
682
- * and record the replaced paragraph's formatting on the paragraph that now ends
683
- * the container: accepting leaves only the paste, and rejecting closes every
684
- * pasted break back into one paragraph that returns to its old formatting.
685
- * Returns the position of the joined paragraph.
686
- */
687
- function rotateIntoFinalParagraph(state, tr, replacedPos, attrs) {
688
- const replaced = tr.doc.nodeAt(replacedPos);
689
- const first = replaced ? tr.doc.nodeAt(replacedPos + replaced.nodeSize) : null;
690
- if (!replaced || !first) return replacedPos;
691
- const previousFormatting = paragraphPropertiesSnapshot(replaced);
692
- const { _sectionProperties: sectionProperties } = replaced.attrs;
693
- tr.join(replacedPos + replaced.nodeSize);
694
- tr.setNodeMarkup(replacedPos, void 0, first.attrs);
695
- const styleResolver = getDocumentStyleResolver(state);
696
- if (styleResolver && replaced.content.size > 0) rebaseParagraphRuns({
697
- previousContext: paragraphRunStyleContext(replaced, styleResolver),
698
- paragraphPosition: replacedPos,
699
- range: {
700
- from: 0,
701
- to: replaced.content.size
702
- },
703
- styleResolver,
704
- tr
705
- });
706
- const $joined = tr.doc.resolve(replacedPos);
707
- const container = $joined.parent;
708
- let finalPos = replacedPos;
709
- for (let index = $joined.index(); index < container.childCount - 1; index += 1) finalPos += container.child(index).nodeSize;
710
- const final = tr.doc.nodeAt(finalPos);
711
- if (final) tr.setNodeMarkup(finalPos, void 0, {
712
- ...final.attrs,
713
- pPrMark: null,
714
- ...sectionProperties == null ? {} : { _sectionProperties: sectionProperties },
715
- _propertyChanges: [{
716
- type: "paragraphPropertyChange",
717
- info: {
718
- id: attrs.revisionId,
719
- author: attrs.author,
720
- date: attrs.date
721
- },
722
- previousFormatting
723
- }]
724
- });
725
- return replacedPos;
726
- }
727
- /**
728
- * Insert text as a tracked insertion, optionally marking replaced selection as deletion.
729
- */
730
- function applySuggestionInsert(view, from, to, text, pluginState) {
731
- const insertionType = view.state.schema.marks["insertion"];
732
- if (!insertionType) return false;
733
- const tr = view.state.tr;
734
- tr.setMeta(SUGGESTION_META, true);
735
- tr.setMeta(SUGGESTED_TEXT_INPUT_META, text);
736
- const { selection } = view.state;
737
- const typesOverSelection = !selection.empty && selection.from === from && selection.to === to;
738
- const selectsAll = selection instanceof AllSelection;
739
- if (selectsAll) {
740
- from = Math.max(from, Selection.atStart(view.state.doc).from);
741
- to = Math.min(to, Selection.atEnd(view.state.doc).to);
742
- } else if (typesOverSelection && selection instanceof CellSelection) {
743
- const cellDeletion = view.state.schema.marks["deletion"];
744
- if (cellDeletion) {
745
- const ranges = selection.ranges.toSorted((a, b) => b.$from.pos - a.$from.pos);
746
- for (const range of ranges) markRangeAsDeleted(tr, view.state.doc, range.$from.pos, range.$to.pos, cellDeletion, pluginState, view.state);
747
- }
748
- const last = Selection.findFrom(view.state.doc.resolve(to), -1, true);
749
- if (last && last.to >= from) {
750
- from = last.to;
751
- to = last.to;
752
- }
753
- }
754
- const replacedFormatting = selectsAll ? (view.state.doc.resolve(from).nodeAfter?.marks ?? []).filter(({ type }) => RUN_FORMATTING_MARK_NAMES.has(type.name)) : null;
755
- const insertAttrs = findAdjacentRevision(view.state.doc, from, "insertion", pluginState.author) || makeMarkAttrs(pluginState);
756
- if (from !== to) {
757
- const deletionType = view.state.schema.marks["deletion"];
758
- if (deletionType) markRangeAsDeleted(tr, view.state.doc, from, to, deletionType, pluginState, view.state);
759
- }
760
- const insertAt = tr.mapping.map(to);
761
- const formattingMarks = formattingMarksBesideLockedControl({
762
- state: view.state,
763
- from,
764
- to
765
- });
766
- if (formattingMarks !== void 0) tr.setStoredMarks(formattingMarks);
767
- const typedFrom = tr.doc.resolve(insertAt).parent.inlineContent ? insertAt : insertAt + 1;
768
- const typedTo = typedFrom + text.length;
769
- tr.insertText(text, insertAt, insertAt);
770
- const deletionType = view.state.schema.marks["deletion"];
771
- if (deletionType) tr.removeMark(typedFrom, typedTo, deletionType);
772
- tr.addMark(typedFrom, typedTo, insertionType.create(insertAttrs));
773
- if (replacedFormatting) {
774
- for (const mark of tr.doc.resolve(typedFrom).nodeAfter?.marks ?? []) if (RUN_FORMATTING_MARK_NAMES.has(mark.type.name)) tr.removeMark(typedFrom, typedTo, mark.type);
775
- for (const mark of replacedFormatting) tr.addMark(typedFrom, typedTo, mark);
776
- }
777
- separateSplitStretch(tr, typedFrom, typedTo, insertAttrs.revisionId);
778
- if (typesOverSelection) tr.setSelection(TextSelection.create(tr.doc, typedTo));
779
- keepTypedTextInComments({
780
- state: view.state,
781
- tr,
782
- replaced: {
783
- from,
784
- to
785
- },
786
- typed: {
787
- from: typedFrom,
788
- to: typedTo
789
- }
790
- });
791
- view.dispatch(tr.scrollIntoView());
792
- return true;
793
- }
794
- /**
795
- * Text typed inside another revision leaves that revision in two stretches.
796
- * A saved package writes each stretch as a wrapper of its own with its own
797
- * `w:id`, so the stretch after the typed text gets a fresh id now: the editor
798
- * lists, resolves and saves the same changes a reopened package does.
799
- */
800
- function separateSplitStretch(tr, from, to, typedId) {
801
- const $from = tr.doc.resolve(from);
802
- const $to = tr.doc.resolve(to);
803
- const before = $from.nodeBefore;
804
- if (!before || $to.parent !== $from.parent) return;
805
- const parent = $to.parent;
806
- const start = $to.start();
807
- for (const mark of before.marks) {
808
- if (mark.type.name !== "insertion" && mark.type.name !== "deletion") continue;
809
- const revisionId = mark.attrs["revisionId"];
810
- if (revisionId === typedId || typeof revisionId !== "number") continue;
811
- let end = to;
812
- let offset = to - start;
813
- while (offset < parent.content.size) {
814
- const child = parent.childAfter(offset).node;
815
- if (!child?.marks.some((candidate) => candidate.eq(mark))) break;
816
- offset += child.nodeSize;
817
- end = start + offset;
818
- }
819
- if (end === to) continue;
820
- tr.removeMark(to, end, mark);
821
- tr.addMark(to, end, mark.type.create({
822
- ...mark.attrs,
823
- revisionId: mintRevisionId()
824
- }));
825
- }
826
- }
827
- /**
828
- * Remove `from`..`to` of `tr.doc` as a suggestion: text the current author
829
- * inserted is retracted, anything else is marked deleted. `false` when the
830
- * editor is not suggesting.
831
- */
832
- function suggestRangeDeletion(state, tr, from, to) {
833
- const pluginState = suggestionModeKey.getState(state);
834
- const insertionType = state.schema.marks["insertion"];
835
- const deletionType = state.schema.marks["deletion"];
836
- if (!pluginState?.active || !insertionType || !deletionType) return false;
837
- markRangeAsDeleted(tr, tr.doc, from, to, deletionType, pluginState);
838
- return true;
839
- }
840
- /**
841
- * Track-changes Enter: split the paragraph and stamp `pPrMark = 'ins'` on the
842
- * FIRST half of the split (the upper paragraph), per ECMA-376 §17.13.5. The
843
- * actual splitting reuses `splitBlockClearBorders` so border/style/stored-mark
844
- * behavior stays identical to ordinary editing.
845
- *
846
- * A `pPrMark` the source paragraph already carries belongs to its break, which
847
- * now ends the new paragraph: it moves there, so no revision is lost.
848
- */
849
- function handleSuggestionEnter(view, pluginState) {
850
- const state = view.state;
851
- if (state.selection.$from.parent.type.name !== "paragraph") return false;
852
- const replacement = { tr: null };
853
- let splitState = state;
854
- if (state.selection instanceof TextSelection && !state.selection.empty) {
855
- if (!handleSuggestionDelete(state, (tr) => {
856
- replacement.tr = tr;
857
- const styles = documentStylesKey.get(state);
858
- const plugins = [];
859
- if (styles) {
860
- const spec = { ...styles.spec };
861
- delete spec.appendTransaction;
862
- delete spec.filterTransaction;
863
- plugins.push(new Plugin(spec));
864
- }
865
- splitState = state.reconfigure({ plugins }).apply(tr);
866
- }, "forward")) return false;
867
- }
868
- const { $from } = splitState.selection;
869
- const sourcePos = $from.before();
870
- const sourceAttrs = $from.parent.attrs;
871
- const captured = { tr: null };
872
- if (!splitBlockClearBorders(splitState, (tr) => {
873
- captured.tr = tr;
874
- }, view) || !captured.tr) return false;
875
- const tr = replacement.tr ?? captured.tr;
876
- if (replacement.tr) {
877
- for (const step of captured.tr.steps) tr.step(step);
878
- tr.setSelection(captured.tr.selection.getBookmark().resolve(tr.doc));
879
- tr.setStoredMarks(captured.tr.storedMarks);
880
- }
881
- tr.setMeta(SUGGESTION_META, true);
882
- const sourceParagraph = tr.doc.nodeAt(sourcePos);
883
- const $caret = tr.selection.$from;
884
- const newPos = $caret.parent.type.name === "paragraph" && $caret.before() !== sourcePos ? $caret.before() : null;
885
- const sourceMark = sourceAttrs["pPrMark"];
886
- if (sourceParagraph?.type.name === "paragraph" && (sourceMark == null || newPos !== null)) {
887
- const markInfo = {
888
- kind: "ins",
889
- info: makeParagraphMarkInfo(pluginState)
890
- };
891
- tr.setNodeAttribute(sourcePos, "pPrMark", markInfo);
892
- if (newPos !== null) {
893
- if (sourceMark != null) tr.setNodeAttribute(newPos, "pPrMark", sourceMark);
894
- recordReplacedParagraphProperties({
895
- tr,
896
- position: newPos,
897
- replaced: $from.parent,
898
- revision: markInfo.info
899
- });
900
- }
901
- }
902
- view.dispatch(tr.scrollIntoView());
903
- return true;
904
- }
905
- /** Find the adjacent visible unit without consuming retained deletions or bookmark markers. */
906
- function caretDeleteTarget(state, direction) {
907
- const { $from } = state.selection;
908
- const backward = direction === "backward";
909
- let cursor = $from.pos;
910
- while (cursor >= $from.start() && cursor <= $from.end()) {
911
- const adjacent = backward ? state.doc.resolve(cursor).nodeBefore : state.doc.resolve(cursor).nodeAfter;
912
- if (!adjacent) return { type: "paragraphEdge" };
913
- if (!isInlineAnchor(adjacent) && !adjacent.marks.some((mark) => mark.type === state.schema.marks["deletion"])) {
914
- const size = adjacent.isAtom && !adjacent.isText ? adjacent.nodeSize : 1;
915
- return {
916
- type: "inlineUnit",
917
- from: backward ? cursor - size : cursor,
918
- to: backward ? cursor : cursor + size
919
- };
920
- }
921
- cursor += backward ? -adjacent.nodeSize : adjacent.nodeSize;
922
- }
923
- return { type: "paragraphEdge" };
924
- }
925
- /**
926
- * Detect a caret-at-paragraph-boundary scenario where Backspace/Delete should
927
- * record a tracked paragraph-mark deletion instead of joining paragraphs.
928
- *
929
- * Returns the position of the paragraph whose `pPrMark` should be set, or
930
- * `null` if the caret is mid-paragraph (let the normal text-delete path run).
931
- *
932
- * - Backspace-at-paragraph-start → previous sibling paragraph.
933
- * - Delete-at-paragraph-end → current paragraph.
934
- *
935
- * Returns `null` when there is no adjacent sibling paragraph (the join would
936
- * not produce paragraph-mark merging, e.g. doc start, doc end, or a table).
937
- * Bookmark markers at an edge do not hide the adjacent paragraph break.
938
- */
939
- function paragraphBoundaryTarget(state, direction) {
940
- const { $from, empty } = state.selection;
941
- if (!empty) return null;
942
- if ($from.parent.type.name !== "paragraph") return null;
943
- const paragraphStart = $from.before();
944
- const paragraphEnd = $from.after();
945
- if (caretDeleteTarget(state, direction).type !== "paragraphEdge") return null;
946
- if (direction === "backward") {
947
- if (paragraphStart === 0) return null;
948
- const prev = state.doc.resolve(paragraphStart).nodeBefore;
949
- if (!prev || prev.type.name !== "paragraph") return null;
950
- return paragraphStart - prev.nodeSize;
951
- }
952
- if (paragraphEnd >= state.doc.content.size) return null;
953
- const next = state.doc.resolve(paragraphEnd).nodeAfter;
954
- if (!next || next.type.name !== "paragraph") return null;
955
- return paragraphStart;
956
- }
957
- /**
958
- * Mark a paragraph break as a tracked deletion. `target` is the position of
959
- * the paragraph whose closing mark is being deleted (per OOXML, that's the
960
- * previous paragraph for Backspace-at-start and the current paragraph for
961
- * Delete-at-end). If the existing mark is the current author's insertion,
962
- * retract it by joining the paragraphs back together.
963
- */
964
- function applyPPrDel(view, targetParagraphPos, pluginState) {
965
- const targetNode = view.state.doc.nodeAt(targetParagraphPos);
966
- if (!targetNode || targetNode.type.name !== "paragraph") return false;
967
- const existingMark = targetNode.attrs["pPrMark"];
968
- if (isCurrentAuthorParagraphInsertion(existingMark, pluginState.author)) {
969
- const tr = view.state.tr;
970
- tr.setMeta(SUGGESTION_META, true);
971
- const joinPos = targetParagraphPos + targetNode.nodeSize;
972
- const joined = view.state.doc.nodeAt(joinPos);
973
- try {
974
- tr.join(joinPos);
975
- tr.setNodeAttribute(targetParagraphPos, "pPrMark", joined?.type === targetNode.type ? expectParagraphAttrs(joined).pPrMark : null);
976
- if (joined?.type === targetNode.type) recordReplacedParagraphProperties({
977
- tr,
978
- position: targetParagraphPos,
979
- replaced: joined,
980
- revision: existingMark.info
981
- });
982
- const styleResolver = getDocumentStyleResolver(view.state);
983
- if (styleResolver && joined?.type === targetNode.type && joined.content.size > 0) rebaseParagraphRuns({
984
- previousContext: paragraphRunStyleContext(joined, styleResolver),
985
- paragraphPosition: targetParagraphPos,
986
- range: {
987
- from: targetNode.content.size,
988
- to: targetNode.content.size + joined.content.size
989
- },
990
- styleResolver,
991
- tr
992
- });
993
- tr.setMeta(JOINED_RUNS_RESTYLED_META, true);
994
- view.dispatch(tr.scrollIntoView());
995
- } catch {
996
- return true;
997
- }
998
- return true;
999
- }
1000
- if (existingMark != null) return true;
1001
- const tr = view.state.tr;
1002
- tr.setMeta(SUGGESTION_META, true);
1003
- const markInfo = {
1004
- kind: "del",
1005
- info: makeParagraphMarkInfo(pluginState)
1006
- };
1007
- tr.setNodeAttribute(targetParagraphPos, "pPrMark", markInfo);
1008
- carryIntoParagraphLeft(view.state, tr, targetNode, paragraphLeftAfter({
1009
- doc: tr.doc,
1010
- paragraphPos: targetParagraphPos
1011
- }) ?? targetParagraphPos + targetNode.nodeSize, markInfo.info);
1012
- view.dispatch(tr.scrollIntoView());
1013
- return true;
1014
- }
1015
- function isCurrentAuthorParagraphInsertion(value, author) {
1016
- if (typeof value !== "object" || value === null) return false;
1017
- const mark = value;
1018
- if (mark.kind !== "ins" || typeof mark.info !== "object" || mark.info === null) return false;
1019
- return mark.info.author === author;
1020
- }
1021
- /** An added break another author made that no deletion has taken yet. */
1022
- function isOtherAuthorParagraphInsertion(value, author) {
1023
- if (typeof value !== "object" || value === null) return false;
1024
- const mark = value;
1025
- return (mark.kind === "ins" || mark.kind === "moveTo") && mark.deletion === void 0 && typeof mark.info === "object" && mark.info.author !== author;
1026
- }
1027
- /**
1028
- * Handle delete (forward or backward) in suggestion mode.
1029
- */
1030
- function handleSuggestionDelete(state, dispatch, direction, { cut = false } = {}) {
1031
- const pluginState = suggestionModeKey.getState(state);
1032
- if (!pluginState?.active) return false;
1033
- const { $from, $to, empty } = state.selection;
1034
- const insertionType = state.schema.marks["insertion"];
1035
- const deletionType = state.schema.marks["deletion"];
1036
- if (!insertionType || !deletionType) return false;
1037
- if (!dispatch) return true;
1038
- const tr = state.tr;
1039
- tr.setMeta(SUGGESTION_META, true);
1040
- if (!empty) {
1041
- const ranges = state.selection.ranges.map(({ $from: rangeFrom, $to: rangeTo }) => expandNoteReferenceDeletionRange(state.doc, rangeFrom.pos, rangeTo.pos) ?? {
1042
- from: rangeFrom.pos,
1043
- to: rangeTo.pos
1044
- }).sort((a, b) => b.from - a.from);
1045
- for (const { from, to } of ranges) markRangeAsDeleted(tr, state.doc, from, to, deletionType, pluginState, state);
1046
- if (state.selection instanceof CellSelection && !cut) tr.setSelection(state.selection.map(tr.doc, tr.mapping));
1047
- else if (state.selection instanceof CellSelection) {
1048
- const caret = Selection.findFrom(tr.doc.resolve(tr.mapping.map(state.selection.to)), -1);
1049
- if (caret) tr.setSelection(caret);
1050
- } else {
1051
- const cursorPos = tr.mapping.map($to.pos);
1052
- tr.setSelection(TextSelection.near(tr.doc.resolve(cursorPos)));
1053
- }
1054
- dispatch(tr.scrollIntoView());
1055
- return true;
1056
- }
1057
- const isBackward = direction === "backward";
1058
- const target = caretDeleteTarget(state, direction);
1059
- if (target.type === "paragraphEdge") {
1060
- const edge = isBackward ? $from.start() : $from.end();
1061
- if ($from.pos === edge) return false;
1062
- const virtual = EditorState.create({
1063
- doc: state.doc,
1064
- selection: TextSelection.create(state.doc, edge)
1065
- });
1066
- if ((isBackward ? joinBackward : joinForward)(virtual, dispatch)) return true;
1067
- return (isBackward ? selectNodeBackward : selectNodeForward)(virtual, dispatch);
1068
- }
1069
- const deletePos = target.from;
1070
- const deleteEnd = target.to;
1071
- const noteRange = expandNoteReferenceDeletionRange(state.doc, deletePos, deleteEnd);
1072
- const rangeFrom = noteRange?.from ?? deletePos;
1073
- const rangeTo = noteRange?.to ?? deleteEnd;
1074
- const nodeAfter = state.doc.resolve(rangeFrom).nodeAfter;
1075
- if (!nodeAfter || !canCarryTrackedRunMark(nodeAfter)) return false;
1076
- const mapFrom = tr.mapping.maps.length;
1077
- if (noteRange) markRangeAsDeleted(tr, state.doc, noteRange.from, noteRange.to, deletionType, pluginState);
1078
- else if (!nodeAfter.marks.some((m) => m.type === deletionType)) {
1079
- const delAttrs = findAdjacentRevisionForRange(state.doc, rangeFrom, rangeTo, "deletion", pluginState.author) || makeMarkAttrs(pluginState);
1080
- addTrackedDeletionMark({
1081
- insertionPolicy: "retract-own",
1082
- tr,
1083
- from: rangeFrom,
1084
- to: rangeTo,
1085
- mark: deletionType.create(delAttrs)
1086
- });
1087
- }
1088
- const newPos = tr.mapping.slice(mapFrom).map(isBackward ? rangeFrom : rangeTo);
1089
- tr.setSelection(TextSelection.near(tr.doc.resolve(newPos)));
1090
- dispatch(tr.scrollIntoView());
1091
- return true;
1092
- }
1093
- /** Apply the editor's selected-content deletion path for a host cut action. */
1094
- const deleteSelectionAsSuggestion = (state, dispatch) => state.selection.empty ? false : handleSuggestionDelete(state, dispatch, "forward", { cut: true });
1095
- /**
1096
- * PM reads the removal of cancelled text back from the DOM, which can take the
1097
- * text around it along and drop its revision marks. The same text was there when
1098
- * the composition started: put back what it was.
1099
- */
1100
- function restoreAfterCancelledComposition(view, startDoc) {
1101
- const { doc } = view.state;
1102
- const start = startDoc.content.findDiffStart(doc.content);
1103
- const end = startDoc.content.findDiffEnd(doc.content);
1104
- if (start === null || end === null) return;
1105
- if (end.a !== end.b || end.a <= start || startDoc.textBetween(start, end.a, "\n", "\n") !== doc.textBetween(start, end.a, "\n", "\n")) return;
1106
- const tr = view.state.tr.replace(start, end.a, startDoc.slice(start, end.a));
1107
- tr.setMeta(SUGGESTION_META, true);
1108
- tr.setMeta("addToHistory", false);
1109
- view.dispatch(tr);
1110
- }
1111
- function markComposedAsInsertion({ view, from, startDoc, foreignSize, foreignEdit, pluginState, replaced, compositionId }) {
1112
- const insertionType = view.state.schema.marks["insertion"];
1113
- const deletionType = view.state.schema.marks["deletion"];
1114
- if (!insertionType || !deletionType) return;
1115
- const { doc } = view.state;
1116
- const composedSize = doc.content.size - startDoc.content.size - foreignSize + (replaced?.size ?? 0);
1117
- const to = Math.min(from + composedSize, view.state.selection.to);
1118
- if (doc.eq(startDoc)) return;
1119
- if (composedSize === 0 && !replaced) {
1120
- if (!foreignEdit) restoreAfterCancelledComposition(view, startDoc);
1121
- return;
1122
- }
1123
- if (to <= from && !replaced) return;
1124
- const tr = view.state.tr;
1125
- tr.setMeta(SUGGESTION_META, true);
1126
- if (compositionId !== null) tr.setMeta("composition", compositionId);
1127
- if (replaced) {
1128
- tr.replaceRange(from, from, replaced);
1129
- markRangeAsDeleted(tr, tr.doc, from, tr.mapping.map(from, 1), deletionType, pluginState);
1130
- const restoredEnd = tr.doc.resolve(tr.mapping.map(from, 1));
1131
- const restoredStart = tr.doc.resolve(from);
1132
- if (restoredStart.parent.type.name === "paragraph" && restoredEnd.parent.type.name === "paragraph" && restoredStart.parent !== restoredEnd.parent) {
1133
- const mark = expectParagraphAttrs(restoredStart.parent).pPrMark;
1134
- if (mark?.kind === "del") carryIntoParagraphLeft(view.state, tr, view.state.doc.resolve(from).parent, restoredEnd.before(), mark.info);
1135
- }
1136
- }
1137
- const insertionFrom = tr.mapping.map(from, 1);
1138
- const insertionTo = tr.mapping.map(to, 1);
1139
- if (insertionTo <= insertionFrom) {
1140
- if (tr.steps.length > 0) view.dispatch(tr);
1141
- return;
1142
- }
1143
- const markAttrs = findAdjacentRevisionForRange(tr.doc, insertionFrom, insertionTo, "insertion", pluginState.author) || makeMarkAttrs(pluginState);
1144
- markRangeAsInserted(tr, tr.doc, insertionFrom, insertionTo, insertionType, deletionType, markAttrs);
1145
- if (tr.steps.length === 0) return;
1146
- const caret = tr.mapping.map(to, 1);
1147
- tr.setSelection(TextSelection.create(tr.doc, caret));
1148
- view.dispatch(tr);
1149
- }
1150
- /**
1151
- * Paragraphs inserted into one (a paste at the caret) split it: its break ends
1152
- * the last part, which reads as the last inserted paragraph. Rejecting the
1153
- * inserted breaks leaves that part, so it records what the paragraph read as.
1154
- */
1155
- function recordSplitParagraph(tr, before, step, insertedFrom, insertedTo, attrs) {
1156
- if (!(step instanceof ReplaceStep) || !before) return;
1157
- const $at = before.resolve(step.from);
1158
- if ($at.parent.type.name !== "paragraph" || step.to > $at.after() || before.textBetween(step.from, step.to) !== "") return;
1159
- const split = $at.parent;
1160
- const $first = tr.doc.resolve(insertedFrom);
1161
- const $last = tr.doc.resolve(insertedTo);
1162
- let lastPos = null;
1163
- if ($last.parent.type.name === "paragraph") lastPos = $last.before();
1164
- else if ($last.nodeBefore?.type.name === "paragraph") lastPos = insertedTo - $last.nodeBefore.nodeSize;
1165
- if ($first.parent.type.name !== "paragraph" || lastPos === null || lastPos === $first.before()) return;
1166
- const revision = {
1167
- id: attrs.revisionId,
1168
- author: attrs.author,
1169
- date: attrs.date
1170
- };
1171
- const { pPrMark } = expectParagraphAttrs(split);
1172
- if (pPrMark) {
1173
- tr.setNodeAttribute(lastPos, "pPrMark", pPrMark);
1174
- tr.setNodeAttribute($first.before(), "pPrMark", {
1175
- kind: "ins",
1176
- info: revision
1177
- });
1178
- }
1179
- recordReplacedParagraphProperties({
1180
- tr,
1181
- position: lastPos,
1182
- replaced: split,
1183
- revision
1184
- });
1185
- }
1186
- /**
1187
- * The inline content a step removed from within one textblock, and where it
1188
- * started: the node a node selection held (an image, a field, a note
1189
- * reference) or a range of runs. Null for a step that removed nothing, or removed paragraph or table
1190
- * structure the catch-all cannot put back.
1191
- */
1192
- function replacedInline(before, step) {
1193
- if (!(step instanceof ReplaceStep) || !before || step.from === step.to) return null;
1194
- const $from = before.resolve(step.from);
1195
- if (!$from.parent.inlineContent || !$from.sameParent(before.resolve(step.to))) return null;
1196
- return {
1197
- from: step.from,
1198
- content: $from.parent.content.cut($from.parentOffset, step.to - $from.start())
1199
- };
1200
- }
1201
- /**
1202
- * A transaction the plugin did not build (a command, a default paste, a
1203
- * keymap) replaced inline content directly. Put it back in front of what
1204
- * replaced it as a tracked deletion, as typing over a selection does, so
1205
- * rejecting restores it and accepting removes it. The author's own
1206
- * insertions are retracted instead.
1207
- */
1208
- function restoreReplacedInline({ tr, replaced, deletionType, pluginState }) {
1209
- for (const { at, content } of replaced) {
1210
- const pos = tr.mapping.map(at, -1);
1211
- const $pos = tr.doc.resolve(pos);
1212
- const index = $pos.index();
1213
- if (!$pos.parent.canReplace(index, index, content)) continue;
1214
- tr.insert(pos, content);
1215
- markRangeAsDeleted(tr, tr.doc, pos, pos + content.size, deletionType, pluginState);
1216
- }
1217
- }
1218
- const readableContent = (content) => content.textBetween(0, content.size, "", "");
1219
- /**
1220
- * The inline content a step puts in place of a selection, or null for block
1221
- * content. Between containers, the step also carries the text after the
1222
- * selection over into the first one, and fills out what it cut with empty blocks.
1223
- */
1224
- const insertedInline = (step, $to, to) => {
1225
- const { content } = step.slice;
1226
- let inline = content;
1227
- while (inline.firstChild && !inline.firstChild.isInline) inline = inline.firstChild.content;
1228
- if (readableContent(inline) !== readableContent(content)) return null;
1229
- if (step.to === to || step instanceof ReplaceAroundStep) return inline;
1230
- const tail = $to.parent.content.cut($to.parentOffset);
1231
- const kept = inline.size - tail.size;
1232
- return kept >= 0 && inline.cut(kept).eq(tail) ? inline.cut(0, kept) : null;
1233
- };
1234
- /**
1235
- * A transaction the plugin did not build (a key binding, a command) replacing a
1236
- * selection that spans textblocks. Null for anything else: table structure and
1237
- * block content have their own paths, and a replacement inside one textblock
1238
- * is `replacedInline`'s.
1239
- */
1240
- function spanningReplacement(oldState, userTr) {
1241
- const [step] = userTr.steps;
1242
- const { doc, selection } = oldState;
1243
- if (userTr.steps.length !== 1 || !(step instanceof ReplaceStep || step instanceof ReplaceAroundStep) || userTr.before !== doc || selection.empty) return null;
1244
- const selectsAll = selection instanceof AllSelection;
1245
- const from = selectsAll ? Selection.atStart(doc).from : selection.from;
1246
- const to = selectsAll ? Selection.atEnd(doc).to : selection.to;
1247
- const $from = doc.resolve(from);
1248
- const $to = doc.resolve(to);
1249
- if (!$from.parent.inlineContent || !$to.parent.inlineContent || $from.sameParent($to) || step.from > from || step.to < to || step instanceof ReplaceAroundStep && step.gapFrom < to) return null;
1250
- const inserted = insertedInline(step, $to, to);
1251
- return inserted && {
1252
- step,
1253
- from,
1254
- to,
1255
- inserted
1256
- };
1257
- }
1258
- /**
1259
- * Put the document back and make the same replacement as typing over the
1260
- * selection does: the selected text is struck and what replaced it follows, so
1261
- * rejecting restores the source and accepting matches the direct edit.
1262
- */
1263
- function trackSpanningReplacement({ tr, oldState, replacement: { step, from, to, inserted }, insertionType, deletionType, pluginState }) {
1264
- tr.step(step.invert(oldState.doc));
1265
- const restored = tr.mapping.maps.length;
1266
- markRangeAsDeleted(tr, tr.doc, from, to, deletionType, pluginState, oldState);
1267
- const at = tr.mapping.slice(restored).map(to);
1268
- tr.insert(at, inserted);
1269
- const end = at + inserted.size;
1270
- tr.removeMark(at, end, deletionType);
1271
- markRangeAsInserted(tr, tr.doc, at, end, insertionType, deletionType, makeMarkAttrs(pluginState));
1272
- tr.setSelection(TextSelection.near(tr.doc.resolve(end), -1));
1273
- }
1274
- /**
1275
- * Create the suggestion mode plugin.
1276
- * When active, text edits become tracked changes.
1277
- */
1278
- function createSuggestionModePlugin(initialActive = false, author = "User") {
1279
- let composing = false;
1280
- let compositionFrom = null;
1281
- let compositionStartDoc = null;
1282
- let compositionForeignSize = 0;
1283
- let compositionForeignEdit = false;
1284
- let compositionReplaced = null;
1285
- let compositionId = null;
1286
- return new Plugin({
1287
- key: suggestionModeKey.createKey(),
1288
- state: {
1289
- init(_config, instance) {
1290
- seedRevisionIdsFromDoc(instance.doc);
1291
- return {
1292
- active: initialActive,
1293
- author
1294
- };
1295
- },
1296
- apply(tr, state) {
1297
- const nativeCompositionId = tr.getMeta("composition");
1298
- if (composing && tr.docChanged && typeof nativeCompositionId === "number") compositionId = nativeCompositionId;
1299
- if (composing && tr.docChanged && tr.getMeta("y-sync$") !== void 0) {
1300
- compositionForeignEdit = true;
1301
- compositionForeignSize += tr.doc.content.size - tr.before.content.size;
1302
- if (compositionFrom !== null) compositionFrom = tr.mapping.map(compositionFrom);
1303
- }
1304
- const meta = tr.getMeta(suggestionModeKey);
1305
- if (meta) return {
1306
- ...state,
1307
- ...meta
1308
- };
1309
- return state;
1310
- }
1311
- },
1312
- props: {
1313
- handleDOMEvents: {
1314
- cut(view, event) {
1315
- if (!suggestionModeKey.getState(view.state)?.active || view.state.selection.empty) return false;
1316
- const data = event.clipboardData;
1317
- if (!data) return false;
1318
- const { dom, text } = view.serializeForClipboard(view.state.selection.content());
1319
- data.clearData();
1320
- data.setData("text/html", dom.innerHTML);
1321
- data.setData("text/plain", text);
1322
- event.preventDefault();
1323
- return handleSuggestionDelete(view.state, view.dispatch, "forward", { cut: true });
1324
- },
1325
- compositionstart(view) {
1326
- if (!suggestionModeKey.getState(view.state)?.active) return false;
1327
- if (composing) return false;
1328
- composing = true;
1329
- compositionId = null;
1330
- const { selection } = view.state;
1331
- const { from, to } = selection instanceof AllSelection ? {
1332
- from: Selection.atStart(view.state.doc).from,
1333
- to: Selection.atEnd(view.state.doc).to
1334
- } : selection;
1335
- compositionFrom = from;
1336
- compositionStartDoc = view.state.doc;
1337
- compositionForeignSize = 0;
1338
- compositionForeignEdit = false;
1339
- compositionReplaced = from === to ? null : view.state.doc.slice(from, to);
1340
- return false;
1341
- },
1342
- compositionend(view) {
1343
- const pluginState = suggestionModeKey.getState(view.state);
1344
- const from = compositionFrom;
1345
- const startDoc = compositionStartDoc;
1346
- const replaced = compositionReplaced;
1347
- compositionFrom = null;
1348
- compositionStartDoc = null;
1349
- compositionReplaced = null;
1350
- if (!pluginState?.active || from == null || !startDoc) {
1351
- composing = false;
1352
- compositionId = null;
1353
- return false;
1354
- }
1355
- afterNativeCompositionFlush(() => {
1356
- try {
1357
- const current = suggestionModeKey.getState(view.state);
1358
- const nativeCompositionId = compositionId;
1359
- if (current?.active) markComposedAsInsertion({
1360
- view,
1361
- from,
1362
- startDoc,
1363
- foreignSize: compositionForeignSize,
1364
- foreignEdit: compositionForeignEdit,
1365
- pluginState: current,
1366
- replaced,
1367
- compositionId: nativeCompositionId
1368
- });
1369
- } finally {
1370
- composing = false;
1371
- compositionId = null;
1372
- }
1373
- });
1374
- return false;
1375
- },
1376
- beforeinput(view, event) {
1377
- if (!suggestionModeKey.getState(view.state)?.active || composing) return false;
1378
- return handleEditorBeforeInput(view, event);
1379
- }
1380
- },
1381
- handleKeyDown(view, event) {
1382
- const pluginState = suggestionModeKey.getState(view.state);
1383
- if (!pluginState?.active) return false;
1384
- if (composing) return false;
1385
- if (selectLockedInlineControl(view, event)) return true;
1386
- if (event.key === "Enter" && !event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey) {
1387
- const { $from, empty } = view.state.selection;
1388
- if (empty && $from.parent.type.name === "paragraph" && expectParagraphAttrs($from.parent).numPr?.kind === "reference") return false;
1389
- return handleSuggestionEnter(view, pluginState);
1390
- }
1391
- if (event.key === "Backspace" && undoInputRule(view.state, view.dispatch)) return true;
1392
- if (event.key === "Backspace" || event.key === "Delete") {
1393
- const { $from, empty } = view.state.selection;
1394
- const atListItemStart = event.key === "Backspace" && empty && $from.parentOffset === 0 && $from.parent.type.name === "paragraph" && expectParagraphAttrs($from.parent).numPr?.kind === "reference";
1395
- if (atListItemStart && !event.ctrlKey && !event.metaKey && !event.shiftKey) return false;
1396
- if (event.key === "Backspace" && !atListItemStart && clearIndentOnBackspace(view.state, (tr) => {
1397
- const revision = makeMarkAttrs(pluginState);
1398
- recordReplacedParagraphProperties({
1399
- tr,
1400
- position: $from.before(),
1401
- replaced: $from.parent,
1402
- revision: {
1403
- id: revision.revisionId,
1404
- author: revision.author,
1405
- date: revision.date
1406
- }
1407
- });
1408
- view.dispatch(tr.setMeta("suggestionModeApplied", true));
1409
- })) return true;
1410
- const boundaryTarget = paragraphBoundaryTarget(view.state, event.key === "Backspace" ? "backward" : "forward");
1411
- if (boundaryTarget !== null) return applyPPrDel(view, boundaryTarget, pluginState);
1412
- const direction = event.key === "Backspace" ? "backward" : "forward";
1413
- return handleSuggestionDelete(view.state, view.dispatch, direction);
1414
- }
1415
- return false;
1416
- },
1417
- handleTextInput(view, from, to, text) {
1418
- const pluginState = suggestionModeKey.getState(view.state);
1419
- if (!pluginState?.active) return false;
1420
- if (composing || view.composing) return false;
1421
- return applySuggestionInsert(view, from, to, text, pluginState);
1422
- },
1423
- handlePaste(view, _event, slice) {
1424
- const pluginState = suggestionModeKey.getState(view.state);
1425
- if (!pluginState?.active) return false;
1426
- return handleSuggestionTableCellPaste(view, slice, pluginState) || handleSuggestionPaste(view, slice, pluginState);
1427
- }
1428
- },
1429
- appendTransaction(transactions, oldState, newState) {
1430
- const pluginState = suggestionModeKey.getState(newState);
1431
- if (!pluginState?.active) return null;
1432
- if (composing) return null;
1433
- const userTr = transactions.find((tr) => tr.docChanged && !tr.getMeta("suggestionModeApplied") && !tr.getMeta("suggestionModeBypass") && !isHistoryTransaction(tr));
1434
- if (!userTr) return null;
1435
- const insertionType = newState.schema.marks["insertion"];
1436
- if (!insertionType) return null;
1437
- const markAttrs = makeMarkAttrs(pluginState);
1438
- const tr = newState.tr;
1439
- tr.setMeta(SUGGESTION_META, true);
1440
- const deletionType = newState.schema.marks["deletion"];
1441
- const laterMaps = transactions.slice(transactions.indexOf(userTr) + 1).flatMap((transaction) => transaction.mapping.maps);
1442
- const restoresReplaced = userTr.getMeta("appendedTransaction") === void 0;
1443
- const spanning = deletionType && restoresReplaced && newState.doc === userTr.doc ? spanningReplacement(oldState, userTr) : null;
1444
- if (deletionType && spanning) {
1445
- trackSpanningReplacement({
1446
- tr,
1447
- oldState,
1448
- replacement: spanning,
1449
- insertionType,
1450
- deletionType,
1451
- pluginState
1452
- });
1453
- return tr;
1454
- }
1455
- const replaced = [];
1456
- for (const [stepIndex, step] of userTr.steps.entries()) {
1457
- const stepMap = step.getMap();
1458
- const following = new Mapping([...userTr.mapping.maps.slice(stepIndex + 1), ...laterMaps]);
1459
- const removed = restoresReplaced ? replacedInline(userTr.docs[stepIndex], step) : null;
1460
- if (removed) replaced.push({
1461
- at: following.map(removed.from, -1),
1462
- content: removed.content
1463
- });
1464
- stepMap.forEach((_oldFrom, _oldTo, stepFrom, stepTo) => {
1465
- const newFrom = following.map(stepFrom, -1);
1466
- const newTo = following.map(stepTo, 1);
1467
- if (newTo > newFrom) {
1468
- if (userTr.getMeta("paste")) enclosePastedRunRevisions({
1469
- tr,
1470
- from: newFrom,
1471
- to: newTo,
1472
- revision: markAttrs
1473
- });
1474
- if (deletionType) markRangeAsInserted(tr, newState.doc, newFrom, newTo, insertionType, deletionType, markAttrs);
1475
- recordSplitParagraph(tr, userTr.docs[stepIndex], step, newFrom, newTo, markAttrs);
1476
- }
1477
- });
1478
- }
1479
- if (deletionType) restoreReplacedInline({
1480
- tr,
1481
- replaced,
1482
- deletionType,
1483
- pluginState
1484
- });
1485
- return tr.steps.length > 0 ? tr : null;
1486
- }
1487
- });
1488
- }
1489
- /**
1490
- * Toggle suggestion mode on/off.
1491
- */
1492
- function toggleSuggestionMode(state, dispatch) {
1493
- const current = suggestionModeKey.getState(state);
1494
- if (!current) return false;
1495
- if (dispatch) dispatch(state.tr.setMeta(suggestionModeKey, { active: !current.active }));
1496
- return true;
1497
- }
1498
- /**
1499
- * Set suggestion mode active state and author.
1500
- */
1501
- function setSuggestionMode(active, state, dispatch, author) {
1502
- if (dispatch) {
1503
- const meta = { active };
1504
- if (author !== void 0) meta.author = author;
1505
- dispatch(state.tr.setMeta(suggestionModeKey, meta));
1506
- }
1507
- return true;
1508
- }
1509
- /**
1510
- * Check if suggestion mode is currently active.
1511
- */
1512
- function isSuggestionModeActive(state) {
1513
- return suggestionModeKey.getState(state)?.active ?? false;
1514
- }
1515
- export { SUGGESTED_TEXT_INPUT_META, SUGGESTION_BYPASS_META, SUGGESTION_META, createSuggestionModePlugin, deleteSelectionAsSuggestion, handleSuggestionEnter, handleSuggestionPaste, handleSuggestionTableCellPaste, isSuggestionModeActive, makeRevisionInfo, paragraphBoundaryTarget, setSuggestionMode, suggestRangeDeletion, suggestionModeKey, toggleSuggestionMode };